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