exm_scene.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. from enum import Enum
  2. from PyQt5.QtWidgets import QGraphicsScene, QGraphicsItem, QGraphicsLineItem, QGraphicsRectItem, \
  3. QGraphicsEllipseItem, QInputDialog, QTableWidgetItem
  4. from PyQt5.Qt import Qt, QPointF, QPen, QTransform, QApplication
  5. from sketchUI.graphics_edge_item import GraphicsEdgeItem
  6. from sketchUI.graphics_node_item import GraphicsNodeItem, IconType
  7. from sketchUI.graphics_sketch_group import SketchGroup
  8. from sketchUI.graphics_sketch_line import SketchedLineItem
  9. from sketchUI import mvops
  10. from evolution.node_ops import NodeAdd, NodeDelete, NodeRetype
  11. from evolution.edge_ops import EdgeDel, EdgeAdd
  12. from evolution.attribute_ops import AttributeAdd
  13. import commons
  14. class Mode(Enum):
  15. SELECT = 0
  16. CONNECT = 1
  17. LINE = 2
  18. RECT = 3
  19. CIRCLE = 4
  20. FREE = 5
  21. class SketchScene(QGraphicsScene):
  22. def __init__(self, model, parent):
  23. QGraphicsScene.__init__(self)
  24. self._cur_drawing = False
  25. self._mode = None # set from mainwindow on start
  26. self._connect_from_item = None # mouse pressed on this item if in connect mode
  27. self._cur_model = model
  28. self._orig_point = QPointF()
  29. self._free_draw_lines = []
  30. self._parent = parent
  31. def set_mode(self, mode):
  32. self._mode = mode
  33. def _in_draw_mode(self):
  34. # are we in one of the draw modes? (rect, line, free, ...)
  35. if self._mode == Mode.CONNECT or self._mode == Mode.SELECT:
  36. return False
  37. return True
  38. def draw_edge(self, from_item, to_item, edge_id=None):
  39. # type: (GraphicsNodeItem, GraphicsNodeItem, str) -> GraphicsEdgeItem
  40. # draw an edge between two items.
  41. line = GraphicsEdgeItem(from_item, to_item, edge_id)
  42. line.setFlag(QGraphicsItem.ItemIsMovable, False)
  43. line.setFlag(QGraphicsItem.ItemIsSelectable, False)
  44. self.addItem(line)
  45. line.redraw()
  46. return line
  47. def mousePressEvent(self, event):
  48. if event.button() == Qt.LeftButton and self._in_draw_mode():
  49. # start drawing, save click point
  50. self._orig_point = event.scenePos()
  51. self._cur_drawing = True
  52. elif event.button() == Qt.LeftButton and self._mode == Mode.CONNECT:
  53. # store clicked item to connect it later
  54. item = self.itemAt(event.scenePos(), QTransform())
  55. if not item or not isinstance(item, GraphicsNodeItem):
  56. return
  57. else:
  58. self._connect_from_item = item
  59. elif event.button() == Qt.LeftButton and self._mode == Mode.SELECT:
  60. item = self.itemAt(event.scenePos(), QTransform())
  61. if not item:
  62. return
  63. elif isinstance(item, GraphicsNodeItem):
  64. self._parent.plainTextEdit.appendPlainText("Selected node {}:{}".format(item.node_id, item.get_type()))
  65. self.highlight_node(item.node_id, Qt.blue)
  66. # load attributes for selected node
  67. self._parent.tableWidget.setRowCount(0)
  68. self._parent.tableWidget.blockSignals(True)
  69. attrs = commons.get_attributes_of_node(self._cur_model, item.node_id)
  70. for attr in attrs:
  71. table_item_key = QTableWidgetItem(attr.key)
  72. table_item_key.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
  73. table_item_val = QTableWidgetItem(attr.val)
  74. cur_row_cnt = self._parent.tableWidget.rowCount()
  75. self._parent.tableWidget.insertRow(cur_row_cnt)
  76. self._parent.tableWidget.setItem(cur_row_cnt, 0, table_item_key)
  77. self._parent.tableWidget.setItem(cur_row_cnt, 1, table_item_val)
  78. self._parent.tableWidget.blockSignals(False)
  79. elif isinstance(item, GraphicsEdgeItem):
  80. self._parent.plainTextEdit.appendPlainText("Selected edge ({},{}),id={}".format(item.from_item.get_type(),
  81. item.to_item.get_type(), item.edge_id))
  82. else:
  83. pass
  84. QGraphicsScene.mousePressEvent(self, event)
  85. def mouseMoveEvent(self, event):
  86. # if in freehand mode, draw lines from move movement
  87. if self._mode == Mode.FREE and self._cur_drawing:
  88. pt = event.scenePos()
  89. line = QGraphicsLineItem(self._orig_point.x(), self._orig_point.y(), pt.x(), pt.y())
  90. line.setPen(QPen(Qt.black, 2, Qt.SolidLine))
  91. self.addItem(line)
  92. self._orig_point = pt
  93. self._free_draw_lines.append(line)
  94. QGraphicsScene.mouseMoveEvent(self, event)
  95. def mouseReleaseEvent(self, event):
  96. if self._cur_drawing:
  97. end_point = event.scenePos()
  98. if self._mode == Mode.LINE:
  99. line = SketchedLineItem(self._orig_point.x(), self._orig_point.y(),
  100. end_point.x(), end_point.y())
  101. line.setPen(QPen(Qt.black, 2, Qt.SolidLine))
  102. self.addItem(line)
  103. elif self._mode == Mode.RECT:
  104. width = abs(end_point.x() - self._orig_point.x())
  105. height = abs(end_point.y() - self._orig_point.y())
  106. rect = QGraphicsRectItem(self._orig_point.x(), self._orig_point.y(),
  107. width, height)
  108. rect.setPen(QPen(Qt.black, 2, Qt.SolidLine))
  109. self.addItem(rect)
  110. elif self._mode == Mode.CIRCLE:
  111. width = abs(end_point.x() - self._orig_point.x())
  112. height = abs(end_point.y() - self._orig_point.y())
  113. ellipse = QGraphicsEllipseItem(self._orig_point.x(), self._orig_point.y(),
  114. width, height)
  115. ellipse.setPen(QPen(Qt.black, 2, Qt.SolidLine))
  116. self.addItem(ellipse)
  117. elif self._mode == Mode.FREE:
  118. line = QGraphicsLineItem(self._orig_point.x(), self._orig_point.y(),
  119. end_point.x(), end_point.y())
  120. line.setPen(QPen(Qt.black, 2, Qt.SolidLine))
  121. self.addItem(line)
  122. # group lines together
  123. self._free_draw_lines.append(line)
  124. group = self.createItemGroup(self._free_draw_lines)
  125. group.setFlag(QGraphicsItem.ItemIsSelectable, False)
  126. group.setFlag(QGraphicsItem.ItemIsMovable, False)
  127. del self._free_draw_lines[:]
  128. else:
  129. pass
  130. self._cur_drawing = False
  131. else:
  132. if self._mode == Mode.SELECT:
  133. item = self.itemAt(event.scenePos(), QTransform())
  134. if not item:
  135. return
  136. for item in self.items():
  137. if isinstance(item, GraphicsEdgeItem):
  138. item.redraw()
  139. elif self._mode == Mode.CONNECT:
  140. item = self.itemAt(event.scenePos(), QTransform())
  141. if not item or not isinstance(item, GraphicsNodeItem):
  142. return
  143. from_item = self._connect_from_item
  144. to_item = item
  145. # global or local edge add?
  146. scope, ok = QInputDialog.getItem(self._parent, "Select scope", "Scope", ["Local", "Global"])
  147. if not ok:
  148. return
  149. QApplication.setOverrideCursor(Qt.WaitCursor)
  150. add_handler = EdgeAdd()
  151. if scope == "Global":
  152. add_handler.execute(self._cur_model, from_item.node_id, to_item.node_id, local=False)
  153. else:
  154. add_handler.execute(self._cur_model, from_item.node_id, to_item.node_id, local=True)
  155. self.draw_edge(self._connect_from_item, item)
  156. # reload model because only then the ids of the edges get set anew
  157. self._parent._load_model()
  158. QApplication.restoreOverrideCursor()
  159. else:
  160. pass
  161. QGraphicsScene.mouseReleaseEvent(self, event)
  162. def keyPressEvent(self, event):
  163. if not self._mode == Mode.SELECT:
  164. return
  165. # "del" deletes all selected items
  166. if event.key() == Qt.Key_Delete:
  167. self._handle_keypress_delete(self.selectedItems())
  168. # "G" groups selected items
  169. elif event.key() == Qt.Key_G:
  170. selected = self.selectedItems()
  171. self.clearSelection()
  172. group = SketchGroup()
  173. for item in selected:
  174. group.addToGroup(item)
  175. bb_rect = QGraphicsRectItem(group.boundingRect())
  176. bb_rect.setData(0, "groupBBox") # identifier for "does not belong to the actual sketch"
  177. bb_rect.setPen(QPen(Qt.gray, 1, Qt.DashLine))
  178. group.addToGroup(bb_rect)
  179. self.addItem(group)
  180. group.setFlag(QGraphicsItem.ItemIsSelectable, True)
  181. group.setFlag(QGraphicsItem.ItemIsMovable, True)
  182. # "T" lets user type selected element
  183. elif event.key() == Qt.Key_T:
  184. # exactly one element that is a group must be selected
  185. selected = self.selectedItems()
  186. if len(selected) != 1:
  187. return
  188. item = selected[0]
  189. if isinstance(item, SketchGroup):
  190. self._handle_keypress_type_on_group(item)
  191. elif isinstance(item, GraphicsNodeItem):
  192. self._handle_keypress_type_on_node(item)
  193. else:
  194. self._parent.plainTextEdit.appendPlainText("Error: Cannot type element {}".format(item))
  195. # "A" attributes a node
  196. elif event.key() == Qt.Key_A:
  197. self._handle_keypress_attribute(self.selectedItems())
  198. else:
  199. QGraphicsScene.keyPressEvent(self, event)
  200. def _handle_keypress_type_on_node(self, item):
  201. # type: (GraphicsNodeItem) -> None
  202. """
  203. type an already typed node = retype it
  204. """
  205. old_type = item.get_type()
  206. node_type, ok = QInputDialog.getText(self._parent, "Retype node", "New type", text=item.get_type())
  207. if not ok or not node_type:
  208. # user canceled or node type empty
  209. return
  210. if node_type in commons.get_available_types():
  211. self._parent.plainTextEdit.appendPlainText("Error: Already such a type: {}".format(node_type))
  212. return
  213. self._parent.plainTextEdit.appendPlainText("Performing retype of node {}".format(node_type))
  214. QApplication.setOverrideCursor(Qt.WaitCursor)
  215. retype_handler = NodeRetype()
  216. retype_handler.execute(self._cur_model, item.node_id, node_type, local=False)
  217. # rename on screen
  218. for node_item in self.items():
  219. if not isinstance(node_item, GraphicsNodeItem):
  220. continue
  221. if node_item.get_type() == old_type:
  222. node_item.set_type(node_type)
  223. # update list widget
  224. self._parent.populate_types()
  225. QApplication.restoreOverrideCursor()
  226. def _handle_keypress_type_on_group(self, group):
  227. # type: (SketchGroup) -> None
  228. """
  229. type the selected group = make a real node out of it and store it in the model
  230. also capture its concrete syntax and store it in the modelverse
  231. """
  232. # get the type from the user
  233. node_type, ok = QInputDialog.getText(self._parent, "Type node", "Enter type")
  234. if not ok or not node_type:
  235. # user canceled or empty type string
  236. return
  237. if node_type in commons.get_available_types():
  238. self._parent.plainTextEdit.appendPlainText("Error: Already such a type: {}".format(node_type))
  239. return
  240. # perform add local or global?
  241. scope, ok = QInputDialog.getItem(self._parent, "Select scope", "Scope", ["Local", "Global"])
  242. if not ok:
  243. return
  244. self._parent.plainTextEdit.appendPlainText("Typing group to type {}".format(node_type))
  245. QApplication.setOverrideCursor(Qt.WaitCursor)
  246. # add the node to the model
  247. add_handler = NodeAdd()
  248. if scope == "Global":
  249. add_handler.execute(self._cur_model, node_type, local=False, check_if_last=False)
  250. else:
  251. add_handler.execute(self._cur_model, node_type, local=True, check_if_last=True)
  252. # Get node id of newly added node in current model
  253. nodeid = commons.all_nodes_with_type(self._cur_model, node_type)[0]
  254. self._parent.plainTextEdit.appendPlainText("Capturing concrete syntax of group ...")
  255. self._parent.plainTextEdit.repaint()
  256. # create concrete syntax model for the sketched elements
  257. csm = mvops.new_concrete_syntax_model(node_type, IconType.PRIMITIVE)
  258. if not csm:
  259. self._parent.plainTextEdit.appendPlainText("Error: Concrete syntax for type {} already exists".format(node_type))
  260. return
  261. # check if we need to scale the group items down to 100x100 first
  262. group_brect = group.boundingRect()
  263. need_scale = False
  264. scale_factor = 1.0
  265. if group_brect.width() > 100 or group_brect.height() > 100:
  266. need_scale = True
  267. scale_factor = 100.0 / max(group_brect.width(), group_brect.height())
  268. # populate CSM with sketched elements
  269. for item in group.childItems():
  270. if item.data(0) == "groupBBox":
  271. # just the bounding box from the group, ignore
  272. continue
  273. if isinstance(item, QGraphicsRectItem):
  274. rect = group.get_item_coord_relative(item)
  275. if need_scale:
  276. new_top_left = rect.topLeft() * scale_factor
  277. new_width = rect.width() * scale_factor
  278. new_height = rect.height() * scale_factor
  279. rect.setTopLeft(new_top_left)
  280. rect.setWidth(new_width)
  281. rect.setHeight(new_height)
  282. mvops.add_rect_to_cs(csm, rect)
  283. elif isinstance(item, QGraphicsEllipseItem):
  284. rect = group.get_item_coord_relative(item)
  285. if need_scale:
  286. new_top_left = rect.topLeft() * scale_factor
  287. new_width = rect.width() * scale_factor
  288. new_height = rect.height() * scale_factor
  289. rect.setTopLeft(new_top_left)
  290. rect.setWidth(new_width)
  291. rect.setHeight(new_height)
  292. mvops.add_rect_to_cs(csm, rect)
  293. elif isinstance(item, SketchedLineItem):
  294. p1, p2 = group.get_item_coord_relative(item)
  295. if need_scale:
  296. p1 *= scale_factor
  297. p2 *= scale_factor
  298. mvops.add_line_to_cs(csm, p1, p2)
  299. else:
  300. print("Dont know how to capture CS of item {}".format(item))
  301. # update view: replace group by actual node item with newly populated CS
  302. csm_content = mvops.get_consyn_of(node_type)
  303. nodeitem = GraphicsNodeItem(nodeid, node_type, csm_content)
  304. nodeitem.setPos(group.scenePos())
  305. nodeitem.setFlag(QGraphicsItem.ItemIsSelectable, True)
  306. nodeitem.setFlag(QGraphicsItem.ItemIsMovable, True)
  307. self.removeItem(group)
  308. self.addItem(nodeitem)
  309. self._parent.populate_types()
  310. QApplication.restoreOverrideCursor()
  311. self._parent.plainTextEdit.appendPlainText("OK")
  312. def _handle_keypress_delete(self, selected):
  313. if len(selected) == 1 and isinstance(selected[0], GraphicsEdgeItem):
  314. # an edge is to be deleted
  315. edge = selected[0]
  316. edge_from_type = edge.from_item.get_type()
  317. edge_to_type = edge.to_item.get_type()
  318. self._parent.plainTextEdit.appendPlainText("Deleting edge ({},{}),id={}".format(edge_from_type, edge_to_type, edge.edge_id))
  319. # local or global?
  320. scope, ok = QInputDialog.getItem(self._parent, "Select scope", "Scope", ["Local", "Global"])
  321. if not ok:
  322. return
  323. del_handler = EdgeDel()
  324. QApplication.setOverrideCursor(Qt.WaitCursor)
  325. if scope == "Global":
  326. del_handler.execute(self._cur_model, edge.edge_id, local=False, check_if_last=False)
  327. # delete all edges with same typing in view
  328. for item in self.items():
  329. if not isinstance(item, GraphicsEdgeItem):
  330. continue
  331. if item.from_item.get_type() in [edge_from_type, edge_to_type] and item.to_item.get_type() in [edge_from_type, edge_to_type]:
  332. self.removeItem(item)
  333. else:
  334. del_handler.execute(self._cur_model, edge.edge_id, local=True, check_if_last=True)
  335. # delete from view
  336. self.removeItem(edge)
  337. QApplication.restoreOverrideCursor()
  338. elif len(selected) == 1 and isinstance(selected[0], GraphicsNodeItem):
  339. del_hander = NodeDelete()
  340. node = selected[0]
  341. # a node is to be deleted
  342. self._parent.plainTextEdit.appendPlainText("Deleting node of type {}".format(node.get_type()))
  343. # when deleting a node, local or global?
  344. scope, ok = QInputDialog.getItem(self._parent, "Select scope", "Scope", ["Local", "Global"])
  345. if not ok:
  346. return
  347. QApplication.setOverrideCursor(Qt.WaitCursor)
  348. if scope == "Global":
  349. # global language evolution, so delete node with same type everywhere
  350. del_hander.execute(self._cur_model, node.node_id, local=False, check_if_last=False)
  351. # also delete its associated CS model
  352. mvops.del_concrete_syntax_model(node.get_type())
  353. # delete all nodes of type from view
  354. for item in self.items():
  355. if not isinstance(item, GraphicsNodeItem):
  356. continue
  357. if item.get_type() == node.get_type():
  358. self.removeItem(item)
  359. else:
  360. # just local, delete from this model only
  361. del_hander.execute(self._cur_model, node.node_id, local=True, check_if_last=True)
  362. if del_hander.was_last():
  363. # it was the last node in the language, so delete its CS model as well
  364. mvops.del_concrete_syntax_model(node.get_type())
  365. # delete this node from view
  366. self.removeItem(node)
  367. # in view, delete edges that were connected to this node as well
  368. # modelverse does this on its own so do not delete edges explicitly here
  369. if scope == "Local":
  370. for edge in self.items():
  371. if not isinstance(edge, GraphicsEdgeItem):
  372. continue
  373. if edge.from_item.node_id == node.node_id or edge.to_item.node_id == node.node_id:
  374. self.removeItem(edge)
  375. else:
  376. # have to remove all edges connected to this type in model
  377. for edge in self.items():
  378. if not isinstance(edge, GraphicsEdgeItem):
  379. continue
  380. if edge.from_item.get_type() == node.get_type() or edge.to_item.get_type() == node.get_type():
  381. self.removeItem(edge)
  382. # repopulate available types just in case
  383. self._parent.populate_types()
  384. else:
  385. if not any(isinstance(x, GraphicsNodeItem) for x in selected) and not any(isinstance(x, GraphicsEdgeItem) for x in selected):
  386. # neither NodeItem nor EdgeItem in selected -> untyped sketch item, simply remove
  387. for obj in selected:
  388. self.removeItem(obj)
  389. QApplication.restoreOverrideCursor()
  390. def _handle_keypress_attribute(self, selected):
  391. if not len(selected) == 1:
  392. return
  393. item = selected[0]
  394. if not isinstance(item, GraphicsNodeItem):
  395. return
  396. # ask user for key value
  397. key, ok = QInputDialog.getText(self._parent, "New attribute", "Key value")
  398. if not ok or not key:
  399. return
  400. # check if key value already used for this node
  401. attrs = commons.get_attributes_of_node(self._cur_model, item.node_id)
  402. for attr in attrs:
  403. if attr.key == key:
  404. self._parent.plainTextEdit.appendPlainText("Error: Already such a key for the node: {}".format(key))
  405. return
  406. # ask of global or local add attribute
  407. scope, ok = QInputDialog.getItem(self._parent, "Select scope", "Scope", ["Local", "Global"])
  408. if not ok:
  409. return
  410. add_handler = AttributeAdd()
  411. if scope == "Global":
  412. add_handler.execute(self._cur_model, item.node_id, key, "unknown", local=False)
  413. else:
  414. add_handler.execute(self._cur_model, item.node_id, key, "unknown", local=True)
  415. # add to view
  416. self._parent.add_new_attribute(key, "unknown")
  417. def highlight_node(self, node_id, color):
  418. for item in self.items():
  419. if not isinstance(item, GraphicsNodeItem):
  420. continue
  421. if item.node_id == node_id:
  422. item.set_highlighted(True, color)
  423. else:
  424. item.set_highlighted(False, color)
  425. item.update(item.boundingRect())