Ejemplo n.º 1
0
QgsJoinDialog::QgsJoinDialog( QgsVectorLayer* layer, QList<QgsMapLayer*> alreadyJoinedLayers, QWidget * parent, Qt::WindowFlags f )
    : QDialog( parent, f )
    , mLayer( layer )
{
  setupUi( this );

  if ( !mLayer )
  {
    return;
  }
  // adds self layer to the joined layer (cannot join to itself)
  alreadyJoinedLayers.append( layer );

  mTargetFieldComboBox->setLayer( mLayer );

  mJoinLayerComboBox->setFilters( QgsMapLayerProxyModel::VectorLayer );
  mJoinLayerComboBox->setExceptedLayerList( alreadyJoinedLayers );
  connect( mJoinLayerComboBox, SIGNAL( layerChanged( QgsMapLayer* ) ), mJoinFieldComboBox, SLOT( setLayer( QgsMapLayer* ) ) );
  connect( mJoinLayerComboBox, SIGNAL( layerChanged( QgsMapLayer* ) ), this, SLOT( joinedLayerChanged( QgsMapLayer* ) ) );

  mCacheInMemoryCheckBox->setChecked( true );

  QgsMapLayer *joinLayer = mJoinLayerComboBox->currentLayer();
  if ( joinLayer && joinLayer->isValid() )
  {
    mJoinFieldComboBox->setLayer( joinLayer );
    joinedLayerChanged( joinLayer );
  }
}
Ejemplo n.º 2
0
//introduced in 1.8
QList<QgsMapLayer *> QgsMapLayerRegistry::addMapLayers(
  QList<QgsMapLayer *> theMapLayers,
  bool addToLegend,
  bool takeOwnership )
{
  QList<QgsMapLayer *> myResultList;
  for ( int i = 0; i < theMapLayers.size(); ++i )
  {
    QgsMapLayer * myLayer = theMapLayers.at( i );
    if ( !myLayer || !myLayer->isValid() )
    {
      QgsDebugMsg( "cannot add invalid layers" );
      continue;
    }
    //check the layer is not already registered!
    if ( !mMapLayers.contains( myLayer->id() ) )
    {
      mMapLayers[myLayer->id()] = myLayer;
      myResultList << mMapLayers[myLayer->id()];
      if ( takeOwnership )
        mOwnedLayers << myLayer;
      emit layerWasAdded( myLayer );
    }
  }
  if ( myResultList.count() > 0 )
  {
    emit layersAdded( myResultList );

    if ( addToLegend )
      emit legendLayersAdded( myResultList );
  }
  return myResultList;
} // QgsMapLayerRegistry::addMapLayers
Ejemplo n.º 3
0
//introduced in 1.8
QList<QgsMapLayer *> QgsMapLayerRegistry::addMapLayers(
  QList<QgsMapLayer *> theMapLayers,
  bool addToLegend )
{
  QList<QgsMapLayer *> myResultList;
  for ( int i = 0; i < theMapLayers.size(); ++i )
  {
    QgsMapLayer * myLayer = theMapLayers.at( i );
    if ( !myLayer || !myLayer->isValid() )
    {
      QgsDebugMsg( "cannot add invalid layers" );
      continue;
    }
    //check the layer is not already registered!
    QMap<QString, QgsMapLayer*>::iterator myIterator =
      mMapLayers.find( myLayer->id() );
    //if myIterator returns mMapLayers.end() then it
    //does not exist in registry and its safe to add it
    if ( myIterator == mMapLayers.end() )
    {
      mMapLayers[myLayer->id()] = myLayer;
      myResultList << mMapLayers[myLayer->id()];
      emit layerWasAdded( myLayer );
    }
  }
  if ( myResultList.count() > 0 )
  {
    emit layersAdded( myResultList );

    if ( addToLegend )
      emit legendLayersAdded( myResultList );
  }
  return myResultList;
} // QgsMapLayerRegistry::addMapLayers
Ejemplo n.º 4
0
bool QgsProject::addLayer( const QDomElement& layerElem, QList<QDomNode>& brokenNodes, QList< QPair< QgsVectorLayer*, QDomElement > >& vectorLayerList )
{
  QString type = layerElem.attribute( "type" );
  QgsDebugMsg( "Layer type is " + type );
  QgsMapLayer *mapLayer = NULL;

  if ( type == "vector" )
  {
    mapLayer = new QgsVectorLayer;
  }
  else if ( type == "raster" )
  {
    mapLayer = new QgsRasterLayer;
  }
  else if ( type == "plugin" )
  {
    QString typeName = layerElem.attribute( "name" );
    mapLayer = QgsPluginLayerRegistry::instance()->createLayer( typeName );
  }

  if ( !mapLayer )
  {
    QgsDebugMsg( "Unable to create layer" );

    return false;
  }

  Q_CHECK_PTR( mapLayer );

  // have the layer restore state that is stored in Dom node
  if ( mapLayer->readLayerXML( layerElem ) && mapLayer->isValid() )
  {
    emit readMapLayer( mapLayer, layerElem );

    QList<QgsMapLayer *> myLayers;
    myLayers << mapLayer;
    QgsMapLayerRegistry::instance()->addMapLayers( myLayers );
    QgsVectorLayer* vLayer = qobject_cast<QgsVectorLayer*>( mapLayer );
    if ( vLayer && vLayer->vectorJoins().size() > 0 )
    {
      vectorLayerList.push_back( qMakePair( vLayer, layerElem ) );
    }
    return true;
  }
  else
  {
    delete mapLayer;

    QgsDebugMsg( "Unable to load " + type + " layer" );
    brokenNodes.push_back( layerElem );
    return false;
  }
}
bool QgsGeoPackageCollectionItem::handleDrop( const QMimeData *data, Qt::DropAction )
{

  if ( !QgsMimeDataUtils::isUriList( data ) )
    return false;

  QString uri;

  QStringList importResults;
  bool hasError = false;

  // Main task
  std::unique_ptr< QgsConcurrentFileWriterImportTask > mainTask( new QgsConcurrentFileWriterImportTask( tr( "GeoPackage import" ) ) );
  QgsTaskList importTasks;

  const auto lst = QgsMimeDataUtils::decodeUriList( data );
  for ( const QgsMimeDataUtils::Uri &dropUri : lst )
  {
    // Check that we are not copying over self
    if ( dropUri.uri.startsWith( mPath ) )
    {
      importResults.append( tr( "You cannot import layer %1 over itself!" ).arg( dropUri.name ) );
      hasError = true;

    }
    else
    {
      QgsMapLayer *srcLayer = nullptr;
      bool owner;
      bool isVector = false;
      QString error;
      // Common checks for raster and vector
      // aspatial is treated like vector
      if ( dropUri.layerType == QStringLiteral( "vector" ) )
      {
        // open the source layer
        srcLayer = dropUri.vectorLayer( owner, error );
        isVector = true;
      }
      else if ( dropUri.layerType == QStringLiteral( "mesh" ) )
      {
        // unsupported
        hasError = true;
        continue;
      }
      else
      {
        srcLayer = dropUri.rasterLayer( owner, error );
      }
      if ( !srcLayer )
      {
        importResults.append( tr( "%1: %2" ).arg( dropUri.name, error ) );
        hasError = true;
        continue;
      }

      if ( srcLayer->isValid() )
      {
        uri = mPath;
        QgsDebugMsgLevel( "URI " + uri, 3 );

        // check if the destination layer already exists
        bool exists = false;
        const auto c( children() );
        for ( const QgsDataItem *child : c )
        {
          if ( child->name() == dropUri.name )
          {
            exists = true;
          }
        }

        if ( exists && !isVector )
        {
          QMessageBox::warning( nullptr, tr( "Cannot Overwrite Layer" ),
                                tr( "Destination layer <b>%1</b> already exists. Overwriting with raster layers is not currently supported." ).arg( dropUri.name ) );
        }
        else if ( ! exists || QMessageBox::question( nullptr, tr( "Overwrite Layer" ),
                  tr( "Destination layer <b>%1</b> already exists. Do you want to overwrite it?" ).arg( dropUri.name ), QMessageBox::Yes |  QMessageBox::No ) == QMessageBox::Yes )
        {
          if ( isVector ) // Import vectors and aspatial
          {
            QgsVectorLayer *vectorSrcLayer = qobject_cast < QgsVectorLayer * >( srcLayer );
            QVariantMap options;
            options.insert( QStringLiteral( "driverName" ), QStringLiteral( "GPKG" ) );
            options.insert( QStringLiteral( "update" ), true );
            options.insert( QStringLiteral( "overwrite" ), true );
            options.insert( QStringLiteral( "layerName" ), dropUri.name );
            options.insert( QStringLiteral( "forceSinglePartGeometryType" ), true );
            QgsVectorLayerExporterTask *exportTask = new QgsVectorLayerExporterTask( vectorSrcLayer, uri, QStringLiteral( "ogr" ), vectorSrcLayer->crs(), options, owner );
            mainTask->addSubTask( exportTask, importTasks );
            importTasks << exportTask;
            // when export is successful:
            connect( exportTask, &QgsVectorLayerExporterTask::exportComplete, this, [ = ]()
            {
              // this is gross - TODO - find a way to get access to messageBar from data items
              QMessageBox::information( nullptr, tr( "Import to GeoPackage database" ), tr( "Import was successful." ) );
              refreshConnections();
            } );

            // when an error occurs:
            connect( exportTask, &QgsVectorLayerExporterTask::errorOccurred, this, [ = ]( int error, const QString & errorMessage )
            {
              if ( error != QgsVectorLayerExporter::ErrUserCanceled )
              {
                QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
                output->setTitle( tr( "Import to GeoPackage database" ) );
                output->setMessage( tr( "Failed to import some vector layers!\n\n" ) + errorMessage, QgsMessageOutput::MessageText );
                output->showMessage();
              }
            } );

          }
          else  // Import raster
          {
            QgsGeoPackageRasterWriterTask  *exportTask = new QgsGeoPackageRasterWriterTask( dropUri, mPath );
            mainTask->addSubTask( exportTask, importTasks );
            importTasks << exportTask;
            // when export is successful:
            connect( exportTask, &QgsGeoPackageRasterWriterTask::writeComplete, this, [ = ]()
            {
              // this is gross - TODO - find a way to get access to messageBar from data items
              QMessageBox::information( nullptr, tr( "Import to GeoPackage database" ), tr( "Import was successful." ) );
              refreshConnections();
            } );

            // when an error occurs:
            connect( exportTask, &QgsGeoPackageRasterWriterTask::errorOccurred, this, [ = ]( QgsGeoPackageRasterWriter::WriterError error, const QString & errorMessage )
            {
              if ( error != QgsGeoPackageRasterWriter::WriterError::ErrUserCanceled )
              {
                QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
                output->setTitle( tr( "Import to GeoPackage database" ) );
                output->setMessage( tr( "Failed to import some raster layers!\n\n" ) + errorMessage, QgsMessageOutput::MessageText );
                output->showMessage();
              }
              // Always try to delete the imported raster, in case the gpkg has been left
              // in an inconsistent status. Ignore delete errors.
              QString deleteErr;
              deleteGeoPackageRasterLayer( QStringLiteral( "GPKG:%1:%2" ).arg( mPath, dropUri.name ), deleteErr );
            } );

          }
        } // do not overwrite
      }
      else
      {
        importResults.append( tr( "%1: Not a valid layer!" ).arg( dropUri.name ) );
        hasError = true;
      }
    } // check for self copy
  } // for each

  if ( hasError )
  {
    QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
    output->setTitle( tr( "Import to GeoPackage database" ) );
    output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( QStringLiteral( "\n" ) ), QgsMessageOutput::MessageText );
    output->showMessage();
  }
  if ( ! importTasks.isEmpty() )
  {
    QgsApplication::taskManager()->addTask( mainTask.release() );
  }
  return true;
}
void QgsBrowserDockWidget::itemClicked( const QModelIndex& index )
{
  QgsDataItem *item = mModel->dataItem( index );
  if ( !item )
    return;

  QgsLayerItem *layerItem = qobject_cast<QgsLayerItem*>( mModel->dataItem( index ) );
  if ( layerItem == NULL )
    return;

  QString uri = layerItem->uri();
  if ( uri.isEmpty() )
    return;

  QgsMapLayer::LayerType type = layerItem->mapLayerType();
  QString providerKey = layerItem->providerKey();

  QgsDebugMsg( providerKey + " : " + uri );
  QgsMapLayer* layer = NULL;
  if ( type == QgsMapLayer::VectorLayer )
  {
    layer = new QgsVectorLayer( uri, layerItem->name(), providerKey );
  }
  if ( type == QgsMapLayer::RasterLayer )
  {
    // This should go to WMS provider
    QStringList URIParts = uri.split( "|" );
    QString rasterLayerPath = URIParts.at( 0 );
    QStringList layers;
    QStringList styles;
    QString format;
    QString crs;
    for ( int i = 1 ; i < URIParts.size(); i++ )
    {
      QString part = URIParts.at( i );
      int pos = part.indexOf( "=" );
      QString field = part.left( pos );
      QString value = part.mid( pos + 1 );

      if ( field == "layers" )
        layers = value.split( "," );
      if ( field == "styles" )
        styles = value.split( "," );
      if ( field == "format" )
        format = value;
      if ( field == "crs" )
        crs = value;
    }
    QgsDebugMsg( "rasterLayerPath = " + rasterLayerPath );
    QgsDebugMsg( "layers = " + layers.join( " " ) );

    layer = new QgsRasterLayer( 0, rasterLayerPath, layerItem->name(), providerKey, layers, styles, format, crs );
  }

  if ( !layer || !layer->isValid() )
  {
    qDebug( "No layer" );
    delete layer;
    return;
  }

  // add layer to the application
  QgsMapLayerRegistry::instance()->addMapLayer( layer );
}
Ejemplo n.º 7
0
QgsMapLayer *QgsHostedVDSBuilder::createMapLayer( const QDomElement &elem,
    const QString &layerName,
    QList<QTemporaryFile *> &filesToRemove,
    QList<QgsMapLayer *> &layersToRemove,
    bool allowCaching ) const
{
  Q_UNUSED( filesToRemove );
  if ( elem.isNull() )
  {
    return nullptr;
  }

  QString providerType = elem.attribute( QStringLiteral( "providerType" ), QStringLiteral( "not found" ) );
  QString uri = elem.attribute( QStringLiteral( "uri" ), QStringLiteral( "not found" ) );

  if ( providerType == QLatin1String( "not found" ) || uri == QLatin1String( "not found" ) )
  {
    QgsDebugMsg( "error, provider type not found" );
    return nullptr;
  }

  QgsMapLayer *ml = nullptr;

  if ( allowCaching ) //take layer from cache if allowed
  {
    QgsDebugMsg( "Taking hostedvds layer from cash" );
    ml = QgsMSLayerCache::instance()->searchLayer( uri, layerName );
  }

  if ( !ml )
  {
    QgsDebugMsg( "hostedvds layer not in cash, so create and insert it" );
    ml = new QgsVectorLayer( uri, layerNameFromUri( uri ), providerType );

    if ( !ml || !ml->isValid() )
    {
      QgsDebugMsg( "error, VectorLayer is 0 or invalid" );
      delete ml;
      return nullptr;
    }

    if ( allowCaching )
    {
      QgsMSLayerCache::instance()->insertLayer( uri, layerName, ml );
    }
    else
    {
      layersToRemove.push_back( ml );
    }
  }

  //projection
  if ( ml )
  {
    QString epsg = elem.attribute( QStringLiteral( "epsg" ) );
    if ( !epsg.isEmpty() )
    {
      bool conversionOk;
      int epsgnr = epsg.toInt( &conversionOk );
      if ( conversionOk )
      {
        //set spatial ref sys
        QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( epsgnr ) );
        ml->setCrs( srs );
      }
    }
  }

  return ml;
}
Ejemplo n.º 8
0
QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer(
  const QDomElement& elem,
  const QString& layerName,
  QList<QTemporaryFile*>& filesToRemove,
  QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  if ( elem.isNull() )
  {
    return nullptr;
  }

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

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

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

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

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


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

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

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

  return result;
}