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