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