exm_scene.py 18 KB

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