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