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