39 #include <QDesktopWidget>
40 #include <QKeySequence>
41 #include <QFileDialog>
43 #include <QSvgGenerator>
44 #include <QToolButton>
45 #include <QCloseEvent>
46 #include <QMessageBox>
48 #include <QPushButton>
50 #include <QTextStream>
51 #include <QActionGroup>
56 QgsModelerToolboxModel::QgsModelerToolboxModel( QObject *parent )
62 Qt::ItemFlags QgsModelerToolboxModel::flags(
const QModelIndex &index )
const
64 Qt::ItemFlags f = QgsProcessingToolboxProxyModel::flags( index );
65 const QModelIndex sourceIndex = mapToSource( index );
66 if ( toolboxModel()->isAlgorithm( sourceIndex ) )
68 f = f | Qt::ItemIsDragEnabled;
73 Qt::DropActions QgsModelerToolboxModel::supportedDragActions()
const
75 return Qt::CopyAction;
80 QgsModelDesignerDialog::QgsModelDesignerDialog( QWidget *parent, Qt::WindowFlags flags )
81 : QMainWindow( parent, flags )
82 , mToolsActionGroup( new QActionGroup( this ) )
86 setAttribute( Qt::WA_DeleteOnClose );
87 setDockOptions( dockOptions() | QMainWindow::GroupedDragging );
88 setWindowFlags( Qt::WindowMinimizeButtonHint |
89 Qt::WindowMaximizeButtonHint |
90 Qt::WindowCloseButtonHint );
94 mModel = std::make_unique< QgsProcessingModelAlgorithm >();
97 mUndoStack =
new QUndoStack(
this );
98 connect( mUndoStack, &QUndoStack::indexChanged,
this, [ = ]
100 if ( mIgnoreUndoStackChanges )
103 mBlockUndoCommands++;
104 updateVariablesGui();
105 mGroupEdit->setText( mModel->group() );
106 mNameEdit->setText( mModel->displayName() );
107 mBlockUndoCommands--;
111 mPropertiesDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable );
112 mInputsDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable );
113 mAlgorithmsDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable );
114 mVariablesDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
116 mAlgorithmsTree->header()->setVisible(
false );
117 mAlgorithmSearchEdit->setShowSearchIcon(
true );
118 mAlgorithmSearchEdit->setPlaceholderText( tr(
"Search…" ) );
119 connect( mAlgorithmSearchEdit, &QgsFilterLineEdit::textChanged, mAlgorithmsTree, &QgsProcessingToolboxTreeView::setFilterString );
121 mInputsTreeWidget->header()->setVisible(
false );
122 mInputsTreeWidget->setAlternatingRowColors(
true );
123 mInputsTreeWidget->setDragDropMode( QTreeWidget::DragOnly );
124 mInputsTreeWidget->setDropIndicatorShown(
true );
126 mNameEdit->setPlaceholderText( tr(
"Enter model name here" ) );
127 mGroupEdit->setPlaceholderText( tr(
"Enter group name here" ) );
130 mMessageBar->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Fixed );
131 mainLayout->insertWidget( 0, mMessageBar );
133 mView->setAcceptDrops(
true );
136 connect( mActionClose, &QAction::triggered,
this, &QWidget::close );
137 connect( mActionNew, &QAction::triggered,
this, &QgsModelDesignerDialog::newModel );
138 connect( mActionZoomIn, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomIn );
139 connect( mActionZoomOut, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomOut );
140 connect( mActionZoomActual, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomActual );
141 connect( mActionZoomToItems, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomFull );
142 connect( mActionExportImage, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToImage );
143 connect( mActionExportPdf, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToPdf );
144 connect( mActionExportSvg, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToSvg );
145 connect( mActionExportPython, &QAction::triggered,
this, &QgsModelDesignerDialog::exportAsPython );
146 connect( mActionSave, &QAction::triggered,
this, [ = ] { saveModel(
false ); } );
147 connect( mActionSaveAs, &QAction::triggered,
this, [ = ] { saveModel(
true ); } );
148 connect( mActionDeleteComponents, &QAction::triggered,
this, &QgsModelDesignerDialog::deleteSelected );
149 connect( mActionSnapSelected, &QAction::triggered, mView, &QgsModelGraphicsView::snapSelected );
150 connect( mActionValidate, &QAction::triggered,
this, &QgsModelDesignerDialog::validate );
151 connect( mActionReorderInputs, &QAction::triggered,
this, &QgsModelDesignerDialog::reorderInputs );
152 connect( mReorderInputsButton, &QPushButton::clicked,
this, &QgsModelDesignerDialog::reorderInputs );
154 mActionSnappingEnabled->setChecked( settings.
value( QStringLiteral(
"/Processing/Modeler/enableSnapToGrid" ),
false ).toBool() );
155 connect( mActionSnappingEnabled, &QAction::toggled,
this, [ = ](
bool enabled )
157 mView->snapper()->setSnapToGrid( enabled );
158 QgsSettings().
setValue( QStringLiteral(
"/Processing/Modeler/enableSnapToGrid" ), enabled );
160 mView->snapper()->setSnapToGrid( mActionSnappingEnabled->isChecked() );
162 connect( mActionSelectAll, &QAction::triggered,
this, [ = ]
167 QStringList docksTitle = settings.
value( QStringLiteral(
"ModelDesigner/hiddenDocksTitle" ), QStringList(),
QgsSettings::App ).toStringList();
168 QStringList docksActive = settings.
value( QStringLiteral(
"ModelDesigner/hiddenDocksActive" ), QStringList(),
QgsSettings::App ).toStringList();
169 if ( !docksTitle.isEmpty() )
171 for (
const auto &title : docksTitle )
173 mPanelStatus.insert( title, PanelStatus(
true, docksActive.contains( title ) ) );
176 mActionHidePanels->setChecked( !docksTitle.isEmpty() );
177 connect( mActionHidePanels, &QAction::toggled,
this, &QgsModelDesignerDialog::setPanelVisibility );
179 mUndoAction = mUndoStack->createUndoAction(
this );
181 mUndoAction->setShortcuts( QKeySequence::Undo );
182 mRedoAction = mUndoStack->createRedoAction(
this );
184 mRedoAction->setShortcuts( QKeySequence::Redo );
186 mMenuEdit->insertAction( mActionDeleteComponents, mRedoAction );
187 mMenuEdit->insertAction( mActionDeleteComponents, mUndoAction );
188 mMenuEdit->insertSeparator( mActionDeleteComponents );
189 mToolbar->insertAction( mActionZoomIn, mUndoAction );
190 mToolbar->insertAction( mActionZoomIn, mRedoAction );
191 mToolbar->insertSeparator( mActionZoomIn );
193 mGroupMenu =
new QMenu( tr(
"Zoom To" ),
this );
194 mMenuView->insertMenu( mActionZoomIn, mGroupMenu );
195 connect( mGroupMenu, &QMenu::aboutToShow,
this, &QgsModelDesignerDialog::populateZoomToMenu );
199 mActionCut =
new QAction( tr(
"Cu&t" ),
this );
200 mActionCut->setShortcuts( QKeySequence::Cut );
201 mActionCut->setStatusTip( tr(
"Cut" ) );
203 connect( mActionCut, &QAction::triggered,
this, [ = ]
205 mView->copySelectedItems( QgsModelGraphicsView::ClipboardCut );
208 mActionCopy =
new QAction( tr(
"&Copy" ),
this );
209 mActionCopy->setShortcuts( QKeySequence::Copy );
210 mActionCopy->setStatusTip( tr(
"Copy" ) );
212 connect( mActionCopy, &QAction::triggered,
this, [ = ]
214 mView->copySelectedItems( QgsModelGraphicsView::ClipboardCopy );
217 mActionPaste =
new QAction( tr(
"&Paste" ),
this );
218 mActionPaste->setShortcuts( QKeySequence::Paste );
219 mActionPaste->setStatusTip( tr(
"Paste" ) );
221 connect( mActionPaste, &QAction::triggered,
this, [ = ]
223 mView->pasteItems( QgsModelGraphicsView::PasteModeCursor );
225 mMenuEdit->insertAction( mActionDeleteComponents, mActionCut );
226 mMenuEdit->insertAction( mActionDeleteComponents, mActionCopy );
227 mMenuEdit->insertAction( mActionDeleteComponents, mActionPaste );
228 mMenuEdit->insertSeparator( mActionDeleteComponents );
231 if ( settings.
value( QStringLiteral(
"Processing/Configuration/SHOW_ALGORITHMS_KNOWN_ISSUES" ),
false ).toBool() )
235 mAlgorithmsTree->setFilters( filters );
236 mAlgorithmsTree->setDragDropMode( QTreeWidget::DragOnly );
237 mAlgorithmsTree->setDropIndicatorShown(
true );
239 mAlgorithmsModel =
new QgsModelerToolboxModel(
this );
240 mAlgorithmsTree->setToolboxProxyModel( mAlgorithmsModel );
242 connect( mView, &QgsModelGraphicsView::algorithmDropped,
this, [ = ](
const QString & algorithmId,
const QPointF & pos )
244 addAlgorithm( algorithmId, pos );
246 connect( mAlgorithmsTree, &QgsProcessingToolboxTreeView::doubleClicked,
this, [ = ]()
248 if ( mAlgorithmsTree->selectedAlgorithm() )
249 addAlgorithm( mAlgorithmsTree->selectedAlgorithm()->id(), QPointF() );
251 connect( mInputsTreeWidget, &QgsModelDesignerInputsTreeWidget::doubleClicked,
this, [ = ](
const QModelIndex & )
253 const QString parameterType = mInputsTreeWidget->currentItem()->data( 0, Qt::UserRole ).toString();
254 addInput( parameterType, QPointF() );
257 connect( mView, &QgsModelGraphicsView::inputDropped,
this, &QgsModelDesignerDialog::addInput );
260 QShortcut *ctrlEquals =
new QShortcut( QKeySequence( QStringLiteral(
"Ctrl+=" ) ),
this );
261 connect( ctrlEquals, &QShortcut::activated,
this, &QgsModelDesignerDialog::zoomIn );
264 mUndoDock->setObjectName( QStringLiteral(
"UndoDock" ) );
265 mUndoView =
new QUndoView( mUndoStack,
this );
266 mUndoDock->setWidget( mUndoView );
267 mUndoDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
268 addDockWidget( Qt::DockWidgetArea::LeftDockWidgetArea, mUndoDock );
270 tabifyDockWidget( mUndoDock, mPropertiesDock );
271 tabifyDockWidget( mVariablesDock, mPropertiesDock );
272 mPropertiesDock->raise();
273 tabifyDockWidget( mInputsDock, mAlgorithmsDock );
274 mInputsDock->raise();
280 beginUndoCommand( tr(
"Change Model Variables" ) );
281 mModel->setVariables( mVariablesEditor->variablesInActiveScope() );
285 connect( mNameEdit, &QLineEdit::textChanged,
this, [ = ](
const QString & name )
289 beginUndoCommand( tr(
"Change Model Name" ), NameChanged );
290 mModel->setName( name );
295 connect( mGroupEdit, &QLineEdit::textChanged,
this, [ = ](
const QString & group )
299 beginUndoCommand( tr(
"Change Model Group" ), GroupChanged );
300 mModel->setGroup( group );
307 QToolButton *toolbuttonExportToScript =
new QToolButton();
308 toolbuttonExportToScript->setPopupMode( QToolButton::InstantPopup );
309 toolbuttonExportToScript->addAction( mActionExportAsScriptAlgorithm );
310 toolbuttonExportToScript->setDefaultAction( mActionExportAsScriptAlgorithm );
311 mToolbar->insertWidget( mActionExportImage, toolbuttonExportToScript );
312 connect( mActionExportAsScriptAlgorithm, &QAction::triggered,
this, &QgsModelDesignerDialog::exportAsScriptAlgorithm );
314 mActionShowComments->setChecked( settings.
value( QStringLiteral(
"/Processing/Modeler/ShowComments" ),
true ).toBool() );
315 connect( mActionShowComments, &QAction::toggled,
this, &QgsModelDesignerDialog::toggleComments );
318 mPanTool->setAction( mActionPan );
320 mToolsActionGroup->addAction( mActionPan );
321 connect( mActionPan, &QAction::triggered, mPanTool, [ = ] { mView->setTool( mPanTool ); } );
324 mSelectTool->setAction( mActionSelectMoveItem );
326 mToolsActionGroup->addAction( mActionSelectMoveItem );
327 connect( mActionSelectMoveItem, &QAction::triggered, mSelectTool, [ = ] { mView->setTool( mSelectTool ); } );
329 mView->setTool( mSelectTool );
332 connect( mView, &QgsModelGraphicsView::macroCommandStarted,
this, [ = ](
const QString & text )
334 mIgnoreUndoStackChanges++;
335 mUndoStack->beginMacro( text );
336 mIgnoreUndoStackChanges--;
338 connect( mView, &QgsModelGraphicsView::macroCommandEnded,
this, [ = ]
340 mIgnoreUndoStackChanges++;
341 mUndoStack->endMacro();
342 mIgnoreUndoStackChanges--;
344 connect( mView, &QgsModelGraphicsView::beginCommand,
this, [ = ](
const QString & text )
346 beginUndoCommand( text );
348 connect( mView, &QgsModelGraphicsView::endCommand,
this, [ = ]
352 connect( mView, &QgsModelGraphicsView::deleteSelectedItems,
this, [ = ]
357 connect( mActionAddGroupBox, &QAction::triggered,
this, [ = ]
359 const QPointF viewCenter = mView->mapToScene( mView->viewport()->rect().center() );
360 QgsProcessingModelGroupBox group;
361 group.setPosition( viewCenter );
362 group.setDescription( tr(
"New Group" ) );
364 beginUndoCommand( tr(
"Add Group Box" ) );
365 model()->addGroupBox( group );
373 restoreState( settings.
value( QStringLiteral(
"ModelDesigner/state" ), QByteArray(),
QgsSettings::App ).toByteArray() );
376 QgsModelDesignerDialog::~QgsModelDesignerDialog()
379 if ( !mPanelStatus.isEmpty() )
381 QStringList docksTitle;
382 QStringList docksActive;
384 for (
const auto &panel : mPanelStatus.toStdMap() )
386 if ( panel.second.isVisible )
387 docksTitle << panel.first;
388 if ( panel.second.isActive )
389 docksActive << panel.first;
403 mIgnoreUndoStackChanges++;
407 void QgsModelDesignerDialog::closeEvent( QCloseEvent *event )
409 if ( checkForUnsavedChanges() )
415 void QgsModelDesignerDialog::beginUndoCommand(
const QString &text,
int id )
417 if ( mBlockUndoCommands || !mUndoStack )
420 if ( mActiveCommand )
423 mActiveCommand = std::make_unique< QgsModelUndoCommand >( mModel.get(), text,
id );
426 void QgsModelDesignerDialog::endUndoCommand()
428 if ( mBlockUndoCommands || !mActiveCommand || !mUndoStack )
431 mActiveCommand->saveAfterState();
432 mIgnoreUndoStackChanges++;
433 mUndoStack->push( mActiveCommand.release() );
434 mIgnoreUndoStackChanges--;
438 QgsProcessingModelAlgorithm *QgsModelDesignerDialog::model()
443 void QgsModelDesignerDialog::setModel( QgsProcessingModelAlgorithm *model )
445 mModel.reset( model );
447 mGroupEdit->setText( mModel->group() );
448 mNameEdit->setText( mModel->displayName() );
450 updateVariablesGui();
452 mView->centerOn( 0, 0 );
455 mIgnoreUndoStackChanges++;
457 mIgnoreUndoStackChanges--;
462 void QgsModelDesignerDialog::loadModel(
const QString &path )
464 std::unique_ptr< QgsProcessingModelAlgorithm > alg = std::make_unique< QgsProcessingModelAlgorithm >();
465 if ( alg->fromFile( path ) )
468 alg->setSourceFilePath( path );
469 setModel( alg.release() );
473 QgsMessageLog::logMessage( tr(
"Could not load model %1" ).arg( path ), tr(
"Processing" ), Qgis::MessageLevel::Critical );
474 QMessageBox::critical(
this, tr(
"Open Model" ), tr(
"The selected model could not be loaded.\n"
475 "See the log for more information." ) );
479 void QgsModelDesignerDialog::setModelScene( QgsModelGraphicsScene *scene )
481 QgsModelGraphicsScene *oldScene = mScene;
484 mScene->setParent(
this );
485 mScene->setChildAlgorithmResults( mChildResults );
486 mScene->setModel( mModel.get() );
487 mScene->setMessageBar( mMessageBar );
489 const QPointF center = mView->mapToScene( mView->viewport()->rect().center() );
490 mView->setModelScene( mScene );
492 mSelectTool->resetCache();
493 mSelectTool->setScene( mScene );
495 connect( mScene, &QgsModelGraphicsScene::rebuildRequired,
this, [ = ]
497 if ( mBlockRepaints )
502 connect( mScene, &QgsModelGraphicsScene::componentAboutToChange,
this, [ = ](
const QString & description,
int id ) { beginUndoCommand( description,
id ); } );
503 connect( mScene, &QgsModelGraphicsScene::componentChanged,
this, [ = ] { endUndoCommand(); } );
505 mView->centerOn( center );
508 oldScene->deleteLater();
511 void QgsModelDesignerDialog::activate()
515 setWindowState( windowState() & ~Qt::WindowMinimized );
519 void QgsModelDesignerDialog::updateVariablesGui()
521 mBlockUndoCommands++;
523 std::unique_ptr< QgsExpressionContextScope > variablesScope = std::make_unique< QgsExpressionContextScope >( tr(
"Model Variables" ) );
524 const QVariantMap modelVars = mModel->variables();
525 for (
auto it = modelVars.constBegin(); it != modelVars.constEnd(); ++it )
527 variablesScope->setVariable( it.key(), it.value() );
530 variablesContext.
appendScope( variablesScope.release() );
531 mVariablesEditor->setContext( &variablesContext );
532 mVariablesEditor->setEditableScopeIndex( 0 );
534 mBlockUndoCommands--;
537 void QgsModelDesignerDialog::setDirty(
bool dirty )
543 bool QgsModelDesignerDialog::validateSave( SaveAction action )
547 case QgsModelDesignerDialog::SaveAction::SaveAsFile:
549 case QgsModelDesignerDialog::SaveAction::SaveInProject:
550 if ( mNameEdit->text().trimmed().isEmpty() )
552 mMessageBar->pushWarning( QString(), tr(
"Please enter a model name before saving" ) );
561 bool QgsModelDesignerDialog::checkForUnsavedChanges()
565 QMessageBox::StandardButton ret = QMessageBox::question(
this, tr(
"Save Model?" ),
566 tr(
"There are unsaved changes in this model. Do you want to keep those?" ),
567 QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Discard, QMessageBox::Cancel );
570 case QMessageBox::Save:
571 return saveModel(
false );
573 case QMessageBox::Discard:
586 void QgsModelDesignerDialog::setLastRunChildAlgorithmResults(
const QVariantMap &results )
588 mChildResults = results;
590 mScene->setChildAlgorithmResults( mChildResults );
593 void QgsModelDesignerDialog::setLastRunChildAlgorithmInputs(
const QVariantMap &inputs )
595 mChildInputs = inputs;
597 mScene->setChildAlgorithmInputs( mChildInputs );
600 void QgsModelDesignerDialog::setModelName(
const QString &name )
602 mNameEdit->setText( name );
605 void QgsModelDesignerDialog::zoomIn()
607 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
608 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
610 const double factor = settings.
value( QStringLiteral(
"/qgis/zoom_favor" ), 2.0 ).toDouble();
611 mView->scale( factor, factor );
612 mView->centerOn( point );
615 void QgsModelDesignerDialog::zoomOut()
617 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
618 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
620 const double factor = 1.0 / settings.
value( QStringLiteral(
"/qgis/zoom_favor" ), 2.0 ).toDouble();
621 mView->scale( factor, factor );
622 mView->centerOn( point );
625 void QgsModelDesignerDialog::zoomActual()
627 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
628 mView->resetTransform();
629 mView->scale( QgsApplication::desktop()->logicalDpiX() / 96, QgsApplication::desktop()->logicalDpiX() / 96 );
630 mView->centerOn( point );
633 void QgsModelDesignerDialog::zoomFull()
635 QRectF totalRect = mView->scene()->itemsBoundingRect();
636 totalRect.adjust( -10, -10, 10, 10 );
637 mView->fitInView( totalRect, Qt::KeepAspectRatio );
640 void QgsModelDesignerDialog::newModel()
642 if ( !checkForUnsavedChanges() )
645 std::unique_ptr< QgsProcessingModelAlgorithm > alg = std::make_unique< QgsProcessingModelAlgorithm >();
647 setModel( alg.release() );
650 void QgsModelDesignerDialog::exportToImage()
652 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Image" ), tr(
"PNG files (*.png *.PNG)" ) );
653 if ( filename.isEmpty() )
658 repaintModel(
false );
660 QRectF totalRect = mView->scene()->itemsBoundingRect();
661 totalRect.adjust( -10, -10, 10, 10 );
662 const QRectF imageRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
664 QImage img( totalRect.width(), totalRect.height(),
665 QImage::Format_ARGB32_Premultiplied );
666 img.fill( Qt::white );
668 painter.setRenderHint( QPainter::Antialiasing );
669 painter.begin( &img );
670 mView->scene()->render( &painter, imageRect, totalRect );
673 img.save( filename );
675 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 );
676 repaintModel(
true );
679 void QgsModelDesignerDialog::exportToPdf()
681 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as PDF" ), tr(
"PDF files (*.pdf *.PDF)" ) );
682 if ( filename.isEmpty() )
687 repaintModel(
false );
689 QRectF totalRect = mView->scene()->itemsBoundingRect();
690 totalRect.adjust( -10, -10, 10, 10 );
691 const QRectF printerRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
694 printer.setOutputFormat( QPrinter::PdfFormat );
695 printer.setOutputFileName( filename );
696 printer.setPaperSize( QSizeF( printerRect.width(), printerRect.height() ), QPrinter::DevicePixel );
697 printer.setFullPage(
true );
699 QPainter painter( &printer );
700 mView->scene()->render( &painter, printerRect, totalRect );
703 mMessageBar->pushMessage( QString(), tr(
"Successfully exported model as PDF to <a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( filename ).toString(),
704 QDir::toNativeSeparators( filename ) ), Qgis::MessageLevel::Success, 0 );
705 repaintModel(
true );
708 void QgsModelDesignerDialog::exportToSvg()
710 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as SVG" ), tr(
"SVG files (*.svg *.SVG)" ) );
711 if ( filename.isEmpty() )
716 repaintModel(
false );
718 QRectF totalRect = mView->scene()->itemsBoundingRect();
719 totalRect.adjust( -10, -10, 10, 10 );
720 const QRectF svgRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
723 svg.setFileName( filename );
724 svg.setSize( QSize( totalRect.width(), totalRect.height() ) );
725 svg.setViewBox( svgRect );
726 svg.setTitle( mModel->displayName() );
728 QPainter painter( &svg );
729 mView->scene()->render( &painter, svgRect, totalRect );
732 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 );
733 repaintModel(
true );
736 void QgsModelDesignerDialog::exportAsPython()
738 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Python Script" ), tr(
"Processing scripts (*.py *.PY)" ) );
739 if ( filename.isEmpty() )
746 QFile outFile( filename );
747 if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
751 QTextStream fout( &outFile );
755 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 );
758 void QgsModelDesignerDialog::toggleComments(
bool show )
762 repaintModel(
true );
765 void QgsModelDesignerDialog::updateWindowTitle()
767 QString title = tr(
"Model Designer" );
768 if ( !mModel->name().isEmpty() )
769 title = QStringLiteral(
"%1 - %2" ).arg( title, mModel->name() );
772 title.prepend(
'*' );
774 setWindowTitle( title );
777 void QgsModelDesignerDialog::deleteSelected()
779 QList< QgsModelComponentGraphicItem * > items = mScene->selectedComponentItems();
783 if ( items.size() == 1 )
785 items.at( 0 )->deleteComponent();
789 std::sort( items.begin(), items.end(), []( QgsModelComponentGraphicItem * p1, QgsModelComponentGraphicItem * p2 )
792 if ( dynamic_cast< QgsModelCommentGraphicItem *>( p1 ) )
794 else if ( dynamic_cast< QgsModelCommentGraphicItem *>( p2 ) )
796 else if ( dynamic_cast< QgsModelGroupBoxGraphicItem *>( p1 ) )
798 else if ( dynamic_cast< QgsModelGroupBoxGraphicItem *>( p2 ) )
800 else if ( dynamic_cast< QgsModelOutputGraphicItem *>( p1 ) )
802 else if ( dynamic_cast< QgsModelOutputGraphicItem *>( p2 ) )
804 else if ( dynamic_cast< QgsModelChildAlgorithmGraphicItem *>( p1 ) )
806 else if ( dynamic_cast< QgsModelChildAlgorithmGraphicItem *>( p2 ) )
812 beginUndoCommand( tr(
"Delete Components" ) );
814 QVariant prevState = mModel->toVariant();
815 mBlockUndoCommands++;
816 mBlockRepaints =
true;
818 while ( !items.empty() )
820 QgsModelComponentGraphicItem *toDelete =
nullptr;
821 for ( QgsModelComponentGraphicItem *item : items )
823 if ( item->canDeleteComponent() )
836 toDelete->deleteComponent();
837 items.removeAll( toDelete );
842 mModel->loadVariant( prevState );
843 QMessageBox::warning(
nullptr, QObject::tr(
"Could not remove components" ),
844 QObject::tr(
"Components depend on the selected items.\n"
845 "Try to remove them before trying deleting these components." ) );
846 mBlockUndoCommands--;
847 mActiveCommand.reset();
851 mBlockUndoCommands--;
855 mBlockRepaints =
false;
859 void QgsModelDesignerDialog::populateZoomToMenu()
862 for (
const QgsProcessingModelGroupBox &box : model()->groupBoxes() )
864 if ( QgsModelComponentGraphicItem *item = mScene->groupBoxItem( box.uuid() ) )
866 QAction *zoomAction =
new QAction( box.description(), mGroupMenu );
867 connect( zoomAction, &QAction::triggered,
this, [ = ]
869 QRectF groupRect = item->mapToScene( item->boundingRect() ).boundingRect();
870 groupRect.adjust( -10, -10, 10, 10 );
871 mView->fitInView( groupRect, Qt::KeepAspectRatio );
872 mView->centerOn( item );
874 mGroupMenu->addAction( zoomAction );
879 void QgsModelDesignerDialog::setPanelVisibility(
bool hidden )
881 const QList<QDockWidget *> docks = findChildren<QDockWidget *>();
882 const QList<QTabBar *> tabBars = findChildren<QTabBar *>();
886 mPanelStatus.clear();
888 for ( QDockWidget *dock : docks )
890 mPanelStatus.insert( dock->windowTitle(), PanelStatus( dock->isVisible(),
false ) );
891 dock->setVisible(
false );
895 for ( QTabBar *tabBar : tabBars )
897 QString currentTabTitle = tabBar->tabText( tabBar->currentIndex() );
898 mPanelStatus[ currentTabTitle ].isActive =
true;
904 for ( QDockWidget *dock : docks )
906 if ( mPanelStatus.contains( dock->windowTitle() ) )
908 dock->setVisible( mPanelStatus.value( dock->windowTitle() ).isVisible );
913 for ( QTabBar *tabBar : tabBars )
916 for (
int i = 0; i < tabBar->count(); ++i )
918 QString tabTitle = tabBar->tabText( i );
919 if ( mPanelStatus.contains( tabTitle ) && mPanelStatus.value( tabTitle ).isActive )
921 tabBar->setCurrentIndex( i );
925 mPanelStatus.clear();
929 void QgsModelDesignerDialog::validate()
932 if ( model()->validate( issues ) )
934 mMessageBar->pushSuccess( QString(), tr(
"Model is valid!" ) );
939 QPushButton *detailsButton =
new QPushButton( tr(
"Details" ) );
940 connect( detailsButton, &QPushButton::clicked, detailsButton, [ = ]
943 dialog->
setTitle( tr(
"Model is Invalid" ) );
945 QString longMessage = tr(
"<p>This model is not valid:</p>" ) + QStringLiteral(
"<ul>" );
946 for (
const QString &issue : issues )
948 longMessage += QStringLiteral(
"<li>%1</li>" ).arg( issue );
950 longMessage += QLatin1String(
"</ul>" );
955 messageWidget->layout()->addWidget( detailsButton );
956 mMessageBar->clearWidgets();
957 mMessageBar->pushWidget( messageWidget, Qgis::MessageLevel::Warning, 0 );
961 void QgsModelDesignerDialog::reorderInputs()
963 QgsModelInputReorderDialog dlg(
this );
964 dlg.setModel( mModel.get() );
967 const QStringList inputOrder = dlg.inputOrder();
968 beginUndoCommand( tr(
"Reorder Inputs" ) );
969 mModel->setParameterOrder( inputOrder );
974 bool QgsModelDesignerDialog::isDirty()
const
976 return mHasChanged && mUndoStack->index() != -1;
979 void QgsModelDesignerDialog::fillInputsTree()
982 std::unique_ptr< QTreeWidgetItem > parametersItem = std::make_unique< QTreeWidgetItem >();
983 parametersItem->setText( 0, tr(
"Parameters" ) );
987 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
994 std::unique_ptr< QTreeWidgetItem > paramItem = std::make_unique< QTreeWidgetItem >();
995 paramItem->setText( 0, param->name() );
996 paramItem->setData( 0, Qt::UserRole, param->id() );
997 paramItem->setIcon( 0, icon );
998 paramItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled );
999 paramItem->setToolTip( 0, param->description() );
1000 parametersItem->addChild( paramItem.release() );
1003 mInputsTreeWidget->addTopLevelItem( parametersItem.release() );
1004 mInputsTreeWidget->topLevelItem( 0 )->setExpanded(
true );
1012 QgsModelChildDependenciesWidget::QgsModelChildDependenciesWidget( QWidget *parent, QgsProcessingModelAlgorithm *model,
const QString &childId )
1015 , mChildId( childId )
1017 QHBoxLayout *hl =
new QHBoxLayout();
1018 hl->setContentsMargins( 0, 0, 0, 0 );
1020 mLineEdit =
new QLineEdit();
1021 mLineEdit->setEnabled(
false );
1022 hl->addWidget( mLineEdit, 1 );
1024 mToolButton =
new QToolButton();
1025 mToolButton->setText( QString( QChar( 0x2026 ) ) );
1026 hl->addWidget( mToolButton );
1030 mLineEdit->setText( tr(
"%1 dependencies selected" ).arg( 0 ) );
1032 connect( mToolButton, &QToolButton::clicked,
this, &QgsModelChildDependenciesWidget::showDialog );
1035 void QgsModelChildDependenciesWidget::setValue(
const QList<QgsProcessingModelChildDependency> &value )
1039 updateSummaryText();
1042 void QgsModelChildDependenciesWidget::showDialog()
1044 const QList<QgsProcessingModelChildDependency> available = mModel->availableDependenciesForChildAlgorithm( mChildId );
1046 QVariantList availableOptions;
1047 for (
const QgsProcessingModelChildDependency &dep : available )
1048 availableOptions << QVariant::fromValue( dep );
1049 QVariantList selectedOptions;
1050 for (
const QgsProcessingModelChildDependency &dep : mValue )
1051 selectedOptions << QVariant::fromValue( dep );
1056 QgsProcessingMultipleSelectionPanelWidget *widget =
new QgsProcessingMultipleSelectionPanelWidget( availableOptions, selectedOptions );
1057 widget->setPanelTitle( tr(
"Algorithm Dependencies" ) );
1059 widget->setValueFormatter( [ = ](
const QVariant & v ) -> QString
1061 const QgsProcessingModelChildDependency dep = v.value< QgsProcessingModelChildDependency >();
1063 const QString description = mModel->childAlgorithm( dep.childId ).description();
1064 if ( dep.conditionalBranch.isEmpty() )
1067 return tr(
"Condition “%1” from algorithm “%2”" ).arg( dep.conditionalBranch, description );
1070 connect( widget, &QgsProcessingMultipleSelectionPanelWidget::selectionChanged,
this, [ = ]()
1072 QList< QgsProcessingModelChildDependency > res;
1073 for (
const QVariant &v : widget->selectedOptions() )
1075 res << v.value< QgsProcessingModelChildDependency >();
1084 void QgsModelChildDependenciesWidget::updateSummaryText()
1086 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.
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.