Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/faq.rst
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ Implement ``saveNode()`` and ``loadNode()`` in your model:
// Recreate node from saved data
}

The library writes the node id itself. With the default ``saveNode()`` and
``loadNode()``, undo of a delete cannot restore the node.

**Embedded widget doesn't show**

Ensure your ``embeddedWidget()`` returns a valid widget:
Expand Down
4 changes: 4 additions & 0 deletions docs/guide/graph-models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,10 @@ Override ``saveNode()`` and ``loadNode()`` to support save/load:
return json;
}

The default ``saveNode()`` returns an empty object and the default
``loadNode()`` does nothing. Without both functions, undo of a delete cannot
restore the node. See :doc:`undo-redo`.

See :doc:`serialization` for complete save/load implementation.

Complete Example
Expand Down
10 changes: 8 additions & 2 deletions docs/guide/undo-redo.rst
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,16 @@ model implements ``saveNode()`` and ``loadNode()``:
restoreNodeInternalData(nodeId, json["internal-data"].toObject());
}

The library writes the ``"id"`` key itself after it calls ``saveNode()``.
Your ``saveNode()`` does not need to save the node id for the undo commands.
It still needs to save the data that ``loadNode()`` reads back.

.. warning::

Without proper ``saveNode()``/``loadNode()``, deleted nodes cannot be
restored by undo.
The default ``saveNode()`` returns an empty object and the default
``loadNode()`` does nothing. With the defaults, the delete command still
deletes the right node, but undo cannot restore it. The node stays deleted.
To restore a deleted node by undo, implement both functions.

Custom Undo Commands
--------------------
Expand Down
11 changes: 11 additions & 0 deletions include/QtNodes/internal/AbstractGraphModel.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,14 @@ class NODE_EDITOR_PUBLIC AbstractGraphModel : public QObject
/**
* Reimplement the function if you want to store/restore the node's
* inner state during undo/redo node deletion operations.
*
* The library writes the "id" key itself after this call. You do not
* need to save the node id for the undo commands.
*
* To restore a deleted node by undo, saveNode() and loadNode() must
* save and restore the node state. The default implementation returns
* an empty object. Then undo of a delete cannot restore the node. The
* node stays deleted.
*/
virtual QJsonObject saveNode(NodeId const) const { return {}; }

Expand All @@ -183,6 +191,9 @@ class NODE_EDITOR_PUBLIC AbstractGraphModel : public QObject
*
* The function must do almost exacly the same thing as the normal addNode().
* The main difference is in a model-specific `inner-data` processing.
*
* The default implementation does nothing. Then undo of a delete cannot
* restore the node. The node stays deleted.
*/
virtual void loadNode(QJsonObject const &) {}

Expand Down
37 changes: 32 additions & 5 deletions include/QtNodes/internal/ConnectionIdUtils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <QJsonObject>

#include <iostream>
#include <limits>
#include <string>

namespace QtNodes {
Expand Down Expand Up @@ -138,20 +139,46 @@ inline QJsonObject toJson(ConnectionId const &connId)
return connJson;
}

// The invalid value is the same for all ids. jsonValueToUInt32() returns it on failure.
static_assert(InvalidNodeId == InvalidGroupId && InvalidNodeId == InvalidPortIndex
&& InvalidNodeId == std::numeric_limits<quint32>::max(),
"InvalidNodeId, InvalidGroupId and InvalidPortIndex must be the same value");

/**
* Reads an unsigned 32-bit id from JSON.
* Returns the maximum value (InvalidNodeId, InvalidGroupId, InvalidPortIndex) when the value is
* not a number in the unsigned 32-bit range.
* QJsonValue::toInt() returns the default value for numbers above the int range.
* This function accepts the whole unsigned range.
*/
inline quint32 jsonValueToUInt32(QJsonValue const &value)
{
constexpr quint32 invalid = std::numeric_limits<quint32>::max();

if (!value.isDouble())
return invalid;

double const number = value.toDouble();
if (number < 0.0 || number > static_cast<double>(invalid))
return invalid;

return static_cast<quint32>(number);
}

inline ConnectionId fromJson(QJsonObject const &connJson)
{
// Support both "inNodeId" (correct) and "intNodeId" (legacy typo) for backward compatibility
NodeId inNodeId = InvalidNodeId;
if (connJson.contains("inNodeId")) {
inNodeId = static_cast<NodeId>(connJson["inNodeId"].toInt(InvalidNodeId));
inNodeId = jsonValueToUInt32(connJson["inNodeId"]);
} else if (connJson.contains("intNodeId")) {
inNodeId = static_cast<NodeId>(connJson["intNodeId"].toInt(InvalidNodeId));
inNodeId = jsonValueToUInt32(connJson["intNodeId"]);
}

ConnectionId connId{static_cast<NodeId>(connJson["outNodeId"].toInt(InvalidNodeId)),
static_cast<PortIndex>(connJson["outPortIndex"].toInt(InvalidPortIndex)),
ConnectionId connId{jsonValueToUInt32(connJson["outNodeId"]),
jsonValueToUInt32(connJson["outPortIndex"]),
inNodeId,
static_cast<PortIndex>(connJson["inPortIndex"].toInt(InvalidPortIndex))};
jsonValueToUInt32(connJson["inPortIndex"])};

return connId;
}
Expand Down
34 changes: 23 additions & 11 deletions src/UndoCommands.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@

namespace QtNodes {

// The library writes the node id itself. A model may not store it in saveNode().
static QJsonObject saveNodeWithId(AbstractGraphModel const &graphModel, NodeId const nodeId)
{
QJsonObject json = graphModel.saveNode(nodeId);
json["id"] = static_cast<qint64>(nodeId);
return json;
}

static QJsonObject serializeSelectedItems(BasicGraphicsScene *scene)
{
QJsonObject serializedScene;
Expand All @@ -37,7 +45,7 @@ static QJsonObject serializeSelectedItems(BasicGraphicsScene *scene)

auto const inserted = selectedNodes.insert(node->nodeId());
if (inserted.second) {
nodesJsonArray.append(graphModel.saveNode(node->nodeId()));
nodesJsonArray.append(saveNodeWithId(graphModel, node->nodeId()));
}
};

Expand Down Expand Up @@ -115,9 +123,12 @@ static void insertSerializedItems(QJsonObject const &json, BasicGraphicsScene *s

graphModel.loadNode(obj);

auto id = obj["id"].toInt();
scene->nodeGraphicsObject(id)->setZValue(1.0);
scene->nodeGraphicsObject(id)->setSelected(true);
// The model may not restore the node, for example with the default loadNode().
NodeId const id = jsonValueToUInt32(obj["id"]);
if (auto *ngo = scene->nodeGraphicsObject(id)) {
ngo->setZValue(1.0);
ngo->setSelected(true);
}
}

QJsonArray const &connJsonArray = json["connections"].toArray();
Expand All @@ -130,7 +141,8 @@ static void insertSerializedItems(QJsonObject const &json, BasicGraphicsScene *s
// Restore the connection
graphModel.addConnection(connId);

scene->connectionGraphicsObject(connId)->setSelected(true);
if (auto *cgo = scene->connectionGraphicsObject(connId))
cgo->setSelected(true);
}

if (json.contains("groups")) {
Expand All @@ -145,7 +157,7 @@ static void insertSerializedItems(QJsonObject const &json, BasicGraphicsScene *s
std::vector<NodeGraphicsObject *> groupNodes;

for (const QJsonValue &idVal : nodeIdsJson) {
NodeId nodeId = static_cast<NodeId>(idVal.toInt());
NodeId nodeId = jsonValueToUInt32(idVal);
if (auto *ngo = scene->nodeGraphicsObject(nodeId)) {
groupNodes.push_back(ngo);
}
Expand All @@ -172,7 +184,7 @@ static void deleteSerializedItems(QJsonObject &sceneJson, AbstractGraphModel &gr

for (QJsonValueRef node : nodesJsonArray) {
QJsonObject nodeJson = node.toObject();
graphModel.deleteNode(nodeJson["id"].toInt());
graphModel.deleteNode(jsonValueToUInt32(nodeJson["id"]));
}
}

Expand Down Expand Up @@ -213,7 +225,7 @@ CreateCommand::CreateCommand(BasicGraphicsScene *scene,
void CreateCommand::undo()
{
QJsonArray nodesJsonArray;
nodesJsonArray.append(_scene->graphModel().saveNode(_nodeId));
nodesJsonArray.append(saveNodeWithId(_scene->graphModel(), _nodeId));
_sceneJson["nodes"] = nodesJsonArray;

_scene->graphModel().deleteNode(_nodeId);
Expand Down Expand Up @@ -264,7 +276,7 @@ DeleteCommand::DeleteCommand(BasicGraphicsScene *scene)
connJsonArray.append(toJson(cid));
}

nodesJsonArray.append(graphModel.saveNode(node->nodeId()));
nodesJsonArray.append(saveNodeWithId(graphModel, node->nodeId()));
};

QJsonArray groupsJsonArray;
Expand Down Expand Up @@ -448,7 +460,7 @@ QJsonObject PasteCommand::makeNewNodeIdsInScene(QJsonObject const &sceneJson)
for (QJsonValueRef node : nodesJsonArray) {
QJsonObject nodeJson = node.toObject();

NodeId oldNodeId = nodeJson["id"].toInt();
NodeId oldNodeId = jsonValueToUInt32(nodeJson["id"]);

NodeId newNodeId = graphModel.newNodeId();

Expand Down Expand Up @@ -491,7 +503,7 @@ QJsonObject PasteCommand::makeNewNodeIdsInScene(QJsonObject const &sceneJson)

QJsonArray newNodeIdsJson;
for (const QJsonValue &idVal : nodeIdsJson) {
NodeId oldId = static_cast<NodeId>(idVal.toInt());
NodeId oldId = jsonValueToUInt32(idVal);
NodeId newId = mapNodeIds[oldId];
newNodeIdsJson.append(static_cast<qint64>(newId));
}
Expand Down
1 change: 1 addition & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ add_executable(test_nodes
src/TestPaintedNodeShadows.cpp
src/TestNodeStyleRole.cpp
src/TestCopyPaste.cpp
src/TestSerializedItemCommands.cpp
src/TestZoomFeatures.cpp
src/TestLoopDetection.cpp
include/ApplicationSetup.hpp
Expand Down
4 changes: 2 additions & 2 deletions test/include/TestGraphModel.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ class TestGraphModel : public AbstractGraphModel
QJsonObject saveNode(NodeId const nodeId) const override
{
QJsonObject result;
result["id"] = static_cast<int>(nodeId);
result["id"] = static_cast<qint64>(nodeId);
auto nodeIt = _nodeData.find(nodeId);
if (nodeIt != _nodeData.end()) {
const auto &data = nodeIt->second;
Expand All @@ -251,7 +251,7 @@ class TestGraphModel : public AbstractGraphModel

void loadNode(QJsonObject const &nodeJson) override
{
NodeId id = static_cast<NodeId>(nodeJson["id"].toInt());
NodeId id = static_cast<NodeId>(nodeJson["id"].toDouble());

_nodeIds.insert(id);

Expand Down
Loading
Loading