GridViewer.py 7.6 KB

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