exm_scene.py 20 KB

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