Logo Search packages:      
Sourcecode: mascyma version File versions  Download package


from __future__ import division 


 A wxPython backend for matplotlib, based (very heavily) on
 backend_template.py and backend_gtk.py

 Author: Jeremy O'Donoghue (jeremy@o-donoghue.com)
 Derived from original copyright work by John Hunter

 Copyright (C) Jeremy O'Donoghue & John Hunter, 2003
 License: This work is licensed under the PSF. A copy should be included
 with this source code, and is also available at

# CVS log information
# $Log: backend_wx.py,v $
# Revision 1.18  2003/12/15 15:43:52  jdh2358
# fixed install path problem
# Revision 1.17  2003/12/05 18:23:49  jdh2358
# resyncing wx
# Revision 1.16  2003/12/02 23:54:07  jodonoghue
# Fixed bug on wxGTK platform: assert self.Ok() in GraphicsContextWx.__init__() fails. This seems to be because the paltform does not allow call to Ok() within derived constructor.
# Revision 1.15  2003/12/02 15:28:20  jodonoghue
# Implemented double buffered drawing. Implemented save to several file formats. Corrected initial figure placement bug on Linux. Corrected figure size bug on Windows. Corrected text attribute redraw bug on all platforms. Fixed mousewheel operation on Windows (subject to known bug behaviour). Fixed toolbar buttons causing multiple events on Windows.
# Revision 1.13  2003/11/21 17:37:02  jodonoghue
# Update to changed Gcf and FigureManager API
# Revision 1.12  2003/11/17 18:15:14  jodonoghue
# Implemented backend changes for faceColor attribute in polygons. Fixed
# figure size difference from GTK, fixed incorrectly sized figure under
# Linux, modified toolbar to be exportable, modified mousewheel control
# to work over buttons as for GTK. Started implementation of saving bitmaps
# (not yet working).
# Revision 1.11  2003/11/14 18:49:53  jodonoghue
# Fixed bug in _onSize: self.bbox.set_bounds(), fixed interactive buttons
# to work without need for menu to be pressed first, menu button contains
# identities of selected axes. Preliminary support for a a wxPython control 
# encapsulating a FigureWx and toolbar - this is a work in progress, with
# some wrinkles, but works for examples.
# Revision 1.10  2003/11/12 18:30:54  jodonoghue
# Updates for refactored axes. Fixed xlabel location bug. Fixed pcolor
# rounding error (JDH patch), fixed problem in subplot_demo.py.
# Revision 1.9  2003/11/11 22:23:51  jdh2358
# refactored axes
# Revision 1.8  2003/11/11 16:22:02  jodonoghue
# Added status bar. Added mousewheel support. Fixed script session does
# not exit cleanly, fixed legend not displayed, fixed no clipping on text
# labels, fixed vertical text renders improperly
# Revision 1.7  2003/11/10 17:40:10  jodonoghue
# Added preliminary interactive zoom and pan support. Fixed incorrect circle
# centres, graphics clipping (text clipping stillnot implemented), coloured
# text, axis background.
 - Mousewheel (on Windows) only works after menu button has been pressed
   at least once
 - Mousewheel on Linux (wxGTK linked against GTK 1.2) does not work at all
 - Vertical text renders horizontally if you use a non TrueType font
   on Windows. This is a known wxPython issue. Work-around is to ensure
   that you use a TrueType font.
 - Pcolor demo puts chart slightly outside bounding box (approx 1-2 pixels
   to the bottom left)
 - embedding_in_wx example does not perform clipping of y axis data
 - Outputting to bitmap more than 300dpi results in some text being incorrectly
   scaled. Seems to be a wxPython bug on Windows or font point sizes > 60, as
   font size is correctly calculated.
 - Performance poorer than for previous direct rendering version
 - TIFF output not supported on wxGTK. This is a wxGTK issue
 - Text is not anti-aliased on wxGTK. This is probably a platform
   configuration issue.
Not implemented:
 - Printing

Fixed this release:
 - Implemented double-buffered drawing
 - GraphicsContextWx now inherits from wxMemoryDC (consequence of double
   buffered drawing)
 - Implemented save to JPEG, Windows BMP, PNG, TIF, PCX, XPM formats
 - Incorrect initial figure window placement on some Unix platforms
 - Mouse wheel (subject to known bug) works in Windows
 - Toolbar button presses cause multiple events on Windows platform
 - Width of figure frame now correct in Windows
 - Figures now respond correctly to resize events
 - Sets self._reset = False in AxisTextWx.__set_font() as per info
   from JDH in axes.py
 - figtext.py now works correctly - text attributes retained correctly

Examples which work on this release:
                         | Windows 2000    |  Linux            |
                         | wxPython 2.3.3  |  wxPython |
 - arctest.py            |     OK          |     OK            |
 - axes_demo.py          |     OK          |     OK            |
 - axes_props.py         |     OK          |     OK            |
 - barchart_demo.py      |     OK          |     OK            |
 - color_demo.py         |     OK          |     OK            |
 - csd_demo.py           |     OK          |     OK            |
 - dynamic_demo.py       |     N/A (2)     |     N/A (2)       |
 - embedding_in_gtk.py   |     N/A (2)     |     N/A (2)       |
 - embedding_in_wx.py    |     OK          |     OK            |
 - errorbar_demo.py      |     OK          |     OK            |
 - figtext.py            |     OK          |     OK            |
 - histogram_demo.py     |     OK          |     OK            |
 - interactive.py        |     N/A (2)     |     N/A (2)       |
 - interactive2.py       |     N/A (2)     |     N/A (2)       |
 - legend_demo.py        |     OK          |     OK            |
 - legend_demo2.py       |     OK          |     OK            |
 - line_styles.py        |     OK          |     OK            |
 - log_demo.py           |     OK          |     OK            |
 - logo.py               |     OK          |     OK            |
 - mpl_with_glade.py     |     N/A (2)     |     N/A (2)       |
 - mri_demo.py           |     OK          |     OK            |
 - mri_demo_with_eeg.py  |     OK          |     OK            |
 - multiple_figs_demo.py |     OK          |     OK            |
 - pcolor_demo.py        |     OK          |     OK            |
 - psd_demo.py           |     OK          |     OK            |
 - scatter_demo.py       |     OK          |     OK            |
 - scatter_demo2.py      |     OK          |     OK            |
 - simple_plot.py        |     OK          |     OK            |
 - stock_demo.py         |     OK          |     OK            |
 - subplot_demo.py       |     OK          |     OK            |
 - system_monitor.py     |     N/A (2)     |     N/A (2)       |
 - text_handles.py       |     OK          |     OK            |
 - text_themes.py        |     OK          |     OK            |
 - vline_demo.py         |     OK          |     OK            |

 (2) - Script uses GTK-specific features - cannot not run,
       but wxPython equivalent should be written.

cvs_id = '$Id: backend_wx.py,v 1.18 2003/12/15 15:43:52 jdh2358 Exp $'
# Debug level
_DEBUG = 4
_DEBUG_lvls = {1 : 'Low ', 2 : 'Med ', 3 : 'High', 4 : 'Error' }

def DEBUG_MSG(string, lvl=3, o=None):
    if lvl >= _DEBUG:
        cls = o.__class__
        print >>sys.stderr, "%s - %s in %s" % (_DEBUG_lvls[lvl], string, cls)

import sys, os, os.path, math

    from wxPython.wx import *
    print >>sys.stderr, "Matplotlib backend_wx requires wxPython be installed"

from matplotlib.backend_bases import RendererBase, GraphicsContextBase,\
     FigureBase, AxisTextBase, FigureManagerBase, _process_text_args, \
       error_msg, arg_to_rgb
from matplotlib._matlab_helpers import Gcf
from matplotlib.artist import Artist
from matplotlib.transforms import Transform, Bound1D, Bound2D
from matplotlib import get_data_path

wxapp = wxPySimpleApp()

# the true dots per inch on the screen; should be display dependent
# see 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 for some info about screen dpi

def error_msg_wx(msg, parent=None):
    Signal an error condition -- in a GUI, popup a error dialog
    dialog = wxMessageDialog(parent  = parent,
                             message = msg,
                             caption = 'Matplotlib backend_wx error',
                             style   = wxOK | wxCENTRE)
    return None

def raise_msg_to_str(msg):
    """msg is a return arg from a raise.  Join with new lines"""
    if not is_string_like(msg):
        msg = '\n'.join(map(str, msg))
    return msg

00206 class RendererWx(RendererBase):
    The renderer handles all the drawing primitives using a graphics
    context instance that controls the colors/styles. It acts as the
    'drawable' instance used by many classes in the hierarchy.
    #In wxPython, drawing is performed on a wxDC instance, which will
    #generally be mapped to the client aread of the window displaying
    #the plot. Under wxPython, the wxDC instance has a wxPen which
    #describes the colour and weight of any lines drawn, and a wxBrush
    #which describes the fill colour of any closed polygon.
00218     def __init__(self, bitmap):
        Initialise a wxWindows renderer instance.
        DEBUG_MSG("__init__()", 1, self)
        self.width  = bitmap.GetWidth()
        self.height = bitmap.GetHeight()
        self.bitmap = bitmap
        #self.gc = None
00228     def draw_arc(self, gc, faceColor, x, y, width, height, angle1, angle2):
        Draw an arc centered at x,y with width and height and angles
        from 0.0 to 360.0.
        If faceColor is present, fill the figure in this colour, otherwise 
        it is not filled.
        assert gc.Ok(), "wxMemoryDC not OK to use"
            # wxPython requires upper left corner of bounding rectange for ellipse
            # Theoretically you don't need the int() below, but it seems to make 
            # rounding of arc centre point more accurate in screen co-ordinates
        ulX = x - int(width/2)
        ulY = self.height - int(y + (height/2))
        if faceColor is not None:
            r,g,b = self._colour_to_rgb(faceColor)
            new_brush = wxBrush(wxColour(r,g,b), wxSOLID)
        gc.DrawEllipticArc(int(ulX), int(ulY), int(width)+1, int(height)+1,
                           int(angle1), int(angle2))
00250     def draw_line(self, gc, x1, y1, x2, y2):
        Draw a single line from x1,y1 to x2,y2
        DEBUG_MSG("draw_line()", 1, self)
        gc.DrawLine(int(x1), self.height - int(y1),
                    int(x2), self.height - int(y2))
00258     def draw_lines(self, gc, x, y):
        x and y are equal length arrays, draw lines connecting each
        point in x, y
        assert gc.Ok(), "wxMemoryDC not OK to use"
        assert len(x) == len(y), "draw_lines() x and y must be of equal length"
        gc.DrawLines([wxPoint(int(x[i]), self.height - int(y[i])) for i in range(len(x))])
00267     def draw_polygon(self, gc, faceColor, points):
        Draw a polygon.  points is a len vertices tuple, each element
        giving the x,y coords a vertex
        assert gc.Ok(), "wxMemoryDC not OK to use"
        points = [(int(x), self.height - int(y)) for x,y in points]
        if faceColor is not None:
            r,g,b = self._colour_to_rgb(faceColor)
            new_brush = wxBrush(wxColour(r,g,b), wxSOLID)

00282     def draw_rectangle(self, gc, faceColor, x, y, width, height):
        Draw a rectangle at lower left x,y with width and height
        If filled=True, fill the rectangle with the gc foreground
        gc is a GraphicsContext instance
        # wxPython uses rectangle from TOP left!
        assert gc.Ok(), "wxMemoryDC not OK to use"
        if faceColor is not None:
            r,g,b = self._colour_to_rgb(faceColor)
            new_brush = wxBrush(wxColour(r,g,b), wxSOLID)
        gc.DrawRectangle(int(x), self.height - int(height + y),
                             int(math.ceil(width)), int(math.ceil(height)))

00299     def draw_point(self, gc, x, y):
        Draw a single point at x,y
        assert gc.Ok(), "wxMemoryDC not OK to use"
        gc.DrawPoint(int(x), self.height - int(y))
    # Note that these text operations, unlike the drawing operations,
    # have already been translated to wxPython co-ordinates before calling
    # in the AxisTextWx class - and in other backends AxisText does not
    # perform calls via RendererXX - I believe that in the long term the
    # renderer is the 'logical' place to perform text operations, but for now
    # this is a reasonable solution for wxWindows.
00312     def draw_text(self, gc, t, x, y):
        Draw text at x, y using attributes from gc
        assert gc.Ok(), "wxMemoryDC not OK to use"
        gc.DrawText(t, int(x), self.height - int(y))
00319     def draw_rotated_text(self, gc, t, x, y, a=90):
        Draw text at (x,y), rotated by a degrees, using attributes from gc
        assert gc.Ok(), "wxMemoryDC not OK to use"
        gc.DrawRotatedText(t, int(x), self.height - int(y), a)

00326     def new_gc(self):
        Return an instance of a GraphicsContextWx, and sets the current gc copy
        DEBUG_MSG('new_gc()', 2, self)
        self.gc = GraphicsContextWx(self.bitmap, self)
        assert self.gc.Ok(), "wxMemoryDC not OK to use"
        return self.gc
00335     def get_gc(self):
        Fetch the locally cached gc.
        # This is a dirty hack to allow anything with access to a drawable to
        # access the current graphics context
        assert self.gc != None, "gc must be defined"
        return self.gc
        #if self.gc == None:
        #    return self.new_gc()
        #    return self.gc
00348     def _colour_to_rgb(self, colour):
        """Takes a colour value and returns a tuple (r,g,b) suitable
        for instantiating a wxColour."""
        r, g, b = arg_to_rgb(colour)
        return (int(r * 255), int(g * 255), int(b * 255))

00355 class GraphicsContextWx(GraphicsContextBase, wxMemoryDC):
    The graphics context provides the color, line styles, etc...
    In wxPython this is done by wrapping a wxDC object and forwarding the
    appropriate calls to it. Notice also that colour and line styles are
    mapped on the wxPen() member of the wxDC. This means that we have some
    rudimentary pen management here.
    The base GraphicsContext stores colors as a RGB tuple on the unit
    interval, eg, (0.5, 0.0, 1.0).  wxPython uses an int interval, but
    since wxPython colour management is rather simple, I have not chosen
    to implement a separate colour manager class.
    _capd = { 'butt':       wxCAP_BUTT,
              'projecting': wxCAP_PROJECTING,
              'round':      wxCAP_ROUND }
    _joind = { 'bevel':     wxJOIN_BEVEL,
               'miter':     wxJOIN_MITER,
               'round':     wxJOIN_ROUND }
    _dashd = { 'solid':     wxSOLID,
               'dashed':    wxSHORT_DASH,
               'dashdot':   wxDOT_DASH,
               'dotted':    wxDOT }
    _lastWxDC = None
    def __init__(self, bitmap, drawable):
        #assert self.Ok(), "wxMemoryDC not OK to use"
        DEBUG_MSG("__init__()", 1, self)
        # Make sure (belt and braces!) that existing wxDC is not selected to
        # to a bitmap.
        if GraphicsContextWx._lastWxDC != None:
            #print >>sys.stderr, "UnSelectObject(%s)" % str(bitmap) 
        #print >>sys.stderr, "SelectObject(%s)" % str(bitmap)
        self.SetPen(wxPen('BLACK', 1, wxSOLID))
        self._style = wxSOLID
        self.drawable = drawable    
        GraphicsContextWx._lastWxDC = self
00400     def set_clip_rectangle(self, rect):
        Destroys previous clipping region and defines a new one.
        DEBUG_MSG("set_clip_rectangle()", 1, self)
        l,b,w,h = rect
        self.SetClippingRegion(int(l), self.drawable.height - int(b+h),
                               int(w), int(h))

00409     def set_foreground(self, fg):
        Set the foreground color.  fg can be a matlab format string, a
        html hex color string, an rgb unit tuple, or a float between 0
        and 1.  In the latter case, grayscale is used.
            # Implementation note: wxPython has a separate concept of pen and
            # brush - the brush fills any outline trace left by the pen.
            # Here we set both to the same colour - if a figure is not to be 
            # filled, the renderer will set the brush to be transparent
        # Same goes for text foreground...
        DEBUG_MSG("set_foreground()", 1, self)
        GraphicsContextBase.set_foreground(self, fg)
        pen = self.GetPen()
        brush = wxBrush(self.get_wxcolour(), wxSOLID)
00429     def set_graylevel(self, frac):
        Set the foreground color.  fg can be a matlab format string, a
        html hex color string, an rgb unit tuple, or a float between 0
        and 1.  In the latter case, grayscale is used.
        DEBUG_MSG("set_graylevel()", 1, self)
        GraphicsContextBase.set_graylevel(self, frac)
        pen = self.GetPen()
        brush = wxBrush(self.get_wxcolour(), wxSOLID)

00443     def set_linewidth(self, w):
        Set the line width.
        DEBUG_MSG("set_linewidth()", 1, self)
        if w>0 and w<1: w = 1
        GraphicsContextBase.set_linewidth(self, w)
        pen = self.GetPen()
00454     def set_capstyle(self, cs):
        Set the capstyle as a string in ('butt', 'round', 'projecting')
        DEBUG_MSG("set_capstyle()", 1, self)
        GraphicsContextBase.set_capstyle(self, cs)
        pen = self.GetPen()
00464     def set_joinstyle(self, js):
        Set the join style to be one of ('miter', 'round', 'bevel')
        DEBUG_MSG("set_joinstyle()", 1, self)
        GraphicsContextBase.set_joinstyle(self, js)
        pen = self.GetPen()

00474     def set_linestyle(self, ls):
        Set the line style to be one of 
        GraphicsContextBase.set_linestyle(self, ls)
            self._style = GraphicsContextWx._dashd[ls]
        except KeyError:
            self._style = wxLONG_DASH # Style not used elsewhere...
        # On MS Windows platform, only line width of 1 allowed for dash lines
        if wxPlatform == '__WXMSW__':
        pen = self.GetPen()
00492     def get_wxcolour(self):
        """return a wxColour from RGB format"""
        r, g, b = self.get_rgb()
        r *= 255
        g *= 255
        b *= 255
        return wxColour(red=int(r), green=int(g), blue=int(b))

# Filetypes supported for saving files
              '.jpg': wxBITMAP_TYPE_JPEG,
              '.png': wxBITMAP_TYPE_PNG,
              '.pcx': wxBITMAP_TYPE_PCX,
              '.tif': wxBITMAP_TYPE_TIF,
              '.xpm': wxBITMAP_TYPE_XPM}
00509 class FigureWx(FigureBase, wxPanel):
    The figure is the main object -- it contains the Axes and Text,
    which in turn contain lines, patches, and more text.
    In the wxPython backend, it is derived from wxPanel, and (usually) lives
    inside a frame instantiated by a FigureManagerWx. The parent window probably
    implements a wxSizer to control the displayed control size - but we give a
    hint as to our preferred minimum size.
00519     def __init__(self, parent, id, figsize, dpi):
        Initialise a FigureWx instance.
        - Initialise the FigureBase and wxPanel parents.
        - Set event handlers for:
          EVT_SIZE  (Resize event)
          EVT_PAINT (Paint event)
        dpi = 72.0 / SCREENDPI * dpi
        FigureBase.__init__(self, figsize, dpi)
        DEBUG_MSG("__init__()", 1, self)

        # Set preferred window size hint - helps the sizer (if one is connected)
        w = int(math.ceil(self.bbox.x.interval()))
        h = int(math.ceil(self.bbox.y.interval()))
        wxPanel.__init__(self, parent, id, size=wxSize(w, h))
        # Create the drawing bitmap
        self.bitmap = wxEmptyBitmap(w, h)
        DEBUG_MSG("__init__() - bitmap w:%d h:%d" % (w,h), 2, self)
        # TODO: Add support for 'point' inspection and plot navigation.
        self._isRealized = False
        self._isConfigured = False
        self._printQueued = []
        self._gray = (0.7, 0.7, 0.7)
        self.drawable = None
        # Event handlers
        EVT_SIZE(self, self._onSize)
        EVT_PAINT(self, self._onPaint)
        EVT_RIGHT_DOWN(self, self._onRightButtonDown)
        EVT_RIGHT_UP(self, self._onRightButtonUp)
        EVT_MOUSEWHEEL(self, self._onMouseWheel)
        EVT_LEFT_DOWN(self, self._onLeftButtonDown)
        EVT_LEFT_UP(self, self._onLeftButtonUp)

00556     def add_axis(self, a):
        Add an instance of Axis to the figure. 
        FigureBase.add_axis(self, a)
        DEBUG_MSG("add_axis()", 1, self)
00565     def draw(self,drawable=None, *args, **kwargs):
        Render the figure using RendererWx instance drawable, or using a
        previously defined drawable if none is specified.
        DEBUG_MSG("draw()", 1, self)
        if drawable is None: drawable = self.drawable
        assert drawable != None, "Drawable must be defined"
        assert self._isRealized, "Figure instance must be realized before draw()"
        self.drawable = drawable

        # draw the figure bounding box, perhaps none for white figure
        # render the axes
        for a in self.axes:
        # render the figure text
        for t in self._text:
00587     def print_figure(self, filename, dpi=150):
        Render the figure to hardcopy using self.drawable as the
        renderer if necessary
        DEBUG_MSG("print_figure()", 1, self)
            # Save state information, and set save DPI
        origBounds   = self.bbox.get_bounds()
        origDPI      = self.dpi.get()
        origDrawable = self.drawable
        origBitmap   = self.bitmap
        dpi = 72.0/SCREENDPI*dpi
        width = int(self.figsize[0]*dpi)
        height = int(self.figsize[1]*dpi)
        self.bbox.set_bounds(0, 0, width, height)

            # Now create a bitmap and draw onto it
        DEBUG_MSG('print_figure(): bitmap w:%d h:%d' % (width, height), 2, self)
        # Following performs the same function as realize(), but without
        # setting GUI attributes - so GUI draw() will render correctly
        self.bitmap = wxEmptyBitmap(width, height)
        self.drawable = RendererWx(self.bitmap)
        for a in self.axes:
        for t in self._text:

        gc = self.drawable.new_gc()
        for a in self.axes:

        for t in self._text:
        # A nice pretty box around the pixmap
        self.drawable.draw_rectangle(gc, 'w', 0, 0, width, height)
        for a in self.axes:
        # render the figure text
        for t in self._text:
        # Now that we have rendered into the bitmap, save it
        # to the appropriate file type and clean up
            filetype = _FILETYPES[os.path.splitext(filename)[1]]
        except KeyError:
            filetype = wxBITMAP_TYPE_JPEG
            filename = filename + '.jpg'
        if not self.bitmap.SaveFile(filename, filetype):
            DEBUG_MSG('print_figure() file save error', 4, self)
            # note the error must be displayed here because trapping
            # the error on a call or print_figure may not work because
            # printing can be qued and called from realize
            error_msg_wx('Could not save figure to %s\n' % (filename))
            # successful draw, reset everything
        # Restore everything to normal
        self.bitmap = origBitmap
        self.drawable = origDrawable
        if self.drawable != None:
00660     def realize(self):
        This method will be called when the system is ready to draw,
        eg when a GUI window is realized

        DEBUG_MSG("realize()", 1, self)
        if not self._isRealized:
        # Print any queued figures
        # TODO: add print queue support to realize
        #for fname, dpi in self.printQued:
        #    self.print_figure(fname, dpi)
        #self.printQued = []
        self._isRealized = True
00677     def text(self, x, y, s, *args, **kwargs):
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text command for the meaning of the other arguments
        DEBUG_MSG("text()", 1, self)
        override = _process_text_args({}, *args, **kwargs)
        t = AxisTextWx( self.dpi, self.bbox, x=x, y=y, text=s,
                            transx = Transform(Bound1D(0,1), self.bbox.x),
                                    transy = Transform(Bound1D(0,1), self.bbox.y),
        return t

00691     def _update_renderer(self):
        Set a new wxRenderer instance for Axes and Text in this figure.
        DEBUG_MSG("update_renderer()", 1, self)
        self.drawable = RendererWx(self.bitmap)
        for a in self.axes:
        for t in self._text:

00702     def _onPaint(self, evt):
        Called when wxPaintEvt is generated

        DEBUG_MSG("_onPaint()", 1, self)
        if not self._isRealized:
        # Render to the bitmap
        # Must use wxPaintDC during paint event
        w = int(math.ceil(self.bbox.x.interval()))
        h = int(math.ceil(self.bbox.y.interval()))

        memDC = self.drawable.new_gc()
        drawDC.Blit(0, 0, w, h, memDC, 0, 0)
        #drawDC.DrawBitmap(self.bitmap, 0, 0)
        #self.bitmap.SaveFile('tmp.bmp', wxBITMAP_TYPE_BMP)
00727     def _onSize(self, evt):
        Called when wxEventSize is generated.
        In this application we attempt to resize to fit the window, so it
        is better to take the performance hit and redraw the whole window.

        DEBUG_MSG("_onSize()", 2, self)
        # Create a new, correctly sized bitmap
        self._width, self._height = self.GetClientSize()
        self.bitmap = wxEmptyBitmap(self._width, self._height)

        if self._width <= 1 or self._height <= 1: return # Empty figure
        # Scale the displayed image (but don't update self.figsize)
        if not self._isConfigured:
            self._orig_width, self._orig_height = self._width, self._height
            self._isConfigured = True

        self.bbox.set_bounds(0, 0, self._width, self._height)
        scalew = int(math.ceil(self._width / self._orig_width))
        scaleh = int(math.ceil(self._height / self._orig_height))
        for a in self.axes:
        for t in self._text:
        if self._isRealized:
            drawDC.DrawBitmap(self.bitmap, 0, 0)
    def _onRightButtonDown(self, evt):
        # TODO: implement right button down handler - show motion menu
    def _onRightButtonUp(self, evt):
        # TODO: implement right button up handler - remove motion menu?
00773     def _onLeftButtonDown(self, evt):
        """Start measuring on an axis."""
00777     def _onLeftButtonUp(self, evt):
        """End measuring on an axis."""
    def _onMouseWheel(self, evt):
        # TODO: implement mouse wheel handler

00785 class AxisTextWx(AxisTextBase):
    Handle storing and drawing of text in window or data co-ordinates.
    # wxPython only supports three standard font weights - I have mapped them
    # onto the same weights as used in the GTK back-end
    fontweights = {'normal'     : wxNORMAL,
                   'bold'       : wxBOLD,
                   'heavy'      : wxBOLD,
                   'light'      : wxLIGHT,
                   'ultrabold'  : wxBOLD,
                   'ultralight' : wxLIGHT }
    fontangles = { 'italic'  : wxITALIC,
                   'normal'  : wxNORMAL,
                   'oblique' : wxSLANT }
    # wxPython allows for portable font styles, choosing them appropriately
    # for the target platform. Map some standard font names to the portable
    # styles
    # QUESTION: Is it be wise to agree standard fontnames across all backends?
    fontnames = { 'Sans'       : wxSWISS,
                  'Roman'      : wxROMAN,
                  'Script'     : wxSCRIPT,
                  'Decorative' : wxDECORATIVE,
                  'Modern'     : wxMODERN,
                  'Courier'    : wxMODERN,
                  'courier'    : wxMODERN }
    def __init__(self, *args, **kwargs):
        # Ensure that default font argument is present. Otherwise, for some
        # reason, the font defaults to 'Times'
            fontname = kwargs['fontname']
            #print >>sys.stderr, "font: %s" % fontname
        except KeyError:
            kwargs['fontname'] = 'Sans'
        AxisTextBase.__init__(self, *args, **kwargs)
        DEBUG_MSG("__init__()", 1, self)
00825     def _compute_offsets(self):
        Return the (x,y) offsets to adjust for the alignment specifications.
        DEBUG_MSG("_compute_offsets()", 1, self)
        # Identical to GTK version
        if self._rotation=='vertical':
            w, h = self._height, self._width
            if self._horizontalalignment=='center': offsetx = -w/2
            elif self._horizontalalignment=='right': offsetx = -w
            else: offsetx = 0

            if self._verticalalignment=='center': offsety = -h/2
            elif self._verticalalignment=='top': offsety = 0
            else: offsety = -h
            h, w = self._height, self._width
            if self._horizontalalignment=='center': offsetx = -w/2
            elif self._horizontalalignment=='right': offsetx = -w
            else: offsetx = 0

            if self._verticalalignment=='center': offsety = h/2
            elif self._verticalalignment=='top': offsety = 0
            else: offsety = h

        return (offsetx, offsety)
00854     def _draw(self, drawable, *args, **kwargs):
        Render the text to the drawable (or the default if drawable is None)
        DEBUG_MSG("_draw()", 1, self)
        if drawable != None:
            self._drawable = drawable

        assert self._drawable != None, "Must define a drawable"
        if self._text=='':
        gc = drawable.new_gc()

        x = self.transx.positions(self._x)
        y = self.transy.positions(self._y)
        ox, oy = self._compute_offsets()
        xox = int(x+ox)
        yoy = int(y+oy)

        if self._clipOn:
        self._reset = 0

        if y+oy<0:
            print >>sys.stderr, 'Warning: text label "%s" is outside window extent' % self._text
        if x+ox<0:
            print >>sys.stderr, 'Warning: text label "%s" is outside window extent' % self._text
        if self._rotation == 'vertical':
            drawable.draw_rotated_text(gc, self._text, xox, yoy)            
            drawable.draw_text(gc, self._text, xox, yoy)
00891     def get_window_extent(self):
        Return the ink extent of the text as (left, bottom, width, height)
        DEBUG_MSG("get_data_extent()", 1, self)
        if self._reset or self.dpi.get() != self._lastDPI:
        x = self.transx.positions(self._x)
        y = self.transy.positions(self._y)
        w = self._width
        h = self._height
        ox, oy = self._compute_offsets()
        l, b = x + ox, y + oy - h
        if self._rotation == 'vertical':
            b = b + h
            w, h = h, w
        return Bound2D(l,b,w,h)
00911     def _set_font(self):
        Update any font information; this function will be called if
        font state (eg, fontsize, fontweight) has been changed
        DEBUG_MSG("_set_font()", 1, self)
        assert self._drawable != None, "Cannot _set_font() without a drawable"
        gc = self._drawable.get_gc()
        self._reset = False
        # Allow use of platform independent and dependent font names
            wxFontname = self.fontnames[self._fontname]
            wxFacename = '' # Empty => wxPython chooses based on wx_fontname
        except KeyError:
            wxFontname = wxSWISS
            wxFacename = self._fontname
        # Font colour is determined by the active wxPen
        # TODO: It may be wise to cache font information
        scale = int(math.ceil(self.dpi.get() / SCREENDPI))
        DEBUG_MSG('_set_font(): font:%s size:%d text:%s' % (self._fontname, self._fontsize*scale, self._text), 1, self) 
        self._font = wxFont(self._fontsize * scale,             # Size
                            wxFontname,                         # 'Generic' name
                            self.fontangles[self._fontangle],   # Angle
                            self.fontweights[self._fontweight], # Weight
                            False,                              # Underline
                            wxFacename)                         # Platform font name
        # Now work out the size of our text on the device context

        self._width, self._height = gc.GetTextExtent(self._text)

# The following functions and classes are for matlab compatibility
# mode (matplotlib.matlab) and implement figure managers, etc...

00952 class ShowOn:
    Manage whether frames are shown or not.
    This is a helper class to show() and draw_if_interactive()
    show = 0

    def set(self, on):
        DEBUG_MSG("set()", 1, self)
        # show all the fig wins
        if not ShowOn.show:
            for figwin in Gcf.get_all_fig_managers():
        ShowOn.show = on
    def get(self):
        DEBUG_MSG("get()", 1, self)
        return ShowOn.show

    def realize_windows(self):
        DEBUG_MSG("realize()", 1, self)

def draw_if_interactive():
    This should be overriden in a windowing environment if drawing
    should be done in interactive python mode
    if ShowOn().get():
        current_fig = Gcf().get_current_figwin().figure

def show():
    Current implementation assumes that matplotlib is executed in a PyCrust
    shell. It appears to be possible to execute wxPython applications from
    within a PyCrust without having to ensure that wxPython has been created
    in a secondary thread (e.g. SciPy gui_thread).
    Unfortunately, gui_thread seems to introduce a number of further
    dependencies on SciPy modules, which I do not wish to introduce
    into the backend at this point. If there is a need I will look
    into this in a later release.

def new_figure_manager(num, figsize, dpi):
    Create a new figure manager instance
    frame = FigureFrameWx(figsize, dpi, num)
    figmgr = frame.get_figure_manager()
    if ShowOn().get():
    return figmgr

class FigureFrameWx(wxFrame):
    def __init__(self, figsize, dpi, num):
            # On non-Windows platform, explicitly set the position - fix
        # positioning bug on some Linux platforms
        if wxPlatform == '__WXMSW__':
            pos = wxDefaultPosition
            pos = wxPoint(20,20)
        wxFrame.__init__(self, parent=None, id=-1, pos=pos,
                          title="Figure %d" % num)
        DEBUG_MSG("__init__()", 1, self)
        self.fig = FigureWx(self, -1, figsize, dpi)
        self.sizer = wxBoxSizer(wxVERTICAL)
        self.sizer.Add(self.fig, 1, wxTOP | wxLEFT | wxEXPAND)
        # By adding toolbar in sizer, we are able to put it at the bottom
        # of the frame - so appearance is closer to GTK version
        self.toolbar = NavigationToolbarWx(self.fig, True)
        # On Windows platform, default window size is incorrect, so set
        # toolbar width to figure width.
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.fig.GetSizeTuple()
        self.toolbar.SetSize(wxSize(fw, th))
        self.sizer.Add(self.toolbar, 0, wxLEFT | wxEXPAND)
        # By adding toolbar in sizer, we are able to put it at the bottom
        # of the frame - so appearance is closer to GTK version
        self.figmgr = FigureManagerWx(self.fig, num, self)
        # Event handlers
        EVT_CLOSE(self, self._onClose)
    def get_figure_manager(self):
        DEBUG_MSG("get_figure_manager()", 1, self)
        return self.figmgr
    def _onClose(self, evt):
    def GetToolBar(self):
        """Override wxFrame::GetToolBar as we don't have managed toolbar"""
        return self.toolbar
01059 class FigureManagerWx(FigureManagerBase):
    This class manages the axes and subplots within a single figure.
    It is instantiated by GcfWx whenever a new figure is created. GcfWx is
    responsible for managing multiple instances of FigureManagerWx.
    NB: FigureManagerBase is found in _matlab_helpers
    def __init__(self, figure, num, frame):
        DEBUG_MSG("__init__()", 1, self)
        FigureManagerBase.__init__(self, figure, num)
        self.frame = frame
        self.tb = frame.GetToolBar()
    def add_subplot(self, *args, **kwargs):
        DEBUG_MSG("add_subplot()", 1, self)
        a = FigureManagerBase.add_subplot(self, *args, **kwargs)
        return a
    def add_axes(self, rect, axisbg):
        DEBUG_MSG("add_axes()", 1, self)
        a = FigureManagerBase.add_axes(self, rect, axisbg)
        return a
    def set_current_axes(self, a):
        DEBUG_MSG("set_current_axes()", 1, self)
        if a not in self.axes.values():
            error_msg_wx('Axes is not in current figure')
        FigureManagerBase.set_current_axes(self, a)

# Identifiers for toolbar controls - images_wx contains bitmaps for the images
# used in the controls. wxWindows does not provide any stock images, so I've
# 'stolen' those from GTK2, and transformed them into the appropriate format.
#import images_wx

_NTB_AXISMENU        = wxNewId()
_NTB_X_PAN_LEFT      = wxNewId()
_NTB_X_PAN_RIGHT     = wxNewId()
_NTB_X_ZOOMIN        = wxNewId()
_NTB_X_ZOOMOUT       = wxNewId()
_NTB_Y_PAN_UP        = wxNewId()
_NTB_Y_PAN_DOWN      = wxNewId()
_NTB_Y_ZOOMIN        = wxNewId()
_NTB_Y_ZOOMOUT       = wxNewId()
_NTB_SAVE            = wxNewId()
_NTB_CLOSE           = wxNewId()

def _load_bitmap(filename):
    Load a bitmap file from the backends/images subdirectory in which the
    matplotlib library is installed. The filename parameter should not
    contain any path information as this is determined automatically.
    Bitmaps should be in XPM format, and of size 16x16 (unless you change
    the code!). I have converted the stock GTK2 16x16 icons to XPM format.
    Returns a wxBitmap object
    basedir = get_data_path()

    bmpFilename = os.path.normpath(os.path.join(basedir, filename))
    if not os.path.exists(bmpFilename):
        print >>sys.stderr, 'Could not find bitmap file; dying', bmpFilename
    bmp = wxBitmap(bmpFilename, wxBITMAP_TYPE_XPM)
    return  bmp

01130 class MenuButtonWx(wxButton):
    wxPython does not permit a menu to be incorporated directly into a toolbar.
    This class simulates the effect by associating a pop-up menu with a button
    in the toolbar, and managing this as though it were a menu.
    def __init__(self, parent):
        wxButton.__init__(self, parent, _NTB_AXISMENU_BUTTON, "Axes:        ",
        self._toolbar = parent
        self._menu = wxMenu()
        self._axisId = []
        # First two menu items never change...
        self._allId = wxNewId()
        self._invertId = wxNewId()
        self._menu.Append(self._allId, "All", "Select all axes", False)
        self._menu.Append(self._invertId, "Invert", "Invert axes selected", False)
        EVT_BUTTON(self, _NTB_AXISMENU_BUTTON, self._onMenuButton)
        EVT_MENU(self, self._allId, self._handleSelectAllAxes)
        EVT_MENU(self, self._invertId, self._handleInvertAxesSelected)
    def Destroy(self):
01156     def _onMenuButton(self, evt):
        """Handle menu button pressed."""
        x, y = self.GetPositionTuple()
        w, h = self.GetSizeTuple()
        self.PopupMenuXY(self._menu, x, y+h-4)
            # When menu returned, indicate selection in button

01164     def _handleSelectAllAxes(self, evt):
        """Called when the 'select all axes' menu item is selected."""
        if len(self._axisId) == 0:
        for i in range(len(self._axisId)):
            self._menu.Check(self._axisId[i], True)
01173     def _handleInvertAxesSelected(self, evt):
        """Called when the invert all menu item is selected"""
        if len(self._axisId) == 0: return
        for i in range(len(self._axisId)):
            if self._menu.IsChecked(self._axisId[i]):
                self._menu.Check(self._axisId[i], False)
                self._menu.Check(self._axisId[i], True)
01184     def _onMenuItemSelected(self, evt):
        """Called whenever one of the specific axis menu items is selected"""
        current = self._menu.IsChecked(evt.GetId())
        if current:
            new = False
            new = True
        self._menu.Check(evt.GetId(), new)
01195     def updateAxes(self, maxAxis):
        """Ensures that there are entries for max_axis axes in the menu
        (selected by default)."""
        if maxAxis > len(self._axisId):
            for i in range(len(self._axisId) + 1, maxAxis + 1, 1):
                menuId = wxNewId()
                self._menu.Append(menuId, "Axis %d" % i, "Select axis %d" % i, True)
                self._menu.Check(menuId, True)
                EVT_MENU(self, menuId, self._onMenuItemSelected)
01207     def getActiveAxes(self):
        """Return a list of the selected axes."""
        active = []
        for i in range(len(self._axisId)):
            if self._menu.IsChecked(self._axisId[i]):
        return active
01215     def updateButtonText(self, lst):
        """Update the list of selected axes in the menu button"""
        axis_txt = ''
        for e in lst:
            axis_txt += '%d,' % (e+1)
        # remove trailing ',' and add to button string
        self.SetLabel("Axes: %s" % axis_txt[:-1])

class NavigationToolbarWx(wxToolBar):
    def __init__(self, figure, can_kill=False):
        figure is the Figure instance that the toolboar controls

        win, if not None, is the wxWindow the Figure is embedded in
        wxToolBar.__init__(self, figure.GetParent(), -1)
        DEBUG_MSG("__init__()", 1, self)
        self.figure = figure
        self._lastControl = None
        self._mouseOnButton = None
        self._parent = figure.GetParent()
        self._NTB_BUTTON_HANDLER = {
            _NTB_X_PAN_LEFT  : self.panx,
            _NTB_X_PAN_RIGHT : self.panx,
            _NTB_X_ZOOMIN    : self.zoomx,
            _NTB_X_ZOOMOUT   : self.zoomy,
            _NTB_Y_PAN_UP    : self.pany,
            _NTB_Y_PAN_DOWN  : self.pany,
            _NTB_Y_ZOOMIN    : self.zoomy,
            _NTB_Y_ZOOMOUT   : self.zoomy }
    def _create_menu(self):
        Creates the 'menu' - implemented as a button which opens a
        pop-up menu since wxPython does not allow a menu as a control
        DEBUG_MSG("_create_menu()", 1, self)
        self._menu = MenuButtonWx(self)
    def _create_controls(self, can_kill):
        Creates the button controls, and links them to event handlers
        DEBUG_MSG("_create_controls()", 1, self)
        # Need the following line as Windows toolbars default to 15x16
        self.AddSimpleTool(_NTB_X_PAN_LEFT, _load_bitmap('stock_left.xpm'),
                           'Left', 'Scroll left')
        self.AddSimpleTool(_NTB_X_PAN_RIGHT, _load_bitmap('stock_right.xpm'),
                           'Right', 'Scroll right')
        self.AddSimpleTool(_NTB_X_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'),
                           'Zoom in', 'Increase X axis magnification')
        self.AddSimpleTool(_NTB_X_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'),
                           'Zoom out', 'Decrease X axis magnification')
                           'Up', 'Scroll up')
        self.AddSimpleTool(_NTB_Y_PAN_DOWN, _load_bitmap('stock_down.xpm'),
                           'Down', 'Scroll down')
        self.AddSimpleTool(_NTB_Y_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'),
                           'Zoom in', 'Increase Y axis magnification')
        self.AddSimpleTool(_NTB_Y_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'),
                           'Zoom out', 'Decrease Y axis magnification')
        self.AddSimpleTool(_NTB_SAVE, _load_bitmap('stock_save_as.xpm'),
                           'Save', 'Save plot contents as images')
        if can_kill:
            self.AddSimpleTool(_NTB_CLOSE, _load_bitmap('stock_close.xpm'),
                               'Close', 'Close plot window')        # Events:
        EVT_TOOL(self, _NTB_X_PAN_LEFT, self._onLeftScroll)
        EVT_TOOL(self, _NTB_X_PAN_RIGHT, self._onRightScroll)
        EVT_TOOL(self, _NTB_X_ZOOMIN, self._onXZoomIn)
        EVT_TOOL(self, _NTB_X_ZOOMOUT, self._onXZoomOut)
        EVT_TOOL(self, _NTB_Y_PAN_UP, self._onUpScroll)
        EVT_TOOL(self, _NTB_Y_PAN_DOWN, self._onDownScroll)
        EVT_TOOL(self, _NTB_Y_ZOOMIN, self._onYZoomIn)
        EVT_TOOL(self, _NTB_Y_ZOOMOUT, self._onYZoomOut)
        EVT_TOOL(self, _NTB_SAVE, self._onSave)
        EVT_TOOL_ENTER(self, self.GetId(), self._onEnterTool)
        if can_kill:
            EVT_TOOL(self, _NTB_CLOSE, self._onClose)
        EVT_MOUSEWHEEL(self, self._onMouseWheel)
    def set_active(self, ind):
        ind is a list of index numbers for the axes which are to be made active
        DEBUG_MSG("set_active()", 1, self)
        self._ind = ind
        if ind != None:
            self._active = [ self._axes[i] for i in self._ind ]
            self._active = []
        # Now update button text wit active axes
    def get_last_control(self):
        """Returns the identity of the last toolbar button pressed."""
        return self._lastControl
    def panx(self, direction):
        DEBUG_MSG("panx()", 1, self)
        for a in self._active:
    def pany(self, direction):
        DEBUG_MSG("pany()", 1, self)
        for a in self._active:
    def zoomx(self, in_out):
        DEBUG_MSG("zoomx()", 1, self)
        for a in self._active:
    def zoomy(self, in_out):
        DEBUG_MSG("zoomy()", 1, self)
        for a in self._active:
    def update(self):
        Update the toolbar menu - called when (e.g.) a new subplot or axes are added
        DEBUG_MSG("update()", 1, self)
        self._axes = self.figure.get_axes()
    def _do_nothing(self, d):
        """A NULL event handler - does nothing whatsoever"""
    # Local event handlers - mainly supply parameters to pan/scroll functions
    def _onEnterTool(self, evt):
        toolId = evt.GetSelection()
            self.button_fn = self._NTB_BUTTON_HANDLER[toolId]
        except KeyError:
            self.button_fn = self._do_nothing
    def _onLeftScroll(self, evt):
    def _onRightScroll(self, evt):
    def _onXZoomIn(self, evt):
    def _onXZoomOut(self, evt):
    def _onUpScroll(self, evt):

    def _onDownScroll(self, evt):
    def _onYZoomIn(self, evt):
    def _onYZoomOut(self, evt):

    def _onMouseEnterButton(self, button):
        self._mouseOnButton = button
    def _onMouseLeaveButton(self, button):
        if self._mouseOnButton == button:
            self._mouseOnButton = None
    def _onMouseWheel(self, evt):
        if evt.GetWheelRotation() > 0:
            direction = 1
            direction = -1
    def _onRedraw(self, evt):
        for a in self.figure.axes:

    def _onSave(self, evt):
        # Fetch the required filename and file type.
        filetypes = "JPEG (*.jpg)|*.jpg|"   \
                    "BMP (*.bmp)|*.bmp|"    \
                    "PCX (*.pcx)|*.pcx|"     \
                    "PNG (*.png)|*.png|"    \
                    "TIFF (*.tif)|*.tif|" \
                    "XPM (*.xpm)|*.xpm|" 
        dlg = wxFileDialog(self._parent, "Save to file", "", "", filetypes,
        if dlg.ShowModal() == wxID_OK:
            dirname  = dlg.GetDirectory()
            filename = dlg.GetFilename()
            DEBUG_MSG('Save file dir:%s name:%s' % (dirname, filename), 3, self)
        self.figure.print_figure(os.path.join(dirname, filename))
    def _onClose(self, evt):

01440 class StatusBarWx(wxStatusBar):
    A status bar is added to _FigureFrame to allow measurements and the
    previously selected scroll function to be displayed as a user
    def __init__(self, parent):
        wxStatusBar.__init__(self, parent, -1)
        self.SetStatusText("Function: None", 1)
        self.SetStatusText("Measurement: None", 2)
    def set_function(self, string):
        self.SetStatusText("Function: %s" % string, 1)
    def set_measurement(self, string):
        self.SetStatusText("Measurement: %s" % string, 2)

# Now just provide the standard names that backend.__init__ is expecting

AxisText = AxisTextWx
Figure = FigureWx
Toolbar = NavigationToolbarWx
FigureManager = FigureManagerWx
error_msg = error_msg_wx

Generated by  Doxygen 1.6.0   Back to index