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