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( mActionZoomIn, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomIn );
138 connect( mActionZoomOut, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomOut );
139 connect( mActionZoomActual, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomActual );
140 connect( mActionZoomToItems, &QAction::triggered,
this, &QgsModelDesignerDialog::zoomFull );
141 connect( mActionExportImage, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToImage );
142 connect( mActionExportPdf, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToPdf );
143 connect( mActionExportSvg, &QAction::triggered,
this, &QgsModelDesignerDialog::exportToSvg );
144 connect( mActionExportPython, &QAction::triggered,
this, &QgsModelDesignerDialog::exportAsPython );
145 connect( mActionSave, &QAction::triggered,
this, [ = ] { saveModel(
false ); } );
146 connect( mActionSaveAs, &QAction::triggered,
this, [ = ] { saveModel(
true ); } );
147 connect( mActionDeleteComponents, &QAction::triggered,
this, &QgsModelDesignerDialog::deleteSelected );
148 connect( mActionSnapSelected, &QAction::triggered, mView, &QgsModelGraphicsView::snapSelected );
149 connect( mActionValidate, &QAction::triggered,
this, &QgsModelDesignerDialog::validate );
150 connect( mActionReorderInputs, &QAction::triggered,
this, &QgsModelDesignerDialog::reorderInputs );
151 connect( mReorderInputsButton, &QPushButton::clicked,
this, &QgsModelDesignerDialog::reorderInputs );
153 mActionSnappingEnabled->setChecked( settings.
value( QStringLiteral(
"/Processing/Modeler/enableSnapToGrid" ),
false ).toBool() );
154 connect( mActionSnappingEnabled, &QAction::toggled,
this, [ = ](
bool enabled )
156 mView->snapper()->setSnapToGrid( enabled );
157 QgsSettings().
setValue( QStringLiteral(
"/Processing/Modeler/enableSnapToGrid" ), enabled );
159 mView->snapper()->setSnapToGrid( mActionSnappingEnabled->isChecked() );
161 connect( mActionSelectAll, &QAction::triggered,
this, [ = ]
166 QStringList docksTitle = settings.
value( QStringLiteral(
"ModelDesigner/hiddenDocksTitle" ), QStringList(),
QgsSettings::App ).toStringList();
167 QStringList docksActive = settings.
value( QStringLiteral(
"ModelDesigner/hiddenDocksActive" ), QStringList(),
QgsSettings::App ).toStringList();
168 if ( !docksTitle.isEmpty() )
170 for (
const auto &title : docksTitle )
172 mPanelStatus.insert( title, PanelStatus(
true, docksActive.contains( title ) ) );
175 mActionHidePanels->setChecked( !docksTitle.isEmpty() );
176 connect( mActionHidePanels, &QAction::toggled,
this, &QgsModelDesignerDialog::setPanelVisibility );
178 mUndoAction = mUndoStack->createUndoAction(
this );
180 mUndoAction->setShortcuts( QKeySequence::Undo );
181 mRedoAction = mUndoStack->createRedoAction(
this );
183 mRedoAction->setShortcuts( QKeySequence::Redo );
185 mMenuEdit->insertAction( mActionDeleteComponents, mRedoAction );
186 mMenuEdit->insertAction( mActionDeleteComponents, mUndoAction );
187 mMenuEdit->insertSeparator( mActionDeleteComponents );
188 mToolbar->insertAction( mActionZoomIn, mUndoAction );
189 mToolbar->insertAction( mActionZoomIn, mRedoAction );
190 mToolbar->insertSeparator( mActionZoomIn );
192 mGroupMenu =
new QMenu( tr(
"Zoom To" ),
this );
193 mMenuView->insertMenu( mActionZoomIn, mGroupMenu );
194 connect( mGroupMenu, &QMenu::aboutToShow,
this, &QgsModelDesignerDialog::populateZoomToMenu );
198 mActionCut =
new QAction( tr(
"Cu&t" ),
this );
199 mActionCut->setShortcuts( QKeySequence::Cut );
200 mActionCut->setStatusTip( tr(
"Cut" ) );
202 connect( mActionCut, &QAction::triggered,
this, [ = ]
204 mView->copySelectedItems( QgsModelGraphicsView::ClipboardCut );
207 mActionCopy =
new QAction( tr(
"&Copy" ),
this );
208 mActionCopy->setShortcuts( QKeySequence::Copy );
209 mActionCopy->setStatusTip( tr(
"Copy" ) );
211 connect( mActionCopy, &QAction::triggered,
this, [ = ]
213 mView->copySelectedItems( QgsModelGraphicsView::ClipboardCopy );
216 mActionPaste =
new QAction( tr(
"&Paste" ),
this );
217 mActionPaste->setShortcuts( QKeySequence::Paste );
218 mActionPaste->setStatusTip( tr(
"Paste" ) );
220 connect( mActionPaste, &QAction::triggered,
this, [ = ]
222 mView->pasteItems( QgsModelGraphicsView::PasteModeCursor );
224 mMenuEdit->insertAction( mActionDeleteComponents, mActionCut );
225 mMenuEdit->insertAction( mActionDeleteComponents, mActionCopy );
226 mMenuEdit->insertAction( mActionDeleteComponents, mActionPaste );
227 mMenuEdit->insertSeparator( mActionDeleteComponents );
230 if ( settings.
value( QStringLiteral(
"Processing/Configuration/SHOW_ALGORITHMS_KNOWN_ISSUES" ),
false ).toBool() )
234 mAlgorithmsTree->setFilters( filters );
235 mAlgorithmsTree->setDragDropMode( QTreeWidget::DragOnly );
236 mAlgorithmsTree->setDropIndicatorShown(
true );
238 mAlgorithmsModel =
new QgsModelerToolboxModel(
this );
239 mAlgorithmsTree->setToolboxProxyModel( mAlgorithmsModel );
241 connect( mView, &QgsModelGraphicsView::algorithmDropped,
this, [ = ](
const QString & algorithmId,
const QPointF & pos )
243 addAlgorithm( algorithmId, pos );
245 connect( mAlgorithmsTree, &QgsProcessingToolboxTreeView::doubleClicked,
this, [ = ]()
247 if ( mAlgorithmsTree->selectedAlgorithm() )
248 addAlgorithm( mAlgorithmsTree->selectedAlgorithm()->id(), QPointF() );
250 connect( mInputsTreeWidget, &QgsModelDesignerInputsTreeWidget::doubleClicked,
this, [ = ](
const QModelIndex & )
252 const QString parameterType = mInputsTreeWidget->currentItem()->data( 0, Qt::UserRole ).toString();
253 addInput( parameterType, QPointF() );
256 connect( mView, &QgsModelGraphicsView::inputDropped,
this, &QgsModelDesignerDialog::addInput );
259 QShortcut *ctrlEquals =
new QShortcut( QKeySequence( QStringLiteral(
"Ctrl+=" ) ),
this );
260 connect( ctrlEquals, &QShortcut::activated,
this, &QgsModelDesignerDialog::zoomIn );
263 mUndoDock->setObjectName( QStringLiteral(
"UndoDock" ) );
264 mUndoView =
new QUndoView( mUndoStack,
this );
265 mUndoDock->setWidget( mUndoView );
266 mUndoDock->setFeatures( QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable );
267 addDockWidget( Qt::DockWidgetArea::LeftDockWidgetArea, mUndoDock );
269 tabifyDockWidget( mUndoDock, mPropertiesDock );
270 tabifyDockWidget( mVariablesDock, mPropertiesDock );
271 mPropertiesDock->raise();
272 tabifyDockWidget( mInputsDock, mAlgorithmsDock );
273 mInputsDock->raise();
279 beginUndoCommand( tr(
"Change Model Variables" ) );
280 mModel->setVariables( mVariablesEditor->variablesInActiveScope() );
284 connect( mNameEdit, &QLineEdit::textChanged,
this, [ = ](
const QString & name )
288 beginUndoCommand( tr(
"Change Model Name" ), NameChanged );
289 mModel->setName( name );
294 connect( mGroupEdit, &QLineEdit::textChanged,
this, [ = ](
const QString & group )
298 beginUndoCommand( tr(
"Change Model Group" ), GroupChanged );
299 mModel->setGroup( group );
306 QToolButton *toolbuttonExportToScript =
new QToolButton();
307 toolbuttonExportToScript->setPopupMode( QToolButton::InstantPopup );
308 toolbuttonExportToScript->addAction( mActionExportAsScriptAlgorithm );
309 toolbuttonExportToScript->setDefaultAction( mActionExportAsScriptAlgorithm );
310 mToolbar->insertWidget( mActionExportImage, toolbuttonExportToScript );
311 connect( mActionExportAsScriptAlgorithm, &QAction::triggered,
this, &QgsModelDesignerDialog::exportAsScriptAlgorithm );
313 mActionShowComments->setChecked( settings.
value( QStringLiteral(
"/Processing/Modeler/ShowComments" ),
true ).toBool() );
314 connect( mActionShowComments, &QAction::toggled,
this, &QgsModelDesignerDialog::toggleComments );
317 mPanTool->setAction( mActionPan );
319 mToolsActionGroup->addAction( mActionPan );
320 connect( mActionPan, &QAction::triggered, mPanTool, [ = ] { mView->setTool( mPanTool ); } );
323 mSelectTool->setAction( mActionSelectMoveItem );
325 mToolsActionGroup->addAction( mActionSelectMoveItem );
326 connect( mActionSelectMoveItem, &QAction::triggered, mSelectTool, [ = ] { mView->setTool( mSelectTool ); } );
328 mView->setTool( mSelectTool );
331 connect( mView, &QgsModelGraphicsView::macroCommandStarted,
this, [ = ](
const QString & text )
333 mIgnoreUndoStackChanges++;
334 mUndoStack->beginMacro( text );
335 mIgnoreUndoStackChanges--;
337 connect( mView, &QgsModelGraphicsView::macroCommandEnded,
this, [ = ]
339 mIgnoreUndoStackChanges++;
340 mUndoStack->endMacro();
341 mIgnoreUndoStackChanges--;
343 connect( mView, &QgsModelGraphicsView::beginCommand,
this, [ = ](
const QString & text )
345 beginUndoCommand( text );
347 connect( mView, &QgsModelGraphicsView::endCommand,
this, [ = ]
351 connect( mView, &QgsModelGraphicsView::deleteSelectedItems,
this, [ = ]
356 connect( mActionAddGroupBox, &QAction::triggered,
this, [ = ]
358 const QPointF viewCenter = mView->mapToScene( mView->viewport()->rect().center() );
359 QgsProcessingModelGroupBox group;
360 group.setPosition( viewCenter );
361 group.setDescription( tr(
"New Group" ) );
363 beginUndoCommand( tr(
"Add Group Box" ) );
364 model()->addGroupBox( group );
372 restoreState( settings.
value( QStringLiteral(
"ModelDesigner/state" ), QByteArray(),
QgsSettings::App ).toByteArray() );
375 QgsModelDesignerDialog::~QgsModelDesignerDialog()
378 if ( !mPanelStatus.isEmpty() )
380 QStringList docksTitle;
381 QStringList docksActive;
383 for (
const auto &panel : mPanelStatus.toStdMap() )
385 if ( panel.second.isVisible )
386 docksTitle << panel.first;
387 if ( panel.second.isActive )
388 docksActive << panel.first;
402 mIgnoreUndoStackChanges++;
406 void QgsModelDesignerDialog::closeEvent( QCloseEvent *event )
408 if ( checkForUnsavedChanges() )
414 void QgsModelDesignerDialog::beginUndoCommand(
const QString &text,
int id )
416 if ( mBlockUndoCommands || !mUndoStack )
419 if ( mActiveCommand )
422 mActiveCommand = std::make_unique< QgsModelUndoCommand >( mModel.get(), text,
id );
425 void QgsModelDesignerDialog::endUndoCommand()
427 if ( mBlockUndoCommands || !mActiveCommand || !mUndoStack )
430 mActiveCommand->saveAfterState();
431 mIgnoreUndoStackChanges++;
432 mUndoStack->push( mActiveCommand.release() );
433 mIgnoreUndoStackChanges--;
437 QgsProcessingModelAlgorithm *QgsModelDesignerDialog::model()
442 void QgsModelDesignerDialog::setModel( QgsProcessingModelAlgorithm *model )
444 mModel.reset( model );
446 mGroupEdit->setText( mModel->group() );
447 mNameEdit->setText( mModel->displayName() );
449 updateVariablesGui();
451 mView->centerOn( 0, 0 );
454 mIgnoreUndoStackChanges++;
456 mIgnoreUndoStackChanges--;
461 void QgsModelDesignerDialog::loadModel(
const QString &path )
463 std::unique_ptr< QgsProcessingModelAlgorithm > alg = std::make_unique< QgsProcessingModelAlgorithm >();
464 if ( alg->fromFile( path ) )
467 setModel( alg.release() );
471 QgsMessageLog::logMessage( tr(
"Could not load model %1" ).arg( path ), tr(
"Processing" ), Qgis::MessageLevel::Critical );
472 QMessageBox::critical(
this, tr(
"Open Model" ), tr(
"The selected model could not be loaded.\n"
473 "See the log for more information." ) );
477 void QgsModelDesignerDialog::setModelScene( QgsModelGraphicsScene *scene )
479 QgsModelGraphicsScene *oldScene = mScene;
482 mScene->setParent(
this );
483 mScene->setChildAlgorithmResults( mChildResults );
484 mScene->setModel( mModel.get() );
485 mScene->setMessageBar( mMessageBar );
487 const QPointF center = mView->mapToScene( mView->viewport()->rect().center() );
488 mView->setModelScene( mScene );
490 mSelectTool->resetCache();
491 mSelectTool->setScene( mScene );
493 connect( mScene, &QgsModelGraphicsScene::rebuildRequired,
this, [ = ]
495 if ( mBlockRepaints )
500 connect( mScene, &QgsModelGraphicsScene::componentAboutToChange,
this, [ = ](
const QString & description,
int id ) { beginUndoCommand( description,
id ); } );
501 connect( mScene, &QgsModelGraphicsScene::componentChanged,
this, [ = ] { endUndoCommand(); } );
503 mView->centerOn( center );
506 oldScene->deleteLater();
509 void QgsModelDesignerDialog::updateVariablesGui()
511 mBlockUndoCommands++;
513 std::unique_ptr< QgsExpressionContextScope > variablesScope = std::make_unique< QgsExpressionContextScope >( tr(
"Model Variables" ) );
514 const QVariantMap modelVars = mModel->variables();
515 for (
auto it = modelVars.constBegin(); it != modelVars.constEnd(); ++it )
517 variablesScope->setVariable( it.key(), it.value() );
520 variablesContext.
appendScope( variablesScope.release() );
521 mVariablesEditor->setContext( &variablesContext );
522 mVariablesEditor->setEditableScopeIndex( 0 );
524 mBlockUndoCommands--;
527 void QgsModelDesignerDialog::setDirty(
bool dirty )
533 bool QgsModelDesignerDialog::validateSave()
535 if ( mNameEdit->text().trimmed().isEmpty() )
537 mMessageBar->pushWarning( QString(), tr(
"Please enter a model name before saving" ) );
544 bool QgsModelDesignerDialog::checkForUnsavedChanges()
548 QMessageBox::StandardButton ret = QMessageBox::question(
this, tr(
"Save Model?" ),
549 tr(
"There are unsaved changes in this model. Do you want to keep those?" ),
550 QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Discard, QMessageBox::Cancel );
553 case QMessageBox::Save:
557 case QMessageBox::Discard:
570 void QgsModelDesignerDialog::setLastRunChildAlgorithmResults(
const QVariantMap &results )
572 mChildResults = results;
574 mScene->setChildAlgorithmResults( mChildResults );
577 void QgsModelDesignerDialog::setLastRunChildAlgorithmInputs(
const QVariantMap &inputs )
579 mChildInputs = inputs;
581 mScene->setChildAlgorithmInputs( mChildInputs );
584 void QgsModelDesignerDialog::zoomIn()
586 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
587 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
589 const double factor = settings.
value( QStringLiteral(
"/qgis/zoom_favor" ), 2.0 ).toDouble();
590 mView->scale( factor, factor );
591 mView->centerOn( point );
594 void QgsModelDesignerDialog::zoomOut()
596 mView->setTransformationAnchor( QGraphicsView::NoAnchor );
597 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
599 const double factor = 1.0 / settings.
value( QStringLiteral(
"/qgis/zoom_favor" ), 2.0 ).toDouble();
600 mView->scale( factor, factor );
601 mView->centerOn( point );
604 void QgsModelDesignerDialog::zoomActual()
606 QPointF point = mView->mapToScene( QPoint( mView->viewport()->width() / 2.0, mView->viewport()->height() / 2 ) );
607 mView->resetTransform();
608 mView->scale( QgsApplication::desktop()->logicalDpiX() / 96, QgsApplication::desktop()->logicalDpiX() / 96 );
609 mView->centerOn( point );
612 void QgsModelDesignerDialog::zoomFull()
614 QRectF totalRect = mView->scene()->itemsBoundingRect();
615 totalRect.adjust( -10, -10, 10, 10 );
616 mView->fitInView( totalRect, Qt::KeepAspectRatio );
619 void QgsModelDesignerDialog::exportToImage()
621 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Image" ), tr(
"PNG files (*.png *.PNG)" ) );
622 if ( filename.isEmpty() )
627 repaintModel(
false );
629 QRectF totalRect = mView->scene()->itemsBoundingRect();
630 totalRect.adjust( -10, -10, 10, 10 );
631 const QRectF imageRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
633 QImage img( totalRect.width(), totalRect.height(),
634 QImage::Format_ARGB32_Premultiplied );
635 img.fill( Qt::white );
637 painter.setRenderHint( QPainter::Antialiasing );
638 painter.begin( &img );
639 mView->scene()->render( &painter, imageRect, totalRect );
642 img.save( filename );
644 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 );
645 repaintModel(
true );
648 void QgsModelDesignerDialog::exportToPdf()
650 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as PDF" ), tr(
"PDF files (*.pdf *.PDF)" ) );
651 if ( filename.isEmpty() )
656 repaintModel(
false );
658 QRectF totalRect = mView->scene()->itemsBoundingRect();
659 totalRect.adjust( -10, -10, 10, 10 );
660 const QRectF printerRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
663 printer.setOutputFormat( QPrinter::PdfFormat );
664 printer.setOutputFileName( filename );
665 printer.setPaperSize( QSizeF( printerRect.width(), printerRect.height() ), QPrinter::DevicePixel );
666 printer.setFullPage(
true );
668 QPainter painter( &printer );
669 mView->scene()->render( &painter, printerRect, totalRect );
672 mMessageBar->pushMessage( QString(), tr(
"Successfully exported model as PDF to <a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( filename ).toString(),
673 QDir::toNativeSeparators( filename ) ), Qgis::MessageLevel::Success, 0 );
674 repaintModel(
true );
677 void QgsModelDesignerDialog::exportToSvg()
679 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as SVG" ), tr(
"SVG files (*.svg *.SVG)" ) );
680 if ( filename.isEmpty() )
685 repaintModel(
false );
687 QRectF totalRect = mView->scene()->itemsBoundingRect();
688 totalRect.adjust( -10, -10, 10, 10 );
689 const QRectF svgRect = QRectF( 0, 0, totalRect.width(), totalRect.height() );
692 svg.setFileName( filename );
693 svg.setSize( QSize( totalRect.width(), totalRect.height() ) );
694 svg.setViewBox( svgRect );
695 svg.setTitle( mModel->displayName() );
697 QPainter painter( &svg );
698 mView->scene()->render( &painter, svgRect, totalRect );
701 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 );
702 repaintModel(
true );
705 void QgsModelDesignerDialog::exportAsPython()
707 QString filename = QFileDialog::getSaveFileName(
this, tr(
"Save Model as Python Script" ), tr(
"Processing scripts (*.py *.PY)" ) );
708 if ( filename.isEmpty() )
715 QFile outFile( filename );
716 if ( !outFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
720 QTextStream fout( &outFile );
724 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 );
727 void QgsModelDesignerDialog::toggleComments(
bool show )
731 repaintModel(
true );
734 void QgsModelDesignerDialog::updateWindowTitle()
736 QString title = tr(
"Model Designer" );
737 if ( !mModel->name().isEmpty() )
738 title = QStringLiteral(
"%1 - %2" ).arg( title, mModel->name() );
741 title.prepend(
'*' );
743 setWindowTitle( title );
746 void QgsModelDesignerDialog::deleteSelected()
748 QList< QgsModelComponentGraphicItem * > items = mScene->selectedComponentItems();
752 if ( items.size() == 1 )
754 items.at( 0 )->deleteComponent();
758 std::sort( items.begin(), items.end(), []( QgsModelComponentGraphicItem * p1, QgsModelComponentGraphicItem * p2 )
761 if ( dynamic_cast< QgsModelCommentGraphicItem *>( p1 ) )
763 else if ( dynamic_cast< QgsModelCommentGraphicItem *>( p2 ) )
765 else if ( dynamic_cast< QgsModelGroupBoxGraphicItem *>( p1 ) )
767 else if ( dynamic_cast< QgsModelGroupBoxGraphicItem *>( p2 ) )
769 else if ( dynamic_cast< QgsModelOutputGraphicItem *>( p1 ) )
771 else if ( dynamic_cast< QgsModelOutputGraphicItem *>( p2 ) )
773 else if ( dynamic_cast< QgsModelChildAlgorithmGraphicItem *>( p1 ) )
775 else if ( dynamic_cast< QgsModelChildAlgorithmGraphicItem *>( p2 ) )
781 beginUndoCommand( tr(
"Delete Components" ) );
783 QVariant prevState = mModel->toVariant();
784 mBlockUndoCommands++;
785 mBlockRepaints =
true;
787 while ( !items.empty() )
789 QgsModelComponentGraphicItem *toDelete =
nullptr;
790 for ( QgsModelComponentGraphicItem *item : items )
792 if ( item->canDeleteComponent() )
805 toDelete->deleteComponent();
806 items.removeAll( toDelete );
811 mModel->loadVariant( prevState );
812 QMessageBox::warning(
nullptr, QObject::tr(
"Could not remove components" ),
813 QObject::tr(
"Components depend on the selected items.\n"
814 "Try to remove them before trying deleting these components." ) );
815 mBlockUndoCommands--;
816 mActiveCommand.reset();
820 mBlockUndoCommands--;
824 mBlockRepaints =
false;
828 void QgsModelDesignerDialog::populateZoomToMenu()
831 for (
const QgsProcessingModelGroupBox &box : model()->groupBoxes() )
833 if ( QgsModelComponentGraphicItem *item = mScene->groupBoxItem( box.uuid() ) )
835 QAction *zoomAction =
new QAction( box.description(), mGroupMenu );
836 connect( zoomAction, &QAction::triggered,
this, [ = ]
838 QRectF groupRect = item->mapToScene( item->boundingRect() ).boundingRect();
839 groupRect.adjust( -10, -10, 10, 10 );
840 mView->fitInView( groupRect, Qt::KeepAspectRatio );
841 mView->centerOn( item );
843 mGroupMenu->addAction( zoomAction );
848 void QgsModelDesignerDialog::setPanelVisibility(
bool hidden )
850 const QList<QDockWidget *> docks = findChildren<QDockWidget *>();
851 const QList<QTabBar *> tabBars = findChildren<QTabBar *>();
855 mPanelStatus.clear();
857 for ( QDockWidget *dock : docks )
859 mPanelStatus.insert( dock->windowTitle(), PanelStatus( dock->isVisible(),
false ) );
860 dock->setVisible(
false );
864 for ( QTabBar *tabBar : tabBars )
866 QString currentTabTitle = tabBar->tabText( tabBar->currentIndex() );
867 mPanelStatus[ currentTabTitle ].isActive =
true;
873 for ( QDockWidget *dock : docks )
875 if ( mPanelStatus.contains( dock->windowTitle() ) )
877 dock->setVisible( mPanelStatus.value( dock->windowTitle() ).isVisible );
882 for ( QTabBar *tabBar : tabBars )
885 for (
int i = 0; i < tabBar->count(); ++i )
887 QString tabTitle = tabBar->tabText( i );
888 if ( mPanelStatus.contains( tabTitle ) && mPanelStatus.value( tabTitle ).isActive )
890 tabBar->setCurrentIndex( i );
894 mPanelStatus.clear();
898 void QgsModelDesignerDialog::validate()
901 if ( model()->validate( issues ) )
903 mMessageBar->pushSuccess( QString(), tr(
"Model is valid!" ) );
907 QgsMessageBarItem *messageWidget = mMessageBar->createMessage( QString(), tr(
"Model is invalid!" ) );
908 QPushButton *detailsButton =
new QPushButton( tr(
"Details" ) );
909 connect( detailsButton, &QPushButton::clicked, detailsButton, [ = ]
912 dialog->
setTitle( tr(
"Model is Invalid" ) );
914 QString longMessage = tr(
"<p>This model is not valid:</p>" ) + QStringLiteral(
"<ul>" );
915 for (
const QString &issue : issues )
917 longMessage += QStringLiteral(
"<li>%1</li>" ).arg( issue );
919 longMessage += QLatin1String(
"</ul>" );
924 messageWidget->layout()->addWidget( detailsButton );
925 mMessageBar->clearWidgets();
926 mMessageBar->pushWidget( messageWidget, Qgis::MessageLevel::Warning, 0 );
930 void QgsModelDesignerDialog::reorderInputs()
932 QgsModelInputReorderDialog dlg(
this );
933 dlg.setModel( mModel.get() );
936 const QStringList inputOrder = dlg.inputOrder();
937 beginUndoCommand( tr(
"Reorder Inputs" ) );
938 mModel->setParameterOrder( inputOrder );
943 bool QgsModelDesignerDialog::isDirty()
const
945 return mHasChanged && mUndoStack->index() != -1;
948 void QgsModelDesignerDialog::fillInputsTree()
951 std::unique_ptr< QTreeWidgetItem > parametersItem = std::make_unique< QTreeWidgetItem >();
952 parametersItem->setText( 0, tr(
"Parameters" ) );
956 return QString::localeAwareCompare( a->name(), b->name() ) < 0;
963 std::unique_ptr< QTreeWidgetItem > paramItem = std::make_unique< QTreeWidgetItem >();
964 paramItem->setText( 0, param->name() );
965 paramItem->setData( 0, Qt::UserRole, param->id() );
966 paramItem->setIcon( 0, icon );
967 paramItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled );
968 paramItem->setToolTip( 0, param->description() );
969 parametersItem->addChild( paramItem.release() );
972 mInputsTreeWidget->addTopLevelItem( parametersItem.release() );
973 mInputsTreeWidget->topLevelItem( 0 )->setExpanded(
true );
981 QgsModelChildDependenciesWidget::QgsModelChildDependenciesWidget( QWidget *parent, QgsProcessingModelAlgorithm *model,
const QString &childId )
984 , mChildId( childId )
986 QHBoxLayout *hl =
new QHBoxLayout();
987 hl->setContentsMargins( 0, 0, 0, 0 );
989 mLineEdit =
new QLineEdit();
990 mLineEdit->setEnabled(
false );
991 hl->addWidget( mLineEdit, 1 );
993 mToolButton =
new QToolButton();
994 mToolButton->setText( QString( QChar( 0x2026 ) ) );
995 hl->addWidget( mToolButton );
999 mLineEdit->setText( tr(
"%1 dependencies selected" ).arg( 0 ) );
1001 connect( mToolButton, &QToolButton::clicked,
this, &QgsModelChildDependenciesWidget::showDialog );
1004 void QgsModelChildDependenciesWidget::setValue(
const QList<QgsProcessingModelChildDependency> &value )
1008 updateSummaryText();
1011 void QgsModelChildDependenciesWidget::showDialog()
1013 const QList<QgsProcessingModelChildDependency> available = mModel->availableDependenciesForChildAlgorithm( mChildId );
1015 QVariantList availableOptions;
1016 for (
const QgsProcessingModelChildDependency &dep : available )
1017 availableOptions << QVariant::fromValue( dep );
1018 QVariantList selectedOptions;
1019 for (
const QgsProcessingModelChildDependency &dep : mValue )
1020 selectedOptions << QVariant::fromValue( dep );
1025 QgsProcessingMultipleSelectionPanelWidget *widget =
new QgsProcessingMultipleSelectionPanelWidget( availableOptions, selectedOptions );
1026 widget->setPanelTitle( tr(
"Algorithm Dependencies" ) );
1028 widget->setValueFormatter( [ = ](
const QVariant & v ) -> QString
1030 const QgsProcessingModelChildDependency dep = v.value< QgsProcessingModelChildDependency >();
1032 const QString description = mModel->childAlgorithm( dep.childId ).description();
1033 if ( dep.conditionalBranch.isEmpty() )
1036 return tr(
"Condition “%1” from algorithm “%2”" ).arg( dep.conditionalBranch, description );
1039 connect( widget, &QgsProcessingMultipleSelectionPanelWidget::selectionChanged,
this, [ = ]()
1041 QList< QgsProcessingModelChildDependency > res;
1042 for (
const QVariant &v : widget->selectedOptions() )
1044 res << v.value< QgsProcessingModelChildDependency >();
1053 void QgsModelChildDependenciesWidget::updateSummaryText()
1055 mLineEdit->setText( tr(
"%1 dependencies selected" ).arg( 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 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.