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