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