44
|
1 #!/usr/bin/python
|
|
2
|
|
3 from PyQt4.QtGui import *
|
|
4 from PyQt4.QtCore import *
|
|
5 import sys
|
46
|
6 from elementtree.SimpleXMLWriter import XMLWriter
|
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_()
|
|
216
|
|
217 def contextMenuEvent(self, event):
|
|
218 menu = QMenu()
|
46
|
219 da = menu.addAction('Delete')
|
|
220 da.triggered.connect(self.delete)
|
44
|
221 pa = menu.addAction('Parameters')
|
|
222 pa.triggered.connect(self.editParameters)
|
|
223 menu.exec_(event.screenPos())
|
|
224
|
46
|
225 def delete(self):
|
|
226 editor.diagramScene.removeItem(self)
|
|
227 # TODO: remove connections
|
|
228
|
44
|
229 def changeSize(self, w, h):
|
|
230 """ Resize block function """
|
|
231 # Limit the block size:
|
|
232 if h < 20:
|
|
233 h = 20
|
|
234 if w < 40:
|
|
235 w = 40
|
|
236 self.setRect(0.0, 0.0, w, h)
|
|
237 # center label:
|
|
238 rect = self.label.boundingRect()
|
|
239 lw, lh = rect.width(), rect.height()
|
|
240 lx = (w - lw) / 2
|
|
241 ly = (h - lh) / 2
|
|
242 self.label.setPos(lx, ly)
|
|
243 # Update port positions:
|
|
244 if len(self.inputs) == 1:
|
|
245 self.inputs[0].setPos(-4, h / 2)
|
|
246 elif len(self.inputs) > 1:
|
|
247 y = 5
|
|
248 dy = (h - 10) / (len(self.inputs) - 1)
|
|
249 for inp in self.inputs:
|
|
250 inp.setPos(-4, y)
|
|
251 y += dy
|
|
252 if len(self.outputs) == 1:
|
|
253 self.outputs[0].setPos(w+4, h / 2)
|
|
254 elif len(self.outputs) > 1:
|
|
255 y = 5
|
|
256 dy = (h - 10) / (len(self.outputs) + 0)
|
|
257 for outp in self.outputs:
|
|
258 outp.setPos(w+4, y)
|
|
259 y += dy
|
|
260 return w, h
|
|
261
|
|
262 class EditorGraphicsView(QGraphicsView):
|
|
263 def __init__(self, scene, parent=None):
|
|
264 QGraphicsView.__init__(self, scene, parent)
|
|
265 def dragEnterEvent(self, event):
|
|
266 if event.mimeData().hasFormat('component/name'):
|
|
267 event.accept()
|
|
268 def dragMoveEvent(self, event):
|
|
269 if event.mimeData().hasFormat('component/name'):
|
|
270 event.accept()
|
|
271 def dropEvent(self, event):
|
|
272 if event.mimeData().hasFormat('component/name'):
|
|
273 name = str(event.mimeData().data('component/name'))
|
|
274 b1 = BlockItem(name)
|
|
275 b1.setPos(self.mapToScene(event.pos()))
|
|
276 self.scene().addItem(b1)
|
|
277
|
|
278 class LibraryModel(QStandardItemModel):
|
|
279 def __init__(self, parent=None):
|
|
280 QStandardItemModel.__init__(self, parent)
|
|
281 def mimeTypes(self):
|
|
282 return ['component/name']
|
|
283 def mimeData(self, idxs):
|
|
284 mimedata = QMimeData()
|
|
285 for idx in idxs:
|
|
286 if idx.isValid():
|
45
|
287 #txt = self.data(idx, Qt.DisplayRole).toByteArray() # python2
|
|
288 txt = self.data(idx, Qt.DisplayRole) # python 3
|
44
|
289 mimedata.setData('component/name', txt)
|
|
290 return mimedata
|
|
291
|
|
292 class DiagramScene(QGraphicsScene):
|
|
293 def __init__(self, parent=None):
|
|
294 super(DiagramScene, self).__init__(parent)
|
|
295 def mouseMoveEvent(self, mouseEvent):
|
|
296 editor.sceneMouseMoveEvent(mouseEvent)
|
|
297 super(DiagramScene, self).mouseMoveEvent(mouseEvent)
|
|
298 def mouseReleaseEvent(self, mouseEvent):
|
|
299 editor.sceneMouseReleaseEvent(mouseEvent)
|
|
300 super(DiagramScene, self).mouseReleaseEvent(mouseEvent)
|
|
301
|
|
302 class DiagramEditor(QWidget):
|
|
303 def __init__(self, parent=None):
|
46
|
304 QWidget.__init__(self, parent)
|
44
|
305 self.setWindowTitle("Diagram editor")
|
|
306
|
|
307 # Widget layout and child widgets:
|
46
|
308 self.horizontalLayout = QHBoxLayout(self)
|
|
309 self.libraryBrowserView = QListView(self)
|
45
|
310 self.libraryBrowserView.setMaximumWidth(160)
|
44
|
311 self.libraryModel = LibraryModel(self)
|
|
312 self.libraryModel.setColumnCount(1)
|
|
313 # Create an icon with an icon:
|
|
314 pixmap = QPixmap(60, 60)
|
|
315 pixmap.fill()
|
|
316 painter = QPainter(pixmap)
|
|
317 painter.fillRect(10, 10, 40, 40, Qt.blue)
|
|
318 painter.setBrush(Qt.red)
|
|
319 painter.drawEllipse(36, 2, 20, 20)
|
|
320 painter.setBrush(Qt.yellow)
|
|
321 painter.drawEllipse(20, 20, 20, 20)
|
|
322 painter.end()
|
|
323
|
|
324 self.libItems = []
|
46
|
325 self.libItems.append( QStandardItem(QIcon(pixmap), 'Block') )
|
|
326 self.libItems.append( QStandardItem(QIcon(pixmap), 'Uber Unit') )
|
|
327 self.libItems.append( QStandardItem(QIcon(pixmap), 'Device') )
|
44
|
328 for i in self.libItems:
|
|
329 self.libraryModel.appendRow(i)
|
|
330 self.libraryBrowserView.setModel(self.libraryModel)
|
|
331 self.libraryBrowserView.setViewMode(self.libraryBrowserView.IconMode)
|
|
332 self.libraryBrowserView.setDragDropMode(self.libraryBrowserView.DragOnly)
|
|
333
|
|
334 self.diagramScene = DiagramScene(self)
|
|
335 self.diagramView = EditorGraphicsView(self.diagramScene, self)
|
|
336 self.horizontalLayout.addWidget(self.libraryBrowserView)
|
|
337 self.horizontalLayout.addWidget(self.diagramView)
|
|
338
|
|
339 self.startedConnection = None
|
|
340 fullScreenShortcut = QShortcut(QKeySequence("F11"), self)
|
|
341 fullScreenShortcut.activated.connect(self.toggleFullScreen)
|
46
|
342 saveShortcut = QShortcut(QKeySequence(QKeySequence.Save), self)
|
|
343 saveShortcut.activated.connect(self.save)
|
|
344 self.loadDiagram('diagram.txt')
|
|
345
|
|
346 def save(self):
|
|
347 self.saveDiagram2('diagram2.txt')
|
|
348 def saveDiagram2(self, filename):
|
|
349 items = self.diagramScene.items()
|
|
350 blocks = [item for item in items if type(item) is BlockItem]
|
|
351 with open(filename, 'w') as f:
|
|
352 w = XMLWriter(f)
|
|
353 model = w.start('model')
|
|
354 for block in blocks:
|
|
355 w.element("block")
|
|
356
|
|
357 w.close(model)
|
|
358 def saveDiagram(self, filename):
|
|
359 items = self.diagramScene.items()
|
|
360 blocks = [item for item in items if type(item) is BlockItem]
|
|
361 with open(filename, 'w') as f:
|
|
362 for block in blocks:
|
|
363 rect = block.rect()
|
|
364 x, y, w, h = block.scenePos().x(), block.scenePos().y(), rect.width(), rect.height()
|
|
365 f.write('B({0};{1};{2};{3}) '.format(x,y,w,h)) # (x;y;w;h)
|
|
366
|
|
367 def loadDiagram(self, filename):
|
|
368 try:
|
|
369 with open(filename, 'r') as f:
|
|
370 txt = f.read()
|
|
371 except IOError as e:
|
|
372 print('{0} not found'.format(filename))
|
|
373 return
|
|
374 parts = txt.split(' ')
|
|
375 for part in parts:
|
|
376 if len(part) < 1:
|
|
377 continue
|
|
378 if part[0] == 'B':
|
|
379 part = part[2:-1]
|
|
380 x,y,w,h = [float(val) for val in part.split(';')]
|
|
381 block = BlockItem('Loaded') # TODO: store name.
|
|
382 self.diagramScene.addItem(block)
|
|
383 block.setPos(x, y)
|
|
384 block.sizer.setPos(w, h)
|
44
|
385 def toggleFullScreen(self):
|
|
386 self.setWindowState(self.windowState() ^ Qt.WindowFullScreen)
|
|
387 def startConnection(self, port):
|
|
388 self.startedConnection = Connection(port, None)
|
|
389 def sceneMouseMoveEvent(self, event):
|
|
390 if self.startedConnection:
|
|
391 pos = event.scenePos()
|
|
392 self.startedConnection.setEndPos(pos)
|
|
393 def sceneMouseReleaseEvent(self, event):
|
|
394 # Clear the actual connection:
|
|
395 if self.startedConnection:
|
46
|
396 items = self.diagramScene.items(event.scenePos())
|
44
|
397 for item in items:
|
|
398 if type(item) is PortItem:
|
|
399 self.startedConnection.setToPort(item)
|
46
|
400 self.startedConnection = None
|
|
401 return
|
|
402 self.startedConnection.delete()
|
|
403 del self.startedConnection
|
44
|
404 self.startedConnection = None
|
|
405
|
|
406 if __name__ == '__main__':
|
45
|
407 if sys.version_info.major != 3:
|
|
408 print('Please use python 3.x')
|
|
409 sys.exit(1)
|
|
410
|
46
|
411 app = QApplication(sys.argv)
|
44
|
412 global editor
|
|
413 editor = DiagramEditor()
|
|
414 editor.show()
|
|
415 editor.resize(700, 800)
|
|
416 app.exec_()
|
|
417
|