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