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