summaryrefslogtreecommitdiff
path: root/src/main/python/shapes/shapes.py
blob: d9f6b522e8d11d752d96c7f423b7de54ed51f418 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import (QEvent, QFile, QIODevice, QMimeData, QPointF, QRect,
                          QRectF, QSizeF, Qt)
from PyQt5.QtGui import (QBrush, QColor, QCursor, QDrag, QFont, QImage,
                         QPainter, QPainterPath, QPen, QTransform, QTextCursor, QPainterPathStroker)
from PyQt5.QtSvg import QGraphicsSvgItem, QSvgRenderer
from PyQt5.QtWidgets import (QGraphicsColorizeEffect, QGraphicsEllipseItem,
                             QGraphicsItem, QGraphicsPathItem,
                             QGraphicsProxyWidget, QGraphicsSceneHoverEvent,
                             QLineEdit, QMenu, QGraphicsTextItem)

from .line import Line, findIndex
from utils.app import fileImporter

# enum for all directions for line grip items
directionsEnum = [
    "top",
    "right",
    "bottom",
    "left"
]

# orientation enum for size grip items
orientationEnum = [
    Qt.Horizontal,
    Qt.Vertical
]

#For extending Lines for repositioned Rectangular Line Grips
rLGPlus = {}
f = open('./shapes/rLGPlus.txt','r')
dataRead = f.readlines()[1:]
for line in dataRead:

    if not line.__contains__(',') :
        rLGPlus[line.strip()] = []
    else:
        grips = line.strip().split(',')
        rLGPlus[list(rLGPlus.keys())[-1]].append(grips)

class ItemLabel(QGraphicsTextItem):
    """Extends PyQt5's QGraphicsPathItem to create text label for svg item
    """

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setPlainText("abc")
        # graphics setting for text label
        self.setFlags(QGraphicsItem.ItemIsMovable |
                      QGraphicsItem.ItemIsSelectable |
                      QGraphicsItem.ItemIsFocusable)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
        # set initial no text interaction
        self.setTextInteractionFlags(Qt.NoTextInteraction)
        # set initial position just below parent
        self.setPos(self.parentItem().boundingRect().bottomLeft())

    def mouseDoubleClickEvent(self, event):
        # make text editable
        self.setTextInteractionFlags(Qt.TextEditorInteraction)
        self.setFocus()  # set focus to text
        super(ItemLabel, self).mouseDoubleClickEvent(event)

    def focusOutEvent(self, event):
        super(ItemLabel, self).focusOutEvent(event)
        self.setTextInteractionFlags(Qt.NoTextInteraction)  # make text not editable and thus movable

    def __getstate__(self):
        return {
            "text": self.toPlainText(),
            "pos": (self.pos().x(), self.pos().y())
        }

    def __setstate__(self, dict):
        self.setPlainText(dict['text'])
        self.setPos(*dict['pos'])


class GripItem(QGraphicsPathItem):
    """
    Extends QGraphicsPathItem to create the structure of the Grabbable points for resizing shapes and connecting lines.
    Takes two parameters, reference item (On which the grip items are to appear) and the path of the item
    """

    def __init__(self, annotation_item, path, parent=None):
        """
        Extends PyQt5's QGraphicsPathItem to create the general structure of the Grabbable points for resizing shapes.
        """
        QGraphicsPathItem.__init__(self, parent)
        self.m_annotation_item = annotation_item
        # set path of item
        self.setPath(path)
        self.setAcceptHoverEvents(True)
        self.setCursor(QCursor(Qt.PointingHandCursor))

    def mouseReleaseEvent(self, event):
        """
        Automatically deselects grip item on mouse release
        """
        self.setSelected(False)
        super(GripItem, self).mouseReleaseEvent(event)


class SizeGripItem(QGraphicsPathItem):
    """
    Extends grip items for vertical and horizontal directions, with hover events and directional changes
    """

    def __init__(self, index, direction=Qt.Horizontal, parent=None):
        super(SizeGripItem, self).__init__(parent=parent)
        # set graphical setting
        #self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
        self.setAcceptHoverEvents(True)
        self.setPen(QPen(Qt.NoPen))
        self.setZValue(2)
        # property direction
        self._direction = (orientationEnum.index(direction) + self.parentItem().rotation) % 4
        self._m_index = index

    @property
    def m_index(self):
        return (self._m_index + self.parentItem().rotation) % 4
    
    @property
    def direction(self):
        """
        property that returns the current intended resize direction of the grip item object
        """
        if self.parentItem().rotation % 2:
            return orientationEnum[(self._direction + 1)%2]
        else:
            return orientationEnum[self._direction]

    def updatePath(self,m_index):
        """updates path of size grip item
        """
        bx = self.parentItem().boundingRect().x()
        by = self.parentItem().boundingRect().y()
        height = self.parentItem().boundingRect().height()
        width = self.parentItem().boundingRect().width()

        path = QPainterPath()
        if(m_index == 0):#top
            by = by+10
            path.moveTo(bx+(width/2)-10,by)
            path.lineTo(bx+(width/2)+10,by)
            path.lineTo(bx+(width/2),by-20)
            path.lineTo(bx+(width/2)-10,by)
        if(m_index == 1):#left
            bx = bx+10
            path.moveTo(bx,by+(height/2)-10)
            path.lineTo(bx,by+(height/2)+10)
            path.lineTo(bx-20,by+(height/2))
            path.lineTo(bx,by+(height/2)-10)
        if(m_index == 2):#bottom
            by = by-10
            path.moveTo(bx+(width/2)-10,by+height)
            path.lineTo (bx+(width/2)+10,by+height)
            path.lineTo (bx+(width/2),by+height+20)
            path.lineTo (bx+(width/2)-10,by+height)
        if(m_index == 3):#right
            bx = bx-10
            path.moveTo(bx+width,by+(height/2)-10)
            path.lineTo(bx+width,by+(height/2)+10)
            path.lineTo(bx+width+20,by+(height/2))
            path.lineTo(bx+width,by+(height/2)-10)
        self.setPath(path)

    def updatePosition(self):
        """updates position of grip items
        """
        self.updatePath(self.m_index)
        pos = self.point(self.m_index)
        self.setEnabled(False)
        self.setPos(pos)
        self.setEnabled(True)

    def point(self, index):
        """
        yields a list of positions of grip items in a node item
        """
        width = self.parentItem().boundingRect().width()
        height = self.parentItem().boundingRect().height()
        if 0 <= index < 4:
            return [
                QPointF(0, -height / 2),
                QPointF(-width / 2, 0),
                QPointF(0, height / 2),
                QPointF(width / 2, 0)
            ][index]

    def hoverEnterEvent(self, event):
        """
        Changes cursor to horizontal resize or vertical resize depending on the direction of the grip item on mouse enter
        """
        if self.direction == Qt.Horizontal:
            self.setCursor(QCursor(Qt.SizeHorCursor))
        else:
            self.setCursor(QCursor(Qt.SizeVerCursor))
        super(SizeGripItem, self).hoverEnterEvent(event)

    def hoverLeaveEvent(self, event):
        """
        reverts cursor to default on mouse leave
        """
        self.setCursor(QCursor(Qt.ArrowCursor))
        super(SizeGripItem, self).hoverLeaveEvent(event)

    def itemChange(self, change, value):
        """
        Moves position of grip item on resize
        """
        if change == QGraphicsItem.ItemPositionChange and self.isEnabled():
            p = QPointF(self.pos())
            if self.direction == Qt.Horizontal:
                p.setX(value.x())
            elif self.direction == Qt.Vertical:
                p.setY(value.y())
            # Find change in positions
            movement = p - self.pos()
            # Set transform to oppose change in transformation due to parent
            transform = QTransform()
            transform.translate(-movement.x() / 2, -movement.y() / 2)
            self.setTransform(transform, True)
            self.parentItem().resize(self.m_index, movement)
            return p
        return super(SizeGripItem, self).itemChange(change, value)

    def mouseReleaseEvent(self, event):
        super(SizeGripItem, self).mouseReleaseEvent(event)
        # Reset transform and update position
        self.resetTransform()
        self.updatePosition()
        # Make parent item move able
        self.parentItem().setFlag(QGraphicsSvgItem.ItemIsMovable, True)
        # If needed, to reset transform of parent set it's position accordingly
        # self.parentItem().setPos(self.parentItem().x() + self.parentItem().transform().dx(), self.parentItem().y() + self.parentItem().transform().dy())
        # self.parentItem().resetTransform()

    def show(self):
        # make self visible
        self.setPen(QPen(QColor(128, 128, 128,150), 2))
        super(SizeGripItem,self).show()

    def hide(self):
        # hide self by setting pen to transparent
        self.setPen(QPen(Qt.NoPen))
        self.setBrush(Qt.transparent)
        super(SizeGripItem,self).hide()


class LineGripItem(QGraphicsPathItem):
    """Extends grip items for connecting lines , with hover events and mouse events
    """
    circle = QPainterPath()
    circle.addEllipse(QRectF(-5, -5, 10, 10))

    def __init__(self, index, grip, parent=None):
        super(LineGripItem, self).__init__(parent=parent)
        self.setPath(LineGripItem.circle)
        # set it's index on item
        self.m_index = index
        # store position of self
        self.position = QPointF(grip[0], grip[1])
        # set location
        self._m_location = directionsEnum.index(grip[2])
        # set size in case of rectangle grip
        self.size = grip[3] if len(grip) == 4 else None
        # stores current line which is in process
        self.tempLine = None
        # stores lines conected to it
        self.lines = []
        # keep previous hovered item when line drawing in process
        self.previousHoveredItem = None
        # set graphical settings
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setPen(QPen(QColor("black"), -1))
        self.setAcceptHoverEvents(True)
        self.setCursor(QCursor(Qt.PointingHandCursor))

    @property
    def m_location(self):
        if self.parentItem().__class__ == Line:
            return directionsEnum[self._m_location]
        index = (self._m_location + self.parentItem().rotation)
        if index%2:
            index = (index + 2*self.parentItem().flipH)%4
        else:
            index = (index + 2*self.parentItem().flipV)%4
        return directionsEnum[index]
    
    @m_location.setter
    def m_location(self, location):
        self._m_location = directionsEnum.index(location)

    def shape(self):
        # return interactive path
        qp = QPainterPathStroker()
        qp.setWidth(8)
        # create outline of path
        path = qp.createStroke(self.path())
        return path

    def paint(self, painter, option, widget):
        # draw path with outline of interactive area(shape)
        painter.setPen(self.pen())
        painter.drawPath(self.shape()) # draw outline
        painter.setBrush(self.brush())
        # if rectangle grip
        if self.size:
            painter.save()
            pen = self.pen()
            pen.setWidth(1)
            painter.setPen(pen)
            painter.drawPath(self.path())
            painter.restore()
        else:
            painter.drawPath(self.path())

    def itemChange(self, change, value):
        """
        Moves position of grip item on resize
        """
        if change == QGraphicsItem.ItemSceneHasChanged and not self.scene():
            # on removing from scene remove all lines connected to it
            for line in self.lines:
                if line.scene():
                    line.scene().removeItem(line)
        return super(LineGripItem, self).itemChange(change, value)

    def updatePosition(self):
        width = self.parentItem().boundingRect().width() # width of parent
        height = self.parentItem().boundingRect().height() # height of parent
        # if grip item is rectangle change it's path
        if self.size:
            rect_width = rect_height = 4
            if self.m_location in ["left", "right"]:
                rect_height = (self.size * height) / 100
            else:
                rect_width = (self.size * width) / 100
            path = QPainterPath() # create path
            path.addRect(QRectF(-rect_width / 2, -rect_height / 2, rect_width, rect_height)) # add rect to path
            self.setPath(path) # set path to grip
        # position according to svg co-ordinate
        x = (self.position.x() * width) / 100
        y = (self.position.y() * height) / 100
        # change position into items coordinate
        x -= width / 2
        y -= height / 2
        y = -y
        self.setEnabled(False)
        self.setPos(QPointF(x, y)) # set pos of grip
        self.setEnabled(True)
        # update all lines connected to it
        for line in self.lines:
            line.updateLine()

    def mousePressEvent(self, mouseEvent):
        """Handle all mouse press for this item
        """
        if mouseEvent.button() != Qt.LeftButton:
            return
        # initialize a line and add on scene
        # restrict circle grip to one line
        if self.size is None and len(self.lines) < 0:
            pass
        else:
            startPoint = self.parentItem().mapToScene(self.pos()) # first point of line
            mpos = self.mapToScene(mouseEvent.pos()) # position of mouse
            gap = 0 # distance from center of grip
            if self.size and self.m_location in ["top", "bottom"]:
                gap = (startPoint.x() - mpos.x()) / self.boundingRect().width()
                startPoint.setX(mpos.x())

            elif self.size:
                gap = (startPoint.y() - mpos.y()) / self.boundingRect().height()
                startPoint.setY(mpos.y())

            endPoint = startPoint
            self.tempLine = Line(startPoint, endPoint) # create a line object
            self.tempLine.startGap = gap # set gap to line
            self.scene().addItem(self.tempLine) # add line on scene
        super().mousePressEvent(mouseEvent)

    def mouseMoveEvent(self, mouseEvent):
        """Handle all mouse move for this item
        """
        # if line get started then update it's end point
        if self.tempLine:
            endPoint = mouseEvent.scenePos() # mouse position
            self.tempLine.updateLine(endPoint=endPoint)
        # find item below cursor
        item = self.scene().itemAt(mouseEvent.scenePos().x(), mouseEvent.scenePos().y(),
                                   QTransform())
        # hide grip of previous hovered item
        if self.previousHoveredItem and item != self.previousHoveredItem and \
                item not in self.previousHoveredItem.lineGripItems:
            self.previousHoveredItem.hideLineGripItem()
            #self.previousHoveredItem.hideSizeGripItem()
        super().mouseMoveEvent(mouseEvent)
        # show grip of current hoverde item
        if isinstance(item, NodeItem):
            self.previousHoveredItem = item
            item.showLineGripItem()

    def mouseReleaseEvent(self, mouseEvent):
        """Handle all mouse release for this item"""
        super().mouseReleaseEvent(mouseEvent)
        # set final position of line
        if self.tempLine:
            tag = 0
            items = self.scene().items(QPointF(mouseEvent.scenePos().x(), mouseEvent.scenePos().y()))
            for item in items:
                # end point on grip
                if type(item) == LineGripItem and item != self:
                    endPoint = item.parentItem().mapToScene(item.pos())
                    gap = 0
                    # restrict line to one grip
                    if item.size is None and len(item.lines) > 0:
                        break
                    # in case of rectangle grip
                    if item.size and item.m_location in ["top", "bottom"]:
                        mpos = self.mapToScene(mouseEvent.pos())
                        gap = (endPoint.x() - mpos.x()) / item.boundingRect().width()
                        endPoint.setX(mpos.x())
                    elif item.size:
                        mpos = self.mapToScene(mouseEvent.pos())
                        gap = (endPoint.y() - mpos.y()) / item.boundingRect().height()
                        endPoint.setY(mpos.y())

                    self.tempLine.endGap = gap
                    self.tempLine.setStartGripItem(self)
                    self.tempLine.setEndGripItem(item)
                    if self.tempLine.startGripItem.parentItem() != self.tempLine.endGripItem.parentItem():
                        # update line with end point so it sets final path
                        self.tempLine.updateLine(endPoint=endPoint)
                        #Adjusting line for repositioned retangular grips
                        if self.parentItem().__class__.__name__ in list(rLGPlus.keys()):
                                for tgrip in rLGPlus[self.parentItem().__class__.__name__]:
                                    if(float(tgrip[3]) == 0):
                                        if self.m_location == tgrip[0]:
                                            tempx,tempy = int(tgrip[1]),int(tgrip[2])
                                            self.tempLine.startPoint.setX(self.tempLine.startPoint.x()+tempx)
                                            self.tempLine.startPoint.setY(self.tempLine.startPoint.y()+tempy)
                                    else:
                                        if self.m_location == tgrip[0] and self.size == float(tgrip[3]):
                                            tempx,tempy = int(tgrip[1]),int(tgrip[2])
                                            self.tempLine.startPoint.setX(self.tempLine.startPoint.x()+tempx)
                                            self.tempLine.startPoint.setY(self.tempLine.startPoint.y()+tempy)
                        if item.parentItem().__class__.__name__ in list(rLGPlus.keys()):
                                for tgrip in rLGPlus[item.parentItem().__class__.__name__]:
                                    if(float(tgrip[3]) == 0):
                                        if item.m_location == tgrip[0]:
                                            tempx,tempy = int(tgrip[1]),int(tgrip[2])
                                            self.tempLine.endPoint.setX(self.tempLine.endPoint.x()+tempx)
                                            self.tempLine.endPoint.setY(self.tempLine.endPoint.y()+tempy)
                                    else:
                                        if item.m_location == tgrip[0] and item.size == float(tgrip[3]):
                                            tempx,tempy = int(tgrip[1]),int(tgrip[2])
                                            self.tempLine.endPoint.setX(self.tempLine.endPoint.x()+tempx)
                                            self.tempLine.endPoint.setY(self.tempLine.endPoint.y()+tempy)
                                        
                        self.lines.append(self.tempLine)
                        item.lines.append(self.tempLine)
                        tag = 1
                        break
                # end point on line
                elif type(item) == Line and item != self.tempLine:
                    self.tempLine.setStartGripItem(self)
                    endPoint = mouseEvent.scenePos()
                    self.tempLine.refLine = item
                    self.tempLine.refIndex = findIndex(item, endPoint)
                    # update line with end point so it sets final path
                    self.tempLine.updateLine(endPoint=endPoint)
                    item.midLines.append(self.tempLine) # stores temp line as mid line to other line
                    self.lines.append(self.tempLine)
                    tag = 1
                    break
            self.scene().removeItem(self.tempLine) # remove temp line from scene
            # if line end point is on grip or line
            if tag:
                self.scene().addItemPlus(self.tempLine) # add line on scene

        self.tempLine = None
        self.previousHoveredItem = None

    def show(self):
        """ shows line grip item
        """
        self.setPen(QPen(QColor(0,0,0,150), 1.5))
        self.setBrush(QColor(140,199,198,255))

    def hide(self):
        """ hides line grip item
        """
        if not self.parentItem().isSelected():
            self.setPen(QPen(Qt.transparent))
            self.setBrush(Qt.transparent)


class NodeItem(QGraphicsSvgItem):
    """
        Extends PyQt5's QGraphicsSvgItem to create the basic structure of shapes with given unit operation type
    """

    def __init__(self, unitOperationType=None, parent=None):
        QGraphicsSvgItem.__init__(self, parent)
        self.m_type = str(unitOperationType)
        self.m_renderer = QSvgRenderer(fileImporter(f'{unitOperationType}.svg'))
        self.setSharedRenderer(self.m_renderer)
        # set initial size of item
        self.width = self.m_renderer.defaultSize().width()
        self.height = self.m_renderer.defaultSize().height()
        # set graphical settings for this item
        self.setFlags(QGraphicsSvgItem.ItemIsMovable |
                      QGraphicsSvgItem.ItemIsSelectable |
                      QGraphicsSvgItem.ItemSendsGeometryChanges)
        self.setAcceptHoverEvents(True)
        self.setZValue(2)
        # items connected to this item
        self.lineGripItems = []
        self.sizeGripItems = []
        self.label = None
        self._rotation = 0
        self.flipState = [False, False]
        self.activateGrip = False
    
    @property
    def flipH(self):
        return self.flipState[0]
    
    @property
    def flipV(self):
        return self.flipState[1]
    
    def updateTransformation(self):
        # update transformation on flipstate or rotation change
        transform = QTransform()
        h = -1 if self.flipH else 1
        w = -1 if self.flipV else 1
        transform.rotate(90*self.rotation)
        transform.scale(h, w)
        self.setTransform(transform)
        self.setTransform(transform)
        for i in self.lineGripItems:
            i.setTransform(transform)
            i.updatePosition()
                
    @flipH.setter
    def flipH(self, state):
        self.flipState[0] = state
        self.updateTransformation()

    @flipV.setter
    def flipV(self, state):
        self.flipState[1] = state
        self.updateTransformation()
            
    @property
    def rotation(self):
        return self._rotation
    
    @rotation.setter
    def rotation(self, rotation):
        self._rotation = rotation % 4
        self.updateTransformation()
        
    def boundingRect(self):
        """Overrides QGraphicsSvgItem's boundingRect() virtual public function and
        returns a valid bounding
        """
        return QRectF(-self.width / 2, -self.height / 2, self.width, self.height)

    def paint(self, painter, option, widget):
        """
            Paints the contents of an item in local coordinates.
            :param painter: QPainter instance
            :param option: QStyleOptionGraphicsItem instance
            :param widget: QWidget instance
        """
        # check if render is set
        if not self.m_renderer:
            QGraphicsSvgItem.paint(self, painter, option, widget)
        else:
            self.m_renderer.render(painter, self.boundingRect())  # render svg using painter

    def resize(self, index, movement):
        """Move grip item with changing rect of node item
        """
        self.prepareGeometryChange()
        if index in [0, 1]:
            self.width -= movement.x()
            self.height -= movement.y()
        else:
            self.width += movement.x()
            self.height += movement.y()
        transform = QTransform()
        transform.translate(movement.x() / 2, movement.y() / 2)
        self.setTransform(transform, True)
        self.updateSizeGripItem([index])

    def addGripItem(self):
        """adds grip items
        """
        if self.scene():
            # add grip for resizing
            for i, (direction) in enumerate(
                    (
                            Qt.Vertical,
                            Qt.Horizontal,
                            Qt.Vertical,
                            Qt.Horizontal,
                    )
            ):
                item = SizeGripItem(i, direction, parent=self)
                self.sizeGripItems.append(item)
            # add grip items for connecting lines
            for i in range(len(self.grips)):
                grip = self.grips[i]
                item = LineGripItem(i, grip, parent=self)
                self.lineGripItems.append(item)

    def updateLineGripItem(self):
        """
        updates line grip items
        """
        for item in self.lineGripItems:
            item.updatePosition()

    def updateSizeGripItem(self, index_no_updates=None):
        """
        updates size grip items
        """
        index_no_updates = index_no_updates or []
        for i, item in enumerate(self.sizeGripItems):
            if i not in index_no_updates:
                item.updatePosition()

    def itemChange(self, change, value):
        """Overloads and extends QGraphicsSvgItem to also update grip items
        """
        newPos = value
        # check if item selected is changed
        if change == QGraphicsItem.ItemSelectedHasChanged:
            # show grips if selected
            if value is True:
                self.showLineGripItem()
                self.showSizeGripItem()
            else:
                self.hideLineGripItem()
                if not self.activateGrip:
                    self.hideSizeGripItem()
            return
        # check if transform changed
        if change == QGraphicsItem.ItemTransformHasChanged:
            self.updateLineGripItem()
            return
        # check if position is changed
        if change == QGraphicsItem.ItemPositionHasChanged:
            # update grips
            self.updateLineGripItem()
            self.updateSizeGripItem()
            
            #restrict movable area of Node Item
            
            if self.parent() is not None:
                rect = self.parent().sceneRect() 
                width = self.boundingRect().width()
                height = self.boundingRect().height()
                eWH1 = QPointF(newPos.x()+width,newPos.y()+height)
                eWH2 = QPointF(newPos.x()-width,newPos.y()-height)
                if not rect.__contains__(eWH1) or not rect.__contains__(eWH2) :
                    newPos.setX(min(rect.right()-width+40, max(newPos.x(), rect.left()+90)))
                    newPos.setY(min(rect.bottom()-height, max(newPos.y(), rect.top()+70)))
                    self.setPos(newPos)
            return super(NodeItem,self).itemChange(change, newPos)
        
        # check if item is add on scene
        if change == QGraphicsItem.ItemSceneHasChanged and self.scene():
            # add grips and update them
            self.addGripItem()
            self.updateLineGripItem()
            self.updateSizeGripItem()
            return
        return super(NodeItem, self).itemChange(change, value)

    def hoverEnterEvent(self, event):
        """defines shape highlighting on Mouse Over
        """
        self.showLineGripItem()
        super(NodeItem, self).hoverEnterEvent(event)

    def hoverLeaveEvent(self, event):
        """defines shape highlighting on Mouse Leave
        """
        self.hideLineGripItem()
        #self.hideSizeGripItem()
        super(NodeItem, self).hoverLeaveEvent(event)
    
    def mouseDoubleClickEvent(self, event):
        self.activateGrip = not self.activateGrip
        if self.activateGrip == False:
            self.hideSizeGripItem()
            self.parent().update()
        else:
            self.showSizeGripItem()
        super(NodeItem,self).mouseDoubleClickEvent(event)

    def showLineGripItem(self):
        """shows line grip items of svg item
        """
        for item in self.lineGripItems:
            item.show()

    def hideLineGripItem(self):
        """hide line grip items of svg item
        """
        for item in self.lineGripItems:
            item.hide()
    
    def showSizeGripItem(self):
        """shows size grip items of svg item
        """
        for item in self.sizeGripItems:
            item.show()

    def hideSizeGripItem(self):
        """hide size grip items of svg item
        """
        self.activateGrip = False
        for item in self.sizeGripItems:
            item.hide()

    def contextMenuEvent(self, event):
        """Pop up menu
        :return:
        """
        # create a menu and add action
        contextMenu = QMenu()
        contextMenu.addAction("Add Label", lambda : setattr(self, "label", ItemLabel(self)))
        contextMenu.addAction("Rotate right(E)", lambda : setattr(self, "rotation", self.rotation + 1))
        contextMenu.addAction("Rotate left(Q)", lambda : setattr(self, "rotation", self.rotation - 1))
        contextMenu.addAction("Flip Horizontally", lambda: setattr(self, "flipH", not self.flipH))
        contextMenu.addAction("Flip Vertically", lambda: setattr(self, "flipV", not self.flipV))
        action = contextMenu.exec_(event.screenPos())

    def __getstate__(self):
        return {
            "_classname_": self.__class__.__name__,
            "width": self.width,
            "height": self.height,
            "pos": (self.pos().x(), self.pos().y()),
            "lineGripItems": [(hex(id(i)), i.m_index) for i in self.lineGripItems],
            "label": self.label,
            "rotation": self.rotation,
            "flipstate": self.flipState
        }

    def __setstate__(self, dict):
        self.prepareGeometryChange()
        self.width = dict['width']
        self.height = dict['height']
        self.updateSizeGripItem()


class InflowLine(NodeItem):
    def __init__(self):
        super(InflowLine, self).__init__("svg/Piping/Inflow Line")
        self.grips = [
            [100, 50, "right"]
        ]


class OutflowLine(NodeItem):
    def __init__(self):
        super(OutflowLine, self).__init__("svg/Piping/Outflow Line")
        self.grips = [
            [0, 50, "left"]
        ]


class DuplexPump(NodeItem):
    def __init__(self):
        super(DuplexPump, self).__init__("svg/Pumps/Duplex Pump")
        self.grips = [
            [100, 68.8031698, "right"],
            [0, 88.1365808, "left"]
        ]


class PlungerPump(NodeItem):
    def __init__(self):
        super(PlungerPump, self).__init__("svg/Pumps/Plunger Pump")
        self.grips = [
            [87.0328592, 100, "top"],
            [87.0328592, 0, "bottom"]
        ]


class ProportioningPump(NodeItem):
    def __init__(self):
        super(ProportioningPump, self).__init__("svg/Pumps/Proportioning Pump")
        self.grips = [
            [100, 83.0966226, "right"],
            [0, 83.0966226, "left"]
        ]


class ReciprocatingPump(NodeItem):
    def __init__(self):
        super(ReciprocatingPump, self).__init__("svg/Pumps/Reciprocating Pump")
        self.grips = [
            [100, 78.3969475, "right"],
            [0, 78.3969475, "left"]
        ]


class BlowingEgg(NodeItem):
    def __init__(self):
        super(BlowingEgg, self).__init__("svg/Pumps/Blowing Egg")
        self.grips = [
            [15.2887853, 56.4147177, "top"],
            [84.7112147, 56.4147177, "top"]
        ]


class EjectorVaporService(NodeItem):
    def __init__(self):
        super(EjectorVaporService, self).__init__("svg/Pumps/Ejector(Vapor Service)")
        self.grips = [
            [18, 100, "top"],
            [0, 50, "left"],
            [100, 50, "right"]
        ]


class HandPumpWithDrum(NodeItem):
    def __init__(self):
        super(HandPumpWithDrum, self).__init__("svg/Pumps/Hand Pump with Drum")
        self.grips = [
            [92.8093483, 70.60413752309337, "right"],
            [7.913824600849647, 70.60413752309337, "left"],
            [4.136894788615162, 86.9886362, "left"]
        ]


class CentrifugalCompressor(NodeItem):
    def __init__(self):
        super(CentrifugalCompressor, self).__init__("svg/Compressors/Centrifugal Compressor")
        self.grips = [
            [41.316753407496, 89.824108247573, "top"],
            [62.0517030576456, 79.183192150093, "top"],
            [41.316753407496, 6.447877022097, "bottom"],
            [62.0517030576456, 16.14847772052, "bottom"]
        ]


class EjectorCompressor(NodeItem):
    def __init__(self):
        super(EjectorCompressor, self).__init__("svg/Compressors/Ejector Compressor")
        self.grips = [
            [13.1018813062, 100, "top"],
            [0, 50, "left"],
            [100, 50, "right"]
        ]


class Fan(NodeItem):
    def __init__(self):
        super(Fan, self).__init__("svg/Compressors/Fan")
        self.grips = [
            [50, 79.92762310350343, "top"],
            [0, 79.92762310350343, "left"],
            [100, 79.92762310350343, "right"]
        ]


class PositiveDisplacementCompressor(NodeItem):
    def __init__(self):
        super(PositiveDisplacementCompressor, self).__init__("svg/Compressors/Positive Displacement Compressor")
        self.grips = [
            [50, 100, "top"],
            [21.15509548928236, 30, "left"],
            [79.57853462426666, 30, "right"]
        ]


class ReciprocatingCompressor(NodeItem):
    def __init__(self):
        super(ReciprocatingCompressor, self).__init__("svg/Compressors/Reciprocating Compressor")
        self.grips = [
            [22.85680252121469, 83, "left"],
            [46.81088180183039, 83, "right"]
        ]


class Turbine(NodeItem):
    def __init__(self):
        super(Turbine, self).__init__("svg/Compressors/Turbine")
        self.grips = [
            [18.06209745144267, 79.11931909160472, "top"],
            [45.2091373550176, 91.385325275219, "top"],
            [18.06209745144267, 16.41537491819628, "bottom"],
            [45.2091373550176, 4.5725942986116, "bottom"]
        ]


class OilGasOrPulverizedFuelFurnace(NodeItem):
    def __init__(self):
        super(OilGasOrPulverizedFuelFurnace, self).__init__(
            "svg/Furnaces and Boilers/Oil Gas or Pulverized Fuel Furnace")
        self.grips = [
            [58.27673386073162, 100, "top"],
            [0, 19.692723451106, "left"],
            [17.2777337415748-5, 33.3944873323144, "left", 66.7889746646288],
            [100+5, 33.3944873323144, "right", 66.7889746646288],
            [57.9723659874, 0-10, "bottom", 81.389264491796]
        ]


class SolidFuelFurnace(NodeItem):
    def __init__(self):
        super(SolidFuelFurnace, self).__init__("svg/Furnaces and Boilers/Solid Fuel Furnace")
        self.grips = [
            [50, 100, "top"],
            [0-5, 33.39352642259468, "left", 66.78705284518936],
            [100+5, 33.39352642259468, "right", 66.78705284518936],
            [50, 0-10, "bottom", 100]
        ]


class Exchanger905(NodeItem):
    def __init__(self):
        super(Exchanger905, self).__init__("svg/Heating or Cooling Arrangements/905Exchanger")
        self.grips = [
            [15.85, 13.5, "bottom", 11.21],
            [60.5, 13.5, "bottom", 55.33],
            [15.85, 88.88, "top", 11.21],
            [60.5, 88.88, "top", 55.33]
        ]

class KettleReboiler907(NodeItem):
    def __init__(self):
        super(KettleReboiler907, self).__init__("svg/Heating or Cooling Arrangements/907Kettle Reboiler")
        self.grips = [
            [18, 20.33, "bottom", 18],
            [70, 20.33, "bottom", 40.33],
            [18, 75, "top", 18],
            [70, 96, "top", 40.33]
        ]

class Exchanger(NodeItem):
    def __init__(self):
        super(Exchanger, self).__init__("svg/Heating or Cooling Arrangements/Exchanger")
        self.grips = [
            [100, 31.74474612706027, "right"],
            [100, 62.70549343934227, "right"],
            [33.68240920045628, 100, "top"],
            [33.68240920045628, 0, "bottom"]
        ]


class HeatExchanger(NodeItem):
    def __init__(self):
        super(HeatExchanger, self).__init__("svg/Heating or Cooling Arrangements/Heat Exchanger")
        self.grips = [
            [0, 47.14356681569796, "left"],
            [100, 47.14356681569796, "right"],
            [50.92839727035332, 100, "top"],
            [50.92839727035332, 0, "bottom"]
        ]


class ImmersionCoil(NodeItem):
    def __init__(self):
        super(ImmersionCoil, self).__init__("svg/Heating or Cooling Arrangements/Immersion Coil")
        self.grips = [
            [44.56276981957, 100, "top"],
            [88.232463407718, 100, "top"]
        ]

class KettleReboiler(NodeItem):
    def __init__(self):
        super(KettleReboiler, self).__init__("svg/Heating or Cooling Arrangements/Kettle Reboiler")
        self.grips = [
            [100, 26.3, "right"],
            [0, 26.3, "left"],
            [50, 100, "top"],
            [50, 0, "bottom"]
        ]

class HorizontalVessel(NodeItem):
    def __init__(self):
        super(HorizontalVessel, self).__init__("svg/Process Vessels/Horizontal Vessel")
        self.grips = [
            [50, 100+10, "top", 87.08554680344],
            [0, 50, "left"],
            [100, 50, "right"],
            [50, 0-10, "bottom", 87.08554680344]
        ]


class PackedVessel(NodeItem):
    def __init__(self):
        super(PackedVessel, self).__init__("svg/Process Vessels/Packed Vessel")
        self.grips = [
            [50, 100, "top"],
            [0-10, 50, "left", 86.703566201060],
            [100+10, 50, "right", 86.703566201060],
            [50, 0, "bottom"]
        ]


class TraysOrPlates(NodeItem):
    def __init__(self):
        super(TraysOrPlates, self).__init__("svg/Process Vessels/Trays or plates")
        self.grips = [
        ]


class VerticalVessel(NodeItem):
    def __init__(self):
        super(VerticalVessel, self).__init__("svg/Process Vessels/Vertical Vessel")
        self.grips = [
            [50, 100, "top"],
            [0-10, 50, "left", 86.703566201060],
            [100+10, 50, "right", 86.703566201060],
            [50, 0, "bottom"]
        ]


class Separators(NodeItem):
    def __init__(self):
        super(Separators, self).__init__("svg/Separators/Separators for Liquids, Decanter")
        self.grips = [
            [50, 100, "top", 100],
            [0, 50, "left", 100],
            [100, 50, "right", 100],
            [50, 0, "bottom", 100]
        ]


class FixedRoofTank(NodeItem):
    def __init__(self):
        super(FixedRoofTank, self).__init__("svg/Storage Vessels Tanks/Fixed Roof Tank")
        self.grips = [
            [50, 100, "top"],
            [0-6, 50, "left", 100],
            [100+7, 50, "right", 100],
            [50, 0-10, "bottom", 100]
        ]


class FloatingRoofTank(NodeItem):
    def __init__(self):
        super(FloatingRoofTank, self).__init__("svg/Storage Vessels Tanks/Floating Roof Tank")
        self.grips = [
            [0-7, 50, "left", 100],
            [100+7, 50, "right", 100],
            [50, 0-10, "bottom", 100]
        ]


class SeparatorsForLiquidsDecanter(NodeItem):
    def __init__(self):
        super(SeparatorsForLiquidsDecanter, self).__init__("svg/Separators/Separators for Liquids, Decanter")
        self.grips = [
            [50, 100+10, "top", 100],
            [0-10, 50, "left", 100],
            [100+10, 50, "right", 100],
            [50, 0-10, "bottom", 100]
        ]

class GateValve(NodeItem):
    def __init__(self):
        super(GateValve, self).__init__("svg/Valves/Gate Valve")
        self.grips = [
            [0, 50, "left"],
            [100, 50, "right"]
        ]

class CentrifugalPump(NodeItem):
    def __init__(self):
        super(CentrifugalPump, self).__init__("svg/Pumps/Centrifugal Pump")
        self.grips = [
            [100, 97.2, "right"],
            [0, 58.78, "left"]
        ]


class OneCellFiredHeaterFurnace(NodeItem):
    def __init__(self):
        super(OneCellFiredHeaterFurnace, self).__init__("svg/Furnaces and Boilers/One Cell Fired Heater, Furnace")
        self.grips = [
            [50, 100, "top"],
            [0-7, 25, "left", 50],
            [25, 87.5, "left", 25],
            [100+7, 25, "right", 50],
            [75, 87.5, "right", 25],
            [50, 0-10, "bottom", 100]
        ]


class TwoCellFiredHeaterFurnace(NodeItem):
    def __init__(self):
        super(TwoCellFiredHeaterFurnace, self).__init__("svg/Furnaces and Boilers/Two Cell Fired Heater, Furnace")
        self.grips = [
            [50, 100, "top"],
            [0-5, 33.33, "left", 66.66],
            [33.33, 91.66, "left", 16.66],
            [100+5, 33.33, "right", 66.66],
            [66.66, 91.66, "right", 16.66],
            [16.67, 0-10, "bottom", 33.33],
            [83.33, 0-10, "bottom", 33.33]
        ]


class ReducerExpander(NodeItem):
    def __init__(self):
        super(ReducerExpander, self).__init__("svg/Fittings/Reducer, Expander")
        self.grips = [
            [100, 50, "right"],
            [0, 50, "left"]
        ]


class Filter(NodeItem):
    def __init__(self):
        super(Filter, self).__init__("svg/Fittings/Filter")
        self.grips = [
            [0, 50, "left"],
            [100, 50, "right"]
        ]


class ContinuousDryer(NodeItem):
    def __init__(self):
        super(ContinuousDryer, self).__init__("svg/Dryers/Continuous Dryer")
        self.grips = [
            [8.13, 35.2, "top"],
            [98.9, 28, "bottom"],
            [50, 100+10, "top", 60.13]
        ]


class JawCrusher(NodeItem):
    def __init__(self):
        super(JawCrusher, self).__init__("svg/Size Reduction Equipements/Jaw Crusher")
        self.grips = [
            [79.65, 100, "top"],
            [0, 0, "bottom"]
        ]


class RollerCrusher(NodeItem):
    def __init__(self):
        super(RollerCrusher, self).__init__("svg/Size Reduction Equipements/Roller Crusher")
        self.grips = [
            [50, 100, "top"],
            [50, 0, "bottom"]
        ]


class GeneralSymbol(NodeItem):
    def __init__(self):
        super(GeneralSymbol, self).__init__("svg/Feeders/General Symbol")
        self.grips = [
            [20, 100, "top"],
            [80, 0, "bottom"]
        ]