summaryrefslogtreecommitdiff
path: root/src/main/python/utils/custom.py
blob: 5625ea458c01adb1a75710c27660e6b62b6b79a9 (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
from PyQt5.QtCore import QRectF, Qt, QSize
from PyQt5.QtGui import (QBrush, QIcon, QImage, QPainter, QPainterPath, QPen,
                         QPixmap, QTransform)
from PyQt5.QtSvg import QGraphicsSvgItem
from PyQt5.QtWidgets import (QBoxLayout, QDialog, QFileDialog,
                             QGraphicsEllipseItem, QGraphicsItem,
                             QGraphicsScene, QGraphicsView, QGridLayout,
                             QInputDialog, QLabel, QLineEdit, QPushButton,
                             QTextEdit)

from shapes import SizeGripItem, directionsEnum

from .app import fileImporter


class ShapeDialog(QDialog):
    
    def __init__(self, parent=None):
        super(ShapeDialog, self).__init__(parent)
        self.resize(500, 300)
        self.setWindowTitle("Add New Shapes")
        self.createLayout()
        self.graphic = None
        
    def createLayout(self):
        importButton = QPushButton("Import", self)
        importButton.clicked.connect(self.importSVG)
        
        saveButton = QPushButton("Save", self)
        saveButton.clicked.connect(self.saveEvent)
        
        self.symbolName = QLineEdit(self)
        self.symbolName.setPlaceholderText("Enter Symbol Name")
        symbolNameLabel = QLabel("Symbol Name")
        symbolNameLabel.setBuddy(self.symbolName)
        
        self.symbolClass = QLineEdit(self)
        self.symbolClass.setPlaceholderText("Enter Symbol Class Name")
        symbolClassLabel = QLabel("Symbol Class Name")
        symbolClassLabel.setBuddy(self.symbolClass)
        
        self.symbolCategory = QLineEdit(self)
        self.symbolCategory.setPlaceholderText("Enter Symbol Category")
        symbolCategoryLabel = QLabel("Symbol Category")
        symbolCategoryLabel.setBuddy(self.symbolCategory)
        
        addGripItem = QPushButton("Add Grip Item", self)
        addGripItem.clicked.connect(self.addGrip)
        addLineGripItem = QPushButton("Add Line Grip Item", self)
        addLineGripItem.clicked.connect(self.addLineGrip)
        
        self.painter = QGraphicsScene()
        view = QGraphicsView(self.painter)
        
        layout = QGridLayout(self)
        
        subLayout = QBoxLayout(QBoxLayout.LeftToRight)
        subLayout.addWidget(importButton)
        subLayout.addWidget(saveButton)
        subLayout.addStretch(1)
        
        layout.addLayout(subLayout, 0, 0, 1, -1)
        
        subLayout2 = QBoxLayout(QBoxLayout.LeftToRight)
        subLayout2.addWidget(view, stretch=1)
        
        subLayout3 = QBoxLayout(QBoxLayout.TopToBottom)
        subLayout3.addWidget(symbolNameLabel)
        subLayout3.addWidget(self.symbolName)
        subLayout3.addWidget(symbolClassLabel)
        subLayout3.addWidget(self.symbolClass)
        subLayout3.addWidget(symbolCategoryLabel)
        subLayout3.addWidget(self.symbolCategory)
        subLayout3.addStretch(1)
        subLayout3.addWidget(addGripItem)
        subLayout3.addWidget(addLineGripItem)
        subLayout2.addLayout(subLayout3)
        
        layout.addLayout(subLayout2, 1, 0, -1, -1)
        self.setLayout(layout)
        
    def importSVG(self):
        self.name = QFileDialog.getOpenFileName(self, 'Open SVG File', '', 'Scalable Vector Graphics (*svg)')
        if self.name:
            self.graphic = QGraphicsSvgItem(self.name[0])
            self.graphic.setZValue(-1)
            self.painter.addItem(self.graphic)
    
    def saveEvent(self):
        if self.graphic is None:
            return
        
        itemName = self.symbolName.text()
        if itemName is '':
            return
        
        className = self.symbolClass.text()
        if className is '':
            return

        category = self.symbolCategory.text()
        if category == "":
            category = "misc"
        
        graphicRect = self.graphic.boundingRect()
        
        QIcon
        
        #save file
        name = QFileDialog.getSaveFileName(self, 'Save Icon', className, 'PNG (*.png)')
        if name:
            QIcon(self.name[0]).pixmap(QSize(64, 64)).toImage().save(name[0])
        else:
            return
        
        gripList = []
        x, y, w, h = graphicRect.getRect()
        for i in self.grips:
            pos = i.pos()
            entry = [abs((x-pos.x())/w)*100, abs((y-pos.y())/h)*100, i.location]
            if isinstance(i, gripRect):
                if i.location in ["top", "bottom"]:
                    entry.append(i.height)
                else:
                    entry.append(i.width)
            gripList.append(entry)

        temp = QDialog(self)
        tempLayout = QBoxLayout(QBoxLayout.TopToBottom)
        output = OutputBox(temp, f"""class {className}(NodeItem):
            def __init__(self):
                super({className}, self).__init__("svg/{category}/{str.split(name[0], "/")[-1][:-4]}")
            self.grips = {gripList}
        """)
        tempLayout.addWidget(output)
        temp.setLayout(tempLayout)
        temp.exec()
      
    @property
    def grips(self):
        return [i for i in self.painter.items() if isinstance(i, gripAbstract)]
    
    def addGrip(self):
        grip = gripDot()
        self.painter.addItem(grip)
    
    def addLineGrip(self):
        rect = gripRect()
        self.painter.addItem(rect)

class gripAbstract(QGraphicsItem):
    
    def __init__(self):
        super(gripAbstract, self).__init__()
        self.location = "top"
        self.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsSelectable)
        
    def mouseDoubleClickEvent(self, event):
        self.location, _ = QInputDialog.getItem(None, "Change location", "Select location", directionsEnum,
                                                     directionsEnum.index(self.location), False)   
        
class gripRect(gripAbstract):
    def __init__(self, x=0, y=0, w=80, h=10 ):
        super(gripRect, self).__init__()
        self.rotation = 0
        self.sizeGripItems = []
        self.width = w
        self.height = h
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges)
        
    def boundingRect(self):
        return QRectF(-self.width / 2, -self.height / 2, self.width, self.height)
    
    def paint(self, painter, option, index):
        painter.setPen(QPen(Qt.black, 1, Qt.SolidLine))
        painter.setBrush(QBrush(Qt.red))
        painter.drawRect(self.boundingRect())
        
    def addGripItems(self):
        for i, (direction) in enumerate((Qt.Vertical,
                                        Qt.Horizontal,
                                        Qt.Vertical,
                                        Qt.Horizontal)):
            self.sizeGripItems.append(SizeGripItem(i, direction, parent=self))
            
    def updateSizeGripItem(self, index_no_updates=None):
        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):
        if change == QGraphicsItem.ItemPositionHasChanged:
            # update grips
            self.updateSizeGripItem()
            return
        # check if item is add on scene
        if change == QGraphicsItem.ItemSceneHasChanged and self.scene():
            # add grips and update them
            self.addGripItems()
            self.updateSizeGripItem()
            return
        return super(gripRect, self).itemChange(change, value)
    
    def resize(self, index, movement):
        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])

class gripDot(gripAbstract):        
    def boundingRect(self):
        return QRectF(0, 0, 10, 10)
    
    def paint(self, painter, option, index):
        painter.setPen(QPen(Qt.black, 1, Qt.SolidLine))
        painter.setBrush(QBrush(Qt.red))
        painter.drawEllipse(self.boundingRect())
        
class OutputBox(QTextEdit):
    
    def __init__(self, parent, text):
        super(OutputBox, self).__init__(parent)
        self.setReadOnly(True)
        self.resize(600, 300)
        self.text = text
        self.setMarkdown("```python\n"+text+"\n```")