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