diff --git a/.gitignore b/.gitignore index 552a9b2f0..81a3fe4ef 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,7 @@ build*/ qt-build tags + +# OpenSpec working directory (local planning) +openspec/ +.claude/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..8099efce4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,96 @@ +# AGENTS.md + +This file provides guidance to coding agents when working with code in this repository. + +## Writing style + +Write short, simple technical English. One idea per sentence. No filler or marketing words. +This applies to answers, code comments, commit messages and docs. + +## Project overview + +QtNodes is a Qt-based C++ library for building node graph editors. It separates graph data +(`AbstractGraphModel`) from visualization (`BasicGraphicsScene`/`GraphicsView`). It supports +generic graph editing and a data-flow paradigm with automatic propagation. It works with Qt5 +(5.15+) and Qt6 (6.3+). + +## Build and test + +```bash +cmake -S . -Bbuild -DCMAKE_BUILD_TYPE=Release -DUSE_QT6=ON # Qt6 (default); -DUSE_QT6=OFF for Qt5 +cmake --build build +cmake --build build --target test_nodes # tests only +./build/bin/test_nodes # all tests +./build/bin/test_nodes "[core]" # by Catch2 tag, e.g. [core] [graphics] +cd build && ctest --output-on-failure # via ctest (Linux headless: xvfb-run -a ctest ...) +``` + +CMake options: `BUILD_TESTING`, `BUILD_EXAMPLES`, `BUILD_DOCS`, `BUILD_SHARED_LIBS`, `USE_QT6`. + +Tests use Catch2 v3 (downloaded if not found) in one executable, `test_nodes`. Helpers are in +`test/include/`: `TestGraphModel`, `UITestHelper`, `TestDataFlowNodes`, `ApplicationSetup`. + +CI (`.github/workflows/cmake_build.yml`): Linux/gcc/Qt5, macOS/clang/Qt6, Windows/MSVC/Qt5 and +Qt6. Apple Clang builds with `-Werror`. + +## Architecture + +Model-View. The model is the single source of truth. The scene and view only observe model +signals. + +- **Model state changes go through the model.** Change the graph with model calls or undo + commands (`UndoCommands.hpp`). The graphics layer follows the model signals. +- `AbstractGraphModel`: pure virtual graph. Node and connection CRUD, data queries by + `NodeRole`/`PortRole`. It can run headless, without a scene. +- `DataFlowGraphModel`: concrete model for the data-flow paradigm. It owns one + `NodeDelegateModel` per node and propagates data through connections. Loops are disabled. +- `NodeDelegateModel`: node logic for `DataFlowGraphModel`. It defines ports, data types and + embedded widgets, receives data in `setInData()` and signals `dataUpdated(PortIndex)`. + Subclasses are registered in `NodeDelegateModelRegistry`. +- Graphics: `BasicGraphicsScene` (owns the `QUndoStack`), `DataFlowGraphicsScene` (JSON + save/load, context menu), `GraphicsView` (zoom, pan, copy/paste, shortcuts). +- Customization by inheritance: `AbstractNodeGeometry`, `AbstractNodePainter`, + `AbstractConnectionPainter`. +- Styling: JSON styles via `NodeStyle`, `ConnectionStyle`, `GraphicsViewStyle`, managed by the + `StyleCollection` singleton. +- Serialization: the `Serializable` interface, `save()`/`load()` with `QJsonObject`. + +Core types: `NodeId` and `PortIndex` are `unsigned int` (`InvalidNodeId` is the maximum +value). `PortType` is `In`, `Out` or `None`. `ConnectionId` is +`{outNodeId, outPortIndex, inNodeId, inPortIndex}`. + +Directories: `include/QtNodes/internal/` (public headers), `src/`, `test/src/` and +`test/include/`, `examples/`. + +## Code style + +Enforced by `.clang-format`. + +- 4 spaces, no tabs, 100 columns. +- Brace on a new line after class, struct and function. Same line after control statements. +- Pointer alignment right (`int *p`). No namespace indentation. +- `#pragma once` in all headers. Everything is in `namespace QtNodes`. +- Members are prefixed with `_` (`_value`). +- `QT_NO_KEYWORDS` is defined. Use `Q_EMIT`, `Q_SIGNALS`, `Q_SLOTS`, `Q_FOREACH`. + +## C++ standard + +The sources use C++17, and Qt 6 requires it. The standard is declared only in the +`QT_NODES_DEVELOPER_DEFAULTS` block of `CMakeLists.txt`. Do not set it for consumers. Projects +that include QtNodes choose their own standard. + +## Tests and docs + +- Test titles state the rule they prove in words. +- A bug fix comes with a regression test that fails without the fix. +- Update `docs/` and `README.rst` when a change alters what they describe. +- Do not silently change recorded behavior or settle an open design decision. Ask. + +## Commits and releases + +- One logical change per commit. +- No `Co-Authored-By` lines or other attribution trailers in commit messages. +- Do not push, tag or delete remote branches unless asked. +- Versions follow semver. A tag on a later commit must have a higher version than the tags + before it. Never move or delete a published tag. +- Branches: `master` (latest dev state) and `v3`. Older versions are tags (`1.0`, `2.*`). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..43c994c2d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/CMakeLists.txt b/CMakeLists.txt index e63c2e645..1b14307f0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -188,7 +188,7 @@ if(NOT "${CMAKE_CXX_SIMULATE_ID}" STREQUAL "MSVC") endif() if(QT_NODES_DEVELOPER_DEFAULTS) - target_compile_features(QtNodes PUBLIC cxx_std_14) + target_compile_features(QtNodes PUBLIC cxx_std_17) set_target_properties(QtNodes PROPERTIES CXX_EXTENSIONS OFF) endif() diff --git a/README.rst b/README.rst index 3a3dbbd9d..2d573fb9c 100644 --- a/README.rst +++ b/README.rst @@ -34,8 +34,9 @@ Warning Branches -------- -There are branches ``v2`` and ``v3`` for versions ``2.x.x`` and ``3.x`` -respectively. The branch ``master`` contains the latest dev state. +There is a branch ``v3`` for version ``3.x``. The branch ``master`` contains the latest +dev state. Older versions are available as tags: ``1.0`` and ``2.*`` (the last ``2.x.x`` +release is ``2.2.4``). .. contents:: Navigation @@ -104,6 +105,13 @@ Current State (v3) Building ======== +C++ standard +------------ + +The sources use C++17 and Qt 6 requires it, so build with C++17 or newer. QtNodes does not +impose a standard on projects that include it. Your project sets it, for example with +``set(CMAKE_CXX_STANDARD 17)``, so that all of its targets stay consistent. + Set this option to false if you want to build with Qt5 version instead of Qt6: :: diff --git a/docs/faq.rst b/docs/faq.rst index d1f92a6a2..01c37570f 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -174,7 +174,8 @@ For ports on all sides, create a custom ``AbstractNodeGeometry``. **Can I group nodes?** -Node grouping is planned but not yet implemented. Track progress on GitHub. +Yes, since 3.1.4. Call ``BasicGraphicsScene::setGroupingEnabled(true)``. Groups have known +limits in 3.x. They are explained in :doc:`migration/v3-to-v4`, together with the plan for v4. **Can I have curved connections?** diff --git a/docs/guide/advanced.rst b/docs/guide/advanced.rst index 601e4ef0c..82ba18822 100644 --- a/docs/guide/advanced.rst +++ b/docs/guide/advanced.rst @@ -275,13 +275,13 @@ Build graphs in code (useful for testing or loading custom formats): } } -Node Groups (Future) --------------------- +Node Groups +----------- .. note:: - Node grouping is planned but not yet implemented. See the - `GitHub issues `_ for status. + Call ``BasicGraphicsScene::setGroupingEnabled(true)`` to enable groups. Groups have known + limits in 3.x, for example group changes cannot be undone. See :doc:`../migration/v3-to-v4`. .. seealso:: diff --git a/docs/index.rst b/docs/index.rst index 3b5c068f0..c9722873e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -93,6 +93,7 @@ Other Resources :maxdepth: 1 migration/v2-to-v3 + migration/v3-to-v4 faq testing license_link diff --git a/docs/migration/v3-to-v4.rst b/docs/migration/v3-to-v4.rst new file mode 100644 index 000000000..8cb16bf91 --- /dev/null +++ b/docs/migration/v3-to-v4.rst @@ -0,0 +1,94 @@ +Planned changes for v4: node groups +=================================== + +Node groups were added in 3.1.4. They work, but their design has limits. +Version 4 will rebuild groups so that the model owns the group data, like +it does for nodes and connections. This page lists the known problems of +groups in 3.x and says why they are not fixed there. + +.. note:: + + The v4 design is not final. Progress is tracked in + `issue #539 `_. + +What is wrong with groups in 3.x +-------------------------------- + +The scene owns the groups. The model does not know about them. A group is a +``NodeGroup`` that holds raw pointers to node graphics items, and the scene +changes node positions and group state directly. This is against the rule of +the library: the model is the source of truth, and the scene follows it. + +The model has no group data, so: + +- A group is not saved by ``DataFlowGraphModel::save()``. It is saved by the + scene. +- Creating a group, adding a node to it and removing a node from it cannot be + undone. +- Undo of a node deletion brings the node back outside its group. A group + that was deleted and restored loses its name and its id. +- Copy and paste of a group loses its name and lock state. + +The graphics items point to each other, so: + +- A node that is dragged over a group keeps a raw pointer to it. If the group + is deleted during the drag, the pointer dangles. +- The drag-into-group state is reset only while the node still touches the + group. If you move a node away from a group in one big step and release it, + the node joins the group. +- The group item changes its own geometry inside ``paint()``. That schedules + the next paint, so a view with a group repaints all the time, also when + idle. This costs CPU. + +Other problems: + +- ``BasicGraphicsScene::loadItems()`` with a paste position moves plain nodes + in the graphics only, and the model keeps the old position. The offset of a + group is wrong, because the group item is always at (0,0). The built-in + paste does not use this path, so only code that calls ``loadItems()`` itself + is affected. +- Two separate drags of the same node are merged into one undo step. This is + the behavior of the upstream code. A fix needs a decision on what one undo + step is. + +Why these are not fixed in 3.x +------------------------------ + +Each of these problems comes from the same cause: the group state is in the +scene. A correct fix moves it to the model. That changes the public API +(``NodeGroup``, ``childNodes()`` and the group functions of the scene), so it +needs a new major version. + +A local fix in 3.x would rewrite code that v4 removes. It would also add more +code to a design we want to leave. So 3.x gets only the fixes that matter to +users today: + +- Node moves go through the model again (#516). +- A locked node, or a node of a locked group, can no longer start connections + (#536). +- Crashes in the group lifetime are fixed (#540): a model reset with a group, + the double delete of the group item, and a node in more than one group. +- ``GroupGraphicsObject`` is exported. On a Windows shared build, code that + called its methods did not link. + +Use of groups in 3.x +-------------------- + +Groups are usable. Until v4: + +- Do not rely on undo for group changes. +- Do not call ``BasicGraphicsScene::loadItems()`` with a paste position. +- Keep the group lock on, if you do not want the drag-into-group behavior. + +What changes in v4 +------------------ + +- The model holds the group data: a ``GroupId`` per node, and name and lock + per group. A small helper class, which a model keeps as a member, does the + bookkeeping, so each model does not need its own. +- ``NodeGroup`` and the pointers between graphics items are removed. + ``GroupGraphicsObject`` becomes a view that draws a rectangle around the + nodes of the group. +- Group changes are undo commands. +- Groups do not nest and cannot be folded. +- Saved scenes keep the ``"groups"`` array, so files of 3.x load in v4. diff --git a/include/QtNodes/internal/BasicGraphicsScene.hpp b/include/QtNodes/internal/BasicGraphicsScene.hpp index 47ac5d60b..1e2bc2a4b 100644 --- a/include/QtNodes/internal/BasicGraphicsScene.hpp +++ b/include/QtNodes/internal/BasicGraphicsScene.hpp @@ -353,6 +353,7 @@ public Q_SLOTS: std::unique_ptr _nodePainter; std::unique_ptr _connectionPainter; bool _nodeDrag; + friend class NodeGraphicsObject; QUndoStack *_undoStack; Qt::Orientation _orientation; bool _groupingEnabled; diff --git a/include/QtNodes/internal/GroupGraphicsObject.hpp b/include/QtNodes/internal/GroupGraphicsObject.hpp index 1b635fbd4..9a2e918fb 100644 --- a/include/QtNodes/internal/GroupGraphicsObject.hpp +++ b/include/QtNodes/internal/GroupGraphicsObject.hpp @@ -2,6 +2,7 @@ #include "BasicGraphicsScene.hpp" #include "Definitions.hpp" +#include "Export.hpp" #include "NodeGroup.hpp" #include #include @@ -45,7 +46,7 @@ class NodeGraphicsObject; * @brief The GroupGraphicsObject class handles the graphical part of a node group. * Each node group is associated with a unique GroupGraphicsObject. */ -class GroupGraphicsObject +class NODE_EDITOR_PUBLIC GroupGraphicsObject : public QObject , public QGraphicsRectItem { diff --git a/include/QtNodes/internal/UndoCommands.hpp b/include/QtNodes/internal/UndoCommands.hpp index 870478618..913e0d100 100644 --- a/include/QtNodes/internal/UndoCommands.hpp +++ b/include/QtNodes/internal/UndoCommands.hpp @@ -99,8 +99,14 @@ class NODE_EDITOR_PUBLIC ConnectCommand : public QUndoCommand class NODE_EDITOR_PUBLIC MoveNodeCommand : public QUndoCommand { public: + /// Moves the currently selected nodes. MoveNodeCommand(BasicGraphicsScene *scene, QPointF const &diff); + /// Moves the given nodes, regardless of the selection. + MoveNodeCommand(BasicGraphicsScene *scene, + std::unordered_set const &nodeIds, + QPointF const &diff); + void undo() override; void redo() override; @@ -117,7 +123,7 @@ class NODE_EDITOR_PUBLIC MoveNodeCommand : public QUndoCommand private: BasicGraphicsScene *_scene; - std::unordered_set _selectedNodes; + std::unordered_set _nodeIds; QPointF _diff; }; diff --git a/src/BasicGraphicsScene.cpp b/src/BasicGraphicsScene.cpp index 4b2998637..e5460016b 100644 --- a/src/BasicGraphicsScene.cpp +++ b/src/BasicGraphicsScene.cpp @@ -130,7 +130,15 @@ BasicGraphicsScene::BasicGraphicsScene(AbstractGraphModel &graphModel, QObject * traverseGraphAndPopulateGraphicsObjects(); } -BasicGraphicsScene::~BasicGraphicsScene() = default; +BasicGraphicsScene::~BasicGraphicsScene() +{ + // A group that is still referenced elsewhere must not delete its item after the scene + // is gone. Delete the items now, while the scene is alive. + for (auto &entry : _groups) { + if (entry.second) + entry.second->setGraphicsObject(nullptr); + } +} AbstractGraphModel const &BasicGraphicsScene::graphModel() const { @@ -419,6 +427,9 @@ void BasicGraphicsScene::onNodeClicked(NodeId const nodeId) void BasicGraphicsScene::onModelReset() { + // The groups own graphics items that clear() would delete a second time. + _groups.clear(); + _connectionGraphicsObjects.clear(); _nodeGraphicsObjects.clear(); @@ -485,7 +496,7 @@ std::weak_ptr BasicGraphicsScene::createGroup(std::vector(nodes, groupId, groupName, this); + auto group = std::make_shared(nodes, groupId, groupName); auto ggo = std::make_unique(*this, *group); group->setGraphicsObject(std::move(ggo)); @@ -554,6 +565,14 @@ void BasicGraphicsScene::addNodeToGroup(NodeId nodeId, GroupId groupId) auto group = groupIt->second; auto node = nodeIt->second.get(); + + if (auto currentGroup = node->nodeGroup().lock()) { + if (currentGroup == group) + return; + + removeNodeFromGroup(nodeId); + } + group->addNode(node); node->setNodeGroup(group); } diff --git a/src/GroupGraphicsObject.cpp b/src/GroupGraphicsObject.cpp index f9c995fb4..4c6262092 100644 --- a/src/GroupGraphicsObject.cpp +++ b/src/GroupGraphicsObject.cpp @@ -2,6 +2,7 @@ #include "BasicGraphicsScene.hpp" #include "NodeConnectionInteraction.hpp" #include "NodeGraphicsObject.hpp" +#include "UndoCommands.hpp" #include #include #include @@ -107,10 +108,11 @@ void GroupGraphicsObject::moveConnections() void GroupGraphicsObject::moveNodes(const QPointF &offset) { + // Writes to the model. No undo command is pushed. + auto &model = _scene.graphModel(); for (auto &node : group().childNodes()) { - auto newPosition = QPointF(node->x() + offset.x(), node->y() + offset.y()); - node->setPos(newPosition); - node->update(); + auto const pos = model.nodeData(node->nodeId(), NodeRole::Position); + model.setNodeData(node->nodeId(), NodeRole::Position, pos + offset); } } @@ -190,10 +192,21 @@ void GroupGraphicsObject::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) void GroupGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - QGraphicsItem::mouseMoveEvent(event); if (event->lastPos() != event->pos()) { auto diff = event->pos() - event->lastPos(); - moveNodes(diff); + + // Children of the group plus any other selected nodes move together. + std::unordered_set nodeIds; + for (auto &node : group().childNodes()) { + nodeIds.insert(node->nodeId()); + } + for (QGraphicsItem *item : _scene.selectedItems()) { + if (auto node = qgraphicsitem_cast(item)) { + nodeIds.insert(node->nodeId()); + } + } + + _scene.undoStack().push(new MoveNodeCommand(&_scene, nodeIds, diff)); moveConnections(); } } diff --git a/src/NodeGraphicsObject.cpp b/src/NodeGraphicsObject.cpp index c13b92086..702b01c4f 100644 --- a/src/NodeGraphicsObject.cpp +++ b/src/NodeGraphicsObject.cpp @@ -123,13 +123,14 @@ void NodeGraphicsObject::embedQWidget() void NodeGraphicsObject::setLockedState() { - NodeFlags flags = _graphModel.nodeFlags(_nodeId); - - bool const locked = flags.testFlag(NodeFlag::Locked); - - setFlag(QGraphicsItem::ItemIsMovable, !locked); - setFlag(QGraphicsItem::ItemIsSelectable, !locked); - setFlag(QGraphicsItem::ItemSendsScenePositionChanges, !locked); + bool const modelLocked = _graphModel.nodeFlags(_nodeId).testFlag(NodeFlag::Locked); + + // The model lock and the group lock both write these flags. Set them in one place, + // 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); } QRectF NodeGraphicsObject::boundingRect() const @@ -196,6 +197,13 @@ QVariant NodeGraphicsObject::itemChange(GraphicsItemChange change, const QVarian void NodeGraphicsObject::mousePressEvent(QGraphicsSceneMouseEvent *event) { + // Position updates from setup or undo must not count as a drag. + nodeScene()->_nodeDrag = false; + + if (_graphModel.nodeFlags(_nodeId) & NodeFlag::Locked) { + return; + } + if (_locked) { nodeScene()->clearSelection(); return; @@ -301,16 +309,15 @@ void NodeGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event) event->accept(); } } else { - QGraphicsObject::mouseMoveEvent(event); - if (event->lastPos() != event->pos()) { auto diff = event->pos() - event->lastPos(); + + // The model moves the nodes, the scene follows its signals. + nodeScene()->undoStack().push(new MoveNodeCommand(nodeScene(), diff)); + if (nodeScene()->groupingEnabled()) { if (auto nodeGroup = _nodeGroup.lock(); nodeGroup) { nodeGroup->groupGraphicsObject().moveConnections(); - if (nodeGroup->groupGraphicsObject().locked()) { - nodeGroup->groupGraphicsObject().moveNodes(diff); - } } else { moveConnections(); // if it intersects with a group, expand group @@ -449,8 +456,7 @@ void NodeGraphicsObject::lock(bool locked) { _locked = locked; - setFlag(QGraphicsItem::ItemIsFocusable, !locked); - setFlag(QGraphicsItem::ItemIsSelectable, !locked); + setLockedState(); } QJsonObject NodeGraphicsObject::save() const diff --git a/src/NodeGroup.cpp b/src/NodeGroup.cpp index 171aa9d0d..8406b2c8a 100644 --- a/src/NodeGroup.cpp +++ b/src/NodeGroup.cpp @@ -100,7 +100,8 @@ QString const &NodeGroup::name() const void NodeGroup::setGraphicsObject(std::unique_ptr &&graphics_object) { _groupGraphicsObject = std::move(graphics_object); - _groupGraphicsObject->lock(true); + if (_groupGraphicsObject) + _groupGraphicsObject->lock(true); } bool NodeGroup::empty() const diff --git a/src/UndoCommands.cpp b/src/UndoCommands.cpp index a4c24f9a7..00f52c6ae 100644 --- a/src/UndoCommands.cpp +++ b/src/UndoCommands.cpp @@ -550,17 +550,28 @@ MoveNodeCommand::MoveNodeCommand(BasicGraphicsScene *scene, QPointF const &diff) : _scene(scene) , _diff(diff) { - _selectedNodes.clear(); for (QGraphicsItem *item : _scene->selectedItems()) { if (auto n = qgraphicsitem_cast(item)) { - _selectedNodes.insert(n->nodeId()); + _nodeIds.insert(n->nodeId()); } } } +MoveNodeCommand::MoveNodeCommand(BasicGraphicsScene *scene, + std::unordered_set const &nodeIds, + QPointF const &diff) + : _scene(scene) + , _nodeIds(nodeIds) + , _diff(diff) +{} + void MoveNodeCommand::undo() { - for (auto nodeId : _selectedNodes) { + for (auto nodeId : _nodeIds) { + // The node may have been deleted outside the undo stack. + if (!_scene->graphModel().nodeExists(nodeId)) + continue; + auto oldPos = _scene->graphModel().nodeData(nodeId, NodeRole::Position).value(); oldPos -= _diff; @@ -571,7 +582,11 @@ void MoveNodeCommand::undo() void MoveNodeCommand::redo() { - for (auto nodeId : _selectedNodes) { + for (auto nodeId : _nodeIds) { + // The node may have been deleted outside the undo stack. + if (!_scene->graphModel().nodeExists(nodeId)) + continue; + auto oldPos = _scene->graphModel().nodeData(nodeId, NodeRole::Position).value(); oldPos += _diff; @@ -589,7 +604,7 @@ bool MoveNodeCommand::mergeWith(QUndoCommand const *c) { auto mc = static_cast(c); - if (_selectedNodes == mc->_selectedNodes) { + if (_nodeIds == mc->_nodeIds) { _diff += mc->_diff; return true; } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index e8f5bdc1f..d6ec99d05 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -17,6 +17,7 @@ add_executable(test_nodes src/TestNodeGroup.cpp src/TestNodeNickname.cpp src/TestUIInteraction.cpp + src/TestNodeDrag.cpp src/TestDataFlow.cpp src/TestNodeValidation.cpp src/TestCustomPainters.cpp diff --git a/test/src/TestNodeDrag.cpp b/test/src/TestNodeDrag.cpp new file mode 100644 index 000000000..a9f3227fc --- /dev/null +++ b/test/src/TestNodeDrag.cpp @@ -0,0 +1,110 @@ +#include "ApplicationSetup.hpp" +#include "TestGraphModel.hpp" +#include "UITestHelper.hpp" + +#include +#include +#include +#include + +#include +#include +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::GraphicsView; +using QtNodes::NodeGraphicsObject; +using QtNodes::NodeId; +using QtNodes::NodeRole; + +TEST_CASE("Interactive node drag syncs the model", "[ui][visual][drag]") +{ + auto app = applicationSetup(); + + auto model = std::make_shared(); + BasicGraphicsScene scene(*model); + GraphicsView view(&scene); + view.resize(800, 600); + view.show(); + REQUIRE(QTest::qWaitForWindowExposed(&view)); + + NodeId const nodeId = model->addNode("TestNode"); + model->setNodeData(nodeId, NodeRole::Position, QPointF(0, 0)); + UITestHelper::waitForUI(); + + auto *item = scene.nodeGraphicsObject(nodeId); + REQUIRE(item != nullptr); + + // No style is loaded in tests, so the default opacity is 0 and Qt would + // skip the node when hit-testing the simulated mouse events. + item->setOpacity(1.0); + + QPointF const start = item->mapToScene(item->boundingRect().center()); + QPointF const delta(60, 40); + + SECTION("Dragging writes the new position to the model and emits nodeMoved") + { + QSignalSpy movedSpy(&scene, &BasicGraphicsScene::nodeMoved); + + UITestHelper::simulateMouseDrag(&view, start, start + delta); + + CHECK(item->pos() == QPointF(0, 0) + delta); + CHECK(model->nodeData(nodeId, NodeRole::Position).value() == item->pos()); + REQUIRE(movedSpy.count() == 1); + CHECK(movedSpy.at(0).at(1).toPointF() == item->pos()); + } + + SECTION("A drag is a single undo step") + { + UITestHelper::simulateMouseDrag(&view, start, start + delta); + REQUIRE(scene.undoStack().count() == 1); + + scene.undoStack().undo(); + CHECK(model->nodeData(nodeId, NodeRole::Position).value() == QPointF(0, 0)); + CHECK(item->pos() == QPointF(0, 0)); + + scene.undoStack().redo(); + CHECK(model->nodeData(nodeId, NodeRole::Position).value() == delta); + CHECK(item->pos() == delta); + } + + SECTION("A click without movement leaves model and undo stack untouched") + { + UITestHelper::simulateMousePress(&view, start); + UITestHelper::simulateMouseRelease(&view, start); + + CHECK(scene.undoStack().count() == 0); + CHECK(model->nodeData(nodeId, NodeRole::Position).value() == QPointF(0, 0)); + } + + SECTION("A click after a position was set from code does not emit nodeMoved") + { + QSignalSpy movedSpy(&scene, &BasicGraphicsScene::nodeMoved); + + model->setNodeData(nodeId, NodeRole::Position, QPointF(0, 0)); + UITestHelper::simulateMousePress(&view, start); + UITestHelper::simulateMouseRelease(&view, start); + + CHECK(movedSpy.count() == 0); + } + + SECTION("All selected nodes are written back") + { + NodeId const other = model->addNode("TestNode"); + model->setNodeData(other, NodeRole::Position, QPointF(300, 0)); + UITestHelper::waitForUI(); + + auto *otherItem = scene.nodeGraphicsObject(other); + REQUIRE(otherItem != nullptr); + otherItem->setOpacity(1.0); + item->setSelected(true); + otherItem->setSelected(true); + + UITestHelper::simulateMouseDrag(&view, start, start + delta); + + CHECK(model->nodeData(nodeId, NodeRole::Position).value() == item->pos()); + CHECK(model->nodeData(other, NodeRole::Position).value() == otherItem->pos()); + CHECK(otherItem->pos() == QPointF(300, 0) + delta); + CHECK(scene.undoStack().count() == 1); + } +} diff --git a/test/src/TestNodeGroup.cpp b/test/src/TestNodeGroup.cpp index 6599656eb..09ae6bc7d 100644 --- a/test/src/TestNodeGroup.cpp +++ b/test/src/TestNodeGroup.cpp @@ -5,7 +5,10 @@ #include #include #include +#include +#include #include +#include #include #include @@ -14,7 +17,10 @@ #include #include #include +#include #include +#include +#include #include #include @@ -370,3 +376,348 @@ TEST_CASE("Saving and restoring node groups", "[node-group]") CHECK(restoredSet.count(connectionIt->inNodeId) == 1); } } + +TEST_CASE("Dragging a group moves its nodes through the model", "[node-group][drag]") +{ + auto app = applicationSetup(); + + auto registry = createDummyRegistry(); + DataFlowGraphModel model(registry); + BasicGraphicsScene scene(model); + scene.setGroupingEnabled(true); + + NodeId const inGroup1 = createNode(model, scene); + NodeId const inGroup2 = createNode(model, scene); + NodeId const outside = createNode(model, scene); + model.setNodeData(inGroup1, NodeRole::Position, QPointF(0, 0)); + model.setNodeData(inGroup2, NodeRole::Position, QPointF(200, 0)); + model.setNodeData(outside, NodeRole::Position, QPointF(0, 300)); + + std::vector nodes{scene.nodeGraphicsObject(inGroup1), + scene.nodeGraphicsObject(inGroup2)}; + auto group = scene.createGroup(nodes, QStringLiteral("Dragged")).lock(); + REQUIRE(group); + + QPointF const diff(10, 5); + QGraphicsSceneMouseEvent move(QEvent::GraphicsSceneMouseMove); + move.setPos(diff); + move.setLastPos(QPointF(0, 0)); + scene.sendEvent(&group->groupGraphicsObject(), &move); + + auto position = [&](NodeId id) { return model.nodeData(id, NodeRole::Position).value(); }; + + SECTION("Group nodes reach the model, other nodes stay") + { + CHECK(position(inGroup1) == QPointF(0, 0) + diff); + CHECK(position(inGroup2) == QPointF(200, 0) + diff); + CHECK(position(outside) == QPointF(0, 300)); + CHECK(scene.nodeGraphicsObject(inGroup1)->pos() == position(inGroup1)); + } + + SECTION("The move is undoable") + { + REQUIRE(scene.undoStack().count() == 1); + scene.undoStack().undo(); + CHECK(position(inGroup1) == QPointF(0, 0)); + CHECK(position(inGroup2) == QPointF(200, 0)); + } + + SECTION("A selected node outside the group moves together with it") + { + scene.nodeGraphicsObject(outside)->setSelected(true); + scene.sendEvent(&group->groupGraphicsObject(), &move); + + CHECK(position(outside) == QPointF(0, 300) + diff); + CHECK(position(inGroup1) == QPointF(0, 0) + diff * 2); + } +} + +TEST_CASE("A mouse move on a node of a locked group moves nothing", "[node-group][drag]") +{ + auto app = applicationSetup(); + + auto registry = createDummyRegistry(); + DataFlowGraphModel model(registry); + BasicGraphicsScene scene(model); + scene.setGroupingEnabled(true); + + NodeId const a = createNode(model, scene); + NodeId const b = createNode(model, scene); + model.setNodeData(a, NodeRole::Position, QPointF(0, 0)); + model.setNodeData(b, NodeRole::Position, QPointF(200, 0)); + + std::vector nodes{scene.nodeGraphicsObject(a), + scene.nodeGraphicsObject(b)}; + auto group = scene.createGroup(nodes, QStringLiteral("Locked")).lock(); + REQUIRE(group); + group->groupGraphicsObject().lock(true); + + QGraphicsSceneMouseEvent move(QEvent::GraphicsSceneMouseMove); + move.setPos(QPointF(10, 5)); + move.setLastPos(QPointF(0, 0)); + scene.sendEvent(scene.nodeGraphicsObject(a), &move); + + CHECK(model.nodeData(a, NodeRole::Position).value() == QPointF(0, 0)); + CHECK(model.nodeData(b, NodeRole::Position).value() == QPointF(200, 0)); +} + +namespace { +// DataFlowGraphModel has no way to set NodeFlag::Locked, so a test model adds it. +class LockableModel : public DataFlowGraphModel +{ +public: + using DataFlowGraphModel::DataFlowGraphModel; + + QtNodes::NodeFlags nodeFlags(NodeId nodeId) const override + { + auto flags = DataFlowGraphModel::nodeFlags(nodeId); + if (_locked.count(nodeId) != 0) + flags |= QtNodes::NodeFlag::Locked; + return flags; + } + + void setLocked(NodeId nodeId, bool locked) + { + if (locked) + _locked.insert(nodeId); + else + _locked.erase(nodeId); + Q_EMIT nodeFlagsUpdated(nodeId); + } + +private: + std::set _locked; +}; + +void pressPort(BasicGraphicsScene &scene, NodeId nodeId, PortType type) +{ + auto *item = scene.nodeGraphicsObject(nodeId); + QPointF const portPos = scene.nodeGeometry().portPosition(nodeId, type, 0); + + QGraphicsSceneMouseEvent press(QEvent::GraphicsSceneMousePress); + press.setButton(Qt::LeftButton); + press.setPos(portPos); + press.setScenePos(item->mapToScene(portPos)); + scene.sendEvent(item, &press); +} + +int countConnectionItems(BasicGraphicsScene &scene) +{ + int count = 0; + for (QGraphicsItem *item : scene.items()) { + if (dynamic_cast(item)) + ++count; + } + return count; +} +} // namespace + +TEST_CASE("A model-locked node does not start a draft connection", "[node-lock]") +{ + auto app = applicationSetup(); + + auto registry = createDummyRegistry(); + LockableModel model(registry); + BasicGraphicsScene scene(model); + + NodeId const a = createNode(model, scene); + model.setLocked(a, true); + + pressPort(scene, a, PortType::Out); + + CHECK(countConnectionItems(scene) == 0); +} + +TEST_CASE("A model-locked node does not detach a connection", "[node-lock]") +{ + auto app = applicationSetup(); + + auto registry = createDummyRegistry(); + LockableModel model(registry); + BasicGraphicsScene scene(model); + + NodeId const a = createNode(model, scene); + NodeId const b = createNode(model, scene); + ConnectionId const connection{a, 0, b, 0}; + model.addConnection(connection); + QCoreApplication::processEvents(); + REQUIRE(model.connectionExists(connection)); + + model.setLocked(b, true); + pressPort(scene, b, PortType::In); + + CHECK(model.connectionExists(connection)); +} + +TEST_CASE("A node stays unselectable while its model lock or its group lock is set", "[node-lock]") +{ + auto app = applicationSetup(); + + auto registry = createDummyRegistry(); + LockableModel model(registry); + BasicGraphicsScene scene(model); + scene.setGroupingEnabled(true); + + NodeId const a = createNode(model, scene); + NodeId const b = createNode(model, scene); + auto *item = scene.nodeGraphicsObject(a); + auto selectable = [&] { return bool(item->flags() & QGraphicsItem::ItemIsSelectable); }; + + REQUIRE(selectable()); + + std::vector nodes{item, scene.nodeGraphicsObject(b)}; + auto group = scene.createGroup(nodes, QStringLiteral("Locked")).lock(); + REQUIRE(group); + group->groupGraphicsObject().lock(true); + REQUIRE_FALSE(selectable()); + + SECTION("Unlocking the model flag keeps the group lock") + { + model.setLocked(a, true); + model.setLocked(a, false); + CHECK_FALSE(selectable()); + } + + SECTION("Unlocking the group keeps the model lock") + { + model.setLocked(a, true); + group->groupGraphicsObject().lock(false); + CHECK_FALSE(selectable()); + } + + SECTION("Removing the node from its group keeps the model lock") + { + model.setLocked(a, true); + scene.removeNodeFromGroup(a); + CHECK_FALSE(selectable()); + } + + SECTION("With both locks gone the node is selectable") + { + group->groupGraphicsObject().lock(false); + CHECK(selectable()); + } +} + +TEST_CASE("A model reset with a group does not leave dangling group items", "[node-group][lifetime]") +{ + auto app = applicationSetup(); + + auto registry = createDummyRegistry(); + DataFlowGraphModel model(registry); + auto scene = std::make_unique(model); + scene->setGroupingEnabled(true); + + NodeId const a = createNode(model, *scene); + NodeId const b = createNode(model, *scene); + std::vector nodes{scene->nodeGraphicsObject(a), + scene->nodeGraphicsObject(b)}; + REQUIRE(scene->createGroup(nodes, QStringLiteral("Reset")).lock()); + + // Changing the orientation resets the model view of the scene. + scene->setOrientation(Qt::Vertical); + + CHECK(scene->groups().empty()); + + // Destroying the scene used to delete the group item a second time. + scene.reset(); +} + +TEST_CASE("A node is in at most one group", "[node-group][lifetime]") +{ + auto app = applicationSetup(); + + auto registry = createDummyRegistry(); + DataFlowGraphModel model(registry); + BasicGraphicsScene scene(model); + scene.setGroupingEnabled(true); + + NodeId const a = createNode(model, scene); + NodeId const b = createNode(model, scene); + NodeId const c = createNode(model, scene); + NodeId const d = createNode(model, scene); + + std::vector first{scene.nodeGraphicsObject(a), + scene.nodeGraphicsObject(b)}; + std::vector second{scene.nodeGraphicsObject(c), + scene.nodeGraphicsObject(d)}; + auto group1 = scene.createGroup(first, QStringLiteral("First")).lock(); + auto group2 = scene.createGroup(second, QStringLiteral("Second")).lock(); + REQUIRE(group1); + REQUIRE(group2); + + SECTION("Adding a node to its own group does not duplicate it") + { + scene.addNodeToGroup(a, group1->id()); + + CHECK(toNodeIdSet(group1->nodeIDs()) == std::set{a, b}); + CHECK(group1->childNodes().size() == 2); + } + + SECTION("Adding a node to another group removes it from the old one") + { + scene.addNodeToGroup(a, group2->id()); + + CHECK(toNodeIdSet(group1->nodeIDs()) == std::set{b}); + CHECK(toNodeIdSet(group2->nodeIDs()) == std::set{a, c, d}); + CHECK(scene.nodeGraphicsObject(a)->nodeGroup().lock() == group2); + } + + SECTION("Moving the last node out of a group removes the empty group") + { + scene.addNodeToGroup(a, group2->id()); + scene.addNodeToGroup(b, group2->id()); + + CHECK(scene.groups().count(group1->id()) == 0); + CHECK(toNodeIdSet(group2->nodeIDs()) == std::set{a, b, c, d}); + } +} + +TEST_CASE("A group does not have the scene as QObject parent", "[node-group][lifetime]") +{ + auto app = applicationSetup(); + + auto registry = createDummyRegistry(); + DataFlowGraphModel model(registry); + auto scene = std::make_unique(model); + scene->setGroupingEnabled(true); + + NodeId const a = createNode(model, *scene); + std::vector nodes{scene->nodeGraphicsObject(a)}; + auto group = scene->createGroup(nodes, QStringLiteral("Owned")).lock(); + REQUIRE(group); + + // The scene holds the group in a shared_ptr. A QObject parent would delete it a second time. + CHECK(group->parent() == nullptr); + + // A group kept past the life of the scene is released without a crash. + scene.reset(); + group.reset(); +} + +TEST_CASE("Undo of a move skips nodes that no longer exist", "[node-group][lifetime]") +{ + auto app = applicationSetup(); + + auto registry = createDummyRegistry(); + DataFlowGraphModel model(registry); + BasicGraphicsScene scene(model); + + NodeId const a = createNode(model, scene); + NodeId const b = createNode(model, scene); + model.setNodeData(a, NodeRole::Position, QPointF(0, 0)); + model.setNodeData(b, NodeRole::Position, QPointF(100, 0)); + + scene.undoStack().push(new QtNodes::MoveNodeCommand(&scene, {a, b}, QPointF(10, 0))); + + // Deleted outside the undo stack. + model.deleteNode(b); + + QSignalSpy spy(&model, &DataFlowGraphModel::nodePositionUpdated); + scene.undoStack().undo(); + + REQUIRE(spy.count() == 1); + CHECK(spy.at(0).at(0).value() == a); + CHECK(model.nodeData(a, NodeRole::Position).value() == QPointF(0, 0)); + CHECK_FALSE(model.nodeExists(b)); +}