backend_tools.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. """
  2. Abstract base classes define the primitives for Tools.
  3. These tools are used by `matplotlib.backend_managers.ToolManager`
  4. :class:`ToolBase`
  5. Simple stateless tool
  6. :class:`ToolToggleBase`
  7. Tool that has two states, only one Toggle tool can be
  8. active at any given time for the same
  9. `matplotlib.backend_managers.ToolManager`
  10. """
  11. import enum
  12. import functools
  13. import re
  14. import time
  15. from types import SimpleNamespace
  16. import uuid
  17. from weakref import WeakKeyDictionary
  18. import numpy as np
  19. import matplotlib as mpl
  20. from matplotlib._pylab_helpers import Gcf
  21. from matplotlib import _api, cbook
  22. class Cursors(enum.IntEnum): # Must subclass int for the macOS backend.
  23. """Backend-independent cursor types."""
  24. POINTER = enum.auto()
  25. HAND = enum.auto()
  26. SELECT_REGION = enum.auto()
  27. MOVE = enum.auto()
  28. WAIT = enum.auto()
  29. RESIZE_HORIZONTAL = enum.auto()
  30. RESIZE_VERTICAL = enum.auto()
  31. cursors = Cursors # Backcompat.
  32. # _tool_registry, _register_tool_class, and _find_tool_class implement a
  33. # mechanism through which ToolManager.add_tool can determine whether a subclass
  34. # of the requested tool class has been registered (either for the current
  35. # canvas class or for a parent class), in which case that tool subclass will be
  36. # instantiated instead. This is the mechanism used e.g. to allow different
  37. # GUI backends to implement different specializations for ConfigureSubplots.
  38. _tool_registry = set()
  39. def _register_tool_class(canvas_cls, tool_cls=None):
  40. """Decorator registering *tool_cls* as a tool class for *canvas_cls*."""
  41. if tool_cls is None:
  42. return functools.partial(_register_tool_class, canvas_cls)
  43. _tool_registry.add((canvas_cls, tool_cls))
  44. return tool_cls
  45. def _find_tool_class(canvas_cls, tool_cls):
  46. """Find a subclass of *tool_cls* registered for *canvas_cls*."""
  47. for canvas_parent in canvas_cls.__mro__:
  48. for tool_child in _api.recursive_subclasses(tool_cls):
  49. if (canvas_parent, tool_child) in _tool_registry:
  50. return tool_child
  51. return tool_cls
  52. # Views positions tool
  53. _views_positions = 'viewpos'
  54. class ToolBase:
  55. """
  56. Base tool class.
  57. A base tool, only implements `trigger` method or no method at all.
  58. The tool is instantiated by `matplotlib.backend_managers.ToolManager`.
  59. """
  60. default_keymap = None
  61. """
  62. Keymap to associate with this tool.
  63. ``list[str]``: List of keys that will trigger this tool when a keypress
  64. event is emitted on ``self.figure.canvas``. Note that this attribute is
  65. looked up on the instance, and can therefore be a property (this is used
  66. e.g. by the built-in tools to load the rcParams at instantiation time).
  67. """
  68. description = None
  69. """
  70. Description of the Tool.
  71. `str`: Tooltip used if the Tool is included in a Toolbar.
  72. """
  73. image = None
  74. """
  75. Filename of the image.
  76. `str`: Filename of the image to use in a Toolbar. If None, the *name* is
  77. used as a label in the toolbar button.
  78. """
  79. def __init__(self, toolmanager, name):
  80. self._name = name
  81. self._toolmanager = toolmanager
  82. self._figure = None
  83. name = property(
  84. lambda self: self._name,
  85. doc="The tool id (str, must be unique among tools of a tool manager).")
  86. toolmanager = property(
  87. lambda self: self._toolmanager,
  88. doc="The `.ToolManager` that controls this tool.")
  89. canvas = property(
  90. lambda self: self._figure.canvas if self._figure is not None else None,
  91. doc="The canvas of the figure affected by this tool, or None.")
  92. def set_figure(self, figure):
  93. self._figure = figure
  94. figure = property(
  95. lambda self: self._figure,
  96. # The setter must explicitly call self.set_figure so that subclasses can
  97. # meaningfully override it.
  98. lambda self, figure: self.set_figure(figure),
  99. doc="The Figure affected by this tool, or None.")
  100. def _make_classic_style_pseudo_toolbar(self):
  101. """
  102. Return a placeholder object with a single `canvas` attribute.
  103. This is useful to reuse the implementations of tools already provided
  104. by the classic Toolbars.
  105. """
  106. return SimpleNamespace(canvas=self.canvas)
  107. def trigger(self, sender, event, data=None):
  108. """
  109. Called when this tool gets used.
  110. This method is called by `.ToolManager.trigger_tool`.
  111. Parameters
  112. ----------
  113. event : `.Event`
  114. The canvas event that caused this tool to be called.
  115. sender : object
  116. Object that requested the tool to be triggered.
  117. data : object
  118. Extra data.
  119. """
  120. pass
  121. class ToolToggleBase(ToolBase):
  122. """
  123. Toggleable tool.
  124. Every time it is triggered, it switches between enable and disable.
  125. Parameters
  126. ----------
  127. ``*args``
  128. Variable length argument to be used by the Tool.
  129. ``**kwargs``
  130. `toggled` if present and True, sets the initial state of the Tool
  131. Arbitrary keyword arguments to be consumed by the Tool
  132. """
  133. radio_group = None
  134. """
  135. Attribute to group 'radio' like tools (mutually exclusive).
  136. `str` that identifies the group or **None** if not belonging to a group.
  137. """
  138. cursor = None
  139. """Cursor to use when the tool is active."""
  140. default_toggled = False
  141. """Default of toggled state."""
  142. def __init__(self, *args, **kwargs):
  143. self._toggled = kwargs.pop('toggled', self.default_toggled)
  144. super().__init__(*args, **kwargs)
  145. def trigger(self, sender, event, data=None):
  146. """Calls `enable` or `disable` based on `toggled` value."""
  147. if self._toggled:
  148. self.disable(event)
  149. else:
  150. self.enable(event)
  151. self._toggled = not self._toggled
  152. def enable(self, event=None):
  153. """
  154. Enable the toggle tool.
  155. `trigger` calls this method when `toggled` is False.
  156. """
  157. pass
  158. def disable(self, event=None):
  159. """
  160. Disable the toggle tool.
  161. `trigger` call this method when `toggled` is True.
  162. This can happen in different circumstances.
  163. * Click on the toolbar tool button.
  164. * Call to `matplotlib.backend_managers.ToolManager.trigger_tool`.
  165. * Another `ToolToggleBase` derived tool is triggered
  166. (from the same `.ToolManager`).
  167. """
  168. pass
  169. @property
  170. def toggled(self):
  171. """State of the toggled tool."""
  172. return self._toggled
  173. def set_figure(self, figure):
  174. toggled = self.toggled
  175. if toggled:
  176. if self.figure:
  177. self.trigger(self, None)
  178. else:
  179. # if no figure the internal state is not changed
  180. # we change it here so next call to trigger will change it back
  181. self._toggled = False
  182. super().set_figure(figure)
  183. if toggled:
  184. if figure:
  185. self.trigger(self, None)
  186. else:
  187. # if there is no figure, trigger won't change the internal
  188. # state we change it back
  189. self._toggled = True
  190. class ToolSetCursor(ToolBase):
  191. """
  192. Change to the current cursor while inaxes.
  193. This tool, keeps track of all `ToolToggleBase` derived tools, and updates
  194. the cursor when a tool gets triggered.
  195. """
  196. def __init__(self, *args, **kwargs):
  197. super().__init__(*args, **kwargs)
  198. self._id_drag = None
  199. self._current_tool = None
  200. self._default_cursor = cursors.POINTER
  201. self._last_cursor = self._default_cursor
  202. self.toolmanager.toolmanager_connect('tool_added_event',
  203. self._add_tool_cbk)
  204. # process current tools
  205. for tool in self.toolmanager.tools.values():
  206. self._add_tool(tool)
  207. def set_figure(self, figure):
  208. if self._id_drag:
  209. self.canvas.mpl_disconnect(self._id_drag)
  210. super().set_figure(figure)
  211. if figure:
  212. self._id_drag = self.canvas.mpl_connect(
  213. 'motion_notify_event', self._set_cursor_cbk)
  214. def _tool_trigger_cbk(self, event):
  215. if event.tool.toggled:
  216. self._current_tool = event.tool
  217. else:
  218. self._current_tool = None
  219. self._set_cursor_cbk(event.canvasevent)
  220. def _add_tool(self, tool):
  221. """Set the cursor when the tool is triggered."""
  222. if getattr(tool, 'cursor', None) is not None:
  223. self.toolmanager.toolmanager_connect('tool_trigger_%s' % tool.name,
  224. self._tool_trigger_cbk)
  225. def _add_tool_cbk(self, event):
  226. """Process every newly added tool."""
  227. if event.tool is self:
  228. return
  229. self._add_tool(event.tool)
  230. def _set_cursor_cbk(self, event):
  231. if not event or not self.canvas:
  232. return
  233. if (self._current_tool and getattr(event, "inaxes", None)
  234. and event.inaxes.get_navigate()):
  235. if self._last_cursor != self._current_tool.cursor:
  236. self.canvas.set_cursor(self._current_tool.cursor)
  237. self._last_cursor = self._current_tool.cursor
  238. elif self._last_cursor != self._default_cursor:
  239. self.canvas.set_cursor(self._default_cursor)
  240. self._last_cursor = self._default_cursor
  241. class ToolCursorPosition(ToolBase):
  242. """
  243. Send message with the current pointer position.
  244. This tool runs in the background reporting the position of the cursor.
  245. """
  246. def __init__(self, *args, **kwargs):
  247. self._id_drag = None
  248. super().__init__(*args, **kwargs)
  249. def set_figure(self, figure):
  250. if self._id_drag:
  251. self.canvas.mpl_disconnect(self._id_drag)
  252. super().set_figure(figure)
  253. if figure:
  254. self._id_drag = self.canvas.mpl_connect(
  255. 'motion_notify_event', self.send_message)
  256. def send_message(self, event):
  257. """Call `matplotlib.backend_managers.ToolManager.message_event`."""
  258. if self.toolmanager.messagelock.locked():
  259. return
  260. from matplotlib.backend_bases import NavigationToolbar2
  261. message = NavigationToolbar2._mouse_event_to_message(event)
  262. self.toolmanager.message_event(message, self)
  263. class RubberbandBase(ToolBase):
  264. """Draw and remove a rubberband."""
  265. def trigger(self, sender, event, data=None):
  266. """Call `draw_rubberband` or `remove_rubberband` based on data."""
  267. if not self.figure.canvas.widgetlock.available(sender):
  268. return
  269. if data is not None:
  270. self.draw_rubberband(*data)
  271. else:
  272. self.remove_rubberband()
  273. def draw_rubberband(self, *data):
  274. """
  275. Draw rubberband.
  276. This method must get implemented per backend.
  277. """
  278. raise NotImplementedError
  279. def remove_rubberband(self):
  280. """
  281. Remove rubberband.
  282. This method should get implemented per backend.
  283. """
  284. pass
  285. class ToolQuit(ToolBase):
  286. """Tool to call the figure manager destroy method."""
  287. description = 'Quit the figure'
  288. default_keymap = property(lambda self: mpl.rcParams['keymap.quit'])
  289. def trigger(self, sender, event, data=None):
  290. Gcf.destroy_fig(self.figure)
  291. class ToolQuitAll(ToolBase):
  292. """Tool to call the figure manager destroy method."""
  293. description = 'Quit all figures'
  294. default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all'])
  295. def trigger(self, sender, event, data=None):
  296. Gcf.destroy_all()
  297. class ToolGrid(ToolBase):
  298. """Tool to toggle the major grids of the figure."""
  299. description = 'Toggle major grids'
  300. default_keymap = property(lambda self: mpl.rcParams['keymap.grid'])
  301. def trigger(self, sender, event, data=None):
  302. sentinel = str(uuid.uuid4())
  303. # Trigger grid switching by temporarily setting :rc:`keymap.grid`
  304. # to a unique key and sending an appropriate event.
  305. with cbook._setattr_cm(event, key=sentinel), \
  306. mpl.rc_context({'keymap.grid': sentinel}):
  307. mpl.backend_bases.key_press_handler(event, self.figure.canvas)
  308. class ToolMinorGrid(ToolBase):
  309. """Tool to toggle the major and minor grids of the figure."""
  310. description = 'Toggle major and minor grids'
  311. default_keymap = property(lambda self: mpl.rcParams['keymap.grid_minor'])
  312. def trigger(self, sender, event, data=None):
  313. sentinel = str(uuid.uuid4())
  314. # Trigger grid switching by temporarily setting :rc:`keymap.grid_minor`
  315. # to a unique key and sending an appropriate event.
  316. with cbook._setattr_cm(event, key=sentinel), \
  317. mpl.rc_context({'keymap.grid_minor': sentinel}):
  318. mpl.backend_bases.key_press_handler(event, self.figure.canvas)
  319. class ToolFullScreen(ToolBase):
  320. """Tool to toggle full screen."""
  321. description = 'Toggle fullscreen mode'
  322. default_keymap = property(lambda self: mpl.rcParams['keymap.fullscreen'])
  323. def trigger(self, sender, event, data=None):
  324. self.figure.canvas.manager.full_screen_toggle()
  325. class AxisScaleBase(ToolToggleBase):
  326. """Base Tool to toggle between linear and logarithmic."""
  327. def trigger(self, sender, event, data=None):
  328. if event.inaxes is None:
  329. return
  330. super().trigger(sender, event, data)
  331. def enable(self, event=None):
  332. self.set_scale(event.inaxes, 'log')
  333. self.figure.canvas.draw_idle()
  334. def disable(self, event=None):
  335. self.set_scale(event.inaxes, 'linear')
  336. self.figure.canvas.draw_idle()
  337. class ToolYScale(AxisScaleBase):
  338. """Tool to toggle between linear and logarithmic scales on the Y axis."""
  339. description = 'Toggle scale Y axis'
  340. default_keymap = property(lambda self: mpl.rcParams['keymap.yscale'])
  341. def set_scale(self, ax, scale):
  342. ax.set_yscale(scale)
  343. class ToolXScale(AxisScaleBase):
  344. """Tool to toggle between linear and logarithmic scales on the X axis."""
  345. description = 'Toggle scale X axis'
  346. default_keymap = property(lambda self: mpl.rcParams['keymap.xscale'])
  347. def set_scale(self, ax, scale):
  348. ax.set_xscale(scale)
  349. class ToolViewsPositions(ToolBase):
  350. """
  351. Auxiliary Tool to handle changes in views and positions.
  352. Runs in the background and should get used by all the tools that
  353. need to access the figure's history of views and positions, e.g.
  354. * `ToolZoom`
  355. * `ToolPan`
  356. * `ToolHome`
  357. * `ToolBack`
  358. * `ToolForward`
  359. """
  360. def __init__(self, *args, **kwargs):
  361. self.views = WeakKeyDictionary()
  362. self.positions = WeakKeyDictionary()
  363. self.home_views = WeakKeyDictionary()
  364. super().__init__(*args, **kwargs)
  365. def add_figure(self, figure):
  366. """Add the current figure to the stack of views and positions."""
  367. if figure not in self.views:
  368. self.views[figure] = cbook._Stack()
  369. self.positions[figure] = cbook._Stack()
  370. self.home_views[figure] = WeakKeyDictionary()
  371. # Define Home
  372. self.push_current(figure)
  373. # Make sure we add a home view for new axes as they're added
  374. figure.add_axobserver(lambda fig: self.update_home_views(fig))
  375. def clear(self, figure):
  376. """Reset the axes stack."""
  377. if figure in self.views:
  378. self.views[figure].clear()
  379. self.positions[figure].clear()
  380. self.home_views[figure].clear()
  381. self.update_home_views()
  382. def update_view(self):
  383. """
  384. Update the view limits and position for each axes from the current
  385. stack position. If any axes are present in the figure that aren't in
  386. the current stack position, use the home view limits for those axes and
  387. don't update *any* positions.
  388. """
  389. views = self.views[self.figure]()
  390. if views is None:
  391. return
  392. pos = self.positions[self.figure]()
  393. if pos is None:
  394. return
  395. home_views = self.home_views[self.figure]
  396. all_axes = self.figure.get_axes()
  397. for a in all_axes:
  398. if a in views:
  399. cur_view = views[a]
  400. else:
  401. cur_view = home_views[a]
  402. a._set_view(cur_view)
  403. if set(all_axes).issubset(pos):
  404. for a in all_axes:
  405. # Restore both the original and modified positions
  406. a._set_position(pos[a][0], 'original')
  407. a._set_position(pos[a][1], 'active')
  408. self.figure.canvas.draw_idle()
  409. def push_current(self, figure=None):
  410. """
  411. Push the current view limits and position onto their respective stacks.
  412. """
  413. if not figure:
  414. figure = self.figure
  415. views = WeakKeyDictionary()
  416. pos = WeakKeyDictionary()
  417. for a in figure.get_axes():
  418. views[a] = a._get_view()
  419. pos[a] = self._axes_pos(a)
  420. self.views[figure].push(views)
  421. self.positions[figure].push(pos)
  422. def _axes_pos(self, ax):
  423. """
  424. Return the original and modified positions for the specified axes.
  425. Parameters
  426. ----------
  427. ax : matplotlib.axes.Axes
  428. The `.Axes` to get the positions for.
  429. Returns
  430. -------
  431. original_position, modified_position
  432. A tuple of the original and modified positions.
  433. """
  434. return (ax.get_position(True).frozen(),
  435. ax.get_position().frozen())
  436. def update_home_views(self, figure=None):
  437. """
  438. Make sure that ``self.home_views`` has an entry for all axes present
  439. in the figure.
  440. """
  441. if not figure:
  442. figure = self.figure
  443. for a in figure.get_axes():
  444. if a not in self.home_views[figure]:
  445. self.home_views[figure][a] = a._get_view()
  446. def home(self):
  447. """Recall the first view and position from the stack."""
  448. self.views[self.figure].home()
  449. self.positions[self.figure].home()
  450. def back(self):
  451. """Back one step in the stack of views and positions."""
  452. self.views[self.figure].back()
  453. self.positions[self.figure].back()
  454. def forward(self):
  455. """Forward one step in the stack of views and positions."""
  456. self.views[self.figure].forward()
  457. self.positions[self.figure].forward()
  458. class ViewsPositionsBase(ToolBase):
  459. """Base class for `ToolHome`, `ToolBack` and `ToolForward`."""
  460. _on_trigger = None
  461. def trigger(self, sender, event, data=None):
  462. self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
  463. getattr(self.toolmanager.get_tool(_views_positions),
  464. self._on_trigger)()
  465. self.toolmanager.get_tool(_views_positions).update_view()
  466. class ToolHome(ViewsPositionsBase):
  467. """Restore the original view limits."""
  468. description = 'Reset original view'
  469. image = 'home'
  470. default_keymap = property(lambda self: mpl.rcParams['keymap.home'])
  471. _on_trigger = 'home'
  472. class ToolBack(ViewsPositionsBase):
  473. """Move back up the view limits stack."""
  474. description = 'Back to previous view'
  475. image = 'back'
  476. default_keymap = property(lambda self: mpl.rcParams['keymap.back'])
  477. _on_trigger = 'back'
  478. class ToolForward(ViewsPositionsBase):
  479. """Move forward in the view lim stack."""
  480. description = 'Forward to next view'
  481. image = 'forward'
  482. default_keymap = property(lambda self: mpl.rcParams['keymap.forward'])
  483. _on_trigger = 'forward'
  484. class ConfigureSubplotsBase(ToolBase):
  485. """Base tool for the configuration of subplots."""
  486. description = 'Configure subplots'
  487. image = 'subplots'
  488. class SaveFigureBase(ToolBase):
  489. """Base tool for figure saving."""
  490. description = 'Save the figure'
  491. image = 'filesave'
  492. default_keymap = property(lambda self: mpl.rcParams['keymap.save'])
  493. class ZoomPanBase(ToolToggleBase):
  494. """Base class for `ToolZoom` and `ToolPan`."""
  495. def __init__(self, *args):
  496. super().__init__(*args)
  497. self._button_pressed = None
  498. self._xypress = None
  499. self._idPress = None
  500. self._idRelease = None
  501. self._idScroll = None
  502. self.base_scale = 2.
  503. self.scrollthresh = .5 # .5 second scroll threshold
  504. self.lastscroll = time.time()-self.scrollthresh
  505. def enable(self, event=None):
  506. """Connect press/release events and lock the canvas."""
  507. self.figure.canvas.widgetlock(self)
  508. self._idPress = self.figure.canvas.mpl_connect(
  509. 'button_press_event', self._press)
  510. self._idRelease = self.figure.canvas.mpl_connect(
  511. 'button_release_event', self._release)
  512. self._idScroll = self.figure.canvas.mpl_connect(
  513. 'scroll_event', self.scroll_zoom)
  514. def disable(self, event=None):
  515. """Release the canvas and disconnect press/release events."""
  516. self._cancel_action()
  517. self.figure.canvas.widgetlock.release(self)
  518. self.figure.canvas.mpl_disconnect(self._idPress)
  519. self.figure.canvas.mpl_disconnect(self._idRelease)
  520. self.figure.canvas.mpl_disconnect(self._idScroll)
  521. def trigger(self, sender, event, data=None):
  522. self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
  523. super().trigger(sender, event, data)
  524. new_navigate_mode = self.name.upper() if self.toggled else None
  525. for ax in self.figure.axes:
  526. ax.set_navigate_mode(new_navigate_mode)
  527. def scroll_zoom(self, event):
  528. # https://gist.github.com/tacaswell/3144287
  529. if event.inaxes is None:
  530. return
  531. if event.button == 'up':
  532. # deal with zoom in
  533. scl = self.base_scale
  534. elif event.button == 'down':
  535. # deal with zoom out
  536. scl = 1/self.base_scale
  537. else:
  538. # deal with something that should never happen
  539. scl = 1
  540. ax = event.inaxes
  541. ax._set_view_from_bbox([event.x, event.y, scl])
  542. # If last scroll was done within the timing threshold, delete the
  543. # previous view
  544. if (time.time()-self.lastscroll) < self.scrollthresh:
  545. self.toolmanager.get_tool(_views_positions).back()
  546. self.figure.canvas.draw_idle() # force re-draw
  547. self.lastscroll = time.time()
  548. self.toolmanager.get_tool(_views_positions).push_current()
  549. class ToolZoom(ZoomPanBase):
  550. """A Tool for zooming using a rectangle selector."""
  551. description = 'Zoom to rectangle'
  552. image = 'zoom_to_rect'
  553. default_keymap = property(lambda self: mpl.rcParams['keymap.zoom'])
  554. cursor = cursors.SELECT_REGION
  555. radio_group = 'default'
  556. def __init__(self, *args):
  557. super().__init__(*args)
  558. self._ids_zoom = []
  559. def _cancel_action(self):
  560. for zoom_id in self._ids_zoom:
  561. self.figure.canvas.mpl_disconnect(zoom_id)
  562. self.toolmanager.trigger_tool('rubberband', self)
  563. self.figure.canvas.draw_idle()
  564. self._xypress = None
  565. self._button_pressed = None
  566. self._ids_zoom = []
  567. return
  568. def _press(self, event):
  569. """Callback for mouse button presses in zoom-to-rectangle mode."""
  570. # If we're already in the middle of a zoom, pressing another
  571. # button works to "cancel"
  572. if self._ids_zoom:
  573. self._cancel_action()
  574. if event.button == 1:
  575. self._button_pressed = 1
  576. elif event.button == 3:
  577. self._button_pressed = 3
  578. else:
  579. self._cancel_action()
  580. return
  581. x, y = event.x, event.y
  582. self._xypress = []
  583. for i, a in enumerate(self.figure.get_axes()):
  584. if (x is not None and y is not None and a.in_axes(event) and
  585. a.get_navigate() and a.can_zoom()):
  586. self._xypress.append((x, y, a, i, a._get_view()))
  587. id1 = self.figure.canvas.mpl_connect(
  588. 'motion_notify_event', self._mouse_move)
  589. id2 = self.figure.canvas.mpl_connect(
  590. 'key_press_event', self._switch_on_zoom_mode)
  591. id3 = self.figure.canvas.mpl_connect(
  592. 'key_release_event', self._switch_off_zoom_mode)
  593. self._ids_zoom = id1, id2, id3
  594. self._zoom_mode = event.key
  595. def _switch_on_zoom_mode(self, event):
  596. self._zoom_mode = event.key
  597. self._mouse_move(event)
  598. def _switch_off_zoom_mode(self, event):
  599. self._zoom_mode = None
  600. self._mouse_move(event)
  601. def _mouse_move(self, event):
  602. """Callback for mouse moves in zoom-to-rectangle mode."""
  603. if self._xypress:
  604. x, y = event.x, event.y
  605. lastx, lasty, a, ind, view = self._xypress[0]
  606. (x1, y1), (x2, y2) = np.clip(
  607. [[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
  608. if self._zoom_mode == "x":
  609. y1, y2 = a.bbox.intervaly
  610. elif self._zoom_mode == "y":
  611. x1, x2 = a.bbox.intervalx
  612. self.toolmanager.trigger_tool(
  613. 'rubberband', self, data=(x1, y1, x2, y2))
  614. def _release(self, event):
  615. """Callback for mouse button releases in zoom-to-rectangle mode."""
  616. for zoom_id in self._ids_zoom:
  617. self.figure.canvas.mpl_disconnect(zoom_id)
  618. self._ids_zoom = []
  619. if not self._xypress:
  620. self._cancel_action()
  621. return
  622. done_ax = []
  623. for cur_xypress in self._xypress:
  624. x, y = event.x, event.y
  625. lastx, lasty, a, _ind, view = cur_xypress
  626. # ignore singular clicks - 5 pixels is a threshold
  627. if abs(x - lastx) < 5 or abs(y - lasty) < 5:
  628. self._cancel_action()
  629. return
  630. # detect twinx, twiny axes and avoid double zooming
  631. twinx = any(a.get_shared_x_axes().joined(a, a1) for a1 in done_ax)
  632. twiny = any(a.get_shared_y_axes().joined(a, a1) for a1 in done_ax)
  633. done_ax.append(a)
  634. if self._button_pressed == 1:
  635. direction = 'in'
  636. elif self._button_pressed == 3:
  637. direction = 'out'
  638. else:
  639. continue
  640. a._set_view_from_bbox((lastx, lasty, x, y), direction,
  641. self._zoom_mode, twinx, twiny)
  642. self._zoom_mode = None
  643. self.toolmanager.get_tool(_views_positions).push_current()
  644. self._cancel_action()
  645. class ToolPan(ZoomPanBase):
  646. """Pan axes with left mouse, zoom with right."""
  647. default_keymap = property(lambda self: mpl.rcParams['keymap.pan'])
  648. description = 'Pan axes with left mouse, zoom with right'
  649. image = 'move'
  650. cursor = cursors.MOVE
  651. radio_group = 'default'
  652. def __init__(self, *args):
  653. super().__init__(*args)
  654. self._id_drag = None
  655. def _cancel_action(self):
  656. self._button_pressed = None
  657. self._xypress = []
  658. self.figure.canvas.mpl_disconnect(self._id_drag)
  659. self.toolmanager.messagelock.release(self)
  660. self.figure.canvas.draw_idle()
  661. def _press(self, event):
  662. if event.button == 1:
  663. self._button_pressed = 1
  664. elif event.button == 3:
  665. self._button_pressed = 3
  666. else:
  667. self._cancel_action()
  668. return
  669. x, y = event.x, event.y
  670. self._xypress = []
  671. for i, a in enumerate(self.figure.get_axes()):
  672. if (x is not None and y is not None and a.in_axes(event) and
  673. a.get_navigate() and a.can_pan()):
  674. a.start_pan(x, y, event.button)
  675. self._xypress.append((a, i))
  676. self.toolmanager.messagelock(self)
  677. self._id_drag = self.figure.canvas.mpl_connect(
  678. 'motion_notify_event', self._mouse_move)
  679. def _release(self, event):
  680. if self._button_pressed is None:
  681. self._cancel_action()
  682. return
  683. self.figure.canvas.mpl_disconnect(self._id_drag)
  684. self.toolmanager.messagelock.release(self)
  685. for a, _ind in self._xypress:
  686. a.end_pan()
  687. if not self._xypress:
  688. self._cancel_action()
  689. return
  690. self.toolmanager.get_tool(_views_positions).push_current()
  691. self._cancel_action()
  692. def _mouse_move(self, event):
  693. for a, _ind in self._xypress:
  694. # safer to use the recorded button at the _press than current
  695. # button: # multiple button can get pressed during motion...
  696. a.drag_pan(self._button_pressed, event.key, event.x, event.y)
  697. self.toolmanager.canvas.draw_idle()
  698. class ToolHelpBase(ToolBase):
  699. description = 'Print tool list, shortcuts and description'
  700. default_keymap = property(lambda self: mpl.rcParams['keymap.help'])
  701. image = 'help'
  702. @staticmethod
  703. def format_shortcut(key_sequence):
  704. """
  705. Convert a shortcut string from the notation used in rc config to the
  706. standard notation for displaying shortcuts, e.g. 'ctrl+a' -> 'Ctrl+A'.
  707. """
  708. return (key_sequence if len(key_sequence) == 1 else
  709. re.sub(r"\+[A-Z]", r"+Shift\g<0>", key_sequence).title())
  710. def _format_tool_keymap(self, name):
  711. keymaps = self.toolmanager.get_tool_keymap(name)
  712. return ", ".join(self.format_shortcut(keymap) for keymap in keymaps)
  713. def _get_help_entries(self):
  714. return [(name, self._format_tool_keymap(name), tool.description)
  715. for name, tool in sorted(self.toolmanager.tools.items())
  716. if tool.description]
  717. def _get_help_text(self):
  718. entries = self._get_help_entries()
  719. entries = ["{}: {}\n\t{}".format(*entry) for entry in entries]
  720. return "\n".join(entries)
  721. def _get_help_html(self):
  722. fmt = "<tr><td>{}</td><td>{}</td><td>{}</td></tr>"
  723. rows = [fmt.format(
  724. "<b>Action</b>", "<b>Shortcuts</b>", "<b>Description</b>")]
  725. rows += [fmt.format(*row) for row in self._get_help_entries()]
  726. return ("<style>td {padding: 0px 4px}</style>"
  727. "<table><thead>" + rows[0] + "</thead>"
  728. "<tbody>".join(rows[1:]) + "</tbody></table>")
  729. class ToolCopyToClipboardBase(ToolBase):
  730. """Tool to copy the figure to the clipboard."""
  731. description = 'Copy the canvas figure to clipboard'
  732. default_keymap = property(lambda self: mpl.rcParams['keymap.copy'])
  733. def trigger(self, *args, **kwargs):
  734. message = "Copy tool is not available"
  735. self.toolmanager.message_event(message, self)
  736. default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward,
  737. 'zoom': ToolZoom, 'pan': ToolPan,
  738. 'subplots': ConfigureSubplotsBase,
  739. 'save': SaveFigureBase,
  740. 'grid': ToolGrid,
  741. 'grid_minor': ToolMinorGrid,
  742. 'fullscreen': ToolFullScreen,
  743. 'quit': ToolQuit,
  744. 'quit_all': ToolQuitAll,
  745. 'xscale': ToolXScale,
  746. 'yscale': ToolYScale,
  747. 'position': ToolCursorPosition,
  748. _views_positions: ToolViewsPositions,
  749. 'cursor': ToolSetCursor,
  750. 'rubberband': RubberbandBase,
  751. 'help': ToolHelpBase,
  752. 'copy': ToolCopyToClipboardBase,
  753. }
  754. default_toolbar_tools = [['navigation', ['home', 'back', 'forward']],
  755. ['zoompan', ['pan', 'zoom', 'subplots']],
  756. ['io', ['save', 'help']]]
  757. def add_tools_to_manager(toolmanager, tools=default_tools):
  758. """
  759. Add multiple tools to a `.ToolManager`.
  760. Parameters
  761. ----------
  762. toolmanager : `.backend_managers.ToolManager`
  763. Manager to which the tools are added.
  764. tools : {str: class_like}, optional
  765. The tools to add in a {name: tool} dict, see
  766. `.backend_managers.ToolManager.add_tool` for more info.
  767. """
  768. for name, tool in tools.items():
  769. toolmanager.add_tool(name, tool)
  770. def add_tools_to_container(container, tools=default_toolbar_tools):
  771. """
  772. Add multiple tools to the container.
  773. Parameters
  774. ----------
  775. container : Container
  776. `.backend_bases.ToolContainerBase` object that will get the tools
  777. added.
  778. tools : list, optional
  779. List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]``
  780. where the tools ``[tool1, tool2, ...]`` will display in group1.
  781. See `.backend_bases.ToolContainerBase.add_tool` for details.
  782. """
  783. for group, grouptools in tools:
  784. for position, tool in enumerate(grouptools):
  785. container.add_tool(tool, group, position)