]> git.mxchange.org Git - flightgear.git/blob - src/GUI/dialog.cxx
Merge branch 'topic/gcintersect' into next
[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     GUIInfo *info = (GUIInfo *)object->getUserData();
394     if (!info) {
395         SG_LOG(SG_GENERAL, SG_ALERT, "dialog: widget without GUIInfo!");
396         return;   // this can't really happen
397     }
398
399     // Treat puText objects specially, so their "values" can be set
400     // from properties.
401     if (object->getType() & PUCLASS_TEXT) {
402         if (info->fmt_type != f_INVALID)
403             info->apply_format(node);
404         else
405             info->text = node->getStringValue();
406
407         object->setLabel(info->text.c_str());
408         return;
409     }
410
411     switch (node->getType()) {
412     case SGPropertyNode::BOOL:
413     case SGPropertyNode::INT:
414     case SGPropertyNode::LONG:
415         object->setValue(node->getIntValue());
416         break;
417     case SGPropertyNode::FLOAT:
418     case SGPropertyNode::DOUBLE:
419         object->setValue(node->getFloatValue());
420         break;
421     default:
422         info->text = node->getStringValue();
423         object->setValue(info->text.c_str());
424         break;
425     }
426 }
427
428
429 static void
430 copy_from_pui (puObject *object, SGPropertyNode *node)
431 {
432     // puText objects are immutable, so should not be copied out
433     if (object->getType() & PUCLASS_TEXT)
434         return;
435
436     switch (node->getType()) {
437     case SGPropertyNode::BOOL:
438     case SGPropertyNode::INT:
439     case SGPropertyNode::LONG:
440         node->setIntValue(object->getIntegerValue());
441         break;
442     case SGPropertyNode::FLOAT:
443     case SGPropertyNode::DOUBLE:
444         node->setFloatValue(object->getFloatValue());
445         break;
446     default:
447         const char *s = object->getStringValue();
448         if (s)
449             node->setStringValue(s);
450         break;
451     }
452 }
453
454
455 \f
456 ////////////////////////////////////////////////////////////////////////
457 // Implementation of FGDialog.
458 ////////////////////////////////////////////////////////////////////////
459
460 FGDialog::FGDialog (SGPropertyNode *props) :
461     _object(0),
462     _gui((NewGUI *)globals->get_subsystem("gui")),
463     _props(props)
464 {
465     _module = string("__dlg:") + props->getStringValue("name", "[unnamed]");
466     SGPropertyNode *nasal = props->getNode("nasal");
467     if (nasal) {
468         _nasal_close = nasal->getNode("close");
469         SGPropertyNode *open = nasal->getNode("open");
470         if (open) {
471             const char *s = open->getStringValue();
472             FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
473             nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s), props);
474         }
475     }
476     display(props);
477 }
478
479 FGDialog::~FGDialog ()
480 {
481     int x, y;
482     _object->getAbsolutePosition(&x, &y);
483     _props->setIntValue("lastx", x);
484     _props->setIntValue("lasty", y);
485
486     FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
487     if (_nasal_close) {
488         const char *s = _nasal_close->getStringValue();
489         nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
490     }
491     nas->deleteModule(_module.c_str());
492
493     puDeleteObject(_object);
494
495     unsigned int i;
496                                 // Delete all the info objects we
497                                 // were forced to keep around because
498                                 // PUI cannot delete its own user data.
499     for (i = 0; i < _info.size(); i++) {
500         delete (GUIInfo *)_info[i];
501         _info[i] = 0;
502     }
503                                 // Finally, delete the property links.
504     for (i = 0; i < _propertyObjects.size(); i++) {
505         delete _propertyObjects[i];
506         _propertyObjects[i] = 0;
507     }
508 }
509
510 void
511 FGDialog::updateValues (const char *objectName)
512 {
513     if (objectName && !objectName[0])
514         objectName = 0;
515
516     for (unsigned int i = 0; i < _propertyObjects.size(); i++) {
517         const string &name = _propertyObjects[i]->name;
518         if (objectName && name != objectName)
519             continue;
520
521         puObject *obj = _propertyObjects[i]->object;
522         if ((obj->getType() & PUCLASS_LIST) && (dynamic_cast<GUI_ID *>(obj)->id & FGCLASS_LIST)) {
523             fgList *pl = static_cast<fgList *>(obj);
524             pl->update();
525         } else
526             copy_to_pui(_propertyObjects[i]->node, obj);
527     }
528 }
529
530 void
531 FGDialog::applyValues (const char *objectName)
532 {
533     if (objectName && !objectName[0])
534         objectName = 0;
535
536     for (unsigned int i = 0; i < _propertyObjects.size(); i++) {
537         const string &name = _propertyObjects[i]->name;
538         if (objectName && name != objectName)
539             continue;
540
541         copy_from_pui(_propertyObjects[i]->object,
542                       _propertyObjects[i]->node);
543     }
544 }
545
546 void
547 FGDialog::update ()
548 {
549     for (unsigned int i = 0; i < _liveObjects.size(); i++) {
550         puObject *obj = _liveObjects[i]->object;
551         if (obj->getType() & PUCLASS_INPUT && ((puInput *)obj)->isAcceptingInput())
552             continue;
553
554         copy_to_pui(_liveObjects[i]->node, obj);
555     }
556 }
557
558 void
559 FGDialog::display (SGPropertyNode *props)
560 {
561     if (_object != 0) {
562         SG_LOG(SG_GENERAL, SG_ALERT, "This widget is already active");
563         return;
564     }
565
566     int screenw = globals->get_props()->getIntValue("/sim/startup/xsize");
567     int screenh = globals->get_props()->getIntValue("/sim/startup/ysize");
568
569     bool userx = props->hasValue("x");
570     bool usery = props->hasValue("y");
571     bool userw = props->hasValue("width");
572     bool userh = props->hasValue("height");
573
574     // Let the layout widget work in the same property subtree.
575     LayoutWidget wid(props);
576
577     SGPropertyNode *fontnode = props->getNode("font");
578     if (fontnode) {
579         FGFontCache *fc = globals->get_fontcache();
580         _font = fc->get(fontnode);
581     } else {
582         _font = _gui->getDefaultFont();
583     }
584     wid.setDefaultFont(_font, int(_font->getPointSize()));
585
586     int pw = 0, ph = 0;
587     int px, py, savex, savey;
588     if (!userw || !userh)
589         wid.calcPrefSize(&pw, &ph);
590     pw = props->getIntValue("width", pw);
591     ph = props->getIntValue("height", ph);
592     px = savex = props->getIntValue("x", (screenw - pw) / 2);
593     py = savey = props->getIntValue("y", (screenh - ph) / 2);
594
595     // Negative x/y coordinates are interpreted as distance from the top/right
596     // corner rather than bottom/left.
597     if (userx && px < 0)
598         px = screenw - pw + px;
599     if (usery && py < 0)
600         py = screenh - ph + py;
601
602     // Define "x", "y", "width" and/or "height" in the property tree if they
603     // are not specified in the configuration file.
604     wid.layout(px, py, pw, ph);
605
606     // Use the dimension and location properties as specified in the
607     // configuration file or from the layout widget.
608     _object = makeObject(props, screenw, screenh);
609
610     // Remove automatically generated properties, so the layout looks
611     // the same next time around, or restore x and y to preserve negative coords.
612     if (userx)
613         props->setIntValue("x", savex);
614     else
615         props->removeChild("x");
616
617     if (usery)
618         props->setIntValue("y", savey);
619     else
620         props->removeChild("y");
621
622     if (!userw) props->removeChild("width");
623     if (!userh) props->removeChild("height");
624
625     if (_object != 0) {
626         _object->reveal();
627     } else {
628         SG_LOG(SG_GENERAL, SG_ALERT, "Widget "
629                << props->getStringValue("name", "[unnamed]")
630                << " does not contain a proper GUI definition");
631     }
632 }
633
634 puObject *
635 FGDialog::makeObject (SGPropertyNode *props, int parentWidth, int parentHeight)
636 {
637     if (!props->getBoolValue("enabled", true))
638         return 0;
639
640     bool presetSize = props->hasValue("width") && props->hasValue("height");
641     int width = props->getIntValue("width", parentWidth);
642     int height = props->getIntValue("height", parentHeight);
643     int x = props->getIntValue("x", (parentWidth - width) / 2);
644     int y = props->getIntValue("y", (parentHeight - height) / 2);
645     string type = props->getName();
646
647     if (type.empty())
648         type = "dialog";
649
650     if (type == "dialog") {
651         puPopup *obj;
652         bool draggable = props->getBoolValue("draggable", true);
653         bool resizable = props->getBoolValue("resizable", false);
654         if (props->getBoolValue("modal", false))
655             obj = new puDialogBox(x, y);
656         else
657             obj = new fgPopup(x, y, resizable, draggable);
658         setupGroup(obj, props, width, height, true);
659         setColor(obj, props);
660         return obj;
661
662     } else if (type == "group") {
663         puGroup *obj = new puGroup(x, y);
664         setupGroup(obj, props, width, height, false);
665         setColor(obj, props);
666         return obj;
667
668     } else if (type == "frame") {
669         puGroup *obj = new puGroup(x, y);
670         setupGroup(obj, props, width, height, true);
671         setColor(obj, props);
672         return obj;
673
674     } else if (type == "hrule" || type == "vrule") {
675         puFrame *obj = new puFrame(x, y, x + width, y + height);
676         obj->setBorderThickness(0);
677         setupObject(obj, props);
678         setColor(obj, props, BACKGROUND|FOREGROUND|HIGHLIGHT);
679         return obj;
680
681     } else if (type == "list") {
682         int slider_width = props->getIntValue("slider", 20);
683         fgList *obj = new fgList(x, y, x + width, y + height, props, slider_width);
684         if (presetSize)
685             obj->setSize(width, height);
686         setupObject(obj, props);
687         setColor(obj, props);
688         return obj;
689
690     } else if (type == "airport-list") {
691         AirportList *obj = new AirportList(x, y, x + width, y + height);
692         if (presetSize)
693             obj->setSize(width, height);
694         setupObject(obj, props);
695         setColor(obj, props);
696         return obj;
697
698     } else if (type == "property-list") {
699         PropertyList *obj = new PropertyList(x, y, x + width, y + height, globals->get_props());
700         if (presetSize)
701             obj->setSize(width, height);
702         setupObject(obj, props);
703         setColor(obj, props);
704         return obj;
705
706     } else if (type == "input") {
707         puInput *obj = new puInput(x, y, x + width, y + height);
708         setupObject(obj, props);
709         setColor(obj, props, FOREGROUND|LABEL);
710         return obj;
711
712     } else if (type == "text") {
713         puText *obj = new puText(x, y);
714         setupObject(obj, props);
715
716         // Layed-out objects need their size set, and non-layout ones
717         // get a different placement.
718         if (presetSize)
719             obj->setSize(width, height);
720         else
721             obj->setLabelPlace(PUPLACE_LABEL_DEFAULT);
722         setColor(obj, props, LABEL);
723         return obj;
724
725     } else if (type == "checkbox") {
726         puButton *obj;
727         obj = new puButton(x, y, x + width, y + height, PUBUTTON_XCHECK);
728         setupObject(obj, props);
729         setColor(obj, props, FOREGROUND|LABEL);
730         return obj;
731
732     } else if (type == "radio") {
733         puButton *obj;
734         obj = new puButton(x, y, x + width, y + height, PUBUTTON_CIRCLE);
735         setupObject(obj, props);
736         setColor(obj, props, FOREGROUND|LABEL);
737         return obj;
738
739     } else if (type == "button") {
740         puButton *obj;
741         const char *legend = props->getStringValue("legend", "[none]");
742         if (props->getBoolValue("one-shot", true))
743             obj = new puOneShot(x, y, legend);
744         else
745             obj = new puButton(x, y, legend);
746         if (presetSize)
747             obj->setSize(width, height);
748         setupObject(obj, props);
749         setColor(obj, props);
750         return obj;
751
752     } else if (type == "combo") {
753         fgComboBox *obj = new fgComboBox(x, y, x + width, y + height, props,
754                 props->getBoolValue("editable", false));
755         setupObject(obj, props);
756         setColor(obj, props, EDITFIELD);
757         return obj;
758
759     } else if (type == "slider") {
760         bool vertical = props->getBoolValue("vertical", false);
761         puSlider *obj = new puSlider(x, y, (vertical ? height : width), vertical);
762         obj->setMinValue(props->getFloatValue("min", 0.0));
763         obj->setMaxValue(props->getFloatValue("max", 1.0));
764         obj->setStepSize(props->getFloatValue("step"));
765         obj->setSliderFraction(props->getFloatValue("fraction"));
766 #if PLIB_VERSION > 185
767         obj->setPageStepSize(props->getFloatValue("pagestep"));
768 #endif
769         setupObject(obj, props);
770         if (presetSize)
771             obj->setSize(width, height);
772         setColor(obj, props, FOREGROUND|LABEL);
773         return obj;
774
775     } else if (type == "dial") {
776         puDial *obj = new puDial(x, y, width);
777         obj->setMinValue(props->getFloatValue("min", 0.0));
778         obj->setMaxValue(props->getFloatValue("max", 1.0));
779         obj->setWrap(props->getBoolValue("wrap", true));
780         setupObject(obj, props);
781         setColor(obj, props, FOREGROUND|LABEL);
782         return obj;
783
784     } else if (type == "textbox") {
785         int slider_width = props->getIntValue("slider", 20);
786         int wrap = props->getBoolValue("wrap", true);
787 #if PLIB_VERSION > 185
788         puaLargeInput *obj = new puaLargeInput(x, y,
789                 x + width, x + height, 11, slider_width, wrap);
790 #else
791         puaLargeInput *obj = new puaLargeInput(x, y,
792                 x + width, x + height, 2, slider_width, wrap);
793 #endif
794
795         if (props->getBoolValue("editable"))
796             obj->enableInput();
797         else
798             obj->disableInput();
799
800         if (presetSize)
801             obj->setSize(width, height);
802         setupObject(obj, props);
803         setColor(obj, props, FOREGROUND|LABEL);
804
805         int top = props->getIntValue("top-line", 0);
806         obj->setTopLineInWindow(top < 0 ? unsigned(-1) >> 1 : top);
807         return obj;
808
809     } else if (type == "select") {
810         fgSelectBox *obj = new fgSelectBox(x, y, x + width, y + height, props);
811         setupObject(obj, props);
812         setColor(obj, props, EDITFIELD);
813         return obj;
814     } else {
815         return 0;
816     }
817 }
818
819 void
820 FGDialog::setupObject (puObject *object, SGPropertyNode *props)
821 {
822     GUIInfo *info = new GUIInfo(this);
823     object->setUserData(info);
824     _info.push_back(info);
825     object->setLabelPlace(PUPLACE_CENTERED_RIGHT);
826     object->makeReturnDefault(props->getBoolValue("default"));
827     info->node = props;
828
829     if (props->hasValue("legend")) {
830         info->legend = props->getStringValue("legend");
831         object->setLegend(info->legend.c_str());
832     }
833
834     if (props->hasValue("label")) {
835         info->label = props->getStringValue("label");
836         object->setLabel(info->label.c_str());
837     }
838
839     if (props->hasValue("border"))
840         object->setBorderThickness( props->getIntValue("border", 2) );
841
842     if (SGPropertyNode *nft = props->getNode("font", false)) {
843        FGFontCache *fc = globals->get_fontcache();
844        puFont *lfnt = fc->get(nft);
845        object->setLabelFont(*lfnt);
846        object->setLegendFont(*lfnt);
847     } else {
848        object->setLabelFont(*_font);
849     }
850
851     string type = props->getName();
852     if (type == "input" && props->getBoolValue("live"))
853         object->setDownCallback(action_callback);
854
855     if (type == "text") {
856         const char *format = props->getStringValue("format", 0);
857         if (format) {
858             info->fmt_type = validate_format(format);
859             if (info->fmt_type != f_INVALID)
860                 info->format = format;
861             else
862                 SG_LOG(SG_GENERAL, SG_ALERT, "DIALOG: invalid <format> '"
863                         << format << '\'');
864         }
865     }
866
867     if (props->hasValue("property")) {
868         const char *name = props->getStringValue("name");
869         if (name == 0)
870             name = "";
871         const char *propname = props->getStringValue("property");
872         SGPropertyNode_ptr node = fgGetNode(propname, true);
873         copy_to_pui(node, object);
874
875         PropertyObject *po = new PropertyObject(name, object, node);
876         _propertyObjects.push_back(po);
877         if (props->getBoolValue("live"))
878             _liveObjects.push_back(po);
879     }
880
881     SGPropertyNode *dest = fgGetNode("/sim/bindings/gui", true);
882     vector<SGPropertyNode_ptr> bindings = props->getChildren("binding");
883     if (bindings.size() > 0) {
884         info->key = props->getIntValue("keynum", -1);
885         if (props->hasValue("key"))
886             info->key = getKeyCode(props->getStringValue("key", ""));
887
888         for (unsigned int i = 0; i < bindings.size(); i++) {
889             unsigned int j = 0;
890             SGPropertyNode_ptr binding;
891             while (dest->getChild("binding", j))
892                 j++;
893
894             const char *cmd = bindings[i]->getStringValue("command");
895             if (!strcmp(cmd, "nasal"))
896                 bindings[i]->setStringValue("module", _module.c_str());
897
898             binding = dest->getChild("binding", j, true);
899             copyProperties(bindings[i], binding);
900             info->bindings.push_back(new SGBinding(binding, globals->get_props()));
901         }
902         object->setCallback(action_callback);
903     }
904 }
905
906 void
907 FGDialog::setupGroup(puGroup *group, SGPropertyNode *props,
908        int width, int height, bool makeFrame)
909 {
910     setupObject(group, props);
911
912     if (makeFrame) {
913         puFrame* f = new puFrame(0, 0, width, height);
914         setColor(f, props);
915     }
916
917     int nChildren = props->nChildren();
918     for (int i = 0; i < nChildren; i++)
919         makeObject(props->getChild(i), width, height);
920     group->close();
921 }
922
923 void
924 FGDialog::setColor(puObject *object, SGPropertyNode *props, int which)
925 {
926     string type = props->getName();
927     if (type.empty())
928         type = "dialog";
929     if (type == "textbox" && props->getBoolValue("editable"))
930         type += "-editable";
931
932     FGColor c(_gui->getColor("background"));
933     c.merge(_gui->getColor(type));
934     c.merge(props->getNode("color"));
935     if (c.isValid())
936         object->setColourScheme(c.red(), c.green(), c.blue(), c.alpha());
937
938     const struct {
939         int mask;
940         int id;
941         const char *name;
942         const char *cname;
943     } pucol[] = {
944         { BACKGROUND, PUCOL_BACKGROUND, "background", "color-background" },
945         { FOREGROUND, PUCOL_FOREGROUND, "foreground", "color-foreground" },
946         { HIGHLIGHT,  PUCOL_HIGHLIGHT,  "highlight",  "color-highlight" },
947         { LABEL,      PUCOL_LABEL,      "label",      "color-label" },
948         { LEGEND,     PUCOL_LEGEND,     "legend",     "color-legend" },
949         { MISC,       PUCOL_MISC,       "misc",       "color-misc" },
950         { EDITFIELD,  PUCOL_EDITFIELD,  "editfield",  "color-editfield" },
951     };
952
953     const int numcol = sizeof(pucol) / sizeof(pucol[0]);
954
955     for (int i = 0; i < numcol; i++) {
956         bool dirty = false;
957         c.clear();
958         c.setAlpha(1.0);
959
960         dirty |= c.merge(_gui->getColor(type + '-' + pucol[i].name));
961         if (which & pucol[i].mask)
962             dirty |= c.merge(props->getNode("color"));
963
964         if ((pucol[i].mask == LABEL) && !c.isValid())
965             dirty |= c.merge(_gui->getColor("label"));
966
967         dirty |= c.merge(props->getNode(pucol[i].cname));
968
969         if (c.isValid() && dirty)
970             object->setColor(pucol[i].id, c.red(), c.green(), c.blue(), c.alpha());
971     }
972 }
973
974
975 static struct {
976     const char *name;
977     int key;
978 } keymap[] = {
979     {"backspace", 8},
980     {"tab", 9},
981     {"return", 13},
982     {"enter", 13},
983     {"esc", 27},
984     {"escape", 27},
985     {"space", ' '},
986     {"&amp;", '&'},
987     {"and", '&'},
988     {"&lt;", '<'},
989     {"&gt;", '>'},
990     {"f1", PU_KEY_F1},
991     {"f2", PU_KEY_F2},
992     {"f3", PU_KEY_F3},
993     {"f4", PU_KEY_F4},
994     {"f5", PU_KEY_F5},
995     {"f6", PU_KEY_F6},
996     {"f7", PU_KEY_F7},
997     {"f8", PU_KEY_F8},
998     {"f9", PU_KEY_F9},
999     {"f10", PU_KEY_F10},
1000     {"f11", PU_KEY_F11},
1001     {"f12", PU_KEY_F12},
1002     {"left", PU_KEY_LEFT},
1003     {"up", PU_KEY_UP},
1004     {"right", PU_KEY_RIGHT},
1005     {"down", PU_KEY_DOWN},
1006     {"pageup", PU_KEY_PAGE_UP},
1007     {"pagedn", PU_KEY_PAGE_DOWN},
1008     {"home", PU_KEY_HOME},
1009     {"end", PU_KEY_END},
1010     {"insert", PU_KEY_INSERT},
1011     {0, -1},
1012 };
1013
1014 int
1015 FGDialog::getKeyCode(const char *str)
1016 {
1017     enum {
1018         CTRL = 0x1,
1019         SHIFT = 0x2,
1020         ALT = 0x4,
1021     };
1022
1023     while (*str == ' ')
1024         str++;
1025
1026     char *buf = new char[strlen(str) + 1];
1027     strcpy(buf, str);
1028     char *s = buf + strlen(buf);
1029     while (s > str && s[-1] == ' ')
1030         s--;
1031     *s = 0;
1032     s = buf;
1033
1034     int mod = 0;
1035     while (1) {
1036         if (!strncmp(s, "Ctrl-", 5) || !strncmp(s, "CTRL-", 5))
1037             s += 5, mod |= CTRL;
1038         else if (!strncmp(s, "Shift-", 6) || !strncmp(s, "SHIFT-", 6))
1039             s += 6, mod |= SHIFT;
1040         else if (!strncmp(s, "Alt-", 4) || !strncmp(s, "ALT-", 4))
1041             s += 4, mod |= ALT;
1042         else
1043             break;
1044     }
1045
1046     int key = -1;
1047     if (strlen(s) == 1 && isascii(*s)) {
1048         key = *s;
1049         if (mod & SHIFT)
1050             key = toupper(key);
1051         if (mod & CTRL)
1052             key = toupper(key) - '@';
1053         if (mod & ALT)
1054             ;   // Alt not propagated to the gui
1055     } else {
1056         for (char *t = s; *t; t++)
1057             *t = tolower(*t);
1058         for (int i = 0; keymap[i].name; i++) {
1059             if (!strcmp(s, keymap[i].name)) {
1060                 key = keymap[i].key;
1061                 break;
1062             }
1063         }
1064     }
1065     delete[] buf;
1066     return key;
1067 }
1068
1069
1070 \f
1071 ////////////////////////////////////////////////////////////////////////
1072 // Implementation of FGDialog::PropertyObject.
1073 ////////////////////////////////////////////////////////////////////////
1074
1075 FGDialog::PropertyObject::PropertyObject(const char *n,
1076         puObject *o, SGPropertyNode_ptr p) :
1077     name(n),
1078     object(o),
1079     node(p)
1080 {
1081 }
1082
1083
1084
1085 \f
1086 ////////////////////////////////////////////////////////////////////////
1087 // Implementation of fgValueList and derived pui widgets
1088 ////////////////////////////////////////////////////////////////////////
1089
1090
1091 fgValueList::fgValueList(SGPropertyNode *p) :
1092     _props(p)
1093 {
1094     make_list();
1095 }
1096
1097 void
1098 fgValueList::update()
1099 {
1100     destroy_list();
1101     make_list();
1102 }
1103
1104 fgValueList::~fgValueList()
1105 {
1106     destroy_list();
1107 }
1108
1109 void
1110 fgValueList::make_list()
1111 {
1112     vector<SGPropertyNode_ptr> value_nodes = _props->getChildren("value");
1113     _list = new char *[value_nodes.size() + 1];
1114     unsigned int i;
1115     for (i = 0; i < value_nodes.size(); i++)
1116         _list[i] = strdup((char *)value_nodes[i]->getStringValue());
1117     _list[i] = 0;
1118 }
1119
1120 void
1121 fgValueList::destroy_list()
1122 {
1123     for (int i = 0; _list[i] != 0; i++)
1124         if (_list[i])
1125             free(_list[i]);
1126     delete[] _list;
1127 }
1128
1129
1130
1131 void
1132 fgList::update()
1133 {
1134     fgValueList::update();
1135     int top = getTopItem();
1136     newList(_list);
1137     setTopItem(top);
1138 }
1139
1140 // end of dialog.cxx