diff --git a/docs/conf.py b/docs/conf.py index 3116bcbf..12aab223 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -45,7 +45,7 @@ def configureDoxyfile(input_dir, output_dir): # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = [ "breathe", "sphinx_rtd_theme" ] +extensions = [ "breathe", "sphinx_rtd_theme", "sphinxcontrib.mermaid" ] #Breathe configuration diff --git a/docs/guide/advanced.rst b/docs/guide/advanced.rst index aeb5d326..0c75bd17 100644 --- a/docs/guide/advanced.rst +++ b/docs/guide/advanced.rst @@ -122,7 +122,8 @@ Update at runtime: Resizable Nodes --------------- -Allow users to resize nodes (useful for embedded widgets): +Allow users to resize nodes (useful for embedded widgets). A resizable node shows a resize +handle. The handle resizes the embedded widget, and the node follows its widget: .. code-block:: cpp @@ -131,7 +132,14 @@ Allow users to resize nodes (useful for embedded widgets): return NodeFlag::Resizable; } -Handle size changes: +The scene computes the size of a node from its content: the widget, the caption, the label and +the ports. It stores the result with ``setNodeData(nodeId, NodeRole::Size, size)``. Your model +must store this value and return it. It is an output of the layout and not a setting. A value +that you set from code does not resize the node, and the next ``nodeUpdated`` replaces it. To +make a node bigger, resize its embedded widget. If the delegate resizes the widget itself, it +emits ``embeddedWidgetSizeUpdated()`` afterwards. + +Store the size: .. code-block:: cpp @@ -139,12 +147,15 @@ Handle size changes: { if (role == NodeRole::Size) { _nodeSizes[nodeId] = value.toSize(); - emit nodeUpdated(nodeId); return true; } // ... } +Do not emit ``nodeUpdated`` when ``Size`` is set. The scene sets ``Size`` while it handles +``nodeUpdated``, so the signal would start an endless recursion. See +:doc:`change-notifications` for the signals that a model must emit. + Non-Detachable Connections -------------------------- diff --git a/docs/guide/change-notifications.rst b/docs/guide/change-notifications.rst new file mode 100644 index 00000000..ed6b993d --- /dev/null +++ b/docs/guide/change-notifications.rst @@ -0,0 +1,348 @@ +Change Notifications +==================== + +This page explains how a change travels from the graph model to the screen. +It is for users who write a custom model, delegate or geometry, and for contributors. + +The Rule +-------- + +The model is the single source of truth. The scene and the view observe the model signals. + +- Change the graph with model calls or with undo commands. Do not move or resize graphics + items by hand. +- The model emits a signal after each change. +- ``BasicGraphicsScene`` connects to the model signals and updates its graphics objects. +- A graphics object reads its data from the model each time it paints. + +The scene follows these model signals: + +.. list-table:: + :widths: 30 30 40 + :header-rows: 1 + + * - Model signal + - Scene slot + - What the scene does + * - ``nodeCreated`` + - ``onNodeCreated`` + - Creates a ``NodeGraphicsObject``. It embeds the widget and computes the size. + * - ``nodeDeleted`` + - ``onNodeDeleted`` + - Removes the node from its group and deletes the graphics object and its widget. + * - ``nodePositionUpdated`` + - ``onNodePositionUpdated`` + - Moves the item to the model position. The connections follow. + * - ``nodeUpdated`` + - ``onNodeUpdated`` + - Recomputes the size, places the widget, repaints, moves the connections. + * - ``connectionCreated`` + - ``onConnectionCreated`` + - Creates a ``ConnectionGraphicsObject`` and repaints both nodes. + * - ``connectionDeleted`` + - ``onConnectionDeleted`` + - Deletes the connection item and repaints both nodes. + * - ``modelReset`` + - ``onModelReset`` + - Deletes all items, groups and widgets and builds the scene again. + * - ``nodeFlagsUpdated`` + - each ``NodeGraphicsObject`` + - Applies the ``Locked`` flag: the node cannot move or be selected. + +``DataFlowGraphicsScene`` also listens to ``DataFlowGraphModel::inPortDataWasSet`` and +calls ``onNodeUpdated`` for the node that received data. + +Who Notifies Whom +----------------- + +.. mermaid:: + + flowchart LR + User["Mouse and keys"] --> Items["NodeGraphicsObject
GroupGraphicsObject
ConnectionGraphicsObject
GraphicsView"] + Items -- "push command" --> Undo["QUndoStack
(owned by the scene)"] + Undo -- "redo() / undo()" --> Model["AbstractGraphModel
DataFlowGraphModel"] + Code["Your code"] -- "addNode, setNodeData, ..." --> Model + Delegate["NodeDelegateModel"] -- "dataUpdated, requestNodeUpdate,
portsAboutToBe..., ports..." --> Model + Model -- "nodeCreated, nodeUpdated,
nodePositionUpdated, connection...,
modelReset" --> Scene["BasicGraphicsScene"] + Model -- "inPortDataWasSet" --> DFScene["DataFlowGraphicsScene"] + Model -- "nodeFlagsUpdated" --> Items + DFScene --> Scene + Scene -- "create, delete, setPos,
update, moveConnections" --> Items + Scene -- "recomputeSize" --> Geometry["AbstractNodeGeometry"] + Geometry -- "setNodeData(Size)" --> Model + Model -- "setInData" --> Delegate + +.. + Fallback: + + Mouse/keys -> graphics items -> push command -> QUndoStack -> redo()/undo() -> model + Your code -> model calls -> model + NodeDelegateModel -> dataUpdated / requestNodeUpdate / ports signals -> DataFlowGraphModel + model -> nodeCreated, nodeDeleted, nodeUpdated, nodePositionUpdated, + connectionCreated, connectionDeleted, modelReset -> BasicGraphicsScene + DataFlowGraphModel -> inPortDataWasSet -> DataFlowGraphicsScene -> onNodeUpdated + model -> nodeFlagsUpdated -> every NodeGraphicsObject + BasicGraphicsScene -> create, delete, setPos, update, moveConnections -> graphics items + BasicGraphicsScene -> recomputeSize -> AbstractNodeGeometry -> setNodeData(Size) -> model + DataFlowGraphModel -> setInData -> NodeDelegateModel + +Note the arrow from the geometry back to the model. ``recomputeSize()`` writes +``NodeRole::Size`` into the model. The size is computed by the view, but it is stored in +the model. See the pitfalls below. + +Main Cases +---------- + +Node Drag +^^^^^^^^^ + +A drag does not move the item directly. Each mouse move pushes a ``MoveNodeCommand``. The undo +stack runs ``redo()`` at once. ``redo()`` writes the new position into the model. The model +emits ``nodePositionUpdated`` and the scene moves the item. Qt then calls +``itemChange(ItemScenePositionHasChanged)``, and the item moves its connections. All moves of +one drag merge into one undo step. + +.. mermaid:: + + sequenceDiagram + participant N as NodeGraphicsObject + participant U as QUndoStack + participant C as MoveNodeCommand + participant M as Model + participant S as BasicGraphicsScene + participant E as ConnectionGraphicsObject + Note over N: mousePressEvent: beginMove() + N->>U: push(MoveNodeCommand(diff)) + U->>C: redo() + C->>M: setNodeData(id, Position, old + diff) + M-->>S: nodePositionUpdated(id) + S->>N: setPos(model position) + N->>N: itemChange(ItemScenePositionHasChanged) + N->>E: moveConnections(): move() for each connection + S->>N: update() + U->>U: mergeWith() the previous move of this drag + Note over N: mouseReleaseEvent: nodeClicked(id) + N-->>S: nodeClicked(id) + S-->>S: onNodeClicked: emit nodeMoved, modified + +.. + Fallback: + + press: NodeGraphicsObject::mousePressEvent -> MoveNodeCommand::beginMove() + move: NodeGraphicsObject::mouseMoveEvent + -> QUndoStack::push(MoveNodeCommand(diff)) + -> MoveNodeCommand::redo() -> model.setNodeData(id, Position, pos + diff) + -> [signal] nodePositionUpdated(id) + -> BasicGraphicsScene::onNodePositionUpdated + -> NodeGraphicsObject::setPos() + -> [Qt] itemChange(ItemScenePositionHasChanged) + -> moveConnections() -> ConnectionGraphicsObject::move() + -> NodeGraphicsObject::update() + -> QUndoStack merges the command into the step of this drag + release: NodeGraphicsObject::mouseReleaseEvent -> [signal] nodeClicked(id) + -> BasicGraphicsScene::onNodeClicked -> nodeMoved(id, pos), modified() + +Undo and redo of the drag take the same path from ``setNodeData`` on. + +Node Creation +^^^^^^^^^^^^^ + +.. mermaid:: + + sequenceDiagram + participant X as Caller (menu, code, undo) + participant M as DataFlowGraphModel + participant S as BasicGraphicsScene + participant N as NodeGraphicsObject + participant G as AbstractNodeGeometry + X->>M: addNode(type) + M->>M: create delegate, connect its signals + M-->>S: nodeCreated(id) + S->>N: new NodeGraphicsObject(scene, id) + N->>M: nodeData(Widget), embed it in a proxy + N->>G: recomputeSize(id) + G->>M: setNodeData(id, Size, size) + N->>M: nodeData(Position), setPos() + X->>M: setNodeData(id, Position, pos) + M-->>S: nodePositionUpdated(id) + S->>N: setPos(pos) + +.. + Fallback: + + caller -> DataFlowGraphModel::addNode(type) + -> registry creates the delegate, connect its signals + -> [signal] nodeCreated(id) + -> BasicGraphicsScene::onNodeCreated -> new NodeGraphicsObject(scene, id) + -> embedQWidget(): nodeData(Widget), QGraphicsProxyWidget + -> AbstractNodeGeometry::recomputeSize(id) -> model.setNodeData(id, Size, s) + -> setPos(nodeData(Position)) + caller -> model.setNodeData(id, Position, pos) (CreateCommand) + -> [signal] nodePositionUpdated(id) -> onNodePositionUpdated -> setPos() + +The model emits ``nodeCreated`` before the position is set. The item is first built at the +default position and then moved. ``DataFlowGraphModel::loadNode()`` also emits ``nodeCreated`` +before it restores the label and calls the delegate's ``load()``. It then emits ``nodeUpdated`` +once, so that the node gets its final size. + +Connection Creation and Data Propagation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A connection drag ends in ``NodeConnectionInteraction::tryConnect()``. It pushes a +``ConnectCommand``. ``redo()`` calls ``addConnection()``. +``DataFlowGraphModel::addConnection()`` emits ``connectionCreated``, tells both delegates, and +then sends the output data of the source to the target. The target's ``setInData()`` runs. The +model emits ``inPortDataWasSet`` and the data-flow scene calls ``onNodeUpdated`` for the target. + +A delegate that emits ``dataUpdated(port)`` starts the same propagation for all connections of +that port. Each node that receives data gets one +``onNodeUpdated``. A chain of three nodes gives two ``onNodeUpdated`` calls per value change. + +A delegate that emits ``dataInvalidated(port)`` sends empty data (``nullptr``) to the inputs that +are connected to that port. The receiving ``setInData()`` runs with no data. + +Undo and Redo +^^^^^^^^^^^^^ + +Undo commands never touch graphics items for the graph data. They call the model. The scene +follows the signals as for any other change. + +``clearScene()``, ``modelReset`` and ``DataFlowGraphicsScene::load()`` replace the whole graph. +They clear the undo stack, because the commands on it refer to nodes by id. + +.. mermaid:: + + sequenceDiagram + participant V as GraphicsView + participant U as QUndoStack + participant D as DeleteCommand + participant M as Model + participant S as BasicGraphicsScene + V->>U: undo() + U->>D: undo() + loop each saved node + D->>M: loadNode(json) + M-->>S: nodeCreated(id), nodePositionUpdated(id) + D->>S: setZValue(1), setSelected(true) on the new item + end + loop each saved connection + D->>M: addConnection(id) + M-->>S: connectionCreated(id) + end + D->>S: createGroup() for each saved group + +.. + Fallback: + + GraphicsView undo action -> QUndoStack::undo() -> DeleteCommand::undo() + -> insertSerializedItems() + -> for each node: model.loadNode(json) -> [signal] nodeCreated, nodePositionUpdated + then item setZValue(1), setSelected(true) (view state) + -> for each connection: model.addConnection(id) -> [signal] connectionCreated + -> for each group: scene.createGroup() (view state) + +Selection, z-order, groups and group locks are view state. The commands read the selection +from the scene and restore it on undo. + +Embedded Widget Size +^^^^^^^^^^^^^^^^^^^^ + +The node size follows the widget. The geometry adds the widget size to the caption and port +sizes and writes the result into the model. Only some paths run it: + +.. mermaid:: + + sequenceDiagram + participant W as Embedded QWidget + participant D as NodeDelegateModel + participant M as DataFlowGraphModel + participant S as BasicGraphicsScene + participant N as NodeGraphicsObject + participant G as AbstractNodeGeometry + Note over N,W: A. Resize handle (Resizable flag) + N->>W: resize(old + mouse diff) + N->>G: recomputeSize(id) + G->>M: setNodeData(id, Size, size) + N->>N: update(), moveConnections() + Note over W,D: B. The widget changes its own size + W->>W: resize(): nothing else happens + Note over D,S: C. The delegate tells the model + D-->>M: embeddedWidgetSizeUpdated() or requestNodeUpdate() + M-->>S: nodeUpdated(id) + S->>G: recomputeSize(id) + G->>M: setNodeData(id, Size, size) + S->>N: updateQWidgetEmbedPos(), update(), moveConnections() + +.. + Fallback: + + A. resize handle: NodeGraphicsObject::mouseMoveEvent + -> widget->resize(old + diff) -> recomputeSize(id) -> model.setNodeData(id, Size, s) + -> update(), moveConnections() (no undo step, no model signal) + B. widget resizes itself: nothing. The node keeps its old size until C happens. + C. delegate emits embeddedWidgetSizeUpdated() or requestNodeUpdate() + -> DataFlowGraphModel lambda -> [signal] nodeUpdated(id) + -> BasicGraphicsScene::onNodeUpdated + -> prepareGeometryChange, recomputeSize -> setNodeData(Size), + updateQWidgetEmbedPos, update, moveConnections + +What Your Code Must Call +------------------------ + +**A custom** ``AbstractGraphModel``: + +- Emit ``nodeCreated``, ``nodeDeleted``, ``connectionCreated`` and ``connectionDeleted`` after + the change is stored. +- Emit ``nodePositionUpdated`` when ``Position`` changes. +- Emit ``nodeUpdated`` when anything changes that affects the look or the size of a node: + caption, label, style, port count, port captions, validation state, processing status. +- Do **not** emit ``nodeUpdated`` when ``Size`` is set. The scene sets ``Size`` while it + handles ``nodeUpdated``. A signal there starts an endless recursion. +- After ``portsInserted()`` or ``portsDeleted()``, emit ``nodeUpdated`` for the node. These + functions restore the shifted connections, but they do not update the node. +- Emit ``nodeFlagsUpdated`` when ``nodeFlags()`` changes. +- Emit ``modelReset`` only if you must replace everything. The scene deletes all items, + embedded widgets, groups and the selection, clears the undo stack, and builds the scene + again. + +**A** ``NodeDelegateModel`` **in a** ``DataFlowGraphModel``: + +- Emit ``dataUpdated(port)`` when an output changes. +- Emit ``requestNodeUpdate()`` after you change something visible that has no signal of its + own: ``setNodeStyle()``, ``setNodeProcessingStatus()``, ``setValidationState()``, + ``setProgressValue()`` or a new caption. +- Emit ``embeddedWidgetSizeUpdated()`` after the embedded widget changed its size. The model + emits ``nodeUpdated`` for the node, like for ``requestNodeUpdate()``. +- Emit ``dataInvalidated(port)`` when an output has no valid data. The connected inputs get no + data. +- After ``portsInserted()`` or ``portsDeleted()`` you do not need to emit anything more. + ``DataFlowGraphModel`` updates the node. +- ``computingStarted()`` and ``computingFinished()`` have no listener in the library. They are + for the application, for example to show a busy state. + +**A custom** ``AbstractNodeGeometry``: + +- ``recomputeSize()`` must store the size with ``setNodeData(nodeId, NodeRole::Size, size)``. + ``size()`` and ``boundingRect()`` read it back from the model. +- The scene calls ``recomputeSize()`` when a node is created and in each ``onNodeUpdated``. + Nothing else calls it, so a size that depends on other state needs a ``nodeUpdated``. +- ``setOrientation()`` replaces the geometry with a default one. + +Pitfalls +-------- + +- **Size is overwritten.** A ``Size`` set from code lasts until the next ``nodeUpdated``. Then + ``recomputeSize()`` writes the computed size again. +- **Two scenes on one model** share one ``Size`` value. The last scene that recomputes wins. + The other scene then draws with the wrong size. +- **Without a scene** the ``Size`` role is not computed. A headless ``DataFlowGraphModel`` + returns an invalid size. +- **A widget that resizes itself** does not grow its node. The delegate must emit + ``embeddedWidgetSizeUpdated()`` or ``requestNodeUpdate()``. +- **A global style change** (``StyleCollection::setNodeStyle()`` and similar) does not repaint + the scene. Delegates copy the node style when they are created, so existing nodes keep the + old style. +- **modelReset** deletes the embedded widgets with their proxies. A model that keeps a raw + widget pointer then has a dangling pointer. It also clears the undo stack. +- **Every** ``nodeUpdated`` is a full relayout of the node: size, widget position, repaint and + all its connections. Do not emit it in a tight loop. diff --git a/docs/guide/graph-models.rst b/docs/guide/graph-models.rst index a33622f4..7ae34c00 100644 --- a/docs/guide/graph-models.rst +++ b/docs/guide/graph-models.rst @@ -118,7 +118,8 @@ Implement ``nodeData()`` and ``setNodeData()`` to provide node information: - Position on the canvas * - ``Size`` - ``QSize`` - - Size hint for embedded widgets + - Layout size of the node. The geometry computes it, and the model only stores it and + returns it. A value set from code is replaced at the next ``nodeUpdated``. * - ``Caption`` - ``QString`` - Display name shown on the node diff --git a/docs/index.rst b/docs/index.rst index c9722873..14604192 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -67,6 +67,7 @@ User Guide guide/styling guide/serialization guide/undo-redo + guide/change-notifications guide/advanced Examples diff --git a/docs/requirements.txt b/docs/requirements.txt index 992b598d..38f75538 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,3 +1,4 @@ sphinx breathe sphinx_rtd_theme +sphinxcontrib-mermaid diff --git a/include/QtNodes/internal/AbstractGraphModel.hpp b/include/QtNodes/internal/AbstractGraphModel.hpp index b948e492..18775803 100644 --- a/include/QtNodes/internal/AbstractGraphModel.hpp +++ b/include/QtNodes/internal/AbstractGraphModel.hpp @@ -120,6 +120,11 @@ class NODE_EDITOR_PUBLIC AbstractGraphModel : public QObject * * Sets: Node Caption, Node Caption Visibility, * Shyle, State, Node Position etc. + * + * NodeRole::Size is not such a property. The geometry of the scene computes the layout + * size from the content of the node and stores it with this function. The model only + * stores the value and returns it. A value that is set from outside is replaced at the + * next `nodeUpdated`. * @see NodeRole. */ virtual bool setNodeData(NodeId nodeId, NodeRole role, QVariant value) = 0; diff --git a/include/QtNodes/internal/Definitions.hpp b/include/QtNodes/internal/Definitions.hpp index 99339872..6577959b 100644 --- a/include/QtNodes/internal/Definitions.hpp +++ b/include/QtNodes/internal/Definitions.hpp @@ -24,7 +24,7 @@ Q_NAMESPACE_EXPORT(NODE_EDITOR_PUBLIC) enum class NodeRole { Type = 0, ///< Type of the current node, usually a string. Position = 1, ///< `QPointF` positon of the node on the scene. - Size = 2, ///< `QSize` for resizable nodes. + Size = 2, ///< `QSize`, layout size computed by the geometry. Not an input. CaptionVisible = 3, ///< `bool` for caption visibility. Caption = 4, ///< `QString` for node caption. Style = 5, ///< Custom NodeStyle as QJsonDocument