-
Notifications
You must be signed in to change notification settings - Fork 1
/
ida_object_viewer.py
2730 lines (2105 loc) · 85.6 KB
/
ida_object_viewer.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 PyQt5 import QtGui, QtCore, QtWidgets
import struct
import idaapi
import ida_kernwin
import idc
import idautils
import re
nodz = None
max_depth = 2 #TEMP
#TODO hook debugger activate event?
dbg_active = False
"""
struct struc_1 -> struc_1
struc_1 -> struc_1
"""
pattern = '^[ ]*(struct[ ]+)?'
pat = re.compile(pattern)
bits = 0
endian = 'little'
############################################################################################################################
############################################## nodz_util.py ############################################################
############################################################################################################################
def convertDataToColor(data=None, alternate=False, av=20):
"""
Convert a list of 3 (rgb) or 4(rgba) values from the configuration
file into a QColor.
:param data: Input color.
:type data: List.
:param alternate: Whether or not this is an alternate color.
:type alternate: Bool.
:param av: Alternate value.
:type av: Int.
"""
# rgb
if len(data) == 3:
color = QtGui.QColor(data[0], data[1], data[2])
if alternate:
mult = generateAlternateColorMultiplier(color, av)
color = QtGui.QColor(data[0]-(av*mult), data[1]-(av*mult), data[2]-(av*mult))
return color
# rgba
elif len(data) == 4:
color = QtGui.QColor(data[0], data[1], data[2], data[3])
if alternate:
mult = generateAlternateColorMultiplier(color, av)
color = QtGui.QColor(data[0]-(av*mult), data[1]-(av*mult), data[2]-(av*mult), data[3])
return color
# wrong
else:
print 'Color from configuration is not recognized : ', data
print 'Can only be [R, G, B] or [R, G, B, A]'
print 'Using default color !'
color = QtGui.QColor(120, 120, 120)
if alternate:
color = QtGui.QColor(120-av, 120-av, 120-av)
return color
def generateAlternateColorMultiplier(color, av):
"""
Generate a multiplier based on the input color lighness to increase
the alternate value for dark color or reduce it for bright colors.
:param color: Input color.
:type color: QColor.
:param av: Alternate value.
:type av: Int.
"""
lightness = color.lightness()
mult = float(lightness)/255
return mult
def createPointerBoundingBox(pointerPos, bbSize):
"""
generate a bounding box around the pointer.
:param pointerPos: Pointer position.
:type pointerPos: QPoint.
:param bbSize: Width and Height of the bounding box.
:type bbSize: Int.
"""
# Create pointer's bounding box.
point = pointerPos
mbbPos = point
point.setX(point.x() - bbSize / 2)
point.setY(point.y() - bbSize / 2)
size = QtCore.QSize(bbSize, bbSize)
bb = QtCore.QRect(mbbPos, size)
bb = QtCore.QRectF(bb)
return bb
def swapListIndices(inputList, oldIndex, newIndex):
"""
Simply swap 2 indices in a the specified list.
:param inputList: List that contains the elements to swap.
:type inputList: List.
:param oldIndex: Index of the element to move.
:type oldIndex: Int.
:param newIndex: Destination index of the element.
:type newIndex: Int.
"""
if oldIndex == -1:
oldIndex = len(inputList)-1
if newIndex == -1:
newIndex = len(inputList)
value = inputList[oldIndex]
inputList.pop(oldIndex)
inputList.insert(newIndex, value)
############################################################################################################################
############################################################################################################################
############################################################################################################################
############################################################################################################################
############################################## nodz_main.py ############################################################
############################################################################################################################
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.
"""
signal_NodeCreated = QtCore.pyqtSignal(object)
signal_NodeDeleted = QtCore.pyqtSignal(object)
signal_NodeEdited = QtCore.pyqtSignal(object, object)
signal_NodeSelected = QtCore.pyqtSignal(object)
signal_NodeMoved = QtCore.pyqtSignal(str, object)
signal_AttrCreated = QtCore.pyqtSignal(object, object)
signal_AttrDeleted = QtCore.pyqtSignal(object, object)
signal_AttrEdited = QtCore.pyqtSignal(object, object, object)
signal_PlugConnected = QtCore.pyqtSignal(object, object, object, object)
signal_PlugDisconnected = QtCore.pyqtSignal(object, object, object, object)
signal_SocketConnected = QtCore.pyqtSignal(object, object, object, object)
signal_SocketDisconnected = QtCore.pyqtSignal(object, object, object, object)
signal_GraphSaved = QtCore.pyqtSignal()
signal_GraphLoaded = QtCore.pyqtSignal()
signal_GraphCleared = QtCore.pyqtSignal()
signal_GraphEvaluated = QtCore.pyqtSignal()
signal_KeyPressed = QtCore.pyqtSignal(object)
signal_Dropped = QtCore.pyqtSignal()
def __init__(self, parent, config_s):
"""
Initialize the graphics view.
"""
super(Nodz, self).__init__(parent)
# Load nodz configuration.
self.loadConfig(config_s)
# General data.
self.gridVisToggle = True
self.gridSnapToggle = False
self._nodeSnap = False
self.selectedNodes = None
# Connections data.
self.drawingConnection = False
self.currentHoveredNode = None
self.sourceSlot = None
# Display options.
self.currentState = 'DEFAULT'
self.pressedKeys = list()
self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)
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 = 1 / inFactor
if event.delta() > 0:
zoomFactor = inFactor
else:
zoomFactor = outFactor
self.scale(zoomFactor, zoomFactor)
self.currentState = 'DEFAULT'
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.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 = 'DRAG_WINDOW'
#self._initRubberband(event.pos())
self.setInteractive(False)
# Drag Item
elif (event.button() == QtCore.Qt.LeftButton and
event.modifiers() == QtCore.Qt.NoModifier and
self.scene().itemAt(self.mapToScene(event.pos()), QtGui.QTransform()) is not None):
self.currentState = 'DRAG_ITEM'
self.setInteractive(True)
# Add selection
elif (event.button() == QtCore.Qt.LeftButton and
QtCore.Qt.Key_Shift in self.pressedKeys and
QtCore.Qt.Key_Control in self.pressedKeys):
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)
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())
# 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.
"""
# 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)
elif self.currentState == 'DRAG_WINDOW':
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)
self.currentState = 'DEFAULT'
super(Nodz, self).mouseReleaseEvent(event)
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 event.key() == QtCore.Qt.Key_Delete:
self._deleteSelectedNodes()
if event.key() == QtCore.Qt.Key_F:
self._focus()
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 _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 _deleteSelectedNodes(self):
"""
Delete selected nodes.
"""
selected_nodes = list()
for node in self.scene().selectedItems():
selected_nodes.append(node.name)
node._remove()
# Emit signal.
self.signal_NodeDeleted.emit(selected_nodes)
def _returnSelection(self):
"""
Wrapper to return selected items.
"""
selected_nodes = list()
if self.scene().selectedItems():
for node in self.scene().selectedItems():
selected_nodes.append(node.name)
# Emit signal.
self.signal_NodeSelected.emit(selected_nodes)
##################################################################
# API
##################################################################
def loadConfig(self, d):
"""
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 = d
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)
# 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
"""
# Check for name clashes
if name in 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 not position:
# Get the center of the view.
p = self.viewport().rect().topLeft()
p.setX(p.x() + 50)
p.setY(p.y() + 50)
position = self.mapToScene(p)
# Set node position.
self.scene().addItem(nodeItem)
#nodeItem.setPos(position - nodeItem.nodeCenter)
nodeItem.setPos(position)
# 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 self.scene().nodes.values():
print 'Node object does not exist !'
print 'Node deletion aborted !'
return
if node in self.scene().nodes.values():
nodeName = node.name
node._remove()
# Emit signal.
self.signal_NodeDeleted.emit([nodeName])
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 self.scene().nodes.values():
print 'Node object does not exist !'
print 'Node edition aborted !'
return
oldName = node.name
if newName != None:
# Check for name clashes
if newName in self.scene().nodes.keys():
print 'A node with the same name already exists : {0}'.format(newName)
print 'Node edition aborted !'
return
else:
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 node.sockets.values():
for connection in socket.connections:
connection.socketNode = newName
if node.plugs:
for plug in node.plugs.values():
for connection in plug.connections:
connection.plugNode = newName
node.update()
# Emit signal.
self.signal_NodeEdited.emit(oldName, newName)
# ATTRS
def createAttribute(self, node, name='default', index=-1, preset='attr_default', plug=True, socket=True, dataType=None):
"""
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.
"""
if not node in 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)
# 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 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.
:type newIndex: int.
:param newIndex: The index for the given attribute.
"""
if not node in self.scene().nodes.values():
print 'Node object does not exist !'
print 'Attribute creation aborted !'
return
if newName != None:
if newName in node.attrs:
print 'An attribute with the same name already exists : {0}'.format(newName)
print 'Attribute edition aborted !'
return
else:
oldName = node.attrs[index]
# Rename in the slot item(s).
if node.attrsData[oldName]['plug']:
node.plugs[oldName].attribute = newName
node.plugs[newName] = node.plugs[oldName]
node.plugs.pop(oldName)
for connection in node.plugs[newName].connections:
connection.plugAttr = newName
if node.attrsData[oldName]['socket']:
node.sockets[oldName].attribute = newName
node.sockets[newName] = node.sockets[oldName]
node.sockets.pop(oldName)
for connection in node.sockets[newName].connections:
connection.socketAttr = newName
# Replace attribute data.
node.attrsData[oldName]['name'] = newName
node.attrsData[newName] = node.attrsData[oldName]
node.attrsData.pop(oldName)
node.attrs[index] = newName
if isinstance(newIndex, int):
attrName = node.attrs[index]
swapListIndices(node.attrs, index, newIndex)
# Refresh connections.
for plug in node.plugs.values():
plug.update()
if plug.connections:
for connection in plug.connections:
if isinstance(connection.source, PlugItem):
connection.source = plug
connection.source_point = plug.center()
else:
connection.target = plug
connection.target_point = plug.center()
if newName:
connection.plugAttr = newName
connection.updatePath()
for socket in node.sockets.values():
socket.update()
if socket.connections:
for connection in socket.connections:
if isinstance(connection.source, SocketItem):
connection.source = socket
connection.source_point = socket.center()
else:
connection.target = socket
connection.target_point = socket.center()
if newName:
connection.socketAttr = newName
connection.updatePath()
self.scene().update()
node.update()
# Emit signal.
if newIndex:
self.signal_AttrEdited.emit(node.name, index, newIndex)
else:
self.signal_AttrEdited.emit(node.name, index, index)
def createConnection(self, sourceNode, sourceAttr, targetNode, targetAttr):
"""
Create a manual connection.
:type sourceNode: str.
:param sourceNode: Node that emits the connection.
:type sourceAttr: str.
:param sourceAttr: Attribute that emits the connection.
:type targetNode: str.
:param targetNode: Node that receives the connection.
:type targetAttr: str.
:param targetAttr: Attribute that receives the connection.
"""
plug = self.scene().nodes[sourceNode].plugs[sourceAttr]
socket = self.scene().nodes[targetNode].sockets[targetAttr]
connection = ConnectionItem(plug.center(), socket.center(), plug, socket)
connection.plugNode = plug.parentItem().name
connection.plugAttr = plug.attribute
connection.socketNode = socket.parentItem().name
connection.socketAttr = socket.attribute
plug.connect(socket, connection)
socket.connect(plug, connection)
connection.updatePath()
self.scene().addItem(connection)
return connection
def evaluateGraph(self):
"""
Create a list of connection tuples.
[("sourceNode.attribute", "TargetNode.attribute"), ...]
"""
scene = self.scene()
data = list()
for item in scene.items():
if isinstance(item, ConnectionItem):
connection = item
data.append(connection._outputConnectionData())
# Emit Signal
self.signal_GraphEvaluated.emit()
return data
def clearGraph(self):
"""
Clear the graph.
"""
self.scene().clear()
self.scene().nodes = dict()
# Emit signal.
self.signal_GraphCleared.emit()
##################################################################
# END API
##################################################################
class NodeScene(QtWidgets.QGraphicsScene):
"""
The scene displaying all the nodes.
"""
signal_NodeMoved = QtCore.pyqtSignal(str, object)
def __init__(self, parent):
"""
Initialize the class.
"""
super(NodeScene, self).__init__(parent)
# General.
self.gridSize = parent.config['grid_size']
# Nodes storage.
self.nodes = dict()
def dragEnterEvent(self, event):
"""
Make the dragging of nodes into the scene possible.
"""
event.setDropAction(QtCore.Qt.MoveAction)
event.accept()
def dragMoveEvent(self, event):