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
|
|
8 """
|
|
9 This script implements a basic diagram editor.
|
|
10 """
|
|
11
|
|
12 class Connection:
|
|
13 """
|
|
14 - fromPort
|
|
15 - list of line items in between
|
|
16 - toPort
|
|
17 """
|
|
18 def __init__(self, fromPort, toPort):
|
|
19 self.pos1 = None
|
|
20 self.pos2 = None
|
46
|
21 self.pathItem = QGraphicsPathItem()
|
|
22 pen = QPen()
|
|
23 pen.setWidth(4)
|
|
24 pen.setColor(Qt.blue)
|
|
25 pen.setCapStyle(Qt.RoundCap)
|
|
26 self.pathItem.setPen(pen)
|
|
27 #self.pathItem.setFlags(self.pathItem.ItemIsSelectable)
|
|
28 editor.diagramScene.addItem(self.pathItem)
|
44
|
29 self.setFromPort(fromPort)
|
46
|
30 self.setToPort(toPort)
|
44
|
31 def setFromPort(self, fromPort):
|
|
32 self.fromPort = fromPort
|
|
33 if self.fromPort:
|
46
|
34 self.setBeginPos(fromPort.scenePos())
|
44
|
35 self.fromPort.posCallbacks.append(self.setBeginPos)
|
|
36 def setToPort(self, toPort):
|
|
37 self.toPort = toPort
|
|
38 if self.toPort:
|
46
|
39 self.setEndPos(toPort.scenePos())
|
44
|
40 self.toPort.posCallbacks.append(self.setEndPos)
|
|
41 def setBeginPos(self, pos1):
|
|
42 self.pos1 = pos1
|
46
|
43 self.updateLineStukken()
|
44
|
44 def setEndPos(self, endpos):
|
|
45 self.pos2 = endpos
|
46
|
46 self.updateLineStukken()
|
44
|
47 def updateLineStukken(self):
|
|
48 """
|
|
49 This algorithm determines the optimal routing of all signals.
|
|
50 TODO: implement nice automatic line router
|
|
51 """
|
46
|
52 if self.pos1 is None or self.pos2 is None:
|
|
53 return
|
44
|
54
|
|
55 ds = editor.diagramScene
|
|
56
|
46
|
57 # TODO: create pieces of lines.
|
|
58
|
|
59 # Determine the begin and end positions:
|
|
60 p1 = self.pos1
|
|
61 p4 = self.pos2
|
|
62 x1, y1 = self.pos1.x(), self.pos1.y()
|
|
63 x4, y4 = self.pos2.x(), self.pos2.y()
|
|
64
|
|
65 def stripHits(hits):
|
|
66 """ Helper function that removes object hits """
|
|
67 hits = [hit for hit in hits if type(hit) is BlockItem]
|
|
68 if self.pathItem in hits:
|
|
69 hits.remove(self.pathItem)
|
|
70 if self.fromPort in hits:
|
|
71 hits.remove(self.fromPort)
|
|
72 if self.toPort in hits:
|
|
73 hits.remove(self.toPort)
|
|
74 return hits
|
|
75
|
|
76 def viaPoints(pA, pB):
|
|
77 # Construct intermediate points:
|
|
78
|
|
79 pAB1 = QPointF(pA.x(), pB.y())
|
|
80 pAB2 = QPointF(pB.x(), pA.y())
|
|
81 path1 = QPainterPath(pA)
|
|
82 path1.lineTo(pAB1)
|
|
83 path2 = QPainterPath(pA)
|
|
84 path2.lineTo(pAB2)
|
|
85 if len(stripHits(ds.items(path1))) > len(stripHits(ds.items(path2))):
|
|
86 pAB = pAB2
|
|
87 else:
|
|
88 pAB = pAB1
|
|
89 return [pAB]
|
|
90
|
|
91 # Determine left or right:
|
|
92 dx = QPointF(10, 0)
|
|
93 if len(stripHits(ds.items(p1 + dx))) > len(stripHits(ds.items(p1 - dx))):
|
|
94 p2 = p1 - dx
|
44
|
95 else:
|
46
|
96 p2 = p1 + dx
|
|
97
|
|
98 if len(stripHits(ds.items(p4 + dx))) > len(stripHits(ds.items(p4 - dx))):
|
|
99 p3 = p4 - dx
|
|
100 else:
|
|
101 p3 = p4 + dx
|
|
102
|
|
103 path = QPainterPath(p1)
|
|
104 path.lineTo(p2)
|
|
105 # Now move from p2 to p3 without hitting blocks:
|
|
106 pts = viaPoints(p2, p3)
|
|
107 for pt in pts:
|
|
108 path.lineTo(pt)
|
|
109 path.lineTo(p3)
|
|
110 path.lineTo(p4)
|
|
111
|
|
112 hits = stripHits(ds.items(path))
|
|
113
|
|
114 #print('Items:', hits)
|
|
115 self.pathItem.setPath(path)
|
44
|
116
|
|
117 def delete(self):
|
46
|
118 editor.diagramScene.removeItem(self.pathItem)
|
44
|
119 # Remove position update callbacks:
|
|
120
|
|
121 class ParameterDialog(QDialog):
|
46
|
122 def __init__(self, parent = None):
|
44
|
123 super(ParameterDialog, self).__init__(parent)
|
|
124 self.button = QPushButton('Ok', self)
|
|
125 l = QVBoxLayout(self)
|
|
126 l.addWidget(self.button)
|
|
127 self.button.clicked.connect(self.OK)
|
|
128 def OK(self):
|
|
129 self.close()
|
|
130
|
|
131 class PortItem(QGraphicsEllipseItem):
|
|
132 """ Represents a port to a subsystem """
|
|
133 def __init__(self, name, parent=None):
|
|
134 QGraphicsEllipseItem.__init__(self, QRectF(-6,-6,12.0,12.0), parent)
|
46
|
135 self.setCursor(QCursor(Qt.CrossCursor))
|
44
|
136 # Properties:
|
|
137 self.setBrush(QBrush(Qt.red))
|
|
138 # Name:
|
|
139 self.name = name
|
|
140 self.posCallbacks = []
|
|
141 self.setFlag(self.ItemSendsScenePositionChanges, True)
|
|
142 def itemChange(self, change, value):
|
|
143 if change == self.ItemScenePositionHasChanged:
|
|
144 for cb in self.posCallbacks:
|
|
145 cb(value)
|
|
146 return value
|
|
147 return super(PortItem, self).itemChange(change, value)
|
|
148 def mousePressEvent(self, event):
|
|
149 editor.startConnection(self)
|
|
150
|
|
151 # Block part:
|
|
152 class HandleItem(QGraphicsEllipseItem):
|
|
153 """ A handle that can be moved by the mouse """
|
|
154 def __init__(self, parent=None):
|
|
155 super(HandleItem, self).__init__(QRectF(-4.0,-4.0,8.0,8.0), parent)
|
|
156 self.posChangeCallbacks = []
|
46
|
157 self.setBrush(QBrush(Qt.white))
|
|
158 self.setFlags(self.ItemIsMovable | self.ItemSendsScenePositionChanges)
|
|
159 self.setCursor(QCursor(Qt.SizeFDiagCursor))
|
44
|
160
|
|
161 def itemChange(self, change, value):
|
|
162 if change == self.ItemPositionChange:
|
45
|
163 #value = value.toPointF()
|
44
|
164 x, y = value.x(), value.y()
|
|
165 # TODO: make this a signal?
|
|
166 # This cannot be a signal because this is not a QObject
|
|
167 for cb in self.posChangeCallbacks:
|
|
168 res = cb(x, y)
|
|
169 if res:
|
|
170 x, y = res
|
|
171 value = QPointF(x, y)
|
|
172 return value
|
|
173 # Call superclass method:
|
|
174 return super(HandleItem, self).itemChange(change, value)
|
|
175
|
|
176 class BlockItem(QGraphicsRectItem):
|
|
177 """
|
|
178 Represents a block in the diagram
|
|
179 Has an x and y and width and height
|
|
180 width and height can only be adjusted with a tip in the lower right corner.
|
|
181
|
|
182 - in and output ports
|
|
183 - parameters
|
|
184 - description
|
|
185 """
|
|
186 def __init__(self, name='Untitled', parent=None):
|
|
187 super(BlockItem, self).__init__(parent)
|
|
188 w = 60.0
|
|
189 h = 40.0
|
|
190 # Properties of the rectangle:
|
46
|
191 self.setPen(QPen(Qt.blue, 2))
|
|
192 self.setBrush(QBrush(Qt.lightGray))
|
44
|
193 self.setFlags(self.ItemIsSelectable | self.ItemIsMovable)
|
46
|
194 self.setCursor(QCursor(Qt.PointingHandCursor))
|
44
|
195 # Label:
|
|
196 self.label = QGraphicsTextItem(name, self)
|
|
197 # Create corner for resize:
|
|
198 self.sizer = HandleItem(self)
|
|
199 self.sizer.setPos(w, h)
|
|
200 self.sizer.posChangeCallbacks.append(self.changeSize) # Connect the callback
|
|
201 #self.sizer.setVisible(False)
|
|
202 self.sizer.setFlag(self.sizer.ItemIsSelectable, True)
|
|
203
|
|
204 # Inputs and outputs of the block:
|
|
205 self.inputs = []
|
|
206 self.inputs.append( PortItem('a', self) )
|
|
207 self.inputs.append( PortItem('b', self) )
|
|
208 self.inputs.append( PortItem('c', self) )
|
|
209 self.outputs = []
|
|
210 self.outputs.append( PortItem('y', self) )
|
|
211 # Update size:
|
|
212 self.changeSize(w, h)
|
|
213 def editParameters(self):
|
|
214 pd = ParameterDialog(self.window())
|
|
215 pd.exec_()
|
48
|
216 def addInput(self, i):
|
|
217 self.inputs.append(i)
|
|
218 def addOutput(self, o):
|
|
219 self.outputs.append(o)
|
44
|
220
|
|
221 def contextMenuEvent(self, event):
|
|
222 menu = QMenu()
|
46
|
223 da = menu.addAction('Delete')
|
|
224 da.triggered.connect(self.delete)
|
44
|
225 pa = menu.addAction('Parameters')
|
|
226 pa.triggered.connect(self.editParameters)
|
|
227 menu.exec_(event.screenPos())
|
|
228
|
46
|
229 def delete(self):
|
|
230 editor.diagramScene.removeItem(self)
|
|
231 # TODO: remove connections
|
|
232
|
44
|
233 def changeSize(self, w, h):
|
|
234 """ Resize block function """
|
|
235 # Limit the block size:
|
|
236 if h < 20:
|
|
237 h = 20
|
|
238 if w < 40:
|
|
239 w = 40
|
|
240 self.setRect(0.0, 0.0, w, h)
|
|
241 # center label:
|
|
242 rect = self.label.boundingRect()
|
|
243 lw, lh = rect.width(), rect.height()
|
|
244 lx = (w - lw) / 2
|
|
245 ly = (h - lh) / 2
|
|
246 self.label.setPos(lx, ly)
|
|
247 # Update port positions:
|
|
248 if len(self.inputs) == 1:
|
|
249 self.inputs[0].setPos(-4, h / 2)
|
|
250 elif len(self.inputs) > 1:
|
|
251 y = 5
|
|
252 dy = (h - 10) / (len(self.inputs) - 1)
|
|
253 for inp in self.inputs:
|
|
254 inp.setPos(-4, y)
|
|
255 y += dy
|
|
256 if len(self.outputs) == 1:
|
|
257 self.outputs[0].setPos(w+4, h / 2)
|
|
258 elif len(self.outputs) > 1:
|
|
259 y = 5
|
|
260 dy = (h - 10) / (len(self.outputs) + 0)
|
|
261 for outp in self.outputs:
|
|
262 outp.setPos(w+4, y)
|
|
263 y += dy
|
|
264 return w, h
|
|
265
|
|
266 class EditorGraphicsView(QGraphicsView):
|
|
267 def __init__(self, scene, parent=None):
|
|
268 QGraphicsView.__init__(self, scene, parent)
|
|
269 def dragEnterEvent(self, event):
|
|
270 if event.mimeData().hasFormat('component/name'):
|
|
271 event.accept()
|
|
272 def dragMoveEvent(self, event):
|
|
273 if event.mimeData().hasFormat('component/name'):
|
|
274 event.accept()
|
|
275 def dropEvent(self, event):
|
|
276 if event.mimeData().hasFormat('component/name'):
|
48
|
277 name = bytes(event.mimeData().data('component/name')).decode()
|
44
|
278 b1 = BlockItem(name)
|
48
|
279 print(event.pos())
|
44
|
280 b1.setPos(self.mapToScene(event.pos()))
|
48
|
281 print(self.mapToScene(event.pos()))
|
44
|
282 self.scene().addItem(b1)
|
|
283
|
|
284 class LibraryModel(QStandardItemModel):
|
|
285 def __init__(self, parent=None):
|
|
286 QStandardItemModel.__init__(self, parent)
|
|
287 def mimeTypes(self):
|
|
288 return ['component/name']
|
|
289 def mimeData(self, idxs):
|
|
290 mimedata = QMimeData()
|
|
291 for idx in idxs:
|
|
292 if idx.isValid():
|
45
|
293 #txt = self.data(idx, Qt.DisplayRole).toByteArray() # python2
|
|
294 txt = self.data(idx, Qt.DisplayRole) # python 3
|
44
|
295 mimedata.setData('component/name', txt)
|
|
296 return mimedata
|
|
297
|
|
298 class DiagramScene(QGraphicsScene):
|
|
299 def __init__(self, parent=None):
|
|
300 super(DiagramScene, self).__init__(parent)
|
|
301 def mouseMoveEvent(self, mouseEvent):
|
|
302 editor.sceneMouseMoveEvent(mouseEvent)
|
|
303 super(DiagramScene, self).mouseMoveEvent(mouseEvent)
|
|
304 def mouseReleaseEvent(self, mouseEvent):
|
|
305 editor.sceneMouseReleaseEvent(mouseEvent)
|
|
306 super(DiagramScene, self).mouseReleaseEvent(mouseEvent)
|
|
307
|
|
308 class DiagramEditor(QWidget):
|
|
309 def __init__(self, parent=None):
|
46
|
310 QWidget.__init__(self, parent)
|
44
|
311 self.setWindowTitle("Diagram editor")
|
|
312
|
|
313 # Widget layout and child widgets:
|
46
|
314 self.horizontalLayout = QHBoxLayout(self)
|
|
315 self.libraryBrowserView = QListView(self)
|
45
|
316 self.libraryBrowserView.setMaximumWidth(160)
|
44
|
317 self.libraryModel = LibraryModel(self)
|
|
318 self.libraryModel.setColumnCount(1)
|
|
319 # Create an icon with an icon:
|
|
320 pixmap = QPixmap(60, 60)
|
|
321 pixmap.fill()
|
|
322 painter = QPainter(pixmap)
|
|
323 painter.fillRect(10, 10, 40, 40, Qt.blue)
|
|
324 painter.setBrush(Qt.red)
|
|
325 painter.drawEllipse(36, 2, 20, 20)
|
|
326 painter.setBrush(Qt.yellow)
|
|
327 painter.drawEllipse(20, 20, 20, 20)
|
|
328 painter.end()
|
|
329
|
|
330 self.libItems = []
|
46
|
331 self.libItems.append( QStandardItem(QIcon(pixmap), 'Block') )
|
|
332 self.libItems.append( QStandardItem(QIcon(pixmap), 'Uber Unit') )
|
|
333 self.libItems.append( QStandardItem(QIcon(pixmap), 'Device') )
|
44
|
334 for i in self.libItems:
|
|
335 self.libraryModel.appendRow(i)
|
|
336 self.libraryBrowserView.setModel(self.libraryModel)
|
|
337 self.libraryBrowserView.setViewMode(self.libraryBrowserView.IconMode)
|
|
338 self.libraryBrowserView.setDragDropMode(self.libraryBrowserView.DragOnly)
|
|
339
|
|
340 self.diagramScene = DiagramScene(self)
|
|
341 self.diagramView = EditorGraphicsView(self.diagramScene, self)
|
|
342 self.horizontalLayout.addWidget(self.libraryBrowserView)
|
|
343 self.horizontalLayout.addWidget(self.diagramView)
|
|
344
|
|
345 self.startedConnection = None
|
|
346 fullScreenShortcut = QShortcut(QKeySequence("F11"), self)
|
|
347 fullScreenShortcut.activated.connect(self.toggleFullScreen)
|
46
|
348 saveShortcut = QShortcut(QKeySequence(QKeySequence.Save), self)
|
|
349 saveShortcut.activated.connect(self.save)
|
48
|
350 testShortcut = QShortcut(QKeySequence("F12"), self)
|
|
351 testShortcut.activated.connect(self.test)
|
|
352 zoomShortcut = QShortcut(QKeySequence("F8"), self)
|
|
353 zoomShortcut.activated.connect(self.zoomAll)
|
47
|
354 self.loadDiagram('diagram2.usd')
|
46
|
355
|
48
|
356 def test(self):
|
|
357 self.diagramView.rotate(11)
|
46
|
358 def save(self):
|
47
|
359 self.saveDiagram('diagram2.usd')
|
46
|
360
|
|
361 def saveDiagram(self, filename):
|
|
362 items = self.diagramScene.items()
|
|
363 blocks = [item for item in items if type(item) is BlockItem]
|
47
|
364
|
|
365 doc = md.Document()
|
|
366 modelElement = doc.createElement('system')
|
|
367 doc.appendChild(modelElement)
|
|
368 for block in blocks:
|
|
369 blockElement = doc.createElement("block")
|
|
370 x, y = block.scenePos().x(), block.scenePos().y()
|
|
371 rect = block.rect()
|
|
372 w, h = rect.width(), rect.height()
|
|
373 blockElement.setAttribute("name", block.label.toPlainText())
|
|
374 blockElement.setAttribute("x", str(x))
|
|
375 blockElement.setAttribute("y", str(y))
|
|
376 blockElement.setAttribute("width", str(w))
|
|
377 blockElement.setAttribute("height", str(h))
|
48
|
378 for inp in block.inputs:
|
|
379 portElement = doc.createElement("input")
|
|
380 portElement.setAttribute("name", inp.name)
|
|
381 blockElement.appendChild(portElement)
|
|
382 for outp in block.outputs:
|
|
383 portElement = doc.createElement("output")
|
|
384 portElement.setAttribute("name", outp.name)
|
|
385 blockElement.appendChild(portElement)
|
47
|
386 modelElement.appendChild(blockElement)
|
46
|
387 with open(filename, 'w') as f:
|
47
|
388 f.write(doc.toprettyxml())
|
46
|
389
|
|
390 def loadDiagram(self, filename):
|
|
391 try:
|
47
|
392 doc = md.parse(filename)
|
46
|
393 except IOError as e:
|
|
394 print('{0} not found'.format(filename))
|
|
395 return
|
47
|
396 sysElements = doc.getElementsByTagName('system')
|
|
397 blockElements = doc.getElementsByTagName('block')
|
|
398 for sysElement in sysElements:
|
|
399 blockElements = sysElement.getElementsByTagName('block')
|
|
400 for blockElement in blockElements:
|
|
401 x = float(blockElement.getAttribute('x'))
|
|
402 y = float(blockElement.getAttribute('y'))
|
|
403 w = float(blockElement.getAttribute('width'))
|
|
404 h = float(blockElement.getAttribute('height'))
|
|
405 name = blockElement.getAttribute('name')
|
|
406 block = BlockItem(name)
|
46
|
407 self.diagramScene.addItem(block)
|
|
408 block.setPos(x, y)
|
|
409 block.sizer.setPos(w, h)
|
48
|
410 # Load ports:
|
|
411 portElements = blockElement.getElementsByTagName('port')
|
|
412 for portElement in portElements:
|
|
413 print(portElement)
|
|
414 connectionElements = sysElement.getElementsByTagName('connection')
|
|
415 for connectionElement in connectionElements:
|
|
416 print(connectionElement)
|
|
417 self.zoomAll()
|
47
|
418
|
44
|
419 def toggleFullScreen(self):
|
|
420 self.setWindowState(self.windowState() ^ Qt.WindowFullScreen)
|
|
421 def startConnection(self, port):
|
|
422 self.startedConnection = Connection(port, None)
|
48
|
423 def zoomAll(self):
|
|
424 """ zoom to fit all items """
|
|
425 rect = self.diagramScene.itemsBoundingRect()
|
|
426 print(rect)
|
|
427 self.diagramView.fitInView(rect, Qt.KeepAspectRatio)
|
44
|
428 def sceneMouseMoveEvent(self, event):
|
|
429 if self.startedConnection:
|
|
430 pos = event.scenePos()
|
|
431 self.startedConnection.setEndPos(pos)
|
|
432 def sceneMouseReleaseEvent(self, event):
|
|
433 # Clear the actual connection:
|
|
434 if self.startedConnection:
|
46
|
435 items = self.diagramScene.items(event.scenePos())
|
44
|
436 for item in items:
|
|
437 if type(item) is PortItem:
|
|
438 self.startedConnection.setToPort(item)
|
46
|
439 self.startedConnection = None
|
|
440 return
|
|
441 self.startedConnection.delete()
|
|
442 del self.startedConnection
|
44
|
443 self.startedConnection = None
|
|
444
|
|
445 if __name__ == '__main__':
|
45
|
446 if sys.version_info.major != 3:
|
|
447 print('Please use python 3.x')
|
|
448 sys.exit(1)
|
|
449
|
46
|
450 app = QApplication(sys.argv)
|
44
|
451 global editor
|
|
452 editor = DiagramEditor()
|
|
453 editor.show()
|
48
|
454 editor.resize(700, 500)
|
44
|
455 app.exec_()
|
|
456
|