QGIS API Documentation 3.32.0-Lima (311a8cb8a6)
qgsstyleexportimportdialog.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsstyleexportimportdialog.cpp
3 ---------------------
4 begin : Jan 2011
5 copyright : (C) 2011 by Alexander Bruy
6 email : alexander dot bruy at gmail dot com
7
8 ***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
18#include "ui_qgsstyleexportimportdialogbase.h"
19
20#include "qgsapplication.h"
21#include "qgsstyle.h"
22#include "qgssymbol.h"
25#include "qgsguiutils.h"
26#include "qgssettings.h"
27#include "qgsgui.h"
28#include "qgsstylemodel.h"
30
31#include <QInputDialog>
32#include <QCloseEvent>
33#include <QFileDialog>
34#include <QMessageBox>
35#include <QNetworkReply>
36#include <QProgressDialog>
37#include <QPushButton>
38#include <QStandardItemModel>
39#include <QTemporaryFile>
40#include <QUrl>
41
43 : QDialog( parent )
44 , mDialogMode( mode )
45 , mStyle( style )
46{
47 setupUi( this );
49
50 // additional buttons
51 QPushButton *pb = nullptr;
52 pb = new QPushButton( tr( "Select All" ) );
53 buttonBox->addButton( pb, QDialogButtonBox::ActionRole );
54 connect( pb, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::selectAll );
55
56 pb = new QPushButton( tr( "Clear Selection" ) );
57 buttonBox->addButton( pb, QDialogButtonBox::ActionRole );
58 connect( pb, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::clearSelection );
59
60 mTempStyle = std::make_unique< QgsStyle >();
61 mTempStyle->createMemoryDatabase();
62
63 // TODO validate
64 mGroupSelectionDlg = nullptr;
65 mTempFile = nullptr;
66
67 QgsStyle *dialogStyle = nullptr;
68 if ( mDialogMode == Import )
69 {
70 setWindowTitle( tr( "Import Item(s)" ) );
71 // populate the import types
72 importTypeCombo->addItem( tr( "File" ), ImportSource::File );
73 // importTypeCombo->addItem( "official QGIS repo online", ImportSource::Official );
74 importTypeCombo->addItem( tr( "URL" ), ImportSource::Url );
75 connect( importTypeCombo, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsStyleExportImportDialog::importTypeChanged );
77
78 mSymbolTags->setText( QStringLiteral( "imported" ) );
79
80 connect( mButtonFetch, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::fetch );
81
82 mImportFileWidget->setStorageMode( QgsFileWidget::GetFile );
83 mImportFileWidget->setDialogTitle( tr( "Load Styles" ) );
84 mImportFileWidget->setFilter( tr( "XML files (*.xml *.XML)" ) );
85
86 const QgsSettings settings;
87 mImportFileWidget->setDefaultRoot( settings.value( QStringLiteral( "StyleManager/lastImportDir" ), QDir::homePath(), QgsSettings::Gui ).toString() );
88 connect( mImportFileWidget, &QgsFileWidget::fileChanged, this, &QgsStyleExportImportDialog::importFileChanged );
89
90 label->setText( tr( "Select items to import" ) );
91 buttonBox->button( QDialogButtonBox::Ok )->setText( tr( "Import" ) );
92
93 dialogStyle = mTempStyle.get();
94 }
95 else
96 {
97 setWindowTitle( tr( "Export Item(s)" ) );
98 // hide import specific controls when exporting
99 mLocationStackedEdit->setHidden( true );
100 fromLabel->setHidden( true );
101 importTypeCombo->setHidden( true );
102 mLocationLabel->setHidden( true );
103
104 mFavorite->setHidden( true );
105 mIgnoreXMLTags->setHidden( true );
106
107 pb = new QPushButton( tr( "Select by Group…" ) );
108 buttonBox->addButton( pb, QDialogButtonBox::ActionRole );
109 connect( pb, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::selectByGroup );
110 tagLabel->setHidden( true );
111 mSymbolTags->setHidden( true );
112 tagHintLabel->setHidden( true );
113
114 buttonBox->button( QDialogButtonBox::Ok )->setText( tr( "Export" ) );
115
116 dialogStyle = mStyle;
117 }
118
119 const double iconSize = Qgis::UI_SCALE_FACTOR * fontMetrics().horizontalAdvance( 'X' ) * 10;
120 listItems->setIconSize( QSize( static_cast< int >( iconSize ), static_cast< int >( iconSize * 0.9 ) ) ); // ~100, 90 on low dpi
121 // set a grid size which allows sufficient vertical spacing to fit reasonably sized entity names
122 listItems->setGridSize( QSize( static_cast< int >( listItems->iconSize().width() * 1.4 ), static_cast< int >( listItems->iconSize().height() * 1.7 ) ) );
123 listItems->setTextElideMode( Qt::TextElideMode::ElideRight );
124
125 mModel = new QgsStyleProxyModel( dialogStyle, this );
126
127 mModel->addDesiredIconSize( listItems->iconSize() );
128 mModel->addTargetScreenProperties( QgsScreenProperties( screen() ) );
129
130 listItems->setModel( mModel );
131
132 connect( listItems->selectionModel(), &QItemSelectionModel::selectionChanged,
133 this, &QgsStyleExportImportDialog::selectionChanged );
134
135 // use Ok button for starting import and export operations
136 disconnect( buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept );
137 connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsStyleExportImportDialog::doExportImport );
138 buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false );
139
140 connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsStyleExportImportDialog::showHelp );
141}
142
144{
145 QModelIndexList selection = listItems->selectionModel()->selectedIndexes();
146 if ( selection.isEmpty() )
147 {
148 QMessageBox::warning( this, tr( "Export/import Item(s)" ),
149 tr( "You should select at least one symbol/color ramp." ) );
150 return;
151 }
152
153 if ( mDialogMode == Export )
154 {
155 QgsSettings settings;
156 const QString lastUsedDir = settings.value( QStringLiteral( "StyleManager/lastExportDir" ), QDir::homePath(), QgsSettings::Gui ).toString();
157 QString fileName = QFileDialog::getSaveFileName( this, tr( "Save Styles" ), lastUsedDir,
158 tr( "XML files (*.xml *.XML)" ) );
159 if ( fileName.isEmpty() )
160 {
161 return;
162 }
163 settings.setValue( QStringLiteral( "StyleManager/lastExportDir" ), QFileInfo( fileName ).absolutePath(), QgsSettings::Gui );
164
165 // ensure the user never omitted the extension from the file name
166 if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) )
167 {
168 fileName += QLatin1String( ".xml" );
169 }
170
171 mFileName = fileName;
172
173 mCursorOverride = std::make_unique< QgsTemporaryCursorOverride >( Qt::WaitCursor );
174 moveStyles( &selection, mStyle, mTempStyle.get() );
175 if ( !mTempStyle->exportXml( mFileName ) )
176 {
177 mCursorOverride.reset();
178 QMessageBox::warning( this, tr( "Export Symbols" ),
179 tr( "Error when saving selected symbols to file:\n%1" )
180 .arg( mTempStyle->errorString() ) );
181 return;
182 }
183 else
184 {
185 mCursorOverride.reset();
186 QMessageBox::information( this, tr( "Export Symbols" ),
187 tr( "The selected symbols were successfully exported to file:\n%1" )
188 .arg( mFileName ) );
189 }
190 }
191 else // import
192 {
193 mCursorOverride = std::make_unique< QgsTemporaryCursorOverride >( Qt::WaitCursor );
194 moveStyles( &selection, mTempStyle.get(), mStyle );
195
196 accept();
197 mCursorOverride.reset();
198 }
199
200 mFileName.clear();
201 mTempStyle->clear();
202}
203
204bool QgsStyleExportImportDialog::populateStyles()
205{
206 QgsTemporaryCursorOverride override( Qt::WaitCursor );
207
208 // load symbols and color ramps from file
209 // NOTE mTempStyle is style here
210 mTempStyle->clear();
211 if ( !mTempStyle->importXml( mFileName ) )
212 {
213 override.release();
214 QMessageBox::warning( this, tr( "Import Symbols or Color Ramps" ),
215 tr( "An error occurred during import:\n%1" ).arg( mTempStyle->errorString() ) );
216 return false;
217 }
218 return true;
219}
220
221void QgsStyleExportImportDialog::moveStyles( QModelIndexList *selection, QgsStyle *src, QgsStyle *dst )
222{
223 QList< QgsStyleManagerDialog::ItemDetails > items;
224 items.reserve( selection->size() );
225 for ( int i = 0; i < selection->size(); ++i )
226 {
227 const QModelIndex index = selection->at( i );
228
229 QgsStyleManagerDialog::ItemDetails details;
230 details.entityType = static_cast< QgsStyle::StyleEntity >( mModel->data( index, QgsStyleModel::TypeRole ).toInt() );
231 if ( details.entityType == QgsStyle::SymbolEntity )
232 details.symbolType = static_cast< Qgis::SymbolType >( mModel->data( index, QgsStyleModel::SymbolTypeRole ).toInt() );
233 details.name = mModel->data( mModel->index( index.row(), QgsStyleModel::Name, index.parent() ), Qt::DisplayRole ).toString();
234
235 items << details;
236 }
237 QgsStyleManagerDialog::copyItems( items, src, dst, this, mCursorOverride, mDialogMode == Import,
238 mSymbolTags->text().split( ',' ), mFavorite->isChecked(), mIgnoreXMLTags->isChecked() );
239}
240
242{
243 delete mTempFile;
244 delete mGroupSelectionDlg;
245}
246
248{
249 mImportFileWidget->setFilePath( path );
250}
251
253{
254 listItems->selectAll();
255}
256
258{
259 listItems->clearSelection();
260}
261
263{
264 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
265 {
266 const QModelIndex index = listItems->model()->index( row, 0 );
267 if ( index.data( QgsStyleModel::IsFavoriteRole ).toBool() )
268 {
269 listItems->selectionModel()->select( index, QItemSelectionModel::Select );
270 }
271 }
272}
273
275{
276 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
277 {
278 const QModelIndex index = listItems->model()->index( row, 0 );
279 if ( index.data( QgsStyleModel::IsFavoriteRole ).toBool() )
280 {
281 const QItemSelection deselection( index, index );
282 listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
283 }
284 }
285}
286
287void QgsStyleExportImportDialog::selectSymbols( const QStringList &symbolNames )
288{
289 const auto constSymbolNames = symbolNames;
290 for ( const QString &symbolName : constSymbolNames )
291 {
292 const QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
293 const auto constIndexes = indexes;
294 for ( const QModelIndex &index : constIndexes )
295 {
296 listItems->selectionModel()->select( index, QItemSelectionModel::Select );
297 }
298 }
299}
300
301void QgsStyleExportImportDialog::deselectSymbols( const QStringList &symbolNames )
302{
303 const auto constSymbolNames = symbolNames;
304 for ( const QString &symbolName : constSymbolNames )
305 {
306 const QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
307 const auto constIndexes = indexes;
308 for ( const QModelIndex &index : constIndexes )
309 {
310 const QItemSelection deselection( index, index );
311 listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
312 }
313 }
314}
315
316void QgsStyleExportImportDialog::selectTag( const QString &tagName )
317{
318 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
319 {
320 const QModelIndex index = listItems->model()->index( row, 0 );
321 if ( index.data( QgsStyleModel::TagRole ).toStringList().contains( tagName, Qt::CaseInsensitive ) )
322 {
323 listItems->selectionModel()->select( index, QItemSelectionModel::Select );
324 }
325 }
326}
327
328void QgsStyleExportImportDialog::deselectTag( const QString &tagName )
329{
330 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
331 {
332 const QModelIndex index = listItems->model()->index( row, 0 );
333 if ( index.data( QgsStyleModel::TagRole ).toStringList().contains( tagName, Qt::CaseInsensitive ) )
334 {
335 const QItemSelection deselection( index, index );
336 listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
337 }
338 }
339}
340
341void QgsStyleExportImportDialog::selectSmartgroup( const QString &groupName )
342{
343 QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
344 selectSymbols( symbolNames );
345 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
346 selectSymbols( symbolNames );
347 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
348 selectSymbols( symbolNames );
349}
350
352{
353 QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
354 deselectSymbols( symbolNames );
355 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
356 deselectSymbols( symbolNames );
357 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
358 deselectSymbols( symbolNames );
359}
360
362{
363 if ( ! mGroupSelectionDlg )
364 {
365 mGroupSelectionDlg = new QgsStyleGroupSelectionDialog( mStyle, this );
366 mGroupSelectionDlg->setWindowTitle( tr( "Select Item(s) by Group" ) );
375 }
376 mGroupSelectionDlg->show();
377 mGroupSelectionDlg->raise();
378 mGroupSelectionDlg->activateWindow();
379}
380
382{
383 const ImportSource source = static_cast< ImportSource >( importTypeCombo->itemData( index ).toInt() );
384
385 switch ( source )
386 {
387 case ImportSource::File:
388 {
389 mLocationStackedEdit->setCurrentIndex( 0 );
390 mLocationLabel->setText( tr( "File" ) );
391 break;
392 }
393#if 0
394 case ImportSource::Official:
395 {
396 btnBrowse->setText( QStringLiteral( "Fetch Items" ) );
397 locationLineEdit->setEnabled( false );
398 break;
399 }
400#endif
401 case ImportSource::Url:
402 {
403 mLocationStackedEdit->setCurrentIndex( 1 );
404 mLocationLabel->setText( tr( "URL" ) );
405 break;
406 }
407 }
408}
409
410void QgsStyleExportImportDialog::fetch()
411{
412 downloadStyleXml( QUrl( mUrlLineEdit->text() ) );
413}
414
415void QgsStyleExportImportDialog::importFileChanged( const QString &path )
416{
417 if ( path.isEmpty() )
418 return;
419
420 mFileName = path;
421 const QFileInfo pathInfo( mFileName );
422 const QString tag = pathInfo.fileName().remove( QStringLiteral( ".xml" ) );
423 mSymbolTags->setText( tag );
424 if ( QFileInfo::exists( mFileName ) )
425 {
426 mTempStyle->clear();
427 populateStyles();
428 mImportFileWidget->setDefaultRoot( pathInfo.absolutePath() );
429 QgsSettings settings;
430 settings.setValue( QStringLiteral( "StyleManager/lastImportDir" ), pathInfo.absolutePath(), QgsSettings::Gui );
431 }
432}
433
434void QgsStyleExportImportDialog::downloadStyleXml( const QUrl &url )
435{
436 mTempFile = new QTemporaryFile();
437 if ( mTempFile->open() )
438 {
439 mFileName = mTempFile->fileName();
440
441 QProgressDialog *progressDlg = new QProgressDialog( this );
442 progressDlg->setLabelText( tr( "Downloading style…" ) );
443 progressDlg->setAutoClose( true );
444 progressDlg->show();
445
447 fetcher->setDescription( tr( "Downloading style" ) );
448 connect( progressDlg, &QProgressDialog::canceled, fetcher, &QgsNetworkContentFetcherTask::cancel );
449 connect( fetcher, &QgsNetworkContentFetcherTask::progressChanged, progressDlg, &QProgressDialog::setValue );
450 connect( fetcher, &QgsNetworkContentFetcherTask::fetched, this, [this, fetcher, progressDlg]
451 {
452 QNetworkReply *reply = fetcher->reply();
453 if ( !reply || reply->error() != QNetworkReply::NoError )
454 {
455 mTempFile->remove();
456 mFileName.clear();
457 if ( reply )
458 QMessageBox::information( this, tr( "Import from URL" ),
459 tr( "HTTP Error! Download failed: %1." ).arg( reply->errorString() ) );
460 }
461 else
462 {
463 mTempFile->write( reply->readAll() );
464 mTempFile->flush();
465 mTempFile->close();
466 populateStyles();
467 }
468 progressDlg->deleteLater();
469 } );
470
472 }
473}
474
475void QgsStyleExportImportDialog::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected )
476{
477 Q_UNUSED( selected )
478 Q_UNUSED( deselected )
479 const bool nothingSelected = listItems->selectionModel()->selectedIndexes().empty();
480 buttonBox->button( QDialogButtonBox::Ok )->setDisabled( nothingSelected );
481}
482
483void QgsStyleExportImportDialog::showHelp()
484{
485 QgsHelp::openHelp( QStringLiteral( "style_library/style_manager.html#sharing-style-items" ) );
486}
SymbolType
Attribute editing capabilities which may be supported by vector data providers.
Definition: qgis.h:340
static const double UI_SCALE_FACTOR
UI scaling factor.
Definition: qgis.h:3749
static QgsTaskManager * taskManager()
Returns the application's task manager, used for managing application wide background task handling.
@ GetFile
Select a single file.
Definition: qgsfilewidget.h:68
void fileChanged(const QString &path)
Emitted whenever the current file or directory path is changed.
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...
Definition: qgsgui.cpp:193
static void openHelp(const QString &key)
Opens help topic for the given help key using default system web browser.
Definition: qgshelp.cpp:38
Handles HTTP network content fetching in a background task.
void fetched()
Emitted when the network content has been fetched, regardless of whether the fetch was successful or ...
QNetworkReply * reply()
Returns the network reply.
void cancel() override
Notifies the task that it should terminate.
Stores properties relating to a screen.
This class is a composition of two QSettings instances:
Definition: qgssettings.h:63
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.
void clearSelection()
clearSelection deselects all symbols
void selectTag(const QString &tagName)
Select the symbols belonging to the given tag.
@ Export
Export existing symbols mode.
void deselectSymbols(const QStringList &symbolNames)
deselectSymbols deselect symbols by name
void selectAll()
selectAll selects all symbols
void selectSymbols(const QStringList &symbolNames)
selectSymbols select symbols by name
void selectSmartgroup(const QString &groupName)
selectSmartgroup selects all symbols from a smart group
void selectByGroup()
selectByGroup open select by group dialog
void deselectFavorites()
Deselects favorite symbols.
void setImportFilePath(const QString &path)
Sets the initial path to use for importing files, when the dialog is in a Import mode.
void deselectSmartgroup(const QString &groupName)
deselectSmartgroup deselects all symbols from a smart group
QgsStyleExportImportDialog(QgsStyle *style, QWidget *parent=nullptr, Mode mode=Export)
Constructor for QgsStyleExportImportDialog, with the specified parent widget.
void selectFavorites()
Selects favorite symbols.
void deselectTag(const QString &tagName)
Deselect the symbols belonging to the given tag.
void favoritesDeselected()
Favorites has been deselected.
void allDeselected()
all deselected
void tagSelected(const QString &tagName)
tag with tagName has been selected
void tagDeselected(const QString &tagName)
tag with tagName has been deselected
void smartgroupDeselected(const QString &groupName)
smart group with groupName has been deselected
void favoritesSelected()
Favorites has need selected.
void smartgroupSelected(const QString &groupName)
smartgroup with groupName has been selected
void allSelected()
all selected
@ TypeRole
Style entity type, see QgsStyle::StyleEntity.
@ IsFavoriteRole
Whether entity is flagged as a favorite.
@ SymbolTypeRole
Symbol type (for symbol or legend patch shape entities)
@ TagRole
String list of tags.
@ Name
Name column.
A QSortFilterProxyModel subclass for showing filtered symbol and color ramps entries from a QgsStyle ...
void addDesiredIconSize(QSize size)
Adds an additional icon size to generate for Qt::DecorationRole data.
void addTargetScreenProperties(const QgsScreenProperties &properties)
Adds additional target screen properties to use when generating icons for Qt::DecorationRole data.
QStringList symbolsOfSmartgroup(StyleEntity type, int id)
Returns the symbols for the smartgroup.
Definition: qgsstyle.cpp:2378
StyleEntity
Enum for Entities involved in a style.
Definition: qgsstyle.h:179
@ TextFormatEntity
Text formats.
Definition: qgsstyle.h:184
@ SymbolEntity
Symbols.
Definition: qgsstyle.h:180
@ ColorrampEntity
Color ramps.
Definition: qgsstyle.h:182
int smartgroupId(const QString &smartgroup)
Returns the database id for the given smartgroup name.
Definition: qgsstyle.cpp:2239
long addTask(QgsTask *task, int priority=0)
Adds a task to the manager.
void progressChanged(double progress)
Will be emitted by task when its progress changes.
void setDescription(const QString &description)
Sets the task's description.
Temporarily sets a cursor override for the QApplication for the lifetime of the object.
Definition: qgsguiutils.h:221
QSize iconSize(bool dockableToolbar)
Returns the user-preferred size of a window's toolbar icons.