44
|
1 #!/usr/bin/python
|
|
2
|
|
3 from PyQt4.QtGui import *
|
|
4 from PyQt4.QtCore import *
|
81
|
5 import sys, json, base64
|
44
|
6
|
56
|
7 """
|
53
|
8 Author: Windel Bouwman
|
|
9 Year: 2012
|
|
10 Description: This script implements a diagram editor.
|
|
11 run with python 3.x as:
|
|
12 $ python [thisfile.py]
|
44
|
13 """
|
81
|
14 saveicon = b'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAGGklEQVR42s2XeWxURRjAv7d3L9ay\nlJBCbAx/SIIpCWilhNLSFsrR0qUgyCmnnKVFa/xDjNbUKGIUSrlaLhEREWlZaQoC24VymBivoGJB\n/MuEtEpjoNt2z/H7Zt+8fdPdGk2MOu23MzvvzXy/+Y6ZWQX+46L8bwC2vLTlZte9e6MMRiMYjQYY\nPWYsZGXngM1iBkUxoERej1RYayJmYGrF1Dbj/31+P1xtuwQ3vvmaP6M/h8Nx69Xq6kclgDWrn2W3\nbt+G5KQkSE9Ph/E5eTB1xixIQID+yIraEMoVJYLGay4KGNS2ty8Aza4muHqpVZvClmCDHbW1igSw\neuUq1tPTA2EWRohkmJCbD9OLS+Fu14M4ZlP6M8lwSvSdEUNTwNXYCFc87iiAzQY7d9XJACuXr2Dd\n3d1gNpvBarXCxMmFUDzLCUk2S3zfKTrlqmIlYgqtTfWDXh80NZ6CNvdFnQUSYNfuXTLAimXLmV5B\nTn4hlDrLICUxHoAC+tHSTNz1jIcCw48HvX60AAK0RgGsaIE9e/fIAMuWPiMB5BZMAWfZHBiUaI1r\nAaZ+Mi32VKVqX5h/ZzwGzpxuRAtckFywt36fDLB08RIZoHAqlDhnQ0eXdwDlosFAP1APRGVoahK0\nYBBedp+XLNCwv0EGWLxwUT+AIphZ6ozNghhlEQCtrZqeqRC+QAjOftqEFogCkAX2HzwgAyxasFAC\nmFQwFaaVEIAJ5P2K6T5ln2uu0LnEHwzBZ2ea4Epr1AUU5AcPH5IBFsx/Wg5CBCgqdoLV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MQLYP2O12BqB0uJrjyk8li8fjdGtri4AfeQAMAUpXayJW\ne2MlANlWbLPZGAB2LPagCoQapZaXl+nOzg6ZmZmRB8CBhANoYTB5U5iQyOzsrDwAjmR4hWpl0WiU\nwpxI5ubmpAAwKLAQ4HWqlUUiEbq/v0/m5+flATAEWiqwtLREDw4OyMLCgjyA1iEIh8P08PCQ+P1+\nKUBPTw8D0DIEi4uL9OjoiASDQSlAd3c3A7i/v9cUAKsgFApJAaxWa2B6etp2e3v71yGlen++X60v\n4EwAAOlUKvUO+oEUoLW19UNfX9/nxsbGhsoOxy+Wl75X2+drdXX1J/zX9AkmI+lU3N7e/hYSxAAT\n0Rs+FdX69rXsA1y5ubn5Vz6fL1Q++w30VO4/0/9IewAAAABJRU5ErkJggg==\n'
|
44
|
19
|
73
|
20 def buildPath(pts):
|
|
21 path = QPainterPath(pts[0])
|
76
|
22 for pt in pts[1:]: path.lineTo(pt)
|
73
|
23 return path
|
55
|
24
|
77
|
25 def equalSpace(n, l, offset=15):
|
74
|
26 if n == 1:
|
|
27 return [l / 2]
|
|
28 elif n > 1:
|
|
29 return [offset + (l - offset*2)/(n - 1)*i for i in range(n)]
|
|
30 return []
|
|
31
|
75
|
32 def uniqify(name, names):
|
76
|
33 newname, i = name, 1
|
77
|
34 while newname in names: newname, i = name + str(i), i + 1
|
75
|
35 return newname
|
|
36
|
49
|
37 class Connection(QGraphicsPathItem):
|
53
|
38 """ Implementation of a connection between blocks """
|
78
|
39 def __init__(self, fromPort=None, toPort=None):
|
49
|
40 super(Connection, self).__init__()
|
74
|
41 self.pos2 = self.fromPort = self.toPort = None
|
76
|
42 self.setFlags(self.ItemIsSelectable | self.ItemClipsToShape)
|
|
43 pen = QPen(Qt.blue, 2, cap=Qt.RoundCap)
|
73
|
44 self.setPen(pen)
|
|
45 self.arrowhead = QGraphicsPathItem(self)
|
|
46 self.arrowhead.setPath(buildPath([QPointF(0.0, 0.0), QPointF(-6.0, 10.0), QPointF(6.0, 10.0), QPointF(0.0, 0.0)]))
|
|
47 self.arrowhead.setPen(pen)
|
|
48 self.arrowhead.setBrush(QBrush(pen.color()))
|
58
|
49 self.vias = []
|
44
|
50 self.setFromPort(fromPort)
|
46
|
51 self.setToPort(toPort)
|
78
|
52 def getDict(self):
|
|
53 d = {}
|
|
54 d['fromBlock'] = self.fromPort.block.name
|
|
55 d['fromPort'] = self.fromPort.name
|
|
56 d['toBlock'] = self.toPort.block.name
|
|
57 d['toPort'] = self.toPort.name
|
|
58 return d
|
|
59 def setDict(self, d):
|
|
60 print(d)
|
|
61 Dict = property(getDict, setDict)
|
72
|
62 def myDelete(self):
|
|
63 scene = self.scene()
|
|
64 if scene:
|
|
65 self.setFromPort(None)
|
|
66 self.setToPort(None)
|
|
67 scene.removeItem(self)
|
44
|
68 def setFromPort(self, fromPort):
|
53
|
69 if self.fromPort:
|
|
70 self.fromPort.posCallbacks.remove(self.setBeginPos)
|
54
|
71 self.fromPort.connection = None
|
44
|
72 self.fromPort = fromPort
|
|
73 if self.fromPort:
|
54
|
74 self.fromPort.connection = self
|
74
|
75 self.updateLineStukken()
|
44
|
76 self.fromPort.posCallbacks.append(self.setBeginPos)
|
|
77 def setToPort(self, toPort):
|
53
|
78 if self.toPort:
|
|
79 self.toPort.posCallbacks.remove(self.setEndPos)
|
54
|
80 self.toPort.connection = None
|
44
|
81 self.toPort = toPort
|
|
82 if self.toPort:
|
46
|
83 self.setEndPos(toPort.scenePos())
|
54
|
84 self.toPort.connection = self
|
44
|
85 self.toPort.posCallbacks.append(self.setEndPos)
|
74
|
86 def getPos1(self):
|
|
87 if self.fromPort:
|
|
88 return self.fromPort.scenePos()
|
76
|
89 def setBeginPos(self, pos1): self.updateLineStukken()
|
44
|
90 def setEndPos(self, endpos):
|
|
91 self.pos2 = endpos
|
46
|
92 self.updateLineStukken()
|
55
|
93 def itemChange(self, change, value):
|
|
94 if change == self.ItemSelectedHasChanged:
|
60
|
95 for via in self.vias:
|
|
96 via.setVisible(value)
|
55
|
97 return super(Connection, self).itemChange(change, value)
|
76
|
98 def shape(self): return self.myshape
|
44
|
99 def updateLineStukken(self):
|
|
100 """
|
|
101 This algorithm determines the optimal routing of all signals.
|
|
102 TODO: implement nice automatic line router
|
|
103 """
|
74
|
104 pos1 = self.getPos1()
|
|
105 if pos1 is None or self.pos2 is None:
|
46
|
106 return
|
74
|
107 pts = [pos1] + [v.pos() for v in self.vias] + [self.pos2]
|
55
|
108 self.arrowhead.setPos(self.pos2)
|
|
109 if pts[-1].x() < pts[-2].x():
|
|
110 self.arrowhead.setRotation(-90)
|
|
111 else:
|
|
112 self.arrowhead.setRotation(90)
|
73
|
113 self.setPath(buildPath(pts))
|
58
|
114 """ Create a shape outline using the path stroker """
|
|
115 s = super(Connection, self).shape()
|
|
116 pps = QPainterPathStroker()
|
|
117 pps.setWidth(10)
|
|
118 self.myshape = pps.createStroke(s).simplified()
|
44
|
119
|
|
120 class ParameterDialog(QDialog):
|
49
|
121 def __init__(self, block, parent = None):
|
44
|
122 super(ParameterDialog, self).__init__(parent)
|
49
|
123 self.block = block
|
44
|
124 self.button = QPushButton('Ok', self)
|
51
|
125 self.nameEdit = QLineEdit(self.block.name)
|
60
|
126 self.codeEdit = QTextEdit(self)
|
|
127 self.codeEdit.setPlainText(self.block.code)
|
75
|
128 l = QFormLayout(self)
|
|
129 l.addRow('Name:', self.nameEdit)
|
|
130 l.addRow('Code:', self.codeEdit)
|
|
131 l.addWidget(self.button)
|
44
|
132 self.button.clicked.connect(self.OK)
|
|
133 def OK(self):
|
75
|
134 self.block.name = self.nameEdit.text()
|
60
|
135 self.block.code = self.codeEdit.toPlainText()
|
50
|
136 self.close()
|
56
|
137
|
53
|
138 class PortItem(QGraphicsPathItem):
|
44
|
139 """ Represents a port to a subsystem """
|
79
|
140 def __init__(self, name, block):
|
53
|
141 super(PortItem, self).__init__(block)
|
79
|
142 self.textItem = QGraphicsTextItem(self)
|
54
|
143 self.connection = None
|
50
|
144 self.block = block
|
46
|
145 self.setCursor(QCursor(Qt.CrossCursor))
|
76
|
146 self.setPen(QPen(Qt.blue, 2, cap=Qt.RoundCap))
|
75
|
147 self.name = name
|
44
|
148 self.posCallbacks = []
|
|
149 self.setFlag(self.ItemSendsScenePositionChanges, True)
|
75
|
150 def getName(self): return self.textItem.toPlainText()
|
53
|
151 def setName(self, name):
|
|
152 self.textItem.setPlainText(name)
|
|
153 rect = self.textItem.boundingRect()
|
|
154 lw, lh = rect.width(), rect.height()
|
79
|
155 lx = 3 if type(self) is InputPort else -3 - lw
|
60
|
156 self.textItem.setPos(lx, -lh / 2)
|
75
|
157 name = property(getName, setName)
|
79
|
158 def getDict(self): return {'name': self.name}
|
78
|
159 Dict = property(getDict)
|
44
|
160 def itemChange(self, change, value):
|
|
161 if change == self.ItemScenePositionHasChanged:
|
79
|
162 for cb in self.posCallbacks: cb(value)
|
44
|
163 return value
|
|
164 return super(PortItem, self).itemChange(change, value)
|
|
165
|
53
|
166 class OutputPort(PortItem):
|
80
|
167 def __init__(self, name, block, d=10.0):
|
79
|
168 super(OutputPort, self).__init__(name, block)
|
|
169 self.setPath(buildPath([QPointF(0.0, -d), QPointF(d, 0), QPointF(0.0, d)]))
|
|
170 def mousePressEvent(self, event):
|
|
171 self.scene().startConnection(self)
|
|
172
|
|
173 class InputPort(PortItem):
|
80
|
174 def __init__(self, name, block, d=10.0):
|
79
|
175 super(InputPort, self).__init__(name, block)
|
|
176 self.setPath(buildPath([QPointF(-d, -d), QPointF(0, 0), QPointF(-d, d)]))
|
53
|
177
|
44
|
178 class HandleItem(QGraphicsEllipseItem):
|
|
179 """ A handle that can be moved by the mouse """
|
|
180 def __init__(self, parent=None):
|
60
|
181 dx = 13.0
|
55
|
182 super(HandleItem, self).__init__(QRectF(-0.5*dx,-0.5*dx,dx,dx), parent)
|
44
|
183 self.posChangeCallbacks = []
|
46
|
184 self.setBrush(QBrush(Qt.white))
|
76
|
185 self.setFlags(self.ItemSendsScenePositionChanges | self.ItemIsMovable)
|
60
|
186 self.setVisible(False)
|
46
|
187 self.setCursor(QCursor(Qt.SizeFDiagCursor))
|
55
|
188 def mouseMoveEvent(self, event):
|
|
189 """ Move function without moving the other selected elements """
|
|
190 p = self.mapToParent(event.pos())
|
|
191 self.setPos(p)
|
44
|
192 def itemChange(self, change, value):
|
|
193 if change == self.ItemPositionChange:
|
|
194 for cb in self.posChangeCallbacks:
|
55
|
195 res = cb(value)
|
80
|
196 if res: value = res
|
44
|
197 return value
|
|
198 return super(HandleItem, self).itemChange(change, value)
|
|
199
|
|
200 class BlockItem(QGraphicsRectItem):
|
78
|
201 """ Represents a block in the diagram """
|
44
|
202 def __init__(self, name='Untitled', parent=None):
|
|
203 super(BlockItem, self).__init__(parent)
|
77
|
204 self.subModel = DiagramScene()
|
|
205 self.subModel.containingBlock = self
|
44
|
206 # Properties of the rectangle:
|
46
|
207 self.setPen(QPen(Qt.blue, 2))
|
|
208 self.setBrush(QBrush(Qt.lightGray))
|
75
|
209 self.setFlags(self.ItemIsSelectable | self.ItemIsMovable | self.ItemSendsScenePositionChanges)
|
46
|
210 self.setCursor(QCursor(Qt.PointingHandCursor))
|
44
|
211 self.label = QGraphicsTextItem(name, self)
|
50
|
212 self.name = name
|
60
|
213 self.code = ''
|
44
|
214 # Create corner for resize:
|
|
215 self.sizer = HandleItem(self)
|
|
216 self.sizer.posChangeCallbacks.append(self.changeSize) # Connect the callback
|
58
|
217 button = QPushButton('+in')
|
|
218 button.clicked.connect(self.newInputPort)
|
|
219 self.buttonItemAddInput = QGraphicsProxyWidget(self)
|
|
220 self.buttonItemAddInput.setWidget(button)
|
|
221 self.buttonItemAddInput.setVisible(False)
|
|
222 button = QPushButton('+out')
|
|
223 button.clicked.connect(self.newOutputPort)
|
|
224 self.buttonItemAddOutput = QGraphicsProxyWidget(self)
|
|
225 self.buttonItemAddOutput.setWidget(button)
|
|
226 self.buttonItemAddOutput.setVisible(False)
|
44
|
227 # Inputs and outputs of the block:
|
|
228 self.inputs = []
|
|
229 self.outputs = []
|
|
230 # Update size:
|
74
|
231 self.sizer.setPos(QPointF(60, 40)) # This is a better resize function
|
44
|
232 def editParameters(self):
|
49
|
233 pd = ParameterDialog(self, self.window())
|
44
|
234 pd.exec_()
|
59
|
235 def mouseDoubleClickEvent(self, event):
|
77
|
236 #self.editParameters()
|
|
237 scene = self.scene()
|
|
238 if scene:
|
|
239 for view in scene.views():
|
80
|
240 view.diagram = self.subModel
|
77
|
241 view.zoomAll()
|
58
|
242 def newInputPort(self):
|
|
243 names = [i.name for i in self.inputs + self.outputs]
|
79
|
244 self.addInput(InputPort(uniqify('in', names), self))
|
58
|
245 def newOutputPort(self):
|
|
246 names = [i.name for i in self.inputs + self.outputs]
|
79
|
247 self.addOutput(OutputPort(uniqify('out', names), self))
|
75
|
248 def setName(self, name): self.label.setPlainText(name)
|
|
249 def getName(self): return self.label.toPlainText()
|
|
250 name = property(getName, setName)
|
78
|
251 def getDict(self):
|
|
252 d = {'x': self.scenePos().x(), 'y': self.scenePos().y()}
|
|
253 rect = self.rect()
|
|
254 d.update({'width': rect.width(), 'height': rect.height()})
|
|
255 d.update({'name': self.name, 'code': self.code})
|
|
256 d['inputs'] = [inp.Dict for inp in self.inputs]
|
|
257 d['outputs'] = [outp.Dict for outp in self.outputs]
|
80
|
258 d['submodel'] = self.subModel.Dict
|
78
|
259 return d
|
|
260 def setDict(self, d):
|
|
261 self.name = d['name']
|
|
262 self.code = d['code']
|
|
263 self.setPos(d['x'], d['y'])
|
|
264 self.sizer.setPos(d['width'], d['height'])
|
79
|
265 for inp in d['inputs']: self.addInput(InputPort(inp['name'], self))
|
|
266 for outp in d['outputs']: self.addOutput(OutputPort(outp['name'], self))
|
80
|
267 self.subModel.Dict = d['submodel']
|
78
|
268 Dict = property(getDict, setDict)
|
48
|
269 def addInput(self, i):
|
|
270 self.inputs.append(i)
|
49
|
271 self.updateSize()
|
48
|
272 def addOutput(self, o):
|
|
273 self.outputs.append(o)
|
49
|
274 self.updateSize()
|
44
|
275 def contextMenuEvent(self, event):
|
|
276 menu = QMenu()
|
|
277 pa = menu.addAction('Parameters')
|
|
278 pa.triggered.connect(self.editParameters)
|
|
279 menu.exec_(event.screenPos())
|
55
|
280 def itemChange(self, change, value):
|
|
281 if change == self.ItemSelectedHasChanged:
|
72
|
282 for child in [self.sizer, self.buttonItemAddInput, self.buttonItemAddOutput]:
|
|
283 child.setVisible(value)
|
55
|
284 return super(BlockItem, self).itemChange(change, value)
|
72
|
285 def myDelete(self):
|
|
286 scene = self.scene()
|
|
287 if scene:
|
|
288 for p in self.inputs + self.outputs:
|
80
|
289 if p.connection: p.connection.myDelete()
|
72
|
290 scene.removeItem(self)
|
49
|
291 def updateSize(self):
|
|
292 rect = self.rect()
|
|
293 h, w = rect.height(), rect.width()
|
58
|
294 self.buttonItemAddInput.setPos(0, h + 4)
|
|
295 self.buttonItemAddOutput.setPos(w+10, h+4)
|
74
|
296 for inp, y in zip(self.inputs, equalSpace(len(self.inputs), h)):
|
|
297 inp.setPos(0.0, y)
|
|
298 for outp, y in zip(self.outputs, equalSpace(len(self.outputs), h)):
|
|
299 outp.setPos(w, y)
|
55
|
300 def changeSize(self, p):
|
74
|
301 h = 20 if p.y() < 20 else p.y()
|
|
302 w = 40 if p.x() < 40 else p.x()
|
49
|
303 self.setRect(0.0, 0.0, w, h)
|
|
304 rect = self.label.boundingRect()
|
74
|
305 self.label.setPos((w - rect.width()) / 2, (h - rect.height()) / 2)
|
49
|
306 self.updateSize()
|
55
|
307 return QPointF(w, h)
|
44
|
308
|
|
309 class EditorGraphicsView(QGraphicsView):
|
72
|
310 def __init__(self, parent=None):
|
|
311 QGraphicsView.__init__(self, parent)
|
54
|
312 self.setDragMode(QGraphicsView.RubberBandDrag)
|
78
|
313 self.delShort = QShortcut(QKeySequence.Delete, self)
|
80
|
314 self._model = None
|
|
315 self.treeView = QTreeView()
|
|
316 def setDiagram(self, d):
|
|
317 self.setScene(d)
|
|
318 self.delShort.activated.connect(d.deleteItems)
|
|
319 def getModel(self): return self._model
|
78
|
320 def setModel(self, m):
|
80
|
321 self._model = m
|
81
|
322 if m:
|
|
323 self.treeView.setModel(m)
|
|
324 self.diagram = m.rootDiagram
|
80
|
325 model = property(getModel, setModel)
|
|
326 diagram = property(lambda s: s.scene(), setDiagram)
|
72
|
327 def save(self):
|
81
|
328 if self.model:
|
|
329 if not self.model.filename:
|
|
330 self.model.filename = QFileDialog.getSaveFileName(self)
|
|
331 if self.model.filename:
|
|
332 with open(self.model.filename, 'w') as f:
|
|
333 f.write(json.dumps(self.model.Dict))
|
72
|
334 def load(self):
|
|
335 filename = QFileDialog.getOpenFileName(self)
|
81
|
336 if filename:
|
|
337 self.model = loadModel(filename)
|
|
338 def newModel(self):
|
|
339 self.model = ModelHierarchyModel()
|
77
|
340 def goUp(self):
|
80
|
341 if hasattr(self.diagram, 'containingBlock'):
|
|
342 self.diagram = self.diagram.containingBlock.scene()
|
77
|
343 self.zoomAll()
|
72
|
344 def zoomAll(self):
|
|
345 """ zoom to fit all items """
|
80
|
346 rect = self.diagram.itemsBoundingRect()
|
72
|
347 self.fitInView(rect, Qt.KeepAspectRatio)
|
55
|
348 def wheelEvent(self, event):
|
|
349 pos = event.pos()
|
|
350 posbefore = self.mapToScene(pos)
|
|
351 degrees = event.delta() / 8.0
|
|
352 sx = (100.0 + degrees) / 100.0
|
|
353 self.scale(sx, sx)
|
|
354 event.accept()
|
44
|
355 def dragEnterEvent(self, event):
|
77
|
356 if event.mimeData().hasFormat('component/name'): event.accept()
|
44
|
357 def dragMoveEvent(self, event):
|
77
|
358 if event.mimeData().hasFormat('component/name'): event.accept()
|
44
|
359 def dropEvent(self, event):
|
|
360 if event.mimeData().hasFormat('component/name'):
|
48
|
361 name = bytes(event.mimeData().data('component/name')).decode()
|
58
|
362 pos = self.mapToScene(event.pos())
|
|
363 self.scene().addNewBlock(pos, name)
|
80
|
364 # TODO: do this in a cleaner way:
|
|
365 self.model.modelReset.emit()
|
44
|
366
|
|
367 class LibraryModel(QStandardItemModel):
|
77
|
368 mimeTypes = lambda self: ['component/name']
|
44
|
369 def mimeData(self, idxs):
|
|
370 mimedata = QMimeData()
|
|
371 for idx in idxs:
|
|
372 if idx.isValid():
|
80
|
373 txt = self.data(idx, Qt.DisplayRole)
|
44
|
374 mimedata.setData('component/name', txt)
|
|
375 return mimedata
|
|
376
|
80
|
377 class ModelHierarchyModel(QAbstractItemModel):
|
78
|
378 def __init__(self):
|
|
379 super(ModelHierarchyModel, self).__init__()
|
79
|
380 self.rootDiagram = DiagramScene()
|
81
|
381 self.filename = None
|
80
|
382 def setDict(self, d):
|
|
383 self.rootDiagram.Dict = d
|
|
384 self.modelReset.emit()
|
|
385 Dict = property(lambda s: s.rootDiagram.Dict, setDict)
|
|
386 def index(self, row, column, parent=None):
|
|
387 if parent.isValid():
|
|
388 parent = parent.internalPointer().subModel
|
|
389 else:
|
|
390 parent = self.rootDiagram
|
|
391 blocks = sorted(parent.blocks, key=lambda b: b.name)
|
|
392 block = blocks[row]
|
|
393 # Store the index to retrieve it later in the parent function.
|
|
394 # TODO: solve this in a better way.
|
|
395 block.index = self.createIndex(row, column, block)
|
|
396 return block.index
|
|
397 def parent(self, index):
|
|
398 if index.isValid():
|
|
399 block = index.internalPointer()
|
|
400 if block.scene() == self.rootDiagram:
|
|
401 return QModelIndex()
|
|
402 else:
|
|
403 outerBlock = block.scene().containingBlock
|
|
404 return outerBlock.index
|
|
405 print('parent: No valid index')
|
|
406 def data(self, index, role):
|
|
407 if index.isValid() and role == Qt.DisplayRole:
|
|
408 b = index.internalPointer()
|
|
409 return b.name
|
78
|
410 def headerData(self, section, orientation, role):
|
|
411 if orientation == Qt.Horizontal and role == Qt.DisplayRole:
|
80
|
412 return "Element"
|
78
|
413 def rowCount(self, parent):
|
80
|
414 if parent.column() > 0: return 0
|
|
415 if parent.isValid():
|
|
416 parent = parent.internalPointer().subModel
|
|
417 else:
|
|
418 parent = self.rootDiagram
|
|
419 return len(parent.blocks)
|
78
|
420 def columnCount(self, parent):
|
|
421 return 1
|
|
422
|
44
|
423 class DiagramScene(QGraphicsScene):
|
78
|
424 def __init__(self):
|
|
425 super(DiagramScene, self).__init__()
|
56
|
426 self.startedConnection = None
|
77
|
427 blocks = property(lambda sel: [i for i in sel.items() if type(i) is BlockItem])
|
|
428 connections = property(lambda sel: [i for i in sel.items() if type(i) is Connection])
|
78
|
429 def setDict(self, d):
|
|
430 for block in d['blocks']:
|
|
431 b = BlockItem()
|
|
432 self.addItem(b)
|
|
433 b.Dict = block
|
|
434 for con in d['connections']:
|
|
435 fromPort = self.findPort(con['fromBlock'], con['fromPort'])
|
|
436 toPort = self.findPort(con['toBlock'], con['toPort'])
|
80
|
437 self.addItem(Connection(fromPort, toPort))
|
78
|
438 def getDict(self):
|
79
|
439 return {'blocks': [b.Dict for b in self.blocks], 'connections': [c.Dict for c in self.connections]}
|
78
|
440 Dict = property(getDict, setDict)
|
50
|
441 def findPort(self, blockname, portname):
|
76
|
442 block = self.findBlock(blockname)
|
|
443 if block:
|
50
|
444 for port in block.inputs + block.outputs:
|
79
|
445 if port.name == portname: return port
|
76
|
446 def findBlock(self, blockname):
|
79
|
447 for block in self.blocks:
|
|
448 if block.name == blockname: return block
|
58
|
449 def addNewBlock(self, pos, name):
|
79
|
450 blocknames = [item.name for item in self.blocks]
|
58
|
451 b1 = BlockItem(uniqify(name, blocknames))
|
|
452 b1.setPos(pos)
|
|
453 self.addItem(b1)
|
56
|
454 def mouseMoveEvent(self, event):
|
|
455 if self.startedConnection:
|
|
456 pos = event.scenePos()
|
|
457 self.startedConnection.setEndPos(pos)
|
|
458 super(DiagramScene, self).mouseMoveEvent(event)
|
|
459 def mouseReleaseEvent(self, event):
|
|
460 if self.startedConnection:
|
74
|
461 for item in self.items(event.scenePos()):
|
79
|
462 if type(item) is InputPort and item.connection == None:
|
|
463 self.startedConnection.setToPort(item)
|
|
464 self.startedConnection = None
|
|
465 return
|
72
|
466 self.startedConnection.myDelete()
|
56
|
467 self.startedConnection = None
|
|
468 super(DiagramScene, self).mouseReleaseEvent(event)
|
|
469 def startConnection(self, port):
|
|
470 self.startedConnection = Connection(port, None)
|
|
471 pos = port.scenePos()
|
|
472 self.startedConnection.setEndPos(pos)
|
|
473 self.addItem(self.startedConnection)
|
72
|
474 def deleteItems(self):
|
80
|
475 for item in list(self.selectedItems()): item.myDelete()
|
61
|
476
|
|
477 class LibraryWidget(QListView):
|
|
478 def __init__(self):
|
|
479 super(LibraryWidget, self).__init__(None)
|
54
|
480 self.libraryModel = LibraryModel(self)
|
|
481 self.libraryModel.setColumnCount(1)
|
|
482 # Create an icon with an icon:
|
|
483 pixmap = QPixmap(60, 60)
|
|
484 pixmap.fill()
|
|
485 painter = QPainter(pixmap)
|
|
486 painter.fillRect(10, 10, 40, 40, Qt.blue)
|
|
487 painter.setBrush(Qt.yellow)
|
|
488 painter.drawEllipse(20, 20, 20, 20)
|
|
489 painter.end()
|
|
490 # Fill library:
|
78
|
491 for name in ['Block', 'Uber unit', 'Device']:
|
|
492 self.libraryModel.appendRow(QStandardItem(QIcon(pixmap), name))
|
61
|
493 self.setModel(self.libraryModel)
|
|
494 self.setViewMode(self.IconMode)
|
|
495 self.setDragDropMode(self.DragOnly)
|
54
|
496
|
81
|
497 def warning(txt):
|
|
498 QMessageBox.warning(None, "Warning", txt)
|
|
499
|
78
|
500 def loadModel(filename):
|
80
|
501 try:
|
81
|
502 m = ModelHierarchyModel()
|
80
|
503 with open(filename, 'r') as f: data = f.read()
|
81
|
504 m.filename = filename
|
80
|
505 m.Dict = json.loads(data)
|
81
|
506 return m
|
|
507 except KeyError:
|
|
508 warning('Corrupt model: {0}'.format(filename))
|
|
509 except ValueError:
|
|
510 warning('Corrupt model: {0}'.format(filename))
|
|
511 except FileNotFoundError:
|
|
512 warning('File [{0}] not found'.format(filename))
|
78
|
513
|
61
|
514 class Main(QMainWindow):
|
|
515 def __init__(self):
|
|
516 super(Main, self).__init__(None)
|
72
|
517 self.editor = EditorGraphicsView()
|
61
|
518 self.setCentralWidget(self.editor)
|
|
519 self.setWindowTitle("Diagram editor")
|
81
|
520 def buildIcon(b64):
|
|
521 icon = base64.decodestring(b64)
|
|
522 pm = QPixmap()
|
|
523 pm.loadFromData(icon)
|
|
524 return QIcon(pm)
|
61
|
525 toolbar = self.addToolBar('Tools')
|
81
|
526 toolbar.setObjectName('Tools')
|
|
527 def act(name, shortcut, callback, icon=None):
|
|
528 a = QAction(icon, name, self) if icon else QAction(name, self)
|
72
|
529 a.setShortcuts(shortcut)
|
|
530 a.triggered.connect(callback)
|
|
531 toolbar.addAction(a)
|
81
|
532 act('New', QKeySequence.New, self.editor.newModel, buildIcon(newicon))
|
|
533 act('Save', QKeySequence.Save, self.editor.save, buildIcon(saveicon))
|
|
534 act('Load', QKeySequence.Open, self.editor.load, buildIcon(loadicon))
|
72
|
535 act('Full screen', QKeySequence("F11"), self.toggleFullScreen)
|
|
536 act('Fit in view', QKeySequence("F8"), self.editor.zoomAll)
|
77
|
537 act('Go up', QKeySequence(Qt.Key_Up), self.editor.goUp)
|
78
|
538 def addDock(name, widget):
|
|
539 dock = QDockWidget(name, self)
|
81
|
540 dock.setObjectName(name)
|
78
|
541 dock.setWidget(widget)
|
|
542 self.addDockWidget(Qt.LeftDockWidgetArea, dock)
|
|
543 addDock('Library', LibraryWidget())
|
80
|
544 addDock('Model tree', self.editor.treeView)
|
81
|
545 self.settings = QSettings('windelsoft', 'diagrameditor')
|
|
546 self.loadSettings()
|
44
|
547 def toggleFullScreen(self):
|
|
548 self.setWindowState(self.windowState() ^ Qt.WindowFullScreen)
|
61
|
549 self.editor.zoomAll()
|
81
|
550 def loadSettings(self):
|
|
551 if self.settings.contains('mainwindowstate'):
|
|
552 self.restoreState(self.settings.value('mainwindowstate'))
|
|
553 if self.settings.contains('mainwindowgeometry'):
|
|
554 self.restoreGeometry(self.settings.value('mainwindowgeometry'))
|
|
555 if self.settings.contains('openedmodel'):
|
|
556 modelfile = self.settings.value('openedmodel')
|
|
557 self.editor.model = loadModel(modelfile)
|
|
558 def closeEvent(self, ev):
|
|
559 self.settings.setValue('mainwindowstate', self.saveState())
|
|
560 self.settings.setValue('mainwindowgeometry', self.saveGeometry())
|
|
561 if self.editor.model and self.editor.model.filename:
|
|
562 self.settings.setValue('openedmodel', self.editor.model.filename)
|
|
563 # TODO: ask for save of opened files
|
|
564 else:
|
|
565 self.settings.remove('openedmodel')
|
|
566 ev.accept()
|
44
|
567
|
|
568 if __name__ == '__main__':
|
45
|
569 if sys.version_info.major != 3:
|
|
570 print('Please use python 3.x')
|
|
571 sys.exit(1)
|
46
|
572 app = QApplication(sys.argv)
|
61
|
573 main = Main()
|
|
574 main.show()
|
44
|
575 app.exec_()
|
|
576
|