Example #1
0
bool DeviceInfo::ParseXml(QXmlStreamReader& xml)
{
	bool foundManufacturer = false;
	bool foundProduct = false;
	bool foundName = false;

	while (!xml.atEnd())
	{
		QXmlStreamReader::TokenType nextToken = xml.readNext();

		if (nextToken == QXmlStreamReader::StartElement)
		{
			if (xml.name() == "manufacturer")
			{
				if (foundManufacturer)
				{
					Alerts::DisplayError("Found multiple <manufacturer> elements in <device>.");
					return (false);
				}

				foundManufacturer = true;

				manufacturer = xml.readElementText();
			}
			else if (xml.name() == "product")
			{
				if (foundProduct)
				{
					Alerts::DisplayError("Found multiple <product> elements in <device>.");
					return (false);
				}

				foundProduct = true;

				product = xml.readElementText();
			}
			else if (xml.name() == "name")
			{
				if (foundName)
				{
					Alerts::DisplayError("Found multiple <name> elements in <device>.");
					return (false);
				}

				foundName = true;

				name = xml.readElementText();
			}
			else
			{
				Alerts::DisplayError(QString("<%1> is not a valid child of <device>.").arg(xml.name().toString()));
				return (false);
			}
		}
		else if (nextToken == QXmlStreamReader::EndElement)
		{
			if (xml.name() == "device")
			{
				if (foundManufacturer && foundProduct && foundName)
				{
					return (true);
				}
				else
				{
					Alerts::DisplayError("Required elements are missing from <device>.");
					return (false);
				}
			}
		}
		else
		{
			if (!(nextToken == QXmlStreamReader::Characters && xml.isWhitespace()))
			{
				Alerts::DisplayError("Unexpected token found in <device>.");
				return (false);
			}
		}
	}

	return (false);
}
Example #2
0
bool FileInfo::ParseXml(QXmlStreamReader& xml)
{
	bool foundId = false;
	bool foundFilename = false;

	while (!xml.atEnd())
	{
		QXmlStreamReader::TokenType nextToken = xml.readNext();

		if (nextToken == QXmlStreamReader::StartElement)
		{
			if (xml.name() == "id")
			{
				if (foundId)
				{
					Alerts::DisplayError("Found multiple <id> elements in <file>.");
					return (false);
				}

				foundId = true;

				partitionId = xml.readElementText().toInt();
			}
			else if (xml.name() == "filename")
			{
				if (foundFilename)
				{
					Alerts::DisplayError("Found multiple <filename> elements in <file>.");
					return (false);
				}

				foundFilename = true;

				filename = xml.readElementText();
			}
			else
			{
				Alerts::DisplayError(QString("<%1> is not a valid child of <file>.").arg(xml.name().toString()));
				return (false);
			}
		}
		else if (nextToken == QXmlStreamReader::EndElement)
		{
			if (xml.name() == "file")
			{
				if (foundId && foundFilename)
				{
					return (true);
				}
				else
				{
					Alerts::DisplayError("Required elements are missing from <file>.");
					return (false);
				}
			}
		}
		else
		{
			if (!(nextToken == QXmlStreamReader::Characters && xml.isWhitespace()))
			{
				Alerts::DisplayError("Unexpected token found in <file>.");
				return (false);
			}
		}
	}

	return (false);
}
Example #3
0
bool FirmwareInfo::ParseXml(QXmlStreamReader& xml)
{
	Clear();

	bool foundName = false;
	bool foundVersion = false;
	bool foundPlatform = false;
	bool foundDevelopers = false;
	bool foundUrl = false;
	bool foundDonateUrl = false;
	bool foundDevices = false;
	bool foundPit = false;
	bool foundRepartition = false;
	bool foundNoReboot = false;
	bool foundFiles = false;

	if (!xml.readNextStartElement())
	{
		Alerts::DisplayError("Failed to find <firmware> element.");
		return (false);
	}

	if (xml.name() != "firmware")
	{
		Alerts::DisplayError(QString("Expected <firmware> element but found <%1>.").arg(xml.name().toString()));
		return (false);
	}

	QString formatVersionString;
	formatVersionString += xml.attributes().value("version");

	if (formatVersionString.isEmpty())
	{
		Alerts::DisplayError("<firmware> is missing the version attribute.");
		return (false);
	}

	bool parsedVersion = false;
	int formatVersion = formatVersionString.toInt(&parsedVersion);

	if (!parsedVersion)
	{
		Alerts::DisplayError("<firmware> contains a malformed version.");
		return (false);
	}

	if (formatVersion > kVersion)
	{
		Alerts::DisplayError("Package is for a newer version of Heimdall Frontend.\nPlease download the latest version of Heimdall Frontend.");
		return (false);
	}

	while (!xml.atEnd())
	{
		QXmlStreamReader::TokenType nextToken = xml.readNext();

		if (nextToken == QXmlStreamReader::StartElement)
		{
			if (xml.name() == "name")
			{
				if (foundName)
				{
					Alerts::DisplayError("Found multiple <name> elements in <firmware>.");
					return (false);
				}

				foundName = true;
				name = xml.readElementText();
			}
			else if (xml.name() == "version")
			{
				if (foundVersion)
				{
					Alerts::DisplayError("Found multiple <version> elements in <firmware>.");
					return (false);
				}

				foundVersion = true;
				version = xml.readElementText();
			}
			else if (xml.name() == "platform")
			{
				if (foundPlatform)
				{
					Alerts::DisplayError("Found multiple <platform> elements in <firmware>.");
					return (false);
				}

				foundPlatform = true;

				if (!platformInfo.ParseXml(xml))
					return (false);
			}
			else if (xml.name() == "developers")
			{
				if (foundDevelopers)
				{
					Alerts::DisplayError("Found multiple <developers> elements in <firmware>.");
					return (false);
				}

				foundDevelopers = true;

				while (!xml.atEnd())
				{
					nextToken = xml.readNext();

					if (nextToken == QXmlStreamReader::StartElement)
					{
						if (xml.name() == "name")
						{
							developers.append(xml.readElementText());
						}
						else
						{
							Alerts::DisplayError(QString("<%1> is not a valid child of <developers>.").arg(xml.name().toString()));
							return (false);
						}
					}
					else if (nextToken == QXmlStreamReader::EndElement)
					{
						if (xml.name() == "developers")
							break;
					}
					else
					{
						if (!(nextToken == QXmlStreamReader::Characters && xml.isWhitespace()))
						{
							Alerts::DisplayError("Unexpected token found in <developers>.");
							return (false);
						}
					}
				}
			}
			else if (xml.name() == "url")
			{
				if (foundUrl)
				{
					Alerts::DisplayError("Found multiple <url> elements in <firmware>.");
					return (false);
				}

				foundUrl = true;

				url = xml.readElementText();
			}
			else if (xml.name() == "donateurl")
			{
				if (foundDonateUrl)
				{
					Alerts::DisplayError("Found multiple <donateurl> elements in <firmware>.");
					return (false);
				}

				foundDonateUrl = true;

				donateUrl = xml.readElementText();
			}
			else if (xml.name() == "devices")
			{
				if (foundDevices)
				{
					Alerts::DisplayError("Found multiple <devices> elements in <firmware>.");
					return (false);
				}

				foundDevices = true;

				while (!xml.atEnd())
				{
					nextToken = xml.readNext();

					if (nextToken == QXmlStreamReader::StartElement)
					{
						if (xml.name() == "device")
						{
							DeviceInfo deviceInfo;

							if (!deviceInfo.ParseXml(xml))
								return (false);

							deviceInfos.append(deviceInfo);
						}
						else
						{
							Alerts::DisplayError(QString("<%1> is not a valid child of <devices>.").arg(xml.name().toString()));
							return (false);
						}
					}
					else if (nextToken == QXmlStreamReader::EndElement)
					{
						if (xml.name() == "devices")
							break;
					}
					else
					{
						if (!(nextToken == QXmlStreamReader::Characters && xml.isWhitespace()))
						{
							Alerts::DisplayError("Unexpected token found in <devices>.");
							return (false);
						}
					}
				}
			}
			else if (xml.name() == "pit")
			{
				if (foundPit)
				{
					Alerts::DisplayError("Found multiple <pit> elements in <firmware>.");
					return (false);
				}

				foundPit = true;

				pitFilename = xml.readElementText();
			}
			else if (xml.name() == "repartition")
			{
				if (foundRepartition)
				{
					Alerts::DisplayError("Found multiple <repartition> elements in <firmware>.");
					return (false);
				}

				foundRepartition = true;

				repartition = (xml.readElementText().toInt() != 0);
			}
			else if (xml.name() == "noreboot")
			{
				if (foundNoReboot)
				{
					Alerts::DisplayError("Found multiple <noreboot> elements in <firmware>.");
					return (false);
				}

				foundNoReboot = true;

				noReboot = (xml.readElementText().toInt() != 0);
			}
			else if (xml.name() == "files")
			{
				if (foundFiles)
				{
					Alerts::DisplayError("Found multiple <files> elements in <firmware>.");
					return (false);
				}

				foundFiles = true;

				while (!xml.atEnd())
				{
					nextToken = xml.readNext();

					if (nextToken == QXmlStreamReader::StartElement)
					{
						if (xml.name() == "file")
						{
							FileInfo fileInfo;

							if (!fileInfo.ParseXml(xml))
								return (false);

							fileInfos.append(fileInfo);
						}
						else
						{
							Alerts::DisplayError(QString("<%1> is not a valid child of <files>.").arg(xml.name().toString()));
							return (false);
						}
					}
					else if (nextToken == QXmlStreamReader::EndElement)
					{
						if (xml.name() == "files")
							break;
					}
					else
					{
						if (!(nextToken == QXmlStreamReader::Characters && xml.isWhitespace()))
						{
							Alerts::DisplayError("Unexpected token found in <devices>.");
							return (false);
						}
					}
				}
			}
			else
			{
				Alerts::DisplayError(QString("<%1> is not a valid child of <firmware>.").arg(xml.name().toString()));
				return (false);
			}
		}
		else if (nextToken == QXmlStreamReader::EndElement)
		{
			if (xml.name() == "firmware")
			{
				if (!(foundName && foundVersion && foundPlatform && foundDevelopers && foundDevices && foundPit && foundRepartition && foundNoReboot && foundFiles))
				{
					Alerts::DisplayError("Required elements are missing from <firmware>.");
					return (false);
				}
				else
				{
					break;
				}
			}
		}
		else
		{
			if (!(nextToken == QXmlStreamReader::Characters && xml.isWhitespace()))
			{
				Alerts::DisplayError("Unexpected token found in <firmware>.");
				return (false);
			}
		}
	}

	// Read whitespaces at the end of the file (if there are any)
	xml.readNext();

	if (!xml.atEnd())
	{
		Alerts::DisplayError("Found data after </firmware>.");
		return (false);
	}
	
	return (true);
}
Example #4
0
/*!
    \fn void ExtensionInfoPrivate::readExtensionInfo(QXmlStreamReader &reader)
    \internal
*/
void ExtensionInfoPrivate::readExtensionInfo(QXmlStreamReader &reader)
{
    QString element = reader.name().toString();
    if (element != QString(EXTENSION)) {
        reader.raiseError(QCoreApplication::translate("ExtensionInfo", "Expected element '%1' as top level element").arg(EXTENSION));
        return;
    }
    name = reader.attributes().value(EXTENSION_NAME).toString();
    if (name.isEmpty()) {
        reader.raiseError(msgAttributeMissing(EXTENSION, EXTENSION_NAME));
        return;
    }
    version = reader.attributes().value(EXTENSION_VERSION).toString();
    if (version.isEmpty()) {
        reader.raiseError(msgAttributeMissing(EXTENSION, EXTENSION_VERSION));
        return;
    }
    if (!isValidVersion(version)) {
        reader.raiseError(msgInvalidFormat(EXTENSION_VERSION));
        return;
    }
    compatVersion = reader.attributes().value(EXTENSION_COMPATVERSION).toString();
    if (!compatVersion.isEmpty() && !isValidVersion(compatVersion)) {
        reader.raiseError(msgInvalidFormat(EXTENSION_COMPATVERSION));
        return;
    } else if (compatVersion.isEmpty()) {
        compatVersion = version;
    }
    QString experimentalString = reader.attributes().value(EXTENSION_EXPERIMENTAL).toString();
    experimental = (experimentalString.compare(QLatin1String("true"), Qt::CaseInsensitive) == 0);
    if (!experimentalString.isEmpty() && !experimental
            && experimentalString.compare(QLatin1String("false"), Qt::CaseInsensitive) != 0) {
        reader.raiseError(msgInvalidFormat(EXTENSION_EXPERIMENTAL));
        return;
    }
    enabled = !experimental;
    while (!reader.atEnd()) {
        reader.readNext();
        switch (reader.tokenType()) {
        case QXmlStreamReader::StartElement:
            element = reader.name().toString();
            if (element == VENDOR)
                vendor = reader.readElementText().trimmed();
            else if (element == COPYRIGHT)
                copyright = reader.readElementText().trimmed();
            else if (element == LICENSE)
                license = reader.readElementText().trimmed();
            else if (element == DESCRIPTION)
                description = reader.readElementText().trimmed();
            else if (element == URL)
                url = reader.readElementText().trimmed();
            else if (element == CATEGORY)
                category = reader.readElementText().trimmed();
            else if (element == DEPENDENCYLIST)
                readDependencies(reader);
            else if (element == ARGUMENTLIST)
                readArgumentDescriptions(reader);
            else
                reader.raiseError(msgInvalidElement(name));
            break;
        case QXmlStreamReader::EndDocument:
        case QXmlStreamReader::Comment:
        case QXmlStreamReader::EndElement:
        case QXmlStreamReader::Characters:
            break;
        default:
            reader.raiseError(msgUnexpectedToken());
            break;
        }
    }
}
Example #5
0
bool PlatformInfo::ParseXml(QXmlStreamReader& xml)
{
	Clear();

	bool foundName = false;
	bool foundVersion = false;

	while (!xml.atEnd())
	{
		QXmlStreamReader::TokenType nextToken = xml.readNext();

		if (nextToken == QXmlStreamReader::StartElement)
		{
			if (xml.name() == "name")
			{
				if (foundName)
				{
					Alerts::DisplayError("Found multiple <name> elements in <platform>.");
					return (false);
				}

				foundName = true;

				name = xml.readElementText();
			}
			else if (xml.name() == "version")
			{
				if (foundVersion)
				{
					Alerts::DisplayError("Found multiple <version> elements in <platform>.");
					return (false);
				}

				foundVersion = true;

				version = xml.readElementText();
			}
			else
			{
				Alerts::DisplayError(QString("<%1> is not a valid child of <platform>.").arg(xml.name().toString()));
				return (false);
			}
		}
		else if (nextToken == QXmlStreamReader::EndElement)
		{
			if (xml.name() == "platform")
			{
				if (foundName && foundVersion)
				{
					return (true);
				}
				else
				{
					Alerts::DisplayError("Required elements are missing from <platform>.");
					return (false);
				}
			}
		}
		else
		{
			if (!(nextToken == QXmlStreamReader::Characters && xml.isWhitespace()))
			{
				Alerts::DisplayError("Unexpected token found in <platform>.");
				return (false);
			}
		}
	}

	return (false);
}
Example #6
0
/** Reads a string from current XML element. */
QString PwStreamUtilsV4::readString(QXmlStreamReader& xml) {
    return xml.readElementText();
}
Example #7
0
TrainingSetFile::TSFResult TrainingSetFile::fromFile(QFile &file)
{
	QString
			version,
			text;

	QStringRef name;

	QXmlStreamReader tsReadXML;

	QXmlStreamReader::TokenType tt;
	QStringList textElements;
	QXmlStreamAttributes attributes;

	TrainingSetFile *retTSF = new TrainingSetFile();
	TSFResult res = {retTSF, true, NoError, "", 0};

	TrainingSet *ts = retTSF->getTrainingSet();

	int
			lastPatternIndex = 0,
			sTextElements,
			pSize = 0,
			iSize = 0,
			tSize = 0;

	Normalization
			*inor = new Normalization(),
			*tnor = new Normalization();

	vector<vector<double> >
			inputs,
			targets;

	DataRepresentation
			*idr = ts->getInputsDataRepresentation(),
			*tdr = ts->getTargetsDataRepresentation();

	if(file.open(QIODevice::ReadOnly)){
		tsReadXML.setDevice(&file);
		while (!tsReadXML.atEnd()) {
			tt = tsReadXML.readNext();

			if(tsReadXML.hasError()){
				file.close();
				return {retTSF, false, toTSFError(tsReadXML.error()), tsReadXML.errorString(), tsReadXML.lineNumber()};
			}

			if(tt == QXmlStreamReader::StartDocument){
				continue;
			}else if(tt == QXmlStreamReader::StartElement){
				name = tsReadXML.name();
				if(name == STR_TRAININGSET){
					attributes = tsReadXML.attributes();
					if(attributes.hasAttribute(STR_PATTERNSIZE) &&
					   attributes.hasAttribute(STR_INPUTSSIZE) &&
					   attributes.hasAttribute(STR_TARGETSSIZE))
					{
						pSize = attributes.value(STR_PATTERNSIZE).toInt();
						iSize = attributes.value(STR_INPUTSSIZE).toInt();
						tSize = attributes.value(STR_TARGETSSIZE).toInt();

						inputs = vector<vector<double> >(pSize, vector<double>(iSize, 0));
						targets = vector<vector<double> >(pSize, vector<double>(tSize, 0));
					}else{
						file.close();
						return {
							retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_PATTERNSIZE + ", " + STR_INPUTSSIZE + ", " + STR_TARGETSSIZE + ") on tag " + STR_TRAININGSET, tsReadXML.lineNumber()
						};
					}
				}else if(name == STR_PROPERTIES){
					attributes = tsReadXML.attributes();
					if(attributes.hasAttribute(STR_VERSION)){
						version = attributes.value(STR_VERSION).toString();
					}else{
						file.close();
						return
						{
							retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_VERSION + ") on tag " + STR_PROPERTIES, tsReadXML.lineNumber()
						};
					}
				}else if(name == STR_INPUTSDATAREPRESENTATION){
					attributes = tsReadXML.attributes();
					if(attributes.hasAttribute(STR_NAME) &&
					   attributes.hasAttribute(STR_WIDTH) &&
					   attributes.hasAttribute(STR_HEIGHT) &&
					   attributes.hasAttribute(STR_FORMAT))
					{
						idr->setType(drFromStrToInt(attributes.value(STR_NAME).toString()));
						idr->setWidth(attributes.value(STR_WIDTH).toInt());
						idr->setHeight(attributes.value(STR_HEIGHT).toInt());
						idr->setImageFormat(fromStrToImgFormat(attributes.value(STR_FORMAT).toString()));
					}else{
						file.close();
						return
						{
							retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_NAME + ", " + STR_WIDTH + ", " + STR_HEIGHT + ", " + STR_FORMAT + ") on tag " + STR_INPUTSDATAREPRESENTATION, tsReadXML.lineNumber()
						};
					}
				}else if(name == STR_TARGETSDATAREPRESENTATION){
					attributes = tsReadXML.attributes();
					if(attributes.hasAttribute(STR_NAME) &&
					   attributes.hasAttribute(STR_WIDTH) &&
					   attributes.hasAttribute(STR_HEIGHT) &&
					   attributes.hasAttribute(STR_FORMAT))
					{
						tdr->setType(drFromStrToInt(attributes.value(STR_NAME).toString()));
						tdr->setWidth(attributes.value(STR_WIDTH).toInt());
						tdr->setHeight(attributes.value(STR_HEIGHT).toInt());
						tdr->setImageFormat(fromStrToImgFormat(attributes.value(STR_FORMAT).toString()));
					}else{
						file.close();
						return
						{
							retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_NAME + ", " + STR_WIDTH + ", " + STR_HEIGHT + ", " + STR_FORMAT + ") on tag " + STR_TARGETSDATAREPRESENTATION, tsReadXML.lineNumber()
						};
					}
				}else if(name == STR_INPUTSNORMALIZATION){
					attributes = tsReadXML.attributes();
					if(attributes.hasAttribute(STR_TYPE) &&
					   attributes.hasAttribute(STR_MAXVALUE) &&
					   attributes.hasAttribute(STR_MINVALUE) &&
					   attributes.hasAttribute(STR_THRESHOLD) &&
					   attributes.hasAttribute(STR_AMPLITUDE) &&
					   attributes.hasAttribute(STR_ELONGATION))
					{
						inor->setType(normFromStrToInt(attributes.value(STR_TYPE).toString()));
						inor->setMaxValue(attributes.value(STR_MAXVALUE).toDouble());
						inor->setMinValue(attributes.value(STR_MINVALUE).toDouble());
						inor->setThreshold(attributes.value(STR_THRESHOLD).toDouble());
						inor->setAmplitude(attributes.value(STR_AMPLITUDE).toDouble());
						inor->setElongation(attributes.value(STR_ELONGATION).toDouble());
					}else{
						file.close();
						return
						{
							retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_TYPE + ", " + STR_MAXVALUE + ", " + STR_MINVALUE + ", " + STR_THRESHOLD + ", " + STR_ELONGATION + ") on tag " + STR_INPUTSNORMALIZATION, tsReadXML.lineNumber()
						};
					}
				}else if(name == STR_TARGETSNORMALIZATION){
					attributes = tsReadXML.attributes();
					if(attributes.hasAttribute(STR_TYPE) &&
					   attributes.hasAttribute(STR_MAXVALUE) &&
					   attributes.hasAttribute(STR_MINVALUE) &&
					   attributes.hasAttribute(STR_THRESHOLD) &&
					   attributes.hasAttribute(STR_AMPLITUDE) &&
					   attributes.hasAttribute(STR_ELONGATION))
					{
						tnor->setType(normFromStrToInt(attributes.value(STR_TYPE).toString()));
						tnor->setMaxValue(attributes.value(STR_MAXVALUE).toDouble());
						tnor->setMinValue(attributes.value(STR_MINVALUE).toDouble());
						tnor->setThreshold(attributes.value(STR_THRESHOLD).toDouble());
						tnor->setAmplitude(attributes.value(STR_AMPLITUDE).toDouble());
						tnor->setElongation(attributes.value(STR_ELONGATION).toDouble());
					}else{
						file.close();
						return
						{
							retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_TYPE + ", " + STR_MAXVALUE + ", " + STR_MINVALUE + ", " + STR_THRESHOLD + ", " + STR_ELONGATION + ") on tag " + STR_TARGETSNORMALIZATION, tsReadXML.lineNumber()
						};
					}
				}else if(name == STR_PATTERN){
					attributes = tsReadXML.attributes();
					if(attributes.hasAttribute(STR_INDEX))
					{
						lastPatternIndex = attributes.value(STR_INDEX).toInt();
					}else{
						file.close();
						return
						{
							retTSF, false, NotWellFormedError, "NotWellFormedError: Missing attributes (" + STR_INDEX + ") on tag " + STR_PATTERN, tsReadXML.lineNumber()
						};
					}
				}else if(name == STR_INPUTS){
					text = tsReadXML.readElementText(QXmlStreamReader::SkipChildElements);
					textElements = text.split(STR_SEPARATOR, QString::KeepEmptyParts, Qt::CaseInsensitive);
					sTextElements = textElements.size();
					if(sTextElements == iSize){
						for(int i = 0; i < sTextElements; i++){
							inputs[lastPatternIndex][i] = textElements[i].toDouble();
						}
					}else{
						file.close();
						return
						{
							retTSF, false, NotWellFormedError, "NotWellFormedError: Incongruence between reported input size with found inputs elements", tsReadXML.lineNumber()
						};
					}
				}else if(name == STR_TARGETS){
					text = tsReadXML.readElementText(QXmlStreamReader::SkipChildElements);
					textElements = text.split(STR_SEPARATOR, QString::KeepEmptyParts, Qt::CaseInsensitive);
					sTextElements = textElements.size();
					if(sTextElements == tSize){
						for(int t = 0; t < sTextElements; t++){
							targets[lastPatternIndex][t] = textElements[t].toDouble();
						}
					}else{
						file.close();
						return
						{
							retTSF, false, NotWellFormedError, "NotWellFormedError: Incongruence between reported target size with found target elements", tsReadXML.lineNumber()
						};
					}
				}
			}
		}

		retTSF->setFileName(file.fileName());
		res.file = retTSF;

		ts->setPatternCount(pSize);
		ts->setInputs(inputs, iSize);
		ts->setTargets(targets, tSize);
		ts->setInputsNormalization(inor);
		ts->setTargetsNormalization(tnor);
		ts->setInputsDataRepresentation(idr);
		ts->setTargetsDataRepresentation(tdr);

		res.sucess = true;
		res.errnum = toTSFError(QXmlStreamReader::NoError);
		res.errormsg = "";
		res.line = -1;

		file.close();
		return res;
	}else{
		file.close();
		return
		{
			retTSF, false, toTSFError(file.error()), file.errorString(), -1
		};
	}
}
Example #8
0
/** Reads a Base-64 encoded UUID from current XML element; in case of error returns in case of error returns default (all-zero) UUID. */
PwUuid PwStreamUtilsV4::readUuid(QXmlStreamReader& xml) {
    QString base64Str = xml.readElementText();
    PwUuid result = PwUuid::fromBase64(base64Str);
    Util::safeClear(base64Str);
    return result;
}
Example #9
0
/** Reads a Base-64 encoded data array from current XML element; in case of error returns an empty array. */
QByteArray PwStreamUtilsV4::readBase64(QXmlStreamReader& xml) {
    QByteArray base64Str = xml.readElementText().toLatin1();
    QByteArray result = QByteArray::fromBase64(base64Str);
    Util::safeClear(base64Str);
    return result;
}
Example #10
0
void
CoverFetchArtPayload::prepareDiscogsUrls( QXmlStreamReader &xml )
{
    while( !xml.atEnd() && !xml.hasError() )
    {
        xml.readNext();
        if( !xml.isStartElement() || xml.name() != "release" )
            continue;

        const QString releaseId = xml.attributes().value( "id" ).toString();
        while( !xml.atEnd() && !xml.hasError() )
        {
            xml.readNext();
            const QStringRef &n = xml.name();
            if( xml.isEndElement() && n == "release" )
                break;
            if( !xml.isStartElement() )
                continue;

            CoverFetch::Metadata metadata;
            metadata[ "source" ] = "Discogs";
            if( n == "title" )
                metadata[ "title" ] = xml.readElementText();
            else if( n == "country" )
                metadata[ "country" ] = xml.readElementText();
            else if( n == "released" )
                metadata[ "released" ] = xml.readElementText();
            else if( n == "notes" )
                metadata[ "notes" ] = xml.readElementText();
            else if( n == "images" )
            {
                while( !xml.atEnd() && !xml.hasError() )
                {
                    xml.readNext();
                    if( xml.isEndElement() && xml.name() == "images" )
                        break;
                    if( !xml.isStartElement() )
                        continue;
                    if( xml.name() == "image" )
                    {
                        const QXmlStreamAttributes &attr = xml.attributes();
                        const KUrl thburl( attr.value( "uri150" ).toString() );
                        const KUrl uri( attr.value( "uri" ).toString() );
                        const KUrl url = (m_size == CoverFetch::ThumbSize) ? thburl : uri;
                        if( !url.isValid() )
                            continue;

                        metadata[ "releaseid"    ] = releaseId;
                        metadata[ "releaseurl"   ] = "http://discogs.com/release/" + releaseId;
                        metadata[ "normalarturl" ] = uri.url();
                        metadata[ "thumbarturl"  ] = thburl.url();
                        metadata[ "width"        ] = attr.value( "width"  ).toString();
                        metadata[ "height"       ] = attr.value( "height" ).toString();
                        metadata[ "type"         ] = attr.value( "type"   ).toString();
                        m_urls.insert( url, metadata );
                    }
                    else
                        xml.skipCurrentElement();
                }
            }
            else
                xml.skipCurrentElement();
        }
    }
}
Example #11
0
void PlcSrConfig::loadPlcConfig()
{
    QString fileName = "PlcSrConfig.xml";
    QFile file(fileName);
    if (false==file.open(QFile::ReadOnly | QFile::Text))
    {
        return;
    }
    else
    {
        QXmlStreamReader reader;
        reader.setDevice(&file);
        while (false==reader.atEnd())
        {
            reader.readNext();
            if(reader.isStartElement())
            {
                if((reader.name()=="plc")&&(reader.attributes().hasAttribute("ID")))
                {
                    QStringRef Temp=reader.attributes().value("ID");
                    plcName=Temp.toString();
                    if((false==plcList.contains(plcName))&&(false==plcName.isEmpty()))
                    {   //可能有重名的传感器不重复添加,传感器名为空也不添加
                        plcNameMap[plcName]=plcName;
                        plcList.append(plcName);
                        this->ui->nameCbBox->addItem(plcName);
                        qDebug()<<plcName<<"传感器配置中...";
                    } else
                        qDebug()<<plcName<<"传感器已存在...";
                } else if(reader.name()=="name")
                {
                    plcName=reader.readElementText();
                    if((false==plcList.contains(plcName))&&(false==plcName.isEmpty()))
                    {   //可能有重名的传感器不重复添加,传感器名为空也不添加
                        plcNameMap[plcName]=plcName;
                        plcList.append(plcName);
                        this->ui->nameCbBox->addItem(plcName);
                        qDebug()<<plcName<<"传感器配置中...";
                    } else
                        qDebug()<<plcName<<"传感器已配置完成...";
                }
                else if(reader.name()=="portId")
                {
                    portId=reader.readElementText();
                    portIdMap[plcName]=portId;
                    if((false==portIdList.contains(portId))&&(false==portId.isEmpty()))
                    {   //可能有有复用同一端口的传感器不重复添加,为空也不添加
                        portIdList.append(portId);
                        this->ui->portIdCbBox->addItem(portId);
                    } else
                        qDebug()<<"已添加过端口"<<portId;
                } else if(reader.name()=="baudRate")
                {
                    baudRate=reader.readElementText();
                    baudRateMap[plcName]=baudRate;
                } else if(reader.name()== "dataBits")
                {
                    dataBits=reader.readElementText();
                    dataBitsMap[plcName]=dataBits;
                } else if(reader.name()=="parity")
                {
                    parity=reader.readElementText();
                    parityMap[plcName]=parity;
                } else if(reader.name()=="stopBits")
                {
                    stopBits=reader.readElementText();
                    stopBitsMap[plcName]=stopBits;
                } else if(reader.name()=="rwDelay")
                {
                    rwDelay=reader.readElementText();
                    rwDelayMap[plcName]=rwDelay;
                } else if(reader.name()=="type")
                {
                    type=reader.readElementText();
                    typeMap[plcName]=type;
                } else if(reader.name()=="rwLen")
                {
                    rwLen=reader.readElementText();
                    rwLenMap[plcName]=rwLen;
                }
                else
                {
                    qDebug()<<"本地配置读取进行中...";
                }
            }
        }
    }
    qDebug()<<"本地配置读取完成";
    setPlcSensor(plcName);//配置界面为最后添加的传感器
    file.close();
}
Example #12
0
bool Document::loadMOJ(QString fileName)
{
  QFile file(fileName);
  if (!file.open(QIODevice::ReadOnly))
  {
    return false;
  }

  QXmlStreamReader reader;

  // check if it is a gzipped moj
  QByteArray s = file.read(2);
  if (s.size() == 2)
  {
    if (s.at(0) == static_cast<char>(0x1f) && s.at(1) == static_cast<char>(0x8b))
    {
      // this is a gzipped file
      file.reset();
      QByteArray compressedData = file.readAll();
      QByteArray uncompressedData;
      if (!QCompressor::gzipDecompress(compressedData, uncompressedData))
      {
        return false;
      }
      reader.addData(uncompressedData);
    }
    else
    {
      file.reset();
      reader.setDevice(&file);
    }
  }
  else
  {
    return false;
  }

  pages.clear();

  int strokeCount = 0;

  while (!reader.atEnd())
  {
    reader.readNext();
    if (reader.name() == "MrWriter" && reader.tokenType() == QXmlStreamReader::StartElement)
    {
      QXmlStreamAttributes attributes = reader.attributes();
      QStringRef docversion = attributes.value("document-version");
      if (docversion.toInt() > DOC_VERSION)
      {
        // TODO warn about newer document version
      }
    }
    if (reader.name() == "page" && reader.tokenType() == QXmlStreamReader::StartElement)
    {
      QXmlStreamAttributes attributes = reader.attributes();
      QStringRef width = attributes.value("", "width");
      QStringRef height = attributes.value("", "height");
      Page newPage;
      newPage.setWidth(width.toDouble());
      newPage.setHeight(height.toDouble());

      pages.append(newPage);
    }
    if (reader.name() == "background" && reader.tokenType() == QXmlStreamReader::StartElement)
    {
      QXmlStreamAttributes attributes = reader.attributes();
      QStringRef color = attributes.value("", "color");
      QColor newColor = stringToColor(color.toString());
      pages.last().setBackgroundColor(newColor);
    }
    if (reader.name() == "stroke" && reader.tokenType() == QXmlStreamReader::StartElement)
    {
      QXmlStreamAttributes attributes = reader.attributes();
      QStringRef tool = attributes.value("", "tool");
      if (tool == "pen")
      {
        Stroke newStroke;
        newStroke.pattern = MrDoc::solidLinePattern;
        QStringRef color = attributes.value("", "color");
        newStroke.color = stringToColor(color.toString());
        QStringRef style = attributes.value("", "style");
        if (style.toString().compare("solid") == 0)
        {
          newStroke.pattern = MrDoc::solidLinePattern;
        }
        else if (style.toString().compare("dash") == 0)
        {
          newStroke.pattern = MrDoc::dashLinePattern;
        }
        else if (style.toString().compare("dashdot") == 0)
        {
          newStroke.pattern = MrDoc::dashDotLinePattern;
        }
        else if (style.toString().compare("dot") == 0)
        {
          newStroke.pattern = MrDoc::dotLinePattern;
        }
        else
        {
          newStroke.pattern = MrDoc::solidLinePattern;
        }
        QStringRef strokeWidth = attributes.value("", "width");
        newStroke.penWidth = strokeWidth.toDouble();
        QString elementText = reader.readElementText();
        QStringList elementTextList = elementText.trimmed().split(" ");
        for (int i = 0; i + 1 < elementTextList.size(); i = i + 2)
        {
          newStroke.points.append(QPointF(elementTextList.at(i).toDouble(), elementTextList.at(i + 1).toDouble()));
        }
        QStringRef pressures = attributes.value("pressures");
        QStringList pressuresList = pressures.toString().trimmed().split(" ");
        for (int i = 0; i < pressuresList.length(); ++i)
        {
          if (pressuresList.length() == 0)
          {
            newStroke.pressures.append(1.0);
          }
          else
          {
            newStroke.pressures.append(pressuresList.at(i).toDouble());
          }
        }
        if (newStroke.pressures.size() != newStroke.points.size())
        {
          return false;
        }
        pages.last().appendStroke(newStroke);
        strokeCount++;
        qDebug() << strokeCount;
      }
    }
  }

  QFileInfo fileInfo(file);
  file.close();

  for (auto &page : pages)
  {
    page.clearDirtyRect();
  }

  if (reader.hasError())
  {
    return false;
  }
  else
  {
    m_path = fileInfo.absolutePath();
    m_docName = fileInfo.completeBaseName();
    return true;
  }
}
Example #13
0
void AdvancedSettings::loadSettings()
{
    qDebug() << "Loading advanced settings";
    reset();

    QXmlStreamReader xml;
    QFile file(Settings::applicationDir() + "/advancedsettings.xml");
    if (!file.exists())
        file.setFileName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/advancedsettings.xml");

    if (!file.exists())
        return;

    if (!file.open(QIODevice::ReadOnly))
        return;
    xml.addData(file.readAll());
    file.close();

    if (!xml.readNextStartElement() || xml.name().toString() != "advancedsettings")
        return;

    while (xml.readNextStartElement()) {
        if (xml.name() == "log")
            loadLog(xml);
        else if (xml.name() == "gui")
            loadGui(xml);
        else if (xml.name() == "sorttokens")
            loadSortTokens(xml);
        else if (xml.name() == "genres")
            loadGenreMappings(xml);
        else if (xml.name() == "fileFilters")
            loadFilters(xml);
        else if (xml.name() == "audioCodecs")
            loadAudioCodecMappings(xml);
        else if (xml.name() == "videoCodecs")
            loadVideoCodecMappings(xml);
        else if (xml.name() == "certifications")
            loadCertificationMappings(xml);
        else if (xml.name() == "studios")
            loadStudioMappings(xml);
        else if (xml.name() == "countries")
            loadCountryMappings(xml);
        else if (xml.name() == "portableMode")
            m_portableMode = (xml.readElementText() == "true");
        else
            xml.skipCurrentElement();
    }

    qDebug() << "Advanced settings";
    qDebug() << "    debugLog              " << m_debugLog;
    qDebug() << "    logFile               " << m_logFile;
    qDebug() << "    forceCache            " << m_forceCache;
    qDebug() << "    sortTokens            " << m_sortTokens;
    qDebug() << "    genreMappings         " << m_genreMappings;
    qDebug() << "    movieFilters          " << m_movieFilters;
    qDebug() << "    concertFilters        " << m_concertFilters;
    qDebug() << "    tvShowFilters         " << m_tvShowFilters;
    qDebug() << "    subtitleFilters       " << m_subtitleFilters;
    qDebug() << "    audioCodecMappings    " << m_audioCodecMappings;
    qDebug() << "    videoCodecMappings    " << m_videoCodecMappings;
    qDebug() << "    certificationMappings " << m_certificationMappings;
    qDebug() << "    studioMappings        " << m_studioMappings;
    qDebug() << "    useFirstStudioOnly    " << m_useFirstStudioOnly;
    qDebug() << "    countryMappings       " << m_countryMappings;
}
Example #14
0
/*!
    \internal
*/
void PluginSpecPrivate::readPluginSpec(QXmlStreamReader &reader)
{
    QString element = reader.name().toString();
    if (element != QLatin1String(PLUGIN)) {
        reader.raiseError(QCoreApplication::translate("PluginSpec", "Expected element '%1' as top level element")
                          .arg(QLatin1String(PLUGIN)));
        return;
    }
    name = reader.attributes().value(QLatin1String(PLUGIN_NAME)).toString();
    if (name.isEmpty()) {
        reader.raiseError(msgAttributeMissing(PLUGIN, PLUGIN_NAME));
        return;
    }
    version = reader.attributes().value(QLatin1String(PLUGIN_VERSION)).toString();
    if (version.isEmpty()) {
        reader.raiseError(msgAttributeMissing(PLUGIN, PLUGIN_VERSION));
        return;
    }
    if (!isValidVersion(version)) {
        reader.raiseError(msgInvalidFormat(PLUGIN_VERSION));
        return;
    }
    compatVersion = reader.attributes().value(QLatin1String(PLUGIN_COMPATVERSION)).toString();
    if (!compatVersion.isEmpty() && !isValidVersion(compatVersion)) {
        reader.raiseError(msgInvalidFormat(PLUGIN_COMPATVERSION));
        return;
    } else if (compatVersion.isEmpty()) {
        compatVersion = version;
    }
    disabledByDefault = readBooleanValue(reader, PLUGIN_DISABLED_BY_DEFAULT);
    experimental = readBooleanValue(reader, PLUGIN_EXPERIMENTAL);
    if (reader.hasError())
        return;
    if (experimental)
        disabledByDefault = true;
    enabledInSettings = !disabledByDefault;
    while (!reader.atEnd()) {
        reader.readNext();
        switch (reader.tokenType()) {
        case QXmlStreamReader::StartElement:
            element = reader.name().toString();
            if (element == QLatin1String(VENDOR))
                vendor = reader.readElementText().trimmed();
            else if (element == QLatin1String(COPYRIGHT))
                copyright = reader.readElementText().trimmed();
            else if (element == QLatin1String(LICENSE))
                license = reader.readElementText().trimmed();
            else if (element == QLatin1String(DESCRIPTION))
                description = reader.readElementText().trimmed();
            else if (element == QLatin1String(URL))
                url = reader.readElementText().trimmed();
            else if (element == QLatin1String(CATEGORY))
                category = reader.readElementText().trimmed();
            else if (element == QLatin1String(DEPENDENCYLIST))
                readDependencies(reader);
            else if (element == QLatin1String(ARGUMENTLIST))
                readArgumentDescriptions(reader);
            else
                reader.raiseError(msgInvalidElement(name));
            break;
        case QXmlStreamReader::EndDocument:
        case QXmlStreamReader::Comment:
        case QXmlStreamReader::EndElement:
        case QXmlStreamReader::Characters:
            break;
        default:
            reader.raiseError(msgUnexpectedToken());
            break;
        }
    }
}
Example #15
0
bool Syntax::load(QString file)
{
	if(xmlSyntaxFileName==file)
		return true;
	else xmlSyntaxFileName=file;
	printf("[Syntax::load] Loading syntax\n");
	QXmlStreamReader xml;
	QStack <QString> stack;
	QFile fileDevice(file);
	if (!fileDevice.open(QFile::ReadOnly | QFile::Text)) {
	         printf("Error al abrir el archivo\n");
	         return false;
	}
	
	highlightingRules.clear();
	highlightingBlockRules.clear();
	highlightingBracketsRules.clear();
	
	xml.setDevice(&fileDevice);
	
	QMap <QString,QString> values;
	
	QVector<QString> xmlMainItems;
	xmlMainItems << "item" << "block" << "bracket";
	
	int ruleOrder=0;
	
	while (!xml.atEnd())
	{
		QXmlStreamReader::TokenType tokenType=xml.readNext();
		switch(tokenType)
		{
			case QXmlStreamReader::StartElement:
				if(xml.name()!="syntax")
				{
					if( xmlMainItems.contains(xml.name().toString()) )
						stack.push(xml.name().toString());
					else
						values[xml.name().toString()]=xml.readElementText().trimmed();
				}
			break;
			case QXmlStreamReader::EndElement:
				if(stack.isEmpty()) break;
				QString name=stack.top();
				if(name==xml.name()) stack.pop();
				if(stack.isEmpty())
				{
					QTextCharFormat format;
					if(values.contains("bold") && values["bold"]=="true") format.setFontWeight(QFont::Bold);
					if(values.contains("underline") && values["underline"]=="true") format.setFontUnderline(true);
					if(values.contains("italic") && values["italic"]=="true") format.setFontItalic(true);
					if(values.contains("foreground")) format.setForeground(QBrush(QColor(values["foreground"])));
					if(values.contains("background")) format.setBackground(QBrush(QColor(values["background"])));
					if(name=="item")
					{
						HighlightingRule rule;
						rule.format=format;
						rule.pattern=QRegExp(values["pattern"]);
						rule.ruleOrder=ruleOrder++;
						highlightingRules.append(rule);
						values.clear();
					}
					else if(name=="block" || name=="bracket")
					{
						HighlightingBlockRule rule;
						rule.format=format;
						rule.startPattern=QRegExp(values["startPattern"]);
						rule.endPattern=QRegExp(values["endPattern"]);
						rule.ruleOrder=ruleOrder++;
						if(name=="block") highlightingBlockRules.append(rule);
						else highlightingBracketsRules.append(rule); //Bracket rule
						values.clear();
					}
				}
			break;
		}
	}
	if (xml.hasError())
	{
		// do error handling
		printf("Error %s: %ld:%ld %s\n", file.toLocal8Bit().data(), xml.lineNumber(), xml.columnNumber(), xml.errorString().toLocal8Bit().data() );
		return false;
	}
	
	return true;
}
Example #16
0
MainWindow::MainWindow(Manager *man, QWidget *parent) : QMainWindow(parent), manager(man), nbElementsAffichablesPile(1)
{

    pile = manager->getPile();

    QXmlStreamReader xmlReader3;
    QFile filePile3("parametres.xml");
    filePile3.open(QFile::ReadOnly);
    xmlReader3.setDevice(&filePile3);



    xmlReader3.readNext();
    QString valeur;


    while(!xmlReader3.atEnd() && !xmlReader3.hasError()) {

            QXmlStreamReader::TokenType token = xmlReader3.readNext();

            if(token == QXmlStreamReader::StartDocument) {
                    continue;
            }

            if(token == QXmlStreamReader::StartElement) {

                    if(xmlReader3.name() == "clavierVisible") {
                            xmlReader3.readElementText();
                    }

                    if(xmlReader3.name() == "valeur") {
                         valeur= xmlReader3.readElementText();
                         if(valeur=="1")
                             clavierVisible=true;
                         else
                             clavierVisible=false;
                    }

                    if(xmlReader3.name() == "nbElementsVisiblesPile") {
                           xmlReader3.readElementText();
                    }

                    if(xmlReader3.name() == "valeur") {

                        valeur = xmlReader3.readElementText();
                        nbElementsAffichablesPile = valeur.toInt();

                    }
            }
    }

    //paramètres d'affichage
    QMenu *menuAfficher = menuBar()->addMenu("&Afficher");
    actionAfficherClavier = new QAction("&Afficher le clavier", this);
    actionAfficherClavier->setCheckable(true);
    actionAfficherClavier->setChecked(true);

    QAction* actionNbElementsPile = new QAction("&Modifier le nombre d'élements affichables dans la pile", this);

    menuAfficher->addAction(actionAfficherClavier);
    menuAfficher->addAction(actionNbElementsPile);

    QObject::connect(actionAfficherClavier, SIGNAL(toggled(bool)), this, SLOT(afficherClavier(bool)));
    QObject::connect(actionNbElementsPile, SIGNAL(triggered(bool)), this, SLOT(modifierNbElementsAffichesPile()));


    // Général
    QHBoxLayout *mainLayout= new QHBoxLayout();
    tabWidget = new QTabWidget();
    QVBoxLayout *verticalLayout = new QVBoxLayout();
    layoutClavier = new QGridLayout;

    //Vue de la pile (gauche)
    QListView *vuePile = new QListView();
    vuePile->setGeometry(0,0,100,300);

    //Vue de l'historique de commandes (droite)
    QTextEdit *vueHistoriqueCommandes = new QTextEdit();
    inputLine = new QLineEdit();

    //Clavier numérique
    QSignalMapper *signalMapper = new QSignalMapper(this);

    QPushButton *bouton1= new QPushButton();
    bouton1->setText("1");
    connect(bouton1, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(bouton1, "1");

    QPushButton *bouton2= new QPushButton();
    bouton2->setText("2");
    connect(bouton2, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(bouton2, "2");

    QPushButton *bouton3= new QPushButton();
    bouton3->setText("3");
    connect(bouton3, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(bouton3, "3");

    QPushButton *bouton4= new QPushButton();
    bouton4->setText("4");
    connect(bouton4, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(bouton4, "4");

    QPushButton *bouton5= new QPushButton();
    bouton5->setText("5");
    connect(bouton5, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(bouton5, "5");

    QPushButton *bouton6= new QPushButton();
    bouton6->setText("6");
    connect(bouton6, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(bouton6, "6");

    QPushButton *bouton7= new QPushButton();
    bouton7->setText("7");
    connect(bouton7, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(bouton7, "7");

    QPushButton *bouton8= new QPushButton();
    bouton8->setText("8");
    connect(bouton8, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(bouton8, "8");

    QPushButton *bouton9= new QPushButton();
    bouton9->setText("9");
    connect(bouton9, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(bouton9, "9");

    QPushButton *boutonEspace= new QPushButton();
    boutonEspace->setText("");
    connect(boutonEspace, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(boutonEspace, " ");

    QPushButton *boutonAddition= new QPushButton();
    boutonAddition->setText("+");
    connect(boutonAddition, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(boutonAddition, "+");

    QPushButton *boutonSoustraction= new QPushButton();
    boutonSoustraction->setText("-");
    connect(boutonSoustraction, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(boutonSoustraction, "-");

    QPushButton *boutonMulitplication= new QPushButton();
    boutonMulitplication->setText("*");
    connect(boutonMulitplication, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(boutonMulitplication, "*");

    QPushButton *boutonDivision= new QPushButton();
    boutonDivision->setText("/");
    connect(boutonDivision, SIGNAL(clicked()), signalMapper, SLOT(map()));
    signalMapper->setMapping(boutonDivision, "/");


    connect(signalMapper, SIGNAL(mapped(QString)), this, SLOT(appendInputKeyboard(QString)));


    QPushButton *boutonEntree= new QPushButton();
    boutonEntree->setText("Entrée");
    connect(boutonEntree, SIGNAL(clicked()), this, SLOT(returnPressedStr()));

    QVBoxLayout *layoutOperateurs = new QVBoxLayout();
    layoutOperateurs->addWidget(boutonAddition);
    layoutOperateurs->addWidget(boutonSoustraction);
    layoutOperateurs->addWidget(boutonMulitplication);
    layoutOperateurs->addWidget(boutonDivision);
    layoutOperateurs->addWidget(boutonEntree);



    //Crée un layout contenant le clavier numérique

    layoutClavier->addWidget(bouton1, 0,0);
    layoutClavier->addWidget(bouton2, 0,1);
    layoutClavier->addWidget(bouton3, 0,2);
    layoutClavier->addWidget(bouton4, 1,0);
    layoutClavier->addWidget(bouton5, 1,1);
    layoutClavier->addWidget(bouton6, 1,2);
    layoutClavier->addWidget(bouton7, 2,0);
    layoutClavier->addWidget(bouton8, 2,1);
    layoutClavier->addWidget(bouton9, 2,2);
    layoutClavier->addWidget(boutonEspace,3,0,1,3);
    layoutClavier->addLayout(layoutOperateurs, 0,3,4,1);

    conteneurClavier = new QWidget();
    conteneurClavier->setLayout(layoutClavier);

    //Crée un layout avec l'historique de commandes, la zone d'entrée et le clavier
    verticalLayout->addWidget(vueHistoriqueCommandes);
    verticalLayout->addWidget(inputLine);
    verticalLayout->addWidget(conteneurClavier);

    //Assemble les layouts
    mainLayout->addWidget(vuePile);
    mainLayout->addLayout(verticalLayout);


    QWidget* tab1 = new QWidget();
    tab1->setLayout(mainLayout);
    tabWidget->addTab(tab1, "Principal");

    QObject::connect(inputLine, SIGNAL(textChanged(QString)), this, SLOT(interpreter(QString))) ;
    QObject::connect(inputLine,SIGNAL(returnPressed()), this, SLOT(returnPressedStr()));

    pile->setView(vuePile);









    //---------------------------------TAB2--------------------------------------------


    QHBoxLayout *layoutProgramme = new QHBoxLayout();
    QVBoxLayout *layoutEditionProgramme = new QVBoxLayout();
    QHBoxLayout *layoutBoutonsProgramme = new QHBoxLayout();

    listeProgrammes = new QListView();

    zoneProgramme = new QTextEdit();
    zoneIdentifiant = new QLineEdit();
    boutonValider = new QPushButton("Ajouter");
    boutonEffacer = new QPushButton("Effacer");
    boutonModifier = new QPushButton("Modifier");
    boutonSupprimer = new QPushButton("Supprimer");
    boutonSupprimer->setEnabled(false);
    boutonModifier->setEnabled(false);



   layoutBoutonsProgramme->addWidget(boutonValider);
   layoutBoutonsProgramme->addWidget(boutonEffacer);
   layoutBoutonsProgramme->addWidget(boutonModifier);
   layoutBoutonsProgramme->addWidget(boutonSupprimer);


   layoutEditionProgramme->addWidget(zoneProgramme);
   layoutEditionProgramme->addWidget(zoneIdentifiant);
   layoutEditionProgramme->addLayout(layoutBoutonsProgramme);

   layoutProgramme->addLayout(layoutEditionProgramme);
   layoutProgramme->addWidget(listeProgrammes);

   QWidget* tab2 = new QWidget();

   tab2->setLayout(layoutProgramme);

   tabWidget->addTab(tab2, "Programmes");



   QXmlStreamReader xmlReader;
   QFile fileProgramme("programmes.xml");
   fileProgramme.open(QFile::ReadOnly);
   xmlReader.setDevice(&fileProgramme);



   xmlReader.readNext();
   QString strIdentifiant;
   QString str;
   while(!xmlReader.atEnd() && !xmlReader.hasError()) {

           QXmlStreamReader::TokenType token = xmlReader.readNext();

           if(token == QXmlStreamReader::StartDocument) {
                   continue;
           }

           if(token == QXmlStreamReader::StartElement) {

                   if(xmlReader.name() == "identifiant") {
                           strIdentifiant= xmlReader.readElementText();
                   }

                   if(xmlReader.name() == "string") {
                        str= xmlReader.readElementText();
                        manager->insererProgramme(strIdentifiant, str);
                   }
           }
   }

   QStringList* listeProgrammesStr = manager->getListProgrammes();

   modeleProgrammes = new QStringListModel(*listeProgrammesStr, this);

   listeProgrammes->setEditTriggers(QAbstractItemView::NoEditTriggers);
   listeProgrammes->setModel(modeleProgrammes);



   fileProgramme.close();

   QObject::connect(boutonValider, SIGNAL(clicked(bool)), this, SLOT(ajouterProgramme()));
   QObject::connect(listeProgrammes, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(afficherProgrammeListe(QModelIndex)));
   QObject::connect(boutonEffacer, SIGNAL(clicked(bool)), this, SLOT(effacerChampsProgramme()));
   QObject::connect(boutonSupprimer, SIGNAL(clicked(bool)), this, SLOT(supprimerProgramme()));
   QObject::connect(boutonModifier, SIGNAL(clicked(bool)), this, SLOT(modifierProgramme()));




   //---------------------------------TAB3--------------------------------------------


   QHBoxLayout *layoutVariable = new QHBoxLayout();
   QVBoxLayout *layoutEditionVariable = new QVBoxLayout();
   QHBoxLayout *layoutBoutonsVariable = new QHBoxLayout();

   listeVariables = new QListView();

   zoneVariable = new QTextEdit();
   zoneIdentifiantVariable = new QLineEdit();
   boutonValiderVariable = new QPushButton("Ajouter");
   boutonEffacerVariable = new QPushButton("Effacer");
   boutonModifierVariable = new QPushButton("Modifier");
   boutonSupprimerVariable = new QPushButton("Supprimer");
   boutonSupprimerVariable->setEnabled(false);
   boutonModifierVariable->setEnabled(false);



  layoutBoutonsVariable->addWidget(boutonValiderVariable);
  layoutBoutonsVariable->addWidget(boutonEffacerVariable);
  layoutBoutonsVariable->addWidget(boutonModifierVariable);
  layoutBoutonsVariable->addWidget(boutonSupprimerVariable);


  layoutEditionVariable->addWidget(zoneVariable);
  layoutEditionVariable->addWidget(zoneIdentifiantVariable);
  layoutEditionVariable->addLayout(layoutBoutonsVariable);

  layoutVariable->addLayout(layoutEditionVariable);
  layoutVariable->addWidget(listeVariables);

  QWidget* tab3 = new QWidget();

  tab3->setLayout(layoutVariable);

  tabWidget->addTab(tab3, "Variables");



  QXmlStreamReader xmlReader2;
  QFile fileVariable("variables.xml");
  fileVariable.open(QFile::ReadOnly);
  xmlReader2.setDevice(&fileVariable);



  xmlReader2.readNext();

  while(!xmlReader2.atEnd() && !xmlReader2.hasError()) {

          QXmlStreamReader::TokenType token = xmlReader2.readNext();

          if(token == QXmlStreamReader::StartDocument) {
                  continue;
          }

          if(token == QXmlStreamReader::StartElement) {

                  if(xmlReader2.name() == "identifiant") {
                          strIdentifiant= xmlReader2.readElementText();
                  }

                  if(xmlReader2.name() == "string") {
                       str= xmlReader2.readElementText();
                       manager->insererVariable(strIdentifiant, str);
                  }
          }
  }

  QStringList* listeVariablesStr = manager->getListVariables();

  modeleVariables = new QStringListModel(*listeVariablesStr, this);

  listeVariables->setEditTriggers(QAbstractItemView::NoEditTriggers);
  listeVariables->setModel(modeleVariables);



  fileVariable.close();

  QObject::connect(boutonValiderVariable, SIGNAL(clicked(bool)), this, SLOT(ajouterVariable()));
  QObject::connect(listeVariables, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(afficherVariableListe(QModelIndex)));
  QObject::connect(boutonEffacerVariable, SIGNAL(clicked(bool)), this, SLOT(effacerChampsVariable()));
  QObject::connect(boutonSupprimerVariable, SIGNAL(clicked(bool)), this, SLOT(supprimerVariable()));
  QObject::connect(boutonModifierVariable, SIGNAL(clicked(bool)), this, SLOT(modifierVariable()));

  QObject::connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(updateTab(int)));


   setCentralWidget(tabWidget);


}
int formMergeSlideCalibrations
    ::funcReadSensitivities(
                                const QString &filePath,
                                structSlideStrSens* slideStrSens
){
    QFile *xmlFile = new QFile( filePath );
    if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text)) {
        return _ERROR;
    }
    QXmlStreamReader *xmlReader = new QXmlStreamReader(xmlFile);

    //Parse the XML until we reach end of it
    while(!xmlReader->atEnd() && !xmlReader->hasError()) {
        // Read next element
        QXmlStreamReader::TokenType token = xmlReader->readNext();
        if(token == QXmlStreamReader::StartDocument) {
            continue;
        }
        //If token is StartElement - read it
        if(token == QXmlStreamReader::StartElement)
        {
            if( xmlReader->name()=="normedOrigR" )
                slideStrSens->normedOrigR.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="normedOrigG" )
                slideStrSens->normedOrigG.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="normedOrigB" )
                slideStrSens->normedOrigB.append( xmlReader->readElementText().trimmed() );

            if( xmlReader->name()=="normedRalfR" )
                slideStrSens->normedRalfR.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="normedRalfG" )
                slideStrSens->normedRalfG.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="normedRalfB" )
                slideStrSens->normedRalfB.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="normedRalfH" )
                slideStrSens->normedRalfH.append( xmlReader->readElementText().trimmed() );

            if( xmlReader->name()=="originalR" )
                slideStrSens->originalR.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="originalG" )
                slideStrSens->originalG.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="originalB" )
                slideStrSens->originalB.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="originalH" )
                slideStrSens->originalH.append( xmlReader->readElementText().trimmed() );

            if( xmlReader->name()=="wR" )
                slideStrSens->wR.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="wG" )
                slideStrSens->wG.append( xmlReader->readElementText().trimmed() );
            if( xmlReader->name()=="wB" )
                slideStrSens->wB.append( xmlReader->readElementText().trimmed() );

        }
    }
    if(xmlReader->hasError()) {
        funcShowMsg("Parse Error",xmlReader->errorString());
        return _ERROR;
    }
    xmlReader->clear();
    xmlFile->close();

    slideStrSens->filled = 1;

    return _OK;
}
Example #18
0
void Argument1DString::readData(QXmlStreamReader &xmlReader)
{
  if(!xmlReader.name().compare("Argument1D", Qt::CaseInsensitive)
     && !xmlReader.hasError()
     &&  xmlReader.tokenType() == QXmlStreamReader::StartElement )
  {
    QXmlStreamAttributes attributes = xmlReader.attributes();

    if(attributes.hasAttribute("Id"))
    {
      QString id = attributes.value("Id").toString();

      if(id.compare(this->id() , Qt::CaseSensitive))
      {
        return;
      }
    }

    while (!(xmlReader.isEndElement() && !xmlReader.name().compare("Argument1D", Qt::CaseInsensitive)) && !xmlReader.hasError())
    {
      if(!xmlReader.name().compare("Dimensions", Qt::CaseInsensitive) && !xmlReader.hasError() &&  xmlReader.tokenType() == QXmlStreamReader::StartElement )
      {
        while (!(xmlReader.isEndElement()  && !xmlReader.name().compare("Dimensions", Qt::CaseInsensitive)) && !xmlReader.hasError())
        {
          if(!xmlReader.name().compare("Dimension", Qt::CaseInsensitive) && !xmlReader.hasError() &&  xmlReader.tokenType() == QXmlStreamReader::StartElement )
          {
            QXmlStreamAttributes attributes = xmlReader.attributes();

            if(attributes.hasAttribute("Id") && attributes.hasAttribute("Length"))
            {
              QString id = attributes.value("Id").toString();

              if(!m_dimension->id().compare(id))
              {
                QString length = attributes.value("Length").toString();
                setLength(length.toInt());
              }
            }

            while (!(xmlReader.isEndElement() && !xmlReader.name().compare("Dimension", Qt::CaseInsensitive)) && !xmlReader.hasError())
            {
              xmlReader.readNext();
            }
          }
          xmlReader.readNext();
        }
        resetDataArray();
      }
      else if(!xmlReader.name().compare("ValueDefinition", Qt::CaseInsensitive) && !xmlReader.hasError() &&  xmlReader.tokenType() == QXmlStreamReader::StartElement )
      {
        valueDefinitionInternal()->readData(xmlReader);

        while (!(xmlReader.isEndElement() && !xmlReader.name().compare("ValueDefinition", Qt::CaseInsensitive)) && !xmlReader.hasError())
        {
        }
      }
      else if(!xmlReader.name().compare("Values", Qt::CaseInsensitive) && !xmlReader.hasError() &&  xmlReader.tokenType() == QXmlStreamReader::StartElement )
      {

        std::vector<QString> values;

        while (!(xmlReader.isEndElement() && !xmlReader.name().compare("Values", Qt::CaseInsensitive)) && !xmlReader.hasError())
        {
          if(!xmlReader.name().compare("Value", Qt::CaseInsensitive) && !xmlReader.hasError() &&  xmlReader.tokenType() == QXmlStreamReader::StartElement )
          {
            QString value = xmlReader.readElementText();
            values.push_back(value);
          }

          xmlReader.readNext();
        }

        if((int)values.size() == length())
        {
          int ind[1] = {0};
          int str[1] = {length()};
          setValues(ind, str,values.data());
        }
      }

      xmlReader.readNext();
    }
  }
}
Example #19
0
bool EFX::loadXML(QXmlStreamReader &root)
{
    if (root.name() != KXMLQLCFunction)
    {
        qWarning() << "Function node not found!";
        return false;
    }

    if (root.attributes().value(KXMLQLCFunctionType).toString() != typeToString(Function::EFX))
    {
        qWarning("Function is not an EFX!");
        return false;
    }

    /* Load EFX contents */
    while (root.readNextStartElement())
    {
        if (root.name() == KXMLQLCBus)
        {
            /* Bus */
            QString str = root.attributes().value(KXMLQLCBusRole).toString();
            if (str == KXMLQLCBusFade)
                m_legacyFadeBus = root.readElementText().toUInt();
            else if (str == KXMLQLCBusHold)
                m_legacyHoldBus = root.readElementText().toUInt();
        }
        else if (root.name() == KXMLQLCFunctionSpeed)
        {
            loadXMLSpeed(root);
        }
        else if (root.name() == KXMLQLCEFXFixture)
        {
            EFXFixture* ef = new EFXFixture(this);
            ef->loadXML(root);
            if (ef->head().isValid())
            {
                if (addFixture(ef) == false)
                    delete ef;
            }
        }
        else if (root.name() == KXMLQLCEFXPropagationMode)
        {
            /* Propagation mode */
            setPropagationMode(stringToPropagationMode(root.readElementText()));
        }
        else if (root.name() == KXMLQLCEFXAlgorithm)
        {
            /* Algorithm */
            setAlgorithm(stringToAlgorithm(root.readElementText()));
        }
        else if (root.name() == KXMLQLCFunctionDirection)
        {
            loadXMLDirection(root);
        }
        else if (root.name() == KXMLQLCFunctionRunOrder)
        {
            loadXMLRunOrder(root);
        }
        else if (root.name() == KXMLQLCEFXWidth)
        {
            /* Width */
            setWidth(root.readElementText().toInt());
        }
        else if (root.name() == KXMLQLCEFXHeight)
        {
            /* Height */
            setHeight(root.readElementText().toInt());
        }
        else if (root.name() == KXMLQLCEFXRotation)
        {
            /* Rotation */
            setRotation(root.readElementText().toInt());
        }
        else if (root.name() == KXMLQLCEFXStartOffset)
        {
            /* StartOffset */
            setStartOffset(root.readElementText().toInt());
        }
        else if (root.name() == KXMLQLCEFXIsRelative)
        {
            /* IsRelative */
            setIsRelative(root.readElementText().toInt() != 0);
        }
        else if (root.name() == KXMLQLCEFXAxis)
        {
            /* Axes */
            loadXMLAxis(root);
        }
        else
        {
            qWarning() << "Unknown EFX tag:" << root.name();
            root.skipCurrentElement();
        }
    }

    return true;
}
Example #20
0
Event Event::Parser::parseXml(QXmlStreamReader& xml)
{
    Event event;

    while (!xml.atEnd()) {
        xml.readNext();

        if (xml.isStartElement()) {
            if (xml.name() == "id") {
                event.setId(xml.readElementText());
            } else if (xml.name() == "name") {
                event.setName(xml.readElementText());
            } else if (xml.name() == "description") {
                event.setDescription(xml.readElementText());
            } else if (xml.name() == "user") {
                event.setUser(xml.readElementText());
            } else if (xml.name() == "startdate") {
                QString date = xml.readElementText().remove(QRegExp(QLatin1String( "\\+.*$" )));
                event.setStartDate(QDate::fromString(date, Qt::ISODate));
            } else if (xml.name() == "enddate") {
                QString date = xml.readElementText().remove(QRegExp(QLatin1String( "\\+.*$" )));
                event.setEndDate(QDate::fromString(date, Qt::ISODate));
            } else if (xml.name() == "latitude") {
                event.setLatitude(xml.readElementText().toFloat());
            } else if (xml.name() == "longitude") {
                event.setLongitude(xml.readElementText().toFloat());
            } else if (xml.name() == "homepage") {
                event.setHomepage(xml.readElementText());
            } else if (xml.name() == "country") {
                event.setCountry(xml.readElementText());
            } else if (xml.name() == "city") {
                event.setCity(xml.readElementText());
            } else {
                event.addExtendedAttribute(xml.name().toString(), xml.readElementText());
            }
        } else if (xml.isEndElement() && xml.name() == "event") {
            break;
        }
    }

    return event;
}
Example #21
0
RunData::RunData(QObject *parent, QXmlStreamReader& reader):
	QObject(parent)
{
	init();
	ID=reader.attributes().value("ID").toString().toInt();
	while(reader.readNextStartElement())
	{
		if(reader.name()=="round")
		{
			round=reader.readElementText().toInt();
		}
		else if(reader.name()=="boatID")
		{
			boatID=reader.readElementText().toInt();
		}
		else if(reader.name()=="color")
		{
			color=reader.readElementText();
		}
		else if(reader.name()=="title1")
		{
			title1=reader.readElementText();
		}
		else if(reader.name()=="firstName1")
		{
			firstName1=reader.readElementText();
		}
		else if(reader.name()=="lastName1")
		{
			lastName1=reader.readElementText();
		}
		else if(reader.name()=="title2")
		{
			title2=reader.readElementText();
		}
		else if(reader.name()=="firstName2")
		{
			firstName2=reader.readElementText();
		}
		else if(reader.name()=="lastName2")
		{
			lastName2=reader.readElementText();
		}
		else if(reader.name()=="startTimeID")
		{
			startTimeID=reader.readElementText().toInt();
		}
		else if(reader.name()=="goalTimeID")
		{
			goalTimeID=reader.readElementText().toInt();
		}
		else if(reader.name()=="dsq")
		{
			dsq=reader.readElementText()=="true"?true:false;
		}
		else if(reader.name()=="errors")
		{
			errors=reader.readElementText();
		}
		else if(reader.name()=="published")
		{
			// ignore the published flag, it defaults to false
			//published=reader.readElementText()=="true"?true:false;
			reader.readElementText();
			published=false;
		}
		else if(reader.name()=="notes")
		{
			notes=reader.readElementText();
		}
		else if(reader.name()=="fireBrigade")
		{
			fireBrigade=reader.readElementText();
		}
		else if(reader.name()=="valuationClass")
		{
			valuationClass=reader.readElementText();
		}
		else if(reader.name()=="agePoints")
		{
			agePoints=reader.readElementText();
		}
		else
		{
			reader.raiseError(tr("unbekanntes XML-Tag innerhalb von 'run', Zeile: ") + QString::number(reader.lineNumber()));
		}
	}

	if(ID==0)
	{
		reader.raiseError(tr("Lauf hat ungültige ID!"));
	}
}
void ProfileManagement::on_pushButton_5_clicked()
{
    QString fileName=QFileDialog::getOpenFileName(this, tr("Open File"),
                                                     "",
                                                     tr("Files (*.xml)"));
    QDateTime DateTime =  QDateTime::currentDateTime();
    QString DateTime11 = DateTime.toString();
    if(fileName==0)
    {
        ui->textEdit->setText("<"+DateTime11+"> Brak sciezki!\n");
        return;
    }
    else
    {
        ui->textEdit->setText("<"+DateTime11+">Plik pomyślnie wczytany!\n");
    }
    QFile file(fileName);
    file.open(QIODevice::ReadOnly);
    QXmlStreamReader *xmlReader = new QXmlStreamReader(&file);
    int hitsAmount=0, hitsAmountBuffer=0;
    int rotation;
    QString powerBuffer;
    QString rotationBuffer;
    QString angleBuffer;
    QString positionBuffer;
    QString nameBuffer;
    QString percentBuffer;
    Profil *Prof;
    while(1)
    {
        xmlReader->readNext();
        if(xmlReader->atEnd())
            break;
        if(xmlReader->tokenType()==QXmlStreamReader::StartDocument)
        {
            continue;
        }
        if(xmlReader->tokenType()==QXmlStreamReader::StartElement)
        {
            if(xmlReader->name()=="Uderzenia" && xmlReader->tokenType()==QXmlStreamReader::StartElement)
            {
                Prof = new Profil;
                Prof->Rows=0;
                QXmlStreamAttributes attributes = xmlReader->attributes();
                hitsAmount=(attributes.value("Ilosc")).toString().toInt();
                continue;
            }
            if(xmlReader->name()=="Nazwa" && xmlReader->tokenType()==QXmlStreamReader::StartElement)
            {
                nameBuffer = xmlReader->readElementText();
                continue;
            }
            if(xmlReader->name()=="Uderzenie" && xmlReader->tokenType()==QXmlStreamReader::StartElement)
            {
                while(!(xmlReader->tokenType() == QXmlStreamReader::EndElement &&
                        xmlReader->name() == "Uderzenie"))
                {
                    if(xmlReader->name() =="Sila")
                    {
                        powerBuffer = xmlReader->readElementText();
                    }
                    if(xmlReader->name() =="Rotacja")
                    {
                        rotationBuffer = xmlReader->readElementText();
                        if(rotationBuffer =="Boczna")
                        {
                            rotation=1;
                        }
                        else if(rotationBuffer =="Wsteczna")
                        {
                            rotation=0;
                        }
                        else
                        {
                            rotation=2;
                        }
                    }
                    if(xmlReader->name() =="Kat")
                    {
                        angleBuffer = xmlReader->readElementText();
                    }
                    if(xmlReader->name() =="Pozycja")
                    {
                        positionBuffer = xmlReader->readElementText();
                    }
                    if(xmlReader->name() =="Procent")
                    {
                        percentBuffer = xmlReader->readElementText();
                        hitsAmountBuffer = hitsAmount * percentBuffer.toDouble();
                    }
                    xmlReader->readNext();
                }
                Prof->Rotation.push_back(rotationBuffer);
                Prof->Power.push_back(powerBuffer.toInt());
                Prof->Position.push_back(positionBuffer.toInt());
                Prof->Angle.push_back(angleBuffer.toInt());
                Prof->Percent.push_back(int(percentBuffer.toDouble()*100));
                Prof->Hits = hitsAmount;
                Prof->Nazwa = nameBuffer;
                Prof->DateTime = (QDateTime::currentDateTime()).toString();
                Prof->Rows++;
            }
        }
        if(xmlReader->name()=="Uderzenia" && xmlReader->tokenType()==QXmlStreamReader::EndElement)
        {
            Profil::Profile_Array.push_back(Prof);
            Refresh_Dialog();
        }
    }
    xmlReader->clear();
    file.close();

    ui->textEdit->setText("<"+DateTime11+">Plik pomyślnie odczytany!\n");
}
bool OsmAnd::FavoriteLocationsGpxCollection_P::loadFrom(QXmlStreamReader& xmlReader)
{
	std::shared_ptr< FavoriteLocation > newItem;
	QList< std::shared_ptr< FavoriteLocation > > newItems;

	while (!xmlReader.atEnd() && !xmlReader.hasError())
	{
		xmlReader.readNext();
		const auto tagName = xmlReader.name();
		if (xmlReader.isStartElement())
		{
			if (tagName == QLatin1String("wpt"))
			{
				if (newItem)
				{
					LogPrintf(LogSeverityLevel::Warning, "Malformed favorites GPX file: unpaired <wpt>");
					return false;
				}

				bool ok = true;
				const double lat = xmlReader.attributes().value(QLatin1String("lat")).toDouble(&ok);
				if (!ok)
				{
					LogPrintf(LogSeverityLevel::Warning, "Malformed favorites GPX file: invalid latitude");
					return false;
				}
				const double lon = xmlReader.attributes().value(QLatin1String("lon")).toDouble(&ok);
				if (!ok)
				{
					LogPrintf(LogSeverityLevel::Warning, "Malformed favorites GPX file: invalid longitude");
					return false;
				}

				newItem.reset(new FavoriteLocation(LatLon(lat, lon)));
			}
			else if (tagName == QLatin1String("name"))
			{
				if (!newItem)
				{
					LogPrintf(LogSeverityLevel::Warning, "Malformed favorites GPX file: unpaired <name>");
					return false;
				}

				newItem->setTitle(xmlReader.readElementText());
			}
			else if (tagName == QLatin1String("category"))
			{
				if (!newItem)
				{
					LogPrintf(LogSeverityLevel::Warning, "Malformed favorites GPX file: unpaired <category>");
					return false;
				}

                const auto& group = xmlReader.readElementText();
                if (!group.isEmpty())
                    newItem->setGroup(group);
			}
			else if (tagName == QLatin1String("color"))
			{
				if (!newItem)
				{
					LogPrintf(LogSeverityLevel::Warning, "Malformed favorites GPX file: unpaired <color>");
					return false;
				}

				bool ok = false;
				const auto color = Utilities::parseColor(xmlReader.readElementText(), ColorARGB(), &ok);
				if (!ok)
				{
					LogPrintf(LogSeverityLevel::Warning, "Malformed favorites GPX file: invalid color");
					continue;
				}

				newItem->setColor(static_cast<ColorRGB>(color));
			}
            else if (tagName == QLatin1String("color"))
            {
                if (!newItem)
                {
                    LogPrintf(LogSeverityLevel::Warning, "Malformed favorites GPX file: unexpected <hidden/>");
                    return false;
                }

                newItem->setIsHidden(true);
            }
		}
		else if (xmlReader.isEndElement())
		{
			if (tagName == QLatin1String("wpt"))
			{
				if (!newItem)
				{
					LogPrintf(LogSeverityLevel::Warning, "Malformed favorites GPX file: unpaired </wpt>");
					return false;
				}

				newItems.push_back(newItem);
				newItem.reset();
			}
		}
	}
	if (xmlReader.hasError())
	{
		LogPrintf(
            LogSeverityLevel::Warning,
            "XML error: %s (%" PRIi64 ", %" PRIi64 ")",
            qPrintable(xmlReader.errorString()),
            xmlReader.lineNumber(),
            xmlReader.columnNumber());
		return false;
	}

	{
		QWriteLocker scopedLocker(&_collectionLock);

		doClearFavoriteLocations();
		appendFrom(newItems);

		notifyCollectionChanged();
	}

	return true;
}
Example #24
0
bool QLCFixtureDef::loadXML(QXmlStreamReader& doc)
{
    bool retval = false;

    if (doc.readNextStartElement() == false)
        return false;

    if (doc.name() == KXMLQLCFixtureDef)
    {
        while (doc.readNextStartElement())
        {
            if (doc.name() == KXMLQLCCreator)
            {
                loadCreator(doc);
            }
            else if (doc.name() == KXMLQLCFixtureDefManufacturer)
            {
                setManufacturer(doc.readElementText());
            }
            else if (doc.name() == KXMLQLCFixtureDefModel)
            {
                setModel(doc.readElementText());
            }
            else if (doc.name() == KXMLQLCFixtureDefType)
            {
                setType(doc.readElementText());
            }
            else if (doc.name() == KXMLQLCChannel)
            {
                QLCChannel* ch = new QLCChannel();
                if (ch->loadXML(doc) == true)
                {
                    /* Loading succeeded */
                    if (addChannel(ch) == false)
                    {
                        /* Channel already exists */
                        delete ch;
                    }
                }
                else
                {
                    /* Loading failed */
                    delete ch;
                }
            }
            else if (doc.name() == KXMLQLCFixtureMode)
            {
                QLCFixtureMode* mode = new QLCFixtureMode(this);
                if (mode->loadXML(doc) == true)
                {
                    /* Loading succeeded */
                    if (addMode(mode) == false)
                    {
                        /* Mode already exists */
                        delete mode;
                    }
                }
                else
                {
                    /* Loading failed */
                    delete mode;
                }
            }
            else
            {
                qWarning() << Q_FUNC_INFO << "Unknown Fixture tag: " << doc.name();
                doc.skipCurrentElement();
            }
        }

        retval = true;
    }
    else
    {
        qWarning() << Q_FUNC_INFO << "Fixture node not found";
        retval = false;
    }

    if (retval == true)
        m_isLoaded = true;
    return retval;
}
void ColorScheme::processColorSchemeXml(QXmlStreamReader &xml,
        QHash<QString, ColorScheme *> &colorSchemes) {
    // The color scheme
    ColorScheme *colorScheme = new ColorScheme;
    // The styles defined
    QHash<QString, StyleInfo> definedStyles;

    QString langId;
    while (!xml.atEnd() && !xml.hasError()) {
        QXmlStreamReader::TokenType token = xml.readNext();
        if (token == QXmlStreamReader::StartElement) {
            if (xml.name() == "colorscheme") {
                QString name = xml.attributes().value("name").toString();
                colorSchemes[name] = colorScheme;
            } else if (xml.name() == "color") {
                QString type = xml.attributes().value("type").toString();
                QString text = xml.readElementText(
                            QXmlStreamReader::ErrorOnUnexpectedElement);
                if (type == "foreground") {
                    colorScheme->m_foreground = convertColor(text);
                } else if (type == "background") {
                    colorScheme->m_background = convertColor(text);
                } else if (type == "caret") {
                    colorScheme->m_caret = convertColor(text);
                } else if (type == "caretLine") {
                    colorScheme->m_caretLine = convertColor(text);
                } else if (type == "selection") {
                    colorScheme->m_selection = convertColor(text);
                } else if (type == "whitespace") {
                    colorScheme->m_whitespaceForeground = convertColor(text);
                }
            } else if (xml.name() == "style") {
                StyleInfo styleInfo;
                QXmlStreamAttributes attrs = xml.attributes();
                QString name = attrs.value("name").toString();
                if (attrs.hasAttribute("foreground")) {
                    styleInfo.setForegroundColor(
                            convertColor(attrs.value("foreground").toString()));
                }
                if (attrs.hasAttribute("background")) {
                    styleInfo.setBackgroundColor(
                            convertColor(attrs.value("background").toString()));
                }
                if (attrs.hasAttribute("bold")) {
                    styleInfo.setBold(attrs.value("bold").toString() == "true");
                }
                if (attrs.hasAttribute("italic")) {
                    styleInfo.setItalic(
                            attrs.value("italic").toString() == "true");
                }
                if (attrs.hasAttribute("underline")) {
                    styleInfo.setUnderline(
                            attrs.value("underline").toString() == "true");
                }
                if (attrs.hasAttribute("eolFilled")) {
                    styleInfo.setEolFilled(
                            attrs.value("eolFilled").toString() == "true");
                }
                definedStyles[name] = styleInfo;
            } else if (xml.name() == "language") {
                langId = xml.attributes().value("id").toString();
                colorScheme->m_languagesStyles[langId] = QHash<int, StyleInfo>();
            } else if (xml.name() == "styleInfo") {
                QString idStr = xml.attributes().value("id").toString();
                bool ok;
                int id = idStr.toInt(&ok);
                if (ok) {
                    QXmlStreamAttributes attrs = xml.attributes();
                    if (attrs.hasAttribute("styleRef")) {
                        QString styleRef = attrs.value("styleRef").toString();
                        colorScheme->m_languagesStyles[langId][id] = definedStyles[styleRef];
                    }
                }
            }
        }
    }
}
Example #26
0
// Private attribute accessor methods
//
MapModel* 
Gpx::load ( QString fileName ){
    QList<Node*> m_trackPoints;
    MapModel *new_model = new MapModel( );
    QList<Way*> m_trackWays;
    QXmlStreamReader reader;
    QFile file(fileName);

    if (!file.open(QFile::ReadOnly | QFile::Text)){
         qDebug( )  << "Error: Cannot read file ";
            //return false
    }
    reader.setDevice(&file);

    if (!reader.atEnd( ))
        reader.readNext( );
    while (!reader.atEnd( )){
        if (reader.isStartElement( ))
        {
            if ((reader.name( ) == "gpx") or (reader.name( ) =="trk") or (reader.name( ) =="name") 
            or (reader.name( ) =="trkseg") or (reader.name( ) =="time")  or (reader.name( ) =="bounds"))
            {
                //qDebug( )<< "StartGPX = "<<reader.name( ).toString( );

                if (reader.name( ) =="time")
                {
                    //qDebug() << "set time: " << reader.readElementText( );
                    new_model->setTimestamp ( reader.readElementText( ) );

                }
                
                if (reader.name( ) =="bounds")
                {
                    new_model->setBounds (reader.attributes( ).value("minlat").toString( ).toDouble( ),
                                     reader.attributes( ).value("minlon").toString( ).toDouble( ),
                                     reader.attributes( ).value("maxlat").toString( ).toDouble( ),
                                     reader.attributes( ).value("maxlon").toString( ).toDouble( ));

                }
                
                if (reader.name( ) =="trkseg")
                {
                    if (!reader.atEnd( ))
                        reader.readNext( );
                    while (!reader.atEnd( ))
                    {
                        //is this element the start of an element?
                        if (reader.isStartElement( ))
                        {
                            if (reader.name( ) =="trkpt")
                            {
                                //add a new node.
                                m_trackPoints << (
                                    new Node(
                                        reader.attributes( ).value("lat").toString( ).toDouble( ),
                                        reader.attributes( ).value("lon").toString( ).toDouble( )));

                                if (!reader.atEnd( ))
                                    reader.readNext( );
                                //do this loop until the end of the file is reached
                                //or untill the end of trkpt is reached (see break).
                                while (!reader.atEnd( )){
                                    if (reader.isStartElement( ))
                                    {
                                        if (reader.name( ) == "ele")
                                        {
                                            //setAltitude
                                            m_trackPoints[m_trackPoints.size( )-1]->setAltitude(reader.readElementText( ).toDouble( ));
                                        }
                                        if (reader.name( ) == "time")
                                        {
                                            //setTimestamp
                                            m_trackPoints[m_trackPoints.size( )-1]->setTimestamp(reader.readElementText( ));
                                        }
                                    }
                                    if (reader.isEndElement( ))
                                    {
                                        if (reader.name( ) == "trkpt")
                                        {
                                            break;
                                        }
                                    }
                                    if (!reader.atEnd( ))
                                        reader.readNext( );
                                }
                            }
                        }
                        //find next element
                        if (!reader.atEnd( ))
                            reader.readNext( );
                    }

                }
                if (!reader.atEnd( ))
                    reader.readNext( );
                if (reader.isStartElement( )){
                    qDebug( )<< "StartGPX2 = "<<reader.name( ).toString( );
                }
            }else{
                qDebug( )<< "Something weird? = "<<reader.name( ).toString( );
                reader.raiseError (QObject::tr("Not a gpx file"));
            }
            if (!reader.atEnd( ))
                reader.readNext( );
        }
        else
        {
            if (!reader.atEnd( ))
                reader.readNext( );
        }
    }

    file.close( );
    if (reader.hasError( ))
    {
        qDebug( ) << "Error: Failed to parse file "<< fileName <<": "<< file.errorString( );
    } 
    else if (file.error( ) != QFile::NoError)
    {
        qDebug( ) << "Error: Cannot read file "<< fileName <<": "<< file.errorString( );
    }
    else 
    {
        m_trackWays << ( new Way(m_trackPoints) );
        new_model->setNodes ( m_trackPoints );
        new_model->setWays( m_trackWays );

        return new_model;
    }

    return 0;
}
Example #27
0
void ITunesFeature::parsePlaylist(QXmlStreamReader &xml, QSqlQuery &query_insert_to_playlists,
                                  QSqlQuery &query_insert_to_playlist_tracks, TreeItem* root) {
    //qDebug() << "Parse Playlist";

    QString playlistname;
    int playlist_id = -1;
    int playlist_position = -1;
    int track_reference = -1;
    //indicates that we haven't found the <
    bool isSystemPlaylist = false;

    QString key;


    //We process and iterate the <dict> tags holding playlist summary information here
    while (!xml.atEnd() && !m_cancelImport) {
        xml.readNext();

        if (xml.isStartElement()) {

            if (xml.name() == "key") {
                QString key = xml.readElementText();
                // The rules are processed in sequence
                // That is, XML is ordered.
                // For iTunes Playlist names are always followed by the ID.
                // Afterwars the playlist entries occur
                if (key == "Name") {
                    readNextStartElement(xml);
                    playlistname = xml.readElementText();
                    continue;
                }
                //When parsing the ID, the playlistname has already been found
                if (key == "Playlist ID") {
                    readNextStartElement(xml);
                    playlist_id = xml.readElementText().toInt();
                    playlist_position = 1;
                    continue;
                }
                //Hide playlists that are system playlists
                if (key == "Master" || key == "Movies" || key == "TV Shows" ||
                    key == "Music" || key == "Books" || key == "Purchased") {
                    isSystemPlaylist = true;
                    continue;
                }

                if (key == "Playlist Items") {
                    //if the playlist is prebuild don't hit the database
                    if (isSystemPlaylist) continue;
                    query_insert_to_playlists.bindValue(":id", playlist_id);
                    query_insert_to_playlists.bindValue(":name", playlistname);

                    bool success = query_insert_to_playlists.exec();
                    if (!success) {
                        qDebug() << "SQL Error in ITunesTableModel.cpp: line" << __LINE__
                                 << " " << query_insert_to_playlists.lastError();
                        return;
                    }
                    //append the playlist to the child model
                    TreeItem *item = new TreeItem(playlistname, playlistname, this, root);
                    root->appendChild(item);

                }
                // When processing playlist entries, playlist name and id have
                // already been processed and persisted
                if (key == "Track ID") {
                    track_reference = -1;

                    readNextStartElement(xml);
                    track_reference = xml.readElementText().toInt();

                    query_insert_to_playlist_tracks.bindValue(":playlist_id", playlist_id);
                    query_insert_to_playlist_tracks.bindValue(":track_id", track_reference);
                    query_insert_to_playlist_tracks.bindValue(":position", playlist_position++);

                    //Insert tracks if we are not in a pre-build playlist
                    if (!isSystemPlaylist && !query_insert_to_playlist_tracks.exec()) {
                        qDebug() << "SQL Error in ITunesFeature.cpp: line" << __LINE__ << " "
                                 << query_insert_to_playlist_tracks.lastError();
                        qDebug() << "trackid" << track_reference;
                        qDebug() << "playlistname; " << playlistname;
                        qDebug() << "-----------------";
                    }
                }
            }
        }
        if (xml.isEndElement()) {
            if (xml.name() == "array") {
                //qDebug() << "exit playlist";
                break;
            }
        }
    }
}
Example #28
0
void ITunesFeature::parseTrack(QXmlStreamReader &xml, QSqlQuery &query) {
    //qDebug() << "----------------TRACK-----------------";
    int id = -1;
    QString title;
    QString artist;
    QString album;
    QString year;
    QString genre;
    QString location;

    int bpm = 0;
    int bitrate = 0;

    //duration of a track
    int playtime = 0;
    int rating = 0;
    QString comment;
    QString tracknumber;

    while (!xml.atEnd()) {
        xml.readNext();

        if (xml.isStartElement()) {
            if (xml.name() == "key") {
                QString key = xml.readElementText();
                QString content =  "";

                if (readNextStartElement(xml)) {
                    content = xml.readElementText();
                }

                //qDebug() << "Key: " << key << " Content: " << content;

                if (key == "Track ID") {
                    id = content.toInt();
                    continue;
                }
                if (key == "Name") {
                    title = content;
                    continue;
                }
                if (key == "Artist") {
                    artist = content;
                    continue;
                }
                if (key == "Album") {
                    album = content;
                    continue;
                }
                if (key == "Genre") {
                    genre = content;
                    continue;
                }
                if (key == "BPM") {
                    bpm = content.toInt();
                    continue;
                }
                if (key == "Bit Rate") {
                    bitrate =  content.toInt();
                    continue;
                }
                if (key == "Comments") {
                    comment = content;
                    continue;
                }
                if (key == "Total Time") {
                    playtime = (content.toInt() / 1000);
                    continue;
                }
                if (key == "Year") {
                    year = content;
                    continue;
                }
                if (key == "Location") {
                    QByteArray strlocbytes = content.toUtf8();
                    location = QUrl::fromEncoded(strlocbytes).toLocalFile();
                    // Replace first part of location with the mixxx iTunes Root
                    // on systems where iTunes installed it only strips //localhost
                    // on iTunes from foreign systems the mount point is replaced
                    if (!m_dbItunesRoot.isEmpty()) {
                        location.replace(m_dbItunesRoot, m_mixxxItunesRoot);
                    }
                    continue;
                }
                if (key == "Track Number") {
                    tracknumber = content;
                    continue;
                }
                if (key == "Rating") {
                    //value is an integer and ranges from 0 to 100
                    rating = (content.toInt() / 20);
                    continue;
                }
            }
        }
        //exit loop on closing </dict>
        if (xml.isEndElement() && xml.name() == "dict") {
            break;
        }
    }
    // If we reach the end of <dict>
    // Save parsed track to database
    query.bindValue(":id", id);
    query.bindValue(":artist", artist);
    query.bindValue(":title", title);
    query.bindValue(":album", album);
    query.bindValue(":genre", genre);
    query.bindValue(":year", year);
    query.bindValue(":duration", playtime);
    query.bindValue(":location", location);
    query.bindValue(":rating", rating);
    query.bindValue(":comment", comment);
    query.bindValue(":tracknumber", tracknumber);
    query.bindValue(":bpm", bpm);
    query.bindValue(":bitrate", bitrate);

    bool success = query.exec();

    if (!success) {
        qDebug() << "SQL Error in itunesfeature.cpp: line" << __LINE__ << " " << query.lastError();
        return;
    }
}
Example #29
0
void ITunesFeature::guessMusicLibraryMountpoint(QXmlStreamReader &xml) {
    // Normally the Folder Layout it some thing like that
    // iTunes/
    // iTunes/Album Artwork
    // iTunes/iTunes Media <- this is the "Music Folder"
    // iTunes/iTunes Music Library.xml <- this location we already knew
    QByteArray strlocbytes = xml.readElementText().toUtf8();
    QString music_folder = QUrl::fromEncoded(strlocbytes).toLocalFile();

    QString music_folder_test = music_folder;
    music_folder_test.replace(localhost_token(), "");
    QDir music_folder_dir(music_folder_test);

    // The music folder exists, so a simple transformation
    // of replacing localhost token with nothing will work.
    if (music_folder_dir.exists()) {
        // Leave defaults intact.
        return;
    }

    // The iTunes Music Library doesn't exist! This means we are likely loading
    // the library from a system that is different from the one that wrote the
    // iTunes configuration. The configuration file path, m_dbfile is a readable
    // location that in most situation is "close" to the music library path so
    // since we can read that file we will try to infer the music library mount
    // point from it.

    // Examples:

    // Windows with non-itunes-managed music:
    // m_dbfile: c:/Users/LegacyII/Music/iTunes/iTunes Music Library.xml
    // Music Folder: file://localhost/C:/Users/LegacyII/Music/
    // Transformation:  "//localhost/" -> ""

    // Mac OS X with iTunes-managed music:
    // m_dbfile: /Users/rjryan/Music/iTunes/iTunes Music Library.xml
    // Music Folder: file://localhost/Users/rjryan/Music/iTunes/iTunes Media/
    // Transformation: "//localhost" -> ""

    // Linux reading an OS X partition mounted at /media/foo to an
    // iTunes-managed music folder:
    // m_dbfile: /media/foo/Users/rjryan/Music/iTunes/iTunes Music Library.xml
    // Music Folder: file://localhost/Users/rjryan/Music/iTunes/iTunes Media/
    // Transformation: "//localhost" -> "/media/foo"

    // Linux reading a Windows partition mounted at /media/foo to an
    // non-itunes-managed music folder:
    // m_dbfile: /media/foo/Users/LegacyII/Music/iTunes/iTunes Music Library.xml
    // Music Folder: file://localhost/C:/Users/LegacyII/Music/
    // Transformation:  "//localhost/C:" -> "/media/foo"

    // Algorithm:
    // 1. Find the largest common subsequence shared between m_dbfile and "Music
    //    Folder"
    // 2. For all tracks, replace the left-side of of the LCS in "Music Folder"
    //    with the left-side of the LCS in m_dbfile.

    QString lcs = LCS(m_dbfile, music_folder);

    if (lcs.size() <= 1) {
        qDebug() << "ERROR: Couldn't find a suitable transformation to load iTunes data files. Leaving defaults intact.";
    }

    int musicFolderLcsIndex = music_folder.indexOf(lcs);
    if (musicFolderLcsIndex < 0) {
        qDebug() << "ERROR: Detected LCS" << lcs
                 << "is not present in music_folder:" << music_folder;
        return;
    }

    int dbfileLcsIndex = m_dbfile.indexOf(lcs);
    if (dbfileLcsIndex < 0) {
        qDebug() << "ERROR: Detected LCS" << lcs
                 << "is not present in m_dbfile" << m_dbfile;
        return;
    }

    m_dbItunesRoot = music_folder.left(musicFolderLcsIndex);
    m_mixxxItunesRoot = m_dbfile.left(dbfileLcsIndex);
    qDebug() << "Detected translation rule for iTunes files:"
             << m_dbItunesRoot << "->" << m_mixxxItunesRoot;
}
Example #30
-12
bool Document::loadXOJ(QString fileName)
{
  QFile file(fileName);
  if (!file.open(QIODevice::ReadOnly))
  {
    return false;
  }

  QXmlStreamReader reader;

  // check if it is a gzipped xoj
  QByteArray s = file.read(2);
  if (s.size() == 2)
  {
    if (s.at(0) == static_cast<char>(0x1f) && s.at(1) == static_cast<char>(0x8b))
    {
      // this is a gzipped file
      file.reset();
      QByteArray compressedData = file.readAll();
      QByteArray uncompressedData;
      if (!QCompressor::gzipDecompress(compressedData, uncompressedData))
      {
        return false;
      }
      reader.addData(uncompressedData);
    }
    else
    {
      file.reset();
      reader.setDevice(&file);
    }
  }
  else
  {
    return false;
  }

  pages.clear();

  int strokeCount = 0;

  while (!reader.atEnd())
  {
    reader.readNext();
    if (reader.name() == "page" && reader.tokenType() == QXmlStreamReader::StartElement)
    {
      QXmlStreamAttributes attributes = reader.attributes();
      QStringRef width = attributes.value("", "width");
      QStringRef height = attributes.value("", "height");
      Page newPage;
      newPage.setWidth(width.toDouble());
      newPage.setHeight(height.toDouble());

      pages.append(newPage);
    }
    if (reader.name() == "background" && reader.tokenType() == QXmlStreamReader::StartElement)
    {
      QXmlStreamAttributes attributes = reader.attributes();
      QStringRef color = attributes.value("", "color");
      QColor newColor = stringToColor(color.toString());
      pages.last().setBackgroundColor(newColor);
    }
    if (reader.name() == "stroke" && reader.tokenType() == QXmlStreamReader::StartElement)
    {
      QXmlStreamAttributes attributes = reader.attributes();
      QStringRef tool = attributes.value("", "tool");
      if (tool == "pen")
      {
        Stroke newStroke;
        newStroke.pattern = MrDoc::solidLinePattern;
        QStringRef color = attributes.value("", "color");
        newStroke.color = stringToColor(color.toString());
        QStringRef strokeWidth = attributes.value("", "width");
        QStringList strokeWidthList = strokeWidth.toString().split(" ");
        newStroke.penWidth = strokeWidthList.at(0).toDouble();
        newStroke.pressures.append(newStroke.penWidth / strokeWidthList.at(0).toDouble());
        for (int i = 1; i < strokeWidthList.size(); ++i)
        {
          newStroke.pressures.append(2 * strokeWidthList.at(i).toDouble() / newStroke.penWidth - newStroke.pressures.at(i - 1));
        }
        QString elementText = reader.readElementText();
        QStringList elementTextList = elementText.split(" ");
        for (int i = 0; i + 1 < elementTextList.size(); i = i + 2)
        {
          newStroke.points.append(QPointF(elementTextList.at(i).toDouble(), elementTextList.at(i + 1).toDouble()));
        }
        while (newStroke.points.size() > newStroke.pressures.size())
        {
          newStroke.pressures.append(1.0);
        }
        pages.last().appendStroke(newStroke);
        strokeCount++;
        qDebug() << strokeCount;
      }
    }
  }

  //    QFileInfo fileInfo(file);
  file.close();

  for (auto &page : pages)
  {
    page.clearDirtyRect();
  }

  if (reader.hasError())
  {
    return false;
  }
  else
  {
    setDocumentChanged(true);
    return true;
  }
}