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