void XMLOperations::setDownloadingThreadNodeValue(QDomDocument &domDoc, QString URL, QList<SDownloadThread> nodeValue)
{
    QDomNodeList tmpList = domDoc.elementsByTagName("File");
    for (int i = 0; i < tmpList.count(); i ++)
    {
        //contentNode:子节点File下面包含的内容节点列表
        QDomNodeList contentNode = tmpList.item(i).toElement().childNodes();
        QDomNode tmpURLNode;
        QDomNode tmpTargeNode;
        for (int j = 0; j < contentNode.count(); j ++)
        {
            QString tmpTagName = contentNode.item(j).nodeName();
            if (tmpTagName == "URL")
                tmpURLNode = contentNode.item(j);
            else if (tmpTagName == "Threads")
                tmpTargeNode = contentNode.item(j);
            else
                continue;
        }
        if (tmpURLNode.toElement().text() == URL)
        {
            //Thread list
            QDomNodeList threadNodeList = tmpTargeNode.toElement().childNodes();
            if (threadNodeList.count() != nodeValue.count())
                return;
            for (int x = 0; x < threadNodeList.count(); x ++)
            {
                QDomNodeList targetNodeList = threadNodeList.item(x).toElement().childNodes();
                for (int y = 0; y < targetNodeList.count(); y ++)
                {
                    if (targetNodeList.item(y).toElement().nodeName() == "CompleteBlockCount"
                            && nodeValue.at(x).completedBlockCount != "")
                        targetNodeList.item(y).toElement().firstChild().setNodeValue(nodeValue.at(x).completedBlockCount);
                }
            }
            break;
        }
    }
}
/*
  Remove a file from the project file.
  Don't delete the file.
*/
bool ProjectManager::removeFromProjectFile(const QString & projectPath, const QString & filePath)
{
  bool retval = false;
  QDomDocument doc;
  QDir dir(projectPath);
  QFile projectFile(dir.filePath(dir.dirName() + ".xml"));
  if (doc.setContent(&projectFile)) {
    projectFile.close();
    QDomNodeList files = doc.elementsByTagName("files").at(0).childNodes();
    for (int i = 0; i < files.count(); i++) {
      if (files.at(i).toElement().text() == dir.relativeFilePath(filePath)) {
        QDomNode parent = files.at(i).parentNode();
        parent.removeChild(files.at(i));
        if (projectFile.open(QIODevice::WriteOnly|QFile::Text)) {
          projectFile.write(doc.toByteArray(2));
          retval = true;
        }
      }
    }
  }
  return retval;
}
Beispiel #3
0
/*
  Remove the file in the current project's project file.
  The file has already been removed from the filebrowser UI.
*/
void ProjectInfo::onRemoveFileRequest(QString filename)
{
  QFile projectFile(projectFilePath( ));
  QDomDocument doc;
  if(doc.setContent(&projectFile))
  {
    projectFile.close();
    QDomNodeList files = doc.elementsByTagName("files").at(0).childNodes();
    for(int i = 0; i < files.count(); i++)
    {
      if(files.at(i).toElement().text() == filename)
      {
        QDomNode parent = files.at(i).parentNode();
        parent.removeChild(files.at(i));
        if(projectFile.open(QIODevice::WriteOnly|QFile::Text))
          projectFile.write(doc.toByteArray());
        mainWindow->removeFileFromProject(filename);
        return;
      }
    }
  }
}
void ServerInterface::sentXMLDone()
{
    disconnect(m_reply, SIGNAL(finished()), this, SLOT(sentXMLDone()));
    m_reply->deleteLater();
    if(checkError())
    {
        QString doctype = m_getDoc.first();
        m_getDoc.removeFirst();
        m_getData.removeFirst();
        QByteArray response = m_reply->readAll();


        QDomDocument doc;

        if(doc.setContent(response))
        {
            QDomNodeList list = doc.elementsByTagName("TransactionTicket");
            if(list.count() == 1 &&
               list.at(0).isElement() &&
               list.at(0).hasChildNodes())
            {
                QDomElement element = list.at(0).toElement();
                QString text = element.childNodes().at(0).toText().nodeValue();
                emit commitFile(doctype, text.toInt());
            }
        }

        if(m_getDoc.isEmpty())
        {
            m_reply = NULL;
            emit commitDone();
        }
        else
        {
            sendXML();
        }
    }

}
ChatStylePlistFileReader::Status ChatStylePlistFileReader::parse(const QDomDocument& document)
{
    QString key, value;
    QDomNodeList keyElements = document.elementsByTagName(QLatin1String("key"));

    for (int i = 0; i < keyElements.size(); i++) {
        if (keyElements.at(i).nextSibling().toElement().tagName() != QLatin1String("key")) {
            key = keyElements.at(i).toElement().text();
            QDomElement nextElement= keyElements.at(i).nextSibling().toElement();
            if (!nextElement.tagName().compare(QLatin1String("true"), Qt::CaseInsensitive)) {
                value = QLatin1String("1");
            } else if(!nextElement.tagName().compare(QLatin1String("false"), Qt::CaseInsensitive)) {
                value = QLatin1String("0");
            } else {
                value = nextElement.text();
            }
            d->data.insert(key, value);
        }
    }

    return Ok;
}
Beispiel #6
0
QDomElement BaseXMLVisitor::getChildByTag(const char *name)
{

    //qDebug("BaseXMLVisitor::getChildByTag(%s): called", name );
    QDomNode mainNode = mNodePath.back();
    if (mainNode.isNull()) {
        qDebug("  BaseXMLVisitor::getChildByTag(): path is null");
        return QDomElement();
    }

    if (mainNode.isElement())
    {
//        qDebug("  BaseXMLVisitor::getChildByTag(): path ends with element");

        QDomElement mainElement = mainNode.toElement();
        QDomNodeList nodesWithTag = mainElement.elementsByTagName(name);
        if (nodesWithTag.length() != 0)
        {
//            qDebug("  BaseXMLVisitor::getChildByTag(): found sub element");
            return nodesWithTag.at(0).toElement();
        }
        return QDomElement();
    }

    if (mainNode.isDocument())
    {
//        qDebug("  BaseXMLVisitor::getChildByTag(): path ends with document");
        QDomDocument mainDocument = mainNode.toDocument();
        QDomNodeList nodesWithTag = mainDocument.elementsByTagName(name);
        if (nodesWithTag.length() != 0)
        {
//            qDebug("  BaseXMLVisitor::getChildByTag(): found sub element");
            return nodesWithTag.at(0).toElement();
        }
        return QDomElement();
    }

    return QDomElement();
}
// --- Slots --------------------------------------------------------------- //
void PubChemQueryThread::replyFinished(QNetworkReply *reply)
{
    QByteArray replyData = reply->readAll();

    // check to see if the reply contains a request id. If it does
    // the PUG must be polled again.
    QDomDocument document;
    document.setContent(replyData, false);

    QDomNodeList nodes = document.elementsByTagName("PCT-Waiting_reqid");
    if(!nodes.isEmpty()){
        QDomNode node = nodes.at(0);
        QDomElement element = node.toElement();

        QString waitingId = element.text();
        poll(waitingId);
    }
    else{
        m_response = replyData;
        exit(0);
    }
}
Beispiel #8
0
void Wizard::checkMissingCodecs()
{
    const QStringList acodecsList = KdenliveSettings::audiocodecs();
    const QStringList vcodecsList = KdenliveSettings::videocodecs();
    bool replaceVorbisCodec = false;
    if (acodecsList.contains("libvorbis")) replaceVorbisCodec = true;
    bool replaceLibfaacCodec = false;
    if (!acodecsList.contains("aac") && acodecsList.contains("libfaac")) replaceLibfaacCodec = true;
    
    QString exportFolder = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/export/";
    QDir directory = QDir(exportFolder);
    QStringList filter;
    filter << "*.xml";
    QStringList fileList = directory.entryList(filter, QDir::Files);
    // We should parse customprofiles.xml in last position, so that user profiles
    // can also override profiles installed by KNewStuff
    QStringList requiredACodecs;
    QStringList requiredVCodecs;
    foreach(const QString &filename, fileList) {
        QDomDocument doc;
        QFile file(exportFolder + filename);
        doc.setContent(&file, false);
        file.close();
        QString std;
        QString format;
        QDomNodeList profiles = doc.elementsByTagName("profile");
        for (int i = 0; i < profiles.count(); ++i) {
            std = profiles.at(i).toElement().attribute("args");
            format.clear();
            if (std.startsWith(QLatin1String("acodec="))) format = std.section("acodec=", 1, 1);
            else if (std.contains(" acodec=")) format = std.section(" acodec=", 1, 1);
            if (!format.isEmpty()) requiredACodecs << format.section(' ', 0, 0).toLower();
            format.clear();
            if (std.startsWith(QLatin1String("vcodec="))) format = std.section("vcodec=", 1, 1);
            else if (std.contains(" vcodec=")) format = std.section(" vcodec=", 1, 1);
            if (!format.isEmpty()) requiredVCodecs << format.section(' ', 0, 0).toLower();
        }
    }
Beispiel #9
0
QMap<QString,QString>  GraphicsWorkflow::extractSvgElements(const QString& xmltext) {
    QDomDocument doc;
    QMap<QString,QString>  result;

    bool isopen = doc.setContent(xmltext);
    if ( !isopen) {
        SafetYAWL::streamlog
                << SafetLog::Error
                << tr("Se presentó un error al tratar de extraer los elementos del archivo de flujo "
                      "de trabajo tipo SVG");
        return result;
    }

    QDomNodeList list = doc.elementsByTagName("g");

    for(int i = 0; i < list.count();i++) {
        QString nodeid, nodetext;
        QTextStream mystream(&nodetext);

        QDomNode node = list.at(i);
        QDomNamedNodeMap attrs = node.attributes();
        nodeid =  attrs.namedItem("id").nodeValue().trimmed();
        if ( nodeid != "graph0") {
            node.save(mystream,0);
            mystream.flush();
//            SafetYAWL::streamlog
//                    << SafetLog::Debug
//                    << tr("Grafico SVG nodetext numero \"%2\": \"%1\"")
//                    .arg(nodetext)
//                    .arg(i);
            QString newdoc = Safet::templateSVGString1.arg(nodetext);
            //result[nodeid] = localeNormalize(newdoc);
            result[nodeid] = newdoc;

        }
    }
    return result;
}
Beispiel #10
0
void XmlSettingsDialog::MergeXml (const QByteArray& newXml)
{
	QDomDocument newDoc;
	newDoc.setContent (newXml);

	QList<QByteArray> props = WorkingObject_->dynamicPropertyNames ();

	QDomNodeList nodes = newDoc.elementsByTagName ("item");
	for (int i = 0; i < nodes.size (); ++i)
	{
		QDomElement elem = nodes.at (i).toElement ();
		if (elem.isNull ())
			continue;

		QString propName = elem.attribute ("property");
		if (!props.contains (propName.toLatin1 ()))
			continue;

		QVariant value = GetValue (elem);
		if (value.isNull ())
			continue;

		WorkingObject_->setProperty (propName.toLatin1 ().constData (), value);

		QWidget *object = findChild<QWidget*> (propName);
		if (!object)
		{
			qWarning () << Q_FUNC_INFO
				<< "could not find object for property"
				<< propName;
			continue;
		}
		HandlersManager_->SetValue (object, value);
	}

	UpdateXml ();
	HandlersManager_->ClearNewValues ();
}
int YourPayProcessor::doCredit(const int pccardid, const int pcvv, const double pamount, const double ptax, const bool ptaxexempt, const double pfreight, const double pduty, const int pcurrid, QString &pneworder, QString &preforder, int &pccpayid, ParameterList &pparams)
{
  if (DEBUG)
    qDebug("YP:doCredit(%d, %d, %f, %f, %d, %f, %f, %d, %s, %s, %d)",
	   pccardid, pcvv, pamount, ptax, ptaxexempt, pfreight, pduty, pcurrid,
	   pneworder.toAscii().data(), preforder.toAscii().data(), pccpayid);

  int returnValue = 0;
  double amount = currToCurr(pcurrid, _ypcurrid, pamount, &returnValue);
  if (returnValue < 0)
    return returnValue;

  QDomDocument request;

  returnValue = buildCommon(pccardid, pcvv, amount, request, "CREDIT");
  if (returnValue !=  0)
    return returnValue;

  QDomElement elem = request.createElement("transactiondetails");
  request.documentElement().appendChild(elem);
  CREATECHILDTEXTNODE(elem, "oid",              preforder);
  CREATECHILDTEXTNODE(elem, "reference_number", pneworder);
  CREATECHILDTEXTNODE(elem, "terminaltype",     "UNSPECIFIED");
  CREATECHILDTEXTNODE(elem, "taxexempt",        ptaxexempt ? "Y" : "N");

  CREATECHILDTEXTNODE(request.elementsByTagName("payment").at(0),
		      "tax", QString::number(ptax));

  QString response;
  returnValue = sendViaHTTP(request.toString(), response);
  if (returnValue < 0)
    return returnValue;

  returnValue = handleResponse(response, pccardid, "R", pamount, pcurrid,
			       pneworder, preforder, pccpayid, pparams);

  return returnValue;
}
/*
  Add a filepath to this project's file list.
  It's path should be relative to the project directory.
*/
bool ProjectManager::addToProjectFile(const QString & projectPath, const QString & newFilePath)
{
  bool retval = false;
  QDomDocument newProjectDoc;
  QDir projectDir(projectPath);
  QFile projectFile(projectDir.filePath(projectDir.dirName() + ".xml"));
  // read in the existing file, and add a node to the "files" section
  if (newProjectDoc.setContent(&projectFile)) {
    projectFile.close();
    QDomElement newFileElement = newProjectDoc.createElement("file");
    QDomText newFilePathElement = newProjectDoc.createTextNode(projectDir.relativeFilePath(newFilePath));
    newFileElement.appendChild(newFilePathElement);
    newProjectDoc.elementsByTagName("files").at(0).toElement().appendChild(newFileElement);

    // write our newly manipulated file
    if (projectFile.open(QIODevice::WriteOnly | QFile::Text)) { // reopen as WriteOnly
      projectFile.write(newProjectDoc.toByteArray(2));
      projectFile.close();
      retval = true;
    }
  }
  return retval;
}
Beispiel #13
0
void QgsMapCanvas::readProject( const QDomDocument & doc )
{
  QDomNodeList nodes = doc.elementsByTagName( "mapcanvas" );
  if ( nodes.count() )
  {
    QDomNode node = nodes.item( 0 );

    QgsMapSettings tmpSettings;
    tmpSettings.readXML( node );
    setMapUnits( tmpSettings.mapUnits() );
    setCrsTransformEnabled( tmpSettings.hasCrsTransformEnabled() );
    setDestinationCrs( tmpSettings.destinationCrs() );
    setExtent( tmpSettings.extent() );
    setRotation( tmpSettings.rotation() );
    mSettings.datumTransformStore() = tmpSettings.datumTransformStore();

    clearExtentHistory(); // clear the extent history on project load
  }
  else
  {
    QgsDebugMsg( "Couldn't read mapcanvas information from project" );
  }
}
void QgsRasterTerrainAnalysisDialog::on_mImportColorsButton_clicked()
{
  QString file = QFileDialog::getOpenFileName( 0, tr( "Import Colors and elevations from xml" ), QDir::homePath() );
  if ( file.isEmpty() )
  {
    return;
  }

  QFile inputFile( file );
  if ( !inputFile.open( QIODevice::ReadOnly ) )
  {
    QMessageBox::critical( 0, tr( "Error opening file" ), tr( "The relief color file could not be opened" ) );
    return;
  }

  QDomDocument doc;
  if ( !doc.setContent( &inputFile, false ) )
  {
    QMessageBox::critical( 0, tr( "Error parsing xml" ), tr( "The xml file could not be loaded" ) );
    return;
  }

  mReliefClassTreeWidget->clear();

  QDomNodeList reliefColorList = doc.elementsByTagName( "ReliefColor" );
  for ( int i = 0; i < reliefColorList.size(); ++i )
  {
    QDomElement reliefColorElem = reliefColorList.at( i ).toElement();
    QTreeWidgetItem* newItem = new QTreeWidgetItem();
    newItem->setText( 0, reliefColorElem.attribute( "MinElevation" ) );
    newItem->setText( 1, reliefColorElem.attribute( "MaxElevation" ) );
    newItem->setBackground( 2, QBrush( QColor( reliefColorElem.attribute( "red" ).toInt(), reliefColorElem.attribute( "green" ).toInt(),
                                       reliefColorElem.attribute( "blue" ).toInt() ) ) );
    mReliefClassTreeWidget->addTopLevelItem( newItem );
  }
}
Beispiel #15
0
void ConfigLoader::loadEnums(QDomDocument const &config)
{
    Reflection *result = new ReflectionGen();
    result->name = ReflectionNaming("enums", NULL, NULL);

    QDomNodeList enums = config.elementsByTagName("enum");
    for (unsigned i = 0; i < enums.length(); i++)
    {
        QDomElement enumElement = enums.at(i).toElement();
        EnumReflection *enumReflection = new EnumReflection();
        enumReflection->name = getNamingFromXML(enumElement);

        QDomNodeList items = enumElement.elementsByTagName("item");
        for (unsigned j = 0; j < items.length(); j++)
        {
            QDomElement itemElement = items.at(j).toElement();
            int id = itemElement.attribute("id").toInt();
            enumReflection->options.push_back(new EnumOption(id, getNamingFromXML(itemElement)));
        }

        // TODO: add support for comment and description
        mEnums.insert(QString(enumReflection->name.name), enumReflection);
    }
}
void RemoteRecipes::stylesDownloaded() {
    QDomDocument inputSource;
    QNetworkReply *reply = qobject_cast<QNetworkReply *> (sender());
    inputSource.setContent(reply->readAll());

    ui->errorLabel->setText("Reading Style list...");

    QDomNodeList styleList = inputSource.elementsByTagName("style");
    qDebug() << "Styles Found " << styleList.count();

    // clear the existing list
    ui->styleCombo->clear();

    for (int i = 0; i < styleList.count(); i++) {
        QDomNode curStyle = styleList.at(i);
        if (curStyle.isElement()) {

            qDebug() << "Value " << curStyle.toElement().text();
            //qDebug() << "Text " << curStyle.nodeType().s
            ui->styleCombo->addItem(curStyle.toElement().text());
        }
    }
    ui->errorLabel->setText("Style List updated.");
}
Beispiel #17
0
void readers::readSetting(){
    QSettings sett("Skyrim", "lib");
    QString path(QString("%1/setting.xml").arg(sett.value("path").toString()));
    QFile file(path);
    QDomDocument doc;
    if (file.open(QIODevice::ReadOnly)){
        doc.setContent(&file);
        QDomNodeList node = doc.elementsByTagName("readers");
        int _w = node.item(0).attributes().namedItem("width").nodeValue().toInt();
        int _h = node.item(0).attributes().namedItem("height").nodeValue().toInt();
        int _x = node.item(0).attributes().namedItem("x").nodeValue().toInt();
        int _y = node.item(0).attributes().namedItem("y").nodeValue().toInt();
        ui.checkBox_fam->setChecked(node.item(0).attributes().namedItem("fam").nodeValue().toInt());
        ui.checkBox_ima->setChecked(node.item(0).attributes().namedItem("ima").nodeValue().toInt());
        ui.checkBox_otc->setChecked(node.item(0).attributes().namedItem("otc").nodeValue().toInt());
        ui.checkBox_data_r->setChecked(node.item(0).attributes().namedItem("date_r").nodeValue().toInt());
        ui.checkBox_num->setChecked(node.item(0).attributes().namedItem("num").nodeValue().toInt());
        ui.checkBox_phone->setChecked(node.item(0).attributes().namedItem("phone").nodeValue().toInt());
        ui.checkBox_address->setChecked(node.item(0).attributes().namedItem("address").nodeValue().toInt());
        ui.checkBox_doc->setChecked(node.item(0).attributes().namedItem("doc").nodeValue().toInt());
        setGeometry(_x, _y, _w, _h);
    }
    file.close();
}
Beispiel #18
0
void RestWidget::parseOrderUrls(QNetworkReply *reply){

    if(reply->error()>0){
        xmloutput->addItem(QTime::currentTime().toString() +" : " + reply->errorString());
        emit connectionError();

    } else{
        QByteArray data = reply->readAll();
        QDomDocument doc;

        dataOutput->setText(data);

        doc.setContent(data);

        QDomNodeList orderNodes = doc.elementsByTagName("order");

        for(int i = 0; i < orderNodes.size(); i++){
            xmloutput->addItem(orderNodes.at(i).toElement().text());
            orderIDs->append(orderNodes.at(i).toElement().text());
        }
        order_ptr = 0; //reset the order pointer.
    }
    QObject::disconnect(netManager2, SIGNAL(finished(QNetworkReply*)),this, SLOT(parseOrderUrls(QNetworkReply*)));
}
Beispiel #19
0
void SearchStream::loadStreams(void)
{
    m_streams.clear();
    m_stations.clear();
    m_genres.clear();

    m_stations.append(tr("<All Stations>"));
    m_genres.append(tr("<All Genres>"));

    QString filename = QString("%1%2").arg(GetShareDir()).arg("mythmusic/streams.xml");

    QFile xmlFile(filename);

    if (!xmlFile.exists() || !xmlFile.open(QIODevice::ReadOnly))
    {
        LOG(VB_GENERAL, LOG_ERR, "SearchStream: Cannot open streams.xml");
        return;
    }

    QString errorMsg;
    int errorLine = 0;
    int errorColumn = 0;

    QDomDocument domDoc;

    if (!domDoc.setContent(&xmlFile, false, &errorMsg,
                           &errorLine, &errorColumn))
    {
        LOG(VB_GENERAL, LOG_ERR,
            "SearchStream: Could not read content of streams.xml" +
                QString("\n\t\t\tError parsing %1").arg(filename) +
                QString("\n\t\t\tat line: %1  column: %2 msg: %3")
                .arg(errorLine).arg(errorColumn).arg(errorMsg));
        return;
    }

    QDomNodeList itemList = domDoc.elementsByTagName("item");

    QDomNode itemNode;
    for (int i = 0; i < itemList.count(); i++)
    {
        itemNode = itemList.item(i);

        Metadata mdata;
        mdata.setStation(itemNode.namedItem(QString("station")).toElement().text());
        mdata.setChannel(itemNode.namedItem(QString("channel")).toElement().text());
        mdata.setUrl(itemNode.namedItem(QString("url")).toElement().text());
        mdata.setLogoUrl(itemNode.namedItem(QString("logourl")).toElement().text());
        mdata.setGenre(itemNode.namedItem(QString("genre")).toElement().text());
        mdata.setMetadataFormat(itemNode.namedItem(QString("metadataformat")).toElement().text());

        m_streams.insert(mdata.Station() + '-' + mdata.Channel(), mdata);

        if (!m_stations.contains(mdata.Station()))
            m_stations.append(mdata.Station());

        QStringList genreList = mdata.Genre().split(',');

        for (int x = 0; x < genreList.count(); x++)
        {
            if (!m_genres.contains(genreList[x].trimmed()))
                m_genres.append(genreList[x].trimmed());
        }
    }

    xmlFile.close();

    m_stations.sort();
    m_genres.sort();
}
int OracleImporter::importTextSpoiler(CardSet *set, const QByteArray &data)
{
	int cards = 0;
	QString bufferContents(data);
	
	// Workaround for ampersand bug in text spoilers
	int index = -1;
	while ((index = bufferContents.indexOf('&', index + 1)) != -1) {
		int semicolonIndex = bufferContents.indexOf(';', index);
		if (semicolonIndex > 5) {
			bufferContents.insert(index + 1, "amp;");
			index += 4;
		}
	}
	
	QDomDocument doc;
	QString errorMsg;
	int errorLine, errorColumn;
	if (!doc.setContent(bufferContents, &errorMsg, &errorLine, &errorColumn))
		qDebug() << "error:" << errorMsg << "line:" << errorLine << "column:" << errorColumn;

	QDomNodeList divs = doc.elementsByTagName("div");
	for (int i = 0; i < divs.size(); ++i) {
		QDomElement div = divs.at(i).toElement();
		QDomNode divClass = div.attributes().namedItem("class");
		if (divClass.nodeValue() == "textspoiler") {
			QString cardName, cardCost, cardType, cardPT, cardText;
			int cardId = 0;
			int cardLoyalty = 0;
			
			QDomNodeList trs = div.elementsByTagName("tr");
			for (int j = 0; j < trs.size(); ++j) {
				QDomElement tr = trs.at(j).toElement();
				QDomNodeList tds = tr.elementsByTagName("td");
				if (tds.size() != 2) {
					QStringList cardTextSplit = cardText.split("\n");
					for (int i = 0; i < cardTextSplit.size(); ++i)
						cardTextSplit[i] = cardTextSplit[i].trimmed();
					
					CardInfo *card = addCard(set->getShortName(), cardName, false, cardId, cardCost, cardType, cardPT, cardLoyalty, cardTextSplit);
					if (!set->contains(card)) {
						card->addToSet(set);
						cards++;
					}
					cardName = cardCost = cardType = cardPT = cardText = QString();
				} else {
					QString v1 = tds.at(0).toElement().text().simplified();
					QString v2 = tds.at(1).toElement().text().replace(trUtf8("—"), "-");
					
					if (v1 == "Name") {
						QDomElement a = tds.at(1).toElement().elementsByTagName("a").at(0).toElement();
						QString href = a.attributes().namedItem("href").nodeValue();
						cardId = href.mid(href.indexOf("multiverseid=") + 13).toInt();
						cardName = v2.simplified();
					} else if (v1 == "Cost:")
						cardCost = v2.simplified();
					else if (v1 == "Type:")
						cardType = v2.simplified();
					else if (v1 == "Pow/Tgh:")
						cardPT = v2.simplified().remove('(').remove(')');
					else if (v1 == "Rules Text:")
						cardText = v2.trimmed();
					else if (v1 == "Loyalty:")
						cardLoyalty = v2.trimmed().remove('(').remove(')').toInt();
				}
			}
			break;
		}
	}
	return cards;
}
Beispiel #21
0
bool HydrogenImport::readSong() 
{
	QHash<QString, InstrumentTrack *> drum_track;
	QHash<QString, int> pattern_length;
	QHash<QString, int> pattern_id;

	Song *s = Engine::getSong();
	int song_num_tracks = s->tracks().size();
	if ( QFile( filename ).exists() == false ) 
	{
		printf( "Song file not found \n" );
		return false;
	}
	QDomDocument doc = LocalFileMng::openXmlDocument( filename );
	QDomNodeList nodeList = doc.elementsByTagName( "song" );

	if( nodeList.isEmpty() )
	{
		printf( "Error reading song: song node not found\n" );
		return false;
	}
	QDomNode songNode = nodeList.at( 0 );

	QString m_sSongVersion = LocalFileMng::readXmlString( songNode , "version", "Unknown version" );


	QString sName( LocalFileMng::readXmlString( songNode, "name", "Untitled Song" ) );
	QString sAuthor( LocalFileMng::readXmlString( songNode, "author", "Unknown Author" ) );
	QString sNotes( LocalFileMng::readXmlString( songNode, "notes", "..." ) );
	QString sLicense( LocalFileMng::readXmlString( songNode, "license", "Unknown license" ) );
	QString sMode = LocalFileMng::readXmlString( songNode, "mode", "pattern" );

	QDomNode instrumentListNode = songNode.firstChildElement( "instrumentList" );
	if ( ( ! instrumentListNode.isNull()  ) ) 
	{

		int instrumentList_count = 0;
		QDomNode instrumentNode;
		instrumentNode = instrumentListNode.firstChildElement( "instrument" );
		while ( ! instrumentNode.isNull()  ) 
		{
			instrumentList_count++;
			QString sId = LocalFileMng::readXmlString( instrumentNode, "id", "" );			// instrument id
			QString sDrumkit = LocalFileMng::readXmlString( instrumentNode, "drumkit", "" );	// drumkit
			QString sName = LocalFileMng::readXmlString( instrumentNode, "name", "" );		// name
			float fVolume = LocalFileMng::readXmlFloat( instrumentNode, "volume", 1.0 );	// volume
			float fPan_L = LocalFileMng::readXmlFloat( instrumentNode, "pan_L", 0.5 );	// pan L
			float fPan_R = LocalFileMng::readXmlFloat( instrumentNode, "pan_R", 0.5 );	// pan R

			if ( sId.isEmpty() ) {
				printf( "Empty ID for instrument. skipping \n" );
				instrumentNode = (QDomNode) instrumentNode.nextSiblingElement( "instrument" );
				continue;
			}
			QDomNode filenameNode = instrumentNode.firstChildElement( "filename" );

			if ( ! filenameNode.isNull() ) 
			{
				return false;
			} 
			else 
			{
				unsigned nLayer = 0;
				QDomNode layerNode = instrumentNode.firstChildElement( "layer" );
				while (  ! layerNode.isNull()  ) 
				{
					if ( nLayer >= MAX_LAYERS ) 
					{
						printf( "nLayer >= MAX_LAYERS" );
						continue;
					}
					QString sFilename = LocalFileMng::readXmlString( layerNode, "filename", "" );
					QString sMode = LocalFileMng::readXmlString( layerNode, "smode", "forward" );

					if ( nLayer == 0 ) 
					{
						drum_track[sId] = ( InstrumentTrack * ) Track::create( Track::InstrumentTrack,Engine::getBBTrackContainer() );
						drum_track[sId]->volumeModel()->setValue( fVolume * 100 );
						drum_track[sId]->panningModel()->setValue( ( fPan_R - fPan_L ) * 100 );
						ins = drum_track[sId]->loadInstrument( "audiofileprocessor" );
						ins->loadFile( sFilename );
					}
					nLayer++;
					layerNode = ( QDomNode ) layerNode.nextSiblingElement( "layer" );
				}
			}

			instrumentNode = (QDomNode) instrumentNode.nextSiblingElement( "instrument" );
		}
		if ( instrumentList_count == 0 ) 
		{
			return false;
		}
	} 
	else 
	{
		return false;
	}
	QDomNode patterns = songNode.firstChildElement( "patternList" );
	int pattern_count = 0;
	int nbb = Engine::getBBTrackContainer()->numOfBBs();
	QDomNode patternNode =  patterns.firstChildElement( "pattern" );
	int pn = 1;
	while (  !patternNode.isNull()  ) 
	{
		if ( pn > 0 ) 
		{
			pattern_count++;
			s->addBBTrack();
			pn = 0;
		}
		QString sName;	// name
		sName = LocalFileMng::readXmlString( patternNode, "name", sName );

		QString sCategory = ""; // category
		sCategory = LocalFileMng::readXmlString( patternNode, "category", sCategory ,false ,false );
		int nSize = -1;
		nSize = LocalFileMng::readXmlInt( patternNode, "size", nSize, false, false );
		pattern_length[sName] = nSize;
		QDomNode pNoteListNode = patternNode.firstChildElement( "noteList" );
		if ( ! pNoteListNode.isNull() ) {
			QDomNode noteNode = pNoteListNode.firstChildElement( "note" );
			while ( ! noteNode.isNull()  ) {
				int nPosition = LocalFileMng::readXmlInt( noteNode, "position", 0 );
				float fVelocity = LocalFileMng::readXmlFloat( noteNode, "velocity", 0.8f );	
				float fPan_L = LocalFileMng::readXmlFloat( noteNode, "pan_L", 0.5 );
				float fPan_R = LocalFileMng::readXmlFloat( noteNode, "pan_R", 0.5 );	
				QString sKey = LocalFileMng::readXmlString( noteNode, "key", "C0", false, false );
				QString nNoteOff = LocalFileMng::readXmlString( noteNode, "note_off", "false", false, false );

				QString instrId = LocalFileMng::readXmlString( noteNode, "instrument", 0,false, false );
				int i = pattern_count - 1 + nbb;
				pattern_id[sName] = pattern_count - 1;
				Pattern*p = dynamic_cast<Pattern*>( drum_track[instrId]->getTCO( i ) );
				Note n; 
				n.setPos( nPosition );
				if ( (nPosition + 48) <= nSize ) 
				{
  					n.setLength( 48 );
				} 
				else 
				{
					n.setLength( nSize - nPosition );
				} 
				n.setVolume( fVelocity * 100 );
				n.setPanning( ( fPan_R - fPan_L ) * 100 );
				n.setKey( NoteKey::stringToNoteKey( sKey ) );
				p->addNote( n,false );
				pn = pn + 1;
				noteNode = ( QDomNode ) noteNode.nextSiblingElement( "note" );
			}        
		}
		patternNode = ( QDomNode ) patternNode.nextSiblingElement( "pattern" );
	}
	// Pattern sequence
	QDomNode patternSequenceNode = songNode.firstChildElement( "patternSequence" );
	QDomNode groupNode = patternSequenceNode.firstChildElement( "group" );
	int pos = 0;
	while (  !groupNode.isNull()  ) 
	{
	    int best_length = 0;
		QDomNode patternId = groupNode.firstChildElement( "patternID" );
		while (  !patternId.isNull()  ) 
		{
			QString patId = patternId.firstChild().nodeValue();
			patternId = ( QDomNode ) patternId.nextSiblingElement( "patternID" );

			int i = pattern_id[patId]+song_num_tracks;
			Track *t = ( BBTrack * ) s->tracks().at( i );
 			TrackContentObject *tco = t->createTCO( pos );      
			tco->movePosition( pos );

			
			if ( pattern_length[patId] > best_length ) 
			{
				best_length = pattern_length[patId];
			}
		}
		pos = pos + best_length;
		groupNode = groupNode.nextSiblingElement( "group" );
	}

	if ( pattern_count == 0 ) 
	{
		return false;
	}
	return true;
}
Beispiel #22
0
bool OsmImport::parseDoc(QDomDocument &doc)
{

    QDomNodeList list = doc.elementsByTagName("node");
    for (int i = 0; i < list.count(); i++)
    {
        nodes.append(new osmNode(list.at(i).toElement()));
    }
    list = doc.elementsByTagName("way");
    for (int i = 0; i < list.count(); i++)
    {
        ways.append(new osmWay(list.at(i).toElement(), nodes));
    }

    bool doPrimary = ImportSettings::instance()->importPrimary();
    bool doSecondary = ImportSettings::instance()->importSecondary();
    bool doTertiary = ImportSettings::instance()->importTertiary();
    bool doMotorway = ImportSettings::instance()->importMotorway();
    bool doService = ImportSettings::instance()->importService();
    bool doPath = ImportSettings::instance()->importPath();
    bool doSteps = ImportSettings::instance()->importSteps();
    bool doTrack = ImportSettings::instance()->importTrack();
    bool doFootpath = ImportSettings::instance()->importFootway();
    bool doResidential = ImportSettings::instance()->importResidential();
    bool doLiving_street = ImportSettings::instance()->importLiving_street();
    bool doCycleway = ImportSettings::instance()->importCycleway();
    bool doTurning_circle = ImportSettings::instance()->importTurning_circle();
    bool doPedestrian = ImportSettings::instance()->importPedestrian();
    bool doUnclassified = ImportSettings::instance()->importUnclassified();
    for (int i = 0; i < ways.count(); i++)
    {
        osmWay *w = ways.at(i);
        osmWay::wayType t = w->type;

        if ((t == osmWay::primary && doPrimary) ||
                (t == osmWay::secondary && doSecondary) ||
                (t == osmWay::tertiary && doTertiary) ||
                (t == osmWay::motorway && doMotorway) ||
                (t == osmWay::service && doService) ||
                (t == osmWay::path && doPath) ||
                (t == osmWay::steps && doSteps) ||
                (t == osmWay::track && doTrack) ||
                (t == osmWay::footway && doFootpath) ||
                (t == osmWay::residential && doResidential) ||
                (t == osmWay::living_street && doLiving_street) ||
                (t == osmWay::cycleway && doCycleway) ||
                (t == osmWay::turning_circle && doTurning_circle) ||
                (t == osmWay::pedestrian && doPedestrian) ||
                (t == osmWay::unclassified && doUnclassified))
        {
            project->XVector = w->XVector;
            project->YVector = w->YVector;
            project->ZVector = w->ZVector;
            if (project->XVector.size() > 0)
            {
                project->addLineStrip(w->name,w->maxSpeed,w->bridge,w->numLanes,w->type);
            }
        }
    }
    qDeleteAll(ways.begin(), ways.end());
    qDeleteAll(nodes.begin(), nodes.end());
    ways.clear();
    nodes.clear();
    // resize
    BoundingBoxVisitor *visitor = new BoundingBoxVisitor();
    project->getProjectData()->getRoadSystem()->accept(visitor);
    project->getProjectData()->getScenerySystem()->accept(visitor);
    QRectF box = visitor->getBoundingBox();
    SetProjectDimensionsCommand *command = new SetProjectDimensionsCommand(project->getProjectData(), box.bottom() + 0.1 * box.height(), box.top() - 0.1 * box.height(), box.right() + 0.1 * box.width(), box.left() - 0.1 * box.width());
    project->getProjectSettings()->executeCommand(command);

    return true;
}
/**
   Read map layers from project file


   @returns \code QPair< bool, QList<QDomNode> > \endcode
        bool is true if function worked; else is false.
     list contains nodes corresponding to layers that couldn't be loaded

   @note XML of form:

\verbatim
   <maplayer type="vector">
      <layername>Hydrop</layername>
      <datasource>/data/usgs/city_shp/hydrop.shp</datasource>
      <zorder>0</zorder>
      <provider>ogr</provider>
      <singlesymbol>
         <renderitem>
            <value>blabla</value>
            <symbol>
               <outlinecolor red="85" green="0" blue="255" />
               <outlinestyle>SolidLine</outlinestyle>
               <outlinewidth>1</outlinewidth>
               <fillcolor red="0" green="170" blue="255" />
               <fillpattern>SolidPattern</fillpattern>
            </symbol>
            <label>blabla</label>
         </renderitem>
      </singlesymbol>
      <label>0</label>
      <labelattributes>
         <label text="Label" field="" />
         <family name="Sans Serif" field="" />
         <size value="12" units="pt" field="" />
         <bold on="0" field="" />
         <italic on="0" field="" />
         <underline on="0" field="" />
         <color red="0" green="0" blue="0" field="" />
         <x field="" />
         <y field="" />
         <offset  units="pt" x="0" xfield="" y="0" yfield="" />
         <angle value="0" field="" />
         <alignment value="center" field="" />
      </labelattributes>
   </maplayer>
\endverbatim
*/
QPair< bool, QList<QDomNode> > QgsProject::_getMapLayers( QDomDocument const &doc )
{
  // Layer order is set by the restoring the legend settings from project file.
  // This is done on the 'readProject( ... )' signal

  QDomNodeList nl = doc.elementsByTagName( "maplayer" );

  // XXX what is this used for? QString layerCount( QString::number(nl.count()) );

  QString wk;

  QList<QDomNode> brokenNodes; // a list of Dom nodes corresponding to layers
  // that we were unable to load; this could be
  // because the layers were removed or
  // re-located after the project was last saved

  // process the map layer nodes

  if ( 0 == nl.count() )      // if we have no layers to process, bail
  {
    return qMakePair( true, brokenNodes ); // Decided to return "true" since it's
    // possible for there to be a project with no
    // layers; but also, more imporantly, this
    // would cause the tests/qgsproject to fail
    // since the test suite doesn't currently
    // support test layers
  }

  bool returnStatus = true;

  emit layerLoaded( 0, nl.count() );

  //Collect vector layers with joins.
  //They need to refresh join caches and symbology infos after all layers are loaded
  QList< QPair< QgsVectorLayer*, QDomElement > > vLayerList;

  for ( int i = 0; i < nl.count(); i++ )
  {
    QDomNode node = nl.item( i );
    QDomElement element = node.toElement();

    if ( element.attribute( "embedded" ) == "1" )
    {
      createEmbeddedLayer( element.attribute( "id" ), readPath( element.attribute( "project" ) ), brokenNodes, vLayerList );
      continue;
    }
    else
    {
      if ( !addLayer( element, brokenNodes, vLayerList ) )
      {
        returnStatus = false;
      }
    }
    emit layerLoaded( i + 1, nl.count() );
  }

  //Update field map of layers with joins and create join caches if necessary
  //Needs to be done here once all dependent layers are loaded
  QList< QPair< QgsVectorLayer*, QDomElement > >::iterator vIt = vLayerList.begin();
  for ( ; vIt != vLayerList.end(); ++vIt )
  {
    vIt->first->createJoinCaches();
    vIt->first->updateFields();
  }

  return qMakePair( returnStatus, brokenNodes );

} // _getMapLayers
Beispiel #24
0
bool SoundFactory::loadLanguage(QDomDocument &layoutDocument, const QString &currentLanguage)
{
    QDomNodeList languagesList,
    alphabetList,
    syllablesList,
    soundNamesList;
    QDomElement languageElement,
    alphabetElement,
    syllableElement,
    soundNameElement;
    QDomAttr nameAttribute, fileAttribute;

    languagesList = layoutDocument.elementsByTagName(QStringLiteral("language"));
    QDomAttr codeAttribute;
    //check if the sound files match current language
    languageElement = (const QDomElement &) languagesList.item(0).toElement();
    codeAttribute = languageElement.attributeNode(QStringLiteral("code"));

    if (currentLanguage != codeAttribute.value()) {
        qCDebug(KLETTRES_LOG) << "Fail reading language !!! ";
        return false;
    } else {
        qCDebug(KLETTRES_LOG) << "current language " << currentLanguage;
    }
    //check here if alphabet and syllables both exist
    alphabetList = languageElement.elementsByTagName(QStringLiteral("alphabet"));
    syllablesList = languageElement.elementsByTagName(QStringLiteral("syllables"));

    //load the sounds for level 1 and 2 (alphabet)
    if ((Prefs::level() == 1) || (Prefs::level() == 2))  {
        if (alphabetList.count() != 1) {
            return false;
        }
        alphabetElement = (const QDomElement &) alphabetList.item(0).toElement();
        soundNamesList = alphabetElement.elementsByTagName(QStringLiteral("sound"));
    }

    //load the sounds for level 3 and 4 (syllables)
    if ((Prefs::level() == 3) || (Prefs::level() == 4))  {
        if (syllablesList.count() != 1) {
            Prefs::setLevel(1);
            Prefs::self()->save();
            return false;
        }

        syllableElement = (const QDomElement &) syllablesList.item(0).toElement();

        soundNamesList = syllableElement.elementsByTagName(QStringLiteral("sound"));
    }
    //Counts the number of sounds
    sounds = soundNamesList.count();
    qCDebug(KLETTRES_LOG) << "number of sounds" << sounds << endl;
    if (sounds < 1)  {
        return false;
    }
    namesList.clear();
    filesList.clear();

    for (uint sound = 0; sound < sounds; sound++)  {
        soundNameElement = (const QDomElement &) soundNamesList.item(sound).toElement();
        nameAttribute = soundNameElement.attributeNode(QStringLiteral("name"));
        //namesList helds the names of the letter or syllable to display
        namesList.append(nameAttribute.value());
        fileAttribute = soundNameElement.attributeNode(QStringLiteral("file"));
        //filesList helds the names of the sound files (i.e the location of the sounds like fr/alpha/a-0.mp3)
        filesList.append(fileAttribute.value());
    }
    if (namesList.isEmpty()) {
        return false;
    }
    if (filesList.isEmpty())  {
        return false;
    }
    return true;
}
Beispiel #25
0
void plotsDialog::savePlotSettings()
{

#ifdef Q_OS_WIN32
    QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
    QDir dir = qApp->applicationDirPath();
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    QString bundleDir(dir.absolutePath());
    QFile ofile(globalpara.caseName),file(bundleDir+"/plotTemp.xml");
#endif
    QTextStream stream;
    stream.setDevice(&file);
    QDomDocument doc;
    QDomElement plotData, currentPlot, general, legend, grid, curve;

    if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        globalpara.reportError("Failed to open and load case file for plot data.",this);
        return;
    }
    else
    {
        if(!doc.setContent(&file))
        {
            globalpara.reportError("Failed to set document for the xml file for plot data.",this);
            file.close();
            return;
        }
        else
        {
            plotData = doc.elementsByTagName("plotData").at(0).toElement();

            for(int i = 0; i < tabs->count(); i++)
            {
                Plot* set_plot = dynamic_cast<Plot*>(tabs->widget(i));
                currentPlot = plotData.elementsByTagName(tabs->tabText(i)).at(0).toElement();

                //general
                if(currentPlot.elementsByTagName("general").count()==0)
                {
                    general = doc.createElement("general");
                    currentPlot.appendChild(general);
                }
                else general = currentPlot.elementsByTagName("general").at(0).toElement();
                general.setAttribute("bgColor",set_plot->canvasBackground().color().name());
                general.setAttribute("lMargin",set_plot->contentsMargins().left());
                general.setAttribute("rMargin",set_plot->contentsMargins().right());
                general.setAttribute("tMargin",set_plot->contentsMargins().top());
                general.setAttribute("bMargin",set_plot->contentsMargins().bottom());
                general.setAttribute("plotTitle",set_plot->title().text());
                general.setAttribute("xTitle",set_plot->axisTitle(QwtPlot::xBottom).text());
                general.setAttribute("yTitle",set_plot->axisTitle(QwtPlot::yLeft).text());

                //legend
                if(currentPlot.elementsByTagName("legend").count()==0)
                {
                    legend = doc.createElement("legend");
                    currentPlot.appendChild(legend);
                }
                else legend = currentPlot.elementsByTagName("legend").at(0).toElement();
                if(set_plot->externalLegend!=NULL||set_plot->internalLegend->isVisible())
                {
                    legend.setAttribute("plotLegend","on");
                    if(set_plot->internalLegend->isVisible())
                    {
                        legend.setAttribute("extInt","int");
                        legend.setAttribute("nCol",set_plot->internalLegend->maxColumns());
                        legend.setAttribute("legendSize",set_plot->internalLegend->font().pointSize());
                    }
                    else if(set_plot->externalLegend!=NULL)
                    {
                        legend.setAttribute("extInt","ext");
                        legend.setAttribute("extPos",0);
                    }
                }
                else legend.setAttribute("plotLegend","off");

                //grid
                if(currentPlot.elementsByTagName("grid").count()==0)
                {
                    grid = doc.createElement("grid");
                    currentPlot.appendChild(grid);
                }
                else grid = currentPlot.elementsByTagName("grid").at(0).toElement();
                if(set_plot->grid->xEnabled()||set_plot->grid->yEnabled())
                {
                    if(set_plot->grid->xEnabled())
                        grid.setAttribute("xMaj","on");
                    else grid.setAttribute("xMaj","off");
                    if(set_plot->grid->yEnabled())
                        grid.setAttribute("yMaj","on");
                    else grid.setAttribute("yMaj","off");
                    grid.setAttribute("majColor",set_plot->grid->majorPen().color().name());
                    grid.setAttribute("majSize",set_plot->grid->majorPen().width());
                    int styleCode;
                    if(set_plot->grid->majorPen().style()==Qt::NoPen)
                        styleCode=0;
                    else if(set_plot->grid->majorPen().style()==Qt::SolidLine)
                        styleCode=1;
                    else if(set_plot->grid->majorPen().style()==Qt::DashLine)
                        styleCode=2;
                    else if(set_plot->grid->majorPen().style()==Qt::DotLine)
                        styleCode=3;
                    else if(set_plot->grid->majorPen().style()==Qt::DashDotLine)
                        styleCode=4;
                    else if(set_plot->grid->majorPen().style()==Qt::DashDotDotLine)
                        styleCode=5;
                    grid.setAttribute("majStyle",styleCode);
                }
                else
                {
                    grid.setAttribute("xMaj","off");
                    grid.setAttribute("yMaj","off");
                }
                if(set_plot->grid->xMinEnabled()||set_plot->grid->yMinEnabled())
                {
                    if(set_plot->grid->xMinEnabled())
                        grid.setAttribute("xMin","on");
                    else grid.setAttribute("xMin","off");
                    if(set_plot->grid->yMinEnabled())
                        grid.setAttribute("yMin","on");
                    else grid.setAttribute("yMin","off");
                    grid.setAttribute("minColor",set_plot->grid->minorPen().color().name());
                    grid.setAttribute("minSize",set_plot->grid->minorPen().width());
                    int styleCode;
                    if(set_plot->grid->minorPen().style()==Qt::NoPen)
                        styleCode=0;
                    else if(set_plot->grid->minorPen().style()==Qt::SolidLine)
                        styleCode=1;
                    else if(set_plot->grid->minorPen().style()==Qt::DashLine)
                        styleCode=2;
                    else if(set_plot->grid->minorPen().style()==Qt::DotLine)
                        styleCode=3;
                    else if(set_plot->grid->minorPen().style()==Qt::DashDotLine)
                        styleCode=4;
                    else if(set_plot->grid->minorPen().style()==Qt::DashDotDotLine)
                        styleCode=5;
                    grid.setAttribute("minStyle",styleCode);
                }
                else
                {
                    grid.setAttribute("xMin","off");
                    grid.setAttribute("yMin","off");
                }

                //curve
                QDomNode const oldCurveSettings = currentPlot.elementsByTagName("curve").at(0);
                currentPlot.removeChild(oldCurveSettings);
                curve = doc.createElement("curve");
                currentPlot.appendChild(curve);
//                if(currentPlot.elementsByTagName("curve").count()==0)
//                {
//                    curve = doc.createElement("curve");
//                    currentPlot.appendChild(curve);
//                }
//                else curve = currentPlot.elementsByTagName("curve").at(0).toElement();
//                if(curve.childNodes().count()!=set_plot->curvelist.count())
//                {
//                    QDomNode node;
//                    for(int i = 0; i < curve.childNodes().count();i++)
//                    {
//                        node = curve.childNodes().at(i);
//                        curve.removeChild(node);
//                    }
//                    QDomElement newCurve;
//                    for(int i = 0; i < set_plot->curvelist.count();i++)
//                    {
//                        newCurve = doc.createElement(set_plot->curvelist.at(i)->title().text().replace(" ",""));
//                        curve.appendChild(newCurve);
//                    }
//                }
                QDomElement currentCurve;
                QwtPlotCurve *thisCurve;
                for(int i = 0; i < set_plot->curvelist.count(); i++)
                {
                    currentCurve = doc.createElement(set_plot->curvelist.at(i)->title().text().replace(" ",""));
                    curve.appendChild(currentCurve);
                    thisCurve = set_plot->curvelist[i];
                    currentCurve = curve.elementsByTagName(set_plot->curvelist.at(i)->title().text().replace(" ","")).at(0).toElement();

                    if(thisCurve->isVisible())
                        currentCurve.setAttribute("isVisible","true");
                    else
                        currentCurve.setAttribute("isVisible","false");
                    currentCurve.setAttribute("lineColor",thisCurve->pen().color().name());
                    currentCurve.setAttribute("lineSize",thisCurve->pen().width());
                    int styleCode;
                    if(thisCurve->pen().style()==Qt::NoPen)
                        styleCode=0;
                    else if(thisCurve->pen().style()==Qt::SolidLine)
                        styleCode=1;
                    else if(thisCurve->pen().style()==Qt::DashLine)
                        styleCode=2;
                    else if(thisCurve->pen().style()==Qt::DotLine)
                        styleCode=3;
                    else if(thisCurve->pen().style()==Qt::DashDotLine)
                        styleCode=4;
                    else if(thisCurve->pen().style()==Qt::DashDotDotLine)
                        styleCode=5;
                    currentCurve.setAttribute("lineType",styleCode);
                }

            }

            file.resize(0);
            doc.save(stream,4);
            file.close();
            return;
        }
    }
}
Beispiel #26
0
void plotsDialog::on_dataSelectButton_clicked()
{
    QString pName = tabs->tabText(tabs->currentIndex());
    QString tableName;
    bool noTable = false;

    //make name-space for the new plot
#ifdef Q_OS_WIN32
    QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
    QDir dir = qApp->applicationDirPath();
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    QString bundleDir(dir.absolutePath());
    QFile file(bundleDir+"/plotTemp.xml");
#endif
    QTextStream stream;
    stream.setDevice(&file);
    if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
    {
        globalpara.reportError("Fail to open case file to copy plot.",this);
        return;
    }
    else
    {
        QDomDocument doc;
        if(!doc.setContent(&file))
        {
            globalpara.reportError("Fail to load xml document to copy plot..",this);
            file.close();
            return;
        }
        else
        {
            //look for the original table that generated the plot
            QDomElement tableData = doc.elementsByTagName("TableData").at(0).toElement();
            QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
            tableName = plotData.elementsByTagName(pName).at(0).toElement().attribute("tableName");
            if(tableData.elementsByTagName(tableName).count()==0)
            {
                noTable = true;
                file.close();
            }
            else
            {
                noTable = false;
                QDomElement oldPlot = plotData.elementsByTagName(pName).at(0).toElement();
                oldPlot.setTagName("tempNode");
                file.resize(0);
                doc.save(stream,4);
                file.close();
                stream.flush();
            }

        }
    }

    if(noTable)
        globalpara.reportError("The original table for this plot is not available in table data.");
    else
    {
        //ask for new selection of parameters
        newParaPlotDialog *pDialog = new newParaPlotDialog(2,tableName,pName,this);
        pDialog->setWindowTitle("Re-select Parameters");
        pDialog->setModal(true);
        if(pDialog->exec()==QDialog::Accepted)
        {
            //if accepted, delete the original node under name _mod
#ifdef Q_OS_WIN32
            QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
            QFile file(bundleDir+"/plotTemp.xml");
#endif
            QTextStream stream;
            stream.setDevice(&file);
            if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
            {
                globalpara.reportError("Fail to open case file to copy plot.",this);
                return;
            }
            else
            {
                QDomDocument doc;
                if(!doc.setContent(&file))
                {
                    globalpara.reportError("Fail to load xml document to copy plot...",this);
                    file.close();
                    return;
                }
                else
                {
                    QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
                    plotData.removeChild(plotData.elementsByTagName("tempNode").at(0));
                }
                file.resize(0);
                doc.save(stream,4);
                file.close();
                stream.flush();

                saveChanges();
                setupPlots(false);
            }

        }
        else
        {
            //if canceled, resume the original plot name
#ifdef Q_OS_WIN32
            QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
            QFile file(bundleDir+"/plotTemp.xml");
#endif

            QTextStream stream;
            stream.setDevice(&file);
            if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
            {
                globalpara.reportError("Fail to open case file to copy plot.",this);
                return;
            }
            else
            {
                QDomDocument doc;
                if(!doc.setContent(&file))
                {
                    globalpara.reportError("Fail to load xml document to copy plot....",this);
                    file.close();
                    return;
                }
                else
                {
                    QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
                    QDomElement oldPlot = plotData.elementsByTagName("tempNode").at(0).toElement();
                    oldPlot.setTagName(pName);
                }
                file.resize(0);
                doc.save(stream,4);
                file.close();
                stream.flush();
            }

        }



    }
}
Beispiel #27
0
void plotsDialog::deleteCurrentPlot()
{
    QMessageBox * askBox = new QMessageBox(this);
    askBox->addButton("Delete",QMessageBox::YesRole);
    askBox->addButton("Cancel",QMessageBox::NoRole);
    askBox->setText("Confirm to delete the plot?");
    askBox->setWindowTitle("Warning");
    askBox->exec();
    if(askBox->buttonRole(askBox->clickedButton())==QMessageBox::YesRole)
    {
        Plot* plotToDelete = dynamic_cast<Plot*>(tabs->currentWidget());
#ifdef Q_OS_WIN32
        QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
        QDir dir = qApp->applicationDirPath();
        /*dir.cdUp();*/
        /*dir.cdUp();*/
        /*dir.cdUp();*/
        QString bundleDir(dir.absolutePath());
        QFile file(bundleDir+"/plotTemp.xml");
#endif
        if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
        {
            return;
            globalpara.reportError("Fail to open xml file for plots!",this);
        }
        else
        {
            QDomDocument doc;
            QTextStream stream;
            stream.setDevice(&file);
            if(!doc.setContent(&file))
            {
                globalpara.reportError("Fail to load xml document for plots!",this);
                file.close();
                return;
            }
            else
            {
                QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
                plotData.removeChild(plotData.elementsByTagName(tabs->tabText(tabs->currentIndex())).at(0));
            }
            file.resize(0);
            doc.save(stream,4);
            file.close();
            stream.flush();
        }


        if(tabs->count()>1)
        {
            tabs->removeTab(tabs->currentIndex());
        }
        else if(tabs->count()==1)
        {
            this->close();
        }
    }
    else return;
}
Beispiel #28
0
void RevertQuery::CheckPreflight()
{
    if (this->OneEditOnly || this->IgnorePreflightCheck)
    {
        this->PreflightFinished = true;
        return;
    }
    if (this->qPreflight == nullptr || !this->qPreflight->IsProcessed())
        return;
    if (this->qPreflight->IsFailed())
    {
        Huggle::Syslog::HuggleLogs->Log(_l("revert-fail-pre-flight", this->qPreflight->Result->ErrorMessage));
        this->Kill();
        this->Result = new QueryResult();
        this->Status = StatusDone;
        this->Result->Failed = true;
        return;
    }
    QDomDocument d;
    d.setContent(this->qPreflight->Result->Data);
    QDomNodeList l = d.elementsByTagName("rev");
    int x=0;
    bool MadeBySameUser = true;
    bool MultipleEdits = false;
    bool PreviousEditsMadeBySameUser = true;
    bool passed = true;
    while (x < l.count())
    {
        QDomElement e = l.at(x).toElement();
        int RevID = WIKI_UNKNOWN_REVID;
        if (e.attributes().contains("revid"))
        {
            RevID = e.attribute("revid").toInt();
            if (edit->RevID == RevID)
            {
                x++;
                continue;
            }
        } else
        {
            x++;
            continue;
        }
        if (e.attributes().contains("user"))
        {
            QString user = e.attribute("user");
            if (PreviousEditsMadeBySameUser && this->edit->RevID != WIKI_UNKNOWN_REVID && RevID > this->edit->RevID)
            {
                if (user != this->edit->User->Username)
                {
                    PreviousEditsMadeBySameUser = false;
                }
                MultipleEdits = PreviousEditsMadeBySameUser;
            }
        }
        if (this->edit->RevID != WIKI_UNKNOWN_REVID && RevID > edit->RevID)
        {
            passed = false;
        }
        x++;
    }
    if (MultipleEdits && Configuration::HuggleConfiguration->ProjectConfig.ConfirmMultipleEdits)
    {
        passed = false;
    }
    if (!passed)
    {
        QString text = ":)";
        if (MultipleEdits)
        {
            // There are multiple edits by same user are you sure you want to revert them
            text = (_l("cr-message-same", this->edit->Page->PageName));
        } else if (MadeBySameUser)
        {
            // There are newer edits, are you sure you want to revert them
            text = (_l("cr-message-new", this->edit->Page->PageName));
        } else
        {
            text = (_l("cr-message-not-same", this->edit->Page->PageName));
        }
        if (Configuration::HuggleConfiguration->UserConfig_AutomaticallyResolveConflicts)
        {
            if (MultipleEdits && !Configuration::HuggleConfiguration->RevertOnMultipleEdits)
            {
                Huggle::Syslog::HuggleLogs->Log(_l("cr-stop-multiple-same", this->edit->Page->PageName));
                this->Cancel();
                return;
            } else if (MultipleEdits && Configuration::HuggleConfiguration->RevertOnMultipleEdits)
            {
                /// \todo LOCALIZE ME
                Huggle::Syslog::HuggleLogs->Log("Conflict resolved: revert all edits - there are multiple edits by same user to " + this->edit->Page->PageName);
            } else
            {
                if (PreviousEditsMadeBySameUser && Configuration::HuggleConfiguration->UserConfig.RevertNewBySame)
                {
                    Huggle::Syslog::HuggleLogs->Log(_l("cr-resolved-same-user", this->edit->Page->PageName));
                } else
                {
                    /// \todo LOCALIZE ME
                    Huggle::Syslog::HuggleLogs->Log("Conflict resolved: do not perform any action - there are newer edits to " + this->edit->Page->PageName);
                    this->Cancel();
                    return;
                }
            }
        }
        QMessageBox::StandardButton re;
        re = QMessageBox::question(Core::HuggleCore->Main, _l("revert-preflightcheck"), text, QMessageBox::Yes|QMessageBox::No);
        if (re == QMessageBox::No)
        {
            // abort
            this->Exit();
            this->CustomStatus = "Stopped";
            this->Result = new QueryResult();
            this->Result->Failed = true;
            this->Result->ErrorMessage = "User requested to abort this";
            this->Status = StatusDone;
            this->PreflightFinished = true;
            return;
        }
    }
    this->PreflightFinished = true;
}
Beispiel #29
0
bool RevertQuery::ProcessRevert()
{
    if (!this->SR_EditToken.size() && this->qSR_PageToken == nullptr)
    {
        // we need to obtain edit token on beginning so that we prevent edit conflict resolution
        this->qSR_PageToken = new ApiQuery();
        this->qSR_PageToken->SetAction(ActionQuery);
        this->qSR_PageToken->Parameters = "prop=info&intoken=edit&titles=" + QUrl::toPercentEncoding(this->edit->Page->PageName);
        this->qSR_PageToken->Target = _l("editquery-token", this->edit->Page->PageName);
        this->qSR_PageToken->RegisterConsumer(HUGGLECONSUMER_REVERTQUERY);
        this->CustomStatus = "Retrieving token";
        QueryPool::HugglePool->AppendQuery(this->qSR_PageToken);
        this->qSR_PageToken->Process();
        return false;
    }
    if (this->qSR_PageToken != nullptr)
    {
        if (!this->qSR_PageToken->IsProcessed())
            return false;

        if (this->qSR_PageToken->IsFailed())
        {
            this->DisplayError("Unable to fetch the token - query failed");
            return true;
        }
        QDomDocument d;
        d.setContent(this->qSR_PageToken->Result->Data);
        QDomNodeList l = d.elementsByTagName("page");
        if (l.count() == 0)
        {
            this->DisplayError("Unable to fetch the token no page info returned by wiki");
            return true;
        }
        QDomElement element = l.at(0).toElement();
        if (!element.attributes().contains("edittoken"))
        {
            this->DisplayError("Unable to get a token there was no token returned by wiki");
            return true;
        }
        this->SR_EditToken = element.attribute("edittoken");
        if (this->SR_EditToken.size() == 0)
        {
            // invalid token
            this->DisplayError("Invalid token");
            return true;
        }
        this->qSR_PageToken->UnregisterConsumer(HUGGLECONSUMER_REVERTQUERY);
        this->qSR_PageToken = nullptr;
    }
    if (this->eqSoftwareRollback != nullptr)
    {
        // we already reverted the page so check if we were successful in that
        if (this->eqSoftwareRollback->IsProcessed() == false)
        {
            // we are still reverting the page so quit this and wait
            return false;
        }
        this->eqSoftwareRollback->UnregisterConsumer(HUGGLECONSUMER_REVERTQUERY);
        this->Result = new QueryResult();
        if (this->eqSoftwareRollback->Result->Failed || this->eqSoftwareRollback->Status == Huggle::StatusInError)
        {
            // failure during revert
            this->Result->Failed = true;
            this->Result->ErrorMessage = this->eqSoftwareRollback->Result->ErrorMessage;
            Syslog::HuggleLogs->ErrorLog(_l("revert-fail", this->edit->Page->PageName,
                                                                                      "edit failed"));
            this->Kill();
            this->Status = StatusDone;
        }
        Syslog::HuggleLogs->DebugLog("Sucessful SR of page " + this->edit->Page->PageName);
        return true;
    }
    if (this->qRetrieve != nullptr)
    {
        // we are retrieving the content of previous edit made by a different user
        if (!this->qRetrieve->IsProcessed())
        {
            return false;
        }
        if (this->qRetrieve->IsFailed())
        {
            this->DisplayError("Unable to rollback the edit because previous content couldn't be retrieved");
            return true;
        }
        QString summary = this->Summary;
        QString content = "";
        QDomDocument d;
        d.setContent(this->qRetrieve->Result->Data);
        QDomNodeList l = d.elementsByTagName("rev");
        if (l.count() == 0)
        {
            this->DisplayError("Unable to rollback the edit because previous content couldn't be retrieved");
            return true;
        }
        QDomElement element = l.at(0).toElement();
        if (!element.attributes().contains("revid"))
        {
            this->DisplayError("Unable to rollback the edit because query used to retrieve the content of previous"\
                               " version retrieved no RevID");
            return true;
        }
        QString rv = element.attribute("revid");
        if (rv.toInt() != this->SR_RevID)
        {
            this->DisplayError("Unable to rollback the edit because query used to retrieve the content of previous"\
                               " version returned invalid RevID");
            return true;
        }
        content = element.text();
        if (summary.size() == 0)
            summary = Configuration::HuggleConfiguration->ProjectConfig.SoftwareRevertDefaultSummary;
        summary = summary.replace("$1", this->edit->User->Username)
                .replace("$2", this->SR_Target)
                .replace("$3", QString::number(this->SR_Depth))
                .replace("$4", QString::number(this->SR_RevID));
        // we need to make sure there is edit suffix in revert summary for huggle
        summary = Huggle::Configuration::HuggleConfiguration->GenerateSuffix(summary);
        if (content == "")
        {
            /// \todo LOCALIZE ME
            this->DisplayError("Cowardly refusing to blank \"" + this->edit->Page->PageName +
                               "\" software rollback was cancelled to prevent damage",
                               "content was resolved to blank edit");
            return true;
        }
        this->eqSoftwareRollback = WikiUtil::EditPage(this->edit->Page, content, summary, this->MinorEdit);
        this->eqSoftwareRollback->RegisterConsumer(HUGGLECONSUMER_REVERTQUERY);
        // we can remove the anonymous ref now
        this->eqSoftwareRollback->DecRef();
        /// \todo LOCALIZE ME
        this->CustomStatus = "Editing page";
        return false;
    }
    if (this->qHistoryInfo == nullptr || !this->qHistoryInfo->IsProcessed())
        return false;
    if (this->qHistoryInfo->Result->Failed)
    {
        this->DisplayError("Failed to retrieve a list of edits made to this page: " + this->qHistoryInfo->Result->ErrorMessage);
        return true;
    }
    QDomDocument d;
    d.setContent(this->qHistoryInfo->Result->Data);
    QDomNodeList l = d.elementsByTagName("rev");
    // we need to find a first revision that is made by a different user
    // but first we need to check if last revision was actually made by this user, because if not
    // it's possible that someone else already reverted them
    if (l.count() == 0)
    {
        // if we have absolutely no revisions in the result, it's pretty f****d
        this->DisplayError("Failed to retrieve a list of edits made to this page, query returned no data");
        return true;
    }
    // if the latest revid doesn't match our revid it means that someone made an edit
    bool passed = true;
    this->SR_Depth = 0;
    int x = 0;
    while (x < l.count())
    {
        QDomElement e = l.at(x).toElement();
        x++;
        if (e.attributes().contains("revid"))
        {
            if (edit->RevID == e.attribute("revid").toInt())
                continue;
            if (this->edit->RevID != WIKI_UNKNOWN_REVID && e.attribute("revid").toInt() > edit->RevID)
                passed = false;
        }
    }
    if (!passed)
    {
        this->DisplayError("Unable to revert the page " + this->edit->Page->PageName + " because it was edited meanwhile");
        return true;
    }
    // now we need to find the first revision that was done by some different user
    x = 0;
    //! \todo this list needs to be sorted by RevID
    while (x < l.count())
    {
        QDomElement e = l.at(x).toElement();
        if (!e.attributes().contains("revid") || !e.attributes().contains("user"))
        {
            // this is f****d up piece of shit
            this->DisplayError("Unable to revert the page " + this->edit->Page->PageName + " because mediawiki returned some non-sense");
            Huggle::Syslog::HuggleLogs->DebugLog("Nonsense: " + this->qHistoryInfo->Result->Data);
            return true;
        }
        // in case we are in depth higher than 0 (we passed out own edit) and we want to revert only 1 revision we exit
        if ((this->SR_Depth >= 1 && this->OneEditOnly) || e.attribute("user") != this->edit->User->Username)
        {
            // we got it, this is the revision we want to revert to
            this->SR_RevID = e.attribute("revid").toInt();
            this->SR_Target = e.attribute("user");
            break;
        }
        this->SR_Depth++;
        x++;
    }
    // let's check if depth isn't too low
    if (this->SR_Depth == 0)
    {
        // something is wrong
        this->DisplayError(_l("revert-fail", this->edit->Page->PageName, "because it was edited meanwhile"));
        return true;
    }
    if (this->SR_RevID == WIKI_UNKNOWN_REVID)
    {
        this->DisplayError(_l("revert-fail", this->edit->Page->PageName,
                                                                        "because no previous version could be retrieved"));
        return true;
    }
    this->CustomStatus = "Retrieving content of previous version";
    // now we need to get the content of page
    this->qRetrieve = new ApiQuery(ActionQuery);
    this->qRetrieve->RegisterConsumer(HUGGLECONSUMER_REVERTQUERY);
    this->qRetrieve->Parameters = "prop=revisions&revids=" + QString::number(this->SR_RevID) + "&rvprop=" +
                                  QUrl::toPercentEncoding("ids|content");
    this->qRetrieve->Process();
    return false;
}
/**

Restore any optional properties found in "doc" to "properties".

properties tags for all optional properties.  Within that there will be scope
tags.  In the following example there exist one property in the "fsplugin"
scope.  "layers" is a list containing three string values.

\verbatim
<properties>
  <fsplugin>
    <foo type="int" >42</foo>
    <baz type="int" >1</baz>
    <layers type="QStringList" >
      <value>railroad</value>
      <value>airport</value>
    </layers>
    <xyqzzy type="int" >1</xyqzzy>
    <bar type="double" >123.456</bar>
    <feature_types type="QStringList" >
       <value>type</value>
    </feature_types>
  </fsplugin>
</properties>
\endverbatim

@param doc xml document
@param project_properties should be the top QgsPropertyKey node.

*/
static
void
_getProperties( QDomDocument const &doc, QgsPropertyKey & project_properties )
{
  QDomNodeList properties = doc.elementsByTagName( "properties" );

  if ( properties.count() > 1 )
  {
    QgsDebugMsg( "there appears to be more than one ``properties'' XML tag ... bailing" );
    return;
  }
  else if ( properties.count() < 1 )  // no properties found, so we're done
  {
    return;
  }

  // item(0) because there should only be ONE
  // "properties" node
  QDomNodeList scopes = properties.item( 0 ).childNodes();

  if ( scopes.count() < 1 )
  {
    QgsDebugMsg( "empty ``properties'' XML tag ... bailing" );
    return;
  }

  QDomNode propertyNode = properties.item( 0 );

  if ( ! project_properties.readXML( propertyNode ) )
  {
    QgsDebugMsg( "Project_properties.readXML() failed" );
  }

#if 0
// DEPRECATED as functionality has been shoved down to QgsProperyKey::readXML()
  size_t i = 0;
  while ( i < scopes.count() )
  {
    QDomNode curr_scope_node = scopes.item( i );

    qDebug( "found %d property node(s) for scope %s",
            curr_scope_node.childNodes().count(),
            curr_scope_node.nodeName().utf8().constData() );

    QString key( curr_scope_node.nodeName() );

    QgsPropertyKey * currentKey =
      dynamic_cast<QgsPropertyKey*>( project_properties.find( key ) );

    if ( ! currentKey )
    {
      // if the property key doesn't yet exist, create an empty instance
      // of that key

      currentKey = project_properties.addKey( key );

      if ( ! currentKey )
      {
        qDebug( "%s:%d unable to add key", __FILE__, __LINE__ );
      }
    }

    if ( ! currentKey->readXML( curr_scope_node ) )
    {
      qDebug( "%s:%d unable to read XML for property %s", __FILE__, __LINE__,
              curr_scope_node.nodeName().utf8().constData() );
    }

    ++i;
  }
#endif
} // _getProperties