QGIS API Documentation  3.20.0-Odense (decaadbb31)
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"
23 #include "qgssymbollayerutils.h"
24 #include "qgscolorramp.h"
25 #include "qgslogger.h"
28 #include "qgsguiutils.h"
29 #include "qgssettings.h"
30 #include "qgsgui.h"
31 #include "qgsstylemodel.h"
32 #include "qgsstylemanagerdialog.h"
33 
34 #include <QInputDialog>
35 #include <QCloseEvent>
36 #include <QFileDialog>
37 #include <QMessageBox>
38 #include <QNetworkReply>
39 #include <QProgressDialog>
40 #include <QPushButton>
41 #include <QStandardItemModel>
42 #include <QTemporaryFile>
43 #include <QUrl>
44 
46  : QDialog( parent )
47  , mDialogMode( mode )
48  , mStyle( style )
49 {
50  setupUi( this );
52 
53  // additional buttons
54  QPushButton *pb = nullptr;
55  pb = new QPushButton( tr( "Select All" ) );
56  buttonBox->addButton( pb, QDialogButtonBox::ActionRole );
57  connect( pb, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::selectAll );
58 
59  pb = new QPushButton( tr( "Clear Selection" ) );
60  buttonBox->addButton( pb, QDialogButtonBox::ActionRole );
61  connect( pb, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::clearSelection );
62 
63  mTempStyle = std::make_unique< QgsStyle >();
64  mTempStyle->createMemoryDatabase();
65 
66  // TODO validate
67  mGroupSelectionDlg = nullptr;
68  mTempFile = nullptr;
69 
70  QgsStyle *dialogStyle = nullptr;
71  if ( mDialogMode == Import )
72  {
73  setWindowTitle( tr( "Import Item(s)" ) );
74  // populate the import types
75  importTypeCombo->addItem( tr( "File" ), ImportSource::File );
76  // importTypeCombo->addItem( "official QGIS repo online", ImportSource::Official );
77  importTypeCombo->addItem( tr( "URL" ), ImportSource::Url );
78  connect( importTypeCombo, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsStyleExportImportDialog::importTypeChanged );
79  importTypeChanged( 0 );
80 
81  mSymbolTags->setText( QStringLiteral( "imported" ) );
82 
83  connect( mButtonFetch, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::fetch );
84 
85  mImportFileWidget->setStorageMode( QgsFileWidget::GetFile );
86  mImportFileWidget->setDialogTitle( tr( "Load Styles" ) );
87  mImportFileWidget->setFilter( tr( "XML files (*.xml *.XML)" ) );
88 
89  QgsSettings settings;
90  mImportFileWidget->setDefaultRoot( settings.value( QStringLiteral( "StyleManager/lastImportDir" ), QDir::homePath(), QgsSettings::Gui ).toString() );
91  connect( mImportFileWidget, &QgsFileWidget::fileChanged, this, &QgsStyleExportImportDialog::importFileChanged );
92 
93  label->setText( tr( "Select items to import" ) );
94  buttonBox->button( QDialogButtonBox::Ok )->setText( tr( "Import" ) );
95 
96  dialogStyle = mTempStyle.get();
97  }
98  else
99  {
100  setWindowTitle( tr( "Export Item(s)" ) );
101  // hide import specific controls when exporting
102  mLocationStackedEdit->setHidden( true );
103  fromLabel->setHidden( true );
104  importTypeCombo->setHidden( true );
105  mLocationLabel->setHidden( true );
106 
107  mFavorite->setHidden( true );
108  mIgnoreXMLTags->setHidden( true );
109 
110  pb = new QPushButton( tr( "Select by Group…" ) );
111  buttonBox->addButton( pb, QDialogButtonBox::ActionRole );
112  connect( pb, &QAbstractButton::clicked, this, &QgsStyleExportImportDialog::selectByGroup );
113  tagLabel->setHidden( true );
114  mSymbolTags->setHidden( true );
115  tagHintLabel->setHidden( true );
116 
117  buttonBox->button( QDialogButtonBox::Ok )->setText( tr( "Export" ) );
118 
119  dialogStyle = mStyle;
120  }
121 
122  double iconSize = Qgis::UI_SCALE_FACTOR * fontMetrics().horizontalAdvance( 'X' ) * 10;
123  listItems->setIconSize( QSize( static_cast< int >( iconSize ), static_cast< int >( iconSize * 0.9 ) ) ); // ~100, 90 on low dpi
124 
125  mModel = new QgsStyleProxyModel( dialogStyle, this );
126 
127  mModel->addDesiredIconSize( listItems->iconSize() );
128 
129  listItems->setModel( mModel );
130 
131  connect( listItems->selectionModel(), &QItemSelectionModel::selectionChanged,
132  this, &QgsStyleExportImportDialog::selectionChanged );
133 
134  // use Ok button for starting import and export operations
135  disconnect( buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept );
136  connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsStyleExportImportDialog::doExportImport );
137  buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false );
138 
139  connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsStyleExportImportDialog::showHelp );
140 }
141 
143 {
144  QModelIndexList selection = listItems->selectionModel()->selectedIndexes();
145  if ( selection.isEmpty() )
146  {
147  QMessageBox::warning( this, tr( "Export/import Item(s)" ),
148  tr( "You should select at least one symbol/color ramp." ) );
149  return;
150  }
151 
152  if ( mDialogMode == Export )
153  {
154  QString fileName = QFileDialog::getSaveFileName( this, tr( "Save Styles" ), QDir::homePath(),
155  tr( "XML files (*.xml *.XML)" ) );
156  if ( fileName.isEmpty() )
157  {
158  return;
159  }
160 
161  // ensure the user never omitted the extension from the file name
162  if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) )
163  {
164  fileName += QLatin1String( ".xml" );
165  }
166 
167  mFileName = fileName;
168 
169  mCursorOverride = std::make_unique< QgsTemporaryCursorOverride >( Qt::WaitCursor );
170  moveStyles( &selection, mStyle, mTempStyle.get() );
171  if ( !mTempStyle->exportXml( mFileName ) )
172  {
173  mCursorOverride.reset();
174  QMessageBox::warning( this, tr( "Export Symbols" ),
175  tr( "Error when saving selected symbols to file:\n%1" )
176  .arg( mTempStyle->errorString() ) );
177  return;
178  }
179  else
180  {
181  mCursorOverride.reset();
182  QMessageBox::information( this, tr( "Export Symbols" ),
183  tr( "The selected symbols were successfully exported to file:\n%1" )
184  .arg( mFileName ) );
185  }
186  }
187  else // import
188  {
189  mCursorOverride = std::make_unique< QgsTemporaryCursorOverride >( Qt::WaitCursor );
190  moveStyles( &selection, mTempStyle.get(), mStyle );
191 
192  accept();
193  mCursorOverride.reset();
194  }
195 
196  mFileName.clear();
197  mTempStyle->clear();
198 }
199 
200 bool QgsStyleExportImportDialog::populateStyles()
201 {
202  QgsTemporaryCursorOverride override( Qt::WaitCursor );
203 
204  // load symbols and color ramps from file
205  // NOTE mTempStyle is style here
206  mTempStyle->clear();
207  if ( !mTempStyle->importXml( mFileName ) )
208  {
209  override.release();
210  QMessageBox::warning( this, tr( "Import Symbols or Color Ramps" ),
211  tr( "An error occurred during import:\n%1" ).arg( mTempStyle->errorString() ) );
212  return false;
213  }
214  return true;
215 }
216 
217 void QgsStyleExportImportDialog::moveStyles( QModelIndexList *selection, QgsStyle *src, QgsStyle *dst )
218 {
219  QList< QgsStyleManagerDialog::ItemDetails > items;
220  items.reserve( selection->size() );
221  for ( int i = 0; i < selection->size(); ++i )
222  {
223  QModelIndex index = selection->at( i );
224 
225  QgsStyleManagerDialog::ItemDetails details;
226  details.entityType = static_cast< QgsStyle::StyleEntity >( mModel->data( index, QgsStyleModel::TypeRole ).toInt() );
227  if ( details.entityType == QgsStyle::SymbolEntity )
228  details.symbolType = static_cast< Qgis::SymbolType >( mModel->data( index, QgsStyleModel::SymbolTypeRole ).toInt() );
229  details.name = mModel->data( mModel->index( index.row(), QgsStyleModel::Name, index.parent() ), Qt::DisplayRole ).toString();
230 
231  items << details;
232  }
233  QgsStyleManagerDialog::copyItems( items, src, dst, this, mCursorOverride, mDialogMode == Import,
234  mSymbolTags->text().split( ',' ), mFavorite->isChecked(), mIgnoreXMLTags->isChecked() );
235 }
236 
238 {
239  delete mTempFile;
240  delete mGroupSelectionDlg;
241 }
242 
244 {
245  mImportFileWidget->setFilePath( path );
246 }
247 
249 {
250  listItems->selectAll();
251 }
252 
254 {
255  listItems->clearSelection();
256 }
257 
259 {
260  QStringList symbolNames = mStyle->symbolsOfFavorite( QgsStyle::SymbolEntity );
261  selectSymbols( symbolNames );
262 }
263 
265 {
266  QStringList symbolNames = mStyle->symbolsOfFavorite( QgsStyle::SymbolEntity );
267  deselectSymbols( symbolNames );
268 }
269 
270 void QgsStyleExportImportDialog::selectSymbols( const QStringList &symbolNames )
271 {
272  const auto constSymbolNames = symbolNames;
273  for ( const QString &symbolName : constSymbolNames )
274  {
275  QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
276  const auto constIndexes = indexes;
277  for ( const QModelIndex &index : constIndexes )
278  {
279  listItems->selectionModel()->select( index, QItemSelectionModel::Select );
280  }
281  }
282 }
283 
284 void QgsStyleExportImportDialog::deselectSymbols( const QStringList &symbolNames )
285 {
286  const auto constSymbolNames = symbolNames;
287  for ( const QString &symbolName : constSymbolNames )
288  {
289  QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
290  const auto constIndexes = indexes;
291  for ( const QModelIndex &index : constIndexes )
292  {
293  QItemSelection deselection( index, index );
294  listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
295  }
296  }
297 }
298 
299 void QgsStyleExportImportDialog::selectTag( const QString &tagName )
300 {
301  QStringList symbolNames = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( tagName ) );
302  selectSymbols( symbolNames );
303 }
304 
305 void QgsStyleExportImportDialog::deselectTag( const QString &tagName )
306 {
307  QStringList symbolNames = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( tagName ) );
308  deselectSymbols( symbolNames );
309 }
310 
311 void QgsStyleExportImportDialog::selectSmartgroup( const QString &groupName )
312 {
313  QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
314  selectSymbols( symbolNames );
315  symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
316  selectSymbols( symbolNames );
317  symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
318  selectSymbols( symbolNames );
319 }
320 
321 void QgsStyleExportImportDialog::deselectSmartgroup( const QString &groupName )
322 {
323  QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
324  deselectSymbols( symbolNames );
325  symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
326  deselectSymbols( symbolNames );
327  symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
328  deselectSymbols( symbolNames );
329 }
330 
332 {
333  if ( ! mGroupSelectionDlg )
334  {
335  mGroupSelectionDlg = new QgsStyleGroupSelectionDialog( mStyle, this );
336  mGroupSelectionDlg->setWindowTitle( tr( "Select Item(s) by Group" ) );
345  }
346  mGroupSelectionDlg->show();
347  mGroupSelectionDlg->raise();
348  mGroupSelectionDlg->activateWindow();
349 }
350 
352 {
353  ImportSource source = static_cast< ImportSource >( importTypeCombo->itemData( index ).toInt() );
354 
355  switch ( source )
356  {
357  case ImportSource::File:
358  {
359  mLocationStackedEdit->setCurrentIndex( 0 );
360  mLocationLabel->setText( tr( "File" ) );
361  break;
362  }
363 #if 0
364  case ImportSource::Official:
365  {
366  btnBrowse->setText( QStringLiteral( "Fetch Items" ) );
367  locationLineEdit->setEnabled( false );
368  break;
369  }
370 #endif
371  case ImportSource::Url:
372  {
373  mLocationStackedEdit->setCurrentIndex( 1 );
374  mLocationLabel->setText( tr( "URL" ) );
375  break;
376  }
377  }
378 }
379 
380 void QgsStyleExportImportDialog::fetch()
381 {
382  downloadStyleXml( QUrl( mUrlLineEdit->text() ) );
383 }
384 
385 void QgsStyleExportImportDialog::importFileChanged( const QString &path )
386 {
387  if ( path.isEmpty() )
388  return;
389 
390  mFileName = path;
391  QFileInfo pathInfo( mFileName );
392  QString tag = pathInfo.fileName().remove( QStringLiteral( ".xml" ) );
393  mSymbolTags->setText( tag );
394  if ( QFileInfo::exists( mFileName ) )
395  {
396  mTempStyle->clear();
397  populateStyles();
398  mImportFileWidget->setDefaultRoot( pathInfo.absolutePath() );
399  QgsSettings settings;
400  settings.setValue( QStringLiteral( "StyleManager/lastImportDir" ), pathInfo.absolutePath(), QgsSettings::Gui );
401  }
402 }
403 
404 void QgsStyleExportImportDialog::downloadStyleXml( const QUrl &url )
405 {
406  mTempFile = new QTemporaryFile();
407  if ( mTempFile->open() )
408  {
409  mFileName = mTempFile->fileName();
410 
411  QProgressDialog *progressDlg = new QProgressDialog( this );
412  progressDlg->setLabelText( tr( "Downloading style…" ) );
413  progressDlg->setAutoClose( true );
414  progressDlg->show();
415 
417  fetcher->setDescription( tr( "Downloading style" ) );
418  connect( progressDlg, &QProgressDialog::canceled, fetcher, &QgsNetworkContentFetcherTask::cancel );
419  connect( fetcher, &QgsNetworkContentFetcherTask::progressChanged, progressDlg, &QProgressDialog::setValue );
420  connect( fetcher, &QgsNetworkContentFetcherTask::fetched, this, [this, fetcher, progressDlg]
421  {
422  QNetworkReply *reply = fetcher->reply();
423  if ( !reply || reply->error() != QNetworkReply::NoError )
424  {
425  mTempFile->remove();
426  mFileName.clear();
427  if ( reply )
428  QMessageBox::information( this, tr( "Import from URL" ),
429  tr( "HTTP Error! Download failed: %1." ).arg( reply->errorString() ) );
430  }
431  else
432  {
433  mTempFile->write( reply->readAll() );
434  mTempFile->flush();
435  mTempFile->close();
436  populateStyles();
437  }
438  progressDlg->deleteLater();
439  } );
440 
441  QgsApplication::taskManager()->addTask( fetcher );
442  }
443 }
444 
445 void QgsStyleExportImportDialog::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected )
446 {
447  Q_UNUSED( selected )
448  Q_UNUSED( deselected )
449  bool nothingSelected = listItems->selectionModel()->selectedIndexes().empty();
450  buttonBox->button( QDialogButtonBox::Ok )->setDisabled( nothingSelected );
451 }
452 
453 void QgsStyleExportImportDialog::showHelp()
454 {
455  QgsHelp::openHelp( QStringLiteral( "style_library/style_manager.html#sharing-style-items" ) );
456 }
SymbolType
Symbol types.
Definition: qgis.h:168
static const double UI_SCALE_FACTOR
UI scaling factor.
Definition: qgis.h:416
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:66
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:156
static void openHelp(const QString &key)
Opens help topic for the given help key using default system web browser.
Definition: qgshelp.cpp:36
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.
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.
@ SymbolTypeRole
Symbol type (for symbol or legend patch shape entities)
@ 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.
QStringList symbolsWithTag(StyleEntity type, int tagid) const
Returns the symbol names with which have the given tag.
Definition: qgsstyle.cpp:1337
QStringList symbolsOfSmartgroup(StyleEntity type, int id)
Returns the symbols for the smartgroup.
Definition: qgsstyle.cpp:2374
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:2235
int tagId(const QString &tag)
Returns the database id for the given tag name.
Definition: qgsstyle.cpp:2230
QStringList symbolsOfFavorite(StyleEntity type) const
Returns the symbol names which are flagged as favorite.
Definition: qgsstyle.cpp:1303
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.