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