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