コード例 #1
0
void
DeferredParameterEdit::setXML()
{
  QDomNode tmpNode = tmpParentNode_.firstChild();

  // no edit -> nothing to be done
  if (!modified_)
    return;

  // delete entry if edit field is empty
  if (tmpNode.isNull() || 
      tmpNode.firstChild().isNull()) {

    if (!node_.isNull()) {
      parentNode_.removeChild(node_);
      delete item_;
    }
    else {
      modified_ = false;
    }
    return;
  }  

  // crete a node if necessary
  if (node_.isNull()) {

    MIRO_ASSERT(!parentNode_.ownerDocument().isNull());
    QDomElement e = parentNode_.ownerDocument().createElement(XML_TAG_PARAMETER);

    e.setAttribute(XML_ATTRIBUTE_KEY, name());
    node_ = parentNode_.appendChild(e);

    MIRO_ASSERT(!node_.isNull());
  }

  //--------------------------------------
  // replace node by new content

  // remember the predecessor
  QListViewItem * pre = NULL;
  if (item_) {
    QListViewItem * parent = item_->listViewItem()->parent();
    if (parent != NULL) {
      pre = parent->firstChild();
      while (pre != NULL) {
	if (pre->nextSibling() == item_->listViewItem())
	  break;
	pre = pre->nextSibling();
      }
    }
    // delete the current content
    delete item_;
  }

  // replace the xml subtree
  QDomNode node = tmpNode.cloneNode();
  node_.parentNode().replaceChild(node, node_);
  node_ = node;

  // reconstruct the listview if available
  if (parentItem_) {
    item_ = NULL;
    QString typeName = parameter_.type_;
    if (type_ == NESTED_PARAMETER) {
      Miro::CFG::Type const * const parameterType =
	ConfigFile::instance()->description().getType(typeName);
      
      if (parameterType == NULL) {
	throw QString("Parameter description for " + typeName +
		      " not found.\nCheck whether the relevant description file is loaded.");
      }
    
      item_ = new CompoundParameter(*parameterType,
				    node,
				    parentItem_->listViewItem(), pre,
				    parentItem_, name());
    }
    else if (type_ == VECTOR ||
	     type_ == SET) {
      item_ = new ParameterList(parameter_, 
				node,
				parentItem_->listViewItem(), pre,
				parentItem_, name());
    }
    if (item_ != NULL)
      dynamic_cast<ParameterXML *>(item_)->init();
  }
}
コード例 #2
0
void SmugTalker::parseResponseLogin(const QByteArray& data)
{
    int errCode = -1;
    QString errMsg;

    emit signalLoginProgress(3);
    QDomDocument doc("login");
    if (!doc.setContent(data))
        return;

    kDebug() << "Parse Login response:" << endl << data;

    QDomElement e = doc.documentElement();
    for (QDomNode node = e.firstChild();
         !node.isNull();
         node = node.nextSibling())
    {
        if (!node.isElement())
            continue;

        e = node.toElement();

        if (e.tagName() == "Login")
        {
            m_user.accountType = e.attribute("AccountType");
            m_user.fileSizeLimit = e.attribute("FileSizeLimit").toInt();

            for (QDomNode nodeL = e.firstChild();
                 !nodeL.isNull();
                 nodeL = nodeL.nextSibling())
            {
                if (!nodeL.isElement())
                    continue;

                e = nodeL.toElement();

                if (e.tagName() == "Session")
                {
                    m_sessionID = e.attribute("id");
                }
                else if (e.tagName() == "User")
                {
                    m_user.nickName = e.attribute("NickName");
                    m_user.displayName = e.attribute("DisplayName");
                }
            }
            errCode = 0;
        }
        else if (e.tagName() == "err")
        {
            errCode = e.attribute("code").toInt();
            errMsg  = e.attribute("msg");
            kDebug() << "Error:" << errCode << errMsg;
        }
    }

    emit signalLoginProgress(4);
    if (errCode != 0) // if login failed, reset user properties
    {
        m_sessionID.clear();
        m_user.clear();
    }

    emit signalBusy(false);
    emit signalLoginDone(errCode, errorToText(errCode, errMsg));
}
コード例 #3
0
void SmugTalker::parseResponseListPhotos(const QByteArray& data)
{
    int errCode = -1;
    QString errMsg;
    QDomDocument doc("images.get");
    if (!doc.setContent(data))
        return;

    kDebug() << "Parse Photos response:" << endl << data;

    QList <SmugPhoto> photosList;
    QDomElement e = doc.documentElement();

    for (QDomNode node = e.firstChild();
         !node.isNull();
         node = node.nextSibling())
    {
        if (!node.isElement())
            continue;

        e = node.toElement();

        if (e.tagName() == "Images")
        {
            for (QDomNode nodeP = e.firstChild();
                 !nodeP.isNull();
                 nodeP = nodeP.nextSibling())
            {
                if (!nodeP.isElement())
                    continue;

                e = nodeP.toElement();

                if (e.tagName() == "Image")
                {
                    SmugPhoto photo;
                    photo.id = e.attribute("id").toInt();
                    photo.key = e.attribute("Key");
                    photo.caption = htmlToText(e.attribute("Caption"));
                    photo.keywords = htmlToText(e.attribute("Keywords"));
                    photo.thumbURL = e.attribute("ThumbURL");
                    // try to get largest size available
                    if (e.hasAttribute("Video1280URL"))
                        photo.originalURL = e.attribute("Video1280URL");
                    else if (e.hasAttribute("Video960URL"))
                        photo.originalURL = e.attribute("Video960URL");
                    else if (e.hasAttribute("Video640URL"))
                        photo.originalURL = e.attribute("Video640URL");
                    else if (e.hasAttribute("Video320URL"))
                        photo.originalURL = e.attribute("Video320URL");
                    else if (e.hasAttribute("OriginalURL"))
                        photo.originalURL = e.attribute("OriginalURL");
                    else if (e.hasAttribute("X3LargeURL"))
                        photo.originalURL = e.attribute("X3LargeURL");
                    else if (e.hasAttribute("X2LargeURL"))
                        photo.originalURL = e.attribute("X2LargeURL");
                    else if (e.hasAttribute("XLargeURL"))
                        photo.originalURL = e.attribute("XLargeURL");
                    else if (e.hasAttribute("LargeURL"))
                        photo.originalURL = e.attribute("LargeURL");
                    else if (e.hasAttribute("MediumURL"))
                        photo.originalURL = e.attribute("MediumURL");
                    else if (e.hasAttribute("SmallURL"))
                        photo.originalURL = e.attribute("SmallURL");
                    photosList.append(photo);
                }
            }
            errCode = 0;
        }
        else if (e.tagName() == "err")
        {
            errCode = e.attribute("code").toInt();
            errMsg  = e.attribute("msg");
            kDebug() << "Error:" << errCode << errMsg;
        }
    }

    if (errCode == 15)  // 15: empty list
        errCode = 0;
    emit signalBusy(false);
    emit signalListPhotosDone(errCode, errorToText(errCode, errMsg),
                              photosList);
}
コード例 #4
0
ファイル: bookmarks.cpp プロジェクト: mkhoeini/Saaghar
void Bookmarks::updateDomElement(QTreeWidgetItem* item, int column)
{
    QDomElement element = m_domElementForItem.value(item);
    if (!element.isNull()) {
        if (column == 0) {
            QDomElement oldTitleElement = element.firstChildElement("title");
            QDomElement newTitleElement = m_domDocument.createElement("title");

            QDomText newTitleText = m_domDocument.createTextNode(item->text(0));
            newTitleElement.appendChild(newTitleText);

            element.replaceChild(newTitleElement, oldTitleElement);
        }
        else {
            if (element.tagName() == "bookmark") {
                QDomElement oldDescElement = element.firstChildElement("desc");
                QDomElement newDescElement = m_domDocument.createElement("desc");
                QDomText newDesc = m_domDocument.createTextNode(item->text(1));//setAttribute("href", item->text(1));
                newDescElement.appendChild(newDesc);
                element.replaceChild(newDescElement, oldDescElement);
                element.setAttribute("href", item->data(1, Qt::UserRole).toString());
            }
        }
    }
}
コード例 #5
0
ファイル: bookmarks.cpp プロジェクト: mkhoeini/Saaghar
bool Bookmarks::updateBookmarkState(const QString &type, const QVariant &data, bool state)
{
    if (type == "Verses" || type == tr("Verses")) {
        QDomElement verseNode = findChildNode("folder", "Verses");
        if (verseNode.isNull()) {
            QDomElement root = m_domDocument.createElement("folder");
            QDomElement child = m_domDocument.createElement("title");
            QDomText newTitleText = m_domDocument.createTextNode(tr("Verses"));
            root.setAttribute("folded", "no");
            child.appendChild(newTitleText);
            root.appendChild(child);
            m_domDocument.documentElement().appendChild(root);
            verseNode = root;
            parseFolderElement(root);
        }

        QTreeWidgetItem* parentItem = m_domElementForItem.key(verseNode);
        //REMOVE OPERATION
        if (!state) {
            int countOfChildren = parentItem->childCount();
            int numOfDel = 0;
            bool allMatchedRemoved = true;
            for (int i = 0; i < countOfChildren; ++i) {
                QTreeWidgetItem* childItem = parentItem->child(i);
                if (!childItem) {
                    continue;
                }

                if (childItem->data(0, Qt::UserRole).toString() == data.toStringList().at(0) + "|" + data.toStringList().at(1)) {
                    ++numOfDel;

                    if (unBookmarkItem(childItem)) {
                        --i; //because one of children was deleted
                        --countOfChildren;
                    }
                    else {
                        allMatchedRemoved = false;
                    }
                }
            }

            //allMatchedRemoved is false when at least one of
            // matched items are not deleted!!
            return allMatchedRemoved;
        }

        QDomElement bookmark = m_domDocument.createElement("bookmark");
        QDomElement bookmarkTitle = m_domDocument.createElement("title");
        QDomElement bookmarkDescription = m_domDocument.createElement("desc");
        QDomElement bookmarkInfo = m_domDocument.createElement("info");
        QDomElement infoMetaData = m_domDocument.createElement("metadata");

        infoMetaData.setAttribute("owner", "http://saaghar.pozh.org");
        QDomText bookmarkSaagharMetadata = m_domDocument.createTextNode(data.toStringList().at(0) + "|" + data.toStringList().at(1));
        infoMetaData.appendChild(bookmarkSaagharMetadata);
        bookmarkInfo.appendChild(infoMetaData);
        bookmark.appendChild(bookmarkTitle);
        bookmark.appendChild(bookmarkDescription);
        bookmark.appendChild(bookmarkInfo);
        verseNode.appendChild(bookmark);

        qDebug() << data << state;
        QDomElement firstChild = m_domDocument.documentElement().firstChildElement("folder");
        firstChild.text();
        QTreeWidgetItem* item = createItem(bookmark, parentItem);
        item->setIcon(0, m_bookmarkIcon);

        QString title = data.toStringList().at(2);
        item->setText(0, title);
        item->setToolTip(0, title);
        item->setData(0, Qt::UserRole, data.toStringList().at(0) + "|" + data.toStringList().at(1));
        item->setData(1, Qt::UserRole, data.toStringList().at(3));
        if (data.toStringList().size() == 5) {
            item->setText(1, data.toStringList().at(4));
            item->setToolTip(1, data.toStringList().at(4));
        }

        if (parentItem->childCount() == 1) {
            resizeColumnToContents(0);
            resizeColumnToContents(1);
        }

        return true;
    }

    //an unknown type!!
    return false;
}
コード例 #6
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( "method", "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 0;
  }


  //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( "GetObservation" );
  if ( getObservationNodeList.size() > 0 )
  {
    requestRootElem = getObservationNodeList.at( 0 ).toElement();
  }
  else //GetObservationById?
  {
    QDomNodeList getObservationByIdNodeList = parentElem.elementsByTagName( "GetObservationById" );
    if ( getObservationByIdNodeList.size() > 0 )
    {
      requestRootElem = getObservationByIdNodeList.at( 0 ).toElement();
    }
  }

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

  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 = 0;
  if ( allowCaching )
  {
    sosLayer = dynamic_cast<QgsVectorLayer*>( QgsMSLayerCache::instance()->searchLayer( providerUrl, layerName ) );
    if ( sosLayer )
    {
      return sosLayer;
    }
  }

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

  if ( !sosLayer->isValid() )
  {
    delete sosLayer;
    return 0;
  }
  else
  {
    if ( allowCaching )
    {
      QgsMSLayerCache::instance()->insertLayer( providerUrl, layerName, sosLayer );
    }
    else
    {
      layersToRemove.push_back( sosLayer );
    }
  }
  return sosLayer;
}
コード例 #7
0
ファイル: CDiagramItem.cpp プロジェクト: jetcodes/JetMind
void CDiagramItem::toXml(QDomElement &n)
{
	QMetaObject				*meta = NULL;
  QMetaProperty			prop;
	QDomDocument			doc;
	QDomElement				ext, childNode;
	QList<QByteArray>		props;
  QStringList				filtersOut, filtersIn;
	CDiagramSerializable	*inst = NULL;

    filtersIn = filterProperties();
    filtersOut  << "width"
                << "height"
                << "x"
                << "y"
                << "z"
                << "pos"
                << "size"
                << "parent"
                << "effect"
                << "children"
                << "layout"
                << "palette";

	doc = n.ownerDocument();
	ext = doc.createElement( QString("ext") );
	childNode = doc.createElement( QString("children") );

	n.setAttribute( QString("type"), interType());
	n.setAttribute( QString("category"), category() );
	n.setAttribute( QString("name"), name() );
	n.setAttribute( QString("libCategory"), libraryCategory() );
	n.setAttribute( QString("libName"), libraryName() );
	n.setAttribute( QString("id"), QString::number(id()) );
	
	meta = const_cast<QMetaObject*>(metaObject());
	for (int i = 0; i < meta->propertyCount(); ++i)
	{
		QString		propName;
		QByteArray	b;
		QDataStream s(&b, QIODevice::WriteOnly);

		prop = meta->property(i);
		propName = QString(prop.name());
        if (filtersIn.isEmpty())
        {
            if (filtersOut.contains(propName, Qt::CaseInsensitive) || prop.userType() == 0)
            {
                continue;
            }
        }
        else
        {
            if (!filtersIn.contains(propName, Qt::CaseInsensitive))
            {
                continue;
            }
        }
		
		if (prop.isValid() && prop.isReadable())
		{
			s <<  prop.read(this);
			QDomElement	e = doc.createElement(QString("property"));
			e.setAttribute( QString("name"), QString(prop.name()) );
			e.setAttribute( QString("type"), QString(prop.typeName()) );
			e.appendChild( doc.createTextNode( QString(b.toBase64() ) ) );
			n.appendChild(e);
			// qDebug() << "save->name:" << prop.name() << " value:" << prop.read(this);
		}
	}
	
	props = dynamicPropertyNames();
	for (int i = 0; i < props.length(); ++i)
	{
		inst = RS_PROPERTY(props.at(i).constData());
		// inst = property(props.at(i).constData()).value<CDiagramSerializable*>();
		if (inst)
		{
			QDomElement	 c = doc.createElement(QString("child"));
			c.setAttribute( QString("dynamicProperty"), QString(props.at(i).constData()) );
			inst->toXml(c);
			childNode.appendChild(c);
		}
	}
	n.appendChild(childNode);

	extToXml( ext );
	n.appendChild( ext );
}
コード例 #8
0
ファイル: mesas.cpp プロジェクト: trifolio6/Bulmages
void Mesa::importXML(const QString val) {

    QDomDocument doc ( "mydocument" );

    if ( !doc.setContent ( val ) ) {
	
        return;
    } // end if

    QDomElement docElem = doc.documentElement();
    QDomElement principal = docElem.firstChildElement ( "IMAGEN" );
    m_filename = principal.text();

    QDomElement nombre = docElem.firstChildElement ( "NOMBRE" );
    m_nombreMesa = nombre.text();

    QDomElement pantalla = docElem.firstChildElement ( "PANTALLA" );
    m_pantalla = pantalla.text();
    
    
    QDomElement posx = docElem.firstChildElement ( "POSX" );
    QDomElement posy = docElem.firstChildElement ( "POSY" );

    QDomElement xscale = docElem.firstChildElement ( "XSCALE" );
    QDomElement yscale = docElem.firstChildElement ( "YSCALE" );
    m_XScale = xscale.text().toInt();
    m_YScale = yscale.text().toInt();
    setGeometry(posx.text().toInt(),posy.text().toInt(),m_XScale+1 , m_YScale+1 );
    setFixedSize(m_XScale+10 ,m_YScale+10);

    repaint();
}
コード例 #9
0
ファイル: qtgradientutils.cpp プロジェクト: fluxer/katie
static QDomElement saveGradient(QDomDocument &doc, const QGradient &gradient)
{
    QDomElement gradElem = doc.createElement(QLatin1String("gradientData"));

    const QGradient::Type type = gradient.type();
    gradElem.setAttribute(QLatin1String("type"), gradientTypeToString(type));
    gradElem.setAttribute(QLatin1String("spread"), gradientSpreadToString(gradient.spread()));
    gradElem.setAttribute(QLatin1String("coordinateMode"), gradientCoordinateModeToString(gradient.coordinateMode()));

    QGradientStops stops = gradient.stops();
    QVectorIterator<QGradientStop > it(stops);
    while (it.hasNext())
        gradElem.appendChild(saveGradientStop(doc, it.next()));

    if (type == QGradient::LinearGradient) {
        const QLinearGradient &g = *static_cast<const QLinearGradient *>(&gradient);
        gradElem.setAttribute(QLatin1String("startX"), QString::number(g.start().x()));
        gradElem.setAttribute(QLatin1String("startY"), QString::number(g.start().y()));
        gradElem.setAttribute(QLatin1String("endX"), QString::number(g.finalStop().x()));
        gradElem.setAttribute(QLatin1String("endY"), QString::number(g.finalStop().y()));
    } else if (type == QGradient::RadialGradient) {
        const QRadialGradient &g = *static_cast<const QRadialGradient *>(&gradient);
        gradElem.setAttribute(QLatin1String("centerX"), QString::number(g.center().x()));
        gradElem.setAttribute(QLatin1String("centerY"), QString::number(g.center().y()));
        gradElem.setAttribute(QLatin1String("focalX"), QString::number(g.focalPoint().x()));
        gradElem.setAttribute(QLatin1String("focalY"), QString::number(g.focalPoint().y()));
        gradElem.setAttribute(QLatin1String("radius"), QString::number(g.radius()));
    } else if (type == QGradient::ConicalGradient) {
        const QConicalGradient &g = *static_cast<const QConicalGradient*>(&gradient);
        gradElem.setAttribute(QLatin1String("centerX"), QString::number(g.center().x()));
        gradElem.setAttribute(QLatin1String("centerY"), QString::number(g.center().y()));
        gradElem.setAttribute(QLatin1String("angle"), QString::number(g.angle()));
    }

    return gradElem;
}
コード例 #10
0
int LoadController::exec()
{
    clean();
    QFile zeus (filename());
    if(!zeus.open(QIODevice::ReadOnly))
    {
        return -1;
    }

    QDomDocument hera;
    if(!hera.setContent(&zeus))
    {
        return -2;
    }

    QDomElement athena = hera.documentElement();
    QDomNodeList hermes = athena.elementsByTagName("user");

    for(int appolon = 0; appolon < hermes.size(); appolon++)
    {
        QDomElement gaia = hermes.at(appolon).toElement();
        UserSPointer ares = UserController::user(cypher(gaia.elementsByTagName("username").at(0).toElement().text(), 57));
        if(ares)
            ares->setType((User::UserType)cypher(gaia.elementsByTagName("type").at(0).toElement().text(), 95).toInt());
    }


    hermes = athena.elementsByTagName("category");

    for(int apollon = 0; apollon < hermes.size(); apollon++)
    {
        if(hermes.at(apollon).parentNode().toElement().tagName() != "subCategory")
        {
            CategorySPointer ares(new Category);
            QDomElement aphrodite = hermes.at(apollon).toElement();
            ares->load(aphrodite);
            if(!categories().contains(ares->name()))
                addCategory(ares);
        }
    }
    hermes = athena.elementsByTagName("entry");

    for(int apollon = 0; apollon < hermes.size(); apollon++)
    {
        if(hermes.at(apollon).parentNode().toElement().tagName() != "subMedia")
        {
            MediaSPointer ares(new Media);
            QDomElement aphrodite = hermes.at(apollon).toElement();
            ares->load(aphrodite, AbstractController::categories());
            if(!medias().contains(qMakePair(ares->category()->name(),ares->name())))
            {
                ares->category()->addAssociations(ares);
                addMedia(ares);
            }
        }
    }

    zeus.close();

    return 0;
}
コード例 #11
0
ファイル: mesas.cpp プロジェクト: trifolio6/Bulmages
void DistroMesas::importXML(const QString val) {
  QFile file ( g_confpr->value( CONF_DIR_USER ) + "distromesas_" + mainCompany()->dbName() + ".cfn" );

    if (file.exists()) {
        if ( !file.open ( QIODevice::ReadOnly ) ) {
            
            return;
        } // end if
        QString result (file.readAll());
        file.close(); 


    QDomDocument doc ( "mydocument" );

    if ( !doc.setContent ( result ) ) {
	
        return;
    } // end if

    QDomElement docElem = doc.documentElement();
    QDomElement principal = docElem.firstChildElement ( "BACKGROUND" );
    m_background = principal.text();

    principal = docElem.firstChildElement ( "ESCALA" );
    g_escala = principal.text().toInt();


    QDomNodeList nodos = docElem.elementsByTagName ( "MESA" );
    int i = 0;
    while (i < nodos.count() ) {
        QDomNode ventana = nodos.item ( i++ );
        QDomElement e1 = ventana.toElement(); /// try to convert the node to an element.
        if ( !e1.isNull() ) { /// the node was really an element.
            QString nodoText = e1.text();
            /// Pasamos el XML a texto para poder procesarlo como tal.
            QString result;
            QTextStream stream ( &result );
            ventana.save(stream,5);

            Mesa *mesa = new Mesa((BtCompany *) mainCompany(), mui_widget);
            mesa->importXML(result);
	    
	    if (! m_listapantallas.contains(mesa->m_pantalla)) {
	        if (m_pantallaactual == "") {
		    m_pantallaactual = mesa->m_pantalla;
		} // end if
		m_listapantallas.append(mesa->m_pantalla);
		QToolButton *but = new QToolButton(this);
		but->setObjectName("p_"+mesa->m_pantalla);
		but->setText(mesa->m_pantalla);
		but->setMinimumHeight(42);
		but->setMinimumWidth(42);
		but->setCheckable(TRUE);
		mui_espaciopantallas->addWidget(but);
		connect(but, SIGNAL(clicked()), this, SLOT(cambiarPantalla()));
	    } // end if
	    if (mesa->m_pantalla == m_pantallaactual) 
		mesa->show();

        } // end if
    } // end while

} // end if

}
コード例 #12
0
ファイル: ellipse.cpp プロジェクト: OpenIndy/OpenIndy-Core
/*!
 * \brief Ellipse::fromOpenIndyXML
 * \param xmlElem
 * \return
 */
bool Ellipse::fromOpenIndyXML(QDomElement &xmlElem){

    bool result = Geometry::fromOpenIndyXML(xmlElem);

    if(result){

        //set ellipse attributes
        QDomElement a = xmlElem.firstChildElement("a");
        QDomElement b = xmlElem.firstChildElement("b");
        QDomElement semiMajorAxis = xmlElem.firstChildElement("semiMajorAxis");
        QDomElement normal = xmlElem.firstChildElement("spatialDirection");
        QDomElement center = xmlElem.firstChildElement("coordinates");

        if(a.isNull() || b.isNull() || semiMajorAxis.isNull() || normal.isNull() || center.isNull()
                || !a.hasAttribute("value") || !b.hasAttribute("value") || semiMajorAxis.hasAttribute("i")
                || !semiMajorAxis.hasAttribute("j") || !semiMajorAxis.hasAttribute("k")
                || !normal.hasAttribute("i") || normal.hasAttribute("j") || normal.hasAttribute("k")
                || !center.hasAttribute("x") || !center.hasAttribute("y") || !center.hasAttribute("z")){
            return false;
        }

        this->a = a.attribute("value").toDouble();
        this->b = b.attribute("value").toDouble();
        this->semiMajorAxis.setVector(semiMajorAxis.attribute("i").toDouble(),
                                      semiMajorAxis.attribute("j").toDouble(),
                                      semiMajorAxis.attribute("k").toDouble());
        this->normal.setVector(normal.attribute("i").toDouble(),
                               normal.attribute("j").toDouble(),
                               normal.attribute("k").toDouble());
        this->center.setVector(center.attribute("x").toDouble(),
                               center.attribute("y").toDouble(),
                               center.attribute("z").toDouble());

    }

    return result;

}
コード例 #13
0
ファイル: ellipse.cpp プロジェクト: OpenIndy/OpenIndy-Core
/*!
 * \brief Ellipse::toOpenIndyXML
 * \param xmlDoc
 * \return
 */
QDomElement Ellipse::toOpenIndyXML(QDomDocument &xmlDoc) const{

    QDomElement ellipse = Geometry::toOpenIndyXML(xmlDoc);

    if(ellipse.isNull()){
        return ellipse;
    }

    ellipse.setAttribute("type", getGeometryTypeName(eEllipseGeometry));

    //set semi-major axis length
    QDomElement a = xmlDoc.createElement("a");
    if(this->isSolved || this->isNominal){
        a.setAttribute("value", this->a);
    }else{
        a.setAttribute("value", 0.0);
    }
    ellipse.appendChild(a);

    //set semi-minor axis length
    QDomElement b = xmlDoc.createElement("b");
    if(this->isSolved || this->isNominal){
        b.setAttribute("value", this->b);
    }else{
        b.setAttribute("value", 0.0);
    }
    ellipse.appendChild(b);

    //set semi-major axis direction
    QDomElement semiMajorAxis = xmlDoc.createElement("semiMajorAxis");
    if(this->isSolved || this->isNominal){
        semiMajorAxis.setAttribute("i", this->semiMajorAxis.getVector().getAt(0));
        semiMajorAxis.setAttribute("j", this->semiMajorAxis.getVector().getAt(1));
        semiMajorAxis.setAttribute("k", this->semiMajorAxis.getVector().getAt(2));
    }else{
        semiMajorAxis.setAttribute("i", 0.0);
        semiMajorAxis.setAttribute("j", 0.0);
        semiMajorAxis.setAttribute("k", 0.0);
    }
    ellipse.appendChild(semiMajorAxis);

    return ellipse;

}
コード例 #14
0
void DistributionTables::build(const std::string& BasePath,
                               const std::string& SourcesFileName, const std::string& DistributionFileName)
{
  SourcesTable.clear();
  UnitsTable.clear();


  // Sources file

  QDomDocument Doc;
  QDomElement Root;

  std::string SourcesFilePath = BasePath+"/"+SourcesFileName;


  QFile File(QString(SourcesFilePath.c_str()));
  if (!File.open(QIODevice::ReadOnly))
  {
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
        "Error opening " + SourcesFilePath);
  }

  bool Parsed = Doc.setContent(&File);
  File.close();


  if (Parsed)
  {
    Root = Doc.documentElement();

    if (!Root.isNull())
    {
      if (Root.tagName() == QString("openfluid"))
      {
        for(QDomElement CurrNode = Root.firstChildElement(); !CurrNode.isNull();
            CurrNode = CurrNode.nextSiblingElement())
        {
          if (CurrNode.tagName() == QString("datasources"))
          {
            for(QDomElement CurrNode2 = CurrNode.firstChildElement(); !CurrNode2.isNull();
                CurrNode2 = CurrNode2.nextSiblingElement())
            {
              if (CurrNode2.tagName() == QString("filesource"))
              {
                QString xmlID = CurrNode2.attributeNode(QString("ID")).value();
                QString xmlFile = CurrNode2.attributeNode(QString("file")).value();

                if (!xmlID.isNull() && !xmlFile.isNull())
                {
                  SourcesTable[xmlID.toStdString()] = BasePath + "/" + xmlFile.toStdString();
                }
              }
            }
          }
        }
      }
      else
        throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                  "Cannot find <openfluid> tag in sources file " +
                                                  SourcesFilePath);
    }
    else
      throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,"Wrong formatted sources file " +
                                                SourcesFilePath);
  }
  else
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,"Cannot open sources file " +
                                              SourcesFilePath);


  // Units distribution file

  long UnitID;
  std::string DataSrcID;

  ColumnTextParser DistriFileParser("%");

  std::string DistributionFilePath = BasePath+"/"+DistributionFileName;

  if (openfluid::tools::Filesystem::isFile(DistributionFilePath))
  {
    if (DistriFileParser.loadFromFile(DistributionFilePath) &&
        DistriFileParser.getColsCount() == 2 &&
        DistriFileParser.getLinesCount() >0)
    {
      for (unsigned int i=0;i<DistriFileParser.getLinesCount();i++)
      {
        if (DistriFileParser.getLongValue(i,0,&UnitID) && DistriFileParser.getStringValue(i,1,&DataSrcID))
        {
          if (SourcesTable.find(DataSrcID) != SourcesTable.end())
            UnitsTable[UnitID] = DataSrcID;
          else
            throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                      "Error in distribution file " + DistributionFilePath +
                                                      ", data source ID not found");
        }
        else
          throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                    "Error in distribution file " + DistributionFilePath +
                                                    ", format error");
      }
    }
    else
      throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                                "Error in distribution file " + DistributionFilePath +
                                                ", file not found or format error");
  }
  else
    throw openfluid::base::FrameworkException(OPENFLUID_CODE_LOCATION,
                                              "Distribution file " + DistributionFilePath + " not found");

}
コード例 #15
0
bool Syntaxer::loadSyntax(const QString &filename)
 {
	QFile file(filename);

	QString errorStr;
	int errorLine;
	int errorColumn;

	QDomDocument domDocument;
	if (!domDocument.setContent(&file, true, &errorStr, &errorLine, &errorColumn)) {
		return false;
	}

	QDomElement root = domDocument.documentElement();
	if (root.isNull()) return false;
	if (root.tagName() != "language") return false;

	QDomElement highlighting = root.firstChildElement("highlighting");
	if (highlighting.isNull()) return false;

	QDomElement general = root.firstChildElement("general");
	if (general.isNull()) return false;

	QDomElement contexts = highlighting.firstChildElement("contexts");
	if (contexts.isNull()) return false;

	m_hlCStringChar = false;
	QDomElement context = contexts.firstChildElement("context");
	while (!context.isNull()) {
		if (context.attribute("attribute").compare("Normal Text") == 0) {
			m_stringDelimiter = getStringDelimiter(context);
			initListsToFormats(context);
		}
		else if (context.attribute("attribute").compare("String") == 0) {
			QDomElement HlCStringChar = context.firstChildElement("HlCStringChar");
			if (!HlCStringChar.isNull()) {
				m_hlCStringChar = true;
			}
		}
		context = context.nextSiblingElement("context");
	}

    m_canProgram = root.attribute("canProgram", "").compare("true", Qt::CaseInsensitive) == 0;
	m_name = root.attribute("name");
	QStringList extensions = root.attribute("extensions").split(";", QString::SkipEmptyParts);
	if (extensions.count() > 0) {
		m_extensionString = m_name + " " + QObject::tr("files") + " (";
		foreach (QString ext, extensions) {
			m_extensionString += ext + " ";
			int ix = ext.indexOf(".");
			if (ix > 0) {
				ext.remove(0, ix);
			}
			m_extensions.append(ext);
		}
コード例 #16
0
ファイル: qtgradientutils.cpp プロジェクト: fluxer/katie
static QGradient loadGradient(const QDomElement &elem)
{
    if (elem.tagName() != QLatin1String("gradientData"))
        return QLinearGradient();

    const QGradient::Type type = stringToGradientType(elem.attribute(QLatin1String("type")));
    const QGradient::Spread spread = stringToGradientSpread(elem.attribute(QLatin1String("spread")));
    const QGradient::CoordinateMode mode = stringToGradientCoordinateMode(elem.attribute(QLatin1String("coordinateMode")));

    QGradient gradient = QLinearGradient();

    if (type == QGradient::LinearGradient) {
        QLinearGradient g;
        g.setStart(elem.attribute(QLatin1String("startX")).toDouble(), elem.attribute(QLatin1String("startY")).toDouble());
        g.setFinalStop(elem.attribute(QLatin1String("endX")).toDouble(), elem.attribute(QLatin1String("endY")).toDouble());
        gradient = g;
    } else if (type == QGradient::RadialGradient) {
        QRadialGradient g;
        g.setCenter(elem.attribute(QLatin1String("centerX")).toDouble(), elem.attribute(QLatin1String("centerY")).toDouble());
        g.setFocalPoint(elem.attribute(QLatin1String("focalX")).toDouble(), elem.attribute(QLatin1String("focalY")).toDouble());
        g.setRadius(elem.attribute(QLatin1String("radius")).toDouble());
        gradient = g;
    } else if (type == QGradient::ConicalGradient) {
        QConicalGradient g;
        g.setCenter(elem.attribute(QLatin1String("centerX")).toDouble(), elem.attribute(QLatin1String("centerY")).toDouble());
        g.setAngle(elem.attribute(QLatin1String("angle")).toDouble());
        gradient = g;
    }

    QDomElement stopElem = elem.firstChildElement();
    while (!stopElem.isNull()) {
        QGradientStop stop = loadGradientStop(stopElem);

        gradient.setColorAt(stop.first, stop.second);

        stopElem = stopElem.nextSiblingElement();
    }

    gradient.setSpread(spread);
    gradient.setCoordinateMode(mode);

    return gradient;
}
コード例 #17
0
void TreeEditor::slotLoadedData()
 {
    QDomDocument doc;
    doc.setContent(m_reply->readAll());
    QDomElement root = doc.documentElement();
    QDomElement content = root.firstChildElement("InternetContent");
    QDomElement grabber = content.firstChildElement("grabber");

    while (!grabber.isNull())
    {
        QString title, author, image, description, type, commandline;
        double version;
        bool search = false;
        bool tree = false;

        title = grabber.firstChildElement("name").text();
        commandline = grabber.firstChildElement("command").text();
        author = grabber.firstChildElement("author").text();
        image = grabber.firstChildElement("thumbnail").text();
        type = grabber.firstChildElement("type").text();
        description = grabber.firstChildElement("description").text();
        version = grabber.firstChildElement("version").text().toDouble();

        QString treestring = grabber.firstChildElement("tree").text();

        if (!treestring.isEmpty() && (treestring.toLower() == "true" ||
            treestring.toLower() == "yes" || treestring == "1"))
            tree = true;

        QString searchstring = grabber.firstChildElement("search").text();

        if (!searchstring.isEmpty() && (searchstring.toLower() == "true" ||
            searchstring.toLower() == "yes" || searchstring == "1"))
            search = true;

        if (type.toLower() == "video" && tree)
        {
            LOG(VB_GENERAL, LOG_INFO,
                QString("Found Browseable Source %1...").arg(title));
            m_grabberList.append(new GrabberScript(title, image, VIDEO_FILE, author,
                        search, tree, description, commandline, version));
        }

        grabber = grabber.nextSiblingElement("grabber");
    }

    parsedData();
 }
コード例 #18
0
void Browser::load(void)
{
  std::cout << qPrintable(tr("Loading data")) << std::endl;

  QFile file( CFG_FILE );
  QDir::setCurrent( CFG_DIR );

  if( !file.open( QIODevice::ReadOnly ) )
    {
      QString strErr = QObject::tr("Error: Can't open config file !\n"
                                   "This is probably the first time\n"
                                   "you run this application.\n"
                                   "So just click ok.\n"
                                   "Next time, this message shouldn't appear.\n"
                                  );
      std::cerr << " " << qPrintable(strErr) << std::endl;
      QMessageBox::warning(0,
                           QObject::tr("Loading config file"),
                           strErr
                          );
      file.close();

      /* Default values */
      default_interval = 5000;
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%200"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%201"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%202"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%203"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%204"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%205"));
/*

<!DOCTYPE BrowserML PUBLIC '-//CELLES//DTD Browser 0.1 //EN' 'http://www.celles.net/dtd/browser/browser_data-0_1.dtd'>
<!--This file describe data for a very light browser for dynamic display-->
<!--http://www.celles.net/wiki/Browser-->
<browser timer="5000">
 <url>http://127.0.0.1/test/0.html</url>
 <url>http://127.0.0.1/test/1.html</url>
 <url>http://127.0.0.1/test/2.html</url>
 <url>http://127.0.0.1/test/3.html</url>
 <url>http://127.0.0.1/test/4.html</url>
 <url>http://127.0.0.1/test/5.html</url>
</browser>

http://www.google.fr/search?hl=fr&q=test
http://www.google.fr/search?hl=fr&amp;q=test

*/

      //save(); // save default values
      return;
    }

  std::cout << " " << qPrintable(tr("Loading...")) << std::endl;
  //std::cout << " ToDo" << std::endl;

  /* validating document using dtd : not possible easily using Qt4 */

  /* En test */
  QDomDocument doc;
  QString errorStr;
  int errorLine;
  int errorColumn;

  /* looking for malformed xml file */
  if( !doc.setContent( &file, true, &errorStr, &errorLine, &errorColumn ) )
    {
      QString strErr = QObject::tr("Parse error at line %1, "
                                   "column %2:\n%3")
                       .arg(errorLine)
                       .arg(errorColumn)
                       .arg(errorStr);
      std::cerr << " " << qPrintable(strErr) << std::endl;
      QMessageBox::warning(0,
                           QObject::tr("DOM Parser"),
                           strErr
                          );
      file.close();
      return;
    }

  QDomElement root = doc.documentElement();

  /* looking for the root name 'ocdata' */
  //std::cout << "root = " << qPrintable(root.tagName()) << std::endl;
  if (root.tagName() != QLatin1String("browser"))
    {
      QString strErr = QObject::tr("Document should begin with <browser> and stop with </browser>");
      std::cerr << " " << qPrintable(strErr) << std::endl;
      QMessageBox::warning(0,
                           QObject::tr("DOM Parser"),
                           strErr
                          );

      file.close();
      return;
    }

  /* parsing file */

  QDomNode node = root.firstChild();
  while ( !node.isNull() )
    {
      default_interval = root.attribute(QLatin1String("timer")).toInt();

      QDomElement element = node.toElement();

      if (element.tagName() == QLatin1String("url"))
        {
          std::cout << qPrintable(tr(" ")) << qPrintable(tr("Parsing"))  << qPrintable(tr(" ")) << qPrintable(element.tagName()) << std::endl;
          std::cout << "  " << qPrintable(element.text()) << std::endl;
         // QString
          QUrl url = QUrl(element.text());
          //QUrl url = QUrl(element.text(),QUrl::TolerantMode);
          //QString str = QString("http://www.google.fr/search?hl=fr&q=test");
          //QUrl url = QUrl(str);
          //url.ParsingMode=QUrl::TolerantMode;
          url_list.append(url);
          //url_list.append(element.text());
          //url_list.append(QUrl::fromEncoded(element.text().toStdString()));
        }
      else
        {
          QString strErr = QObject::tr("Error: Undefined element tagName");
          std::cerr << qPrintable(tr(" ")) << qPrintable(strErr) << std::endl;
          QMessageBox::warning(0,
                               QObject::tr("DOM Parser"),
                               strErr
                              );
        }

      node = node.nextSibling();
    }

  file.close();

  std::cout << qPrintable(tr(" ")) << qPrintable(tr("Data loaded")) << std::endl;

  if (url_list.count()==0) {
    //url_list.append(QUrl("about:blank"));
    url_list.append(QUrl("http://www.google.fr"));
  }

}
コード例 #19
0
QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer(
  const QDomElement& elem,
  const QString& layerName,
  QList<QTemporaryFile*>& filesToRemove,
  QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  if ( elem.isNull() )
  {
    return 0;
  }

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

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

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

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

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


  if ( serviceName == "WFS" )
  {
    //support for old format where type is explicitly given and not part of url
    QString tname = onlineResourceElement.attribute( "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 ), "WFS" );
    if ( result->isValid() )
    {
      if ( allowCaching )
      {
        QgsMSLayerCache::instance()->insertLayer( url, layerName, result );
      }
      else
      {
        layersToRemove.push_back( result );
      }
    }
  }
  else if ( serviceName == "WMS" )
  {
    result = wmsLayerFromUrl( url, layerName, layersToRemove, allowCaching );
  }
  else if ( serviceName == "WCS" )
  {
    QgsDebugMsg( "Trying to get WCS layer" );
    result = wcsLayerFromUrl( url, layerName, filesToRemove, layersToRemove );
  }
  else if ( serviceName == "SOS" )
  {
    result = sosLayer( elem, url, layerName, layersToRemove, allowCaching );
  }

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

  return result;
}
コード例 #20
0
void QgsRendererRangeV2::toSld( QDomDocument &doc, QDomElement &element, QgsStringMap props ) const
{
  if ( !mSymbol || props.value( "attribute", "" ).isEmpty() )
    return;

  QString attrName = props[ "attribute" ];

  QDomElement ruleElem = doc.createElement( "se:Rule" );
  element.appendChild( ruleElem );

  QDomElement nameElem = doc.createElement( "se:Name" );
  nameElem.appendChild( doc.createTextNode( mLabel ) );
  ruleElem.appendChild( nameElem );

  QDomElement descrElem = doc.createElement( "se:Description" );
  QDomElement titleElem = doc.createElement( "se:Title" );
  QString descrStr = QString( "range: %1 - %2" ).arg( mLowerValue ).arg( mUpperValue );
  titleElem.appendChild( doc.createTextNode( !mLabel.isEmpty() ? mLabel : descrStr ) );
  descrElem.appendChild( titleElem );
  ruleElem.appendChild( descrElem );

  // create the ogc:Filter for the range
  QDomElement filterElem = doc.createElement( "ogc:Filter" );
  QString filterFunc = QString( "%1 > %2 AND %1 <= %3" )
                       .arg( attrName.replace( "\"", "\"\"" ) )
                       .arg( mLowerValue ).arg( mUpperValue );
  QgsSymbolLayerV2Utils::createFunctionElement( doc, filterElem, filterFunc );
  ruleElem.appendChild( filterElem );

  mSymbol->toSld( doc, ruleElem, props );
}
コード例 #21
0
ファイル: CDiagramItem.cpp プロジェクト: jetcodes/JetMind
void CDiagramItem::fromXml(const QDomElement &n)
{
	QDomElement				e;
	QString					type, name, prop;
	QObject					*obj = NULL;
	QMetaProperty			pro;
	QMetaObject				*meta = NULL;
	CDiagramSerializable	*serialItem = NULL;

	setLibraryCategory(n.attribute( QString("libCategory") ) );
	setLibraryName(n.attribute( QString("libName") ) );
	setCategory(n.attribute( QString("category") ) );
	setName(n.attribute( QString("name") ) );
	setId(n.attribute( QString("id") ).toInt() );

	obj = dynamic_cast<QObject*>(this);
	e = n.firstChildElement( QString("property") );
	while (!e.isNull())
	{
		QByteArray	b;

		name = e.attribute( QString("name") );
		type = e.attribute( QString("type") );

		b = QByteArray::fromBase64( e.text().toAscii() );
		QDataStream s(&b, QIODevice::ReadOnly);
		QVariant	value(s);
		if (value.convert( QVariant::nameToType( qPrintable(type) ) ) )
		{
			meta = const_cast<QMetaObject*>( obj->metaObject() );
			pro = meta->property( meta->indexOfProperty(qPrintable(name)) );
			if (pro.isWritable())
				obj->setProperty(qPrintable(name), value);
		}
		e = e.nextSiblingElement( QString("property") );
	}
	
	e = n.firstChildElement( QString("children") );
	if (!e.isNull())
	{
		e = e.firstChildElement( QString("child") );
		while (!e.isNull())
		{
			prop = e.attribute( QString("dynamicProperty") );
			serialItem = RS_PROPERTY(prop.toAscii().constData());
			if (serialItem)
				serialItem->fromXml(e);
			e = e.nextSiblingElement(QString("child"));
		}
	}
	
	e = n.firstChildElement( QString("ext" ) );
	extFromXml(e);
}
コード例 #22
0
QgsFeatureRendererV2* QgsGraduatedSymbolRendererV2::create( QDomElement& element )
{
  QDomElement symbolsElem = element.firstChildElement( "symbols" );
  if ( symbolsElem.isNull() )
    return NULL;

  QDomElement rangesElem = element.firstChildElement( "ranges" );
  if ( rangesElem.isNull() )
    return NULL;

  QgsSymbolV2Map symbolMap = QgsSymbolLayerV2Utils::loadSymbols( symbolsElem );
  QgsRangeList ranges;

  QDomElement rangeElem = rangesElem.firstChildElement();
  while ( !rangeElem.isNull() )
  {
    if ( rangeElem.tagName() == "range" )
    {
      double lowerValue = rangeElem.attribute( "lower" ).toDouble();
      double upperValue = rangeElem.attribute( "upper" ).toDouble();
      QString symbolName = rangeElem.attribute( "symbol" );
      QString label = rangeElem.attribute( "label" );
      if ( symbolMap.contains( symbolName ) )
      {
        QgsSymbolV2* symbol = symbolMap.take( symbolName );
        ranges.append( QgsRendererRangeV2( lowerValue, upperValue, symbol, label ) );
      }
    }
    rangeElem = rangeElem.nextSiblingElement();
  }

  QString attrName = element.attribute( "attr" );

  QgsGraduatedSymbolRendererV2* r = new QgsGraduatedSymbolRendererV2( attrName, ranges );

  // delete symbols if there are any more
  QgsSymbolLayerV2Utils::clearSymbolMap( symbolMap );

  // try to load source symbol (optional)
  QDomElement sourceSymbolElem = element.firstChildElement( "source-symbol" );
  if ( !sourceSymbolElem.isNull() )
  {
    QgsSymbolV2Map sourceSymbolMap = QgsSymbolLayerV2Utils::loadSymbols( sourceSymbolElem );
    if ( sourceSymbolMap.contains( "0" ) )
    {
      r->setSourceSymbol( sourceSymbolMap.take( "0" ) );
    }
    QgsSymbolLayerV2Utils::clearSymbolMap( sourceSymbolMap );
  }

  // try to load color ramp (optional)
  QDomElement sourceColorRampElem = element.firstChildElement( "colorramp" );
  if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( "name" ) == "[source]" )
  {
    r->setSourceColorRamp( QgsSymbolLayerV2Utils::loadColorRamp( sourceColorRampElem ) );
  }

  // try to load mode
  QDomElement modeElem = element.firstChildElement( "mode" );
  if ( !modeElem.isNull() )
  {
    QString modeString = modeElem.attribute( "name" );
    if ( modeString == "equal" )
      r->setMode( EqualInterval );
    else if ( modeString == "quantile" )
      r->setMode( Quantile );
    else if ( modeString == "jenks" )
      r->setMode( Jenks );
    else if ( modeString == "stddev" )
      r->setMode( StdDev );
    else if ( modeString == "pretty" )
      r->setMode( Pretty );
  }

  QDomElement rotationElem = element.firstChildElement( "rotation" );
  if ( !rotationElem.isNull() )
    r->setRotationField( rotationElem.attribute( "field" ) );

  QDomElement sizeScaleElem = element.firstChildElement( "sizescale" );
  if ( !sizeScaleElem.isNull() )
  {
    r->setSizeScaleField( sizeScaleElem.attribute( "field" ) );
    r->setScaleMethod( QgsSymbolLayerV2Utils::decodeScaleMethod( sizeScaleElem.attribute( "scalemethod" ) ) );
  }

  // TODO: symbol levels
  return r;
}
コード例 #23
0
ファイル: bookmarks.cpp プロジェクト: mkhoeini/Saaghar
void Bookmarks::parseFolderElement(const QDomElement &element,
                                   QTreeWidgetItem* parentItem, const QString &/*elementID*/)
{
    QDomElement parentElement(element);
    QString id = "";
    if (parentElement.tagName() == "folder") {
        //old files that their 'folder' tag don't use 'id' attribute
        // just contain 'folder' tag of type 'Verses'!
        id = parentElement.attribute("id", "Verses");
        parentElement.setAttribute("id", id);
    }

    QTreeWidgetItem* item = createItem(parentElement, parentItem, id);

    QString title;
    if (id == "Verses") {
        title = tr("Verses");
    }
    else {
        title = element.firstChildElement("title").text();
    }
    if (title.isEmpty()) {
        title = QObject::tr("Folder");
    }

    item->setIcon(0, m_folderIcon);
    item->setText(0, title);
    item->setToolTip(0, title);

    bool folded = (parentElement.attribute("folded") != "no");
    setItemExpanded(item, !folded);

    QDomElement child = parentElement.firstChildElement();
    while (!child.isNull()) {
        if (child.tagName() == "folder") {
//TODO: we can save labguage within a 'metadata' tag of this 'folder'
//          //update node title by new loaded translation
            QString id = child.attribute("id");
            QString title = child.firstChildElement("title").text();

            if (id.isEmpty()) {
                //old files that their 'folder' tags don't use 'id' attribute just contain 'folder' tags of type 'Verses'!
                id = "Verses";
                title = tr(title.toLocal8Bit().data());
                QDomElement oldTitleElement = child.firstChildElement("title");
                QDomElement newTitleElement = m_domDocument.createElement("title");
                QDomText newTitleText = m_domDocument.createTextNode(tr("Verses"));
                newTitleElement.appendChild(newTitleText);

                child.replaceChild(newTitleElement, oldTitleElement);
                child.setAttribute("id", "Verses");
            }
            parseFolderElement(child, item, id);
        }
        else if (child.tagName() == "bookmark") {
            QTreeWidgetItem* childItem = createItem(child, item);

            QString title = child.firstChildElement("title").text();
            if (title.isEmpty()) {
                title = QObject::tr("Folder");
            }

            QDomElement infoChild = child.firstChildElement("info");
            QDomElement metaData = infoChild.firstChildElement("metadata");
            while (!metaData.isNull()) {
                QString owner = metaData.attribute("owner");
                if (owner == "http://saaghar.pozh.org") {
                    break;
                }
                metaData = metaData.nextSiblingElement("metadata");
            }
            if (!metaData.isNull() && metaData.attribute("owner") == "http://saaghar.pozh.org") {
                childItem->setData(0, Qt::UserRole, metaData.text());
            }
            else {
                qDebug() << "This DOM-NODE SHOULD deleted--->" << title;
            }
            //href data URL data
            childItem->setData(1, Qt::UserRole, child.attribute("href", "http://saaghar.pozh.org"));
            childItem->setIcon(0, m_bookmarkIcon);
            childItem->setText(0, title);
            childItem->setToolTip(0, title);
            childItem->setText(1, child.firstChildElement("desc").text());
            childItem->setToolTip(1, child.firstChildElement("desc").text());
        }
        else if (child.tagName() == "separator") {
            QTreeWidgetItem* childItem = createItem(child, item);
            childItem->setFlags(item->flags() & ~(Qt::ItemIsSelectable | Qt::ItemIsEditable));
            childItem->setText(0, QString(30, 0xB7));
        }
        child = child.nextSiblingElement();
    }
}
コード例 #24
0
QDomElement QgsGraduatedSymbolRendererV2::save( QDomDocument& doc )
{
  QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME );
  rendererElem.setAttribute( "type", "graduatedSymbol" );
  rendererElem.setAttribute( "symbollevels", ( mUsingSymbolLevels ? "1" : "0" ) );
  rendererElem.setAttribute( "attr", mAttrName );

  // ranges
  int i = 0;
  QgsSymbolV2Map symbols;
  QDomElement rangesElem = doc.createElement( "ranges" );
  QgsRangeList::const_iterator it = mRanges.constBegin();
  for ( ; it != mRanges.constEnd(); it++ )
  {
    const QgsRendererRangeV2& range = *it;
    QString symbolName = QString::number( i );
    symbols.insert( symbolName, range.symbol() );

    QDomElement rangeElem = doc.createElement( "range" );
    rangeElem.setAttribute( "lower", QString::number( range.lowerValue(), 'f' ) );
    rangeElem.setAttribute( "upper", QString::number( range.upperValue(), 'f' ) );
    rangeElem.setAttribute( "symbol", symbolName );
    rangeElem.setAttribute( "label", range.label() );
    rangesElem.appendChild( rangeElem );
    i++;
  }

  rendererElem.appendChild( rangesElem );

  // save symbols
  QDomElement symbolsElem = QgsSymbolLayerV2Utils::saveSymbols( symbols, "symbols", doc );
  rendererElem.appendChild( symbolsElem );

  // save source symbol
  if ( mSourceSymbol )
  {
    QgsSymbolV2Map sourceSymbols;
    sourceSymbols.insert( "0", mSourceSymbol );
    QDomElement sourceSymbolElem = QgsSymbolLayerV2Utils::saveSymbols( sourceSymbols, "source-symbol", doc );
    rendererElem.appendChild( sourceSymbolElem );
  }

  // save source color ramp
  if ( mSourceColorRamp )
  {
    QDomElement colorRampElem = QgsSymbolLayerV2Utils::saveColorRamp( "[source]", mSourceColorRamp, doc );
    rendererElem.appendChild( colorRampElem );
  }

  // save mode
  QString modeString;
  if ( mMode == EqualInterval )
    modeString = "equal";
  else if ( mMode == Quantile )
    modeString = "quantile";
  else if ( mMode == Jenks )
    modeString = "jenks";
  else if ( mMode == StdDev )
    modeString = "stddev";
  else if ( mMode == Pretty )
    modeString = "pretty";
  if ( !modeString.isEmpty() )
  {
    QDomElement modeElem = doc.createElement( "mode" );
    modeElem.setAttribute( "name", modeString );
    rendererElem.appendChild( modeElem );
  }

  QDomElement rotationElem = doc.createElement( "rotation" );
  rotationElem.setAttribute( "field", mRotationField );
  rendererElem.appendChild( rotationElem );

  QDomElement sizeScaleElem = doc.createElement( "sizescale" );
  sizeScaleElem.setAttribute( "field", mSizeScaleField );
  sizeScaleElem.setAttribute( "scalemethod", QgsSymbolLayerV2Utils::encodeScaleMethod( mScaleMethod ) );
  rendererElem.appendChild( sizeScaleElem );

  return rendererElem;
}
コード例 #25
0
void SmugTalker::parseResponseListCategories(const QByteArray& data)
{
    int errCode = -1;
    QString errMsg;
    QDomDocument doc("categories.get");
    if (!doc.setContent(data))
        return;

    kDebug() << "Parse Categories response:" << endl << data;

    QList <SmugCategory> categoriesList;
    QDomElement e = doc.documentElement();

    for (QDomNode node = e.firstChild();
         !node.isNull();
         node = node.nextSibling())
    {
        if (!node.isElement())
            continue;

        e = node.toElement();

        if (e.tagName() == "Categories")
        {
            for (QDomNode nodeC = e.firstChild();
                 !nodeC.isNull();
                 nodeC = nodeC.nextSibling())
            {
                if (!nodeC.isElement())
                    continue;

                QDomElement e = nodeC.toElement();

                if (e.tagName() == "Category")
                {
                    SmugCategory category;
                    category.id = e.attribute("id").toInt();
                    category.name = htmlToText(e.attribute("Title")); // Name in 1.2.1
                    categoriesList.append(category);
                }
            }
            errCode = 0;
        }
        else if (e.tagName() == "err")
        {
            errCode = e.attribute("code").toInt();
            errMsg  = e.attribute("msg");
            kDebug() << "Error:" << errCode << errMsg;
        }
    }

    if (errCode == 15)  // 15: empty list
        errCode = 0;

    emit signalBusy(false);
    emit signalListCategoriesDone(errCode, errorToText(errCode, errMsg),
                                  categoriesList);
}
コード例 #26
0
ファイル: gameengine.cpp プロジェクト: tsampareek/BridgeGame
void GameEngine::playMatch(QString match)
{
    QDomDocument doc;
    doc.setContent(match);

    QDomElement matchElem = doc.documentElement();
    QDomElement board = matchElem.elementsByTagName("board").at(0).toElement();
    QMetaObject::invokeMethod(qmlItem, "setBoard",
                              Q_ARG(QVariant, board.attribute("dealer").toInt()),
                              Q_ARG(QVariant, board.attribute("vulnerable").toInt()),
                              Q_ARG(QVariant, matchElem.attribute("round").toInt()+1),
                              Q_ARG(QVariant, matchElem.attribute("boardNo").toInt()+1),
                              Q_ARG(QVariant, matchElem.attribute("ns_pair").toInt()+1),
                              Q_ARG(QVariant, matchElem.attribute("ew_pair").toInt()+1));

    QDomNodeList allCards = board.elementsByTagName("cards");
    for (int i=0; i<allCards.size(); i++) {
        QDomElement elem = allCards.at(i).toElement();
        int player = elem.attribute("player").toInt();
        QStringList cards = elem.text().split(QChar(','));
        if (m_talker->player() == player) {
            m_talker->setCards(elem.text());
        }
        QMetaObject::invokeMethod(qmlItem, "showCards",
                                  Q_ARG(QVariant, player),
                                  Q_ARG(QVariant, cards));
    }

    QDomNodeList moves = matchElem.elementsByTagName("item");
    for (int i=0; i<moves.size(); i++) {
        m_moveItems << XMLEngine::parseXml(moves.at(i).toElement());
    }

    QMetaObject::invokeMethod(qmlItem, "setAnimated", Q_ARG(QVariant, false));
    connect(&m_playTimer, SIGNAL(timeout()), this, SLOT(playListedMoves()));
    m_playTimer.start(50);
}
コード例 #27
0
void SmugTalker::parseResponseListAlbums(const QByteArray& data)
{
    int errCode = -1;
    QString errMsg;
    QDomDocument doc("albums.get");
    if (!doc.setContent(data))
        return;

    kDebug() << "Parse Albums response:" << endl << data;

    QList <SmugAlbum> albumsList;
    QDomElement e = doc.documentElement();
    for (QDomNode node = e.firstChild();
         !node.isNull();
         node = node.nextSibling())
    {
        if (!node.isElement())
            continue;

        e = node.toElement();

        if (e.tagName() == "Albums")
        {
            for (QDomNode nodeA = e.firstChild();
                 !nodeA.isNull();
                 nodeA = nodeA.nextSibling())
            {
                if (!nodeA.isElement())
                    continue;

                e = nodeA.toElement();

                if (e.tagName() == "Album")
                {
                    SmugAlbum album;
                    album.id = e.attribute("id").toInt();
                    album.key = e.attribute("Key");
                    album.title = htmlToText(e.attribute("Title"));
                    album.description = htmlToText(e.attribute("Description"));
                    album.keywords = htmlToText(e.attribute("Keywords"));
                    album.isPublic = e.attribute("Public") == "1";
                    album.password = htmlToText(e.attribute("Password"));
                    album.passwordHint = htmlToText(e.attribute("PasswordHint"));
                    album.imageCount = e.attribute("ImageCount").toInt();

                    for (QDomNode nodeC = e.firstChild();
                         !nodeC.isNull();
                         nodeC = node.nextSibling())
                    {
                        if (!nodeC.isElement())
                            continue;

                        e = nodeC.toElement();

                        if (e.tagName() == "Category")
                        {
                            album.categoryID = e.attribute("id").toInt();
                            album.category = htmlToText(e.attribute("Name"));
                        }
                        else if (e.tagName() == "SubCategory")
                        {
                            album.subCategoryID = e.attribute("id").toInt();
                            album.subCategory = htmlToText(e.attribute("Name"));
                        }
                    }
                    albumsList.append(album);
                }
            }
            errCode = 0;
        }
        else if (e.tagName() == "err")
        {
            errCode = e.attribute("code").toInt();
            errMsg = e.attribute("msg");
            kDebug() << "Error:" << errCode << errMsg;
        }
    }

    if (errCode == 15)  // 15: empty list
        errCode = 0;

    emit signalBusy(false);
    emit signalListAlbumsDone(errCode, errorToText(errCode, errMsg),
                              albumsList);
}
コード例 #28
0
static PyObject *meth_QDomElement_setAttribute(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        const QString * a0;
        int a0State = 0;
        const QString * a1;
        int a1State = 0;
        QDomElement *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "BJ1J1", &sipSelf, sipType_QDomElement, &sipCpp, sipType_QString,&a0, &a0State, sipType_QString,&a1, &a1State))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->setAttribute(*a0,*a1);
            Py_END_ALLOW_THREADS
            sipReleaseType(const_cast<QString *>(a0),sipType_QString,a0State);
            sipReleaseType(const_cast<QString *>(a1),sipType_QString,a1State);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    {
        const QString * a0;
        int a0State = 0;
        qlonglong a1;
        QDomElement *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "BJ1n", &sipSelf, sipType_QDomElement, &sipCpp, sipType_QString,&a0, &a0State, &a1))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->setAttribute(*a0,a1);
            Py_END_ALLOW_THREADS
            sipReleaseType(const_cast<QString *>(a0),sipType_QString,a0State);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    {
        const QString * a0;
        int a0State = 0;
        qulonglong a1;
        QDomElement *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "BJ1o", &sipSelf, sipType_QDomElement, &sipCpp, sipType_QString,&a0, &a0State, &a1))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->setAttribute(*a0,a1);
            Py_END_ALLOW_THREADS
            sipReleaseType(const_cast<QString *>(a0),sipType_QString,a0State);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    {
        const QString * a0;
        int a0State = 0;
        double a1;
        QDomElement *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "BJ1Xd", &sipSelf, sipType_QDomElement, &sipCpp, sipType_QString,&a0, &a0State, &a1))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->setAttribute(*a0,a1);
            Py_END_ALLOW_THREADS
            sipReleaseType(const_cast<QString *>(a0),sipType_QString,a0State);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    {
        const QString * a0;
        int a0State = 0;
        int a1;
        QDomElement *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "BJ1i", &sipSelf, sipType_QDomElement, &sipCpp, sipType_QString,&a0, &a0State, &a1))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->setAttribute(*a0,a1);
            Py_END_ALLOW_THREADS
            sipReleaseType(const_cast<QString *>(a0),sipType_QString,a0State);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QDomElement, sipName_setAttribute, NULL);

    return NULL;
}
コード例 #29
0
void SmugTalker::parseResponseListAlbumTmpl(const QByteArray& data)
{
    int errCode = -1;
    QString errMsg;
    QDomDocument doc("albumtemplates.get");
    if (!doc.setContent(data))
        return;

    kDebug() << "Parse AlbumTemplates response:" << endl << data;

    QList<SmugAlbumTmpl> albumTList;
    QDomElement e = doc.documentElement();
    for (QDomNode node = e.firstChild();
         !node.isNull();
         node = node.nextSibling())
    {
        if (!node.isElement())
            continue;

        e = node.toElement();

        if (e.tagName() == "AlbumTemplates")
        {
            for (QDomNode nodeT = e.firstChild();
                 !nodeT.isNull();
                 nodeT = nodeT.nextSibling())
            {
                if (!nodeT.isElement())
                    continue;

                QDomElement e = nodeT.toElement();

                if (e.tagName() == "AlbumTemplate")
                {
                    SmugAlbumTmpl tmpl;
                    tmpl.id = e.attribute("id").toInt();
                    tmpl.name = htmlToText(e.attribute("AlbumTemplateName"));
                    tmpl.isPublic = e.attribute("Public") == "1";
                    tmpl.password = htmlToText(e.attribute("Password"));
                    tmpl.passwordHint = htmlToText(e.attribute("PasswordHint"));
                    albumTList.append(tmpl);
                }
            }
            errCode = 0;
        }
        else if (e.tagName() == "err")
        {
            errCode = e.attribute("code").toInt();
            errMsg  = e.attribute("msg");
            kDebug() << "Error:" << errCode << errMsg;
        }
    }

    if (errCode == 15)  // 15: empty list
        errCode = 0;

    emit signalBusy(false);
    emit signalListAlbumTmplDone(errCode, errorToText(errCode, errMsg),
                                 albumTList);
}
コード例 #30
0
bool TrussResultsManager::parseExecutionResults ( 
                                              Plugin::ExecutionResult exRes,
                                              QString& errMsg )
{
    QDomDocument doc;

    if ( exRes.status == Plugin::InternalErrStatus ) {
        errMsg = exRes.data;
        return false;       
    }

    if ( ! doc.setContent( exRes.data ) ) {
        errMsg = QString( tr("Wrong XML format of the results") );
        return false;
    }

    QDomElement pluginResElem = doc.documentElement();
    if ( pluginResElem.isNull() ) {
        errMsg = QString( tr("Wrong XML format of the results") );
        return false;
    }

    if ( ! pluginResElem.hasAttribute( "trussUUID" ) ) {
        errMsg = QString( tr("Wrong XML format of the results: truss UUID wasn't set") );
        return false;
    }
    
    QString trussID = pluginResElem.attribute( "trussUUID" );

    WindowList windows = windowMng.getTrussUnitWindowList();
    bool found = false;
    TrussUnitWindow* w = 0;
    foreach ( w, windows )
        if ( w->getUUID() == trussID ) {
            found = true;
            break;
        }

    if ( ! found ) {
        errMsg = QString( tr("Truss with the given UUID wasn't found") );
        return false;
    }

    // Create new solution results
    TrussSolutionResults* newTrussResults = &createSolutionResults();
    PluginResults& pluginRes = newTrussResults->createPluginResults();

    // Reading results XML
    try { pluginRes.loadAttributesFromXML( pluginResElem, false ); }
    catch ( ... ) {
        // Remove if there was error while reading XML
        removeSolutionResults( *newTrussResults );
        
        errMsg = QString( tr("Error while reading XML of the results") );
        return false;
    }

    // Remove old results
    TrussSolutionResults* trussResults = getResultsForTrussUnit( trussID );
    if ( trussResults )
        removeSolutionResults( *trussResults );

    newTrussResults->setTrussUnit( trussID );
    w->setCalculatedStatus( true );
    
    return true;
}