]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/mainframe.cpp
-DGTK_DISABLE_DEPRECATED
[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 "version.h"
31
32 #include "ifilesystem.h"
33 #include "iundo.h"
34 #include "editable.h"
35 #include "ientity.h"
36 #include "ishaders.h"
37 #include "igl.h"
38 #include "moduleobserver.h"
39
40 #include <ctime>
41
42 #include <gdk/gdkkeysyms.h>
43 #include <gtk/gtk.h>
44
45
46 #include "cmdlib.h"
47 #include "stream/stringstream.h"
48 #include "signal/isignal.h"
49 #include "os/path.h"
50 #include "os/file.h"
51 #include "eclasslib.h"
52 #include "moduleobservers.h"
53
54 #include "gtkutil/clipboard.h"
55 #include "gtkutil/frame.h"
56 #include "gtkutil/glwidget.h"
57 #include "gtkutil/image.h"
58 #include "gtkutil/menu.h"
59 #include "gtkutil/paned.h"
60
61 #include "autosave.h"
62 #include "build.h"
63 #include "brushmanip.h"
64 #include "brushmodule.h"
65 #include "camwindow.h"
66 #include "csg.h"
67 #include "commands.h"
68 #include "console.h"
69 #include "entity.h"
70 #include "entityinspector.h"
71 #include "entitylist.h"
72 #include "filters.h"
73 #include "findtexturedialog.h"
74 #include "grid.h"
75 #include "groupdialog.h"
76 #include "gtkdlgs.h"
77 #include "gtkmisc.h"
78 #include "help.h"
79 #include "map.h"
80 #include "mru.h"
81 #include "multimon.h"
82 #include "patchdialog.h"
83 #include "patchmanip.h"
84 #include "plugin.h"
85 #include "pluginmanager.h"
86 #include "pluginmenu.h"
87 #include "plugintoolbar.h"
88 #include "preferences.h"
89 #include "qe3.h"
90 #include "qgl.h"
91 #include "select.h"
92 #include "server.h"
93 #include "surfacedialog.h"
94 #include "textures.h"
95 #include "texwindow.h"
96 #include "url.h"
97 #include "xywindow.h"
98 #include "windowobservers.h"
99 #include "renderstate.h"
100 #include "feedback.h"
101 #include "referencecache.h"
102
103
104
105 struct layout_globals_t
106 {
107         WindowPosition m_position;
108
109
110         int nXYHeight;
111         int nXYWidth;
112         int nCamWidth;
113         int nCamHeight;
114         int nState;
115
116         layout_globals_t() :
117                 m_position( -1, -1, 640, 480 ),
118
119                 nXYHeight( 300 ),
120                 nXYWidth( 300 ),
121                 nCamWidth( 200 ),
122                 nCamHeight( 200 ),
123                 nState( GDK_WINDOW_STATE_MAXIMIZED ){
124         }
125 };
126
127 layout_globals_t g_layout_globals;
128 glwindow_globals_t g_glwindow_globals;
129
130
131 // VFS
132 class VFSModuleObserver : public ModuleObserver
133 {
134 std::size_t m_unrealised;
135 public:
136 VFSModuleObserver() : m_unrealised( 1 ){
137 }
138 void realise(){
139         if ( --m_unrealised == 0 ) {
140                 QE_InitVFS();
141                 GlobalFileSystem().initialise();
142         }
143 }
144 void unrealise(){
145         if ( ++m_unrealised == 1 ) {
146                 GlobalFileSystem().shutdown();
147         }
148 }
149 };
150
151 VFSModuleObserver g_VFSModuleObserver;
152
153 void VFS_Construct(){
154         Radiant_attachHomePathsObserver( g_VFSModuleObserver );
155 }
156 void VFS_Destroy(){
157         Radiant_detachHomePathsObserver( g_VFSModuleObserver );
158 }
159
160 // Home Paths
161
162 #ifdef WIN32
163 #include <shlobj.h>
164 #include <objbase.h>
165 const GUID qFOLDERID_SavedGames = {0x4C5C32FF, 0xBB9D, 0x43b0, {0xB5, 0xB4, 0x2D, 0x72, 0xE5, 0x4E, 0xAA, 0xA4}};
166 #define qREFKNOWNFOLDERID GUID
167 #define qKF_FLAG_CREATE 0x8000
168 #define qKF_FLAG_NO_ALIAS 0x1000
169 typedef HRESULT ( WINAPI qSHGetKnownFolderPath_t )( qREFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath );
170 static qSHGetKnownFolderPath_t *qSHGetKnownFolderPath;
171 #endif
172 void HomePaths_Realise(){
173         do
174         {
175                 const char* prefix = g_pGameDescription->getKeyValue( "prefix" );
176                 if ( !string_empty( prefix ) ) {
177                         StringOutputStream path( 256 );
178
179 #if defined( __APPLE__ )
180                         path.clear();
181                         path << DirectoryCleaned( g_get_home_dir() ) << "Library/Application Support" << ( prefix + 1 ) << "/";
182                         if ( file_is_directory( path.c_str() ) ) {
183                                 g_qeglobals.m_userEnginePath = path.c_str();
184                                 break;
185                         }
186                         path.clear();
187                         path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
188 #endif
189
190 #if defined( WIN32 )
191                         TCHAR mydocsdir[MAX_PATH + 1];
192                         wchar_t *mydocsdirw;
193                         HMODULE shfolder = LoadLibrary( "shfolder.dll" );
194                         if ( shfolder ) {
195                                 qSHGetKnownFolderPath = (qSHGetKnownFolderPath_t *) GetProcAddress( shfolder, "SHGetKnownFolderPath" );
196                         }
197                         else{
198                                 qSHGetKnownFolderPath = NULL;
199                         }
200                         CoInitializeEx( NULL, COINIT_APARTMENTTHREADED );
201                         if ( qSHGetKnownFolderPath && qSHGetKnownFolderPath( qFOLDERID_SavedGames, qKF_FLAG_CREATE | qKF_FLAG_NO_ALIAS, NULL, &mydocsdirw ) == S_OK ) {
202                                 memset( mydocsdir, 0, sizeof( mydocsdir ) );
203                                 wcstombs( mydocsdir, mydocsdirw, sizeof( mydocsdir ) - 1 );
204                                 CoTaskMemFree( mydocsdirw );
205                                 path.clear();
206                                 path << DirectoryCleaned( mydocsdir ) << ( prefix + 1 ) << "/";
207                                 if ( file_is_directory( path.c_str() ) ) {
208                                         g_qeglobals.m_userEnginePath = path.c_str();
209                                         CoUninitialize();
210                                         FreeLibrary( shfolder );
211                                         break;
212                                 }
213                         }
214                         CoUninitialize();
215                         if ( shfolder ) {
216                                 FreeLibrary( shfolder );
217                         }
218                         if ( SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, 0, mydocsdir ) ) {
219                                 path.clear();
220                                 path << DirectoryCleaned( mydocsdir ) << "My Games/" << ( prefix + 1 ) << "/";
221                                 // win32: only add it if it already exists
222                                 if ( file_is_directory( path.c_str() ) ) {
223                                         g_qeglobals.m_userEnginePath = path.c_str();
224                                         break;
225                                 }
226                         }
227 #endif
228
229 #if defined( POSIX )
230                         path.clear();
231                         path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
232                         g_qeglobals.m_userEnginePath = path.c_str();
233                         break;
234 #endif
235                 }
236
237                 g_qeglobals.m_userEnginePath = EnginePath_get();
238         }
239         while ( 0 );
240
241         Q_mkdir( g_qeglobals.m_userEnginePath.c_str() );
242
243         {
244                 StringOutputStream path( 256 );
245                 path << g_qeglobals.m_userEnginePath.c_str() << gamename_get() << '/';
246                 g_qeglobals.m_userGamePath = path.c_str();
247         }
248         ASSERT_MESSAGE( !string_empty( g_qeglobals.m_userGamePath.c_str() ), "HomePaths_Realise: user-game-path is empty" );
249         Q_mkdir( g_qeglobals.m_userGamePath.c_str() );
250 }
251
252 ModuleObservers g_homePathObservers;
253
254 void Radiant_attachHomePathsObserver( ModuleObserver& observer ){
255         g_homePathObservers.attach( observer );
256 }
257
258 void Radiant_detachHomePathsObserver( ModuleObserver& observer ){
259         g_homePathObservers.detach( observer );
260 }
261
262 class HomePathsModuleObserver : public ModuleObserver
263 {
264 std::size_t m_unrealised;
265 public:
266 HomePathsModuleObserver() : m_unrealised( 1 ){
267 }
268 void realise(){
269         if ( --m_unrealised == 0 ) {
270                 HomePaths_Realise();
271                 g_homePathObservers.realise();
272         }
273 }
274 void unrealise(){
275         if ( ++m_unrealised == 1 ) {
276                 g_homePathObservers.unrealise();
277         }
278 }
279 };
280
281 HomePathsModuleObserver g_HomePathsModuleObserver;
282
283 void HomePaths_Construct(){
284         Radiant_attachEnginePathObserver( g_HomePathsModuleObserver );
285 }
286 void HomePaths_Destroy(){
287         Radiant_detachEnginePathObserver( g_HomePathsModuleObserver );
288 }
289
290
291 // Engine Path
292
293 std::string g_strEnginePath;
294 ModuleObservers g_enginePathObservers;
295 std::size_t g_enginepath_unrealised = 1;
296
297 void Radiant_attachEnginePathObserver( ModuleObserver& observer ){
298         g_enginePathObservers.attach( observer );
299 }
300
301 void Radiant_detachEnginePathObserver( ModuleObserver& observer ){
302         g_enginePathObservers.detach( observer );
303 }
304
305
306 void EnginePath_Realise(){
307         if ( --g_enginepath_unrealised == 0 ) {
308                 g_enginePathObservers.realise();
309         }
310 }
311
312
313 const char* EnginePath_get(){
314         ASSERT_MESSAGE( g_enginepath_unrealised == 0, "EnginePath_get: engine path not realised" );
315         return g_strEnginePath.c_str();
316 }
317
318 void EnginePath_Unrealise(){
319         if ( ++g_enginepath_unrealised == 1 ) {
320                 g_enginePathObservers.unrealise();
321         }
322 }
323
324 void setEnginePath( const char* path ){
325         StringOutputStream buffer( 256 );
326         buffer << DirectoryCleaned( path );
327         if ( !path_equal( buffer.c_str(), g_strEnginePath.c_str() ) ) {
328 #if 0
329                 while ( !ConfirmModified( "Paths Changed" ) )
330                 {
331                         if ( Map_Unnamed( g_map ) ) {
332                                 Map_SaveAs();
333                         }
334                         else
335                         {
336                                 Map_Save();
337                         }
338                 }
339                 Map_RegionOff();
340 #endif
341
342                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Changing Engine Path" );
343
344                 EnginePath_Unrealise();
345
346                 g_strEnginePath = buffer.c_str();
347
348                 EnginePath_Realise();
349         }
350 }
351
352
353 // App Path
354
355 std::string g_strAppPath;                 ///< holds the full path of the executable
356
357 const char* AppPath_get(){
358         return g_strAppPath.c_str();
359 }
360
361 /// the path to the local rc-dir
362 const char* LocalRcPath_get( void ){
363         static std::string rc_path;
364         if ( rc_path.empty() ) {
365                 StringOutputStream stream( 256 );
366                 stream << GlobalRadiant().getSettingsPath() << g_pGameDescription->mGameFile.c_str() << "/";
367                 rc_path = stream.c_str();
368         }
369         return rc_path.c_str();
370 }
371
372 /// directory for temp files
373 /// NOTE: on *nix this is were we check for .pid
374 std::string g_strSettingsPath;
375 const char* SettingsPath_get(){
376         return g_strSettingsPath.c_str();
377 }
378
379
380 /*!
381    points to the game tools directory, for instance
382    C:/Program Files/Quake III Arena/GtkRadiant
383    (or other games)
384    this is one of the main variables that are configured by the game selection on startup
385    [GameToolsPath]/plugins
386    [GameToolsPath]/modules
387    and also q3map, bspc
388  */
389 std::string g_strGameToolsPath;           ///< this is set by g_GamesDialog
390
391 const char* GameToolsPath_get(){
392         return g_strGameToolsPath.c_str();
393 }
394
395 void EnginePathImport( std::string& self, const char* value ){
396         setEnginePath( value );
397 }
398 typedef ReferenceCaller1<std::string, const char*, EnginePathImport> EnginePathImportCaller;
399
400 void Paths_constructPreferences( PreferencesPage& page ){
401         page.appendPathEntry( "Engine Path", true,
402                                                   StringImportCallback( EnginePathImportCaller( g_strEnginePath ) ),
403                                                   StringExportCallback( StringExportCaller( g_strEnginePath ) )
404                                                   );
405 }
406 void Paths_constructPage( PreferenceGroup& group ){
407         PreferencesPage page( group.createPage( "Paths", "Path Settings" ) );
408         Paths_constructPreferences( page );
409 }
410 void Paths_registerPreferencesPage(){
411         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Paths_constructPage>() );
412 }
413
414
415 class PathsDialog : public Dialog
416 {
417 public:
418 ui::Window BuildDialog(){
419         GtkFrame* frame = create_dialog_frame( "Path settings", GTK_SHADOW_ETCHED_IN );
420
421         GtkVBox* vbox2 = create_dialog_vbox( 0, 4 );
422         gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( vbox2 ) );
423
424         {
425                 PreferencesPage preferencesPage( *this, ui::Widget(GTK_WIDGET( vbox2 )) );
426                 Paths_constructPreferences( preferencesPage );
427         }
428
429         return ui::Window(create_simple_modal_dialog_window( "Engine Path Not Found", m_modal, GTK_WIDGET( frame ) ));
430 }
431 };
432
433 PathsDialog g_PathsDialog;
434
435 void EnginePath_verify(){
436         if ( !file_exists( g_strEnginePath.c_str() ) ) {
437                 g_PathsDialog.Create();
438                 g_PathsDialog.DoModal();
439                 g_PathsDialog.Destroy();
440         }
441 }
442
443 namespace
444 {
445 std::string g_gamename;
446 std::string g_gamemode;
447 ModuleObservers g_gameNameObservers;
448 ModuleObservers g_gameModeObservers;
449 }
450
451 void Radiant_attachGameNameObserver( ModuleObserver& observer ){
452         g_gameNameObservers.attach( observer );
453 }
454
455 void Radiant_detachGameNameObserver( ModuleObserver& observer ){
456         g_gameNameObservers.detach( observer );
457 }
458
459 const char* basegame_get(){
460         return g_pGameDescription->getRequiredKeyValue( "basegame" );
461 }
462
463 const char* gamename_get(){
464         const char* gamename = g_gamename.c_str();
465         if ( string_empty( gamename ) ) {
466                 return basegame_get();
467         }
468         return gamename;
469 }
470
471 void gamename_set( const char* gamename ){
472         if ( !string_equal( gamename, g_gamename.c_str() ) ) {
473                 g_gameNameObservers.unrealise();
474                 g_gamename = gamename;
475                 g_gameNameObservers.realise();
476         }
477 }
478
479 void Radiant_attachGameModeObserver( ModuleObserver& observer ){
480         g_gameModeObservers.attach( observer );
481 }
482
483 void Radiant_detachGameModeObserver( ModuleObserver& observer ){
484         g_gameModeObservers.detach( observer );
485 }
486
487 const char* gamemode_get(){
488         return g_gamemode.c_str();
489 }
490
491 void gamemode_set( const char* gamemode ){
492         if ( !string_equal( gamemode, g_gamemode.c_str() ) ) {
493                 g_gameModeObservers.unrealise();
494                 g_gamemode = gamemode;
495                 g_gameModeObservers.realise();
496         }
497 }
498
499 #include "os/dir.h"
500
501 class CLoadModule
502 {
503 const char* m_path;
504 public:
505 CLoadModule( const char* path ) : m_path( path ){
506 }
507 void operator()( const char* name ) const {
508         char fullname[1024];
509         ASSERT_MESSAGE( strlen( m_path ) + strlen( name ) < 1024, "" );
510         strcpy( fullname, m_path );
511         strcat( fullname, name );
512         globalOutputStream() << "Found '" << fullname << "'\n";
513         GlobalModuleServer_loadModule( fullname );
514 }
515 };
516
517 const char* const c_library_extension =
518 #if defined( WIN32 )
519         "dll"
520 #elif defined ( __APPLE__ )
521         "dylib"
522 #elif defined( __linux__ ) || defined ( __FreeBSD__ )
523         "so"
524 #endif
525 ;
526
527 void Radiant_loadModules( const char* path ){
528         Directory_forEach( path, MatchFileExtension<CLoadModule>( c_library_extension, CLoadModule( path ) ) );
529 }
530
531 void Radiant_loadModulesFromRoot( const char* directory ){
532         {
533                 StringOutputStream path( 256 );
534                 path << directory << g_pluginsDir;
535                 Radiant_loadModules( path.c_str() );
536         }
537
538         if ( !string_equal( g_pluginsDir, g_modulesDir ) ) {
539                 StringOutputStream path( 256 );
540                 path << directory << g_modulesDir;
541                 Radiant_loadModules( path.c_str() );
542         }
543 }
544
545 //! Make COLOR_BRUSHES override worldspawn eclass colour.
546 void SetWorldspawnColour( const Vector3& colour ){
547         EntityClass* worldspawn = GlobalEntityClassManager().findOrInsert( "worldspawn", true );
548         eclass_release_state( worldspawn );
549         worldspawn->color = colour;
550         eclass_capture_state( worldspawn );
551 }
552
553
554 class WorldspawnColourEntityClassObserver : public ModuleObserver
555 {
556 std::size_t m_unrealised;
557 public:
558 WorldspawnColourEntityClassObserver() : m_unrealised( 1 ){
559 }
560 void realise(){
561         if ( --m_unrealised == 0 ) {
562                 SetWorldspawnColour( g_xywindow_globals.color_brushes );
563         }
564 }
565 void unrealise(){
566         if ( ++m_unrealised == 1 ) {
567         }
568 }
569 };
570
571 WorldspawnColourEntityClassObserver g_WorldspawnColourEntityClassObserver;
572
573
574 ModuleObservers g_gameToolsPathObservers;
575
576 void Radiant_attachGameToolsPathObserver( ModuleObserver& observer ){
577         g_gameToolsPathObservers.attach( observer );
578 }
579
580 void Radiant_detachGameToolsPathObserver( ModuleObserver& observer ){
581         g_gameToolsPathObservers.detach( observer );
582 }
583
584 void Radiant_Initialise(){
585         GlobalModuleServer_Initialise();
586
587         Radiant_loadModulesFromRoot( AppPath_get() );
588
589         Preferences_Load();
590
591         bool success = Radiant_Construct( GlobalModuleServer_get() );
592         ASSERT_MESSAGE( success, "module system failed to initialise - see radiant.log for error messages" );
593
594         g_gameToolsPathObservers.realise();
595         g_gameModeObservers.realise();
596         g_gameNameObservers.realise();
597 }
598
599 void Radiant_Shutdown(){
600         g_gameNameObservers.unrealise();
601         g_gameModeObservers.unrealise();
602         g_gameToolsPathObservers.unrealise();
603
604         if ( !g_preferences_globals.disable_ini ) {
605                 globalOutputStream() << "Start writing prefs\n";
606                 Preferences_Save();
607                 globalOutputStream() << "Done prefs\n";
608         }
609
610         Radiant_Destroy();
611
612         GlobalModuleServer_Shutdown();
613 }
614
615 void Exit(){
616         if ( ConfirmModified( "Exit Radiant" ) ) {
617                 gtk_main_quit();
618         }
619 }
620
621
622 void Undo(){
623         GlobalUndoSystem().undo();
624         SceneChangeNotify();
625 }
626
627 void Redo(){
628         GlobalUndoSystem().redo();
629         SceneChangeNotify();
630 }
631
632 void deleteSelection(){
633         UndoableCommand undo( "deleteSelected" );
634         Select_Delete();
635 }
636
637 void Map_ExportSelected( TextOutputStream& ostream ){
638         Map_ExportSelected( ostream, Map_getFormat( g_map ) );
639 }
640
641 void Map_ImportSelected( TextInputStream& istream ){
642         Map_ImportSelected( istream, Map_getFormat( g_map ) );
643 }
644
645 void Selection_Copy(){
646         clipboard_copy( Map_ExportSelected );
647 }
648
649 void Selection_Paste(){
650         clipboard_paste( Map_ImportSelected );
651 }
652
653 void Copy(){
654         if ( SelectedFaces_empty() ) {
655                 Selection_Copy();
656         }
657         else
658         {
659                 SelectedFaces_copyTexture();
660         }
661 }
662
663 void Paste(){
664         if ( SelectedFaces_empty() ) {
665                 UndoableCommand undo( "paste" );
666
667                 GlobalSelectionSystem().setSelectedAll( false );
668                 Selection_Paste();
669         }
670         else
671         {
672                 SelectedFaces_pasteTexture();
673         }
674 }
675
676 void PasteToCamera(){
677         CamWnd& camwnd = *g_pParentWnd->GetCamWnd();
678         GlobalSelectionSystem().setSelectedAll( false );
679
680         UndoableCommand undo( "pasteToCamera" );
681
682         Selection_Paste();
683
684         // Work out the delta
685         Vector3 mid;
686         Select_GetMid( mid );
687         Vector3 delta = vector3_subtracted( vector3_snapped( Camera_getOrigin( camwnd ), GetSnapGridSize() ), mid );
688
689         // Move to camera
690         GlobalSelectionSystem().translateSelected( delta );
691 }
692
693
694 void ColorScheme_Original(){
695         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
696
697         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
698         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
699         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
700
701         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
702         g_xywindow_globals.color_gridminor = Vector3( 0.75f, 0.75f, 0.75f );
703         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
704         g_xywindow_globals.color_gridminor_alt = Vector3( 0.5f, 0.0f, 0.0f );
705         g_xywindow_globals.color_gridmajor_alt = Vector3( 1.0f, 0.0f, 0.0f );
706         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
707         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
708         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
709         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
710         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
711         SetWorldspawnColour( g_xywindow_globals.color_brushes );
712         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
713         XY_UpdateAllWindows();
714 }
715
716 void ColorScheme_QER(){
717         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
718
719         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
720         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
721         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
722
723         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
724         g_xywindow_globals.color_gridminor = Vector3( 1.0f, 1.0f, 1.0f );
725         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
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_Black(){
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( 0.0f, 0.0f, 0.0f );
744         g_xywindow_globals.color_gridminor = Vector3( 0.2f, 0.2f, 0.2f );
745         g_xywindow_globals.color_gridmajor = Vector3( 0.3f, 0.5f, 0.5f );
746         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
747         g_xywindow_globals.color_gridtext = Vector3( 1.0f, 1.0f, 1.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( 1.0f, 1.0f, 1.0f );
751         SetWorldspawnColour( g_xywindow_globals.color_brushes );
752         g_xywindow_globals.color_viewname = Vector3( 0.7f, 0.7f, 0.0f );
753         XY_UpdateAllWindows();
754 }
755
756 /* ydnar: to emulate maya/max/lightwave color schemes */
757 void ColorScheme_Ydnar(){
758         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
759
760         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
761         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
762         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
763
764         g_xywindow_globals.color_gridback = Vector3( 0.77f, 0.77f, 0.77f );
765         g_xywindow_globals.color_gridminor = Vector3( 0.83f, 0.83f, 0.83f );
766         g_xywindow_globals.color_gridmajor = Vector3( 0.89f, 0.89f, 0.89f );
767         g_xywindow_globals.color_gridblock = Vector3( 1.0f, 1.0f, 1.0f );
768         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
769         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
770         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
771         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
772         SetWorldspawnColour( g_xywindow_globals.color_brushes );
773         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
774         XY_UpdateAllWindows();
775 }
776
777 typedef Callback1<Vector3&> GetColourCallback;
778 typedef Callback1<const Vector3&> SetColourCallback;
779
780 class ChooseColour
781 {
782 GetColourCallback m_get;
783 SetColourCallback m_set;
784 public:
785 ChooseColour( const GetColourCallback& get, const SetColourCallback& set )
786         : m_get( get ), m_set( set ){
787 }
788 void operator()(){
789         Vector3 colour;
790         m_get( colour );
791         color_dialog( MainFrame_getWindow(), colour );
792         m_set( colour );
793 }
794 };
795
796
797
798 void Colour_get( const Vector3& colour, Vector3& other ){
799         other = colour;
800 }
801 typedef ConstReferenceCaller1<Vector3, Vector3&, Colour_get> ColourGetCaller;
802
803 void Colour_set( Vector3& colour, const Vector3& other ){
804         colour = other;
805         SceneChangeNotify();
806 }
807 typedef ReferenceCaller1<Vector3, const Vector3&, Colour_set> ColourSetCaller;
808
809 void BrushColour_set( const Vector3& other ){
810         g_xywindow_globals.color_brushes = other;
811         SetWorldspawnColour( g_xywindow_globals.color_brushes );
812         SceneChangeNotify();
813 }
814 typedef FreeCaller1<const Vector3&, BrushColour_set> BrushColourSetCaller;
815
816 void ClipperColour_set( const Vector3& other ){
817         g_xywindow_globals.color_clipper = other;
818         Brush_clipperColourChanged();
819         SceneChangeNotify();
820 }
821 typedef FreeCaller1<const Vector3&, ClipperColour_set> ClipperColourSetCaller;
822
823 void TextureBrowserColour_get( Vector3& other ){
824         other = TextureBrowser_getBackgroundColour( GlobalTextureBrowser() );
825 }
826 typedef FreeCaller1<Vector3&, TextureBrowserColour_get> TextureBrowserColourGetCaller;
827
828 void TextureBrowserColour_set( const Vector3& other ){
829         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), other );
830 }
831 typedef FreeCaller1<const Vector3&, TextureBrowserColour_set> TextureBrowserColourSetCaller;
832
833
834 class ColoursMenu
835 {
836 public:
837 ChooseColour m_textureback;
838 ChooseColour m_xyback;
839 ChooseColour m_gridmajor;
840 ChooseColour m_gridminor;
841 ChooseColour m_gridmajor_alt;
842 ChooseColour m_gridminor_alt;
843 ChooseColour m_gridtext;
844 ChooseColour m_gridblock;
845 ChooseColour m_cameraback;
846 ChooseColour m_brush;
847 ChooseColour m_selectedbrush;
848 ChooseColour m_selectedbrush3d;
849 ChooseColour m_clipper;
850 ChooseColour m_viewname;
851
852 ColoursMenu() :
853         m_textureback( TextureBrowserColourGetCaller(), TextureBrowserColourSetCaller() ),
854         m_xyback( ColourGetCaller( g_xywindow_globals.color_gridback ), ColourSetCaller( g_xywindow_globals.color_gridback ) ),
855         m_gridmajor( ColourGetCaller( g_xywindow_globals.color_gridmajor ), ColourSetCaller( g_xywindow_globals.color_gridmajor ) ),
856         m_gridminor( ColourGetCaller( g_xywindow_globals.color_gridminor ), ColourSetCaller( g_xywindow_globals.color_gridminor ) ),
857         m_gridmajor_alt( ColourGetCaller( g_xywindow_globals.color_gridmajor_alt ), ColourSetCaller( g_xywindow_globals.color_gridmajor_alt ) ),
858         m_gridminor_alt( ColourGetCaller( g_xywindow_globals.color_gridminor_alt ), ColourSetCaller( g_xywindow_globals.color_gridminor_alt ) ),
859         m_gridtext( ColourGetCaller( g_xywindow_globals.color_gridtext ), ColourSetCaller( g_xywindow_globals.color_gridtext ) ),
860         m_gridblock( ColourGetCaller( g_xywindow_globals.color_gridblock ), ColourSetCaller( g_xywindow_globals.color_gridblock ) ),
861         m_cameraback( ColourGetCaller( g_camwindow_globals.color_cameraback ), ColourSetCaller( g_camwindow_globals.color_cameraback ) ),
862         m_brush( ColourGetCaller( g_xywindow_globals.color_brushes ), BrushColourSetCaller() ),
863         m_selectedbrush( ColourGetCaller( g_xywindow_globals.color_selbrushes ), ColourSetCaller( g_xywindow_globals.color_selbrushes ) ),
864         m_selectedbrush3d( ColourGetCaller( g_camwindow_globals.color_selbrushes3d ), ColourSetCaller( g_camwindow_globals.color_selbrushes3d ) ),
865         m_clipper( ColourGetCaller( g_xywindow_globals.color_clipper ), ClipperColourSetCaller() ),
866         m_viewname( ColourGetCaller( g_xywindow_globals.color_viewname ), ColourSetCaller( g_xywindow_globals.color_viewname ) ){
867 }
868 };
869
870 ColoursMenu g_ColoursMenu;
871
872 GtkMenuItem* create_colours_menu(){
873         GtkMenuItem* colours_menu_item = new_sub_menu_item_with_mnemonic( "Colors" );
874         GtkMenu* menu_in_menu = GTK_MENU( gtk_menu_item_get_submenu( colours_menu_item ) );
875         if ( g_Layout_enableDetachableMenus.m_value ) {
876                 menu_tearoff( menu_in_menu );
877         }
878
879         GtkMenu* menu_3 = create_sub_menu_with_mnemonic( menu_in_menu, "Themes" );
880         if ( g_Layout_enableDetachableMenus.m_value ) {
881                 menu_tearoff( menu_3 );
882         }
883
884         create_menu_item_with_mnemonic( menu_3, "QE4 Original", "ColorSchemeOriginal" );
885         create_menu_item_with_mnemonic( menu_3, "Q3Radiant Original", "ColorSchemeQER" );
886         create_menu_item_with_mnemonic( menu_3, "Black and Green", "ColorSchemeBlackAndGreen" );
887         create_menu_item_with_mnemonic( menu_3, "Maya/Max/Lightwave Emulation", "ColorSchemeYdnar" );
888
889         menu_separator( menu_in_menu );
890
891         create_menu_item_with_mnemonic( menu_in_menu, "_Texture Background...", "ChooseTextureBackgroundColor" );
892         create_menu_item_with_mnemonic( menu_in_menu, "Grid Background...", "ChooseGridBackgroundColor" );
893         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major...", "ChooseGridMajorColor" );
894         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor...", "ChooseGridMinorColor" );
895         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major Small...", "ChooseSmallGridMajorColor" );
896         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor Small...", "ChooseSmallGridMinorColor" );
897         create_menu_item_with_mnemonic( menu_in_menu, "Grid Text...", "ChooseGridTextColor" );
898         create_menu_item_with_mnemonic( menu_in_menu, "Grid Block...", "ChooseGridBlockColor" );
899         create_menu_item_with_mnemonic( menu_in_menu, "Default Brush...", "ChooseBrushColor" );
900         create_menu_item_with_mnemonic( menu_in_menu, "Camera Background...", "ChooseCameraBackgroundColor" );
901         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush...", "ChooseSelectedBrushColor" );
902         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush (Camera)...", "ChooseCameraSelectedBrushColor" );
903         create_menu_item_with_mnemonic( menu_in_menu, "Clipper...", "ChooseClipperColor" );
904         create_menu_item_with_mnemonic( menu_in_menu, "Active View name...", "ChooseOrthoViewNameColor" );
905
906         return colours_menu_item;
907 }
908
909
910 void Restart(){
911         PluginsMenu_clear();
912         PluginToolbar_clear();
913
914         Radiant_Shutdown();
915         Radiant_Initialise();
916
917         PluginsMenu_populate();
918
919         PluginToolbar_populate();
920 }
921
922
923 void thunk_OnSleep(){
924         g_pParentWnd->OnSleep();
925 }
926
927 void OpenUpdateURL(){
928         // build the URL
929         StringOutputStream URL( 256 );
930         URL << "http://www.icculus.org/netradiant/?cmd=update&data=dlupdate&query_dlup=1";
931 #ifdef WIN32
932         URL << "&OS_dlup=1";
933 #elif defined( __APPLE__ )
934         URL << "&OS_dlup=2";
935 #else
936         URL << "&OS_dlup=3";
937 #endif
938         URL << "&Version_dlup=" << radiant::version();
939         g_GamesDialog.AddPacksURL( URL );
940         OpenURL( URL.c_str() );
941 }
942
943 // open the Q3Rad manual
944 void OpenHelpURL(){
945         // at least on win32, AppPath + "docs/index.html"
946         StringOutputStream help( 256 );
947         help << AppPath_get() << "docs/index.html";
948         OpenURL( help.c_str() );
949 }
950
951 void OpenBugReportURL(){
952         OpenURL( "http://www.icculus.org/netradiant/?cmd=bugs" );
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 GtkLabel* m_label;
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 = GTK_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                 gtk_widget_show( GTK_WIDGET( dialog.m_label ) );
1629                 gtk_widget_set_size_request( GTK_WIDGET( dialog.m_label ), 200, -1 );
1630
1631                 gtk_container_add( GTK_CONTAINER( dialog.m_window ), GTK_WIDGET( 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<std::string> 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                 process_gui();
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                 process_gui();
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                         gtk_widget_show( GTK_WIDGET( g_wait.m_window ) );
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 GtkMenuItem* create_file_menu(){
1785         // File menu
1786         GtkMenuItem* file_menu_item = new_sub_menu_item_with_mnemonic( "_File" );
1787         GtkMenu* 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, "Save s_elected...", "SaveSelected" );
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, "Check for NetRadiant update (web)", "CheckForUpdate" ); // FIXME
1820         create_menu_item_with_mnemonic( menu, "E_xit", "Exit" );
1821
1822         return file_menu_item;
1823 }
1824
1825 GtkMenuItem* create_edit_menu(){
1826         // Edit menu
1827         GtkMenuItem* edit_menu_item = new_sub_menu_item_with_mnemonic( "_Edit" );
1828         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( edit_menu_item ) );
1829         if ( g_Layout_enableDetachableMenus.m_value ) {
1830                 menu_tearoff( menu );
1831         }
1832         create_menu_item_with_mnemonic( menu, "_Undo", "Undo" );
1833         create_menu_item_with_mnemonic( menu, "_Redo", "Redo" );
1834         menu_separator( menu );
1835         create_menu_item_with_mnemonic( menu, "_Copy", "Copy" );
1836         create_menu_item_with_mnemonic( menu, "_Paste", "Paste" );
1837         create_menu_item_with_mnemonic( menu, "P_aste To Camera", "PasteToCamera" );
1838         menu_separator( menu );
1839         create_menu_item_with_mnemonic( menu, "_Duplicate", "CloneSelection" );
1840         create_menu_item_with_mnemonic( menu, "Duplicate, make uni_que", "CloneSelectionAndMakeUnique" );
1841         create_menu_item_with_mnemonic( menu, "D_elete", "DeleteSelection" );
1842         menu_separator( menu );
1843         create_menu_item_with_mnemonic( menu, "Pa_rent", "ParentSelection" );
1844         menu_separator( menu );
1845         create_menu_item_with_mnemonic( menu, "C_lear Selection", "UnSelectSelection" );
1846         create_menu_item_with_mnemonic( menu, "_Invert Selection", "InvertSelection" );
1847         create_menu_item_with_mnemonic( menu, "Select i_nside", "SelectInside" );
1848         create_menu_item_with_mnemonic( menu, "Select _touching", "SelectTouching" );
1849
1850         GtkMenu* convert_menu = create_sub_menu_with_mnemonic( menu, "E_xpand Selection" );
1851         if ( g_Layout_enableDetachableMenus.m_value ) {
1852                 menu_tearoff( convert_menu );
1853         }
1854         create_menu_item_with_mnemonic( convert_menu, "To Whole _Entities", "ExpandSelectionToEntities" );
1855
1856         menu_separator( menu );
1857         create_menu_item_with_mnemonic( menu, "Pre_ferences...", "Preferences" );
1858
1859         return edit_menu_item;
1860 }
1861
1862 void fill_view_xy_top_menu( GtkMenu* menu ){
1863         create_check_menu_item_with_mnemonic( menu, "XY (Top) View", "ToggleView" );
1864 }
1865
1866
1867 void fill_view_yz_side_menu( GtkMenu* menu ){
1868         create_check_menu_item_with_mnemonic( menu, "YZ (Side) View", "ToggleSideView" );
1869 }
1870
1871
1872 void fill_view_xz_front_menu( GtkMenu* menu ){
1873         create_check_menu_item_with_mnemonic( menu, "XZ (Front) View", "ToggleFrontView" );
1874 }
1875
1876
1877 ui::Widget g_toggle_z_item;
1878 ui::Widget g_toggle_console_item;
1879 ui::Widget g_toggle_entity_item;
1880 ui::Widget g_toggle_entitylist_item;
1881
1882 GtkMenuItem* create_view_menu( MainFrame::EViewStyle style ){
1883         // View menu
1884         GtkMenuItem* view_menu_item = new_sub_menu_item_with_mnemonic( "Vie_w" );
1885         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( view_menu_item ) );
1886         if ( g_Layout_enableDetachableMenus.m_value ) {
1887                 menu_tearoff( menu );
1888         }
1889
1890         if ( style == MainFrame::eFloating ) {
1891                 fill_view_camera_menu( menu );
1892                 fill_view_xy_top_menu( menu );
1893                 fill_view_yz_side_menu( menu );
1894                 fill_view_xz_front_menu( menu );
1895         }
1896         if ( style == MainFrame::eFloating || style == MainFrame::eSplit ) {
1897                 create_menu_item_with_mnemonic( menu, "Console View", "ToggleConsole" );
1898                 create_menu_item_with_mnemonic( menu, "Texture Browser", "ToggleTextures" );
1899                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ToggleEntityInspector" );
1900         }
1901         else
1902         {
1903                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ViewEntityInfo" );
1904         }
1905         create_menu_item_with_mnemonic( menu, "_Surface Inspector", "SurfaceInspector" );
1906         create_menu_item_with_mnemonic( menu, "Entity List", "EntityList" );
1907
1908         menu_separator( menu );
1909         {
1910                 GtkMenu* camera_menu = create_sub_menu_with_mnemonic( menu, "Camera" );
1911                 if ( g_Layout_enableDetachableMenus.m_value ) {
1912                         menu_tearoff( camera_menu );
1913                 }
1914                 create_menu_item_with_mnemonic( camera_menu, "_Center", "CenterView" );
1915                 create_menu_item_with_mnemonic( camera_menu, "_Up Floor", "UpFloor" );
1916                 create_menu_item_with_mnemonic( camera_menu, "_Down Floor", "DownFloor" );
1917                 menu_separator( camera_menu );
1918                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane In", "CubicClipZoomIn" );
1919                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane Out", "CubicClipZoomOut" );
1920                 menu_separator( camera_menu );
1921                 create_menu_item_with_mnemonic( camera_menu, "Next leak spot", "NextLeakSpot" );
1922                 create_menu_item_with_mnemonic( camera_menu, "Previous leak spot", "PrevLeakSpot" );
1923                 menu_separator( camera_menu );
1924                 create_menu_item_with_mnemonic( camera_menu, "Look Through Selected", "LookThroughSelected" );
1925                 create_menu_item_with_mnemonic( camera_menu, "Look Through Camera", "LookThroughCamera" );
1926         }
1927         menu_separator( menu );
1928         {
1929                 GtkMenu* orthographic_menu = create_sub_menu_with_mnemonic( menu, "Orthographic" );
1930                 if ( g_Layout_enableDetachableMenus.m_value ) {
1931                         menu_tearoff( orthographic_menu );
1932                 }
1933                 if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
1934                         create_menu_item_with_mnemonic( orthographic_menu, "_Next (XY, YZ, XY)", "NextView" );
1935                         create_menu_item_with_mnemonic( orthographic_menu, "XY (Top)", "ViewTop" );
1936                         create_menu_item_with_mnemonic( orthographic_menu, "YZ", "ViewSide" );
1937                         create_menu_item_with_mnemonic( orthographic_menu, "XZ", "ViewFront" );
1938                         menu_separator( orthographic_menu );
1939                 }
1940
1941                 create_menu_item_with_mnemonic( orthographic_menu, "_XY 100%", "Zoom100" );
1942                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _In", "ZoomIn" );
1943                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _Out", "ZoomOut" );
1944         }
1945
1946         menu_separator( menu );
1947
1948         {
1949                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Show" );
1950                 if ( g_Layout_enableDetachableMenus.m_value ) {
1951                         menu_tearoff( menu_in_menu );
1952                 }
1953                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Angles", "ShowAngles" );
1954                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Names", "ShowNames" );
1955                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Blocks", "ShowBlocks" );
1956                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show C_oordinates", "ShowCoordinates" );
1957                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Window Outline", "ShowWindowOutline" );
1958                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Axes", "ShowAxes" );
1959                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Workzone", "ShowWorkzone" );
1960                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Stats", "ShowStats" );
1961         }
1962
1963         {
1964                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Filter" );
1965                 if ( g_Layout_enableDetachableMenus.m_value ) {
1966                         menu_tearoff( menu_in_menu );
1967                 }
1968                 Filters_constructMenu( menu_in_menu );
1969         }
1970         menu_separator( menu );
1971         {
1972                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Hide/Show" );
1973                 if ( g_Layout_enableDetachableMenus.m_value ) {
1974                         menu_tearoff( menu_in_menu );
1975                 }
1976                 create_menu_item_with_mnemonic( menu_in_menu, "Hide Selected", "HideSelected" );
1977                 create_menu_item_with_mnemonic( menu_in_menu, "Show Hidden", "ShowHidden" );
1978         }
1979         menu_separator( menu );
1980         {
1981                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Region" );
1982                 if ( g_Layout_enableDetachableMenus.m_value ) {
1983                         menu_tearoff( menu_in_menu );
1984                 }
1985                 create_menu_item_with_mnemonic( menu_in_menu, "_Off", "RegionOff" );
1986                 create_menu_item_with_mnemonic( menu_in_menu, "_Set XY", "RegionSetXY" );
1987                 create_menu_item_with_mnemonic( menu_in_menu, "Set _Brush", "RegionSetBrush" );
1988                 create_menu_item_with_mnemonic( menu_in_menu, "Set Se_lected Brushes", "RegionSetSelection" );
1989         }
1990
1991         command_connect_accelerator( "CenterXYView" );
1992
1993         return view_menu_item;
1994 }
1995
1996 GtkMenuItem* create_selection_menu(){
1997         // Selection menu
1998         GtkMenuItem* selection_menu_item = new_sub_menu_item_with_mnemonic( "M_odify" );
1999         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( selection_menu_item ) );
2000         if ( g_Layout_enableDetachableMenus.m_value ) {
2001                 menu_tearoff( menu );
2002         }
2003
2004         {
2005                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Components" );
2006                 if ( g_Layout_enableDetachableMenus.m_value ) {
2007                         menu_tearoff( menu_in_menu );
2008                 }
2009                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Edges", "DragEdges" );
2010                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Vertices", "DragVertices" );
2011                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Faces", "DragFaces" );
2012         }
2013
2014         menu_separator( menu );
2015
2016         {
2017                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Nudge" );
2018                 if ( g_Layout_enableDetachableMenus.m_value ) {
2019                         menu_tearoff( menu_in_menu );
2020                 }
2021                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Left", "SelectNudgeLeft" );
2022                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Right", "SelectNudgeRight" );
2023                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Up", "SelectNudgeUp" );
2024                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Down", "SelectNudgeDown" );
2025         }
2026         {
2027                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Rotate" );
2028                 if ( g_Layout_enableDetachableMenus.m_value ) {
2029                         menu_tearoff( menu_in_menu );
2030                 }
2031                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate X", "RotateSelectionX" );
2032                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Y", "RotateSelectionY" );
2033                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Z", "RotateSelectionZ" );
2034         }
2035         {
2036                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Flip" );
2037                 if ( g_Layout_enableDetachableMenus.m_value ) {
2038                         menu_tearoff( menu_in_menu );
2039                 }
2040                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _X", "MirrorSelectionX" );
2041                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Y", "MirrorSelectionY" );
2042                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Z", "MirrorSelectionZ" );
2043         }
2044         menu_separator( menu );
2045         create_menu_item_with_mnemonic( menu, "Arbitrary rotation...", "ArbitraryRotation" );
2046         create_menu_item_with_mnemonic( menu, "Arbitrary scale...", "ArbitraryScale" );
2047
2048         return selection_menu_item;
2049 }
2050
2051 GtkMenuItem* create_bsp_menu(){
2052         // BSP menu
2053         GtkMenuItem* bsp_menu_item = new_sub_menu_item_with_mnemonic( "_Build" );
2054         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( bsp_menu_item ) );
2055
2056         if ( g_Layout_enableDetachableMenus.m_value ) {
2057                 menu_tearoff( menu );
2058         }
2059
2060         create_menu_item_with_mnemonic( menu, "Customize...", "BuildMenuCustomize" );
2061
2062         menu_separator( menu );
2063
2064         Build_constructMenu( menu );
2065
2066         g_bsp_menu = menu;
2067
2068         return bsp_menu_item;
2069 }
2070
2071 GtkMenuItem* create_grid_menu(){
2072         // Grid menu
2073         GtkMenuItem* grid_menu_item = new_sub_menu_item_with_mnemonic( "_Grid" );
2074         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( grid_menu_item ) );
2075         if ( g_Layout_enableDetachableMenus.m_value ) {
2076                 menu_tearoff( menu );
2077         }
2078
2079         Grid_constructMenu( menu );
2080
2081         return grid_menu_item;
2082 }
2083
2084 GtkMenuItem* create_misc_menu(){
2085         // Misc menu
2086         GtkMenuItem* misc_menu_item = new_sub_menu_item_with_mnemonic( "M_isc" );
2087         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( misc_menu_item ) );
2088         if ( g_Layout_enableDetachableMenus.m_value ) {
2089                 menu_tearoff( menu );
2090         }
2091
2092 #if 0
2093         create_menu_item_with_mnemonic( menu, "_Benchmark", FreeCaller<GlobalCamera_Benchmark>() );
2094 #endif
2095         gtk_container_add( GTK_CONTAINER( menu ), GTK_WIDGET( create_colours_menu() ) );
2096
2097         create_menu_item_with_mnemonic( menu, "Find brush...", "FindBrush" );
2098         create_menu_item_with_mnemonic( menu, "Map Info...", "MapInfo" );
2099         // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394
2100 //  create_menu_item_with_mnemonic(menu, "_Print XY View", FreeCaller<WXY_Print>());
2101         create_menu_item_with_mnemonic( menu, "_Background select", FreeCaller<WXY_BackgroundSelect>() );
2102         return misc_menu_item;
2103 }
2104
2105 GtkMenuItem* create_entity_menu(){
2106         // Brush menu
2107         GtkMenuItem* entity_menu_item = new_sub_menu_item_with_mnemonic( "E_ntity" );
2108         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( entity_menu_item ) );
2109         if ( g_Layout_enableDetachableMenus.m_value ) {
2110                 menu_tearoff( menu );
2111         }
2112
2113         Entity_constructMenu( menu );
2114
2115         return entity_menu_item;
2116 }
2117
2118 GtkMenuItem* create_brush_menu(){
2119         // Brush menu
2120         GtkMenuItem* brush_menu_item = new_sub_menu_item_with_mnemonic( "B_rush" );
2121         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( brush_menu_item ) );
2122         if ( g_Layout_enableDetachableMenus.m_value ) {
2123                 menu_tearoff( menu );
2124         }
2125
2126         Brush_constructMenu( menu );
2127
2128         return brush_menu_item;
2129 }
2130
2131 GtkMenuItem* create_patch_menu(){
2132         // Curve menu
2133         GtkMenuItem* patch_menu_item = new_sub_menu_item_with_mnemonic( "_Curve" );
2134         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( patch_menu_item ) );
2135         if ( g_Layout_enableDetachableMenus.m_value ) {
2136                 menu_tearoff( menu );
2137         }
2138
2139         Patch_constructMenu( menu );
2140
2141         return patch_menu_item;
2142 }
2143
2144 GtkMenuItem* create_help_menu(){
2145         // Help menu
2146         GtkMenuItem* help_menu_item = new_sub_menu_item_with_mnemonic( "_Help" );
2147         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( help_menu_item ) );
2148         if ( g_Layout_enableDetachableMenus.m_value ) {
2149                 menu_tearoff( menu );
2150         }
2151
2152         create_menu_item_with_mnemonic( menu, "Manual", "OpenManual" );
2153
2154         // this creates all the per-game drop downs for the game pack helps
2155         // it will take care of hooking the Sys_OpenURL calls etc.
2156         create_game_help_menu( menu );
2157
2158         create_menu_item_with_mnemonic( menu, "Bug report", FreeCaller<OpenBugReportURL>() );
2159         create_menu_item_with_mnemonic( menu, "Shortcuts list", FreeCaller<DoCommandListDlg>() );
2160         create_menu_item_with_mnemonic( menu, "_About", FreeCaller<DoAbout>() );
2161
2162         return help_menu_item;
2163 }
2164
2165 GtkMenuBar* create_main_menu( MainFrame::EViewStyle style ){
2166         GtkMenuBar* menu_bar = GTK_MENU_BAR( gtk_menu_bar_new() );
2167         gtk_widget_show( GTK_WIDGET( menu_bar ) );
2168
2169         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_file_menu() ) );
2170         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_edit_menu() ) );
2171         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_view_menu( style ) ) );
2172         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_selection_menu() ) );
2173         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_bsp_menu() ) );
2174         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_grid_menu() ) );
2175         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_misc_menu() ) );
2176         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_entity_menu() ) );
2177         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_brush_menu() ) );
2178         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_patch_menu() ) );
2179         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_plugins_menu() ) );
2180         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_help_menu() ) );
2181
2182         return menu_bar;
2183 }
2184
2185
2186 void PatchInspector_registerShortcuts(){
2187         command_connect_accelerator( "PatchInspector" );
2188 }
2189
2190 void Patch_registerShortcuts(){
2191         command_connect_accelerator( "InvertCurveTextureX" );
2192         command_connect_accelerator( "InvertCurveTextureY" );
2193         command_connect_accelerator( "PatchInsertInsertColumn" );
2194         command_connect_accelerator( "PatchInsertInsertRow" );
2195         command_connect_accelerator( "PatchDeleteLastColumn" );
2196         command_connect_accelerator( "PatchDeleteLastRow" );
2197         command_connect_accelerator( "NaturalizePatch" );
2198         //command_connect_accelerator("CapCurrentCurve");
2199 }
2200
2201 void Manipulators_registerShortcuts(){
2202         toggle_add_accelerator( "MouseRotate" );
2203         toggle_add_accelerator( "MouseTranslate" );
2204         toggle_add_accelerator( "MouseScale" );
2205         toggle_add_accelerator( "MouseDrag" );
2206         toggle_add_accelerator( "ToggleClipper" );
2207 }
2208
2209 void TexdefNudge_registerShortcuts(){
2210         command_connect_accelerator( "TexRotateClock" );
2211         command_connect_accelerator( "TexRotateCounter" );
2212         command_connect_accelerator( "TexScaleUp" );
2213         command_connect_accelerator( "TexScaleDown" );
2214         command_connect_accelerator( "TexScaleLeft" );
2215         command_connect_accelerator( "TexScaleRight" );
2216         command_connect_accelerator( "TexShiftUp" );
2217         command_connect_accelerator( "TexShiftDown" );
2218         command_connect_accelerator( "TexShiftLeft" );
2219         command_connect_accelerator( "TexShiftRight" );
2220 }
2221
2222 void SelectNudge_registerShortcuts(){
2223         command_connect_accelerator( "MoveSelectionDOWN" );
2224         command_connect_accelerator( "MoveSelectionUP" );
2225         //command_connect_accelerator("SelectNudgeLeft");
2226         //command_connect_accelerator("SelectNudgeRight");
2227         //command_connect_accelerator("SelectNudgeUp");
2228         //command_connect_accelerator("SelectNudgeDown");
2229 }
2230
2231 void SnapToGrid_registerShortcuts(){
2232         command_connect_accelerator( "SnapToGrid" );
2233 }
2234
2235 void SelectByType_registerShortcuts(){
2236         command_connect_accelerator( "SelectAllOfType" );
2237 }
2238
2239 void SurfaceInspector_registerShortcuts(){
2240         command_connect_accelerator( "FitTexture" );
2241 }
2242
2243
2244 void register_shortcuts(){
2245         PatchInspector_registerShortcuts();
2246         Patch_registerShortcuts();
2247         Grid_registerShortcuts();
2248         XYWnd_registerShortcuts();
2249         CamWnd_registerShortcuts();
2250         Manipulators_registerShortcuts();
2251         SurfaceInspector_registerShortcuts();
2252         TexdefNudge_registerShortcuts();
2253         SelectNudge_registerShortcuts();
2254         SnapToGrid_registerShortcuts();
2255         SelectByType_registerShortcuts();
2256 }
2257
2258 void File_constructToolbar( GtkToolbar* toolbar ){
2259         toolbar_append_button( toolbar, "Open an existing map (CTRL + O)", "file_open.png", "OpenMap" );
2260         toolbar_append_button( toolbar, "Save the active map (CTRL + S)", "file_save.png", "SaveMap" );
2261 }
2262
2263 void UndoRedo_constructToolbar( GtkToolbar* toolbar ){
2264         toolbar_append_button( toolbar, "Undo (CTRL + Z)", "undo.png", "Undo" );
2265         toolbar_append_button( toolbar, "Redo (CTRL + Y)", "redo.png", "Redo" );
2266 }
2267
2268 void RotateFlip_constructToolbar( GtkToolbar* toolbar ){
2269         toolbar_append_button( toolbar, "x-axis Flip", "brush_flipx.png", "MirrorSelectionX" );
2270         toolbar_append_button( toolbar, "x-axis Rotate", "brush_rotatex.png", "RotateSelectionX" );
2271         toolbar_append_button( toolbar, "y-axis Flip", "brush_flipy.png", "MirrorSelectionY" );
2272         toolbar_append_button( toolbar, "y-axis Rotate", "brush_rotatey.png", "RotateSelectionY" );
2273         toolbar_append_button( toolbar, "z-axis Flip", "brush_flipz.png", "MirrorSelectionZ" );
2274         toolbar_append_button( toolbar, "z-axis Rotate", "brush_rotatez.png", "RotateSelectionZ" );
2275 }
2276
2277 void Select_constructToolbar( GtkToolbar* toolbar ){
2278         toolbar_append_button( toolbar, "Select touching", "selection_selecttouching.png", "SelectTouching" );
2279         toolbar_append_button( toolbar, "Select inside", "selection_selectinside.png", "SelectInside" );
2280 }
2281
2282 void CSG_constructToolbar( GtkToolbar* toolbar ){
2283         toolbar_append_button( toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.png", "CSGSubtract" );
2284         toolbar_append_button( toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.png", "CSGMerge" );
2285         toolbar_append_button( toolbar, "Hollow", "selection_makehollow.png", "CSGHollow" );
2286 }
2287
2288 void ComponentModes_constructToolbar( GtkToolbar* toolbar ){
2289         toolbar_append_toggle_button( toolbar, "Select Vertices (V)", "modify_vertices.png", "DragVertices" );
2290         toolbar_append_toggle_button( toolbar, "Select Edges (E)", "modify_edges.png", "DragEdges" );
2291         toolbar_append_toggle_button( toolbar, "Select Faces (F)", "modify_faces.png", "DragFaces" );
2292 }
2293
2294 void Clipper_constructToolbar( GtkToolbar* toolbar ){
2295
2296         toolbar_append_toggle_button( toolbar, "Clipper (X)", "view_clipper.png", "ToggleClipper" );
2297 }
2298
2299 void XYWnd_constructToolbar( GtkToolbar* toolbar ){
2300         toolbar_append_button( toolbar, "Change views", "view_change.png", "NextView" );
2301 }
2302
2303 void Manipulators_constructToolbar( GtkToolbar* toolbar ){
2304         toolbar_append_toggle_button( toolbar, "Translate (W)", "select_mousetranslate.png", "MouseTranslate" );
2305         toolbar_append_toggle_button( toolbar, "Rotate (R)", "select_mouserotate.png", "MouseRotate" );
2306         toolbar_append_toggle_button( toolbar, "Scale", "select_mousescale.png", "MouseScale" );
2307         toolbar_append_toggle_button( toolbar, "Resize (Q)", "select_mouseresize.png", "MouseDrag" );
2308
2309         Clipper_constructToolbar( toolbar );
2310 }
2311
2312 GtkToolbar* create_main_toolbar( MainFrame::EViewStyle style ){
2313         GtkToolbar* toolbar = GTK_TOOLBAR( gtk_toolbar_new() );
2314         gtk_orientable_set_orientation( GTK_ORIENTABLE(toolbar), GTK_ORIENTATION_HORIZONTAL );
2315         gtk_toolbar_set_style( toolbar, GTK_TOOLBAR_ICONS );
2316
2317         gtk_widget_show( GTK_WIDGET( toolbar ) );
2318
2319         auto space = [&]() {
2320                 auto btn = gtk_separator_tool_item_new();
2321                 gtk_widget_show(GTK_WIDGET(btn));
2322                 gtk_container_add(GTK_CONTAINER(toolbar), GTK_WIDGET(btn));
2323         };
2324
2325         File_constructToolbar( toolbar );
2326
2327         space();
2328
2329         UndoRedo_constructToolbar( toolbar );
2330
2331         space();
2332
2333         RotateFlip_constructToolbar( toolbar );
2334
2335         space();
2336
2337         Select_constructToolbar( toolbar );
2338
2339         space();
2340
2341         CSG_constructToolbar( toolbar );
2342
2343         space();
2344
2345         ComponentModes_constructToolbar( toolbar );
2346
2347         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
2348                 space();
2349
2350                 XYWnd_constructToolbar( toolbar );
2351         }
2352
2353         space();
2354
2355         CamWnd_constructToolbar( toolbar );
2356
2357         space();
2358
2359         Manipulators_constructToolbar( toolbar );
2360
2361         if ( g_Layout_enablePatchToolbar.m_value ) {
2362                 space();
2363
2364                 Patch_constructToolbar( toolbar );
2365         }
2366
2367         space();
2368
2369         toolbar_append_toggle_button( toolbar, "Texture Lock (SHIFT +T)", "texture_lock.png", "TogTexLock" );
2370
2371         space();
2372
2373         /*GtkButton* g_view_entities_button =*/ toolbar_append_button( toolbar, "Entities (N)", "entities.png", "ToggleEntityInspector" );
2374         auto g_view_console_button = toolbar_append_button( toolbar, "Console (O)", "console.png", "ToggleConsole" );
2375         auto g_view_textures_button = toolbar_append_button( toolbar, "Texture Browser (T)", "texture_browser.png", "ToggleTextures" );
2376         // TODO: call light inspector
2377         //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.png", "ToggleLightInspector");
2378
2379         space();
2380         /*GtkButton* g_refresh_models_button =*/ toolbar_append_button( toolbar, "Refresh Models", "refresh_models.png", "RefreshReferences" );
2381
2382
2383         // disable the console and texture button in the regular layouts
2384         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft ) {
2385                 gtk_widget_set_sensitive( GTK_WIDGET( g_view_console_button ), FALSE );
2386                 gtk_widget_set_sensitive( GTK_WIDGET( g_view_textures_button ), FALSE );
2387         }
2388
2389         return toolbar;
2390 }
2391
2392 ui::Widget create_main_statusbar( ui::Widget pStatusLabel[c_count_status] ){
2393         GtkTable* table = ui::Table( 1, c_count_status, FALSE );
2394         gtk_widget_show( GTK_WIDGET( table ) );
2395
2396         {
2397                 GtkLabel* label = GTK_LABEL( ui::Label( "Label" ) );
2398                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
2399                 gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
2400                 gtk_widget_show( GTK_WIDGET( label ) );
2401                 gtk_table_attach_defaults( table, GTK_WIDGET( label ), 0, 1, 0, 1 );
2402                 pStatusLabel[c_command_status] = ui::Widget(GTK_WIDGET( label ));
2403         }
2404
2405         for ( int i = 1; i < c_count_status; ++i )
2406         {
2407                 GtkFrame* frame = ui::Frame();
2408                 gtk_widget_show( GTK_WIDGET( frame ) );
2409                 gtk_table_attach_defaults( table, GTK_WIDGET( frame ), i, i + 1, 0, 1 );
2410                 gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN );
2411
2412                 GtkLabel* label = GTK_LABEL( ui::Label( "Label" ) );
2413                 gtk_label_set_ellipsize( label, PANGO_ELLIPSIZE_END );
2414                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
2415                 gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
2416                 gtk_widget_show( GTK_WIDGET( label ) );
2417                 gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( label ) );
2418                 pStatusLabel[i] = ui::Widget(GTK_WIDGET( label ));
2419         }
2420
2421         return ui::Widget(GTK_WIDGET( table ));
2422 }
2423
2424 #if 0
2425
2426
2427 WidgetFocusPrinter g_mainframeWidgetFocusPrinter( "mainframe" );
2428
2429 class WindowFocusPrinter
2430 {
2431 const char* m_name;
2432
2433 static gboolean frame_event( ui::Widget widget, GdkEvent* event, WindowFocusPrinter* self ){
2434         globalOutputStream() << self->m_name << " frame_event\n";
2435         return FALSE;
2436 }
2437 static gboolean keys_changed( ui::Widget widget, WindowFocusPrinter* self ){
2438         globalOutputStream() << self->m_name << " keys_changed\n";
2439         return FALSE;
2440 }
2441 static gboolean notify( ui::Window window, gpointer dummy, WindowFocusPrinter* self ){
2442         if ( gtk_window_is_active( window ) ) {
2443                 globalOutputStream() << self->m_name << " takes toplevel focus\n";
2444         }
2445         else
2446         {
2447                 globalOutputStream() << self->m_name << " loses toplevel focus\n";
2448         }
2449         return FALSE;
2450 }
2451 public:
2452 WindowFocusPrinter( const char* name ) : m_name( name ){
2453 }
2454 void connect( ui::Window toplevel_window ){
2455         g_signal_connect( G_OBJECT( toplevel_window ), "notify::has_toplevel_focus", G_CALLBACK( notify ), this );
2456         g_signal_connect( G_OBJECT( toplevel_window ), "notify::is_active", G_CALLBACK( notify ), this );
2457         g_signal_connect( G_OBJECT( toplevel_window ), "keys_changed", G_CALLBACK( keys_changed ), this );
2458         g_signal_connect( G_OBJECT( toplevel_window ), "frame_event", G_CALLBACK( frame_event ), this );
2459 }
2460 };
2461
2462 WindowFocusPrinter g_mainframeFocusPrinter( "mainframe" );
2463
2464 #endif
2465
2466 class MainWindowActive
2467 {
2468 static gboolean notify( ui::Window window, gpointer dummy, MainWindowActive* self ){
2469         if ( g_wait.m_window && gtk_window_is_active( window ) && !gtk_widget_get_visible( g_wait.m_window ) ) {
2470                 gtk_widget_show( GTK_WIDGET( g_wait.m_window ) );
2471         }
2472
2473         return FALSE;
2474 }
2475 public:
2476 void connect( ui::Window toplevel_window ){
2477         g_signal_connect( G_OBJECT( toplevel_window ), "notify::is-active", G_CALLBACK( notify ), this );
2478 }
2479 };
2480
2481 MainWindowActive g_MainWindowActive;
2482
2483 SignalHandlerId XYWindowDestroyed_connect( const SignalHandler& handler ){
2484         return g_pParentWnd->GetXYWnd()->onDestroyed.connectFirst( handler );
2485 }
2486
2487 void XYWindowDestroyed_disconnect( SignalHandlerId id ){
2488         g_pParentWnd->GetXYWnd()->onDestroyed.disconnect( id );
2489 }
2490
2491 MouseEventHandlerId XYWindowMouseDown_connect( const MouseEventHandler& handler ){
2492         return g_pParentWnd->GetXYWnd()->onMouseDown.connectFirst( handler );
2493 }
2494
2495 void XYWindowMouseDown_disconnect( MouseEventHandlerId id ){
2496         g_pParentWnd->GetXYWnd()->onMouseDown.disconnect( id );
2497 }
2498
2499 // =============================================================================
2500 // MainFrame class
2501
2502 MainFrame* g_pParentWnd = nullptr;
2503
2504 ui::Window MainFrame_getWindow()
2505 {
2506         return g_pParentWnd ? g_pParentWnd->m_window : ui::Window();
2507 }
2508
2509 std::vector<ui::Widget> g_floating_windows;
2510
2511 MainFrame::MainFrame() : m_window( 0 ), m_idleRedrawStatusText( RedrawStatusTextCaller( *this ) ){
2512         m_pXYWnd = 0;
2513         m_pCamWnd = 0;
2514         m_pZWnd = 0;
2515         m_pYZWnd = 0;
2516         m_pXZWnd = 0;
2517         m_pActiveXY = 0;
2518
2519         for ( int n = 0; n < c_count_status; n++ )
2520         {
2521                 m_pStatusLabel[n] = ui::root;
2522         }
2523
2524         m_bSleeping = false;
2525
2526         Create();
2527 }
2528
2529 MainFrame::~MainFrame(){
2530         SaveWindowInfo();
2531
2532         gtk_widget_hide( GTK_WIDGET( m_window ) );
2533
2534         Shutdown();
2535
2536         for ( std::vector<ui::Widget>::iterator i = g_floating_windows.begin(); i != g_floating_windows.end(); ++i )
2537         {
2538                 gtk_widget_destroy( *i );
2539         }
2540
2541         gtk_widget_destroy( GTK_WIDGET( m_window ) );
2542 }
2543
2544 void MainFrame::SetActiveXY( XYWnd* p ){
2545         if ( m_pActiveXY ) {
2546                 m_pActiveXY->SetActive( false );
2547         }
2548
2549         m_pActiveXY = p;
2550
2551         if ( m_pActiveXY ) {
2552                 m_pActiveXY->SetActive( true );
2553         }
2554
2555 }
2556
2557 void MainFrame::ReleaseContexts(){
2558 #if 0
2559         if ( m_pXYWnd ) {
2560                 m_pXYWnd->DestroyContext();
2561         }
2562         if ( m_pYZWnd ) {
2563                 m_pYZWnd->DestroyContext();
2564         }
2565         if ( m_pXZWnd ) {
2566                 m_pXZWnd->DestroyContext();
2567         }
2568         if ( m_pCamWnd ) {
2569                 m_pCamWnd->DestroyContext();
2570         }
2571         if ( m_pTexWnd ) {
2572                 m_pTexWnd->DestroyContext();
2573         }
2574         if ( m_pZWnd ) {
2575                 m_pZWnd->DestroyContext();
2576         }
2577 #endif
2578 }
2579
2580 void MainFrame::CreateContexts(){
2581 #if 0
2582         if ( m_pCamWnd ) {
2583                 m_pCamWnd->CreateContext();
2584         }
2585         if ( m_pXYWnd ) {
2586                 m_pXYWnd->CreateContext();
2587         }
2588         if ( m_pYZWnd ) {
2589                 m_pYZWnd->CreateContext();
2590         }
2591         if ( m_pXZWnd ) {
2592                 m_pXZWnd->CreateContext();
2593         }
2594         if ( m_pTexWnd ) {
2595                 m_pTexWnd->CreateContext();
2596         }
2597         if ( m_pZWnd ) {
2598                 m_pZWnd->CreateContext();
2599         }
2600 #endif
2601 }
2602
2603 #ifdef _DEBUG
2604 //#define DBG_SLEEP
2605 #endif
2606
2607 void MainFrame::OnSleep(){
2608 #if 0
2609         m_bSleeping ^= 1;
2610         if ( m_bSleeping ) {
2611                 // useful when trying to debug crashes in the sleep code
2612                 globalOutputStream() << "Going into sleep mode..\n";
2613
2614                 globalOutputStream() << "Dispatching sleep msg...";
2615                 DispatchRadiantMsg( RADIANT_SLEEP );
2616                 globalOutputStream() << "Done.\n";
2617
2618                 gtk_window_iconify( m_window );
2619                 GlobalSelectionSystem().setSelectedAll( false );
2620
2621                 GlobalShaderCache().unrealise();
2622                 Shaders_Free();
2623                 GlobalOpenGL_debugAssertNoErrors();
2624                 ScreenUpdates_Disable();
2625
2626                 // release contexts
2627                 globalOutputStream() << "Releasing contexts...";
2628                 ReleaseContexts();
2629                 globalOutputStream() << "Done.\n";
2630         }
2631         else
2632         {
2633                 globalOutputStream() << "Waking up\n";
2634
2635                 gtk_window_deiconify( m_window );
2636
2637                 // create contexts
2638                 globalOutputStream() << "Creating contexts...";
2639                 CreateContexts();
2640                 globalOutputStream() << "Done.\n";
2641
2642                 globalOutputStream() << "Making current on camera...";
2643                 m_pCamWnd->MakeCurrent();
2644                 globalOutputStream() << "Done.\n";
2645
2646                 globalOutputStream() << "Reloading shaders...";
2647                 Shaders_Load();
2648                 GlobalShaderCache().realise();
2649                 globalOutputStream() << "Done.\n";
2650
2651                 ScreenUpdates_Enable();
2652
2653                 globalOutputStream() << "Dispatching wake msg...";
2654                 DispatchRadiantMsg( RADIANT_WAKEUP );
2655                 globalOutputStream() << "Done\n";
2656         }
2657 #endif
2658 }
2659
2660
2661 ui::Window create_splash(){
2662         ui::Window window = ui::Window( ui::window_type::TOP );
2663         gtk_window_set_decorated( window, FALSE );
2664         gtk_window_set_resizable( window, FALSE );
2665         gtk_window_set_modal( window, TRUE );
2666         gtk_window_set_default_size( window, -1, -1 );
2667         gtk_window_set_position( window, GTK_WIN_POS_CENTER );
2668         gtk_container_set_border_width( GTK_CONTAINER( window ), 0 );
2669
2670         GtkImage* image = new_local_image( "splash.png" );
2671         gtk_widget_show( GTK_WIDGET( image ) );
2672         gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( image ) );
2673
2674         gtk_widget_set_size_request( GTK_WIDGET( window ), -1, -1 );
2675         gtk_widget_show( GTK_WIDGET( window ) );
2676
2677         return window;
2678 }
2679
2680 static ui::Window splash_screen;
2681
2682 void show_splash(){
2683         splash_screen = create_splash();
2684
2685         process_gui();
2686 }
2687
2688 void hide_splash(){
2689         gtk_widget_destroy( GTK_WIDGET( splash_screen ) );
2690 }
2691
2692 WindowPositionTracker g_posCamWnd;
2693 WindowPositionTracker g_posXYWnd;
2694 WindowPositionTracker g_posXZWnd;
2695 WindowPositionTracker g_posYZWnd;
2696
2697 static gint mainframe_delete( ui::Widget widget, GdkEvent *event, gpointer data ){
2698         if ( ConfirmModified( "Exit Radiant" ) ) {
2699                 gtk_main_quit();
2700         }
2701
2702         return TRUE;
2703 }
2704
2705 void MainFrame::Create(){
2706         ui::Window window = ui::Window( ui::window_type::TOP );
2707
2708         GlobalWindowObservers_connectTopLevel( window );
2709
2710         gtk_window_set_transient_for( splash_screen, window );
2711
2712 #if !defined( WIN32 )
2713         {
2714                 GdkPixbuf* pixbuf = pixbuf_new_from_file_with_mask( "bitmaps/icon.png" );
2715                 if ( pixbuf != 0 ) {
2716                         gtk_window_set_icon( window, pixbuf );
2717                         gdk_pixbuf_unref( pixbuf );
2718                 }
2719         }
2720 #endif
2721
2722         gtk_widget_add_events( GTK_WIDGET( window ), GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK );
2723         g_signal_connect( G_OBJECT( window ), "delete_event", G_CALLBACK( mainframe_delete ), this );
2724
2725         m_position_tracker.connect( window );
2726
2727 #if 0
2728         g_mainframeWidgetFocusPrinter.connect( window );
2729         g_mainframeFocusPrinter.connect( window );
2730 #endif
2731
2732         g_MainWindowActive.connect( window );
2733
2734         GetPlugInMgr().Init( window );
2735
2736         ui::Widget vbox = ui::VBox( FALSE, 0 );
2737         gtk_container_add( GTK_CONTAINER( window ), vbox );
2738         gtk_widget_show( vbox );
2739
2740         global_accel_connect_window( window );
2741
2742         m_nCurrentStyle = (EViewStyle)g_Layout_viewStyle.m_value;
2743
2744         register_shortcuts();
2745
2746         GtkMenuBar* main_menu = create_main_menu( CurrentStyle() );
2747         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( main_menu ), FALSE, FALSE, 0 );
2748
2749         GtkToolbar* main_toolbar = create_main_toolbar( CurrentStyle() );
2750         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( main_toolbar ), FALSE, FALSE, 0 );
2751
2752         GtkToolbar* plugin_toolbar = create_plugin_toolbar();
2753         if ( !g_Layout_enablePluginToolbar.m_value ) {
2754                 gtk_widget_hide( GTK_WIDGET( plugin_toolbar ) );
2755         }
2756         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( plugin_toolbar ), FALSE, FALSE, 0 );
2757
2758         ui::Widget main_statusbar = create_main_statusbar( m_pStatusLabel );
2759         gtk_box_pack_end( GTK_BOX( vbox ), main_statusbar, FALSE, TRUE, 2 );
2760
2761         GroupDialog_constructWindow( window );
2762         g_page_entity = GroupDialog_addPage( "Entities", EntityInspector_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Entities" ) );
2763
2764         if ( FloatingGroupDialog() ) {
2765                 g_page_console = GroupDialog_addPage( "Console", Console_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Console" ) );
2766         }
2767
2768 #ifdef WIN32
2769         if ( g_multimon_globals.m_bStartOnPrimMon ) {
2770                 PositionWindowOnPrimaryScreen( g_layout_globals.m_position );
2771                 window_set_position( window, g_layout_globals.m_position );
2772         }
2773         else
2774 #endif
2775         if ( g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED ) {
2776                 gtk_window_maximize( window );
2777                 WindowPosition default_position( -1, -1, 640, 480 );
2778                 window_set_position( window, default_position );
2779         }
2780         else
2781         {
2782                 window_set_position( window, g_layout_globals.m_position );
2783         }
2784
2785         m_window = window;
2786
2787         gtk_widget_show( GTK_WIDGET( window ) );
2788
2789         if ( CurrentStyle() == eRegular || CurrentStyle() == eRegularLeft ) {
2790                 {
2791                         ui::Widget vsplit = ui::VPaned();
2792                         m_vSplit = vsplit;
2793                         gtk_box_pack_start( GTK_BOX( vbox ), vsplit, TRUE, TRUE, 0 );
2794                         gtk_widget_show( vsplit );
2795
2796                         // console
2797                         ui::Widget console_window = Console_constructWindow( window );
2798                         gtk_paned_pack2( GTK_PANED( vsplit ), console_window, FALSE, TRUE );
2799
2800                         {
2801                                 ui::Widget hsplit = ui::HPaned();
2802                                 gtk_widget_show( hsplit );
2803                                 m_hSplit = hsplit;
2804                                 gtk_paned_add1( GTK_PANED( vsplit ), hsplit );
2805
2806                                 // xy
2807                                 m_pXYWnd = new XYWnd();
2808                                 m_pXYWnd->SetViewType( XY );
2809                                 ui::Widget xy_window = ui::Widget(GTK_WIDGET( create_framed_widget( m_pXYWnd->GetWidget() ) ));
2810
2811                                 {
2812                                         ui::Widget vsplit2 = ui::VPaned();
2813                                         gtk_widget_show( vsplit2 );
2814                                         m_vSplit2 = vsplit2;
2815
2816                                         if ( CurrentStyle() == eRegular ) {
2817                                                 gtk_paned_add1( GTK_PANED( hsplit ), xy_window );
2818                                                 gtk_paned_add2( GTK_PANED( hsplit ), vsplit2 );
2819                                         }
2820                                         else
2821                                         {
2822                                                 gtk_paned_add1( GTK_PANED( hsplit ), vsplit2 );
2823                                                 gtk_paned_add2( GTK_PANED( hsplit ), xy_window );
2824                                         }
2825
2826
2827                                         // camera
2828                                         m_pCamWnd = NewCamWnd();
2829                                         GlobalCamera_setCamWnd( *m_pCamWnd );
2830                                         CamWnd_setParent( *m_pCamWnd, window );
2831                                         GtkFrame* camera_window = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
2832
2833                                         gtk_paned_add1( GTK_PANED( vsplit2 ), GTK_WIDGET( camera_window ) );
2834
2835                                         // textures
2836                                         GtkFrame* texture_window = create_framed_widget( TextureBrowser_constructWindow( window ) );
2837
2838                                         gtk_paned_add2( GTK_PANED( vsplit2 ), GTK_WIDGET( texture_window ) );
2839                                 }
2840                         }
2841                 }
2842
2843                 gtk_paned_set_position( GTK_PANED( m_vSplit ), g_layout_globals.nXYHeight );
2844
2845                 if ( CurrentStyle() == eRegular ) {
2846                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nXYWidth );
2847                 }
2848                 else
2849                 {
2850                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nCamWidth );
2851                 }
2852
2853                 gtk_paned_set_position( GTK_PANED( m_vSplit2 ), g_layout_globals.nCamHeight );
2854         }
2855         else if ( CurrentStyle() == eFloating ) {
2856                 {
2857                         ui::Window window = ui::Window(create_persistent_floating_window( "Camera", m_window ));
2858                         global_accel_connect_window( window );
2859                         g_posCamWnd.connect( window );
2860
2861                         gtk_widget_show( GTK_WIDGET( window ) );
2862
2863                         m_pCamWnd = NewCamWnd();
2864                         GlobalCamera_setCamWnd( *m_pCamWnd );
2865
2866                         {
2867                                 GtkFrame* frame = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
2868                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2869                         }
2870                         CamWnd_setParent( *m_pCamWnd, window );
2871
2872                         g_floating_windows.push_back( window );
2873                 }
2874
2875                 {
2876                         ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( XY ), m_window ));
2877                         global_accel_connect_window( window );
2878                         g_posXYWnd.connect( window );
2879
2880                         m_pXYWnd = new XYWnd();
2881                         m_pXYWnd->m_parent = window;
2882                         m_pXYWnd->SetViewType( XY );
2883
2884
2885                         {
2886                                 GtkFrame* frame = create_framed_widget( m_pXYWnd->GetWidget() );
2887                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2888                         }
2889                         XY_Top_Shown_Construct( window );
2890
2891                         g_floating_windows.push_back( window );
2892                 }
2893
2894                 {
2895                         ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( XZ ), m_window ));
2896                         global_accel_connect_window( window );
2897                         g_posXZWnd.connect( window );
2898
2899                         m_pXZWnd = new XYWnd();
2900                         m_pXZWnd->m_parent = window;
2901                         m_pXZWnd->SetViewType( XZ );
2902
2903                         {
2904                                 GtkFrame* frame = create_framed_widget( m_pXZWnd->GetWidget() );
2905                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2906                         }
2907
2908                         XZ_Front_Shown_Construct( window );
2909
2910                         g_floating_windows.push_back( window );
2911                 }
2912
2913                 {
2914                         ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( YZ ), m_window ));
2915                         global_accel_connect_window( window );
2916                         g_posYZWnd.connect( window );
2917
2918                         m_pYZWnd = new XYWnd();
2919                         m_pYZWnd->m_parent = window;
2920                         m_pYZWnd->SetViewType( YZ );
2921
2922                         {
2923                                 GtkFrame* frame = create_framed_widget( m_pYZWnd->GetWidget() );
2924                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2925                         }
2926
2927                         YZ_Side_Shown_Construct( window );
2928
2929                         g_floating_windows.push_back( window );
2930                 }
2931
2932                 {
2933                         GtkFrame* frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
2934                         g_page_textures = GroupDialog_addPage( "Textures", ui::Widget(GTK_WIDGET( frame )), TextureBrowserExportTitleCaller() );
2935                 }
2936
2937                 GroupDialog_show();
2938         }
2939         else // 4 way
2940         {
2941                 m_pCamWnd = NewCamWnd();
2942                 GlobalCamera_setCamWnd( *m_pCamWnd );
2943                 CamWnd_setParent( *m_pCamWnd, window );
2944
2945                 ui::Widget camera = CamWnd_getWidget( *m_pCamWnd );
2946
2947                 m_pYZWnd = new XYWnd();
2948                 m_pYZWnd->SetViewType( YZ );
2949
2950                 ui::Widget yz = m_pYZWnd->GetWidget();
2951
2952                 m_pXYWnd = new XYWnd();
2953                 m_pXYWnd->SetViewType( XY );
2954
2955                 ui::Widget xy = m_pXYWnd->GetWidget();
2956
2957                 m_pXZWnd = new XYWnd();
2958                 m_pXZWnd->SetViewType( XZ );
2959
2960                 ui::Widget xz = m_pXZWnd->GetWidget();
2961
2962                 GtkHPaned* split = create_split_views( camera, yz, xy, xz );
2963                 gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( split ), TRUE, TRUE, 0 );
2964
2965                 {
2966                         GtkFrame* frame = create_framed_widget( TextureBrowser_constructWindow( window ) );
2967                         g_page_textures = GroupDialog_addPage( "Textures", ui::Widget(GTK_WIDGET( frame )), TextureBrowserExportTitleCaller() );
2968                 }
2969         }
2970
2971         EntityList_constructWindow( window );
2972         PreferencesDialog_constructWindow( window );
2973         FindTextureDialog_constructWindow( window );
2974         SurfaceInspector_constructWindow( window );
2975         PatchInspector_constructWindow( window );
2976
2977         SetActiveXY( m_pXYWnd );
2978
2979         AddGridChangeCallback( SetGridStatusCaller( *this ) );
2980         AddGridChangeCallback( ReferenceCaller<MainFrame, XY_UpdateAllWindows>( *this ) );
2981
2982         g_defaultToolMode = DragMode;
2983         g_defaultToolMode();
2984         SetStatusText( m_command_status, c_TranslateMode_status );
2985
2986         EverySecondTimer_enable();
2987
2988         //GlobalShortcuts_reportUnregistered();
2989 }
2990
2991 void MainFrame::SaveWindowInfo(){
2992         if ( !FloatingGroupDialog() ) {
2993                 g_layout_globals.nXYHeight = gtk_paned_get_position( GTK_PANED( m_vSplit ) );
2994
2995                 if ( CurrentStyle() != eRegular ) {
2996                         g_layout_globals.nCamWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
2997                 }
2998                 else
2999                 {
3000                         g_layout_globals.nXYWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
3001                 }
3002
3003                 g_layout_globals.nCamHeight = gtk_paned_get_position( GTK_PANED( m_vSplit2 ) );
3004         }
3005
3006         g_layout_globals.m_position = m_position_tracker.getPosition();
3007
3008         g_layout_globals.nState = gdk_window_get_state( gtk_widget_get_window(GTK_WIDGET( m_window )) );
3009 }
3010
3011 void MainFrame::Shutdown(){
3012         EverySecondTimer_disable();
3013
3014         EntityList_destroyWindow();
3015
3016         delete m_pXYWnd;
3017         m_pXYWnd = 0;
3018         delete m_pYZWnd;
3019         m_pYZWnd = 0;
3020         delete m_pXZWnd;
3021         m_pXZWnd = 0;
3022
3023         TextureBrowser_destroyWindow();
3024
3025         DeleteCamWnd( m_pCamWnd );
3026         m_pCamWnd = 0;
3027
3028         PreferencesDialog_destroyWindow();
3029         SurfaceInspector_destroyWindow();
3030         FindTextureDialog_destroyWindow();
3031         PatchInspector_destroyWindow();
3032
3033         g_DbgDlg.destroyWindow();
3034
3035         // destroying group-dialog last because it may contain texture-browser
3036         GroupDialog_destroyWindow();
3037 }
3038
3039 void MainFrame::RedrawStatusText(){
3040         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_command_status] ), m_command_status.c_str() );
3041         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_position_status] ), m_position_status.c_str() );
3042         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_brushcount_status] ), m_brushcount_status.c_str() );
3043         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_texture_status] ), m_texture_status.c_str() );
3044         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_grid_status] ), m_grid_status.c_str() );
3045 }
3046
3047 void MainFrame::UpdateStatusText(){
3048         m_idleRedrawStatusText.queueDraw();
3049 }
3050
3051 void MainFrame::SetStatusText( std::string& status_text, const char* pText ){
3052         status_text = pText;
3053         UpdateStatusText();
3054 }
3055
3056 void Sys_Status( const char* status ){
3057         if ( g_pParentWnd != 0 ) {
3058                 g_pParentWnd->SetStatusText( g_pParentWnd->m_command_status, status );
3059         }
3060 }
3061
3062 int getRotateIncrement(){
3063         return static_cast<int>( g_si_globals.rotate );
3064 }
3065
3066 int getFarClipDistance(){
3067         return g_camwindow_globals.m_nCubicScale;
3068 }
3069
3070 float ( *GridStatus_getGridSize )() = GetGridSize;
3071 int ( *GridStatus_getRotateIncrement )() = getRotateIncrement;
3072 int ( *GridStatus_getFarClipDistance )() = getFarClipDistance;
3073 bool ( *GridStatus_getTextureLockEnabled )();
3074
3075 void MainFrame::SetGridStatus(){
3076         StringOutputStream status( 64 );
3077         const char* lock = ( GridStatus_getTextureLockEnabled() ) ? "ON" : "OFF";
3078         status << ( GetSnapGridSize() > 0 ? "G:" : "g:" ) << GridStatus_getGridSize()
3079                    << "  R:" << GridStatus_getRotateIncrement()
3080                    << "  C:" << GridStatus_getFarClipDistance()
3081                    << "  L:" << lock;
3082         SetStatusText( m_grid_status, status.c_str() );
3083 }
3084
3085 void GridStatus_onTextureLockEnabledChanged(){
3086         if ( g_pParentWnd != 0 ) {
3087                 g_pParentWnd->SetGridStatus();
3088         }
3089 }
3090
3091 void GlobalGL_sharedContextCreated(){
3092         GLFont *g_font = NULL;
3093
3094         // report OpenGL information
3095         globalOutputStream() << "GL_VENDOR: " << reinterpret_cast<const char*>( glGetString( GL_VENDOR ) ) << "\n";
3096         globalOutputStream() << "GL_RENDERER: " << reinterpret_cast<const char*>( glGetString( GL_RENDERER ) ) << "\n";
3097         globalOutputStream() << "GL_VERSION: " << reinterpret_cast<const char*>( glGetString( GL_VERSION ) ) << "\n";
3098         globalOutputStream() << "GL_EXTENSIONS: " << reinterpret_cast<const char*>( glGetString( GL_EXTENSIONS ) ) << "\n";
3099
3100         QGL_sharedContextCreated( GlobalOpenGL() );
3101
3102         ShaderCache_extensionsInitialised();
3103
3104         GlobalShaderCache().realise();
3105         Textures_Realise();
3106
3107 #ifdef WIN32
3108         /* win32 is dodgy here, just use courier new then */
3109         g_font = glfont_create( "arial 9" );
3110 #else
3111         GtkSettings *settings = gtk_settings_get_default();
3112         gchar *fontname;
3113         g_object_get( settings, "gtk-font-name", &fontname, NULL );
3114         g_font = glfont_create( fontname );
3115 #endif
3116
3117         GlobalOpenGL().m_font = g_font;
3118 }
3119
3120 void GlobalGL_sharedContextDestroyed(){
3121         Textures_Unrealise();
3122         GlobalShaderCache().unrealise();
3123
3124         QGL_sharedContextDestroyed( GlobalOpenGL() );
3125 }
3126
3127
3128 void Layout_constructPreferences( PreferencesPage& page ){
3129         {
3130                 const char* layouts[] = { "window1.png", "window2.png", "window3.png", "window4.png" };
3131                 page.appendRadioIcons(
3132                         "Window Layout",
3133                         STRING_ARRAY_RANGE( layouts ),
3134                         LatchedIntImportCaller( g_Layout_viewStyle ),
3135                         IntExportCaller( g_Layout_viewStyle.m_latched )
3136                         );
3137         }
3138         page.appendCheckBox(
3139                 "", "Detachable Menus",
3140                 LatchedBoolImportCaller( g_Layout_enableDetachableMenus ),
3141                 BoolExportCaller( g_Layout_enableDetachableMenus.m_latched )
3142                 );
3143         if ( !string_empty( g_pGameDescription->getKeyValue( "no_patch" ) ) ) {
3144                 page.appendCheckBox(
3145                         "", "Patch Toolbar",
3146                         LatchedBoolImportCaller( g_Layout_enablePatchToolbar ),
3147                         BoolExportCaller( g_Layout_enablePatchToolbar.m_latched )
3148                         );
3149         }
3150         page.appendCheckBox(
3151                 "", "Plugin Toolbar",
3152                 LatchedBoolImportCaller( g_Layout_enablePluginToolbar ),
3153                 BoolExportCaller( g_Layout_enablePluginToolbar.m_latched )
3154                 );
3155 }
3156
3157 void Layout_constructPage( PreferenceGroup& group ){
3158         PreferencesPage page( group.createPage( "Layout", "Layout Preferences" ) );
3159         Layout_constructPreferences( page );
3160 }
3161
3162 void Layout_registerPreferencesPage(){
3163         PreferencesDialog_addInterfacePage( FreeCaller1<PreferenceGroup&, Layout_constructPage>() );
3164 }
3165
3166
3167 #include "preferencesystem.h"
3168 #include "stringio.h"
3169
3170 void MainFrame_Construct(){
3171         GlobalCommands_insert( "OpenManual", FreeCaller<OpenHelpURL>(), Accelerator( GDK_F1 ) );
3172
3173         GlobalCommands_insert( "Sleep", FreeCaller<thunk_OnSleep>(), Accelerator( 'P', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
3174         GlobalCommands_insert( "NewMap", FreeCaller<NewMap>() );
3175         GlobalCommands_insert( "OpenMap", FreeCaller<OpenMap>(), Accelerator( 'O', (GdkModifierType)GDK_CONTROL_MASK ) );
3176         GlobalCommands_insert( "ImportMap", FreeCaller<ImportMap>() );
3177         GlobalCommands_insert( "SaveMap", FreeCaller<SaveMap>(), Accelerator( 'S', (GdkModifierType)GDK_CONTROL_MASK ) );
3178         GlobalCommands_insert( "SaveMapAs", FreeCaller<SaveMapAs>() );
3179         GlobalCommands_insert( "SaveSelected", FreeCaller<ExportMap>() );
3180         GlobalCommands_insert( "SaveRegion", FreeCaller<SaveRegion>() );
3181         GlobalCommands_insert( "RefreshReferences", FreeCaller<RefreshReferences>() );
3182         GlobalCommands_insert( "ProjectSettings", FreeCaller<DoProjectSettings>() );
3183         GlobalCommands_insert( "CheckForUpdate", FreeCaller<OpenUpdateURL>() );
3184         GlobalCommands_insert( "Exit", FreeCaller<Exit>() );
3185
3186         GlobalCommands_insert( "Undo", FreeCaller<Undo>(), Accelerator( 'Z', (GdkModifierType)GDK_CONTROL_MASK ) );
3187         GlobalCommands_insert( "Redo", FreeCaller<Redo>(), Accelerator( 'Y', (GdkModifierType)GDK_CONTROL_MASK ) );
3188         GlobalCommands_insert( "Copy", FreeCaller<Copy>(), Accelerator( 'C', (GdkModifierType)GDK_CONTROL_MASK ) );
3189         GlobalCommands_insert( "Paste", FreeCaller<Paste>(), Accelerator( 'V', (GdkModifierType)GDK_CONTROL_MASK ) );
3190         GlobalCommands_insert( "PasteToCamera", FreeCaller<PasteToCamera>(), Accelerator( 'V', (GdkModifierType)GDK_MOD1_MASK ) );
3191         GlobalCommands_insert( "CloneSelection", FreeCaller<Selection_Clone>(), Accelerator( GDK_space ) );
3192         GlobalCommands_insert( "CloneSelectionAndMakeUnique", FreeCaller<Selection_Clone_MakeUnique>(), Accelerator( GDK_space, (GdkModifierType)GDK_SHIFT_MASK ) );
3193         GlobalCommands_insert( "DeleteSelection", FreeCaller<deleteSelection>(), Accelerator( GDK_BackSpace ) );
3194         GlobalCommands_insert( "ParentSelection", FreeCaller<Scene_parentSelected>() );
3195         GlobalCommands_insert( "UnSelectSelection", FreeCaller<Selection_Deselect>(), Accelerator( GDK_Escape ) );
3196         GlobalCommands_insert( "InvertSelection", FreeCaller<Select_Invert>(), Accelerator( 'I' ) );
3197         GlobalCommands_insert( "SelectInside", FreeCaller<Select_Inside>() );
3198         GlobalCommands_insert( "SelectTouching", FreeCaller<Select_Touching>() );
3199         GlobalCommands_insert( "ExpandSelectionToEntities", FreeCaller<Scene_ExpandSelectionToEntities>(), Accelerator( 'E', (GdkModifierType)( GDK_MOD1_MASK | GDK_CONTROL_MASK ) ) );
3200         GlobalCommands_insert( "Preferences", FreeCaller<PreferencesDialog_showDialog>(), Accelerator( 'P' ) );
3201
3202         GlobalCommands_insert( "ToggleConsole", FreeCaller<Console_ToggleShow>(), Accelerator( 'O' ) );
3203         GlobalCommands_insert( "ToggleEntityInspector", FreeCaller<EntityInspector_ToggleShow>(), Accelerator( 'N' ) );
3204         GlobalCommands_insert( "EntityList", FreeCaller<EntityList_toggleShown>(), Accelerator( 'L' ) );
3205
3206         GlobalCommands_insert( "ShowHidden", FreeCaller<Select_ShowAllHidden>(), Accelerator( 'H', (GdkModifierType)GDK_SHIFT_MASK ) );
3207         GlobalCommands_insert( "HideSelected", FreeCaller<HideSelected>(), Accelerator( 'H' ) );
3208
3209         GlobalToggles_insert( "DragVertices", FreeCaller<SelectVertexMode>(), ToggleItem::AddCallbackCaller( g_vertexMode_button ), Accelerator( 'V' ) );
3210         GlobalToggles_insert( "DragEdges", FreeCaller<SelectEdgeMode>(), ToggleItem::AddCallbackCaller( g_edgeMode_button ), Accelerator( 'E' ) );
3211         GlobalToggles_insert( "DragFaces", FreeCaller<SelectFaceMode>(), ToggleItem::AddCallbackCaller( g_faceMode_button ), Accelerator( 'F' ) );
3212
3213         GlobalCommands_insert( "MirrorSelectionX", FreeCaller<Selection_Flipx>() );
3214         GlobalCommands_insert( "RotateSelectionX", FreeCaller<Selection_Rotatex>() );
3215         GlobalCommands_insert( "MirrorSelectionY", FreeCaller<Selection_Flipy>() );
3216         GlobalCommands_insert( "RotateSelectionY", FreeCaller<Selection_Rotatey>() );
3217         GlobalCommands_insert( "MirrorSelectionZ", FreeCaller<Selection_Flipz>() );
3218         GlobalCommands_insert( "RotateSelectionZ", FreeCaller<Selection_Rotatez>() );
3219
3220         GlobalCommands_insert( "ArbitraryRotation", FreeCaller<DoRotateDlg>() );
3221         GlobalCommands_insert( "ArbitraryScale", FreeCaller<DoScaleDlg>() );
3222
3223         GlobalCommands_insert( "BuildMenuCustomize", FreeCaller<DoBuildMenu>() );
3224
3225         GlobalCommands_insert( "FindBrush", FreeCaller<DoFind>() );
3226
3227         GlobalCommands_insert( "MapInfo", FreeCaller<DoMapInfo>(), Accelerator( 'M' ) );
3228
3229
3230         GlobalToggles_insert( "ToggleClipper", FreeCaller<ClipperMode>(), ToggleItem::AddCallbackCaller( g_clipper_button ), Accelerator( 'X' ) );
3231
3232         GlobalToggles_insert( "MouseTranslate", FreeCaller<TranslateMode>(), ToggleItem::AddCallbackCaller( g_translatemode_button ), Accelerator( 'W' ) );
3233         GlobalToggles_insert( "MouseRotate", FreeCaller<RotateMode>(), ToggleItem::AddCallbackCaller( g_rotatemode_button ), Accelerator( 'R' ) );
3234         GlobalToggles_insert( "MouseScale", FreeCaller<ScaleMode>(), ToggleItem::AddCallbackCaller( g_scalemode_button ) );
3235         GlobalToggles_insert( "MouseDrag", FreeCaller<DragMode>(), ToggleItem::AddCallbackCaller( g_dragmode_button ), Accelerator( 'Q' ) );
3236
3237         GlobalCommands_insert( "ColorSchemeOriginal", FreeCaller<ColorScheme_Original>() );
3238         GlobalCommands_insert( "ColorSchemeQER", FreeCaller<ColorScheme_QER>() );
3239         GlobalCommands_insert( "ColorSchemeBlackAndGreen", FreeCaller<ColorScheme_Black>() );
3240         GlobalCommands_insert( "ColorSchemeYdnar", FreeCaller<ColorScheme_Ydnar>() );
3241         GlobalCommands_insert( "ChooseTextureBackgroundColor", makeCallback( g_ColoursMenu.m_textureback ) );
3242         GlobalCommands_insert( "ChooseGridBackgroundColor", makeCallback( g_ColoursMenu.m_xyback ) );
3243         GlobalCommands_insert( "ChooseGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor ) );
3244         GlobalCommands_insert( "ChooseGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor ) );
3245         GlobalCommands_insert( "ChooseSmallGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor_alt ) );
3246         GlobalCommands_insert( "ChooseSmallGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor_alt ) );
3247         GlobalCommands_insert( "ChooseGridTextColor", makeCallback( g_ColoursMenu.m_gridtext ) );
3248         GlobalCommands_insert( "ChooseGridBlockColor", makeCallback( g_ColoursMenu.m_gridblock ) );
3249         GlobalCommands_insert( "ChooseBrushColor", makeCallback( g_ColoursMenu.m_brush ) );
3250         GlobalCommands_insert( "ChooseCameraBackgroundColor", makeCallback( g_ColoursMenu.m_cameraback ) );
3251         GlobalCommands_insert( "ChooseSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush ) );
3252         GlobalCommands_insert( "ChooseCameraSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush3d ) );
3253         GlobalCommands_insert( "ChooseClipperColor", makeCallback( g_ColoursMenu.m_clipper ) );
3254         GlobalCommands_insert( "ChooseOrthoViewNameColor", makeCallback( g_ColoursMenu.m_viewname ) );
3255
3256
3257         GlobalCommands_insert( "CSGSubtract", FreeCaller<CSG_Subtract>(), Accelerator( 'U', (GdkModifierType)GDK_SHIFT_MASK ) );
3258         GlobalCommands_insert( "CSGMerge", FreeCaller<CSG_Merge>(), Accelerator( 'U', (GdkModifierType)GDK_CONTROL_MASK ) );
3259         GlobalCommands_insert( "CSGHollow", FreeCaller<CSG_MakeHollow>() );
3260
3261         Grid_registerCommands();
3262
3263         GlobalCommands_insert( "SnapToGrid", FreeCaller<Selection_SnapToGrid>(), Accelerator( 'G', (GdkModifierType)GDK_CONTROL_MASK ) );
3264
3265         GlobalCommands_insert( "SelectAllOfType", FreeCaller<Select_AllOfType>(), Accelerator( 'A', (GdkModifierType)GDK_SHIFT_MASK ) );
3266
3267         GlobalCommands_insert( "TexRotateClock", FreeCaller<Texdef_RotateClockwise>(), Accelerator( GDK_Next, (GdkModifierType)GDK_SHIFT_MASK ) );
3268         GlobalCommands_insert( "TexRotateCounter", FreeCaller<Texdef_RotateAntiClockwise>(), Accelerator( GDK_Prior, (GdkModifierType)GDK_SHIFT_MASK ) );
3269         GlobalCommands_insert( "TexScaleUp", FreeCaller<Texdef_ScaleUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_CONTROL_MASK ) );
3270         GlobalCommands_insert( "TexScaleDown", FreeCaller<Texdef_ScaleDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_CONTROL_MASK ) );
3271         GlobalCommands_insert( "TexScaleLeft", FreeCaller<Texdef_ScaleLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_CONTROL_MASK ) );
3272         GlobalCommands_insert( "TexScaleRight", FreeCaller<Texdef_ScaleRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_CONTROL_MASK ) );
3273         GlobalCommands_insert( "TexShiftUp", FreeCaller<Texdef_ShiftUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_SHIFT_MASK ) );
3274         GlobalCommands_insert( "TexShiftDown", FreeCaller<Texdef_ShiftDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_SHIFT_MASK ) );
3275         GlobalCommands_insert( "TexShiftLeft", FreeCaller<Texdef_ShiftLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_SHIFT_MASK ) );
3276         GlobalCommands_insert( "TexShiftRight", FreeCaller<Texdef_ShiftRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_SHIFT_MASK ) );
3277
3278         GlobalCommands_insert( "MoveSelectionDOWN", FreeCaller<Selection_MoveDown>(), Accelerator( GDK_KP_Subtract ) );
3279         GlobalCommands_insert( "MoveSelectionUP", FreeCaller<Selection_MoveUp>(), Accelerator( GDK_KP_Add ) );
3280
3281         GlobalCommands_insert( "SelectNudgeLeft", FreeCaller<Selection_NudgeLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_MOD1_MASK ) );
3282         GlobalCommands_insert( "SelectNudgeRight", FreeCaller<Selection_NudgeRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_MOD1_MASK ) );
3283         GlobalCommands_insert( "SelectNudgeUp", FreeCaller<Selection_NudgeUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_MOD1_MASK ) );
3284         GlobalCommands_insert( "SelectNudgeDown", FreeCaller<Selection_NudgeDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_MOD1_MASK ) );
3285
3286         Patch_registerCommands();
3287         XYShow_registerCommands();
3288
3289         typedef FreeCaller1<const Selectable&, ComponentMode_SelectionChanged> ComponentModeSelectionChangedCaller;
3290         GlobalSelectionSystem().addSelectionChangeCallback( ComponentModeSelectionChangedCaller() );
3291
3292         GlobalPreferenceSystem().registerPreference( "DetachableMenus", BoolImportStringCaller( g_Layout_enableDetachableMenus.m_latched ), BoolExportStringCaller( g_Layout_enableDetachableMenus.m_latched ) );
3293         GlobalPreferenceSystem().registerPreference( "PatchToolBar", BoolImportStringCaller( g_Layout_enablePatchToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePatchToolbar.m_latched ) );
3294         GlobalPreferenceSystem().registerPreference( "PluginToolBar", BoolImportStringCaller( g_Layout_enablePluginToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePluginToolbar.m_latched ) );
3295         GlobalPreferenceSystem().registerPreference( "QE4StyleWindows", IntImportStringCaller( g_Layout_viewStyle.m_latched ), IntExportStringCaller( g_Layout_viewStyle.m_latched ) );
3296         GlobalPreferenceSystem().registerPreference( "XYHeight", IntImportStringCaller( g_layout_globals.nXYHeight ), IntExportStringCaller( g_layout_globals.nXYHeight ) );
3297         GlobalPreferenceSystem().registerPreference( "XYWidth", IntImportStringCaller( g_layout_globals.nXYWidth ), IntExportStringCaller( g_layout_globals.nXYWidth ) );
3298         GlobalPreferenceSystem().registerPreference( "CamWidth", IntImportStringCaller( g_layout_globals.nCamWidth ), IntExportStringCaller( g_layout_globals.nCamWidth ) );
3299         GlobalPreferenceSystem().registerPreference( "CamHeight", IntImportStringCaller( g_layout_globals.nCamHeight ), IntExportStringCaller( g_layout_globals.nCamHeight ) );
3300
3301         GlobalPreferenceSystem().registerPreference( "State", IntImportStringCaller( g_layout_globals.nState ), IntExportStringCaller( g_layout_globals.nState ) );
3302         GlobalPreferenceSystem().registerPreference( "PositionX", IntImportStringCaller( g_layout_globals.m_position.x ), IntExportStringCaller( g_layout_globals.m_position.x ) );
3303         GlobalPreferenceSystem().registerPreference( "PositionY", IntImportStringCaller( g_layout_globals.m_position.y ), IntExportStringCaller( g_layout_globals.m_position.y ) );
3304         GlobalPreferenceSystem().registerPreference( "Width", IntImportStringCaller( g_layout_globals.m_position.w ), IntExportStringCaller( g_layout_globals.m_position.w ) );
3305         GlobalPreferenceSystem().registerPreference( "Height", IntImportStringCaller( g_layout_globals.m_position.h ), IntExportStringCaller( g_layout_globals.m_position.h ) );
3306
3307         GlobalPreferenceSystem().registerPreference( "CamWnd", WindowPositionTrackerImportStringCaller( g_posCamWnd ), WindowPositionTrackerExportStringCaller( g_posCamWnd ) );
3308         GlobalPreferenceSystem().registerPreference( "XYWnd", WindowPositionTrackerImportStringCaller( g_posXYWnd ), WindowPositionTrackerExportStringCaller( g_posXYWnd ) );
3309         GlobalPreferenceSystem().registerPreference( "YZWnd", WindowPositionTrackerImportStringCaller( g_posYZWnd ), WindowPositionTrackerExportStringCaller( g_posYZWnd ) );
3310         GlobalPreferenceSystem().registerPreference( "XZWnd", WindowPositionTrackerImportStringCaller( g_posXZWnd ), WindowPositionTrackerExportStringCaller( g_posXZWnd ) );
3311
3312         {
3313                 const char* ENGINEPATH_ATTRIBUTE =
3314 #if defined( WIN32 )
3315                         "enginepath_win32"
3316 #elif defined( __APPLE__ )
3317                         "enginepath_macos"
3318 #elif defined( __linux__ ) || defined ( __FreeBSD__ )
3319                         "enginepath_linux"
3320 #else
3321 #error "unknown platform"
3322 #endif
3323                 ;
3324                 StringOutputStream path( 256 );
3325                 path << DirectoryCleaned( g_pGameDescription->getRequiredKeyValue( ENGINEPATH_ATTRIBUTE ) );
3326                 g_strEnginePath = path.c_str();
3327         }
3328
3329         GlobalPreferenceSystem().registerPreference( "EnginePath", CopiedStringImportStringCaller( g_strEnginePath ), CopiedStringExportStringCaller( g_strEnginePath ) );
3330
3331         g_Layout_viewStyle.useLatched();
3332         g_Layout_enableDetachableMenus.useLatched();
3333         g_Layout_enablePatchToolbar.useLatched();
3334         g_Layout_enablePluginToolbar.useLatched();
3335
3336         Layout_registerPreferencesPage();
3337         Paths_registerPreferencesPage();
3338
3339         g_brushCount.setCountChangedCallback( FreeCaller<QE_brushCountChanged>() );
3340         g_entityCount.setCountChangedCallback( FreeCaller<QE_entityCountChanged>() );
3341         GlobalEntityCreator().setCounter( &g_entityCount );
3342
3343         GLWidget_sharedContextCreated = GlobalGL_sharedContextCreated;
3344         GLWidget_sharedContextDestroyed = GlobalGL_sharedContextDestroyed;
3345
3346         GlobalEntityClassManager().attach( g_WorldspawnColourEntityClassObserver );
3347 }
3348
3349 void MainFrame_Destroy(){
3350         GlobalEntityClassManager().detach( g_WorldspawnColourEntityClassObserver );
3351
3352         GlobalEntityCreator().setCounter( 0 );
3353         g_entityCount.setCountChangedCallback( Callback() );
3354         g_brushCount.setCountChangedCallback( Callback() );
3355 }
3356
3357
3358 void GLWindow_Construct(){
3359         GlobalPreferenceSystem().registerPreference( "MouseButtons", IntImportStringCaller( g_glwindow_globals.m_nMouseType ), IntExportStringCaller( g_glwindow_globals.m_nMouseType ) );
3360 }
3361
3362 void GLWindow_Destroy(){
3363 }