int QilexDoc::doc_insert_geometric_object(QDomElement geom_element)
{
   int error = 0;
   const char * buffer;
    
   SbVec3f joinax;
   SoTransform *pos_rot = new SoTransform;

   float joinangle;
   float pos_x, pos_y, pos_z, pos_rx, pos_ry, pos_rz;

   QString data, name;

   QDomNode node;
   QDomElement element;
   QDomNodeList list;

   SoSeparator *geomelement = new SoSeparator;
   SoSeparator *geomtest = new SoSeparator;
   
   name = geom_element.attribute ("name", QString::null);

   data = geom_element.attribute ("pos_x", QString::null);
   pos_x = data.toFloat();

   data = geom_element.attribute ("pos_y", QString::null);
   pos_y = data.toFloat();

   data = geom_element.attribute ("pos_z", QString::null);
   pos_z = data.toFloat();

   data = geom_element.attribute ("pos_rx", QString::null);
   pos_rx = data.toFloat();

   data = geom_element.attribute ("pos_ry", QString::null);
   pos_ry = data.toFloat();

   data = geom_element.attribute ("pos_rz", QString::null);
   pos_rz = data.toFloat();

   data = geom_element.attribute ("pos_angle", QString::null);
   joinangle = data.toFloat();

   joinax.setValue(SbVec3f( pos_x, pos_y, pos_z));
   pos_rot->translation.setValue(joinax);
   pos_rot->rotation.setValue(SbVec3f(pos_rx, pos_ry, pos_rz), (float) rad((double)joinangle));
   
   list = geom_element.elementsByTagName ("model3d");
   if (list.length() == 1)
   {
      node = list.item(0);
      element = node.toElement();

      data = element.attribute ("format", QString::null);
      // some stuff to take care about the format

      data = element.attribute ("size", QString::null);
      size_t size = (size_t)data.toULong(0,10);
      buffer = new char[size];

      data = element.text();
      buffer = data.ascii();

      SoInput input;
      input.setBuffer((void*) buffer, size);

      if (input.isValidBuffer())
      {
         geomelement = SoDB::readAll(&input);
         if (geomelement == NULL)
            error = 10;
      }
      else
         {error = 8;} //   assigno un nombre diferent de 0
   }
   else
   { error =9; }// assigno un nombre diferent de 0

   if (error == 0)
   {
      geomelement->ref();
      geomtest = (SoSeparator*)SoNode::getByName(name.latin1());

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


        if(tabs->count()>1)
        {
            tabs->removeTab(tabs->currentIndex());
        }
        else if(tabs->count()==1)
        {
            this->close();
        }
    }
    else return;
}
Beispiel #3
0
void NewstuffModelPrivate::handleProviderData(QNetworkReply *reply)
{
    if ( reply->operation() == QNetworkAccessManager::HeadOperation ) {
        const QVariant redirectionAttribute = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
        if ( !redirectionAttribute.isNull() ) {
            for ( int i=0; i<m_items.size(); ++i ) {
                NewstuffItem &item = m_items[i];
                if ( item.m_payloadUrl == reply->url() ) {
                    item.m_payloadUrl = redirectionAttribute.toUrl();
                }
            }
            m_networkAccessManager.head( QNetworkRequest( redirectionAttribute.toUrl() ) );
            return;
        }

        QVariant const size = reply->header( QNetworkRequest::ContentLengthHeader );
        if ( size.isValid() ) {
            qint64 length = size.value<qint64>();
            for ( int i=0; i<m_items.size(); ++i ) {
                NewstuffItem &item = m_items[i];
                if ( item.m_payloadUrl == reply->url() ) {
                    item.m_payloadSize = length;
                    QModelIndex const affected = m_parent->index( i );
                    emit m_parent->dataChanged( affected, affected );
                }
            }
        }
        return;
    }

    FetchPreviewJob *const job = m_networkJobs.take( reply );

    // check if we are redirected
    const QVariant redirectionAttribute = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
    if ( !redirectionAttribute.isNull() ) {
        QNetworkReply *redirectReply = m_networkAccessManager.get( QNetworkRequest( QUrl( redirectionAttribute.toUrl() ) ) );
        if ( job ) {
            m_networkJobs.insert( redirectReply, job );
        }
        return;
    }

    if ( job ) {
        job->run( reply->readAll() );
        delete job;
        return;
    }

    QDomDocument xml;
    if ( !xml.setContent( reply->readAll() ) ) {
        mDebug() << "Cannot parse newstuff xml data ";
        return;
    }

    m_items.clear();

    QDomElement root = xml.documentElement();
    QDomNodeList items = root.elementsByTagName( "stuff" );
#if QT_VERSION < 0x050000
    unsigned int i=0;
#else
    int i=0;
#endif
    for ( ; i < items.length(); ++i ) {
        m_items << importNode( items.item( i ) );
    }

    updateModel();
}
Beispiel #4
0
  QDomDocument createTransactionDocument( QgsServerInterface* serverIface, const QString& version,
                                          const QgsServerRequest& request )
  {
    Q_UNUSED( version );

    QDomDocument doc;

    QgsWfsProjectParser* configParser = getConfigParser( serverIface );
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl* accessControl = serverIface->accessControls();
#endif
    const QString requestBody = request.getParameter( QStringLiteral( "REQUEST_BODY" ) );

    QString errorMsg;
    if ( !doc.setContent( requestBody, true, &errorMsg ) )
    {
      throw QgsRequestNotWellFormedException( errorMsg );
    }

    QDomElement docElem = doc.documentElement();
    QDomNodeList docChildNodes = docElem.childNodes();

    // Re-organize the transaction document
    QDomDocument mDoc;
    QDomElement mDocElem = mDoc.createElement( QStringLiteral( "myTransactionDocument" ) );
    mDocElem.setAttribute( QStringLiteral( "xmlns" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:wfs" ), WFS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    mDoc.appendChild( mDocElem );

    QDomElement actionElem;
    QString actionName;
    QDomElement typeNameElem;
    QString typeName;

    for ( int i = docChildNodes.count(); 0 < i; --i )
    {
      actionElem = docChildNodes.at( i - 1 ).toElement();
      actionName = actionElem.localName();

      if ( actionName == QLatin1String( "Insert" ) )
      {
        QDomElement featureElem = actionElem.firstChild().toElement();
        typeName = featureElem.localName();
      }
      else if ( actionName == QLatin1String( "Update" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }
      else if ( actionName == QLatin1String( "Delete" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }

      if ( typeName.contains( QLatin1String( ":" ) ) )
        typeName = typeName.section( QStringLiteral( ":" ), 1, 1 );

      QDomNodeList typeNameList = mDocElem.elementsByTagName( typeName );
      if ( typeNameList.count() == 0 )
      {
        typeNameElem = mDoc.createElement( typeName );
        mDocElem.appendChild( typeNameElem );
      }
      else
        typeNameElem = typeNameList.at( 0 ).toElement();

      typeNameElem.appendChild( actionElem );
    }

    // It's time to make the transaction
    // Create the response document
    QDomDocument resp;
    //wfs:WFS_TransactionRespone element
    QDomElement respElem = resp.createElement( QStringLiteral( "WFS_TransactionResponse" )/*wfs:WFS_TransactionResponse*/ );
    respElem.setAttribute( QStringLiteral( "xmlns" ), WFS_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    respElem.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/wfs.xsd" );
    respElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) );
    resp.appendChild( respElem );

    // Store the created feature id for WFS
    QStringList insertResults;
    // Get the WFS layers id
    QStringList wfsLayersId = configParser->wfsLayers();;

    QList<QgsMapLayer*> layerList;
    QgsMapLayer* currentLayer = nullptr;

    // Loop through the layer transaction elements
    docChildNodes = mDocElem.childNodes();
    for ( int i = 0; i < docChildNodes.count(); ++i )
    {
      // Get the vector layer
      typeNameElem = docChildNodes.at( i ).toElement();
      typeName = typeNameElem.tagName();

      layerList = configParser->mapLayerFromTypeName( typeName );
      // Could be empty!
      if ( layerList.count() > 0 )
      {
        currentLayer = layerList.at( 0 );
      }
      else
      {
        throw QgsRequestNotWellFormedException( QStringLiteral( "Wrong TypeName: %1" ).arg( typeName ) );
      }

      QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( currentLayer );
      // it's a vectorlayer and defined by the administrator as a WFS layer
      if ( layer && wfsLayersId.contains( layer->id() ) )
      {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        if ( actionName == QLatin1String( "Insert" ) )
        {
          if ( !accessControl->layerInsertPermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature insert permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Update" ) )
        {
          if ( !accessControl->layerUpdatePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature update permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Delete" ) )
        {
          if ( !accessControl->layerDeletePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature delete permission denied" ) );
          }
        }
#endif

        // Get the provider and it's capabilities
        QgsVectorDataProvider* provider = layer->dataProvider();
        if ( !provider )
        {
          continue;
        }

        int cap = provider->capabilities();

        // Start the update transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::ChangeAttributeValues ) && ( cap & QgsVectorDataProvider::ChangeGeometries ) )
        {
          // Loop through the update elements for this layer
          QDomNodeList upNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Update" ) );
          for ( int j = 0; j < upNodeList.count(); ++j )
          {
            if ( !configParser->wfstUpdateLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS updates on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Update" ), errorMsg );
              return resp;
            }

            actionElem = upNodeList.at( j ).toElement();

            // Get the Feature Ids for this filter on the layer
            QDomElement filterElem = actionElem.elementsByTagName( QStringLiteral( "Filter" ) ).at( 0 ).toElement();
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

            // Loop through the property elements
            // Store properties and the geometry element
            QDomNodeList propertyNodeList = actionElem.elementsByTagName( QStringLiteral( "Property" ) );
            QMap<QString, QString> propertyMap;
            QDomElement propertyElem;
            QDomElement nameElem;
            QDomElement valueElem;
            QDomElement geometryElem;

            for ( int l = 0; l < propertyNodeList.count(); ++l )
            {
              propertyElem = propertyNodeList.at( l ).toElement();
              nameElem = propertyElem.elementsByTagName( QStringLiteral( "Name" ) ).at( 0 ).toElement();
              valueElem = propertyElem.elementsByTagName( QStringLiteral( "Value" ) ).at( 0 ).toElement();
              if ( nameElem.text() != QLatin1String( "geometry" ) )
              {
                propertyMap.insert( nameElem.text(), valueElem.text() );
              }
              else
              {
                geometryElem = valueElem;
              }
            }

            // Update the features
            QgsFields fields = provider->fields();
            QMap<QString, int> fieldMap = provider->fieldNameMap();
            QMap<QString, int>::const_iterator fieldMapIt;
            QString fieldName;
            bool conversionSuccess;

            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif

              QMap< QString, QString >::const_iterator it = propertyMap.constBegin();
              for ( ; it != propertyMap.constEnd(); ++it )
              {
                fieldName = it.key();
                fieldMapIt = fieldMap.find( fieldName );
                if ( fieldMapIt == fieldMap.constEnd() )
                {
                  continue;
                }
                QgsField field = fields.at( fieldMapIt.value() );
                if ( field.type() == 2 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toInt( &conversionSuccess ) );
                else if ( field.type() == 6 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toDouble( &conversionSuccess ) );
                else
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value() );
              }

              if ( !geometryElem.isNull() )
              {
                QgsGeometry g = QgsOgcUtils::geometryFromGML( geometryElem );
                if ( !layer->changeGeometry( *fidIt, g ) )
                {
                  throw QgsRequestNotWellFormedException( QStringLiteral( "Error in change geometry" ) );
                }
              }

#ifdef HAVE_SERVER_PYTHON_PLUGINS
              fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  layer->rollBack();
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif
            }
          }
        }
        // Commit the changes of the update elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Update" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }
        // Start the delete transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::DeleteFeatures ) )
        {
          // Loop through the delete elements
          QDomNodeList delNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Delete" ) );
          for ( int j = 0; j < delNodeList.count(); ++j )
          {
            if ( !configParser->wfstDeleteLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS deletes on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Delete" ), errorMsg );
              return resp;
            }

            actionElem = delNodeList.at( j ).toElement();
            QDomElement filterElem = actionElem.firstChild().toElement();
            // Get Feature Ids for the Filter element
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

#ifdef HAVE_SERVER_PYTHON_PLUGINS
            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
            }
#endif

            layer->selectByIds( fids );
            layer->deleteSelectedFeatures();
          }
        }
        // Commit the changes of the delete elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Delete" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }

        // Store the inserted features
        QgsFeatureList inFeatList;
        if ( cap & QgsVectorDataProvider::AddFeatures )
        {
          // Get Layer Field Information
          QgsFields fields = provider->fields();
          QMap<QString, int> fieldMap = provider->fieldNameMap();
          QMap<QString, int>::const_iterator fieldMapIt;

          // Loop through the insert elements
          QDomNodeList inNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Insert" ) );
          for ( int j = 0; j < inNodeList.count(); ++j )
          {
            if ( !configParser->wfstInsertLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS inserts on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Insert" ), errorMsg );
              return resp;
            }

            actionElem = inNodeList.at( j ).toElement();
            // Loop through the feature element
            QDomNodeList featNodes = actionElem.childNodes();
            for ( int l = 0; l < featNodes.count(); l++ )
            {
              // Add the feature to the layer
              // and store it to put it's Feature Id in the response
              inFeatList << QgsFeature( fields );

              // Create feature for this layer
              QDomElement featureElem = featNodes.at( l ).toElement();

              QDomNode currentAttributeChild = featureElem.firstChild();

              while ( !currentAttributeChild.isNull() )
              {
                QDomElement currentAttributeElement = currentAttributeChild.toElement();
                QString attrName = currentAttributeElement.localName();

                if ( attrName != QLatin1String( "boundedBy" ) )
                {
                  if ( attrName != QLatin1String( "geometry" ) ) //a normal attribute
                  {
                    fieldMapIt = fieldMap.find( attrName );
                    if ( fieldMapIt == fieldMap.constEnd() )
                    {
                      continue;
                    }
                    QgsField field = fields.at( fieldMapIt.value() );
                    QString attrValue = currentAttributeElement.text();
                    int attrType = field.type();
                    QgsMessageLog::logMessage( QStringLiteral( "attr: name=%1 idx=%2 value=%3" ).arg( attrName ).arg( fieldMapIt.value() ).arg( attrValue ) );
                    if ( attrType == QVariant::Int )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toInt() );
                    else if ( attrType == QVariant::Double )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toDouble() );
                    else
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue );
                  }
                  else //a geometry attribute
                  {
                    QgsGeometry g = QgsOgcUtils::geometryFromGML( currentAttributeElement );
                    inFeatList.last().setGeometry( g );
                  }
                }
                currentAttributeChild = currentAttributeChild.nextSibling();
              }
            }
          }
        }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        QgsFeatureList::iterator featureIt = inFeatList.begin();
        while ( featureIt != inFeatList.end() )
        {
          if ( !accessControl->allowToEdit( layer, *featureIt ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
          }
          featureIt++;
        }
#endif

        // add the features
        if ( !provider->addFeatures( inFeatList ) )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "Partial" ), QStringLiteral( "Insert" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          if ( provider->hasErrors() )
          {
            provider->clearErrors();
          }
          return resp;
        }
        // Get the Feature Ids of the inserted feature
        for ( int j = 0; j < inFeatList.size(); j++ )
        {
          insertResults << typeName + "." + QString::number( inFeatList[j].id() );
        }
      }
    }

    // Put the Feature Ids of the inserted feature
    if ( !insertResults.isEmpty() )
    {
      Q_FOREACH ( const QString &fidStr, insertResults )
      {
        QDomElement irElem = doc.createElement( QStringLiteral( "InsertResult" ) );
        QDomElement fiElem = doc.createElement( QStringLiteral( "ogc:FeatureId" ) );
        fiElem.setAttribute( QStringLiteral( "fid" ), fidStr );
        irElem.appendChild( fiElem );
        respElem.appendChild( irElem );
      }
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" ) );
        }
      }
    }
  }
  return restrictedLayerSet;
}
Beispiel #6
0
/**
 * @brief Parses info XML data and assigns it to the given tv show object
 * @param xml XML data
 * @param show Tv Show object
 * @param updateAllEpisodes Update all child episodes (regardless if they already have infos or not)
 */
void TheTvDb::parseAndAssignInfos(QString xml, TvShow *show, TvShowUpdateType updateType, QList<int> infosToLoad)
{
    QDomDocument domDoc;
    domDoc.setContent(xml);

    if (updateType == UpdateShow || updateType == UpdateShowAndAllEpisodes || updateType == UpdateShowAndNewEpisodes) {
        show->clear(infosToLoad);
        if (!domDoc.elementsByTagName("Series").isEmpty()) {
            QDomElement elem = domDoc.elementsByTagName("Series").at(0).toElement();
            if (infosToLoad.contains(TvShowScraperInfos::Certification) && !elem.elementsByTagName("ContentRating").isEmpty())
                show->setCertification(Helper::mapCertification(elem.elementsByTagName("ContentRating").at(0).toElement().text()));
            if (infosToLoad.contains(TvShowScraperInfos::FirstAired) && !elem.elementsByTagName("FirstAired").isEmpty())
                show->setFirstAired(QDate::fromString(elem.elementsByTagName("FirstAired").at(0).toElement().text(), "yyyy-MM-dd"));
            if (infosToLoad.contains(TvShowScraperInfos::Genres) && !elem.elementsByTagName("Genre").isEmpty())
                show->setGenres(Helper::mapGenre(elem.elementsByTagName("Genre").at(0).toElement().text().split("|", QString::SkipEmptyParts)));
            if (infosToLoad.contains(TvShowScraperInfos::Network) && !elem.elementsByTagName("Network").isEmpty())
                show->setNetwork(elem.elementsByTagName("Network").at(0).toElement().text());
            if (infosToLoad.contains(TvShowScraperInfos::Overview) && !elem.elementsByTagName("Overview").isEmpty())
                show->setOverview(elem.elementsByTagName("Overview").at(0).toElement().text());
            if (infosToLoad.contains(TvShowScraperInfos::Rating) && !elem.elementsByTagName("Rating").isEmpty())
                show->setRating(elem.elementsByTagName("Rating").at(0).toElement().text().toFloat());
            if (infosToLoad.contains(TvShowScraperInfos::Title) && !elem.elementsByTagName("SeriesName").isEmpty())
                show->setName(elem.elementsByTagName("SeriesName").at(0).toElement().text());
        }
    }

    if (updateType == UpdateAllEpisodes || updateType == UpdateNewEpisodes || updateType == UpdateShowAndAllEpisodes || updateType == UpdateShowAndNewEpisodes) {
        for (int i=0, n=domDoc.elementsByTagName("Episode").count() ; i<n ; ++i) {
            QDomElement elem = domDoc.elementsByTagName("Episode").at(i).toElement();
            if (!elem.elementsByTagName("SeasonNumber").isEmpty() && !elem.elementsByTagName("EpisodeNumber").isEmpty()) {
                int seasonNumber = elem.elementsByTagName("SeasonNumber").at(0).toElement().text().toInt();
                int episodeNumber = elem.elementsByTagName("EpisodeNumber").at(0).toElement().text().toInt();
                TvShowEpisode *episode = show->episode(seasonNumber, episodeNumber);
                if (!episode->isValid())
                    continue;
                if (updateType == UpdateAllEpisodes || updateType == UpdateShowAndAllEpisodes ||
                        ((updateType == UpdateNewEpisodes || updateType == UpdateShowAndNewEpisodes) && !episode->infoLoaded())) {
                    episode->clear(infosToLoad);
                    parseAndAssignSingleEpisodeInfos(elem, episode, infosToLoad);
                }
            }
        }

    }
}
Beispiel #7
0
/**
 * @brief Parses XML data (dom element) and assigns it to the given episode object
 * @param elem Dom element
 * @param episode Episode object
 */
void TheTvDb::parseAndAssignSingleEpisodeInfos(QDomElement elem, TvShowEpisode *episode, QList<int> infosToLoad)
{
    if (infosToLoad.contains(TvShowScraperInfos::Director) && !elem.elementsByTagName("Director").isEmpty())
        episode->setDirectors(elem.elementsByTagName("Director").at(0).toElement().text().split("|", QString::SkipEmptyParts));
    if (infosToLoad.contains(TvShowScraperInfos::Title) && !elem.elementsByTagName("EpisodeName").isEmpty())
        episode->setName(elem.elementsByTagName("EpisodeName").at(0).toElement().text());
    if (infosToLoad.contains(TvShowScraperInfos::SeasonEpisode) && !elem.elementsByTagName("EpisodeNumber").isEmpty())
        episode->setEpisode(elem.elementsByTagName("EpisodeNumber").at(0).toElement().text().toInt());
    if (infosToLoad.contains(TvShowScraperInfos::FirstAired) && !elem.elementsByTagName("FirstAired").isEmpty())
        episode->setFirstAired(QDate::fromString(elem.elementsByTagName("FirstAired").at(0).toElement().text(), "yyyy-MM-dd"));
    if (infosToLoad.contains(TvShowScraperInfos::Overview) && !elem.elementsByTagName("Overview").isEmpty())
        episode->setOverview(elem.elementsByTagName("Overview").at(0).toElement().text());
    if (infosToLoad.contains(TvShowScraperInfos::Rating) && !elem.elementsByTagName("Rating").isEmpty())
        episode->setRating(elem.elementsByTagName("Rating").at(0).toElement().text().toFloat());
    if (infosToLoad.contains(TvShowScraperInfos::SeasonEpisode) && !elem.elementsByTagName("SeasonNumber").isEmpty())
        episode->setSeason(elem.elementsByTagName("SeasonNumber").at(0).toElement().text().toInt());
    if (infosToLoad.contains(TvShowScraperInfos::Writer) && !elem.elementsByTagName("Writer").isEmpty())
        episode->setWriters(elem.elementsByTagName("Writer").at(0).toElement().text().split("|", QString::SkipEmptyParts));
    if (infosToLoad.contains(TvShowScraperInfos::Thumbnail) && !elem.elementsByTagName("filename").isEmpty() &&
            !elem.elementsByTagName("filename").at(0).toElement().text().isEmpty()) {
        QString mirror = m_bannerMirrors.at(qrand()%m_bannerMirrors.count());
        episode->setThumbnail(QUrl(QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("filename").at(0).toElement().text())));
    }
    episode->setInfosLoaded(true);
}
void QgsSingleBandGrayRenderer::toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap &props ) const
{
  QgsStringMap newProps = props;

  // create base structure
  QgsRasterRenderer::toSld( doc, element, props );

  // look for RasterSymbolizer tag
  QDomNodeList elements = element.elementsByTagName( QStringLiteral( "sld:RasterSymbolizer" ) );
  if ( elements.size() == 0 )
    return;

  // there SHOULD be only one
  QDomElement rasterSymbolizerElem = elements.at( 0 ).toElement();

  // add Channel Selection tags
  // Need to insert channelSelection in the correct sequence as in SLD standard e.g.
  // after opacity or geometry or as first element after sld:RasterSymbolizer
  QDomElement channelSelectionElem = doc.createElement( QStringLiteral( "sld:ChannelSelection" ) );
  elements = rasterSymbolizerElem.elementsByTagName( QStringLiteral( "sld:Opacity" ) );
  if ( elements.size() != 0 )
  {
    rasterSymbolizerElem.insertAfter( channelSelectionElem, elements.at( 0 ) );
  }
  else
  {
    elements = rasterSymbolizerElem.elementsByTagName( QStringLiteral( "sld:Geometry" ) );
    if ( elements.size() != 0 )
    {
      rasterSymbolizerElem.insertAfter( channelSelectionElem, elements.at( 0 ) );
    }
    else
    {
      rasterSymbolizerElem.insertBefore( channelSelectionElem, rasterSymbolizerElem.firstChild() );
    }
  }

  // for gray band
  QDomElement channelElem = doc.createElement( QStringLiteral( "sld:GrayChannel" ) );
  channelSelectionElem.appendChild( channelElem );

  // set band
  QDomElement sourceChannelNameElem = doc.createElement( QStringLiteral( "sld:SourceChannelName" ) );
  sourceChannelNameElem.appendChild( doc.createTextNode( QString::number( grayBand() ) ) );
  channelElem.appendChild( sourceChannelNameElem );

  // set ContrastEnhancement
  if ( contrastEnhancement() )
  {
    QDomElement contrastEnhancementElem = doc.createElement( QStringLiteral( "sld:ContrastEnhancement" ) );
    contrastEnhancement()->toSld( doc, contrastEnhancementElem );

    // do changes to minValue/maxValues depending on stretching algorithm. This is necessary because
    // geoserver do a first stretch on min/max, then apply colo map rules. In some combination is necessary
    // to use real min/max values and in othere the actual edited min/max values
    switch ( contrastEnhancement()->contrastEnhancementAlgorithm() )
    {
      case QgsContrastEnhancement::StretchAndClipToMinimumMaximum:
      case QgsContrastEnhancement::ClipToMinimumMaximum:
      {
        // with this renderer export have to be check against real min/max values of the raster
        QgsRasterBandStats myRasterBandStats = mInput->bandStatistics( grayBand(), QgsRasterBandStats::Min | QgsRasterBandStats::Max );

        // if minimum range differ from the real minimum => set is in exported SLD vendor option
        if ( !qgsDoubleNear( contrastEnhancement()->minimumValue(), myRasterBandStats.minimumValue ) )
        {
          // look for VendorOption tag to look for that with minValue attribute
          QDomNodeList elements = contrastEnhancementElem.elementsByTagName( QStringLiteral( "sld:VendorOption" ) );
          for ( int i = 0; i < elements.size(); ++i )
          {
            QDomElement vendorOption = elements.at( i ).toElement();
            if ( vendorOption.attribute( QStringLiteral( "name" ) ) != QStringLiteral( "minValue" ) )
              continue;

            // remove old value and add the new one
            vendorOption.removeChild( vendorOption.firstChild() );
            vendorOption.appendChild( doc.createTextNode( QString::number( myRasterBandStats.minimumValue ) ) );
          }
        }
        break;
      }
      case QgsContrastEnhancement::UserDefinedEnhancement:
        break;
      case QgsContrastEnhancement::NoEnhancement:
        break;
      case QgsContrastEnhancement::StretchToMinimumMaximum:
        break;
    }

    channelElem.appendChild( contrastEnhancementElem );
  }

  // for each color set a ColorMapEntry tag nested into "sld:ColorMap" tag
  // e.g. <ColorMapEntry color="#EEBE2F" quantity="-300" label="label" opacity="0"/>
  QList< QPair< QString, QColor > > classes;
  legendSymbologyItems( classes );

  // add ColorMap tag
  QDomElement colorMapElem = doc.createElement( QStringLiteral( "sld:ColorMap" ) );
  rasterSymbolizerElem.appendChild( colorMapElem );

  // TODO: add clip intervals basing on real min/max without trigger
  // min/max calculation again that can takes a lot for remote or big images
  //
  // contrast enhancement against a color map can be SLD simulated playing with ColorMapEntryies
  // each ContrastEnhancementAlgorithm need a specific management.
  // set type of ColorMap ramp [ramp, intervals, values]
  // basing on interpolation algorithm of the raster shader
  QList< QPair< QString, QColor > > colorMapping( classes );
  switch ( contrastEnhancement()->contrastEnhancementAlgorithm() )
  {
    case ( QgsContrastEnhancement::StretchAndClipToMinimumMaximum ):
    case ( QgsContrastEnhancement::ClipToMinimumMaximum ):
    {
      QString lowValue = classes[0].first;
      QColor lowColor = classes[0].second;
      lowColor.setAlpha( 0 );
      QString highValue = classes[1].first;
      QColor highColor = classes[1].second;
      highColor.setAlpha( 0 );

      colorMapping.prepend( QPair< QString, QColor >( lowValue, lowColor ) );
      colorMapping.append( QPair< QString, QColor >( highValue, highColor ) );
      break;
    }
    case ( QgsContrastEnhancement::StretchToMinimumMaximum ):
    {
      colorMapping[0].first = QStringLiteral( "0" );
      colorMapping[1].first = QStringLiteral( "255" );
      break;
    }
    case ( QgsContrastEnhancement::UserDefinedEnhancement ):
      break;
    case ( QgsContrastEnhancement::NoEnhancement ):
      break;
  }

  // create tags
  QList< QPair< QString, QColor > >::ConstIterator it;
  for ( it = colorMapping.begin(); it != colorMapping.constEnd() ; ++it )
  {
    // set low level color mapping
    QDomElement lowColorMapEntryElem = doc.createElement( QStringLiteral( "sld:ColorMapEntry" ) );
    colorMapElem.appendChild( lowColorMapEntryElem );
    lowColorMapEntryElem.setAttribute( QStringLiteral( "color" ), it->second.name() );
    lowColorMapEntryElem.setAttribute( QStringLiteral( "quantity" ), it->first );
    if ( it->second.alphaF() == 0.0 )
    {
      lowColorMapEntryElem.setAttribute( QStringLiteral( "opacity" ), QString::number( it->second.alpha() ) );
    }
  }
}
QgsMapLayer* QgsInterpolationLayerBuilder::createMapLayer( const QDomElement& elem, const QString& layerName, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  if ( !mVectorLayer )
  {
    return 0;
  }

  QDomNodeList interpolationList = elem.elementsByTagName( "Interpolation" );
  if ( interpolationList.size() < 1 )
  {
    QgsMSDebugMsg( "No Interpolation element found" );
    return 0;
  }
  QDomElement interpolationElem = interpolationList.at( 0 ).toElement();

  //create QgsInterpolator object from XML
  QDomNodeList tinList = interpolationElem.elementsByTagName( "TINMethod" );
  QDomNodeList idwList = interpolationElem.elementsByTagName( "IDWMethod" );

  QgsInterpolator* theInterpolator = 0;
  QList<QgsInterpolator::LayerData> layerDataList;
  QgsInterpolator::LayerData currentLayerData;
  currentLayerData.vectorLayer = mVectorLayer;
  QDomNodeList propertyNameList = interpolationElem.elementsByTagName( "PropertyName" );
  if ( propertyNameList.size() < 1 )
  {
    currentLayerData.zCoordInterpolation = true;
  }
  else
  {
    currentLayerData.zCoordInterpolation = false;

    //set attribute field interpolation or z-Coordinate interpolation
    QString attributeName = propertyNameList.at( 0 ).toElement().text();
    QgsVectorDataProvider* provider = mVectorLayer->dataProvider();
    if ( !provider )
    {
      return 0;
    }
    int attributeIndex = provider->fieldNameIndex( attributeName );
    if ( attributeIndex == -1 )
    {
      return 0; //attribute field not found
    }
    currentLayerData.interpolationAttribute = attributeIndex;
  }
  currentLayerData.mInputType = QgsInterpolator::POINTS;

  layerDataList.push_back( currentLayerData );

  if ( idwList.size() > 0 ) //inverse distance interpolator
  {
    theInterpolator = new QgsIDWInterpolator( layerDataList );

    //todo: parse <DistanceWeightingCoefficient>
  }
  else //tin is default
  {
    theInterpolator = new QgsTINInterpolator( layerDataList );
    //todo: parse <InterpolationFunction>
  }

  //Resolution
  int nCols, nRows;

  QDomNodeList resolutionNodeList = elem.elementsByTagName( "Resolution" );
  if ( resolutionNodeList.size() < 1 )
  {
    //use default values...
    nCols = 100;
    nRows = 100;
  }
  else
  {
    QDomElement resolutionElem = resolutionNodeList.at( 0 ).toElement();
    nCols = resolutionElem.attribute( "ncols" ).toInt();
    nRows = resolutionElem.attribute( "nrows" ).toInt();
    if ( nCols == 0 && nRows == 0 )
    {
      QgsMSDebugMsg( "Reading of resolution failed" );
      return 0;
    }
  }

  QTemporaryFile* tmpFile = new QTemporaryFile();
  if ( !tmpFile->open() )
  {
    delete tmpFile;
  }

  QgsRectangle extent = mVectorLayer->extent();
  QgsGridFileWriter gridWriter( theInterpolator, tmpFile->fileName(), extent, nCols, nRows, extent.width() / nCols, extent.height() / nRows );
  if ( gridWriter.writeFile( false ) != 0 )
  {
    QgsMSDebugMsg( "Interpolation of raster failed" );
    return 0;
  }

  filesToRemove.push_back( tmpFile ); //store raster in temporary file and remove after request
  QgsRasterLayer* theRaster = new QgsRasterLayer( tmpFile->fileName() );
  layersToRemove.push_back( theRaster );
  return theRaster;
}
Beispiel #10
0
/*static*/ QMenu* JMenuUtil::jMenuFromElement(QDomElement main, WindowInterface* wi, QObject* context)
{
 bool addSep = false;
 QString name = "<none>";
 Logger log("JMenuUtil");
 if (main.isNull())
 {
  log.warn("Menu from element called without an element");
  return new QMenu(name);
 }

 //name = LocaleSelector.getAttribute(main, "name");
 name = GuiUtilBase::getLocaleAttribute(main, "name");
 QMenu* menu = new QMenu(name);
 QList<int> mnemonicList = QList<int>();
 //QDomNodeList nodes = main.elementsByTagName("node");
 QDomNodeList nodes = main.childNodes();
 for(int i = 0; i < nodes.size(); i++)
 {
  QObject* menuItem = NULL;
  QDomElement child = nodes.at(i).toElement();
  if(child.tagName()!= "node")
   continue;
  if (child.elementsByTagName("node").size() == 0)
  {  // leaf
   //QAction* menuItem = NULL;
   if ((child.text().trimmed())==("separator"))
   {
    addSep = true;
   }
   else
   {
    if ((/*!SystemType.isMacOSX()*/
//                        && UIManager.getLookAndFeel().isNativeLookAndFeel() &&
         (!(child.firstChildElement("adapter").isNull()
        && child.firstChildElement("adapter").text()==("apps.gui3.TabbedPreferencesAction"))
        || !(child.firstChildElement("current").isNull()
        && child.firstChildElement("current").text()==("quit")))))
    {
     if (addSep)
     {
      menu->addSeparator();
      addSep = false;
     }
     QString leafName = child.attribute("name");
     Action* act = actionFromNode(child, wi, context);
     if(act !=NULL)
     {
      log.debug(tr("create action item '%1' in '%2' menu").arg(act->text()).arg(name));
      menu->addAction((QAction*)(menuItem = (QObject*)act));
      if(!child.firstChildElement("type").isNull())
      {
       if(child.firstChildElement("type").text() == "checkbox")
        act->setCheckable(true);
      }
      if (!child.firstChildElement("current").isNull())
      {
       //setMenuItemInterAction(context, child.firstChildElement("current").text(), menuItem);
       QString current = act->data().toString();
      ((RosterFrame*)wi)->currentMapper->setMapping(act,act);
      connect(act, SIGNAL(triggered(bool)), ((RosterFrame*)wi)->currentMapper, SLOT(map()));
      }
     }
    }
   }
  }
void QgsGetRequestHandler::sendGetFeatureInfoResponse( const QDomDocument& infoDoc, const QString& infoFormat ) const
{
  QByteArray ba;
  QgsMSDebugMsg( "Info format is:" + infoFormat );

  if ( infoFormat == "text/xml" )
  {
    ba = infoDoc.toByteArray();
  }
  else if ( infoFormat == "text/plain" || infoFormat == "text/html" )
  {
    //create string
    QString featureInfoString;

    if ( infoFormat == "text/plain" )
    {
      featureInfoString.append( "GetFeatureInfo results\n" );
      featureInfoString.append( "\n" );
    }
    else if ( infoFormat == "text/html" )
    {
      featureInfoString.append( "<HEAD>\n" );
      featureInfoString.append( "<TITLE> GetFeatureInfo results </TITLE>\n" );
      featureInfoString.append( "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">\n" );
      featureInfoString.append( "</HEAD>\n" );
      featureInfoString.append( "<BODY>\n" );
    }

    QDomNodeList layerList = infoDoc.elementsByTagName( "Layer" );

    //layer loop
    for ( int i = 0; i < layerList.size(); ++i )
    {
      QDomElement layerElem = layerList.at( i ).toElement();
      if ( infoFormat == "text/plain" )
      {
        featureInfoString.append( "Layer '" + layerElem.attribute( "name" ) + "'\n" );
      }
      else if ( infoFormat == "text/html" )
      {
        featureInfoString.append( "<TABLE border=1 width=100%>\n" );
        featureInfoString.append( "<TR><TH width=25%>Layer</TH><TD>" + layerElem.attribute( "name" ) + "</TD></TR>\n" );
        featureInfoString.append( "</BR>" );
      }

      //feature loop (for vector layers)
      QDomNodeList featureNodeList = layerElem.elementsByTagName( "Feature" );
      QDomElement currentFeatureElement;

      if ( featureNodeList.size() < 1 ) //raster layer?
      {
        QDomNodeList attributeNodeList = layerElem.elementsByTagName( "Attribute" );
        for ( int j = 0; j < attributeNodeList.size(); ++j )
        {
          QDomElement attributeElement = attributeNodeList.at( j ).toElement();
          if ( infoFormat == "text/plain" )
          {
            featureInfoString.append( attributeElement.attribute( "name" ) + " = '" +
                                      attributeElement.attribute( "value" ) + "'\n" );
          }
          else if ( infoFormat == "text/html" )
          {
            featureInfoString.append( "<TR><TH>" + attributeElement.attribute( "name" ) + "</TH><TD>" +
                                      attributeElement.attribute( "value" ) + "</TD></TR>\n" );
          }
        }
      }
      else //vector layer
      {
        for ( int j = 0; j < featureNodeList.size(); ++j )
        {
          QDomElement featureElement = featureNodeList.at( j ).toElement();
          if ( infoFormat == "text/plain" )
          {
            featureInfoString.append( "Feature " + featureElement.attribute( "id" ) + "\n" );
          }
          else if ( infoFormat == "text/html" )
          {
            featureInfoString.append( "<TABLE border=1 width=100%>\n" );
            featureInfoString.append( "<TR><TH>Feature</TH><TD>" + featureElement.attribute( "id" ) + "</TD></TR>\n" );
          }
          //attribute loop
          QDomNodeList attributeNodeList = featureElement.elementsByTagName( "Attribute" );
          for ( int k = 0; k < attributeNodeList.size(); ++k )
          {
            QDomElement attributeElement = attributeNodeList.at( k ).toElement();
            if ( infoFormat == "text/plain" )
            {
              featureInfoString.append( attributeElement.attribute( "name" ) + " = '" +
                                        attributeElement.attribute( "value" ) + "'\n" );
            }
            else if ( infoFormat == "text/html" )
            {
              featureInfoString.append( "<TR><TH>" + attributeElement.attribute( "name" ) + "</TH><TD>" + attributeElement.attribute( "value" ) + "</TD></TR>\n" );
            }
          }

          if ( infoFormat == "text/html" )
          {
            featureInfoString.append( "</TABLE>\n</BR>\n" );
          }
        }
      }
      if ( infoFormat == "text/plain" )
      {
        featureInfoString.append( "\n" );
      }
      else if ( infoFormat == "text/html" )
      {
        featureInfoString.append( "</TABLE>\n<BR></BR>\n" );

      }
    }
    if ( infoFormat == "text/html" )
    {
      featureInfoString.append( "</BODY>\n" );
    }
    ba = featureInfoString.toUtf8();
  }
  else //unsupported format, send exception
  {
    //todo: send service exception
  }

  sendHttpResponse( &ba, infoFormat );
}
Beispiel #12
0
static bool loadDetailsFromXML(const QString &filename, FileDetails *details)
{
    QDomDocument doc("mydocument");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return false;

    if (!doc.setContent(&file))
    {
        file.close();
        return false;
    }
    file.close();

    QString docType = doc.doctype().name();

    if (docType == "MYTHARCHIVEITEM")
    {
        QDomNodeList itemNodeList = doc.elementsByTagName("item");
        QString type, dbVersion;

        if (itemNodeList.count() < 1)
        {
            VERBOSE(VB_IMPORTANT, "Couldn't find an 'item' element in XML file");
            return false;
        }

        QDomNode n = itemNodeList.item(0);
        QDomElement e = n.toElement();
        type = e.attribute("type");
        dbVersion = e.attribute("databaseversion");
        if (type == "recording")
        {
            QDomNodeList nodeList = e.elementsByTagName("recorded");
            if (nodeList.count() < 1)
            {
                VERBOSE(VB_IMPORTANT,
                        "Couldn't find a 'recorded' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                        details->title = e.text();

                    if (e.tagName() == "subtitle")
                        details->subtitle = e.text();

                    if (e.tagName() == "starttime")
                        details->startTime = QDateTime::fromString(e.text(), Qt::ISODate);

                    if (e.tagName() == "description")
                        details->description = e.text();
                }
                n = n.nextSibling();
            }

            // get channel info
            n = itemNodeList.item(0);
            e = n.toElement();
            nodeList = e.elementsByTagName("channel");
            if (nodeList.count() < 1)
            {
                VERBOSE(VB_IMPORTANT,
                        "Couldn't find a 'channel' element in XML file");
                details->chanID = "";
                details->chanNo = "";
                details->chanName = "";
                details->callsign =  "";
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            details->chanID = e.attribute("chanid");
            details->chanNo = e.attribute("channum");
            details->chanName = e.attribute("name");
            details->callsign =  e.attribute("callsign");
            return true;
        }
        else if (type == "video")
        {
            QDomNodeList nodeList = e.elementsByTagName("videometadata");
            if (nodeList.count() < 1)
            {
                VERBOSE(VB_IMPORTANT,
                        "Couldn't find a 'videometadata' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                    {
                        details->title = e.text();
                        details->subtitle = "";
                        details->startTime = QDateTime();
                    }

                    if (e.tagName() == "plot")
                    {
                        details->description = e.text();
                    }
                }
                n = n.nextSibling();
            }

            details->chanID = "N/A";
            details->chanNo = "N/A";
            details->chanName = "N/A";
            details->callsign = "N/A";

            return true;
        }
    }

    return false;
}
Beispiel #13
0
bool QgsComposerArrow::readXml( const QDomElement& itemElem, const QDomDocument& doc )
{
  mArrowHeadWidth = itemElem.attribute( QStringLiteral( "arrowHeadWidth" ), QStringLiteral( "2.0" ) ).toDouble();
  mArrowHeadFillColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "arrowHeadFillColor" ), QStringLiteral( "0,0,0,255" ) ) );
  mArrowHeadOutlineColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "arrowHeadOutlineColor" ), QStringLiteral( "0,0,0,255" ) ) );
  mArrowHeadOutlineWidth = itemElem.attribute( QStringLiteral( "outlineWidth" ), QStringLiteral( "1.0" ) ).toDouble();
  setStartMarker( itemElem.attribute( QStringLiteral( "startMarkerFile" ), QLatin1String( "" ) ) );
  setEndMarker( itemElem.attribute( QStringLiteral( "endMarkerFile" ), QLatin1String( "" ) ) );
  mMarkerMode = QgsComposerArrow::MarkerMode( itemElem.attribute( QStringLiteral( "markerMode" ), QStringLiteral( "0" ) ).toInt() );
  //if bounds behaviour version is not set, default to 2.2 behaviour
  mBoundsBehaviour = itemElem.attribute( QStringLiteral( "boundsBehaviourVersion" ), QStringLiteral( "22" ) ).toInt();

  //arrow style
  QDomElement styleElem = itemElem.firstChildElement( QStringLiteral( "lineStyle" ) );
  if ( !styleElem.isNull() )
  {
    QDomElement lineStyleElem = styleElem.firstChildElement( QStringLiteral( "symbol" ) );
    if ( !lineStyleElem.isNull() )
    {
      delete mLineSymbol;
      mLineSymbol = QgsSymbolLayerUtils::loadSymbol<QgsLineSymbol>( lineStyleElem );
    }
  }
  else
  {
    //old project file, read arrow width and color
    delete mLineSymbol;

    QgsStringMap properties;
    properties.insert( QStringLiteral( "width" ), itemElem.attribute( QStringLiteral( "outlineWidth" ), QStringLiteral( "1.0" ) ) );

    if ( mBoundsBehaviour == 22 )
    {
      //if arrow was created in versions prior to 2.4, use the old rendering style
      properties.insert( QStringLiteral( "capstyle" ), QStringLiteral( "flat" ) );
    }
    else
    {
      properties.insert( QStringLiteral( "capstyle" ), QStringLiteral( "square" ) );
    }
    int red = 0;
    int blue = 0;
    int green = 0;
    int alpha = 255;

    QDomNodeList arrowColorList = itemElem.elementsByTagName( QStringLiteral( "ArrowColor" ) );
    if ( !arrowColorList.isEmpty() )
    {
      QDomElement arrowColorElem = arrowColorList.at( 0 ).toElement();
      red = arrowColorElem.attribute( QStringLiteral( "red" ), QStringLiteral( "0" ) ).toInt();
      green = arrowColorElem.attribute( QStringLiteral( "green" ), QStringLiteral( "0" ) ).toInt();
      blue = arrowColorElem.attribute( QStringLiteral( "blue" ), QStringLiteral( "0" ) ).toInt();
      alpha = arrowColorElem.attribute( QStringLiteral( "alpha" ), QStringLiteral( "255" ) ).toInt();
      mArrowHeadFillColor = QColor( red, green, blue, alpha );
      mArrowHeadOutlineColor = QColor( red, green, blue, alpha );
    }
    properties.insert( QStringLiteral( "color" ), QStringLiteral( "%1,%2,%3,%4" ).arg( red ).arg( green ).arg( blue ).arg( alpha ) );
    mLineSymbol = QgsLineSymbol::createSimple( properties );
  }

  mPen.setColor( mArrowHeadOutlineColor );
  mPen.setWidthF( mArrowHeadOutlineWidth );
  mBrush.setColor( mArrowHeadFillColor );

  //restore general composer item properties
  //needs to be before start point / stop point because setSceneRect()
  QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) );
  if ( !composerItemList.isEmpty() )
  {
    QDomElement composerItemElem = composerItemList.at( 0 ).toElement();
    _readXml( composerItemElem, doc );
  }

  //start point
  QDomNodeList startPointList = itemElem.elementsByTagName( QStringLiteral( "StartPoint" ) );
  if ( !startPointList.isEmpty() )
  {
    QDomElement startPointElem = startPointList.at( 0 ).toElement();
    mStartPoint.setX( startPointElem.attribute( QStringLiteral( "x" ), QStringLiteral( "0.0" ) ).toDouble() );
    mStartPoint.setY( startPointElem.attribute( QStringLiteral( "y" ), QStringLiteral( "0.0" ) ).toDouble() );
  }

  //stop point
  QDomNodeList stopPointList = itemElem.elementsByTagName( QStringLiteral( "StopPoint" ) );
  if ( !stopPointList.isEmpty() )
  {
    QDomElement stopPointElem = stopPointList.at( 0 ).toElement();
    mStopPoint.setX( stopPointElem.attribute( QStringLiteral( "x" ), QStringLiteral( "0.0" ) ).toDouble() );
    mStopPoint.setY( stopPointElem.attribute( QStringLiteral( "y" ), QStringLiteral( "0.0" ) ).toDouble() );
  }

  mStartXIdx = mStopPoint.x() < mStartPoint.x();
  mStartYIdx = mStopPoint.y() < mStartPoint.y();

  adaptItemSceneRect();
  emit itemChanged();
  return true;
}
Beispiel #14
0
void QgsWCSProjectParser::serviceCapabilities( QDomElement& parentElement, QDomDocument& doc ) const
{
  QDomElement serviceElem = doc.createElement( "Service" );

  QDomElement propertiesElem = mProjectParser.propertiesElem();
  if ( propertiesElem.isNull() )
  {
    QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc );
    return;
  }

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

  //Service name is always WCS
  QDomElement wcsNameElem = doc.createElement( "name" );
  QDomText wcsNameText = doc.createTextNode( "WCS" );
  wcsNameElem.appendChild( wcsNameText );
  serviceElem.appendChild( wcsNameElem );

  //WMS title
  QDomElement titleElem = propertiesElem.firstChildElement( "WMSServiceTitle" );
  if ( !titleElem.isNull() )
  {
    QDomElement wcsLabelElem = doc.createElement( "label" );
    QDomText wcsLabelText = doc.createTextNode( titleElem.text() );
    wcsLabelElem.appendChild( wcsLabelText );
    serviceElem.appendChild( wcsLabelElem );
  }

  //WMS abstract
  QDomElement abstractElem = propertiesElem.firstChildElement( "WMSServiceAbstract" );
  if ( !abstractElem.isNull() )
  {
    QDomElement wcsDescriptionElem = doc.createElement( "description" );
    QDomText wcsDescriptionText = doc.createTextNode( abstractElem.text() );
    wcsDescriptionElem.appendChild( wcsDescriptionText );
    serviceElem.appendChild( wcsDescriptionElem );
  }

  //keyword list
  QDomElement keywordListElem = propertiesElem.firstChildElement( "WMSKeywordList" );
  if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() )
  {
    QDomNodeList keywordList = keywordListElem.elementsByTagName( "value" );
    if ( keywordList.size() > 0 )
    {
      QDomElement wcsKeywordsElem = doc.createElement( "keywords" );
      for ( int i = 0; i < keywordList.size(); ++i )
      {
        QDomElement wcsKeywordElem = doc.createElement( "keyword" );
        QDomText keywordText = doc.createTextNode( keywordList.at( i ).toElement().text() );
        wcsKeywordElem.appendChild( keywordText );
        wcsKeywordsElem.appendChild( wcsKeywordElem );
      }
      serviceElem.appendChild( wcsKeywordsElem );
    }
  }

  //Fees
  QDomElement feesElem = propertiesElem.firstChildElement( "WMSFees" );
  if ( !feesElem.isNull() )
  {
    QDomElement wcsFeesElem = doc.createElement( "fees" );
    QDomText wcsFeesText = doc.createTextNode( feesElem.text() );
    wcsFeesElem.appendChild( wcsFeesText );
    serviceElem.appendChild( wcsFeesElem );
  }

  //AccessConstraints
  QDomElement accessConstraintsElem = propertiesElem.firstChildElement( "WMSAccessConstraints" );
  if ( !accessConstraintsElem.isNull() )
  {
    QDomElement wcsAccessConstraintsElem = doc.createElement( "accessConstraints" );
    QDomText wcsAccessConstraintsText = doc.createTextNode( accessConstraintsElem.text() );
    wcsAccessConstraintsElem.appendChild( wcsAccessConstraintsText );
    serviceElem.appendChild( wcsAccessConstraintsElem );
  }

  parentElement.appendChild( serviceElem );
}
Beispiel #15
0
bool Deck::importMnemosyne(QString fileName)
{
    QFileInfo fi(fileName);
    QString baseName = fi.baseName().toLower();

    QString tempFolder = utils::combinePaths(tempPath(), baseName);
    QString metadataPath = utils::combinePaths(tempFolder, "METADATA"); 
    QString cardsPath = utils::combinePaths(tempFolder, "cards.xml"); 

    utils::createDirectory(tempFolder);

    Compressor c;
    if(!c.decompressFolder(fileName, tempFolder)) {
        return false;
    }

    /// import metadata
    ///
    QTextStream s;
    QFile metadataFile(metadataPath);

    metadataFile.open(QIODevice::ReadOnly | QIODevice::Text);

    if(!metadataFile.isOpen())
        return false;

    s.setDevice(&metadataFile);
    s.setCodec("UTF-8");

    QStringList sl;
    QString l = s.readLine();
    while (!s.atEnd()) {
        sl = l.split(":");

        if(sl.size()>1) {
            if(sl[0]=="tags")
                setTags(sl[1]);
            else if(sl[0]=="notes")
                setDesc(sl[1]);
            else if(sl[0]=="author_name")
                setAuthor(sl[1]);
            else if(sl[0]=="card_set_name")
                setName(sl[1]);
        }

        l = s.readLine();
    }

    /// read cards
    QDomDocument domDocument;
    QString errorStr;
    int errorLine;
    int errorColumn;
    QString front, back, level;
    QFile cardsFile(cardsPath);

    cardsFile.open(QIODevice::ReadOnly | QIODevice::Text);

    if(!cardsFile.isOpen())
        return false;

    if (!domDocument.setContent(&cardsFile, true, &errorStr, &errorLine,
        &errorColumn)) {
            qDebug() << QString("Parse error at line %1, column %2:\n%3")
                .arg(errorLine)
                .arg(errorColumn)
                .arg(errorStr);
            return false;
    }

    QDomElement root = domDocument.documentElement();
    QString rootName = root.tagName().toLower();

    if (rootName == "opensm2sync") {
        QDomNodeList nodes = root.elementsByTagName("log");
        QDomNode node;
        QDomElement elnode;
        
        int count = nodes.count();

        for(int no = 0; no < count; no++) {
            node = nodes.at(no);

            if(node.attributes().namedItem("type").nodeValue()=="16") {
                elnode = node.firstChildElement("f");
                front = elnode.text();

                elnode = node.firstChildElement("b");
                back = elnode.text();

                if(!front.isEmpty()) {
                    Card *card = new Card();

                    card->updateFront(front);
                    card->updateBack(back);

                    addCard(card);
                }
            }
        }
    }

    metadataFile.close();
    cardsFile.close();

    utils::removeFile(metadataPath);
    utils::removeFile(cardsPath);
    utils::copyDirectory(getDeckPath(), tempFolder);

    return true;
}
Beispiel #16
0
void QgsDiagramSettings::readXml( const QDomElement& elem, const QgsVectorLayer* layer )
{
  Q_UNUSED( layer );

  enabled = ( elem.attribute( "enabled", "1" ) != "0" );
  if ( !QgsFontUtils::setFromXmlChildNode( font, elem, "fontProperties" ) )
  {
    font.fromString( elem.attribute( "font" ) );
  }
  backgroundColor.setNamedColor( elem.attribute( "backgroundColor" ) );
  backgroundColor.setAlpha( elem.attribute( "backgroundAlpha" ).toInt() );
  size.setWidth( elem.attribute( "width" ).toDouble() );
  size.setHeight( elem.attribute( "height" ).toDouble() );
  transparency = elem.attribute( "transparency", "0" ).toInt();
  penColor.setNamedColor( elem.attribute( "penColor" ) );
  int penAlpha = elem.attribute( "penAlpha", "255" ).toInt();
  penColor.setAlpha( penAlpha );
  penWidth = elem.attribute( "penWidth" ).toDouble();

  minScaleDenominator = elem.attribute( "minScaleDenominator", "-1" ).toDouble();
  maxScaleDenominator = elem.attribute( "maxScaleDenominator", "-1" ).toDouble();
  if ( elem.hasAttribute( "scaleBasedVisibility" ) )
  {
    scaleBasedVisibility = ( elem.attribute( "scaleBasedVisibility", "1" ) != "0" );
  }
  else
  {
    scaleBasedVisibility = minScaleDenominator >= 0 && maxScaleDenominator >= 0;
  }

  //diagram size unit type and scale
  if ( elem.attribute( "sizeType" ) == "MapUnits" )
  {
    //compatibility with pre-2.16 project files
    sizeType = QgsUnitTypes::RenderMapUnits;
  }
  else
  {
    sizeType = QgsUnitTypes::decodeRenderUnit( elem.attribute( "sizeType" ) );
  }
  sizeScale = QgsSymbolLayerUtils::decodeMapUnitScale( elem.attribute( "sizeScale" ) );

  //line width unit type and scale
  lineSizeUnit = QgsUnitTypes::decodeRenderUnit( elem.attribute( "lineSizeType" ) );
  lineSizeScale = QgsSymbolLayerUtils::decodeMapUnitScale( elem.attribute( "lineSizeScale" ) );

  //label placement method
  if ( elem.attribute( "labelPlacementMethod" ) == "Height" )
  {
    labelPlacementMethod = Height;
  }
  else
  {
    labelPlacementMethod = XHeight;
  }

  // orientation
  if ( elem.attribute( "diagramOrientation" ) == "Left" )
  {
    diagramOrientation = Left;
  }
  else if ( elem.attribute( "diagramOrientation" ) == "Right" )
  {
    diagramOrientation = Right;
  }
  else if ( elem.attribute( "diagramOrientation" ) == "Down" )
  {
    diagramOrientation = Down;
  }
  else
  {
    diagramOrientation = Up;
  }

  // scale dependency
  if ( elem.attribute( "scaleDependency" ) == "Diameter" )
  {
    scaleByArea = false;
  }
  else
  {
    scaleByArea = true;
  }

  barWidth = elem.attribute( "barWidth" ).toDouble();

  angleOffset = elem.attribute( "angleOffset" ).toInt();

  minimumSize = elem.attribute( "minimumSize" ).toDouble();

  //colors
  categoryColors.clear();
  QDomNodeList attributes = elem.elementsByTagName( "attribute" );

  if ( attributes.length() > 0 )
  {
    for ( int i = 0; i < attributes.size(); i++ )
    {
      QDomElement attrElem = attributes.at( i ).toElement();
      QColor newColor( attrElem.attribute( "color" ) );
      newColor.setAlpha( 255 - transparency );
      categoryColors.append( newColor );
      categoryAttributes.append( attrElem.attribute( "field" ) );
      categoryLabels.append( attrElem.attribute( "label" ) );
      if ( categoryLabels.back().isEmpty() )
      {
        categoryLabels.back() = categoryAttributes.back();
      }
    }
  }
  else
  {
    // Restore old format attributes and colors

    QStringList colorList = elem.attribute( "colors" ).split( '/' );
    QStringList::const_iterator colorIt = colorList.constBegin();
    for ( ; colorIt != colorList.constEnd(); ++colorIt )
    {
      QColor newColor( *colorIt );
      newColor.setAlpha( 255 - transparency );
      categoryColors.append( QColor( newColor ) );
    }

    //attribute indices
    categoryAttributes.clear();
    QStringList catList = elem.attribute( "categories" ).split( '/' );
    QStringList::const_iterator catIt = catList.constBegin();
    for ( ; catIt != catList.constEnd(); ++catIt )
    {
      categoryAttributes.append( *catIt );
      categoryLabels.append( *catIt );
    }
  }
}
Beispiel #17
0
bool Deck::importFromXml(QString fileName)
{
    QDomDocument domDocument;
    QString errorStr;
    int errorLine;
    int errorColumn;
    QFile file(fileName);

    file.open(QIODevice::ReadOnly | QIODevice::Text);

    if(!file.isOpen())
        return false;

    if (!domDocument.setContent(&file, true, &errorStr, &errorLine,
                                &errorColumn)) {
        qDebug() << QString("Parse error at line %1, column %2:\n%3")
                                 .arg(errorLine)
                                 .arg(errorColumn)
                                 .arg(errorStr);
        return false;
    }

    QDomElement root = domDocument.documentElement();
    if (root.tagName().toLower() != XML_TAG_ROOT) {
        qDebug() << "root node is mismatched.";

        return false;
    }

    QDomElement nodeDeck;
    QDomElement nodeCards;
    QDomElement elnode;

    nodeDeck = root.firstChildElement(XML_TAG_DECK);
    if(nodeDeck.isNull()) {
        qDebug() << "deck node is mismatched.";

        return false;
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_NAME);
    if(!elnode.isNull()) {
        name=elnode.text();
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_DESC);
    if(!elnode.isNull()) {
        desc=elnode.text();
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_ICON);
    if(!elnode.isNull()) {
        
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_GUID);
    if(!elnode.isNull()) {
        guid=QUuid(elnode.text());
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_CREATED);
    if(!elnode.isNull()) {
        createdTime=QDateTime::fromString(elnode.text());
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_UPDATED);
    if(!elnode.isNull()) {
        updatedTime=QDateTime::fromString(elnode.text());
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_AUTHOR);
    if(!elnode.isNull()) {
        author=elnode.text();
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_TAGS);
    if(!elnode.isNull()) {
        tags=elnode.text();
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_FLAGS);
    if(!elnode.isNull()) {
        flags=elnode.text().toUInt();
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_INHAND);
    if(!elnode.isNull()) {
        inhand=elnode.text().toInt();
    }

    elnode = nodeDeck.firstChildElement(XML_TAG_FORMAT);
    if(!elnode.isNull()) {
        //// Converting QDomElement to QString
        //// http://qt-project.org/doc/qt-5/qdomnode.html#save
        QString str;
        QTextStream stream(&str);
        elnode.save(stream, 4);
        format.fromString(str);
    }

    nodeCards = nodeDeck.firstChildElement(XML_TAG_CARDS);
    if(!elnode.isNull()) {
        QDomNodeList nodes = root.elementsByTagName(XML_TAG_CARD);
        QDomNode nodeCard;
        QString front, back;
        int flags = 0;

        int count = nodes.count();
        for(int no = 0; no < count; no++) {
            nodeCard = nodes.at(no);
            flags = 0;
            front.clear();
            back.clear();

            elnode = nodeCard.firstChildElement(XML_TAG_FRONT);
            if(!elnode.isNull()) {
                front = elnode.text();
            }

            elnode = nodeCard.firstChildElement(XML_TAG_BACK);            
            if(!elnode.isNull()) {
                back = elnode.text();
            }

            elnode = nodeCard.firstChildElement(XML_TAG_FLAGS);            
            if(!elnode.isNull()) {
                flags = elnode.text().toInt();
            }

            if(!front.isEmpty()) {
                Card *card = new Card;

                card->updateFront(front);
                card->updateBack(back);
                card->setFlags(flags);

                addCard(card);
            }
        }
    }
        
    file.close();

    return true;
}
Beispiel #18
0
QDBusIntrospection::Interfaces
QDBusXmlParser::interfaces() const
{
    QDBusIntrospection::Interfaces retval;

    if (m_node.isNull())
        return retval;

    QDomNodeList interfaceList = m_node.elementsByTagName(QLatin1String("interface"));
    for (int i = 0; i < interfaceList.count(); ++i)
    {
        QDomElement iface = interfaceList.item(i).toElement();
        QString ifaceName = iface.attribute(QLatin1String("name"));
        if (iface.isNull())
            continue;           // for whatever reason
        if (!QDBusUtil::isValidInterfaceName(ifaceName)) {
            qWarning("Invalid D-BUS interface name '%s' found while parsing introspection",
                     qPrintable(ifaceName));
            continue;
        }

        QDBusIntrospection::Interface *ifaceData = new QDBusIntrospection::Interface;
        ifaceData->name = ifaceName;
        {
            // save the data
            QTextStream ts(&ifaceData->introspection);
            iface.save(ts,2);
        }

        // parse annotations
        ifaceData->annotations = parseAnnotations(iface);

        // parse methods
        QDomNodeList list = iface.elementsByTagName(QLatin1String("method"));
        for (int j = 0; j < list.count(); ++j)
        {
            QDomElement method = list.item(j).toElement();
            QString methodName = method.attribute(QLatin1String("name"));
            if (method.isNull())
                continue;
            if (!QDBusUtil::isValidMemberName(methodName)) {
                qWarning("Invalid D-BUS member name '%s' found in interface '%s' while parsing introspection",
                         qPrintable(methodName), qPrintable(ifaceName));
                continue;
            }

            QDBusIntrospection::Method methodData;
            methodData.name = methodName;

            // parse arguments
            methodData.inputArgs = parseArgs(method, QLatin1String("in"), true);
            methodData.outputArgs = parseArgs(method, QLatin1String("out"), false);
            methodData.annotations = parseAnnotations(method);

            // add it
            ifaceData->methods.insert(methodName, methodData);
        }

        // parse signals
        list = iface.elementsByTagName(QLatin1String("signal"));
        for (int j = 0; j < list.count(); ++j)
        {
            QDomElement signal = list.item(j).toElement();
            QString signalName = signal.attribute(QLatin1String("name"));
            if (signal.isNull())
                continue;
            if (!QDBusUtil::isValidMemberName(signalName)) {
                qWarning("Invalid D-BUS member name '%s' found in interface '%s' while parsing introspection",
                         qPrintable(signalName), qPrintable(ifaceName));
                continue;
            }

            QDBusIntrospection::Signal signalData;
            signalData.name = signalName;

            // parse data
            signalData.outputArgs = parseArgs(signal, QLatin1String("out"), true);
            signalData.annotations = parseAnnotations(signal);

            // add it
            ifaceData->signals_.insert(signalName, signalData);
        }

        // parse properties
        list = iface.elementsByTagName(QLatin1String("property"));
        for (int j = 0; j < list.count(); ++j)
        {
            QDomElement property = list.item(j).toElement();
            QString propertyName = property.attribute(QLatin1String("name"));
            if (property.isNull())
                continue;
            if (!QDBusUtil::isValidMemberName(propertyName)) {
                qWarning("Invalid D-BUS member name '%s' found in interface '%s' while parsing introspection",
                         qPrintable(propertyName), qPrintable(ifaceName));
                continue;
            }

            QDBusIntrospection::Property propertyData;

            // parse data
            propertyData.name = propertyName;
            propertyData.type = property.attribute(QLatin1String("type"));
            propertyData.annotations = parseAnnotations(property);

            if (!QDBusUtil::isValidSingleSignature(propertyData.type)) {
                // cannot be!
                qWarning("Invalid D-BUS type signature '%s' found in property '%s.%s' while parsing introspection",
                         qPrintable(propertyData.type), qPrintable(ifaceName),
                         qPrintable(propertyName));
                continue;
            }

            QString access = property.attribute(QLatin1String("access"));
            if (access == QLatin1String("read"))
                propertyData.access = QDBusIntrospection::Property::Read;
            else if (access == QLatin1String("write"))
                propertyData.access = QDBusIntrospection::Property::Write;
            else if (access == QLatin1String("readwrite"))
                propertyData.access = QDBusIntrospection::Property::ReadWrite;
            else {
                qWarning("Invalid D-BUS property access '%s' found in property '%s.%s' while parsing introspection",
                         qPrintable(access), qPrintable(ifaceName),
                         qPrintable(propertyName));
                continue;       // invalid one!
            }

            // add it
            ifaceData->properties.insert(propertyName, propertyData);
        }

        // add it
        retval.insert(ifaceName, QSharedDataPointer<QDBusIntrospection::Interface>(ifaceData));
    }

    return retval;
}
Beispiel #19
0
/**
 * @brief Parses banner XML data and assigns it to the given tv show object
 * @param xml XML data
 * @param show Tv Show object
 */
void TheTvDb::parseAndAssignBanners(QString xml, TvShow *show, TvShowUpdateType updateType, QList<int> infosToLoad)
{
    QDomDocument domDoc;
    domDoc.setContent(xml);
    for (int i=0, n=domDoc.elementsByTagName("Banner").count() ; i<n ; ++i) {
        QDomElement elem = domDoc.elementsByTagName("Banner").at(i).toElement();
        if (elem.elementsByTagName("BannerType").isEmpty())
            continue;

        if (updateType == UpdateAllEpisodes || updateType == UpdateNewEpisodes)
            continue;

        QString mirror = m_bannerMirrors.at(qrand()%m_bannerMirrors.count());
        QString bannerType = elem.elementsByTagName("BannerType").at(0).toElement().text();
        QString bannerType2 = elem.elementsByTagName("BannerType2").at(0).toElement().text();
        if (bannerType == "fanart" && infosToLoad.contains(TvShowScraperInfos::Fanart)) {
            Poster p;
            if (!elem.elementsByTagName("id").isEmpty())
                p.id = elem.elementsByTagName("id").at(0).toElement().text();
            if (!elem.elementsByTagName("BannerPath").isEmpty())
                p.originalUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("BannerPath").at(0).toElement().text());
            if (!elem.elementsByTagName("ThumbnailPath").isEmpty())
                p.thumbUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("ThumbnailPath").at(0).toElement().text());
            if (!elem.elementsByTagName("BannerType2").isEmpty()) {
                QRegExp rx("(\\d+)x(\\d+)");
                if (rx.indexIn(elem.elementsByTagName("BannerType2").at(0).toElement().text(), 0) != -1) {
                    p.originalSize.setWidth(rx.cap(1).toInt());
                    p.originalSize.setHeight(rx.cap(2).toInt());
                }
            }
            show->addBackdrop(p);
        } else if (bannerType == "poster" && infosToLoad.contains(TvShowScraperInfos::Poster)) {
            Poster p;
            if (!elem.elementsByTagName("id").isEmpty())
                p.id = elem.elementsByTagName("id").at(0).toElement().text();
            if (!elem.elementsByTagName("BannerPath").isEmpty()) {
                p.originalUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("BannerPath").at(0).toElement().text());
                p.thumbUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("BannerPath").at(0).toElement().text());
            }
            if (!elem.elementsByTagName("BannerType2").isEmpty()) {
                QRegExp rx("(\\d+)x(\\d+)");
                if (rx.indexIn(elem.elementsByTagName("BannerType2").at(0).toElement().text(), 0) != -1) {
                    p.originalSize.setWidth(rx.cap(1).toInt());
                    p.originalSize.setHeight(rx.cap(2).toInt());
                }
            }
            show->addPoster(p);
        } else if (bannerType == "season" && bannerType2 == "season" && infosToLoad.contains(TvShowScraperInfos::SeasonPoster)) {
            Poster p;
            if (!elem.elementsByTagName("id").isEmpty())
                p.id = elem.elementsByTagName("id").at(0).toElement().text();
            if (!elem.elementsByTagName("BannerPath").isEmpty()) {
                p.originalUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("BannerPath").at(0).toElement().text());
                p.thumbUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("BannerPath").at(0).toElement().text());
            }
            if (!elem.elementsByTagName("Season").isEmpty()) {
                int season = elem.elementsByTagName("Season").at(0).toElement().text().toInt();
                show->addSeasonPoster(season, p);
            }
        } else if (bannerType == "season" && bannerType2 == "seasonwide" && infosToLoad.contains(TvShowScraperInfos::SeasonBanner)) {
            Poster p;
            if (!elem.elementsByTagName("id").isEmpty())
                p.id = elem.elementsByTagName("id").at(0).toElement().text();
            if (!elem.elementsByTagName("BannerPath").isEmpty()) {
                p.originalUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("BannerPath").at(0).toElement().text());
                p.thumbUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("BannerPath").at(0).toElement().text());
            }
            if (!elem.elementsByTagName("Season").isEmpty()) {
                int season = elem.elementsByTagName("Season").at(0).toElement().text().toInt();
                show->addSeasonBanner(season, p);
            }
        } else if (bannerType == "series" && infosToLoad.contains(TvShowScraperInfos::Banner)) {
            Poster p;
            if (!elem.elementsByTagName("id").isEmpty())
                p.id = elem.elementsByTagName("id").at(0).toElement().text();
            if (!elem.elementsByTagName("BannerPath").isEmpty()) {
                p.originalUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("BannerPath").at(0).toElement().text());
                p.thumbUrl = QString("%1/banners/%2").arg(mirror).arg(elem.elementsByTagName("BannerPath").at(0).toElement().text());
            }
            show->addBanner(p);
        }
    }
}
Beispiel #20
0
bool QgsComposerLegend::readXML( const QDomElement& itemElem, const QDomDocument& doc )
{
  if ( itemElem.isNull() )
  {
    return false;
  }

  //read general properties
  mSettings.setTitle( itemElem.attribute( "title" ) );
  if ( !itemElem.attribute( "titleAlignment" ).isEmpty() )
  {
    mSettings.setTitleAlignment(( Qt::AlignmentFlag )itemElem.attribute( "titleAlignment" ).toInt() );
  }
  int colCount = itemElem.attribute( "columnCount", "1" ).toInt();
  if ( colCount < 1 ) colCount = 1;
  mSettings.setColumnCount( colCount );
  mSettings.setSplitLayer( itemElem.attribute( "splitLayer", "0" ).toInt() == 1 );
  mSettings.setEqualColumnWidth( itemElem.attribute( "equalColumnWidth", "0" ).toInt() == 1 );

  QDomNodeList stylesNodeList = itemElem.elementsByTagName( "styles" );
  if ( stylesNodeList.size() > 0 )
  {
    QDomNode stylesNode = stylesNodeList.at( 0 );
    for ( int i = 0; i < stylesNode.childNodes().size(); i++ )
    {
      QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
      QgsComposerLegendStyle style;
      style.readXML( styleElem, doc );
      QString name = styleElem.attribute( "name" );
      QgsComposerLegendStyle::Style s;
      if ( name == "title" ) s = QgsComposerLegendStyle::Title;
      else if ( name == "group" ) s = QgsComposerLegendStyle::Group;
      else if ( name == "subgroup" ) s = QgsComposerLegendStyle::Subgroup;
      else if ( name == "symbol" ) s = QgsComposerLegendStyle::Symbol;
      else if ( name == "symbolLabel" ) s = QgsComposerLegendStyle::SymbolLabel;
      else continue;
      setStyle( s, style );
    }
  }

  //font color
  QColor fontClr;
  fontClr.setNamedColor( itemElem.attribute( "fontColor", "#000000" ) );
  mSettings.setFontColor( fontClr );

  //spaces
  mSettings.setBoxSpace( itemElem.attribute( "boxSpace", "2.0" ).toDouble() );
  mSettings.setColumnSpace( itemElem.attribute( "columnSpace", "2.0" ).toDouble() );

  mSettings.setSymbolSize( QSizeF( itemElem.attribute( "symbolWidth", "7.0" ).toDouble(), itemElem.attribute( "symbolHeight", "14.0" ).toDouble() ) );
  mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( "wmsLegendWidth", "50" ).toDouble(), itemElem.attribute( "wmsLegendHeight", "25" ).toDouble() ) );

  mSettings.setWrapChar( itemElem.attribute( "wrapChar" ) );

  //composer map
  if ( !itemElem.attribute( "map" ).isEmpty() )
  {
    mComposerMap = mComposition->getComposerMapById( itemElem.attribute( "map" ).toInt() );
  }

  //read model properties
  QDomNodeList modelNodeList = itemElem.elementsByTagName( "Model" );
  if ( modelNodeList.size() > 0 )
  {
    QDomElement modelElem = modelNodeList.at( 0 ).toElement();
    mLegendModel.readXML( modelElem, doc );
  }

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

  // < 2.0 projects backward compatibility >>>>>
  //title font
  QString titleFontString = itemElem.attribute( "titleFont" );
  if ( !titleFontString.isEmpty() )
  {
    rstyle( QgsComposerLegendStyle::Title ).rfont().fromString( titleFontString );
  }
  //group font
  QString groupFontString = itemElem.attribute( "groupFont" );
  if ( !groupFontString.isEmpty() )
  {
    rstyle( QgsComposerLegendStyle::Group ).rfont().fromString( groupFontString );
  }

  //layer font
  QString layerFontString = itemElem.attribute( "layerFont" );
  if ( !layerFontString.isEmpty() )
  {
    rstyle( QgsComposerLegendStyle::Subgroup ).rfont().fromString( layerFontString );
  }
  //item font
  QString itemFontString = itemElem.attribute( "itemFont" );
  if ( !itemFontString.isEmpty() )
  {
    rstyle( QgsComposerLegendStyle::SymbolLabel ).rfont().fromString( itemFontString );
  }

  if ( !itemElem.attribute( "groupSpace" ).isEmpty() )
  {
    rstyle( QgsComposerLegendStyle::Group ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "groupSpace", "3.0" ).toDouble() );
  }
  if ( !itemElem.attribute( "layerSpace" ).isEmpty() )
  {
    rstyle( QgsComposerLegendStyle::Subgroup ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "layerSpace", "3.0" ).toDouble() );
  }
  if ( !itemElem.attribute( "symbolSpace" ).isEmpty() )
  {
    rstyle( QgsComposerLegendStyle::Symbol ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "symbolSpace", "2.0" ).toDouble() );
    rstyle( QgsComposerLegendStyle::SymbolLabel ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "symbolSpace", "2.0" ).toDouble() );
  }
  // <<<<<<< < 2.0 projects backward compatibility

  emit itemChanged();
  return true;
}
KisHatchingPaintOpSettingsWidget:: KisHatchingPaintOpSettingsWidget(QWidget* parent)
                                 : KisBrushBasedPaintopOptionWidget(parent)
{
    //-------Adding widgets to the screen------------
    
    addPaintOpOption(new KisHatchingOptions());
    addPaintOpOption(new KisHatchingPreferences());
    addPaintOpOption(new KisPaintActionTypeOption());
    addPaintOpOption(new KisCurveOptionWidget(new KisHatchingPressureSeparationOption()));
    addPaintOpOption(new KisCurveOptionWidget(new KisHatchingPressureThicknessOption()));
    addPaintOpOption(new KisCurveOptionWidget(new KisHatchingPressureCrosshatchingOption()));
    addPaintOpOption(new KisCurveOptionWidget(new KisPressureSizeOption()));
    addPaintOpOption(new KisCurveOptionWidget(new KisPressureOpacityOption()));

    //-----Useful to read first:------
    /*
    Below you will encounter a reasonably correct solution to the problem of changing
    the default presets of the "BrushTip" popup configuration dialgoue.
    In my (Pentalis) opinion, the best solution is code refactoring (simpler ways
    to change the defaults). On the meanwhile, copypasting this code
    won't give your class a charisma penalty.
    In kis_hatching_paintop_settings.cpp you will find a snippet of code to
    discover the structure of your XML config tree if you need to edit it at build
    time like here.    
    */
    
    //---------START ALTERING DEFAULT VALUES-----------
    
    //As the name implies, reconfigurationCourier is the KisPropertiesConfiguration*
    //we'll use as an intermediary to edit the default settings
    KisPropertiesConfiguration* reconfigurationCourier = configuration();
    
    /*xMLAnalyzer is an empty document we'll use to analyze and edit the config string part by part
    I know the important string is "brush_definition" because I read the tree with the snippet
    in kis_hatching_paintop_settings.cpp */
    QDomDocument xMLAnalyzer("");
    xMLAnalyzer.setContent(reconfigurationCourier->getString("brush_definition") );
    
    /*More things I know by reading the XML tree. At this point you can just read it with:
    qDebug() << xMLAnalyzer.toString() ;
    those QDomElements are the way to navigate the XML tree, read
    http://doc.qt.nokia.com/latest/qdomdocument.html for more information */
    QDomElement firstTag = xMLAnalyzer.documentElement();
    QDomElement firstTagsChild = firstTag.elementsByTagName("MaskGenerator").item(0).toElement();
    
    // SET THE DEFAULT VALUES
    firstTag.attributeNode("spacing").setValue("0.4");
    firstTagsChild.attributeNode("diameter").setValue("30");
    
    //Write them into the intermediary config file
    reconfigurationCourier->setProperty("brush_definition", xMLAnalyzer.toString() );
    
    KisCubicCurve CurveSize;
    
    CurveSize.fromString("0,1;1,0.1;");
    //qDebug() << "\n\n\n" << CurveSize.toString() << "\n\n\n";
    
    QVariant QVCurveSize = QVariant::fromValue(CurveSize);
    
    reconfigurationCourier->setProperty("CurveSize", QVCurveSize);
    
    setConfiguration(reconfigurationCourier);  // Finished.
    
    /* Debugging block
    QMap<QString, QVariant> rofl = QMap<QString, QVariant>(reconfigurationCourier->getProperties());
    
    QMap<QString, QVariant>::const_iterator i;
    for (i = rofl.constBegin(); i != rofl.constEnd(); ++i)
        qDebug() << i.key() << ":" << i.value();
    */
    
    delete reconfigurationCourier;
}
Beispiel #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
    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 ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() )
    {
        QDomElement wmsKeywordElem = doc.createElement( "KeywordList" );
        QDomNodeList keywordList = keywordListElem.elementsByTagName( "value" );
        for ( int i = 0; i < keywordList.size(); ++i )
        {
            QDomElement keywordElem = doc.createElement( "Keyword" );
            QDomText keywordText = doc.createTextNode( keywordList.at( i ).toElement().text() );
            keywordElem.appendChild( keywordText );
            if ( sia2045 )
            {
                keywordElem.setAttribute( "vocabulary", "SIA_Geo405" );
            }
            wmsKeywordElem.appendChild( keywordElem );
        }

        if ( keywordList.size() > 0 )
        {
            serviceElem.appendChild( wmsKeywordElem );
        }
    }

    //OnlineResource element is mandatory according to the WMS specification
    QDomElement wmsOnlineResourceElem = propertiesElement.firstChildElement( "WMSOnlineResource" );
    QDomElement onlineResourceElem = doc.createElement( "OnlineResource" );
    onlineResourceElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" );
    onlineResourceElem.setAttribute( "xlink:type", "simple" );
    if ( !wmsOnlineResourceElem.isNull() )
    {
        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 );
        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" );
    if ( !feesElem.isNull() )
    {
        QDomElement wmsFeesElem = doc.createElement( "Fees" );
        QDomText wmsFeesText = doc.createTextNode( feesElem.text() );
        wmsFeesElem.appendChild( wmsFeesText );
        serviceElem.appendChild( wmsFeesElem );
    }

    //AccessConstraints
    QDomElement accessConstraintsElem = propertiesElement.firstChildElement( "WMSAccessConstraints" );
    if ( !accessConstraintsElem.isNull() )
    {
        QDomElement wmsAccessConstraintsElem = doc.createElement( "AccessConstraints" );
        QDomText 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 );
}
Beispiel #23
0
void QgsGrassNewMapset::loadRegions()
{
    QgsDebugMsg( "entered." );

    QString path = QgsApplication::pkgDataPath() + "/grass/locations.gml";
    QgsDebugMsg( QString( "load:%1" ).arg( path.toLocal8Bit().constData() ) );

    QFile file( path );

    if ( !file.exists() )
    {
        QMessageBox::warning( 0, tr( "Warning" ),
                              tr( "Regions file (%1) not found." ).arg( path ) );
        return;
    }
    if ( ! file.open( QIODevice::ReadOnly ) )
    {
        QMessageBox::warning( 0, tr( "Warning" ),
                              tr( "Cannot open locations file (%1)" ).arg( path ) );
        return;
    }

    QDomDocument doc( "gml:FeatureCollection" );
    QString err;
    int line, column;

    if ( !doc.setContent( &file,  &err, &line, &column ) )
    {
        QString errmsg = tr( "Cannot read locations file (%1):" ).arg( path )
                         + tr( "\n%1\nat line %2 column %3" ).arg( err ).arg( line ).arg( column );
        QgsDebugMsg( errmsg );
        QMessageBox::warning( 0, tr( "Warning" ), errmsg );
        file.close();
        return;
    }

    QDomElement docElem = doc.documentElement();
    QDomNodeList nodes = docElem.elementsByTagName( "gml:featureMember" );

    for ( int i = 0; i < nodes.count(); i++ )
    {
        QDomNode node = nodes.item( i );

        if ( node.isNull() )
        {
            continue;
        }

        QDomElement elem = node.toElement();
        QDomNodeList nameNodes = elem.elementsByTagName( "gml:name" );
        if ( nameNodes.count() == 0 )
            continue;
        if ( nameNodes.item( 0 ).isNull() )
            continue;

        QDomElement nameElem = nameNodes.item( 0 ).toElement();
        if ( nameElem.text().isNull() )
            continue;

        QDomNodeList envNodes = elem.elementsByTagName( "gml:Envelope" );
        if ( envNodes.count() == 0 )
            continue;
        if ( envNodes.item( 0 ).isNull() )
            continue;
        QDomElement envElem = envNodes.item( 0 ).toElement();

        QDomNodeList coorNodes = envElem.elementsByTagName( "gml:coordinates" );
        if ( coorNodes.count() == 0 )
            continue;
        if ( coorNodes.item( 0 ).isNull() )
            continue;
        QDomElement coorElem = coorNodes.item( 0 ).toElement();
        if ( coorElem.text().isNull() )
            continue;

        QStringList coor = coorElem.text().split( " ", QString::SkipEmptyParts );
        if ( coor.size() != 2 )
        {
            QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) );
            continue;
        }

        QStringList ll = coor[0].split( ",", QString::SkipEmptyParts );
        QStringList ur = coor[1].split( ",", QString::SkipEmptyParts );
        if ( ll.size() != 2 || ur.size() != 2 )
        {
            QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) );
            continue;
        }

        // Add region
        mRegionsComboBox->addItem( nameElem.text() );

        QgsPoint llp( ll[0].toDouble(), ll[1].toDouble() );
        mRegionsPoints.push_back( llp );
        QgsPoint urp( ur[0].toDouble(), ur[1].toDouble() );
        mRegionsPoints.push_back( urp );
    }

    file.close();
}
Beispiel #24
0
void CollapsibleGroup::dropEvent(QDropEvent *event)
{
    frame->setProperty("target", false);
    frame->setStyleSheet(frame->styleSheet());
    const QString effects = QString::fromUtf8(event->mimeData()->data("kdenlive/effectslist"));
    //event->acceptProposedAction();
    QDomDocument doc;
    doc.setContent(effects, true);
    QDomElement e = doc.documentElement();
    int ix = e.attribute("kdenlive_ix").toInt();
    if (ix == 0 || e.tagName() == "effectgroup") {
	if (e.tagName() == "effectgroup") {
	    // dropped a group on another group
	    QDomNodeList pastedEffects = e.elementsByTagName("effect");
	    if (pastedEffects.isEmpty() || m_subWidgets.isEmpty()) {
		// Buggy groups, should not happen
		event->ignore();
		return;
	    }
	    QList <int> pastedEffectIndexes;
	    QList <int> currentEffectIndexes;
	    EffectInfo pasteInfo;
	    pasteInfo.fromString(pastedEffects.at(0).toElement().attribute("kdenlive_info"));
	    if (pasteInfo.groupIndex == -1) {
		// Group dropped from effects list, add effect
		e.setAttribute("kdenlive_ix", m_subWidgets.last()->effectIndex());
		emit addEffect(e);
		event->setDropAction(Qt::CopyAction);
		event->accept();
		return;
	    }
	    // Moving group
	    for (int i = 0; i < pastedEffects.count(); i++) {
		pastedEffectIndexes << pastedEffects.at(i).toElement().attribute("kdenlive_ix").toInt();
	    }
	    for (int i = 0; i < m_subWidgets.count(); i++) {
		currentEffectIndexes << m_subWidgets.at(i)->effectIndex();
	    }
	    kDebug()<<"PASTING: "<<pastedEffectIndexes<<" TO "<<currentEffectIndexes;
	    if (pastedEffectIndexes.at(0) < currentEffectIndexes.at(0)) {
		// Pasting group after current one:
		emit moveEffect(pastedEffectIndexes, currentEffectIndexes.last(), pasteInfo.groupIndex, pasteInfo.groupName);
	    }
	    else {
		// Group moved before current one
		emit moveEffect(pastedEffectIndexes, currentEffectIndexes.first(), pasteInfo.groupIndex, pasteInfo.groupName);
	    }
	    event->setDropAction(Qt::MoveAction);
	    event->accept();
	    return;
	}
	// effect dropped from effects list, add it
	e.setAttribute("kdenlive_info", m_info.toString());
	if (!m_subWidgets.isEmpty()) {
	    e.setAttribute("kdenlive_ix", m_subWidgets.at(0)->effectIndex());
	}
	emit addEffect(e);
	event->setDropAction(Qt::CopyAction);
	event->accept();
	return;
    }
    if (m_subWidgets.isEmpty()) return;
    int new_index = m_subWidgets.last()->effectIndex();
    emit moveEffect(QList <int> () <<ix, new_index, m_info.groupIndex, m_title->text());
    event->setDropAction(Qt::MoveAction);
    event->accept();
}
Beispiel #25
0
void OsmNominatimRunner::handleSearchResult( 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, GeoDataPoint::Degree );
            GeoDataFeature::GeoDataVisualCategory category = GeoDataFeature::OsmVisualCategory( key + "=" + value );
            placemark->setVisualCategory( category );
            placemarks << placemark;
        }
    }
    
    emit searchFinished( placemarks );
}
Beispiel #26
0
bool QgsLayoutTable::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &, const QgsReadWriteContext & )
{
  mEmptyTableMode = QgsLayoutTable::EmptyTableMode( itemElem.attribute( QStringLiteral( "emptyTableMode" ), QStringLiteral( "0" ) ).toInt() );
  mEmptyTableMessage = itemElem.attribute( QStringLiteral( "emptyTableMessage" ), tr( "No matching records" ) );
  mShowEmptyRows = itemElem.attribute( QStringLiteral( "showEmptyRows" ), QStringLiteral( "0" ) ).toInt();
  if ( !QgsFontUtils::setFromXmlChildNode( mHeaderFont, itemElem, QStringLiteral( "headerFontProperties" ) ) )
  {
    mHeaderFont.fromString( itemElem.attribute( QStringLiteral( "headerFont" ), QString() ) );
  }
  mHeaderFontColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "headerFontColor" ), QStringLiteral( "0,0,0,255" ) ) );
  mHeaderHAlignment = QgsLayoutTable::HeaderHAlignment( itemElem.attribute( QStringLiteral( "headerHAlignment" ), QStringLiteral( "0" ) ).toInt() );
  mHeaderMode = QgsLayoutTable::HeaderMode( itemElem.attribute( QStringLiteral( "headerMode" ), QStringLiteral( "0" ) ).toInt() );
  if ( !QgsFontUtils::setFromXmlChildNode( mContentFont, itemElem, QStringLiteral( "contentFontProperties" ) ) )
  {
    mContentFont.fromString( itemElem.attribute( QStringLiteral( "contentFont" ), QString() ) );
  }
  mContentFontColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "contentFontColor" ), QStringLiteral( "0,0,0,255" ) ) );
  mCellMargin = itemElem.attribute( QStringLiteral( "cellMargin" ), QStringLiteral( "1.0" ) ).toDouble();
  mGridStrokeWidth = itemElem.attribute( QStringLiteral( "gridStrokeWidth" ), QStringLiteral( "0.5" ) ).toDouble();
  mHorizontalGrid = itemElem.attribute( QStringLiteral( "horizontalGrid" ), QStringLiteral( "1" ) ).toInt();
  mVerticalGrid = itemElem.attribute( QStringLiteral( "verticalGrid" ), QStringLiteral( "1" ) ).toInt();
  mShowGrid = itemElem.attribute( QStringLiteral( "showGrid" ), QStringLiteral( "1" ) ).toInt();
  mGridColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "gridColor" ), QStringLiteral( "0,0,0,255" ) ) );
  mBackgroundColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "backgroundColor" ), QStringLiteral( "255,255,255,0" ) ) );
  mWrapBehavior = QgsLayoutTable::WrapBehavior( itemElem.attribute( QStringLiteral( "wrapBehavior" ), QStringLiteral( "0" ) ).toInt() );

  //restore column specifications
  qDeleteAll( mColumns );
  mColumns.clear();
  QDomNodeList columnsList = itemElem.elementsByTagName( QStringLiteral( "displayColumns" ) );
  if ( !columnsList.isEmpty() )
  {
    QDomElement columnsElem = columnsList.at( 0 ).toElement();
    QDomNodeList columnEntryList = columnsElem.elementsByTagName( QStringLiteral( "column" ) );
    for ( int i = 0; i < columnEntryList.size(); ++i )
    {
      QDomElement columnElem = columnEntryList.at( i ).toElement();
      QgsLayoutTableColumn *column = new QgsLayoutTableColumn;
      column->readXml( columnElem );
      mColumns.append( column );
    }
  }

  //restore cell styles
  QDomNodeList stylesList = itemElem.elementsByTagName( QStringLiteral( "cellStyles" ) );
  if ( !stylesList.isEmpty() )
  {
    QDomElement stylesElem = stylesList.at( 0 ).toElement();

    QMap< CellStyleGroup, QString >::const_iterator it = mCellStyleNames.constBegin();
    for ( ; it != mCellStyleNames.constEnd(); ++it )
    {
      QString styleName = it.value();
      QDomNodeList styleList = stylesElem.elementsByTagName( styleName );
      if ( !styleList.isEmpty() )
      {
        QDomElement styleElem = styleList.at( 0 ).toElement();
        QgsLayoutTableStyle *style = mCellStyles.value( it.key() );
        if ( style )
          style->readXml( styleElem );
      }
    }
  }

  emit changed();
  return true;
}
Beispiel #27
0
void plotsDialog::on_dataSelectButton_clicked()
{
    QString pName = tabs->tabText(tabs->currentIndex());
    QString tableName;
    bool noTable = false;

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

        }
    }

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

                saveChanges();
                setupPlots(false);
            }

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

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

        }



    }
}
bool QgsCoordinateTransformContext::readXml( const QDomElement &element, const QgsReadWriteContext &, QStringList &missingTransforms )
{
  d.detach();
  d->mLock.lockForWrite();

  d->mSourceDestDatumTransforms.clear();
#if 0
  d->mSourceDatumTransforms.clear();
  d->mDestDatumTransforms.clear();
#endif

  const QDomNodeList contextNodes = element.elementsByTagName( QStringLiteral( "transformContext" ) );
  if ( contextNodes.count() < 1 )
  {
    d->mLock.unlock();
    return true;
  }

  missingTransforms.clear();
  bool result = true;

  const QDomElement contextElem = contextNodes.at( 0 ).toElement();

  // src/dest transforms
  const QDomNodeList srcDestNodes = contextElem.elementsByTagName( QStringLiteral( "srcDest" ) );
  for ( int i = 0; i < srcDestNodes.size(); ++i )
  {
    const QDomElement transformElem = srcDestNodes.at( i ).toElement();
    QString key1 = transformElem.attribute( QStringLiteral( "source" ) );
    QString key2 = transformElem.attribute( QStringLiteral( "dest" ) );

    QString value1 = transformElem.attribute( QStringLiteral( "sourceTransform" ) );
    QString value2 = transformElem.attribute( QStringLiteral( "destTransform" ) );

    Q_NOWARN_DEPRECATED_PUSH
    int datumId1 = -1;
    int datumId2 = -1;
    //warn if value1 or value2 is non-empty, yet no matching transform was found
    if ( !value1.isEmpty() )
    {
      datumId1 = QgsDatumTransform::projStringToDatumTransformId( value1 );
      if ( datumId1 < 0 )
      {
        result = false;
        missingTransforms << value1;
      }
    }
    if ( !value2.isEmpty() )
    {
      datumId2 = QgsDatumTransform::projStringToDatumTransformId( value2 );
      if ( datumId2 < 0 )
      {
        result = false;
        missingTransforms << value2;
      }
    }
    Q_NOWARN_DEPRECATED_POP

    d->mSourceDestDatumTransforms.insert( qMakePair( key1, key2 ), QgsDatumTransform::TransformPair( datumId1, datumId2 ) );
  }

#if 0
  // src transforms
  const QDomNodeList srcNodes = contextElem.elementsByTagName( QStringLiteral( "source" ) );
  for ( int i = 0; i < srcNodes .size(); ++i )
  {
    const QDomElement transformElem = srcNodes.at( i ).toElement();
    QString key = transformElem.attribute( QStringLiteral( "crs" ) );
    QString value = transformElem.attribute( QStringLiteral( "transform" ) );
    if ( value.isEmpty() )
      continue;

    int datumId = QgsCoordinateTransform::projStringToDatumTransformId( value );
    //TODO - throw warning if datumId is -1
    d->mSourceDatumTransforms.insert( key, datumId );
  }

  // dest transforms
  const QDomNodeList destNodes = contextElem.elementsByTagName( QStringLiteral( "dest" ) );
  for ( int i = 0; i < destNodes.size(); ++i )
  {
    const QDomElement transformElem = destNodes.at( i ).toElement();
    QString key = transformElem.attribute( QStringLiteral( "crs" ) );
    QString value = transformElem.attribute( QStringLiteral( "transform" ) );
    if ( value.isEmpty() )
      continue;

    int datumId = QgsCoordinateTransform::projStringToDatumTransformId( value );
    //TODO - throw warning if datumId is -1
    d->mDestDatumTransforms.insert( key, datumId );
  }
#endif

  d->mLock.unlock();
  return result;
}
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;
}
Beispiel #30
0
int QilexDoc::doc_insert_kinematic_chain(QDomElement kine_element)
{
   int error = 0;
   const char * buffer;

   QDomNodeList list;
   
   Rchain *kineengine = new Rchain;
   
   SoSeparator *kinechain = new SoSeparator;
   SoSeparator *kinetest = new SoSeparator;

   //Rchain *kineengine = new Rchain;
   SoTransform *pos_rot = new SoTransform;
   SbVec3f joinax;

   float joinangle;
   float pos_x, pos_y, pos_z, pos_rx, pos_ry, pos_rz;

   QString data, name;

   QDomNode node;
   QDomElement element;
   
   name = kine_element.attribute ("name", QString::null);
   data = kine_element.attribute ("kineengine", QString::null);
   // here put some stuff to select the kinechain engine

   data = kine_element.attribute ("pos_x", QString::null);
   pos_x = data.toFloat();

   data = kine_element.attribute ("pos_y", QString::null);
   pos_y = data.toFloat();
      
   data = kine_element.attribute ("pos_z", QString::null);
   pos_z = data.toFloat();

   data = kine_element.attribute ("pos_rx", QString::null);
   pos_rx = data.toFloat();

   data = kine_element.attribute ("pos_ry", QString::null);
   pos_ry = data.toFloat();

   data = kine_element.attribute ("pos_rz", QString::null);
   pos_rz = data.toFloat();

   data = kine_element.attribute ("pos_angle", QString::null);
   joinangle = data.toFloat();
      
   joinax.setValue(SbVec3f( pos_x, pos_y, pos_z));
   pos_rot->translation.setValue(joinax);
   pos_rot->rotation.setValue(SbVec3f(pos_rx, pos_ry, pos_rz), (float) rad((double)joinangle));

   list = kine_element.elementsByTagName ("kinechain");

   if (list.length() == 1)
   {
      node = list.item(0);
      element = node.toElement();
      error = kineengine->read_element_xml (element);
   }
   else
   { error =4;} // assigno un nombre diferrent de 0
      
   list = kine_element.elementsByTagName ("model3d");
   if (list.length() == 1)
   {
      node = list.item(0);
      element = node.toElement();
            
      data = element.attribute ("format", QString::null);
      // some stuff to take care about the format
            
      data = element.attribute ("size", QString::null);
      size_t size = (size_t)data.toULong(0,10);
      buffer = new char[size];
   
      data = element.text();
      buffer = data.ascii();

  /*    char *buffer2 = new char[size];
      for(unsigned i=0;i<size;i++)
         buffer2[i] = buffer[i];
    */                 
      SoInput input;
      input.setBuffer((void *)buffer, size);

      if (input.isValidBuffer())
      {
         kinechain = SoDB::readAll(&input);
         
         if (kinechain == NULL)
            error = 10;
      }
      else
         {error = 8;} //  assigno un nombre diferent de 0
   }
   else
   { error =9; }// assigno un nombre diferent de 0
      
   if (error == 0)
   {
      kinechain->ref();
      kinetest = (SoSeparator*)SoNode::getByName(name.latin1());

      if (kinetest==NULL)
      {
         //we need to put it in a buffer to write the xml file
         // if is Ok
         kinechain->insertChild(pos_rot, 0);
         kinechain->setName(name.latin1());
         
         error = doc_insert_kinematic_chain(kineengine, kinechain);
      }
   }
   else {error = 5;}
   
   
   return error;
}