44
|
1 #!/usr/bin/python
|
|
2
|
|
3 from PyQt4.QtGui import *
|
|
4 from PyQt4.QtCore import *
|
72
|
5 import sys, xml
|
47
|
6 import xml.dom.minidom as md
|
44
|
7
|
56
|
8 """
|
53
|
9 Author: Windel Bouwman
|
|
10 Year: 2012
|
|
11 Description: This script implements a diagram editor.
|
|
12 run with python 3.x as:
|
|
13 $ python [thisfile.py]
|
44
|
14 """
|
|
15
|
73
|
16 def buildPath(pts):
|
|
17 path = QPainterPath(pts[0])
|
|
18 for pt in pts[1:]:
|
|
19 path.lineTo(pt)
|
|
20 return path
|
55
|
21
|
49
|
22 class Connection(QGraphicsPathItem):
|
53
|
23 """ Implementation of a connection between blocks """
|
44
|
24 def __init__(self, fromPort, toPort):
|
49
|
25 super(Connection, self).__init__()
|
73
|
26 self.pos1, self.pos2 = None, None
|
|
27 self.fromPort, self.toPort = None, None
|
55
|
28 self.setFlag(self.ItemIsSelectable, True)
|
|
29 self.setFlag(self.ItemClipsToShape, True)
|
73
|
30 pen = QPen(Qt.blue, 2)
|
|
31 pen.setCapStyle(Qt.RoundCap)
|
|
32 self.setPen(pen)
|
|
33 self.arrowhead = QGraphicsPathItem(self)
|
|
34 self.arrowhead.setPath(buildPath([QPointF(0.0, 0.0), QPointF(-6.0, 10.0), QPointF(6.0, 10.0), QPointF(0.0, 0.0)]))
|
|
35 self.arrowhead.setPen(pen)
|
|
36 self.arrowhead.setBrush(QBrush(pen.color()))
|
58
|
37 self.vias = []
|
44
|
38 self.setFromPort(fromPort)
|
46
|
39 self.setToPort(toPort)
|
58
|
40 def mouseDoubleClickEvent(self, event):
|
|
41 pos = event.scenePos()
|
60
|
42 pts = [self.pos1] + [v.pos() for v in self.vias] + [self.pos2]
|
|
43 idx = 0
|
|
44 tidx = 0
|
|
45 for p1, p2 in zip(pts[0:-1], pts[1:]):
|
|
46 l1 = QLineF(p1, p2)
|
|
47 l2 = QLineF(p1, pos)
|
|
48 l3 = QLineF(pos, p2)
|
|
49 d = l2.length() + l3.length() - l1.length()
|
|
50 if d < 5:
|
|
51 tidx = idx
|
|
52 idx += 1
|
|
53 self.addHandle(pos, tidx)
|
|
54
|
|
55 def addHandle(self, pos, idx=None):
|
|
56 hi = HandleItem(self)
|
|
57 if idx:
|
|
58 self.vias.insert(idx, hi)
|
58
|
59 else:
|
60
|
60 self.vias.append(hi)
|
|
61 def callback(p):
|
58
|
62 self.updateLineStukken()
|
60
|
63 return p
|
58
|
64 hi.posChangeCallbacks.append(callback)
|
|
65 hi.setPos(pos)
|
|
66 self.updateLineStukken()
|
72
|
67 def myDelete(self):
|
|
68 scene = self.scene()
|
|
69 if scene:
|
|
70 self.setFromPort(None)
|
|
71 self.setToPort(None)
|
|
72 scene.removeItem(self)
|
58
|
73
|
44
|
74 def setFromPort(self, fromPort):
|
53
|
75 if self.fromPort:
|
|
76 self.fromPort.posCallbacks.remove(self.setBeginPos)
|
54
|
77 self.fromPort.connection = None
|
44
|
78 self.fromPort = fromPort
|
|
79 if self.fromPort:
|
54
|
80 self.fromPort.connection = self
|
46
|
81 self.setBeginPos(fromPort.scenePos())
|
44
|
82 self.fromPort.posCallbacks.append(self.setBeginPos)
|
|
83 def setToPort(self, toPort):
|
53
|
84 if self.toPort:
|
|
85 self.toPort.posCallbacks.remove(self.setEndPos)
|
54
|
86 self.toPort.connection = None
|
44
|
87 self.toPort = toPort
|
|
88 if self.toPort:
|
46
|
89 self.setEndPos(toPort.scenePos())
|
54
|
90 self.toPort.connection = self
|
44
|
91 self.toPort.posCallbacks.append(self.setEndPos)
|
|
92 def setBeginPos(self, pos1):
|
|
93 self.pos1 = pos1
|
46
|
94 self.updateLineStukken()
|
44
|
95 def setEndPos(self, endpos):
|
|
96 self.pos2 = endpos
|
46
|
97 self.updateLineStukken()
|
55
|
98 def itemChange(self, change, value):
|
|
99 if change == self.ItemSelectedHasChanged:
|
60
|
100 for via in self.vias:
|
|
101 via.setVisible(value)
|
55
|
102 return super(Connection, self).itemChange(change, value)
|
56
|
103 def shape(self):
|
58
|
104 return self.myshape
|
44
|
105 def updateLineStukken(self):
|
|
106 """
|
|
107 This algorithm determines the optimal routing of all signals.
|
|
108 TODO: implement nice automatic line router
|
|
109 """
|
46
|
110 if self.pos1 is None or self.pos2 is None:
|
|
111 return
|
58
|
112 pts = [self.pos1] + [v.pos() for v in self.vias] + [self.pos2]
|
55
|
113 self.arrowhead.setPos(self.pos2)
|
|
114 if pts[-1].x() < pts[-2].x():
|
|
115 self.arrowhead.setRotation(-90)
|
|
116 else:
|
|
117 self.arrowhead.setRotation(90)
|
73
|
118 self.setPath(buildPath(pts))
|
58
|
119 """ Create a shape outline using the path stroker """
|
|
120 s = super(Connection, self).shape()
|
|
121 pps = QPainterPathStroker()
|
|
122 pps.setWidth(10)
|
|
123 self.myshape = pps.createStroke(s).simplified()
|
44
|
124
|
|
125 class ParameterDialog(QDialog):
|
49
|
126 def __init__(self, block, parent = None):
|
44
|
127 super(ParameterDialog, self).__init__(parent)
|
49
|
128 self.block = block
|
44
|
129 self.button = QPushButton('Ok', self)
|
49
|
130 l = QGridLayout(self)
|
|
131 l.addWidget(QLabel('Name:', self), 0, 0)
|
51
|
132 self.nameEdit = QLineEdit(self.block.name)
|
49
|
133 l.addWidget(self.nameEdit, 0, 1)
|
60
|
134 l.addWidget(QLabel('Code:', self), 1, 0)
|
|
135 self.codeEdit = QTextEdit(self)
|
|
136 self.codeEdit.setPlainText(self.block.code)
|
|
137 l.addWidget(self.codeEdit, 1, 1)
|
|
138 l.addWidget(self.button, 2, 0, 1, 2)
|
44
|
139 self.button.clicked.connect(self.OK)
|
|
140 def OK(self):
|
50
|
141 self.block.setName(self.nameEdit.text())
|
60
|
142 self.block.code = self.codeEdit.toPlainText()
|
50
|
143 self.close()
|
56
|
144
|
53
|
145 class PortItem(QGraphicsPathItem):
|
44
|
146 """ Represents a port to a subsystem """
|
53
|
147 def __init__(self, name, block, direction):
|
|
148 super(PortItem, self).__init__(block)
|
54
|
149 self.connection = None
|
53
|
150 path = QPainterPath()
|
56
|
151 d = 10.0
|
53
|
152 if direction == 'input':
|
|
153 path.moveTo(-d, -d)
|
|
154 path.lineTo(0.0, 0.0)
|
|
155 path.lineTo(-d, d)
|
|
156 else:
|
|
157 path.moveTo(0.0, -d)
|
|
158 path.lineTo(d, 0.0)
|
|
159 path.lineTo(0.0, d)
|
|
160 self.setPath(path)
|
|
161 self.direction = direction
|
50
|
162 self.block = block
|
46
|
163 self.setCursor(QCursor(Qt.CrossCursor))
|
56
|
164 pen = QPen(Qt.blue, 2)
|
|
165 pen.setCapStyle(Qt.RoundCap)
|
|
166 self.setPen(pen)
|
44
|
167 self.name = name
|
50
|
168 self.textItem = QGraphicsTextItem(name, self)
|
53
|
169 self.setName(name)
|
44
|
170 self.posCallbacks = []
|
|
171 self.setFlag(self.ItemSendsScenePositionChanges, True)
|
53
|
172 def setName(self, name):
|
|
173 self.name = name
|
|
174 self.textItem.setPlainText(name)
|
|
175 rect = self.textItem.boundingRect()
|
|
176 lw, lh = rect.width(), rect.height()
|
|
177 if self.direction == 'input':
|
|
178 lx = 3
|
|
179 else:
|
|
180 lx = -3 - lw
|
60
|
181 self.textItem.setPos(lx, -lh / 2)
|
44
|
182 def itemChange(self, change, value):
|
|
183 if change == self.ItemScenePositionHasChanged:
|
|
184 for cb in self.posCallbacks:
|
|
185 cb(value)
|
|
186 return value
|
|
187 return super(PortItem, self).itemChange(change, value)
|
|
188 def mousePressEvent(self, event):
|
54
|
189 if self.direction == 'output':
|
58
|
190 self.scene().startConnection(self)
|
44
|
191
|
53
|
192 class OutputPort(PortItem):
|
|
193 # TODO: create a subclass OR make a member porttype
|
|
194 pass
|
|
195
|
44
|
196 # Block part:
|
|
197 class HandleItem(QGraphicsEllipseItem):
|
|
198 """ A handle that can be moved by the mouse """
|
|
199 def __init__(self, parent=None):
|
60
|
200 dx = 13.0
|
55
|
201 super(HandleItem, self).__init__(QRectF(-0.5*dx,-0.5*dx,dx,dx), parent)
|
44
|
202 self.posChangeCallbacks = []
|
46
|
203 self.setBrush(QBrush(Qt.white))
|
54
|
204 self.setFlag(self.ItemSendsScenePositionChanges, True)
|
|
205 self.setFlag(self.ItemIsMovable, True)
|
60
|
206 self.setVisible(False)
|
46
|
207 self.setCursor(QCursor(Qt.SizeFDiagCursor))
|
55
|
208 def mouseMoveEvent(self, event):
|
|
209 """ Move function without moving the other selected elements """
|
|
210 p = self.mapToParent(event.pos())
|
|
211 self.setPos(p)
|
58
|
212 def mySetPos(self, p):
|
60
|
213 # TODO: use this instead of itemChange?
|
58
|
214 self.setPos(p)
|
44
|
215 def itemChange(self, change, value):
|
|
216 if change == self.ItemPositionChange:
|
|
217 for cb in self.posChangeCallbacks:
|
55
|
218 res = cb(value)
|
44
|
219 if res:
|
55
|
220 value = res
|
44
|
221 return value
|
|
222 # Call superclass method:
|
|
223 return super(HandleItem, self).itemChange(change, value)
|
|
224
|
58
|
225 def uniqify(name, names):
|
|
226 newname = name
|
|
227 i = 1
|
|
228 while newname in names:
|
|
229 newname = name + str(i)
|
|
230 i += 1
|
|
231 return newname
|
|
232
|
44
|
233 class BlockItem(QGraphicsRectItem):
|
|
234 """
|
|
235 Represents a block in the diagram
|
|
236 Has an x and y and width and height
|
|
237 width and height can only be adjusted with a tip in the lower right corner.
|
|
238
|
|
239 - in and output ports
|
|
240 - parameters
|
|
241 - description
|
|
242 """
|
|
243 def __init__(self, name='Untitled', parent=None):
|
|
244 super(BlockItem, self).__init__(parent)
|
|
245 # Properties of the rectangle:
|
46
|
246 self.setPen(QPen(Qt.blue, 2))
|
|
247 self.setBrush(QBrush(Qt.lightGray))
|
44
|
248 self.setFlags(self.ItemIsSelectable | self.ItemIsMovable)
|
60
|
249 self.setFlag(self.ItemSendsScenePositionChanges, True)
|
46
|
250 self.setCursor(QCursor(Qt.PointingHandCursor))
|
44
|
251 self.label = QGraphicsTextItem(name, self)
|
50
|
252 self.name = name
|
60
|
253 self.code = ''
|
44
|
254 # Create corner for resize:
|
|
255 self.sizer = HandleItem(self)
|
|
256 self.sizer.posChangeCallbacks.append(self.changeSize) # Connect the callback
|
58
|
257 button = QPushButton('+in')
|
|
258 button.clicked.connect(self.newInputPort)
|
|
259 self.buttonItemAddInput = QGraphicsProxyWidget(self)
|
|
260 self.buttonItemAddInput.setWidget(button)
|
|
261 self.buttonItemAddInput.setVisible(False)
|
|
262 button = QPushButton('+out')
|
|
263 button.clicked.connect(self.newOutputPort)
|
|
264 self.buttonItemAddOutput = QGraphicsProxyWidget(self)
|
|
265 self.buttonItemAddOutput.setWidget(button)
|
|
266 self.buttonItemAddOutput.setVisible(False)
|
44
|
267
|
|
268 # Inputs and outputs of the block:
|
|
269 self.inputs = []
|
|
270 self.outputs = []
|
|
271 # Update size:
|
60
|
272 self.sizer.mySetPos(QPointF(60, 40)) # This is a better resize function
|
44
|
273 def editParameters(self):
|
49
|
274 pd = ParameterDialog(self, self.window())
|
44
|
275 pd.exec_()
|
59
|
276 def mouseDoubleClickEvent(self, event):
|
|
277 self.editParameters()
|
58
|
278 def newInputPort(self):
|
|
279 names = [i.name for i in self.inputs + self.outputs]
|
|
280 self.addInput(PortItem(uniqify('in', names), self, 'input'))
|
|
281 def newOutputPort(self):
|
|
282 names = [i.name for i in self.inputs + self.outputs]
|
|
283 self.addOutput(PortItem(uniqify('out', names), self, 'output'))
|
50
|
284 def setName(self, name):
|
|
285 self.name = name
|
|
286 self.label.setPlainText(name)
|
48
|
287 def addInput(self, i):
|
|
288 self.inputs.append(i)
|
49
|
289 self.updateSize()
|
48
|
290 def addOutput(self, o):
|
|
291 self.outputs.append(o)
|
49
|
292 self.updateSize()
|
44
|
293
|
|
294 def contextMenuEvent(self, event):
|
|
295 menu = QMenu()
|
|
296 pa = menu.addAction('Parameters')
|
|
297 pa.triggered.connect(self.editParameters)
|
|
298 menu.exec_(event.screenPos())
|
55
|
299 def itemChange(self, change, value):
|
|
300 if change == self.ItemSelectedHasChanged:
|
72
|
301 for child in [self.sizer, self.buttonItemAddInput, self.buttonItemAddOutput]:
|
|
302 child.setVisible(value)
|
55
|
303 return super(BlockItem, self).itemChange(change, value)
|
72
|
304 def myDelete(self):
|
|
305 # TODO: move the below to blockitem:
|
|
306 scene = self.scene()
|
|
307 if scene:
|
|
308 for p in self.inputs + self.outputs:
|
|
309 if p.connection:
|
|
310 p.connection.myDelete()
|
|
311 scene.removeItem(self)
|
44
|
312
|
49
|
313 def updateSize(self):
|
|
314 rect = self.rect()
|
|
315 h, w = rect.height(), rect.width()
|
58
|
316 self.buttonItemAddInput.setPos(0, h + 4)
|
|
317 self.buttonItemAddOutput.setPos(w+10, h+4)
|
72
|
318 for inp in self.inputs:
|
|
319 inp.setX(0.0)
|
|
320 for inp in self.outputs:
|
|
321 inp.setX(w)
|
44
|
322 if len(self.inputs) == 1:
|
53
|
323 self.inputs[0].setPos(0.0, h / 2)
|
44
|
324 elif len(self.inputs) > 1:
|
53
|
325 y = 15
|
|
326 dy = (h - 30) / (len(self.inputs) - 1)
|
44
|
327 for inp in self.inputs:
|
53
|
328 inp.setPos(0.0, y)
|
44
|
329 y += dy
|
|
330 if len(self.outputs) == 1:
|
53
|
331 self.outputs[0].setPos(w, h / 2)
|
44
|
332 elif len(self.outputs) > 1:
|
53
|
333 y = 15
|
|
334 dy = (h - 30) / (len(self.outputs) - 1)
|
44
|
335 for outp in self.outputs:
|
53
|
336 outp.setPos(w, y)
|
44
|
337 y += dy
|
49
|
338
|
55
|
339 def changeSize(self, p):
|
49
|
340 """ Resize block function """
|
55
|
341 w, h = p.x(), p.y()
|
49
|
342 # Limit the block size:
|
72
|
343 h = 20 if h < 20 else h
|
|
344 w = 40 if w < 40 else w
|
49
|
345 self.setRect(0.0, 0.0, w, h)
|
|
346 # center label:
|
|
347 rect = self.label.boundingRect()
|
|
348 lw, lh = rect.width(), rect.height()
|
|
349 lx = (w - lw) / 2
|
|
350 ly = (h - lh) / 2
|
|
351 self.label.setPos(lx, ly)
|
|
352 # Update port positions:
|
|
353 self.updateSize()
|
55
|
354 return QPointF(w, h)
|
44
|
355
|
|
356 class EditorGraphicsView(QGraphicsView):
|
72
|
357 def __init__(self, parent=None):
|
|
358 QGraphicsView.__init__(self, parent)
|
|
359 scene = DiagramScene(self)
|
|
360 self.diagramScene = scene
|
|
361 self.setScene(scene)
|
54
|
362 self.setDragMode(QGraphicsView.RubberBandDrag)
|
72
|
363 testShortcut = QShortcut(QKeySequence("F12"), self)
|
|
364 testShortcut.activated.connect(self.test)
|
|
365 delShort = QShortcut(QKeySequence.Delete, self)
|
|
366 delShort.activated.connect(scene.deleteItems)
|
|
367 self.loadDiagram = scene.loadDiagram
|
|
368 def save(self):
|
|
369 self.diagramScene.saveDiagram('diagram2.usd')
|
|
370 def load(self):
|
|
371 filename = QFileDialog.getOpenFileName(self)
|
|
372 self.diagramScene.loadDiagram(filename)
|
|
373 def zoomAll(self):
|
|
374 """ zoom to fit all items """
|
|
375 rect = self.diagramScene.itemsBoundingRect()
|
|
376 self.fitInView(rect, Qt.KeepAspectRatio)
|
|
377 def test(self):
|
|
378 self.rotate(30)
|
|
379 self.zoomAll()
|
|
380
|
55
|
381 def wheelEvent(self, event):
|
|
382 pos = event.pos()
|
|
383 posbefore = self.mapToScene(pos)
|
|
384 degrees = event.delta() / 8.0
|
|
385 sx = (100.0 + degrees) / 100.0
|
|
386 self.scale(sx, sx)
|
|
387 event.accept()
|
44
|
388 def dragEnterEvent(self, event):
|
|
389 if event.mimeData().hasFormat('component/name'):
|
|
390 event.accept()
|
|
391 def dragMoveEvent(self, event):
|
|
392 if event.mimeData().hasFormat('component/name'):
|
|
393 event.accept()
|
|
394 def dropEvent(self, event):
|
|
395 if event.mimeData().hasFormat('component/name'):
|
48
|
396 name = bytes(event.mimeData().data('component/name')).decode()
|
58
|
397 pos = self.mapToScene(event.pos())
|
|
398 self.scene().addNewBlock(pos, name)
|
44
|
399
|
|
400 class LibraryModel(QStandardItemModel):
|
|
401 def __init__(self, parent=None):
|
|
402 QStandardItemModel.__init__(self, parent)
|
|
403 def mimeTypes(self):
|
|
404 return ['component/name']
|
|
405 def mimeData(self, idxs):
|
|
406 mimedata = QMimeData()
|
|
407 for idx in idxs:
|
|
408 if idx.isValid():
|
45
|
409 txt = self.data(idx, Qt.DisplayRole) # python 3
|
44
|
410 mimedata.setData('component/name', txt)
|
|
411 return mimedata
|
|
412
|
|
413 class DiagramScene(QGraphicsScene):
|
54
|
414 """ Save and load and deletion of item"""
|
44
|
415 def __init__(self, parent=None):
|
|
416 super(DiagramScene, self).__init__(parent)
|
56
|
417 self.startedConnection = None
|
55
|
418
|
46
|
419 def saveDiagram(self, filename):
|
54
|
420 items = self.items()
|
46
|
421 blocks = [item for item in items if type(item) is BlockItem]
|
49
|
422 connections = [item for item in items if type(item) is Connection]
|
47
|
423
|
|
424 doc = md.Document()
|
|
425 modelElement = doc.createElement('system')
|
|
426 doc.appendChild(modelElement)
|
|
427 for block in blocks:
|
|
428 blockElement = doc.createElement("block")
|
|
429 x, y = block.scenePos().x(), block.scenePos().y()
|
|
430 rect = block.rect()
|
|
431 w, h = rect.width(), rect.height()
|
50
|
432 blockElement.setAttribute("name", block.name)
|
49
|
433 blockElement.setAttribute("x", str(int(x)))
|
|
434 blockElement.setAttribute("y", str(int(y)))
|
|
435 blockElement.setAttribute("width", str(int(w)))
|
|
436 blockElement.setAttribute("height", str(int(h)))
|
60
|
437 codeNode = doc.createCDATASection(block.code)
|
|
438 codeElement = doc.createElement('code')
|
|
439 codeElement.appendChild(codeNode)
|
|
440 blockElement.appendChild(codeElement)
|
48
|
441 for inp in block.inputs:
|
|
442 portElement = doc.createElement("input")
|
|
443 portElement.setAttribute("name", inp.name)
|
|
444 blockElement.appendChild(portElement)
|
|
445 for outp in block.outputs:
|
|
446 portElement = doc.createElement("output")
|
|
447 portElement.setAttribute("name", outp.name)
|
|
448 blockElement.appendChild(portElement)
|
47
|
449 modelElement.appendChild(blockElement)
|
49
|
450 for connection in connections:
|
|
451 connectionElement = doc.createElement("connection")
|
|
452 fromPort = connection.fromPort.name
|
|
453 toPort = connection.toPort.name
|
50
|
454 fromBlock = connection.fromPort.block.name
|
|
455 toBlock = connection.toPort.block.name
|
49
|
456 connectionElement.setAttribute("fromBlock", fromBlock)
|
|
457 connectionElement.setAttribute("fromPort", fromPort)
|
|
458 connectionElement.setAttribute("toBlock", toBlock)
|
|
459 connectionElement.setAttribute("toPort", toPort)
|
60
|
460 for via in connection.vias:
|
|
461 viaElement = doc.createElement('via')
|
|
462 viaElement.setAttribute('x', str(int(via.x())))
|
|
463 viaElement.setAttribute('y', str(int(via.y())))
|
|
464 connectionElement.appendChild(viaElement)
|
49
|
465 modelElement.appendChild(connectionElement)
|
46
|
466 with open(filename, 'w') as f:
|
47
|
467 f.write(doc.toprettyxml())
|
46
|
468
|
|
469 def loadDiagram(self, filename):
|
|
470 try:
|
47
|
471 doc = md.parse(filename)
|
46
|
472 except IOError as e:
|
|
473 print('{0} not found'.format(filename))
|
|
474 return
|
60
|
475 except xml.parsers.expat.ExpatError as e:
|
|
476 print('{0}'.format(e))
|
|
477 return
|
47
|
478 sysElements = doc.getElementsByTagName('system')
|
|
479 blockElements = doc.getElementsByTagName('block')
|
|
480 for sysElement in sysElements:
|
|
481 blockElements = sysElement.getElementsByTagName('block')
|
|
482 for blockElement in blockElements:
|
|
483 x = float(blockElement.getAttribute('x'))
|
|
484 y = float(blockElement.getAttribute('y'))
|
|
485 w = float(blockElement.getAttribute('width'))
|
|
486 h = float(blockElement.getAttribute('height'))
|
|
487 name = blockElement.getAttribute('name')
|
|
488 block = BlockItem(name)
|
54
|
489 self.addItem(block)
|
46
|
490 block.setPos(x, y)
|
|
491 block.sizer.setPos(w, h)
|
60
|
492 codeElements = blockElement.getElementsByTagName('code')
|
|
493 if codeElements:
|
|
494 cn = codeElements[0].childNodes
|
|
495 cdatas = [cd for cd in cn if type(cd) is md.CDATASection]
|
|
496 if len(cdatas) > 0:
|
|
497 block.code = cdatas[0].data
|
48
|
498 # Load ports:
|
49
|
499 portElements = blockElement.getElementsByTagName('input')
|
48
|
500 for portElement in portElements:
|
49
|
501 name = portElement.getAttribute('name')
|
53
|
502 inp = PortItem(name, block, 'input')
|
49
|
503 block.addInput(inp)
|
|
504 portElements = blockElement.getElementsByTagName('output')
|
|
505 for portElement in portElements:
|
|
506 name = portElement.getAttribute('name')
|
53
|
507 outp = PortItem(name, block, 'output')
|
49
|
508 block.addOutput(outp)
|
48
|
509 connectionElements = sysElement.getElementsByTagName('connection')
|
|
510 for connectionElement in connectionElements:
|
50
|
511 fromBlock = connectionElement.getAttribute('fromBlock')
|
|
512 fromPort = connectionElement.getAttribute('fromPort')
|
|
513 toBlock = connectionElement.getAttribute('toBlock')
|
|
514 toPort = connectionElement.getAttribute('toPort')
|
60
|
515 viaElements = connectionElement.getElementsByTagName('via')
|
50
|
516 fromPort = self.findPort(fromBlock, fromPort)
|
|
517 toPort = self.findPort(toBlock, toPort)
|
|
518 connection = Connection(fromPort, toPort)
|
60
|
519 for viaElement in viaElements:
|
|
520 x = int(viaElement.getAttribute('x'))
|
|
521 y = int(viaElement.getAttribute('y'))
|
|
522 connection.addHandle(QPointF(x, y))
|
54
|
523 self.addItem(connection)
|
50
|
524 def findPort(self, blockname, portname):
|
54
|
525 items = self.items()
|
50
|
526 blocks = [item for item in items if type(item) is BlockItem]
|
|
527 for block in [b for b in blocks if b.name == blockname]:
|
|
528 for port in block.inputs + block.outputs:
|
|
529 if port.name == portname:
|
|
530 return port
|
58
|
531 def addNewBlock(self, pos, name):
|
|
532 blocknames = [item.name for item in self.items() if type(item) is BlockItem]
|
|
533 b1 = BlockItem(uniqify(name, blocknames))
|
|
534 b1.setPos(pos)
|
|
535 self.addItem(b1)
|
56
|
536 def mouseMoveEvent(self, event):
|
|
537 if self.startedConnection:
|
|
538 pos = event.scenePos()
|
|
539 self.startedConnection.setEndPos(pos)
|
|
540 super(DiagramScene, self).mouseMoveEvent(event)
|
|
541 def mouseReleaseEvent(self, event):
|
|
542 if self.startedConnection:
|
|
543 items = self.items(event.scenePos())
|
|
544 for item in items:
|
|
545 if type(item) is PortItem:
|
|
546 self.startedConnection.setToPort(item)
|
|
547 self.startedConnection = None
|
|
548 return
|
72
|
549 self.startedConnection.myDelete()
|
56
|
550 self.startedConnection = None
|
|
551 super(DiagramScene, self).mouseReleaseEvent(event)
|
|
552 def startConnection(self, port):
|
|
553 self.startedConnection = Connection(port, None)
|
|
554 pos = port.scenePos()
|
|
555 self.startedConnection.setEndPos(pos)
|
|
556 self.addItem(self.startedConnection)
|
72
|
557 def deleteItems(self):
|
|
558 # Try to delete all currently selected items:
|
|
559 for item in list(self.selectedItems()):
|
|
560 item.myDelete()
|
61
|
561
|
|
562 class LibraryWidget(QListView):
|
|
563 def __init__(self):
|
|
564 super(LibraryWidget, self).__init__(None)
|
54
|
565 self.libraryModel = LibraryModel(self)
|
|
566 self.libraryModel.setColumnCount(1)
|
|
567 # Create an icon with an icon:
|
|
568 pixmap = QPixmap(60, 60)
|
|
569 pixmap.fill()
|
|
570 painter = QPainter(pixmap)
|
|
571 painter.fillRect(10, 10, 40, 40, Qt.blue)
|
|
572 painter.setBrush(Qt.yellow)
|
|
573 painter.drawEllipse(20, 20, 20, 20)
|
|
574 painter.end()
|
|
575
|
|
576 # Fill library:
|
|
577 self.libItems = []
|
|
578 self.libItems.append( QStandardItem(QIcon(pixmap), 'Block') )
|
|
579 self.libItems.append( QStandardItem(QIcon(pixmap), 'Uber Unit') )
|
|
580 self.libItems.append( QStandardItem(QIcon(pixmap), 'Device') )
|
|
581 for i in self.libItems:
|
|
582 self.libraryModel.appendRow(i)
|
61
|
583 self.setModel(self.libraryModel)
|
|
584 self.setViewMode(self.IconMode)
|
|
585 self.setDragDropMode(self.DragOnly)
|
54
|
586
|
61
|
587 class Main(QMainWindow):
|
|
588 def __init__(self):
|
|
589 super(Main, self).__init__(None)
|
72
|
590 self.editor = EditorGraphicsView()
|
61
|
591 self.setCentralWidget(self.editor)
|
|
592 self.setWindowTitle("Diagram editor")
|
|
593 toolbar = self.addToolBar('Tools')
|
72
|
594 def act(name, shortcut, callback):
|
|
595 a = QAction(name, self)
|
|
596 a.setShortcuts(shortcut)
|
|
597 a.triggered.connect(callback)
|
|
598 toolbar.addAction(a)
|
|
599 act('Save', QKeySequence.Save, self.editor.save)
|
|
600 act('Load', QKeySequence.Open, self.editor.load)
|
|
601 act('Full screen', QKeySequence("F11"), self.toggleFullScreen)
|
|
602 act('Fit in view', QKeySequence("F8"), self.editor.zoomAll)
|
54
|
603
|
61
|
604 self.library = LibraryWidget()
|
|
605 libraryDock = QDockWidget('Library', self)
|
|
606 libraryDock.setWidget(self.library)
|
|
607 self.addDockWidget(Qt.LeftDockWidgetArea, libraryDock)
|
|
608
|
|
609 self.editor.loadDiagram('diagram2.usd')
|
|
610
|
44
|
611 def toggleFullScreen(self):
|
|
612 self.setWindowState(self.windowState() ^ Qt.WindowFullScreen)
|
61
|
613 self.editor.zoomAll()
|
44
|
614
|
|
615 if __name__ == '__main__':
|
45
|
616 if sys.version_info.major != 3:
|
|
617 print('Please use python 3.x')
|
|
618 sys.exit(1)
|
|
619
|
46
|
620 app = QApplication(sys.argv)
|
61
|
621 main = Main()
|
|
622 main.show()
|
|
623 main.resize(700, 500)
|
|
624 main.editor.zoomAll()
|
44
|
625 app.exec_()
|
|
626
|