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