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