35 #include <QPushButton> 37 #include <QMessageBox> 38 #include <QFileDialog> 42 #include <ogr_srs_api.h> 43 #include <gdal_version.h> 44 #include <cpl_error.h> 45 #include <cpl_string.h> 47 #define DEFAULT_OGR_FID_COLUMN_TITLE "fid" // default value from OGR 50 : QDialog( parent, fl )
55 connect( mAddAttributeButton, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked );
56 connect( mRemoveAttributeButton, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked );
57 connect( mFieldTypeBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged );
58 connect( mGeometryTypeBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged );
59 connect( mTableNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textChanged );
60 connect( mTableNameEdit, &QLineEdit::textEdited,
this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textEdited );
61 connect( mLayerIdentifierEdit, &QLineEdit::textEdited,
this, &QgsNewGeoPackageLayerDialog::mLayerIdentifierEdit_textEdited );
62 connect( buttonBox, &QDialogButtonBox::accepted,
this, &QgsNewGeoPackageLayerDialog::buttonBox_accepted );
63 connect( buttonBox, &QDialogButtonBox::rejected,
this, &QgsNewGeoPackageLayerDialog::buttonBox_rejected );
64 connect( buttonBox, &QDialogButtonBox::helpRequested,
this, &QgsNewGeoPackageLayerDialog::showHelp );
73 mGeometryTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconPointLayer.svg" ) ), tr(
"MultiPoint" ), wkbMultiPoint );
74 mGeometryTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconLineLayer.svg" ) ), tr(
"MultiLine" ), wkbMultiLineString );
75 mGeometryTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconPolygonLayer.svg" ) ), tr(
"MultiPolygon" ), wkbMultiPolygon );
79 mGeometryTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconLineLayer.svg" ) ), tr(
"CircularString" ), wkbCircularString );
81 mGeometryTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconLineLayer.svg" ) ), tr(
"CompoundCurve" ), wkbCompoundCurve );
82 mGeometryTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconPolygonLayer.svg" ) ), tr(
"CurvePolygon" ), wkbCurvePolygon );
84 mGeometryTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconPolygonLayer.svg" ) ), tr(
"MultiSurface" ), wkbMultiSurface );
86 mGeometryWithZCheckBox->setEnabled(
false );
87 mGeometryWithMCheckBox->setEnabled(
false );
88 mGeometryColumnEdit->setEnabled(
false );
89 mGeometryColumnEdit->setText( QStringLiteral(
"geometry" ) );
91 mCheckBoxCreateSpatialIndex->setEnabled(
false );
92 mCrsSelector->setEnabled(
false );
95 mFieldTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconFieldInteger.svg" ) ), tr(
"Whole number (integer)" ),
"integer" );
96 mFieldTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconFieldInteger.svg" ) ), tr(
"Whole number (integer 64 bit)" ),
"integer64" );
97 mFieldTypeBox->addItem(
QgsApplication::getThemeIcon( QStringLiteral(
"/mIconFieldFloat.svg" ) ), tr(
"Decimal number (real)" ),
"real" );
103 mOkButton = buttonBox->button( QDialogButtonBox::Ok );
104 mOkButton->setEnabled(
false );
106 connect( mFieldNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::fieldNameChanged );
107 connect( mAttributeView, &QTreeWidget::itemSelectionChanged,
this, &QgsNewGeoPackageLayerDialog::selectionChanged );
108 connect( mTableNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::checkOk );
110 mAddAttributeButton->setEnabled(
false );
111 mRemoveAttributeButton->setEnabled(
false );
113 mCheckBoxCreateSpatialIndex->setChecked(
true );
117 mDatabase->setFilter( tr(
"GeoPackage" ) +
" (*.gpkg)" );
118 mDatabase->setDialogTitle( tr(
"Select Existing or Create a New GeoPackage Database Fileā¦" ) );
119 mDatabase->setDefaultRoot( settings.
value( QStringLiteral(
"UI/lastVectorFileFilterDir" ), QDir::homePath() ).toString() );
120 mDatabase->setConfirmOverwrite(
false );
124 QFileInfo tmplFileInfo( filePath );
125 settings.
setValue( QStringLiteral(
"UI/lastVectorFileFilterDir" ), tmplFileInfo.absolutePath() );
126 if ( !filePath.isEmpty() && !mTableNameEdited )
128 QFileInfo fileInfo( filePath );
129 mTableNameEdit->setText( fileInfo.baseName() );
137 mCrsSelector->setCrs( crs );
142 mDatabase->setReadOnly(
true );
145 void QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged(
int )
147 QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
148 mFieldLengthEdit->setEnabled( myType == QLatin1String(
"text" ) );
149 if ( myType != QLatin1String(
"text" ) )
150 mFieldLengthEdit->clear();
154 void QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged(
int )
156 OGRwkbGeometryType geomType =
static_cast<OGRwkbGeometryType
> 157 ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
158 bool isSpatial = geomType != wkbNone;
159 mGeometryWithZCheckBox->setEnabled( isSpatial );
160 mGeometryWithMCheckBox->setEnabled( isSpatial );
161 mGeometryColumnEdit->setEnabled( isSpatial );
162 mCheckBoxCreateSpatialIndex->setEnabled( isSpatial );
163 mCrsSelector->setEnabled( isSpatial );
166 void QgsNewGeoPackageLayerDialog::mTableNameEdit_textChanged(
const QString &text )
168 mTableNameEdited = !text.isEmpty();
169 if ( !text.isEmpty() && !mLayerIdentifierEdited )
171 mLayerIdentifierEdit->setText( text );
175 void QgsNewGeoPackageLayerDialog::mTableNameEdit_textEdited(
const QString &text )
178 mTableNameEdited = !text.isEmpty();
181 void QgsNewGeoPackageLayerDialog::mLayerIdentifierEdit_textEdited(
const QString &text )
184 mLayerIdentifierEdited = !text.isEmpty();
187 void QgsNewGeoPackageLayerDialog::checkOk()
189 bool ok = !mDatabase->filePath().isEmpty() &&
190 !mTableNameEdit->text().isEmpty();
191 mOkButton->setEnabled( ok );
194 void QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked()
196 if ( !mFieldNameEdit->text().isEmpty() )
198 QString myName = mFieldNameEdit->text();
199 const QString featureId = mFeatureIdColumnEdit->text().isEmpty() ? QStringLiteral(
DEFAULT_OGR_FID_COLUMN_TITLE ) : mFeatureIdColumnEdit->text();
200 if ( myName.compare( featureId, Qt::CaseInsensitive ) == 0 )
202 QMessageBox::critical(
this, tr(
"Add Field" ), tr(
"The field cannot have the same name as the feature identifier." ) );
207 QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
208 QString length = mFieldLengthEdit->text();
209 mAttributeView->addTopLevelItem(
new QTreeWidgetItem( QStringList() << myName << myType << length ) );
213 mFieldNameEdit->clear();
217 void QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked()
219 delete mAttributeView->currentItem();
224 void QgsNewGeoPackageLayerDialog::fieldNameChanged(
const QString &name )
226 mAddAttributeButton->setDisabled( name.isEmpty() || ! mAttributeView->findItems( name, Qt::MatchExactly ).isEmpty() );
229 void QgsNewGeoPackageLayerDialog::selectionChanged()
231 mRemoveAttributeButton->setDisabled( mAttributeView->selectedItems().isEmpty() );
234 void QgsNewGeoPackageLayerDialog::buttonBox_accepted()
240 void QgsNewGeoPackageLayerDialog::buttonBox_rejected()
245 bool QgsNewGeoPackageLayerDialog::apply()
247 QString fileName( mDatabase->filePath() );
248 if ( !fileName.endsWith( QLatin1String(
".gpkg" ), Qt::CaseInsensitive ) )
249 fileName += QLatin1String(
".gpkg" );
251 bool createNewDb =
false;
253 if ( QFile( fileName ).exists( fileName ) )
255 bool overwrite =
false;
262 msgBox.setIcon( QMessageBox::Question );
263 msgBox.setWindowTitle( tr(
"New GeoPackage Layer" ) );
264 msgBox.setText( tr(
"The File already exists. Do you want to overwrite the existing file with a new database or add a new layer to it?" ) );
265 QPushButton *overwriteButton = msgBox.addButton( tr(
"Overwrite" ), QMessageBox::ActionRole );
266 QPushButton *addNewLayerButton = msgBox.addButton( tr(
"Add New Layer" ), QMessageBox::ActionRole );
267 msgBox.setStandardButtons( QMessageBox::Cancel );
268 msgBox.setDefaultButton( addNewLayerButton );
270 if ( property(
"hideDialogs" ).toBool() )
272 overwrite = property(
"question_existing_db_answer_overwrite" ).toBool();
274 cancel = !property(
"question_existing_db_answer_add_new_layer" ).toBool();
278 int ret = msgBox.exec();
279 if ( ret == QMessageBox::Cancel )
281 if ( msgBox.clickedButton() == overwriteButton )
302 QFile( fileName ).remove();
311 OGRSFDriverH hGpkgDriver = OGRGetDriverByName(
"GPKG" );
314 if ( !property(
"hideDialogs" ).toBool() )
315 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ),
316 tr(
"Layer creation failed. GeoPackage driver not found." ) );
323 hDS.reset( OGR_Dr_CreateDataSource( hGpkgDriver, fileName.toUtf8().constData(), nullptr ) );
326 QString msg( tr(
"Creation of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
327 if ( !property(
"hideDialogs" ).toBool() )
328 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
334 OGRSFDriverH hDriver =
nullptr;
335 hDS.reset( OGROpen( fileName.toUtf8().constData(),
true, &hDriver ) );
338 QString msg( tr(
"Opening of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
339 if ( !property(
"hideDialogs" ).toBool() )
340 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
343 if ( hDriver != hGpkgDriver )
345 QString msg( tr(
"Opening of file succeeded, but this is not a GeoPackage database." ) );
346 if ( !property(
"hideDialogs" ).toBool() )
347 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
352 QString tableName( mTableNameEdit->text() );
354 bool overwriteTable =
false;
355 if ( OGR_DS_GetLayerByName( hDS.get(), tableName.toUtf8().constData() ) )
357 if ( property(
"hideDialogs" ).toBool() )
359 overwriteTable = property(
"question_existing_layer_answer_overwrite" ).toBool();
361 else if ( QMessageBox::question(
this, tr(
"New GeoPackage Layer" ),
362 tr(
"A table with the same name already exists. Do you want to overwrite it?" ),
363 QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) == QMessageBox::Yes )
365 overwriteTable =
true;
368 if ( !overwriteTable )
374 QString layerIdentifier( mLayerIdentifierEdit->text() );
375 QString layerDescription( mLayerDescriptionEdit->text() );
377 OGRwkbGeometryType wkbType =
static_cast<OGRwkbGeometryType
> 378 ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
381 if ( mGeometryWithZCheckBox->isChecked() )
382 wkbType = OGR_GT_SetZ( wkbType );
384 if ( mGeometryWithMCheckBox->isChecked() )
385 wkbType = OGR_GT_SetM( wkbType );
390 if ( wkbType != wkbNone && srs.
isValid() )
392 QString srsWkt = srs.
toWkt();
393 hSRS = OSRNewSpatialReference( srsWkt.toLocal8Bit().data() );
397 char **options =
nullptr;
399 if ( overwriteTable )
400 options = CSLSetNameValue( options,
"OVERWRITE",
"YES" );
401 if ( !layerIdentifier.isEmpty() )
402 options = CSLSetNameValue( options,
"IDENTIFIER", layerIdentifier.toUtf8().constData() );
403 if ( !layerDescription.isEmpty() )
404 options = CSLSetNameValue( options,
"DESCRIPTION", layerDescription.toUtf8().constData() );
406 QString featureId( mFeatureIdColumnEdit->text() );
407 if ( !featureId.isEmpty() )
408 options = CSLSetNameValue( options,
"FID", featureId.toUtf8().constData() );
410 QString geometryColumn( mGeometryColumnEdit->text() );
411 if ( wkbType != wkbNone && !geometryColumn.isEmpty() )
412 options = CSLSetNameValue( options,
"GEOMETRY_COLUMN", geometryColumn.toUtf8().constData() );
414 if ( wkbType != wkbNone )
415 options = CSLSetNameValue( options,
"SPATIAL_INDEX", mCheckBoxCreateSpatialIndex->isChecked() ?
"YES" :
"NO" );
417 OGRLayerH hLayer = OGR_DS_CreateLayer( hDS.get(), tableName.toUtf8().constData(), hSRS, wkbType, options );
418 CSLDestroy( options );
423 QString msg( tr(
"Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
424 if ( !property(
"hideDialogs" ).toBool() )
425 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
429 QTreeWidgetItemIterator it( mAttributeView );
432 QString fieldName( ( *it )->text( 0 ) );
433 QString fieldType( ( *it )->text( 1 ) );
434 QString fieldWidth( ( *it )->text( 2 ) );
437 OGRFieldType ogrType( OFTString );
438 if ( fieldType == QLatin1String(
"text" ) )
440 else if ( fieldType == QLatin1String(
"integer" ) )
441 ogrType = OFTInteger;
442 else if ( fieldType == QLatin1String(
"integer64" ) )
443 ogrType = OFTInteger64;
444 else if ( fieldType == QLatin1String(
"real" ) )
446 else if ( fieldType == QLatin1String(
"date" ) )
448 else if ( fieldType == QLatin1String(
"datetime" ) )
449 ogrType = OFTDateTime;
450 else if ( fieldType == QLatin1String(
"bool" ) )
452 ogrType = OFTInteger;
455 else if ( fieldType == QLatin1String(
"binary" ) )
458 int ogrWidth = fieldWidth.toInt();
461 if ( ogrType != OFTBinary )
462 OGR_Fld_SetWidth( fld.get(), ogrWidth );
464 OGR_Fld_SetSubType( fld.get(), OFSTBoolean );
466 if ( OGR_L_CreateField( hLayer, fld.get(), true ) != OGRERR_NONE )
468 if ( !property(
"hideDialogs" ).toBool() )
470 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ),
471 tr(
"Creation of field %1 failed (OGR error: %2)" )
472 .arg( fieldName, QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
483 OGR_L_ResetReading( hLayer );
484 if ( CPLGetLastErrorType() != CE_None )
486 QString msg( tr(
"Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
487 if ( !property(
"hideDialogs" ).toBool() )
488 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
493 QString uri( QStringLiteral(
"%1|layername=%2" ).arg( fileName, tableName ) );
494 QString userVisiblelayerName( layerIdentifier.isEmpty() ? tableName : layerIdentifier );
496 std::unique_ptr< QgsVectorLayer > layer = qgis::make_unique< QgsVectorLayer >( uri, userVisiblelayerName, QStringLiteral(
"ogr" ), layerOptions );
497 if ( layer->isValid() )
502 QList<QgsMapLayer *> myList;
503 myList << layer.release();
516 if ( !property(
"hideDialogs" ).toBool() )
517 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), tr(
"%1 is an invalid layer and cannot be loaded." ).arg( tableName ) );
525 mBehavior = behavior;
530 mAddToProject = addToProject;
533 void QgsNewGeoPackageLayerDialog::showHelp()
535 QgsHelp::openHelp( QStringLiteral(
"managing_data_source/create_layers.html#creating-a-new-geopackage-layer" ) );
void setOverwriteBehavior(OverwriteBehavior behavior)
Sets the behavior to use when a path to an existing geopackage file is used.
#define DEFAULT_OGR_FID_COLUMN_TITLE
This class is a composition of two QSettings instances:
Setting options for loading vector layers.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
QgsNewGeoPackageLayerDialog(QWidget *parent=nullptr, Qt::WindowFlags fl=QgsGuiUtils::ModalDialogFlags)
Constructor.
static QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
Keep existing contents and add new layer.
const QgsCoordinateReferenceSystem & crs
OverwriteBehavior
Behavior to use when an existing geopackage already exists.
Overwrite whole geopackage.
void setAddToProject(bool addToProject)
Sets whether a newly created layer should automatically be added to the current project.
QgsCoordinateTransformContext transformContext
void lockDatabasePath()
Sets the database path widgets to a locked and read-only mode.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
static QgsProject * instance()
Returns the QgsProject singleton instance.
This class represents a coordinate reference system (CRS).
QString toWkt() const
Returns a WKT representation of this CRS.
std::unique_ptr< std::remove_pointer< OGRFieldDefnH >::type, OGRFldDeleter > ogr_field_def_unique_ptr
Scoped OGR field definition.
static void enableAutoGeometryRestore(QWidget *widget, const QString &key=QString())
Register the widget to allow its position to be automatically saved and restored when open and closed...
static void openHelp(const QString &key)
Opens help topic for the given help key using default system web browser.
void setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the crs value for the new layer in the dialog.
std::unique_ptr< std::remove_pointer< OGRDataSourceH >::type, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.
void * OGRSpatialReferenceH
bool isValid() const
Returns whether this CRS is correctly initialized and usable.