backend_wx.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  1. """
  2. A wxPython backend for matplotlib.
  3. Originally contributed by Jeremy O'Donoghue (jeremy@o-donoghue.com) and John
  4. Hunter (jdhunter@ace.bsd.uchicago.edu).
  5. Copyright (C) Jeremy O'Donoghue & John Hunter, 2003-4.
  6. """
  7. import logging
  8. import math
  9. import pathlib
  10. import sys
  11. import weakref
  12. import numpy as np
  13. import PIL
  14. import matplotlib as mpl
  15. from matplotlib.backend_bases import (
  16. _Backend, _check_savefig_extra_args, FigureCanvasBase, FigureManagerBase,
  17. GraphicsContextBase, MouseButton, NavigationToolbar2, RendererBase,
  18. StatusbarBase, TimerBase, ToolContainerBase, cursors)
  19. from matplotlib import cbook, backend_tools
  20. from matplotlib._pylab_helpers import Gcf
  21. from matplotlib.backend_managers import ToolManager
  22. from matplotlib.figure import Figure
  23. from matplotlib.path import Path
  24. from matplotlib.transforms import Affine2D
  25. from matplotlib.widgets import SubplotTool
  26. import wx
  27. _log = logging.getLogger(__name__)
  28. # Debugging settings here...
  29. # Debug level set here. If the debug level is less than 5, information
  30. # messages (progressively more info for lower value) are printed. In addition,
  31. # traceback is performed, and pdb activated, for all uncaught exceptions in
  32. # this case
  33. _DEBUG = 5
  34. _DEBUG_lvls = {1: 'Low ', 2: 'Med ', 3: 'High', 4: 'Error'}
  35. @cbook.deprecated("3.3")
  36. def DEBUG_MSG(string, lvl=3, o=None):
  37. if lvl >= _DEBUG:
  38. print(f"{_DEBUG_lvls[lvl]}- {string} in {type(o)}")
  39. # the True dots per inch on the screen; should be display dependent; see
  40. # http://groups.google.com/groups?q=screen+dpi+x11&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=7077.26e81ad5%40swift.cs.tcd.ie&rnum=5
  41. # for some info about screen dpi
  42. PIXELS_PER_INCH = 75
  43. # Delay time for idle checks
  44. IDLE_DELAY = 5 # Documented as deprecated as of Matplotlib 3.1.
  45. def error_msg_wx(msg, parent=None):
  46. """Signal an error condition with a popup error dialog."""
  47. dialog = wx.MessageDialog(parent=parent,
  48. message=msg,
  49. caption='Matplotlib backend_wx error',
  50. style=wx.OK | wx.CENTRE)
  51. dialog.ShowModal()
  52. dialog.Destroy()
  53. return None
  54. class TimerWx(TimerBase):
  55. """Subclass of `.TimerBase` using wx.Timer events."""
  56. def __init__(self, *args, **kwargs):
  57. self._timer = wx.Timer()
  58. self._timer.Notify = self._on_timer
  59. TimerBase.__init__(self, *args, **kwargs)
  60. def _timer_start(self):
  61. self._timer.Start(self._interval, self._single)
  62. def _timer_stop(self):
  63. self._timer.Stop()
  64. def _timer_set_interval(self):
  65. if self._timer.IsRunning():
  66. self._timer_start() # Restart with new interval.
  67. class RendererWx(RendererBase):
  68. """
  69. The renderer handles all the drawing primitives using a graphics
  70. context instance that controls the colors/styles. It acts as the
  71. 'renderer' instance used by many classes in the hierarchy.
  72. """
  73. # In wxPython, drawing is performed on a wxDC instance, which will
  74. # generally be mapped to the client area of the window displaying
  75. # the plot. Under wxPython, the wxDC instance has a wx.Pen which
  76. # describes the colour and weight of any lines drawn, and a wxBrush
  77. # which describes the fill colour of any closed polygon.
  78. # Font styles, families and weight.
  79. fontweights = {
  80. 100: wx.FONTWEIGHT_LIGHT,
  81. 200: wx.FONTWEIGHT_LIGHT,
  82. 300: wx.FONTWEIGHT_LIGHT,
  83. 400: wx.FONTWEIGHT_NORMAL,
  84. 500: wx.FONTWEIGHT_NORMAL,
  85. 600: wx.FONTWEIGHT_NORMAL,
  86. 700: wx.FONTWEIGHT_BOLD,
  87. 800: wx.FONTWEIGHT_BOLD,
  88. 900: wx.FONTWEIGHT_BOLD,
  89. 'ultralight': wx.FONTWEIGHT_LIGHT,
  90. 'light': wx.FONTWEIGHT_LIGHT,
  91. 'normal': wx.FONTWEIGHT_NORMAL,
  92. 'medium': wx.FONTWEIGHT_NORMAL,
  93. 'semibold': wx.FONTWEIGHT_NORMAL,
  94. 'bold': wx.FONTWEIGHT_BOLD,
  95. 'heavy': wx.FONTWEIGHT_BOLD,
  96. 'ultrabold': wx.FONTWEIGHT_BOLD,
  97. 'black': wx.FONTWEIGHT_BOLD,
  98. }
  99. fontangles = {
  100. 'italic': wx.FONTSTYLE_ITALIC,
  101. 'normal': wx.FONTSTYLE_NORMAL,
  102. 'oblique': wx.FONTSTYLE_SLANT,
  103. }
  104. # wxPython allows for portable font styles, choosing them appropriately for
  105. # the target platform. Map some standard font names to the portable styles.
  106. # QUESTION: Is it be wise to agree standard fontnames across all backends?
  107. fontnames = {
  108. 'Sans': wx.FONTFAMILY_SWISS,
  109. 'Roman': wx.FONTFAMILY_ROMAN,
  110. 'Script': wx.FONTFAMILY_SCRIPT,
  111. 'Decorative': wx.FONTFAMILY_DECORATIVE,
  112. 'Modern': wx.FONTFAMILY_MODERN,
  113. 'Courier': wx.FONTFAMILY_MODERN,
  114. 'courier': wx.FONTFAMILY_MODERN,
  115. }
  116. def __init__(self, bitmap, dpi):
  117. """Initialise a wxWindows renderer instance."""
  118. cbook.warn_deprecated(
  119. "2.0", name="wx", obj_type="backend", removal="the future",
  120. alternative="wxagg", addendum="See the Matplotlib usage FAQ for "
  121. "more info on backends.")
  122. RendererBase.__init__(self)
  123. _log.debug("%s - __init__()", type(self))
  124. self.width = bitmap.GetWidth()
  125. self.height = bitmap.GetHeight()
  126. self.bitmap = bitmap
  127. self.fontd = {}
  128. self.dpi = dpi
  129. self.gc = None
  130. def flipy(self):
  131. # docstring inherited
  132. return True
  133. def offset_text_height(self):
  134. return True
  135. def get_text_width_height_descent(self, s, prop, ismath):
  136. # docstring inherited
  137. if ismath:
  138. s = cbook.strip_math(s)
  139. if self.gc is None:
  140. gc = self.new_gc()
  141. else:
  142. gc = self.gc
  143. gfx_ctx = gc.gfx_ctx
  144. font = self.get_wx_font(s, prop)
  145. gfx_ctx.SetFont(font, wx.BLACK)
  146. w, h, descent, leading = gfx_ctx.GetFullTextExtent(s)
  147. return w, h, descent
  148. def get_canvas_width_height(self):
  149. # docstring inherited
  150. return self.width, self.height
  151. def handle_clip_rectangle(self, gc):
  152. new_bounds = gc.get_clip_rectangle()
  153. if new_bounds is not None:
  154. new_bounds = new_bounds.bounds
  155. gfx_ctx = gc.gfx_ctx
  156. if gfx_ctx._lastcliprect != new_bounds:
  157. gfx_ctx._lastcliprect = new_bounds
  158. if new_bounds is None:
  159. gfx_ctx.ResetClip()
  160. else:
  161. gfx_ctx.Clip(new_bounds[0],
  162. self.height - new_bounds[1] - new_bounds[3],
  163. new_bounds[2], new_bounds[3])
  164. @staticmethod
  165. def convert_path(gfx_ctx, path, transform):
  166. wxpath = gfx_ctx.CreatePath()
  167. for points, code in path.iter_segments(transform):
  168. if code == Path.MOVETO:
  169. wxpath.MoveToPoint(*points)
  170. elif code == Path.LINETO:
  171. wxpath.AddLineToPoint(*points)
  172. elif code == Path.CURVE3:
  173. wxpath.AddQuadCurveToPoint(*points)
  174. elif code == Path.CURVE4:
  175. wxpath.AddCurveToPoint(*points)
  176. elif code == Path.CLOSEPOLY:
  177. wxpath.CloseSubpath()
  178. return wxpath
  179. def draw_path(self, gc, path, transform, rgbFace=None):
  180. # docstring inherited
  181. gc.select()
  182. self.handle_clip_rectangle(gc)
  183. gfx_ctx = gc.gfx_ctx
  184. transform = transform + \
  185. Affine2D().scale(1.0, -1.0).translate(0.0, self.height)
  186. wxpath = self.convert_path(gfx_ctx, path, transform)
  187. if rgbFace is not None:
  188. gfx_ctx.SetBrush(wx.Brush(gc.get_wxcolour(rgbFace)))
  189. gfx_ctx.DrawPath(wxpath)
  190. else:
  191. gfx_ctx.StrokePath(wxpath)
  192. gc.unselect()
  193. def draw_image(self, gc, x, y, im):
  194. bbox = gc.get_clip_rectangle()
  195. if bbox is not None:
  196. l, b, w, h = bbox.bounds
  197. else:
  198. l = 0
  199. b = 0
  200. w = self.width
  201. h = self.height
  202. rows, cols = im.shape[:2]
  203. bitmap = wx.Bitmap.FromBufferRGBA(cols, rows, im.tobytes())
  204. gc.select()
  205. gc.gfx_ctx.DrawBitmap(bitmap, int(l), int(self.height - b),
  206. int(w), int(-h))
  207. gc.unselect()
  208. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  209. # docstring inherited
  210. if ismath:
  211. s = cbook.strip_math(s)
  212. _log.debug("%s - draw_text()", type(self))
  213. gc.select()
  214. self.handle_clip_rectangle(gc)
  215. gfx_ctx = gc.gfx_ctx
  216. font = self.get_wx_font(s, prop)
  217. color = gc.get_wxcolour(gc.get_rgb())
  218. gfx_ctx.SetFont(font, color)
  219. w, h, d = self.get_text_width_height_descent(s, prop, ismath)
  220. x = int(x)
  221. y = int(y - h)
  222. if angle == 0.0:
  223. gfx_ctx.DrawText(s, x, y)
  224. else:
  225. rads = math.radians(angle)
  226. xo = h * math.sin(rads)
  227. yo = h * math.cos(rads)
  228. gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads)
  229. gc.unselect()
  230. def new_gc(self):
  231. # docstring inherited
  232. _log.debug("%s - new_gc()", type(self))
  233. self.gc = GraphicsContextWx(self.bitmap, self)
  234. self.gc.select()
  235. self.gc.unselect()
  236. return self.gc
  237. @cbook.deprecated("3.3", alternative=".gc")
  238. def get_gc(self):
  239. """
  240. Fetch the locally cached gc.
  241. """
  242. # This is a dirty hack to allow anything with access to a renderer to
  243. # access the current graphics context
  244. assert self.gc is not None, "gc must be defined"
  245. return self.gc
  246. def get_wx_font(self, s, prop):
  247. """Return a wx font. Cache font instances for efficiency."""
  248. _log.debug("%s - get_wx_font()", type(self))
  249. key = hash(prop)
  250. font = self.fontd.get(key)
  251. if font is not None:
  252. return font
  253. # Font colour is determined by the active wx.Pen
  254. # TODO: It may be wise to cache font information
  255. self.fontd[key] = font = wx.Font( # Cache the font and gc.
  256. pointSize=self.points_to_pixels(prop.get_size_in_points()),
  257. family=self.fontnames.get(prop.get_name(), wx.ROMAN),
  258. style=self.fontangles[prop.get_style()],
  259. weight=self.fontweights[prop.get_weight()])
  260. return font
  261. def points_to_pixels(self, points):
  262. # docstring inherited
  263. return points * (PIXELS_PER_INCH / 72.0 * self.dpi / 72.0)
  264. class GraphicsContextWx(GraphicsContextBase):
  265. """
  266. The graphics context provides the color, line styles, etc...
  267. This class stores a reference to a wxMemoryDC, and a
  268. wxGraphicsContext that draws to it. Creating a wxGraphicsContext
  269. seems to be fairly heavy, so these objects are cached based on the
  270. bitmap object that is passed in.
  271. The base GraphicsContext stores colors as a RGB tuple on the unit
  272. interval, e.g., (0.5, 0.0, 1.0). wxPython uses an int interval, but
  273. since wxPython colour management is rather simple, I have not chosen
  274. to implement a separate colour manager class.
  275. """
  276. _capd = {'butt': wx.CAP_BUTT,
  277. 'projecting': wx.CAP_PROJECTING,
  278. 'round': wx.CAP_ROUND}
  279. _joind = {'bevel': wx.JOIN_BEVEL,
  280. 'miter': wx.JOIN_MITER,
  281. 'round': wx.JOIN_ROUND}
  282. _cache = weakref.WeakKeyDictionary()
  283. def __init__(self, bitmap, renderer):
  284. GraphicsContextBase.__init__(self)
  285. # assert self.Ok(), "wxMemoryDC not OK to use"
  286. _log.debug("%s - __init__(): %s", type(self), bitmap)
  287. dc, gfx_ctx = self._cache.get(bitmap, (None, None))
  288. if dc is None:
  289. dc = wx.MemoryDC()
  290. dc.SelectObject(bitmap)
  291. gfx_ctx = wx.GraphicsContext.Create(dc)
  292. gfx_ctx._lastcliprect = None
  293. self._cache[bitmap] = dc, gfx_ctx
  294. self.bitmap = bitmap
  295. self.dc = dc
  296. self.gfx_ctx = gfx_ctx
  297. self._pen = wx.Pen('BLACK', 1, wx.SOLID)
  298. gfx_ctx.SetPen(self._pen)
  299. self.renderer = renderer
  300. def select(self):
  301. """Select the current bitmap into this wxDC instance."""
  302. if sys.platform == 'win32':
  303. self.dc.SelectObject(self.bitmap)
  304. self.IsSelected = True
  305. def unselect(self):
  306. """Select a Null bitmap into this wxDC instance."""
  307. if sys.platform == 'win32':
  308. self.dc.SelectObject(wx.NullBitmap)
  309. self.IsSelected = False
  310. def set_foreground(self, fg, isRGBA=None):
  311. # docstring inherited
  312. # Implementation note: wxPython has a separate concept of pen and
  313. # brush - the brush fills any outline trace left by the pen.
  314. # Here we set both to the same colour - if a figure is not to be
  315. # filled, the renderer will set the brush to be transparent
  316. # Same goes for text foreground...
  317. _log.debug("%s - set_foreground()", type(self))
  318. self.select()
  319. GraphicsContextBase.set_foreground(self, fg, isRGBA)
  320. self._pen.SetColour(self.get_wxcolour(self.get_rgb()))
  321. self.gfx_ctx.SetPen(self._pen)
  322. self.unselect()
  323. def set_linewidth(self, w):
  324. # docstring inherited
  325. w = float(w)
  326. _log.debug("%s - set_linewidth()", type(self))
  327. self.select()
  328. if 0 < w < 1:
  329. w = 1
  330. GraphicsContextBase.set_linewidth(self, w)
  331. lw = int(self.renderer.points_to_pixels(self._linewidth))
  332. if lw == 0:
  333. lw = 1
  334. self._pen.SetWidth(lw)
  335. self.gfx_ctx.SetPen(self._pen)
  336. self.unselect()
  337. def set_capstyle(self, cs):
  338. # docstring inherited
  339. _log.debug("%s - set_capstyle()", type(self))
  340. self.select()
  341. GraphicsContextBase.set_capstyle(self, cs)
  342. self._pen.SetCap(GraphicsContextWx._capd[self._capstyle])
  343. self.gfx_ctx.SetPen(self._pen)
  344. self.unselect()
  345. def set_joinstyle(self, js):
  346. # docstring inherited
  347. _log.debug("%s - set_joinstyle()", type(self))
  348. self.select()
  349. GraphicsContextBase.set_joinstyle(self, js)
  350. self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle])
  351. self.gfx_ctx.SetPen(self._pen)
  352. self.unselect()
  353. def get_wxcolour(self, color):
  354. """Convert a RGB(A) color to a wx.Colour."""
  355. _log.debug("%s - get_wx_color()", type(self))
  356. if len(color) == 3:
  357. r, g, b = color
  358. r *= 255
  359. g *= 255
  360. b *= 255
  361. return wx.Colour(red=int(r), green=int(g), blue=int(b))
  362. else:
  363. r, g, b, a = color
  364. r *= 255
  365. g *= 255
  366. b *= 255
  367. a *= 255
  368. return wx.Colour(
  369. red=int(r),
  370. green=int(g),
  371. blue=int(b),
  372. alpha=int(a))
  373. class _FigureCanvasWxBase(FigureCanvasBase, wx.Panel):
  374. """
  375. The FigureCanvas contains the figure and does event handling.
  376. In the wxPython backend, it is derived from wxPanel, and (usually) lives
  377. inside a frame instantiated by a FigureManagerWx. The parent window
  378. probably implements a wx.Sizer to control the displayed control size - but
  379. we give a hint as to our preferred minimum size.
  380. """
  381. required_interactive_framework = "wx"
  382. _timer_cls = TimerWx
  383. keyvald = {
  384. wx.WXK_CONTROL: 'control',
  385. wx.WXK_SHIFT: 'shift',
  386. wx.WXK_ALT: 'alt',
  387. wx.WXK_LEFT: 'left',
  388. wx.WXK_UP: 'up',
  389. wx.WXK_RIGHT: 'right',
  390. wx.WXK_DOWN: 'down',
  391. wx.WXK_ESCAPE: 'escape',
  392. wx.WXK_F1: 'f1',
  393. wx.WXK_F2: 'f2',
  394. wx.WXK_F3: 'f3',
  395. wx.WXK_F4: 'f4',
  396. wx.WXK_F5: 'f5',
  397. wx.WXK_F6: 'f6',
  398. wx.WXK_F7: 'f7',
  399. wx.WXK_F8: 'f8',
  400. wx.WXK_F9: 'f9',
  401. wx.WXK_F10: 'f10',
  402. wx.WXK_F11: 'f11',
  403. wx.WXK_F12: 'f12',
  404. wx.WXK_SCROLL: 'scroll_lock',
  405. wx.WXK_PAUSE: 'break',
  406. wx.WXK_BACK: 'backspace',
  407. wx.WXK_RETURN: 'enter',
  408. wx.WXK_INSERT: 'insert',
  409. wx.WXK_DELETE: 'delete',
  410. wx.WXK_HOME: 'home',
  411. wx.WXK_END: 'end',
  412. wx.WXK_PAGEUP: 'pageup',
  413. wx.WXK_PAGEDOWN: 'pagedown',
  414. wx.WXK_NUMPAD0: '0',
  415. wx.WXK_NUMPAD1: '1',
  416. wx.WXK_NUMPAD2: '2',
  417. wx.WXK_NUMPAD3: '3',
  418. wx.WXK_NUMPAD4: '4',
  419. wx.WXK_NUMPAD5: '5',
  420. wx.WXK_NUMPAD6: '6',
  421. wx.WXK_NUMPAD7: '7',
  422. wx.WXK_NUMPAD8: '8',
  423. wx.WXK_NUMPAD9: '9',
  424. wx.WXK_NUMPAD_ADD: '+',
  425. wx.WXK_NUMPAD_SUBTRACT: '-',
  426. wx.WXK_NUMPAD_MULTIPLY: '*',
  427. wx.WXK_NUMPAD_DIVIDE: '/',
  428. wx.WXK_NUMPAD_DECIMAL: 'dec',
  429. wx.WXK_NUMPAD_ENTER: 'enter',
  430. wx.WXK_NUMPAD_UP: 'up',
  431. wx.WXK_NUMPAD_RIGHT: 'right',
  432. wx.WXK_NUMPAD_DOWN: 'down',
  433. wx.WXK_NUMPAD_LEFT: 'left',
  434. wx.WXK_NUMPAD_PAGEUP: 'pageup',
  435. wx.WXK_NUMPAD_PAGEDOWN: 'pagedown',
  436. wx.WXK_NUMPAD_HOME: 'home',
  437. wx.WXK_NUMPAD_END: 'end',
  438. wx.WXK_NUMPAD_INSERT: 'insert',
  439. wx.WXK_NUMPAD_DELETE: 'delete',
  440. }
  441. def __init__(self, parent, id, figure):
  442. """
  443. Initialize a FigureWx instance.
  444. - Initialize the FigureCanvasBase and wxPanel parents.
  445. - Set event handlers for resize, paint, and keyboard and mouse
  446. interaction.
  447. """
  448. FigureCanvasBase.__init__(self, figure)
  449. w, h = map(math.ceil, figure.bbox.size)
  450. # Set preferred window size hint - helps the sizer, if one is connected
  451. wx.Panel.__init__(self, parent, id, size=wx.Size(w, h))
  452. # Create the drawing bitmap
  453. self.bitmap = wx.Bitmap(w, h)
  454. _log.debug("%s - __init__() - bitmap w:%d h:%d", type(self), w, h)
  455. # TODO: Add support for 'point' inspection and plot navigation.
  456. self._isDrawn = False
  457. self.Bind(wx.EVT_SIZE, self._onSize)
  458. self.Bind(wx.EVT_PAINT, self._onPaint)
  459. self.Bind(wx.EVT_KEY_DOWN, self._onKeyDown)
  460. self.Bind(wx.EVT_KEY_UP, self._onKeyUp)
  461. self.Bind(wx.EVT_LEFT_DOWN, self._onMouseButton)
  462. self.Bind(wx.EVT_LEFT_DCLICK, self._onMouseButton)
  463. self.Bind(wx.EVT_LEFT_UP, self._onMouseButton)
  464. self.Bind(wx.EVT_MIDDLE_DOWN, self._onMouseButton)
  465. self.Bind(wx.EVT_MIDDLE_DCLICK, self._onMouseButton)
  466. self.Bind(wx.EVT_MIDDLE_UP, self._onMouseButton)
  467. self.Bind(wx.EVT_RIGHT_DOWN, self._onMouseButton)
  468. self.Bind(wx.EVT_RIGHT_DCLICK, self._onMouseButton)
  469. self.Bind(wx.EVT_RIGHT_UP, self._onMouseButton)
  470. self.Bind(wx.EVT_MOUSEWHEEL, self._onMouseWheel)
  471. self.Bind(wx.EVT_MOTION, self._onMotion)
  472. self.Bind(wx.EVT_LEAVE_WINDOW, self._onLeave)
  473. self.Bind(wx.EVT_ENTER_WINDOW, self._onEnter)
  474. self.Bind(wx.EVT_MOUSE_CAPTURE_CHANGED, self._onCaptureLost)
  475. self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self._onCaptureLost)
  476. self.SetBackgroundStyle(wx.BG_STYLE_PAINT) # Reduce flicker.
  477. self.SetBackgroundColour(wx.WHITE)
  478. def Copy_to_Clipboard(self, event=None):
  479. """Copy bitmap of canvas to system clipboard."""
  480. bmp_obj = wx.BitmapDataObject()
  481. bmp_obj.SetBitmap(self.bitmap)
  482. if not wx.TheClipboard.IsOpened():
  483. open_success = wx.TheClipboard.Open()
  484. if open_success:
  485. wx.TheClipboard.SetData(bmp_obj)
  486. wx.TheClipboard.Close()
  487. wx.TheClipboard.Flush()
  488. def draw_idle(self):
  489. # docstring inherited
  490. _log.debug("%s - draw_idle()", type(self))
  491. self._isDrawn = False # Force redraw
  492. # Triggering a paint event is all that is needed to defer drawing
  493. # until later. The platform will send the event when it thinks it is
  494. # a good time (usually as soon as there are no other events pending).
  495. self.Refresh(eraseBackground=False)
  496. def flush_events(self):
  497. # docstring inherited
  498. wx.Yield()
  499. def start_event_loop(self, timeout=0):
  500. # docstring inherited
  501. if hasattr(self, '_event_loop'):
  502. raise RuntimeError("Event loop already running")
  503. timer = wx.Timer(self, id=wx.ID_ANY)
  504. if timeout > 0:
  505. timer.Start(timeout * 1000, oneShot=True)
  506. self.Bind(wx.EVT_TIMER, self.stop_event_loop, id=timer.GetId())
  507. # Event loop handler for start/stop event loop
  508. self._event_loop = wx.GUIEventLoop()
  509. self._event_loop.Run()
  510. timer.Stop()
  511. def stop_event_loop(self, event=None):
  512. # docstring inherited
  513. if hasattr(self, '_event_loop'):
  514. if self._event_loop.IsRunning():
  515. self._event_loop.Exit()
  516. del self._event_loop
  517. def _get_imagesave_wildcards(self):
  518. """Return the wildcard string for the filesave dialog."""
  519. default_filetype = self.get_default_filetype()
  520. filetypes = self.get_supported_filetypes_grouped()
  521. sorted_filetypes = sorted(filetypes.items())
  522. wildcards = []
  523. extensions = []
  524. filter_index = 0
  525. for i, (name, exts) in enumerate(sorted_filetypes):
  526. ext_list = ';'.join(['*.%s' % ext for ext in exts])
  527. extensions.append(exts[0])
  528. wildcard = '%s (%s)|%s' % (name, ext_list, ext_list)
  529. if default_filetype in exts:
  530. filter_index = i
  531. wildcards.append(wildcard)
  532. wildcards = '|'.join(wildcards)
  533. return wildcards, extensions, filter_index
  534. def gui_repaint(self, drawDC=None, origin='WX'):
  535. """
  536. Performs update of the displayed image on the GUI canvas, using the
  537. supplied wx.PaintDC device context.
  538. The 'WXAgg' backend sets origin accordingly.
  539. """
  540. _log.debug("%s - gui_repaint()", type(self))
  541. # The "if self" check avoids a "wrapped C/C++ object has been deleted"
  542. # RuntimeError if doing things after window is closed.
  543. if self and self.IsShownOnScreen():
  544. if not drawDC:
  545. # not called from OnPaint use a ClientDC
  546. drawDC = wx.ClientDC(self)
  547. # following is for 'WX' backend on Windows
  548. # the bitmap can not be in use by another DC,
  549. # see GraphicsContextWx._cache
  550. if wx.Platform == '__WXMSW__' and origin == 'WX':
  551. img = self.bitmap.ConvertToImage()
  552. bmp = img.ConvertToBitmap()
  553. drawDC.DrawBitmap(bmp, 0, 0)
  554. else:
  555. drawDC.DrawBitmap(self.bitmap, 0, 0)
  556. filetypes = {
  557. **FigureCanvasBase.filetypes,
  558. 'bmp': 'Windows bitmap',
  559. 'jpeg': 'JPEG',
  560. 'jpg': 'JPEG',
  561. 'pcx': 'PCX',
  562. 'png': 'Portable Network Graphics',
  563. 'tif': 'Tagged Image Format File',
  564. 'tiff': 'Tagged Image Format File',
  565. 'xpm': 'X pixmap',
  566. }
  567. def print_figure(self, filename, *args, **kwargs):
  568. # docstring inherited
  569. super().print_figure(filename, *args, **kwargs)
  570. # Restore the current view; this is needed because the artist contains
  571. # methods rely on particular attributes of the rendered figure for
  572. # determining things like bounding boxes.
  573. if self._isDrawn:
  574. self.draw()
  575. def _onPaint(self, event):
  576. """Called when wxPaintEvt is generated."""
  577. _log.debug("%s - _onPaint()", type(self))
  578. drawDC = wx.PaintDC(self)
  579. if not self._isDrawn:
  580. self.draw(drawDC=drawDC)
  581. else:
  582. self.gui_repaint(drawDC=drawDC)
  583. drawDC.Destroy()
  584. def _onSize(self, event):
  585. """
  586. Called when wxEventSize is generated.
  587. In this application we attempt to resize to fit the window, so it
  588. is better to take the performance hit and redraw the whole window.
  589. """
  590. _log.debug("%s - _onSize()", type(self))
  591. sz = self.GetParent().GetSizer()
  592. if sz:
  593. si = sz.GetItem(self)
  594. if sz and si and not si.Proportion and not si.Flag & wx.EXPAND:
  595. # managed by a sizer, but with a fixed size
  596. size = self.GetMinSize()
  597. else:
  598. # variable size
  599. size = self.GetClientSize()
  600. # Do not allow size to become smaller than MinSize
  601. size.IncTo(self.GetMinSize())
  602. if getattr(self, "_width", None):
  603. if size == (self._width, self._height):
  604. # no change in size
  605. return
  606. self._width, self._height = size
  607. self._isDrawn = False
  608. if self._width <= 1 or self._height <= 1:
  609. return # Empty figure
  610. # Create a new, correctly sized bitmap
  611. self.bitmap = wx.Bitmap(self._width, self._height)
  612. dpival = self.figure.dpi
  613. winch = self._width / dpival
  614. hinch = self._height / dpival
  615. self.figure.set_size_inches(winch, hinch, forward=False)
  616. # Rendering will happen on the associated paint event
  617. # so no need to do anything here except to make sure
  618. # the whole background is repainted.
  619. self.Refresh(eraseBackground=False)
  620. FigureCanvasBase.resize_event(self)
  621. def _get_key(self, event):
  622. keyval = event.KeyCode
  623. if keyval in self.keyvald:
  624. key = self.keyvald[keyval]
  625. elif keyval < 256:
  626. key = chr(keyval)
  627. # wx always returns an uppercase, so make it lowercase if the shift
  628. # key is not depressed (NOTE: this will not handle Caps Lock)
  629. if not event.ShiftDown():
  630. key = key.lower()
  631. else:
  632. key = None
  633. for meth, prefix in (
  634. [event.AltDown, 'alt'],
  635. [event.ControlDown, 'ctrl'], ):
  636. if meth():
  637. key = '{0}+{1}'.format(prefix, key)
  638. return key
  639. def _onKeyDown(self, event):
  640. """Capture key press."""
  641. key = self._get_key(event)
  642. FigureCanvasBase.key_press_event(self, key, guiEvent=event)
  643. if self:
  644. event.Skip()
  645. def _onKeyUp(self, event):
  646. """Release key."""
  647. key = self._get_key(event)
  648. FigureCanvasBase.key_release_event(self, key, guiEvent=event)
  649. if self:
  650. event.Skip()
  651. def _set_capture(self, capture=True):
  652. """Control wx mouse capture."""
  653. if self.HasCapture():
  654. self.ReleaseMouse()
  655. if capture:
  656. self.CaptureMouse()
  657. def _onCaptureLost(self, event):
  658. """Capture changed or lost"""
  659. self._set_capture(False)
  660. def _onMouseButton(self, event):
  661. """Start measuring on an axis."""
  662. event.Skip()
  663. self._set_capture(event.ButtonDown() or event.ButtonDClick())
  664. x = event.X
  665. y = self.figure.bbox.height - event.Y
  666. button_map = {
  667. wx.MOUSE_BTN_LEFT: MouseButton.LEFT,
  668. wx.MOUSE_BTN_MIDDLE: MouseButton.MIDDLE,
  669. wx.MOUSE_BTN_RIGHT: MouseButton.RIGHT,
  670. }
  671. button = event.GetButton()
  672. button = button_map.get(button, button)
  673. if event.ButtonDown():
  674. self.button_press_event(x, y, button, guiEvent=event)
  675. elif event.ButtonDClick():
  676. self.button_press_event(x, y, button, dblclick=True,
  677. guiEvent=event)
  678. elif event.ButtonUp():
  679. self.button_release_event(x, y, button, guiEvent=event)
  680. def _onMouseWheel(self, event):
  681. """Translate mouse wheel events into matplotlib events"""
  682. # Determine mouse location
  683. x = event.GetX()
  684. y = self.figure.bbox.height - event.GetY()
  685. # Convert delta/rotation/rate into a floating point step size
  686. step = event.LinesPerAction * event.WheelRotation / event.WheelDelta
  687. # Done handling event
  688. event.Skip()
  689. # Mac gives two events for every wheel event; skip every second one.
  690. if wx.Platform == '__WXMAC__':
  691. if not hasattr(self, '_skipwheelevent'):
  692. self._skipwheelevent = True
  693. elif self._skipwheelevent:
  694. self._skipwheelevent = False
  695. return # Return without processing event
  696. else:
  697. self._skipwheelevent = True
  698. FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event)
  699. def _onMotion(self, event):
  700. """Start measuring on an axis."""
  701. x = event.GetX()
  702. y = self.figure.bbox.height - event.GetY()
  703. event.Skip()
  704. FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event)
  705. def _onLeave(self, event):
  706. """Mouse has left the window."""
  707. event.Skip()
  708. FigureCanvasBase.leave_notify_event(self, guiEvent=event)
  709. def _onEnter(self, event):
  710. """Mouse has entered the window."""
  711. x = event.GetX()
  712. y = self.figure.bbox.height - event.GetY()
  713. event.Skip()
  714. FigureCanvasBase.enter_notify_event(self, guiEvent=event, xy=(x, y))
  715. class FigureCanvasWx(_FigureCanvasWxBase):
  716. # Rendering to a Wx canvas using the deprecated Wx renderer.
  717. def draw(self, drawDC=None):
  718. """
  719. Render the figure using RendererWx instance renderer, or using a
  720. previously defined renderer if none is specified.
  721. """
  722. _log.debug("%s - draw()", type(self))
  723. self.renderer = RendererWx(self.bitmap, self.figure.dpi)
  724. self.figure.draw(self.renderer)
  725. self._isDrawn = True
  726. self.gui_repaint(drawDC=drawDC)
  727. def print_bmp(self, filename, *args, **kwargs):
  728. return self._print_image(filename, wx.BITMAP_TYPE_BMP, *args, **kwargs)
  729. def print_jpeg(self, filename, *args, **kwargs):
  730. return self._print_image(filename, wx.BITMAP_TYPE_JPEG,
  731. *args, **kwargs)
  732. print_jpg = print_jpeg
  733. def print_pcx(self, filename, *args, **kwargs):
  734. return self._print_image(filename, wx.BITMAP_TYPE_PCX, *args, **kwargs)
  735. def print_png(self, filename, *args, **kwargs):
  736. return self._print_image(filename, wx.BITMAP_TYPE_PNG, *args, **kwargs)
  737. def print_tiff(self, filename, *args, **kwargs):
  738. return self._print_image(filename, wx.BITMAP_TYPE_TIF, *args, **kwargs)
  739. print_tif = print_tiff
  740. def print_xpm(self, filename, *args, **kwargs):
  741. return self._print_image(filename, wx.BITMAP_TYPE_XPM, *args, **kwargs)
  742. @_check_savefig_extra_args
  743. def _print_image(self, filename, filetype, *, quality=None):
  744. origBitmap = self.bitmap
  745. self.bitmap = wx.Bitmap(math.ceil(self.figure.bbox.width),
  746. math.ceil(self.figure.bbox.height))
  747. renderer = RendererWx(self.bitmap, self.figure.dpi)
  748. gc = renderer.new_gc()
  749. self.figure.draw(renderer)
  750. # image is the object that we call SaveFile on.
  751. image = self.bitmap
  752. # set the JPEG quality appropriately. Unfortunately, it is only
  753. # possible to set the quality on a wx.Image object. So if we
  754. # are saving a JPEG, convert the wx.Bitmap to a wx.Image,
  755. # and set the quality.
  756. if filetype == wx.BITMAP_TYPE_JPEG:
  757. if quality is None:
  758. quality = dict.__getitem__(mpl.rcParams,
  759. 'savefig.jpeg_quality')
  760. image = self.bitmap.ConvertToImage()
  761. image.SetOption(wx.IMAGE_OPTION_QUALITY, str(quality))
  762. # Now that we have rendered into the bitmap, save it to the appropriate
  763. # file type and clean up.
  764. if (cbook.is_writable_file_like(filename) and
  765. not isinstance(image, wx.Image)):
  766. image = image.ConvertToImage()
  767. if not image.SaveFile(filename, filetype):
  768. raise RuntimeError(f'Could not save figure to {filename}')
  769. # Restore everything to normal
  770. self.bitmap = origBitmap
  771. # Note: draw is required here since bits of state about the
  772. # last renderer are strewn about the artist draw methods. Do
  773. # not remove the draw without first verifying that these have
  774. # been cleaned up. The artist contains() methods will fail
  775. # otherwise.
  776. if self._isDrawn:
  777. self.draw()
  778. # The "if self" check avoids a "wrapped C/C++ object has been deleted"
  779. # RuntimeError if doing things after window is closed.
  780. if self:
  781. self.Refresh()
  782. class FigureFrameWx(wx.Frame):
  783. def __init__(self, num, fig):
  784. # On non-Windows platform, explicitly set the position - fix
  785. # positioning bug on some Linux platforms
  786. if wx.Platform == '__WXMSW__':
  787. pos = wx.DefaultPosition
  788. else:
  789. pos = wx.Point(20, 20)
  790. wx.Frame.__init__(self, parent=None, id=-1, pos=pos,
  791. title="Figure %d" % num)
  792. # Frame will be sized later by the Fit method
  793. _log.debug("%s - __init__()", type(self))
  794. self.num = num
  795. _set_frame_icon(self)
  796. self.canvas = self.get_canvas(fig)
  797. self.canvas.SetInitialSize(wx.Size(fig.bbox.width, fig.bbox.height))
  798. self.canvas.SetFocus()
  799. self.sizer = wx.BoxSizer(wx.VERTICAL)
  800. self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
  801. # By adding toolbar in sizer, we are able to put it at the bottom
  802. # of the frame - so appearance is closer to GTK version
  803. self.figmgr = FigureManagerWx(self.canvas, num, self)
  804. self.toolbar = self._get_toolbar()
  805. if self.figmgr.toolmanager:
  806. backend_tools.add_tools_to_manager(self.figmgr.toolmanager)
  807. if self.toolbar:
  808. backend_tools.add_tools_to_container(self.toolbar)
  809. if self.toolbar is not None:
  810. self.toolbar.Realize()
  811. # On Windows platform, default window size is incorrect, so set
  812. # toolbar width to figure width.
  813. tw, th = self.toolbar.GetSize()
  814. fw, fh = self.canvas.GetSize()
  815. # By adding toolbar in sizer, we are able to put it at the bottom
  816. # of the frame - so appearance is closer to GTK version.
  817. self.toolbar.SetSize(wx.Size(fw, th))
  818. self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
  819. self.SetSizer(self.sizer)
  820. self.Fit()
  821. self.canvas.SetMinSize((2, 2))
  822. self.Bind(wx.EVT_CLOSE, self._onClose)
  823. @cbook.deprecated("3.2", alternative="self.GetStatusBar()")
  824. @property
  825. def statusbar(self):
  826. return self.GetStatusBar()
  827. @property
  828. def toolmanager(self):
  829. return self.figmgr.toolmanager
  830. def _get_toolbar(self):
  831. if mpl.rcParams['toolbar'] == 'toolbar2':
  832. toolbar = NavigationToolbar2Wx(self.canvas)
  833. elif mpl.rcParams['toolbar'] == 'toolmanager':
  834. toolbar = ToolbarWx(self.toolmanager, self)
  835. else:
  836. toolbar = None
  837. return toolbar
  838. def get_canvas(self, fig):
  839. return FigureCanvasWx(self, -1, fig)
  840. def get_figure_manager(self):
  841. _log.debug("%s - get_figure_manager()", type(self))
  842. return self.figmgr
  843. def _onClose(self, event):
  844. _log.debug("%s - onClose()", type(self))
  845. self.canvas.close_event()
  846. self.canvas.stop_event_loop()
  847. Gcf.destroy(self)
  848. if self:
  849. self.Destroy()
  850. def GetToolBar(self):
  851. """Override wxFrame::GetToolBar as we don't have managed toolbar"""
  852. return self.toolbar
  853. def Destroy(self, *args, **kwargs):
  854. try:
  855. self.canvas.mpl_disconnect(self.toolbar._id_drag)
  856. # Rationale for line above: see issue 2941338.
  857. except AttributeError:
  858. pass # classic toolbar lacks the attribute
  859. # The "if self" check avoids a "wrapped C/C++ object has been deleted"
  860. # RuntimeError at exit with e.g.
  861. # MPLBACKEND=wxagg python -c 'from pylab import *; plot()'.
  862. if self and not self.IsBeingDeleted():
  863. wx.Frame.Destroy(self, *args, **kwargs)
  864. if self.toolbar is not None:
  865. self.toolbar.Destroy()
  866. wxapp = wx.GetApp()
  867. if wxapp:
  868. wxapp.Yield()
  869. return True
  870. class FigureManagerWx(FigureManagerBase):
  871. """
  872. Container/controller for the FigureCanvas and GUI frame.
  873. It is instantiated by Gcf whenever a new figure is created. Gcf is
  874. responsible for managing multiple instances of FigureManagerWx.
  875. Attributes
  876. ----------
  877. canvas : `FigureCanvas`
  878. a FigureCanvasWx(wx.Panel) instance
  879. window : wxFrame
  880. a wxFrame instance - wxpython.org/Phoenix/docs/html/Frame.html
  881. """
  882. def __init__(self, canvas, num, frame):
  883. _log.debug("%s - __init__()", type(self))
  884. FigureManagerBase.__init__(self, canvas, num)
  885. self.frame = frame
  886. self.window = frame
  887. @property
  888. def toolbar(self):
  889. return self.frame.GetToolBar()
  890. @toolbar.setter
  891. def toolbar(self, value):
  892. # Never allow this, except that base class inits this to None before
  893. # the frame is set up.
  894. if value is not None or hasattr(self, "frame"):
  895. raise AttributeError("can't set attribute")
  896. def show(self):
  897. # docstring inherited
  898. self.frame.Show()
  899. self.canvas.draw()
  900. if mpl.rcParams['figure.raise_window']:
  901. self.frame.Raise()
  902. def destroy(self, *args):
  903. # docstring inherited
  904. _log.debug("%s - destroy()", type(self))
  905. frame = self.frame
  906. if frame: # Else, may have been already deleted, e.g. when closing.
  907. frame.Close()
  908. wxapp = wx.GetApp()
  909. if wxapp:
  910. wxapp.Yield()
  911. def get_window_title(self):
  912. # docstring inherited
  913. return self.window.GetTitle()
  914. def set_window_title(self, title):
  915. # docstring inherited
  916. self.window.SetTitle(title)
  917. def resize(self, width, height):
  918. # docstring inherited
  919. self.canvas.SetInitialSize(wx.Size(width, height))
  920. self.window.GetSizer().Fit(self.window)
  921. def _load_bitmap(filename):
  922. """
  923. Load a wx.Bitmap from a file in the "images" directory of the Matplotlib
  924. data.
  925. """
  926. return wx.Bitmap(str(cbook._get_data_path('images', filename)))
  927. def _set_frame_icon(frame):
  928. bundle = wx.IconBundle()
  929. for image in ('matplotlib.png', 'matplotlib_large.png'):
  930. icon = wx.Icon(_load_bitmap(image))
  931. if not icon.IsOk():
  932. return
  933. bundle.AddIcon(icon)
  934. frame.SetIcons(bundle)
  935. cursord = {
  936. cursors.MOVE: wx.CURSOR_HAND,
  937. cursors.HAND: wx.CURSOR_HAND,
  938. cursors.POINTER: wx.CURSOR_ARROW,
  939. cursors.SELECT_REGION: wx.CURSOR_CROSS,
  940. cursors.WAIT: wx.CURSOR_WAIT,
  941. }
  942. class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar):
  943. def __init__(self, canvas, coordinates=True):
  944. wx.ToolBar.__init__(self, canvas.GetParent(), -1)
  945. if 'wxMac' in wx.PlatformInfo:
  946. self.SetToolBitmapSize((24, 24))
  947. self.wx_ids = {}
  948. for text, tooltip_text, image_file, callback in self.toolitems:
  949. if text is None:
  950. self.AddSeparator()
  951. continue
  952. self.wx_ids[text] = (
  953. self.AddTool(
  954. -1,
  955. bitmap=self._icon(f"{image_file}.png"),
  956. bmpDisabled=wx.NullBitmap,
  957. label=text, shortHelp=tooltip_text,
  958. kind=(wx.ITEM_CHECK if text in ["Pan", "Zoom"]
  959. else wx.ITEM_NORMAL))
  960. .Id)
  961. self.Bind(wx.EVT_TOOL, getattr(self, callback),
  962. id=self.wx_ids[text])
  963. self._coordinates = coordinates
  964. if self._coordinates:
  965. self.AddStretchableSpace()
  966. self._label_text = wx.StaticText(self)
  967. self.AddControl(self._label_text)
  968. self.Realize()
  969. NavigationToolbar2.__init__(self, canvas)
  970. self._idle = True
  971. self._prevZoomRect = None
  972. # for now, use alternate zoom-rectangle drawing on all
  973. # Macs. N.B. In future versions of wx it may be possible to
  974. # detect Retina displays with window.GetContentScaleFactor()
  975. # and/or dc.GetContentScaleFactor()
  976. self._retinaFix = 'wxMac' in wx.PlatformInfo
  977. prevZoomRect = cbook._deprecate_privatize_attribute("3.3")
  978. retinaFix = cbook._deprecate_privatize_attribute("3.3")
  979. savedRetinaImage = cbook._deprecate_privatize_attribute("3.3")
  980. wxoverlay = cbook._deprecate_privatize_attribute("3.3")
  981. zoomAxes = cbook._deprecate_privatize_attribute("3.3")
  982. zoomStartX = cbook._deprecate_privatize_attribute("3.3")
  983. zoomStartY = cbook._deprecate_privatize_attribute("3.3")
  984. @staticmethod
  985. def _icon(name):
  986. """
  987. Construct a `wx.Bitmap` suitable for use as icon from an image file
  988. *name*, including the extension and relative to Matplotlib's "images"
  989. data directory.
  990. """
  991. image = np.array(PIL.Image.open(cbook._get_data_path("images", name)))
  992. try:
  993. dark = wx.SystemSettings.GetAppearance().IsDark()
  994. except AttributeError: # wxpython < 4.1
  995. # copied from wx's IsUsingDarkBackground / GetLuminance.
  996. bg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
  997. fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
  998. # See wx.Colour.GetLuminance.
  999. bg_lum = (.299 * bg.red + .587 * bg.green + .114 * bg.blue) / 255
  1000. fg_lum = (.299 * fg.red + .587 * fg.green + .114 * fg.blue) / 255
  1001. dark = fg_lum - bg_lum > .2
  1002. if dark:
  1003. fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
  1004. black_mask = (image[..., :3] == 0).all(axis=-1)
  1005. image[black_mask, :3] = (fg.Red(), fg.Green(), fg.Blue())
  1006. return wx.Bitmap.FromBufferRGBA(
  1007. image.shape[1], image.shape[0], image.tobytes())
  1008. def get_canvas(self, frame, fig):
  1009. return type(self.canvas)(frame, -1, fig)
  1010. def zoom(self, *args):
  1011. self.ToggleTool(self.wx_ids['Pan'], False)
  1012. NavigationToolbar2.zoom(self, *args)
  1013. def pan(self, *args):
  1014. self.ToggleTool(self.wx_ids['Zoom'], False)
  1015. NavigationToolbar2.pan(self, *args)
  1016. def configure_subplots(self, *args):
  1017. global FigureManager # placates pyflakes: created by @_Backend.export
  1018. frame = wx.Frame(None, -1, "Configure subplots")
  1019. _set_frame_icon(frame)
  1020. toolfig = Figure((6, 3))
  1021. canvas = type(self.canvas)(frame, -1, toolfig)
  1022. # Create a figure manager to manage things
  1023. FigureManager(canvas, 1, frame)
  1024. # Now put all into a sizer
  1025. sizer = wx.BoxSizer(wx.VERTICAL)
  1026. # This way of adding to sizer allows resizing
  1027. sizer.Add(canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
  1028. frame.SetSizer(sizer)
  1029. frame.Fit()
  1030. SubplotTool(self.canvas.figure, toolfig)
  1031. frame.Show()
  1032. def save_figure(self, *args):
  1033. # Fetch the required filename and file type.
  1034. filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards()
  1035. default_file = self.canvas.get_default_filename()
  1036. dlg = wx.FileDialog(
  1037. self.canvas.GetParent(), "Save to file",
  1038. mpl.rcParams["savefig.directory"], default_file, filetypes,
  1039. wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  1040. dlg.SetFilterIndex(filter_index)
  1041. if dlg.ShowModal() == wx.ID_OK:
  1042. path = pathlib.Path(dlg.GetPath())
  1043. _log.debug('%s - Save file path: %s', type(self), path)
  1044. fmt = exts[dlg.GetFilterIndex()]
  1045. ext = path.suffix[1:]
  1046. if ext in self.canvas.get_supported_filetypes() and fmt != ext:
  1047. # looks like they forgot to set the image type drop
  1048. # down, going with the extension.
  1049. _log.warning('extension %s did not match the selected '
  1050. 'image type %s; going with %s',
  1051. ext, fmt, ext)
  1052. fmt = ext
  1053. # Save dir for next time, unless empty str (which means use cwd).
  1054. if mpl.rcParams["savefig.directory"]:
  1055. mpl.rcParams["savefig.directory"] = str(path.parent)
  1056. try:
  1057. self.canvas.figure.savefig(str(path), format=fmt)
  1058. except Exception as e:
  1059. error_msg_wx(str(e))
  1060. def set_cursor(self, cursor):
  1061. cursor = wx.Cursor(cursord[cursor])
  1062. self.canvas.SetCursor(cursor)
  1063. self.canvas.Update()
  1064. def press_zoom(self, event):
  1065. super().press_zoom(event)
  1066. if self.mode.name == 'ZOOM':
  1067. if not self._retinaFix:
  1068. self._wxoverlay = wx.Overlay()
  1069. else:
  1070. if event.inaxes is not None:
  1071. self._savedRetinaImage = self.canvas.copy_from_bbox(
  1072. event.inaxes.bbox)
  1073. self._zoomStartX = event.xdata
  1074. self._zoomStartY = event.ydata
  1075. self._zoomAxes = event.inaxes
  1076. def release_zoom(self, event):
  1077. super().release_zoom(event)
  1078. if self.mode.name == 'ZOOM':
  1079. # When the mouse is released we reset the overlay and it
  1080. # restores the former content to the window.
  1081. if not self._retinaFix:
  1082. self._wxoverlay.Reset()
  1083. del self._wxoverlay
  1084. else:
  1085. del self._savedRetinaImage
  1086. if self._prevZoomRect:
  1087. self._prevZoomRect.pop(0).remove()
  1088. self._prevZoomRect = None
  1089. if self._zoomAxes:
  1090. self._zoomAxes = None
  1091. def draw_rubberband(self, event, x0, y0, x1, y1):
  1092. if self._retinaFix: # On Macs, use the following code
  1093. # wx.DCOverlay does not work properly on Retina displays.
  1094. rubberBandColor = '#C0C0FF'
  1095. if self._prevZoomRect:
  1096. self._prevZoomRect.pop(0).remove()
  1097. self.canvas.restore_region(self._savedRetinaImage)
  1098. X0, X1 = self._zoomStartX, event.xdata
  1099. Y0, Y1 = self._zoomStartY, event.ydata
  1100. lineX = (X0, X0, X1, X1, X0)
  1101. lineY = (Y0, Y1, Y1, Y0, Y0)
  1102. self._prevZoomRect = self._zoomAxes.plot(
  1103. lineX, lineY, '-', color=rubberBandColor)
  1104. self._zoomAxes.draw_artist(self._prevZoomRect[0])
  1105. self.canvas.blit(self._zoomAxes.bbox)
  1106. return
  1107. # Use an Overlay to draw a rubberband-like bounding box.
  1108. dc = wx.ClientDC(self.canvas)
  1109. odc = wx.DCOverlay(self._wxoverlay, dc)
  1110. odc.Clear()
  1111. # Mac's DC is already the same as a GCDC, and it causes
  1112. # problems with the overlay if we try to use an actual
  1113. # wx.GCDC so don't try it.
  1114. if 'wxMac' not in wx.PlatformInfo:
  1115. dc = wx.GCDC(dc)
  1116. height = self.canvas.figure.bbox.height
  1117. y1 = height - y1
  1118. y0 = height - y0
  1119. if y1 < y0:
  1120. y0, y1 = y1, y0
  1121. if x1 < x0:
  1122. x0, x1 = x1, x0
  1123. w = x1 - x0
  1124. h = y1 - y0
  1125. rect = wx.Rect(x0, y0, w, h)
  1126. rubberBandColor = '#C0C0FF' # or load from config?
  1127. # Set a pen for the border
  1128. color = wx.Colour(rubberBandColor)
  1129. dc.SetPen(wx.Pen(color, 1))
  1130. # use the same color, plus alpha for the brush
  1131. r, g, b, a = color.Get(True)
  1132. color.Set(r, g, b, 0x60)
  1133. dc.SetBrush(wx.Brush(color))
  1134. dc.DrawRectangle(rect)
  1135. @cbook.deprecated("3.2")
  1136. def set_status_bar(self, statbar):
  1137. self.GetTopLevelParent().SetStatusBar(statbar)
  1138. @cbook.deprecated("3.2",
  1139. alternative="self.GetTopLevelParent().GetStatusBar()")
  1140. @property
  1141. def statbar(self):
  1142. return self.GetTopLevelParent().GetStatusBar()
  1143. def set_message(self, s):
  1144. if self._coordinates:
  1145. self._label_text.SetLabel(s)
  1146. def set_history_buttons(self):
  1147. can_backward = self._nav_stack._pos > 0
  1148. can_forward = self._nav_stack._pos < len(self._nav_stack._elements) - 1
  1149. if 'Back' in self.wx_ids:
  1150. self.EnableTool(self.wx_ids['Back'], can_backward)
  1151. if 'Forward' in self.wx_ids:
  1152. self.EnableTool(self.wx_ids['Forward'], can_forward)
  1153. @cbook.deprecated("3.3")
  1154. class StatusBarWx(wx.StatusBar):
  1155. """
  1156. A status bar is added to _FigureFrame to allow measurements and the
  1157. previously selected scroll function to be displayed as a user convenience.
  1158. """
  1159. def __init__(self, parent, *args, **kwargs):
  1160. wx.StatusBar.__init__(self, parent, -1)
  1161. self.SetFieldsCount(2)
  1162. def set_function(self, string):
  1163. self.SetStatusText("%s" % string, 1)
  1164. # tools for matplotlib.backend_managers.ToolManager:
  1165. class ToolbarWx(ToolContainerBase, wx.ToolBar):
  1166. def __init__(self, toolmanager, parent, style=wx.TB_HORIZONTAL):
  1167. ToolContainerBase.__init__(self, toolmanager)
  1168. wx.ToolBar.__init__(self, parent, -1, style=style)
  1169. self._space = self.AddStretchableSpace()
  1170. self._label_text = wx.StaticText(self)
  1171. self.AddControl(self._label_text)
  1172. self._toolitems = {}
  1173. self._groups = {} # Mapping of groups to the separator after them.
  1174. def _get_tool_pos(self, tool):
  1175. """
  1176. Find the position (index) of a wx.ToolBarToolBase in a ToolBar.
  1177. ``ToolBar.GetToolPos`` is not useful because wx assigns the same Id to
  1178. all Separators and StretchableSpaces.
  1179. """
  1180. pos, = [pos for pos in range(self.ToolsCount)
  1181. if self.GetToolByPos(pos) == tool]
  1182. return pos
  1183. def add_toolitem(self, name, group, position, image_file, description,
  1184. toggle):
  1185. # Find or create the separator that follows this group.
  1186. if group not in self._groups:
  1187. self._groups[group] = self.InsertSeparator(
  1188. self._get_tool_pos(self._space))
  1189. sep = self._groups[group]
  1190. # List all separators.
  1191. seps = [t for t in map(self.GetToolByPos, range(self.ToolsCount))
  1192. if t.IsSeparator() and not t.IsStretchableSpace()]
  1193. # Find where to insert the tool.
  1194. if position >= 0:
  1195. # Find the start of the group by looking for the separator
  1196. # preceding this one; then move forward from it.
  1197. start = (0 if sep == seps[0]
  1198. else self._get_tool_pos(seps[seps.index(sep) - 1]) + 1)
  1199. else:
  1200. # Move backwards from this separator.
  1201. start = self._get_tool_pos(sep) + 1
  1202. idx = start + position
  1203. if image_file:
  1204. bmp = NavigationToolbar2Wx._icon(image_file)
  1205. kind = wx.ITEM_NORMAL if not toggle else wx.ITEM_CHECK
  1206. tool = self.InsertTool(idx, -1, name, bmp, wx.NullBitmap, kind,
  1207. description or "")
  1208. else:
  1209. size = (self.GetTextExtent(name)[0] + 10, -1)
  1210. if toggle:
  1211. control = wx.ToggleButton(self, -1, name, size=size)
  1212. else:
  1213. control = wx.Button(self, -1, name, size=size)
  1214. tool = self.InsertControl(idx, control, label=name)
  1215. self.Realize()
  1216. def handler(event):
  1217. self.trigger_tool(name)
  1218. if image_file:
  1219. self.Bind(wx.EVT_TOOL, handler, tool)
  1220. else:
  1221. control.Bind(wx.EVT_LEFT_DOWN, handler)
  1222. self._toolitems.setdefault(name, [])
  1223. self._toolitems[name].append((tool, handler))
  1224. def toggle_toolitem(self, name, toggled):
  1225. if name not in self._toolitems:
  1226. return
  1227. for tool, handler in self._toolitems[name]:
  1228. if not tool.IsControl():
  1229. self.ToggleTool(tool.Id, toggled)
  1230. else:
  1231. tool.GetControl().SetValue(toggled)
  1232. self.Refresh()
  1233. def remove_toolitem(self, name):
  1234. for tool, handler in self._toolitems[name]:
  1235. self.DeleteTool(tool.Id)
  1236. del self._toolitems[name]
  1237. def set_message(self, s):
  1238. self._label_text.SetLabel(s)
  1239. @cbook.deprecated("3.3")
  1240. class StatusbarWx(StatusbarBase, wx.StatusBar):
  1241. """For use with ToolManager."""
  1242. def __init__(self, parent, *args, **kwargs):
  1243. StatusbarBase.__init__(self, *args, **kwargs)
  1244. wx.StatusBar.__init__(self, parent, -1)
  1245. self.SetFieldsCount(1)
  1246. self.SetStatusText("")
  1247. def set_message(self, s):
  1248. self.SetStatusText(s)
  1249. class ConfigureSubplotsWx(backend_tools.ConfigureSubplotsBase):
  1250. def trigger(self, *args):
  1251. NavigationToolbar2Wx.configure_subplots(
  1252. self._make_classic_style_pseudo_toolbar())
  1253. @cbook.deprecated("3.2")
  1254. def configure_subplots(self):
  1255. frame = wx.Frame(None, -1, "Configure subplots")
  1256. _set_frame_icon(frame)
  1257. toolfig = Figure((6, 3))
  1258. canvas = self.get_canvas(frame, toolfig)
  1259. # Now put all into a sizer
  1260. sizer = wx.BoxSizer(wx.VERTICAL)
  1261. # This way of adding to sizer allows resizing
  1262. sizer.Add(canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
  1263. frame.SetSizer(sizer)
  1264. frame.Fit()
  1265. SubplotTool(self.canvas.figure, toolfig)
  1266. frame.Show()
  1267. @cbook.deprecated("3.2")
  1268. def get_canvas(self, frame, fig):
  1269. return type(self.canvas)(frame, -1, fig)
  1270. class SaveFigureWx(backend_tools.SaveFigureBase):
  1271. def trigger(self, *args):
  1272. NavigationToolbar2Wx.save_figure(
  1273. self._make_classic_style_pseudo_toolbar())
  1274. class SetCursorWx(backend_tools.SetCursorBase):
  1275. def set_cursor(self, cursor):
  1276. NavigationToolbar2Wx.set_cursor(
  1277. self._make_classic_style_pseudo_toolbar(), cursor)
  1278. if 'wxMac' not in wx.PlatformInfo:
  1279. # on most platforms, use overlay
  1280. class RubberbandWx(backend_tools.RubberbandBase):
  1281. def __init__(self, *args, **kwargs):
  1282. backend_tools.RubberbandBase.__init__(self, *args, **kwargs)
  1283. self._wxoverlay = None
  1284. def draw_rubberband(self, x0, y0, x1, y1):
  1285. # Use an Overlay to draw a rubberband-like bounding box.
  1286. if self._wxoverlay is None:
  1287. self._wxoverlay = wx.Overlay()
  1288. dc = wx.ClientDC(self.canvas)
  1289. odc = wx.DCOverlay(self._wxoverlay, dc)
  1290. odc.Clear()
  1291. dc = wx.GCDC(dc)
  1292. height = self.canvas.figure.bbox.height
  1293. y1 = height - y1
  1294. y0 = height - y0
  1295. if y1 < y0:
  1296. y0, y1 = y1, y0
  1297. if x1 < x0:
  1298. x0, x1 = x1, x0
  1299. w = x1 - x0
  1300. h = y1 - y0
  1301. rect = wx.Rect(x0, y0, w, h)
  1302. rubberBandColor = '#C0C0FF' # or load from config?
  1303. # Set a pen for the border
  1304. color = wx.Colour(rubberBandColor)
  1305. dc.SetPen(wx.Pen(color, 1))
  1306. # use the same color, plus alpha for the brush
  1307. r, g, b, a = color.Get(True)
  1308. color.Set(r, g, b, 0x60)
  1309. dc.SetBrush(wx.Brush(color))
  1310. dc.DrawRectangle(rect)
  1311. def remove_rubberband(self):
  1312. if self._wxoverlay is None:
  1313. return
  1314. self._wxoverlay.Reset()
  1315. self._wxoverlay = None
  1316. else:
  1317. # on Mac OS retina displays DCOverlay does not work
  1318. # and dc.SetLogicalFunction does not have an effect on any display
  1319. # the workaround is to blit the full image for remove_rubberband
  1320. class RubberbandWx(backend_tools.RubberbandBase):
  1321. def __init__(self, *args, **kwargs):
  1322. backend_tools.RubberbandBase.__init__(self, *args, **kwargs)
  1323. self._rect = None
  1324. def draw_rubberband(self, x0, y0, x1, y1):
  1325. dc = wx.ClientDC(self.canvas)
  1326. # this would be required if the Canvas is a ScrolledWindow,
  1327. # which is not the case for now
  1328. # self.PrepareDC(dc)
  1329. # delete old rubberband
  1330. if self._rect:
  1331. self.remove_rubberband(dc)
  1332. # draw new rubberband
  1333. dc.SetPen(wx.Pen(wx.BLACK, 1, wx.SOLID))
  1334. dc.SetBrush(wx.TRANSPARENT_BRUSH)
  1335. self._rect = (x0, self.canvas._height-y0, x1-x0, -y1+y0)
  1336. dc.DrawRectangle(self._rect)
  1337. def remove_rubberband(self, dc=None):
  1338. if not self._rect:
  1339. return
  1340. if self.canvas.bitmap:
  1341. if dc is None:
  1342. dc = wx.ClientDC(self.canvas)
  1343. dc.DrawBitmap(self.canvas.bitmap, 0, 0)
  1344. # for testing the method on Windows, use this code instead:
  1345. # img = self.canvas.bitmap.ConvertToImage()
  1346. # bmp = img.ConvertToBitmap()
  1347. # dc.DrawBitmap(bmp, 0, 0)
  1348. self._rect = None
  1349. class _HelpDialog(wx.Dialog):
  1350. _instance = None # a reference to an open dialog singleton
  1351. headers = [("Action", "Shortcuts", "Description")]
  1352. widths = [100, 140, 300]
  1353. def __init__(self, parent, help_entries):
  1354. wx.Dialog.__init__(self, parent, title="Help",
  1355. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
  1356. sizer = wx.BoxSizer(wx.VERTICAL)
  1357. grid_sizer = wx.FlexGridSizer(0, 3, 8, 6)
  1358. # create and add the entries
  1359. bold = self.GetFont().MakeBold()
  1360. for r, row in enumerate(self.headers + help_entries):
  1361. for (col, width) in zip(row, self.widths):
  1362. label = wx.StaticText(self, label=col)
  1363. if r == 0:
  1364. label.SetFont(bold)
  1365. label.Wrap(width)
  1366. grid_sizer.Add(label, 0, 0, 0)
  1367. # finalize layout, create button
  1368. sizer.Add(grid_sizer, 0, wx.ALL, 6)
  1369. OK = wx.Button(self, wx.ID_OK)
  1370. sizer.Add(OK, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 8)
  1371. self.SetSizer(sizer)
  1372. sizer.Fit(self)
  1373. self.Layout()
  1374. self.Bind(wx.EVT_CLOSE, self.OnClose)
  1375. OK.Bind(wx.EVT_BUTTON, self.OnClose)
  1376. def OnClose(self, event):
  1377. _HelpDialog._instance = None # remove global reference
  1378. self.DestroyLater()
  1379. event.Skip()
  1380. @classmethod
  1381. def show(cls, parent, help_entries):
  1382. # if no dialog is shown, create one; otherwise just re-raise it
  1383. if cls._instance:
  1384. cls._instance.Raise()
  1385. return
  1386. cls._instance = cls(parent, help_entries)
  1387. cls._instance.Show()
  1388. class HelpWx(backend_tools.ToolHelpBase):
  1389. def trigger(self, *args):
  1390. _HelpDialog.show(self.figure.canvas.GetTopLevelParent(),
  1391. self._get_help_entries())
  1392. class ToolCopyToClipboardWx(backend_tools.ToolCopyToClipboardBase):
  1393. def trigger(self, *args, **kwargs):
  1394. if not self.canvas._isDrawn:
  1395. self.canvas.draw()
  1396. if not self.canvas.bitmap.IsOk() or not wx.TheClipboard.Open():
  1397. return
  1398. try:
  1399. wx.TheClipboard.SetData(wx.BitmapDataObject(self.canvas.bitmap))
  1400. finally:
  1401. wx.TheClipboard.Close()
  1402. backend_tools.ToolSaveFigure = SaveFigureWx
  1403. backend_tools.ToolConfigureSubplots = ConfigureSubplotsWx
  1404. backend_tools.ToolSetCursor = SetCursorWx
  1405. backend_tools.ToolRubberband = RubberbandWx
  1406. backend_tools.ToolHelp = HelpWx
  1407. backend_tools.ToolCopyToClipboard = ToolCopyToClipboardWx
  1408. @_Backend.export
  1409. class _BackendWx(_Backend):
  1410. FigureCanvas = FigureCanvasWx
  1411. FigureManager = FigureManagerWx
  1412. _frame_class = FigureFrameWx
  1413. @staticmethod
  1414. def trigger_manager_draw(manager):
  1415. manager.canvas.draw_idle()
  1416. @classmethod
  1417. def new_figure_manager(cls, num, *args, **kwargs):
  1418. # Create a wx.App instance if it has not been created so far.
  1419. wxapp = wx.GetApp()
  1420. if wxapp is None:
  1421. wxapp = wx.App(False)
  1422. wxapp.SetExitOnFrameDelete(True)
  1423. # Retain a reference to the app object so that it does not get
  1424. # garbage collected.
  1425. _BackendWx._theWxApp = wxapp
  1426. return super().new_figure_manager(num, *args, **kwargs)
  1427. @classmethod
  1428. def new_figure_manager_given_figure(cls, num, figure):
  1429. frame = cls._frame_class(num, figure)
  1430. figmgr = frame.get_figure_manager()
  1431. if mpl.is_interactive():
  1432. figmgr.frame.Show()
  1433. figure.canvas.draw_idle()
  1434. return figmgr
  1435. @staticmethod
  1436. def mainloop():
  1437. if not wx.App.IsMainLoopRunning():
  1438. wxapp = wx.GetApp()
  1439. if wxapp is not None:
  1440. wxapp.MainLoop()