QGIS API Documentation 3.99.0-Master (d270888f95f)
Loading...
Searching...
No Matches
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
17#include "ui_qgsstyleexportimportdialogbase.h"
19
20#include "qgsapplication.h"
21#include "qgsgui.h"
22#include "qgsguiutils.h"
24#include "qgssettings.h"
25#include "qgsstyle.h"
28#include "qgsstylemodel.h"
29#include "qgssymbol.h"
30
31#include <QCloseEvent>
32#include <QFileDialog>
33#include <QInputDialog>
34#include <QMessageBox>
35#include <QNetworkReply>
36#include <QProgressDialog>
37#include <QPushButton>
38#include <QStandardItemModel>
39#include <QString>
40#include <QTemporaryFile>
41#include <QUrl>
42
43#include "moc_qgsstyleexportimportdialog.cpp"
44
45using namespace Qt::StringLiterals;
46
48 : QDialog( parent )
49 , mDialogMode( mode )
50 , mStyle( style )
51{
52 setupUi( this );
54
55 // additional buttons
56 QPushButton *pb = nullptr;
57 pb = new QPushButton( tr( "Select All" ) );
58 buttonBox->addButton( pb, QDialogButtonBox::ActionRole );
59 connect( pb, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::selectAll );
60
61 pb = new QPushButton( tr( "Clear Selection" ) );
62 buttonBox->addButton( pb, QDialogButtonBox::ActionRole );
63 connect( pb, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::clearSelection );
64
65 mTempStyle = std::make_unique<QgsStyle>();
66 mTempStyle->createMemoryDatabase();
67
68 // TODO validate
69 mGroupSelectionDlg = nullptr;
70 mTempFile = nullptr;
71
72 QgsStyle *dialogStyle = nullptr;
73 if ( mDialogMode == Import )
74 {
75 setWindowTitle( tr( "Import Item(s)" ) );
76 // populate the import types
77 importTypeCombo->addItem( tr( "File" ), ImportSource::File );
78 // importTypeCombo->addItem( "official QGIS repo online", ImportSource::Official );
79 importTypeCombo->addItem( tr( "URL" ), ImportSource::Url );
80 connect( importTypeCombo, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsStyleExportImportDialog::importTypeChanged );
82
83 mSymbolTags->setText( u"imported"_s );
84
85 connect( mButtonFetch, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::fetch );
86
87 mImportFileWidget->setStorageMode( QgsFileWidget::GetFile );
88 mImportFileWidget->setDialogTitle( tr( "Load Styles" ) );
89 mImportFileWidget->setFilter( tr( "XML files (*.xml *.XML)" ) );
90
91 const QgsSettings settings;
92 mImportFileWidget->setDefaultRoot( settings.value( u"StyleManager/lastImportDir"_s, QDir::homePath(), QgsSettings::Gui ).toString() );
93 connect( mImportFileWidget, &QgsFileWidget::fileChanged, this, &QgsStyleExportImportDialog::importFileChanged );
94
95 label->setText( tr( "Select items to import" ) );
96 buttonBox->button( QDialogButtonBox::Ok )->setText( tr( "Import" ) );
97
98 dialogStyle = mTempStyle.get();
99 }
100 else
101 {
102 setWindowTitle( tr( "Export Item(s)" ) );
103 // hide import specific controls when exporting
104 mLocationStackedEdit->setHidden( true );
105 fromLabel->setHidden( true );
106 importTypeCombo->setHidden( true );
107 mLocationLabel->setHidden( true );
108
109 mFavorite->setHidden( true );
110 mIgnoreXMLTags->setHidden( true );
111
112 pb = new QPushButton( tr( "Select by Group…" ) );
113 buttonBox->addButton( pb, QDialogButtonBox::ActionRole );
114 connect( pb, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::selectByGroup );
115 tagLabel->setHidden( true );
116 mSymbolTags->setHidden( true );
117 tagHintLabel->setHidden( true );
118
119 buttonBox->button( QDialogButtonBox::Ok )->setText( tr( "Export" ) );
120
121 dialogStyle = mStyle;
122 }
123
124 const double iconSize = Qgis::UI_SCALE_FACTOR * fontMetrics().horizontalAdvance( 'X' ) * 10;
125 listItems->setIconSize( QSize( static_cast<int>( iconSize ), static_cast<int>( iconSize * 0.9 ) ) ); // ~100, 90 on low dpi
126 // set a grid size which allows sufficient vertical spacing to fit reasonably sized entity names
127 listItems->setGridSize( QSize( static_cast<int>( listItems->iconSize().width() * 1.4 ), static_cast<int>( listItems->iconSize().height() * 1.7 ) ) );
128 listItems->setTextElideMode( Qt::TextElideMode::ElideRight );
129
130 mModel = new QgsStyleProxyModel( dialogStyle, this );
131
132 mModel->addDesiredIconSize( listItems->iconSize() );
133 mModel->addTargetScreenProperties( QgsScreenProperties( screen() ) );
134
135 listItems->setModel( mModel );
136
137 connect( listItems->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsStyleExportImportDialog::selectionChanged );
138
139 // use Ok button for starting import and export operations
140 disconnect( buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept );
141 connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsStyleExportImportDialog::doExportImport );
142 buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false );
143
144 connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsStyleExportImportDialog::showHelp );
145}
146
148{
149 QModelIndexList selection = listItems->selectionModel()->selectedIndexes();
150 if ( selection.isEmpty() )
151 {
152 QMessageBox::warning( this, tr( "Export/import Item(s)" ), tr( "You should select at least one symbol/color ramp." ) );
153 return;
154 }
155
156 if ( mDialogMode == Export )
157 {
158 QgsSettings settings;
159 const QString lastUsedDir = settings.value( u"StyleManager/lastExportDir"_s, QDir::homePath(), QgsSettings::Gui ).toString();
160 QString fileName = QFileDialog::getSaveFileName( this, tr( "Save Styles" ), lastUsedDir, tr( "XML files (*.xml *.XML)" ) );
161 // return dialog focus on Mac
162 activateWindow();
163 raise();
164 if ( fileName.isEmpty() )
165 {
166 return;
167 }
168 settings.setValue( u"StyleManager/lastExportDir"_s, QFileInfo( fileName ).absolutePath(), QgsSettings::Gui );
169
170 // ensure the user never omitted the extension from the file name
171 if ( !fileName.endsWith( ".xml"_L1, Qt::CaseInsensitive ) )
172 {
173 fileName += ".xml"_L1;
174 }
175
176 mFileName = fileName;
177
178 mCursorOverride = std::make_unique<QgsTemporaryCursorOverride>( Qt::WaitCursor );
179 moveStyles( &selection, mStyle, mTempStyle.get() );
180 if ( !mTempStyle->exportXml( mFileName ) )
181 {
182 mCursorOverride.reset();
183 QMessageBox::warning( this, tr( "Export Symbols" ), tr( "Error when saving selected symbols to file:\n%1" ).arg( mTempStyle->errorString() ) );
184 return;
185 }
186 else
187 {
188 mCursorOverride.reset();
189 QMessageBox::information( this, tr( "Export Symbols" ), tr( "The selected symbols were successfully exported to file:\n%1" ).arg( mFileName ) );
190 }
191 }
192 else // import
193 {
194 mCursorOverride = std::make_unique<QgsTemporaryCursorOverride>( Qt::WaitCursor );
195 moveStyles( &selection, mTempStyle.get(), mStyle );
196
197 accept();
198 mCursorOverride.reset();
199 }
200
201 mFileName.clear();
202 mTempStyle->clear();
203}
204
205bool QgsStyleExportImportDialog::populateStyles()
206{
207 QgsTemporaryCursorOverride override( Qt::WaitCursor );
208
209 // load symbols and color ramps from file
210 // NOTE mTempStyle is style here
211 mTempStyle->clear();
212 if ( !mTempStyle->importXml( mFileName ) )
213 {
214 override.release();
215 QMessageBox::warning( this, tr( "Import Symbols or Color Ramps" ), 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, static_cast<int>( QgsStyleModel::CustomRole::Type ) ).toInt() );
231 if ( details.entityType == QgsStyle::SymbolEntity )
232 details.symbolType = static_cast<Qgis::SymbolType>( mModel->data( index, static_cast<int>( QgsStyleModel::CustomRole::SymbolType ) ).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, mSymbolTags->text().split( ',' ), mFavorite->isChecked(), mIgnoreXMLTags->isChecked() );
238}
239
241{
242 delete mTempFile;
243 delete mGroupSelectionDlg;
244}
245
247{
248 mImportFileWidget->setFilePath( path );
249}
250
252{
253 listItems->selectAll();
254}
255
257{
258 listItems->clearSelection();
259}
260
262{
263 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
264 {
265 const QModelIndex index = listItems->model()->index( row, 0 );
266 if ( index.data( static_cast<int>( QgsStyleModel::CustomRole::IsFavorite ) ).toBool() )
267 {
268 listItems->selectionModel()->select( index, QItemSelectionModel::Select );
269 }
270 }
271}
272
274{
275 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
276 {
277 const QModelIndex index = listItems->model()->index( row, 0 );
278 if ( index.data( static_cast<int>( QgsStyleModel::CustomRole::IsFavorite ) ).toBool() )
279 {
280 const QItemSelection deselection( index, index );
281 listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
282 }
283 }
284}
285
286void QgsStyleExportImportDialog::selectSymbols( const QStringList &symbolNames )
287{
288 const auto constSymbolNames = symbolNames;
289 for ( const QString &symbolName : constSymbolNames )
290 {
291 const QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
292 const auto constIndexes = indexes;
293 for ( const QModelIndex &index : constIndexes )
294 {
295 listItems->selectionModel()->select( index, QItemSelectionModel::Select );
296 }
297 }
298}
299
300void QgsStyleExportImportDialog::deselectSymbols( const QStringList &symbolNames )
301{
302 const auto constSymbolNames = symbolNames;
303 for ( const QString &symbolName : constSymbolNames )
304 {
305 const QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
306 const auto constIndexes = indexes;
307 for ( const QModelIndex &index : constIndexes )
308 {
309 const QItemSelection deselection( index, index );
310 listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
311 }
312 }
313}
314
315void QgsStyleExportImportDialog::selectTag( const QString &tagName )
316{
317 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
318 {
319 const QModelIndex index = listItems->model()->index( row, 0 );
320 if ( index.data( static_cast<int>( QgsStyleModel::CustomRole::Tag ) ).toStringList().contains( tagName, Qt::CaseInsensitive ) )
321 {
322 listItems->selectionModel()->select( index, QItemSelectionModel::Select );
323 }
324 }
325}
326
327void QgsStyleExportImportDialog::deselectTag( const QString &tagName )
328{
329 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
330 {
331 const QModelIndex index = listItems->model()->index( row, 0 );
332 if ( index.data( static_cast<int>( QgsStyleModel::CustomRole::Tag ) ).toStringList().contains( tagName, Qt::CaseInsensitive ) )
333 {
334 const QItemSelection deselection( index, index );
335 listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
336 }
337 }
338}
339
340void QgsStyleExportImportDialog::selectSmartgroup( const QString &groupName )
341{
342 QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
343 selectSymbols( symbolNames );
344 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
345 selectSymbols( symbolNames );
346 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
347 selectSymbols( symbolNames );
348}
349
351{
352 QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
353 deselectSymbols( symbolNames );
354 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
355 deselectSymbols( symbolNames );
356 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
357 deselectSymbols( symbolNames );
358}
359
361{
362 if ( !mGroupSelectionDlg )
363 {
364 mGroupSelectionDlg = new QgsStyleGroupSelectionDialog( mStyle, this );
365 mGroupSelectionDlg->setWindowTitle( tr( "Select Item(s) by Group" ) );
374 }
375 mGroupSelectionDlg->show();
376 mGroupSelectionDlg->raise();
377 mGroupSelectionDlg->activateWindow();
378}
379
381{
382 const ImportSource source = static_cast<ImportSource>( importTypeCombo->itemData( index ).toInt() );
383
384 switch ( source )
385 {
386 case ImportSource::File:
387 {
388 mLocationStackedEdit->setCurrentIndex( 0 );
389 mLocationLabel->setText( tr( "File" ) );
390 break;
391 }
392#if 0
393 case ImportSource::Official:
394 {
395 btnBrowse->setText( u"Fetch Items"_s );
396 locationLineEdit->setEnabled( false );
397 break;
398 }
399#endif
400 case ImportSource::Url:
401 {
402 mLocationStackedEdit->setCurrentIndex( 1 );
403 mLocationLabel->setText( tr( "URL" ) );
404 break;
405 }
406 }
407}
408
409void QgsStyleExportImportDialog::fetch()
410{
411 downloadStyleXml( QUrl( mUrlLineEdit->text() ) );
412}
413
414void QgsStyleExportImportDialog::importFileChanged( const QString &path )
415{
416 if ( path.isEmpty() )
417 return;
418
419 mFileName = path;
420 const QFileInfo pathInfo( mFileName );
421 const QString tag = pathInfo.fileName().remove( u".xml"_s );
422 mSymbolTags->setText( tag );
423 if ( QFileInfo::exists( mFileName ) )
424 {
425 mTempStyle->clear();
426 populateStyles();
427 mImportFileWidget->setDefaultRoot( pathInfo.absolutePath() );
428 QgsSettings settings;
429 settings.setValue( u"StyleManager/lastImportDir"_s, pathInfo.absolutePath(), QgsSettings::Gui );
430 }
431}
432
433void QgsStyleExportImportDialog::downloadStyleXml( const QUrl &url )
434{
435 mTempFile = new QTemporaryFile();
436 if ( mTempFile->open() )
437 {
438 mFileName = mTempFile->fileName();
439
440 QProgressDialog *progressDlg = new QProgressDialog( this );
441 progressDlg->setLabelText( tr( "Downloading style…" ) );
442 progressDlg->setAutoClose( true );
443 progressDlg->show();
444
445 QgsNetworkContentFetcherTask *fetcher = new QgsNetworkContentFetcherTask( url );
446 fetcher->setDescription( tr( "Downloading style" ) );
447 connect( progressDlg, &QProgressDialog::canceled, fetcher, &QgsNetworkContentFetcherTask::cancel );
448 connect( fetcher, &QgsNetworkContentFetcherTask::progressChanged, progressDlg, &QProgressDialog::setValue );
449 connect( fetcher, &QgsNetworkContentFetcherTask::fetched, this, [this, fetcher, progressDlg] {
450 QNetworkReply *reply = fetcher->reply();
451 if ( !reply || reply->error() != QNetworkReply::NoError )
452 {
453 mTempFile->remove();
454 mFileName.clear();
455 if ( reply )
456 QMessageBox::information( this, tr( "Import from URL" ), tr( "HTTP Error! Download failed: %1." ).arg( reply->errorString() ) );
457 }
458 else
459 {
460 mTempFile->write( reply->readAll() );
461 mTempFile->flush();
462 mTempFile->close();
463 populateStyles();
464 }
465 progressDlg->deleteLater();
466 } );
467
469 }
470}
471
472void QgsStyleExportImportDialog::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected )
473{
474 Q_UNUSED( selected )
475 Q_UNUSED( deselected )
476 const bool nothingSelected = listItems->selectionModel()->selectedIndexes().empty();
477 buttonBox->button( QDialogButtonBox::Ok )->setDisabled( nothingSelected );
478}
479
480void QgsStyleExportImportDialog::showHelp()
481{
482 QgsHelp::openHelp( u"style_library/style_manager.html#sharing-style-items"_s );
483}
SymbolType
Symbol types.
Definition qgis.h:629
static const double UI_SCALE_FACTOR
UI scaling factor.
Definition qgis.h:6499
static QgsTaskManager * taskManager()
Returns the application's task manager, used for managing application wide background task handling.
@ GetFile
Select a single file.
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:224
static void openHelp(const QString &key)
Opens help topic for the given help key using default system web browser.
Definition qgshelp.cpp:41
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.
Stores settings for use within QGIS.
Definition qgssettings.h:68
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.
A dialog which presents available groups from a QgsStyle.
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
@ IsFavorite
Whether entity is flagged as a favorite.
@ SymbolType
Symbol type (for symbol or legend patch shape entities).
@ Type
Style entity type, see QgsStyle::StyleEntity.
@ Tag
String list of tags.
@ Name
Name column.
A QSortFilterProxyModel subclass for showing filtered symbol and color ramps entries from a QgsStyle ...
A database of saved style entities, including symbols, color ramps, text formats and others.
Definition qgsstyle.h:89
StyleEntity
Enum for Entities involved in a style.
Definition qgsstyle.h:205
@ TextFormatEntity
Text formats.
Definition qgsstyle.h:210
@ SymbolEntity
Symbols.
Definition qgsstyle.h:206
@ ColorrampEntity
Color ramps.
Definition qgsstyle.h:208
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.