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