]> git.mxchange.org Git - flightgear.git/blob - src/GUI/dialog.cxx
Oliver Schroeder:
[flightgear.git] / src / GUI / dialog.cxx
1 // dialog.cxx: implementation of an XML-configurable dialog box.
2
3 #include <stdlib.h>             // atof()
4
5 #include <Input/input.hxx>
6
7 #include "dialog.hxx"
8 #include "new_gui.hxx"
9
10 #include "puList.hxx"
11 #include "AirportList.hxx"
12 #include "layout.hxx"
13
14 int fgPopup::checkHit(int button, int updown, int x, int y)
15 {
16     int result = puPopup::checkHit(button, updown, x, y);
17
18     if ( !_draggable)
19        return result;
20
21     // This is annoying.  We would really want a true result from the
22     // superclass to indicate "handled by child object", but all it
23     // tells us is that the pointer is inside the dialog.  So do the
24     // intersection test (again) to make sure we don't start a drag
25     // when inside controls.
26
27     if(updown == PU_DOWN && !_dragging) {
28         if(!result)
29             return 0;
30
31         int hit = getHitObjects(this, x, y);
32         if(hit & (PUCLASS_BUTTON|PUCLASS_ONESHOT|PUCLASS_INPUT))
33             return result;
34
35         int px, py;
36         getPosition(&px, &py);
37         _dragging = true;
38         _dX = px - x;
39         _dY = py - y;
40     } else if(updown == PU_DRAG && _dragging) {
41         setPosition(x + _dX, y + _dY);
42     } else {
43         _dragging = false;
44     }
45     return result;
46 }
47
48 int fgPopup::getHitObjects(puObject *object, int x, int y)
49 {
50     int type = 0;
51     if(object->getType() & PUCLASS_GROUP)
52         for (puObject *obj = ((puGroup *)object)->getFirstChild();
53                 obj; obj = obj->getNextObject())
54             type |= getHitObjects(obj, x, y);
55
56     int cx, cy, cw, ch;
57     object->getAbsolutePosition(&cx, &cy);
58     object->getSize(&cw, &ch);
59     if(x >= cx && x < cx + cw && y >= cy && y < cy + ch)
60         type |= object->getType();
61     return type;
62 }
63
64
65 \f
66 ////////////////////////////////////////////////////////////////////////
67 // Callbacks.
68 ////////////////////////////////////////////////////////////////////////
69
70 /**
71  * User data for a GUI object.
72  */
73 struct GUIInfo
74 {
75     GUIInfo (FGDialog * d);
76     virtual ~GUIInfo ();
77
78     FGDialog * dialog;
79     vector <FGBinding *> bindings;
80 };
81
82
83 /**
84  * Action callback.
85  */
86 static void
87 action_callback (puObject * object)
88 {
89     GUIInfo * info = (GUIInfo *)object->getUserData();
90     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
91     gui->setActiveDialog(info->dialog);
92     int nBindings = info->bindings.size();
93     for (int i = 0; i < nBindings; i++) {
94         info->bindings[i]->fire();
95         if (gui->getActiveDialog() == 0)
96             break;
97     }
98     gui->setActiveDialog(0);
99 }
100
101
102 static void
103 format_callback(puObject *obj, int dx, int dy, void *n)
104 {
105     SGPropertyNode *node = (SGPropertyNode *)n;
106     const char *format = node->getStringValue("format"), *f = format;
107     bool number, l = false;
108     // make sure the format matches '[ -+#]?\d*(\.\d*)?l?[fs]'
109     for (; *f; f++) {
110         if (*f == '%') {
111             if (f[1] == '%')
112                 f++;
113             else
114                 break;
115         }
116     }
117     if (*f++ != '%')
118         return;
119     if (*f == ' ' || *f == '+' || *f == '-' || *f == '#')
120         f++;
121     while (*f && isdigit(*f))
122         f++;
123     if (*f == '.') {
124         f++;
125         while (*f && isdigit(*f))
126             f++;
127     }
128     if (*f == 'l')
129         l = true, f++;
130
131     if (*f == 'f')
132         number = true;
133     else if (*f == 's') {
134         if (l)
135             return;
136         number = false;
137     } else
138         return;
139
140     for (++f; *f; f++) {
141         if (*f == '%') {
142             if (f[1] == '%')
143                 f++;
144             else
145                 return;
146         }
147     }
148
149     char buf[256];
150     const char *src = obj->getLabel();
151
152     if (number) {
153         float value = atof(src);
154         snprintf(buf, 256, format, value);
155     } else {
156         snprintf(buf, 256, format, src);
157     }
158
159     buf[255] = '\0';
160
161     SGPropertyNode *result = node->getNode("formatted", true);
162     result->setStringValue(buf);
163     obj->setLabel(result->getStringValue());
164 }
165
166
167 \f
168 ////////////////////////////////////////////////////////////////////////
169 // Static helper functions.
170 ////////////////////////////////////////////////////////////////////////
171
172 /**
173  * Copy a property value to a PUI object.
174  */
175 static void
176 copy_to_pui (SGPropertyNode * node, puObject * object)
177 {
178     // Treat puText objects specially, so their "values" can be set
179     // from properties.
180     if(object->getType() & PUCLASS_TEXT) {
181         object->setLabel(node->getStringValue());
182         return;
183     }
184
185     switch (node->getType()) {
186     case SGPropertyNode::BOOL:
187     case SGPropertyNode::INT:
188     case SGPropertyNode::LONG:
189         object->setValue(node->getIntValue());
190         break;
191     case SGPropertyNode::FLOAT:
192     case SGPropertyNode::DOUBLE:
193         object->setValue(node->getFloatValue());
194         break;
195     default:
196         object->setValue(node->getStringValue());
197         break;
198     }
199 }
200
201
202 static void
203 copy_from_pui (puObject * object, SGPropertyNode * node)
204 {
205     // puText objects are immutable, so should not be copied out
206     if(object->getType() & PUCLASS_TEXT)
207         return;
208
209     switch (node->getType()) {
210     case SGPropertyNode::BOOL:
211     case SGPropertyNode::INT:
212     case SGPropertyNode::LONG:
213         node->setIntValue(object->getIntegerValue());
214         break;
215     case SGPropertyNode::FLOAT:
216     case SGPropertyNode::DOUBLE:
217         node->setFloatValue(object->getFloatValue());
218         break;
219     default:
220         // Special case to handle lists, as getStringValue cannot be overridden
221         if(object->getType() & PUCLASS_LIST)
222         {
223             node->setStringValue(((puList *) object)->getListStringValue());
224         }
225         else
226         {
227             node->setStringValue(object->getStringValue());
228         }
229         break;
230     }
231 }
232
233
234 \f
235 ////////////////////////////////////////////////////////////////////////
236 // Implementation of GUIInfo.
237 ////////////////////////////////////////////////////////////////////////
238
239 GUIInfo::GUIInfo (FGDialog * d)
240     : dialog(d)
241 {
242 }
243
244 GUIInfo::~GUIInfo ()
245 {
246     for (unsigned int i = 0; i < bindings.size(); i++) {
247         delete bindings[i];
248         bindings[i] = 0;
249     }
250 }
251
252
253 \f
254 ////////////////////////////////////////////////////////////////////////
255 // Implementation of FGDialog.
256 ////////////////////////////////////////////////////////////////////////
257
258 FGDialog::FGDialog (SGPropertyNode * props)
259     : _object(0),
260       _gui((NewGUI *)globals->get_subsystem("gui"))
261 {
262     char* envp = ::getenv( "FG_FONTS" );
263     if ( envp != NULL ) {
264         _font_path.set( envp );
265     } else {
266         _font_path.set( globals->get_fg_root() );
267         _font_path.append( "Fonts" );
268     }
269
270     display(props);
271 }
272
273 FGDialog::~FGDialog ()
274 {
275     puDeleteObject(_object);
276
277     unsigned int i;
278
279                                 // Delete all the arrays we made
280                                 // and were forced to keep around
281                                 // because PUI won't do its own
282                                 // memory management.
283     for (i = 0; i < _char_arrays.size(); i++) {
284         for (int j = 0; _char_arrays[i][j] != 0; j++)
285             free(_char_arrays[i][j]); // added with strdup
286         delete[] _char_arrays[i];
287     }
288
289                                 // Delete all the info objects we
290                                 // were forced to keep around because
291                                 // PUI cannot delete its own user data.
292     for (i = 0; i < _info.size(); i++) {
293         delete (GUIInfo *)_info[i];
294         _info[i] = 0;
295     }
296
297                                 // Finally, delete the property links.
298     for (i = 0; i < _propertyObjects.size(); i++) {
299         delete _propertyObjects[i];
300         _propertyObjects[i] = 0;
301     }
302 }
303
304 void
305 FGDialog::updateValue (const char * objectName)
306 {
307     for (unsigned int i = 0; i < _propertyObjects.size(); i++) {
308         const string &name = _propertyObjects[i]->name;
309         if (name == objectName)
310             copy_to_pui(_propertyObjects[i]->node,
311                         _propertyObjects[i]->object);
312     }
313 }
314
315 void
316 FGDialog::applyValue (const char * objectName)
317 {
318     for (unsigned int i = 0; i < _propertyObjects.size(); i++) {
319         if (_propertyObjects[i]->name == objectName)
320             copy_from_pui(_propertyObjects[i]->object,
321                           _propertyObjects[i]->node);
322     }
323 }
324
325 void
326 FGDialog::updateValues ()
327 {
328     for (unsigned int i = 0; i < _propertyObjects.size(); i++)
329         copy_to_pui(_propertyObjects[i]->node, _propertyObjects[i]->object);
330 }
331
332 void
333 FGDialog::applyValues ()
334 {
335     for (unsigned int i = 0; i < _propertyObjects.size(); i++)
336         copy_from_pui(_propertyObjects[i]->object,
337                       _propertyObjects[i]->node);
338 }
339
340 void
341 FGDialog::update ()
342 {
343     for (unsigned int i = 0; i < _liveObjects.size(); i++) {
344         puObject *obj = _liveObjects[i]->object;
345         if (obj->getType() & PUCLASS_INPUT && ((puInput *)obj)->isAcceptingInput())
346             continue;
347
348         copy_to_pui(_liveObjects[i]->node, obj);
349     }
350 }
351
352 void
353 FGDialog::display (SGPropertyNode * props)
354 {
355     if (_object != 0) {
356         SG_LOG(SG_GENERAL, SG_ALERT, "This widget is already active");
357         return;
358     }
359
360     int screenw = globals->get_props()->getIntValue("/sim/startup/xsize");
361     int screenh = globals->get_props()->getIntValue("/sim/startup/ysize");
362
363     bool userx = props->hasValue("x");
364     bool usery = props->hasValue("y");
365     bool userw = props->hasValue("width");
366     bool userh = props->hasValue("height");
367
368     // Let the layout widget work in the same property subtree.
369     LayoutWidget wid(props);
370
371     puFont *fnt = _gui->getDefaultFont();
372     wid.setDefaultFont(fnt, int(fnt->getPointSize()));
373
374     int pw=0, ph=0;
375     if(!userw || !userh)
376         wid.calcPrefSize(&pw, &ph);
377     pw = props->getIntValue("width", pw);
378     ph = props->getIntValue("height", ph);
379     int px = props->getIntValue("x", (screenw - pw) / 2);
380     int py = props->getIntValue("y", (screenh - ph) / 2);
381
382     // Define "x", "y", "width" and/or "height" in the property tree if they
383     // are not specified in the configuration file.
384     wid.layout(px, py, pw, ph);
385
386     // Use the dimension and location properties as specified in the
387     // configuration file or from the layout widget.
388     _object = makeObject(props, screenw, screenh);
389
390     // Remove automatically generated properties, so the layout looks
391     // the same next time around.
392     if(!userx) props->removeChild("x");
393     if(!usery) props->removeChild("y");
394     if(!userw) props->removeChild("width");
395     if(!userh) props->removeChild("height");
396
397     if (_object != 0) {
398         _object->reveal();
399     } else {
400         SG_LOG(SG_GENERAL, SG_ALERT, "Widget "
401                << props->getStringValue("name", "[unnamed]")
402                << " does not contain a proper GUI definition");
403     }
404 }
405
406 puObject *
407 FGDialog::makeObject (SGPropertyNode * props, int parentWidth, int parentHeight)
408 {
409     if (props->getBoolValue("hide"))
410         return 0;
411
412     bool presetSize = props->hasValue("width") && props->hasValue("height");
413     int width = props->getIntValue("width", parentWidth);
414     int height = props->getIntValue("height", parentHeight);
415     int x = props->getIntValue("x", (parentWidth - width) / 2);
416     int y = props->getIntValue("y", (parentHeight - height) / 2);
417     string type = props->getName();
418
419     if (type == "")
420         type = "dialog";
421
422     if (type == "dialog") {
423         puPopup * obj;
424         bool draggable = props->getBoolValue("draggable", true);
425         if (props->getBoolValue("modal", false))
426             obj = new puDialogBox(x, y);
427         else
428             obj = new fgPopup(x, y, draggable);
429         setupGroup(obj, props, width, height, true);
430         setColor(obj, props);
431         return obj;
432
433     } else if (type == "group") {
434         puGroup * obj = new puGroup(x, y);
435         setupGroup(obj, props, width, height, false);
436         setColor(obj, props);
437         return obj;
438
439     } else if (type == "frame") {
440         puGroup * obj = new puGroup(x, y);
441         setupGroup(obj, props, width, height, true);
442         setColor(obj, props);
443         return obj;
444
445     } else if (type == "hrule" || type == "vrule") {
446         puFrame * obj = new puFrame(x, y, x + width, y + height);
447         obj->setBorderThickness(0);
448         setColor(obj, props, BACKGROUND|FOREGROUND|HIGHLIGHT);
449         return obj;
450
451     } else if (type == "list") {
452         puList * obj = new puList(x, y, x + width, y + height);
453         setupObject(obj, props);
454         setColor(obj, props);
455         return obj;
456
457     } else if (type == "airport-list") {
458         AirportList * obj = new AirportList(x, y, x + width, y + height);
459         setupObject(obj, props);
460         setColor(obj, props);
461         return obj;
462
463     } else if (type == "input") {
464         puInput * obj = new puInput(x, y, x + width, y + height);
465         setupObject(obj, props);
466         setColor(obj, props, FOREGROUND|LABEL);
467         return obj;
468
469     } else if (type == "text") {
470         puText * obj = new puText(x, y);
471         setupObject(obj, props);
472
473         if (props->getNode("format")) {
474             SGPropertyNode *live = props->getNode("live");
475             if (live && live->getBoolValue())
476                 obj->setRenderCallback(format_callback, props);
477             else
478                 format_callback(obj, x, y, props);
479         }
480         // Layed-out objects need their size set, and non-layout ones
481         // get a different placement.
482         if(presetSize) obj->setSize(width, height);
483         else obj->setLabelPlace(PUPLACE_LABEL_DEFAULT);
484         setColor(obj, props, LABEL);
485         return obj;
486
487     } else if (type == "checkbox") {
488         puButton * obj;
489         obj = new puButton(x, y, x + width, y + height, PUBUTTON_XCHECK);
490         setupObject(obj, props);
491         setColor(obj, props, FOREGROUND|LABEL);
492         return obj;
493
494     } else if (type == "radio") {
495         puButton * obj;
496         obj = new puButton(x, y, x + width, y + height, PUBUTTON_CIRCLE);
497         setupObject(obj, props);
498         setColor(obj, props, FOREGROUND|LABEL);
499         return obj;
500
501     } else if (type == "button") {
502         puButton * obj;
503         const char * legend = props->getStringValue("legend", "[none]");
504         if (props->getBoolValue("one-shot", true))
505             obj = new puOneShot(x, y, legend);
506         else
507             obj = new puButton(x, y, legend);
508         if(presetSize)
509             obj->setSize(width, height);
510         setupObject(obj, props);
511         setColor(obj, props);
512         return obj;
513
514     } else if (type == "combo") {
515         vector<SGPropertyNode_ptr> value_nodes = props->getChildren("value");
516         char ** entries = make_char_array(value_nodes.size());
517         for (unsigned int i = 0, j = value_nodes.size() - 1;
518              i < value_nodes.size();
519              i++, j--)
520             entries[i] = strdup((char *)value_nodes[i]->getStringValue());
521         puComboBox * obj = new puComboBox(x, y, x + width, y + height, entries,
522                            props->getBoolValue("editable", false));
523         setupObject(obj, props);
524         setColor(obj, props, FOREGROUND|LABEL);
525         return obj;
526
527     } else if (type == "slider") {
528         bool vertical = props->getBoolValue("vertical", false);
529         puSlider * obj = new puSlider(x, y, (vertical ? height : width));
530         obj->setMinValue(props->getFloatValue("min", 0.0));
531         obj->setMaxValue(props->getFloatValue("max", 1.0));
532         setupObject(obj, props);
533         if(presetSize)
534             obj->setSize(width, height);
535         setColor(obj, props, FOREGROUND|LABEL);
536         return obj;
537
538     } else if (type == "dial") {
539         puDial * obj = new puDial(x, y, width);
540         obj->setMinValue(props->getFloatValue("min", 0.0));
541         obj->setMaxValue(props->getFloatValue("max", 1.0));
542         obj->setWrap(props->getBoolValue("wrap", true));
543         setupObject(obj, props);
544         setColor(obj, props, FOREGROUND|LABEL);
545         return obj;
546
547     } else if (type == "textbox") {
548         int slider_width = props->getIntValue("slider", parentHeight);
549         int wrap = props->getBoolValue("wrap", true);
550         if (slider_width==0) slider_width=20;
551         puLargeInput * obj = new puLargeInput(x, y,
552                 x+width, x+height, 2, slider_width, wrap);
553
554         if (props->hasValue("editable")) {
555             if (props->getBoolValue("editable")==false)
556                 obj->disableInput();
557             else
558                 obj->enableInput();
559         }
560         setupObject(obj, props);
561         setColor(obj, props, FOREGROUND|LABEL);
562         return obj;
563
564     } else if (type == "select") {
565         vector<SGPropertyNode_ptr> value_nodes;
566         SGPropertyNode * selection_node =
567                 fgGetNode(props->getChild("selection")->getStringValue(), true);
568
569         for (int q = 0; q < selection_node->nChildren(); q++)
570             value_nodes.push_back(selection_node->getChild(q));
571
572         char ** entries = make_char_array(value_nodes.size());
573         for (unsigned int i = 0, j = value_nodes.size() - 1;
574              i < value_nodes.size();
575              i++, j--)
576             entries[i] = strdup((char *)value_nodes[i]->getName());
577         puSelectBox * obj =
578             new puSelectBox(x, y, x + width, y + height, entries);
579         setupObject(obj, props);
580         setColor(obj, props, FOREGROUND|LABEL);
581         return obj;
582     } else {
583         return 0;
584     }
585 }
586
587 void
588 FGDialog::setupObject (puObject * object, SGPropertyNode * props)
589 {
590     object->setLabelPlace(PUPLACE_CENTERED_RIGHT);
591
592     if (props->hasValue("legend"))
593         object->setLegend(props->getStringValue("legend"));
594
595     if (props->hasValue("label"))
596         object->setLabel(props->getStringValue("label"));
597
598     if (props->hasValue("border"))
599         object->setBorderThickness( props->getIntValue("border", 2) );
600
601     if ( SGPropertyNode *nft = props->getNode("font", false) ) {
602        SGPath path( _font_path );
603        const char *name = nft->getStringValue("name", "default");
604        float size = nft->getFloatValue("size", 13.0);
605        float slant = nft->getFloatValue("slant", 0.0);
606        path.append( name );
607        path.concat( ".txf" );
608
609        fntFont *font = new fntTexFont;
610        font->load( (char *)path.c_str() );
611
612        puFont lfnt(font, size, slant);
613        object->setLabelFont( lfnt );
614     }
615
616     if (props->hasValue("property")) {
617         const char * name = props->getStringValue("name");
618         if (name == 0)
619             name = "";
620         const char * propname = props->getStringValue("property");
621         SGPropertyNode_ptr node = fgGetNode(propname, true);
622         copy_to_pui(node, object);
623         PropertyObject* po = new PropertyObject(name, object, node);
624         _propertyObjects.push_back(po);
625         if(props->getBoolValue("live"))
626             _liveObjects.push_back(po);
627     }
628
629     SGPropertyNode * dest = fgGetNode("/sim/bindings/gui", true);
630     vector<SGPropertyNode_ptr> bindings = props->getChildren("binding");
631     if (bindings.size() > 0) {
632         GUIInfo * info = new GUIInfo(this);
633
634         for (unsigned int i = 0; i < bindings.size(); i++) {
635             unsigned int j = 0;
636             SGPropertyNode *binding;
637             while (dest->getChild("binding", j))
638                 j++;
639
640             binding = dest->getChild("binding", j, true);
641             copyProperties(bindings[i], binding);
642             info->bindings.push_back(new FGBinding(binding));
643         }
644         object->setCallback(action_callback);
645         object->setUserData(info);
646         _info.push_back(info);
647     }
648
649     object->makeReturnDefault(props->getBoolValue("default"));
650 }
651
652 void
653 FGDialog::setupGroup (puGroup * group, SGPropertyNode * props,
654                     int width, int height, bool makeFrame)
655 {
656     setupObject(group, props);
657
658     if (makeFrame) {
659         puFrame* f = new puFrame(0, 0, width, height);
660         setColor(f, props);
661     }
662
663     int nChildren = props->nChildren();
664     for (int i = 0; i < nChildren; i++)
665         makeObject(props->getChild(i), width, height);
666     group->close();
667 }
668
669 void
670 FGDialog::setColor(puObject * object, SGPropertyNode * props, int which)
671 {
672     string type = props->getName();
673     if (type == "")
674         type = "dialog";
675
676     FGColor *c = new FGColor(_gui->getColor("background"));
677     c->merge(_gui->getColor(type));
678     c->merge(props->getNode("color"));
679     if (c->isValid())
680         object->setColourScheme(c->red(), c->green(), c->blue(), c->alpha());
681
682     const int numcol = 6;
683     const struct {
684         int mask;
685         int id;
686         const char *name;
687         const char *cname;
688     } pucol[numcol] = {
689         { BACKGROUND, PUCOL_BACKGROUND, "background", "color-background" },
690         { FOREGROUND, PUCOL_FOREGROUND, "foreground", "color-foreground" },
691         { HIGHLIGHT,  PUCOL_HIGHLIGHT,  "highlight",  "color-highlight" },
692         { LABEL,      PUCOL_LABEL,      "label",      "color-label" },
693         { LEGEND,     PUCOL_LEGEND,     "legend",     "color-legend" },
694         { MISC,       PUCOL_MISC,       "misc",       "color-misc" }
695     };
696
697     for (int i = 0; i < numcol; i++) {
698         bool dirty = false;
699         c->clear();
700         c->setAlpha(1.0);
701
702         dirty |= c->merge(_gui->getColor(type + '-' + pucol[i].name));
703         if (which & pucol[i].mask)
704             dirty |= c->merge(props->getNode("color"));
705
706         if ((pucol[i].mask == LABEL) && !c->isValid())
707             dirty |= c->merge(_gui->getColor("label"));
708
709         if (c->isValid() && dirty)
710             object->setColor(pucol[i].id, c->red(), c->green(), c->blue(), c->alpha());
711     }
712 }
713
714 char **
715 FGDialog::make_char_array (int size)
716 {
717     char ** list = new char*[size+1];
718     for (int i = 0; i <= size; i++)
719         list[i] = 0;
720     _char_arrays.push_back(list);
721     return list;
722 }
723
724
725 \f
726 ////////////////////////////////////////////////////////////////////////
727 // Implementation of FGDialog::PropertyObject.
728 ////////////////////////////////////////////////////////////////////////
729
730 FGDialog::PropertyObject::PropertyObject (const char * n,
731                                            puObject * o,
732                                            SGPropertyNode_ptr p)
733     : name(n),
734       object(o),
735       node(p)
736 {
737 }
738
739
740 // end of dialog.cxx