41#include <QKeySequence>
44#include <QSvgGenerator>
52#include <QActionGroup>
57QgsModelerToolboxModel::QgsModelerToolboxModel( QObject *parent )
63Qt::ItemFlags QgsModelerToolboxModel::flags(
const QModelIndex &index )
const
65 Qt::ItemFlags f = QgsProcessingToolboxProxyModel::flags( index );
66 const QModelIndex sourceIndex = mapToSource( index );
67 if ( toolboxModel()->isAlgorithm( sourceIndex ) )
69 f = f | Qt::ItemIsDragEnabled;
74Qt::DropActions QgsModelerToolboxModel::supportedDragActions()
const
76 return Qt::CopyAction;
81QgsModelDesignerDialog::QgsModelDesignerDialog( QWidget *parent, Qt::WindowFlags flags )
82 : QMainWindow( parent, flags )
83 , mToolsActionGroup( new QActionGroup( this ) )
89 setAttribute( Qt::WA_DeleteOnClose );
90 setDockOptions( dockOptions() | QMainWindow::GroupedDragging );
91 setWindowFlags( Qt::WindowMinimizeButtonHint |
92 Qt::WindowMaximizeButtonHint |
93 Qt::WindowCloseButtonHint );
97 mModel = std::make_unique< QgsProcessingModelAlgorithm >();
100 mUndoStack =
new QUndoStack(
this );
101 connect( mUndoStack, &QUndoStack::indexChanged,
this, [ = ]
103 if ( mIgnoreUndoStackChanges )
106 mBlockUndoCommands++;
107 updateVariablesGui();
108 mGroupEdit->setText( mModel->group() );
109 mNameEdit->setText( mModel->displayName() );
110 mBlockUndoCommands--;
114 mPropertiesDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable );
115 mInputsDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable );
116 mAlgorithmsDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable );
117 mVariablesDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
119 mAlgorithmsTree->header()->setVisible(
false );
120 mAlgorithmSearchEdit->setShowSearchIcon(
true );
121 mAlgorithmSearchEdit->setPlaceholderText( tr(
"Search…" ) );
122 connect( mAlgorithmSearchEdit, &QgsFilterLineEdit::textChanged, mAlgorithmsTree, &QgsProcessingToolboxTreeView::setFilterString );
124 mInputsTreeWidget->header()->setVisible(
false );
125 mInputsTreeWidget->setAlternatingRowColors(
true );
126 mInputsTreeWidget->setDragDropMode( QTreeWidget::DragOnly );
127 mInputsTreeWidget->setDropIndicatorShown(
true );
129 mNameEdit->setPlaceholderText( tr(
"Enter model name here" ) );
130 mGroupEdit->setPlaceholderText( tr(
"Enter group name here" ) );
133 mMessageBar->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Fixed );
134 mainLayout->insertWidget( 0, mMessageBar );
136 mView->setAcceptDrops(
true );
139 connect( mActionClose, &QAction::triggered,
this, &QWidget::close );
140 connect( mActionNew, &QAction::triggered,
this, &QgsModelDesignerDialog::newModel );
141 connect( mActionZoomIn, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomIn );
142 connect( mActionZoomOut, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomOut );
143 connect( mActionZoomActual, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomActual );
144 connect( mActionZoomToItems, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomFull );
145 connect( mActionExportImage, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToImage );
146 connect( mActionExportPdf, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToPdf );
147 connect( mActionExportSvg, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToSvg );
148 connect( mActionExportPython, &QAction::triggered,
this, &QgsModelDesignerDialog::exportAsPython );
149 connect( mActionSave, &QAction::triggered,
this, [ = ] { saveModel(
false ); } );
150 connect( mActionSaveAs, &QAction::triggered,
this, [ = ] { saveModel(
true ); } );
151 connect( mActionDeleteComponents, &QAction::triggered,
this, &QgsModelDesignerDialog::deleteSelected );
152 connect( mActionSnapSelected, &QAction::triggered, mView, &QgsModelGraphicsView::snapSelected );
153 connect( mActionValidate, &QAction::triggered,
this, &QgsModelDesignerDialog::validate );
154 connect( mActionReorderInputs, &QAction::triggered,
this, &QgsModelDesignerDialog::reorderInputs );
155 connect( mActionEditHelp, &QAction::triggered,
this, &QgsModelDesignerDialog::editHelp );
156 connect( mReorderInputsButton, &QPushButton::clicked,
this, &QgsModelDesignerDialog::reorderInputs );
158 mActionSnappingEnabled->setChecked( settings.
value( QStringLiteral(
"/Processing/Modeler/enableSnapToGrid" ),
false ).toBool() );
159 connect( mActionSnappingEnabled, &QAction::toggled,
this, [ = ](
bool enabled )
161 mView->snapper()->setSnapToGrid( enabled );
162 QgsSettings().
setValue( QStringLiteral(
"/Processing/Modeler/enableSnapToGrid" ), enabled );
164 mView->snapper()->setSnapToGrid( mActionSnappingEnabled->isChecked() );
166 connect( mActionSelectAll, &QAction::triggered,
this, [ = ]
171 QStringList docksTitle = settings.
value( QStringLiteral(
"ModelDesigner/hiddenDocksTitle" ), QStringList(),
QgsSettings::App ).toStringList();
172 QStringList docksActive = settings.
value( QStringLiteral(
"ModelDesigner/hiddenDocksActive" ), QStringList(),
QgsSettings::App ).toStringList();
173 if ( !docksTitle.isEmpty() )
175 for (
const auto &title : docksTitle )
177 mPanelStatus.insert( title, PanelStatus(
true, docksActive.contains( title ) ) );
180 mActionHidePanels->setChecked( !docksTitle.isEmpty() );
181 connect( mActionHidePanels, &QAction::toggled,
this, &QgsModelDesignerDialog::setPanelVisibility );
183 mUndoAction = mUndoStack->createUndoAction(
this );
185 mUndoAction->setShortcuts( QKeySequence::Undo );
186 mRedoAction = mUndoStack->createRedoAction(
this );
188 mRedoAction->setShortcuts( QKeySequence::Redo );
190 mMenuEdit->insertAction( mActionDeleteComponents, mRedoAction );
191 mMenuEdit->insertAction( mActionDeleteComponents, mUndoAction );
192 mMenuEdit->insertSeparator( mActionDeleteComponents );
193 mToolbar->insertAction( mActionZoomIn, mUndoAction );
194 mToolbar->insertAction( mActionZoomIn, mRedoAction );
195 mToolbar->insertSeparator( mActionZoomIn );
197 mGroupMenu =
new QMenu( tr(
"Zoom To" ),
this );
198 mMenuView->insertMenu( mActionZoomIn, mGroupMenu );
199 connect( mGroupMenu, &QMenu::aboutToShow,
this, &QgsModelDesignerDialog::populateZoomToMenu );
203 mActionCut =
new QAction( tr(
"Cu&t" ),
this );
204 mActionCut->setShortcuts( QKeySequence::Cut );
205 mActionCut->setStatusTip( tr(
"Cut" ) );
207 connect( mActionCut, &QAction::triggered,
this, [ = ]
209 mView->copySelectedItems( QgsModelGraphicsView::ClipboardCut );
212 mActionCopy =
new QAction( tr(
"&Copy" ),
this );
213 mActionCopy->setShortcuts( QKeySequence::Copy );
214 mActionCopy->setStatusTip( tr(
"Copy" ) );
216 connect( mActionCopy, &QAction::triggered,
this, [ = ]
218 mView->copySelectedItems( QgsModelGraphicsView::ClipboardCopy );
221 mActionPaste =
new QAction( tr(
"&Paste" ),
this );
222 mActionPaste->setShortcuts( QKeySequence::Paste );
223 mActionPaste->setStatusTip( tr(
"Paste" ) );
225 connect( mActionPaste, &QAction::triggered,
this, [ = ]
227 mView->pasteItems( QgsModelGraphicsView::PasteModeCursor );
229 mMenuEdit->insertAction( mActionDeleteComponents, mActionCut );
230 mMenuEdit->insertAction( mActionDeleteComponents, mActionCopy );
231 mMenuEdit->insertAction( mActionDeleteComponents, mActionPaste );
232 mMenuEdit->insertSeparator( mActionDeleteComponents );
234 mAlgorithmsModel =
new QgsModelerToolboxModel(
this );
235 mAlgorithmsTree->setToolboxProxyModel( mAlgorithmsModel );
238 if ( settings.
value( QStringLiteral(
"Processing/Configuration/SHOW_ALGORITHMS_KNOWN_ISSUES" ),
false ).toBool() )
242 mAlgorithmsTree->setFilters( filters );
243 mAlgorithmsTree->setDragDropMode( QTreeWidget::DragOnly );
244 mAlgorithmsTree->setDropIndicatorShown(
true );
246 connect( mView, &QgsModelGraphicsView::algorithmDropped,
this, [ = ](
const QString & algorithmId,
const QPointF & pos )
248 addAlgorithm( algorithmId, pos );
250 connect( mAlgorithmsTree, &QgsProcessingToolboxTreeView::doubleClicked,
this, [ = ]()
252 if ( mAlgorithmsTree->selectedAlgorithm() )
253 addAlgorithm( mAlgorithmsTree->selectedAlgorithm()->id(), QPointF() );
255 connect( mInputsTreeWidget, &QgsModelDesignerInputsTreeWidget::doubleClicked,
this, [ = ](
const QModelIndex & )
257 const QString parameterType = mInputsTreeWidget->currentItem()->data( 0, Qt::UserRole ).toString();
258 addInput( parameterType, QPointF() );
261 connect( mView, &QgsModelGraphicsView::inputDropped,
this, &QgsModelDesignerDialog::addInput );
264 QShortcut *ctrlEquals =
new QShortcut( QKeySequence( QStringLiteral(
"Ctrl+=" ) ),
this );
265 connect( ctrlEquals, &QShortcut::activated,
this, &QgsModelDesignerDialog::zoomIn );
268 mUndoDock->setObjectName( QStringLiteral(
"UndoDock" ) );
269 mUndoView =
new QUndoView( mUndoStack,
this );
270 mUndoDock->setWidget( mUndoView );
271 mUndoDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
272 addDockWidget( Qt::DockWidgetArea::LeftDockWidgetArea, mUndoDock );
274 tabifyDockWidget( mUndoDock, mPropertiesDock );
275 tabifyDockWidget( mVariablesDock, mPropertiesDock );
276 mPropertiesDock->raise();
277 tabifyDockWidget( mInputsDock, mAlgorithmsDock );
278 mInputsDock->raise();
284 beginUndoCommand( tr(
"Change Model Variables" ) );
285 mModel->setVariables( mVariablesEditor->variablesInActiveScope() );
289 connect( mNameEdit, &QLineEdit::textChanged,
this, [ = ](
const QString & name )
293 beginUndoCommand( tr(
"Change Model Name" ), NameChanged );
294 mModel->setName( name );
299 connect( mGroupEdit, &QLineEdit::textChanged,
this, [ = ](
const QString & group )
303 beginUndoCommand( tr(
"Change Model Group" ), GroupChanged );
304 mModel->setGroup( group );
311 QToolButton *toolbuttonExportToScript =
new QToolButton();
312 toolbuttonExportToScript->setPopupMode( QToolButton::InstantPopup );
313 toolbuttonExportToScript->addAction( mActionExportAsScriptAlgorithm );
314 toolbuttonExportToScript->setDefaultAction( mActionExportAsScriptAlgorithm );
315 mToolbar->insertWidget( mActionExportImage, toolbuttonExportToScript );
316 connect( mActionExportAsScriptAlgorithm, &QAction::triggered,
this, &QgsModelDesignerDialog::exportAsScriptAlgorithm );
318 mActionShowComments->setChecked( settings.
value( QStringLiteral(
"/Processing/Modeler/ShowComments" ),
true ).toBool() );
319 connect( mActionShowComments, &QAction::toggled,
this, &QgsModelDesignerDialog::toggleComments );
322 mPanTool->setAction( mActionPan );
324 mToolsActionGroup->addAction( mActionPan );
325 connect( mActionPan, &QAction::triggered, mPanTool, [ = ] { mView->setTool( mPanTool ); } );
328 mSelectTool->setAction( mActionSelectMoveItem );
330 mToolsActionGroup->addAction( mActionSelectMoveItem );
331 connect( mActionSelectMoveItem, &QAction::triggered, mSelectTool, [ = ] { mView->setTool( mSelectTool ); } );
333 mView->setTool( mSelectTool );
336 connect( mView, &QgsModelGraphicsView::macroCommandStarted,
this, [ = ](
const QString & text )
338 mIgnoreUndoStackChanges++;
339 mUndoStack->beginMacro( text );
340 mIgnoreUndoStackChanges--;
342 connect( mView, &QgsModelGraphicsView::macroCommandEnded,
this, [ = ]
344 mIgnoreUndoStackChanges++;
345 mUndoStack->endMacro();
346 mIgnoreUndoStackChanges--;
348 connect( mView, &QgsModelGraphicsView::beginCommand,
this, [ = ](
const QString & text )
350 beginUndoCommand( text );
352 connect( mView, &QgsModelGraphicsView::endCommand,
this, [ = ]
356 connect( mView, &QgsModelGraphicsView::deleteSelectedItems,
this, [ = ]
361 connect( mActionAddGroupBox, &QAction::triggered,
this, [ = ]
363 const QPointF viewCenter = mView->mapToScene( mView->viewport()->rect().center() );
364 QgsProcessingModelGroupBox group;
365 group.setPosition( viewCenter );
366 group.setDescription( tr(
"New Group" ) );
368 beginUndoCommand( tr(
"Add Group Box" ) );
369 model()->addGroupBox( group );
377 restoreState( settings.
value( QStringLiteral(
"ModelDesigner/state" ), QByteArray(),
QgsSettings::App ).toByteArray() );
380QgsModelDesignerDialog::~QgsModelDesignerDialog()
383 if ( !mPanelStatus.isEmpty() )
385 QStringList docksTitle;
386 QStringList docksActive;
388 for (
const auto &panel : mPanelStatus.toStdMap() )
390 if ( panel.second.isVisible )
391 docksTitle << panel.first;
392 if ( panel.second.isActive )
393 docksActive << panel.first;
407 mIgnoreUndoStackChanges++;
411void QgsModelDesignerDialog::closeEvent( QCloseEvent *event )
413 if ( checkForUnsavedChanges() )
419void QgsModelDesignerDialog::beginUndoCommand(
const QString &text,
int id )
421 if ( mBlockUndoCommands || !mUndoStack )
424 if ( mActiveCommand )
427 mActiveCommand = std::make_unique< QgsModelUndoCommand >( mModel.get(), text,
id );
430void QgsModelDesignerDialog::endUndoCommand()
432 if ( mBlockUndoCommands || !mActiveCommand || !mUndoStack )
435 mActiveCommand->saveAfterState();
436 mIgnoreUndoStackChanges++;
437 mUndoStack->push( mActiveCommand.release() );
438 mIgnoreUndoStackChanges--;
442QgsProcessingModelAlgorithm *QgsModelDesignerDialog::model()
447void QgsModelDesignerDialog::setModel( QgsProcessingModelAlgorithm *model )
449 mModel.reset( model );
451 mGroupEdit->setText( mModel->group() );
452 mNameEdit->setText( mModel->displayName() );
454 updateVariablesGui();
456 mView->centerOn( 0, 0 );
459 mIgnoreUndoStackChanges++;
461 mIgnoreUndoStackChanges--;
466void QgsModelDesignerDialog::loadModel(
const QString &path )
468 std::unique_ptr< QgsProcessingModelAlgorithm > alg = std::make_unique< QgsProcessingModelAlgorithm >();
469 if ( alg->fromFile( path ) )
472 alg->setSourceFilePath( path );
473 setModel( alg.release() );
477 QgsMessageLog::logMessage( tr(
"Could not load model %1" ).arg( path ), tr(
"Processing" ), Qgis::MessageLevel::Critical );
478 QMessageBox::critical(
this, tr(
"Open Model" ), tr(
"The selected model could not be loaded.\n"
479 "See the log for more information." ) );
483void QgsModelDesignerDialog::setModelScene( QgsModelGraphicsScene *scene )
485 QgsModelGraphicsScene *oldScene = mScene;
488 mScene->setParent(
this );
489 mScene->setChildAlgorithmResults( mChildResults );
490 mScene->setModel( mModel.get() );
491 mScene->setMessageBar( mMessageBar );
493 const QPointF center = mView->mapToScene( mView->viewport()->rect().center() );
494 mView->setModelScene( mScene );
496 mSelectTool->resetCache();
497 mSelectTool->setScene( mScene );
499 connect( mScene, &QgsModelGraphicsScene::rebuildRequired,
this, [ = ]
501 if ( mBlockRepaints )
506 connect( mScene, &QgsModelGraphicsScene::componentAboutToChange,
this, [ = ](
const QString & description,
int id ) { beginUndoCommand( description,
id ); } );
507 connect( mScene, &QgsModelGraphicsScene::componentChanged,
this, [ = ] { endUndoCommand(); } );
509 mView->centerOn( center );
512 oldScene->deleteLater();
515void QgsModelDesignerDialog::activate()
519 setWindowState( windowState() & ~Qt::WindowMinimized );
523void QgsModelDesignerDialog::updateVariablesGui()
525 mBlockUndoCommands++;
527 std::unique_ptr< QgsExpressionContextScope > variablesScope = std::make_unique< QgsExpressionContextScope >( tr(
"Model Variables" ) );
528 const QVariantMap modelVars = mModel->variables();
529 for (
auto it = modelVars.constBegin(); it != modelVars.constEnd(); ++it )
531 variablesScope->setVariable( it.key(), it.value() );
534 variablesContext.
appendScope( variablesScope.release() );
535 mVariablesEditor->setContext( &variablesContext );
536 mVariablesEditor->setEditableScopeIndex( 0 );
538 mBlockUndoCommands--;
541void QgsModelDesignerDialog::setDirty(
bool dirty )
547bool QgsModelDesignerDialog::validateSave( SaveAction action )
551 case QgsModelDesignerDialog::SaveAction::SaveAsFile:
553 case QgsModelDesignerDialog::SaveAction::SaveInProject:
554 if ( mNameEdit->text().trimmed().isEmpty() )
556 mMessageBar->pushWarning( QString(), tr(
"Please enter a model name before saving" ) );
565bool QgsModelDesignerDialog::checkForUnsavedChanges()
569 QMessageBox::StandardButton ret = QMessageBox::question(
this, tr(
"Save Model?" ),
570 tr(
"There are unsaved changes in this model. Do you want to keep those?" ),
571 QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Discard, QMessageBox::Cancel );
574 case QMessageBox::Save:
575 return saveModel(
false );
577 case QMessageBox::Discard:
590void QgsModelDesignerDialog::setLastRunChildAlgorithmResults(
const QVariantMap &results )
592 mChildResults = results;
594 mScene->setChildAlgorithmResults( mChildResults );
597void QgsModelDesignerDialog::setLastRunChildAlgorithmInputs(
const QVariantMap &inputs )
599 mChildInputs = inputs;
601 mScene->setChildAlgorithmInputs( mChildInputs );
604void QgsModelDesignerDialog::setModelName(
const QString &name )
606 mNameEdit->setText( name );
609void QgsModelDesignerDialog::zoomIn()
611 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
612 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
614 const double factor = settings.
value( QStringLiteral(
"/qgis/zoom_favor" ), 2.0 ).toDouble();
615 mView->scale( factor, factor );
616 mView->centerOn( point );
619void QgsModelDesignerDialog::zoomOut()
621 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
622 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
624 const double factor = 1.0 / settings.
value( QStringLiteral(
"/qgis/zoom_favor" ), 2.0 ).toDouble();
625 mView->scale( factor, factor );
626 mView->centerOn( point );
629void QgsModelDesignerDialog::zoomActual()
631 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
632 mView->resetTransform();
633 mView->scale( mScreenHelper->screenDpi() / 96, mScreenHelper->screenDpi() / 96 );
634 mView->centerOn( point );
637void QgsModelDesignerDialog::zoomFull()
639 QRectF totalRect = mView->scene()->itemsBoundingRect();
640 totalRect.adjust( -10, -10, 10, 10 );
641 mView->fitInView( totalRect, Qt::KeepAspectRatio );
644void QgsModelDesignerDialog::newModel()
646 if ( !checkForUnsavedChanges() )
649 std::unique_ptr< QgsProcessingModelAlgorithm > alg = std::make_unique< QgsProcessingModelAlgorithm >();
651 setModel( alg.release() );
654void QgsModelDesignerDialog::exportToImage()
657 QString lastExportDir = settings.
value( QStringLiteral(
"lastModelDesignerExportDir" ), QDir::homePath(),
QgsSettings::App ).toString();
659 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Image" ),
661 tr(
"PNG files (*.png *.PNG)" ) );
662 if ( filename.isEmpty() )
667 const QFileInfo saveFileInfo( filename );
670 repaintModel(
false );
672 QRectF totalRect = mView->scene()->itemsBoundingRect();
673 totalRect.adjust( -10, -10, 10, 10 );
674 const QRectF imageRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
676 QImage img( totalRect.width(), totalRect.height(),
677 QImage::Format_ARGB32_Premultiplied );
678 img.fill( Qt::white );
680 painter.setRenderHint( QPainter::Antialiasing );
681 painter.begin( &img );
682 mView->scene()->render( &painter, imageRect, totalRect );
685 img.save( filename );
687 mMessageBar->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 );
688 repaintModel(
true );
691void QgsModelDesignerDialog::exportToPdf()
694 QString lastExportDir = settings.
value( QStringLiteral(
"lastModelDesignerExportDir" ), QDir::homePath(),
QgsSettings::App ).toString();
696 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as PDF" ),
698 tr(
"PDF files (*.pdf *.PDF)" ) );
699 if ( filename.isEmpty() )
704 const QFileInfo saveFileInfo( filename );
707 repaintModel(
false );
709 QRectF totalRect = mView->scene()->itemsBoundingRect();
710 totalRect.adjust( -10, -10, 10, 10 );
711 const QRectF printerRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
714 printer.setOutputFormat( QPrinter::PdfFormat );
715 printer.setOutputFileName( filename );
717 const double scaleFactor = 96 / 25.4;
719 QPageLayout pageLayout( QPageSize( totalRect.size() / scaleFactor, QPageSize::Millimeter ),
720 QPageLayout::Portrait,
721 QMarginsF( 0, 0, 0, 0 ) );
722 pageLayout.setMode( QPageLayout::FullPageMode );
723 printer.setPageLayout( pageLayout );
725 printer.setFullPage(
true );
727 QPainter painter( &printer );
728 mView->scene()->render( &painter, printerRect, totalRect );
731 mMessageBar->pushMessage( QString(), tr(
"Successfully exported model as PDF to <a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( filename ).toString(),
732 QDir::toNativeSeparators( filename ) ), Qgis::MessageLevel::Success, 0 );
733 repaintModel(
true );
736void QgsModelDesignerDialog::exportToSvg()
739 QString lastExportDir = settings.
value( QStringLiteral(
"lastModelDesignerExportDir" ), QDir::homePath(),
QgsSettings::App ).toString();
741 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as SVG" ),
743 tr(
"SVG files (*.svg *.SVG)" ) );
744 if ( filename.isEmpty() )
749 const QFileInfo saveFileInfo( filename );
752 repaintModel(
false );
754 QRectF totalRect = mView->scene()->itemsBoundingRect();
755 totalRect.adjust( -10, -10, 10, 10 );
756 const QRectF svgRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
759 svg.setFileName( filename );
760 svg.setSize( QSize( totalRect.width(), totalRect.height() ) );
761 svg.setViewBox( svgRect );
762 svg.setTitle( mModel->displayName() );
764 QPainter painter( &svg );
765 mView->scene()->render( &painter, svgRect, totalRect );
768 mMessageBar->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 );
769 repaintModel(
true );
772void QgsModelDesignerDialog::exportAsPython()
775 QString lastExportDir = settings.
value( QStringLiteral(
"lastModelDesignerExportDir" ), QDir::homePath(),
QgsSettings::App ).toString();
777 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Python Script" ),
779 tr(
"Processing scripts (*.py *.PY)" ) );
780 if ( filename.isEmpty() )
785 const QFileInfo saveFileInfo( filename );
790 QFile outFile( filename );
791 if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
795 QTextStream fout( &outFile );
799 mMessageBar->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 );
802void QgsModelDesignerDialog::toggleComments(
bool show )
806 repaintModel(
true );
809void QgsModelDesignerDialog::updateWindowTitle()
811 QString title = tr(
"Model Designer" );
812 if ( !mModel->name().isEmpty() )
813 title = QStringLiteral(
"%1 - %2" ).arg( title, mModel->name() );
816 title.prepend(
'*' );
818 setWindowTitle( title );
821void QgsModelDesignerDialog::deleteSelected()
823 QList< QgsModelComponentGraphicItem * > items = mScene->selectedComponentItems();
827 if ( items.size() == 1 )
829 items.at( 0 )->deleteComponent();
833 std::sort( items.begin(), items.end(), []( QgsModelComponentGraphicItem * p1, QgsModelComponentGraphicItem * p2 )
836 if ( dynamic_cast< QgsModelCommentGraphicItem *>( p1 ) )
838 else if ( dynamic_cast< QgsModelCommentGraphicItem *>( p2 ) )
840 else if ( dynamic_cast< QgsModelGroupBoxGraphicItem *>( p1 ) )
842 else if ( dynamic_cast< QgsModelGroupBoxGraphicItem *>( p2 ) )
844 else if ( dynamic_cast< QgsModelOutputGraphicItem *>( p1 ) )
846 else if ( dynamic_cast< QgsModelOutputGraphicItem *>( p2 ) )
848 else if ( dynamic_cast< QgsModelChildAlgorithmGraphicItem *>( p1 ) )
850 else if ( dynamic_cast< QgsModelChildAlgorithmGraphicItem *>( p2 ) )
856 beginUndoCommand( tr(
"Delete Components" ) );
858 QVariant prevState = mModel->toVariant();
859 mBlockUndoCommands++;
860 mBlockRepaints =
true;
862 while ( !items.empty() )
864 QgsModelComponentGraphicItem *toDelete =
nullptr;
865 for ( QgsModelComponentGraphicItem *item : items )
867 if ( item->canDeleteComponent() )
880 toDelete->deleteComponent();
881 items.removeAll( toDelete );
886 mModel->loadVariant( prevState );
887 QMessageBox::warning(
nullptr, QObject::tr(
"Could not remove components" ),
888 QObject::tr(
"Components depend on the selected items.\n"
889 "Try to remove them before trying deleting these components." ) );
890 mBlockUndoCommands--;
891 mActiveCommand.reset();
895 mBlockUndoCommands--;
899 mBlockRepaints =
false;
903void QgsModelDesignerDialog::populateZoomToMenu()
906 for (
const QgsProcessingModelGroupBox &box : model()->groupBoxes() )
908 if ( QgsModelComponentGraphicItem *item = mScene->groupBoxItem( box.uuid() ) )
910 QAction *zoomAction =
new QAction( box.description(), mGroupMenu );
911 connect( zoomAction, &QAction::triggered,
this, [ = ]
913 QRectF groupRect = item->mapToScene( item->boundingRect() ).boundingRect();
914 groupRect.adjust( -10, -10, 10, 10 );
915 mView->fitInView( groupRect, Qt::KeepAspectRatio );
916 mView->centerOn( item );
918 mGroupMenu->addAction( zoomAction );
923void QgsModelDesignerDialog::setPanelVisibility(
bool hidden )
925 const QList<QDockWidget *> docks = findChildren<QDockWidget *>();
926 const QList<QTabBar *> tabBars = findChildren<QTabBar *>();
930 mPanelStatus.clear();
932 for ( QDockWidget *dock : docks )
934 mPanelStatus.insert( dock->windowTitle(), PanelStatus( dock->isVisible(),
false ) );
935 dock->setVisible(
false );
939 for ( QTabBar *tabBar : tabBars )
941 QString currentTabTitle = tabBar->tabText( tabBar->currentIndex() );
942 mPanelStatus[ currentTabTitle ].isActive =
true;
948 for ( QDockWidget *dock : docks )
950 if ( mPanelStatus.contains( dock->windowTitle() ) )
952 dock->setVisible( mPanelStatus.value( dock->windowTitle() ).isVisible );
957 for ( QTabBar *tabBar : tabBars )
960 for (
int i = 0; i < tabBar->count(); ++i )
962 QString tabTitle = tabBar->tabText( i );
963 if ( mPanelStatus.contains( tabTitle ) && mPanelStatus.value( tabTitle ).isActive )
965 tabBar->setCurrentIndex( i );
969 mPanelStatus.clear();
973void QgsModelDesignerDialog::editHelp()
975 QgsProcessingHelpEditorDialog dialog(
this );
976 dialog.setWindowTitle( tr(
"Edit Model Help" ) );
977 dialog.setAlgorithm( mModel.get() );
980 beginUndoCommand( tr(
"Edit Model Help" ) );
981 mModel->setHelpContent( dialog.helpContent() );
986void QgsModelDesignerDialog::validate()
989 if ( model()->validate( issues ) )
991 mMessageBar->pushSuccess( QString(), tr(
"Model is valid!" ) );
996 QPushButton *detailsButton =
new QPushButton( tr(
"Details" ) );
997 connect( detailsButton, &QPushButton::clicked, detailsButton, [ = ]
1000 dialog->
setTitle( tr(
"Model is Invalid" ) );
1002 QString longMessage = tr(
"<p>This model is not valid:</p>" ) + QStringLiteral(
"<ul>" );
1003 for (
const QString &issue : issues )
1005 longMessage += QStringLiteral(
"<li>%1</li>" ).arg( issue );
1007 longMessage += QLatin1String(
"</ul>" );
1012 messageWidget->layout()->addWidget( detailsButton );
1013 mMessageBar->clearWidgets();
1014 mMessageBar->pushWidget( messageWidget, Qgis::MessageLevel::Warning, 0 );
1018void QgsModelDesignerDialog::reorderInputs()
1020 QgsModelInputReorderDialog dlg(
this );
1021 dlg.setModel( mModel.get() );
1024 const QStringList inputOrder = dlg.inputOrder();
1025 beginUndoCommand( tr(
"Reorder Inputs" ) );
1026 mModel->setParameterOrder( inputOrder );
1031bool QgsModelDesignerDialog::isDirty()
const
1033 return mHasChanged && mUndoStack->index() != -1;
1036void QgsModelDesignerDialog::fillInputsTree()
1039 std::unique_ptr< QTreeWidgetItem > parametersItem = std::make_unique< QTreeWidgetItem >();
1040 parametersItem->setText( 0, tr(
"Parameters" ) );
1044 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
1051 std::unique_ptr< QTreeWidgetItem > paramItem = std::make_unique< QTreeWidgetItem >();
1052 paramItem->setText( 0, param->name() );
1053 paramItem->setData( 0, Qt::UserRole, param->id() );
1054 paramItem->setIcon( 0, icon );
1055 paramItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled );
1056 paramItem->setToolTip( 0, param->description() );
1057 parametersItem->addChild( paramItem.release() );
1060 mInputsTreeWidget->addTopLevelItem( parametersItem.release() );
1061 mInputsTreeWidget->topLevelItem( 0 )->setExpanded(
true );
1069QgsModelChildDependenciesWidget::QgsModelChildDependenciesWidget( QWidget *parent, QgsProcessingModelAlgorithm *model,
const QString &childId )
1072 , mChildId( childId )
1074 QHBoxLayout *hl =
new QHBoxLayout();
1075 hl->setContentsMargins( 0, 0, 0, 0 );
1077 mLineEdit =
new QLineEdit();
1078 mLineEdit->setEnabled(
false );
1079 hl->addWidget( mLineEdit, 1 );
1081 mToolButton =
new QToolButton();
1082 mToolButton->setText( QString( QChar( 0x2026 ) ) );
1083 hl->addWidget( mToolButton );
1087 mLineEdit->setText( tr(
"%1 dependencies selected" ).arg( 0 ) );
1089 connect( mToolButton, &QToolButton::clicked,
this, &QgsModelChildDependenciesWidget::showDialog );
1092void QgsModelChildDependenciesWidget::setValue(
const QList<QgsProcessingModelChildDependency> &value )
1096 updateSummaryText();
1099void QgsModelChildDependenciesWidget::showDialog()
1101 const QList<QgsProcessingModelChildDependency> available = mModel->availableDependenciesForChildAlgorithm( mChildId );
1103 QVariantList availableOptions;
1104 for (
const QgsProcessingModelChildDependency &dep : available )
1105 availableOptions << QVariant::fromValue( dep );
1106 QVariantList selectedOptions;
1107 for (
const QgsProcessingModelChildDependency &dep : mValue )
1108 selectedOptions << QVariant::fromValue( dep );
1113 QgsProcessingMultipleSelectionPanelWidget *widget =
new QgsProcessingMultipleSelectionPanelWidget( availableOptions, selectedOptions );
1114 widget->setPanelTitle( tr(
"Algorithm Dependencies" ) );
1116 widget->setValueFormatter( [ = ](
const QVariant & v ) -> QString
1118 const QgsProcessingModelChildDependency dep = v.value< QgsProcessingModelChildDependency >();
1120 const QString description = mModel->childAlgorithm( dep.childId ).description();
1121 if ( dep.conditionalBranch.isEmpty() )
1124 return tr(
"Condition “%1” from algorithm “%2”" ).arg( dep.conditionalBranch, description );
1127 connect( widget, &QgsProcessingMultipleSelectionPanelWidget::selectionChanged,
this, [ = ]()
1129 QList< QgsProcessingModelChildDependency > res;
1130 for (
const QVariant &v : widget->selectedOptions() )
1132 res << v.value< QgsProcessingModelChildDependency >();
1141void QgsModelChildDependenciesWidget::updateSummaryText()
1143 mLineEdit->setText( tr(
"%n dependencies selected",
nullptr, mValue.count() ) );
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.
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...
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.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
A generic message view for displaying QGIS messages.
void setTitle(const QString &title) override
Sets title for the messages.
void setMessage(const QString &message, MessageType msgType) override
Sets message, it won't be displayed until.
void showMessage(bool blocking=true) override
display the message to the user and deletes itself
Makes metadata of processing parameters available.
@ ExposeToModeler
Is this parameter available in the modeler. Is set to on by default.
QList< QgsProcessingParameterType * > parameterTypes() const
Returns a list with all known parameter types.
@ PythonQgsProcessingAlgorithmSubclass
Full Python QgsProcessingAlgorithm subclass.
A utility class for dynamic handling of changes to screen properties.
This class is a composition of two QSettings instances:
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.