]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/mainframe.cpp
Hack around segfault at launch, patch from danfe: https://github.com/TTimo/GtkRadiant...
[xonotic/netradiant.git] / radiant / mainframe.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // Main Window for Q3Radiant
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "mainframe.h"
29
30 #include "debugging/debugging.h"
31 #include "version.h"
32
33 #include "ifilesystem.h"
34 #include "iundo.h"
35 #include "ifilter.h"
36 #include "itoolbar.h"
37 #include "editable.h"
38 #include "ientity.h"
39 #include "ishaders.h"
40 #include "igl.h"
41 #include "moduleobserver.h"
42
43 #include <ctime>
44
45 #include <gdk/gdkkeysyms.h>
46 #include <gtk/gtkhbox.h>
47 #include <gtk/gtkvbox.h>
48 #include <gtk/gtkframe.h>
49 #include <gtk/gtklabel.h>
50 #include <gtk/gtkhpaned.h>
51 #include <gtk/gtkvpaned.h>
52 #include <gtk/gtktoolbar.h>
53 #include <gtk/gtkmenubar.h>
54 #include <gtk/gtkimage.h>
55 #include <gtk/gtktable.h>
56
57
58 #include "cmdlib.h"
59 #include "scenelib.h"
60 #include "stream/stringstream.h"
61 #include "signal/isignal.h"
62 #include "os/path.h"
63 #include "os/file.h"
64 #include "eclasslib.h"
65 #include "moduleobservers.h"
66
67 #include "gtkutil/clipboard.h"
68 #include "gtkutil/container.h"
69 #include "gtkutil/frame.h"
70 #include "gtkutil/glfont.h"
71 #include "gtkutil/glwidget.h"
72 #include "gtkutil/image.h"
73 #include "gtkutil/menu.h"
74 #include "gtkutil/paned.h"
75 #include "gtkutil/widget.h"
76
77 #include "autosave.h"
78 #include "build.h"
79 #include "brushmanip.h"
80 #include "brushmodule.h"
81 #include "camwindow.h"
82 #include "csg.h"
83 #include "commands.h"
84 #include "console.h"
85 #include "entity.h"
86 #include "entityinspector.h"
87 #include "entitylist.h"
88 #include "filters.h"
89 #include "findtexturedialog.h"
90 #include "grid.h"
91 #include "groupdialog.h"
92 #include "gtkdlgs.h"
93 #include "gtkmisc.h"
94 #include "help.h"
95 #include "map.h"
96 #include "mru.h"
97 #include "multimon.h"
98 #include "patchdialog.h"
99 #include "patchmanip.h"
100 #include "plugin.h"
101 #include "pluginmanager.h"
102 #include "pluginmenu.h"
103 #include "plugintoolbar.h"
104 #include "points.h"
105 #include "preferences.h"
106 #include "qe3.h"
107 #include "qgl.h"
108 #include "select.h"
109 #include "server.h"
110 #include "surfacedialog.h"
111 #include "textures.h"
112 #include "texwindow.h"
113 #include "url.h"
114 #include "xywindow.h"
115 #include "windowobservers.h"
116 #include "renderstate.h"
117 #include "feedback.h"
118 #include "referencecache.h"
119
120
121
122 struct layout_globals_t
123 {
124         WindowPosition m_position;
125
126
127         int nXYHeight;
128         int nXYWidth;
129         int nCamWidth;
130         int nCamHeight;
131         int nState;
132
133         layout_globals_t() :
134                 m_position( -1, -1, 640, 480 ),
135
136                 nXYHeight( 300 ),
137                 nXYWidth( 300 ),
138                 nCamWidth( 200 ),
139                 nCamHeight( 200 ),
140                 nState( GDK_WINDOW_STATE_MAXIMIZED ){
141         }
142 };
143
144 layout_globals_t g_layout_globals;
145 glwindow_globals_t g_glwindow_globals;
146
147
148 // VFS
149 class VFSModuleObserver : public ModuleObserver
150 {
151 std::size_t m_unrealised;
152 public:
153 VFSModuleObserver() : m_unrealised( 1 ){
154 }
155 void realise(){
156         if ( --m_unrealised == 0 ) {
157                 QE_InitVFS();
158                 GlobalFileSystem().initialise();
159         }
160 }
161 void unrealise(){
162         if ( ++m_unrealised == 1 ) {
163                 GlobalFileSystem().shutdown();
164         }
165 }
166 };
167
168 VFSModuleObserver g_VFSModuleObserver;
169
170 void VFS_Construct(){
171         Radiant_attachHomePathsObserver( g_VFSModuleObserver );
172 }
173 void VFS_Destroy(){
174         Radiant_detachHomePathsObserver( g_VFSModuleObserver );
175 }
176
177 // Home Paths
178
179 #ifdef WIN32
180 #include <shlobj.h>
181 #include <objbase.h>
182 const GUID qFOLDERID_SavedGames = {0x4C5C32FF, 0xBB9D, 0x43b0, {0xB5, 0xB4, 0x2D, 0x72, 0xE5, 0x4E, 0xAA, 0xA4}};
183 #define qREFKNOWNFOLDERID GUID
184 #define qKF_FLAG_CREATE 0x8000
185 #define qKF_FLAG_NO_ALIAS 0x1000
186 typedef HRESULT ( WINAPI qSHGetKnownFolderPath_t )( qREFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath );
187 static qSHGetKnownFolderPath_t *qSHGetKnownFolderPath;
188 #endif
189 void HomePaths_Realise(){
190         do
191         {
192                 const char* prefix = g_pGameDescription->getKeyValue( "prefix" );
193                 if ( !string_empty( prefix ) ) {
194                         StringOutputStream path( 256 );
195
196 #if defined( __APPLE__ )
197                         path.clear();
198                         path << DirectoryCleaned( g_get_home_dir() ) << "Library/Application Support" << ( prefix + 1 ) << "/";
199                         if ( file_is_directory( path.c_str() ) ) {
200                                 g_qeglobals.m_userEnginePath = path.c_str();
201                                 break;
202                         }
203                         path.clear();
204                         path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
205 #endif
206
207 #if defined( WIN32 )
208                         TCHAR mydocsdir[MAX_PATH + 1];
209                         wchar_t *mydocsdirw;
210                         HMODULE shfolder = LoadLibrary( "shfolder.dll" );
211                         if ( shfolder ) {
212                                 qSHGetKnownFolderPath = (qSHGetKnownFolderPath_t *) GetProcAddress( shfolder, "SHGetKnownFolderPath" );
213                         }
214                         else{
215                                 qSHGetKnownFolderPath = NULL;
216                         }
217                         CoInitializeEx( NULL, COINIT_APARTMENTTHREADED );
218                         if ( qSHGetKnownFolderPath && qSHGetKnownFolderPath( qFOLDERID_SavedGames, qKF_FLAG_CREATE | qKF_FLAG_NO_ALIAS, NULL, &mydocsdirw ) == S_OK ) {
219                                 memset( mydocsdir, 0, sizeof( mydocsdir ) );
220                                 wcstombs( mydocsdir, mydocsdirw, sizeof( mydocsdir ) - 1 );
221                                 CoTaskMemFree( mydocsdirw );
222                                 path.clear();
223                                 path << DirectoryCleaned( mydocsdir ) << ( prefix + 1 ) << "/";
224                                 if ( file_is_directory( path.c_str() ) ) {
225                                         g_qeglobals.m_userEnginePath = path.c_str();
226                                         CoUninitialize();
227                                         FreeLibrary( shfolder );
228                                         break;
229                                 }
230                         }
231                         CoUninitialize();
232                         if ( shfolder ) {
233                                 FreeLibrary( shfolder );
234                         }
235                         if ( SHGetFolderPath( NULL, CSIDL_PERSONAL, NULL, 0, mydocsdir ) ) {
236                                 path.clear();
237                                 path << DirectoryCleaned( mydocsdir ) << "My Games/" << ( prefix + 1 ) << "/";
238                                 // win32: only add it if it already exists
239                                 if ( file_is_directory( path.c_str() ) ) {
240                                         g_qeglobals.m_userEnginePath = path.c_str();
241                                         break;
242                                 }
243                         }
244 #endif
245
246 #if defined( POSIX )
247                         path.clear();
248                         path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
249                         g_qeglobals.m_userEnginePath = path.c_str();
250                         break;
251 #endif
252                 }
253
254                 g_qeglobals.m_userEnginePath = EnginePath_get();
255         }
256         while ( 0 );
257
258         Q_mkdir( g_qeglobals.m_userEnginePath.c_str() );
259
260         {
261                 StringOutputStream path( 256 );
262                 path << g_qeglobals.m_userEnginePath.c_str() << gamename_get() << '/';
263                 g_qeglobals.m_userGamePath = path.c_str();
264         }
265         ASSERT_MESSAGE( !string_empty( g_qeglobals.m_userGamePath.c_str() ), "HomePaths_Realise: user-game-path is empty" );
266         Q_mkdir( g_qeglobals.m_userGamePath.c_str() );
267 }
268
269 ModuleObservers g_homePathObservers;
270
271 void Radiant_attachHomePathsObserver( ModuleObserver& observer ){
272         g_homePathObservers.attach( observer );
273 }
274
275 void Radiant_detachHomePathsObserver( ModuleObserver& observer ){
276         g_homePathObservers.detach( observer );
277 }
278
279 class HomePathsModuleObserver : public ModuleObserver
280 {
281 std::size_t m_unrealised;
282 public:
283 HomePathsModuleObserver() : m_unrealised( 1 ){
284 }
285 void realise(){
286         if ( --m_unrealised == 0 ) {
287                 HomePaths_Realise();
288                 g_homePathObservers.realise();
289         }
290 }
291 void unrealise(){
292         if ( ++m_unrealised == 1 ) {
293                 g_homePathObservers.unrealise();
294         }
295 }
296 };
297
298 HomePathsModuleObserver g_HomePathsModuleObserver;
299
300 void HomePaths_Construct(){
301         Radiant_attachEnginePathObserver( g_HomePathsModuleObserver );
302 }
303 void HomePaths_Destroy(){
304         Radiant_detachEnginePathObserver( g_HomePathsModuleObserver );
305 }
306
307
308 // Engine Path
309
310 CopiedString g_strEnginePath;
311 ModuleObservers g_enginePathObservers;
312 std::size_t g_enginepath_unrealised = 1;
313
314 void Radiant_attachEnginePathObserver( ModuleObserver& observer ){
315         g_enginePathObservers.attach( observer );
316 }
317
318 void Radiant_detachEnginePathObserver( ModuleObserver& observer ){
319         g_enginePathObservers.detach( observer );
320 }
321
322
323 void EnginePath_Realise(){
324         if ( --g_enginepath_unrealised == 0 ) {
325                 g_enginePathObservers.realise();
326         }
327 }
328
329
330 const char* EnginePath_get(){
331         ASSERT_MESSAGE( g_enginepath_unrealised == 0, "EnginePath_get: engine path not realised" );
332         return g_strEnginePath.c_str();
333 }
334
335 void EnginePath_Unrealise(){
336         if ( ++g_enginepath_unrealised == 1 ) {
337                 g_enginePathObservers.unrealise();
338         }
339 }
340
341 void setEnginePath( const char* path ){
342         StringOutputStream buffer( 256 );
343         buffer << DirectoryCleaned( path );
344         if ( !path_equal( buffer.c_str(), g_strEnginePath.c_str() ) ) {
345 #if 0
346                 while ( !ConfirmModified( "Paths Changed" ) )
347                 {
348                         if ( Map_Unnamed( g_map ) ) {
349                                 Map_SaveAs();
350                         }
351                         else
352                         {
353                                 Map_Save();
354                         }
355                 }
356                 Map_RegionOff();
357 #endif
358
359                 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Changing Engine Path" );
360
361                 EnginePath_Unrealise();
362
363                 g_strEnginePath = buffer.c_str();
364
365                 EnginePath_Realise();
366         }
367 }
368
369
370 // App Path
371
372 CopiedString g_strAppPath;                 ///< holds the full path of the executable
373
374 const char* AppPath_get(){
375         return g_strAppPath.c_str();
376 }
377
378 /// the path to the local rc-dir
379 const char* LocalRcPath_get( void ){
380         static CopiedString rc_path;
381         if ( rc_path.empty() ) {
382                 StringOutputStream stream( 256 );
383                 stream << GlobalRadiant().getSettingsPath() << g_pGameDescription->mGameFile.c_str() << "/";
384                 rc_path = stream.c_str();
385         }
386         return rc_path.c_str();
387 }
388
389 /// directory for temp files
390 /// NOTE: on *nix this is were we check for .pid
391 CopiedString g_strSettingsPath;
392 const char* SettingsPath_get(){
393         return g_strSettingsPath.c_str();
394 }
395
396
397 /*!
398    points to the game tools directory, for instance
399    C:/Program Files/Quake III Arena/GtkRadiant
400    (or other games)
401    this is one of the main variables that are configured by the game selection on startup
402    [GameToolsPath]/plugins
403    [GameToolsPath]/modules
404    and also q3map, bspc
405  */
406 CopiedString g_strGameToolsPath;           ///< this is set by g_GamesDialog
407
408 const char* GameToolsPath_get(){
409         return g_strGameToolsPath.c_str();
410 }
411
412 void EnginePathImport( CopiedString& self, const char* value ){
413         setEnginePath( value );
414 }
415 typedef ReferenceCaller1<CopiedString, const char*, EnginePathImport> EnginePathImportCaller;
416
417 void Paths_constructPreferences( PreferencesPage& page ){
418         page.appendPathEntry( "Engine Path", true,
419                                                   StringImportCallback( EnginePathImportCaller( g_strEnginePath ) ),
420                                                   StringExportCallback( StringExportCaller( g_strEnginePath ) )
421                                                   );
422 }
423 void Paths_constructPage( PreferenceGroup& group ){
424         PreferencesPage page( group.createPage( "Paths", "Path Settings" ) );
425         Paths_constructPreferences( page );
426 }
427 void Paths_registerPreferencesPage(){
428         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Paths_constructPage>() );
429 }
430
431
432 class PathsDialog : public Dialog
433 {
434 public:
435 GtkWindow* BuildDialog(){
436         GtkFrame* frame = create_dialog_frame( "Path settings", GTK_SHADOW_ETCHED_IN );
437
438         GtkVBox* vbox2 = create_dialog_vbox( 0, 4 );
439         gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( vbox2 ) );
440
441         {
442                 PreferencesPage preferencesPage( *this, GTK_WIDGET( vbox2 ) );
443                 Paths_constructPreferences( preferencesPage );
444         }
445
446         return create_simple_modal_dialog_window( "Engine Path Not Found", m_modal, GTK_WIDGET( frame ) );
447 }
448 };
449
450 PathsDialog g_PathsDialog;
451
452 void EnginePath_verify(){
453         if ( !file_exists( g_strEnginePath.c_str() ) ) {
454                 g_PathsDialog.Create();
455                 g_PathsDialog.DoModal();
456                 g_PathsDialog.Destroy();
457         }
458 }
459
460 namespace
461 {
462 CopiedString g_gamename;
463 CopiedString g_gamemode;
464 ModuleObservers g_gameNameObservers;
465 ModuleObservers g_gameModeObservers;
466 }
467
468 void Radiant_attachGameNameObserver( ModuleObserver& observer ){
469         g_gameNameObservers.attach( observer );
470 }
471
472 void Radiant_detachGameNameObserver( ModuleObserver& observer ){
473         g_gameNameObservers.detach( observer );
474 }
475
476 const char* basegame_get(){
477         return g_pGameDescription->getRequiredKeyValue( "basegame" );
478 }
479
480 const char* gamename_get(){
481         const char* gamename = g_gamename.c_str();
482         if ( string_empty( gamename ) ) {
483                 return basegame_get();
484         }
485         return gamename;
486 }
487
488 void gamename_set( const char* gamename ){
489         if ( !string_equal( gamename, g_gamename.c_str() ) ) {
490                 g_gameNameObservers.unrealise();
491                 g_gamename = gamename;
492                 g_gameNameObservers.realise();
493         }
494 }
495
496 void Radiant_attachGameModeObserver( ModuleObserver& observer ){
497         g_gameModeObservers.attach( observer );
498 }
499
500 void Radiant_detachGameModeObserver( ModuleObserver& observer ){
501         g_gameModeObservers.detach( observer );
502 }
503
504 const char* gamemode_get(){
505         return g_gamemode.c_str();
506 }
507
508 void gamemode_set( const char* gamemode ){
509         if ( !string_equal( gamemode, g_gamemode.c_str() ) ) {
510                 g_gameModeObservers.unrealise();
511                 g_gamemode = gamemode;
512                 g_gameModeObservers.realise();
513         }
514 }
515
516 #include "os/dir.h"
517
518 class CLoadModule
519 {
520 const char* m_path;
521 public:
522 CLoadModule( const char* path ) : m_path( path ){
523 }
524 void operator()( const char* name ) const {
525         char fullname[1024];
526         ASSERT_MESSAGE( strlen( m_path ) + strlen( name ) < 1024, "" );
527         strcpy( fullname, m_path );
528         strcat( fullname, name );
529         globalOutputStream() << "Found '" << fullname << "'\n";
530         GlobalModuleServer_loadModule( fullname );
531 }
532 };
533
534 const char* const c_library_extension =
535 #if defined( WIN32 )
536         "dll"
537 #elif defined ( __APPLE__ )
538         "dylib"
539 #elif defined( __linux__ ) || defined ( __FreeBSD__ )
540         "so"
541 #endif
542 ;
543
544 void Radiant_loadModules( const char* path ){
545         Directory_forEach( path, MatchFileExtension<CLoadModule>( c_library_extension, CLoadModule( path ) ) );
546 }
547
548 void Radiant_loadModulesFromRoot( const char* directory ){
549         {
550                 StringOutputStream path( 256 );
551                 path << directory << g_pluginsDir;
552                 Radiant_loadModules( path.c_str() );
553         }
554
555         if ( !string_equal( g_pluginsDir, g_modulesDir ) ) {
556                 StringOutputStream path( 256 );
557                 path << directory << g_modulesDir;
558                 Radiant_loadModules( path.c_str() );
559         }
560 }
561
562 //! Make COLOR_BRUSHES override worldspawn eclass colour.
563 void SetWorldspawnColour( const Vector3& colour ){
564         EntityClass* worldspawn = GlobalEntityClassManager().findOrInsert( "worldspawn", true );
565         eclass_release_state( worldspawn );
566         worldspawn->color = colour;
567         eclass_capture_state( worldspawn );
568 }
569
570
571 class WorldspawnColourEntityClassObserver : public ModuleObserver
572 {
573 std::size_t m_unrealised;
574 public:
575 WorldspawnColourEntityClassObserver() : m_unrealised( 1 ){
576 }
577 void realise(){
578         if ( --m_unrealised == 0 ) {
579                 SetWorldspawnColour( g_xywindow_globals.color_brushes );
580         }
581 }
582 void unrealise(){
583         if ( ++m_unrealised == 1 ) {
584         }
585 }
586 };
587
588 WorldspawnColourEntityClassObserver g_WorldspawnColourEntityClassObserver;
589
590
591 ModuleObservers g_gameToolsPathObservers;
592
593 void Radiant_attachGameToolsPathObserver( ModuleObserver& observer ){
594         g_gameToolsPathObservers.attach( observer );
595 }
596
597 void Radiant_detachGameToolsPathObserver( ModuleObserver& observer ){
598         g_gameToolsPathObservers.detach( observer );
599 }
600
601 void Radiant_Initialise(){
602         GlobalModuleServer_Initialise();
603
604         Radiant_loadModulesFromRoot( AppPath_get() );
605
606         Preferences_Load();
607
608         bool success = Radiant_Construct( GlobalModuleServer_get() );
609         ASSERT_MESSAGE( success, "module system failed to initialise - see radiant.log for error messages" );
610
611         g_gameToolsPathObservers.realise();
612         g_gameModeObservers.realise();
613         g_gameNameObservers.realise();
614 }
615
616 void Radiant_Shutdown(){
617         g_gameNameObservers.unrealise();
618         g_gameModeObservers.unrealise();
619         g_gameToolsPathObservers.unrealise();
620
621         if ( !g_preferences_globals.disable_ini ) {
622                 globalOutputStream() << "Start writing prefs\n";
623                 Preferences_Save();
624                 globalOutputStream() << "Done prefs\n";
625         }
626
627         Radiant_Destroy();
628
629         GlobalModuleServer_Shutdown();
630 }
631
632 void Exit(){
633         if ( ConfirmModified( "Exit Radiant" ) ) {
634                 gtk_main_quit();
635         }
636 }
637
638
639 void Undo(){
640         GlobalUndoSystem().undo();
641         SceneChangeNotify();
642 }
643
644 void Redo(){
645         GlobalUndoSystem().redo();
646         SceneChangeNotify();
647 }
648
649 void deleteSelection(){
650         UndoableCommand undo( "deleteSelected" );
651         Select_Delete();
652 }
653
654 void Map_ExportSelected( TextOutputStream& ostream ){
655         Map_ExportSelected( ostream, Map_getFormat( g_map ) );
656 }
657
658 void Map_ImportSelected( TextInputStream& istream ){
659         Map_ImportSelected( istream, Map_getFormat( g_map ) );
660 }
661
662 void Selection_Copy(){
663         clipboard_copy( Map_ExportSelected );
664 }
665
666 void Selection_Paste(){
667         clipboard_paste( Map_ImportSelected );
668 }
669
670 void Copy(){
671         if ( SelectedFaces_empty() ) {
672                 Selection_Copy();
673         }
674         else
675         {
676                 SelectedFaces_copyTexture();
677         }
678 }
679
680 void Paste(){
681         if ( SelectedFaces_empty() ) {
682                 UndoableCommand undo( "paste" );
683
684                 GlobalSelectionSystem().setSelectedAll( false );
685                 Selection_Paste();
686         }
687         else
688         {
689                 SelectedFaces_pasteTexture();
690         }
691 }
692
693 void PasteToCamera(){
694         CamWnd& camwnd = *g_pParentWnd->GetCamWnd();
695         GlobalSelectionSystem().setSelectedAll( false );
696
697         UndoableCommand undo( "pasteToCamera" );
698
699         Selection_Paste();
700
701         // Work out the delta
702         Vector3 mid;
703         Select_GetMid( mid );
704         Vector3 delta = vector3_subtracted( vector3_snapped( Camera_getOrigin( camwnd ), GetSnapGridSize() ), mid );
705
706         // Move to camera
707         GlobalSelectionSystem().translateSelected( delta );
708 }
709
710
711 void ColorScheme_Original(){
712         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
713
714         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
715         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
716         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
717
718         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
719         g_xywindow_globals.color_gridminor = Vector3( 0.75f, 0.75f, 0.75f );
720         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
721         g_xywindow_globals.color_gridminor_alt = Vector3( 0.5f, 0.0f, 0.0f );
722         g_xywindow_globals.color_gridmajor_alt = Vector3( 1.0f, 0.0f, 0.0f );
723         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
724         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
725         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
726         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
727         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
728         SetWorldspawnColour( g_xywindow_globals.color_brushes );
729         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
730         XY_UpdateAllWindows();
731 }
732
733 void ColorScheme_QER(){
734         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
735
736         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
737         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
738         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
739
740         g_xywindow_globals.color_gridback = Vector3( 1.0f, 1.0f, 1.0f );
741         g_xywindow_globals.color_gridminor = Vector3( 1.0f, 1.0f, 1.0f );
742         g_xywindow_globals.color_gridmajor = Vector3( 0.5f, 0.5f, 0.5f );
743         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
744         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.0f );
745         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
746         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
747         g_xywindow_globals.color_brushes = Vector3( 0.0f, 0.0f, 0.0f );
748         SetWorldspawnColour( g_xywindow_globals.color_brushes );
749         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
750         XY_UpdateAllWindows();
751 }
752
753 void ColorScheme_Black(){
754         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), Vector3( 0.25f, 0.25f, 0.25f ) );
755
756         g_camwindow_globals.color_cameraback = Vector3( 0.25f, 0.25f, 0.25f );
757         g_camwindow_globals.color_selbrushes3d = Vector3( 1.0f, 0.0f, 0.0f );
758         CamWnd_Update( *g_pParentWnd->GetCamWnd() );
759
760         g_xywindow_globals.color_gridback = Vector3( 0.0f, 0.0f, 0.0f );
761         g_xywindow_globals.color_gridminor = Vector3( 0.2f, 0.2f, 0.2f );
762         g_xywindow_globals.color_gridmajor = Vector3( 0.3f, 0.5f, 0.5f );
763         g_xywindow_globals.color_gridblock = Vector3( 0.0f, 0.0f, 1.0f );
764         g_xywindow_globals.color_gridtext = Vector3( 1.0f, 1.0f, 1.0f );
765         g_xywindow_globals.color_selbrushes = Vector3( 1.0f, 0.0f, 0.0f );
766         g_xywindow_globals.color_clipper = Vector3( 0.0f, 0.0f, 1.0f );
767         g_xywindow_globals.color_brushes = Vector3( 1.0f, 1.0f, 1.0f );
768         SetWorldspawnColour( g_xywindow_globals.color_brushes );
769         g_xywindow_globals.color_viewname = Vector3( 0.7f, 0.7f, 0.0f );
770         XY_UpdateAllWindows();
771 }
772
773 /* ydnar: to emulate maya/max/lightwave color schemes */
774 void ColorScheme_Ydnar(){
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.77f, 0.77f, 0.77f );
782         g_xywindow_globals.color_gridminor = Vector3( 0.83f, 0.83f, 0.83f );
783         g_xywindow_globals.color_gridmajor = Vector3( 0.89f, 0.89f, 0.89f );
784         g_xywindow_globals.color_gridblock = Vector3( 1.0f, 1.0f, 1.0f );
785         g_xywindow_globals.color_gridtext = Vector3( 0.0f, 0.0f, 0.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( 0.0f, 0.0f, 0.0f );
789         SetWorldspawnColour( g_xywindow_globals.color_brushes );
790         g_xywindow_globals.color_viewname = Vector3( 0.5f, 0.0f, 0.75f );
791         XY_UpdateAllWindows();
792 }
793
794 typedef Callback1<Vector3&> GetColourCallback;
795 typedef Callback1<const Vector3&> SetColourCallback;
796
797 class ChooseColour
798 {
799 GetColourCallback m_get;
800 SetColourCallback m_set;
801 public:
802 ChooseColour( const GetColourCallback& get, const SetColourCallback& set )
803         : m_get( get ), m_set( set ){
804 }
805 void operator()(){
806         Vector3 colour;
807         m_get( colour );
808         color_dialog( GTK_WIDGET( MainFrame_getWindow() ), colour );
809         m_set( colour );
810 }
811 };
812
813
814
815 void Colour_get( const Vector3& colour, Vector3& other ){
816         other = colour;
817 }
818 typedef ConstReferenceCaller1<Vector3, Vector3&, Colour_get> ColourGetCaller;
819
820 void Colour_set( Vector3& colour, const Vector3& other ){
821         colour = other;
822         SceneChangeNotify();
823 }
824 typedef ReferenceCaller1<Vector3, const Vector3&, Colour_set> ColourSetCaller;
825
826 void BrushColour_set( const Vector3& other ){
827         g_xywindow_globals.color_brushes = other;
828         SetWorldspawnColour( g_xywindow_globals.color_brushes );
829         SceneChangeNotify();
830 }
831 typedef FreeCaller1<const Vector3&, BrushColour_set> BrushColourSetCaller;
832
833 void ClipperColour_set( const Vector3& other ){
834         g_xywindow_globals.color_clipper = other;
835         Brush_clipperColourChanged();
836         SceneChangeNotify();
837 }
838 typedef FreeCaller1<const Vector3&, ClipperColour_set> ClipperColourSetCaller;
839
840 void TextureBrowserColour_get( Vector3& other ){
841         other = TextureBrowser_getBackgroundColour( GlobalTextureBrowser() );
842 }
843 typedef FreeCaller1<Vector3&, TextureBrowserColour_get> TextureBrowserColourGetCaller;
844
845 void TextureBrowserColour_set( const Vector3& other ){
846         TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), other );
847 }
848 typedef FreeCaller1<const Vector3&, TextureBrowserColour_set> TextureBrowserColourSetCaller;
849
850
851 class ColoursMenu
852 {
853 public:
854 ChooseColour m_textureback;
855 ChooseColour m_xyback;
856 ChooseColour m_gridmajor;
857 ChooseColour m_gridminor;
858 ChooseColour m_gridmajor_alt;
859 ChooseColour m_gridminor_alt;
860 ChooseColour m_gridtext;
861 ChooseColour m_gridblock;
862 ChooseColour m_cameraback;
863 ChooseColour m_brush;
864 ChooseColour m_selectedbrush;
865 ChooseColour m_selectedbrush3d;
866 ChooseColour m_clipper;
867 ChooseColour m_viewname;
868
869 ColoursMenu() :
870         m_textureback( TextureBrowserColourGetCaller(), TextureBrowserColourSetCaller() ),
871         m_xyback( ColourGetCaller( g_xywindow_globals.color_gridback ), ColourSetCaller( g_xywindow_globals.color_gridback ) ),
872         m_gridmajor( ColourGetCaller( g_xywindow_globals.color_gridmajor ), ColourSetCaller( g_xywindow_globals.color_gridmajor ) ),
873         m_gridminor( ColourGetCaller( g_xywindow_globals.color_gridminor ), ColourSetCaller( g_xywindow_globals.color_gridminor ) ),
874         m_gridmajor_alt( ColourGetCaller( g_xywindow_globals.color_gridmajor_alt ), ColourSetCaller( g_xywindow_globals.color_gridmajor_alt ) ),
875         m_gridminor_alt( ColourGetCaller( g_xywindow_globals.color_gridminor_alt ), ColourSetCaller( g_xywindow_globals.color_gridminor_alt ) ),
876         m_gridtext( ColourGetCaller( g_xywindow_globals.color_gridtext ), ColourSetCaller( g_xywindow_globals.color_gridtext ) ),
877         m_gridblock( ColourGetCaller( g_xywindow_globals.color_gridblock ), ColourSetCaller( g_xywindow_globals.color_gridblock ) ),
878         m_cameraback( ColourGetCaller( g_camwindow_globals.color_cameraback ), ColourSetCaller( g_camwindow_globals.color_cameraback ) ),
879         m_brush( ColourGetCaller( g_xywindow_globals.color_brushes ), BrushColourSetCaller() ),
880         m_selectedbrush( ColourGetCaller( g_xywindow_globals.color_selbrushes ), ColourSetCaller( g_xywindow_globals.color_selbrushes ) ),
881         m_selectedbrush3d( ColourGetCaller( g_camwindow_globals.color_selbrushes3d ), ColourSetCaller( g_camwindow_globals.color_selbrushes3d ) ),
882         m_clipper( ColourGetCaller( g_xywindow_globals.color_clipper ), ClipperColourSetCaller() ),
883         m_viewname( ColourGetCaller( g_xywindow_globals.color_viewname ), ColourSetCaller( g_xywindow_globals.color_viewname ) ){
884 }
885 };
886
887 ColoursMenu g_ColoursMenu;
888
889 GtkMenuItem* create_colours_menu(){
890         GtkMenuItem* colours_menu_item = new_sub_menu_item_with_mnemonic( "Colors" );
891         GtkMenu* menu_in_menu = GTK_MENU( gtk_menu_item_get_submenu( colours_menu_item ) );
892         if ( g_Layout_enableDetachableMenus.m_value ) {
893                 menu_tearoff( menu_in_menu );
894         }
895
896         GtkMenu* menu_3 = create_sub_menu_with_mnemonic( menu_in_menu, "Themes" );
897         if ( g_Layout_enableDetachableMenus.m_value ) {
898                 menu_tearoff( menu_3 );
899         }
900
901         create_menu_item_with_mnemonic( menu_3, "QE4 Original", "ColorSchemeOriginal" );
902         create_menu_item_with_mnemonic( menu_3, "Q3Radiant Original", "ColorSchemeQER" );
903         create_menu_item_with_mnemonic( menu_3, "Black and Green", "ColorSchemeBlackAndGreen" );
904         create_menu_item_with_mnemonic( menu_3, "Maya/Max/Lightwave Emulation", "ColorSchemeYdnar" );
905
906         menu_separator( menu_in_menu );
907
908         create_menu_item_with_mnemonic( menu_in_menu, "_Texture Background...", "ChooseTextureBackgroundColor" );
909         create_menu_item_with_mnemonic( menu_in_menu, "Grid Background...", "ChooseGridBackgroundColor" );
910         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major...", "ChooseGridMajorColor" );
911         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor...", "ChooseGridMinorColor" );
912         create_menu_item_with_mnemonic( menu_in_menu, "Grid Major Small...", "ChooseSmallGridMajorColor" );
913         create_menu_item_with_mnemonic( menu_in_menu, "Grid Minor Small...", "ChooseSmallGridMinorColor" );
914         create_menu_item_with_mnemonic( menu_in_menu, "Grid Text...", "ChooseGridTextColor" );
915         create_menu_item_with_mnemonic( menu_in_menu, "Grid Block...", "ChooseGridBlockColor" );
916         create_menu_item_with_mnemonic( menu_in_menu, "Default Brush...", "ChooseBrushColor" );
917         create_menu_item_with_mnemonic( menu_in_menu, "Camera Background...", "ChooseCameraBackgroundColor" );
918         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush...", "ChooseSelectedBrushColor" );
919         create_menu_item_with_mnemonic( menu_in_menu, "Selected Brush (Camera)...", "ChooseCameraSelectedBrushColor" );
920         create_menu_item_with_mnemonic( menu_in_menu, "Clipper...", "ChooseClipperColor" );
921         create_menu_item_with_mnemonic( menu_in_menu, "Active View name...", "ChooseOrthoViewNameColor" );
922
923         return colours_menu_item;
924 }
925
926
927 void Restart(){
928         PluginsMenu_clear();
929         PluginToolbar_clear();
930
931         Radiant_Shutdown();
932         Radiant_Initialise();
933
934         PluginsMenu_populate();
935
936         PluginToolbar_populate();
937 }
938
939
940 void thunk_OnSleep(){
941         g_pParentWnd->OnSleep();
942 }
943
944 void OpenUpdateURL(){
945         // build the URL
946         StringOutputStream URL( 256 );
947         URL << "http://www.icculus.org/netradiant/?cmd=update&data=dlupdate&query_dlup=1";
948 #ifdef WIN32
949         URL << "&OS_dlup=1";
950 #elif defined( __APPLE__ )
951         URL << "&OS_dlup=2";
952 #else
953         URL << "&OS_dlup=3";
954 #endif
955         URL << "&Version_dlup=" RADIANT_VERSION;
956         g_GamesDialog.AddPacksURL( URL );
957         OpenURL( URL.c_str() );
958 }
959
960 // open the Q3Rad manual
961 void OpenHelpURL(){
962         // at least on win32, AppPath + "docs/index.html"
963         StringOutputStream help( 256 );
964         help << AppPath_get() << "docs/index.html";
965         OpenURL( help.c_str() );
966 }
967
968 void OpenBugReportURL(){
969         OpenURL( "http://www.icculus.org/netradiant/?cmd=bugs" );
970 }
971
972
973 GtkWidget* g_page_console;
974
975 void Console_ToggleShow(){
976         GroupDialog_showPage( g_page_console );
977 }
978
979 GtkWidget* g_page_entity;
980
981 void EntityInspector_ToggleShow(){
982         GroupDialog_showPage( g_page_entity );
983 }
984
985
986
987 void SetClipMode( bool enable );
988 void ModeChangeNotify();
989
990 typedef void ( *ToolMode )();
991 ToolMode g_currentToolMode = 0;
992 bool g_currentToolModeSupportsComponentEditing = false;
993 ToolMode g_defaultToolMode = 0;
994
995
996
997 void SelectionSystem_DefaultMode(){
998         GlobalSelectionSystem().SetMode( SelectionSystem::ePrimitive );
999         GlobalSelectionSystem().SetComponentMode( SelectionSystem::eDefault );
1000         ModeChangeNotify();
1001 }
1002
1003
1004 bool EdgeMode(){
1005         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1006                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eEdge;
1007 }
1008
1009 bool VertexMode(){
1010         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1011                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex;
1012 }
1013
1014 bool FaceMode(){
1015         return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1016                    && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace;
1017 }
1018
1019 template<bool( *BoolFunction ) ( )>
1020 class BoolFunctionExport
1021 {
1022 public:
1023 static void apply( const BoolImportCallback& importCallback ){
1024         importCallback( BoolFunction() );
1025 }
1026 };
1027
1028 typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<EdgeMode>::apply> EdgeModeApplyCaller;
1029 EdgeModeApplyCaller g_edgeMode_button_caller;
1030 BoolExportCallback g_edgeMode_button_callback( g_edgeMode_button_caller );
1031 ToggleItem g_edgeMode_button( g_edgeMode_button_callback );
1032
1033 typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<VertexMode>::apply> VertexModeApplyCaller;
1034 VertexModeApplyCaller g_vertexMode_button_caller;
1035 BoolExportCallback g_vertexMode_button_callback( g_vertexMode_button_caller );
1036 ToggleItem g_vertexMode_button( g_vertexMode_button_callback );
1037
1038 typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<FaceMode>::apply> FaceModeApplyCaller;
1039 FaceModeApplyCaller g_faceMode_button_caller;
1040 BoolExportCallback g_faceMode_button_callback( g_faceMode_button_caller );
1041 ToggleItem g_faceMode_button( g_faceMode_button_callback );
1042
1043 void ComponentModeChanged(){
1044         g_edgeMode_button.update();
1045         g_vertexMode_button.update();
1046         g_faceMode_button.update();
1047 }
1048
1049 void ComponentMode_SelectionChanged( const Selectable& selectable ){
1050         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
1051                  && GlobalSelectionSystem().countSelected() == 0 ) {
1052                 SelectionSystem_DefaultMode();
1053                 ComponentModeChanged();
1054         }
1055 }
1056
1057 void SelectEdgeMode(){
1058 #if 0
1059         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1060                 GlobalSelectionSystem().Select( false );
1061         }
1062 #endif
1063
1064         if ( EdgeMode() ) {
1065                 SelectionSystem_DefaultMode();
1066         }
1067         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1068                 if ( !g_currentToolModeSupportsComponentEditing ) {
1069                         g_defaultToolMode();
1070                 }
1071
1072                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1073                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eEdge );
1074         }
1075
1076         ComponentModeChanged();
1077
1078         ModeChangeNotify();
1079 }
1080
1081 void SelectVertexMode(){
1082 #if 0
1083         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1084                 GlobalSelectionSystem().Select( false );
1085         }
1086 #endif
1087
1088         if ( VertexMode() ) {
1089                 SelectionSystem_DefaultMode();
1090         }
1091         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1092                 if ( !g_currentToolModeSupportsComponentEditing ) {
1093                         g_defaultToolMode();
1094                 }
1095
1096                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1097                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eVertex );
1098         }
1099
1100         ComponentModeChanged();
1101
1102         ModeChangeNotify();
1103 }
1104
1105 void SelectFaceMode(){
1106 #if 0
1107         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1108                 GlobalSelectionSystem().Select( false );
1109         }
1110 #endif
1111
1112         if ( FaceMode() ) {
1113                 SelectionSystem_DefaultMode();
1114         }
1115         else if ( GlobalSelectionSystem().countSelected() != 0 ) {
1116                 if ( !g_currentToolModeSupportsComponentEditing ) {
1117                         g_defaultToolMode();
1118                 }
1119
1120                 GlobalSelectionSystem().SetMode( SelectionSystem::eComponent );
1121                 GlobalSelectionSystem().SetComponentMode( SelectionSystem::eFace );
1122         }
1123
1124         ComponentModeChanged();
1125
1126         ModeChangeNotify();
1127 }
1128
1129
1130 class CloneSelected : public scene::Graph::Walker
1131 {
1132 bool doMakeUnique;
1133 NodeSmartReference worldspawn;
1134 public:
1135 CloneSelected( bool d ) : doMakeUnique( d ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){
1136 }
1137 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1138         if ( path.size() == 1 ) {
1139                 return true;
1140         }
1141
1142         // ignore worldspawn, but keep checking children
1143         NodeSmartReference me( path.top().get() );
1144         if ( me == worldspawn ) {
1145                 return true;
1146         }
1147
1148         if ( !path.top().get().isRoot() ) {
1149                 Selectable* selectable = Instance_getSelectable( instance );
1150                 if ( selectable != 0
1151                          && selectable->isSelected() ) {
1152                         return false;
1153                 }
1154         }
1155
1156         return true;
1157 }
1158 void post( const scene::Path& path, scene::Instance& instance ) const {
1159         if ( path.size() == 1 ) {
1160                 return;
1161         }
1162
1163         // ignore worldspawn, but keep checking children
1164         NodeSmartReference me( path.top().get() );
1165         if ( me == worldspawn ) {
1166                 return;
1167         }
1168
1169         if ( !path.top().get().isRoot() ) {
1170                 Selectable* selectable = Instance_getSelectable( instance );
1171                 if ( selectable != 0
1172                          && selectable->isSelected() ) {
1173                         NodeSmartReference clone( Node_Clone( path.top() ) );
1174                         if ( doMakeUnique ) {
1175                                 Map_gatherNamespaced( clone );
1176                         }
1177                         Node_getTraversable( path.parent().get() )->insert( clone );
1178                 }
1179         }
1180 }
1181 };
1182
1183 void Scene_Clone_Selected( scene::Graph& graph, bool doMakeUnique ){
1184         graph.traverse( CloneSelected( doMakeUnique ) );
1185
1186         Map_mergeClonedNames();
1187 }
1188
1189 enum ENudgeDirection
1190 {
1191         eNudgeUp = 1,
1192         eNudgeDown = 3,
1193         eNudgeLeft = 0,
1194         eNudgeRight = 2,
1195 };
1196
1197 struct AxisBase
1198 {
1199         Vector3 x;
1200         Vector3 y;
1201         Vector3 z;
1202         AxisBase( const Vector3& x_, const Vector3& y_, const Vector3& z_ )
1203                 : x( x_ ), y( y_ ), z( z_ ){
1204         }
1205 };
1206
1207 AxisBase AxisBase_forViewType( VIEWTYPE viewtype ){
1208         switch ( viewtype )
1209         {
1210         case XY:
1211                 return AxisBase( g_vector3_axis_x, g_vector3_axis_y, g_vector3_axis_z );
1212         case XZ:
1213                 return AxisBase( g_vector3_axis_x, g_vector3_axis_z, g_vector3_axis_y );
1214         case YZ:
1215                 return AxisBase( g_vector3_axis_y, g_vector3_axis_z, g_vector3_axis_x );
1216         }
1217
1218         ERROR_MESSAGE( "invalid viewtype" );
1219         return AxisBase( Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ), Vector3( 0, 0, 0 ) );
1220 }
1221
1222 Vector3 AxisBase_axisForDirection( const AxisBase& axes, ENudgeDirection direction ){
1223         switch ( direction )
1224         {
1225         case eNudgeLeft:
1226                 return vector3_negated( axes.x );
1227         case eNudgeUp:
1228                 return axes.y;
1229         case eNudgeRight:
1230                 return axes.x;
1231         case eNudgeDown:
1232                 return vector3_negated( axes.y );
1233         }
1234
1235         ERROR_MESSAGE( "invalid direction" );
1236         return Vector3( 0, 0, 0 );
1237 }
1238
1239 void NudgeSelection( ENudgeDirection direction, float fAmount, VIEWTYPE viewtype ){
1240         AxisBase axes( AxisBase_forViewType( viewtype ) );
1241         Vector3 view_direction( vector3_negated( axes.z ) );
1242         Vector3 nudge( vector3_scaled( AxisBase_axisForDirection( axes, direction ), fAmount ) );
1243         GlobalSelectionSystem().NudgeManipulator( nudge, view_direction );
1244 }
1245
1246 void Selection_Clone(){
1247         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
1248                 UndoableCommand undo( "cloneSelected" );
1249
1250                 Scene_Clone_Selected( GlobalSceneGraph(), false );
1251
1252                 //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1253                 //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1254         }
1255 }
1256
1257 void Selection_Clone_MakeUnique(){
1258         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
1259                 UndoableCommand undo( "cloneSelectedMakeUnique" );
1260
1261                 Scene_Clone_Selected( GlobalSceneGraph(), true );
1262
1263                 //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1264                 //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType());
1265         }
1266 }
1267
1268 // called when the escape key is used (either on the main window or on an inspector)
1269 void Selection_Deselect(){
1270         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1271                 if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
1272                         GlobalSelectionSystem().setSelectedAllComponents( false );
1273                 }
1274                 else
1275                 {
1276                         SelectionSystem_DefaultMode();
1277                         ComponentModeChanged();
1278                 }
1279         }
1280         else
1281         {
1282                 if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
1283                         GlobalSelectionSystem().setSelectedAllComponents( false );
1284                 }
1285                 else
1286                 {
1287                         GlobalSelectionSystem().setSelectedAll( false );
1288                 }
1289         }
1290 }
1291
1292
1293 void Selection_NudgeUp(){
1294         UndoableCommand undo( "nudgeSelectedUp" );
1295         NudgeSelection( eNudgeUp, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1296 }
1297
1298 void Selection_NudgeDown(){
1299         UndoableCommand undo( "nudgeSelectedDown" );
1300         NudgeSelection( eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1301 }
1302
1303 void Selection_NudgeLeft(){
1304         UndoableCommand undo( "nudgeSelectedLeft" );
1305         NudgeSelection( eNudgeLeft, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1306 }
1307
1308 void Selection_NudgeRight(){
1309         UndoableCommand undo( "nudgeSelectedRight" );
1310         NudgeSelection( eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType() );
1311 }
1312
1313
1314 void TranslateToolExport( const BoolImportCallback& importCallback ){
1315         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eTranslate );
1316 }
1317
1318 void RotateToolExport( const BoolImportCallback& importCallback ){
1319         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eRotate );
1320 }
1321
1322 void ScaleToolExport( const BoolImportCallback& importCallback ){
1323         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eScale );
1324 }
1325
1326 void DragToolExport( const BoolImportCallback& importCallback ){
1327         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag );
1328 }
1329
1330 void ClipperToolExport( const BoolImportCallback& importCallback ){
1331         importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip );
1332 }
1333
1334 FreeCaller1<const BoolImportCallback&, TranslateToolExport> g_translatemode_button_caller;
1335 BoolExportCallback g_translatemode_button_callback( g_translatemode_button_caller );
1336 ToggleItem g_translatemode_button( g_translatemode_button_callback );
1337
1338 FreeCaller1<const BoolImportCallback&, RotateToolExport> g_rotatemode_button_caller;
1339 BoolExportCallback g_rotatemode_button_callback( g_rotatemode_button_caller );
1340 ToggleItem g_rotatemode_button( g_rotatemode_button_callback );
1341
1342 FreeCaller1<const BoolImportCallback&, ScaleToolExport> g_scalemode_button_caller;
1343 BoolExportCallback g_scalemode_button_callback( g_scalemode_button_caller );
1344 ToggleItem g_scalemode_button( g_scalemode_button_callback );
1345
1346 FreeCaller1<const BoolImportCallback&, DragToolExport> g_dragmode_button_caller;
1347 BoolExportCallback g_dragmode_button_callback( g_dragmode_button_caller );
1348 ToggleItem g_dragmode_button( g_dragmode_button_callback );
1349
1350 FreeCaller1<const BoolImportCallback&, ClipperToolExport> g_clipper_button_caller;
1351 BoolExportCallback g_clipper_button_callback( g_clipper_button_caller );
1352 ToggleItem g_clipper_button( g_clipper_button_callback );
1353
1354 void ToolChanged(){
1355         g_translatemode_button.update();
1356         g_rotatemode_button.update();
1357         g_scalemode_button.update();
1358         g_dragmode_button.update();
1359         g_clipper_button.update();
1360 }
1361
1362 const char* const c_ResizeMode_status = "QE4 Drag Tool: move and resize objects";
1363
1364 void DragMode(){
1365         if ( g_currentToolMode == DragMode && g_defaultToolMode != DragMode ) {
1366                 g_defaultToolMode();
1367         }
1368         else
1369         {
1370                 g_currentToolMode = DragMode;
1371                 g_currentToolModeSupportsComponentEditing = true;
1372
1373                 OnClipMode( false );
1374
1375                 Sys_Status( c_ResizeMode_status );
1376                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eDrag );
1377                 ToolChanged();
1378                 ModeChangeNotify();
1379         }
1380 }
1381
1382
1383 const char* const c_TranslateMode_status = "Translate Tool: translate objects and components";
1384
1385 void TranslateMode(){
1386         if ( g_currentToolMode == TranslateMode && g_defaultToolMode != TranslateMode ) {
1387                 g_defaultToolMode();
1388         }
1389         else
1390         {
1391                 g_currentToolMode = TranslateMode;
1392                 g_currentToolModeSupportsComponentEditing = true;
1393
1394                 OnClipMode( false );
1395
1396                 Sys_Status( c_TranslateMode_status );
1397                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eTranslate );
1398                 ToolChanged();
1399                 ModeChangeNotify();
1400         }
1401 }
1402
1403 const char* const c_RotateMode_status = "Rotate Tool: rotate objects and components";
1404
1405 void RotateMode(){
1406         if ( g_currentToolMode == RotateMode && g_defaultToolMode != RotateMode ) {
1407                 g_defaultToolMode();
1408         }
1409         else
1410         {
1411                 g_currentToolMode = RotateMode;
1412                 g_currentToolModeSupportsComponentEditing = true;
1413
1414                 OnClipMode( false );
1415
1416                 Sys_Status( c_RotateMode_status );
1417                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eRotate );
1418                 ToolChanged();
1419                 ModeChangeNotify();
1420         }
1421 }
1422
1423 const char* const c_ScaleMode_status = "Scale Tool: scale objects and components";
1424
1425 void ScaleMode(){
1426         if ( g_currentToolMode == ScaleMode && g_defaultToolMode != ScaleMode ) {
1427                 g_defaultToolMode();
1428         }
1429         else
1430         {
1431                 g_currentToolMode = ScaleMode;
1432                 g_currentToolModeSupportsComponentEditing = true;
1433
1434                 OnClipMode( false );
1435
1436                 Sys_Status( c_ScaleMode_status );
1437                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eScale );
1438                 ToolChanged();
1439                 ModeChangeNotify();
1440         }
1441 }
1442
1443
1444 const char* const c_ClipperMode_status = "Clipper Tool: apply clip planes to objects";
1445
1446
1447 void ClipperMode(){
1448         if ( g_currentToolMode == ClipperMode && g_defaultToolMode != ClipperMode ) {
1449                 g_defaultToolMode();
1450         }
1451         else
1452         {
1453                 g_currentToolMode = ClipperMode;
1454                 g_currentToolModeSupportsComponentEditing = false;
1455
1456                 SelectionSystem_DefaultMode();
1457
1458                 OnClipMode( true );
1459
1460                 Sys_Status( c_ClipperMode_status );
1461                 GlobalSelectionSystem().SetManipulatorMode( SelectionSystem::eClip );
1462                 ToolChanged();
1463                 ModeChangeNotify();
1464         }
1465 }
1466
1467
1468 void Texdef_Rotate( float angle ){
1469         StringOutputStream command;
1470         command << "brushRotateTexture -angle " << angle;
1471         UndoableCommand undo( command.c_str() );
1472         Select_RotateTexture( angle );
1473 }
1474
1475 void Texdef_RotateClockwise(){
1476         Texdef_Rotate( static_cast<float>( fabs( g_si_globals.rotate ) ) );
1477 }
1478
1479 void Texdef_RotateAntiClockwise(){
1480         Texdef_Rotate( static_cast<float>( -fabs( g_si_globals.rotate ) ) );
1481 }
1482
1483 void Texdef_Scale( float x, float y ){
1484         StringOutputStream command;
1485         command << "brushScaleTexture -x " << x << " -y " << y;
1486         UndoableCommand undo( command.c_str() );
1487         Select_ScaleTexture( x, y );
1488 }
1489
1490 void Texdef_ScaleUp(){
1491         Texdef_Scale( 0, g_si_globals.scale[1] );
1492 }
1493
1494 void Texdef_ScaleDown(){
1495         Texdef_Scale( 0, -g_si_globals.scale[1] );
1496 }
1497
1498 void Texdef_ScaleLeft(){
1499         Texdef_Scale( -g_si_globals.scale[0],0 );
1500 }
1501
1502 void Texdef_ScaleRight(){
1503         Texdef_Scale( g_si_globals.scale[0],0 );
1504 }
1505
1506 void Texdef_Shift( float x, float y ){
1507         StringOutputStream command;
1508         command << "brushShiftTexture -x " << x << " -y " << y;
1509         UndoableCommand undo( command.c_str() );
1510         Select_ShiftTexture( x, y );
1511 }
1512
1513 void Texdef_ShiftLeft(){
1514         Texdef_Shift( -g_si_globals.shift[0], 0 );
1515 }
1516
1517 void Texdef_ShiftRight(){
1518         Texdef_Shift( g_si_globals.shift[0], 0 );
1519 }
1520
1521 void Texdef_ShiftUp(){
1522         Texdef_Shift( 0, g_si_globals.shift[1] );
1523 }
1524
1525 void Texdef_ShiftDown(){
1526         Texdef_Shift( 0, -g_si_globals.shift[1] );
1527 }
1528
1529
1530
1531 class SnappableSnapToGridSelected : public scene::Graph::Walker
1532 {
1533 float m_snap;
1534 public:
1535 SnappableSnapToGridSelected( float snap )
1536         : m_snap( snap ){
1537 }
1538 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1539         if ( path.top().get().visible() ) {
1540                 Snappable* snappable = Node_getSnappable( path.top() );
1541                 if ( snappable != 0
1542                          && Instance_getSelectable( instance )->isSelected() ) {
1543                         snappable->snapto( m_snap );
1544                 }
1545         }
1546         return true;
1547 }
1548 };
1549
1550 void Scene_SnapToGrid_Selected( scene::Graph& graph, float snap ){
1551         graph.traverse( SnappableSnapToGridSelected( snap ) );
1552 }
1553
1554 class ComponentSnappableSnapToGridSelected : public scene::Graph::Walker
1555 {
1556 float m_snap;
1557 public:
1558 ComponentSnappableSnapToGridSelected( float snap )
1559         : m_snap( snap ){
1560 }
1561 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1562         if ( path.top().get().visible() ) {
1563                 ComponentSnappable* componentSnappable = Instance_getComponentSnappable( instance );
1564                 if ( componentSnappable != 0
1565                          && Instance_getSelectable( instance )->isSelected() ) {
1566                         componentSnappable->snapComponents( m_snap );
1567                 }
1568         }
1569         return true;
1570 }
1571 };
1572
1573 void Scene_SnapToGrid_Component_Selected( scene::Graph& graph, float snap ){
1574         graph.traverse( ComponentSnappableSnapToGridSelected( snap ) );
1575 }
1576
1577 void Selection_SnapToGrid(){
1578         StringOutputStream command;
1579         command << "snapSelected -grid " << GetGridSize();
1580         UndoableCommand undo( command.c_str() );
1581
1582         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1583                 Scene_SnapToGrid_Component_Selected( GlobalSceneGraph(), GetGridSize() );
1584         }
1585         else
1586         {
1587                 Scene_SnapToGrid_Selected( GlobalSceneGraph(), GetGridSize() );
1588         }
1589 }
1590
1591
1592 static gint qe_every_second( gpointer data ){
1593         GdkModifierType mask;
1594
1595         gdk_window_get_pointer( 0, 0, 0, &mask );
1596
1597         if ( ( mask & ( GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK ) ) == 0 ) {
1598                 QE_CheckAutoSave();
1599         }
1600
1601         return TRUE;
1602 }
1603
1604 guint s_qe_every_second_id = 0;
1605
1606 void EverySecondTimer_enable(){
1607         if ( s_qe_every_second_id == 0 ) {
1608                 s_qe_every_second_id = gtk_timeout_add( 1000, qe_every_second, 0 );
1609         }
1610 }
1611
1612 void EverySecondTimer_disable(){
1613         if ( s_qe_every_second_id != 0 ) {
1614                 gtk_timeout_remove( s_qe_every_second_id );
1615                 s_qe_every_second_id = 0;
1616         }
1617 }
1618
1619 gint window_realize_remove_decoration( GtkWidget* widget, gpointer data ){
1620         gdk_window_set_decorations( widget->window, (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MENU | GDK_DECOR_MINIMIZE | GDK_DECOR_MAXIMIZE ) );
1621         return FALSE;
1622 }
1623
1624 class WaitDialog
1625 {
1626 public:
1627 GtkWindow* m_window;
1628 GtkLabel* m_label;
1629 };
1630
1631 WaitDialog create_wait_dialog( const char* title, const char* text ){
1632         WaitDialog dialog;
1633
1634         dialog.m_window = create_floating_window( title, MainFrame_getWindow() );
1635         gtk_window_set_resizable( dialog.m_window, FALSE );
1636         gtk_container_set_border_width( GTK_CONTAINER( dialog.m_window ), 0 );
1637         gtk_window_set_position( dialog.m_window, GTK_WIN_POS_CENTER_ON_PARENT );
1638
1639         g_signal_connect( G_OBJECT( dialog.m_window ), "realize", G_CALLBACK( window_realize_remove_decoration ), 0 );
1640
1641         {
1642                 dialog.m_label = GTK_LABEL( gtk_label_new( text ) );
1643                 gtk_misc_set_alignment( GTK_MISC( dialog.m_label ), 0.0, 0.5 );
1644                 gtk_label_set_justify( dialog.m_label, GTK_JUSTIFY_LEFT );
1645                 gtk_widget_show( GTK_WIDGET( dialog.m_label ) );
1646                 gtk_widget_set_size_request( GTK_WIDGET( dialog.m_label ), 200, -1 );
1647
1648                 gtk_container_add( GTK_CONTAINER( dialog.m_window ), GTK_WIDGET( dialog.m_label ) );
1649         }
1650         return dialog;
1651 }
1652
1653 namespace
1654 {
1655 clock_t g_lastRedrawTime = 0;
1656 const clock_t c_redrawInterval = clock_t( CLOCKS_PER_SEC / 10 );
1657
1658 bool redrawRequired(){
1659         clock_t currentTime = std::clock();
1660         if ( currentTime - g_lastRedrawTime >= c_redrawInterval ) {
1661                 g_lastRedrawTime = currentTime;
1662                 return true;
1663         }
1664         return false;
1665 }
1666 }
1667
1668 bool MainFrame_isActiveApp(){
1669         //globalOutputStream() << "listing\n";
1670         GList* list = gtk_window_list_toplevels();
1671         for ( GList* i = list; i != 0; i = g_list_next( i ) )
1672         {
1673                 //globalOutputStream() << "toplevel.. ";
1674                 if ( gtk_window_is_active( GTK_WINDOW( i->data ) ) ) {
1675                         //globalOutputStream() << "is active\n";
1676                         return true;
1677                 }
1678                 //globalOutputStream() << "not active\n";
1679         }
1680         return false;
1681 }
1682
1683 typedef std::list<CopiedString> StringStack;
1684 StringStack g_wait_stack;
1685 WaitDialog g_wait;
1686
1687 bool ScreenUpdates_Enabled(){
1688         return g_wait_stack.empty();
1689 }
1690
1691 void ScreenUpdates_process(){
1692         if ( redrawRequired() && GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
1693                 process_gui();
1694         }
1695 }
1696
1697
1698 void ScreenUpdates_Disable( const char* message, const char* title ){
1699         if ( g_wait_stack.empty() ) {
1700                 EverySecondTimer_disable();
1701
1702                 process_gui();
1703
1704                 bool isActiveApp = MainFrame_isActiveApp();
1705
1706                 g_wait = create_wait_dialog( title, message );
1707                 gtk_grab_add( GTK_WIDGET( g_wait.m_window ) );
1708
1709                 if ( isActiveApp ) {
1710                         gtk_widget_show( GTK_WIDGET( g_wait.m_window ) );
1711                         ScreenUpdates_process();
1712                 }
1713         }
1714         else if ( GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
1715                 gtk_label_set_text( g_wait.m_label, message );
1716                 ScreenUpdates_process();
1717         }
1718         g_wait_stack.push_back( message );
1719 }
1720
1721 void ScreenUpdates_Enable(){
1722         ASSERT_MESSAGE( !ScreenUpdates_Enabled(), "screen updates already enabled" );
1723         g_wait_stack.pop_back();
1724         if ( g_wait_stack.empty() ) {
1725                 EverySecondTimer_enable();
1726                 //gtk_widget_set_sensitive(GTK_WIDGET(MainFrame_getWindow()), TRUE);
1727
1728                 gtk_grab_remove( GTK_WIDGET( g_wait.m_window ) );
1729                 destroy_floating_window( g_wait.m_window );
1730                 g_wait.m_window = 0;
1731
1732                 //gtk_window_present(MainFrame_getWindow());
1733         }
1734         else if ( GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
1735                 gtk_label_set_text( g_wait.m_label, g_wait_stack.back().c_str() );
1736                 ScreenUpdates_process();
1737         }
1738 }
1739
1740
1741
1742 void GlobalCamera_UpdateWindow(){
1743         if ( g_pParentWnd != 0 ) {
1744                 CamWnd_Update( *g_pParentWnd->GetCamWnd() );
1745         }
1746 }
1747
1748 void XY_UpdateWindow( MainFrame& mainframe ){
1749         if ( mainframe.GetXYWnd() != 0 ) {
1750                 XYWnd_Update( *mainframe.GetXYWnd() );
1751         }
1752 }
1753
1754 void XZ_UpdateWindow( MainFrame& mainframe ){
1755         if ( mainframe.GetXZWnd() != 0 ) {
1756                 XYWnd_Update( *mainframe.GetXZWnd() );
1757         }
1758 }
1759
1760 void YZ_UpdateWindow( MainFrame& mainframe ){
1761         if ( mainframe.GetYZWnd() != 0 ) {
1762                 XYWnd_Update( *mainframe.GetYZWnd() );
1763         }
1764 }
1765
1766 void XY_UpdateAllWindows( MainFrame& mainframe ){
1767         XY_UpdateWindow( mainframe );
1768         XZ_UpdateWindow( mainframe );
1769         YZ_UpdateWindow( mainframe );
1770 }
1771
1772 void XY_UpdateAllWindows(){
1773         if ( g_pParentWnd != 0 ) {
1774                 XY_UpdateAllWindows( *g_pParentWnd );
1775         }
1776 }
1777
1778 void UpdateAllWindows(){
1779         GlobalCamera_UpdateWindow();
1780         XY_UpdateAllWindows();
1781 }
1782
1783
1784 void ModeChangeNotify(){
1785         SceneChangeNotify();
1786 }
1787
1788 void ClipperChangeNotify(){
1789         GlobalCamera_UpdateWindow();
1790         XY_UpdateAllWindows();
1791 }
1792
1793
1794 LatchedInt g_Layout_viewStyle( 0, "Window Layout" );
1795 LatchedBool g_Layout_enableDetachableMenus( true, "Detachable Menus" );
1796 LatchedBool g_Layout_enablePatchToolbar( true, "Patch Toolbar" );
1797 LatchedBool g_Layout_enablePluginToolbar( true, "Plugin Toolbar" );
1798
1799
1800
1801 GtkMenuItem* create_file_menu(){
1802         // File menu
1803         GtkMenuItem* file_menu_item = new_sub_menu_item_with_mnemonic( "_File" );
1804         GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( file_menu_item ) );
1805         if ( g_Layout_enableDetachableMenus.m_value ) {
1806                 menu_tearoff( menu );
1807         }
1808
1809         create_menu_item_with_mnemonic( menu, "_New Map", "NewMap" );
1810         menu_separator( menu );
1811
1812 #if 0
1813         //++timo temporary experimental stuff for sleep mode..
1814         create_menu_item_with_mnemonic( menu, "_Sleep", "Sleep" );
1815         menu_separator( menu );
1816         // end experimental
1817 #endif
1818
1819         create_menu_item_with_mnemonic( menu, "_Open...", "OpenMap" );
1820
1821         create_menu_item_with_mnemonic( menu, "_Import...", "ImportMap" );
1822         create_menu_item_with_mnemonic( menu, "_Save", "SaveMap" );
1823         create_menu_item_with_mnemonic( menu, "Save _as...", "SaveMapAs" );
1824         create_menu_item_with_mnemonic( menu, "Save s_elected...", "SaveSelected" );
1825         menu_separator( menu );
1826         create_menu_item_with_mnemonic( menu, "Save re_gion...", "SaveRegion" );
1827         menu_separator( menu );
1828         create_menu_item_with_mnemonic( menu, "_Refresh models", "RefreshReferences" );
1829         menu_separator( menu );
1830         create_menu_item_with_mnemonic( menu, "Pro_ject settings...", "ProjectSettings" );
1831         menu_separator( menu );
1832         create_menu_item_with_mnemonic( menu, "_Pointfile...", "TogglePointfile" );
1833         menu_separator( menu );
1834         MRU_constructMenu( menu );
1835         menu_separator( menu );
1836         create_menu_item_with_mnemonic( menu, "Check for NetRadiant update (web)", "CheckForUpdate" ); // FIXME
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( "IncPatchColumn" );
2211         command_connect_accelerator( "IncPatchRow" );
2212         command_connect_accelerator( "DecPatchColumn" );
2213         command_connect_accelerator( "DecPatchRow" );
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.bmp", "OpenMap" );
2277         toolbar_append_button( toolbar, "Save the active map (CTRL + S)", "file_save.bmp", "SaveMap" );
2278 }
2279
2280 void UndoRedo_constructToolbar( GtkToolbar* toolbar ){
2281         toolbar_append_button( toolbar, "Undo (CTRL + Z)", "undo.bmp", "Undo" );
2282         toolbar_append_button( toolbar, "Redo (CTRL + Y)", "redo.bmp", "Redo" );
2283 }
2284
2285 void RotateFlip_constructToolbar( GtkToolbar* toolbar ){
2286         toolbar_append_button( toolbar, "x-axis Flip", "brush_flipx.bmp", "MirrorSelectionX" );
2287         toolbar_append_button( toolbar, "x-axis Rotate", "brush_rotatex.bmp", "RotateSelectionX" );
2288         toolbar_append_button( toolbar, "y-axis Flip", "brush_flipy.bmp", "MirrorSelectionY" );
2289         toolbar_append_button( toolbar, "y-axis Rotate", "brush_rotatey.bmp", "RotateSelectionY" );
2290         toolbar_append_button( toolbar, "z-axis Flip", "brush_flipz.bmp", "MirrorSelectionZ" );
2291         toolbar_append_button( toolbar, "z-axis Rotate", "brush_rotatez.bmp", "RotateSelectionZ" );
2292 }
2293
2294 void Select_constructToolbar( GtkToolbar* toolbar ){
2295         toolbar_append_button( toolbar, "Select touching", "selection_selecttouching.bmp", "SelectTouching" );
2296         toolbar_append_button( toolbar, "Select inside", "selection_selectinside.bmp", "SelectInside" );
2297 }
2298
2299 void CSG_constructToolbar( GtkToolbar* toolbar ){
2300         toolbar_append_button( toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.bmp", "CSGSubtract" );
2301         toolbar_append_button( toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.bmp", "CSGMerge" );
2302         toolbar_append_button( toolbar, "Hollow", "selection_makehollow.bmp", "CSGHollow" );
2303 }
2304
2305 void ComponentModes_constructToolbar( GtkToolbar* toolbar ){
2306         toolbar_append_toggle_button( toolbar, "Select Vertices (V)", "modify_vertices.bmp", "DragVertices" );
2307         toolbar_append_toggle_button( toolbar, "Select Edges (E)", "modify_edges.bmp", "DragEdges" );
2308         toolbar_append_toggle_button( toolbar, "Select Faces (F)", "modify_faces.bmp", "DragFaces" );
2309 }
2310
2311 void Clipper_constructToolbar( GtkToolbar* toolbar ){
2312
2313         toolbar_append_toggle_button( toolbar, "Clipper (X)", "view_clipper.bmp", "ToggleClipper" );
2314 }
2315
2316 void XYWnd_constructToolbar( GtkToolbar* toolbar ){
2317         toolbar_append_button( toolbar, "Change views", "view_change.bmp", "NextView" );
2318 }
2319
2320 void Manipulators_constructToolbar( GtkToolbar* toolbar ){
2321         toolbar_append_toggle_button( toolbar, "Translate (W)", "select_mousetranslate.bmp", "MouseTranslate" );
2322         toolbar_append_toggle_button( toolbar, "Rotate (R)", "select_mouserotate.bmp", "MouseRotate" );
2323         toolbar_append_toggle_button( toolbar, "Scale", "select_mousescale.bmp", "MouseScale" );
2324         toolbar_append_toggle_button( toolbar, "Resize (Q)", "select_mouseresize.bmp", "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.bmp", "TogTexLock" );
2381
2382         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2383
2384         GtkButton* g_view_entities_button = toolbar_append_button( toolbar, "Entities (N)", "entities.bmp", "ToggleEntityInspector" );
2385         GtkButton* g_view_console_button = toolbar_append_button( toolbar, "Console (O)", "console.bmp", "ToggleConsole" );
2386         GtkButton* g_view_textures_button = toolbar_append_button( toolbar, "Texture Browser (T)", "texture_browser.bmp", "ToggleTextures" );
2387         // TODO: call light inspector
2388         //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.bmp", "ToggleLightInspector");
2389
2390         gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
2391         GtkButton* g_refresh_models_button = toolbar_append_button( toolbar, "Refresh Models", "refresh_models.bmp", "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.bmp" );
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.bmp" );
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.bmp", "window2.bmp", "window3.bmp", "window4.bmp" };
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( "CheckForUpdate", FreeCaller<OpenUpdateURL>() );
3197         GlobalCommands_insert( "Exit", FreeCaller<Exit>() );
3198
3199         GlobalCommands_insert( "Undo", FreeCaller<Undo>(), Accelerator( 'Z', (GdkModifierType)GDK_CONTROL_MASK ) );
3200         GlobalCommands_insert( "Redo", FreeCaller<Redo>(), Accelerator( 'Y', (GdkModifierType)GDK_CONTROL_MASK ) );
3201         GlobalCommands_insert( "Copy", FreeCaller<Copy>(), Accelerator( 'C', (GdkModifierType)GDK_CONTROL_MASK ) );
3202         GlobalCommands_insert( "Paste", FreeCaller<Paste>(), Accelerator( 'V', (GdkModifierType)GDK_CONTROL_MASK ) );
3203         GlobalCommands_insert( "PasteToCamera", FreeCaller<PasteToCamera>(), Accelerator( 'V', (GdkModifierType)GDK_MOD1_MASK ) );
3204         GlobalCommands_insert( "CloneSelection", FreeCaller<Selection_Clone>(), Accelerator( GDK_space ) );
3205         GlobalCommands_insert( "CloneSelectionAndMakeUnique", FreeCaller<Selection_Clone_MakeUnique>(), Accelerator( GDK_space, (GdkModifierType)GDK_SHIFT_MASK ) );
3206         GlobalCommands_insert( "DeleteSelection", FreeCaller<deleteSelection>(), Accelerator( GDK_BackSpace ) );
3207         GlobalCommands_insert( "ParentSelection", FreeCaller<Scene_parentSelected>() );
3208         GlobalCommands_insert( "UnSelectSelection", FreeCaller<Selection_Deselect>(), Accelerator( GDK_Escape ) );
3209         GlobalCommands_insert( "InvertSelection", FreeCaller<Select_Invert>(), Accelerator( 'I' ) );
3210         GlobalCommands_insert( "SelectInside", FreeCaller<Select_Inside>() );
3211         GlobalCommands_insert( "SelectTouching", FreeCaller<Select_Touching>() );
3212         GlobalCommands_insert( "ExpandSelectionToEntities", FreeCaller<Scene_ExpandSelectionToEntities>(), Accelerator( 'E', (GdkModifierType)( GDK_MOD1_MASK | GDK_CONTROL_MASK ) ) );
3213         GlobalCommands_insert( "Preferences", FreeCaller<PreferencesDialog_showDialog>(), Accelerator( 'P' ) );
3214
3215         GlobalCommands_insert( "ToggleConsole", FreeCaller<Console_ToggleShow>(), Accelerator( 'O' ) );
3216         GlobalCommands_insert( "ToggleEntityInspector", FreeCaller<EntityInspector_ToggleShow>(), Accelerator( 'N' ) );
3217         GlobalCommands_insert( "EntityList", FreeCaller<EntityList_toggleShown>(), Accelerator( 'L' ) );
3218
3219         GlobalCommands_insert( "ShowHidden", FreeCaller<Select_ShowAllHidden>(), Accelerator( 'H', (GdkModifierType)GDK_SHIFT_MASK ) );
3220         GlobalCommands_insert( "HideSelected", FreeCaller<HideSelected>(), Accelerator( 'H' ) );
3221
3222         GlobalToggles_insert( "DragVertices", FreeCaller<SelectVertexMode>(), ToggleItem::AddCallbackCaller( g_vertexMode_button ), Accelerator( 'V' ) );
3223         GlobalToggles_insert( "DragEdges", FreeCaller<SelectEdgeMode>(), ToggleItem::AddCallbackCaller( g_edgeMode_button ), Accelerator( 'E' ) );
3224         GlobalToggles_insert( "DragFaces", FreeCaller<SelectFaceMode>(), ToggleItem::AddCallbackCaller( g_faceMode_button ), Accelerator( 'F' ) );
3225
3226         GlobalCommands_insert( "MirrorSelectionX", FreeCaller<Selection_Flipx>() );
3227         GlobalCommands_insert( "RotateSelectionX", FreeCaller<Selection_Rotatex>() );
3228         GlobalCommands_insert( "MirrorSelectionY", FreeCaller<Selection_Flipy>() );
3229         GlobalCommands_insert( "RotateSelectionY", FreeCaller<Selection_Rotatey>() );
3230         GlobalCommands_insert( "MirrorSelectionZ", FreeCaller<Selection_Flipz>() );
3231         GlobalCommands_insert( "RotateSelectionZ", FreeCaller<Selection_Rotatez>() );
3232
3233         GlobalCommands_insert( "ArbitraryRotation", FreeCaller<DoRotateDlg>() );
3234         GlobalCommands_insert( "ArbitraryScale", FreeCaller<DoScaleDlg>() );
3235
3236         GlobalCommands_insert( "BuildMenuCustomize", FreeCaller<DoBuildMenu>() );
3237
3238         GlobalCommands_insert( "FindBrush", FreeCaller<DoFind>() );
3239
3240         GlobalCommands_insert( "MapInfo", FreeCaller<DoMapInfo>(), Accelerator( 'M' ) );
3241
3242
3243         GlobalToggles_insert( "ToggleClipper", FreeCaller<ClipperMode>(), ToggleItem::AddCallbackCaller( g_clipper_button ), Accelerator( 'X' ) );
3244
3245         GlobalToggles_insert( "MouseTranslate", FreeCaller<TranslateMode>(), ToggleItem::AddCallbackCaller( g_translatemode_button ), Accelerator( 'W' ) );
3246         GlobalToggles_insert( "MouseRotate", FreeCaller<RotateMode>(), ToggleItem::AddCallbackCaller( g_rotatemode_button ), Accelerator( 'R' ) );
3247         GlobalToggles_insert( "MouseScale", FreeCaller<ScaleMode>(), ToggleItem::AddCallbackCaller( g_scalemode_button ) );
3248         GlobalToggles_insert( "MouseDrag", FreeCaller<DragMode>(), ToggleItem::AddCallbackCaller( g_dragmode_button ), Accelerator( 'Q' ) );
3249
3250         GlobalCommands_insert( "ColorSchemeOriginal", FreeCaller<ColorScheme_Original>() );
3251         GlobalCommands_insert( "ColorSchemeQER", FreeCaller<ColorScheme_QER>() );
3252         GlobalCommands_insert( "ColorSchemeBlackAndGreen", FreeCaller<ColorScheme_Black>() );
3253         GlobalCommands_insert( "ColorSchemeYdnar", FreeCaller<ColorScheme_Ydnar>() );
3254         GlobalCommands_insert( "ChooseTextureBackgroundColor", makeCallback( g_ColoursMenu.m_textureback ) );
3255         GlobalCommands_insert( "ChooseGridBackgroundColor", makeCallback( g_ColoursMenu.m_xyback ) );
3256         GlobalCommands_insert( "ChooseGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor ) );
3257         GlobalCommands_insert( "ChooseGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor ) );
3258         GlobalCommands_insert( "ChooseSmallGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor_alt ) );
3259         GlobalCommands_insert( "ChooseSmallGridMinorColor", makeCallback( g_ColoursMenu.m_gridminor_alt ) );
3260         GlobalCommands_insert( "ChooseGridTextColor", makeCallback( g_ColoursMenu.m_gridtext ) );
3261         GlobalCommands_insert( "ChooseGridBlockColor", makeCallback( g_ColoursMenu.m_gridblock ) );
3262         GlobalCommands_insert( "ChooseBrushColor", makeCallback( g_ColoursMenu.m_brush ) );
3263         GlobalCommands_insert( "ChooseCameraBackgroundColor", makeCallback( g_ColoursMenu.m_cameraback ) );
3264         GlobalCommands_insert( "ChooseSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush ) );
3265         GlobalCommands_insert( "ChooseCameraSelectedBrushColor", makeCallback( g_ColoursMenu.m_selectedbrush3d ) );
3266         GlobalCommands_insert( "ChooseClipperColor", makeCallback( g_ColoursMenu.m_clipper ) );
3267         GlobalCommands_insert( "ChooseOrthoViewNameColor", makeCallback( g_ColoursMenu.m_viewname ) );
3268
3269
3270         GlobalCommands_insert( "CSGSubtract", FreeCaller<CSG_Subtract>(), Accelerator( 'U', (GdkModifierType)GDK_SHIFT_MASK ) );
3271         GlobalCommands_insert( "CSGMerge", FreeCaller<CSG_Merge>(), Accelerator( 'U', (GdkModifierType)GDK_CONTROL_MASK ) );
3272         GlobalCommands_insert( "CSGHollow", FreeCaller<CSG_MakeHollow>() );
3273
3274         Grid_registerCommands();
3275
3276         GlobalCommands_insert( "SnapToGrid", FreeCaller<Selection_SnapToGrid>(), Accelerator( 'G', (GdkModifierType)GDK_CONTROL_MASK ) );
3277
3278         GlobalCommands_insert( "SelectAllOfType", FreeCaller<Select_AllOfType>(), Accelerator( 'A', (GdkModifierType)GDK_SHIFT_MASK ) );
3279
3280         GlobalCommands_insert( "TexRotateClock", FreeCaller<Texdef_RotateClockwise>(), Accelerator( GDK_Next, (GdkModifierType)GDK_SHIFT_MASK ) );
3281         GlobalCommands_insert( "TexRotateCounter", FreeCaller<Texdef_RotateAntiClockwise>(), Accelerator( GDK_Prior, (GdkModifierType)GDK_SHIFT_MASK ) );
3282         GlobalCommands_insert( "TexScaleUp", FreeCaller<Texdef_ScaleUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_CONTROL_MASK ) );
3283         GlobalCommands_insert( "TexScaleDown", FreeCaller<Texdef_ScaleDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_CONTROL_MASK ) );
3284         GlobalCommands_insert( "TexScaleLeft", FreeCaller<Texdef_ScaleLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_CONTROL_MASK ) );
3285         GlobalCommands_insert( "TexScaleRight", FreeCaller<Texdef_ScaleRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_CONTROL_MASK ) );
3286         GlobalCommands_insert( "TexShiftUp", FreeCaller<Texdef_ShiftUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_SHIFT_MASK ) );
3287         GlobalCommands_insert( "TexShiftDown", FreeCaller<Texdef_ShiftDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_SHIFT_MASK ) );
3288         GlobalCommands_insert( "TexShiftLeft", FreeCaller<Texdef_ShiftLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_SHIFT_MASK ) );
3289         GlobalCommands_insert( "TexShiftRight", FreeCaller<Texdef_ShiftRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_SHIFT_MASK ) );
3290
3291         GlobalCommands_insert( "MoveSelectionDOWN", FreeCaller<Selection_MoveDown>(), Accelerator( GDK_KP_Subtract ) );
3292         GlobalCommands_insert( "MoveSelectionUP", FreeCaller<Selection_MoveUp>(), Accelerator( GDK_KP_Add ) );
3293
3294         GlobalCommands_insert( "SelectNudgeLeft", FreeCaller<Selection_NudgeLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_MOD1_MASK ) );
3295         GlobalCommands_insert( "SelectNudgeRight", FreeCaller<Selection_NudgeRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_MOD1_MASK ) );
3296         GlobalCommands_insert( "SelectNudgeUp", FreeCaller<Selection_NudgeUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_MOD1_MASK ) );
3297         GlobalCommands_insert( "SelectNudgeDown", FreeCaller<Selection_NudgeDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_MOD1_MASK ) );
3298
3299         Patch_registerCommands();
3300         XYShow_registerCommands();
3301
3302         typedef FreeCaller1<const Selectable&, ComponentMode_SelectionChanged> ComponentModeSelectionChangedCaller;
3303         GlobalSelectionSystem().addSelectionChangeCallback( ComponentModeSelectionChangedCaller() );
3304
3305         GlobalPreferenceSystem().registerPreference( "DetachableMenus", BoolImportStringCaller( g_Layout_enableDetachableMenus.m_latched ), BoolExportStringCaller( g_Layout_enableDetachableMenus.m_latched ) );
3306         GlobalPreferenceSystem().registerPreference( "PatchToolBar", BoolImportStringCaller( g_Layout_enablePatchToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePatchToolbar.m_latched ) );
3307         GlobalPreferenceSystem().registerPreference( "PluginToolBar", BoolImportStringCaller( g_Layout_enablePluginToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePluginToolbar.m_latched ) );
3308         GlobalPreferenceSystem().registerPreference( "QE4StyleWindows", IntImportStringCaller( g_Layout_viewStyle.m_latched ), IntExportStringCaller( g_Layout_viewStyle.m_latched ) );
3309         GlobalPreferenceSystem().registerPreference( "XYHeight", IntImportStringCaller( g_layout_globals.nXYHeight ), IntExportStringCaller( g_layout_globals.nXYHeight ) );
3310         GlobalPreferenceSystem().registerPreference( "XYWidth", IntImportStringCaller( g_layout_globals.nXYWidth ), IntExportStringCaller( g_layout_globals.nXYWidth ) );
3311         GlobalPreferenceSystem().registerPreference( "CamWidth", IntImportStringCaller( g_layout_globals.nCamWidth ), IntExportStringCaller( g_layout_globals.nCamWidth ) );
3312         GlobalPreferenceSystem().registerPreference( "CamHeight", IntImportStringCaller( g_layout_globals.nCamHeight ), IntExportStringCaller( g_layout_globals.nCamHeight ) );
3313
3314         GlobalPreferenceSystem().registerPreference( "State", IntImportStringCaller( g_layout_globals.nState ), IntExportStringCaller( g_layout_globals.nState ) );
3315         GlobalPreferenceSystem().registerPreference( "PositionX", IntImportStringCaller( g_layout_globals.m_position.x ), IntExportStringCaller( g_layout_globals.m_position.x ) );
3316         GlobalPreferenceSystem().registerPreference( "PositionY", IntImportStringCaller( g_layout_globals.m_position.y ), IntExportStringCaller( g_layout_globals.m_position.y ) );
3317         GlobalPreferenceSystem().registerPreference( "Width", IntImportStringCaller( g_layout_globals.m_position.w ), IntExportStringCaller( g_layout_globals.m_position.w ) );
3318         GlobalPreferenceSystem().registerPreference( "Height", IntImportStringCaller( g_layout_globals.m_position.h ), IntExportStringCaller( g_layout_globals.m_position.h ) );
3319
3320         GlobalPreferenceSystem().registerPreference( "CamWnd", WindowPositionTrackerImportStringCaller( g_posCamWnd ), WindowPositionTrackerExportStringCaller( g_posCamWnd ) );
3321         GlobalPreferenceSystem().registerPreference( "XYWnd", WindowPositionTrackerImportStringCaller( g_posXYWnd ), WindowPositionTrackerExportStringCaller( g_posXYWnd ) );
3322         GlobalPreferenceSystem().registerPreference( "YZWnd", WindowPositionTrackerImportStringCaller( g_posYZWnd ), WindowPositionTrackerExportStringCaller( g_posYZWnd ) );
3323         GlobalPreferenceSystem().registerPreference( "XZWnd", WindowPositionTrackerImportStringCaller( g_posXZWnd ), WindowPositionTrackerExportStringCaller( g_posXZWnd ) );
3324
3325         {
3326                 const char* ENGINEPATH_ATTRIBUTE =
3327 #if defined( WIN32 )
3328                         "enginepath_win32"
3329 #elif defined( __APPLE__ )
3330                         "enginepath_macos"
3331 #elif defined( __linux__ ) || defined ( __FreeBSD__ )
3332                         "enginepath_linux"
3333 #else
3334 #error "unknown platform"
3335 #endif
3336                 ;
3337                 StringOutputStream path( 256 );
3338                 path << DirectoryCleaned( g_pGameDescription->getRequiredKeyValue( ENGINEPATH_ATTRIBUTE ) );
3339                 g_strEnginePath = path.c_str();
3340         }
3341
3342         GlobalPreferenceSystem().registerPreference( "EnginePath", CopiedStringImportStringCaller( g_strEnginePath ), CopiedStringExportStringCaller( g_strEnginePath ) );
3343
3344         g_Layout_viewStyle.useLatched();
3345         g_Layout_enableDetachableMenus.useLatched();
3346         g_Layout_enablePatchToolbar.useLatched();
3347         g_Layout_enablePluginToolbar.useLatched();
3348
3349         Layout_registerPreferencesPage();
3350         Paths_registerPreferencesPage();
3351
3352         g_brushCount.setCountChangedCallback( FreeCaller<QE_brushCountChanged>() );
3353         g_entityCount.setCountChangedCallback( FreeCaller<QE_entityCountChanged>() );
3354         GlobalEntityCreator().setCounter( &g_entityCount );
3355
3356         GLWidget_sharedContextCreated = GlobalGL_sharedContextCreated;
3357         GLWidget_sharedContextDestroyed = GlobalGL_sharedContextDestroyed;
3358
3359         GlobalEntityClassManager().attach( g_WorldspawnColourEntityClassObserver );
3360 }
3361
3362 void MainFrame_Destroy(){
3363         GlobalEntityClassManager().detach( g_WorldspawnColourEntityClassObserver );
3364
3365         GlobalEntityCreator().setCounter( 0 );
3366         g_entityCount.setCountChangedCallback( Callback() );
3367         g_brushCount.setCountChangedCallback( Callback() );
3368 }
3369
3370
3371 void GLWindow_Construct(){
3372         GlobalPreferenceSystem().registerPreference( "MouseButtons", IntImportStringCaller( g_glwindow_globals.m_nMouseType ), IntExportStringCaller( g_glwindow_globals.m_nMouseType ) );
3373 }
3374
3375 void GLWindow_Destroy(){
3376 }