]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/mainframe.cpp
8accc5ef36134f6f756b6e40d20b53dc50cdab4f
[xonotic/netradiant.git] / radiant / mainframe.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // Main Window for Q3Radiant
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "mainframe.h"
29 #include "globaldefs.h"
30
31 #include <gtk/gtk.h>
32
33 #include "ifilesystem.h"
34 #include "iundo.h"
35 #include "editable.h"
36 #include "ientity.h"
37 #include "ishaders.h"
38 #include "igl.h"
39 #include "moduleobserver.h"
40
41 #include <ctime>
42
43 #include <gdk/gdkkeysyms.h>
44
45
46 #include "cmdlib.h"
47 #include "stream/stringstream.h"
48 #include "signal/isignal.h"
49 #include "os/path.h"
50 #include "os/file.h"
51 #include "eclasslib.h"
52 #include "moduleobservers.h"
53
54 #include "gtkutil/clipboard.h"
55 #include "gtkutil/frame.h"
56 #include "gtkutil/glwidget.h"
57 #include "gtkutil/image.h"
58 #include "gtkutil/menu.h"
59 #include "gtkutil/paned.h"
60
61 #include "autosave.h"
62 #include "build.h"
63 #include "brushmanip.h"
64 #include "brushmodule.h"
65 #include "camwindow.h"
66 #include "csg.h"
67 #include "commands.h"
68 #include "console.h"
69 #include "entity.h"
70 #include "entityinspector.h"
71 #include "entitylist.h"
72 #include "filters.h"
73 #include "findtexturedialog.h"
74 #include "grid.h"
75 #include "groupdialog.h"
76 #include "gtkdlgs.h"
77 #include "gtkmisc.h"
78 #include "help.h"
79 #include "map.h"
80 #include "mru.h"
81 #include "multimon.h"
82 #include "patchdialog.h"
83 #include "patchmanip.h"
84 #include "plugin.h"
85 #include "pluginmanager.h"
86 #include "pluginmenu.h"
87 #include "plugintoolbar.h"
88 #include "preferences.h"
89 #include "qe3.h"
90 #include "qgl.h"
91 #include "select.h"
92 #include "server.h"
93 #include "surfacedialog.h"
94 #include "textures.h"
95 #include "texwindow.h"
96 #include "url.h"
97 #include "xywindow.h"
98 #include "windowobservers.h"
99 #include "renderstate.h"
100 #include "feedback.h"
101 #include "referencecache.h"
102 #include "texwindow.h"
103
104 #if GDEF_OS_WINDOWS
105 #include <process.h>
106 #else
107 #include <spawn.h>
108 #endif
109
110 #ifdef WORKAROUND_WINDOWS_GTK2_GLWIDGET
111 /* workaround for gtk 2.24 issue: not displayed glwidget after toggle */
112 #define WORKAROUND_GOBJECT_SET_GLWIDGET(window, widget) g_object_set_data( G_OBJECT( window ), "glwidget", G_OBJECT( widget ) )
113 #else
114 #define WORKAROUND_GOBJECT_SET_GLWIDGET(window, widget)
115 #endif
116
117 struct layout_globals_t
118 {
119         WindowPosition m_position;
120
121
122         int nXYHeight;
123         int nXYWidth;
124         int nCamWidth;
125         int nCamHeight;
126         int nState;
127
128         layout_globals_t() :
129                 m_position( -1, -1, 640, 480 ),
130
131                 nXYHeight( 300 ),
132                 nXYWidth( 300 ),
133                 nCamWidth( 200 ),
134                 nCamHeight( 200 ),
135                 nState( GDK_WINDOW_STATE_MAXIMIZED ){
136         }
137 };
138
139 layout_globals_t g_layout_globals;
140 glwindow_globals_t g_glwindow_globals;
141
142
143 // VFS
144
145 bool g_vfsInitialized = false;
146
147 void VFS_Init(){
148         if ( g_vfsInitialized ) return;
149         QE_InitVFS();
150         GlobalFileSystem().initialise();
151         g_vfsInitialized = true;
152 }
153
154 void VFS_Shutdown(){
155         if ( !g_vfsInitialized ) return;
156         GlobalFileSystem().shutdown();
157         g_vfsInitialized = false;
158 }
159
160 void VFS_Refresh(){
161         if ( !g_vfsInitialized ) return;
162         // Always set camwindow visible when reloading VFS
163         // especially when loading maps, because GL states loaded
164         // by the camwindow are also used by the xywindow.
165         // Loading map at startup (not deferred) may also requires this
166         // to make sure GL states are ready at map loading time
167         // since camwindow is now the place to initialize GL stuff.
168         GlobalCamera_SetVisible();
169         GlobalFileSystem().clear();
170         QE_InitVFS();
171         GlobalFileSystem().refresh();
172         g_vfsInitialized = true;
173         // also refresh models
174         RefreshReferences();
175         // also refresh texture browser
176         TextureBrowser_RefreshShaders();
177 }
178
179 void VFS_Restart(){
180         VFS_Shutdown();
181         VFS_Init();
182 }
183
184 class VFSModuleObserver : public ModuleObserver
185 {
186 public:
187 void realise(){
188         VFS_Init();
189 }
190
191 void unrealise(){
192         VFS_Shutdown();
193 }
194 };
195
196 VFSModuleObserver g_VFSModuleObserver;
197
198 void VFS_Construct(){
199         Radiant_attachHomePathsObserver( g_VFSModuleObserver );
200 }
201
202 void VFS_Destroy(){
203         Radiant_detachHomePathsObserver( g_VFSModuleObserver );
204 }
205
206 // Home Paths
207
208 #if GDEF_OS_WINDOWS
209 #include <shlobj.h>
210 #include <objbase.h>
211 const GUID qFOLDERID_SavedGames = {0x4C5C32FF, 0xBB9D, 0x43b0, {0xB5, 0xB4, 0x2D, 0x72, 0xE5, 0x4E, 0xAA, 0xA4}};
212 #define qREFKNOWNFOLDERID GUID
213 #define qKF_FLAG_CREATE 0x8000
214 #define qKF_FLAG_NO_ALIAS 0x1000
215 typedef HRESULT ( WINAPI qSHGetKnownFolderPath_t )( qREFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath );
216 static qSHGetKnownFolderPath_t *qSHGetKnownFolderPath;
217 #endif
218
219 void HomePaths_Realise(){
220         do
221         {
222                 const char* prefix = g_pGameDescription->getKeyValue( "prefix" );
223                 if ( !string_empty( prefix ) ) {
224                         StringOutputStream path( 256 );
225
226 #if GDEF_OS_MACOS
227                         path.clear();
228                         path << DirectoryCleaned( g_get_home_dir() ) << "Library/Application Support" << ( prefix + 1 ) << "/";
229                         if ( file_is_directory( path.c_str() ) ) {
230                                 g_qeglobals.m_userEnginePath = path.c_str();
231                                 break;
232                         }
233                         path.clear();
234                         path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
235 #elif GDEF_OS_WINDOWS
236                         TCHAR mydocsdir[MAX_PATH + 1];
237                         wchar_t *mydocsdirw;
238                         HMODULE shfolder = LoadLibrary( "shfolder.dll" );
239                         if ( shfolder ) {
240                                 qSHGetKnownFolderPath = (qSHGetKnownFolderPath_t *) GetProcAddress( shfolder, "SHGetKnownFolderPath" );
241                         }
242                         else{
243                                 qSHGetKnownFolderPath = NULL;
244                         }
245                         CoInitializeEx( NULL, COINIT_APARTMENTTHREADED );
246                         if ( qSHGetKnownFolderPath && qSHGetKnownFolderPath( qFOLDERID_SavedGames, qKF_FLAG_CREATE | qKF_FLAG_NO_ALIAS, NULL, &mydocsdirw ) == S_OK ) {
247                                 memset( mydocsdir, 0, sizeof( mydocsdir ) );
248                                 wcstombs( mydocsdir, mydocsdirw, sizeof( mydocsdir ) - 1 );
249                                 CoTaskMemFree( mydocsdirw );
250                                 path.clear();
251                                 path << DirectoryCleaned( mydocsdir ) << ( prefix + 1 ) << "/";
252                                 if ( file_is_directory( path.c_str() ) ) {
253                                         g_qeglobals.m_userEnginePath = path.c_str();
254                                         CoUninitialize();
255                                         FreeLibrary( shfolder );
256                                         break;
257                                 }
258                         }
259                         CoUninitialize();
260                         if ( shfolder ) {
261                                 FreeLibrary( shfolder );
262                         }
263                         if ( SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, 0, mydocsdir ) ) {
264                                 path.clear();
265                                 path << DirectoryCleaned( mydocsdir ) << "My Games/" << ( prefix + 1 ) << "/";
266                                 // win32: only add it if it already exists
267                                 if ( file_is_directory( path.c_str() ) ) {
268                                         g_qeglobals.m_userEnginePath = path.c_str();
269                                         break;
270                                 }
271                         }
272 #elif GDEF_OS_XDG
273                         path.clear();
274                         path << DirectoryCleaned( g_get_user_data_dir() ) << ( prefix + 1 ) << "/";
275                         if ( file_exists( path.c_str() ) && file_is_directory( path.c_str() ) ) {
276                                 g_qeglobals.m_userEnginePath = path.c_str();
277                                 break;
278                         }
279                         else {
280                                 path.clear();
281                                 path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
282                                 g_qeglobals.m_userEnginePath = path.c_str();
283                                 break;
284                         }
285 #endif
286                 }
287
288                 g_qeglobals.m_userEnginePath = EnginePath_get();
289         }
290         while ( 0 );
291
292         Q_mkdir( g_qeglobals.m_userEnginePath.c_str() );
293
294         {
295                 StringOutputStream path( 256 );
296                 path << g_qeglobals.m_userEnginePath.c_str() << gamename_get() << '/';
297                 g_qeglobals.m_userGamePath = path.c_str();
298         }
299         ASSERT_MESSAGE( !string_empty( g_qeglobals.m_userGamePath.c_str() ), "HomePaths_Realise: user-game-path is empty" );
300         Q_mkdir( g_qeglobals.m_userGamePath.c_str() );
301 }
302
303 ModuleObservers g_homePathObservers;
304
305 void Radiant_attachHomePathsObserver( ModuleObserver& observer ){
306         g_homePathObservers.attach( observer );
307 }
308
309 void Radiant_detachHomePathsObserver( ModuleObserver& observer ){
310         g_homePathObservers.detach( observer );
311 }
312
313 class HomePathsModuleObserver : public ModuleObserver
314 {
315 std::size_t m_unrealised;
316 public:
317 HomePathsModuleObserver() : m_unrealised( 1 ){
318 }
319
320 void realise(){
321         if ( --m_unrealised == 0 ) {
322                 HomePaths_Realise();
323                 g_homePathObservers.realise();
324         }
325 }
326
327 void unrealise(){
328         if ( ++m_unrealised == 1 ) {
329                 g_homePathObservers.unrealise();
330         }
331 }
332 };
333
334 HomePathsModuleObserver g_HomePathsModuleObserver;
335
336 void HomePaths_Construct(){
337         Radiant_attachEnginePathObserver( g_HomePathsModuleObserver );
338 }
339
340 void HomePaths_Destroy(){
341         Radiant_detachEnginePathObserver( g_HomePathsModuleObserver );
342 }
343
344
345 // Engine Path
346
347 CopiedString g_strEnginePath;
348 ModuleObservers g_enginePathObservers;
349 std::size_t g_enginepath_unrealised = 1;
350
351 void Radiant_attachEnginePathObserver( ModuleObserver& observer ){
352         g_enginePathObservers.attach( observer );
353 }
354
355 void Radiant_detachEnginePathObserver( ModuleObserver& observer ){
356         g_enginePathObservers.detach( observer );
357 }
358
359
360 void EnginePath_Realise(){
361         if ( --g_enginepath_unrealised == 0 ) {
362                 g_enginePathObservers.realise();
363         }
364 }
365
366
367 const char* EnginePath_get(){
368         ASSERT_MESSAGE( g_enginepath_unrealised == 0, "EnginePath_get: engine path not realised" );
369         return g_strEnginePath.c_str();
370 }
371
372 void EnginePath_Unrealise(){
373         if ( ++g_enginepath_unrealised == 1 ) {
374                 g_enginePathObservers.unrealise();
375         }
376 }
377
378 void setEnginePath( const char* path ){
379         StringOutputStream buffer( 256 );
380         buffer << DirectoryCleaned( path );
381         if ( !path_equal( buffer.c_str(), g_strEnginePath.c_str() ) ) {
382 #if 0
383                 while ( !ConfirmModified( "Paths Changed" ) )
384                 {
385                         if ( Map_Unnamed( g_map ) ) {
386                                 Map_SaveAs();
387                         }
388                         else
389                         {
390                                 Map_Save();
391                         }
392                 }
393                 Map_RegionOff();
394 #endif
395
396                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Changing Engine Path" );
397
398                 EnginePath_Unrealise();
399
400                 g_strEnginePath = buffer.c_str();
401
402                 EnginePath_Realise();
403         }
404 }
405
406 // Pak Path
407
408 CopiedString g_strPakPath[g_pakPathCount] = { "", "", "", "", "" };
409 ModuleObservers g_pakPathObservers[g_pakPathCount];
410 std::size_t g_pakpath_unrealised[g_pakPathCount] = { 1, 1, 1, 1, 1 };
411
412 void Radiant_attachPakPathObserver( int num, ModuleObserver& observer ){
413         g_pakPathObservers[num].attach( observer );
414 }
415
416 void Radiant_detachPakPathObserver( int num, ModuleObserver& observer ){
417         g_pakPathObservers[num].detach( observer );
418 }
419
420
421 void PakPath_Realise( int num ){
422         if ( --g_pakpath_unrealised[num] == 0 ) {
423                 g_pakPathObservers[num].realise();
424         }
425 }
426
427 const char* PakPath_get( int num ){
428         std::string message = "PakPath_get: pak path " + std::to_string(num) + " not realised";
429         ASSERT_MESSAGE( g_pakpath_unrealised[num] == 0, message.c_str() );
430         return g_strPakPath[num].c_str();
431 }
432
433 void PakPath_Unrealise( int num ){
434         if ( ++g_pakpath_unrealised[num] == 1 ) {
435                 g_pakPathObservers[num].unrealise();
436         }
437 }
438
439 void setPakPath( int num, const char* path ){
440         if (!g_strcmp0( path, "")) {
441                 g_strPakPath[num] = "";
442                 return;
443         }
444
445         StringOutputStream buffer( 256 );
446         buffer << DirectoryCleaned( path );
447         if ( !path_equal( buffer.c_str(), g_strPakPath[num].c_str() ) ) {
448                 std::string message = "Changing Pak Path " + std::to_string(num);
449                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", message.c_str() );
450
451                 PakPath_Unrealise(num);
452
453                 g_strPakPath[num] = buffer.c_str();
454
455                 PakPath_Realise(num);
456         }
457 }
458
459
460 // executable file path (full path)
461 CopiedString g_strAppFilePath;
462
463 // directory paths
464 CopiedString g_strAppPath; 
465 CopiedString g_strLibPath;
466 CopiedString g_strDataPath;
467
468 const char* AppFilePath_get(){
469         return g_strAppFilePath.c_str();
470 }
471
472 const char* AppPath_get(){
473         return g_strAppPath.c_str();
474 }
475
476 const char *LibPath_get()
477 {
478     return g_strLibPath.c_str();
479 }
480
481 const char *DataPath_get()
482 {
483     return g_strDataPath.c_str();
484 }
485
486 /// the path to the local rc-dir
487 const char* LocalRcPath_get( void ){
488         static CopiedString rc_path;
489         if ( rc_path.empty() ) {
490                 StringOutputStream stream( 256 );
491                 stream << GlobalRadiant().getSettingsPath() << g_pGameDescription->mGameFile.c_str() << "/";
492                 rc_path = stream.c_str();
493         }
494         return rc_path.c_str();
495 }
496
497 /// directory for temp files
498 /// NOTE: on *nix this is were we check for .pid
499 CopiedString g_strSettingsPath;
500
501 const char* SettingsPath_get(){
502         return g_strSettingsPath.c_str();
503 }
504
505
506 /*!
507    points to the game tools directory, for instance
508    C:/Program Files/Quake III Arena/GtkRadiant
509    (or other games)
510    this is one of the main variables that are configured by the game selection on startup
511    [GameToolsPath]/plugins
512    [GameToolsPath]/modules
513    and also q3map, bspc
514  */
515 CopiedString g_strGameToolsPath;           ///< this is set by g_GamesDialog
516
517 const char* GameToolsPath_get(){
518         return g_strGameToolsPath.c_str();
519 }
520
521 struct EnginePath {
522         static void Export(const CopiedString &self, const Callback<void(const char *)> &returnz) {
523                 returnz(self.c_str());
524         }
525
526         static void Import(CopiedString &self, const char *value) {
527         setEnginePath( value );
528 }
529 };
530
531 struct PakPath0 {
532         static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
533                 returnz( self.c_str() );
534         }
535
536         static void Import( CopiedString &self, const char *value ) {
537                 setPakPath( 0, value );
538         }
539 };
540
541 struct PakPath1 {
542         static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
543                 returnz( self.c_str() );
544         }
545
546         static void Import( CopiedString &self, const char *value ) {
547                 setPakPath( 1, value );
548         }
549 };
550
551 struct PakPath2 {
552         static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
553                 returnz( self.c_str() );
554         }
555
556         static void Import( CopiedString &self, const char *value ) {
557                 setPakPath( 2, value );
558         }
559 };
560
561 struct PakPath3 {
562         static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
563                 returnz( self.c_str() );
564         }
565
566         static void Import( CopiedString &self, const char *value ) {
567                 setPakPath( 3, value );
568         }
569 };
570
571 struct PakPath4 {
572         static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
573                 returnz( self.c_str() );
574         }
575
576         static void Import( CopiedString &self, const char *value ) {
577                 setPakPath( 4, value );
578         }
579 };
580
581 bool g_disableEnginePath = false;
582 bool g_disableHomePath = false;
583
584 void Paths_constructBasicPreferences(  PreferencesPage& page ) {
585         page.appendPathEntry( "Engine Path", true, make_property<EnginePath>(g_strEnginePath) );
586 }
587
588 void Paths_constructPreferences( PreferencesPage& page ){
589         Paths_constructBasicPreferences( page );
590
591         page.appendSpacer( 4 );
592         page.appendLabel( "", "Advanced options" );
593         page.appendCheckBox( "", "Do not use Engine Path", g_disableEnginePath );
594         page.appendCheckBox( "", "Do not use Home Path", g_disableHomePath );
595
596         page.appendSpacer( 4 );
597         page.appendLabel( "", "Only a very few games support Pak Paths," );
598         page.appendLabel( "", "if you don't know what it is, leave this blank." );
599
600         const char *label = "Pak Path ";
601         page.appendPathEntry( label, true, make_property<PakPath0>( g_strPakPath[0] ) );
602         page.appendPathEntry( label, true, make_property<PakPath1>( g_strPakPath[1] ) );
603         page.appendPathEntry( label, true, make_property<PakPath2>( g_strPakPath[2] ) );
604         page.appendPathEntry( label, true, make_property<PakPath3>( g_strPakPath[3] ) );
605         page.appendPathEntry( label, true, make_property<PakPath4>( g_strPakPath[4] ) );
606 }
607
608 void Paths_constructPage( PreferenceGroup& group ){
609         PreferencesPage page( group.createPage( "Paths", "Path Settings" ) );
610         Paths_constructPreferences( page );
611 }
612
613 void Paths_registerPreferencesPage(){
614         PreferencesDialog_addSettingsPage( makeCallbackF(Paths_constructPage) );
615 }
616
617
618 class PathsDialog : public Dialog
619 {
620 public:
621 ui::Window BuildDialog(){
622         auto frame = create_dialog_frame( "Path Settings", ui::Shadow::ETCHED_IN );
623
624         auto vbox2 = create_dialog_vbox( 0, 4 );
625         frame.add(vbox2);
626
627         {
628                 PreferencesPage page( *this, vbox2 );
629                 Paths_constructBasicPreferences( page );
630         }
631
632         return ui::Window(create_simple_modal_dialog_window( "Engine Path Not Found", m_modal, frame ));
633 }
634 };
635
636 PathsDialog g_PathsDialog;
637
638 void EnginePath_verify(){
639         if ( !file_exists( g_strEnginePath.c_str() ) ) {
640                 g_PathsDialog.Create();
641                 g_PathsDialog.DoModal();
642                 g_PathsDialog.Destroy();
643         }
644 }
645
646 namespace
647 {
648 CopiedString g_gamename;
649 CopiedString g_gamemode;
650 ModuleObservers g_gameNameObservers;
651 ModuleObservers g_gameModeObservers;
652 }
653
654 void Radiant_attachGameNameObserver( ModuleObserver& observer ){
655         g_gameNameObservers.attach( observer );
656 }
657
658 void Radiant_detachGameNameObserver( ModuleObserver& observer ){
659         g_gameNameObservers.detach( observer );
660 }
661
662 const char* basegame_get(){
663         return g_pGameDescription->getRequiredKeyValue( "basegame" );
664 }
665
666 const char* gamename_get(){
667         const char* gamename = g_gamename.c_str();
668         if ( string_empty( gamename ) ) {
669                 return basegame_get();
670         }
671         return gamename;
672 }
673
674 void gamename_set( const char* gamename ){
675         if ( !string_equal( gamename, g_gamename.c_str() ) ) {
676                 g_gameNameObservers.unrealise();
677                 g_gamename = gamename;
678                 g_gameNameObservers.realise();
679         }
680 }
681
682 void Radiant_attachGameModeObserver( ModuleObserver& observer ){
683         g_gameModeObservers.attach( observer );
684 }
685
686 void Radiant_detachGameModeObserver( ModuleObserver& observer ){
687         g_gameModeObservers.detach( observer );
688 }
689
690 const char* gamemode_get(){
691         return g_gamemode.c_str();
692 }
693
694 void gamemode_set( const char* gamemode ){
695         if ( !string_equal( gamemode, g_gamemode.c_str() ) ) {
696                 g_gameModeObservers.unrealise();
697                 g_gamemode = gamemode;
698                 g_gameModeObservers.realise();
699         }
700 }
701
702
703 #include "os/dir.h"
704
705 const char* const c_library_extension =
706 #if defined( CMAKE_SHARED_MODULE_SUFFIX )
707     CMAKE_SHARED_MODULE_SUFFIX
708 #elif GDEF_OS_WINDOWS
709         "dll"
710 #elif GDEF_OS_MACOS
711         "dylib"
712 #elif GDEF_OS_LINUX || GDEF_OS_BSD
713         "so"
714 #endif
715 ;
716
717 void Radiant_loadModules( const char* path ){
718         Directory_forEach(path, matchFileExtension(c_library_extension, [&](const char *name) {
719                 char fullname[1024];
720                 ASSERT_MESSAGE(strlen(path) + strlen(name) < 1024, "");
721                 strcpy(fullname, path);
722                 strcat(fullname, name);
723                 globalOutputStream() << "Found '" << fullname << "'\n";
724                 GlobalModuleServer_loadModule(fullname);
725         }));
726 }
727
728 void Radiant_loadModulesFromRoot( const char* directory ){
729         {
730                 StringOutputStream path( 256 );
731                 path << directory << g_pluginsDir;
732                 Radiant_loadModules( path.c_str() );
733         }
734
735         if ( !string_equal( g_pluginsDir, g_modulesDir ) ) {
736                 StringOutputStream path( 256 );
737                 path << directory << g_modulesDir;
738                 Radiant_loadModules( path.c_str() );
739         }
740 }
741
742 //! Make COLOR_BRUSHES override worldspawn eclass colour.
743 void SetWorldspawnColour( const Vector3& colour ){
744         EntityClass* worldspawn = GlobalEntityClassManager().findOrInsert( "worldspawn", true );
745         eclass_release_state( worldspawn );
746         worldspawn->color = colour;
747         eclass_capture_state( worldspawn );
748 }
749
750
751 class WorldspawnColourEntityClassObserver : public ModuleObserver
752 {
753 std::size_t m_unrealised;
754 public:
755 WorldspawnColourEntityClassObserver() : m_unrealised( 1 ){
756 }
757
758 void realise(){
759         if ( --m_unrealised == 0 ) {
760                 SetWorldspawnColour( g_xywindow_globals.color_brushes );
761         }
762 }
763
764 void unrealise(){
765         if ( ++m_unrealised == 1 ) {
766         }
767 }
768 };
769
770 WorldspawnColourEntityClassObserver g_WorldspawnColourEntityClassObserver;
771
772
773 ModuleObservers g_gameToolsPathObservers;
774
775 void Radiant_attachGameToolsPathObserver( ModuleObserver& observer ){
776         g_gameToolsPathObservers.attach( observer );
777 }
778
779 void Radiant_detachGameToolsPathObserver( ModuleObserver& observer ){
780         g_gameToolsPathObservers.detach( observer );
781 }
782
783 void Radiant_Initialise(){
784         GlobalModuleServer_Initialise();
785
786         Radiant_loadModulesFromRoot( LibPath_get() );
787
788         Preferences_Load();
789
790         bool success = Radiant_Construct( GlobalModuleServer_get() );
791         ASSERT_MESSAGE( success, "module system failed to initialise - see radiant.log for error messages" );
792
793         g_gameToolsPathObservers.realise();
794         g_gameModeObservers.realise();
795         g_gameNameObservers.realise();
796 }
797
798 void Radiant_Shutdown(){
799         g_gameNameObservers.unrealise();
800         g_gameModeObservers.unrealise();
801         g_gameToolsPathObservers.unrealise();
802
803         if ( !g_preferences_globals.disable_ini ) {
804                 globalOutputStream() << "Start writing prefs\n";
805                 Preferences_Save();
806                 globalOutputStream() << "Done prefs\n";
807         }
808
809         Radiant_Destroy();
810
811         GlobalModuleServer_Shutdown();
812 }
813
814 void Exit(){
815         if ( ConfirmModified( "Exit " RADIANT_NAME ) ) {
816                 gtk_main_quit();
817         }
818 }
819
820
821 void Undo(){
822         GlobalUndoSystem().undo();
823         SceneChangeNotify();
824 }
825
826 void Redo(){
827         GlobalUndoSystem().redo();
828         SceneChangeNotify();
829 }
830
831 void deleteSelection(){
832         UndoableCommand undo( "deleteSelected" );
833         Select_Delete();
834 }
835
836 void Map_ExportSelected( TextOutputStream& ostream ){
837         Map_ExportSelected( ostream, Map_getFormat( g_map ) );
838 }
839
840 void Map_ImportSelected( TextInputStream& istream ){
841         Map_ImportSelected( istream, Map_getFormat( g_map ) );
842 }
843
844 void Selection_Copy(){
845         clipboard_copy( Map_ExportSelected );
846 }
847
848 void Selection_Paste(){
849         clipboard_paste( Map_ImportSelected );
850 }
851
852 void Copy(){
853         if ( SelectedFaces_empty() ) {
854                 Selection_Copy();
855         }
856         else
857         {
858                 SelectedFaces_copyTexture();
859         }
860 }
861
862 void Paste(){
863         if ( SelectedFaces_empty() ) {
864                 UndoableCommand undo( "paste" );
865
866                 GlobalSelectionSystem().setSelectedAll( false );
867                 Selection_Paste();
868         }
869         else
870         {
871                 SelectedFaces_pasteTexture();
872         }
873 }
874
875 void PasteToCamera(){
876         CamWnd& camwnd = *g_pParentWnd->GetCamWnd();
877         GlobalSelectionSystem().setSelectedAll( false );
878
879         UndoableCommand undo( "pasteToCamera" );
880
881         Selection_Paste();
882
883         // Work out the delta
884         Vector3 mid;
885         Select_GetMid( mid );
886         Vector3 delta = vector3_subtracted( vector3_snapped( Camera_getOrigin( camwnd ), GetSnapGridSize() ), mid );
887
888         // Move to camera
889         GlobalSelectionSystem().translateSelected( delta );
890 }
891
892
893 void ColorScheme_Original(){
894         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
895
896         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
897         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
898         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
899
900         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
901         g_xywindow_globals.color_gridminor = Vector3( 0.75f, 0.75f, 0.75f );
902         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
903         g_xywindow_globals.color_gridminor_alt = Vector3( 0.5f, 0.0f, 0.0f );
904         g_xywindow_globals.color_gridmajor_alt = Vector3( 1.0f, 0.0f, 0.0f );
905         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
906         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
907         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
908         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
909         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
910         SetWorldspawnColour( g_xywindow_globals.color_brushes );
911         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
912         XY_UpdateAllWindows();
913 }
914
915 void ColorScheme_QER(){
916         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
917
918         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
919         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
920         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
921
922         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
923         g_xywindow_globals.color_gridminor = Vector3( 1.0f, 1.0f, 1.0f );
924         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
925         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
926         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
927         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
928         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
929         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
930         SetWorldspawnColour( g_xywindow_globals.color_brushes );
931         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
932         XY_UpdateAllWindows();
933 }
934
935 void ColorScheme_Black(){
936         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
937
938         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
939         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
940         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
941
942         g_xywindow_globals.color_gridback = Vector3( 0.0f, 0.0f, 0.0f );
943         g_xywindow_globals.color_gridminor = Vector3( 0.2f, 0.2f, 0.2f );
944         g_xywindow_globals.color_gridmajor = Vector3( 0.3f, 0.5f, 0.5f );
945         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
946         g_xywindow_globals.color_gridtext = Vector3( 1.0f, 1.0f, 1.0f );
947         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
948         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
949         g_xywindow_globals.color_brushes = Vector3( 1.0f, 1.0f, 1.0f );
950         SetWorldspawnColour( g_xywindow_globals.color_brushes );
951         g_xywindow_globals.color_viewname = Vector3( 0.7f, 0.7f, 0.0f );
952         XY_UpdateAllWindows();
953 }
954
955 /* ydnar: to emulate maya/max/lightwave color schemes */
956 void ColorScheme_Ydnar(){
957         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
958
959         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
960         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
961         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
962
963         g_xywindow_globals.color_gridback = Vector3( 0.77f, 0.77f, 0.77f );
964         g_xywindow_globals.color_gridminor = Vector3( 0.83f, 0.83f, 0.83f );
965         g_xywindow_globals.color_gridmajor = Vector3( 0.89f, 0.89f, 0.89f );
966         g_xywindow_globals.color_gridblock = Vector3( 1.0f, 1.0f, 1.0f );
967         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
968         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
969         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
970         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
971         SetWorldspawnColour( g_xywindow_globals.color_brushes );
972         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
973         XY_UpdateAllWindows();
974 }
975
976 /* color scheme to fit the GTK Adwaita Dark theme */
977 void ColorScheme_AdwaitaDark()
978 {
979         // SI_Colors0
980         // GlobalTextureBrowser().color_textureback
981         TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), Vector3(0.25f, 0.25f, 0.25f));
982
983         // SI_Colors4
984         g_camwindow_globals.color_cameraback = Vector3(0.25f, 0.25f, 0.25f);
985         // SI_Colors12
986         g_camwindow_globals.color_selbrushes3d = Vector3(1.0f, 0.0f, 0.0f);
987         CamWnd_Update(*g_pParentWnd->GetCamWnd());
988
989         // SI_Colors1
990         g_xywindow_globals.color_gridback = Vector3(0.25f, 0.25f, 0.25f);
991         // SI_Colors2
992         g_xywindow_globals.color_gridminor = Vector3(0.21f, 0.23f, 0.23f);
993         // SI_Colors3
994         g_xywindow_globals.color_gridmajor = Vector3(0.14f, 0.15f, 0.15f);
995         // SI_Colors14
996         g_xywindow_globals.color_gridmajor_alt = Vector3(1.0f, 0.0f, 0.0f);
997         // SI_Colors6
998         g_xywindow_globals.color_gridblock = Vector3(1.0f, 1.0f, 1.0f);
999         // SI_Colors7
1000         g_xywindow_globals.color_gridtext = Vector3(0.0f, 0.0f, 0.0f);
1001         // ??
1002         g_xywindow_globals.color_selbrushes = Vector3(1.0f, 0.0f, 0.0f);
1003         // ??
1004         g_xywindow_globals.color_clipper = Vector3(0.0f, 0.0f, 1.0f);
1005         // SI_Colors8
1006         g_xywindow_globals.color_brushes = Vector3(0.73f, 0.73f, 0.73f);
1007
1008         // SI_AxisColors0
1009         g_xywindow_globals.AxisColorX = Vector3(1.0f, 0.0f, 0.0f);
1010         // SI_AxisColors1
1011         g_xywindow_globals.AxisColorY = Vector3(0.0f, 1.0f, 0.0f);
1012         // SI_AxisColors2
1013         g_xywindow_globals.AxisColorZ = Vector3(0.0f, 0.0f, 1.0f);
1014         SetWorldspawnColour(g_xywindow_globals.color_brushes);
1015         // ??
1016         g_xywindow_globals.color_viewname = Vector3(0.5f, 0.0f, 0.75f);
1017         XY_UpdateAllWindows();
1018
1019         // SI_Colors5
1020         // g_entity_globals.color_entity = Vector3(0.0f, 0.0f, 0.0f);
1021 }
1022
1023 typedef Callback<void(Vector3&)> GetColourCallback;
1024 typedef Callback<void(const Vector3&)> SetColourCallback;
1025
1026 class ChooseColour
1027 {
1028 GetColourCallback m_get;
1029 SetColourCallback m_set;
1030 public:
1031 ChooseColour( const GetColourCallback& get, const SetColourCallback& set )
1032         : m_get( get ), m_set( set ){
1033 }
1034
1035 void operator()(){
1036         Vector3 colour;
1037         m_get( colour );
1038         color_dialog( MainFrame_getWindow(), colour );
1039         m_set( colour );
1040 }
1041 };
1042
1043
1044 void Colour_get( const Vector3& colour, Vector3& other ){
1045         other = colour;
1046 }
1047
1048 typedef ConstReferenceCaller<Vector3, void(Vector3&), Colour_get> ColourGetCaller;
1049
1050 void Colour_set( Vector3& colour, const Vector3& other ){
1051         colour = other;
1052         SceneChangeNotify();
1053 }
1054
1055 typedef ReferenceCaller<Vector3, void(const Vector3&), Colour_set> ColourSetCaller;
1056
1057 void BrushColour_set( const Vector3& other ){
1058         g_xywindow_globals.color_brushes = other;
1059         SetWorldspawnColour( g_xywindow_globals.color_brushes );
1060         SceneChangeNotify();
1061 }
1062
1063 typedef FreeCaller<void(const Vector3&), BrushColour_set> BrushColourSetCaller;
1064
1065 void ClipperColour_set( const Vector3& other ){
1066         g_xywindow_globals.color_clipper = other;
1067         Brush_clipperColourChanged();
1068         SceneChangeNotify();
1069 }
1070
1071 typedef FreeCaller<void(const Vector3&), ClipperColour_set> ClipperColourSetCaller;
1072
1073 void TextureBrowserColour_get( Vector3& other ){
1074         other = TextureBrowser_getBackgroundColour( GlobalTextureBrowser() );
1075 }
1076
1077 typedef FreeCaller<void(Vector3&), TextureBrowserColour_get> TextureBrowserColourGetCaller;
1078
1079 void TextureBrowserColour_set( const Vector3& other ){
1080         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), other );
1081 }
1082
1083 typedef FreeCaller<void(const Vector3&), TextureBrowserColour_set> TextureBrowserColourSetCaller;
1084
1085
1086 class ColoursMenu
1087 {
1088 public:
1089 ChooseColour m_textureback;
1090 ChooseColour m_xyback;
1091 ChooseColour m_gridmajor;
1092 ChooseColour m_gridminor;
1093 ChooseColour m_gridmajor_alt;
1094 ChooseColour m_gridminor_alt;
1095 ChooseColour m_gridtext;
1096 ChooseColour m_gridblock;
1097 ChooseColour m_cameraback;
1098 ChooseColour m_brush;
1099 ChooseColour m_selectedbrush;
1100 ChooseColour m_selectedbrush3d;
1101 ChooseColour m_clipper;
1102 ChooseColour m_viewname;
1103
1104 ColoursMenu() :
1105         m_textureback( TextureBrowserColourGetCaller(), TextureBrowserColourSetCaller() ),
1106         m_xyback( ColourGetCaller( g_xywindow_globals.color_gridback ), ColourSetCaller( g_xywindow_globals.color_gridback ) ),
1107         m_gridmajor( ColourGetCaller( g_xywindow_globals.color_gridmajor ), ColourSetCaller( g_xywindow_globals.color_gridmajor ) ),
1108         m_gridminor( ColourGetCaller( g_xywindow_globals.color_gridminor ), ColourSetCaller( g_xywindow_globals.color_gridminor ) ),
1109         m_gridmajor_alt( ColourGetCaller( g_xywindow_globals.color_gridmajor_alt ), ColourSetCaller( g_xywindow_globals.color_gridmajor_alt ) ),
1110         m_gridminor_alt( ColourGetCaller( g_xywindow_globals.color_gridminor_alt ), ColourSetCaller( g_xywindow_globals.color_gridminor_alt ) ),
1111         m_gridtext( ColourGetCaller( g_xywindow_globals.color_gridtext ), ColourSetCaller( g_xywindow_globals.color_gridtext ) ),
1112         m_gridblock( ColourGetCaller( g_xywindow_globals.color_gridblock ), ColourSetCaller( g_xywindow_globals.color_gridblock ) ),
1113         m_cameraback( ColourGetCaller( g_camwindow_globals.color_cameraback ), ColourSetCaller( g_camwindow_globals.color_cameraback ) ),
1114         m_brush( ColourGetCaller( g_xywindow_globals.color_brushes ), BrushColourSetCaller() ),
1115         m_selectedbrush( ColourGetCaller( g_xywindow_globals.color_selbrushes ), ColourSetCaller( g_xywindow_globals.color_selbrushes ) ),
1116         m_selectedbrush3d( ColourGetCaller( g_camwindow_globals.color_selbrushes3d ), ColourSetCaller( g_camwindow_globals.color_selbrushes3d ) ),
1117         m_clipper( ColourGetCaller( g_xywindow_globals.color_clipper ), ClipperColourSetCaller() ),
1118         m_viewname( ColourGetCaller( g_xywindow_globals.color_viewname ), ColourSetCaller( g_xywindow_globals.color_viewname ) ){
1119 }
1120 };
1121
1122 ColoursMenu g_ColoursMenu;
1123
1124 ui::MenuItem create_colours_menu(){
1125         auto colours_menu_item = new_sub_menu_item_with_mnemonic( "Colors" );
1126         auto menu_in_menu = ui::Menu::from( gtk_menu_item_get_submenu( colours_menu_item ) );
1127         if ( g_Layout_enableDetachableMenus.m_value ) {
1128                 menu_tearoff( menu_in_menu );
1129         }
1130
1131         auto menu_3 = create_sub_menu_with_mnemonic( menu_in_menu, "Themes" );
1132         if ( g_Layout_enableDetachableMenus.m_value ) {
1133                 menu_tearoff( menu_3 );
1134         }
1135
1136         create_menu_item_with_mnemonic( menu_3, "QE4 Original", "ColorSchemeOriginal" );
1137         create_menu_item_with_mnemonic( menu_3, "Q3Radiant Original", "ColorSchemeQER" );
1138         create_menu_item_with_mnemonic( menu_3, "Black and Green", "ColorSchemeBlackAndGreen" );
1139         create_menu_item_with_mnemonic( menu_3, "Maya/Max/Lightwave Emulation", "ColorSchemeYdnar" );
1140         create_menu_item_with_mnemonic(menu_3, "Adwaita Dark", "ColorSchemeAdwaitaDark");
1141
1142         menu_separator( menu_in_menu );
1143
1144         create_menu_item_with_mnemonic( menu_in_menu, "_Texture Background...", "ChooseTextureBackgroundColor" );
1145         create_menu_item_with_mnemonic( menu_in_menu, "Grid Background...", "ChooseGridBackgroundColor" );
1146         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major...", "ChooseGridMajorColor" );
1147         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor...", "ChooseGridMinorColor" );
1148         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major Small...", "ChooseSmallGridMajorColor" );
1149         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor Small...", "ChooseSmallGridMinorColor" );
1150         create_menu_item_with_mnemonic( menu_in_menu, "Grid Text...", "ChooseGridTextColor" );
1151         create_menu_item_with_mnemonic( menu_in_menu, "Grid Block...", "ChooseGridBlockColor" );
1152         create_menu_item_with_mnemonic( menu_in_menu, "Default Brush...", "ChooseBrushColor" );
1153         create_menu_item_with_mnemonic( menu_in_menu, "Camera Background...", "ChooseCameraBackgroundColor" );
1154         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush...", "ChooseSelectedBrushColor" );
1155         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush (Camera)...", "ChooseCameraSelectedBrushColor" );
1156         create_menu_item_with_mnemonic( menu_in_menu, "Clipper...", "ChooseClipperColor" );
1157         create_menu_item_with_mnemonic( menu_in_menu, "Active View name...", "ChooseOrthoViewNameColor" );
1158
1159         return colours_menu_item;
1160 }
1161
1162
1163 void Restart(){
1164         PluginsMenu_clear();
1165         PluginToolbar_clear();
1166
1167         Radiant_Shutdown();
1168         Radiant_Initialise();
1169
1170         PluginsMenu_populate();
1171
1172         PluginToolbar_populate();
1173 }
1174
1175
1176 void thunk_OnSleep(){
1177         g_pParentWnd->OnSleep();
1178 }
1179
1180 void OpenHelpURL(){
1181         OpenURL( "https://gitlab.com/xonotic/xonotic/wikis/Mapping" );
1182 }
1183
1184 void OpenBugReportURL(){
1185         OpenURL( "https://gitlab.com/xonotic/netradiant/issues" );
1186 }
1187
1188
1189 ui::Widget g_page_console{ui::null};
1190
1191 void Console_ToggleShow(){
1192         GroupDialog_showPage( g_page_console );
1193 }
1194
1195 ui::Widget g_page_entity{ui::null};
1196
1197 void EntityInspector_ToggleShow(){
1198         GroupDialog_showPage( g_page_entity );
1199 }
1200
1201
1202 void SetClipMode( bool enable );
1203
1204 void ModeChangeNotify();
1205
1206 typedef void ( *ToolMode )();
1207
1208 ToolMode g_currentToolMode = 0;
1209 bool g_currentToolModeSupportsComponentEditing = false;
1210 ToolMode g_defaultToolMode = 0;
1211
1212
1213 void SelectionSystem_DefaultMode(){
1214         GlobalSelectionSystem().SetMode( SelectionSystem::ePrimitive );
1215         GlobalSelectionSystem().SetComponentMode( SelectionSystem::eDefault );
1216         ModeChangeNotify();
1217 }
1218
1219
1220 bool EdgeMode(){
1221         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1222                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eEdge;
1223 }
1224
1225 bool VertexMode(){
1226         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1227                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex;
1228 }
1229
1230 bool FaceMode(){
1231         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1232                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace;
1233 }
1234
1235 template<bool( *BoolFunction ) ( )>
1236 class BoolFunctionExport
1237 {
1238 public:
1239 static void apply( const Callback<void(bool)> & importCallback ){
1240         importCallback( BoolFunction() );
1241 }
1242 };
1243
1244 typedef FreeCaller<void(const Callback<void(bool)> &), &BoolFunctionExport<EdgeMode>::apply> EdgeModeApplyCaller;
1245 EdgeModeApplyCaller g_edgeMode_button_caller;
1246 Callback<void(const Callback<void(bool)> &)> g_edgeMode_button_callback( g_edgeMode_button_caller );
1247 ToggleItem g_edgeMode_button( g_edgeMode_button_callback );
1248
1249 typedef FreeCaller<void(const Callback<void(bool)> &), &BoolFunctionExport<VertexMode>::apply> VertexModeApplyCaller;
1250 VertexModeApplyCaller g_vertexMode_button_caller;
1251 Callback<void(const Callback<void(bool)> &)> g_vertexMode_button_callback( g_vertexMode_button_caller );
1252 ToggleItem g_vertexMode_button( g_vertexMode_button_callback );
1253
1254 typedef FreeCaller<void(const Callback<void(bool)> &), &BoolFunctionExport<FaceMode>::apply> FaceModeApplyCaller;
1255 FaceModeApplyCaller g_faceMode_button_caller;
1256 Callback<void(const Callback<void(bool)> &)> g_faceMode_button_callback( g_faceMode_button_caller );
1257 ToggleItem g_faceMode_button( g_faceMode_button_callback );
1258
1259 void ComponentModeChanged(){
1260         g_edgeMode_button.update();
1261         g_vertexMode_button.update();
1262         g_faceMode_button.update();
1263 }
1264
1265 void ComponentMode_SelectionChanged( const Selectable& selectable ){
1266         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1267                  && GlobalSelectionSystem().countSelected() == 0 ) {
1268                 SelectionSystem_DefaultMode();
1269                 ComponentModeChanged();
1270         }
1271 }
1272
1273 void SelectEdgeMode(){
1274 #if 0
1275         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1276                 GlobalSelectionSystem().Select( false );
1277         }
1278 #endif
1279
1280         if ( EdgeMode() ) {
1281                 SelectionSystem_DefaultMode();
1282         }
1283         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1284                 if ( !g_currentToolModeSupportsComponentEditing ) {
1285                         g_defaultToolMode();
1286                 }
1287
1288                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1289                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eEdge );
1290         }
1291
1292         ComponentModeChanged();
1293
1294         ModeChangeNotify();
1295 }
1296
1297 void SelectVertexMode(){
1298 #if 0
1299         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1300                 GlobalSelectionSystem().Select( false );
1301         }
1302 #endif
1303
1304         if ( VertexMode() ) {
1305                 SelectionSystem_DefaultMode();
1306         }
1307         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1308                 if ( !g_currentToolModeSupportsComponentEditing ) {
1309                         g_defaultToolMode();
1310                 }
1311
1312                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1313                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eVertex );
1314         }
1315
1316         ComponentModeChanged();
1317
1318         ModeChangeNotify();
1319 }
1320
1321 void SelectFaceMode(){
1322 #if 0
1323         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1324                 GlobalSelectionSystem().Select( false );
1325         }
1326 #endif
1327
1328         if ( FaceMode() ) {
1329                 SelectionSystem_DefaultMode();
1330         }
1331         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1332                 if ( !g_currentToolModeSupportsComponentEditing ) {
1333                         g_defaultToolMode();
1334                 }
1335
1336                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1337                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eFace );
1338         }
1339
1340         ComponentModeChanged();
1341
1342         ModeChangeNotify();
1343 }
1344
1345
1346 class CloneSelected : public scene::Graph::Walker
1347 {
1348 bool doMakeUnique;
1349 NodeSmartReference worldspawn;
1350 public:
1351 CloneSelected( bool d ) : doMakeUnique( d ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){
1352 }
1353
1354 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1355         if ( path.size() == 1 ) {
1356                 return true;
1357         }
1358
1359         // ignore worldspawn, but keep checking children
1360         NodeSmartReference me( path.top().get() );
1361         if ( me == worldspawn ) {
1362                 return true;
1363         }
1364
1365         if ( !path.top().get().isRoot() ) {
1366                 Selectable* selectable = Instance_getSelectable( instance );
1367                 if ( selectable != 0
1368                          && selectable->isSelected() ) {
1369                         return false;
1370                 }
1371         }
1372
1373         return true;
1374 }
1375
1376 void post( const scene::Path& path, scene::Instance& instance ) const {
1377         if ( path.size() == 1 ) {
1378                 return;
1379         }
1380
1381         // ignore worldspawn, but keep checking children
1382         NodeSmartReference me( path.top().get() );
1383         if ( me == worldspawn ) {
1384                 return;
1385         }
1386
1387         if ( !path.top().get().isRoot() ) {
1388                 Selectable* selectable = Instance_getSelectable( instance );
1389                 if ( selectable != 0
1390                          && selectable->isSelected() ) {
1391                         NodeSmartReference clone( Node_Clone( path.top() ) );
1392                         if ( doMakeUnique ) {
1393                                 Map_gatherNamespaced( clone );
1394                         }
1395                         Node_getTraversable( path.parent().get() )->insert( clone );
1396                 }
1397         }
1398 }
1399 };
1400
1401 void Scene_Clone_Selected( scene::Graph& graph, bool doMakeUnique ){
1402         graph.traverse( CloneSelected( doMakeUnique ) );
1403
1404         Map_mergeClonedNames();
1405 }
1406
1407 enum ENudgeDirection
1408 {
1409         eNudgeUp = 1,
1410         eNudgeDown = 3,
1411         eNudgeLeft = 0,
1412         eNudgeRight = 2,
1413 };
1414
1415 struct AxisBase
1416 {
1417         Vector3 x;
1418         Vector3 y;
1419         Vector3 z;
1420
1421         AxisBase( const Vector3& x_, const Vector3& y_, const Vector3& z_ )
1422                 : x( x_ ), y( y_ ), z( z_ ){
1423         }
1424 };
1425
1426 AxisBase AxisBase_forViewType( VIEWTYPE viewtype ){
1427         switch ( viewtype )
1428         {
1429         case XY:
1430                 return AxisBase( g_vector3_axis_x, g_vector3_axis_y, g_vector3_axis_z );
1431         case XZ:
1432                 return AxisBase( g_vector3_axis_x, g_vector3_axis_z, g_vector3_axis_y );
1433         case YZ:
1434                 return AxisBase( g_vector3_axis_y, g_vector3_axis_z, g_vector3_axis_x );
1435         }
1436
1437         ERROR_MESSAGE( "invalid viewtype" );
1438         return AxisBase( Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ) );
1439 }
1440
1441 Vector3 AxisBase_axisForDirection( const AxisBase& axes, ENudgeDirection direction ){
1442         switch ( direction )
1443         {
1444         case eNudgeLeft:
1445                 return vector3_negated( axes.x );
1446         case eNudgeUp:
1447                 return axes.y;
1448         case eNudgeRight:
1449                 return axes.x;
1450         case eNudgeDown:
1451                 return vector3_negated( axes.y );
1452         }
1453
1454         ERROR_MESSAGE( "invalid direction" );
1455         return Vector3( 0, 0, 0 );
1456 }
1457
1458 void NudgeSelection( ENudgeDirection direction, float fAmount, VIEWTYPE viewtype ){
1459         AxisBase axes( AxisBase_forViewType( viewtype ) );
1460         Vector3 view_direction( vector3_negated( axes.z ) );
1461         Vector3 nudge( vector3_scaled( AxisBase_axisForDirection( axes, direction ), fAmount ) );
1462         GlobalSelectionSystem().NudgeManipulator( nudge, view_direction );
1463 }
1464
1465 void Selection_Clone(){
1466         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
1467                 UndoableCommand undo( "cloneSelected" );
1468
1469                 Scene_Clone_Selected( GlobalSceneGraph(), false );
1470
1471                 //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1472                 //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1473         }
1474 }
1475
1476 void Selection_Clone_MakeUnique(){
1477         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
1478                 UndoableCommand undo( "cloneSelectedMakeUnique" );
1479
1480                 Scene_Clone_Selected( GlobalSceneGraph(), true );
1481
1482                 //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1483                 //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1484         }
1485 }
1486
1487 // called when the escape key is used (either on the main window or on an inspector)
1488 void Selection_Deselect(){
1489         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1490                 if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
1491                         GlobalSelectionSystem().setSelectedAllComponents( false );
1492                 }
1493                 else
1494                 {
1495                         SelectionSystem_DefaultMode();
1496                         ComponentModeChanged();
1497                 }
1498         }
1499         else
1500         {
1501                 if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
1502                         GlobalSelectionSystem().setSelectedAllComponents( false );
1503                 }
1504                 else
1505                 {
1506                         GlobalSelectionSystem().setSelectedAll( false );
1507                 }
1508         }
1509 }
1510
1511
1512 void Selection_NudgeUp(){
1513         UndoableCommand undo( "nudgeSelectedUp" );
1514         NudgeSelection( eNudgeUp, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1515 }
1516
1517 void Selection_NudgeDown(){
1518         UndoableCommand undo( "nudgeSelectedDown" );
1519         NudgeSelection( eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1520 }
1521
1522 void Selection_NudgeLeft(){
1523         UndoableCommand undo( "nudgeSelectedLeft" );
1524         NudgeSelection( eNudgeLeft, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1525 }
1526
1527 void Selection_NudgeRight(){
1528         UndoableCommand undo( "nudgeSelectedRight" );
1529         NudgeSelection( eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1530 }
1531
1532
1533 void TranslateToolExport( const Callback<void(bool)> & importCallback ){
1534         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eTranslate );
1535 }
1536
1537 void RotateToolExport( const Callback<void(bool)> & importCallback ){
1538         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eRotate );
1539 }
1540
1541 void ScaleToolExport( const Callback<void(bool)> & importCallback ){
1542         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eScale );
1543 }
1544
1545 void DragToolExport( const Callback<void(bool)> & importCallback ){
1546         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag );
1547 }
1548
1549 void ClipperToolExport( const Callback<void(bool)> & importCallback ){
1550         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip );
1551 }
1552
1553 FreeCaller<void(const Callback<void(bool)> &), TranslateToolExport> g_translatemode_button_caller;
1554 Callback<void(const Callback<void(bool)> &)> g_translatemode_button_callback( g_translatemode_button_caller );
1555 ToggleItem g_translatemode_button( g_translatemode_button_callback );
1556
1557 FreeCaller<void(const Callback<void(bool)> &), RotateToolExport> g_rotatemode_button_caller;
1558 Callback<void(const Callback<void(bool)> &)> g_rotatemode_button_callback( g_rotatemode_button_caller );
1559 ToggleItem g_rotatemode_button( g_rotatemode_button_callback );
1560
1561 FreeCaller<void(const Callback<void(bool)> &), ScaleToolExport> g_scalemode_button_caller;
1562 Callback<void(const Callback<void(bool)> &)> g_scalemode_button_callback( g_scalemode_button_caller );
1563 ToggleItem g_scalemode_button( g_scalemode_button_callback );
1564
1565 FreeCaller<void(const Callback<void(bool)> &), DragToolExport> g_dragmode_button_caller;
1566 Callback<void(const Callback<void(bool)> &)> g_dragmode_button_callback( g_dragmode_button_caller );
1567 ToggleItem g_dragmode_button( g_dragmode_button_callback );
1568
1569 FreeCaller<void(const Callback<void(bool)> &), ClipperToolExport> g_clipper_button_caller;
1570 Callback<void(const Callback<void(bool)> &)> g_clipper_button_callback( g_clipper_button_caller );
1571 ToggleItem g_clipper_button( g_clipper_button_callback );
1572
1573 void ToolChanged(){
1574         g_translatemode_button.update();
1575         g_rotatemode_button.update();
1576         g_scalemode_button.update();
1577         g_dragmode_button.update();
1578         g_clipper_button.update();
1579 }
1580
1581 const char* const c_ResizeMode_status = "QE4 Drag Tool: move and resize objects";
1582
1583 void DragMode(){
1584         if ( g_currentToolMode == DragMode && g_defaultToolMode != DragMode ) {
1585                 g_defaultToolMode();
1586         }
1587         else
1588         {
1589                 g_currentToolMode = DragMode;
1590                 g_currentToolModeSupportsComponentEditing = true;
1591
1592                 OnClipMode( false );
1593
1594                 Sys_Status( c_ResizeMode_status );
1595                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eDrag );
1596                 ToolChanged();
1597                 ModeChangeNotify();
1598         }
1599 }
1600
1601
1602 const char* const c_TranslateMode_status = "Translate Tool: translate objects and components";
1603
1604 void TranslateMode(){
1605         if ( g_currentToolMode == TranslateMode && g_defaultToolMode != TranslateMode ) {
1606                 g_defaultToolMode();
1607         }
1608         else
1609         {
1610                 g_currentToolMode = TranslateMode;
1611                 g_currentToolModeSupportsComponentEditing = true;
1612
1613                 OnClipMode( false );
1614
1615                 Sys_Status( c_TranslateMode_status );
1616                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eTranslate );
1617                 ToolChanged();
1618                 ModeChangeNotify();
1619         }
1620 }
1621
1622 const char* const c_RotateMode_status = "Rotate Tool: rotate objects and components";
1623
1624 void RotateMode(){
1625         if ( g_currentToolMode == RotateMode && g_defaultToolMode != RotateMode ) {
1626                 g_defaultToolMode();
1627         }
1628         else
1629         {
1630                 g_currentToolMode = RotateMode;
1631                 g_currentToolModeSupportsComponentEditing = true;
1632
1633                 OnClipMode( false );
1634
1635                 Sys_Status( c_RotateMode_status );
1636                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eRotate );
1637                 ToolChanged();
1638                 ModeChangeNotify();
1639         }
1640 }
1641
1642 const char* const c_ScaleMode_status = "Scale Tool: scale objects and components";
1643
1644 void ScaleMode(){
1645         if ( g_currentToolMode == ScaleMode && g_defaultToolMode != ScaleMode ) {
1646                 g_defaultToolMode();
1647         }
1648         else
1649         {
1650                 g_currentToolMode = ScaleMode;
1651                 g_currentToolModeSupportsComponentEditing = true;
1652
1653                 OnClipMode( false );
1654
1655                 Sys_Status( c_ScaleMode_status );
1656                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eScale );
1657                 ToolChanged();
1658                 ModeChangeNotify();
1659         }
1660 }
1661
1662
1663 const char* const c_ClipperMode_status = "Clipper Tool: apply clip planes to objects";
1664
1665
1666 void ClipperMode(){
1667         if ( g_currentToolMode == ClipperMode && g_defaultToolMode != ClipperMode ) {
1668                 g_defaultToolMode();
1669         }
1670         else
1671         {
1672                 g_currentToolMode = ClipperMode;
1673                 g_currentToolModeSupportsComponentEditing = false;
1674
1675                 SelectionSystem_DefaultMode();
1676
1677                 OnClipMode( true );
1678
1679                 Sys_Status( c_ClipperMode_status );
1680                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eClip );
1681                 ToolChanged();
1682                 ModeChangeNotify();
1683         }
1684 }
1685
1686
1687 void Texdef_Rotate( float angle ){
1688         StringOutputStream command;
1689         command << "brushRotateTexture -angle " << angle;
1690         UndoableCommand undo( command.c_str() );
1691         Select_RotateTexture( angle );
1692 }
1693
1694 void Texdef_RotateClockwise(){
1695         Texdef_Rotate( static_cast<float>( fabs( g_si_globals.rotate ) ) );
1696 }
1697
1698 void Texdef_RotateAntiClockwise(){
1699         Texdef_Rotate( static_cast<float>( -fabs( g_si_globals.rotate ) ) );
1700 }
1701
1702 void Texdef_Scale( float x, float y ){
1703         StringOutputStream command;
1704         command << "brushScaleTexture -x " << x << " -y " << y;
1705         UndoableCommand undo( command.c_str() );
1706         Select_ScaleTexture( x, y );
1707 }
1708
1709 void Texdef_ScaleUp(){
1710         Texdef_Scale( 0, g_si_globals.scale[1] );
1711 }
1712
1713 void Texdef_ScaleDown(){
1714         Texdef_Scale( 0, -g_si_globals.scale[1] );
1715 }
1716
1717 void Texdef_ScaleLeft(){
1718         Texdef_Scale( -g_si_globals.scale[0],0 );
1719 }
1720
1721 void Texdef_ScaleRight(){
1722         Texdef_Scale( g_si_globals.scale[0],0 );
1723 }
1724
1725 void Texdef_Shift( float x, float y ){
1726         StringOutputStream command;
1727         command << "brushShiftTexture -x " << x << " -y " << y;
1728         UndoableCommand undo( command.c_str() );
1729         Select_ShiftTexture( x, y );
1730 }
1731
1732 void Texdef_ShiftLeft(){
1733         Texdef_Shift( -g_si_globals.shift[0], 0 );
1734 }
1735
1736 void Texdef_ShiftRight(){
1737         Texdef_Shift( g_si_globals.shift[0], 0 );
1738 }
1739
1740 void Texdef_ShiftUp(){
1741         Texdef_Shift( 0, g_si_globals.shift[1] );
1742 }
1743
1744 void Texdef_ShiftDown(){
1745         Texdef_Shift( 0, -g_si_globals.shift[1] );
1746 }
1747
1748
1749
1750 class SnappableSnapToGridSelected : public scene::Graph::Walker
1751 {
1752 float m_snap;
1753 public:
1754 SnappableSnapToGridSelected( float snap )
1755         : m_snap( snap ){
1756 }
1757
1758 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1759         if ( path.top().get().visible() ) {
1760                 Snappable* snappable = Node_getSnappable( path.top() );
1761                 if ( snappable != 0
1762                          && Instance_getSelectable( instance )->isSelected() ) {
1763                         snappable->snapto( m_snap );
1764                 }
1765         }
1766         return true;
1767 }
1768 };
1769
1770 void Scene_SnapToGrid_Selected( scene::Graph& graph, float snap ){
1771         graph.traverse( SnappableSnapToGridSelected( snap ) );
1772 }
1773
1774 class ComponentSnappableSnapToGridSelected : public scene::Graph::Walker
1775 {
1776 float m_snap;
1777 public:
1778 ComponentSnappableSnapToGridSelected( float snap )
1779         : m_snap( snap ){
1780 }
1781
1782 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1783         if ( path.top().get().visible() ) {
1784                 ComponentSnappable* componentSnappable = Instance_getComponentSnappable( instance );
1785                 if ( componentSnappable != 0
1786                          && Instance_getSelectable( instance )->isSelected() ) {
1787                         componentSnappable->snapComponents( m_snap );
1788                 }
1789         }
1790         return true;
1791 }
1792 };
1793
1794 void Scene_SnapToGrid_Component_Selected( scene::Graph& graph, float snap ){
1795         graph.traverse( ComponentSnappableSnapToGridSelected( snap ) );
1796 }
1797
1798 void Selection_SnapToGrid(){
1799         StringOutputStream command;
1800         command << "snapSelected -grid " << GetGridSize();
1801         UndoableCommand undo( command.c_str() );
1802
1803         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1804                 Scene_SnapToGrid_Component_Selected( GlobalSceneGraph(), GetGridSize() );
1805         }
1806         else
1807         {
1808                 Scene_SnapToGrid_Selected( GlobalSceneGraph(), GetGridSize() );
1809         }
1810 }
1811
1812
1813 static gint qe_every_second( gpointer data ){
1814         if (g_pParentWnd == nullptr)
1815                 return TRUE;
1816
1817         GdkModifierType mask;
1818         gdk_window_get_pointer( gtk_widget_get_window(g_pParentWnd->m_window), nullptr, nullptr, &mask );
1819
1820         if ( ( mask & ( GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK ) ) == 0 ) {
1821                 QE_CheckAutoSave();
1822         }
1823
1824         return TRUE;
1825 }
1826
1827 guint s_qe_every_second_id = 0;
1828
1829 void EverySecondTimer_enable(){
1830         if ( s_qe_every_second_id == 0 ) {
1831                 s_qe_every_second_id = g_timeout_add( 1000, qe_every_second, 0 );
1832         }
1833 }
1834
1835 void EverySecondTimer_disable(){
1836         if ( s_qe_every_second_id != 0 ) {
1837                 g_source_remove( s_qe_every_second_id );
1838                 s_qe_every_second_id = 0;
1839         }
1840 }
1841
1842 gint window_realize_remove_decoration( ui::Widget widget, gpointer data ){
1843         gdk_window_set_decorations( gtk_widget_get_window(widget), (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MENU | GDK_DECOR_MINIMIZE | GDK_DECOR_MAXIMIZE ) );
1844         return FALSE;
1845 }
1846
1847 class WaitDialog
1848 {
1849 public:
1850 ui::Window m_window{ui::null};
1851 ui::Label m_label{ui::null};
1852 };
1853
1854 WaitDialog create_wait_dialog( const char* title, const char* text ){
1855         WaitDialog dialog;
1856
1857         dialog.m_window = MainFrame_getWindow().create_floating_window(title);
1858         gtk_window_set_resizable( dialog.m_window, FALSE );
1859         gtk_container_set_border_width( GTK_CONTAINER( dialog.m_window ), 0 );
1860         gtk_window_set_position( dialog.m_window, GTK_WIN_POS_CENTER_ON_PARENT );
1861
1862         dialog.m_window.connect( "realize", G_CALLBACK( window_realize_remove_decoration ), 0 );
1863
1864         {
1865                 dialog.m_label = ui::Label( text );
1866                 gtk_misc_set_alignment( GTK_MISC( dialog.m_label ), 0.0, 0.5 );
1867                 gtk_label_set_justify( dialog.m_label, GTK_JUSTIFY_LEFT );
1868                 dialog.m_label.show();
1869                 dialog.m_label.dimensions(200, -1);
1870
1871                 dialog.m_window.add(dialog.m_label);
1872         }
1873         return dialog;
1874 }
1875
1876 namespace
1877 {
1878 clock_t g_lastRedrawTime = 0;
1879 const clock_t c_redrawInterval = clock_t( CLOCKS_PER_SEC / 10 );
1880
1881 bool redrawRequired(){
1882         clock_t currentTime = std::clock();
1883         if ( currentTime - g_lastRedrawTime >= c_redrawInterval ) {
1884                 g_lastRedrawTime = currentTime;
1885                 return true;
1886         }
1887         return false;
1888 }
1889 }
1890
1891 bool MainFrame_isActiveApp(){
1892         //globalOutputStream() << "listing\n";
1893         GList* list = gtk_window_list_toplevels();
1894         for ( GList* i = list; i != 0; i = g_list_next( i ) )
1895         {
1896                 //globalOutputStream() << "toplevel.. ";
1897                 if ( gtk_window_is_active( ui::Window::from( i->data ) ) ) {
1898                         //globalOutputStream() << "is active\n";
1899                         return true;
1900                 }
1901                 //globalOutputStream() << "not active\n";
1902         }
1903         return false;
1904 }
1905
1906 typedef std::list<CopiedString> StringStack;
1907 StringStack g_wait_stack;
1908 WaitDialog g_wait;
1909
1910 bool ScreenUpdates_Enabled(){
1911         return g_wait_stack.empty();
1912 }
1913
1914 void ScreenUpdates_process(){
1915         if ( redrawRequired() && g_wait.m_window.visible() ) {
1916                 ui::process();
1917         }
1918 }
1919
1920
1921 void ScreenUpdates_Disable( const char* message, const char* title ){
1922         if ( g_wait_stack.empty() ) {
1923                 EverySecondTimer_disable();
1924
1925                 ui::process();
1926
1927                 bool isActiveApp = MainFrame_isActiveApp();
1928
1929                 g_wait = create_wait_dialog( title, message );
1930
1931                 if ( isActiveApp ) {
1932                         g_wait.m_window.show();
1933                         gtk_grab_add( g_wait.m_window  );
1934                         ScreenUpdates_process();
1935                 }
1936         }
1937         else if ( g_wait.m_window.visible() ) {
1938                 g_wait.m_label.text(message);
1939                 if ( GTK_IS_WINDOW(g_wait.m_window) ) {
1940                         gtk_grab_add(g_wait.m_window);
1941                 }
1942                 ScreenUpdates_process();
1943         }
1944         g_wait_stack.push_back( message );
1945 }
1946
1947 void ScreenUpdates_Enable(){
1948         ASSERT_MESSAGE( !ScreenUpdates_Enabled(), "screen updates already enabled" );
1949         g_wait_stack.pop_back();
1950         if ( g_wait_stack.empty() ) {
1951                 EverySecondTimer_enable();
1952                 //gtk_widget_set_sensitive(MainFrame_getWindow(), TRUE);
1953
1954                 gtk_grab_remove( g_wait.m_window  );
1955                 destroy_floating_window( g_wait.m_window );
1956                 g_wait.m_window = ui::Window{ui::null};
1957
1958                 //gtk_window_present(MainFrame_getWindow());
1959         }
1960         else if ( g_wait.m_window.visible() ) {
1961                 g_wait.m_label.text(g_wait_stack.back().c_str());
1962                 ScreenUpdates_process();
1963         }
1964 }
1965
1966
1967 void GlobalCamera_UpdateWindow(){
1968         if ( g_pParentWnd != 0 ) {
1969                 CamWnd_Update( *g_pParentWnd->GetCamWnd() );
1970         }
1971 }
1972
1973 void XY_UpdateWindow( MainFrame& mainframe ){
1974         if ( mainframe.GetXYWnd() != 0 ) {
1975                 XYWnd_Update( *mainframe.GetXYWnd() );
1976         }
1977 }
1978
1979 void XZ_UpdateWindow( MainFrame& mainframe ){
1980         if ( mainframe.GetXZWnd() != 0 ) {
1981                 XYWnd_Update( *mainframe.GetXZWnd() );
1982         }
1983 }
1984
1985 void YZ_UpdateWindow( MainFrame& mainframe ){
1986         if ( mainframe.GetYZWnd() != 0 ) {
1987                 XYWnd_Update( *mainframe.GetYZWnd() );
1988         }
1989 }
1990
1991 void XY_UpdateAllWindows( MainFrame& mainframe ){
1992         XY_UpdateWindow( mainframe );
1993         XZ_UpdateWindow( mainframe );
1994         YZ_UpdateWindow( mainframe );
1995 }
1996
1997 void XY_UpdateAllWindows(){
1998         if ( g_pParentWnd != 0 ) {
1999                 XY_UpdateAllWindows( *g_pParentWnd );
2000         }
2001 }
2002
2003 void UpdateAllWindows(){
2004         XY_UpdateAllWindows();
2005         GlobalCamera_UpdateWindow();
2006 }
2007
2008
2009 void ModeChangeNotify(){
2010         SceneChangeNotify();
2011 }
2012
2013 void ClipperChangeNotify(){
2014         XY_UpdateAllWindows();
2015         GlobalCamera_UpdateWindow();
2016 }
2017
2018
2019 LatchedValue<int> g_Layout_viewStyle( 0, "Window Layout" );
2020 LatchedValue<bool> g_Layout_enableDetachableMenus( true, "Detachable Menus" );
2021 LatchedValue<bool> g_Layout_enablePatchToolbar( true, "Patch Toolbar" );
2022 LatchedValue<bool> g_Layout_enablePluginToolbar( true, "Plugin Toolbar" );
2023
2024
2025 ui::MenuItem create_file_menu(){
2026         // File menu
2027         auto file_menu_item = new_sub_menu_item_with_mnemonic( "_File" );
2028         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( file_menu_item ) );
2029         if ( g_Layout_enableDetachableMenus.m_value ) {
2030                 menu_tearoff( menu );
2031         }
2032
2033         create_menu_item_with_mnemonic( menu, "_New Map", "NewMap" );
2034         menu_separator( menu );
2035
2036 #if 0
2037         //++timo temporary experimental stuff for sleep mode..
2038         create_menu_item_with_mnemonic( menu, "_Sleep", "Sleep" );
2039         menu_separator( menu );
2040         // end experimental
2041 #endif
2042
2043         create_menu_item_with_mnemonic( menu, "_Open...", "OpenMap" );
2044
2045         create_menu_item_with_mnemonic( menu, "_Import...", "ImportMap" );
2046         create_menu_item_with_mnemonic( menu, "_Save", "SaveMap" );
2047         create_menu_item_with_mnemonic( menu, "Save _as...", "SaveMapAs" );
2048         create_menu_item_with_mnemonic( menu, "_Export selected...", "ExportSelected" );
2049         menu_separator( menu );
2050         create_menu_item_with_mnemonic( menu, "Save re_gion...", "SaveRegion" );
2051         menu_separator( menu );
2052         create_menu_item_with_mnemonic( menu, "_Refresh models", "RefreshReferences" );
2053         menu_separator( menu );
2054         create_menu_item_with_mnemonic( menu, "Pro_ject settings...", "ProjectSettings" );
2055         menu_separator( menu );
2056         create_menu_item_with_mnemonic( menu, "_Pointfile...", "TogglePointfile" );
2057         menu_separator( menu );
2058         MRU_constructMenu( menu );
2059         menu_separator( menu );
2060         create_menu_item_with_mnemonic( menu, "E_xit", "Exit" );
2061
2062         return file_menu_item;
2063 }
2064
2065 ui::MenuItem create_edit_menu(){
2066         // Edit menu
2067         auto edit_menu_item = new_sub_menu_item_with_mnemonic( "_Edit" );
2068         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( edit_menu_item ) );
2069         if ( g_Layout_enableDetachableMenus.m_value ) {
2070                 menu_tearoff( menu );
2071         }
2072         create_menu_item_with_mnemonic( menu, "_Undo", "Undo" );
2073         create_menu_item_with_mnemonic( menu, "_Redo", "Redo" );
2074         menu_separator( menu );
2075         create_menu_item_with_mnemonic( menu, "_Copy", "Copy" );
2076         create_menu_item_with_mnemonic( menu, "_Paste", "Paste" );
2077         create_menu_item_with_mnemonic( menu, "P_aste To Camera", "PasteToCamera" );
2078         menu_separator( menu );
2079         create_menu_item_with_mnemonic( menu, "_Duplicate", "CloneSelection" );
2080         create_menu_item_with_mnemonic( menu, "Duplicate, make uni_que", "CloneSelectionAndMakeUnique" );
2081         create_menu_item_with_mnemonic( menu, "D_elete", "DeleteSelection" );
2082         menu_separator( menu );
2083         create_menu_item_with_mnemonic( menu, "Pa_rent", "ParentSelection" );
2084         menu_separator( menu );
2085         create_menu_item_with_mnemonic( menu, "C_lear Selection", "UnSelectSelection" );
2086         create_menu_item_with_mnemonic( menu, "_Invert Selection", "InvertSelection" );
2087         create_menu_item_with_mnemonic( menu, "Select i_nside", "SelectInside" );
2088         create_menu_item_with_mnemonic( menu, "Select _touching", "SelectTouching" );
2089
2090         auto convert_menu = create_sub_menu_with_mnemonic( menu, "E_xpand Selection" );
2091         if ( g_Layout_enableDetachableMenus.m_value ) {
2092                 menu_tearoff( convert_menu );
2093         }
2094         create_menu_item_with_mnemonic( convert_menu, "To Whole _Entities", "ExpandSelectionToEntities" );
2095
2096         menu_separator( menu );
2097         create_menu_item_with_mnemonic( menu, "Pre_ferences...", "Preferences" );
2098
2099         return edit_menu_item;
2100 }
2101
2102 void fill_view_xy_top_menu( ui::Menu menu ){
2103         create_check_menu_item_with_mnemonic( menu, "XY (Top) View", "ToggleView" );
2104 }
2105
2106
2107 void fill_view_yz_side_menu( ui::Menu menu ){
2108         create_check_menu_item_with_mnemonic( menu, "YZ (Side) View", "ToggleSideView" );
2109 }
2110
2111
2112 void fill_view_xz_front_menu( ui::Menu menu ){
2113         create_check_menu_item_with_mnemonic( menu, "XZ (Front) View", "ToggleFrontView" );
2114 }
2115
2116
2117 ui::Widget g_toggle_z_item{ui::null};
2118 ui::Widget g_toggle_console_item{ui::null};
2119 ui::Widget g_toggle_entity_item{ui::null};
2120 ui::Widget g_toggle_entitylist_item{ui::null};
2121
2122 ui::MenuItem create_view_menu( MainFrame::EViewStyle style ){
2123         // View menu
2124         auto view_menu_item = new_sub_menu_item_with_mnemonic( "Vie_w" );
2125         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( view_menu_item ) );
2126         if ( g_Layout_enableDetachableMenus.m_value ) {
2127                 menu_tearoff( menu );
2128         }
2129
2130         if ( style == MainFrame::eFloating ) {
2131                 fill_view_camera_menu( menu );
2132                 fill_view_xy_top_menu( menu );
2133                 fill_view_yz_side_menu( menu );
2134                 fill_view_xz_front_menu( menu );
2135         }
2136         if ( style == MainFrame::eFloating || style == MainFrame::eSplit ) {
2137                 create_menu_item_with_mnemonic( menu, "Console View", "ToggleConsole" );
2138                 create_menu_item_with_mnemonic( menu, "Texture Browser", "ToggleTextures" );
2139                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ToggleEntityInspector" );
2140         }
2141         else
2142         {
2143                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ViewEntityInfo" );
2144         }
2145         create_menu_item_with_mnemonic( menu, "_Surface Inspector", "SurfaceInspector" );
2146         create_menu_item_with_mnemonic( menu, "Entity List", "EntityList" );
2147
2148         menu_separator( menu );
2149         {
2150                 auto camera_menu = create_sub_menu_with_mnemonic( menu, "Camera" );
2151                 if ( g_Layout_enableDetachableMenus.m_value ) {
2152                         menu_tearoff( camera_menu );
2153                 }
2154                 create_menu_item_with_mnemonic( camera_menu, "_Center", "CenterView" );
2155                 create_menu_item_with_mnemonic( camera_menu, "_Up Floor", "UpFloor" );
2156                 create_menu_item_with_mnemonic( camera_menu, "_Down Floor", "DownFloor" );
2157                 menu_separator( camera_menu );
2158                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane In", "CubicClipZoomIn" );
2159                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane Out", "CubicClipZoomOut" );
2160                 menu_separator( camera_menu );
2161                 create_menu_item_with_mnemonic( camera_menu, "Decrease FOV", "FOVDec" );
2162                 create_menu_item_with_mnemonic( camera_menu, "Increase FOV", "FOVInc" );
2163                 menu_separator( camera_menu );
2164                 create_menu_item_with_mnemonic( camera_menu, "Next leak spot", "NextLeakSpot" );
2165                 create_menu_item_with_mnemonic( camera_menu, "Previous leak spot", "PrevLeakSpot" );
2166                 menu_separator( camera_menu );
2167                 create_menu_item_with_mnemonic( camera_menu, "Look Through Selected", "LookThroughSelected" );
2168                 create_menu_item_with_mnemonic( camera_menu, "Look Through Camera", "LookThroughCamera" );
2169         }
2170         menu_separator( menu );
2171         {
2172                 auto orthographic_menu = create_sub_menu_with_mnemonic( menu, "Orthographic" );
2173                 if ( g_Layout_enableDetachableMenus.m_value ) {
2174                         menu_tearoff( orthographic_menu );
2175                 }
2176                 if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
2177                         create_menu_item_with_mnemonic( orthographic_menu, "_Next (XY, YZ, XY)", "NextView" );
2178                         create_menu_item_with_mnemonic( orthographic_menu, "XY (Top)", "ViewTop" );
2179                         create_menu_item_with_mnemonic( orthographic_menu, "YZ", "ViewSide" );
2180                         create_menu_item_with_mnemonic( orthographic_menu, "XZ", "ViewFront" );
2181                         menu_separator( orthographic_menu );
2182                 }
2183
2184                 create_menu_item_with_mnemonic( orthographic_menu, "_XY 100%", "Zoom100" );
2185                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _In", "ZoomIn" );
2186                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _Out", "ZoomOut" );
2187         }
2188
2189         menu_separator( menu );
2190
2191         {
2192                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Show" );
2193                 if ( g_Layout_enableDetachableMenus.m_value ) {
2194                         menu_tearoff( menu_in_menu );
2195                 }
2196                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Angles", "ShowAngles" );
2197                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Names", "ShowNames" );
2198                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Blocks", "ShowBlocks" );
2199                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show C_oordinates", "ShowCoordinates" );
2200                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Window Outline", "ShowWindowOutline" );
2201                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Axes", "ShowAxes" );
2202                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Workzone", "ShowWorkzone" );
2203                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Stats", "ShowStats" );
2204         }
2205
2206         {
2207                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Filter" );
2208                 if ( g_Layout_enableDetachableMenus.m_value ) {
2209                         menu_tearoff( menu_in_menu );
2210                 }
2211                 Filters_constructMenu( menu_in_menu );
2212         }
2213         menu_separator( menu );
2214         {
2215                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Hide/Show" );
2216                 if ( g_Layout_enableDetachableMenus.m_value ) {
2217                         menu_tearoff( menu_in_menu );
2218                 }
2219                 create_menu_item_with_mnemonic( menu_in_menu, "Hide Selected", "HideSelected" );
2220                 create_menu_item_with_mnemonic( menu_in_menu, "Show Hidden", "ShowHidden" );
2221         }
2222         menu_separator( menu );
2223         {
2224                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Region" );
2225                 if ( g_Layout_enableDetachableMenus.m_value ) {
2226                         menu_tearoff( menu_in_menu );
2227                 }
2228                 create_menu_item_with_mnemonic( menu_in_menu, "_Off", "RegionOff" );
2229                 create_menu_item_with_mnemonic( menu_in_menu, "_Set XY", "RegionSetXY" );
2230                 create_menu_item_with_mnemonic( menu_in_menu, "Set _Brush", "RegionSetBrush" );
2231                 create_menu_item_with_mnemonic( menu_in_menu, "Set Se_lected Brushes", "RegionSetSelection" );
2232         }
2233
2234         command_connect_accelerator( "CenterXYView" );
2235
2236         return view_menu_item;
2237 }
2238
2239 ui::MenuItem create_selection_menu(){
2240         // Selection menu
2241         auto selection_menu_item = new_sub_menu_item_with_mnemonic( "M_odify" );
2242         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( selection_menu_item ) );
2243         if ( g_Layout_enableDetachableMenus.m_value ) {
2244                 menu_tearoff( menu );
2245         }
2246
2247         {
2248                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Components" );
2249                 if ( g_Layout_enableDetachableMenus.m_value ) {
2250                         menu_tearoff( menu_in_menu );
2251                 }
2252                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Edges", "DragEdges" );
2253                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Vertices", "DragVertices" );
2254                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Faces", "DragFaces" );
2255         }
2256
2257         menu_separator( menu );
2258
2259         {
2260                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Nudge" );
2261                 if ( g_Layout_enableDetachableMenus.m_value ) {
2262                         menu_tearoff( menu_in_menu );
2263                 }
2264                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Left", "SelectNudgeLeft" );
2265                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Right", "SelectNudgeRight" );
2266                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Up", "SelectNudgeUp" );
2267                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Down", "SelectNudgeDown" );
2268         }
2269         {
2270                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Rotate" );
2271                 if ( g_Layout_enableDetachableMenus.m_value ) {
2272                         menu_tearoff( menu_in_menu );
2273                 }
2274                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate X", "RotateSelectionX" );
2275                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Y", "RotateSelectionY" );
2276                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Z", "RotateSelectionZ" );
2277         }
2278         {
2279                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Flip" );
2280                 if ( g_Layout_enableDetachableMenus.m_value ) {
2281                         menu_tearoff( menu_in_menu );
2282                 }
2283                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _X", "MirrorSelectionX" );
2284                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Y", "MirrorSelectionY" );
2285                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Z", "MirrorSelectionZ" );
2286         }
2287         menu_separator( menu );
2288         create_menu_item_with_mnemonic( menu, "Arbitrary rotation...", "ArbitraryRotation" );
2289         create_menu_item_with_mnemonic( menu, "Arbitrary scale...", "ArbitraryScale" );
2290
2291         return selection_menu_item;
2292 }
2293
2294 ui::MenuItem create_bsp_menu(){
2295         // BSP menu
2296         auto bsp_menu_item = new_sub_menu_item_with_mnemonic( "_Build" );
2297         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( bsp_menu_item ) );
2298
2299         if ( g_Layout_enableDetachableMenus.m_value ) {
2300                 menu_tearoff( menu );
2301         }
2302
2303         create_menu_item_with_mnemonic( menu, "Customize...", "BuildMenuCustomize" );
2304
2305         menu_separator( menu );
2306
2307         Build_constructMenu( menu );
2308
2309         g_bsp_menu = menu;
2310
2311         return bsp_menu_item;
2312 }
2313
2314 ui::MenuItem create_grid_menu(){
2315         // Grid menu
2316         auto grid_menu_item = new_sub_menu_item_with_mnemonic( "_Grid" );
2317         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( grid_menu_item ) );
2318         if ( g_Layout_enableDetachableMenus.m_value ) {
2319                 menu_tearoff( menu );
2320         }
2321
2322         Grid_constructMenu( menu );
2323
2324         return grid_menu_item;
2325 }
2326
2327 ui::MenuItem create_misc_menu(){
2328         // Misc menu
2329         auto misc_menu_item = new_sub_menu_item_with_mnemonic( "M_isc" );
2330         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( misc_menu_item ) );
2331         if ( g_Layout_enableDetachableMenus.m_value ) {
2332                 menu_tearoff( menu );
2333         }
2334
2335 #if 0
2336         create_menu_item_with_mnemonic( menu, "_Benchmark", makeCallbackF(GlobalCamera_Benchmark) );
2337 #endif
2338     menu.add(create_colours_menu());
2339
2340         create_menu_item_with_mnemonic( menu, "Find brush...", "FindBrush" );
2341         create_menu_item_with_mnemonic( menu, "Map Info...", "MapInfo" );
2342         // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394
2343 //  create_menu_item_with_mnemonic(menu, "_Print XY View", FreeCaller<void(), WXY_Print>());
2344         create_menu_item_with_mnemonic( menu, "_Background select", makeCallbackF(WXY_BackgroundSelect) );
2345         return misc_menu_item;
2346 }
2347
2348 ui::MenuItem create_entity_menu(){
2349         // Brush menu
2350         auto entity_menu_item = new_sub_menu_item_with_mnemonic( "E_ntity" );
2351         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( entity_menu_item ) );
2352         if ( g_Layout_enableDetachableMenus.m_value ) {
2353                 menu_tearoff( menu );
2354         }
2355
2356         Entity_constructMenu( menu );
2357
2358         return entity_menu_item;
2359 }
2360
2361 ui::MenuItem create_brush_menu(){
2362         // Brush menu
2363         auto brush_menu_item = new_sub_menu_item_with_mnemonic( "B_rush" );
2364         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( brush_menu_item ) );
2365         if ( g_Layout_enableDetachableMenus.m_value ) {
2366                 menu_tearoff( menu );
2367         }
2368
2369         Brush_constructMenu( menu );
2370
2371         return brush_menu_item;
2372 }
2373
2374 ui::MenuItem create_patch_menu(){
2375         // Curve menu
2376         auto patch_menu_item = new_sub_menu_item_with_mnemonic( "_Curve" );
2377         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( patch_menu_item ) );
2378         if ( g_Layout_enableDetachableMenus.m_value ) {
2379                 menu_tearoff( menu );
2380         }
2381
2382         Patch_constructMenu( menu );
2383
2384         return patch_menu_item;
2385 }
2386
2387 ui::MenuItem create_help_menu(){
2388         // Help menu
2389         auto help_menu_item = new_sub_menu_item_with_mnemonic( "_Help" );
2390         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( help_menu_item ) );
2391         if ( g_Layout_enableDetachableMenus.m_value ) {
2392                 menu_tearoff( menu );
2393         }
2394
2395         create_menu_item_with_mnemonic( menu, "Manual", "OpenManual" );
2396
2397         // this creates all the per-game drop downs for the game pack helps
2398         // it will take care of hooking the Sys_OpenURL calls etc.
2399         create_game_help_menu( menu );
2400
2401         create_menu_item_with_mnemonic( menu, "Bug report", makeCallbackF(OpenBugReportURL) );
2402         create_menu_item_with_mnemonic( menu, "Shortcuts list", makeCallbackF(DoCommandListDlg) );
2403         create_menu_item_with_mnemonic( menu, "_About...", makeCallbackF(DoAbout) );
2404
2405         return help_menu_item;
2406 }
2407
2408 ui::MenuBar create_main_menu( MainFrame::EViewStyle style ){
2409         auto menu_bar = ui::MenuBar::from( gtk_menu_bar_new() );
2410         menu_bar.show();
2411
2412         menu_bar.add(create_file_menu());
2413         menu_bar.add(create_edit_menu());
2414         menu_bar.add(create_view_menu(style));
2415         menu_bar.add(create_selection_menu());
2416         menu_bar.add(create_bsp_menu());
2417         menu_bar.add(create_grid_menu());
2418         menu_bar.add(create_misc_menu());
2419         menu_bar.add(create_entity_menu());
2420         menu_bar.add(create_brush_menu());
2421         menu_bar.add(create_patch_menu());
2422         menu_bar.add(create_plugins_menu());
2423         menu_bar.add(create_help_menu());
2424
2425         return menu_bar;
2426 }
2427
2428
2429 void PatchInspector_registerShortcuts(){
2430         command_connect_accelerator( "PatchInspector" );
2431 }
2432
2433 void Patch_registerShortcuts(){
2434         command_connect_accelerator( "InvertCurveTextureX" );
2435         command_connect_accelerator( "InvertCurveTextureY" );
2436         command_connect_accelerator( "PatchInsertInsertColumn" );
2437         command_connect_accelerator( "PatchInsertInsertRow" );
2438         command_connect_accelerator( "PatchDeleteLastColumn" );
2439         command_connect_accelerator( "PatchDeleteLastRow" );
2440         command_connect_accelerator( "NaturalizePatch" );
2441         //command_connect_accelerator("CapCurrentCurve");
2442 }
2443
2444 void Manipulators_registerShortcuts(){
2445         toggle_add_accelerator( "MouseRotate" );
2446         toggle_add_accelerator( "MouseTranslate" );
2447         toggle_add_accelerator( "MouseScale" );
2448         toggle_add_accelerator( "MouseDrag" );
2449         toggle_add_accelerator( "ToggleClipper" );
2450 }
2451
2452 void TexdefNudge_registerShortcuts(){
2453         command_connect_accelerator( "TexRotateClock" );
2454         command_connect_accelerator( "TexRotateCounter" );
2455         command_connect_accelerator( "TexScaleUp" );
2456         command_connect_accelerator( "TexScaleDown" );
2457         command_connect_accelerator( "TexScaleLeft" );
2458         command_connect_accelerator( "TexScaleRight" );
2459         command_connect_accelerator( "TexShiftUp" );
2460         command_connect_accelerator( "TexShiftDown" );
2461         command_connect_accelerator( "TexShiftLeft" );
2462         command_connect_accelerator( "TexShiftRight" );
2463 }
2464
2465 void SelectNudge_registerShortcuts(){
2466         command_connect_accelerator( "MoveSelectionDOWN" );
2467         command_connect_accelerator( "MoveSelectionUP" );
2468         //command_connect_accelerator("SelectNudgeLeft");
2469         //command_connect_accelerator("SelectNudgeRight");
2470         //command_connect_accelerator("SelectNudgeUp");
2471         //command_connect_accelerator("SelectNudgeDown");
2472 }
2473
2474 void SnapToGrid_registerShortcuts(){
2475         command_connect_accelerator( "SnapToGrid" );
2476 }
2477
2478 void SelectByType_registerShortcuts(){
2479         command_connect_accelerator( "SelectAllOfType" );
2480 }
2481
2482 void SurfaceInspector_registerShortcuts(){
2483         command_connect_accelerator( "FitTexture" );
2484 }
2485
2486
2487 void register_shortcuts(){
2488         PatchInspector_registerShortcuts();
2489         Patch_registerShortcuts();
2490         Grid_registerShortcuts();
2491         XYWnd_registerShortcuts();
2492         CamWnd_registerShortcuts();
2493         Manipulators_registerShortcuts();
2494         SurfaceInspector_registerShortcuts();
2495         TexdefNudge_registerShortcuts();
2496         SelectNudge_registerShortcuts();
2497         SnapToGrid_registerShortcuts();
2498         SelectByType_registerShortcuts();
2499 }
2500
2501 void File_constructToolbar( ui::Toolbar toolbar ){
2502         toolbar_append_button( toolbar, "Open an existing map (CTRL + O)", "file_open.png", "OpenMap" );
2503         toolbar_append_button( toolbar, "Save the active map (CTRL + S)", "file_save.png", "SaveMap" );
2504 }
2505
2506 void UndoRedo_constructToolbar( ui::Toolbar toolbar ){
2507         toolbar_append_button( toolbar, "Undo (CTRL + Z)", "undo.png", "Undo" );
2508         toolbar_append_button( toolbar, "Redo (CTRL + Y)", "redo.png", "Redo" );
2509 }
2510
2511 void RotateFlip_constructToolbar( ui::Toolbar toolbar ){
2512         toolbar_append_button( toolbar, "x-axis Flip", "brush_flipx.png", "MirrorSelectionX" );
2513         toolbar_append_button( toolbar, "x-axis Rotate", "brush_rotatex.png", "RotateSelectionX" );
2514         toolbar_append_button( toolbar, "y-axis Flip", "brush_flipy.png", "MirrorSelectionY" );
2515         toolbar_append_button( toolbar, "y-axis Rotate", "brush_rotatey.png", "RotateSelectionY" );
2516         toolbar_append_button( toolbar, "z-axis Flip", "brush_flipz.png", "MirrorSelectionZ" );
2517         toolbar_append_button( toolbar, "z-axis Rotate", "brush_rotatez.png", "RotateSelectionZ" );
2518 }
2519
2520 void Select_constructToolbar( ui::Toolbar toolbar ){
2521         toolbar_append_button( toolbar, "Select touching", "selection_selecttouching.png", "SelectTouching" );
2522         toolbar_append_button( toolbar, "Select inside", "selection_selectinside.png", "SelectInside" );
2523 }
2524
2525 void CSG_constructToolbar( ui::Toolbar toolbar ){
2526         toolbar_append_button( toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.png", "CSGSubtract" );
2527         toolbar_append_button( toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.png", "CSGMerge" );
2528         toolbar_append_button( toolbar, "Make Hollow", "selection_makehollow.png", "CSGMakeHollow" );
2529         toolbar_append_button( toolbar, "Make Room", "selection_makeroom.png", "CSGMakeRoom" );
2530 }
2531
2532 void ComponentModes_constructToolbar( ui::Toolbar toolbar ){
2533         toolbar_append_toggle_button( toolbar, "Select Vertices (V)", "modify_vertices.png", "DragVertices" );
2534         toolbar_append_toggle_button( toolbar, "Select Edges (E)", "modify_edges.png", "DragEdges" );
2535         toolbar_append_toggle_button( toolbar, "Select Faces (F)", "modify_faces.png", "DragFaces" );
2536 }
2537
2538 void Clipper_constructToolbar( ui::Toolbar toolbar ){
2539
2540         toolbar_append_toggle_button( toolbar, "Clipper (X)", "view_clipper.png", "ToggleClipper" );
2541 }
2542
2543 void XYWnd_constructToolbar( ui::Toolbar toolbar ){
2544         toolbar_append_button( toolbar, "Change views", "view_change.png", "NextView" );
2545 }
2546
2547 void Manipulators_constructToolbar( ui::Toolbar toolbar ){
2548         toolbar_append_toggle_button( toolbar, "Translate (W)", "select_mousetranslate.png", "MouseTranslate" );
2549         toolbar_append_toggle_button( toolbar, "Rotate (R)", "select_mouserotate.png", "MouseRotate" );
2550         toolbar_append_toggle_button( toolbar, "Scale", "select_mousescale.png", "MouseScale" );
2551         toolbar_append_toggle_button( toolbar, "Resize (Q)", "select_mouseresize.png", "MouseDrag" );
2552
2553         Clipper_constructToolbar( toolbar );
2554 }
2555
2556 ui::Toolbar create_main_toolbar( MainFrame::EViewStyle style ){
2557         auto toolbar = ui::Toolbar::from( gtk_toolbar_new() );
2558         gtk_orientable_set_orientation( GTK_ORIENTABLE(toolbar), GTK_ORIENTATION_HORIZONTAL );
2559         gtk_toolbar_set_style( toolbar, GTK_TOOLBAR_ICONS );
2560
2561         toolbar.show();
2562
2563         auto space = [&]() {
2564                 auto btn = ui::ToolItem::from(gtk_separator_tool_item_new());
2565                 btn.show();
2566                 toolbar.add(btn);
2567         };
2568
2569         File_constructToolbar( toolbar );
2570
2571         space();
2572
2573         UndoRedo_constructToolbar( toolbar );
2574
2575         space();
2576
2577         RotateFlip_constructToolbar( toolbar );
2578
2579         space();
2580
2581         Select_constructToolbar( toolbar );
2582
2583         space();
2584
2585         CSG_constructToolbar( toolbar );
2586
2587         space();
2588
2589         ComponentModes_constructToolbar( toolbar );
2590
2591         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
2592                 space();
2593
2594                 XYWnd_constructToolbar( toolbar );
2595         }
2596
2597         space();
2598
2599         CamWnd_constructToolbar( toolbar );
2600
2601         space();
2602
2603         Manipulators_constructToolbar( toolbar );
2604
2605         if ( g_Layout_enablePatchToolbar.m_value ) {
2606                 space();
2607
2608                 Patch_constructToolbar( toolbar );
2609         }
2610
2611         space();
2612
2613         toolbar_append_toggle_button( toolbar, "Texture Lock (SHIFT +T)", "texture_lock.png", "TogTexLock" );
2614
2615         space();
2616
2617         /*auto g_view_entities_button =*/ toolbar_append_button( toolbar, "Entities (N)", "entities.png", "ToggleEntityInspector" );
2618         auto g_view_console_button = toolbar_append_button( toolbar, "Console (O)", "console.png", "ToggleConsole" );
2619         auto g_view_textures_button = toolbar_append_button( toolbar, "Texture Browser (T)", "texture_browser.png", "ToggleTextures" );
2620         // TODO: call light inspector
2621         //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.png", "ToggleLightInspector");
2622
2623         space();
2624         /*auto g_refresh_models_button =*/ toolbar_append_button( toolbar, "Refresh Models", "refresh_models.png", "RefreshReferences" );
2625
2626
2627         // disable the console and texture button in the regular layouts
2628         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft ) {
2629                 gtk_widget_set_sensitive( g_view_console_button , FALSE );
2630                 gtk_widget_set_sensitive( g_view_textures_button , FALSE );
2631         }
2632
2633         return toolbar;
2634 }
2635
2636 ui::Widget create_main_statusbar( ui::Widget pStatusLabel[c_count_status] ){
2637         auto table = ui::Table( 1, c_count_status, FALSE );
2638         table.show();
2639
2640         {
2641                 auto label = ui::Label( "Label" );
2642                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
2643                 gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
2644                 label.show();
2645                 table.attach(label, {0, 1, 0, 1});
2646                 pStatusLabel[c_command_status] = ui::Widget(label );
2647         }
2648
2649         for (unsigned int i = 1; (int) i < c_count_status; ++i)
2650         {
2651                 auto frame = ui::Frame();
2652                 frame.show();
2653                 table.attach(frame, {i, i + 1, 0, 1});
2654                 gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN );
2655
2656                 auto label = ui::Label( "Label" );
2657                 gtk_label_set_ellipsize( label, PANGO_ELLIPSIZE_END );
2658                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
2659                 gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
2660                 label.show();
2661                 frame.add(label);
2662                 pStatusLabel[i] = ui::Widget(label );
2663         }
2664
2665         return ui::Widget(table );
2666 }
2667
2668 #if 0
2669
2670
2671 WidgetFocusPrinter g_mainframeWidgetFocusPrinter( "mainframe" );
2672
2673 class WindowFocusPrinter
2674 {
2675 const char* m_name;
2676
2677 static gboolean frame_event( ui::Widget widget, GdkEvent* event, WindowFocusPrinter* self ){
2678         globalOutputStream() << self->m_name << " frame_event\n";
2679         return FALSE;
2680 }
2681 static gboolean keys_changed( ui::Widget widget, WindowFocusPrinter* self ){
2682         globalOutputStream() << self->m_name << " keys_changed\n";
2683         return FALSE;
2684 }
2685 static gboolean notify( ui::Window window, gpointer dummy, WindowFocusPrinter* self ){
2686         if ( gtk_window_is_active( window ) ) {
2687                 globalOutputStream() << self->m_name << " takes toplevel focus\n";
2688         }
2689         else
2690         {
2691                 globalOutputStream() << self->m_name << " loses toplevel focus\n";
2692         }
2693         return FALSE;
2694 }
2695 public:
2696 WindowFocusPrinter( const char* name ) : m_name( name ){
2697 }
2698 void connect( ui::Window toplevel_window ){
2699         toplevel_window.connect( "notify::has_toplevel_focus", G_CALLBACK( notify ), this );
2700         toplevel_window.connect( "notify::is_active", G_CALLBACK( notify ), this );
2701         toplevel_window.connect( "keys_changed", G_CALLBACK( keys_changed ), this );
2702         toplevel_window.connect( "frame_event", G_CALLBACK( frame_event ), this );
2703 }
2704 };
2705
2706 WindowFocusPrinter g_mainframeFocusPrinter( "mainframe" );
2707
2708 #endif
2709
2710 class MainWindowActive
2711 {
2712 static gboolean notify( ui::Window window, gpointer dummy, MainWindowActive* self ){
2713         if ( g_wait.m_window && gtk_window_is_active( window ) && !g_wait.m_window.visible() ) {
2714                 g_wait.m_window.show();
2715         }
2716
2717         return FALSE;
2718 }
2719
2720 public:
2721 void connect( ui::Window toplevel_window ){
2722         toplevel_window.connect( "notify::is-active", G_CALLBACK( notify ), this );
2723 }
2724 };
2725
2726 MainWindowActive g_MainWindowActive;
2727
2728 SignalHandlerId XYWindowDestroyed_connect( const SignalHandler& handler ){
2729         return g_pParentWnd->GetXYWnd()->onDestroyed.connectFirst( handler );
2730 }
2731
2732 void XYWindowDestroyed_disconnect( SignalHandlerId id ){
2733         g_pParentWnd->GetXYWnd()->onDestroyed.disconnect( id );
2734 }
2735
2736 MouseEventHandlerId XYWindowMouseDown_connect( const MouseEventHandler& handler ){
2737         return g_pParentWnd->GetXYWnd()->onMouseDown.connectFirst( handler );
2738 }
2739
2740 void XYWindowMouseDown_disconnect( MouseEventHandlerId id ){
2741         g_pParentWnd->GetXYWnd()->onMouseDown.disconnect( id );
2742 }
2743
2744 // =============================================================================
2745 // MainFrame class
2746
2747 MainFrame* g_pParentWnd = 0;
2748
2749 ui::Window MainFrame_getWindow()
2750 {
2751         return g_pParentWnd ? g_pParentWnd->m_window : ui::Window{ui::null};
2752 }
2753
2754 std::vector<ui::Widget> g_floating_windows;
2755
2756 MainFrame::MainFrame() : m_idleRedrawStatusText( RedrawStatusTextCaller( *this ) ){
2757         m_pXYWnd = 0;
2758         m_pCamWnd = 0;
2759         m_pZWnd = 0;
2760         m_pYZWnd = 0;
2761         m_pXZWnd = 0;
2762         m_pActiveXY = 0;
2763
2764         for (auto &n : m_pStatusLabel) {
2765         n = NULL;
2766         }
2767
2768         m_bSleeping = false;
2769
2770         Create();
2771 }
2772
2773 MainFrame::~MainFrame(){
2774         SaveWindowInfo();
2775
2776         m_window.hide();
2777
2778         Shutdown();
2779
2780         for ( std::vector<ui::Widget>::iterator i = g_floating_windows.begin(); i != g_floating_windows.end(); ++i )
2781         {
2782 #ifndef WORKAROUND_MACOS_GTK2_DESTROY
2783                 i->destroy();
2784 #endif
2785         }
2786
2787 #ifndef WORKAROUND_MACOS_GTK2_DESTROY
2788         m_window.destroy();
2789 #endif
2790 }
2791
2792 void MainFrame::SetActiveXY( XYWnd* p ){
2793         if ( m_pActiveXY ) {
2794                 m_pActiveXY->SetActive( false );
2795         }
2796
2797         m_pActiveXY = p;
2798
2799         if ( m_pActiveXY ) {
2800                 m_pActiveXY->SetActive( true );
2801         }
2802
2803 }
2804
2805 void MainFrame::ReleaseContexts(){
2806 #if 0
2807         if ( m_pXYWnd ) {
2808                 m_pXYWnd->DestroyContext();
2809         }
2810         if ( m_pYZWnd ) {
2811                 m_pYZWnd->DestroyContext();
2812         }
2813         if ( m_pXZWnd ) {
2814                 m_pXZWnd->DestroyContext();
2815         }
2816         if ( m_pCamWnd ) {
2817                 m_pCamWnd->DestroyContext();
2818         }
2819         if ( m_pTexWnd ) {
2820                 m_pTexWnd->DestroyContext();
2821         }
2822         if ( m_pZWnd ) {
2823                 m_pZWnd->DestroyContext();
2824         }
2825 #endif
2826 }
2827
2828 void MainFrame::CreateContexts(){
2829 #if 0
2830         if ( m_pCamWnd ) {
2831                 m_pCamWnd->CreateContext();
2832         }
2833         if ( m_pXYWnd ) {
2834                 m_pXYWnd->CreateContext();
2835         }
2836         if ( m_pYZWnd ) {
2837                 m_pYZWnd->CreateContext();
2838         }
2839         if ( m_pXZWnd ) {
2840                 m_pXZWnd->CreateContext();
2841         }
2842         if ( m_pTexWnd ) {
2843                 m_pTexWnd->CreateContext();
2844         }
2845         if ( m_pZWnd ) {
2846                 m_pZWnd->CreateContext();
2847         }
2848 #endif
2849 }
2850
2851 #if GDEF_DEBUG
2852 //#define DBG_SLEEP
2853 #endif
2854
2855 void MainFrame::OnSleep(){
2856 #if 0
2857         m_bSleeping ^= 1;
2858         if ( m_bSleeping ) {
2859                 // useful when trying to debug crashes in the sleep code
2860                 globalOutputStream() << "Going into sleep mode..\n";
2861
2862                 globalOutputStream() << "Dispatching sleep msg...";
2863                 DispatchRadiantMsg( RADIANT_SLEEP );
2864                 globalOutputStream() << "Done.\n";
2865
2866                 gtk_window_iconify( m_window );
2867                 GlobalSelectionSystem().setSelectedAll( false );
2868
2869                 GlobalShaderCache().unrealise();
2870                 Shaders_Free();
2871                 GlobalOpenGL_debugAssertNoErrors();
2872                 ScreenUpdates_Disable();
2873
2874                 // release contexts
2875                 globalOutputStream() << "Releasing contexts...";
2876                 ReleaseContexts();
2877                 globalOutputStream() << "Done.\n";
2878         }
2879         else
2880         {
2881                 globalOutputStream() << "Waking up\n";
2882
2883                 gtk_window_deiconify( m_window );
2884
2885                 // create contexts
2886                 globalOutputStream() << "Creating contexts...";
2887                 CreateContexts();
2888                 globalOutputStream() << "Done.\n";
2889
2890                 globalOutputStream() << "Making current on camera...";
2891                 m_pCamWnd->MakeCurrent();
2892                 globalOutputStream() << "Done.\n";
2893
2894                 globalOutputStream() << "Reloading shaders...";
2895                 Shaders_Load();
2896                 GlobalShaderCache().realise();
2897                 globalOutputStream() << "Done.\n";
2898
2899                 ScreenUpdates_Enable();
2900
2901                 globalOutputStream() << "Dispatching wake msg...";
2902                 DispatchRadiantMsg( RADIANT_WAKEUP );
2903                 globalOutputStream() << "Done\n";
2904         }
2905 #endif
2906 }
2907
2908
2909 ui::Window create_splash(){
2910         auto window = ui::Window( ui::window_type::TOP );
2911         gtk_window_set_decorated(window, false);
2912         gtk_window_set_resizable(window, false);
2913         gtk_window_set_modal(window, true);
2914         gtk_window_set_default_size( window, -1, -1 );
2915         gtk_window_set_position( window, GTK_WIN_POS_CENTER );
2916         gtk_container_set_border_width(window, 0);
2917
2918         auto image = new_local_image( "splash.png" );
2919         image.show();
2920         window.add(image);
2921
2922         window.dimensions(-1, -1);
2923         window.show();
2924
2925         return window;
2926 }
2927
2928 static ui::Window splash_screen{ui::null};
2929
2930 void show_splash(){
2931         splash_screen = create_splash();
2932
2933         ui::process();
2934 }
2935
2936 void hide_splash(){
2937         splash_screen.destroy();
2938 }
2939
2940 WindowPositionTracker g_posCamWnd;
2941 WindowPositionTracker g_posXYWnd;
2942 WindowPositionTracker g_posXZWnd;
2943 WindowPositionTracker g_posYZWnd;
2944
2945 static gint mainframe_delete( ui::Widget widget, GdkEvent *event, gpointer data ){
2946         if ( ConfirmModified( "Exit " RADIANT_NAME ) ) {
2947                 gtk_main_quit();
2948         }
2949
2950         return TRUE;
2951 }
2952
2953 void MainFrame::Create(){
2954         ui::Window window = ui::Window( ui::window_type::TOP );
2955
2956         GlobalWindowObservers_connectTopLevel( window );
2957
2958         gtk_window_set_transient_for( splash_screen, window );
2959
2960 #if !GDEF_OS_WINDOWS
2961         {
2962                 GdkPixbuf* pixbuf = pixbuf_new_from_file_with_mask( "bitmaps/icon.png" );
2963                 if ( pixbuf != 0 ) {
2964                         gtk_window_set_icon( window, pixbuf );
2965                         g_object_unref( pixbuf );
2966                 }
2967         }
2968 #endif
2969
2970         gtk_widget_add_events( window , GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK );
2971         window.connect( "delete_event", G_CALLBACK( mainframe_delete ), this );
2972
2973         m_position_tracker.connect( window );
2974
2975 #if 0
2976         g_mainframeWidgetFocusPrinter.connect( window );
2977         g_mainframeFocusPrinter.connect( window );
2978 #endif
2979
2980         g_MainWindowActive.connect( window );
2981
2982         GetPlugInMgr().Init( window );
2983
2984         auto vbox = ui::VBox( FALSE, 0 );
2985         window.add(vbox);
2986         vbox.show();
2987
2988         global_accel_connect_window( window );
2989
2990         m_nCurrentStyle = (EViewStyle)g_Layout_viewStyle.m_value;
2991
2992         register_shortcuts();
2993
2994     auto main_menu = create_main_menu( CurrentStyle() );
2995         vbox.pack_start( main_menu, FALSE, FALSE, 0 );
2996
2997     auto main_toolbar = create_main_toolbar( CurrentStyle() );
2998         vbox.pack_start( main_toolbar, FALSE, FALSE, 0 );
2999
3000         auto plugin_toolbar = create_plugin_toolbar();
3001         if ( !g_Layout_enablePluginToolbar.m_value ) {
3002                 plugin_toolbar.hide();
3003         }
3004         vbox.pack_start( plugin_toolbar, FALSE, FALSE, 0 );
3005
3006         ui::Widget main_statusbar = create_main_statusbar(reinterpret_cast<ui::Widget *>(m_pStatusLabel));
3007         vbox.pack_end(main_statusbar, FALSE, TRUE, 2);
3008
3009         GroupDialog_constructWindow( window );
3010         g_page_entity = GroupDialog_addPage( "Entities", EntityInspector_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Entities" ) );
3011
3012         if ( FloatingGroupDialog() ) {
3013                 g_page_console = GroupDialog_addPage( "Console", Console_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Console" ) );
3014         }
3015
3016 #if GDEF_OS_WINDOWS
3017         if ( g_multimon_globals.m_bStartOnPrimMon ) {
3018                 PositionWindowOnPrimaryScreen( g_layout_globals.m_position );
3019                 window_set_position( window, g_layout_globals.m_position );
3020         }
3021         else
3022 #endif
3023         if ( g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED ) {
3024                 gtk_window_maximize( window );
3025                 WindowPosition default_position( -1, -1, 640, 480 );
3026                 window_set_position( window, default_position );
3027         }
3028         else
3029         {
3030                 window_set_position( window, g_layout_globals.m_position );
3031         }
3032
3033         m_window = window;
3034
3035         window.show();
3036
3037         if ( CurrentStyle() == eRegular || CurrentStyle() == eRegularLeft ) {
3038                 {
3039                         ui::Widget vsplit = ui::VPaned(ui::New);
3040                         m_vSplit = vsplit;
3041                         vbox.pack_start( vsplit, TRUE, TRUE, 0 );
3042                         vsplit.show();
3043
3044                         // console
3045                         ui::Widget console_window = Console_constructWindow( window );
3046                         gtk_paned_pack2( GTK_PANED( vsplit ), console_window, FALSE, TRUE );
3047
3048                         {
3049                                 ui::Widget hsplit = ui::HPaned(ui::New);
3050                                 hsplit.show();
3051                                 m_hSplit = hsplit;
3052                                 gtk_paned_add1( GTK_PANED( vsplit ), hsplit );
3053
3054                                 // xy
3055                                 m_pXYWnd = new XYWnd();
3056                                 m_pXYWnd->SetViewType( XY );
3057                                 ui::Widget xy_window = ui::Widget(create_framed_widget( m_pXYWnd->GetWidget( ) ));
3058
3059                                 {
3060                                         ui::Widget vsplit2 = ui::VPaned(ui::New);
3061                                         vsplit2.show();
3062                                         m_vSplit2 = vsplit2;
3063
3064                                         if ( CurrentStyle() == eRegular ) {
3065                                                 gtk_paned_add1( GTK_PANED( hsplit ), xy_window );
3066                                                 gtk_paned_add2( GTK_PANED( hsplit ), vsplit2 );
3067                                         }
3068                                         else
3069                                         {
3070                                                 gtk_paned_add1( GTK_PANED( hsplit ), vsplit2 );
3071                                                 gtk_paned_add2( GTK_PANED( hsplit ), xy_window );
3072                                         }
3073
3074
3075                                         // camera
3076                                         m_pCamWnd = NewCamWnd();
3077                                         GlobalCamera_setCamWnd( *m_pCamWnd );
3078                                         CamWnd_setParent( *m_pCamWnd, window );
3079                                         auto camera_window = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
3080
3081                                         gtk_paned_add1( GTK_PANED( vsplit2 ), camera_window  );
3082
3083                                         // textures
3084                                         auto texture_window = create_framed_widget( TextureBrowser_constructWindow( window ) );
3085
3086                                         gtk_paned_add2( GTK_PANED( vsplit2 ), texture_window  );
3087                                 }
3088                         }
3089                 }
3090
3091                 gtk_paned_set_position( GTK_PANED( m_vSplit ), g_layout_globals.nXYHeight );
3092
3093                 if ( CurrentStyle() == eRegular ) {
3094                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nXYWidth );
3095                 }
3096                 else
3097                 {
3098                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nCamWidth );
3099                 }
3100
3101                 gtk_paned_set_position( GTK_PANED( m_vSplit2 ), g_layout_globals.nCamHeight );
3102         }
3103         else if ( CurrentStyle() == eFloating ) {
3104                 {
3105                         ui::Window window = ui::Window(create_persistent_floating_window( "Camera", m_window ));
3106                         global_accel_connect_window( window );
3107                         g_posCamWnd.connect( window );
3108
3109                         window.show();
3110
3111                         m_pCamWnd = NewCamWnd();
3112                         GlobalCamera_setCamWnd( *m_pCamWnd );
3113
3114                         {
3115                                 auto frame = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
3116                                 window.add(frame);
3117                         }
3118                         CamWnd_setParent( *m_pCamWnd, window );
3119
3120                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, CamWnd_getWidget( *m_pCamWnd ) );
3121
3122                         g_floating_windows.push_back( window );
3123                 }
3124
3125                 {
3126                         ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( XY ), m_window ));
3127                         global_accel_connect_window( window );
3128                         g_posXYWnd.connect( window );
3129
3130                         m_pXYWnd = new XYWnd();
3131                         m_pXYWnd->m_parent = window;
3132                         m_pXYWnd->SetViewType( XY );
3133
3134
3135                         {
3136                                 auto frame = create_framed_widget( m_pXYWnd->GetWidget() );
3137                                 window.add(frame);
3138                         }
3139                         XY_Top_Shown_Construct( window );
3140
3141                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, m_pXYWnd->GetWidget() );
3142
3143                         g_floating_windows.push_back( window );
3144                 }
3145
3146                 {
3147                         ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( XZ ), m_window ));
3148                         global_accel_connect_window( window );
3149                         g_posXZWnd.connect( window );
3150
3151                         m_pXZWnd = new XYWnd();
3152                         m_pXZWnd->m_parent = window;
3153                         m_pXZWnd->SetViewType( XZ );
3154
3155                         {
3156                                 auto frame = create_framed_widget( m_pXZWnd->GetWidget() );
3157                                 window.add(frame);
3158                         }
3159
3160                         XZ_Front_Shown_Construct( window );
3161
3162                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, m_pXZWnd->GetWidget() );
3163
3164                         g_floating_windows.push_back( window );
3165                 }
3166
3167                 {
3168                         ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( YZ ), m_window ));
3169                         global_accel_connect_window( window );
3170                         g_posYZWnd.connect( window );
3171
3172                         m_pYZWnd = new XYWnd();
3173                         m_pYZWnd->m_parent = window;
3174                         m_pYZWnd->SetViewType( YZ );
3175
3176                         {
3177                                 auto frame = create_framed_widget( m_pYZWnd->GetWidget() );
3178                                 window.add(frame);
3179                         }
3180
3181                         YZ_Side_Shown_Construct( window );
3182
3183                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, m_pYZWnd->GetWidget() );
3184
3185                         g_floating_windows.push_back( window );
3186                 }
3187
3188                 {
3189                         auto frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
3190                         g_page_textures = GroupDialog_addPage( "Textures", frame, TextureBrowserExportTitleCaller() );
3191
3192                         WORKAROUND_GOBJECT_SET_GLWIDGET( GroupDialog_getWindow(), TextureBrowser_getGLWidget() );
3193                 }
3194
3195                 GroupDialog_show();
3196         }
3197         else // 4 way
3198         {
3199                 m_pCamWnd = NewCamWnd();
3200                 GlobalCamera_setCamWnd( *m_pCamWnd );
3201                 CamWnd_setParent( *m_pCamWnd, window );
3202
3203                 ui::Widget camera = CamWnd_getWidget( *m_pCamWnd );
3204
3205                 m_pYZWnd = new XYWnd();
3206                 m_pYZWnd->SetViewType( YZ );
3207
3208                 ui::Widget yz = m_pYZWnd->GetWidget();
3209
3210                 m_pXYWnd = new XYWnd();
3211                 m_pXYWnd->SetViewType( XY );
3212
3213                 ui::Widget xy = m_pXYWnd->GetWidget();
3214
3215                 m_pXZWnd = new XYWnd();
3216                 m_pXZWnd->SetViewType( XZ );
3217
3218                 ui::Widget xz = m_pXZWnd->GetWidget();
3219
3220         auto split = create_split_views( camera, yz, xy, xz );
3221                 vbox.pack_start( split, TRUE, TRUE, 0 );
3222
3223                 {
3224             auto frame = create_framed_widget( TextureBrowser_constructWindow( window ) );
3225                         g_page_textures = GroupDialog_addPage( "Textures", frame, TextureBrowserExportTitleCaller() );
3226
3227                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, TextureBrowser_getGLWidget() );
3228                 }
3229         }
3230
3231         EntityList_constructWindow( window );
3232         PreferencesDialog_constructWindow( window );
3233         FindTextureDialog_constructWindow( window );
3234         SurfaceInspector_constructWindow( window );
3235         PatchInspector_constructWindow( window );
3236
3237         SetActiveXY( m_pXYWnd );
3238
3239         AddGridChangeCallback( SetGridStatusCaller( *this ) );
3240         AddGridChangeCallback( ReferenceCaller<MainFrame, void(), XY_UpdateAllWindows>( *this ) );
3241
3242         g_defaultToolMode = DragMode;
3243         g_defaultToolMode();
3244         SetStatusText( m_command_status, c_TranslateMode_status );
3245
3246         EverySecondTimer_enable();
3247
3248         //GlobalShortcuts_reportUnregistered();
3249 }
3250
3251 void MainFrame::SaveWindowInfo(){
3252         if ( !FloatingGroupDialog() ) {
3253                 g_layout_globals.nXYHeight = gtk_paned_get_position( GTK_PANED( m_vSplit ) );
3254
3255                 if ( CurrentStyle() != eRegular ) {
3256                         g_layout_globals.nCamWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
3257                 }
3258                 else
3259                 {
3260                         g_layout_globals.nXYWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
3261                 }
3262
3263                 g_layout_globals.nCamHeight = gtk_paned_get_position( GTK_PANED( m_vSplit2 ) );
3264         }
3265
3266         g_layout_globals.m_position = m_position_tracker.getPosition();
3267
3268         g_layout_globals.nState = gdk_window_get_state( gtk_widget_get_window(m_window ) );
3269 }
3270
3271 void MainFrame::Shutdown(){
3272         EverySecondTimer_disable();
3273
3274         EntityList_destroyWindow();
3275
3276         delete m_pXYWnd;
3277         m_pXYWnd = 0;
3278         delete m_pYZWnd;
3279         m_pYZWnd = 0;
3280         delete m_pXZWnd;
3281         m_pXZWnd = 0;
3282
3283         TextureBrowser_destroyWindow();
3284
3285         DeleteCamWnd( m_pCamWnd );
3286         m_pCamWnd = 0;
3287
3288         PreferencesDialog_destroyWindow();
3289         SurfaceInspector_destroyWindow();
3290         FindTextureDialog_destroyWindow();
3291         PatchInspector_destroyWindow();
3292
3293         g_DbgDlg.destroyWindow();
3294
3295         // destroying group-dialog last because it may contain texture-browser
3296         GroupDialog_destroyWindow();
3297 }
3298
3299 void MainFrame::RedrawStatusText(){
3300         ui::Label::from(m_pStatusLabel[c_command_status]).text(m_command_status.c_str());
3301         ui::Label::from(m_pStatusLabel[c_position_status]).text(m_position_status.c_str());
3302         ui::Label::from(m_pStatusLabel[c_brushcount_status]).text(m_brushcount_status.c_str());
3303         ui::Label::from(m_pStatusLabel[c_texture_status]).text(m_texture_status.c_str());
3304         ui::Label::from(m_pStatusLabel[c_grid_status]).text(m_grid_status.c_str());
3305 }
3306
3307 void MainFrame::UpdateStatusText(){
3308         m_idleRedrawStatusText.queueDraw();
3309 }
3310
3311 void MainFrame::SetStatusText( CopiedString& status_text, const char* pText ){
3312         status_text = pText;
3313         UpdateStatusText();
3314 }
3315
3316 void Sys_Status( const char* status ){
3317         if ( g_pParentWnd != nullptr ) {
3318                 g_pParentWnd->SetStatusText( g_pParentWnd->m_command_status, status );
3319         }
3320 }
3321
3322 int getRotateIncrement(){
3323         return static_cast<int>( g_si_globals.rotate );
3324 }
3325
3326 int getFarClipDistance(){
3327         return g_camwindow_globals.m_nCubicScale;
3328 }
3329
3330 float ( *GridStatus_getGridSize )() = GetGridSize;
3331
3332 int ( *GridStatus_getRotateIncrement )() = getRotateIncrement;
3333
3334 int ( *GridStatus_getFarClipDistance )() = getFarClipDistance;
3335
3336 bool ( *GridStatus_getTextureLockEnabled )();
3337
3338 void MainFrame::SetGridStatus(){
3339         StringOutputStream status( 64 );
3340         const char* lock = ( GridStatus_getTextureLockEnabled() ) ? "ON" : "OFF";
3341         status << ( GetSnapGridSize() > 0 ? "G:" : "g:" ) << GridStatus_getGridSize()
3342                    << "  R:" << GridStatus_getRotateIncrement()
3343                    << "  C:" << GridStatus_getFarClipDistance()
3344                    << "  L:" << lock;
3345         SetStatusText( m_grid_status, status.c_str() );
3346 }
3347
3348 void GridStatus_onTextureLockEnabledChanged(){
3349         if ( g_pParentWnd != nullptr ) {
3350                 g_pParentWnd->SetGridStatus();
3351         }
3352 }
3353
3354 void GlobalGL_sharedContextCreated(){
3355         GLFont *g_font = NULL;
3356
3357         // report OpenGL information
3358         globalOutputStream() << "GL_VENDOR: " << reinterpret_cast<const char*>( glGetString( GL_VENDOR ) ) << "\n";
3359         globalOutputStream() << "GL_RENDERER: " << reinterpret_cast<const char*>( glGetString( GL_RENDERER ) ) << "\n";
3360         globalOutputStream() << "GL_VERSION: " << reinterpret_cast<const char*>( glGetString( GL_VERSION ) ) << "\n";
3361     const auto extensions = reinterpret_cast<const char*>( glGetString(GL_EXTENSIONS ) );
3362     globalOutputStream() << "GL_EXTENSIONS: " << (extensions ? extensions : "") << "\n";
3363
3364         QGL_sharedContextCreated( GlobalOpenGL() );
3365
3366         ShaderCache_extensionsInitialised();
3367
3368         GlobalShaderCache().realise();
3369         Textures_TriggerRealise();
3370
3371 #if GDEF_OS_WINDOWS
3372         /* win32 is dodgy here, just use courier new then */
3373         g_font = glfont_create( "arial 9" );
3374 #else
3375         auto settings = gtk_settings_get_default();
3376         gchar *fontname;
3377         g_object_get( settings, "gtk-font-name", &fontname, NULL );
3378         g_font = glfont_create( fontname );
3379 #endif
3380
3381         GlobalOpenGL().m_font = g_font;
3382 }
3383
3384 void GlobalGL_sharedContextDestroyed(){
3385         Textures_Unrealise();
3386         GlobalShaderCache().unrealise();
3387
3388         QGL_sharedContextDestroyed( GlobalOpenGL() );
3389 }
3390
3391
3392 void Layout_constructPreferences( PreferencesPage& page ){
3393         {
3394                 const char* layouts[] = { "window1.png", "window2.png", "window3.png", "window4.png" };
3395                 page.appendRadioIcons(
3396                         "Window Layout",
3397                         STRING_ARRAY_RANGE( layouts ),
3398                         make_property( g_Layout_viewStyle )
3399                         );
3400         }
3401         page.appendCheckBox(
3402                 "", "Detachable Menus",
3403                 make_property( g_Layout_enableDetachableMenus )
3404                 );
3405         if ( !string_empty( g_pGameDescription->getKeyValue( "no_patch" ) ) ) {
3406                 page.appendCheckBox(
3407                         "", "Patch Toolbar",
3408                         make_property( g_Layout_enablePatchToolbar )
3409                         );
3410         }
3411         page.appendCheckBox(
3412                 "", "Plugin Toolbar",
3413                 make_property( g_Layout_enablePluginToolbar )
3414                 );
3415 }
3416
3417 void Layout_constructPage( PreferenceGroup& group ){
3418         PreferencesPage page( group.createPage( "Layout", "Layout Preferences" ) );
3419         Layout_constructPreferences( page );
3420 }
3421
3422 void Layout_registerPreferencesPage(){
3423         PreferencesDialog_addInterfacePage( makeCallbackF(Layout_constructPage) );
3424 }
3425
3426
3427 #include "preferencesystem.h"
3428 #include "stringio.h"
3429
3430 void MainFrame_Construct(){
3431         GlobalCommands_insert( "OpenManual", makeCallbackF(OpenHelpURL), Accelerator( GDK_KEY_F1 ) );
3432
3433         GlobalCommands_insert( "Sleep", makeCallbackF(thunk_OnSleep), Accelerator( 'P', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
3434         GlobalCommands_insert( "NewMap", makeCallbackF(NewMap) );
3435         GlobalCommands_insert( "OpenMap", makeCallbackF(OpenMap), Accelerator( 'O', (GdkModifierType)GDK_CONTROL_MASK ) );
3436         GlobalCommands_insert( "ImportMap", makeCallbackF(ImportMap) );
3437         GlobalCommands_insert( "SaveMap", makeCallbackF(SaveMap), Accelerator( 'S', (GdkModifierType)GDK_CONTROL_MASK ) );
3438         GlobalCommands_insert( "SaveMapAs", makeCallbackF(SaveMapAs) );
3439         GlobalCommands_insert( "ExportSelected", makeCallbackF(ExportMap) );
3440         GlobalCommands_insert( "SaveRegion", makeCallbackF(SaveRegion) );
3441         GlobalCommands_insert( "RefreshReferences", makeCallbackF(VFS_Refresh) );
3442         GlobalCommands_insert( "ProjectSettings", makeCallbackF(DoProjectSettings) );
3443         GlobalCommands_insert( "Exit", makeCallbackF(Exit) );
3444
3445         GlobalCommands_insert( "Undo", makeCallbackF(Undo), Accelerator( 'Z', (GdkModifierType)GDK_CONTROL_MASK ) );
3446         GlobalCommands_insert( "Redo", makeCallbackF(Redo), Accelerator( 'Y', (GdkModifierType)GDK_CONTROL_MASK ) );
3447         GlobalCommands_insert( "Copy", makeCallbackF(Copy), Accelerator( 'C', (GdkModifierType)GDK_CONTROL_MASK ) );
3448         GlobalCommands_insert( "Paste", makeCallbackF(Paste), Accelerator( 'V', (GdkModifierType)GDK_CONTROL_MASK ) );
3449         GlobalCommands_insert( "PasteToCamera", makeCallbackF(PasteToCamera), Accelerator( 'V', (GdkModifierType)GDK_MOD1_MASK ) );
3450         GlobalCommands_insert( "CloneSelection", makeCallbackF(Selection_Clone), Accelerator( GDK_KEY_space ) );
3451         GlobalCommands_insert( "CloneSelectionAndMakeUnique", makeCallbackF(Selection_Clone_MakeUnique), Accelerator( GDK_KEY_space, (GdkModifierType)GDK_SHIFT_MASK ) );
3452         GlobalCommands_insert( "DeleteSelection", makeCallbackF(deleteSelection), Accelerator( GDK_KEY_BackSpace ) );
3453         GlobalCommands_insert( "ParentSelection", makeCallbackF(Scene_parentSelected) );
3454         GlobalCommands_insert( "UnSelectSelection", makeCallbackF(Selection_Deselect), Accelerator( GDK_KEY_Escape ) );
3455         GlobalCommands_insert( "InvertSelection", makeCallbackF(Select_Invert), Accelerator( 'I' ) );
3456         GlobalCommands_insert( "SelectInside", makeCallbackF(Select_Inside) );
3457         GlobalCommands_insert( "SelectTouching", makeCallbackF(Select_Touching) );
3458         GlobalCommands_insert( "ExpandSelectionToEntities", makeCallbackF(Scene_ExpandSelectionToEntities), Accelerator( 'E', (GdkModifierType)( GDK_MOD1_MASK | GDK_CONTROL_MASK ) ) );
3459         GlobalCommands_insert( "Preferences", makeCallbackF(PreferencesDialog_showDialog), Accelerator( 'P' ) );
3460
3461         GlobalCommands_insert( "ToggleConsole", makeCallbackF(Console_ToggleShow), Accelerator( 'O' ) );
3462         GlobalCommands_insert( "ToggleEntityInspector", makeCallbackF(EntityInspector_ToggleShow), Accelerator( 'N' ) );
3463         GlobalCommands_insert( "EntityList", makeCallbackF(EntityList_toggleShown), Accelerator( 'L' ) );
3464
3465         GlobalCommands_insert( "ShowHidden", makeCallbackF(Select_ShowAllHidden), Accelerator( 'H', (GdkModifierType)GDK_SHIFT_MASK ) );
3466         GlobalCommands_insert( "HideSelected", makeCallbackF(HideSelected), Accelerator( 'H' ) );
3467
3468         GlobalToggles_insert( "DragVertices", makeCallbackF(SelectVertexMode), ToggleItem::AddCallbackCaller( g_vertexMode_button ), Accelerator( 'V' ) );
3469         GlobalToggles_insert( "DragEdges", makeCallbackF(SelectEdgeMode), ToggleItem::AddCallbackCaller( g_edgeMode_button ), Accelerator( 'E' ) );
3470         GlobalToggles_insert( "DragFaces", makeCallbackF(SelectFaceMode), ToggleItem::AddCallbackCaller( g_faceMode_button ), Accelerator( 'F' ) );
3471
3472         GlobalCommands_insert( "MirrorSelectionX", makeCallbackF(Selection_Flipx) );
3473         GlobalCommands_insert( "RotateSelectionX", makeCallbackF(Selection_Rotatex) );
3474         GlobalCommands_insert( "MirrorSelectionY", makeCallbackF(Selection_Flipy) );
3475         GlobalCommands_insert( "RotateSelectionY", makeCallbackF(Selection_Rotatey) );
3476         GlobalCommands_insert( "MirrorSelectionZ", makeCallbackF(Selection_Flipz) );
3477         GlobalCommands_insert( "RotateSelectionZ", makeCallbackF(Selection_Rotatez) );
3478
3479         GlobalCommands_insert( "ArbitraryRotation", makeCallbackF(DoRotateDlg) );
3480         GlobalCommands_insert( "ArbitraryScale", makeCallbackF(DoScaleDlg) );
3481
3482         GlobalCommands_insert( "BuildMenuCustomize", makeCallbackF(DoBuildMenu) );
3483
3484         GlobalCommands_insert( "FindBrush", makeCallbackF(DoFind) );
3485
3486         GlobalCommands_insert( "MapInfo", makeCallbackF(DoMapInfo), Accelerator( 'M' ) );
3487
3488
3489         GlobalToggles_insert( "ToggleClipper", makeCallbackF(ClipperMode), ToggleItem::AddCallbackCaller( g_clipper_button ), Accelerator( 'X' ) );
3490
3491         GlobalToggles_insert( "MouseTranslate", makeCallbackF(TranslateMode), ToggleItem::AddCallbackCaller( g_translatemode_button ), Accelerator( 'W' ) );
3492         GlobalToggles_insert( "MouseRotate", makeCallbackF(RotateMode), ToggleItem::AddCallbackCaller( g_rotatemode_button ), Accelerator( 'R' ) );
3493         GlobalToggles_insert( "MouseScale", makeCallbackF(ScaleMode), ToggleItem::AddCallbackCaller( g_scalemode_button ) );
3494         GlobalToggles_insert( "MouseDrag", makeCallbackF(DragMode), ToggleItem::AddCallbackCaller( g_dragmode_button ), Accelerator( 'Q' ) );
3495
3496         GlobalCommands_insert( "ColorSchemeOriginal", makeCallbackF(ColorScheme_Original) );
3497         GlobalCommands_insert( "ColorSchemeQER", makeCallbackF(ColorScheme_QER) );
3498         GlobalCommands_insert( "ColorSchemeBlackAndGreen", makeCallbackF(ColorScheme_Black) );
3499         GlobalCommands_insert( "ColorSchemeYdnar", makeCallbackF(ColorScheme_Ydnar) );
3500         GlobalCommands_insert("ColorSchemeAdwaitaDark", makeCallbackF(ColorScheme_AdwaitaDark));
3501         GlobalCommands_insert( "ChooseTextureBackgroundColor", makeCallback( g_ColoursMenu.m_textureback ) );
3502         GlobalCommands_insert( "ChooseGridBackgroundColor", makeCallback( g_ColoursMenu.m_xyback ) );
3503         GlobalCommands_insert( "ChooseGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor ) );
3504         GlobalCommands_insert( "ChooseGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor ) );
3505         GlobalCommands_insert( "ChooseSmallGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor_alt ) );
3506         GlobalCommands_insert( "ChooseSmallGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor_alt ) );
3507         GlobalCommands_insert( "ChooseGridTextColor", makeCallback( g_ColoursMenu.m_gridtext ) );
3508         GlobalCommands_insert( "ChooseGridBlockColor", makeCallback( g_ColoursMenu.m_gridblock ) );
3509         GlobalCommands_insert( "ChooseBrushColor", makeCallback( g_ColoursMenu.m_brush ) );
3510         GlobalCommands_insert( "ChooseCameraBackgroundColor", makeCallback( g_ColoursMenu.m_cameraback ) );
3511         GlobalCommands_insert( "ChooseSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush ) );
3512         GlobalCommands_insert( "ChooseCameraSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush3d ) );
3513         GlobalCommands_insert( "ChooseClipperColor", makeCallback( g_ColoursMenu.m_clipper ) );
3514         GlobalCommands_insert( "ChooseOrthoViewNameColor", makeCallback( g_ColoursMenu.m_viewname ) );
3515
3516
3517         GlobalCommands_insert( "CSGSubtract", makeCallbackF(CSG_Subtract), Accelerator( 'U', (GdkModifierType)GDK_SHIFT_MASK ) );
3518         GlobalCommands_insert( "CSGMerge", makeCallbackF(CSG_Merge), Accelerator( 'U', (GdkModifierType) GDK_CONTROL_MASK ) );
3519         GlobalCommands_insert( "CSGMakeHollow", makeCallbackF(CSG_MakeHollow) );
3520         GlobalCommands_insert( "CSGMakeRoom", makeCallbackF(CSG_MakeRoom) );
3521
3522         Grid_registerCommands();
3523
3524         GlobalCommands_insert( "SnapToGrid", makeCallbackF(Selection_SnapToGrid), Accelerator( 'G', (GdkModifierType)GDK_CONTROL_MASK ) );
3525
3526         GlobalCommands_insert( "SelectAllOfType", makeCallbackF(Select_AllOfType), Accelerator( 'A', (GdkModifierType)GDK_SHIFT_MASK ) );
3527
3528         GlobalCommands_insert( "TexRotateClock", makeCallbackF(Texdef_RotateClockwise), Accelerator( GDK_KEY_Next, (GdkModifierType)GDK_SHIFT_MASK ) );
3529         GlobalCommands_insert( "TexRotateCounter", makeCallbackF(Texdef_RotateAntiClockwise), Accelerator( GDK_KEY_Prior, (GdkModifierType)GDK_SHIFT_MASK ) );
3530         GlobalCommands_insert( "TexScaleUp", makeCallbackF(Texdef_ScaleUp), Accelerator( GDK_KEY_Up, (GdkModifierType)GDK_CONTROL_MASK ) );
3531         GlobalCommands_insert( "TexScaleDown", makeCallbackF(Texdef_ScaleDown), Accelerator( GDK_KEY_Down, (GdkModifierType)GDK_CONTROL_MASK ) );
3532         GlobalCommands_insert( "TexScaleLeft", makeCallbackF(Texdef_ScaleLeft), Accelerator( GDK_KEY_Left, (GdkModifierType)GDK_CONTROL_MASK ) );
3533         GlobalCommands_insert( "TexScaleRight", makeCallbackF(Texdef_ScaleRight), Accelerator( GDK_KEY_Right, (GdkModifierType)GDK_CONTROL_MASK ) );
3534         GlobalCommands_insert( "TexShiftUp", makeCallbackF(Texdef_ShiftUp), Accelerator( GDK_KEY_Up, (GdkModifierType)GDK_SHIFT_MASK ) );
3535         GlobalCommands_insert( "TexShiftDown", makeCallbackF(Texdef_ShiftDown), Accelerator( GDK_KEY_Down, (GdkModifierType)GDK_SHIFT_MASK ) );
3536         GlobalCommands_insert( "TexShiftLeft", makeCallbackF(Texdef_ShiftLeft), Accelerator( GDK_KEY_Left, (GdkModifierType)GDK_SHIFT_MASK ) );
3537         GlobalCommands_insert( "TexShiftRight", makeCallbackF(Texdef_ShiftRight), Accelerator( GDK_KEY_Right, (GdkModifierType)GDK_SHIFT_MASK ) );
3538
3539         GlobalCommands_insert( "MoveSelectionDOWN", makeCallbackF(Selection_MoveDown), Accelerator( GDK_KEY_KP_Subtract ) );
3540         GlobalCommands_insert( "MoveSelectionUP", makeCallbackF(Selection_MoveUp), Accelerator( GDK_KEY_KP_Add ) );
3541
3542         GlobalCommands_insert( "SelectNudgeLeft", makeCallbackF(Selection_NudgeLeft), Accelerator( GDK_KEY_Left, (GdkModifierType)GDK_MOD1_MASK ) );
3543         GlobalCommands_insert( "SelectNudgeRight", makeCallbackF(Selection_NudgeRight), Accelerator( GDK_KEY_Right, (GdkModifierType)GDK_MOD1_MASK ) );
3544         GlobalCommands_insert( "SelectNudgeUp", makeCallbackF(Selection_NudgeUp), Accelerator( GDK_KEY_Up, (GdkModifierType)GDK_MOD1_MASK ) );
3545         GlobalCommands_insert( "SelectNudgeDown", makeCallbackF(Selection_NudgeDown), Accelerator( GDK_KEY_Down, (GdkModifierType)GDK_MOD1_MASK ) );
3546
3547         Patch_registerCommands();
3548         XYShow_registerCommands();
3549
3550         typedef FreeCaller<void(const Selectable&), ComponentMode_SelectionChanged> ComponentModeSelectionChangedCaller;
3551         GlobalSelectionSystem().addSelectionChangeCallback( ComponentModeSelectionChangedCaller() );
3552
3553         GlobalPreferenceSystem().registerPreference( "DetachableMenus", make_property_string( g_Layout_enableDetachableMenus.m_latched ) );
3554         GlobalPreferenceSystem().registerPreference( "PatchToolBar", make_property_string( g_Layout_enablePatchToolbar.m_latched ) );
3555         GlobalPreferenceSystem().registerPreference( "PluginToolBar", make_property_string( g_Layout_enablePluginToolbar.m_latched ) );
3556         GlobalPreferenceSystem().registerPreference( "QE4StyleWindows", make_property_string( g_Layout_viewStyle.m_latched ) );
3557         GlobalPreferenceSystem().registerPreference( "XYHeight", make_property_string( g_layout_globals.nXYHeight ) );
3558         GlobalPreferenceSystem().registerPreference( "XYWidth", make_property_string( g_layout_globals.nXYWidth ) );
3559         GlobalPreferenceSystem().registerPreference( "CamWidth", make_property_string( g_layout_globals.nCamWidth ) );
3560         GlobalPreferenceSystem().registerPreference( "CamHeight", make_property_string( g_layout_globals.nCamHeight ) );
3561
3562         GlobalPreferenceSystem().registerPreference( "State", make_property_string( g_layout_globals.nState ) );
3563         GlobalPreferenceSystem().registerPreference( "PositionX", make_property_string( g_layout_globals.m_position.x ) );
3564         GlobalPreferenceSystem().registerPreference( "PositionY", make_property_string( g_layout_globals.m_position.y ) );
3565         GlobalPreferenceSystem().registerPreference( "Width", make_property_string( g_layout_globals.m_position.w ) );
3566         GlobalPreferenceSystem().registerPreference( "Height", make_property_string( g_layout_globals.m_position.h ) );
3567
3568         GlobalPreferenceSystem().registerPreference( "CamWnd", make_property<WindowPositionTracker_String>(g_posCamWnd) );
3569         GlobalPreferenceSystem().registerPreference( "XYWnd", make_property<WindowPositionTracker_String>(g_posXYWnd) );
3570         GlobalPreferenceSystem().registerPreference( "YZWnd", make_property<WindowPositionTracker_String>(g_posYZWnd) );
3571         GlobalPreferenceSystem().registerPreference( "XZWnd", make_property<WindowPositionTracker_String>(g_posXZWnd) );
3572
3573         {
3574                 const char* ENGINEPATH_ATTRIBUTE =
3575 #if GDEF_OS_WINDOWS
3576                         "enginepath_win32"
3577 #elif GDEF_OS_MACOS
3578                         "enginepath_macos"
3579 #elif GDEF_OS_LINUX || GDEF_OS_BSD
3580                         "enginepath_linux"
3581 #else
3582 #error "unknown platform"
3583 #endif
3584                 ;
3585                 StringOutputStream path( 256 );
3586                 path << DirectoryCleaned( g_pGameDescription->getRequiredKeyValue( ENGINEPATH_ATTRIBUTE ) );
3587                 g_strEnginePath = path.c_str();
3588         }
3589
3590         GlobalPreferenceSystem().registerPreference( "EnginePath", make_property_string( g_strEnginePath ) );
3591
3592         GlobalPreferenceSystem().registerPreference( "DisableEnginePath", make_property_string( g_disableEnginePath ) );
3593         GlobalPreferenceSystem().registerPreference( "DisableHomePath", make_property_string( g_disableHomePath ) );
3594
3595         for ( int i = 0; i < g_pakPathCount; i++ ) {
3596                 std::string label = "PakPath" + std::to_string( i );
3597                 GlobalPreferenceSystem().registerPreference( label.c_str(), make_property_string( g_strPakPath[i] ) );
3598         }
3599
3600         g_Layout_viewStyle.useLatched();
3601         g_Layout_enableDetachableMenus.useLatched();
3602         g_Layout_enablePatchToolbar.useLatched();
3603         g_Layout_enablePluginToolbar.useLatched();
3604
3605         Layout_registerPreferencesPage();
3606         Paths_registerPreferencesPage();
3607
3608         g_brushCount.setCountChangedCallback( makeCallbackF(QE_brushCountChanged) );
3609         g_entityCount.setCountChangedCallback( makeCallbackF(QE_entityCountChanged) );
3610         GlobalEntityCreator().setCounter( &g_entityCount );
3611
3612         glwidget_set_shared_context_constructors( GlobalGL_sharedContextCreated, GlobalGL_sharedContextDestroyed);
3613
3614         GlobalEntityClassManager().attach( g_WorldspawnColourEntityClassObserver );
3615 }
3616
3617 void MainFrame_Destroy(){
3618         GlobalEntityClassManager().detach( g_WorldspawnColourEntityClassObserver );
3619
3620         GlobalEntityCreator().setCounter( 0 );
3621         g_entityCount.setCountChangedCallback( Callback<void()>() );
3622         g_brushCount.setCountChangedCallback( Callback<void()>() );
3623 }
3624
3625
3626 void GLWindow_Construct(){
3627         GlobalPreferenceSystem().registerPreference( "MouseButtons", make_property_string( g_glwindow_globals.m_nMouseType ) );
3628 }
3629
3630 void GLWindow_Destroy(){
3631 }
3632
3633 /* HACK: If ui::main is not called yet,
3634 gtk_main_quit will not quit, so tell main
3635 to not call ui::main. This happens when a
3636 map is loaded from command line and require
3637 a restart because of wrong format.
3638 Delete this when the code to not have to
3639 restart to load another format is merged. */
3640 extern bool g_dontStart;
3641
3642 void Radiant_Restart(){
3643         // preferences are expected to be already saved in any way
3644         // this is just to be sure and be future proof
3645         Preferences_Save();
3646
3647         // this asks user for saving if map is modified
3648         // user can chose to not save, it's ok
3649         ConfirmModified( "Restart " RADIANT_NAME );
3650
3651         int status;
3652
3653         char *argv[ 3 ];
3654         char exe_file[ 256 ];
3655         char map_file[ 256 ];
3656         bool with_map = false;
3657
3658         strncpy( exe_file, g_strAppFilePath.c_str(), 256 );
3659
3660         if ( !Map_Unnamed( g_map ) ) {
3661                 strncpy( map_file, Map_Name( g_map ), 256 );
3662                 with_map = true;
3663         }
3664
3665         argv[ 0 ] = exe_file;
3666         argv[ 1 ] = with_map ? map_file : NULL;
3667         argv[ 2 ] = NULL;
3668
3669 #if GDEF_OS_WINDOWS
3670         status = !_spawnvpe( P_NOWAIT, exe_file, argv, environ );
3671 #else
3672         pid_t pid;
3673
3674         status = posix_spawn( &pid, exe_file, NULL, NULL, argv, environ );
3675 #endif
3676
3677         // quit if radiant successfully started
3678         if ( status == 0 ) {
3679                 gtk_main_quit();
3680                 /* HACK: If ui::main is not called yet,
3681                 gtk_main_quit will not quit, so tell main
3682                 to not call ui::main. This happens when a
3683                 map is loaded from command line and require
3684                 a restart because of wrong format.
3685                 Delete this when the code to not have to
3686                 restart to load another format is merged. */
3687                 g_dontStart = true;
3688         }
3689 }