Guest User

backend_wx.py

a guest
Sep 30th, 2017
561
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 64.71 KB | None | 0 0
  1. """
  2. A wxPython backend for matplotlib, based (very heavily) on
  3. backend_template.py and backend_gtk.py
  4.  
  5. Author: Jeremy O'Donoghue ([email protected])
  6.  
  7. Derived from original copyright work by John Hunter
  8.  
  9. Copyright (C) Jeremy O'Donoghue & John Hunter, 2003-4
  10.  
  11. License: This work is licensed under a PSF compatible license. A copy
  12. should be included with this source code.
  13.  
  14. """
  15. from __future__ import (absolute_import, division, print_function,
  16. unicode_literals)
  17.  
  18. from six.moves import xrange
  19.  
  20. import sys
  21. import os
  22. import os.path
  23. import math
  24. import weakref
  25. import warnings
  26.  
  27. import numpy as np
  28.  
  29. import matplotlib
  30. from matplotlib.backend_bases import (
  31. _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
  32. NavigationToolbar2, RendererBase, TimerBase, cursors)
  33. from matplotlib.backend_bases import _has_pil
  34.  
  35. from matplotlib._pylab_helpers import Gcf
  36. from matplotlib.cbook import is_writable_file_like, warn_deprecated
  37. from matplotlib.figure import Figure
  38. from matplotlib.path import Path
  39. from matplotlib.transforms import Affine2D
  40. from matplotlib.widgets import SubplotTool
  41. from matplotlib import cbook, rcParams
  42.  
  43. from . import wx_compat as wxc
  44. import wx
  45.  
  46. # Debugging settings here...
  47. # Debug level set here. If the debug level is less than 5, information
  48. # messages (progressively more info for lower value) are printed. In addition,
  49. # traceback is performed, and pdb activated, for all uncaught exceptions in
  50. # this case
  51. _DEBUG = 5
  52. if _DEBUG < 5:
  53. import traceback
  54. import pdb
  55. _DEBUG_lvls = {1: 'Low ', 2: 'Med ', 3: 'High', 4: 'Error'}
  56.  
  57.  
  58. def DEBUG_MSG(string, lvl=3, o=None):
  59. if lvl >= _DEBUG:
  60. cls = o.__class__
  61. # Jeremy, often times the commented line won't print but the
  62. # one below does. I think WX is redefining stderr, damned
  63. # beast
  64. #print >>sys.stderr, "%s- %s in %s" % (_DEBUG_lvls[lvl], string, cls)
  65. print("%s- %s in %s" % (_DEBUG_lvls[lvl], string, cls))
  66.  
  67.  
  68. def debug_on_error(type, value, tb):
  69. """Code due to Thomas Heller - published in Python Cookbook (O'Reilley)"""
  70. traceback.print_exception(type, value, tb)
  71. print()
  72. pdb.pm() # jdh uncomment
  73.  
  74.  
  75. class fake_stderr(object):
  76. """
  77. Wx does strange things with stderr, as it makes the assumption that
  78. there is probably no console. This redirects stderr to the console, since
  79. we know that there is one!
  80. """
  81.  
  82. def write(self, msg):
  83. print("Stderr: %s\n\r" % msg)
  84.  
  85. #if _DEBUG < 5:
  86. #sys.excepthook = debug_on_error
  87. #WxLogger =wx.LogStderr()
  88. #sys.stderr = fake_stderr
  89.  
  90. # the True dots per inch on the screen; should be display dependent
  91. # see
  92. # 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
  93. # for some info about screen dpi
  94. PIXELS_PER_INCH = 75
  95.  
  96. # Delay time for idle checks
  97. IDLE_DELAY = 5
  98.  
  99.  
  100. def error_msg_wx(msg, parent=None):
  101. """
  102. Signal an error condition -- in a GUI, popup a error dialog
  103. """
  104. dialog = wx.MessageDialog(parent=parent,
  105. message=msg,
  106. caption='Matplotlib backend_wx error',
  107. style=wx.OK | wx.CENTRE)
  108. dialog.ShowModal()
  109. dialog.Destroy()
  110. return None
  111.  
  112.  
  113. def raise_msg_to_str(msg):
  114. """msg is a return arg from a raise. Join with new lines"""
  115. if not isinstance(msg, six.string_types):
  116. msg = '\n'.join(map(str, msg))
  117. return msg
  118.  
  119.  
  120. class TimerWx(TimerBase):
  121. '''
  122. Subclass of :class:`backend_bases.TimerBase` that uses WxTimer events.
  123.  
  124. Attributes
  125. ----------
  126. interval : int
  127. The time between timer events in milliseconds. Default is 1000 ms.
  128. single_shot : bool
  129. Boolean flag indicating whether this timer should operate as single
  130. shot (run once and then stop). Defaults to False.
  131. callbacks : list
  132. Stores list of (func, args) tuples that will be called upon timer
  133. events. This list can be manipulated directly, or the functions
  134. `add_callback` and `remove_callback` can be used.
  135.  
  136. '''
  137.  
  138. def __init__(self, parent, *args, **kwargs):
  139. TimerBase.__init__(self, *args, **kwargs)
  140.  
  141. # Create a new timer and connect the timer event to our handler.
  142. # For WX, the events have to use a widget for binding.
  143. self.parent = parent
  144. self._timer = wx.Timer(self.parent, wx.NewId())
  145. self.parent.Bind(wx.EVT_TIMER, self._on_timer, self._timer)
  146.  
  147. # Unbinding causes Wx to stop for some reason. Disabling for now.
  148. # def __del__(self):
  149. # TimerBase.__del__(self)
  150. # self.parent.Bind(wx.EVT_TIMER, None, self._timer)
  151.  
  152. def _timer_start(self):
  153. self._timer.Start(self._interval, self._single)
  154.  
  155. def _timer_stop(self):
  156. self._timer.Stop()
  157.  
  158. def _timer_set_interval(self):
  159. self._timer_start()
  160.  
  161. def _timer_set_single_shot(self):
  162. self._timer.Start()
  163.  
  164. def _on_timer(self, *args):
  165. TimerBase._on_timer(self)
  166.  
  167.  
  168. class RendererWx(RendererBase):
  169. """
  170. The renderer handles all the drawing primitives using a graphics
  171. context instance that controls the colors/styles. It acts as the
  172. 'renderer' instance used by many classes in the hierarchy.
  173. """
  174. # In wxPython, drawing is performed on a wxDC instance, which will
  175. # generally be mapped to the client aread of the window displaying
  176. # the plot. Under wxPython, the wxDC instance has a wx.Pen which
  177. # describes the colour and weight of any lines drawn, and a wxBrush
  178. # which describes the fill colour of any closed polygon.
  179.  
  180. fontweights = wxc.fontweights
  181. fontangles = wxc.fontangles
  182.  
  183. # wxPython allows for portable font styles, choosing them appropriately
  184. # for the target platform. Map some standard font names to the portable
  185. # styles
  186. # QUESTION: Is it be wise to agree standard fontnames across all backends?
  187. fontnames = wxc.fontnames
  188.  
  189. def __init__(self, bitmap, dpi):
  190. """
  191. Initialise a wxWindows renderer instance.
  192. """
  193. warn_deprecated('2.0', message="The WX backend is "
  194. "deprecated. It's untested "
  195. "and will be removed in Matplotlib 2.2. "
  196. "Use the WXAgg backend instead. "
  197. "See Matplotlib usage FAQ for more info on backends.",
  198. alternative='WXAgg')
  199. RendererBase.__init__(self)
  200. DEBUG_MSG("__init__()", 1, self)
  201. self.width = bitmap.GetWidth()
  202. self.height = bitmap.GetHeight()
  203. self.bitmap = bitmap
  204. self.fontd = {}
  205. self.dpi = dpi
  206. self.gc = None
  207.  
  208. def flipy(self):
  209. return True
  210.  
  211. def offset_text_height(self):
  212. return True
  213.  
  214. def get_text_width_height_descent(self, s, prop, ismath):
  215. """
  216. get the width and height in display coords of the string s
  217. with FontPropertry prop
  218. """
  219. # return 1, 1
  220. if ismath:
  221. s = self.strip_math(s)
  222.  
  223. if self.gc is None:
  224. gc = self.new_gc()
  225. else:
  226. gc = self.gc
  227. gfx_ctx = gc.gfx_ctx
  228. font = self.get_wx_font(s, prop)
  229. gfx_ctx.SetFont(font, wx.BLACK)
  230. w, h, descent, leading = gfx_ctx.GetFullTextExtent(s)
  231.  
  232. return w, h, descent
  233.  
  234. def get_canvas_width_height(self):
  235. 'return the canvas width and height in display coords'
  236. return self.width, self.height
  237.  
  238. def handle_clip_rectangle(self, gc):
  239. new_bounds = gc.get_clip_rectangle()
  240. if new_bounds is not None:
  241. new_bounds = new_bounds.bounds
  242. gfx_ctx = gc.gfx_ctx
  243. if gfx_ctx._lastcliprect != new_bounds:
  244. gfx_ctx._lastcliprect = new_bounds
  245. if new_bounds is None:
  246. gfx_ctx.ResetClip()
  247. else:
  248. gfx_ctx.Clip(new_bounds[0],
  249. self.height - new_bounds[1] - new_bounds[3],
  250. new_bounds[2], new_bounds[3])
  251.  
  252. @staticmethod
  253. def convert_path(gfx_ctx, path, transform):
  254. wxpath = gfx_ctx.CreatePath()
  255. for points, code in path.iter_segments(transform):
  256. if code == Path.MOVETO:
  257. wxpath.MoveToPoint(*points)
  258. elif code == Path.LINETO:
  259. wxpath.AddLineToPoint(*points)
  260. elif code == Path.CURVE3:
  261. wxpath.AddQuadCurveToPoint(*points)
  262. elif code == Path.CURVE4:
  263. wxpath.AddCurveToPoint(*points)
  264. elif code == Path.CLOSEPOLY:
  265. wxpath.CloseSubpath()
  266. return wxpath
  267.  
  268. def draw_path(self, gc, path, transform, rgbFace=None):
  269. gc.select()
  270. self.handle_clip_rectangle(gc)
  271. gfx_ctx = gc.gfx_ctx
  272. transform = transform + \
  273. Affine2D().scale(1.0, -1.0).translate(0.0, self.height)
  274. wxpath = self.convert_path(gfx_ctx, path, transform)
  275. if rgbFace is not None:
  276. gfx_ctx.SetBrush(wx.Brush(gc.get_wxcolour(rgbFace)))
  277. gfx_ctx.DrawPath(wxpath)
  278. else:
  279. gfx_ctx.StrokePath(wxpath)
  280. gc.unselect()
  281.  
  282. def draw_image(self, gc, x, y, im):
  283. bbox = gc.get_clip_rectangle()
  284. if bbox is not None:
  285. l, b, w, h = bbox.bounds
  286. else:
  287. l = 0
  288. b = 0
  289. w = self.width
  290. h = self.height
  291. rows, cols = im.shape[:2]
  292. bitmap = wxc.BitmapFromBuffer(cols, rows, im.tostring())
  293. gc = self.get_gc()
  294. gc.select()
  295. gc.gfx_ctx.DrawBitmap(bitmap, int(l), int(self.height - b),
  296. int(w), int(-h))
  297. gc.unselect()
  298.  
  299. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  300. if ismath:
  301. s = self.strip_math(s)
  302. DEBUG_MSG("draw_text()", 1, self)
  303. gc.select()
  304. self.handle_clip_rectangle(gc)
  305. gfx_ctx = gc.gfx_ctx
  306.  
  307. font = self.get_wx_font(s, prop)
  308. color = gc.get_wxcolour(gc.get_rgb())
  309. gfx_ctx.SetFont(font, color)
  310.  
  311. w, h, d = self.get_text_width_height_descent(s, prop, ismath)
  312. x = int(x)
  313. y = int(y - h)
  314.  
  315. if angle == 0.0:
  316. gfx_ctx.DrawText(s, x, y)
  317. else:
  318. rads = math.radians(angle)
  319. xo = h * math.sin(rads)
  320. yo = h * math.cos(rads)
  321. gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads)
  322.  
  323. gc.unselect()
  324.  
  325. def new_gc(self):
  326. """
  327. Return an instance of a GraphicsContextWx, and sets the current gc copy
  328. """
  329. DEBUG_MSG('new_gc()', 2, self)
  330. self.gc = GraphicsContextWx(self.bitmap, self)
  331. self.gc.select()
  332. self.gc.unselect()
  333. return self.gc
  334.  
  335. def get_gc(self):
  336. """
  337. Fetch the locally cached gc.
  338. """
  339. # This is a dirty hack to allow anything with access to a renderer to
  340. # access the current graphics context
  341. assert self.gc is not None, "gc must be defined"
  342. return self.gc
  343.  
  344. def get_wx_font(self, s, prop):
  345. """
  346. Return a wx font. Cache instances in a font dictionary for
  347. efficiency
  348. """
  349. DEBUG_MSG("get_wx_font()", 1, self)
  350.  
  351. key = hash(prop)
  352. fontprop = prop
  353. fontname = fontprop.get_name()
  354.  
  355. font = self.fontd.get(key)
  356. if font is not None:
  357. return font
  358.  
  359. # Allow use of platform independent and dependent font names
  360. wxFontname = self.fontnames.get(fontname, wx.ROMAN)
  361. wxFacename = '' # Empty => wxPython chooses based on wx_fontname
  362.  
  363. # Font colour is determined by the active wx.Pen
  364. # TODO: It may be wise to cache font information
  365. size = self.points_to_pixels(fontprop.get_size_in_points())
  366.  
  367. font = wx.Font(int(size + 0.5), # Size
  368. wxFontname, # 'Generic' name
  369. self.fontangles[fontprop.get_style()], # Angle
  370. self.fontweights[fontprop.get_weight()], # Weight
  371. False, # Underline
  372. wxFacename) # Platform font name
  373.  
  374. # cache the font and gc and return it
  375. self.fontd[key] = font
  376.  
  377. return font
  378.  
  379. def points_to_pixels(self, points):
  380. """
  381. convert point measures to pixes using dpi and the pixels per
  382. inch of the display
  383. """
  384. return points * (PIXELS_PER_INCH / 72.0 * self.dpi / 72.0)
  385.  
  386.  
  387. class GraphicsContextWx(GraphicsContextBase):
  388. """
  389. The graphics context provides the color, line styles, etc...
  390.  
  391. This class stores a reference to a wxMemoryDC, and a
  392. wxGraphicsContext that draws to it. Creating a wxGraphicsContext
  393. seems to be fairly heavy, so these objects are cached based on the
  394. bitmap object that is passed in.
  395.  
  396. The base GraphicsContext stores colors as a RGB tuple on the unit
  397. interval, e.g., (0.5, 0.0, 1.0). wxPython uses an int interval, but
  398. since wxPython colour management is rather simple, I have not chosen
  399. to implement a separate colour manager class.
  400. """
  401. _capd = {'butt': wx.CAP_BUTT,
  402. 'projecting': wx.CAP_PROJECTING,
  403. 'round': wx.CAP_ROUND}
  404.  
  405. _joind = {'bevel': wx.JOIN_BEVEL,
  406. 'miter': wx.JOIN_MITER,
  407. 'round': wx.JOIN_ROUND}
  408.  
  409. _cache = weakref.WeakKeyDictionary()
  410.  
  411. def __init__(self, bitmap, renderer):
  412. GraphicsContextBase.__init__(self)
  413. #assert self.Ok(), "wxMemoryDC not OK to use"
  414. DEBUG_MSG("__init__()", 1, self)
  415. DEBUG_MSG("__init__() 2: %s" % bitmap, 1, self)
  416.  
  417. dc, gfx_ctx = self._cache.get(bitmap, (None, None))
  418. if dc is None:
  419. dc = wx.MemoryDC()
  420. dc.SelectObject(bitmap)
  421. gfx_ctx = wx.GraphicsContext.Create(dc)
  422. gfx_ctx._lastcliprect = None
  423. self._cache[bitmap] = dc, gfx_ctx
  424.  
  425. self.bitmap = bitmap
  426. self.dc = dc
  427. self.gfx_ctx = gfx_ctx
  428. self._pen = wx.Pen('BLACK', 1, wx.SOLID)
  429. gfx_ctx.SetPen(self._pen)
  430. self._style = wx.SOLID
  431. self.renderer = renderer
  432.  
  433. def select(self):
  434. """
  435. Select the current bitmap into this wxDC instance
  436. """
  437.  
  438. if sys.platform == 'win32':
  439. self.dc.SelectObject(self.bitmap)
  440. self.IsSelected = True
  441.  
  442. def unselect(self):
  443. """
  444. Select a Null bitmasp into this wxDC instance
  445. """
  446. if sys.platform == 'win32':
  447. self.dc.SelectObject(wx.NullBitmap)
  448. self.IsSelected = False
  449.  
  450. def set_foreground(self, fg, isRGBA=None):
  451. """
  452. Set the foreground color. fg can be a matlab format string, a
  453. html hex color string, an rgb unit tuple, or a float between 0
  454. and 1. In the latter case, grayscale is used.
  455. """
  456. # Implementation note: wxPython has a separate concept of pen and
  457. # brush - the brush fills any outline trace left by the pen.
  458. # Here we set both to the same colour - if a figure is not to be
  459. # filled, the renderer will set the brush to be transparent
  460. # Same goes for text foreground...
  461. DEBUG_MSG("set_foreground()", 1, self)
  462. self.select()
  463. GraphicsContextBase.set_foreground(self, fg, isRGBA)
  464.  
  465. self._pen.SetColour(self.get_wxcolour(self.get_rgb()))
  466. self.gfx_ctx.SetPen(self._pen)
  467. self.unselect()
  468.  
  469. def set_linewidth(self, w):
  470. """
  471. Set the line width.
  472. """
  473. w = float(w)
  474. DEBUG_MSG("set_linewidth()", 1, self)
  475. self.select()
  476. if w > 0 and w < 1:
  477. w = 1
  478. GraphicsContextBase.set_linewidth(self, w)
  479. lw = int(self.renderer.points_to_pixels(self._linewidth))
  480. if lw == 0:
  481. lw = 1
  482. self._pen.SetWidth(lw)
  483. self.gfx_ctx.SetPen(self._pen)
  484. self.unselect()
  485.  
  486. def set_capstyle(self, cs):
  487. """
  488. Set the capstyle as a string in ('butt', 'round', 'projecting')
  489. """
  490. DEBUG_MSG("set_capstyle()", 1, self)
  491. self.select()
  492. GraphicsContextBase.set_capstyle(self, cs)
  493. self._pen.SetCap(GraphicsContextWx._capd[self._capstyle])
  494. self.gfx_ctx.SetPen(self._pen)
  495. self.unselect()
  496.  
  497. def set_joinstyle(self, js):
  498. """
  499. Set the join style to be one of ('miter', 'round', 'bevel')
  500. """
  501. DEBUG_MSG("set_joinstyle()", 1, self)
  502. self.select()
  503. GraphicsContextBase.set_joinstyle(self, js)
  504. self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle])
  505. self.gfx_ctx.SetPen(self._pen)
  506. self.unselect()
  507.  
  508. @cbook.deprecated("2.1")
  509. def set_linestyle(self, ls):
  510. """
  511. Set the line style to be one of
  512. """
  513. DEBUG_MSG("set_linestyle()", 1, self)
  514. self.select()
  515. GraphicsContextBase.set_linestyle(self, ls)
  516. try:
  517. self._style = wxc.dashd_wx[ls]
  518. except KeyError:
  519. self._style = wx.LONG_DASH # Style not used elsewhere...
  520.  
  521. # On MS Windows platform, only line width of 1 allowed for dash lines
  522. if wx.Platform == '__WXMSW__':
  523. self.set_linewidth(1)
  524.  
  525. self._pen.SetStyle(self._style)
  526. self.gfx_ctx.SetPen(self._pen)
  527. self.unselect()
  528.  
  529. def get_wxcolour(self, color):
  530. """return a wx.Colour from RGB format"""
  531. DEBUG_MSG("get_wx_color()", 1, self)
  532. if len(color) == 3:
  533. r, g, b = color
  534. r *= 255
  535. g *= 255
  536. b *= 255
  537. return wx.Colour(red=int(r), green=int(g), blue=int(b))
  538. else:
  539. r, g, b, a = color
  540. r *= 255
  541. g *= 255
  542. b *= 255
  543. a *= 255
  544. return wx.Colour(
  545. red=int(r),
  546. green=int(g),
  547. blue=int(b),
  548. alpha=int(a))
  549.  
  550.  
  551. class FigureCanvasWx(FigureCanvasBase, wx.Panel):
  552. """
  553. The FigureCanvas contains the figure and does event handling.
  554.  
  555. In the wxPython backend, it is derived from wxPanel, and (usually) lives
  556. inside a frame instantiated by a FigureManagerWx. The parent window
  557. probably implements a wx.Sizer to control the displayed control size - but
  558. we give a hint as to our preferred minimum size.
  559. """
  560.  
  561. keyvald = {
  562. wx.WXK_CONTROL: 'control',
  563. wx.WXK_SHIFT: 'shift',
  564. wx.WXK_ALT: 'alt',
  565. wx.WXK_LEFT: 'left',
  566. wx.WXK_UP: 'up',
  567. wx.WXK_RIGHT: 'right',
  568. wx.WXK_DOWN: 'down',
  569. wx.WXK_ESCAPE: 'escape',
  570. wx.WXK_F1: 'f1',
  571. wx.WXK_F2: 'f2',
  572. wx.WXK_F3: 'f3',
  573. wx.WXK_F4: 'f4',
  574. wx.WXK_F5: 'f5',
  575. wx.WXK_F6: 'f6',
  576. wx.WXK_F7: 'f7',
  577. wx.WXK_F8: 'f8',
  578. wx.WXK_F9: 'f9',
  579. wx.WXK_F10: 'f10',
  580. wx.WXK_F11: 'f11',
  581. wx.WXK_F12: 'f12',
  582. wx.WXK_SCROLL: 'scroll_lock',
  583. wx.WXK_PAUSE: 'break',
  584. wx.WXK_BACK: 'backspace',
  585. wx.WXK_RETURN: 'enter',
  586. wx.WXK_INSERT: 'insert',
  587. wx.WXK_DELETE: 'delete',
  588. wx.WXK_HOME: 'home',
  589. wx.WXK_END: 'end',
  590. wx.WXK_PAGEUP: 'pageup',
  591. wx.WXK_PAGEDOWN: 'pagedown',
  592. wx.WXK_NUMPAD0: '0',
  593. wx.WXK_NUMPAD1: '1',
  594. wx.WXK_NUMPAD2: '2',
  595. wx.WXK_NUMPAD3: '3',
  596. wx.WXK_NUMPAD4: '4',
  597. wx.WXK_NUMPAD5: '5',
  598. wx.WXK_NUMPAD6: '6',
  599. wx.WXK_NUMPAD7: '7',
  600. wx.WXK_NUMPAD8: '8',
  601. wx.WXK_NUMPAD9: '9',
  602. wx.WXK_NUMPAD_ADD: '+',
  603. wx.WXK_NUMPAD_SUBTRACT: '-',
  604. wx.WXK_NUMPAD_MULTIPLY: '*',
  605. wx.WXK_NUMPAD_DIVIDE: '/',
  606. wx.WXK_NUMPAD_DECIMAL: 'dec',
  607. wx.WXK_NUMPAD_ENTER: 'enter',
  608. wx.WXK_NUMPAD_UP: 'up',
  609. wx.WXK_NUMPAD_RIGHT: 'right',
  610. wx.WXK_NUMPAD_DOWN: 'down',
  611. wx.WXK_NUMPAD_LEFT: 'left',
  612. wx.WXK_NUMPAD_PAGEUP: 'pageup',
  613. wx.WXK_NUMPAD_PAGEDOWN: 'pagedown',
  614. wx.WXK_NUMPAD_HOME: 'home',
  615. wx.WXK_NUMPAD_END: 'end',
  616. wx.WXK_NUMPAD_INSERT: 'insert',
  617. wx.WXK_NUMPAD_DELETE: 'delete',
  618. }
  619.  
  620. def __init__(self, parent, id, figure):
  621. """
  622. Initialise a FigureWx instance.
  623.  
  624. - Initialise the FigureCanvasBase and wxPanel parents.
  625. - Set event handlers for:
  626. EVT_SIZE (Resize event)
  627. EVT_PAINT (Paint event)
  628. """
  629.  
  630. FigureCanvasBase.__init__(self, figure)
  631. # Set preferred window size hint - helps the sizer (if one is
  632. # connected)
  633. l, b, w, h = figure.bbox.bounds
  634. w = int(math.ceil(w))
  635. h = int(math.ceil(h))
  636.  
  637. wx.Panel.__init__(self, parent, id, size=wx.Size(w, h))
  638.  
  639. def do_nothing(*args, **kwargs):
  640. warnings.warn(
  641. "could not find a setinitialsize function for backend_wx; "
  642. "please report your wxpython version=%s "
  643. "to the matplotlib developers list" %
  644. wxc.backend_version)
  645. pass
  646.  
  647. # try to find the set size func across wx versions
  648. try:
  649. getattr(self, 'SetInitialSize')
  650. except AttributeError:
  651. self.SetInitialSize = getattr(self, 'SetBestFittingSize',
  652. do_nothing)
  653.  
  654. if not hasattr(self, 'IsShownOnScreen'):
  655. self.IsShownOnScreen = getattr(self, 'IsVisible',
  656. lambda *args: True)
  657.  
  658. # Create the drawing bitmap
  659. self.bitmap = wxc.EmptyBitmap(w, h)
  660. DEBUG_MSG("__init__() - bitmap w:%d h:%d" % (w, h), 2, self)
  661. # TODO: Add support for 'point' inspection and plot navigation.
  662. self._isDrawn = False
  663.  
  664. self.Bind(wx.EVT_SIZE, self._onSize)
  665. self.Bind(wx.EVT_PAINT, self._onPaint)
  666. self.Bind(wx.EVT_KEY_DOWN, self._onKeyDown)
  667. self.Bind(wx.EVT_KEY_UP, self._onKeyUp)
  668. self.Bind(wx.EVT_RIGHT_DOWN, self._onRightButtonDown)
  669. self.Bind(wx.EVT_RIGHT_DCLICK, self._onRightButtonDClick)
  670. self.Bind(wx.EVT_RIGHT_UP, self._onRightButtonUp)
  671. self.Bind(wx.EVT_MOUSEWHEEL, self._onMouseWheel)
  672. self.Bind(wx.EVT_LEFT_DOWN, self._onLeftButtonDown)
  673. self.Bind(wx.EVT_LEFT_DCLICK, self._onLeftButtonDClick)
  674. self.Bind(wx.EVT_LEFT_UP, self._onLeftButtonUp)
  675. self.Bind(wx.EVT_MOTION, self._onMotion)
  676. self.Bind(wx.EVT_LEAVE_WINDOW, self._onLeave)
  677. self.Bind(wx.EVT_ENTER_WINDOW, self._onEnter)
  678. # Add middle button events
  679. self.Bind(wx.EVT_MIDDLE_DOWN, self._onMiddleButtonDown)
  680. self.Bind(wx.EVT_MIDDLE_DCLICK, self._onMiddleButtonDClick)
  681. self.Bind(wx.EVT_MIDDLE_UP, self._onMiddleButtonUp)
  682.  
  683. self.Bind(wx.EVT_MOUSE_CAPTURE_CHANGED, self._onCaptureLost)
  684. self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self._onCaptureLost)
  685.  
  686. if wx.VERSION_STRING < "2.9":
  687. # only needed in 2.8 to reduce flicker
  688. self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
  689. self.Bind(wx.EVT_ERASE_BACKGROUND, self._onEraseBackground)
  690. else:
  691. # this does the same in 2.9+
  692. self.SetBackgroundStyle(wx.BG_STYLE_PAINT)
  693.  
  694. self.macros = {} # dict from wx id to seq of macros
  695.  
  696. def Destroy(self, *args, **kwargs):
  697. wx.Panel.Destroy(self, *args, **kwargs)
  698.  
  699. def Copy_to_Clipboard(self, event=None):
  700. "copy bitmap of canvas to system clipboard"
  701. bmp_obj = wx.BitmapDataObject()
  702. bmp_obj.SetBitmap(self.bitmap)
  703.  
  704. if not wx.TheClipboard.IsOpened():
  705. open_success = wx.TheClipboard.Open()
  706. if open_success:
  707. wx.TheClipboard.SetData(bmp_obj)
  708. wx.TheClipboard.Close()
  709. wx.TheClipboard.Flush()
  710.  
  711. def draw_idle(self):
  712. """
  713. Delay rendering until the GUI is idle.
  714. """
  715. DEBUG_MSG("draw_idle()", 1, self)
  716. self._isDrawn = False # Force redraw
  717.  
  718. # Triggering a paint event is all that is needed to defer drawing
  719. # until later. The platform will send the event when it thinks it is
  720. # a good time (usually as soon as there are no other events pending).
  721. self.Refresh(eraseBackground=False)
  722.  
  723. def draw(self, drawDC=None):
  724. """
  725. Render the figure using RendererWx instance renderer, or using a
  726. previously defined renderer if none is specified.
  727. """
  728. DEBUG_MSG("draw()", 1, self)
  729. self.renderer = RendererWx(self.bitmap, self.figure.dpi)
  730. self.figure.draw(self.renderer)
  731. self._isDrawn = True
  732. self.gui_repaint(drawDC=drawDC)
  733.  
  734. def new_timer(self, *args, **kwargs):
  735. """
  736. Creates a new backend-specific subclass of
  737. :class:`backend_bases.Timer`. This is useful for getting periodic
  738. events through the backend's native event loop. Implemented only
  739. for backends with GUIs.
  740.  
  741. Other Parameters
  742. ----------------
  743. interval : scalar
  744. Timer interval in milliseconds
  745. callbacks : list
  746. Sequence of (func, args, kwargs) where ``func(*args, **kwargs)``
  747. will be executed by the timer every *interval*.
  748.  
  749. """
  750. return TimerWx(self, *args, **kwargs)
  751.  
  752. def flush_events(self):
  753. wx.Yield()
  754.  
  755. def start_event_loop(self, timeout=0):
  756. """
  757. Start an event loop. This is used to start a blocking event
  758. loop so that interactive functions, such as ginput and
  759. waitforbuttonpress, can wait for events. This should not be
  760. confused with the main GUI event loop, which is always running
  761. and has nothing to do with this.
  762.  
  763. This call blocks until a callback function triggers
  764. stop_event_loop() or *timeout* is reached. If *timeout* is
  765. <=0, never timeout.
  766.  
  767. Raises RuntimeError if event loop is already running.
  768. """
  769. if hasattr(self, '_event_loop'):
  770. raise RuntimeError("Event loop already running")
  771. id = wx.NewId()
  772. timer = wx.Timer(self, id=id)
  773. if timeout > 0:
  774. timer.Start(timeout * 1000, oneShot=True)
  775. self.Bind(wx.EVT_TIMER, self.stop_event_loop, id=id)
  776.  
  777. # Event loop handler for start/stop event loop
  778. self._event_loop = wxc.EventLoop()
  779. self._event_loop.Run()
  780. timer.Stop()
  781.  
  782. def stop_event_loop(self, event=None):
  783. """
  784. Stop an event loop. This is used to stop a blocking event
  785. loop so that interactive functions, such as ginput and
  786. waitforbuttonpress, can wait for events.
  787.  
  788. """
  789. if hasattr(self, '_event_loop'):
  790. if self._event_loop.IsRunning():
  791. self._event_loop.Exit()
  792. del self._event_loop
  793.  
  794. def _get_imagesave_wildcards(self):
  795. 'return the wildcard string for the filesave dialog'
  796. default_filetype = self.get_default_filetype()
  797. filetypes = self.get_supported_filetypes_grouped()
  798. sorted_filetypes = sorted(filetypes.items())
  799. wildcards = []
  800. extensions = []
  801. filter_index = 0
  802. for i, (name, exts) in enumerate(sorted_filetypes):
  803. ext_list = ';'.join(['*.%s' % ext for ext in exts])
  804. extensions.append(exts[0])
  805. wildcard = '%s (%s)|%s' % (name, ext_list, ext_list)
  806. if default_filetype in exts:
  807. filter_index = i
  808. wildcards.append(wildcard)
  809. wildcards = '|'.join(wildcards)
  810. return wildcards, extensions, filter_index
  811.  
  812. def gui_repaint(self, drawDC=None, origin='WX'):
  813. """
  814. Performs update of the displayed image on the GUI canvas, using the
  815. supplied wx.PaintDC device context.
  816.  
  817. The 'WXAgg' backend sets origin accordingly.
  818. """
  819. DEBUG_MSG("gui_repaint()", 1, self)
  820. if self.IsShownOnScreen():
  821. if not drawDC:
  822. # not called from OnPaint use a ClientDC
  823. drawDC = wx.ClientDC(self)
  824.  
  825. # following is for 'WX' backend on Windows
  826. # the bitmap can not be in use by another DC,
  827. # see GraphicsContextWx._cache
  828. if wx.Platform == '__WXMSW__' and origin == 'WX':
  829. img = self.bitmap.ConvertToImage()
  830. bmp = img.ConvertToBitmap()
  831. drawDC.DrawBitmap(bmp, 0, 0)
  832. else:
  833. drawDC.DrawBitmap(self.bitmap, 0, 0)
  834.  
  835. filetypes = FigureCanvasBase.filetypes.copy()
  836. filetypes['bmp'] = 'Windows bitmap'
  837. filetypes['jpeg'] = 'JPEG'
  838. filetypes['jpg'] = 'JPEG'
  839. filetypes['pcx'] = 'PCX'
  840. filetypes['png'] = 'Portable Network Graphics'
  841. filetypes['tif'] = 'Tagged Image Format File'
  842. filetypes['tiff'] = 'Tagged Image Format File'
  843. filetypes['xpm'] = 'X pixmap'
  844.  
  845. def print_figure(self, filename, *args, **kwargs):
  846. # Use pure Agg renderer to draw
  847. FigureCanvasBase.print_figure(self, filename, *args, **kwargs)
  848. # Restore the current view; this is needed because the
  849. # artist contains methods rely on particular attributes
  850. # of the rendered figure for determining things like
  851. # bounding boxes.
  852. if self._isDrawn:
  853. self.draw()
  854.  
  855. def print_bmp(self, filename, *args, **kwargs):
  856. return self._print_image(filename, wx.BITMAP_TYPE_BMP, *args, **kwargs)
  857.  
  858. if not _has_pil:
  859. def print_jpeg(self, filename, *args, **kwargs):
  860. return self._print_image(filename, wx.BITMAP_TYPE_JPEG,
  861. *args, **kwargs)
  862. print_jpg = print_jpeg
  863.  
  864. def print_pcx(self, filename, *args, **kwargs):
  865. return self._print_image(filename, wx.BITMAP_TYPE_PCX, *args, **kwargs)
  866.  
  867. def print_png(self, filename, *args, **kwargs):
  868. return self._print_image(filename, wx.BITMAP_TYPE_PNG, *args, **kwargs)
  869.  
  870. if not _has_pil:
  871. def print_tiff(self, filename, *args, **kwargs):
  872. return self._print_image(filename, wx.BITMAP_TYPE_TIF,
  873. *args, **kwargs)
  874. print_tif = print_tiff
  875.  
  876. def print_xpm(self, filename, *args, **kwargs):
  877. return self._print_image(filename, wx.BITMAP_TYPE_XPM, *args, **kwargs)
  878.  
  879. def _print_image(self, filename, filetype, *args, **kwargs):
  880. origBitmap = self.bitmap
  881.  
  882. l, b, width, height = self.figure.bbox.bounds
  883. width = int(math.ceil(width))
  884. height = int(math.ceil(height))
  885.  
  886. self.bitmap = wxc.EmptyBitmap(width, height)
  887.  
  888. renderer = RendererWx(self.bitmap, self.figure.dpi)
  889.  
  890. gc = renderer.new_gc()
  891.  
  892. self.figure.draw(renderer)
  893.  
  894. # image is the object that we call SaveFile on.
  895. image = self.bitmap
  896. # set the JPEG quality appropriately. Unfortunately, it is only
  897. # possible to set the quality on a wx.Image object. So if we
  898. # are saving a JPEG, convert the wx.Bitmap to a wx.Image,
  899. # and set the quality.
  900. if filetype == wx.BITMAP_TYPE_JPEG:
  901. jpeg_quality = kwargs.get('quality',
  902. rcParams['savefig.jpeg_quality'])
  903. image = self.bitmap.ConvertToImage()
  904. image.SetOption(wx.IMAGE_OPTION_QUALITY, str(jpeg_quality))
  905.  
  906. # Now that we have rendered into the bitmap, save it
  907. # to the appropriate file type and clean up
  908. if isinstance(filename, six.string_types):
  909. if not image.SaveFile(filename, filetype):
  910. DEBUG_MSG('print_figure() file save error', 4, self)
  911. raise RuntimeError(
  912. 'Could not save figure to %s\n' %
  913. (filename))
  914. elif is_writable_file_like(filename):
  915. if not isinstance(image, wx.Image):
  916. image = image.ConvertToImage()
  917. if not image.SaveStream(filename, filetype):
  918. DEBUG_MSG('print_figure() file save error', 4, self)
  919. raise RuntimeError(
  920. 'Could not save figure to %s\n' %
  921. (filename))
  922.  
  923. # Restore everything to normal
  924. self.bitmap = origBitmap
  925.  
  926. # Note: draw is required here since bits of state about the
  927. # last renderer are strewn about the artist draw methods. Do
  928. # not remove the draw without first verifying that these have
  929. # been cleaned up. The artist contains() methods will fail
  930. # otherwise.
  931. if self._isDrawn:
  932. self.draw()
  933. self.Refresh()
  934.  
  935. def _onPaint(self, evt):
  936. """
  937. Called when wxPaintEvt is generated
  938. """
  939.  
  940. DEBUG_MSG("_onPaint()", 1, self)
  941. drawDC = wx.PaintDC(self)
  942. if not self._isDrawn:
  943. self.draw(drawDC=drawDC)
  944. else:
  945. self.gui_repaint(drawDC=drawDC)
  946. evt.Skip()
  947.  
  948. def _onEraseBackground(self, evt):
  949. """
  950. Called when window is redrawn; since we are blitting the entire
  951. image, we can leave this blank to suppress flicker.
  952. """
  953. pass
  954.  
  955. def _onSize(self, evt):
  956. """
  957. Called when wxEventSize is generated.
  958.  
  959. In this application we attempt to resize to fit the window, so it
  960. is better to take the performance hit and redraw the whole window.
  961. """
  962.  
  963. DEBUG_MSG("_onSize()", 2, self)
  964. # Create a new, correctly sized bitmap
  965. self._width, self._height = self.GetClientSize()
  966. self.bitmap = wxc.EmptyBitmap(self._width, self._height)
  967.  
  968. self._isDrawn = False
  969.  
  970. if self._width <= 1 or self._height <= 1:
  971. return # Empty figure
  972.  
  973. dpival = self.figure.dpi
  974. winch = self._width / dpival
  975. hinch = self._height / dpival
  976. self.figure.set_size_inches(winch, hinch, forward=False)
  977.  
  978. # Rendering will happen on the associated paint event
  979. # so no need to do anything here except to make sure
  980. # the whole background is repainted.
  981. self.Refresh(eraseBackground=False)
  982. FigureCanvasBase.resize_event(self)
  983.  
  984. def _get_key(self, evt):
  985.  
  986. keyval = evt.KeyCode
  987. if keyval in self.keyvald:
  988. key = self.keyvald[keyval]
  989. elif keyval < 256:
  990. key = chr(keyval)
  991. # wx always returns an uppercase, so make it lowercase if the shift
  992. # key is not depressed (NOTE: this will not handle Caps Lock)
  993. if not evt.ShiftDown():
  994. key = key.lower()
  995. else:
  996. key = None
  997.  
  998. for meth, prefix in (
  999. [evt.AltDown, 'alt'],
  1000. [evt.ControlDown, 'ctrl'], ):
  1001. if meth():
  1002. key = '{0}+{1}'.format(prefix, key)
  1003.  
  1004. return key
  1005.  
  1006. def _onKeyDown(self, evt):
  1007. """Capture key press."""
  1008. key = self._get_key(evt)
  1009. evt.Skip()
  1010. FigureCanvasBase.key_press_event(self, key, guiEvent=evt)
  1011.  
  1012. def _onKeyUp(self, evt):
  1013. """Release key."""
  1014. key = self._get_key(evt)
  1015. # print 'release key', key
  1016. evt.Skip()
  1017. FigureCanvasBase.key_release_event(self, key, guiEvent=evt)
  1018.  
  1019. def _set_capture(self, capture=True):
  1020. """control wx mouse capture """
  1021. if self.HasCapture():
  1022. self.ReleaseMouse()
  1023. if capture:
  1024. self.CaptureMouse()
  1025.  
  1026. def _onCaptureLost(self, evt):
  1027. """Capture changed or lost"""
  1028. self._set_capture(False)
  1029.  
  1030. def _onRightButtonDown(self, evt):
  1031. """Start measuring on an axis."""
  1032. x = evt.GetX()
  1033. y = self.figure.bbox.height - evt.GetY()
  1034. evt.Skip()
  1035. self._set_capture(True)
  1036. FigureCanvasBase.button_press_event(self, x, y, 3, guiEvent=evt)
  1037.  
  1038. def _onRightButtonDClick(self, evt):
  1039. """Start measuring on an axis."""
  1040. x = evt.GetX()
  1041. y = self.figure.bbox.height - evt.GetY()
  1042. evt.Skip()
  1043. self._set_capture(True)
  1044. FigureCanvasBase.button_press_event(self, x, y, 3,
  1045. dblclick=True, guiEvent=evt)
  1046.  
  1047. def _onRightButtonUp(self, evt):
  1048. """End measuring on an axis."""
  1049. x = evt.GetX()
  1050. y = self.figure.bbox.height - evt.GetY()
  1051. evt.Skip()
  1052. self._set_capture(False)
  1053. FigureCanvasBase.button_release_event(self, x, y, 3, guiEvent=evt)
  1054.  
  1055. def _onLeftButtonDown(self, evt):
  1056. """Start measuring on an axis."""
  1057. x = evt.GetX()
  1058. y = self.figure.bbox.height - evt.GetY()
  1059. evt.Skip()
  1060. self._set_capture(True)
  1061. FigureCanvasBase.button_press_event(self, x, y, 1, guiEvent=evt)
  1062.  
  1063. def _onLeftButtonDClick(self, evt):
  1064. """Start measuring on an axis."""
  1065. x = evt.GetX()
  1066. y = self.figure.bbox.height - evt.GetY()
  1067. evt.Skip()
  1068. self._set_capture(True)
  1069. FigureCanvasBase.button_press_event(self, x, y, 1,
  1070. dblclick=True, guiEvent=evt)
  1071.  
  1072. def _onLeftButtonUp(self, evt):
  1073. """End measuring on an axis."""
  1074. x = evt.GetX()
  1075. y = self.figure.bbox.height - evt.GetY()
  1076. # print 'release button', 1
  1077. evt.Skip()
  1078. self._set_capture(False)
  1079. FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=evt)
  1080.  
  1081. # Add middle button events
  1082. def _onMiddleButtonDown(self, evt):
  1083. """Start measuring on an axis."""
  1084. x = evt.GetX()
  1085. y = self.figure.bbox.height - evt.GetY()
  1086. evt.Skip()
  1087. self._set_capture(True)
  1088. FigureCanvasBase.button_press_event(self, x, y, 2, guiEvent=evt)
  1089.  
  1090. def _onMiddleButtonDClick(self, evt):
  1091. """Start measuring on an axis."""
  1092. x = evt.GetX()
  1093. y = self.figure.bbox.height - evt.GetY()
  1094. evt.Skip()
  1095. self._set_capture(True)
  1096. FigureCanvasBase.button_press_event(self, x, y, 2,
  1097. dblclick=True, guiEvent=evt)
  1098.  
  1099. def _onMiddleButtonUp(self, evt):
  1100. """End measuring on an axis."""
  1101. x = evt.GetX()
  1102. y = self.figure.bbox.height - evt.GetY()
  1103. # print 'release button', 1
  1104. evt.Skip()
  1105. self._set_capture(False)
  1106. FigureCanvasBase.button_release_event(self, x, y, 2, guiEvent=evt)
  1107.  
  1108. def _onMouseWheel(self, evt):
  1109. """Translate mouse wheel events into matplotlib events"""
  1110.  
  1111. # Determine mouse location
  1112. x = evt.GetX()
  1113. y = self.figure.bbox.height - evt.GetY()
  1114.  
  1115. # Convert delta/rotation/rate into a floating point step size
  1116. delta = evt.GetWheelDelta()
  1117. rotation = evt.GetWheelRotation()
  1118. rate = evt.GetLinesPerAction()
  1119. # print "delta,rotation,rate",delta,rotation,rate
  1120. step = rate * float(rotation) / delta
  1121.  
  1122. # Done handling event
  1123. evt.Skip()
  1124.  
  1125. # Mac is giving two events for every wheel event
  1126. # Need to skip every second one
  1127. if wx.Platform == '__WXMAC__':
  1128. if not hasattr(self, '_skipwheelevent'):
  1129. self._skipwheelevent = True
  1130. elif self._skipwheelevent:
  1131. self._skipwheelevent = False
  1132. return # Return without processing event
  1133. else:
  1134. self._skipwheelevent = True
  1135.  
  1136. # Convert to mpl event
  1137. FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=evt)
  1138.  
  1139. def _onMotion(self, evt):
  1140. """Start measuring on an axis."""
  1141.  
  1142. x = evt.GetX()
  1143. y = self.figure.bbox.height - evt.GetY()
  1144. evt.Skip()
  1145. FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=evt)
  1146.  
  1147. def _onLeave(self, evt):
  1148. """Mouse has left the window."""
  1149.  
  1150. evt.Skip()
  1151. FigureCanvasBase.leave_notify_event(self, guiEvent=evt)
  1152.  
  1153. def _onEnter(self, evt):
  1154. """Mouse has entered the window."""
  1155. FigureCanvasBase.enter_notify_event(self, guiEvent=evt)
  1156.  
  1157.  
  1158. ########################################################################
  1159. #
  1160. # The following functions and classes are for pylab compatibility
  1161. # mode (matplotlib.pylab) and implement figure managers, etc...
  1162. #
  1163. ########################################################################
  1164.  
  1165.  
  1166. class FigureFrameWx(wx.Frame):
  1167. def __init__(self, num, fig):
  1168. # On non-Windows platform, explicitly set the position - fix
  1169. # positioning bug on some Linux platforms
  1170. if wx.Platform == '__WXMSW__':
  1171. pos = wx.DefaultPosition
  1172. else:
  1173. pos = wx.Point(20, 20)
  1174. l, b, w, h = fig.bbox.bounds
  1175. wx.Frame.__init__(self, parent=None, id=-1, pos=pos,
  1176. title="Figure %d" % num)
  1177. # Frame will be sized later by the Fit method
  1178. DEBUG_MSG("__init__()", 1, self)
  1179. self.num = num
  1180.  
  1181. statbar = StatusBarWx(self)
  1182. self.SetStatusBar(statbar)
  1183. self.canvas = self.get_canvas(fig)
  1184. self.canvas.SetInitialSize(wx.Size(fig.bbox.width, fig.bbox.height))
  1185. self.canvas.SetFocus()
  1186. self.sizer = wx.BoxSizer(wx.VERTICAL)
  1187. self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
  1188. # By adding toolbar in sizer, we are able to put it at the bottom
  1189. # of the frame - so appearance is closer to GTK version
  1190.  
  1191. self.toolbar = self._get_toolbar(statbar)
  1192.  
  1193. if self.toolbar is not None:
  1194. self.toolbar.Realize()
  1195. # On Windows platform, default window size is incorrect, so set
  1196. # toolbar width to figure width.
  1197. if wxc.is_phoenix:
  1198. tw, th = self.toolbar.GetSize()
  1199. fw, fh = self.canvas.GetSize()
  1200. else:
  1201. tw, th = self.toolbar.GetSizeTuple()
  1202. fw, fh = self.canvas.GetSizeTuple()
  1203. # By adding toolbar in sizer, we are able to put it at the bottom
  1204. # of the frame - so appearance is closer to GTK version.
  1205. self.toolbar.SetSize(wx.Size(fw, th))
  1206. self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
  1207. self.SetSizer(self.sizer)
  1208. self.Fit()
  1209.  
  1210. self.canvas.SetMinSize((2, 2))
  1211.  
  1212. # give the window a matplotlib icon rather than the stock one.
  1213. # This is not currently working on Linux and is untested elsewhere.
  1214. # icon_path = os.path.join(matplotlib.rcParams['datapath'],
  1215. # 'images', 'matplotlib.png')
  1216. #icon = wx.IconFromBitmap(wx.Bitmap(icon_path))
  1217. # for xpm type icons try:
  1218. #icon = wx.Icon(icon_path, wx.BITMAP_TYPE_XPM)
  1219. # self.SetIcon(icon)
  1220.  
  1221. self.figmgr = FigureManagerWx(self.canvas, num, self)
  1222.  
  1223. self.Bind(wx.EVT_CLOSE, self._onClose)
  1224.  
  1225. def _get_toolbar(self, statbar):
  1226. if rcParams['toolbar'] == 'toolbar2':
  1227. toolbar = NavigationToolbar2Wx(self.canvas)
  1228. toolbar.set_status_bar(statbar)
  1229. else:
  1230. toolbar = None
  1231. return toolbar
  1232.  
  1233. def get_canvas(self, fig):
  1234. return FigureCanvasWx(self, -1, fig)
  1235.  
  1236. def get_figure_manager(self):
  1237. DEBUG_MSG("get_figure_manager()", 1, self)
  1238. return self.figmgr
  1239.  
  1240. def _onClose(self, evt):
  1241. DEBUG_MSG("onClose()", 1, self)
  1242. self.canvas.close_event()
  1243. self.canvas.stop_event_loop()
  1244. Gcf.destroy(self.num)
  1245. # self.Destroy()
  1246.  
  1247. def GetToolBar(self):
  1248. """Override wxFrame::GetToolBar as we don't have managed toolbar"""
  1249. return self.toolbar
  1250.  
  1251. def Destroy(self, *args, **kwargs):
  1252. try:
  1253. self.canvas.mpl_disconnect(self.toolbar._idDrag)
  1254. # Rationale for line above: see issue 2941338.
  1255. except AttributeError:
  1256. pass # classic toolbar lacks the attribute
  1257. if not self.IsBeingDeleted():
  1258. wx.Frame.Destroy(self, *args, **kwargs)
  1259. if self.toolbar is not None:
  1260. self.toolbar.Destroy()
  1261. wxapp = wx.GetApp()
  1262. if wxapp:
  1263. wxapp.Yield()
  1264. return True
  1265.  
  1266.  
  1267. class FigureManagerWx(FigureManagerBase):
  1268. """
  1269. This class contains the FigureCanvas and GUI frame
  1270.  
  1271. It is instantiated by GcfWx whenever a new figure is created. GcfWx is
  1272. responsible for managing multiple instances of FigureManagerWx.
  1273.  
  1274. Attributes
  1275. ----------
  1276. canvas : `FigureCanvas`
  1277. a FigureCanvasWx(wx.Panel) instance
  1278. window : wxFrame
  1279. a wxFrame instance - wxpython.org/Phoenix/docs/html/Frame.html
  1280.  
  1281. """
  1282.  
  1283. def __init__(self, canvas, num, frame):
  1284. DEBUG_MSG("__init__()", 1, self)
  1285. FigureManagerBase.__init__(self, canvas, num)
  1286. self.frame = frame
  1287. self.window = frame
  1288.  
  1289. self.tb = frame.GetToolBar()
  1290. self.toolbar = self.tb # consistent with other backends
  1291.  
  1292. def notify_axes_change(fig):
  1293. 'this will be called whenever the current axes is changed'
  1294. if self.tb is not None:
  1295. self.tb.update()
  1296. self.canvas.figure.add_axobserver(notify_axes_change)
  1297.  
  1298. def show(self):
  1299. self.frame.Show()
  1300. self.canvas.draw()
  1301.  
  1302. def destroy(self, *args):
  1303. DEBUG_MSG("destroy()", 1, self)
  1304. self.frame.Destroy()
  1305. wxapp = wx.GetApp()
  1306. if wxapp:
  1307. wxapp.Yield()
  1308.  
  1309. def get_window_title(self):
  1310. return self.window.GetTitle()
  1311.  
  1312. def set_window_title(self, title):
  1313. self.window.SetTitle(title)
  1314.  
  1315. def resize(self, width, height):
  1316. 'Set the canvas size in pixels'
  1317. self.canvas.SetInitialSize(wx.Size(width, height))
  1318. self.window.GetSizer().Fit(self.window)
  1319.  
  1320. # Identifiers for toolbar controls - images_wx contains bitmaps for the images
  1321. # used in the controls. wxWindows does not provide any stock images, so I've
  1322. # 'stolen' those from GTK2, and transformed them into the appropriate format.
  1323. #import images_wx
  1324.  
  1325. _NTB_AXISMENU = wx.NewId()
  1326. _NTB_AXISMENU_BUTTON = wx.NewId()
  1327. _NTB_X_PAN_LEFT = wx.NewId()
  1328. _NTB_X_PAN_RIGHT = wx.NewId()
  1329. _NTB_X_ZOOMIN = wx.NewId()
  1330. _NTB_X_ZOOMOUT = wx.NewId()
  1331. _NTB_Y_PAN_UP = wx.NewId()
  1332. _NTB_Y_PAN_DOWN = wx.NewId()
  1333. _NTB_Y_ZOOMIN = wx.NewId()
  1334. _NTB_Y_ZOOMOUT = wx.NewId()
  1335. #_NTB_SUBPLOT =wx.NewId()
  1336. _NTB_SAVE = wx.NewId()
  1337. _NTB_CLOSE = wx.NewId()
  1338.  
  1339.  
  1340. def _load_bitmap(filename):
  1341. """
  1342. Load a bitmap file from the backends/images subdirectory in which the
  1343. matplotlib library is installed. The filename parameter should not
  1344. contain any path information as this is determined automatically.
  1345.  
  1346. Returns a wx.Bitmap object
  1347. """
  1348.  
  1349. basedir = os.path.join(rcParams['datapath'], 'images')
  1350.  
  1351. bmpFilename = os.path.normpath(os.path.join(basedir, filename))
  1352. if not os.path.exists(bmpFilename):
  1353. raise IOError('Could not find bitmap file "%s"; dying' % bmpFilename)
  1354.  
  1355. bmp = wx.Bitmap(bmpFilename)
  1356. return bmp
  1357.  
  1358.  
  1359. class MenuButtonWx(wx.Button):
  1360. """
  1361. wxPython does not permit a menu to be incorporated directly into a toolbar.
  1362. This class simulates the effect by associating a pop-up menu with a button
  1363. in the toolbar, and managing this as though it were a menu.
  1364. """
  1365.  
  1366. def __init__(self, parent):
  1367.  
  1368. wx.Button.__init__(self, parent, _NTB_AXISMENU_BUTTON, "Axes: ",
  1369. style=wx.BU_EXACTFIT)
  1370. self._toolbar = parent
  1371. self._menu = wx.Menu()
  1372. self._axisId = []
  1373. # First two menu items never change...
  1374. self._allId = wx.NewId()
  1375. self._invertId = wx.NewId()
  1376. self._menu.Append(self._allId, "All", "Select all axes", False)
  1377. self._menu.Append(self._invertId, "Invert", "Invert axes selected",
  1378. False)
  1379. self._menu.AppendSeparator()
  1380.  
  1381. self.Bind(wx.EVT_BUTTON, self._onMenuButton, id=_NTB_AXISMENU_BUTTON)
  1382. self.Bind(wx.EVT_MENU, self._handleSelectAllAxes, id=self._allId)
  1383. self.Bind(wx.EVT_MENU, self._handleInvertAxesSelected,
  1384. id=self._invertId)
  1385.  
  1386. def Destroy(self):
  1387. self._menu.Destroy()
  1388. self.Destroy()
  1389.  
  1390. def _onMenuButton(self, evt):
  1391. """Handle menu button pressed."""
  1392. if wxc.is_phoenix:
  1393. x, y = self.GetPosition()
  1394. w, h = self.GetSize()
  1395. else:
  1396. x, y = self.GetPositionTuple()
  1397. w, h = self.GetSizeTuple()
  1398. self.PopupMenuXY(self._menu, x, y + h - 4)
  1399. # When menu returned, indicate selection in button
  1400. evt.Skip()
  1401.  
  1402. def _handleSelectAllAxes(self, evt):
  1403. """Called when the 'select all axes' menu item is selected."""
  1404. if len(self._axisId) == 0:
  1405. return
  1406. for i in range(len(self._axisId)):
  1407. self._menu.Check(self._axisId[i], True)
  1408. self._toolbar.set_active(self.getActiveAxes())
  1409. evt.Skip()
  1410.  
  1411. def _handleInvertAxesSelected(self, evt):
  1412. """Called when the invert all menu item is selected"""
  1413. if len(self._axisId) == 0:
  1414. return
  1415. for i in range(len(self._axisId)):
  1416. if self._menu.IsChecked(self._axisId[i]):
  1417. self._menu.Check(self._axisId[i], False)
  1418. else:
  1419. self._menu.Check(self._axisId[i], True)
  1420. self._toolbar.set_active(self.getActiveAxes())
  1421. evt.Skip()
  1422.  
  1423. def _onMenuItemSelected(self, evt):
  1424. """Called whenever one of the specific axis menu items is selected"""
  1425. current = self._menu.IsChecked(evt.GetId())
  1426. if current:
  1427. new = False
  1428. else:
  1429. new = True
  1430. self._menu.Check(evt.GetId(), new)
  1431. # Lines above would be deleted based on svn tracker ID 2841525;
  1432. # not clear whether this matters or not.
  1433. self._toolbar.set_active(self.getActiveAxes())
  1434. evt.Skip()
  1435.  
  1436. def updateAxes(self, maxAxis):
  1437. """Ensures that there are entries for max_axis axes in the menu
  1438. (selected by default)."""
  1439. if maxAxis > len(self._axisId):
  1440. for i in range(len(self._axisId) + 1, maxAxis + 1, 1):
  1441. menuId = wx.NewId()
  1442. self._axisId.append(menuId)
  1443. self._menu.Append(menuId, "Axis %d" % i,
  1444. "Select axis %d" % i,
  1445. True)
  1446. self._menu.Check(menuId, True)
  1447. self.Bind(wx.EVT_MENU, self._onMenuItemSelected, id=menuId)
  1448. elif maxAxis < len(self._axisId):
  1449. for menuId in self._axisId[maxAxis:]:
  1450. self._menu.Delete(menuId)
  1451. self._axisId = self._axisId[:maxAxis]
  1452. self._toolbar.set_active(list(xrange(maxAxis)))
  1453.  
  1454. def getActiveAxes(self):
  1455. """Return a list of the selected axes."""
  1456. active = []
  1457. for i in range(len(self._axisId)):
  1458. if self._menu.IsChecked(self._axisId[i]):
  1459. active.append(i)
  1460. return active
  1461.  
  1462. def updateButtonText(self, lst):
  1463. """Update the list of selected axes in the menu button"""
  1464. axis_txt = ''
  1465. for e in lst:
  1466. axis_txt += '%d,' % (e + 1)
  1467. # remove trailing ',' and add to button string
  1468. self.SetLabel("Axes: %s" % axis_txt[:-1])
  1469.  
  1470.  
  1471. cursord = {
  1472. cursors.MOVE: wx.CURSOR_HAND,
  1473. cursors.HAND: wx.CURSOR_HAND,
  1474. cursors.POINTER: wx.CURSOR_ARROW,
  1475. cursors.SELECT_REGION: wx.CURSOR_CROSS,
  1476. cursors.WAIT: wx.CURSOR_WAIT,
  1477. }
  1478.  
  1479.  
  1480. class SubplotToolWX(wx.Frame):
  1481. def __init__(self, targetfig):
  1482. wx.Frame.__init__(self, None, -1, "Configure subplots")
  1483.  
  1484. toolfig = Figure((6, 3))
  1485. canvas = FigureCanvasWx(self, -1, toolfig)
  1486.  
  1487. # Create a figure manager to manage things
  1488. figmgr = FigureManager(canvas, 1, self)
  1489.  
  1490. # Now put all into a sizer
  1491. sizer = wx.BoxSizer(wx.VERTICAL)
  1492. # This way of adding to sizer allows resizing
  1493. sizer.Add(canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
  1494. self.SetSizer(sizer)
  1495. self.Fit()
  1496. tool = SubplotTool(targetfig, toolfig)
  1497.  
  1498.  
  1499. class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar):
  1500. def __init__(self, canvas):
  1501. wx.ToolBar.__init__(self, canvas.GetParent(), -1)
  1502. NavigationToolbar2.__init__(self, canvas)
  1503. self.canvas = canvas
  1504. self._idle = True
  1505. self.statbar = None
  1506. self.prevZoomRect = None
  1507. # for now, use alternate zoom-rectangle drawing on all
  1508. # Macs. N.B. In future versions of wx it may be possible to
  1509. # detect Retina displays with window.GetContentScaleFactor()
  1510. # and/or dc.GetContentScaleFactor()
  1511. self.retinaFix = 'wxMac' in wx.PlatformInfo
  1512.  
  1513. def get_canvas(self, frame, fig):
  1514. return FigureCanvasWx(frame, -1, fig)
  1515.  
  1516. def _init_toolbar(self):
  1517. DEBUG_MSG("_init_toolbar", 1, self)
  1518.  
  1519. self._parent = self.canvas.GetParent()
  1520.  
  1521. self.wx_ids = {}
  1522. for text, tooltip_text, image_file, callback in self.toolitems:
  1523. if text is None:
  1524. self.AddSeparator()
  1525. continue
  1526. self.wx_ids[text] = wx.NewId()
  1527. wxc._AddTool(self, self.wx_ids, text,
  1528. _load_bitmap(image_file + '.png'),
  1529. tooltip_text)
  1530.  
  1531. self.Bind(wx.EVT_TOOL, getattr(self, callback),
  1532. id=self.wx_ids[text])
  1533.  
  1534. self.Realize()
  1535.  
  1536. def zoom(self, *args):
  1537. self.ToggleTool(self.wx_ids['Pan'], False)
  1538. NavigationToolbar2.zoom(self, *args)
  1539.  
  1540. def pan(self, *args):
  1541. self.ToggleTool(self.wx_ids['Zoom'], False)
  1542. NavigationToolbar2.pan(self, *args)
  1543.  
  1544. def configure_subplots(self, evt):
  1545. frame = wx.Frame(None, -1, "Configure subplots")
  1546.  
  1547. toolfig = Figure((6, 3))
  1548. canvas = self.get_canvas(frame, toolfig)
  1549.  
  1550. # Create a figure manager to manage things
  1551. figmgr = FigureManager(canvas, 1, frame)
  1552.  
  1553. # Now put all into a sizer
  1554. sizer = wx.BoxSizer(wx.VERTICAL)
  1555. # This way of adding to sizer allows resizing
  1556. sizer.Add(canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
  1557. frame.SetSizer(sizer)
  1558. frame.Fit()
  1559. tool = SubplotTool(self.canvas.figure, toolfig)
  1560. frame.Show()
  1561.  
  1562. def save_figure(self, *args):
  1563. # Fetch the required filename and file type.
  1564. filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards()
  1565. default_file = self.canvas.get_default_filename()
  1566. dlg = wx.FileDialog(self._parent, "Save to file", "", default_file,
  1567. filetypes,
  1568. wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  1569. dlg.SetFilterIndex(filter_index)
  1570. if dlg.ShowModal() == wx.ID_OK:
  1571. dirname = dlg.GetDirectory()
  1572. filename = dlg.GetFilename()
  1573. DEBUG_MSG(
  1574. 'Save file dir:%s name:%s' %
  1575. (dirname, filename), 3, self)
  1576. format = exts[dlg.GetFilterIndex()]
  1577. basename, ext = os.path.splitext(filename)
  1578. if ext.startswith('.'):
  1579. ext = ext[1:]
  1580. if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format != ext:
  1581. # looks like they forgot to set the image type drop
  1582. # down, going with the extension.
  1583. warnings.warn(
  1584. 'extension %s did not match the selected '
  1585. 'image type %s; going with %s' %
  1586. (ext, format, ext), stacklevel=0)
  1587. format = ext
  1588. try:
  1589. self.canvas.figure.savefig(
  1590. os.path.join(dirname, filename), format=format)
  1591. except Exception as e:
  1592. error_msg_wx(str(e))
  1593.  
  1594. def set_cursor(self, cursor):
  1595. cursor = wxc.Cursor(cursord[cursor])
  1596. self.canvas.SetCursor(cursor)
  1597. self.canvas.Update()
  1598.  
  1599. def release(self, event):
  1600. try:
  1601. del self.lastrect
  1602. except AttributeError:
  1603. pass
  1604.  
  1605. @cbook.deprecated("2.1", alternative="canvas.draw_idle")
  1606. def dynamic_update(self):
  1607. d = self._idle
  1608. self._idle = False
  1609. if d:
  1610. self.canvas.draw()
  1611. self._idle = True
  1612.  
  1613. def press(self, event):
  1614. if self._active == 'ZOOM':
  1615. if not self.retinaFix:
  1616. self.wxoverlay = wx.Overlay()
  1617. else:
  1618. if event.inaxes is not None:
  1619. self.savedRetinaImage = self.canvas.copy_from_bbox(
  1620. event.inaxes.bbox)
  1621. self.zoomStartX = event.xdata
  1622. self.zoomStartY = event.ydata
  1623. self.zoomAxes = event.inaxes
  1624.  
  1625. def release(self, event):
  1626. if self._active == 'ZOOM':
  1627. # When the mouse is released we reset the overlay and it
  1628. # restores the former content to the window.
  1629. if not self.retinaFix:
  1630. self.wxoverlay.Reset()
  1631. del self.wxoverlay
  1632. else:
  1633. del self.savedRetinaImage
  1634. if self.prevZoomRect:
  1635. self.prevZoomRect.pop(0).remove()
  1636. self.prevZoomRect = None
  1637. if self.zoomAxes:
  1638. self.zoomAxes = None
  1639.  
  1640. def draw_rubberband(self, event, x0, y0, x1, y1):
  1641. if self.retinaFix: # On Macs, use the following code
  1642. # wx.DCOverlay does not work properly on Retina displays.
  1643. rubberBandColor = '#C0C0FF'
  1644. if self.prevZoomRect:
  1645. self.prevZoomRect.pop(0).remove()
  1646. self.canvas.restore_region(self.savedRetinaImage)
  1647. X0, X1 = self.zoomStartX, event.xdata
  1648. Y0, Y1 = self.zoomStartY, event.ydata
  1649. lineX = (X0, X0, X1, X1, X0)
  1650. lineY = (Y0, Y1, Y1, Y0, Y0)
  1651. self.prevZoomRect = self.zoomAxes.plot(
  1652. lineX, lineY, '-', color=rubberBandColor)
  1653. self.zoomAxes.draw_artist(self.prevZoomRect[0])
  1654. self.canvas.blit(self.zoomAxes.bbox)
  1655. return
  1656.  
  1657. # Use an Overlay to draw a rubberband-like bounding box.
  1658.  
  1659. dc = wx.ClientDC(self.canvas)
  1660. odc = wx.DCOverlay(self.wxoverlay, dc)
  1661. odc.Clear()
  1662.  
  1663. # Mac's DC is already the same as a GCDC, and it causes
  1664. # problems with the overlay if we try to use an actual
  1665. # wx.GCDC so don't try it.
  1666. if 'wxMac' not in wx.PlatformInfo:
  1667. dc = wx.GCDC(dc)
  1668.  
  1669. height = self.canvas.figure.bbox.height
  1670. y1 = height - y1
  1671. y0 = height - y0
  1672.  
  1673. if y1 < y0:
  1674. y0, y1 = y1, y0
  1675. if x1 < y0:
  1676. x0, x1 = x1, x0
  1677.  
  1678. w = x1 - x0
  1679. h = y1 - y0
  1680. rect = wx.Rect(x0, y0, w, h)
  1681.  
  1682. rubberBandColor = '#C0C0FF' # or load from config?
  1683.  
  1684. # Set a pen for the border
  1685. color = wxc.NamedColour(rubberBandColor)
  1686. dc.SetPen(wx.Pen(color, 1))
  1687.  
  1688. # use the same color, plus alpha for the brush
  1689. r, g, b, a = color.Get(True)
  1690. color.Set(r, g, b, 0x60)
  1691. dc.SetBrush(wx.Brush(color))
  1692. if wxc.is_phoenix:
  1693. dc.DrawRectangle(rect)
  1694. else:
  1695. dc.DrawRectangleRect(rect)
  1696.  
  1697. def set_status_bar(self, statbar):
  1698. self.statbar = statbar
  1699.  
  1700. def set_message(self, s):
  1701. if self.statbar is not None:
  1702. self.statbar.set_function(s)
  1703.  
  1704. def set_history_buttons(self):
  1705. can_backward = (self._views._pos > 0)
  1706. can_forward = (self._views._pos < len(self._views._elements) - 1)
  1707. self.EnableTool(self.wx_ids['Back'], can_backward)
  1708. self.EnableTool(self.wx_ids['Forward'], can_forward)
  1709.  
  1710.  
  1711. class StatusBarWx(wx.StatusBar):
  1712. """
  1713. A status bar is added to _FigureFrame to allow measurements and the
  1714. previously selected scroll function to be displayed as a user
  1715. convenience.
  1716. """
  1717.  
  1718. def __init__(self, parent):
  1719. wx.StatusBar.__init__(self, parent, -1)
  1720. self.SetFieldsCount(2)
  1721. self.SetStatusText("None", 1)
  1722. #self.SetStatusText("Measurement: None", 2)
  1723. # self.Reposition()
  1724.  
  1725. def set_function(self, string):
  1726. self.SetStatusText("%s" % string, 1)
  1727.  
  1728. # def set_measurement(self, string):
  1729. # self.SetStatusText("Measurement: %s" % string, 2)
  1730.  
  1731.  
  1732. #< Additions for printing support: Matt Newville
  1733.  
  1734. class PrintoutWx(wx.Printout):
  1735. """
  1736. Simple wrapper around wx Printout class -- all the real work
  1737. here is scaling the matplotlib canvas bitmap to the current
  1738. printer's definition.
  1739. """
  1740.  
  1741. def __init__(self, canvas, width=5.5, margin=0.5, title='matplotlib'):
  1742. wx.Printout.__init__(self, title=title)
  1743. self.canvas = canvas
  1744. # width, in inches of output figure (approximate)
  1745. self.width = width
  1746. self.margin = margin
  1747.  
  1748. def HasPage(self, page):
  1749. # current only supports 1 page print
  1750. return page == 1
  1751.  
  1752. def GetPageInfo(self):
  1753. return (1, 1, 1, 1)
  1754.  
  1755. def OnPrintPage(self, page):
  1756. self.canvas.draw()
  1757.  
  1758. dc = self.GetDC()
  1759. (ppw, pph) = self.GetPPIPrinter() # printer's pixels per in
  1760. (pgw, pgh) = self.GetPageSizePixels() # page size in pixels
  1761. (dcw, dch) = dc.GetSize()
  1762. if wxc.is_phoenix:
  1763. (grw, grh) = self.canvas.GetSize()
  1764. else:
  1765. (grw, grh) = self.canvas.GetSizeTuple()
  1766.  
  1767. # save current figure dpi resolution and bg color,
  1768. # so that we can temporarily set them to the dpi of
  1769. # the printer, and the bg color to white
  1770. bgcolor = self.canvas.figure.get_facecolor()
  1771. fig_dpi = self.canvas.figure.dpi
  1772.  
  1773. # draw the bitmap, scaled appropriately
  1774. vscale = float(ppw) / fig_dpi
  1775.  
  1776. # set figure resolution,bg color for printer
  1777. self.canvas.figure.dpi = ppw
  1778. self.canvas.figure.set_facecolor('#FFFFFF')
  1779.  
  1780. renderer = RendererWx(self.canvas.bitmap, self.canvas.figure.dpi)
  1781. self.canvas.figure.draw(renderer)
  1782. self.canvas.bitmap.SetWidth(
  1783. int(self.canvas.bitmap.GetWidth() * vscale))
  1784. self.canvas.bitmap.SetHeight(
  1785. int(self.canvas.bitmap.GetHeight() * vscale))
  1786. self.canvas.draw()
  1787.  
  1788. # page may need additional scaling on preview
  1789. page_scale = 1.0
  1790. if self.IsPreview():
  1791. page_scale = float(dcw) / pgw
  1792.  
  1793. # get margin in pixels = (margin in in) * (pixels/in)
  1794. top_margin = int(self.margin * pph * page_scale)
  1795. left_margin = int(self.margin * ppw * page_scale)
  1796. class PrintoutWx():
  1797. # set scale so that width of output is self.width inches
  1798. # (assuming grw is size of graph in inches....)
  1799. user_scale = (self.width * fig_dpi * page_scale) / float(grw)
  1800.  
  1801. dc.SetDeviceOrigin(left_margin, top_margin)
  1802. dc.SetUserScale(user_scale, user_scale)
  1803.  
  1804. self.title = title
  1805. try:
  1806. dc.DrawBitmap(self.canvas.bitmap, 0, 0)
  1807. except:
  1808. try:
  1809. dc.DrawBitmap(self.canvas.bitmap, (0, 0))
  1810. except:
  1811. pass
  1812.  
  1813. # restore original figure resolution
  1814. self.canvas.figure.set_facecolor(bgcolor)
  1815. self.canvas.figure.dpi = fig_dpi
  1816. self.canvas.draw()
  1817. return True
  1818. #>
  1819.  
  1820. ########################################################################
  1821. #
  1822. # Now just provide the standard names that backend.__init__ is expecting
  1823. #
  1824. ########################################################################
  1825.  
  1826. Toolbar = NavigationToolbar2Wx
  1827.  
  1828.  
  1829. @_Backend.export
  1830. class _BackendWx(_Backend):
  1831. FigureCanvas = FigureCanvasWx
  1832. FigureManager = FigureManagerWx
  1833. _frame_class = FigureFrameWx
  1834.  
  1835. @staticmethod
  1836. def trigger_manager_draw(manager):
  1837. manager.canvas.draw_idle()
  1838.  
  1839. @classmethod
  1840. def new_figure_manager(cls, num, *args, **kwargs):
  1841. # Create a wx.App instance if it has not been created sofar.
  1842. wxapp = wx.GetApp()
  1843. if wxapp is None:
  1844. wxapp = wx.App(False)
  1845. wxapp.SetExitOnFrameDelete(True)
  1846. # Retain a reference to the app object so that it does not get
  1847. # garbage collected.
  1848. _BackendWx._theWxApp = wxapp
  1849. return super(_BackendWx, cls).new_figure_manager(num, *args, **kwargs)
  1850.  
  1851. @classmethod
  1852. def new_figure_manager_given_figure(cls, num, figure):
  1853. frame = cls._frame_class(num, figure)
  1854. figmgr = frame.get_figure_manager()
  1855. if matplotlib.is_interactive():
  1856. figmgr.frame.Show()
  1857. figure.canvas.draw_idle()
  1858. return figmgr
  1859.  
  1860. @staticmethod
  1861. def mainloop():
  1862. if not wx.App.IsMainLoopRunning():
  1863. wxapp = wx.GetApp()
  1864. if wxapp is not None:
  1865. wxapp.MainLoop()
Advertisement
Add Comment
Please, Sign In to add comment