42#include <QKeySequence>
45#include <QSvgGenerator>
53#include <QActionGroup>
58QgsModelerToolboxModel::QgsModelerToolboxModel( QObject *parent )
64Qt::ItemFlags QgsModelerToolboxModel::flags(
const QModelIndex &index )
const
66 Qt::ItemFlags f = QgsProcessingToolboxProxyModel::flags( index );
67 const QModelIndex sourceIndex = mapToSource( index );
68 if ( toolboxModel()->isAlgorithm( sourceIndex ) )
70 f = f | Qt::ItemIsDragEnabled;
75Qt::DropActions QgsModelerToolboxModel::supportedDragActions()
const
77 return Qt::CopyAction;
82QgsModelDesignerDialog::QgsModelDesignerDialog( QWidget *parent, Qt::WindowFlags flags )
83 : QMainWindow( parent, flags )
84 , mToolsActionGroup( new QActionGroup( this ) )
90 setAttribute( Qt::WA_DeleteOnClose );
91 setDockOptions( dockOptions() | QMainWindow::GroupedDragging );
92 setWindowFlags( Qt::WindowMinimizeButtonHint |
93 Qt::WindowMaximizeButtonHint |
94 Qt::WindowCloseButtonHint );
98 mModel = std::make_unique< QgsProcessingModelAlgorithm >();
101 mUndoStack =
new QUndoStack(
this );
102 connect( mUndoStack, &QUndoStack::indexChanged,
this, [ = ]
104 if ( mIgnoreUndoStackChanges )
107 mBlockUndoCommands++;
108 updateVariablesGui();
109 mGroupEdit->setText( mModel->group() );
110 mNameEdit->setText( mModel->displayName() );
111 mBlockUndoCommands--;
115 mPropertiesDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable );
116 mInputsDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable );
117 mAlgorithmsDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable );
118 mVariablesDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
120 mAlgorithmsTree->header()->setVisible(
false );
121 mAlgorithmSearchEdit->setShowSearchIcon(
true );
122 mAlgorithmSearchEdit->setPlaceholderText( tr(
"Search…" ) );
123 connect( mAlgorithmSearchEdit, &QgsFilterLineEdit::textChanged, mAlgorithmsTree, &QgsProcessingToolboxTreeView::setFilterString );
125 mInputsTreeWidget->header()->setVisible(
false );
126 mInputsTreeWidget->setAlternatingRowColors(
true );
127 mInputsTreeWidget->setDragDropMode( QTreeWidget::DragOnly );
128 mInputsTreeWidget->setDropIndicatorShown(
true );
130 mNameEdit->setPlaceholderText( tr(
"Enter model name here" ) );
131 mGroupEdit->setPlaceholderText( tr(
"Enter group name here" ) );
134 mMessageBar->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Fixed );
135 mainLayout->insertWidget( 0, mMessageBar );
137 mView->setAcceptDrops(
true );
140 connect( mActionClose, &QAction::triggered,
this, &QWidget::close );
141 connect( mActionNew, &QAction::triggered,
this, &QgsModelDesignerDialog::newModel );
142 connect( mActionZoomIn, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomIn );
143 connect( mActionZoomOut, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomOut );
144 connect( mActionZoomActual, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomActual );
145 connect( mActionZoomToItems, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomFull );
146 connect( mActionExportImage, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToImage );
147 connect( mActionExportPdf, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToPdf );
148 connect( mActionExportSvg, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToSvg );
149 connect( mActionExportPython, &QAction::triggered,
this, &QgsModelDesignerDialog::exportAsPython );
150 connect( mActionSave, &QAction::triggered,
this, [ = ] { saveModel(
false ); } );
151 connect( mActionSaveAs, &QAction::triggered,
this, [ = ] { saveModel(
true ); } );
152 connect( mActionDeleteComponents, &QAction::triggered,
this, &QgsModelDesignerDialog::deleteSelected );
153 connect( mActionSnapSelected, &QAction::triggered, mView, &QgsModelGraphicsView::snapSelected );
154 connect( mActionValidate, &QAction::triggered,
this, &QgsModelDesignerDialog::validate );
155 connect( mActionReorderInputs, &QAction::triggered,
this, &QgsModelDesignerDialog::reorderInputs );
156 connect( mActionReorderOutputs, &QAction::triggered,
this, &QgsModelDesignerDialog::reorderOutputs );
157 connect( mActionEditHelp, &QAction::triggered,
this, &QgsModelDesignerDialog::editHelp );
158 connect( mReorderInputsButton, &QPushButton::clicked,
this, &QgsModelDesignerDialog::reorderInputs );
160 mActionSnappingEnabled->setChecked( settings.
value( QStringLiteral(
"/Processing/Modeler/enableSnapToGrid" ),
false ).toBool() );
161 connect( mActionSnappingEnabled, &QAction::toggled,
this, [ = ](
bool enabled )
163 mView->snapper()->setSnapToGrid( enabled );
164 QgsSettings().
setValue( QStringLiteral(
"/Processing/Modeler/enableSnapToGrid" ), enabled );
166 mView->snapper()->setSnapToGrid( mActionSnappingEnabled->isChecked() );
168 connect( mActionSelectAll, &QAction::triggered,
this, [ = ]
173 QStringList docksTitle = settings.
value( QStringLiteral(
"ModelDesigner/hiddenDocksTitle" ), QStringList(),
QgsSettings::App ).toStringList();
174 QStringList docksActive = settings.
value( QStringLiteral(
"ModelDesigner/hiddenDocksActive" ), QStringList(),
QgsSettings::App ).toStringList();
175 if ( !docksTitle.isEmpty() )
177 for (
const auto &title : docksTitle )
179 mPanelStatus.insert( title, PanelStatus(
true, docksActive.contains( title ) ) );
182 mActionHidePanels->setChecked( !docksTitle.isEmpty() );
183 connect( mActionHidePanels, &QAction::toggled,
this, &QgsModelDesignerDialog::setPanelVisibility );
185 mUndoAction = mUndoStack->createUndoAction(
this );
187 mUndoAction->setShortcuts( QKeySequence::Undo );
188 mRedoAction = mUndoStack->createRedoAction(
this );
190 mRedoAction->setShortcuts( QKeySequence::Redo );
192 mMenuEdit->insertAction( mActionDeleteComponents, mRedoAction );
193 mMenuEdit->insertAction( mActionDeleteComponents, mUndoAction );
194 mMenuEdit->insertSeparator( mActionDeleteComponents );
195 mToolbar->insertAction( mActionZoomIn, mUndoAction );
196 mToolbar->insertAction( mActionZoomIn, mRedoAction );
197 mToolbar->insertSeparator( mActionZoomIn );
199 mGroupMenu =
new QMenu( tr(
"Zoom To" ),
this );
200 mMenuView->insertMenu( mActionZoomIn, mGroupMenu );
201 connect( mGroupMenu, &QMenu::aboutToShow,
this, &QgsModelDesignerDialog::populateZoomToMenu );
205 mActionCut =
new QAction( tr(
"Cu&t" ),
this );
206 mActionCut->setShortcuts( QKeySequence::Cut );
207 mActionCut->setStatusTip( tr(
"Cut" ) );
209 connect( mActionCut, &QAction::triggered,
this, [ = ]
211 mView->copySelectedItems( QgsModelGraphicsView::ClipboardCut );
214 mActionCopy =
new QAction( tr(
"&Copy" ),
this );
215 mActionCopy->setShortcuts( QKeySequence::Copy );
216 mActionCopy->setStatusTip( tr(
"Copy" ) );
218 connect( mActionCopy, &QAction::triggered,
this, [ = ]
220 mView->copySelectedItems( QgsModelGraphicsView::ClipboardCopy );
223 mActionPaste =
new QAction( tr(
"&Paste" ),
this );
224 mActionPaste->setShortcuts( QKeySequence::Paste );
225 mActionPaste->setStatusTip( tr(
"Paste" ) );
227 connect( mActionPaste, &QAction::triggered,
this, [ = ]
229 mView->pasteItems( QgsModelGraphicsView::PasteModeCursor );
231 mMenuEdit->insertAction( mActionDeleteComponents, mActionCut );
232 mMenuEdit->insertAction( mActionDeleteComponents, mActionCopy );
233 mMenuEdit->insertAction( mActionDeleteComponents, mActionPaste );
234 mMenuEdit->insertSeparator( mActionDeleteComponents );
236 mAlgorithmsModel =
new QgsModelerToolboxModel(
this );
237 mAlgorithmsTree->setToolboxProxyModel( mAlgorithmsModel );
240 if ( settings.
value( QStringLiteral(
"Processing/Configuration/SHOW_ALGORITHMS_KNOWN_ISSUES" ),
false ).toBool() )
244 mAlgorithmsTree->setFilters( filters );
245 mAlgorithmsTree->setDragDropMode( QTreeWidget::DragOnly );
246 mAlgorithmsTree->setDropIndicatorShown(
true );
248 connect( mView, &QgsModelGraphicsView::algorithmDropped,
this, [ = ](
const QString & algorithmId,
const QPointF & pos )
250 addAlgorithm( algorithmId, pos );
252 connect( mAlgorithmsTree, &QgsProcessingToolboxTreeView::doubleClicked,
this, [ = ]()
254 if ( mAlgorithmsTree->selectedAlgorithm() )
255 addAlgorithm( mAlgorithmsTree->selectedAlgorithm()->id(), QPointF() );
257 connect( mInputsTreeWidget, &QgsModelDesignerInputsTreeWidget::doubleClicked,
this, [ = ](
const QModelIndex & )
259 const QString parameterType = mInputsTreeWidget->currentItem()->data( 0, Qt::UserRole ).toString();
260 addInput( parameterType, QPointF() );
263 connect( mView, &QgsModelGraphicsView::inputDropped,
this, &QgsModelDesignerDialog::addInput );
266 QShortcut *ctrlEquals =
new QShortcut( QKeySequence( QStringLiteral(
"Ctrl+=" ) ),
this );
267 connect( ctrlEquals, &QShortcut::activated,
this, &QgsModelDesignerDialog::zoomIn );
270 mUndoDock->setObjectName( QStringLiteral(
"UndoDock" ) );
271 mUndoView =
new QUndoView( mUndoStack,
this );
272 mUndoDock->setWidget( mUndoView );
273 mUndoDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
274 addDockWidget( Qt::DockWidgetArea::LeftDockWidgetArea, mUndoDock );
276 tabifyDockWidget( mUndoDock, mPropertiesDock );
277 tabifyDockWidget( mVariablesDock, mPropertiesDock );
278 mPropertiesDock->raise();
279 tabifyDockWidget( mInputsDock, mAlgorithmsDock );
280 mInputsDock->raise();
286 beginUndoCommand( tr(
"Change Model Variables" ) );
287 mModel->setVariables( mVariablesEditor->variablesInActiveScope() );
291 connect( mNameEdit, &QLineEdit::textChanged,
this, [ = ](
const QString & name )
295 beginUndoCommand( tr(
"Change Model Name" ), NameChanged );
296 mModel->setName( name );
301 connect( mGroupEdit, &QLineEdit::textChanged,
this, [ = ](
const QString & group )
305 beginUndoCommand( tr(
"Change Model Group" ), GroupChanged );
306 mModel->setGroup( group );
313 QToolButton *toolbuttonExportToScript =
new QToolButton();
314 toolbuttonExportToScript->setPopupMode( QToolButton::InstantPopup );
315 toolbuttonExportToScript->addAction( mActionExportAsScriptAlgorithm );
316 toolbuttonExportToScript->setDefaultAction( mActionExportAsScriptAlgorithm );
317 mToolbar->insertWidget( mActionExportImage, toolbuttonExportToScript );
318 connect( mActionExportAsScriptAlgorithm, &QAction::triggered,
this, &QgsModelDesignerDialog::exportAsScriptAlgorithm );
320 mActionShowComments->setChecked( settings.
value( QStringLiteral(
"/Processing/Modeler/ShowComments" ),
true ).toBool() );
321 connect( mActionShowComments, &QAction::toggled,
this, &QgsModelDesignerDialog::toggleComments );
324 mPanTool->setAction( mActionPan );
326 mToolsActionGroup->addAction( mActionPan );
327 connect( mActionPan, &QAction::triggered, mPanTool, [ = ] { mView->setTool( mPanTool ); } );
330 mSelectTool->setAction( mActionSelectMoveItem );
332 mToolsActionGroup->addAction( mActionSelectMoveItem );
333 connect( mActionSelectMoveItem, &QAction::triggered, mSelectTool, [ = ] { mView->setTool( mSelectTool ); } );
335 mView->setTool( mSelectTool );
338 connect( mView, &QgsModelGraphicsView::macroCommandStarted,
this, [ = ](
const QString & text )
340 mIgnoreUndoStackChanges++;
341 mUndoStack->beginMacro( text );
342 mIgnoreUndoStackChanges--;
344 connect( mView, &QgsModelGraphicsView::macroCommandEnded,
this, [ = ]
346 mIgnoreUndoStackChanges++;
347 mUndoStack->endMacro();
348 mIgnoreUndoStackChanges--;
350 connect( mView, &QgsModelGraphicsView::beginCommand,
this, [ = ](
const QString & text )
352 beginUndoCommand( text );
354 connect( mView, &QgsModelGraphicsView::endCommand,
this, [ = ]
358 connect( mView, &QgsModelGraphicsView::deleteSelectedItems,
this, [ = ]
363 connect( mActionAddGroupBox, &QAction::triggered,
this, [ = ]
365 const QPointF viewCenter = mView->mapToScene( mView->viewport()->rect().center() );
366 QgsProcessingModelGroupBox group;
367 group.setPosition( viewCenter );
368 group.setDescription( tr(
"New Group" ) );
370 beginUndoCommand( tr(
"Add Group Box" ) );
371 model()->addGroupBox( group );
379 restoreState( settings.
value( QStringLiteral(
"ModelDesigner/state" ), QByteArray(),
QgsSettings::App ).toByteArray() );
382QgsModelDesignerDialog::~QgsModelDesignerDialog()
385 if ( !mPanelStatus.isEmpty() )
387 QStringList docksTitle;
388 QStringList docksActive;
390 for (
const auto &panel : mPanelStatus.toStdMap() )
392 if ( panel.second.isVisible )
393 docksTitle << panel.first;
394 if ( panel.second.isActive )
395 docksActive << panel.first;
409 mIgnoreUndoStackChanges++;
413void QgsModelDesignerDialog::closeEvent( QCloseEvent *event )
415 if ( checkForUnsavedChanges() )
421void QgsModelDesignerDialog::beginUndoCommand(
const QString &text,
int id )
423 if ( mBlockUndoCommands || !mUndoStack )
426 if ( mActiveCommand )
429 mActiveCommand = std::make_unique< QgsModelUndoCommand >( mModel.get(), text,
id );
432void QgsModelDesignerDialog::endUndoCommand()
434 if ( mBlockUndoCommands || !mActiveCommand || !mUndoStack )
437 mActiveCommand->saveAfterState();
438 mIgnoreUndoStackChanges++;
439 mUndoStack->push( mActiveCommand.release() );
440 mIgnoreUndoStackChanges--;
444QgsProcessingModelAlgorithm *QgsModelDesignerDialog::model()
449void QgsModelDesignerDialog::setModel( QgsProcessingModelAlgorithm *model )
451 mModel.reset( model );
453 mGroupEdit->setText( mModel->group() );
454 mNameEdit->setText( mModel->displayName() );
456 updateVariablesGui();
458 mView->centerOn( 0, 0 );
461 mIgnoreUndoStackChanges++;
463 mIgnoreUndoStackChanges--;
468void QgsModelDesignerDialog::loadModel(
const QString &path )
470 std::unique_ptr< QgsProcessingModelAlgorithm > alg = std::make_unique< QgsProcessingModelAlgorithm >();
471 if ( alg->fromFile( path ) )
474 alg->setSourceFilePath( path );
475 setModel( alg.release() );
479 QgsMessageLog::logMessage( tr(
"Could not load model %1" ).arg( path ), tr(
"Processing" ), Qgis::MessageLevel::Critical );
480 QMessageBox::critical(
this, tr(
"Open Model" ), tr(
"The selected model could not be loaded.\n"
481 "See the log for more information." ) );
485void QgsModelDesignerDialog::setModelScene( QgsModelGraphicsScene *scene )
487 QgsModelGraphicsScene *oldScene = mScene;
490 mScene->setParent(
this );
491 mScene->setChildAlgorithmResults( mChildResults );
492 mScene->setModel( mModel.get() );
493 mScene->setMessageBar( mMessageBar );
495 const QPointF center = mView->mapToScene( mView->viewport()->rect().center() );
496 mView->setModelScene( mScene );
498 mSelectTool->resetCache();
499 mSelectTool->setScene( mScene );
501 connect( mScene, &QgsModelGraphicsScene::rebuildRequired,
this, [ = ]
503 if ( mBlockRepaints )
508 connect( mScene, &QgsModelGraphicsScene::componentAboutToChange,
this, [ = ](
const QString & description,
int id ) { beginUndoCommand( description,
id ); } );
509 connect( mScene, &QgsModelGraphicsScene::componentChanged,
this, [ = ] { endUndoCommand(); } );
511 mView->centerOn( center );
514 oldScene->deleteLater();
517void QgsModelDesignerDialog::activate()
521 setWindowState( windowState() & ~Qt::WindowMinimized );
525void QgsModelDesignerDialog::updateVariablesGui()
527 mBlockUndoCommands++;
529 std::unique_ptr< QgsExpressionContextScope > variablesScope = std::make_unique< QgsExpressionContextScope >( tr(
"Model Variables" ) );
530 const QVariantMap modelVars = mModel->variables();
531 for (
auto it = modelVars.constBegin(); it != modelVars.constEnd(); ++it )
533 variablesScope->setVariable( it.key(), it.value() );
536 variablesContext.
appendScope( variablesScope.release() );
537 mVariablesEditor->setContext( &variablesContext );
538 mVariablesEditor->setEditableScopeIndex( 0 );
540 mBlockUndoCommands--;
543void QgsModelDesignerDialog::setDirty(
bool dirty )
549bool QgsModelDesignerDialog::validateSave( SaveAction action )
553 case QgsModelDesignerDialog::SaveAction::SaveAsFile:
555 case QgsModelDesignerDialog::SaveAction::SaveInProject:
556 if ( mNameEdit->text().trimmed().isEmpty() )
558 mMessageBar->pushWarning( QString(), tr(
"Please enter a model name before saving" ) );
567bool QgsModelDesignerDialog::checkForUnsavedChanges()
571 QMessageBox::StandardButton ret = QMessageBox::question(
this, tr(
"Save Model?" ),
572 tr(
"There are unsaved changes in this model. Do you want to keep those?" ),
573 QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Discard, QMessageBox::Cancel );
576 case QMessageBox::Save:
577 return saveModel(
false );
579 case QMessageBox::Discard:
592void QgsModelDesignerDialog::setLastRunChildAlgorithmResults(
const QVariantMap &results )
594 mChildResults = results;
596 mScene->setChildAlgorithmResults( mChildResults );
599void QgsModelDesignerDialog::setLastRunChildAlgorithmInputs(
const QVariantMap &inputs )
601 mChildInputs = inputs;
603 mScene->setChildAlgorithmInputs( mChildInputs );
606void QgsModelDesignerDialog::setModelName(
const QString &name )
608 mNameEdit->setText( name );
611void QgsModelDesignerDialog::zoomIn()
613 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
614 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
616 const double factor = settings.
value( QStringLiteral(
"/qgis/zoom_favor" ), 2.0 ).toDouble();
617 mView->scale( factor, factor );
618 mView->centerOn( point );
621void QgsModelDesignerDialog::zoomOut()
623 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
624 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
626 const double factor = 1.0 / settings.
value( QStringLiteral(
"/qgis/zoom_favor" ), 2.0 ).toDouble();
627 mView->scale( factor, factor );
628 mView->centerOn( point );
631void QgsModelDesignerDialog::zoomActual()
633 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
634 mView->resetTransform();
635 mView->scale( mScreenHelper->screenDpi() / 96, mScreenHelper->screenDpi() / 96 );
636 mView->centerOn( point );
639void QgsModelDesignerDialog::zoomFull()
641 QRectF totalRect = mView->scene()->itemsBoundingRect();
642 totalRect.adjust( -10, -10, 10, 10 );
643 mView->fitInView( totalRect, Qt::KeepAspectRatio );
646void QgsModelDesignerDialog::newModel()
648 if ( !checkForUnsavedChanges() )
651 std::unique_ptr< QgsProcessingModelAlgorithm > alg = std::make_unique< QgsProcessingModelAlgorithm >();
653 setModel( alg.release() );
656void QgsModelDesignerDialog::exportToImage()
659 QString lastExportDir = settings.
value( QStringLiteral(
"lastModelDesignerExportDir" ), QDir::homePath(),
QgsSettings::App ).toString();
661 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Image" ),
663 tr(
"PNG files (*.png *.PNG)" ) );
664 if ( filename.isEmpty() )
669 const QFileInfo saveFileInfo( filename );
672 repaintModel(
false );
674 QRectF totalRect = mView->scene()->itemsBoundingRect();
675 totalRect.adjust( -10, -10, 10, 10 );
676 const QRectF imageRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
678 QImage img( totalRect.width(), totalRect.height(),
679 QImage::Format_ARGB32_Premultiplied );
680 img.fill( Qt::white );
682 painter.setRenderHint( QPainter::Antialiasing );
683 painter.begin( &img );
684 mView->scene()->render( &painter, imageRect, totalRect );
687 img.save( filename );
689 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 );
690 repaintModel(
true );
693void QgsModelDesignerDialog::exportToPdf()
696 QString lastExportDir = settings.
value( QStringLiteral(
"lastModelDesignerExportDir" ), QDir::homePath(),
QgsSettings::App ).toString();
698 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as PDF" ),
700 tr(
"PDF files (*.pdf *.PDF)" ) );
701 if ( filename.isEmpty() )
706 const QFileInfo saveFileInfo( filename );
709 repaintModel(
false );
711 QRectF totalRect = mView->scene()->itemsBoundingRect();
712 totalRect.adjust( -10, -10, 10, 10 );
713 const QRectF printerRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
716 printer.setOutputFormat( QPrinter::PdfFormat );
717 printer.setOutputFileName( filename );
719 const double scaleFactor = 96 / 25.4;
721 QPageLayout pageLayout( QPageSize( totalRect.size() / scaleFactor, QPageSize::Millimeter ),
722 QPageLayout::Portrait,
723 QMarginsF( 0, 0, 0, 0 ) );
724 pageLayout.setMode( QPageLayout::FullPageMode );
725 printer.setPageLayout( pageLayout );
727 printer.setFullPage(
true );
729 QPainter painter( &printer );
730 mView->scene()->render( &painter, printerRect, totalRect );
733 mMessageBar->pushMessage( QString(), tr(
"Successfully exported model as PDF to <a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( filename ).toString(),
734 QDir::toNativeSeparators( filename ) ), Qgis::MessageLevel::Success, 0 );
735 repaintModel(
true );
738void QgsModelDesignerDialog::exportToSvg()
741 QString lastExportDir = settings.
value( QStringLiteral(
"lastModelDesignerExportDir" ), QDir::homePath(),
QgsSettings::App ).toString();
743 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as SVG" ),
745 tr(
"SVG files (*.svg *.SVG)" ) );
746 if ( filename.isEmpty() )
751 const QFileInfo saveFileInfo( filename );
754 repaintModel(
false );
756 QRectF totalRect = mView->scene()->itemsBoundingRect();
757 totalRect.adjust( -10, -10, 10, 10 );
758 const QRectF svgRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
761 svg.setFileName( filename );
762 svg.setSize( QSize( totalRect.width(), totalRect.height() ) );
763 svg.setViewBox( svgRect );
764 svg.setTitle( mModel->displayName() );
766 QPainter painter( &svg );
767 mView->scene()->render( &painter, svgRect, totalRect );
770 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 );
771 repaintModel(
true );
774void QgsModelDesignerDialog::exportAsPython()
777 QString lastExportDir = settings.
value( QStringLiteral(
"lastModelDesignerExportDir" ), QDir::homePath(),
QgsSettings::App ).toString();
779 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Python Script" ),
781 tr(
"Processing scripts (*.py *.PY)" ) );
782 if ( filename.isEmpty() )
787 const QFileInfo saveFileInfo( filename );
792 QFile outFile( filename );
793 if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
797 QTextStream fout( &outFile );
801 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 );
804void QgsModelDesignerDialog::toggleComments(
bool show )
808 repaintModel(
true );
811void QgsModelDesignerDialog::updateWindowTitle()
813 QString title = tr(
"Model Designer" );
814 if ( !mModel->name().isEmpty() )
815 title = QStringLiteral(
"%1 - %2" ).arg( title, mModel->name() );
818 title.prepend(
'*' );
820 setWindowTitle( title );
823void QgsModelDesignerDialog::deleteSelected()
825 QList< QgsModelComponentGraphicItem * > items = mScene->selectedComponentItems();
829 if ( items.size() == 1 )
831 items.at( 0 )->deleteComponent();
835 std::sort( items.begin(), items.end(), []( QgsModelComponentGraphicItem * p1, QgsModelComponentGraphicItem * p2 )
838 if ( dynamic_cast< QgsModelCommentGraphicItem *>( p1 ) )
840 else if ( dynamic_cast< QgsModelCommentGraphicItem *>( p2 ) )
842 else if ( dynamic_cast< QgsModelGroupBoxGraphicItem *>( p1 ) )
844 else if ( dynamic_cast< QgsModelGroupBoxGraphicItem *>( p2 ) )
846 else if ( dynamic_cast< QgsModelOutputGraphicItem *>( p1 ) )
848 else if ( dynamic_cast< QgsModelOutputGraphicItem *>( p2 ) )
850 else if ( dynamic_cast< QgsModelChildAlgorithmGraphicItem *>( p1 ) )
852 else if ( dynamic_cast< QgsModelChildAlgorithmGraphicItem *>( p2 ) )
858 beginUndoCommand( tr(
"Delete Components" ) );
860 QVariant prevState = mModel->toVariant();
861 mBlockUndoCommands++;
862 mBlockRepaints =
true;
864 while ( !items.empty() )
866 QgsModelComponentGraphicItem *toDelete =
nullptr;
867 for ( QgsModelComponentGraphicItem *item : items )
869 if ( item->canDeleteComponent() )
882 toDelete->deleteComponent();
883 items.removeAll( toDelete );
888 mModel->loadVariant( prevState );
889 QMessageBox::warning(
nullptr, QObject::tr(
"Could not remove components" ),
890 QObject::tr(
"Components depend on the selected items.\n"
891 "Try to remove them before trying deleting these components." ) );
892 mBlockUndoCommands--;
893 mActiveCommand.reset();
897 mBlockUndoCommands--;
901 mBlockRepaints =
false;
905void QgsModelDesignerDialog::populateZoomToMenu()
908 for (
const QgsProcessingModelGroupBox &box : model()->groupBoxes() )
910 if ( QgsModelComponentGraphicItem *item = mScene->groupBoxItem( box.uuid() ) )
912 QAction *zoomAction =
new QAction( box.description(), mGroupMenu );
913 connect( zoomAction, &QAction::triggered,
this, [ = ]
915 QRectF groupRect = item->mapToScene( item->boundingRect() ).boundingRect();
916 groupRect.adjust( -10, -10, 10, 10 );
917 mView->fitInView( groupRect, Qt::KeepAspectRatio );
918 mView->centerOn( item );
920 mGroupMenu->addAction( zoomAction );
925void QgsModelDesignerDialog::setPanelVisibility(
bool hidden )
927 const QList<QDockWidget *> docks = findChildren<QDockWidget *>();
928 const QList<QTabBar *> tabBars = findChildren<QTabBar *>();
932 mPanelStatus.clear();
934 for ( QDockWidget *dock : docks )
936 mPanelStatus.insert( dock->windowTitle(), PanelStatus( dock->isVisible(),
false ) );
937 dock->setVisible(
false );
941 for ( QTabBar *tabBar : tabBars )
943 QString currentTabTitle = tabBar->tabText( tabBar->currentIndex() );
944 mPanelStatus[ currentTabTitle ].isActive =
true;
950 for ( QDockWidget *dock : docks )
952 if ( mPanelStatus.contains( dock->windowTitle() ) )
954 dock->setVisible( mPanelStatus.value( dock->windowTitle() ).isVisible );
959 for ( QTabBar *tabBar : tabBars )
962 for (
int i = 0; i < tabBar->count(); ++i )
964 QString tabTitle = tabBar->tabText( i );
965 if ( mPanelStatus.contains( tabTitle ) && mPanelStatus.value( tabTitle ).isActive )
967 tabBar->setCurrentIndex( i );
971 mPanelStatus.clear();
975void QgsModelDesignerDialog::editHelp()
977 QgsProcessingHelpEditorDialog dialog(
this );
978 dialog.setWindowTitle( tr(
"Edit Model Help" ) );
979 dialog.setAlgorithm( mModel.get() );
982 beginUndoCommand( tr(
"Edit Model Help" ) );
983 mModel->setHelpContent( dialog.helpContent() );
988void QgsModelDesignerDialog::validate()
991 if ( model()->validate( issues ) )
993 mMessageBar->pushSuccess( QString(), tr(
"Model is valid!" ) );
998 QPushButton *detailsButton =
new QPushButton( tr(
"Details" ) );
999 connect( detailsButton, &QPushButton::clicked, detailsButton, [ = ]
1002 dialog->
setTitle( tr(
"Model is Invalid" ) );
1004 QString longMessage = tr(
"<p>This model is not valid:</p>" ) + QStringLiteral(
"<ul>" );
1005 for (
const QString &issue : issues )
1007 longMessage += QStringLiteral(
"<li>%1</li>" ).arg( issue );
1009 longMessage += QLatin1String(
"</ul>" );
1014 messageWidget->layout()->addWidget( detailsButton );
1015 mMessageBar->clearWidgets();
1016 mMessageBar->pushWidget( messageWidget, Qgis::MessageLevel::Warning, 0 );
1020void QgsModelDesignerDialog::reorderInputs()
1022 QgsModelInputReorderDialog dlg(
this );
1023 dlg.setModel( mModel.get() );
1026 const QStringList inputOrder = dlg.inputOrder();
1027 beginUndoCommand( tr(
"Reorder Inputs" ) );
1028 mModel->setParameterOrder( inputOrder );
1033void QgsModelDesignerDialog::reorderOutputs()
1035 QgsModelOutputReorderDialog dlg(
this );
1036 dlg.setModel( mModel.get() );
1039 const QStringList outputOrder = dlg.outputOrder();
1040 beginUndoCommand( tr(
"Reorder Outputs" ) );
1041 mModel->setOutputOrder( outputOrder );
1042 mModel->setOutputGroup( dlg.outputGroup() );
1047bool QgsModelDesignerDialog::isDirty()
const
1049 return mHasChanged && mUndoStack->index() != -1;
1052void QgsModelDesignerDialog::fillInputsTree()
1055 std::unique_ptr< QTreeWidgetItem > parametersItem = std::make_unique< QTreeWidgetItem >();
1056 parametersItem->setText( 0, tr(
"Parameters" ) );
1060 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
1067 std::unique_ptr< QTreeWidgetItem > paramItem = std::make_unique< QTreeWidgetItem >();
1068 paramItem->setText( 0, param->name() );
1069 paramItem->setData( 0, Qt::UserRole, param->id() );
1070 paramItem->setIcon( 0, icon );
1071 paramItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled );
1072 paramItem->setToolTip( 0, param->description() );
1073 parametersItem->addChild( paramItem.release() );
1076 mInputsTreeWidget->addTopLevelItem( parametersItem.release() );
1077 mInputsTreeWidget->topLevelItem( 0 )->setExpanded(
true );
1085QgsModelChildDependenciesWidget::QgsModelChildDependenciesWidget( QWidget *parent, QgsProcessingModelAlgorithm *model,
const QString &childId )
1088 , mChildId( childId )
1090 QHBoxLayout *hl =
new QHBoxLayout();
1091 hl->setContentsMargins( 0, 0, 0, 0 );
1093 mLineEdit =
new QLineEdit();
1094 mLineEdit->setEnabled(
false );
1095 hl->addWidget( mLineEdit, 1 );
1097 mToolButton =
new QToolButton();
1098 mToolButton->setText( QString( QChar( 0x2026 ) ) );
1099 hl->addWidget( mToolButton );
1103 mLineEdit->setText( tr(
"%1 dependencies selected" ).arg( 0 ) );
1105 connect( mToolButton, &QToolButton::clicked,
this, &QgsModelChildDependenciesWidget::showDialog );
1108void QgsModelChildDependenciesWidget::setValue(
const QList<QgsProcessingModelChildDependency> &value )
1112 updateSummaryText();
1115void QgsModelChildDependenciesWidget::showDialog()
1117 const QList<QgsProcessingModelChildDependency> available = mModel->availableDependenciesForChildAlgorithm( mChildId );
1119 QVariantList availableOptions;
1120 for (
const QgsProcessingModelChildDependency &dep : available )
1121 availableOptions << QVariant::fromValue( dep );
1122 QVariantList selectedOptions;
1123 for (
const QgsProcessingModelChildDependency &dep : mValue )
1124 selectedOptions << QVariant::fromValue( dep );
1129 QgsProcessingMultipleSelectionPanelWidget *widget =
new QgsProcessingMultipleSelectionPanelWidget( availableOptions, selectedOptions );
1130 widget->setPanelTitle( tr(
"Algorithm Dependencies" ) );
1132 widget->setValueFormatter( [ = ](
const QVariant & v ) -> QString
1134 const QgsProcessingModelChildDependency dep = v.value< QgsProcessingModelChildDependency >();
1136 const QString description = mModel->childAlgorithm( dep.childId ).description();
1137 if ( dep.conditionalBranch.isEmpty() )
1140 return tr(
"Condition “%1” from algorithm “%2”" ).arg( dep.conditionalBranch, description );
1143 connect( widget, &QgsProcessingMultipleSelectionPanelWidget::selectionChanged,
this, [ = ]()
1145 QList< QgsProcessingModelChildDependency > res;
1146 for (
const QVariant &v : widget->selectedOptions() )
1148 res << v.value< QgsProcessingModelChildDependency >();
1157void QgsModelChildDependenciesWidget::updateSummaryText()
1159 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.