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