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