]> git.mxchange.org Git - simgear.git/blob - simgear/props/props_io.cxx
Merge commit 'refs/merge-requests/9' of git://gitorious.org/fg/simgear into merge...
[simgear.git] / simgear / props / props_io.cxx
1 /**
2  * \file props_io.cxx
3  * Started Fall 2000 by David Megginson, david@megginson.com
4  * This code is released into the Public Domain.
5  *
6  * See props.html for documentation [replace with URL when available].
7  *
8  * $Id$
9  */
10
11 #ifdef HAVE_CONFIG_H
12 #  include <simgear_config.h>
13 #endif
14
15 #include <simgear/compiler.h>
16
17 #include <stdlib.h>             // atof() atoi()
18
19 #include <simgear/sg_inlines.h>
20 #include <simgear/debug/logstream.hxx>
21 #include <simgear/math/SGMath.hxx>
22 #include <simgear/misc/sg_path.hxx>
23 #include <simgear/xml/easyxml.hxx>
24 #include <simgear/misc/ResourceManager.hxx>
25
26 #include "props.hxx"
27 #include "props_io.hxx"
28
29 #include <iostream>
30 #include <fstream>
31 #include <string>
32 #include <cstring>              // strcmp()
33 #include <vector>
34 #include <map>
35
36 using std::istream;
37 using std::ifstream;
38 using std::ostream;
39 using std::ofstream;
40 using std::string;
41 using std::vector;
42 using std::map;
43
44 using std::endl;
45
46 #define DEFAULT_MODE (SGPropertyNode::READ|SGPropertyNode::WRITE)
47
48
49 \f
50 ////////////////////////////////////////////////////////////////////////
51 // Property list visitor, for XML parsing.
52 ////////////////////////////////////////////////////////////////////////
53
54 class PropsVisitor : public XMLVisitor
55 {
56 public:
57
58   PropsVisitor (SGPropertyNode * root, const string &base, int default_mode = 0,
59                 bool extended = false)
60     : _default_mode(default_mode), _root(root), _level(0), _base(base),
61       _hasException(false), _extended(extended)
62   {}
63
64   virtual ~PropsVisitor () {}
65
66   void startXML ();
67   void endXML ();
68   void startElement (const char * name, const XMLAttributes &atts);
69   void endElement (const char * name);
70   void data (const char * s, int length);
71   void warning (const char * message, int line, int column);
72
73   bool hasException () const { return _hasException; }
74   sg_io_exception &getException () { return _exception; }
75   void setException (const sg_io_exception &exception) {
76     _exception = exception;
77     _hasException = true;
78   }
79
80 private:
81
82   struct State
83   {
84     State () : node(0), type(""), mode(DEFAULT_MODE), omit(false) {}
85     State (SGPropertyNode * _node, const char * _type, int _mode, bool _omit)
86       : node(_node), type(_type), mode(_mode), omit(_omit) {}
87     SGPropertyNode * node;
88     string type;
89     int mode;
90     bool omit;
91     map<string,int> counters;
92   };
93
94   State &state () { return _state_stack[_state_stack.size() - 1]; }
95
96   void push_state (SGPropertyNode * node, const char * type, int mode, bool omit = false) {
97     if (type == 0)
98       _state_stack.push_back(State(node, "unspecified", mode, omit));
99     else
100       _state_stack.push_back(State(node, type, mode, omit));
101     _level++;
102     _data = "";
103   }
104
105   void pop_state () {
106     _state_stack.pop_back();
107     _level--;
108   }
109
110   int _default_mode;
111   string _data;
112   SGPropertyNode * _root;
113   SGPropertyNode null;
114   int _level;
115   vector<State> _state_stack;
116   string _base;
117   sg_io_exception _exception;
118   bool _hasException;
119   bool _extended;
120 };
121
122 void
123 PropsVisitor::startXML ()
124 {
125   _level = 0;
126   _state_stack.resize(0);
127 }
128
129 void
130 PropsVisitor::endXML ()
131 {
132   _level = 0;
133   _state_stack.resize(0);
134 }
135
136
137 /**
138  * Check a yes/no flag, with default.
139  */
140 static bool
141 checkFlag (const char * flag, bool defaultState = true)
142 {
143   if (flag == 0)
144     return defaultState;
145   else if (!strcmp(flag, "y"))
146     return true;
147   else if (!strcmp(flag, "n"))
148     return false;
149   else {
150     string message = "Unrecognized flag value '";
151     message += flag;
152     message += '\'';
153                                 // FIXME: add location info
154     throw sg_io_exception(message, "SimGear Property Reader");
155   }
156 }
157
158 void
159 PropsVisitor::startElement (const char * name, const XMLAttributes &atts)
160 {
161   const char * attval;
162
163   if (_level == 0) {
164     if (strcmp(name, "PropertyList")) {
165       string message = "Root element name is ";
166       message += name;
167       message += "; expected PropertyList";
168       throw sg_io_exception(message, "SimGear Property Reader");
169     }
170
171                                 // Check for an include.
172     attval = atts.getValue("include");
173     if (attval != 0) {
174       try {
175           SGPath path = simgear::ResourceManager::instance()->findPath(attval, SGPath(_base).dir());
176           if (path.isNull())
177           {
178               throw sg_io_exception("Cannot open file", sg_location(attval));
179           }
180           readProperties(path.str(), _root, 0, _extended);
181       } catch (sg_io_exception &e) {
182           setException(e);
183       }
184     }
185
186     push_state(_root, "", DEFAULT_MODE);
187   }
188
189   else {
190     State &st = state();
191                                 // Get the index.
192     attval = atts.getValue("n");
193     int index = 0;
194     string strName(name);
195     if (attval != 0) {
196       index = atoi(attval);
197       st.counters[strName] = SG_MAX2(st.counters[strName], index+1);
198     } else {
199       index = st.counters[strName];
200       st.counters[strName]++;
201     }
202
203                                 // Got the index, so grab the node.
204     SGPropertyNode * node = st.node->getChild(strName, index, true);
205     if (!node->getAttribute(SGPropertyNode::WRITE)) {
206       SG_LOG(SG_INPUT, SG_ALERT, "Not overwriting write-protected property "
207           << node->getPath(true));
208       node = &null;
209     }
210
211                                 // Get the access-mode attributes,
212                                 // but don't set yet (in case they
213                                 // prevent us from recording the value).
214     int mode = _default_mode;
215
216     attval = atts.getValue("read");
217     if (checkFlag(attval, true))
218       mode |= SGPropertyNode::READ;
219     attval = atts.getValue("write");
220     if (checkFlag(attval, true))
221       mode |= SGPropertyNode::WRITE;
222     attval = atts.getValue("archive");
223     if (checkFlag(attval, false))
224       mode |= SGPropertyNode::ARCHIVE;
225     attval = atts.getValue("trace-read");
226     if (checkFlag(attval, false))
227       mode |= SGPropertyNode::TRACE_READ;
228     attval = atts.getValue("trace-write");
229     if (checkFlag(attval, false))
230       mode |= SGPropertyNode::TRACE_WRITE;
231     attval = atts.getValue("userarchive");
232     if (checkFlag(attval, false))
233       mode |= SGPropertyNode::USERARCHIVE;
234     attval = atts.getValue("preserve");
235     if (checkFlag(attval, false))
236       mode |= SGPropertyNode::PRESERVE;
237
238                                 // Check for an alias.
239     attval = atts.getValue("alias");
240     if (attval != 0) {
241       if (!node->alias(attval))
242         SG_LOG(SG_INPUT, SG_ALERT, "Failed to set alias to " << attval);
243     }
244
245                                 // Check for an include.
246     bool omit = false;
247     attval = atts.getValue("include");
248     if (attval != 0) {
249       try {
250           SGPath path = simgear::ResourceManager::instance()->findPath(attval, SGPath(_base).dir());
251           if (path.isNull())
252           {
253               throw sg_io_exception("Cannot open file", sg_location(attval));
254           }
255           readProperties(path.str(), node, 0, _extended);
256       } catch (sg_io_exception &e) {
257           setException(e);
258       }
259
260       attval = atts.getValue("omit-node");
261       omit = checkFlag(attval, false);
262     }
263
264     const char *type = atts.getValue("type");
265     if (type)
266       node->clearValue();
267     push_state(node, type, mode, omit);
268   }
269 }
270
271 void
272 PropsVisitor::endElement (const char * name)
273 {
274   State &st = state();
275   bool ret;
276
277                                 // If there are no children and it's
278                                 // not an alias, then it's a leaf value.
279   if (st.node->nChildren() == 0 && !st.node->isAlias()) {
280     if (st.type == "bool") {
281       if (_data == "true" || atoi(_data.c_str()) != 0)
282         ret = st.node->setBoolValue(true);
283       else
284         ret = st.node->setBoolValue(false);
285     } else if (st.type == "int") {
286       ret = st.node->setIntValue(atoi(_data.c_str()));
287     } else if (st.type == "long") {
288       ret = st.node->setLongValue(strtol(_data.c_str(), 0, 0));
289     } else if (st.type == "float") {
290       ret = st.node->setFloatValue(atof(_data.c_str()));
291     } else if (st.type == "double") {
292       ret = st.node->setDoubleValue(strtod(_data.c_str(), 0));
293     } else if (st.type == "string") {
294       ret = st.node->setStringValue(_data.c_str());
295     } else if (st.type == "vec3d" && _extended) {
296       ret = st.node
297         ->setValue(simgear::parseString<SGVec3d>(_data));
298     } else if (st.type == "vec4d" && _extended) {
299       ret = st.node
300         ->setValue(simgear::parseString<SGVec4d>(_data));
301     } else if (st.type == "unspecified") {
302       ret = st.node->setUnspecifiedValue(_data.c_str());
303     } else if (_level == 1) {
304       ret = true;               // empty <PropertyList>
305     } else {
306       string message = "Unrecognized data type '";
307       message += st.type;
308       message += '\'';
309                                 // FIXME: add location information
310       throw sg_io_exception(message, "SimGear Property Reader");
311     }
312     if (!ret)
313       SG_LOG(SG_INPUT, SG_ALERT, "readProperties: Failed to set "
314              << st.node->getPath() << " to value \""
315              << _data << "\" with type " << st.type);
316   }
317
318                                 // Set the access-mode attributes now,
319                                 // once the value has already been 
320                                 // assigned.
321   st.node->setAttributes(st.mode);
322
323   if (st.omit) {
324     State &parent = _state_stack[_state_stack.size() - 2];
325     int nChildren = st.node->nChildren();
326     for (int i = 0; i < nChildren; i++) {
327       SGPropertyNode *src = st.node->getChild(i);
328       const char *name = src->getName();
329       int index = parent.counters[name];
330       parent.counters[name]++;
331       SGPropertyNode *dst = parent.node->getChild(name, index, true);
332       copyProperties(src, dst);
333     }
334     parent.node->removeChild(st.node->getName(), st.node->getIndex(), false);
335   }
336   pop_state();
337 }
338
339 void
340 PropsVisitor::data (const char * s, int length)
341 {
342   if (state().node->nChildren() == 0)
343     _data.append(string(s, length));
344 }
345
346 void
347 PropsVisitor::warning (const char * message, int line, int column)
348 {
349   SG_LOG(SG_INPUT, SG_ALERT, "readProperties: warning: "
350          << message << " at line " << line << ", column " << column);
351 }
352
353
354 \f
355 ////////////////////////////////////////////////////////////////////////
356 // Property list reader.
357 ////////////////////////////////////////////////////////////////////////
358
359
360 /**
361  * Read properties from an input stream.
362  *
363  * @param input The input stream containing an XML property file.
364  * @param start_node The root node for reading properties.
365  * @param base A base path for resolving external include references.
366  * @return true if the read succeeded, false otherwise.
367  */
368 void
369 readProperties (istream &input, SGPropertyNode * start_node,
370                 const string &base, int default_mode, bool extended)
371 {
372   PropsVisitor visitor(start_node, base, default_mode, extended);
373   readXML(input, visitor, base);
374   if (visitor.hasException())
375     throw visitor.getException();
376 }
377
378
379 /**
380  * Read properties from a file.
381  *
382  * @param file A string containing the file path.
383  * @param start_node The root node for reading properties.
384  * @return true if the read succeeded, false otherwise.
385  */
386 void
387 readProperties (const string &file, SGPropertyNode * start_node,
388                 int default_mode, bool extended)
389 {
390   PropsVisitor visitor(start_node, file, default_mode, extended);
391   readXML(file, visitor);
392   if (visitor.hasException())
393     throw visitor.getException();
394 }
395
396
397 /**
398  * Read properties from an in-memory buffer.
399  *
400  * @param buf A character buffer containing the xml data.
401  * @param size The size/length of the buffer in bytes
402  * @param start_node The root node for reading properties.
403  * @return true if the read succeeded, false otherwise.
404  */
405 void readProperties (const char *buf, const int size,
406                      SGPropertyNode * start_node, int default_mode,
407                      bool extended)
408 {
409   PropsVisitor visitor(start_node, "", default_mode, extended);
410   readXML(buf, size, visitor);
411   if (visitor.hasException())
412     throw visitor.getException();
413 }
414
415 \f
416 ////////////////////////////////////////////////////////////////////////
417 // Property list writer.
418 ////////////////////////////////////////////////////////////////////////
419
420 #define INDENT_STEP 2
421
422 /**
423  * Return the type name.
424  */
425 static const char *
426 getTypeName (simgear::props::Type type)
427 {
428   using namespace simgear;
429   switch (type) {
430   case props::UNSPECIFIED:
431     return "unspecified";
432   case props::BOOL:
433     return "bool";
434   case props::INT:
435     return "int";
436   case props::LONG:
437     return "long";
438   case props::FLOAT:
439     return "float";
440   case props::DOUBLE:
441     return "double";
442   case props::STRING:
443     return "string";
444   case props::VEC3D:
445     return "vec3d";
446   case props::VEC4D:
447     return "vec4d";
448   case props::ALIAS:
449   case props::NONE:
450     return "unspecified";
451   default: // avoid compiler warning
452     break;
453   }
454
455   // keep the compiler from squawking
456   return "unspecified";
457 }
458
459
460 /**
461  * Escape characters for output.
462  */
463 static void
464 writeData (ostream &output, const string &data)
465 {
466   for (int i = 0; i < (int)data.size(); i++) {
467     switch (data[i]) {
468     case '&':
469       output << "&amp;";
470       break;
471     case '<':
472       output << "&lt;";
473       break;
474     case '>':
475       output << "&gt;";
476       break;
477     default:
478       output << data[i];
479       break;
480     }
481   }
482 }
483
484 static void
485 doIndent (ostream &output, int indent)
486 {
487   while (indent-- > 0) {
488     output << ' ';
489   }
490 }
491
492
493 static void
494 writeAtts (ostream &output, const SGPropertyNode * node, bool forceindex)
495 {
496   int index = node->getIndex();
497
498   if (index != 0 || forceindex)
499     output << " n=\"" << index << '"';
500
501 #if 0
502   if (!node->getAttribute(SGPropertyNode::READ))
503     output << " read=\"n\"";
504
505   if (!node->getAttribute(SGPropertyNode::WRITE))
506     output << " write=\"n\"";
507
508   if (node->getAttribute(SGPropertyNode::ARCHIVE))
509     output << " archive=\"y\"";
510 #endif
511
512 }
513
514
515 /**
516  * Test whether a node is archivable or has archivable descendants.
517  */
518 static bool
519 isArchivable (const SGPropertyNode * node, SGPropertyNode::Attribute archive_flag)
520 {
521   // FIXME: it's inefficient to do this all the time
522   if (node->getAttribute(archive_flag))
523     return true;
524   else {
525     int nChildren = node->nChildren();
526     for (int i = 0; i < nChildren; i++)
527       if (isArchivable(node->getChild(i), archive_flag))
528         return true;
529   }
530   return false;
531 }
532
533
534 static bool
535 writeNode (ostream &output, const SGPropertyNode * node,
536            bool write_all, int indent, SGPropertyNode::Attribute archive_flag)
537 {
538                                 // Don't write the node or any of
539                                 // its descendants unless it is
540                                 // allowed to be archived.
541   if (!write_all && !isArchivable(node, archive_flag))
542     return true;                // Everything's OK, but we won't write.
543
544   const string name = node->getName();
545   int nChildren = node->nChildren();
546   bool node_has_value = false;
547
548                                 // If there is a literal value,
549                                 // write it first.
550   if (node->hasValue() && (write_all || node->getAttribute(archive_flag))) {
551     doIndent(output, indent);
552     output << '<' << name;
553     writeAtts(output, node, nChildren != 0);
554     if (node->isAlias() && node->getAliasTarget() != 0) {
555       output << " alias=\"" << node->getAliasTarget()->getPath()
556              << "\"/>" << endl;
557     } else {
558       if (node->getType() != simgear::props::UNSPECIFIED)
559         output << " type=\"" << getTypeName(node->getType()) << '"';
560       output << '>';
561       writeData(output, node->getStringValue());
562       output << "</" << name << '>' << endl;
563     }
564     node_has_value = true;
565   }
566
567                                 // If there are children, write them next.
568   if (nChildren > 0) {
569     doIndent(output, indent);
570     output << '<' << name;
571     writeAtts(output, node, node_has_value);
572     output << '>' << endl;
573     for (int i = 0; i < nChildren; i++)
574       writeNode(output, node->getChild(i), write_all, indent + INDENT_STEP, archive_flag);
575     doIndent(output, indent);
576     output << "</" << name << '>' << endl;
577   }
578
579   return true;
580 }
581
582
583 void
584 writeProperties (ostream &output, const SGPropertyNode * start_node,
585                  bool write_all, SGPropertyNode::Attribute archive_flag)
586 {
587   int nChildren = start_node->nChildren();
588
589   output << "<?xml version=\"1.0\"?>" << endl << endl;
590   output << "<PropertyList>" << endl;
591
592   for (int i = 0; i < nChildren; i++) {
593     writeNode(output, start_node->getChild(i), write_all, INDENT_STEP, archive_flag);
594   }
595
596   output << "</PropertyList>" << endl;
597 }
598
599
600 void
601 writeProperties (const string &file, const SGPropertyNode * start_node,
602                  bool write_all, SGPropertyNode::Attribute archive_flag)
603 {
604   SGPath path(file.c_str());
605   path.create_dir(0777);
606
607   ofstream output(file.c_str());
608   if (output.good()) {
609     writeProperties(output, start_node, write_all, archive_flag);
610   } else {
611     throw sg_io_exception("Cannot open file", sg_location(file));
612   }
613 }
614
615 // Another variation, useful when called from gdb
616 void
617 writeProperties (const char* file, const SGPropertyNode * start_node)
618 {
619     writeProperties(string(file), start_node, true);
620 }
621
622
623 \f
624 ////////////////////////////////////////////////////////////////////////
625 // Copy properties from one tree to another.
626 ////////////////////////////////////////////////////////////////////////
627
628
629 /**
630  * Copy one property tree to another.
631  * 
632  * @param in The source property tree.
633  * @param out The destination property tree.
634  * @param attr_value Only copy properties with given attribute values.
635  * @param attr_mask  Mask for attributes to be considered by attr_value
636  *                   (default is 0 = attributes not considered, all
637  *                   properties copied).
638  * @return true if all properties were copied, false if some failed
639  *  (for example, if the property's value is tied read-only).
640  */
641 bool
642 copyProperties (const SGPropertyNode *in, SGPropertyNode *out,
643                 int attr_value, int attr_mask)
644 {
645   using namespace simgear;
646   bool retval = true;
647
648                                 // First, copy the actual value,
649                                 // if any.
650   if (in->hasValue()) {
651     switch (in->getType()) {
652     case props::BOOL:
653       if (!out->setBoolValue(in->getBoolValue()))
654         retval = false;
655       break;
656     case props::INT:
657       if (!out->setIntValue(in->getIntValue()))
658         retval = false;
659       break;
660     case props::LONG:
661       if (!out->setLongValue(in->getLongValue()))
662         retval = false;
663       break;
664     case props::FLOAT:
665       if (!out->setFloatValue(in->getFloatValue()))
666         retval = false;
667       break;
668     case props::DOUBLE:
669       if (!out->setDoubleValue(in->getDoubleValue()))
670         retval = false;
671       break;
672     case props::STRING:
673       if (!out->setStringValue(in->getStringValue()))
674         retval = false;
675       break;
676     case props::UNSPECIFIED:
677       if (!out->setUnspecifiedValue(in->getStringValue()))
678         retval = false;
679       break;
680     case props::VEC3D:
681       if (!out->setValue(in->getValue<SGVec3d>()))
682         retval = false;
683       break;
684     case props::VEC4D:
685       if (!out->setValue(in->getValue<SGVec4d>()))
686         retval = false;
687       break;
688     default:
689       if (in->isAlias())
690         break;
691       string message = "Unknown internal SGPropertyNode type";
692       message += in->getType();
693       throw sg_error(message, "SimGear Property Reader");
694     }
695   }
696
697   // copy the attributes.
698   out->setAttributes( in->getAttributes() );
699
700   // Next, copy the children.
701   int nChildren = in->nChildren();
702   for (int i = 0; i < nChildren; i++) {
703     const SGPropertyNode * in_child = in->getChild(i);
704     int mask = attr_mask;
705     /* attributes have no meaning for nodes without values - except
706      * the PRESERVE flag. So ignore them. */
707     if (!in_child->hasValue())
708         mask &= SGPropertyNode::PRESERVE;
709     if ((in_child->getAttributes() & mask) == (attr_value & mask))
710     {
711       SGPropertyNode * out_child = out->getChild(in_child->getNameString(),
712                              in_child->getIndex(),
713                              false);
714       if (!out_child)
715       {
716           out_child = out->getChild(in_child->getNameString(),
717                                     in_child->getIndex(),
718                                     true);
719       }
720       else
721       {
722           mask = attr_mask;
723           if (!out_child->hasValue())
724               mask &= SGPropertyNode::PRESERVE;
725           if ((out_child->getAttributes() & mask) != (attr_value & mask))
726               out_child = NULL;
727       }
728       if (out_child &&
729           (!copyProperties(in_child, out_child, attr_value, attr_mask)))
730           retval = false;
731     }
732   }
733
734   return retval;
735 }
736
737 // end of props_io.cxx