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