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