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