Exemplo n.º 1
0
void XBELImportCommand::doExecute(const KBookmarkGroup &/*bkGroup*/) {
    // check if already open first???
    KBookmarkManager *pManager = KBookmarkManager::managerForFile(m_fileName, QString());

    QDomDocument doc = GlobalBookmarkManager::self()->mgr()->internalDocument();

    // get the xbel
    QDomNode subDoc = pManager->internalDocument().namedItem("xbel").cloneNode();
    if (subDoc.isProcessingInstruction())
        subDoc = subDoc.nextSibling();
    if (subDoc.isDocumentType())
        subDoc = subDoc.nextSibling();
    if (subDoc.nodeName() != "xbel")
        return;

    if (!folder().isEmpty()) {
        // transform into folder
        subDoc.toElement().setTagName("folder");

        // clear attributes
        QStringList tags;
        for (int i = 0; i < subDoc.attributes().count(); i++)
            tags << subDoc.attributes().item(i).toAttr().name();
        for (QStringList::const_iterator it = tags.constBegin(); it != tags.constEnd(); ++it)
            subDoc.attributes().removeNamedItem((*it));

        subDoc.toElement().setAttribute("icon", m_icon);

        // give the folder a name
        QDomElement textElem = doc.createElement("title");
        subDoc.insertBefore(textElem, subDoc.firstChild());
        textElem.appendChild(doc.createTextNode(folder()));
    }

    // import and add it
    QDomNode node = doc.importNode(subDoc, true);

    if (!folder().isEmpty()) {
        GlobalBookmarkManager::self()->root().internalElement().appendChild(node);
        m_group = KBookmarkGroup(node.toElement()).address();

    } else {
        QDomElement root = GlobalBookmarkManager::self()->root().internalElement();

        QList<QDomElement> childList;

        QDomNode n = subDoc.firstChild().toElement();
        while (!n.isNull()) {
            QDomElement e = n.toElement();
            if (!e.isNull())
                childList.append(e);
            n = n.nextSibling();
        }

        QList<QDomElement>::Iterator it = childList.begin();
        QList<QDomElement>::Iterator end = childList.end();
        for (; it!= end ; ++it)
            root.appendChild((*it));
    }
}
Exemplo n.º 2
0
QDomNode QDomDocumentProto::importNode(const QDomNode& importedNode, bool deep)
{
    QDomDocument *item = qscriptvalue_cast<QDomDocument*>(thisObject());
    if (item)
        return item->importNode(importedNode, deep);
    return QDomNode();
}
Exemplo n.º 3
0
void InterpreterElementImpl::init(QRectF &contents, PortFactoryInterface const &portFactory
		, QList<PortInterface *> &ports, LabelFactoryInterface &labelFactory
		, QList<LabelInterface *> &labels, SdfRendererInterface *renderer, ElementRepoInterface *elementRepo)
{
	Q_UNUSED(elementRepo);
	if (mId.element() == "MetaEntityNode") {
		mGraphics.setContent(mEditorRepoApi->stringProperty(mId, "shape"));
		QDomDocument classDoc;
		QDomElement sdfElement = mGraphics.firstChildElement("graphics").firstChildElement("picture");
		classDoc.appendChild(classDoc.importNode(sdfElement, true));
		if (!classDoc.childNodes().isEmpty()) {
			mRenderer = renderer;
			mRenderer->load(classDoc);
		}

		int width = 0;
		int height = 0;
		if (!sdfElement.isNull()) {
			width = sdfElement.attribute("sizex").toInt();
			height = sdfElement.attribute("sizey").toInt();
		}

		initPointPorts(portFactory, ports, width, height);
		initLinePorts(portFactory, ports, width, height);

		contents.setWidth(width);
		contents.setHeight(height);
		initLabels(width, height, labelFactory, labels);
	}
}
Exemplo n.º 4
0
void Signaltypes::save_types()
{
	char cfg_path[MAX_PATH_LENGTH];
	bool success;
	QDomDocument document;

	// Creating xml-document part
	QDomElement root = document.createElement("Signaltypes");
	root.setAttribute("version", "0.0.1");

	for(unsigned i=0; i<types.size(); i++)
	{
		QDomNode type = document.importNode( types[i]->toQDom(), true );	// true : Import the whole tree.
		root.appendChild(type);
	}


	// Writing-to-file part
	configpath(cfg_path, "Signaltypes.xml");
	QFile file(cfg_path);
	success = file.open( QIODevice::WriteOnly | QIODevice::Text ); 
	if(not success) { QMessageBox::warning(parent->mainwindow, tr("Signaltypes"), tr("Cannot write file %1:\n%2.").arg(cfg_path).arg(file.errorString())); default_types(); return; }

	QTextStream stream( &file );
	
	stream << document.toString();

	file.close();
}
Exemplo n.º 5
0
void CollapsibleGroup::slotDeleteGroup()
{
    QDomDocument doc;
    // delete effects from the last one to the first, otherwise each deletion would trigger an update
    // in other effects's kdenlive_ix index.
    for (int i = m_subWidgets.count() - 1; i >= 0; i--)
        doc.appendChild(doc.importNode(m_subWidgets.at(i)->effect(), true));
    emit deleteGroup(doc);
}
Exemplo n.º 6
0
void CollapsibleGroup::slotDeleteGroup()
{
    QDomDocument doc;
    // delete effects from the last one to the first, otherwise each deletion would trigger an update
    // in other effects's kdenlive_ix index.
    for (int i = m_subWidgets.count() - 1; i >= 0; --i)
        doc.appendChild(doc.importNode(m_subWidgets.at(i)->effect(), true));
    doc.documentElement().setAttribute(QStringLiteral("name"), m_info.groupName);
    emit deleteGroup(doc);
}
Exemplo n.º 7
0
QDomDocument CollapsibleGroup::effectsData()
{
    QMutexLocker lock(&m_mutex);
    QDomDocument doc;
    QDomElement list = doc.createElement("effectgroup");
    list.setAttribute("name", m_title->text());
    doc.appendChild(list);
    for (int j = 0; j < m_subWidgets.count(); j++) {
	list.appendChild(doc.importNode(m_subWidgets.at(j)->effect(), true));
    }
    return doc;
}
Exemplo n.º 8
0
QString SvgFileSplitter::elementString(const QString & elementID) {
	QDomElement root = m_domDocument.documentElement();

	QDomElement mainElement = TextUtils::findElementWithAttribute(root, "id", elementID);
	if (mainElement.isNull()) return ___emptyString___;

	QDomDocument document;
	QDomNode node = document.importNode(mainElement, true);
	document.appendChild(node);

	return document.toString();
}
Exemplo n.º 9
0
void ZynAddSubFxInstrument::saveSettings( QDomDocument & _doc,
											QDomElement & _this )
{
	m_portamentoModel.saveSettings( _doc, _this, "portamento" );
	m_filterFreqModel.saveSettings( _doc, _this, "filterfreq" );
	m_filterQModel.saveSettings( _doc, _this, "filterq" );
	m_bandwidthModel.saveSettings( _doc, _this, "bandwidth" );
	m_fmGainModel.saveSettings( _doc, _this, "fmgain" );
	m_resCenterFreqModel.saveSettings( _doc, _this, "rescenterfreq" );
	m_resBandwidthModel.saveSettings( _doc, _this, "resbandwidth" );

	QString modifiedControllers;
	for( QMap<int, bool>::ConstIterator it = m_modifiedControllers.begin();
									it != m_modifiedControllers.end(); ++it )
	{
		if( it.value() )
		{
			modifiedControllers += QString( "%1," ).arg( it.key() );
		}
	}
	_this.setAttribute( "modifiedcontrollers", modifiedControllers );

	m_forwardMidiCcModel.saveSettings( _doc, _this, "forwardmidicc" );

	QTemporaryFile tf;
	if( tf.open() )
	{
		const std::string fn = QSTR_TO_STDSTR(
									QDir::toNativeSeparators( tf.fileName() ) );
		m_pluginMutex.lock();
		if( m_remotePlugin )
		{
			m_remotePlugin->lock();
			m_remotePlugin->sendMessage( RemotePlugin::message( IdSaveSettingsToFile ).addString( fn ) );
			m_remotePlugin->waitForMessage( IdSaveSettingsToFile );
			m_remotePlugin->unlock();
		}
		else
		{
			m_plugin->saveXML( fn );
		}
		m_pluginMutex.unlock();
		QByteArray a = tf.readAll();
		QDomDocument doc( "mydoc" );
		if( doc.setContent( a ) )
		{
			QDomNode n = _doc.importNode( doc.documentElement(), true );
			_this.appendChild( n );
		}
	}
}
Exemplo n.º 10
0
// Author & Date: Ehsan Azar       3 April 2012
// Purpose: Get the string equivalent of the current node or document
// Outputs:
//   Returns a string of the current node (and its children) as separate XML document string
QString XmlFile::toString()
{
    QDomElement node;
    // If it is the first node
    if (m_nodes.isEmpty())
    {
        return m_doc.toString();
    }
    // Create a document with new root 
    QDomDocument doc;
    node = m_nodes.last().cloneNode().toElement();
    if (!node.isNull())
    {
        doc.importNode(node, true);
        doc.appendChild(node);
    }
    return doc.toString();
}
Exemplo n.º 11
0
void ScrobblerSubmitter::saveSubmitQueue()
{
    QFile file( m_savePath );

    if( !file.open( IO_WriteOnly ) )
    {
        debug() << "[SCROBBLER] Couldn't write submit queue to file: " << m_savePath << endl;
        return;
    }

    if ( m_lastSubmissionFinishTime == 0 )
        m_lastSubmissionFinishTime = QDateTime::currentDateTime( Qt::UTC ).toTime_t();

    QDomDocument newdoc;
    QDomElement submitQueue = newdoc.createElement( "submit" );
    submitQueue.setAttribute( "product", "pan" ); //registered @ last.fm Jan 2010
    submitQueue.setAttribute( "version", APP_VERSION );
    submitQueue.setAttribute( "lastSubmissionFinishTime", m_lastSubmissionFinishTime );


    m_submitQueue.first();
    for ( uint idx = 0; idx < m_submitQueue.count(); idx++ )
    {
        SubmitItem *item = m_submitQueue.at( idx );
        QDomElement i = item->toDomElement( newdoc );
        submitQueue.appendChild( i );
    }
    m_fakeQueue.first();
    for ( uint idx = 0; idx < m_fakeQueue.count(); idx++ )
    {
        SubmitItem *item = m_fakeQueue.at( idx );
        QDomElement i = item->toDomElement( newdoc );
        submitQueue.appendChild( i );
    }

    QDomNode submitNode = newdoc.importNode( submitQueue, true );
    newdoc.appendChild( submitNode );

    QTextStream stream( &file );
    stream.setEncoding( QTextStream::UnicodeUTF8 );
    stream << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    stream << newdoc.toString();
    file.close();
}
void F520xmlserializer::deserialize(QDomDocument xml, F520Status &f520, SysError &sysErr) {

    qDebug() << "F520xmlserializer -> deserialize";


    QDomNodeList attributeNodes = xml.elementsByTagName( ATTRIBUTE );

    for(unsigned indey = 0; indey < attributeNodes.length(); indey++) {
        QDomElement element = attributeNodes.at(indey).toElement();
        qDebug() << "Element Name: " << element.attributes().namedItem(NAME).nodeValue();
        if (element.attributes().namedItem(NAME).nodeValue().compare(WHERE) == 0) {
            qDebug() << "Element Value: " << element.attributes().namedItem(VALUE).nodeValue();
            f520.setWhere(element.attributes().namedItem(VALUE).nodeValue());
        } else if (element.attributes().namedItem(NAME).nodeValue().compare(SRC) == 0) {
            f520.setXmlPath(element.attributes().namedItem(VALUE).nodeValue());
        } else if (element.attributes().namedItem(NAME).nodeValue().compare(MAX_ENERGY_VALUE) == 0) {
            f520.setMaxNrgValue(element.attributes().namedItem(VALUE).nodeValue());
        }
    }

    QDomNodeList carico = xml.elementsByTagName( CARICO );

    if (carico.count() < 1) {
        sysErr = SysError(SysError::F520_RESOUCES_NOT_FOUND, "F520 Can not find resources");
        return;
    }

    QDomDocument document;

    QDomNode tmp = document.importNode(carico.item(0), true);
    document.appendChild(tmp);

    qDebug() << document.toString();

    QFile inFile( f520.getXmlPath() );
    inFile.open( QIODevice::ReadWrite );
    inFile.resize(0);

    inFile.write(document.toString().toStdString().c_str());

    inFile.close();
}
Exemplo n.º 13
0
void CarlaInstrument::saveSettings(QDomDocument& doc, QDomElement& parent)
{
    if (fHandle == NULL || fDescriptor->get_state == NULL)
        return;

    char* const state = fDescriptor->get_state(fHandle);

    if (state == NULL)
        return;

    QDomDocument carlaDoc("carla");

    if (carlaDoc.setContent(QString(state)))
    {
        QDomNode n = doc.importNode(carlaDoc.documentElement(), true);
        parent.appendChild(n);
    }

    std::free(state);
}
Exemplo n.º 14
0
QByteArray FopLeader::SaveElement( const QDomElement e )
{
    QDomDocument em;
    QDomElement import = em.createElement(e.tagName().toLower());
    em.appendChild( import );
    QDomNamedNodeMap attlist = e.attributes();
    for (int i=0; i<attlist.count(); i++){
    QDomNode nod = attlist.item(i);
    import.setAttribute (nod.nodeName().toLower(),nod.nodeValue()); 
    }
                            QDomNode child = e.firstChild();
                               while ( !child.isNull() ) {
                                   if ( child.isElement() ) {
                                    import.appendChild(em.importNode(child,true).toElement());
                                   }
                                 child = child.nextSibling();            
                               }
															 
    return em.toByteArray(0);
}
Exemplo n.º 15
0
QDomDocument QgsSLDConfigParser::getStyle( const QString& styleName, const QString& layerName ) const
{
  QDomElement userLayerElement = findUserLayerElement( layerName );

  if ( userLayerElement.isNull() )
  {
    throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a Layer not offered by the server." ) );
  }

  QDomElement userStyleElement = findUserStyleElement( userLayerElement, styleName );

  if ( userStyleElement.isNull() )
  {
    throw QgsMapServiceException( QStringLiteral( "StyleNotDefined" ), QStringLiteral( "Operation request references a Style not offered by the server." ) );
  }

  QDomDocument styleDoc;
  styleDoc.appendChild( styleDoc.importNode( userStyleElement, true ) );
  return styleDoc;
}
Exemplo n.º 16
0
QDomDocument QgsSLDConfigParser::getStyles( QStringList& layerList ) const
{
  QDomDocument styleDoc;
  for ( int i = 0; i < layerList.size(); i++ )
  {
    QString layerName;
    layerName = layerList.at( i );
    QDomElement userLayerElement = findUserLayerElement( layerName );
    if ( userLayerElement.isNull() )
    {
      throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a Layer not offered by the server." ) );
    }
    QDomNodeList userStyleList = userLayerElement.elementsByTagName( QStringLiteral( "UserStyle" ) );
    for ( int j = 0; j < userStyleList.size(); j++ )
    {
      QDomElement userStyleElement = userStyleList.item( i ).toElement();
      styleDoc.appendChild( styleDoc.importNode( userStyleElement, true ) );
    }
  }
  return styleDoc;
}
Exemplo n.º 17
0
//virtual
QMimeData * EffectsListWidget::mimeData(const QList<QTreeWidgetItem *> list) const
{
    QDomDocument doc;
    bool transitionMode = false;
    foreach(QTreeWidgetItem *item, list) {
        if (item->flags() & Qt::ItemIsDragEnabled) {
            int type = item->data(0, TypeRole).toInt();
            if (type == EffectsList::TRANSITION_TYPE) {
                transitionMode = true;
            }
            QStringList info = item->data(0, IdRole).toStringList();
            const QDomElement e = itemEffect(type, info);
            if (!e.isNull())
                doc.appendChild(doc.importNode(e, true));
        }
    }
    QMimeData *mime = new QMimeData;
    QByteArray data;
    data.append(doc.toString().toUtf8());
    mime->setData(transitionMode ? "kdenlive/transitionslist" : "kdenlive/effectslist", data);
    return mime;
}
Exemplo n.º 18
0
// function that parses an XML DOM for 'xs:include' directives and loads
// and inserts the mentioned documents into it
void
load(QDomNode n) {
    while (!n.isNull()) {
        if (n.hasChildNodes()) {
            load(n.firstChild());
        }
        if (n.nodeName() == "xs:include") {
            QString f = n.toElement().attribute("schemaLocation");
            QDomDocument d = loadDocument(dir+"/"+f);
            QDomDocument o = n.ownerDocument();
            QDomNode newn = o.importNode(d.documentElement(), true);
            QDomNode p = n.parentNode();
            QDomNode old = n;
            n = n.nextSibling();
            p.removeChild(old);
            while (!newn.firstChild().isNull()) {
                p.insertBefore(newn.firstChild(), n);
            }
        } else {
            n = n.nextSibling();
        }
    }
}
Exemplo n.º 19
0
QByteArray CatDomElement( const QDomElement e )
{
    if (e.isNull()) {
        return QByteArray();
    }
    QDomDocument doc;
    QDomElement Pbb = doc.createElement(e.tagName());
    QDomNamedNodeMap alist = e.attributes();
    for (int i=0; i<alist.count(); i++) {
        QDomNode nod = alist.item(i);
        Pbb.setAttribute(nod.nodeName().toLower(),nod.nodeValue());
    }
    doc.appendChild(Pbb);

    QDomNode child = e.firstChild();
    while ( !child.isNull() ) {
        if ( child.isElement() ) {
            Pbb.appendChild(doc.importNode(child,true).toElement());
        }
        child = child.nextSibling();
    }

    return doc.toByteArray(1);
}
RenderSettingsDialog::RenderSettingsDialog(QWidget *parent) :
		QDialog(parent, Qt::Sheet),
	ui(new Ui::RenderSettingsDialog), m_icNode(NULL), m_aiNode(NULL) {
	ui->setupUi(this);

	connect(ui->integratorBox, SIGNAL(highlighted(int)), SLOT(cbHighlighted(int)));
	connect(ui->integratorBox, SIGNAL(activated(int)), SLOT(update()));
	connect(ui->samplerBox, SIGNAL(highlighted(int)), SLOT(cbHighlighted(int)));
	connect(ui->samplerBox, SIGNAL(activated(int)), SLOT(update()));
	connect(ui->rFilterBox, SIGNAL(highlighted(int)), SLOT(cbHighlighted(int)));
	connect(ui->rFilterBox, SIGNAL(activated(int)), SLOT(update()));
	connect(ui->icBox, SIGNAL(pressed()), SLOT(chkBoxPressed()));
	connect(ui->aiBox, SIGNAL(pressed()), SLOT(chkBoxPressed()));
	connect(ui->icBox, SIGNAL(toggled(bool)), SLOT(update()));
	connect(ui->aiBox, SIGNAL(toggled(bool)), SLOT(update()));
	connect(ui->resolutionBox, SIGNAL(activated(int)), SLOT(refresh()));
	connect(ui->resolutionBox, SIGNAL(editTextChanged(const QString &)), SLOT(refresh()));

	QFile file(":/resources/docs.xml");
	if (!file.open(QIODevice::ReadOnly) || !m_document.setContent(&file))
		SLog(EError, "Unable to read the documentation file!");
	file.close();

	/* Populate the integrator, rec. filter & sampler combo box widgets */
	QDomElement docRoot = m_document.documentElement();
	for (QDomElement e = docRoot.firstChildElement("plugin"); !e.isNull();
		 e = e.nextSiblingElement("plugin")) {
		QString docString, name = e.attribute("name");
		if (!e.firstChildElement("descr").isNull()) {
			/* Create a HTML-based documentation string */
			QDomDocument helpDoc;
			QDomElement root = helpDoc.createElement("p");
			helpDoc.appendChild(root);

			for (QDomNode child = e.firstChildElement("descr").firstChild();
			   !child.isNull(); child = child.nextSibling())
			root.appendChild(helpDoc.importNode(child, true));
			docString = helpDoc.toString();
		}

		if (e.hasAttribute("show") && e.attribute("show") == "true") {
			QString type = e.attribute("type"),
					className = e.attribute("className"),
					readableName = e.attribute("readableName"),
					name = e.attribute("name");

			QList<QVariant> list;
			list.append(className);
			list.append(docString);
			list.append(name);

			if (type == "integrator")
				ui->integratorBox->addItem(readableName, list);
			else if (type == "sampler")
				ui->samplerBox->addItem(readableName, list);
			else if (type == "rfilter")
				ui->rFilterBox->addItem(readableName, list);
		}
		if (name == "irrcache")
			ui->icBox->setProperty("help", docString);
		else if (name == "adaptive")
			ui->aiBox->setProperty("help", docString);
	}

	m_model = new XMLTreeModel(docRoot, palette(), this);
	ui->treeView->setModel(m_model);
	ui->treeView->setAlternatingRowColors(true);
	ui->treeView->setUniformRowHeights(true);
	ui->treeView->setColumnWidth(0, 270);
	ui->treeView->setStyleSheet("QTreeView::item { padding-right: 8px; }");
	ui->treeView->setItemDelegate(new PropertyDelegate(this));
	connect(ui->treeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection)),
		SLOT(onTreeSelectionChange(const QItemSelection &, const QItemSelection &)));
	connect(m_model, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(dataChanged()));
	m_integratorNode = m_model->registerClass("MIPathTracer", "Path tracer");
	m_samplerNode = m_model->registerClass("IndependentSampler", "Independent sampler");
	m_rFilterNode = m_model->registerClass("BoxFilter", "Box filter");
	QRegExp resRegExp("^[1-9]\\d{0,4}x[1-9]\\d{0,4}$");
	ui->resolutionBox->setValidator(new QRegExpValidator(resRegExp, this));
	QPalette pal = ui->helpViewer->palette();
	pal.setColor(QPalette::Text, pal.color(QPalette::Foreground));
	pal.setColor(QPalette::Base, pal.color(QPalette::Window));
	ui->helpViewer->setPalette(pal);
	ui->helpViewer->setHtml("Click on any setting for documentation");
}
Exemplo n.º 21
0
QDomElement SmartPlaylistEditor::result() {
    QDomDocument doc;
    QDomNode node = doc.namedItem( "smartplaylists" );
    QDomElement nodeE;
    nodeE = node.toElement();

    QDomElement smartplaylist = doc.createElement( "smartplaylist" );

    smartplaylist.setAttribute( "name", name() );

    // Limit
    if ( m_limitCheck->isChecked() )
        smartplaylist.setAttribute( "maxresults", m_limitSpin->value() );

    nodeE.appendChild( smartplaylist );
    // Matches
    if( m_matchAnyCheck->isChecked() ) {
        QDomElement matches = doc.createElement("matches");
        smartplaylist.appendChild( matches );
        // Iterate through all criteria list
        CriteriaEditor *criteriaeditor = m_criteriaEditorAnyList.first();
        for( int i=0; criteriaeditor; criteriaeditor = m_criteriaEditorAnyList.next(), ++i ) {
            matches.appendChild( doc.importNode( criteriaeditor->getDomSearchCriteria( doc ), true ) );
        }
        matches.setAttribute( "glue",  "OR" );
        smartplaylist.appendChild( matches );
    }

    if( m_matchAllCheck->isChecked() ) {
        QDomElement matches = doc.createElement("matches");
        smartplaylist.appendChild( matches );
        // Iterate through all criteria list
        CriteriaEditor *criteriaeditor = m_criteriaEditorAllList.first();
        for( int i=0; criteriaeditor; criteriaeditor = m_criteriaEditorAllList.next(), ++i ) {
            matches.appendChild( doc.importNode( criteriaeditor->getDomSearchCriteria( doc ), true ) );
        }
        matches.setAttribute( "glue",  "AND" );
        smartplaylist.appendChild( matches );
    }

    // Order By
    if( m_orderCheck->isChecked() ) {
        QDomElement orderby = doc.createElement("orderby");
        if (m_orderCombo->currentItem() != m_orderCombo->count()-1) {
            orderby.setAttribute( "field", m_dbFields[ m_orderCombo->currentItem() ] );
            orderby.setAttribute( "order", m_orderTypeCombo->currentItem() == 1 ? "DESC" : "ASC" );
        } else {
            orderby.setAttribute( "field", "random" );
            orderby.setAttribute( "order", m_orderTypeCombo->currentItem() == 1 ? "weighted" : "random" );
        }

        smartplaylist.appendChild( orderby );
    }
    QDomElement Sql = doc.createElement("sqlquery");
    buildQuery();
    Sql.appendChild( doc.createTextNode( m_query ) );
    smartplaylist.appendChild( Sql );

    if( m_expandCheck->isChecked() ) {
        QDomElement expandBy = doc.createElement("expandby");
        expandBy.setAttribute( "field", m_expandableFields[ m_expandCombo->currentItem() ] );
        QDomText t = doc.createTextNode( m_expandQuery );
        expandBy.appendChild( t );
        smartplaylist.appendChild( expandBy );
    }
    return (smartplaylist);
}
Exemplo n.º 22
0
bool SvgFileSplitter::splitString(QString & contents, const QString & elementID)
{
	m_byteArray.clear();

	// gets rid of some crap inserted by illustrator which can screw up polygons and paths
	contents.replace('\t', ' ');
	contents.replace('\n', ' ');
	contents.replace('\r', ' ');

	// get rid of inkscape stuff too
	TextUtils::cleanSodipodi(contents);

	QString errorStr;
	int errorLine;
	int errorColumn;

	if (!m_domDocument.setContent(contents, true, &errorStr, &errorLine, &errorColumn)) {
        //DebugDialog::debug(QString("parse error: %1 l:%2 c:%3\n\n%4").arg(errorStr).arg(errorLine).arg(errorColumn).arg(contents));
		return false;
	}

	QDomElement root = m_domDocument.documentElement();
	if (root.isNull()) {
		return false;
	}

	if (root.tagName() != "svg") {
		return false;
	}

	root.removeAttribute("space");

	QDomElement element = TextUtils::findElementWithAttribute(root, "id", elementID);
	if (element.isNull()) {
		return false;
	}

	QStringList superTransforms;
	QDomNode parent = element.parentNode();
	while (!parent.isNull()) {
		QDomElement e = parent.toElement();
		if (!e.isNull()) {
			QString transform = e.attribute("transform");
			if (!transform.isEmpty()) {
				superTransforms.append(transform);
			}
		}
		parent = parent.parentNode();
	}

	if (!superTransforms.isEmpty()) {
		element.removeAttribute("id");
	}

	QDomDocument document;
	QDomNode node = document.importNode(element, true);
	document.appendChild(node);
	QString elementText = document.toString();

	if (!superTransforms.isEmpty()) {
		for (int i = 0; i < superTransforms.count() - 1; i++) {
			elementText = QString("<g transform='%1'>%2</g>").arg(superTransforms[i]).arg(elementText);
		}
		elementText = QString("<g id='%1' transform='%2'>%3</g>")
			.arg(elementID)
			.arg(superTransforms[superTransforms.count() - 1])
			.arg(elementText);
	}

	while (!root.firstChild().isNull()) {
		root.removeChild(root.firstChild());
	}

	// at this point the document should contain only the <svg> element and possibly svg info strings
	QString svgOnly = m_domDocument.toString();
	int ix = svgOnly.lastIndexOf("/>");
	if (ix < 0) return false;

	svgOnly[ix] = ' ';
	svgOnly += elementText;
	svgOnly += "</svg>";

	if (!m_domDocument.setContent(svgOnly, true, &errorStr, &errorLine, &errorColumn)) {
		return false;
	}

	m_byteArray = m_domDocument.toByteArray();

	//QString s = m_domDocument.toString();
	//DebugDialog::debug(s);

	return true;
}
Exemplo n.º 23
0
void EffectStackEdit::transferParamDesc(const QDomElement& d, int in, int out)
{
    kDebug() << "in";
    m_params = d;
    m_in = in;
    m_out = out;
    clearAllItems();
    if (m_params.isNull()) return;

    QDomDocument doc;
    doc.appendChild(doc.importNode(m_params, true));
    //kDebug() << "IMPORTED TRANS: " << doc.toString();
    QDomNodeList namenode = m_params.elementsByTagName("parameter");
    QDomElement e = m_params.toElement();
    const int minFrame = e.attribute("start").toInt();
    const int maxFrame = e.attribute("end").toInt();


    for (int i = 0;i < namenode.count() ;i++) {
        kDebug() << "in form";
        QDomElement pa = namenode.item(i).toElement();
        QDomNode na = pa.firstChildElement("name");
        QString type = pa.attribute("type");
        QString paramName = i18n(na.toElement().text().toUtf8().data());
        QWidget * toFillin = new QWidget;
        QString value = pa.attribute("value").isNull() ?
                        pa.attribute("default") : pa.attribute("value");
        if (type == "geometry") {
            /*pa.setAttribute("namedesc", "X;Y;Width;Height;Transparency");
            pa.setAttribute("format", "%d%,%d%:%d%x%d%:%d");
            pa.setAttribute("min", "-500;-500;0;0;0");
            pa.setAttribute("max", "500;500;200;200;100");*/
        } else if (type == "complex") {
            //pa.setAttribute("namedesc",pa.attribute("name"));

        }


        //TODO constant, list, bool, complex , color, geometry, position
        if (type == "double" || type == "constant") {
            createSliderItem(paramName, value.toInt(), pa.attribute("min").toInt(), pa.attribute("max").toInt());
            delete toFillin;
            toFillin = NULL;
        } else if (type == "list") {
            Listval *lsval = new Listval;
            lsval->setupUi(toFillin);
            QStringList listitems = pa.attribute("paramlist").split(',');
            QStringList listitemsdisplay = pa.attribute("paramlistdisplay").split(',');
            if (listitemsdisplay.count() != listitems.count()) listitemsdisplay = listitems;
            //lsval->list->addItems(listitems);
            lsval->list->setIconSize(QSize(30, 30));
            for (int i = 0;i < listitems.count();i++) {
                lsval->list->addItem(listitemsdisplay.at(i), listitems.at(i));
                QString entry = listitems.at(i);
                if (!entry.isEmpty() && (entry.endsWith(".png") || entry.endsWith(".pgm"))) {
                    if (!EffectStackEdit::iconCache.contains(entry)) {
                        QImage pix(entry);
                        EffectStackEdit::iconCache[entry] = pix.scaled(30, 30);
                    }
                    lsval->list->setItemIcon(i, QPixmap::fromImage(iconCache[entry]));
                }
            }
            if (!value.isEmpty()) lsval->list->setCurrentIndex(listitems.indexOf(value));

            connect(lsval->list, SIGNAL(currentIndexChanged(int)) , this, SLOT(collectAllParameters()));
            lsval->title->setTitle(paramName);
            m_valueItems[paramName] = lsval;
            m_uiItems.append(lsval);
        } else if (type == "bool") {
Exemplo n.º 24
0
/** Actually sends the sMethod action to the command URL specified
 *  in the constructor (url+[/]+sControlPath).
 *
 * \param sMethod method to be invoked. e.g. "SetChannel",
 *                "GetConnectionInfoResult"
 *
 * \param list Parsed as a series of key value pairs for the input params
 *             and then cleared and used for the output params.
 *
 * \param nErrCode set to zero on success, non-zero in case of error.
 *
 * \param sErrCode returns error description from device, when applicable.
 *
 * \param bInQtThread May be set to true if this is run from within
 *                    a QThread with a running an event loop.
 *
 * \return Returns a QDomDocument containing output parameters on success.
 */
QDomDocument SOAPClient::SendSOAPRequest(const QString &sMethod,
                                         QStringMap    &list,
                                         int           &nErrCode,
                                         QString       &sErrDesc,
                                         bool           bInQtThread)
{
    QUrl url(m_url);

    url.setPath(m_sControlPath);

    nErrCode = UPnPResult_Success;
    sErrDesc = "";

    QDomDocument xmlResult;
    if (m_sNamespace.isEmpty())
    {
        nErrCode = UPnPResult_MythTV_NoNamespaceGiven;
        sErrDesc = "No namespace given";
        return xmlResult;
    }

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------

    QHttpRequestHeader header("POST", sMethod, 1, 0);

    header.setValue("CONTENT-TYPE", "text/xml; charset=\"utf-8\"" );
    header.setValue("SOAPACTION",
                    QString("\"%1#%2\"").arg(m_sNamespace).arg(sMethod));

    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os.setCodec("UTF-8");

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope "
        " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\""
        " xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for (QStringMap::iterator it = list.begin(); it != list.end(); ++it)
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    QBuffer buff(&aBuffer);

    LOG(VB_UPNP, LOG_DEBUG,
        QString("SOAPClient(%1) sending:\n").arg(url.toString()) +
        header.toString() + QString("\n%1\n").arg(aBuffer.constData()));

    QString sXml =
        HttpComms::postHttp(url,
                            &header,
                            &buff, // QIODevice*
                            10000, // ms -- Technically should be 30ms per spec
                            3,     // retries
                            0,     // redirects
                            false, // allow gzip
                            NULL,  // login
                            bInQtThread,
                            QString() // userAgent, UPnP/1.0 very strict on
                                      // format if set
        );

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG, "SOAPClient response:\n" +
                            QString("%1\n").arg(sXml));

    // TODO handle timeout without response correctly.

    list.clear();

    QDomDocument doc;

    if (!doc.setContent(sXml, true, &sErrDesc, &nErrCode))
    {
        LOG(VB_UPNP, LOG_ERR,
            QString("SendSOAPRequest( %1 ) - Invalid response from %2")
                .arg(sMethod).arg(url.toString()) + 
            QString("%1: %2").arg(nErrCode).arg(sErrDesc));

        return xmlResult;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     =
        doc.elementsByTagNameNS(m_sNamespace, sResponseName);

    if (oNodeList.count() == 0)
    {
        // --------------------------------------------------------------
        // Must be a fault... parse it to return reason
        // --------------------------------------------------------------

        nErrCode = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorCode", 500);
        sErrDesc = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorDescription", "");
        if (sErrDesc.isEmpty())
            sErrDesc = QString("Unknown #%1").arg(nErrCode);

        QDomNode oNode  = FindNode( "Envelope/Body/Fault", doc );

        oNode = xmlResult.importNode( oNode, true );
        xmlResult.appendChild( oNode );

        return xmlResult;
    }

    QDomNode oMethod = oNodeList.item(0);
    if (oMethod.isNull())
        return xmlResult;

    QDomNode oNode = oMethod.firstChild(); 
    for (; !oNode.isNull(); oNode = oNode.nextSibling())
    {
        QDomElement e = oNode.toElement();
        if (e.isNull())
            continue;

        QString sName  = e.tagName();
        QString sValue = "";
    
        QDomText  oText = oNode.firstChild().toText();
    
        if (!oText.isNull())
            sValue = oText.nodeValue();

        list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                    QUrl::fromPercentEncoding(sValue.toUtf8()));
    }

    // Create copy of oMethod that can be used with xmlResult.

    oMethod = xmlResult.importNode( oMethod.firstChild(), true  );

    // importNode does not attach the new nodes to the document,
    // do it here.

    xmlResult.appendChild( oMethod );

    return xmlResult;
}
Exemplo n.º 25
0
QDomDocument SOAPClient::SendSOAPRequest(const QString &sMethod,
                                         QStringMap    &list,
                                         int           &nErrCode,
                                         QString       &sErrDesc)
{
    QUrl url(m_url);

    url.setPath(m_sControlPath);

    nErrCode = UPnPResult_Success;
    sErrDesc = "";

    QDomDocument xmlResult;
    if (m_sNamespace.isEmpty())
    {
        nErrCode = UPnPResult_MythTV_NoNamespaceGiven;
        sErrDesc = "No namespace given";
        return xmlResult;
    }

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------
    QHash<QByteArray, QByteArray> headers;

    headers.insert("Content-Type", "text/xml; charset=\"utf-8\"");
    QString soapHeader = QString("\"%1#%2\"").arg(m_sNamespace).arg(sMethod);
	headers.insert("SOAPACTION", soapHeader.toUtf8());
    headers.insert("User-Agent", "Mozilla/9.876 (X11; U; Linux 2.2.12-20 i686, en) "
                                 "Gecko/25250101 Netscape/5.432b1");
    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os.setCodec("UTF-8");

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope "
        " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\""
        " xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for (QStringMap::iterator it = list.begin(); it != list.end(); ++it)
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG,
        QString("SOAPClient(%1) sending:\n %2").arg(url.toString()).arg(aBuffer.constData()));

    QString sXml;

    if (!GetMythDownloadManager()->postAuth(url.toString(), &aBuffer, NULL, NULL, &headers))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("SOAPClient::SendSOAPRequest: request failed: %1")
                                         .arg(url.toString()));
    }
    else
        sXml = QString(aBuffer);

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG, "SOAPClient response:\n" +
                            QString("%1\n").arg(sXml));

    // TODO handle timeout without response correctly.

    list.clear();

    QDomDocument doc;

    if (!doc.setContent(sXml, true, &sErrDesc, &nErrCode))
    {
        LOG(VB_UPNP, LOG_ERR,
            QString("SendSOAPRequest( %1 ) - Invalid response from %2")
                .arg(sMethod).arg(url.toString()) + 
            QString("%1: %2").arg(nErrCode).arg(sErrDesc));

        return xmlResult;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     =
        doc.elementsByTagNameNS(m_sNamespace, sResponseName);

    if (oNodeList.count() == 0)
    {
        // --------------------------------------------------------------
        // Must be a fault... parse it to return reason
        // --------------------------------------------------------------

        nErrCode = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorCode", 500);
        sErrDesc = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorDescription", "");
        if (sErrDesc.isEmpty())
            sErrDesc = QString("Unknown #%1").arg(nErrCode);

        QDomNode oNode  = FindNode( "Envelope/Body/Fault", doc );

        oNode = xmlResult.importNode( oNode, true );
        xmlResult.appendChild( oNode );

        return xmlResult;
    }

    QDomNode oMethod = oNodeList.item(0);
    if (oMethod.isNull())
        return xmlResult;

    QDomNode oNode = oMethod.firstChild(); 
    for (; !oNode.isNull(); oNode = oNode.nextSibling())
    {
        QDomElement e = oNode.toElement();
        if (e.isNull())
            continue;

        QString sName  = e.tagName();
        QString sValue = "";
    
        QDomText  oText = oNode.firstChild().toText();
    
        if (!oText.isNull())
            sValue = oText.nodeValue();

        list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                    QUrl::fromPercentEncoding(sValue.toUtf8()));
    }

    // Create copy of oMethod that can be used with xmlResult.

    oMethod = xmlResult.importNode( oMethod.firstChild(), true  );

    // importNode does not attach the new nodes to the document,
    // do it here.

    xmlResult.appendChild( oMethod );

    return xmlResult;
}
QDomElement XmlElementDefinition::writeXml(QDomDocument &xml_doc) const {
	QDomElement element_elmt = xml_element_.documentElement();
	QDomNode new_node = xml_doc.importNode(element_elmt, true);
	return(new_node.toElement());
}
Exemplo n.º 27
0
void ZynAddSubFxInstrument::loadSettings( const QDomElement & _this )
{
	if( !_this.hasChildNodes() )
	{
		return;
	}

	m_portamentoModel.loadSettings( _this, "portamento" );
	m_filterFreqModel.loadSettings( _this, "filterfreq" );
	m_filterQModel.loadSettings( _this, "filterq" );
	m_bandwidthModel.loadSettings( _this, "bandwidth" );
	m_fmGainModel.loadSettings( _this, "fmgain" );
	m_resCenterFreqModel.loadSettings( _this, "rescenterfreq" );
	m_resBandwidthModel.loadSettings( _this, "resbandwidth" );
	m_forwardMidiCcModel.loadSettings( _this, "forwardmidicc" );

	QDomDocument doc;
	QDomElement data = _this.firstChildElement( "ZynAddSubFX-data" );
	if( data.isNull() )
	{
		data = _this.firstChildElement();
	}
	doc.appendChild( doc.importNode( data, true ) );

	QTemporaryFile tf;
	tf.setAutoRemove( false );
	if( tf.open() )
	{
		QByteArray a = doc.toString( 0 ).toUtf8();
		tf.write( a );
		tf.flush();

		const std::string fn = QSTR_TO_STDSTR( QDir::toNativeSeparators( tf.fileName() ) );
		m_pluginMutex.lock();
		if( m_remotePlugin )
		{
			m_remotePlugin->lock();
			m_remotePlugin->sendMessage( RemotePlugin::message( IdLoadSettingsFromFile ).addString( fn ) );
			m_remotePlugin->waitForMessage( IdLoadSettingsFromFile );
			m_remotePlugin->unlock();
		}
		else
		{
			m_plugin->loadXML( fn );
		}
		m_pluginMutex.unlock();

		m_modifiedControllers.clear();
		foreach( const QString & c, _this.attribute( "modifiedcontrollers" ).split( ',' ) )
		{
			if( !c.isEmpty() )
			{
				switch( c.toInt() )
				{
					case C_portamento: updatePortamento(); break;
					case C_filtercutoff: updateFilterFreq(); break;
					case C_filterq: updateFilterQ(); break;
					case C_bandwidth: updateBandwidth(); break;
					case C_fmamp: updateFmGain(); break;
					case C_resonance_center: updateResCenterFreq(); break;
					case C_resonance_bandwidth: updateResBandwidth(); break;
					default:
						break;
				}
			}
		}

		emit settingsChanged();
	}
Exemplo n.º 28
0
QgsVectorLayer* QgsRemoteOWSBuilder::sosLayer( const QDomElement& remoteOWSElem, const QString& url, const QString& layerName, QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  //url for sos provider is: "url=... method=... xml=....
  QString method = remoteOWSElem.attribute( QStringLiteral( "method" ), QStringLiteral( "POST" ) ); //possible GET/POST/SOAP

  //search for <LayerSensorObservationConstraints> node that is sibling of remoteOSW element
  //parent element of <remoteOWS> (normally <UserLayer>)
  QDomElement parentElem = remoteOWSElem.parentNode().toElement();
  if ( parentElem.isNull() )
  {
    return nullptr;
  }


  //Root element of the request (can be 'GetObservation' or 'GetObservationById' at the moment, probably also 'GetFeatureOfInterest' or 'GetFeatureOfInterestTime' in the future)
  QDomElement requestRootElem;

  QDomNodeList getObservationNodeList = parentElem.elementsByTagName( QStringLiteral( "GetObservation" ) );
  if ( !getObservationNodeList.isEmpty() )
  {
    requestRootElem = getObservationNodeList.at( 0 ).toElement();
  }
  else //GetObservationById?
  {
    QDomNodeList getObservationByIdNodeList = parentElem.elementsByTagName( QStringLiteral( "GetObservationById" ) );
    if ( !getObservationByIdNodeList.isEmpty() )
    {
      requestRootElem = getObservationByIdNodeList.at( 0 ).toElement();
    }
  }

  if ( requestRootElem.isNull() )
  {
    return nullptr;
  }

  QDomDocument requestDoc;
  QDomNode newDocRoot = requestDoc.importNode( requestRootElem, true );
  requestDoc.appendChild( newDocRoot );

  QString providerUrl = "url=" + url + " method=" + method + " xml=" + requestDoc.toString();

  //check if layer is already in cache
  QgsVectorLayer* sosLayer = nullptr;
  if ( allowCaching )
  {
    sosLayer = qobject_cast<QgsVectorLayer*>( QgsMSLayerCache::instance()->searchLayer( providerUrl, layerName ) );
    if ( sosLayer )
    {
      return sosLayer;
    }
  }

  sosLayer = new QgsVectorLayer( providerUrl, QStringLiteral( "Sensor layer" ), QStringLiteral( "SOS" ) );

  if ( !sosLayer->isValid() )
  {
    delete sosLayer;
    return nullptr;
  }
  else
  {
    if ( allowCaching )
    {
      QgsMSLayerCache::instance()->insertLayer( providerUrl, layerName, sosLayer );
    }
    else
    {
      layersToRemove.push_back( sosLayer );
    }
  }
  return sosLayer;
}