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