]> git.mxchange.org Git - simgear.git/blob - simgear/misc/props_io.cxx
Misc Irix tweaks.
[simgear.git] / simgear / misc / props_io.cxx
1
2 #include <simgear/compiler.h>
3
4 #include <stdlib.h>             // atof() atoi()
5
6 #include <simgear/sg_inlines.h>
7 #include <simgear/debug/logstream.hxx>
8 #include <simgear/xml/easyxml.hxx>
9
10 #include "sg_path.hxx"
11 #include "props.hxx"
12
13 #include STL_IOSTREAM
14 #if !defined(SG_HAVE_NATIVE_SGI_COMPILERS)
15 #  include <fstream>
16 #else
17 #  include <fstream.h>
18 #endif
19 #include STL_STRING
20 #include <vector>
21 #include <map>
22
23 #if !defined(SG_HAVE_NATIVE_SGI_COMPILERS)
24 SG_USING_STD(istream);
25 SG_USING_STD(ifstream);
26 SG_USING_STD(ostream);
27 SG_USING_STD(ofstream);
28 #endif
29 SG_USING_STD(string);
30 SG_USING_STD(vector);
31 SG_USING_STD(map);
32
33 #define DEFAULT_MODE (SGPropertyNode::READ|SGPropertyNode::WRITE)
34
35
36 \f
37 ////////////////////////////////////////////////////////////////////////
38 // Property list visitor, for XML parsing.
39 ////////////////////////////////////////////////////////////////////////
40
41 class PropsVisitor : public XMLVisitor
42 {
43 public:
44
45   PropsVisitor (SGPropertyNode * root, const string &base)
46     : _root(root), _level(0), _base(base), _hasException(false) {}
47
48   virtual ~PropsVisitor () {}
49
50   void startXML ();
51   void endXML ();
52   void startElement (const char * name, const XMLAttributes &atts);
53   void endElement (const char * name);
54   void data (const char * s, int length);
55   void warning (const char * message, int line, int column);
56
57   bool hasException () const { return _hasException; }
58   sg_io_exception &getException () { return _exception; }
59   void setException (const sg_io_exception &exception) {
60     _exception = exception;
61     _hasException = true;
62   }
63
64 private:
65
66   struct State
67   {
68     State () : node(0), type(""), mode(DEFAULT_MODE) {}
69     State (SGPropertyNode * _node, const char * _type, int _mode)
70       : node(_node), type(_type), mode(_mode) {}
71     SGPropertyNode * node;
72     string type;
73     int mode;
74     map<string,int> counters;
75   };
76
77   State &state () { return _state_stack[_state_stack.size() - 1]; }
78
79   void push_state (SGPropertyNode * node, const char * type, int mode) {
80     if (type == 0)
81       _state_stack.push_back(State(node, "unspecified", mode));
82     else
83       _state_stack.push_back(State(node, type, mode));
84     _level++;
85     _data = "";
86   }
87
88   void pop_state () {
89     _state_stack.pop_back();
90     _level--;
91   }
92
93   string _data;
94   SGPropertyNode * _root;
95   int _level;
96   vector<State> _state_stack;
97   string _base;
98   sg_io_exception _exception;
99   bool _hasException;
100 };
101
102 void
103 PropsVisitor::startXML ()
104 {
105   _level = 0;
106   _state_stack.resize(0);
107 }
108
109 void
110 PropsVisitor::endXML ()
111 {
112   _level = 0;
113   _state_stack.resize(0);
114 }
115
116
117 /**
118  * Check a yes/no flag, with default.
119  */
120 static bool
121 checkFlag (const char * flag, bool defaultState = true)
122 {
123   if (flag == 0)
124     return defaultState;
125   else if (string(flag) == "y")
126     return true;
127   else if (string(flag) == "n")
128     return false;
129   else {
130     string message = "Unrecognized flag value '";
131     message += flag;
132     message += '\'';
133                                 // FIXME: add location info
134     throw sg_io_exception(message, "SimGear Property Reader");
135   }
136 }
137
138 void
139 PropsVisitor::startElement (const char * name, const XMLAttributes &atts)
140 {
141   State &st = state();
142
143   if (_level == 0) {
144     if (string(name) != (string)"PropertyList") {
145       string message = "Root element name is ";
146       message += name;
147       message += "; expected PropertyList";
148       throw sg_io_exception(message, "SimGear Property Reader");
149     }
150     push_state(_root, "", DEFAULT_MODE);
151   }
152
153   else {
154
155     const char * attval;
156                                 // Get the index.
157     attval = atts.getValue("n");
158     int index = 0;
159     if (attval != 0) {
160       index = atoi(attval);
161       st.counters[name] = SG_MAX2(st.counters[name], index+1);
162     } else {
163       index = st.counters[name];
164       st.counters[name]++;
165     }
166
167                                 // Got the index, so grab the node.
168     SGPropertyNode * node = st.node->getChild(name, index, true);
169
170                                 // Get the access-mode attributes,
171                                 // but don't set yet (in case they
172                                 // prevent us from recording the value).
173     int mode = 0;
174
175     attval = atts.getValue("read");
176     if (checkFlag(attval, true))
177       mode |= SGPropertyNode::READ;
178     attval = atts.getValue("write");
179     if (checkFlag(attval, true))
180       mode |= SGPropertyNode::WRITE;
181     attval = atts.getValue("archive");
182     if (checkFlag(attval, false))
183       mode |= SGPropertyNode::ARCHIVE;
184
185                                 // Check for an alias.
186     attval = atts.getValue("alias");
187     if (attval != 0) {
188       if (!node->alias(attval))
189         SG_LOG(SG_INPUT, SG_ALERT, "Failed to set alias to " << attval);
190     }
191
192                                 // Check for an include.
193     attval = atts.getValue("include");
194     if (attval != 0) {
195       SGPath path(SGPath(_base).dir());
196       path.append(attval);
197       try {
198         readProperties(path.str(), node);
199       } catch (sg_io_exception &e) {
200         setException(e);
201       }
202     }
203
204     push_state(node, atts.getValue("type"), mode);
205   }
206 }
207
208 void
209 PropsVisitor::endElement (const char * name)
210 {
211   State &st = state();
212   bool ret;
213
214                                 // If there are no children and it's
215                                 // not an alias, then it's a leaf value.
216   if (st.node->nChildren() == 0 && !st.node->isAlias()) {
217     if (st.type == "bool") {
218       if (_data == "true" || atoi(_data.c_str()) != 0)
219         ret = st.node->setBoolValue(true);
220       else
221         ret = st.node->setBoolValue(false);
222     } else if (st.type == "int") {
223       ret = st.node->setIntValue(atoi(_data.c_str()));
224     } else if (st.type == "long") {
225       ret = st.node->setLongValue(strtol(_data.c_str(), 0, 0));
226     } else if (st.type == "float") {
227       ret = st.node->setFloatValue(atof(_data.c_str()));
228     } else if (st.type == "double") {
229       ret = st.node->setDoubleValue(strtod(_data.c_str(), 0));
230     } else if (st.type == "string") {
231       ret = st.node->setStringValue(_data);
232     } else if (st.type == "unspecified") {
233       ret = st.node->setUnspecifiedValue(_data);
234     } else {
235       string message = "Unrecognized data type '";
236       message += st.type;
237       message += '\'';
238                                 // FIXME: add location information
239       throw sg_io_exception(message, "SimGear Property Reader");
240     }
241     if (!ret)
242       SG_LOG(SG_INPUT, SG_ALERT, "readProperties: Failed to set "
243              << st.node->getPath() << " to value \""
244              << _data << "\" with type " << st.type);
245   }
246
247                                 // Set the access-mode attributes now,
248                                 // once the value has already been 
249                                 // assigned.
250   st.node->setAttributes(st.mode);
251
252   pop_state();
253 }
254
255 void
256 PropsVisitor::data (const char * s, int length)
257 {
258   if (state().node->nChildren() == 0)
259     _data.append(string(s, length));
260 }
261
262 void
263 PropsVisitor::warning (const char * message, int line, int column)
264 {
265   SG_LOG(SG_INPUT, SG_ALERT, "readProperties: warning: "
266          << message << " at line " << line << ", column " << column);
267 }
268
269
270 \f
271 ////////////////////////////////////////////////////////////////////////
272 // Property list reader.
273 ////////////////////////////////////////////////////////////////////////
274
275
276 /**
277  * Read properties from an input stream.
278  *
279  * @param input The input stream containing an XML property file.
280  * @param start_node The root node for reading properties.
281  * @param base A base path for resolving external include references.
282  * @return true if the read succeeded, false otherwise.
283  */
284 void
285 readProperties (istream &input, SGPropertyNode * start_node,
286                 const string &base)
287 {
288   PropsVisitor visitor(start_node, base);
289   readXML(input, visitor, base);
290   if (visitor.hasException())
291     throw visitor.getException();
292 }
293
294
295 /**
296  * Read properties from a file.
297  *
298  * @param file A string containing the file path.
299  * @param start_node The root node for reading properties.
300  * @return true if the read succeeded, false otherwise.
301  */
302 void
303 readProperties (const string &file, SGPropertyNode * start_node)
304 {
305   PropsVisitor visitor(start_node, file);
306   readXML(file, visitor);
307   if (visitor.hasException())
308     throw visitor.getException();
309 }
310
311
312 \f
313 ////////////////////////////////////////////////////////////////////////
314 // Property list writer.
315 ////////////////////////////////////////////////////////////////////////
316
317 #define INDENT_STEP 2
318
319 /**
320  * Return the type name.
321  */
322 static const char *
323 getTypeName (SGPropertyNode::Type type)
324 {
325   switch (type) {
326   case SGPropertyNode::UNSPECIFIED:
327     return "unspecified";
328   case SGPropertyNode::BOOL:
329     return "bool";
330   case SGPropertyNode::INT:
331     return "int";
332   case SGPropertyNode::LONG:
333     return "long";
334   case SGPropertyNode::FLOAT:
335     return "float";
336   case SGPropertyNode::DOUBLE:
337     return "double";
338   case SGPropertyNode::STRING:
339     return "string";
340   }
341
342   // keep the compiler from squawking
343   return "unspecified";
344 }
345
346
347 /**
348  * Escape characters for output.
349  */
350 static void
351 writeData (ostream &output, const string &data)
352 {
353   for (int i = 0; i < (int)data.size(); i++) {
354     switch (data[i]) {
355     case '&':
356       output << "&amp;";
357       break;
358     case '<':
359       output << "&lt;";
360       break;
361     case '>':
362       output << "&gt;";
363       break;
364     default:
365       output << data[i];
366       break;
367     }
368   }
369 }
370
371 static void
372 doIndent (ostream &output, int indent)
373 {
374   while (indent-- > 0) {
375     output << ' ';
376   }
377 }
378
379
380 static void
381 writeAtts (ostream &output, const SGPropertyNode * node)
382 {
383   int index = node->getIndex();
384
385   if (index != 0)
386     output << " n=\"" << index << '"';
387
388 #if 0
389   if (!node->getAttribute(SGPropertyNode::READ))
390     output << " read=\"n\"";
391
392   if (!node->getAttribute(SGPropertyNode::WRITE))
393     output << " write=\"n\"";
394
395   if (node->getAttribute(SGPropertyNode::ARCHIVE))
396     output << " archive=\"y\"";
397 #endif
398
399 }
400
401
402 /**
403  * Test whether a node is archivable or has archivable descendants.
404  */
405 static bool
406 isArchivable (const SGPropertyNode * node)
407 {
408   // FIXME: it's inefficient to do this all the time
409   if (node->getAttribute(SGPropertyNode::ARCHIVE))
410     return true;
411   else {
412     int nChildren = node->nChildren();
413     for (int i = 0; i < nChildren; i++)
414       if (isArchivable(node->getChild(i)))
415         return true;
416   }
417   return false;
418 }
419
420
421 static bool
422 writeNode (ostream &output, const SGPropertyNode * node, int indent)
423 {
424                                 // Don't write the node or any of
425                                 // its descendants unless it is
426                                 // allowed to be archived.
427   if (!isArchivable(node))
428     return true;                // Everything's OK, but we won't write.
429
430   const string &name = node->getName();
431   int index = node->getIndex();
432   int nChildren = node->nChildren();
433
434                                 // If there is a literal value,
435                                 // write it first.
436   if (node->hasValue() && node->getAttribute(SGPropertyNode::ARCHIVE)) {
437     doIndent(output, indent);
438     output << '<' << name;
439     writeAtts(output, node);
440     if (node->isAlias() && node->getAliasTarget() != 0) {
441       output << " alias=\"" << node->getAliasTarget()->getPath()
442              << "\"/>" << endl;
443     } else {
444       if (node->getType() != SGPropertyNode::UNSPECIFIED)
445         output << " type=\"" << getTypeName(node->getType()) << '"';
446       output << '>';
447       writeData(output, node->getStringValue());
448       output << "</" << name << '>' << endl;
449     }
450   }
451
452                                 // If there are children, write them
453                                 // next.
454   if (nChildren > 0 || node->isAlias()) {
455     doIndent(output, indent);
456     output << '<' << name;
457     writeAtts(output, node);
458     output << '>' << endl;
459     for (int i = 0; i < nChildren; i++)
460       writeNode(output, node->getChild(i), indent + INDENT_STEP);
461     doIndent(output, indent);
462     output << "</" << name << '>' << endl;
463   }
464
465   return true;
466 }
467
468
469 void
470 writeProperties (ostream &output, const SGPropertyNode * start_node)
471 {
472   int nChildren = start_node->nChildren();
473
474   output << "<?xml version=\"1.0\"?>" << endl << endl;
475   output << "<PropertyList>" << endl;
476
477   for (int i = 0; i < nChildren; i++) {
478     writeNode(output, start_node->getChild(i), INDENT_STEP);
479   }
480
481   output << "</PropertyList>" << endl;
482 }
483
484
485 void
486 writeProperties (const string &file, const SGPropertyNode * start_node)
487 {
488   ofstream output(file.c_str());
489   if (output.good()) {
490     writeProperties(output, start_node);
491   } else {
492     throw sg_io_exception("Cannot open file", sg_location(file));
493   }
494 }
495
496
497 \f
498 ////////////////////////////////////////////////////////////////////////
499 // Copy properties from one tree to another.
500 ////////////////////////////////////////////////////////////////////////
501
502
503 /**
504  * Copy one property tree to another.
505  * 
506  * @param in The source property tree.
507  * @param out The destination property tree.
508  * @return true if all properties were copied, false if some failed
509  *  (for example, if the property's value is tied read-only).
510  */
511 bool
512 copyProperties (const SGPropertyNode *in, SGPropertyNode *out)
513 {
514   bool retval = true;
515
516                                 // First, copy the actual value,
517                                 // if any.
518   if (in->hasValue()) {
519     switch (in->getType()) {
520     case SGPropertyNode::BOOL:
521       if (!out->setBoolValue(in->getBoolValue()))
522         retval = false;
523       break;
524     case SGPropertyNode::INT:
525       if (!out->setIntValue(in->getIntValue()))
526         retval = false;
527       break;
528     case SGPropertyNode::LONG:
529       if (!out->setLongValue(in->getLongValue()))
530         retval = false;
531       break;
532     case SGPropertyNode::FLOAT:
533       if (!out->setFloatValue(in->getFloatValue()))
534         retval = false;
535       break;
536     case SGPropertyNode::DOUBLE:
537       if (!out->setDoubleValue(in->getDoubleValue()))
538         retval = false;
539       break;
540     case SGPropertyNode::STRING:
541       if (!out->setStringValue(in->getStringValue()))
542         retval = false;
543       break;
544     case SGPropertyNode::UNSPECIFIED:
545       if (!out->setUnspecifiedValue(in->getStringValue()))
546         retval = false;
547       break;
548     default:
549       string message = "Unknown internal SGPropertyNode type";
550       message += in->getType();
551       throw sg_error(message, "SimGear Property Reader");
552     }
553   }
554
555                                 // Next, copy the children.
556   int nChildren = in->nChildren();
557   for (int i = 0; i < nChildren; i++) {
558     const SGPropertyNode * in_child = in->getChild(i);
559     SGPropertyNode * out_child = out->getChild(in_child->getName(),
560                                                in_child->getIndex(),
561                                                true);
562     if (!copyProperties(in_child, out_child))
563       retval = false;
564   }
565
566   return retval;
567 }
568
569 // end of props_io.cxx