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