Example #1
0
HeatmapGui::HeatmapGui( QWidget* parent, Qt::WindowFlags fl, QMap<QString, QVariant>* temporarySettings )
    : QDialog( parent, fl ),
    mRows( 500 )
{
  setupUi( this );

  QgsDebugMsg( QString( "Creating Heatmap Dialog" ) );

  blockAllSignals( true );

  mHeatmapSessionSettings = temporarySettings;

  // Adding point layers to the inputLayerCombo
  QString defaultLayer = mHeatmapSessionSettings->value( QString( "lastInputLayer" ) ).toString();
  int defaultLayerIndex = 0;
  bool usingLastInputLayer = false;
  int currentIndex = -1;
  foreach ( QgsMapLayer *l, QgsMapLayerRegistry::instance()->mapLayers() )
  {
    QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( l );
    if ( !vl || vl->geometryType() != QGis::Point )
      continue;

    currentIndex++;
    inputLayerCombo->addItem( vl->name(), vl->id() );
    if ( vl->id() == defaultLayer )
    {
      // if this layer is the same layer as a heatmap was last generated using,
      // then default to this layer
      usingLastInputLayer = true;
      defaultLayerIndex = currentIndex;
    }
  }
QgsInterpolationDialog::QgsInterpolationDialog( QWidget* parent, QgisInterface* iface ): QDialog( parent ), mIface( iface ), mInterpolatorDialog( nullptr )
{
  setupUi( this );

  QSettings settings;
  restoreGeometry( settings.value( "/Interpolation/geometry" ).toByteArray() );

  //enter available layers into the combo box
  QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers();
  QMap<QString, QgsMapLayer*>::iterator layer_it = mapLayers.begin();

  for ( ; layer_it != mapLayers.end(); ++layer_it )
  {
    QgsVectorLayer* vl = qobject_cast<QgsVectorLayer *>( layer_it.value() );
    if ( vl )
    {
      mInputLayerComboBox->insertItem( 0, vl->name() );
    }
  }

  //default resolution 300 * 300
  mNumberOfColumnsSpinBox->setValue( 300 );
  mNumberOfRowsSpinBox->setValue( 300 );

  //only inverse distance weighting available for now
  mInterpolationMethodComboBox->insertItem( 0, tr( "Triangular interpolation (TIN)" ) );
  mInterpolationMethodComboBox->insertItem( 1, tr( "Inverse Distance Weighting (IDW)" ) );
  mInterpolationMethodComboBox->setCurrentIndex( settings.value( "/Interpolation/lastMethod", 0 ).toInt() );

  enableOrDisableOkButton();
}
void QgsVectorLayerJoinBuffer::updateFields( QgsFields& fields )
{
  QList< QgsVectorJoinInfo>::const_iterator joinIt = mVectorJoins.constBegin();
  for ( int joinIdx = 0 ; joinIt != mVectorJoins.constEnd(); ++joinIt, ++joinIdx )
  {
    QgsVectorLayer* joinLayer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( joinIt->joinLayerId ) );
    if ( !joinLayer )
    {
      continue;
    }

    joinIt->tmpTargetField = fields.indexFromName( joinIt->targetFieldName );

    const QgsFields& joinFields = joinLayer->pendingFields();
    joinIt->tmpJoinField = joinFields.indexFromName( joinIt->joinFieldName );

    for ( int idx = 0; idx < joinFields.count(); ++idx )
    {
      //skip the join field to avoid double field names (fields often have the same name)
      if ( joinFields[idx].name() != joinIt->joinFieldName )
      {
        QgsField f = joinFields[idx];
        f.setName( joinLayer->name() + "_" + f.name() );
        fields.append( f, QgsFields::OriginJoin, idx + ( joinIdx*1000 ) );
      }
    }
  }
}
void QgsZonalStatisticsDialog::insertAvailableLayers()
{
  //insert available raster layers
  //enter available layers into the combo box
  QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers();
  QMap<QString, QgsMapLayer*>::iterator layer_it = mapLayers.begin();

  for ( ; layer_it != mapLayers.end(); ++layer_it )
  {
    QgsRasterLayer* rl = dynamic_cast<QgsRasterLayer*>( layer_it.value() );
    if ( rl )
    {
      QgsRasterDataProvider* rp = rl->dataProvider();
      if ( rp && rp->name() == "gdal" )
      {
        mRasterLayerComboBox->addItem( rl->name(), QVariant( rl->id() ) );
      }
    }
    else
    {
      QgsVectorLayer* vl = dynamic_cast<QgsVectorLayer*>( layer_it.value() );
      if ( vl && vl->geometryType() == QGis::Polygon )
      {
        QgsVectorDataProvider* provider  = vl->dataProvider();
        if ( provider->capabilities() & QgsVectorDataProvider::AddAttributes )
        {
          mPolygonLayerComboBox->addItem( vl->name(), QVariant( vl->id() ) );
        }
      }
    }
  }
}
QgsAttributeTypeDialog::QgsAttributeTypeDialog( QgsVectorLayer *vl )
    : QDialog()
    , mLayer( vl )
{
  setupUi( this );
  tableWidget->insertRow( 0 );
  connect( selectionListWidget, SIGNAL( currentRowChanged( int ) ), this, SLOT( setStackPage( int ) ) );
  connect( removeSelectedButton, SIGNAL( clicked() ), this, SLOT( removeSelectedButtonPushed() ) );
  connect( loadFromLayerButton, SIGNAL( clicked() ), this, SLOT( loadFromLayerButtonPushed() ) );
  connect( loadFromCSVButton, SIGNAL( clicked() ), this, SLOT( loadFromCSVButtonPushed() ) );
  connect( tableWidget, SIGNAL( cellChanged( int, int ) ), this, SLOT( vCellChanged( int, int ) ) );
  connect( valueRelationEditExpression, SIGNAL( clicked() ), this, SLOT( editValueRelationExpression() ) );

  QMapIterator<QString, QgsEditorWidgetFactory*> i( QgsEditorWidgetRegistry::instance()->factories() );
  while ( i.hasNext() )
  {
    i.next();
    QListWidgetItem* item = new QListWidgetItem( selectionListWidget );
    item->setText( i.value()->name() );
    item->setData( Qt::UserRole, i.key() );
    selectionListWidget->addItem( item );
  }

  valueRelationLayer->clear();
  foreach ( QgsMapLayer *l, QgsMapLayerRegistry::instance()->mapLayers() )
  {
    QgsVectorLayer *vl = qobject_cast< QgsVectorLayer * >( l );
    if ( vl )
      valueRelationLayer->addItem( vl->name(), vl->id() );
  }
void QgsOfflineEditingPluginGui::updateLayerList( bool filterEditableLayers )
{
  ui_layerList->clear();

  QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers();
  for ( QMap<QString, QgsMapLayer*>::iterator layer_it = mapLayers.begin() ; layer_it != mapLayers.end(); ++layer_it )
  {
    if ( layer_it.value()->type() == QgsMapLayer::VectorLayer )
    {
      QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( layer_it.value() );

      bool showLayer = true;
      if ( filterEditableLayers )
      {
        int cap = layer->dataProvider()->capabilities();
        showLayer = ( cap & QgsVectorDataProvider::AddFeatures ) &&
                    ( cap & QgsVectorDataProvider::DeleteFeatures ) &&
                    ( cap & QgsVectorDataProvider::ChangeAttributeValues ) &&
                    ( cap & QgsVectorDataProvider::AddAttributes ) &&
                    ( cap & QgsVectorDataProvider::ChangeGeometries );
      }
      if ( showLayer )
      {
        QListWidgetItem* item = new QListWidgetItem( layer->name(), ui_layerList );
        item->setData( Qt::UserRole, QVariant( layer_it.key() ) );
      }
    }
  }
}
void QgsVectorLayerJoinBuffer::updateFields( QgsFields& fields )
{
  QList< QgsVectorJoinInfo>::const_iterator joinIt = mVectorJoins.constBegin();
  for ( int joinIdx = 0 ; joinIt != mVectorJoins.constEnd(); ++joinIt, ++joinIdx )
  {
    QgsVectorLayer* joinLayer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( joinIt->joinLayerId ) );
    if ( !joinLayer )
    {
      continue;
    }

    const QgsFields& joinFields = joinLayer->pendingFields();
    QString joinFieldName;
    if ( joinIt->joinFieldName.isEmpty() && joinIt->joinFieldIndex >= 0 && joinIt->joinFieldIndex < joinFields.count() )
      joinFieldName = joinFields.field( joinIt->joinFieldIndex ).name();  //for compatibility with 1.x
    else
      joinFieldName = joinIt->joinFieldName;

    for ( int idx = 0; idx < joinFields.count(); ++idx )
    {
      //skip the join field to avoid double field names (fields often have the same name)
      if ( joinFields[idx].name() != joinFieldName )
      {
        QgsField f = joinFields[idx];
        f.setName( joinLayer->name() + "_" + f.name() );
        fields.append( f, QgsFields::OriginJoin, idx + ( joinIdx*1000 ) );
      }
    }
  }
}
void QgsAttributeTypeLoadDialog::fillLayerList()
{
  layerComboBox->clear();
  foreach ( QgsMapLayer *l, QgsMapLayerRegistry::instance()->mapLayers() )
  {
    QgsVectorLayer *vl = qobject_cast< QgsVectorLayer * >( l );
    if ( vl )
      layerComboBox->addItem( vl->name(), vl->id() );
  }
Example #9
0
void QgsLegendModel::updateSymbolV2ItemText( QStandardItem* symbolItem )
{
  QgsComposerSymbolV2Item* sv2Item = dynamic_cast<QgsComposerSymbolV2Item*>( symbolItem );
  if ( !sv2Item ) return;

  QgsComposerLayerItem* lItem = dynamic_cast<QgsComposerLayerItem*>( sv2Item->parent() );
  if ( !lItem ) return;

  QgsMapLayer* mapLayer = QgsMapLayerRegistry::instance()->mapLayer( lItem->layerID() );
  if ( !mapLayer ) return;

  QgsVectorLayer* vLayer = qobject_cast<QgsVectorLayer*>( mapLayer );
  if ( !vLayer ) return;

  QgsFeatureRendererV2* renderer = vLayer->rendererV2();
  if ( !renderer ) return;

  if ( lItem->showFeatureCount() ) vLayer->countSymbolFeatures();

  QgsLegendSymbolList symbolList = renderer->legendSymbolItems();

  QPair<QString, QgsSymbolV2*> symbol = symbolList.value( symbolItem->row() );

  QString label = sv2Item->userText().isEmpty() ? symbol.first : sv2Item->userText();

  if ( renderer->type() == "singleSymbol" )
  {
    if ( !sv2Item->userText().isEmpty() )
    {
      label = sv2Item->userText();
    }
    else if ( !lItem->userText().isEmpty() )
    {
      label = lItem->userText();
    }
    else if ( !vLayer->title().isEmpty() )
    {
      label = vLayer->title();
    }
    else
    {
      label = vLayer->name();
    }
  }

  if ( lItem->showFeatureCount() )
  {
    // Add counts to multi symbols layers only or labeled single symbols,
    // so that single symbol layers are still drawn on single line
    if ( symbolList.size() > 1 || !label.isEmpty() )
    {
      label += QString( " [%1]" ).arg( vLayer->featureCount( symbol.second ) );
    }
  }
  symbolItem->setText( label );
}
QgsVirtualLayerDefinition QgsVirtualLayerDefinitionUtils::fromJoinedLayer( QgsVectorLayer *layer )
{
  QgsVirtualLayerDefinition def;

  QStringList leftJoins;
  QStringList columns;

  // add the geometry column if the layer is spatial
  if ( layer->isSpatial() )
    columns << "t.geometry";

  // look for the uid
  QgsFields fields = layer->dataProvider()->fields();
  {
    QgsAttributeList pk = layer->dataProvider()->pkAttributeIndexes();
    if ( pk.size() == 1 )
    {
      def.setUid( fields.field( pk[0] ).name() );
    }
    else
    {
      // find an uid name
      QString uid = QStringLiteral( "uid" );
      while ( fields.lookupField( uid ) != -1 )
        uid += QLatin1String( "_" ); // add "_" each time this name already exists

      // add a column
      columns << "t.rowid AS " + uid;
      def.setUid( uid );
    }
  }
  const QgsFields providerFields = layer->dataProvider()->fields();
  for ( const auto &f : providerFields )
  {
    columns << "t.\"" + f.name() + "\"";
  }

  int joinIdx = 0;
  Q_FOREACH ( const QgsVectorLayerJoinInfo &join, layer->vectorJoins() )
  {
    QString joinName = QStringLiteral( "j%1" ).arg( ++joinIdx );
    QgsVectorLayer *joinedLayer = join.joinLayer();
    if ( !joinedLayer )
      continue;
    QString prefix = join.prefix().isEmpty() ? joinedLayer->name() + "_" : join.prefix();

    leftJoins << QStringLiteral( "LEFT JOIN \"%1\" AS %2 ON t.\"%5\"=%2.\"%3\"" ).arg( joinedLayer->id(), joinName, join.joinFieldName(), join.targetFieldName() );
    if ( join.joinFieldNamesSubset() )
    {
      Q_FOREACH ( const QString &f, *join.joinFieldNamesSubset() )
      {
        columns << joinName + ".\"" + f + "\" AS \"" + prefix + f + "\"";
      }
    }
    else
    {
void QgsGlobePluginDialog::updatePointLayers()
{
  modelLayerCombo->clear();
  QList<QgsVectorLayer*> layers = pointLayers();
  QListIterator<QgsVectorLayer*> it( layers );
  while ( it.hasNext() )
  {
    QgsVectorLayer* layer = it.next();
    modelLayerCombo->addItem( layer->name() );
  }
}
Example #12
0
void QgsGrassPlugin::onEditingStarted()
{
  QgsDebugMsg( "Entered" );
  QgsVectorLayer *vectorLayer = qobject_cast<QgsVectorLayer *>( sender() );
  if ( !vectorLayer )
    return;
  QgsDebugMsg( "started editing of layer " + vectorLayer->name() );

  // Set editing renderer
  QgsGrassProvider* grassProvider = dynamic_cast<QgsGrassProvider*>( vectorLayer->dataProvider() );
  if ( !grassProvider )
    return;

  QgsRendererV2Registry::instance()->addRenderer( new QgsRendererV2Metadata( "grassEdit",
      QObject::tr( "GRASS Edit" ),
      QgsGrassEditRenderer::create,
      QIcon(),
      QgsGrassEditRendererWidget::create ) );

  QgsGrassEditRenderer *renderer = new QgsGrassEditRenderer();

  mOldStyles[vectorLayer] = vectorLayer->styleManager()->currentStyle();

  // Because the edit style may be stored to project:
  // - do not translate because it may be loaded in QGIS running with different language
  // - do not change the name until really necessary because it could not be found in project
  QString editStyleName = "GRASS Edit"; // should not be translated

  if ( vectorLayer->styleManager()->styles().contains( editStyleName ) )
  {
    QgsDebugMsg( editStyleName + " style exists -> set as current" );
    vectorLayer->styleManager()->setCurrentStyle( editStyleName );
  }
  else
  {
    QgsDebugMsg( "create and set style " + editStyleName );
    vectorLayer->styleManager()->addStyleFromLayer( editStyleName );

    //vectorLayer->styleManager()->addStyle( editStyleName, QgsMapLayerStyle() );
    vectorLayer->styleManager()->setCurrentStyle( editStyleName );
    vectorLayer->setRendererV2( renderer );
  }

  grassProvider->startEditing( vectorLayer );
  vectorLayer->updateFields();

  connect( vectorLayer, SIGNAL( editingStopped() ), SLOT( onEditingStopped() ) );

  resetEditActions();
}
Example #13
0
HeatmapGui::HeatmapGui( QWidget* parent, Qt::WFlags fl )
    : QDialog( parent, fl )
{
  setupUi( this );

  // Adding point layers to the mInputVectorCombo
  foreach( QgsMapLayer *l, QgsMapLayerRegistry::instance()->mapLayers() )
  {
    QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( l );
    if ( !vl || vl->geometryType() != QGis::Point )
      continue;

    mInputVectorCombo->addItem( vl->name(), vl->id() );
  }
void QgsVectorLayerProperties::addJoinToTreeWidget( const QgsVectorJoinInfo& join )
{
  QTreeWidgetItem* joinItem = new QTreeWidgetItem();

  QgsVectorLayer* joinLayer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( join.joinLayerId ) );
  if ( !joinLayer )
  {
    return;
  }

  joinItem->setText( 0, joinLayer->name() );
  joinItem->setData( 0, Qt::UserRole, join.joinLayerId );
  joinItem->setText( 1, join.joinFieldName );
  joinItem->setText( 2, join.targetFieldName );

  mJoinTreeWidget->addTopLevelItem( joinItem );
}
QgsVectorLayer* RgLineVectorLayerSettingsWidget::selectedLayer()
{
  QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers();
  QMap<QString, QgsMapLayer*>::iterator layer_it = mapLayers.begin();

  for ( ; layer_it != mapLayers.end(); ++layer_it )
  {
    QgsVectorLayer* vl = dynamic_cast<QgsVectorLayer*>( layer_it.value() );
    if ( !vl )
      continue;
    if ( vl->geometryType() != QGis::Line )
      continue;
    if ( vl->name() == mcbLayers->currentText() )
      return vl;
  }

  return NULL;
} // RgLineVectorLayerSettingsWidget::setlectedLayer()
QgsAttributeTypeDialog::QgsAttributeTypeDialog( QgsVectorLayer *vl )
    : QDialog()
    , mLayer( vl )
{
  setupUi( this );
  tableWidget->insertRow( 0 );
  connect( selectionComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( setStackPage( int ) ) );
  connect( removeSelectedButton, SIGNAL( clicked() ), this, SLOT( removeSelectedButtonPushed() ) );
  connect( loadFromLayerButton, SIGNAL( clicked() ), this, SLOT( loadFromLayerButtonPushed() ) );
  connect( loadFromCSVButton, SIGNAL( clicked() ), this, SLOT( loadFromCSVButtonPushed() ) );
  connect( tableWidget, SIGNAL( cellChanged( int, int ) ), this, SLOT( vCellChanged( int, int ) ) );

  valueRelationLayer->clear();
  foreach( QgsMapLayer *l, QgsMapLayerRegistry::instance()->mapLayers() )
  {
    QgsVectorLayer *vl = qobject_cast< QgsVectorLayer * >( l );
    if ( vl )
      valueRelationLayer->addItem( vl->name(), vl->id() );
  }
Example #17
0
QString QgsSpatialQueryDialog::getDescriptionLayerShow( bool isTarget )
{
  QgsVectorLayer* lyr = NULL;
  QCheckBox * checkBox = NULL;
  if ( isTarget )
  {
    lyr = mLayerTarget;
    checkBox = ckbUsingSelectedTarget;
  }
  else
  {
    lyr = mLayerReference;
    checkBox = ckbUsingSelectedReference;
  }

  QString sDescFeatures = checkBox->isChecked()
                          ? tr( "%1 of %2" ).arg( lyr->selectedFeatureCount() ).arg( lyr->featureCount() )
                          : tr( "all = %1" ).arg( lyr->featureCount() );

  return QString( "%1 (%2)" ).arg( lyr->name() ).arg( sDescFeatures );
} // QString QgsSpatialQueryDialog::getDescriptionLayerShow(bool isTarget)
Example #18
0
RgExportDlg::RgExportDlg( QWidget* parent, Qt::WindowFlags fl )
    : QDialog( parent, fl )
{
  // create base widgets;
  setWindowTitle( tr( "Export feature" ) );
  QVBoxLayout *v = new QVBoxLayout( this );

  QHBoxLayout *h = new QHBoxLayout();
  QLabel *l = new QLabel( tr( "Select destination layer" ), this );
  h->addWidget( l );
  mcbLayers = new QComboBox( this );
  h->addWidget( mcbLayers );
  v->addLayout( h );

  QDialogButtonBox *bb = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this );
  connect( bb, SIGNAL( accepted() ), this, SLOT( on_buttonBox_accepted() ) );
  connect( bb, SIGNAL( rejected() ), this, SLOT( on_buttonBox_rejected() ) );
  v->addWidget( bb );

  //fill list of layers
  mcbLayers->insertItem( 0, tr( "New temporary layer" ), QVariant( "-1" ) );

  QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers();
  QMap<QString, QgsMapLayer*>::iterator layer_it = mapLayers.begin();

  for ( ; layer_it != mapLayers.end(); ++layer_it )
  {
    QgsVectorLayer* vl = dynamic_cast<QgsVectorLayer*>( layer_it.value() );
    if ( !vl )
      continue;
    if ( vl->geometryType() != QGis::Line )
      continue;
    mcbLayers->insertItem( 0, vl->name(), QVariant( vl->id() ) );
  }

} // RgSettingsDlg::RgSettingsDlg()
Example #19
0
QString QgsSpatialQueryDialog::getDescriptionInvalidFeaturesShow( bool isTarget )
{
  QgsVectorLayer* lyr = NULL;
  QCheckBox* checkBox = NULL;
  int totalInvalid = 0;
  if ( isTarget )
  {
    lyr = mLayerTarget;
    checkBox = ckbUsingSelectedTarget;
    totalInvalid = mFeatureInvalidTarget.size();
  }
  else
  {
    lyr = mLayerReference;
    checkBox = ckbUsingSelectedReference;
    totalInvalid = mFeatureInvalidReference.size();
  }

  QString sDescFeatures = checkBox->isChecked()
                          ? tr( "%1 of %2(selected features)" ).arg( totalInvalid ).arg( lyr->selectedFeatureCount() )
                          : tr( "%1 of %2" ).arg( totalInvalid ).arg( lyr->featureCount() );

  return QString( "%1: %2" ).arg( lyr->name() ).arg( sDescFeatures );
} // QString QgsSpatialQueryDialog::getDescriptionInvalidFeatures(bool isTarget)
Example #20
0
void QgsQuickPrint::printMap()
{
  if ( mOutputFileName.isEmpty() )
  {
    return;
  }
  if ( mpMapRenderer == NULL )
  {
    return;
  }
  //ensure the user never omitted the extension from the file name
  if ( !mOutputFileName.toUpper().endsWith( ".PDF" ) )
  {
    mOutputFileName += ".pdf";
  }

  // Initialising the printer this way lets us find out what
  // the screen resolution is which we store and then
  // reset the resolution of the printer after that...
  QPrinter myPrinter( QPrinter::ScreenResolution );

  // Try to force the printer resolution to 300dpi
  // to get past platform specific defaults in printer
  // resolution...
  //
  int myPrintResolutionDpi = 300;
  myPrinter.setResolution( myPrintResolutionDpi );
  myPrinter.setOutputFormat( QPrinter::PdfFormat );
  QgsDebugMsg( QString( "Printing to page size %1" ).arg( pageSizeToString( mPageSize ) ) );
  myPrinter.setPageSize( mPageSize );
  myPrinter.setOutputFileName( mOutputFileName );
  myPrinter.setOrientation( QPrinter::Landscape );
  myPrinter.setDocName( "quickprint Report" );
  QPainter myPrintPainter( &myPrinter );
  myPrintPainter.setPen( Qt::gray );
  myPrintPainter.setBrush( Qt::white );
  // This is what we are aiming for:
  // a
  // +-(1)------ Acme Maps (2) --------------------------------------+
  // |b         12/01/2007 (3)                                         |
  // |                           Earthquakes (4)                       |
  // | +--(5)--------------------------------------------------------+ |
  // | |c                                                            | |
  // | | +-(6)---------------------------------------+  +~(7)~~~~~~+ | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | |                                           |  |          | | |
  // | | +-------------------------------------------+  +~~~~~~~~~~+ | |
  // | |                                                             | |
  // | +-------------------------------------------------------------+ |
  // |                                                                 |
  // |   +-(8)-----+ +-(9-)----+ +-(10)----+                 /|\       |
  // |   |         | |Copyright| |         |                / | \      |
  // |   |         | |  2008   | |         |                  |(11)    |
  // |   +---------+ +---------+ +---------+                           |
  // |                                                  +~(12)~~~~~~+  |
  // +-----------------------------------------------------------------+
  //
  // 1) PageBorder              8) Logo1
  // 2) PageTitle               9) CopyrightText
  // 3) MapDate                 10) Logo2
  // 4) MapTitle                11) NorthArrow
  // 5) MapFrame                12) ScaleBar
  // 6) MapPixmap
  // 7) LegendPixmap
  // a OriginXY
  // b HorizontalSpacing
  // c VerticalSpacing

  //
  // Note: Different operating systems will use different
  // page resolutions for QPrinter::HighResolution so I'm
  // working all coordinates out as percentages of page
  // size so that we can hopefully get comarable print
  // results on all platforms.
  //

  //
  // Note #2: Im defining all measurements here as my plan
  // is to later support templates with different page
  // layouts and paper sizes etc.
  //


  //set the top left origin for the print layout
  int myOriginX = myPrinter.pageRect().left();
  int myOriginY = myPrinter.pageRect().top();
  int myDrawableWidth = myPrinter.pageRect().width() - myOriginX;
  int myDrawableHeight = myPrinter.pageRect().height() - myOriginY;

  //define the spacing between layout elements
  int myHorizontalSpacing = myDrawableWidth / 100; // 1%
  int myVerticalSpacing = myDrawableHeight / 100; // 1%

  //define the proportions for the page layout
  int myMapWidthPercent = 65;
  int myMapHeightPercent = 71;
  int myLegendWidthPercent = 25;
  int myLegendHeightPercent = 65;
  int myLogoWidthPercent = 23;
  int myLogoHeightPercent = 17;
  //
  // Remember the size and dpi of the maprender
  // so we can restore it properly
  //
  int myOriginalDpi = mpMapRenderer->outputDpi();
  //sensible default to prevent divide by zero
  if ( 0 == myOriginalDpi ) myOriginalDpi = 96;
  QSize myOriginalSize = mpMapRenderer->outputSize();

  //define the font sizes and family
  int myMapTitleFontSize = 24;
  int myMapDateFontSize = 16;
  int myMapNameFontSize = 32;
  int myLegendFontSize = 12;
#ifdef Q_OS_LINUX//this sucks...
  myLegendFontSize -= 2;
#endif

#ifdef WIN32 //this sucks too...
  myMapTitleFontSize /= 2;
  myMapDateFontSize /= 2;
  myMapNameFontSize /= 2;
  myLegendFontSize /= 2;
#endif
  QString myFontFamily = "Arial";

  //
  // Draw the PageBorder
  //
  myPrintPainter.drawRect(
    myOriginX, myOriginY, myDrawableWidth, myDrawableHeight );
  //
  // Draw the PageTitle
  //
  QFont myTitleFont( myFontFamily, myMapTitleFontSize );
  myPrintPainter.setFont( myTitleFont );
  QFontMetrics myTitleMetrics( myTitleFont, &myPrinter );
  int myPageTitleHeight = myTitleMetrics.height();
  int myPageTitleWidth = myTitleMetrics.width( mTitleText );
  myOriginX += myHorizontalSpacing;
  myOriginY -= ( myPageTitleHeight / 2 );
  QRect myPageTitleRect( myOriginX,
                         myOriginY,
                         myPageTitleWidth,
                         myPageTitleHeight );
  // make sure the title goes onto a white background
  myPrintPainter.setPen( Qt::white );
  myPrintPainter.drawRect( myPageTitleRect );
  myPrintPainter.setPen( Qt::black );
  myPrintPainter.drawText( myPageTitleRect, Qt::AlignCenter, mTitleText );

  //
  // Draw the MapDate
  //
  QFont myDateFont( myFontFamily, myMapDateFontSize );
  QString myDateText( QDate::currentDate().toString( Qt::LocalDate ) );
  myPrintPainter.setFont( myDateFont );
  QFontMetrics myDateMetrics( myDateFont, &myPrinter );
  int myDateHeight = myDateMetrics.height();
  //int myDateWidth = myDateMetrics.width(myDateText);
  myOriginX += myHorizontalSpacing;
  myOriginY += myPageTitleHeight  + myVerticalSpacing ;
  QRect myDateRect( myOriginX,
                    myOriginY,
                    myPageTitleWidth, //use same width as page title for centering
                    myDateHeight );
  // make sure the title goes onto a white background
  myPrintPainter.setPen( Qt::white );
  myPrintPainter.drawRect( myDateRect );
  myPrintPainter.setPen( Qt::black );
  myPrintPainter.drawText( myDateRect, Qt::AlignCenter, myDateText );

  //
  // Draw the MapName
  //
  QFont myNameFont( myFontFamily, myMapNameFontSize );
  myPrintPainter.setFont( myNameFont );
  QFontMetrics myNameMetrics( myNameFont, &myPrinter );
  int myNameHeight = myNameMetrics.height();
  int myNameWidth = myNameMetrics.width( mNameText );
  myOriginX = myPrinter.pageRect().left() + myDrawableWidth / 2; //page center
  myOriginX -= myNameWidth / 2;
  myOriginY = myPrinter.pageRect().top() + ( myPageTitleHeight / 2 )  + myVerticalSpacing ;
  QRect myNameRect( myOriginX,
                    myOriginY,
                    myNameWidth,
                    myNameHeight );
  // make sure the title goes onto a white background
  myPrintPainter.setPen( Qt::white );
  myPrintPainter.drawRect( myNameRect );
  myPrintPainter.setPen( Qt::black );
  myPrintPainter.drawText( myNameRect, Qt::AlignCenter, mNameText );

  //
  // Draw the MapFrame (top)
  //
  int myMapFrameWidth = myDrawableWidth ;
  myOriginX = myPrinter.pageRect().left() + myHorizontalSpacing;
  myOriginY += myNameHeight + myVerticalSpacing;
  QLine myMapFrameTopLine( myOriginX,
                           myOriginY,
                           myMapFrameWidth,
                           myOriginY );
  myPrintPainter.setPen( Qt::black );
  myPrintPainter.drawLine( myMapFrameTopLine );


  // Draw the map onto a pixmap
  // @TODO: we need to save teh extent of the screen map and
  // then set them again for the print map so that the map scales
  // properly in the print
  int myMapDimensionX = ( myDrawableWidth / 100 ) * myMapHeightPercent;
  int myMapDimensionY = ( myDrawableHeight / 100 ) * myMapWidthPercent;

  QImage myMapImage( QSize( myMapDimensionX, myMapDimensionY ), QImage::Format_ARGB32 );
  myMapImage.setDotsPerMeterX(( double )( myPrinter.logicalDpiX() ) / 25.4 * 1000.0 );
  myMapImage.setDotsPerMeterY(( double )( myPrinter.logicalDpiY() ) / 25.4 * 1000.0 );
  myMapImage.fill( 0 );
  QPainter myMapPainter;
  myMapPainter.begin( &myMapImage );
  // Now resize for print
  mpMapRenderer->setOutputSize( QSize( myMapDimensionX, myMapDimensionY ), ( myPrinter.logicalDpiX() + myPrinter.logicalDpiY() ) / 2 );
  mpMapRenderer->render( &myMapPainter );

  myMapPainter.end();
  //draw the map pixmap onto our pdf print device
  myOriginX = myPrinter.pageRect().left() + myHorizontalSpacing;
  myOriginY += myVerticalSpacing * 2;

  myPrintPainter.drawImage( myOriginX, myOriginY, myMapImage );

  //
  // Draw the legend
  //
  QFont myLegendFont( myFontFamily, myLegendFontSize );
  //myPrintPainter.setFont(myLegendFont);
  int myLegendDimensionX = ( myDrawableWidth / 100 ) * myLegendWidthPercent;
  int myLegendDimensionY = ( myDrawableHeight / 100 ) * myLegendHeightPercent;


  // Create a viewport to make coordinate conversions easier
  // The viewport has the same dimensions as the page(otherwise items
  // drawn into it will appear squashed), but a different origin.
  QRect myOriginalViewport = myPrintPainter.viewport(); //for restoring later
  myOriginX += myMapDimensionX + myHorizontalSpacing;
  myPrintPainter.setViewport( myOriginX,
                              myOriginY,
                              myOriginalViewport.width(),
                              myOriginalViewport.height() );
  //draw a rectangale around the legend frame
  //@TODO make this user settable
  if ( 0 == 1 ) //put some real logic here
  {
    myPrintPainter.drawRect( 0, 0, myLegendDimensionX, myLegendDimensionY );
  }
  //get font metric and other vars needed
  QFontMetrics myLegendFontMetrics( myLegendFont, &myPrinter );
  int myLegendFontHeight = myLegendFontMetrics.height();
  int myLegendXPos = 0;
  int myLegendYPos = 0;
  int myLegendSpacer = myLegendFontHeight / 2; //for vertical and horizontal spacing
  int myLegendVerticalSpacer = myLegendFontHeight / 3; //for vertical between rows
  int myIconWidth = myLegendFontHeight;
  myPrintPainter.setFont( myLegendFont );
  QStringList myLayerSet = mpMapRenderer->layerSet();
  QStringListIterator myLayerIterator( myLayerSet );
  //second clause below is to prevent legend spilling out the bottom
  while ( myLayerIterator.hasNext() &&
          myLegendYPos < myLegendDimensionY )
  {
    QString myLayerId = myLayerIterator.next();
    QgsMapLayer * mypLayer =
      QgsMapLayerRegistry::instance()->mapLayer( myLayerId );
    if ( mypLayer )
    {
      QgsVectorLayer *mypVectorLayer  =
        qobject_cast<QgsVectorLayer *>( mypLayer );
      // TODO: add support for symbology-ng renderers
      if ( mypVectorLayer && mypVectorLayer->renderer() )
      {
        QString myLayerName = mypVectorLayer->name();
        QIcon myIcon;
        QPixmap myPixmap( QSize( myIconWidth, myIconWidth ) );   //square
        //based on code from qgslegendlayer.cpp - see that file for more info
        const QgsRenderer* mypRenderer = mypVectorLayer->renderer();
        const QList<QgsSymbol*> mySymbolList = mypRenderer->symbols();
        //
        // Single symbol
        //
        double widthScale = ( myPrinter.logicalDpiX() + myPrinter.logicalDpiY() ) / 2.0 / 25.4;

        if ( 1 == mySymbolList.size() )
        {
          QgsSymbol * mypSymbol = mySymbolList.at( 0 );
          myPrintPainter.setPen( mypSymbol->pen() );
          myPrintPainter.setBrush( mypSymbol->brush() );
          myLegendXPos = 0 ;
          if ( mypSymbol->type() == QGis::Point )
          {
            QImage myImage;
            myImage = mypSymbol->getPointSymbolAsImage( widthScale );
            myPrintPainter.drawImage( myLegendXPos, myLegendYPos, myImage );
          }
          else if ( mypSymbol->type() == QGis::Line )
          {
            myPrintPainter.drawLine( myLegendXPos, myLegendYPos,
                                     myLegendXPos + myIconWidth,
                                     myLegendYPos + myIconWidth );
          }
          else //polygon
          {
            myPrintPainter.drawRect( myLegendXPos, myLegendYPos, myIconWidth, myIconWidth );
          }
          myLegendXPos += myIconWidth + myLegendSpacer;
          myPrintPainter.setPen( Qt::black );
          QStringList myWrappedLayerNameList = wordWrap( myLayerName,
                                               myLegendFontMetrics,
                                               myLegendDimensionX - myIconWidth );
          //
          // Loop through wrapped legend label lines
          //
          QStringListIterator myLineWrapIterator( myWrappedLayerNameList );
          while ( myLineWrapIterator.hasNext() )
          {
            QString myLine = myLineWrapIterator.next();
            QRect myLegendItemRect( myLegendXPos,
                                    myLegendYPos,
                                    myLegendDimensionX - myIconWidth,
                                    myLegendFontHeight );
            myPrintPainter.drawText( myLegendItemRect, Qt::AlignLeft, myLine );
            myLegendYPos += myLegendVerticalSpacer + myLegendFontHeight;
          }
        }
        else  //class breaks
        {
          // draw in the layer name first, after we loop for the class breaks
          QStringList myWrappedLayerNameList = wordWrap( myLayerName,
                                               myLegendFontMetrics,
                                               myLegendDimensionX - myIconWidth );
          // Check the wrapped layer name wont overrun the space we have
          // for the legend ...
          int myLabelHeight = myLegendFontHeight *
                              myWrappedLayerNameList.count();
          if ( myLegendYPos + myLabelHeight > myLegendDimensionY )
          {
            continue;
          }

          //
          // Loop through wrapped legend label lines
          //
          QStringListIterator myLineWrapIterator( myWrappedLayerNameList );
          while ( myLineWrapIterator.hasNext() )
          {
            QString myLine = myLineWrapIterator.next();
            myLegendXPos = myIconWidth;
            QRect myLegendItemRect( myLegendXPos,
                                    myLegendYPos,
                                    myLegendFontMetrics.width( myLine ),
                                    myLegendFontHeight );
            myPrintPainter.setPen( Qt::black );
            myPrintPainter.drawText( myLegendItemRect, Qt::AlignLeft, myLine );
            myLegendYPos += myLegendVerticalSpacer + myLegendFontHeight;
          }
          //
          // Loop through the class breaks
          //
          QListIterator<QgsSymbol *> myIterator( mySymbolList );
          while ( myIterator.hasNext() && myLegendYPos < myLegendDimensionY )
          {
            QgsSymbol * mypSymbol = myIterator.next();
            myPrintPainter.setPen( mypSymbol->pen() );
            myPrintPainter.setBrush( mypSymbol->brush() );
            myLegendXPos = myLegendSpacer * 3; //extra indent for class breaks
            if ( mypSymbol->type() == QGis::Point )
            {
              QImage myImage;
              myImage = mypSymbol->getPointSymbolAsImage( widthScale );
              myPrintPainter.drawImage( myLegendXPos, myLegendYPos, myImage );
            }
            else if ( mypSymbol->type() == QGis::Line )
            {
              myPrintPainter.drawLine( myLegendXPos, myLegendYPos,
                                       myLegendXPos + myIconWidth,
                                       myLegendYPos + myIconWidth );
            }
            else //polygon
            {
              myPrintPainter.drawRect(
                myLegendXPos, myLegendYPos, myIconWidth, myIconWidth );
            }
            //
            // Now work out the class break label
            //
            QString myLabel;
            QString myLower = mypSymbol->lowerValue();
            if ( !myLower.isEmpty() )
            {
              myLabel = myLower;
            }
            QString myUpper = mypSymbol->upperValue();
            if ( !myUpper.isEmpty() )
            {
              myLabel += " - ";
              myLabel += myUpper;
            }
            QString myText = mypSymbol->label();
            if ( !myText.isEmpty() )
            {
              myLabel += " ";
              myLabel += myText;
            }
            myLabel = myLabel.trimmed();
            myLegendXPos += myIconWidth + myLegendSpacer;
            myPrintPainter.setPen( Qt::black );

            QStringList myWrappedLayerNameList = wordWrap( myLabel,
                                                 myLegendFontMetrics,
                                                 myLegendDimensionX - myLegendXPos );
            //
            // Loop through wrapped legend label lines
            //
            QStringListIterator myLineWrapIterator( myWrappedLayerNameList );
            while ( myLineWrapIterator.hasNext() )
            {
              QString myLine = myLineWrapIterator.next();
              // check if the text will overflow the space we have
              QRect myLegendItemRect( myLegendXPos,
                                      myLegendYPos,
                                      myLegendDimensionX - myIconWidth,
                                      myLegendFontHeight );
              myPrintPainter.drawText( myLegendItemRect, Qt::AlignLeft, myLine );
              myLegendYPos += myLegendVerticalSpacer + myLegendFontHeight;
            } //wordwrap loop
          } //symbol loop
        } //class breaks
      } //if vectorlayer
    } //if maplayer
  } //layer iterator

  //reinstate the viewport
  myPrintPainter.setViewport( myOriginalViewport );


  //
  // Draw the MapFrame (bottom)
  //
  myOriginX = myPrinter.pageRect().left() + myHorizontalSpacing;
  myOriginY += myMapDimensionY + ( myVerticalSpacing * 2 );
  QLine myMapFrameBottomLine( myOriginX,
                              myOriginY,
                              myMapFrameWidth,
                              myOriginY );
  myPrintPainter.setPen( Qt::black );
  myPrintPainter.drawLine( myMapFrameBottomLine );


  //
  // Draw logo 1
  //
  int myLogoXDim = ( myDrawableWidth / 100 ) * myLogoWidthPercent;
  int myLogoYDim = ( myDrawableHeight / 100 ) * myLogoHeightPercent;
  QPixmap myLogo1;
  QgsDebugMsg( QString( "Logo1: %1" ).arg( mLogo1File ) );
  myLogo1.fill( Qt::white );
  myLogo1.load( mLogo1File );
  myLogo1 = myLogo1.scaled( myLogoXDim, myLogoYDim, Qt::KeepAspectRatio );
  myOriginX = myPrinter.pageRect().left() + myHorizontalSpacing;
  myOriginY += myVerticalSpacing ;
  myPrintPainter.drawPixmap( myOriginX,
                             myOriginY,
                             myLogo1 );

  //
  // Draw Copyright Text
  //
  myOriginX += myHorizontalSpacing + myLogoXDim;
  QRect myCopyrightRect( myOriginX, myOriginY, myLogoXDim, myLogoYDim );
  myPrintPainter.setPen( Qt::black );
  QFont myCopyrightFont( myFontFamily, myMapDateFontSize );
  myPrintPainter.setFont( myCopyrightFont );
  //myPrintPainter.drawRect( myCopyrightRect );
  myPrintPainter.drawText( myCopyrightRect, Qt::AlignCenter | Qt::TextWordWrap, mCopyrightText );

  //
  // Draw logo 2
  //
  QPixmap myLogo2;
  myLogo2.fill( Qt::white );
  myLogo2.load( mLogo2File );
  myLogo2 = myLogo2.scaled( myLogoXDim, myLogoYDim, Qt::KeepAspectRatio );
  myOriginX += myHorizontalSpacing + myLogoXDim;
  myPrintPainter.drawPixmap( myOriginX,
                             myOriginY,
                             myLogo2 );

  //
  // Draw the north arrow
  //
  myOriginX += myHorizontalSpacing + myLogoXDim;
  // use half the available space for the n.arrow
  // and the rest for the scale bar (see below)
  QPixmap myNorthArrow( myLogoYDim / 2, myLogoYDim / 2 );
  myNorthArrow.fill( Qt::white );
  QPainter myNorthPainter( &myNorthArrow );
  QSvgRenderer mySvgRenderer( mNorthArrowFile );
  mySvgRenderer.render( &myNorthPainter );
  myPrintPainter.drawPixmap( myOriginX + (( myLogoXDim / 2 ) ),
                             myOriginY,
                             myNorthArrow );

  //
  // Draw the scale bar
  //
  myOriginY += myLogoYDim / 2 + myVerticalSpacing;
  myPrintPainter.setViewport( myOriginX,
                              myOriginY,
                              myOriginalViewport.width(),
                              myOriginalViewport.height() );
  renderPrintScaleBar( &myPrintPainter, mpMapRenderer, myLogoXDim );
  myPrintPainter.setViewport( myOriginalViewport );

  //
  // Finish up
  //


  myPrintPainter.end();
#if 0
  mProgressDialog.setValue( 0 );
  mProgressDialog.setLabelText( tr( "Please wait while your report is generated", "COMMENTED OUT" ) );
  mProgressDialog.show();
  mProgressDialog.setWindowModality( Qt::WindowModal );
  mProgressDialog.setAutoClose( true );
#endif
  //
  // Restore the map render to its former glory
  //
  mpMapRenderer->setOutputSize( myOriginalSize, myOriginalDpi );
}
Example #21
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 );
      }
Example #22
0
QVariant QgsVectorLayerAndAttributeModel::data( const QModelIndex& idx, int role ) const
{
  if ( idx.column() == 0 )
  {
    if ( role == Qt::CheckStateRole )
    {
      if ( !idx.isValid() )
        return QVariant();

      if ( mCheckedLeafs.contains( idx ) )
        return Qt::Checked;

      bool hasChecked = false, hasUnchecked = false;
      int n;
      for ( n = 0; !hasChecked || !hasUnchecked; n++ )
      {
        QVariant v = data( idx.child( n, 0 ), role );
        if ( !v.isValid() )
          break;

        switch ( v.toInt() )
        {
          case Qt::PartiallyChecked:
            // parent of partially checked child shared state
            return Qt::PartiallyChecked;

          case Qt::Checked:
            hasChecked = true;
            break;

          case Qt::Unchecked:
            hasUnchecked = true;
            break;
        }
      }

      // unchecked leaf
      if ( n == 0 )
        return Qt::Unchecked;

      // both
      if ( hasChecked && hasUnchecked )
        return Qt::PartiallyChecked;

      if ( hasChecked )
        return Qt::Checked;

      Q_ASSERT( hasUnchecked );
      return Qt::Unchecked;
    }
    else
      return QgsLayerTreeModel::data( idx, role );
  }

  QgsVectorLayer *vl = vectorLayer( idx );
  if ( vl )
  {
    int idx = mAttributeIdx.value( vl, -1 );
    if ( role == Qt::EditRole )
      return idx;

    if ( role == Qt::DisplayRole )
    {
      if ( vl->fields().exists( idx ) )
        return vl->fields().at( idx ).name();
      else
        return vl->name();
    }

    if ( role == Qt::ToolTipRole )
    {
      return tr( "Attribute containing the name of the destination layer in the DXF output." );
    }
  }

  return QVariant();
}
Example #23
0
void QgsMapToolSelectUtils::setSelectFeatures( QgsMapCanvas* canvas,
	QgsGeometry* selectGeometry,
	bool doContains,
	bool doDifference,
	bool singleSelect )
{
	if ( selectGeometry->type() != QGis::Polygon )
	{
		return;
	}
	QgsVectorLayer* vlayer = QgsMapToolSelectUtils::getCurrentVectorLayer( canvas );
	if ( vlayer == nullptr )
	{
		return;
	}

	// toLayerCoordinates will throw an exception for any 'invalid' points in
	// the rubber band.
	// For example, if you project a world map onto a globe using EPSG 2163
	// and then click somewhere off the globe, an exception will be thrown.
	//QgsGeometry selectGeomTrans( *selectGeometry );

	//if ( canvas->mapSettings().hasCrsTransformEnabled() )
	//{
	//	try
	//	{
	//		QgsCoordinateTransform ct( canvas->mapSettings().destinationCrs(), vlayer->crs() );
	//		selectGeomTrans.transform( ct );
	//	}
	//	catch ( QgsCsException &cse )
	//	{
	//		Q_UNUSED( cse );
	//		// catch exception for 'invalid' point and leave existing selection unchanged
	//		QgsLogger::warning( "Caught CRS exception " + QString( __FILE__ ) + ": " + QString::number( __LINE__ ) );
	//		LOG_INFO( "CRS Exception\nSelection extends beyond layer's coordinate system" );
	//		return;
	//	}
	//}
	QgsGeometry selectGeomTrans;
	try{
		selectGeomTrans = toLayerCoordinates( canvas, selectGeometry, vlayer );
	}
	catch ( QgsCsException & )
	{
		return;
	}

	QApplication::setOverrideCursor( Qt::WaitCursor );

	QgsDebugMsg( "Selection layer: " + vlayer->name() );
	QgsDebugMsg( "Selection polygon: " + selectGeomTrans.exportToWkt() );
	QgsDebugMsg( "doContains: " + QString( doContains ? "T" : "F" ) );
	QgsDebugMsg( "doDifference: " + QString( doDifference ? "T" : "F" ) );

	QgsRenderContext context = QgsRenderContext::fromMapSettings( canvas->mapSettings() );
	QgsFeatureRendererV2* r = vlayer->rendererV2();
	if ( r )
		r->startRender( context, vlayer->pendingFields() );

	QgsFeatureRequest request;
	request.setFilterRect( selectGeomTrans.boundingBox() );
	request.setFlags( QgsFeatureRequest::ExactIntersect );
	if ( r )
		request.setSubsetOfAttributes( r->usedAttributes(), vlayer->pendingFields() );
	else
		request.setSubsetOfAttributes( QgsAttributeList() );

	QgsFeatureIterator fit = vlayer->getFeatures( request );

	QgsFeatureIds newSelectedFeatures;
	QgsFeature f;
	QgsFeatureId closestFeatureId = 0;
	bool foundSingleFeature = false;
	double closestFeatureDist = std::numeric_limits<double>::max();
	while ( fit.nextFeature( f ) )
	{
#if (VERSION_INT >= 21601)
		context.expressionContext().setFeature( f );		//taken from QGIS 2.16.1
		// make sure to only use features that are visible
		if ( r && !r->willRenderFeature( f, context ) )
#else
		if ( r && !r->willRenderFeature( f ) )
#endif
			continue;

		QgsGeometry* g = f.geometry();
		if ( doContains )
		{
			if ( !selectGeomTrans.contains( g ) )
				continue;
		}
		else
		{
			if ( !selectGeomTrans.intersects( g ) )
				continue;
		}
		if ( singleSelect )
		{
			foundSingleFeature = true;
			double distance = g->distance( selectGeomTrans );
			if ( distance <= closestFeatureDist )
			{
				closestFeatureDist = distance;
				closestFeatureId = f.id();
			}
		}
		else
		{
			newSelectedFeatures.insert( f.id() );
		}
	}
	if ( singleSelect && foundSingleFeature )
	{
		newSelectedFeatures.insert( closestFeatureId );
	}

	if ( r )
		r->stopRender( context );

	QgsDebugMsg( "Number of new selected features: " + QString::number( newSelectedFeatures.size() ) );

	if ( doDifference )
	{
		QgsFeatureIds layerSelectedFeatures = vlayer->selectedFeaturesIds();

		QgsFeatureIds selectedFeatures;
		QgsFeatureIds deselectedFeatures;

		QgsFeatureIds::const_iterator i = newSelectedFeatures.constEnd();
		while ( i != newSelectedFeatures.constBegin() )
		{
			--i;
			if ( layerSelectedFeatures.contains( *i ) )
			{
				deselectedFeatures.insert( *i );
			}
			else
			{
				selectedFeatures.insert( *i );
			}
		}

		vlayer->modifySelection( selectedFeatures, deselectedFeatures );
	}
	else
	{
		SelectFeatures( vlayer, newSelectedFeatures );		//		vlayer->setSelectedFeatures( newSelectedFeatures );
	}

	QApplication::restoreOverrideCursor();
}
Example #24
0
void QgsMapToolSelectUtils::setSelectFeatures( QgsMapCanvas* canvas,
    QgsGeometry* selectGeometry,
    bool doContains,
    bool doDifference,
    bool singleSelect )
{
  if ( selectGeometry->type() != QGis::Polygon )
  {
    return;
  }
  QgsVectorLayer* vlayer = QgsMapToolSelectUtils::getCurrentVectorLayer( canvas );
  if ( vlayer == NULL )
  {
    return;
  }

  // toLayerCoordinates will throw an exception for any 'invalid' points in
  // the rubber band.
  // For example, if you project a world map onto a globe using EPSG 2163
  // and then click somewhere off the globe, an exception will be thrown.
  QgsGeometry selectGeomTrans( *selectGeometry );

  if ( canvas->mapSettings().hasCrsTransformEnabled() )
  {
    try
    {
      QgsCoordinateTransform ct( canvas->mapSettings().destinationCrs(), vlayer->crs() );
      selectGeomTrans.transform( ct );
    }
    catch ( QgsCsException &cse )
    {
      Q_UNUSED( cse );
      // catch exception for 'invalid' point and leave existing selection unchanged
      QgsLogger::warning( "Caught CRS exception " + QString( __FILE__ ) + ": " + QString::number( __LINE__ ) );
      QgisApp::instance()->messageBar()->pushMessage(
        QObject::tr( "CRS Exception" ),
        QObject::tr( "Selection extends beyond layer's coordinate system" ),
        QgsMessageBar::WARNING,
        QgisApp::instance()->messageTimeout() );
      return;
    }
  }

  QApplication::setOverrideCursor( Qt::WaitCursor );

  QgsDebugMsg( "Selection layer: " + vlayer->name() );
  QgsDebugMsg( "Selection polygon: " + selectGeomTrans.exportToWkt() );
  QgsDebugMsg( "doContains: " + QString( doContains ? "T" : "F" ) );
  QgsDebugMsg( "doDifference: " + QString( doDifference ? "T" : "F" ) );

  QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( selectGeomTrans.boundingBox() ).setFlags( QgsFeatureRequest::ExactIntersect ).setSubsetOfAttributes( QgsAttributeList() ) );

  QgsFeatureIds newSelectedFeatures;
  QgsFeature f;
  QgsFeatureId closestFeatureId = 0;
  bool foundSingleFeature = false;
  double closestFeatureDist = std::numeric_limits<double>::max();
  while ( fit.nextFeature( f ) )
  {
    QgsGeometry* g = f.geometry();
    if ( doContains )
    {
      if ( !selectGeomTrans.contains( g ) )
        continue;
    }
    else
    {
      if ( !selectGeomTrans.intersects( g ) )
        continue;
    }
    if ( singleSelect )
    {
      foundSingleFeature = true;
      double distance = g->distance( selectGeomTrans );
      if ( distance <= closestFeatureDist )
      {
        closestFeatureDist = distance;
        closestFeatureId = f.id();
      }
    }
    else
    {
      newSelectedFeatures.insert( f.id() );
    }
  }
  if ( singleSelect && foundSingleFeature )
  {
    newSelectedFeatures.insert( closestFeatureId );
  }

  QgsDebugMsg( "Number of new selected features: " + QString::number( newSelectedFeatures.size() ) );

  if ( doDifference )
  {
    QgsFeatureIds layerSelectedFeatures = vlayer->selectedFeaturesIds();

    QgsFeatureIds selectedFeatures;
    QgsFeatureIds deselectedFeatures;

    QgsFeatureIds::const_iterator i = newSelectedFeatures.constEnd();
    while ( i != newSelectedFeatures.constBegin() )
    {
      --i;
      if ( layerSelectedFeatures.contains( *i ) )
      {
        deselectedFeatures.insert( *i );
      }
      else
      {
        selectedFeatures.insert( *i );
      }
    }

    vlayer->modifySelection( selectedFeatures, deselectedFeatures );
  }
  else
  {
    vlayer->setSelectedFeatures( newSelectedFeatures );
  }

  QApplication::restoreOverrideCursor();
}
QgsGeometryCheckerResultTab::QgsGeometryCheckerResultTab( QgisInterface *iface, QgsGeometryChecker *checker, QTabWidget *tabWidget, QWidget *parent )
  : QWidget( parent )
  , mTabWidget( tabWidget )
  , mIface( iface )
  , mChecker( checker )
{
  ui.setupUi( this );
  mErrorCount = 0;
  mFixedCount = 0;
  mCloseable = true;

  const QStringList layers = mChecker->featurePools().keys();
  for ( const QString &layerId : layers )
  {
    QgsVectorLayer *layer = mChecker->featurePools()[layerId]->layer();
    QTreeWidgetItem *item = new QTreeWidgetItem( ui.treeWidgetMergeAttribute, QStringList() << layer->name() << QString() );
    QComboBox *attribCombo = new QComboBox();
    const QgsFields fields = layer->fields();
    for ( const QgsField &field : fields )
    {
      attribCombo->addItem( field.name() );
    }
    attribCombo->setCurrentIndex( 0 );
    connect( attribCombo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( updateMergeAttributeIndices() ) );
    ui.treeWidgetMergeAttribute->setItemWidget( item, 1, attribCombo );
  }
  updateMergeAttributeIndices();

  connect( checker, &QgsGeometryChecker::errorAdded, this, &QgsGeometryCheckerResultTab::addError );
  connect( checker, &QgsGeometryChecker::errorUpdated, this, &QgsGeometryCheckerResultTab::updateError );
  connect( ui.tableWidgetErrors->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsGeometryCheckerResultTab::onSelectionChanged );
  connect( ui.buttonGroupSelectAction, static_cast<void ( QButtonGroup::* )( int )>( &QButtonGroup::buttonClicked ), this, [this]( int ) { QgsGeometryCheckerResultTab::highlightErrors(); } );
  connect( ui.pushButtonOpenAttributeTable, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::openAttributeTable );
  connect( ui.pushButtonFixWithDefault, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::fixErrorsWithDefault );
  connect( ui.pushButtonFixWithPrompt, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::fixErrorsWithPrompt );
  connect( ui.pushButtonErrorResolutionSettings, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::setDefaultResolutionMethods );
  connect( ui.checkBoxHighlight, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::highlightErrors );
  connect( QgsProject::instance(), static_cast<void ( QgsProject::* )( const QStringList & )>( &QgsProject::layersWillBeRemoved ), this, &QgsGeometryCheckerResultTab::checkRemovedLayer );
  connect( ui.pushButtonExport, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::exportErrors );

  bool allLayersEditable = true;
  for ( const QgsFeaturePool *featurePool : mChecker->featurePools().values() )
  {
    if ( ( featurePool->layer()->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 )
    {
      allLayersEditable = false;
      break;
    }
  }
  if ( !allLayersEditable )
  {
    ui.pushButtonFixWithDefault->setEnabled( false );
    ui.pushButtonFixWithPrompt->setEnabled( false );
  }

  ui.progressBarFixErrors->setVisible( false );
  ui.tableWidgetErrors->horizontalHeader()->setSortIndicator( 0, Qt::AscendingOrder );
  ui.tableWidgetErrors->resizeColumnToContents( 0 );
  ui.tableWidgetErrors->resizeColumnToContents( 1 );
  ui.tableWidgetErrors->horizontalHeader()->setResizeMode( 2, QHeaderView::Stretch );
  ui.tableWidgetErrors->horizontalHeader()->setResizeMode( 3, QHeaderView::Stretch );
  ui.tableWidgetErrors->horizontalHeader()->setResizeMode( 4, QHeaderView::Stretch );
  ui.tableWidgetErrors->horizontalHeader()->setResizeMode( 5, QHeaderView::Stretch );
  // Not sure why, but this is needed...
  ui.tableWidgetErrors->setSortingEnabled( true );
  ui.tableWidgetErrors->setSortingEnabled( false );
}
Example #26
0
void QgsDxfExport::writeEntities()
{
  startSection();
  writeGroup( 2, "ENTITIES" );

  //label engine
  QgsDxfPalLabeling labelEngine( this, mExtent.isEmpty() ? dxfExtent() : mExtent, mSymbologyScaleDenominator, mMapUnits );
  QgsRenderContext& ctx = labelEngine.renderContext();

  //iterate through the maplayers
  QList< QgsMapLayer* >::iterator layerIt = mLayers.begin();
  for ( ; layerIt != mLayers.end(); ++layerIt )
  {
    QgsVectorLayer* vl = qobject_cast<QgsVectorLayer*>( *layerIt );
    if ( !vl || !layerIsScaleBasedVisible( vl ) )
    {
      continue;
    }

    QgsSymbolV2RenderContext sctx( ctx, QgsSymbolV2::MM , 1.0, false, 0, 0 );
    QgsFeatureRendererV2* renderer = vl->rendererV2();
    renderer->startRender( ctx, vl->pendingFields() );

    QStringList attributes = renderer->usedAttributes();

    bool labelLayer = ( labelEngine.prepareLayer( vl, attributes, ctx ) != 0 );

    if ( mSymbologyExport == QgsDxfExport::SymbolLayerSymbology && ( renderer->capabilities() & QgsFeatureRendererV2::SymbolLevels ) &&
         renderer->usingSymbolLevels() )
    {
      writeEntitiesSymbolLevels( vl );
      renderer->stopRender( ctx );
      continue;
    }

    QgsFeatureRequest freq = QgsFeatureRequest().setSubsetOfAttributes(
                               attributes, vl->pendingFields() );
    if ( !mExtent.isEmpty() )
    {
      freq.setFilterRect( mExtent );
    }
    QgsFeatureIterator featureIt = vl->getFeatures( freq );
    QgsFeature fet;
    while ( featureIt.nextFeature( fet ) )
    {
      sctx.setFeature( &fet );
      if ( mSymbologyExport == NoSymbology )
      {
        addFeature( sctx, dxfLayerName( vl->name() ), 0, 0 ); //no symbology at all
      }
      else
      {
        if ( !renderer )
        {
          continue;
        }
        QgsSymbolV2List symbolList = renderer->symbolsForFeature( fet );
        if ( symbolList.size() < 1 )
        {
          continue;
        }

        if ( mSymbologyExport == QgsDxfExport::SymbolLayerSymbology ) //symbol layer symbology, but layer does not use symbol levels
        {
          QgsSymbolV2List::iterator symbolIt = symbolList.begin();
          for ( ; symbolIt != symbolList.end(); ++symbolIt )
          {
            int nSymbolLayers = ( *symbolIt )->symbolLayerCount();
            for ( int i = 0; i < nSymbolLayers; ++i )
            {
              addFeature( sctx, dxfLayerName( vl->name() ), ( *symbolIt )->symbolLayer( i ), *symbolIt );
            }
          }
        }
        else
        {
          //take first symbollayer from first symbol
          QgsSymbolV2* s = symbolList.first();
          if ( !s || s->symbolLayerCount() < 1 )
          {
            continue;
          }
          addFeature( sctx, dxfLayerName( vl->name() ), s->symbolLayer( 0 ), s );
        }

        if ( labelLayer )
        {
          labelEngine.registerFeature( vl->id(), fet, ctx );
        }
      }
    }
    renderer->stopRender( ctx );
  }

  labelEngine.drawLabeling( ctx );
  endSection();
}
Example #27
0
void QgsSnappingDialog::update()
{
  if ( !mMapCanvas )
    return;

  QSettings myQsettings;
  bool myDockFlag = myQsettings.value( "/qgis/dockSnapping", false ).toBool();

  double defaultSnappingTolerance = myQsettings.value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble();
  int defaultSnappingUnit = myQsettings.value( "/qgis/digitizing/default_snapping_tolerance_unit", 0 ).toInt();
  QString defaultSnappingString = myQsettings.value( "/qgis/digitizing/default_snap_mode", "to vertex" ).toString();

  int defaultSnappingStringIdx = 0;
  if ( defaultSnappingString == "to vertex" )
  {
    defaultSnappingStringIdx = 0;
  }
  else if ( defaultSnappingString == "to segment" )
  {
    defaultSnappingStringIdx = 1;
  }
  else //to vertex and segment
  {
    defaultSnappingStringIdx = 2;
  }

  bool layerIdListOk, enabledListOk, toleranceListOk, toleranceUnitListOk, snapToListOk, avoidIntersectionListOk;
  QStringList layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", &layerIdListOk );
  QStringList enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", &enabledListOk );
  QStringList toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", & toleranceListOk );
  QStringList toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", & toleranceUnitListOk );
  QStringList snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", &snapToListOk );
  QStringList avoidIntersectionsList = QgsProject::instance()->readListEntry( "Digitizing", "/AvoidIntersectionsList", &avoidIntersectionListOk );

  mLayerTreeWidget->clear();

  QMap< QString, QgsMapLayer *> mapLayers = QgsMapLayerRegistry::instance()->mapLayers();
  QMap< QString, QgsMapLayer *>::iterator it;
  for ( it = mapLayers.begin(); it != mapLayers.end() ; ++it )
  {
    QgsVectorLayer *currentVectorLayer = qobject_cast<QgsVectorLayer *>( it.value() );
    if ( !currentVectorLayer || currentVectorLayer->geometryType() == QGis::NoGeometry )
      continue;

    //snap to layer yes/no
    QTreeWidgetItem *item = new QTreeWidgetItem( mLayerTreeWidget );

    QCheckBox *cbxEnable = new QCheckBox( mLayerTreeWidget );
    mLayerTreeWidget->setItemWidget( item, 0, cbxEnable );
    item->setData( 0, Qt::UserRole, currentVectorLayer->getLayerID() );

    item->setText( 1, currentVectorLayer->name() );

    //snap to vertex/ snap to segment
    QComboBox *cbxSnapTo = new QComboBox( mLayerTreeWidget );
    cbxSnapTo->insertItem( 0, tr( "to vertex" ) );
    cbxSnapTo->insertItem( 1, tr( "to segment" ) );
    cbxSnapTo->insertItem( 2, tr( "to vertex and segment" ) );
    cbxSnapTo->setCurrentIndex( defaultSnappingStringIdx );
    mLayerTreeWidget->setItemWidget( item, 2, cbxSnapTo );

    //snapping tolerance
    QLineEdit *leTolerance = new QLineEdit( mLayerTreeWidget );
    QDoubleValidator *validator = new QDoubleValidator( leTolerance );
    leTolerance->setValidator( validator );
    leTolerance->setText( QString::number( defaultSnappingTolerance, 'f' ) );

    mLayerTreeWidget->setItemWidget( item, 3, leTolerance );

    //snap to vertex/ snap to segment
    QComboBox *cbxUnits = new QComboBox( mLayerTreeWidget );
    cbxUnits->insertItem( 0, tr( "map units" ) );
    cbxUnits->insertItem( 1, tr( "pixels" ) );
    cbxUnits->setCurrentIndex( defaultSnappingUnit );
    mLayerTreeWidget->setItemWidget( item, 4, cbxUnits );

    QCheckBox *cbxAvoidIntersection = 0;
    if ( currentVectorLayer->geometryType() == QGis::Polygon )
    {
      cbxAvoidIntersection = new QCheckBox( mLayerTreeWidget );
      mLayerTreeWidget->setItemWidget( item, 5, cbxAvoidIntersection );
    }

    int idx = layerIdList.indexOf( currentVectorLayer->getLayerID() );
    if ( idx < 0 )
    {
      // no settings for this layer yet
      continue;
    }

    cbxEnable->setChecked( enabledList[ idx ] == "enabled" );

    int snappingStringIdx = 0;
    if ( snapToList[idx] == "to_vertex" )
    {
      snappingStringIdx = 0;
    }
    else if ( snapToList[idx] == "to_segment" )
    {
      snappingStringIdx = 1;
    }
    else //to vertex and segment
    {
      snappingStringIdx = 2;
    }
    cbxSnapTo->setCurrentIndex( snappingStringIdx );
    leTolerance->setText( QString::number( toleranceList[idx].toDouble(), 'f' ) );
    cbxUnits->setCurrentIndex( toleranceUnitList[idx].toInt() );
    if ( cbxAvoidIntersection )
    {
      cbxAvoidIntersection->setChecked( avoidIntersectionsList.contains( currentVectorLayer->getLayerID() ) );
    }
  }

  // read the digitizing settings
  int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );
  if ( topologicalEditing != 0 )
  {
    cbxEnableTopologicalEditingCheckBox->setCheckState( Qt::Checked );
  }
  else
  {
    cbxEnableTopologicalEditingCheckBox->setCheckState( Qt::Unchecked );
  }

  if ( myDockFlag )
  {
    for ( int i = 0; i < mLayerTreeWidget->topLevelItemCount(); ++i )
    {
      QTreeWidgetItem *item = mLayerTreeWidget->topLevelItem( i );
      connect( mLayerTreeWidget->itemWidget( item, 0 ), SIGNAL( stateChanged( int ) ), this, SLOT( apply() ) );
      connect( mLayerTreeWidget->itemWidget( item, 2 ), SIGNAL( currentIndexChanged( int ) ), this, SLOT( apply() ) );
      connect( mLayerTreeWidget->itemWidget( item, 3 ), SIGNAL( textEdited( const QString ) ), this, SLOT( apply() ) );
      connect( mLayerTreeWidget->itemWidget( item, 4 ), SIGNAL( currentIndexChanged( int ) ), this, SLOT( apply() ) );

      QCheckBox *cbxAvoidIntersection = qobject_cast<QCheckBox*>( mLayerTreeWidget->itemWidget( item, 5 ) );
      if ( cbxAvoidIntersection )
      {
        connect( cbxAvoidIntersection, SIGNAL( stateChanged( int ) ), this, SLOT( apply() ) );
      }
    }
  }
}
Example #28
0
QDomElement QgsFeatureRendererV2::writeSld( QDomDocument& doc, const QgsVectorLayer &layer ) const
{
  return writeSld( doc, layer.name() );
}
bool QgsGeometryCheckerResultTab::exportErrorsDo( const QString &file )
{
  QList< QPair<QString, QString> > attributes;
  attributes.append( qMakePair( QStringLiteral( "Layer" ), QStringLiteral( "String;30;" ) ) );
  attributes.append( qMakePair( QStringLiteral( "FeatureID" ), QStringLiteral( "String;10;" ) ) );
  attributes.append( qMakePair( QStringLiteral( "ErrorDesc" ), QStringLiteral( "String;80;" ) ) );

  QFileInfo fi( file );
  QString ext = fi.suffix();
  QString driver = QgsVectorFileWriter::driverForExtension( ext );

  QLibrary ogrLib( QgsProviderRegistry::instance()->library( QStringLiteral( "ogr" ) ) );
  if ( !ogrLib.load() )
  {
    return false;
  }
  typedef bool ( *createEmptyDataSourceProc )( const QString &, const QString &, const QString &, QgsWkbTypes::Type, const QList< QPair<QString, QString> > &, const QgsCoordinateReferenceSystem & );
  createEmptyDataSourceProc createEmptyDataSource = ( createEmptyDataSourceProc ) cast_to_fptr( ogrLib.resolve( "createEmptyDataSource" ) );
  if ( !createEmptyDataSource )
  {
    return false;
  }
  if ( !createEmptyDataSource( file, driver, "UTF-8", QgsWkbTypes::Point, attributes, QgsProject::instance()->crs() ) )
  {
    return false;
  }
  QgsVectorLayer *layer = new QgsVectorLayer( file, QFileInfo( file ).baseName(), QStringLiteral( "ogr" ) );
  if ( !layer->isValid() )
  {
    delete layer;
    return false;
  }

  int fieldLayer = layer->fields().lookupField( QStringLiteral( "Layer" ) );
  int fieldFeatureId = layer->fields().lookupField( QStringLiteral( "FeatureID" ) );
  int fieldErrDesc = layer->fields().lookupField( QStringLiteral( "ErrorDesc" ) );
  for ( int row = 0, nRows = ui.tableWidgetErrors->rowCount(); row < nRows; ++row )
  {
    QgsGeometryCheckError *error = ui.tableWidgetErrors->item( row, 0 )->data( Qt::UserRole ).value<QgsGeometryCheckError *>();
    QgsVectorLayer *srcLayer = mChecker->featurePools()[error->layerId()]->layer();
    QgsFeature f( layer->fields() );
    f.setAttribute( fieldLayer, srcLayer->name() );
    f.setAttribute( fieldFeatureId, error->featureId() );
    f.setAttribute( fieldErrDesc, error->description() );
    QgsGeometry geom( new QgsPoint( error->location() ) );
    f.setGeometry( geom );
    layer->dataProvider()->addFeatures( QgsFeatureList() << f );
  }

  // Remove existing layer with same uri
  QStringList toRemove;
  for ( QgsMapLayer *maplayer : QgsProject::instance()->mapLayers() )
  {
    if ( dynamic_cast<QgsVectorLayer *>( maplayer ) &&
         static_cast<QgsVectorLayer *>( maplayer )->dataProvider()->dataSourceUri() == layer->dataProvider()->dataSourceUri() )
    {
      toRemove.append( maplayer->id() );
    }
  }
  if ( !toRemove.isEmpty() )
  {
    QgsProject::instance()->removeMapLayers( toRemove );
  }

  QgsProject::instance()->addMapLayers( QList<QgsMapLayer *>() << layer );
  return true;
}
RgLineVectorLayerSettingsWidget::RgLineVectorLayerSettingsWidget( RgLineVectorLayerSettings *s, QWidget* parent )
    : QWidget( parent )
{
  // create base widgets;
  QTabWidget *tab = new QTabWidget( this );
  QVBoxLayout *v = new QVBoxLayout( this );
  v->addWidget( tab );

  // transportation layer
  QFrame *frame = new QFrame( this );
  tab->addTab( frame, tr( "Transportation layer" ) );
  v = new QVBoxLayout( frame );
  QLabel *l = new QLabel( tr( "Layer" ), frame );
  mcbLayers = new QComboBox( frame );
  QHBoxLayout *h = new QHBoxLayout();

  h->addWidget( l );
  h->addWidget( mcbLayers );
  v->addLayout( h );

  h = new QHBoxLayout();
  l = new QLabel( tr( "Direction field" ), frame );
  mcbDirection = new QComboBox( frame );
  h->addWidget( l );
  h->addWidget( mcbDirection );
  v->addLayout( h );

  h = new QHBoxLayout();
  h->addWidget( new QLabel( tr( "Value for forward direction" ), frame ) );
  mleFirstPointToLastPointDirection = new QLineEdit( s->mFirstPointToLastPointDirectionVal, frame );
  h->addWidget( mleFirstPointToLastPointDirection );
  v->addLayout( h );

  h = new QHBoxLayout();
  h->addWidget( new QLabel( tr( "Value for reverse direction" ), frame ) );
  mleLastPointToFirstPointDirection = new QLineEdit( s->mLastPointToFirstPointDirectionVal, frame );
  h->addWidget( mleLastPointToFirstPointDirection );
  v->addLayout( h );

  h = new QHBoxLayout();
  h->addWidget( new QLabel( tr( "Value two-way direction" ), frame ) );
  mleBothDirection = new QLineEdit( s->mBothDirectionVal, frame );
  h->addWidget( mleBothDirection );
  v->addLayout( h );

  h = new QHBoxLayout();
  l = new QLabel( tr( "Speed field" ), frame );
  mcbSpeed = new QComboBox( frame );
  h->addWidget( l );
  h->addWidget( mcbSpeed );
  mcbUnitOfSpeed = new QComboBox( this );
  h->addWidget( mcbUnitOfSpeed );

  mcbUnitOfSpeed->insertItem( 0, tr( "km/h" ) );
  mcbUnitOfSpeed->insertItem( 0, tr( "m/s" ) );

  v->addLayout( h );

  frame = new QFrame( tab );
  tab->addTab( frame, tr( "Default settings" ) );
  v = new QVBoxLayout( frame );
  h = new QHBoxLayout();
  l = new QLabel( tr( "Direction" ), frame );
  mcbDirectionDefault = new QComboBox( frame );
  mcbDirectionDefault->insertItem( 0, tr( "Two-way direction" ) );
  mcbDirectionDefault->insertItem( 1, tr( "Forward direction" ) );
  mcbDirectionDefault->insertItem( 2, tr( "Reverse direction" ) );
  connect( mcbLayers, SIGNAL( currentIndexChanged( int ) ), this, SLOT( on_mcbLayers_selectItem() ) );

  h->addWidget( l );
  h->addWidget( mcbDirectionDefault );
  v->addLayout( h );

  h = new QHBoxLayout();
  l = new QLabel( tr( "Cost" ), frame );
  h->addWidget( l );
  l = new QLabel( tr( "Line lengths" ), frame );
  h->addWidget( l );
  v->addLayout( h );

  h = new QHBoxLayout();
  l = new QLabel( tr( "Speed" ), frame );
  msbSpeedDefault = new QSpinBox( frame );
  msbSpeedDefault->setMinimum( 1 );
  msbSpeedDefault->setMaximum( 10000000 );
  h->addWidget( l );
  h->addWidget( msbSpeedDefault );
  v->addLayout( h );


  // fill list of layers
  QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers();
  QMap<QString, QgsMapLayer*>::iterator layer_it = mapLayers.begin();

  for ( ; layer_it != mapLayers.end(); ++layer_it )
  {
    QgsVectorLayer* vl = dynamic_cast<QgsVectorLayer*>( layer_it.value() );
    if ( !vl )
      continue;
    if ( vl->geometryType() != QGis::Line )
      continue;
    mcbLayers->insertItem( 0, vl->name() );
  }

  //sets current settings
  msbSpeedDefault->setValue( static_cast<int>( s->mDefaultSpeed ) );

  int idx = mcbLayers->findText( s->mLayer );
  if ( idx != -1 )
  {
    mcbLayers->setCurrentIndex( idx );
  }

  idx = mcbDirection->findText( s->mDirection );
  if ( idx != -1 )
    mcbDirection->setCurrentIndex( idx );

  idx = mcbSpeed->findText( s->mSpeed );
  if ( idx != -1 )
    mcbSpeed->setCurrentIndex( idx );


  switch ( s->mDefaultDirection )
  {
    case RgLineVectorLayerSettings::Both:
      mcbDirectionDefault->setCurrentIndex( 0 );
      break;
    case RgLineVectorLayerSettings::FirstPointToLastPoint:
      mcbDirectionDefault->setCurrentIndex( 1 );
      break;
    case RgLineVectorLayerSettings::LastPointToFirstPoint:
      mcbDirectionDefault->setCurrentIndex( 2 );
      break;
  }
  if ( s->mSpeedUnitName == "km/h" )
    mcbUnitOfSpeed->setCurrentIndex( 1 );
  else if ( s->mSpeedUnitName == "m/s" )
    mcbUnitOfSpeed->setCurrentIndex( 0 );

} // RgLineVectorLayerSettingsWidget::RgLineVectorLayerSettingsWidget()