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