2 #include <simgear/compiler.h>
4 #include <stdlib.h> // atof() atoi()
6 #include <simgear/sg_inlines.h>
7 #include <simgear/debug/logstream.hxx>
8 #include <simgear/xml/easyxml.hxx>
10 #include "sg_path.hxx"
14 #if !defined(SG_HAVE_NATIVE_SGI_COMPILERS)
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);
33 #define DEFAULT_MODE (SGPropertyNode::READ|SGPropertyNode::WRITE)
37 ////////////////////////////////////////////////////////////////////////
38 // Property list visitor, for XML parsing.
39 ////////////////////////////////////////////////////////////////////////
41 class PropsVisitor : public XMLVisitor
45 PropsVisitor (SGPropertyNode * root, const string &base)
46 : _root(root), _level(0), _base(base), _hasException(false) {}
48 virtual ~PropsVisitor () {}
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);
57 bool hasException () const { return _hasException; }
58 sg_io_exception &getException () { return _exception; }
59 void setException (const sg_io_exception &exception) {
60 _exception = exception;
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;
74 map<string,int> counters;
77 State &state () { return _state_stack[_state_stack.size() - 1]; }
79 void push_state (SGPropertyNode * node, const char * type, int mode) {
81 _state_stack.push_back(State(node, "unspecified", mode));
83 _state_stack.push_back(State(node, type, mode));
89 _state_stack.pop_back();
94 SGPropertyNode * _root;
96 vector<State> _state_stack;
98 sg_io_exception _exception;
103 PropsVisitor::startXML ()
106 _state_stack.resize(0);
110 PropsVisitor::endXML ()
113 _state_stack.resize(0);
118 * Check a yes/no flag, with default.
121 checkFlag (const char * flag, bool defaultState = true)
125 else if (string(flag) == "y")
127 else if (string(flag) == "n")
130 string message = "Unrecognized flag value '";
133 // FIXME: add location info
134 throw sg_io_exception(message, "SimGear Property Reader");
139 PropsVisitor::startElement (const char * name, const XMLAttributes &atts)
144 if (string(name) != (string)"PropertyList") {
145 string message = "Root element name is ";
147 message += "; expected PropertyList";
148 throw sg_io_exception(message, "SimGear Property Reader");
150 push_state(_root, "", DEFAULT_MODE);
157 attval = atts.getValue("n");
160 index = atoi(attval);
161 st.counters[name] = SG_MAX2(st.counters[name], index+1);
163 index = st.counters[name];
167 // Got the index, so grab the node.
168 SGPropertyNode * node = st.node->getChild(name, index, true);
170 // Get the access-mode attributes,
171 // but don't set yet (in case they
172 // prevent us from recording the value).
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;
185 // Check for an alias.
186 attval = atts.getValue("alias");
188 if (!node->alias(attval))
189 SG_LOG(SG_INPUT, SG_ALERT, "Failed to set alias to " << attval);
192 // Check for an include.
193 attval = atts.getValue("include");
195 SGPath path(SGPath(_base).dir());
198 readProperties(path.str(), node);
199 } catch (sg_io_exception &e) {
204 push_state(node, atts.getValue("type"), mode);
209 PropsVisitor::endElement (const char * name)
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);
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);
235 string message = "Unrecognized data type '";
238 // FIXME: add location information
239 throw sg_io_exception(message, "SimGear Property Reader");
242 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: Failed to set "
243 << st.node->getPath() << " to value \""
244 << _data << "\" with type " << st.type);
247 // Set the access-mode attributes now,
248 // once the value has already been
250 st.node->setAttributes(st.mode);
256 PropsVisitor::data (const char * s, int length)
258 if (state().node->nChildren() == 0)
259 _data.append(string(s, length));
263 PropsVisitor::warning (const char * message, int line, int column)
265 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: warning: "
266 << message << " at line " << line << ", column " << column);
271 ////////////////////////////////////////////////////////////////////////
272 // Property list reader.
273 ////////////////////////////////////////////////////////////////////////
277 * Read properties from an input stream.
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.
285 readProperties (istream &input, SGPropertyNode * start_node,
288 PropsVisitor visitor(start_node, base);
289 readXML(input, visitor, base);
290 if (visitor.hasException())
291 throw visitor.getException();
296 * Read properties from a file.
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.
303 readProperties (const string &file, SGPropertyNode * start_node)
305 PropsVisitor visitor(start_node, file);
306 readXML(file, visitor);
307 if (visitor.hasException())
308 throw visitor.getException();
313 ////////////////////////////////////////////////////////////////////////
314 // Property list writer.
315 ////////////////////////////////////////////////////////////////////////
317 #define INDENT_STEP 2
320 * Return the type name.
323 getTypeName (SGPropertyNode::Type type)
326 case SGPropertyNode::UNSPECIFIED:
327 return "unspecified";
328 case SGPropertyNode::BOOL:
330 case SGPropertyNode::INT:
332 case SGPropertyNode::LONG:
334 case SGPropertyNode::FLOAT:
336 case SGPropertyNode::DOUBLE:
338 case SGPropertyNode::STRING:
342 // keep the compiler from squawking
343 return "unspecified";
348 * Escape characters for output.
351 writeData (ostream &output, const string &data)
353 for (int i = 0; i < (int)data.size(); i++) {
372 doIndent (ostream &output, int indent)
374 while (indent-- > 0) {
381 writeAtts (ostream &output, const SGPropertyNode * node)
383 int index = node->getIndex();
386 output << " n=\"" << index << '"';
389 if (!node->getAttribute(SGPropertyNode::READ))
390 output << " read=\"n\"";
392 if (!node->getAttribute(SGPropertyNode::WRITE))
393 output << " write=\"n\"";
395 if (node->getAttribute(SGPropertyNode::ARCHIVE))
396 output << " archive=\"y\"";
403 * Test whether a node is archivable or has archivable descendants.
406 isArchivable (const SGPropertyNode * node)
408 // FIXME: it's inefficient to do this all the time
409 if (node->getAttribute(SGPropertyNode::ARCHIVE))
412 int nChildren = node->nChildren();
413 for (int i = 0; i < nChildren; i++)
414 if (isArchivable(node->getChild(i)))
422 writeNode (ostream &output, const SGPropertyNode * node, int indent)
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.
430 const string &name = node->getName();
431 int index = node->getIndex();
432 int nChildren = node->nChildren();
434 // If there is a literal value,
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()
444 if (node->getType() != SGPropertyNode::UNSPECIFIED)
445 output << " type=\"" << getTypeName(node->getType()) << '"';
447 writeData(output, node->getStringValue());
448 output << "</" << name << '>' << endl;
452 // If there are children, write them
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;
470 writeProperties (ostream &output, const SGPropertyNode * start_node)
472 int nChildren = start_node->nChildren();
474 output << "<?xml version=\"1.0\"?>" << endl << endl;
475 output << "<PropertyList>" << endl;
477 for (int i = 0; i < nChildren; i++) {
478 writeNode(output, start_node->getChild(i), INDENT_STEP);
481 output << "</PropertyList>" << endl;
486 writeProperties (const string &file, const SGPropertyNode * start_node)
488 ofstream output(file.c_str());
490 writeProperties(output, start_node);
492 throw sg_io_exception("Cannot open file", sg_location(file));
498 ////////////////////////////////////////////////////////////////////////
499 // Copy properties from one tree to another.
500 ////////////////////////////////////////////////////////////////////////
504 * Copy one property tree to another.
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).
512 copyProperties (const SGPropertyNode *in, SGPropertyNode *out)
516 // First, copy the actual value,
518 if (in->hasValue()) {
519 switch (in->getType()) {
520 case SGPropertyNode::BOOL:
521 if (!out->setBoolValue(in->getBoolValue()))
524 case SGPropertyNode::INT:
525 if (!out->setIntValue(in->getIntValue()))
528 case SGPropertyNode::LONG:
529 if (!out->setLongValue(in->getLongValue()))
532 case SGPropertyNode::FLOAT:
533 if (!out->setFloatValue(in->getFloatValue()))
536 case SGPropertyNode::DOUBLE:
537 if (!out->setDoubleValue(in->getDoubleValue()))
540 case SGPropertyNode::STRING:
541 if (!out->setStringValue(in->getStringValue()))
544 case SGPropertyNode::UNSPECIFIED:
545 if (!out->setUnspecifiedValue(in->getStringValue()))
549 string message = "Unknown internal SGPropertyNode type";
550 message += in->getType();
551 throw sg_error(message, "SimGear Property Reader");
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(),
562 if (!copyProperties(in_child, out_child))
569 // end of props_io.cxx