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, int default_mode = 0)
41 : _root(root), _level(0), _base(base), _hasException(false), _default_mode(default_mode) {}
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();
90 SGPropertyNode * _root;
92 vector<State> _state_stack;
94 sg_io_exception _exception;
99 PropsVisitor::startXML ()
102 _state_stack.resize(0);
106 PropsVisitor::endXML ()
109 _state_stack.resize(0);
114 * Check a yes/no flag, with default.
117 checkFlag (const char * flag, bool defaultState = true)
121 else if (!strcmp(flag, "y"))
123 else if (!strcmp(flag, "n"))
126 string message = "Unrecognized flag value '";
129 // FIXME: add location info
130 throw sg_io_exception(message, "SimGear Property Reader");
135 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);
165 attval = atts.getValue("n");
168 index = atoi(attval);
169 st.counters[name] = SG_MAX2(st.counters[name], index+1);
171 index = st.counters[name];
175 // Got the index, so grab the node.
176 SGPropertyNode * node = st.node->getChild(name, index, true);
178 // Get the access-mode attributes,
179 // but don't set yet (in case they
180 // prevent us from recording the value).
181 int mode = _default_mode;
183 attval = atts.getValue("read");
184 if (checkFlag(attval, true))
185 mode |= SGPropertyNode::READ;
186 attval = atts.getValue("write");
187 if (checkFlag(attval, true))
188 mode |= SGPropertyNode::WRITE;
189 attval = atts.getValue("archive");
190 if (checkFlag(attval, false))
191 mode |= SGPropertyNode::ARCHIVE;
192 attval = atts.getValue("trace-read");
193 if (checkFlag(attval, false))
194 mode |= SGPropertyNode::TRACE_READ;
195 attval = atts.getValue("trace-write");
196 if (checkFlag(attval, false))
197 mode |= SGPropertyNode::TRACE_WRITE;
198 attval = atts.getValue("userarchive");
199 if (checkFlag(attval, false))
200 mode |= SGPropertyNode::USERARCHIVE;
202 // Check for an alias.
203 attval = atts.getValue("alias");
205 if (!node->alias(attval))
206 SG_LOG(SG_INPUT, SG_ALERT, "Failed to set alias to " << attval);
209 // Check for an include.
210 attval = atts.getValue("include");
212 SGPath path(SGPath(_base).dir());
215 readProperties(path.str(), node);
216 } catch (sg_io_exception &e) {
221 const char *type = atts.getValue("type");
224 push_state(node, type, mode);
229 PropsVisitor::endElement (const char * name)
234 // If there are no children and it's
235 // not an alias, then it's a leaf value.
236 if (st.node->nChildren() == 0 && !st.node->isAlias()) {
237 if (st.type == "bool") {
238 if (_data == "true" || atoi(_data.c_str()) != 0)
239 ret = st.node->setBoolValue(true);
241 ret = st.node->setBoolValue(false);
242 } else if (st.type == "int") {
243 ret = st.node->setIntValue(atoi(_data.c_str()));
244 } else if (st.type == "long") {
245 ret = st.node->setLongValue(strtol(_data.c_str(), 0, 0));
246 } else if (st.type == "float") {
247 ret = st.node->setFloatValue(atof(_data.c_str()));
248 } else if (st.type == "double") {
249 ret = st.node->setDoubleValue(strtod(_data.c_str(), 0));
250 } else if (st.type == "string") {
251 ret = st.node->setStringValue(_data.c_str());
252 } else if (st.type == "unspecified") {
253 ret = st.node->setUnspecifiedValue(_data.c_str());
255 string message = "Unrecognized data type '";
258 // FIXME: add location information
259 throw sg_io_exception(message, "SimGear Property Reader");
262 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: Failed to set "
263 << st.node->getPath() << " to value \""
264 << _data << "\" with type " << st.type);
267 // Set the access-mode attributes now,
268 // once the value has already been
270 st.node->setAttributes(st.mode);
276 PropsVisitor::data (const char * s, int length)
278 if (state().node->nChildren() == 0)
279 _data.append(string(s, length));
283 PropsVisitor::warning (const char * message, int line, int column)
285 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: warning: "
286 << message << " at line " << line << ", column " << column);
291 ////////////////////////////////////////////////////////////////////////
292 // Property list reader.
293 ////////////////////////////////////////////////////////////////////////
297 * Read properties from an input stream.
299 * @param input The input stream containing an XML property file.
300 * @param start_node The root node for reading properties.
301 * @param base A base path for resolving external include references.
302 * @return true if the read succeeded, false otherwise.
305 readProperties (istream &input, SGPropertyNode * start_node,
306 const string &base, int default_mode)
308 PropsVisitor visitor(start_node, base, default_mode);
309 readXML(input, visitor, base);
310 if (visitor.hasException())
311 throw visitor.getException();
316 * Read properties from a file.
318 * @param file A string containing the file path.
319 * @param start_node The root node for reading properties.
320 * @return true if the read succeeded, false otherwise.
323 readProperties (const string &file, SGPropertyNode * start_node,
326 PropsVisitor visitor(start_node, file, default_mode);
327 readXML(file, visitor);
328 if (visitor.hasException())
329 throw visitor.getException();
334 * Read properties from an in-memory buffer.
336 * @param buf A character buffer containing the xml data.
337 * @param size The size/length of the buffer in bytes
338 * @param start_node The root node for reading properties.
339 * @return true if the read succeeded, false otherwise.
341 void readProperties (const char *buf, const int size,
342 SGPropertyNode * start_node, int default_mode)
344 PropsVisitor visitor(start_node, "", default_mode);
345 readXML(buf, size, visitor);
346 if (visitor.hasException())
347 throw visitor.getException();
351 ////////////////////////////////////////////////////////////////////////
352 // Property list writer.
353 ////////////////////////////////////////////////////////////////////////
355 #define INDENT_STEP 2
358 * Return the type name.
361 getTypeName (SGPropertyNode::Type type)
364 case SGPropertyNode::UNSPECIFIED:
365 return "unspecified";
366 case SGPropertyNode::BOOL:
368 case SGPropertyNode::INT:
370 case SGPropertyNode::LONG:
372 case SGPropertyNode::FLOAT:
374 case SGPropertyNode::DOUBLE:
376 case SGPropertyNode::STRING:
378 case SGPropertyNode::ALIAS:
379 case SGPropertyNode::NONE:
380 return "unspecified";
383 // keep the compiler from squawking
384 return "unspecified";
389 * Escape characters for output.
392 writeData (ostream &output, const string &data)
394 for (int i = 0; i < (int)data.size(); i++) {
413 doIndent (ostream &output, int indent)
415 while (indent-- > 0) {
422 writeAtts (ostream &output, const SGPropertyNode * node)
424 int index = node->getIndex();
427 output << " n=\"" << index << '"';
430 if (!node->getAttribute(SGPropertyNode::READ))
431 output << " read=\"n\"";
433 if (!node->getAttribute(SGPropertyNode::WRITE))
434 output << " write=\"n\"";
436 if (node->getAttribute(SGPropertyNode::ARCHIVE))
437 output << " archive=\"y\"";
444 * Test whether a node is archivable or has archivable descendants.
447 isArchivable (const SGPropertyNode * node, SGPropertyNode::Attribute archive_flag)
449 // FIXME: it's inefficient to do this all the time
450 if (node->getAttribute(archive_flag))
453 int nChildren = node->nChildren();
454 for (int i = 0; i < nChildren; i++)
455 if (isArchivable(node->getChild(i), archive_flag))
463 writeNode (ostream &output, const SGPropertyNode * node,
464 bool write_all, int indent, SGPropertyNode::Attribute archive_flag)
466 // Don't write the node or any of
467 // its descendants unless it is
468 // allowed to be archived.
469 if (!write_all && !isArchivable(node, archive_flag))
470 return true; // Everything's OK, but we won't write.
472 const string name = node->getName();
473 int nChildren = node->nChildren();
475 // If there is a literal value,
477 if (node->hasValue() && (write_all || node->getAttribute(archive_flag))) {
478 doIndent(output, indent);
479 output << '<' << name;
480 writeAtts(output, node);
481 if (node->isAlias() && node->getAliasTarget() != 0) {
482 output << " alias=\"" << node->getAliasTarget()->getPath()
485 if (node->getType() != SGPropertyNode::UNSPECIFIED)
486 output << " type=\"" << getTypeName(node->getType()) << '"';
488 writeData(output, node->getStringValue());
489 output << "</" << name << '>' << endl;
493 // If there are children, write them next.
495 doIndent(output, indent);
496 output << '<' << name;
497 writeAtts(output, node);
498 output << '>' << endl;
499 for (int i = 0; i < nChildren; i++)
500 writeNode(output, node->getChild(i), write_all, indent + INDENT_STEP, archive_flag);
501 doIndent(output, indent);
502 output << "</" << name << '>' << endl;
510 writeProperties (ostream &output, const SGPropertyNode * start_node,
511 bool write_all, SGPropertyNode::Attribute archive_flag)
513 int nChildren = start_node->nChildren();
515 output << "<?xml version=\"1.0\"?>" << endl << endl;
516 output << "<PropertyList>" << endl;
518 for (int i = 0; i < nChildren; i++) {
519 writeNode(output, start_node->getChild(i), write_all, INDENT_STEP, archive_flag);
522 output << "</PropertyList>" << endl;
527 writeProperties (const string &file, const SGPropertyNode * start_node,
528 bool write_all, SGPropertyNode::Attribute archive_flag)
530 ofstream output(file.c_str());
532 writeProperties(output, start_node, write_all, archive_flag);
534 throw sg_io_exception("Cannot open file", sg_location(file));
540 ////////////////////////////////////////////////////////////////////////
541 // Copy properties from one tree to another.
542 ////////////////////////////////////////////////////////////////////////
546 * Copy one property tree to another.
548 * @param in The source property tree.
549 * @param out The destination property tree.
550 * @return true if all properties were copied, false if some failed
551 * (for example, if the property's value is tied read-only).
554 copyProperties (const SGPropertyNode *in, SGPropertyNode *out)
558 // First, copy the actual value,
560 if (in->hasValue()) {
561 switch (in->getType()) {
562 case SGPropertyNode::BOOL:
563 if (!out->setBoolValue(in->getBoolValue()))
566 case SGPropertyNode::INT:
567 if (!out->setIntValue(in->getIntValue()))
570 case SGPropertyNode::LONG:
571 if (!out->setLongValue(in->getLongValue()))
574 case SGPropertyNode::FLOAT:
575 if (!out->setFloatValue(in->getFloatValue()))
578 case SGPropertyNode::DOUBLE:
579 if (!out->setDoubleValue(in->getDoubleValue()))
582 case SGPropertyNode::STRING:
583 if (!out->setStringValue(in->getStringValue()))
586 case SGPropertyNode::UNSPECIFIED:
587 if (!out->setUnspecifiedValue(in->getStringValue()))
593 string message = "Unknown internal SGPropertyNode type";
594 message += in->getType();
595 throw sg_error(message, "SimGear Property Reader");
599 // copy the attributes.
600 out->setAttributes( in->getAttributes() );
602 // Next, copy the children.
603 int nChildren = in->nChildren();
604 for (int i = 0; i < nChildren; i++) {
605 const SGPropertyNode * in_child = in->getChild(i);
606 SGPropertyNode * out_child = out->getChild(in_child->getName(),
607 in_child->getIndex(),
609 if (!copyProperties(in_child, out_child))
616 // end of props_io.cxx