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)
139 if (strcmp(name, "PropertyList")) {
140 string message = "Root element name is ";
142 message += "; expected PropertyList";
143 throw sg_io_exception(message, "SimGear Property Reader");
146 // Check for an include.
147 attval = atts.getValue("include");
149 SGPath path(SGPath(_base).dir());
152 readProperties(path.str(), _root);
153 } catch (sg_io_exception &e) {
158 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);
178 // Get the access-mode attributes,
179 // but don't set yet (in case they
180 // prevent us from recording the value).
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;
199 // Check for an alias.
200 attval = atts.getValue("alias");
202 if (!node->alias(attval))
203 SG_LOG(SG_INPUT, SG_ALERT, "Failed to set alias to " << attval);
206 // Check for an include.
207 attval = atts.getValue("include");
209 SGPath path(SGPath(_base).dir());
212 readProperties(path.str(), node);
213 } catch (sg_io_exception &e) {
218 push_state(node, atts.getValue("type"), mode);
223 PropsVisitor::endElement (const char * name)
228 // If there are no children and it's
229 // not an alias, then it's a leaf value.
230 if (st.node->nChildren() == 0 && !st.node->isAlias()) {
231 if (st.type == "bool") {
232 if (_data == "true" || atoi(_data.c_str()) != 0)
233 ret = st.node->setBoolValue(true);
235 ret = st.node->setBoolValue(false);
236 } else if (st.type == "int") {
237 ret = st.node->setIntValue(atoi(_data.c_str()));
238 } else if (st.type == "long") {
239 ret = st.node->setLongValue(strtol(_data.c_str(), 0, 0));
240 } else if (st.type == "float") {
241 ret = st.node->setFloatValue(atof(_data.c_str()));
242 } else if (st.type == "double") {
243 ret = st.node->setDoubleValue(strtod(_data.c_str(), 0));
244 } else if (st.type == "string") {
245 ret = st.node->setStringValue(_data.c_str());
246 } else if (st.type == "unspecified") {
247 ret = st.node->setUnspecifiedValue(_data.c_str());
249 string message = "Unrecognized data type '";
252 // FIXME: add location information
253 throw sg_io_exception(message, "SimGear Property Reader");
256 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: Failed to set "
257 << st.node->getPath() << " to value \""
258 << _data << "\" with type " << st.type);
261 // Set the access-mode attributes now,
262 // once the value has already been
264 st.node->setAttributes(st.mode);
270 PropsVisitor::data (const char * s, int length)
272 if (state().node->nChildren() == 0)
273 _data.append(string(s, length));
277 PropsVisitor::warning (const char * message, int line, int column)
279 SG_LOG(SG_INPUT, SG_ALERT, "readProperties: warning: "
280 << message << " at line " << line << ", column " << column);
285 ////////////////////////////////////////////////////////////////////////
286 // Property list reader.
287 ////////////////////////////////////////////////////////////////////////
291 * Read properties from an input stream.
293 * @param input The input stream containing an XML property file.
294 * @param start_node The root node for reading properties.
295 * @param base A base path for resolving external include references.
296 * @return true if the read succeeded, false otherwise.
299 readProperties (istream &input, SGPropertyNode * start_node,
302 PropsVisitor visitor(start_node, base);
303 readXML(input, visitor, base);
304 if (visitor.hasException())
305 throw visitor.getException();
310 * Read properties from a file.
312 * @param file A string containing the file path.
313 * @param start_node The root node for reading properties.
314 * @return true if the read succeeded, false otherwise.
317 readProperties (const string &file, SGPropertyNode * start_node)
319 PropsVisitor visitor(start_node, file);
320 readXML(file, visitor);
321 if (visitor.hasException())
322 throw visitor.getException();
327 * Read properties from an in-memory buffer.
329 * @param buf A character buffer containing the xml data.
330 * @param size The size/length of the buffer in bytes
331 * @param start_node The root node for reading properties.
332 * @return true if the read succeeded, false otherwise.
334 void readProperties (const char *buf, const int size,
335 SGPropertyNode * start_node)
337 PropsVisitor visitor(start_node, "");
338 readXML(buf, size, visitor);
339 if (visitor.hasException())
340 throw visitor.getException();
344 ////////////////////////////////////////////////////////////////////////
345 // Property list writer.
346 ////////////////////////////////////////////////////////////////////////
348 #define INDENT_STEP 2
351 * Return the type name.
354 getTypeName (SGPropertyNode::Type type)
357 case SGPropertyNode::UNSPECIFIED:
358 return "unspecified";
359 case SGPropertyNode::BOOL:
361 case SGPropertyNode::INT:
363 case SGPropertyNode::LONG:
365 case SGPropertyNode::FLOAT:
367 case SGPropertyNode::DOUBLE:
369 case SGPropertyNode::STRING:
371 case SGPropertyNode::ALIAS:
372 case SGPropertyNode::NONE:
373 return "unspecified";
376 // keep the compiler from squawking
377 return "unspecified";
382 * Escape characters for output.
385 writeData (ostream &output, const string &data)
387 for (int i = 0; i < (int)data.size(); i++) {
406 doIndent (ostream &output, int indent)
408 while (indent-- > 0) {
415 writeAtts (ostream &output, const SGPropertyNode * node)
417 int index = node->getIndex();
420 output << " n=\"" << index << '"';
423 if (!node->getAttribute(SGPropertyNode::READ))
424 output << " read=\"n\"";
426 if (!node->getAttribute(SGPropertyNode::WRITE))
427 output << " write=\"n\"";
429 if (node->getAttribute(SGPropertyNode::ARCHIVE))
430 output << " archive=\"y\"";
437 * Test whether a node is archivable or has archivable descendants.
440 isArchivable (const SGPropertyNode * node)
442 // FIXME: it's inefficient to do this all the time
443 if (node->getAttribute(SGPropertyNode::ARCHIVE))
446 int nChildren = node->nChildren();
447 for (int i = 0; i < nChildren; i++)
448 if (isArchivable(node->getChild(i)))
456 writeNode (ostream &output, const SGPropertyNode * node,
457 bool write_all, int indent)
459 // Don't write the node or any of
460 // its descendants unless it is
461 // allowed to be archived.
462 if (!write_all && !isArchivable(node))
463 return true; // Everything's OK, but we won't write.
465 const string name = node->getName();
466 int nChildren = node->nChildren();
468 // If there is a literal value,
470 if (node->hasValue() && (write_all || node->getAttribute(SGPropertyNode::ARCHIVE))) {
471 doIndent(output, indent);
472 output << '<' << name;
473 writeAtts(output, node);
474 if (node->isAlias() && node->getAliasTarget() != 0) {
475 output << " alias=\"" << node->getAliasTarget()->getPath()
478 if (node->getType() != SGPropertyNode::UNSPECIFIED)
479 output << " type=\"" << getTypeName(node->getType()) << '"';
481 writeData(output, node->getStringValue());
482 output << "</" << name << '>' << endl;
486 // If there are children, write them next.
488 doIndent(output, indent);
489 output << '<' << name;
490 writeAtts(output, node);
491 output << '>' << endl;
492 for (int i = 0; i < nChildren; i++)
493 writeNode(output, node->getChild(i), write_all, indent + INDENT_STEP);
494 doIndent(output, indent);
495 output << "</" << name << '>' << endl;
503 writeProperties (ostream &output, const SGPropertyNode * start_node,
506 int nChildren = start_node->nChildren();
508 output << "<?xml version=\"1.0\"?>" << endl << endl;
509 output << "<PropertyList>" << endl;
511 for (int i = 0; i < nChildren; i++) {
512 writeNode(output, start_node->getChild(i), write_all, INDENT_STEP);
515 output << "</PropertyList>" << endl;
520 writeProperties (const string &file, const SGPropertyNode * start_node,
523 ofstream output(file.c_str());
525 writeProperties(output, start_node, write_all);
527 throw sg_io_exception("Cannot open file", sg_location(file));
533 ////////////////////////////////////////////////////////////////////////
534 // Copy properties from one tree to another.
535 ////////////////////////////////////////////////////////////////////////
539 * Copy one property tree to another.
541 * @param in The source property tree.
542 * @param out The destination property tree.
543 * @return true if all properties were copied, false if some failed
544 * (for example, if the property's value is tied read-only).
547 copyProperties (const SGPropertyNode *in, SGPropertyNode *out)
551 // First, copy the actual value,
553 if (in->hasValue()) {
554 switch (in->getType()) {
555 case SGPropertyNode::BOOL:
556 if (!out->setBoolValue(in->getBoolValue()))
559 case SGPropertyNode::INT:
560 if (!out->setIntValue(in->getIntValue()))
563 case SGPropertyNode::LONG:
564 if (!out->setLongValue(in->getLongValue()))
567 case SGPropertyNode::FLOAT:
568 if (!out->setFloatValue(in->getFloatValue()))
571 case SGPropertyNode::DOUBLE:
572 if (!out->setDoubleValue(in->getDoubleValue()))
575 case SGPropertyNode::STRING:
576 if (!out->setStringValue(in->getStringValue()))
579 case SGPropertyNode::UNSPECIFIED:
580 if (!out->setUnspecifiedValue(in->getStringValue()))
586 string message = "Unknown internal SGPropertyNode type";
587 message += in->getType();
588 throw sg_error(message, "SimGear Property Reader");
592 // Next, copy the children.
593 int nChildren = in->nChildren();
594 for (int i = 0; i < nChildren; i++) {
595 const SGPropertyNode * in_child = in->getChild(i);
596 SGPropertyNode * out_child = out->getChild(in_child->getName(),
597 in_child->getIndex(),
599 if (!copyProperties(in_child, out_child))
606 // end of props_io.cxx