QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgsmodeldesignerdialog.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsmodeldesignerdialog.cpp
3 ------------------------
4 Date : March 2020
5 Copyright : (C) 2020 Nyall Dawson
6 Email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17
21#include "qgsapplication.h"
22#include "qgscodeeditorpython.h"
23#include "qgsfileutils.h"
24#include "qgsgui.h"
25#include "qgsmessagebar.h"
26#include "qgsmessagebaritem.h"
27#include "qgsmessagelog.h"
28#include "qgsmessageviewer.h"
33#include "qgsmodelundocommand.h"
34#include "qgsmodelviewtoolpan.h"
36#include "qgspanelwidget.h"
50#include "qgsproject.h"
51#include "qgsscreenhelper.h"
52#include "qgssettings.h"
53
54#include <QActionGroup>
55#include <QCloseEvent>
56#include <QFileDialog>
57#include <QKeySequence>
58#include <QMessageBox>
59#include <QPdfWriter>
60#include <QPushButton>
61#include <QShortcut>
62#include <QString>
63#include <QSvgGenerator>
64#include <QTextStream>
65#include <QTimer>
66#include <QToolButton>
67#include <QUndoView>
68#include <QUrl>
69
70#include "moc_qgsmodeldesignerdialog.cpp"
71
72using namespace Qt::StringLiterals;
73
75
76
77QgsModelerToolboxModel::QgsModelerToolboxModel( QObject *parent )
79{}
80
81Qt::ItemFlags QgsModelerToolboxModel::flags( const QModelIndex &index ) const
82{
83 Qt::ItemFlags f = QgsProcessingToolboxProxyModel::flags( index );
84 const QModelIndex sourceIndex = mapToSource( index );
85 if ( toolboxModel()->isAlgorithm( sourceIndex ) || toolboxModel()->isParameter( sourceIndex ) )
86 {
87 f = f | Qt::ItemIsDragEnabled;
88 }
89 return f;
90}
91
92Qt::DropActions QgsModelerToolboxModel::supportedDragActions() const
93{
94 return Qt::CopyAction;
95}
96
97QgsModelDesignerDialog::QgsModelDesignerDialog( QWidget *parent, Qt::WindowFlags flags )
98 : QMainWindow( parent, flags )
99 , mContext( QgsGui::processingGuiRegistry()->contextFactory() ? QgsGui::processingGuiRegistry()->contextFactory()->createContext() : new QgsProcessingContext() )
100 , mToolsActionGroup( new QActionGroup( this ) )
101{
102 setupUi( this );
103
104 mToolbar->setIconSize( QgsGui::iconSize() );
105 setStyleSheet( QgsGui::applicationStyleSheet() );
106 connect( QgsGui::instance(), &QgsGui::applicationStyleSheetChanged, this, &QgsModelDesignerDialog::setStyleSheet );
107
108 mLayerStore.setProject( QgsProject::instance() );
109
110 mScreenHelper = new QgsScreenHelper( this );
111
112 setAttribute( Qt::WA_DeleteOnClose );
113 setDockOptions( dockOptions() | QMainWindow::GroupedDragging );
114 setWindowFlags( Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint );
115
117
118 mModel = std::make_unique<QgsProcessingModelAlgorithm>();
119 mModel->setProvider( QgsApplication::processingRegistry()->providerById( QgsProcessing::MODEL_PROVIDER_ID ) );
120
121 mUndoStack = new QUndoStack( this );
122 connect( mUndoStack, &QUndoStack::indexChanged, this, [this] {
123 if ( mIgnoreUndoStackChanges )
124 return;
125
126 mBlockUndoCommands++;
127 updateVariablesGui();
128 mGroupEdit->setText( mModel->group() );
129 mNameEdit->setText( mModel->displayName() );
130 mBlockUndoCommands--;
131 repaintModel();
132 } );
133
134 mConfigWidgetDock = new QgsDockWidget( this );
135 mConfigWidgetDock->setWindowTitle( tr( "Configuration" ) );
136 mConfigWidgetDock->setObjectName( u"ModelConfigDock"_s );
137
138 mConfigWidget = new QgsModelDesignerConfigDockWidget();
139 mConfigWidgetDock->setWidget( mConfigWidget );
140 mConfigWidgetDock->setFeatures( QDockWidget::NoDockWidgetFeatures );
141 addDockWidget( Qt::RightDockWidgetArea, mConfigWidgetDock );
142
143 mPropertiesDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
144 mInputsDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
145 mAlgorithmsDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
146 mVariablesDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
147
148 mToolboxTree->header()->setVisible( false );
149 mToolboxSearchEdit->setShowSearchIcon( true );
150 mToolboxSearchEdit->setPlaceholderText( tr( "Search…" ) );
151 connect( mToolboxSearchEdit, &QgsFilterLineEdit::textChanged, mToolboxTree, &QgsProcessingToolboxTreeView::setFilterString );
152
153 mInputsTreeWidget->header()->setVisible( false );
154 mInputsTreeWidget->setAlternatingRowColors( true );
155 mInputsTreeWidget->setDragDropMode( QTreeWidget::DragOnly );
156 mInputsTreeWidget->setDropIndicatorShown( true );
157
158 mNameEdit->setPlaceholderText( tr( "Enter model name here" ) );
159 mGroupEdit->setPlaceholderText( tr( "Enter group name here" ) );
160
161 mMessageBar = new QgsMessageBar();
162 mMessageBar->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Fixed );
163 mainLayout->insertWidget( 0, mMessageBar );
164
165 mView->setAcceptDrops( true );
166 QgsSettings settings;
167
168 connect( mActionClose, &QAction::triggered, this, &QWidget::close );
169 connect( mActionNew, &QAction::triggered, this, &QgsModelDesignerDialog::newModel );
170 connect( mActionZoomIn, &QAction::triggered, this, &QgsModelDesignerDialog::zoomIn );
171 connect( mActionZoomOut, &QAction::triggered, this, &QgsModelDesignerDialog::zoomOut );
172 connect( mActionZoomActual, &QAction::triggered, this, &QgsModelDesignerDialog::zoomActual );
173 connect( mActionZoomToItems, &QAction::triggered, this, &QgsModelDesignerDialog::zoomFull );
174 connect( mActionExportImage, &QAction::triggered, this, &QgsModelDesignerDialog::exportToImage );
175 connect( mActionExportPdf, &QAction::triggered, this, &QgsModelDesignerDialog::exportToPdf );
176 connect( mActionExportSvg, &QAction::triggered, this, &QgsModelDesignerDialog::exportToSvg );
177 connect( mActionExportPython, &QAction::triggered, this, &QgsModelDesignerDialog::exportAsPython );
178 connect( mActionOpen, &QAction::triggered, this, &QgsModelDesignerDialog::openModel );
179 connect( mActionSave, &QAction::triggered, this, [this] { saveModel( false ); } );
180 connect( mActionSaveAs, &QAction::triggered, this, [this] { saveModel( true ); } );
181 connect( mActionSaveInProject, &QAction::triggered, this, &QgsModelDesignerDialog::saveInProject );
182 connect( mActionDeleteComponents, &QAction::triggered, this, &QgsModelDesignerDialog::deleteSelected );
183 connect( mActionSnapSelected, &QAction::triggered, mView, &QgsModelGraphicsView::snapSelected );
184 connect( mActionValidate, &QAction::triggered, this, &QgsModelDesignerDialog::validate );
185 connect( mActionReorderInputs, &QAction::triggered, this, &QgsModelDesignerDialog::reorderInputs );
186 connect( mActionReorderOutputs, &QAction::triggered, this, &QgsModelDesignerDialog::reorderOutputs );
187 connect( mActionEditHelp, &QAction::triggered, this, &QgsModelDesignerDialog::editHelp );
188 connect( mReorderInputsButton, &QPushButton::clicked, this, &QgsModelDesignerDialog::reorderInputs );
189 connect( mActionRun, &QAction::triggered, this, [this] { run(); } );
190 connect( mActionRunSelectedSteps, &QAction::triggered, this, &QgsModelDesignerDialog::runSelectedSteps );
191
192 mActionSnappingEnabled->setChecked( settings.value( u"/Processing/Modeler/enableSnapToGrid"_s, false ).toBool() );
193 connect( mActionSnappingEnabled, &QAction::toggled, this, [this]( bool enabled ) {
194 mView->snapper()->setSnapToGrid( enabled );
195 QgsSettings().setValue( u"/Processing/Modeler/enableSnapToGrid"_s, enabled );
196 } );
197 mView->snapper()->setSnapToGrid( mActionSnappingEnabled->isChecked() );
198
199 connect( mView, &QgsModelGraphicsView::itemFocused, this, &QgsModelDesignerDialog::onItemFocused );
200
201 connect( mActionSelectAll, &QAction::triggered, this, [this] { mScene->selectAll(); } );
202
203 QStringList docksTitle = settings.value( u"ModelDesigner/hiddenDocksTitle"_s, QStringList(), QgsSettings::App ).toStringList();
204 QStringList docksActive = settings.value( u"ModelDesigner/hiddenDocksActive"_s, QStringList(), QgsSettings::App ).toStringList();
205 if ( !docksTitle.isEmpty() )
206 {
207 for ( const auto &title : docksTitle )
208 {
209 mPanelStatus.insert( title, PanelStatus( true, docksActive.contains( title ) ) );
210 }
211 }
212 mActionHidePanels->setChecked( !docksTitle.isEmpty() );
213 connect( mActionHidePanels, &QAction::toggled, this, &QgsModelDesignerDialog::setPanelVisibility );
214
215 mUndoAction = mUndoStack->createUndoAction( this );
216 mUndoAction->setIcon( QgsApplication::getThemeIcon( u"/mActionUndo.svg"_s ) );
217 mUndoAction->setShortcuts( QKeySequence::Undo );
218 mRedoAction = mUndoStack->createRedoAction( this );
219 mRedoAction->setIcon( QgsApplication::getThemeIcon( u"/mActionRedo.svg"_s ) );
220 mRedoAction->setShortcuts( QKeySequence::Redo );
221
222 mMenuEdit->insertAction( mActionDeleteComponents, mRedoAction );
223 mMenuEdit->insertAction( mActionDeleteComponents, mUndoAction );
224 mMenuEdit->insertSeparator( mActionDeleteComponents );
225 mToolbar->insertAction( mActionZoomIn, mUndoAction );
226 mToolbar->insertAction( mActionZoomIn, mRedoAction );
227 mToolbar->insertSeparator( mActionZoomIn );
228
229 mGroupMenu = new QMenu( tr( "Zoom To" ), this );
230 mMenuView->insertMenu( mActionZoomIn, mGroupMenu );
231 connect( mGroupMenu, &QMenu::aboutToShow, this, &QgsModelDesignerDialog::populateZoomToMenu );
232
233 //cut/copy/paste actions. Note these are not included in the ui file
234 //as ui files have no support for QKeySequence shortcuts
235 mActionCut = new QAction( tr( "Cu&t" ), this );
236 mActionCut->setShortcuts( QKeySequence::Cut );
237 mActionCut->setStatusTip( tr( "Cut" ) );
238 mActionCut->setIcon( QgsApplication::getThemeIcon( u"/mActionEditCut.svg"_s ) );
239 connect( mActionCut, &QAction::triggered, this, [this] { mView->copySelectedItems( QgsModelGraphicsView::ClipboardCut ); } );
240
241 mActionCopy = new QAction( tr( "&Copy" ), this );
242 mActionCopy->setShortcuts( QKeySequence::Copy );
243 mActionCopy->setStatusTip( tr( "Copy" ) );
244 mActionCopy->setIcon( QgsApplication::getThemeIcon( u"/mActionEditCopy.svg"_s ) );
245 connect( mActionCopy, &QAction::triggered, this, [this] { mView->copySelectedItems( QgsModelGraphicsView::ClipboardCopy ); } );
246
247 mActionPaste = new QAction( tr( "&Paste" ), this );
248 mActionPaste->setShortcuts( QKeySequence::Paste );
249 mActionPaste->setStatusTip( tr( "Paste" ) );
250 mActionPaste->setIcon( QgsApplication::getThemeIcon( u"/mActionEditPaste.svg"_s ) );
251 connect( mActionPaste, &QAction::triggered, this, [this] { mView->pasteItems( QgsModelGraphicsView::PasteModeCursor ); } );
252 mMenuEdit->insertAction( mActionDeleteComponents, mActionCut );
253 mMenuEdit->insertAction( mActionDeleteComponents, mActionCopy );
254 mMenuEdit->insertAction( mActionDeleteComponents, mActionPaste );
255 mMenuEdit->insertSeparator( mActionDeleteComponents );
256
257 mAlgorithmsModel = new QgsModelerToolboxModel( this );
258 mToolboxTree->setToolboxProxyModel( mAlgorithmsModel );
259
261 if ( settings.value( u"Processing/Configuration/SHOW_ALGORITHMS_KNOWN_ISSUES"_s, false ).toBool() )
262 {
264 }
265 mToolboxTree->setFilters( filters );
266 mToolboxTree->setDragDropMode( QTreeWidget::DragOnly );
267 mToolboxTree->setDropIndicatorShown( true );
268
269 connect( mView, &QgsModelGraphicsView::algorithmDropped, this, [this]( const QString &algorithmId, const QPointF &pos ) { addAlgorithm( algorithmId, pos ); } );
270 connect( mView, &QgsModelGraphicsView::inputDropped, this, &QgsModelDesignerDialog::addInput );
271
272 connect( mToolboxTree, &QgsProcessingToolboxTreeView::doubleClicked, this, [this]( const QModelIndex & ) {
273 if ( mToolboxTree->selectedAlgorithm() )
274 addAlgorithm( mToolboxTree->selectedAlgorithm()->id(), QPointF() );
275 if ( mToolboxTree->selectedParameterType() )
276 addInput( mToolboxTree->selectedParameterType()->id(), QPointF() );
277 } );
278
279 connect( mInputsTreeWidget, &QgsModelDesignerInputsTreeWidget::doubleClicked, this, [this]( const QModelIndex & ) {
280 const QString parameterType = mInputsTreeWidget->currentItem()->data( 0, Qt::UserRole ).toString();
281 addInput( parameterType, QPointF() );
282 } );
283
284 // Ctrl+= should also trigger a zoom in action
285 QShortcut *ctrlEquals = new QShortcut( QKeySequence( u"Ctrl+="_s ), this );
286 connect( ctrlEquals, &QShortcut::activated, this, &QgsModelDesignerDialog::zoomIn );
287
288 mUndoDock = new QgsDockWidget( tr( "Undo History" ), this );
289 mUndoDock->setObjectName( u"UndoDock"_s );
290 mUndoView = new QUndoView( mUndoStack, this );
291 mUndoDock->setWidget( mUndoView );
292 mUndoDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
293 addDockWidget( Qt::DockWidgetArea::LeftDockWidgetArea, mUndoDock );
294
295 tabifyDockWidget( mUndoDock, mPropertiesDock );
296 tabifyDockWidget( mVariablesDock, mPropertiesDock );
297 mPropertiesDock->raise();
298 tabifyDockWidget( mInputsDock, mAlgorithmsDock );
299 mInputsDock->raise();
300
301 connect( mVariablesEditor, &QgsVariableEditorWidget::scopeChanged, this, [this] {
302 if ( mModel )
303 {
304 beginUndoCommand( tr( "Change Model Variables" ) );
305 mModel->setVariables( mVariablesEditor->variablesInActiveScope() );
306 endUndoCommand();
307 }
308 } );
309 connect( mNameEdit, &QLineEdit::textChanged, this, [this]( const QString &name ) {
310 if ( mModel )
311 {
312 beginUndoCommand( tr( "Change Model Name" ), QString(), QgsModelUndoCommand::CommandOperation::NameChanged );
313 mModel->setName( name );
314 endUndoCommand();
315 updateWindowTitle();
316 }
317 } );
318 connect( mGroupEdit, &QLineEdit::textChanged, this, [this]( const QString &group ) {
319 if ( mModel )
320 {
321 beginUndoCommand( tr( "Change Model Group" ), QString(), QgsModelUndoCommand::CommandOperation::GroupChanged );
322 mModel->setGroup( group );
323 endUndoCommand();
324 updateWindowTitle();
325 }
326 } );
327
328 fillInputsTree();
329
330 QToolButton *toolbuttonExportToScript = new QToolButton();
331 toolbuttonExportToScript->setPopupMode( QToolButton::InstantPopup );
332 toolbuttonExportToScript->addAction( mActionExportAsScriptAlgorithm );
333 toolbuttonExportToScript->setDefaultAction( mActionExportAsScriptAlgorithm );
334 mToolbar->insertWidget( mActionExportImage, toolbuttonExportToScript );
335 connect( mActionExportAsScriptAlgorithm, &QAction::triggered, this, &QgsModelDesignerDialog::exportAsScriptAlgorithm );
336
337 mActionShowComments->setChecked( settings.value( u"/Processing/Modeler/ShowComments"_s, true ).toBool() );
338 connect( mActionShowComments, &QAction::toggled, this, &QgsModelDesignerDialog::toggleComments );
339
340 mActionShowFeatureCount->setChecked( settings.value( u"/Processing/Modeler/ShowFeatureCount"_s, true ).toBool() );
341 connect( mActionShowFeatureCount, &QAction::toggled, this, &QgsModelDesignerDialog::toggleFeatureCount );
342
343 mPanTool = new QgsModelViewToolPan( mView );
344 mPanTool->setAction( mActionPan );
345
346 mToolsActionGroup->addAction( mActionPan );
347 connect( mActionPan, &QAction::triggered, mPanTool, [this] { mView->setTool( mPanTool ); } );
348
349 // We use a QObjectUniquePtr here because we want to delete QgsModelViewToolSelect
350 // mouse handles before everything else and don't want to wait for QObject destructor to destroy it
351 mSelectTool = make_qobject_unique<QgsModelViewToolSelect>( mView );
352 mSelectTool->setAction( mActionSelectMoveItem );
353
354 mToolsActionGroup->addAction( mActionSelectMoveItem );
355 connect( mActionSelectMoveItem, &QAction::triggered, mSelectTool, [this] { mView->setTool( mSelectTool ); } );
356
357 mView->setTool( mSelectTool );
358 mView->setFocus();
359
360 connect( mView, &QgsModelGraphicsView::macroCommandStarted, this, [this]( const QString &text ) {
361 mIgnoreUndoStackChanges++;
362 mUndoStack->beginMacro( text );
363 mIgnoreUndoStackChanges--;
364 } );
365 connect( mView, &QgsModelGraphicsView::macroCommandEnded, this, [this] {
366 mIgnoreUndoStackChanges++;
367 mUndoStack->endMacro();
368 mIgnoreUndoStackChanges--;
369 } );
370 connect( mView, &QgsModelGraphicsView::commandBegun, this, [this]( const QString &text ) { beginUndoCommand( text ); } );
371 connect( mView, &QgsModelGraphicsView::commandEnded, this, [this] { endUndoCommand(); } );
372 connect( mView, &QgsModelGraphicsView::commandAborted, this, [this] { abortUndoCommand(); } );
373 connect( mView, &QgsModelGraphicsView::deleteSelectedItems, this, [this] { deleteSelected(); } );
374
375 connect( mActionAddGroupBox, &QAction::triggered, this, [this] {
376 const QPointF viewCenter = mView->mapToScene( mView->viewport()->rect().center() );
377 QgsProcessingModelGroupBox group;
378 group.setPosition( viewCenter );
379 group.setDescription( tr( "New Group" ) );
380
381 beginUndoCommand( tr( "Add Group Box" ) );
382 model()->addGroupBox( group );
383 repaintModel();
384 endUndoCommand();
385 } );
386
387 updateWindowTitle();
388
389 // restore the toolbar and dock widgets positions using Qt settings API
390 restoreState( settings.value( u"ModelDesigner/state"_s, QByteArray(), QgsSettings::App ).toByteArray() );
391
392 repaintModel();
393}
394
395QgsModelDesignerDialog::~QgsModelDesignerDialog()
396{
397 if ( mAlgorithmWidget )
398 {
399 delete mAlgorithmWidget;
400 }
401 for ( const QPointer<QgsProcessingAlgorithmWidget> &widget : std::as_const( mAlgorithmWidgetsToCleanUp ) )
402 {
403 // this is a work around for the MESSY ownership issues associated with the python subclass
404 // of QgsProcessingAlgorithmWidget. We have to FORCE all widgets to be deleted prior
405 // to destruction of this window, and we can't be sure that python will have actually
406 // deleted the widget when we asked...
407 if ( widget )
408 {
409 delete widget;
410 }
411 }
412
413 QgsSettings settings;
414 if ( !mPanelStatus.isEmpty() )
415 {
416 QStringList docksTitle;
417 QStringList docksActive;
418
419 for ( const auto &panel : mPanelStatus.toStdMap() )
420 {
421 if ( panel.second.isVisible )
422 docksTitle << panel.first;
423 if ( panel.second.isActive )
424 docksActive << panel.first;
425 }
426 settings.setValue( u"ModelDesigner/hiddenDocksTitle"_s, docksTitle, QgsSettings::App );
427 settings.setValue( u"ModelDesigner/hiddenDocksActive"_s, docksActive, QgsSettings::App );
428 }
429 else
430 {
431 settings.remove( u"ModelDesigner/hiddenDocksTitle"_s, QgsSettings::App );
432 settings.remove( u"ModelDesigner/hiddenDocksActive"_s, QgsSettings::App );
433 }
434
435 // store the toolbar/dock widget settings using Qt settings API
436 settings.setValue( u"ModelDesigner/state"_s, saveState(), QgsSettings::App );
437
438 mIgnoreUndoStackChanges++;
439}
440
441void QgsModelDesignerDialog::closeEvent( QCloseEvent *event )
442{
443 if ( checkForUnsavedChanges() )
444 {
445 emit aboutToClose();
446 event->accept();
447 }
448 else
449 {
450 event->ignore();
451 }
452}
453
454void QgsModelDesignerDialog::beginUndoCommand( const QString &text, const QString &id, QgsModelUndoCommand::CommandOperation operation )
455{
456 if ( mBlockUndoCommands || !mUndoStack )
457 return;
458
459 if ( mActiveCommand )
460 endUndoCommand();
461
462 if ( !id.isEmpty() )
463 {
464 mActiveCommand = std::make_unique<QgsModelUndoCommand>( mModel.get(), text, id );
465 }
466 else
467 {
468 mActiveCommand = std::make_unique<QgsModelUndoCommand>( mModel.get(), text, operation );
469 }
470}
471
472void QgsModelDesignerDialog::endUndoCommand()
473{
474 if ( mBlockUndoCommands || !mActiveCommand || !mUndoStack )
475 return;
476
477 mActiveCommand->saveAfterState();
478 mIgnoreUndoStackChanges++;
479 mUndoStack->push( mActiveCommand.release() );
480 mIgnoreUndoStackChanges--;
481 setDirty( true );
482}
483
484void QgsModelDesignerDialog::abortUndoCommand()
485{
486 if ( mActiveCommand )
487 mActiveCommand->setObsolete( true );
488}
489
490QgsProcessingModelAlgorithm *QgsModelDesignerDialog::model()
491{
492 return mModel.get();
493}
494
495void QgsModelDesignerDialog::setModel( QgsProcessingModelAlgorithm *model )
496{
497 mModel.reset( model );
498
499 mGroupEdit->setText( mModel->group() );
500 mNameEdit->setText( mModel->displayName() );
501 repaintModel( true );
502 updateVariablesGui();
503
504 const QString modelQgisVersion = mModel->modelQgisVersion();
505 handleVersionMismatch( modelQgisVersion );
506
507 setDirty( false );
508
509 mIgnoreUndoStackChanges++;
510 mUndoStack->clear();
511 mIgnoreUndoStackChanges--;
512
513 updateWindowTitle();
514
515 // Delay zoom to the full model to ensure the scene has been properly set
516 // and that the itemsBoundingRect returns the correct value.
517 QTimer::singleShot( 100, this, [this] { zoomFull(); } );
518}
519
520void QgsModelDesignerDialog::loadModel( const QString &path )
521{
522 std::unique_ptr< QgsProcessingModelAlgorithm > alg = QgsProcessingModelAlgorithm::loadModel( path );
523 if ( !alg )
524 {
525 QMessageBox::critical(
526 this,
527 QObject::tr( "Open Model" ),
528 QObject::tr(
529 "The selected model could not be loaded.\n"
530 "See the log for more information."
531 )
532 );
533 return;
534 }
535
536 setModel( alg.release() );
537}
538
539void QgsModelDesignerDialog::handleVersionMismatch( const QString &modelVersion ) const
540{
541 const QgsProjectVersion thisVersion( Qgis::version() );
542
543 const QgsProjectVersion fileVersion = ( modelVersion.isEmpty() ) ? QgsProjectVersion( 0, 0, 0, QString() ) : QgsProjectVersion( modelVersion );
544
545 // Special case before 4.4 we didn't store the qgis version in the model so assume it's before 4.4
546 if ( fileVersion == QgsProjectVersion( 0, 0, 0 ) )
547 {
548 const QString message = tr(
549 "This model file was created in an older QGIS version."
550 " When saving this model file, QGIS will update it to version %1, "
551 "possibly rendering it unusable with older versions of QGIS."
552 )
553 .arg( thisVersion.text() );
554 mMessageBar->pushInfo( QString(), message );
555 }
556 else if ( thisVersion > fileVersion )
557 {
558 const QString message = tr(
559 "This model file was created in QGIS version %1."
560 " When saving this model file, QGIS will update it to version %2, "
561 "possibly rendering it unusable with older versions of QGIS."
562 )
563 .arg( fileVersion.text(), thisVersion.text() );
564 mMessageBar->pushInfo( QString(), message );
565 }
566 else if ( thisVersion < fileVersion )
567 {
568 const QString message = tr(
569 "This model was created by a newer version of QGIS (%1)."
570 " The integrity of this model file may not be guaranteed."
571 )
572 .arg( fileVersion.text() );
573
574 mMessageBar->pushWarning( QString(), message );
575 }
576 else
577 {
578 //All good model and qgis version match!
579 }
580}
581
582void QgsModelDesignerDialog::setModelScene( QgsModelGraphicsScene *scene )
583{
584 QgsModelGraphicsScene *oldScene = mScene;
585
586 mScene = scene;
587 mScene->setParent( this );
588 mScene->setLastRunResult( mLastResult, mLayerStore );
589 mScene->setModel( mModel.get() );
590 mScene->setMessageBar( mMessageBar );
591 mScene->registerWidgetContextGenerator( this );
592
593 QgsSettings settings;
594 const bool showFeatureCount = settings.value( u"/Processing/Modeler/ShowFeatureCount"_s, true ).toBool();
595 if ( !showFeatureCount )
596 mScene->setFlag( QgsModelGraphicsScene::FlagHideFeatureCount );
597
598 mView->setModelScene( mScene );
599
600 mSelectTool->resetCache();
601 mSelectTool->setScene( mScene );
602
603 connect( mScene, &QgsModelGraphicsScene::rebuildRequired, this, [this] {
604 if ( mBlockRepaints )
605 return;
606
607 repaintModel();
608 mScene->flagChildrenAsOutdated( mOutdatedChildResults );
609 } );
610 connect( mScene, &QgsModelGraphicsScene::componentAboutToChange, this, [this]( const QString &description, const QString &id ) { beginUndoCommand( description, id ); } );
611 connect( mScene, &QgsModelGraphicsScene::componentChanged, this, [this] { endUndoCommand(); } );
612 connect( mScene, &QgsModelGraphicsScene::runFromChild, this, &QgsModelDesignerDialog::runFromChild );
613 connect( mScene, &QgsModelGraphicsScene::runSelected, this, &QgsModelDesignerDialog::runSelectedSteps );
614 connect( mScene, &QgsModelGraphicsScene::showChildAlgorithmOutputs, this, &QgsModelDesignerDialog::showChildAlgorithmOutputs );
615 connect( mScene, &QgsModelGraphicsScene::showChildAlgorithmLog, this, &QgsModelDesignerDialog::showChildAlgorithmLog );
616
617 if ( oldScene )
618 oldScene->deleteLater();
619}
620
621QgsModelGraphicsScene *QgsModelDesignerDialog::modelScene()
622{
623 return mScene;
624}
625
626QgsProcessingFeedback *QgsModelDesignerDialog::createFeedback()
627{
628 auto result = std::make_unique< QgsProcessingModelFeedback >();
629 mScene->setupFeedbackConnections( result.get() );
630 connect( result.get(), &QgsProcessingModelFeedback::childResultReported, this, [this]( const QString &childId, const QgsProcessingModelChildAlgorithmResult & ) {
631 mOutdatedChildResults.remove( childId );
632 } );
633
634 return result.release();
635}
636
637QgsProcessingParameterWidgetContext QgsModelDesignerDialog::createWidgetContext()
638{
640 context.setModel( model() );
641 context.setModelDesignerDialog( this );
643 return context;
644}
645
646void QgsModelDesignerDialog::activate()
647{
648 show();
649 raise();
650 setWindowState( windowState() & ~Qt::WindowMinimized );
651 activateWindow();
652}
653
654QgsProcessingContext *QgsModelDesignerDialog::processingContext() const
655{
656 return mContext.get();
657}
658
659void QgsModelDesignerDialog::updateVariablesGui()
660{
661 mBlockUndoCommands++;
662
663 auto variablesScope = std::make_unique<QgsExpressionContextScope>( tr( "Model Variables" ) );
664 const QVariantMap modelVars = mModel->variables();
665 for ( auto it = modelVars.constBegin(); it != modelVars.constEnd(); ++it )
666 {
667 variablesScope->setVariable( it.key(), it.value() );
668 }
669 QgsExpressionContext variablesContext;
670 variablesContext.appendScope( variablesScope.release() );
671 mVariablesEditor->setContext( &variablesContext );
672 mVariablesEditor->setEditableScopeIndex( 0 );
673
674 mBlockUndoCommands--;
675}
676
677void QgsModelDesignerDialog::setDirty( bool dirty )
678{
679 mHasChanged = dirty;
680 updateWindowTitle();
681 if ( mAlgorithmWidget )
682 {
683 if ( QgsMessageBar *messageBar = mAlgorithmWidget->messageBar() )
684 {
685 QgsMessageBarItem *messageBarItem = messageBar->createMessage( QString(), tr( "The model has changed, this panel should be reloaded." ) );
686 auto reloadButton = new QPushButton( tr( "Reload Now" ) );
687 connect( reloadButton, &QPushButton::clicked, reloadButton, [this] {
688 if ( mAlgorithmWidget && mAlgorithmWidget->isRunning() )
689 {
690 QMessageBox messageBox;
691 messageBox.setIcon( QMessageBox::Icon::Warning );
692 messageBox.setWindowTitle( tr( "Run Model" ) );
693 messageBox.setText( tr( "This model is currently running." ) );
694 messageBox.setStandardButtons( QMessageBox::StandardButton::Cancel | QMessageBox::StandardButton::RestoreDefaults );
695
696 QAbstractButton *buttonReRun = messageBox.button( QMessageBox::StandardButton::RestoreDefaults );
697 buttonReRun->setText( tr( "Terminate and Reload" ) );
698
699 int r = messageBox.exec();
700
701 switch ( r )
702 {
703 case QMessageBox::StandardButton::Cancel:
704 return;
705 case QMessageBox::StandardButton::RestoreDefaults:
706 break;
707 default:
708 break;
709 }
710 }
711 cancelRunningModel();
712 run();
713 } );
714 messageBarItem->layout()->addWidget( reloadButton );
715 messageBar->pushWidget( messageBarItem, Qgis::MessageLevel::Warning );
716 }
717 }
718}
719
720bool QgsModelDesignerDialog::validateSave( SaveAction action )
721{
722 switch ( action )
723 {
724 case QgsModelDesignerDialog::SaveAction::SaveAsFile:
725 break;
726 case QgsModelDesignerDialog::SaveAction::SaveInProject:
727 if ( mNameEdit->text().trimmed().isEmpty() )
728 {
729 mMessageBar->pushWarning( QString(), tr( "Please enter a model name before saving" ) );
730 return false;
731 }
732 break;
733 }
734
735 return true;
736}
737
738bool QgsModelDesignerDialog::checkForUnsavedChanges()
739{
740 if ( isDirty() )
741 {
742 QMessageBox::StandardButton ret = QMessageBox::
743 question( this, tr( "Save Model?" ), tr( "There are unsaved changes in this model. Do you want to keep those?" ), QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Discard, QMessageBox::Cancel );
744 switch ( ret )
745 {
746 case QMessageBox::Save:
747 return saveModel( false );
748
749 case QMessageBox::Discard:
750 return true;
751
752 default:
753 return false;
754 }
755 }
756 else
757 {
758 return true;
759 }
760}
761
762void QgsModelDesignerDialog::setLastRunResult( const QgsProcessingModelResult &result )
763{
764 mLastResult.mergeWith( result );
765 if ( mScene )
766 mScene->setLastRunResult( mLastResult, mLayerStore );
767}
768
769void QgsModelDesignerDialog::setModelName( const QString &name )
770{
771 mNameEdit->setText( name );
772}
773
774void QgsModelDesignerDialog::saveInProject()
775{
776 if ( !validateSave( SaveAction::SaveInProject ) )
777 return;
778
779 mModel->setSourceFilePath( QString() );
780
781 auto projectProvider = qobject_cast< QgsProcessingProjectModelProvider * >( QgsApplication::processingRegistry()->providerById( QgsProcessing::PROJECT_PROVIDER_ID ) );
782 if ( !projectProvider )
783 return; // should not happen
784
785 projectProvider->addModel( *mModel );
786
787 emit modelUpdated();
788
789 mMessageBar->pushMessage( QString(), tr( "Model was saved inside current project" ), Qgis::MessageLevel::Success, 5 );
790
791 setDirty( false );
793}
794
795bool QgsModelDesignerDialog::saveModel( bool saveAs )
796{
797 if ( !validateSave( SaveAction::SaveAsFile ) )
798 return false;
799
800 const bool modelNameMatchedFileName = mModel->modelNameMatchesFilePath();
801 QString fileName;
802 if ( !mModel->sourceFilePath().isEmpty() && !saveAs )
803 {
804 fileName = mModel->sourceFilePath();
805 }
806 else
807 {
808 QString initialPath;
809 if ( !mModel->sourceFilePath().isEmpty() )
810 {
811 initialPath = mModel->sourceFilePath();
812 }
813 else if ( !mModel->name().isEmpty() )
814 {
815 initialPath = u"%1/%2.model3"_s.arg( QgsProcessingUtils::modelFolders()[0], mModel->name() );
816 }
817 else
818 {
819 initialPath = QgsProcessingUtils::modelFolders()[0];
820 }
821
822 fileName = QFileDialog::getSaveFileName( this, tr( "Save Model" ), initialPath, tr( "Processing models (*.model3 *.MODEL3)" ) );
823 if ( fileName.isEmpty() )
824 {
825 return false;
826 }
827
828 fileName = QgsFileUtils::ensureFileNameHasExtension( fileName, { "model3" } );
829 mModel->setSourceFilePath( fileName );
830
831 if ( mModel->name().isEmpty() || mModel->name() == tr( "model" ) )
832 {
833 setModelName( QFileInfo( fileName ).baseName() );
834 }
835 else if ( saveAs && modelNameMatchedFileName )
836 {
837 // if saving as, and the model name used to match the filename, then automatically update the
838 // model name to match the new file name
839 setModelName( QFileInfo( fileName ).baseName() );
840 }
841 }
842
843 if ( !mModel->toFile( fileName ) )
844 {
845 if ( saveAs )
846 {
847 QMessageBox::warning( this, tr( "Save Model" ), tr( "Unable to save edits (probably you do not have permission to write to this location)." ) );
848 }
849 else
850 {
851 QMessageBox::warning(
852 this,
853 tr( "Save Model" ),
854 tr(
855 "This model can't be saved in its original location (probably you do not "
856 "have permission to do it). Please, use the 'Save as…' option."
857 )
858 );
859 }
860 return false;
861 }
862
863 emit modelUpdated();
864 if ( saveAs )
865 {
866 mMessageBar->pushMessage( QString(), tr( "Model was saved to <a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( fileName ).toString(), QDir::toNativeSeparators( fileName ) ), Qgis::MessageLevel::Success, 5 );
867 }
868
869 setDirty( false );
870 return true;
871}
872
873QPointF QgsModelDesignerDialog::getPositionForParameterItem() const
874{
875 constexpr double MARGIN = 20;
876 constexpr double BOX_WIDTH = 200;
877 constexpr double BOX_HEIGHT = 80;
878
879 double newX = 0;
880 const QMap<QString, QgsProcessingModelParameter> components = mModel->parameterComponents();
881 if ( !components.isEmpty() )
882 {
883 double maxX = 0;
884 for ( auto it = components.constBegin(); it != components.constEnd(); ++it )
885 {
886 maxX = std::max( maxX, it->position().x() );
887 }
888 newX = MARGIN + BOX_WIDTH + maxX;
889 }
890 else
891 {
892 newX = MARGIN + BOX_WIDTH / 2.0;
893 }
894 return QPointF( newX, MARGIN + BOX_HEIGHT / 2.0 );
895}
896
897QPointF QgsModelDesignerDialog::getPositionForAlgorithmItem() const
898{
899 constexpr double MARGIN = 20;
900 constexpr double BOX_WIDTH = 200;
901 constexpr double BOX_HEIGHT = 80;
902
903 const QMap<QString, QgsProcessingModelChildAlgorithm> algorithms = mModel->childAlgorithms();
904
905 double newX = 0;
906 double newY = 0;
907 if ( !algorithms.isEmpty() )
908 {
909 double maxX = 0;
910 double maxY = 0;
911 for ( auto it = algorithms.constBegin(); it != algorithms.constEnd(); ++it )
912 {
913 maxX = std::max( maxX, it->position().x() );
914 maxY = std::max( maxY, it->position().y() );
915 }
916 newX = MARGIN + BOX_WIDTH + maxX;
917 newY = MARGIN + BOX_HEIGHT + maxY;
918 }
919 else
920 {
921 newX = MARGIN + BOX_WIDTH / 2.0;
922 newY = MARGIN * 2 + BOX_HEIGHT + BOX_HEIGHT / 2.0;
923 }
924 return QPointF( newX, newY );
925}
926
927void QgsModelDesignerDialog::autoGenerateParameterName( QgsProcessingParameterDefinition *parameter ) const
928{
929 const QString safeName = QgsProcessingModelAlgorithm::safeName( parameter->description() );
930 QString name = safeName.toLower();
931 int i = 2;
932 while ( mModel->parameterDefinition( name ) )
933 {
934 name = safeName.toLower() + QString::number( i );
935 i += 1;
936 }
937 parameter->setName( name );
938}
939
940void QgsModelDesignerDialog::addAlgorithm( const QString &algorithmId, const QPointF &pos )
941{
942 std::unique_ptr< QgsProcessingAlgorithm > alg( QgsApplication::processingRegistry()->createAlgorithmById( algorithmId ) );
943 if ( !alg )
944 return;
945
946 QgsProcessingModelChildAlgorithm childAlg = QgsProcessingModelChildAlgorithm( algorithmId );
947 childAlg.setDescription( alg->displayName() );
948
949 if ( pos.isNull() )
950 {
951 childAlg.setPosition( getPositionForAlgorithmItem() );
952 }
953 else
954 {
955 childAlg.setPosition( pos );
956 }
957
958 childAlg.comment()->setPosition( childAlg.position() + QPointF( childAlg.size().width(), -1.5 * childAlg.size().height() ) );
959
960 const double outputOffsetX = childAlg.size().width();
961 double outputOffsetY = 1.5 * childAlg.size().height();
962
963 const QMap<QString, QgsProcessingModelOutput> childOutputs = childAlg.modelOutputs();
964 for ( auto out = childOutputs.constBegin(); out != childOutputs.constEnd(); ++out )
965 {
966 childAlg.modelOutput( out.key() ).setPosition( childAlg.position() + QPointF( outputOffsetX, outputOffsetY ) );
967 outputOffsetY += 1.5 * childAlg.modelOutput( out.key() ).size().height();
968 }
969
970 beginUndoCommand( tr( "Add Algorithm" ) );
971 mModel->addChildAlgorithm( childAlg );
972 repaintModel();
973 endUndoCommand();
974}
975
976void QgsModelDesignerDialog::addInput( const QString &parameterType, const QPointF &position )
977{
978 QPointF pos = position;
979 if ( !QgsApplication::processingRegistry()->parameterType( parameterType ) )
980 return;
981
982 std::unique_ptr< QgsProcessingParameterDefinition > newParam;
983 QString comment;
984
985 QgsProcessingParameterWidgetContext widgetContext = createWidgetContext();
986 QgsProcessingParameterDefinitionDialog dlg( parameterType, *mContext, widgetContext, nullptr, mModel.get() );
987 dlg.registerProcessingContextGenerator( this );
988 if ( !dlg.exec() )
989 return;
990
991 newParam.reset( dlg.createParameter() );
992 if ( !newParam )
993 return;
994
995 autoGenerateParameterName( newParam.get() );
996 dlg.comments();
997 comment = dlg.comments();
998
999 if ( pos.isNull() )
1000 {
1001 pos = getPositionForParameterItem();
1002 }
1003
1004 QgsProcessingModelParameter component = QgsProcessingModelParameter( newParam->name() );
1005 component.setDescription( newParam->name() );
1006 component.setPosition( pos );
1007
1008 component.comment()->setDescription( comment );
1009 component.comment()->setPosition( component.position() + QPointF( component.size().width(), -1.5 * component.size().height() ) );
1010
1011 beginUndoCommand( tr( "Add Model Input" ) );
1012 mModel->addModelParameter( newParam.release(), component );
1013 repaintModel();
1014 endUndoCommand();
1015}
1016
1017QgsProcessingAlgorithmWidget *QgsModelDesignerDialog::createExecutionWidget()
1018{
1020 if ( !dialogFactory )
1021 return nullptr; // should never happen
1022
1023 QgsProcessingAlgorithmWidget *widget = dialogFactory->createWidget( mModel->create(), false, this, QgsProcessingAlgorithmWidgetBase::WidgetFlags(), Qgis::DockableWidgetInitialState::ForceDocked );
1024 if ( !widget )
1025 return nullptr; // should never happen
1026
1027 widget->registerProcessingFeedbackGenerator( this );
1028 return widget;
1029}
1030
1031void QgsModelDesignerDialog::exportAsScriptAlgorithm()
1032{
1034 if ( !dialogFactory )
1035 return; // should never happen
1036
1037 QgsProcessingScriptEditorDialog *dialog = dialogFactory->createScriptEditorDialog();
1038 if ( !dialog )
1039 return; // should never happen
1040
1041 const QStringList codeLines = mModel->asPythonCode( QgsProcessing::PythonOutputType::PythonQgsProcessingAlgorithmSubclass, 4 );
1042
1043 dialog->codeEditor()->setText( codeLines.join( '\n' ) );
1044
1045 dialog->show();
1046}
1047
1048void QgsModelDesignerDialog::zoomIn()
1049{
1050 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
1051 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
1052 QgsSettings settings;
1053 const double factor = settings.value( u"/qgis/zoom_favor"_s, 2.0 ).toDouble();
1054 mView->scale( factor, factor );
1055 mView->centerOn( point );
1056}
1057
1058void QgsModelDesignerDialog::zoomOut()
1059{
1060 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
1061 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
1062 QgsSettings settings;
1063 const double factor = 1.0 / settings.value( u"/qgis/zoom_favor"_s, 2.0 ).toDouble();
1064 mView->scale( factor, factor );
1065 mView->centerOn( point );
1066}
1067
1068void QgsModelDesignerDialog::zoomActual()
1069{
1070 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
1071 mView->resetTransform();
1072 mView->scale( mScreenHelper->screenDpi() / 96, mScreenHelper->screenDpi() / 96 );
1073 mView->centerOn( point );
1074}
1075
1076void QgsModelDesignerDialog::zoomFull()
1077{
1078 QRectF totalRect = mView->scene()->itemsBoundingRect();
1079 totalRect.adjust( -10, -10, 10, 10 );
1080 mView->fitInView( totalRect, Qt::KeepAspectRatio );
1081}
1082
1083void QgsModelDesignerDialog::newModel()
1084{
1085 if ( !checkForUnsavedChanges() )
1086 return;
1087
1088 auto alg = std::make_unique<QgsProcessingModelAlgorithm>();
1089 alg->setProvider( QgsApplication::processingRegistry()->providerById( QgsProcessing::MODEL_PROVIDER_ID ) );
1090 setModel( alg.release() );
1091}
1092
1093void QgsModelDesignerDialog::openModel()
1094{
1095 if ( !checkForUnsavedChanges() )
1096 return;
1097
1098 QgsSettings settings;
1099 const QString lastModelDir = settings.value( u"Processing/lastModelsDir"_s, QDir::homePath() ).toString();
1100 const QString fileName = QFileDialog::getOpenFileName( this, tr( "Open Model" ), lastModelDir, tr( "Processing models (*.model3 *.MODEL3)" ) );
1101 if ( !fileName.isEmpty() )
1102 {
1103 settings.setValue( u"Processing/lastModelsDir"_s, QFileInfo( fileName ).absoluteDir().absolutePath() );
1104 loadModel( fileName );
1105 }
1106}
1107
1108void QgsModelDesignerDialog::exportToImage()
1109{
1110 QgsSettings settings;
1111 QString lastExportDir = settings.value( u"lastModelDesignerExportDir"_s, QDir::homePath(), QgsSettings::App ).toString();
1112
1113 QString filename = QFileDialog::getSaveFileName( this, tr( "Save Model as Image" ), lastExportDir, tr( "PNG files (*.png *.PNG)" ) );
1114 // return dialog focus on Mac
1115 activateWindow();
1116 raise();
1117 if ( filename.isEmpty() )
1118 return;
1119
1120 filename = QgsFileUtils::ensureFileNameHasExtension( filename, QStringList() << u"png"_s );
1121
1122 const QFileInfo saveFileInfo( filename );
1123 settings.setValue( u"lastModelDesignerExportDir"_s, saveFileInfo.absolutePath(), QgsSettings::App );
1124
1125 repaintModel( false );
1126
1127 QRectF totalRect = mView->scene()->itemsBoundingRect();
1128 totalRect.adjust( -10, -10, 10, 10 );
1129 const QRectF imageRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
1130
1131 QImage img( totalRect.width(), totalRect.height(), QImage::Format_ARGB32_Premultiplied );
1132 img.fill( Qt::white );
1133 QPainter painter;
1134 painter.setRenderHint( QPainter::Antialiasing );
1135 painter.begin( &img );
1136 mView->scene()->render( &painter, imageRect, totalRect );
1137 painter.end();
1138
1139 img.save( filename );
1140
1141 mMessageBar
1142 ->pushMessage( QString(), tr( "Successfully exported model as image to <a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( filename ).toString(), QDir::toNativeSeparators( filename ) ), Qgis::MessageLevel::Success, 0 );
1143 repaintModel( true );
1144}
1145
1146void QgsModelDesignerDialog::exportToPdf()
1147{
1148 QgsSettings settings;
1149 QString lastExportDir = settings.value( u"lastModelDesignerExportDir"_s, QDir::homePath(), QgsSettings::App ).toString();
1150
1151 QString filename = QFileDialog::getSaveFileName( this, tr( "Save Model as PDF" ), lastExportDir, tr( "PDF files (*.pdf *.PDF)" ) );
1152 // return dialog focus on Mac
1153 activateWindow();
1154 raise();
1155 if ( filename.isEmpty() )
1156 return;
1157
1158 filename = QgsFileUtils::ensureFileNameHasExtension( filename, QStringList() << u"pdf"_s );
1159
1160 const QFileInfo saveFileInfo( filename );
1161 settings.setValue( u"lastModelDesignerExportDir"_s, saveFileInfo.absolutePath(), QgsSettings::App );
1162
1163 repaintModel( false );
1164
1165 QRectF totalRect = mView->scene()->itemsBoundingRect();
1166 totalRect.adjust( -10, -10, 10, 10 );
1167 const QRectF printerRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
1168
1169 QPdfWriter pdfWriter( filename );
1170
1171 const double scaleFactor = 96 / 25.4; // based on 96 dpi sizes
1172
1173 QPageLayout pageLayout( QPageSize( totalRect.size() / scaleFactor, QPageSize::Millimeter ), QPageLayout::Portrait, QMarginsF( 0, 0, 0, 0 ) );
1174 pageLayout.setMode( QPageLayout::FullPageMode );
1175 pdfWriter.setPageLayout( pageLayout );
1176
1177 QPainter painter( &pdfWriter );
1178 mView->scene()->render( &painter, printerRect, totalRect );
1179 painter.end();
1180
1181 mMessageBar
1182 ->pushMessage( QString(), tr( "Successfully exported model as PDF to <a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( filename ).toString(), QDir::toNativeSeparators( filename ) ), Qgis::MessageLevel::Success, 0 );
1183 repaintModel( true );
1184}
1185
1186void QgsModelDesignerDialog::exportToSvg()
1187{
1188 QgsSettings settings;
1189 QString lastExportDir = settings.value( u"lastModelDesignerExportDir"_s, QDir::homePath(), QgsSettings::App ).toString();
1190
1191 QString filename = QFileDialog::getSaveFileName( this, tr( "Save Model as SVG" ), lastExportDir, tr( "SVG files (*.svg *.SVG)" ) );
1192 // return dialog focus on Mac
1193 activateWindow();
1194 raise();
1195 if ( filename.isEmpty() )
1196 return;
1197
1198 filename = QgsFileUtils::ensureFileNameHasExtension( filename, QStringList() << u"svg"_s );
1199
1200 const QFileInfo saveFileInfo( filename );
1201 settings.setValue( u"lastModelDesignerExportDir"_s, saveFileInfo.absolutePath(), QgsSettings::App );
1202
1203 repaintModel( false );
1204
1205 QRectF totalRect = mView->scene()->itemsBoundingRect();
1206 totalRect.adjust( -10, -10, 10, 10 );
1207 const QRectF svgRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
1208
1209 QSvgGenerator svg;
1210 svg.setFileName( filename );
1211 svg.setSize( QSize( totalRect.width(), totalRect.height() ) );
1212 svg.setViewBox( svgRect );
1213 svg.setTitle( mModel->displayName() );
1214
1215 QPainter painter( &svg );
1216 mView->scene()->render( &painter, svgRect, totalRect );
1217 painter.end();
1218
1219 mMessageBar
1220 ->pushMessage( QString(), tr( "Successfully exported model as SVG to <a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( filename ).toString(), QDir::toNativeSeparators( filename ) ), Qgis::MessageLevel::Success, 0 );
1221 repaintModel( true );
1222}
1223
1224void QgsModelDesignerDialog::exportAsPython()
1225{
1226 QgsSettings settings;
1227 QString lastExportDir = settings.value( u"lastModelDesignerExportDir"_s, QDir::homePath(), QgsSettings::App ).toString();
1228
1229 QString filename = QFileDialog::getSaveFileName( this, tr( "Save Model as Python Script" ), lastExportDir, tr( "Processing scripts (*.py *.PY)" ) );
1230 // return dialog focus on Mac
1231 activateWindow();
1232 raise();
1233 if ( filename.isEmpty() )
1234 return;
1235
1236 filename = QgsFileUtils::ensureFileNameHasExtension( filename, QStringList() << u"py"_s );
1237
1238 const QFileInfo saveFileInfo( filename );
1239 settings.setValue( u"lastModelDesignerExportDir"_s, saveFileInfo.absolutePath(), QgsSettings::App );
1240
1241 const QString text = mModel->asPythonCode( QgsProcessing::PythonOutputType::PythonQgsProcessingAlgorithmSubclass, 4 ).join( '\n' );
1242
1243 QFile outFile( filename );
1244 if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
1245 {
1246 return;
1247 }
1248 QTextStream fout( &outFile );
1249 fout << text;
1250 outFile.close();
1251
1252 mMessageBar
1253 ->pushMessage( QString(), tr( "Successfully exported model as Python script to <a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( filename ).toString(), QDir::toNativeSeparators( filename ) ), Qgis::MessageLevel::Success, 0 );
1254}
1255
1256void QgsModelDesignerDialog::repaintModel( bool showControls )
1257{
1258 auto scene = new QgsModelGraphicsScene( this );
1259 if ( !showControls )
1260 {
1261 scene->setFlag( QgsModelGraphicsScene::Flag::FlagHideControls );
1262 }
1263
1264 const bool showComments = QgsSettings().value( "/Processing/Modeler/ShowComments", true ).toBool();
1265 if ( !showComments )
1266 {
1267 scene->setFlag( QgsModelGraphicsScene::Flag::FlagHideComments );
1268 }
1269
1270 setModelScene( scene );
1271 scene->createItems( mModel.get(), *mContext );
1272 scene->updateBounds();
1273}
1274
1275void QgsModelDesignerDialog::toggleComments( bool show )
1276{
1277 QgsSettings().setValue( u"/Processing/Modeler/ShowComments"_s, show );
1278
1279 repaintModel( true );
1280}
1281
1282void QgsModelDesignerDialog::toggleFeatureCount( bool show )
1283{
1284 QgsSettings().setValue( u"/Processing/Modeler/ShowFeatureCount"_s, show );
1285
1286 repaintModel( true );
1287}
1288
1289void QgsModelDesignerDialog::updateWindowTitle()
1290{
1291 QString title = tr( "Model Designer" );
1292 if ( !mModel->name().isEmpty() )
1293 title = mModel->group().isEmpty() ? u"%1: %2"_s.arg( title, mModel->name() ) : u"%1: %2 - %3"_s.arg( title, mModel->group(), mModel->name() );
1294
1295 if ( isDirty() )
1296 title.prepend( '*' );
1297
1298 setWindowTitle( title );
1299}
1300
1301void QgsModelDesignerDialog::deleteSelected()
1302{
1303 QList<QgsModelComponentGraphicItem *> items = mScene->selectedComponentItems();
1304 if ( items.empty() )
1305 return;
1306
1307 if ( items.size() == 1 )
1308 {
1309 items.at( 0 )->deleteComponent();
1310 return;
1311 }
1312
1313 std::sort( items.begin(), items.end(), []( QgsModelComponentGraphicItem *p1, QgsModelComponentGraphicItem *p2 ) {
1314 // try to delete the easy stuff first, so comments, then outputs, as nothing will depend on these...
1315 // NOLINTBEGIN(bugprone-branch-clone)
1316
1317 // 1. comments
1318 if ( dynamic_cast<QgsModelCommentGraphicItem *>( p1 ) && dynamic_cast<QgsModelCommentGraphicItem *>( p2 ) )
1319 return false;
1320 else if ( dynamic_cast<QgsModelCommentGraphicItem *>( p1 ) )
1321 return true;
1322 else if ( dynamic_cast<QgsModelCommentGraphicItem *>( p2 ) )
1323 return false;
1324 // 2. group boxes
1325 else if ( dynamic_cast<QgsModelGroupBoxGraphicItem *>( p1 ) && dynamic_cast<QgsModelGroupBoxGraphicItem *>( p2 ) )
1326 return false;
1327 else if ( dynamic_cast<QgsModelGroupBoxGraphicItem *>( p1 ) )
1328 return true;
1329 else if ( dynamic_cast<QgsModelGroupBoxGraphicItem *>( p2 ) )
1330 return false;
1331 // 3. outputs
1332 else if ( dynamic_cast<QgsModelOutputGraphicItem *>( p1 ) && dynamic_cast<QgsModelOutputGraphicItem *>( p2 ) )
1333 return false;
1334 else if ( dynamic_cast<QgsModelOutputGraphicItem *>( p1 ) )
1335 return true;
1336 else if ( dynamic_cast<QgsModelOutputGraphicItem *>( p2 ) )
1337 return false;
1338 // 4. child algorithms
1339 else if ( dynamic_cast<QgsModelChildAlgorithmGraphicItem *>( p1 ) && dynamic_cast<QgsModelChildAlgorithmGraphicItem *>( p2 ) )
1340 return false;
1341 else if ( dynamic_cast<QgsModelChildAlgorithmGraphicItem *>( p1 ) )
1342 return true;
1343 else if ( dynamic_cast<QgsModelChildAlgorithmGraphicItem *>( p2 ) )
1344 return false;
1345 return false;
1346 // NOLINTEND(bugprone-branch-clone)
1347 } );
1348
1349
1350 beginUndoCommand( tr( "Delete Components" ) );
1351
1352 QVariant prevState = mModel->toVariant();
1353 mBlockUndoCommands++;
1354 mBlockRepaints = true;
1355 bool failed = false;
1356 while ( !items.empty() )
1357 {
1358 QgsModelComponentGraphicItem *toDelete = nullptr;
1359 for ( QgsModelComponentGraphicItem *item : items )
1360 {
1361 if ( item->canDeleteComponent() )
1362 {
1363 toDelete = item;
1364 break;
1365 }
1366 }
1367
1368 if ( !toDelete )
1369 {
1370 failed = true;
1371 break;
1372 }
1373
1374 toDelete->deleteComponent();
1375 items.removeAll( toDelete );
1376 }
1377
1378 if ( failed )
1379 {
1380 mModel->loadVariant( prevState );
1381 QMessageBox::warning(
1382 nullptr,
1383 QObject::tr( "Could not remove components" ),
1384 QObject::tr(
1385 "Components depend on the selected items.\n"
1386 "Try to remove them before trying deleting these components."
1387 )
1388 );
1389 mBlockUndoCommands--;
1390 mActiveCommand.reset();
1391 }
1392 else
1393 {
1394 mBlockUndoCommands--;
1395 endUndoCommand();
1396 }
1397
1398 mBlockRepaints = false;
1399 repaintModel();
1400}
1401
1402void QgsModelDesignerDialog::populateZoomToMenu()
1403{
1404 mGroupMenu->clear();
1405 for ( const QgsProcessingModelGroupBox &box : model()->groupBoxes() )
1406 {
1407 if ( QgsModelComponentGraphicItem *item = mScene->groupBoxItem( box.uuid() ) )
1408 {
1409 QAction *zoomAction = new QAction( box.description(), mGroupMenu );
1410 connect( zoomAction, &QAction::triggered, this, [this, item] {
1411 QRectF groupRect = item->mapToScene( item->boundingRect() ).boundingRect();
1412 groupRect.adjust( -10, -10, 10, 10 );
1413 mView->fitInView( groupRect, Qt::KeepAspectRatio );
1414 mView->centerOn( item );
1415 } );
1416 mGroupMenu->addAction( zoomAction );
1417 }
1418 }
1419}
1420
1421void QgsModelDesignerDialog::setPanelVisibility( bool hidden )
1422{
1423 const QList<QDockWidget *> docks = findChildren<QDockWidget *>();
1424 const QList<QTabBar *> tabBars = findChildren<QTabBar *>();
1425
1426 if ( hidden )
1427 {
1428 mPanelStatus.clear();
1429 //record status of all docks
1430 for ( QDockWidget *dock : docks )
1431 {
1432 mPanelStatus.insert( dock->windowTitle(), PanelStatus( dock->isVisible(), false ) );
1433 dock->setVisible( false );
1434 }
1435
1436 //record active dock tabs
1437 for ( QTabBar *tabBar : tabBars )
1438 {
1439 QString currentTabTitle = tabBar->tabText( tabBar->currentIndex() );
1440 mPanelStatus[currentTabTitle].isActive = true;
1441 }
1442 }
1443 else
1444 {
1445 //restore visibility of all docks
1446 for ( QDockWidget *dock : docks )
1447 {
1448 if ( mPanelStatus.contains( dock->windowTitle() ) )
1449 {
1450 dock->setVisible( mPanelStatus.value( dock->windowTitle() ).isVisible );
1451 }
1452 }
1453
1454 //restore previously active dock tabs
1455 for ( QTabBar *tabBar : tabBars )
1456 {
1457 //loop through all tabs in tab bar
1458 for ( int i = 0; i < tabBar->count(); ++i )
1459 {
1460 QString tabTitle = tabBar->tabText( i );
1461 if ( mPanelStatus.contains( tabTitle ) && mPanelStatus.value( tabTitle ).isActive )
1462 {
1463 tabBar->setCurrentIndex( i );
1464 }
1465 }
1466 }
1467 mPanelStatus.clear();
1468 }
1469}
1470
1471void QgsModelDesignerDialog::editHelp()
1472{
1473 QgsProcessingHelpEditorDialog dialog( this );
1474 dialog.setWindowTitle( tr( "Edit Model Help" ) );
1475 dialog.setAlgorithm( mModel.get() );
1476 if ( dialog.exec() )
1477 {
1478 beginUndoCommand( tr( "Edit Model Help" ) );
1479 mModel->setHelpContent( dialog.helpContent() );
1480 endUndoCommand();
1481 }
1482}
1483
1484void QgsModelDesignerDialog::runSelectedSteps()
1485{
1486 QSet<QString> children;
1487 const QList<QgsModelComponentGraphicItem *> items = mScene->selectedComponentItems();
1488 for ( QgsModelComponentGraphicItem *item : items )
1489 {
1490 if ( QgsProcessingModelChildAlgorithm *childAlgorithm = dynamic_cast<QgsProcessingModelChildAlgorithm *>( item->component() ) )
1491 {
1492 children.insert( childAlgorithm->childId() );
1493 }
1494 }
1495
1496 if ( children.isEmpty() )
1497 {
1498 mMessageBar->pushWarning( QString(), tr( "No steps are selected" ) );
1499 return;
1500 }
1501
1502 run( children );
1503}
1504
1505void QgsModelDesignerDialog::runFromChild( const QString &id )
1506{
1507 QSet<QString> children = mModel->dependentChildAlgorithms( id );
1508 children.insert( id );
1509 run( children );
1510}
1511
1512void QgsModelDesignerDialog::cancelRunningModel()
1513{
1514 if ( !mAlgorithmWidget )
1515 return;
1516
1517 // these checks are wrong - mAlgorithmWidget is a QPointer, and we explicitly want to check
1518 // if it gets deleted in the cancel/forceClose dance!
1519 // cppcheck-suppress nullPointerRedundantCheck
1520 mAlgorithmWidget->cancel();
1521 // cppcheck-suppress nullPointerRedundantCheck
1522 mAlgorithmWidget->forceClose();
1523
1524 //Stop tracking change to the previous dialog in the QPointer
1525 if ( mAlgorithmWidget )
1526 {
1527 // this is a work around for the MESSY ownership issues associated with the python subclass
1528 // of QgsProcessingAlgorithmWidget. We have to FORCE all widgets to be deleted prior
1529 // to destruction of this window, and we can't be sure that python will have actually
1530 // deleted the widget when we asked...
1531 mAlgorithmWidgetsToCleanUp << mAlgorithmWidget;
1532 }
1533 mAlgorithmWidget.clear();
1534}
1535
1536void QgsModelDesignerDialog::run( const QSet<QString> &childAlgorithmSubset )
1537{
1538 QStringList errors;
1539 const bool isValid = model()->validate( errors );
1540 if ( !isValid )
1541 {
1542 QMessageBox messageBox;
1543 messageBox.setWindowTitle( tr( "Model is Invalid" ) );
1544 messageBox.setIcon( QMessageBox::Icon::Warning );
1545 messageBox.setText( tr( "This model is not valid and contains one or more issues. Are you sure you want to run it in this state?" ) );
1546 messageBox.setStandardButtons( QMessageBox::StandardButton::Yes | QMessageBox::StandardButton::Cancel );
1547 messageBox.setDefaultButton( QMessageBox::StandardButton::Cancel );
1548
1549 QString errorString;
1550 for ( const QString &error : std::as_const( errors ) )
1551 {
1552 QString cleanedError = error;
1553 const thread_local QRegularExpression re( u"<[^>]*>"_s );
1554 cleanedError.replace( re, QString() );
1555 errorString += u"• %1\n"_s.arg( cleanedError );
1556 }
1557
1558 messageBox.setDetailedText( errorString );
1559 if ( messageBox.exec() == QMessageBox::StandardButton::Cancel )
1560 return;
1561 }
1562
1563 if ( !childAlgorithmSubset.isEmpty() )
1564 {
1565 for ( const QString &child : childAlgorithmSubset )
1566 {
1567 // has user previously run all requirements for this step?
1568 const QSet<QString> requirements = mModel->dependsOnChildAlgorithms( child );
1569 for ( const QString &requirement : requirements )
1570 {
1571 if ( !mLastResult.executedChildIds().contains( requirement ) )
1572 {
1573 QMessageBox messageBox;
1574 messageBox.setWindowTitle( tr( "Run Model" ) );
1575 messageBox.setIcon( QMessageBox::Icon::Warning );
1576 messageBox.setText( tr( "Prerequisite parts of this model have not yet been run (try running the full model first)." ) );
1577 messageBox.setStandardButtons( QMessageBox::StandardButton::Ok );
1578 messageBox.exec();
1579 return;
1580 }
1581 }
1582 }
1583 }
1584
1585 if ( mAlgorithmWidget && mAlgorithmWidget->isRunning() )
1586 {
1587 QMessageBox messageBox;
1588 messageBox.setIcon( QMessageBox::Icon::Warning );
1589 messageBox.setWindowTitle( tr( "Run Model" ) );
1590 messageBox.setText( tr( "This model is already running." ) );
1591 messageBox.setStandardButtons( QMessageBox::StandardButton::Cancel | QMessageBox::StandardButton::RestoreDefaults | QMessageBox::StandardButton::Ok );
1592
1593 QAbstractButton *buttonShowRunningAlg = messageBox.button( QMessageBox::StandardButton::Ok );
1594 buttonShowRunningAlg->setText( tr( "Show Progress" ) );
1595
1596 QAbstractButton *buttonReRun = messageBox.button( QMessageBox::StandardButton::RestoreDefaults );
1597 buttonReRun->setText( tr( "Cancel and Restart Model" ) );
1598
1599 int r = messageBox.exec();
1600
1601 switch ( r )
1602 {
1603 case QMessageBox::StandardButton::Cancel:
1604 return;
1605 case QMessageBox::StandardButton::RestoreDefaults:
1606 cancelRunningModel();
1607 break;
1608 case QMessageBox::StandardButton::Ok:
1609 mAlgorithmWidget->showWidget();
1610 return;
1611 default:
1612 break;
1613 }
1614 }
1615 else if ( mAlgorithmWidget )
1616 {
1617 // Close and create a new one
1618 mAlgorithmWidget->close();
1619 if ( mAlgorithmWidget )
1620 {
1621 // this is a work around for the MESSY ownership issues associated with the python subclass
1622 // of QgsProcessingAlgorithmWidget. We have to FORCE all widgets to be deleted prior
1623 // to destruction of this window, and we can't be sure that python will have actually
1624 // deleted the widget when we asked...
1625 mAlgorithmWidgetsToCleanUp << mAlgorithmWidget;
1626 }
1627 //Stop tracking change to the previous widget in the QPointer
1628 mAlgorithmWidget.clear();
1629 }
1630
1631 if ( !mAlgorithmWidget )
1632 {
1633 mAlgorithmWidget = createExecutionWidget();
1634 if ( !mAlgorithmWidget )
1635 return; // should not happen
1636
1637 mAlgorithmWidget->hideShortHelp();
1638 mAlgorithmWidget->setTitle( tr( "Run Model" ) );
1639
1640 mAlgorithmWidget->setLogLevel( Qgis::ProcessingLogLevel::ModelDebug );
1641 mAlgorithmWidget->setParameters( mModel->designerParameterValues() );
1642
1643 if ( !childAlgorithmSubset.isEmpty() )
1644 {
1645 mAlgorithmWidget->runButton()->setText( tr( "Run Subset" ) );
1646 mAlgorithmWidget->runButton()->setToolTip( tr( "Runs a subset of the child algorithms from this model" ) );
1647 }
1648
1649 connect( mAlgorithmWidget.get(), &QgsProcessingAlgorithmWidgetBase::algorithmAboutToRun, this, [this, childAlgorithmSubset]( QgsProcessingContext *context ) {
1650 if ( !childAlgorithmSubset.empty() )
1651 {
1652 // start from previous state
1653 auto modelConfig = std::make_unique<QgsProcessingModelInitialRunConfig>();
1654 modelConfig->setChildAlgorithmSubset( childAlgorithmSubset );
1655 modelConfig->setPreviouslyExecutedChildAlgorithms( mLastResult.executedChildIds() );
1656 modelConfig->setInitialChildInputs( mLastResult.rawChildInputs() );
1657 modelConfig->setInitialChildOutputs( mLastResult.rawChildOutputs() );
1658
1659 // add copies of layers from previous runs to context's layer store, so that they can be used
1660 // when running the subset
1661 const QMap<QString, QgsMapLayer *> previousOutputLayers = mLayerStore.temporaryLayerStore()->mapLayers();
1662 auto previousResultStore = std::make_unique<QgsMapLayerStore>();
1663 for ( auto it = previousOutputLayers.constBegin(); it != previousOutputLayers.constEnd(); ++it )
1664 {
1665 std::unique_ptr<QgsMapLayer> clone( it.value()->clone() );
1666 clone->setId( it.value()->id() );
1667 previousResultStore->addMapLayer( clone.release() );
1668 }
1669 previousResultStore->moveToThread( nullptr );
1670 modelConfig->setPreviousLayerStore( std::move( previousResultStore ) );
1671 context->setModelInitialRunConfig( std::move( modelConfig ) );
1672
1673 mScene->resetChildAlgorithmItems( childAlgorithmSubset );
1674
1675 // for all algorithms downstream of the subset which won't be re-run, flag their old results as outdated.
1676 for ( const QString &child : childAlgorithmSubset )
1677 {
1678 const QSet< QString > outdated = mModel->dependentChildAlgorithms( child );
1679 mScene->flagChildrenAsOutdated( outdated );
1680 mOutdatedChildResults.unite( outdated );
1681 }
1682 }
1683 else
1684 {
1685 // reset all child algorithm results
1686 mScene->resetChildAlgorithmItems();
1687 }
1688 } );
1689
1690 connect( mAlgorithmWidget, &QgsProcessingAlgorithmWidgetBase::algorithmFinished, this, [this]( bool, const QVariantMap &, QgsProcessingContext *context ) {
1691 // take child output layers
1692 mLayerStore.temporaryLayerStore()->removeAllMapLayers();
1693 mLayerStore.takeResultsFrom( *context );
1694
1695 mModel->setDesignerParameterValues( mAlgorithmWidget->createProcessingParameters( QgsProcessingParametersGenerator::Flag::SkipDefaultValueParameters ) );
1696 setLastRunResult( context->modelResult() );
1697 } );
1698 }
1699}
1700
1701void QgsModelDesignerDialog::showChildAlgorithmOutputs( const QString &childId )
1702{
1703 const bool isOutdated = mOutdatedChildResults.contains( childId );
1704 const QString childDescription = mModel->childAlgorithm( childId ).description();
1705
1706 const QgsProcessingModelChildAlgorithmResult result = mLastResult.childResults().value( childId );
1707 const QVariantMap childAlgorithmOutputs = result.outputs();
1708 if ( childAlgorithmOutputs.isEmpty() )
1709 {
1710 mMessageBar->pushWarning( QString(), tr( "No results are available for %1" ).arg( childDescription ) );
1711 return;
1712 }
1713
1714 const QgsProcessingAlgorithm *algorithm = mModel->childAlgorithm( childId ).algorithm();
1715 if ( !algorithm )
1716 {
1717 mMessageBar->pushCritical( QString(), tr( "Results cannot be shown for an invalid model component" ) );
1718 return;
1719 }
1720
1721 const QList<const QgsProcessingParameterDefinition *> outputParams = algorithm->destinationParameterDefinitions();
1722 if ( outputParams.isEmpty() )
1723 {
1724 // this situation should not arise in normal use, we don't show the action in this case
1725 QgsDebugError( "Cannot show results for algorithms with no outputs" );
1726 return;
1727 }
1728
1729 bool foundResults = false;
1730 for ( const QgsProcessingParameterDefinition *outputParam : outputParams )
1731 {
1732 const QVariant output = childAlgorithmOutputs.value( outputParam->name() );
1733 if ( !output.isValid() )
1734 continue;
1735
1736 if ( output.typeId() == QMetaType::Type::QString )
1737 {
1738 if ( QgsMapLayer *resultLayer = QgsProcessingUtils::mapLayerFromString( output.toString(), mLayerStore ) )
1739 {
1740 QgsDebugMsgLevel( u"Loading previous result for %1: %2"_s.arg( outputParam->name(), output.toString() ), 2 );
1741
1742 std::unique_ptr<QgsMapLayer> layer( resultLayer->clone() );
1743
1744 QString baseName;
1745 if ( outputParams.size() > 1 )
1746 baseName = tr( "%1 — %2" ).arg( childDescription, outputParam->name() );
1747 else
1748 baseName = childDescription;
1749
1750 // make name unique, so that's it's easy to see which is the most recent result.
1751 // (this helps when running the model multiple times.)
1752 QString name = baseName;
1753 int counter = 1;
1754 while ( !QgsProject::instance()->mapLayersByName( name ).empty() )
1755 {
1756 counter += 1;
1757 name = tr( "%1 (%2)" ).arg( baseName ).arg( counter );
1758 }
1759
1760 layer->setName( name );
1761
1762 QgsProject::instance()->addMapLayer( layer.release() );
1763 foundResults = true;
1764 }
1765 else
1766 {
1767 // should not happen in normal operation
1768 QgsDebugError( u"Could not load previous result for %1: %2"_s.arg( outputParam->name(), output.toString() ) );
1769 }
1770 }
1771 }
1772
1773 if ( !foundResults )
1774 {
1775 mMessageBar->pushWarning( QString(), tr( "No results are available for %1" ).arg( childDescription ) );
1776 return;
1777 }
1778 else if ( isOutdated )
1779 {
1780 mMessageBar->pushWarning( QString(), tr( "These results are outdated, and may not reflect the most recent model execution" ) );
1781 return;
1782 }
1783}
1784
1785void QgsModelDesignerDialog::showChildAlgorithmLog( const QString &childId )
1786{
1787 const QString childDescription = mModel->childAlgorithm( childId ).description();
1788
1790 // prefer to fetch the log from the item itself -- if we are currently mid-way through
1791 // running the model, it will have the LATEST log available
1792 if ( QgsModelChildAlgorithmGraphicItem *item = mScene->childAlgorithmItem( childId ) )
1793 {
1794 result = item->results();
1795 }
1796 if ( result.htmlLog().isEmpty() )
1797 {
1798 result = mLastResult.childResults().value( childId );
1799 }
1800
1801 if ( result.htmlLog().isEmpty() )
1802 {
1803 mMessageBar->pushWarning( QString(), tr( "No log is available for %1" ).arg( childDescription ) );
1804 return;
1805 }
1806
1807 QgsMessageViewer m( this, QgsGuiUtils::ModalDialogFlags, false );
1808 m.setWindowTitle( childDescription );
1809 m.setCheckBoxVisible( false );
1810 m.setMessageAsHtml( result.htmlLog() );
1811 m.exec();
1812}
1813
1814void QgsModelDesignerDialog::onItemFocused( QgsModelComponentGraphicItem *item )
1815{
1816 QgsProcessingParameterWidgetContext widgetContext = createWidgetContext();
1817 widgetContext.registerProcessingContextGenerator( this );
1818 widgetContext.setModelDesignerDialog( this );
1819
1820 if ( !item || !item->component() )
1821 {
1822 mConfigWidget->showComponentConfig( nullptr, *mContext, widgetContext );
1823 }
1824 else
1825 {
1826 mConfigWidget->showComponentConfig( item->component(), *mContext, widgetContext );
1827
1828 if ( auto childAlgorithmItem = qobject_cast< QgsModelChildAlgorithmGraphicItem * >( item ) )
1829 {
1830 connect( childAlgorithmItem, &QgsModelChildAlgorithmGraphicItem::rebuildConfigurationDockWidget, childAlgorithmItem, [this] {
1831 QgsProcessingParameterWidgetContext widgetContext = createWidgetContext();
1832 widgetContext.registerProcessingContextGenerator( this );
1833 widgetContext.setModelDesignerDialog( this );
1834 mConfigWidget->showComponentConfig( nullptr, *mContext, widgetContext );
1835 } );
1836 }
1837 }
1838}
1839
1840void QgsModelDesignerDialog::validate()
1841{
1842 QStringList issues;
1843 if ( model()->validate( issues ) )
1844 {
1845 mMessageBar->pushSuccess( QString(), tr( "Model is valid!" ) );
1846 }
1847 else
1848 {
1849 QgsMessageBarItem *messageWidget = QgsMessageBar::createMessage( QString(), tr( "Model is invalid!" ) );
1850 QPushButton *detailsButton = new QPushButton( tr( "Details" ) );
1851 connect( detailsButton, &QPushButton::clicked, detailsButton, [detailsButton, issues] {
1852 QgsMessageViewer *dialog = new QgsMessageViewer( detailsButton );
1853 dialog->setTitle( tr( "Model is Invalid" ) );
1854
1855 QString longMessage = tr( "<p>This model is not valid:</p>" ) + u"<ul>"_s;
1856 for ( const QString &issue : issues )
1857 {
1858 longMessage += u"<li>%1</li>"_s.arg( issue );
1859 }
1860 longMessage += "</ul>"_L1;
1861
1862 dialog->setMessage( longMessage, Qgis::StringFormat::Html );
1863 dialog->showMessage();
1864 } );
1865 messageWidget->layout()->addWidget( detailsButton );
1866 mMessageBar->clearWidgets();
1867 mMessageBar->pushWidget( messageWidget, Qgis::MessageLevel::Warning, 0 );
1868 }
1869}
1870
1871void QgsModelDesignerDialog::reorderInputs()
1872{
1873 QgsModelInputReorderDialog dlg( this );
1874 dlg.setModel( mModel.get() );
1875 if ( dlg.exec() )
1876 {
1877 const QStringList inputOrder = dlg.inputOrder();
1878 beginUndoCommand( tr( "Reorder Inputs" ) );
1879 mModel->setParameterOrder( inputOrder );
1880 endUndoCommand();
1881 }
1882}
1883
1884void QgsModelDesignerDialog::reorderOutputs()
1885{
1886 QgsModelOutputReorderDialog dlg( this );
1887 dlg.setModel( mModel.get() );
1888 if ( dlg.exec() )
1889 {
1890 const QStringList outputOrder = dlg.outputOrder();
1891 beginUndoCommand( tr( "Reorder Outputs" ) );
1892 mModel->setOutputOrder( outputOrder );
1893 mModel->setOutputGroup( dlg.outputGroup() );
1894 endUndoCommand();
1895 }
1896}
1897
1898bool QgsModelDesignerDialog::isDirty() const
1899{
1900 return mHasChanged && mUndoStack->index() != -1;
1901}
1902
1903void QgsModelDesignerDialog::fillInputsTree()
1904{
1905 const QIcon icon = QgsApplication::getThemeIcon( u"mIconModelInput.svg"_s );
1906 auto parametersItem = std::make_unique<QTreeWidgetItem>();
1907 parametersItem->setText( 0, tr( "Parameters" ) );
1908 QList<QgsProcessingParameterType *> available = QgsApplication::processingRegistry()->parameterTypes();
1909 std::sort( available.begin(), available.end(), []( const QgsProcessingParameterType *a, const QgsProcessingParameterType *b ) -> bool {
1910 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
1911 } );
1912
1913 for ( QgsProcessingParameterType *param : std::as_const( available ) )
1914 {
1916 {
1917 auto paramItem = std::make_unique<QTreeWidgetItem>();
1918 paramItem->setText( 0, param->name() );
1919 paramItem->setData( 0, Qt::UserRole, param->id() );
1920 paramItem->setIcon( 0, icon );
1921 paramItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled );
1922 paramItem->setToolTip( 0, param->description() );
1923 parametersItem->addChild( paramItem.release() );
1924 }
1925 }
1926 mInputsTreeWidget->addTopLevelItem( parametersItem.release() );
1927 mInputsTreeWidget->topLevelItem( 0 )->setExpanded( true );
1928}
1929
1930
1931//
1932// QgsModelChildDependenciesWidget
1933//
1934
1935QgsModelChildDependenciesWidget::QgsModelChildDependenciesWidget( QWidget *parent, QgsProcessingModelAlgorithm *model, const QString &childId )
1936 : QWidget( parent )
1937 , mModel( model )
1938 , mChildId( childId )
1939{
1940 QHBoxLayout *hl = new QHBoxLayout();
1941 hl->setContentsMargins( 0, 0, 0, 0 );
1942
1943 mLineEdit = new QLineEdit();
1944 mLineEdit->setEnabled( false );
1945 hl->addWidget( mLineEdit, 1 );
1946
1947 mToolButton = new QToolButton();
1948 mToolButton->setText( QString( QChar( 0x2026 ) ) );
1949 hl->addWidget( mToolButton );
1950
1951 setLayout( hl );
1952
1953 mLineEdit->setText( tr( "%1 dependencies selected" ).arg( 0 ) );
1954
1955 connect( mToolButton, &QToolButton::clicked, this, &QgsModelChildDependenciesWidget::showDialog );
1956}
1957
1958void QgsModelChildDependenciesWidget::setValue( const QList<QgsProcessingModelChildDependency> &value )
1959{
1960 const bool hasChanged = value != mValue;
1961 mValue = value;
1962
1963 updateSummaryText();
1964 if ( hasChanged )
1965 {
1966 emit changed();
1967 }
1968}
1969
1970void QgsModelChildDependenciesWidget::showDialog()
1971{
1972 const QList<QgsProcessingModelChildDependency> available = mModel->availableDependenciesForChildAlgorithm( mChildId );
1973
1974 QVariantList availableOptions;
1975 for ( const QgsProcessingModelChildDependency &dep : available )
1976 availableOptions << QVariant::fromValue( dep );
1977 QVariantList selectedOptions;
1978 for ( const QgsProcessingModelChildDependency &dep : mValue )
1979 selectedOptions << QVariant::fromValue( dep );
1980
1982 if ( panel )
1983 {
1984 QgsProcessingMultipleSelectionPanelWidget *widget = new QgsProcessingMultipleSelectionPanelWidget( availableOptions, selectedOptions );
1985 widget->setPanelTitle( tr( "Algorithm Dependencies" ) );
1986
1987 widget->setValueFormatter( [this]( const QVariant &v ) -> QString {
1988 const QgsProcessingModelChildDependency dep = v.value<QgsProcessingModelChildDependency>();
1989
1990 const QString description = mModel->childAlgorithm( dep.childId ).description();
1991 if ( dep.conditionalBranch.isEmpty() )
1992 return description;
1993 else
1994 return tr( "Condition “%1” from algorithm “%2”" ).arg( dep.conditionalBranch, description );
1995 } );
1996
1997 connect( widget, &QgsProcessingMultipleSelectionPanelWidget::selectionChanged, this, [this, widget]() {
1998 QList<QgsProcessingModelChildDependency> res;
1999 for ( const QVariant &v : widget->selectedOptions() )
2000 {
2001 res << v.value<QgsProcessingModelChildDependency>();
2002 }
2003 setValue( res );
2004 } );
2005 connect( widget, &QgsProcessingMultipleSelectionPanelWidget::acceptClicked, widget, &QgsPanelWidget::acceptPanel );
2006 panel->openPanel( widget );
2007 }
2008}
2009
2010void QgsModelChildDependenciesWidget::updateSummaryText()
2011{
2012 mLineEdit->setText( tr( "%n dependencies selected", nullptr, mValue.count() ) );
2013}
2014
static QString version()
Version string.
Definition qgis.cpp:682
@ ExposeToModeler
Is this parameter available in the modeler. Is set to on by default.
Definition qgis.h:4012
@ Warning
Warning message.
Definition qgis.h:162
@ Success
Used for reporting a successful operation.
Definition qgis.h:164
@ Html
HTML message.
Definition qgis.h:177
@ ForceDocked
Force the widget to be docked.
Definition qgis.h:7118
@ ModelDebug
Model debug level logging. Includes verbose logging and other outputs useful for debugging models.
Definition qgis.h:3910
static QgsProcessingRegistry * processingRegistry()
Returns the application's processing registry, used for managing processing providers,...
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
A QDockWidget subclass with more fine-grained control over how the widget is closed or opened.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
static QString ensureFileNameHasExtension(const QString &fileName, const QStringList &extensions)
Ensures that a fileName ends with an extension from the provided list of extensions.
A singleton class containing various registry and other global members related to GUI classes.
Definition qgsgui.h:71
static QSize iconSize(Qgis::UserInterfaceIconType iconType=Qgis::UserInterfaceIconType::MainWindowToolbar)
Returns the desired size for user interface icons.
Definition qgsgui.cpp:514
static QgsProcessingGuiRegistry * processingGuiRegistry()
Returns the global processing gui registry, used for registering the GUI behavior of processing algor...
Definition qgsgui.cpp:170
void applicationStyleSheetChanged(const QString &styleSheet)
Emitted whenever the application style sheet is changed.
static QString applicationStyleSheet()
Returns the application style sheet.
Definition qgsgui.cpp:399
static QgsGui * instance()
Returns a pointer to the singleton instance.
Definition qgsgui.cpp:94
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:225
Base class for all map layer types.
Definition qgsmaplayer.h:84
Represents an item shown within a QgsMessageBar widget.
A bar for displaying non-blocking messages to the user.
static QgsMessageBarItem * createMessage(const QString &text, QWidget *parent=nullptr)
Creates message bar item widget containing a message text to be displayed on the bar.
A generic message view for displaying QGIS messages.
void setMessage(const QString &message, Qgis::StringFormat format) override
Sets message, it won't be displayed until.
void setTitle(const QString &title) override
Sets title for the messages.
void showMessage(bool blocking=true) override
display the message to the user and deletes itself
A dockable panel widget stack which allows users to specify the properties of a Processing model comp...
Model designer view tool for panning a model.
Base class for any widget that can be shown as an inline panel.
void openPanel(QgsPanelWidget *panel)
Open a panel or dialog depending on dock mode setting If dock mode is true this method will emit the ...
void acceptPanel()
Accept the panel.
static QgsPanelWidget * findParentPanel(QWidget *widget)
Traces through the parents of a widget to find if it is contained within a QgsPanelWidget widget.
Abstract base class for processing algorithms.
Contains information about the context in which a processing algorithm is executed.
QgsProcessingModelResult modelResult() const
Returns the model results, populated when the context is used to run a model algorithm.
A factory for creating widgets and dialogs for Processing components.
virtual QgsProcessingScriptEditorDialog * createScriptEditorDialog(const QString &filePath=QString(), QWidget *parent=nullptr)=0
Creates a new script editor dialog.
virtual QgsProcessingAlgorithmWidget * createWidget(QgsProcessingAlgorithm *algorithm, bool inPlace=false, QMainWindow *parent=nullptr, QgsProcessingAlgorithmWidgetBase::WidgetFlags flags=QgsProcessingAlgorithmWidgetBase::WidgetFlags(), Qgis::DockableWidgetInitialState initialState=Qgis::DockableWidgetInitialState::RestorePreviousState)=0
Creates a new widget for executing the specified algorithm.
Base class for providing feedback from a processing algorithm.
QgsProcessingDialogFactory * dialogFactory()
Returns the application's processing dialog factory, if set.
QgsProcessingParameterWidgetContext createWidgetContext() override
Register a Processing widget context.
Encapsulates the results of running a child algorithm within a model.
QString htmlLog() const
Returns the HTML formatted contents of logged messages which occurred while running the child.
QVariantMap outputs() const
Returns the outputs generated by the child algorithm.
void childResultReported(const QString &childId, const QgsProcessingModelChildAlgorithmResult &result)
Emitted when the result of a child algorithm has been reported.
Encapsulates the results of running a Processing model.
QMap< QString, QgsProcessingModelChildAlgorithmResult > childResults() const
Returns the map of child algorithm results.
A dialog which allows users to specify the properties of a Processing parameter.
Base class for the definition of processing parameters.
QString description() const
Returns the description for the parameter.
void setName(const QString &name)
Sets the name of the parameter.
Makes metadata of processing parameters available.
Contains settings which reflect the context in which a Processing parameter widget is shown.
void setModelDesignerDialog(QgsModelDesignerDialog *dialog)
Sets the associated model designer dialog, if applicable.
void setModel(QgsProcessingModelAlgorithm *model)
Sets the model which the parameter widget is associated with.
void registerProcessingContextGenerator(QgsProcessingContextGenerator *generator)
Registers a Processing context generator class that will be used to retrieve a Processing context for...
@ SkipDefaultValueParameters
Parameters which are unchanged from their default values should not be included.
QList< QgsProcessingParameterType * > parameterTypes() const
Returns a list with all known parameter types.
A proxy model for providers and algorithms shown within the Processing toolbox.
@ ShowKnownIssues
Show algorithms with known issues (hidden by default).
@ Modeler
Filters out any algorithms and content which should not be shown in the modeler.
static QStringList modelFolders()
Returns the list of locations for reading Processing model files.
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers=true, QgsProcessingUtils::LayerHint typeHint=QgsProcessingUtils::LayerHint::UnknownType, QgsProcessing::LayerOptionsFlags flags=QgsProcessing::LayerOptionsFlags())
Interprets a string as a map layer within the supplied context.
static const QString MODEL_PROVIDER_ID
Constant used for the model provider's ID.
@ PythonQgsProcessingAlgorithmSubclass
Full Python QgsProcessingAlgorithm subclass.
static const QString PROJECT_PROVIDER_ID
Constant used for the project model provider's ID.
Describes the version of a project.
QString text() const
Returns a string representation of the version.
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsMapLayer * addMapLayer(QgsMapLayer *mapLayer, bool addToLegend=true, bool takeOwnership=true)
Add a layer to the map of loaded layers.
void setDirty(bool b=true)
Flag the project as dirty (modified).
A utility class for dynamic handling of changes to screen properties.
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 remove(const QString &key, QgsSettings::Section section=QgsSettings::NoSection)
Removes the setting key and any sub-settings of key in a section.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
void scopeChanged()
Emitted when the user has modified a scope using the widget.
void addDockWidget(QMainWindow *window, Qt::DockWidgetArea area, QDockWidget *dockwidget)
Add a dock widget to a main window.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into allowing algorithms to be written in pure substantial changes are required in order to port existing x Processing algorithms for QGIS x The most significant changes are outlined not GeoAlgorithm For algorithms which operate on features one by consider subclassing the QgsProcessingFeatureBasedAlgorithm class This class allows much of the boilerplate code for looping over features from a vector layer to be bypassed and instead requires implementation of a processFeature method Ensure that your algorithm(or algorithm 's parent class) implements the new pure virtual createInstance(self) call
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71
constexpr QObjectUniquePtr< Tp > make_qobject_unique(Args &&...args)
Create an object owned by a QObjectUniquePtr.