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