diff --git a/docs/guide/advanced.rst b/docs/guide/advanced.rst index 82ba1882..aeb5d326 100644 --- a/docs/guide/advanced.rst +++ b/docs/guide/advanced.rst @@ -39,6 +39,9 @@ inputs like "Add N Numbers" or "Merge Arrays". // 3. Complete: library restores shifted connections portsInserted(); + + // 4. The port count changed: let the scene recompute the node size + emit nodeUpdated(nodeId); } void MyModel::removePortFromNode(NodeId nodeId, PortIndex portIndex) @@ -51,6 +54,9 @@ inputs like "Add N Numbers" or "Merge Arrays". // 3. Complete portsDeleted(); + + // 4. The port count changed: let the scene recompute the node size + emit nodeUpdated(nodeId); } **In NodeDelegateModel:** @@ -66,6 +72,9 @@ inputs like "Add N Numbers" or "Merge Arrays". emit portsInserted(); } +``DataFlowGraphModel`` updates the node after ``portsInserted()`` and ``portsDeleted()``. +A delegate does not need to emit ``requestNodeUpdate()`` for the port change. + .. warning:: Always use the two-phase approach. Modifying ports without the diff --git a/docs/guide/data-flow.rst b/docs/guide/data-flow.rst index b8a2c19a..2f161af4 100644 --- a/docs/guide/data-flow.rst +++ b/docs/guide/data-flow.rst @@ -177,8 +177,27 @@ Implementing Data Flow **Signals to emit:** -- ``dataUpdated(portIndex)`` -- Output data changed, propagate downstream -- ``dataInvalidated(portIndex)`` -- Output is no longer valid +- ``dataUpdated(portIndex)`` -- Output data changed. ``DataFlowGraphModel`` calls + ``outData()`` and sends the value to all connected inputs. To clear the inputs + downstream, return ``nullptr`` from ``outData()`` and emit ``dataUpdated``. +- ``dataInvalidated(portIndex)`` -- Output is no longer valid. ``DataFlowGraphModel`` sends + empty data (``nullptr``) to all connected inputs. ``dataUpdated`` with a ``nullptr`` + output has the same effect. +- ``requestNodeUpdate()`` -- Something visible changed that has no signal of its own, + for example after ``setNodeStyle()``, ``setNodeProcessingStatus()``, + ``setValidationState()`` or ``setProgressValue()``. The model emits ``nodeUpdated`` + and the scene recomputes the size and repaints the node. +- ``embeddedWidgetSizeUpdated()`` -- The embedded widget changed its size. The model + emits ``nodeUpdated``, like for ``requestNodeUpdate()``. +- ``portsAboutToBeInserted()`` / ``portsInserted()`` and ``portsAboutToBeDeleted()`` / + ``portsDeleted()`` -- The port count changes. See :doc:`advanced`. The model fixes the + connections, emits its port signals and then ``nodeUpdated``. + +**Signals for the application:** + +``computingStarted()`` and ``computingFinished()`` have no listener in the library. Emitting +them changes nothing in the model or on the scene. Your application can connect to them, for +example to show a busy state, as the ``calculator`` example does. Data Flow Diagram ----------------- diff --git a/docs/guide/graph-models.rst b/docs/guide/graph-models.rst index fed51af6..a33622f4 100644 --- a/docs/guide/graph-models.rst +++ b/docs/guide/graph-models.rst @@ -279,6 +279,28 @@ Your model **must** emit these signals at the appropriate times: // After removing a connection emit connectionDeleted(connectionId); + // After nodeFlags() changed, for example a node was locked + emit nodeFlagsUpdated(nodeId); + +Do not emit ``nodeUpdated`` when ``NodeRole::Size`` is set. The scene sets ``Size`` +while it handles ``nodeUpdated``. + +Emit ``modelReset()`` only when you replace the whole graph. The scene deletes all +items, groups and embedded widgets, builds them again and clears the undo stack. + +When the port count of a node changes, call the connection fix-up methods around the +change and emit ``nodeUpdated`` at the end, so that the scene recomputes the node size: + +.. code-block:: cpp + + portsAboutToBeInserted(nodeId, PortType::In, first, last); // fixes connections + // ... change the port count ... + portsInserted(); // restores connections + emit nodeUpdated(nodeId); + +The deletion is the same with ``portsAboutToBeDeleted()`` and ``portsDeleted()``. +``DataFlowGraphModel`` does all of this when a delegate changes its ports. + .. warning:: Forgetting to emit signals will cause the view to become out of sync diff --git a/docs/guide/undo-redo.rst b/docs/guide/undo-redo.rst index 5e2ea36a..0068a189 100644 --- a/docs/guide/undo-redo.rst +++ b/docs/guide/undo-redo.rst @@ -14,7 +14,7 @@ automatically push commands to this stack: - Creating connections - Deleting connections - Moving nodes -- Duplicating nodes +- Pasting and duplicating nodes Accessing the Undo Stack ------------------------ @@ -47,10 +47,14 @@ QtNodes provides these ``QUndoCommand`` implementations in ``UndoCommands.cpp``: * - Command - Description + * - ``CreateCommand`` + - Creates a node * - ``DeleteCommand`` - Removes nodes and their connections - * - ``DuplicateCommand`` - - Duplicates selected nodes + * - ``CopyCommand`` + - Copies the selection to the clipboard. It does not stay on the stack + * - ``PasteCommand`` + - Inserts the nodes and connections from the clipboard * - ``DisconnectCommand`` - Removes a connection * - ``ConnectCommand`` @@ -58,6 +62,8 @@ QtNodes provides these ``QUndoCommand`` implementations in ``UndoCommands.cpp``: * - ``MoveNodeCommand`` - Moves a node to a new position +Duplicate has no command of its own. It pushes a ``CopyCommand`` and a ``PasteCommand``. + Serialization Requirement ------------------------- @@ -168,6 +174,10 @@ Use macros to group multiple commands: Clearing History ---------------- +``BasicGraphicsScene::clearScene()`` deletes the nodes without an undo step, so it clears the +stack. A ``modelReset`` and ``DataFlowGraphicsScene::load()`` clear it too. The commands on +the stack refer to nodes by id, and these nodes are gone. + .. code-block:: cpp // Clear all undo history @@ -189,7 +199,7 @@ Default shortcuts (handled by ``GraphicsView``): - ``Ctrl+Z`` -- Undo - ``Ctrl+Shift+Z`` or ``Ctrl+Y`` -- Redo - ``Delete`` -- Delete selection (creates ``DeleteCommand``) -- ``Ctrl+D`` -- Duplicate (creates ``DuplicateCommand``) +- ``Ctrl+D`` -- Duplicate (creates ``CopyCommand`` and ``PasteCommand``) .. seealso:: diff --git a/docs/guide/visualization.rst b/docs/guide/visualization.rst index 6e2265f0..e3defcbe 100644 --- a/docs/guide/visualization.rst +++ b/docs/guide/visualization.rst @@ -237,6 +237,15 @@ Connect to user interactions: // Show connection info }); + // Connection interactions + connect(&scene, &BasicGraphicsScene::connectionSelected, [](ConnectionId id) { + // Show the connection in a side panel + }); + + connect(&scene, &BasicGraphicsScene::connectionDoubleClicked, [](ConnectionId id) { + // Open an editor for the connection + }); + // Context menus connect(&scene, &BasicGraphicsScene::nodeContextMenu, [](NodeId id, QPointF scenePos) { diff --git a/include/QtNodes/internal/AbstractGraphModel.hpp b/include/QtNodes/internal/AbstractGraphModel.hpp index 9901cd08..b948e492 100644 --- a/include/QtNodes/internal/AbstractGraphModel.hpp +++ b/include/QtNodes/internal/AbstractGraphModel.hpp @@ -215,8 +215,10 @@ class NODE_EDITOR_PUBLIC AbstractGraphModel : public QObject PortIndex const last); /** - * Signal emitted when model no longer has the old data associated with the - * given port indices and when the node must be repainted. + * Function re-creates the connections that were shifted during the port + * deletion. Call it when the model no longer has the old data of the + * deleted ports. It does not update the node: the model must emit + * `nodeUpdated` after this call, so that the scene recomputes the size. */ void portsDeleted(); @@ -236,7 +238,8 @@ class NODE_EDITOR_PUBLIC AbstractGraphModel : public QObject /** * Function re-creates the connections that were shifted during the port - * insertion. After that the node is updated. + * insertion. It does not update the node: the model must emit + * `nodeUpdated` after this call, so that the scene recomputes the size. */ void portsInserted(); diff --git a/include/QtNodes/internal/BasicGraphicsScene.hpp b/include/QtNodes/internal/BasicGraphicsScene.hpp index 1e2bc2a4..756d2fd8 100644 --- a/include/QtNodes/internal/BasicGraphicsScene.hpp +++ b/include/QtNodes/internal/BasicGraphicsScene.hpp @@ -103,6 +103,7 @@ class NODE_EDITOR_PUBLIC BasicGraphicsScene : public QGraphicsScene void resetDraftConnection(); /// Deletes all the nodes. Connections are removed automatically. + /// The deletion is not an undo step, so the function also clears the undo stack. void clearScene(); /** @@ -280,6 +281,12 @@ class NODE_EDITOR_PUBLIC BasicGraphicsScene : public QGraphicsScene void zoomFitAllClicked(); void zoomFitSelectedClicked(); + /// A press on a connection left it selected. Like `nodeSelected` for nodes. + void connectionSelected(ConnectionId const connectionId); + + /// A double click on a connection. Like `nodeDoubleClicked` for nodes. + void connectionDoubleClicked(ConnectionId const connectionId); + private: /** * @brief Creates Node and Connection graphics objects. diff --git a/include/QtNodes/internal/ConnectionGraphicsObject.hpp b/include/QtNodes/internal/ConnectionGraphicsObject.hpp index 03c06a03..d638483b 100644 --- a/include/QtNodes/internal/ConnectionGraphicsObject.hpp +++ b/include/QtNodes/internal/ConnectionGraphicsObject.hpp @@ -73,6 +73,8 @@ class NODE_EDITOR_PUBLIC ConnectionGraphicsObject : public QGraphicsObject void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; + private: void initializePosition(); diff --git a/include/QtNodes/internal/DataFlowGraphModel.hpp b/include/QtNodes/internal/DataFlowGraphModel.hpp index de54d199..f378412d 100644 --- a/include/QtNodes/internal/DataFlowGraphModel.hpp +++ b/include/QtNodes/internal/DataFlowGraphModel.hpp @@ -113,6 +113,9 @@ class NODE_EDITOR_PUBLIC DataFlowGraphModel void sendConnectionDeletion(ConnectionId const connectionId); + /// Connects the signals of a new or restored delegate to this model. + void connectDelegateModel(NodeId const nodeId, NodeDelegateModel *model); + private Q_SLOTS: /** * Fuction is called in three cases: @@ -126,6 +129,8 @@ private Q_SLOTS: */ void onOutPortDataUpdated(NodeId const nodeId, PortIndex const portIndex); + void onOutPortDataInvalidated(NodeId const nodeId, PortIndex const portIndex); + /// Function is called after detaching a connection. void propagateEmptyDataTo(NodeId const nodeId, PortIndex const portIndex); diff --git a/include/QtNodes/internal/GroupGraphicsObject.hpp b/include/QtNodes/internal/GroupGraphicsObject.hpp index 474c3f4d..116cc098 100644 --- a/include/QtNodes/internal/GroupGraphicsObject.hpp +++ b/include/QtNodes/internal/GroupGraphicsObject.hpp @@ -83,6 +83,12 @@ class NODE_EDITOR_PUBLIC GroupGraphicsObject */ QRectF boundingRect() const override; + /** + * @brief Recomputes the group area from the areas of its nodes. It is called + * when a node of the group moves, changes its size, joins or leaves. + */ + void updateGeometry(); + enum { Type = UserType + 3 }; /** diff --git a/include/QtNodes/internal/NodeDelegateModel.hpp b/include/QtNodes/internal/NodeDelegateModel.hpp index bb359a45..7062fc5c 100644 --- a/include/QtNodes/internal/NodeDelegateModel.hpp +++ b/include/QtNodes/internal/NodeDelegateModel.hpp @@ -154,15 +154,27 @@ public Q_SLOTS: virtual void outputConnectionDeleted(ConnectionId const &) {} Q_SIGNALS: - /// Triggers the updates in the nodes downstream. + /// Triggers the updates in the nodes downstream. `DataFlowGraphModel` calls + /// `outData(index)` and sends the result to all connected inputs. A `nullptr` + /// output clears the inputs downstream. void dataUpdated(PortIndex const index); - /// Triggers the propagation of the empty data downstream. + /** + * Tells the model that the output at `index` is no longer valid. + * `DataFlowGraphModel` sends empty data (`nullptr`) to the inputs that are + * connected to this output. + */ void dataInvalidated(PortIndex const index); + /// For the application. The library does not listen to these signals. void computingStarted(); void computingFinished(); + /** + * Emit this signal after the embedded widget changed its size. + * `DataFlowGraphModel` emits `nodeUpdated` for the node, like for + * `requestNodeUpdate`, so that the scene recomputes the node size. + */ void embeddedWidgetSizeUpdated(); /// Request an update of the node's UI. diff --git a/include/QtNodes/internal/NodeGraphicsObject.hpp b/include/QtNodes/internal/NodeGraphicsObject.hpp index e3226802..2e8c88ff 100644 --- a/include/QtNodes/internal/NodeGraphicsObject.hpp +++ b/include/QtNodes/internal/NodeGraphicsObject.hpp @@ -97,6 +97,7 @@ class NODE_EDITOR_PUBLIC NodeGraphicsObject : public QGraphicsObject private: void embedQWidget(); void setLockedState(); + void updateGroupGeometry() const; private: NodeId _nodeId; diff --git a/src/BasicGraphicsScene.cpp b/src/BasicGraphicsScene.cpp index 6dee5710..c08931c7 100644 --- a/src/BasicGraphicsScene.cpp +++ b/src/BasicGraphicsScene.cpp @@ -239,6 +239,9 @@ void BasicGraphicsScene::clearScene() for (auto nodeId : allNodeIds) { graphModel().deleteNode(nodeId); } + + // The deletion is not an undo step. + _undoStack->clear(); } std::vector> BasicGraphicsScene::connectionsWithinGroup(GroupId groupID) @@ -417,6 +420,9 @@ void BasicGraphicsScene::onNodeUpdated(NodeId const nodeId) node->updateQWidgetEmbedPos(); node->update(); node->moveConnections(); + + if (auto group = node->nodeGroup().lock()) + group->groupGraphicsObject().updateGeometry(); } } @@ -439,6 +445,8 @@ void BasicGraphicsScene::onModelReset() clear(); + _undoStack->clear(); + traverseGraphAndPopulateGraphicsObjects(); } @@ -675,7 +683,9 @@ std::unordered_map BasicGraphicsScene::loadItems(const QByteArray offsetInitialized = true; } if (usePastePos) { - nodeRef.moveBy(offset.x(), offset.y()); + // Move through the model, so that the model and the item agree. + QPointF const pos = _graphModel.nodeData(newNodeId, NodeRole::Position); + _graphModel.setNodeData(newNodeId, NodeRole::Position, pos + offset); } nodeRef.moveConnections(); nodeRef.setSelected(true); diff --git a/src/ConnectionGraphicsObject.cpp b/src/ConnectionGraphicsObject.cpp index 05ae46b3..b392a53c 100644 --- a/src/ConnectionGraphicsObject.cpp +++ b/src/ConnectionGraphicsObject.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -204,6 +205,17 @@ void ConnectionGraphicsObject::paint(QPainter *painter, void ConnectionGraphicsObject::mousePressEvent(QGraphicsSceneMouseEvent *event) { QGraphicsItem::mousePressEvent(event); + + if (isSelected()) { + Q_EMIT nodeScene()->connectionSelected(connectionId()); + } +} + +void ConnectionGraphicsObject::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsItem::mouseDoubleClickEvent(event); + + Q_EMIT nodeScene()->connectionDoubleClicked(connectionId()); } void ConnectionGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event) diff --git a/src/DataFlowGraphModel.cpp b/src/DataFlowGraphModel.cpp index 2a812830..134438c7 100644 --- a/src/DataFlowGraphModel.cpp +++ b/src/DataFlowGraphModel.cpp @@ -59,6 +59,50 @@ bool DataFlowGraphModel::connectionExists(ConnectionId const connectionId) const return (_connectivity.find(connectionId) != _connectivity.end()); } +void DataFlowGraphModel::connectDelegateModel(NodeId const nodeId, NodeDelegateModel *model) +{ + connect(model, &NodeDelegateModel::dataUpdated, [nodeId, this](PortIndex const portIndex) { + onOutPortDataUpdated(nodeId, portIndex); + }); + + connect(model, &NodeDelegateModel::dataInvalidated, [nodeId, this](PortIndex const portIndex) { + onOutPortDataInvalidated(nodeId, portIndex); + }); + + connect(model, + &NodeDelegateModel::portsAboutToBeDeleted, + this, + [nodeId, this](PortType const portType, PortIndex const first, PortIndex const last) { + portsAboutToBeDeleted(nodeId, portType, first, last); + }); + + // The port count changed, so the node size changes too. + connect(model, &NodeDelegateModel::portsDeleted, this, [nodeId, this]() { + portsDeleted(); + Q_EMIT nodeUpdated(nodeId); + }); + + connect(model, + &NodeDelegateModel::portsAboutToBeInserted, + this, + [nodeId, this](PortType const portType, PortIndex const first, PortIndex const last) { + portsAboutToBeInserted(nodeId, portType, first, last); + }); + + connect(model, &NodeDelegateModel::portsInserted, this, [nodeId, this]() { + portsInserted(); + Q_EMIT nodeUpdated(nodeId); + }); + + connect(model, &NodeDelegateModel::requestNodeUpdate, this, [nodeId, this]() { + Q_EMIT nodeUpdated(nodeId); + }); + + connect(model, &NodeDelegateModel::embeddedWidgetSizeUpdated, this, [nodeId, this]() { + Q_EMIT nodeUpdated(nodeId); + }); +} + NodeId DataFlowGraphModel::addNode(QString const nodeType) { std::unique_ptr model = _registry->create(nodeType); @@ -66,39 +110,7 @@ NodeId DataFlowGraphModel::addNode(QString const nodeType) if (model) { NodeId newId = newNodeId(); - connect(model.get(), - &NodeDelegateModel::dataUpdated, - [newId, this](PortIndex const portIndex) { - onOutPortDataUpdated(newId, portIndex); - }); - - connect(model.get(), - &NodeDelegateModel::portsAboutToBeDeleted, - this, - [newId, this](PortType const portType, PortIndex const first, PortIndex const last) { - portsAboutToBeDeleted(newId, portType, first, last); - }); - - connect(model.get(), - &NodeDelegateModel::portsDeleted, - this, - &DataFlowGraphModel::portsDeleted); - - connect(model.get(), - &NodeDelegateModel::portsAboutToBeInserted, - this, - [newId, this](PortType const portType, PortIndex const first, PortIndex const last) { - portsAboutToBeInserted(newId, portType, first, last); - }); - - connect(model.get(), - &NodeDelegateModel::portsInserted, - this, - &DataFlowGraphModel::portsInserted); - - connect(model.get(), &NodeDelegateModel::requestNodeUpdate, this, [newId, this]() { - Q_EMIT nodeUpdated(newId); - }); + connectDelegateModel(newId, model.get()); _models[newId] = std::move(model); @@ -613,41 +625,7 @@ void DataFlowGraphModel::loadNode(QJsonObject const &nodeJson) std::unique_ptr model = _registry->create(delegateModelName); if (model) { - connect(model.get(), - &NodeDelegateModel::dataUpdated, - [restoredNodeId, this](PortIndex const portIndex) { - onOutPortDataUpdated(restoredNodeId, portIndex); - }); - - connect(model.get(), - &NodeDelegateModel::portsAboutToBeDeleted, - this, - [restoredNodeId, - this](PortType const portType, PortIndex const first, PortIndex const last) { - portsAboutToBeDeleted(restoredNodeId, portType, first, last); - }); - - connect(model.get(), - &NodeDelegateModel::portsDeleted, - this, - &DataFlowGraphModel::portsDeleted); - - connect(model.get(), - &NodeDelegateModel::portsAboutToBeInserted, - this, - [restoredNodeId, - this](PortType const portType, PortIndex const first, PortIndex const last) { - portsAboutToBeInserted(restoredNodeId, portType, first, last); - }); - - connect(model.get(), - &NodeDelegateModel::portsInserted, - this, - &DataFlowGraphModel::portsInserted); - - connect(model.get(), &NodeDelegateModel::requestNodeUpdate, this, [restoredNodeId, this]() { - Q_EMIT nodeUpdated(restoredNodeId); - }); + connectDelegateModel(restoredNodeId, model.get()); _models[restoredNodeId] = std::move(model); @@ -665,6 +643,9 @@ void DataFlowGraphModel::loadNode(QJsonObject const &nodeJson) : restoredModel->labelVisible(); restoredModel->load(internalDataJson); + + // nodeCreated came before the label and the delegate state. Update the node once more. + Q_EMIT nodeUpdated(restoredNodeId); } else { throw std::logic_error(std::string("No registered model with name ") + delegateModelName.toLocal8Bit().data()); @@ -704,6 +685,18 @@ void DataFlowGraphModel::onOutPortDataUpdated(NodeId const nodeId, PortIndex con } } +void DataFlowGraphModel::onOutPortDataInvalidated(NodeId const nodeId, PortIndex const portIndex) +{ + // The output has no valid data. The connected inputs get no data. + std::unordered_set const &connected = connections(nodeId, + PortType::Out, + portIndex); + + for (auto const &cn : connected) { + propagateEmptyDataTo(cn.inNodeId, cn.inPortIndex); + } +} + void DataFlowGraphModel::propagateEmptyDataTo(NodeId const nodeId, PortIndex const portIndex) { QVariant emptyData{}; diff --git a/src/GraphicsView.cpp b/src/GraphicsView.cpp index 51adad2d..540a7862 100644 --- a/src/GraphicsView.cpp +++ b/src/GraphicsView.cpp @@ -83,18 +83,33 @@ QAction *GraphicsView::deleteSelectionAction() const return _deleteSelectionAction; } +namespace { + +// The undo and redo actions have no member pointer. Find the ones of the previous scene by name. +QString const undoActionName = QStringLiteral("QtNodesUndoAction"); +QString const redoActionName = QStringLiteral("QtNodesRedoAction"); + +} // namespace + void GraphicsView::setScene(BasicGraphicsScene *scene) { QGraphicsView::setScene(scene); + + for (QString const &name : {undoActionName, redoActionName}) { + qDeleteAll(findChildren(name, Qt::FindDirectChildrenOnly)); + } + if (!scene) { // Clear actions. delete _clearSelectionAction; delete _deleteSelectionAction; + delete _cutSelectionAction; delete _duplicateSelectionAction; delete _copySelectionAction; delete _pasteAction; _clearSelectionAction = nullptr; _deleteSelectionAction = nullptr; + _cutSelectionAction = nullptr; _duplicateSelectionAction = nullptr; _copySelectionAction = nullptr; _pasteAction = nullptr; @@ -181,10 +196,12 @@ void GraphicsView::setScene(BasicGraphicsScene *scene) } auto undoAction = scene->undoStack().createUndoAction(this, tr("&Undo")); + undoAction->setObjectName(undoActionName); undoAction->setShortcuts(QKeySequence::Undo); addAction(undoAction); auto redoAction = scene->undoStack().createRedoAction(this, tr("&Redo")); + redoAction->setObjectName(redoActionName); redoAction->setShortcuts(QKeySequence::Redo); addAction(redoAction); } diff --git a/src/GroupGraphicsObject.cpp b/src/GroupGraphicsObject.cpp index 1aac8e61..78499e10 100644 --- a/src/GroupGraphicsObject.cpp +++ b/src/GroupGraphicsObject.cpp @@ -58,6 +58,8 @@ GroupGraphicsObject::GroupGraphicsObject(BasicGraphicsScene &scene, NodeGroup &n setZValue(-_groupAreaZValue); setAcceptHoverEvents(true); + + updateGeometry(); } GroupGraphicsObject::~GroupGraphicsObject() @@ -76,6 +78,11 @@ NodeGroup const &GroupGraphicsObject::group() const } QRectF GroupGraphicsObject::boundingRect() const +{ + return rect(); +} + +void GroupGraphicsObject::updateGeometry() { QRectF ret{}; for (auto &node : _group.childNodes()) { @@ -84,7 +91,14 @@ QRectF GroupGraphicsObject::boundingRect() const if (_possibleChild) { ret |= _possibleChild->mapRectToScene(_possibleChild->boundingRect()); } - return mapRectFromScene(ret.marginsAdded(_margins)); + + QRectF const newRect = mapRectFromScene(ret.marginsAdded(_margins)); + if (newRect == rect()) + return; + + // setRect() calls prepareGeometryChange(). + setRect(newRect); + positionLockedIcon(); } void GroupGraphicsObject::setFillColor(const QColor &color) @@ -159,11 +173,13 @@ void GroupGraphicsObject::setHovered(bool hovered) void GroupGraphicsObject::setPossibleChild(QtNodes::NodeGraphicsObject *possibleChild) { _possibleChild = possibleChild; + updateGeometry(); } void GroupGraphicsObject::unsetPossibleChild() { _possibleChild = nullptr; + updateGeometry(); } std::vector> GroupGraphicsObject::connections() const @@ -230,9 +246,6 @@ void GroupGraphicsObject::paint(QPainter *painter, QWidget *widget) { Q_UNUSED(widget); - prepareGeometryChange(); - setRect(boundingRect()); - positionLockedIcon(); painter->setClipRect(option->exposedRect); painter->setBrush(_currentFillColor); diff --git a/src/NodeGraphicsObject.cpp b/src/NodeGraphicsObject.cpp index 03f5f696..d0cf615f 100644 --- a/src/NodeGraphicsObject.cpp +++ b/src/NodeGraphicsObject.cpp @@ -33,6 +33,8 @@ NodeGraphicsObject::NodeGraphicsObject(BasicGraphicsScene &scene, NodeId nodeId) setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true); setFlag(QGraphicsItem::ItemIsFocusable, true); + // Connections follow the node through itemChange(), also when the node is locked. + setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true); setLockedState(); @@ -130,7 +132,6 @@ void NodeGraphicsObject::setLockedState() // so that one lock does not undo the other. setFlag(QGraphicsItem::ItemIsMovable, !modelLocked); setFlag(QGraphicsItem::ItemIsSelectable, !modelLocked && !_locked); - setFlag(QGraphicsItem::ItemSendsScenePositionChanges, !modelLocked); setFlag(QGraphicsItem::ItemIsFocusable, !_locked); } @@ -163,6 +164,13 @@ void NodeGraphicsObject::moveConnections() const } } +void NodeGraphicsObject::updateGroupGeometry() const +{ + // The box of the group contains this node, so it follows each change of the node area. + if (auto group = _nodeGroup.lock()) + group->groupGraphicsObject().updateGeometry(); +} + void NodeGraphicsObject::reactToConnection(ConnectionGraphicsObject const *cgo) { _nodeState.storeConnectionForReaction(cgo); @@ -191,6 +199,7 @@ QVariant NodeGraphicsObject::itemChange(GraphicsItemChange change, const QVarian { if (change == ItemScenePositionHasChanged && scene()) { moveConnections(); + updateGroupGeometry(); } return QGraphicsObject::itemChange(change, value); @@ -309,6 +318,7 @@ void NodeGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event) update(); moveConnections(); + updateGroupGeometry(); event->accept(); } diff --git a/src/NodeGroup.cpp b/src/NodeGroup.cpp index 8406b2c8..bee15325 100644 --- a/src/NodeGroup.cpp +++ b/src/NodeGroup.cpp @@ -117,8 +117,10 @@ int NodeGroup::groupCount() void NodeGroup::addNode(NodeGraphicsObject *node) { _childNodes.push_back(node); - if (_groupGraphicsObject && _groupGraphicsObject->locked()) { - node->lock(true); + if (_groupGraphicsObject) { + if (_groupGraphicsObject->locked()) + node->lock(true); + _groupGraphicsObject->updateGeometry(); } } @@ -129,6 +131,7 @@ void NodeGroup::removeNode(NodeGraphicsObject *node) if (nodeIt != _childNodes.end()) { (*nodeIt)->unsetNodeGroup(); _childNodes.erase(nodeIt); - groupGraphicsObject().positionLockedIcon(); + if (_groupGraphicsObject) + _groupGraphicsObject->updateGeometry(); } } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index a84d440b..a93ab385 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -34,6 +34,12 @@ add_executable(test_nodes src/TestWidgetPosition.cpp src/TestOrientationWidgets.cpp src/TestViewDragMode.cpp + src/TestNodeSizeUpdates.cpp + src/TestSceneSetup.cpp + src/TestLockAndPaste.cpp + src/TestGroupRepaint.cpp + src/TestNotifications.cpp + src/TestDataInvalidated.cpp include/ApplicationSetup.hpp include/TestGraphModel.hpp include/UITestHelper.hpp diff --git a/test/src/TestDataInvalidated.cpp b/test/src/TestDataInvalidated.cpp new file mode 100644 index 00000000..3ceed3ac --- /dev/null +++ b/test/src/TestDataInvalidated.cpp @@ -0,0 +1,84 @@ +#include "ApplicationSetup.hpp" + +#include +#include +#include +#include + +#include + +#include + +using namespace QtNodes; + +namespace { + +class NumberData : public NodeData +{ +public: + NodeDataType type() const override { return {"number", "Number"}; } +}; + +class InvalidatingSource : public NodeDelegateModel +{ +public: + QString name() const override { return QStringLiteral("InvalidatingSource"); } + QString caption() const override { return QStringLiteral("Source"); } + unsigned int nPorts(PortType type) const override { return type == PortType::Out ? 1 : 0; } + NodeDataType dataType(PortType, PortIndex) const override { return NumberData{}.type(); } + void setInData(std::shared_ptr, PortIndex) override {} + std::shared_ptr outData(PortIndex) override { return std::make_shared(); } + QWidget *embeddedWidget() override { return nullptr; } +}; + +class RecordingSink : public NodeDelegateModel +{ +public: + QString name() const override { return QStringLiteral("RecordingSink"); } + QString caption() const override { return QStringLiteral("Sink"); } + unsigned int nPorts(PortType type) const override { return type == PortType::In ? 1 : 0; } + NodeDataType dataType(PortType, PortIndex) const override { return NumberData{}.type(); } + void setInData(std::shared_ptr data, PortIndex) override + { + received = data; + ++calls; + } + std::shared_ptr outData(PortIndex) override { return nullptr; } + QWidget *embeddedWidget() override { return nullptr; } + + std::shared_ptr received; + int calls = 0; +}; + +} // namespace + +TEST_CASE("dataInvalidated sends empty data to the inputs that are connected to the port", + "[dataflow][invalidated]") +{ + auto app = applicationSetup(); + + auto registry = std::make_shared(); + registry->registerModel(); + registry->registerModel(); + DataFlowGraphModel model(registry); + + NodeId const source = model.addNode(QStringLiteral("InvalidatingSource")); + NodeId const sink = model.addNode(QStringLiteral("RecordingSink")); + model.addConnection(ConnectionId{source, 0, sink, 0}); + + auto *sourceModel = model.delegateModel(source); + auto *sinkModel = model.delegateModel(sink); + + Q_EMIT sourceModel->dataUpdated(0); + REQUIRE(sinkModel->received != nullptr); + + int const callsBefore = sinkModel->calls; + Q_EMIT sourceModel->dataInvalidated(0); + + CHECK(sinkModel->calls == callsBefore + 1); + CHECK(sinkModel->received == nullptr); + + // Valid data flows again after an invalidation. + Q_EMIT sourceModel->dataUpdated(0); + CHECK(sinkModel->received != nullptr); +} diff --git a/test/src/TestGroupRepaint.cpp b/test/src/TestGroupRepaint.cpp new file mode 100644 index 00000000..39ac6cbb --- /dev/null +++ b/test/src/TestGroupRepaint.cpp @@ -0,0 +1,133 @@ +#include "ApplicationSetup.hpp" +#include "TestGraphModel.hpp" +#include "UITestHelper.hpp" + +#include +#include +#include +#include +#include + +#include + +#include +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::ConnectionId; +using QtNodes::GraphicsView; +using QtNodes::NodeGraphicsObject; +using QtNodes::NodeId; +using QtNodes::NodeRole; + +namespace { + +/// Counts the paint events of a widget. +class PaintCounter : public QObject +{ +public: + int paints = 0; + +protected: + bool eventFilter(QObject *watched, QEvent *event) override + { + if (event->type() == QEvent::Paint) + ++paints; + return QObject::eventFilter(watched, event); + } +}; + +bool groupContains(QtNodes::GroupGraphicsObject &group, NodeGraphicsObject &node) +{ + return group.sceneBoundingRect().contains(node.sceneBoundingRect()); +} + +} // namespace + +TEST_CASE("An idle view with a node group does not repaint", "[node-group][paint]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + GraphicsView view(&scene); + view.resize(800, 600); + view.show(); + REQUIRE(QTest::qWaitForWindowExposed(&view)); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(250, 0)); + model.addConnection(ConnectionId{a, 0, b, 0}); + + std::vector nodes{scene.nodeGraphicsObject(a), + scene.nodeGraphicsObject(b)}; + REQUIRE_FALSE(scene.createGroup(nodes, "Group").expired()); + UITestHelper::waitForUI(100); + + PaintCounter counter; + view.viewport()->installEventFilter(&counter); + UITestHelper::waitForUI(300); + + CHECK(counter.paints == 0); +} + +TEST_CASE("The box of a group follows its nodes when they move, join or leave", "[node-group]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + NodeId const c = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(250, 0)); + model.setNodeData(c, NodeRole::Position, QPointF(0, 600)); + + auto *nodeA = scene.nodeGraphicsObject(a); + auto *nodeB = scene.nodeGraphicsObject(b); + auto *nodeC = scene.nodeGraphicsObject(c); + + std::vector nodes{nodeA, nodeB}; + auto group = scene.createGroup(nodes, "Group").lock(); + REQUIRE(group); + auto &box = group->groupGraphicsObject(); + + CHECK(groupContains(box, *nodeA)); + CHECK(groupContains(box, *nodeB)); + CHECK_FALSE(groupContains(box, *nodeC)); + + model.setNodeData(b, NodeRole::Position, QPointF(900, 400)); + CHECK(groupContains(box, *nodeB)); + + scene.addNodeToGroup(c, group->id()); + CHECK(groupContains(box, *nodeC)); + + scene.removeNodeFromGroup(c); + CHECK_FALSE(groupContains(box, *nodeC)); +} + +TEST_CASE("The box of a group follows a node that changes its size", "[node-group]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(250, 0)); + + auto *nodeB = scene.nodeGraphicsObject(b); + std::vector nodes{scene.nodeGraphicsObject(a), nodeB}; + auto group = scene.createGroup(nodes, "Group").lock(); + REQUIRE(group); + auto &box = group->groupGraphicsObject(); + + qreal const widthBefore = nodeB->sceneBoundingRect().width(); + + // A longer caption makes the node wider. + model.setNodeData(b, NodeRole::Caption, QString(60, 'W')); + Q_EMIT model.nodeUpdated(b); + + REQUIRE(nodeB->sceneBoundingRect().width() > widthBefore); + CHECK(groupContains(box, *nodeB)); +} diff --git a/test/src/TestLockAndPaste.cpp b/test/src/TestLockAndPaste.cpp new file mode 100644 index 00000000..0f92780d --- /dev/null +++ b/test/src/TestLockAndPaste.cpp @@ -0,0 +1,101 @@ +#include "ApplicationSetup.hpp" +#include "LockableModel.hpp" +#include "TestDataFlowNodes.hpp" +#include "TestGraphModel.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::ConnectionId; +using QtNodes::DataFlowGraphModel; +using QtNodes::NodeDelegateModelRegistry; +using QtNodes::NodeFlag; +using QtNodes::NodeId; +using QtNodes::NodeRole; +using QtNodes::PortType; + +namespace { + +/// Counts the listeners of the signal for the lock state of a node. +class FlagsReceiversModel : public LockableModel +{ +public: + int flagsReceivers() const + { + QByteArray const signal + = "2" + QMetaMethod::fromSignal(&TestGraphModel::nodeFlagsUpdated).methodSignature(); + return receivers(signal.constData()); + } +}; + +QPointF connectionEnd(BasicGraphicsScene &scene, ConnectionId const &id, PortType portType) +{ + auto *cgo = scene.connectionGraphicsObject(id); + REQUIRE(cgo != nullptr); + return cgo->mapToScene(cgo->endPoint(portType)); +} + +QPointF portOnScene(BasicGraphicsScene &scene, NodeId id, PortType portType) +{ + auto *node = scene.nodeGraphicsObject(id); + REQUIRE(node != nullptr); + return scene.nodeGeometry().portScenePosition(id, portType, 0, node->sceneTransform()); +} + +} // namespace + +TEST_CASE("A model-locked node moved from code keeps its connections attached", "[node-lock]") +{ + auto app = applicationSetup(); + LockableModel model; + BasicGraphicsScene scene(model); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(300, 0)); + ConnectionId const c{a, 0, b, 0}; + model.addConnection(c); + + model.setLocked(a, true); + model.setNodeData(a, NodeRole::Position, QPointF(0, 200)); + + CHECK(connectionEnd(scene, c, PortType::Out) == portOnScene(scene, a, PortType::Out)); + + // The lock still keeps the node in place for the mouse. + auto *item = scene.nodeGraphicsObject(a); + CHECK_FALSE(item->flags().testFlag(QGraphicsItem::ItemIsMovable)); + CHECK_FALSE(item->flags().testFlag(QGraphicsItem::ItemIsSelectable)); +} + +TEST_CASE("Pasting at a position moves the node in the model, not only its item", "[copy-paste]") +{ + auto app = applicationSetup(); + auto registry = std::make_shared(); + registry->registerModel("Test"); + + DataFlowGraphModel source(registry); + NodeId const id = source.addNode("TestDisplayNode"); + source.setNodeData(id, NodeRole::Position, QPointF(10, 10)); + QByteArray const data = QJsonDocument(source.save()).toJson(); + + DataFlowGraphModel model(registry); + BasicGraphicsScene scene(model); + scene.loadItems(data, QPointF(500, 500), true); + + REQUIRE(model.allNodeIds().size() == 1); + NodeId const pasted = *model.allNodeIds().begin(); + + CHECK(model.nodeData(pasted, NodeRole::Position).toPointF() == QPointF(500, 500)); + CHECK(scene.nodeGraphicsObject(pasted)->pos() == QPointF(500, 500)); +} diff --git a/test/src/TestNodeSizeUpdates.cpp b/test/src/TestNodeSizeUpdates.cpp new file mode 100644 index 00000000..5634a775 --- /dev/null +++ b/test/src/TestNodeSizeUpdates.cpp @@ -0,0 +1,154 @@ +#include "ApplicationSetup.hpp" +#include "TestDataFlowNodes.hpp" +#include "TestDelegateModels.hpp" + +#include + +#include +#include +#include + +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::DataFlowGraphModel; +using QtNodes::NodeDelegateModelRegistry; +using QtNodes::NodeId; +using QtNodes::NodeRole; +using QtNodes::PortType; + +namespace { + +/// A delegate that adds and removes In ports at run time. +class DynamicInPorts : public StubDelegateModel +{ +public: + DynamicInPorts() + : StubDelegateModel("DynamicInPorts", "Dynamic") + {} + + unsigned int nPorts(PortType portType) const override + { + return portType == PortType::In ? _nIn : 1; + } + + void addInPort() + { + Q_EMIT portsAboutToBeInserted(PortType::In, _nIn, _nIn); + ++_nIn; + Q_EMIT portsInserted(); + } + + void removeInPort() + { + Q_EMIT portsAboutToBeDeleted(PortType::In, _nIn - 1, _nIn - 1); + --_nIn; + Q_EMIT portsDeleted(); + } + +private: + unsigned int _nIn = 1; +}; + +/// A source node that reports the size change of its widget. +class SizeReportingSource : public TestSourceNode +{ +public: + static QString Name() { return "SizeReportingSource"; } + QString name() const override { return Name(); } + + void growWidget() + { + embeddedWidget()->resize(embeddedWidget()->width() + 80, embeddedWidget()->height() + 60); + Q_EMIT embeddedWidgetSizeUpdated(); + } +}; + +std::shared_ptr makeRegistry() +{ + auto registry = std::make_shared(); + registry->registerModel("Test"); + registry->registerModel("Test"); + registry->registerModel([] { return std::make_unique(); }, "Test"); + return registry; +} + +QSize sizeOf(DataFlowGraphModel &model, NodeId id) +{ + return model.nodeData(id, NodeRole::Size).value(); +} + +} // namespace + +TEST_CASE("A node recomputes its size when its delegate inserts or deletes ports", + "[graphics][dynamic-ports]") +{ + auto app = applicationSetup(); + DataFlowGraphModel model(makeRegistry()); + BasicGraphicsScene scene(model); + + NodeId const id = model.addNode("DynamicInPorts"); + auto *delegate = model.delegateModel(id); + QSize const oneInPort = sizeOf(model, id); + + delegate->addInPort(); + QSize const twoInPorts = sizeOf(model, id); + CHECK(twoInPorts.height() > oneInPort.height()); + + // The size after the insert is the size that a full update computes. + scene.onNodeUpdated(id); + CHECK(sizeOf(model, id) == twoInPorts); + + delegate->removeInPort(); + CHECK(sizeOf(model, id) == oneInPort); +} + +TEST_CASE("A node loaded with a visible label has the size of a fully updated node", + "[graphics][serialization]") +{ + auto app = applicationSetup(); + auto registry = makeRegistry(); + + DataFlowGraphModel source(registry); + NodeId const id = source.addNode("TestDisplayNode"); + source.setNodeData(id, NodeRole::LabelVisible, true); + source.setNodeData(id, NodeRole::Label, QString("A rather long label for this node")); + QJsonObject const json = source.save(); + + DataFlowGraphModel model(registry); + BasicGraphicsScene scene(model); + QSignalSpy updated(&model, &DataFlowGraphModel::nodeUpdated); + + model.load(json); + + // One update per loaded node, after the label and the delegate state are restored. + CHECK(updated.count() == 1); + + NodeId const loaded = *model.allNodeIds().begin(); + QSize const afterLoad = sizeOf(model, loaded); + scene.onNodeUpdated(loaded); + CHECK(afterLoad == sizeOf(model, loaded)); +} + +TEST_CASE("embeddedWidgetSizeUpdated makes the node follow its widget, also after a load", + "[graphics][widget]") +{ + auto app = applicationSetup(); + DataFlowGraphModel model(makeRegistry()); + BasicGraphicsScene scene(model); + + NodeId const created = model.addNode("SizeReportingSource"); + + QJsonObject json = model.saveNode(created); + json["id"] = static_cast(created + 100); + model.loadNode(json); + NodeId const loaded = created + 100; + + for (NodeId const id : {created, loaded}) { + QSize const before = sizeOf(model, id); + model.delegateModel(id)->growWidget(); + QSize const after = sizeOf(model, id); + CHECK(after.width() == before.width() + 80); + CHECK(after.height() > before.height()); + } +} diff --git a/test/src/TestNotifications.cpp b/test/src/TestNotifications.cpp new file mode 100644 index 00000000..9c62dff1 --- /dev/null +++ b/test/src/TestNotifications.cpp @@ -0,0 +1,96 @@ +#include "ApplicationSetup.hpp" +#include "TestGraphModel.hpp" +#include "UITestHelper.hpp" + +#include +#include +#include + +#include + +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::ConnectionId; +using QtNodes::GraphicsView; +using QtNodes::NodeId; +using QtNodes::NodeRole; +using QtNodes::PortType; + +Q_DECLARE_METATYPE(QtNodes::ConnectionId) + +namespace { + +struct SceneWithConnection +{ + SceneWithConnection() + : scene(model) + , view(&scene) + { + qRegisterMetaType("ConnectionId"); + + view.resize(1000, 600); + view.show(); + REQUIRE(QTest::qWaitForWindowExposed(&view)); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(600, 0)); + connection = ConnectionId{a, 0, b, 0}; + model.addConnection(connection); + UITestHelper::waitForUI(); + + auto *cgo = scene.connectionGraphicsObject(connection); + REQUIRE(cgo != nullptr); + QPointF const out = cgo->mapToScene(cgo->endPoint(PortType::Out)); + QPointF const in = cgo->mapToScene(cgo->endPoint(PortType::In)); + middle = (out + in) / 2.0; + REQUIRE(scene.itemAt(middle, view.transform()) == cgo); + } + + TestGraphModel model; + BasicGraphicsScene scene; + GraphicsView view; + ConnectionId connection; + QPointF middle; +}; + +} // namespace + +TEST_CASE("A click on a connection emits connectionSelected once", "[graphics][signals]") +{ + auto app = applicationSetup(); + SceneWithConnection f; + QSignalSpy spy(&f.scene, &BasicGraphicsScene::connectionSelected); + + UITestHelper::simulateMousePress(&f.view, f.middle); + UITestHelper::simulateMouseRelease(&f.view, f.middle); + + REQUIRE(spy.count() == 1); + CHECK(spy.at(0).at(0).value() == f.connection); + CHECK(f.scene.connectionGraphicsObject(f.connection)->isSelected()); +} + +TEST_CASE("A double click on a connection emits connectionDoubleClicked once", + "[graphics][signals]") +{ + auto app = applicationSetup(); + SceneWithConnection f; + QSignalSpy spy(&f.scene, &BasicGraphicsScene::connectionDoubleClicked); + + UITestHelper::simulateMousePress(&f.view, f.middle); + UITestHelper::simulateMouseRelease(&f.view, f.middle); + + QPoint const viewPos = f.view.mapFromScene(f.middle); + QMouseEvent doubleClick(QEvent::MouseButtonDblClick, + viewPos, + f.view.viewport()->mapToGlobal(viewPos), + Qt::LeftButton, + Qt::LeftButton, + Qt::NoModifier); + QApplication::sendEvent(f.view.viewport(), &doubleClick); + UITestHelper::simulateMouseRelease(&f.view, f.middle); + + REQUIRE(spy.count() == 1); + CHECK(spy.at(0).at(0).value() == f.connection); +} diff --git a/test/src/TestSceneSetup.cpp b/test/src/TestSceneSetup.cpp new file mode 100644 index 00000000..dc79f80d --- /dev/null +++ b/test/src/TestSceneSetup.cpp @@ -0,0 +1,83 @@ +#include "ApplicationSetup.hpp" +#include "TestGraphModel.hpp" + +#include +#include +#include + +#include + +#include +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::CreateCommand; +using QtNodes::GraphicsView; + +namespace { + +int countActionsWithShortcut(GraphicsView &view, QKeySequence::StandardKey key) +{ + int n = 0; + for (QAction *action : view.actions()) { + if (action->shortcuts().contains(QKeySequence(key))) + ++n; + } + return n; +} + +} // namespace + +TEST_CASE("Clearing the scene empties the undo stack", "[undo]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + + scene.undoStack().push(new CreateCommand(&scene, "TestNode", QPointF(0, 0))); + REQUIRE(scene.undoStack().count() == 1); + + scene.clearScene(); + + CHECK(scene.undoStack().count() == 0); +} + +TEST_CASE("A model reset empties the undo stack", "[undo]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + + scene.undoStack().push(new CreateCommand(&scene, "TestNode", QPointF(0, 0))); + REQUIRE(scene.undoStack().count() == 1); + + Q_EMIT model.modelReset(); + + CHECK(scene.undoStack().count() == 0); +} + +TEST_CASE("Setting the scene of a view again keeps one Undo and one Redo action", "[view]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene first(model); + BasicGraphicsScene second(model); + + GraphicsView view(&first); + view.setScene(&second); + view.setScene(&first); + + CHECK(countActionsWithShortcut(view, QKeySequence::Undo) == 1); + CHECK(countActionsWithShortcut(view, QKeySequence::Redo) == 1); + + // The actions belong to the stack of the current scene. + first.undoStack().push(new CreateCommand(&first, "TestNode", QPointF(0, 0))); + for (QAction *action : view.actions()) { + if (action->shortcuts().contains(QKeySequence(QKeySequence::Undo))) + CHECK(action->isEnabled()); + } + + view.setScene(nullptr); + CHECK(countActionsWithShortcut(view, QKeySequence::Undo) == 0); + CHECK(countActionsWithShortcut(view, QKeySequence::Redo) == 0); +}