Esempio n. 1
0
QString Soap::xpath(const QDomNode& node, const QString &expr)
{
//  if(m_model == canonicaltree)
//  {
//      //QString provider = m_soap->xpath(node, "/SOAP-ENC:Array/provider");
//      expr = expr.section("/", 2);
//      // FIXME: Array handling for Canonical Tree Structures?
//      kDebug() << "EXPR " << expr;
//  }

    QDomNode n = node;
    const QStringList explist = expr.split('/', QString::SkipEmptyParts);
    for (QStringList::const_iterator it = explist.begin(); it != explist.end(); ++it) {
        QDomElement el = n.toElement();
        QDomNodeList l = el.elementsByTagName((*it));
        if (!l.size()) {
            return QString();
        }
        n = l.item(0);
    }
    QString s = n.toElement().text();
    return s;
}
Esempio n. 2
0
void UiConverter::traverse(QDomNode node, QDomDocument *doc)
{
    if (node.isNull())
        return;

    QDomElement element = node.toElement();
    if (!element.isNull()) {
        if (element.nodeName() == QLatin1String("ui"))
            fixUiNode(element, doc);
        else if (element.nodeName() == QLatin1String("set"))
            fixSetNode(element, doc);
        else if (element.nodeName() == QLatin1String("enum"))
            fixEnumNode(element, doc);
        else if (element.nodeName() == QLatin1String("connection"))
            fixConnectionNode(element, doc);
        else if (element.nodeName() == QLatin1String("widget"))
            fixWidgetNode(element, doc);
    }

    QDomNodeList list = node.childNodes();
    for (int i=0; i<list.size(); ++i)
        traverse(list.at(i), doc);
}
Esempio n. 3
0
void QgsEditorWidgetRegistry::readMapLayer( QgsMapLayer* mapLayer, const QDomElement& layerElem )
{
  if ( mapLayer->type() != QgsMapLayer::VectorLayer )
  {
    return;
  }

  QgsVectorLayer* vectorLayer = qobject_cast<QgsVectorLayer*>( mapLayer );
  Q_ASSERT( vectorLayer );

  QDomNodeList editTypeNodes = layerElem.namedItem( "edittypes" ).childNodes();

  for ( int i = 0; i < editTypeNodes.size(); i++ )
  {
    QDomNode editTypeNode = editTypeNodes.at( i );
    QDomElement editTypeElement = editTypeNode.toElement();

    QString name = editTypeElement.attribute( "name" );

    int idx = vectorLayer->fieldNameIndex( name );
    if ( idx == -1 )
      continue;

    bool hasLegacyType;
    QgsVectorLayer::EditType editType =
      ( QgsVectorLayer::EditType ) editTypeElement.attribute( "type" ).toInt( &hasLegacyType );

    QString ewv2Type;
    QgsEditorWidgetConfig cfg;

    if ( hasLegacyType && editType != QgsVectorLayer::EditorWidgetV2 )
    {
      Q_NOWARN_DEPRECATED_PUSH
      ewv2Type = readLegacyConfig( vectorLayer, editTypeElement, cfg );
      Q_NOWARN_DEPRECATED_POP
    }
    else
Esempio n. 4
0
void NewstuffModelPrivate::updateModel()
{
    QDomNodeList items = m_root.elementsByTagName( "stuff" );
    for (int i=0 ; i < items.length(); ++i ) {
        QString const key = m_idTag == NewstuffModel::PayloadTag ? "payload" : "name";
        QDomNodeList matches = items.item( i ).toElement().elementsByTagName( key );
        if ( matches.size() == 1 ) {
            QString const value = matches.at( 0 ).toElement().text();
            bool found = false;
            for ( int j=0; j<m_items.size() && !found; ++j ) {
                NewstuffItem &item = m_items[j];
                if ( m_idTag == NewstuffModel::PayloadTag && item.m_payloadUrl.toString() == value ) {
                    item.m_registryNode = items.item( i );
                    found = true;
                }
                if ( m_idTag == NewstuffModel::NameTag && item.m_name == value ) {
                    item.m_registryNode = items.item( i );
                    found = true;
                }
            }

            if ( !found ) {
                // Not found in newstuff or newstuff not there yet
                NewstuffItem item = importNode( items.item( i ) );
                if ( m_idTag == NewstuffModel::PayloadTag ) {
                    item.m_registryNode = items.item( i );
                } else if ( m_idTag == NewstuffModel::NameTag ) {
                    item.m_registryNode = items.item( i );
                }
                m_items << item;
            }
        }
    }

    m_parent->beginResetModel();
    m_parent->endResetModel();
}
Esempio n. 5
0
bool MainWindow::LoadPersionInfo()
{
    QDomDocument doc;
    QFile file("Config/PersionInfo.xml");
    bool bl = file.open(QIODevice::ReadOnly);
    if(!bl)
    {
        return false;
    }
    if(!doc.setContent(&file))
    {
        return false;
    }

    m_perInfo.clear();
    m_names.clear();
    QDomElement root = doc.documentElement();
    if(root.hasChildNodes())
    {
        QDomNodeList keyList = root.childNodes();
        for(int i=0; i<keyList.size(); ++i)
        {
            // 键值
            QDomElement keyElem = keyList.at(i).toElement();
            QString key = keyElem.attribute("Key");
            // value值
            QDomElement valueElem = keyElem.childNodes().at(0).toElement();
            PersionInfo info;
            info.blackCount = valueElem.text().toInt();
            // 插入新节点
            m_perInfo.insert(key, info);
            m_names.push_back(key);
        }
    }
    file.close();
    return true;
}
bool QgsComposerPicture::readXML( const QDomElement& itemElem, const QDomDocument& doc )
{
  if ( itemElem.isNull() )
  {
    return false;
  }

  QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" );
  if ( composerItemList.size() > 0 )
  {
    _readXML( composerItemList.at( 0 ).toElement(), doc );
  }

  mSvgCacheUpToDate = false;
  mDefaultSvgSize = QSize( 0, 0 );
  mCachedDpi = 0;

  QString fileName = itemElem.attribute( "file" );
  setPictureFile( fileName );

  mRotation = itemElem.attribute( "rotation" ).toDouble();

  return true;
}
void QgsEmbedLayerDialog::addLegendGroupToTreeWidget( const QDomElement& groupElem, QTreeWidgetItem* parent )
{
  QDomNodeList groupChildren = groupElem.childNodes();
  QDomElement currentChildElem;

  if ( groupElem.attribute( "embedded" ) == "1" )
  {
    return;
  }

  QTreeWidgetItem* groupItem = 0;
  if ( !parent )
  {
    groupItem = new QTreeWidgetItem( mTreeWidget );
  }
  else
  {
    groupItem = new QTreeWidgetItem( parent );
  }
  groupItem->setIcon( 0, QgsApplication::getThemeIcon( "mActionFolder.png" ) );
  groupItem->setText( 0, groupElem.attribute( "name" ) );
  groupItem->setData( 0, Qt::UserRole, "group" );

  for ( int i = 0; i < groupChildren.size(); ++i )
  {
    currentChildElem = groupChildren.at( i ).toElement();
    if ( currentChildElem.tagName() == "legendlayer" )
    {
      addLegendLayerToTreeWidget( currentChildElem, groupItem );
    }
    else if ( currentChildElem.tagName() == "legendgroup" )
    {
      addLegendGroupToTreeWidget( currentChildElem, groupItem );
    }
  }
}
Esempio n. 8
0
/**
 * \brief load the definition of the patterns in this syntax
 * \param nodes the node list from which the definition of the patterns should be loaded
 * \return true on sucess, false on any error
 *
 * This function loads the definition of the patterns on this syntax from the node list passed as a parameter.
 *
 * TODO
 *   define what are patterns
 */
bool	QsvLangDef::loadPatternItems( QDomNodeList nodes )
{
	QDomNode node;
	int i, size = nodes.size();

	i = patternItems.size();

	for( i=0; i<size; i++ )
	{
		node = nodes.at( i );

		QsvEntityPatternItem e;
		if (!loadEntity( node, e )) return false;
		e.regex = node.toElement().elementsByTagName("regex").item(0).toElement().text();

		// WTF???
// 		e.regex.replace( "\\\\", "\\" );
		e.regex.replace( "\\n", "$" );
		
		patternItems << e;
	}

	return true;
}
Esempio n. 9
0
void RestWidget::parseOrderUrls(QNetworkReply *reply){

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

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

        dataOutput->setText(data);

        doc.setContent(data);

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

        for(int i = 0; i < orderNodes.size(); i++){
            xmloutput->addItem(orderNodes.at(i).toElement().text());
            orderIDs->append(orderNodes.at(i).toElement().text());
        }
        order_ptr = 0; //reset the order pointer.
    }
    QObject::disconnect(netManager2, SIGNAL(finished(QNetworkReply*)),this, SLOT(parseOrderUrls(QNetworkReply*)));
}
void CGrammarManagerFromProgram::GetCategoryDataFromXml(QDomElement& parentElement, CTreeItem* parentItem)
{
	QDomNodeList childrenNode = parentElement.childNodes();
	for (int i = 0; i < childrenNode.size(); i++)
	{
		if (childrenNode.at(i).isElement())
		{
			QDomElement childElement = childrenNode.at(i).toElement();
			if (childElement.tagName() == XML_TAG_CATEGORY)
			{
				/*创建分类模型子节点*/
				QList<QVariant> childData;
				childData << childElement.attribute(XML_ATTRIBUTE_NAME);
				CTreeItem* childItem = new CTreeItem(childData, parentItem);

				/*将子节点添加到模型中*/
				parentItem->appendChild(childItem);

				GetCategoryDataFromXml(childElement, childItem);
			}
		}

	}
}
void QgsRasterTerrainAnalysisDialog::on_mImportColorsButton_clicked()
{
  QString file = QFileDialog::getOpenFileName( 0, tr( "Import Colors and elevations from xml" ), QDir::homePath() );
  if ( file.isEmpty() )
  {
    return;
  }

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

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

  mReliefClassTreeWidget->clear();

  QDomNodeList reliefColorList = doc.elementsByTagName( "ReliefColor" );
  for ( int i = 0; i < reliefColorList.size(); ++i )
  {
    QDomElement reliefColorElem = reliefColorList.at( i ).toElement();
    QTreeWidgetItem* newItem = new QTreeWidgetItem();
    newItem->setText( 0, reliefColorElem.attribute( "MinElevation" ) );
    newItem->setText( 1, reliefColorElem.attribute( "MaxElevation" ) );
    newItem->setBackground( 2, QBrush( QColor( reliefColorElem.attribute( "red" ).toInt(), reliefColorElem.attribute( "green" ).toInt(),
                                       reliefColorElem.attribute( "blue" ).toInt() ) ) );
    mReliefClassTreeWidget->addTopLevelItem( newItem );
  }
}
Esempio n. 12
0
QList<QDomElement> QgsSLDConfigParser::findNamedLayerElements( const QString& layerName ) const
{
  QList<QDomElement> resultList;
  if ( mXMLDoc )
  {
    QDomElement sldElement = mXMLDoc->documentElement();
    if ( !sldElement.isNull() )
    {
      QDomNodeList NamedLayerList = sldElement.elementsByTagName( QStringLiteral( "NamedLayer" ) );
      for ( int i = 0; i < NamedLayerList.size(); ++i )
      {
        QDomNodeList nameList = NamedLayerList.item( i ).toElement().elementsByTagName( QStringLiteral( "Name" ) );
        if ( !nameList.isEmpty() )
        {
          if ( nameList.item( 0 ).toElement().text() == layerName )
          {
            resultList.push_back( NamedLayerList.item( i ).toElement() );
          }
        }
      }
    }
  }
  return resultList;
}
Esempio n. 13
0
QDomElement QgsSLDConfigParser::findUserLayerElement( const QString& layerName ) const
{
  QDomElement defaultResult;
  if ( mXMLDoc )
  {
    QDomElement sldElement = mXMLDoc->documentElement();
    if ( !sldElement.isNull() )
    {
      QDomNodeList UserLayerList = sldElement.elementsByTagName( QStringLiteral( "UserLayer" ) );
      for ( int i = 0; i < UserLayerList.size(); ++i )
      {
        QDomNodeList nameList = UserLayerList.item( i ).toElement().elementsByTagName( QStringLiteral( "Name" ) );
        if ( !nameList.isEmpty() )
        {
          if ( nameList.item( 0 ).toElement().text() == layerName )
          {
            return UserLayerList.item( i ).toElement();
          }
        }
      }
    }
  }
  return defaultResult;
}
Esempio n. 14
0
/*!
 * \brief TLMEditor::addInterfacesData
 * Adds the InterfacePoint tag to SubModel.
 * \param interfaces
 */
void TLMEditor::addInterfacesData(QDomElement interfaces)
{
  QDomNodeList subModelList = mXmlDocument.elementsByTagName("SubModel");
  for (int i = 0 ; i < subModelList.size() ; i++) {
    QDomElement subModel = subModelList.at(i).toElement();
    QDomElement interfaceDataElement = interfaces.firstChildElement();
    while (!interfaceDataElement.isNull()) {
      if (subModel.attribute("Name").compare(interfaceDataElement.attribute("model")) == 0
          && !existInterfaceData(subModel.attribute("Name"), interfaceDataElement.attribute("name"))) {
        QDomElement interfacePoint = mXmlDocument.createElement("InterfacePoint");
        interfacePoint.setAttribute("Name",interfaceDataElement.attribute("name"));
        interfacePoint.setAttribute("Position",interfaceDataElement.attribute("Position"));
        interfacePoint.setAttribute("Angle321",interfaceDataElement.attribute("Angle321"));
        subModel.appendChild(interfacePoint);
        mpPlainTextEdit->setPlainText(mXmlDocument.toString());

        TLMInterfacePointInfo *pTLMInterfacePointInfo;
        pTLMInterfacePointInfo = new TLMInterfacePointInfo(subModel.attribute("Name"),"shaft3" , interfaceDataElement.attribute("name"));
        getModelWidget()->getDiagramGraphicsView()->getComponentObject(subModel.attribute("Name"))->addInterfacePoint(pTLMInterfacePointInfo);
      }
      interfaceDataElement = interfaceDataElement.nextSiblingElement();
    }
  }
}
Esempio n. 15
0
    /**
     * @brief parseCmd
     * @param cmd
     * @param ns
     * @return
     *
     * 解析客户端发送的数据流
     * 解析用户发送的命令,如果是报文,直接转发,返回值为0,否则返回1, ns 中存储命名空间列表
     *开始报文的格式为
     <start>
        <namespace/>
        <namespace/>
        <namespace/>
        <appname/>
        ..
     </start>
     */
    static int     parseCmd(const QString cmd, QList<QString> &ns)
{
    int pos = 0;

    pos = cmd.indexOf(QString("<CZXP"));

    if ( pos < 0)
        return CMD_ERROR;
    pos = cmd.indexOf(QString("iq"));
    if ( pos >= 0) return CMD_NORMAL;
    pos = cmd.indexOf(QString("message"));
    if (pos >= 0) return CMD_NORMAL;
    QDomDocument  dom;
    QDomElement   root;
    //QDomNode      root;
    QDomNodeList  nslist;

    if( !dom.setContent(cmd.toUtf8()))
        return CMD_ERROR;
    //如果没有start节点则认为是正常的报文
    root = dom.firstChild().toElement();
    if ( root.isNull())
        return CMD_NORMAL;
    nslist = root.elementsByTagName(QString("namespace"));
    int sz = nslist.size();
    if ( sz  == 0 )
        return CMD_NORMAL;
    ns.clear();
    for ( pos = 0; pos < sz; ++pos)
    {
        QDomNode    node = nslist.item(pos);
        QString     value = node.lastChild().nodeValue();
        ns.push_back(value);
    }
    return CMD_START;
}
Esempio n. 16
0
QList<QDomElement> QgsServerProjectParser::setLegendGroupElementsWithLayerTree( QgsLayerTreeGroup* layerTreeGroup, const QDomElement& legendElement ) const
{
  QList<QDomElement> LegendGroupElemList;
  QList< QgsLayerTreeNode * > layerTreeGroupChildren = layerTreeGroup->children();
  QDomNodeList legendElementChildNodes = legendElement.childNodes();
  int g = 0; // index of the last child layer tree group
  for ( int i = 0; i < legendElementChildNodes.size(); ++i )
  {
    QDomNode legendElementNode = legendElementChildNodes.at( i );
    if ( !legendElementNode.isElement() )
      continue;
    QDomElement legendElement = legendElementNode.toElement();
    if ( legendElement.tagName() != "legendgroup" )
      continue;
    for ( int j = g; j < i + 1; ++j )
    {
      QgsLayerTreeNode* layerTreeNode = layerTreeGroupChildren.at( j );
      if ( layerTreeNode->nodeType() != QgsLayerTreeNode::NodeGroup )
        continue;
      QgsLayerTreeGroup* layerTreeGroup = static_cast<QgsLayerTreeGroup *>( layerTreeNode );
      if ( layerTreeGroup->name() == legendElement.attribute( "name" ) )
      {
        g = j;
        QString shortName = layerTreeGroup->customProperty( "wmsShortName" ).toString();
        if ( !shortName.isEmpty() )
          legendElement.setAttribute( "shortName", shortName );
        QString title = layerTreeGroup->customProperty( "wmsTitle" ).toString();
        if ( !title.isEmpty() )
          legendElement.setAttribute( "title", title );
        LegendGroupElemList.append( setLegendGroupElementsWithLayerTree( layerTreeGroup, legendElement ) );
      }
    }
    LegendGroupElemList.push_back( legendElement );
  }
  return LegendGroupElemList;
}
Esempio n. 17
0
void ModPlusExeCtrl::setInputVariablesXml(QDomDocument & doc, QString modelName, MOVector<Variable> *variables)
{
    QDomElement xfmi = doc.firstChildElement("fmiModelDescription");
    QDomElement oldxfmi = xfmi;

    QDomElement xModelVars = xfmi.firstChildElement("ModelVariables");
    QDomElement oldxModelVars = xModelVars;

    QDomNodeList listScalarVars = xModelVars.elementsByTagName("ScalarVariable");


    // filling map
    QMap<QString,int> mapScalarVars; //<name,index in listScalarVars>
    QMap<QDomElement,QDomElement> mapNewScalarVars; // <old node,new node>
    QDomElement curVar;
    QDomElement oldVar;
    QDomElement newVar;
    int index;
    QDomElement oldType;
    QDomElement newType;
    QString localVarName;

    // create map for index looking
    for(int i=0;i<listScalarVars.size();i++)
    {
        curVar = listScalarVars.at(i).toElement();
        mapScalarVars.insert(curVar.attribute("name"),i);
    }

    // change variables values
    for(int i=0;i<variables->size();i++)
    {
        // getting local var name (name in init file does not contain model name)
        localVarName = variables->at(i)->name(Variable::SHORT);
        if(localVarName.contains(modelName))
          localVarName = localVarName.remove(modelName+".");

        index = mapScalarVars.value(localVarName,-1);
        if(index>-1)
        {
            oldVar = listScalarVars.at(index).toElement();
            newVar = oldVar;

            oldType = newVar.firstChildElement("Real");
            if(oldType.isNull())
                oldType = newVar.firstChildElement("Integer");
            if(oldType.isNull())
                oldType = newVar.firstChildElement("Boolean");

            if(!oldType.isNull())
            {
                newType = oldType;
                newType.setAttribute("start",variables->at(i)->value().toString());
                newVar.replaceChild(newType,oldType);
                xModelVars.replaceChild(newVar,oldVar);
            }
            xModelVars.replaceChild(newVar,oldVar);
        }
    }

    // update xfmi with new vars
    xfmi.replaceChild(xModelVars,oldxModelVars);
    doc.replaceChild(xfmi,oldxfmi);
}
Esempio n. 18
0
bool QgsComposerShape::readXML( const QDomElement& itemElem, const QDomDocument& doc )
{
  mShape = QgsComposerShape::Shape( itemElem.attribute( "shapeType", "0" ).toInt() );
  mCornerRadius = itemElem.attribute( "cornerRadius", "0" ).toDouble();

  //restore general composer item properties
  QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" );
  if ( composerItemList.size() > 0 )
  {
    QDomElement composerItemElem = composerItemList.at( 0 ).toElement();

    //rotation
    if ( composerItemElem.attribute( "rotation", "0" ).toDouble() != 0 )
    {
      //check for old (pre 2.1) rotation attribute
      setItemRotation( composerItemElem.attribute( "rotation", "0" ).toDouble() );
    }

    _readXML( composerItemElem, doc );
  }

  QDomElement shapeStyleSymbolElem = itemElem.firstChildElement( "symbol" );
  if ( !shapeStyleSymbolElem.isNull() )
  {
    delete mShapeStyleSymbol;
    mShapeStyleSymbol = dynamic_cast<QgsFillSymbolV2*>( QgsSymbolLayerV2Utils::loadSymbol( shapeStyleSymbolElem ) );
  }
  else
  {
    //upgrade project file from 2.0 to use symbolV2 styling
    delete mShapeStyleSymbol;
    QgsStringMap properties;
    properties.insert( "color", QgsSymbolLayerV2Utils::encodeColor( brush().color() ) );
    if ( hasBackground() )
    {
      properties.insert( "style", "solid" );
    }
    else
    {
      properties.insert( "style", "no" );
    }
    if ( hasFrame() )
    {
      properties.insert( "style_border", "solid" );
    }
    else
    {
      properties.insert( "style_border", "no" );
    }
    properties.insert( "color_border", QgsSymbolLayerV2Utils::encodeColor( pen().color() ) );
    properties.insert( "width_border", QString::number( pen().widthF() ) );

    //for pre 2.0 projects, shape colour and outline were specified in a different element...
    QDomNodeList outlineColorList = itemElem.elementsByTagName( "OutlineColor" );
    if ( outlineColorList.size() > 0 )
    {
      QDomElement frameColorElem = outlineColorList.at( 0 ).toElement();
      bool redOk, greenOk, blueOk, alphaOk, widthOk;
      int penRed, penGreen, penBlue, penAlpha;
      double penWidth;

      penWidth = itemElem.attribute( "outlineWidth" ).toDouble( &widthOk );
      penRed = frameColorElem.attribute( "red" ).toDouble( &redOk );
      penGreen = frameColorElem.attribute( "green" ).toDouble( &greenOk );
      penBlue = frameColorElem.attribute( "blue" ).toDouble( &blueOk );
      penAlpha = frameColorElem.attribute( "alpha" ).toDouble( &alphaOk );

      if ( redOk && greenOk && blueOk && alphaOk && widthOk )
      {
        properties.insert( "color_border", QgsSymbolLayerV2Utils::encodeColor( QColor( penRed, penGreen, penBlue, penAlpha ) ) );
        properties.insert( "width_border", QString::number( penWidth ) );
      }
    }
    QDomNodeList fillColorList = itemElem.elementsByTagName( "FillColor" );
    if ( fillColorList.size() > 0 )
    {
      QDomElement fillColorElem = fillColorList.at( 0 ).toElement();
      bool redOk, greenOk, blueOk, alphaOk;
      int fillRed, fillGreen, fillBlue, fillAlpha;

      fillRed = fillColorElem.attribute( "red" ).toDouble( &redOk );
      fillGreen = fillColorElem.attribute( "green" ).toDouble( &greenOk );
      fillBlue = fillColorElem.attribute( "blue" ).toDouble( &blueOk );
      fillAlpha = fillColorElem.attribute( "alpha" ).toDouble( &alphaOk );

      if ( redOk && greenOk && blueOk && alphaOk )
      {
        properties.insert( "color", QgsSymbolLayerV2Utils::encodeColor( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) ) );
        properties.insert( "style", "solid" );
      }
    }
    if ( itemElem.hasAttribute( "transparentFill" ) )
    {
      //old style (pre 2.0) of specifying that shapes had no fill
      bool hasOldTransparentFill = itemElem.attribute( "transparentFill", "0" ).toInt();
      if ( hasOldTransparentFill )
      {
        properties.insert( "style", "no" );
      }
    }

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

	QDomNodeList divs = doc.elementsByTagName("div");
	for (int i = 0; i < divs.size(); ++i) {
		QDomElement div = divs.at(i).toElement();
		QDomNode divClass = div.attributes().namedItem("class");
		if (divClass.nodeValue() == "textspoiler") {
			QString cardName, cardCost, cardType, cardPT, cardText;
			int cardId = 0;
			int cardLoyalty = 0;
			
			QDomNodeList trs = div.elementsByTagName("tr");
			for (int j = 0; j < trs.size(); ++j) {
				QDomElement tr = trs.at(j).toElement();
				QDomNodeList tds = tr.elementsByTagName("td");
				if (tds.size() != 2) {
					QStringList cardTextSplit = cardText.split("\n");
					for (int i = 0; i < cardTextSplit.size(); ++i)
						cardTextSplit[i] = cardTextSplit[i].trimmed();
					
					CardInfo *card = addCard(set->getShortName(), cardName, false, cardId, cardCost, cardType, cardPT, cardLoyalty, cardTextSplit);
					if (!set->contains(card)) {
						card->addToSet(set);
						cards++;
					}
					cardName = cardCost = cardType = cardPT = cardText = QString();
				} else {
					QString v1 = tds.at(0).toElement().text().simplified();
					QString v2 = tds.at(1).toElement().text().replace(trUtf8("—"), "-");
					
					if (v1 == "Name") {
						QDomElement a = tds.at(1).toElement().elementsByTagName("a").at(0).toElement();
						QString href = a.attributes().namedItem("href").nodeValue();
						cardId = href.mid(href.indexOf("multiverseid=") + 13).toInt();
						cardName = v2.simplified();
					} else if (v1 == "Cost:")
						cardCost = v2.simplified();
					else if (v1 == "Type:")
						cardType = v2.simplified();
					else if (v1 == "Pow/Tgh:")
						cardPT = v2.simplified().remove('(').remove(')');
					else if (v1 == "Rules Text:")
						cardText = v2.trimmed();
					else if (v1 == "Loyalty:")
						cardLoyalty = v2.trimmed().remove('(').remove(')').toInt();
				}
			}
			break;
		}
	}
	return cards;
}
Esempio n. 20
0
/*!
 * \brief CTConfToyRing::setParameters
 *
 * Sets values of all configurable block parameters based on the content of the
 * supplied XML tree.
 *
 * \param root XML tree containing data of all configurable parameters.
 */
bool CTConfToyRing::setParameters(QDomElement root)
{
    /* Check if the supplied configuration is applicable */
    if ("block" != root.tagName() || "ring" != root.attribute("name"))
    {
        return false;
    }

    /* Set block comment */
    QString comment = root.namedItem("comment").toElement().text();
    ui->qte_comment->setPlainText(comment);

    /* Set block runtime */
    QDomElement runtime = root.namedItem("runtime").toElement();
    double duration =
            runtime.namedItem("duration").toElement().text().toDouble();
    int repetitions =
            runtime.namedItem("repetitions").toElement().text().toInt();
    ui->qsb_block_duration->setValue(duration);
    ui->qsb_block_repetitions->setValue(repetitions);

    /* Set block stimuli */
    int num_stimuli = NUM_LIGHTS + NUM_SPEAKERS;
    QDomElement stimuli_block = root.namedItem("stimuli").toElement();
    int stimuli_count = stimuli_block.attribute("number").toInt();
    QDomNodeList stimuli = stimuli_block.childNodes();
    /* Check consistency */
    if (num_stimuli != stimuli_count || num_stimuli != stimuli.size())
    {
        qDebug() << "num_stimuli != stimuli_count || num_stimuli != stimuli.size() : " << num_stimuli << stimuli_count << stimuli.size();
        return false;
    }

    for (int i = 0; i < num_stimuli; i++)
    {
        QDomElement stimulus = stimuli.at(i).toElement();
        /* Do not process disabled stimuli */
        if ("false" == stimulus.attribute("enabled")) { continue; }

        if (i < NUM_LIGHTS)
        {
            light_stimuli[i]->setParameters(stimulus);
        }
        else if (i < (NUM_LIGHTS + NUM_SPEAKERS))
        {
            int j = i - NUM_LIGHTS;
            speaker_stimuli[j]->setParameters(stimulus);
        }

    }

    /* Set block feedback events */
    QDomElement feedback_block = root.namedItem("feedback").toElement();

    QDomElement event = feedback_block.namedItem("event").toElement();
    QString event_name = event.attribute("name");
    if ("null" == event_name)
    {
        ui->qrb_null_event->setChecked(true);
    }
    else if ("pressure" == event_name)
    {
        ui->qrb_pressure_event->setChecked(true);
        QString sensor = event.attribute("sensor");
        ui->qcb_pressure->setCurrentIndex(ui->qcb_pressure->findText(sensor));
        double value =
                event.namedItem("condition").toElement().text().toDouble();
        ui->qsb_pressure->setValue(value);
    }
    else if ("position" == event_name)
    {
        ui->qrb_position_event->setChecked(true);
        QString value = event.namedItem("condition").toElement().text();
        ui->qcb_position->setCurrentIndex(ui->qcb_position->findText(value));
    }
    else if ("body" == event_name)
    {
        ui->qrb_body_event->setChecked(true);
        QString value = event.namedItem("condition").toElement().text();
        ui->qcb_body->setCurrentIndex(ui->qcb_body->findText(value));
    }
    else if ("head" == event_name)
    {
        ui->qrb_head_event->setChecked(true);
        QString value = event.namedItem("condition").toElement().text();
        ui->qcb_head->setCurrentIndex(ui->qcb_head->findText(value));
    }

    /* Set block feedback actions */
    int num_actions = NUM_LIGHTS + NUM_SPEAKERS;
    QDomElement actions_block = feedback_block.namedItem("actions").toElement();
    int actions_count = actions_block.attribute("number").toInt();
    QDomNodeList actions = actions_block.childNodes();
    /* Check consistency */
    if (num_actions != actions_count || num_actions != actions.size())
    {
        return false;
    }

    for (int i = 0; i < num_actions; i++)
    {
        QDomElement action = actions.at(i).toElement();
        /* Do not process disabled actions */
        if ("false" == action.attribute("enabled")) { continue; }

        if (i < NUM_LIGHTS)
        {
            light_actions[i]->setParameters(action);

            QDomElement xml_duration = action.namedItem("duration").toElement();
            double val_duration_min =
                    xml_duration.namedItem("from").toElement().text().toDouble();
            double val_duration_max =
                    xml_duration.namedItem("to").toElement().text().toDouble();
            ui->qsb_duration_min->setMinimum(val_duration_min);
            ui->qsb_duration_min->setValue(val_duration_min);
            ui->qsb_duration_max->setValue(val_duration_max);
        }
        else if (i < (NUM_LIGHTS + NUM_SPEAKERS))
        {
            int j = i - NUM_LIGHTS;
            speaker_actions[j]->setParameters(action);

            QDomElement xml_duration = action.namedItem("duration").toElement();
            double val_duration_min =
                    xml_duration.namedItem("from").toElement().text().toDouble();
            double val_duration_max =
                    xml_duration.namedItem("to").toElement().text().toDouble();
            ui->qsb_duration_min->setMinimum(val_duration_min);
            ui->qsb_duration_min->setValue(val_duration_min);
            ui->qsb_duration_max->setValue(val_duration_max);
        }
    }
    ui->qsb_pause->setValue(duration - calculateRequiredTime());
    return true;
}
Esempio n. 21
0
QStringList QgsServerProjectParser::supportedOutputCrsList() const
{
  QStringList crsList;
  if ( !mXMLDoc )
  {
    return crsList;
  }

  QDomElement qgisElem = mXMLDoc->documentElement();
  if ( qgisElem.isNull() )
  {
    return crsList;
  }
  QDomElement propertiesElem = qgisElem.firstChildElement( "properties" );
  if ( propertiesElem.isNull() )
  {
    return crsList;
  }
  QDomElement wmsCrsElem = propertiesElem.firstChildElement( "WMSCrsList" );
  if ( !wmsCrsElem.isNull() )
  {
    QDomNodeList valueList = wmsCrsElem.elementsByTagName( "value" );
    for ( int i = 0; i < valueList.size(); ++i )
    {
      crsList.append( valueList.at( i ).toElement().text() );
    }
  }
  else
  {
    QDomElement wmsEpsgElem = propertiesElem.firstChildElement( "WMSEpsgList" );
    if ( !wmsEpsgElem.isNull() )
    {
      QDomNodeList valueList = wmsEpsgElem.elementsByTagName( "value" );
      bool conversionOk;
      for ( int i = 0; i < valueList.size(); ++i )
      {
        int epsgNr = valueList.at( i ).toElement().text().toInt( &conversionOk );
        if ( conversionOk )
        {
          crsList.append( QString( "EPSG:%1" ).arg( epsgNr ) );
        }
      }
    }
    else
    {
      //no CRS restriction defined in the project. Provide project CRS, wgs84 and pseudo mercator
      QString projectCrsId = projectCrs().authid();
      crsList.append( projectCrsId );
      if ( projectCrsId.compare( "EPSG:4326", Qt::CaseInsensitive ) != 0 )
      {
        crsList.append( QString( "EPSG:%1" ).arg( 4326 ) );
      }
      if ( projectCrsId.compare( "EPSG:3857", Qt::CaseInsensitive ) != 0 )
      {
        crsList.append( QString( "EPSG:%1" ).arg( 3857 ) );
      }
    }
  }

  return crsList;
}
Esempio n. 22
0
void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QDomDocument& doc, const QString& service, bool sia2045 ) const
{
  QDomElement propertiesElement = propertiesElem();
  if ( propertiesElement.isNull() )
  {
    QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc );
    return;
  }
  QDomElement serviceElem = doc.createElement( "Service" );

  QDomElement serviceCapabilityElem = propertiesElement.firstChildElement( "WMSServiceCapabilities" );
  if ( serviceCapabilityElem.isNull() || serviceCapabilityElem.text().compare( "true", Qt::CaseInsensitive ) != 0 )
  {
    QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc );
    return;
  }

  //Service name
  QDomElement wmsNameElem = doc.createElement( "Name" );
  QDomText wmsNameText = doc.createTextNode( service );
  wmsNameElem.appendChild( wmsNameText );
  serviceElem.appendChild( wmsNameElem );

  //WMS title
  //why not use project title ?
  QDomElement titleElem = propertiesElement.firstChildElement( "WMSServiceTitle" );
  if ( !titleElem.isNull() )
  {
    QDomElement wmsTitleElem = doc.createElement( "Title" );
    QDomText wmsTitleText = doc.createTextNode( titleElem.text() );
    wmsTitleElem.appendChild( wmsTitleText );
    serviceElem.appendChild( wmsTitleElem );
  }

  //WMS abstract
  QDomElement abstractElem = propertiesElement.firstChildElement( "WMSServiceAbstract" );
  if ( !abstractElem.isNull() )
  {
    QDomElement wmsAbstractElem = doc.createElement( "Abstract" );
    QDomText wmsAbstractText = doc.createTextNode( abstractElem.text() );
    wmsAbstractElem.appendChild( wmsAbstractText );
    serviceElem.appendChild( wmsAbstractElem );
  }

  //keyword list
  QDomElement keywordListElem = propertiesElement.firstChildElement( "WMSKeywordList" );
  if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 )
  {
    QDomElement wmsKeywordElem = doc.createElement( "KeywordList" );
    //add default keyword
    QDomElement keywordElem = doc.createElement( "Keyword" );
    keywordElem.setAttribute( "vocabulary", "ISO" );
    QDomText keywordText = doc.createTextNode( "infoMapAccessService" );
    /* If WFS and WCS 2.0 is implemented
    if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 )
      keywordText = doc.createTextNode( "infoFeatureAccessService" );
    else if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 )
      keywordText = doc.createTextNode( "infoCoverageAccessService" );*/
    keywordElem.appendChild( keywordText );
    wmsKeywordElem.appendChild( keywordElem );
    serviceElem.appendChild( wmsKeywordElem );
    //add config keywords
    if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() )
    {
      QDomNodeList keywordList = keywordListElem.elementsByTagName( "value" );
      for ( int i = 0; i < keywordList.size(); ++i )
      {
        keywordElem = doc.createElement( "Keyword" );
        keywordText = doc.createTextNode( keywordList.at( i ).toElement().text() );
        keywordElem.appendChild( keywordText );
        if ( sia2045 )
        {
          keywordElem.setAttribute( "vocabulary", "SIA_Geo405" );
        }
        wmsKeywordElem.appendChild( keywordElem );
      }
    }
  }
  else if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() )
  {
    QDomNodeList keywordNodeList = keywordListElem.elementsByTagName( "value" );
    QStringList keywordList;
    for ( int i = 0; i < keywordNodeList.size(); ++i )
    {
      keywordList.push_back( keywordNodeList.at( i ).toElement().text() );
    }
    QDomElement wmsKeywordElem = doc.createElement( "Keywords" );
    if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 )
      wmsKeywordElem = doc.createElement( "keywords" );
    QDomText keywordText = doc.createTextNode( keywordList.join( ", " ) );
    wmsKeywordElem.appendChild( keywordText );
    serviceElem.appendChild( wmsKeywordElem );
  }

  //OnlineResource element is mandatory according to the WMS specification
  QDomElement wmsOnlineResourceElem = propertiesElement.firstChildElement( "WMSOnlineResource" );
  if ( !wmsOnlineResourceElem.isNull() )
  {
    QDomElement onlineResourceElem = doc.createElement( "OnlineResource" );
    if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 )
    {
      QDomText onlineResourceText = doc.createTextNode( wmsOnlineResourceElem.text() );
      onlineResourceElem.appendChild( onlineResourceText );
    }
    else
    {
      onlineResourceElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" );
      onlineResourceElem.setAttribute( "xlink:type", "simple" );
      onlineResourceElem.setAttribute( "xlink:href", wmsOnlineResourceElem.text() );
    }
    serviceElem.appendChild( onlineResourceElem );
  }

  if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) //no contact information in WFS 1.0 and WCS 1.0
  {
    //Contact information
    QDomElement contactInfoElem = doc.createElement( "ContactInformation" );

    //Contact person primary
    QDomElement contactPersonPrimaryElem = doc.createElement( "ContactPersonPrimary" );

    //Contact person
    QDomElement contactPersonElem = propertiesElement.firstChildElement( "WMSContactPerson" );
    QString contactPersonString;
    if ( !contactPersonElem.isNull() )
    {
      contactPersonString = contactPersonElem.text();
    }
    QDomElement wmsContactPersonElem = doc.createElement( "ContactPerson" );
    QDomText contactPersonText = doc.createTextNode( contactPersonString );
    wmsContactPersonElem.appendChild( contactPersonText );
    contactPersonPrimaryElem.appendChild( wmsContactPersonElem );


    //Contact organisation
    QDomElement contactOrganizationElem = propertiesElement.firstChildElement( "WMSContactOrganization" );
    QString contactOrganizationString;
    if ( !contactOrganizationElem.isNull() )
    {
      contactOrganizationString = contactOrganizationElem.text();
    }
    QDomElement wmsContactOrganizationElem = doc.createElement( "ContactOrganization" );
    QDomText contactOrganizationText = doc.createTextNode( contactOrganizationString );
    wmsContactOrganizationElem.appendChild( contactOrganizationText );
    contactPersonPrimaryElem.appendChild( wmsContactOrganizationElem );

    //Contact position
    QDomElement contactPositionElem = propertiesElement.firstChildElement( "WMSContactPosition" );
    QString contactPositionString;
    if ( !contactPositionElem.isNull() )
    {
      contactPositionString = contactPositionElem.text();
    }
    QDomElement wmsContactPositionElem = doc.createElement( "ContactPosition" );
    QDomText contactPositionText = doc.createTextNode( contactPositionString );
    wmsContactPositionElem.appendChild( contactPositionText );
    contactPersonPrimaryElem.appendChild( wmsContactPositionElem );
    contactInfoElem.appendChild( contactPersonPrimaryElem );

    //phone
    QDomElement phoneElem = propertiesElement.firstChildElement( "WMSContactPhone" );
    if ( !phoneElem.isNull() )
    {
      QDomElement wmsPhoneElem = doc.createElement( "ContactVoiceTelephone" );
      QDomText wmsPhoneText = doc.createTextNode( phoneElem.text() );
      wmsPhoneElem.appendChild( wmsPhoneText );
      contactInfoElem.appendChild( wmsPhoneElem );
    }

    //mail
    QDomElement mailElem = propertiesElement.firstChildElement( "WMSContactMail" );
    if ( !mailElem.isNull() )
    {
      QDomElement wmsMailElem = doc.createElement( "ContactElectronicMailAddress" );
      QDomText wmsMailText = doc.createTextNode( mailElem.text() );
      wmsMailElem.appendChild( wmsMailText );
      contactInfoElem.appendChild( wmsMailElem );
    }

    serviceElem.appendChild( contactInfoElem );
  }

  //Fees
  QDomElement feesElem = propertiesElement.firstChildElement( "WMSFees" );
  QDomElement wmsFeesElem = doc.createElement( "Fees" );
  QDomText wmsFeesText = doc.createTextNode( "conditions unknown" ); // default value if access conditions are unknown
  if ( !feesElem.isNull() && !feesElem.text().isEmpty() )
  {
    wmsFeesText = doc.createTextNode( feesElem.text() );
  }
  wmsFeesElem.appendChild( wmsFeesText );
  serviceElem.appendChild( wmsFeesElem );

  //AccessConstraints
  QDomElement accessConstraintsElem = propertiesElement.firstChildElement( "WMSAccessConstraints" );
  QDomElement wmsAccessConstraintsElem = doc.createElement( "AccessConstraints" );
  QDomText wmsAccessConstraintsText = doc.createTextNode( "None" ); // default value if access constraints are unknown
  if ( !accessConstraintsElem.isNull() && !accessConstraintsElem.text().isEmpty() )
  {
    wmsAccessConstraintsText = doc.createTextNode( accessConstraintsElem.text() );
  }
  wmsAccessConstraintsElem.appendChild( wmsAccessConstraintsText );
  serviceElem.appendChild( wmsAccessConstraintsElem );

  //max width, max height for WMS
  if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 )
  {
    QString version = doc.documentElement().attribute( "version" );
    if ( version != "1.1.1" )
    {
      //max width
      QDomElement mwElem = propertiesElement.firstChildElement( "WMSMaxWidth" );
      if ( !mwElem.isNull() )
      {
        QDomElement maxWidthElem = doc.createElement( "MaxWidth" );
        QDomText maxWidthText = doc.createTextNode( mwElem.text() );
        maxWidthElem.appendChild( maxWidthText );
        serviceElem.appendChild( maxWidthElem );
      }
      //max height
      QDomElement mhElem = propertiesElement.firstChildElement( "WMSMaxHeight" );
      if ( !mhElem.isNull() )
      {
        QDomElement maxHeightElem = doc.createElement( "MaxHeight" );
        QDomText maxHeightText = doc.createTextNode( mhElem.text() );
        maxHeightElem.appendChild( maxHeightText );
        serviceElem.appendChild( maxHeightElem );
      }
    }
  }
  parentElement.appendChild( serviceElem );
}
Esempio n. 23
0
QSet<QString> QgsServerProjectParser::findRestrictedLayers() const
{
  QSet<QString> restrictedLayerSet;

  if ( !mXMLDoc )
  {
    return restrictedLayerSet;
  }

  //names of unpublished layers / groups
  QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( "properties" );
  if ( !propertiesElem.isNull() )
  {
    QDomElement wmsLayerRestrictionElem = propertiesElem.firstChildElement( "WMSRestrictedLayers" );
    if ( !wmsLayerRestrictionElem.isNull() )
    {
      QStringList restrictedLayersAndGroups;
      QDomNodeList wmsLayerRestrictionValues = wmsLayerRestrictionElem.elementsByTagName( "value" );
      for ( int i = 0; i < wmsLayerRestrictionValues.size(); ++i )
      {
        restrictedLayerSet.insert( wmsLayerRestrictionValues.at( i ).toElement().text() );
      }
    }
  }

  //get legend dom element
  if ( restrictedLayerSet.size() < 1 || !mXMLDoc )
  {
    return restrictedLayerSet;
  }

  QDomElement legendElem = mXMLDoc->documentElement().firstChildElement( "legend" );
  if ( legendElem.isNull() )
  {
    return restrictedLayerSet;
  }

  //go through all legend groups and insert names of subgroups / sublayers if there is a match
  QDomNodeList legendGroupList = legendElem.elementsByTagName( "legendgroup" );
  for ( int i = 0; i < legendGroupList.size(); ++i )
  {
    //get name
    QDomElement groupElem = legendGroupList.at( i ).toElement();
    QString groupName = groupElem.attribute( "name" );
    if ( restrictedLayerSet.contains( groupName ) ) //match: add names of subgroups and sublayers to set
    {
      //embedded group? -> also get names of subgroups and sublayers from embedded projects
      if ( groupElem.attribute( "embedded" ) == "1" )
      {
        sublayersOfEmbeddedGroup( convertToAbsolutePath( groupElem.attribute( "project" ) ), groupName, restrictedLayerSet );
      }
      else //local group
      {
        QDomNodeList subgroupList = groupElem.elementsByTagName( "legendgroup" );
        for ( int j = 0; j < subgroupList.size(); ++j )
        {
          restrictedLayerSet.insert( subgroupList.at( j ).toElement().attribute( "name" ) );
        }
        QDomNodeList sublayerList = groupElem.elementsByTagName( "legendlayer" );
        for ( int k = 0; k < sublayerList.size(); ++k )
        {
          restrictedLayerSet.insert( sublayerList.at( k ).toElement().attribute( "name" ) );
        }
      }
    }
  }

  // wmsLayerRestrictionValues contains LayerIDs
  if ( mUseLayerIDs )
  {
    QDomNodeList legendLayerList = legendElem.elementsByTagName( "legendlayer" );
    for ( int i = 0; i < legendLayerList.size(); ++i )
    {
      //get name
      QDomElement layerElem = legendLayerList.at( i ).toElement();
      QString layerName = layerElem.attribute( "name" );
      if ( restrictedLayerSet.contains( layerName ) ) //match: add layer id
      {
        // get legend layer file element
        QDomNodeList layerfileList = layerElem.elementsByTagName( "legendlayerfile" );
        if ( !layerfileList.isEmpty() )
        {
          // add layer id
          restrictedLayerSet.insert( layerfileList.at( 0 ).toElement().attribute( "layerid" ) );
        }
      }
    }
  }
  return restrictedLayerSet;
}
Esempio n. 24
0
bool QgsComposerScaleBar::readXML( const QDomElement& itemElem, const QDomDocument& doc )
{
  if ( itemElem.isNull() )
  {
    return false;
  }

  mHeight = itemElem.attribute( "height", "5.0" ).toDouble();
  mLabelBarSpace = itemElem.attribute( "labelBarSpace", "3.0" ).toDouble();
  mBoxContentSpace = itemElem.attribute( "boxContentSpace", "1.0" ).toDouble();
  mNumSegments = itemElem.attribute( "numSegments", "2" ).toInt();
  mNumSegmentsLeft = itemElem.attribute( "numSegmentsLeft", "0" ).toInt();
  mNumUnitsPerSegment = itemElem.attribute( "numUnitsPerSegment", "1.0" ).toDouble();
  mSegmentSizeMode = static_cast<SegmentSizeMode>( itemElem.attribute( "segmentSizeMode", "0" ).toInt() );
  mMinBarWidth = itemElem.attribute( "minBarWidth", "50" ).toInt();
  mMaxBarWidth = itemElem.attribute( "maxBarWidth", "150" ).toInt();
  mSegmentMillimeters = itemElem.attribute( "segmentMillimeters", "0.0" ).toDouble();
  mNumMapUnitsPerScaleBarUnit = itemElem.attribute( "numMapUnitsPerScaleBarUnit", "1.0" ).toDouble();
  mPen.setWidthF( itemElem.attribute( "outlineWidth", "1.0" ).toDouble() );
  mUnitLabeling = itemElem.attribute( "unitLabel" );
  mLineJoinStyle = QgsSymbolLayerV2Utils::decodePenJoinStyle( itemElem.attribute( "lineJoinStyle", "miter" ) );
  mPen.setJoinStyle( mLineJoinStyle );
  mLineCapStyle = QgsSymbolLayerV2Utils::decodePenCapStyle( itemElem.attribute( "lineCapStyle", "square" ) );
  mPen.setCapStyle( mLineCapStyle );
  QString fontString = itemElem.attribute( "font", "" );
  if ( !fontString.isEmpty() )
  {
    mFont.fromString( fontString );
  }

  //colors
  //fill color
  QDomNodeList fillColorList = itemElem.elementsByTagName( "fillColor" );
  if ( fillColorList.size() > 0 )
  {
    QDomElement fillColorElem = fillColorList.at( 0 ).toElement();
    bool redOk, greenOk, blueOk, alphaOk;
    int fillRed, fillGreen, fillBlue, fillAlpha;

    fillRed = fillColorElem.attribute( "red" ).toDouble( &redOk );
    fillGreen = fillColorElem.attribute( "green" ).toDouble( &greenOk );
    fillBlue = fillColorElem.attribute( "blue" ).toDouble( &blueOk );
    fillAlpha = fillColorElem.attribute( "alpha" ).toDouble( &alphaOk );

    if ( redOk && greenOk && blueOk && alphaOk )
    {
      mBrush.setColor( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) );
    }
  }
  else
  {
    mBrush.setColor( QColor( itemElem.attribute( "brushColor", "#000000" ) ) );
  }

  //fill color 2
  QDomNodeList fillColor2List = itemElem.elementsByTagName( "fillColor2" );
  if ( fillColor2List.size() > 0 )
  {
    QDomElement fillColor2Elem = fillColor2List.at( 0 ).toElement();
    bool redOk, greenOk, blueOk, alphaOk;
    int fillRed, fillGreen, fillBlue, fillAlpha;

    fillRed = fillColor2Elem.attribute( "red" ).toDouble( &redOk );
    fillGreen = fillColor2Elem.attribute( "green" ).toDouble( &greenOk );
    fillBlue = fillColor2Elem.attribute( "blue" ).toDouble( &blueOk );
    fillAlpha = fillColor2Elem.attribute( "alpha" ).toDouble( &alphaOk );

    if ( redOk && greenOk && blueOk && alphaOk )
    {
      mBrush2.setColor( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) );
    }
  }
  else
  {
    mBrush2.setColor( QColor( itemElem.attribute( "brush2Color", "#ffffff" ) ) );
  }

  //stroke color
  QDomNodeList strokeColorList = itemElem.elementsByTagName( "strokeColor" );
  if ( strokeColorList.size() > 0 )
  {
    QDomElement strokeColorElem = strokeColorList.at( 0 ).toElement();
    bool redOk, greenOk, blueOk, alphaOk;
    int strokeRed, strokeGreen, strokeBlue, strokeAlpha;

    strokeRed = strokeColorElem.attribute( "red" ).toDouble( &redOk );
    strokeGreen = strokeColorElem.attribute( "green" ).toDouble( &greenOk );
    strokeBlue = strokeColorElem.attribute( "blue" ).toDouble( &blueOk );
    strokeAlpha = strokeColorElem.attribute( "alpha" ).toDouble( &alphaOk );

    if ( redOk && greenOk && blueOk && alphaOk )
    {
      mPen.setColor( QColor( strokeRed, strokeGreen, strokeBlue, strokeAlpha ) );
    }
  }
  else
  {
    mPen.setColor( QColor( itemElem.attribute( "penColor", "#000000" ) ) );
  }

  //font color
  QDomNodeList textColorList = itemElem.elementsByTagName( "textColor" );
  if ( textColorList.size() > 0 )
  {
    QDomElement textColorElem = textColorList.at( 0 ).toElement();
    bool redOk, greenOk, blueOk, alphaOk;
    int textRed, textGreen, textBlue, textAlpha;

    textRed = textColorElem.attribute( "red" ).toDouble( &redOk );
    textGreen = textColorElem.attribute( "green" ).toDouble( &greenOk );
    textBlue = textColorElem.attribute( "blue" ).toDouble( &blueOk );
    textAlpha = textColorElem.attribute( "alpha" ).toDouble( &alphaOk );

    if ( redOk && greenOk && blueOk && alphaOk )
    {
      mFontColor = QColor( textRed, textGreen, textBlue, textAlpha );
    }
  }
  else
  {
    mFontColor.setNamedColor( itemElem.attribute( "fontColor", "#000000" ) );
  }

  //style
  delete mStyle;
  mStyle = 0;
  QString styleString = itemElem.attribute( "style", "" );
  setStyle( tr( styleString.toLocal8Bit().data() ) );

  mUnits = ( ScaleBarUnits )itemElem.attribute( "units" ).toInt();
  mAlignment = ( Alignment )( itemElem.attribute( "alignment", "0" ).toInt() );

  //map
  int mapId = itemElem.attribute( "mapId", "-1" ).toInt();
  if ( mapId >= 0 )
  {
    const QgsComposerMap* composerMap = mComposition->getComposerMapById( mapId );
    mComposerMap = composerMap;
    if ( mComposerMap )
    {
      connect( mComposerMap, SIGNAL( extentChanged() ), this, SLOT( updateSegmentSize() ) );
      connect( mComposerMap, SIGNAL( destroyed( QObject* ) ), this, SLOT( invalidateCurrentMap() ) );
    }
  }

  updateSegmentSize();

  //restore general composer item properties
  QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" );
  if ( composerItemList.size() > 0 )
  {
    QDomElement composerItemElem = composerItemList.at( 0 ).toElement();
    _readXML( composerItemElem, doc );
  }

  return true;
}
Esempio n. 25
0
bool QgsProject::createEmbeddedLayer( const QString& layerId, const QString& projectFilePath, QList<QDomNode>& brokenNodes,
                                      QList< QPair< QgsVectorLayer*, QDomElement > >& vectorLayerList, bool saveFlag )
{
  QFile projectFile( projectFilePath );
  if ( !projectFile.open( QIODevice::ReadOnly ) )
  {
    return false;
  }

  QDomDocument projectDocument;
  if ( !projectDocument.setContent( &projectFile ) )
  {
    return false;
  }

  //does project store pathes absolute or relative?
  bool useAbsolutePathes = true;
  QDomElement propertiesElem = projectDocument.documentElement().firstChildElement( "properties" );
  if ( !propertiesElem.isNull() )
  {
    QDomElement absElem = propertiesElem.firstChildElement( "Paths" ).firstChildElement( "Absolute" );
    if ( !absElem.isNull() )
    {
      useAbsolutePathes = absElem.text().compare( "true", Qt::CaseInsensitive ) == 0;
    }
  }

  QDomElement projectLayersElem = projectDocument.documentElement().firstChildElement( "projectlayers" );
  if ( projectLayersElem.isNull() )
  {
    return false;
  }

  QDomNodeList mapLayerNodes = projectLayersElem.elementsByTagName( "maplayer" );
  for ( int i = 0; i < mapLayerNodes.size(); ++i )
  {
    //get layer id
    QDomElement mapLayerElem = mapLayerNodes.at( i ).toElement();
    QString id = mapLayerElem.firstChildElement( "id" ).text();
    if ( id == layerId )
    {
      //layer can be embedded only once
      if ( mapLayerElem.attribute( "embedded" ) == "1" )
      {
        return false;
      }

      mEmbeddedLayers.insert( layerId, qMakePair( projectFilePath, saveFlag ) );

      //change datasource path from relative to absolute if necessary
      if ( !useAbsolutePathes )
      {
        QDomElement provider = mapLayerElem.firstChildElement( "provider" );
        if ( provider.text() == "spatialite" )
        {
          QDomElement dsElem = mapLayerElem.firstChildElement( "datasource" );

          QgsDataSourceURI uri( dsElem.text() );

          QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + "/" + uri.database() );
          if ( absoluteDs.exists() )
          {
            uri.setDatabase( absoluteDs.absoluteFilePath() );
            dsElem.removeChild( dsElem.childNodes().at( 0 ) );
            dsElem.appendChild( projectDocument.createTextNode( uri.uri() ) );
          }
        }
        else
        {
          QDomElement dsElem = mapLayerElem.firstChildElement( "datasource" );
          QString debug( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
          QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
          if ( absoluteDs.exists() )
          {
            dsElem.removeChild( dsElem.childNodes().at( 0 ) );
            dsElem.appendChild( projectDocument.createTextNode( absoluteDs.absoluteFilePath() ) );
          }
        }
      }

      if ( addLayer( mapLayerElem, brokenNodes, vectorLayerList ) )
      {
        return true;
      }
      else
      {
        mEmbeddedLayers.remove( layerId );
        return false;
      }
    }
  }

  return false;
}
bool QgsComposerAttributeTable::readXML( const QDomElement& itemElem, const QDomDocument& doc )
{
  if ( itemElem.isNull() )
  {
    return false;
  }

  mShowOnlyVisibleFeatures = itemElem.attribute( "showOnlyVisibleFeatures", "1" ).toInt();
  mFilterFeatures = itemElem.attribute( "filterFeatures", "false" ) == "true" ? true : false;
  mFeatureFilter = itemElem.attribute( "featureFilter", "" );

  //composer map
  int composerMapId = itemElem.attribute( "composerMap", "-1" ).toInt();
  if ( composerMapId == -1 )
  {
    mComposerMap = 0;
  }

  if ( composition() )
  {
    mComposerMap = composition()->getComposerMapById( composerMapId );
  }
  else
  {
    mComposerMap = 0;
  }

  if ( mComposerMap )
  {
    //if we have found a valid map item, listen out to extent changes on it and refresh the table
    QObject::connect( mComposerMap, SIGNAL( extentChanged() ), this, SLOT( refreshAttributes() ) );
  }

  //vector layer
  QString layerId = itemElem.attribute( "vectorLayer", "not_existing" );
  if ( layerId == "not_existing" )
  {
    mVectorLayer = 0;
  }
  else
  {
    QgsMapLayer* ml = QgsMapLayerRegistry::instance()->mapLayer( layerId );
    if ( ml )
    {
      mVectorLayer = dynamic_cast<QgsVectorLayer*>( ml );
      if ( mVectorLayer )
      {
        //if we have found a valid vector layer, listen for modifications on it and refresh the table
        QObject::connect( mVectorLayer, SIGNAL( layerModified() ), this, SLOT( refreshAttributes() ) );
      }
    }
  }

  //restore display attribute map
  mDisplayAttributes.clear();
  QDomNodeList displayAttributeList = itemElem.elementsByTagName( "displayAttributes" );
  if ( displayAttributeList.size() > 0 )
  {
    QDomElement displayAttributesElem =  displayAttributeList.at( 0 ).toElement();
    QDomNodeList attributeEntryList = displayAttributesElem.elementsByTagName( "attributeEntry" );
    for ( int i = 0; i < attributeEntryList.size(); ++i )
    {
      QDomElement attributeEntryElem = attributeEntryList.at( i ).toElement();
      int index = attributeEntryElem.attribute( "index", "-1" ).toInt();
      if ( index != -1 )
      {
        mDisplayAttributes.insert( index );
      }
    }
  }

  //restore alias map
  mFieldAliasMap.clear();
  QDomNodeList aliasMapNodeList = itemElem.elementsByTagName( "attributeAliasMap" );
  if ( aliasMapNodeList.size() > 0 )
  {
    QDomElement attributeAliasMapElem = aliasMapNodeList.at( 0 ).toElement();
    QDomNodeList aliasMepEntryList = attributeAliasMapElem.elementsByTagName( "aliasEntry" );
    for ( int i = 0; i < aliasMepEntryList.size(); ++i )
    {
      QDomElement aliasEntryElem = aliasMepEntryList.at( i ).toElement();
      int key = aliasEntryElem.attribute( "key", "-1" ).toInt();
      QString value = aliasEntryElem.attribute( "value", "" );
      mFieldAliasMap.insert( key, value );
    }
  }

  //restore sort columns
  mSortInformation.clear();
  QDomElement sortColumnsElem = itemElem.firstChildElement( "sortColumns" );
  if ( !sortColumnsElem.isNull() )
  {
    QDomNodeList columns = sortColumnsElem.elementsByTagName( "column" );
    for ( int i = 0; i < columns.size(); ++i )
    {
      QDomElement columnElem = columns.at( i ).toElement();
      int attribute = columnElem.attribute( "index" ).toInt();
      bool ascending = columnElem.attribute( "ascending" ) == "true" ? true : false;
      mSortInformation.push_back( qMakePair( attribute, ascending ) );
    }
  }
  bool success = tableReadXML( itemElem, doc );

  //must be done here because tableReadXML->setSceneRect changes mMaximumNumberOfFeatures
  mMaximumNumberOfFeatures = itemElem.attribute( "maxFeatures", "5" ).toInt();

  refreshAttributes();

  emit itemChanged();
  return success;
}
Esempio n. 27
0
int QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, QString& geometryAttribute, QgsFields& fields, QGis::WkbType& geomType )
{
  //get the <schema> root element
  QDomNodeList schemaNodeList = schemaDoc.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "schema" );
  if ( schemaNodeList.length() < 1 )
  {
    return 1;
  }
  QDomElement schemaElement = schemaNodeList.at( 0 ).toElement();
  mApplicationNamespace = schemaElement.attribute( "targetNamespace" );
  QDomElement complexTypeElement; //the <complexType> element corresponding to the feature type

  //find out, on which lines the first <element> or the first <complexType> occur. If <element> occurs first (mapserver), read the type of the relevant <complexType> tag. If <complexType> occurs first (geoserver), search for information about the feature type directly under this first complexType element

  int firstElementTagPos = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "element" ).at( 0 ).toElement().columnNumber();
  int firstComplexTypeTagPos = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "complexType" ).at( 0 ).toElement().columnNumber();

  if ( firstComplexTypeTagPos < firstElementTagPos )
  {
    //geoserver
    complexTypeElement = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "complexType" ).at( 0 ).toElement();
  }
  else
  {
    //UMN mapserver
    QString complexTypeType;
    QDomNodeList typeElementNodeList = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "element" );
    QDomElement typeElement = typeElementNodeList.at( 0 ).toElement();
    complexTypeType = typeElement.attribute( "type" );

    if ( complexTypeType.isEmpty() )
    {
      return 3;
    }

    //remove the namespace on complexTypeType
    if ( complexTypeType.contains( ':' ) )
    {
      complexTypeType = complexTypeType.section( ':', 1, 1 );
    }

    //find <complexType name=complexTypeType
    QDomNodeList complexTypeNodeList = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "complexType" );
    for ( int i = 0; i < complexTypeNodeList.size(); ++i )
    {
      if ( complexTypeNodeList.at( i ).toElement().attribute( "name" ) == complexTypeType )
      {
        complexTypeElement = complexTypeNodeList.at( i ).toElement();
        break;
      }
    }
  }

  if ( complexTypeElement.isNull() )
  {
    return 4;
  }

  //we have the relevant <complexType> element. Now find out the geometry and the thematic attributes
  QDomNodeList attributeNodeList = complexTypeElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "element" );
  if ( attributeNodeList.size() < 1 )
  {
    return 5;
  }

  bool foundGeometryAttribute = false;

  for ( int i = 0; i < attributeNodeList.size(); ++i )
  {
    QDomElement attributeElement = attributeNodeList.at( i ).toElement();
    //attribute name
    QString name = attributeElement.attribute( "name" );
    //attribute type
    QString type = attributeElement.attribute( "type" );

    //is it a geometry attribute?
    //MH 090428: sometimes the <element> tags for geometry attributes have only attribute ref="gml:polygonProperty" and no name
    QRegExp gmlPT( "gml:(.*)PropertyType" );
    // the GeometryAssociationType has been seen in #11785
    if ( type.indexOf( gmlPT ) == 0 || type == "gml:GeometryAssociationType" || name.isEmpty() )
    {
      foundGeometryAttribute = true;
      geometryAttribute = name;
      geomType = geomTypeFromPropertyType( geometryAttribute, gmlPT.cap( 1 ) );
    }
    else //todo: distinguish between numerical and non-numerical types
    {
      QVariant::Type  attributeType = QVariant::String; //string is default type
      if ( type.contains( "double", Qt::CaseInsensitive ) || type.contains( "float", Qt::CaseInsensitive ) || type.contains( "decimal", Qt::CaseInsensitive ) )
      {
        attributeType = QVariant::Double;
      }
      else if ( type.contains( "int", Qt::CaseInsensitive ) )
      {
        attributeType = QVariant::Int;
      }
      else if ( type.contains( "long", Qt::CaseInsensitive ) )
      {
        attributeType = QVariant::LongLong;
      }
      fields.append( QgsField( name, attributeType, type ) );
    }
  }
  if ( !foundGeometryAttribute )
  {
    geomType = QGis::WKBNoGeometry;
  }

  return 0;
}
Esempio n. 28
0
void QgsMilXLibraryLoader::run()
{
#ifdef __MINGW32__
  QString galleryPath = QDir( QString( "%1/../opt/mss/MilXGalleryFiles" ).arg( QApplication::applicationDirPath() ) ).absolutePath();
#else
  QString galleryPath = QDir( QgsApplication::applicationDirPath() ).absoluteFilePath( "MilXGalleryFiles" );
#endif
  if ( !QDir( galleryPath ).exists() )
  {
    galleryPath = QSettings().value( "/milx/milx_gallery_path", "" ).toString();
  }
  QString lang = QSettings().value( "/locale/currentLang", "en" ).toString().left( 2 ).toUpper();

  QDir galleryDir( galleryPath );
  if ( galleryDir.exists() )
  {
    foreach ( const QString& galleryFileName, galleryDir.entryList( QStringList() << "*.xml", QDir::Files ) )
    {
      QString galleryFilePath = galleryDir.absoluteFilePath( galleryFileName );
      QFile galleryFile( galleryFilePath );
      if ( !galleryFilePath.endsWith( "_international.xml", Qt::CaseInsensitive ) && galleryFile.open( QIODevice::ReadOnly ) )
      {
        QImage galleryIcon( QString( galleryFilePath ).replace( QRegExp( ".xml$" ), ".png" ) );
        QDomDocument doc;
        doc.setContent( &galleryFile );
        QDomElement mssGalleryEl = doc.firstChildElement( "MssGallery" );
        QDomElement galleryNameEl = mssGalleryEl.firstChildElement( QString( "Name_%1" ).arg( lang ) );
        if ( galleryNameEl.isNull() )
        {
          galleryNameEl = mssGalleryEl.firstChildElement( "Name_EN" );
        }
        QStandardItem* galleryItem = addItem( 0, galleryNameEl.text(), galleryIcon );

        QDomNodeList sectionNodes = mssGalleryEl.elementsByTagName( "Section" );
        for ( int iSection = 0, nSections = sectionNodes.size(); iSection < nSections; ++iSection )
        {
          QDomElement sectionEl = sectionNodes.at( iSection ).toElement();
          QDomElement sectionNameEl = sectionEl.firstChildElement( QString( "Name_%1" ).arg( lang ) );
          if ( sectionNameEl.isNull() )
          {
            sectionNameEl = mssGalleryEl.firstChildElement( "Name_EN" );
          }
          QStandardItem* sectionItem = addItem( galleryItem, sectionNameEl.text() );

          QDomNodeList subSectionNodes = sectionEl.elementsByTagName( "SubSection" );
          for ( int iSubSection = 0, nSubSections = subSectionNodes.size(); iSubSection < nSubSections; ++iSubSection )
          {
            QDomElement subSectionEl = subSectionNodes.at( iSubSection ).toElement();
            QDomElement subSectionNameEl = subSectionEl.firstChildElement( QString( "Name_%1" ).arg( lang ) );
            if ( subSectionNameEl.isNull() )
            {
              subSectionNameEl = mssGalleryEl.firstChildElement( "Name_EN" );
            }
            QStandardItem* subSectionItem = addItem( sectionItem, subSectionNameEl.text() );

            QDomNodeList memberNodes = subSectionEl.elementsByTagName( "Member" );
            QStringList symbolXmls;
            for ( int iMember = 0, nMembers = memberNodes.size(); iMember < nMembers; ++iMember )
            {
              symbolXmls.append( memberNodes.at( iMember ).toElement().attribute( "MssStringXML" ) );
            }
            QList<MilXClient::SymbolDesc> symbolDescs;
            MilXClient::getSymbolsMetadata( symbolXmls, symbolDescs );
            foreach ( const MilXClient::SymbolDesc& symbolDesc, symbolDescs )
            {
              if ( mAborted )
                return;
              addItem( subSectionItem, symbolDesc.name, symbolDesc.icon, true, symbolDesc.symbolId, symbolDesc.militaryName, symbolDesc.minNumPoints, symbolDesc.hasVariablePoints );
            }
          }
        }
      }
    }
Esempio n. 29
0
void OsmNominatimRunner::handleResult( QNetworkReply* reply )
{   
    QDomDocument xml;
    if (!xml.setContent(reply->readAll())) {
        qWarning() << "Cannot parse osm nominatim result";
        returnNoResults();
        return;
    }

    QVector<GeoDataPlacemark*> placemarks;
    QDomElement root = xml.documentElement();
    QDomNodeList places = root.elementsByTagName("place");
    for (int i=0; i<places.size(); ++i) {
        QDomNode place = places.at(i);
        QDomNamedNodeMap attributes = place.attributes();
        QString lon = attributes.namedItem("lon").nodeValue();
        QString lat = attributes.namedItem("lat").nodeValue();
        QString desc = attributes.namedItem("display_name").nodeValue();
        QString key = attributes.namedItem("class").nodeValue();
        QString value = attributes.namedItem("type").nodeValue();

        QString name = place.firstChildElement(value).text();
        QString road = place.firstChildElement("road").text();

        QString city = place.firstChildElement("city").text();
        if( city.isEmpty() ) {
            city = place.firstChildElement("town").text();
            if( city.isEmpty() ) {
                city = place.firstChildElement("village").text();
            } if( city.isEmpty() ) {
                city = place.firstChildElement("hamlet").text();
            }
        }

        QString administrative = place.firstChildElement("county").text();
        if( administrative.isEmpty() ) {
            administrative = place.firstChildElement("region").text();
            if( administrative.isEmpty() ) {
                administrative = place.firstChildElement("state").text();
            }
        }

        QString country = place.firstChildElement("country").text();

        QString description;
        for (int i=0; i<place.childNodes().size(); ++i) {
            QDomElement item = place.childNodes().at(i).toElement();
            description += item.nodeName() + ':' + item.text() + '\n';
        }
        description += "Category: " + key + '/' + value;

        if (!lon.isEmpty() && !lat.isEmpty() && !desc.isEmpty()) {
            QString placemarkName;
            GeoDataPlacemark* placemark = new GeoDataPlacemark;
            // try to provide 2 fields
            if (!name.isEmpty()) {
                placemarkName = name;
            }
            if (!road.isEmpty() && road != placemarkName ) {
                if( !placemarkName.isEmpty() ) {
                    placemarkName += ", ";
                }
                placemarkName += road;
            }
            if (!city.isEmpty() && !placemarkName.contains(",") && city != placemarkName) {
                if( !placemarkName.isEmpty() ) {
                    placemarkName += ", ";
                }
                placemarkName += city;
            }
            if (!administrative.isEmpty()&& !placemarkName.contains(",") && administrative != placemarkName) {
                if( !placemarkName.isEmpty() ) {
                    placemarkName += ", ";
                }
                placemarkName += administrative;
            }
            if (!country.isEmpty()&& !placemarkName.contains(",") && country != placemarkName) {
                if( !placemarkName.isEmpty() ) {
                    placemarkName += ", ";
                }
                placemarkName += country;
            }
            if (placemarkName.isEmpty()) {
                placemarkName = desc;
            }
            placemark->setName( placemarkName );
            placemark->setDescription(description);
            placemark->setCoordinate( lon.toDouble(), lat.toDouble(), 0, GeoDataCoordinates::Degree );
            GeoDataFeature::GeoDataVisualCategory category = GeoDataFeature::OsmVisualCategory( key + '=' + value );
            placemark->setVisualCategory( category );
            placemarks << placemark;
        }
    }
    
    emit searchFinished( placemarks );
}
Esempio n. 30
0
void RSSEditPopup::slotSave(QNetworkReply* reply)
{
    QDomDocument document;
    document.setContent(reply->read(reply->bytesAvailable()), true);

    QString text = document.toString();

    QString title = m_titleEdit->GetText();
    QString description = m_descEdit->GetText();
    QString author = m_authorEdit->GetText();
    QString file = m_thumbImage->GetFilename();

    bool download;
    if (m_download->GetCheckState() == MythUIStateType::Full)
        download = true;
    else
        download = false;

    VERBOSE(VB_GENERAL|VB_EXTRA, QString("Text to Parse: %1").arg(text));

    QDomElement root = document.documentElement();
    QDomElement channel = root.firstChildElement ("channel");
    if (!channel.isNull ())
    {
        Parse parser;
        if (title.isEmpty())
            title = channel.firstChildElement("title").text().trimmed();
        if (description.isEmpty())
            description = channel.firstChildElement("description").text();
        if (author.isEmpty())
            author = parser.GetAuthor(channel);
        if (author.isEmpty())
            author = channel.firstChildElement("managingEditor").text();
        if (author.isEmpty())
            author = channel.firstChildElement("webMaster").text();

        QString thumbnailURL = channel.firstChildElement("image").attribute("url");
        if (thumbnailURL.isEmpty())
        {
            QDomElement thumbElem = channel.firstChildElement("image");
            if (!thumbElem.isNull())
                thumbnailURL = thumbElem.firstChildElement("url").text();
        }
        if (thumbnailURL.isEmpty())
        {
            QDomNodeList nodes = channel.elementsByTagNameNS(
                           "http://www.itunes.com/dtds/podcast-1.0.dtd", "image");
            if (nodes.size())
            {
                thumbnailURL = nodes.at(0).toElement().attributeNode("href").value();
                if (thumbnailURL.isEmpty())
                    thumbnailURL = nodes.at(0).toElement().text();
            }
        }

        bool download;
        if (m_download->GetCheckState() == MythUIStateType::Full)
            download = true;
        else
            download = false;

        QDateTime updated = QDateTime::currentDateTime();
        QString filename("");

        if (file.isEmpty())
            filename = file;

        QString link = m_urlEdit->GetText();

        if (!thumbnailURL.isEmpty() && filename.isEmpty())
        {
            QString fileprefix = GetConfDir();

            QDir dir(fileprefix);
            if (!dir.exists())
                    dir.mkdir(fileprefix);

            fileprefix += "/MythNetvision";

            dir = QDir(fileprefix);
            if (!dir.exists())
                dir.mkdir(fileprefix);

            fileprefix += "/sitecovers";

            dir = QDir(fileprefix);
            if (!dir.exists())
                dir.mkdir(fileprefix);

            QFileInfo fi(thumbnailURL);
            QString rawFilename = fi.fileName();

            filename = QString("%1/%2").arg(fileprefix).arg(rawFilename);

            bool exists = QFile::exists(filename);
            if (!exists)
                HttpComms::getHttpFile(filename, thumbnailURL, 20000, 1, 2);
        }
        if (insertInDB(new RSSSite(title, filename, VIDEO_PODCAST, description, link,
                author, download, QDateTime::currentDateTime())))
            emit saving();
    }
    Close();
}