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>
25 #include "props_io.hxx"
43 #define DEFAULT_MODE (SGPropertyNode::READ|SGPropertyNode::WRITE)
47 ////////////////////////////////////////////////////////////////////////
48 // Property list visitor, for XML parsing.
49 ////////////////////////////////////////////////////////////////////////
51 class PropsVisitor : public XMLVisitor
55 PropsVisitor (SGPropertyNode * root, const string &base, int default_mode = 0)
56 : _default_mode(default_mode), _root(root), _level(0), _base(base), _hasException(false) {}
58 virtual ~PropsVisitor () {}
62 void startElement (const char * name, const XMLAttributes &atts);
63 void endElement (const char * name);
64 void data (const char * s, int length);
65 void warning (const char * message, int line, int column);
67 bool hasException () const { return _hasException; }
68 sg_io_exception &getException () { return _exception; }
69 void setException (const sg_io_exception &exception) {
70 _exception = exception;
78 State () : node(0), type(""), mode(DEFAULT_MODE), omit(false) {}
79 State (SGPropertyNode * _node, const char * _type, int _mode, bool _omit)
80 : node(_node), type(_type), mode(_mode), omit(_omit) {}
81 SGPropertyNode * node;
85 map<string,int> counters;
88 State &state () { return _state_stack[_state_stack.size() - 1]; }
90 void push_state (SGPropertyNode * node, const char * type, int mode, bool omit = false) {
92 _state_stack.push_back(State(node, "unspecified", mode, omit));
94 _state_stack.push_back(State(node, type, mode, omit));
100 _state_stack.pop_back();
106 SGPropertyNode * _root;
109 vector<State> _state_stack;
111 sg_io_exception _exception;
116 PropsVisitor::startXML ()
119 _state_stack.resize(0);
123 PropsVisitor::endXML ()
126 _state_stack.resize(0);
131 * Check a yes/no flag, with default.
134 checkFlag (const char * flag, bool defaultState = true)
138 else if (!strcmp(flag, "y"))
140 else if (!strcmp(flag, "n"))
143 string message = "Unrecognized flag value '";
146 // FIXME: add location info
147 throw sg_io_exception(message, "SimGear Property Reader");
152 PropsVisitor::startElement (const char * name, const XMLAttributes &atts)
157 if (strcmp(name, "PropertyList")) {
158 string message = "Root element name is ";
160 message += "; expected PropertyList";
161 throw sg_io_exception(message, "SimGear Property Reader");
164 // Check for an include.
165 attval = atts.getValue("include");
167 SGPath path(SGPath(_base).dir());
170 readProperties(path.str(), _root);
171 } catch (sg_io_exception &e) {
176 push_state(_root, "", DEFAULT_MODE);
182 attval = atts.getValue("n");
185 index = atoi(attval);
186 st.counters[name] = SG_MAX2(st.counters[name], index+1);
188 index = st.counters[name];
192 // Got the index, so grab the node.
193 SGPropertyNode * node = st.node->getChild(name, index, true);
194 if (!node->getAttribute(SGPropertyNode::WRITE)) {
195 SG_LOG(SG_INPUT, SG_ALERT, "Not overwriting write-protected property "
196 << node->getPath(true));
200 // Get the access-mode attributes,
201 // but don't set yet (in case they
202 // prevent us from recording the value).
203 int mode = _default_mode;
205 attval = atts.getValue("read");
206 if (checkFlag(attval, true))
207 mode |= SGPropertyNode::READ;
208 attval = atts.getValue("write");
209 if (checkFlag(attval, true))
210 mode |= SGPropertyNode::WRITE;
211 attval = atts.getValue("archive");
212 if (checkFlag(attval, false))
213 mode |= SGPropertyNode::ARCHIVE;
214 attval = atts.getValue("trace-read");
215 if (checkFlag(attval, false))
216 mode |= SGPropertyNode::TRACE_READ;
217 attval = atts.getValue("trace-write");
218 if (checkFlag(attval, false))
219 mode |= SGPropertyNode::TRACE_WRITE;
220 attval = atts.getValue("userarchive");
221 if (checkFlag(attval, false))
222 mode |= SGPropertyNode::USERARCHIVE;
224 // Check for an alias.
225 attval = atts.getValue("alias");
227 if (!node->alias(attval))
228 SG_LOG(SG_INPUT, SG_ALERT, "Failed to set alias to " << attval);
231 // Check for an include.
233 attval = atts.getValue("include");
235 SGPath path(SGPath(_base).dir());
238 readProperties(path.str(), node);
239 } catch (sg_io_exception &e) {
243 attval = atts.getValue("omit-node");
244 omit = checkFlag(attval, false);
247 const char *type = atts.getValue("type");
250 push_state(node, type, mode, omit);
255 PropsVisitor::endElement (const char * name)
260 // If there are no children and it's
261 // not an alias, then it's a leaf value.
262 if (st.node->nChildren() == 0 && !st.node->isAlias()) {
263 if (st.type == "bool") {
264 if (_data == "true" || atoi(_data.c_str()) != 0)
265 ret = st.node->setBoolValue(true);
267 ret = st.node->setBoolValue(false);
268 } else if (st.type == "int") {
269 ret = st.node->setIntValue(atoi(_data.c_str()));
270 } else if (st.type == "long") {
271 ret = st.node->setLongValue(strtol(_data.c_str(), 0, 0));
272 } else if (st.type == "float") {
273 ret = st.node->setFloatValue(atof(_data.c_str()));
274 } else if (st.type == "double") {
275 ret = st.node->setDoubleValue(strtod(_data.c_str(), 0));
276 } else if (st.type == "string") {
277 ret = st.node->setStringValue(_data.c_str());
278 } else if (st.type == "unspecified") {
279 ret = st.node->setUnspecifiedValue(_data.c_str());
280 } else if (_level == 1) {
281 ret = true; // empty <PropertyList>
283 string message = "Unrecognized data type '";
286 // FIXME: add location information
287 throw sg_io_exception(message, "SimGear Property Reader");
290 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: Failed to set "
291 << st.node->getPath() << " to value \""
292 << _data << "\" with type " << st.type);
295 // Set the access-mode attributes now,
296 // once the value has already been
298 st.node->setAttributes(st.mode);
301 State &parent = _state_stack[_state_stack.size() - 2];
302 int nChildren = st.node->nChildren();
303 for (int i = 0; i < nChildren; i++) {
304 SGPropertyNode *src = st.node->getChild(i);
305 const char *name = src->getName();
306 int index = parent.counters[name];
307 parent.counters[name]++;
308 SGPropertyNode *dst = parent.node->getChild(name, index, true);
309 copyProperties(src, dst);
311 parent.node->removeChild(st.node->getName(), st.node->getIndex(), false);
317 PropsVisitor::data (const char * s, int length)
319 if (state().node->nChildren() == 0)
320 _data.append(string(s, length));
324 PropsVisitor::warning (const char * message, int line, int column)
326 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: warning: "
327 << message << " at line " << line << ", column " << column);
332 ////////////////////////////////////////////////////////////////////////
333 // Property list reader.
334 ////////////////////////////////////////////////////////////////////////
338 * Read properties from an input stream.
340 * @param input The input stream containing an XML property file.
341 * @param start_node The root node for reading properties.
342 * @param base A base path for resolving external include references.
343 * @return true if the read succeeded, false otherwise.
346 readProperties (istream &input, SGPropertyNode * start_node,
347 const string &base, int default_mode)
349 PropsVisitor visitor(start_node, base, default_mode);
350 readXML(input, visitor, base);
351 if (visitor.hasException())
352 throw visitor.getException();
357 * Read properties from a file.
359 * @param file A string containing the file path.
360 * @param start_node The root node for reading properties.
361 * @return true if the read succeeded, false otherwise.
364 readProperties (const string &file, SGPropertyNode * start_node,
367 PropsVisitor visitor(start_node, file, default_mode);
368 readXML(file, visitor);
369 if (visitor.hasException())
370 throw visitor.getException();
375 * Read properties from an in-memory buffer.
377 * @param buf A character buffer containing the xml data.
378 * @param size The size/length of the buffer in bytes
379 * @param start_node The root node for reading properties.
380 * @return true if the read succeeded, false otherwise.
382 void readProperties (const char *buf, const int size,
383 SGPropertyNode * start_node, int default_mode)
385 PropsVisitor visitor(start_node, "", default_mode);
386 readXML(buf, size, visitor);
387 if (visitor.hasException())
388 throw visitor.getException();
392 ////////////////////////////////////////////////////////////////////////
393 // Property list writer.
394 ////////////////////////////////////////////////////////////////////////
396 #define INDENT_STEP 2
399 * Return the type name.
402 getTypeName (SGPropertyNode::Type type)
405 case SGPropertyNode::UNSPECIFIED:
406 return "unspecified";
407 case SGPropertyNode::BOOL:
409 case SGPropertyNode::INT:
411 case SGPropertyNode::LONG:
413 case SGPropertyNode::FLOAT:
415 case SGPropertyNode::DOUBLE:
417 case SGPropertyNode::STRING:
419 case SGPropertyNode::ALIAS:
420 case SGPropertyNode::NONE:
421 return "unspecified";
424 // keep the compiler from squawking
425 return "unspecified";
430 * Escape characters for output.
433 writeData (ostream &output, const string &data)
435 for (int i = 0; i < (int)data.size(); i++) {
454 doIndent (ostream &output, int indent)
456 while (indent-- > 0) {
463 writeAtts (ostream &output, const SGPropertyNode * node, bool forceindex)
465 int index = node->getIndex();
467 if (index != 0 || forceindex)
468 output << " n=\"" << index << '"';
471 if (!node->getAttribute(SGPropertyNode::READ))
472 output << " read=\"n\"";
474 if (!node->getAttribute(SGPropertyNode::WRITE))
475 output << " write=\"n\"";
477 if (node->getAttribute(SGPropertyNode::ARCHIVE))
478 output << " archive=\"y\"";
485 * Test whether a node is archivable or has archivable descendants.
488 isArchivable (const SGPropertyNode * node, SGPropertyNode::Attribute archive_flag)
490 // FIXME: it's inefficient to do this all the time
491 if (node->getAttribute(archive_flag))
494 int nChildren = node->nChildren();
495 for (int i = 0; i < nChildren; i++)
496 if (isArchivable(node->getChild(i), archive_flag))
504 writeNode (ostream &output, const SGPropertyNode * node,
505 bool write_all, int indent, SGPropertyNode::Attribute archive_flag)
507 // Don't write the node or any of
508 // its descendants unless it is
509 // allowed to be archived.
510 if (!write_all && !isArchivable(node, archive_flag))
511 return true; // Everything's OK, but we won't write.
513 const string name = node->getName();
514 int nChildren = node->nChildren();
515 bool node_has_value = false;
517 // If there is a literal value,
519 if (node->hasValue() && (write_all || node->getAttribute(archive_flag))) {
520 doIndent(output, indent);
521 output << '<' << name;
522 writeAtts(output, node, nChildren != 0);
523 if (node->isAlias() && node->getAliasTarget() != 0) {
524 output << " alias=\"" << node->getAliasTarget()->getPath()
527 if (node->getType() != SGPropertyNode::UNSPECIFIED)
528 output << " type=\"" << getTypeName(node->getType()) << '"';
530 writeData(output, node->getStringValue());
531 output << "</" << name << '>' << endl;
533 node_has_value = true;
536 // If there are children, write them next.
538 doIndent(output, indent);
539 output << '<' << name;
540 writeAtts(output, node, node_has_value);
541 output << '>' << endl;
542 for (int i = 0; i < nChildren; i++)
543 writeNode(output, node->getChild(i), write_all, indent + INDENT_STEP, archive_flag);
544 doIndent(output, indent);
545 output << "</" << name << '>' << endl;
553 writeProperties (ostream &output, const SGPropertyNode * start_node,
554 bool write_all, SGPropertyNode::Attribute archive_flag)
556 int nChildren = start_node->nChildren();
558 output << "<?xml version=\"1.0\"?>" << endl << endl;
559 output << "<PropertyList>" << endl;
561 for (int i = 0; i < nChildren; i++) {
562 writeNode(output, start_node->getChild(i), write_all, INDENT_STEP, archive_flag);
565 output << "</PropertyList>" << endl;
570 writeProperties (const string &file, const SGPropertyNode * start_node,
571 bool write_all, SGPropertyNode::Attribute archive_flag)
573 SGPath path(file.c_str());
574 path.create_dir(0777);
576 ofstream output(file.c_str());
578 writeProperties(output, start_node, write_all, archive_flag);
580 throw sg_io_exception("Cannot open file", sg_location(file));
586 ////////////////////////////////////////////////////////////////////////
587 // Copy properties from one tree to another.
588 ////////////////////////////////////////////////////////////////////////
592 * Copy one property tree to another.
594 * @param in The source property tree.
595 * @param out The destination property tree.
596 * @return true if all properties were copied, false if some failed
597 * (for example, if the property's value is tied read-only).
600 copyProperties (const SGPropertyNode *in, SGPropertyNode *out)
604 // First, copy the actual value,
606 if (in->hasValue()) {
607 switch (in->getType()) {
608 case SGPropertyNode::BOOL:
609 if (!out->setBoolValue(in->getBoolValue()))
612 case SGPropertyNode::INT:
613 if (!out->setIntValue(in->getIntValue()))
616 case SGPropertyNode::LONG:
617 if (!out->setLongValue(in->getLongValue()))
620 case SGPropertyNode::FLOAT:
621 if (!out->setFloatValue(in->getFloatValue()))
624 case SGPropertyNode::DOUBLE:
625 if (!out->setDoubleValue(in->getDoubleValue()))
628 case SGPropertyNode::STRING:
629 if (!out->setStringValue(in->getStringValue()))
632 case SGPropertyNode::UNSPECIFIED:
633 if (!out->setUnspecifiedValue(in->getStringValue()))
639 string message = "Unknown internal SGPropertyNode type";
640 message += in->getType();
641 throw sg_error(message, "SimGear Property Reader");
645 // copy the attributes.
646 out->setAttributes( in->getAttributes() );
648 // Next, copy the children.
649 int nChildren = in->nChildren();
650 for (int i = 0; i < nChildren; i++) {
651 const SGPropertyNode * in_child = in->getChild(i);
652 SGPropertyNode * out_child = out->getChild(in_child->getName(),
653 in_child->getIndex(),
655 if (!copyProperties(in_child, out_child))
662 // end of props_io.cxx