332d737958f629bbaec0fef3f542aa6545c422f2
[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         GdkModifierType mask;
1808
1809         gdk_window_get_pointer( 0, 0, 0, &mask );
1810
1811         if ( ( mask & ( GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK ) ) == 0 ) {
1812                 QE_CheckAutoSave();
1813         }
1814
1815         return TRUE;
1816 }
1817
1818 guint s_qe_every_second_id = 0;
1819
1820 void EverySecondTimer_enable(){
1821         if ( s_qe_every_second_id == 0 ) {
1822                 s_qe_every_second_id = g_timeout_add( 1000, qe_every_second, 0 );
1823         }
1824 }
1825
1826 void EverySecondTimer_disable(){
1827         if ( s_qe_every_second_id != 0 ) {
1828                 g_source_remove( s_qe_every_second_id );
1829                 s_qe_every_second_id = 0;
1830         }
1831 }
1832
1833 gint window_realize_remove_decoration( ui::Widget widget, gpointer data ){
1834         gdk_window_set_decorations( gtk_widget_get_window(widget), (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MENU | GDK_DECOR_MINIMIZE | GDK_DECOR_MAXIMIZE ) );
1835         return FALSE;
1836 }
1837
1838 class WaitDialog
1839 {
1840 public:
1841 ui::Window m_window{ui::null};
1842 ui::Label m_label{ui::null};
1843 };
1844
1845 WaitDialog create_wait_dialog( const char* title, const char* text ){
1846         WaitDialog dialog;
1847
1848         dialog.m_window = MainFrame_getWindow().create_floating_window(title);
1849         gtk_window_set_resizable( dialog.m_window, FALSE );
1850         gtk_container_set_border_width( GTK_CONTAINER( dialog.m_window ), 0 );
1851         gtk_window_set_position( dialog.m_window, GTK_WIN_POS_CENTER_ON_PARENT );
1852
1853         dialog.m_window.connect( "realize", G_CALLBACK( window_realize_remove_decoration ), 0 );
1854
1855         {
1856                 dialog.m_label = ui::Label( text );
1857                 gtk_misc_set_alignment( GTK_MISC( dialog.m_label ), 0.0, 0.5 );
1858                 gtk_label_set_justify( dialog.m_label, GTK_JUSTIFY_LEFT );
1859                 dialog.m_label.show();
1860                 dialog.m_label.dimensions(200, -1);
1861
1862                 dialog.m_window.add(dialog.m_label);
1863         }
1864         return dialog;
1865 }
1866
1867 namespace
1868 {
1869 clock_t g_lastRedrawTime = 0;
1870 const clock_t c_redrawInterval = clock_t( CLOCKS_PER_SEC / 10 );
1871
1872 bool redrawRequired(){
1873         clock_t currentTime = std::clock();
1874         if ( currentTime - g_lastRedrawTime >= c_redrawInterval ) {
1875                 g_lastRedrawTime = currentTime;
1876                 return true;
1877         }
1878         return false;
1879 }
1880 }
1881
1882 bool MainFrame_isActiveApp(){
1883         //globalOutputStream() << "listing\n";
1884         GList* list = gtk_window_list_toplevels();
1885         for ( GList* i = list; i != 0; i = g_list_next( i ) )
1886         {
1887                 //globalOutputStream() << "toplevel.. ";
1888                 if ( gtk_window_is_active( ui::Window::from( i->data ) ) ) {
1889                         //globalOutputStream() << "is active\n";
1890                         return true;
1891                 }
1892                 //globalOutputStream() << "not active\n";
1893         }
1894         return false;
1895 }
1896
1897 typedef std::list<CopiedString> StringStack;
1898 StringStack g_wait_stack;
1899 WaitDialog g_wait;
1900
1901 bool ScreenUpdates_Enabled(){
1902         return g_wait_stack.empty();
1903 }
1904
1905 void ScreenUpdates_process(){
1906         if ( redrawRequired() && g_wait.m_window.visible() ) {
1907                 ui::process();
1908         }
1909 }
1910
1911
1912 void ScreenUpdates_Disable( const char* message, const char* title ){
1913         if ( g_wait_stack.empty() ) {
1914                 EverySecondTimer_disable();
1915
1916                 ui::process();
1917
1918                 bool isActiveApp = MainFrame_isActiveApp();
1919
1920                 g_wait = create_wait_dialog( title, message );
1921                 gtk_grab_add( g_wait.m_window  );
1922
1923                 if ( isActiveApp ) {
1924                         g_wait.m_window.show();
1925                         ScreenUpdates_process();
1926                 }
1927         }
1928         else if ( g_wait.m_window.visible() ) {
1929                 g_wait.m_label.text(message);
1930                 ScreenUpdates_process();
1931         }
1932         g_wait_stack.push_back( message );
1933 }
1934
1935 void ScreenUpdates_Enable(){
1936         ASSERT_MESSAGE( !ScreenUpdates_Enabled(), "screen updates already enabled" );
1937         g_wait_stack.pop_back();
1938         if ( g_wait_stack.empty() ) {
1939                 EverySecondTimer_enable();
1940                 //gtk_widget_set_sensitive(MainFrame_getWindow(), TRUE);
1941
1942                 gtk_grab_remove( g_wait.m_window  );
1943                 destroy_floating_window( g_wait.m_window );
1944                 g_wait.m_window = ui::Window{ui::null};
1945
1946                 //gtk_window_present(MainFrame_getWindow());
1947         }
1948         else if ( g_wait.m_window.visible() ) {
1949                 g_wait.m_label.text(g_wait_stack.back().c_str());
1950                 ScreenUpdates_process();
1951         }
1952 }
1953
1954
1955 void GlobalCamera_UpdateWindow(){
1956         if ( g_pParentWnd != 0 ) {
1957                 CamWnd_Update( *g_pParentWnd->GetCamWnd() );
1958         }
1959 }
1960
1961 void XY_UpdateWindow( MainFrame& mainframe ){
1962         if ( mainframe.GetXYWnd() != 0 ) {
1963                 XYWnd_Update( *mainframe.GetXYWnd() );
1964         }
1965 }
1966
1967 void XZ_UpdateWindow( MainFrame& mainframe ){
1968         if ( mainframe.GetXZWnd() != 0 ) {
1969                 XYWnd_Update( *mainframe.GetXZWnd() );
1970         }
1971 }
1972
1973 void YZ_UpdateWindow( MainFrame& mainframe ){
1974         if ( mainframe.GetYZWnd() != 0 ) {
1975                 XYWnd_Update( *mainframe.GetYZWnd() );
1976         }
1977 }
1978
1979 void XY_UpdateAllWindows( MainFrame& mainframe ){
1980         XY_UpdateWindow( mainframe );
1981         XZ_UpdateWindow( mainframe );
1982         YZ_UpdateWindow( mainframe );
1983 }
1984
1985 void XY_UpdateAllWindows(){
1986         if ( g_pParentWnd != 0 ) {
1987                 XY_UpdateAllWindows( *g_pParentWnd );
1988         }
1989 }
1990
1991 void UpdateAllWindows(){
1992         GlobalCamera_UpdateWindow();
1993         XY_UpdateAllWindows();
1994 }
1995
1996
1997 void ModeChangeNotify(){
1998         SceneChangeNotify();
1999 }
2000
2001 void ClipperChangeNotify(){
2002         GlobalCamera_UpdateWindow();
2003         XY_UpdateAllWindows();
2004 }
2005
2006
2007 LatchedValue<int> g_Layout_viewStyle( 0, "Window Layout" );
2008 LatchedValue<bool> g_Layout_enableDetachableMenus( true, "Detachable Menus" );
2009 LatchedValue<bool> g_Layout_enablePatchToolbar( true, "Patch Toolbar" );
2010 LatchedValue<bool> g_Layout_enablePluginToolbar( true, "Plugin Toolbar" );
2011
2012
2013 ui::MenuItem create_file_menu(){
2014         // File menu
2015         auto file_menu_item = new_sub_menu_item_with_mnemonic( "_File" );
2016         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( file_menu_item ) );
2017         if ( g_Layout_enableDetachableMenus.m_value ) {
2018                 menu_tearoff( menu );
2019         }
2020
2021         create_menu_item_with_mnemonic( menu, "_New Map", "NewMap" );
2022         menu_separator( menu );
2023
2024 #if 0
2025         //++timo temporary experimental stuff for sleep mode..
2026         create_menu_item_with_mnemonic( menu, "_Sleep", "Sleep" );
2027         menu_separator( menu );
2028         // end experimental
2029 #endif
2030
2031         create_menu_item_with_mnemonic( menu, "_Open...", "OpenMap" );
2032
2033         create_menu_item_with_mnemonic( menu, "_Import...", "ImportMap" );
2034         create_menu_item_with_mnemonic( menu, "_Save", "SaveMap" );
2035         create_menu_item_with_mnemonic( menu, "Save _as...", "SaveMapAs" );
2036         create_menu_item_with_mnemonic( menu, "_Export selected...", "ExportSelected" );
2037         menu_separator( menu );
2038         create_menu_item_with_mnemonic( menu, "Save re_gion...", "SaveRegion" );
2039         menu_separator( menu );
2040         create_menu_item_with_mnemonic( menu, "_Refresh models", "RefreshReferences" );
2041         menu_separator( menu );
2042         create_menu_item_with_mnemonic( menu, "Pro_ject settings...", "ProjectSettings" );
2043         menu_separator( menu );
2044         create_menu_item_with_mnemonic( menu, "_Pointfile...", "TogglePointfile" );
2045         menu_separator( menu );
2046         MRU_constructMenu( menu );
2047         menu_separator( menu );
2048         create_menu_item_with_mnemonic( menu, "E_xit", "Exit" );
2049
2050         return file_menu_item;
2051 }
2052
2053 ui::MenuItem create_edit_menu(){
2054         // Edit menu
2055         auto edit_menu_item = new_sub_menu_item_with_mnemonic( "_Edit" );
2056         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( edit_menu_item ) );
2057         if ( g_Layout_enableDetachableMenus.m_value ) {
2058                 menu_tearoff( menu );
2059         }
2060         create_menu_item_with_mnemonic( menu, "_Undo", "Undo" );
2061         create_menu_item_with_mnemonic( menu, "_Redo", "Redo" );
2062         menu_separator( menu );
2063         create_menu_item_with_mnemonic( menu, "_Copy", "Copy" );
2064         create_menu_item_with_mnemonic( menu, "_Paste", "Paste" );
2065         create_menu_item_with_mnemonic( menu, "P_aste To Camera", "PasteToCamera" );
2066         menu_separator( menu );
2067         create_menu_item_with_mnemonic( menu, "_Duplicate", "CloneSelection" );
2068         create_menu_item_with_mnemonic( menu, "Duplicate, make uni_que", "CloneSelectionAndMakeUnique" );
2069         create_menu_item_with_mnemonic( menu, "D_elete", "DeleteSelection" );
2070         menu_separator( menu );
2071         create_menu_item_with_mnemonic( menu, "Pa_rent", "ParentSelection" );
2072         menu_separator( menu );
2073         create_menu_item_with_mnemonic( menu, "C_lear Selection", "UnSelectSelection" );
2074         create_menu_item_with_mnemonic( menu, "_Invert Selection", "InvertSelection" );
2075         create_menu_item_with_mnemonic( menu, "Select i_nside", "SelectInside" );
2076         create_menu_item_with_mnemonic( menu, "Select _touching", "SelectTouching" );
2077
2078         auto convert_menu = create_sub_menu_with_mnemonic( menu, "E_xpand Selection" );
2079         if ( g_Layout_enableDetachableMenus.m_value ) {
2080                 menu_tearoff( convert_menu );
2081         }
2082         create_menu_item_with_mnemonic( convert_menu, "To Whole _Entities", "ExpandSelectionToEntities" );
2083
2084         menu_separator( menu );
2085         create_menu_item_with_mnemonic( menu, "Pre_ferences...", "Preferences" );
2086
2087         return edit_menu_item;
2088 }
2089
2090 void fill_view_xy_top_menu( ui::Menu menu ){
2091         create_check_menu_item_with_mnemonic( menu, "XY (Top) View", "ToggleView" );
2092 }
2093
2094
2095 void fill_view_yz_side_menu( ui::Menu menu ){
2096         create_check_menu_item_with_mnemonic( menu, "YZ (Side) View", "ToggleSideView" );
2097 }
2098
2099
2100 void fill_view_xz_front_menu( ui::Menu menu ){
2101         create_check_menu_item_with_mnemonic( menu, "XZ (Front) View", "ToggleFrontView" );
2102 }
2103
2104
2105 ui::Widget g_toggle_z_item{ui::null};
2106 ui::Widget g_toggle_console_item{ui::null};
2107 ui::Widget g_toggle_entity_item{ui::null};
2108 ui::Widget g_toggle_entitylist_item{ui::null};
2109
2110 ui::MenuItem create_view_menu( MainFrame::EViewStyle style ){
2111         // View menu
2112         auto view_menu_item = new_sub_menu_item_with_mnemonic( "Vie_w" );
2113         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( view_menu_item ) );
2114         if ( g_Layout_enableDetachableMenus.m_value ) {
2115                 menu_tearoff( menu );
2116         }
2117
2118         if ( style == MainFrame::eFloating ) {
2119                 fill_view_camera_menu( menu );
2120                 fill_view_xy_top_menu( menu );
2121                 fill_view_yz_side_menu( menu );
2122                 fill_view_xz_front_menu( menu );
2123         }
2124         if ( style == MainFrame::eFloating || style == MainFrame::eSplit ) {
2125                 create_menu_item_with_mnemonic( menu, "Console View", "ToggleConsole" );
2126                 create_menu_item_with_mnemonic( menu, "Texture Browser", "ToggleTextures" );
2127                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ToggleEntityInspector" );
2128         }
2129         else
2130         {
2131                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ViewEntityInfo" );
2132         }
2133         create_menu_item_with_mnemonic( menu, "_Surface Inspector", "SurfaceInspector" );
2134         create_menu_item_with_mnemonic( menu, "Entity List", "EntityList" );
2135
2136         menu_separator( menu );
2137         {
2138                 auto camera_menu = create_sub_menu_with_mnemonic( menu, "Camera" );
2139                 if ( g_Layout_enableDetachableMenus.m_value ) {
2140                         menu_tearoff( camera_menu );
2141                 }
2142                 create_menu_item_with_mnemonic( camera_menu, "_Center", "CenterView" );
2143                 create_menu_item_with_mnemonic( camera_menu, "_Up Floor", "UpFloor" );
2144                 create_menu_item_with_mnemonic( camera_menu, "_Down Floor", "DownFloor" );
2145                 menu_separator( camera_menu );
2146                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane In", "CubicClipZoomIn" );
2147                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane Out", "CubicClipZoomOut" );
2148                 menu_separator( camera_menu );
2149                 create_menu_item_with_mnemonic( camera_menu, "Next leak spot", "NextLeakSpot" );
2150                 create_menu_item_with_mnemonic( camera_menu, "Previous leak spot", "PrevLeakSpot" );
2151                 menu_separator( camera_menu );
2152                 create_menu_item_with_mnemonic( camera_menu, "Look Through Selected", "LookThroughSelected" );
2153                 create_menu_item_with_mnemonic( camera_menu, "Look Through Camera", "LookThroughCamera" );
2154         }
2155         menu_separator( menu );
2156         {
2157                 auto orthographic_menu = create_sub_menu_with_mnemonic( menu, "Orthographic" );
2158                 if ( g_Layout_enableDetachableMenus.m_value ) {
2159                         menu_tearoff( orthographic_menu );
2160                 }
2161                 if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
2162                         create_menu_item_with_mnemonic( orthographic_menu, "_Next (XY, YZ, XY)", "NextView" );
2163                         create_menu_item_with_mnemonic( orthographic_menu, "XY (Top)", "ViewTop" );
2164                         create_menu_item_with_mnemonic( orthographic_menu, "YZ", "ViewSide" );
2165                         create_menu_item_with_mnemonic( orthographic_menu, "XZ", "ViewFront" );
2166                         menu_separator( orthographic_menu );
2167                 }
2168
2169                 create_menu_item_with_mnemonic( orthographic_menu, "_XY 100%", "Zoom100" );
2170                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _In", "ZoomIn" );
2171                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _Out", "ZoomOut" );
2172         }
2173
2174         menu_separator( menu );
2175
2176         {
2177                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Show" );
2178                 if ( g_Layout_enableDetachableMenus.m_value ) {
2179                         menu_tearoff( menu_in_menu );
2180                 }
2181                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Angles", "ShowAngles" );
2182                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Names", "ShowNames" );
2183                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Blocks", "ShowBlocks" );
2184                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show C_oordinates", "ShowCoordinates" );
2185                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Window Outline", "ShowWindowOutline" );
2186                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Axes", "ShowAxes" );
2187                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Workzone", "ShowWorkzone" );
2188                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Stats", "ShowStats" );
2189         }
2190
2191         {
2192                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Filter" );
2193                 if ( g_Layout_enableDetachableMenus.m_value ) {
2194                         menu_tearoff( menu_in_menu );
2195                 }
2196                 Filters_constructMenu( menu_in_menu );
2197         }
2198         menu_separator( menu );
2199         {
2200                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Hide/Show" );
2201                 if ( g_Layout_enableDetachableMenus.m_value ) {
2202                         menu_tearoff( menu_in_menu );
2203                 }
2204                 create_menu_item_with_mnemonic( menu_in_menu, "Hide Selected", "HideSelected" );
2205                 create_menu_item_with_mnemonic( menu_in_menu, "Show Hidden", "ShowHidden" );
2206         }
2207         menu_separator( menu );
2208         {
2209                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Region" );
2210                 if ( g_Layout_enableDetachableMenus.m_value ) {
2211                         menu_tearoff( menu_in_menu );
2212                 }
2213                 create_menu_item_with_mnemonic( menu_in_menu, "_Off", "RegionOff" );
2214                 create_menu_item_with_mnemonic( menu_in_menu, "_Set XY", "RegionSetXY" );
2215                 create_menu_item_with_mnemonic( menu_in_menu, "Set _Brush", "RegionSetBrush" );
2216                 create_menu_item_with_mnemonic( menu_in_menu, "Set Se_lected Brushes", "RegionSetSelection" );
2217         }
2218
2219         command_connect_accelerator( "CenterXYView" );
2220
2221         return view_menu_item;
2222 }
2223
2224 ui::MenuItem create_selection_menu(){
2225         // Selection menu
2226         auto selection_menu_item = new_sub_menu_item_with_mnemonic( "M_odify" );
2227         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( selection_menu_item ) );
2228         if ( g_Layout_enableDetachableMenus.m_value ) {
2229                 menu_tearoff( menu );
2230         }
2231
2232         {
2233                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Components" );
2234                 if ( g_Layout_enableDetachableMenus.m_value ) {
2235                         menu_tearoff( menu_in_menu );
2236                 }
2237                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Edges", "DragEdges" );
2238                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Vertices", "DragVertices" );
2239                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Faces", "DragFaces" );
2240         }
2241
2242         menu_separator( menu );
2243
2244         {
2245                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Nudge" );
2246                 if ( g_Layout_enableDetachableMenus.m_value ) {
2247                         menu_tearoff( menu_in_menu );
2248                 }
2249                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Left", "SelectNudgeLeft" );
2250                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Right", "SelectNudgeRight" );
2251                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Up", "SelectNudgeUp" );
2252                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Down", "SelectNudgeDown" );
2253         }
2254         {
2255                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Rotate" );
2256                 if ( g_Layout_enableDetachableMenus.m_value ) {
2257                         menu_tearoff( menu_in_menu );
2258                 }
2259                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate X", "RotateSelectionX" );
2260                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Y", "RotateSelectionY" );
2261                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Z", "RotateSelectionZ" );
2262         }
2263         {
2264                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Flip" );
2265                 if ( g_Layout_enableDetachableMenus.m_value ) {
2266                         menu_tearoff( menu_in_menu );
2267                 }
2268                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _X", "MirrorSelectionX" );
2269                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Y", "MirrorSelectionY" );
2270                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Z", "MirrorSelectionZ" );
2271         }
2272         menu_separator( menu );
2273         create_menu_item_with_mnemonic( menu, "Arbitrary rotation...", "ArbitraryRotation" );
2274         create_menu_item_with_mnemonic( menu, "Arbitrary scale...", "ArbitraryScale" );
2275
2276         return selection_menu_item;
2277 }
2278
2279 ui::MenuItem create_bsp_menu(){
2280         // BSP menu
2281         auto bsp_menu_item = new_sub_menu_item_with_mnemonic( "_Build" );
2282         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( bsp_menu_item ) );
2283
2284         if ( g_Layout_enableDetachableMenus.m_value ) {
2285                 menu_tearoff( menu );
2286         }
2287
2288         create_menu_item_with_mnemonic( menu, "Customize...", "BuildMenuCustomize" );
2289
2290         menu_separator( menu );
2291
2292         Build_constructMenu( menu );
2293
2294         g_bsp_menu = menu;
2295
2296         return bsp_menu_item;
2297 }
2298
2299 ui::MenuItem create_grid_menu(){
2300         // Grid menu
2301         auto grid_menu_item = new_sub_menu_item_with_mnemonic( "_Grid" );
2302         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( grid_menu_item ) );
2303         if ( g_Layout_enableDetachableMenus.m_value ) {
2304                 menu_tearoff( menu );
2305         }
2306
2307         Grid_constructMenu( menu );
2308
2309         return grid_menu_item;
2310 }
2311
2312 ui::MenuItem create_misc_menu(){
2313         // Misc menu
2314         auto misc_menu_item = new_sub_menu_item_with_mnemonic( "M_isc" );
2315         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( misc_menu_item ) );
2316         if ( g_Layout_enableDetachableMenus.m_value ) {
2317                 menu_tearoff( menu );
2318         }
2319
2320 #if 0
2321         create_menu_item_with_mnemonic( menu, "_Benchmark", makeCallbackF(GlobalCamera_Benchmark) );
2322 #endif
2323     menu.add(create_colours_menu());
2324
2325         create_menu_item_with_mnemonic( menu, "Find brush...", "FindBrush" );
2326         create_menu_item_with_mnemonic( menu, "Map Info...", "MapInfo" );
2327         // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394
2328 //  create_menu_item_with_mnemonic(menu, "_Print XY View", FreeCaller<void(), WXY_Print>());
2329         create_menu_item_with_mnemonic( menu, "_Background select", makeCallbackF(WXY_BackgroundSelect) );
2330         return misc_menu_item;
2331 }
2332
2333 ui::MenuItem create_entity_menu(){
2334         // Brush menu
2335         auto entity_menu_item = new_sub_menu_item_with_mnemonic( "E_ntity" );
2336         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( entity_menu_item ) );
2337         if ( g_Layout_enableDetachableMenus.m_value ) {
2338                 menu_tearoff( menu );
2339         }
2340
2341         Entity_constructMenu( menu );
2342
2343         return entity_menu_item;
2344 }
2345
2346 ui::MenuItem create_brush_menu(){
2347         // Brush menu
2348         auto brush_menu_item = new_sub_menu_item_with_mnemonic( "B_rush" );
2349         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( brush_menu_item ) );
2350         if ( g_Layout_enableDetachableMenus.m_value ) {
2351                 menu_tearoff( menu );
2352         }
2353
2354         Brush_constructMenu( menu );
2355
2356         return brush_menu_item;
2357 }
2358
2359 ui::MenuItem create_patch_menu(){
2360         // Curve menu
2361         auto patch_menu_item = new_sub_menu_item_with_mnemonic( "_Curve" );
2362         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( patch_menu_item ) );
2363         if ( g_Layout_enableDetachableMenus.m_value ) {
2364                 menu_tearoff( menu );
2365         }
2366
2367         Patch_constructMenu( menu );
2368
2369         return patch_menu_item;
2370 }
2371
2372 ui::MenuItem create_help_menu(){
2373         // Help menu
2374         auto help_menu_item = new_sub_menu_item_with_mnemonic( "_Help" );
2375         auto menu = ui::Menu::from( gtk_menu_item_get_submenu( help_menu_item ) );
2376         if ( g_Layout_enableDetachableMenus.m_value ) {
2377                 menu_tearoff( menu );
2378         }
2379
2380         create_menu_item_with_mnemonic( menu, "Manual", "OpenManual" );
2381
2382         // this creates all the per-game drop downs for the game pack helps
2383         // it will take care of hooking the Sys_OpenURL calls etc.
2384         create_game_help_menu( menu );
2385
2386         create_menu_item_with_mnemonic( menu, "Bug report", makeCallbackF(OpenBugReportURL) );
2387         create_menu_item_with_mnemonic( menu, "Shortcuts list", makeCallbackF(DoCommandListDlg) );
2388         create_menu_item_with_mnemonic( menu, "_About...", makeCallbackF(DoAbout) );
2389
2390         return help_menu_item;
2391 }
2392
2393 ui::MenuBar create_main_menu( MainFrame::EViewStyle style ){
2394         auto menu_bar = ui::MenuBar::from( gtk_menu_bar_new() );
2395         menu_bar.show();
2396
2397         menu_bar.add(create_file_menu());
2398         menu_bar.add(create_edit_menu());
2399         menu_bar.add(create_view_menu(style));
2400         menu_bar.add(create_selection_menu());
2401         menu_bar.add(create_bsp_menu());
2402         menu_bar.add(create_grid_menu());
2403         menu_bar.add(create_misc_menu());
2404         menu_bar.add(create_entity_menu());
2405         menu_bar.add(create_brush_menu());
2406         menu_bar.add(create_patch_menu());
2407         menu_bar.add(create_plugins_menu());
2408         menu_bar.add(create_help_menu());
2409
2410         return menu_bar;
2411 }
2412
2413
2414 void PatchInspector_registerShortcuts(){
2415         command_connect_accelerator( "PatchInspector" );
2416 }
2417
2418 void Patch_registerShortcuts(){
2419         command_connect_accelerator( "InvertCurveTextureX" );
2420         command_connect_accelerator( "InvertCurveTextureY" );
2421         command_connect_accelerator( "PatchInsertInsertColumn" );
2422         command_connect_accelerator( "PatchInsertInsertRow" );
2423         command_connect_accelerator( "PatchDeleteLastColumn" );
2424         command_connect_accelerator( "PatchDeleteLastRow" );
2425         command_connect_accelerator( "NaturalizePatch" );
2426         //command_connect_accelerator("CapCurrentCurve");
2427 }
2428
2429 void Manipulators_registerShortcuts(){
2430         toggle_add_accelerator( "MouseRotate" );
2431         toggle_add_accelerator( "MouseTranslate" );
2432         toggle_add_accelerator( "MouseScale" );
2433         toggle_add_accelerator( "MouseDrag" );
2434         toggle_add_accelerator( "ToggleClipper" );
2435 }
2436
2437 void TexdefNudge_registerShortcuts(){
2438         command_connect_accelerator( "TexRotateClock" );
2439         command_connect_accelerator( "TexRotateCounter" );
2440         command_connect_accelerator( "TexScaleUp" );
2441         command_connect_accelerator( "TexScaleDown" );
2442         command_connect_accelerator( "TexScaleLeft" );
2443         command_connect_accelerator( "TexScaleRight" );
2444         command_connect_accelerator( "TexShiftUp" );
2445         command_connect_accelerator( "TexShiftDown" );
2446         command_connect_accelerator( "TexShiftLeft" );
2447         command_connect_accelerator( "TexShiftRight" );
2448 }
2449
2450 void SelectNudge_registerShortcuts(){
2451         command_connect_accelerator( "MoveSelectionDOWN" );
2452         command_connect_accelerator( "MoveSelectionUP" );
2453         //command_connect_accelerator("SelectNudgeLeft");
2454         //command_connect_accelerator("SelectNudgeRight");
2455         //command_connect_accelerator("SelectNudgeUp");
2456         //command_connect_accelerator("SelectNudgeDown");
2457 }
2458
2459 void SnapToGrid_registerShortcuts(){
2460         command_connect_accelerator( "SnapToGrid" );
2461 }
2462
2463 void SelectByType_registerShortcuts(){
2464         command_connect_accelerator( "SelectAllOfType" );
2465 }
2466
2467 void SurfaceInspector_registerShortcuts(){
2468         command_connect_accelerator( "FitTexture" );
2469 }
2470
2471
2472 void register_shortcuts(){
2473         PatchInspector_registerShortcuts();
2474         Patch_registerShortcuts();
2475         Grid_registerShortcuts();
2476         XYWnd_registerShortcuts();
2477         CamWnd_registerShortcuts();
2478         Manipulators_registerShortcuts();
2479         SurfaceInspector_registerShortcuts();
2480         TexdefNudge_registerShortcuts();
2481         SelectNudge_registerShortcuts();
2482         SnapToGrid_registerShortcuts();
2483         SelectByType_registerShortcuts();
2484 }
2485
2486 void File_constructToolbar( ui::Toolbar toolbar ){
2487         toolbar_append_button( toolbar, "Open an existing map (CTRL + O)", "file_open.png", "OpenMap" );
2488         toolbar_append_button( toolbar, "Save the active map (CTRL + S)", "file_save.png", "SaveMap" );
2489 }
2490
2491 void UndoRedo_constructToolbar( ui::Toolbar toolbar ){
2492         toolbar_append_button( toolbar, "Undo (CTRL + Z)", "undo.png", "Undo" );
2493         toolbar_append_button( toolbar, "Redo (CTRL + Y)", "redo.png", "Redo" );
2494 }
2495
2496 void RotateFlip_constructToolbar( ui::Toolbar toolbar ){
2497         toolbar_append_button( toolbar, "x-axis Flip", "brush_flipx.png", "MirrorSelectionX" );
2498         toolbar_append_button( toolbar, "x-axis Rotate", "brush_rotatex.png", "RotateSelectionX" );
2499         toolbar_append_button( toolbar, "y-axis Flip", "brush_flipy.png", "MirrorSelectionY" );
2500         toolbar_append_button( toolbar, "y-axis Rotate", "brush_rotatey.png", "RotateSelectionY" );
2501         toolbar_append_button( toolbar, "z-axis Flip", "brush_flipz.png", "MirrorSelectionZ" );
2502         toolbar_append_button( toolbar, "z-axis Rotate", "brush_rotatez.png", "RotateSelectionZ" );
2503 }
2504
2505 void Select_constructToolbar( ui::Toolbar toolbar ){
2506         toolbar_append_button( toolbar, "Select touching", "selection_selecttouching.png", "SelectTouching" );
2507         toolbar_append_button( toolbar, "Select inside", "selection_selectinside.png", "SelectInside" );
2508 }
2509
2510 void CSG_constructToolbar( ui::Toolbar toolbar ){
2511         toolbar_append_button( toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.png", "CSGSubtract" );
2512         toolbar_append_button( toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.png", "CSGMerge" );
2513         toolbar_append_button( toolbar, "Make Hollow", "selection_makehollow.png", "CSGMakeHollow" );
2514         toolbar_append_button( toolbar, "Make Room", "selection_makeroom.png", "CSGMakeRoom" );
2515 }
2516
2517 void ComponentModes_constructToolbar( ui::Toolbar toolbar ){
2518         toolbar_append_toggle_button( toolbar, "Select Vertices (V)", "modify_vertices.png", "DragVertices" );
2519         toolbar_append_toggle_button( toolbar, "Select Edges (E)", "modify_edges.png", "DragEdges" );
2520         toolbar_append_toggle_button( toolbar, "Select Faces (F)", "modify_faces.png", "DragFaces" );
2521 }
2522
2523 void Clipper_constructToolbar( ui::Toolbar toolbar ){
2524
2525         toolbar_append_toggle_button( toolbar, "Clipper (X)", "view_clipper.png", "ToggleClipper" );
2526 }
2527
2528 void XYWnd_constructToolbar( ui::Toolbar toolbar ){
2529         toolbar_append_button( toolbar, "Change views", "view_change.png", "NextView" );
2530 }
2531
2532 void Manipulators_constructToolbar( ui::Toolbar toolbar ){
2533         toolbar_append_toggle_button( toolbar, "Translate (W)", "select_mousetranslate.png", "MouseTranslate" );
2534         toolbar_append_toggle_button( toolbar, "Rotate (R)", "select_mouserotate.png", "MouseRotate" );
2535         toolbar_append_toggle_button( toolbar, "Scale", "select_mousescale.png", "MouseScale" );
2536         toolbar_append_toggle_button( toolbar, "Resize (Q)", "select_mouseresize.png", "MouseDrag" );
2537
2538         Clipper_constructToolbar( toolbar );
2539 }
2540
2541 ui::Toolbar create_main_toolbar( MainFrame::EViewStyle style ){
2542         auto toolbar = ui::Toolbar::from( gtk_toolbar_new() );
2543         gtk_orientable_set_orientation( GTK_ORIENTABLE(toolbar), GTK_ORIENTATION_HORIZONTAL );
2544         gtk_toolbar_set_style( toolbar, GTK_TOOLBAR_ICONS );
2545
2546         toolbar.show();
2547
2548         auto space = [&]() {
2549                 auto btn = ui::ToolItem::from(gtk_separator_tool_item_new());
2550                 btn.show();
2551                 toolbar.add(btn);
2552         };
2553
2554         File_constructToolbar( toolbar );
2555
2556         space();
2557
2558         UndoRedo_constructToolbar( toolbar );
2559
2560         space();
2561
2562         RotateFlip_constructToolbar( toolbar );
2563
2564         space();
2565
2566         Select_constructToolbar( toolbar );
2567
2568         space();
2569
2570         CSG_constructToolbar( toolbar );
2571
2572         space();
2573
2574         ComponentModes_constructToolbar( toolbar );
2575
2576         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
2577                 space();
2578
2579                 XYWnd_constructToolbar( toolbar );
2580         }
2581
2582         space();
2583
2584         CamWnd_constructToolbar( toolbar );
2585
2586         space();
2587
2588         Manipulators_constructToolbar( toolbar );
2589
2590         if ( g_Layout_enablePatchToolbar.m_value ) {
2591                 space();
2592
2593                 Patch_constructToolbar( toolbar );
2594         }
2595
2596         space();
2597
2598         toolbar_append_toggle_button( toolbar, "Texture Lock (SHIFT +T)", "texture_lock.png", "TogTexLock" );
2599
2600         space();
2601
2602         /*auto g_view_entities_button =*/ toolbar_append_button( toolbar, "Entities (N)", "entities.png", "ToggleEntityInspector" );
2603         auto g_view_console_button = toolbar_append_button( toolbar, "Console (O)", "console.png", "ToggleConsole" );
2604         auto g_view_textures_button = toolbar_append_button( toolbar, "Texture Browser (T)", "texture_browser.png", "ToggleTextures" );
2605         // TODO: call light inspector
2606         //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.png", "ToggleLightInspector");
2607
2608         space();
2609         /*auto g_refresh_models_button =*/ toolbar_append_button( toolbar, "Refresh Models", "refresh_models.png", "RefreshReferences" );
2610
2611
2612         // disable the console and texture button in the regular layouts
2613         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft ) {
2614                 gtk_widget_set_sensitive( g_view_console_button , FALSE );
2615                 gtk_widget_set_sensitive( g_view_textures_button , FALSE );
2616         }
2617
2618         return toolbar;
2619 }
2620
2621 ui::Widget create_main_statusbar( ui::Widget pStatusLabel[c_count_status] ){
2622         auto table = ui::Table( 1, c_count_status, FALSE );
2623         table.show();
2624
2625         {
2626                 auto label = ui::Label( "Label" );
2627                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
2628                 gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
2629                 label.show();
2630                 table.attach(label, {0, 1, 0, 1});
2631                 pStatusLabel[c_command_status] = ui::Widget(label );
2632         }
2633
2634         for (unsigned int i = 1; (int) i < c_count_status; ++i)
2635         {
2636                 auto frame = ui::Frame();
2637                 frame.show();
2638                 table.attach(frame, {i, i + 1, 0, 1});
2639                 gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN );
2640
2641                 auto label = ui::Label( "Label" );
2642                 gtk_label_set_ellipsize( label, PANGO_ELLIPSIZE_END );
2643                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
2644                 gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
2645                 label.show();
2646                 frame.add(label);
2647                 pStatusLabel[i] = ui::Widget(label );
2648         }
2649
2650         return ui::Widget(table );
2651 }
2652
2653 #if 0
2654
2655
2656 WidgetFocusPrinter g_mainframeWidgetFocusPrinter( "mainframe" );
2657
2658 class WindowFocusPrinter
2659 {
2660 const char* m_name;
2661
2662 static gboolean frame_event( ui::Widget widget, GdkEvent* event, WindowFocusPrinter* self ){
2663         globalOutputStream() << self->m_name << " frame_event\n";
2664         return FALSE;
2665 }
2666 static gboolean keys_changed( ui::Widget widget, WindowFocusPrinter* self ){
2667         globalOutputStream() << self->m_name << " keys_changed\n";
2668         return FALSE;
2669 }
2670 static gboolean notify( ui::Window window, gpointer dummy, WindowFocusPrinter* self ){
2671         if ( gtk_window_is_active( window ) ) {
2672                 globalOutputStream() << self->m_name << " takes toplevel focus\n";
2673         }
2674         else
2675         {
2676                 globalOutputStream() << self->m_name << " loses toplevel focus\n";
2677         }
2678         return FALSE;
2679 }
2680 public:
2681 WindowFocusPrinter( const char* name ) : m_name( name ){
2682 }
2683 void connect( ui::Window toplevel_window ){
2684         toplevel_window.connect( "notify::has_toplevel_focus", G_CALLBACK( notify ), this );
2685         toplevel_window.connect( "notify::is_active", G_CALLBACK( notify ), this );
2686         toplevel_window.connect( "keys_changed", G_CALLBACK( keys_changed ), this );
2687         toplevel_window.connect( "frame_event", G_CALLBACK( frame_event ), this );
2688 }
2689 };
2690
2691 WindowFocusPrinter g_mainframeFocusPrinter( "mainframe" );
2692
2693 #endif
2694
2695 class MainWindowActive
2696 {
2697 static gboolean notify( ui::Window window, gpointer dummy, MainWindowActive* self ){
2698         if ( g_wait.m_window && gtk_window_is_active( window ) && !g_wait.m_window.visible() ) {
2699                 g_wait.m_window.show();
2700         }
2701
2702         return FALSE;
2703 }
2704
2705 public:
2706 void connect( ui::Window toplevel_window ){
2707         toplevel_window.connect( "notify::is-active", G_CALLBACK( notify ), this );
2708 }
2709 };
2710
2711 MainWindowActive g_MainWindowActive;
2712
2713 SignalHandlerId XYWindowDestroyed_connect( const SignalHandler& handler ){
2714         return g_pParentWnd->GetXYWnd()->onDestroyed.connectFirst( handler );
2715 }
2716
2717 void XYWindowDestroyed_disconnect( SignalHandlerId id ){
2718         g_pParentWnd->GetXYWnd()->onDestroyed.disconnect( id );
2719 }
2720
2721 MouseEventHandlerId XYWindowMouseDown_connect( const MouseEventHandler& handler ){
2722         return g_pParentWnd->GetXYWnd()->onMouseDown.connectFirst( handler );
2723 }
2724
2725 void XYWindowMouseDown_disconnect( MouseEventHandlerId id ){
2726         g_pParentWnd->GetXYWnd()->onMouseDown.disconnect( id );
2727 }
2728
2729 // =============================================================================
2730 // MainFrame class
2731
2732 MainFrame* g_pParentWnd = 0;
2733
2734 ui::Window MainFrame_getWindow()
2735 {
2736         return g_pParentWnd ? g_pParentWnd->m_window : ui::Window{ui::null};
2737 }
2738
2739 std::vector<ui::Widget> g_floating_windows;
2740
2741 MainFrame::MainFrame() : m_idleRedrawStatusText( RedrawStatusTextCaller( *this ) ){
2742         m_pXYWnd = 0;
2743         m_pCamWnd = 0;
2744         m_pZWnd = 0;
2745         m_pYZWnd = 0;
2746         m_pXZWnd = 0;
2747         m_pActiveXY = 0;
2748
2749         for (auto &n : m_pStatusLabel) {
2750         n = NULL;
2751         }
2752
2753         m_bSleeping = false;
2754
2755         Create();
2756 }
2757
2758 MainFrame::~MainFrame(){
2759         SaveWindowInfo();
2760
2761         m_window.hide();
2762
2763         Shutdown();
2764
2765         for ( std::vector<ui::Widget>::iterator i = g_floating_windows.begin(); i != g_floating_windows.end(); ++i )
2766         {
2767 #ifndef WORKAROUND_MACOS_GTK2_DESTROY
2768                 i->destroy();
2769 #endif
2770         }
2771
2772 #ifndef WORKAROUND_MACOS_GTK2_DESTROY
2773         m_window.destroy();
2774 #endif
2775 }
2776
2777 void MainFrame::SetActiveXY( XYWnd* p ){
2778         if ( m_pActiveXY ) {
2779                 m_pActiveXY->SetActive( false );
2780         }
2781
2782         m_pActiveXY = p;
2783
2784         if ( m_pActiveXY ) {
2785                 m_pActiveXY->SetActive( true );
2786         }
2787
2788 }
2789
2790 void MainFrame::ReleaseContexts(){
2791 #if 0
2792         if ( m_pXYWnd ) {
2793                 m_pXYWnd->DestroyContext();
2794         }
2795         if ( m_pYZWnd ) {
2796                 m_pYZWnd->DestroyContext();
2797         }
2798         if ( m_pXZWnd ) {
2799                 m_pXZWnd->DestroyContext();
2800         }
2801         if ( m_pCamWnd ) {
2802                 m_pCamWnd->DestroyContext();
2803         }
2804         if ( m_pTexWnd ) {
2805                 m_pTexWnd->DestroyContext();
2806         }
2807         if ( m_pZWnd ) {
2808                 m_pZWnd->DestroyContext();
2809         }
2810 #endif
2811 }
2812
2813 void MainFrame::CreateContexts(){
2814 #if 0
2815         if ( m_pCamWnd ) {
2816                 m_pCamWnd->CreateContext();
2817         }
2818         if ( m_pXYWnd ) {
2819                 m_pXYWnd->CreateContext();
2820         }
2821         if ( m_pYZWnd ) {
2822                 m_pYZWnd->CreateContext();
2823         }
2824         if ( m_pXZWnd ) {
2825                 m_pXZWnd->CreateContext();
2826         }
2827         if ( m_pTexWnd ) {
2828                 m_pTexWnd->CreateContext();
2829         }
2830         if ( m_pZWnd ) {
2831                 m_pZWnd->CreateContext();
2832         }
2833 #endif
2834 }
2835
2836 #if GDEF_DEBUG
2837 //#define DBG_SLEEP
2838 #endif
2839
2840 void MainFrame::OnSleep(){
2841 #if 0
2842         m_bSleeping ^= 1;
2843         if ( m_bSleeping ) {
2844                 // useful when trying to debug crashes in the sleep code
2845                 globalOutputStream() << "Going into sleep mode..\n";
2846
2847                 globalOutputStream() << "Dispatching sleep msg...";
2848                 DispatchRadiantMsg( RADIANT_SLEEP );
2849                 globalOutputStream() << "Done.\n";
2850
2851                 gtk_window_iconify( m_window );
2852                 GlobalSelectionSystem().setSelectedAll( false );
2853
2854                 GlobalShaderCache().unrealise();
2855                 Shaders_Free();
2856                 GlobalOpenGL_debugAssertNoErrors();
2857                 ScreenUpdates_Disable();
2858
2859                 // release contexts
2860                 globalOutputStream() << "Releasing contexts...";
2861                 ReleaseContexts();
2862                 globalOutputStream() << "Done.\n";
2863         }
2864         else
2865         {
2866                 globalOutputStream() << "Waking up\n";
2867
2868                 gtk_window_deiconify( m_window );
2869
2870                 // create contexts
2871                 globalOutputStream() << "Creating contexts...";
2872                 CreateContexts();
2873                 globalOutputStream() << "Done.\n";
2874
2875                 globalOutputStream() << "Making current on camera...";
2876                 m_pCamWnd->MakeCurrent();
2877                 globalOutputStream() << "Done.\n";
2878
2879                 globalOutputStream() << "Reloading shaders...";
2880                 Shaders_Load();
2881                 GlobalShaderCache().realise();
2882                 globalOutputStream() << "Done.\n";
2883
2884                 ScreenUpdates_Enable();
2885
2886                 globalOutputStream() << "Dispatching wake msg...";
2887                 DispatchRadiantMsg( RADIANT_WAKEUP );
2888                 globalOutputStream() << "Done\n";
2889         }
2890 #endif
2891 }
2892
2893
2894 ui::Window create_splash(){
2895         auto window = ui::Window( ui::window_type::TOP );
2896         gtk_window_set_decorated(window, false);
2897         gtk_window_set_resizable(window, false);
2898         gtk_window_set_modal(window, true);
2899         gtk_window_set_default_size( window, -1, -1 );
2900         gtk_window_set_position( window, GTK_WIN_POS_CENTER );
2901         gtk_container_set_border_width(window, 0);
2902
2903         auto image = new_local_image( "splash.png" );
2904         image.show();
2905         window.add(image);
2906
2907         window.dimensions(-1, -1);
2908         window.show();
2909
2910         return window;
2911 }
2912
2913 static ui::Window splash_screen{ui::null};
2914
2915 void show_splash(){
2916         splash_screen = create_splash();
2917
2918         ui::process();
2919 }
2920
2921 void hide_splash(){
2922         splash_screen.destroy();
2923 }
2924
2925 WindowPositionTracker g_posCamWnd;
2926 WindowPositionTracker g_posXYWnd;
2927 WindowPositionTracker g_posXZWnd;
2928 WindowPositionTracker g_posYZWnd;
2929
2930 static gint mainframe_delete( ui::Widget widget, GdkEvent *event, gpointer data ){
2931         if ( ConfirmModified( "Exit " RADIANT_NAME ) ) {
2932                 gtk_main_quit();
2933         }
2934
2935         return TRUE;
2936 }
2937
2938 void MainFrame::Create(){
2939         ui::Window window = ui::Window( ui::window_type::TOP );
2940
2941         GlobalWindowObservers_connectTopLevel( window );
2942
2943         gtk_window_set_transient_for( splash_screen, window );
2944
2945 #if !GDEF_OS_WINDOWS
2946         {
2947                 GdkPixbuf* pixbuf = pixbuf_new_from_file_with_mask( "bitmaps/icon.png" );
2948                 if ( pixbuf != 0 ) {
2949                         gtk_window_set_icon( window, pixbuf );
2950                         g_object_unref( pixbuf );
2951                 }
2952         }
2953 #endif
2954
2955         gtk_widget_add_events( window , GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK );
2956         window.connect( "delete_event", G_CALLBACK( mainframe_delete ), this );
2957
2958         m_position_tracker.connect( window );
2959
2960 #if 0
2961         g_mainframeWidgetFocusPrinter.connect( window );
2962         g_mainframeFocusPrinter.connect( window );
2963 #endif
2964
2965         g_MainWindowActive.connect( window );
2966
2967         GetPlugInMgr().Init( window );
2968
2969         auto vbox = ui::VBox( FALSE, 0 );
2970         window.add(vbox);
2971         vbox.show();
2972
2973         global_accel_connect_window( window );
2974
2975         m_nCurrentStyle = (EViewStyle)g_Layout_viewStyle.m_value;
2976
2977         register_shortcuts();
2978
2979     auto main_menu = create_main_menu( CurrentStyle() );
2980         vbox.pack_start( main_menu, FALSE, FALSE, 0 );
2981
2982     auto main_toolbar = create_main_toolbar( CurrentStyle() );
2983         vbox.pack_start( main_toolbar, FALSE, FALSE, 0 );
2984
2985         auto plugin_toolbar = create_plugin_toolbar();
2986         if ( !g_Layout_enablePluginToolbar.m_value ) {
2987                 plugin_toolbar.hide();
2988         }
2989         vbox.pack_start( plugin_toolbar, FALSE, FALSE, 0 );
2990
2991         ui::Widget main_statusbar = create_main_statusbar(reinterpret_cast<ui::Widget *>(m_pStatusLabel));
2992         vbox.pack_end(main_statusbar, FALSE, TRUE, 2);
2993
2994         GroupDialog_constructWindow( window );
2995         g_page_entity = GroupDialog_addPage( "Entities", EntityInspector_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Entities" ) );
2996
2997         if ( FloatingGroupDialog() ) {
2998                 g_page_console = GroupDialog_addPage( "Console", Console_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Console" ) );
2999         }
3000
3001 #if GDEF_OS_WINDOWS
3002         if ( g_multimon_globals.m_bStartOnPrimMon ) {
3003                 PositionWindowOnPrimaryScreen( g_layout_globals.m_position );
3004                 window_set_position( window, g_layout_globals.m_position );
3005         }
3006         else
3007 #endif
3008         if ( g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED ) {
3009                 gtk_window_maximize( window );
3010                 WindowPosition default_position( -1, -1, 640, 480 );
3011                 window_set_position( window, default_position );
3012         }
3013         else
3014         {
3015                 window_set_position( window, g_layout_globals.m_position );
3016         }
3017
3018         m_window = window;
3019
3020         window.show();
3021
3022         if ( CurrentStyle() == eRegular || CurrentStyle() == eRegularLeft ) {
3023                 {
3024                         ui::Widget vsplit = ui::VPaned(ui::New);
3025                         m_vSplit = vsplit;
3026                         vbox.pack_start( vsplit, TRUE, TRUE, 0 );
3027                         vsplit.show();
3028
3029                         // console
3030                         ui::Widget console_window = Console_constructWindow( window );
3031                         gtk_paned_pack2( GTK_PANED( vsplit ), console_window, FALSE, TRUE );
3032
3033                         {
3034                                 ui::Widget hsplit = ui::HPaned(ui::New);
3035                                 hsplit.show();
3036                                 m_hSplit = hsplit;
3037                                 gtk_paned_add1( GTK_PANED( vsplit ), hsplit );
3038
3039                                 // xy
3040                                 m_pXYWnd = new XYWnd();
3041                                 m_pXYWnd->SetViewType( XY );
3042                                 ui::Widget xy_window = ui::Widget(create_framed_widget( m_pXYWnd->GetWidget( ) ));
3043
3044                                 {
3045                                         ui::Widget vsplit2 = ui::VPaned(ui::New);
3046                                         vsplit2.show();
3047                                         m_vSplit2 = vsplit2;
3048
3049                                         if ( CurrentStyle() == eRegular ) {
3050                                                 gtk_paned_add1( GTK_PANED( hsplit ), xy_window );
3051                                                 gtk_paned_add2( GTK_PANED( hsplit ), vsplit2 );
3052                                         }
3053                                         else
3054                                         {
3055                                                 gtk_paned_add1( GTK_PANED( hsplit ), vsplit2 );
3056                                                 gtk_paned_add2( GTK_PANED( hsplit ), xy_window );
3057                                         }
3058
3059
3060                                         // camera
3061                                         m_pCamWnd = NewCamWnd();
3062                                         GlobalCamera_setCamWnd( *m_pCamWnd );
3063                                         CamWnd_setParent( *m_pCamWnd, window );
3064                                         auto camera_window = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
3065
3066                                         gtk_paned_add1( GTK_PANED( vsplit2 ), camera_window  );
3067
3068                                         // textures
3069                                         auto texture_window = create_framed_widget( TextureBrowser_constructWindow( window ) );
3070
3071                                         gtk_paned_add2( GTK_PANED( vsplit2 ), texture_window  );
3072                                 }
3073                         }
3074                 }
3075
3076                 gtk_paned_set_position( GTK_PANED( m_vSplit ), g_layout_globals.nXYHeight );
3077
3078                 if ( CurrentStyle() == eRegular ) {
3079                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nXYWidth );
3080                 }
3081                 else
3082                 {
3083                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nCamWidth );
3084                 }
3085
3086                 gtk_paned_set_position( GTK_PANED( m_vSplit2 ), g_layout_globals.nCamHeight );
3087         }
3088         else if ( CurrentStyle() == eFloating ) {
3089                 {
3090                         ui::Window window = ui::Window(create_persistent_floating_window( "Camera", m_window ));
3091                         global_accel_connect_window( window );
3092                         g_posCamWnd.connect( window );
3093
3094                         window.show();
3095
3096                         m_pCamWnd = NewCamWnd();
3097                         GlobalCamera_setCamWnd( *m_pCamWnd );
3098
3099                         {
3100                                 auto frame = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
3101                                 window.add(frame);
3102                         }
3103                         CamWnd_setParent( *m_pCamWnd, window );
3104
3105                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, CamWnd_getWidget( *m_pCamWnd ) );
3106
3107                         g_floating_windows.push_back( window );
3108                 }
3109
3110                 {
3111                         ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( XY ), m_window ));
3112                         global_accel_connect_window( window );
3113                         g_posXYWnd.connect( window );
3114
3115                         m_pXYWnd = new XYWnd();
3116                         m_pXYWnd->m_parent = window;
3117                         m_pXYWnd->SetViewType( XY );
3118
3119
3120                         {
3121                                 auto frame = create_framed_widget( m_pXYWnd->GetWidget() );
3122                                 window.add(frame);
3123                         }
3124                         XY_Top_Shown_Construct( window );
3125
3126                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, m_pXYWnd->GetWidget() );
3127
3128                         g_floating_windows.push_back( window );
3129                 }
3130
3131                 {
3132                         ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( XZ ), m_window ));
3133                         global_accel_connect_window( window );
3134                         g_posXZWnd.connect( window );
3135
3136                         m_pXZWnd = new XYWnd();
3137                         m_pXZWnd->m_parent = window;
3138                         m_pXZWnd->SetViewType( XZ );
3139
3140                         {
3141                                 auto frame = create_framed_widget( m_pXZWnd->GetWidget() );
3142                                 window.add(frame);
3143                         }
3144
3145                         XZ_Front_Shown_Construct( window );
3146
3147                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, m_pXZWnd->GetWidget() );
3148
3149                         g_floating_windows.push_back( window );
3150                 }
3151
3152                 {
3153                         ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( YZ ), m_window ));
3154                         global_accel_connect_window( window );
3155                         g_posYZWnd.connect( window );
3156
3157                         m_pYZWnd = new XYWnd();
3158                         m_pYZWnd->m_parent = window;
3159                         m_pYZWnd->SetViewType( YZ );
3160
3161                         {
3162                                 auto frame = create_framed_widget( m_pYZWnd->GetWidget() );
3163                                 window.add(frame);
3164                         }
3165
3166                         YZ_Side_Shown_Construct( window );
3167
3168                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, m_pYZWnd->GetWidget() );
3169
3170                         g_floating_windows.push_back( window );
3171                 }
3172
3173                 {
3174                         auto frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
3175                         g_page_textures = GroupDialog_addPage( "Textures", frame, TextureBrowserExportTitleCaller() );
3176
3177                         WORKAROUND_GOBJECT_SET_GLWIDGET( GroupDialog_getWindow(), TextureBrowser_getGLWidget() );
3178                 }
3179
3180                 GroupDialog_show();
3181         }
3182         else // 4 way
3183         {
3184                 m_pCamWnd = NewCamWnd();
3185                 GlobalCamera_setCamWnd( *m_pCamWnd );
3186                 CamWnd_setParent( *m_pCamWnd, window );
3187
3188                 ui::Widget camera = CamWnd_getWidget( *m_pCamWnd );
3189
3190                 m_pYZWnd = new XYWnd();
3191                 m_pYZWnd->SetViewType( YZ );
3192
3193                 ui::Widget yz = m_pYZWnd->GetWidget();
3194
3195                 m_pXYWnd = new XYWnd();
3196                 m_pXYWnd->SetViewType( XY );
3197
3198                 ui::Widget xy = m_pXYWnd->GetWidget();
3199
3200                 m_pXZWnd = new XYWnd();
3201                 m_pXZWnd->SetViewType( XZ );
3202
3203                 ui::Widget xz = m_pXZWnd->GetWidget();
3204
3205         auto split = create_split_views( camera, yz, xy, xz );
3206                 vbox.pack_start( split, TRUE, TRUE, 0 );
3207
3208                 {
3209             auto frame = create_framed_widget( TextureBrowser_constructWindow( window ) );
3210                         g_page_textures = GroupDialog_addPage( "Textures", frame, TextureBrowserExportTitleCaller() );
3211
3212                         WORKAROUND_GOBJECT_SET_GLWIDGET( window, TextureBrowser_getGLWidget() );
3213                 }
3214         }
3215
3216         EntityList_constructWindow( window );
3217         PreferencesDialog_constructWindow( window );
3218         FindTextureDialog_constructWindow( window );
3219         SurfaceInspector_constructWindow( window );
3220         PatchInspector_constructWindow( window );
3221
3222         SetActiveXY( m_pXYWnd );
3223
3224         AddGridChangeCallback( SetGridStatusCaller( *this ) );
3225         AddGridChangeCallback( ReferenceCaller<MainFrame, void(), XY_UpdateAllWindows>( *this ) );
3226
3227         g_defaultToolMode = DragMode;
3228         g_defaultToolMode();
3229         SetStatusText( m_command_status, c_TranslateMode_status );
3230
3231         EverySecondTimer_enable();
3232
3233         //GlobalShortcuts_reportUnregistered();
3234 }
3235
3236 void MainFrame::SaveWindowInfo(){
3237         if ( !FloatingGroupDialog() ) {
3238                 g_layout_globals.nXYHeight = gtk_paned_get_position( GTK_PANED( m_vSplit ) );
3239
3240                 if ( CurrentStyle() != eRegular ) {
3241                         g_layout_globals.nCamWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
3242                 }
3243                 else
3244                 {
3245                         g_layout_globals.nXYWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
3246                 }
3247
3248                 g_layout_globals.nCamHeight = gtk_paned_get_position( GTK_PANED( m_vSplit2 ) );
3249         }
3250
3251         g_layout_globals.m_position = m_position_tracker.getPosition();
3252
3253         g_layout_globals.nState = gdk_window_get_state( gtk_widget_get_window(m_window ) );
3254 }
3255
3256 void MainFrame::Shutdown(){
3257         EverySecondTimer_disable();
3258
3259         EntityList_destroyWindow();
3260
3261         delete m_pXYWnd;
3262         m_pXYWnd = 0;
3263         delete m_pYZWnd;
3264         m_pYZWnd = 0;
3265         delete m_pXZWnd;
3266         m_pXZWnd = 0;
3267
3268         TextureBrowser_destroyWindow();
3269
3270         DeleteCamWnd( m_pCamWnd );
3271         m_pCamWnd = 0;
3272
3273         PreferencesDialog_destroyWindow();
3274         SurfaceInspector_destroyWindow();
3275         FindTextureDialog_destroyWindow();
3276         PatchInspector_destroyWindow();
3277
3278         g_DbgDlg.destroyWindow();
3279
3280         // destroying group-dialog last because it may contain texture-browser
3281         GroupDialog_destroyWindow();
3282 }
3283
3284 void MainFrame::RedrawStatusText(){
3285         ui::Label::from(m_pStatusLabel[c_command_status]).text(m_command_status.c_str());
3286         ui::Label::from(m_pStatusLabel[c_position_status]).text(m_position_status.c_str());
3287         ui::Label::from(m_pStatusLabel[c_brushcount_status]).text(m_brushcount_status.c_str());
3288         ui::Label::from(m_pStatusLabel[c_texture_status]).text(m_texture_status.c_str());
3289         ui::Label::from(m_pStatusLabel[c_grid_status]).text(m_grid_status.c_str());
3290 }
3291
3292 void MainFrame::UpdateStatusText(){
3293         m_idleRedrawStatusText.queueDraw();
3294 }
3295
3296 void MainFrame::SetStatusText( CopiedString& status_text, const char* pText ){
3297         status_text = pText;
3298         UpdateStatusText();
3299 }
3300
3301 void Sys_Status( const char* status ){
3302         if ( g_pParentWnd != 0 ) {
3303                 g_pParentWnd->SetStatusText( g_pParentWnd->m_command_status, status );
3304         }
3305 }
3306
3307 int getRotateIncrement(){
3308         return static_cast<int>( g_si_globals.rotate );
3309 }
3310
3311 int getFarClipDistance(){
3312         return g_camwindow_globals.m_nCubicScale;
3313 }
3314
3315 float ( *GridStatus_getGridSize )() = GetGridSize;
3316
3317 int ( *GridStatus_getRotateIncrement )() = getRotateIncrement;
3318
3319 int ( *GridStatus_getFarClipDistance )() = getFarClipDistance;
3320
3321 bool ( *GridStatus_getTextureLockEnabled )();
3322
3323 void MainFrame::SetGridStatus(){
3324         StringOutputStream status( 64 );
3325         const char* lock = ( GridStatus_getTextureLockEnabled() ) ? "ON" : "OFF";
3326         status << ( GetSnapGridSize() > 0 ? "G:" : "g:" ) << GridStatus_getGridSize()
3327                    << "  R:" << GridStatus_getRotateIncrement()
3328                    << "  C:" << GridStatus_getFarClipDistance()
3329                    << "  L:" << lock;
3330         SetStatusText( m_grid_status, status.c_str() );
3331 }
3332
3333 void GridStatus_onTextureLockEnabledChanged(){
3334         if ( g_pParentWnd != 0 ) {
3335                 g_pParentWnd->SetGridStatus();
3336         }
3337 }
3338
3339 void GlobalGL_sharedContextCreated(){
3340         GLFont *g_font = NULL;
3341
3342         // report OpenGL information
3343         globalOutputStream() << "GL_VENDOR: " << reinterpret_cast<const char*>( glGetString( GL_VENDOR ) ) << "\n";
3344         globalOutputStream() << "GL_RENDERER: " << reinterpret_cast<const char*>( glGetString( GL_RENDERER ) ) << "\n";
3345         globalOutputStream() << "GL_VERSION: " << reinterpret_cast<const char*>( glGetString( GL_VERSION ) ) << "\n";
3346     const auto extensions = reinterpret_cast<const char*>( glGetString(GL_EXTENSIONS ) );
3347     globalOutputStream() << "GL_EXTENSIONS: " << (extensions ? extensions : "") << "\n";
3348
3349         QGL_sharedContextCreated( GlobalOpenGL() );
3350
3351         ShaderCache_extensionsInitialised();
3352
3353         GlobalShaderCache().realise();
3354         Textures_Realise();
3355
3356 #if GDEF_OS_WINDOWS
3357         /* win32 is dodgy here, just use courier new then */
3358         g_font = glfont_create( "arial 9" );
3359 #else
3360         auto settings = gtk_settings_get_default();
3361         gchar *fontname;
3362         g_object_get( settings, "gtk-font-name", &fontname, NULL );
3363         g_font = glfont_create( fontname );
3364 #endif
3365
3366         GlobalOpenGL().m_font = g_font;
3367 }
3368
3369 void GlobalGL_sharedContextDestroyed(){
3370         Textures_Unrealise();
3371         GlobalShaderCache().unrealise();
3372
3373         QGL_sharedContextDestroyed( GlobalOpenGL() );
3374 }
3375
3376
3377 void Layout_constructPreferences( PreferencesPage& page ){
3378         {
3379                 const char* layouts[] = { "window1.png", "window2.png", "window3.png", "window4.png" };
3380                 page.appendRadioIcons(
3381                         "Window Layout",
3382                         STRING_ARRAY_RANGE( layouts ),
3383                         make_property( g_Layout_viewStyle )
3384                         );
3385         }
3386         page.appendCheckBox(
3387                 "", "Detachable Menus",
3388                 make_property( g_Layout_enableDetachableMenus )
3389                 );
3390         if ( !string_empty( g_pGameDescription->getKeyValue( "no_patch" ) ) ) {
3391                 page.appendCheckBox(
3392                         "", "Patch Toolbar",
3393                         make_property( g_Layout_enablePatchToolbar )
3394                         );
3395         }
3396         page.appendCheckBox(
3397                 "", "Plugin Toolbar",
3398                 make_property( g_Layout_enablePluginToolbar )
3399                 );
3400 }
3401
3402 void Layout_constructPage( PreferenceGroup& group ){
3403         PreferencesPage page( group.createPage( "Layout", "Layout Preferences" ) );
3404         Layout_constructPreferences( page );
3405 }
3406
3407 void Layout_registerPreferencesPage(){
3408         PreferencesDialog_addInterfacePage( makeCallbackF(Layout_constructPage) );
3409 }
3410
3411
3412 #include "preferencesystem.h"
3413 #include "stringio.h"
3414
3415 void MainFrame_Construct(){
3416         GlobalCommands_insert( "OpenManual", makeCallbackF(OpenHelpURL), Accelerator( GDK_KEY_F1 ) );
3417
3418         GlobalCommands_insert( "Sleep", makeCallbackF(thunk_OnSleep), Accelerator( 'P', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
3419         GlobalCommands_insert( "NewMap", makeCallbackF(NewMap) );
3420         GlobalCommands_insert( "OpenMap", makeCallbackF(OpenMap), Accelerator( 'O', (GdkModifierType)GDK_CONTROL_MASK ) );
3421         GlobalCommands_insert( "ImportMap", makeCallbackF(ImportMap) );
3422         GlobalCommands_insert( "SaveMap", makeCallbackF(SaveMap), Accelerator( 'S', (GdkModifierType)GDK_CONTROL_MASK ) );
3423         GlobalCommands_insert( "SaveMapAs", makeCallbackF(SaveMapAs) );
3424         GlobalCommands_insert( "ExportSelected", makeCallbackF(ExportMap) );
3425         GlobalCommands_insert( "SaveRegion", makeCallbackF(SaveRegion) );
3426         GlobalCommands_insert( "RefreshReferences", makeCallbackF(VFS_Refresh) );
3427         GlobalCommands_insert( "ProjectSettings", makeCallbackF(DoProjectSettings) );
3428         GlobalCommands_insert( "Exit", makeCallbackF(Exit) );
3429
3430         GlobalCommands_insert( "Undo", makeCallbackF(Undo), Accelerator( 'Z', (GdkModifierType)GDK_CONTROL_MASK ) );
3431         GlobalCommands_insert( "Redo", makeCallbackF(Redo), Accelerator( 'Y', (GdkModifierType)GDK_CONTROL_MASK ) );
3432         GlobalCommands_insert( "Copy", makeCallbackF(Copy), Accelerator( 'C', (GdkModifierType)GDK_CONTROL_MASK ) );
3433         GlobalCommands_insert( "Paste", makeCallbackF(Paste), Accelerator( 'V', (GdkModifierType)GDK_CONTROL_MASK ) );
3434         GlobalCommands_insert( "PasteToCamera", makeCallbackF(PasteToCamera), Accelerator( 'V', (GdkModifierType)GDK_MOD1_MASK ) );
3435         GlobalCommands_insert( "CloneSelection", makeCallbackF(Selection_Clone), Accelerator( GDK_KEY_space ) );
3436         GlobalCommands_insert( "CloneSelectionAndMakeUnique", makeCallbackF(Selection_Clone_MakeUnique), Accelerator( GDK_KEY_space, (GdkModifierType)GDK_SHIFT_MASK ) );
3437         GlobalCommands_insert( "DeleteSelection", makeCallbackF(deleteSelection), Accelerator( GDK_KEY_BackSpace ) );
3438         GlobalCommands_insert( "ParentSelection", makeCallbackF(Scene_parentSelected) );
3439         GlobalCommands_insert( "UnSelectSelection", makeCallbackF(Selection_Deselect), Accelerator( GDK_KEY_Escape ) );
3440         GlobalCommands_insert( "InvertSelection", makeCallbackF(Select_Invert), Accelerator( 'I' ) );
3441         GlobalCommands_insert( "SelectInside", makeCallbackF(Select_Inside) );
3442         GlobalCommands_insert( "SelectTouching", makeCallbackF(Select_Touching) );
3443         GlobalCommands_insert( "ExpandSelectionToEntities", makeCallbackF(Scene_ExpandSelectionToEntities), Accelerator( 'E', (GdkModifierType)( GDK_MOD1_MASK | GDK_CONTROL_MASK ) ) );
3444         GlobalCommands_insert( "Preferences", makeCallbackF(PreferencesDialog_showDialog), Accelerator( 'P' ) );
3445
3446         GlobalCommands_insert( "ToggleConsole", makeCallbackF(Console_ToggleShow), Accelerator( 'O' ) );
3447         GlobalCommands_insert( "ToggleEntityInspector", makeCallbackF(EntityInspector_ToggleShow), Accelerator( 'N' ) );
3448         GlobalCommands_insert( "EntityList", makeCallbackF(EntityList_toggleShown), Accelerator( 'L' ) );
3449
3450         GlobalCommands_insert( "ShowHidden", makeCallbackF(Select_ShowAllHidden), Accelerator( 'H', (GdkModifierType)GDK_SHIFT_MASK ) );
3451         GlobalCommands_insert( "HideSelected", makeCallbackF(HideSelected), Accelerator( 'H' ) );
3452
3453         GlobalToggles_insert( "DragVertices", makeCallbackF(SelectVertexMode), ToggleItem::AddCallbackCaller( g_vertexMode_button ), Accelerator( 'V' ) );
3454         GlobalToggles_insert( "DragEdges", makeCallbackF(SelectEdgeMode), ToggleItem::AddCallbackCaller( g_edgeMode_button ), Accelerator( 'E' ) );
3455         GlobalToggles_insert( "DragFaces", makeCallbackF(SelectFaceMode), ToggleItem::AddCallbackCaller( g_faceMode_button ), Accelerator( 'F' ) );
3456
3457         GlobalCommands_insert( "MirrorSelectionX", makeCallbackF(Selection_Flipx) );
3458         GlobalCommands_insert( "RotateSelectionX", makeCallbackF(Selection_Rotatex) );
3459         GlobalCommands_insert( "MirrorSelectionY", makeCallbackF(Selection_Flipy) );
3460         GlobalCommands_insert( "RotateSelectionY", makeCallbackF(Selection_Rotatey) );
3461         GlobalCommands_insert( "MirrorSelectionZ", makeCallbackF(Selection_Flipz) );
3462         GlobalCommands_insert( "RotateSelectionZ", makeCallbackF(Selection_Rotatez) );
3463
3464         GlobalCommands_insert( "ArbitraryRotation", makeCallbackF(DoRotateDlg) );
3465         GlobalCommands_insert( "ArbitraryScale", makeCallbackF(DoScaleDlg) );
3466
3467         GlobalCommands_insert( "BuildMenuCustomize", makeCallbackF(DoBuildMenu) );
3468
3469         GlobalCommands_insert( "FindBrush", makeCallbackF(DoFind) );
3470
3471         GlobalCommands_insert( "MapInfo", makeCallbackF(DoMapInfo), Accelerator( 'M' ) );
3472
3473
3474         GlobalToggles_insert( "ToggleClipper", makeCallbackF(ClipperMode), ToggleItem::AddCallbackCaller( g_clipper_button ), Accelerator( 'X' ) );
3475
3476         GlobalToggles_insert( "MouseTranslate", makeCallbackF(TranslateMode), ToggleItem::AddCallbackCaller( g_translatemode_button ), Accelerator( 'W' ) );
3477         GlobalToggles_insert( "MouseRotate", makeCallbackF(RotateMode), ToggleItem::AddCallbackCaller( g_rotatemode_button ), Accelerator( 'R' ) );
3478         GlobalToggles_insert( "MouseScale", makeCallbackF(ScaleMode), ToggleItem::AddCallbackCaller( g_scalemode_button ) );
3479         GlobalToggles_insert( "MouseDrag", makeCallbackF(DragMode), ToggleItem::AddCallbackCaller( g_dragmode_button ), Accelerator( 'Q' ) );
3480
3481         GlobalCommands_insert( "ColorSchemeOriginal", makeCallbackF(ColorScheme_Original) );
3482         GlobalCommands_insert( "ColorSchemeQER", makeCallbackF(ColorScheme_QER) );
3483         GlobalCommands_insert( "ColorSchemeBlackAndGreen", makeCallbackF(ColorScheme_Black) );
3484         GlobalCommands_insert( "ColorSchemeYdnar", makeCallbackF(ColorScheme_Ydnar) );
3485         GlobalCommands_insert("ColorSchemeAdwaitaDark", makeCallbackF(ColorScheme_AdwaitaDark));
3486         GlobalCommands_insert( "ChooseTextureBackgroundColor", makeCallback( g_ColoursMenu.m_textureback ) );
3487         GlobalCommands_insert( "ChooseGridBackgroundColor", makeCallback( g_ColoursMenu.m_xyback ) );
3488         GlobalCommands_insert( "ChooseGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor ) );
3489         GlobalCommands_insert( "ChooseGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor ) );
3490         GlobalCommands_insert( "ChooseSmallGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor_alt ) );
3491         GlobalCommands_insert( "ChooseSmallGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor_alt ) );
3492         GlobalCommands_insert( "ChooseGridTextColor", makeCallback( g_ColoursMenu.m_gridtext ) );
3493         GlobalCommands_insert( "ChooseGridBlockColor", makeCallback( g_ColoursMenu.m_gridblock ) );
3494         GlobalCommands_insert( "ChooseBrushColor", makeCallback( g_ColoursMenu.m_brush ) );
3495         GlobalCommands_insert( "ChooseCameraBackgroundColor", makeCallback( g_ColoursMenu.m_cameraback ) );
3496         GlobalCommands_insert( "ChooseSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush ) );
3497         GlobalCommands_insert( "ChooseCameraSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush3d ) );
3498         GlobalCommands_insert( "ChooseClipperColor", makeCallback( g_ColoursMenu.m_clipper ) );
3499         GlobalCommands_insert( "ChooseOrthoViewNameColor", makeCallback( g_ColoursMenu.m_viewname ) );
3500
3501
3502         GlobalCommands_insert( "CSGSubtract", makeCallbackF(CSG_Subtract), Accelerator( 'U', (GdkModifierType)GDK_SHIFT_MASK ) );
3503         GlobalCommands_insert( "CSGMerge", makeCallbackF(CSG_Merge), Accelerator( 'U', (GdkModifierType) GDK_CONTROL_MASK ) );
3504         GlobalCommands_insert( "CSGMakeHollow", makeCallbackF(CSG_MakeHollow) );
3505         GlobalCommands_insert( "CSGMakeRoom", makeCallbackF(CSG_MakeRoom) );
3506
3507         Grid_registerCommands();
3508
3509         GlobalCommands_insert( "SnapToGrid", makeCallbackF(Selection_SnapToGrid), Accelerator( 'G', (GdkModifierType)GDK_CONTROL_MASK ) );
3510
3511         GlobalCommands_insert( "SelectAllOfType", makeCallbackF(Select_AllOfType), Accelerator( 'A', (GdkModifierType)GDK_SHIFT_MASK ) );
3512
3513         GlobalCommands_insert( "TexRotateClock", makeCallbackF(Texdef_RotateClockwise), Accelerator( GDK_KEY_Next, (GdkModifierType)GDK_SHIFT_MASK ) );
3514         GlobalCommands_insert( "TexRotateCounter", makeCallbackF(Texdef_RotateAntiClockwise), Accelerator( GDK_KEY_Prior, (GdkModifierType)GDK_SHIFT_MASK ) );
3515         GlobalCommands_insert( "TexScaleUp", makeCallbackF(Texdef_ScaleUp), Accelerator( GDK_KEY_Up, (GdkModifierType)GDK_CONTROL_MASK ) );
3516         GlobalCommands_insert( "TexScaleDown", makeCallbackF(Texdef_ScaleDown), Accelerator( GDK_KEY_Down, (GdkModifierType)GDK_CONTROL_MASK ) );
3517         GlobalCommands_insert( "TexScaleLeft", makeCallbackF(Texdef_ScaleLeft), Accelerator( GDK_KEY_Left, (GdkModifierType)GDK_CONTROL_MASK ) );
3518         GlobalCommands_insert( "TexScaleRight", makeCallbackF(Texdef_ScaleRight), Accelerator( GDK_KEY_Right, (GdkModifierType)GDK_CONTROL_MASK ) );
3519         GlobalCommands_insert( "TexShiftUp", makeCallbackF(Texdef_ShiftUp), Accelerator( GDK_KEY_Up, (GdkModifierType)GDK_SHIFT_MASK ) );
3520         GlobalCommands_insert( "TexShiftDown", makeCallbackF(Texdef_ShiftDown), Accelerator( GDK_KEY_Down, (GdkModifierType)GDK_SHIFT_MASK ) );
3521         GlobalCommands_insert( "TexShiftLeft", makeCallbackF(Texdef_ShiftLeft), Accelerator( GDK_KEY_Left, (GdkModifierType)GDK_SHIFT_MASK ) );
3522         GlobalCommands_insert( "TexShiftRight", makeCallbackF(Texdef_ShiftRight), Accelerator( GDK_KEY_Right, (GdkModifierType)GDK_SHIFT_MASK ) );
3523
3524         GlobalCommands_insert( "MoveSelectionDOWN", makeCallbackF(Selection_MoveDown), Accelerator( GDK_KEY_KP_Subtract ) );
3525         GlobalCommands_insert( "MoveSelectionUP", makeCallbackF(Selection_MoveUp), Accelerator( GDK_KEY_KP_Add ) );
3526
3527         GlobalCommands_insert( "SelectNudgeLeft", makeCallbackF(Selection_NudgeLeft), Accelerator( GDK_KEY_Left, (GdkModifierType)GDK_MOD1_MASK ) );
3528         GlobalCommands_insert( "SelectNudgeRight", makeCallbackF(Selection_NudgeRight), Accelerator( GDK_KEY_Right, (GdkModifierType)GDK_MOD1_MASK ) );
3529         GlobalCommands_insert( "SelectNudgeUp", makeCallbackF(Selection_NudgeUp), Accelerator( GDK_KEY_Up, (GdkModifierType)GDK_MOD1_MASK ) );
3530         GlobalCommands_insert( "SelectNudgeDown", makeCallbackF(Selection_NudgeDown), Accelerator( GDK_KEY_Down, (GdkModifierType)GDK_MOD1_MASK ) );
3531
3532         Patch_registerCommands();
3533         XYShow_registerCommands();
3534
3535         typedef FreeCaller<void(const Selectable&), ComponentMode_SelectionChanged> ComponentModeSelectionChangedCaller;
3536         GlobalSelectionSystem().addSelectionChangeCallback( ComponentModeSelectionChangedCaller() );
3537
3538         GlobalPreferenceSystem().registerPreference( "DetachableMenus", make_property_string( g_Layout_enableDetachableMenus.m_latched ) );
3539         GlobalPreferenceSystem().registerPreference( "PatchToolBar", make_property_string( g_Layout_enablePatchToolbar.m_latched ) );
3540         GlobalPreferenceSystem().registerPreference( "PluginToolBar", make_property_string( g_Layout_enablePluginToolbar.m_latched ) );
3541         GlobalPreferenceSystem().registerPreference( "QE4StyleWindows", make_property_string( g_Layout_viewStyle.m_latched ) );
3542         GlobalPreferenceSystem().registerPreference( "XYHeight", make_property_string( g_layout_globals.nXYHeight ) );
3543         GlobalPreferenceSystem().registerPreference( "XYWidth", make_property_string( g_layout_globals.nXYWidth ) );
3544         GlobalPreferenceSystem().registerPreference( "CamWidth", make_property_string( g_layout_globals.nCamWidth ) );
3545         GlobalPreferenceSystem().registerPreference( "CamHeight", make_property_string( g_layout_globals.nCamHeight ) );
3546
3547         GlobalPreferenceSystem().registerPreference( "State", make_property_string( g_layout_globals.nState ) );
3548         GlobalPreferenceSystem().registerPreference( "PositionX", make_property_string( g_layout_globals.m_position.x ) );
3549         GlobalPreferenceSystem().registerPreference( "PositionY", make_property_string( g_layout_globals.m_position.y ) );
3550         GlobalPreferenceSystem().registerPreference( "Width", make_property_string( g_layout_globals.m_position.w ) );
3551         GlobalPreferenceSystem().registerPreference( "Height", make_property_string( g_layout_globals.m_position.h ) );
3552
3553         GlobalPreferenceSystem().registerPreference( "CamWnd", make_property<WindowPositionTracker_String>(g_posCamWnd) );
3554         GlobalPreferenceSystem().registerPreference( "XYWnd", make_property<WindowPositionTracker_String>(g_posXYWnd) );
3555         GlobalPreferenceSystem().registerPreference( "YZWnd", make_property<WindowPositionTracker_String>(g_posYZWnd) );
3556         GlobalPreferenceSystem().registerPreference( "XZWnd", make_property<WindowPositionTracker_String>(g_posXZWnd) );
3557
3558         {
3559                 const char* ENGINEPATH_ATTRIBUTE =
3560 #if GDEF_OS_WINDOWS
3561                         "enginepath_win32"
3562 #elif GDEF_OS_MACOS
3563                         "enginepath_macos"
3564 #elif GDEF_OS_LINUX || GDEF_OS_BSD
3565                         "enginepath_linux"
3566 #else
3567 #error "unknown platform"
3568 #endif
3569                 ;
3570                 StringOutputStream path( 256 );
3571                 path << DirectoryCleaned( g_pGameDescription->getRequiredKeyValue( ENGINEPATH_ATTRIBUTE ) );
3572                 g_strEnginePath = path.c_str();
3573         }
3574
3575         GlobalPreferenceSystem().registerPreference( "EnginePath", make_property_string( g_strEnginePath ) );
3576
3577         GlobalPreferenceSystem().registerPreference( "DisableEnginePath", make_property_string( g_disableEnginePath ) );
3578         GlobalPreferenceSystem().registerPreference( "DisableHomePath", make_property_string( g_disableHomePath ) );
3579
3580         for ( int i = 0; i < g_pakPathCount; i++ ) {
3581                 std::string label = "PakPath" + std::to_string( i );
3582                 GlobalPreferenceSystem().registerPreference( label.c_str(), make_property_string( g_strPakPath[i] ) );
3583         }
3584
3585         g_Layout_viewStyle.useLatched();
3586         g_Layout_enableDetachableMenus.useLatched();
3587         g_Layout_enablePatchToolbar.useLatched();
3588         g_Layout_enablePluginToolbar.useLatched();
3589
3590         Layout_registerPreferencesPage();
3591         Paths_registerPreferencesPage();
3592
3593         g_brushCount.setCountChangedCallback( makeCallbackF(QE_brushCountChanged) );
3594         g_entityCount.setCountChangedCallback( makeCallbackF(QE_entityCountChanged) );
3595         GlobalEntityCreator().setCounter( &g_entityCount );
3596
3597         GLWidget_sharedContextCreated = GlobalGL_sharedContextCreated;
3598         GLWidget_sharedContextDestroyed = GlobalGL_sharedContextDestroyed;
3599
3600         GlobalEntityClassManager().attach( g_WorldspawnColourEntityClassObserver );
3601 }
3602
3603 void MainFrame_Destroy(){
3604         GlobalEntityClassManager().detach( g_WorldspawnColourEntityClassObserver );
3605
3606         GlobalEntityCreator().setCounter( 0 );
3607         g_entityCount.setCountChangedCallback( Callback<void()>() );
3608         g_brushCount.setCountChangedCallback( Callback<void()>() );
3609 }
3610
3611
3612 void GLWindow_Construct(){
3613         GlobalPreferenceSystem().registerPreference( "MouseButtons", make_property_string( g_glwindow_globals.m_nMouseType ) );
3614 }
3615
3616 void GLWindow_Destroy(){
3617 }
3618
3619 void Radiant_Restart(){
3620         // preferences are expected to be already saved in any way
3621         // this is just to be sure and be future proof
3622         Preferences_Save();
3623
3624         // this asks user for saving if map is modified
3625         // user can chose to not save, it's ok
3626         ConfirmModified( "Restart " RADIANT_NAME );
3627
3628         int status;
3629
3630         char *argv[ 3 ];
3631         char exe_file[ 256 ];
3632         char map_file[ 256 ];
3633         bool with_map = false;
3634
3635         strncpy( exe_file, g_strAppFilePath.c_str(), 256 );
3636
3637         if ( !Map_Unnamed( g_map ) ) {
3638                 strncpy( map_file, Map_Name( g_map ), 256 );
3639                 with_map = true;
3640         }
3641
3642         argv[ 0 ] = exe_file;
3643         argv[ 1 ] = with_map ? map_file : NULL;
3644         argv[ 2 ] = NULL;
3645
3646 #if GDEF_OS_WINDOWS
3647         status = !_spawnvpe( P_NOWAIT, exe_file, argv, environ );
3648 #else
3649         pid_t pid;
3650
3651         status = posix_spawn( &pid, exe_file, NULL, NULL, argv, environ );
3652 #endif
3653
3654         // quit if radiant successfully started
3655         if ( status == 0 ) {
3656                 gtk_main_quit();
3657         }
3658 }