QString QgsZonalStatistics::getUniqueFieldName( const QString& fieldName ) { QgsVectorDataProvider* dp = mPolygonLayer->dataProvider(); if ( !dp->storageType().contains( QLatin1String( "ESRI Shapefile" ) ) ) { return fieldName; } QgsFields providerFields = dp->fields(); QString shortName = fieldName.mid( 0, 10 ); bool found = false; for ( int idx = 0; idx < providerFields.count(); ++idx ) { if ( shortName == providerFields.at( idx ).name() ) { found = true; break; } } if ( !found ) { return shortName; } int n = 1; shortName = QStringLiteral( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n ); found = true; while ( found ) { found = false; for ( int idx = 0; idx < providerFields.count(); ++idx ) { if ( shortName == providerFields.at( idx ).name() ) { n += 1; if ( n < 9 ) { shortName = QStringLiteral( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n ); } else { shortName = QStringLiteral( "%1_%2" ).arg( fieldName.mid( 0, 7 ) ).arg( n ); } found = true; } } } return shortName; }
void QgsComposerAttributeTableV2::setDisplayedFields( const QStringList& fields, bool refresh ) { QgsVectorLayer* source = sourceLayer(); if ( !source ) { return; } //rebuild columns list, taking only fields contained in supplied list qDeleteAll( mColumns ); mColumns.clear(); QgsFields layerFields = source->fields(); if ( !fields.isEmpty() ) { Q_FOREACH ( const QString& field, fields ) { int attrIdx = layerFields.lookupField( field ); if ( attrIdx < 0 ) continue; QString currentAlias = source->attributeDisplayName( attrIdx ); QgsComposerTableColumn* col = new QgsComposerTableColumn; col->setAttribute( layerFields.at( attrIdx ).name() ); col->setHeading( currentAlias ); mColumns.append( col ); }
void QgsFields::extend( const QgsFields &other ) { for ( int i = 0; i < other.count(); ++i ) { append( other.at( i ), other.fieldOrigin( i ), other.fieldOriginIndex( i ) ); } }
QgsFieldConstraints::Constraints QgsVectorDataProvider::fieldConstraints( int fieldIndex ) const { QgsFields f = fields(); if ( fieldIndex < 0 || fieldIndex >= f.count() ) return nullptr; return f.at( fieldIndex ).constraints().constraints(); }
QStringList QgsGrassVectorMapLayer::fieldNames( QgsFields & fields ) { QStringList list; for ( int i = 0; i < fields.size(); i++ ) { list << fields.at( i ).name(); } return list; }
QSet<QString> QgsDiagramLayerSettings::referencedFields( const QgsExpressionContext &context, const QgsFields& fieldsParameter ) const { QSet< QString > referenced; if ( renderer ) referenced = renderer->referencedFields( context, fieldsParameter ); //and the ones needed for data defined diagram positions if ( xPosColumn >= 0 && xPosColumn < fieldsParameter.count() ) referenced << fieldsParameter.at( xPosColumn ).name(); if ( yPosColumn >= 0 && yPosColumn < fieldsParameter.count() ) referenced << fieldsParameter.at( yPosColumn ).name(); // and the ones needed for data defined diagram visibility if ( showColumn >= 0 && showColumn < fieldsParameter.count() ) referenced << fieldsParameter.at( showColumn ).name(); return referenced; }
QgsDataDefinedSymbolDialog::QgsDataDefinedSymbolDialog( const QMap< QString, QPair< QString, QString > >& properties, const QgsVectorLayer* vl, QWidget* parent, Qt::WindowFlags f ): QDialog( parent, f ), mVectorLayer( vl ) { setupUi( this ); QgsFields attributeFields; if ( mVectorLayer ) { attributeFields = mVectorLayer->pendingFields(); } mTableWidget->setRowCount( properties.size() ); int i = 0; QMap< QString, QPair< QString, QString > >::const_iterator it = properties.constBegin(); for ( ; it != properties.constEnd(); ++it ) { //check box QCheckBox* cb = new QCheckBox( this ); cb->setChecked( !it.value().second.isEmpty() ); mTableWidget->setCellWidget( i, 0, cb ); mTableWidget->setColumnWidth( 0, cb->width() ); //property name QTableWidgetItem* propertyItem = new QTableWidgetItem( it.value().first ); propertyItem->setData( Qt::UserRole, it.key() ); mTableWidget->setItem( i, 1, propertyItem ); //attribute list QString expressionString = it.value().second; QComboBox* attributeComboBox = new QComboBox( this ); attributeComboBox->addItem( QString() ); for ( int j = 0; j < attributeFields.count(); ++j ) { attributeComboBox->addItem( attributeFields.at( j ).name() ); } int attrComboIndex = comboIndexForExpressionString( expressionString, attributeComboBox ); if ( attrComboIndex >= 0 ) { attributeComboBox->setCurrentIndex( attrComboIndex ); } else { attributeComboBox->setItemText( 0, expressionString ); } mTableWidget->setCellWidget( i, 2, attributeComboBox ); //expression button QPushButton* expressionButton = new QPushButton( "...", this ); QObject::connect( expressionButton, SIGNAL( clicked() ), this, SLOT( expressionButtonClicked() ) ); mTableWidget->setCellWidget( i, 3, expressionButton ); ++i; } }
void QgsAtlasComposition::readXml( const QDomElement& atlasElem, const QDomDocument& ) { mEnabled = atlasElem.attribute( QStringLiteral( "enabled" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; emit toggled( mEnabled ); if ( !mEnabled ) { emit parameterChanged(); return; } // look for stored layer name mCoverageLayer = nullptr; QMap<QString, QgsMapLayer*> layers = QgsMapLayerRegistry::instance()->mapLayers(); for ( QMap<QString, QgsMapLayer*>::const_iterator it = layers.begin(); it != layers.end(); ++it ) { if ( it.key() == atlasElem.attribute( QStringLiteral( "coverageLayer" ) ) ) { mCoverageLayer = dynamic_cast<QgsVectorLayer*>( it.value() ); break; } } mPageNameExpression = atlasElem.attribute( QStringLiteral( "pageNameExpression" ), QString() ); mSingleFile = atlasElem.attribute( QStringLiteral( "singleFile" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; mFilenamePattern = atlasElem.attribute( QStringLiteral( "filenamePattern" ), QLatin1String( "" ) ); mSortFeatures = atlasElem.attribute( QStringLiteral( "sortFeatures" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; if ( mSortFeatures ) { mSortKeyAttributeName = atlasElem.attribute( QStringLiteral( "sortKey" ), QLatin1String( "" ) ); // since 2.3, the field name is saved instead of the field index // following code keeps compatibility with version 2.2 projects // to be removed in QGIS 3.0 bool isIndex; int idx = mSortKeyAttributeName.toInt( &isIndex ); if ( isIndex && mCoverageLayer ) { QgsFields fields = mCoverageLayer->fields(); if ( idx >= 0 && idx < fields.count() ) { mSortKeyAttributeName = fields.at( idx ).name(); } } mSortAscending = atlasElem.attribute( QStringLiteral( "sortAscending" ), QStringLiteral( "true" ) ) == QLatin1String( "true" ) ? true : false; } mFilterFeatures = atlasElem.attribute( QStringLiteral( "filterFeatures" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; if ( mFilterFeatures ) { mFeatureFilter = atlasElem.attribute( QStringLiteral( "featureFilter" ), QLatin1String( "" ) ); } mHideCoverage = atlasElem.attribute( QStringLiteral( "hideCoverage" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; emit parameterChanged(); }
QMap<QString, int> QgsVectorDataProvider::fieldNameMap() const { QMap<QString, int> resultMap; QgsFields theFields = fields(); for ( int i = 0; i < theFields.count(); ++i ) { resultMap.insert( theFields.at( i ).name(), i ); } return resultMap; }
void QgsAtlasComposition::readXml( const QDomElement &atlasElem, const QDomDocument & ) { mEnabled = atlasElem.attribute( QStringLiteral( "enabled" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ); emit toggled( mEnabled ); if ( !mEnabled ) { emit parameterChanged(); return; } // look for stored layer name QString layerId = atlasElem.attribute( QStringLiteral( "coverageLayer" ) ); QString layerName = atlasElem.attribute( QStringLiteral( "coverageLayerName" ) ); QString layerSource = atlasElem.attribute( QStringLiteral( "coverageLayerSource" ) ); QString layerProvider = atlasElem.attribute( QStringLiteral( "coverageLayerProvider" ) ); mCoverageLayer = QgsVectorLayerRef( layerId, layerName, layerSource, layerProvider ); mCoverageLayer.resolveWeakly( mComposition->project() ); mPageNameExpression = atlasElem.attribute( QStringLiteral( "pageNameExpression" ), QString() ); mSingleFile = atlasElem.attribute( QStringLiteral( "singleFile" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ); mFilenamePattern = atlasElem.attribute( QStringLiteral( "filenamePattern" ), QLatin1String( "" ) ); mSortFeatures = atlasElem.attribute( QStringLiteral( "sortFeatures" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ); if ( mSortFeatures ) { mSortKeyAttributeName = atlasElem.attribute( QStringLiteral( "sortKey" ), QLatin1String( "" ) ); // since 2.3, the field name is saved instead of the field index // following code keeps compatibility with version 2.2 projects // to be removed in QGIS 3.0 bool isIndex; int idx = mSortKeyAttributeName.toInt( &isIndex ); if ( isIndex && mCoverageLayer ) { QgsFields fields = mCoverageLayer->fields(); if ( idx >= 0 && idx < fields.count() ) { mSortKeyAttributeName = fields.at( idx ).name(); } } mSortAscending = atlasElem.attribute( QStringLiteral( "sortAscending" ), QStringLiteral( "true" ) ) == QLatin1String( "true" ); } mFilterFeatures = atlasElem.attribute( QStringLiteral( "filterFeatures" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ); if ( mFilterFeatures ) { mFeatureFilter = atlasElem.attribute( QStringLiteral( "featureFilter" ), QLatin1String( "" ) ); } mHideCoverage = atlasElem.attribute( QStringLiteral( "hideCoverage" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ); emit parameterChanged(); }
void QgsAtlasComposition::setSortKeyAttributeIndex( int idx ) { if ( mCoverageLayer ) { QgsFields fields = mCoverageLayer->fields(); if ( idx >= 0 && idx < fields.count() ) { mSortKeyAttributeName = fields.at( idx ).name(); return; } } mSortKeyAttributeName = ""; }
void TestQgsFields::qforeach() { QgsFields fields; QgsField field( QString( "1" ) ); fields.append( field ); QgsField field2( QString( "2" ) ); fields.append( field2 ); int i = 0; Q_FOREACH ( const QgsField& field, fields ) { QCOMPARE( field, fields.at( i ) ); ++i; }
void QgsEditorWidgetRegistry::writeMapLayer( QgsMapLayer* mapLayer, QDomElement& layerElem, QDomDocument& doc ) const { if ( mapLayer->type() != QgsMapLayer::VectorLayer ) { return; } QgsVectorLayer* vectorLayer = qobject_cast<QgsVectorLayer*>( mapLayer ); if ( !vectorLayer ) { return; } QDomNode editTypesNode = doc.createElement( "edittypes" ); QgsFields fields = vectorLayer->fields(); for ( int idx = 0; idx < fields.count(); ++idx ) { QgsField field = fields.at( idx ); const QString& widgetType = vectorLayer->editFormConfig()->widgetType( idx ); if ( !mWidgetFactories.contains( widgetType ) ) { QgsMessageLog::logMessage( tr( "Could not save unknown editor widget type '%1'." ).arg( widgetType ) ); continue; } QDomElement editTypeElement = doc.createElement( "edittype" ); editTypeElement.setAttribute( "name", field.name() ); editTypeElement.setAttribute( "widgetv2type", widgetType ); if ( mWidgetFactories.contains( widgetType ) ) { QDomElement ewv2CfgElem = doc.createElement( "widgetv2config" ); ewv2CfgElem.setAttribute( "fieldEditable", !vectorLayer->editFormConfig()->readOnly( idx ) ); ewv2CfgElem.setAttribute( "labelOnTop", vectorLayer->editFormConfig()->labelOnTop( idx ) ); ewv2CfgElem.setAttribute( "notNull", vectorLayer->editFormConfig()->notNull( idx ) ); ewv2CfgElem.setAttribute( "constraint", vectorLayer->editFormConfig()->expression( idx ) ); ewv2CfgElem.setAttribute( "constraintDescription", vectorLayer->editFormConfig()->expressionDescription( idx ) ); mWidgetFactories[widgetType]->writeConfig( vectorLayer->editFormConfig()->widgetConfig( idx ), ewv2CfgElem, doc, vectorLayer, idx ); editTypeElement.appendChild( ewv2CfgElem ); } editTypesNode.appendChild( editTypeElement ); } layerElem.appendChild( editTypesNode ); }
void QgsOverlayAnalyzer::combineFieldLists( QgsFields &fieldListA, const QgsFields &fieldListB ) { QList<QString> names; Q_FOREACH ( const QgsField &field, fieldListA ) names.append( field.name() ); for ( int idx = 0; idx < fieldListB.count(); ++idx ) { QgsField field = fieldListB.at( idx ); int count = 0; while ( names.contains( field.name() ) ) { QString name = QStringLiteral( "%1_%2" ).arg( field.name() ).arg( count ); field = QgsField( name, field.type() ); ++count; } fieldListA.append( field ); names.append( field.name() ); } }
void TestQgsFields::extend() { QgsFields destination; QgsField field( "testfield" ); destination.append( field ); QgsField field2( "testfield2" ); destination.append( field2 ); QgsFields source; QgsField field3( "testfield3" ); source.append( field3, QgsFields::OriginJoin, 5 ); QgsField field4( "testfield4" ); source.append( field4 ); QCOMPARE( destination.count(), 2 ); destination.extend( source ); QCOMPARE( destination.count(), 4 ); QCOMPARE( destination.at( 2 ), field3 ); QCOMPARE( destination.at( 3 ), field4 ); }
void TestQgsFields::remove() { QgsFields fields; //test for no crash fields.remove( 1 ); QgsField field( "testfield" ); fields.append( field ); QgsField field2( "testfield2" ); fields.append( field2 ); //test for no crash fields.remove( -1 ); fields.remove( 5 ); //remove valid field fields.remove( 0 ); QCOMPARE( fields.count(), 1 ); QCOMPARE( fields.at( 0 ).name(), QString( "testfield2" ) ); QCOMPARE( fields.indexFromName( "testfield2" ), 0 ); }
QWidget *QgsFormAnnotation::createDesignerWidget( const QString &filePath ) { QFile file( filePath ); if ( !file.open( QFile::ReadOnly ) ) { return nullptr; } QUiLoader loader; QFileInfo fi( file ); loader.setWorkingDirectory( fi.dir() ); QWidget *widget = loader.load( &file, nullptr ); file.close(); //get feature and set attribute information QgsAttributeEditorContext context; QgsVectorLayer *vectorLayer = qobject_cast< QgsVectorLayer * >( mapLayer() ); if ( vectorLayer && associatedFeature().isValid() ) { QgsFields fields = vectorLayer->fields(); QgsAttributes attrs = associatedFeature().attributes(); for ( int i = 0; i < attrs.count(); ++i ) { if ( i < fields.count() ) { QWidget *attWidget = widget->findChild<QWidget *>( fields.at( i ).name() ); if ( attWidget ) { QgsEditorWidgetWrapper *eww = QgsGui::editorWidgetRegistry()->create( vectorLayer, i, attWidget, widget, context ); if ( eww ) { eww->setValue( attrs.at( i ) ); } } } } } return widget; }
/** * Slot called when the index changes for the cboxCompassBearingField combo box. * @param theIndex - The index of the new selected item */ void eVisGenericEventBrowserGui::on_cboxCompassOffsetField_currentIndexChanged( int theIndex ) { Q_UNUSED( theIndex ); if ( !mIgnoreEvent ) { mConfiguration.setCompassOffsetField( cboxCompassOffsetField->currentText() ); QgsFields myFields = mDataProvider->fields(); QgsFeature* myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( !myFeature ) return; QgsAttributes myAttrs = myFeature->attributes(); for ( int i = 0; i < myAttrs.count(); ++i ) { if ( myFields.at( i ).name() == cboxCompassOffsetField->currentText() ) { mCompassOffset = myAttrs.at( i ).toDouble(); } } } }
/** * Slot called when the index changes for the cboxEventImagePathField combo box. * \param index - The index of the new selected item */ void eVisGenericEventBrowserGui::cboxEventImagePathField_currentIndexChanged( int index ) { Q_UNUSED( index ); if ( !mIgnoreEvent ) { mConfiguration.setEventImagePathField( cboxEventImagePathField->currentText() ); QgsFields myFields = mVectorLayer->fields(); QgsFeature *myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( !myFeature ) return; QgsAttributes myAttrs = myFeature->attributes(); for ( int i = 0; i < myAttrs.count(); ++i ) { if ( myFields.at( i ).name() == cboxEventImagePathField->currentText() ) { mEventImagePath = myAttrs.at( i ).toString(); } } } }
void QgsProjectFileTransform::transform0110to1000() { if ( ! mDom.isNull() ) { QDomNodeList layerList = mDom.elementsByTagName( QStringLiteral( "maplayer" ) ); for ( int i = 0; i < layerList.size(); ++i ) { QDomElement layerElem = layerList.at( i ).toElement(); QString typeString = layerElem.attribute( QStringLiteral( "type" ) ); if ( typeString != QLatin1String( "vector" ) ) { continue; } //datasource QDomNode dataSourceNode = layerElem.namedItem( QStringLiteral( "datasource" ) ); if ( dataSourceNode.isNull() ) { return; } QString dataSource = dataSourceNode.toElement().text(); //provider key QDomNode providerNode = layerElem.namedItem( QStringLiteral( "provider" ) ); if ( providerNode.isNull() ) { return; } QString providerKey = providerNode.toElement().text(); //create the layer to get the provider for int->fieldName conversion QgsVectorLayer* theLayer = new QgsVectorLayer( dataSource, QLatin1String( "" ), providerKey, false ); if ( !theLayer->isValid() ) { delete theLayer; return; } QgsVectorDataProvider* theProvider = theLayer->dataProvider(); if ( !theProvider ) { return; } QgsFields theFields = theProvider->fields(); //read classificationfield QDomNodeList classificationFieldList = layerElem.elementsByTagName( QStringLiteral( "classificationfield" ) ); for ( int j = 0; j < classificationFieldList.size(); ++j ) { QDomElement classificationFieldElem = classificationFieldList.at( j ).toElement(); int fieldNumber = classificationFieldElem.text().toInt(); if ( fieldNumber >= 0 && fieldNumber < theFields.count() ) { QDomText fieldName = mDom.createTextNode( theFields.at( fieldNumber ).name() ); QDomNode nameNode = classificationFieldElem.firstChild(); classificationFieldElem.replaceChild( fieldName, nameNode ); } } } } }
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 ); }
void QgsFieldModel::updateModel() { if ( mLayer ) { QgsFields newFields = mLayer->fields(); if ( mFields.toList() != newFields.toList() ) { // Try to handle two special cases: addition of a new field and removal of a field. // It would be better to listen directly to attributeAdded/attributeDeleted // so we would not have to check for addition/removal here. if ( mFields.count() == newFields.count() - 1 ) { QgsFields tmpNewFields = newFields; tmpNewFields.remove( tmpNewFields.count() - 1 ); if ( mFields.toList() == tmpNewFields.toList() ) { // the only change is a new field at the end beginInsertRows( QModelIndex(), mFields.count(), mFields.count() ); mFields = newFields; endInsertRows(); return; } } if ( mFields.count() == newFields.count() + 1 ) { QgsFields tmpOldFields = mFields; tmpOldFields.remove( tmpOldFields.count() - 1 ); if ( tmpOldFields.toList() == newFields.toList() ) { // the only change is a field removed at the end beginRemoveRows( QModelIndex(), mFields.count() - 1, mFields.count() - 1 ); mFields = newFields; endRemoveRows(); return; } for ( int i = 0; i < newFields.count(); ++i ) { if ( mFields.at( i ) != newFields.at( i ) ) { QgsFields tmpOldFields = mFields; tmpOldFields.remove( i ); if ( tmpOldFields.toList() != newFields.toList() ) break; // the change is more complex - go with general case // the only change is a field removed at index i beginRemoveRows( QModelIndex(), i, i ); mFields = newFields; endRemoveRows(); return; } } } // general case with reset - not good - resets selections beginResetModel(); mFields = mLayer->fields(); endResetModel(); } else emit dataChanged( index( 0, 0 ), index( rowCount(), 0 ) ); } else { beginResetModel(); mFields = QgsFields(); endResetModel(); } }
QVariant QgsOgrUtils::getOgrFeatureAttribute( OGRFeatureH ogrFet, const QgsFields& fields, int attIndex, QTextCodec* encoding , bool* ok ) { if ( !ogrFet || attIndex < 0 || attIndex >= fields.count() ) { if ( ok ) *ok = false; return QVariant(); } OGRFieldDefnH fldDef = OGR_F_GetFieldDefnRef( ogrFet, attIndex ); if ( ! fldDef ) { if ( ok ) *ok = false; QgsDebugMsg( "ogrFet->GetFieldDefnRef(attindex) returns NULL" ); return QVariant(); } QVariant value; if ( ok ) *ok = true; if ( OGR_F_IsFieldSet( ogrFet, attIndex ) ) { switch ( fields.at( attIndex ).type() ) { case QVariant::String: { if ( encoding ) value = QVariant( encoding->toUnicode( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) ); else value = QVariant( QString::fromUtf8( OGR_F_GetFieldAsString( ogrFet, attIndex ) ) ); break; } case QVariant::Int: value = QVariant( OGR_F_GetFieldAsInteger( ogrFet, attIndex ) ); break; #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 2000000 case QVariant::LongLong: value = QVariant( OGR_F_GetFieldAsInteger64( ogrFet, attIndex ) ); break; #endif case QVariant::Double: value = QVariant( OGR_F_GetFieldAsDouble( ogrFet, attIndex ) ); break; case QVariant::Date: case QVariant::DateTime: case QVariant::Time: { int year, month, day, hour, minute, second, tzf; OGR_F_GetFieldAsDateTime( ogrFet, attIndex, &year, &month, &day, &hour, &minute, &second, &tzf ); if ( fields.at( attIndex ).type() == QVariant::Date ) value = QDate( year, month, day ); else if ( fields.at( attIndex ).type() == QVariant::Time ) value = QTime( hour, minute, second ); else value = QDateTime( QDate( year, month, day ), QTime( hour, minute, second ) ); } break; default: Q_ASSERT_X( false, "QgsOgrUtils::getOgrFeatureAttribute", "unsupported field type" ); if ( ok ) *ok = false; } } else { value = QVariant( QString::null ); } return value; }
QgsDataDefinedSymbolDialog::QgsDataDefinedSymbolDialog( const QList< DataDefinedSymbolEntry >& entries, const QgsVectorLayer* vl, QWidget * parent, Qt::WindowFlags f ) : QDialog( parent, f ) , mVectorLayer( vl ) { setupUi( this ); QgsFields attributeFields; if ( mVectorLayer ) { attributeFields = mVectorLayer->pendingFields(); } mTableWidget->setRowCount( entries.size() ); int i = 0; QList< DataDefinedSymbolEntry >::const_iterator entryIt = entries.constBegin(); for ( ; entryIt != entries.constEnd(); ++entryIt ) { //check box QCheckBox* cb = new QCheckBox( this ); cb->setChecked( !entryIt->initialValue.isEmpty() ); mTableWidget->setCellWidget( i, 0, cb ); mTableWidget->setColumnWidth( 0, cb->width() ); //property name QTableWidgetItem* propertyItem = new QTableWidgetItem( entryIt->title ); propertyItem->setData( Qt::UserRole, entryIt->property ); mTableWidget->setItem( i, 1, propertyItem ); //attribute list QString expressionString = entryIt->initialValue; QComboBox* attributeComboBox = new QComboBox( this ); attributeComboBox->addItem( QString() ); for ( int j = 0; j < attributeFields.count(); ++j ) { attributeComboBox->addItem( attributeFields.at( j ).name() ); } int attrComboIndex = comboIndexForExpressionString( expressionString, attributeComboBox ); if ( attrComboIndex >= 0 ) { attributeComboBox->setCurrentIndex( attrComboIndex ); } else { attributeComboBox->setItemText( 0, expressionString ); } mTableWidget->setCellWidget( i, 2, attributeComboBox ); //expression button QPushButton* expressionButton = new QPushButton( "...", this ); QObject::connect( expressionButton, SIGNAL( clicked() ), this, SLOT( expressionButtonClicked() ) ); mTableWidget->setCellWidget( i, 3, expressionButton ); //help text QTableWidgetItem* helpItem = new QTableWidgetItem( entryIt->helpText ); mTableWidget->setItem( i, 4, helpItem ); ++i; } }
/** * This method is an extension of the constructor. It was implemented to reduce the amount of code duplicated between the constuctors. */ bool eVisGenericEventBrowserGui::initBrowser() { //setup gui setWindowTitle( tr( "Generic Event Browser" ) ); connect( treeEventData, SIGNAL( itemDoubleClicked( QTreeWidgetItem *, int ) ), this, SLOT( launchExternalApplication( QTreeWidgetItem *, int ) ) ); mHighlightSymbol.load( ":/evis/eVisHighlightSymbol.png" ); mPointerSymbol.load( ":/evis/eVisPointerSymbol.png" ); mCompassOffset = 0.0; //Flag to let us know if the browser fully loaded mBrowserInitialized = false; //Initialize some class variables mDefaultEventImagePathField = 0; mDefaultCompassBearingField = 0; mDefaultCompassOffsetField = 0; //initialize Display tab GUI elements pbtnNext->setEnabled( false ); pbtnPrevious->setEnabled( false ); //Set up Attribute display treeEventData->setColumnCount( 2 ); QStringList treeHeaders; treeHeaders << tr( "Field" ) << tr( "Value" ); treeEventData->setHeaderLabels( treeHeaders ); //Initialize Options tab GUI elements cboxEventImagePathField->setEnabled( true ); chkboxEventImagePathRelative->setChecked( false ); chkboxDisplayCompassBearing->setChecked( false ); cboxCompassBearingField->setEnabled( true ); rbtnManualCompassOffset->setChecked( false ); dsboxCompassOffset->setEnabled( true ); dsboxCompassOffset->setValue( 0.0 ); rbtnAttributeCompassOffset->setChecked( false ); cboxCompassOffsetField->setEnabled( true ); chkboxUseOnlyFilename->setChecked( false ); QString myThemePath = QgsApplication::activeThemePath(); pbtnResetEventImagePathData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.svg" ) ) ); pbtnResetCompassBearingData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.svg" ) ) ); pbtnResetCompassOffsetData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.svg" ) ) ); pbtnResetBasePathData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.svg" ) ) ); pbtnResetUseOnlyFilenameData->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.svg" ) ) ); pbtnResetApplyPathRulesToDocs->setIcon( QIcon( QPixmap( myThemePath + "/mActionDraw.svg" ) ) ); chkboxSaveEventImagePathData->setChecked( false ); chkboxSaveCompassBearingData->setChecked( false ); chkboxSaveCompassOffsetData->setChecked( false ); chkboxSaveBasePathData->setChecked( false ); chkboxSaveUseOnlyFilenameData->setChecked( false ); //Set up Configure External Application buttons pbtnAddFileType->setIcon( QIcon( QPixmap( myThemePath + "/mActionNewAttribute.png" ) ) ); pbtnDeleteFileType->setIcon( QIcon( QPixmap( myThemePath + "/mActionDeleteAttribute.png" ) ) ); //Check to for interface, not null when launched from plugin toolbar, otherwise expect map canvas if ( mInterface ) { //check for active layer if ( mInterface->activeLayer() ) { //verify that the active layer is a vector layer if ( QgsMapLayer::VectorLayer == mInterface->activeLayer()->type() ) { mVectorLayer = ( QgsVectorLayer* )mInterface->activeLayer(); mCanvas = mInterface->mapCanvas(); } else { QMessageBox::warning( this, tr( "Warning" ), tr( "This tool only supports vector data" ) ); return false; } } else { QMessageBox::warning( this, tr( "Warning" ), tr( "No active layers found" ) ); return false; } } //check for map canvas, if map canvas is null, throw error else if ( mCanvas ) { //check for active layer if ( mCanvas->currentLayer() ) { //verify that the active layer is a vector layer if ( QgsMapLayer::VectorLayer == mCanvas->currentLayer()->type() ) { mVectorLayer = ( QgsVectorLayer* )mCanvas->currentLayer(); } else { QMessageBox::warning( this, tr( "Warning" ), tr( "This tool only supports vector data" ) ); return false; } } else { QMessageBox::warning( this, tr( "Warning" ), tr( "No active layers found" ) ); return false; } } else { QMessageBox::warning( this, tr( "Error" ), tr( "Unable to connect to either the map canvas or application interface" ) ); return false; } //Connect rendering routine for highlighting symbols and load symbols connect( mCanvas, SIGNAL( renderComplete( QPainter * ) ), this, SLOT( renderSymbol( QPainter * ) ) ); mDataProvider = mVectorLayer->dataProvider(); /* * A list of the selected feature ids is made so that we can move forward and backward through * the list. The data providers only have the ability to get one feature at a time or * sequentially move forward through the selected features */ if ( 0 == mVectorLayer->selectedFeatureCount() ) //if nothing is selected select everything { mVectorLayer->invertSelection(); mFeatureIds = mVectorLayer->selectedFeaturesIds().toList(); } else //use selected features { mFeatureIds = mVectorLayer->selectedFeaturesIds().toList(); } if ( 0 == mFeatureIds.size() ) return false; //get the first feature in the list so we can set the field in the pulldown menues QgsFeature* myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( !myFeature ) { QMessageBox::warning( this, tr( "Error" ), tr( "An invalid feature was received during initialization" ) ); return false; } QgsFields myFields = mDataProvider->fields(); mIgnoreEvent = true; //Ignore indexChanged event when adding items to combo boxes for ( int x = 0; x < myFields.count(); x++ ) { QString name = myFields.at( x ).name(); cboxEventImagePathField->addItem( name ); cboxCompassBearingField->addItem( name ); cboxCompassOffsetField->addItem( name ); if ( myFeature->attribute( x ).toString().contains( QRegExp( "(jpg|jpeg|tif|tiff|gif)", Qt::CaseInsensitive ) ) ) { mDefaultEventImagePathField = x; } if ( name.contains( QRegExp( "(comp|bear)", Qt::CaseInsensitive ) ) ) { mDefaultCompassBearingField = x; } if ( name.contains( QRegExp( "(offset|declination)", Qt::CaseInsensitive ) ) ) { mDefaultCompassOffsetField = x; } } mIgnoreEvent = false; //Set Display tab gui items if ( mFeatureIds.size() > 1 ) { pbtnNext->setEnabled( true ); } setWindowTitle( tr( "Event Browser - Displaying records 01 of %1" ).arg( mFeatureIds.size(), 2, 10, QChar( '0' ) ) ); //Set Options tab gui items initOptionsTab(); //Load file associations into Configure External Applications tab gui items QSettings myQSettings; myQSettings.beginWriteArray( "/eVis/filetypeassociations" ); int myTotalAssociations = myQSettings.childGroups().count(); int myIterator = 0; while ( myIterator < myTotalAssociations ) { myQSettings.setArrayIndex( myIterator ); tableFileTypeAssociations->insertRow( tableFileTypeAssociations->rowCount() ); tableFileTypeAssociations->setItem( myIterator, 0, new QTableWidgetItem( myQSettings.value( "extension", "" ).toString() ) ); tableFileTypeAssociations->setItem( myIterator, 1, new QTableWidgetItem( myQSettings.value( "application", "" ).toString() ) ); myIterator++; } myQSettings.endArray(); mBrowserInitialized = true; return true; }
QgsVectorLayerExporter::ExportError QgsVectorLayerExporter::exportLayer( QgsVectorLayer *layer, const QString &uri, const QString &providerKey, const QgsCoordinateReferenceSystem &destCRS, bool onlySelected, QString *errorMessage, const QMap<QString, QVariant> &options, QgsFeedback *feedback ) { QgsCoordinateReferenceSystem outputCRS; QgsCoordinateTransform ct; bool shallTransform = false; if ( !layer ) return ErrInvalidLayer; if ( destCRS.isValid() ) { // This means we should transform outputCRS = destCRS; shallTransform = true; } else { // This means we shouldn't transform, use source CRS as output (if defined) outputCRS = layer->crs(); } bool overwrite = false; bool forceSinglePartGeom = false; QMap<QString, QVariant> providerOptions = options; if ( !options.isEmpty() ) { overwrite = providerOptions.take( QStringLiteral( "overwrite" ) ).toBool(); forceSinglePartGeom = providerOptions.take( QStringLiteral( "forceSinglePartGeometryType" ) ).toBool(); } QgsFields fields = layer->fields(); QgsWkbTypes::Type wkbType = layer->wkbType(); // Special handling for Shapefiles if ( layer->providerType() == QLatin1String( "ogr" ) && layer->storageType() == QLatin1String( "ESRI Shapefile" ) ) { // convert field names to lowercase for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx ) { fields[fldIdx].setName( fields.at( fldIdx ).name().toLower() ); } if ( !forceSinglePartGeom ) { // convert wkbtype to multipart (see #5547) switch ( wkbType ) { case QgsWkbTypes::Point: wkbType = QgsWkbTypes::MultiPoint; break; case QgsWkbTypes::LineString: wkbType = QgsWkbTypes::MultiLineString; break; case QgsWkbTypes::Polygon: wkbType = QgsWkbTypes::MultiPolygon; break; case QgsWkbTypes::Point25D: wkbType = QgsWkbTypes::MultiPoint25D; break; case QgsWkbTypes::LineString25D: wkbType = QgsWkbTypes::MultiLineString25D; break; case QgsWkbTypes::Polygon25D: wkbType = QgsWkbTypes::MultiPolygon25D; break; default: break; } } } QgsVectorLayerExporter *writer = new QgsVectorLayerExporter( uri, providerKey, fields, wkbType, outputCRS, overwrite, providerOptions ); // check whether file creation was successful ExportError err = writer->errorCode(); if ( err != NoError ) { if ( errorMessage ) *errorMessage = writer->errorMessage(); delete writer; return err; } if ( errorMessage ) { errorMessage->clear(); } QgsFeature fet; QgsFeatureRequest req; if ( wkbType == QgsWkbTypes::NoGeometry ) req.setFlags( QgsFeatureRequest::NoGeometry ); if ( onlySelected ) req.setFilterFids( layer->selectedFeatureIds() ); QgsFeatureIterator fit = layer->getFeatures( req ); // Create our transform if ( destCRS.isValid() ) { Q_NOWARN_DEPRECATED_PUSH ct = QgsCoordinateTransform( layer->crs(), destCRS ); Q_NOWARN_DEPRECATED_POP }
void QgsVectorDataProvider::fillMinMaxCache() const { if ( !mCacheMinMaxDirty ) return; QgsFields flds = fields(); for ( int i = 0; i < flds.count(); ++i ) { if ( flds.at( i ).type() == QVariant::Int ) { mCacheMinValues[i] = QVariant( INT_MAX ); mCacheMaxValues[i] = QVariant( INT_MIN ); } else if ( flds.at( i ).type() == QVariant::LongLong ) { mCacheMinValues[i] = QVariant( std::numeric_limits<qlonglong>::max() ); mCacheMaxValues[i] = QVariant( std::numeric_limits<qlonglong>::min() ); } else if ( flds.at( i ).type() == QVariant::Double ) { mCacheMinValues[i] = QVariant( DBL_MAX ); mCacheMaxValues[i] = QVariant( -DBL_MAX ); } else { mCacheMinValues[i] = QVariant(); mCacheMaxValues[i] = QVariant(); } } QgsFeature f; QgsAttributeList keys = mCacheMinValues.keys(); QgsFeatureIterator fi = getFeatures( QgsFeatureRequest().setSubsetOfAttributes( keys ) ); while ( fi.nextFeature( f ) ) { QgsAttributes attrs = f.attributes(); for ( QgsAttributeList::const_iterator it = keys.begin(); it != keys.end(); ++it ) { const QVariant& varValue = attrs.at( *it ); if ( varValue.isNull() ) continue; if ( flds.at( *it ).type() == QVariant::Int ) { int value = varValue.toInt(); if ( value < mCacheMinValues[*it].toInt() ) mCacheMinValues[*it] = value; if ( value > mCacheMaxValues[*it].toInt() ) mCacheMaxValues[*it] = value; } else if ( flds.at( *it ).type() == QVariant::LongLong ) { qlonglong value = varValue.toLongLong(); if ( value < mCacheMinValues[*it].toLongLong() ) mCacheMinValues[*it] = value; if ( value > mCacheMaxValues[*it].toLongLong() ) mCacheMaxValues[*it] = value; } else if ( flds.at( *it ).type() == QVariant::Double ) { double value = varValue.toDouble(); if ( value < mCacheMinValues[*it].toDouble() ) mCacheMinValues[*it] = value; if ( value > mCacheMaxValues[*it].toDouble() ) mCacheMaxValues[*it] = value; } else { QString value = varValue.toString(); if ( mCacheMinValues[*it].isNull() || value < mCacheMinValues[*it].toString() ) { mCacheMinValues[*it] = value; } if ( mCacheMaxValues[*it].isNull() || value > mCacheMaxValues[*it].toString() ) { mCacheMaxValues[*it] = value; } } } } mCacheMinMaxDirty = false; }
QgsVectorLayerImport::ImportError QgsVectorLayerImport::importLayer( QgsVectorLayer* layer, const QString& uri, const QString& providerKey, const QgsCoordinateReferenceSystem *destCRS, bool onlySelected, QString *errorMessage, bool skipAttributeCreation, QMap<QString, QVariant> *options, QProgressDialog *progress ) { const QgsCoordinateReferenceSystem* outputCRS; QgsCoordinateTransform* ct = nullptr; bool shallTransform = false; if ( !layer ) return ErrInvalidLayer; if ( destCRS && destCRS->isValid() ) { // This means we should transform outputCRS = destCRS; shallTransform = true; } else { // This means we shouldn't transform, use source CRS as output (if defined) outputCRS = &layer->crs(); } bool overwrite = false; bool forceSinglePartGeom = false; if ( options ) { overwrite = options->take( "overwrite" ).toBool(); forceSinglePartGeom = options->take( "forceSinglePartGeometryType" ).toBool(); } QgsFields fields = skipAttributeCreation ? QgsFields() : layer->fields(); QGis::WkbType wkbType = layer->wkbType(); // Special handling for Shapefiles if ( layer->providerType() == "ogr" && layer->storageType() == "ESRI Shapefile" ) { // convert field names to lowercase for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx ) { fields[fldIdx].setName( fields.at( fldIdx ).name().toLower() ); } if ( !forceSinglePartGeom ) { // convert wkbtype to multipart (see #5547) switch ( wkbType ) { case QGis::WKBPoint: wkbType = QGis::WKBMultiPoint; break; case QGis::WKBLineString: wkbType = QGis::WKBMultiLineString; break; case QGis::WKBPolygon: wkbType = QGis::WKBMultiPolygon; break; case QGis::WKBPoint25D: wkbType = QGis::WKBMultiPoint25D; break; case QGis::WKBLineString25D: wkbType = QGis::WKBMultiLineString25D; break; case QGis::WKBPolygon25D: wkbType = QGis::WKBMultiPolygon25D; break; default: break; } } } QgsVectorLayerImport * writer = new QgsVectorLayerImport( uri, providerKey, fields, wkbType, outputCRS, overwrite, options, progress ); // check whether file creation was successful ImportError err = writer->hasError(); if ( err != NoError ) { if ( errorMessage ) *errorMessage = writer->errorMessage(); delete writer; return err; } if ( errorMessage ) { errorMessage->clear(); } QgsAttributeList allAttr = skipAttributeCreation ? QgsAttributeList() : layer->attributeList(); QgsFeature fet; QgsFeatureRequest req; if ( wkbType == QGis::WKBNoGeometry ) req.setFlags( QgsFeatureRequest::NoGeometry ); if ( skipAttributeCreation ) req.setSubsetOfAttributes( QgsAttributeList() ); QgsFeatureIterator fit = layer->getFeatures( req ); const QgsFeatureIds& ids = layer->selectedFeaturesIds(); // Create our transform if ( destCRS ) ct = new QgsCoordinateTransform( layer->crs(), *destCRS ); // Check for failure if ( !ct ) shallTransform = false; int n = 0; if ( errorMessage ) { *errorMessage = QObject::tr( "Feature write errors:" ); } if ( progress ) { progress->setRange( 0, layer->featureCount() ); } // write all features while ( fit.nextFeature( fet ) ) { if ( progress && progress->wasCanceled() ) { if ( errorMessage ) { *errorMessage += '\n' + QObject::tr( "Import was canceled at %1 of %2" ).arg( progress->value() ).arg( progress->maximum() ); } break; } if ( writer->errorCount() > 1000 ) { if ( errorMessage ) { *errorMessage += '\n' + QObject::tr( "Stopping after %1 errors" ).arg( writer->errorCount() ); } break; } if ( onlySelected && !ids.contains( fet.id() ) ) continue; if ( shallTransform ) { try { if ( fet.constGeometry() ) { fet.geometry()->transform( *ct ); } } catch ( QgsCsException &e ) { delete ct; delete writer; QString msg = QObject::tr( "Failed to transform a point while drawing a feature with ID '%1'. Writing stopped. (Exception: %2)" ) .arg( fet.id() ).arg( e.what() ); QgsMessageLog::logMessage( msg, QObject::tr( "Vector import" ) ); if ( errorMessage ) *errorMessage += '\n' + msg; return ErrProjection; } } if ( skipAttributeCreation ) { fet.initAttributes( 0 ); } if ( !writer->addFeature( fet ) ) { if ( writer->hasError() && errorMessage ) { *errorMessage += '\n' + writer->errorMessage(); } } n++; if ( progress ) { progress->setValue( n ); } } // flush the buffer to be sure that all features are written if ( !writer->flushBuffer() ) { if ( writer->hasError() && errorMessage ) { *errorMessage += '\n' + writer->errorMessage(); } } int errors = writer->errorCount(); if ( !writer->createSpatialIndex() ) { if ( writer->hasError() && errorMessage ) { *errorMessage += '\n' + writer->errorMessage(); } } delete writer; if ( shallTransform ) { delete ct; } if ( errorMessage ) { if ( errors > 0 ) { *errorMessage += '\n' + QObject::tr( "Only %1 of %2 features written." ).arg( n - errors ).arg( n ); } else { errorMessage->clear(); } } return errors == 0 ? NoError : ErrFeatureWriteFailed; }
QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QString& uri, const QgsFields &fields, QgsWkbTypes::Type wkbType, const QgsCoordinateReferenceSystem& srs, bool overwrite, QMap<int, int> *oldToNewAttrIdxMap, QString *errorMessage, const QMap<QString, QVariant> *options ) { Q_UNUSED( options ); // populate members from the uri structure QgsDataSourceUri dsUri( uri ); QString connInfo = dsUri.connectionInfo(); QString errMsg; QString srsName; QgsDebugMsg( "uri: " + uri ); // connect to database QSqlDatabase db = QgsDb2Provider::getDatabase( connInfo, errMsg ); if ( !errMsg.isEmpty() ) { if ( errorMessage ) *errorMessage = errMsg; return QgsVectorLayerImport::ErrConnectionFailed; } // Get the SRS name using srid, needed to register the spatial column // srs->posgisSrid() seems to return the authority id which is // most often the EPSG id. Hopefully DB2 has defined an SRS using this // value as the srid / srs_id. If not, we are out of luck. QgsDebugMsg( "srs: " + srs.toWkt() ); long srid = srs.postgisSrid(); QgsDebugMsg( QString( "srid: %1" ).arg( srid ) ); if ( srid >= 0 ) { QSqlQuery query( db ); QString statement = QString( "SELECT srs_name FROM db2gse.st_spatial_reference_systems where srs_id=%1" ) .arg( srid ); QgsDebugMsg( statement ); if ( !query.exec( statement ) || !query.isActive() ) { QgsDebugMsg( query.lastError().text() ); } if ( query.next() ) { srsName = query.value( 0 ).toString(); QgsDebugMsg( QString( "srs_name: %1" ).arg( srsName ) ); } else { QgsDebugMsg( "Couldn't get srs_name from db2gse.st_spatial_reference_systems" ); } } QString schemaName = dsUri.schema().toUpper(); QString tableName = dsUri.table().toUpper(); QString fullName; if ( schemaName.isEmpty() ) { schemaName = dsUri.username().toUpper(); // set schema to user name } fullName = schemaName + "." + tableName; QString geometryColumn = dsUri.geometryColumn().toUpper(); QString primaryKey = dsUri.keyColumn().toUpper(); QString primaryKeyType; // TODO - this is a bad hack to cope with shapefiles. // The wkbType from the shapefile header is usually a multi-type // even if all the data is a single-type. If we create the column as // a multi-type, the insert will fail if the actual data is a single-type // due to type mismatch. // We could potentially defer adding the spatial column until addFeatures is // called the first time, but QgsVectorLayerImport doesn't pass the CRS/srid // information to the DB2 provider and we need this information to register // the spatial column. // This hack is problematic because the drag/drop will fail if the // actual data is a multi-type which is possible with a shapefile or // other data source. QgsWkbTypes::Type wkbTypeSingle; wkbTypeSingle = QgsWkbTypes::singleType( wkbType ); if ( wkbType != QgsWkbTypes::NoGeometry && geometryColumn.isEmpty() ) geometryColumn = "GEOM"; if ( primaryKey.isEmpty() ) primaryKey = "QGS_FID"; // get the pk's name and type // if no pk name was passed, define the new pk field name int fieldCount = fields.size(); if ( primaryKey.isEmpty() ) { int index = 0; QString pk = primaryKey = "QGS_FID"; for ( int i = 0; i < fieldCount; ++i ) { if ( fields.at( i ).name() == primaryKey ) { // it already exists, try again with a new name primaryKey = QString( "%1_%2" ).arg( pk ).arg( index++ ); i = 0; } } } else { // search for the passed field for ( int i = 0; i < fieldCount; ++i ) { if ( fields.at( i ).name() == primaryKey ) { // found, get the field type QgsField fld = fields.at( i ); if ( convertField( fld ) ) { primaryKeyType = fld.typeName(); } } } } QgsDebugMsg( "primaryKeyType: '" + primaryKeyType + "'" ); QString sql; QSqlQuery q = QSqlQuery( db ); q.setForwardOnly( true ); // get wkb type and dimension QString geometryType; int dim = 2; db2WkbTypeAndDimension( wkbTypeSingle, geometryType, dim ); QgsDebugMsg( QString( "wkbTypeSingle: %1; geometryType: %2" ).arg( wkbTypeSingle ).arg( geometryType ) ); if ( overwrite ) { // remove the old table with the same name sql = "DROP TABLE " + fullName; if ( !q.exec( sql ) ) { if ( q.lastError().number() != -206 ) // -206 is "not found" just ignore { QString lastError = q.lastError().text(); QgsDebugMsg( lastError ); if ( errorMessage ) { *errorMessage = lastError; } return QgsVectorLayerImport::ErrCreateLayer; } } } // add fields to the layer if ( oldToNewAttrIdxMap ) oldToNewAttrIdxMap->clear(); QString attr2Create = ""; if ( fields.size() > 0 ) { int offset = 0; // get the list of fields QgsDebugMsg( "PrimaryKey: '" + primaryKey + "'" ); for ( int i = 0; i < fieldCount; ++i ) { QgsField fld = fields.field( i ); QgsDebugMsg( QString( "i: %1; fldIdx: %2; offset: %3" ) .arg( i ).arg( fields.lookupField( fld.name() ) ).arg( offset ) ); if ( oldToNewAttrIdxMap && fld.name() == primaryKey ) { oldToNewAttrIdxMap->insert( i , 0 ); continue; } if ( fld.name() == geometryColumn ) { // Found a field with the same name of the geometry column. Skip it! continue; } QString db2Field = qgsFieldToDb2Field( fld ); if ( db2Field.isEmpty() ) { if ( errorMessage ) { *errorMessage = QObject::tr( "Unsupported type for field %1" ).arg( fld.name() ); } return QgsVectorLayerImport::ErrAttributeTypeUnsupported; } if ( oldToNewAttrIdxMap ) { oldToNewAttrIdxMap->insert( fields.lookupField( fld.name() ), offset++ ); } attr2Create += ',' + db2Field.toUpper(); } QgsDebugMsg( attr2Create ); if ( !geometryColumn.isEmpty() ) { sql = QString( // need to set specific geometry type "CREATE TABLE %1(%2 BIGINT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, " "%3 DB2GSE.%4 %5) " ) .arg( fullName, primaryKey, geometryColumn, geometryType, attr2Create ); } else { //geometryless table sql = QString( // need to set specific geometry type "CREATE TABLE %1.%2(%3 INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS %4) " ) .arg( schemaName, tableName, primaryKey, attr2Create ); } QgsDebugMsg( sql ); if ( !q.exec( sql ) ) { QString lastError = q.lastError().text(); QgsDebugMsg( lastError ); if ( errorMessage ) { *errorMessage = lastError; } return QgsVectorLayerImport::ErrCreateLayer; } if ( !geometryColumn.isEmpty() ) { int computeExtents = 0; int msgCode = 0; int outCode; int outMsg; QVariant msgText( " " ); QSqlQuery query( db ); int db2Environment = ENV_LUW; // get the environment QgsDb2GeometryColumns gc( db ); int rc = gc.open( schemaName, tableName ); // returns SQLCODE if failure if ( rc == 0 ) { db2Environment = gc.db2Environment(); } if ( ENV_LUW == db2Environment ) { sql = QString( "CALL DB2GSE.ST_Register_Spatial_Column(?, ?, ?, ?, ?, ?, ?)" ); outCode = 5; outMsg = 6; } else // z/OS doesn't support 'computeExtents' parameter and has different schema { sql = QString( "CALL SYSPROC.ST_Register_Spatial_Column(?, ?, ?, ?, ?, ?)" ); outCode = 4; outMsg = 5; } query.prepare( sql ); query.bindValue( 0, schemaName ); query.bindValue( 1, tableName ); query.bindValue( 2, geometryColumn ); query.bindValue( 3, srsName ); if ( ENV_LUW == db2Environment ) { query.bindValue( 4, computeExtents ); } query.bindValue( outCode, msgCode, QSql::Out ); query.bindValue( outMsg, msgText, QSql::Out ); if ( !query.exec() ) { QgsDebugMsg( QString( "error: %1; sql: %2" ).arg( query.lastError().text(), query.lastQuery() ) ); } else { msgCode = query.boundValue( outCode ).toInt(); msgText = query.boundValue( outMsg ).toString(); // never gets a value... if ( 0 != msgCode ) { QgsDebugMsg( QString( "Register failed with code: %1; text: '%2'" ).arg( msgCode ).arg( msgText.toString() ) ); } else { QgsDebugMsg( "Register successful" ); } } QList<QVariant> list = query.boundValues().values(); for ( int i = 0; i < list.size(); ++i ) { QgsDebugMsg( QString( "i: %1; value: %2; type: %3" ) .arg( i ).arg( list.at( i ).toString().toLatin1().data() ).arg( list.at( i ).typeName() ) ); } } // clear any resources hold by the query q.clear(); q.setForwardOnly( true ); } QgsDebugMsg( "successfully created empty layer" ); return QgsVectorLayerImport::NoError; }
/** * Display the attrbiutes for the current feature and load the image */ void eVisGenericEventBrowserGui::loadRecord() { treeEventData->clear(); //Get a pointer to the current feature QgsFeature* myFeature; myFeature = featureAtId( mFeatureIds.at( mCurrentFeatureIndex ) ); if ( !myFeature ) return; QString myCompassBearingField = cboxCompassBearingField->currentText(); QString myCompassOffsetField = cboxCompassOffsetField->currentText(); QString myEventImagePathField = cboxEventImagePathField->currentText(); QgsFields myFields = mDataProvider->fields(); QgsAttributes myAttrs = myFeature->attributes(); //loop through the attributes and display their contents for ( int i = 0; i < myAttrs.count(); ++i ) { QStringList myValues; QString fieldName = myFields.at( i ).name(); myValues << fieldName << myAttrs.at( i ).toString(); QTreeWidgetItem* myItem = new QTreeWidgetItem( myValues ); if ( fieldName == myEventImagePathField ) { mEventImagePath = myAttrs.at( i ).toString(); } if ( fieldName == myCompassBearingField ) { mCompassBearing = myAttrs.at( i ).toDouble(); } if ( mConfiguration.isAttributeCompassOffsetSet() ) { if ( fieldName == myCompassOffsetField ) { mCompassOffset = myAttrs.at( i ).toDouble(); } } else { mCompassOffset = 0.0; } //Check to see if the attribute is a know file type int myIterator = 0; while ( myIterator < tableFileTypeAssociations->rowCount() ) { if ( tableFileTypeAssociations->item( myIterator, 0 ) && ( myAttrs.at( i ).toString().startsWith( tableFileTypeAssociations->item( myIterator, 0 )->text() + ':', Qt::CaseInsensitive ) || myAttrs.at( i ).toString().endsWith( tableFileTypeAssociations->item( myIterator, 0 )->text(), Qt::CaseInsensitive ) ) ) { myItem->setBackground( 1, QBrush( QColor( 183, 216, 125, 255 ) ) ); break; } else myIterator++; } treeEventData->addTopLevelItem( myItem ); } //Modify EventImagePath as needed buildEventImagePath(); //Request the image to be displayed in the browser displayImage(); }