42#include <ogr_srs_api.h>
43#include <gdal_version.h>
45#include <cpl_string.h>
47#define DEFAULT_OGR_FID_COLUMN_TITLE "fid"
50 : QDialog( parent, fl )
53 setObjectName( QStringLiteral(
"QgsNewGeoPackageLayerDialog" ) );
56 connect( mAddAttributeButton, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked );
57 connect( mRemoveAttributeButton, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked );
58 connect( mFieldTypeBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged );
59 connect( mGeometryTypeBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged );
60 connect( mTableNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textChanged );
61 connect( mTableNameEdit, &QLineEdit::textEdited,
this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textEdited );
62 connect( mLayerIdentifierEdit, &QLineEdit::textEdited,
this, &QgsNewGeoPackageLayerDialog::mLayerIdentifierEdit_textEdited );
63 connect( buttonBox, &QDialogButtonBox::accepted,
this, &QgsNewGeoPackageLayerDialog::buttonBox_accepted );
64 connect( buttonBox, &QDialogButtonBox::rejected,
this, &QgsNewGeoPackageLayerDialog::buttonBox_rejected );
65 connect( buttonBox, &QDialogButtonBox::helpRequested,
this, &QgsNewGeoPackageLayerDialog::showHelp );
70 const auto addGeomItem = [
this]( OGRwkbGeometryType ogrGeomType )
76 addGeomItem( wkbNone );
77 addGeomItem( wkbPoint );
78 addGeomItem( wkbLineString );
79 addGeomItem( wkbPolygon );
80 addGeomItem( wkbMultiPoint );
81 addGeomItem( wkbMultiLineString );
82 addGeomItem( wkbMultiPolygon );
86 addGeomItem( wkbCircularString );
88 addGeomItem( wkbCompoundCurve );
89 addGeomItem( wkbCurvePolygon );
90 addGeomItem( wkbMultiCurve );
91 addGeomItem( wkbMultiSurface );
92 mGeometryTypeBox->setCurrentIndex( -1 );
94 mGeometryWithZCheckBox->setEnabled(
false );
95 mGeometryWithMCheckBox->setEnabled(
false );
96 mGeometryColumnEdit->setEnabled(
false );
97 mGeometryColumnEdit->setText( QStringLiteral(
"geometry" ) );
99 mCheckBoxCreateSpatialIndex->setEnabled(
false );
100 mCrsSelector->setEnabled(
false );
101 mCrsSelector->setShowAccuracyWarnings(
true );
113 mOkButton = buttonBox->button( QDialogButtonBox::Ok );
114 mOkButton->setEnabled(
false );
116 connect( mFieldNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::fieldNameChanged );
117 connect( mAttributeView, &QTreeWidget::itemSelectionChanged,
this, &QgsNewGeoPackageLayerDialog::selectionChanged );
118 connect( mTableNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::checkOk );
119 connect( mGeometryTypeBox,
static_cast<void( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::checkOk );
121 mAddAttributeButton->setEnabled(
false );
122 mRemoveAttributeButton->setEnabled(
false );
124 mCheckBoxCreateSpatialIndex->setChecked(
true );
128 mDatabase->setFilter( tr(
"GeoPackage" ) +
" (*.gpkg)" );
129 mDatabase->setDialogTitle( tr(
"Select Existing or Create a New GeoPackage Database File…" ) );
130 mDatabase->setDefaultRoot( settings.
value( QStringLiteral(
"UI/lastVectorFileFilterDir" ), QDir::homePath() ).toString() );
131 mDatabase->setConfirmOverwrite(
false );
135 const QFileInfo tmplFileInfo( filePath );
136 settings.
setValue( QStringLiteral(
"UI/lastVectorFileFilterDir" ), tmplFileInfo.absolutePath() );
137 if ( !filePath.isEmpty() && !mTableNameEdited )
139 const QFileInfo fileInfo( filePath );
140 mTableNameEdit->setText( fileInfo.baseName() );
147 QCompleter *completer =
new QCompleter(
this );
148 completer->setModel( ogrProviderModel );
150 completer->setCompletionMode( QCompleter::PopupCompletion );
151 completer->setFilterMode( Qt::MatchContains );
152 mDatabase->lineEdit()->setCompleter( completer );
157 mCrsSelector->setCrs(
crs );
162 mDatabase->setReadOnly(
true );
165void QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged(
int )
167 const QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
168 mFieldLengthEdit->setEnabled( myType == QLatin1String(
"text" ) );
169 if ( myType != QLatin1String(
"text" ) )
170 mFieldLengthEdit->clear();
174void QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged(
int )
176 const OGRwkbGeometryType geomType =
static_cast<OGRwkbGeometryType
>
177 ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
178 const bool isSpatial = geomType != wkbNone;
179 mGeometryWithZCheckBox->setEnabled( isSpatial );
180 mGeometryWithMCheckBox->setEnabled( isSpatial );
181 mGeometryColumnEdit->setEnabled( isSpatial );
182 mCheckBoxCreateSpatialIndex->setEnabled( isSpatial );
183 mCrsSelector->setEnabled( isSpatial );
186void QgsNewGeoPackageLayerDialog::mTableNameEdit_textChanged(
const QString &text )
188 mTableNameEdited = !text.isEmpty();
189 if ( !text.isEmpty() && !mLayerIdentifierEdited )
191 mLayerIdentifierEdit->setText( text );
195void QgsNewGeoPackageLayerDialog::mTableNameEdit_textEdited(
const QString &text )
198 mTableNameEdited = !text.isEmpty();
201void QgsNewGeoPackageLayerDialog::mLayerIdentifierEdit_textEdited(
const QString &text )
204 mLayerIdentifierEdited = !text.isEmpty();
207void QgsNewGeoPackageLayerDialog::checkOk()
209 const bool ok = !mDatabase->filePath().isEmpty() &&
210 !mTableNameEdit->text().isEmpty() &&
211 mGeometryTypeBox->currentIndex() != -1;
213 mOkButton->setEnabled( ok );
216void QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked()
218 if ( !mFieldNameEdit->text().isEmpty() )
220 const QString myName = mFieldNameEdit->text();
221 const QString featureId = mFeatureIdColumnEdit->text().isEmpty() ? QStringLiteral(
DEFAULT_OGR_FID_COLUMN_TITLE ) : mFeatureIdColumnEdit->text();
222 if ( myName.compare( featureId, Qt::CaseInsensitive ) == 0 )
224 QMessageBox::critical(
this, tr(
"Add Field" ), tr(
"The field cannot have the same name as the feature identifier." ) );
229 const QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
230 const QString length = mFieldLengthEdit->text();
231 mAttributeView->addTopLevelItem(
new QTreeWidgetItem( QStringList() << myName << myType << length ) );
235 mFieldNameEdit->clear();
239void QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked()
241 delete mAttributeView->currentItem();
246void QgsNewGeoPackageLayerDialog::fieldNameChanged(
const QString &name )
248 mAddAttributeButton->setDisabled( name.isEmpty() || ! mAttributeView->findItems( name, Qt::MatchExactly ).isEmpty() );
251void QgsNewGeoPackageLayerDialog::selectionChanged()
253 mRemoveAttributeButton->setDisabled( mAttributeView->selectedItems().isEmpty() );
256void QgsNewGeoPackageLayerDialog::buttonBox_accepted()
262void QgsNewGeoPackageLayerDialog::buttonBox_rejected()
267bool QgsNewGeoPackageLayerDialog::apply()
269 if ( !mFieldNameEdit->text().trimmed().isEmpty() )
271 const QString currentFieldName = mFieldNameEdit->text();
272 bool currentFound =
false;
273 QTreeWidgetItemIterator it( mAttributeView );
276 QTreeWidgetItem *item = *it;
277 if ( item->text( 0 ) == currentFieldName )
287 if ( QMessageBox::question(
this, windowTitle(),
288 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 ),
289 QMessageBox::Ok | QMessageBox::Cancel ) != QMessageBox::Ok )
296 QString fileName( mDatabase->filePath() );
297 if ( !fileName.endsWith( QLatin1String(
".gpkg" ), Qt::CaseInsensitive ) )
298 fileName += QLatin1String(
".gpkg" );
300 bool createNewDb =
false;
302 if ( QFile::exists( fileName ) )
304 bool overwrite =
false;
311 msgBox.setIcon( QMessageBox::Question );
312 msgBox.setWindowTitle( tr(
"New GeoPackage Layer" ) );
313 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?" ) );
314 QPushButton *overwriteButton = msgBox.addButton( tr(
"Overwrite" ), QMessageBox::ActionRole );
315 QPushButton *addNewLayerButton = msgBox.addButton( tr(
"Add New Layer" ), QMessageBox::ActionRole );
316 msgBox.setStandardButtons( QMessageBox::Cancel );
317 msgBox.setDefaultButton( addNewLayerButton );
319 if ( property(
"hideDialogs" ).toBool() )
321 overwrite = property(
"question_existing_db_answer_overwrite" ).toBool();
323 cancel = !property(
"question_existing_db_answer_add_new_layer" ).toBool();
327 const int ret = msgBox.exec();
328 if ( ret == QMessageBox::Cancel )
330 if ( msgBox.clickedButton() == overwriteButton )
351 QFile( fileName ).remove();
360 OGRSFDriverH hGpkgDriver = OGRGetDriverByName(
"GPKG" );
363 if ( !property(
"hideDialogs" ).toBool() )
364 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ),
365 tr(
"Layer creation failed. GeoPackage driver not found." ) );
372 hDS.reset( OGR_Dr_CreateDataSource( hGpkgDriver, fileName.toUtf8().constData(),
nullptr ) );
375 const QString msg( tr(
"Creation of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
376 if ( !property(
"hideDialogs" ).toBool() )
377 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
383 OGRSFDriverH hDriver =
nullptr;
384 hDS.reset( OGROpen( fileName.toUtf8().constData(),
true, &hDriver ) );
387 const QString msg( tr(
"Opening of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
388 if ( !property(
"hideDialogs" ).toBool() )
389 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
392 if ( hDriver != hGpkgDriver )
394 const QString msg( tr(
"Opening of file succeeded, but this is not a GeoPackage database." ) );
395 if ( !property(
"hideDialogs" ).toBool() )
396 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
401 const QString tableName( mTableNameEdit->text() );
403 bool overwriteTable =
false;
404 if ( OGR_DS_GetLayerByName( hDS.get(), tableName.toUtf8().constData() ) )
406 if ( property(
"hideDialogs" ).toBool() )
408 overwriteTable = property(
"question_existing_layer_answer_overwrite" ).toBool();
410 else if ( QMessageBox::question(
this, tr(
"New GeoPackage Layer" ),
411 tr(
"A table with the same name already exists. Do you want to overwrite it?" ),
412 QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) == QMessageBox::Yes )
414 overwriteTable =
true;
417 if ( !overwriteTable )
423 const QString layerIdentifier( mLayerIdentifierEdit->text() );
424 const QString layerDescription( mLayerDescriptionEdit->text() );
426 OGRwkbGeometryType wkbType =
static_cast<OGRwkbGeometryType
>
427 ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
430 if ( mGeometryWithZCheckBox->isChecked() )
431 wkbType = OGR_GT_SetZ( wkbType );
433 if ( mGeometryWithMCheckBox->isChecked() )
434 wkbType = OGR_GT_SetM( wkbType );
439 if ( wkbType != wkbNone && srs.
isValid() )
445 char **options =
nullptr;
447 if ( overwriteTable )
448 options = CSLSetNameValue( options,
"OVERWRITE",
"YES" );
449 if ( !layerIdentifier.isEmpty() )
450 options = CSLSetNameValue( options,
"IDENTIFIER", layerIdentifier.toUtf8().constData() );
451 if ( !layerDescription.isEmpty() )
452 options = CSLSetNameValue( options,
"DESCRIPTION", layerDescription.toUtf8().constData() );
454 const QString featureId( mFeatureIdColumnEdit->text() );
455 if ( !featureId.isEmpty() )
456 options = CSLSetNameValue( options,
"FID", featureId.toUtf8().constData() );
458 const QString geometryColumn( mGeometryColumnEdit->text() );
459 if ( wkbType != wkbNone && !geometryColumn.isEmpty() )
460 options = CSLSetNameValue( options,
"GEOMETRY_COLUMN", geometryColumn.toUtf8().constData() );
462 if ( wkbType != wkbNone )
463 options = CSLSetNameValue( options,
"SPATIAL_INDEX", mCheckBoxCreateSpatialIndex->isChecked() ?
"YES" :
"NO" );
465 OGRLayerH hLayer = OGR_DS_CreateLayer( hDS.get(), tableName.toUtf8().constData(), hSRS, wkbType, options );
466 CSLDestroy( options );
471 const QString msg( tr(
"Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
472 if ( !property(
"hideDialogs" ).toBool() )
473 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
477 QTreeWidgetItemIterator it( mAttributeView );
480 const QString fieldName( ( *it )->text( 0 ) );
481 const QString fieldType( ( *it )->text( 1 ) );
482 const QString fieldWidth( ( *it )->text( 2 ) );
484 OGRFieldType ogrType( OFTString );
485 OGRFieldSubType ogrSubType = OFSTNone;
486 if ( fieldType == QLatin1String(
"text" ) )
488 else if ( fieldType == QLatin1String(
"integer" ) )
489 ogrType = OFTInteger;
490 else if ( fieldType == QLatin1String(
"integer64" ) )
491 ogrType = OFTInteger64;
492 else if ( fieldType == QLatin1String(
"real" ) )
494 else if ( fieldType == QLatin1String(
"date" ) )
496 else if ( fieldType == QLatin1String(
"datetime" ) )
497 ogrType = OFTDateTime;
498 else if ( fieldType == QLatin1String(
"bool" ) )
500 ogrType = OFTInteger;
501 ogrSubType = OFSTBoolean;
503 else if ( fieldType == QLatin1String(
"binary" ) )
505 else if ( fieldType == QLatin1String(
"json" ) )
508 ogrSubType = OFSTJSON;
511 const int ogrWidth = fieldWidth.toInt();
514 if ( ogrSubType != OFSTNone )
515 OGR_Fld_SetSubType( fld.get(), ogrSubType );
517 if ( ogrType != OFTBinary )
518 OGR_Fld_SetWidth( fld.get(), ogrWidth );
520 if ( OGR_L_CreateField( hLayer, fld.get(),
true ) != OGRERR_NONE )
522 if ( !property(
"hideDialogs" ).toBool() )
524 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ),
525 tr(
"Creation of field %1 failed (OGR error: %2)" )
526 .arg( fieldName, QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
537 OGR_L_ResetReading( hLayer );
538 if ( CPLGetLastErrorType() != CE_None )
540 const QString msg( tr(
"Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
541 if ( !property(
"hideDialogs" ).toBool() )
542 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
547 const QString uri( QStringLiteral(
"%1|layername=%2" ).arg( fileName, tableName ) );
548 const QString userVisiblelayerName( layerIdentifier.isEmpty() ? tableName : layerIdentifier );
550 std::unique_ptr< QgsVectorLayer > layer = std::make_unique< QgsVectorLayer >( uri, userVisiblelayerName, QStringLiteral(
"ogr" ), layerOptions );
551 if ( layer->isValid() )
556 QList<QgsMapLayer *> myList;
557 myList << layer.release();
570 if ( !property(
"hideDialogs" ).toBool() )
571 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), tr(
"%1 is an invalid layer and cannot be loaded." ).arg( tableName ) );
579 mBehavior = behavior;
584 mAddToProject = addToProject;
587void QgsNewGeoPackageLayerDialog::showHelp()
589 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.
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
static QIcon iconForFieldType(QVariant::Type type, QVariant::Type subType=QVariant::Type::Invalid, 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.
@ RoleUri
Connection URI string.
This class is a composition of two QSettings instances:
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(QVariant::Type type, QVariant::Type subType=QVariant::Type::Invalid)
Returns a user-friendly translated string representing a QVariant type.
static 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.
void * OGRSpatialReferenceH
#define DEFAULT_OGR_FID_COLUMN_TITLE
const QgsCoordinateReferenceSystem & crs
Setting options for loading vector layers.