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