]> git.mxchange.org Git - flightgear.git/blob - src/GUI/dialog.cxx
- abstract out reading colors from the property tree into a routine.
[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 {
261     char* envp = ::getenv( "FG_FONTS" );
262     if ( envp != NULL ) {
263         _font_path.set( envp );
264     } else {
265         _font_path.set( globals->get_fg_root() );
266         _font_path.append( "Fonts" );
267     }
268
269     const sgVec4 background = {0.8, 0.8, 0.9, 0.85};
270     const sgVec4 foreground = {0, 0, 0, 1};
271     sgCopyVec4(_bgcolor, background);
272     sgCopyVec4(_fgcolor, foreground);
273     display(props);
274 }
275
276 FGDialog::~FGDialog ()
277 {
278     puDeleteObject(_object);
279
280     unsigned int i;
281
282                                 // Delete all the arrays we made
283                                 // and were forced to keep around
284                                 // because PUI won't do its own
285                                 // memory management.
286     for (i = 0; i < _char_arrays.size(); i++) {
287         for (int j = 0; _char_arrays[i][j] != 0; j++)
288             free(_char_arrays[i][j]); // added with strdup
289         delete[] _char_arrays[i];
290     }
291
292                                 // Delete all the info objects we
293                                 // were forced to keep around because
294                                 // PUI cannot delete its own user data.
295     for (i = 0; i < _info.size(); i++) {
296         delete (GUIInfo *)_info[i];
297         _info[i] = 0;
298     }
299
300                                 // Finally, delete the property links.
301     for (i = 0; i < _propertyObjects.size(); i++) {
302         delete _propertyObjects[i];
303         _propertyObjects[i] = 0;
304     }
305 }
306
307 void
308 FGDialog::updateValue (const char * objectName)
309 {
310     for (unsigned int i = 0; i < _propertyObjects.size(); i++) {
311         const string &name = _propertyObjects[i]->name;
312         if (name == objectName)
313             copy_to_pui(_propertyObjects[i]->node,
314                         _propertyObjects[i]->object);
315     }
316 }
317
318 void
319 FGDialog::applyValue (const char * objectName)
320 {
321     for (unsigned int i = 0; i < _propertyObjects.size(); i++) {
322         if (_propertyObjects[i]->name == objectName)
323             copy_from_pui(_propertyObjects[i]->object,
324                           _propertyObjects[i]->node);
325     }
326 }
327
328 void
329 FGDialog::updateValues ()
330 {
331     for (unsigned int i = 0; i < _propertyObjects.size(); i++)
332         copy_to_pui(_propertyObjects[i]->node, _propertyObjects[i]->object);
333 }
334
335 void
336 FGDialog::applyValues ()
337 {
338     for (unsigned int i = 0; i < _propertyObjects.size(); i++)
339         copy_from_pui(_propertyObjects[i]->object,
340                       _propertyObjects[i]->node);
341 }
342
343 void
344 FGDialog::update ()
345 {
346     for (unsigned int i = 0; i < _liveObjects.size(); i++) {
347         puObject *obj = _liveObjects[i]->object;
348         if (obj->getType() & PUCLASS_INPUT && ((puInput *)obj)->isAcceptingInput())
349             continue;
350
351         copy_to_pui(_liveObjects[i]->node, obj);
352     }
353 }
354
355 void
356 FGDialog::display (SGPropertyNode * props)
357 {
358     if (_object != 0) {
359         SG_LOG(SG_GENERAL, SG_ALERT, "This widget is already active");
360         return;
361     }
362
363     int screenw = globals->get_props()->getIntValue("/sim/startup/xsize");
364     int screenh = globals->get_props()->getIntValue("/sim/startup/ysize");
365
366     bool userx = props->hasValue("x");
367     bool usery = props->hasValue("y");
368     bool userw = props->hasValue("width");
369     bool userh = props->hasValue("height");
370
371     // Let the layout widget work in the same property subtree.
372     LayoutWidget wid(props);
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     bool presetSize = props->hasValue("width") && props->hasValue("height");
410     int width = props->getIntValue("width", parentWidth);
411     int height = props->getIntValue("height", parentHeight);
412     int x = props->getIntValue("x", (parentWidth - width) / 2);
413     int y = props->getIntValue("y", (parentHeight - height) / 2);
414     string type = props->getName();
415
416     sgVec4 color;
417
418     if (type == "hrule" || type == "vrule")
419         sgCopyVec4(color, _fgcolor);
420     else
421         sgCopyVec4(color, _bgcolor);
422
423     getColor(props->getNode("color"), color);
424
425     if (type == "")
426         type = "dialog";
427
428     if (type == "dialog") {
429         puPopup * dialog;
430         bool draggable = props->getBoolValue("draggable", true);
431         if (props->getBoolValue("modal", false))
432             dialog = new puDialogBox(x, y);
433         else
434             dialog = new fgPopup(x, y, draggable);
435         setupGroup(dialog, props, width, height, color, true);
436         return dialog;
437     } else if (type == "group") {
438         puGroup * group = new puGroup(x, y);
439         setupGroup(group, props, width, height, color, false);
440         return group;
441     } else if (type == "frame") {
442         puGroup * group = new puGroup(x, y);
443         setupGroup(group, props, width, height, color, true);
444         return group;
445     } else if (type == "hrule" || type == "vrule") {
446         puFrame * rule = new puFrame(x, y, x + width, y + height);
447         rule->setBorderThickness(0);
448         rule->setColorScheme(color[0], color[1], color[2], color[3]);
449         return rule;
450     } else if (type == "list") {
451         puList * list = new puList(x, y, x + width, y + height);
452         setupObject(list, props);
453         return list;
454     } else if (type == "airport-list") {
455         AirportList * list = new AirportList(x, y, x + width, y + height);
456         setupObject(list, props);
457         return list;
458     } else if (type == "input") {
459         puInput * input = new puInput(x, y, x + width, y + height);
460         setupObject(input, props);
461         return input;
462     } else if (type == "text") {
463         puText * text = new puText(x, y);
464         setupObject(text, props);
465
466         if (props->getNode("format")) {
467             SGPropertyNode *live = props->getNode("live");
468             if (live && live->getBoolValue())
469                 text->setRenderCallback(format_callback, props);
470             else
471                 format_callback(text, x, y, props);
472         }
473         // Layed-out objects need their size set, and non-layout ones
474         // get a different placement.
475         if(presetSize) text->setSize(width, height);
476         else text->setLabelPlace(PUPLACE_LABEL_DEFAULT);
477         return text;
478     } else if (type == "checkbox") {
479         puButton * b;
480         b = new puButton(x, y, x + width, y + height, PUBUTTON_XCHECK);
481         b->setColourScheme(.8, .7, .7); // matches "PUI input pink"
482         setupObject(b, props);
483         return b;
484     } else if (type == "radio") {
485         puButton * b;
486         b = new puButton(x, y, x + width, y + height, PUBUTTON_CIRCLE);
487         b->setColourScheme(.8, .7, .7); // matches "PUI input pink"
488         setupObject(b, props);
489         return b;
490     } else if (type == "button") {
491         puButton * b;
492         const char * legend = props->getStringValue("legend", "[none]");
493         if (props->getBoolValue("one-shot", true))
494             b = new puOneShot(x, y, legend);
495         else
496             b = new puButton(x, y, legend);
497         if(presetSize)
498             b->setSize(width, height);
499         setupObject(b, props);
500         return b;
501     } else if (type == "combo") {
502         vector<SGPropertyNode_ptr> value_nodes = props->getChildren("value");
503         char ** entries = make_char_array(value_nodes.size());
504         for (unsigned int i = 0, j = value_nodes.size() - 1;
505              i < value_nodes.size();
506              i++, j--)
507             entries[i] = strdup((char *)value_nodes[i]->getStringValue());
508         puComboBox * combo =
509             new puComboBox(x, y, x + width, y + height, entries,
510                            props->getBoolValue("editable", false));
511         setupObject(combo, props);
512         return combo;
513     } else if (type == "slider") {
514         bool vertical = props->getBoolValue("vertical", false);
515         puSlider * slider = new puSlider(x, y, (vertical ? height : width));
516         slider->setMinValue(props->getFloatValue("min", 0.0));
517         slider->setMaxValue(props->getFloatValue("max", 1.0));
518         setupObject(slider, props);
519         if(presetSize)
520             slider->setSize(width, height);
521         return slider;
522     } else if (type == "dial") {
523         puDial * dial = new puDial(x, y, width);
524         dial->setMinValue(props->getFloatValue("min", 0.0));
525         dial->setMaxValue(props->getFloatValue("max", 1.0));
526         dial->setWrap(props->getBoolValue("wrap", true));
527         setupObject(dial, props);
528         return dial;
529     } else if (type == "textbox") {
530        int slider_width = props->getIntValue("slider", parentHeight);
531        int wrap = props->getBoolValue("wrap", true);
532        if (slider_width==0) slider_width=20;
533        puLargeInput * puTextBox =
534                      new puLargeInput(x, y, x+width, x+height, 2, slider_width, wrap);
535        if  (props->hasValue("editable"))
536        {
537           if (props->getBoolValue("editable")==false)
538              puTextBox->disableInput();
539           else
540              puTextBox->enableInput();
541        }
542        setupObject(puTextBox,props);
543        return puTextBox;
544     } else if (type == "select") {
545         vector<SGPropertyNode_ptr> value_nodes;
546         SGPropertyNode * selection_node =
547                 fgGetNode(props->getChild("selection")->getStringValue(), true);
548
549         for (int q = 0; q < selection_node->nChildren(); q++)
550             value_nodes.push_back(selection_node->getChild(q));
551
552         char ** entries = make_char_array(value_nodes.size());
553         for (unsigned int i = 0, j = value_nodes.size() - 1;
554              i < value_nodes.size();
555              i++, j--)
556             entries[i] = strdup((char *)value_nodes[i]->getName());
557         puSelectBox * select =
558             new puSelectBox(x, y, x + width, y + height, entries);
559         setupObject(select, props);
560         return select;
561     } else {
562         return 0;
563     }
564 }
565
566 void
567 FGDialog::setupObject (puObject * object, SGPropertyNode * props)
568 {
569     object->setLabelPlace(PUPLACE_CENTERED_RIGHT);
570
571     if (props->hasValue("legend"))
572         object->setLegend(props->getStringValue("legend"));
573
574     if (props->hasValue("label"))
575         object->setLabel(props->getStringValue("label"));
576
577     if (props->hasValue("border"))
578         object->setBorderThickness( props->getIntValue("border", 2) );
579
580     if ( SGPropertyNode *nft = props->getNode("font", false) ) {
581        SGPath path( _font_path );
582        const char *name = nft->getStringValue("name", "default");
583        float size = nft->getFloatValue("size", 13.0);
584        float slant = nft->getFloatValue("slant", 0.0);
585        path.append( name );
586        path.concat( ".txf" );
587
588        fntFont *font = new fntTexFont;
589        font->load( (char *)path.c_str() );
590
591        puFont lfnt(font, size, slant);
592        object->setLabelFont( lfnt );
593     }
594
595     sgVec4 color;
596     sgCopyVec4(color, _fgcolor);
597     getColor(props->getNode("color"), color);
598     object->setColor(PUCOL_LABEL, color[0], color[1], color[2], color[3]);
599
600     if (props->hasValue("property")) {
601         const char * name = props->getStringValue("name");
602         if (name == 0)
603             name = "";
604         const char * propname = props->getStringValue("property");
605         SGPropertyNode_ptr node = fgGetNode(propname, true);
606         copy_to_pui(node, object);
607         PropertyObject* po = new PropertyObject(name, object, node);
608         _propertyObjects.push_back(po);
609         if(props->getBoolValue("live"))
610             _liveObjects.push_back(po);
611     }
612
613     SGPropertyNode * dest = fgGetNode("/sim/bindings/gui", true);
614     vector<SGPropertyNode_ptr> bindings = props->getChildren("binding");
615     if (bindings.size() > 0) {
616         GUIInfo * info = new GUIInfo(this);
617
618         for (unsigned int i = 0; i < bindings.size(); i++) {
619             unsigned int j = 0;
620             SGPropertyNode *binding;
621             while (dest->getChild("binding", j))
622                 j++;
623
624             binding = dest->getChild("binding", j, true);
625             copyProperties(bindings[i], binding);
626             info->bindings.push_back(new FGBinding(binding));
627         }
628         object->setCallback(action_callback);
629         object->setUserData(info);
630         _info.push_back(info);
631     }
632
633     object->makeReturnDefault(props->getBoolValue("default"));
634 }
635
636 void
637 FGDialog::setupGroup (puGroup * group, SGPropertyNode * props,
638                     int width, int height, sgVec4 color, bool makeFrame)
639 {
640     setupObject(group, props);
641
642     if (makeFrame) {
643         puFrame* f = new puFrame(0, 0, width, height);
644         f->setColorScheme(color[0], color[1], color[2], color[3]);
645     }
646
647     int nChildren = props->nChildren();
648     for (int i = 0; i < nChildren; i++)
649         makeObject(props->getChild(i), width, height);
650     group->close();
651 }
652
653 void
654 FGDialog::getColor (const SGPropertyNode * prop, sgVec4 color)
655 {
656     if (!prop)
657         return;
658
659     const SGPropertyNode *p;
660     if ((p = prop->getChild("red")))
661         color[0] = p->getFloatValue();
662     if ((p = prop->getChild("green")))
663         color[1] = p->getFloatValue();
664     if ((p = prop->getChild("blue")))
665         color[2] = p->getFloatValue();
666     if ((p = prop->getChild("alpha")))
667         color[3] = p->getFloatValue();
668 }
669
670 char **
671 FGDialog::make_char_array (int size)
672 {
673     char ** list = new char*[size+1];
674     for (int i = 0; i <= size; i++)
675         list[i] = 0;
676     _char_arrays.push_back(list);
677     return list;
678 }
679
680
681 \f
682 ////////////////////////////////////////////////////////////////////////
683 // Implementation of FGDialog::PropertyObject.
684 ////////////////////////////////////////////////////////////////////////
685
686 FGDialog::PropertyObject::PropertyObject (const char * n,
687                                            puObject * o,
688                                            SGPropertyNode_ptr p)
689     : name(n),
690       object(o),
691       node(p)
692 {
693 }
694
695
696 // end of dialog.cxx