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