forked from Golaem/Nodz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodz_main.py
3087 lines (2404 loc) · 114 KB
/
nodz_main.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
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from builtins import str
from builtins import range
from past.utils import old_div
from builtins import object
import os
import re
import json
import copy
from glm.Qtpy.Qt import QtGui, QtCore, QtWidgets, Qt
from . import nodz_utils as utils
from . import nodz_extra
defaultConfigPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'default_config.json')
if Qt.IsPyQt5 or Qt.IsPyQt4:
signalObject = 'PyQt_PyObject'
else:
signalObject = 'PyObject'
class ConnectionInfo(object):
def __init__(self, connectionItem):
# Storage.
self.socketNode = connectionItem.socketNode
self.socketAttr = connectionItem.socketAttr
self.plugNode = connectionItem.plugNode
self.plugAttr = connectionItem.plugAttr
class Nodz(QtWidgets.QGraphicsView):
"""
The main view for the node graph representation.
The node view implements a state pattern to control all the
different user interactions.
"""
# if we want to be more generic, should use pre and post signals, and fetch whatever in Layout side, but this is not resilient to nested calls :/
# some calls have not been handled via those methodes : createNode (handled via nodeCreator overload), editNode, deleteNode, createAttribute, editAttribute, deleteAttribute : they are not called directly by LayoutEditor, but encapsulated via nodeCreator, loadGraph, etc. We issue less events if handling the top level action issueing this
# all undo calls start with emitter nodzInstance
signal_UndoRedoModifySelection = QtCore.Signal(signalObject, signalObject, signalObject) # node id list before, node id list after. signal_NodeSelected does not send previous selection
signal_UndoRedoDeleteSelectedNodes = QtCore.Signal(signalObject, signalObject) # list of deleted nodes (user data copies). signal_NodeDeleted does only send deleted node names, too late to get their userData for redo
# # signal_UndoRedoEditNodeName = QtCore.Signal(signalObject, str, str) # node name before, node name after UNUSED
signal_UndoRedoAddNode = QtCore.Signal(signalObject, signalObject) # node added user data. For consistency with signal_UndoRedoDeleteSelectedNodes (we may actually store undo via signal_NodeCreated, but would be called a lot of time from loadGraph)
signal_UndoRedoMoveNodes = QtCore.Signal(signalObject, signalObject, signalObject, signalObject) # node name list, fromPos list, toPos list. signal_NodeMoved does not send previous position
signal_UndoRedoConnectNodes = QtCore.Signal(signalObject, signalObject, signalObject) # list of removed ConnectionInfo (potentially due to addition), list of new ConnectionInfo. Could deal with it with plug/socket connected / disconnected but would be tedious with a lot of calls
signal_dropOnNode = QtCore.Signal(signalObject, signalObject) #nodzInst, nodeItem
signal_StartCompoundInteraction = QtCore.Signal(signalObject) # starts user interaction on a nodz
signal_EndCompoundInteraction = QtCore.Signal(signalObject, bool) # end user interaction on a nodz
signal_SceneDoubleClicked = QtCore.Signal()
signal_NodeCreated = QtCore.Signal(signalObject)
signal_NodePreDeleted = QtCore.Signal(signalObject)
signal_NodeDeleted = QtCore.Signal(signalObject)
signal_NodeEdited = QtCore.Signal(signalObject, signalObject)
signal_NodeSelected = QtCore.Signal(signalObject)
signal_NodeMoved = QtCore.Signal(signalObject, signalObject)
# signal_NodeRightClicked = QtCore.Signal(signalObject)
signal_NodeDoubleClicked = QtCore.Signal(signalObject)
signal_ViewContextMenuEvent = QtCore.Signal(signalObject) # view context menu event
signal_NodeContextMenuEvent = QtCore.Signal(signalObject, signalObject) # node context menu event, node name
signal_AttrCreated = QtCore.Signal(signalObject, signalObject)
signal_AttrDeleted = QtCore.Signal(signalObject, signalObject)
signal_AttrEdited = QtCore.Signal(signalObject, signalObject, signalObject)
signal_PlugConnected = QtCore.Signal(signalObject, signalObject, signalObject, signalObject)
signal_PlugDisconnected = QtCore.Signal(signalObject, signalObject, signalObject, signalObject)
signal_SocketConnected = QtCore.Signal(signalObject, signalObject, signalObject, signalObject)
signal_SocketDisconnected = QtCore.Signal(signalObject, signalObject, signalObject, signalObject)
signal_GraphSaved = QtCore.Signal()
signal_GraphLoaded = QtCore.Signal()
signal_GraphCleared = QtCore.Signal()
signal_GraphEvaluated = QtCore.Signal()
signal_KeyPressed = QtCore.Signal(signalObject)
signal_Dropped = QtCore.Signal()
signal_dragEvent = QtCore.Signal(signalObject, signalObject) # dragDropEvent, nodzInst
signal_dragMoveEvent = QtCore.Signal(signalObject, signalObject) # dragDropEvent, nodzInst
signal_dropEvent = QtCore.Signal(signalObject, signalObject) # dragDropEvent, nodzInst
def __init__(self, parent, configPath=defaultConfigPath):
"""
Initialize the graphics view.
"""
super(Nodz, self).__init__(parent)
# Load nodz configuration.
self.config = None
self.loadConfig(configPath)
# General data.
self.gridVisToggle = True
self.gridSnapToggle = False
self._nodeSnap = False
self.selectedNodes = list()
# Connections data.
self.drawingConnection = False
self.currentHoveredNodeForConnection = None
self.currentHoveredNodeForDrop = None
self.currentHoveredAttribute = None
self.currentHoveredLink = None
self.sourceSlot = None
self.allowLoop = True
self.editEnabled = True
# Display options.
self.currentState = 'DEFAULT'
self.pressedKeys = list()
# Node creation helper
self.nodeCreationPopup = None
self.nodeCreationPopupKeyEvent = None
# drag n drop data to set when event called
self.dragAccept = False
self.dragMoveAccept = False
self.dropAccept = False
self.cutTool = None
self.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform | QtGui.QPainter.HighQualityAntialiasing)
def setEnableDrop(self, enabled):
self.setAcceptDrops(enabled and self.editEnabled)
# self.setDropIndicatorShown(enabled)
def dragEnterEvent(self, e):
if (self.editEnabled):
self.signal_dragEvent.emit(e, self)
if self.dragAccept:
e.accept()
else:
e.ignore()
else:
e.ignore()
def dragMoveEvent(self, e):
if (self.editEnabled):
self.signal_dragMoveEvent.emit(e, self)
if self.dragMoveAccept:
e.accept()
else:
e.ignore()
else:
e.ignore()
def dropEvent(self, e):
if (self.editEnabled):
self.signal_dropEvent.emit(e, self)
if self.dropAccept:
e.accept()
else:
e.ignore()
else:
e.ignore()
def event(self, event):
if (self.editEnabled and event.type() == QtCore.QEvent.KeyPress): # bypass QWidget behaviors which is to checks for Tab and Shift+Tab and tries to move the focus appropriately
self.keyPressEvent(event)
return True
return super(Nodz, self).event(event)
def wheelEvent(self, event):
"""
Zoom in the view with the mouse wheel.
"""
self.currentState = 'ZOOM_VIEW'
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
inFactor = 1.15
outFactor = old_div(1, inFactor)
delta = int(0)
if (hasattr(event, 'angleDelta') and callable(getattr(event, 'angleDelta'))):
delta = event.angleDelta().y()
else:
delta = event.delta()
if delta > 0:
zoomFactor = inFactor
self.scale(zoomFactor, zoomFactor)
elif delta < 0:
zoomFactor = outFactor
self.scale(zoomFactor, zoomFactor)
# if delta is 0 we probably have alt key active or things like that
self.currentState = 'DEFAULT'
def contextMenuEvent(self, event):
if (event.modifiers() & QtCore.Qt.AltModifier) or (event.modifiers() & QtCore.Qt.ControlModifier) or (not self.editEnabled):
return
p=event.pos()
item=self.itemAt(p.x(),p.y())
if item is not None:
item.contextMenuEvent(event)
return
self.signal_ViewContextMenuEvent.emit(event)
def mouseDoubleClickEvent(self, event):
"""
Emit a signal.
"""
super(Nodz, self).mouseDoubleClickEvent(event)
self.signal_SceneDoubleClicked.emit()
def mousePressEvent(self, event):
"""
Initialize tablet zoom, drag canvas and the selection.
"""
# Tablet zoom
if (event.button() == QtCore.Qt.RightButton and
(event.modifiers() & QtCore.Qt.AltModifier)):
self.currentState = 'ZOOM_VIEW'
self.initMousePos = event.pos()
self.zoomInitialPos = event.pos()
self.initMouse = QtGui.QCursor.pos()
self.setInteractive(False)
# Drag view
elif (event.button() == QtCore.Qt.MiddleButton and
(event.modifiers() & QtCore.Qt.AltModifier)):
self.currentState = 'DRAG_VIEW'
self.prevPos = event.pos()
self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)
self.setCursor(QtCore.Qt.ClosedHandCursor)
self.setInteractive(False)
# Rubber band selection
elif (event.button() == QtCore.Qt.LeftButton and
(event.modifiers() == QtCore.Qt.NoModifier) and
self.scene().itemAt(self.mapToScene(event.pos()), QtGui.QTransform()) is None):
self.currentState = 'SELECTION'
self._initRubberband(event.pos())
self.setInteractive(False)
# Drag Item
elif (self.editEnabled and
event.button() == QtCore.Qt.LeftButton and
(event.modifiers() == QtCore.Qt.NoModifier) and
isinstance(self.scene().itemAt(self.mapToScene(event.pos()), QtGui.QTransform()), NodeItem)):
self.currentState = 'DRAG_ITEM'
self.setInteractive(True)
# Add selection
elif (event.button() == QtCore.Qt.LeftButton and
(event.modifiers() & QtCore.Qt.ShiftModifier) and
(event.modifiers() & QtCore.Qt.ControlModifier)):
self.currentState = 'ADD_SELECTION'
self._initRubberband(event.pos())
self.setInteractive(False)
# Subtract selection
elif (event.button() == QtCore.Qt.LeftButton and
(event.modifiers() & QtCore.Qt.ControlModifier)):
self.currentState = 'SUBTRACT_SELECTION'
self._initRubberband(event.pos())
self.setInteractive(False)
# Toggle selection
elif (event.button() == QtCore.Qt.LeftButton and
(event.modifiers() & QtCore.Qt.ShiftModifier)):
self.currentState = 'TOGGLE_SELECTION'
self._initRubberband(event.pos())
self.setInteractive(False)
# Cut tool Golaem
elif (self.editEnabled and
event.button() == QtCore.Qt.LeftButton and
(event.modifiers() & QtCore.Qt.AltModifier) and
self.scene().itemAt(self.mapToScene(event.pos()), QtGui.QTransform()) is None):
self.currentState = 'CUT_LINK'
self._initCutTool(event.pos())
self.setCursor(QtCore.Qt.CrossCursor)
self.setInteractive(True)
else:
self.currentState = 'DEFAULT'
super(Nodz, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
"""
Update tablet zoom, canvas dragging and selection.
"""
# Zoom.
if self.currentState == 'ZOOM_VIEW':
offset = self.zoomInitialPos.x() - event.pos().x()
if offset > self.previousMouseOffset:
self.previousMouseOffset = offset
self.zoomDirection = -1
self.zoomIncr -= 1
elif offset == self.previousMouseOffset:
self.previousMouseOffset = offset
if self.zoomDirection == -1:
self.zoomDirection = -1
else:
self.zoomDirection = 1
else:
self.previousMouseOffset = offset
self.zoomDirection = 1
self.zoomIncr += 1
if self.zoomDirection == 1:
zoomFactor = 1.03
else:
zoomFactor = 1 / 1.03
# Perform zoom and re-center on initial click position.
pBefore = self.mapToScene(self.initMousePos)
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorViewCenter)
self.scale(zoomFactor, zoomFactor)
pAfter = self.mapToScene(self.initMousePos)
diff = pAfter - pBefore
self.setTransformationAnchor(QtWidgets.QGraphicsView.NoAnchor)
self.translate(diff.x(), diff.y())
# Drag canvas.
elif self.currentState == 'DRAG_VIEW':
offset = self.prevPos - event.pos()
self.prevPos = event.pos()
self.verticalScrollBar().setValue(self.verticalScrollBar().value() + offset.y())
self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() + offset.x())
# cutTool Golaem
elif self.currentState == 'CUT_LINK':
scenePos = self.mapToScene(event.pos())
deltaLine = scenePos - self.cutToolStartScenePos
self.cutTool.setLine(self.cutToolStartScenePos.x(), self.cutToolStartScenePos.y(), self.cutToolStartScenePos.x() + deltaLine.x(), self.cutToolStartScenePos.y() + deltaLine.y())
# RuberBand selection.
elif (self.currentState == 'SELECTION' or
self.currentState == 'ADD_SELECTION' or
self.currentState == 'SUBTRACT_SELECTION' or
self.currentState == 'TOGGLE_SELECTION'):
self.rubberband.setGeometry(QtCore.QRect(self.origin, event.pos()).normalized())
super(Nodz, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
"""
Apply tablet zoom, dragging and selection.
"""
self.setDragMode(QtWidgets.QGraphicsView.NoDrag)
# Zoom the View.
if self.currentState == '.ZOOM_VIEW':
self.offset = 0
self.zoomDirection = 0
self.zoomIncr = 0
self.setInteractive(True)
# Drag View.
elif self.currentState == 'DRAG_VIEW':
self.setCursor(QtCore.Qt.ArrowCursor)
self.setInteractive(True)
# Selection.
elif self.currentState == 'SELECTION':
self.rubberband.setGeometry(QtCore.QRect(self.origin,
event.pos()).normalized())
painterPath = self._releaseRubberband()
self.setInteractive(True)
self.scene().setSelectionArea(painterPath)
# Add Selection.
elif self.currentState == 'ADD_SELECTION':
self.rubberband.setGeometry(QtCore.QRect(self.origin,
event.pos()).normalized())
painterPath = self._releaseRubberband()
self.setInteractive(True)
for item in self.scene().items(painterPath):
item.setSelected(True)
# Subtract Selection.
elif self.currentState == 'SUBTRACT_SELECTION':
self.rubberband.setGeometry(QtCore.QRect(self.origin,
event.pos()).normalized())
painterPath = self._releaseRubberband()
self.setInteractive(True)
for item in self.scene().items(painterPath):
item.setSelected(False)
# Toggle Selection
elif self.currentState == 'TOGGLE_SELECTION':
self.rubberband.setGeometry(QtCore.QRect(self.origin,
event.pos()).normalized())
painterPath = self._releaseRubberband()
self.setInteractive(True)
for item in self.scene().items(painterPath):
if item.isSelected():
item.setSelected(False)
else:
item.setSelected(True)
# Cut tool Golaem
elif self.currentState == 'CUT_LINK':
scenePos = self.mapToScene(event.pos())
deltaLine = scenePos - self.cutToolStartScenePos
self.cutTool.setLine(self.cutToolStartScenePos.x(), self.cutToolStartScenePos.y(), self.cutToolStartScenePos.x() + deltaLine.x(), self.cutToolStartScenePos.y() + deltaLine.y())
painterPath = self._releaseCutTool()
removedConnections = list()
addedConnections = list()
self.setInteractive(True)
for item in self.scene().items(painterPath):
if (isinstance(item, ConnectionItem)):
removedConnections.append(ConnectionInfo(item))
item._remove()
self.setCursor(QtCore.Qt.ArrowCursor)
if len(removedConnections) > 0:
self.signal_UndoRedoConnectNodes.emit(self, removedConnections, addedConnections)
self.currentState = 'DEFAULT'
super(Nodz, self).mouseReleaseEvent(event)
if(self.editEnabled and event.button() == QtCore.Qt.RightButton and not event.isAccepted()):
self.signal_ViewRightClicked.emit()
def keyPressEvent(self, event):
"""
Save pressed key and apply shortcuts.
Shortcuts are:
DEL - Delete the selected nodes
F - Focus view on the selection
"""
if event.key() not in self.pressedKeys:
self.pressedKeys.append(event.key())
if (self.editEnabled):
if event.key() in (QtCore.Qt.Key_Delete, QtCore.Qt.Key_Backspace):
self._deleteSelectedNodes()
if event.key() == self.nodeCreationPopupKeyEvent:
self.nodeCreationPopup.popup()
if event.key() == QtCore.Qt.Key_Escape:
self.nodeCreationPopup.popdown()
if event.key() == QtCore.Qt.Key_F:
self._focus()
if event.key() == QtCore.Qt.Key_A:
itemsArea = self.scene().itemsBoundingRect()
self.fitInView(itemsArea, QtCore.Qt.KeepAspectRatio)
if event.key() == QtCore.Qt.Key_S:
self._nodeSnap = True
# Emit signal.
self.signal_KeyPressed.emit(event.key())
def keyReleaseEvent(self, event):
"""
Clear the key from the pressed key list.
"""
if event.key() == QtCore.Qt.Key_S:
self._nodeSnap = False
if event.key() in self.pressedKeys:
self.pressedKeys.remove(event.key())
def _initRubberband(self, position):
"""
Initialize the rubber band at the given position.
"""
self.rubberBandStart = position
self.origin = position
self.rubberband.setGeometry(QtCore.QRect(self.origin, QtCore.QSize()))
self.rubberband.show()
def _releaseRubberband(self):
"""
Hide the rubber band and return the path.
"""
painterPath = QtGui.QPainterPath()
rect = self.mapToScene(self.rubberband.geometry())
painterPath.addPolygon(rect)
self.rubberband.hide()
return painterPath
def _initCutTool(self, position):
"""
Initialize the cut tool at the given position.
"""
if (self.cutTool is None):
self.cutTool = QtWidgets.QGraphicsLineItem()
self.cutTool.setZValue(65535)
pen = QtGui.QPen(QtCore.Qt.red, 2, QtCore.Qt.DashLine)
self.cutTool.setPen(pen)
self.cutTool.hide()
self.scene().addItem(self.cutTool)
self.cutToolStartScenePos = self.mapToScene(position)
self.cutTool.setPos(0,0)
self.cutTool.setLine(self.cutToolStartScenePos.x(), self.cutToolStartScenePos.y(), self.cutToolStartScenePos.x(), self.cutToolStartScenePos.y())
self.cutTool.show()
def _releaseCutTool(self):
"""
Hide the cut tool
"""
painterPath = self.cutTool.shape()
self.cutTool.hide()
return painterPath
def _focus(self):
"""
Center on selected nodes or all of them if no active selection.
"""
if self.scene().selectedItems():
itemsArea = self._getSelectionBoundingbox()
self.fitInView(itemsArea, QtCore.Qt.KeepAspectRatio)
else:
itemsArea = self.scene().itemsBoundingRect()
self.fitInView(itemsArea, QtCore.Qt.KeepAspectRatio)
def _getSelectionBoundingbox(self):
"""
Return the bounding box of the selection.
"""
bbx_min = None
bbx_max = None
bby_min = None
bby_max = None
bbw = 0
bbh = 0
for item in self.scene().selectedItems():
pos = item.scenePos()
x = pos.x()
y = pos.y()
w = x + item.boundingRect().width()
h = y + item.boundingRect().height()
# bbx min
if bbx_min is None:
bbx_min = x
elif x < bbx_min:
bbx_min = x
# end if
# bbx max
if bbx_max is None:
bbx_max = w
elif w > bbx_max:
bbx_max = w
# end if
# bby min
if bby_min is None:
bby_min = y
elif y < bby_min:
bby_min = y
# end if
# bby max
if bby_max is None:
bby_max = h
elif h > bby_max:
bby_max = h
# end if
# end if
bbw = bbx_max - bbx_min
bbh = bby_max - bby_min
return QtCore.QRectF(QtCore.QRect(bbx_min, bby_min, bbw, bbh))
def _resetScale(self):
"""
Resets the scale of the graphics view
"""
originalTransform = self.transform()
self.resetTransform()
self.translate(originalTransform.dx(), originalTransform.dy())
def _deleteSelectedNodes(self):
"""
Delete selected nodes.
"""
# self.signal_UndoRedoPreDeleteSelectedNodes.emit()
removedConnections = list()
deletedNodesUserData = list()
# iterate on nodes first, will delete single connections after getting back selected items
selected_nodes = list()
if len(self.scene().selectedItems()) == 0:
return
for node in self.scene().selectedItems():
if type(node) is NodeItem:
#NodeItem
selected_nodes.append(node.name)
nodzInst = self.scene().views()[0]
nodzInst.signal_StartCompoundInteraction.emit(nodzInst)
if len(selected_nodes) > 0:
self.signal_NodePreDeleted.emit(selected_nodes)
for node in self.scene().selectedItems():
if type(node) is NodeItem:
#NodeItem
if node.scene() is not None: # else already deleted by a previous node
# stack all sockets connections.
for socket in list(node.sockets.values()):
for iCon in range(0, len(socket.connections)):
removedConnections.append(ConnectionInfo(socket.connections[iCon]))
# stack all plugs connections.
for plug in list(node.plugs.values()):
for iCon in range(0, len(plug.connections)):
removedConnections.append(ConnectionInfo(plug.connections[iCon]))
deletedNodesUserData.append(copy.deepcopy(node.userData))
node._remove()
# scene should be refreshed with deleted items absent of selection now, just process remaining single connectionItems
for node in self.scene().selectedItems():
if type(node) is ConnectionItem:
#connectionItem
removedConnections.append(ConnectionInfo(node))
node._remove()
if len(removedConnections)>0 :
addedConnections = list()
self.signal_UndoRedoConnectNodes.emit(self, removedConnections, addedConnections)
nodzInst.signal_EndCompoundInteraction.emit(nodzInst, True)
# Emit signal.
if len(selected_nodes) > 0:
self.signal_NodeDeleted.emit(selected_nodes)
self.signal_UndoRedoDeleteSelectedNodes.emit(self, deletedNodesUserData)
def _returnSelection(self):
"""
Wrapper to return selected items.
"""
#self.selectedNodes
# self.signal_UndoRedoPreModifySelection.emit()
oldSelectedNodes = self.selectedNodes
self.selectedNodes = list()
if self.scene().selectedItems():
for node in self.scene().selectedItems():
if type(node) is NodeItem:
self.selectedNodes.append(node.name)
# Emit signal.
self.signal_NodeSelected.emit(self.selectedNodes)
#self.selectedNodes
if (oldSelectedNodes != self.selectedNodes):
self.signal_UndoRedoModifySelection.emit(self, oldSelectedNodes, self.selectedNodes)
##################################################################
# API
##################################################################
def loadConfig(self, filePath):
"""
Set a specific configuration for this instance of Nodz.
:type filePath: str.
:param filePath: The path to the config file that you want to
use.
"""
self.config = utils._loadConfig(filePath)
def initialize(self):
"""
Setup the view's behavior.
"""
# Setup view.
config = self.config
self.setRenderHint(QtGui.QPainter.Antialiasing, config['antialiasing'])
self.setRenderHint(QtGui.QPainter.TextAntialiasing, config['antialiasing'])
self.setRenderHint(QtGui.QPainter.HighQualityAntialiasing, config['antialiasing_boost'])
self.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, config['smooth_pixmap'])
self.setRenderHint(QtGui.QPainter.NonCosmeticDefaultPen, True)
self.setViewportUpdateMode(QtWidgets.QGraphicsView.FullViewportUpdate)
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.rubberband = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self)
# Setup scene.
scene = NodeScene(self)
sceneWidth = config['scene_width']
sceneHeight = config['scene_height']
scene.setSceneRect(0, 0, sceneWidth, sceneHeight)
self.setScene(scene)
# Connect scene node moved signal
scene.signal_NodeMoved.connect(self.signal_NodeMoved)
# Tablet zoom.
self.previousMouseOffset = 0
self.zoomDirection = 0
self.zoomIncr = 0
# Connect signals.
self.scene().selectionChanged.connect(self._returnSelection)
def initNodeCreationHelper(self, completerNodeList=[], nodeCreatorCallback=None, keyEvent=QtCore.Qt.Key_Tab):
"""
Setup the node's creation helper that is available from the tab key
"""
self.nodeCreationPopupKeyEvent = keyEvent
self.nodeCreationPopup = nodz_extra.QtPopupLineEditWidget(self.scene().views()[0])
self.nodeCreationPopup.setNodesList(completerNodeList)
if nodeCreatorCallback is not None:
self.nodeCreationPopup.nodeCreator = nodeCreatorCallback
# NODES
def createNode(self, name='default', preset='node_default', position=None, alternate=True):
"""
Create a new node with a given name, position and color.
:type name: str.
:param name: The name of the node. The name has to be unique
as it is used as a key to store the node object.
:type preset: str.
:param preset: The name of graphical preset in the config file.
:type position: QtCore.QPoint.
:param position: The position of the node once created. If None,
it will be created at the center of the scene.
:type alternate: bool.
:param alternate: The attribute color alternate state, if True,
every 2 attribute the color will be slightly
darker.
:return : The created node
"""
# print("create node {} at creaetNode pos {}".format(name, position))
# Check for name clashes
if name in list(self.scene().nodes.keys()):
print('A node with the same name already exists : {0}'.format(name))
print('Node creation aborted !')
return
else:
nodeItem = NodeItem(name=name, alternate=alternate, preset=preset,
config=self.config)
# Store node in scene.
self.scene().nodes[name] = nodeItem
if position is None:
# 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)
nodeItem.checkIsWithinSceneRect()
# Emit signal.
self.signal_NodeCreated.emit(name)
return nodeItem
def deleteNode(self, node):
"""
Delete the specified node from the view.
:type node: class.
:param node: The node instance that you want to delete.
"""
if not node in list(self.scene().nodes.values()):
print('Node object does not exist !')
print('Node deletion aborted !')
return
if node in list(self.scene().nodes.values()):
nodeName = node.name
# Should handle UndoRedo here, but deleteNode is not used anywhere in our code
removedConnections = list()
addedConnections = list()
selected_nodes = list()
selected_nodes.append(node)
# stack all sockets connections.
for socket in list(node.sockets.values()):
if len(socket.connections)>0:
for socketConnection in socket.connections:
removedConnections.append(ConnectionInfo(socketConnection))
# stack all plugs connections.
for plug in list(node.plugs.values()):
if len(plug.connections)>0:
for plugConnection in plug.connections:
removedConnections.append(ConnectionInfo(plugConnection))
self.signal_NodePreDeleted.emit([nodeName])
node._remove()
# Emit signal.
self.signal_NodeDeleted.emit([nodeName])
self.signal_UndoRedoConnectNodes.emit(self, removedConnections, addedConnections)
self.signal_UndoRedoDeleteSelectedNodes.emit(self, selected_nodes)
def editNode(self, node, newName=None):
"""
Rename an existing node.
:type node: class.
:param node: The node instance that you want to delete.
:type newName: str.
:param newName: The new name for the given node.
"""
if not node in list(self.scene().nodes.values()):
print('Node object does not exist !')
print('Node edition aborted !')
return
oldName = node.name
if newName is not None:
# Check for name clashes
if newName in list(self.scene().nodes.keys()):
print('A node with the same name already exists : {0}'.format(newName))
print('Node edition aborted !')
return
else:
#oldName = node.name
node.name = newName
# Replace node data.
self.scene().nodes[newName] = self.scene().nodes[oldName]
self.scene().nodes.pop(oldName)
# Store new node name in the connections
if node.sockets:
for socket in list(node.sockets.values()):
for connection in socket.connections:
connection.socketNode = newName
if node.plugs:
for plug in list(node.plugs.values()):
for connection in plug.connections:
connection.plugNode = newName
node.update()
# Emit signal.
self.signal_NodeEdited.emit(oldName, newName)
# editNode ot used in golaem, else needs an event
# self.signal_UndoRedoEditNodeName.emit(self, oldName, newName)
# ATTRS
def createAttribute(self, node, name='default', index=-1, preset='attr_default', plug=True, socket=True, dataType=None, plugMaxConnections=-1, socketMaxConnections=1):
"""
Create a new attribute with a given name.
:type node: class.
:param node: The node instance that you want to delete.
:type name: str.
:param name: The name of the attribute. The name has to be
unique as it is used as a key to store the node
object.
:type index: int.
:param index: The index of the attribute in the node.
:type preset: str.
:param preset: The name of graphical preset in the config file.
:type plug: bool.
:param plug: Whether or not this attribute can emit connections.
:type socket: bool.
:param socket: Whether or not this attribute can receive
connections.
:type dataType: type.
:param dataType: Type of the data represented by this attribute
in order to highlight attributes of the same
type while performing a connection.
:type plugMaxConnections: int.
:param plugMaxConnections: The maximum connections that the plug can have (-1 for infinite).
:type socketMaxConnections: int.
:param socketMaxConnections: The maximum connections that the socket can have (-1 for infinite).
"""
if not node in list(self.scene().nodes.values()):
print('Node object does not exist !')
print('Attribute creation aborted !')
return
if name in node.attrs:
print('An attribute with the same name already exists : {0}'.format(name))
print('Attribute creation aborted !')
return
node._createAttribute(name=name, index=index, preset=preset, plug=plug, socket=socket, dataType=dataType, plugMaxConnections=plugMaxConnections, socketMaxConnections=socketMaxConnections)
# Emit signal.
self.signal_AttrCreated.emit(node.name, index)
def deleteAttribute(self, node, index):
"""
Delete the specified attribute.
:type node: class.
:param node: The node instance that you want to delete.
:type index: int.
:param index: The index of the attribute in the node.
"""
if not node in list(self.scene().nodes.values()):
print('Node object does not exist !')
print('Attribute deletion aborted !')
return
node._deleteAttribute(index)
# Emit signal.
self.signal_AttrDeleted.emit(node.name, index)
def editAttribute(self, node, index, newName=None, newIndex=None):
"""
Edit the specified attribute.
:type node: class.
:param node: The node instance that you want to delete.
:type index: int.
:param index: The index of the attribute in the node.
:type newName: str.
:param newName: The new name for the given attribute.