92
|
1 """
|
|
2 Contains all blocks that can be used to build models.
|
|
3 """
|
|
4
|
390
|
5 import sys
|
|
6 import json
|
|
7 import base64
|
|
8 import os
|
|
9
|
|
10 sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'ide'))
|
|
11
|
|
12 from qtwrapper import QtGui, QtCore, QtWidgets, pyqtSignal, get_icon
|
|
13 from qtwrapper import abspath, Qt
|
|
14
|
88
|
15
|
91
|
16 def uniqify(name, names):
|
390
|
17 newname, i = name, 1
|
|
18 while newname in names: newname, i = name + str(i), i + 1
|
|
19 return newname
|
|
20
|
91
|
21
|
88
|
22 def enum(**enums):
|
390
|
23 return type('Enum', (), enums)
|
|
24
|
88
|
25
|
|
26 Position = enum(TOP=0, TOP_RIGHT=1, RIGHT=2, BOTTOM_RIGHT=3, BOTTOM=4, BOTTOM_LEFT=5, LEFT=6, TOP_LEFT=7)
|
|
27
|
390
|
28
|
88
|
29 def buildPath(pts):
|
390
|
30 path = QtGui.QPainterPath(pts[0])
|
|
31 for pt in pts[1:]: path.lineTo(pt)
|
|
32 return path
|
88
|
33
|
|
34 def equalSpace(n, l, offset=15):
|
390
|
35 if n == 1:
|
|
36 return [l / 2]
|
|
37 elif n > 1:
|
|
38 return [offset + (l - offset*2)/(n - 1)*i for i in range(n)]
|
|
39 return []
|
88
|
40
|
390
|
41
|
|
42 class Connection(QtWidgets.QGraphicsPathItem):
|
92
|
43 """ A connection between blocks """
|
88
|
44 def __init__(self, fromPort=None, toPort=None):
|
|
45 super(Connection, self).__init__()
|
|
46 self.pos2 = self.fromPort = self.toPort = None
|
|
47 self.setFlags(self.ItemIsSelectable | self.ItemClipsToShape)
|
390
|
48 pen = QtGui.QPen(Qt.blue, 2, cap=Qt.RoundCap)
|
88
|
49 self.setPen(pen)
|
390
|
50 self.arrowhead = QtGui.QGraphicsPathItem(self)
|
88
|
51 self.arrowhead.setPath(buildPath([QPointF(0.0, 0.0), QPointF(-6.0, 10.0), QPointF(6.0, 10.0), QPointF(0.0, 0.0)]))
|
|
52 self.arrowhead.setPen(pen)
|
390
|
53 self.arrowhead.setBrush(QtGui.QBrush(pen.color()))
|
88
|
54 self.vias = []
|
|
55 self.setFromPort(fromPort)
|
|
56 self.setToPort(toPort)
|
|
57 def getDict(self):
|
|
58 d = {}
|
|
59 d['fromBlock'] = self.fromPort.block.name
|
|
60 d['fromPort'] = self.fromPort.name
|
|
61 d['toBlock'] = self.toPort.block.name
|
|
62 d['toPort'] = self.toPort.name
|
|
63 return d
|
|
64 Dict = property(getDict)
|
|
65 def myDelete(self):
|
|
66 scene = self.scene()
|
|
67 if scene:
|
|
68 self.setFromPort(None)
|
|
69 self.setToPort(None)
|
|
70 scene.removeItem(self)
|
|
71 def setFromPort(self, fromPort):
|
|
72 if self.fromPort:
|
|
73 self.fromPort.posCallbacks.remove(self.setBeginPos)
|
|
74 self.fromPort.connection = None
|
|
75 self.fromPort = fromPort
|
|
76 if self.fromPort:
|
|
77 self.fromPort.connection = self
|
|
78 self.updateLineStukken()
|
|
79 self.fromPort.posCallbacks.append(self.setBeginPos)
|
|
80 def setToPort(self, toPort):
|
|
81 if self.toPort:
|
|
82 self.toPort.posCallbacks.remove(self.setEndPos)
|
|
83 self.toPort.connection = None
|
|
84 self.toPort = toPort
|
|
85 if self.toPort:
|
|
86 self.setEndPos(toPort.scenePos())
|
|
87 self.toPort.connection = self
|
|
88 self.toPort.posCallbacks.append(self.setEndPos)
|
|
89 def getPos1(self):
|
|
90 if self.fromPort:
|
|
91 return self.fromPort.scenePos()
|
|
92 def setBeginPos(self, pos1): self.updateLineStukken()
|
|
93 def setEndPos(self, endpos):
|
|
94 self.pos2 = endpos
|
|
95 self.updateLineStukken()
|
|
96 def itemChange(self, change, value):
|
|
97 if change == self.ItemSelectedHasChanged:
|
|
98 for via in self.vias:
|
|
99 via.setVisible(value)
|
|
100 return super(Connection, self).itemChange(change, value)
|
|
101 def shape(self): return self.myshape
|
|
102 def updateLineStukken(self):
|
|
103 """
|
|
104 This algorithm determines the optimal routing of all signals.
|
|
105 TODO: implement nice automatic line router
|
|
106 """
|
|
107 pos1 = self.getPos1()
|
|
108 pos2 = self.pos2
|
|
109 if pos1 is None or pos2 is None:
|
|
110 return
|
|
111 scene = self.scene()
|
|
112 vias = [pos1 + QPointF(20, 0)] + self.vias + [pos2 + QPointF(-20, 0)]
|
|
113 if scene:
|
390
|
114 litem = QtGui.QGraphicsLineItem()
|
88
|
115 litem.setFlags(self.ItemIsSelectable)
|
|
116 scene.addItem(litem)
|
|
117 for p1, p2 in zip(vias[:-1], vias[1:]):
|
|
118 line = QLineF(p1, p2)
|
|
119 litem.setLine(line)
|
|
120 citems = scene.collidingItems(litem)
|
89
|
121 citems = [i for i in citems if type(i) is Block]
|
88
|
122 scene.removeItem(litem)
|
|
123 pts = [pos1] + vias + [pos2]
|
|
124 self.arrowhead.setPos(pos2)
|
|
125 self.arrowhead.setRotation(90)
|
|
126 p = buildPath(pts)
|
|
127 self.setPath(p)
|
|
128 """ Create a shape outline using the path stroker """
|
|
129 s = super(Connection, self).shape()
|
390
|
130 pps = QtGui.QPainterPathStroker()
|
88
|
131 pps.setWidth(10)
|
|
132 self.myshape = pps.createStroke(s).simplified()
|
|
133
|
390
|
134 class PortItem(QtWidgets.QGraphicsPathItem):
|
88
|
135 """ Represents a port to a subsystem """
|
|
136 def __init__(self, name, block):
|
|
137 super(PortItem, self).__init__(block)
|
390
|
138 self.textItem = QtGui.QGraphicsTextItem(self)
|
88
|
139 self.connection = None
|
|
140 self.block = block
|
390
|
141 self.setCursor(QtGui.QCursor(Qt.CrossCursor))
|
|
142 self.setPen(QtGui.QPen(Qt.blue, 2, cap=Qt.RoundCap))
|
88
|
143 self.name = name
|
|
144 self.posCallbacks = []
|
|
145 self.setFlag(self.ItemSendsScenePositionChanges, True)
|
|
146 def getName(self): return self.textItem.toPlainText()
|
|
147 def setName(self, name):
|
|
148 self.textItem.setPlainText(name)
|
|
149 rect = self.textItem.boundingRect()
|
|
150 lw, lh = rect.width(), rect.height()
|
|
151 lx = 3 if type(self) is InputPort else -3 - lw
|
|
152 self.textItem.setPos(lx, -lh / 2)
|
|
153 name = property(getName, setName)
|
91
|
154 def getDict(self):
|
|
155 return {'name': self.name}
|
88
|
156 Dict = property(getDict)
|
|
157 def itemChange(self, change, value):
|
|
158 if change == self.ItemScenePositionHasChanged:
|
|
159 for cb in self.posCallbacks: cb(value)
|
|
160 return value
|
|
161 return super(PortItem, self).itemChange(change, value)
|
|
162
|
|
163 class OutputPort(PortItem):
|
|
164 def __init__(self, name, block, d=10.0):
|
|
165 super(OutputPort, self).__init__(name, block)
|
|
166 self.setPath(buildPath([QPointF(0.0, -d), QPointF(d, 0), QPointF(0.0, d)]))
|
|
167 def mousePressEvent(self, event):
|
|
168 self.scene().startConnection(self)
|
|
169
|
|
170 class InputPort(PortItem):
|
|
171 def __init__(self, name, block, d=10.0):
|
|
172 super(InputPort, self).__init__(name, block)
|
|
173 self.setPath(buildPath([QPointF(-d, -d), QPointF(0, 0), QPointF(-d, d)]))
|
|
174
|
390
|
175 class Handle(QtWidgets.QGraphicsEllipseItem):
|
88
|
176 """ A handle that can be moved by the mouse """
|
89
|
177 def __init__(self, dx=10.0, parent=None):
|
390
|
178 super(Handle, self).__init__(QtCore.QRectF(-0.5*dx,-0.5*dx,dx,dx), parent)
|
|
179 self.setBrush(QtGui.QBrush(Qt.white))
|
90
|
180 self.setFlags(self.ItemIsMovable)
|
|
181 self.setZValue(1)
|
88
|
182 self.setVisible(False)
|
390
|
183 self.setCursor(QtGui.QCursor(Qt.SizeFDiagCursor))
|
88
|
184 def mouseMoveEvent(self, event):
|
|
185 """ Move function without moving the other selected elements """
|
|
186 p = self.mapToParent(event.pos())
|
|
187 self.setPos(p)
|
|
188
|
|
189 class ResizeSelectionHandle(Handle):
|
90
|
190 def __init__(self, position, block):
|
93
|
191 super(ResizeSelectionHandle, self).__init__(dx=12, parent=block)
|
88
|
192 self.position = position
|
90
|
193 self.block = block
|
88
|
194 if position in [Position.TOP_LEFT, Position.BOTTOM_RIGHT]:
|
390
|
195 self.setCursor(QtGui.QCursor(Qt.SizeFDiagCursor))
|
88
|
196 elif position in [Position.TOP_RIGHT, Position.BOTTOM_LEFT]:
|
|
197 self.setCursor(QCursor(Qt.SizeBDiagCursor))
|
|
198 elif position in [Position.TOP, Position.BOTTOM]:
|
|
199 self.setCursor(QCursor(Qt.SizeVerCursor))
|
|
200 elif position in [Position.LEFT, Position.RIGHT]:
|
390
|
201 self.setCursor(QtGui.QCursor(Qt.SizeHorCursor))
|
88
|
202 def mouseMoveEvent(self, event):
|
90
|
203 self.block.sizerMoveEvent(self, event.scenePos())
|
88
|
204
|
390
|
205 class Block(QtWidgets.QGraphicsRectItem):
|
92
|
206 """ Represents a block in the diagram. """
|
88
|
207 def __init__(self, name='Untitled', parent=None):
|
89
|
208 super(Block, self).__init__(parent)
|
90
|
209 self.selectionHandles = [ResizeSelectionHandle(i, self) for i in range(8)]
|
88
|
210 # Properties of the rectangle:
|
390
|
211 self.setPen(QtGui.QPen(Qt.blue, 2))
|
|
212 self.setBrush(QtGui.QBrush(Qt.lightGray))
|
88
|
213 self.setFlags(self.ItemIsSelectable | self.ItemIsMovable | self.ItemSendsScenePositionChanges)
|
390
|
214 self.setCursor(QtGui.QCursor(Qt.PointingHandCursor))
|
92
|
215 self.setAcceptHoverEvents(True)
|
390
|
216 self.label = QtWidgets.QGraphicsTextItem(name, self)
|
88
|
217 self.name = name
|
|
218 # Create corner for resize:
|
390
|
219 button = QtWidgets.QPushButton('+in')
|
88
|
220 button.clicked.connect(self.newInputPort)
|
390
|
221 self.buttonItemAddInput = QtWidgets.QGraphicsProxyWidget(self)
|
88
|
222 self.buttonItemAddInput.setWidget(button)
|
|
223 self.buttonItemAddInput.setVisible(False)
|
390
|
224 button = QtWidgets.QPushButton('+out')
|
88
|
225 button.clicked.connect(self.newOutputPort)
|
390
|
226 self.buttonItemAddOutput = QtWidgets.QGraphicsProxyWidget(self)
|
88
|
227 self.buttonItemAddOutput.setWidget(button)
|
|
228 self.buttonItemAddOutput.setVisible(False)
|
|
229 # Inputs and outputs of the block:
|
|
230 self.inputs = []
|
|
231 self.outputs = []
|
91
|
232 self.changeSize(2,2)
|
88
|
233 def editParameters(self):
|
|
234 pd = ParameterDialog(self, self.window())
|
|
235 pd.exec_()
|
|
236 def newInputPort(self):
|
|
237 names = [i.name for i in self.inputs + self.outputs]
|
|
238 self.addInput(InputPort(uniqify('in', names), self))
|
|
239 def newOutputPort(self):
|
|
240 names = [i.name for i in self.inputs + self.outputs]
|
|
241 self.addOutput(OutputPort(uniqify('out', names), self))
|
|
242 def setName(self, name): self.label.setPlainText(name)
|
|
243 def getName(self): return self.label.toPlainText()
|
|
244 name = property(getName, setName)
|
|
245 def getDict(self):
|
|
246 d = {'x': self.scenePos().x(), 'y': self.scenePos().y()}
|
|
247 rect = self.rect()
|
|
248 d.update({'width': rect.width(), 'height': rect.height()})
|
91
|
249 d['name'] = self.name
|
88
|
250 d['inputs'] = [inp.Dict for inp in self.inputs]
|
|
251 d['outputs'] = [outp.Dict for outp in self.outputs]
|
|
252 return d
|
|
253 def setDict(self, d):
|
|
254 self.name = d['name']
|
|
255 self.setPos(d['x'], d['y'])
|
|
256 self.changeSize(d['width'], d['height'])
|
92
|
257 for inp in d['inputs']:
|
|
258 self.addInput(InputPort(inp['name'], self))
|
|
259 for outp in d['outputs']:
|
|
260 self.addOutput(OutputPort(outp['name'], self))
|
88
|
261 Dict = property(getDict, setDict)
|
|
262 def addInput(self, i):
|
|
263 self.inputs.append(i)
|
|
264 self.updateSize()
|
|
265 def addOutput(self, o):
|
|
266 self.outputs.append(o)
|
|
267 self.updateSize()
|
|
268 def contextMenuEvent(self, event):
|
|
269 menu = QMenu()
|
|
270 pa = menu.addAction('Parameters')
|
|
271 pa.triggered.connect(self.editParameters)
|
|
272 menu.exec_(event.screenPos())
|
|
273 def itemChange(self, change, value):
|
|
274 if change == self.ItemSelectedHasChanged:
|
|
275 for child in [self.buttonItemAddInput, self.buttonItemAddOutput]:
|
|
276 child.setVisible(value)
|
90
|
277 if value:
|
|
278 self.repositionAndShowHandles()
|
|
279 else:
|
|
280 [h.setVisible(False) for h in self.selectionHandles]
|
|
281
|
89
|
282 return super(Block, self).itemChange(change, value)
|
91
|
283 def hoverEnterEvent(self, event):
|
92
|
284 if not self.isSelected():
|
|
285 self.repositionAndShowHandles()
|
91
|
286 super(Block, self).hoverEnterEvent(event)
|
|
287 def hoverLeaveEvent(self, event):
|
92
|
288 if not self.isSelected():
|
|
289 [h.setVisible(False) for h in self.selectionHandles]
|
91
|
290 super(Block, self).hoverLeaveEvent(event)
|
88
|
291 def myDelete(self):
|
|
292 for p in self.inputs + self.outputs:
|
|
293 if p.connection: p.connection.myDelete()
|
|
294 self.scene().removeItem(self)
|
90
|
295 def repositionAndShowHandles(self):
|
|
296 r = self.rect()
|
|
297 self.selectionHandles[Position.TOP_LEFT].setPos(r.topLeft())
|
|
298 self.selectionHandles[Position.TOP].setPos(r.center().x(), r.top())
|
|
299 self.selectionHandles[Position.TOP_RIGHT].setPos(r.topRight())
|
|
300 self.selectionHandles[Position.RIGHT].setPos(r.right(), r.center().y())
|
|
301 self.selectionHandles[Position.BOTTOM_RIGHT].setPos(r.bottomRight())
|
|
302 self.selectionHandles[Position.BOTTOM].setPos(r.center().x(), r.bottom())
|
|
303 self.selectionHandles[Position.BOTTOM_LEFT].setPos(r.bottomLeft())
|
|
304 self.selectionHandles[Position.LEFT].setPos(r.left(), r.center().y())
|
|
305 for h in self.selectionHandles:
|
|
306 h.setVisible(True)
|
|
307 def sizerMoveEvent(self, handle, pos):
|
|
308 r = self.rect().translated(self.pos())
|
|
309 if handle.position == Position.TOP_LEFT: r.setTopLeft(pos)
|
|
310 elif handle.position == Position.TOP: r.setTop(pos.y())
|
|
311 elif handle.position == Position.TOP_RIGHT: r.setTopRight(pos)
|
|
312 elif handle.position == Position.RIGHT: r.setRight(pos.x())
|
|
313 elif handle.position == Position.BOTTOM_RIGHT: r.setBottomRight(pos)
|
|
314 elif handle.position == Position.BOTTOM: r.setBottom(pos.y())
|
|
315 elif handle.position == Position.BOTTOM_LEFT: r.setBottomLeft(pos)
|
|
316 elif handle.position == Position.LEFT: r.setLeft(pos.x())
|
|
317 else:
|
|
318 print('invalid position')
|
|
319 self.setCenterAndSize(r.center(), r.size())
|
|
320 self.repositionAndShowHandles()
|
88
|
321 def updateSize(self):
|
|
322 rect = self.rect()
|
|
323 h, w = rect.height(), rect.width()
|
|
324 self.buttonItemAddInput.setPos(0, h + 4)
|
|
325 self.buttonItemAddOutput.setPos(w+10, h+4)
|
|
326 for inp, y in zip(self.inputs, equalSpace(len(self.inputs), h)):
|
|
327 inp.setPos(0.0, y)
|
|
328 for outp, y in zip(self.outputs, equalSpace(len(self.outputs), h)):
|
|
329 outp.setPos(w, y)
|
|
330 def setCenterAndSize(self, center, size):
|
|
331 self.changeSize(size.width(), size.height())
|
|
332 p = QPointF(size.width(), size.height())
|
|
333 self.setPos(center - p / 2)
|
|
334 def changeSize(self, w, h):
|
99
|
335 minw = 150
|
|
336 minh = 50
|
|
337 h = minh if h < minh else h
|
|
338 w = minw if w < minw else w
|
88
|
339 self.setRect(0.0, 0.0, w, h)
|
|
340 rect = self.label.boundingRect()
|
|
341 self.label.setPos((w - rect.width()) / 2, (h - rect.height()) / 2)
|
|
342 self.updateSize()
|
|
343
|
390
|
344
|
90
|
345 class CodeBlock(Block):
|
390
|
346 def __init__(self, name='Untitled', parent=None):
|
|
347 super(CodeBlock, self).__init__(name, parent)
|
|
348 self.code = ''
|
|
349
|
|
350 def setDict(self, d):
|
|
351 super(CodeBlock, self).setDict(d)
|
|
352 self.code = d['code']
|
|
353
|
|
354 def getDict(self):
|
|
355 d = super(CodeBlock, self).getDict()
|
|
356 d['code'] = self.code
|
|
357 return d
|
|
358
|
|
359 def gencode(self):
|
90
|
360 c = ['def {0}():'.format(self.name)]
|
|
361 if self.code:
|
|
362 c += indent(self.code.split('\n'))
|
|
363 else:
|
|
364 c += indent(['pass'])
|
|
365 return c
|
|
366
|
390
|
367
|
90
|
368 class DiagramBlock(Block):
|
390
|
369 def __init__(self, name='Untitled', parent=None):
|
90
|
370 super(DiagramBlock, self).__init__(name, parent)
|
|
371 self.subModel = DiagramScene()
|
|
372 self.subModel.containingBlock = self
|
390
|
373
|
|
374 def setDict(self, d):
|
|
375 self.subModel.Dict = d['submodel']
|
|
376
|
|
377 def mouseDoubleClickEvent(self, event):
|
93
|
378 # descent into child diagram
|
|
379 #self.editParameters()
|
|
380 print('descent')
|
|
381 scene = self.scene()
|
|
382 if scene:
|
|
383 for view in scene.views():
|
|
384 view.diagram = self.subModel
|
|
385 view.zoomAll()
|
90
|
386
|
390
|
387
|
|
388 class DiagramScene(QtWidgets.QGraphicsScene):
|
92
|
389 """ A diagram scene consisting of blocks and connections """
|
93
|
390 structureChanged = pyqtSignal()
|
88
|
391 def __init__(self):
|
|
392 super(DiagramScene, self).__init__()
|
|
393 self.startedConnection = None
|
|
394
|
92
|
395 blocks = property(lambda sel: [i for i in sel.items() if isinstance(i, Block)])
|
88
|
396 connections = property(lambda sel: [i for i in sel.items() if type(i) is Connection])
|
93
|
397 def addItem(self, item):
|
|
398 super(DiagramScene, self).addItem(item)
|
|
399 if isinstance(item, Block):
|
|
400 self.structureChanged.emit()
|
|
401 def removeItem(self, item):
|
|
402 super(DiagramScene, self).removeItem(item)
|
|
403 if isinstance(item, Block):
|
|
404 self.structureChanged.emit()
|
88
|
405 def setDict(self, d):
|
|
406 for block in d['blocks']:
|
89
|
407 b = Block()
|
88
|
408 self.addItem(b)
|
|
409 b.Dict = block
|
|
410 for con in d['connections']:
|
|
411 fromPort = self.findPort(con['fromBlock'], con['fromPort'])
|
|
412 toPort = self.findPort(con['toBlock'], con['toPort'])
|
|
413 self.addItem(Connection(fromPort, toPort))
|
|
414 def getDict(self):
|
|
415 return {'blocks': [b.Dict for b in self.blocks], 'connections': [c.Dict for c in self.connections]}
|
|
416 Dict = property(getDict, setDict)
|
|
417 def gencode(self):
|
|
418 c = []
|
|
419 for b in self.blocks:
|
|
420 c += b.gencode()
|
|
421 for b in self.blocks:
|
|
422 c.append('{0}()'.format(b.name))
|
|
423 return c
|
|
424 def findPort(self, blockname, portname):
|
|
425 block = self.findBlock(blockname)
|
|
426 if block:
|
|
427 for port in block.inputs + block.outputs:
|
|
428 if port.name == portname: return port
|
|
429 def findBlock(self, blockname):
|
|
430 for block in self.blocks:
|
|
431 if block.name == blockname: return block
|
91
|
432 def uniqify(self, name):
|
88
|
433 blocknames = [item.name for item in self.blocks]
|
91
|
434 return uniqify(name, blocknames)
|
88
|
435 def mouseMoveEvent(self, event):
|
|
436 if self.startedConnection:
|
|
437 pos = event.scenePos()
|
|
438 self.startedConnection.setEndPos(pos)
|
|
439 super(DiagramScene, self).mouseMoveEvent(event)
|
|
440 def mouseReleaseEvent(self, event):
|
|
441 if self.startedConnection:
|
|
442 for item in self.items(event.scenePos()):
|
|
443 if type(item) is InputPort and item.connection == None:
|
|
444 self.startedConnection.setToPort(item)
|
|
445 self.startedConnection = None
|
|
446 return
|
|
447 self.startedConnection.myDelete()
|
|
448 self.startedConnection = None
|
|
449 super(DiagramScene, self).mouseReleaseEvent(event)
|
|
450 def startConnection(self, port):
|
|
451 self.startedConnection = Connection(port, None)
|
|
452 pos = port.scenePos()
|
|
453 self.startedConnection.setEndPos(pos)
|
|
454 self.addItem(self.startedConnection)
|
|
455 def deleteItems(self):
|
|
456 for item in list(self.selectedItems()): item.myDelete()
|
89
|
457
|