3 * Started Fall 2000 by David Megginson, david@megginson.com
4 * This code is released into the Public Domain.
6 * See props.html for documentation [replace with URL when available].
12 # include <simgear_config.h>
15 #include <simgear/compiler.h>
17 #include <stdlib.h> // atof() atoi()
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>
27 #include "props_io.hxx"
32 #include <cstring> // strcmp()
46 #define DEFAULT_MODE (SGPropertyNode::READ|SGPropertyNode::WRITE)
50 ////////////////////////////////////////////////////////////////////////
51 // Property list visitor, for XML parsing.
52 ////////////////////////////////////////////////////////////////////////
54 class PropsVisitor : public XMLVisitor
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)
64 virtual ~PropsVisitor () {}
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);
73 bool hasException () const { return _hasException; }
74 sg_io_exception &getException () { return _exception; }
75 void setException (const sg_io_exception &exception) {
76 _exception = exception;
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;
91 map<string,int> counters;
94 State &state () { return _state_stack[_state_stack.size() - 1]; }
96 void push_state (SGPropertyNode * node, const char * type, int mode, bool omit = false) {
98 _state_stack.push_back(State(node, "unspecified", mode, omit));
100 _state_stack.push_back(State(node, type, mode, omit));
106 _state_stack.pop_back();
112 SGPropertyNode * _root;
115 vector<State> _state_stack;
117 sg_io_exception _exception;
123 PropsVisitor::startXML ()
126 _state_stack.resize(0);
130 PropsVisitor::endXML ()
133 _state_stack.resize(0);
138 * Check a yes/no flag, with default.
141 checkFlag (const char * flag, bool defaultState = true)
145 else if (!strcmp(flag, "y"))
147 else if (!strcmp(flag, "n"))
150 string message = "Unrecognized flag value '";
153 // FIXME: add location info
154 throw sg_io_exception(message, "SimGear Property Reader");
159 PropsVisitor::startElement (const char * name, const XMLAttributes &atts)
164 if (strcmp(name, "PropertyList")) {
165 string message = "Root element name is ";
167 message += "; expected PropertyList";
168 throw sg_io_exception(message, "SimGear Property Reader");
171 // Check for an include.
172 attval = atts.getValue("include");
175 SGPath path = simgear::ResourceManager::instance()->findPath(attval, SGPath(_base).dir());
178 throw sg_io_exception("Cannot open file", sg_location(attval));
180 readProperties(path.str(), _root, 0, _extended);
181 } catch (sg_io_exception &e) {
186 push_state(_root, "", DEFAULT_MODE);
192 attval = atts.getValue("n");
194 string strName(name);
196 index = atoi(attval);
197 st.counters[strName] = SG_MAX2(st.counters[strName], index+1);
199 index = st.counters[strName];
200 st.counters[strName]++;
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));
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;
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;
238 // Check for an alias.
239 attval = atts.getValue("alias");
241 if (!node->alias(attval))
242 SG_LOG(SG_INPUT, SG_ALERT, "Failed to set alias to " << attval);
245 // Check for an include.
247 attval = atts.getValue("include");
250 SGPath path = simgear::ResourceManager::instance()->findPath(attval, SGPath(_base).dir());
253 throw sg_io_exception("Cannot open file", sg_location(attval));
255 readProperties(path.str(), node, 0, _extended);
256 } catch (sg_io_exception &e) {
260 attval = atts.getValue("omit-node");
261 omit = checkFlag(attval, false);
264 const char *type = atts.getValue("type");
267 push_state(node, type, mode, omit);
272 PropsVisitor::endElement (const char * name)
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);
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) {
297 ->setValue(simgear::parseString<SGVec3d>(_data));
298 } else if (st.type == "vec4d" && _extended) {
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>
306 string message = "Unrecognized data type '";
309 // FIXME: add location information
310 throw sg_io_exception(message, "SimGear Property Reader");
313 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: Failed to set "
314 << st.node->getPath() << " to value \""
315 << _data << "\" with type " << st.type);
318 // Set the access-mode attributes now,
319 // once the value has already been
321 st.node->setAttributes(st.mode);
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);
334 parent.node->removeChild(st.node->getName(), st.node->getIndex(), false);
340 PropsVisitor::data (const char * s, int length)
342 if (state().node->nChildren() == 0)
343 _data.append(string(s, length));
347 PropsVisitor::warning (const char * message, int line, int column)
349 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: warning: "
350 << message << " at line " << line << ", column " << column);
355 ////////////////////////////////////////////////////////////////////////
356 // Property list reader.
357 ////////////////////////////////////////////////////////////////////////
361 * Read properties from an input stream.
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.
369 readProperties (istream &input, SGPropertyNode * start_node,
370 const string &base, int default_mode, bool extended)
372 PropsVisitor visitor(start_node, base, default_mode, extended);
373 readXML(input, visitor, base);
374 if (visitor.hasException())
375 throw visitor.getException();
380 * Read properties from a file.
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.
387 readProperties (const string &file, SGPropertyNode * start_node,
388 int default_mode, bool extended)
390 PropsVisitor visitor(start_node, file, default_mode, extended);
391 readXML(file, visitor);
392 if (visitor.hasException())
393 throw visitor.getException();
398 * Read properties from an in-memory buffer.
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.
405 void readProperties (const char *buf, const int size,
406 SGPropertyNode * start_node, int default_mode,
409 PropsVisitor visitor(start_node, "", default_mode, extended);
410 readXML(buf, size, visitor);
411 if (visitor.hasException())
412 throw visitor.getException();
416 ////////////////////////////////////////////////////////////////////////
417 // Property list writer.
418 ////////////////////////////////////////////////////////////////////////
420 #define INDENT_STEP 2
423 * Return the type name.
426 getTypeName (simgear::props::Type type)
428 using namespace simgear;
430 case props::UNSPECIFIED:
431 return "unspecified";
450 return "unspecified";
451 default: // avoid compiler warning
455 // keep the compiler from squawking
456 return "unspecified";
461 * Escape characters for output.
464 writeData (ostream &output, const string &data)
466 for (int i = 0; i < (int)data.size(); i++) {
485 doIndent (ostream &output, int indent)
487 while (indent-- > 0) {
494 writeAtts (ostream &output, const SGPropertyNode * node, bool forceindex)
496 int index = node->getIndex();
498 if (index != 0 || forceindex)
499 output << " n=\"" << index << '"';
502 if (!node->getAttribute(SGPropertyNode::READ))
503 output << " read=\"n\"";
505 if (!node->getAttribute(SGPropertyNode::WRITE))
506 output << " write=\"n\"";
508 if (node->getAttribute(SGPropertyNode::ARCHIVE))
509 output << " archive=\"y\"";
516 * Test whether a node is archivable or has archivable descendants.
519 isArchivable (const SGPropertyNode * node, SGPropertyNode::Attribute archive_flag)
521 // FIXME: it's inefficient to do this all the time
522 if (node->getAttribute(archive_flag))
525 int nChildren = node->nChildren();
526 for (int i = 0; i < nChildren; i++)
527 if (isArchivable(node->getChild(i), archive_flag))
535 writeNode (ostream &output, const SGPropertyNode * node,
536 bool write_all, int indent, SGPropertyNode::Attribute archive_flag)
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.
544 const string name = node->getName();
545 int nChildren = node->nChildren();
546 bool node_has_value = false;
548 // If there is a literal value,
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()
558 if (node->getType() != simgear::props::UNSPECIFIED)
559 output << " type=\"" << getTypeName(node->getType()) << '"';
561 writeData(output, node->getStringValue());
562 output << "</" << name << '>' << endl;
564 node_has_value = true;
567 // If there are children, write them next.
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;
584 writeProperties (ostream &output, const SGPropertyNode * start_node,
585 bool write_all, SGPropertyNode::Attribute archive_flag)
587 int nChildren = start_node->nChildren();
589 output << "<?xml version=\"1.0\"?>" << endl << endl;
590 output << "<PropertyList>" << endl;
592 for (int i = 0; i < nChildren; i++) {
593 writeNode(output, start_node->getChild(i), write_all, INDENT_STEP, archive_flag);
596 output << "</PropertyList>" << endl;
601 writeProperties (const string &file, const SGPropertyNode * start_node,
602 bool write_all, SGPropertyNode::Attribute archive_flag)
604 SGPath path(file.c_str());
605 path.create_dir(0777);
607 ofstream output(file.c_str());
609 writeProperties(output, start_node, write_all, archive_flag);
611 throw sg_io_exception("Cannot open file", sg_location(file));
615 // Another variation, useful when called from gdb
617 writeProperties (const char* file, const SGPropertyNode * start_node)
619 writeProperties(string(file), start_node, true);
624 ////////////////////////////////////////////////////////////////////////
625 // Copy properties from one tree to another.
626 ////////////////////////////////////////////////////////////////////////
630 * Copy one property tree to another.
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).
642 copyProperties (const SGPropertyNode *in, SGPropertyNode *out,
643 int attr_value, int attr_mask)
645 using namespace simgear;
648 // First, copy the actual value,
650 if (in->hasValue()) {
651 switch (in->getType()) {
653 if (!out->setBoolValue(in->getBoolValue()))
657 if (!out->setIntValue(in->getIntValue()))
661 if (!out->setLongValue(in->getLongValue()))
665 if (!out->setFloatValue(in->getFloatValue()))
669 if (!out->setDoubleValue(in->getDoubleValue()))
673 if (!out->setStringValue(in->getStringValue()))
676 case props::UNSPECIFIED:
677 if (!out->setUnspecifiedValue(in->getStringValue()))
681 if (!out->setValue(in->getValue<SGVec3d>()))
685 if (!out->setValue(in->getValue<SGVec4d>()))
691 string message = "Unknown internal SGPropertyNode type";
692 message += in->getType();
693 throw sg_error(message, "SimGear Property Reader");
697 // copy the attributes.
698 out->setAttributes( in->getAttributes() );
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))
711 SGPropertyNode * out_child = out->getChild(in_child->getNameString(),
712 in_child->getIndex(),
716 out_child = out->getChild(in_child->getNameString(),
717 in_child->getIndex(),
723 if (!out_child->hasValue())
724 mask &= SGPropertyNode::PRESERVE;
725 if ((out_child->getAttributes() & mask) != (attr_value & mask))
729 (!copyProperties(in_child, out_child, attr_value, attr_mask)))
737 // end of props_io.cxx