Wrap more GTK
[xonotic/netradiant.git] / radiant / entityinspector.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 #include "entityinspector.h"
23
24 #include "debugging/debugging.h"
25 #include <gtk/gtk.h>
26
27 #include "ientity.h"
28 #include "ifilesystem.h"
29 #include "imodel.h"
30 #include "iscenegraph.h"
31 #include "iselection.h"
32 #include "iundo.h"
33
34 #include <map>
35 #include <set>
36 #include <gdk/gdkkeysyms.h>
37 #include <uilib/uilib.h>
38
39
40 #include "os/path.h"
41 #include "eclasslib.h"
42 #include "scenelib.h"
43 #include "generic/callback.h"
44 #include "os/file.h"
45 #include "stream/stringstream.h"
46 #include "moduleobserver.h"
47 #include "convert.h"
48 #include "stringio.h"
49
50 #include "gtkutil/accelerator.h"
51 #include "gtkutil/dialog.h"
52 #include "gtkutil/filechooser.h"
53 #include "gtkutil/messagebox.h"
54 #include "gtkutil/nonmodal.h"
55 #include "gtkutil/button.h"
56 #include "gtkutil/entry.h"
57 #include "gtkutil/container.h"
58
59 #include "qe3.h"
60 #include "gtkmisc.h"
61 #include "gtkdlgs.h"
62 #include "entity.h"
63 #include "mainframe.h"
64 #include "textureentry.h"
65 #include "groupdialog.h"
66
67 ui::Entry numeric_entry_new(){
68         auto entry = ui::Entry();
69         entry.show();
70         entry.dimensions(64, -1);
71         return entry;
72 }
73
74 namespace
75 {
76 typedef std::map<CopiedString, CopiedString> KeyValues;
77 KeyValues g_selectedKeyValues;
78 KeyValues g_selectedDefaultKeyValues;
79 }
80
81 const char* SelectedEntity_getValueForKey( const char* key ){
82         {
83                 KeyValues::const_iterator i = g_selectedKeyValues.find( key );
84                 if ( i != g_selectedKeyValues.end() ) {
85                         return ( *i ).second.c_str();
86                 }
87         }
88         {
89                 KeyValues::const_iterator i = g_selectedDefaultKeyValues.find( key );
90                 if ( i != g_selectedDefaultKeyValues.end() ) {
91                         return ( *i ).second.c_str();
92                 }
93         }
94         return "";
95 }
96
97 void Scene_EntitySetKeyValue_Selected_Undoable( const char* key, const char* value ){
98         StringOutputStream command( 256 );
99         command << "entitySetKeyValue -key " << makeQuoted( key ) << " -value " << makeQuoted( value );
100         UndoableCommand undo( command.c_str() );
101         Scene_EntitySetKeyValue_Selected( key, value );
102 }
103
104 class EntityAttribute
105 {
106 public:
107 virtual ui::Widget getWidget() const = 0;
108 virtual void update() = 0;
109 virtual void release() = 0;
110 };
111
112 class BooleanAttribute : public EntityAttribute
113 {
114 CopiedString m_key;
115 ui::CheckButton m_check;
116
117 static gboolean toggled( ui::Widget widget, BooleanAttribute* self ){
118         self->apply();
119         return FALSE;
120 }
121 public:
122 BooleanAttribute( const char* key ) :
123         m_key( key ),
124         m_check( ui::null ){
125         auto check = ui::CheckButton();
126         check.show();
127
128         m_check = check;
129
130         guint handler = check.connect( "toggled", G_CALLBACK( toggled ), this );
131         g_object_set_data( G_OBJECT( check ), "handler", gint_to_pointer( handler ) );
132
133         update();
134 }
135 ui::Widget getWidget() const {
136         return m_check;
137 }
138 void release(){
139         delete this;
140 }
141 void apply(){
142         Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), m_check.active() ? "1" : "0" );
143 }
144 typedef MemberCaller<BooleanAttribute, &BooleanAttribute::apply> ApplyCaller;
145
146 void update(){
147         const char* value = SelectedEntity_getValueForKey( m_key.c_str() );
148         if ( !string_empty( value ) ) {
149                 toggle_button_set_active_no_signal( m_check, atoi( value ) != 0 );
150         }
151         else
152         {
153                 toggle_button_set_active_no_signal( m_check, false );
154         }
155 }
156 typedef MemberCaller<BooleanAttribute, &BooleanAttribute::update> UpdateCaller;
157 };
158
159
160 class StringAttribute : public EntityAttribute
161 {
162 CopiedString m_key;
163 ui::Entry m_entry;
164 NonModalEntry m_nonModal;
165 public:
166 StringAttribute( const char* key ) :
167         m_key( key ),
168         m_entry( ui::null ),
169         m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){
170         auto entry = ui::Entry();
171         entry.show();
172         entry.dimensions(50, -1);
173
174         m_entry = entry;
175         m_nonModal.connect( m_entry );
176 }
177 ui::Widget getWidget() const {
178         return m_entry;
179 }
180 ui::Entry getEntry() const {
181         return m_entry;
182 }
183
184 void release(){
185         delete this;
186 }
187 void apply(){
188         StringOutputStream value( 64 );
189         value << m_entry.text();
190         Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() );
191 }
192 typedef MemberCaller<StringAttribute, &StringAttribute::apply> ApplyCaller;
193
194 void update(){
195         StringOutputStream value( 64 );
196         value << SelectedEntity_getValueForKey( m_key.c_str() );
197         m_entry.text(value.c_str());
198 }
199 typedef MemberCaller<StringAttribute, &StringAttribute::update> UpdateCaller;
200 };
201
202 class ShaderAttribute : public StringAttribute
203 {
204 public:
205 ShaderAttribute( const char* key ) : StringAttribute( key ){
206         GlobalShaderEntryCompletion::instance().connect( StringAttribute::getEntry() );
207 }
208 };
209
210
211 class ModelAttribute : public EntityAttribute
212 {
213 CopiedString m_key;
214 BrowsedPathEntry m_entry;
215 NonModalEntry m_nonModal;
216 public:
217 ModelAttribute( const char* key ) :
218         m_key( key ),
219         m_entry( BrowseCaller( *this ) ),
220         m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){
221         m_nonModal.connect( m_entry.m_entry.m_entry );
222 }
223 void release(){
224         delete this;
225 }
226 ui::Widget getWidget() const {
227         return m_entry.m_entry.m_frame;
228 }
229 void apply(){
230         StringOutputStream value( 64 );
231         value << m_entry.m_entry.m_entry.text();
232         Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() );
233 }
234 typedef MemberCaller<ModelAttribute, &ModelAttribute::apply> ApplyCaller;
235 void update(){
236         StringOutputStream value( 64 );
237         value << SelectedEntity_getValueForKey( m_key.c_str() );
238         m_entry.m_entry.m_entry.text(value.c_str());
239 }
240 typedef MemberCaller<ModelAttribute, &ModelAttribute::update> UpdateCaller;
241 void browse( const BrowsedPathEntry::SetPathCallback& setPath ){
242         const char *filename = misc_model_dialog( ui::Widget(gtk_widget_get_toplevel( GTK_WIDGET( m_entry.m_entry.m_frame ) ) ));
243
244         if ( filename != 0 ) {
245                 setPath( filename );
246                 apply();
247         }
248 }
249 typedef MemberCaller1<ModelAttribute, const BrowsedPathEntry::SetPathCallback&, &ModelAttribute::browse> BrowseCaller;
250 };
251
252 const char* browse_sound( ui::Widget parent ){
253         StringOutputStream buffer( 1024 );
254
255         buffer << g_qeglobals.m_userGamePath.c_str() << "sound/";
256
257         if ( !file_readable( buffer.c_str() ) ) {
258                 // just go to fsmain
259                 buffer.clear();
260                 buffer << g_qeglobals.m_userGamePath.c_str() << "/";
261         }
262
263         const char* filename = parent.file_dialog(TRUE, "Open Wav File", buffer.c_str(), "sound" );
264         if ( filename != 0 ) {
265                 const char* relative = path_make_relative( filename, GlobalFileSystem().findRoot( filename ) );
266                 if ( relative == filename ) {
267                         globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n";
268                 }
269                 return relative;
270         }
271         return filename;
272 }
273
274 class SoundAttribute : public EntityAttribute
275 {
276 CopiedString m_key;
277 BrowsedPathEntry m_entry;
278 NonModalEntry m_nonModal;
279 public:
280 SoundAttribute( const char* key ) :
281         m_key( key ),
282         m_entry( BrowseCaller( *this ) ),
283         m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){
284         m_nonModal.connect( m_entry.m_entry.m_entry );
285 }
286 void release(){
287         delete this;
288 }
289 ui::Widget getWidget() const {
290         return ui::Widget(GTK_WIDGET( m_entry.m_entry.m_frame ));
291 }
292 void apply(){
293         StringOutputStream value( 64 );
294         value << m_entry.m_entry.m_entry.text();
295         Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), value.c_str() );
296 }
297 typedef MemberCaller<SoundAttribute, &SoundAttribute::apply> ApplyCaller;
298 void update(){
299         StringOutputStream value( 64 );
300         value << SelectedEntity_getValueForKey( m_key.c_str() );
301         m_entry.m_entry.m_entry.text(value.c_str());
302 }
303 typedef MemberCaller<SoundAttribute, &SoundAttribute::update> UpdateCaller;
304 void browse( const BrowsedPathEntry::SetPathCallback& setPath ){
305         const char *filename = browse_sound( ui::Widget(gtk_widget_get_toplevel( GTK_WIDGET( m_entry.m_entry.m_frame ) )) );
306
307         if ( filename != 0 ) {
308                 setPath( filename );
309                 apply();
310         }
311 }
312 typedef MemberCaller1<SoundAttribute, const BrowsedPathEntry::SetPathCallback&, &SoundAttribute::browse> BrowseCaller;
313 };
314
315 inline double angle_normalised( double angle ){
316         return float_mod( angle, 360.0 );
317 }
318
319 class AngleAttribute : public EntityAttribute
320 {
321 CopiedString m_key;
322 ui::Entry m_entry;
323 NonModalEntry m_nonModal;
324 public:
325 AngleAttribute( const char* key ) :
326         m_key( key ),
327         m_entry( ui::null ),
328         m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){
329         auto entry = numeric_entry_new();
330         m_entry = entry;
331         m_nonModal.connect( m_entry );
332 }
333 void release(){
334         delete this;
335 }
336 ui::Widget getWidget() const {
337         return ui::Widget(GTK_WIDGET( m_entry ));
338 }
339 void apply(){
340         StringOutputStream angle( 32 );
341         angle << angle_normalised( entry_get_float( m_entry ) );
342         Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), angle.c_str() );
343 }
344 typedef MemberCaller<AngleAttribute, &AngleAttribute::apply> ApplyCaller;
345
346 void update(){
347         const char* value = SelectedEntity_getValueForKey( m_key.c_str() );
348         if ( !string_empty( value ) ) {
349                 StringOutputStream angle( 32 );
350                 angle << angle_normalised( atof( value ) );
351                 m_entry.text(angle.c_str());
352         }
353         else
354         {
355                 m_entry.text("0");
356         }
357 }
358 typedef MemberCaller<AngleAttribute, &AngleAttribute::update> UpdateCaller;
359 };
360
361 namespace
362 {
363 typedef const char* String;
364 const String buttons[] = { "up", "down", "z-axis" };
365 }
366
367 class DirectionAttribute : public EntityAttribute
368 {
369 CopiedString m_key;
370 ui::Entry m_entry;
371 NonModalEntry m_nonModal;
372 RadioHBox m_radio;
373 NonModalRadio m_nonModalRadio;
374 ui::HBox m_hbox{ui::null};
375 public:
376 DirectionAttribute( const char* key ) :
377         m_key( key ),
378         m_entry( ui::null ),
379         m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ),
380         m_radio( RadioHBox_new( STRING_ARRAY_RANGE( buttons ) ) ),
381         m_nonModalRadio( ApplyRadioCaller( *this ) ){
382         auto entry = numeric_entry_new();
383         m_entry = entry;
384         m_nonModal.connect( m_entry );
385
386         m_nonModalRadio.connect( m_radio.m_radio );
387
388         m_hbox = ui::HBox( FALSE, 4 );
389         m_hbox.show();
390
391         gtk_box_pack_start( GTK_BOX( m_hbox ), GTK_WIDGET( m_radio.m_hbox ), TRUE, TRUE, 0 );
392         gtk_box_pack_start( GTK_BOX( m_hbox ), GTK_WIDGET( m_entry ), TRUE, TRUE, 0 );
393 }
394 void release(){
395         delete this;
396 }
397 ui::Widget getWidget() const {
398         return ui::Widget(GTK_WIDGET( m_hbox ));
399 }
400 void apply(){
401         StringOutputStream angle( 32 );
402         angle << angle_normalised( entry_get_float( m_entry ) );
403         Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), angle.c_str() );
404 }
405 typedef MemberCaller<DirectionAttribute, &DirectionAttribute::apply> ApplyCaller;
406
407 void update(){
408         const char* value = SelectedEntity_getValueForKey( m_key.c_str() );
409         if ( !string_empty( value ) ) {
410                 float f = float(atof( value ) );
411                 if ( f == -1 ) {
412                         gtk_widget_set_sensitive( GTK_WIDGET( m_entry ), FALSE );
413                         radio_button_set_active_no_signal( m_radio.m_radio, 0 );
414                         m_entry.text("");
415                 }
416                 else if ( f == -2 ) {
417                         gtk_widget_set_sensitive( GTK_WIDGET( m_entry ), FALSE );
418                         radio_button_set_active_no_signal( m_radio.m_radio, 1 );
419                         m_entry.text("");
420                 }
421                 else
422                 {
423                         gtk_widget_set_sensitive( GTK_WIDGET( m_entry ), TRUE );
424                         radio_button_set_active_no_signal( m_radio.m_radio, 2 );
425                         StringOutputStream angle( 32 );
426                         angle << angle_normalised( f );
427                         m_entry.text(angle.c_str());
428                 }
429         }
430         else
431         {
432                 m_entry.text("0");
433         }
434 }
435 typedef MemberCaller<DirectionAttribute, &DirectionAttribute::update> UpdateCaller;
436
437 void applyRadio(){
438         int index = radio_button_get_active( m_radio.m_radio );
439         if ( index == 0 ) {
440                 Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), "-1" );
441         }
442         else if ( index == 1 ) {
443                 Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), "-2" );
444         }
445         else if ( index == 2 ) {
446                 apply();
447         }
448 }
449 typedef MemberCaller<DirectionAttribute, &DirectionAttribute::applyRadio> ApplyRadioCaller;
450 };
451
452
453 class AnglesEntry
454 {
455 public:
456 ui::Entry m_roll;
457 ui::Entry m_pitch;
458 ui::Entry m_yaw;
459 AnglesEntry() : m_roll( ui::null ), m_pitch( ui::null ), m_yaw( ui::null ){
460 }
461 };
462
463 typedef BasicVector3<double> DoubleVector3;
464
465 class AnglesAttribute : public EntityAttribute
466 {
467 CopiedString m_key;
468 AnglesEntry m_angles;
469 NonModalEntry m_nonModal;
470 ui::HBox m_hbox;
471 public:
472 AnglesAttribute( const char* key ) :
473         m_key( key ),
474         m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ),
475         m_hbox(ui::HBox( TRUE, 4 ))
476 {
477         m_hbox.show();
478         {
479                 auto entry = numeric_entry_new();
480                 gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 );
481                 m_angles.m_pitch = entry;
482                 m_nonModal.connect( m_angles.m_pitch );
483         }
484         {
485                 auto entry = numeric_entry_new();
486                 gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 );
487                 m_angles.m_yaw = entry;
488                 m_nonModal.connect( m_angles.m_yaw );
489         }
490         {
491                 auto entry = numeric_entry_new();
492                 gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 );
493                 m_angles.m_roll = entry;
494                 m_nonModal.connect( m_angles.m_roll );
495         }
496 }
497 void release(){
498         delete this;
499 }
500 ui::Widget getWidget() const {
501         return ui::Widget(GTK_WIDGET( m_hbox ));
502 }
503 void apply(){
504         StringOutputStream angles( 64 );
505         angles << angle_normalised( entry_get_float( m_angles.m_pitch ) )
506                    << " " << angle_normalised( entry_get_float( m_angles.m_yaw ) )
507                    << " " << angle_normalised( entry_get_float( m_angles.m_roll ) );
508         Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), angles.c_str() );
509 }
510 typedef MemberCaller<AnglesAttribute, &AnglesAttribute::apply> ApplyCaller;
511
512 void update(){
513         StringOutputStream angle( 32 );
514         const char* value = SelectedEntity_getValueForKey( m_key.c_str() );
515         if ( !string_empty( value ) ) {
516                 DoubleVector3 pitch_yaw_roll;
517                 if ( !string_parse_vector3( value, pitch_yaw_roll ) ) {
518                         pitch_yaw_roll = DoubleVector3( 0, 0, 0 );
519                 }
520
521                 angle << angle_normalised( pitch_yaw_roll.x() );
522                 m_angles.m_pitch.text(angle.c_str());
523                 angle.clear();
524
525                 angle << angle_normalised( pitch_yaw_roll.y() );
526                 m_angles.m_yaw.text(angle.c_str());
527                 angle.clear();
528
529                 angle << angle_normalised( pitch_yaw_roll.z() );
530                 m_angles.m_roll.text(angle.c_str());
531                 angle.clear();
532         }
533         else
534         {
535                 m_angles.m_pitch.text("0");
536                 m_angles.m_yaw.text("0");
537                 m_angles.m_roll.text("0");
538         }
539 }
540 typedef MemberCaller<AnglesAttribute, &AnglesAttribute::update> UpdateCaller;
541 };
542
543 class Vector3Entry
544 {
545 public:
546 ui::Entry m_x;
547 ui::Entry m_y;
548 ui::Entry m_z;
549 Vector3Entry() : m_x( ui::null ), m_y( ui::null ), m_z( ui::null ){
550 }
551 };
552
553 class Vector3Attribute : public EntityAttribute
554 {
555 CopiedString m_key;
556 Vector3Entry m_vector3;
557 NonModalEntry m_nonModal;
558 ui::Box m_hbox{ui::null};
559 public:
560 Vector3Attribute( const char* key ) :
561         m_key( key ),
562         m_nonModal( ApplyCaller( *this ), UpdateCaller( *this ) ){
563         m_hbox = ui::HBox( TRUE, 4 );
564         m_hbox.show();
565         {
566                 auto entry = numeric_entry_new();
567                 gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 );
568                 m_vector3.m_x = entry;
569                 m_nonModal.connect( m_vector3.m_x );
570         }
571         {
572                 auto entry = numeric_entry_new();
573                 gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 );
574                 m_vector3.m_y = entry;
575                 m_nonModal.connect( m_vector3.m_y );
576         }
577         {
578                 auto entry = numeric_entry_new();
579                 gtk_box_pack_start( m_hbox, GTK_WIDGET( entry ), TRUE, TRUE, 0 );
580                 m_vector3.m_z = entry;
581                 m_nonModal.connect( m_vector3.m_z );
582         }
583 }
584 void release(){
585         delete this;
586 }
587 ui::Widget getWidget() const {
588         return ui::Widget(GTK_WIDGET( m_hbox ));
589 }
590 void apply(){
591         StringOutputStream vector3( 64 );
592         vector3 << entry_get_float( m_vector3.m_x )
593                         << " " << entry_get_float( m_vector3.m_y )
594                         << " " << entry_get_float( m_vector3.m_z );
595         Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), vector3.c_str() );
596 }
597 typedef MemberCaller<Vector3Attribute, &Vector3Attribute::apply> ApplyCaller;
598
599 void update(){
600         StringOutputStream buffer( 32 );
601         const char* value = SelectedEntity_getValueForKey( m_key.c_str() );
602         if ( !string_empty( value ) ) {
603                 DoubleVector3 x_y_z;
604                 if ( !string_parse_vector3( value, x_y_z ) ) {
605                         x_y_z = DoubleVector3( 0, 0, 0 );
606                 }
607
608                 buffer << x_y_z.x();
609                 m_vector3.m_x.text(buffer.c_str());
610                 buffer.clear();
611
612                 buffer << x_y_z.y();
613                 m_vector3.m_y.text(buffer.c_str());
614                 buffer.clear();
615
616                 buffer << x_y_z.z();
617                 m_vector3.m_z.text(buffer.c_str());
618                 buffer.clear();
619         }
620         else
621         {
622                 m_vector3.m_x.text("0");
623                 m_vector3.m_y.text("0");
624                 m_vector3.m_z.text("0");
625         }
626 }
627 typedef MemberCaller<Vector3Attribute, &Vector3Attribute::update> UpdateCaller;
628 };
629
630 class NonModalComboBox
631 {
632 Callback m_changed;
633 guint m_changedHandler;
634
635 static gboolean changed( GtkComboBox *widget, NonModalComboBox* self ){
636         self->m_changed();
637         return FALSE;
638 }
639
640 public:
641 NonModalComboBox( const Callback& changed ) : m_changed( changed ), m_changedHandler( 0 ){
642 }
643 void connect( ui::ComboBox combo ){
644         m_changedHandler = combo.connect( "changed", G_CALLBACK( changed ), this );
645 }
646 void setActive( ui::ComboBox combo, int value ){
647         g_signal_handler_disconnect( G_OBJECT( combo ), m_changedHandler );
648         gtk_combo_box_set_active( combo, value );
649         connect( combo );
650 }
651 };
652
653 class ListAttribute : public EntityAttribute
654 {
655 CopiedString m_key;
656 ui::ComboBox m_combo;
657 NonModalComboBox m_nonModal;
658 const ListAttributeType& m_type;
659 public:
660 ListAttribute( const char* key, const ListAttributeType& type ) :
661         m_key( key ),
662         m_combo( 0 ),
663         m_nonModal( ApplyCaller( *this ) ),
664         m_type( type ){
665         auto combo = ui::ComboBoxText();
666
667         for ( ListAttributeType::const_iterator i = type.begin(); i != type.end(); ++i )
668         {
669                 gtk_combo_box_text_append_text( GTK_COMBO_BOX_TEXT( combo ), ( *i ).first.c_str() );
670         }
671
672         combo.show();
673         m_nonModal.connect( combo );
674
675         m_combo = combo;
676 }
677 void release(){
678         delete this;
679 }
680 ui::Widget getWidget() const {
681         return ui::Widget(GTK_WIDGET( m_combo ));
682 }
683 void apply(){
684         Scene_EntitySetKeyValue_Selected_Undoable( m_key.c_str(), m_type[gtk_combo_box_get_active( m_combo )].second.c_str() );
685 }
686 typedef MemberCaller<ListAttribute, &ListAttribute::apply> ApplyCaller;
687
688 void update(){
689         const char* value = SelectedEntity_getValueForKey( m_key.c_str() );
690         ListAttributeType::const_iterator i = m_type.findValue( value );
691         if ( i != m_type.end() ) {
692                 m_nonModal.setActive( m_combo, static_cast<int>( std::distance( m_type.begin(), i ) ) );
693         }
694         else
695         {
696                 m_nonModal.setActive( m_combo, 0 );
697         }
698 }
699 typedef MemberCaller<ListAttribute, &ListAttribute::update> UpdateCaller;
700 };
701
702
703 namespace
704 {
705 ui::Widget g_entity_split1;
706 ui::Widget g_entity_split2;
707 int g_entitysplit1_position;
708 int g_entitysplit2_position;
709
710 bool g_entityInspector_windowConstructed = false;
711
712 GtkTreeView* g_entityClassList;
713 ui::TextView g_entityClassComment;
714
715 GtkCheckButton* g_entitySpawnflagsCheck[MAX_FLAGS];
716
717 ui::Entry g_entityKeyEntry;
718 ui::Entry g_entityValueEntry;
719
720 ui::ListStore g_entlist_store{ui::null};
721 ui::ListStore g_entprops_store{ui::null};
722 const EntityClass* g_current_flags = 0;
723 const EntityClass* g_current_comment = 0;
724 const EntityClass* g_current_attributes = 0;
725
726 // the number of active spawnflags
727 int g_spawnflag_count;
728 // table: index, match spawnflag item to the spawnflag index (i.e. which bit)
729 int spawn_table[MAX_FLAGS];
730 // we change the layout depending on how many spawn flags we need to display
731 // the table is a 4x4 in which we need to put the comment box g_entityClassComment and the spawn flags..
732 GtkTable* g_spawnflagsTable;
733
734 ui::VBox g_attributeBox{ui::null};
735 typedef std::vector<EntityAttribute*> EntityAttributes;
736 EntityAttributes g_entityAttributes;
737 }
738
739 void GlobalEntityAttributes_clear(){
740         for ( EntityAttributes::iterator i = g_entityAttributes.begin(); i != g_entityAttributes.end(); ++i )
741         {
742                 ( *i )->release();
743         }
744         g_entityAttributes.clear();
745 }
746
747 class GetKeyValueVisitor : public Entity::Visitor
748 {
749 KeyValues& m_keyvalues;
750 public:
751 GetKeyValueVisitor( KeyValues& keyvalues )
752         : m_keyvalues( keyvalues ){
753 }
754
755 void visit( const char* key, const char* value ){
756         m_keyvalues.insert( KeyValues::value_type( CopiedString( key ), CopiedString( value ) ) );
757 }
758
759 };
760
761 void Entity_GetKeyValues( const Entity& entity, KeyValues& keyvalues, KeyValues& defaultValues ){
762         GetKeyValueVisitor visitor( keyvalues );
763
764         entity.forEachKeyValue( visitor );
765
766         const EntityClassAttributes& attributes = entity.getEntityClass().m_attributes;
767
768         for ( EntityClassAttributes::const_iterator i = attributes.begin(); i != attributes.end(); ++i )
769         {
770                 defaultValues.insert( KeyValues::value_type( ( *i ).first, ( *i ).second.m_value ) );
771         }
772 }
773
774 void Entity_GetKeyValues_Selected( KeyValues& keyvalues, KeyValues& defaultValues ){
775         class EntityGetKeyValues : public SelectionSystem::Visitor
776         {
777         KeyValues& m_keyvalues;
778         KeyValues& m_defaultValues;
779         mutable std::set<Entity*> m_visited;
780 public:
781         EntityGetKeyValues( KeyValues& keyvalues, KeyValues& defaultValues )
782                 : m_keyvalues( keyvalues ), m_defaultValues( defaultValues ){
783         }
784         void visit( scene::Instance& instance ) const {
785                 Entity* entity = Node_getEntity( instance.path().top() );
786                 if ( entity == 0 && instance.path().size() != 1 ) {
787                         entity = Node_getEntity( instance.path().parent() );
788                 }
789                 if ( entity != 0 && m_visited.insert( entity ).second ) {
790                         Entity_GetKeyValues( *entity, m_keyvalues, m_defaultValues );
791                 }
792         }
793         } visitor( keyvalues, defaultValues );
794         GlobalSelectionSystem().foreachSelected( visitor );
795 }
796
797 const char* keyvalues_valueforkey( KeyValues& keyvalues, const char* key ){
798         KeyValues::iterator i = keyvalues.find( CopiedString( key ) );
799         if ( i != keyvalues.end() ) {
800                 return ( *i ).second.c_str();
801         }
802         return "";
803 }
804
805 class EntityClassListStoreAppend : public EntityClassVisitor
806 {
807 ui::ListStore store;
808 public:
809 EntityClassListStoreAppend( ui::ListStore store_ ) : store( store_ ){
810 }
811 void visit( EntityClass* e ){
812         GtkTreeIter iter;
813         gtk_list_store_append( store, &iter );
814         gtk_list_store_set( store, &iter, 0, e->name(), 1, e, -1 );
815 }
816 };
817
818 void EntityClassList_fill(){
819         EntityClassListStoreAppend append( g_entlist_store );
820         GlobalEntityClassManager().forEach( append );
821 }
822
823 void EntityClassList_clear(){
824         gtk_list_store_clear( g_entlist_store );
825 }
826
827 void SetComment( EntityClass* eclass ){
828         if ( eclass == g_current_comment ) {
829                 return;
830         }
831
832         g_current_comment = eclass;
833
834         g_entityClassComment.text(eclass->comments());
835 }
836
837 void SurfaceFlags_setEntityClass( EntityClass* eclass ){
838         if ( eclass == g_current_flags ) {
839                 return;
840         }
841
842         g_current_flags = eclass;
843
844         int spawnflag_count = 0;
845
846         {
847                 // do a first pass to count the spawn flags, don't touch the widgets, we don't know in what state they are
848                 for ( int i = 0 ; i < MAX_FLAGS ; i++ )
849                 {
850                         if ( eclass->flagnames[i] && eclass->flagnames[i][0] != 0 && strcmp( eclass->flagnames[i],"-" ) ) {
851                                 spawn_table[spawnflag_count] = i;
852                                 spawnflag_count++;
853                         }
854                 }
855         }
856
857         // disable all remaining boxes
858         // NOTE: these boxes might not even be on display
859         {
860                 for ( int i = 0; i < g_spawnflag_count; ++i )
861                 {
862                         auto widget = ui::Widget(GTK_WIDGET(g_entitySpawnflagsCheck[i]));
863                         auto label = ui::Label(GTK_LABEL(gtk_bin_get_child(GTK_BIN(widget))));
864                         label.text(" ");
865                         gtk_widget_hide( widget );
866                         g_object_ref( widget );
867                         gtk_container_remove( GTK_CONTAINER( g_spawnflagsTable ), widget );
868                 }
869         }
870
871         g_spawnflag_count = spawnflag_count;
872
873         {
874                 for ( int i = 0; i < g_spawnflag_count; ++i )
875                 {
876                         ui::Widget widget = ui::Widget(GTK_WIDGET( g_entitySpawnflagsCheck[i] ));
877                         widget.show();
878
879                         StringOutputStream str( 16 );
880                         str << LowerCase( eclass->flagnames[spawn_table[i]] );
881
882                         gtk_table_attach( g_spawnflagsTable, widget, i % 4, i % 4 + 1, i / 4, i / 4 + 1,
883                                                           (GtkAttachOptions)( GTK_FILL ),
884                                                           (GtkAttachOptions)( GTK_FILL ), 0, 0 );
885                         widget.unref();
886
887                         auto label = ui::Label(GTK_LABEL(gtk_bin_get_child(GTK_BIN(widget)) ));
888                         label.text(str.c_str());
889                 }
890         }
891 }
892
893 void EntityClassList_selectEntityClass( EntityClass* eclass ){
894         GtkTreeModel* model = GTK_TREE_MODEL( g_entlist_store );
895         GtkTreeIter iter;
896         for ( gboolean good = gtk_tree_model_get_iter_first( model, &iter ); good != FALSE; good = gtk_tree_model_iter_next( model, &iter ) )
897         {
898                 char* text;
899                 gtk_tree_model_get( model, &iter, 0, &text, -1 );
900                 if ( strcmp( text, eclass->name() ) == 0 ) {
901                         GtkTreeView* view = g_entityClassList;
902                         GtkTreePath* path = gtk_tree_model_get_path( model, &iter );
903                         gtk_tree_selection_select_path( gtk_tree_view_get_selection( view ), path );
904                         if ( gtk_widget_get_realized( GTK_WIDGET(view) ) ) {
905                                 gtk_tree_view_scroll_to_cell( view, path, 0, FALSE, 0, 0 );
906                         }
907                         gtk_tree_path_free( path );
908                         good = FALSE;
909                 }
910                 g_free( text );
911         }
912 }
913
914 void EntityInspector_appendAttribute( const char* name, EntityAttribute& attribute ){
915         auto row = DialogRow_new( name, attribute.getWidget() );
916         DialogVBox_packRow( ui::VBox(g_attributeBox), row );
917 }
918
919
920 template<typename Attribute>
921 class StatelessAttributeCreator
922 {
923 public:
924 static EntityAttribute* create( const char* name ){
925         return new Attribute( name );
926 }
927 };
928
929 class EntityAttributeFactory
930 {
931 typedef EntityAttribute* ( *CreateFunc )( const char* name );
932 typedef std::map<const char*, CreateFunc, RawStringLess> Creators;
933 Creators m_creators;
934 public:
935 EntityAttributeFactory(){
936         m_creators.insert( Creators::value_type( "string", &StatelessAttributeCreator<StringAttribute>::create ) );
937         m_creators.insert( Creators::value_type( "color", &StatelessAttributeCreator<StringAttribute>::create ) );
938         m_creators.insert( Creators::value_type( "integer", &StatelessAttributeCreator<StringAttribute>::create ) );
939         m_creators.insert( Creators::value_type( "real", &StatelessAttributeCreator<StringAttribute>::create ) );
940         m_creators.insert( Creators::value_type( "shader", &StatelessAttributeCreator<ShaderAttribute>::create ) );
941         m_creators.insert( Creators::value_type( "boolean", &StatelessAttributeCreator<BooleanAttribute>::create ) );
942         m_creators.insert( Creators::value_type( "angle", &StatelessAttributeCreator<AngleAttribute>::create ) );
943         m_creators.insert( Creators::value_type( "direction", &StatelessAttributeCreator<DirectionAttribute>::create ) );
944         m_creators.insert( Creators::value_type( "angles", &StatelessAttributeCreator<AnglesAttribute>::create ) );
945         m_creators.insert( Creators::value_type( "model", &StatelessAttributeCreator<ModelAttribute>::create ) );
946         m_creators.insert( Creators::value_type( "sound", &StatelessAttributeCreator<SoundAttribute>::create ) );
947         m_creators.insert( Creators::value_type( "vector3", &StatelessAttributeCreator<Vector3Attribute>::create ) );
948         m_creators.insert( Creators::value_type( "real3", &StatelessAttributeCreator<Vector3Attribute>::create ) );
949 }
950 EntityAttribute* create( const char* type, const char* name ){
951         Creators::iterator i = m_creators.find( type );
952         if ( i != m_creators.end() ) {
953                 return ( *i ).second( name );
954         }
955         const ListAttributeType* listType = GlobalEntityClassManager().findListType( type );
956         if ( listType != 0 ) {
957                 return new ListAttribute( name, *listType );
958         }
959         return 0;
960 }
961 };
962
963 typedef Static<EntityAttributeFactory> GlobalEntityAttributeFactory;
964
965 void EntityInspector_setEntityClass( EntityClass *eclass ){
966         EntityClassList_selectEntityClass( eclass );
967         SurfaceFlags_setEntityClass( eclass );
968
969         if ( eclass != g_current_attributes ) {
970                 g_current_attributes = eclass;
971
972                 container_remove_all( g_attributeBox );
973                 GlobalEntityAttributes_clear();
974
975                 for ( EntityClassAttributes::const_iterator i = eclass->m_attributes.begin(); i != eclass->m_attributes.end(); ++i )
976                 {
977                         EntityAttribute* attribute = GlobalEntityAttributeFactory::instance().create( ( *i ).second.m_type.c_str(), ( *i ).first.c_str() );
978                         if ( attribute != 0 ) {
979                                 g_entityAttributes.push_back( attribute );
980                                 EntityInspector_appendAttribute( EntityClassAttributePair_getName( *i ), *g_entityAttributes.back() );
981                         }
982                 }
983         }
984 }
985
986 void EntityInspector_updateSpawnflags(){
987         {
988                 int f = atoi( SelectedEntity_getValueForKey( "spawnflags" ) );
989                 for ( int i = 0; i < g_spawnflag_count; ++i )
990                 {
991                         int v = !!( f & ( 1 << spawn_table[i] ) );
992
993                         toggle_button_set_active_no_signal( ui::ToggleButton(GTK_TOGGLE_BUTTON( g_entitySpawnflagsCheck[i] )), v );
994                 }
995         }
996         {
997                 // take care of the remaining ones
998                 for ( int i = g_spawnflag_count; i < MAX_FLAGS; ++i )
999                 {
1000                         toggle_button_set_active_no_signal( ui::ToggleButton(GTK_TOGGLE_BUTTON( g_entitySpawnflagsCheck[i] )), FALSE );
1001                 }
1002         }
1003 }
1004
1005 void EntityInspector_applySpawnflags(){
1006         int f, i, v;
1007         char sz[32];
1008
1009         f = 0;
1010         for ( i = 0; i < g_spawnflag_count; ++i )
1011         {
1012                 v = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( g_entitySpawnflagsCheck[i] ) );
1013                 f |= v << spawn_table[i];
1014         }
1015
1016         sprintf( sz, "%i", f );
1017         const char* value = ( f == 0 ) ? "" : sz;
1018
1019         {
1020                 StringOutputStream command;
1021                 command << "entitySetFlags -flags " << f;
1022                 UndoableCommand undo( "entitySetSpawnflags" );
1023
1024                 Scene_EntitySetKeyValue_Selected( "spawnflags", value );
1025         }
1026 }
1027
1028
1029 void EntityInspector_updateKeyValues(){
1030         g_selectedKeyValues.clear();
1031         g_selectedDefaultKeyValues.clear();
1032         Entity_GetKeyValues_Selected( g_selectedKeyValues, g_selectedDefaultKeyValues );
1033
1034         EntityInspector_setEntityClass( GlobalEntityClassManager().findOrInsert( keyvalues_valueforkey( g_selectedKeyValues, "classname" ), false ) );
1035
1036         EntityInspector_updateSpawnflags();
1037
1038         ui::ListStore store = g_entprops_store;
1039
1040         // save current key/val pair around filling epair box
1041         // row_select wipes it and sets to first in list
1042         CopiedString strKey( g_entityKeyEntry.text() );
1043         CopiedString strVal( g_entityValueEntry.text() );
1044
1045         gtk_list_store_clear( store );
1046         // Walk through list and add pairs
1047         for ( KeyValues::iterator i = g_selectedKeyValues.begin(); i != g_selectedKeyValues.end(); ++i )
1048         {
1049                 GtkTreeIter iter;
1050                 gtk_list_store_append( store, &iter );
1051                 StringOutputStream key( 64 );
1052                 key << ( *i ).first.c_str();
1053                 StringOutputStream value( 64 );
1054                 value << ( *i ).second.c_str();
1055                 gtk_list_store_set( store, &iter, 0, key.c_str(), 1, value.c_str(), -1 );
1056         }
1057
1058         g_entityKeyEntry.text( strKey.c_str() );
1059         g_entityValueEntry.text( strVal.c_str() );
1060
1061         for ( EntityAttributes::const_iterator i = g_entityAttributes.begin(); i != g_entityAttributes.end(); ++i )
1062         {
1063                 ( *i )->update();
1064         }
1065 }
1066
1067 class EntityInspectorDraw
1068 {
1069 IdleDraw m_idleDraw;
1070 public:
1071 EntityInspectorDraw() : m_idleDraw( FreeCaller<EntityInspector_updateKeyValues>( ) ){
1072 }
1073 void queueDraw(){
1074         m_idleDraw.queueDraw();
1075 }
1076 };
1077
1078 EntityInspectorDraw g_EntityInspectorDraw;
1079
1080
1081 void EntityInspector_keyValueChanged(){
1082         g_EntityInspectorDraw.queueDraw();
1083 }
1084 void EntityInspector_selectionChanged( const Selectable& ){
1085         EntityInspector_keyValueChanged();
1086 }
1087
1088 // Creates a new entity based on the currently selected brush and entity type.
1089 //
1090 void EntityClassList_createEntity(){
1091         GtkTreeView* view = g_entityClassList;
1092
1093         // find out what type of entity we are trying to create
1094         GtkTreeModel* model;
1095         GtkTreeIter iter;
1096         if ( gtk_tree_selection_get_selected( gtk_tree_view_get_selection( view ), &model, &iter ) == FALSE ) {
1097                 ui::Widget(gtk_widget_get_toplevel( GTK_WIDGET( g_entityClassList ) )).alert( "You must have a selected class to create an entity", "info" );
1098                 return;
1099         }
1100
1101         char* text;
1102         gtk_tree_model_get( model, &iter, 0, &text, -1 );
1103
1104         {
1105                 StringOutputStream command;
1106                 command << "entityCreate -class " << text;
1107
1108                 UndoableCommand undo( command.c_str() );
1109
1110                 Entity_createFromSelection( text, g_vector3_identity );
1111         }
1112         g_free( text );
1113 }
1114
1115 void EntityInspector_applyKeyValue(){
1116         // Get current selection text
1117         StringOutputStream key( 64 );
1118         key << gtk_entry_get_text( g_entityKeyEntry );
1119         StringOutputStream value( 64 );
1120         value << gtk_entry_get_text( g_entityValueEntry );
1121
1122
1123         // TTimo: if you change the classname to worldspawn you won't merge back in the structural brushes but create a parasite entity
1124         if ( !strcmp( key.c_str(), "classname" ) && !strcmp( value.c_str(), "worldspawn" ) ) {
1125                 ui::Widget(gtk_widget_get_toplevel( GTK_WIDGET( g_entityKeyEntry )) ).alert( "Cannot change \"classname\" key back to worldspawn.", 0, ui::alert_type::OK );
1126                 return;
1127         }
1128
1129
1130         // RR2DO2: we don't want spaces in entity keys
1131         if ( strstr( key.c_str(), " " ) ) {
1132                 ui::Widget(gtk_widget_get_toplevel( GTK_WIDGET( g_entityKeyEntry )) ).alert( "No spaces are allowed in entity keys.", 0, ui::alert_type::OK );
1133                 return;
1134         }
1135
1136         if ( strcmp( key.c_str(), "classname" ) == 0 ) {
1137                 StringOutputStream command;
1138                 command << "entitySetClass -class " << value.c_str();
1139                 UndoableCommand undo( command.c_str() );
1140                 Scene_EntitySetClassname_Selected( value.c_str() );
1141         }
1142         else
1143         {
1144                 Scene_EntitySetKeyValue_Selected_Undoable( key.c_str(), value.c_str() );
1145         }
1146 }
1147
1148 void EntityInspector_clearKeyValue(){
1149         // Get current selection text
1150         StringOutputStream key( 64 );
1151         key << gtk_entry_get_text( g_entityKeyEntry );
1152
1153         if ( strcmp( key.c_str(), "classname" ) != 0 ) {
1154                 StringOutputStream command;
1155                 command << "entityDeleteKey -key " << key.c_str();
1156                 UndoableCommand undo( command.c_str() );
1157                 Scene_EntitySetKeyValue_Selected( key.c_str(), "" );
1158         }
1159 }
1160
1161 void EntityInspector_clearAllKeyValues(){
1162         UndoableCommand undo( "entityClear" );
1163
1164         // remove all keys except classname
1165         for ( KeyValues::iterator i = g_selectedKeyValues.begin(); i != g_selectedKeyValues.end(); ++i )
1166         {
1167                 if ( strcmp( ( *i ).first.c_str(), "classname" ) != 0 ) {
1168                         Scene_EntitySetKeyValue_Selected( ( *i ).first.c_str(), "" );
1169                 }
1170         }
1171 }
1172
1173 // =============================================================================
1174 // callbacks
1175
1176 static void EntityClassList_selection_changed( GtkTreeSelection* selection, gpointer data ){
1177         GtkTreeModel* model;
1178         GtkTreeIter selected;
1179         if ( gtk_tree_selection_get_selected( selection, &model, &selected ) ) {
1180                 EntityClass* eclass;
1181                 gtk_tree_model_get( model, &selected, 1, &eclass, -1 );
1182                 if ( eclass != 0 ) {
1183                         SetComment( eclass );
1184                 }
1185         }
1186 }
1187
1188 static gint EntityClassList_button_press( ui::Widget widget, GdkEventButton *event, gpointer data ){
1189         if ( event->type == GDK_2BUTTON_PRESS ) {
1190                 EntityClassList_createEntity();
1191                 return TRUE;
1192         }
1193         return FALSE;
1194 }
1195
1196 static gint EntityClassList_keypress( ui::Widget widget, GdkEventKey* event, gpointer data ){
1197         unsigned int code = gdk_keyval_to_upper( event->keyval );
1198
1199         if ( event->keyval == GDK_KEY_Return ) {
1200                 EntityClassList_createEntity();
1201                 return TRUE;
1202         }
1203
1204         // select the entity that starts with the key pressed
1205         if ( code <= 'Z' && code >= 'A' ) {
1206                 GtkTreeView* view = g_entityClassList;
1207                 GtkTreeModel* model;
1208                 GtkTreeIter iter;
1209                 if ( gtk_tree_selection_get_selected( gtk_tree_view_get_selection( view ), &model, &iter ) == FALSE
1210                          || gtk_tree_model_iter_next( model, &iter ) == FALSE ) {
1211                         gtk_tree_model_get_iter_first( model, &iter );
1212                 }
1213
1214                 for ( std::size_t count = gtk_tree_model_iter_n_children( model, 0 ); count > 0; --count )
1215                 {
1216                         char* text;
1217                         gtk_tree_model_get( model, &iter, 0, &text, -1 );
1218
1219                         if ( toupper( text[0] ) == (int)code ) {
1220                                 GtkTreePath* path = gtk_tree_model_get_path( model, &iter );
1221                                 gtk_tree_selection_select_path( gtk_tree_view_get_selection( view ), path );
1222                                 if ( gtk_widget_get_realized( GTK_WIDGET(view) ) ) {
1223                                         gtk_tree_view_scroll_to_cell( view, path, 0, FALSE, 0, 0 );
1224                                 }
1225                                 gtk_tree_path_free( path );
1226                                 count = 1;
1227                         }
1228
1229                         g_free( text );
1230
1231                         if ( gtk_tree_model_iter_next( model, &iter ) == FALSE ) {
1232                                 gtk_tree_model_get_iter_first( model, &iter );
1233                         }
1234                 }
1235
1236                 return TRUE;
1237         }
1238         return FALSE;
1239 }
1240
1241 static void EntityProperties_selection_changed( GtkTreeSelection* selection, gpointer data ){
1242         // find out what type of entity we are trying to create
1243         GtkTreeModel* model;
1244         GtkTreeIter iter;
1245         if ( gtk_tree_selection_get_selected( selection, &model, &iter ) == FALSE ) {
1246                 return;
1247         }
1248
1249         char* key;
1250         char* val;
1251         gtk_tree_model_get( model, &iter, 0, &key, 1, &val, -1 );
1252
1253         g_entityKeyEntry.text( key );
1254         g_entityValueEntry.text( val );
1255
1256         g_free( key );
1257         g_free( val );
1258 }
1259
1260 static void SpawnflagCheck_toggled( ui::Widget widget, gpointer data ){
1261         EntityInspector_applySpawnflags();
1262 }
1263
1264 static gint EntityEntry_keypress( GtkEntry* widget, GdkEventKey* event, gpointer data ){
1265         if ( event->keyval == GDK_KEY_Return ) {
1266                 if ( widget == g_entityKeyEntry ) {
1267                         g_entityValueEntry.text( "" );
1268                         gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( widget ) ) ), GTK_WIDGET( g_entityValueEntry ) );
1269                 }
1270                 else
1271                 {
1272                         EntityInspector_applyKeyValue();
1273                 }
1274                 return TRUE;
1275         }
1276         if ( event->keyval == GDK_KEY_Escape ) {
1277                 gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( widget ) ) ), NULL );
1278                 return TRUE;
1279         }
1280
1281         return FALSE;
1282 }
1283
1284 void EntityInspector_destroyWindow( ui::Widget widget, gpointer data ){
1285         g_entitysplit1_position = gtk_paned_get_position( GTK_PANED( g_entity_split1 ) );
1286         g_entitysplit2_position = gtk_paned_get_position( GTK_PANED( g_entity_split2 ) );
1287
1288         g_entityInspector_windowConstructed = false;
1289         GlobalEntityAttributes_clear();
1290 }
1291
1292 ui::Widget EntityInspector_constructWindow( ui::Window toplevel ){
1293         ui::Widget vbox = ui::VBox( FALSE, 2 );
1294         vbox.show();
1295         gtk_container_set_border_width( GTK_CONTAINER( vbox ), 2 );
1296
1297         vbox.connect( "destroy", G_CALLBACK( EntityInspector_destroyWindow ), 0 );
1298
1299         {
1300                 ui::Widget split1 = ui::VPaned();
1301                 gtk_box_pack_start( GTK_BOX( vbox ), split1, TRUE, TRUE, 0 );
1302                 split1.show();
1303
1304                 g_entity_split1 = split1;
1305
1306                 {
1307                         ui::Widget split2 = ui::VPaned();
1308                         gtk_paned_add1( GTK_PANED( split1 ), split2 );
1309                         split2.show();
1310
1311                         g_entity_split2 = split2;
1312
1313                         {
1314                                 // class list
1315                                 auto scr = ui::ScrolledWindow();
1316                                 scr.show();
1317                                 gtk_paned_add1( GTK_PANED( split2 ), scr );
1318                                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scr ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
1319                                 gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scr ), GTK_SHADOW_IN );
1320
1321                                 {
1322                                         ui::ListStore store = ui::ListStore(gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_POINTER ));
1323
1324                                         auto view = ui::TreeView( ui::TreeModel( GTK_TREE_MODEL( store ) ));
1325                                         gtk_tree_view_set_enable_search( GTK_TREE_VIEW( view ), FALSE );
1326                                         gtk_tree_view_set_headers_visible( view, FALSE );
1327                                         view.connect( "button_press_event", G_CALLBACK( EntityClassList_button_press ), 0 );
1328                                         view.connect( "key_press_event", G_CALLBACK( EntityClassList_keypress ), 0 );
1329
1330                                         {
1331                                                 auto renderer = ui::CellRendererText();
1332                                                 GtkTreeViewColumn* column = ui::TreeViewColumn( "Key", renderer, {{"text", 0}} );
1333                                                 gtk_tree_view_append_column( view, column );
1334                                         }
1335
1336                                         {
1337                                                 auto selection = ui::TreeSelection(gtk_tree_view_get_selection( view ));
1338                                                 selection.connect( "changed", G_CALLBACK( EntityClassList_selection_changed ), 0 );
1339                                         }
1340
1341                                         view.show();
1342
1343                                         scr.add(view);
1344
1345                                         store.unref();
1346                                         g_entityClassList = view;
1347                                         g_entlist_store = store;
1348                                 }
1349                         }
1350
1351                         {
1352                                 auto scr = ui::ScrolledWindow();
1353                                 scr.show();
1354                                 gtk_paned_add2( GTK_PANED( split2 ), scr );
1355                                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scr ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
1356                                 gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scr ), GTK_SHADOW_IN );
1357
1358                                 {
1359                                         auto text = ui::TextView();
1360                                         gtk_widget_set_size_request( GTK_WIDGET( text ), 0, -1 ); // allow shrinking
1361                                         gtk_text_view_set_wrap_mode( text, GTK_WRAP_WORD );
1362                                         gtk_text_view_set_editable( text, FALSE );
1363                                         text.show();
1364                                         scr.add(text);
1365                                         g_entityClassComment = text;
1366                                 }
1367                         }
1368                 }
1369
1370                 {
1371                         ui::Widget split2 = ui::VPaned();
1372                         gtk_paned_add2( GTK_PANED( split1 ), split2 );
1373                         split2.show();
1374
1375                         {
1376                                 ui::Widget vbox2 = ui::VBox( FALSE, 2 );
1377                                 vbox2.show();
1378                                 gtk_paned_pack1( GTK_PANED( split2 ), vbox2, FALSE, FALSE );
1379
1380                                 {
1381                                         // Spawnflags (4 colums wide max, or window gets too wide.)
1382                                         auto table = ui::Table( 4, 4, FALSE );
1383                                         gtk_box_pack_start( GTK_BOX( vbox2 ), GTK_WIDGET( table ), FALSE, TRUE, 0 );
1384                                         table.show();
1385
1386                                         g_spawnflagsTable = table;
1387
1388                                         for ( int i = 0; i < MAX_FLAGS; i++ )
1389                                         {
1390                                                 auto check = ui::CheckButton( "" );
1391                                                 g_object_ref( GTK_WIDGET( check ) );
1392                                                 g_object_set_data( G_OBJECT( check ), "handler", gint_to_pointer( check.connect( "toggled", G_CALLBACK( SpawnflagCheck_toggled ), 0 ) ) );
1393                                                 g_entitySpawnflagsCheck[i] = check;
1394                                         }
1395                                 }
1396
1397                                 {
1398                                         // key/value list
1399                                         auto scr = ui::ScrolledWindow();
1400                                         scr.show();
1401                                         gtk_box_pack_start( GTK_BOX( vbox2 ), scr, TRUE, TRUE, 0 );
1402                                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scr ), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
1403                                         gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scr ), GTK_SHADOW_IN );
1404
1405                                         {
1406                                                 ui::ListStore store = ui::ListStore(gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_STRING ));
1407
1408                                                 ui::Widget view = ui::TreeView(ui::TreeModel( GTK_TREE_MODEL( store ) ));
1409                                                 gtk_tree_view_set_enable_search( GTK_TREE_VIEW( view ), FALSE );
1410                                                 gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( view ), FALSE );
1411
1412                                                 {
1413                                                         auto renderer = ui::CellRendererText();
1414                                                         GtkTreeViewColumn* column = ui::TreeViewColumn( "", renderer, {{"text", 0}} );
1415                                                         gtk_tree_view_append_column( GTK_TREE_VIEW( view ), column );
1416                                                 }
1417
1418                                                 {
1419                                                         auto renderer = ui::CellRendererText();
1420                                                         GtkTreeViewColumn* column = ui::TreeViewColumn( "", renderer, {{"text", 1}} );
1421                                                         gtk_tree_view_append_column( GTK_TREE_VIEW( view ), column );
1422                                                 }
1423
1424                                                 {
1425                                                         auto selection = ui::TreeSelection(gtk_tree_view_get_selection( GTK_TREE_VIEW( view ) ));
1426                                                         selection.connect( "changed", G_CALLBACK( EntityProperties_selection_changed ), 0 );
1427                                                 }
1428
1429                                                 view.show();
1430
1431                                                 scr.add(view);
1432
1433                                                 store.unref();
1434
1435                                                 g_entprops_store = store;
1436                                         }
1437                                 }
1438
1439                                 {
1440                                         // key/value entry
1441                                         auto table = ui::Table( 2, 2, FALSE );
1442                                         table.show();
1443                                         gtk_box_pack_start( GTK_BOX( vbox2 ), GTK_WIDGET( table ), FALSE, TRUE, 0 );
1444                                         gtk_table_set_row_spacings( table, 3 );
1445                                         gtk_table_set_col_spacings( table, 5 );
1446
1447                                         {
1448                                                 auto entry = ui::Entry();
1449                                                 entry.show();
1450                                                 gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 0, 1,
1451                                                                                   (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ),
1452                                                                                   (GtkAttachOptions)( 0 ), 0, 0 );
1453                                                 gtk_widget_set_events( GTK_WIDGET( entry ), GDK_KEY_PRESS_MASK );
1454                                                 entry.connect( "key_press_event", G_CALLBACK( EntityEntry_keypress ), 0 );
1455                                                 g_entityKeyEntry = entry;
1456                                         }
1457
1458                                         {
1459                                                 auto entry = ui::Entry();
1460                                                 entry.show();
1461                                                 gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 1, 2,
1462                                                                                   (GtkAttachOptions)( GTK_EXPAND | GTK_FILL ),
1463                                                                                   (GtkAttachOptions)( 0 ), 0, 0 );
1464                                                 gtk_widget_set_events( GTK_WIDGET( entry ), GDK_KEY_PRESS_MASK );
1465                                                 entry.connect( "key_press_event", G_CALLBACK( EntityEntry_keypress ), 0 );
1466                                                 g_entityValueEntry = entry;
1467                                         }
1468
1469                                         {
1470                                                 auto label = ui::Label( "Value" );
1471                                                 label.show();
1472                                                 gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 1, 2,
1473                                                                                   (GtkAttachOptions)( GTK_FILL ),
1474                                                                                   (GtkAttachOptions)( 0 ), 0, 0 );
1475                                                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
1476                                         }
1477
1478                                         {
1479                                                 auto label = ui::Label( "Key" );
1480                                                 label.show();
1481                                                 gtk_table_attach( table, GTK_WIDGET( label ), 0, 1, 0, 1,
1482                                                                                   (GtkAttachOptions)( GTK_FILL ),
1483                                                                                   (GtkAttachOptions)( 0 ), 0, 0 );
1484                                                 gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
1485                                         }
1486                                 }
1487
1488                                 {
1489                                         auto hbox = ui::HBox( TRUE, 4 );
1490                                         hbox.show();
1491                                         gtk_box_pack_start( GTK_BOX( vbox2 ), GTK_WIDGET( hbox ), FALSE, TRUE, 0 );
1492
1493                                         {
1494                                                 auto button = ui::Button( "Clear All" );
1495                                                 button.show();
1496                                                 button.connect( "clicked", G_CALLBACK( EntityInspector_clearAllKeyValues ), 0 );
1497                                                 gtk_box_pack_start( hbox, GTK_WIDGET( button ), TRUE, TRUE, 0 );
1498                                         }
1499                                         {
1500                                                 auto button = ui::Button( "Delete Key" );
1501                                                 button.show();
1502                                                 button.connect( "clicked", G_CALLBACK( EntityInspector_clearKeyValue ), 0 );
1503                                                 gtk_box_pack_start( hbox, GTK_WIDGET( button ), TRUE, TRUE, 0 );
1504                                         }
1505                                 }
1506                         }
1507
1508                         {
1509                                 auto scr = ui::ScrolledWindow();
1510                                 scr.show();
1511                                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scr ), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC );
1512
1513                                 auto viewport = ui::Container(GTK_CONTAINER(gtk_viewport_new( 0, 0 )));
1514                                 viewport.show();
1515                                 gtk_viewport_set_shadow_type( GTK_VIEWPORT( viewport ), GTK_SHADOW_NONE );
1516
1517                                 g_attributeBox = ui::VBox( FALSE, 2 );
1518                                 g_attributeBox.show();
1519
1520                                 viewport.add(g_attributeBox);
1521                                 scr.add(viewport);
1522                                 gtk_paned_pack2( GTK_PANED( split2 ), scr, FALSE, FALSE );
1523                         }
1524                 }
1525         }
1526
1527
1528         {
1529                 // show the sliders in any case
1530                 if ( g_entitysplit2_position > 22 ) {
1531                         gtk_paned_set_position( GTK_PANED( g_entity_split2 ), g_entitysplit2_position );
1532                 }
1533                 else {
1534                         g_entitysplit2_position = 22;
1535                         gtk_paned_set_position( GTK_PANED( g_entity_split2 ), 22 );
1536                 }
1537                 if ( ( g_entitysplit1_position - g_entitysplit2_position ) > 27 ) {
1538                         gtk_paned_set_position( GTK_PANED( g_entity_split1 ), g_entitysplit1_position );
1539                 }
1540                 else {
1541                         gtk_paned_set_position( GTK_PANED( g_entity_split1 ), g_entitysplit2_position + 27 );
1542                 }
1543         }
1544
1545         g_entityInspector_windowConstructed = true;
1546         EntityClassList_fill();
1547
1548         typedef FreeCaller1<const Selectable&, EntityInspector_selectionChanged> EntityInspectorSelectionChangedCaller;
1549         GlobalSelectionSystem().addSelectionChangeCallback( EntityInspectorSelectionChangedCaller() );
1550         GlobalEntityCreator().setKeyValueChangedFunc( EntityInspector_keyValueChanged );
1551
1552         // hack
1553         gtk_container_set_focus_chain( GTK_CONTAINER( vbox ), NULL );
1554
1555         return vbox;
1556 }
1557
1558 class EntityInspector : public ModuleObserver
1559 {
1560 std::size_t m_unrealised;
1561 public:
1562 EntityInspector() : m_unrealised( 1 ){
1563 }
1564 void realise(){
1565         if ( --m_unrealised == 0 ) {
1566                 if ( g_entityInspector_windowConstructed ) {
1567                         //globalOutputStream() << "Entity Inspector: realise\n";
1568                         EntityClassList_fill();
1569                 }
1570         }
1571 }
1572 void unrealise(){
1573         if ( ++m_unrealised == 1 ) {
1574                 if ( g_entityInspector_windowConstructed ) {
1575                         //globalOutputStream() << "Entity Inspector: unrealise\n";
1576                         EntityClassList_clear();
1577                 }
1578         }
1579 }
1580 };
1581
1582 EntityInspector g_EntityInspector;
1583
1584 #include "preferencesystem.h"
1585 #include "stringio.h"
1586
1587 void EntityInspector_construct(){
1588         GlobalEntityClassManager().attach( g_EntityInspector );
1589
1590         GlobalPreferenceSystem().registerPreference( "EntitySplit1", IntImportStringCaller( g_entitysplit1_position ), IntExportStringCaller( g_entitysplit1_position ) );
1591         GlobalPreferenceSystem().registerPreference( "EntitySplit2", IntImportStringCaller( g_entitysplit2_position ), IntExportStringCaller( g_entitysplit2_position ) );
1592
1593 }
1594
1595 void EntityInspector_destroy(){
1596         GlobalEntityClassManager().detach( g_EntityInspector );
1597 }
1598
1599 const char *EntityInspector_getCurrentKey(){
1600         if ( !GroupDialog_isShown() ) {
1601                 return 0;
1602         }
1603         if ( GroupDialog_getPage() != g_page_entity ) {
1604                 return 0;
1605         }
1606         return gtk_entry_get_text( g_entityKeyEntry );
1607 }