forked from paceholder/nodeeditor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlowScene.cpp
More file actions
1444 lines (1134 loc) · 35 KB
/
Copy pathFlowScene.cpp
File metadata and controls
1444 lines (1134 loc) · 35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "FlowScene.hpp"
#include <iostream>
#include <stdexcept>
#include <set>
#include <tuple>
#include <QtWidgets/QGraphicsSceneMoveEvent>
#include <QtWidgets/QFileDialog>
#include <QtCore/QByteArray>
#include <QtCore/QBuffer>
#include <QtCore/QDataStream>
#include <QtCore/QFile>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
#include <QDebug>
#include "Node.hpp"
#include "Group.hpp"
#include "NodeGraphicsObject.hpp"
#include "NodeGraphicsObject.hpp"
#include "ConnectionGraphicsObject.hpp"
#include "Connection.hpp"
#include "FlowView.hpp"
#include "DataModelRegistry.hpp"
using QtNodes::FlowScene;
using QtNodes::Node;
using QtNodes::Group;
using QtNodes::NodeGraphicsObject;
using QtNodes::Connection;
using QtNodes::DataModelRegistry;
using QtNodes::NodeDataModel;
//using QtNodes::Properties;
using QtNodes::PortType;
using QtNodes::PortIndex;
FlowScene::
FlowScene(std::shared_ptr<DataModelRegistry> registry)
: _registry(registry)
{
setItemIndexMethod(QGraphicsScene::NoIndex);
ResetHistory();
auto UpdateLamda = [this](Node& n, const QPointF& newPosition, const QPointF &oldPosition)
{
resolveGroups(n);
QUuid id = n.id();
AddAction(
UndoRedoAction(
[this, id, oldPosition](void *)
{
UniqueNode n = _nodes[id];
n->nodeGraphicsObject().setPos(oldPosition);
return 0;
},
[this, id, newPosition](void *)
{
UniqueNode n = _nodes[id];
n->nodeGraphicsObject().setPos(newPosition);
return 0;
},
"Moved Node " + n.nodeDataModel()->name()
)
);
};
connect(this, &FlowScene::nodeMoveFinished, this, UpdateLamda);
auto GroupUpdateLamda = [this](Group& g, const QPointF& newPosition, const QPointF& oldPosition)
{
resolveGroups(g);
AddAction(UndoRedoAction(
[&g, oldPosition](void *ptr)
{
g.groupGraphicsObject().setPos(oldPosition);
return 0;
},
[&g, newPosition](void *ptr)
{
g.groupGraphicsObject().setPos(newPosition);
return 0;
},
"Moved Group " + g.GetName()
));
};
connect(this, &FlowScene::groupMoveFinished, this, GroupUpdateLamda);
anchors.resize(10);
}
FlowScene::
~FlowScene()
{
clearScene();
}
//------------------------------------------------------------------------------
std::shared_ptr<Connection>
FlowScene::
createConnection(PortType connectedPort,
Node& node,
PortIndex portIndex)
{
auto connection = std::make_shared<Connection>(connectedPort, node, portIndex);
auto cgo = std::make_unique<ConnectionGraphicsObject>(*this, *connection);
// after this function connection points are set to node port
connection->setGraphicsObject(std::move(cgo));
_connections[connection->id()] = connection;
connectionCreated(*connection);
return connection;
}
std::shared_ptr<Connection>
FlowScene::
createConnection(Node& nodeIn,
PortIndex portIndexIn,
Node& nodeOut,
PortIndex portIndexOut,
QUuid *id)
{
auto connection =
std::make_shared<Connection>(nodeIn,
portIndexIn,
nodeOut,
portIndexOut,
id);
auto cgo = std::make_unique<ConnectionGraphicsObject>(*this, *connection);
// after this function connection points are set to node port
connection->setGraphicsObject(std::move(cgo));
nodeIn.nodeState().setConnection(PortType::In, portIndexIn, *connection);
nodeOut.nodeState().setConnection(PortType::Out, portIndexOut, *connection);
// trigger data propagation
nodeOut.onDataUpdated(portIndexOut);
_connections[connection->id()] = connection;
connectionCreated(*connection);
return connection;
}
std::shared_ptr<Connection>
FlowScene::
restoreConnection(QJsonObject const &connectionJson)
{
QUuid nodeInId = QUuid(connectionJson["in_id"].toString());
QUuid nodeOutId = QUuid(connectionJson["out_id"].toString());
PortIndex portIndexIn = connectionJson["in_index"].toInt();
PortIndex portIndexOut = connectionJson["out_index"].toInt();
auto nodeIn = _nodes[nodeInId].get();
auto nodeOut = _nodes[nodeOutId].get();
std::vector<NodeState::ConnectionPtrSet> connIn = nodeIn->nodeState().getEntries(PortType::In);
std::vector<NodeState::ConnectionPtrSet> connOut = nodeOut->nodeState().getEntries(PortType::Out);
int numConnectionsIn = connIn.size();
int numConnectionsOut = connOut.size();
portIndexIn = std::min(numConnectionsIn - 1, portIndexIn);
portIndexOut = std::min(numConnectionsOut - 1, portIndexOut);
nodeIn->currentInputConnections++;
return createConnection(*nodeIn, portIndexIn, *nodeOut, portIndexOut);
}
void FlowScene::pasteConnection(QJsonObject const &connectionJson, QUuid newIn, QUuid newOut)
{
QUuid nodeInId = QUuid(connectionJson["in_id"].toString());
QUuid nodeOutId = QUuid(connectionJson["out_id"].toString());
PortIndex portIndexIn = connectionJson["in_index"].toInt();
PortIndex portIndexOut = connectionJson["out_index"].toInt();
auto nodeIn = _nodes[newIn].get();
auto nodeOut = _nodes[newOut].get();
if (!nodeIn || !nodeOut)
return;
createConnection(*nodeIn, portIndexIn, *nodeOut, portIndexOut);
}
void
FlowScene::
deleteConnection(Connection& connection)
{
connectionDeleted(connection);
connection.removeFromNodes();
_connections.erase(connection.id());
}
void
FlowScene::
deleteConnection(Connection* connection)
{
// connectionDeleted(connection);
connection->removeFromNodes();
_connections.erase(connection->id());
}
void
FlowScene::
deleteConnectionWithID(QUuid id)
{
Connection *connection = _connections[id].get();
deleteConnection(connection);
}
Node&
FlowScene::
createNode(std::unique_ptr<NodeDataModel> && dataModel)
{
auto node = std::make_unique<Node>(std::move(dataModel));
auto ngo = std::make_unique<NodeGraphicsObject>(*this, *node);
node->setGraphicsObject(std::move(ngo));
auto nodePtr = node.get();
_nodes[node->id()] = std::move(node);
nodeCreated(*nodePtr);
return *nodePtr;
}
Node&
FlowScene::
createNodeWithID(std::unique_ptr<NodeDataModel> && dataModel, QUuid id)
{
auto node = std::make_unique<Node>(std::move(dataModel));
node->setId(id);
auto ngo = std::make_unique<NodeGraphicsObject>(*this, *node);
node->setGraphicsObject(std::move(ngo));
auto nodePtr = node.get();
_nodes[node->id()] = std::move(node);
nodeCreated(*nodePtr);
return *nodePtr;
}
Group& FlowScene::createGroup() {
auto group = std::make_shared<Group>(*this);
auto ggo = std::make_shared<GroupGraphicsObject>(*this, *group);
QUuid id = group->id();
auto groupPtr = group.get();
group->setGraphicsObject(ggo);
_groups[id] = group;
return *groupPtr;
}
Group&
FlowScene::
restoreGroup(QJsonObject const& nodeJson) {
auto group = std::make_shared<Group>(*this);
auto ggo = std::make_shared<GroupGraphicsObject>(*this, *group);
QUuid id = group->id();
auto groupPtr = group.get();
group->setGraphicsObject(ggo);
_groups[id] = group;
group->restore(nodeJson);
return *groupPtr;
}
Group&
FlowScene::
pasteGroup(QJsonObject const& groupJson, QPointF nodeGroupCentroid, QPointF mousePos) {
auto group = std::make_shared<Group>(*this);
auto ggo = std::make_shared<GroupGraphicsObject>(*this, *group);
QUuid id = group->id();
auto groupPtr = group.get();
group->setGraphicsObject(ggo);
_groups[id] = group;
QJsonObject positionJson = groupJson["position"].toObject();
QPointF point(positionJson["x"].toDouble(),
positionJson["y"].toDouble());
QPointF pos = mousePos + (point - nodeGroupCentroid);
group->restoreAtPosition(groupJson, pos);
// group->groupGraphicsObject().setPos(pos);
// Group &groupRef = *(group);
// resolveGroups(groupRef);
// bool collapsed = (bool)groupJson["collapsed"].toInt();
// if(collapsed)
// {
// group->groupGraphicsObject().Collapse();
// }
return *groupPtr;
}
Node&
FlowScene::
restoreNode(QJsonObject const& nodeJson, bool keepId)
{
QString modelName = nodeJson["model"].toObject()["name"].toString();
auto dataModel = registry().create(modelName); //This is where it looks for the node by name
if (!dataModel)
{
dataModel = registry().create("DeletedNode");
}
auto node = std::make_shared<Node>(std::move(dataModel));
if(keepId) node->setId(QUuid( nodeJson["id"].toString() ));
auto ngo = std::make_unique<NodeGraphicsObject>(*this, *node);
node->setGraphicsObject(std::move(ngo));
auto nodePtr = node.get();
nodeCreated(*nodePtr);
node->restore(nodeJson);
_nodes[node->id()] = std::move(node);
resolveGroups(*nodePtr);
return *nodePtr;
}
QUuid FlowScene::pasteNode(QJsonObject &nodeJson, QPointF nodeGroupCentroid, QPointF mousePos) {
QString modelName = nodeJson["model"].toObject()["name"].toString();
auto dataModel = registry().create(modelName);
if (!dataModel)
throw std::logic_error(std::string("No registered model with name ") +
modelName.toLocal8Bit().data());
auto node = std::make_unique<Node>(std::move(dataModel));
auto ngo = std::make_unique<NodeGraphicsObject>(*this, *node);
node->setGraphicsObject(std::move(ngo));
QUuid newId = QUuid::createUuid();
node->paste(nodeJson, newId);
QPointF pos = mousePos + (node->nodeGraphicsObject().pos() - nodeGroupCentroid);
node->nodeGraphicsObject().setPos(pos);
auto nodePtr = node.get();
_nodes[node->id()] = std::move(node);
nodeCreated(*nodePtr);
nodePtr->updateView();
return newId;
}
void
FlowScene::
removeNode(Node& node)
{
// call signal
nodeDeleted(node);
auto deleteConnections =
[&node, this] (PortType portType)
{
auto nodeState = node.nodeState();
auto const & nodeEntries = nodeState.getEntries(portType);
for (auto &connections : nodeEntries)
{
for (auto const &pair : connections)
deleteConnection(*pair.second);
}
};
deleteConnections(PortType::In);
deleteConnections(PortType::Out);
_nodes.erase(node.id());
}
void
FlowScene::
removeNodeWithID(QUuid id)
{
UniqueNode nodePtr = _nodes[id];
Node &node = *nodePtr;
// call signal
nodeDeleted(node);
auto deleteConnections =
[&node, this] (PortType portType)
{
auto nodeState = node.nodeState();
auto const & nodeEntries = nodeState.getEntries(portType);
for (auto &connections : nodeEntries)
{
for (auto const &pair : connections)
deleteConnection(*pair.second);
}
};
deleteConnections(PortType::In);
deleteConnections(PortType::Out);
_nodes.erase(node.id());
}
void
FlowScene::
removeGroup(Group& group)
{
GroupGraphicsObject &ggo = group.groupGraphicsObject();
for(int i=ggo.childItems().size()-1; i>=0; i--)
{
QGraphicsItem *child = ggo.childItems()[i];
NodeGraphicsObject* n = qgraphicsitem_cast<NodeGraphicsObject*>(child);
if(n != nullptr)
{
QPointF position = n->scenePos();
ggo.childItems()[i]->setParentItem(0);
n->setPos(position);
n->moveConnections();
}
}
_groups.erase(group.id());
}
DataModelRegistry&
FlowScene::
registry() const
{
return *_registry;
}
std::shared_ptr<DataModelRegistry>
FlowScene::registryShared() const
{
return _registry;
}
void
FlowScene::
setRegistry(std::shared_ptr<DataModelRegistry> registry)
{
_registry = registry;
}
void
FlowScene::
iterateOverNodes(std::function<void(Node*)> visitor)
{
for (const auto& _node : _nodes)
{
visitor(_node.second.get());
}
}
void
FlowScene::
iterateOverNodeData(std::function<void(NodeDataModel*)> visitor)
{
for (const auto& _node : _nodes)
{
visitor(_node.second->nodeDataModel());
}
}
void
FlowScene::
iterateOverNodeDataDependentOrder(std::function<void(NodeDataModel*)> visitor)
{
std::set<QUuid> visitedNodesSet;
//A leaf node is a node with no input ports, or all possible input ports empty
auto isNodeLeaf =
[](Node const &node, NodeDataModel const &model)
{
for (size_t i = 0; i < model.nPorts(PortType::In); ++i)
{
auto connections = node.nodeState().connections(PortType::In, i);
if (!connections.empty())
{
return false;
}
}
return true;
};
//Iterate over "leaf" nodes
for (auto const &_node : _nodes)
{
auto const &node = _node.second;
auto model = node->nodeDataModel();
if (isNodeLeaf(*node, *model))
{
visitor(model);
visitedNodesSet.insert(node->id());
}
}
auto areNodeInputsVisitedBefore =
[&](Node const &node, NodeDataModel const &model)
{
for (size_t i = 0; i < model.nPorts(PortType::In); ++i)
{
auto connections = node.nodeState().connections(PortType::In, i);
for (auto& conn : connections)
{
if (visitedNodesSet.find(conn.second->getNode(PortType::Out)->id()) == visitedNodesSet.end())
{
return false;
}
}
}
return true;
};
//Iterate over dependent nodes
while (_nodes.size() != visitedNodesSet.size())
{
for (auto const &_node : _nodes)
{
auto const &node = _node.second;
if (visitedNodesSet.find(node->id()) != visitedNodesSet.end())
continue;
auto model = node->nodeDataModel();
if (areNodeInputsVisitedBefore(*node, *model))
{
visitor(model);
visitedNodesSet.insert(node->id());
}
}
}
}
QPointF
FlowScene::
getNodePosition(const Node& node) const
{
return node.nodeGraphicsObject().pos();
}
void
FlowScene::
setNodePosition(Node& node, const QPointF& pos) const
{
node.nodeGraphicsObject().setPos(pos);
node.nodeGraphicsObject().moveConnections();
}
QSizeF
FlowScene::
getNodeSize(const Node& node) const
{
return QSizeF(node.nodeGeometry().width(), node.nodeGeometry().height());
}
void
FlowScene::
resolveGroups(Group& group) {
if(group.groupGraphicsObject().isCollapsed()) return;
GroupGraphicsObject& ggo = group.groupGraphicsObject();
QRectF groupRect = ggo.mapRectToScene(ggo.boundingRect());
//Check if the nodes that were inside the group still are (When resizing)
for(int i=ggo.childItems().size()-1; i>=0; i--) {
QGraphicsObject* node = (QGraphicsObject*) ggo.childItems()[i];
QRectF nodeRect = node->mapRectToScene(node->boundingRect());
if(!groupRect.contains(nodeRect)) {
QPointF scenePos = node->scenePos();
node->setParentItem(nullptr);
ggo.childItems().removeAt(i);
node->setPos(scenePos);
}
}
//Check all the the other things that collide the group at its new location
QList<QGraphicsItem*>others = collidingItems(&ggo, Qt::IntersectsItemBoundingRect);
for(int i=0; i<others.size(); i++) {
QGraphicsItem* other = others[i];
NodeGraphicsObject* ngo = dynamic_cast<NodeGraphicsObject*>(other);
GroupGraphicsObject* ggo1 = dynamic_cast<GroupGraphicsObject*>(other);
if(ngo || ggo1) {
QRectF otherRect = other->mapRectToScene(other->boundingRect());
//checks what is inside
if(groupRect.contains(otherRect)) {
QPointF scenePos = other->scenePos();
QPointF parentPos = ggo.mapFromScene(scenePos);
if(!other->isAncestorOf(&ggo)) {
other->setParentItem(&ggo);
other->setPos(parentPos);
}
} else if(otherRect.contains(groupRect)) { // Checks inside of what it is
QPointF scenePos = ggo.scenePos();
QPointF parentPos = other->mapFromScene(scenePos);
if(!ggo.isAncestorOf(other)) {
ggo.setParentItem(other);
ggo.setPos(parentPos);
}
}
} else {
}
}
ggo.moveConnections();
}
void
FlowScene::
resolveGroups(Node& n) {
NodeGraphicsObject& c = n.nodeGraphicsObject();
bool hasIntersect = false;
//Check if the final position is inside a group
for (auto& group : _groups)
{
auto groupPtr = group.second.get();
GroupGraphicsObject* ggo = (GroupGraphicsObject*) groupPtr->_groupGraphicsObject.get();
QRectF groupRect = ggo->mapRectToScene(ggo->boundingRect());
QRectF nodeRect = c.mapRectToScene(c.boundingRect());
if(groupRect.contains(nodeRect)) {
hasIntersect = true;
if(c.parentItem() != ggo) {
QPointF scenePos = c.scenePos();
QPointF parentPos = ggo->mapFromScene(scenePos);
c.setParentItem(ggo);
c.setPos(parentPos);
}
}
}
//Check if it went out of a group
if(!hasIntersect && c.parentItem() != nullptr ) {
QPointF newPos = c.parentItem()->mapToScene(c.pos());
c.setParentItem(nullptr);
c.setPos(newPos);
}
}
std::unordered_map<QUuid, std::shared_ptr<Node> > const &
FlowScene::
nodes() const
{
return _nodes;
}
std::unordered_map<QUuid, std::shared_ptr<Node> > &
FlowScene::
nodes()
{
return _nodes;
}
std::unordered_map<QUuid, std::shared_ptr<Connection> > const &
FlowScene::
connections() const
{
return _connections;
}
std::vector<Node*>
FlowScene::
selectedNodes() const
{
QList<QGraphicsItem*> graphicsItems = selectedItems();
std::vector<Node*> ret;
ret.reserve(graphicsItems.size());
for (QGraphicsItem* item : graphicsItems)
{
auto ngo = qgraphicsitem_cast<NodeGraphicsObject*>(item);
if (ngo != nullptr)
{
Node* n = &(ngo->node());
ret.push_back(n);
}
}
return ret;
}
//------------------------------------------------------------------------------
void
FlowScene::
clearScene()
{
//Manual node cleanup. Simply clearing the holding datastructures doesn't work, the code crashes when
// there are both nodes and connections in the scene. (The data propagation internal logic tries to propagate
// data through already freed connections.)
std::vector<Node*> nodesToDelete;
for (auto& node : _nodes)
{
nodesToDelete.push_back(node.second.get());
}
for (auto& node : nodesToDelete)
{
removeNode(*node);
}
_groups.clear();
// for (auto& group : _groups)
// {
// _groups.erase(group.first);
// }
}
void
FlowScene::
save() const
{
QString fileName =
QFileDialog::getSaveFileName(nullptr,
tr("Open Flow Scene"),
QDir::homePath(),
tr("Flow Scene Files (*.flow)"));
if (!fileName.isEmpty())
{
if (!fileName.endsWith("flow", Qt::CaseInsensitive))
fileName += ".flow";
QFile file(fileName);
if (file.open(QIODevice::WriteOnly))
{
file.write(saveToMemory());
}
}
}
void
FlowScene::
load()
{
clearScene();
//-------------
QString fileName =
QFileDialog::getOpenFileName(nullptr,
tr("Open Flow Scene"),
QDir::homePath(),
tr("Flow Scene Files (*.flow)"));
if (!QFileInfo::exists(fileName))
return;
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return;
QByteArray wholeFile = file.readAll();
loadFromMemory(wholeFile);
}
QByteArray
FlowScene::
saveToMemory() const
{
QJsonObject sceneJson;
QJsonArray groupsJsonArray;
for (auto const & pair : _groups)
{
auto const &group = pair.second;
groupsJsonArray.append(group->save());
}
sceneJson["groups"] = groupsJsonArray;
QJsonArray nodesJsonArray;
for (auto const & pair : _nodes)
{
auto const &node = pair.second;
nodesJsonArray.append(node->save());
}
sceneJson["nodes"] = nodesJsonArray;
QJsonArray connectionJsonArray;
std::set<std::tuple<QUuid, PortIndex, QUuid, PortIndex>> uniqueConnections;
for (auto const & pair : _connections)
{
auto const &connection = pair.second;
QJsonObject connectionJson = connection->save();
if (!connectionJson.isEmpty())
{
// Extract connection details for duplicate detection
QUuid nodeInId = QUuid(connectionJson["in_id"].toString());
QUuid nodeOutId = QUuid(connectionJson["out_id"].toString());
PortIndex portIndexIn = connectionJson["in_index"].toInt();
PortIndex portIndexOut = connectionJson["out_index"].toInt();
// Create a unique identifier tuple
auto connectionKey = std::make_tuple(nodeInId, portIndexIn, nodeOutId, portIndexOut);
// Only add if we haven't seen this connection before
if (uniqueConnections.find(connectionKey) == uniqueConnections.end())
{
uniqueConnections.insert(connectionKey);
connectionJsonArray.append(connectionJson);
}
}
}
sceneJson["connections"] = connectionJsonArray;
QJsonArray anchorsJsonArray;
for(int i=0; i<anchors.size(); i++) {
QJsonObject anchor;
anchor["position_x"] = anchors[i].position.x();
anchor["position_y"] = anchors[i].position.y();
anchor["scale"] = anchors[i].scale;
anchorsJsonArray.append(anchor);
}
sceneJson["anchors"] = anchorsJsonArray;
QJsonDocument document(sceneJson);
return document.toJson();
}
void FlowScene::saveToClipBoard()
{
}
void
FlowScene::
loadFromMemory(const QByteArray& data)
{
QJsonObject const jsonDocument = QJsonDocument::fromJson(data).object();
QJsonArray nodesJsonArray = jsonDocument["nodes"].toArray();
for (int i = 0; i < nodesJsonArray.size(); ++i)
{
restoreNode(nodesJsonArray[i].toObject());
}
QJsonArray connectionJsonArray = jsonDocument["connections"].toArray();
for (int i = 0; i < connectionJsonArray.size(); ++i)
{
QJsonObject jsonObject = connectionJsonArray[i].toObject();
QUuid nodeInId = QUuid(jsonObject["in_id"].toString());
auto nodeIn = _nodes[nodeInId].get();
nodeIn->targetInputConnections++;
}
std::stable_sort( connectionJsonArray.begin( ), connectionJsonArray.end( ), [this]( const auto& lhs, const auto& rhs )
{
QPointF posA, posB;
QString nameA, nameB;
{
QJsonObject objA = lhs.toObject();
QUuid nodeInId = QUuid(objA["in_id"].toString());
PortIndex portIndexIn = objA["in_index"].toInt();
auto nodeIn = _nodes[nodeInId].get();
NodeGraphicsObject & ngo = nodeIn->nodeGraphicsObject();
posA = ngo.scenePos();
NodeDataModel *dm = nodeIn->nodeDataModel();
nameA = dm->name();
}
{
QJsonObject objB = rhs.toObject();
QUuid nodeInId = QUuid(objB["in_id"].toString());
PortIndex portIndexIn = objB["in_index"].toInt();
auto nodeIn = _nodes[nodeInId].get();
NodeGraphicsObject & ngo = nodeIn->nodeGraphicsObject();
posB = ngo.scenePos();
NodeDataModel *dm = nodeIn->nodeDataModel();
nameB = dm->name();
}
//We put input variables at the end, so we only compute them when all the data is loaded.
if (QString::compare(nameA, QString("InputVariable")) == 0 && QString::compare(nameB, QString("InputVariable")) != 0) {
return false;
}
else if (QString::compare(nameB, QString("InputVariable")) == 0 && QString::compare(nameA, QString("InputVariable")) != 0) {
return true;
}
else {
return posA.x() < posB.x();
}
});
for (int i = 0; i < connectionJsonArray.size(); ++i)
{
restoreConnection(connectionJsonArray[i].toObject());
}
QJsonArray groupsJsonArray = jsonDocument["groups"].toArray();
for (int i = 0; i < groupsJsonArray.size(); ++i)
{
restoreGroup(groupsJsonArray[i].toObject());
}
if(jsonDocument.contains("anchors")) {
QJsonArray anchorsJsonArray = jsonDocument["anchors"].toArray();