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