GridViewer.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. '''
  2. ** By Cro-Ki l@b, 2017 **
  3. '''
  4. from timeit import timeit
  5. from PyQt5.Qt import Qt, QEvent, QRectF
  6. from PyQt5.QtCore import QPointF
  7. from PyQt5.QtGui import QPolygonF
  8. from PyQt5.QtWidgets import QMainWindow, \
  9. QApplication, QGraphicsScene, QGraphicsView
  10. import yaml
  11. from GridDialogBox import GridDialogBox
  12. from GridViewerCell import GridViewerCell
  13. from ListViewDialog import ListViewDialog
  14. from pypog.grid_objects import SquareGrid, FHexGrid, HexGrid, BaseGrid
  15. from qt_viewer import Ui_window
  16. class GridViewer(QMainWindow):
  17. def __init__(self):
  18. super (GridViewer, self).__init__()
  19. self.cells = {}
  20. self.selection = []
  21. self.job_index = 0
  22. self.job_results = []
  23. self.grid = BaseGrid(1, 1)
  24. self.createWidgets()
  25. # ## GUI related methods
  26. def createWidgets(self):
  27. self.ui = Ui_window()
  28. self.ui.setupUi(self)
  29. self.ui.btn_new_grid.clicked.connect(self.show_new_grid_dialog)
  30. self.ui.btn_list_view.clicked.connect(self.show_list_view_dialog)
  31. self.ui.btn_zoom_plus.clicked.connect(self.zoom_plus)
  32. self.ui.btn_zoom_minus.clicked.connect(self.zoom_minus)
  33. self.ui.btn_zoom_view.clicked.connect(self.fit_in_view)
  34. self.ui.chk_displayCoords.toggled.connect(self.update_cell_labels)
  35. self.ui.btn_run_job.clicked.connect(self.run_selected_job_clicked)
  36. self.ui.btn_job_next.clicked.connect(self.job_next_clicked)
  37. self.ui.btn_job_previous.clicked.connect(self.job_previous_clicked)
  38. self.ui.btn_job_validate.clicked.connect(self.job_validate_clicked)
  39. self.ui.view.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)
  40. self.ui.view.setDragMode(QGraphicsView.NoDrag)
  41. self.ui.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
  42. self.ui.view.viewport().installEventFilter(self)
  43. self.ui.cb_jobs.insertItems(0, self.get_job_names())
  44. self._update_stack_job()
  45. def eventFilter(self, obj, event):
  46. if event.type() == QEvent.Wheel:
  47. if event.angleDelta().y() > 0:
  48. self.zoom_plus()
  49. elif event.angleDelta().y() < 0:
  50. self.zoom_minus()
  51. return True
  52. return False
  53. def fit_in_view(self):
  54. self.ui.view.fitInView(self._scene.sceneRect(), Qt.KeepAspectRatio)
  55. def zoom_plus(self):
  56. self.ui.view.scale(1.2, 1.2)
  57. def zoom_minus(self):
  58. self.ui.view.scale(0.8, 0.8)
  59. # ## Grid and selection
  60. def make_grid(self, grid):
  61. QApplication.setOverrideCursor(Qt.WaitCursor)
  62. self.grid = grid
  63. self.cells = {}
  64. self.selection = []
  65. self._scene = QGraphicsScene()
  66. self._scene.setItemIndexMethod(QGraphicsScene.BspTreeIndex)
  67. if len(grid) > 10000:
  68. self.ui.chk_displayCoords.setChecked(False)
  69. scale = 120
  70. margin = 2 * scale
  71. ratio = 0.866 if isinstance(grid, HexGrid) else 1
  72. self._scene.setSceneRect(0 - margin, 0 - margin, (ratio * scale * (grid.width + 2)) + margin, (scale * (grid.height + 2)) + margin)
  73. for x, y in grid:
  74. cell = GridViewerCell(self, x, y)
  75. cell.generate(grid.geometry.graphicsitem(x, y), show_label=self.ui.chk_displayCoords.isChecked())
  76. self._scene.addItem(cell)
  77. self.cells[(x, y)] = cell
  78. self.ui.view.setScene(self._scene)
  79. self.ui.view.centerOn(QPointF(0, 0))
  80. self.fit_in_view()
  81. self.grid = grid
  82. QApplication.restoreOverrideCursor()
  83. def add_to_selection(self, x, y):
  84. self.selection.append((x, y))
  85. def remove_from_selection(self, x, y):
  86. self.selection.remove((x, y))
  87. def update_selected_cells(self, new_selection):
  88. if not new_selection != self.selection:
  89. return
  90. QApplication.setOverrideCursor(Qt.WaitCursor)
  91. for x, y in tuple(self.selection):
  92. self.cells[(x, y)].unselect()
  93. for x, y in new_selection:
  94. if (x, y) in self.grid:
  95. self.cells[(x, y)].select()
  96. QApplication.restoreOverrideCursor()
  97. def update_cell_labels(self):
  98. for cell in self.cells.values():
  99. cell.show_label(bool(self.ui.chk_displayCoords.isChecked()))
  100. # ## Dialogs
  101. def show_new_grid_dialog(self):
  102. grid = GridDialogBox.get()
  103. if grid:
  104. self.make_grid(grid)
  105. def show_list_view_dialog(self):
  106. new_lst = ListViewDialog(self.selection).exec_()
  107. self.update_selected_cells(new_lst)
  108. # ## IT Jobs
  109. def run_selected_job_clicked(self):
  110. self.job_index = 0
  111. self.job_results = self.run_job(self.ui.cb_jobs.currentText())
  112. self._update_stack_job()
  113. def job_next_clicked(self):
  114. if self.job_index < (len(self.job_results) - 1):
  115. self.job_index += 1
  116. self._update_stack_job()
  117. def job_previous_clicked(self):
  118. if self.job_index > 0:
  119. self.job_index -= 1
  120. self._update_stack_job()
  121. def job_validate_clicked(self):
  122. self.save_result_for(*self.job_results[self.job_index])
  123. self._update_stack_job()
  124. def _update_stack_job(self):
  125. if not self.job_results:
  126. self.ui.stack_job.setCurrentIndex(0)
  127. return
  128. self.ui.stack_job.setCurrentIndex(1)
  129. self.ui.lbl_job_number.setText("Test {} / {}".format(self.job_index + 1, len(self.job_results)))
  130. gridstr, callstr, result, ittime = self.job_results[self.job_index]
  131. new_grid = eval(gridstr)
  132. if not (new_grid.__class__ == self.grid.__class__ and
  133. new_grid.width == self.grid.width and
  134. new_grid.height == self.grid.height):
  135. self.make_grid(new_grid)
  136. self.ui.txt_job_run.setText(callstr)
  137. self.update_selected_cells(result)
  138. saved = self.saved_result_for(callstr)
  139. if saved:
  140. self.ui.lbl_job_exectime.setText("Exec. in {0:.2f} ms. / Saved: {1:.2f} ms. / Same result: {2:}".format(ittime, saved[3], str(result) == saved[2]))
  141. else:
  142. self.ui.lbl_job_exectime.setText("Exec. in {0:.2f} ms.".format(ittime))
  143. @staticmethod
  144. def get_job_names():
  145. with open("jobs.yml", "r") as f:
  146. jobs = yaml.load(f)
  147. return jobs.keys()
  148. @staticmethod
  149. def run_job(job_name):
  150. with open("jobs.yml", "r") as f:
  151. jobs = yaml.load(f)
  152. callstrings = [(gridstr, "{}.{}".format(gridstr, funcstr)) for gridstr, calls in jobs[job_name].items() for funcstr in calls]
  153. return [(gridstr, callstr, eval(callstr), GridViewer.ittime(callstr)) for gridstr, callstr in callstrings]
  154. @staticmethod
  155. def ittime(callstr):
  156. """ returns the execution time in milli-seconds
  157. callstr has to be a string
  158. (ex: 'time.sleep(1)', which will return 1000)
  159. """
  160. number, t = 1, 0
  161. while t < 10 ** 8:
  162. t = timeit(lambda: eval(callstr), number=number)
  163. if t >= 0.001:
  164. return 1000 * t / number
  165. number *= 10
  166. else:
  167. return -1
  168. @staticmethod
  169. def saved_results():
  170. try:
  171. with open("results.yml", "r") as f:
  172. data = yaml.load(f)
  173. return dict(data)
  174. except (FileNotFoundError, TypeError):
  175. return {}
  176. @staticmethod
  177. def saved_result_for(callstr):
  178. try:
  179. return tuple(GridViewer.saved_results()[callstr])
  180. except (TypeError, KeyError):
  181. return None
  182. @staticmethod
  183. def save_result(gridstr, callstr, result, ittime):
  184. data = GridViewer.saved_results()
  185. data[callstr] = [gridstr, callstr, str(result), ittime]
  186. with open("results.yml", "w+") as f:
  187. yaml.dump(data, f)