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/misc/sg_path.hxx>
9 #include <simgear/xml/easyxml.hxx>
12 #include "props_io.hxx"
20 SG_USING_STD(istream);
21 SG_USING_STD(ifstream);
22 SG_USING_STD(ostream);
23 SG_USING_STD(ofstream);
28 #define DEFAULT_MODE (SGPropertyNode::READ|SGPropertyNode::WRITE)
32 ////////////////////////////////////////////////////////////////////////
33 // Property list visitor, for XML parsing.
34 ////////////////////////////////////////////////////////////////////////
36 class PropsVisitor : public XMLVisitor
40 PropsVisitor (SGPropertyNode * root, const string &base)
41 : _root(root), _level(0), _base(base), _hasException(false) {}
43 virtual ~PropsVisitor () {}
47 void startElement (const char * name, const XMLAttributes &atts);
48 void endElement (const char * name);
49 void data (const char * s, int length);
50 void warning (const char * message, int line, int column);
52 bool hasException () const { return _hasException; }
53 sg_io_exception &getException () { return _exception; }
54 void setException (const sg_io_exception &exception) {
55 _exception = exception;
63 State () : node(0), type(""), mode(DEFAULT_MODE) {}
64 State (SGPropertyNode * _node, const char * _type, int _mode)
65 : node(_node), type(_type), mode(_mode) {}
66 SGPropertyNode * node;
69 map<string,int> counters;
72 State &state () { return _state_stack[_state_stack.size() - 1]; }
74 void push_state (SGPropertyNode * node, const char * type, int mode) {
76 _state_stack.push_back(State(node, "unspecified", mode));
78 _state_stack.push_back(State(node, type, mode));
84 _state_stack.pop_back();
89 SGPropertyNode * _root;
91 vector<State> _state_stack;
93 sg_io_exception _exception;
98 PropsVisitor::startXML ()
101 _state_stack.resize(0);
105 PropsVisitor::endXML ()
108 _state_stack.resize(0);
113 * Check a yes/no flag, with default.
116 checkFlag (const char * flag, bool defaultState = true)
120 else if (!strcmp(flag, "y"))
122 else if (!strcmp(flag, "n"))
125 string message = "Unrecognized flag value '";
128 // FIXME: add location info
129 throw sg_io_exception(message, "SimGear Property Reader");
134 PropsVisitor::startElement (const char * name, const XMLAttributes &atts)
140 if (strcmp(name, "PropertyList")) {
141 string message = "Root element name is ";
143 message += "; expected PropertyList";
144 throw sg_io_exception(message, "SimGear Property Reader");
147 // Check for an include.
148 attval = atts.getValue("include");
150 SGPath path(SGPath(_base).dir());
153 readProperties(path.str(), _root);
154 } catch (sg_io_exception &e) {
159 push_state(_root, "", DEFAULT_MODE);
164 attval = atts.getValue("n");
167 index = atoi(attval);
168 st.counters[name] = SG_MAX2(st.counters[name], index+1);
170 index = st.counters[name];
174 // Got the index, so grab the node.
175 SGPropertyNode * node = st.node->getChild(name, index, true);
177 // Get the access-mode attributes,
178 // but don't set yet (in case they
179 // prevent us from recording the value).
182 attval = atts.getValue("read");
183 if (checkFlag(attval, true))
184 mode |= SGPropertyNode::READ;
185 attval = atts.getValue("write");
186 if (checkFlag(attval, true))
187 mode |= SGPropertyNode::WRITE;
188 attval = atts.getValue("archive");
189 if (checkFlag(attval, false))
190 mode |= SGPropertyNode::ARCHIVE;
191 attval = atts.getValue("trace-read");
192 if (checkFlag(attval, false))
193 mode |= SGPropertyNode::TRACE_READ;
194 attval = atts.getValue("trace-write");
195 if (checkFlag(attval, false))
196 mode |= SGPropertyNode::TRACE_WRITE;
198 // Check for an alias.
199 attval = atts.getValue("alias");
201 if (!node->alias(attval))
202 SG_LOG(SG_INPUT, SG_ALERT, "Failed to set alias to " << attval);
205 // Check for an include.
206 attval = atts.getValue("include");
208 SGPath path(SGPath(_base).dir());
211 readProperties(path.str(), node);
212 } catch (sg_io_exception &e) {
217 push_state(node, atts.getValue("type"), mode);
222 PropsVisitor::endElement (const char * name)
227 // If there are no children and it's
228 // not an alias, then it's a leaf value.
229 if (st.node->nChildren() == 0 && !st.node->isAlias()) {
230 if (st.type == "bool") {
231 if (_data == "true" || atoi(_data.c_str()) != 0)
232 ret = st.node->setBoolValue(true);
234 ret = st.node->setBoolValue(false);
235 } else if (st.type == "int") {
236 ret = st.node->setIntValue(atoi(_data.c_str()));
237 } else if (st.type == "long") {
238 ret = st.node->setLongValue(strtol(_data.c_str(), 0, 0));
239 } else if (st.type == "float") {
240 ret = st.node->setFloatValue(atof(_data.c_str()));
241 } else if (st.type == "double") {
242 ret = st.node->setDoubleValue(strtod(_data.c_str(), 0));
243 } else if (st.type == "string") {
244 ret = st.node->setStringValue(_data.c_str());
245 } else if (st.type == "unspecified") {
246 ret = st.node->setUnspecifiedValue(_data.c_str());
248 string message = "Unrecognized data type '";
251 // FIXME: add location information
252 throw sg_io_exception(message, "SimGear Property Reader");
255 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: Failed to set "
256 << st.node->getPath() << " to value \""
257 << _data << "\" with type " << st.type);
260 // Set the access-mode attributes now,
261 // once the value has already been
263 st.node->setAttributes(st.mode);
269 PropsVisitor::data (const char * s, int length)
271 if (state().node->nChildren() == 0)
272 _data.append(string(s, length));
276 PropsVisitor::warning (const char * message, int line, int column)
278 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: warning: "
279 << message << " at line " << line << ", column " << column);
284 ////////////////////////////////////////////////////////////////////////
285 // Property list reader.
286 ////////////////////////////////////////////////////////////////////////
290 * Read properties from an input stream.
292 * @param input The input stream containing an XML property file.
293 * @param start_node The root node for reading properties.
294 * @param base A base path for resolving external include references.
295 * @return true if the read succeeded, false otherwise.
298 readProperties (istream &input, SGPropertyNode * start_node,
301 PropsVisitor visitor(start_node, base);
302 readXML(input, visitor, base);
303 if (visitor.hasException())
304 throw visitor.getException();
309 * Read properties from a file.
311 * @param file A string containing the file path.
312 * @param start_node The root node for reading properties.
313 * @return true if the read succeeded, false otherwise.
316 readProperties (const string &file, SGPropertyNode * start_node)
318 PropsVisitor visitor(start_node, file);
319 readXML(file, visitor);
320 if (visitor.hasException())
321 throw visitor.getException();
326 ////////////////////////////////////////////////////////////////////////
327 // Property list writer.
328 ////////////////////////////////////////////////////////////////////////
330 #define INDENT_STEP 2
333 * Return the type name.
336 getTypeName (SGPropertyNode::Type type)
339 case SGPropertyNode::UNSPECIFIED:
340 return "unspecified";
341 case SGPropertyNode::BOOL:
343 case SGPropertyNode::INT:
345 case SGPropertyNode::LONG:
347 case SGPropertyNode::FLOAT:
349 case SGPropertyNode::DOUBLE:
351 case SGPropertyNode::STRING:
353 case SGPropertyNode::ALIAS:
354 case SGPropertyNode::NONE:
355 return "unspecified";
358 // keep the compiler from squawking
359 return "unspecified";
364 * Escape characters for output.
367 writeData (ostream &output, const string &data)
369 for (int i = 0; i < (int)data.size(); i++) {
388 doIndent (ostream &output, int indent)
390 while (indent-- > 0) {
397 writeAtts (ostream &output, const SGPropertyNode * node)
399 int index = node->getIndex();
402 output << " n=\"" << index << '"';
405 if (!node->getAttribute(SGPropertyNode::READ))
406 output << " read=\"n\"";
408 if (!node->getAttribute(SGPropertyNode::WRITE))
409 output << " write=\"n\"";
411 if (node->getAttribute(SGPropertyNode::ARCHIVE))
412 output << " archive=\"y\"";
419 * Test whether a node is archivable or has archivable descendants.
422 isArchivable (const SGPropertyNode * node)
424 // FIXME: it's inefficient to do this all the time
425 if (node->getAttribute(SGPropertyNode::ARCHIVE))
428 int nChildren = node->nChildren();
429 for (int i = 0; i < nChildren; i++)
430 if (isArchivable(node->getChild(i)))
438 writeNode (ostream &output, const SGPropertyNode * node,
439 bool write_all, int indent)
441 // Don't write the node or any of
442 // its descendants unless it is
443 // allowed to be archived.
444 if (!write_all && !isArchivable(node))
445 return true; // Everything's OK, but we won't write.
447 const string name = node->getName();
448 int nChildren = node->nChildren();
450 // If there is a literal value,
452 if (node->hasValue() && (write_all || node->getAttribute(SGPropertyNode::ARCHIVE))) {
453 doIndent(output, indent);
454 output << '<' << name;
455 writeAtts(output, node);
456 if (node->isAlias() && node->getAliasTarget() != 0) {
457 output << " alias=\"" << node->getAliasTarget()->getPath()
460 if (node->getType() != SGPropertyNode::UNSPECIFIED)
461 output << " type=\"" << getTypeName(node->getType()) << '"';
463 writeData(output, node->getStringValue());
464 output << "</" << name << '>' << endl;
468 // If there are children, write them next.
469 if (nChildren > 0 || node->isAlias()) {
470 doIndent(output, indent);
471 output << '<' << name;
472 writeAtts(output, node);
473 output << '>' << endl;
474 for (int i = 0; i < nChildren; i++)
475 writeNode(output, node->getChild(i), write_all, indent + INDENT_STEP);
476 doIndent(output, indent);
477 output << "</" << name << '>' << endl;
485 writeProperties (ostream &output, const SGPropertyNode * start_node,
488 int nChildren = start_node->nChildren();
490 output << "<?xml version=\"1.0\"?>" << endl << endl;
491 output << "<PropertyList>" << endl;
493 for (int i = 0; i < nChildren; i++) {
494 writeNode(output, start_node->getChild(i), write_all, INDENT_STEP);
497 output << "</PropertyList>" << endl;
502 writeProperties (const string &file, const SGPropertyNode * start_node,
505 ofstream output(file.c_str());
507 writeProperties(output, start_node, write_all);
509 throw sg_io_exception("Cannot open file", sg_location(file));
515 ////////////////////////////////////////////////////////////////////////
516 // Copy properties from one tree to another.
517 ////////////////////////////////////////////////////////////////////////
521 * Copy one property tree to another.
523 * @param in The source property tree.
524 * @param out The destination property tree.
525 * @return true if all properties were copied, false if some failed
526 * (for example, if the property's value is tied read-only).
529 copyProperties (const SGPropertyNode *in, SGPropertyNode *out)
533 // First, copy the actual value,
535 if (in->hasValue()) {
536 switch (in->getType()) {
537 case SGPropertyNode::BOOL:
538 if (!out->setBoolValue(in->getBoolValue()))
541 case SGPropertyNode::INT:
542 if (!out->setIntValue(in->getIntValue()))
545 case SGPropertyNode::LONG:
546 if (!out->setLongValue(in->getLongValue()))
549 case SGPropertyNode::FLOAT:
550 if (!out->setFloatValue(in->getFloatValue()))
553 case SGPropertyNode::DOUBLE:
554 if (!out->setDoubleValue(in->getDoubleValue()))
557 case SGPropertyNode::STRING:
558 if (!out->setStringValue(in->getStringValue()))
561 case SGPropertyNode::UNSPECIFIED:
562 if (!out->setUnspecifiedValue(in->getStringValue()))
566 string message = "Unknown internal SGPropertyNode type";
567 message += in->getType();
568 throw sg_error(message, "SimGear Property Reader");
572 // Next, copy the children.
573 int nChildren = in->nChildren();
574 for (int i = 0; i < nChildren; i++) {
575 const SGPropertyNode * in_child = in->getChild(i);
576 SGPropertyNode * out_child = out->getChild(in_child->getName(),
577 in_child->getIndex(),
579 if (!copyProperties(in_child, out_child))
586 // end of props_io.cxx