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