]> git.mxchange.org Git - flightgear.git/blob - src/GUI/dialog.cxx
Merge branch 'jmt/acinclude'
[flightgear.git] / src / GUI / dialog.cxx
1 // dialog.cxx: implementation of an XML-configurable dialog box.
2
3 #ifdef HAVE_CONFIG_H
4 #  include "config.h"
5 #endif
6
7 #include <simgear/structure/SGBinding.hxx>
8 #include <Scripting/NasalSys.hxx>
9 #include <Main/fg_os.hxx>
10
11 #include "dialog.hxx"
12 #include "new_gui.hxx"
13 #include "AirportList.hxx"
14 #include "property_list.hxx"
15 #include "layout.hxx"
16 #include "WaypointList.hxx"
17 #include "MapWidget.hxx"
18
19 enum format_type { f_INVALID, f_INT, f_LONG, f_FLOAT, f_DOUBLE, f_STRING };
20 static const int FORMAT_BUFSIZE = 255;
21 static const int RESIZE_MARGIN = 7;
22
23
24 /**
25  * Makes sure the format matches '%[ -+#]?\d*(\.\d*)?(l?[df]|s)', with
26  * only one number or string placeholder and otherwise arbitrary prefix
27  * and postfix containing only quoted percent signs (%%).
28  */
29 static format_type
30 validate_format(const char *f)
31 {
32     bool l = false;
33     format_type type;
34     for (; *f; f++) {
35         if (*f == '%') {
36             if (f[1] == '%')
37                 f++;
38             else
39                 break;
40         }
41     }
42     if (*f++ != '%')
43         return f_INVALID;
44     while (*f == ' ' || *f == '+' || *f == '-' || *f == '#' || *f == '0')
45         f++;
46     while (*f && isdigit(*f))
47         f++;
48     if (*f == '.') {
49         f++;
50         while (*f && isdigit(*f))
51             f++;
52     }
53
54     if (*f == 'l')
55         l = true, f++;
56
57     if (*f == 'd') {
58         type = l ? f_LONG : f_INT;
59     } else if (*f == 'f')
60         type = l ? f_DOUBLE : f_FLOAT;
61     else if (*f == 's') {
62         if (l)
63             return f_INVALID;
64         type = f_STRING;
65     } else
66         return f_INVALID;
67
68     for (++f; *f; f++) {
69         if (*f == '%') {
70             if (f[1] == '%')
71                 f++;
72             else
73                 return f_INVALID;
74         }
75     }
76     return type;
77 }
78
79
80 ////////////////////////////////////////////////////////////////////////
81 // Implementation of GUIInfo.
82 ////////////////////////////////////////////////////////////////////////
83
84 /**
85  * User data for a GUI object.
86  */
87 struct GUIInfo
88 {
89     GUIInfo(FGDialog *d);
90     virtual ~GUIInfo();
91     void apply_format(SGPropertyNode *);
92
93     FGDialog *dialog;
94     SGPropertyNode_ptr node;
95     vector <SGBinding *> bindings;
96     int key;
97     string label, legend, text, format;
98     format_type fmt_type;
99 };
100
101 GUIInfo::GUIInfo (FGDialog *d) :
102     dialog(d),
103     key(-1),
104     fmt_type(f_INVALID)
105 {
106 }
107
108 GUIInfo::~GUIInfo ()
109 {
110     for (unsigned int i = 0; i < bindings.size(); i++) {
111         delete bindings[i];
112         bindings[i] = 0;
113     }
114 }
115
116 void GUIInfo::apply_format(SGPropertyNode *n)
117 {
118     char buf[FORMAT_BUFSIZE + 1];
119     if (fmt_type == f_INT)
120         snprintf(buf, FORMAT_BUFSIZE, format.c_str(), n->getIntValue());
121     else if (fmt_type == f_LONG)
122         snprintf(buf, FORMAT_BUFSIZE, format.c_str(), n->getLongValue());
123     else if (fmt_type == f_FLOAT)
124         snprintf(buf, FORMAT_BUFSIZE, format.c_str(), n->getFloatValue());
125     else if (fmt_type == f_DOUBLE)
126         snprintf(buf, FORMAT_BUFSIZE, format.c_str(), n->getDoubleValue());
127     else
128         snprintf(buf, FORMAT_BUFSIZE, format.c_str(), n->getStringValue());
129
130     buf[FORMAT_BUFSIZE] = '\0';
131     text = buf;
132 }
133
134
135 \f
136 /**
137  * Key handler.
138  */
139 int fgPopup::checkKey(int key, int updown)
140 {
141     if (updown == PU_UP || !isVisible() || !isActive() || window != puGetWindow())
142         return false;
143
144     puObject *input = getActiveInputField(this);
145     if (input)
146         return input->checkKey(key, updown);
147
148     puObject *object = getKeyObject(this, key);
149     if (!object)
150         return puPopup::checkKey(key, updown);
151
152     // invokeCallback() isn't enough; we need to simulate a mouse button press
153     object->checkHit(PU_LEFT_BUTTON, PU_DOWN,
154             (object->getABox()->min[0] + object->getABox()->max[0]) / 2,
155             (object->getABox()->min[1] + object->getABox()->max[1]) / 2);
156     object->checkHit(PU_LEFT_BUTTON, PU_UP,
157             (object->getABox()->min[0] + object->getABox()->max[0]) / 2,
158             (object->getABox()->min[1] + object->getABox()->max[1]) / 2);
159     return true;
160 }
161
162 puObject *fgPopup::getKeyObject(puObject *object, int key)
163 {
164     puObject *ret;
165     if (object->getType() & PUCLASS_GROUP)
166         for (puObject *obj = ((puGroup *)object)->getFirstChild();
167                 obj; obj = obj->getNextObject())
168             if ((ret = getKeyObject(obj, key)))
169                 return ret;
170
171     GUIInfo *info = (GUIInfo *)object->getUserData();
172     if (info && info->key == key)
173         return object;
174
175     return 0;
176 }
177
178 puObject *fgPopup::getActiveInputField(puObject *object)
179 {
180     puObject *ret;
181     if (object->getType() & PUCLASS_GROUP)
182         for (puObject *obj = ((puGroup *)object)->getFirstChild();
183                 obj; obj = obj->getNextObject())
184             if ((ret = getActiveInputField(obj)))
185                 return ret;
186
187     if (object->getType() & (PUCLASS_INPUT|PUCLASS_LARGEINPUT)
188             && ((puInput *)object)->isAcceptingInput())
189         return object;
190
191     return 0;
192 }
193
194 /**
195  * Mouse handler.
196  */
197 int fgPopup::checkHit(int button, int updown, int x, int y)
198 {
199     int result = 0;
200     if (updown != PU_DRAG && !_dragging)
201         result = puPopup::checkHit(button, updown, x, y);
202
203     if (!_draggable)
204        return result;
205
206     // This is annoying.  We would really want a true result from the
207     // superclass to indicate "handled by child object", but all it
208     // tells us is that the pointer is inside the dialog.  So do the
209     // intersection test (again) to make sure we don't start a drag
210     // when inside controls.
211
212     if (updown == PU_DOWN && !_dragging) {
213         if (!result)
214             return 0;
215         int global_drag = fgGetKeyModifiers() & KEYMOD_SHIFT;
216         int global_resize = fgGetKeyModifiers() & KEYMOD_CTRL;
217
218         int hit = getHitObjects(this, x, y);
219         if (hit & PUCLASS_LIST)  // ctrl-click in property browser (toggle bool)
220             return result;
221         if (!global_resize && hit & (PUCLASS_BUTTON|PUCLASS_ONESHOT|PUCLASS_INPUT
222                 |PUCLASS_LARGEINPUT|PUCLASS_SCROLLBAR))
223             return result;
224
225         getPosition(&_dlgX, &_dlgY);
226         getSize(&_dlgW, &_dlgH);
227         _start_cursor = fgGetMouseCursor();
228         _dragging = true;
229         _startX = x;
230         _startY = y;
231
232         // check and prepare for resizing
233         static const int cursor[] = {
234             MOUSE_CURSOR_POINTER, MOUSE_CURSOR_LEFTSIDE, MOUSE_CURSOR_RIGHTSIDE, 0,
235             MOUSE_CURSOR_TOPSIDE, MOUSE_CURSOR_TOPLEFT, MOUSE_CURSOR_TOPRIGHT, 0,
236             MOUSE_CURSOR_BOTTOMSIDE, MOUSE_CURSOR_BOTTOMLEFT, MOUSE_CURSOR_BOTTOMRIGHT, 0,
237         };
238
239         _resizing = 0;
240         if (!global_drag && _resizable) {
241             int hmargin = global_resize ? _dlgW / 3 : RESIZE_MARGIN;
242             int vmargin = global_resize ? _dlgH / 3 : RESIZE_MARGIN;
243
244             if (y - _dlgY < vmargin)
245                 _resizing |= BOTTOM;
246             else if (_dlgY + _dlgH - y < vmargin)
247                 _resizing |= TOP;
248
249             if (x - _dlgX < hmargin)
250                 _resizing |= LEFT;
251             else if (_dlgX + _dlgW - x < hmargin)
252                 _resizing |= RIGHT;
253
254             if (!_resizing && global_resize)
255                 _resizing = BOTTOM|RIGHT;
256
257             _cursor = cursor[_resizing];
258            if (_resizing && _resizable)
259                 fgSetMouseCursor(_cursor);
260        }
261
262     } else if (updown == PU_DRAG && _dragging) {
263         if (_resizing) {
264             GUIInfo *info = (GUIInfo *)getUserData();
265             if (_resizable && info && info->node) {
266                 int w = _dlgW;
267                 int h = _dlgH;
268                 if (_resizing & LEFT)
269                     w += _startX - x;
270                 if (_resizing & RIGHT)
271                     w += x - _startX;
272                 if (_resizing & TOP)
273                     h += y - _startY;
274                 if (_resizing & BOTTOM)
275                     h += _startY - y;
276
277                 int prefw, prefh;
278                 LayoutWidget wid(info->node);
279                 wid.calcPrefSize(&prefw, &prefh);
280                 if (w < prefw)
281                     w = prefw;
282                 if (h < prefh)
283                     h = prefh;
284
285                 int x = _dlgX;
286                 int y = _dlgY;
287                 if (_resizing & LEFT)
288                     x += _dlgW - w;
289                 if (_resizing & BOTTOM)
290                     y += _dlgH - h;
291
292                 wid.layout(x, y, w, h);
293                 setSize(w, h);
294                 setPosition(x, y);
295                 applySize(static_cast<puObject *>(this));
296                 getFirstChild()->setSize(w, h); // dialog background puFrame
297             }
298         } else {
299             int posX = x + _dlgX - _startX,
300               posY = y + _dlgY - _startY;
301             setPosition(posX, posY);
302             
303             GUIInfo *info = (GUIInfo *)getUserData();
304             if (info && info->node) {
305                 info->node->setIntValue("x", posX);
306                 info->node->setIntValue("y", posY);
307             }
308         } // re-positioning
309
310     } else if (_dragging) {
311         fgSetMouseCursor(_start_cursor);
312         _dragging = false;
313     }
314     return result;
315 }
316
317 int fgPopup::getHitObjects(puObject *object, int x, int y)
318 {
319     if (!object->isVisible())
320         return 0;
321
322     int type = 0;
323     if (object->getType() & PUCLASS_GROUP)
324         for (puObject *obj = ((puGroup *)object)->getFirstChild();
325                 obj; obj = obj->getNextObject())
326             type |= getHitObjects(obj, x, y);
327
328     int cx, cy, cw, ch;
329     object->getAbsolutePosition(&cx, &cy);
330     object->getSize(&cw, &ch);
331     if (x >= cx && x < cx + cw && y >= cy && y < cy + ch)
332         type |= object->getType();
333     return type;
334 }
335
336 void fgPopup::applySize(puObject *object)
337 {
338     // compound plib widgets use setUserData() for internal purposes, so refuse
339     // to descend into anything that has other bits set than the following
340     const int validUserData = PUCLASS_VALUE|PUCLASS_OBJECT|PUCLASS_GROUP|PUCLASS_INTERFACE
341             |PUCLASS_FRAME|PUCLASS_TEXT|PUCLASS_BUTTON|PUCLASS_ONESHOT|PUCLASS_INPUT
342             |PUCLASS_ARROW|PUCLASS_DIAL|PUCLASS_POPUP;
343
344     int type = object->getType();
345     if (type & PUCLASS_GROUP && !(type & ~validUserData))
346         for (puObject *obj = ((puGroup *)object)->getFirstChild();
347                 obj; obj = obj->getNextObject())
348             applySize(obj);
349
350     GUIInfo *info = (GUIInfo *)object->getUserData();
351     if (!info)
352         return;
353
354     SGPropertyNode *n = info->node;
355     if (!n) {
356         SG_LOG(SG_GENERAL, SG_ALERT, "fgPopup::applySize: no props");
357         return;
358     }
359     int x = n->getIntValue("x");
360     int y = n->getIntValue("y");
361     int w = n->getIntValue("width", 4);
362     int h = n->getIntValue("height", 4);
363     object->setPosition(x, y);
364     object->setSize(w, h);
365 }
366
367 ////////////////////////////////////////////////////////////////////////
368
369 void FGDialog::ConditionalObject::update(FGDialog* aDlg)
370 {
371   if (_name == "visible") {
372     bool wasVis = _pu->isVisible();
373     bool newVis = test();
374     
375     if (newVis == wasVis) {
376       return;
377     }
378     
379     if (newVis) { // puObject needs a setVisible. Oh well.
380     _pu->reveal();
381     } else {
382       _pu->hide();
383     }
384   } else if (_name == "enable") {
385     bool wasEnabled = _pu->isActive();
386     bool newEnable = test();
387     
388     if (wasEnabled == newEnable) {
389       return;
390     }
391     
392     if (newEnable) {
393       _pu->activate();
394     } else {
395       _pu->greyOut();
396     }
397   }
398   
399   aDlg->setNeedsLayout();
400 }
401 \f////////////////////////////////////////////////////////////////////////
402 // Callbacks.
403 ////////////////////////////////////////////////////////////////////////
404
405 /**
406  * Action callback.
407  */
408 static void
409 action_callback (puObject *object)
410 {
411     GUIInfo *info = (GUIInfo *)object->getUserData();
412     NewGUI *gui = (NewGUI *)globals->get_subsystem("gui");
413     gui->setActiveDialog(info->dialog);
414     int nBindings = info->bindings.size();
415     for (int i = 0; i < nBindings; i++) {
416         info->bindings[i]->fire();
417         if (gui->getActiveDialog() == 0)
418             break;
419     }
420     gui->setActiveDialog(0);
421 }
422
423
424 \f
425 ////////////////////////////////////////////////////////////////////////
426 // Static helper functions.
427 ////////////////////////////////////////////////////////////////////////
428
429 /**
430  * Copy a property value to a PUI object.
431  */
432 static void
433 copy_to_pui (SGPropertyNode *node, puObject *object)
434 {
435     using namespace simgear;
436     GUIInfo *info = (GUIInfo *)object->getUserData();
437     if (!info) {
438         SG_LOG(SG_GENERAL, SG_ALERT, "dialog: widget without GUIInfo!");
439         return;   // this can't really happen
440     }
441
442     // Treat puText objects specially, so their "values" can be set
443     // from properties.
444     if (object->getType() & PUCLASS_TEXT) {
445         if (info->fmt_type != f_INVALID)
446             info->apply_format(node);
447         else
448             info->text = node->getStringValue();
449
450         object->setLabel(info->text.c_str());
451         return;
452     }
453
454     switch (node->getType()) {
455     case props::BOOL:
456     case props::INT:
457     case props::LONG:
458         object->setValue(node->getIntValue());
459         break;
460     case props::FLOAT:
461     case props::DOUBLE:
462         object->setValue(node->getFloatValue());
463         break;
464     default:
465         info->text = node->getStringValue();
466         object->setValue(info->text.c_str());
467         break;
468     }
469 }
470
471
472 static void
473 copy_from_pui (puObject *object, SGPropertyNode *node)
474 {
475     using namespace simgear;
476     // puText objects are immutable, so should not be copied out
477     if (object->getType() & PUCLASS_TEXT)
478         return;
479
480     switch (node->getType()) {
481     case props::BOOL:
482     case props::INT:
483     case props::LONG:
484         node->setIntValue(object->getIntegerValue());
485         break;
486     case props::FLOAT:
487     case props::DOUBLE:
488         node->setFloatValue(object->getFloatValue());
489         break;
490     default:
491         const char *s = object->getStringValue();
492         if (s)
493             node->setStringValue(s);
494         break;
495     }
496 }
497
498
499 \f
500 ////////////////////////////////////////////////////////////////////////
501 // Implementation of FGDialog.
502 ////////////////////////////////////////////////////////////////////////
503
504 FGDialog::FGDialog (SGPropertyNode *props) :
505     _object(0),
506     _gui((NewGUI *)globals->get_subsystem("gui")),
507     _props(props),
508     _needsRelayout(false)
509 {
510     _module = string("__dlg:") + props->getStringValue("name", "[unnamed]");
511         
512     SGPropertyNode *nasal = props->getNode("nasal");
513     if (nasal) {
514         _nasal_close = nasal->getNode("close");
515         SGPropertyNode *open = nasal->getNode("open");
516         if (open) {
517             const char *s = open->getStringValue();
518             FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
519             if (nas)
520                 nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s), props);
521         }
522     }
523     display(props);
524 }
525
526 FGDialog::~FGDialog ()
527 {
528     int x, y;
529     _object->getAbsolutePosition(&x, &y);
530     _props->setIntValue("lastx", x);
531     _props->setIntValue("lasty", y);
532
533     FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
534     if (nas) {
535         if (_nasal_close) {
536             const char *s = _nasal_close->getStringValue();
537             nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
538         }
539         nas->deleteModule(_module.c_str());
540     }
541
542     puDeleteObject(_object);
543
544     unsigned int i;
545                                 // Delete all the info objects we
546                                 // were forced to keep around because
547                                 // PUI cannot delete its own user data.
548     for (i = 0; i < _info.size(); i++) {
549         delete (GUIInfo *)_info[i];
550         _info[i] = 0;
551     }
552                                 // Finally, delete the property links.
553     for (i = 0; i < _propertyObjects.size(); i++) {
554         delete _propertyObjects[i];
555         _propertyObjects[i] = 0;
556     }
557 }
558
559 void
560 FGDialog::updateValues (const char *objectName)
561 {
562     if (objectName && !objectName[0])
563         objectName = 0;
564
565   for (unsigned int i = 0; i < _propertyObjects.size(); i++) {
566     const string &name = _propertyObjects[i]->name;
567     if (objectName && name != objectName) {
568       continue;
569     }
570     
571     puObject *widget = _propertyObjects[i]->object;
572     int widgetType = widget->getType();
573     if (widgetType & PUCLASS_LIST) {
574       GUI_ID* gui_id = dynamic_cast<GUI_ID *>(widget);
575       if (gui_id && (gui_id->id & FGCLASS_LIST)) {
576         fgList *pl = static_cast<fgList*>(widget);
577         pl->update();
578       } else {
579         copy_to_pui(_propertyObjects[i]->node, widget);
580       }
581     } else if (widgetType & PUCLASS_COMBOBOX) {
582       fgComboBox* combo = static_cast<fgComboBox*>(widget);
583       combo->update();
584     } else {
585       copy_to_pui(_propertyObjects[i]->node, widget);
586     }
587   } // of property objects iteration
588 }
589
590 void
591 FGDialog::applyValues (const char *objectName)
592 {
593     if (objectName && !objectName[0])
594         objectName = 0;
595
596     for (unsigned int i = 0; i < _propertyObjects.size(); i++) {
597         const string &name = _propertyObjects[i]->name;
598         if (objectName && name != objectName)
599             continue;
600
601         copy_from_pui(_propertyObjects[i]->object,
602                       _propertyObjects[i]->node);
603     }
604 }
605
606 void
607 FGDialog::update ()
608 {
609     for (unsigned int i = 0; i < _liveObjects.size(); i++) {
610         puObject *obj = _liveObjects[i]->object;
611         if (obj->getType() & PUCLASS_INPUT && ((puInput *)obj)->isAcceptingInput())
612             continue;
613
614         copy_to_pui(_liveObjects[i]->node, obj);
615     }
616     
617   for (unsigned int j=0; j < _conditionalObjects.size(); ++j) {
618     _conditionalObjects[j]->update(this);
619   }
620   
621   if (_needsRelayout) {
622     relayout();
623   }
624 }
625
626 void
627 FGDialog::display (SGPropertyNode *props)
628 {
629     if (_object != 0) {
630         SG_LOG(SG_GENERAL, SG_ALERT, "This widget is already active");
631         return;
632     }
633
634     int screenw = globals->get_props()->getIntValue("/sim/startup/xsize");
635     int screenh = globals->get_props()->getIntValue("/sim/startup/ysize");
636
637     bool userx = props->hasValue("x");
638     bool usery = props->hasValue("y");
639     bool userw = props->hasValue("width");
640     bool userh = props->hasValue("height");
641
642     // Let the layout widget work in the same property subtree.
643     LayoutWidget wid(props);
644
645     SGPropertyNode *fontnode = props->getNode("font");
646     if (fontnode) {
647         FGFontCache *fc = globals->get_fontcache();
648         _font = fc->get(fontnode);
649     } else {
650         _font = _gui->getDefaultFont();
651     }
652     wid.setDefaultFont(_font, int(_font->getPointSize()));
653
654     int pw = 0, ph = 0;
655     int px, py, savex, savey;
656     if (!userw || !userh)
657         wid.calcPrefSize(&pw, &ph);
658     pw = props->getIntValue("width", pw);
659     ph = props->getIntValue("height", ph);
660     px = savex = props->getIntValue("x", (screenw - pw) / 2);
661     py = savey = props->getIntValue("y", (screenh - ph) / 2);
662
663     // Negative x/y coordinates are interpreted as distance from the top/right
664     // corner rather than bottom/left.
665     if (userx && px < 0)
666         px = screenw - pw + px;
667     if (usery && py < 0)
668         py = screenh - ph + py;
669
670     // Define "x", "y", "width" and/or "height" in the property tree if they
671     // are not specified in the configuration file.
672     wid.layout(px, py, pw, ph);
673
674     // Use the dimension and location properties as specified in the
675     // configuration file or from the layout widget.
676     _object = makeObject(props, screenw, screenh);
677
678     // Remove automatically generated properties, so the layout looks
679     // the same next time around, or restore x and y to preserve negative coords.
680     if (userx)
681         props->setIntValue("x", savex);
682     else
683         props->removeChild("x");
684
685     if (usery)
686         props->setIntValue("y", savey);
687     else
688         props->removeChild("y");
689
690     if (!userw) props->removeChild("width");
691     if (!userh) props->removeChild("height");
692
693     if (_object != 0) {
694         _object->reveal();
695     } else {
696         SG_LOG(SG_GENERAL, SG_ALERT, "Widget "
697                << props->getStringValue("name", "[unnamed]")
698                << " does not contain a proper GUI definition");
699     }
700 }
701
702 puObject *
703 FGDialog::makeObject (SGPropertyNode *props, int parentWidth, int parentHeight)
704 {
705     if (!props->getBoolValue("enabled", true))
706         return 0;
707
708     bool presetSize = props->hasValue("width") && props->hasValue("height");
709     int width = props->getIntValue("width", parentWidth);
710     int height = props->getIntValue("height", parentHeight);
711     int x = props->getIntValue("x", (parentWidth - width) / 2);
712     int y = props->getIntValue("y", (parentHeight - height) / 2);
713     string type = props->getName();
714
715     if (type.empty())
716         type = "dialog";
717
718     if (type == "dialog") {
719         puPopup *obj;
720         bool draggable = props->getBoolValue("draggable", true);
721         bool resizable = props->getBoolValue("resizable", false);
722         if (props->getBoolValue("modal", false))
723             obj = new puDialogBox(x, y);
724         else
725             obj = new fgPopup(x, y, resizable, draggable);
726         setupGroup(obj, props, width, height, true);
727         setColor(obj, props);
728         return obj;
729
730     } else if (type == "group") {
731         puGroup *obj = new puGroup(x, y);
732         setupGroup(obj, props, width, height, false);
733         setColor(obj, props);
734         return obj;
735
736     } else if (type == "frame") {
737         puGroup *obj = new puGroup(x, y);
738         setupGroup(obj, props, width, height, true);
739         setColor(obj, props);
740         return obj;
741
742     } else if (type == "hrule" || type == "vrule") {
743         puFrame *obj = new puFrame(x, y, x + width, y + height);
744         obj->setBorderThickness(0);
745         setupObject(obj, props);
746         setColor(obj, props, BACKGROUND|FOREGROUND|HIGHLIGHT);
747         return obj;
748
749     } else if (type == "list") {
750         int slider_width = props->getIntValue("slider", 20);
751         fgList *obj = new fgList(x, y, x + width, y + height, props, slider_width);
752         if (presetSize)
753             obj->setSize(width, height);
754         setupObject(obj, props);
755         setColor(obj, props);
756         return obj;
757
758     } else if (type == "airport-list") {
759         AirportList *obj = new AirportList(x, y, x + width, y + height);
760         if (presetSize)
761             obj->setSize(width, height);
762         setupObject(obj, props);
763         setColor(obj, props);
764         return obj;
765
766     } else if (type == "property-list") {
767         PropertyList *obj = new PropertyList(x, y, x + width, y + height, globals->get_props());
768         if (presetSize)
769             obj->setSize(width, height);
770         setupObject(obj, props);
771         setColor(obj, props);
772         return obj;
773
774     } else if (type == "input") {
775         puInput *obj = new puInput(x, y, x + width, y + height);
776         setupObject(obj, props);
777         setColor(obj, props, FOREGROUND|LABEL);
778         return obj;
779
780     } else if (type == "text") {
781         puText *obj = new puText(x, y);
782         setupObject(obj, props);
783
784         // Layed-out objects need their size set, and non-layout ones
785         // get a different placement.
786         if (presetSize)
787             obj->setSize(width, height);
788         else
789             obj->setLabelPlace(PUPLACE_LABEL_DEFAULT);
790         setColor(obj, props, LABEL);
791         return obj;
792
793     } else if (type == "checkbox") {
794         puButton *obj;
795         obj = new puButton(x, y, x + width, y + height, PUBUTTON_XCHECK);
796         setupObject(obj, props);
797         setColor(obj, props, FOREGROUND|LABEL);
798         return obj;
799
800     } else if (type == "radio") {
801         puButton *obj;
802         obj = new puButton(x, y, x + width, y + height, PUBUTTON_CIRCLE);
803         setupObject(obj, props);
804         setColor(obj, props, FOREGROUND|LABEL);
805         return obj;
806
807     } else if (type == "button") {
808         puButton *obj;
809         const char *legend = props->getStringValue("legend", "[none]");
810         if (props->getBoolValue("one-shot", true))
811             obj = new puOneShot(x, y, legend);
812         else
813             obj = new puButton(x, y, legend);
814         if (presetSize)
815             obj->setSize(width, height);
816         setupObject(obj, props);
817         setColor(obj, props);
818         return obj;
819     } else if (type == "map") {
820         MapWidget* mapWidget = new MapWidget(x, y, x + width, y + height);
821         setupObject(mapWidget, props);
822         return mapWidget;
823     } else if (type == "combo") {
824         fgComboBox *obj = new fgComboBox(x, y, x + width, y + height, props,
825                 props->getBoolValue("editable", false));
826         setupObject(obj, props);
827         setColor(obj, props, EDITFIELD);
828         return obj;
829
830     } else if (type == "slider") {
831         bool vertical = props->getBoolValue("vertical", false);
832         puSlider *obj = new puSlider(x, y, (vertical ? height : width), vertical);
833         obj->setMinValue(props->getFloatValue("min", 0.0));
834         obj->setMaxValue(props->getFloatValue("max", 1.0));
835         obj->setStepSize(props->getFloatValue("step"));
836         obj->setSliderFraction(props->getFloatValue("fraction"));
837 #if PLIB_VERSION > 185
838         obj->setPageStepSize(props->getFloatValue("pagestep"));
839 #endif
840         setupObject(obj, props);
841         if (presetSize)
842             obj->setSize(width, height);
843         setColor(obj, props, FOREGROUND|LABEL);
844         return obj;
845
846     } else if (type == "dial") {
847         puDial *obj = new puDial(x, y, width);
848         obj->setMinValue(props->getFloatValue("min", 0.0));
849         obj->setMaxValue(props->getFloatValue("max", 1.0));
850         obj->setWrap(props->getBoolValue("wrap", true));
851         setupObject(obj, props);
852         setColor(obj, props, FOREGROUND|LABEL);
853         return obj;
854
855     } else if (type == "textbox") {
856         int slider_width = props->getIntValue("slider", 20);
857         int wrap = props->getBoolValue("wrap", true);
858 #if PLIB_VERSION > 185
859         puaLargeInput *obj = new puaLargeInput(x, y,
860                 x + width, x + height, 11, slider_width, wrap);
861 #else
862         puaLargeInput *obj = new puaLargeInput(x, y,
863                 x + width, x + height, 2, slider_width, wrap);
864 #endif
865
866         if (props->getBoolValue("editable"))
867             obj->enableInput();
868         else
869             obj->disableInput();
870
871         if (presetSize)
872             obj->setSize(width, height);
873         setupObject(obj, props);
874         setColor(obj, props, FOREGROUND|LABEL);
875
876         int top = props->getIntValue("top-line", 0);
877         obj->setTopLineInWindow(top < 0 ? unsigned(-1) >> 1 : top);
878         return obj;
879
880     } else if (type == "select") {
881         fgSelectBox *obj = new fgSelectBox(x, y, x + width, y + height, props);
882         setupObject(obj, props);
883         setColor(obj, props, EDITFIELD);
884         return obj;
885     } else if (type == "waypointlist") {
886         ScrolledWaypointList* obj = new ScrolledWaypointList(x, y, width, height);
887         setupObject(obj, props);
888         return obj;
889     } else {
890         return 0;
891     }
892 }
893
894 void
895 FGDialog::setupObject (puObject *object, SGPropertyNode *props)
896 {
897     GUIInfo *info = new GUIInfo(this);
898     object->setUserData(info);
899     _info.push_back(info);
900     object->setLabelPlace(PUPLACE_CENTERED_RIGHT);
901     object->makeReturnDefault(props->getBoolValue("default"));
902     info->node = props;
903
904     if (props->hasValue("legend")) {
905         info->legend = props->getStringValue("legend");
906         object->setLegend(info->legend.c_str());
907     }
908
909     if (props->hasValue("label")) {
910         info->label = props->getStringValue("label");
911         object->setLabel(info->label.c_str());
912     }
913
914     if (props->hasValue("border"))
915         object->setBorderThickness( props->getIntValue("border", 2) );
916
917     if (SGPropertyNode *nft = props->getNode("font", false)) {
918        FGFontCache *fc = globals->get_fontcache();
919        puFont *lfnt = fc->get(nft);
920        object->setLabelFont(*lfnt);
921        object->setLegendFont(*lfnt);
922     } else {
923        object->setLabelFont(*_font);
924     }
925
926     if (props->hasChild("visible")) {
927       ConditionalObject* cnd = new ConditionalObject("visible", object);
928       cnd->setCondition(sgReadCondition(globals->get_props(), props->getChild("visible")));
929       _conditionalObjects.push_back(cnd);
930     }
931
932     if (props->hasChild("enable")) {
933       ConditionalObject* cnd = new ConditionalObject("enable", object);
934       cnd->setCondition(sgReadCondition(globals->get_props(), props->getChild("enable")));
935       _conditionalObjects.push_back(cnd);
936     }
937
938     string type = props->getName();
939     if (type == "input" && props->getBoolValue("live"))
940         object->setDownCallback(action_callback);
941
942     if (type == "text") {
943         const char *format = props->getStringValue("format", 0);
944         if (format) {
945             info->fmt_type = validate_format(format);
946             if (info->fmt_type != f_INVALID)
947                 info->format = format;
948             else
949                 SG_LOG(SG_GENERAL, SG_ALERT, "DIALOG: invalid <format> '"
950                         << format << '\'');
951         }
952     }
953
954     if (props->hasValue("property")) {
955         const char *name = props->getStringValue("name");
956         if (name == 0)
957             name = "";
958         const char *propname = props->getStringValue("property");
959         SGPropertyNode_ptr node = fgGetNode(propname, true);
960         if (type == "map") {
961           // mapWidget binds to a sub-tree of properties, and
962           // ignroes the puValue mechanism, so special case things here
963           MapWidget* mw = static_cast<MapWidget*>(object);
964           mw->setProperty(node);
965         } else {
966             // normal widget, creating PropertyObject
967             copy_to_pui(node, object);
968             PropertyObject *po = new PropertyObject(name, object, node);
969             _propertyObjects.push_back(po);
970             if (props->getBoolValue("live"))
971                 _liveObjects.push_back(po);
972         }
973         
974
975     }
976
977     SGPropertyNode *dest = fgGetNode("/sim/bindings/gui", true);
978     vector<SGPropertyNode_ptr> bindings = props->getChildren("binding");
979     if (bindings.size() > 0) {
980         info->key = props->getIntValue("keynum", -1);
981         if (props->hasValue("key"))
982             info->key = getKeyCode(props->getStringValue("key", ""));
983
984         for (unsigned int i = 0; i < bindings.size(); i++) {
985             unsigned int j = 0;
986             SGPropertyNode_ptr binding;
987             while (dest->getChild("binding", j))
988                 j++;
989
990             const char *cmd = bindings[i]->getStringValue("command");
991             if (!strcmp(cmd, "nasal"))
992                 bindings[i]->setStringValue("module", _module.c_str());
993
994             binding = dest->getChild("binding", j, true);
995             copyProperties(bindings[i], binding);
996             info->bindings.push_back(new SGBinding(binding, globals->get_props()));
997         }
998         object->setCallback(action_callback);
999     }
1000 }
1001
1002 void
1003 FGDialog::setupGroup(puGroup *group, SGPropertyNode *props,
1004        int width, int height, bool makeFrame)
1005 {
1006     setupObject(group, props);
1007
1008     if (makeFrame) {
1009         puFrame* f = new puFrame(0, 0, width, height);
1010         setColor(f, props);
1011     }
1012
1013     int nChildren = props->nChildren();
1014     for (int i = 0; i < nChildren; i++)
1015         makeObject(props->getChild(i), width, height);
1016     group->close();
1017 }
1018
1019 void
1020 FGDialog::setColor(puObject *object, SGPropertyNode *props, int which)
1021 {
1022     string type = props->getName();
1023     if (type.empty())
1024         type = "dialog";
1025     if (type == "textbox" && props->getBoolValue("editable"))
1026         type += "-editable";
1027
1028     FGColor c(_gui->getColor("background"));
1029     c.merge(_gui->getColor(type));
1030     c.merge(props->getNode("color"));
1031     if (c.isValid())
1032         object->setColourScheme(c.red(), c.green(), c.blue(), c.alpha());
1033
1034     const struct {
1035         int mask;
1036         int id;
1037         const char *name;
1038         const char *cname;
1039     } pucol[] = {
1040         { BACKGROUND, PUCOL_BACKGROUND, "background", "color-background" },
1041         { FOREGROUND, PUCOL_FOREGROUND, "foreground", "color-foreground" },
1042         { HIGHLIGHT,  PUCOL_HIGHLIGHT,  "highlight",  "color-highlight" },
1043         { LABEL,      PUCOL_LABEL,      "label",      "color-label" },
1044         { LEGEND,     PUCOL_LEGEND,     "legend",     "color-legend" },
1045         { MISC,       PUCOL_MISC,       "misc",       "color-misc" },
1046         { EDITFIELD,  PUCOL_EDITFIELD,  "editfield",  "color-editfield" },
1047     };
1048
1049     const int numcol = sizeof(pucol) / sizeof(pucol[0]);
1050
1051     for (int i = 0; i < numcol; i++) {
1052         bool dirty = false;
1053         c.clear();
1054         c.setAlpha(1.0);
1055
1056         dirty |= c.merge(_gui->getColor(type + '-' + pucol[i].name));
1057         if (which & pucol[i].mask)
1058             dirty |= c.merge(props->getNode("color"));
1059
1060         if ((pucol[i].mask == LABEL) && !c.isValid())
1061             dirty |= c.merge(_gui->getColor("label"));
1062
1063         dirty |= c.merge(props->getNode(pucol[i].cname));
1064
1065         if (c.isValid() && dirty)
1066             object->setColor(pucol[i].id, c.red(), c.green(), c.blue(), c.alpha());
1067     }
1068 }
1069
1070
1071 static struct {
1072     const char *name;
1073     int key;
1074 } keymap[] = {
1075     {"backspace", 8},
1076     {"tab", 9},
1077     {"return", 13},
1078     {"enter", 13},
1079     {"esc", 27},
1080     {"escape", 27},
1081     {"space", ' '},
1082     {"&amp;", '&'},
1083     {"and", '&'},
1084     {"&lt;", '<'},
1085     {"&gt;", '>'},
1086     {"f1", PU_KEY_F1},
1087     {"f2", PU_KEY_F2},
1088     {"f3", PU_KEY_F3},
1089     {"f4", PU_KEY_F4},
1090     {"f5", PU_KEY_F5},
1091     {"f6", PU_KEY_F6},
1092     {"f7", PU_KEY_F7},
1093     {"f8", PU_KEY_F8},
1094     {"f9", PU_KEY_F9},
1095     {"f10", PU_KEY_F10},
1096     {"f11", PU_KEY_F11},
1097     {"f12", PU_KEY_F12},
1098     {"left", PU_KEY_LEFT},
1099     {"up", PU_KEY_UP},
1100     {"right", PU_KEY_RIGHT},
1101     {"down", PU_KEY_DOWN},
1102     {"pageup", PU_KEY_PAGE_UP},
1103     {"pagedn", PU_KEY_PAGE_DOWN},
1104     {"home", PU_KEY_HOME},
1105     {"end", PU_KEY_END},
1106     {"insert", PU_KEY_INSERT},
1107     {0, -1},
1108 };
1109
1110 int
1111 FGDialog::getKeyCode(const char *str)
1112 {
1113     enum {
1114         CTRL = 0x1,
1115         SHIFT = 0x2,
1116         ALT = 0x4,
1117     };
1118
1119     while (*str == ' ')
1120         str++;
1121
1122     char *buf = new char[strlen(str) + 1];
1123     strcpy(buf, str);
1124     char *s = buf + strlen(buf);
1125     while (s > str && s[-1] == ' ')
1126         s--;
1127     *s = 0;
1128     s = buf;
1129
1130     int mod = 0;
1131     while (1) {
1132         if (!strncmp(s, "Ctrl-", 5) || !strncmp(s, "CTRL-", 5))
1133             s += 5, mod |= CTRL;
1134         else if (!strncmp(s, "Shift-", 6) || !strncmp(s, "SHIFT-", 6))
1135             s += 6, mod |= SHIFT;
1136         else if (!strncmp(s, "Alt-", 4) || !strncmp(s, "ALT-", 4))
1137             s += 4, mod |= ALT;
1138         else
1139             break;
1140     }
1141
1142     int key = -1;
1143     if (strlen(s) == 1 && isascii(*s)) {
1144         key = *s;
1145         if (mod & SHIFT)
1146             key = toupper(key);
1147         if (mod & CTRL)
1148             key = toupper(key) - '@';
1149         /* if (mod & ALT)
1150             ;   // Alt not propagated to the gui
1151         */
1152     } else {
1153         for (char *t = s; *t; t++)
1154             *t = tolower(*t);
1155         for (int i = 0; keymap[i].name; i++) {
1156             if (!strcmp(s, keymap[i].name)) {
1157                 key = keymap[i].key;
1158                 break;
1159             }
1160         }
1161     }
1162     delete[] buf;
1163     return key;
1164 }
1165
1166 void\fFGDialog::relayout()
1167 {
1168   _needsRelayout = false;
1169   
1170   int screenw = globals->get_props()->getIntValue("/sim/startup/xsize");
1171   int screenh = globals->get_props()->getIntValue("/sim/startup/ysize");
1172
1173   bool userx = _props->hasValue("x");
1174   bool usery = _props->hasValue("y");
1175   bool userw = _props->hasValue("width");
1176   bool userh = _props->hasValue("height");
1177
1178   // Let the layout widget work in the same property subtree.
1179   LayoutWidget wid(_props);
1180   wid.setDefaultFont(_font, int(_font->getPointSize()));
1181
1182   int pw = 0, ph = 0;
1183   int px, py, savex, savey;
1184   if (!userw || !userh) {
1185     wid.calcPrefSize(&pw, &ph);
1186   }
1187   
1188   pw = _props->getIntValue("width", pw);
1189   ph = _props->getIntValue("height", ph);
1190   px = savex = _props->getIntValue("x", (screenw - pw) / 2);
1191   py = savey = _props->getIntValue("y", (screenh - ph) / 2);
1192
1193   // Negative x/y coordinates are interpreted as distance from the top/right
1194   // corner rather than bottom/left.
1195   if (userx && px < 0)
1196     px = screenw - pw + px;
1197   if (usery && py < 0)
1198     py = screenh - ph + py;
1199
1200   // Define "x", "y", "width" and/or "height" in the property tree if they
1201   // are not specified in the configuration file.
1202   wid.layout(px, py, pw, ph);
1203
1204   applySize(_object);
1205   
1206   // Remove automatically generated properties, so the layout looks
1207   // the same next time around, or restore x and y to preserve negative coords.
1208   if (userx)
1209       _props->setIntValue("x", savex);
1210   else
1211       _props->removeChild("x");
1212
1213   if (usery)
1214       _props->setIntValue("y", savey);
1215   else
1216       _props->removeChild("y");
1217
1218   if (!userw) _props->removeChild("width");
1219   if (!userh) _props->removeChild("height");
1220 }
1221
1222 void
1223 FGDialog::applySize(puObject *object)
1224 {
1225   // compound plib widgets use setUserData() for internal purposes, so refuse
1226   // to descend into anything that has other bits set than the following
1227   const int validUserData = PUCLASS_VALUE|PUCLASS_OBJECT|PUCLASS_GROUP|PUCLASS_INTERFACE
1228           |PUCLASS_FRAME|PUCLASS_TEXT|PUCLASS_BUTTON|PUCLASS_ONESHOT|PUCLASS_INPUT
1229           |PUCLASS_ARROW|PUCLASS_DIAL|PUCLASS_POPUP;
1230
1231   int type = object->getType();
1232   if ((type & PUCLASS_GROUP) && !(type & ~validUserData)) {
1233     puObject* c = ((puGroup *)object)->getFirstChild();
1234     for (; c != NULL; c = c->getNextObject()) {
1235       applySize(c);
1236     } // of child iteration
1237   } // of group object case
1238   
1239   GUIInfo *info = (GUIInfo *)object->getUserData();
1240   if (!info)
1241     return;
1242
1243   SGPropertyNode *n = info->node;
1244   if (!n) {
1245     SG_LOG(SG_GENERAL, SG_ALERT, "FGDialog::applySize: no props");
1246     return;
1247   }
1248   
1249   int x = n->getIntValue("x");
1250   int y = n->getIntValue("y");
1251   int w = n->getIntValue("width", 4);
1252   int h = n->getIntValue("height", 4);
1253   object->setPosition(x, y);
1254   object->setSize(w, h);
1255 }
1256
1257 ////////////////////////////////////////////////////////////////////////
1258 // Implementation of FGDialog::PropertyObject.
1259 ////////////////////////////////////////////////////////////////////////
1260
1261 FGDialog::PropertyObject::PropertyObject(const char *n,
1262         puObject *o, SGPropertyNode_ptr p) :
1263     name(n),
1264     object(o),
1265     node(p)
1266 {
1267 }
1268
1269
1270
1271 \f
1272 ////////////////////////////////////////////////////////////////////////
1273 // Implementation of fgValueList and derived pui widgets
1274 ////////////////////////////////////////////////////////////////////////
1275
1276
1277 fgValueList::fgValueList(SGPropertyNode *p) :
1278     _props(p)
1279 {
1280     make_list();
1281 }
1282
1283 void
1284 fgValueList::update()
1285 {
1286     destroy_list();
1287     make_list();
1288 }
1289
1290 fgValueList::~fgValueList()
1291 {
1292     destroy_list();
1293 }
1294
1295 void
1296 fgValueList::make_list()
1297 {
1298   SGPropertyNode_ptr values = _props;
1299   const char* vname = "value";
1300   
1301   if (_props->hasChild("properties")) {
1302     // dynamic values, read from a property's children
1303     const char* path = _props->getStringValue("properties");
1304     values = fgGetNode(path, true);
1305   }
1306   
1307   if (_props->hasChild("property-name")) {
1308     vname = _props->getStringValue("property-name");
1309   }
1310   
1311   vector<SGPropertyNode_ptr> value_nodes = values->getChildren(vname);
1312   _list = new char *[value_nodes.size() + 1];
1313   unsigned int i;
1314   for (i = 0; i < value_nodes.size(); i++) {
1315     _list[i] = strdup((char *)value_nodes[i]->getStringValue());
1316   }
1317   _list[i] = 0;
1318 }
1319
1320 void
1321 fgValueList::destroy_list()
1322 {
1323     for (int i = 0; _list[i] != 0; i++)
1324         if (_list[i])
1325             free(_list[i]);
1326     delete[] _list;
1327 }
1328
1329
1330
1331 void
1332 fgList::update()
1333 {
1334     fgValueList::update();
1335     int top = getTopItem();
1336     newList(_list);
1337     setTopItem(top);
1338 }
1339
1340 void fgComboBox::update()
1341 {
1342   fgValueList::update();
1343   newList(_list);
1344 }
1345
1346 // end of dialog.cxx