Пример #1
0
 void DefParser::parseProperties(Model::PropertyDefinition::Map& properties, Model::ModelDefinition::List& modelDefinitions, StringList& baseClasses) {
     Token token = m_tokenizer.peekToken();
     if (token.type() == OBrace) {
         token = m_tokenizer.nextToken();
         while (parseProperty(properties, modelDefinitions, baseClasses));
     }
 }
Пример #2
0
Declaration* CssParser::parseDeclaration () {
  Declaration* declaration = NULL;
  TokenList property;

  if (!parseProperty(&property))
    return NULL;
  
  skipWhitespace();

  declaration = new Declaration(property.toString());
  
  if (tokenizer->getTokenType() != Token::COLON) {
    throw new ParseException(tokenizer->getToken()->str,
                             "colon following property(':')");
  }
  tokenizer->readNextToken();
  skipWhitespace();

  TokenList* value = parseValue();
  if (value == NULL) {
    throw new ParseException(tokenizer->getToken()->str,
                             "value for property");
  }
  declaration->setValue(value);
  return declaration;
}
Пример #3
0
UnprocessedStatement* LessParser::parseRulesetStatement (LessRuleset &ruleset) {
  UnprocessedStatement* statement;
  Selector tokens;
  size_t property_i;
  
  while (parseProperty(tokens) || parsePropertyVariable(tokens)) {}
  
  property_i = tokens.size();

  parseWhitespace(tokens);
  parseSelector(tokens);
  tokens.trim();

  if (tokens.empty())
    return NULL;

  statement = ruleset.createUnprocessedStatement();
  
  statement->getTokens()->swap(tokens);
  statement->property_i = property_i;
    
  if (tokenizer->getTokenType() == Token::BRACKET_OPEN) 
    return statement;
  
  parseValue(*statement->getTokens());
  
  if (tokenizer->getTokenType() == Token::DELIMITER) {
    tokenizer->readNextToken();
    skipWhitespace();
  } 
  return statement;
}
Пример #4
0
	void Properties::load(QIODevice *pDevice)
	{
	    const QLatin1Char append_char(msEscapeChar);
	
	    if (!pDevice)
		{
			logger()->warn("No device specified for load.");
			return;
		}
		
		QTextStream stream(pDevice);
		QString line;
		int line_number = 0;
		QString property;
		int property_start_line = 1;
		
		do {
			line = trimLeft(stream.readLine());
			line_number++;
			
			if (!line.isEmpty() && line.at(line.length() - 1) == append_char)
				property += line.left(line.length() - 1);
			else
			{
				property += line;
				parseProperty(property, property_start_line);
				property.clear();
				property_start_line = line_number + 1;
			}
		}
		while (!line.isNull());
	}
Пример #5
0
//-------------------------------------------------------
void coTParser::parseContent()
{
	while (m_currentToken.m_type != coTLexer::EToken_EOF)
	{
		parseProperty();
	}
	coTEST_SILENT(m_currentToken.m_type == coTLexer::EToken_EOF);
}
Пример #6
0
int CTmxPropertyList::parseTmx(TiXmlNode *xmlnPropertiesList)
{
	TiXmlNode *xmlnProperty = xmlnPropertiesList->FirstChild("property");

	while (xmlnProperty) {
		parseProperty(xmlnProperty);
		xmlnProperty = xmlnPropertiesList->IterateChildren("property", xmlnProperty);
	}
	return 0;
}
Пример #7
0
void RSCParse::findProperties()
{
	string::size_type pos = fileTextBuffer->find("__property(", 0);
	string _type, _property;
	while (pos != string::npos) {
		pos += 11;
		if (parseProperty(_type, _property, pos) == true) {
			_Ptr_data->properties.push_back({ _type,_property });
		}
		pos = fileTextBuffer->find("__property(", pos);
	}
}
Пример #8
0
QString SGFParser::loadFile(const QString &fileName)
{
	qDebug("Trying to load file <%s>", fileName.toUtf8().constData());
	
	QFile file(fileName);
	
	if (!file.exists())
	{
        qDebug() << "Could not find file: " << fileName;
		return NULL;
	}
	
	if (!file.open(QIODevice::ReadOnly))
	{
        qDebug() << "Could not open file: " << fileName;
		return NULL;
	}
	
	QTextStream txt(&file);
	stream = &txt;
	if (!setCodec())
	{
        qDebug() << "Invalid text encoding given. Please check preferences!";
		return NULL;
	}
	
	QString toParse;
	int i = 10;
	while (!txt.atEnd() && i--)
		toParse.append(txt.readLine() + "\n");
	QString tmp="";
	if (!parseProperty(toParse, "CA", tmp))		//codec
		return NULL;
	if (!tmp.isEmpty())
	{
		if(!setCodec(tmp))
			return NULL;
		toParse.clear();
		txt.seek(0);
	}
	while (!txt.atEnd())
		toParse.append(txt.readLine() + "\n");
	readCodec = stream->codec();
	file.close();
#ifdef DEBUG_CODEC
	QMessageBox::information(0, "READING", toParse);
#endif
	loadedfromfile = true;		//no need to check the codec later
	return toParse;
}
Пример #9
0
//-------------------------------------------------------
void coTParser::parsePropertyBlock()
{
	coTEST_SILENT(m_currentToken.m_type == coTLexer::EToken_LBRACE);
	consumeToken();

	m_semanticAnalyzer->onEnterPropertyBlock();
	while (m_currentToken.m_type == coTLexer::EToken_RAW_IDENTIFIER)
	{
		parseProperty();
	}

	coTEST_SILENT(m_currentToken.m_type == coTLexer::EToken_RBRACE);
	consumeToken();
	m_semanticAnalyzer->onExitPropertyBlock();
}
Пример #10
0
bool StyleSheet::parse(const QString &content)
{
    int current_index = 0;
    int bracket_begin_index = 0;
    int bracket_end_index = 0;

    while(1) {
        bracket_begin_index = content.indexOf('{',current_index);

        if (bracket_begin_index != -1) {
            bracket_end_index = content.indexOf('}',bracket_begin_index);

            if (bracket_end_index != -1) {
                PropertyBlock *current_block;
                QString unparsed_properties;
                QString unparsed_owners;
                QStringList unparsed_owner_list;
                QStringList unparsed_property_list;

                current_block = new PropertyBlock;

                unparsed_owners = content.mid(current_index, bracket_begin_index - current_index - 1);
                unparsed_properties = content.mid(bracket_begin_index+1, bracket_end_index - bracket_begin_index - 1);

                unparsed_owner_list = unparsed_owners.split(',');
                unparsed_property_list = unparsed_properties.split(';');

                foreach (const QString & unparsed_owner, unparsed_owner_list) {
                    PropertyOwner *new_owner = parseOwner(unparsed_owner.trimmed());
                    if(new_owner)
                    {
                        current_block->ownerList.push_back(new_owner);
                    }
                }

                foreach (const QString & unparsed_property, unparsed_property_list) {
                    Property *new_property = parseProperty(unparsed_property.trimmed());
                    if(new_property)
                    {
                        current_block->propertyList.push_back(new_property);
                    }
                }
Пример #11
0
/**
* EVT interface
*/
int evt_GetPropertyValue(char* apikey, char* thngId, char* propertyName, Property *property)
{
	connect();
	
	char * urlPath = createGetPropertyURLPath(thngId, propertyName);
	char * header = createHeader(apikey);
	
	int responseCode = HTTP_Get(socket, EVRYTHNG_API_HOST, urlPath, header, respHeader, ARRAY_SIZE(respHeader), respBody, ARRAY_SIZE(respBody),200);
	
	if (responseCode == 200)
	{
		parseProperty(property, respBody);
	}

	disconnect();
	free(urlPath);
	free(header);
	
	return responseCode;	
};
Пример #12
0
void AnalyzeTask::parseTrackInfo(QXmlStreamReader &xmlStream, const MI_trackType_t trackType, AudioFileModel &audioFile)
{
	QString coverMimeType;
	while (xmlStream.readNextStartElement())
	{
		const MI_propertyId_t idx = m_mediaInfoIdx.value(qMakePair(trackType, xmlStream.name().toString().simplified().toLower()), MI_propertyId_t(-1));
		if (idx != MI_propertyId_t(-1))
		{
			const QString encoding = findAttribute(QLatin1String("dt"), xmlStream.attributes());
			const QString value = xmlStream.readElementText(QXmlStreamReader::SkipChildElements).simplified();
			if (!value.isEmpty())
			{
				parseProperty(encoding.isEmpty() ? value : decodeStr(value, encoding), idx, audioFile, coverMimeType);
			}
		}
		else
		{
			xmlStream.skipCurrentElement();
		}
	}
}
Пример #13
0
bool SGFParser::initGame(const QString &toParse, const QString &fileName)
{
	QString tmp="";
	GameData *gameData = new GameData;

	// White player name
	if (!parseProperty(toParse, "PW", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->playerWhite = tmp;
	else
		gameData->playerWhite = "White";

	// White player rank
	if (!parseProperty(toParse, "WR", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->rankWhite = tmp;
	else
		gameData->rankWhite = "";

	// Black player name
	if (!parseProperty(toParse, "PB", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->playerBlack = tmp;
	else
		gameData->playerBlack = "Black";
	
	// Black player rank
	if (!parseProperty(toParse, "BR", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->rankBlack = tmp;
	else
		gameData->rankBlack = "";
	
	// Board size
	if (!parseProperty(toParse, "SZ", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->size = tmp.toInt();
	else
		gameData->size = 19;
	
	// Komi
	if (!parseProperty(toParse, "KM", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->komi = tmp.toFloat();
	else
		gameData->komi = 0.0;
	
	// Handicap
	if (!parseProperty(toParse, "HA", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->handicap = tmp.toInt();
	else
		gameData->handicap = 0;
	
	// Result
	if (!parseProperty(toParse, "RE", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->result = tmp;
	else
		gameData->result = "";
	
	// Date
	if (!parseProperty(toParse, "DT", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->date = tmp;
	else
		gameData->date = "";
	
	// Place
	if (!parseProperty(toParse, "PC", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->place = tmp;
	else
		gameData->place = "";
	
	// Copyright
	if (!parseProperty(toParse, "CP", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->copyright = tmp;
	else
		gameData->copyright = "";
	
	// Game Name
	if (!parseProperty(toParse, "GN", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->gameName = tmp;
	else
		gameData->gameName = "";

	// Comments style
	if (!parseProperty(toParse, "ST", tmp))
		return false;
	if (!tmp.isEmpty())
		gameData->style = tmp.toInt();
	else
		gameData->style = 1;

	// Timelimit
	if (!parseProperty(toParse, "TM", tmp))
		return false;
	if (!tmp.isEmpty())
	{
		gameData->timelimit = tmp.toInt();
		gameData->timeSystem = absolute;
	}
	else
	{
		gameData->timelimit = 0;
		gameData->timeSystem = none;
	}

	// Overtime == time system
	if (!parseProperty(toParse, "OT", tmp))
		return false;
	if (!tmp.isEmpty())
	{
		gameData->overtime = tmp;
		if (tmp.contains("byo-yomi"))
		{
			// type: OT[5x30 byo-yomi]
			gameData->timeSystem = byoyomi;
			int pos1, pos2;
			if ((pos1 = tmp.find("x")) != -1)
			{
				pos2 = tmp.find("byo");
				QString time = tmp.mid(pos1+1, pos2-pos1-1);
				gameData->byoTime = time.toInt();
				gameData->byoPeriods = tmp.left(pos1).toInt();
				gameData->byoStones = 0;

				qDebug(QString("byoyomi time system: %1 Periods at %2 seconds").arg(gameData->byoPeriods).arg(gameData->byoTime));
			}
		}
		else if (tmp.contains(":"))
		{
			// type: OT[3:30] = byo-yomi?;
			int pos1;
			gameData->timeSystem = byoyomi;
			if ((pos1 = tmp.find(":")) != -1)
			{
				QString time = tmp.left(pos1);
				int t = time.toInt()*60 + tmp.right(tmp.length() - pos1 - 1).toInt();
				gameData->byoTime = 30;
				gameData->byoPeriods = t/gameData->byoTime;
				gameData->byoStones = 0;

				qDebug(QString("byoyomi time system: %1 Periods at %2 seconds").arg(gameData->byoPeriods).arg(gameData->byoTime));
			}
		}
		else if (tmp.contains("Canadian"))
		{
			// type: OT[25/300 Canadian]
			gameData->timeSystem = canadian;
			int pos1, pos2;
			if ((pos1 = tmp.find("/")) != -1)
			{
				pos2 = tmp.find("Can");
				QString time = tmp.mid(pos1+1, pos2-pos1-1);
				gameData->byoTime = time.toInt();
				gameData->byoStones = tmp.left(pos1).toInt();

				qDebug(QString("Canadian time system: %1 seconds at %2 stones").arg(gameData->byoTime).arg(gameData->byoStones));
			}
		}

		// simple check
		if (gameData->byoStones < 0)
			gameData->byoStones = 0;
		if (gameData->byoTime <= 0)
		{
			gameData->byoTime = 0;
//			gameData->timeSystem = none;
		}
	}
	else
	{
		gameData->overtime = "";
//		gameData->timeSystem = none;
		gameData->byoStones = 0;
	}

	// Game number
	gameData->gameNumber = 0;

	gameData->fileName = fileName;
	
	boardHandler->board->initGame(gameData, true);  // Set sgf flag
	
	return true;
}
Пример #14
0
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
bool BaseRegion::loadBuffer(byte *buffer, bool complete) {
	TOKEN_TABLE_START(commands)
	TOKEN_TABLE(REGION)
	TOKEN_TABLE(TEMPLATE)
	TOKEN_TABLE(NAME)
	TOKEN_TABLE(ACTIVE)
	TOKEN_TABLE(POINT)
	TOKEN_TABLE(CAPTION)
	TOKEN_TABLE(SCRIPT)
	TOKEN_TABLE(EDITOR_SELECTED_POINT)
	TOKEN_TABLE(PROPERTY)
	TOKEN_TABLE_END

	byte *params;
	int cmd;
	BaseParser parser;

	if (complete) {
		if (parser.getCommand((char **)&buffer, commands, (char **)&params) != TOKEN_REGION) {
			_gameRef->LOG(0, "'REGION' keyword expected.");
			return STATUS_FAILED;
		}
		buffer = params;
	}

	for (uint32 i = 0; i < _points.size(); i++) {
		delete _points[i];
	}
	_points.clear();

	while ((cmd = parser.getCommand((char **)&buffer, commands, (char **)&params)) > 0) {
		switch (cmd) {
		case TOKEN_TEMPLATE:
			if (DID_FAIL(loadFile((char *)params))) {
				cmd = PARSERR_GENERIC;
			}
			break;

		case TOKEN_NAME:
			setName((char *)params);
			break;

		case TOKEN_CAPTION:
			setCaption((char *)params);
			break;

		case TOKEN_ACTIVE:
			parser.scanStr((char *)params, "%b", &_active);
			break;

		case TOKEN_POINT: {
			int x, y;
			parser.scanStr((char *)params, "%d,%d", &x, &y);
			_points.add(new BasePoint(x, y));
		}
		break;

		case TOKEN_SCRIPT:
			addScript((char *)params);
			break;

		case TOKEN_EDITOR_SELECTED_POINT:
			parser.scanStr((char *)params, "%d", &_editorSelectedPoint);
			break;

		case TOKEN_PROPERTY:
			parseProperty(params, false);
			break;
		}
	}
	if (cmd == PARSERR_TOKENNOTFOUND) {
		_gameRef->LOG(0, "Syntax error in REGION definition");
		return STATUS_FAILED;
	}

	createRegion();

	return STATUS_OK;
}
Пример #15
0
int main(int argc, char *argv[])
{
    // Get options from the command line
    QApplication a(argc, argv);
    QTextStream qout(stdout);
    if (argc < 2) {
        qout << "Usage: " << argv[0] << " <qmlfile> [outputfolder]";
        return(1);
    }
    // source qml file
    QFileInfo qmlfile(argv[1]);
    if (!qmlfile.exists()) {
        qout << "File not found: " << qmlfile.filePath();
        return (1);
    }
    // output folder
    QFileInfo outputfolder("");
    if (argc == 3) {
        outputfolder.setFile(argv[2]);
        if (!outputfolder.isDir()) {
            qout << "Output folder doesn't exist: " << outputfolder.filePath();
            return (1);
        }
    }

    // Parse the qml file
    QDeclarativeEngine* qmlEngine = new QDeclarativeEngine();
    qmlEngine->addPluginPath("../../imports/com/nokia/symbian"); // component's own imports specified fully so point directly to import folder where dll built to
    //qmlEngine->addImportPath("../../imports");
    QDeclarativeComponent* qmlComponent = new QDeclarativeComponent(qmlEngine, QUrl::fromLocalFile(qmlfile.filePath()));
    if (qmlComponent->isError()) {
        qDebug() << qmlComponent->errors();
        return (1);
        }
    QObject* qmlObject = qmlComponent->create();
    if ( !qmlObject ) {
        qout << "Failed to load: " << qmlfile.path();
        qDebug() << qmlComponent->errors();
        return (1);
    }

    //explicit mapping of Qt types to QML types
    //it's too complicated to scan through the basic types using private headers so hard-coding this
    QMap<QString,QString> qmlBasicType;
    qmlBasicType.insert("QAction",                      "action");
    qmlBasicType.insert("bool",                         "bool");
    qmlBasicType.insert("QColor",                       "color");
    qmlBasicType.insert("QDateTime",                    "date");
    qmlBasicType.insert("double",                       "double");
    qmlBasicType.insert("enumeration",                  "enumeration");
    qmlBasicType.insert("QFont",                        "font");
    qmlBasicType.insert("int",                          "int");
    qmlBasicType.insert("ListProperty",                 "list");
    qmlBasicType.insert("QPointF",                      "point");
    qmlBasicType.insert("qreal",                        "real");
    qmlBasicType.insert("QRectF",                       "rect");
    qmlBasicType.insert("QSize",                        "size");
    qmlBasicType.insert("QString",                      "string");
    qmlBasicType.insert("QDateTime",                    "time"); //Duplicate...
    qmlBasicType.insert("QUrl",                         "url");
    qmlBasicType.insert("QVariant",                     "variant");
    qmlBasicType.insert("TransformOrigin",              "enumeration");
    qmlBasicType.insert("QVector3d",                    "vector3d");
    qmlBasicType.insert("QGraphicsObject",              "Item");
    qmlBasicType.insert("SStyleWrapper",                "style");
    qmlBasicType.insert("QObject",                      "QtObject");
    qmlBasicType.insert("QValidator",                   "validator");
    qmlBasicType.insert("SDeclarativeImplicitSizeItem", "Item");
    qmlBasicType.insert("ListProperty<QObject>",        "list<QtObject>");
    qmlBasicType.insert("ListProperty<QGraphicsObject>","list<Item>");


    // Get the component name and remove the _QMLTYPE part
    QString componentname(qmlObject->metaObject()->className());
    componentname =  componentname.left(componentname.indexOf("_QML"));

    QStringList memberlist;

    // Collect all the properties (excluding inherited)
    for(int i = qmlObject->metaObject()->propertyOffset() ; i < qmlObject->metaObject()->propertyCount(); ++i) {
        memberlist.append(parseProperty(&qmlObject->metaObject()->property(i),qmlBasicType,componentname));
    }

    // Collect all the methods (excluding inherited)
    for(int i = qmlObject->metaObject()->methodOffset() ; i < qmlObject->metaObject()->methodCount(); ++i) {
        memberlist.append(parseMethod(&qmlObject->metaObject()->method(i),qmlBasicType,componentname));
    }

    // Output the results
    memberlist.sort();
    if (outputfolder.exists()) { // output to file
        QFile outputfile(outputfolder.filePath() + "/" + componentname.toLower() + ".txt");
        if (outputfile.open(QFile::WriteOnly)) {
            QTextStream fout(&outputfile);
            for (int i=0; i<memberlist.size();i++) {
                if (memberlist.at(i) != QString::null)
                    fout << memberlist.at(i) << "\n";
            }
        }
        else {
            qout << "Failed to open: " << outputfile.fileName();
            return(1);
        }
        outputfile.close();
    }
    else { // output to console
        for (int i=0; i<memberlist.size();i++) {
            if (memberlist.at(i) != QString::null)
                qout << memberlist.at(i) << "\n";
        }
    }

}
Пример #16
0
void Moc::parse()
{
    QList<NamespaceDef> namespaceList;
    bool templateClass = false;
    while (hasNext()) {
        Token t = next();
        switch (t) {
            case NAMESPACE: {
                int rewind = index;
                if (test(IDENTIFIER)) {
                    if (test(EQ)) {
                        // namespace Foo = Bar::Baz;
                        until(SEMIC);
                    } else if (!test(SEMIC)) {
                        NamespaceDef def;
                        def.name = lexem();
                        next(LBRACE);
                        def.begin = index - 1;
                        until(RBRACE);
                        def.end = index;
                        index = def.begin + 1;
                        namespaceList += def;
                        index = rewind;
                    }
                }
                break;
            }
            case SEMIC:
            case RBRACE:
                templateClass = false;
                break;
            case TEMPLATE:
                templateClass = true;
                break;
            case MOC_INCLUDE_BEGIN:
                currentFilenames.push(symbol().unquotedLexem());
                break;
            case MOC_INCLUDE_END:
                currentFilenames.pop();
                break;
            case Q_DECLARE_INTERFACE_TOKEN:
                parseDeclareInterface();
                break;
            case Q_DECLARE_METATYPE_TOKEN:
                parseDeclareMetatype();
                break;
            case USING:
                if (test(NAMESPACE)) {
                    while (test(SCOPE) || test(IDENTIFIER))
                        ;
                    next(SEMIC);
                }
                break;
            case CLASS:
            case STRUCT: {
                if (currentFilenames.size() <= 1)
                    break;

                ClassDef def;
                if (!parseClassHead(&def))
                    continue;

                while (inClass(&def) && hasNext()) {
                    if (next() == Q_OBJECT_TOKEN) {
                        def.hasQObject = true;
                        break;
                    }
                }

                if (!def.hasQObject)
                    continue;

                for (int i = namespaceList.size() - 1; i >= 0; --i)
                    if (inNamespace(&namespaceList.at(i)))
                        def.qualified.prepend(namespaceList.at(i).name + "::");

                knownQObjectClasses.insert(def.classname);
                knownQObjectClasses.insert(def.qualified);

                continue; }
            default: break;
        }
        if ((t != CLASS && t != STRUCT)|| currentFilenames.size() > 1)
            continue;
        ClassDef def;
        if (parseClassHead(&def)) {
            FunctionDef::Access access = FunctionDef::Private;
            for (int i = namespaceList.size() - 1; i >= 0; --i)
                if (inNamespace(&namespaceList.at(i)))
                    def.qualified.prepend(namespaceList.at(i).name + "::");
            while (inClass(&def) && hasNext()) {
                switch ((t = next())) {
                case PRIVATE:
                    access = FunctionDef::Private;
                    if (test(Q_SIGNALS_TOKEN))
                        error("Signals cannot have access specifier");
                    break;
                case PROTECTED:
                    access = FunctionDef::Protected;
                    if (test(Q_SIGNALS_TOKEN))
                        error("Signals cannot have access specifier");
                    break;
                case PUBLIC:
                    access = FunctionDef::Public;
                    if (test(Q_SIGNALS_TOKEN))
                        error("Signals cannot have access specifier");
                    break;
                case CLASS: {
                    ClassDef nestedDef;
                    if (parseClassHead(&nestedDef)) {
                        while (inClass(&nestedDef) && inClass(&def)) {
                            t = next();
                            if (t >= Q_META_TOKEN_BEGIN && t < Q_META_TOKEN_END)
                                error("Meta object features not supported for nested classes");
                        }
                    }
                } break;
                case Q_SIGNALS_TOKEN:
                    parseSignals(&def);
                    break;
                case Q_SLOTS_TOKEN:
                    switch (lookup(-1)) {
                    case PUBLIC:
                    case PROTECTED:
                    case PRIVATE:
                        parseSlots(&def, access);
                        break;
                    default:
                        error("Missing access specifier for slots");
                    }
                    break;
                case Q_OBJECT_TOKEN:
                    def.hasQObject = true;
                    if (templateClass)
                        error("Template classes not supported by Q_OBJECT");
                    if (def.classname != "Qt" && def.classname != "QObject" && def.superclassList.isEmpty())
                        error("Class contains Q_OBJECT macro but does not inherit from QObject");
                    break;
                case Q_GADGET_TOKEN:
                    def.hasQGadget = true;
                    if (templateClass)
                        error("Template classes not supported by Q_GADGET");
                    break;
                case Q_PROPERTY_TOKEN:
                    parseProperty(&def);
                    break;
                case Q_ENUMS_TOKEN:
                    parseEnumOrFlag(&def, false);
                    break;
                case Q_FLAGS_TOKEN:
                    parseEnumOrFlag(&def, true);
                    break;
                case Q_DECLARE_FLAGS_TOKEN:
                    parseFlag(&def);
                    break;
                case Q_CLASSINFO_TOKEN:
                    parseClassInfo(&def);
                    break;
                case Q_INTERFACES_TOKEN:
                    parseInterfaces(&def);
                    break;
                case Q_PRIVATE_SLOT_TOKEN:
                    parseSlotInPrivate(&def, access);
                    break;
                case Q_PRIVATE_PROPERTY_TOKEN:
                    parsePrivateProperty(&def);
                    break;
                case ENUM: {
                    EnumDef enumDef;
                    if (parseEnum(&enumDef))
                        def.enumList += enumDef;
                } break;
                default:
                    FunctionDef funcDef;
                    funcDef.access = access;
                    int rewind = index;
                    if (parseMaybeFunction(&def, &funcDef)) {
                        if (funcDef.isConstructor) {
                            if ((access == FunctionDef::Public) && funcDef.isInvokable) {
                                def.constructorList += funcDef;
                                while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
                                    funcDef.wasCloned = true;
                                    funcDef.arguments.removeLast();
                                    def.constructorList += funcDef;
                                }
                            }
                        } else if (funcDef.isDestructor) {
                            // don't care about destructors
                        } else {
                            if (access == FunctionDef::Public)
                                def.publicList += funcDef;
                            if (funcDef.isSlot) {
                                def.slotList += funcDef;
                                while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
                                    funcDef.wasCloned = true;
                                    funcDef.arguments.removeLast();
                                    def.slotList += funcDef;
                                }
                            } else if (funcDef.isSignal) {
                                def.signalList += funcDef;
                                while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
                                    funcDef.wasCloned = true;
                                    funcDef.arguments.removeLast();
                                    def.signalList += funcDef;
                                }
                            } else if (funcDef.isInvokable) {
                                def.methodList += funcDef;
                                while (funcDef.arguments.size() > 0 && funcDef.arguments.last().isDefault) {
                                    funcDef.wasCloned = true;
                                    funcDef.arguments.removeLast();
                                    def.methodList += funcDef;
                                }
                            }
                        }
                    } else {
                        index = rewind;
                    }
                }
            }

            next(RBRACE);

            if (!def.hasQObject && !def.hasQGadget && def.signalList.isEmpty() && def.slotList.isEmpty()
                && def.propertyList.isEmpty() && def.enumDeclarations.isEmpty())
                continue; // no meta object code required


            if (!def.hasQObject && !def.hasQGadget)
                error("Class declarations lacks Q_OBJECT macro.");

            checkSuperClasses(&def);
            checkProperties(&def);

            classList += def;
            knownQObjectClasses.insert(def.classname);
            knownQObjectClasses.insert(def.qualified);
        }
    }
}
Пример #17
0
GameData * SGFParser::initGame(const QString &toParse, const QString &fileName)
{
	QString tmp="";
	GameData *gameData = new GameData;

	if (!parseProperty(toParse, "CA", tmp))		//codec
		return NULL;
	if (!tmp.isEmpty())
		gameData->codec = tmp;
	else
		gameData->codec = QString();
	//probably should either be Latin1 or some default codec from somewhere FIXME
		
	// White player name
	if (!parseProperty(toParse, "PW", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->white_name = tmp;
	else
		gameData->white_name = "White";

	// White player rank
	if (!parseProperty(toParse, "WR", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->white_rank = tmp;
	else
		gameData->white_rank = "";

	// Black player name
	if (!parseProperty(toParse, "PB", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->black_name = tmp;
	else
		gameData->black_name = "Black";
	
	// Black player rank
	if (!parseProperty(toParse, "BR", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->black_rank = tmp;
	else
		gameData->black_rank = "";
	
	// Board size
	if (!parseProperty(toParse, "SZ", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->board_size = tmp.toInt();
	else
		gameData->board_size = 19;
	
	// Komi
	if (!parseProperty(toParse, "KM", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->komi = tmp.toFloat();
	else
		gameData->komi = 0.0;
	
	// Handicap
	if (!parseProperty(toParse, "HA", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->handicap = tmp.toInt();
	else
		gameData->handicap = 0;
	
	// Result
	if (!parseProperty(toParse, "RE", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->result = tmp;
	else
		gameData->result = "";
	
	// Date
	if (!parseProperty(toParse, "DT", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->date = tmp;
	else
		gameData->date = "";
	
	// Place
	if (!parseProperty(toParse, "PC", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->place = tmp;
	else
		gameData->place = "";
	
	// Copyright
	if (!parseProperty(toParse, "CP", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->copyright = tmp;
	else
		gameData->copyright = "";
	
	// Game Name
	if (!parseProperty(toParse, "GN", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->gameName = tmp;
	else
		gameData->gameName = "";

	// Comments style
	if (!parseProperty(toParse, "ST", tmp))
        return NULL;
	if (!tmp.isEmpty())
		gameData->style = tmp.toInt();
	else
		gameData->style = 1;

	// Timelimit
	if (!parseProperty(toParse, "TM", tmp))
        return NULL;
	if (!tmp.isEmpty())
	{
		gameData->timelimit = tmp.toInt();
		gameData->timeSystem = absolute;
	}
	else
	{
		gameData->timelimit = 0;
		gameData->timeSystem = none;
	}

	// Overtime == time system
	if (!parseProperty(toParse, "OT", tmp))
        return NULL;
	if (!tmp.isEmpty())
	{
		gameData->overtime = tmp;
		if (tmp.contains("byo-yomi"))
		{
			// type: OT[5x30 byo-yomi]
			gameData->timeSystem = byoyomi;
			int pos1, pos2;
			if ((pos1 = tmp.indexOf("x")) != -1)
			{
				pos2 = tmp.indexOf("byo");
				QString time = tmp.mid(pos1+1, pos2-pos1-1);
				/*gameData->byoTime = time.toInt();
				gameData->byoPeriods = tmp.left(pos1).toInt();
				gameData->byoStones = 0;*/
				//FIXME okay?
				gameData->periodtime = time.toInt();
				gameData->stones_periods = tmp.left(pos1).toInt();
#ifdef FIXME
				qDebug(QString("byoyomi time system: %1 Periods at %2 seconds").arg(gameData->stones_periods).arg(gameData->periodtime).toLatin1().constData());
#endif //FIXME
			}
		}
		else if (tmp.contains(":"))
		{
			// type: OT[3:30] = byo-yomi?;
			int pos1;
			gameData->timeSystem = byoyomi;
			if ((pos1 = tmp.indexOf(":")) != -1)
			{
				QString time = tmp.left(pos1);
				int t = time.toInt()*60 + tmp.right(tmp.length() - pos1 - 1).toInt();
				gameData->periodtime = 30;
				gameData->stones_periods = t/gameData->periodtime;
				//gameData->byoStones = 0;

////////////////////FIXME	qDebug(QString("byoyomi time system: %1 Periods at %2 seconds").arg(gameData->byoPeriods).arg(gameData->byoTime));
			}
		}
		else if (tmp.contains("Canadian"))
		{
			// type: OT[25/300 Canadian]
			gameData->timeSystem = canadian;
			int pos1, pos2;
			if ((pos1 = tmp.indexOf("/")) != -1)
			{
				pos2 = tmp.indexOf("Can");
				QString time = tmp.mid(pos1+1, pos2-pos1-1);
				gameData->periodtime = time.toInt();
				gameData->stones_periods = tmp.left(pos1).toInt();

///////////////////////				qDebug(QString("Canadian time system: %1 seconds at %2 stones").arg(gameData->byoTime).arg(gameData->byoStones));
			}
		}

		// simple check
		if (gameData->stones_periods < 0)
			gameData->stones_periods = 0;
		if (gameData->periodtime <= 0)
		{
			gameData->periodtime = 0;
//			gameData->timeSystem = none;
		}
	}
	else
	{
		gameData->overtime = "";
//		gameData->timeSystem = none;
		gameData->stones_periods = 0;
	}

	// Game number
	gameData->number = 0;

	gameData->fileName = fileName;
	
//	boardHandler->board->initGame(gameData, true);  // Set sgf flag
	
	return gameData ;
}
Пример #18
0
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
bool AdActor::loadBuffer(byte *buffer, bool complete) {
	TOKEN_TABLE_START(commands)
	TOKEN_TABLE(ACTOR)
	TOKEN_TABLE(X)
	TOKEN_TABLE(Y)
	TOKEN_TABLE(TEMPLATE)
	TOKEN_TABLE(NAME)
	TOKEN_TABLE(SCALABLE)
	TOKEN_TABLE(REGISTRABLE)
	TOKEN_TABLE(INTERACTIVE)
	TOKEN_TABLE(SHADOWABLE)
	TOKEN_TABLE(COLORABLE)
	TOKEN_TABLE(ACTIVE)
	TOKEN_TABLE(WALK)
	TOKEN_TABLE(STAND)
	TOKEN_TABLE(TALK_SPECIAL)
	TOKEN_TABLE(TALK)
	TOKEN_TABLE(TURN_LEFT)
	TOKEN_TABLE(TURN_RIGHT)
	TOKEN_TABLE(EVENTS)
	TOKEN_TABLE(FONT)
	TOKEN_TABLE(CURSOR)
	TOKEN_TABLE(SCRIPT)
	TOKEN_TABLE(SOUND_VOLUME)
	TOKEN_TABLE(SOUND_PANNING)
	TOKEN_TABLE(CAPTION)
	TOKEN_TABLE(PROPERTY)
	TOKEN_TABLE(BLOCKED_REGION)
	TOKEN_TABLE(WAYPOINTS)
	TOKEN_TABLE(IGNORE_ITEMS)
	TOKEN_TABLE(ROTABLE)
	TOKEN_TABLE(ROTATABLE)
	TOKEN_TABLE(ALPHA_COLOR)
	TOKEN_TABLE(SCALE)
	TOKEN_TABLE(RELATIVE_SCALE)
	TOKEN_TABLE(ALPHA)
	TOKEN_TABLE(EDITOR_PROPERTY)
	TOKEN_TABLE(ANIMATION)
	TOKEN_TABLE_END

	byte *params;
	int cmd;
	BaseParser parser;

	if (complete) {
		if (parser.getCommand((char **)&buffer, commands, (char **)&params) != TOKEN_ACTOR) {
			_gameRef->LOG(0, "'ACTOR' keyword expected.");
			return STATUS_FAILED;
		}
		buffer = params;
	}

	AdGame *adGame = (AdGame *)_gameRef;
	AdSpriteSet *spr = nullptr;
	int ar = 0, ag = 0, ab = 0, alpha = 0;
	while ((cmd = parser.getCommand((char **)&buffer, commands, (char **)&params)) > 0) {
		switch (cmd) {
		case TOKEN_TEMPLATE:
			if (DID_FAIL(loadFile((char *)params))) {
				cmd = PARSERR_GENERIC;
			}
			break;

		case TOKEN_X:
			parser.scanStr((char *)params, "%d", &_posX);
			break;

		case TOKEN_Y:
			parser.scanStr((char *)params, "%d", &_posY);
			break;

		case TOKEN_NAME:
			setName((char *)params);
			break;

		case TOKEN_CAPTION:
			setCaption((char *)params);
			break;

		case TOKEN_FONT:
			setFont((char *)params);
			break;

		case TOKEN_SCALABLE:
			parser.scanStr((char *)params, "%b", &_zoomable);
			break;

		case TOKEN_ROTABLE:
		case TOKEN_ROTATABLE:
			parser.scanStr((char *)params, "%b", &_rotatable);
			break;

		case TOKEN_REGISTRABLE:
		case TOKEN_INTERACTIVE:
			parser.scanStr((char *)params, "%b", &_registrable);
			break;

		case TOKEN_SHADOWABLE:
		case TOKEN_COLORABLE:
			parser.scanStr((char *)params, "%b", &_shadowable);
			break;

		case TOKEN_ACTIVE:
			parser.scanStr((char *)params, "%b", &_active);
			break;

		case TOKEN_WALK:
			delete _walkSprite;
			_walkSprite = nullptr;
			spr = new AdSpriteSet(_gameRef, this);
			if (!spr || DID_FAIL(spr->loadBuffer(params, true, adGame->_texWalkLifeTime, CACHE_HALF))) {
				cmd = PARSERR_GENERIC;
			} else {
				_walkSprite = spr;
			}
			break;

		case TOKEN_TALK:
			spr = new AdSpriteSet(_gameRef, this);
			if (!spr || DID_FAIL(spr->loadBuffer(params, true, adGame->_texTalkLifeTime))) {
				cmd = PARSERR_GENERIC;
			} else {
				_talkSprites.add(spr);
			}
			break;

		case TOKEN_TALK_SPECIAL:
			spr = new AdSpriteSet(_gameRef, this);
			if (!spr || DID_FAIL(spr->loadBuffer(params, true, adGame->_texTalkLifeTime))) {
				cmd = PARSERR_GENERIC;
			} else {
				_talkSpritesEx.add(spr);
			}
			break;

		case TOKEN_STAND:
			delete _standSprite;
			_standSprite = nullptr;
			spr = new AdSpriteSet(_gameRef, this);
			if (!spr || DID_FAIL(spr->loadBuffer(params, true, adGame->_texStandLifeTime))) {
				cmd = PARSERR_GENERIC;
			} else {
				_standSprite = spr;
			}
			break;

		case TOKEN_TURN_LEFT:
			delete _turnLeftSprite;
			_turnLeftSprite = nullptr;
			spr = new AdSpriteSet(_gameRef, this);
			if (!spr || DID_FAIL(spr->loadBuffer(params, true))) {
				cmd = PARSERR_GENERIC;
			} else {
				_turnLeftSprite = spr;
			}
			break;

		case TOKEN_TURN_RIGHT:
			delete _turnRightSprite;
			_turnRightSprite = nullptr;
			spr = new AdSpriteSet(_gameRef, this);
			if (!spr || DID_FAIL(spr->loadBuffer(params, true))) {
				cmd = PARSERR_GENERIC;
			} else {
				_turnRightSprite = spr;
			}
			break;

		case TOKEN_SCRIPT:
			addScript((char *)params);
			break;

		case TOKEN_CURSOR:
			delete _cursor;
			_cursor = new BaseSprite(_gameRef);
			if (!_cursor || DID_FAIL(_cursor->loadFile((char *)params))) {
				delete _cursor;
				_cursor = nullptr;
				cmd = PARSERR_GENERIC;
			}
			break;

		case TOKEN_SOUND_VOLUME:
			parser.scanStr((char *)params, "%d", &_sFXVolume);
			break;

		case TOKEN_SCALE: {
			int s;
			parser.scanStr((char *)params, "%d", &s);
			_scale = (float)s;

		}
		break;

		case TOKEN_RELATIVE_SCALE: {
			int s;
			parser.scanStr((char *)params, "%d", &s);
			_relativeScale = (float)s;

		}
		break;

		case TOKEN_SOUND_PANNING:
			parser.scanStr((char *)params, "%b", &_autoSoundPanning);
			break;

		case TOKEN_PROPERTY:
			parseProperty(params, false);
			break;

		case TOKEN_BLOCKED_REGION: {
			delete _blockRegion;
			delete _currentBlockRegion;
			_blockRegion = nullptr;
			_currentBlockRegion = nullptr;
			BaseRegion *rgn = new BaseRegion(_gameRef);
			BaseRegion *crgn = new BaseRegion(_gameRef);
			if (!rgn || !crgn || DID_FAIL(rgn->loadBuffer(params, false))) {
				delete _blockRegion;
				delete _currentBlockRegion;
				_blockRegion = nullptr;
				_currentBlockRegion = nullptr;
				cmd = PARSERR_GENERIC;
			} else {
				_blockRegion = rgn;
				_currentBlockRegion = crgn;
				_currentBlockRegion->mimic(_blockRegion);
			}
		}
		break;

		case TOKEN_WAYPOINTS: {
			delete _wptGroup;
			delete _currentWptGroup;
			_wptGroup = nullptr;
			_currentWptGroup = nullptr;
			AdWaypointGroup *wpt = new AdWaypointGroup(_gameRef);
			AdWaypointGroup *cwpt = new AdWaypointGroup(_gameRef);
			if (!wpt || !cwpt || DID_FAIL(wpt->loadBuffer(params, false))) {
				delete _wptGroup;
				delete _currentWptGroup;
				_wptGroup = nullptr;
				_currentWptGroup = nullptr;
				cmd = PARSERR_GENERIC;
			} else {
				_wptGroup = wpt;
				_currentWptGroup = cwpt;
				_currentWptGroup->mimic(_wptGroup);
			}
		}
		break;

		case TOKEN_IGNORE_ITEMS:
			parser.scanStr((char *)params, "%b", &_ignoreItems);
			break;

		case TOKEN_ALPHA_COLOR:
			parser.scanStr((char *)params, "%d,%d,%d", &ar, &ag, &ab);
			break;

		case TOKEN_ALPHA:
			parser.scanStr((char *)params, "%d", &alpha);
			break;

		case TOKEN_EDITOR_PROPERTY:
			parseEditorProperty(params, false);
			break;

		case TOKEN_ANIMATION: {
			AdSpriteSet *anim = new AdSpriteSet(_gameRef, this);
			if (!anim || DID_FAIL(anim->loadBuffer(params, false))) {
				cmd = PARSERR_GENERIC;
			} else {
				_anims.add(anim);
			}
		}
		break;
		}
	}
	if (cmd == PARSERR_TOKENNOTFOUND) {
		_gameRef->LOG(0, "Syntax error in ACTOR definition");
		return STATUS_FAILED;
	}
	if (cmd == PARSERR_GENERIC) {
		if (spr) {
			delete spr;
		}
		_gameRef->LOG(0, "Error loading ACTOR definition");
		return STATUS_FAILED;
	}

	if (alpha != 0 && ar == 0 && ag == 0 && ab == 0) {
		ar = ag = ab = 255;
	}
	_alphaColor = BYTETORGBA(ar, ag, ab, alpha);
	_state = _nextState = STATE_READY;

	return STATUS_OK;
}
Пример #19
0
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
bool AdRegion::loadBuffer(byte *buffer, bool complete) {
	TOKEN_TABLE_START(commands)
	TOKEN_TABLE(REGION)
	TOKEN_TABLE(TEMPLATE)
	TOKEN_TABLE(NAME)
	TOKEN_TABLE(ACTIVE)
	TOKEN_TABLE(ZOOM)
	TOKEN_TABLE(SCALE)
	TOKEN_TABLE(BLOCKED)
	TOKEN_TABLE(DECORATION)
	TOKEN_TABLE(POINT)
	TOKEN_TABLE(ALPHA_COLOR)
	TOKEN_TABLE(ALPHA)
	TOKEN_TABLE(EDITOR_SELECTED_POINT)
	TOKEN_TABLE(EDITOR_SELECTED)
	TOKEN_TABLE(SCRIPT)
	TOKEN_TABLE(CAPTION)
	TOKEN_TABLE(PROPERTY)
	TOKEN_TABLE(EDITOR_PROPERTY)
	TOKEN_TABLE_END

	byte *params;
	int cmd;
	BaseParser parser;

	if (complete) {
		if (parser.getCommand((char **)&buffer, commands, (char **)&params) != TOKEN_REGION) {
			_gameRef->LOG(0, "'REGION' keyword expected.");
			return STATUS_FAILED;
		}
		buffer = params;
	}

	for (uint32 i = 0; i < _points.size(); i++) {
		delete _points[i];
	}
	_points.clear();

	int ar = 255, ag = 255, ab = 255, alpha = 255;

	while ((cmd = parser.getCommand((char **)&buffer, commands, (char **)&params)) > 0) {
		switch (cmd) {
		case TOKEN_TEMPLATE:
			if (DID_FAIL(loadFile((char *)params))) {
				cmd = PARSERR_GENERIC;
			}
			break;

		case TOKEN_NAME:
			setName((char *)params);
			break;

		case TOKEN_CAPTION:
			setCaption((char *)params);
			break;

		case TOKEN_ACTIVE:
			parser.scanStr((char *)params, "%b", &_active);
			break;

		case TOKEN_BLOCKED:
			parser.scanStr((char *)params, "%b", &_blocked);
			break;

		case TOKEN_DECORATION:
			parser.scanStr((char *)params, "%b", &_decoration);
			break;

		case TOKEN_ZOOM:
		case TOKEN_SCALE: {
			int j;
			parser.scanStr((char *)params, "%d", &j);
			_zoom = (float)j;
		}
		break;

		case TOKEN_POINT: {
			int x, y;
			parser.scanStr((char *)params, "%d,%d", &x, &y);
			_points.add(new BasePoint(x, y));
		}
		break;

		case TOKEN_ALPHA_COLOR:
			parser.scanStr((char *)params, "%d,%d,%d", &ar, &ag, &ab);
			break;

		case TOKEN_ALPHA:
			parser.scanStr((char *)params, "%d", &alpha);
			break;

		case TOKEN_EDITOR_SELECTED:
			parser.scanStr((char *)params, "%b", &_editorSelected);
			break;

		case TOKEN_EDITOR_SELECTED_POINT:
			parser.scanStr((char *)params, "%d", &_editorSelectedPoint);
			break;

		case TOKEN_SCRIPT:
			addScript((char *)params);
			break;

		case TOKEN_PROPERTY:
			parseProperty(params, false);
			break;

		case TOKEN_EDITOR_PROPERTY:
			parseEditorProperty(params, false);
			break;
		}
	}
	if (cmd == PARSERR_TOKENNOTFOUND) {
		_gameRef->LOG(0, "Syntax error in REGION definition");
		return STATUS_FAILED;
	}

	createRegion();

	_alpha = BYTETORGBA(ar, ag, ab, alpha);

	return STATUS_OK;
}
Пример #20
0
bool SGFParser::doParse(const QString &toParseStr)
{
	if (toParseStr.isNull() || toParseStr.isEmpty())
	{
		qWarning("Failed loading from file. Is it empty?");
		return false;
	}
	QString tmp;

	if(!loadedfromfile)
	{
		/* This bit of ugliness is because sgfs are used to duplicate boards as well
		 * as load from file FIXME */
		parseProperty(toParseStr, "CA", tmp);		//codec
		if (!tmp.isEmpty())
			readCodec = QTextCodec::codecForName(tmp.toLatin1().constData());
	}
	
	const MyString *toParse = NULL;

//////TODO	if (static_cast<Codec>(setting->readIntEntry("CODEC")) == codecNone)
/////////		toParse = new MySimpleString(toParseStr);
///////	else
		toParse = new MyString(toParseStr);

	Q_CHECK_PTR(toParse);
	
	int 	pos = 0,
		posVarBegin = 0,
		posVarEnd = 0,
		posNode = 0,
		moves = 0,
		i, x=-1, y=-1;

	int 	a_offset = QChar::fromLatin1('a').unicode() - 1 ;

	unsigned int pointer = 0,
		strLength = toParse->length();
	bool black = true,
		setup = false,
        old_label = false;
	isRoot = true;
	bool remember_root;
	QString unknownProperty;
	State state;
	MarkType markType;
	QString moveStr, commentStr;
	Position *position;
	MoveNum *moveNum;
	QStack<Move*> stack;
	QStack<MoveNum*> movesStack;
	/* FIXME toRemove, et., al., appears unused Remove it */
	QStack<Position*> toRemove;
/*
////TODO	stack.setAutoDelete(false);
	movesStack.setAutoDelete(true);
	toRemove.setAutoDelete(true);
*/
	// Initialises the tree with board size
	parseProperty(toParseStr, "SZ", tmp);
//	Tree *tree = new Tree(tmp.isEmpty() ? 19 : tmp.toInt()) ;// boardHandler->getTree();
	
	state = stateVarBegin;
	
	bool cancel = false;
    //FIXME abort does nothing!!
	
	// qDebug("File length = %d", strLength);
	
    tree->setLoadingSGF(true);
	
	QString sss="";
    do {
		posVarBegin = toParse->find('(', pointer);
		posVarEnd = toParse->find(')', pointer);
		posNode = toParse->find(';', pointer);
		
		pos = minPos(posVarBegin, posVarEnd, posNode);

		// Switch states

		// Node -> VarEnd
		if (state == stateNode && pos == posVarEnd)
			state = stateVarEnd;
		
		// Node -> VarBegin
		if (state == stateNode && pos == posVarBegin)
			state = stateVarBegin;
		
		// VarBegin -> Node
		else if (state == stateVarBegin && pos == posNode)
			state = stateNode;
		
		// VarEnd -> VarBegin
		else if (state == stateVarEnd && pos == posVarBegin)
			state = stateVarBegin;
		
		// qDebug("State after switch = %d", state);
		
		// Do the work
		switch (state)
		{
		case stateVarBegin:
			if (pos != posVarBegin)
			{
				delete toParse;
				return corruptSgf(pos);
			}
			
			// qDebug("Var BEGIN at %d, moves = %d", pos, moves);
			
			stack.push(tree->getCurrent());
			moveNum = new MoveNum;
			moveNum->n = moves;
			movesStack.push(moveNum);
			pointer = pos + 1;
			break;
			
		case stateVarEnd:
			if (pos != posVarEnd)
			{
				delete toParse;
				return corruptSgf(pos);
			}
			
			// qDebug("VAR END");
			
			if (!movesStack.isEmpty() && !stack.isEmpty())
			{
				Move *m = stack.pop();
				Q_CHECK_PTR(m);
				x = movesStack.pop()->n;
				
				// qDebug("Var END at %d, moves = %d, moves from stack = %d", pos, moves, x);
				
				for (i=moves; i > x; i--)
				{
					position = toRemove.pop();
					if (position == NULL)
						continue;
///////////////////			boardHandler->getStoneHandler()->removeStone(position->x, position->y);
//					tree->removeStone(position->x, position->y);
					// qDebug("Removing %d %d from stoneHandler.", position->x, position->y);
				}
				
				moves = x;
 							
				
				tree->setCurrent(m);
			}
			pointer = pos + 1;
			break;
			
		case stateNode:
			if (pos != posNode)
			{
				delete toParse;
				return corruptSgf(pos);
			}
			
			// qDebug("Node at %d", pos);
			commentStr = QString();
			setup = false;
			markType = markNone;
			
			// Create empty node
			remember_root = isRoot;
			if (!isRoot)
			{
/////////////////////		boardHandler->createMoveSGF();
//				qDebug("############### Before creating move ####################");
//				qDebug(toParse->Str.toLatin1().constData());
				//tree->createMoveSGF();
				/* This does happen, why??? FIXME */
//				qDebug("###############                      ####################");
//				qDebug(toParse->Str.toLatin1().constData());
//				qDebug("############### After creating move ####################");
				unknownProperty = QString();
#ifdef FIXME	//why is this a warning? this happens on loading a file with time info
				if (tree->getCurrent()->getTimeinfo())
				qWarning("*** Timeinfo set !!!!");
#endif //FIXME
				//tree->getCurrent()->setTimeinfo(false);
			}
			else
				isRoot = false;
						
			Property prop;
			pos ++;

			do {
				uint tmppos=0;
				pos = toParse->next_nonspace (pos);
				
                if ((tmppos = toParse->isProperty("B",pos)))
				{
					prop = moveBlack;
					pos = tmppos;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("W",pos)))
				{
					prop = moveWhite;
					pos = tmppos;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("N",pos)))
				{
					prop = nodeName;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("AB",pos)))
				{
					prop = editBlack;
					pos = tmppos;
					setup = true;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("AW",pos)))
				{
					prop = editWhite;
					pos = tmppos;
					setup = true;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("AE",pos)))
				{
					prop = editErase;
					pos = tmppos;
					setup = true;
				}
                else if ((tmppos = toParse->isProperty("TR",pos)))
				{
					prop = editMark;
					markType = markTriangle;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("CR",pos)))
				{
					prop = editMark;
					markType = markCircle;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("SQ",pos)))
				{
					prop = editMark;
					markType = markSquare;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("MA",pos)))
				{
					prop = editMark;
					markType = markCross;
					pos = tmppos;
				}
				// old definition
                else if ((tmppos = toParse->isProperty("M",pos)))
				{
					prop = editMark;
					markType = markCross;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("LB",pos)))
				{
					prop = editMark;
					markType = markText;
					pos = tmppos;
					old_label = false;
				}
				// Added old L property. This is not SGF4, but many files contain this tag.
                else if ((tmppos = toParse->isProperty("L",pos)))
				{
					prop = editMark;
					markType = markText;
					pos = tmppos;
					old_label = true;
				}
                else if ((tmppos = toParse->isProperty("C",pos)))
				{
					prop = comment;
					pos = tmppos;
				}
                else if ((tmppos = toParse->isProperty("TB",pos)))
				{
					prop = editMark;
					markType = markTerrBlack;
					pos = tmppos;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("TW",pos)))
				{
					prop = editMark;
					markType = markTerrWhite;
					pos = tmppos;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("BL",pos)))
				{
					prop = timeLeft;
					pos = tmppos;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("WL",pos)))
				{
					prop = timeLeft;
					pos = tmppos;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("OB",pos)))
				{
					prop = openMoves;
					pos = tmppos;
					black = true;
				}
                else if ((tmppos = toParse->isProperty("OW",pos)))
				{
					prop = openMoves;
					pos = tmppos;
					black = false;
				}
                else if ((tmppos = toParse->isProperty("PL",pos)))
				{
					prop = nextMove;
					pos = tmppos;
				}
                    else if ((tmppos = toParse->isProperty("RG",pos)))
				{
					prop = unknownProp;
					pos = tmppos;
          				setup = true;
				}
				// Empty node
				else if (toParse->at(pos) == ';' || toParse->at(pos) == '(' || toParse->at(pos) == ')')
				{
					qDebug("Found empty node at %d", pos);
					while (toParse->at(pos).isSpace())
						pos++;
					continue;
				}
				else
				{
					// handle like comment
					prop = unknownProp;
					pos = toParse->next_nonspace (pos);
					//qDebug("SGF: next nonspace (1st):" + QString(toParse->at(pos)) + QString(toParse->at(pos+1)) + QString(toParse->at(pos+2)));
				}
				
				//qDebug("Start do loop : FOUND PROP %d, pos at %d now", prop, pos);
				//qDebug(toParse->getStr());			//causes crash
				// Next is one or more '[xx]'.
				// Only one in a move property, several in a setup propery
				do {
					if (toParse->at(pos) != '[' && prop != unknownProp)
					{
						delete toParse;
						return corruptSgf(pos);
					}
					
					// Empty type
					if (toParse->at(pos+1) == ']')
					{
						// CGoban stores pass as 'B[]' or 'W[]'
						if (prop == moveBlack || prop == moveWhite)
						{
							tree->doPass(true);
							
							// Remember this move for later, to remove from the matrix.
							position = new Position;
							position->x = x;
							position->y = y;
							toRemove.push(position);
							moves ++;
						}
						
						pos += 2;
						continue;
					}
					
					switch (prop)
					{
					case moveBlack:
					case moveWhite:
						// rare case: root contains move or placed stone:
						if (remember_root)
						{
							qDebug("root contains stone -> node created");
							/* Something is screwy here, inconsistencies
							 * in the way SGF's are treated. Like the below:
							 * the whole point of "remember_root", FIXME*/
							tree->addEmptyMove();
							isRoot = false;
							unknownProperty = QString();
#ifdef FIXME	//why is this a warning?
							if (tree->getCurrent()->getTimeinfo())
								qWarning("*** Timeinfo set (2)!!!!");
#endif //FIXME
							//tree->getCurrent()->setTimeinfo(false);
						}
					case editBlack:
					case editWhite:
					case editErase:
					{
						x = toParse->at(pos+1).unicode() - a_offset ;// - 'a';// + 1;
						y = toParse->at(pos+2).unicode() - a_offset ; //- 'a' + 1;

						int x1, y1;
						bool compressed_list;

						// check for compressed lists
						if (toParse->at(pos+3) == ':')
						{
							x1 = toParse->at(pos+4).unicode() -a_offset;// - 'a' + 1;
							y1 = toParse->at(pos+5).unicode() -a_offset;// - 'a' + 1;
							compressed_list = true;
						}
						else
						{
							x1 = x;
							y1 = y;
							compressed_list = false;
						}
/*								
*						TODO Do we nned this when the tree is created from file ?
*						boardHandler->setModeSGF(setup || compressed_list ? modeEdit : modeNormal);
*/
						
						int i, j;
						for (i = x; i <= x1; i++)
							for (j = y; j <= y1; j++)
                            {
                                if (prop == editErase)
								{
									tree->addStoneToCurrentMove(stoneErase, i, j);
								}
								else
								{
									if(setup)
									{
                                        if ((!remember_root) && (stack.top() == tree->getCurrent()))
                                            tree->addEmptyMove(); //if this is first in branch we need to add an empty move

										tree->addStoneToCurrentMove(black ? stoneBlack : stoneWhite, i, j);
									}
									else
                                    {
                                        Move *result = tree->getCurrent()->makeMove(black ? stoneBlack : stoneWhite, i, j);
                                        if (result)
                                            tree->setCurrent(result);
                                    }
								}
								// tree->getCurrent()->getMatrix()->debug();
								//qDebug("ADDING MOVE %s %d/%d", black?"B":"W", x, y);
								
								// Remember this move for later, to remove from the matrix.
								position = new Position;
								position->x = i;
								position->y = j;
								toRemove.push(position);
								moves ++;
							}
												
						if (compressed_list)
							// Advance pos by 7
							pos += 7;
						else
							// Advance pos by 4
							pos += 4;
						break;
					}
						
					case nodeName:
					{
						commentStr = QString();
						bool skip = false;
						
						while (toParse->at(++pos) != ']')
						{
							if (static_cast<unsigned int>(pos) > strLength-1)
							{
								qDebug("SGF: Nodename string ended immediately");
								delete toParse;
								return corruptSgf(pos, "SGF: Nodename string ended immediately");
							}

							// white spaces
							if (toParse->at(pos) == '\\')
							{
								while (toParse->at(pos+1).isSpace() &&
									static_cast<unsigned int>(pos) < strLength-2)
									pos++;
								if (toParse->at(pos).isSpace())
									pos++;

								// case: "../<cr><lf>]"
								if (toParse->at(pos) == ']')
								{
									pos--;
									skip = true;
								}
							}

							// escaped chars: '\', ']', ':'
							if (!(toParse->at(pos) == '\\' &&
								(toParse->at(pos+1) == ']' ||
								 toParse->at(pos+1) == '\\' ||
								 toParse->at(pos+1) == ':')) &&
								 !skip &&
								 // no formatting
								!(toParse->at(pos) == '\n') &&
								!(toParse->at(pos) == '\r'))
								commentStr.append(toParse->at(pos));
						}
						
					 	//qDebug("Node name read: %s", commentStr.toLatin1().constData());
						if (!commentStr.isEmpty())
							// add comment; skip 'C[]'
							tree->getCurrent()->setNodeName(commentStr);
						pos++;
						break;
					}

					case comment:
					{
						commentStr = QString();
						bool skip = false;
						
						while (toParse->at(++pos) != ']' ||
							(toParse->at(pos-1) == '\\' && toParse->at(pos) == ']'))
						{
							if (static_cast<unsigned int>(pos) > strLength-1)
							{
								qDebug("SGF: Comment string ended immediately");
								delete toParse;
								return corruptSgf(pos, "SGF: Comment string ended immediately");
							}

							// white spaces
							if (toParse->at(pos) == '\\')
							{
								while (toParse->at(pos+1).isSpace() &&
									static_cast<unsigned int>(pos) < strLength-2)
									pos++;
								if (toParse->at(pos).isSpace())
									pos++;

								// case: "../<cr><lf>]"
								if (toParse->at(pos) == ']')
								{
									pos--;
									skip = true;
								}
							}

							// escaped chars: '\', ']', ':'
							if (!(toParse->at(pos) == '\\' &&
								(toParse->at(pos+1) == ']' ||
								 toParse->at(pos+1) == '\\' ||
								 toParse->at(pos+1) == ':')) &&
								 !skip)
								commentStr.append(toParse->at(pos));
						}

						//qDebug("Comment read: %s", commentStr.toLatin1().constData());
						if (!commentStr.isEmpty())
						{
							// add comment; skip 'C[]'
							if(readCodec)
								tree->getCurrent()->setComment(readCodec->toUnicode(commentStr.toLatin1().constData()));
							else
								tree->getCurrent()->setComment(commentStr.toLatin1().constData());
						}
						pos ++;
						break;
					}

					case unknownProp:
					{
						// skip if property is known anyway
						bool skip = false;

						// save correct property name (or p.n. + '[')
						commentStr = QString(toParse->at(pos));
						commentStr += toParse->at(tmppos = toParse->next_nonspace (pos + 1));
						pos = tmppos;

						// check if it's really necessary to hold properties
						// maybe they are handled at another position
						if (commentStr == "WR" ||
							commentStr == "BR" ||
							commentStr == "PW" ||
							commentStr == "PB" ||
							commentStr == "SZ" ||
							commentStr == "KM" ||
							commentStr == "HA" ||
							commentStr == "RE" ||
							commentStr == "DT" ||
							commentStr == "PC" ||
							commentStr == "CP" ||
							commentStr == "GN" ||
							commentStr == "OT" ||
							commentStr == "TM" ||
							// now: general options
							commentStr == "GM" ||
							commentStr == "ST" ||
							commentStr == "AP" ||
							commentStr == "FF")
						{
							skip = true;
						}
						sss= toParse->at(pos);
						while (toParse->at(++pos) != ']' ||
							(toParse->at(pos-1) == '\\' && toParse->at(pos) == ']'))
						{
							if (static_cast<unsigned int>(pos) > strLength-1)
							{
								qDebug("SGF: Unknown property ended immediately");
								delete toParse;
								return corruptSgf(pos, "SGF: Unknown property ended immediately");
							}
              						sss= toParse->at(pos);
							if (!skip)
								commentStr.append(toParse->at(pos));
						}

						if (!skip)
							commentStr.append("]");

						// qDebug("Comment read: %s", commentStr.latin1());
						if ((!commentStr.isEmpty()) && (!skip))
						{
							// cumulate unknown properties; skip empty property 'XZ[]'
							unknownProperty += commentStr;
							tree->getCurrent()->setUnknownProperty(unknownProperty);
						}
						pos ++;
            					sss= toParse->at(pos);
						break;
					}

					case editMark:
						// set moveStr for increment labels of old 'L[]' property
						moveStr = "A";
						while (toParse->at(pos) == '[' &&
							static_cast<unsigned int>(pos) < strLength)
						{
							x = toParse->at(pos+1).unicode() -a_offset;// - 'a' + 1;
							y = toParse->at(pos+2).unicode() -a_offset;// - 'a' + 1;
							// qDebug("MARK: %d at %d/%d", markType, x, y);
							pos += 3;
							
							// 'LB' property? Then we need to get the text
							if (markType == markText && !old_label)
							{
								if (toParse->at(pos) != ':')
								{
									delete toParse;
									return corruptSgf(pos);
								}
								moveStr = "";
								while (toParse->at(++pos) != ']' &&
									static_cast<unsigned int>(pos) < strLength)
									moveStr.append(toParse->at(pos));
								// qDebug("LB TEXT = %s", moveStr.latin1());
								// It might me a number mark?
								bool check = false;
								moveStr.toInt(&check);  // Try to convert to Integer
								// treat integers as characters...
								check = false;
								
								if (check)
									tree->getCurrent()->getMatrix()->
									insertMark(x, y, markNumber);  // Worked, its a number
								else
									tree->getCurrent()->getMatrix()->
									insertMark(x, y, markType);    // Nope, its a letter
								tree->getCurrent()->getMatrix()->
										setMarkText(x, y, moveStr);
							
								/*else	//fastload
								{
									if (check)  // Number
										tree->getCurrent()->insertFastLoadMark(x, y, markNumber);
									else        // Text
										tree->getCurrent()->insertFastLoadMark(x, y, markType, moveStr);
								}*/
							}
							else
							{
								int x1, y1;
								bool compressed_list;

								// check for compressed lists
								if (toParse->at(pos) == ':')
								{
									x1 = toParse->at(pos+1).unicode() -a_offset;// - 'a' + 1;
									y1 = toParse->at(pos+2).unicode() -a_offset;// - 'a' + 1;
									compressed_list = true;
								}
								else
								{
									x1 = x;
									y1 = y;
									compressed_list = false;
								}
								
								int i, j;
								for (i = x; i <= x1; i++)
									for (j = y; j <= y1; j++)
									{
										tree->getCurrent()->getMatrix()->insertMark(i, j, markType);
										//else	//fastload
										//	tree->getCurrent()->insertFastLoadMark(i, j, markType);

										// auto increment for old property 'L'
										if (old_label)
										{
											tree->getCurrent()->getMatrix()->
												setMarkText(x, y, moveStr);
											QChar c1 = moveStr[0];
											if (c1 == 'Z')
												moveStr = QString("a");
											else
												moveStr = c1.unicode() + 1;
										}
									}

//								new_node = false;

								if (compressed_list)
									// Advance pos by 3
									pos += 3;

								if((markType == markTerrWhite || markType == markTerrBlack) && !tree->getCurrent()->isTerritoryMarked())
									tree->getCurrent()->setTerritoryMarked();
							}

							//old_label = false;
							pos ++;
							while (toParse->at(pos).isSpace()) pos++;
						}
						break;

					case openMoves:
					{
						QString tmp_mv;
						while (toParse->at(++pos) != ']')
							tmp_mv += toParse->at(pos);
						tree->getCurrent()->setOpenMoves(tmp_mv.toInt());
						pos++;

						if (!tree->getCurrent()->getTimeinfo())
						{
							tree->getCurrent()->setTimeinfo(true);
							tree->getCurrent()->setTimeLeft(0);
						}
						break;
					}

					case timeLeft:
					{
						QString tmp_mv;
						while (toParse->at(++pos) != ']')
							tmp_mv += toParse->at(pos);
						tree->getCurrent()->setTimeLeft(tmp_mv.toFloat());
						pos++;

						if (!tree->getCurrent()->getTimeinfo())
						{
							tree->getCurrent()->setTimeinfo(true);
							tree->getCurrent()->setOpenMoves(0);
						}
						break;
					}

					case nextMove:
						if (toParse->at(++pos) == 'W')
							tree->getCurrent()->setPLinfo(stoneWhite);
						else if (toParse->at(pos) == 'B')
							tree->getCurrent()->setPLinfo(stoneBlack);

						pos += 2;
						break;

					default:
						break;
				}
		
				while (toParse->at(pos).isSpace())
			    		pos++;
        	
				sss= toParse->at(pos);

			} while (setup && toParse->at(pos) == '[');
			
//			tree->getCurrent()->getMatrix()->debug();
//			qDebug("end do loop");
//			qDebug(toParse->getStr());
			
			while (toParse->at(pos).isSpace())
				pos++;

		} while (toParse->at(pos) != ';' && toParse->at(pos) != '(' && toParse->at(pos) != ')' &&    static_cast<unsigned int>(pos) < strLength);
		
		// Advance pointer
		pointer = pos;
	
		break;
	
	default:
		delete toParse;
		return corruptSgf(pointer);
	}
	
	} while (pointer < strLength && pos >= 0);

	tree->setLoadingSGF(false);
	
	delete toParse;
	return !cancel;
}
Пример #21
0
const UniProps *
PreparsedUCD::getProps(UnicodeSet &newValues, UErrorCode &errorCode) {
    if(U_FAILURE(errorCode)) { return NULL; }
    newValues.clear();
    if(!lineHasPropertyValues()) {
        errorCode=U_ILLEGAL_ARGUMENT_ERROR;
        return NULL;
    }
    firstField();
    const char *field=nextField();
    if(field==NULL) {
        // No range field after the type.
        fprintf(stderr,
                "error in preparsed UCD: missing default/block/cp range field "
                "(no second field) on line %ld\n",
                (long)lineNumber);
        errorCode=U_PARSE_ERROR;
        return NULL;
    }
    UChar32 start, end;
    if(!parseCodePointRange(field, start, end, errorCode)) { return NULL; }
    UniProps *props;
    switch(lineType) {
    case DEFAULTS_LINE:
        if(defaultLineIndex>=0) {
            fprintf(stderr,
                    "error in preparsed UCD: second line with default properties on line %ld\n",
                    (long)lineNumber);
            errorCode=U_PARSE_ERROR;
            return NULL;
        }
        if(start!=0 || end!=0x10ffff) {
            fprintf(stderr,
                    "error in preparsed UCD: default range must be 0..10FFFF, not '%s' on line %ld\n",
                    field, (long)lineNumber);
            errorCode=U_PARSE_ERROR;
            return NULL;
        }
        props=&defaultProps;
        defaultLineIndex=lineIndex;
        break;
    case BLOCK_LINE:
        blockProps=defaultProps;  // Block inherits default properties.
        props=&blockProps;
        blockLineIndex=lineIndex;
        break;
    case CP_LINE:
        if(blockProps.start<=start && end<=blockProps.end) {
            // Code point range fully inside the last block inherits the block properties.
            cpProps=blockProps;
        } else if(start>blockProps.end || end<blockProps.start) {
            // Code point range fully outside the last block inherits the default properties.
            cpProps=defaultProps;
        } else {
            // Code point range partially overlapping with the last block is illegal.
            fprintf(stderr,
                    "error in preparsed UCD: cp range %s on line %ld only "
                    "partially overlaps with block range %04lX..%04lX\n",
                    field, (long)lineNumber, (long)blockProps.start, (long)blockProps.end);
            errorCode=U_PARSE_ERROR;
            return NULL;
        }
        props=&cpProps;
        break;
    default:
        // Will not occur because of the range check above.
        errorCode=U_ILLEGAL_ARGUMENT_ERROR;
        return NULL;
    }
    props->start=start;
    props->end=end;
    while((field=nextField())!=NULL) {
        if(!parseProperty(*props, field, newValues, errorCode)) { return NULL; }
    }
    return props;
}
Пример #22
0
TOKEN_DEF_END
//////////////////////////////////////////////////////////////////////////
bool AdEntity::loadBuffer(byte *buffer, bool complete) {
	TOKEN_TABLE_START(commands)
	TOKEN_TABLE(ENTITY)
	TOKEN_TABLE(SPRITE)
	TOKEN_TABLE(X)
	TOKEN_TABLE(Y)
	TOKEN_TABLE(TEMPLATE)
	TOKEN_TABLE(NAME)
	TOKEN_TABLE(SCALABLE)
	TOKEN_TABLE(REGISTRABLE)
	TOKEN_TABLE(INTERACTIVE)
	TOKEN_TABLE(SHADOWABLE)
	TOKEN_TABLE(COLORABLE)
	TOKEN_TABLE(ACTIVE)
	TOKEN_TABLE(EVENTS)
	TOKEN_TABLE(FONT)
	TOKEN_TABLE(TALK_SPECIAL)
	TOKEN_TABLE(TALK)
	TOKEN_TABLE(CURSOR)
	TOKEN_TABLE(REGION)
	TOKEN_TABLE(BLOCKED_REGION)
	TOKEN_TABLE(EDITOR_SELECTED)
	TOKEN_TABLE(SCRIPT)
	TOKEN_TABLE(SOUND_START_TIME)
	TOKEN_TABLE(SOUND_VOLUME)
	TOKEN_TABLE(SOUND_PANNING)
	TOKEN_TABLE(SOUND)
	TOKEN_TABLE(SUBTYPE)
	TOKEN_TABLE(CAPTION)
	TOKEN_TABLE(PROPERTY)
	TOKEN_TABLE(WAYPOINTS)
	TOKEN_TABLE(IGNORE_ITEMS)
	TOKEN_TABLE(ROTABLE)
	TOKEN_TABLE(ROTATABLE)
	TOKEN_TABLE(ALPHA_COLOR)
	TOKEN_TABLE(SCALE)
	TOKEN_TABLE(RELATIVE_SCALE)
	TOKEN_TABLE(ALPHA)
	TOKEN_TABLE(EDITOR_PROPERTY)
	TOKEN_TABLE(ITEM)
	TOKEN_TABLE(WALK_TO_X)
	TOKEN_TABLE(WALK_TO_Y)
	TOKEN_TABLE(WALK_TO_DIR)
	TOKEN_TABLE(SAVE_STATE)
	TOKEN_TABLE_END

	byte *params;
	int cmd;
	BaseParser parser;

	if (complete) {
		if (parser.getCommand((char **)&buffer, commands, (char **)&params) != TOKEN_ENTITY) {
			_gameRef->LOG(0, "'ENTITY' keyword expected.");
			return STATUS_FAILED;
		}
		buffer = params;
	}

	AdGame *adGame = (AdGame *)_gameRef;
	BaseSprite *spr = nullptr;
	int ar = 0, ag = 0, ab = 0, alpha = 0;
	while ((cmd = parser.getCommand((char **)&buffer, commands, (char **)&params)) > 0) {
		switch (cmd) {
		case TOKEN_TEMPLATE:
			if (DID_FAIL(loadFile((char *)params))) {
				cmd = PARSERR_GENERIC;
			}
			break;

		case TOKEN_X:
			parser.scanStr((char *)params, "%d", &_posX);
			break;

		case TOKEN_Y:
			parser.scanStr((char *)params, "%d", &_posY);
			break;

		case TOKEN_SPRITE: {
			delete _sprite;
			_sprite = nullptr;
			spr = new BaseSprite(_gameRef, this);
			if (!spr || DID_FAIL(spr->loadFile((char *)params))) {
				cmd = PARSERR_GENERIC;
			} else {
				_sprite = spr;
			}
		}
		break;

		case TOKEN_TALK: {
			spr = new BaseSprite(_gameRef, this);
			if (!spr || DID_FAIL(spr->loadFile((char *)params, adGame->_texTalkLifeTime))) {
				cmd = PARSERR_GENERIC;
			} else {
				_talkSprites.add(spr);
			}
		}
		break;

		case TOKEN_TALK_SPECIAL: {
			spr = new BaseSprite(_gameRef, this);
			if (!spr || DID_FAIL(spr->loadFile((char *)params, adGame->_texTalkLifeTime))) {
				cmd = PARSERR_GENERIC;
			} else {
				_talkSpritesEx.add(spr);
			}
		}
		break;

		case TOKEN_NAME:
			setName((char *)params);
			break;

		case TOKEN_ITEM:
			setItem((char *)params);
			break;

		case TOKEN_CAPTION:
			setCaption((char *)params);
			break;

		case TOKEN_FONT:
			setFont((char *)params);
			break;

		case TOKEN_SCALABLE:
			parser.scanStr((char *)params, "%b", &_zoomable);
			break;

		case TOKEN_SCALE: {
			int s;
			parser.scanStr((char *)params, "%d", &s);
			_scale = (float)s;

		}
		break;

		case TOKEN_RELATIVE_SCALE: {
			int s;
			parser.scanStr((char *)params, "%d", &s);
			_relativeScale = (float)s;

		}
		break;

		case TOKEN_ROTABLE:
		case TOKEN_ROTATABLE:
			parser.scanStr((char *)params, "%b", &_rotatable);
			break;

		case TOKEN_REGISTRABLE:
		case TOKEN_INTERACTIVE:
			parser.scanStr((char *)params, "%b", &_registrable);
			break;

		case TOKEN_SHADOWABLE:
		case TOKEN_COLORABLE:
			parser.scanStr((char *)params, "%b", &_shadowable);
			break;

		case TOKEN_ACTIVE:
			parser.scanStr((char *)params, "%b", &_active);
			break;

		case TOKEN_CURSOR:
			delete _cursor;
			_cursor = new BaseSprite(_gameRef);
			if (!_cursor || DID_FAIL(_cursor->loadFile((char *)params))) {
				delete _cursor;
				_cursor = nullptr;
				cmd = PARSERR_GENERIC;
			}
			break;

		case TOKEN_EDITOR_SELECTED:
			parser.scanStr((char *)params, "%b", &_editorSelected);
			break;

		case TOKEN_REGION: {
			if (_region) {
				_gameRef->unregisterObject(_region);
			}
			_region = nullptr;
			BaseRegion *rgn = new BaseRegion(_gameRef);
			if (!rgn || DID_FAIL(rgn->loadBuffer(params, false))) {
				cmd = PARSERR_GENERIC;
			} else {
				_region = rgn;
				_gameRef->registerObject(_region);
			}
		}
		break;

		case TOKEN_BLOCKED_REGION: {
			delete _blockRegion;
			_blockRegion = nullptr;
			delete _currentBlockRegion;
			_currentBlockRegion = nullptr;
			BaseRegion *rgn = new BaseRegion(_gameRef);
			BaseRegion *crgn = new BaseRegion(_gameRef);
			if (!rgn || !crgn || DID_FAIL(rgn->loadBuffer(params, false))) {
				delete _blockRegion;
				_blockRegion = nullptr;
				delete _currentBlockRegion;
				_currentBlockRegion = nullptr;
				cmd = PARSERR_GENERIC;
			} else {
				_blockRegion = rgn;
				_currentBlockRegion = crgn;
				_currentBlockRegion->mimic(_blockRegion);
			}
		}
		break;

		case TOKEN_WAYPOINTS: {
			delete _wptGroup;
			_wptGroup = nullptr;
			delete _currentWptGroup;
			_currentWptGroup = nullptr;
			AdWaypointGroup *wpt = new AdWaypointGroup(_gameRef);
			AdWaypointGroup *cwpt = new AdWaypointGroup(_gameRef);
			if (!wpt || !cwpt || DID_FAIL(wpt->loadBuffer(params, false))) {
				delete _wptGroup;
				_wptGroup = nullptr;
				delete _currentWptGroup;
				_currentWptGroup = nullptr;
				cmd = PARSERR_GENERIC;
			} else {
				_wptGroup = wpt;
				_currentWptGroup = cwpt;
				_currentWptGroup->mimic(_wptGroup);
			}
		}
		break;

		case TOKEN_SCRIPT:
			addScript((char *)params);
			break;

		case TOKEN_SUBTYPE: {
			if (scumm_stricmp((char *)params, "sound") == 0) {
				delete _sprite;
				_sprite = nullptr;
				if (_gameRef->_editorMode) {
					spr = new BaseSprite(_gameRef, this);
					if (!spr || DID_FAIL(spr->loadFile("entity_sound.sprite"))) {
						cmd = PARSERR_GENERIC;
					} else {
						_sprite = spr;
					}
				}
				if (_gameRef->_editorMode) {
					_editorOnly = true;
				}
				_zoomable = false;
				_rotatable = false;
				_registrable = _gameRef->_editorMode;
				_shadowable = false;
				_subtype = ENTITY_SOUND;
			}
		}
		break;

		case TOKEN_SOUND:
			playSFX((char *)params, false, false);
			break;

		case TOKEN_SOUND_START_TIME:
			parser.scanStr((char *)params, "%d", &_sFXStart);
			break;

		case TOKEN_SOUND_VOLUME:
			parser.scanStr((char *)params, "%d", &_sFXVolume);
			break;

		case TOKEN_SOUND_PANNING:
			parser.scanStr((char *)params, "%b", &_autoSoundPanning);
			break;

		case TOKEN_SAVE_STATE:
			parser.scanStr((char *)params, "%b", &_saveState);
			break;

		case TOKEN_PROPERTY:
			parseProperty(params, false);
			break;

		case TOKEN_IGNORE_ITEMS:
			parser.scanStr((char *)params, "%b", &_ignoreItems);
			break;

		case TOKEN_ALPHA_COLOR:
			parser.scanStr((char *)params, "%d,%d,%d", &ar, &ag, &ab);
			break;

		case TOKEN_ALPHA:
			parser.scanStr((char *)params, "%d", &alpha);
			break;

		case TOKEN_EDITOR_PROPERTY:
			parseEditorProperty(params, false);
			break;

		case TOKEN_WALK_TO_X:
			parser.scanStr((char *)params, "%d", &_walkToX);
			break;

		case TOKEN_WALK_TO_Y:
			parser.scanStr((char *)params, "%d", &_walkToY);
			break;

		case TOKEN_WALK_TO_DIR: {
			int i;
			parser.scanStr((char *)params, "%d", &i);
			if (i < 0) {
				i = 0;
			}
			if (i >= NUM_DIRECTIONS) {
				i = DI_NONE;
			}
			_walkToDir = (TDirection)i;
		}
		break;
		}
	}
	if (cmd == PARSERR_TOKENNOTFOUND) {
		_gameRef->LOG(0, "Syntax error in ENTITY definition");
		return STATUS_FAILED;
	}
	if (cmd == PARSERR_GENERIC) {
		_gameRef->LOG(0, "Error loading ENTITY definition");
		if (spr) {
			delete spr;
		}
		return STATUS_FAILED;
	}

	if (_region && _sprite) {
		_gameRef->LOG(0, "Warning: Entity '%s' has both sprite and region.", getName());
	}

	updatePosition();

	if (alpha != 0 && ar == 0 && ag == 0 && ab == 0) {
		ar = ag = ab = 255;
	}
	_alphaColor = BYTETORGBA(ar, ag, ab, alpha);
	_state = STATE_READY;

	if (_item && ((AdGame *)_gameRef)->isItemTaken(_item)) {
		_active = false;
	}

	return STATUS_OK;
}
Пример #23
0
bool Parser::parseObject(ObjectAst **yynode)
{
    *yynode = create<ObjectAst>();

    (*yynode)->startToken = tokenStream->index() - 1;
    (*yynode)->type = -1;
    (*yynode)->name = -1;

    if (yytoken == Token_LBRACE)
    {
        if (yytoken != Token_LBRACE)
        {
            expectedToken(yytoken, Token_LBRACE, "LBRACE");
            return false;
        }
        yylex();

        if (yytoken != Token_IDENTIFIER)
        {
            expectedToken(yytoken, Token_IDENTIFIER, "IDENTIFIER");
            return false;
        }
        (*yynode)->type = tokenStream->index() - 1;
        yylex();

        if (yytoken != Token_LPAREN)
        {
            expectedToken(yytoken, Token_LPAREN, "LPAREN");
            return false;
        }
        yylex();

        if (yytoken != Token_VALUE)
        {
            expectedToken(yytoken, Token_VALUE, "VALUE");
            return false;
        }
        (*yynode)->name = tokenStream->index() - 1;
        yylex();

        if (yytoken != Token_RPAREN)
        {
            expectedToken(yytoken, Token_RPAREN, "RPAREN");
            return false;
        }
        yylex();

        while (yytoken == Token_IDENTIFIER
                || yytoken == Token_LBRACE)
        {
            if (yytoken == Token_IDENTIFIER)
            {
                PropertyAst *__node_1 = 0;
                if (!parseProperty(&__node_1))
                {
                    expectedSymbol(AstNode::PropertyKind, "property");
                    return false;
                }
                (*yynode)->propertiesSequence = snoc((*yynode)->propertiesSequence, __node_1, memoryPool);

            }
            else if (yytoken == Token_LBRACE)
            {
                ObjectAst *__node_2 = 0;
                if (!parseObject(&__node_2))
                {
                    expectedSymbol(AstNode::ObjectKind, "object");
                    return false;
                }
                (*yynode)->objectsSequence = snoc((*yynode)->objectsSequence, __node_2, memoryPool);

            }
            else
            {
                return false;
            }
        }
        if (yytoken != Token_RBRACE)
        {
            expectedToken(yytoken, Token_RBRACE, "RBRACE");
            return false;
        }
        yylex();

    }
    else
    {
        return false;
    }

    (*yynode)->endToken = tokenStream->index() - 2;

    return true;
}