54#include <QActionGroup>
57#include <QKeySequence>
63#include <QSvgGenerator>
70#include "moc_qgsmodeldesignerdialog.cpp"
72using namespace Qt::StringLiterals;
77QgsModelerToolboxModel::QgsModelerToolboxModel( QObject *parent )
81Qt::ItemFlags QgsModelerToolboxModel::flags(
const QModelIndex &index )
const
83 Qt::ItemFlags f = QgsProcessingToolboxProxyModel::flags( index );
84 const QModelIndex sourceIndex = mapToSource( index );
85 if ( toolboxModel()->isAlgorithm( sourceIndex ) || toolboxModel()->isParameter( sourceIndex ) )
87 f = f | Qt::ItemIsDragEnabled;
92Qt::DropActions QgsModelerToolboxModel::supportedDragActions()
const
94 return Qt::CopyAction;
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 ) )
112 setAttribute( Qt::WA_DeleteOnClose );
113 setDockOptions( dockOptions() | QMainWindow::GroupedDragging );
114 setWindowFlags( Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint );
118 mModel = std::make_unique<QgsProcessingModelAlgorithm>();
121 mUndoStack =
new QUndoStack(
this );
122 connect( mUndoStack, &QUndoStack::indexChanged,
this, [
this] {
123 if ( mIgnoreUndoStackChanges )
126 mBlockUndoCommands++;
127 updateVariablesGui();
128 mGroupEdit->setText( mModel->group() );
129 mNameEdit->setText( mModel->displayName() );
130 mBlockUndoCommands--;
135 mConfigWidgetDock->setWindowTitle( tr(
"Configuration" ) );
136 mConfigWidgetDock->setObjectName( u
"ModelConfigDock"_s );
139 mConfigWidgetDock->setWidget( mConfigWidget );
140 mConfigWidgetDock->setFeatures( QDockWidget::NoDockWidgetFeatures );
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 );
148 mToolboxTree->header()->setVisible(
false );
149 mToolboxSearchEdit->setShowSearchIcon(
true );
150 mToolboxSearchEdit->setPlaceholderText( tr(
"Search…" ) );
151 connect( mToolboxSearchEdit, &QgsFilterLineEdit::textChanged, mToolboxTree, &QgsProcessingToolboxTreeView::setFilterString );
153 mInputsTreeWidget->header()->setVisible(
false );
154 mInputsTreeWidget->setAlternatingRowColors(
true );
155 mInputsTreeWidget->setDragDropMode( QTreeWidget::DragOnly );
156 mInputsTreeWidget->setDropIndicatorShown(
true );
158 mNameEdit->setPlaceholderText( tr(
"Enter model name here" ) );
159 mGroupEdit->setPlaceholderText( tr(
"Enter group name here" ) );
162 mMessageBar->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Fixed );
163 mainLayout->insertWidget( 0, mMessageBar );
165 mView->setAcceptDrops(
true );
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 );
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 );
197 mView->snapper()->setSnapToGrid( mActionSnappingEnabled->isChecked() );
199 connect( mView, &QgsModelGraphicsView::itemFocused,
this, &QgsModelDesignerDialog::onItemFocused );
201 connect( mActionSelectAll, &QAction::triggered,
this, [
this] { mScene->selectAll(); } );
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() )
207 for (
const auto &title : docksTitle )
209 mPanelStatus.insert( title, PanelStatus(
true, docksActive.contains( title ) ) );
212 mActionHidePanels->setChecked( !docksTitle.isEmpty() );
213 connect( mActionHidePanels, &QAction::toggled,
this, &QgsModelDesignerDialog::setPanelVisibility );
215 mUndoAction = mUndoStack->createUndoAction(
this );
217 mUndoAction->setShortcuts( QKeySequence::Undo );
218 mRedoAction = mUndoStack->createRedoAction(
this );
220 mRedoAction->setShortcuts( QKeySequence::Redo );
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 );
229 mGroupMenu =
new QMenu( tr(
"Zoom To" ),
this );
230 mMenuView->insertMenu( mActionZoomIn, mGroupMenu );
231 connect( mGroupMenu, &QMenu::aboutToShow,
this, &QgsModelDesignerDialog::populateZoomToMenu );
235 mActionCut =
new QAction( tr(
"Cu&t" ),
this );
236 mActionCut->setShortcuts( QKeySequence::Cut );
237 mActionCut->setStatusTip( tr(
"Cut" ) );
239 connect( mActionCut, &QAction::triggered,
this, [
this] { mView->copySelectedItems( QgsModelGraphicsView::ClipboardCut ); } );
241 mActionCopy =
new QAction( tr(
"&Copy" ),
this );
242 mActionCopy->setShortcuts( QKeySequence::Copy );
243 mActionCopy->setStatusTip( tr(
"Copy" ) );
245 connect( mActionCopy, &QAction::triggered,
this, [
this] { mView->copySelectedItems( QgsModelGraphicsView::ClipboardCopy ); } );
247 mActionPaste =
new QAction( tr(
"&Paste" ),
this );
248 mActionPaste->setShortcuts( QKeySequence::Paste );
249 mActionPaste->setStatusTip( tr(
"Paste" ) );
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 );
257 mAlgorithmsModel =
new QgsModelerToolboxModel(
this );
258 mToolboxTree->setToolboxProxyModel( mAlgorithmsModel );
261 if ( settings.
value( u
"Processing/Configuration/SHOW_ALGORITHMS_KNOWN_ISSUES"_s,
false ).toBool() )
265 mToolboxTree->setFilters( filters );
266 mToolboxTree->setDragDropMode( QTreeWidget::DragOnly );
267 mToolboxTree->setDropIndicatorShown(
true );
269 connect( mView, &QgsModelGraphicsView::algorithmDropped,
this, [
this](
const QString &algorithmId,
const QPointF &pos ) { addAlgorithm( algorithmId, pos ); } );
270 connect( mView, &QgsModelGraphicsView::inputDropped,
this, &QgsModelDesignerDialog::addInput );
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() );
279 connect( mInputsTreeWidget, &QgsModelDesignerInputsTreeWidget::doubleClicked,
this, [
this](
const QModelIndex & ) {
280 const QString parameterType = mInputsTreeWidget->currentItem()->data( 0, Qt::UserRole ).toString();
281 addInput( parameterType, QPointF() );
285 QShortcut *ctrlEquals =
new QShortcut( QKeySequence( u
"Ctrl+="_s ),
this );
286 connect( ctrlEquals, &QShortcut::activated,
this, &QgsModelDesignerDialog::zoomIn );
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 );
295 tabifyDockWidget( mUndoDock, mPropertiesDock );
296 tabifyDockWidget( mVariablesDock, mPropertiesDock );
297 mPropertiesDock->raise();
298 tabifyDockWidget( mInputsDock, mAlgorithmsDock );
299 mInputsDock->raise();
304 beginUndoCommand( tr(
"Change Model Variables" ) );
305 mModel->setVariables( mVariablesEditor->variablesInActiveScope() );
309 connect( mNameEdit, &QLineEdit::textChanged,
this, [
this](
const QString &name ) {
312 beginUndoCommand( tr(
"Change Model Name" ), QString(), QgsModelUndoCommand::CommandOperation::NameChanged );
313 mModel->setName( name );
318 connect( mGroupEdit, &QLineEdit::textChanged,
this, [
this](
const QString &group ) {
321 beginUndoCommand( tr(
"Change Model Group" ), QString(), QgsModelUndoCommand::CommandOperation::GroupChanged );
322 mModel->setGroup( group );
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 );
337 mActionShowComments->setChecked( settings.
value( u
"/Processing/Modeler/ShowComments"_s,
true ).toBool() );
338 connect( mActionShowComments, &QAction::toggled,
this, &QgsModelDesignerDialog::toggleComments );
340 mActionShowFeatureCount->setChecked( settings.
value( u
"/Processing/Modeler/ShowFeatureCount"_s,
true ).toBool() );
341 connect( mActionShowFeatureCount, &QAction::toggled,
this, &QgsModelDesignerDialog::toggleFeatureCount );
344 mPanTool->setAction( mActionPan );
346 mToolsActionGroup->addAction( mActionPan );
347 connect( mActionPan, &QAction::triggered, mPanTool, [
this] { mView->setTool( mPanTool ); } );
352 mSelectTool->setAction( mActionSelectMoveItem );
354 mToolsActionGroup->addAction( mActionSelectMoveItem );
355 connect( mActionSelectMoveItem, &QAction::triggered, mSelectTool, [
this] { mView->setTool( mSelectTool ); } );
357 mView->setTool( mSelectTool );
360 connect( mView, &QgsModelGraphicsView::macroCommandStarted,
this, [
this](
const QString &text ) {
361 mIgnoreUndoStackChanges++;
362 mUndoStack->beginMacro( text );
363 mIgnoreUndoStackChanges--;
365 connect( mView, &QgsModelGraphicsView::macroCommandEnded,
this, [
this] {
366 mIgnoreUndoStackChanges++;
367 mUndoStack->endMacro();
368 mIgnoreUndoStackChanges--;
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(); } );
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" ) );
381 beginUndoCommand( tr(
"Add Group Box" ) );
382 model()->addGroupBox( group );
390 restoreState( settings.
value( u
"ModelDesigner/state"_s, QByteArray(),
QgsSettings::App ).toByteArray() );
395QgsModelDesignerDialog::~QgsModelDesignerDialog()
397 if ( mAlgorithmWidget )
399 delete mAlgorithmWidget;
401 for (
const QPointer<QgsProcessingAlgorithmWidget> &widget : std::as_const( mAlgorithmWidgetsToCleanUp ) )
414 if ( !mPanelStatus.isEmpty() )
416 QStringList docksTitle;
417 QStringList docksActive;
419 for (
const auto &panel : mPanelStatus.toStdMap() )
421 if ( panel.second.isVisible )
422 docksTitle << panel.first;
423 if ( panel.second.isActive )
424 docksActive << panel.first;
438 mIgnoreUndoStackChanges++;
441void QgsModelDesignerDialog::closeEvent( QCloseEvent *event )
443 if ( checkForUnsavedChanges() )
454void QgsModelDesignerDialog::beginUndoCommand(
const QString &text,
const QString &
id, QgsModelUndoCommand::CommandOperation operation )
456 if ( mBlockUndoCommands || !mUndoStack )
459 if ( mActiveCommand )
464 mActiveCommand = std::make_unique<QgsModelUndoCommand>( mModel.get(), text,
id );
468 mActiveCommand = std::make_unique<QgsModelUndoCommand>( mModel.get(), text, operation );
472void QgsModelDesignerDialog::endUndoCommand()
474 if ( mBlockUndoCommands || !mActiveCommand || !mUndoStack )
477 mActiveCommand->saveAfterState();
478 mIgnoreUndoStackChanges++;
479 mUndoStack->push( mActiveCommand.release() );
480 mIgnoreUndoStackChanges--;
484void QgsModelDesignerDialog::abortUndoCommand()
486 if ( mActiveCommand )
487 mActiveCommand->setObsolete(
true );
490QgsProcessingModelAlgorithm *QgsModelDesignerDialog::model()
495void QgsModelDesignerDialog::setModel( QgsProcessingModelAlgorithm *model )
497 mModel.reset( model );
499 mGroupEdit->setText( mModel->group() );
500 mNameEdit->setText( mModel->displayName() );
501 repaintModel(
true );
502 updateVariablesGui();
504 const QString modelQgisVersion = mModel->modelQgisVersion();
505 handleVersionMismatch( modelQgisVersion );
509 mIgnoreUndoStackChanges++;
511 mIgnoreUndoStackChanges--;
517 QTimer::singleShot( 100,
this, [
this] { zoomFull(); } );
520void QgsModelDesignerDialog::loadModel(
const QString &path )
522 std::unique_ptr< QgsProcessingModelAlgorithm > alg = QgsProcessingModelAlgorithm::loadModel( path );
525 QMessageBox::critical(
527 QObject::tr(
"Open Model" ),
529 "The selected model could not be loaded.\n"
530 "See the log for more information."
536 setModel( alg.release() );
539void QgsModelDesignerDialog::handleVersionMismatch(
const QString &modelVersion )
const
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."
553 .arg( thisVersion.text() );
554 mMessageBar->pushInfo( QString(), message );
556 else if ( thisVersion > fileVersion )
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."
563 .arg( fileVersion.
text(), thisVersion.text() );
564 mMessageBar->pushInfo( QString(), message );
566 else if ( thisVersion < fileVersion )
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."
572 .arg( fileVersion.
text() );
574 mMessageBar->pushWarning( QString(), message );
582void QgsModelDesignerDialog::setModelScene( QgsModelGraphicsScene *scene )
584 QgsModelGraphicsScene *oldScene = mScene;
587 mScene->setParent(
this );
588 mScene->setLastRunResult( mLastResult, mLayerStore );
589 mScene->setModel( mModel.get() );
590 mScene->setMessageBar( mMessageBar );
591 mScene->registerWidgetContextGenerator(
this );
594 const bool showFeatureCount = settings.
value( u
"/Processing/Modeler/ShowFeatureCount"_s,
true ).toBool();
595 if ( !showFeatureCount )
596 mScene->setFlag( QgsModelGraphicsScene::FlagHideFeatureCount );
598 mView->setModelScene( mScene );
600 mSelectTool->resetCache();
601 mSelectTool->setScene( mScene );
603 connect( mScene, &QgsModelGraphicsScene::rebuildRequired,
this, [
this] {
604 if ( mBlockRepaints )
608 mScene->flagChildrenAsOutdated( mOutdatedChildResults );
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 );
618 oldScene->deleteLater();
621QgsModelGraphicsScene *QgsModelDesignerDialog::modelScene()
628 auto result = std::make_unique< QgsProcessingModelFeedback >();
629 mScene->setupFeedbackConnections( result.get() );
631 mOutdatedChildResults.remove( childId );
634 return result.release();
646void QgsModelDesignerDialog::activate()
650 setWindowState( windowState() & ~Qt::WindowMinimized );
656 return mContext.get();
659void QgsModelDesignerDialog::updateVariablesGui()
661 mBlockUndoCommands++;
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 )
667 variablesScope->setVariable( it.key(), it.value() );
670 variablesContext.
appendScope( variablesScope.release() );
671 mVariablesEditor->setContext( &variablesContext );
672 mVariablesEditor->setEditableScopeIndex( 0 );
674 mBlockUndoCommands--;
677void QgsModelDesignerDialog::setDirty(
bool dirty )
681 if ( mAlgorithmWidget )
683 if (
QgsMessageBar *messageBar = mAlgorithmWidget->messageBar() )
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() )
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 );
696 QAbstractButton *buttonReRun = messageBox.button( QMessageBox::StandardButton::RestoreDefaults );
697 buttonReRun->setText( tr(
"Terminate and Reload" ) );
699 int r = messageBox.exec();
703 case QMessageBox::StandardButton::Cancel:
705 case QMessageBox::StandardButton::RestoreDefaults:
711 cancelRunningModel();
714 messageBarItem->layout()->addWidget( reloadButton );
720bool QgsModelDesignerDialog::validateSave( SaveAction action )
724 case QgsModelDesignerDialog::SaveAction::SaveAsFile:
726 case QgsModelDesignerDialog::SaveAction::SaveInProject:
727 if ( mNameEdit->text().trimmed().isEmpty() )
729 mMessageBar->pushWarning( QString(), tr(
"Please enter a model name before saving" ) );
738bool QgsModelDesignerDialog::checkForUnsavedChanges()
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 );
746 case QMessageBox::Save:
747 return saveModel(
false );
749 case QMessageBox::Discard:
764 mLastResult.mergeWith( result );
766 mScene->setLastRunResult( mLastResult, mLayerStore );
769void QgsModelDesignerDialog::setModelName(
const QString &name )
771 mNameEdit->setText( name );
774void QgsModelDesignerDialog::saveInProject()
776 if ( !validateSave( SaveAction::SaveInProject ) )
779 mModel->setSourceFilePath( QString() );
782 if ( !projectProvider )
785 projectProvider->addModel( *mModel );
795bool QgsModelDesignerDialog::saveModel(
bool saveAs )
797 if ( !validateSave( SaveAction::SaveAsFile ) )
800 const bool modelNameMatchedFileName = mModel->modelNameMatchesFilePath();
802 if ( !mModel->sourceFilePath().isEmpty() && !saveAs )
804 fileName = mModel->sourceFilePath();
809 if ( !mModel->sourceFilePath().isEmpty() )
811 initialPath = mModel->sourceFilePath();
813 else if ( !mModel->name().isEmpty() )
822 fileName = QFileDialog::getSaveFileName(
this, tr(
"Save Model" ), initialPath, tr(
"Processing models (*.model3 *.MODEL3)" ) );
823 if ( fileName.isEmpty() )
829 mModel->setSourceFilePath( fileName );
831 if ( mModel->name().isEmpty() || mModel->name() == tr(
"model" ) )
833 setModelName( QFileInfo( fileName ).baseName() );
835 else if ( saveAs && modelNameMatchedFileName )
839 setModelName( QFileInfo( fileName ).baseName() );
843 if ( !mModel->toFile( fileName ) )
847 QMessageBox::warning(
this, tr(
"Save Model" ), tr(
"Unable to save edits (probably you do not have permission to write to this location)." ) );
851 QMessageBox::warning(
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."
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 );
873QPointF QgsModelDesignerDialog::getPositionForParameterItem()
const
875 constexpr double MARGIN = 20;
876 constexpr double BOX_WIDTH = 200;
877 constexpr double BOX_HEIGHT = 80;
880 const QMap<QString, QgsProcessingModelParameter> components = mModel->parameterComponents();
881 if ( !components.isEmpty() )
884 for (
auto it = components.constBegin(); it != components.constEnd(); ++it )
886 maxX = std::max( maxX, it->position().x() );
888 newX = MARGIN + BOX_WIDTH + maxX;
892 newX = MARGIN + BOX_WIDTH / 2.0;
894 return QPointF( newX, MARGIN + BOX_HEIGHT / 2.0 );
897QPointF QgsModelDesignerDialog::getPositionForAlgorithmItem()
const
899 constexpr double MARGIN = 20;
900 constexpr double BOX_WIDTH = 200;
901 constexpr double BOX_HEIGHT = 80;
903 const QMap<QString, QgsProcessingModelChildAlgorithm> algorithms = mModel->childAlgorithms();
907 if ( !algorithms.isEmpty() )
911 for (
auto it = algorithms.constBegin(); it != algorithms.constEnd(); ++it )
913 maxX = std::max( maxX, it->position().x() );
914 maxY = std::max( maxY, it->position().y() );
916 newX = MARGIN + BOX_WIDTH + maxX;
917 newY = MARGIN + BOX_HEIGHT + maxY;
921 newX = MARGIN + BOX_WIDTH / 2.0;
922 newY = MARGIN * 2 + BOX_HEIGHT + BOX_HEIGHT / 2.0;
924 return QPointF( newX, newY );
929 const QString safeName = QgsProcessingModelAlgorithm::safeName( parameter->
description() );
930 QString name = safeName.toLower();
932 while ( mModel->parameterDefinition( name ) )
934 name = safeName.toLower() + QString::number( i );
940void QgsModelDesignerDialog::addAlgorithm(
const QString &algorithmId,
const QPointF &pos )
946 QgsProcessingModelChildAlgorithm childAlg = QgsProcessingModelChildAlgorithm( algorithmId );
947 childAlg.setDescription( alg->displayName() );
951 childAlg.setPosition( getPositionForAlgorithmItem() );
955 childAlg.setPosition( pos );
958 childAlg.comment()->setPosition( childAlg.position() + QPointF( childAlg.size().width(), -1.5 * childAlg.size().height() ) );
960 const double outputOffsetX = childAlg.size().width();
961 double outputOffsetY = 1.5 * childAlg.size().height();
963 const QMap<QString, QgsProcessingModelOutput> childOutputs = childAlg.modelOutputs();
964 for (
auto out = childOutputs.constBegin(); out != childOutputs.constEnd(); ++out )
966 childAlg.modelOutput( out.key() ).setPosition( childAlg.position() + QPointF( outputOffsetX, outputOffsetY ) );
967 outputOffsetY += 1.5 * childAlg.modelOutput( out.key() ).size().height();
970 beginUndoCommand( tr(
"Add Algorithm" ) );
971 mModel->addChildAlgorithm( childAlg );
976void QgsModelDesignerDialog::addInput(
const QString ¶meterType,
const QPointF &position )
978 QPointF pos = position;
982 std::unique_ptr< QgsProcessingParameterDefinition > newParam;
987 dlg.registerProcessingContextGenerator(
this );
991 newParam.reset( dlg.createParameter() );
995 autoGenerateParameterName( newParam.get() );
997 comment = dlg.comments();
1001 pos = getPositionForParameterItem();
1004 QgsProcessingModelParameter component = QgsProcessingModelParameter( newParam->name() );
1005 component.setDescription( newParam->name() );
1006 component.setPosition( pos );
1008 component.comment()->setDescription( comment );
1009 component.comment()->setPosition( component.position() + QPointF( component.size().width(), -1.5 * component.size().height() ) );
1011 beginUndoCommand( tr(
"Add Model Input" ) );
1012 mModel->addModelParameter( newParam.release(), component );
1017QgsProcessingAlgorithmWidget *QgsModelDesignerDialog::createExecutionWidget()
1020 if ( !dialogFactory )
1027 widget->registerProcessingFeedbackGenerator(
this );
1031void QgsModelDesignerDialog::exportAsScriptAlgorithm()
1034 if ( !dialogFactory )
1043 dialog->codeEditor()->setText( codeLines.join(
'\n' ) );
1048void QgsModelDesignerDialog::zoomIn()
1050 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
1051 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
1053 const double factor = settings.
value( u
"/qgis/zoom_favor"_s, 2.0 ).toDouble();
1054 mView->scale( factor, factor );
1055 mView->centerOn( point );
1058void QgsModelDesignerDialog::zoomOut()
1060 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
1061 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
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 );
1068void QgsModelDesignerDialog::zoomActual()
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 );
1076void QgsModelDesignerDialog::zoomFull()
1078 QRectF totalRect = mView->scene()->itemsBoundingRect();
1079 totalRect.adjust( -10, -10, 10, 10 );
1080 mView->fitInView( totalRect, Qt::KeepAspectRatio );
1083void QgsModelDesignerDialog::newModel()
1085 if ( !checkForUnsavedChanges() )
1088 auto alg = std::make_unique<QgsProcessingModelAlgorithm>();
1090 setModel( alg.release() );
1093void QgsModelDesignerDialog::openModel()
1095 if ( !checkForUnsavedChanges() )
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() )
1103 settings.
setValue( u
"Processing/lastModelsDir"_s, QFileInfo( fileName ).absoluteDir().absolutePath() );
1104 loadModel( fileName );
1108void QgsModelDesignerDialog::exportToImage()
1111 QString lastExportDir = settings.
value( u
"lastModelDesignerExportDir"_s, QDir::homePath(),
QgsSettings::App ).toString();
1113 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Image" ), lastExportDir, tr(
"PNG files (*.png *.PNG)" ) );
1117 if ( filename.isEmpty() )
1122 const QFileInfo saveFileInfo( filename );
1125 repaintModel(
false );
1127 QRectF totalRect = mView->scene()->itemsBoundingRect();
1128 totalRect.adjust( -10, -10, 10, 10 );
1129 const QRectF imageRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
1131 QImage img( totalRect.width(), totalRect.height(), QImage::Format_ARGB32_Premultiplied );
1132 img.fill( Qt::white );
1134 painter.setRenderHint( QPainter::Antialiasing );
1135 painter.begin( &img );
1136 mView->scene()->render( &painter, imageRect, totalRect );
1139 img.save( filename );
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 );
1146void QgsModelDesignerDialog::exportToPdf()
1149 QString lastExportDir = settings.
value( u
"lastModelDesignerExportDir"_s, QDir::homePath(),
QgsSettings::App ).toString();
1151 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as PDF" ), lastExportDir, tr(
"PDF files (*.pdf *.PDF)" ) );
1155 if ( filename.isEmpty() )
1160 const QFileInfo saveFileInfo( filename );
1163 repaintModel(
false );
1165 QRectF totalRect = mView->scene()->itemsBoundingRect();
1166 totalRect.adjust( -10, -10, 10, 10 );
1167 const QRectF printerRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
1169 QPdfWriter pdfWriter( filename );
1171 const double scaleFactor = 96 / 25.4;
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 );
1177 QPainter painter( &pdfWriter );
1178 mView->scene()->render( &painter, printerRect, totalRect );
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 );
1186void QgsModelDesignerDialog::exportToSvg()
1189 QString lastExportDir = settings.
value( u
"lastModelDesignerExportDir"_s, QDir::homePath(),
QgsSettings::App ).toString();
1191 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as SVG" ), lastExportDir, tr(
"SVG files (*.svg *.SVG)" ) );
1195 if ( filename.isEmpty() )
1200 const QFileInfo saveFileInfo( filename );
1203 repaintModel(
false );
1205 QRectF totalRect = mView->scene()->itemsBoundingRect();
1206 totalRect.adjust( -10, -10, 10, 10 );
1207 const QRectF svgRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
1210 svg.setFileName( filename );
1211 svg.setSize( QSize( totalRect.width(), totalRect.height() ) );
1212 svg.setViewBox( svgRect );
1213 svg.setTitle( mModel->displayName() );
1215 QPainter painter( &svg );
1216 mView->scene()->render( &painter, svgRect, totalRect );
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 );
1224void QgsModelDesignerDialog::exportAsPython()
1227 QString lastExportDir = settings.
value( u
"lastModelDesignerExportDir"_s, QDir::homePath(),
QgsSettings::App ).toString();
1229 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Python Script" ), lastExportDir, tr(
"Processing scripts (*.py *.PY)" ) );
1233 if ( filename.isEmpty() )
1238 const QFileInfo saveFileInfo( filename );
1243 QFile outFile( filename );
1244 if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
1248 QTextStream fout( &outFile );
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 );
1256void QgsModelDesignerDialog::repaintModel(
bool showControls )
1258 auto scene =
new QgsModelGraphicsScene(
this );
1259 if ( !showControls )
1261 scene->setFlag( QgsModelGraphicsScene::Flag::FlagHideControls );
1264 const bool showComments =
QgsSettings().
value(
"/Processing/Modeler/ShowComments",
true ).toBool();
1265 if ( !showComments )
1267 scene->setFlag( QgsModelGraphicsScene::Flag::FlagHideComments );
1270 setModelScene( scene );
1271 scene->createItems( mModel.get(), *mContext );
1272 scene->updateBounds();
1275void QgsModelDesignerDialog::toggleComments(
bool show )
1279 repaintModel(
true );
1282void QgsModelDesignerDialog::toggleFeatureCount(
bool show )
1286 repaintModel(
true );
1289void QgsModelDesignerDialog::updateWindowTitle()
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() );
1296 title.prepend(
'*' );
1298 setWindowTitle( title );
1301void QgsModelDesignerDialog::deleteSelected()
1303 QList<QgsModelComponentGraphicItem *> items = mScene->selectedComponentItems();
1304 if ( items.empty() )
1307 if ( items.size() == 1 )
1309 items.at( 0 )->deleteComponent();
1313 std::sort( items.begin(), items.end(), []( QgsModelComponentGraphicItem *p1, QgsModelComponentGraphicItem *p2 ) {
1318 if ( dynamic_cast<QgsModelCommentGraphicItem *>( p1 ) && dynamic_cast<QgsModelCommentGraphicItem *>( p2 ) )
1320 else if ( dynamic_cast<QgsModelCommentGraphicItem *>( p1 ) )
1322 else if ( dynamic_cast<QgsModelCommentGraphicItem *>( p2 ) )
1325 else if ( dynamic_cast<QgsModelGroupBoxGraphicItem *>( p1 ) && dynamic_cast<QgsModelGroupBoxGraphicItem *>( p2 ) )
1327 else if ( dynamic_cast<QgsModelGroupBoxGraphicItem *>( p1 ) )
1329 else if ( dynamic_cast<QgsModelGroupBoxGraphicItem *>( p2 ) )
1332 else if ( dynamic_cast<QgsModelOutputGraphicItem *>( p1 ) && dynamic_cast<QgsModelOutputGraphicItem *>( p2 ) )
1334 else if ( dynamic_cast<QgsModelOutputGraphicItem *>( p1 ) )
1336 else if ( dynamic_cast<QgsModelOutputGraphicItem *>( p2 ) )
1339 else if ( dynamic_cast<QgsModelChildAlgorithmGraphicItem *>( p1 ) && dynamic_cast<QgsModelChildAlgorithmGraphicItem *>( p2 ) )
1341 else if ( dynamic_cast<QgsModelChildAlgorithmGraphicItem *>( p1 ) )
1343 else if ( dynamic_cast<QgsModelChildAlgorithmGraphicItem *>( p2 ) )
1350 beginUndoCommand( tr(
"Delete Components" ) );
1352 QVariant prevState = mModel->toVariant();
1353 mBlockUndoCommands++;
1354 mBlockRepaints =
true;
1355 bool failed =
false;
1356 while ( !items.empty() )
1358 QgsModelComponentGraphicItem *toDelete =
nullptr;
1359 for ( QgsModelComponentGraphicItem *item : items )
1361 if ( item->canDeleteComponent() )
1374 toDelete->deleteComponent();
1375 items.removeAll( toDelete );
1380 mModel->loadVariant( prevState );
1381 QMessageBox::warning(
1383 QObject::tr(
"Could not remove components" ),
1385 "Components depend on the selected items.\n"
1386 "Try to remove them before trying deleting these components."
1389 mBlockUndoCommands--;
1390 mActiveCommand.reset();
1394 mBlockUndoCommands--;
1398 mBlockRepaints =
false;
1402void QgsModelDesignerDialog::populateZoomToMenu()
1404 mGroupMenu->clear();
1405 for (
const QgsProcessingModelGroupBox &box : model()->groupBoxes() )
1407 if ( QgsModelComponentGraphicItem *item = mScene->groupBoxItem( box.uuid() ) )
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 );
1416 mGroupMenu->addAction( zoomAction );
1421void QgsModelDesignerDialog::setPanelVisibility(
bool hidden )
1423 const QList<QDockWidget *> docks = findChildren<QDockWidget *>();
1424 const QList<QTabBar *> tabBars = findChildren<QTabBar *>();
1428 mPanelStatus.clear();
1430 for ( QDockWidget *dock : docks )
1432 mPanelStatus.insert( dock->windowTitle(), PanelStatus( dock->isVisible(),
false ) );
1433 dock->setVisible(
false );
1437 for ( QTabBar *tabBar : tabBars )
1439 QString currentTabTitle = tabBar->tabText( tabBar->currentIndex() );
1440 mPanelStatus[currentTabTitle].isActive =
true;
1446 for ( QDockWidget *dock : docks )
1448 if ( mPanelStatus.contains( dock->windowTitle() ) )
1450 dock->setVisible( mPanelStatus.value( dock->windowTitle() ).isVisible );
1455 for ( QTabBar *tabBar : tabBars )
1458 for (
int i = 0; i < tabBar->count(); ++i )
1460 QString tabTitle = tabBar->tabText( i );
1461 if ( mPanelStatus.contains( tabTitle ) && mPanelStatus.value( tabTitle ).isActive )
1463 tabBar->setCurrentIndex( i );
1467 mPanelStatus.clear();
1471void QgsModelDesignerDialog::editHelp()
1473 QgsProcessingHelpEditorDialog dialog(
this );
1474 dialog.setWindowTitle( tr(
"Edit Model Help" ) );
1475 dialog.setAlgorithm( mModel.get() );
1476 if ( dialog.exec() )
1478 beginUndoCommand( tr(
"Edit Model Help" ) );
1479 mModel->setHelpContent( dialog.helpContent() );
1484void QgsModelDesignerDialog::runSelectedSteps()
1486 QSet<QString> children;
1487 const QList<QgsModelComponentGraphicItem *> items = mScene->selectedComponentItems();
1488 for ( QgsModelComponentGraphicItem *item : items )
1490 if ( QgsProcessingModelChildAlgorithm *childAlgorithm =
dynamic_cast<QgsProcessingModelChildAlgorithm *
>( item->component() ) )
1492 children.insert( childAlgorithm->childId() );
1496 if ( children.isEmpty() )
1498 mMessageBar->pushWarning( QString(), tr(
"No steps are selected" ) );
1505void QgsModelDesignerDialog::runFromChild(
const QString &
id )
1507 QSet<QString> children = mModel->dependentChildAlgorithms(
id );
1508 children.insert(
id );
1512void QgsModelDesignerDialog::cancelRunningModel()
1514 if ( !mAlgorithmWidget )
1520 mAlgorithmWidget->cancel();
1522 mAlgorithmWidget->forceClose();
1525 if ( mAlgorithmWidget )
1531 mAlgorithmWidgetsToCleanUp << mAlgorithmWidget;
1533 mAlgorithmWidget.clear();
1536void QgsModelDesignerDialog::run(
const QSet<QString> &childAlgorithmSubset )
1539 const bool isValid = model()->validate( errors );
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 );
1549 QString errorString;
1550 for (
const QString &error : std::as_const( errors ) )
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 );
1558 messageBox.setDetailedText( errorString );
1559 if ( messageBox.exec() == QMessageBox::StandardButton::Cancel )
1563 if ( !childAlgorithmSubset.isEmpty() )
1565 for (
const QString &child : childAlgorithmSubset )
1568 const QSet<QString> requirements = mModel->dependsOnChildAlgorithms( child );
1569 for (
const QString &requirement : requirements )
1571 if ( !mLastResult.executedChildIds().contains( requirement ) )
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 );
1585 if ( mAlgorithmWidget && mAlgorithmWidget->isRunning() )
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 );
1593 QAbstractButton *buttonShowRunningAlg = messageBox.button( QMessageBox::StandardButton::Ok );
1594 buttonShowRunningAlg->setText( tr(
"Show Progress" ) );
1596 QAbstractButton *buttonReRun = messageBox.button( QMessageBox::StandardButton::RestoreDefaults );
1597 buttonReRun->setText( tr(
"Cancel and Restart Model" ) );
1599 int r = messageBox.exec();
1603 case QMessageBox::StandardButton::Cancel:
1605 case QMessageBox::StandardButton::RestoreDefaults:
1606 cancelRunningModel();
1608 case QMessageBox::StandardButton::Ok:
1609 mAlgorithmWidget->showWidget();
1615 else if ( mAlgorithmWidget )
1618 mAlgorithmWidget->close();
1619 if ( mAlgorithmWidget )
1625 mAlgorithmWidgetsToCleanUp << mAlgorithmWidget;
1628 mAlgorithmWidget.clear();
1631 if ( !mAlgorithmWidget )
1633 mAlgorithmWidget = createExecutionWidget();
1634 if ( !mAlgorithmWidget )
1637 mAlgorithmWidget->hideShortHelp();
1638 mAlgorithmWidget->setTitle( tr(
"Run Model" ) );
1641 mAlgorithmWidget->setParameters( mModel->designerParameterValues() );
1643 if ( !childAlgorithmSubset.isEmpty() )
1645 mAlgorithmWidget->runButton()->setText( tr(
"Run Subset" ) );
1646 mAlgorithmWidget->runButton()->setToolTip( tr(
"Runs a subset of the child algorithms from this model" ) );
1649 connect( mAlgorithmWidget.get(), &QgsProcessingAlgorithmWidgetBase::algorithmAboutToRun,
this, [
this, childAlgorithmSubset](
QgsProcessingContext *context ) {
1650 if ( !childAlgorithmSubset.empty() )
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() );
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 )
1665 std::unique_ptr<QgsMapLayer> clone( it.value()->clone() );
1666 clone->setId( it.value()->id() );
1667 previousResultStore->addMapLayer( clone.release() );
1669 previousResultStore->moveToThread( nullptr );
1670 modelConfig->setPreviousLayerStore( std::move( previousResultStore ) );
1671 context->setModelInitialRunConfig( std::move( modelConfig ) );
1673 mScene->resetChildAlgorithmItems( childAlgorithmSubset );
1676 for ( const QString &child : childAlgorithmSubset )
1678 const QSet< QString > outdated = mModel->dependentChildAlgorithms( child );
1679 mScene->flagChildrenAsOutdated( outdated );
1680 mOutdatedChildResults.unite( outdated );
1686 mScene->resetChildAlgorithmItems();
1690 connect( mAlgorithmWidget, &QgsProcessingAlgorithmWidgetBase::algorithmFinished,
this, [
this](
bool,
const QVariantMap &,
QgsProcessingContext *context ) {
1692 mLayerStore.temporaryLayerStore()->removeAllMapLayers();
1693 mLayerStore.takeResultsFrom( *context );
1701void QgsModelDesignerDialog::showChildAlgorithmOutputs(
const QString &childId )
1703 const bool isOutdated = mOutdatedChildResults.contains( childId );
1704 const QString childDescription = mModel->childAlgorithm( childId ).description();
1707 const QVariantMap childAlgorithmOutputs = result.
outputs();
1708 if ( childAlgorithmOutputs.isEmpty() )
1710 mMessageBar->pushWarning( QString(), tr(
"No results are available for %1" ).arg( childDescription ) );
1717 mMessageBar->pushCritical( QString(), tr(
"Results cannot be shown for an invalid model component" ) );
1721 const QList<const QgsProcessingParameterDefinition *> outputParams =
algorithm->destinationParameterDefinitions();
1722 if ( outputParams.isEmpty() )
1725 QgsDebugError(
"Cannot show results for algorithms with no outputs" );
1729 bool foundResults =
false;
1732 const QVariant output = childAlgorithmOutputs.value( outputParam->name() );
1733 if ( !output.isValid() )
1736 if ( output.typeId() == QMetaType::Type::QString )
1740 QgsDebugMsgLevel( u
"Loading previous result for %1: %2"_s.arg( outputParam->name(), output.toString() ), 2 );
1742 std::unique_ptr<QgsMapLayer> layer( resultLayer->clone() );
1745 if ( outputParams.size() > 1 )
1746 baseName = tr(
"%1 — %2" ).arg( childDescription, outputParam->name() );
1748 baseName = childDescription;
1752 QString name = baseName;
1757 name = tr(
"%1 (%2)" ).arg( baseName ).arg( counter );
1760 layer->setName( name );
1763 foundResults =
true;
1768 QgsDebugError( u
"Could not load previous result for %1: %2"_s.arg( outputParam->name(), output.toString() ) );
1773 if ( !foundResults )
1775 mMessageBar->pushWarning( QString(), tr(
"No results are available for %1" ).arg( childDescription ) );
1778 else if ( isOutdated )
1780 mMessageBar->pushWarning( QString(), tr(
"These results are outdated, and may not reflect the most recent model execution" ) );
1785void QgsModelDesignerDialog::showChildAlgorithmLog(
const QString &childId )
1787 const QString childDescription = mModel->childAlgorithm( childId ).description();
1792 if ( QgsModelChildAlgorithmGraphicItem *item = mScene->childAlgorithmItem( childId ) )
1794 result = item->results();
1796 if ( result.
htmlLog().isEmpty() )
1798 result = mLastResult.childResults().value( childId );
1801 if ( result.
htmlLog().isEmpty() )
1803 mMessageBar->pushWarning( QString(), tr(
"No log is available for %1" ).arg( childDescription ) );
1808 m.setWindowTitle( childDescription );
1809 m.setCheckBoxVisible(
false );
1810 m.setMessageAsHtml( result.
htmlLog() );
1814void QgsModelDesignerDialog::onItemFocused( QgsModelComponentGraphicItem *item )
1820 if ( !item || !item->component() )
1822 mConfigWidget->showComponentConfig(
nullptr, *mContext, widgetContext );
1826 mConfigWidget->showComponentConfig( item->component(), *mContext, widgetContext );
1828 if (
auto childAlgorithmItem = qobject_cast< QgsModelChildAlgorithmGraphicItem * >( item ) )
1830 connect( childAlgorithmItem, &QgsModelChildAlgorithmGraphicItem::rebuildConfigurationDockWidget, childAlgorithmItem, [
this] {
1834 mConfigWidget->showComponentConfig(
nullptr, *mContext, widgetContext );
1840void QgsModelDesignerDialog::validate()
1843 if ( model()->validate( issues ) )
1845 mMessageBar->pushSuccess( QString(), tr(
"Model is valid!" ) );
1850 QPushButton *detailsButton =
new QPushButton( tr(
"Details" ) );
1851 connect( detailsButton, &QPushButton::clicked, detailsButton, [detailsButton, issues] {
1853 dialog->
setTitle( tr(
"Model is Invalid" ) );
1855 QString longMessage = tr(
"<p>This model is not valid:</p>" ) + u
"<ul>"_s;
1856 for (
const QString &issue : issues )
1858 longMessage += u
"<li>%1</li>"_s.arg( issue );
1860 longMessage +=
"</ul>"_L1;
1865 messageWidget->layout()->addWidget( detailsButton );
1866 mMessageBar->clearWidgets();
1871void QgsModelDesignerDialog::reorderInputs()
1873 QgsModelInputReorderDialog dlg(
this );
1874 dlg.setModel( mModel.get() );
1877 const QStringList inputOrder = dlg.inputOrder();
1878 beginUndoCommand( tr(
"Reorder Inputs" ) );
1879 mModel->setParameterOrder( inputOrder );
1884void QgsModelDesignerDialog::reorderOutputs()
1886 QgsModelOutputReorderDialog dlg(
this );
1887 dlg.setModel( mModel.get() );
1890 const QStringList outputOrder = dlg.outputOrder();
1891 beginUndoCommand( tr(
"Reorder Outputs" ) );
1892 mModel->setOutputOrder( outputOrder );
1893 mModel->setOutputGroup( dlg.outputGroup() );
1898bool QgsModelDesignerDialog::isDirty()
const
1900 return mHasChanged && mUndoStack->index() != -1;
1903void QgsModelDesignerDialog::fillInputsTree()
1906 auto parametersItem = std::make_unique<QTreeWidgetItem>();
1907 parametersItem->setText( 0, tr(
"Parameters" ) );
1910 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
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() );
1926 mInputsTreeWidget->addTopLevelItem( parametersItem.release() );
1927 mInputsTreeWidget->topLevelItem( 0 )->setExpanded(
true );
1935QgsModelChildDependenciesWidget::QgsModelChildDependenciesWidget( QWidget *parent, QgsProcessingModelAlgorithm *model,
const QString &childId )
1938 , mChildId( childId )
1940 QHBoxLayout *hl =
new QHBoxLayout();
1941 hl->setContentsMargins( 0, 0, 0, 0 );
1943 mLineEdit =
new QLineEdit();
1944 mLineEdit->setEnabled(
false );
1945 hl->addWidget( mLineEdit, 1 );
1947 mToolButton =
new QToolButton();
1948 mToolButton->setText( QString( QChar( 0x2026 ) ) );
1949 hl->addWidget( mToolButton );
1953 mLineEdit->setText( tr(
"%1 dependencies selected" ).arg( 0 ) );
1955 connect( mToolButton, &QToolButton::clicked,
this, &QgsModelChildDependenciesWidget::showDialog );
1958void QgsModelChildDependenciesWidget::setValue(
const QList<QgsProcessingModelChildDependency> &value )
1960 const bool hasChanged = value != mValue;
1963 updateSummaryText();
1970void QgsModelChildDependenciesWidget::showDialog()
1972 const QList<QgsProcessingModelChildDependency> available = mModel->availableDependenciesForChildAlgorithm( mChildId );
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 );
1984 QgsProcessingMultipleSelectionPanelWidget *widget =
new QgsProcessingMultipleSelectionPanelWidget( availableOptions, selectedOptions );
1985 widget->setPanelTitle( tr(
"Algorithm Dependencies" ) );
1987 widget->setValueFormatter( [
this](
const QVariant &v ) -> QString {
1988 const QgsProcessingModelChildDependency dep = v.value<QgsProcessingModelChildDependency>();
1990 const QString description = mModel->childAlgorithm( dep.childId ).description();
1991 if ( dep.conditionalBranch.isEmpty() )
1994 return tr(
"Condition “%1” from algorithm “%2”" ).arg( dep.conditionalBranch, description );
1997 connect( widget, &QgsProcessingMultipleSelectionPanelWidget::selectionChanged,
this, [
this, widget]() {
1998 QList<QgsProcessingModelChildDependency> res;
1999 for (
const QVariant &v : widget->selectedOptions() )
2001 res << v.value<QgsProcessingModelChildDependency>();
2010void QgsModelChildDependenciesWidget::updateSummaryText()
2012 mLineEdit->setText( tr(
"%n dependencies selected",
nullptr, mValue.count() ) );
static QString version()
Version string.
@ ExposeToModeler
Is this parameter available in the modeler. Is set to on by default.
@ Warning
Warning message.
@ Success
Used for reporting a successful operation.
@ ForceDocked
Force the widget to be docked.
@ ModelDebug
Model debug level logging. Includes verbose logging and other outputs useful for debugging models.
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.
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.
static QSize iconSize(Qgis::UserInterfaceIconType iconType=Qgis::UserInterfaceIconType::MainWindowToolbar)
Returns the desired size for user interface icons.
static QgsProcessingGuiRegistry * processingGuiRegistry()
Returns the global processing gui registry, used for registering the GUI behavior of processing algor...
void applicationStyleSheetChanged(const QString &styleSheet)
Emitted whenever the application style sheet is changed.
static QString applicationStyleSheet()
Returns the application style sheet.
static QgsGui * instance()
Returns a pointer to the singleton instance.
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...
Base class for all map layer types.
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
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.
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.
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 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)
#define QgsDebugError(str)
constexpr QObjectUniquePtr< Tp > make_qobject_unique(Args &&...args)
Create an object owned by a QObjectUniquePtr.