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