-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathnodegraph.py
1796 lines (1333 loc) · 58.3 KB
/
nodegraph.py
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
import logging
from coconodz import Qt
import nodz_main
import nodz_utils
from coconodz.lib import (BaseWindow,
GraphContext,
BackdropContext,
SearchField,
RenameField,
AttributeContext,
Backdrop,
ConfiguationMixin)
from coconodz import Manager as EventsManager
from coconodz import SuppressEvents
_COCONODZ_LOG = logging.getLogger(name="CocoNodz")
LOG = logging.getLogger(name="CocoNodz.nodegraph")
class Basegraph(object):
""" base graph class that should defined all available properties and methods
"""
RESERVED_NODETYPES = ["backdrop",
"dot"]
def __init__(self, *args, **kwargs):
super(Basegraph, self).__init__()
self._all_nodes = {}
self._all_backdrops = []
# the current Nodz implementation stores the
# node as tuple, which is not really clear to us
# why. lets handle node querying bettter by providing
# some useful properties
@property
def nodes_dict(self):
return self._all_nodes
@property
def all_nodes(self):
return [_[-1] for _ in self._all_nodes.items()]
@property
def all_node_names(self):
return self._all_nodes.keys()
@property
def selected_nodes(self):
return [_ for _ in self.all_nodes if _.isSelected()]
@property
def selected_node_names(self):
return [_.name for _ in self.selected_nodes if _.isSelected()]
@property
def all_backdrops(self):
return self._all_backdrops
@property
def all_backdrop_names(self):
return [_.name for _ in self.all_backdrops]
@property
def selected_backdrops(self):
return [_ for _ in self.all_backdrops if _.isSelected()]
@property
def selected_backdrop_names(self):
return [_.name for _ in self.selected_backdrops]
def get_node_by_name(self, node_name):
if node_name in self.nodes_dict:
return self.nodes_dict[node_name]
def get_slot_by_name(self, slot_name, plug_or_socket):
node = self.get_node_by_name(slot_name.split(".")[0])
name = slot_name.split(".", 1)[1]
if node:
if plug_or_socket == "plug":
if name in node.plugs:
return node.plugs[name]
elif plug_or_socket == "socket":
if name in node.sockets:
return node.sockets[name]
else:
raise NotImplementedError
def get_plug_by_name(self, plug_name):
return self.get_slot_by_name(plug_name, "plug")
def get_socket_by_name(self, socket_name):
return self.get_slot_by_name(socket_name, "socket")
def create_backdrop(self):
raise NotImplementedError
def on_creation_field_request(self):
raise NotImplementedError
def on_search_field_request(self):
raise NotImplementedError
def on_layout_request(self):
raise NotImplementedError
def on_rename_field_request(self):
raise NotImplementedError
def on_rename_field_input_accepted(self, new_node_name):
raise NotImplementedError
def on_context_request(self, widget):
raise NotImplementedError
def on_creation_field_input_accepted(self, node_type):
raise NotImplementedError
def on_search_field_opened(self):
raise NotImplementedError
def on_search_fiel_input_accepted(self, node_name):
raise NotImplementedError
def on_attribute_field_input_accepted(self, node_name, attribute_name):
raise NotImplementedError
def on_node_created(self, node):
raise NotImplementedError
def on_after_node_created(self, node):
raise NotImplementedError
def on_node_name_changed(self, node, old_name, new_name):
raise NotImplementedError
def on_node_selected(self):
raise NotImplementedError
def on_nodes_deleted(self, nodeitems_list):
raise NotImplementedError
def on_about_attribute_create(self, node_name, attribute_name):
raise NotImplementedError
def on_plug_created(self, plug_item):
raise NotImplementedError
def on_socket_created(self, socket_item):
raise NotImplementedError
def on_connection_made(self, connection_item):
raise NotImplementedError
def on_disconnection_made(self, connection_item):
raise NotImplementedError
def on_plug_connected(self, source_node_name, plug_name, destination_node_name, socket_name):
raise NotImplementedError
def on_plug_disconnected(self, source_node_name, plug_name, destination_node_name, socket_name):
raise NotImplementedError
def on_socket_connected(self, source_node_name, plug_name, destination_node_name, socket_name):
raise NotImplementedError
def on_socket_disconnected(self, source_node_name, plug_name, destination_node_name, socket_name):
raise NotImplementedError
def on_host_node_created(self, node_name, node_type):
raise NotImplementedError
def on_host_node_deleted(self, node_name):
raise NotImplementedError
def on_host_node_name_changed(self, new_name, old_name):
raise NotImplementedError
def on_host_nodes_selected(self, node_name):
raise NotImplementedError
def on_host_node_deselected(self, node_name):
raise NotImplementedError
def on_host_connection_made(self, plug_name, socket_name):
raise NotImplementedError
def on_host_disconnection_made(self, plug_name, socket_name):
raise NotImplementedError
def reset_configuration(self):
raise NotImplementedError
def apply_configuration(self):
raise NotImplementedError
def open(self):
raise NotImplementedError
def add_network(self, network):
raise NotImplementedError
def remove_network(self, network):
raise NotImplementedError
def clean_active_graph(self):
raise NotImplementedError
def save_active_graph(self, filepath):
raise NotImplementedError
def load_into_graph(self, filepath):
raise NotImplementedError
def load_configuration(self, configuration_file):
raise NotImplementedError
def configuration(self):
raise NotImplementedError
def save_configuration(self, filepath):
raise NotImplementedError
def update(self):
raise NotImplementedError
def clear(self):
raise NotImplementedError
class ItemSignals(Qt.QtCore.QObject):
""" signals we provide for all items
Unfortunately we are not able to provide custom
signals when subclassing QGraphicsItems.
"""
signal_context_request = Qt.QtCore.Signal(object)
signal_attr_created = Qt.QtCore.Signal(object)
signal_socket_created = Qt.QtCore.Signal(object)
signal_plug_created = Qt.QtCore.Signal(object)
signal_name_changed = Qt.QtCore.Signal(object)
signal_selected = Qt.QtCore.Signal(object)
def __init__(self):
Qt.QtCore.QObject.__init__(self)
class BackdropItem(Backdrop):
""" extends the Backdrop class
"""
signals = ItemSignals()
signal_context_request = signals.signal_context_request
def __init__(self, *args, **kwargs):
super(BackdropItem, self).__init__(*args, **kwargs)
def mousePressEvent(self, event):
""" extend the mousePressEvent
We are adding a context widget request on RMB click here
Args:
event:
Returns:
"""
if event.button() == Qt.QtCore.Qt.RightButton:
self.signal_context_request.emit(self)
super(BackdropItem, self).mousePressEvent(event)
class NodeItem(nodz_main.NodeItem):
""" extends the nodz_main.NodeItem class
Original implementation customization
"""
signals = ItemSignals()
signal_context_request = signals.signal_context_request
signal_attr_created = signals.signal_attr_created
signal_socket_created = signals.signal_socket_created
signal_plug_created = signals.signal_plug_created
signal_name_changed = signals.signal_name_changed
def __init__(self, name, alternate, preset, config):
super(NodeItem, self).__init__(name, alternate, preset, config)
self._node_type = None
self._plugs_dict = {}
self._sockets_dict = {}
self._connections = []
# unfortunately the original NodeItem implementation doesn't store the config
# by default
self._config = config
@property
def node_type(self):
""" holds the nodes node type
Returns: string node type
"""
return self._node_type
@node_type.setter
def node_type(self, value):
""" sets the nodes node type
Args:
value: node type string
Returns:
"""
assert isinstance(value, basestring)
self._node_type = value
@property
def connections(self):
""" holds all the connections to the node
Returns: ConnectionItem list
"""
return self._connections
def append_connection(self, connection):
""" appends the stored node connection to the connections list
Args:
connection: ConnectionItem instance
Returns:
"""
assert isinstance(connection, ConnectionItem)
self._connections.append(connection)
def remove_connection(self, connection):
""" removes a stored node connection from stored node connections list
Args:
connection: ConnectionItem instance
Returns:
"""
if connection in self.connections:
self.connections.remove(connection)
def mousePressEvent(self, event):
""" extend the mousePressEvent
We are adding a context widget request on RMB click here
Args:
event:
Returns:
"""
if event.button() == Qt.QtCore.Qt.RightButton:
self.signal_context_request.emit(self)
super(NodeItem, self).mousePressEvent(event)
def add_attribute(self, name, add_mode=None, plug=True, socket=True, data_type=""):
""" wrapper around the _createAttribute method that allows better customization of attribute generation
Args:
name:
add_mode: defines where on the node the attribute will be placed, "top", "bottom", "alphabetical"
plug: if True the attribute will be added as plug
socket: if True the attribute will be added as socket
data_type: attribute data type
Returns:
"""
# skip process if slot already exists
if name in self.attrs:
return
# closure to avoid redoing preset checking all the time
def _do_creation():
if data_type:
preset = "datatype_{0}".format(data_type)
else:
preset = "datatype_default"
if preset not in self._config:
LOG.info("Attribute preset for type {0} not configured.".format(data_type))
self._createAttribute(name, index, "datatype_default", plug, socket, data_type)
else:
self._createAttribute(name, index, preset, plug, socket, data_type)
# emit specific signals
if plug:
self.plugs[name].node = self.plugs[name].parentItem()
self.signal_plug_created.emit(self.plugs[name])
if socket:
self.sockets[name].node = self.sockets[name].parentItem()
self.signal_socket_created.emit(self.sockets[name])
# if no add_mode is defined take the order from the config
if not add_mode:
add_mode = self._config["attribute_order"]
_allowed_modes = ["top", "bottom", "alphabetical"]
assert add_mode in _allowed_modes, "Unknown mode. Choose from: " + "".join("'{0}' ".format(_) for _ in _allowed_modes)
# create attribute at expected index
if add_mode == "top":
index = 0
_do_creation()
elif add_mode == "bottom":
index = -1
_do_creation()
elif add_mode == "alphabetical":
_attrs = list(self.attrs)
_attrs.append(name)
_sorted = sorted(_attrs)
index = _sorted.index(name)
_do_creation()
else:
raise NotImplementedError
# update the connections paths
for connection in self.connections:
connection.target_point = connection.target.center()
connection.source_point = connection.source.center()
connection.updatePath()
class ConnectionItem(nodz_main.ConnectionItem):
""" extends the nodz_main.ConnectionItem class
Original implementation customization
"""
def __init__(self, source_point, target_point, source, target):
super(ConnectionItem, self).__init__(source_point, target_point, source, target)
self.setAcceptHoverEvents(True)
self.setFlag(Qt.QtWidgets.QGraphicsItem.ItemIsSelectable)
self.configuration = self.source.scene().views()[0].configuration
self._selected_pen = Qt.QtGui.QPen(nodz_utils._convertDataToColor(
self.configuration.connection_highlight_color)
)
self._selected_pen.setWidth(2)
self.title = Qt.QtWidgets.QGraphicsTextItem("", parent=self)
self.title_font = Qt.QtGui.QFont(self.configuration.attr_font,
self.configuration.attr_font_size)
self.title.setFont(self.title_font)
self.title.setDefaultTextColor(nodz_utils._convertDataToColor(
self.configuration.connection_text_color)
)
self._moved = False
self._hovered = False
def updatePath(self):
""" overrides the original method
We added support for configurable path shapes here
Returns:
"""
self.setPen(self._pen)
path = Qt.QtGui.QPainterPath()
path.moveTo(self.source_point)
dx = (self.target_point.x() - self.source_point.x()) * 0.5
dy = self.target_point.y() - self.source_point.y()
ctrl1 = Qt.QtCore.QPointF(self.source_point.x() + dx, self.source_point.y() + dy * 0)
ctrl2 = Qt.QtCore.QPointF(self.source_point.x() + dx, self.source_point.y() + dy * 1)
# handle interpolation mode
if self.configuration.connection_interpolation == "line":
path.lineTo(self.target_point)
elif self.configuration.connection_interpolation == "bezier":
path.cubicTo(ctrl1, ctrl2, self.target_point)
self.setPath(path)
def _show_connection_title(self):
self.title.setPlainText("{0}.{1} - {2}.{3}".format(self.source.parentItem().name,
self.source.attribute,
self.target.parentItem().name,
self.target.attribute))
center_position = Qt.QtCore.QPointF(self.boundingRect().center().x() - (self.title.boundingRect().width() / 2),
self.boundingRect().center().y() - (self.title.boundingRect().height() / 2)
)
self.title.setPos(center_position)
self.title.setVisible(True)
def hoverEnterEvent(self, event):
self._show_connection_title()
self._hovered = True
super(ConnectionItem, self).hoverEnterEvent(event)
def hoverLeaveEvent(self, event):
self.title.setVisible(False)
self._hovered = False
super(ConnectionItem, self).hoverLeaveEvent(event)
def shape(self):
stroker = Qt.QtGui.QPainterPathStroker()
stroker.setWidth(5)
shape = stroker.createStroke(self.path())
return shape
def mousePressEvent(self, event):
self._moved = False
self.scene().clearSelection()
self.setSelected(True)
def mouseReleaseEvent(self, event):
if self._moved:
item = self.scene().itemAt(self.mapToScene(event.pos()), Qt.QtGui.QTransform())
if not (isinstance(item, nodz_main.PlugItem) or isinstance(item, nodz_main.SocketItem)):
self.target.disconnect(self)
self.source.disconnect(self)
scene = self.scene()
scene.removeItem(self)
scene.update()
def mouseMoveEvent(self, event):
self._moved = True
super(ConnectionItem, self).mouseMoveEvent(event)
def paint(self, painter, *args):
self.updatePath()
if self._hovered or self.isSelected():
painter.setPen(self._selected_pen)
else:
painter.setPen(self._pen)
painter.drawPath(self.path())
class Nodz(ConfiguationMixin, nodz_main.Nodz):
""" extends the nodz_main.Nodz class
Original implementation customization
"""
signal_node_created = Qt.QtCore.Signal(object)
signal_nodes_deleted = Qt.QtCore.Signal(object)
signal_selection_changed = Qt.QtCore.Signal(object)
signal_after_node_created = Qt.QtCore.Signal(object)
signal_node_name_changed = Qt.QtCore.Signal(object, str, str)
signal_plug_created = Qt.QtCore.Signal(object)
signal_socket_created = Qt.QtCore.Signal(object)
signal_connection_made = Qt.QtCore.Signal(object)
signal_disconnection_made = Qt.QtCore.Signal(object)
signal_about_attribute_create = Qt.QtCore.Signal(str, str)
signal_context_request = Qt.QtCore.Signal(object)
signal_creation_field_request = Qt.QtCore.Signal()
signal_search_field_request = Qt.QtCore.Signal()
signal_rename_field_request = Qt.QtCore.Signal()
signal_layout_request = Qt.QtCore.Signal()
signal_plug_connected = None
signal_plug_disconnected = None
signal_socket_connected = None
signal_socket_disconnected = None
def __init__(self, parent):
# unfortunately nodz_main.Nodz expects a default config file at the same level as the module
# we pass our default here
super(Nodz, self).__init__(parent, configPath=self.BASE_CONFIG_PATH)
self.initialize_configuration()
self.config = self.configuration_data
self._rename_field = RenameField(self)
self._search_field = SearchField(self)
self._creation_field = SearchField(self)
self._context = GraphContext(self)
self._attribute_context = AttributeContext(self)
self._backdrop_context = BackdropContext(self)
# patching original signals
self.signal_plug_connected = self.signal_PlugConnected
self.signal_plug_disconnected = self.signal_PlugDisconnected
self.signal_socket_connected = self.signal_SocketConnected
self.signal_socket_disconnected = self.signal_SocketDisconnected
# test
self.selected_nodes = []
@property
def rename_field(self):
return self._rename_field
@property
def search_field(self):
""" holds the search field widget
Returns: SearchField instance
"""
return self._search_field
@property
def creation_field(self):
""" holds the creation field widgets
Returns: SearchField instance
"""
return self._creation_field
@property
def context(self):
""" holds the creation field widgets
Returns: GraphContext instance
"""
return self._context
@property
def attribute_context(self):
""" holds the attribute field widgets
Returns: AttributeContext instance
"""
return self._attribute_context
@property
def backdrop_context(self):
""" holds the backdrop context widget
Returns: AttributeContext instance
"""
return self._backdrop_context
def keyPressEvent(self, event):
""" overrides the keyPressEvent
We are adding more key press events here
Args:
event:
Returns:
"""
if event.key() not in self.pressedKeys:
self.pressedKeys.append(event.key())
if event.key() == Qt.QtCore.Qt.Key_Delete:
self._deleteSelectedNodes()
if (event.key() == Qt.QtCore.Qt.Key_F and
event.modifiers() == Qt.QtCore.Qt.NoModifier):
self._focus()
if (event.key() == Qt.QtCore.Qt.Key_S and
event.modifiers() == Qt.QtCore.Qt.NoModifier):
self._nodeSnap = True
if event.key() == Qt.QtCore.Qt.Key_Tab:
self.signal_creation_field_request.emit()
if (event.key() == Qt.QtCore.Qt.Key_F and
event.modifiers() == Qt.QtCore.Qt.ControlModifier):
self.signal_search_field_request.emit()
if event.key() == Qt.QtCore.Qt.Key_L:
self.signal_layout_request.emit()
if event.key() == Qt.QtCore.Qt.Key_R:
self.signal_rename_field_request.emit()
# Emit signal.
self.signal_KeyPressed.emit(event.key())
super(Nodz, self).keyPressEvent(event)
def mousePressEvent(self, event):
""" extends the mousePressEvent
We are adding a context widget request on RMB click here
Args:
event:
Returns:
"""
if not self.scene().itemAt(self.mapToScene(event.pos()), Qt.QtGui.QTransform()):
if event.button() == Qt.QtCore.Qt.RightButton and event.modifiers() == Qt.QtCore.Qt.NoModifier:
self.signal_context_request.emit(self.scene().itemAt(self.mapToScene(event.pos()), Qt.QtGui.QTransform()))
super(Nodz, self).mousePressEvent(event)
def _deleteSelectedNodes(self):
""" overrides original method
Let us emit a signal on nodes deletion
Returns:
"""
self.signal_nodes_deleted.emit([_ for _ in self.scene().selectedItems() if isinstance(_, NodeItem)])
super(Nodz, self)._deleteSelectedNodes()
def _deleteSelectedNodes(self):
""" overrides original method
Let us emit a signal on nodes deletion
Returns:
"""
for node in self.scene().selectedItems():
node._remove()
# Emit signal.
self.signal_nodes_deleted.emit([_ for _ in self.scene().selectedItems() if isinstance(_, NodeItem)])
def retrieve_creation_position(self):
""" retrieves the position where something should be created
Depending on the configuration we define where to place nodes/backdrops/dots etc
Returns: QPointF
"""
if self.configuration.node_placement == "cursor":
position = Qt.QtCore.QPointF(self.mapToScene(self.mapFromGlobal(Qt.QtGui.QCursor.pos())))
elif self.configuration.node_placement == "creation_field":
position = Qt.QtCore.QPointF(self.mapToScene(self.mapFromGlobal(self.creation_field.pos())))
else:
position = None
return position
def create_node(self, name, position=None, alternate=False, node_type="default"):
""" wrapper around Nodz.createNode() to extend behavior
Args:
name: node name
position: if unset it will calculate the position based on the configuration
alternate: The attribute color alternate state, if True, every 2 attribute the color will be slightly darker
node_type: node type
Returns: NodeItem instance
"""
if node_type == "backdrop":
self.create_backdrop()
else:
if not position:
position = self.retrieve_creation_position()
_ = "node_{0}".format(node_type)
if hasattr(self.configuration, _):
# and create node with included preset
node = self.createNode(name, _, position=position, alternate=alternate)
else:
LOG.info("Node preset for type {0} not configured.".format(node_type))
node = self.createNode(name, position=position, alternate=alternate)
node.node_type = node_type
self.signal_node_created.emit(node)
return node
def createNode(self, name="default", preset="node_default", position=None, alternate=False):
""" overrides the createNode method
Args:
name:
preset:
position:
alternate:
Returns:
"""
nodeItem = NodeItem(name=name, alternate=alternate, preset=preset,
config=self.configuration_data)
nodeItem.signal_context_request.connect(self.on_context_request)
nodeItem.signal_plug_created.connect(self.on_plug_created)
nodeItem.signal_socket_created.connect(self.on_socket_created)
# Store node in scene.
self.scene().nodes[name] = nodeItem
if not position:
# Get the center of the view.
position = self.mapToScene(self.viewport().rect().center())
# Set node position.
self.scene().addItem(nodeItem)
nodeItem.setPos(position - nodeItem.nodeCenter)
# Emit signal.
self.signal_NodeCreated.emit(name)
return nodeItem
def delete_node(self, name):
raise NotImplementedError
def rename_node(self, node, new_name):
""" gives specified node a new name
Args:
node: NodeItem instance
new_name: new name
Returns:
"""
old_name = node.name
if old_name != new_name:
self.editNode(node, new_name)
self.signal_node_name_changed.emit(node, old_name, new_name)
def create_backdrop(self):
pass
def apply_data_type_color_to_connection(self, connection):
""" takes and applies the data type color to the connection
Args:
connection: ConnectionItemInstance
Returns:
"""
# set color based on data_type
if self.configuration.connection_inherit_datatype_color:
if connection.plugItem:
expected_config = "datatype_{0}".format(connection.plugItem.dataType)
else:
expected_config = "datatype_{0}".format(connection.socketItem.dataType)
if hasattr(self.configuration, expected_config):
color = nodz_utils._convertDataToColor(self.configuration_data[expected_config]["plug"])
connection._pen = color
def connect_attributes(self, plug, socket):
""" creates a new ConnectionItem instance that connects plug and socket
Args:
plug:
socket:
Returns:
"""
connection = self.createConnection(plug, socket)
return connection
def createConnection(self, plug, socket):
""" extends the createConnection
We are adding the possibility to apply data type color to the connection here
Args:
plug:
socket:
Returns:
"""
connection = ConnectionItem(plug.center(), socket.center(), plug, socket)
connection.plugNode = plug.parentItem().name
connection.plugAttr = plug.attribute
connection.plugItem = plug
connection.socketNode = socket.parentItem().name
connection.socketAttr = socket.attribute
connection.socketItem = socket
plug.connect(socket, connection)
socket.connect(plug, connection)
# let us apply the corresponding data type color
self.apply_data_type_color_to_connection(connection)
self.scene().addItem(connection)
connection.updatePath()
return connection
def get_shared_connection(self, plug, socket):
""" finds the shared connection item
Args:
plug: PlugItem instance
socket: SocketItem instance
Returns: ConnectionItem instance
"""
all_connections = plug.connections + socket.connections
shared_connections = list(set(all_connections))
if shared_connections:
if len(shared_connections) != 1:
LOG.error("Multiple shared connections on plug '{0}' and socket '{1}'".format(plug, socket))
else:
return shared_connections[0]
def disconnect_attributes(self, plug, socket):
""" removes a shared connection
Args:
plug: PlugItem instance
socket: SocketItem instance
Returns:
"""
connection = self.get_shared_connection(plug, socket)
if connection:
connection._remove()
def on_context_request(self, node_item):
""" placeholder method, has to be overriden in Nodegraph class
Args:
node_item:
Returns:
"""
pass
def on_plug_created(self, plug_item):
pass
def on_socket_created(self, socket_item):
pass
def on_selected(self, node):
pass
def layout_nodes(self, node_names=None):
""" rearranges node positions
Notes:
Adopted from implementation of user https://github.com/glm-ypinczon
Args:
node_names: expects a list of node names otherwise it will consider all available nodes
Returns:
"""
node_width = 300 # default value, will be replaced by node.baseWidth + margin when iterating on the first node
margin = self.configuration.layout_margin_size
scene_nodes = self.scene().nodes.keys()
if not node_names:
node_names = scene_nodes
root_nodes = []
already_placed_nodes = []
# root nodes (without connection on the plug)
for node_name in node_names:
node = self.scene().nodes[node_name]
if node is not None:
node_width = node.baseWidth + margin
is_root = True
for plug in node.plugs.values():
is_root &= (len(plug.connections) == 0)
if is_root:
root_nodes.append(node)
max_graph_width = 0
root_graphs = []
for root_node in root_nodes:
root_graph = list()
root_graph.append([root_node])
current_graph_level = 0
do_next_graph_level = True
while do_next_graph_level:
do_next_graph_level = False
for _node in range(len(root_graph[current_graph_level])):
node = root_graph[current_graph_level][_node]
for attr in node.attrs:
if attr in node.sockets:
socket = node.sockets[attr]
for connection in socket.connections:
if len(root_graph) <= current_graph_level + 1:
root_graph.append(list())
root_graph[current_graph_level + 1].append(connection.plugItem.parentItem())
do_next_graph_level = True
current_graph_level += 1