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