]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/mainframe.cpp
Q3map2:
[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 class VFSModuleObserver : public ModuleObserver
150 {
151 std::size_t m_unrealised;
152 public:
153 VFSModuleObserver() : m_unrealised( 1 ){
154 }
155 void realise(){
156         if ( --m_unrealised == 0 ) {
157                 QE_InitVFS();
158                 GlobalFileSystem().initialise();
159         }
160 }
161 void unrealise(){
162         if ( ++m_unrealised == 1 ) {
163                 GlobalFileSystem().shutdown();
164         }
165 }
166 };
167
168 VFSModuleObserver g_VFSModuleObserver;
169
170 void VFS_Construct(){
171         Radiant_attachHomePathsObserver( g_VFSModuleObserver );
172 }
173 void VFS_Destroy(){
174         Radiant_detachHomePathsObserver( g_VFSModuleObserver );
175 }
176
177 // Home Paths
178
179 #ifdef WIN32
180 #include <shlobj.h>
181 #include <objbase.h>
182 const GUID qFOLDERID_SavedGames = {0x4C5C32FF, 0xBB9D, 0x43b0, {0xB5, 0xB4, 0x2D, 0x72, 0xE5, 0x4E, 0xAA, 0xA4}};
183 #define qREFKNOWNFOLDERID GUID
184 #define qKF_FLAG_CREATE 0x8000
185 #define qKF_FLAG_NO_ALIAS 0x1000
186 typedef HRESULT ( WINAPI qSHGetKnownFolderPath_t )( qREFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath );
187 static qSHGetKnownFolderPath_t *qSHGetKnownFolderPath;
188 #endif
189 void HomePaths_Realise(){
190         do
191         {
192                 const char* prefix = g_pGameDescription->getKeyValue( "prefix" );
193                 if ( !string_empty( prefix ) ) {
194                         StringOutputStream path( 256 );
195
196 #if defined( __APPLE__ )
197                         path.clear();
198                         path << DirectoryCleaned( g_get_home_dir() ) << "Library/Application Support" << ( prefix + 1 ) << "/";
199                         if ( file_is_directory( path.c_str() ) ) {
200                                 g_qeglobals.m_userEnginePath = path.c_str();
201                                 break;
202                         }
203 #endif
204
205 #if defined( WIN32 )
206                         TCHAR mydocsdir[MAX_PATH + 1];
207                         wchar_t *mydocsdirw;
208                         HMODULE shfolder = LoadLibrary( "shfolder.dll" );
209                         if ( shfolder ) {
210                                 qSHGetKnownFolderPath = (qSHGetKnownFolderPath_t *) GetProcAddress( shfolder, "SHGetKnownFolderPath" );
211                         }
212                         else{
213                                 qSHGetKnownFolderPath = NULL;
214                         }
215                         CoInitializeEx( NULL, COINIT_APARTMENTTHREADED );
216                         if ( qSHGetKnownFolderPath && qSHGetKnownFolderPath( qFOLDERID_SavedGames, qKF_FLAG_CREATE | qKF_FLAG_NO_ALIAS, NULL, &mydocsdirw ) == S_OK ) {
217                                 memset( mydocsdir, 0, sizeof( mydocsdir ) );
218                                 wcstombs( mydocsdir, mydocsdirw, sizeof( mydocsdir ) - 1 );
219                                 CoTaskMemFree( mydocsdirw );
220                                 path.clear();
221                                 path << DirectoryCleaned( mydocsdir ) << ( prefix + 1 ) << "/";
222                                 if ( file_is_directory( path.c_str() ) ) {
223                                         g_qeglobals.m_userEnginePath = path.c_str();
224                                         CoUninitialize();
225                                         FreeLibrary( shfolder );
226                                         break;
227                                 }
228                         }
229                         CoUninitialize();
230                         if ( shfolder ) {
231                                 FreeLibrary( shfolder );
232                         }
233                         if ( SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, 0, mydocsdir ) ) {
234                                 path.clear();
235                                 path << DirectoryCleaned( mydocsdir ) << "My Games/" << ( prefix + 1 ) << "/";
236                                 // win32: only add it if it already exists
237                                 if ( file_is_directory( path.c_str() ) ) {
238                                         g_qeglobals.m_userEnginePath = path.c_str();
239                                         break;
240                                 }
241                         }
242 #endif
243
244 #if defined( POSIX )
245                         path.clear();
246                         path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
247                         g_qeglobals.m_userEnginePath = path.c_str();
248                         break;
249 #endif
250                 }
251
252                 g_qeglobals.m_userEnginePath = EnginePath_get();
253         }
254         while ( 0 );
255
256         Q_mkdir( g_qeglobals.m_userEnginePath.c_str() );
257
258         {
259                 StringOutputStream path( 256 );
260                 path << g_qeglobals.m_userEnginePath.c_str() << gamename_get() << '/';
261                 g_qeglobals.m_userGamePath = path.c_str();
262         }
263         ASSERT_MESSAGE( !string_empty( g_qeglobals.m_userGamePath.c_str() ), "HomePaths_Realise: user-game-path is empty" );
264         Q_mkdir( g_qeglobals.m_userGamePath.c_str() );
265 }
266
267 ModuleObservers g_homePathObservers;
268
269 void Radiant_attachHomePathsObserver( ModuleObserver& observer ){
270         g_homePathObservers.attach( observer );
271 }
272
273 void Radiant_detachHomePathsObserver( ModuleObserver& observer ){
274         g_homePathObservers.detach( observer );
275 }
276
277 class HomePathsModuleObserver : public ModuleObserver
278 {
279 std::size_t m_unrealised;
280 public:
281 HomePathsModuleObserver() : m_unrealised( 1 ){
282 }
283 void realise(){
284         if ( --m_unrealised == 0 ) {
285                 HomePaths_Realise();
286                 g_homePathObservers.realise();
287         }
288 }
289 void unrealise(){
290         if ( ++m_unrealised == 1 ) {
291                 g_homePathObservers.unrealise();
292         }
293 }
294 };
295
296 HomePathsModuleObserver g_HomePathsModuleObserver;
297
298 void HomePaths_Construct(){
299         Radiant_attachEnginePathObserver( g_HomePathsModuleObserver );
300 }
301 void HomePaths_Destroy(){
302         Radiant_detachEnginePathObserver( g_HomePathsModuleObserver );
303 }
304
305
306 // Engine Path
307
308 CopiedString g_strEnginePath;
309 ModuleObservers g_enginePathObservers;
310 std::size_t g_enginepath_unrealised = 1;
311
312 void Radiant_attachEnginePathObserver( ModuleObserver& observer ){
313         g_enginePathObservers.attach( observer );
314 }
315
316 void Radiant_detachEnginePathObserver( ModuleObserver& observer ){
317         g_enginePathObservers.detach( observer );
318 }
319
320
321 void EnginePath_Realise(){
322         if ( --g_enginepath_unrealised == 0 ) {
323                 g_enginePathObservers.realise();
324         }
325 }
326
327
328 const char* EnginePath_get(){
329         ASSERT_MESSAGE( g_enginepath_unrealised == 0, "EnginePath_get: engine path not realised" );
330         return g_strEnginePath.c_str();
331 }
332
333 void EnginePath_Unrealise(){
334         if ( ++g_enginepath_unrealised == 1 ) {
335                 g_enginePathObservers.unrealise();
336         }
337 }
338
339 void setEnginePath( const char* path ){
340         StringOutputStream buffer( 256 );
341         buffer << DirectoryCleaned( path );
342         if ( !path_equal( buffer.c_str(), g_strEnginePath.c_str() ) ) {
343 #if 0
344                 while ( !ConfirmModified( "Paths Changed" ) )
345                 {
346                         if ( Map_Unnamed( g_map ) ) {
347                                 Map_SaveAs();
348                         }
349                         else
350                         {
351                                 Map_Save();
352                         }
353                 }
354                 Map_RegionOff();
355 #endif
356
357                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Changing Engine Path" );
358
359                 EnginePath_Unrealise();
360
361                 g_strEnginePath = buffer.c_str();
362
363                 EnginePath_Realise();
364         }
365 }
366
367
368 // App Path
369
370 CopiedString g_strAppPath;                 ///< holds the full path of the executable
371
372 const char* AppPath_get(){
373         return g_strAppPath.c_str();
374 }
375
376 /// the path to the local rc-dir
377 const char* LocalRcPath_get( void ){
378         static CopiedString rc_path;
379         if ( rc_path.empty() ) {
380                 StringOutputStream stream( 256 );
381                 stream << GlobalRadiant().getSettingsPath() << g_pGameDescription->mGameFile.c_str() << "/";
382                 rc_path = stream.c_str();
383         }
384         return rc_path.c_str();
385 }
386
387 /// directory for temp files
388 /// NOTE: on *nix this is were we check for .pid
389 CopiedString g_strSettingsPath;
390 const char* SettingsPath_get(){
391         return g_strSettingsPath.c_str();
392 }
393
394
395 /*!
396    points to the game tools directory, for instance
397    C:/Program Files/Quake III Arena/GtkRadiant
398    (or other games)
399    this is one of the main variables that are configured by the game selection on startup
400    [GameToolsPath]/plugins
401    [GameToolsPath]/modules
402    and also q3map, bspc
403  */
404 CopiedString g_strGameToolsPath;           ///< this is set by g_GamesDialog
405
406 const char* GameToolsPath_get(){
407         return g_strGameToolsPath.c_str();
408 }
409
410 void EnginePathImport( CopiedString& self, const char* value ){
411         setEnginePath( value );
412 }
413 typedef ReferenceCaller1<CopiedString, const char*, EnginePathImport> EnginePathImportCaller;
414
415 void Paths_constructPreferences( PreferencesPage& page ){
416         page.appendPathEntry( "Engine Path", true,
417                                                   StringImportCallback( EnginePathImportCaller( g_strEnginePath ) ),
418                                                   StringExportCallback( StringExportCaller( g_strEnginePath ) )
419                                                   );
420 }
421 void Paths_constructPage( PreferenceGroup& group ){
422         PreferencesPage page( group.createPage( "Paths", "Path Settings" ) );
423         Paths_constructPreferences( page );
424 }
425 void Paths_registerPreferencesPage(){
426         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Paths_constructPage>() );
427 }
428
429
430 class PathsDialog : public Dialog
431 {
432 public:
433 GtkWindow* BuildDialog(){
434         GtkFrame* frame = create_dialog_frame( "Path settings", GTK_SHADOW_ETCHED_IN );
435
436         GtkVBox* vbox2 = create_dialog_vbox( 0, 4 );
437         gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( vbox2 ) );
438
439         {
440                 PreferencesPage preferencesPage( *this, GTK_WIDGET( vbox2 ) );
441                 Paths_constructPreferences( preferencesPage );
442         }
443
444         return create_simple_modal_dialog_window( "Engine Path Not Found", m_modal, GTK_WIDGET( frame ) );
445 }
446 };
447
448 PathsDialog g_PathsDialog;
449
450 void EnginePath_verify(){
451         if ( !file_exists( g_strEnginePath.c_str() ) ) {
452                 g_PathsDialog.Create();
453                 g_PathsDialog.DoModal();
454                 g_PathsDialog.Destroy();
455         }
456 }
457
458 namespace
459 {
460 CopiedString g_gamename;
461 CopiedString g_gamemode;
462 ModuleObservers g_gameNameObservers;
463 ModuleObservers g_gameModeObservers;
464 }
465
466 void Radiant_attachGameNameObserver( ModuleObserver& observer ){
467         g_gameNameObservers.attach( observer );
468 }
469
470 void Radiant_detachGameNameObserver( ModuleObserver& observer ){
471         g_gameNameObservers.detach( observer );
472 }
473
474 const char* basegame_get(){
475         return g_pGameDescription->getRequiredKeyValue( "basegame" );
476 }
477
478 const char* gamename_get(){
479         const char* gamename = g_gamename.c_str();
480         if ( string_empty( gamename ) ) {
481                 return basegame_get();
482         }
483         return gamename;
484 }
485
486 void gamename_set( const char* gamename ){
487         if ( !string_equal( gamename, g_gamename.c_str() ) ) {
488                 g_gameNameObservers.unrealise();
489                 g_gamename = gamename;
490                 g_gameNameObservers.realise();
491         }
492 }
493
494 void Radiant_attachGameModeObserver( ModuleObserver& observer ){
495         g_gameModeObservers.attach( observer );
496 }
497
498 void Radiant_detachGameModeObserver( ModuleObserver& observer ){
499         g_gameModeObservers.detach( observer );
500 }
501
502 const char* gamemode_get(){
503         return g_gamemode.c_str();
504 }
505
506 void gamemode_set( const char* gamemode ){
507         if ( !string_equal( gamemode, g_gamemode.c_str() ) ) {
508                 g_gameModeObservers.unrealise();
509                 g_gamemode = gamemode;
510                 g_gameModeObservers.realise();
511         }
512 }
513
514 #include "os/dir.h"
515
516 class CLoadModule
517 {
518 const char* m_path;
519 public:
520 CLoadModule( const char* path ) : m_path( path ){
521 }
522 void operator()( const char* name ) const {
523         char fullname[1024];
524         ASSERT_MESSAGE( strlen( m_path ) + strlen( name ) < 1024, "" );
525         strcpy( fullname, m_path );
526         strcat( fullname, name );
527         globalOutputStream() << "Found '" << fullname << "'\n";
528         GlobalModuleServer_loadModule( fullname );
529 }
530 };
531
532 const char* const c_library_extension =
533 #if defined( WIN32 )
534         "dll"
535 #elif defined ( __APPLE__ )
536         "dylib"
537 #elif defined( __linux__ ) || defined ( __FreeBSD__ )
538         "so"
539 #endif
540 ;
541
542 void Radiant_loadModules( const char* path ){
543         Directory_forEach( path, MatchFileExtension<CLoadModule>( c_library_extension, CLoadModule( path ) ) );
544 }
545
546 void Radiant_loadModulesFromRoot( const char* directory ){
547         {
548                 StringOutputStream path( 256 );
549                 path << directory << g_pluginsDir;
550                 Radiant_loadModules( path.c_str() );
551         }
552
553         if ( !string_equal( g_pluginsDir, g_modulesDir ) ) {
554                 StringOutputStream path( 256 );
555                 path << directory << g_modulesDir;
556                 Radiant_loadModules( path.c_str() );
557         }
558 }
559
560 //! Make COLOR_BRUSHES override worldspawn eclass colour.
561 void SetWorldspawnColour( const Vector3& colour ){
562         EntityClass* worldspawn = GlobalEntityClassManager().findOrInsert( "worldspawn", true );
563         eclass_release_state( worldspawn );
564         worldspawn->color = colour;
565         eclass_capture_state( worldspawn );
566 }
567
568
569 class WorldspawnColourEntityClassObserver : public ModuleObserver
570 {
571 std::size_t m_unrealised;
572 public:
573 WorldspawnColourEntityClassObserver() : m_unrealised( 1 ){
574 }
575 void realise(){
576         if ( --m_unrealised == 0 ) {
577                 SetWorldspawnColour( g_xywindow_globals.color_brushes );
578         }
579 }
580 void unrealise(){
581         if ( ++m_unrealised == 1 ) {
582         }
583 }
584 };
585
586 WorldspawnColourEntityClassObserver g_WorldspawnColourEntityClassObserver;
587
588
589 ModuleObservers g_gameToolsPathObservers;
590
591 void Radiant_attachGameToolsPathObserver( ModuleObserver& observer ){
592         g_gameToolsPathObservers.attach( observer );
593 }
594
595 void Radiant_detachGameToolsPathObserver( ModuleObserver& observer ){
596         g_gameToolsPathObservers.detach( observer );
597 }
598
599 void Radiant_Initialise(){
600         GlobalModuleServer_Initialise();
601
602         Radiant_loadModulesFromRoot( AppPath_get() );
603
604         Preferences_Load();
605
606         bool success = Radiant_Construct( GlobalModuleServer_get() );
607         ASSERT_MESSAGE( success, "module system failed to initialise - see radiant.log for error messages" );
608
609         g_gameToolsPathObservers.realise();
610         g_gameModeObservers.realise();
611         g_gameNameObservers.realise();
612 }
613
614 void Radiant_Shutdown(){
615         g_gameNameObservers.unrealise();
616         g_gameModeObservers.unrealise();
617         g_gameToolsPathObservers.unrealise();
618
619         if ( !g_preferences_globals.disable_ini ) {
620                 globalOutputStream() << "Start writing prefs\n";
621                 Preferences_Save();
622                 globalOutputStream() << "Done prefs\n";
623         }
624
625         Radiant_Destroy();
626
627         GlobalModuleServer_Shutdown();
628 }
629
630 void Exit(){
631         if ( ConfirmModified( "Exit Radiant" ) ) {
632                 gtk_main_quit();
633         }
634 }
635
636
637 void Undo(){
638         GlobalUndoSystem().undo();
639         SceneChangeNotify();
640 }
641
642 void Redo(){
643         GlobalUndoSystem().redo();
644         SceneChangeNotify();
645 }
646
647 void deleteSelection(){
648         UndoableCommand undo( "deleteSelected" );
649         Select_Delete();
650 }
651
652 void Map_ExportSelected( TextOutputStream& ostream ){
653         Map_ExportSelected( ostream, Map_getFormat( g_map ) );
654 }
655
656 void Map_ImportSelected( TextInputStream& istream ){
657         Map_ImportSelected( istream, Map_getFormat( g_map ) );
658 }
659
660 void Selection_Copy(){
661         clipboard_copy( Map_ExportSelected );
662 }
663
664 void Selection_Paste(){
665         clipboard_paste( Map_ImportSelected );
666 }
667
668 void Copy(){
669         if ( SelectedFaces_empty() ) {
670                 Selection_Copy();
671         }
672         else
673         {
674                 SelectedFaces_copyTexture();
675         }
676 }
677
678 void Paste(){
679         if ( SelectedFaces_empty() ) {
680                 UndoableCommand undo( "paste" );
681
682                 GlobalSelectionSystem().setSelectedAll( false );
683                 Selection_Paste();
684         }
685         else
686         {
687                 SelectedFaces_pasteTexture();
688         }
689 }
690
691 void PasteToCamera(){
692         CamWnd& camwnd = *g_pParentWnd->GetCamWnd();
693         GlobalSelectionSystem().setSelectedAll( false );
694
695         UndoableCommand undo( "pasteToCamera" );
696
697         Selection_Paste();
698
699         // Work out the delta
700         Vector3 mid;
701         Select_GetMid( mid );
702         Vector3 delta = vector3_subtracted( vector3_snapped( Camera_getOrigin( camwnd ), GetSnapGridSize() ), mid );
703
704         // Move to camera
705         GlobalSelectionSystem().translateSelected( delta );
706 }
707
708
709 void ColorScheme_Original(){
710         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
711
712         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
713         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
714         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
715
716         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
717         g_xywindow_globals.color_gridminor = Vector3( 0.75f, 0.75f, 0.75f );
718         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
719         g_xywindow_globals.color_gridminor_alt = Vector3( 0.5f, 0.0f, 0.0f );
720         g_xywindow_globals.color_gridmajor_alt = Vector3( 1.0f, 0.0f, 0.0f );
721         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
722         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
723         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
724         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
725         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
726         SetWorldspawnColour( g_xywindow_globals.color_brushes );
727         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
728         XY_UpdateAllWindows();
729 }
730
731 void ColorScheme_QER(){
732         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
733
734         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
735         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
736         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
737
738         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
739         g_xywindow_globals.color_gridminor = Vector3( 1.0f, 1.0f, 1.0f );
740         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
741         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
742         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
743         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
744         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
745         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
746         SetWorldspawnColour( g_xywindow_globals.color_brushes );
747         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
748         XY_UpdateAllWindows();
749 }
750
751 void ColorScheme_Black(){
752         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
753
754         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
755         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
756         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
757
758         g_xywindow_globals.color_gridback = Vector3( 0.0f, 0.0f, 0.0f );
759         g_xywindow_globals.color_gridminor = Vector3( 0.2f, 0.2f, 0.2f );
760         g_xywindow_globals.color_gridmajor = Vector3( 0.3f, 0.5f, 0.5f );
761         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
762         g_xywindow_globals.color_gridtext = Vector3( 1.0f, 1.0f, 1.0f );
763         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
764         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
765         g_xywindow_globals.color_brushes = Vector3( 1.0f, 1.0f, 1.0f );
766         SetWorldspawnColour( g_xywindow_globals.color_brushes );
767         g_xywindow_globals.color_viewname = Vector3( 0.7f, 0.7f, 0.0f );
768         XY_UpdateAllWindows();
769 }
770
771 /* ydnar: to emulate maya/max/lightwave color schemes */
772 void ColorScheme_Ydnar(){
773         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
774
775         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
776         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
777         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
778
779         g_xywindow_globals.color_gridback = Vector3( 0.77f, 0.77f, 0.77f );
780         g_xywindow_globals.color_gridminor = Vector3( 0.83f, 0.83f, 0.83f );
781         g_xywindow_globals.color_gridmajor = Vector3( 0.89f, 0.89f, 0.89f );
782         g_xywindow_globals.color_gridblock = Vector3( 1.0f, 1.0f, 1.0f );
783         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
784         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
785         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
786         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
787         SetWorldspawnColour( g_xywindow_globals.color_brushes );
788         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
789         XY_UpdateAllWindows();
790 }
791
792 typedef Callback1<Vector3&> GetColourCallback;
793 typedef Callback1<const Vector3&> SetColourCallback;
794
795 class ChooseColour
796 {
797 GetColourCallback m_get;
798 SetColourCallback m_set;
799 public:
800 ChooseColour( const GetColourCallback& get, const SetColourCallback& set )
801         : m_get( get ), m_set( set ){
802 }
803 void operator()(){
804         Vector3 colour;
805         m_get( colour );
806         color_dialog( GTK_WIDGET( MainFrame_getWindow() ), colour );
807         m_set( colour );
808 }
809 };
810
811
812
813 void Colour_get( const Vector3& colour, Vector3& other ){
814         other = colour;
815 }
816 typedef ConstReferenceCaller1<Vector3, Vector3&, Colour_get> ColourGetCaller;
817
818 void Colour_set( Vector3& colour, const Vector3& other ){
819         colour = other;
820         SceneChangeNotify();
821 }
822 typedef ReferenceCaller1<Vector3, const Vector3&, Colour_set> ColourSetCaller;
823
824 void BrushColour_set( const Vector3& other ){
825         g_xywindow_globals.color_brushes = other;
826         SetWorldspawnColour( g_xywindow_globals.color_brushes );
827         SceneChangeNotify();
828 }
829 typedef FreeCaller1<const Vector3&, BrushColour_set> BrushColourSetCaller;
830
831 void ClipperColour_set( const Vector3& other ){
832         g_xywindow_globals.color_clipper = other;
833         Brush_clipperColourChanged();
834         SceneChangeNotify();
835 }
836 typedef FreeCaller1<const Vector3&, ClipperColour_set> ClipperColourSetCaller;
837
838 void TextureBrowserColour_get( Vector3& other ){
839         other = TextureBrowser_getBackgroundColour( GlobalTextureBrowser() );
840 }
841 typedef FreeCaller1<Vector3&, TextureBrowserColour_get> TextureBrowserColourGetCaller;
842
843 void TextureBrowserColour_set( const Vector3& other ){
844         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), other );
845 }
846 typedef FreeCaller1<const Vector3&, TextureBrowserColour_set> TextureBrowserColourSetCaller;
847
848
849 class ColoursMenu
850 {
851 public:
852 ChooseColour m_textureback;
853 ChooseColour m_xyback;
854 ChooseColour m_gridmajor;
855 ChooseColour m_gridminor;
856 ChooseColour m_gridmajor_alt;
857 ChooseColour m_gridminor_alt;
858 ChooseColour m_gridtext;
859 ChooseColour m_gridblock;
860 ChooseColour m_cameraback;
861 ChooseColour m_brush;
862 ChooseColour m_selectedbrush;
863 ChooseColour m_selectedbrush3d;
864 ChooseColour m_clipper;
865 ChooseColour m_viewname;
866
867 ColoursMenu() :
868         m_textureback( TextureBrowserColourGetCaller(), TextureBrowserColourSetCaller() ),
869         m_xyback( ColourGetCaller( g_xywindow_globals.color_gridback ), ColourSetCaller( g_xywindow_globals.color_gridback ) ),
870         m_gridmajor( ColourGetCaller( g_xywindow_globals.color_gridmajor ), ColourSetCaller( g_xywindow_globals.color_gridmajor ) ),
871         m_gridminor( ColourGetCaller( g_xywindow_globals.color_gridminor ), ColourSetCaller( g_xywindow_globals.color_gridminor ) ),
872         m_gridmajor_alt( ColourGetCaller( g_xywindow_globals.color_gridmajor_alt ), ColourSetCaller( g_xywindow_globals.color_gridmajor_alt ) ),
873         m_gridminor_alt( ColourGetCaller( g_xywindow_globals.color_gridminor_alt ), ColourSetCaller( g_xywindow_globals.color_gridminor_alt ) ),
874         m_gridtext( ColourGetCaller( g_xywindow_globals.color_gridtext ), ColourSetCaller( g_xywindow_globals.color_gridtext ) ),
875         m_gridblock( ColourGetCaller( g_xywindow_globals.color_gridblock ), ColourSetCaller( g_xywindow_globals.color_gridblock ) ),
876         m_cameraback( ColourGetCaller( g_camwindow_globals.color_cameraback ), ColourSetCaller( g_camwindow_globals.color_cameraback ) ),
877         m_brush( ColourGetCaller( g_xywindow_globals.color_brushes ), BrushColourSetCaller() ),
878         m_selectedbrush( ColourGetCaller( g_xywindow_globals.color_selbrushes ), ColourSetCaller( g_xywindow_globals.color_selbrushes ) ),
879         m_selectedbrush3d( ColourGetCaller( g_camwindow_globals.color_selbrushes3d ), ColourSetCaller( g_camwindow_globals.color_selbrushes3d ) ),
880         m_clipper( ColourGetCaller( g_xywindow_globals.color_clipper ), ClipperColourSetCaller() ),
881         m_viewname( ColourGetCaller( g_xywindow_globals.color_viewname ), ColourSetCaller( g_xywindow_globals.color_viewname ) ){
882 }
883 };
884
885 ColoursMenu g_ColoursMenu;
886
887 GtkMenuItem* create_colours_menu(){
888         GtkMenuItem* colours_menu_item = new_sub_menu_item_with_mnemonic( "Colors" );
889         GtkMenu* menu_in_menu = GTK_MENU( gtk_menu_item_get_submenu( colours_menu_item ) );
890         if ( g_Layout_enableDetachableMenus.m_value ) {
891                 menu_tearoff( menu_in_menu );
892         }
893
894         GtkMenu* menu_3 = create_sub_menu_with_mnemonic( menu_in_menu, "Themes" );
895         if ( g_Layout_enableDetachableMenus.m_value ) {
896                 menu_tearoff( menu_3 );
897         }
898
899         create_menu_item_with_mnemonic( menu_3, "QE4 Original", "ColorSchemeOriginal" );
900         create_menu_item_with_mnemonic( menu_3, "Q3Radiant Original", "ColorSchemeQER" );
901         create_menu_item_with_mnemonic( menu_3, "Black and Green", "ColorSchemeBlackAndGreen" );
902         create_menu_item_with_mnemonic( menu_3, "Maya/Max/Lightwave Emulation", "ColorSchemeYdnar" );
903
904         menu_separator( menu_in_menu );
905
906         create_menu_item_with_mnemonic( menu_in_menu, "_Texture Background...", "ChooseTextureBackgroundColor" );
907         create_menu_item_with_mnemonic( menu_in_menu, "Grid Background...", "ChooseGridBackgroundColor" );
908         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major...", "ChooseGridMajorColor" );
909         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor...", "ChooseGridMinorColor" );
910         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major Small...", "ChooseSmallGridMajorColor" );
911         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor Small...", "ChooseSmallGridMinorColor" );
912         create_menu_item_with_mnemonic( menu_in_menu, "Grid Text...", "ChooseGridTextColor" );
913         create_menu_item_with_mnemonic( menu_in_menu, "Grid Block...", "ChooseGridBlockColor" );
914         create_menu_item_with_mnemonic( menu_in_menu, "Default Brush...", "ChooseBrushColor" );
915         create_menu_item_with_mnemonic( menu_in_menu, "Camera Background...", "ChooseCameraBackgroundColor" );
916         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush...", "ChooseSelectedBrushColor" );
917         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush (Camera)...", "ChooseCameraSelectedBrushColor" );
918         create_menu_item_with_mnemonic( menu_in_menu, "Clipper...", "ChooseClipperColor" );
919         create_menu_item_with_mnemonic( menu_in_menu, "Active View name...", "ChooseOrthoViewNameColor" );
920
921         return colours_menu_item;
922 }
923
924
925 void Restart(){
926         PluginsMenu_clear();
927         PluginToolbar_clear();
928
929         Radiant_Shutdown();
930         Radiant_Initialise();
931
932         PluginsMenu_populate();
933
934         PluginToolbar_populate();
935 }
936
937
938 void thunk_OnSleep(){
939         g_pParentWnd->OnSleep();
940 }
941
942 void OpenUpdateURL(){
943         // build the URL
944         StringOutputStream URL( 256 );
945         URL << "http://www.icculus.org/netradiant/?cmd=update&data=dlupdate&query_dlup=1";
946 #ifdef WIN32
947         URL << "&OS_dlup=1";
948 #elif defined( __APPLE__ )
949         URL << "&OS_dlup=2";
950 #else
951         URL << "&OS_dlup=3";
952 #endif
953         URL << "&Version_dlup=" RADIANT_VERSION;
954         g_GamesDialog.AddPacksURL( URL );
955         OpenURL( URL.c_str() );
956 }
957
958 // open the Q3Rad manual
959 void OpenHelpURL(){
960         // at least on win32, AppPath + "docs/index.html"
961         StringOutputStream help( 256 );
962         help << AppPath_get() << "docs/index.html";
963         OpenURL( help.c_str() );
964 }
965
966 void OpenBugReportURL(){
967         OpenURL( "http://www.icculus.org/netradiant/?cmd=bugs" );
968 }
969
970
971 GtkWidget* g_page_console;
972
973 void Console_ToggleShow(){
974         GroupDialog_showPage( g_page_console );
975 }
976
977 GtkWidget* g_page_entity;
978
979 void EntityInspector_ToggleShow(){
980         GroupDialog_showPage( g_page_entity );
981 }
982
983
984
985 void SetClipMode( bool enable );
986 void ModeChangeNotify();
987
988 typedef void ( *ToolMode )();
989 ToolMode g_currentToolMode = 0;
990 bool g_currentToolModeSupportsComponentEditing = false;
991 ToolMode g_defaultToolMode = 0;
992
993
994
995 void SelectionSystem_DefaultMode(){
996         GlobalSelectionSystem().SetMode( SelectionSystem::ePrimitive );
997         GlobalSelectionSystem().SetComponentMode( SelectionSystem::eDefault );
998         ModeChangeNotify();
999 }
1000
1001
1002 bool EdgeMode(){
1003         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1004                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eEdge;
1005 }
1006
1007 bool VertexMode(){
1008         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1009                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex;
1010 }
1011
1012 bool FaceMode(){
1013         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1014                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace;
1015 }
1016
1017 template<bool( *BoolFunction ) ( )>
1018 class BoolFunctionExport
1019 {
1020 public:
1021 static void apply( const BoolImportCallback& importCallback ){
1022         importCallback( BoolFunction() );
1023 }
1024 };
1025
1026 typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<EdgeMode>::apply> EdgeModeApplyCaller;
1027 EdgeModeApplyCaller g_edgeMode_button_caller;
1028 BoolExportCallback g_edgeMode_button_callback( g_edgeMode_button_caller );
1029 ToggleItem g_edgeMode_button( g_edgeMode_button_callback );
1030
1031 typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<VertexMode>::apply> VertexModeApplyCaller;
1032 VertexModeApplyCaller g_vertexMode_button_caller;
1033 BoolExportCallback g_vertexMode_button_callback( g_vertexMode_button_caller );
1034 ToggleItem g_vertexMode_button( g_vertexMode_button_callback );
1035
1036 typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<FaceMode>::apply> FaceModeApplyCaller;
1037 FaceModeApplyCaller g_faceMode_button_caller;
1038 BoolExportCallback g_faceMode_button_callback( g_faceMode_button_caller );
1039 ToggleItem g_faceMode_button( g_faceMode_button_callback );
1040
1041 void ComponentModeChanged(){
1042         g_edgeMode_button.update();
1043         g_vertexMode_button.update();
1044         g_faceMode_button.update();
1045 }
1046
1047 void ComponentMode_SelectionChanged( const Selectable& selectable ){
1048         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1049                  && GlobalSelectionSystem().countSelected() == 0 ) {
1050                 SelectionSystem_DefaultMode();
1051                 ComponentModeChanged();
1052         }
1053 }
1054
1055 void SelectEdgeMode(){
1056 #if 0
1057         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1058                 GlobalSelectionSystem().Select( false );
1059         }
1060 #endif
1061
1062         if ( EdgeMode() ) {
1063                 SelectionSystem_DefaultMode();
1064         }
1065         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1066                 if ( !g_currentToolModeSupportsComponentEditing ) {
1067                         g_defaultToolMode();
1068                 }
1069
1070                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1071                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eEdge );
1072         }
1073
1074         ComponentModeChanged();
1075
1076         ModeChangeNotify();
1077 }
1078
1079 void SelectVertexMode(){
1080 #if 0
1081         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1082                 GlobalSelectionSystem().Select( false );
1083         }
1084 #endif
1085
1086         if ( VertexMode() ) {
1087                 SelectionSystem_DefaultMode();
1088         }
1089         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1090                 if ( !g_currentToolModeSupportsComponentEditing ) {
1091                         g_defaultToolMode();
1092                 }
1093
1094                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1095                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eVertex );
1096         }
1097
1098         ComponentModeChanged();
1099
1100         ModeChangeNotify();
1101 }
1102
1103 void SelectFaceMode(){
1104 #if 0
1105         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1106                 GlobalSelectionSystem().Select( false );
1107         }
1108 #endif
1109
1110         if ( FaceMode() ) {
1111                 SelectionSystem_DefaultMode();
1112         }
1113         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1114                 if ( !g_currentToolModeSupportsComponentEditing ) {
1115                         g_defaultToolMode();
1116                 }
1117
1118                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1119                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eFace );
1120         }
1121
1122         ComponentModeChanged();
1123
1124         ModeChangeNotify();
1125 }
1126
1127
1128 class CloneSelected : public scene::Graph::Walker
1129 {
1130 bool doMakeUnique;
1131 NodeSmartReference worldspawn;
1132 public:
1133 CloneSelected( bool d ) : doMakeUnique( d ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){
1134 }
1135 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1136         if ( path.size() == 1 ) {
1137                 return true;
1138         }
1139
1140         // ignore worldspawn, but keep checking children
1141         NodeSmartReference me( path.top().get() );
1142         if ( me == worldspawn ) {
1143                 return true;
1144         }
1145
1146         if ( !path.top().get().isRoot() ) {
1147                 Selectable* selectable = Instance_getSelectable( instance );
1148                 if ( selectable != 0
1149                          && selectable->isSelected() ) {
1150                         return false;
1151                 }
1152         }
1153
1154         return true;
1155 }
1156 void post( const scene::Path& path, scene::Instance& instance ) const {
1157         if ( path.size() == 1 ) {
1158                 return;
1159         }
1160
1161         // ignore worldspawn, but keep checking children
1162         NodeSmartReference me( path.top().get() );
1163         if ( me == worldspawn ) {
1164                 return;
1165         }
1166
1167         if ( !path.top().get().isRoot() ) {
1168                 Selectable* selectable = Instance_getSelectable( instance );
1169                 if ( selectable != 0
1170                          && selectable->isSelected() ) {
1171                         NodeSmartReference clone( Node_Clone( path.top() ) );
1172                         if ( doMakeUnique ) {
1173                                 Map_gatherNamespaced( clone );
1174                         }
1175                         Node_getTraversable( path.parent().get() )->insert( clone );
1176                 }
1177         }
1178 }
1179 };
1180
1181 void Scene_Clone_Selected( scene::Graph& graph, bool doMakeUnique ){
1182         graph.traverse( CloneSelected( doMakeUnique ) );
1183
1184         Map_mergeClonedNames();
1185 }
1186
1187 enum ENudgeDirection
1188 {
1189         eNudgeUp = 1,
1190         eNudgeDown = 3,
1191         eNudgeLeft = 0,
1192         eNudgeRight = 2,
1193 };
1194
1195 struct AxisBase
1196 {
1197         Vector3 x;
1198         Vector3 y;
1199         Vector3 z;
1200         AxisBase( const Vector3& x_, const Vector3& y_, const Vector3& z_ )
1201                 : x( x_ ), y( y_ ), z( z_ ){
1202         }
1203 };
1204
1205 AxisBase AxisBase_forViewType( VIEWTYPE viewtype ){
1206         switch ( viewtype )
1207         {
1208         case XY:
1209                 return AxisBase( g_vector3_axis_x, g_vector3_axis_y, g_vector3_axis_z );
1210         case XZ:
1211                 return AxisBase( g_vector3_axis_x, g_vector3_axis_z, g_vector3_axis_y );
1212         case YZ:
1213                 return AxisBase( g_vector3_axis_y, g_vector3_axis_z, g_vector3_axis_x );
1214         }
1215
1216         ERROR_MESSAGE( "invalid viewtype" );
1217         return AxisBase( Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ) );
1218 }
1219
1220 Vector3 AxisBase_axisForDirection( const AxisBase& axes, ENudgeDirection direction ){
1221         switch ( direction )
1222         {
1223         case eNudgeLeft:
1224                 return vector3_negated( axes.x );
1225         case eNudgeUp:
1226                 return axes.y;
1227         case eNudgeRight:
1228                 return axes.x;
1229         case eNudgeDown:
1230                 return vector3_negated( axes.y );
1231         }
1232
1233         ERROR_MESSAGE( "invalid direction" );
1234         return Vector3( 0, 0, 0 );
1235 }
1236
1237 void NudgeSelection( ENudgeDirection direction, float fAmount, VIEWTYPE viewtype ){
1238         AxisBase axes( AxisBase_forViewType( viewtype ) );
1239         Vector3 view_direction( vector3_negated( axes.z ) );
1240         Vector3 nudge( vector3_scaled( AxisBase_axisForDirection( axes, direction ), fAmount ) );
1241         GlobalSelectionSystem().NudgeManipulator( nudge, view_direction );
1242 }
1243
1244 void Selection_Clone(){
1245         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
1246                 UndoableCommand undo( "cloneSelected" );
1247
1248                 Scene_Clone_Selected( GlobalSceneGraph(), false );
1249
1250                 //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1251                 //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1252         }
1253 }
1254
1255 void Selection_Clone_MakeUnique(){
1256         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
1257                 UndoableCommand undo( "cloneSelectedMakeUnique" );
1258
1259                 Scene_Clone_Selected( GlobalSceneGraph(), true );
1260
1261                 //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1262                 //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1263         }
1264 }
1265
1266 // called when the escape key is used (either on the main window or on an inspector)
1267 void Selection_Deselect(){
1268         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1269                 if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
1270                         GlobalSelectionSystem().setSelectedAllComponents( false );
1271                 }
1272                 else
1273                 {
1274                         SelectionSystem_DefaultMode();
1275                         ComponentModeChanged();
1276                 }
1277         }
1278         else
1279         {
1280                 if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
1281                         GlobalSelectionSystem().setSelectedAllComponents( false );
1282                 }
1283                 else
1284                 {
1285                         GlobalSelectionSystem().setSelectedAll( false );
1286                 }
1287         }
1288 }
1289
1290
1291 void Selection_NudgeUp(){
1292         UndoableCommand undo( "nudgeSelectedUp" );
1293         NudgeSelection( eNudgeUp, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1294 }
1295
1296 void Selection_NudgeDown(){
1297         UndoableCommand undo( "nudgeSelectedDown" );
1298         NudgeSelection( eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1299 }
1300
1301 void Selection_NudgeLeft(){
1302         UndoableCommand undo( "nudgeSelectedLeft" );
1303         NudgeSelection( eNudgeLeft, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1304 }
1305
1306 void Selection_NudgeRight(){
1307         UndoableCommand undo( "nudgeSelectedRight" );
1308         NudgeSelection( eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1309 }
1310
1311
1312 void TranslateToolExport( const BoolImportCallback& importCallback ){
1313         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eTranslate );
1314 }
1315
1316 void RotateToolExport( const BoolImportCallback& importCallback ){
1317         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eRotate );
1318 }
1319
1320 void ScaleToolExport( const BoolImportCallback& importCallback ){
1321         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eScale );
1322 }
1323
1324 void DragToolExport( const BoolImportCallback& importCallback ){
1325         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag );
1326 }
1327
1328 void ClipperToolExport( const BoolImportCallback& importCallback ){
1329         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip );
1330 }
1331
1332 FreeCaller1<const BoolImportCallback&, TranslateToolExport> g_translatemode_button_caller;
1333 BoolExportCallback g_translatemode_button_callback( g_translatemode_button_caller );
1334 ToggleItem g_translatemode_button( g_translatemode_button_callback );
1335
1336 FreeCaller1<const BoolImportCallback&, RotateToolExport> g_rotatemode_button_caller;
1337 BoolExportCallback g_rotatemode_button_callback( g_rotatemode_button_caller );
1338 ToggleItem g_rotatemode_button( g_rotatemode_button_callback );
1339
1340 FreeCaller1<const BoolImportCallback&, ScaleToolExport> g_scalemode_button_caller;
1341 BoolExportCallback g_scalemode_button_callback( g_scalemode_button_caller );
1342 ToggleItem g_scalemode_button( g_scalemode_button_callback );
1343
1344 FreeCaller1<const BoolImportCallback&, DragToolExport> g_dragmode_button_caller;
1345 BoolExportCallback g_dragmode_button_callback( g_dragmode_button_caller );
1346 ToggleItem g_dragmode_button( g_dragmode_button_callback );
1347
1348 FreeCaller1<const BoolImportCallback&, ClipperToolExport> g_clipper_button_caller;
1349 BoolExportCallback g_clipper_button_callback( g_clipper_button_caller );
1350 ToggleItem g_clipper_button( g_clipper_button_callback );
1351
1352 void ToolChanged(){
1353         g_translatemode_button.update();
1354         g_rotatemode_button.update();
1355         g_scalemode_button.update();
1356         g_dragmode_button.update();
1357         g_clipper_button.update();
1358 }
1359
1360 const char* const c_ResizeMode_status = "QE4 Drag Tool: move and resize objects";
1361
1362 void DragMode(){
1363         if ( g_currentToolMode == DragMode && g_defaultToolMode != DragMode ) {
1364                 g_defaultToolMode();
1365         }
1366         else
1367         {
1368                 g_currentToolMode = DragMode;
1369                 g_currentToolModeSupportsComponentEditing = true;
1370
1371                 OnClipMode( false );
1372
1373                 Sys_Status( c_ResizeMode_status );
1374                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eDrag );
1375                 ToolChanged();
1376                 ModeChangeNotify();
1377         }
1378 }
1379
1380
1381 const char* const c_TranslateMode_status = "Translate Tool: translate objects and components";
1382
1383 void TranslateMode(){
1384         if ( g_currentToolMode == TranslateMode && g_defaultToolMode != TranslateMode ) {
1385                 g_defaultToolMode();
1386         }
1387         else
1388         {
1389                 g_currentToolMode = TranslateMode;
1390                 g_currentToolModeSupportsComponentEditing = true;
1391
1392                 OnClipMode( false );
1393
1394                 Sys_Status( c_TranslateMode_status );
1395                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eTranslate );
1396                 ToolChanged();
1397                 ModeChangeNotify();
1398         }
1399 }
1400
1401 const char* const c_RotateMode_status = "Rotate Tool: rotate objects and components";
1402
1403 void RotateMode(){
1404         if ( g_currentToolMode == RotateMode && g_defaultToolMode != RotateMode ) {
1405                 g_defaultToolMode();
1406         }
1407         else
1408         {
1409                 g_currentToolMode = RotateMode;
1410                 g_currentToolModeSupportsComponentEditing = true;
1411
1412                 OnClipMode( false );
1413
1414                 Sys_Status( c_RotateMode_status );
1415                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eRotate );
1416                 ToolChanged();
1417                 ModeChangeNotify();
1418         }
1419 }
1420
1421 const char* const c_ScaleMode_status = "Scale Tool: scale objects and components";
1422
1423 void ScaleMode(){
1424         if ( g_currentToolMode == ScaleMode && g_defaultToolMode != ScaleMode ) {
1425                 g_defaultToolMode();
1426         }
1427         else
1428         {
1429                 g_currentToolMode = ScaleMode;
1430                 g_currentToolModeSupportsComponentEditing = true;
1431
1432                 OnClipMode( false );
1433
1434                 Sys_Status( c_ScaleMode_status );
1435                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eScale );
1436                 ToolChanged();
1437                 ModeChangeNotify();
1438         }
1439 }
1440
1441
1442 const char* const c_ClipperMode_status = "Clipper Tool: apply clip planes to objects";
1443
1444
1445 void ClipperMode(){
1446         if ( g_currentToolMode == ClipperMode && g_defaultToolMode != ClipperMode ) {
1447                 g_defaultToolMode();
1448         }
1449         else
1450         {
1451                 g_currentToolMode = ClipperMode;
1452                 g_currentToolModeSupportsComponentEditing = false;
1453
1454                 SelectionSystem_DefaultMode();
1455
1456                 OnClipMode( true );
1457
1458                 Sys_Status( c_ClipperMode_status );
1459                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eClip );
1460                 ToolChanged();
1461                 ModeChangeNotify();
1462         }
1463 }
1464
1465
1466 void Texdef_Rotate( float angle ){
1467         StringOutputStream command;
1468         command << "brushRotateTexture -angle " << angle;
1469         UndoableCommand undo( command.c_str() );
1470         Select_RotateTexture( angle );
1471 }
1472
1473 void Texdef_RotateClockwise(){
1474         Texdef_Rotate( static_cast<float>( fabs( g_si_globals.rotate ) ) );
1475 }
1476
1477 void Texdef_RotateAntiClockwise(){
1478         Texdef_Rotate( static_cast<float>( -fabs( g_si_globals.rotate ) ) );
1479 }
1480
1481 void Texdef_Scale( float x, float y ){
1482         StringOutputStream command;
1483         command << "brushScaleTexture -x " << x << " -y " << y;
1484         UndoableCommand undo( command.c_str() );
1485         Select_ScaleTexture( x, y );
1486 }
1487
1488 void Texdef_ScaleUp(){
1489         Texdef_Scale( 0, g_si_globals.scale[1] );
1490 }
1491
1492 void Texdef_ScaleDown(){
1493         Texdef_Scale( 0, -g_si_globals.scale[1] );
1494 }
1495
1496 void Texdef_ScaleLeft(){
1497         Texdef_Scale( -g_si_globals.scale[0],0 );
1498 }
1499
1500 void Texdef_ScaleRight(){
1501         Texdef_Scale( g_si_globals.scale[0],0 );
1502 }
1503
1504 void Texdef_Shift( float x, float y ){
1505         StringOutputStream command;
1506         command << "brushShiftTexture -x " << x << " -y " << y;
1507         UndoableCommand undo( command.c_str() );
1508         Select_ShiftTexture( x, y );
1509 }
1510
1511 void Texdef_ShiftLeft(){
1512         Texdef_Shift( -g_si_globals.shift[0], 0 );
1513 }
1514
1515 void Texdef_ShiftRight(){
1516         Texdef_Shift( g_si_globals.shift[0], 0 );
1517 }
1518
1519 void Texdef_ShiftUp(){
1520         Texdef_Shift( 0, g_si_globals.shift[1] );
1521 }
1522
1523 void Texdef_ShiftDown(){
1524         Texdef_Shift( 0, -g_si_globals.shift[1] );
1525 }
1526
1527
1528
1529 class SnappableSnapToGridSelected : public scene::Graph::Walker
1530 {
1531 float m_snap;
1532 public:
1533 SnappableSnapToGridSelected( float snap )
1534         : m_snap( snap ){
1535 }
1536 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1537         if ( path.top().get().visible() ) {
1538                 Snappable* snappable = Node_getSnappable( path.top() );
1539                 if ( snappable != 0
1540                          && Instance_getSelectable( instance )->isSelected() ) {
1541                         snappable->snapto( m_snap );
1542                 }
1543         }
1544         return true;
1545 }
1546 };
1547
1548 void Scene_SnapToGrid_Selected( scene::Graph& graph, float snap ){
1549         graph.traverse( SnappableSnapToGridSelected( snap ) );
1550 }
1551
1552 class ComponentSnappableSnapToGridSelected : public scene::Graph::Walker
1553 {
1554 float m_snap;
1555 public:
1556 ComponentSnappableSnapToGridSelected( float snap )
1557         : m_snap( snap ){
1558 }
1559 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1560         if ( path.top().get().visible() ) {
1561                 ComponentSnappable* componentSnappable = Instance_getComponentSnappable( instance );
1562                 if ( componentSnappable != 0
1563                          && Instance_getSelectable( instance )->isSelected() ) {
1564                         componentSnappable->snapComponents( m_snap );
1565                 }
1566         }
1567         return true;
1568 }
1569 };
1570
1571 void Scene_SnapToGrid_Component_Selected( scene::Graph& graph, float snap ){
1572         graph.traverse( ComponentSnappableSnapToGridSelected( snap ) );
1573 }
1574
1575 void Selection_SnapToGrid(){
1576         StringOutputStream command;
1577         command << "snapSelected -grid " << GetGridSize();
1578         UndoableCommand undo( command.c_str() );
1579
1580         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1581                 Scene_SnapToGrid_Component_Selected( GlobalSceneGraph(), GetGridSize() );
1582         }
1583         else
1584         {
1585                 Scene_SnapToGrid_Selected( GlobalSceneGraph(), GetGridSize() );
1586         }
1587 }
1588
1589
1590 static gint qe_every_second( gpointer data ){
1591         GdkModifierType mask;
1592
1593         gdk_window_get_pointer( 0, 0, 0, &mask );
1594
1595         if ( ( mask & ( GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK ) ) == 0 ) {
1596                 QE_CheckAutoSave();
1597         }
1598
1599         return TRUE;
1600 }
1601
1602 guint s_qe_every_second_id = 0;
1603
1604 void EverySecondTimer_enable(){
1605         if ( s_qe_every_second_id == 0 ) {
1606                 s_qe_every_second_id = gtk_timeout_add( 1000, qe_every_second, 0 );
1607         }
1608 }
1609
1610 void EverySecondTimer_disable(){
1611         if ( s_qe_every_second_id != 0 ) {
1612                 gtk_timeout_remove( s_qe_every_second_id );
1613                 s_qe_every_second_id = 0;
1614         }
1615 }
1616
1617 gint window_realize_remove_decoration( GtkWidget* widget, gpointer data ){
1618         gdk_window_set_decorations( widget->window, (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MENU | GDK_DECOR_MINIMIZE | GDK_DECOR_MAXIMIZE ) );
1619         return FALSE;
1620 }
1621
1622 class WaitDialog
1623 {
1624 public:
1625 GtkWindow* m_window;
1626 GtkLabel* m_label;
1627 };
1628
1629 WaitDialog create_wait_dialog( const char* title, const char* text ){
1630         WaitDialog dialog;
1631
1632         dialog.m_window = create_floating_window( title, MainFrame_getWindow() );
1633         gtk_window_set_resizable( dialog.m_window, FALSE );
1634         gtk_container_set_border_width( GTK_CONTAINER( dialog.m_window ), 0 );
1635         gtk_window_set_position( dialog.m_window, GTK_WIN_POS_CENTER_ON_PARENT );
1636
1637         g_signal_connect( G_OBJECT( dialog.m_window ), "realize", G_CALLBACK( window_realize_remove_decoration ), 0 );
1638
1639         {
1640                 dialog.m_label = GTK_LABEL( gtk_label_new( text ) );
1641                 gtk_misc_set_alignment( GTK_MISC( dialog.m_label ), 0.0, 0.5 );
1642                 gtk_label_set_justify( dialog.m_label, GTK_JUSTIFY_LEFT );
1643                 gtk_widget_show( GTK_WIDGET( dialog.m_label ) );
1644                 gtk_widget_set_size_request( GTK_WIDGET( dialog.m_label ), 200, -1 );
1645
1646                 gtk_container_add( GTK_CONTAINER( dialog.m_window ), GTK_WIDGET( dialog.m_label ) );
1647         }
1648         return dialog;
1649 }
1650
1651 namespace
1652 {
1653 clock_t g_lastRedrawTime = 0;
1654 const clock_t c_redrawInterval = clock_t( CLOCKS_PER_SEC / 10 );
1655
1656 bool redrawRequired(){
1657         clock_t currentTime = std::clock();
1658         if ( currentTime - g_lastRedrawTime >= c_redrawInterval ) {
1659                 g_lastRedrawTime = currentTime;
1660                 return true;
1661         }
1662         return false;
1663 }
1664 }
1665
1666 bool MainFrame_isActiveApp(){
1667         //globalOutputStream() << "listing\n";
1668         GList* list = gtk_window_list_toplevels();
1669         for ( GList* i = list; i != 0; i = g_list_next( i ) )
1670         {
1671                 //globalOutputStream() << "toplevel.. ";
1672                 if ( gtk_window_is_active( GTK_WINDOW( i->data ) ) ) {
1673                         //globalOutputStream() << "is active\n";
1674                         return true;
1675                 }
1676                 //globalOutputStream() << "not active\n";
1677         }
1678         return false;
1679 }
1680
1681 typedef std::list<CopiedString> StringStack;
1682 StringStack g_wait_stack;
1683 WaitDialog g_wait;
1684
1685 bool ScreenUpdates_Enabled(){
1686         return g_wait_stack.empty();
1687 }
1688
1689 void ScreenUpdates_process(){
1690         if ( redrawRequired() && GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
1691                 process_gui();
1692         }
1693 }
1694
1695
1696 void ScreenUpdates_Disable( const char* message, const char* title ){
1697         if ( g_wait_stack.empty() ) {
1698                 EverySecondTimer_disable();
1699
1700                 process_gui();
1701
1702                 bool isActiveApp = MainFrame_isActiveApp();
1703
1704                 g_wait = create_wait_dialog( title, message );
1705                 gtk_grab_add( GTK_WIDGET( g_wait.m_window ) );
1706
1707                 if ( isActiveApp ) {
1708                         gtk_widget_show( GTK_WIDGET( g_wait.m_window ) );
1709                         ScreenUpdates_process();
1710                 }
1711         }
1712         else if ( GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
1713                 gtk_label_set_text( g_wait.m_label, message );
1714                 ScreenUpdates_process();
1715         }
1716         g_wait_stack.push_back( message );
1717 }
1718
1719 void ScreenUpdates_Enable(){
1720         ASSERT_MESSAGE( !ScreenUpdates_Enabled(), "screen updates already enabled" );
1721         g_wait_stack.pop_back();
1722         if ( g_wait_stack.empty() ) {
1723                 EverySecondTimer_enable();
1724                 //gtk_widget_set_sensitive(GTK_WIDGET(MainFrame_getWindow()), TRUE);
1725
1726                 gtk_grab_remove( GTK_WIDGET( g_wait.m_window ) );
1727                 destroy_floating_window( g_wait.m_window );
1728                 g_wait.m_window = 0;
1729
1730                 //gtk_window_present(MainFrame_getWindow());
1731         }
1732         else if ( GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
1733                 gtk_label_set_text( g_wait.m_label, g_wait_stack.back().c_str() );
1734                 ScreenUpdates_process();
1735         }
1736 }
1737
1738
1739
1740 void GlobalCamera_UpdateWindow(){
1741         if ( g_pParentWnd != 0 ) {
1742                 CamWnd_Update( *g_pParentWnd->GetCamWnd() );
1743         }
1744 }
1745
1746 void XY_UpdateWindow( MainFrame& mainframe ){
1747         if ( mainframe.GetXYWnd() != 0 ) {
1748                 XYWnd_Update( *mainframe.GetXYWnd() );
1749         }
1750 }
1751
1752 void XZ_UpdateWindow( MainFrame& mainframe ){
1753         if ( mainframe.GetXZWnd() != 0 ) {
1754                 XYWnd_Update( *mainframe.GetXZWnd() );
1755         }
1756 }
1757
1758 void YZ_UpdateWindow( MainFrame& mainframe ){
1759         if ( mainframe.GetYZWnd() != 0 ) {
1760                 XYWnd_Update( *mainframe.GetYZWnd() );
1761         }
1762 }
1763
1764 void XY_UpdateAllWindows( MainFrame& mainframe ){
1765         XY_UpdateWindow( mainframe );
1766         XZ_UpdateWindow( mainframe );
1767         YZ_UpdateWindow( mainframe );
1768 }
1769
1770 void XY_UpdateAllWindows(){
1771         if ( g_pParentWnd != 0 ) {
1772                 XY_UpdateAllWindows( *g_pParentWnd );
1773         }
1774 }
1775
1776 void UpdateAllWindows(){
1777         GlobalCamera_UpdateWindow();
1778         XY_UpdateAllWindows();
1779 }
1780
1781
1782 void ModeChangeNotify(){
1783         SceneChangeNotify();
1784 }
1785
1786 void ClipperChangeNotify(){
1787         GlobalCamera_UpdateWindow();
1788         XY_UpdateAllWindows();
1789 }
1790
1791
1792 LatchedInt g_Layout_viewStyle( 0, "Window Layout" );
1793 LatchedBool g_Layout_enableDetachableMenus( true, "Detachable Menus" );
1794 LatchedBool g_Layout_enablePatchToolbar( true, "Patch Toolbar" );
1795 LatchedBool g_Layout_enablePluginToolbar( true, "Plugin Toolbar" );
1796 LatchedBool g_Layout_enableFilterToolbar( true, "Filter Toolbar" );
1797
1798
1799
1800 GtkMenuItem* create_file_menu(){
1801         // File menu
1802         GtkMenuItem* file_menu_item = new_sub_menu_item_with_mnemonic( "_File" );
1803         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( file_menu_item ) );
1804         if ( g_Layout_enableDetachableMenus.m_value ) {
1805                 menu_tearoff( menu );
1806         }
1807
1808         create_menu_item_with_mnemonic( menu, "_New Map", "NewMap" );
1809         menu_separator( menu );
1810
1811 #if 0
1812         //++timo temporary experimental stuff for sleep mode..
1813         create_menu_item_with_mnemonic( menu, "_Sleep", "Sleep" );
1814         menu_separator( menu );
1815         // end experimental
1816 #endif
1817
1818         create_menu_item_with_mnemonic( menu, "_Open...", "OpenMap" );
1819
1820         create_menu_item_with_mnemonic( menu, "_Import...", "ImportMap" );
1821         create_menu_item_with_mnemonic( menu, "_Save", "SaveMap" );
1822         create_menu_item_with_mnemonic( menu, "Save _as...", "SaveMapAs" );
1823         create_menu_item_with_mnemonic( menu, "Save s_elected...", "SaveSelected" );
1824         menu_separator( menu );
1825         create_menu_item_with_mnemonic( menu, "Save re_gion...", "SaveRegion" );
1826 //      menu_separator( menu );
1827 //      create_menu_item_with_mnemonic( menu, "_Refresh models", "RefreshReferences" );
1828 //      menu_separator( menu );
1829         create_menu_item_with_mnemonic( menu, "Pro_ject settings...", "ProjectSettings" );
1830         menu_separator( menu );
1831         create_menu_item_with_mnemonic( menu, "_Pointfile...", "TogglePointfile" );
1832         menu_separator( menu );
1833         MRU_constructMenu( menu );
1834         menu_separator( menu );
1835 //      create_menu_item_with_mnemonic( menu, "Check for NetRadiant update (web)", "CheckForUpdate" ); // FIXME
1836         create_menu_item_with_mnemonic( menu, "E_xit", "Exit" );
1837
1838         return file_menu_item;
1839 }
1840
1841 GtkMenuItem* create_edit_menu(){
1842         // Edit menu
1843         GtkMenuItem* edit_menu_item = new_sub_menu_item_with_mnemonic( "_Edit" );
1844         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( edit_menu_item ) );
1845         if ( g_Layout_enableDetachableMenus.m_value ) {
1846                 menu_tearoff( menu );
1847         }
1848         create_menu_item_with_mnemonic( menu, "_Undo", "Undo" );
1849         create_menu_item_with_mnemonic( menu, "_Redo", "Redo" );
1850         menu_separator( menu );
1851         create_menu_item_with_mnemonic( menu, "_Copy", "Copy" );
1852         create_menu_item_with_mnemonic( menu, "_Paste", "Paste" );
1853         create_menu_item_with_mnemonic( menu, "P_aste To Camera", "PasteToCamera" );
1854         menu_separator( menu );
1855         create_menu_item_with_mnemonic( menu, "_Duplicate", "CloneSelection" );
1856         create_menu_item_with_mnemonic( menu, "Duplicate, make uni_que", "CloneSelectionAndMakeUnique" );
1857         create_menu_item_with_mnemonic( menu, "D_elete", "DeleteSelection" );
1858         menu_separator( menu );
1859         create_menu_item_with_mnemonic( menu, "Snap To Grid", "SnapToGrid" );
1860         //create_menu_item_with_mnemonic( menu, "Pa_rent", "ParentSelection" );
1861         menu_separator( menu );
1862         create_menu_item_with_mnemonic( menu, "C_lear Selection", "UnSelectSelection" );
1863         create_menu_item_with_mnemonic( menu, "_Invert Selection", "InvertSelection" );
1864         create_menu_item_with_mnemonic( menu, "Select i_nside", "SelectInside" );
1865         create_menu_item_with_mnemonic( menu, "Select _touching", "SelectTouching" );
1866
1867         menu_separator( menu );
1868
1869 //      GtkMenu* convert_menu = create_sub_menu_with_mnemonic( menu, "E_xpand Selection" );
1870 //      if ( g_Layout_enableDetachableMenus.m_value ) {
1871 //              menu_tearoff( convert_menu );
1872 //      }
1873         create_menu_item_with_mnemonic( menu, "Select All Of Type", "SelectAllOfType" );
1874         create_menu_item_with_mnemonic( menu, "_Expand Selection To Entities", "ExpandSelectionToEntities" );
1875
1876         menu_separator( menu );
1877         create_menu_item_with_mnemonic( menu, "Pre_ferences...", "Preferences" );
1878
1879         return edit_menu_item;
1880 }
1881
1882 void fill_view_xy_top_menu( GtkMenu* menu ){
1883         create_check_menu_item_with_mnemonic( menu, "XY (Top) View", "ToggleView" );
1884 }
1885
1886
1887 void fill_view_yz_side_menu( GtkMenu* menu ){
1888         create_check_menu_item_with_mnemonic( menu, "YZ (Side) View", "ToggleSideView" );
1889 }
1890
1891
1892 void fill_view_xz_front_menu( GtkMenu* menu ){
1893         create_check_menu_item_with_mnemonic( menu, "XZ (Front) View", "ToggleFrontView" );
1894 }
1895
1896
1897 GtkWidget* g_toggle_z_item = 0;
1898 GtkWidget* g_toggle_console_item = 0;
1899 GtkWidget* g_toggle_entity_item = 0;
1900 GtkWidget* g_toggle_entitylist_item = 0;
1901
1902 GtkMenuItem* create_view_menu( MainFrame::EViewStyle style ){
1903         // View menu
1904         GtkMenuItem* view_menu_item = new_sub_menu_item_with_mnemonic( "Vie_w" );
1905         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( view_menu_item ) );
1906         if ( g_Layout_enableDetachableMenus.m_value ) {
1907                 menu_tearoff( menu );
1908         }
1909
1910         if ( style == MainFrame::eFloating ) {
1911                 fill_view_camera_menu( menu );
1912                 fill_view_xy_top_menu( menu );
1913                 fill_view_yz_side_menu( menu );
1914                 fill_view_xz_front_menu( menu );
1915         }
1916         if ( style == MainFrame::eFloating || style == MainFrame::eSplit ) {
1917                 create_menu_item_with_mnemonic( menu, "Console View", "ToggleConsole" );
1918                 create_menu_item_with_mnemonic( menu, "Texture Browser", "ToggleTextures" );
1919                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ToggleEntityInspector" );
1920         }
1921         else
1922         {
1923                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ViewEntityInfo" );
1924         }
1925         create_menu_item_with_mnemonic( menu, "_Surface Inspector", "SurfaceInspector" );
1926         create_menu_item_with_mnemonic( menu, "_Patch Inspector", "PatchInspector" );
1927         create_menu_item_with_mnemonic( menu, "Entity List", "EntityList" );
1928
1929         menu_separator( menu );
1930         {
1931                 GtkMenu* camera_menu = create_sub_menu_with_mnemonic( menu, "Camera" );
1932                 if ( g_Layout_enableDetachableMenus.m_value ) {
1933                         menu_tearoff( camera_menu );
1934                 }
1935                 create_menu_item_with_mnemonic( camera_menu, "_Center", "CenterView" );
1936                 create_menu_item_with_mnemonic( camera_menu, "_Up Floor", "UpFloor" );
1937                 create_menu_item_with_mnemonic( camera_menu, "_Down Floor", "DownFloor" );
1938                 menu_separator( camera_menu );
1939                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane In", "CubicClipZoomIn" );
1940                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane Out", "CubicClipZoomOut" );
1941                 menu_separator( camera_menu );
1942                 create_menu_item_with_mnemonic( camera_menu, "Next leak spot", "NextLeakSpot" );
1943                 create_menu_item_with_mnemonic( camera_menu, "Previous leak spot", "PrevLeakSpot" );
1944                 menu_separator( camera_menu );
1945                 create_menu_item_with_mnemonic( camera_menu, "Look Through Selected", "LookThroughSelected" );
1946                 create_menu_item_with_mnemonic( camera_menu, "Look Through Camera", "LookThroughCamera" );
1947         }
1948         menu_separator( menu );
1949         {
1950                 GtkMenu* orthographic_menu = create_sub_menu_with_mnemonic( menu, "Orthographic" );
1951                 if ( g_Layout_enableDetachableMenus.m_value ) {
1952                         menu_tearoff( orthographic_menu );
1953                 }
1954                 if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
1955                         create_menu_item_with_mnemonic( orthographic_menu, "_Next (XY, YZ, XY)", "NextView" );
1956                         create_menu_item_with_mnemonic( orthographic_menu, "XY (Top)", "ViewTop" );
1957                         create_menu_item_with_mnemonic( orthographic_menu, "YZ", "ViewSide" );
1958                         create_menu_item_with_mnemonic( orthographic_menu, "XZ", "ViewFront" );
1959                         menu_separator( orthographic_menu );
1960                 }
1961
1962                 create_menu_item_with_mnemonic( orthographic_menu, "Center on Selected", "CenterXYView" );
1963                 menu_separator( orthographic_menu );
1964                 create_menu_item_with_mnemonic( orthographic_menu, "_XY 100%", "Zoom100" );
1965                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _In", "ZoomIn" );
1966                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _Out", "ZoomOut" );
1967         }
1968
1969         menu_separator( menu );
1970
1971         {
1972                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Show" );
1973                 if ( g_Layout_enableDetachableMenus.m_value ) {
1974                         menu_tearoff( menu_in_menu );
1975                 }
1976                 create_menu_item_with_mnemonic( menu_in_menu, "Show Size Info", "ToggleSizePaint" );
1977                 create_menu_item_with_mnemonic( menu_in_menu, "Show Crosshair", "ToggleCrosshairs" );
1978                 create_menu_item_with_mnemonic( menu_in_menu, "Show Grid", "ToggleGrid" );
1979
1980                 menu_separator( menu_in_menu );
1981
1982                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Angles", "ShowAngles" );
1983                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Names", "ShowNames" );
1984                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Blocks", "ShowBlocks" );
1985                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show C_oordinates", "ShowCoordinates" );
1986                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Window Outline", "ShowWindowOutline" );
1987                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Axes", "ShowAxes" );
1988                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Workzone", "ShowWorkzone" );
1989                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Stats", "ShowStats" );
1990         }
1991
1992         {
1993                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Filter" );
1994                 if ( g_Layout_enableDetachableMenus.m_value ) {
1995                         menu_tearoff( menu_in_menu );
1996                 }
1997                 Filters_constructMenu( menu_in_menu );
1998         }
1999         menu_separator( menu );
2000         {
2001 //              GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Hide/Show" );
2002 //              if ( g_Layout_enableDetachableMenus.m_value ) {
2003 //                      menu_tearoff( menu_in_menu );
2004 //              }
2005 //              create_menu_item_with_mnemonic( menu_in_menu, "Hide Selected", "HideSelected" );
2006 //              create_menu_item_with_mnemonic( menu_in_menu, "Show Hidden", "ShowHidden" );
2007                 create_menu_item_with_mnemonic( menu, "Hide Selected", "HideSelected" );
2008                 create_menu_item_with_mnemonic( 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( "IncPatchColumn" );
2225         command_connect_accelerator( "IncPatchRow" );
2226         command_connect_accelerator( "DecPatchColumn" );
2227         command_connect_accelerator( "DecPatchRow" );
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.bmp", "OpenMap" );
2291         toolbar_append_button( toolbar, "Save the active map (CTRL + S)", "file_save.bmp", "SaveMap" );
2292 }
2293
2294 void UndoRedo_constructToolbar( GtkToolbar* toolbar ){
2295         toolbar_append_button( toolbar, "Undo (CTRL + Z)", "undo.bmp", "Undo" );
2296         toolbar_append_button( toolbar, "Redo (CTRL + Y)", "redo.bmp", "Redo" );
2297 }
2298
2299 void RotateFlip_constructToolbar( GtkToolbar* toolbar ){
2300         toolbar_append_button( toolbar, "x-axis Flip", "brush_flipx.bmp", "MirrorSelectionX" );
2301         toolbar_append_button( toolbar, "x-axis Rotate", "brush_rotatex.bmp", "RotateSelectionX" );
2302         toolbar_append_button( toolbar, "y-axis Flip", "brush_flipy.bmp", "MirrorSelectionY" );
2303         toolbar_append_button( toolbar, "y-axis Rotate", "brush_rotatey.bmp", "RotateSelectionY" );
2304         toolbar_append_button( toolbar, "z-axis Flip", "brush_flipz.bmp", "MirrorSelectionZ" );
2305         toolbar_append_button( toolbar, "z-axis Rotate", "brush_rotatez.bmp", "RotateSelectionZ" );
2306 }
2307
2308 void Select_constructToolbar( GtkToolbar* toolbar ){
2309         toolbar_append_button( toolbar, "Select touching", "selection_selecttouching.bmp", "SelectTouching" );
2310         toolbar_append_button( toolbar, "Select inside", "selection_selectinside.bmp", "SelectInside" );
2311 }
2312
2313 void CSG_constructToolbar( GtkToolbar* toolbar ){
2314         toolbar_append_button( toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.bmp", "CSGSubtract" );
2315         toolbar_append_button( toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.bmp", "CSGMerge" );
2316         toolbar_append_button( toolbar, "Hollow", "selection_makehollow.bmp", "CSGHollow" );
2317 }
2318
2319 void ComponentModes_constructToolbar( GtkToolbar* toolbar ){
2320         toolbar_append_toggle_button( toolbar, "Select Vertices (V)", "modify_vertices.bmp", "DragVertices" );
2321         toolbar_append_toggle_button( toolbar, "Select Edges (E)", "modify_edges.bmp", "DragEdges" );
2322         toolbar_append_toggle_button( toolbar, "Select Faces (F)", "modify_faces.bmp", "DragFaces" );
2323 }
2324
2325 void Clipper_constructToolbar( GtkToolbar* toolbar ){
2326
2327         toolbar_append_toggle_button( toolbar, "Clipper (X)", "view_clipper.bmp", "ToggleClipper" );
2328 }
2329
2330 void XYWnd_constructToolbar( GtkToolbar* toolbar ){
2331         toolbar_append_button( toolbar, "Change views", "view_change.bmp", "NextView" );
2332 }
2333
2334 void Manipulators_constructToolbar( GtkToolbar* toolbar ){
2335         toolbar_append_toggle_button( toolbar, "Translate (W)", "select_mousetranslate.bmp", "MouseTranslate" );
2336         toolbar_append_toggle_button( toolbar, "Rotate (R)", "select_mouserotate.bmp", "MouseRotate" );
2337         toolbar_append_toggle_button( toolbar, "Scale", "select_mousescale.bmp", "MouseScale" );
2338         toolbar_append_toggle_button( toolbar, "Resize (Q)", "select_mouseresize.bmp", "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.bmp", "TogTexLock" );
2395
2396         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2397
2398         GtkButton* g_view_entities_button = toolbar_append_button( toolbar, "Entities (N)", "entities.bmp", "ToggleEntityInspector" );
2399         GtkButton* g_view_console_button = toolbar_append_button( toolbar, "Console (O)", "console.bmp", "ToggleConsole" );
2400         GtkButton* g_view_textures_button = toolbar_append_button( toolbar, "Texture Browser (T)", "texture_browser.bmp", "ToggleTextures" );
2401         // TODO: call light inspector
2402         //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.bmp", "ToggleLightInspector");
2403
2404         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2405         GtkButton* g_refresh_models_button = toolbar_append_button( toolbar, "Refresh Models", "refresh_models.bmp", "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.bmp" );
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.bmp" );
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
2784         if ( g_Layout_enableFilterToolbar.m_value ) {
2785                 gtk_toolbar_append_space( GTK_TOOLBAR( plugin_toolbar ) );
2786                 gtk_toolbar_append_space( GTK_TOOLBAR( plugin_toolbar ) );
2787                 toolbar_append_toggle_button( plugin_toolbar, "World (ALT + 1)", "f-world.bmp", "FilterWorldBrushes" );
2788                 toolbar_append_toggle_button( plugin_toolbar, "Details (CTRL + D)", "f-details.bmp", "FilterDetails" );
2789                 toolbar_append_toggle_button( plugin_toolbar, "Structural (CTRL + SHIFT + D)", "f-structural.bmp", "FilterStructural" );
2790                 toolbar_append_toggle_button( plugin_toolbar, "Patches (CTRL + P)", "patch_wireframe.bmp", "FilterPatches" );
2791                 gtk_toolbar_append_space( GTK_TOOLBAR( plugin_toolbar ) );
2792                 toolbar_append_toggle_button( plugin_toolbar, "Areaportals (ALT + 3)", "f-areaportal.bmp", "FilterAreaportals" );
2793                 toolbar_append_toggle_button( plugin_toolbar, "Translucent (ALT + 4)", "f-translucent.bmp", "FilterTranslucent" );
2794                 toolbar_append_toggle_button( plugin_toolbar, "Liquids (ALT + 5)", "f-liquids.bmp", "FilterLiquids" );
2795                 toolbar_append_toggle_button( plugin_toolbar, "Caulk (ALT + 6)", "f-caulk.bmp", "FilterCaulk" );
2796                 toolbar_append_toggle_button( plugin_toolbar, "Clips (ALT + 7)", "f-clip.bmp", "FilterClips" );
2797                 toolbar_append_toggle_button( plugin_toolbar, "HintsSkips (CTRL + H)", "f-hint.bmp", "FilterHintsSkips" );
2798                 //toolbar_append_toggle_button( plugin_toolbar, "Paths (ALT + 8)", "texture_lock.bmp", "FilterPaths" );
2799                 gtk_toolbar_append_space( GTK_TOOLBAR( plugin_toolbar ) );
2800                 toolbar_append_toggle_button( plugin_toolbar, "Entities (ALT + 2)", "f-entities.bmp", "FilterEntities" );
2801                 toolbar_append_toggle_button( plugin_toolbar, "Lights (ALT + 0)", "lightinspector.bmp", "FilterLights" );
2802                 toolbar_append_toggle_button( plugin_toolbar, "Models (SHIFT + M)", "f-models.bmp", "FilterModels" );
2803                 toolbar_append_toggle_button( plugin_toolbar, "Triggers (CTRL + SHIFT + T)", "f-triggers.bmp", "FilterTriggers" );
2804                 toolbar_append_toggle_button( plugin_toolbar, "Decals (SHIFT + D)", "f-decals.bmp", "FilterDecals" );
2805                 gtk_toolbar_append_space( GTK_TOOLBAR( plugin_toolbar ) );
2806                 toolbar_append_button( plugin_toolbar, "InvertFilters", "f-invert.bmp", "InvertFilters" );
2807                 toolbar_append_button( plugin_toolbar, "ResetFilters", "f-reset.bmp", "ResetFilters" );
2808         }
2809         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( plugin_toolbar ), FALSE, FALSE, 0 );
2810
2811         GtkWidget* main_statusbar = create_main_statusbar( m_pStatusLabel );
2812         gtk_box_pack_end( GTK_BOX( vbox ), main_statusbar, FALSE, TRUE, 2 );
2813
2814         GroupDialog_constructWindow( window );
2815         g_page_entity = GroupDialog_addPage( "Entities", EntityInspector_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Entities" ) );
2816
2817         if ( FloatingGroupDialog() ) {
2818                 g_page_console = GroupDialog_addPage( "Console", Console_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Console" ) );
2819         }
2820
2821 #ifdef WIN32
2822         if ( g_multimon_globals.m_bStartOnPrimMon ) {
2823                 PositionWindowOnPrimaryScreen( g_layout_globals.m_position );
2824                 window_set_position( window, g_layout_globals.m_position );
2825         }
2826         else
2827 #endif
2828         if ( g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED ) {
2829                 gtk_window_maximize( window );
2830                 WindowPosition default_position( -1, -1, 640, 480 );
2831                 window_set_position( window, default_position );
2832         }
2833         else
2834         {
2835                 window_set_position( window, g_layout_globals.m_position );
2836         }
2837
2838         m_window = window;
2839
2840         gtk_widget_show( GTK_WIDGET( window ) );
2841
2842         if ( CurrentStyle() == eRegular || CurrentStyle() == eRegularLeft ) {
2843                 {
2844                         GtkWidget* vsplit = gtk_vpaned_new();
2845                         m_vSplit = vsplit;
2846                         gtk_box_pack_start( GTK_BOX( vbox ), vsplit, TRUE, TRUE, 0 );
2847                         gtk_widget_show( vsplit );
2848
2849                         // console
2850                         GtkWidget* console_window = Console_constructWindow( window );
2851                         gtk_paned_pack2( GTK_PANED( vsplit ), console_window, FALSE, TRUE );
2852
2853                         {
2854                                 GtkWidget* hsplit = gtk_hpaned_new();
2855                                 gtk_widget_show( hsplit );
2856                                 m_hSplit = hsplit;
2857                                 gtk_paned_add1( GTK_PANED( vsplit ), hsplit );
2858
2859                                 // xy
2860                                 m_pXYWnd = new XYWnd();
2861                                 m_pXYWnd->SetViewType( XY );
2862                                 GtkWidget* xy_window = GTK_WIDGET( create_framed_widget( m_pXYWnd->GetWidget() ) );
2863
2864                                 {
2865                                         GtkWidget* vsplit2 = gtk_vpaned_new();
2866                                         gtk_widget_show( vsplit2 );
2867                                         m_vSplit2 = vsplit2;
2868
2869                                         if ( CurrentStyle() == eRegular ) {
2870                                                 gtk_paned_add1( GTK_PANED( hsplit ), xy_window );
2871                                                 gtk_paned_add2( GTK_PANED( hsplit ), vsplit2 );
2872                                         }
2873                                         else
2874                                         {
2875                                                 gtk_paned_add1( GTK_PANED( hsplit ), vsplit2 );
2876                                                 gtk_paned_add2( GTK_PANED( hsplit ), xy_window );
2877                                         }
2878
2879
2880                                         // camera
2881                                         m_pCamWnd = NewCamWnd();
2882                                         GlobalCamera_setCamWnd( *m_pCamWnd );
2883                                         CamWnd_setParent( *m_pCamWnd, window );
2884                                         GtkFrame* camera_window = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
2885
2886                                         gtk_paned_add1( GTK_PANED( vsplit2 ), GTK_WIDGET( camera_window ) );
2887
2888                                         // textures
2889                                         GtkFrame* texture_window = create_framed_widget( TextureBrowser_constructWindow( window ) );
2890
2891                                         gtk_paned_add2( GTK_PANED( vsplit2 ), GTK_WIDGET( texture_window ) );
2892                                 }
2893                         }
2894                 }
2895
2896                 gtk_paned_set_position( GTK_PANED( m_vSplit ), g_layout_globals.nXYHeight );
2897
2898                 if ( CurrentStyle() == eRegular ) {
2899                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nXYWidth );
2900                 }
2901                 else
2902                 {
2903                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nCamWidth );
2904                 }
2905
2906                 gtk_paned_set_position( GTK_PANED( m_vSplit2 ), g_layout_globals.nCamHeight );
2907         }
2908         else if ( CurrentStyle() == eFloating ) {
2909                 {
2910                         GtkWindow* window = create_persistent_floating_window( "Camera", m_window );
2911                         global_accel_connect_window( window );
2912                         g_posCamWnd.connect( window );
2913
2914                         gtk_widget_show( GTK_WIDGET( window ) );
2915
2916                         m_pCamWnd = NewCamWnd();
2917                         GlobalCamera_setCamWnd( *m_pCamWnd );
2918
2919                         {
2920                                 GtkFrame* frame = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
2921                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2922                         }
2923                         CamWnd_setParent( *m_pCamWnd, window );
2924
2925                         g_floating_windows.push_back( GTK_WIDGET( window ) );
2926                 }
2927
2928                 {
2929                         GtkWindow* window = create_persistent_floating_window( ViewType_getTitle( XY ), m_window );
2930                         global_accel_connect_window( window );
2931                         g_posXYWnd.connect( window );
2932
2933                         m_pXYWnd = new XYWnd();
2934                         m_pXYWnd->m_parent = window;
2935                         m_pXYWnd->SetViewType( XY );
2936
2937
2938                         {
2939                                 GtkFrame* frame = create_framed_widget( m_pXYWnd->GetWidget() );
2940                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2941                         }
2942                         XY_Top_Shown_Construct( window );
2943
2944                         g_floating_windows.push_back( GTK_WIDGET( window ) );
2945                 }
2946
2947                 {
2948                         GtkWindow* window = create_persistent_floating_window( ViewType_getTitle( XZ ), m_window );
2949                         global_accel_connect_window( window );
2950                         g_posXZWnd.connect( window );
2951
2952                         m_pXZWnd = new XYWnd();
2953                         m_pXZWnd->m_parent = window;
2954                         m_pXZWnd->SetViewType( XZ );
2955
2956                         {
2957                                 GtkFrame* frame = create_framed_widget( m_pXZWnd->GetWidget() );
2958                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2959                         }
2960
2961                         XZ_Front_Shown_Construct( window );
2962
2963                         g_floating_windows.push_back( GTK_WIDGET( window ) );
2964                 }
2965
2966                 {
2967                         GtkWindow* window = create_persistent_floating_window( ViewType_getTitle( YZ ), m_window );
2968                         global_accel_connect_window( window );
2969                         g_posYZWnd.connect( window );
2970
2971                         m_pYZWnd = new XYWnd();
2972                         m_pYZWnd->m_parent = window;
2973                         m_pYZWnd->SetViewType( YZ );
2974
2975                         {
2976                                 GtkFrame* frame = create_framed_widget( m_pYZWnd->GetWidget() );
2977                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2978                         }
2979
2980                         YZ_Side_Shown_Construct( window );
2981
2982                         g_floating_windows.push_back( GTK_WIDGET( window ) );
2983                 }
2984
2985                 {
2986                         GtkFrame* frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
2987                         g_page_textures = GroupDialog_addPage( "Textures", GTK_WIDGET( frame ), TextureBrowserExportTitleCaller() );
2988                 }
2989
2990                 GroupDialog_show();
2991         }
2992         else // 4 way
2993         {
2994                 m_pCamWnd = NewCamWnd();
2995                 GlobalCamera_setCamWnd( *m_pCamWnd );
2996                 CamWnd_setParent( *m_pCamWnd, window );
2997
2998                 GtkWidget* camera = CamWnd_getWidget( *m_pCamWnd );
2999
3000                 m_pYZWnd = new XYWnd();
3001                 m_pYZWnd->SetViewType( YZ );
3002
3003                 GtkWidget* yz = m_pYZWnd->GetWidget();
3004
3005                 m_pXYWnd = new XYWnd();
3006                 m_pXYWnd->SetViewType( XY );
3007
3008                 GtkWidget* xy = m_pXYWnd->GetWidget();
3009
3010                 m_pXZWnd = new XYWnd();
3011                 m_pXZWnd->SetViewType( XZ );
3012
3013                 GtkWidget* xz = m_pXZWnd->GetWidget();
3014
3015                 GtkHPaned* split = create_split_views( camera, yz, xy, xz );
3016                 gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( split ), TRUE, TRUE, 0 );
3017
3018                 {
3019                         GtkFrame* frame = create_framed_widget( TextureBrowser_constructWindow( window ) );
3020                         g_page_textures = GroupDialog_addPage( "Textures", GTK_WIDGET( frame ), TextureBrowserExportTitleCaller() );
3021                 }
3022         }
3023
3024         EntityList_constructWindow( window );
3025         PreferencesDialog_constructWindow( window );
3026         FindTextureDialog_constructWindow( window );
3027         SurfaceInspector_constructWindow( window );
3028         PatchInspector_constructWindow( window );
3029
3030         SetActiveXY( m_pXYWnd );
3031
3032         AddGridChangeCallback( SetGridStatusCaller( *this ) );
3033         AddGridChangeCallback( ReferenceCaller<MainFrame, XY_UpdateAllWindows>( *this ) );
3034
3035         g_defaultToolMode = DragMode;
3036         g_defaultToolMode();
3037         SetStatusText( m_command_status, c_TranslateMode_status );
3038
3039         EverySecondTimer_enable();
3040
3041         //GlobalShortcuts_reportUnregistered();
3042 }
3043
3044 void MainFrame::SaveWindowInfo(){
3045         if ( !FloatingGroupDialog() ) {
3046                 g_layout_globals.nXYHeight = gtk_paned_get_position( GTK_PANED( m_vSplit ) );
3047
3048                 if ( CurrentStyle() != eRegular ) {
3049                         g_layout_globals.nCamWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
3050                 }
3051                 else
3052                 {
3053                         g_layout_globals.nXYWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
3054                 }
3055
3056                 g_layout_globals.nCamHeight = gtk_paned_get_position( GTK_PANED( m_vSplit2 ) );
3057         }
3058
3059         g_layout_globals.m_position = m_position_tracker.getPosition();
3060
3061         g_layout_globals.nState = gdk_window_get_state( GTK_WIDGET( m_window )->window );
3062 }
3063
3064 void MainFrame::Shutdown(){
3065         EverySecondTimer_disable();
3066
3067         EntityList_destroyWindow();
3068
3069         delete m_pXYWnd;
3070         m_pXYWnd = 0;
3071         delete m_pYZWnd;
3072         m_pYZWnd = 0;
3073         delete m_pXZWnd;
3074         m_pXZWnd = 0;
3075
3076         TextureBrowser_destroyWindow();
3077
3078         DeleteCamWnd( m_pCamWnd );
3079         m_pCamWnd = 0;
3080
3081         PreferencesDialog_destroyWindow();
3082         SurfaceInspector_destroyWindow();
3083         FindTextureDialog_destroyWindow();
3084         PatchInspector_destroyWindow();
3085
3086         g_DbgDlg.destroyWindow();
3087
3088         // destroying group-dialog last because it may contain texture-browser
3089         GroupDialog_destroyWindow();
3090 }
3091
3092 void MainFrame::RedrawStatusText(){
3093         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_command_status] ), m_command_status.c_str() );
3094         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_position_status] ), m_position_status.c_str() );
3095         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_brushcount_status] ), m_brushcount_status.c_str() );
3096         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_texture_status] ), m_texture_status.c_str() );
3097         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_grid_status] ), m_grid_status.c_str() );
3098 }
3099
3100 void MainFrame::UpdateStatusText(){
3101         m_idleRedrawStatusText.queueDraw();
3102 }
3103
3104 void MainFrame::SetStatusText( CopiedString& status_text, const char* pText ){
3105         status_text = pText;
3106         UpdateStatusText();
3107 }
3108
3109 void Sys_Status( const char* status ){
3110         if ( g_pParentWnd != 0 ) {
3111                 g_pParentWnd->SetStatusText( g_pParentWnd->m_command_status, status );
3112         }
3113 }
3114
3115 int getRotateIncrement(){
3116         return static_cast<int>( g_si_globals.rotate );
3117 }
3118
3119 int getFarClipDistance(){
3120         return g_camwindow_globals.m_nCubicScale;
3121 }
3122
3123 float ( *GridStatus_getGridSize )() = GetGridSize;
3124 int ( *GridStatus_getRotateIncrement )() = getRotateIncrement;
3125 int ( *GridStatus_getFarClipDistance )() = getFarClipDistance;
3126 bool ( *GridStatus_getTextureLockEnabled )();
3127
3128 void MainFrame::SetGridStatus(){
3129         StringOutputStream status( 64 );
3130         const char* lock = ( GridStatus_getTextureLockEnabled() ) ? "ON" : "OFF";
3131         status << ( GetSnapGridSize() > 0 ? "G:" : "g:" ) << GridStatus_getGridSize()
3132                    << "  R:" << GridStatus_getRotateIncrement()
3133                    << "  C:" << GridStatus_getFarClipDistance()
3134                    << "  L:" << lock;
3135         SetStatusText( m_grid_status, status.c_str() );
3136 }
3137
3138 void GridStatus_onTextureLockEnabledChanged(){
3139         if ( g_pParentWnd != 0 ) {
3140                 g_pParentWnd->SetGridStatus();
3141         }
3142 }
3143
3144 void GlobalGL_sharedContextCreated(){
3145         GLFont *g_font = NULL;
3146
3147         // report OpenGL information
3148         globalOutputStream() << "GL_VENDOR: " << reinterpret_cast<const char*>( glGetString( GL_VENDOR ) ) << "\n";
3149         globalOutputStream() << "GL_RENDERER: " << reinterpret_cast<const char*>( glGetString( GL_RENDERER ) ) << "\n";
3150         globalOutputStream() << "GL_VERSION: " << reinterpret_cast<const char*>( glGetString( GL_VERSION ) ) << "\n";
3151         globalOutputStream() << "GL_EXTENSIONS: " << reinterpret_cast<const char*>( glGetString( GL_EXTENSIONS ) ) << "\n";
3152
3153         QGL_sharedContextCreated( GlobalOpenGL() );
3154
3155         ShaderCache_extensionsInitialised();
3156
3157         GlobalShaderCache().realise();
3158         Textures_Realise();
3159
3160 #ifdef WIN32
3161         /* win32 is dodgy here, just use courier new then */
3162         g_font = glfont_create( "arial 9" );
3163 #else
3164         GtkSettings *settings = gtk_settings_get_default();
3165         gchar *fontname;
3166         g_object_get( settings, "gtk-font-name", &fontname, NULL );
3167         g_font = glfont_create( fontname );
3168 #endif
3169
3170         GlobalOpenGL().m_font = g_font;
3171 }
3172
3173 void GlobalGL_sharedContextDestroyed(){
3174         Textures_Unrealise();
3175         GlobalShaderCache().unrealise();
3176
3177         QGL_sharedContextDestroyed( GlobalOpenGL() );
3178 }
3179
3180
3181 void Layout_constructPreferences( PreferencesPage& page ){
3182         {
3183                 const char* layouts[] = { "window1.bmp", "window2.bmp", "window3.bmp", "window4.bmp" };
3184                 page.appendRadioIcons(
3185                         "Window Layout",
3186                         STRING_ARRAY_RANGE( layouts ),
3187                         LatchedIntImportCaller( g_Layout_viewStyle ),
3188                         IntExportCaller( g_Layout_viewStyle.m_latched )
3189                         );
3190         }
3191         page.appendCheckBox(
3192                 "", "Detachable Menus",
3193                 LatchedBoolImportCaller( g_Layout_enableDetachableMenus ),
3194                 BoolExportCaller( g_Layout_enableDetachableMenus.m_latched )
3195                 );
3196         if ( !string_empty( g_pGameDescription->getKeyValue( "no_patch" ) ) ) {
3197                 page.appendCheckBox(
3198                         "", "Patch Toolbar",
3199                         LatchedBoolImportCaller( g_Layout_enablePatchToolbar ),
3200                         BoolExportCaller( g_Layout_enablePatchToolbar.m_latched )
3201                         );
3202         }
3203         page.appendCheckBox(
3204                 "", "Plugin Toolbar",
3205                 LatchedBoolImportCaller( g_Layout_enablePluginToolbar ),
3206                 BoolExportCaller( g_Layout_enablePluginToolbar.m_latched )
3207                 );
3208         page.appendCheckBox(
3209                 "", "Filter Toolbar",
3210                 LatchedBoolImportCaller( g_Layout_enableFilterToolbar ),
3211                 BoolExportCaller( g_Layout_enableFilterToolbar.m_latched )
3212                 );
3213 }
3214
3215 void Layout_constructPage( PreferenceGroup& group ){
3216         PreferencesPage page( group.createPage( "Layout", "Layout Preferences" ) );
3217         Layout_constructPreferences( page );
3218 }
3219
3220 void Layout_registerPreferencesPage(){
3221         PreferencesDialog_addInterfacePage( FreeCaller1<PreferenceGroup&, Layout_constructPage>() );
3222 }
3223
3224
3225 #include "preferencesystem.h"
3226 #include "stringio.h"
3227
3228 void MainFrame_Construct(){
3229         GlobalCommands_insert( "OpenManual", FreeCaller<OpenHelpURL>(), Accelerator( GDK_F1 ) );
3230
3231         GlobalCommands_insert( "Sleep", FreeCaller<thunk_OnSleep>(), Accelerator( 'P', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
3232         GlobalCommands_insert( "NewMap", FreeCaller<NewMap>() );
3233         GlobalCommands_insert( "OpenMap", FreeCaller<OpenMap>(), Accelerator( 'O', (GdkModifierType)GDK_CONTROL_MASK ) );
3234         GlobalCommands_insert( "ImportMap", FreeCaller<ImportMap>() );
3235         GlobalCommands_insert( "SaveMap", FreeCaller<SaveMap>(), Accelerator( 'S', (GdkModifierType)GDK_CONTROL_MASK ) );
3236         GlobalCommands_insert( "SaveMapAs", FreeCaller<SaveMapAs>() );
3237         GlobalCommands_insert( "SaveSelected", FreeCaller<ExportMap>() );
3238         GlobalCommands_insert( "SaveRegion", FreeCaller<SaveRegion>() );
3239         GlobalCommands_insert( "RefreshReferences", FreeCaller<RefreshReferences>() );
3240         GlobalCommands_insert( "ProjectSettings", FreeCaller<DoProjectSettings>() );
3241         GlobalCommands_insert( "CheckForUpdate", FreeCaller<OpenUpdateURL>() );
3242         GlobalCommands_insert( "Exit", FreeCaller<Exit>() );
3243
3244         GlobalCommands_insert( "Undo", FreeCaller<Undo>(), Accelerator( 'Z', (GdkModifierType)GDK_CONTROL_MASK ) );
3245         GlobalCommands_insert( "Redo", FreeCaller<Redo>(), Accelerator( 'Y', (GdkModifierType)GDK_CONTROL_MASK ) );
3246         GlobalCommands_insert( "Copy", FreeCaller<Copy>(), Accelerator( 'C', (GdkModifierType)GDK_CONTROL_MASK ) );
3247         GlobalCommands_insert( "Paste", FreeCaller<Paste>(), Accelerator( 'V', (GdkModifierType)GDK_CONTROL_MASK ) );
3248         GlobalCommands_insert( "PasteToCamera", FreeCaller<PasteToCamera>(), Accelerator( 'V', (GdkModifierType)GDK_SHIFT_MASK ) );
3249         GlobalCommands_insert( "CloneSelection", FreeCaller<Selection_Clone>(), Accelerator( GDK_space ) );
3250         GlobalCommands_insert( "CloneSelectionAndMakeUnique", FreeCaller<Selection_Clone_MakeUnique>(), Accelerator( GDK_space, (GdkModifierType)GDK_SHIFT_MASK ) );
3251 //      GlobalCommands_insert( "DeleteSelection", FreeCaller<deleteSelection>(), Accelerator( GDK_BackSpace ) );
3252         GlobalCommands_insert( "DeleteSelection", FreeCaller<deleteSelection>(), Accelerator( 'Z' ) );
3253         GlobalCommands_insert( "ParentSelection", FreeCaller<Scene_parentSelected>() );
3254 //      GlobalCommands_insert( "UnSelectSelection", FreeCaller<Selection_Deselect>(), Accelerator( GDK_Escape ) );
3255         GlobalCommands_insert( "UnSelectSelection", FreeCaller<Selection_Deselect>(), Accelerator( 'C' ) );
3256         GlobalCommands_insert( "InvertSelection", FreeCaller<Select_Invert>(), Accelerator( 'I' ) );
3257         GlobalCommands_insert( "SelectInside", FreeCaller<Select_Inside>() );
3258         GlobalCommands_insert( "SelectTouching", FreeCaller<Select_Touching>() );
3259         GlobalCommands_insert( "ExpandSelectionToEntities", FreeCaller<Scene_ExpandSelectionToEntities>(), Accelerator( 'E', (GdkModifierType)GDK_SHIFT_MASK ) );
3260         GlobalCommands_insert( "Preferences", FreeCaller<PreferencesDialog_showDialog>(), Accelerator( 'P' ) );
3261
3262         GlobalCommands_insert( "ToggleConsole", FreeCaller<Console_ToggleShow>(), Accelerator( 'O' ) );
3263         GlobalCommands_insert( "ToggleEntityInspector", FreeCaller<EntityInspector_ToggleShow>(), Accelerator( 'N' ) );
3264         GlobalCommands_insert( "EntityList", FreeCaller<EntityList_toggleShown>(), Accelerator( 'L' ) );
3265
3266         GlobalCommands_insert( "ShowHidden", FreeCaller<Select_ShowAllHidden>(), Accelerator( 'H', (GdkModifierType)GDK_SHIFT_MASK ) );
3267         GlobalCommands_insert( "HideSelected", FreeCaller<HideSelected>(), Accelerator( 'H' ) );
3268
3269         GlobalToggles_insert( "DragVertices", FreeCaller<SelectVertexMode>(), ToggleItem::AddCallbackCaller( g_vertexMode_button ), Accelerator( 'V' ) );
3270         GlobalToggles_insert( "DragEdges", FreeCaller<SelectEdgeMode>(), ToggleItem::AddCallbackCaller( g_edgeMode_button ), Accelerator( 'E' ) );
3271         GlobalToggles_insert( "DragFaces", FreeCaller<SelectFaceMode>(), ToggleItem::AddCallbackCaller( g_faceMode_button ), Accelerator( 'F' ) );
3272
3273         GlobalCommands_insert( "MirrorSelectionX", FreeCaller<Selection_Flipx>() );
3274         GlobalCommands_insert( "RotateSelectionX", FreeCaller<Selection_Rotatex>() );
3275         GlobalCommands_insert( "MirrorSelectionY", FreeCaller<Selection_Flipy>() );
3276         GlobalCommands_insert( "RotateSelectionY", FreeCaller<Selection_Rotatey>() );
3277         GlobalCommands_insert( "MirrorSelectionZ", FreeCaller<Selection_Flipz>() );
3278         GlobalCommands_insert( "RotateSelectionZ", FreeCaller<Selection_Rotatez>() );
3279
3280         GlobalCommands_insert( "ArbitraryRotation", FreeCaller<DoRotateDlg>(), Accelerator( 'R', (GdkModifierType)GDK_SHIFT_MASK ) );
3281         GlobalCommands_insert( "ArbitraryScale", FreeCaller<DoScaleDlg>(), Accelerator( 'S', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
3282
3283         GlobalCommands_insert( "BuildMenuCustomize", FreeCaller<DoBuildMenu>() );
3284
3285         GlobalCommands_insert( "FindBrush", FreeCaller<DoFind>() );
3286
3287         GlobalCommands_insert( "MapInfo", FreeCaller<DoMapInfo>(), Accelerator( 'M' ) );
3288
3289
3290         GlobalToggles_insert( "ToggleClipper", FreeCaller<ClipperMode>(), ToggleItem::AddCallbackCaller( g_clipper_button ), Accelerator( 'X' ) );
3291
3292         GlobalToggles_insert( "MouseTranslate", FreeCaller<TranslateMode>(), ToggleItem::AddCallbackCaller( g_translatemode_button ), Accelerator( 'W' ) );
3293         GlobalToggles_insert( "MouseRotate", FreeCaller<RotateMode>(), ToggleItem::AddCallbackCaller( g_rotatemode_button ), Accelerator( 'R' ) );
3294         GlobalToggles_insert( "MouseScale", FreeCaller<ScaleMode>(), ToggleItem::AddCallbackCaller( g_scalemode_button ) );
3295         GlobalToggles_insert( "MouseDrag", FreeCaller<DragMode>(), ToggleItem::AddCallbackCaller( g_dragmode_button ), Accelerator( 'Q' ) );
3296
3297         GlobalCommands_insert( "ColorSchemeOriginal", FreeCaller<ColorScheme_Original>() );
3298         GlobalCommands_insert( "ColorSchemeQER", FreeCaller<ColorScheme_QER>() );
3299         GlobalCommands_insert( "ColorSchemeBlackAndGreen", FreeCaller<ColorScheme_Black>() );
3300         GlobalCommands_insert( "ColorSchemeYdnar", FreeCaller<ColorScheme_Ydnar>() );
3301         GlobalCommands_insert( "ChooseTextureBackgroundColor", makeCallback( g_ColoursMenu.m_textureback ) );
3302         GlobalCommands_insert( "ChooseGridBackgroundColor", makeCallback( g_ColoursMenu.m_xyback ) );
3303         GlobalCommands_insert( "ChooseGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor ) );
3304         GlobalCommands_insert( "ChooseGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor ) );
3305         GlobalCommands_insert( "ChooseSmallGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor_alt ) );
3306         GlobalCommands_insert( "ChooseSmallGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor_alt ) );
3307         GlobalCommands_insert( "ChooseGridTextColor", makeCallback( g_ColoursMenu.m_gridtext ) );
3308         GlobalCommands_insert( "ChooseGridBlockColor", makeCallback( g_ColoursMenu.m_gridblock ) );
3309         GlobalCommands_insert( "ChooseBrushColor", makeCallback( g_ColoursMenu.m_brush ) );
3310         GlobalCommands_insert( "ChooseCameraBackgroundColor", makeCallback( g_ColoursMenu.m_cameraback ) );
3311         GlobalCommands_insert( "ChooseSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush ) );
3312         GlobalCommands_insert( "ChooseCameraSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush3d ) );
3313         GlobalCommands_insert( "ChooseClipperColor", makeCallback( g_ColoursMenu.m_clipper ) );
3314         GlobalCommands_insert( "ChooseOrthoViewNameColor", makeCallback( g_ColoursMenu.m_viewname ) );
3315
3316
3317         GlobalCommands_insert( "CSGSubtract", FreeCaller<CSG_Subtract>(), Accelerator( 'U', (GdkModifierType)GDK_SHIFT_MASK ) );
3318         GlobalCommands_insert( "CSGMerge", FreeCaller<CSG_Merge>(), Accelerator( 'U', (GdkModifierType)GDK_CONTROL_MASK ) );
3319         GlobalCommands_insert( "CSGHollow", FreeCaller<CSG_MakeHollow>() );
3320
3321         Grid_registerCommands();
3322
3323         GlobalCommands_insert( "SnapToGrid", FreeCaller<Selection_SnapToGrid>(), Accelerator( 'G', (GdkModifierType)GDK_CONTROL_MASK ) );
3324
3325         GlobalCommands_insert( "SelectAllOfType", FreeCaller<Select_AllOfType>(), Accelerator( 'A', (GdkModifierType)GDK_SHIFT_MASK ) );
3326
3327         GlobalCommands_insert( "TexRotateClock", FreeCaller<Texdef_RotateClockwise>(), Accelerator( GDK_Next, (GdkModifierType)GDK_SHIFT_MASK ) );
3328         GlobalCommands_insert( "TexRotateCounter", FreeCaller<Texdef_RotateAntiClockwise>(), Accelerator( GDK_Prior, (GdkModifierType)GDK_SHIFT_MASK ) );
3329         GlobalCommands_insert( "TexScaleUp", FreeCaller<Texdef_ScaleUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_CONTROL_MASK ) );
3330         GlobalCommands_insert( "TexScaleDown", FreeCaller<Texdef_ScaleDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_CONTROL_MASK ) );
3331         GlobalCommands_insert( "TexScaleLeft", FreeCaller<Texdef_ScaleLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_CONTROL_MASK ) );
3332         GlobalCommands_insert( "TexScaleRight", FreeCaller<Texdef_ScaleRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_CONTROL_MASK ) );
3333         GlobalCommands_insert( "TexShiftUp", FreeCaller<Texdef_ShiftUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_SHIFT_MASK ) );
3334         GlobalCommands_insert( "TexShiftDown", FreeCaller<Texdef_ShiftDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_SHIFT_MASK ) );
3335         GlobalCommands_insert( "TexShiftLeft", FreeCaller<Texdef_ShiftLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_SHIFT_MASK ) );
3336         GlobalCommands_insert( "TexShiftRight", FreeCaller<Texdef_ShiftRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_SHIFT_MASK ) );
3337
3338         GlobalCommands_insert( "MoveSelectionDOWN", FreeCaller<Selection_MoveDown>(), Accelerator( GDK_KP_Subtract ) );
3339         GlobalCommands_insert( "MoveSelectionUP", FreeCaller<Selection_MoveUp>(), Accelerator( GDK_KP_Add ) );
3340
3341         GlobalCommands_insert( "SelectNudgeLeft", FreeCaller<Selection_NudgeLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_MOD1_MASK ) );
3342         GlobalCommands_insert( "SelectNudgeRight", FreeCaller<Selection_NudgeRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_MOD1_MASK ) );
3343         GlobalCommands_insert( "SelectNudgeUp", FreeCaller<Selection_NudgeUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_MOD1_MASK ) );
3344         GlobalCommands_insert( "SelectNudgeDown", FreeCaller<Selection_NudgeDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_MOD1_MASK ) );
3345
3346         Patch_registerCommands();
3347         XYShow_registerCommands();
3348
3349         typedef FreeCaller1<const Selectable&, ComponentMode_SelectionChanged> ComponentModeSelectionChangedCaller;
3350         GlobalSelectionSystem().addSelectionChangeCallback( ComponentModeSelectionChangedCaller() );
3351
3352         GlobalPreferenceSystem().registerPreference( "DetachableMenus", BoolImportStringCaller( g_Layout_enableDetachableMenus.m_latched ), BoolExportStringCaller( g_Layout_enableDetachableMenus.m_latched ) );
3353         GlobalPreferenceSystem().registerPreference( "PatchToolBar", BoolImportStringCaller( g_Layout_enablePatchToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePatchToolbar.m_latched ) );
3354         GlobalPreferenceSystem().registerPreference( "PluginToolBar", BoolImportStringCaller( g_Layout_enablePluginToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePluginToolbar.m_latched ) );
3355         GlobalPreferenceSystem().registerPreference( "FilterToolBar", BoolImportStringCaller( g_Layout_enableFilterToolbar.m_latched ), BoolExportStringCaller( g_Layout_enableFilterToolbar.m_latched ) );
3356         GlobalPreferenceSystem().registerPreference( "QE4StyleWindows", IntImportStringCaller( g_Layout_viewStyle.m_latched ), IntExportStringCaller( g_Layout_viewStyle.m_latched ) );
3357         GlobalPreferenceSystem().registerPreference( "XYHeight", IntImportStringCaller( g_layout_globals.nXYHeight ), IntExportStringCaller( g_layout_globals.nXYHeight ) );
3358         GlobalPreferenceSystem().registerPreference( "XYWidth", IntImportStringCaller( g_layout_globals.nXYWidth ), IntExportStringCaller( g_layout_globals.nXYWidth ) );
3359         GlobalPreferenceSystem().registerPreference( "CamWidth", IntImportStringCaller( g_layout_globals.nCamWidth ), IntExportStringCaller( g_layout_globals.nCamWidth ) );
3360         GlobalPreferenceSystem().registerPreference( "CamHeight", IntImportStringCaller( g_layout_globals.nCamHeight ), IntExportStringCaller( g_layout_globals.nCamHeight ) );
3361
3362         GlobalPreferenceSystem().registerPreference( "State", IntImportStringCaller( g_layout_globals.nState ), IntExportStringCaller( g_layout_globals.nState ) );
3363         GlobalPreferenceSystem().registerPreference( "PositionX", IntImportStringCaller( g_layout_globals.m_position.x ), IntExportStringCaller( g_layout_globals.m_position.x ) );
3364         GlobalPreferenceSystem().registerPreference( "PositionY", IntImportStringCaller( g_layout_globals.m_position.y ), IntExportStringCaller( g_layout_globals.m_position.y ) );
3365         GlobalPreferenceSystem().registerPreference( "Width", IntImportStringCaller( g_layout_globals.m_position.w ), IntExportStringCaller( g_layout_globals.m_position.w ) );
3366         GlobalPreferenceSystem().registerPreference( "Height", IntImportStringCaller( g_layout_globals.m_position.h ), IntExportStringCaller( g_layout_globals.m_position.h ) );
3367
3368         GlobalPreferenceSystem().registerPreference( "CamWnd", WindowPositionTrackerImportStringCaller( g_posCamWnd ), WindowPositionTrackerExportStringCaller( g_posCamWnd ) );
3369         GlobalPreferenceSystem().registerPreference( "XYWnd", WindowPositionTrackerImportStringCaller( g_posXYWnd ), WindowPositionTrackerExportStringCaller( g_posXYWnd ) );
3370         GlobalPreferenceSystem().registerPreference( "YZWnd", WindowPositionTrackerImportStringCaller( g_posYZWnd ), WindowPositionTrackerExportStringCaller( g_posYZWnd ) );
3371         GlobalPreferenceSystem().registerPreference( "XZWnd", WindowPositionTrackerImportStringCaller( g_posXZWnd ), WindowPositionTrackerExportStringCaller( g_posXZWnd ) );
3372
3373         {
3374                 const char* ENGINEPATH_ATTRIBUTE =
3375 #if defined( WIN32 )
3376                         "enginepath_win32"
3377 #elif defined( __linux__ ) || defined ( __FreeBSD__ )
3378                         "enginepath_linux"
3379 #elif defined( __APPLE__ )
3380                         "enginepath_macos"
3381 #else
3382 #error "unknown platform"
3383 #endif
3384                 ;
3385                 StringOutputStream path( 256 );
3386                 path << DirectoryCleaned( g_pGameDescription->getRequiredKeyValue( ENGINEPATH_ATTRIBUTE ) );
3387                 g_strEnginePath = path.c_str();
3388         }
3389
3390         GlobalPreferenceSystem().registerPreference( "EnginePath", CopiedStringImportStringCaller( g_strEnginePath ), CopiedStringExportStringCaller( g_strEnginePath ) );
3391
3392         g_Layout_viewStyle.useLatched();
3393         g_Layout_enableDetachableMenus.useLatched();
3394         g_Layout_enablePatchToolbar.useLatched();
3395         g_Layout_enablePluginToolbar.useLatched();
3396         g_Layout_enableFilterToolbar.useLatched();
3397
3398         Layout_registerPreferencesPage();
3399         Paths_registerPreferencesPage();
3400
3401         g_brushCount.setCountChangedCallback( FreeCaller<QE_brushCountChanged>() );
3402         g_entityCount.setCountChangedCallback( FreeCaller<QE_entityCountChanged>() );
3403         GlobalEntityCreator().setCounter( &g_entityCount );
3404
3405         GLWidget_sharedContextCreated = GlobalGL_sharedContextCreated;
3406         GLWidget_sharedContextDestroyed = GlobalGL_sharedContextDestroyed;
3407
3408         GlobalEntityClassManager().attach( g_WorldspawnColourEntityClassObserver );
3409 }
3410
3411 void MainFrame_Destroy(){
3412         GlobalEntityClassManager().detach( g_WorldspawnColourEntityClassObserver );
3413
3414         GlobalEntityCreator().setCounter( 0 );
3415         g_entityCount.setCountChangedCallback( Callback() );
3416         g_brushCount.setCountChangedCallback( Callback() );
3417 }
3418
3419
3420 void GLWindow_Construct(){
3421         GlobalPreferenceSystem().registerPreference( "MouseButtons", IntImportStringCaller( g_glwindow_globals.m_nMouseType ), IntExportStringCaller( g_glwindow_globals.m_nMouseType ) );
3422 }
3423
3424 void GLWindow_Destroy(){
3425 }