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