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