QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgsdataitemguiproviderutils.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsdataitemguiproviderutils.cpp
3 --------------------------------------
4 Date : June 2024
5 Copyright : (C) 2024 by Nyall Dawson
6 Email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17
19#include "qgsapplication.h"
20#include "qgsdataitem.h"
23#include "qgsmaplayerutils.h"
24#include "qgsmessagebar.h"
25#include "qgsmessagebaritem.h"
26#include "qgsmessageoutput.h"
27#include "qgsprovidermetadata.h"
28#include "qgsproviderregistry.h"
29#include "qgstaskmanager.h"
30#include "qgsvectorlayer.h"
32
33#include <QMessageBox>
34#include <QPointer>
35#include <QPushButton>
36#include <QString>
37
38using namespace Qt::StringLiterals;
39
40void QgsDataItemGuiProviderUtils::deleteConnectionsPrivate( const QStringList &connectionNames, const std::function<void( const QString & )> &deleteConnection, QPointer<QgsDataItem> firstParent )
41{
42 if ( connectionNames.size() > 1 )
43 {
44 if ( QMessageBox::
45 question( nullptr, QObject::tr( "Remove Connections" ), QObject::tr( "Are you sure you want to remove all %1 selected connections?" ).arg( connectionNames.size() ), QMessageBox::Yes | QMessageBox::No, QMessageBox::No )
46 != QMessageBox::Yes )
47 return;
48 }
49 else
50 {
51 if ( QMessageBox::
52 question( nullptr, QObject::tr( "Remove Connection" ), QObject::tr( "Are you sure you want to remove the connection to “%1”?" ).arg( connectionNames.at( 0 ) ), QMessageBox::Yes | QMessageBox::No, QMessageBox::No )
53 != QMessageBox::Yes )
54 return;
55 }
56
57 for ( const QString &connectionName : std::as_const( connectionNames ) )
58 {
59 deleteConnection( connectionName );
60 }
61
62 if ( firstParent )
63 firstParent->refreshConnections();
64}
65
66const QString QgsDataItemGuiProviderUtils::uniqueName( const QString &name, const QStringList &connectionNames )
67{
68 int i = 0;
69 QString newConnectionName( name );
70 while ( connectionNames.contains( newConnectionName ) )
71 {
72 ++i;
73 newConnectionName = QObject::tr( "%1 (copy %2)" ).arg( name ).arg( i );
74 }
75
76 return newConnectionName;
77}
78
80 std::unique_ptr<QgsAbstractDatabaseProviderConnection> connection,
81 const QgsMimeDataUtils::Uri &sourceUri,
82 const QString &destinationSchema,
84 const QString &shortTitle,
85 const QString &longTitle,
86 const QVariantMap &destinationProviderOptions,
87 const std::function<void()> &onSuccessfulCompletion,
88 const std::function<void( Qgis::VectorExportResult, const QString & )> &onError,
89 QObject *connectionContext
90)
91{
92 if ( !connection )
93 return false;
94
95 const QString connectionUri = connection->uri();
96 const QString connectionProvider = connection->providerKey();
97
98 QgsDbImportVectorLayerDialog dialog( connection.release(), context.messageBar() ? context.messageBar()->parentWidget() : nullptr );
99 dialog.setMapCanvas( context.mapCanvas() );
100 dialog.setSourceUri( sourceUri );
101 dialog.setDestinationSchema( destinationSchema );
102 if ( !dialog.exec() )
103 return false;
104
105 std::unique_ptr< QgsVectorLayerExporterTask > exportTask = dialog.createExporterTask( destinationProviderOptions );
106 if ( !exportTask )
107 return false;
108
109 const QString destSchema = dialog.schema();
110 const QString destTableName = dialog.tableName();
111 const QString tableComment = dialog.tableComment();
112 const QString destGeometryColumn = dialog.geometryColumn();
113
114 auto pushError = [shortTitle, longTitle, context]( const QString &error ) {
115 QgsMessageBarItem *item = new QgsMessageBarItem( shortTitle, QObject::tr( "Import failed." ), Qgis::MessageLevel::Warning, 0, nullptr );
116 QPushButton *detailsButton = new QPushButton( QObject::tr( "Details…" ) );
117 QObject::connect( detailsButton, &QPushButton::clicked, detailsButton, [longTitle, error] {
119 output->setTitle( longTitle );
121 output->showMessage();
122 } );
123 item->layout()->addWidget( detailsButton );
125 };
126
127 QgsVectorLayer *styleSourceLayer = dialog.saveStyleToDatabase() ? dialog.sourceLayer() : nullptr;
128
129 // when export is successful:
130 QObject::connect(
131 exportTask.get(),
133 connectionContext,
134 [onSuccessfulCompletion, connectionUri, longTitle, pushError, connectionProvider, destSchema, destTableName, tableComment, destGeometryColumn, styleSourceLayer, shortTitle, context]() {
135 if ( !tableComment.isEmpty() || styleSourceLayer )
136 {
137 std::unique_ptr<QgsAbstractDatabaseProviderConnection> connection;
138 try
139 {
140 QgsProviderMetadata *md = QgsProviderRegistry::instance()->providerMetadata( connectionProvider );
141 connection.reset( static_cast<QgsAbstractDatabaseProviderConnection *>( md->createConnection( connectionUri, {} ) ) );
142 }
143 catch ( QgsProviderConnectionException &e )
144 {
145 pushError( QObject::tr( "Could not retrieve connection details:\n\n%1" ).arg( e.what() ) );
146 return;
147 }
148
149 if ( !tableComment.isEmpty() )
150 {
151 try
152 {
153 connection->setTableComment( destSchema, destTableName, tableComment );
154 }
155 catch ( QgsProviderConnectionException &e )
156 {
157 pushError( QObject::tr( "Failed to set new table comment!\n\n" ) + e.what() );
158 return;
159 }
160 }
161
162 if ( styleSourceLayer )
163 {
164 QString styleUri;
165 try
166 {
167 styleUri = connection->styleStorageUri( destSchema, destTableName, destGeometryColumn, styleSourceLayer->wkbType() );
168 }
169 catch ( QgsProviderConnectionException &e )
170 {
171 pushError( QObject::tr( "Failed to save style to database!\n\n" ) + e.what() );
172 return;
173 }
174 const QgsSaveStyleResult styleResult = QgsMapLayerUtils::saveLayerStyleToDatabase( styleSourceLayer, connectionProvider, styleUri, destTableName, QString(), true, QString() );
175 const QString errMsg = styleResult.providerSaveStyleError.isEmpty() ? styleResult.qmlError : styleResult.providerSaveStyleError;
176 if ( !errMsg.isEmpty() )
177 {
178 pushError( QObject::tr( "Failed to save style to database!\n\n" ) + errMsg );
179 return;
180 }
181 }
182 }
183
184 context.messageBar()->pushSuccess( shortTitle, QObject::tr( "Import was successful." ) );
185 onSuccessfulCompletion();
186 }
187 );
188
189 // when an error occurs:
190 QObject::connect( exportTask.get(), &QgsVectorLayerExporterTask::errorOccurred, connectionContext, [onError, shortTitle, pushError, longTitle]( Qgis::VectorExportResult error, const QString &errorMessage ) {
191 if ( error != Qgis::VectorExportResult::UserCanceled )
192 {
193 pushError( QObject::tr( "Failed to import layer!\n\n" ) + errorMessage );
194 }
195
196 onError( error, errorMessage );
197 } );
198
199 QgsApplication::taskManager()->addTask( exportTask.release() );
200 return true;
201}
202
204 std::unique_ptr<QgsAbstractDatabaseProviderConnection> connection,
205 const QString &destinationSchema,
206 QgsDataItemGuiContext context,
207 const QString &shortTitle,
208 const QString &longTitle,
209 const QVariantMap &destinationProviderOptions,
210 const std::function<void()> &onSuccessfulCompletion,
211 const std::function<void( Qgis::VectorExportResult, const QString & )> &onError,
212 QObject *connectionContext
213)
214{
215 if ( !connection )
216 return;
217
218 const QString connectionUri = connection->uri();
219 const QString connectionProvider = connection->providerKey();
220
221 QgsDbImportVectorLayerDialog dialog( connection.release(), context.messageBar() ? context.messageBar()->parentWidget() : nullptr );
222 dialog.setMapCanvas( context.mapCanvas() );
223 dialog.setDestinationSchema( destinationSchema );
224 if ( !dialog.exec() )
225 return;
226
227 std::unique_ptr< QgsVectorLayerExporterTask > exportTask = dialog.createExporterTask( destinationProviderOptions );
228 if ( !exportTask )
229 return;
230
231 const QString destSchema = dialog.schema();
232 const QString destTableName = dialog.tableName();
233 const QString tableComment = dialog.tableComment();
234 const QString destGeometryColumn = dialog.geometryColumn();
235
236 auto pushError = [shortTitle, longTitle, context]( const QString &error ) {
237 QgsMessageBarItem *item = new QgsMessageBarItem( shortTitle, QObject::tr( "Import failed." ), Qgis::MessageLevel::Warning, 0, nullptr );
238 QPushButton *detailsButton = new QPushButton( QObject::tr( "Details…" ) );
239 QObject::connect( detailsButton, &QPushButton::clicked, detailsButton, [longTitle, error] {
241 output->setTitle( longTitle );
243 output->showMessage();
244 } );
245 item->layout()->addWidget( detailsButton );
247 };
248
249 QgsVectorLayer *styleSourceLayer = dialog.saveStyleToDatabase() ? dialog.sourceLayer() : nullptr;
250
251 // when export is successful:
252 QObject::connect(
253 exportTask.get(),
255 connectionContext,
256 [onSuccessfulCompletion, connectionUri, longTitle, pushError, connectionProvider, destSchema, destTableName, tableComment, destGeometryColumn, styleSourceLayer, shortTitle, context]() {
257 if ( !tableComment.isEmpty() || styleSourceLayer )
258 {
259 std::unique_ptr<QgsAbstractDatabaseProviderConnection> connection;
260 try
261 {
262 QgsProviderMetadata *md = QgsProviderRegistry::instance()->providerMetadata( connectionProvider );
263 connection.reset( static_cast<QgsAbstractDatabaseProviderConnection *>( md->createConnection( connectionUri, {} ) ) );
264 }
265 catch ( QgsProviderConnectionException &e )
266 {
267 pushError( QObject::tr( "Could not retrieve connection details:\n\n%1" ).arg( e.what() ) );
268 return;
269 }
270
271 if ( !tableComment.isEmpty() )
272 {
273 try
274 {
275 connection->setTableComment( destSchema, destTableName, tableComment );
276 }
277 catch ( QgsProviderConnectionException &e )
278 {
279 pushError( QObject::tr( "Failed to set new table comment!\n\n" ) + e.what() );
280 return;
281 }
282 }
283
284 if ( styleSourceLayer )
285 {
286 QString styleUri;
287 try
288 {
289 styleUri = connection->styleStorageUri( destSchema, destTableName, destGeometryColumn, styleSourceLayer->wkbType() );
290 }
291 catch ( QgsProviderConnectionException &e )
292 {
293 pushError( QObject::tr( "Failed to save style to database!\n\n" ) + e.what() );
294 return;
295 }
296 const QgsSaveStyleResult styleResult = QgsMapLayerUtils::saveLayerStyleToDatabase( styleSourceLayer, connectionProvider, styleUri, destTableName, QString(), true, QString() );
297 const QString errMsg = styleResult.providerSaveStyleError.isEmpty() ? styleResult.qmlError : styleResult.providerSaveStyleError;
298 if ( !errMsg.isEmpty() )
299 {
300 pushError( QObject::tr( "Failed to save style to database!\n\n" ) + errMsg );
301 return;
302 }
303 }
304 }
305
306 context.messageBar()->pushSuccess( shortTitle, QObject::tr( "Import was successful." ) );
307 onSuccessfulCompletion();
308 }
309 );
310
311 // when an error occurs:
312 QObject::connect( exportTask.get(), &QgsVectorLayerExporterTask::errorOccurred, connectionContext, [onError, shortTitle, pushError, longTitle]( Qgis::VectorExportResult error, const QString &errorMessage ) {
313 if ( error != Qgis::VectorExportResult::UserCanceled )
314 {
315 pushError( QObject::tr( "Failed to import layer!\n\n" ) + errorMessage );
316 }
317
318 onError( error, errorMessage );
319 } );
320
321 QgsApplication::taskManager()->addTask( exportTask.release() );
322}
323
324void QgsDataItemGuiProviderUtils::addToSubMenu( QMenu *mainMenu, QAction *actionToAdd, const QString &subMenuName )
325{
326 // this action should sit in the Manage menu. If one does not exist, create it now
327 bool foundExistingManageMenu = false;
328 const QList<QAction *> actions = mainMenu->actions();
329 for ( QAction *action : actions )
330 {
331 if ( action->text() == subMenuName )
332 {
333 action->menu()->addAction( actionToAdd );
334 foundExistingManageMenu = true;
335 break;
336 }
337 }
338 if ( !foundExistingManageMenu )
339 {
340 QMenu *addSubMenu = new QMenu( subMenuName, mainMenu );
341 addSubMenu->addAction( actionToAdd );
342 mainMenu->addMenu( addSubMenu );
343 }
344}
345
347{
348 const QVector<QgsDataItem *> constChildren { item->children() };
349 for ( QgsDataItem *c : constChildren )
350 {
351 if ( c->name() == name )
352 {
353 if ( c->state() != Qgis::BrowserItemState::NotPopulated )
354 {
355 c->refresh();
356 }
357 break;
358 }
359 }
360}
@ NotPopulated
Children not yet created.
Definition qgis.h:1021
VectorExportResult
Vector layer export result codes.
Definition qgis.h:1153
@ Warning
Warning message.
Definition qgis.h:162
@ PlainText
Text message.
Definition qgis.h:176
static QgsTaskManager * taskManager()
Returns the application's task manager, used for managing application wide background task handling.
Encapsulates the context in which a QgsDataItem is shown within the application GUI.
QgsMessageBar * messageBar() const
Returns the associated message bar.
QgsMapCanvas * mapCanvas() const
Returns the map canvas associated with the item.
static void refreshChildWithName(QgsDataItem *item, const QString &name)
Refresh child of item that has give name.
static void handleImportVectorLayerForConnection(std::unique_ptr< QgsAbstractDatabaseProviderConnection > connection, const QString &destinationSchema, QgsDataItemGuiContext context, const QString &shortTitle, const QString &longTitle, const QVariantMap &destinationProviderOptions, const std::function< void()> &onSuccessfulCompletion, const std::function< void(Qgis::VectorExportResult error, const QString &errorMessage)> &onError, QObject *connectionContext)
Handles importing a vector layer for connection items.
static const QString uniqueName(const QString &name, const QStringList &connectionNames)
Check if connection with name exists in connectionNames list and then try to append a number to it to...
static bool handleDropUriForConnection(std::unique_ptr< QgsAbstractDatabaseProviderConnection > connection, const QgsMimeDataUtils::Uri &sourceUri, const QString &destinationSchema, QgsDataItemGuiContext context, const QString &shortTitle, const QString &longTitle, const QVariantMap &destinationProviderOptions, const std::function< void()> &onSuccessfulCompletion, const std::function< void(Qgis::VectorExportResult error, const QString &errorMessage)> &onError, QObject *connectionContext)
Handles dropping a vector layer for connection items.
static void addToSubMenu(QMenu *mainMenu, QAction *actionToAdd, const QString &subMenuName)
Add an actionToAdd to the sub menu with subMenuName in mainMenu.
Base class for all items in the model.
Definition qgsdataitem.h:50
QVector< QgsDataItem * > children() const
A generic dialog for customising vector layer import options for database connections.
void setDestinationSchema(const QString &schema)
Sets the destination schema for the new table.
QgsVectorLayer * sourceLayer() const
Returns the source layer, or nullptr if no source layer is set.
std::unique_ptr< QgsVectorLayerExporterTask > createExporterTask(const QVariantMap &extraProviderOptions=QVariantMap())
Creates a new exporter task to match the settings defined in the dialog.
bool saveStyleToDatabase() const
Returns true if the style should be saved to the database after import.
void setMapCanvas(QgsMapCanvas *canvas)
Sets a map canvas to associate with the dialog.
QString geometryColumn() const
Returns the geometry column name for the destination table.
void setSourceUri(const QgsMimeDataUtils::Uri &uri)
Sets the source table uri.
QString schema() const
Returns the destination schema.
QString tableName() const
Returns the destination table name.
QString tableComment() const
Returns the optional comment to use for the new table.
Represents an item shown within a QgsMessageBar widget.
QgsMessageBarItem * pushWidget(QWidget *widget, Qgis::MessageLevel level=Qgis::MessageLevel::Info, int duration=0)
Display a widget as a message on the bar, after hiding the currently visible one and putting it in a ...
void pushSuccess(const QString &title, const QString &message)
Pushes a success message with default timeout to the message bar.
Interface for showing messages from QGIS in GUI independent way.
virtual void showMessage(bool blocking=true)=0
display the message to the user and deletes itself
static QgsMessageOutput * createMessageOutput()
function that returns new class derived from QgsMessageOutput (don't forget to delete it then if show...
virtual void setMessage(const QString &message, Qgis::StringFormat format)=0
Sets message, it won't be displayed until.
virtual void setTitle(const QString &title)=0
Sets title for the messages.
long addTask(QgsTask *task, int priority=0)
Adds a task to the manager.
void exportComplete()
Emitted when exporting the layer is successfully completed.
void errorOccurred(Qgis::VectorExportResult error, const QString &errorMessage)
Emitted when an error occurs which prevented the layer being exported (or if the task is canceled).
Represents a vector layer which manages a vector based dataset.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c