Пример #1
0
  bool ConfigBase::convertProfile( const QString &profile ) {

    if ( profile.isNull() || profile.isEmpty() ) {

      return false;
    }

    QFile xml( profile );

    if ( !xml.exists() ) {
      return false;
    }

    xml.open( QIODevice::ReadOnly );

    QDomDocument doc;
    doc.setContent( &xml );

    xml.close();

    QDomNode node = doc.documentElement().firstChild();

    QString dosboxBinary, dosboxVersion;

#ifdef Q_OS_UNIX
    dosboxBinary = searchDosboxBinary();
    dosboxVersion = "0.72";
#endif

    QStringList gameProfiles;
    bool winHide = true;
    bool keyMapper = false;

    while ( !node.isNull() ) {
      qApp->processEvents();

      if ( node.toElement().tagName() == "software_info" ) {

        // iterate over section node
        QDomNode sectionNode = node;

        while ( !sectionNode.isNull() ) {
          qApp->processEvents();

          // iterate over setting node
          QDomNode settingNode = sectionNode.firstChild();

          while ( !settingNode.isNull() ) {
            qApp->processEvents();

            QString name = settingNode.toElement().attribute( "name" );

            if ( name == "binary" ) {

              dosboxBinary = settingNode.toElement().text();
            } else if ( name == "version" ) {

              dosboxVersion = settingNode.toElement().text();
            } else if ( name == "winHide" ) {

              winHide = settingNode.toElement().text() == "false" || settingNode.toElement().text().isEmpty() || settingNode.toElement().text().isNull() ? false : true;
            } else if ( name == "keyMapper" ) {

              keyMapper = settingNode.toElement().text() == "false" || settingNode.toElement().text().isEmpty() || settingNode.toElement().text().isNull() ? false : true;
            } else if ( settingNode.hasChildNodes() ) {

              // iterate over setting child nodes
              QDomNode settingChildNode = settingNode.firstChild();

              while ( !settingChildNode.isNull() ) {
                qApp->processEvents();

                if ( settingChildNode.toElement().tagName() == "value" ) {

                  gameProfiles.append( settingChildNode.toElement().text() );
                }

                settingChildNode = settingChildNode.nextSibling();
              }

            }

            settingNode = settingNode.nextSibling();
          }

          sectionNode = sectionNode.nextSibling();
        }
      }

      node = node.nextSibling();
    }

    xmlPreferences().setString( "binary", dosboxBinary, "DOSBox" );

    xmlPreferences().setString( "version", dosboxVersion, "DOSBox" );

    if ( gameProfiles.isEmpty() || gameProfiles.size() <= 0 ) {
      gameProfiles = readProfiles();
    }

    xmlPreferences().setStringList( "Name", gameProfiles, "Profile" );

    xmlPreferences().setBool( "winHide", winHide, "DBoxFE" );
    xmlPreferences().setBool( "keyMapper", keyMapper, "DBoxFE" );
    bool saved = xmlPreferences().save( settingFile() );

    return saved;
  }
Пример #2
0
QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer(
  const QDomElement& elem,
  const QString& layerName,
  QList<QTemporaryFile*>& filesToRemove,
  QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  if ( elem.isNull() )
  {
    return nullptr;
  }

  //parse service element
  QDomNode serviceNode = elem.namedItem( QStringLiteral( "Service" ) );
  if ( serviceNode.isNull() )
  {
    QgsDebugMsg( "No <Service> node found, returning 0" );
    return nullptr; //service node is necessary
  }

  //parse OnlineResource element
  QDomNode onlineResourceNode = elem.namedItem( QStringLiteral( "OnlineResource" ) );
  if ( onlineResourceNode.isNull() )
  {
    QgsDebugMsg( "No <OnlineResource> element, returning 0" );
    return nullptr;
  }

  //get uri
  QDomElement onlineResourceElement = onlineResourceNode.toElement();
  QString url = onlineResourceElement.attribute( QStringLiteral( "href" ) );

  QgsMapLayer* result = nullptr;
  QString serviceName = serviceNode.toElement().text();

  //append missing ? or & at the end of the url, but only for WFS and WMS
  if ( serviceName == QLatin1String( "WFS" ) || serviceName == QLatin1String( "WMS" ) )
  {
    if ( !url.endsWith( QLatin1String( "?" ) ) && !url.endsWith( QLatin1String( "&" ) ) )
    {
      if ( url.contains( QLatin1String( "?" ) ) )
      {
        url.append( "&" );
      }
      else
      {
        url.append( "?" );
      }
    }
  }


  if ( serviceName == QLatin1String( "WFS" ) )
  {
    //support for old format where type is explicitly given and not part of url
    QString tname = onlineResourceElement.attribute( QStringLiteral( "type" ) );
    if ( !tname.isEmpty() )
    {
      url.append( "SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=" + tname );
    }

    if ( allowCaching )
    {
      result = QgsMSLayerCache::instance()->searchLayer( url, layerName );
    }
    if ( result )
    {
      return result;
    }
    result = new QgsVectorLayer( url, layerNameFromUri( url ), QStringLiteral( "WFS" ) );
    if ( result->isValid() )
    {
      if ( allowCaching )
      {
        QgsMSLayerCache::instance()->insertLayer( url, layerName, result );
      }
      else
      {
        layersToRemove.push_back( result );
      }
    }
  }
  else if ( serviceName == QLatin1String( "WMS" ) )
  {
    result = wmsLayerFromUrl( url, layerName, layersToRemove, allowCaching );
  }
  else if ( serviceName == QLatin1String( "WCS" ) )
  {
    QgsDebugMsg( "Trying to get WCS layer" );
    result = wcsLayerFromUrl( url, layerName, filesToRemove, layersToRemove );
  }
  else if ( serviceName == QLatin1String( "SOS" ) )
  {
    result = sosLayer( elem, url, layerName, layersToRemove, allowCaching );
  }

  if ( !result || !result->isValid() )
  {
    QgsDebugMsg( "Error, maplayer is 0 or invalid" );
    if ( result )
    {
      delete result;
    }
    return nullptr;
  }

  return result;
}
Пример #3
0
SyncDocument *SyncDocument::load(const QString &fileName)
{
	SyncDocument *ret = new SyncDocument;
	ret->fileName = fileName;

	QFile file(fileName);
	if (!file.open(QIODevice::ReadOnly)) {
		QMessageBox::critical(NULL, "Error", file.errorString());
		return NULL;
	}

	QDomDocument doc;
	QString err;
	if (!doc.setContent(&file, &err)) {
		file.close();
		QMessageBox::critical(NULL, "Error", err);
		return NULL;
	}
	file.close();

	QDomNamedNodeMap attribs = doc.documentElement().attributes();
	QDomNode rowsParam = attribs.namedItem("rows");
	if (!rowsParam.isNull()) {
		QString rowsString = rowsParam.nodeValue();
		ret->setRows(rowsString.toInt());
	}

	QDomNodeList trackNodes =
	    doc.documentElement().elementsByTagName("track");
	for (int i = 0; i < trackNodes.count(); ++i) {
		QDomNode trackNode = trackNodes.item(i);
		QDomNamedNodeMap attribs = trackNode.attributes();

		QString name = attribs.namedItem("name").nodeValue();

		// look up track-name, create it if it doesn't exist
		SyncTrack *t = ret->findTrack(name.toUtf8());
		if (!t)
			t = ret->createTrack(name.toUtf8().constData());

		QDomNodeList rowNodes = trackNode.childNodes();
		for (int i = 0; i < rowNodes.count(); ++i) {
			QDomNode keyNode = rowNodes.item(i);
			QString baseName = keyNode.nodeName();
			if (baseName == "key") {
				QDomNamedNodeMap rowAttribs = keyNode.attributes();
				QString rowString = rowAttribs.namedItem("row").nodeValue();
				QString valueString = rowAttribs.namedItem("value").nodeValue();
				QString interpolationString = rowAttribs.namedItem("interpolation").nodeValue();

				SyncTrack::TrackKey k;
				k.row = rowString.toInt();
				k.value = valueString.toFloat();
				k.type = SyncTrack::TrackKey::KeyType(interpolationString.toInt());

				Q_ASSERT(!t->isKeyFrame(k.row));
				t->setKey(k);
			}
		}
	}

	// YUCK: gathers from entire document
	QDomNodeList bookmarkNodes =
	    doc.documentElement().elementsByTagName("bookmark");
	for (int i = 0; i < bookmarkNodes.count(); ++i) {
		QDomNode bookmarkNode =
		    bookmarkNodes.item(i);
		QDomNamedNodeMap bookmarkAttribs =
		    bookmarkNode.attributes();
		QString str =
		    bookmarkAttribs.namedItem("row").nodeValue();
		int row = str.toInt();
		ret->toggleRowBookmark(row);
	}

	return ret;
}
Пример #4
0
void XMLHandler::add_files(QList<QString> file_list)
{
	QDomDocument doc;
	QFile file(filename);
	if (!file.open(QIODevice::ReadOnly))
	    return;
	if (!doc.setContent(&file)) {
	    file.close();
	    return;
	}
	file.close();

	QDomElement docElem = doc.documentElement();
	QDomNode n = docElem.firstChild();
	QDomElement files_tag;
	while(!n.isNull()) {
	    QDomElement e = n.toElement();
	    if(!e.isNull() && e.tagName() == "Files") {
	        files_tag = e;
	    }
	    n = n.nextSibling();
	}

	// get file ID of last file element
	QDomElement last_file_element = files_tag.lastChildElement();
	QString last_file_ID_str = last_file_element.attribute("ID");
	int last_file_ID = last_file_ID_str.toInt();

	// TODO: check for duplicate files

	// append files from QList<QString>
	int file_ID= last_file_ID + 1;
	for (int i = 0; i < file_list.size(); ++i)
	{
	    QString path = file_list[i];
	    QString filename = path.section("/",-1,-1);

	    QDomElement file_tag = doc.createElement("File");
	    file_tag.setAttribute("ID", QString::number(file_ID));
	    files_tag.appendChild(file_tag);
	    file_ID++;

	    QDomElement file_name_tag = doc.createElement("Name");
	    file_tag.appendChild(file_name_tag);
	    QDomText t1 = doc.createTextNode(filename);
	    file_name_tag.appendChild(t1);

	    QDomElement location_name_tag = doc.createElement("Location");
	    file_tag.appendChild(location_name_tag);
	    QDomText t2 = doc.createTextNode(path);
	    location_name_tag.appendChild(t2);
    }

    // write to file
    QString xml = doc.toString();

    if (!file.open(QFile::WriteOnly | QFile::Text))
    {
        qDebug() << "Could not open file for writing!";
    }

    QTextStream out(&file);
    out << xml;
    file.flush();
    file.close();
}
Пример #5
0
void VCButton_Test::save()
{
    QWidget w;

    Scene* sc = new Scene(m_doc);
    m_doc->addFunction(sc);
    m_doc->setWorkspacePath(QDir("../../../gfx").absolutePath());

    VCButton btn(&w, m_doc);
    btn.setCaption("Foobar");
    btn.setIconPath("../../../gfx/qlcplus.png");
    btn.setFunction(sc->id());
    btn.setAction(VCButton::Flash);
    btn.setKeySequence(QKeySequence(keySequenceB));
    btn.setAdjustIntensity(true);
    btn.setIntensityAdjustment(0.2);

    QDomDocument xmldoc;
    QDomElement root = xmldoc.createElement("Root");
    xmldoc.appendChild(root);

    int function = 0, action = 0, key = 0, intensity = 0, wstate = 0, appearance = 0;
    QCOMPARE(btn.saveXML(&xmldoc, &root), true);
    QDomElement tag = root.firstChild().toElement();
    QCOMPARE(tag.tagName(), QString("Button"));
    QCOMPARE(tag.attribute("Icon"), QString("qlcplus.png"));
    QCOMPARE(tag.attribute("Caption"), QString("Foobar"));
    QDomNode node = tag.firstChild();
    while (node.isNull() == false)
    {
        QDomElement tag = node.toElement();
        if (tag.tagName() == "Function")
        {
            function++;
            QCOMPARE(tag.attribute("ID"), QString::number(sc->id()));
        }
        else if (tag.tagName() == "Action")
        {
            action++;
            QCOMPARE(tag.text(), QString("Flash"));
        }
        else if (tag.tagName() == "Key")
        {
            key++;
            QCOMPARE(tag.text(), QKeySequence(keySequenceB).toString());
        }
        else if (tag.tagName() == "Intensity")
        {
            intensity++;
            QCOMPARE(tag.attribute("Adjust"), QString("True"));
            QCOMPARE(tag.text(), QString("20"));
        }
        else if (tag.tagName() == "WindowState")
        {
            wstate++;
        }
        else if (tag.tagName() == "Appearance")
        {
            appearance++;
        }
        else
        {
            QFAIL(QString("Unexpected tag: %1").arg(tag.tagName()).toUtf8().constData());
        }

        node = node.nextSibling();
    }

    QCOMPARE(function, 1);
    QCOMPARE(action, 1);
    QCOMPARE(key, 1);
    QCOMPARE(intensity, 1);
    QCOMPARE(wstate, 1);
    QCOMPARE(appearance, 1);
}
Пример #6
0
bool TemporalVarianceBGModule::setParameters(QDomNode& config)
{
	QDomNode n;
	if(config.isNull())  //Parameter set for module not defined
	{
		this->bgSizeWindow = 11;
		this->fgSizeWindow = 5; //influye en la permanencia de los fantasmas.
		this->detectionFactorThreshold = 7.0;//valores altos, clasifican a mas pixeles como fondo
		this->fgVarianceThreshold = 187.0;//un pixel con varianza mayor a este umbral es considerado pixel en movimiento
		this->factorSigmoid = 3;//entre mas grande es este valor, mas pixeles son clasificados como fondo

		this->minScale = 0;
		this->maxScale = 80;
		this->displayFirstModel = true;
		this->displayFeatureMap = true;
	m_tuningActivated = false;
	}
	else
	{
		if( !( n = XmlCommon::XmlCommon::getParameterNode("bgSizeWindow", config) ).isNull() )
				this->bgSizeWindow = XmlCommon::getParameterValue(n).toInt();
		else
		{
			this->bgSizeWindow = 9;
						AppendToLog("TemporalVarianceBGModule: Warning: 'bgSizeWindow' not defined. Taking defaults: \n\t\tbgSizeWindow = " + QString::number(this->bgSizeWindow) + "\n");
		}
		if( !( n = XmlCommon::XmlCommon::getParameterNode("fgSizeWindow", config) ).isNull() )
			this->fgSizeWindow = XmlCommon::getParameterValue(n).toInt();
		else
		{
			this->fgSizeWindow = 4;
						AppendToLog("TemporalVarianceBGModule: Warning: 'fgSizeWindow' not defined. Taking defaults: \n\t\tfgSizeWindow = " + QString::number(this->fgSizeWindow) + "\n");
		}
		if( !( n = XmlCommon::XmlCommon::getParameterNode("detectionFactorThreshold", config) ).isNull() )
			this->detectionFactorThreshold = XmlCommon::getParameterValue(n).toFloat();
		else
		{
			this->detectionFactorThreshold = 7;
						AppendToLog("TemporalVarianceBGModule: Warning: 'detectionFactorThreshold' not defined. Taking defaults: \n\t\tdetectionFactorThreshold = " + QString::number(this->detectionFactorThreshold) + "\n");
		}
		if( !( n = XmlCommon::XmlCommon::getParameterNode("fgVarianceThreshold", config) ).isNull() )
			this->fgVarianceThreshold = XmlCommon::getParameterValue(n).toFloat();
		else
		{
			this->fgVarianceThreshold = 187;
						AppendToLog("TemporalVarianceBGModule: Warning: 'fgVarianceThreshold' not defined. Taking defaults: \n\t\tfgVarianceThreshold = " + QString::number(this->fgVarianceThreshold) + "\n");
		}
		if( !( n = XmlCommon::XmlCommon::getParameterNode("factorSigmoid", config) ).isNull() )
			this->factorSigmoid = XmlCommon::getParameterValue(n).toInt();
		else
		{
			this->factorSigmoid = 3;
						AppendToLog("TemporalVarianceBGModule: Warning: 'factorSigmoid' not defined. Taking defaults: \n\t\tfactorSigmoid = " + QString::number(this->factorSigmoid) + "\n");
		}
		if( !( n = XmlCommon::XmlCommon::getParameterNode("minScale", config) ).isNull() )
			this->minScale = XmlCommon::getParameterValue(n).toInt();
		else
		{
			this->minScale = 0;
			AppendToLog("TemporalVarianceBGModule: Warning: 'minScale' not defined. Taking defaults: \n\t\tminScale = " + QString::number(this->minScale) + "\n");
		}
		if( !( n = XmlCommon::XmlCommon::getParameterNode("maxScale", config) ).isNull() )
			this->maxScale = XmlCommon::getParameterValue(n).toInt();
		else
		{
			this->maxScale = 255;
			AppendToLog("TemporalVarianceBGModule: Warning: 'maxScale' not defined. Taking defaults: \n\t\tmaxScale = " + QString::number(this->maxScale) + "\n");
		}
		if( !( n = XmlCommon::XmlCommon::getParameterNode("displayFeatureMap", config) ).isNull() )
			this->displayFeatureMap  = XmlCommon::getParameterValue(n) == "true" ? true : false;
		else
		{
			this->displayFeatureMap = false;
			AppendToLog("TemporalVarianceBGModule: Warning: 'displayFeatureMap' not defined. Taking defaults: \n\t\tdisplayFeatureMap = false \n");
		}
		if( !( n = XmlCommon::XmlCommon::getParameterNode("displayFirstModel", config) ).isNull() )
			this->displayFirstModel  = XmlCommon::getParameterValue(n) == "true" ? true : false;
		else
		{
			this->displayFirstModel = false;
			AppendToLog("TemporalVarianceBGModule: Warning: 'displayFirstModel' not defined. Taking defaults: \n\t\tdisplayFirstModel = false \n");
		}

        if( ( n = XmlCommon::getParameterNode("TuningActivated", config) ).isNull() ) {
            m_tuningActivated = false;
        } else {
            m_tuningActivated = XmlCommon::getParameterValue(n) == "true" ? true : false;
            if(m_tuningActivated) {
                m_data->tuningEnded = false;
            }
        }


	}

	//Setea la lista de parametros y la lista de tipos de parametros utilizadas en el ParameterDialog.
	addParameter("bgSizeWindow", QString::number(this->bgSizeWindow), "int");
	addParameter("fgSizeWindow", QString::number(this->fgSizeWindow), "int");
	addParameter("detectionFactorThreshold", QString::number(this->detectionFactorThreshold), "float");
	addParameter("fgVarianceThreshold", QString::number(this->fgVarianceThreshold), "float");
	addParameter("factorSigmoid", QString::number(this->factorSigmoid), "int");
	addParameter("minScale", QString::number(this->minScale), "uchar");
	addParameter("maxScale", QString::number(this->maxScale), "uchar");
	addParameter("displayFeatureMap", (this->displayFeatureMap== true)? "yes" : "no", "bool");
	addParameter("displayFirstModel", (this->displayFirstModel== true)? "yes" : "no", "bool");

	return true;
}
Пример #7
0
bool Chaser::loadXML(const QDomElement* root)
{
	QDomNode node;
	QDomElement tag;

	Q_ASSERT(root != NULL);

	if (root->tagName() != KXMLQLCFunction)
	{
		qDebug() << "Function node not found!";
		return false;
	}

        if (root->attribute(KXMLQLCFunctionType) !=
            typeToString(Function::Chaser))
        {
                qWarning("Function is not a chaser!");
                return false;
        }

	/* Load chaser contents */
	node = root->firstChild();
	while (node.isNull() == false)
	{
		tag = node.toElement();

		if (tag.tagName() == KXMLQLCBus)
		{
			/* Bus */
			setBus(tag.text().toUInt());
		}
		else if (tag.tagName() == KXMLQLCFunctionDirection)
		{
			/* Direction */
			setDirection(Function::stringToDirection(tag.text()));
		}
		else if (tag.tagName() == KXMLQLCFunctionRunOrder)
		{
			/* Run Order */
			setRunOrder(Function::stringToRunOrder(tag.text()));
		}
		else if (tag.tagName() == KXMLQLCFunctionStep)
		{
			t_function_id fid = -1;
			int num = 0;

			num = tag.attribute(KXMLQLCFunctionNumber).toInt();
			fid = tag.text().toInt();

			/* Don't check for the member function's existence,
			   because it might not have been loaded yet. */
			if (num >= m_steps.size())
				m_steps.append(fid);
			else
				m_steps.insert(num, fid);
		}
		else
		{
			qDebug() << "Unknown chaser tag:" << tag.tagName();
		}

		node = node.nextSibling();
	}

	return true;
}
Пример #8
0
bool VCSlider::loadXML(const QDomElement* root)
{
    bool visible = false;
    int x = 0;
    int y = 0;
    int w = 0;
    int h = 0;

    SliderMode sliderMode = Playback;
    QDomElement tag;
    QDomNode node;
    QString caption;
    QString str;

    Q_ASSERT(root != NULL);

    if (root->tagName() != KXMLQLCVCSlider)
    {
        qWarning() << Q_FUNC_INFO << "Slider node not found";
        return false;
    }

    /* Caption */
    caption = root->attribute(KXMLQLCVCCaption);
    if (root->attribute(KXMLQLCVCSliderInvertedAppearance) == "false")
        setInvertedAppearance(false);
    else
        setInvertedAppearance(true);

    /* Children */
    node = root->firstChild();
    while (node.isNull() == false)
    {
        tag = node.toElement();
        if (tag.tagName() == KXMLQLCWindowState)
        {
            loadXMLWindowState(&tag, &x, &y, &w, &h, &visible);
            setGeometry(x, y, w, h);
        }
        else if (tag.tagName() == KXMLQLCVCWidgetAppearance)
        {
            loadXMLAppearance(&tag);
        }
        else if (tag.tagName() == KXMLQLCVCSliderMode)
        {
            sliderMode = stringToSliderMode(tag.text());

            str = tag.attribute(KXMLQLCVCSliderValueDisplayStyle);
            setValueDisplayStyle(stringToValueDisplayStyle(str));
        }
        else if (tag.tagName() == KXMLQLCVCSliderLevel)
        {
            loadXMLLevel(&tag);
        }
        else if (tag.tagName() == KXMLQLCVCWidgetInput)
        {
            loadXMLInput(&tag);
        }
        else if (tag.tagName() == KXMLQLCVCSliderPlayback)
        {
            loadXMLPlayback(&tag);
        }
        else
        {
            qWarning() << Q_FUNC_INFO << "Unknown slider tag:" << tag.tagName();
        }

        node = node.nextSibling();
    }

    /* Set the mode last, after everything else has been set */
    setSliderMode(sliderMode);
    setCaption(caption);

    return true;
}
Пример #9
0
/**
 * \fn UPNPScanner::ParseDescription(const QUrl&, QNetworkReply*)
 *  Parse the device description XML return my a media server.
 */
bool UPNPScanner::ParseDescription(const QUrl &url, QNetworkReply *reply)
{
    if (url.isEmpty() || !reply)
        return false;

    QByteArray data = reply->readAll();
    if (data.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("%1 returned an empty device description.")
            .arg(url.toString()));
        return false;
    }

    // parse the device description
    QString controlURL = QString();
    QString eventURL   = QString();
    QString friendlyName = QString("Unknown");
    QString URLBase = QString();

    QDomDocument doc;
    QString errorMessage;
    int errorLine   = 0;
    int errorColumn = 0;
    if (!doc.setContent(data, false, &errorMessage, &errorLine, &errorColumn))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Failed to parse device description from %1")
            .arg(url.toString()));
        LOG(VB_GENERAL, LOG_ERR, LOC + QString("Line: %1 Col: %2 Error: '%3'")
            .arg(errorLine).arg(errorColumn).arg(errorMessage));
        return false;
    }

    QDomElement docElem = doc.documentElement();
    QDomNode n = docElem.firstChild();
    while (!n.isNull())
    {
        QDomElement e1 = n.toElement();
        if (!e1.isNull())
        {
            if(e1.tagName() == "device")
                ParseDevice(e1, controlURL, eventURL, friendlyName);
            if (e1.tagName() == "URLBase")
                URLBase = e1.text();
        }
        n = n.nextSibling();
    }

    if (controlURL.isEmpty())
    {
        LOG(VB_UPNP, LOG_ERR, LOC +
            QString("Failed to parse device description for %1")
            .arg(url.toString()));
        return false;
    }

    // if no URLBase was provided, use the known url
    if (URLBase.isEmpty())
        URLBase = url.toString(QUrl::RemovePath | QUrl::RemoveFragment |
                               QUrl::RemoveQuery);

    // strip leading slashes off the controlURL
    while (!controlURL.isEmpty() && controlURL.left(1) == "/")
        controlURL = controlURL.mid(1);

    // strip leading slashes off the eventURL
    //while (!eventURL.isEmpty() && eventURL.left(1) == "/")
    //    eventURL = eventURL.mid(1);

    // strip trailing slashes off URLBase
    while (!URLBase.isEmpty() && URLBase.right(1) == "/")
        URLBase = URLBase.mid(0, URLBase.size() - 1);

    controlURL = URLBase + "/" + controlURL;
    QString fulleventURL = URLBase + "/" + eventURL;

    LOG(VB_UPNP, LOG_INFO, LOC + QString("Control URL for %1 at %2")
        .arg(friendlyName).arg(controlURL));
    LOG(VB_UPNP, LOG_INFO, LOC + QString("Event URL for %1 at %2")
        .arg(friendlyName).arg(fulleventURL));

    // update the server details. If the server has gone away since the request
    // was posted, this will silently fail and we won't try again
    QString usn;
    QUrl qeventurl = QUrl(fulleventURL);
    int timeout = 0;

    m_lock.lock();
    QHashIterator<QString,MediaServer*> it(m_servers);
    while (it.hasNext())
    {
        it.next();
        if (it.value()->m_URL == url)
        {
            usn = it.key();
            QUrl qcontrolurl(controlURL);
            it.value()->m_controlURL   = qcontrolurl;
            it.value()->m_eventSubURL  = qeventurl;
            it.value()->m_eventSubPath = eventURL;
            it.value()->m_friendlyName = friendlyName;
            it.value()->m_name         = friendlyName;
            break;
        }
    }

    if (m_subscription && !usn.isEmpty())
    {
        timeout = m_subscription->Subscribe(usn, qeventurl, eventURL);
        m_servers[usn]->m_subscribed = (timeout > 0);
    }
    m_lock.unlock();

    if (timeout > 0)
    {
        LOG(VB_GENERAL, LOG_INFO, LOC +
            QString("Subscribed for %1 seconds to %2") .arg(timeout).arg(usn));
        ScheduleRenewal(usn, timeout);
        // we only scan servers we are subscribed to - and the scan is now
        // incomplete
        m_scanComplete = false;
    }

    Debug();
    return true;
}
Пример #10
0
bool KigPlugin::readInfo( KFileMetaInfo& metainfo, uint /*what*/ )
{
  KFileMetaInfoGroup metagroup = appendGroup( metainfo, "KigInfo");

  QString sfile =  metainfo.path();
  bool iscompressed = false;
  QFile f( sfile );
  if ( !sfile.endsWith( ".kig", false ) )
  {
    iscompressed = true;

    QString tempdir = KGlobal::dirs()->saveLocation( "tmp" );
    if ( tempdir.isEmpty() )
      return false;

    QString tempname = sfile.section( '/', -1 );
    if ( sfile.endsWith( ".kigz", false ) )
    {
      tempname.remove( QRegExp( "\\.[Kk][Ii][Gg][Zz]$" ) );
    }
    else
      return false;
    // reading compressed file
    KTar* ark = new KTar( sfile, "application/x-gzip" );
    ark->open( IO_ReadOnly );
    const KArchiveDirectory* dir = ark->directory();
    QStringList entries = dir->entries();
    QStringList kigfiles = entries.grep( QRegExp( "\\.kig$" ) );
    if ( kigfiles.count() != 1 )
      return false;
    const KArchiveEntry* kigz = dir->entry( kigfiles[0] );
    if ( !kigz->isFile() )
      return false;
    dynamic_cast<const KArchiveFile*>( kigz )->copyTo( tempdir );

    f.setName( tempdir + kigz->name() );
  }

  if ( !f.open( IO_ReadOnly ) )
    return false;

  QDomDocument doc( "KigDocument" );
  if ( !doc.setContent( &f ) )
    return false;

  f.close();

  // removing temp file
  if ( iscompressed )
    f.remove();

  QDomElement main = doc.documentElement();

  // reading the version...
  QString version = main.attribute( "Version" );
  if ( version.isEmpty() ) version = main.attribute( "version" );
  if ( version.isEmpty() ) version = i18n( "Translators: Not Available", "n/a" );
  appendItem( metagroup, "Version", version );

  // reading the compatibility version...
  QString compatversion = main.attribute( "CompatibilityVersion" );
  if ( compatversion.isEmpty() )
    compatversion = i18n( "%1 represents Kig version",
                          "%1 (as the version)" ).arg( version );
  appendItem( metagroup, "CompatVersion", compatversion );

  // reading the Coordinate System...
  QCString coordsystem;
  for ( QDomNode n = main.firstChild(); ! n.isNull(); n = n.nextSibling() )
  {
    QDomElement e = n.toElement();
    if ( e.isNull() ) continue;
    if ( e.tagName() == "CoordinateSystem" )
      coordsystem = e.text().latin1();
  }
  appendItem( metagroup, "CoordSystem", coordsystem );

  // has Kig document the grid?
  bool btmp = true;
  QString stmp = main.attribute( "grid" );
  if ( !( stmp.isEmpty() || ( stmp != "0" ) ) )
    btmp = ( stmp != "0" );
  QString stmp2 = btmp ? i18n( "Yes" ) : i18n( "No" );
  appendItem( metagroup, "Grid", stmp2 );

  // has Kig document the axes?
  btmp = true;
  stmp = main.attribute( "axes" );
  if ( !( stmp.isEmpty() || ( stmp != "0" ) ) )
    btmp = ( stmp != "0" );
  stmp2 = btmp ? i18n( "Yes" ) : i18n( "No" );
  appendItem( metagroup, "Axes", stmp2 );

  stmp2 = iscompressed ? i18n( "Yes" ) : i18n( "No" );
  appendItem( metagroup, "Compressed", stmp2 );

  return true;
}
Пример #11
0
bool EFX::loadXML(const QDomElement& root)
{
    if (root.tagName() != KXMLQLCFunction)
    {
        qWarning() << "Function node not found!";
        return false;
    }

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

    /* Load EFX contents */
    QDomNode node = root.firstChild();
    while (node.isNull() == false)
    {
        QDomElement tag = node.toElement();

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

        node = node.nextSibling();
    }

    return true;
}
Пример #12
0
QList< Choqok::Post* > TwitterSearch::parseAtom(const QByteArray& buffer)
{
    kDebug();
    QDomDocument document;
    QList<Choqok::Post*> statusList;

    document.setContent( buffer );

    QDomElement root = document.documentElement();

    if ( root.tagName() != "feed" ) {
        kDebug() << "There is no feed element in Atom feed " << buffer.data();
        return statusList;
    }

    QDomNode node = root.firstChild();
    QString timeStr;
    while ( !node.isNull() ) {
        if ( node.toElement().tagName() != "entry" ) {
            node = node.nextSibling();
            continue;
        }

        QDomNode entryNode = node.firstChild();
        Choqok::Post *status = new Choqok::Post;
        status->isPrivate = false;

        while ( !entryNode.isNull() ) {
            QDomElement elm = entryNode.toElement();
            if ( elm.tagName() == "id" ) {
                // Fomatting example: "tag:search.twitter.com,2005:1235016836"
                ChoqokId id;
                if(m_rId.exactMatch(elm.text())) {
                    id = m_rId.cap(1);
                }
                /*                sscanf( qPrintable( elm.text() ),
                "tag:search.twitter.com,%*d:%d", &id);*/
                status->postId = id;
            } else if ( elm.tagName() == "published" ) {
                // Formatting example: "2009-02-21T19:42:39Z"
                // Need to extract date in similar fashion to dateFromString
                int year, month, day, hour, minute, second;
                sscanf( qPrintable( elm.text() ),
                        "%d-%d-%dT%d:%d:%d%*s", &year, &month, &day, &hour, &minute, &second);
                        QDateTime recognized( QDate( year, month, day), QTime( hour, minute, second ) );
                        recognized.setTimeSpec( Qt::UTC );
                        status->creationDateTime = recognized;
            } else if ( elm.tagName() == "title" ) {
                status->content = elm.text();
            } else if ( elm.tagName() == "twitter:source" ) {
                status->source = elm.text();
            } else if ( elm.tagName() == "link") {
                if(elm.attributeNode( "rel" ).value() == "image") {
                status->author.profileImageUrl = elm.attribute( "href" );
                } else if(elm.attributeNode( "rel" ).value() == "alternate") {
                    status->link = elm.attribute( "href" );
                }
            } else if ( elm.tagName() == "author") {
                QDomNode userNode = entryNode.firstChild();
                while ( !userNode.isNull() )
                {
                    if ( userNode.toElement().tagName() == "name" )
                    {
                        QString fullName = userNode.toElement().text();
                        int bracketPos = fullName.indexOf( " ", 0 );

                        QString screenName = fullName.left( bracketPos );
                        QString name = fullName.right ( fullName.size() - bracketPos - 2 );
                        name.chop( 1 );

                        status->author.realName = name;
                        status->author.userName = screenName;
                    }
                    userNode = userNode.nextSibling();
                }
            }
            entryNode = entryNode.nextSibling();
        }
        status->isFavorited = false;
        statusList.insert( 0, status );
        node = node.nextSibling();
    }

    return statusList;
}
Пример #13
0
void QgsSLDConfigParser::layersAndStylesCapabilities( QDomElement& parentElement, QDomDocument& doc, const QString& version, bool fullProjectSettings ) const
{
  Q_UNUSED( version );
  Q_UNUSED( fullProjectSettings );

  //iterate over all <UserLayer> nodes
  if ( mXMLDoc )
  {
    QDomNode sldNode = mXMLDoc->documentElement();
    if ( !sldNode.isNull() )
    {
      //create wgs84 to reproject the layer bounding boxes
      //QgsCoordinateReferenceSystem wgs84;
      //wgs84.createFromEpsg(4326);

      QDomNodeList layerNodeList = sldNode.toElement().elementsByTagName( "UserLayer" );
      for ( int i = 0; i < layerNodeList.size(); ++i )
      {
        QDomElement layerElement = doc.createElement( "Layer" );
        layerElement.setAttribute( "queryable", "1" ); //support GetFeatureInfo for all layers
        parentElement.appendChild( layerElement );

        //add name
        QDomNodeList nameList = layerNodeList.item( i ).toElement().elementsByTagName( "Name" );
        if ( !nameList.isEmpty() )
        {
          //layer name
          QDomElement layerNameElement = doc.createElement( "Name" );
          QDomText layerNameText = doc.createTextNode( nameList.item( 0 ).toElement().text() );
          layerNameElement.appendChild( layerNameText );
          layerElement.appendChild( layerNameElement );
        }

        //add title
        QDomNodeList titleList = layerNodeList.item( i ).toElement().elementsByTagName( "Title" );
        if ( !titleList.isEmpty() )
        {
          QDomElement layerTitleElement = doc.createElement( "Title" );
          QDomText layerTitleText = doc.createTextNode( titleList.item( 0 ).toElement().text() );
          layerTitleElement.appendChild( layerTitleText );
          layerElement.appendChild( layerTitleElement );
        }
        //add abstract
        QDomNodeList abstractList = layerNodeList.item( i ).toElement().elementsByTagName( "Abstract" );
        if ( !abstractList.isEmpty() )
        {
          QDomElement layerAbstractElement = doc.createElement( "Abstract" );
          QDomText layerAbstractText = doc.createTextNode( abstractList.item( 0 ).toElement().text() );
          layerAbstractElement.appendChild( layerAbstractText );
          layerElement.appendChild( layerAbstractElement );
        }


        //get QgsMapLayer object to add Ex_GeographicalBoundingBox, Bounding Box
        QList<QgsMapLayer*> layerList = mapLayerFromStyle( nameList.item( 0 ).toElement().text(), "" );
        if ( layerList.size() < 1 )//error while generating the layer
        {
          QgsDebugMsg( "Error, no maplayer in layer list" );
          continue;
        }

        //get only the first layer since we don't want to have the other ones in the capabilities document
        QgsMapLayer* theMapLayer = layerList.at( 0 );
        if ( !theMapLayer )//error while generating the layer
        {
          QgsDebugMsg( "Error, QgsMapLayer object is 0" );
          continue;
        }

        //append geographic bbox and the CRS elements
        QStringList crsNumbers = QgsConfigParserUtils::createCrsListForLayer( theMapLayer );
        QStringList crsRestriction; //no crs restrictions in SLD parser
        QgsConfigParserUtils::appendCrsElementsToLayer( layerElement, doc, crsNumbers, crsRestriction );
        QgsConfigParserUtils::appendLayerBoundingBoxes( layerElement, doc, theMapLayer->extent(), theMapLayer->crs(), crsNumbers, crsRestriction );

        //iterate over all <UserStyle> nodes within a user layer
        QDomNodeList userStyleList = layerNodeList.item( i ).toElement().elementsByTagName( "UserStyle" );
        for ( int j = 0; j < userStyleList.size(); ++j )
        {
          QDomElement styleElement = doc.createElement( "Style" );
          layerElement.appendChild( styleElement );
          //Name
          QDomNodeList nameList = userStyleList.item( j ).toElement().elementsByTagName( "Name" );
          if ( !nameList.isEmpty() )
          {
            QDomElement styleNameElement = doc.createElement( "Name" );
            QDomText styleNameText = doc.createTextNode( nameList.item( 0 ).toElement().text() );
            styleNameElement.appendChild( styleNameText );
            styleElement.appendChild( styleNameElement );

            QDomElement styleTitleElement = doc.createElement( "Title" );
            QDomText styleTitleText = doc.createTextNode( nameList.item( 0 ).toElement().text() );
            styleTitleElement.appendChild( styleTitleText );
            styleElement.appendChild( styleTitleElement );
          }
          //Title
          QDomNodeList titleList = userStyleList.item( j ).toElement().elementsByTagName( "Title" );
          if ( !titleList.isEmpty() )
          {
            QDomElement styleTitleElement = doc.createElement( "Title" );
            QDomText styleTitleText = doc.createTextNode( titleList.item( 0 ).toElement().text() );
            styleTitleElement.appendChild( styleTitleText );
            styleElement.appendChild( styleTitleElement );
          }
          //Abstract
          QDomNodeList abstractList = userStyleList.item( j ).toElement().elementsByTagName( "Abstract" );
          if ( !abstractList.isEmpty() )
          {
            QDomElement styleAbstractElement = doc.createElement( "Abstract" );
            QDomText styleAbstractText = doc.createTextNode( abstractList.item( 0 ).toElement().text() );
            styleAbstractElement.appendChild( styleAbstractText );
            styleElement.appendChild( styleAbstractElement );
          }
        }
      }
    }
  }
}
Пример #14
0
QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userLayerElem, const QString& layerName, bool allowCaching ) const
{
  QgsDebugMsg( "Entering." );
  QgsMSLayerBuilder* layerBuilder = nullptr;
  QDomElement builderRootElement;

  //hosted vector data?
  QDomNode hostedVDSNode = userLayerElem.namedItem( "HostedVDS" );
  if ( !hostedVDSNode.isNull() )
  {
    builderRootElement = hostedVDSNode.toElement();
    layerBuilder = new QgsHostedVDSBuilder();
  }

  //hosted raster data?
  QDomNode hostedRDSNode = userLayerElem.namedItem( "HostedRDS" );
  if ( !layerBuilder && !hostedRDSNode.isNull() )
  {
    builderRootElement = hostedRDSNode.toElement();
    layerBuilder = new QgsHostedRDSBuilder();
  }

  //remote OWS (WMS, WFS, WCS)?
  QDomNode remoteOWSNode = userLayerElem.namedItem( "RemoteOWS" );
  if ( !layerBuilder && !remoteOWSNode.isNull() )
  {
    builderRootElement = remoteOWSNode.toElement();
    layerBuilder = new QgsRemoteOWSBuilder( mParameterMap );
  }

  //remote vector/raster datasource
  QDomNode remoteRDSNode = userLayerElem.namedItem( "RemoteRDS" );
  if ( !layerBuilder && !remoteRDSNode.isNull() )
  {
    builderRootElement = remoteRDSNode.toElement();
    layerBuilder = new QgsRemoteDataSourceBuilder();
    QgsDebugMsg( "Detected remote raster datasource" );
  }

  QDomNode remoteVDSNode = userLayerElem.namedItem( "RemoteVDS" );
  if ( !layerBuilder && !remoteVDSNode.isNull() )
  {
    builderRootElement = remoteVDSNode.toElement();
    layerBuilder = new QgsRemoteDataSourceBuilder();
    QgsDebugMsg( "Detected remote vector datasource" );
  }

  //sent vector/raster datasource
  QDomNode sentVDSNode = userLayerElem.namedItem( "SentVDS" );
  if ( !layerBuilder && !sentVDSNode.isNull() )
  {
    builderRootElement = sentVDSNode.toElement();
    layerBuilder = new QgsSentDataSourceBuilder();
  }

  QDomNode sentRDSNode = userLayerElem.namedItem( "SentRDS" );
  if ( !layerBuilder && !sentRDSNode.isNull() )
  {
    builderRootElement = sentRDSNode.toElement();
    layerBuilder = new QgsSentDataSourceBuilder();
  }

  if ( !layerBuilder )
  {
    return nullptr;
  }

  QgsMapLayer* theMapLayer = layerBuilder->createMapLayer( builderRootElement, layerName, mFilesToRemove, mLayersToRemove, allowCaching );
  if ( theMapLayer )
  {
    setCrsForLayer( builderRootElement, theMapLayer ); //consider attributes "epsg" and "proj"
  }

  //maybe the datasource is defined in the fallback SLD?
  if ( !theMapLayer && mFallbackParser )
  {
    QList<QgsMapLayer*> fallbackList = mFallbackParser->mapLayerFromStyle( layerName, "", allowCaching );
    if ( !fallbackList.isEmpty() )
    {
      QgsMapLayer* fallbackLayer = fallbackList.at( 0 ); //todo: prevent crash if layer list is empty
      if ( fallbackLayer )
      {
        theMapLayer = dynamic_cast<QgsVectorLayer*>( fallbackLayer );
      }
    }
  }

#if 0 //todo: fixme
  //GML from outside the SLD?
  if ( !theMapLayer )
  {
    QMap<QString, QDomDocument*>::const_iterator gmlIt = mExternalGMLDatasets.find( layerName );

    if ( gmlIt != mExternalGMLDatasets.end() )
    {
      QgsDebugMsg( "Trying to get maplayer from external GML" );
      theMapLayer = vectorLayerFromGML( gmlIt.value()->documentElement() );
    }
  }
#endif //0

  //raster layer from interpolation

  QDomNode rasterInterpolationNode = userLayerElem.namedItem( "RasterInterpolation" );
  if ( !rasterInterpolationNode.isNull() )
  {
    QgsVectorLayer* vectorCast = dynamic_cast<QgsVectorLayer*>( theMapLayer );
    if ( vectorCast )
    {
      builderRootElement = rasterInterpolationNode.toElement();
      layerBuilder = new QgsInterpolationLayerBuilder( vectorCast );
      theMapLayer = layerBuilder->createMapLayer( builderRootElement, layerName, mFilesToRemove, mLayersToRemove, allowCaching );
    }
  }

  return theMapLayer;
}
Пример #15
0
void InstrumentTrack::loadTrackSpecificSettings( const QDomElement & thisElement )
{
	silenceAllNotes( true );

	lock();

	m_volumeModel.loadSettings( thisElement, "vol" );
	m_panningModel.loadSettings( thisElement, "pan" );
	m_pitchRangeModel.loadSettings( thisElement, "pitchrange" );
	m_pitchModel.loadSettings( thisElement, "pitch" );
	m_effectChannelModel.setRange( 0, Engine::fxMixer()->numChannels()-1 );
	m_effectChannelModel.loadSettings( thisElement, "fxch" );
	m_baseNoteModel.loadSettings( thisElement, "basenote" );
	m_useMasterPitchModel.loadSettings( thisElement, "usemasterpitch");

	// clear effect-chain just in case we load an old preset without FX-data
	m_audioPort.effects()->clear();

	QDomNode node = thisElement.firstChild();
	while( !node.isNull() )
	{
		if( node.isElement() )
		{
			if( m_soundShaping.nodeName() == node.nodeName() )
			{
				m_soundShaping.restoreState( node.toElement() );
			}
			else if( m_noteStacking.nodeName() == node.nodeName() )
			{
				m_noteStacking.restoreState( node.toElement() );
			}
			else if( m_arpeggio.nodeName() == node.nodeName() )
			{
				m_arpeggio.restoreState( node.toElement() );
			}
			else if( m_midiPort.nodeName() == node.nodeName() )
			{
				m_midiPort.restoreState( node.toElement() );
			}
			else if( m_audioPort.effects()->nodeName() == node.nodeName() )
			{
				m_audioPort.effects()->restoreState( node.toElement() );
			}
			else if( node.nodeName() == "instrument" )
			{
				delete m_instrument;
				m_instrument = NULL;
				m_instrument = Instrument::instantiate( node.toElement().attribute( "name" ), this );
				m_instrument->restoreState( node.firstChildElement() );

				emit instrumentChanged();
			}
			// compat code - if node-name doesn't match any known
			// one, we assume that it is an instrument-plugin
			// which we'll try to load
			else if( AutomationPattern::classNodeName() != node.nodeName() &&
					ControllerConnection::classNodeName() != node.nodeName() &&
					!node.toElement().hasAttribute( "id" ) )
			{
				delete m_instrument;
				m_instrument = NULL;
				m_instrument = Instrument::instantiate( node.nodeName(), this );
				if( m_instrument->nodeName() == node.nodeName() )
				{
					m_instrument->restoreState( node.toElement() );
				}
				emit instrumentChanged();
			}
		}
		node = node.nextSibling();
	}
	updatePitchRange();
	unlock();
}
Пример #16
0
/**
 * \fn UPNPScanner::ParseBrowse(const QUrl&, QNetworkReply*)
 *  Parse the XML returned from Content Directory Service browse request.
 */
void UPNPScanner::ParseBrowse(const QUrl &url, QNetworkReply *reply)
{
    QByteArray data = reply->readAll();
    if (data.isEmpty())
        return;

    // Open the response for parsing
    QDomDocument *parent = new QDomDocument();
    QString errorMessage;
    int errorLine   = 0;
    int errorColumn = 0;
    if (!parent->setContent(data, false, &errorMessage, &errorLine,
                            &errorColumn))
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("DIDL Parse error, Line: %1 Col: %2 Error: '%3'")
            .arg(errorLine).arg(errorColumn).arg(errorMessage));
        delete parent;
        return;
    }

    LOG(VB_UPNP, LOG_INFO, "\n\n" + parent->toString(4) + "\n\n");

    // pull out the actual result
    QDomDocument *result = NULL;
    uint num      = 0;
    uint total    = 0;
    uint updateid = 0;
    QDomElement docElem = parent->documentElement();
    QDomNode n = docElem.firstChild();
    if (!n.isNull())
        result = FindResult(n, num, total, updateid);
    delete parent;

    if (!result || num < 1 || total < 1)
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Failed to find result for %1") .arg(url.toString()));
        return;
    }

    // determine the 'server' which requested the browse
    m_lock.lock();

    MediaServer* server = NULL;
    QHashIterator<QString,MediaServer*> it(m_servers);
    while (it.hasNext())
    {
        it.next();
        if (url == it.value()->m_controlURL)
        {
            server = it.value();
            break;
        }
    }

    // discard unmatched responses
    if (!server)
    {
        m_lock.unlock();
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Received unknown response for %1").arg(url.toString()));
        return;
    }

    // check the update ID
    if (server->m_systemUpdateID != (int)updateid)
    {
        // if this is not the root container, this browse will now fail
        // as the appropriate parentID will not be found
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("%1 updateID changed during browse (old %2 new %3)")
            .arg(server->m_friendlyName).arg(server->m_systemUpdateID)
            .arg(updateid));
        m_scanComplete &= server->ResetContent(updateid);
        Debug();
    }

    // find containers (directories) and actual items and add them
    docElem = result->documentElement();
    n = docElem.firstChild();
    while (!n.isNull())
    {
        FindItems(n, *server);
        n = n.nextSibling();
    }
    delete result;

    m_lock.unlock();
}
Пример #17
0
/**
 *  \copydoc MythUIType::ParseElement()
 */
bool MythUIShape::ParseElement(
    const QString &filename, QDomElement &element, bool showWarnings)
{
    if (element.tagName() == "type")
    {
        QString type = getFirstText(element);

        if (type == "box" || type == "roundbox" || type == "ellipse") // Validate input
            m_type = type;
    }
    else if (element.tagName() == "fill")
    {
        QString style = element.attribute("style", "solid");
        QString color = element.attribute("color", "");
        int alpha = element.attribute("alpha", "255").toInt();

        if (style == "solid" && !color.isEmpty())
        {
            m_fillBrush.setStyle(Qt::SolidPattern);
            QColor brushColor = QColor(color);
            brushColor.setAlpha(alpha);
            m_fillBrush.setColor(brushColor);
        }
        else if (style == "gradient")
        {
            for (QDomNode child = element.firstChild(); !child.isNull();
                 child = child.nextSibling())
            {
                QDomElement childElem = child.toElement();

                if (childElem.tagName() == "gradient")
                    m_fillBrush = parseGradient(childElem);
            }
        }
        else
            m_fillBrush.setStyle(Qt::NoBrush);
    }
    else if (element.tagName() == "line")
    {
        QString style = element.attribute("style", "solid");
        QString color = element.attribute("color", "");

        if (style == "solid" && !color.isEmpty())
        {
            int orig_width = element.attribute("width", "1").toInt();
            int width = (orig_width) ? max(NormX(orig_width), 1) : 0;
            int alpha = element.attribute("alpha", "255").toInt();
            QColor lineColor = QColor(color);
            lineColor.setAlpha(alpha);
            m_linePen.setColor(lineColor);
            m_linePen.setWidth(width);
            m_linePen.setStyle(Qt::SolidLine);
        }
        else
            m_linePen.setStyle(Qt::NoPen);
    }
    else if (element.tagName() == "cornerradius")
    {
        m_cornerRadius = NormX(getFirstText(element).toInt());
    }
    else
    {
        return MythUIType::ParseElement(filename, element, showWarnings);
    }

    return true;
}
Пример #18
0
bool EFX::loadXML(const QDomElement* root)
{
	QString str;
	QDomNode node;
	QDomElement tag;

	Q_ASSERT(root != NULL);

	if (root->tagName() != KXMLQLCFunction)
	{
		qWarning() << "Function node not found!";
		return false;
	}

	if (root->attribute(KXMLQLCFunctionType) != typeToString(Function::EFX))
	{
		qWarning("Function is not an EFX!");
		return false;
	}

	/* Load EFX contents */
	node = root->firstChild();
	while (node.isNull() == false)
	{
		tag = node.toElement();

		if (tag.tagName() == KXMLQLCBus)
		{
			/* Bus */
			str = tag.attribute(KXMLQLCBusRole);
			setBus(tag.text().toUInt());
		}
		else if (tag.tagName() == KXMLQLCEFXFixture)
		{
			EFXFixture* ef = new EFXFixture(this);
			ef->loadXML(&tag);
			if (ef->fixture() != Fixture::invalidId())
			{
				if (addFixture(ef) == false)
					delete ef;
			}
		}
		else if (tag.tagName() == KXMLQLCEFXPropagationMode)
		{
			/* Propagation mode */
			setPropagationMode(stringToPropagationMode(tag.text()));
		}
		else if (tag.tagName() == KXMLQLCEFXAlgorithm)
		{
			/* Algorithm */
			setAlgorithm(tag.text());
		}
		else if (tag.tagName() == KXMLQLCFunctionDirection)
		{
			/* Direction */
			setDirection(Function::stringToDirection(tag.text()));
		}
		else if (tag.tagName() == KXMLQLCFunctionRunOrder)
		{
			/* Run Order */
			setRunOrder(Function::stringToRunOrder(tag.text()));
		}
		else if (tag.tagName() == KXMLQLCEFXWidth)
		{
			/* Width */
			setWidth(tag.text().toInt());
		}
		else if (tag.tagName() == KXMLQLCEFXHeight)
		{
			/* Height */
			setHeight(tag.text().toInt());
		}
		else if (tag.tagName() == KXMLQLCEFXRotation)
		{
			/* Rotation */
			setRotation(tag.text().toInt());
		}
		else if (tag.tagName() == KXMLQLCEFXStartScene)
		{
			/* Start scene */
			setStartScene(tag.text().toInt());

			if (tag.attribute(KXMLQLCFunctionEnabled) ==
			    KXMLQLCTrue)
				setStartSceneEnabled(true);
			else
				setStartSceneEnabled(false);
		}
		else if (tag.tagName() == KXMLQLCEFXStopScene)
		{
			/* Stop scene */
			setStopScene(tag.text().toInt());

			if (tag.attribute(KXMLQLCFunctionEnabled) ==
			    KXMLQLCTrue)
				setStopSceneEnabled(true);
			else
				setStopSceneEnabled(false);
		}
		else if (tag.tagName() == KXMLQLCEFXAxis)
		{
			/* Axes */
			loadXMLAxis(&tag);
		}
		else
		{
			qWarning() << "Unknown EFX tag:" << tag.tagName();
		}

		node = node.nextSibling();
	}

	return true;
}
Пример #19
0
// static
Skin SkinConfigWidget::loadSkin(KLFPluginConfigAccess * config, const QString& fn, bool getstylesheet)
{
  Q_UNUSED(getstylesheet) ;
  KLF_DEBUG_BLOCK(KLF_FUNC_NAME) ;
  klfDbg("loading skin "<<fn<<", get style sheet="<<getstylesheet) ;

  Skin skin;

  skin.fn = fn;

  QFile f(fn);
  if ( ! f.open(QIODevice::ReadOnly) ) {
    qWarning()<<KLF_FUNC_NAME<<": Can't read skin "<<fn<<"!";
    return skin;
  }

  QDomDocument doc("klf-skin");
  QString errMsg; int errLine, errCol;
  bool r = doc.setContent(&f, false, &errMsg, &errLine, &errCol);
  if (!r) {
    qWarning()<<KLF_FUNC_NAME<<": Error parsing file "<<fn<<": "<<errMsg<<" at line "<<errLine<<", col "<<errCol;
    return skin;
  }
  f.close();

  QDomElement root = doc.documentElement();
  if (root.nodeName() != "klf-skin") {
    qWarning("%s: Error parsing XML for skin `%s': Bad root node `%s'.\n",
	     KLF_FUNC_NAME, qPrintable(fn), qPrintable(root.nodeName()));
    return skin;
  }

  QMap<QString,QString> defines;

  QStringList stylesheetpath = QStringList()
    << QLatin1String(":/plugindata/skin/stylesheets")
    << config->homeConfigPluginDataDir() + "/stylesheets";

  // read XML file
  QDomNode n;
  for (n = root.firstChild(); ! n.isNull(); n = n.nextSibling()) {
    QDomElement e = n.toElement(); // try to convert the node to an element.
    if ( e.isNull() || n.nodeType() != QDomNode::ElementNode )
      continue;
    if ( e.nodeName() == "name" ) {
      skin.name = qApp->translate("xmltr_pluginskins", e.text().toUtf8().constData(),
				  "[[tag: <name>]]", QCoreApplication::UnicodeUTF8);
      continue;
    } else if ( e.nodeName() == "author" ) {
      skin.author = e.text();
      continue;
    } else if ( e.nodeName() == "def" ) {
      QString key = e.attribute("name");
      QString value = e.text();
      if (QRegExp("^[A-Za-z][A-Za-z0-9_]*$").exactMatch(key))
	defines[key] = value;
      else
	qWarning()<<KLF_FUNC_NAME<<": file "<<fn<<": Illegal <def> name: "<<key;
    } else if ( e.nodeName() == "description" ) {
      skin.description = qApp->translate("xmltr_pluginskins", e.text().toUtf8().constData(),
				  "[[tag: <description>]]", QCoreApplication::UnicodeUTF8);
      continue;
    } else if ( e.nodeName() == "stylesheet" ) {
      QString fnqssbase = e.text().trimmed();
      QString fnqss = klfSearchPath(fnqssbase, stylesheetpath);
      QFile fqss(fnqss);
      if (fnqss.isEmpty() || !fqss.exists() || !fqss.open(QIODevice::ReadOnly)) {
	qWarning()<<KLF_FUNC_NAME<<"Can't open qss-stylesheet file "<<fnqssbase
		  <<" while reading skin "<<fn<<".";
	continue;
      }
      QString ss = QString::fromUtf8(fqss.readAll());
      if (!defines.isEmpty()) {
	// we need to process <def>ines ...
	QRegExp alldefines_rx = QRegExp("\\b("+QStringList(defines.keys()).join("|")+")\\b");
	int k = 0;
	while ( (k = alldefines_rx.indexIn(ss, k+1)) != -1) {
	  QString key = alldefines_rx.cap(1);
	  KLF_ASSERT_CONDITION( defines.contains(key), "Error: key "<<key<<" found, but not in defines="
				<<defines<<"?!?",   ++k; continue; ) ;
	  QString value = defines[key];
	  klfDbg("Substituting def. "<<key<<" by "<<value<<" in style sheet "<<fnqss<<" for "<<fn) ;
	  ss.replace(k, alldefines_rx.matchedLength(), value);
	  k += value.length();
	}
	klfDbg("def-Replaced style sheet is \n"<<ss) ;
      }
Пример #20
0
bool EFX::loadXMLAxis(const QDomElement* root)
{
	int frequency = 0;
	int offset = 0;
	int phase = 0;
	QString axis;

	QDomNode node;
	QDomElement tag;

	Q_ASSERT(root != NULL);

	if (root->tagName() != KXMLQLCEFXAxis)
	{
		qWarning() << "EFX axis node not found!";
		return false;
	}

	/* Get the axis name */
	axis = root->attribute(KXMLQLCFunctionName);

	/* Load axis contents */
	node = root->firstChild();
	while (node.isNull() == false)
	{
		tag = node.toElement();

		if (tag.tagName() == KXMLQLCEFXOffset)
		{
			offset = tag.text().toInt();
		}
		else if (tag.tagName() == KXMLQLCEFXFrequency)
		{
			frequency = tag.text().toInt();
		}
		else if (tag.tagName() == KXMLQLCEFXPhase)
		{
			phase = tag.text().toInt();
		}
		else
		{
			qWarning() << "Unknown EFX axis tag: "
				   << tag.tagName();
		}

		node = node.nextSibling();
	}

	if (axis == KXMLQLCEFXY)
	{
		setYOffset(offset);
		setYFrequency(frequency);
		setYPhase(phase);

		return true;
	}
	else if (axis == KXMLQLCEFXX)
	{
		setXOffset(offset);
		setXFrequency(frequency);
		setXPhase(phase);

		return true;
	}
	else
	{
		qWarning() << "Unknown EFX axis:" << axis;

		return false;
	}
}
Пример #21
0
void WPushButton::setup(QDomNode node, const SkinContext& context) {
    // Number of states
    int iNumStates = context.selectInt(node, "NumberStates");
    setStates(iNumStates);

    // Set background pixmap if available
    if (context.hasNode(node, "BackPath")) {
        QString mode_str = context.selectAttributeString(
                context.selectElement(node, "BackPath"), "scalemode", "TILE");
        setPixmapBackground(context.getSkinPath(context.selectString(node, "BackPath")),
                            Paintable::DrawModeFromString(mode_str));
    }

    // Load pixmaps for associated states
    QDomNode state = context.selectNode(node, "State");
    while (!state.isNull()) {
        if (state.isElement() && state.nodeName() == "State") {
            int iState = context.selectInt(state, "Number");
            if (iState < m_iNoStates) {
                if (context.hasNode(state, "Pressed")) {
                    setPixmap(iState, true,
                              context.getSkinPath(context.selectString(state, "Pressed")));
                }
                if (context.hasNode(state, "Unpressed")) {
                    setPixmap(iState, false,
                              context.getSkinPath(context.selectString(state, "Unpressed")));
                }
                m_text.replace(iState, context.selectString(state, "Text"));
            }
        }
        state = state.nextSibling();
    }

    ControlParameterWidgetConnection* leftConnection = NULL;
    if (m_leftConnections.isEmpty()) {
        if (!m_connections.isEmpty()) {
            // If no left connection is set, the this is the left connection
            leftConnection = m_connections.at(0);
        }
    } else {
        leftConnection = m_leftConnections.at(0);
    }

    if (leftConnection) {
        bool leftClickForcePush = context.selectBool(node, "LeftClickIsPushButton", false);
        m_leftButtonMode = ControlPushButton::PUSH;
        if (!leftClickForcePush) {
            const ConfigKey& configKey = leftConnection->getKey();
            ControlPushButton* p = dynamic_cast<ControlPushButton*>(
                    ControlObject::getControl(configKey));
            if (p) {
                m_leftButtonMode = p->getButtonMode();
            }
        }
        if (leftConnection->getEmitOption() &
                ControlParameterWidgetConnection::EMIT_DEFAULT) {
            switch (m_leftButtonMode) {
                case ControlPushButton::PUSH:
                case ControlPushButton::LONGPRESSLATCHING:
                case ControlPushButton::POWERWINDOW:
                    leftConnection->setEmitOption(
                            ControlParameterWidgetConnection::EMIT_ON_PRESS_AND_RELEASE);
                    break;
                default:
                    leftConnection->setEmitOption(
                            ControlParameterWidgetConnection::EMIT_ON_PRESS);
                    break;
            }
        }
        if (leftConnection->getDirectionOption() &
                        ControlParameterWidgetConnection::DIR_DEFAULT) {
            if (m_pDisplayConnection == leftConnection) {
                leftConnection->setDirectionOption(ControlParameterWidgetConnection::DIR_FROM_AND_TO_WIDGET);
            } else {
                leftConnection->setDirectionOption(ControlParameterWidgetConnection::DIR_FROM_WIDGET);
                if (m_pDisplayConnection->getDirectionOption() &
                        ControlParameterWidgetConnection::DIR_DEFAULT) {
                    m_pDisplayConnection->setDirectionOption(ControlParameterWidgetConnection::DIR_TO_WIDGET);
                }
            }
        }
    }

    if (!m_rightConnections.isEmpty()) {
        ControlParameterWidgetConnection* rightConnection = m_rightConnections.at(0);
        bool rightClickForcePush = context.selectBool(node, "RightClickIsPushButton", false);
        m_rightButtonMode = ControlPushButton::PUSH;
        if (!rightClickForcePush) {
            const ConfigKey configKey = rightConnection->getKey();
            ControlPushButton* p = dynamic_cast<ControlPushButton*>(
                    ControlObject::getControl(configKey));
            if (p) {
                m_rightButtonMode = p->getButtonMode();
                if (m_rightButtonMode != ControlPushButton::PUSH) {
                    qWarning()
                            << "WPushButton::setup: Connecting a Pushbutton not in PUSH mode is not implemented\n"
                            << "Please set <RightClickIsPushButton>true</RightClickIsPushButton>";
                }
            }
        }
        if (rightConnection->getEmitOption() &
                ControlParameterWidgetConnection::EMIT_DEFAULT) {
            switch (m_rightButtonMode) {
                case ControlPushButton::PUSH:
                case ControlPushButton::LONGPRESSLATCHING:
                case ControlPushButton::POWERWINDOW:
                    leftConnection->setEmitOption(
                            ControlParameterWidgetConnection::EMIT_ON_PRESS_AND_RELEASE);
                    break;
                default:
                    leftConnection->setEmitOption(
                            ControlParameterWidgetConnection::EMIT_ON_PRESS);
                    break;
            }
        }
        if (rightConnection->getDirectionOption() &
                        ControlParameterWidgetConnection::DIR_DEFAULT) {
            rightConnection->setDirectionOption(ControlParameterWidgetConnection::DIR_FROM_WIDGET);
        }
    }
}
Пример #22
0
bool MyMoneyStatement::read(const QDomElement& _e)
{
  bool result = false;

  if (_e.tagName() == "STATEMENT") {
    result = true;

    m_strAccountName = _e.attribute("accountname");
    m_strAccountNumber = _e.attribute("accountnumber");
    m_strRoutingNumber = _e.attribute("routingnumber");
    m_strCurrency = _e.attribute("currency");
    m_dateBegin = QDate::fromString(_e.attribute("begindate"), Qt::ISODate);
    m_dateEnd = QDate::fromString(_e.attribute("enddate"), Qt::ISODate);
    m_closingBalance = MyMoneyMoney(_e.attribute("closingbalance"));
    m_accountId = _e.attribute("accountid");
    m_skipCategoryMatching = _e.attribute("skipCategoryMatching").isEmpty();

    int i = kAccountTypeTxt.indexOf(_e.attribute("type", kAccountTypeTxt[1]));
    if (i != -1)
      m_eType = static_cast<EType>(i);

    QDomNode child = _e.firstChild();
    while (!child.isNull() && child.isElement()) {
      QDomElement c = child.toElement();

      if (c.tagName() == "TRANSACTION") {
        MyMoneyStatement::Transaction t;

        t.m_datePosted = QDate::fromString(c.attribute("dateposted"), Qt::ISODate);
        t.m_amount = MyMoneyMoney(c.attribute("amount"));
        t.m_strMemo = c.attribute("memo");
        t.m_strNumber = c.attribute("number");
        t.m_strPayee = c.attribute("payee");
        t.m_strBankID = c.attribute("bankid");
        t.m_reconcile = static_cast<MyMoneySplit::reconcileFlagE>(c.attribute("reconcile").toInt());
        int i = kActionText.indexOf(c.attribute("action", kActionText[1]));
        if (i != -1)
          t.m_eAction = static_cast<Transaction::EAction>(i);

        if (m_eType == etInvestment) {
          t.m_shares = MyMoneyMoney(c.attribute("shares"));
          t.m_strSecurity = c.attribute("security");
          t.m_strBrokerageAccount = c.attribute("brokerageaccount");
        }

        // process splits (if any)
        QDomNode child = c.firstChild();
        while (!child.isNull() && child.isElement()) {
          QDomElement c = child.toElement();
          if (c.tagName() == "SPLIT") {
            MyMoneyStatement::Split s;
            s.m_accountId = c.attribute("accountid");
            s.m_amount = MyMoneyMoney(c.attribute("amount"));
            s.m_reconcile = static_cast<MyMoneySplit::reconcileFlagE>(c.attribute("reconcile").toInt());
            s.m_strCategoryName = c.attribute("category");
            s.m_strMemo = c.attribute("memo");
            t.m_listSplits += s;
          }
          child = child.nextSibling();
        }
        m_listTransactions += t;
      } else if (c.tagName() == "PRICE") {
        MyMoneyStatement::Price p;

        p.m_date = QDate::fromString(c.attribute("dateposted"), Qt::ISODate);
        p.m_strSecurity = c.attribute("security");
        p.m_amount = MyMoneyMoney(c.attribute("amount"));

        m_listPrices += p;
      } else if (c.tagName() == "SECURITY") {
        MyMoneyStatement::Security s;

        s.m_strName = c.attribute("name");
        s.m_strSymbol = c.attribute("symbol");
        s.m_strId = c.attribute("id");

        m_listSecurities += s;
      }
      child = child.nextSibling();
    }
  }

  return result;
}
Пример #23
0
//update model with test case name & result
void xmlVerifyWidget::updateDialogResults()
{
    QDomNode tempNodeChild;
    QDomNode firstNodeOfTheXml;
    QStandardItem *item;
    QDomNode firstChild;
    QDomNodeList listChild;
    QString nodeDataTextRoom;
    QString nodeDataTextFloor;
    QString nodeDataTextHouse;
    QString nodeDataDeviceType;
    QString nodeDataDeviceSubType;
    QString nodeTagname;
    bool statusFail;

    // root have Test Case nodes
    if(list.count() != 0)
    {
        for(int i =0; i< list.count() ; i++)
        {
            statusFail = FALSE;

            tempNodeChild = list.at(i);
            if(i == 0)
            {
                firstNodeOfTheXml = tempNodeChild;
            }
            // Create list of child nodes of - test case
            listChild = tempNodeChild.childNodes();

            //Read room name from node
            tempNodeChild = listChild.at(ROOM_NAME_NUMBER);
            if (!tempNodeChild.isNull()){
                nodeDataTextRoom = tempNodeChild.toElement().text();
                //Check if node is empty
                if(nodeDataTextRoom == ""){
                    statusFail = TRUE;
                }

            }
            else{
                nodeDataTextRoom = "";
                statusFail = TRUE;
            }

            //Read floor name from node
            tempNodeChild = listChild.at(FLOOR_NAME_NUMBER);
            if (!tempNodeChild.isNull()){
                nodeDataTextFloor = tempNodeChild.toElement().text();
                //Check if node is empty
                if(nodeDataTextFloor == ""){
                    statusFail = TRUE;
                }

            }
            else{
                nodeDataTextFloor = "";
                statusFail = TRUE;
            }

            //Read house name from node
            tempNodeChild = listChild.at(HOUSE_NAME_NUMBER);
            if (!tempNodeChild.isNull()){
                nodeDataTextHouse = tempNodeChild.toElement().text();
                //Check if node is empty
                if(nodeDataTextHouse == ""){
                    statusFail = TRUE;
                }

            }
            else{
                nodeDataTextHouse = "";
                statusFail = TRUE;
            }
            //Itterate test steps of the - test case node
            for(int device = DEVICE_NODE_NUMBER; device<listChild.count(); device++)
            {
                //Read test Description from node
                tempNodeChild = listChild.at(device);
                if (!tempNodeChild.isNull()){

                    //Read first child of the node
                    firstChild = tempNodeChild.firstChild();
                    if(!firstChild.isNull()){
                        for(int column =0; column < MODEL_INITIAL_COLUMNS; column++ ){

                            if(column != DEVICE_DESCRIPTION_DEVICE_PACKET_COLUMN)
                            {
                                if(firstChild.toElement().text() == ""){
                                    statusFail = TRUE;
                                }
                            }
                            else
                            {
                                if(firstChild.isNull())
                                {
                                    statusFail = TRUE;
                                    //QMessageBox::information(this, "Packet Node", "Packet Node is NULL");
                                }
                                else
                                {
                                    //Do nothing
                                }

                                nodeTagname = firstChild.toElement().tagName();
                                if((nodeTagname!=PACKET_SWITCH_TEXT)&&(nodeTagname!=PACKET_SENSOR_TEXT))
                                {
                                    statusFail = TRUE;
                                    //QMessageBox::information(this, "Packet Node", "Packet Node Tagname Incorrect" + nodeTagname);
                                }
                                else
                                {
                                    //Do nothing
                                }

                            }

                            if(column == DEVICE_TYPE_COLUMN)
                            {
                                nodeDataDeviceType = firstChild.toElement().text();
                            }
                            else if(column == DEVICE_SUB_TYPE_COLUMN)
                            {
                                nodeDataDeviceSubType = firstChild.toElement().text();
                            }
                            else
                            {
                                /* Do nothing*/
                            }
                            // Get the next child
                            firstChild = firstChild.nextSibling();
                        }


                        // Check if the device is switch type
                        if(nodeDataDeviceType == DEVICE_SWITCH)
                        {
                            if((nodeDataDeviceSubType == SWITCH_SUB_TYPE_ONE) || (nodeDataDeviceSubType == SWITCH_SUB_TYPE_TWO))
                            {
                                //Do nothing
                            }
                            else
                            {
                                statusFail = TRUE;
                            }

                        }
                        else if(nodeDataDeviceType == DEVICE_SENSOR) // check if device is sensor type
                        {
                            if(nodeDataDeviceSubType == SENSOR_SUB_TYPE_DEFAULT)
                            {
                                /*QMessageBox *msgBox 	= new QMessageBox();
                                                msgBox->setText(SENSOR_SUB_TYPE_DEFAULT);
                                                msgBox->setWindowFlags(Qt::WindowStaysOnTopHint);
                                                msgBox->exec();*/
                                //Do nothing
                            }
                            else
                            {
                                statusFail = TRUE;
                            }

                        }
                        else
                        {
                            statusFail = TRUE;
                        }
                        nodeDataDeviceType = "";
                        nodeDataDeviceSubType = "";
                    }
                }
                else{
                    // Do nothing
                }
            }


            //Append to model
            if(statusFail == TRUE){
                item = new QStandardItem(TEST_CASE_FAIL);
            }else{
                item = new QStandardItem(TEST_CASE_PASS);
            }
            VerifyModel->setItem(i, TEST_CASE_RESULT_COLUMN, item);

            //Append to model
            item = new QStandardItem(nodeDataTextRoom);
            VerifyModel->setItem(i, 1, item);            
            //Append to model
            item = new QStandardItem(nodeDataTextFloor);
            VerifyModel->setItem(i, 2, item);
            //Append to model
            item = new QStandardItem(nodeDataTextHouse);
            VerifyModel->setItem(i, 3, item);

            if(statusFail == TRUE){
                VerifyModel->setData(VerifyModel->index(i, 0), Qt::red, Qt::BackgroundRole);
                VerifyModel->setData(VerifyModel->index(i, 1), Qt::red, Qt::BackgroundRole);
                VerifyModel->setData(VerifyModel->index(i, 2), Qt::red, Qt::BackgroundRole);
                VerifyModel->setData(VerifyModel->index(i, 3), Qt::red, Qt::BackgroundRole);
            }else{
                //Do nothing
            }

        }
    }
}
// Slot called by the menu manager on user action
void UAVSettingsImportExportFactory::importUAVSettings()
{
    // ask for file name
    QString fileName;
    QString filters = tr("UAVObjects XML files (*.uav);; XML files (*.xml)");
    fileName = QFileDialog::getOpenFileName(0, tr("Import UAV Settings"), "", filters);
    if (fileName.isEmpty()) {
        return;
    }

    // Now open the file
    QFile file(fileName);
    QDomDocument doc("UAVObjects");
    file.open(QFile::ReadOnly|QFile::Text);
    if (!doc.setContent(file.readAll())) {
        QMessageBox msgBox;
        msgBox.setText(tr("File Parsing Failed."));
        msgBox.setInformativeText(tr("This file is not a correct XML file"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.exec();
        return;
    }
    file.close();

    // find the root of settings subtree
    emit importAboutToBegin();
    qDebug()<<"Import about to begin";

    QDomElement root = doc.documentElement();
    if (root.tagName() == "uavobjects") {
        root = root.firstChildElement("settings");
    }
    if (root.isNull() || (root.tagName() != "settings")) {
        QMessageBox msgBox;
        msgBox.setText(tr("Wrong file contents"));
        msgBox.setInformativeText(tr("This file does not contain correct UAVSettings"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.exec();
        return;
    }

    // We are now ok: setup the import summary dialog & update it as we
    // go along.
    ImportSummaryDialog swui((QWidget*)Core::ICore::instance()->mainWindow());

    ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
    UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
    swui.show();

    QDomNode node = root.firstChild();
    while (!node.isNull()) {
        QDomElement e = node.toElement();
        if (e.tagName() == "object") {

            //  - Read each object
            QString uavObjectName  = e.attribute("name");
            uint uavObjectID = e.attribute("id").toUInt(NULL,16);

            // Sanity Check:
            UAVObject *obj = objManager->getObject(uavObjectName);
            UAVDataObject *dobj = dynamic_cast<UAVDataObject*>(obj);
            if (obj == NULL) {
                // This object is unknown!
                qDebug() << "Object unknown:" << uavObjectName << uavObjectID;
                swui.addLine(uavObjectName, "Error (Object unknown)", false);
            } else if(dobj && !dobj->getIsPresentOnHardware()) {
                swui.addLine(uavObjectName, "Error (Object not present on hw)", false);
            } else {
                //  - Update each field
                //  - Issue and "updated" command
                bool error = false;
                bool setError = false;
                QDomNode field = node.firstChild();
                while(!field.isNull()) {
                    QDomElement f = field.toElement();
                    if (f.tagName() == "field") {
                        UAVObjectField *uavfield = obj->getField(f.attribute("name"));
                        if (uavfield) {
                            QStringList list = f.attribute("values").split(",");
                            if (list.length() == 1) {
                                if (false == uavfield->checkValue(f.attribute("values"))) {
                                    qDebug() << "checkValue returned false on: " << uavObjectName << f.attribute("values");
                                    setError = true;
                                } else {
                                    uavfield->setValue(f.attribute("values"));
                                }
                            } else {
                                // This is an enum:
                                int i = 0;
                                QStringList list = f.attribute("values").split(",");
                                foreach (QString element, list) {
                                    if (false == uavfield->checkValue(element, i)) {
                                        qDebug() << "checkValue(list) returned false on: " << uavObjectName << list;
                                        setError = true;
                                    } else {
                            		 uavfield->setValue(element,i);
                                    }
                                    i++;
                                }
                            }
                        } else {
                            error = true;
                        }
                    }
                    field = field.nextSibling();
                }
                obj->updated();

                if (error) {
                    swui.addLine(uavObjectName, "Warning (Object field unknown)", true);
                } else if (uavObjectID != obj->getObjID()) {
                    qDebug() << "Mismatch for Object " << uavObjectName << uavObjectID << " - " << obj->getObjID();
                    swui.addLine(uavObjectName, "Warning (ObjectID mismatch)", true);
                } else if (setError) {
                    swui.addLine(uavObjectName, "Warning (Objects field value(s) invalid)", false);
                } else {
                    swui.addLine(uavObjectName, "OK", true);
                }
            }
Пример #25
0
// load given song
void song::loadProject( const QString & _file_name )
{
	QDomNode node;

	m_loadingProject = true;

	clearProject();

	engine::projectJournal()->setJournalling( false );

	m_fileName = _file_name;
	m_oldFileName = _file_name;

	DataFile dataFile( m_fileName );
	// if file could not be opened, head-node is null and we create
	// new project
	if( dataFile.head().isNull() )
	{
		createNewProject();
		return;
	}

	engine::mixer()->lock();

	// get the header information from the DOM
	m_tempoModel.loadSettings( dataFile.head(), "bpm" );
	m_timeSigModel.loadSettings( dataFile.head(), "timesig" );
	m_masterVolumeModel.loadSettings( dataFile.head(), "mastervol" );
	m_masterPitchModel.loadSettings( dataFile.head(), "masterpitch" );

	if( m_playPos[Mode_PlaySong].m_timeLine )
	{
		// reset loop-point-state
		m_playPos[Mode_PlaySong].m_timeLine->toggleLoopPoints( 0 );
	}

	if( !dataFile.content().firstChildElement( "track" ).isNull() )
	{
		m_globalAutomationTrack->restoreState( dataFile.content().
						firstChildElement( "track" ) );
	}

	//Backward compatibility for LMMS <= 0.4.15
	PeakController::initGetControllerBySetting();

	// Load mixer first to be able to set the correct range for FX channels
	node = dataFile.content().firstChildElement( engine::fxMixer()->nodeName() );
	if( !node.isNull() )
	{
		engine::fxMixer()->restoreState( node.toElement() );
		if( engine::hasGUI() )
		{
			// refresh FxMixerView
			engine::fxMixerView()->refreshDisplay();
		}
	}

	node = dataFile.content().firstChild();
	while( !node.isNull() )
	{
		if( node.isElement() )
		{
			if( node.nodeName() == "trackcontainer" )
			{
				( (JournallingObject *)( this ) )->restoreState( node.toElement() );
			}
			else if( node.nodeName() == "controllers" )
			{
				restoreControllerStates( node.toElement() );
			}
			else if( engine::hasGUI() )
			{
				if( node.nodeName() == engine::getControllerRackView()->nodeName() )
				{
					engine::getControllerRackView()->restoreState( node.toElement() );
				}
				else if( node.nodeName() == engine::pianoRoll()->nodeName() )
				{
					engine::pianoRoll()->restoreState( node.toElement() );
				}
				else if( node.nodeName() == engine::automationEditor()->nodeName() )
				{
					engine::automationEditor()->restoreState( node.toElement() );
				}
				else if( node.nodeName() == engine::getProjectNotes()->nodeName() )
				{
					 engine::getProjectNotes()->SerializingObject::restoreState( node.toElement() );
				}
				else if( node.nodeName() == m_playPos[Mode_PlaySong].m_timeLine->nodeName() )
				{
					m_playPos[Mode_PlaySong].m_timeLine->restoreState( node.toElement() );
				}
			}
		}
		node = node.nextSibling();
	}

	// quirk for fixing projects with broken positions of TCOs inside
	// BB-tracks
	engine::getBBTrackContainer()->fixIncorrectPositions();

	// Connect controller links to their controllers 
	// now that everything is loaded
	ControllerConnection::finalizeConnections();

	// resolve all IDs so that autoModels are automated
	AutomationPattern::resolveAllIDs();


	engine::mixer()->unlock();

	configManager::inst()->addRecentlyOpenedProject( _file_name );

	engine::projectJournal()->setJournalling( true );

	emit projectLoaded();

	m_loadingProject = false;
	m_modified = false;

	if( engine::mainWindow() )
	{
		engine::mainWindow()->resetWindowTitle();
	}
}
Пример #26
0
int YourPayProcessor::handleResponse(const QString &presponse, const int pccardid, const QString &ptype, const double pamount, const int pcurrid, QString &pneworder, QString &preforder, int &pccpayid, ParameterList &pparams)
{
  if (DEBUG)
    qDebug("YP::handleResponse(%s, %d, %s, %f, %d, %s, %d, pparams)",
	   presponse.toAscii().data(), pccardid,
	   ptype.toAscii().data(), pamount, pcurrid,
	   preforder.toAscii().data(), pccpayid);

  QDomDocument response;
  // YP doesn't even send back a valid XML doc!
  response.setContent("<yp_wrapper>" + presponse + "</yp_wrapper>");

  QDomNode node;
  QDomElement root = response.documentElement();

  QString r_approved;
  QString r_avs;
  QString r_code;
  QString r_error;
  QString r_message;
  QString r_ordernum;
  QString r_ref;
  QString r_score;
  QString r_shipping;
  QString r_tax;
  QString r_tdate;
  QString r_time;

  QString status;

  node = root.firstChild();
  while ( !node.isNull() )
  {
    if (node.isElement())
    {
      if (node.nodeName() == "r_approved" )
	r_approved = node.toElement().text();

      else if (node.nodeName() == "r_avs" )
	r_avs = node.toElement().text();

      else if (node.nodeName() == "r_code" )
	r_code = node.toElement().text();

      else if (node.nodeName() == "r_error" )
	r_error = node.toElement().text();

      else if (node.nodeName() == "r_message" )
	r_message = node.toElement().text();

      else if (node.nodeName() == "r_ordernum" )
	r_ordernum = node.toElement().text();

      else if (node.nodeName() == "r_ref" )
	r_ref = node.toElement().text();

      else if (node.nodeName() == "r_score" )
	r_score = node.toElement().text();

      else if (node.nodeName() == "r_shipping" )
	r_shipping = node.toElement().text();

      else if (node.nodeName() == "r_tax" )
	r_tax = node.toElement().text();

      else if (node.nodeName() == "r_tdate" )
	r_tdate = node.toElement().text();

      else if (node.nodeName() == "r_time" )
	r_time = node.toElement().text();
    }

    node = node.nextSibling();
  }

  if (isTest())
  {
    // in test mode YP doesn't send an approval code
    if (r_approved == "APPROVED" && r_code.isEmpty())
    r_code = "12345";

    // inject failures to test AVS and CVV checking but ONLY IN TEST MODE
    if (r_avs.isEmpty() && _metrics->value("CCTestResult") == "S")
    {
      switch (qrand() % 50)
      {
	case 0: r_avs = "NN";
		break;
	case 1: r_avs = "XN";
		break;
	case 2: r_avs = "YN";
		break;
	case 3: r_avs = "NX";
		break;
	case 4: r_avs = "XX";
		break;
	case 5: r_avs = "YX";
		break;
	default:
		r_avs = "YY";
		break;
      }
      switch (qrand() % 50)
      {
	case 0: r_avs += "N";
		break;
	case 1: r_avs += "P";
		break;
	case 2: r_avs += "S";
		break;
	case 3: r_avs += "U";
		break;
	default:
		r_avs += "M";
		break;
      }
    }
  }

  int returnValue = 0;
  if (r_approved == "APPROVED")
  {
    _errorMsg = errorMsg(0).arg(r_ref);
    if (ptype == "A")
      status = "A";	// Authorized
    else if (ptype == "V")
      status = "V";	// Voided
    else
      status = "C";	// Completed/Charged
  }

  else if (r_approved == "DENIED")
  {
    _errorMsg = errorMsg(-90).arg(r_message);
    returnValue = -90;
    status = "D";
  }

  else if (r_approved == "DUPLICATE")
  {
    _errorMsg = errorMsg(-91).arg(r_message);
    returnValue = -91;
    status = "D";
  }

  else if (r_approved == "DECLINED")
  {
    _errorMsg = errorMsg(-92).arg(r_error);
    returnValue = -92;
    status = "D";
  }

  else if (r_approved == "FRAUD")
  {
    _errorMsg = errorMsg(-93).arg(r_error);
    returnValue = -93;
    status = "D";
  }

  else if (r_approved.isEmpty())
  {
    _errorMsg = errorMsg(-100)
		     .arg(r_error).arg(r_message).arg(presponse);
    returnValue = -100;
    status = "X";
  }

  // YP encodes AVS and CVV checking in the r_avs response field
  QRegExp avsRegExp("^[" + _metrics->value("CCAvsAddr") +
		    "][" + _metrics->value("CCAvsZIP") + "]");

  _passedAvs = _metrics->value("CCAvsCheck") == "X" ||
	       ! r_avs.contains(avsRegExp); // avsregexp matches failures

  _passedCvv = _metrics->value("CCCVVCheck") == "X" ||
	       ! r_avs.contains(QRegExp("[" + _metrics->value("CCCVVErrors") +
					"]$"));

  _passedLinkShield = (! _metrics->boolean("CCYPLinkShield")) ||
	      (! r_score.isEmpty() &&
	       r_score.toInt() <= _metrics->value("CCYPLinkShieldMax").toInt());

  if (DEBUG)
    qDebug("YP:%s\t_passedAvs %d\t_passedCvv %d\t_passedLinkShield %d",
	    r_avs.toAscii().data(), _passedAvs, _passedCvv, _passedLinkShield);

  pparams.append("ccard_id",    pccardid);
  pparams.append("auth_charge", ptype);
  pparams.append("type",        ptype);
  pparams.append("reforder",    preforder.isEmpty() ? pneworder : preforder);
  pparams.append("status",      status);
  pparams.append("avs",         r_avs);
  pparams.append("ordernum",    pneworder);
  pparams.append("xactionid",   r_ordernum.isEmpty() ? pneworder : r_ordernum);
  pparams.append("error",       r_error);
  pparams.append("approved",    r_approved);
  pparams.append("code",        r_code);
  pparams.append("score",       r_score.toInt());
  pparams.append("shipping",    r_shipping);
  pparams.append("tax",         r_tax);
  pparams.append("tdate",       r_tdate);
  pparams.append("ref",         r_ref);
  pparams.append("message",     r_message);

  if (pcurrid != _ypcurrid)
  {
    pparams.append("fromcurr",  pcurrid);
    pparams.append("tocurr",    _ypcurrid);
  }
  else
    pparams.append("currid",    pcurrid);

  if (ptype == "A")
    pparams.append("auth", QVariant(true, 0));
  else
    pparams.append("auth", QVariant(false, 1));

  if (! r_time.isEmpty())
    pparams.append("time",     r_time);

  if (DEBUG)
    qDebug("YP:r_error.isEmpty() = %d", r_error.isEmpty());

  if (! r_error.isEmpty())
  {
    _errorMsg = errorMsg(-12).arg(r_error);
    returnValue = -12;
  }

  if (returnValue == 0)
    pparams.append("amount",   pamount);
  else
    pparams.append("amount",   0);	// no money changed hands this attempt

  return returnValue;
}
Пример #27
0
bool VirtualConsole::loadPropertiesXML(const QDomElement &root)
{
    if (root.tagName() != KXMLQLCVCProperties)
    {
        qWarning() << Q_FUNC_INFO << "Virtual Console properties node not found";
        return false;
    }

    QString str;
    QDomNode node = root.firstChild();
    while (node.isNull() == false)
    {
        QDomElement tag = node.toElement();
        /** This is a legacy property, converted into
         *  VCFrame "WindowState" tag */
        if (tag.tagName() == KXMLQLCVCPropertiesSize)
        {
            QSize sz;

            /* Width */
            str = tag.attribute(KXMLQLCVCPropertiesSizeWidth);
            if (str.isEmpty() == false)
                sz.setWidth(str.toInt());

            /* Height */
            str = tag.attribute(KXMLQLCVCPropertiesSizeHeight);
            if (str.isEmpty() == false)
                sz.setHeight(str.toInt());

            /* Set size if both are valid */
            if (sz.isValid() == true)
                m_pages.at(0)->setGeometry(QRect(0, 0, sz.width(), sz.height()));
        }
#if 0
        else if (tag.tagName() == KXMLQLCVCPropertiesGrandMaster)
        {
            quint32 universe = InputOutputMap::invalidUniverse();
            quint32 channel = QLCChannel::invalid();

            str = tag.attribute(KXMLQLCVCPropertiesGrandMasterChannelMode);
            setGrandMasterChannelMode(GrandMaster::stringToChannelMode(str));

            str = tag.attribute(KXMLQLCVCPropertiesGrandMasterValueMode);
            setGrandMasterValueMode(GrandMaster::stringToValueMode(str));

            if (tag.hasAttribute(KXMLQLCVCPropertiesGrandMasterSliderMode))
            {
                str = tag.attribute(KXMLQLCVCPropertiesGrandMasterSliderMode);
                setGrandMasterSliderMode(GrandMaster::stringToSliderMode(str));
            }

            /* External input */
            if (loadXMLInput(tag.firstChild().toElement(), &universe, &channel) == true)
                setGrandMasterInputSource(universe, channel);
        }
#endif
        else
        {
            qWarning() << Q_FUNC_INFO << "Unknown Virtual Console property tag:"
                       << tag.tagName();
        }

        /* Next node */
        node = node.nextSibling();
    }

    return true;
}
Пример #28
0
QMap<QString, QVariant> MainWindow::loadObjectFromTemplateFile(QString filename)
{
    QDomDocument doc("New Object");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return QMap<QString, QVariant>();
    if (!doc.setContent(&file)) {
        file.close();
        return QMap<QString, QVariant>();
    }
    file.close();

    QMap<QString, QVariant> newObject;
    QString itemName = "null";
    QString itemName2 = "null";
    QString itemContents = "null";
    QString itemTag = "null";

    // print out the element names of all elements that are direct children
    // of the outermost element.
    QDomElement docElem = doc.documentElement();

    QDomNode n = docElem.firstChild();
    n = n.firstChild();
    while(!n.isNull()) {
        QDomElement e = n.toElement(); // try to convert the node to an element.
        if(!e.isNull()) {

            itemName = qPrintable(e.text()); // the node really is an element.
            itemTag = qPrintable(e.tagName());

            Q_ASSERT_X(itemTag == "key", "MainWindow::loadObjectFromTemplateFile", "Tag should be a key, but isn't!");

            n = n.nextSibling();
            e = n.toElement();
            itemContents = qPrintable(e.text());
            itemTag = qPrintable(e.tagName());
            if(itemTag != "array")
            {
                newObject.insert(itemName, itemContents);
            }
            else
            {
                QList< QVariant > subList;
                QDomNode x = e.firstChild(); // guessing here...
                while(!x.isNull())
                {
                    QMap<QString, QVariant> newMap;
                    QDomNode p = x.firstChild();
                    while(!p.isNull())
                    {
                        QDomElement g = p.toElement(); // try to convert the node to an element.
                        if(!g.isNull()) {

                            itemName2 = qPrintable(g.text()); // the node really is an element.
                            itemTag = qPrintable(g.tagName());

                            Q_ASSERT_X(itemTag == "key", "MainWindow::loadLevelPlist", "Level object tag should be a key, but isn't!");

                            p = p.nextSibling();
                            g = p.toElement();
                            itemContents = qPrintable(g.text());
                            itemTag = qPrintable(g.tagName());

                            newMap.insert(itemName2, itemContents);

                            p = p.nextSibling();
                        }
                    } // while object dict is not done

                    subList.append(newMap);
                    x = x.nextSibling();
                }

                newObject.insert(itemName, subList);
            }

            n = n.nextSibling();
        }
    }

    return newObject;
}
Пример #29
0
Файл: Song.cpp Проект: LMMS/lmms
// load given song
void Song::loadProject( const QString & fileName )
{
	QDomNode node;

	m_loadingProject = true;

	Engine::projectJournal()->setJournalling( false );

	m_oldFileName = m_fileName;
	setProjectFileName(fileName);

	DataFile dataFile( m_fileName );
	// if file could not be opened, head-node is null and we create
	// new project
	if( dataFile.head().isNull() )
	{
		if( m_loadOnLaunch )
		{
			createNewProject();
		}
		setProjectFileName(m_oldFileName);
		return;
	}

	m_oldFileName = m_fileName;

	clearProject();

	clearErrors();

	Engine::mixer()->requestChangeInModel();

	// get the header information from the DOM
	m_tempoModel.loadSettings( dataFile.head(), "bpm" );
	m_timeSigModel.loadSettings( dataFile.head(), "timesig" );
	m_masterVolumeModel.loadSettings( dataFile.head(), "mastervol" );
	m_masterPitchModel.loadSettings( dataFile.head(), "masterpitch" );

	if( m_playPos[Mode_PlaySong].m_timeLine )
	{
		// reset loop-point-state
		m_playPos[Mode_PlaySong].m_timeLine->toggleLoopPoints( 0 );
	}

	if( !dataFile.content().firstChildElement( "track" ).isNull() )
	{
		m_globalAutomationTrack->restoreState( dataFile.content().
						firstChildElement( "track" ) );
	}

	//Backward compatibility for LMMS <= 0.4.15
	PeakController::initGetControllerBySetting();

	// Load mixer first to be able to set the correct range for FX channels
	node = dataFile.content().firstChildElement( Engine::fxMixer()->nodeName() );
	if( !node.isNull() )
	{
		Engine::fxMixer()->restoreState( node.toElement() );
		if( gui )
		{
			// refresh FxMixerView
			gui->fxMixerView()->refreshDisplay();
		}
	}

	node = dataFile.content().firstChild();

	QDomNodeList tclist=dataFile.content().elementsByTagName("trackcontainer");
	m_nLoadingTrack=0;
	for( int i=0,n=tclist.count(); i<n; ++i )
	{
		QDomNode nd=tclist.at(i).firstChild();
		while(!nd.isNull())
		{
			if( nd.isElement() && nd.nodeName() == "track" )
			{
				++m_nLoadingTrack;
				if( nd.toElement().attribute("type").toInt() == Track::BBTrack )
				{
					n += nd.toElement().elementsByTagName("bbtrack").at(0)
						.toElement().firstChildElement().childNodes().count();
				}
				nd=nd.nextSibling();
			}
		}
	}

	while( !node.isNull() && !isCancelled() )
	{
		if( node.isElement() )
		{
			if( node.nodeName() == "trackcontainer" )
			{
				( (JournallingObject *)( this ) )->restoreState( node.toElement() );
			}
			else if( node.nodeName() == "controllers" )
			{
				restoreControllerStates( node.toElement() );
			}
			else if( gui )
			{
				if( node.nodeName() == gui->getControllerRackView()->nodeName() )
				{
					gui->getControllerRackView()->restoreState( node.toElement() );
				}
				else if( node.nodeName() == gui->pianoRoll()->nodeName() )
				{
					gui->pianoRoll()->restoreState( node.toElement() );
				}
				else if( node.nodeName() == gui->automationEditor()->m_editor->nodeName() )
				{
					gui->automationEditor()->m_editor->restoreState( node.toElement() );
				}
				else if( node.nodeName() == gui->getProjectNotes()->nodeName() )
				{
					 gui->getProjectNotes()->SerializingObject::restoreState( node.toElement() );
				}
				else if( node.nodeName() == m_playPos[Mode_PlaySong].m_timeLine->nodeName() )
				{
					m_playPos[Mode_PlaySong].m_timeLine->restoreState( node.toElement() );
				}
			}
		}
		node = node.nextSibling();
	}

	// quirk for fixing projects with broken positions of TCOs inside
	// BB-tracks
	Engine::getBBTrackContainer()->fixIncorrectPositions();

	// Connect controller links to their controllers
	// now that everything is loaded
	ControllerConnection::finalizeConnections();

	// Remove dummy controllers that was added for correct connections
	m_controllers.erase(std::remove_if(m_controllers.begin(), m_controllers.end(),
		[](Controller* c){return c->type() == Controller::DummyController;}),
		m_controllers.end());

	// resolve all IDs so that autoModels are automated
	AutomationPattern::resolveAllIDs();


	Engine::mixer()->doneChangeInModel();

	ConfigManager::inst()->addRecentlyOpenedProject( fileName );

	Engine::projectJournal()->setJournalling( true );

	emit projectLoaded();

	if( isCancelled() )
	{
		m_isCancelled = false;
		createNewProject();
		return;
	}

	if ( hasErrors())
	{
		if ( gui )
		{
			QMessageBox::warning( NULL, tr("LMMS Error report"), errorSummary(),
							QMessageBox::Ok );
		}
		else
		{
			QTextStream(stderr) << Engine::getSong()->errorSummary() << endl;
		}
	}

	m_loadingProject = false;
	setModified(false);
	m_loadOnLaunch = false;
}
Пример #30
0
bool KXpsPlugin::readInfo( KFileMetaInfo& info, uint /* what */)
{
    KFileMetaInfoGroup generalGroup = appendGroup(info, "General");

    KZip *xpsArchive = new KZip( info.path() );
    if ( xpsArchive->open( IO_ReadOnly ) == true ) {
        // kdDebug(7115) << "Successful open of " << xpsArchive->fileName() << endl;
    } else {
        kDebug(7115) << "Could not open XPS archive: " << xpsArchive->fileName();
	delete xpsArchive;
	return false;
    }

    const KZipFileEntry* relFile = static_cast<const KZipFileEntry *>(xpsArchive->directory()->entry("_rels/.rels"));

    if ( !relFile ) {
        delete xpsArchive;	
        // this might occur if we can't read the zip directory, or it doesn't have the relationships entry
        return false;
    }


    if ( relFile->name().isEmpty() ) {
	delete xpsArchive;
        // this might occur if we can't read the zip directory, or it doesn't have the relationships entry
        return false;
    }

    QIODevice* relDevice = relFile->createDevice();

    QDomDocument relDom;
    QString errMsg;
    int errLine, errCol;
    if ( relDom.setContent( relDevice, true, &errMsg, &errLine, &errCol ) == false ) {
        // parse error
        kDebug(7115) << "Could not parse relationship document: " << errMsg << " : "
		     << errLine << " : " << errCol << endl;
        delete relDevice;
	delete xpsArchive;
	return false;
    }

    QDomElement docElem = relDom.documentElement();
    
    QString thumbFileName;
    QString fixedRepresentationFileName;
    QString metadataFileName;

    QDomNode n = docElem.firstChild();
    while( !n.isNull() ) {
        QDomElement e = n.toElement();
	if( !e.isNull() ) {
	    if ("http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail" == e.attribute("Type") ) {
	        thumbFileName = e.attribute("Target");
	    } else if ("http://schemas.microsoft.com/xps/2005/06/fixedrepresentation" == e.attribute("Type") ) {
	        fixedRepresentationFileName = e.attribute("Target");
	    } else if ("http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" == e.attribute("Type") ) {
	        metadataFileName = e.attribute("Target");
	    }
	}
	n = n.nextSibling();
    }

    delete relDevice;

    if ( fixedRepresentationFileName.isEmpty() ) {
	delete xpsArchive;
        // FixedRepresentation is a required part of the XPS document
        return false;
    }

    const KZipFileEntry* fixedRepFile = static_cast<const KZipFileEntry *>(xpsArchive->directory()->entry( fixedRepresentationFileName ));

    QIODevice* fixedRepDevice = fixedRepFile->createDevice();

    QDomDocument fixedRepDom;
    if ( fixedRepDom.setContent( fixedRepDevice, true, &errMsg, &errLine, &errCol ) == false ) {
        // parse error
        kDebug(7115) << "Could not parse Fixed Representation document: " << errMsg << " : "
		     << errLine << " : " << errCol << endl;
        delete fixedRepDevice;
	delete xpsArchive;
	return false;
    }

    docElem = fixedRepDom.documentElement();

    QString firstDocumentFileName;
    int numDocuments = 0; // the number of Documents in this FixedDocumentSequence

    n = docElem.firstChild();
    while( !n.isNull() ) {
        QDomElement e = n.toElement();
	if( !e.isNull() ) {
	    if (e.tagName() == "DocumentReference") {
	        if (firstDocumentFileName.isEmpty()) {
		    // we don't already have a filename, so take this one
		    firstDocumentFileName = e.attribute("Source");
		}
		numDocuments++;
	    }
	}
	n = n.nextSibling();
    }

    delete fixedRepDevice;

#if 0
    // This stuff is used for detailed parsing - not really required

    // no document? bail out here.
    if ( firstDocumentFileName.isEmpty() ) {
        return false;
    }

    KZipFileEntry* firstDocumentFile = static_cast<const KZipFileEntry *>(xpsArchive->directory()->entry( firstDocumentFileName ));

    QIODevice* firstDocumentDevice = firstDocumentFile->device();    

    QDomDocument firstDocumentDom;
    if ( firstDocumentDom.setContent( firstDocumentDevice, true, &errMsg, &errLine, &errCol ) == false ) {
        // parse error
        kDebug(7115) << "Could not parse first document: " << errMsg << " : "
		     << errLine << " : " << errCol << endl;
	return false;
    }

    n = firstDocumentDom.documentElement().firstChild();

    while( !n.isNull() ) {
        QDomElement e = n.toElement();
	if( !e.isNull() ) {
	  kDebug(7155) << "DOcument: " << e.tagName() << " : " << e.text();
	}
	n = n.nextSibling();
    }
#endif

    if ( ! metadataFileName.isEmpty() ) {
        const KZipFileEntry* corepropsFile = static_cast<const KZipFileEntry *>(xpsArchive->directory()->entry(metadataFileName));
	kDebug(7115) << "metadata file name: " << metadataFileName;

	QDomDocument metadataDocumentDom;

	QIODevice *corepropsDevice = corepropsFile->createDevice();

	if ( metadataDocumentDom.setContent( corepropsDevice, true, &errMsg, &errLine, &errCol ) == false ) {
	    // parse error
	    kDebug(7115) << "Could not parse core properties (metadata) document: " << errMsg << " : "
			 << errLine << " : " << errCol << endl;
            delete corepropsDevice;
	    delete xpsArchive;
	    return false;
	}

	n = metadataDocumentDom.documentElement().firstChild(); // the <coreProperties> level
	while( !n.isNull() ) {
	    QDomElement e = n.toElement();
	    if( !e.isNull() ) {
		if (e.tagName() == "title") {
		    appendItem(generalGroup, "Title", e.text() );
		} else if (e.tagName() == "subject") {
		    appendItem(generalGroup, "Subject", e.text() );
		} else if (e.tagName() == "description") {
		    appendItem(generalGroup, "Description", e.text() );
		} else if (e.tagName() == "creator") {
		    appendItem(generalGroup, "Author", e.text() );
		} else if (e.tagName() == "created") {
		    appendItem(generalGroup, "CreationDate", QDateTime::fromString( e.text(), "yyyy-MM-ddThh:mm:ssZ" ) );
		} else if (e.tagName() == "modified") {
		    appendItem(generalGroup, "ModificationDate", QDateTime::fromString( e.text(), "yyyy-MM-ddThh:mm:ssZ" ) );
		} else if (e.tagName() == "keywords") {
		    appendItem(generalGroup, "Keywords", e.text() );
		} else {
		    kDebug(7155) << "unhandled metadata tag: " << e.tagName() << " : " << e.text();
		}
	    }
	    n = n.nextSibling();
	}

	delete corepropsDevice;
    }

    if ( ! thumbFileName.isEmpty() ) {
        const KZipFileEntry* thumbFile = static_cast<const KZipFileEntry *>(xpsArchive->directory()->entry(thumbFileName));

	QImage img;
	img.loadFromData(thumbFile->data());

	appendItem( generalGroup, "Thumbnail", img);
	appendItem( generalGroup, "ThumbnailDimensions", QSize( img.width(), img.height() ) );
    }

    appendItem(generalGroup, "Documents", numDocuments);

    delete xpsArchive;

    return true;
}