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