QGIS API Documentation 3.36.0-Maidenhead (09951dc0acf)
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
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 // return dialog focus on Mac
160 activateWindow();
161 raise();
162 if ( fileName.isEmpty() )
163 {
164 return;
165 }
166 settings.setValue( QStringLiteral( "StyleManager/lastExportDir" ), QFileInfo( fileName ).absolutePath(), QgsSettings::Gui );
167
168 // ensure the user never omitted the extension from the file name
169 if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) )
170 {
171 fileName += QLatin1String( ".xml" );
172 }
173
174 mFileName = fileName;
175
176 mCursorOverride = std::make_unique< QgsTemporaryCursorOverride >( Qt::WaitCursor );
177 moveStyles( &selection, mStyle, mTempStyle.get() );
178 if ( !mTempStyle->exportXml( mFileName ) )
179 {
180 mCursorOverride.reset();
181 QMessageBox::warning( this, tr( "Export Symbols" ),
182 tr( "Error when saving selected symbols to file:\n%1" )
183 .arg( mTempStyle->errorString() ) );
184 return;
185 }
186 else
187 {
188 mCursorOverride.reset();
189 QMessageBox::information( this, tr( "Export Symbols" ),
190 tr( "The selected symbols were successfully exported to file:\n%1" )
191 .arg( mFileName ) );
192 }
193 }
194 else // import
195 {
196 mCursorOverride = std::make_unique< QgsTemporaryCursorOverride >( Qt::WaitCursor );
197 moveStyles( &selection, mTempStyle.get(), mStyle );
198
199 accept();
200 mCursorOverride.reset();
201 }
202
203 mFileName.clear();
204 mTempStyle->clear();
205}
206
207bool QgsStyleExportImportDialog::populateStyles()
208{
209 QgsTemporaryCursorOverride override( Qt::WaitCursor );
210
211 // load symbols and color ramps from file
212 // NOTE mTempStyle is style here
213 mTempStyle->clear();
214 if ( !mTempStyle->importXml( mFileName ) )
215 {
216 override.release();
217 QMessageBox::warning( this, tr( "Import Symbols or Color Ramps" ),
218 tr( "An error occurred during import:\n%1" ).arg( mTempStyle->errorString() ) );
219 return false;
220 }
221 return true;
222}
223
224void QgsStyleExportImportDialog::moveStyles( QModelIndexList *selection, QgsStyle *src, QgsStyle *dst )
225{
226 QList< QgsStyleManagerDialog::ItemDetails > items;
227 items.reserve( selection->size() );
228 for ( int i = 0; i < selection->size(); ++i )
229 {
230 const QModelIndex index = selection->at( i );
231
232 QgsStyleManagerDialog::ItemDetails details;
233 details.entityType = static_cast< QgsStyle::StyleEntity >( mModel->data( index, static_cast< int >( QgsStyleModel::CustomRole::Type ) ).toInt() );
234 if ( details.entityType == QgsStyle::SymbolEntity )
235 details.symbolType = static_cast< Qgis::SymbolType >( mModel->data( index, static_cast< int >( QgsStyleModel::CustomRole::SymbolType ) ).toInt() );
236 details.name = mModel->data( mModel->index( index.row(), QgsStyleModel::Name, index.parent() ), Qt::DisplayRole ).toString();
237
238 items << details;
239 }
240 QgsStyleManagerDialog::copyItems( items, src, dst, this, mCursorOverride, mDialogMode == Import,
241 mSymbolTags->text().split( ',' ), mFavorite->isChecked(), mIgnoreXMLTags->isChecked() );
242}
243
245{
246 delete mTempFile;
247 delete mGroupSelectionDlg;
248}
249
251{
252 mImportFileWidget->setFilePath( path );
253}
254
256{
257 listItems->selectAll();
258}
259
261{
262 listItems->clearSelection();
263}
264
266{
267 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
268 {
269 const QModelIndex index = listItems->model()->index( row, 0 );
270 if ( index.data( static_cast< int >( QgsStyleModel::CustomRole::IsFavorite ) ).toBool() )
271 {
272 listItems->selectionModel()->select( index, QItemSelectionModel::Select );
273 }
274 }
275}
276
278{
279 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
280 {
281 const QModelIndex index = listItems->model()->index( row, 0 );
282 if ( index.data( static_cast< int >( QgsStyleModel::CustomRole::IsFavorite ) ).toBool() )
283 {
284 const QItemSelection deselection( index, index );
285 listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
286 }
287 }
288}
289
290void QgsStyleExportImportDialog::selectSymbols( const QStringList &symbolNames )
291{
292 const auto constSymbolNames = symbolNames;
293 for ( const QString &symbolName : constSymbolNames )
294 {
295 const QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
296 const auto constIndexes = indexes;
297 for ( const QModelIndex &index : constIndexes )
298 {
299 listItems->selectionModel()->select( index, QItemSelectionModel::Select );
300 }
301 }
302}
303
304void QgsStyleExportImportDialog::deselectSymbols( const QStringList &symbolNames )
305{
306 const auto constSymbolNames = symbolNames;
307 for ( const QString &symbolName : constSymbolNames )
308 {
309 const QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
310 const auto constIndexes = indexes;
311 for ( const QModelIndex &index : constIndexes )
312 {
313 const QItemSelection deselection( index, index );
314 listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
315 }
316 }
317}
318
319void QgsStyleExportImportDialog::selectTag( const QString &tagName )
320{
321 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
322 {
323 const QModelIndex index = listItems->model()->index( row, 0 );
324 if ( index.data( static_cast< int >( QgsStyleModel::CustomRole::Tag ) ).toStringList().contains( tagName, Qt::CaseInsensitive ) )
325 {
326 listItems->selectionModel()->select( index, QItemSelectionModel::Select );
327 }
328 }
329}
330
331void QgsStyleExportImportDialog::deselectTag( const QString &tagName )
332{
333 for ( int row = 0; row < listItems->model()->rowCount(); ++row )
334 {
335 const QModelIndex index = listItems->model()->index( row, 0 );
336 if ( index.data( static_cast< int >( QgsStyleModel::CustomRole::Tag ) ).toStringList().contains( tagName, Qt::CaseInsensitive ) )
337 {
338 const QItemSelection deselection( index, index );
339 listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
340 }
341 }
342}
343
344void QgsStyleExportImportDialog::selectSmartgroup( const QString &groupName )
345{
346 QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
347 selectSymbols( symbolNames );
348 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
349 selectSymbols( symbolNames );
350 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
351 selectSymbols( symbolNames );
352}
353
355{
356 QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
357 deselectSymbols( symbolNames );
358 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
359 deselectSymbols( symbolNames );
360 symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
361 deselectSymbols( symbolNames );
362}
363
365{
366 if ( ! mGroupSelectionDlg )
367 {
368 mGroupSelectionDlg = new QgsStyleGroupSelectionDialog( mStyle, this );
369 mGroupSelectionDlg->setWindowTitle( tr( "Select Item(s) by Group" ) );
378 }
379 mGroupSelectionDlg->show();
380 mGroupSelectionDlg->raise();
381 mGroupSelectionDlg->activateWindow();
382}
383
385{
386 const ImportSource source = static_cast< ImportSource >( importTypeCombo->itemData( index ).toInt() );
387
388 switch ( source )
389 {
390 case ImportSource::File:
391 {
392 mLocationStackedEdit->setCurrentIndex( 0 );
393 mLocationLabel->setText( tr( "File" ) );
394 break;
395 }
396#if 0
397 case ImportSource::Official:
398 {
399 btnBrowse->setText( QStringLiteral( "Fetch Items" ) );
400 locationLineEdit->setEnabled( false );
401 break;
402 }
403#endif
404 case ImportSource::Url:
405 {
406 mLocationStackedEdit->setCurrentIndex( 1 );
407 mLocationLabel->setText( tr( "URL" ) );
408 break;
409 }
410 }
411}
412
413void QgsStyleExportImportDialog::fetch()
414{
415 downloadStyleXml( QUrl( mUrlLineEdit->text() ) );
416}
417
418void QgsStyleExportImportDialog::importFileChanged( const QString &path )
419{
420 if ( path.isEmpty() )
421 return;
422
423 mFileName = path;
424 const QFileInfo pathInfo( mFileName );
425 const QString tag = pathInfo.fileName().remove( QStringLiteral( ".xml" ) );
426 mSymbolTags->setText( tag );
427 if ( QFileInfo::exists( mFileName ) )
428 {
429 mTempStyle->clear();
430 populateStyles();
431 mImportFileWidget->setDefaultRoot( pathInfo.absolutePath() );
432 QgsSettings settings;
433 settings.setValue( QStringLiteral( "StyleManager/lastImportDir" ), pathInfo.absolutePath(), QgsSettings::Gui );
434 }
435}
436
437void QgsStyleExportImportDialog::downloadStyleXml( const QUrl &url )
438{
439 mTempFile = new QTemporaryFile();
440 if ( mTempFile->open() )
441 {
442 mFileName = mTempFile->fileName();
443
444 QProgressDialog *progressDlg = new QProgressDialog( this );
445 progressDlg->setLabelText( tr( "Downloading style…" ) );
446 progressDlg->setAutoClose( true );
447 progressDlg->show();
448
450 fetcher->setDescription( tr( "Downloading style" ) );
451 connect( progressDlg, &QProgressDialog::canceled, fetcher, &QgsNetworkContentFetcherTask::cancel );
452 connect( fetcher, &QgsNetworkContentFetcherTask::progressChanged, progressDlg, &QProgressDialog::setValue );
453 connect( fetcher, &QgsNetworkContentFetcherTask::fetched, this, [this, fetcher, progressDlg]
454 {
455 QNetworkReply *reply = fetcher->reply();
456 if ( !reply || reply->error() != QNetworkReply::NoError )
457 {
458 mTempFile->remove();
459 mFileName.clear();
460 if ( reply )
461 QMessageBox::information( this, tr( "Import from URL" ),
462 tr( "HTTP Error! Download failed: %1." ).arg( reply->errorString() ) );
463 }
464 else
465 {
466 mTempFile->write( reply->readAll() );
467 mTempFile->flush();
468 mTempFile->close();
469 populateStyles();
470 }
471 progressDlg->deleteLater();
472 } );
473
475 }
476}
477
478void QgsStyleExportImportDialog::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected )
479{
480 Q_UNUSED( selected )
481 Q_UNUSED( deselected )
482 const bool nothingSelected = listItems->selectionModel()->selectedIndexes().empty();
483 buttonBox->button( QDialogButtonBox::Ok )->setDisabled( nothingSelected );
484}
485
486void QgsStyleExportImportDialog::showHelp()
487{
488 QgsHelp::openHelp( QStringLiteral( "style_library/style_manager.html#sharing-style-items" ) );
489}
SymbolType
Attribute editing capabilities which may be supported by vector data providers.
Definition qgis.h:401
static const double UI_SCALE_FACTOR
UI scaling factor.
Definition qgis.h:4865
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:194
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:64
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
@ 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 ...
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.
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.
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.