23#include <cpl_string.h>
24#include <gdal_version.h>
26#include <ogr_srs_api.h>
47#include "moc_qgsnewgeopackagelayerdialog.cpp"
49#define DEFAULT_OGR_FID_COLUMN_TITLE "fid"
52 : QDialog( parent, fl )
55 setObjectName( QStringLiteral(
"QgsNewGeoPackageLayerDialog" ) );
58 connect( mAddAttributeButton, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked );
59 connect( mRemoveAttributeButton, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked );
60 connect( mFieldTypeBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged );
61 connect( mGeometryTypeBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged );
62 connect( mTableNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textChanged );
63 connect( mTableNameEdit, &QLineEdit::textEdited,
this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textEdited );
64 connect( mLayerIdentifierEdit, &QLineEdit::textEdited,
this, &QgsNewGeoPackageLayerDialog::mLayerIdentifierEdit_textEdited );
65 connect( buttonBox, &QDialogButtonBox::accepted,
this, &QgsNewGeoPackageLayerDialog::buttonBox_accepted );
66 connect( buttonBox, &QDialogButtonBox::rejected,
this, &QgsNewGeoPackageLayerDialog::buttonBox_rejected );
67 connect( buttonBox, &QDialogButtonBox::helpRequested,
this, &QgsNewGeoPackageLayerDialog::showHelp );
68 connect( mButtonUp, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::moveFieldsUp );
69 connect( mButtonDown, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::moveFieldsDown );
74 const auto addGeomItem = [
this]( OGRwkbGeometryType ogrGeomType ) {
79 addGeomItem( wkbNone );
80 addGeomItem( wkbPoint );
81 addGeomItem( wkbLineString );
82 addGeomItem( wkbPolygon );
83 addGeomItem( wkbMultiPoint );
84 addGeomItem( wkbMultiLineString );
85 addGeomItem( wkbMultiPolygon );
89 addGeomItem( wkbCircularString );
91 addGeomItem( wkbCompoundCurve );
92 addGeomItem( wkbCurvePolygon );
93 addGeomItem( wkbMultiCurve );
94 addGeomItem( wkbMultiSurface );
95 mGeometryTypeBox->setCurrentIndex( -1 );
97 mGeometryWithZCheckBox->setEnabled(
false );
98 mGeometryWithMCheckBox->setEnabled(
false );
99 mGeometryColumnEdit->setEnabled(
false );
100 mGeometryColumnEdit->setText( QStringLiteral(
"geometry" ) );
102 mCheckBoxCreateSpatialIndex->setEnabled(
false );
103 mCrsSelector->setEnabled(
false );
104 mCrsSelector->setShowAccuracyWarnings(
true );
116 mOkButton = buttonBox->button( QDialogButtonBox::Ok );
117 mOkButton->setEnabled(
false );
119 connect( mFieldNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::fieldNameChanged );
120 connect( mAttributeView, &QTreeWidget::itemSelectionChanged,
this, &QgsNewGeoPackageLayerDialog::selectionChanged );
121 connect( mTableNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::checkOk );
122 connect( mGeometryTypeBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::checkOk );
124 mAddAttributeButton->setEnabled(
false );
125 mRemoveAttributeButton->setEnabled(
false );
126 mButtonUp->setEnabled(
false );
127 mButtonDown->setEnabled(
false );
129 mCheckBoxCreateSpatialIndex->setChecked(
true );
133 mFileName->setFilter( tr(
"GeoPackage" ) +
" (*.gpkg)" );
134 mFileName->setDialogTitle( tr(
"Select Existing or Create a New GeoPackage Database File…" ) );
135 mFileName->setDefaultRoot( settings.
value( QStringLiteral(
"UI/lastVectorFileFilterDir" ), QDir::homePath() ).toString() );
136 mFileName->setConfirmOverwrite(
false );
139 const QFileInfo tmplFileInfo( filePath );
140 settings.
setValue( QStringLiteral(
"UI/lastVectorFileFilterDir" ), tmplFileInfo.absolutePath() );
141 if ( !filePath.isEmpty() && !mTableNameEdited )
143 const QFileInfo fileInfo( filePath );
144 mTableNameEdit->setText( fileInfo.baseName() );
151 QCompleter *completer =
new QCompleter(
this );
152 completer->setModel( ogrProviderModel );
154 completer->setCompletionMode( QCompleter::PopupCompletion );
155 completer->setFilterMode( Qt::MatchContains );
156 mFileName->lineEdit()->setCompleter( completer );
161 mCrsSelector->setCrs( crs );
166 mFileName->setReadOnly(
true );
169void QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged(
int )
171 const QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
172 mFieldLengthEdit->setEnabled( myType == QLatin1String(
"text" ) );
173 if ( myType != QLatin1String(
"text" ) )
174 mFieldLengthEdit->clear();
178void QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged(
int )
180 const OGRwkbGeometryType geomType =
static_cast<OGRwkbGeometryType
>( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
181 const bool isSpatial = geomType != wkbNone;
182 mGeometryWithZCheckBox->setEnabled( isSpatial );
183 mGeometryWithMCheckBox->setEnabled( isSpatial );
184 mGeometryColumnEdit->setEnabled( isSpatial );
185 mCheckBoxCreateSpatialIndex->setEnabled( isSpatial );
186 mCrsSelector->setEnabled( isSpatial );
189void QgsNewGeoPackageLayerDialog::mTableNameEdit_textChanged(
const QString &text )
191 mTableNameEdited = !text.isEmpty();
192 if ( !text.isEmpty() && !mLayerIdentifierEdited )
194 mLayerIdentifierEdit->setText( text );
198void QgsNewGeoPackageLayerDialog::mTableNameEdit_textEdited(
const QString &text )
201 mTableNameEdited = !text.isEmpty();
204void QgsNewGeoPackageLayerDialog::mLayerIdentifierEdit_textEdited(
const QString &text )
207 mLayerIdentifierEdited = !text.isEmpty();
210void QgsNewGeoPackageLayerDialog::checkOk()
212 const bool ok = !mFileName->filePath().isEmpty() && !mTableNameEdit->text().isEmpty() && mGeometryTypeBox->currentIndex() != -1;
214 mOkButton->setEnabled( ok );
217void QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked()
219 if ( !mFieldNameEdit->text().isEmpty() )
221 const QString myName = mFieldNameEdit->text();
222 const QString featureId = mFeatureIdColumnEdit->text().isEmpty() ? QStringLiteral(
DEFAULT_OGR_FID_COLUMN_TITLE ) : mFeatureIdColumnEdit->text();
223 if ( myName.compare( featureId, Qt::CaseInsensitive ) == 0 )
225 QMessageBox::critical( this, tr(
"Add Field" ), tr(
"The field cannot have the same name as the feature identifier." ) );
230 const QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
231 const QString length = mFieldLengthEdit->text();
232 mAttributeView->addTopLevelItem(
new QTreeWidgetItem( QStringList() << myName << myType << length ) );
236 mFieldNameEdit->clear();
238 if ( !mFieldNameEdit->hasFocus() )
240 mFieldNameEdit->setFocus();
245void QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked()
247 delete mAttributeView->currentItem();
252void QgsNewGeoPackageLayerDialog::fieldNameChanged(
const QString &name )
254 mAddAttributeButton->setDisabled( name.isEmpty() || !mAttributeView->findItems( name, Qt::MatchExactly ).isEmpty() );
257void QgsNewGeoPackageLayerDialog::selectionChanged()
259 mRemoveAttributeButton->setDisabled( mAttributeView->selectedItems().isEmpty() );
260 mButtonUp->setDisabled( mAttributeView->selectedItems().isEmpty() );
261 mButtonDown->setDisabled( mAttributeView->selectedItems().isEmpty() );
264void QgsNewGeoPackageLayerDialog::buttonBox_accepted()
270void QgsNewGeoPackageLayerDialog::buttonBox_rejected()
275void QgsNewGeoPackageLayerDialog::moveFieldsUp()
277 int currentRow = mAttributeView->currentIndex().row();
278 if ( currentRow == 0 )
281 mAttributeView->insertTopLevelItem( currentRow - 1, mAttributeView->takeTopLevelItem( currentRow ) );
282 mAttributeView->setCurrentIndex( mAttributeView->model()->index( currentRow - 1, 0 ) );
285void QgsNewGeoPackageLayerDialog::moveFieldsDown()
287 int currentRow = mAttributeView->currentIndex().row();
288 if ( currentRow == mAttributeView->topLevelItemCount() - 1 )
291 mAttributeView->insertTopLevelItem( currentRow + 1, mAttributeView->takeTopLevelItem( currentRow ) );
292 mAttributeView->setCurrentIndex( mAttributeView->model()->index( currentRow + 1, 0 ) );
295bool QgsNewGeoPackageLayerDialog::apply()
297 if ( !mFieldNameEdit->text().trimmed().isEmpty() )
299 const QString currentFieldName = mFieldNameEdit->text();
300 bool currentFound =
false;
301 QTreeWidgetItemIterator it( mAttributeView );
304 QTreeWidgetItem *item = *it;
305 if ( item->text( 0 ) == currentFieldName )
315 if ( QMessageBox::question(
this, windowTitle(), tr(
"The field “%1” has not been added to the fields list. Are you sure you want to proceed and discard this field?" ).arg( currentFieldName ), QMessageBox::Ok | QMessageBox::Cancel ) != QMessageBox::Ok )
322 QString fileName( mFileName->filePath() );
323 if ( !fileName.endsWith( QLatin1String(
".gpkg" ), Qt::CaseInsensitive ) )
324 fileName += QLatin1String(
".gpkg" );
326 bool createNewDb =
false;
328 if ( QFile::exists( fileName ) )
330 bool overwrite =
false;
337 msgBox.setIcon( QMessageBox::Question );
338 msgBox.setWindowTitle( tr(
"New GeoPackage Layer" ) );
339 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?" ) );
340 QPushButton *overwriteButton = msgBox.addButton( tr(
"Overwrite" ), QMessageBox::ActionRole );
341 QPushButton *addNewLayerButton = msgBox.addButton( tr(
"Add New Layer" ), QMessageBox::ActionRole );
342 msgBox.setStandardButtons( QMessageBox::Cancel );
343 msgBox.setDefaultButton( addNewLayerButton );
345 if ( property(
"hideDialogs" ).toBool() )
347 overwrite = property(
"question_existing_db_answer_overwrite" ).toBool();
349 cancel = !property(
"question_existing_db_answer_add_new_layer" ).toBool();
353 const int ret = msgBox.exec();
354 if ( ret == QMessageBox::Cancel )
356 if ( msgBox.clickedButton() == overwriteButton )
377 QFile( fileName ).remove();
386 OGRSFDriverH hGpkgDriver = OGRGetDriverByName(
"GPKG" );
389 if ( !property(
"hideDialogs" ).toBool() )
390 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), tr(
"Layer creation failed. GeoPackage driver not found." ) );
397 hDS.reset( OGR_Dr_CreateDataSource( hGpkgDriver, fileName.toUtf8().constData(),
nullptr ) );
400 const QString msg( tr(
"Creation of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
401 if ( !property(
"hideDialogs" ).toBool() )
402 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
408 OGRSFDriverH hDriver =
nullptr;
409 hDS.reset( OGROpen( fileName.toUtf8().constData(),
true, &hDriver ) );
412 const QString msg( tr(
"Opening of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
413 if ( !property(
"hideDialogs" ).toBool() )
414 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
417 if ( hDriver != hGpkgDriver )
419 const QString msg( tr(
"Opening of file succeeded, but this is not a GeoPackage database." ) );
420 if ( !property(
"hideDialogs" ).toBool() )
421 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
426 const QString tableName( mTableNameEdit->text() );
428 bool overwriteTable =
false;
429 if ( OGR_DS_GetLayerByName( hDS.get(), tableName.toUtf8().constData() ) )
431 if ( property(
"hideDialogs" ).toBool() )
433 overwriteTable = property(
"question_existing_layer_answer_overwrite" ).toBool();
435 else if ( QMessageBox::question(
this, tr(
"New GeoPackage Layer" ), tr(
"A table with the same name already exists. Do you want to overwrite it?" ), QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) == QMessageBox::Yes )
437 overwriteTable =
true;
440 if ( !overwriteTable )
446 const QString layerIdentifier( mLayerIdentifierEdit->text() );
447 const QString layerDescription( mLayerDescriptionEdit->text() );
449 OGRwkbGeometryType wkbType =
static_cast<OGRwkbGeometryType
>( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
452 if ( mGeometryWithZCheckBox->isChecked() )
453 wkbType = OGR_GT_SetZ( wkbType );
455 if ( mGeometryWithMCheckBox->isChecked() )
456 wkbType = OGR_GT_SetM( wkbType );
458 OGRSpatialReferenceH hSRS =
nullptr;
460 const QgsCoordinateReferenceSystem srs = mCrsSelector->crs();
461 if ( wkbType != wkbNone && srs.
isValid() )
467 char **options =
nullptr;
469 if ( overwriteTable )
470 options = CSLSetNameValue( options,
"OVERWRITE",
"YES" );
471 if ( !layerIdentifier.isEmpty() )
472 options = CSLSetNameValue( options,
"IDENTIFIER", layerIdentifier.toUtf8().constData() );
473 if ( !layerDescription.isEmpty() )
474 options = CSLSetNameValue( options,
"DESCRIPTION", layerDescription.toUtf8().constData() );
476 const QString featureId( mFeatureIdColumnEdit->text() );
477 if ( !featureId.isEmpty() )
478 options = CSLSetNameValue( options,
"FID", featureId.toUtf8().constData() );
480 const QString geometryColumn( mGeometryColumnEdit->text() );
481 if ( wkbType != wkbNone && !geometryColumn.isEmpty() )
482 options = CSLSetNameValue( options,
"GEOMETRY_COLUMN", geometryColumn.toUtf8().constData() );
484 if ( wkbType != wkbNone )
485 options = CSLSetNameValue( options,
"SPATIAL_INDEX", mCheckBoxCreateSpatialIndex->isChecked() ?
"YES" :
"NO" );
487 OGRLayerH hLayer = OGR_DS_CreateLayer( hDS.get(), tableName.toUtf8().constData(), hSRS, wkbType, options );
488 CSLDestroy( options );
493 const QString msg( tr(
"Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
494 if ( !property(
"hideDialogs" ).toBool() )
495 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
499 QTreeWidgetItemIterator it( mAttributeView );
502 const QString fieldName( ( *it )->text( 0 ) );
503 const QString fieldType( ( *it )->text( 1 ) );
504 const QString fieldWidth( ( *it )->text( 2 ) );
506 OGRFieldType ogrType( OFTString );
507 OGRFieldSubType ogrSubType = OFSTNone;
508 if ( fieldType == QLatin1String(
"text" ) )
510 else if ( fieldType == QLatin1String(
"integer" ) )
511 ogrType = OFTInteger;
512 else if ( fieldType == QLatin1String(
"integer64" ) )
513 ogrType = OFTInteger64;
514 else if ( fieldType == QLatin1String(
"real" ) )
516 else if ( fieldType == QLatin1String(
"date" ) )
518 else if ( fieldType == QLatin1String(
"datetime" ) )
519 ogrType = OFTDateTime;
520 else if ( fieldType == QLatin1String(
"bool" ) )
522 ogrType = OFTInteger;
523 ogrSubType = OFSTBoolean;
525 else if ( fieldType == QLatin1String(
"binary" ) )
527 else if ( fieldType == QLatin1String(
"json" ) )
530 ogrSubType = OFSTJSON;
533 const int ogrWidth = fieldWidth.toInt();
536 if ( ogrSubType != OFSTNone )
537 OGR_Fld_SetSubType( fld.get(), ogrSubType );
539 if ( ogrType != OFTBinary )
540 OGR_Fld_SetWidth( fld.get(), ogrWidth );
542 if ( OGR_L_CreateField( hLayer, fld.get(),
true ) != OGRERR_NONE )
544 if ( !property(
"hideDialogs" ).toBool() )
546 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), tr(
"Creation of field %1 failed (OGR error: %2)" ).arg( fieldName, QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
557 OGR_L_ResetReading( hLayer );
558 if ( CPLGetLastErrorType() != CE_None )
560 const QString msg( tr(
"Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
561 if ( !property(
"hideDialogs" ).toBool() )
562 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
567 const QString uri( QStringLiteral(
"%1|layername=%2" ).arg( fileName, tableName ) );
568 const QString userVisiblelayerName( layerIdentifier.isEmpty() ? tableName : layerIdentifier );
570 auto layer = std::make_unique<QgsVectorLayer>( uri, userVisiblelayerName, QStringLiteral(
"ogr" ), layerOptions );
571 if ( layer->isValid() )
576 QList<QgsMapLayer *> myList;
577 myList << layer.release();
590 if ( !property(
"hideDialogs" ).toBool() )
591 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), tr(
"%1 is an invalid layer and cannot be loaded." ).arg( tableName ) );
599 mBehavior = behavior;
604 mAddToProject = addToProject;
607void QgsNewGeoPackageLayerDialog::showHelp()
609 QgsHelp::openHelp( QStringLiteral(
"managing_data_source/create_layers.html#creating-a-new-geopackage-layer" ) );
WkbType
The WKB type describes the number of dimensions a geometry has.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
static QIcon iconForFieldType(QMetaType::Type type, QMetaType::Type subType=QMetaType::Type::UnknownType, const QString &typeString=QString())
Returns an icon corresponding to a field type.
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.
static QIcon iconForWkbType(Qgis::WkbType type)
Returns the icon for a vector layer whose geometry type is provided.
OverwriteBehavior
Behavior to use when an existing geopackage already exists.
@ AddNewLayer
Keep existing contents and add new layer.
@ Overwrite
Overwrite whole geopackage.
@ Prompt
Prompt user for action.
void setAddToProject(bool addToProject)
Sets whether a newly created layer should automatically be added to the current project.
void setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the crs value for the new layer in the dialog.
void lockDatabasePath()
Sets the database path widgets to a locked and read-only mode.
QgsNewGeoPackageLayerDialog(QWidget *parent=nullptr, Qt::WindowFlags fl=QgsGuiUtils::ModalDialogFlags)
Constructor.
void setOverwriteBehavior(OverwriteBehavior behavior)
Sets the behavior to use when a path to an existing geopackage file is used.
static Qgis::WkbType ogrGeometryTypeToQgsWkbType(OGRwkbGeometryType ogrGeomType)
Converts a OGRwkbGeometryType to QgsWkbTypes::Type.
static OGRSpatialReferenceH crsToOGRSpatialReference(const QgsCoordinateReferenceSystem &crs)
Returns a OGRSpatialReferenceH corresponding to the specified crs object.
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsCoordinateTransformContext transformContext
A model containing registered connection names for a specific data provider.
@ Uri
Connection URI string.
Stores settings for use within QGIS.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
static QString typeToDisplayString(QMetaType::Type type, QMetaType::Type subType=QMetaType::Type::UnknownType)
Returns a user-friendly translated string representing a QVariant type.
static Q_INVOKABLE QString translatedDisplayString(Qgis::WkbType type)
Returns a translated display string type for a WKB type, e.g., the geometry name used in WKT geometry...
std::unique_ptr< std::remove_pointer< OGRDataSourceH >::type, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.
std::unique_ptr< std::remove_pointer< OGRFieldDefnH >::type, OGRFldDeleter > ogr_field_def_unique_ptr
Scoped OGR field definition.
#define DEFAULT_OGR_FID_COLUMN_TITLE