PlotCanvas.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://caram.cl/software/flatcam #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from PyQt4 import QtGui, QtCore
  9. from matplotlib.figure import Figure
  10. from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
  11. import FlatCAMApp
  12. # class FCFigureCanvas(FigureCanvas):
  13. #
  14. # resized = QtCore.pyqtSignal()
  15. #
  16. # def resizeEvent(self, event):
  17. # FigureCanvas.resizeEvent(self, event)
  18. # self.emit(QtCore.SIGNAL("resized"))
  19. # print self.geometry()
  20. class PlotCanvas:
  21. """
  22. Class handling the plotting area in the application.
  23. """
  24. def __init__(self, container):
  25. """
  26. The constructor configures the Matplotlib figure that
  27. will contain all plots, creates the base axes and connects
  28. events to the plotting area.
  29. :param container: The parent container in which to draw plots.
  30. :rtype: PlotCanvas
  31. """
  32. # Options
  33. self.x_margin = 15 # pixels
  34. self.y_margin = 25 # Pixels
  35. # Parent container
  36. self.container = container
  37. # Plots go onto a single matplotlib.figure
  38. self.figure = Figure(dpi=50) # TODO: dpi needed?
  39. self.figure.patch.set_visible(False)
  40. # These axes show the ticks and grid. No plotting done here.
  41. # New axes must have a label, otherwise mpl returns an existing one.
  42. self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
  43. self.axes.set_aspect(1)
  44. self.axes.grid(True)
  45. # The canvas is the top level container (Gtk.DrawingArea)
  46. self.canvas = FigureCanvas(self.figure)
  47. #self.canvas.set_hexpand(1)
  48. #self.canvas.set_vexpand(1)
  49. #self.canvas.set_can_focus(True) # For key press
  50. # Attach to parent
  51. #self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??
  52. self.container.addWidget(self.canvas) # Qt
  53. # Events
  54. self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
  55. #self.canvas.connect('configure-event', self.auto_adjust_axes)
  56. self.canvas.mpl_connect('resize_event', self.auto_adjust_axes)
  57. #self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
  58. #self.canvas.connect("scroll-event", self.on_scroll)
  59. self.canvas.mpl_connect('scroll_event', self.on_scroll)
  60. self.canvas.mpl_connect('key_press_event', self.on_key_down)
  61. self.canvas.mpl_connect('key_release_event', self.on_key_up)
  62. self.mouse = [0, 0]
  63. self.key = None
  64. def on_key_down(self, event):
  65. """
  66. :param event:
  67. :return:
  68. """
  69. FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
  70. self.key = event.key
  71. def on_key_up(self, event):
  72. """
  73. :param event:
  74. :return:
  75. """
  76. self.key = None
  77. def mpl_connect(self, event_name, callback):
  78. """
  79. Attach an event handler to the canvas through the Matplotlib interface.
  80. :param event_name: Name of the event
  81. :type event_name: str
  82. :param callback: Function to call
  83. :type callback: func
  84. :return: Connection id
  85. :rtype: int
  86. """
  87. return self.canvas.mpl_connect(event_name, callback)
  88. def mpl_disconnect(self, cid):
  89. """
  90. Disconnect callback with the give id.
  91. :param cid: Callback id.
  92. :return: None
  93. """
  94. self.canvas.mpl_disconnect(cid)
  95. def connect(self, event_name, callback):
  96. """
  97. Attach an event handler to the canvas through the native GTK interface.
  98. :param event_name: Name of the event
  99. :type event_name: str
  100. :param callback: Function to call
  101. :type callback: function
  102. :return: Nothing
  103. """
  104. self.canvas.connect(event_name, callback)
  105. def clear(self):
  106. """
  107. Clears axes and figure.
  108. :return: None
  109. """
  110. # Clear
  111. self.axes.cla()
  112. try:
  113. self.figure.clf()
  114. except KeyError:
  115. FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")
  116. # Re-build
  117. self.figure.add_axes(self.axes)
  118. self.axes.set_aspect(1)
  119. self.axes.grid(True)
  120. # Re-draw
  121. self.canvas.draw()
  122. def adjust_axes(self, xmin, ymin, xmax, ymax):
  123. """
  124. Adjusts all axes while maintaining the use of the whole canvas
  125. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  126. request that will be modified to fit these restrictions.
  127. :param xmin: Requested minimum value for the X axis.
  128. :type xmin: float
  129. :param ymin: Requested minimum value for the Y axis.
  130. :type ymin: float
  131. :param xmax: Requested maximum value for the X axis.
  132. :type xmax: float
  133. :param ymax: Requested maximum value for the Y axis.
  134. :type ymax: float
  135. :return: None
  136. """
  137. # FlatCAMApp.App.log.debug("PC.adjust_axes()")
  138. width = xmax - xmin
  139. height = ymax - ymin
  140. try:
  141. r = width / height
  142. except ZeroDivisionError:
  143. FlatCAMApp.App.log.error("Height is %f" % height)
  144. return
  145. canvas_w, canvas_h = self.canvas.get_width_height()
  146. canvas_r = float(canvas_w) / canvas_h
  147. x_ratio = float(self.x_margin) / canvas_w
  148. y_ratio = float(self.y_margin) / canvas_h
  149. if r > canvas_r:
  150. ycenter = (ymin + ymax) / 2.0
  151. newheight = height * r / canvas_r
  152. ymin = ycenter - newheight / 2.0
  153. ymax = ycenter + newheight / 2.0
  154. else:
  155. xcenter = (xmax + xmin) / 2.0
  156. newwidth = width * canvas_r / r
  157. xmin = xcenter - newwidth / 2.0
  158. xmax = xcenter + newwidth / 2.0
  159. # Adjust axes
  160. for ax in self.figure.get_axes():
  161. if ax._label != 'base':
  162. ax.set_frame_on(False) # No frame
  163. ax.set_xticks([]) # No tick
  164. ax.set_yticks([]) # No ticks
  165. ax.patch.set_visible(False) # No background
  166. ax.set_aspect(1)
  167. ax.set_xlim((xmin, xmax))
  168. ax.set_ylim((ymin, ymax))
  169. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  170. # Re-draw
  171. self.canvas.draw()
  172. def auto_adjust_axes(self, *args):
  173. """
  174. Calls ``adjust_axes()`` using the extents of the base axes.
  175. :rtype : None
  176. :return: None
  177. """
  178. xmin, xmax = self.axes.get_xlim()
  179. ymin, ymax = self.axes.get_ylim()
  180. self.adjust_axes(xmin, ymin, xmax, ymax)
  181. def zoom(self, factor, center=None):
  182. """
  183. Zooms the plot by factor around a given
  184. center point. Takes care of re-drawing.
  185. :param factor: Number by which to scale the plot.
  186. :type factor: float
  187. :param center: Coordinates [x, y] of the point around which to scale the plot.
  188. :type center: list
  189. :return: None
  190. """
  191. xmin, xmax = self.axes.get_xlim()
  192. ymin, ymax = self.axes.get_ylim()
  193. width = xmax - xmin
  194. height = ymax - ymin
  195. if center is None or center == [None, None]:
  196. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  197. # For keeping the point at the pointer location
  198. relx = (xmax - center[0]) / width
  199. rely = (ymax - center[1]) / height
  200. new_width = width / factor
  201. new_height = height / factor
  202. xmin = center[0] - new_width * (1 - relx)
  203. xmax = center[0] + new_width * relx
  204. ymin = center[1] - new_height * (1 - rely)
  205. ymax = center[1] + new_height * rely
  206. # Adjust axes
  207. for ax in self.figure.get_axes():
  208. ax.set_xlim((xmin, xmax))
  209. ax.set_ylim((ymin, ymax))
  210. # Re-draw
  211. self.canvas.draw()
  212. def pan(self, x, y):
  213. xmin, xmax = self.axes.get_xlim()
  214. ymin, ymax = self.axes.get_ylim()
  215. width = xmax - xmin
  216. height = ymax - ymin
  217. # Adjust axes
  218. for ax in self.figure.get_axes():
  219. ax.set_xlim((xmin + x*width, xmax + x*width))
  220. ax.set_ylim((ymin + y*height, ymax + y*height))
  221. # Re-draw
  222. self.canvas.draw()
  223. def new_axes(self, name):
  224. """
  225. Creates and returns an Axes object attached to this object's Figure.
  226. :param name: Unique label for the axes.
  227. :return: Axes attached to the figure.
  228. :rtype: Axes
  229. """
  230. return self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  231. def on_scroll(self, event):
  232. """
  233. Scroll event handler.
  234. :param event: Event object containing the event information.
  235. :return: None
  236. """
  237. # So it can receive key presses
  238. # self.canvas.grab_focus()
  239. self.canvas.setFocus()
  240. # Event info
  241. # z, direction = event.get_scroll_direction()
  242. if self.key is None:
  243. if event.button == 'up':
  244. self.zoom(1.5, self.mouse)
  245. else:
  246. self.zoom(1/1.5, self.mouse)
  247. return
  248. if self.key == 'shift':
  249. if event.button == 'up':
  250. self.pan(0.3, 0)
  251. else:
  252. self.pan(-0.3, 0)
  253. return
  254. if self.key == 'control':
  255. if event.button == 'up':
  256. self.pan(0, 0.3)
  257. else:
  258. self.pan(0, -0.3)
  259. return
  260. def on_mouse_move(self, event):
  261. """
  262. Mouse movement event hadler. Stores the coordinates.
  263. :param event: Contains information about the event.
  264. :return: None
  265. """
  266. self.mouse = [event.xdata, event.ydata]