45#include <ogr_srs_api.h>
46#include <gdal_version.h>
48#include <cpl_string.h>
50#define DEFAULT_OGR_FID_COLUMN_TITLE "fid"
53 : QDialog( parent, fl )
56 setObjectName( QStringLiteral(
"QgsNewGeoPackageLayerDialog" ) );
59 connect( mAddAttributeButton, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked );
60 connect( mRemoveAttributeButton, &QToolButton::clicked,
this, &QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked );
61 connect( mFieldTypeBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged );
62 connect( mGeometryTypeBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged );
63 connect( mTableNameEdit, &QLineEdit::textChanged,
this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textChanged );
64 connect( mTableNameEdit, &QLineEdit::textEdited,
this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textEdited );
65 connect( mLayerIdentifierEdit, &QLineEdit::textEdited,
this, &QgsNewGeoPackageLayerDialog::mLayerIdentifierEdit_textEdited );
66 connect( buttonBox, &QDialogButtonBox::accepted,
this, &QgsNewGeoPackageLayerDialog::buttonBox_accepted );
67 connect( buttonBox, &QDialogButtonBox::rejected,
this, &QgsNewGeoPackageLayerDialog::buttonBox_rejected );
68 connect( buttonBox, &QDialogButtonBox::helpRequested,
this, &QgsNewGeoPackageLayerDialog::showHelp );
73 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 );
127 mCheckBoxCreateSpatialIndex->setChecked(
true );
131 mDatabase->setFilter( tr(
"GeoPackage" ) +
" (*.gpkg)" );
132 mDatabase->setDialogTitle( tr(
"Select Existing or Create a New GeoPackage Database File…" ) );
133 mDatabase->setDefaultRoot( settings.
value( QStringLiteral(
"UI/lastVectorFileFilterDir" ), QDir::homePath() ).toString() );
134 mDatabase->setConfirmOverwrite(
false );
138 const QFileInfo tmplFileInfo( filePath );
139 settings.
setValue( QStringLiteral(
"UI/lastVectorFileFilterDir" ), tmplFileInfo.absolutePath() );
140 if ( !filePath.isEmpty() && !mTableNameEdited )
142 const QFileInfo fileInfo( filePath );
143 mTableNameEdit->setText( fileInfo.baseName() );
150 QCompleter *completer =
new QCompleter(
this );
151 completer->setModel( ogrProviderModel );
153 completer->setCompletionMode( QCompleter::PopupCompletion );
154 completer->setFilterMode( Qt::MatchContains );
155 mDatabase->lineEdit()->setCompleter( completer );
160 mCrsSelector->setCrs(
crs );
165 mDatabase->setReadOnly(
true );
168void QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged(
int )
170 const QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
171 mFieldLengthEdit->setEnabled( myType == QLatin1String(
"text" ) );
172 if ( myType != QLatin1String(
"text" ) )
173 mFieldLengthEdit->clear();
177void QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged(
int )
179 const OGRwkbGeometryType geomType =
static_cast<OGRwkbGeometryType
>
180 ( 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 = !mDatabase->filePath().isEmpty() &&
213 !mTableNameEdit->text().isEmpty() &&
214 mGeometryTypeBox->currentIndex() != -1;
216 mOkButton->setEnabled( ok );
219void QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked()
221 if ( !mFieldNameEdit->text().isEmpty() )
223 const QString myName = mFieldNameEdit->text();
224 const QString featureId = mFeatureIdColumnEdit->text().isEmpty() ? QStringLiteral(
DEFAULT_OGR_FID_COLUMN_TITLE ) : mFeatureIdColumnEdit->text();
225 if ( myName.compare( featureId, Qt::CaseInsensitive ) == 0 )
227 QMessageBox::critical(
this, tr(
"Add Field" ), tr(
"The field cannot have the same name as the feature identifier." ) );
232 const QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
233 const QString length = mFieldLengthEdit->text();
234 mAttributeView->addTopLevelItem(
new QTreeWidgetItem( QStringList() << myName << myType << length ) );
238 mFieldNameEdit->clear();
242void QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked()
244 delete mAttributeView->currentItem();
249void QgsNewGeoPackageLayerDialog::fieldNameChanged(
const QString &name )
251 mAddAttributeButton->setDisabled( name.isEmpty() || ! mAttributeView->findItems( name, Qt::MatchExactly ).isEmpty() );
254void QgsNewGeoPackageLayerDialog::selectionChanged()
256 mRemoveAttributeButton->setDisabled( mAttributeView->selectedItems().isEmpty() );
259void QgsNewGeoPackageLayerDialog::buttonBox_accepted()
265void QgsNewGeoPackageLayerDialog::buttonBox_rejected()
270bool QgsNewGeoPackageLayerDialog::apply()
272 if ( !mFieldNameEdit->text().trimmed().isEmpty() )
274 const QString currentFieldName = mFieldNameEdit->text();
275 bool currentFound =
false;
276 QTreeWidgetItemIterator it( mAttributeView );
279 QTreeWidgetItem *item = *it;
280 if ( item->text( 0 ) == currentFieldName )
290 if ( QMessageBox::question(
this, windowTitle(),
291 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 ),
292 QMessageBox::Ok | QMessageBox::Cancel ) != QMessageBox::Ok )
299 QString fileName( mDatabase->filePath() );
300 if ( !fileName.endsWith( QLatin1String(
".gpkg" ), Qt::CaseInsensitive ) )
301 fileName += QLatin1String(
".gpkg" );
303 bool createNewDb =
false;
305 if ( QFile::exists( fileName ) )
307 bool overwrite =
false;
314 msgBox.setIcon( QMessageBox::Question );
315 msgBox.setWindowTitle( tr(
"New GeoPackage Layer" ) );
316 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?" ) );
317 QPushButton *overwriteButton = msgBox.addButton( tr(
"Overwrite" ), QMessageBox::ActionRole );
318 QPushButton *addNewLayerButton = msgBox.addButton( tr(
"Add New Layer" ), QMessageBox::ActionRole );
319 msgBox.setStandardButtons( QMessageBox::Cancel );
320 msgBox.setDefaultButton( addNewLayerButton );
322 if ( property(
"hideDialogs" ).toBool() )
324 overwrite = property(
"question_existing_db_answer_overwrite" ).toBool();
326 cancel = !property(
"question_existing_db_answer_add_new_layer" ).toBool();
330 const int ret = msgBox.exec();
331 if ( ret == QMessageBox::Cancel )
333 if ( msgBox.clickedButton() == overwriteButton )
354 QFile( fileName ).remove();
363 OGRSFDriverH hGpkgDriver = OGRGetDriverByName(
"GPKG" );
366 if ( !property(
"hideDialogs" ).toBool() )
367 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ),
368 tr(
"Layer creation failed. GeoPackage driver not found." ) );
375 hDS.reset( OGR_Dr_CreateDataSource( hGpkgDriver, fileName.toUtf8().constData(),
nullptr ) );
378 const QString msg( tr(
"Creation of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
379 if ( !property(
"hideDialogs" ).toBool() )
380 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
386 OGRSFDriverH hDriver =
nullptr;
387 hDS.reset( OGROpen( fileName.toUtf8().constData(),
true, &hDriver ) );
390 const QString msg( tr(
"Opening of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
391 if ( !property(
"hideDialogs" ).toBool() )
392 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
395 if ( hDriver != hGpkgDriver )
397 const QString msg( tr(
"Opening of file succeeded, but this is not a GeoPackage database." ) );
398 if ( !property(
"hideDialogs" ).toBool() )
399 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
404 const QString tableName( mTableNameEdit->text() );
406 bool overwriteTable =
false;
407 if ( OGR_DS_GetLayerByName( hDS.get(), tableName.toUtf8().constData() ) )
409 if ( property(
"hideDialogs" ).toBool() )
411 overwriteTable = property(
"question_existing_layer_answer_overwrite" ).toBool();
413 else if ( QMessageBox::question(
this, tr(
"New GeoPackage Layer" ),
414 tr(
"A table with the same name already exists. Do you want to overwrite it?" ),
415 QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) == QMessageBox::Yes )
417 overwriteTable =
true;
420 if ( !overwriteTable )
426 const QString layerIdentifier( mLayerIdentifierEdit->text() );
427 const QString layerDescription( mLayerDescriptionEdit->text() );
429 OGRwkbGeometryType wkbType =
static_cast<OGRwkbGeometryType
>
430 ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
433 if ( mGeometryWithZCheckBox->isChecked() )
434 wkbType = OGR_GT_SetZ( wkbType );
436 if ( mGeometryWithMCheckBox->isChecked() )
437 wkbType = OGR_GT_SetM( wkbType );
442 if ( wkbType != wkbNone && srs.
isValid() )
448 char **options =
nullptr;
450 if ( overwriteTable )
451 options = CSLSetNameValue( options,
"OVERWRITE",
"YES" );
452 if ( !layerIdentifier.isEmpty() )
453 options = CSLSetNameValue( options,
"IDENTIFIER", layerIdentifier.toUtf8().constData() );
454 if ( !layerDescription.isEmpty() )
455 options = CSLSetNameValue( options,
"DESCRIPTION", layerDescription.toUtf8().constData() );
457 const QString featureId( mFeatureIdColumnEdit->text() );
458 if ( !featureId.isEmpty() )
459 options = CSLSetNameValue( options,
"FID", featureId.toUtf8().constData() );
461 const QString geometryColumn( mGeometryColumnEdit->text() );
462 if ( wkbType != wkbNone && !geometryColumn.isEmpty() )
463 options = CSLSetNameValue( options,
"GEOMETRY_COLUMN", geometryColumn.toUtf8().constData() );
465 if ( wkbType != wkbNone )
466 options = CSLSetNameValue( options,
"SPATIAL_INDEX", mCheckBoxCreateSpatialIndex->isChecked() ?
"YES" :
"NO" );
468 OGRLayerH hLayer = OGR_DS_CreateLayer( hDS.get(), tableName.toUtf8().constData(), hSRS, wkbType, options );
469 CSLDestroy( options );
474 const QString msg( tr(
"Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
475 if ( !property(
"hideDialogs" ).toBool() )
476 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
480 QTreeWidgetItemIterator it( mAttributeView );
483 const QString fieldName( ( *it )->text( 0 ) );
484 const QString fieldType( ( *it )->text( 1 ) );
485 const QString fieldWidth( ( *it )->text( 2 ) );
487 OGRFieldType ogrType( OFTString );
488 OGRFieldSubType ogrSubType = OFSTNone;
489 if ( fieldType == QLatin1String(
"text" ) )
491 else if ( fieldType == QLatin1String(
"integer" ) )
492 ogrType = OFTInteger;
493 else if ( fieldType == QLatin1String(
"integer64" ) )
494 ogrType = OFTInteger64;
495 else if ( fieldType == QLatin1String(
"real" ) )
497 else if ( fieldType == QLatin1String(
"date" ) )
499 else if ( fieldType == QLatin1String(
"datetime" ) )
500 ogrType = OFTDateTime;
501 else if ( fieldType == QLatin1String(
"bool" ) )
503 ogrType = OFTInteger;
504 ogrSubType = OFSTBoolean;
506 else if ( fieldType == QLatin1String(
"binary" ) )
508 else if ( fieldType == QLatin1String(
"json" ) )
511 ogrSubType = OFSTJSON;
514 const int ogrWidth = fieldWidth.toInt();
517 if ( ogrSubType != OFSTNone )
518 OGR_Fld_SetSubType( fld.get(), ogrSubType );
520 if ( ogrType != OFTBinary )
521 OGR_Fld_SetWidth( fld.get(), ogrWidth );
523 if ( OGR_L_CreateField( hLayer, fld.get(),
true ) != OGRERR_NONE )
525 if ( !property(
"hideDialogs" ).toBool() )
527 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ),
528 tr(
"Creation of field %1 failed (OGR error: %2)" )
529 .arg( fieldName, QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
540 OGR_L_ResetReading( hLayer );
541 if ( CPLGetLastErrorType() != CE_None )
543 const QString msg( tr(
"Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
544 if ( !property(
"hideDialogs" ).toBool() )
545 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), msg );
550 const QString uri( QStringLiteral(
"%1|layername=%2" ).arg( fileName, tableName ) );
551 const QString userVisiblelayerName( layerIdentifier.isEmpty() ? tableName : layerIdentifier );
553 std::unique_ptr< QgsVectorLayer > layer = std::make_unique< QgsVectorLayer >( uri, userVisiblelayerName, QStringLiteral(
"ogr" ), layerOptions );
554 if ( layer->isValid() )
559 QList<QgsMapLayer *> myList;
560 myList << layer.release();
573 if ( !property(
"hideDialogs" ).toBool() )
574 QMessageBox::critical(
this, tr(
"New GeoPackage Layer" ), tr(
"%1 is an invalid layer and cannot be loaded." ).arg( tableName ) );
582 mBehavior = behavior;
587 mAddToProject = addToProject;
590void QgsNewGeoPackageLayerDialog::showHelp()
592 QgsHelp::openHelp( QStringLiteral(
"managing_data_source/create_layers.html#creating-a-new-geopackage-layer" ) );
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)
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(QgsWkbTypes::Type 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 OGRSpatialReferenceH crsToOGRSpatialReference(const QgsCoordinateReferenceSystem &crs)
Returns a OGRSpatialReferenceH corresponding to the specified crs object.
static QgsWkbTypes::Type ogrGeometryTypeToQgsWkbType(OGRwkbGeometryType ogrGeomType)
Converts a OGRwkbGeometryType to QgsWkbTypes::Type.
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(Type type) SIP_HOLDGIL
Returns a translated display string type for a WKB type, e.g., the geometry name used in WKT geometry...
Type
The WKB type describes the number of dimensions a geometry has.
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.