diff options
author | Stephen Kennedy | 2008-07-03 10:10:29 +0000 |
---|---|---|
committer | Stephen Kennedy | 2008-07-03 10:10:29 +0000 |
commit | d01594594eed8e1271fa1fe4c23335abb9498a66 (patch) | |
tree | c30c9bc77abca82901724bbaae281b57114421f0 /common | |
parent | 18559708c620b82f05c490e0ff118a02611730dd (diff) | |
download | scummvm-rg350-d01594594eed8e1271fa1fe4c23335abb9498a66.tar.gz scummvm-rg350-d01594594eed8e1271fa1fe4c23335abb9498a66.tar.bz2 scummvm-rg350-d01594594eed8e1271fa1fe4c23335abb9498a66.zip |
First commit:
- changed Rect to derive from Shape and added Polygon class (also derived from Shape)
- added ImageMap class that encapsulates generalised functionality of image maps
- skeletal classes for VirtualKeyboard and VirtualKeyboardParser
svn-id: r32880
Diffstat (limited to 'common')
-rw-r--r-- | common/imageMap.cpp | 48 | ||||
-rw-r--r-- | common/imageMap.h | 78 | ||||
-rw-r--r-- | common/module.mk | 3 | ||||
-rw-r--r-- | common/polygon.cpp | 55 | ||||
-rw-r--r-- | common/polygon.h | 111 | ||||
-rw-r--r-- | common/rect.h | 53 | ||||
-rw-r--r-- | common/shape.h | 104 | ||||
-rw-r--r-- | common/xmlparser.cpp | 257 | ||||
-rw-r--r-- | common/xmlparser.h | 349 |
9 files changed, 1016 insertions, 42 deletions
diff --git a/common/imageMap.cpp b/common/imageMap.cpp new file mode 100644 index 0000000000..7c8498ea06 --- /dev/null +++ b/common/imageMap.cpp @@ -0,0 +1,48 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * $URL$ + * $Id$ + * + */ + +#include "common/imageMap.h" + +namespace Common { + +void ImageMap::addRectMapArea(const Rect& rect, const String& target) { + areas.push_back(MapArea(rect, target)); +} + +void ImageMap::addPolygonMapArea(const Polygon& poly, const String& target) { + areas.push_back(MapArea(poly, target)); +} + +MapArea *ImageMap::findMapArea(int x, int y) { + Array<MapArea>::iterator it; + for (it = areas.begin(); it != areas.end(); it++) { + if (it->contains(x, y)) + return it; + } + return 0; +} + + +} // End of namespace Common diff --git a/common/imageMap.h b/common/imageMap.h new file mode 100644 index 0000000000..4edf511825 --- /dev/null +++ b/common/imageMap.h @@ -0,0 +1,78 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * $URL$ + * $Id$ + * + */ + +#ifndef COMMON_IMAGEMAP_H +#define COMMON_IMAGEMAP_H + +#include "common/array.h" +#include "common/rect.h" +#include "common/polygon.h" + +namespace Common { + +class MapArea { +public: + MapArea() : _shape(0), _target() {} + MapArea(const Rect& r, const String& t) : _target(t) { + _shape = new Rect(r); + } + MapArea(const Polygon& p, const String& t) : _target(t) { + _shape = new Polygon(p); + } + virtual ~MapArea() { + delete _shape; + } + + virtual bool contains(int x, int y) { + return _shape->contains(x, y); + } + + const String& getTarget() { return _target; } + +protected: + /* shape defining the MapArea's boundary */ + Shape *_shape; + /* generalised flags for the area + * TODO: change this */ + String _target; +}; + +class ImageMap { + +public: + + void addRectMapArea(const Rect& rect, const String& target); + void addPolygonMapArea(const Polygon& poly, const String& target); + + MapArea *findMapArea(int x, int y); + +protected: + Array<MapArea> areas; +}; + + +} // End of namespace Common + +#endif diff --git a/common/module.mk b/common/module.mk index c3f2a38c3f..d3b483c8e5 100644 --- a/common/module.mk +++ b/common/module.mk @@ -6,16 +6,19 @@ MODULE_OBJS := \ config-manager.o \ file.o \ fs.o \ + imageMap.o \ hashmap.o \ memorypool.o \ md5.o \ mutex.o \ + polygon.o \ str.o \ stream.o \ util.o \ system.o \ unarj.o \ unzip.o \ + xmlparser.o \ zlib.o # Include common rules diff --git a/common/polygon.cpp b/common/polygon.cpp new file mode 100644 index 0000000000..4a41d127d5 --- /dev/null +++ b/common/polygon.cpp @@ -0,0 +1,55 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * $URL$ + * $Id$ + * + */ + +#include "common/polygon.h" + +namespace Common { + +bool Polygon::contains(int16 x, int16 y) const { + int yflag0; + int yflag1; + bool inside_flag = false; + unsigned int pt; + + const Point *vtx0 = &points[points.size() - 1]; + const Point *vtx1 = &points[0]; + + yflag0 = (vtx0->y >= y); + for (pt = 0; pt < points.size(); pt++, vtx1++) { + yflag1 = (vtx1->y >= y); + if (yflag0 != yflag1) { + if (((vtx1->y - y) * (vtx0->x - vtx1->x) >= + (vtx1->x - x) * (vtx0->y - vtx1->y)) == yflag1) { + inside_flag = !inside_flag; + } + } + yflag0 = yflag1; + vtx0 = vtx1; + } + + return inside_flag; +} + +} // end of namespace Common diff --git a/common/polygon.h b/common/polygon.h new file mode 100644 index 0000000000..af3e2fb900 --- /dev/null +++ b/common/polygon.h @@ -0,0 +1,111 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * $URL$ + * $Id$ + * + */ + +#ifndef COMMON_POLYGON_H +#define COMMON_POLYGON_H + +#include "common/array.h" +#include "common/rect.h" +#include "common/shape.h" + +namespace Common { + +struct Polygon : public Shape { + + Array<Point> points; + + Polygon() {} + Polygon(const Polygon& p) : Shape(), points(p.points), bound(p.bound) {} + Polygon(Array<Point> p) : points(p) { + if (p.empty()) return; + bound = Rect(p[0].x, p[0].y, p[0].x, p[0].y); + for (uint i = 1; i < p.size(); i++) { + bound.extend(Rect(p[i].x, p[i].y, p[i].x, p[i].y)); + } + } + Polygon(Point *p, int n) { + for (int i = 0; i < n; i++) { + addPoint(p[i]); + } + } + virtual ~Polygon() {} + + void addPoint(const Point& p) { + points.push_back(p); + bound.extend(Rect(p.x, p.y, p.x, p.y)); + } + + void addPoint(int16 x, int16 y) { + addPoint(Point(x,y)); + } + + /*! @brief check if given position is inside this polygon + + @param x the horizontal position to check + @param y the vertical position to check + + @return true if the given position is inside this polygon, false otherwise + */ + virtual bool contains(int16 x, int16 y) const; + + /*! @brief check if given point is inside this polygon + + @param p the point to check + + @return true if the given point is inside this polygon, false otherwise + */ + virtual bool contains(const Point &p) const { + return contains(p.x, p.y); + } + + virtual void moveTo(int16 x, int16 y) { + int16 dx = x - ((bound.right + bound.left) / 2); + int16 dy = y - ((bound.bottom + bound.top) / 2); + translate(dx, dy); + } + + virtual void moveTo(const Point &p) { + moveTo(p.x, p.y); + } + + virtual void translate(int16 dx, int16 dy) { + Array<Point>::iterator it; + for (it = points.begin(); it != points.end(); it++) { + it->x += dx; + it->y += dy; + } + } + + virtual Rect getBoundingRect() const { + return bound; + } + +private: + Rect bound; +}; + +} // end of namespace Common + +#endif diff --git a/common/rect.h b/common/rect.h index f71124434a..0cd10a2147 100644 --- a/common/rect.h +++ b/common/rect.h @@ -26,45 +26,10 @@ #ifndef COMMON_RECT_H #define COMMON_RECT_H -#include "common/scummsys.h" -#include "common/util.h" +#include "common/shape.h" namespace Common { -/*! @brief simple class for handling both 2D position and size - - This small class is an helper for position and size values. -*/ -struct Point { - int16 x; //!< The horizontal part of the point - int16 y; //!< The vertical part of the point - - Point() : x(0), y(0) {} - Point(const Point &p) : x(p.x), y(p.y) {} - explicit Point(int16 x1, int16 y1) : x(x1), y(y1) {} - Point & operator=(const Point & p) { x = p.x; y = p.y; return *this; }; - bool operator==(const Point & p) const { return x == p.x && y == p.y; }; - bool operator!=(const Point & p) const { return x != p.x || y != p.y; }; - - /** - * Return the square of the distance between this point and the point p. - * - * @param p the other point - * @return the distance between this and p - */ - uint sqrDist(const Point & p) const { - int diffx = ABS(p.x - x); - if (diffx >= 0x1000) - return 0xFFFFFF; - - int diffy = ABS(p.y - y); - if (diffy >= 0x1000) - return 0xFFFFFF; - - return uint(diffx*diffx + diffy*diffy); - } -}; - /*! @brief simple class for handling a rectangular zone. This small class is an helper for rectangles. @@ -83,7 +48,7 @@ struct Point { When writing code using our Rect class, always keep this principle in mind! */ -struct Rect { +struct Rect : public Shape { int16 top, left; //!< The point at the top left of the rectangle (part of the rect). int16 bottom, right; //!< The point at the bottom right of the rectangle (not part of the rect). @@ -110,7 +75,7 @@ struct Rect { @return true if the given position is inside this rectangle, false otherwise */ - bool contains(int16 x, int16 y) const { + virtual bool contains(int16 x, int16 y) const { return (left <= x) && (x < right) && (top <= y) && (y < bottom); } @@ -120,7 +85,7 @@ struct Rect { @return true if the given point is inside this rectangle, false otherwise */ - bool contains(const Point &p) const { + virtual bool contains(const Point &p) const { return contains(p.x, p.y); } @@ -181,19 +146,19 @@ struct Rect { return (left <= right && top <= bottom); } - void moveTo(int16 x, int16 y) { + virtual void moveTo(int16 x, int16 y) { bottom += y - top; right += x - left; top = y; left = x; } - void translate(int16 dx, int16 dy) { + virtual void translate(int16 dx, int16 dy) { left += dx; right += dx; top += dy; bottom += dy; } - void moveTo(const Point &p) { + virtual void moveTo(const Point &p) { moveTo(p.x, p.y); } @@ -207,6 +172,10 @@ struct Rect { h /= 2; return Rect(cx - w, cy - h, cx + w, cy + h); } + + virtual Rect getBoundingRect() const { + return *this; + } }; } // End of namespace Common diff --git a/common/shape.h b/common/shape.h new file mode 100644 index 0000000000..34df476718 --- /dev/null +++ b/common/shape.h @@ -0,0 +1,104 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * $URL$ + * $Id$ + * + */ + +#ifndef COMMON_SHAPE_H +#define COMMON_SHAPE_H + +#include "common/scummsys.h" +#include "common/util.h" + +namespace Common { + +class Rect; + +/*! @brief simple class for handling both 2D position and size + + This small class is an helper for position and size values. +*/ +struct Point { + int16 x; //!< The horizontal part of the point + int16 y; //!< The vertical part of the point + + Point() : x(0), y(0) {} + Point(const Point &p) : x(p.x), y(p.y) {} + explicit Point(int16 x1, int16 y1) : x(x1), y(y1) {} + Point & operator=(const Point & p) { x = p.x; y = p.y; return *this; }; + bool operator==(const Point & p) const { return x == p.x && y == p.y; }; + bool operator!=(const Point & p) const { return x != p.x || y != p.y; }; + + /** + * Return the square of the distance between this point and the point p. + * + * @param p the other point + * @return the distance between this and p + */ + uint sqrDist(const Point & p) const { + int diffx = ABS(p.x - x); + if (diffx >= 0x1000) + return 0xFFFFFF; + + int diffy = ABS(p.y - y); + if (diffy >= 0x1000) + return 0xFFFFFF; + + return uint(diffx*diffx + diffy*diffy); + } +}; + +/*! @brief simple interface that provides common methods for 2D shapes + +*/ +struct Shape { + + /*! @brief check if given position is inside this shape + + @param x the horizontal position to check + @param y the vertical position to check + + @return true if the given position is inside this shape, false otherwise + */ + virtual bool contains(int16 x, int16 y) const = 0; + + /*! @brief check if given point is inside this shape + + @param p the point to check + + @return true if the given point is inside this shape, false otherwise + */ + virtual bool contains(const Point &p) const = 0; + + virtual void moveTo(int16 x, int16 y) = 0; + + virtual void moveTo(const Point &p) = 0; + + virtual void translate(int16 dx, int16 dy) = 0; + + virtual Rect getBoundingRect() const = 0; + +}; + +} // end of namespace Common + +#endif diff --git a/common/xmlparser.cpp b/common/xmlparser.cpp new file mode 100644 index 0000000000..8ff93a4c59 --- /dev/null +++ b/common/xmlparser.cpp @@ -0,0 +1,257 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * $URL$ + * $Id$ + * + */ + +#include "common/util.h" +#include "common/system.h" +#include "common/events.h" +#include "common/hashmap.h" +#include "common/hash-str.h" +#include "common/xmlparser.h" + +namespace Common { + +using namespace Graphics; + +bool XMLParser::parserError(const char *errorString, ...) { + _state = kParserError; + + int pos = _pos; + 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); + + char lineStr[70]; + _text.stream()->seek(lineStart, SEEK_SET); + _text.stream()->readLine(lineStr, 70); + + printf(" 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); + + int cursor = MIN(_pos - lineStart, 70); + + if (!startFull) + cursor += 3; + + while (cursor--) + printf(" "); + + printf("^\n"); + printf("Parser error: "); + + va_list args; + va_start(args, errorString); + vprintf(errorString, args); + va_end(args); + + printf("\n"); + + return false; +} + +bool XMLParser::parseActiveKey(bool closed) { + bool ignore = false; + + // check if any of the parents must be ignored. + // if a parent is ignored, all children are too. + for (int i = _activeKey.size() - 1; i >= 0; --i) { + if (_activeKey[i]->ignore) + ignore = true; + } + + if (ignore == false && keyCallback(_activeKey.top()->name) == false) { + return false; + } + + if (closed) { + delete _activeKey.pop(); + } + + return true; +} + +bool XMLParser::parseKeyValue(Common::String keyName) { + assert(_activeKey.empty() == false); + + if (_activeKey.top()->values.contains(keyName)) + return false; + + _token.clear(); + char stringStart; + + if (_text[_pos] == '"' || _text[_pos] == '\'') { + stringStart = _text[_pos++]; + + while (_text[_pos] && _text[_pos] != stringStart) + _token += _text[_pos++]; + + if (_text[_pos++] == 0) + return false; + + } else if (!parseToken()) { + return false; + } + + _activeKey.top()->values[keyName] = _token; + return true; +} + +bool XMLParser::parse() { + + if (_text.ready() == false) + return parserError("XML stream not ready for reading."); + + bool activeClosure = false; + bool selfClosure = false; + + _state = kParserNeedKey; + _pos = 0; + _activeKey.clear(); + + while (_text[_pos]) { + if (_state == kParserError) + break; + + if (skipSpaces()) + continue; + + if (skipComments()) + continue; + + switch (_state) { + case kParserNeedKey: + if (_text[_pos++] != '<') { + parserError("Parser expecting key start."); + break; + } + + if (_text[_pos] == 0) { + parserError("Unexpected end of file."); + break; + } + + if (_text[_pos] == '/' && _text[_pos + 1] != '*') { + _pos++; + activeClosure = true; + } + + _state = kParserNeedKeyName; + break; + + case kParserNeedKeyName: + if (!parseToken()) { + parserError("Invalid key name."); + break; + } + + if (activeClosure) { + if (_activeKey.empty() || _token != _activeKey.top()->name) { + parserError("Unexpected closure."); + break; + } + } else { + ParserNode *node = new ParserNode; + node->name = _token; + node->ignore = false; + node->depth = _activeKey.size(); + _activeKey.push(node); + } + + _state = kParserNeedPropertyName; + break; + + case kParserNeedPropertyName: + if (activeClosure) { + activeClosure = false; + delete _activeKey.pop(); + + if (_text[_pos++] != '>') + parserError("Invalid syntax in key closure."); + else + _state = kParserNeedKey; + + break; + } + + selfClosure = (_text[_pos] == '/'); + + if ((selfClosure && _text[_pos + 1] == '>') || _text[_pos] == '>') { + if (parseActiveKey(selfClosure)) { + _pos += selfClosure ? 2 : 1; + _state = kParserNeedKey; + } + break; + } + + if (!parseToken()) + parserError("Error when parsing key value."); + else + _state = kParserNeedPropertyOperator; + + break; + + case kParserNeedPropertyOperator: + if (_text[_pos++] != '=') + parserError("Syntax error after key name."); + else + _state = kParserNeedPropertyValue; + + break; + + case kParserNeedPropertyValue: + if (!parseKeyValue(_token)) + parserError("Invalid key value."); + else + _state = kParserNeedPropertyName; + + break; + + default: + break; + } + } + + if (_state == kParserError) + return false; + + if (_state != kParserNeedKey || !_activeKey.empty()) + return parserError("Unexpected end of file."); + + return true; +} + +} + diff --git a/common/xmlparser.h b/common/xmlparser.h new file mode 100644 index 0000000000..4850dc5113 --- /dev/null +++ b/common/xmlparser.h @@ -0,0 +1,349 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * $URL$ + * $Id$ + * + */ + +#ifndef XML_PARSER_H +#define XML_PARSER_H + +#include "common/scummsys.h" +#include "graphics/surface.h" +#include "common/system.h" +#include "common/xmlparser.h" +#include "common/stream.h" +#include "common/file.h" + +#include "common/hashmap.h" +#include "common/hash-str.h" +#include "common/stack.h" + +namespace Common { + +class XMLStream { +protected: + SeekableReadStream *_stream; + int _pos; + +public: + XMLStream() : _stream(0), _pos(0) {} + + ~XMLStream() { + delete _stream; + } + + SeekableReadStream *stream() { + return _stream; + } + + char operator [](int idx) { + assert(_stream && idx >= 0); + + if (_pos + 1 != idx) + _stream->seek(idx, SEEK_SET); + + _pos = idx; + + return _stream->readSByte(); + } + + void loadStream(SeekableReadStream *s) { + delete _stream; + _stream = s; + } + + bool ready() { + return _stream != 0; + } +}; + +/** + * The base XMLParser class implements generic functionality for parsing + * XML-like files. + * + * In order to use it, it must be inherited with a child class that implements + * the XMLParser::keyCallback() function. + * + * @see XMLParser::keyCallback() + */ +class XMLParser { + /** Maximum depth for nested keys that the parser supports */ + static const int kParserMaxDepth = 4; + +public: + /** + * Parser constructor. + */ + XMLParser() {} + + virtual ~XMLParser() { + while (!_activeKey.empty()) + delete _activeKey.pop(); + } + + /** Active state for the parser */ + enum ParserState { + kParserNeedKey, + kParserNeedKeyName, + + kParserNeedPropertyName, + kParserNeedPropertyOperator, + kParserNeedPropertyValue, + + kParserError + }; + + /** Struct representing a parsed node */ + struct ParserNode { + Common::String name; + Common::StringMap values; + bool ignore; + int depth; + }; + + /** + * Loads a file into the parser. + * Used for the loading of Theme Description files + * straight from the filesystem. + * + * @param filename Name of the file to load. + */ + virtual bool loadFile(Common::String filename) { + Common::File *f = new Common::File; + + if (!f->open(filename, Common::File::kFileReadMode)) + return false; + + _fileName = filename; + _text.loadStream(f); + return true; + } + + /** + * Loads a memory buffer into the parser. + * Used for loading the default theme fallback directly + * from memory if no themes can be found. + * + * @param buffer Pointer to the buffer. + * @param disposable Sets if the XMLParser owns the buffer, + * i.e. if it can be freed safely after it's + * no longer needed by the parser. + */ + virtual bool loadBuffer(const char *buffer, bool disposable = false) { + _text.loadStream(new MemoryReadStream((const byte*)buffer, strlen(buffer), disposable)); + _fileName = "Memory Stream"; + return true; + } + + /** + * The actual parsing function. + * Parses the loaded data stream, returns true if successful. + */ + virtual bool parse(); + + /** + * Returns the active node being parsed (the one on top of + * the node stack). + */ + ParserNode *getActiveNode() { + if (!_activeKey.empty()) + return _activeKey.top(); + + return 0; + } + + /** + * Returns the parent of a given node in the stack. + */ + ParserNode *getParentNode(ParserNode *child) { + return child->depth > 0 ? _activeKey[child->depth - 1] : 0; + } + +protected: + /** + * The keycallback function must be overloaded by inheriting classes + * to implement parser-specific functions. + * + * 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. + * + * 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. + * + * When parsing a key, 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. + * See the sample implementation in GUI::ThemeParser. + */ + virtual bool keyCallback(Common::String keyName) { + return false; + } + + /** + * Parses the value of a given key. There's no reason to overload this. + */ + virtual 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); + + /** + * 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); + + /** + * 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() { + if (!isspace(_text[_pos])) + return false; + + while (_text[_pos] && isspace(_text[_pos])) + _pos++; + + return true; + } + + /** + * Skips comment blocks and comment lines. + * Returns true if any comments were skipped. + * Overload this if you want to disable comments on your XML syntax + * or to change the commenting syntax. + */ + virtual bool skipComments() { + if (_text[_pos] == '/' && _text[_pos + 1] == '*') { + _pos += 2; + while (_text[_pos++]) { + if (_text[_pos - 2] == '*' && _text[_pos - 1] == '/') + break; + if (_text[_pos] == 0) + parserError("Comment has no closure."); + } + return true; + } + + if (_text[_pos] == '/' && _text[_pos + 1] == '/') { + _pos += 2; + while (_text[_pos] && _text[_pos] != '\n' && _text[_pos] != '\r') + _pos++; + return true; + } + + return false; + } + + /** + * Check if a given character can be part of a KEY or VALUE name. + * Overload this if you want to support keys with strange characters + * in their name. + */ + virtual bool isValidNameChar(char c) { + return isalnum(c) || c == '_'; + } + + /** + * Parses a the first textual token found. + * There's no reason to overload this. + */ + virtual bool parseToken() { + _token.clear(); + while (isValidNameChar(_text[_pos])) + _token += _text[_pos++]; + + return isspace(_text[_pos]) != 0 || _text[_pos] == '>'; + } + + /** + * Parses the values inside an integer key. + * The count parameter specifies the number of values inside + * the key, which are expected to be separated with commas. + * + * Sample usage: + * parseIntegerKey("255, 255, 255", 3, &red, &green, &blue); + * [will parse each field into its own integer] + * + * parseIntegerKey("1234", 1, &number); + * [will parse the single number into the variable] + * + * @param key String containing the integers to be parsed. + * @param count Number of comma-separated ints in the string. + * @param ... Integer variables to store the parsed ints, passed + * by reference. + * @returns True if the parsing succeeded. + */ + virtual bool parseIntegerKey(const char *key, int count, ...) { + char *parseEnd; + int *num_ptr; + + va_list args; + va_start(args, count); + + while (count--) { + while (isspace(*key)) + key++; + + num_ptr = va_arg(args, int*); + *num_ptr = strtol(key, &parseEnd, 10); + + key = parseEnd; + + while (isspace(*key)) + key++; + + if (count && *key++ != ',') + return false; + } + + va_end(args); + return (*key == 0); + } + + int _pos; /** Current position on the XML buffer. */ + XMLStream _text; /** Buffer with the text being parsed */ + Common::String _fileName; + + ParserState _state; /** Internal state of the parser */ + + Common::String _error; /** Current error message */ + Common::String _token; /** Current text token */ + + Common::FixedStack<ParserNode*, kParserMaxDepth> _activeKey; /** Node stack of the parsed keys */ +}; + +} + +#endif |