GTK: wrap GTK_WIDGET
[xonotic/netradiant.git] / radiant / mainframe.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // Main Window for Q3Radiant
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "mainframe.h"
29 #include "globaldefs.h"
30
31 #include <gtk/gtk.h>
32
33 #include "ifilesystem.h"
34 #include "iundo.h"
35 #include "editable.h"
36 #include "ientity.h"
37 #include "ishaders.h"
38 #include "igl.h"
39 #include "moduleobserver.h"
40
41 #include <ctime>
42
43 #include <gdk/gdkkeysyms.h>
44
45
46 #include "cmdlib.h"
47 #include "stream/stringstream.h"
48 #include "signal/isignal.h"
49 #include "os/path.h"
50 #include "os/file.h"
51 #include "eclasslib.h"
52 #include "moduleobservers.h"
53
54 #include "gtkutil/clipboard.h"
55 #include "gtkutil/frame.h"
56 #include "gtkutil/glwidget.h"
57 #include "gtkutil/image.h"
58 #include "gtkutil/menu.h"
59 #include "gtkutil/paned.h"
60
61 #include "autosave.h"
62 #include "build.h"
63 #include "brushmanip.h"
64 #include "brushmodule.h"
65 #include "camwindow.h"
66 #include "csg.h"
67 #include "commands.h"
68 #include "console.h"
69 #include "entity.h"
70 #include "entityinspector.h"
71 #include "entitylist.h"
72 #include "filters.h"
73 #include "findtexturedialog.h"
74 #include "grid.h"
75 #include "groupdialog.h"
76 #include "gtkdlgs.h"
77 #include "gtkmisc.h"
78 #include "help.h"
79 #include "map.h"
80 #include "mru.h"
81 #include "multimon.h"
82 #include "patchdialog.h"
83 #include "patchmanip.h"
84 #include "plugin.h"
85 #include "pluginmanager.h"
86 #include "pluginmenu.h"
87 #include "plugintoolbar.h"
88 #include "preferences.h"
89 #include "qe3.h"
90 #include "qgl.h"
91 #include "select.h"
92 #include "server.h"
93 #include "surfacedialog.h"
94 #include "textures.h"
95 #include "texwindow.h"
96 #include "url.h"
97 #include "xywindow.h"
98 #include "windowobservers.h"
99 #include "renderstate.h"
100 #include "feedback.h"
101 #include "referencecache.h"
102 #include "texwindow.h"
103
104
105 struct layout_globals_t
106 {
107         WindowPosition m_position;
108
109
110         int nXYHeight;
111         int nXYWidth;
112         int nCamWidth;
113         int nCamHeight;
114         int nState;
115
116         layout_globals_t() :
117                 m_position( -1, -1, 640, 480 ),
118
119                 nXYHeight( 300 ),
120                 nXYWidth( 300 ),
121                 nCamWidth( 200 ),
122                 nCamHeight( 200 ),
123                 nState( GDK_WINDOW_STATE_MAXIMIZED ){
124         }
125 };
126
127 layout_globals_t g_layout_globals;
128 glwindow_globals_t g_glwindow_globals;
129
130
131 // VFS
132
133 bool g_vfsInitialized = false;
134
135 void VFS_Init(){
136         if ( g_vfsInitialized ) return;
137         QE_InitVFS();
138         GlobalFileSystem().initialise();
139         g_vfsInitialized = true;
140 }
141 void VFS_Shutdown(){
142         if ( !g_vfsInitialized ) return;
143         GlobalFileSystem().shutdown();
144         g_vfsInitialized = false;
145 }
146 void VFS_Refresh(){
147         if ( !g_vfsInitialized ) return;
148         GlobalFileSystem().clear();
149         QE_InitVFS();
150         GlobalFileSystem().refresh();
151         g_vfsInitialized = true;
152         // also refresg models
153         RefreshReferences();
154         // also refresh texture browser
155         TextureBrowser_RefreshShaders();
156 }
157 void VFS_Restart(){
158         VFS_Shutdown();
159         VFS_Init();
160 }
161
162 class VFSModuleObserver : public ModuleObserver
163 {
164 public:
165 void realise(){
166         VFS_Init();
167 }
168 void unrealise(){
169         VFS_Shutdown();
170 }
171 };
172
173 VFSModuleObserver g_VFSModuleObserver;
174
175 void VFS_Construct(){
176         Radiant_attachHomePathsObserver( g_VFSModuleObserver );
177 }
178 void VFS_Destroy(){
179         Radiant_detachHomePathsObserver( g_VFSModuleObserver );
180 }
181
182 // Home Paths
183
184 #if GDEF_OS_WINDOWS
185 #include <shlobj.h>
186 #include <objbase.h>
187 const GUID qFOLDERID_SavedGames = {0x4C5C32FF, 0xBB9D, 0x43b0, {0xB5, 0xB4, 0x2D, 0x72, 0xE5, 0x4E, 0xAA, 0xA4}};
188 #define qREFKNOWNFOLDERID GUID
189 #define qKF_FLAG_CREATE 0x8000
190 #define qKF_FLAG_NO_ALIAS 0x1000
191 typedef HRESULT ( WINAPI qSHGetKnownFolderPath_t )( qREFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath );
192 static qSHGetKnownFolderPath_t *qSHGetKnownFolderPath;
193 #endif
194 void HomePaths_Realise(){
195         do
196         {
197                 const char* prefix = g_pGameDescription->getKeyValue( "prefix" );
198                 if ( !string_empty( prefix ) ) {
199                         StringOutputStream path( 256 );
200
201 #if GDEF_OS_MACOS
202                         path.clear();
203                         path << DirectoryCleaned( g_get_home_dir() ) << "Library/Application Support" << ( prefix + 1 ) << "/";
204                         if ( file_is_directory( path.c_str() ) ) {
205                                 g_qeglobals.m_userEnginePath = path.c_str();
206                                 break;
207                         }
208                         path.clear();
209                         path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
210 #endif
211
212 #if GDEF_OS_WINDOWS
213                         TCHAR mydocsdir[MAX_PATH + 1];
214                         wchar_t *mydocsdirw;
215                         HMODULE shfolder = LoadLibrary( "shfolder.dll" );
216                         if ( shfolder ) {
217                                 qSHGetKnownFolderPath = (qSHGetKnownFolderPath_t *) GetProcAddress( shfolder, "SHGetKnownFolderPath" );
218                         }
219                         else{
220                                 qSHGetKnownFolderPath = NULL;
221                         }
222                         CoInitializeEx( NULL, COINIT_APARTMENTTHREADED );
223                         if ( qSHGetKnownFolderPath && qSHGetKnownFolderPath( qFOLDERID_SavedGames, qKF_FLAG_CREATE | qKF_FLAG_NO_ALIAS, NULL, &mydocsdirw ) == S_OK ) {
224                                 memset( mydocsdir, 0, sizeof( mydocsdir ) );
225                                 wcstombs( mydocsdir, mydocsdirw, sizeof( mydocsdir ) - 1 );
226                                 CoTaskMemFree( mydocsdirw );
227                                 path.clear();
228                                 path << DirectoryCleaned( mydocsdir ) << ( prefix + 1 ) << "/";
229                                 if ( file_is_directory( path.c_str() ) ) {
230                                         g_qeglobals.m_userEnginePath = path.c_str();
231                                         CoUninitialize();
232                                         FreeLibrary( shfolder );
233                                         break;
234                                 }
235                         }
236                         CoUninitialize();
237                         if ( shfolder ) {
238                                 FreeLibrary( shfolder );
239                         }
240                         if ( SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, 0, mydocsdir ) ) {
241                                 path.clear();
242                                 path << DirectoryCleaned( mydocsdir ) << "My Games/" << ( prefix + 1 ) << "/";
243                                 // win32: only add it if it already exists
244                                 if ( file_is_directory( path.c_str() ) ) {
245                                         g_qeglobals.m_userEnginePath = path.c_str();
246                                         break;
247                                 }
248                         }
249 #endif
250
251 #if GDEF_OS_POSIX
252                         path.clear();
253                         path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
254                         g_qeglobals.m_userEnginePath = path.c_str();
255                         break;
256 #endif
257                 }
258
259                 g_qeglobals.m_userEnginePath = EnginePath_get();
260         }
261         while ( 0 );
262
263         Q_mkdir( g_qeglobals.m_userEnginePath.c_str() );
264
265         {
266                 StringOutputStream path( 256 );
267                 path << g_qeglobals.m_userEnginePath.c_str() << gamename_get() << '/';
268                 g_qeglobals.m_userGamePath = path.c_str();
269         }
270         ASSERT_MESSAGE( !string_empty( g_qeglobals.m_userGamePath.c_str() ), "HomePaths_Realise: user-game-path is empty" );
271         Q_mkdir( g_qeglobals.m_userGamePath.c_str() );
272 }
273
274 ModuleObservers g_homePathObservers;
275
276 void Radiant_attachHomePathsObserver( ModuleObserver& observer ){
277         g_homePathObservers.attach( observer );
278 }
279
280 void Radiant_detachHomePathsObserver( ModuleObserver& observer ){
281         g_homePathObservers.detach( observer );
282 }
283
284 class HomePathsModuleObserver : public ModuleObserver
285 {
286 std::size_t m_unrealised;
287 public:
288 HomePathsModuleObserver() : m_unrealised( 1 ){
289 }
290 void realise(){
291         if ( --m_unrealised == 0 ) {
292                 HomePaths_Realise();
293                 g_homePathObservers.realise();
294         }
295 }
296 void unrealise(){
297         if ( ++m_unrealised == 1 ) {
298                 g_homePathObservers.unrealise();
299         }
300 }
301 };
302
303 HomePathsModuleObserver g_HomePathsModuleObserver;
304
305 void HomePaths_Construct(){
306         Radiant_attachEnginePathObserver( g_HomePathsModuleObserver );
307 }
308 void HomePaths_Destroy(){
309         Radiant_detachEnginePathObserver( g_HomePathsModuleObserver );
310 }
311
312
313 // Engine Path
314
315 CopiedString g_strEnginePath;
316 ModuleObservers g_enginePathObservers;
317 std::size_t g_enginepath_unrealised = 1;
318
319 void Radiant_attachEnginePathObserver( ModuleObserver& observer ){
320         g_enginePathObservers.attach( observer );
321 }
322
323 void Radiant_detachEnginePathObserver( ModuleObserver& observer ){
324         g_enginePathObservers.detach( observer );
325 }
326
327
328 void EnginePath_Realise(){
329         if ( --g_enginepath_unrealised == 0 ) {
330                 g_enginePathObservers.realise();
331         }
332 }
333
334
335 const char* EnginePath_get(){
336         ASSERT_MESSAGE( g_enginepath_unrealised == 0, "EnginePath_get: engine path not realised" );
337         return g_strEnginePath.c_str();
338 }
339
340 void EnginePath_Unrealise(){
341         if ( ++g_enginepath_unrealised == 1 ) {
342                 g_enginePathObservers.unrealise();
343         }
344 }
345
346 void setEnginePath( const char* path ){
347         StringOutputStream buffer( 256 );
348         buffer << DirectoryCleaned( path );
349         if ( !path_equal( buffer.c_str(), g_strEnginePath.c_str() ) ) {
350 #if 0
351                 while ( !ConfirmModified( "Paths Changed" ) )
352                 {
353                         if ( Map_Unnamed( g_map ) ) {
354                                 Map_SaveAs();
355                         }
356                         else
357                         {
358                                 Map_Save();
359                         }
360                 }
361                 Map_RegionOff();
362 #endif
363
364                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Changing Engine Path" );
365
366                 EnginePath_Unrealise();
367
368                 g_strEnginePath = buffer.c_str();
369
370                 EnginePath_Realise();
371         }
372 }
373
374
375 // App Path
376
377 CopiedString g_strAppPath;                 ///< holds the full path of the executable
378
379 const char* AppPath_get(){
380         return g_strAppPath.c_str();
381 }
382
383 /// the path to the local rc-dir
384 const char* LocalRcPath_get( void ){
385         static CopiedString rc_path;
386         if ( rc_path.empty() ) {
387                 StringOutputStream stream( 256 );
388                 stream << GlobalRadiant().getSettingsPath() << g_pGameDescription->mGameFile.c_str() << "/";
389                 rc_path = stream.c_str();
390         }
391         return rc_path.c_str();
392 }
393
394 /// directory for temp files
395 /// NOTE: on *nix this is were we check for .pid
396 CopiedString g_strSettingsPath;
397 const char* SettingsPath_get(){
398         return g_strSettingsPath.c_str();
399 }
400
401
402 /*!
403    points to the game tools directory, for instance
404    C:/Program Files/Quake III Arena/GtkRadiant
405    (or other games)
406    this is one of the main variables that are configured by the game selection on startup
407    [GameToolsPath]/plugins
408    [GameToolsPath]/modules
409    and also q3map, bspc
410  */
411 CopiedString g_strGameToolsPath;           ///< this is set by g_GamesDialog
412
413 const char* GameToolsPath_get(){
414         return g_strGameToolsPath.c_str();
415 }
416
417 void EnginePathImport( CopiedString& self, const char* value ){
418         setEnginePath( value );
419 }
420 typedef ReferenceCaller1<CopiedString, const char*, EnginePathImport> EnginePathImportCaller;
421
422 void Paths_constructPreferences( PreferencesPage& page ){
423         page.appendPathEntry( "Engine Path", true,
424                                                   StringImportCallback( EnginePathImportCaller( g_strEnginePath ) ),
425                                                   StringExportCallback( StringExportCaller( g_strEnginePath ) )
426                                                   );
427 }
428 void Paths_constructPage( PreferenceGroup& group ){
429         PreferencesPage page( group.createPage( "Paths", "Path Settings" ) );
430         Paths_constructPreferences( page );
431 }
432 void Paths_registerPreferencesPage(){
433         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Paths_constructPage>() );
434 }
435
436
437 class PathsDialog : public Dialog
438 {
439 public:
440 ui::Window BuildDialog(){
441         auto frame = create_dialog_frame( "Path settings", ui::Shadow::ETCHED_IN );
442
443         auto vbox2 = create_dialog_vbox( 0, 4 );
444         frame.add(vbox2);
445
446         {
447                 PreferencesPage preferencesPage( *this, vbox2 );
448                 Paths_constructPreferences( preferencesPage );
449         }
450
451         return ui::Window(create_simple_modal_dialog_window( "Engine Path Not Found", m_modal, frame ));
452 }
453 };
454
455 PathsDialog g_PathsDialog;
456
457 void EnginePath_verify(){
458         if ( !file_exists( g_strEnginePath.c_str() ) ) {
459                 g_PathsDialog.Create();
460                 g_PathsDialog.DoModal();
461                 g_PathsDialog.Destroy();
462         }
463 }
464
465 namespace
466 {
467 CopiedString g_gamename;
468 CopiedString g_gamemode;
469 ModuleObservers g_gameNameObservers;
470 ModuleObservers g_gameModeObservers;
471 }
472
473 void Radiant_attachGameNameObserver( ModuleObserver& observer ){
474         g_gameNameObservers.attach( observer );
475 }
476
477 void Radiant_detachGameNameObserver( ModuleObserver& observer ){
478         g_gameNameObservers.detach( observer );
479 }
480
481 const char* basegame_get(){
482         return g_pGameDescription->getRequiredKeyValue( "basegame" );
483 }
484
485 const char* gamename_get(){
486         const char* gamename = g_gamename.c_str();
487         if ( string_empty( gamename ) ) {
488                 return basegame_get();
489         }
490         return gamename;
491 }
492
493 void gamename_set( const char* gamename ){
494         if ( !string_equal( gamename, g_gamename.c_str() ) ) {
495                 g_gameNameObservers.unrealise();
496                 g_gamename = gamename;
497                 g_gameNameObservers.realise();
498         }
499 }
500
501 void Radiant_attachGameModeObserver( ModuleObserver& observer ){
502         g_gameModeObservers.attach( observer );
503 }
504
505 void Radiant_detachGameModeObserver( ModuleObserver& observer ){
506         g_gameModeObservers.detach( observer );
507 }
508
509 const char* gamemode_get(){
510         return g_gamemode.c_str();
511 }
512
513 void gamemode_set( const char* gamemode ){
514         if ( !string_equal( gamemode, g_gamemode.c_str() ) ) {
515                 g_gameModeObservers.unrealise();
516                 g_gamemode = gamemode;
517                 g_gameModeObservers.realise();
518         }
519 }
520
521
522 #include "os/dir.h"
523
524 class CLoadModule
525 {
526 const char* m_path;
527 public:
528 CLoadModule( const char* path ) : m_path( path ){
529 }
530 void operator()( const char* name ) const {
531         char fullname[1024];
532         ASSERT_MESSAGE( strlen( m_path ) + strlen( name ) < 1024, "" );
533         strcpy( fullname, m_path );
534         strcat( fullname, name );
535         globalOutputStream() << "Found '" << fullname << "'\n";
536         GlobalModuleServer_loadModule( fullname );
537 }
538 };
539
540 const char* const c_library_extension =
541 #if defined( CMAKE_SHARED_MODULE_SUFFIX )
542     CMAKE_SHARED_MODULE_SUFFIX
543 #elif GDEF_OS_WINDOWS
544         "dll"
545 #elif GDEF_OS_MACOS
546         "dylib"
547 #elif GDEF_OS_LINUX || GDEF_OS_BSD
548         "so"
549 #endif
550 ;
551
552 void Radiant_loadModules( const char* path ){
553         Directory_forEach( path, MatchFileExtension<CLoadModule>( c_library_extension, CLoadModule( path ) ) );
554 }
555
556 void Radiant_loadModulesFromRoot( const char* directory ){
557         {
558                 StringOutputStream path( 256 );
559                 path << directory << g_pluginsDir;
560                 Radiant_loadModules( path.c_str() );
561         }
562
563         if ( !string_equal( g_pluginsDir, g_modulesDir ) ) {
564                 StringOutputStream path( 256 );
565                 path << directory << g_modulesDir;
566                 Radiant_loadModules( path.c_str() );
567         }
568 }
569
570 //! Make COLOR_BRUSHES override worldspawn eclass colour.
571 void SetWorldspawnColour( const Vector3& colour ){
572         EntityClass* worldspawn = GlobalEntityClassManager().findOrInsert( "worldspawn", true );
573         eclass_release_state( worldspawn );
574         worldspawn->color = colour;
575         eclass_capture_state( worldspawn );
576 }
577
578
579 class WorldspawnColourEntityClassObserver : public ModuleObserver
580 {
581 std::size_t m_unrealised;
582 public:
583 WorldspawnColourEntityClassObserver() : m_unrealised( 1 ){
584 }
585 void realise(){
586         if ( --m_unrealised == 0 ) {
587                 SetWorldspawnColour( g_xywindow_globals.color_brushes );
588         }
589 }
590 void unrealise(){
591         if ( ++m_unrealised == 1 ) {
592         }
593 }
594 };
595
596 WorldspawnColourEntityClassObserver g_WorldspawnColourEntityClassObserver;
597
598
599 ModuleObservers g_gameToolsPathObservers;
600
601 void Radiant_attachGameToolsPathObserver( ModuleObserver& observer ){
602         g_gameToolsPathObservers.attach( observer );
603 }
604
605 void Radiant_detachGameToolsPathObserver( ModuleObserver& observer ){
606         g_gameToolsPathObservers.detach( observer );
607 }
608
609 void Radiant_Initialise(){
610         GlobalModuleServer_Initialise();
611
612         Radiant_loadModulesFromRoot( AppPath_get() );
613
614         Preferences_Load();
615
616         bool success = Radiant_Construct( GlobalModuleServer_get() );
617         ASSERT_MESSAGE( success, "module system failed to initialise - see radiant.log for error messages" );
618
619         g_gameToolsPathObservers.realise();
620         g_gameModeObservers.realise();
621         g_gameNameObservers.realise();
622 }
623
624 void Radiant_Shutdown(){
625         g_gameNameObservers.unrealise();
626         g_gameModeObservers.unrealise();
627         g_gameToolsPathObservers.unrealise();
628
629         if ( !g_preferences_globals.disable_ini ) {
630                 globalOutputStream() << "Start writing prefs\n";
631                 Preferences_Save();
632                 globalOutputStream() << "Done prefs\n";
633         }
634
635         Radiant_Destroy();
636
637         GlobalModuleServer_Shutdown();
638 }
639
640 void Exit(){
641         if ( ConfirmModified( "Exit Radiant" ) ) {
642                 gtk_main_quit();
643         }
644 }
645
646
647 void Undo(){
648         GlobalUndoSystem().undo();
649         SceneChangeNotify();
650 }
651
652 void Redo(){
653         GlobalUndoSystem().redo();
654         SceneChangeNotify();
655 }
656
657 void deleteSelection(){
658         UndoableCommand undo( "deleteSelected" );
659         Select_Delete();
660 }
661
662 void Map_ExportSelected( TextOutputStream& ostream ){
663         Map_ExportSelected( ostream, Map_getFormat( g_map ) );
664 }
665
666 void Map_ImportSelected( TextInputStream& istream ){
667         Map_ImportSelected( istream, Map_getFormat( g_map ) );
668 }
669
670 void Selection_Copy(){
671         clipboard_copy( Map_ExportSelected );
672 }
673
674 void Selection_Paste(){
675         clipboard_paste( Map_ImportSelected );
676 }
677
678 void Copy(){
679         if ( SelectedFaces_empty() ) {
680                 Selection_Copy();
681         }
682         else
683         {
684                 SelectedFaces_copyTexture();
685         }
686 }
687
688 void Paste(){
689         if ( SelectedFaces_empty() ) {
690                 UndoableCommand undo( "paste" );
691
692                 GlobalSelectionSystem().setSelectedAll( false );
693                 Selection_Paste();
694         }
695         else
696         {
697                 SelectedFaces_pasteTexture();
698         }
699 }
700
701 void PasteToCamera(){
702         CamWnd& camwnd = *g_pParentWnd->GetCamWnd();
703         GlobalSelectionSystem().setSelectedAll( false );
704
705         UndoableCommand undo( "pasteToCamera" );
706
707         Selection_Paste();
708
709         // Work out the delta
710         Vector3 mid;
711         Select_GetMid( mid );
712         Vector3 delta = vector3_subtracted( vector3_snapped( Camera_getOrigin( camwnd ), GetSnapGridSize() ), mid );
713
714         // Move to camera
715         GlobalSelectionSystem().translateSelected( delta );
716 }
717
718
719 void ColorScheme_Original(){
720         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
721
722         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
723         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
724         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
725
726         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
727         g_xywindow_globals.color_gridminor = Vector3( 0.75f, 0.75f, 0.75f );
728         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
729         g_xywindow_globals.color_gridminor_alt = Vector3( 0.5f, 0.0f, 0.0f );
730         g_xywindow_globals.color_gridmajor_alt = Vector3( 1.0f, 0.0f, 0.0f );
731         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
732         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
733         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
734         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
735         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
736         SetWorldspawnColour( g_xywindow_globals.color_brushes );
737         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
738         XY_UpdateAllWindows();
739 }
740
741 void ColorScheme_QER(){
742         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
743
744         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
745         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
746         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
747
748         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
749         g_xywindow_globals.color_gridminor = Vector3( 1.0f, 1.0f, 1.0f );
750         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
751         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
752         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
753         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
754         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
755         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
756         SetWorldspawnColour( g_xywindow_globals.color_brushes );
757         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
758         XY_UpdateAllWindows();
759 }
760
761 void ColorScheme_Black(){
762         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
763
764         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
765         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
766         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
767
768         g_xywindow_globals.color_gridback = Vector3( 0.0f, 0.0f, 0.0f );
769         g_xywindow_globals.color_gridminor = Vector3( 0.2f, 0.2f, 0.2f );
770         g_xywindow_globals.color_gridmajor = Vector3( 0.3f, 0.5f, 0.5f );
771         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
772         g_xywindow_globals.color_gridtext = Vector3( 1.0f, 1.0f, 1.0f );
773         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
774         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
775         g_xywindow_globals.color_brushes = Vector3( 1.0f, 1.0f, 1.0f );
776         SetWorldspawnColour( g_xywindow_globals.color_brushes );
777         g_xywindow_globals.color_viewname = Vector3( 0.7f, 0.7f, 0.0f );
778         XY_UpdateAllWindows();
779 }
780
781 /* ydnar: to emulate maya/max/lightwave color schemes */
782 void ColorScheme_Ydnar(){
783         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
784
785         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
786         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
787         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
788
789         g_xywindow_globals.color_gridback = Vector3( 0.77f, 0.77f, 0.77f );
790         g_xywindow_globals.color_gridminor = Vector3( 0.83f, 0.83f, 0.83f );
791         g_xywindow_globals.color_gridmajor = Vector3( 0.89f, 0.89f, 0.89f );
792         g_xywindow_globals.color_gridblock = Vector3( 1.0f, 1.0f, 1.0f );
793         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
794         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
795         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
796         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
797         SetWorldspawnColour( g_xywindow_globals.color_brushes );
798         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
799         XY_UpdateAllWindows();
800 }
801
802 typedef Callback1<Vector3&> GetColourCallback;
803 typedef Callback1<const Vector3&> SetColourCallback;
804
805 class ChooseColour
806 {
807 GetColourCallback m_get;
808 SetColourCallback m_set;
809 public:
810 ChooseColour( const GetColourCallback& get, const SetColourCallback& set )
811         : m_get( get ), m_set( set ){
812 }
813 void operator()(){
814         Vector3 colour;
815         m_get( colour );
816         color_dialog( MainFrame_getWindow(), colour );
817         m_set( colour );
818 }
819 };
820
821
822
823 void Colour_get( const Vector3& colour, Vector3& other ){
824         other = colour;
825 }
826 typedef ConstReferenceCaller1<Vector3, Vector3&, Colour_get> ColourGetCaller;
827
828 void Colour_set( Vector3& colour, const Vector3& other ){
829         colour = other;
830         SceneChangeNotify();
831 }
832 typedef ReferenceCaller1<Vector3, const Vector3&, Colour_set> ColourSetCaller;
833
834 void BrushColour_set( const Vector3& other ){
835         g_xywindow_globals.color_brushes = other;
836         SetWorldspawnColour( g_xywindow_globals.color_brushes );
837         SceneChangeNotify();
838 }
839 typedef FreeCaller1<const Vector3&, BrushColour_set> BrushColourSetCaller;
840
841 void ClipperColour_set( const Vector3& other ){
842         g_xywindow_globals.color_clipper = other;
843         Brush_clipperColourChanged();
844         SceneChangeNotify();
845 }
846 typedef FreeCaller1<const Vector3&, ClipperColour_set> ClipperColourSetCaller;
847
848 void TextureBrowserColour_get( Vector3& other ){
849         other = TextureBrowser_getBackgroundColour( GlobalTextureBrowser() );
850 }
851 typedef FreeCaller1<Vector3&, TextureBrowserColour_get> TextureBrowserColourGetCaller;
852
853 void TextureBrowserColour_set( const Vector3& other ){
854         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), other );
855 }
856 typedef FreeCaller1<const Vector3&, TextureBrowserColour_set> TextureBrowserColourSetCaller;
857
858
859 class ColoursMenu
860 {
861 public:
862 ChooseColour m_textureback;
863 ChooseColour m_xyback;
864 ChooseColour m_gridmajor;
865 ChooseColour m_gridminor;
866 ChooseColour m_gridmajor_alt;
867 ChooseColour m_gridminor_alt;
868 ChooseColour m_gridtext;
869 ChooseColour m_gridblock;
870 ChooseColour m_cameraback;
871 ChooseColour m_brush;
872 ChooseColour m_selectedbrush;
873 ChooseColour m_selectedbrush3d;
874 ChooseColour m_clipper;
875 ChooseColour m_viewname;
876
877 ColoursMenu() :
878         m_textureback( TextureBrowserColourGetCaller(), TextureBrowserColourSetCaller() ),
879         m_xyback( ColourGetCaller( g_xywindow_globals.color_gridback ), ColourSetCaller( g_xywindow_globals.color_gridback ) ),
880         m_gridmajor( ColourGetCaller( g_xywindow_globals.color_gridmajor ), ColourSetCaller( g_xywindow_globals.color_gridmajor ) ),
881         m_gridminor( ColourGetCaller( g_xywindow_globals.color_gridminor ), ColourSetCaller( g_xywindow_globals.color_gridminor ) ),
882         m_gridmajor_alt( ColourGetCaller( g_xywindow_globals.color_gridmajor_alt ), ColourSetCaller( g_xywindow_globals.color_gridmajor_alt ) ),
883         m_gridminor_alt( ColourGetCaller( g_xywindow_globals.color_gridminor_alt ), ColourSetCaller( g_xywindow_globals.color_gridminor_alt ) ),
884         m_gridtext( ColourGetCaller( g_xywindow_globals.color_gridtext ), ColourSetCaller( g_xywindow_globals.color_gridtext ) ),
885         m_gridblock( ColourGetCaller( g_xywindow_globals.color_gridblock ), ColourSetCaller( g_xywindow_globals.color_gridblock ) ),
886         m_cameraback( ColourGetCaller( g_camwindow_globals.color_cameraback ), ColourSetCaller( g_camwindow_globals.color_cameraback ) ),
887         m_brush( ColourGetCaller( g_xywindow_globals.color_brushes ), BrushColourSetCaller() ),
888         m_selectedbrush( ColourGetCaller( g_xywindow_globals.color_selbrushes ), ColourSetCaller( g_xywindow_globals.color_selbrushes ) ),
889         m_selectedbrush3d( ColourGetCaller( g_camwindow_globals.color_selbrushes3d ), ColourSetCaller( g_camwindow_globals.color_selbrushes3d ) ),
890         m_clipper( ColourGetCaller( g_xywindow_globals.color_clipper ), ClipperColourSetCaller() ),
891         m_viewname( ColourGetCaller( g_xywindow_globals.color_viewname ), ColourSetCaller( g_xywindow_globals.color_viewname ) ){
892 }
893 };
894
895 ColoursMenu g_ColoursMenu;
896
897 ui::MenuItem create_colours_menu(){
898         auto colours_menu_item = new_sub_menu_item_with_mnemonic( "Colors" );
899         auto menu_in_menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( colours_menu_item ) ));
900         if ( g_Layout_enableDetachableMenus.m_value ) {
901                 menu_tearoff( menu_in_menu );
902         }
903
904         auto menu_3 = create_sub_menu_with_mnemonic( menu_in_menu, "Themes" );
905         if ( g_Layout_enableDetachableMenus.m_value ) {
906                 menu_tearoff( menu_3 );
907         }
908
909         create_menu_item_with_mnemonic( menu_3, "QE4 Original", "ColorSchemeOriginal" );
910         create_menu_item_with_mnemonic( menu_3, "Q3Radiant Original", "ColorSchemeQER" );
911         create_menu_item_with_mnemonic( menu_3, "Black and Green", "ColorSchemeBlackAndGreen" );
912         create_menu_item_with_mnemonic( menu_3, "Maya/Max/Lightwave Emulation", "ColorSchemeYdnar" );
913
914         menu_separator( menu_in_menu );
915
916         create_menu_item_with_mnemonic( menu_in_menu, "_Texture Background...", "ChooseTextureBackgroundColor" );
917         create_menu_item_with_mnemonic( menu_in_menu, "Grid Background...", "ChooseGridBackgroundColor" );
918         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major...", "ChooseGridMajorColor" );
919         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor...", "ChooseGridMinorColor" );
920         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major Small...", "ChooseSmallGridMajorColor" );
921         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor Small...", "ChooseSmallGridMinorColor" );
922         create_menu_item_with_mnemonic( menu_in_menu, "Grid Text...", "ChooseGridTextColor" );
923         create_menu_item_with_mnemonic( menu_in_menu, "Grid Block...", "ChooseGridBlockColor" );
924         create_menu_item_with_mnemonic( menu_in_menu, "Default Brush...", "ChooseBrushColor" );
925         create_menu_item_with_mnemonic( menu_in_menu, "Camera Background...", "ChooseCameraBackgroundColor" );
926         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush...", "ChooseSelectedBrushColor" );
927         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush (Camera)...", "ChooseCameraSelectedBrushColor" );
928         create_menu_item_with_mnemonic( menu_in_menu, "Clipper...", "ChooseClipperColor" );
929         create_menu_item_with_mnemonic( menu_in_menu, "Active View name...", "ChooseOrthoViewNameColor" );
930
931         return colours_menu_item;
932 }
933
934
935 void Restart(){
936         PluginsMenu_clear();
937         PluginToolbar_clear();
938
939         Radiant_Shutdown();
940         Radiant_Initialise();
941
942         PluginsMenu_populate();
943
944         PluginToolbar_populate();
945 }
946
947
948 void thunk_OnSleep(){
949         g_pParentWnd->OnSleep();
950 }
951
952 void OpenHelpURL(){
953         OpenURL( "https://gitlab.com/xonotic/xonotic/wikis/Mapping" );
954 }
955
956 void OpenBugReportURL(){
957         OpenURL( "https://gitlab.com/xonotic/netradiant/issues" );
958 }
959
960
961 ui::Widget g_page_console{ui::null};
962
963 void Console_ToggleShow(){
964         GroupDialog_showPage( g_page_console );
965 }
966
967 ui::Widget g_page_entity{ui::null};
968
969 void EntityInspector_ToggleShow(){
970         GroupDialog_showPage( g_page_entity );
971 }
972
973
974
975 void SetClipMode( bool enable );
976 void ModeChangeNotify();
977
978 typedef void ( *ToolMode )();
979 ToolMode g_currentToolMode = 0;
980 bool g_currentToolModeSupportsComponentEditing = false;
981 ToolMode g_defaultToolMode = 0;
982
983
984
985 void SelectionSystem_DefaultMode(){
986         GlobalSelectionSystem().SetMode( SelectionSystem::ePrimitive );
987         GlobalSelectionSystem().SetComponentMode( SelectionSystem::eDefault );
988         ModeChangeNotify();
989 }
990
991
992 bool EdgeMode(){
993         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
994                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eEdge;
995 }
996
997 bool VertexMode(){
998         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
999                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex;
1000 }
1001
1002 bool FaceMode(){
1003         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1004                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace;
1005 }
1006
1007 template<bool( *BoolFunction ) ( )>
1008 class BoolFunctionExport
1009 {
1010 public:
1011 static void apply( const BoolImportCallback& importCallback ){
1012         importCallback( BoolFunction() );
1013 }
1014 };
1015
1016 typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<EdgeMode>::apply> EdgeModeApplyCaller;
1017 EdgeModeApplyCaller g_edgeMode_button_caller;
1018 BoolExportCallback g_edgeMode_button_callback( g_edgeMode_button_caller );
1019 ToggleItem g_edgeMode_button( g_edgeMode_button_callback );
1020
1021 typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<VertexMode>::apply> VertexModeApplyCaller;
1022 VertexModeApplyCaller g_vertexMode_button_caller;
1023 BoolExportCallback g_vertexMode_button_callback( g_vertexMode_button_caller );
1024 ToggleItem g_vertexMode_button( g_vertexMode_button_callback );
1025
1026 typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<FaceMode>::apply> FaceModeApplyCaller;
1027 FaceModeApplyCaller g_faceMode_button_caller;
1028 BoolExportCallback g_faceMode_button_callback( g_faceMode_button_caller );
1029 ToggleItem g_faceMode_button( g_faceMode_button_callback );
1030
1031 void ComponentModeChanged(){
1032         g_edgeMode_button.update();
1033         g_vertexMode_button.update();
1034         g_faceMode_button.update();
1035 }
1036
1037 void ComponentMode_SelectionChanged( const Selectable& selectable ){
1038         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1039                  && GlobalSelectionSystem().countSelected() == 0 ) {
1040                 SelectionSystem_DefaultMode();
1041                 ComponentModeChanged();
1042         }
1043 }
1044
1045 void SelectEdgeMode(){
1046 #if 0
1047         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1048                 GlobalSelectionSystem().Select( false );
1049         }
1050 #endif
1051
1052         if ( EdgeMode() ) {
1053                 SelectionSystem_DefaultMode();
1054         }
1055         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1056                 if ( !g_currentToolModeSupportsComponentEditing ) {
1057                         g_defaultToolMode();
1058                 }
1059
1060                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1061                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eEdge );
1062         }
1063
1064         ComponentModeChanged();
1065
1066         ModeChangeNotify();
1067 }
1068
1069 void SelectVertexMode(){
1070 #if 0
1071         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1072                 GlobalSelectionSystem().Select( false );
1073         }
1074 #endif
1075
1076         if ( VertexMode() ) {
1077                 SelectionSystem_DefaultMode();
1078         }
1079         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1080                 if ( !g_currentToolModeSupportsComponentEditing ) {
1081                         g_defaultToolMode();
1082                 }
1083
1084                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1085                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eVertex );
1086         }
1087
1088         ComponentModeChanged();
1089
1090         ModeChangeNotify();
1091 }
1092
1093 void SelectFaceMode(){
1094 #if 0
1095         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1096                 GlobalSelectionSystem().Select( false );
1097         }
1098 #endif
1099
1100         if ( FaceMode() ) {
1101                 SelectionSystem_DefaultMode();
1102         }
1103         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1104                 if ( !g_currentToolModeSupportsComponentEditing ) {
1105                         g_defaultToolMode();
1106                 }
1107
1108                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1109                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eFace );
1110         }
1111
1112         ComponentModeChanged();
1113
1114         ModeChangeNotify();
1115 }
1116
1117
1118 class CloneSelected : public scene::Graph::Walker
1119 {
1120 bool doMakeUnique;
1121 NodeSmartReference worldspawn;
1122 public:
1123 CloneSelected( bool d ) : doMakeUnique( d ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){
1124 }
1125 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1126         if ( path.size() == 1 ) {
1127                 return true;
1128         }
1129
1130         // ignore worldspawn, but keep checking children
1131         NodeSmartReference me( path.top().get() );
1132         if ( me == worldspawn ) {
1133                 return true;
1134         }
1135
1136         if ( !path.top().get().isRoot() ) {
1137                 Selectable* selectable = Instance_getSelectable( instance );
1138                 if ( selectable != 0
1139                          && selectable->isSelected() ) {
1140                         return false;
1141                 }
1142         }
1143
1144         return true;
1145 }
1146 void post( const scene::Path& path, scene::Instance& instance ) const {
1147         if ( path.size() == 1 ) {
1148                 return;
1149         }
1150
1151         // ignore worldspawn, but keep checking children
1152         NodeSmartReference me( path.top().get() );
1153         if ( me == worldspawn ) {
1154                 return;
1155         }
1156
1157         if ( !path.top().get().isRoot() ) {
1158                 Selectable* selectable = Instance_getSelectable( instance );
1159                 if ( selectable != 0
1160                          && selectable->isSelected() ) {
1161                         NodeSmartReference clone( Node_Clone( path.top() ) );
1162                         if ( doMakeUnique ) {
1163                                 Map_gatherNamespaced( clone );
1164                         }
1165                         Node_getTraversable( path.parent().get() )->insert( clone );
1166                 }
1167         }
1168 }
1169 };
1170
1171 void Scene_Clone_Selected( scene::Graph& graph, bool doMakeUnique ){
1172         graph.traverse( CloneSelected( doMakeUnique ) );
1173
1174         Map_mergeClonedNames();
1175 }
1176
1177 enum ENudgeDirection
1178 {
1179         eNudgeUp = 1,
1180         eNudgeDown = 3,
1181         eNudgeLeft = 0,
1182         eNudgeRight = 2,
1183 };
1184
1185 struct AxisBase
1186 {
1187         Vector3 x;
1188         Vector3 y;
1189         Vector3 z;
1190         AxisBase( const Vector3& x_, const Vector3& y_, const Vector3& z_ )
1191                 : x( x_ ), y( y_ ), z( z_ ){
1192         }
1193 };
1194
1195 AxisBase AxisBase_forViewType( VIEWTYPE viewtype ){
1196         switch ( viewtype )
1197         {
1198         case XY:
1199                 return AxisBase( g_vector3_axis_x, g_vector3_axis_y, g_vector3_axis_z );
1200         case XZ:
1201                 return AxisBase( g_vector3_axis_x, g_vector3_axis_z, g_vector3_axis_y );
1202         case YZ:
1203                 return AxisBase( g_vector3_axis_y, g_vector3_axis_z, g_vector3_axis_x );
1204         }
1205
1206         ERROR_MESSAGE( "invalid viewtype" );
1207         return AxisBase( Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ) );
1208 }
1209
1210 Vector3 AxisBase_axisForDirection( const AxisBase& axes, ENudgeDirection direction ){
1211         switch ( direction )
1212         {
1213         case eNudgeLeft:
1214                 return vector3_negated( axes.x );
1215         case eNudgeUp:
1216                 return axes.y;
1217         case eNudgeRight:
1218                 return axes.x;
1219         case eNudgeDown:
1220                 return vector3_negated( axes.y );
1221         }
1222
1223         ERROR_MESSAGE( "invalid direction" );
1224         return Vector3( 0, 0, 0 );
1225 }
1226
1227 void NudgeSelection( ENudgeDirection direction, float fAmount, VIEWTYPE viewtype ){
1228         AxisBase axes( AxisBase_forViewType( viewtype ) );
1229         Vector3 view_direction( vector3_negated( axes.z ) );
1230         Vector3 nudge( vector3_scaled( AxisBase_axisForDirection( axes, direction ), fAmount ) );
1231         GlobalSelectionSystem().NudgeManipulator( nudge, view_direction );
1232 }
1233
1234 void Selection_Clone(){
1235         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
1236                 UndoableCommand undo( "cloneSelected" );
1237
1238                 Scene_Clone_Selected( GlobalSceneGraph(), false );
1239
1240                 //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1241                 //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1242         }
1243 }
1244
1245 void Selection_Clone_MakeUnique(){
1246         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
1247                 UndoableCommand undo( "cloneSelectedMakeUnique" );
1248
1249                 Scene_Clone_Selected( GlobalSceneGraph(), true );
1250
1251                 //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1252                 //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1253         }
1254 }
1255
1256 // called when the escape key is used (either on the main window or on an inspector)
1257 void Selection_Deselect(){
1258         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1259                 if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
1260                         GlobalSelectionSystem().setSelectedAllComponents( false );
1261                 }
1262                 else
1263                 {
1264                         SelectionSystem_DefaultMode();
1265                         ComponentModeChanged();
1266                 }
1267         }
1268         else
1269         {
1270                 if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
1271                         GlobalSelectionSystem().setSelectedAllComponents( false );
1272                 }
1273                 else
1274                 {
1275                         GlobalSelectionSystem().setSelectedAll( false );
1276                 }
1277         }
1278 }
1279
1280
1281 void Selection_NudgeUp(){
1282         UndoableCommand undo( "nudgeSelectedUp" );
1283         NudgeSelection( eNudgeUp, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1284 }
1285
1286 void Selection_NudgeDown(){
1287         UndoableCommand undo( "nudgeSelectedDown" );
1288         NudgeSelection( eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1289 }
1290
1291 void Selection_NudgeLeft(){
1292         UndoableCommand undo( "nudgeSelectedLeft" );
1293         NudgeSelection( eNudgeLeft, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1294 }
1295
1296 void Selection_NudgeRight(){
1297         UndoableCommand undo( "nudgeSelectedRight" );
1298         NudgeSelection( eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1299 }
1300
1301
1302 void TranslateToolExport( const BoolImportCallback& importCallback ){
1303         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eTranslate );
1304 }
1305
1306 void RotateToolExport( const BoolImportCallback& importCallback ){
1307         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eRotate );
1308 }
1309
1310 void ScaleToolExport( const BoolImportCallback& importCallback ){
1311         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eScale );
1312 }
1313
1314 void DragToolExport( const BoolImportCallback& importCallback ){
1315         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag );
1316 }
1317
1318 void ClipperToolExport( const BoolImportCallback& importCallback ){
1319         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip );
1320 }
1321
1322 FreeCaller1<const BoolImportCallback&, TranslateToolExport> g_translatemode_button_caller;
1323 BoolExportCallback g_translatemode_button_callback( g_translatemode_button_caller );
1324 ToggleItem g_translatemode_button( g_translatemode_button_callback );
1325
1326 FreeCaller1<const BoolImportCallback&, RotateToolExport> g_rotatemode_button_caller;
1327 BoolExportCallback g_rotatemode_button_callback( g_rotatemode_button_caller );
1328 ToggleItem g_rotatemode_button( g_rotatemode_button_callback );
1329
1330 FreeCaller1<const BoolImportCallback&, ScaleToolExport> g_scalemode_button_caller;
1331 BoolExportCallback g_scalemode_button_callback( g_scalemode_button_caller );
1332 ToggleItem g_scalemode_button( g_scalemode_button_callback );
1333
1334 FreeCaller1<const BoolImportCallback&, DragToolExport> g_dragmode_button_caller;
1335 BoolExportCallback g_dragmode_button_callback( g_dragmode_button_caller );
1336 ToggleItem g_dragmode_button( g_dragmode_button_callback );
1337
1338 FreeCaller1<const BoolImportCallback&, ClipperToolExport> g_clipper_button_caller;
1339 BoolExportCallback g_clipper_button_callback( g_clipper_button_caller );
1340 ToggleItem g_clipper_button( g_clipper_button_callback );
1341
1342 void ToolChanged(){
1343         g_translatemode_button.update();
1344         g_rotatemode_button.update();
1345         g_scalemode_button.update();
1346         g_dragmode_button.update();
1347         g_clipper_button.update();
1348 }
1349
1350 const char* const c_ResizeMode_status = "QE4 Drag Tool: move and resize objects";
1351
1352 void DragMode(){
1353         if ( g_currentToolMode == DragMode && g_defaultToolMode != DragMode ) {
1354                 g_defaultToolMode();
1355         }
1356         else
1357         {
1358                 g_currentToolMode = DragMode;
1359                 g_currentToolModeSupportsComponentEditing = true;
1360
1361                 OnClipMode( false );
1362
1363                 Sys_Status( c_ResizeMode_status );
1364                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eDrag );
1365                 ToolChanged();
1366                 ModeChangeNotify();
1367         }
1368 }
1369
1370
1371 const char* const c_TranslateMode_status = "Translate Tool: translate objects and components";
1372
1373 void TranslateMode(){
1374         if ( g_currentToolMode == TranslateMode && g_defaultToolMode != TranslateMode ) {
1375                 g_defaultToolMode();
1376         }
1377         else
1378         {
1379                 g_currentToolMode = TranslateMode;
1380                 g_currentToolModeSupportsComponentEditing = true;
1381
1382                 OnClipMode( false );
1383
1384                 Sys_Status( c_TranslateMode_status );
1385                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eTranslate );
1386                 ToolChanged();
1387                 ModeChangeNotify();
1388         }
1389 }
1390
1391 const char* const c_RotateMode_status = "Rotate Tool: rotate objects and components";
1392
1393 void RotateMode(){
1394         if ( g_currentToolMode == RotateMode && g_defaultToolMode != RotateMode ) {
1395                 g_defaultToolMode();
1396         }
1397         else
1398         {
1399                 g_currentToolMode = RotateMode;
1400                 g_currentToolModeSupportsComponentEditing = true;
1401
1402                 OnClipMode( false );
1403
1404                 Sys_Status( c_RotateMode_status );
1405                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eRotate );
1406                 ToolChanged();
1407                 ModeChangeNotify();
1408         }
1409 }
1410
1411 const char* const c_ScaleMode_status = "Scale Tool: scale objects and components";
1412
1413 void ScaleMode(){
1414         if ( g_currentToolMode == ScaleMode && g_defaultToolMode != ScaleMode ) {
1415                 g_defaultToolMode();
1416         }
1417         else
1418         {
1419                 g_currentToolMode = ScaleMode;
1420                 g_currentToolModeSupportsComponentEditing = true;
1421
1422                 OnClipMode( false );
1423
1424                 Sys_Status( c_ScaleMode_status );
1425                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eScale );
1426                 ToolChanged();
1427                 ModeChangeNotify();
1428         }
1429 }
1430
1431
1432 const char* const c_ClipperMode_status = "Clipper Tool: apply clip planes to objects";
1433
1434
1435 void ClipperMode(){
1436         if ( g_currentToolMode == ClipperMode && g_defaultToolMode != ClipperMode ) {
1437                 g_defaultToolMode();
1438         }
1439         else
1440         {
1441                 g_currentToolMode = ClipperMode;
1442                 g_currentToolModeSupportsComponentEditing = false;
1443
1444                 SelectionSystem_DefaultMode();
1445
1446                 OnClipMode( true );
1447
1448                 Sys_Status( c_ClipperMode_status );
1449                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eClip );
1450                 ToolChanged();
1451                 ModeChangeNotify();
1452         }
1453 }
1454
1455
1456 void Texdef_Rotate( float angle ){
1457         StringOutputStream command;
1458         command << "brushRotateTexture -angle " << angle;
1459         UndoableCommand undo( command.c_str() );
1460         Select_RotateTexture( angle );
1461 }
1462
1463 void Texdef_RotateClockwise(){
1464         Texdef_Rotate( static_cast<float>( fabs( g_si_globals.rotate ) ) );
1465 }
1466
1467 void Texdef_RotateAntiClockwise(){
1468         Texdef_Rotate( static_cast<float>( -fabs( g_si_globals.rotate ) ) );
1469 }
1470
1471 void Texdef_Scale( float x, float y ){
1472         StringOutputStream command;
1473         command << "brushScaleTexture -x " << x << " -y " << y;
1474         UndoableCommand undo( command.c_str() );
1475         Select_ScaleTexture( x, y );
1476 }
1477
1478 void Texdef_ScaleUp(){
1479         Texdef_Scale( 0, g_si_globals.scale[1] );
1480 }
1481
1482 void Texdef_ScaleDown(){
1483         Texdef_Scale( 0, -g_si_globals.scale[1] );
1484 }
1485
1486 void Texdef_ScaleLeft(){
1487         Texdef_Scale( -g_si_globals.scale[0],0 );
1488 }
1489
1490 void Texdef_ScaleRight(){
1491         Texdef_Scale( g_si_globals.scale[0],0 );
1492 }
1493
1494 void Texdef_Shift( float x, float y ){
1495         StringOutputStream command;
1496         command << "brushShiftTexture -x " << x << " -y " << y;
1497         UndoableCommand undo( command.c_str() );
1498         Select_ShiftTexture( x, y );
1499 }
1500
1501 void Texdef_ShiftLeft(){
1502         Texdef_Shift( -g_si_globals.shift[0], 0 );
1503 }
1504
1505 void Texdef_ShiftRight(){
1506         Texdef_Shift( g_si_globals.shift[0], 0 );
1507 }
1508
1509 void Texdef_ShiftUp(){
1510         Texdef_Shift( 0, g_si_globals.shift[1] );
1511 }
1512
1513 void Texdef_ShiftDown(){
1514         Texdef_Shift( 0, -g_si_globals.shift[1] );
1515 }
1516
1517
1518
1519 class SnappableSnapToGridSelected : public scene::Graph::Walker
1520 {
1521 float m_snap;
1522 public:
1523 SnappableSnapToGridSelected( float snap )
1524         : m_snap( snap ){
1525 }
1526 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1527         if ( path.top().get().visible() ) {
1528                 Snappable* snappable = Node_getSnappable( path.top() );
1529                 if ( snappable != 0
1530                          && Instance_getSelectable( instance )->isSelected() ) {
1531                         snappable->snapto( m_snap );
1532                 }
1533         }
1534         return true;
1535 }
1536 };
1537
1538 void Scene_SnapToGrid_Selected( scene::Graph& graph, float snap ){
1539         graph.traverse( SnappableSnapToGridSelected( snap ) );
1540 }
1541
1542 class ComponentSnappableSnapToGridSelected : public scene::Graph::Walker
1543 {
1544 float m_snap;
1545 public:
1546 ComponentSnappableSnapToGridSelected( float snap )
1547         : m_snap( snap ){
1548 }
1549 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1550         if ( path.top().get().visible() ) {
1551                 ComponentSnappable* componentSnappable = Instance_getComponentSnappable( instance );
1552                 if ( componentSnappable != 0
1553                          && Instance_getSelectable( instance )->isSelected() ) {
1554                         componentSnappable->snapComponents( m_snap );
1555                 }
1556         }
1557         return true;
1558 }
1559 };
1560
1561 void Scene_SnapToGrid_Component_Selected( scene::Graph& graph, float snap ){
1562         graph.traverse( ComponentSnappableSnapToGridSelected( snap ) );
1563 }
1564
1565 void Selection_SnapToGrid(){
1566         StringOutputStream command;
1567         command << "snapSelected -grid " << GetGridSize();
1568         UndoableCommand undo( command.c_str() );
1569
1570         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1571                 Scene_SnapToGrid_Component_Selected( GlobalSceneGraph(), GetGridSize() );
1572         }
1573         else
1574         {
1575                 Scene_SnapToGrid_Selected( GlobalSceneGraph(), GetGridSize() );
1576         }
1577 }
1578
1579
1580 static gint qe_every_second( gpointer data ){
1581         GdkModifierType mask;
1582
1583         gdk_window_get_pointer( 0, 0, 0, &mask );
1584
1585         if ( ( mask & ( GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK ) ) == 0 ) {
1586                 QE_CheckAutoSave();
1587         }
1588
1589         return TRUE;
1590 }
1591
1592 guint s_qe_every_second_id = 0;
1593
1594 void EverySecondTimer_enable(){
1595         if ( s_qe_every_second_id == 0 ) {
1596                 s_qe_every_second_id = g_timeout_add( 1000, qe_every_second, 0 );
1597         }
1598 }
1599
1600 void EverySecondTimer_disable(){
1601         if ( s_qe_every_second_id != 0 ) {
1602                 g_source_remove( s_qe_every_second_id );
1603                 s_qe_every_second_id = 0;
1604         }
1605 }
1606
1607 gint window_realize_remove_decoration( ui::Widget widget, gpointer data ){
1608         gdk_window_set_decorations( gtk_widget_get_window(widget), (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MENU | GDK_DECOR_MINIMIZE | GDK_DECOR_MAXIMIZE ) );
1609         return FALSE;
1610 }
1611
1612 class WaitDialog
1613 {
1614 public:
1615 ui::Window m_window{ui::null};
1616 ui::Label m_label{ui::null};
1617 };
1618
1619 WaitDialog create_wait_dialog( const char* title, const char* text ){
1620         WaitDialog dialog;
1621
1622         dialog.m_window = MainFrame_getWindow().create_floating_window(title);
1623         gtk_window_set_resizable( dialog.m_window, FALSE );
1624         gtk_container_set_border_width( GTK_CONTAINER( dialog.m_window ), 0 );
1625         gtk_window_set_position( dialog.m_window, GTK_WIN_POS_CENTER_ON_PARENT );
1626
1627         dialog.m_window.connect( "realize", G_CALLBACK( window_realize_remove_decoration ), 0 );
1628
1629         {
1630                 dialog.m_label = ui::Label( text );
1631                 gtk_misc_set_alignment( GTK_MISC( dialog.m_label ), 0.0, 0.5 );
1632                 gtk_label_set_justify( dialog.m_label, GTK_JUSTIFY_LEFT );
1633                 dialog.m_label.show();
1634                 gtk_widget_set_size_request( dialog.m_label , 200, -1 );
1635
1636                 dialog.m_window.add(dialog.m_label);
1637         }
1638         return dialog;
1639 }
1640
1641 namespace
1642 {
1643 clock_t g_lastRedrawTime = 0;
1644 const clock_t c_redrawInterval = clock_t( CLOCKS_PER_SEC / 10 );
1645
1646 bool redrawRequired(){
1647         clock_t currentTime = std::clock();
1648         if ( currentTime - g_lastRedrawTime >= c_redrawInterval ) {
1649                 g_lastRedrawTime = currentTime;
1650                 return true;
1651         }
1652         return false;
1653 }
1654 }
1655
1656 bool MainFrame_isActiveApp(){
1657         //globalOutputStream() << "listing\n";
1658         GList* list = gtk_window_list_toplevels();
1659         for ( GList* i = list; i != 0; i = g_list_next( i ) )
1660         {
1661                 //globalOutputStream() << "toplevel.. ";
1662                 if ( gtk_window_is_active( GTK_WINDOW( i->data ) ) ) {
1663                         //globalOutputStream() << "is active\n";
1664                         return true;
1665                 }
1666                 //globalOutputStream() << "not active\n";
1667         }
1668         return false;
1669 }
1670
1671 typedef std::list<CopiedString> StringStack;
1672 StringStack g_wait_stack;
1673 WaitDialog g_wait;
1674
1675 bool ScreenUpdates_Enabled(){
1676         return g_wait_stack.empty();
1677 }
1678
1679 void ScreenUpdates_process(){
1680         if ( redrawRequired() && g_wait.m_window.visible() ) {
1681                 ui::process();
1682         }
1683 }
1684
1685
1686 void ScreenUpdates_Disable( const char* message, const char* title ){
1687         if ( g_wait_stack.empty() ) {
1688                 EverySecondTimer_disable();
1689
1690                 ui::process();
1691
1692                 bool isActiveApp = MainFrame_isActiveApp();
1693
1694                 g_wait = create_wait_dialog( title, message );
1695                 gtk_grab_add( g_wait.m_window  );
1696
1697                 if ( isActiveApp ) {
1698                         g_wait.m_window.show();
1699                         ScreenUpdates_process();
1700                 }
1701         }
1702         else if ( g_wait.m_window.visible() ) {
1703                 g_wait.m_label.text(message);
1704                 ScreenUpdates_process();
1705         }
1706         g_wait_stack.push_back( message );
1707 }
1708
1709 void ScreenUpdates_Enable(){
1710         ASSERT_MESSAGE( !ScreenUpdates_Enabled(), "screen updates already enabled" );
1711         g_wait_stack.pop_back();
1712         if ( g_wait_stack.empty() ) {
1713                 EverySecondTimer_enable();
1714                 //gtk_widget_set_sensitive(MainFrame_getWindow(), TRUE);
1715
1716                 gtk_grab_remove( g_wait.m_window  );
1717                 destroy_floating_window( g_wait.m_window );
1718                 g_wait.m_window = ui::Window{ui::null};
1719
1720                 //gtk_window_present(MainFrame_getWindow());
1721         }
1722         else if ( g_wait.m_window.visible() ) {
1723                 g_wait.m_label.text(g_wait_stack.back().c_str());
1724                 ScreenUpdates_process();
1725         }
1726 }
1727
1728
1729
1730 void GlobalCamera_UpdateWindow(){
1731         if ( g_pParentWnd != 0 ) {
1732                 CamWnd_Update( *g_pParentWnd->GetCamWnd() );
1733         }
1734 }
1735
1736 void XY_UpdateWindow( MainFrame& mainframe ){
1737         if ( mainframe.GetXYWnd() != 0 ) {
1738                 XYWnd_Update( *mainframe.GetXYWnd() );
1739         }
1740 }
1741
1742 void XZ_UpdateWindow( MainFrame& mainframe ){
1743         if ( mainframe.GetXZWnd() != 0 ) {
1744                 XYWnd_Update( *mainframe.GetXZWnd() );
1745         }
1746 }
1747
1748 void YZ_UpdateWindow( MainFrame& mainframe ){
1749         if ( mainframe.GetYZWnd() != 0 ) {
1750                 XYWnd_Update( *mainframe.GetYZWnd() );
1751         }
1752 }
1753
1754 void XY_UpdateAllWindows( MainFrame& mainframe ){
1755         XY_UpdateWindow( mainframe );
1756         XZ_UpdateWindow( mainframe );
1757         YZ_UpdateWindow( mainframe );
1758 }
1759
1760 void XY_UpdateAllWindows(){
1761         if ( g_pParentWnd != 0 ) {
1762                 XY_UpdateAllWindows( *g_pParentWnd );
1763         }
1764 }
1765
1766 void UpdateAllWindows(){
1767         GlobalCamera_UpdateWindow();
1768         XY_UpdateAllWindows();
1769 }
1770
1771
1772 void ModeChangeNotify(){
1773         SceneChangeNotify();
1774 }
1775
1776 void ClipperChangeNotify(){
1777         GlobalCamera_UpdateWindow();
1778         XY_UpdateAllWindows();
1779 }
1780
1781
1782 LatchedInt g_Layout_viewStyle( 0, "Window Layout" );
1783 LatchedBool g_Layout_enableDetachableMenus( true, "Detachable Menus" );
1784 LatchedBool g_Layout_enablePatchToolbar( true, "Patch Toolbar" );
1785 LatchedBool g_Layout_enablePluginToolbar( true, "Plugin Toolbar" );
1786
1787
1788
1789 ui::MenuItem create_file_menu(){
1790         // File menu
1791         auto file_menu_item = new_sub_menu_item_with_mnemonic( "_File" );
1792         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( file_menu_item ) ));
1793         if ( g_Layout_enableDetachableMenus.m_value ) {
1794                 menu_tearoff( menu );
1795         }
1796
1797         create_menu_item_with_mnemonic( menu, "_New Map", "NewMap" );
1798         menu_separator( menu );
1799
1800 #if 0
1801         //++timo temporary experimental stuff for sleep mode..
1802         create_menu_item_with_mnemonic( menu, "_Sleep", "Sleep" );
1803         menu_separator( menu );
1804         // end experimental
1805 #endif
1806
1807         create_menu_item_with_mnemonic( menu, "_Open...", "OpenMap" );
1808
1809         create_menu_item_with_mnemonic( menu, "_Import...", "ImportMap" );
1810         create_menu_item_with_mnemonic( menu, "_Save", "SaveMap" );
1811         create_menu_item_with_mnemonic( menu, "Save _as...", "SaveMapAs" );
1812         create_menu_item_with_mnemonic( menu, "_Export selected...", "ExportSelected" );
1813         menu_separator( menu );
1814         create_menu_item_with_mnemonic( menu, "Save re_gion...", "SaveRegion" );
1815         menu_separator( menu );
1816         create_menu_item_with_mnemonic( menu, "_Refresh models", "RefreshReferences" );
1817         menu_separator( menu );
1818         create_menu_item_with_mnemonic( menu, "Pro_ject settings...", "ProjectSettings" );
1819         menu_separator( menu );
1820         create_menu_item_with_mnemonic( menu, "_Pointfile...", "TogglePointfile" );
1821         menu_separator( menu );
1822         MRU_constructMenu( menu );
1823         menu_separator( menu );
1824         create_menu_item_with_mnemonic( menu, "E_xit", "Exit" );
1825
1826         return file_menu_item;
1827 }
1828
1829 ui::MenuItem create_edit_menu(){
1830         // Edit menu
1831         auto edit_menu_item = new_sub_menu_item_with_mnemonic( "_Edit" );
1832         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( edit_menu_item ) ));
1833         if ( g_Layout_enableDetachableMenus.m_value ) {
1834                 menu_tearoff( menu );
1835         }
1836         create_menu_item_with_mnemonic( menu, "_Undo", "Undo" );
1837         create_menu_item_with_mnemonic( menu, "_Redo", "Redo" );
1838         menu_separator( menu );
1839         create_menu_item_with_mnemonic( menu, "_Copy", "Copy" );
1840         create_menu_item_with_mnemonic( menu, "_Paste", "Paste" );
1841         create_menu_item_with_mnemonic( menu, "P_aste To Camera", "PasteToCamera" );
1842         menu_separator( menu );
1843         create_menu_item_with_mnemonic( menu, "_Duplicate", "CloneSelection" );
1844         create_menu_item_with_mnemonic( menu, "Duplicate, make uni_que", "CloneSelectionAndMakeUnique" );
1845         create_menu_item_with_mnemonic( menu, "D_elete", "DeleteSelection" );
1846         menu_separator( menu );
1847         create_menu_item_with_mnemonic( menu, "Pa_rent", "ParentSelection" );
1848         menu_separator( menu );
1849         create_menu_item_with_mnemonic( menu, "C_lear Selection", "UnSelectSelection" );
1850         create_menu_item_with_mnemonic( menu, "_Invert Selection", "InvertSelection" );
1851         create_menu_item_with_mnemonic( menu, "Select i_nside", "SelectInside" );
1852         create_menu_item_with_mnemonic( menu, "Select _touching", "SelectTouching" );
1853
1854         auto convert_menu = create_sub_menu_with_mnemonic( menu, "E_xpand Selection" );
1855         if ( g_Layout_enableDetachableMenus.m_value ) {
1856                 menu_tearoff( convert_menu );
1857         }
1858         create_menu_item_with_mnemonic( convert_menu, "To Whole _Entities", "ExpandSelectionToEntities" );
1859
1860         menu_separator( menu );
1861         create_menu_item_with_mnemonic( menu, "Pre_ferences...", "Preferences" );
1862
1863         return edit_menu_item;
1864 }
1865
1866 void fill_view_xy_top_menu( ui::Menu menu ){
1867         create_check_menu_item_with_mnemonic( menu, "XY (Top) View", "ToggleView" );
1868 }
1869
1870
1871 void fill_view_yz_side_menu( ui::Menu menu ){
1872         create_check_menu_item_with_mnemonic( menu, "YZ (Side) View", "ToggleSideView" );
1873 }
1874
1875
1876 void fill_view_xz_front_menu( ui::Menu menu ){
1877         create_check_menu_item_with_mnemonic( menu, "XZ (Front) View", "ToggleFrontView" );
1878 }
1879
1880
1881 ui::Widget g_toggle_z_item{ui::null};
1882 ui::Widget g_toggle_console_item{ui::null};
1883 ui::Widget g_toggle_entity_item{ui::null};
1884 ui::Widget g_toggle_entitylist_item{ui::null};
1885
1886 ui::MenuItem create_view_menu( MainFrame::EViewStyle style ){
1887         // View menu
1888         auto view_menu_item = new_sub_menu_item_with_mnemonic( "Vie_w" );
1889         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( view_menu_item ) ));
1890         if ( g_Layout_enableDetachableMenus.m_value ) {
1891                 menu_tearoff( menu );
1892         }
1893
1894         if ( style == MainFrame::eFloating ) {
1895                 fill_view_camera_menu( menu );
1896                 fill_view_xy_top_menu( menu );
1897                 fill_view_yz_side_menu( menu );
1898                 fill_view_xz_front_menu( menu );
1899         }
1900         if ( style == MainFrame::eFloating || style == MainFrame::eSplit ) {
1901                 create_menu_item_with_mnemonic( menu, "Console View", "ToggleConsole" );
1902                 create_menu_item_with_mnemonic( menu, "Texture Browser", "ToggleTextures" );
1903                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ToggleEntityInspector" );
1904         }
1905         else
1906         {
1907                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ViewEntityInfo" );
1908         }
1909         create_menu_item_with_mnemonic( menu, "_Surface Inspector", "SurfaceInspector" );
1910         create_menu_item_with_mnemonic( menu, "Entity List", "EntityList" );
1911
1912         menu_separator( menu );
1913         {
1914                 auto camera_menu = create_sub_menu_with_mnemonic( menu, "Camera" );
1915                 if ( g_Layout_enableDetachableMenus.m_value ) {
1916                         menu_tearoff( camera_menu );
1917                 }
1918                 create_menu_item_with_mnemonic( camera_menu, "_Center", "CenterView" );
1919                 create_menu_item_with_mnemonic( camera_menu, "_Up Floor", "UpFloor" );
1920                 create_menu_item_with_mnemonic( camera_menu, "_Down Floor", "DownFloor" );
1921                 menu_separator( camera_menu );
1922                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane In", "CubicClipZoomIn" );
1923                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane Out", "CubicClipZoomOut" );
1924                 menu_separator( camera_menu );
1925                 create_menu_item_with_mnemonic( camera_menu, "Next leak spot", "NextLeakSpot" );
1926                 create_menu_item_with_mnemonic( camera_menu, "Previous leak spot", "PrevLeakSpot" );
1927                 menu_separator( camera_menu );
1928                 create_menu_item_with_mnemonic( camera_menu, "Look Through Selected", "LookThroughSelected" );
1929                 create_menu_item_with_mnemonic( camera_menu, "Look Through Camera", "LookThroughCamera" );
1930         }
1931         menu_separator( menu );
1932         {
1933                 auto orthographic_menu = create_sub_menu_with_mnemonic( menu, "Orthographic" );
1934                 if ( g_Layout_enableDetachableMenus.m_value ) {
1935                         menu_tearoff( orthographic_menu );
1936                 }
1937                 if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
1938                         create_menu_item_with_mnemonic( orthographic_menu, "_Next (XY, YZ, XY)", "NextView" );
1939                         create_menu_item_with_mnemonic( orthographic_menu, "XY (Top)", "ViewTop" );
1940                         create_menu_item_with_mnemonic( orthographic_menu, "YZ", "ViewSide" );
1941                         create_menu_item_with_mnemonic( orthographic_menu, "XZ", "ViewFront" );
1942                         menu_separator( orthographic_menu );
1943                 }
1944
1945                 create_menu_item_with_mnemonic( orthographic_menu, "_XY 100%", "Zoom100" );
1946                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _In", "ZoomIn" );
1947                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _Out", "ZoomOut" );
1948         }
1949
1950         menu_separator( menu );
1951
1952         {
1953                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Show" );
1954                 if ( g_Layout_enableDetachableMenus.m_value ) {
1955                         menu_tearoff( menu_in_menu );
1956                 }
1957                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Angles", "ShowAngles" );
1958                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Names", "ShowNames" );
1959                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Blocks", "ShowBlocks" );
1960                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show C_oordinates", "ShowCoordinates" );
1961                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Window Outline", "ShowWindowOutline" );
1962                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Axes", "ShowAxes" );
1963                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Workzone", "ShowWorkzone" );
1964                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Stats", "ShowStats" );
1965         }
1966
1967         {
1968                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Filter" );
1969                 if ( g_Layout_enableDetachableMenus.m_value ) {
1970                         menu_tearoff( menu_in_menu );
1971                 }
1972                 Filters_constructMenu( menu_in_menu );
1973         }
1974         menu_separator( menu );
1975         {
1976                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Hide/Show" );
1977                 if ( g_Layout_enableDetachableMenus.m_value ) {
1978                         menu_tearoff( menu_in_menu );
1979                 }
1980                 create_menu_item_with_mnemonic( menu_in_menu, "Hide Selected", "HideSelected" );
1981                 create_menu_item_with_mnemonic( menu_in_menu, "Show Hidden", "ShowHidden" );
1982         }
1983         menu_separator( menu );
1984         {
1985                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Region" );
1986                 if ( g_Layout_enableDetachableMenus.m_value ) {
1987                         menu_tearoff( menu_in_menu );
1988                 }
1989                 create_menu_item_with_mnemonic( menu_in_menu, "_Off", "RegionOff" );
1990                 create_menu_item_with_mnemonic( menu_in_menu, "_Set XY", "RegionSetXY" );
1991                 create_menu_item_with_mnemonic( menu_in_menu, "Set _Brush", "RegionSetBrush" );
1992                 create_menu_item_with_mnemonic( menu_in_menu, "Set Se_lected Brushes", "RegionSetSelection" );
1993         }
1994
1995         command_connect_accelerator( "CenterXYView" );
1996
1997         return view_menu_item;
1998 }
1999
2000 ui::MenuItem create_selection_menu(){
2001         // Selection menu
2002         auto selection_menu_item = new_sub_menu_item_with_mnemonic( "M_odify" );
2003         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( selection_menu_item ) ));
2004         if ( g_Layout_enableDetachableMenus.m_value ) {
2005                 menu_tearoff( menu );
2006         }
2007
2008         {
2009                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Components" );
2010                 if ( g_Layout_enableDetachableMenus.m_value ) {
2011                         menu_tearoff( menu_in_menu );
2012                 }
2013                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Edges", "DragEdges" );
2014                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Vertices", "DragVertices" );
2015                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Faces", "DragFaces" );
2016         }
2017
2018         menu_separator( menu );
2019
2020         {
2021                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Nudge" );
2022                 if ( g_Layout_enableDetachableMenus.m_value ) {
2023                         menu_tearoff( menu_in_menu );
2024                 }
2025                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Left", "SelectNudgeLeft" );
2026                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Right", "SelectNudgeRight" );
2027                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Up", "SelectNudgeUp" );
2028                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Down", "SelectNudgeDown" );
2029         }
2030         {
2031                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Rotate" );
2032                 if ( g_Layout_enableDetachableMenus.m_value ) {
2033                         menu_tearoff( menu_in_menu );
2034                 }
2035                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate X", "RotateSelectionX" );
2036                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Y", "RotateSelectionY" );
2037                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Z", "RotateSelectionZ" );
2038         }
2039         {
2040                 auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Flip" );
2041                 if ( g_Layout_enableDetachableMenus.m_value ) {
2042                         menu_tearoff( menu_in_menu );
2043                 }
2044                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _X", "MirrorSelectionX" );
2045                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Y", "MirrorSelectionY" );
2046                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Z", "MirrorSelectionZ" );
2047         }
2048         menu_separator( menu );
2049         create_menu_item_with_mnemonic( menu, "Arbitrary rotation...", "ArbitraryRotation" );
2050         create_menu_item_with_mnemonic( menu, "Arbitrary scale...", "ArbitraryScale" );
2051
2052         return selection_menu_item;
2053 }
2054
2055 ui::MenuItem create_bsp_menu(){
2056         // BSP menu
2057         auto bsp_menu_item = new_sub_menu_item_with_mnemonic( "_Build" );
2058         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( bsp_menu_item ) ));
2059
2060         if ( g_Layout_enableDetachableMenus.m_value ) {
2061                 menu_tearoff( menu );
2062         }
2063
2064         create_menu_item_with_mnemonic( menu, "Customize...", "BuildMenuCustomize" );
2065
2066         menu_separator( menu );
2067
2068         Build_constructMenu( menu );
2069
2070         g_bsp_menu = menu;
2071
2072         return bsp_menu_item;
2073 }
2074
2075 ui::MenuItem create_grid_menu(){
2076         // Grid menu
2077         auto grid_menu_item = new_sub_menu_item_with_mnemonic( "_Grid" );
2078         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( grid_menu_item ) ));
2079         if ( g_Layout_enableDetachableMenus.m_value ) {
2080                 menu_tearoff( menu );
2081         }
2082
2083         Grid_constructMenu( menu );
2084
2085         return grid_menu_item;
2086 }
2087
2088 ui::MenuItem create_misc_menu(){
2089         // Misc menu
2090         auto misc_menu_item = new_sub_menu_item_with_mnemonic( "M_isc" );
2091         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( misc_menu_item ) ));
2092         if ( g_Layout_enableDetachableMenus.m_value ) {
2093                 menu_tearoff( menu );
2094         }
2095
2096 #if 0
2097         create_menu_item_with_mnemonic( menu, "_Benchmark", FreeCaller<GlobalCamera_Benchmark>() );
2098 #endif
2099     menu.add(create_colours_menu());
2100
2101         create_menu_item_with_mnemonic( menu, "Find brush...", "FindBrush" );
2102         create_menu_item_with_mnemonic( menu, "Map Info...", "MapInfo" );
2103         // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394
2104 //  create_menu_item_with_mnemonic(menu, "_Print XY View", FreeCaller<WXY_Print>());
2105         create_menu_item_with_mnemonic( menu, "_Background select", FreeCaller<WXY_BackgroundSelect>() );
2106         return misc_menu_item;
2107 }
2108
2109 ui::MenuItem create_entity_menu(){
2110         // Brush menu
2111         auto entity_menu_item = new_sub_menu_item_with_mnemonic( "E_ntity" );
2112         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( entity_menu_item ) ));
2113         if ( g_Layout_enableDetachableMenus.m_value ) {
2114                 menu_tearoff( menu );
2115         }
2116
2117         Entity_constructMenu( menu );
2118
2119         return entity_menu_item;
2120 }
2121
2122 ui::MenuItem create_brush_menu(){
2123         // Brush menu
2124         auto brush_menu_item = new_sub_menu_item_with_mnemonic( "B_rush" );
2125         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( brush_menu_item ) ));
2126         if ( g_Layout_enableDetachableMenus.m_value ) {
2127                 menu_tearoff( menu );
2128         }
2129
2130         Brush_constructMenu( menu );
2131
2132         return brush_menu_item;
2133 }
2134
2135 ui::MenuItem create_patch_menu(){
2136         // Curve menu
2137         auto patch_menu_item = new_sub_menu_item_with_mnemonic( "_Curve" );
2138         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( patch_menu_item ) ));
2139         if ( g_Layout_enableDetachableMenus.m_value ) {
2140                 menu_tearoff( menu );
2141         }
2142
2143         Patch_constructMenu( menu );
2144
2145         return patch_menu_item;
2146 }
2147
2148 ui::MenuItem create_help_menu(){
2149         // Help menu
2150         auto help_menu_item = new_sub_menu_item_with_mnemonic( "_Help" );
2151         auto menu = ui::Menu(GTK_MENU( gtk_menu_item_get_submenu( help_menu_item ) ));
2152         if ( g_Layout_enableDetachableMenus.m_value ) {
2153                 menu_tearoff( menu );
2154         }
2155
2156         create_menu_item_with_mnemonic( menu, "Manual", "OpenManual" );
2157
2158         // this creates all the per-game drop downs for the game pack helps
2159         // it will take care of hooking the Sys_OpenURL calls etc.
2160         create_game_help_menu( menu );
2161
2162         create_menu_item_with_mnemonic( menu, "Bug report", FreeCaller<OpenBugReportURL>() );
2163         create_menu_item_with_mnemonic( menu, "Shortcuts list", FreeCaller<DoCommandListDlg>() );
2164         create_menu_item_with_mnemonic( menu, "_About", FreeCaller<DoAbout>() );
2165
2166         return help_menu_item;
2167 }
2168
2169 ui::MenuBar create_main_menu( MainFrame::EViewStyle style ){
2170         auto menu_bar = ui::MenuBar(GTK_MENU_BAR( gtk_menu_bar_new() ));
2171         menu_bar.show();
2172
2173         menu_bar.add(create_file_menu());
2174         menu_bar.add(create_edit_menu());
2175         menu_bar.add(create_view_menu(style));
2176         menu_bar.add(create_selection_menu());
2177         menu_bar.add(create_bsp_menu());
2178         menu_bar.add(create_grid_menu());
2179         menu_bar.add(create_misc_menu());
2180         menu_bar.add(create_entity_menu());
2181         menu_bar.add(create_brush_menu());
2182         menu_bar.add(create_patch_menu());
2183         menu_bar.add(create_plugins_menu());
2184         menu_bar.add(create_help_menu());
2185
2186         return menu_bar;
2187 }
2188
2189
2190 void PatchInspector_registerShortcuts(){
2191         command_connect_accelerator( "PatchInspector" );
2192 }
2193
2194 void Patch_registerShortcuts(){
2195         command_connect_accelerator( "InvertCurveTextureX" );
2196         command_connect_accelerator( "InvertCurveTextureY" );
2197         command_connect_accelerator( "PatchInsertInsertColumn" );
2198         command_connect_accelerator( "PatchInsertInsertRow" );
2199         command_connect_accelerator( "PatchDeleteLastColumn" );
2200         command_connect_accelerator( "PatchDeleteLastRow" );
2201         command_connect_accelerator( "NaturalizePatch" );
2202         //command_connect_accelerator("CapCurrentCurve");
2203 }
2204
2205 void Manipulators_registerShortcuts(){
2206         toggle_add_accelerator( "MouseRotate" );
2207         toggle_add_accelerator( "MouseTranslate" );
2208         toggle_add_accelerator( "MouseScale" );
2209         toggle_add_accelerator( "MouseDrag" );
2210         toggle_add_accelerator( "ToggleClipper" );
2211 }
2212
2213 void TexdefNudge_registerShortcuts(){
2214         command_connect_accelerator( "TexRotateClock" );
2215         command_connect_accelerator( "TexRotateCounter" );
2216         command_connect_accelerator( "TexScaleUp" );
2217         command_connect_accelerator( "TexScaleDown" );
2218         command_connect_accelerator( "TexScaleLeft" );
2219         command_connect_accelerator( "TexScaleRight" );
2220         command_connect_accelerator( "TexShiftUp" );
2221         command_connect_accelerator( "TexShiftDown" );
2222         command_connect_accelerator( "TexShiftLeft" );
2223         command_connect_accelerator( "TexShiftRight" );
2224 }
2225
2226 void SelectNudge_registerShortcuts(){
2227         command_connect_accelerator( "MoveSelectionDOWN" );
2228         command_connect_accelerator( "MoveSelectionUP" );
2229         //command_connect_accelerator("SelectNudgeLeft");
2230         //command_connect_accelerator("SelectNudgeRight");
2231         //command_connect_accelerator("SelectNudgeUp");
2232         //command_connect_accelerator("SelectNudgeDown");
2233 }
2234
2235 void SnapToGrid_registerShortcuts(){
2236         command_connect_accelerator( "SnapToGrid" );
2237 }
2238
2239 void SelectByType_registerShortcuts(){
2240         command_connect_accelerator( "SelectAllOfType" );
2241 }
2242
2243 void SurfaceInspector_registerShortcuts(){
2244         command_connect_accelerator( "FitTexture" );
2245 }
2246
2247
2248 void register_shortcuts(){
2249         PatchInspector_registerShortcuts();
2250         Patch_registerShortcuts();
2251         Grid_registerShortcuts();
2252         XYWnd_registerShortcuts();
2253         CamWnd_registerShortcuts();
2254         Manipulators_registerShortcuts();
2255         SurfaceInspector_registerShortcuts();
2256         TexdefNudge_registerShortcuts();
2257         SelectNudge_registerShortcuts();
2258         SnapToGrid_registerShortcuts();
2259         SelectByType_registerShortcuts();
2260 }
2261
2262 void File_constructToolbar( ui::Toolbar toolbar ){
2263         toolbar_append_button( toolbar, "Open an existing map (CTRL + O)", "file_open.png", "OpenMap" );
2264         toolbar_append_button( toolbar, "Save the active map (CTRL + S)", "file_save.png", "SaveMap" );
2265 }
2266
2267 void UndoRedo_constructToolbar( ui::Toolbar toolbar ){
2268         toolbar_append_button( toolbar, "Undo (CTRL + Z)", "undo.png", "Undo" );
2269         toolbar_append_button( toolbar, "Redo (CTRL + Y)", "redo.png", "Redo" );
2270 }
2271
2272 void RotateFlip_constructToolbar( ui::Toolbar toolbar ){
2273         toolbar_append_button( toolbar, "x-axis Flip", "brush_flipx.png", "MirrorSelectionX" );
2274         toolbar_append_button( toolbar, "x-axis Rotate", "brush_rotatex.png", "RotateSelectionX" );
2275         toolbar_append_button( toolbar, "y-axis Flip", "brush_flipy.png", "MirrorSelectionY" );
2276         toolbar_append_button( toolbar, "y-axis Rotate", "brush_rotatey.png", "RotateSelectionY" );
2277         toolbar_append_button( toolbar, "z-axis Flip", "brush_flipz.png", "MirrorSelectionZ" );
2278         toolbar_append_button( toolbar, "z-axis Rotate", "brush_rotatez.png", "RotateSelectionZ" );
2279 }
2280
2281 void Select_constructToolbar( ui::Toolbar toolbar ){
2282         toolbar_append_button( toolbar, "Select touching", "selection_selecttouching.png", "SelectTouching" );
2283         toolbar_append_button( toolbar, "Select inside", "selection_selectinside.png", "SelectInside" );
2284 }
2285
2286 void CSG_constructToolbar( ui::Toolbar toolbar ){
2287         toolbar_append_button( toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.png", "CSGSubtract" );
2288         toolbar_append_button( toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.png", "CSGMerge" );
2289         toolbar_append_button( toolbar, "Hollow", "selection_makehollow.png", "CSGHollow" );
2290 }
2291
2292 void ComponentModes_constructToolbar( ui::Toolbar toolbar ){
2293         toolbar_append_toggle_button( toolbar, "Select Vertices (V)", "modify_vertices.png", "DragVertices" );
2294         toolbar_append_toggle_button( toolbar, "Select Edges (E)", "modify_edges.png", "DragEdges" );
2295         toolbar_append_toggle_button( toolbar, "Select Faces (F)", "modify_faces.png", "DragFaces" );
2296 }
2297
2298 void Clipper_constructToolbar( ui::Toolbar toolbar ){
2299
2300         toolbar_append_toggle_button( toolbar, "Clipper (X)", "view_clipper.png", "ToggleClipper" );
2301 }
2302
2303 void XYWnd_constructToolbar( ui::Toolbar toolbar ){
2304         toolbar_append_button( toolbar, "Change views", "view_change.png", "NextView" );
2305 }
2306
2307 void Manipulators_constructToolbar( ui::Toolbar toolbar ){
2308         toolbar_append_toggle_button( toolbar, "Translate (W)", "select_mousetranslate.png", "MouseTranslate" );
2309         toolbar_append_toggle_button( toolbar, "Rotate (R)", "select_mouserotate.png", "MouseRotate" );
2310         toolbar_append_toggle_button( toolbar, "Scale", "select_mousescale.png", "MouseScale" );
2311         toolbar_append_toggle_button( toolbar, "Resize (Q)", "select_mouseresize.png", "MouseDrag" );
2312
2313         Clipper_constructToolbar( toolbar );
2314 }
2315
2316 ui::Toolbar create_main_toolbar( MainFrame::EViewStyle style ){
2317         auto toolbar = ui::Toolbar(GTK_TOOLBAR( gtk_toolbar_new() ));
2318         gtk_orientable_set_orientation( GTK_ORIENTABLE(toolbar), GTK_ORIENTATION_HORIZONTAL );
2319         gtk_toolbar_set_style( toolbar, GTK_TOOLBAR_ICONS );
2320
2321         toolbar.show();
2322
2323         auto space = [&]() {
2324                 auto btn = ui::ToolItem(gtk_separator_tool_item_new());
2325                 btn.show();
2326                 toolbar.add(btn);
2327         };
2328
2329         File_constructToolbar( toolbar );
2330
2331         space();
2332
2333         UndoRedo_constructToolbar( toolbar );
2334
2335         space();
2336
2337         RotateFlip_constructToolbar( toolbar );
2338
2339         space();
2340
2341         Select_constructToolbar( toolbar );
2342
2343         space();
2344
2345         CSG_constructToolbar( toolbar );
2346
2347         space();
2348
2349         ComponentModes_constructToolbar( toolbar );
2350
2351         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
2352                 space();
2353
2354                 XYWnd_constructToolbar( toolbar );
2355         }
2356
2357         space();
2358
2359         CamWnd_constructToolbar( toolbar );
2360
2361         space();
2362
2363         Manipulators_constructToolbar( toolbar );
2364
2365         if ( g_Layout_enablePatchToolbar.m_value ) {
2366                 space();
2367
2368                 Patch_constructToolbar( toolbar );
2369         }
2370
2371         space();
2372
2373         toolbar_append_toggle_button( toolbar, "Texture Lock (SHIFT +T)", "texture_lock.png", "TogTexLock" );
2374
2375         space();
2376
2377         /*auto g_view_entities_button =*/ toolbar_append_button( toolbar, "Entities (N)", "entities.png", "ToggleEntityInspector" );
2378         auto g_view_console_button = toolbar_append_button( toolbar, "Console (O)", "console.png", "ToggleConsole" );
2379         auto g_view_textures_button = toolbar_append_button( toolbar, "Texture Browser (T)", "texture_browser.png", "ToggleTextures" );
2380         // TODO: call light inspector
2381         //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.png", "ToggleLightInspector");
2382
2383         space();
2384         /*auto g_refresh_models_button =*/ toolbar_append_button( toolbar, "Refresh Models", "refresh_models.png", "RefreshReferences" );
2385
2386
2387         // disable the console and texture button in the regular layouts
2388         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft ) {
2389                 gtk_widget_set_sensitive( g_view_console_button , FALSE );
2390                 gtk_widget_set_sensitive( g_view_textures_button , FALSE );
2391         }
2392
2393         return toolbar;
2394 }
2395
2396 ui::Widget create_main_statusbar( ui::Widget pStatusLabel[c_count_status] ){
2397         auto table = ui::Table( 1, c_count_status, FALSE );
2398         table.show();
2399
2400         {
2401                 auto label = ui::Label( "Label" );
2402                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
2403                 gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
2404                 label.show();
2405                 gtk_table_attach_defaults( table, label , 0, 1, 0, 1 );
2406                 pStatusLabel[c_command_status] = ui::Widget(label );
2407         }
2408
2409         for ( int i = 1; i < c_count_status; ++i )
2410         {
2411                 auto frame = ui::Frame();
2412                 frame.show();
2413                 gtk_table_attach_defaults( table, frame , i, i + 1, 0, 1 );
2414                 gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN );
2415
2416                 auto label = ui::Label( "Label" );
2417                 gtk_label_set_ellipsize( label, PANGO_ELLIPSIZE_END );
2418                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
2419                 gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
2420                 label.show();
2421                 frame.add(label);
2422                 pStatusLabel[i] = ui::Widget(label );
2423         }
2424
2425         return ui::Widget(table );
2426 }
2427
2428 #if 0
2429
2430
2431 WidgetFocusPrinter g_mainframeWidgetFocusPrinter( "mainframe" );
2432
2433 class WindowFocusPrinter
2434 {
2435 const char* m_name;
2436
2437 static gboolean frame_event( ui::Widget widget, GdkEvent* event, WindowFocusPrinter* self ){
2438         globalOutputStream() << self->m_name << " frame_event\n";
2439         return FALSE;
2440 }
2441 static gboolean keys_changed( ui::Widget widget, WindowFocusPrinter* self ){
2442         globalOutputStream() << self->m_name << " keys_changed\n";
2443         return FALSE;
2444 }
2445 static gboolean notify( ui::Window window, gpointer dummy, WindowFocusPrinter* self ){
2446         if ( gtk_window_is_active( window ) ) {
2447                 globalOutputStream() << self->m_name << " takes toplevel focus\n";
2448         }
2449         else
2450         {
2451                 globalOutputStream() << self->m_name << " loses toplevel focus\n";
2452         }
2453         return FALSE;
2454 }
2455 public:
2456 WindowFocusPrinter( const char* name ) : m_name( name ){
2457 }
2458 void connect( ui::Window toplevel_window ){
2459         toplevel_window.connect( "notify::has_toplevel_focus", G_CALLBACK( notify ), this );
2460         toplevel_window.connect( "notify::is_active", G_CALLBACK( notify ), this );
2461         toplevel_window.connect( "keys_changed", G_CALLBACK( keys_changed ), this );
2462         toplevel_window.connect( "frame_event", G_CALLBACK( frame_event ), this );
2463 }
2464 };
2465
2466 WindowFocusPrinter g_mainframeFocusPrinter( "mainframe" );
2467
2468 #endif
2469
2470 class MainWindowActive
2471 {
2472 static gboolean notify( ui::Window window, gpointer dummy, MainWindowActive* self ){
2473         if ( g_wait.m_window && gtk_window_is_active( window ) && !g_wait.m_window.visible() ) {
2474                 g_wait.m_window.show();
2475         }
2476
2477         return FALSE;
2478 }
2479 public:
2480 void connect( ui::Window toplevel_window ){
2481         toplevel_window.connect( "notify::is-active", G_CALLBACK( notify ), this );
2482 }
2483 };
2484
2485 MainWindowActive g_MainWindowActive;
2486
2487 SignalHandlerId XYWindowDestroyed_connect( const SignalHandler& handler ){
2488         return g_pParentWnd->GetXYWnd()->onDestroyed.connectFirst( handler );
2489 }
2490
2491 void XYWindowDestroyed_disconnect( SignalHandlerId id ){
2492         g_pParentWnd->GetXYWnd()->onDestroyed.disconnect( id );
2493 }
2494
2495 MouseEventHandlerId XYWindowMouseDown_connect( const MouseEventHandler& handler ){
2496         return g_pParentWnd->GetXYWnd()->onMouseDown.connectFirst( handler );
2497 }
2498
2499 void XYWindowMouseDown_disconnect( MouseEventHandlerId id ){
2500         g_pParentWnd->GetXYWnd()->onMouseDown.disconnect( id );
2501 }
2502
2503 // =============================================================================
2504 // MainFrame class
2505
2506 MainFrame* g_pParentWnd = 0;
2507
2508 ui::Window MainFrame_getWindow()
2509 {
2510         return g_pParentWnd ? g_pParentWnd->m_window : ui::Window{ui::null};
2511 }
2512
2513 std::vector<ui::Widget> g_floating_windows;
2514
2515 MainFrame::MainFrame() : m_idleRedrawStatusText( RedrawStatusTextCaller( *this ) ){
2516         m_pXYWnd = 0;
2517         m_pCamWnd = 0;
2518         m_pZWnd = 0;
2519         m_pYZWnd = 0;
2520         m_pXZWnd = 0;
2521         m_pActiveXY = 0;
2522
2523         for (auto &n : m_pStatusLabel) {
2524         n = NULL;
2525         }
2526
2527         m_bSleeping = false;
2528
2529         Create();
2530 }
2531
2532 MainFrame::~MainFrame(){
2533         SaveWindowInfo();
2534
2535         m_window.hide();
2536
2537         Shutdown();
2538
2539         for ( std::vector<ui::Widget>::iterator i = g_floating_windows.begin(); i != g_floating_windows.end(); ++i )
2540         {
2541                 i->destroy();
2542         }
2543
2544         m_window.destroy();
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 #if GDEF_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( 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         splash_screen.destroy();
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 !GDEF_OS_WINDOWS
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( 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         auto 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     auto main_menu = create_main_menu( CurrentStyle() );
2750         vbox.pack_start( main_menu, FALSE, FALSE, 0 );
2751
2752     auto main_toolbar = create_main_toolbar( CurrentStyle() );
2753         vbox.pack_start( main_toolbar, FALSE, FALSE, 0 );
2754
2755         auto plugin_toolbar = create_plugin_toolbar();
2756         if ( !g_Layout_enablePluginToolbar.m_value ) {
2757                 plugin_toolbar.hide();
2758         }
2759         vbox.pack_start( plugin_toolbar, FALSE, FALSE, 0 );
2760
2761         ui::Widget main_statusbar = create_main_statusbar(reinterpret_cast<ui::Widget *>(m_pStatusLabel));
2762         vbox.pack_end(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 #if GDEF_OS_WINDOWS
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(ui::New);
2795                         m_vSplit = vsplit;
2796                         vbox.pack_start( 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(ui::New);
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(create_framed_widget( m_pXYWnd->GetWidget( ) ));
2813
2814                                 {
2815                                         ui::Widget vsplit2 = ui::VPaned(ui::New);
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                                         auto camera_window = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
2835
2836                                         gtk_paned_add1( GTK_PANED( vsplit2 ), camera_window  );
2837
2838                                         // textures
2839                                         auto texture_window = create_framed_widget( TextureBrowser_constructWindow( window ) );
2840
2841                                         gtk_paned_add2( GTK_PANED( vsplit2 ), 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                         auto frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
2937                         g_page_textures = GroupDialog_addPage( "Textures", 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         auto split = create_split_views( camera, yz, xy, xz );
2966                 vbox.pack_start( split, TRUE, TRUE, 0 );
2967
2968                 {
2969             auto frame = create_framed_widget( TextureBrowser_constructWindow( window ) );
2970                         g_page_textures = GroupDialog_addPage( "Textures", 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(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         ui::Label::from(m_pStatusLabel[c_command_status]).text(m_command_status.c_str());
3044         ui::Label::from(m_pStatusLabel[c_position_status]).text(m_position_status.c_str());
3045         ui::Label::from(m_pStatusLabel[c_brushcount_status]).text(m_brushcount_status.c_str());
3046         ui::Label::from(m_pStatusLabel[c_texture_status]).text(m_texture_status.c_str());
3047         ui::Label::from(m_pStatusLabel[c_grid_status]).text(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 #if GDEF_OS_WINDOWS
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 GDEF_OS_WINDOWS
3318                         "enginepath_win32"
3319 #elif GDEF_OS_MACOS
3320                         "enginepath_macos"
3321 #elif GDEF_OS_LINUX || GDEF_OS_BSD
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 }