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