]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/mainframe.cpp
Auto cap button
[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
1797
1798
1799 GtkMenuItem* create_file_menu(){
1800         // File menu
1801         GtkMenuItem* file_menu_item = new_sub_menu_item_with_mnemonic( "_File" );
1802         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( file_menu_item ) );
1803         if ( g_Layout_enableDetachableMenus.m_value ) {
1804                 menu_tearoff( menu );
1805         }
1806
1807         create_menu_item_with_mnemonic( menu, "_New Map", "NewMap" );
1808         menu_separator( menu );
1809
1810 #if 0
1811         //++timo temporary experimental stuff for sleep mode..
1812         create_menu_item_with_mnemonic( menu, "_Sleep", "Sleep" );
1813         menu_separator( menu );
1814         // end experimental
1815 #endif
1816
1817         create_menu_item_with_mnemonic( menu, "_Open...", "OpenMap" );
1818
1819         create_menu_item_with_mnemonic( menu, "_Import...", "ImportMap" );
1820         create_menu_item_with_mnemonic( menu, "_Save", "SaveMap" );
1821         create_menu_item_with_mnemonic( menu, "Save _as...", "SaveMapAs" );
1822         create_menu_item_with_mnemonic( menu, "Save s_elected...", "SaveSelected" );
1823         menu_separator( menu );
1824         create_menu_item_with_mnemonic( menu, "Save re_gion...", "SaveRegion" );
1825         menu_separator( menu );
1826         create_menu_item_with_mnemonic( menu, "_Refresh models", "RefreshReferences" );
1827         menu_separator( menu );
1828         create_menu_item_with_mnemonic( menu, "Pro_ject settings...", "ProjectSettings" );
1829         menu_separator( menu );
1830         create_menu_item_with_mnemonic( menu, "_Pointfile...", "TogglePointfile" );
1831         menu_separator( menu );
1832         MRU_constructMenu( menu );
1833         menu_separator( menu );
1834         create_menu_item_with_mnemonic( menu, "Check for NetRadiant update (web)", "CheckForUpdate" ); // FIXME
1835         create_menu_item_with_mnemonic( menu, "E_xit", "Exit" );
1836
1837         return file_menu_item;
1838 }
1839
1840 GtkMenuItem* create_edit_menu(){
1841         // Edit menu
1842         GtkMenuItem* edit_menu_item = new_sub_menu_item_with_mnemonic( "_Edit" );
1843         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( edit_menu_item ) );
1844         if ( g_Layout_enableDetachableMenus.m_value ) {
1845                 menu_tearoff( menu );
1846         }
1847         create_menu_item_with_mnemonic( menu, "_Undo", "Undo" );
1848         create_menu_item_with_mnemonic( menu, "_Redo", "Redo" );
1849         menu_separator( menu );
1850         create_menu_item_with_mnemonic( menu, "_Copy", "Copy" );
1851         create_menu_item_with_mnemonic( menu, "_Paste", "Paste" );
1852         create_menu_item_with_mnemonic( menu, "P_aste To Camera", "PasteToCamera" );
1853         menu_separator( menu );
1854         create_menu_item_with_mnemonic( menu, "_Duplicate", "CloneSelection" );
1855         create_menu_item_with_mnemonic( menu, "Duplicate, make uni_que", "CloneSelectionAndMakeUnique" );
1856         create_menu_item_with_mnemonic( menu, "D_elete", "DeleteSelection" );
1857         menu_separator( menu );
1858         create_menu_item_with_mnemonic( menu, "Pa_rent", "ParentSelection" );
1859         menu_separator( menu );
1860         create_menu_item_with_mnemonic( menu, "C_lear Selection", "UnSelectSelection" );
1861         create_menu_item_with_mnemonic( menu, "_Invert Selection", "InvertSelection" );
1862         create_menu_item_with_mnemonic( menu, "Select i_nside", "SelectInside" );
1863         create_menu_item_with_mnemonic( menu, "Select _touching", "SelectTouching" );
1864
1865         GtkMenu* convert_menu = create_sub_menu_with_mnemonic( menu, "E_xpand Selection" );
1866         if ( g_Layout_enableDetachableMenus.m_value ) {
1867                 menu_tearoff( convert_menu );
1868         }
1869         create_menu_item_with_mnemonic( convert_menu, "To Whole _Entities", "ExpandSelectionToEntities" );
1870
1871         menu_separator( menu );
1872         create_menu_item_with_mnemonic( menu, "Pre_ferences...", "Preferences" );
1873
1874         return edit_menu_item;
1875 }
1876
1877 void fill_view_xy_top_menu( GtkMenu* menu ){
1878         create_check_menu_item_with_mnemonic( menu, "XY (Top) View", "ToggleView" );
1879 }
1880
1881
1882 void fill_view_yz_side_menu( GtkMenu* menu ){
1883         create_check_menu_item_with_mnemonic( menu, "YZ (Side) View", "ToggleSideView" );
1884 }
1885
1886
1887 void fill_view_xz_front_menu( GtkMenu* menu ){
1888         create_check_menu_item_with_mnemonic( menu, "XZ (Front) View", "ToggleFrontView" );
1889 }
1890
1891
1892 GtkWidget* g_toggle_z_item = 0;
1893 GtkWidget* g_toggle_console_item = 0;
1894 GtkWidget* g_toggle_entity_item = 0;
1895 GtkWidget* g_toggle_entitylist_item = 0;
1896
1897 GtkMenuItem* create_view_menu( MainFrame::EViewStyle style ){
1898         // View menu
1899         GtkMenuItem* view_menu_item = new_sub_menu_item_with_mnemonic( "Vie_w" );
1900         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( view_menu_item ) );
1901         if ( g_Layout_enableDetachableMenus.m_value ) {
1902                 menu_tearoff( menu );
1903         }
1904
1905         if ( style == MainFrame::eFloating ) {
1906                 fill_view_camera_menu( menu );
1907                 fill_view_xy_top_menu( menu );
1908                 fill_view_yz_side_menu( menu );
1909                 fill_view_xz_front_menu( menu );
1910         }
1911         if ( style == MainFrame::eFloating || style == MainFrame::eSplit ) {
1912                 create_menu_item_with_mnemonic( menu, "Console View", "ToggleConsole" );
1913                 create_menu_item_with_mnemonic( menu, "Texture Browser", "ToggleTextures" );
1914                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ToggleEntityInspector" );
1915         }
1916         else
1917         {
1918                 create_menu_item_with_mnemonic( menu, "Entity Inspector", "ViewEntityInfo" );
1919         }
1920         create_menu_item_with_mnemonic( menu, "_Surface Inspector", "SurfaceInspector" );
1921         create_menu_item_with_mnemonic( menu, "Entity List", "EntityList" );
1922
1923         menu_separator( menu );
1924         {
1925                 GtkMenu* camera_menu = create_sub_menu_with_mnemonic( menu, "Camera" );
1926                 if ( g_Layout_enableDetachableMenus.m_value ) {
1927                         menu_tearoff( camera_menu );
1928                 }
1929                 create_menu_item_with_mnemonic( camera_menu, "_Center", "CenterView" );
1930                 create_menu_item_with_mnemonic( camera_menu, "_Up Floor", "UpFloor" );
1931                 create_menu_item_with_mnemonic( camera_menu, "_Down Floor", "DownFloor" );
1932                 menu_separator( camera_menu );
1933                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane In", "CubicClipZoomIn" );
1934                 create_menu_item_with_mnemonic( camera_menu, "Far Clip Plane Out", "CubicClipZoomOut" );
1935                 menu_separator( camera_menu );
1936                 create_menu_item_with_mnemonic( camera_menu, "Next leak spot", "NextLeakSpot" );
1937                 create_menu_item_with_mnemonic( camera_menu, "Previous leak spot", "PrevLeakSpot" );
1938                 menu_separator( camera_menu );
1939                 create_menu_item_with_mnemonic( camera_menu, "Look Through Selected", "LookThroughSelected" );
1940                 create_menu_item_with_mnemonic( camera_menu, "Look Through Camera", "LookThroughCamera" );
1941         }
1942         menu_separator( menu );
1943         {
1944                 GtkMenu* orthographic_menu = create_sub_menu_with_mnemonic( menu, "Orthographic" );
1945                 if ( g_Layout_enableDetachableMenus.m_value ) {
1946                         menu_tearoff( orthographic_menu );
1947                 }
1948                 if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
1949                         create_menu_item_with_mnemonic( orthographic_menu, "_Next (XY, YZ, XY)", "NextView" );
1950                         create_menu_item_with_mnemonic( orthographic_menu, "XY (Top)", "ViewTop" );
1951                         create_menu_item_with_mnemonic( orthographic_menu, "YZ", "ViewSide" );
1952                         create_menu_item_with_mnemonic( orthographic_menu, "XZ", "ViewFront" );
1953                         menu_separator( orthographic_menu );
1954                 }
1955
1956                 create_menu_item_with_mnemonic( orthographic_menu, "_XY 100%", "Zoom100" );
1957                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _In", "ZoomIn" );
1958                 create_menu_item_with_mnemonic( orthographic_menu, "XY Zoom _Out", "ZoomOut" );
1959         }
1960
1961         menu_separator( menu );
1962
1963         {
1964                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Show" );
1965                 if ( g_Layout_enableDetachableMenus.m_value ) {
1966                         menu_tearoff( menu_in_menu );
1967                 }
1968                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Angles", "ShowAngles" );
1969                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show _Names", "ShowNames" );
1970                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Blocks", "ShowBlocks" );
1971                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show C_oordinates", "ShowCoordinates" );
1972                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Window Outline", "ShowWindowOutline" );
1973                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Axes", "ShowAxes" );
1974                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Workzone", "ShowWorkzone" );
1975                 create_check_menu_item_with_mnemonic( menu_in_menu, "Show Stats", "ShowStats" );
1976         }
1977
1978         {
1979                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Filter" );
1980                 if ( g_Layout_enableDetachableMenus.m_value ) {
1981                         menu_tearoff( menu_in_menu );
1982                 }
1983                 Filters_constructMenu( menu_in_menu );
1984         }
1985         menu_separator( menu );
1986         {
1987                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Hide/Show" );
1988                 if ( g_Layout_enableDetachableMenus.m_value ) {
1989                         menu_tearoff( menu_in_menu );
1990                 }
1991                 create_menu_item_with_mnemonic( menu_in_menu, "Hide Selected", "HideSelected" );
1992                 create_menu_item_with_mnemonic( menu_in_menu, "Show Hidden", "ShowHidden" );
1993         }
1994         menu_separator( menu );
1995         {
1996                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Region" );
1997                 if ( g_Layout_enableDetachableMenus.m_value ) {
1998                         menu_tearoff( menu_in_menu );
1999                 }
2000                 create_menu_item_with_mnemonic( menu_in_menu, "_Off", "RegionOff" );
2001                 create_menu_item_with_mnemonic( menu_in_menu, "_Set XY", "RegionSetXY" );
2002                 create_menu_item_with_mnemonic( menu_in_menu, "Set _Brush", "RegionSetBrush" );
2003                 create_menu_item_with_mnemonic( menu_in_menu, "Set Se_lected Brushes", "RegionSetSelection" );
2004         }
2005
2006         command_connect_accelerator( "CenterXYView" );
2007
2008         return view_menu_item;
2009 }
2010
2011 GtkMenuItem* create_selection_menu(){
2012         // Selection menu
2013         GtkMenuItem* selection_menu_item = new_sub_menu_item_with_mnemonic( "M_odify" );
2014         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( selection_menu_item ) );
2015         if ( g_Layout_enableDetachableMenus.m_value ) {
2016                 menu_tearoff( menu );
2017         }
2018
2019         {
2020                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Components" );
2021                 if ( g_Layout_enableDetachableMenus.m_value ) {
2022                         menu_tearoff( menu_in_menu );
2023                 }
2024                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Edges", "DragEdges" );
2025                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Vertices", "DragVertices" );
2026                 create_check_menu_item_with_mnemonic( menu_in_menu, "_Faces", "DragFaces" );
2027         }
2028
2029         menu_separator( menu );
2030
2031         {
2032                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Nudge" );
2033                 if ( g_Layout_enableDetachableMenus.m_value ) {
2034                         menu_tearoff( menu_in_menu );
2035                 }
2036                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Left", "SelectNudgeLeft" );
2037                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Right", "SelectNudgeRight" );
2038                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Up", "SelectNudgeUp" );
2039                 create_menu_item_with_mnemonic( menu_in_menu, "Nudge Down", "SelectNudgeDown" );
2040         }
2041         {
2042                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Rotate" );
2043                 if ( g_Layout_enableDetachableMenus.m_value ) {
2044                         menu_tearoff( menu_in_menu );
2045                 }
2046                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate X", "RotateSelectionX" );
2047                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Y", "RotateSelectionY" );
2048                 create_menu_item_with_mnemonic( menu_in_menu, "Rotate Z", "RotateSelectionZ" );
2049         }
2050         {
2051                 GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Flip" );
2052                 if ( g_Layout_enableDetachableMenus.m_value ) {
2053                         menu_tearoff( menu_in_menu );
2054                 }
2055                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _X", "MirrorSelectionX" );
2056                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Y", "MirrorSelectionY" );
2057                 create_menu_item_with_mnemonic( menu_in_menu, "Flip _Z", "MirrorSelectionZ" );
2058         }
2059         menu_separator( menu );
2060         create_menu_item_with_mnemonic( menu, "Arbitrary rotation...", "ArbitraryRotation" );
2061         create_menu_item_with_mnemonic( menu, "Arbitrary scale...", "ArbitraryScale" );
2062
2063         return selection_menu_item;
2064 }
2065
2066 GtkMenuItem* create_bsp_menu(){
2067         // BSP menu
2068         GtkMenuItem* bsp_menu_item = new_sub_menu_item_with_mnemonic( "_Build" );
2069         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( bsp_menu_item ) );
2070
2071         if ( g_Layout_enableDetachableMenus.m_value ) {
2072                 menu_tearoff( menu );
2073         }
2074
2075         create_menu_item_with_mnemonic( menu, "Customize...", "BuildMenuCustomize" );
2076
2077         menu_separator( menu );
2078
2079         Build_constructMenu( menu );
2080
2081         g_bsp_menu = menu;
2082
2083         return bsp_menu_item;
2084 }
2085
2086 GtkMenuItem* create_grid_menu(){
2087         // Grid menu
2088         GtkMenuItem* grid_menu_item = new_sub_menu_item_with_mnemonic( "_Grid" );
2089         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( grid_menu_item ) );
2090         if ( g_Layout_enableDetachableMenus.m_value ) {
2091                 menu_tearoff( menu );
2092         }
2093
2094         Grid_constructMenu( menu );
2095
2096         return grid_menu_item;
2097 }
2098
2099 GtkMenuItem* create_misc_menu(){
2100         // Misc menu
2101         GtkMenuItem* misc_menu_item = new_sub_menu_item_with_mnemonic( "M_isc" );
2102         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( misc_menu_item ) );
2103         if ( g_Layout_enableDetachableMenus.m_value ) {
2104                 menu_tearoff( menu );
2105         }
2106
2107 #if 0
2108         create_menu_item_with_mnemonic( menu, "_Benchmark", FreeCaller<GlobalCamera_Benchmark>() );
2109 #endif
2110         gtk_container_add( GTK_CONTAINER( menu ), GTK_WIDGET( create_colours_menu() ) );
2111
2112         create_menu_item_with_mnemonic( menu, "Find brush...", "FindBrush" );
2113         create_menu_item_with_mnemonic( menu, "Map Info...", "MapInfo" );
2114         // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394
2115 //  create_menu_item_with_mnemonic(menu, "_Print XY View", FreeCaller<WXY_Print>());
2116         create_menu_item_with_mnemonic( menu, "_Background select", FreeCaller<WXY_BackgroundSelect>() );
2117         return misc_menu_item;
2118 }
2119
2120 GtkMenuItem* create_entity_menu(){
2121         // Brush menu
2122         GtkMenuItem* entity_menu_item = new_sub_menu_item_with_mnemonic( "E_ntity" );
2123         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( entity_menu_item ) );
2124         if ( g_Layout_enableDetachableMenus.m_value ) {
2125                 menu_tearoff( menu );
2126         }
2127
2128         Entity_constructMenu( menu );
2129
2130         return entity_menu_item;
2131 }
2132
2133 GtkMenuItem* create_brush_menu(){
2134         // Brush menu
2135         GtkMenuItem* brush_menu_item = new_sub_menu_item_with_mnemonic( "B_rush" );
2136         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( brush_menu_item ) );
2137         if ( g_Layout_enableDetachableMenus.m_value ) {
2138                 menu_tearoff( menu );
2139         }
2140
2141         Brush_constructMenu( menu );
2142
2143         return brush_menu_item;
2144 }
2145
2146 GtkMenuItem* create_patch_menu(){
2147         // Curve menu
2148         GtkMenuItem* patch_menu_item = new_sub_menu_item_with_mnemonic( "_Curve" );
2149         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( patch_menu_item ) );
2150         if ( g_Layout_enableDetachableMenus.m_value ) {
2151                 menu_tearoff( menu );
2152         }
2153
2154         Patch_constructMenu( menu );
2155
2156         return patch_menu_item;
2157 }
2158
2159 GtkMenuItem* create_help_menu(){
2160         // Help menu
2161         GtkMenuItem* help_menu_item = new_sub_menu_item_with_mnemonic( "_Help" );
2162         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( help_menu_item ) );
2163         if ( g_Layout_enableDetachableMenus.m_value ) {
2164                 menu_tearoff( menu );
2165         }
2166
2167         create_menu_item_with_mnemonic( menu, "Manual", "OpenManual" );
2168
2169         // this creates all the per-game drop downs for the game pack helps
2170         // it will take care of hooking the Sys_OpenURL calls etc.
2171         create_game_help_menu( menu );
2172
2173         create_menu_item_with_mnemonic( menu, "Bug report", FreeCaller<OpenBugReportURL>() );
2174         create_menu_item_with_mnemonic( menu, "Shortcuts list", FreeCaller<DoCommandListDlg>() );
2175         create_menu_item_with_mnemonic( menu, "_About", FreeCaller<DoAbout>() );
2176
2177         return help_menu_item;
2178 }
2179
2180 GtkMenuBar* create_main_menu( MainFrame::EViewStyle style ){
2181         GtkMenuBar* menu_bar = GTK_MENU_BAR( gtk_menu_bar_new() );
2182         gtk_widget_show( GTK_WIDGET( menu_bar ) );
2183
2184         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_file_menu() ) );
2185         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_edit_menu() ) );
2186         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_view_menu( style ) ) );
2187         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_selection_menu() ) );
2188         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_bsp_menu() ) );
2189         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_grid_menu() ) );
2190         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_misc_menu() ) );
2191         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_entity_menu() ) );
2192         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_brush_menu() ) );
2193         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_patch_menu() ) );
2194         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_plugins_menu() ) );
2195         gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_help_menu() ) );
2196
2197         return menu_bar;
2198 }
2199
2200
2201 void PatchInspector_registerShortcuts(){
2202         command_connect_accelerator( "PatchInspector" );
2203 }
2204
2205 void Patch_registerShortcuts(){
2206         command_connect_accelerator( "InvertCurveTextureX" );
2207         command_connect_accelerator( "InvertCurveTextureY" );
2208         command_connect_accelerator( "PatchInsertInsertColumn" );
2209         command_connect_accelerator( "PatchInsertInsertRow" );
2210         command_connect_accelerator( "PatchDeleteLastColumn" );
2211         command_connect_accelerator( "PatchDeleteLastRow" );
2212         command_connect_accelerator( "NaturalizePatch" );
2213         //command_connect_accelerator("CapCurrentCurve");
2214 }
2215
2216 void Manipulators_registerShortcuts(){
2217         toggle_add_accelerator( "MouseRotate" );
2218         toggle_add_accelerator( "MouseTranslate" );
2219         toggle_add_accelerator( "MouseScale" );
2220         toggle_add_accelerator( "MouseDrag" );
2221         toggle_add_accelerator( "ToggleClipper" );
2222 }
2223
2224 void TexdefNudge_registerShortcuts(){
2225         command_connect_accelerator( "TexRotateClock" );
2226         command_connect_accelerator( "TexRotateCounter" );
2227         command_connect_accelerator( "TexScaleUp" );
2228         command_connect_accelerator( "TexScaleDown" );
2229         command_connect_accelerator( "TexScaleLeft" );
2230         command_connect_accelerator( "TexScaleRight" );
2231         command_connect_accelerator( "TexShiftUp" );
2232         command_connect_accelerator( "TexShiftDown" );
2233         command_connect_accelerator( "TexShiftLeft" );
2234         command_connect_accelerator( "TexShiftRight" );
2235 }
2236
2237 void SelectNudge_registerShortcuts(){
2238         command_connect_accelerator( "MoveSelectionDOWN" );
2239         command_connect_accelerator( "MoveSelectionUP" );
2240         //command_connect_accelerator("SelectNudgeLeft");
2241         //command_connect_accelerator("SelectNudgeRight");
2242         //command_connect_accelerator("SelectNudgeUp");
2243         //command_connect_accelerator("SelectNudgeDown");
2244 }
2245
2246 void SnapToGrid_registerShortcuts(){
2247         command_connect_accelerator( "SnapToGrid" );
2248 }
2249
2250 void SelectByType_registerShortcuts(){
2251         command_connect_accelerator( "SelectAllOfType" );
2252 }
2253
2254 void SurfaceInspector_registerShortcuts(){
2255         command_connect_accelerator( "FitTexture" );
2256 }
2257
2258
2259 void register_shortcuts(){
2260         PatchInspector_registerShortcuts();
2261         Patch_registerShortcuts();
2262         Grid_registerShortcuts();
2263         XYWnd_registerShortcuts();
2264         CamWnd_registerShortcuts();
2265         Manipulators_registerShortcuts();
2266         SurfaceInspector_registerShortcuts();
2267         TexdefNudge_registerShortcuts();
2268         SelectNudge_registerShortcuts();
2269         SnapToGrid_registerShortcuts();
2270         SelectByType_registerShortcuts();
2271 }
2272
2273 void File_constructToolbar( GtkToolbar* toolbar ){
2274         toolbar_append_button( toolbar, "Open an existing map (CTRL + O)", "file_open.bmp", "OpenMap" );
2275         toolbar_append_button( toolbar, "Save the active map (CTRL + S)", "file_save.bmp", "SaveMap" );
2276 }
2277
2278 void UndoRedo_constructToolbar( GtkToolbar* toolbar ){
2279         toolbar_append_button( toolbar, "Undo (CTRL + Z)", "undo.bmp", "Undo" );
2280         toolbar_append_button( toolbar, "Redo (CTRL + Y)", "redo.bmp", "Redo" );
2281 }
2282
2283 void RotateFlip_constructToolbar( GtkToolbar* toolbar ){
2284         toolbar_append_button( toolbar, "x-axis Flip", "brush_flipx.bmp", "MirrorSelectionX" );
2285         toolbar_append_button( toolbar, "x-axis Rotate", "brush_rotatex.bmp", "RotateSelectionX" );
2286         toolbar_append_button( toolbar, "y-axis Flip", "brush_flipy.bmp", "MirrorSelectionY" );
2287         toolbar_append_button( toolbar, "y-axis Rotate", "brush_rotatey.bmp", "RotateSelectionY" );
2288         toolbar_append_button( toolbar, "z-axis Flip", "brush_flipz.bmp", "MirrorSelectionZ" );
2289         toolbar_append_button( toolbar, "z-axis Rotate", "brush_rotatez.bmp", "RotateSelectionZ" );
2290 }
2291
2292 void Select_constructToolbar( GtkToolbar* toolbar ){
2293         toolbar_append_button( toolbar, "Select touching", "selection_selecttouching.bmp", "SelectTouching" );
2294         toolbar_append_button( toolbar, "Select inside", "selection_selectinside.bmp", "SelectInside" );
2295 }
2296
2297 void CSG_constructToolbar( GtkToolbar* toolbar ){
2298         toolbar_append_button( toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.bmp", "CSGSubtract" );
2299         toolbar_append_button( toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.bmp", "CSGMerge" );
2300         toolbar_append_button( toolbar, "Hollow", "selection_makehollow.bmp", "CSGHollow" );
2301 }
2302
2303 void ComponentModes_constructToolbar( GtkToolbar* toolbar ){
2304         toolbar_append_toggle_button( toolbar, "Select Vertices (V)", "modify_vertices.bmp", "DragVertices" );
2305         toolbar_append_toggle_button( toolbar, "Select Edges (E)", "modify_edges.bmp", "DragEdges" );
2306         toolbar_append_toggle_button( toolbar, "Select Faces (F)", "modify_faces.bmp", "DragFaces" );
2307 }
2308
2309 void Clipper_constructToolbar( GtkToolbar* toolbar ){
2310
2311         toolbar_append_toggle_button( toolbar, "Clipper (X)", "view_clipper.bmp", "ToggleClipper" );
2312 }
2313
2314 void XYWnd_constructToolbar( GtkToolbar* toolbar ){
2315         toolbar_append_button( toolbar, "Change views", "view_change.bmp", "NextView" );
2316 }
2317
2318 void Manipulators_constructToolbar( GtkToolbar* toolbar ){
2319         toolbar_append_toggle_button( toolbar, "Translate (W)", "select_mousetranslate.bmp", "MouseTranslate" );
2320         toolbar_append_toggle_button( toolbar, "Rotate (R)", "select_mouserotate.bmp", "MouseRotate" );
2321         toolbar_append_toggle_button( toolbar, "Scale", "select_mousescale.bmp", "MouseScale" );
2322         toolbar_append_toggle_button( toolbar, "Resize (Q)", "select_mouseresize.bmp", "MouseDrag" );
2323
2324         Clipper_constructToolbar( toolbar );
2325 }
2326
2327 GtkToolbar* create_main_toolbar( MainFrame::EViewStyle style ){
2328         GtkToolbar* toolbar = GTK_TOOLBAR( gtk_toolbar_new() );
2329         gtk_toolbar_set_orientation( toolbar, GTK_ORIENTATION_HORIZONTAL );
2330         gtk_toolbar_set_style( toolbar, GTK_TOOLBAR_ICONS );
2331
2332         gtk_widget_show( GTK_WIDGET( toolbar ) );
2333
2334         File_constructToolbar( toolbar );
2335
2336         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2337
2338         UndoRedo_constructToolbar( toolbar );
2339
2340         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2341
2342         RotateFlip_constructToolbar( toolbar );
2343
2344         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2345
2346         Select_constructToolbar( toolbar );
2347
2348         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2349
2350         CSG_constructToolbar( toolbar );
2351
2352         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2353
2354         ComponentModes_constructToolbar( toolbar );
2355
2356         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating ) {
2357                 gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2358
2359                 XYWnd_constructToolbar( toolbar );
2360         }
2361
2362         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2363
2364         CamWnd_constructToolbar( toolbar );
2365
2366         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2367
2368         Manipulators_constructToolbar( toolbar );
2369
2370         if ( g_Layout_enablePatchToolbar.m_value ) {
2371                 gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2372
2373                 Patch_constructToolbar( toolbar );
2374         }
2375
2376         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2377
2378         toolbar_append_toggle_button( toolbar, "Texture Lock (SHIFT +T)", "texture_lock.bmp", "TogTexLock" );
2379
2380         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2381
2382         GtkButton* g_view_entities_button = toolbar_append_button( toolbar, "Entities (N)", "entities.bmp", "ToggleEntityInspector" );
2383         GtkButton* g_view_console_button = toolbar_append_button( toolbar, "Console (O)", "console.bmp", "ToggleConsole" );
2384         GtkButton* g_view_textures_button = toolbar_append_button( toolbar, "Texture Browser (T)", "texture_browser.bmp", "ToggleTextures" );
2385         // TODO: call light inspector
2386         //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.bmp", "ToggleLightInspector");
2387
2388         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2389         GtkButton* g_refresh_models_button = toolbar_append_button( toolbar, "Refresh Models", "refresh_models.bmp", "RefreshReferences" );
2390
2391
2392         // disable the console and texture button in the regular layouts
2393         if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft ) {
2394                 gtk_widget_set_sensitive( GTK_WIDGET( g_view_console_button ), FALSE );
2395                 gtk_widget_set_sensitive( GTK_WIDGET( g_view_textures_button ), FALSE );
2396         }
2397
2398         return toolbar;
2399 }
2400
2401 GtkWidget* create_main_statusbar( GtkWidget *pStatusLabel[c_count_status] ){
2402         GtkTable* table = GTK_TABLE( gtk_table_new( 1, c_count_status, FALSE ) );
2403         gtk_widget_show( GTK_WIDGET( table ) );
2404
2405         {
2406                 GtkLabel* label = GTK_LABEL( gtk_label_new( "Label" ) );
2407                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
2408                 gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
2409                 gtk_widget_show( GTK_WIDGET( label ) );
2410                 gtk_table_attach_defaults( table, GTK_WIDGET( label ), 0, 1, 0, 1 );
2411                 pStatusLabel[c_command_status] = GTK_WIDGET( label );
2412         }
2413
2414         for ( int i = 1; i < c_count_status; ++i )
2415         {
2416                 GtkFrame* frame = GTK_FRAME( gtk_frame_new( 0 ) );
2417                 gtk_widget_show( GTK_WIDGET( frame ) );
2418                 gtk_table_attach_defaults( table, GTK_WIDGET( frame ), i, i + 1, 0, 1 );
2419                 gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN );
2420
2421                 GtkLabel* label = GTK_LABEL( gtk_label_new( "Label" ) );
2422                 gtk_label_set_ellipsize( label, PANGO_ELLIPSIZE_END );
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_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( label ) );
2427                 pStatusLabel[i] = GTK_WIDGET( label );
2428         }
2429
2430         return GTK_WIDGET( table );
2431 }
2432
2433 #if 0
2434
2435
2436 WidgetFocusPrinter g_mainframeWidgetFocusPrinter( "mainframe" );
2437
2438 class WindowFocusPrinter
2439 {
2440 const char* m_name;
2441
2442 static gboolean frame_event( GtkWidget *widget, GdkEvent* event, WindowFocusPrinter* self ){
2443         globalOutputStream() << self->m_name << " frame_event\n";
2444         return FALSE;
2445 }
2446 static gboolean keys_changed( GtkWidget *widget, WindowFocusPrinter* self ){
2447         globalOutputStream() << self->m_name << " keys_changed\n";
2448         return FALSE;
2449 }
2450 static gboolean notify( GtkWindow* window, gpointer dummy, WindowFocusPrinter* self ){
2451         if ( gtk_window_is_active( window ) ) {
2452                 globalOutputStream() << self->m_name << " takes toplevel focus\n";
2453         }
2454         else
2455         {
2456                 globalOutputStream() << self->m_name << " loses toplevel focus\n";
2457         }
2458         return FALSE;
2459 }
2460 public:
2461 WindowFocusPrinter( const char* name ) : m_name( name ){
2462 }
2463 void connect( GtkWindow* toplevel_window ){
2464         g_signal_connect( G_OBJECT( toplevel_window ), "notify::has_toplevel_focus", G_CALLBACK( notify ), this );
2465         g_signal_connect( G_OBJECT( toplevel_window ), "notify::is_active", G_CALLBACK( notify ), this );
2466         g_signal_connect( G_OBJECT( toplevel_window ), "keys_changed", G_CALLBACK( keys_changed ), this );
2467         g_signal_connect( G_OBJECT( toplevel_window ), "frame_event", G_CALLBACK( frame_event ), this );
2468 }
2469 };
2470
2471 WindowFocusPrinter g_mainframeFocusPrinter( "mainframe" );
2472
2473 #endif
2474
2475 class MainWindowActive
2476 {
2477 static gboolean notify( GtkWindow* window, gpointer dummy, MainWindowActive* self ){
2478         if ( g_wait.m_window != 0 && gtk_window_is_active( window ) && !GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
2479                 gtk_widget_show( GTK_WIDGET( g_wait.m_window ) );
2480         }
2481
2482         return FALSE;
2483 }
2484 public:
2485 void connect( GtkWindow* toplevel_window ){
2486         g_signal_connect( G_OBJECT( toplevel_window ), "notify::is-active", G_CALLBACK( notify ), this );
2487 }
2488 };
2489
2490 MainWindowActive g_MainWindowActive;
2491
2492 SignalHandlerId XYWindowDestroyed_connect( const SignalHandler& handler ){
2493         return g_pParentWnd->GetXYWnd()->onDestroyed.connectFirst( handler );
2494 }
2495
2496 void XYWindowDestroyed_disconnect( SignalHandlerId id ){
2497         g_pParentWnd->GetXYWnd()->onDestroyed.disconnect( id );
2498 }
2499
2500 MouseEventHandlerId XYWindowMouseDown_connect( const MouseEventHandler& handler ){
2501         return g_pParentWnd->GetXYWnd()->onMouseDown.connectFirst( handler );
2502 }
2503
2504 void XYWindowMouseDown_disconnect( MouseEventHandlerId id ){
2505         g_pParentWnd->GetXYWnd()->onMouseDown.disconnect( id );
2506 }
2507
2508 // =============================================================================
2509 // MainFrame class
2510
2511 MainFrame* g_pParentWnd = 0;
2512
2513 GtkWindow* MainFrame_getWindow(){
2514         if ( g_pParentWnd == 0 ) {
2515                 return 0;
2516         }
2517         return g_pParentWnd->m_window;
2518 }
2519
2520 std::vector<GtkWidget*> g_floating_windows;
2521
2522 MainFrame::MainFrame() : m_window( 0 ), m_idleRedrawStatusText( RedrawStatusTextCaller( *this ) ){
2523         m_pXYWnd = 0;
2524         m_pCamWnd = 0;
2525         m_pZWnd = 0;
2526         m_pYZWnd = 0;
2527         m_pXZWnd = 0;
2528         m_pActiveXY = 0;
2529
2530         for ( int n = 0; n < c_count_status; n++ )
2531         {
2532                 m_pStatusLabel[n] = 0;
2533         }
2534
2535         m_bSleeping = false;
2536
2537         Create();
2538 }
2539
2540 MainFrame::~MainFrame(){
2541         SaveWindowInfo();
2542
2543         gtk_widget_hide( GTK_WIDGET( m_window ) );
2544
2545         Shutdown();
2546
2547         for ( std::vector<GtkWidget*>::iterator i = g_floating_windows.begin(); i != g_floating_windows.end(); ++i )
2548         {
2549                 gtk_widget_destroy( *i );
2550         }
2551
2552         gtk_widget_destroy( GTK_WIDGET( m_window ) );
2553 }
2554
2555 void MainFrame::SetActiveXY( XYWnd* p ){
2556         if ( m_pActiveXY ) {
2557                 m_pActiveXY->SetActive( false );
2558         }
2559
2560         m_pActiveXY = p;
2561
2562         if ( m_pActiveXY ) {
2563                 m_pActiveXY->SetActive( true );
2564         }
2565
2566 }
2567
2568 void MainFrame::ReleaseContexts(){
2569 #if 0
2570         if ( m_pXYWnd ) {
2571                 m_pXYWnd->DestroyContext();
2572         }
2573         if ( m_pYZWnd ) {
2574                 m_pYZWnd->DestroyContext();
2575         }
2576         if ( m_pXZWnd ) {
2577                 m_pXZWnd->DestroyContext();
2578         }
2579         if ( m_pCamWnd ) {
2580                 m_pCamWnd->DestroyContext();
2581         }
2582         if ( m_pTexWnd ) {
2583                 m_pTexWnd->DestroyContext();
2584         }
2585         if ( m_pZWnd ) {
2586                 m_pZWnd->DestroyContext();
2587         }
2588 #endif
2589 }
2590
2591 void MainFrame::CreateContexts(){
2592 #if 0
2593         if ( m_pCamWnd ) {
2594                 m_pCamWnd->CreateContext();
2595         }
2596         if ( m_pXYWnd ) {
2597                 m_pXYWnd->CreateContext();
2598         }
2599         if ( m_pYZWnd ) {
2600                 m_pYZWnd->CreateContext();
2601         }
2602         if ( m_pXZWnd ) {
2603                 m_pXZWnd->CreateContext();
2604         }
2605         if ( m_pTexWnd ) {
2606                 m_pTexWnd->CreateContext();
2607         }
2608         if ( m_pZWnd ) {
2609                 m_pZWnd->CreateContext();
2610         }
2611 #endif
2612 }
2613
2614 #ifdef _DEBUG
2615 //#define DBG_SLEEP
2616 #endif
2617
2618 void MainFrame::OnSleep(){
2619 #if 0
2620         m_bSleeping ^= 1;
2621         if ( m_bSleeping ) {
2622                 // useful when trying to debug crashes in the sleep code
2623                 globalOutputStream() << "Going into sleep mode..\n";
2624
2625                 globalOutputStream() << "Dispatching sleep msg...";
2626                 DispatchRadiantMsg( RADIANT_SLEEP );
2627                 globalOutputStream() << "Done.\n";
2628
2629                 gtk_window_iconify( m_window );
2630                 GlobalSelectionSystem().setSelectedAll( false );
2631
2632                 GlobalShaderCache().unrealise();
2633                 Shaders_Free();
2634                 GlobalOpenGL_debugAssertNoErrors();
2635                 ScreenUpdates_Disable();
2636
2637                 // release contexts
2638                 globalOutputStream() << "Releasing contexts...";
2639                 ReleaseContexts();
2640                 globalOutputStream() << "Done.\n";
2641         }
2642         else
2643         {
2644                 globalOutputStream() << "Waking up\n";
2645
2646                 gtk_window_deiconify( m_window );
2647
2648                 // create contexts
2649                 globalOutputStream() << "Creating contexts...";
2650                 CreateContexts();
2651                 globalOutputStream() << "Done.\n";
2652
2653                 globalOutputStream() << "Making current on camera...";
2654                 m_pCamWnd->MakeCurrent();
2655                 globalOutputStream() << "Done.\n";
2656
2657                 globalOutputStream() << "Reloading shaders...";
2658                 Shaders_Load();
2659                 GlobalShaderCache().realise();
2660                 globalOutputStream() << "Done.\n";
2661
2662                 ScreenUpdates_Enable();
2663
2664                 globalOutputStream() << "Dispatching wake msg...";
2665                 DispatchRadiantMsg( RADIANT_WAKEUP );
2666                 globalOutputStream() << "Done\n";
2667         }
2668 #endif
2669 }
2670
2671
2672 GtkWindow* create_splash(){
2673         GtkWindow* window = GTK_WINDOW( gtk_window_new( GTK_WINDOW_TOPLEVEL ) );
2674         gtk_window_set_decorated( window, FALSE );
2675         gtk_window_set_resizable( window, FALSE );
2676         gtk_window_set_modal( window, TRUE );
2677         gtk_window_set_default_size( window, -1, -1 );
2678         gtk_window_set_position( window, GTK_WIN_POS_CENTER );
2679         gtk_container_set_border_width( GTK_CONTAINER( window ), 0 );
2680
2681         GtkImage* image = new_local_image( "splash.bmp" );
2682         gtk_widget_show( GTK_WIDGET( image ) );
2683         gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( image ) );
2684
2685         gtk_widget_set_size_request( GTK_WIDGET( window ), -1, -1 );
2686         gtk_widget_show( GTK_WIDGET( window ) );
2687
2688         return window;
2689 }
2690
2691 static GtkWindow *splash_screen = 0;
2692
2693 void show_splash(){
2694         splash_screen = create_splash();
2695
2696         process_gui();
2697 }
2698
2699 void hide_splash(){
2700         gtk_widget_destroy( GTK_WIDGET( splash_screen ) );
2701 }
2702
2703 WindowPositionTracker g_posCamWnd;
2704 WindowPositionTracker g_posXYWnd;
2705 WindowPositionTracker g_posXZWnd;
2706 WindowPositionTracker g_posYZWnd;
2707
2708 static gint mainframe_delete( GtkWidget *widget, GdkEvent *event, gpointer data ){
2709         if ( ConfirmModified( "Exit Radiant" ) ) {
2710                 gtk_main_quit();
2711         }
2712
2713         return TRUE;
2714 }
2715
2716 void MainFrame::Create(){
2717         GtkWindow* window = GTK_WINDOW( gtk_window_new( GTK_WINDOW_TOPLEVEL ) );
2718
2719         GlobalWindowObservers_connectTopLevel( window );
2720
2721         gtk_window_set_transient_for( splash_screen, window );
2722
2723 #if !defined( WIN32 )
2724         {
2725                 GdkPixbuf* pixbuf = pixbuf_new_from_file_with_mask( "bitmaps/icon.bmp" );
2726                 if ( pixbuf != 0 ) {
2727                         gtk_window_set_icon( window, pixbuf );
2728                         gdk_pixbuf_unref( pixbuf );
2729                 }
2730         }
2731 #endif
2732
2733         gtk_widget_add_events( GTK_WIDGET( window ), GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK );
2734         g_signal_connect( G_OBJECT( window ), "delete_event", G_CALLBACK( mainframe_delete ), this );
2735
2736         m_position_tracker.connect( window );
2737
2738 #if 0
2739         g_mainframeWidgetFocusPrinter.connect( window );
2740         g_mainframeFocusPrinter.connect( window );
2741 #endif
2742
2743         g_MainWindowActive.connect( window );
2744
2745         GetPlugInMgr().Init( GTK_WIDGET( window ) );
2746
2747         GtkWidget* vbox = gtk_vbox_new( FALSE, 0 );
2748         gtk_container_add( GTK_CONTAINER( window ), vbox );
2749         gtk_widget_show( vbox );
2750
2751         global_accel_connect_window( window );
2752
2753         m_nCurrentStyle = (EViewStyle)g_Layout_viewStyle.m_value;
2754
2755         register_shortcuts();
2756
2757         GtkMenuBar* main_menu = create_main_menu( CurrentStyle() );
2758         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( main_menu ), FALSE, FALSE, 0 );
2759
2760         GtkToolbar* main_toolbar = create_main_toolbar( CurrentStyle() );
2761         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( main_toolbar ), FALSE, FALSE, 0 );
2762
2763         GtkToolbar* plugin_toolbar = create_plugin_toolbar();
2764         if ( !g_Layout_enablePluginToolbar.m_value ) {
2765                 gtk_widget_hide( GTK_WIDGET( plugin_toolbar ) );
2766         }
2767         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( plugin_toolbar ), FALSE, FALSE, 0 );
2768
2769         GtkWidget* main_statusbar = create_main_statusbar( m_pStatusLabel );
2770         gtk_box_pack_end( GTK_BOX( vbox ), main_statusbar, FALSE, TRUE, 2 );
2771
2772         GroupDialog_constructWindow( window );
2773         g_page_entity = GroupDialog_addPage( "Entities", EntityInspector_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Entities" ) );
2774
2775         if ( FloatingGroupDialog() ) {
2776                 g_page_console = GroupDialog_addPage( "Console", Console_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Console" ) );
2777         }
2778
2779 #ifdef WIN32
2780         if ( g_multimon_globals.m_bStartOnPrimMon ) {
2781                 PositionWindowOnPrimaryScreen( g_layout_globals.m_position );
2782                 window_set_position( window, g_layout_globals.m_position );
2783         }
2784         else
2785 #endif
2786         if ( g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED ) {
2787                 gtk_window_maximize( window );
2788                 WindowPosition default_position( -1, -1, 640, 480 );
2789                 window_set_position( window, default_position );
2790         }
2791         else
2792         {
2793                 window_set_position( window, g_layout_globals.m_position );
2794         }
2795
2796         m_window = window;
2797
2798         gtk_widget_show( GTK_WIDGET( window ) );
2799
2800         if ( CurrentStyle() == eRegular || CurrentStyle() == eRegularLeft ) {
2801                 {
2802                         GtkWidget* vsplit = gtk_vpaned_new();
2803                         m_vSplit = vsplit;
2804                         gtk_box_pack_start( GTK_BOX( vbox ), vsplit, TRUE, TRUE, 0 );
2805                         gtk_widget_show( vsplit );
2806
2807                         // console
2808                         GtkWidget* console_window = Console_constructWindow( window );
2809                         gtk_paned_pack2( GTK_PANED( vsplit ), console_window, FALSE, TRUE );
2810
2811                         {
2812                                 GtkWidget* hsplit = gtk_hpaned_new();
2813                                 gtk_widget_show( hsplit );
2814                                 m_hSplit = hsplit;
2815                                 gtk_paned_add1( GTK_PANED( vsplit ), hsplit );
2816
2817                                 // xy
2818                                 m_pXYWnd = new XYWnd();
2819                                 m_pXYWnd->SetViewType( XY );
2820                                 GtkWidget* xy_window = GTK_WIDGET( create_framed_widget( m_pXYWnd->GetWidget() ) );
2821
2822                                 {
2823                                         GtkWidget* vsplit2 = gtk_vpaned_new();
2824                                         gtk_widget_show( vsplit2 );
2825                                         m_vSplit2 = vsplit2;
2826
2827                                         if ( CurrentStyle() == eRegular ) {
2828                                                 gtk_paned_add1( GTK_PANED( hsplit ), xy_window );
2829                                                 gtk_paned_add2( GTK_PANED( hsplit ), vsplit2 );
2830                                         }
2831                                         else
2832                                         {
2833                                                 gtk_paned_add1( GTK_PANED( hsplit ), vsplit2 );
2834                                                 gtk_paned_add2( GTK_PANED( hsplit ), xy_window );
2835                                         }
2836
2837
2838                                         // camera
2839                                         m_pCamWnd = NewCamWnd();
2840                                         GlobalCamera_setCamWnd( *m_pCamWnd );
2841                                         CamWnd_setParent( *m_pCamWnd, window );
2842                                         GtkFrame* camera_window = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
2843
2844                                         gtk_paned_add1( GTK_PANED( vsplit2 ), GTK_WIDGET( camera_window ) );
2845
2846                                         // textures
2847                                         GtkFrame* texture_window = create_framed_widget( TextureBrowser_constructWindow( window ) );
2848
2849                                         gtk_paned_add2( GTK_PANED( vsplit2 ), GTK_WIDGET( texture_window ) );
2850                                 }
2851                         }
2852                 }
2853
2854                 gtk_paned_set_position( GTK_PANED( m_vSplit ), g_layout_globals.nXYHeight );
2855
2856                 if ( CurrentStyle() == eRegular ) {
2857                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nXYWidth );
2858                 }
2859                 else
2860                 {
2861                         gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nCamWidth );
2862                 }
2863
2864                 gtk_paned_set_position( GTK_PANED( m_vSplit2 ), g_layout_globals.nCamHeight );
2865         }
2866         else if ( CurrentStyle() == eFloating ) {
2867                 {
2868                         GtkWindow* window = create_persistent_floating_window( "Camera", m_window );
2869                         global_accel_connect_window( window );
2870                         g_posCamWnd.connect( window );
2871
2872                         gtk_widget_show( GTK_WIDGET( window ) );
2873
2874                         m_pCamWnd = NewCamWnd();
2875                         GlobalCamera_setCamWnd( *m_pCamWnd );
2876
2877                         {
2878                                 GtkFrame* frame = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
2879                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2880                         }
2881                         CamWnd_setParent( *m_pCamWnd, window );
2882
2883                         g_floating_windows.push_back( GTK_WIDGET( window ) );
2884                 }
2885
2886                 {
2887                         GtkWindow* window = create_persistent_floating_window( ViewType_getTitle( XY ), m_window );
2888                         global_accel_connect_window( window );
2889                         g_posXYWnd.connect( window );
2890
2891                         m_pXYWnd = new XYWnd();
2892                         m_pXYWnd->m_parent = window;
2893                         m_pXYWnd->SetViewType( XY );
2894
2895
2896                         {
2897                                 GtkFrame* frame = create_framed_widget( m_pXYWnd->GetWidget() );
2898                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2899                         }
2900                         XY_Top_Shown_Construct( window );
2901
2902                         g_floating_windows.push_back( GTK_WIDGET( window ) );
2903                 }
2904
2905                 {
2906                         GtkWindow* window = create_persistent_floating_window( ViewType_getTitle( XZ ), m_window );
2907                         global_accel_connect_window( window );
2908                         g_posXZWnd.connect( window );
2909
2910                         m_pXZWnd = new XYWnd();
2911                         m_pXZWnd->m_parent = window;
2912                         m_pXZWnd->SetViewType( XZ );
2913
2914                         {
2915                                 GtkFrame* frame = create_framed_widget( m_pXZWnd->GetWidget() );
2916                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2917                         }
2918
2919                         XZ_Front_Shown_Construct( window );
2920
2921                         g_floating_windows.push_back( GTK_WIDGET( window ) );
2922                 }
2923
2924                 {
2925                         GtkWindow* window = create_persistent_floating_window( ViewType_getTitle( YZ ), m_window );
2926                         global_accel_connect_window( window );
2927                         g_posYZWnd.connect( window );
2928
2929                         m_pYZWnd = new XYWnd();
2930                         m_pYZWnd->m_parent = window;
2931                         m_pYZWnd->SetViewType( YZ );
2932
2933                         {
2934                                 GtkFrame* frame = create_framed_widget( m_pYZWnd->GetWidget() );
2935                                 gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
2936                         }
2937
2938                         YZ_Side_Shown_Construct( window );
2939
2940                         g_floating_windows.push_back( GTK_WIDGET( window ) );
2941                 }
2942
2943                 {
2944                         GtkFrame* frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
2945                         g_page_textures = GroupDialog_addPage( "Textures", GTK_WIDGET( frame ), TextureBrowserExportTitleCaller() );
2946                 }
2947
2948                 GroupDialog_show();
2949         }
2950         else // 4 way
2951         {
2952                 m_pCamWnd = NewCamWnd();
2953                 GlobalCamera_setCamWnd( *m_pCamWnd );
2954                 CamWnd_setParent( *m_pCamWnd, window );
2955
2956                 GtkWidget* camera = CamWnd_getWidget( *m_pCamWnd );
2957
2958                 m_pYZWnd = new XYWnd();
2959                 m_pYZWnd->SetViewType( YZ );
2960
2961                 GtkWidget* yz = m_pYZWnd->GetWidget();
2962
2963                 m_pXYWnd = new XYWnd();
2964                 m_pXYWnd->SetViewType( XY );
2965
2966                 GtkWidget* xy = m_pXYWnd->GetWidget();
2967
2968                 m_pXZWnd = new XYWnd();
2969                 m_pXZWnd->SetViewType( XZ );
2970
2971                 GtkWidget* xz = m_pXZWnd->GetWidget();
2972
2973                 GtkHPaned* split = create_split_views( camera, yz, xy, xz );
2974                 gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( split ), TRUE, TRUE, 0 );
2975
2976                 {
2977                         GtkFrame* frame = create_framed_widget( TextureBrowser_constructWindow( window ) );
2978                         g_page_textures = GroupDialog_addPage( "Textures", GTK_WIDGET( frame ), TextureBrowserExportTitleCaller() );
2979                 }
2980         }
2981
2982         EntityList_constructWindow( window );
2983         PreferencesDialog_constructWindow( window );
2984         FindTextureDialog_constructWindow( window );
2985         SurfaceInspector_constructWindow( window );
2986         PatchInspector_constructWindow( window );
2987
2988         SetActiveXY( m_pXYWnd );
2989
2990         AddGridChangeCallback( SetGridStatusCaller( *this ) );
2991         AddGridChangeCallback( ReferenceCaller<MainFrame, XY_UpdateAllWindows>( *this ) );
2992
2993         g_defaultToolMode = DragMode;
2994         g_defaultToolMode();
2995         SetStatusText( m_command_status, c_TranslateMode_status );
2996
2997         EverySecondTimer_enable();
2998
2999         //GlobalShortcuts_reportUnregistered();
3000 }
3001
3002 void MainFrame::SaveWindowInfo(){
3003         if ( !FloatingGroupDialog() ) {
3004                 g_layout_globals.nXYHeight = gtk_paned_get_position( GTK_PANED( m_vSplit ) );
3005
3006                 if ( CurrentStyle() != eRegular ) {
3007                         g_layout_globals.nCamWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
3008                 }
3009                 else
3010                 {
3011                         g_layout_globals.nXYWidth = gtk_paned_get_position( GTK_PANED( m_hSplit ) );
3012                 }
3013
3014                 g_layout_globals.nCamHeight = gtk_paned_get_position( GTK_PANED( m_vSplit2 ) );
3015         }
3016
3017         g_layout_globals.m_position = m_position_tracker.getPosition();
3018
3019         g_layout_globals.nState = gdk_window_get_state( GTK_WIDGET( m_window )->window );
3020 }
3021
3022 void MainFrame::Shutdown(){
3023         EverySecondTimer_disable();
3024
3025         EntityList_destroyWindow();
3026
3027         delete m_pXYWnd;
3028         m_pXYWnd = 0;
3029         delete m_pYZWnd;
3030         m_pYZWnd = 0;
3031         delete m_pXZWnd;
3032         m_pXZWnd = 0;
3033
3034         TextureBrowser_destroyWindow();
3035
3036         DeleteCamWnd( m_pCamWnd );
3037         m_pCamWnd = 0;
3038
3039         PreferencesDialog_destroyWindow();
3040         SurfaceInspector_destroyWindow();
3041         FindTextureDialog_destroyWindow();
3042         PatchInspector_destroyWindow();
3043
3044         g_DbgDlg.destroyWindow();
3045
3046         // destroying group-dialog last because it may contain texture-browser
3047         GroupDialog_destroyWindow();
3048 }
3049
3050 void MainFrame::RedrawStatusText(){
3051         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_command_status] ), m_command_status.c_str() );
3052         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_position_status] ), m_position_status.c_str() );
3053         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_brushcount_status] ), m_brushcount_status.c_str() );
3054         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_texture_status] ), m_texture_status.c_str() );
3055         gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_grid_status] ), m_grid_status.c_str() );
3056 }
3057
3058 void MainFrame::UpdateStatusText(){
3059         m_idleRedrawStatusText.queueDraw();
3060 }
3061
3062 void MainFrame::SetStatusText( CopiedString& status_text, const char* pText ){
3063         status_text = pText;
3064         UpdateStatusText();
3065 }
3066
3067 void Sys_Status( const char* status ){
3068         if ( g_pParentWnd != 0 ) {
3069                 g_pParentWnd->SetStatusText( g_pParentWnd->m_command_status, status );
3070         }
3071 }
3072
3073 int getRotateIncrement(){
3074         return static_cast<int>( g_si_globals.rotate );
3075 }
3076
3077 int getFarClipDistance(){
3078         return g_camwindow_globals.m_nCubicScale;
3079 }
3080
3081 float ( *GridStatus_getGridSize )() = GetGridSize;
3082 int ( *GridStatus_getRotateIncrement )() = getRotateIncrement;
3083 int ( *GridStatus_getFarClipDistance )() = getFarClipDistance;
3084 bool ( *GridStatus_getTextureLockEnabled )();
3085
3086 void MainFrame::SetGridStatus(){
3087         StringOutputStream status( 64 );
3088         const char* lock = ( GridStatus_getTextureLockEnabled() ) ? "ON" : "OFF";
3089         status << ( GetSnapGridSize() > 0 ? "G:" : "g:" ) << GridStatus_getGridSize()
3090                    << "  R:" << GridStatus_getRotateIncrement()
3091                    << "  C:" << GridStatus_getFarClipDistance()
3092                    << "  L:" << lock;
3093         SetStatusText( m_grid_status, status.c_str() );
3094 }
3095
3096 void GridStatus_onTextureLockEnabledChanged(){
3097         if ( g_pParentWnd != 0 ) {
3098                 g_pParentWnd->SetGridStatus();
3099         }
3100 }
3101
3102 void GlobalGL_sharedContextCreated(){
3103         GLFont *g_font = NULL;
3104
3105         // report OpenGL information
3106         globalOutputStream() << "GL_VENDOR: " << reinterpret_cast<const char*>( glGetString( GL_VENDOR ) ) << "\n";
3107         globalOutputStream() << "GL_RENDERER: " << reinterpret_cast<const char*>( glGetString( GL_RENDERER ) ) << "\n";
3108         globalOutputStream() << "GL_VERSION: " << reinterpret_cast<const char*>( glGetString( GL_VERSION ) ) << "\n";
3109         globalOutputStream() << "GL_EXTENSIONS: " << reinterpret_cast<const char*>( glGetString( GL_EXTENSIONS ) ) << "\n";
3110
3111         QGL_sharedContextCreated( GlobalOpenGL() );
3112
3113         ShaderCache_extensionsInitialised();
3114
3115         GlobalShaderCache().realise();
3116         Textures_Realise();
3117
3118 #ifdef WIN32
3119         /* win32 is dodgy here, just use courier new then */
3120         g_font = glfont_create( "arial 9" );
3121 #else
3122         GtkSettings *settings = gtk_settings_get_default();
3123         gchar *fontname;
3124         g_object_get( settings, "gtk-font-name", &fontname, NULL );
3125         g_font = glfont_create( fontname );
3126 #endif
3127
3128         GlobalOpenGL().m_font = g_font;
3129 }
3130
3131 void GlobalGL_sharedContextDestroyed(){
3132         Textures_Unrealise();
3133         GlobalShaderCache().unrealise();
3134
3135         QGL_sharedContextDestroyed( GlobalOpenGL() );
3136 }
3137
3138
3139 void Layout_constructPreferences( PreferencesPage& page ){
3140         {
3141                 const char* layouts[] = { "window1.bmp", "window2.bmp", "window3.bmp", "window4.bmp" };
3142                 page.appendRadioIcons(
3143                         "Window Layout",
3144                         STRING_ARRAY_RANGE( layouts ),
3145                         LatchedIntImportCaller( g_Layout_viewStyle ),
3146                         IntExportCaller( g_Layout_viewStyle.m_latched )
3147                         );
3148         }
3149         page.appendCheckBox(
3150                 "", "Detachable Menus",
3151                 LatchedBoolImportCaller( g_Layout_enableDetachableMenus ),
3152                 BoolExportCaller( g_Layout_enableDetachableMenus.m_latched )
3153                 );
3154         if ( !string_empty( g_pGameDescription->getKeyValue( "no_patch" ) ) ) {
3155                 page.appendCheckBox(
3156                         "", "Patch Toolbar",
3157                         LatchedBoolImportCaller( g_Layout_enablePatchToolbar ),
3158                         BoolExportCaller( g_Layout_enablePatchToolbar.m_latched )
3159                         );
3160         }
3161         page.appendCheckBox(
3162                 "", "Plugin Toolbar",
3163                 LatchedBoolImportCaller( g_Layout_enablePluginToolbar ),
3164                 BoolExportCaller( g_Layout_enablePluginToolbar.m_latched )
3165                 );
3166 }
3167
3168 void Layout_constructPage( PreferenceGroup& group ){
3169         PreferencesPage page( group.createPage( "Layout", "Layout Preferences" ) );
3170         Layout_constructPreferences( page );
3171 }
3172
3173 void Layout_registerPreferencesPage(){
3174         PreferencesDialog_addInterfacePage( FreeCaller1<PreferenceGroup&, Layout_constructPage>() );
3175 }
3176
3177
3178 #include "preferencesystem.h"
3179 #include "stringio.h"
3180
3181 void MainFrame_Construct(){
3182         GlobalCommands_insert( "OpenManual", FreeCaller<OpenHelpURL>(), Accelerator( GDK_F1 ) );
3183
3184         GlobalCommands_insert( "Sleep", FreeCaller<thunk_OnSleep>(), Accelerator( 'P', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
3185         GlobalCommands_insert( "NewMap", FreeCaller<NewMap>() );
3186         GlobalCommands_insert( "OpenMap", FreeCaller<OpenMap>(), Accelerator( 'O', (GdkModifierType)GDK_CONTROL_MASK ) );
3187         GlobalCommands_insert( "ImportMap", FreeCaller<ImportMap>() );
3188         GlobalCommands_insert( "SaveMap", FreeCaller<SaveMap>(), Accelerator( 'S', (GdkModifierType)GDK_CONTROL_MASK ) );
3189         GlobalCommands_insert( "SaveMapAs", FreeCaller<SaveMapAs>() );
3190         GlobalCommands_insert( "SaveSelected", FreeCaller<ExportMap>() );
3191         GlobalCommands_insert( "SaveRegion", FreeCaller<SaveRegion>() );
3192         GlobalCommands_insert( "RefreshReferences", FreeCaller<RefreshReferences>() );
3193         GlobalCommands_insert( "ProjectSettings", FreeCaller<DoProjectSettings>() );
3194         GlobalCommands_insert( "CheckForUpdate", FreeCaller<OpenUpdateURL>() );
3195         GlobalCommands_insert( "Exit", FreeCaller<Exit>() );
3196
3197         GlobalCommands_insert( "Undo", FreeCaller<Undo>(), Accelerator( 'Z', (GdkModifierType)GDK_CONTROL_MASK ) );
3198         GlobalCommands_insert( "Redo", FreeCaller<Redo>(), Accelerator( 'Y', (GdkModifierType)GDK_CONTROL_MASK ) );
3199         GlobalCommands_insert( "Copy", FreeCaller<Copy>(), Accelerator( 'C', (GdkModifierType)GDK_CONTROL_MASK ) );
3200         GlobalCommands_insert( "Paste", FreeCaller<Paste>(), Accelerator( 'V', (GdkModifierType)GDK_CONTROL_MASK ) );
3201         GlobalCommands_insert( "PasteToCamera", FreeCaller<PasteToCamera>(), Accelerator( 'V', (GdkModifierType)GDK_MOD1_MASK ) );
3202         GlobalCommands_insert( "CloneSelection", FreeCaller<Selection_Clone>(), Accelerator( GDK_space ) );
3203         GlobalCommands_insert( "CloneSelectionAndMakeUnique", FreeCaller<Selection_Clone_MakeUnique>(), Accelerator( GDK_space, (GdkModifierType)GDK_SHIFT_MASK ) );
3204         GlobalCommands_insert( "DeleteSelection", FreeCaller<deleteSelection>(), Accelerator( GDK_BackSpace ) );
3205         GlobalCommands_insert( "ParentSelection", FreeCaller<Scene_parentSelected>() );
3206         GlobalCommands_insert( "UnSelectSelection", FreeCaller<Selection_Deselect>(), Accelerator( GDK_Escape ) );
3207         GlobalCommands_insert( "InvertSelection", FreeCaller<Select_Invert>(), Accelerator( 'I' ) );
3208         GlobalCommands_insert( "SelectInside", FreeCaller<Select_Inside>() );
3209         GlobalCommands_insert( "SelectTouching", FreeCaller<Select_Touching>() );
3210         GlobalCommands_insert( "ExpandSelectionToEntities", FreeCaller<Scene_ExpandSelectionToEntities>(), Accelerator( 'E', (GdkModifierType)( GDK_MOD1_MASK | GDK_CONTROL_MASK ) ) );
3211         GlobalCommands_insert( "Preferences", FreeCaller<PreferencesDialog_showDialog>(), Accelerator( 'P' ) );
3212
3213         GlobalCommands_insert( "ToggleConsole", FreeCaller<Console_ToggleShow>(), Accelerator( 'O' ) );
3214         GlobalCommands_insert( "ToggleEntityInspector", FreeCaller<EntityInspector_ToggleShow>(), Accelerator( 'N' ) );
3215         GlobalCommands_insert( "EntityList", FreeCaller<EntityList_toggleShown>(), Accelerator( 'L' ) );
3216
3217         GlobalCommands_insert( "ShowHidden", FreeCaller<Select_ShowAllHidden>(), Accelerator( 'H', (GdkModifierType)GDK_SHIFT_MASK ) );
3218         GlobalCommands_insert( "HideSelected", FreeCaller<HideSelected>(), Accelerator( 'H' ) );
3219
3220         GlobalToggles_insert( "DragVertices", FreeCaller<SelectVertexMode>(), ToggleItem::AddCallbackCaller( g_vertexMode_button ), Accelerator( 'V' ) );
3221         GlobalToggles_insert( "DragEdges", FreeCaller<SelectEdgeMode>(), ToggleItem::AddCallbackCaller( g_edgeMode_button ), Accelerator( 'E' ) );
3222         GlobalToggles_insert( "DragFaces", FreeCaller<SelectFaceMode>(), ToggleItem::AddCallbackCaller( g_faceMode_button ), Accelerator( 'F' ) );
3223
3224         GlobalCommands_insert( "MirrorSelectionX", FreeCaller<Selection_Flipx>() );
3225         GlobalCommands_insert( "RotateSelectionX", FreeCaller<Selection_Rotatex>() );
3226         GlobalCommands_insert( "MirrorSelectionY", FreeCaller<Selection_Flipy>() );
3227         GlobalCommands_insert( "RotateSelectionY", FreeCaller<Selection_Rotatey>() );
3228         GlobalCommands_insert( "MirrorSelectionZ", FreeCaller<Selection_Flipz>() );
3229         GlobalCommands_insert( "RotateSelectionZ", FreeCaller<Selection_Rotatez>() );
3230
3231         GlobalCommands_insert( "ArbitraryRotation", FreeCaller<DoRotateDlg>() );
3232         GlobalCommands_insert( "ArbitraryScale", FreeCaller<DoScaleDlg>() );
3233
3234         GlobalCommands_insert( "BuildMenuCustomize", FreeCaller<DoBuildMenu>() );
3235
3236         GlobalCommands_insert( "FindBrush", FreeCaller<DoFind>() );
3237
3238         GlobalCommands_insert( "MapInfo", FreeCaller<DoMapInfo>(), Accelerator( 'M' ) );
3239
3240
3241         GlobalToggles_insert( "ToggleClipper", FreeCaller<ClipperMode>(), ToggleItem::AddCallbackCaller( g_clipper_button ), Accelerator( 'X' ) );
3242
3243         GlobalToggles_insert( "MouseTranslate", FreeCaller<TranslateMode>(), ToggleItem::AddCallbackCaller( g_translatemode_button ), Accelerator( 'W' ) );
3244         GlobalToggles_insert( "MouseRotate", FreeCaller<RotateMode>(), ToggleItem::AddCallbackCaller( g_rotatemode_button ), Accelerator( 'R' ) );
3245         GlobalToggles_insert( "MouseScale", FreeCaller<ScaleMode>(), ToggleItem::AddCallbackCaller( g_scalemode_button ) );
3246         GlobalToggles_insert( "MouseDrag", FreeCaller<DragMode>(), ToggleItem::AddCallbackCaller( g_dragmode_button ), Accelerator( 'Q' ) );
3247
3248         GlobalCommands_insert( "ColorSchemeOriginal", FreeCaller<ColorScheme_Original>() );
3249         GlobalCommands_insert( "ColorSchemeQER", FreeCaller<ColorScheme_QER>() );
3250         GlobalCommands_insert( "ColorSchemeBlackAndGreen", FreeCaller<ColorScheme_Black>() );
3251         GlobalCommands_insert( "ColorSchemeYdnar", FreeCaller<ColorScheme_Ydnar>() );
3252         GlobalCommands_insert( "ChooseTextureBackgroundColor", makeCallback( g_ColoursMenu.m_textureback ) );
3253         GlobalCommands_insert( "ChooseGridBackgroundColor", makeCallback( g_ColoursMenu.m_xyback ) );
3254         GlobalCommands_insert( "ChooseGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor ) );
3255         GlobalCommands_insert( "ChooseGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor ) );
3256         GlobalCommands_insert( "ChooseSmallGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor_alt ) );
3257         GlobalCommands_insert( "ChooseSmallGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor_alt ) );
3258         GlobalCommands_insert( "ChooseGridTextColor", makeCallback( g_ColoursMenu.m_gridtext ) );
3259         GlobalCommands_insert( "ChooseGridBlockColor", makeCallback( g_ColoursMenu.m_gridblock ) );
3260         GlobalCommands_insert( "ChooseBrushColor", makeCallback( g_ColoursMenu.m_brush ) );
3261         GlobalCommands_insert( "ChooseCameraBackgroundColor", makeCallback( g_ColoursMenu.m_cameraback ) );
3262         GlobalCommands_insert( "ChooseSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush ) );
3263         GlobalCommands_insert( "ChooseCameraSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush3d ) );
3264         GlobalCommands_insert( "ChooseClipperColor", makeCallback( g_ColoursMenu.m_clipper ) );
3265         GlobalCommands_insert( "ChooseOrthoViewNameColor", makeCallback( g_ColoursMenu.m_viewname ) );
3266
3267
3268         GlobalCommands_insert( "CSGSubtract", FreeCaller<CSG_Subtract>(), Accelerator( 'U', (GdkModifierType)GDK_SHIFT_MASK ) );
3269         GlobalCommands_insert( "CSGMerge", FreeCaller<CSG_Merge>(), Accelerator( 'U', (GdkModifierType)GDK_CONTROL_MASK ) );
3270         GlobalCommands_insert( "CSGHollow", FreeCaller<CSG_MakeHollow>() );
3271
3272         Grid_registerCommands();
3273
3274         GlobalCommands_insert( "SnapToGrid", FreeCaller<Selection_SnapToGrid>(), Accelerator( 'G', (GdkModifierType)GDK_CONTROL_MASK ) );
3275
3276         GlobalCommands_insert( "SelectAllOfType", FreeCaller<Select_AllOfType>(), Accelerator( 'A', (GdkModifierType)GDK_SHIFT_MASK ) );
3277
3278         GlobalCommands_insert( "TexRotateClock", FreeCaller<Texdef_RotateClockwise>(), Accelerator( GDK_Next, (GdkModifierType)GDK_SHIFT_MASK ) );
3279         GlobalCommands_insert( "TexRotateCounter", FreeCaller<Texdef_RotateAntiClockwise>(), Accelerator( GDK_Prior, (GdkModifierType)GDK_SHIFT_MASK ) );
3280         GlobalCommands_insert( "TexScaleUp", FreeCaller<Texdef_ScaleUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_CONTROL_MASK ) );
3281         GlobalCommands_insert( "TexScaleDown", FreeCaller<Texdef_ScaleDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_CONTROL_MASK ) );
3282         GlobalCommands_insert( "TexScaleLeft", FreeCaller<Texdef_ScaleLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_CONTROL_MASK ) );
3283         GlobalCommands_insert( "TexScaleRight", FreeCaller<Texdef_ScaleRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_CONTROL_MASK ) );
3284         GlobalCommands_insert( "TexShiftUp", FreeCaller<Texdef_ShiftUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_SHIFT_MASK ) );
3285         GlobalCommands_insert( "TexShiftDown", FreeCaller<Texdef_ShiftDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_SHIFT_MASK ) );
3286         GlobalCommands_insert( "TexShiftLeft", FreeCaller<Texdef_ShiftLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_SHIFT_MASK ) );
3287         GlobalCommands_insert( "TexShiftRight", FreeCaller<Texdef_ShiftRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_SHIFT_MASK ) );
3288
3289         GlobalCommands_insert( "MoveSelectionDOWN", FreeCaller<Selection_MoveDown>(), Accelerator( GDK_KP_Subtract ) );
3290         GlobalCommands_insert( "MoveSelectionUP", FreeCaller<Selection_MoveUp>(), Accelerator( GDK_KP_Add ) );
3291
3292         GlobalCommands_insert( "SelectNudgeLeft", FreeCaller<Selection_NudgeLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_MOD1_MASK ) );
3293         GlobalCommands_insert( "SelectNudgeRight", FreeCaller<Selection_NudgeRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_MOD1_MASK ) );
3294         GlobalCommands_insert( "SelectNudgeUp", FreeCaller<Selection_NudgeUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_MOD1_MASK ) );
3295         GlobalCommands_insert( "SelectNudgeDown", FreeCaller<Selection_NudgeDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_MOD1_MASK ) );
3296
3297         Patch_registerCommands();
3298         XYShow_registerCommands();
3299
3300         typedef FreeCaller1<const Selectable&, ComponentMode_SelectionChanged> ComponentModeSelectionChangedCaller;
3301         GlobalSelectionSystem().addSelectionChangeCallback( ComponentModeSelectionChangedCaller() );
3302
3303         GlobalPreferenceSystem().registerPreference( "DetachableMenus", BoolImportStringCaller( g_Layout_enableDetachableMenus.m_latched ), BoolExportStringCaller( g_Layout_enableDetachableMenus.m_latched ) );
3304         GlobalPreferenceSystem().registerPreference( "PatchToolBar", BoolImportStringCaller( g_Layout_enablePatchToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePatchToolbar.m_latched ) );
3305         GlobalPreferenceSystem().registerPreference( "PluginToolBar", BoolImportStringCaller( g_Layout_enablePluginToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePluginToolbar.m_latched ) );
3306         GlobalPreferenceSystem().registerPreference( "QE4StyleWindows", IntImportStringCaller( g_Layout_viewStyle.m_latched ), IntExportStringCaller( g_Layout_viewStyle.m_latched ) );
3307         GlobalPreferenceSystem().registerPreference( "XYHeight", IntImportStringCaller( g_layout_globals.nXYHeight ), IntExportStringCaller( g_layout_globals.nXYHeight ) );
3308         GlobalPreferenceSystem().registerPreference( "XYWidth", IntImportStringCaller( g_layout_globals.nXYWidth ), IntExportStringCaller( g_layout_globals.nXYWidth ) );
3309         GlobalPreferenceSystem().registerPreference( "CamWidth", IntImportStringCaller( g_layout_globals.nCamWidth ), IntExportStringCaller( g_layout_globals.nCamWidth ) );
3310         GlobalPreferenceSystem().registerPreference( "CamHeight", IntImportStringCaller( g_layout_globals.nCamHeight ), IntExportStringCaller( g_layout_globals.nCamHeight ) );
3311
3312         GlobalPreferenceSystem().registerPreference( "State", IntImportStringCaller( g_layout_globals.nState ), IntExportStringCaller( g_layout_globals.nState ) );
3313         GlobalPreferenceSystem().registerPreference( "PositionX", IntImportStringCaller( g_layout_globals.m_position.x ), IntExportStringCaller( g_layout_globals.m_position.x ) );
3314         GlobalPreferenceSystem().registerPreference( "PositionY", IntImportStringCaller( g_layout_globals.m_position.y ), IntExportStringCaller( g_layout_globals.m_position.y ) );
3315         GlobalPreferenceSystem().registerPreference( "Width", IntImportStringCaller( g_layout_globals.m_position.w ), IntExportStringCaller( g_layout_globals.m_position.w ) );
3316         GlobalPreferenceSystem().registerPreference( "Height", IntImportStringCaller( g_layout_globals.m_position.h ), IntExportStringCaller( g_layout_globals.m_position.h ) );
3317
3318         GlobalPreferenceSystem().registerPreference( "CamWnd", WindowPositionTrackerImportStringCaller( g_posCamWnd ), WindowPositionTrackerExportStringCaller( g_posCamWnd ) );
3319         GlobalPreferenceSystem().registerPreference( "XYWnd", WindowPositionTrackerImportStringCaller( g_posXYWnd ), WindowPositionTrackerExportStringCaller( g_posXYWnd ) );
3320         GlobalPreferenceSystem().registerPreference( "YZWnd", WindowPositionTrackerImportStringCaller( g_posYZWnd ), WindowPositionTrackerExportStringCaller( g_posYZWnd ) );
3321         GlobalPreferenceSystem().registerPreference( "XZWnd", WindowPositionTrackerImportStringCaller( g_posXZWnd ), WindowPositionTrackerExportStringCaller( g_posXZWnd ) );
3322
3323         {
3324                 const char* ENGINEPATH_ATTRIBUTE =
3325 #if defined( WIN32 )
3326                         "enginepath_win32"
3327 #elif defined( __linux__ ) || defined ( __FreeBSD__ )
3328                         "enginepath_linux"
3329 #elif defined( __APPLE__ )
3330                         "enginepath_macos"
3331 #else
3332 #error "unknown platform"
3333 #endif
3334                 ;
3335                 StringOutputStream path( 256 );
3336                 path << DirectoryCleaned( g_pGameDescription->getRequiredKeyValue( ENGINEPATH_ATTRIBUTE ) );
3337                 g_strEnginePath = path.c_str();
3338         }
3339
3340         GlobalPreferenceSystem().registerPreference( "EnginePath", CopiedStringImportStringCaller( g_strEnginePath ), CopiedStringExportStringCaller( g_strEnginePath ) );
3341
3342         g_Layout_viewStyle.useLatched();
3343         g_Layout_enableDetachableMenus.useLatched();
3344         g_Layout_enablePatchToolbar.useLatched();
3345         g_Layout_enablePluginToolbar.useLatched();
3346
3347         Layout_registerPreferencesPage();
3348         Paths_registerPreferencesPage();
3349
3350         g_brushCount.setCountChangedCallback( FreeCaller<QE_brushCountChanged>() );
3351         g_entityCount.setCountChangedCallback( FreeCaller<QE_entityCountChanged>() );
3352         GlobalEntityCreator().setCounter( &g_entityCount );
3353
3354         GLWidget_sharedContextCreated = GlobalGL_sharedContextCreated;
3355         GLWidget_sharedContextDestroyed = GlobalGL_sharedContextDestroyed;
3356
3357         GlobalEntityClassManager().attach( g_WorldspawnColourEntityClassObserver );
3358 }
3359
3360 void MainFrame_Destroy(){
3361         GlobalEntityClassManager().detach( g_WorldspawnColourEntityClassObserver );
3362
3363         GlobalEntityCreator().setCounter( 0 );
3364         g_entityCount.setCountChangedCallback( Callback() );
3365         g_brushCount.setCountChangedCallback( Callback() );
3366 }
3367
3368
3369 void GLWindow_Construct(){
3370         GlobalPreferenceSystem().registerPreference( "MouseButtons", IntImportStringCaller( g_glwindow_globals.m_nMouseType ), IntExportStringCaller( g_glwindow_globals.m_nMouseType ) );
3371 }
3372
3373 void GLWindow_Destroy(){
3374 }