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