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