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/misc/sg_path.hxx>
22 #include <simgear/xml/easyxml.hxx>
23 #include <simgear/misc/ResourceManager.hxx>
26 #include "props_io.hxx"
27 #include "vectorPropTemplates.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");
265 // if a type is given and the node is tied,
266 // don't clear the value because
267 // clearValue() unties the property
268 if (type && false == node->isTied() )
270 push_state(node, type, mode, omit);
275 PropsVisitor::endElement (const char * name)
280 // If there are no children and it's
281 // not an alias, then it's a leaf value.
282 if (st.node->nChildren() == 0 && !st.node->isAlias()) {
283 if (st.type == "bool") {
284 if (_data == "true" || atoi(_data.c_str()) != 0)
285 ret = st.node->setBoolValue(true);
287 ret = st.node->setBoolValue(false);
288 } else if (st.type == "int") {
289 ret = st.node->setIntValue(atoi(_data.c_str()));
290 } else if (st.type == "long") {
291 ret = st.node->setLongValue(strtol(_data.c_str(), 0, 0));
292 } else if (st.type == "float") {
293 ret = st.node->setFloatValue(atof(_data.c_str()));
294 } else if (st.type == "double") {
295 ret = st.node->setDoubleValue(strtod(_data.c_str(), 0));
296 } else if (st.type == "string") {
297 ret = st.node->setStringValue(_data.c_str());
298 } else if (st.type == "vec3d" && _extended) {
300 ->setValue(simgear::parseString<SGVec3d>(_data));
301 } else if (st.type == "vec4d" && _extended) {
303 ->setValue(simgear::parseString<SGVec4d>(_data));
304 } else if (st.type == "unspecified") {
305 ret = st.node->setUnspecifiedValue(_data.c_str());
306 } else if (_level == 1) {
307 ret = true; // empty <PropertyList>
309 string message = "Unrecognized data type '";
312 // FIXME: add location information
313 throw sg_io_exception(message, "SimGear Property Reader");
316 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: Failed to set "
317 << st.node->getPath() << " to value \""
318 << _data << "\" with type " << st.type);
321 // Set the access-mode attributes now,
322 // once the value has already been
324 st.node->setAttributes(st.mode);
327 State &parent = _state_stack[_state_stack.size() - 2];
328 int nChildren = st.node->nChildren();
329 for (int i = 0; i < nChildren; i++) {
330 SGPropertyNode *src = st.node->getChild(i);
331 const char *name = src->getName();
332 int index = parent.counters[name];
333 parent.counters[name]++;
334 SGPropertyNode *dst = parent.node->getChild(name, index, true);
335 copyProperties(src, dst);
337 parent.node->removeChild(st.node->getName(), st.node->getIndex(), false);
343 PropsVisitor::data (const char * s, int length)
345 if (state().node->nChildren() == 0)
346 _data.append(string(s, length));
350 PropsVisitor::warning (const char * message, int line, int column)
352 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: warning: "
353 << message << " at line " << line << ", column " << column);
358 ////////////////////////////////////////////////////////////////////////
359 // Property list reader.
360 ////////////////////////////////////////////////////////////////////////
364 * Read properties from an input stream.
366 * @param input The input stream containing an XML property file.
367 * @param start_node The root node for reading properties.
368 * @param base A base path for resolving external include references.
369 * @return true if the read succeeded, false otherwise.
372 readProperties (istream &input, SGPropertyNode * start_node,
373 const string &base, int default_mode, bool extended)
375 PropsVisitor visitor(start_node, base, default_mode, extended);
376 readXML(input, visitor, base);
377 if (visitor.hasException())
378 throw visitor.getException();
383 * Read properties from a file.
385 * @param file A string containing the file path.
386 * @param start_node The root node for reading properties.
387 * @return true if the read succeeded, false otherwise.
390 readProperties (const string &file, SGPropertyNode * start_node,
391 int default_mode, bool extended)
393 PropsVisitor visitor(start_node, file, default_mode, extended);
394 readXML(file, visitor);
395 if (visitor.hasException())
396 throw visitor.getException();
401 * Read properties from an in-memory buffer.
403 * @param buf A character buffer containing the xml data.
404 * @param size The size/length of the buffer in bytes
405 * @param start_node The root node for reading properties.
406 * @return true if the read succeeded, false otherwise.
408 void readProperties (const char *buf, const int size,
409 SGPropertyNode * start_node, int default_mode,
412 PropsVisitor visitor(start_node, "", default_mode, extended);
413 readXML(buf, size, visitor);
414 if (visitor.hasException())
415 throw visitor.getException();
419 ////////////////////////////////////////////////////////////////////////
420 // Property list writer.
421 ////////////////////////////////////////////////////////////////////////
423 #define INDENT_STEP 2
426 * Return the type name.
429 getTypeName (simgear::props::Type type)
431 using namespace simgear;
433 case props::UNSPECIFIED:
434 return "unspecified";
453 return "unspecified";
454 default: // avoid compiler warning
458 // keep the compiler from squawking
459 return "unspecified";
464 * Escape characters for output.
467 writeData (ostream &output, const string &data)
469 for (int i = 0; i < (int)data.size(); i++) {
488 doIndent (ostream &output, int indent)
490 while (indent-- > 0) {
497 writeAtts (ostream &output, const SGPropertyNode * node, bool forceindex)
499 int index = node->getIndex();
501 if (index != 0 || forceindex)
502 output << " n=\"" << index << '"';
505 if (!node->getAttribute(SGPropertyNode::READ))
506 output << " read=\"n\"";
508 if (!node->getAttribute(SGPropertyNode::WRITE))
509 output << " write=\"n\"";
511 if (node->getAttribute(SGPropertyNode::ARCHIVE))
512 output << " archive=\"y\"";
519 * Test whether a node is archivable or has archivable descendants.
522 isArchivable (const SGPropertyNode * node, SGPropertyNode::Attribute archive_flag)
524 // FIXME: it's inefficient to do this all the time
525 if (node->getAttribute(archive_flag))
528 int nChildren = node->nChildren();
529 for (int i = 0; i < nChildren; i++)
530 if (isArchivable(node->getChild(i), archive_flag))
538 writeNode (ostream &output, const SGPropertyNode * node,
539 bool write_all, int indent, SGPropertyNode::Attribute archive_flag)
541 // Don't write the node or any of
542 // its descendants unless it is
543 // allowed to be archived.
544 if (!write_all && !isArchivable(node, archive_flag))
545 return true; // Everything's OK, but we won't write.
547 const string name = node->getName();
548 int nChildren = node->nChildren();
549 bool node_has_value = false;
551 // If there is a literal value,
553 if (node->hasValue() && (write_all || node->getAttribute(archive_flag))) {
554 doIndent(output, indent);
555 output << '<' << name;
556 writeAtts(output, node, nChildren != 0);
557 if (node->isAlias() && node->getAliasTarget() != 0) {
558 output << " alias=\"" << node->getAliasTarget()->getPath()
561 if (node->getType() != simgear::props::UNSPECIFIED)
562 output << " type=\"" << getTypeName(node->getType()) << '"';
564 writeData(output, node->getStringValue());
565 output << "</" << name << '>' << endl;
567 node_has_value = true;
570 // If there are children, write them next.
572 doIndent(output, indent);
573 output << '<' << name;
574 writeAtts(output, node, node_has_value);
575 output << '>' << endl;
576 for (int i = 0; i < nChildren; i++)
577 writeNode(output, node->getChild(i), write_all, indent + INDENT_STEP, archive_flag);
578 doIndent(output, indent);
579 output << "</" << name << '>' << endl;
587 writeProperties (ostream &output, const SGPropertyNode * start_node,
588 bool write_all, SGPropertyNode::Attribute archive_flag)
590 int nChildren = start_node->nChildren();
592 output << "<?xml version=\"1.0\"?>" << endl << endl;
593 output << "<PropertyList>" << endl;
595 for (int i = 0; i < nChildren; i++) {
596 writeNode(output, start_node->getChild(i), write_all, INDENT_STEP, archive_flag);
599 output << "</PropertyList>" << endl;
604 writeProperties (const string &file, const SGPropertyNode * start_node,
605 bool write_all, SGPropertyNode::Attribute archive_flag)
607 SGPath path(file.c_str());
608 path.create_dir(0777);
610 ofstream output(file.c_str());
612 writeProperties(output, start_node, write_all, archive_flag);
614 throw sg_io_exception("Cannot open file", sg_location(file));
618 // Another variation, useful when called from gdb
620 writeProperties (const char* file, const SGPropertyNode * start_node)
622 writeProperties(string(file), start_node, true);
627 ////////////////////////////////////////////////////////////////////////
628 // Copy properties from one tree to another.
629 ////////////////////////////////////////////////////////////////////////
633 * Copy one property tree to another.
635 * @param in The source property tree.
636 * @param out The destination property tree.
637 * @param attr_value Only copy properties with given attribute values.
638 * @param attr_mask Mask for attributes to be considered by attr_value
639 * (default is 0 = attributes not considered, all
640 * properties copied).
641 * @return true if all properties were copied, false if some failed
642 * (for example, if the property's value is tied read-only).
645 copyProperties (const SGPropertyNode *in, SGPropertyNode *out,
646 int attr_value, int attr_mask)
648 using namespace simgear;
651 // First, copy the actual value,
653 if (in->hasValue()) {
654 switch (in->getType()) {
656 if (!out->setBoolValue(in->getBoolValue()))
660 if (!out->setIntValue(in->getIntValue()))
664 if (!out->setLongValue(in->getLongValue()))
668 if (!out->setFloatValue(in->getFloatValue()))
672 if (!out->setDoubleValue(in->getDoubleValue()))
676 if (!out->setStringValue(in->getStringValue()))
679 case props::UNSPECIFIED:
680 if (!out->setUnspecifiedValue(in->getStringValue()))
684 if (!out->setValue(in->getValue<SGVec3d>()))
688 if (!out->setValue(in->getValue<SGVec4d>()))
694 string message = "Unknown internal SGPropertyNode type";
695 message += in->getType();
696 throw sg_error(message, "SimGear Property Reader");
700 // copy the attributes.
701 out->setAttributes( in->getAttributes() );
703 // Next, copy the children.
704 int nChildren = in->nChildren();
705 for (int i = 0; i < nChildren; i++) {
706 const SGPropertyNode * in_child = in->getChild(i);
707 int mask = attr_mask;
708 /* attributes have no meaning for nodes without values - except
709 * the PRESERVE flag. So ignore them. */
710 if (!in_child->hasValue())
711 mask &= SGPropertyNode::PRESERVE;
712 if ((in_child->getAttributes() & mask) == (attr_value & mask))
714 SGPropertyNode * out_child = out->getChild(in_child->getNameString(),
715 in_child->getIndex(),
719 out_child = out->getChild(in_child->getNameString(),
720 in_child->getIndex(),
726 if (!out_child->hasValue())
727 mask &= SGPropertyNode::PRESERVE;
728 if ((out_child->getAttributes() & mask) != (attr_value & mask))
732 (!copyProperties(in_child, out_child, attr_value, attr_mask)))
740 // end of props_io.cxx