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