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