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