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