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