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