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