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