QGIS API Documentation  3.18.1-Zürich (202f1bf7e5)
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 = qgis::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 #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0)
123  double iconSize = Qgis::UI_SCALE_FACTOR * fontMetrics().width( 'X' ) * 10;
124 #else
125  double iconSize = Qgis::UI_SCALE_FACTOR * fontMetrics().horizontalAdvance( 'X' ) * 10;
126 #endif
127  listItems->setIconSize( QSize( static_cast< int >( iconSize ), static_cast< int >( iconSize * 0.9 ) ) ); // ~100, 90 on low dpi
128 
129  mModel = new QgsStyleProxyModel( dialogStyle, this );
130 
131  mModel->addDesiredIconSize( listItems->iconSize() );
132 
133  listItems->setModel( mModel );
134 
135  connect( listItems->selectionModel(), &QItemSelectionModel::selectionChanged,
136  this, &QgsStyleExportImportDialog::selectionChanged );
137 
138  // use Ok button for starting import and export operations
139  disconnect( buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept );
140  connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsStyleExportImportDialog::doExportImport );
141  buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false );
142 
143  connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsStyleExportImportDialog::showHelp );
144 }
145 
147 {
148  QModelIndexList selection = listItems->selectionModel()->selectedIndexes();
149  if ( selection.isEmpty() )
150  {
151  QMessageBox::warning( this, tr( "Export/import Item(s)" ),
152  tr( "You should select at least one symbol/color ramp." ) );
153  return;
154  }
155 
156  if ( mDialogMode == Export )
157  {
158  QString fileName = QFileDialog::getSaveFileName( this, tr( "Save Styles" ), QDir::homePath(),
159  tr( "XML files (*.xml *.XML)" ) );
160  if ( fileName.isEmpty() )
161  {
162  return;
163  }
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 = qgis::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 = qgis::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 
204 bool 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 
221 void 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  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< QgsSymbol::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  QStringList symbolNames = mStyle->symbolsOfFavorite( QgsStyle::SymbolEntity );
265  selectSymbols( symbolNames );
266 }
267 
269 {
270  QStringList symbolNames = mStyle->symbolsOfFavorite( QgsStyle::SymbolEntity );
271  deselectSymbols( symbolNames );
272 }
273 
274 void QgsStyleExportImportDialog::selectSymbols( const QStringList &symbolNames )
275 {
276  const auto constSymbolNames = symbolNames;
277  for ( const QString &symbolName : constSymbolNames )
278  {
279  QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
280  const auto constIndexes = indexes;
281  for ( const QModelIndex &index : constIndexes )
282  {
283  listItems->selectionModel()->select( index, QItemSelectionModel::Select );
284  }
285  }
286 }
287 
288 void QgsStyleExportImportDialog::deselectSymbols( const QStringList &symbolNames )
289 {
290  const auto constSymbolNames = symbolNames;
291  for ( const QString &symbolName : constSymbolNames )
292  {
293  QModelIndexList indexes = listItems->model()->match( listItems->model()->index( 0, QgsStyleModel::Name ), Qt::DisplayRole, symbolName, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive );
294  const auto constIndexes = indexes;
295  for ( const QModelIndex &index : constIndexes )
296  {
297  QItemSelection deselection( index, index );
298  listItems->selectionModel()->select( deselection, QItemSelectionModel::Deselect );
299  }
300  }
301 }
302 
303 void QgsStyleExportImportDialog::selectTag( const QString &tagName )
304 {
305  QStringList symbolNames = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( tagName ) );
306  selectSymbols( symbolNames );
307 }
308 
309 void QgsStyleExportImportDialog::deselectTag( const QString &tagName )
310 {
311  QStringList symbolNames = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( tagName ) );
312  deselectSymbols( symbolNames );
313 }
314 
315 void QgsStyleExportImportDialog::selectSmartgroup( const QString &groupName )
316 {
317  QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
318  selectSymbols( symbolNames );
319  symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
320  selectSymbols( symbolNames );
321  symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
322  selectSymbols( symbolNames );
323 }
324 
325 void QgsStyleExportImportDialog::deselectSmartgroup( const QString &groupName )
326 {
327  QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) );
328  deselectSymbols( symbolNames );
329  symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) );
330  deselectSymbols( symbolNames );
331  symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::TextFormatEntity, mStyle->smartgroupId( groupName ) );
332  deselectSymbols( symbolNames );
333 }
334 
336 {
337  if ( ! mGroupSelectionDlg )
338  {
339  mGroupSelectionDlg = new QgsStyleGroupSelectionDialog( mStyle, this );
340  mGroupSelectionDlg->setWindowTitle( tr( "Select Item(s) by Group" ) );
349  }
350  mGroupSelectionDlg->show();
351  mGroupSelectionDlg->raise();
352  mGroupSelectionDlg->activateWindow();
353 }
354 
356 {
357  ImportSource source = static_cast< ImportSource >( importTypeCombo->itemData( index ).toInt() );
358 
359  switch ( source )
360  {
361  case ImportSource::File:
362  {
363  mLocationStackedEdit->setCurrentIndex( 0 );
364  mLocationLabel->setText( tr( "File" ) );
365  break;
366  }
367 #if 0
368  case ImportSource::Official:
369  {
370  btnBrowse->setText( QStringLiteral( "Fetch Items" ) );
371  locationLineEdit->setEnabled( false );
372  break;
373  }
374 #endif
375  case ImportSource::Url:
376  {
377  mLocationStackedEdit->setCurrentIndex( 1 );
378  mLocationLabel->setText( tr( "URL" ) );
379  break;
380  }
381  }
382 }
383 
384 void QgsStyleExportImportDialog::fetch()
385 {
386  downloadStyleXml( QUrl( mUrlLineEdit->text() ) );
387 }
388 
389 void QgsStyleExportImportDialog::importFileChanged( const QString &path )
390 {
391  if ( path.isEmpty() )
392  return;
393 
394  mFileName = path;
395  QFileInfo pathInfo( mFileName );
396  QString tag = pathInfo.fileName().remove( QStringLiteral( ".xml" ) );
397  mSymbolTags->setText( tag );
398  if ( QFileInfo::exists( mFileName ) )
399  {
400  mTempStyle->clear();
401  populateStyles();
402  mImportFileWidget->setDefaultRoot( pathInfo.absolutePath() );
403  QgsSettings settings;
404  settings.setValue( QStringLiteral( "StyleManager/lastImportDir" ), pathInfo.absolutePath(), QgsSettings::Gui );
405  }
406 }
407 
408 void QgsStyleExportImportDialog::downloadStyleXml( const QUrl &url )
409 {
410  mTempFile = new QTemporaryFile();
411  if ( mTempFile->open() )
412  {
413  mFileName = mTempFile->fileName();
414 
415  QProgressDialog *progressDlg = new QProgressDialog( this );
416  progressDlg->setLabelText( tr( "Downloading style…" ) );
417  progressDlg->setAutoClose( true );
418  progressDlg->show();
419 
421  fetcher->setDescription( tr( "Downloading style" ) );
422  connect( progressDlg, &QProgressDialog::canceled, fetcher, &QgsNetworkContentFetcherTask::cancel );
423  connect( fetcher, &QgsNetworkContentFetcherTask::progressChanged, progressDlg, &QProgressDialog::setValue );
424  connect( fetcher, &QgsNetworkContentFetcherTask::fetched, this, [this, fetcher, progressDlg]
425  {
426  QNetworkReply *reply = fetcher->reply();
427  if ( !reply || reply->error() != QNetworkReply::NoError )
428  {
429  mTempFile->remove();
430  mFileName.clear();
431  if ( reply )
432  QMessageBox::information( this, tr( "Import from URL" ),
433  tr( "HTTP Error! Download failed: %1." ).arg( reply->errorString() ) );
434  }
435  else
436  {
437  mTempFile->write( reply->readAll() );
438  mTempFile->flush();
439  mTempFile->close();
440  populateStyles();
441  }
442  progressDlg->deleteLater();
443  } );
444 
445  QgsApplication::taskManager()->addTask( fetcher );
446  }
447 }
448 
449 void QgsStyleExportImportDialog::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected )
450 {
451  Q_UNUSED( selected )
452  Q_UNUSED( deselected )
453  bool nothingSelected = listItems->selectionModel()->selectedIndexes().empty();
454  buttonBox->button( QDialogButtonBox::Ok )->setDisabled( nothingSelected );
455 }
456 
457 void QgsStyleExportImportDialog::showHelp()
458 {
459  QgsHelp::openHelp( QStringLiteral( "style_library/style_manager.html#sharing-style-items" ) );
460 }
static const double UI_SCALE_FACTOR
UI scaling factor.
Definition: qgis.h:183
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.
This class is a composition of two QSettings instances:
Definition: qgssettings.h:62
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.
@ 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:1317
QStringList symbolsOfSmartgroup(StyleEntity type, int id)
Returns the symbols for the smartgroup.
Definition: qgsstyle.cpp:2352
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:2215
int tagId(const QString &tag)
Returns the database id for the given tag name.
Definition: qgsstyle.cpp:2210
QStringList symbolsOfFavorite(StyleEntity type) const
Returns the symbol names which are flagged as favorite.
Definition: qgsstyle.cpp:1283
SymbolType
Type of the symbol.
Definition: qgssymbol.h:87
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:222
QSize iconSize(bool dockableToolbar)
Returns the user-preferred size of a window's toolbar icons.