aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorStephen Kennedy2008-08-18 12:44:54 +0000
committerStephen Kennedy2008-08-18 12:44:54 +0000
commit049ac6c42b83dba3bf165e5be7c3416d1f7d959f (patch)
tree775d65ed176bf8ec4e070d8226a6ebd5a10f8e8f
parentd92909203b56d9b3fa6c4989bdeb83dbed5b94d5 (diff)
downloadscummvm-rg350-049ac6c42b83dba3bf165e5be7c3416d1f7d959f.tar.gz
scummvm-rg350-049ac6c42b83dba3bf165e5be7c3416d1f7d959f.tar.bz2
scummvm-rg350-049ac6c42b83dba3bf165e5be7c3416d1f7d959f.zip
Updated to latest version of XMLParser, and modified VirtualKeyboardParser to reflect changes.
svn-id: r33987
-rw-r--r--backends/vkeybd/virtual-keyboard-parser.cpp220
-rw-r--r--backends/vkeybd/virtual-keyboard-parser.h58
-rw-r--r--backends/vkeybd/virtual-keyboard.cpp10
-rw-r--r--backends/vkeybd/vkeybd.zipbin335616 -> 641277 bytes
-rw-r--r--common/xmlparser.cpp94
-rw-r--r--common/xmlparser.h322
6 files changed, 480 insertions, 224 deletions
diff --git a/backends/vkeybd/virtual-keyboard-parser.cpp b/backends/vkeybd/virtual-keyboard-parser.cpp
index bb575d64c1..8a276cd959 100644
--- a/backends/vkeybd/virtual-keyboard-parser.cpp
+++ b/backends/vkeybd/virtual-keyboard-parser.cpp
@@ -31,18 +31,8 @@
namespace Common {
-VirtualKeyboardParser::VirtualKeyboardParser(VirtualKeyboard *kbd) : XMLParser() {
- _keyboard = kbd;
-
- _callbacks["keyboard"] = &VirtualKeyboardParser::parserCallback_Keyboard;
- _callbacks["mode"] = &VirtualKeyboardParser::parserCallback_Mode;
- _callbacks["event"] = &VirtualKeyboardParser::parserCallback_Event;
- _callbacks["layout"] = &VirtualKeyboardParser::parserCallback_Layout;
- _callbacks["map"] = &VirtualKeyboardParser::parserCallback_Map;
- _callbacks["area"] = &VirtualKeyboardParser::parserCallback_Area;
-
- _closedCallbacks["keyboard"] = &VirtualKeyboardParser::parserCallback_KeyboardClosed;
- _closedCallbacks["mode"] = &VirtualKeyboardParser::parserCallback_ModeClosed;
+VirtualKeyboardParser::VirtualKeyboardParser(VirtualKeyboard *kbd)
+ : XMLParser(), _keyboard(kbd) {
}
void VirtualKeyboardParser::cleanup() {
@@ -55,27 +45,21 @@ void VirtualKeyboardParser::cleanup() {
}
}
-bool VirtualKeyboardParser::keyCallback(String keyName) {
- if (!_callbacks.contains(_activeKey.top()->name))
- return parserError("%s is not a valid key name.", keyName.c_str());
-
- return (this->*(_callbacks[_activeKey.top()->name]))();
-}
-
-bool VirtualKeyboardParser::closedKeyCallback(String keyName) {
- if (!_closedCallbacks.contains(_activeKey.top()->name))
- return true;
-
- return (this->*(_closedCallbacks[_activeKey.top()->name]))();
+bool VirtualKeyboardParser::closedKeyCallback(ParserNode *node) {
+ if (node->name.equalsIgnoreCase("keyboard")) {
+ _kbdParsed = true;
+ if (!_keyboard->_initialMode)
+ return parserError("Initial mode of keyboard pack not defined");
+ } else if (node->name.equalsIgnoreCase("mode")) {
+ if (!_layoutParsed) {
+ return parserError("'%s' layout missing from '%s' mode",
+ _mode->resolution.c_str(), _mode->name.c_str());
+ }
+ }
+ return true;
}
-bool VirtualKeyboardParser::parserCallback_Keyboard() {
- ParserNode *kbdNode = getActiveNode();
-
- assert(kbdNode->name == "keyboard");
-
- if (getParentNode(kbdNode) != 0)
- return parserError("Keyboard element must be root");
+bool VirtualKeyboardParser::parserCallback_keyboard(ParserNode *node) {
if (_kbdParsed)
return parserError("Only a single keyboard element is allowed");
@@ -84,53 +68,34 @@ bool VirtualKeyboardParser::parserCallback_Keyboard() {
if (_parseMode == kParseCheckResolutions)
return true;
- if (!kbdNode->values.contains("initial_mode"))
- return parserError("Keyboard element must contain initial_mode attribute");
-
- _initialModeName = kbdNode->values["initial_mode"];
+ _initialModeName = node->values["initial_mode"];
- if (kbdNode->values.contains("h_align")) {
- String h = kbdNode->values["h_align"];
- if (h == "left")
+ if (node->values.contains("h_align")) {
+ String h = node->values["h_align"];
+ if (h.equalsIgnoreCase("left"))
_keyboard->_hAlignment = VirtualKeyboard::kAlignLeft;
- else if (h == "centre" || h == "center")
+ else if (h.equalsIgnoreCase("centre") || h.equalsIgnoreCase("center"))
_keyboard->_hAlignment = VirtualKeyboard::kAlignCentre;
- else if (h == "right")
+ else if (h.equalsIgnoreCase("right"))
_keyboard->_hAlignment = VirtualKeyboard::kAlignRight;
}
- if (kbdNode->values.contains("v_align")) {
- String v = kbdNode->values["h_align"];
- if (v == "top")
+ if (node->values.contains("v_align")) {
+ String v = node->values["h_align"];
+ if (v.equalsIgnoreCase("top"))
_keyboard->_vAlignment = VirtualKeyboard::kAlignTop;
- else if (v == "middle" || v == "center")
+ else if (v.equalsIgnoreCase("middle") || v.equalsIgnoreCase("center"))
_keyboard->_vAlignment = VirtualKeyboard::kAlignMiddle;
- else if (v == "bottom")
+ else if (v.equalsIgnoreCase("bottom"))
_keyboard->_vAlignment = VirtualKeyboard::kAlignBottom;
}
return true;
}
-bool VirtualKeyboardParser::parserCallback_KeyboardClosed() {
- _kbdParsed = true;
- if (!_keyboard->_initialMode)
- return parserError("Initial mode of keyboard pack not defined");
- return true;
-}
-
-bool VirtualKeyboardParser::parserCallback_Mode() {
- ParserNode *modeNode = getActiveNode();
+bool VirtualKeyboardParser::parserCallback_mode(ParserNode *node) {
- assert(modeNode->name == "mode");
-
- if (getParentNode(modeNode) == 0 || getParentNode(modeNode)->name != "keyboard")
- return parserError("Mode element must be child of keyboard element");
-
- if (!modeNode->values.contains("name") || !modeNode->values.contains("resolutions"))
- return parserError("Mode element must contain name and resolutions attributes");
-
- String name = modeNode->values["name"];
+ String name = node->values["name"];
if (_parseMode == kParseFull) {
// if full parse then add new mode to keyboard
@@ -146,7 +111,7 @@ bool VirtualKeyboardParser::parserCallback_Mode() {
if (name == _initialModeName)
_keyboard->_initialMode = _mode;
- String resolutions = modeNode->values["resolutions"];
+ String resolutions = node->values["resolutions"];
StringTokenizer tok (resolutions, " ,");
// select best resolution simply by minimising the difference between the
@@ -179,7 +144,7 @@ bool VirtualKeyboardParser::parserCallback_Mode() {
if (_parseMode == kParseCheckResolutions) {
if (_mode->resolution == newResolution) {
- modeNode->ignore = true;
+ node->ignore = true;
return true;
} else {
// remove data relating to old resolution
@@ -198,87 +163,69 @@ bool VirtualKeyboardParser::parserCallback_Mode() {
return true;
}
-bool VirtualKeyboardParser::parserCallback_ModeClosed() {
- if (!_layoutParsed) {
- return parserError("'%s' layout missing from '%s' mode", _mode->resolution.c_str(), _mode->name.c_str());
- }
- return true;
-}
-
-bool VirtualKeyboardParser::parserCallback_Event() {
- ParserNode *evtNode = getActiveNode();
-
- assert(evtNode->name == "event");
-
- if (getParentNode(evtNode) == 0 || getParentNode(evtNode)->name != "mode")
- return parserError("Event element must be child of mode element");
-
- if (!evtNode->values.contains("name") || !evtNode->values.contains("type"))
- return parserError("Event element must contain name and type attributes");
-
- assert(_mode);
-
+bool VirtualKeyboardParser::parserCallback_event(ParserNode *node) {
+
// if just checking resolutions we're done
if (_parseMode == kParseCheckResolutions)
return true;
- String name = evtNode->values["name"];
+ String name = node->values["name"];
if (_mode->events.contains(name))
return parserError("Event '%s' has already been defined", name.c_str());
VirtualKeyboard::Event *evt = new VirtualKeyboard::Event();
evt->name = name;
- String type = evtNode->values["type"];
- if (type == "key") {
- if (!evtNode->values.contains("code") || !evtNode->values.contains("ascii")) {
+ String type = node->values["type"];
+ if (type.equalsIgnoreCase("key")) {
+ if (!node->values.contains("code") || !node->values.contains("ascii")) {
delete evt;
return parserError("Key event element must contain code and ascii attributes");
}
evt->type = VirtualKeyboard::kEventKey;
KeyState *ks = (KeyState*) malloc(sizeof(KeyState));
- ks->keycode = (KeyCode)atoi(evtNode->values["code"].c_str());
- ks->ascii = atoi(evtNode->values["ascii"].c_str());
+ ks->keycode = (KeyCode)atoi(node->values["code"].c_str());
+ ks->ascii = atoi(node->values["ascii"].c_str());
ks->flags = 0;
- if (evtNode->values.contains("modifiers"))
- ks->flags = parseFlags(evtNode->values["modifiers"]);
+ if (node->values.contains("modifiers"))
+ ks->flags = parseFlags(node->values["modifiers"]);
evt->data = ks;
- } else if (type == "modifier") {
- if (!evtNode->values.contains("modifiers")) {
+ } else if (type.equalsIgnoreCase("modifier")) {
+ if (!node->values.contains("modifiers")) {
delete evt;
return parserError("Key modifier element must contain modifier attributes");
}
evt->type = VirtualKeyboard::kEventModifier;
byte *flags = (byte*) malloc(sizeof(byte));
- *(flags) = parseFlags(evtNode->values["modifiers"]);
+ *(flags) = parseFlags(node->values["modifiers"]);
evt->data = flags;
- } else if (type == "switch_mode") {
- if (!evtNode->values.contains("mode")) {
+ } else if (type.equalsIgnoreCase("switch_mode")) {
+ if (!node->values.contains("mode")) {
delete evt;
return parserError("Switch mode event element must contain mode attribute");
}
evt->type = VirtualKeyboard::kEventSwitchMode;
- String& mode = evtNode->values["mode"];
+ String& mode = node->values["mode"];
char *str = (char*) malloc(sizeof(char) * mode.size() + 1);
memcpy(str, mode.c_str(), sizeof(char) * mode.size());
str[mode.size()] = 0;
evt->data = str;
- } else if (type == "submit") {
+ } else if (type.equalsIgnoreCase("submit")) {
evt->type = VirtualKeyboard::kEventSubmit;
- } else if (type == "cancel") {
+ } else if (type.equalsIgnoreCase("cancel")) {
evt->type = VirtualKeyboard::kEventCancel;
- } else if (type == "clear") {
+ } else if (type.equalsIgnoreCase("clear")) {
evt->type = VirtualKeyboard::kEventClear;
- } else if (type == "delete") {
+ } else if (type.equalsIgnoreCase("delete")) {
evt->type = VirtualKeyboard::kEventDelete;
- } else if (type == "move_left") {
+ } else if (type.equalsIgnoreCase("move_left")) {
evt->type = VirtualKeyboard::kEventMoveLeft;
- } else if (type == "move_right") {
+ } else if (type.equalsIgnoreCase("move_right")) {
evt->type = VirtualKeyboard::kEventMoveRight;
} else {
delete evt;
@@ -290,27 +237,18 @@ bool VirtualKeyboardParser::parserCallback_Event() {
return true;
}
-bool VirtualKeyboardParser::parserCallback_Layout() {
- ParserNode *layoutNode = getActiveNode();
-
- assert(layoutNode->name == "layout");
-
- if (getParentNode(layoutNode) == 0 || getParentNode(layoutNode)->name != "mode")
- return parserError("Layout element must be child of mode element");
-
- if (!layoutNode->values.contains("resolution") || !layoutNode->values.contains("bitmap"))
- return parserError("Layout element must contain resolution and bitmap attributes");
+bool VirtualKeyboardParser::parserCallback_layout(ParserNode *node) {
assert(!_mode->resolution.empty());
- String res = layoutNode->values["resolution"];
+ String res = node->values["resolution"];
if (res != _mode->resolution) {
- layoutNode->ignore = true;
+ node->ignore = true;
return true;
}
- _mode->bitmapName = layoutNode->values["bitmap"];
+ _mode->bitmapName = node->values["bitmap"];
_mode->image = ImageMan.getSurface(_mode->bitmapName);
if (!_mode->image) {
if (!ImageMan.registerSurface(_mode->bitmapName, 0))
@@ -321,17 +259,17 @@ bool VirtualKeyboardParser::parserCallback_Layout() {
return parserError("Error loading bitmap '%s'", _mode->bitmapName.c_str());
}
- if (layoutNode->values.contains("transparent_color")) {
+ if (node->values.contains("transparent_color")) {
int r, g, b;
- if (!parseIntegerKey(layoutNode->values["transparent_color"].c_str(), 3, &r, &g, &b))
+ if (!parseIntegerKey(node->values["transparent_color"].c_str(), 3, &r, &g, &b))
return parserError("Could not parse color value");
_mode->transparentColor = g_system->RGBToColor(r, g, b);
- } else
- _mode->transparentColor = g_system->RGBToColor(255, 0, 255); // default to purple
+ } else // default to purple
+ _mode->transparentColor = g_system->RGBToColor(255, 0, 255);
- if (layoutNode->values.contains("display_font_color")) {
+ if (node->values.contains("display_font_color")) {
int r, g, b;
- if (!parseIntegerKey(layoutNode->values["display_font_color"].c_str(), 3, &r, &g, &b))
+ if (!parseIntegerKey(node->values["display_font_color"].c_str(), 3, &r, &g, &b))
return parserError("Could not parse color value");
_mode->displayFontColor = g_system->RGBToColor(r, g, b);
} else
@@ -342,41 +280,25 @@ bool VirtualKeyboardParser::parserCallback_Layout() {
return true;
}
-bool VirtualKeyboardParser::parserCallback_Map() {
- ParserNode *mapNode = getActiveNode();
-
- assert(mapNode->name == "map");
-
- if (getParentNode(mapNode) == 0 || getParentNode(mapNode)->name != "layout")
- return parserError("Map element must be child of layout element");
-
+bool VirtualKeyboardParser::parserCallback_map(ParserNode *node) {
return true;
}
-bool VirtualKeyboardParser::parserCallback_Area() {
- ParserNode *areaNode = getActiveNode();
-
- assert(areaNode->name == "area");
-
- if (getParentNode(areaNode) == 0 || getParentNode(areaNode)->name != "map")
- return parserError("Area element must be child of map element");
-
- if (!areaNode->values.contains("shape") || !areaNode->values.contains("coords") || !areaNode->values.contains("target"))
- return parserError("Area element must contain shape, coords and target attributes");
+bool VirtualKeyboardParser::parserCallback_area(ParserNode *node) {
- String& shape = areaNode->values["shape"];
- String& target = areaNode->values["target"];
- String& coords = areaNode->values["coords"];
+ String& shape = node->values["shape"];
+ String& target = node->values["target"];
+ String& coords = node->values["coords"];
- if (target == "display_area") {
- if (shape != "rect")
+ if (target.equalsIgnoreCase("display_area")) {
+ if (! shape.equalsIgnoreCase("rect"))
return parserError("display_area must be a rect area");
_mode->displayArea = new Rect();
return parseRect(_mode->displayArea, coords);
- } else if (shape == "rect") {
+ } else if (shape.equalsIgnoreCase("rect")) {
Polygon *poly = _mode->imageMap.createArea(target);
return parseRectAsPolygon(poly, coords);
- } else if (shape == "poly") {
+ } else if (shape.equalsIgnoreCase("poly")) {
Polygon *poly = _mode->imageMap.createArea(target);
return parsePolygon(poly, coords);
}
diff --git a/backends/vkeybd/virtual-keyboard-parser.h b/backends/vkeybd/virtual-keyboard-parser.h
index 59a770bdce..3f8f567d54 100644
--- a/backends/vkeybd/virtual-keyboard-parser.h
+++ b/backends/vkeybd/virtual-keyboard-parser.h
@@ -170,8 +170,6 @@ enum ParseMode {
class VirtualKeyboardParser : public Common::XMLParser {
- typedef bool (VirtualKeyboardParser::*ParserCallback)();
-
public:
VirtualKeyboardParser(VirtualKeyboard *kbd);
@@ -180,6 +178,40 @@ public:
}
protected:
+ CUSTOM_XML_PARSER(VirtualKeyboardParser) {
+ XML_KEY(keyboard)
+ XML_PROP(initial_mode, true)
+ XML_PROP(v_align, false)
+ XML_PROP(h_align, false)
+ XML_KEY(mode)
+ XML_PROP(name, true)
+ XML_PROP(resolutions, true)
+ XML_KEY(layout)
+ XML_PROP(resolution, true)
+ XML_PROP(bitmap, true)
+ XML_PROP(transparent_color, false)
+ XML_PROP(display_font_color, false)
+ XML_KEY(map)
+ XML_KEY(area)
+ XML_PROP(shape, true)
+ XML_PROP(coords, true)
+ XML_PROP(target, true)
+ KEY_END()
+ KEY_END()
+ KEY_END()
+ XML_KEY(event)
+ XML_PROP(name, true)
+ XML_PROP(type, true)
+ XML_PROP(code, false)
+ XML_PROP(ascii, false)
+ XML_PROP(modifiers, false)
+ XML_PROP(mode, false)
+ KEY_END()
+ KEY_END()
+ KEY_END()
+ } PARSER_END()
+
+protected:
VirtualKeyboard *_keyboard;
/** internal state variables of parser */
@@ -189,27 +221,21 @@ protected:
bool _kbdParsed;
bool _layoutParsed;
- bool keyCallback(String keyName);
- bool closedKeyCallback(String keyName);
void cleanup();
- bool parserCallback_Keyboard();
- bool parserCallback_Mode();
- bool parserCallback_Event();
- bool parserCallback_Layout();
- bool parserCallback_Map();
- bool parserCallback_Area();
-
- bool parserCallback_KeyboardClosed();
- bool parserCallback_ModeClosed();
+ bool parserCallback_keyboard(ParserNode *node);
+ bool parserCallback_mode(ParserNode *node);
+ bool parserCallback_event(ParserNode *node);
+ bool parserCallback_layout(ParserNode *node);
+ bool parserCallback_map(ParserNode *node);
+ bool parserCallback_area(ParserNode *node);
+
+ bool closedKeyCallback(ParserNode *node);
byte parseFlags(const String& flags);
bool parseRect(Rect *rect, const String& coords);
bool parsePolygon(Polygon *poly, const String& coords);
bool parseRectAsPolygon(Polygon *poly, const String& coords);
-
- HashMap<String, ParserCallback, IgnoreCase_Hash, IgnoreCase_EqualTo> _callbacks;
- HashMap<String, ParserCallback, IgnoreCase_Hash, IgnoreCase_EqualTo> _closedCallbacks;
};
} // end of namespace GUI
diff --git a/backends/vkeybd/virtual-keyboard.cpp b/backends/vkeybd/virtual-keyboard.cpp
index fbf26b80b5..bb80affeaa 100644
--- a/backends/vkeybd/virtual-keyboard.cpp
+++ b/backends/vkeybd/virtual-keyboard.cpp
@@ -85,20 +85,22 @@ bool VirtualKeyboard::loadKeyboardPack(Common::String packName) {
} else { // use current directory
vkDir = new FilesystemNode(".");
}
-
- // TODO - make parser support FilesystemNode's
+
+ // HACK/FIXME:
+ // - the ImageManager still needs the default directory to be added
+ // - would be nice for everything to use FSNodes
File::addDefaultDirectory(vkDir->getPath());
if (vkDir->getChild(packName + ".xml").exists()) {
// uncompressed keyboard pack
- if (!_parser->loadFile(packName + ".xml"))
+ if (!_parser->loadFile(vkDir->getChild(packName + ".xml")))
return false;
} else if (vkDir->getChild(packName + ".zip").exists()) {
// compressed keyboard pack
#ifdef USE_ZLIB
- unzFile zipFile = unzOpen((packName + ".zip").c_str());
+ unzFile zipFile = unzOpen(vkDir->getChild(packName + ".zip").getPath().c_str());
if (zipFile && unzLocateFile(zipFile, (packName + ".xml").c_str(), 2) == UNZ_OK) {
unz_file_info fileInfo;
unzOpenCurrentFile(zipFile);
diff --git a/backends/vkeybd/vkeybd.zip b/backends/vkeybd/vkeybd.zip
index 8c0c778aef..216512fef2 100644
--- a/backends/vkeybd/vkeybd.zip
+++ b/backends/vkeybd/vkeybd.zip
Binary files differ
diff --git a/common/xmlparser.cpp b/common/xmlparser.cpp
index d0c89a9d3e..900f2f81ab 100644
--- a/common/xmlparser.cpp
+++ b/common/xmlparser.cpp
@@ -41,25 +41,34 @@ bool XMLParser::parserError(const char *errorString, ...) {
int lineCount = 1;
int lineStart = 0;
- do {
- if (_text[pos] == '\n' || _text[pos] == '\r') {
- lineCount++;
-
- if (lineStart == 0)
- lineStart = MAX(pos + 1, _pos - 60);
- }
- } while (pos-- > 0);
+ if (_fileName == "Memory Stream") {
+ lineStart = MAX(0, _pos - 35);
+ lineCount = 0;
+ } else {
+ do {
+ if (_text[pos] == '\n' || _text[pos] == '\r') {
+ lineCount++;
+
+ if (lineStart == 0)
+ lineStart = MAX(pos + 1, _pos - 60);
+ }
+ } while (pos-- > 0);
+ }
char lineStr[70];
_text.stream()->seek(lineStart, SEEK_SET);
_text.stream()->readLine(lineStr, 70);
+
+ for (int i = 0; i < 70; ++i)
+ if (lineStr[i] == '\n')
+ lineStr[i] = ' ';
- printf(" File <%s>, line %d:\n", _fileName.c_str(), lineCount);
+ printf("\n File <%s>, line %d:\n", _fileName.c_str(), lineCount);
bool startFull = lineStr[0] == '<';
bool endFull = lineStr[strlen(lineStr) - 1] == '>';
- printf("%s%s%s\n", startFull ? "" : "...", endFull ? "" : "...", lineStr);
+ printf("%s%s%s\n", startFull ? "" : "...", lineStr, endFull ? "" : "...");
int cursor = MIN(_pos - lineStart, 70);
@@ -77,13 +86,36 @@ bool XMLParser::parserError(const char *errorString, ...) {
vprintf(errorString, args);
va_end(args);
- printf("\n");
+ printf("\n\n");
return false;
}
bool XMLParser::parseActiveKey(bool closed) {
bool ignore = false;
+ assert(_activeKey.empty() == false);
+
+ ParserNode *key = _activeKey.top();
+ XMLKeyLayout *layout = (_activeKey.size() == 1) ? _XMLkeys : getParentNode(key)->layout;
+
+ if (layout->children.contains(key->name)) {
+ key->layout = layout->children[key->name];
+
+ Common::StringMap localMap = key->values;
+
+ for (Common::List<XMLKeyLayout::XMLKeyProperty>::const_iterator i = key->layout->properties.begin(); i != key->layout->properties.end(); ++i) {
+ if (localMap.contains(i->name))
+ localMap.erase(i->name);
+ else if (i->required)
+ return parserError("Missing required property '%s' inside key '%s'", i->name.c_str(), key->name.c_str());
+ }
+
+ if (localMap.empty() == false)
+ return parserError("Unhandled property inside key '%s': '%s'", key->name.c_str(), localMap.begin()->_key.c_str());
+
+ } else {
+ return parserError("Unexpected key in the active scope: '%s'.", key->name.c_str());
+ }
// check if any of the parents must be ignored.
// if a parent is ignored, all children are too.
@@ -92,13 +124,18 @@ bool XMLParser::parseActiveKey(bool closed) {
ignore = true;
}
- if (ignore == false && keyCallback(_activeKey.top()->name) == false) {
+ if (ignore == false && keyCallback(key) == false) {
+ // HACK: People may be stupid and overlook the fact that
+ // when keyCallback() fails, a parserError() must be set.
+ // We set it manually in that case.
+ if (_state != kParserError)
+ parserError("Unhandled exception when parsing '%s' key.", key->name.c_str());
+
return false;
}
- if (closed) {
- delete _activeKey.pop();
- }
+ if (closed)
+ return closeKey();
return true;
}
@@ -129,10 +166,33 @@ bool XMLParser::parseKeyValue(Common::String keyName) {
return true;
}
+bool XMLParser::closeKey() {
+ bool ignore = false;
+ bool result = true;
+
+ for (int i = _activeKey.size() - 1; i >= 0; --i) {
+ if (_activeKey[i]->ignore)
+ ignore = true;
+ }
+
+ if (ignore == false)
+ result = closedKeyCallback(_activeKey.top());
+
+ delete _activeKey.pop();
+
+ return result;
+}
+
bool XMLParser::parse() {
if (_text.ready() == false)
return parserError("XML stream not ready for reading.");
+
+ if (_XMLkeys == 0)
+ buildLayout();
+
+ while (!_activeKey.empty())
+ delete _activeKey.pop();
cleanup();
@@ -186,6 +246,7 @@ bool XMLParser::parse() {
node->name = _token;
node->ignore = false;
node->depth = _activeKey.size();
+ node->layout = 0;
_activeKey.push(node);
}
@@ -194,13 +255,12 @@ bool XMLParser::parse() {
case kParserNeedPropertyName:
if (activeClosure) {
- if (!closedKeyCallback(_activeKey.top()->name)) {
+ if (!closeKey()) {
parserError("Missing data when closing key '%s'.", _activeKey.top()->name.c_str());
break;
}
activeClosure = false;
- delete _activeKey.pop();
if (_text[_pos++] != '>')
parserError("Invalid syntax in key closure.");
diff --git a/common/xmlparser.h b/common/xmlparser.h
index 399525d161..4d1c8fc85d 100644
--- a/common/xmlparser.h
+++ b/common/xmlparser.h
@@ -32,12 +32,199 @@
#include "common/xmlparser.h"
#include "common/stream.h"
#include "common/file.h"
+#include "common/fs.h"
#include "common/hashmap.h"
#include "common/hash-str.h"
#include "common/stack.h"
namespace Common {
+
+/***********************************************
+ **** XMLParser.cpp/h -- Generic XML Parser ****
+ ***********************************************
+
+ This is a simple implementation of a generic parser which is able to
+ interpret a subset of the XML language.
+
+ The XMLParser class is virtual, and must be derived into a child class,
+ called a Custom Parser Class, which will manage the parsed data for your
+ specific needs.
+
+ Custom Parser Classes have two basic requirements:
+ They must inherit directly the XMLParser class, and they must define the
+ parsing layout of the XML file.
+
+ Declaring the XML layout is done with the help of the CUSTOM_XML_PARSER()
+ macro: this macro must appear once inside the Custom Parser Class
+ declaration, and takes a single parameter, the name of the Custom Parser
+ Class.
+
+ The macro must be followed by the actual layout of the XML files to be
+ parsed, and closed with the PARSER_END() macro. The layout of XML files
+ is defined by the use of 3 helper macros: XML_KEY(), KEY_END() and
+ XML_PROP().
+
+ Here's a sample of its usage:
+
+ =========== =========== =========== =========== =========== ===========
+
+ CUSTOM_XML_PARSER(ThemeParser) {
+ XML_KEY(render_info)
+ XML_KEY(palette)
+ XML_KEY(color)
+ XML_PROP(name, true)
+ XML_PROP(rgb, true)
+ KEY_END()
+ KEY_END()
+
+ XML_KEY(fonts)
+ XML_KEY(font)
+ XML_PROP(id, true)
+ XML_PROP(type, true)
+ XML_PROP(color, true)
+ KEY_END()
+ KEY_END()
+
+ XML_KEY(defaults)
+ XML_PROP(stroke, false)
+ XML_PROP(shadow, false)
+ XML_PROP(factor, false)
+ XML_PROP(fg_color, false)
+ XML_PROP(bg_color, false)
+ XML_PROP(gradient_start, false)
+ XML_PROP(gradient_end, false)
+ XML_PROP(gradient_factor, false)
+ XML_PROP(fill, false)
+ KEY_END()
+ KEY_END()
+ } PARSER_END()
+
+ =========== =========== =========== =========== =========== ===========
+
+ The XML_KEY() macro takes a single argument, the name of the expected key.
+ Inside the scope of each key, you may define properties for the given key
+ with the XML_PROP() macro, which takes as parameters the name of the
+ property and whether it's optional or required. You might also define the
+ contained children keys, using the XML_KEY() macro again.
+ The scope of a XML key is closed with the KEY_END() macro.
+
+ Keys which may contain any kind of Property names may be defined with the
+ XML_PROP_ANY() macro instead of the XML_PROP() macro. This macro takes no
+ arguments.
+
+ As an example, the following XML layout:
+
+ XML_KEY(palette)
+ XML_KEY(color)
+ XML_PROP(name, true)
+ XML_PROP(rgb, true)
+ XML_PROP(optional_param, false)
+ KEY_END()
+ KEY_END()
+
+ will expect to parse a syntax like this:
+
+ <palette>
+ <color name = "red" rgb = "255, 0, 0" />
+ <color name = "blue" rgb = "0, 0, 255" optional_param = "565" />
+ </palette>
+
+ Once a layout has been defined, everytime a XML node (that is, a key and
+ all its properties) has been parsed, a specific callback funcion is called,
+ which should take care of managing the parsed data for the node.
+
+ Callback functions must be explicitly declared with the following syntax:
+
+ bool parserCallback_KEYNAME(ParserNode *node);
+
+ A callback function is needed for each key that can be parsed, since they
+ are called automatically; the function will receive a pointer to the XML
+ Node that has been parsed. This XML Node has the following properties:
+
+ - It's assured to be expected in the layout of the XML file (i.e.
+ has the proper position and depth in the XML tree).
+
+ - It's assured to contain all the required Properties that have
+ been declared in the XML layout.
+
+ - It's assured to contain NO unexpected properties (i.e. properties
+ which haven't been declared in the XML layout).
+
+ Further validation of the Node's data may be performed inside the callback
+ function. Once the node has been validated and its data has been parsed/
+ managed, the callback function is expected to return true.
+
+ If the data in the XML Node is corrupted or there was a problem when
+ parsing it, the callback function is expected to return false or,
+ preferably, to throw a parserError() using the following syntax:
+
+ return parserError("There was a problem in key '%s'.", arg1, ...);
+
+ Also, note that the XML parser doesn't take into account the actual order
+ of the keys and properties in the XML layout definition, only its layout
+ and relationships.
+
+ Lastly, when defining your own Custom XML Parser, further customization
+ may be accomplished _optionally_ by overloading several virtual functions
+ of the XMLParser class.
+
+ Check the API documentation of the following functions for more info:
+
+ virtual bool closedKeyCallback(ParserNode *node);
+ virtual bool skipComments();
+ virtual bool isValidNameChar(char c);
+ virtual void cleanup();
+
+ Check the sample implementation of the GUI::ThemeParser custom parser
+ for a working sample of a Custom XML Parser.
+
+*/
+
+#define XML_KEY(keyName) {\
+ lay = new CustomXMLKeyLayout;\
+ lay->callback = (&kLocalParserName::parserCallback_##keyName);\
+ layout.top()->children[#keyName] = lay;\
+ layout.push(lay); \
+ _layoutList.push_back(lay);\
+ for (Common::List<XMLKeyLayout::XMLKeyProperty>::const_iterator p = globalProps.begin(); p != globalProps.end(); ++p){\
+ layout.top()->properties.push_back(*p);}
+
+#define XML_KEY_RECURSIVE(keyName) {\
+ layout.top()->children[#keyName] = layout.top();\
+ layout.push(layout.top());\
+ }
+
+#define KEY_END() layout.pop(); }
+
+#define XML_PROP(propName, req) {\
+ prop.name = #propName; \
+ prop.required = req; \
+ layout.top()->properties.push_back(prop); }
+
+#define XML_GLOBAL_PROP(propName, req) {\
+ prop.name = #propName; \
+ prop.required = req;\
+ globalProps.push_back(prop); }
+
+
+#define CUSTOM_XML_PARSER(parserName) \
+ protected: \
+ typedef parserName kLocalParserName; \
+ bool keyCallback(ParserNode *node) {return node->layout->doCallback(this, node); }\
+ struct CustomXMLKeyLayout : public XMLKeyLayout {\
+ typedef bool (parserName::*ParserCallback)(ParserNode *node);\
+ ParserCallback callback;\
+ bool doCallback(XMLParser *parent, ParserNode *node) {return ((kLocalParserName*)parent->*callback)(node);} };\
+ virtual void buildLayout() { \
+ Common::Stack<XMLKeyLayout*> layout; \
+ CustomXMLKeyLayout *lay = 0; \
+ XMLKeyLayout::XMLKeyProperty prop; \
+ Common::List<XMLKeyLayout::XMLKeyProperty> globalProps; \
+ _XMLkeys = new CustomXMLKeyLayout; \
+ layout.push(_XMLkeys);
+
+#define PARSER_END() layout.clear(); }
class XMLStream {
protected:
@@ -91,11 +278,19 @@ public:
/**
* Parser constructor.
*/
- XMLParser() {}
+ XMLParser() : _XMLkeys(0) {}
virtual ~XMLParser() {
while (!_activeKey.empty())
delete _activeKey.pop();
+
+ delete _XMLkeys;
+
+ for (Common::List<XMLKeyLayout*>::iterator i = _layoutList.begin();
+ i != _layoutList.end(); ++i)
+ delete *i;
+
+ _layoutList.clear();
}
/** Active state for the parser */
@@ -109,6 +304,28 @@ public:
kParserError
};
+
+ struct XMLKeyLayout;
+ struct ParserNode;
+
+ typedef Common::HashMap<Common::String, XMLParser::XMLKeyLayout*, Common::IgnoreCase_Hash, Common::IgnoreCase_EqualTo> ChildMap;
+
+ /** nested struct representing the layout of the XML file */
+ struct XMLKeyLayout {
+ struct XMLKeyProperty {
+ Common::String name;
+ bool required;
+ };
+
+ Common::List<XMLKeyProperty> properties;
+ ChildMap children;
+
+ virtual bool doCallback(XMLParser *parent, ParserNode *node) = 0;
+
+ virtual ~XMLKeyLayout() {
+ properties.clear();
+ }
+ } *_XMLkeys;
/** Struct representing a parsed node */
struct ParserNode {
@@ -116,6 +333,7 @@ public:
Common::StringMap values;
bool ignore;
int depth;
+ XMLKeyLayout *layout;
};
/**
@@ -125,16 +343,31 @@ public:
*
* @param filename Name of the file to load.
*/
- virtual bool loadFile(Common::String filename) {
+ bool loadFile(const Common::String &filename) {
Common::File *f = new Common::File;
- if (!f->open(filename))
+ if (!f->open(filename)) {
+ delete f;
return false;
+ }
_fileName = filename;
_text.loadStream(f);
return true;
}
+
+ bool loadFile(const FilesystemNode &node) {
+ Common::File *f = new Common::File;
+
+ if (!f->open(node)) {
+ delete f;
+ return false;
+ }
+
+ _fileName = node.getName();
+ _text.loadStream(f);
+ return true;
+ }
/**
* Loads a memory buffer into the parser.
@@ -147,17 +380,23 @@ public:
* i.e. if it can be freed safely after it's
* no longer needed by the parser.
*/
- virtual bool loadBuffer(const byte *buffer, uint32 size, bool disposable = false) {
+ bool loadBuffer(const byte *buffer, uint32 size, bool disposable = false) {
_text.loadStream(new MemoryReadStream(buffer, size, disposable));
_fileName = "Memory Stream";
return true;
}
+
+ bool loadStream(MemoryReadStream *stream) {
+ _text.loadStream(stream);
+ _fileName = "Compressed File Stream";
+ return true;
+ }
/**
* The actual parsing function.
* Parses the loaded data stream, returns true if successful.
*/
- virtual bool parse();
+ bool parse();
/**
* Returns the active node being parsed (the one on top of
@@ -178,70 +417,81 @@ public:
}
protected:
+
/**
- * The keycallback function must be overloaded by inheriting classes
- * to implement parser-specific functions.
+ * The buildLayout function builds the layout for the parser to use
+ * based on a series of helper macros. This function is automatically
+ * generated by the CUSTOM_XML_PARSER() macro on custom parsers.
*
- * This function is called everytime a key has successfully been parsed.
- * The keyName parameter contains the name of the key that has just been
- * parsed; this same key is still on top of the Node Stack.
+ * See the documentation regarding XML layouts.
+ */
+ virtual void buildLayout() = 0;
+
+ /**
+ * The keycallback function is automatically overloaded on custom parsers
+ * when using the CUSTOM_XML_PARSER() macro.
*
- * Access the node stack to view this key's properties and its parents.
- * Remember to leave the node stack _UNCHANGED_ in your own function. Removal
- * of closed keys is done automatically.
+ * Its job is to call the corresponding Callback function for the given node.
+ * A function for each key type must be declared separately. See the custom
+ * parser creation instructions.
*
- * When parsing a key, one may chose to skip it, e.g. because it's not needed
+ * When parsing a key in such function, one may chose to skip it, e.g. because it's not needed
* on the current configuration. In order to ignore a key, you must set
* the "ignore" field of its KeyNode struct to "true": The key and all its children
* will then be automatically ignored by the parser.
*
- * Return true if the key was properly handled (this includes the case when the
- * key is being ignored). False otherwise.
+ * The callback function must return true if the key was properly handled (this includes the case when the
+ * key is being ignored). False otherwise. The return of keyCallback() is the same as
+ * the callback function's.
* See the sample implementation in GUI::ThemeParser.
*/
- virtual bool keyCallback(Common::String keyName) {
- return false;
- }
+ virtual bool keyCallback(ParserNode *node) = 0;
/**
- * The closed key callback function must be overloaded by inheriting classes to
+ * The closed key callback function MAY be overloaded by inheriting classes to
* implement parser-specific functions.
*
* The closedKeyCallback is issued once a key has been finished parsing, to let
* the parser verify that all the required subkeys, etc, were included.
*
+ * Unlike the keyCallbacks(), there's just a closedKeyCallback() for all keys.
+ * Use "node->name" to distinguish between each key type.
+ *
* Returns true if the key was properly closed, false otherwise.
* By default, all keys are properly closed.
*/
- virtual bool closedKeyCallback(Common::String keyName) {
+ virtual bool closedKeyCallback(ParserNode *node) {
return true;
}
+
+ /**
+ * Called when a node is closed. Manages its cleanup and calls the
+ * closing callback function if needed.
+ */
+ bool closeKey();
/**
* Parses the value of a given key. There's no reason to overload this.
*/
- virtual bool parseKeyValue(Common::String keyName);
+ bool parseKeyValue(Common::String keyName);
/**
* Called once a key has been parsed. It handles the closing/cleanup of the
* node stack and calls the keyCallback.
- * There's no reason to overload this.
*/
- virtual bool parseActiveKey(bool closed);
+ bool parseActiveKey(bool closed);
/**
* Prints an error message when parsing fails and stops the parser.
* Parser error always returns "false" so we can pass the return value directly
* and break down the parsing.
*/
- virtual bool parserError(const char *errorString, ...) GCC_PRINTF(2, 3);
+ bool parserError(const char *errorString, ...) GCC_PRINTF(2, 3);
/**
* Skips spaces/whitelines etc. Returns true if any spaces were skipped.
- * Overload this if you want to make your parser depend on newlines or
- * whatever.
*/
- virtual bool skipSpaces() {
+ bool skipSpaces() {
if (!isspace(_text[_pos]))
return false;
@@ -269,13 +519,6 @@ protected:
return true;
}
- if (_text[_pos] == '/' && _text[_pos + 1] == '/') {
- _pos += 2;
- while (_text[_pos] && _text[_pos] != '\n' && _text[_pos] != '\r')
- _pos++;
- return true;
- }
-
return false;
}
@@ -292,12 +535,12 @@ protected:
* Parses a the first textual token found.
* There's no reason to overload this.
*/
- virtual bool parseToken() {
+ bool parseToken() {
_token.clear();
while (isValidNameChar(_text[_pos]))
_token += _text[_pos++];
- return isspace(_text[_pos]) != 0 || _text[_pos] == '>' || _text[_pos] == '=';
+ return isspace(_text[_pos]) != 0 || _text[_pos] == '>' || _text[_pos] == '=' || _text[_pos] == '/';
}
/**
@@ -318,7 +561,7 @@ protected:
* by reference.
* @returns True if the parsing succeeded.
*/
- virtual bool parseIntegerKey(const char *key, int count, ...) {
+ bool parseIntegerKey(const char *key, int count, ...) {
char *parseEnd;
int *num_ptr;
@@ -352,6 +595,9 @@ protected:
*/
virtual void cleanup() {}
+ Common::List<XMLKeyLayout*> _layoutList;
+
+private:
int _pos; /** Current position on the XML buffer. */
XMLStream _text; /** Buffer with the text being parsed */
Common::String _fileName;