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