3
ƽh@                @   s  d Z ddlmZmZ ddlmZmZ ddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlmZ ddlZddlZddlmZmZmZmZmZmZmZmZm Z m!Z! ddl"m#Z# ddl$m%Z% dd	l&m'Z' dd
l(m)Z) ddl*m+Z+ ej,e-Z.ddddddddddddddZ/ddddddddddddddZ0dTddZ1dd Z2G dd  d Z3G d!d" d"Z4G d#d$ d$Z5G d%d& d&Z6G d'd( d(e6Z7G d)d* d*e6Z8G d+d, d,e6Z9G d-d. d.e6Z:G d/d0 d0eZ;G d1d2 d2e:Z<G d3d4 d4e6Z=G d5d6 d6e:Z>dUd7d8Z?d9d: Z@df fd;d<ZAG d=d> d>ZBdVd?d@ZCdWdAdBZDG dCdD dDeEZFG dEdF dFZGejHZHG dGdH dHeIeZJG dIdJ dJZKG dKdL dLZLejMdMG dNdO dOZNG dPdQ dQZOG dRdS dSeOZPdS )Xa  
Abstract base classes define the primitives that renderers and
graphics contexts must implement to serve as a Matplotlib backend.

`RendererBase`
    An abstract base class to handle drawing/rendering operations.

`FigureCanvasBase`
    The abstraction layer that separates the `.Figure` from the backend
    specific details like a user interface drawing area.

`GraphicsContextBase`
    An abstract base class that provides color, line styles, etc.

`Event`
    The base class for all of the Matplotlib event handling.  Derived classes
    such as `KeyEvent` and `MouseEvent` store the meta data like keys and
    buttons pressed, x and y locations in pixel and `~.axes.Axes` coordinates.

`ShowBase`
    The base class for the ``Show`` class of each interactive backend; the
    'show' callable is then set to ``Show.__call__``.

`ToolContainerBase`
    The base class for the Toolbar class of each interactive backend.
    )contextmanagersuppress)EnumIntEnumN)WeakKeyDictionary)
backend_toolscbookcolorstextpath
tight_bbox
transformswidgetsget_backendis_interactivercParams)Gcf)ToolManager)Affine2D)Path)_setattr_cmzEncapsulated Postscriptz Joint Photographic Experts GroupzPortable Document FormatzPGF code for LaTeXzPortable Network GraphicsZ
PostscriptzRaw RGBA bitmapzScalable Vector GraphicszTagged Image File Format)epsZjpgZjpegZpdfZpgfZpngZpsrawZrgbasvgZsvgzZtifZtiffzmatplotlib.backends.backend_pszmatplotlib.backends.backend_aggzmatplotlib.backends.backend_pdfzmatplotlib.backends.backend_pgfzmatplotlib.backends.backend_svgc             C   s    |dkrd}|t | < |t| < dS )a$  
    Register a backend for saving to a given file format.

    Parameters
    ----------
    format : str
        File extension
    backend : module string or canvas class
        Backend for handling file output
    description : str, default: ""
        Description of the file type.
    N )_default_backends_default_filetypes)formatbackenddescription r   >/tmp/pip-build-7iwl8md4/matplotlib/matplotlib/backend_bases.pyregister_backendX   s    r!   c             C   s6   | t krdS t |  }t|tr2tj|j}|t | < |S )zv
    Return the registered default canvas for given file format.
    Handles deferred import of required backend.
    N)r   
isinstancestr	importlibimport_moduleFigureCanvas)r   Zbackend_classr   r   r    get_registered_canvas_classk   s    
r'   c                   s(  e Zd ZdZ fddZdEddZdd ZdFd	d
ZdGddZdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd ZdHddZdd  Zd!d" Zejd#d$dId&d'ZdJd)d*Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z!d?d@ Z"dAdB Z#dCdD Z$  Z%S )KRendererBasea'  
    An abstract base class to handle drawing/rendering operations.

    The following methods must be implemented in the backend for full
    functionality (though just implementing :meth:`draw_path` alone would
    give a highly capable backend):

    * :meth:`draw_path`
    * :meth:`draw_image`
    * :meth:`draw_gouraud_triangle`

    The following methods *should* be implemented in the backend for
    optimization reasons:

    * :meth:`draw_text`
    * :meth:`draw_markers`
    * :meth:`draw_path_collection`
    * :meth:`draw_quad_mesh`
    c                s   t  j  d | _tj | _d S )N)super__init___texmanagerr
   Z
TextToPath
_text2path)self)	__class__r   r    r*      s    
zRendererBase.__init__Nc             C   s   dS )zz
        Open a grouping element with label *s* and *gid* (if set) as id.

        Only used by the SVG renderer.
        Nr   )r-   sgidr   r   r    
open_group   s    zRendererBase.open_groupc             C   s   dS )zb
        Close a grouping element with label *s*.

        Only used by the SVG renderer.
        Nr   )r-   r/   r   r   r    close_group   s    zRendererBase.close_groupc             C   s   t dS )z?Draw a `~.path.Path` instance using the given affine transform.N)NotImplementedError)r-   gcpath	transformrgbFacer   r   r    	draw_path   s    zRendererBase.draw_pathc             C   sX   xR|j |ddD ]@\}}t|r|dd \}	}
| j|||tj j|	|
 | qW dS )a3  
        Draw a marker at each of the vertices in path.

        This includes all vertices, including control points on curves.
        To avoid that behavior, those vertices should be removed before
        calling this function.

        This provides a fallback implementation of draw_markers that
        makes multiple calls to :meth:`draw_path`.  Some backends may
        want to override this method in order to draw the marker only
        once and reuse it multiple times.

        Parameters
        ----------
        gc : `.GraphicsContextBase`
            The graphics context.

        marker_trans : `matplotlib.transforms.Transform`
            An affine transform applied to the marker.

        trans : `matplotlib.transforms.Transform`
            An affine transform applied to the path.

        F)Zsimplify   N)Ziter_segmentslenr8   r   r   	translate)r-   r4   Zmarker_pathZmarker_transr5   transr7   Zverticescodesxyr   r   r    draw_markers   s    zRendererBase.draw_markersc             C   s   | j |||}xt| j|||t||||||	|
|||D ]J\}}}}}|\}}|dks\|dkrp|j }|j|| | j|||| q6W dS )a  
        Draw a collection of paths selecting drawing properties from
        the lists *facecolors*, *edgecolors*, *linewidths*,
        *linestyles* and *antialiaseds*. *offsets* is a list of
        offsets to apply to each of the paths.  The offsets in
        *offsets* are first transformed by *offsetTrans* before being
        applied.

        *offset_position* may be either "screen" or "data" depending on the
        space that the offsets are in; "data" is deprecated.

        This provides a fallback implementation of
        :meth:`draw_path_collection` that makes multiple calls to
        :meth:`draw_path`.  Some backends may want to override this in
        order to render each set of path data only once, and then
        reference that path multiple times with the different offsets,
        colors, styles etc.  The generator methods
        :meth:`_iter_collection_raw_paths` and
        :meth:`_iter_collection` are provided to help with (and
        standardize) the implementation across backends.  It is highly
        recommended to use those generators, so that changes to the
        behavior of :meth:`draw_path_collection` can be made globally.
        r   N)_iter_collection_raw_paths_iter_collectionlistfrozenr<   r8   )r-   r4   master_transformpathsall_transformsoffsetsoffsetTrans
facecolors
edgecolors
linewidths
linestylesantialiasedsurlsoffset_positionpath_idsxoyopath_idgc0r7   r5   r6   r   r   r    draw_path_collection   s    
z!RendererBase.draw_path_collectionc             C   s^   ddl m} |j|||}|
dkr&|}
tj|j gt}| j|||g ||||
|g |	gdgdS )z
        Fallback implementation of :meth:`draw_quad_mesh` that generates paths
        and then calls :meth:`draw_path_collection`.
        r   )QuadMeshNZscreen)Zmatplotlib.collectionsrX   Zconvert_mesh_to_pathsnparrayget_linewidthfloatrW   )r-   r4   rF   Z	meshWidthZ
meshHeightZcoordinatesrI   rJ   rK   ZantialiasedrL   rX   rG   rM   r   r   r    draw_quad_mesh   s    
zRendererBase.draw_quad_meshc             C   s   t dS )a  
        Draw a Gouraud-shaded triangle.

        Parameters
        ----------
        gc : `.GraphicsContextBase`
            The graphics context.

        points : array-like, shape=(3, 2)
            Array of (x, y) points for the triangle.

        colors : array-like, shape=(3, 4)
            RGBA colors for each point of the triangle.

        transform : `matplotlib.transforms.Transform`
            An affine transform to apply to the points.

        N)r3   )r-   r4   pointsr	   r6   r   r   r    draw_gouraud_triangle  s    z"RendererBase.draw_gouraud_trianglec             C   s4   |j  }x&t||D ]\}}| j|||| qW dS )a  
        Draw a series of Gouraud triangles.

        Parameters
        ----------
        points : array-like, shape=(N, 3, 2)
            Array of *N* (x, y) points for the triangles.

        colors : array-like, shape=(N, 3, 4)
            Array of *N* RGBA colors for each point of the triangles.

        transform : `matplotlib.transforms.Transform`
            An affine transform to apply to the points.
        N)rE   zipr_   )r-   r4   Ztriangles_arrayZcolors_arrayr6   Ztricolr   r   r    draw_gouraud_triangles  s    z#RendererBase.draw_gouraud_trianglesc       
      c   sr   t |}t |}t||}|dkr&dS tj }x>t|D ]2}|||  }	|r\t|||  }|	|| fV  q8W dS )a  
        Helper method (along with :meth:`_iter_collection`) to implement
        :meth:`draw_path_collection` in a space-efficient manner.

        This method yields all of the base path/transform
        combinations, given a master transform, a list of paths and
        list of transforms.

        The arguments should be exactly what is passed in to
        :meth:`draw_path_collection`.

        The backend should take each yielded path and transform and
        create an object that can be referenced (reused) later.
        r   N)r;   maxr   ZIdentityTransformranger   )
r-   rF   rG   rH   NpathsNtransformsNr6   ir5   r   r   r    rB   1  s    
z'RendererBase._iter_collection_raw_pathsc       	      C   s`   t |}|dks0t |t |  ko*dkn  r4dS t|t |}t|t |}|| d | S )a|  
        Compute how many times each raw path object returned by
        _iter_collection_raw_paths would be used when calling
        _iter_collection. This is intended for the backend to decide
        on the tradeoff between using the paths in-line and storing
        them once and reusing. Rounds up in case the number of uses
        is not the same for every path.
        r      )r;   rc   )	r-   rG   rH   rI   rK   rL   re   Z	Npath_idsrg   r   r   r    _iter_collection_uses_per_pathO  s    
(z+RendererBase._iter_collection_uses_per_pathc       #      c   sz  t |}t |}t |}t||}t |}t |}t |	}t |
}t |}t |}|dkrhtjddd |dkrx|dks|dkrdS |r|j|}| j }|j| |dkrd}|dkr|jd d
\}}xt|D ]}|||  }|rZ|||  \}}|dkrZ|r$t	|||  | }n|}|j||fdg\\}}\} }!| |  }|!|  }t
j|ont
j|stq|r|||  }|r|r|j|	||   |r|j|
||    |||  }"t |"dkr|"d	 dkr|jd n
|j|" n
|j|" |dk	r0t |dkr0|d	 dkr0d}|j|||   |rZ|j|||   |||||fV  qW |j  dS )a  
        Helper method (along with :meth:`_iter_collection_raw_paths`) to
        implement :meth:`draw_path_collection` in a space-efficient manner.

        This method yields all of the path, offset and graphics
        context combinations to draw the path collection.  The caller
        should already have looped over the results of
        :meth:`_iter_collection_raw_paths` to draw this collection.

        The arguments should be the same as that passed into
        :meth:`draw_path_collection`, with the exception of
        *path_ids*, which is a list of arbitrary objects that the
        backend will use to reference one of the paths created in the
        :meth:`_iter_collection_raw_paths` stage.

        Each yielded result is of the form::

           xo, yo, path_id, gc, rgbFace

        where *xo*, *yo* is an offset; *path_id* is one of the elements of
        *path_ids*; *gc* is a graphics context and *rgbFace* is a color to
        use for filling the path.
        dataz3.3zaSupport for offset_position='data' is deprecated since %(since)s and will be removed %(removal)s.)messager   Ng              )r   r   )r   r   )r;   rc   r   warn_deprecatedr6   new_gccopy_propertiesset_linewidthrd   r   rY   isfinite
set_dashesset_foregroundset_antialiasedset_urlrestore)#r-   r4   rF   rH   rR   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rf   re   ZNoffsetsrg   ZNfacecolorsZNedgecolorsZNlinewidthsZNlinestylesZNaaZNurlsZtoffsetsrV   r7   rS   rT   rh   rU   r6   ZxpZypfgr   r   r    rC   `  sx    








zRendererBase._iter_collectionc             C   s   dS )z
        Get the factor by which to magnify images passed to :meth:`draw_image`.
        Allows a backend to have images at a different resolution to other
        artists.
        g      ?r   )r-   r   r   r    get_image_magnification  s    z$RendererBase.get_image_magnificationc             C   s   t dS )a  
        Draw an RGBA image.

        Parameters
        ----------
        gc : `.GraphicsContextBase`
            A graphics context with clipping information.

        x : scalar
            The distance in physical units (i.e., dots or pixels) from the left
            hand side of the canvas.

        y : scalar
            The distance in physical units (i.e., dots or pixels) from the
            bottom side of the canvas.

        im : array-like, shape=(N, M, 4), dtype=np.uint8
            An array of RGBA pixels.

        transform : `matplotlib.transforms.Affine2DBase`
            If and only if the concrete backend is written such that
            :meth:`option_scale_image` returns ``True``, an affine
            transformation (i.e., an `.Affine2DBase`) *may* be passed to
            :meth:`draw_image`.  The translation vector of the transformation
            is given in physical units (i.e., dots or pixels). Note that
            the transformation does not override *x* and *y*, and has to be
            applied *before* translating the result by *x* and *y* (this can
            be accomplished by adding *x* and *y* to the translation vector
            defined by *transform*).
        N)r3   )r-   r4   r?   r@   Zimr6   r   r   r    
draw_image  s    zRendererBase.draw_imagec             C   s   dS )a*  
        Return whether image composition by Matplotlib should be skipped.

        Raster backends should usually return False (letting the C-level
        rasterizer take care of image composition); vector backends should
        usually return ``not rcParams["image.composite_image"]``.
        Fr   )r-   r   r   r    option_image_nocomposite  s    z%RendererBase.option_image_nocompositec             C   s   dS )z
        Return whether arbitrary affine transformations in :meth:`draw_image`
        are supported (True for most vector backends).
        Fr   )r-   r   r   r    option_scale_image  s    zRendererBase.option_scale_imagez3.3ismathTeX!c	       	   	   C   s   | j ||||||dd dS )z	
        TeX)r~   N)_draw_text_as_path)	r-   r4   r?   r@   r/   propangler~   mtextr   r   r    draw_tex  s    zRendererBase.draw_texFc	       	      C   s   | j ||||||| dS )a  
        Draw the text instance.

        Parameters
        ----------
        gc : `.GraphicsContextBase`
            The graphics context.
        x : float
            The x location of the text in display coords.
        y : float
            The y location of the text baseline in display coords.
        s : str
            The text string.
        prop : `matplotlib.font_manager.FontProperties`
            The font properties.
        angle : float
            The rotation angle in degrees anti-clockwise.
        mtext : `matplotlib.text.Text`
            The original text object to be rendered.

        Notes
        -----
        **Note for backend implementers:**

        When you are trying to determine if you have gotten your bounding box
        right (which is what enables the text layout/alignment to work
        properly), it helps to change the line in text.py::

            if 0: bbox_artist(self, renderer)

        to if 1, and then the actual bounding box will be plotted along with
        your text.
        N)r   )	r-   r4   r?   r@   r/   r   r   r~   r   r   r   r    	draw_text  s    #zRendererBase.draw_textc             C   s   | j }| j|j }|j|||d\}	}
t|	|
}tj|}| j rv| j \}}t	 j
||j j|j||| }n t	 j
||j j|j||}||fS )aO  
        Return the text path and transform.

        Parameters
        ----------
        prop : `matplotlib.font_manager.FontProperties`
            The font property.
        s : str
            The text to be converted.
        ismath : bool or "TeX"
            If True, use mathtext parser. If "TeX", use *usetex* mode.
        )r~   )r,   points_to_pixelsget_size_in_pointsZget_text_pathr   rY   Zdeg2radflipyget_canvas_width_heightr   scaleZ
FONT_SCALErotater<   )r-   r?   r@   r/   r   r   r~   Z	text2pathfontsizeZvertsr>   r5   widthheightr6   r   r   r    _get_text_path_transform)  s     

z%RendererBase._get_text_path_transformc             C   s@   | j ||||||\}}	|j }
|jd | j|||	|
d dS )a  
        Draw the text by converting them to paths using textpath module.

        Parameters
        ----------
        prop : `matplotlib.font_manager.FontProperties`
            The font property.
        s : str
            The text to be converted.
        usetex : bool
            Whether to use usetex mode.
        ismath : bool or "TeX"
            If True, use mathtext parser. If "TeX", use *usetex* mode.
        g        )r7   N)r   get_rgbrr   r8   )r-   r4   r?   r@   r/   r   r   r~   r5   r6   colorr   r   r    r   K  s
    
zRendererBase._draw_text_as_pathc             C   s   |dkr:| j j }|j }|j||| d\}}}|||fS | jd}	|rf| j jj||	|}
|
dd S | j j }| j j|}|j }|j	||	 |j
|d|d |j \}}|j }|d }|d }|d }|||fS )	z
        Get the width, height, and descent (offset from the bottom
        to the baseline), in display coords, of the string *s* with
        `.FontProperties` *prop*.
        r   )rendererH   r   rn   g        )flagsg      P@)r,   get_texmanagerr   get_text_width_height_descentr   Zmathtext_parserparseZ_get_hinting_flagZ	_get_fontZset_sizeZset_textget_width_heightZget_descent)r-   r/   r   r~   Z
texmanagerr   whddpiZdimsr   fontsizer   r   r    r   `  s*    



z*RendererBase.get_text_width_height_descentc             C   s   dS )z
        Return whether y values increase from top to bottom.

        Note that this only affects drawing of texts and images.
        Tr   )r-   r   r   r    r     s    zRendererBase.flipyc             C   s   dS )z5Return the canvas width and height in display coords.ri   )ri   ri   r   )r-   r   r   r    r     s    z$RendererBase.get_canvas_width_heightc             C   s$   | j dkrddlm} | | _ | j S )z"Return the `.TexManager` instance.Nr   )
TexManager)r+   Zmatplotlib.texmanagerr   )r-   r   r   r   r    r     s    
zRendererBase.get_texmanagerc             C   s   t  S )z/Return an instance of a `.GraphicsContextBase`.)GraphicsContextBase)r-   r   r   r    rp     s    zRendererBase.new_gcc             C   s   |S )a  
        Convert points to display units.

        You need to override this function (unless your backend
        doesn't have a dpi, e.g., postscript or svg).  Some imaging
        systems assume some value for pixels per inch::

            points to pixels = points * pixels_per_inch/72 * dpi/72

        Parameters
        ----------
        points : float or array-like
            a float or a numpy array of float

        Returns
        -------
        Points converted to pixels
        r   )r-   r^   r   r   r    r     s    zRendererBase.points_to_pixelsc             C   s   dS )zW
        Switch to the raster renderer.

        Used by `.MixedModeRenderer`.
        Nr   )r-   r   r   r    start_rasterizing  s    zRendererBase.start_rasterizingc             C   s   dS )z
        Switch back to the vector renderer and draw the contents of the raster
        renderer as an image on the vector renderer.

        Used by `.MixedModeRenderer`.
        Nr   )r-   r   r   r    stop_rasterizing  s    zRendererBase.stop_rasterizingc             C   s   dS )z
        Switch to a temporary renderer for image filtering effects.

        Currently only supported by the agg renderer.
        Nr   )r-   r   r   r    start_filter  s    zRendererBase.start_filterc             C   s   dS )z
        Switch back to the original renderer.  The contents of the temporary
        renderer is processed with the *filter_func* and is drawn on the
        original renderer as an image.

        Currently only supported by the agg renderer.
        Nr   )r-   Zfilter_funcr   r   r    stop_filter  s    zRendererBase.stop_filterc             C   s   dd t tD }t| f|S )a	  
        Context manager to temporary disable drawing.

        This is used for getting the drawn size of Artists.  This lets us
        run the draw process to update any Python state but does not pay the
        cost of the draw_XYZ calls on the canvas.
        c             S   s(   i | ] }|j d s|dkrdd |qS )Zdraw_r1   r2   c              _   s   d S )Nr   )argskwargsr   r   r    <lambda>  s    z8RendererBase._draw_disabled.<locals>.<dictcomp>.<lambda>)r1   r2   )
startswith).0	meth_namer   r   r    
<dictcomp>  s   
z/RendererBase._draw_disabled.<locals>.<dictcomp>)dirr(   r   )r-   Zno_opsr   r   r    _draw_disabled  s    zRendererBase._draw_disabled)N)N)N)N)r   N)FN)&__name__
__module____qualname____doc__r*   r1   r2   r8   rA   rW   r]   r_   rb   rB   rj   rC   rz   r{   r|   r}   r   Z_delete_parameterr   r   r   r   r   r   r   r   rp   r   r   r   r   r   r   __classcell__r   r   )r.   r    r(   y   sB   


!-d
!


%" 	r(   c               @   s6  e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- ZdMd/d0Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z!dNd@dAZ"dBdC Z#dDdE Z$dFdG Z%dHdI Z&dOdKdLZ'dJS )Pr   z=An abstract base class that provides color, line styles, etc.c             C   s~   d| _ d| _d| _d| _d | _d | _d| _d| _d| _d| _	d| _
d | _tjtd	 | _td
 | _d | _d | _d | _d | _d S )N      ?Fri   buttr   roundZsolid        zhatch.colorzhatch.linewidth)r   N)r   r   r   r   )_alpha_forced_alpha_antialiased	_capstyle	_cliprect	_clippath_dashes
_joinstyle
_linestyle
_linewidth_rgb_hatchr	   to_rgbar   _hatch_color_hatch_linewidth_url_gid_snap_sketch)r-   r   r   r    r*     s$    
zGraphicsContextBase.__init__c             C   s   |j | _ |j| _|j| _|j| _|j| _|j| _|j| _|j| _|j| _|j	| _	|j
| _
|j| _|j| _|j| _|j| _|j| _|j| _|j| _dS )z"Copy properties from *gc* to self.N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r-   r4   r   r   r    rq     s$    z#GraphicsContextBase.copy_propertiesc             C   s   dS )z
        Restore the graphics context from the stack - needed only
        for backends that save graphics contexts on a stack.
        Nr   )r-   r   r   r    rx   	  s    zGraphicsContextBase.restorec             C   s   | j S )zc
        Return the alpha value used for blending - not supported on all
        backends.
        )r   )r-   r   r   r    	get_alpha  s    zGraphicsContextBase.get_alphac             C   s   | j S )zAReturn whether the object should try to do antialiased rendering.)r   )r-   r   r   r    get_antialiased  s    z#GraphicsContextBase.get_antialiasedc             C   s   | j S )zU
        Return the capstyle as a string in ('butt', 'round', 'projecting').
        )r   )r-   r   r   r    get_capstyle  s    z GraphicsContextBase.get_capstylec             C   s   | j S )zX
        Return the clip rectangle as a `~matplotlib.transforms.Bbox` instance.
        )r   )r-   r   r   r    get_clip_rectangle   s    z&GraphicsContextBase.get_clip_rectanglec             C   s   | j dk	r| j j S dS )z
        Return the clip path in the form (path, transform), where path
        is a `~.path.Path` instance, and transform is
        an affine transform to apply to the path before clipping.
        N)NN)r   Zget_transformed_path_and_affine)r-   r   r   r    get_clip_path&  s    

z!GraphicsContextBase.get_clip_pathc             C   s   | j S )aX  
        Return the dash style as an (offset, dash-list) pair.

        The dash list is a even-length list that gives the ink on, ink off in
        points.  See p. 107 of to PostScript `blue book`_ for more info.

        Default value is (None, None).

        .. _blue book: https://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF
        )r   )r-   r   r   r    
get_dashes0  s    zGraphicsContextBase.get_dashesc             C   s   | j S )z
        Return whether the value given by get_alpha() should be used to
        override any other alpha-channel values.
        )r   )r-   r   r   r    get_forced_alpha=  s    z$GraphicsContextBase.get_forced_alphac             C   s   | j S )zAReturn the line join style as one of ('miter', 'round', 'bevel').)r   )r-   r   r   r    get_joinstyleD  s    z!GraphicsContextBase.get_joinstylec             C   s   | j S )z Return the line width in points.)r   )r-   r   r   r    r[   H  s    z!GraphicsContextBase.get_linewidthc             C   s   | j S )z0Return a tuple of three or four floats from 0-1.)r   )r-   r   r   r    r   L  s    zGraphicsContextBase.get_rgbc             C   s   | j S )z+Return a url if one is set, None otherwise.)r   )r-   r   r   r    get_urlP  s    zGraphicsContextBase.get_urlc             C   s   | j S )z;Return the object identifier if one is set, None otherwise.)r   )r-   r   r   r    get_gidT  s    zGraphicsContextBase.get_gidc             C   s   | j S )a  
        Return the snap setting, which can be:

        * True: snap vertices to the nearest pixel center
        * False: leave vertices as-is
        * None: (auto) If the path contains only rectilinear line segments,
          round to the nearest pixel center
        )r   )r-   r   r   r    get_snapX  s    	zGraphicsContextBase.get_snapc             C   s6   |dk	r|| _ d| _nd| _ d| _| j| jdd dS )aB  
        Set the alpha value used for blending - not supported on all backends.

        If ``alpha=None`` (the default), the alpha components of the
        foreground and fill colors will be used to set their respective
        transparencies (where applicable); otherwise, ``alpha`` will override
        them.
        NTg      ?F)isRGBA)r   r   ru   r   )r-   alphar   r   r    	set_alphac  s    	zGraphicsContextBase.set_alphac             C   s   t t|| _dS )z>Set whether object should be drawn with antialiased rendering.N)intboolr   )r-   br   r   r    rv   t  s    z#GraphicsContextBase.set_antialiasedc             C   s   t jdddg|d || _dS )z>Set the capstyle to be one of ('butt', 'round', 'projecting').r   r   Z
projecting)csN)r   _check_in_listr   )r-   r   r   r   r    set_capstyley  s    z GraphicsContextBase.set_capstylec             C   s
   || _ dS )zT
        Set the clip rectangle with sequence (left, bottom, width, height)
        N)r   )r-   Z	rectangler   r   r    set_clip_rectangle~  s    z&GraphicsContextBase.set_clip_rectanglec             C   s   t jtjdf|d || _dS )z
        Set the clip path and transformation.

        Parameters
        ----------
        path : `~matplotlib.transforms.TransformedPath` or None
        N)r5   )r   Z_check_isinstancer   ZTransformedPathr   )r-   r5   r   r   r    set_clip_path  s    z!GraphicsContextBase.set_clip_pathc             C   s6   |dk	r(t j|}t j|dk r(td||f| _dS )a  
        Set the dash style for the gc.

        Parameters
        ----------
        dash_offset : float or None
            The offset (usually 0).
        dash_list : array-like or None
            The on-off sequence as points.

        Notes
        -----
        ``(None, None)`` specifies a solid line.

        See p. 107 of to PostScript `blue book`_ for more info.

        .. _blue book: https://www-cdf.fnal.gov/offline/PostScript/BLUEBOOK.PDF
        Ng        z,All values in the dash list must be positive)rY   Zasarrayany
ValueErrorr   )r-   Zdash_offsetZ	dash_listdlr   r   r    rt     s    
zGraphicsContextBase.set_dashesFc             C   sV   | j r"|r"|dd | jf | _n0| j r:tj|| j| _n|rF|| _ntj|| _dS )z
        Set the foreground color.

        Parameters
        ----------
        fg : color
        isRGBA : bool
            If *fg* is known to be an ``(r, g, b, a)`` tuple, *isRGBA* can be
            set to True to improve performance.
        Nrn   )r   r   r   r	   r   )r-   ry   r   r   r   r    ru     s    
z"GraphicsContextBase.set_foregroundc             C   s   t jdddg|d || _dS )z<Set the join style to be one of ('miter', 'round', 'bevel').Zmiterr   Zbevel)jsN)r   r   r   )r-   r   r   r   r    set_joinstyle  s    z!GraphicsContextBase.set_joinstylec             C   s   t || _dS )zSet the linewidth in points.N)r\   r   )r-   r   r   r   r    rr     s    z!GraphicsContextBase.set_linewidthc             C   s
   || _ dS )z-Set the url for links in compatible backends.N)r   )r-   urlr   r   r    rw     s    zGraphicsContextBase.set_urlc             C   s
   || _ dS )zSet the id.N)r   )r-   idr   r   r    set_gid  s    zGraphicsContextBase.set_gidc             C   s
   || _ dS )a  
        Set the snap setting which may be:

        * True: snap vertices to the nearest pixel center
        * False: leave vertices as-is
        * None: (auto) If the path contains only rectilinear line segments,
          round to the nearest pixel center
        N)r   )r-   Zsnapr   r   r    set_snap  s    	zGraphicsContextBase.set_snapc             C   s
   || _ dS )z Set the hatch style (for fills).N)r   )r-   hatchr   r   r    	set_hatch  s    zGraphicsContextBase.set_hatchc             C   s   | j S )zGet the current hatch style.)r   )r-   r   r   r    	get_hatch  s    zGraphicsContextBase.get_hatch      @c             C   s    | j  }|dkrdS tj||S )z'Return a `.Path` for the current hatch.N)r   r   r   )r-   Zdensityr   r   r   r    get_hatch_path  s    z"GraphicsContextBase.get_hatch_pathc             C   s   | j S )zGet the hatch color.)r   )r-   r   r   r    get_hatch_color  s    z#GraphicsContextBase.get_hatch_colorc             C   s
   || _ dS )zSet the hatch color.N)r   )r-   Zhatch_colorr   r   r    set_hatch_color  s    z#GraphicsContextBase.set_hatch_colorc             C   s   | j S )zGet the hatch linewidth.)r   )r-   r   r   r    get_hatch_linewidth  s    z'GraphicsContextBase.get_hatch_linewidthc             C   s   | j S )a  
        Return the sketch parameters for the artist.

        Returns
        -------
        tuple or `None`

            A 3-tuple with the following elements:

            * ``scale``: The amplitude of the wiggle perpendicular to the
              source line.
            * ``length``: The length of the wiggle along the line.
            * ``randomness``: The scale factor by which the length is
              shrunken or expanded.

            May return `None` if no sketch parameters were set.
        )r   )r-   r   r   r    get_sketch_params  s    z%GraphicsContextBase.get_sketch_paramsNc             C   s$   |dkrdn||pd|pdf| _ dS )a  
        Set the sketch parameters.

        Parameters
        ----------
        scale : float, optional
            The amplitude of the wiggle perpendicular to the source line, in
            pixels.  If scale is `None`, or not provided, no sketch filter will
            be provided.
        length : float, default: 128
             The length of the wiggle along the line, in pixels.
        randomness : float, default: 16
            The scale factor by which the length is shrunken or expanded.
        Ng      `@g      0@)r   )r-   r   lengthZ
randomnessr   r   r    set_sketch_params  s    z%GraphicsContextBase.set_sketch_params)F)r   )NNN)(r   r   r   r   r*   rq   rx   r   r   r   r   r   r   r   r   r[   r   r   r   r   r   rv   r   r   r   rt   ru   r   rr   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r     sJ   


r   c               @   s   e Zd ZdZdddZdd Zd ddZd	d
 Zdd Zdd Z	e
dd Zejdd Ze
dd Zejdd Zdd Zdd Zdd Zdd Zdd ZdS )!	TimerBasea5  
    A base class for providing timer events, useful for things animations.
    Backends need to implement a few specific methods in order to use their
    own timing mechanisms so that the timer events are integrated into their
    event loops.

    Subclasses must override the following methods:

    - ``_timer_start``: Backend-specific code for starting the timer.
    - ``_timer_stop``: Backend-specific code for stopping the timer.

    Subclasses may additionally override the following methods:

    - ``_timer_set_single_shot``: Code for setting the timer to single shot
      operating mode, if supported by the timer object.  If not, the `Timer`
      class itself will store the flag and the ``_on_timer`` method should be
      overridden to support such behavior.

    - ``_timer_set_interval``: Code for setting the interval on the timer, if
      there is a method for doing so on the timer object.

    - ``_on_timer``: The internal function that any timer object should call,
      which will handle the task of running all callbacks that have been set.
    Nc             C   s2   |dkrg n|j  | _|dkr"dn|| _d| _dS )a  
        Parameters
        ----------
        interval : int, default: 1000ms
            The time between timer events in milliseconds.  Will be stored as
            ``timer.interval``.
        callbacks : List[Tuple[callable, Tuple, Dict]]
            List of (func, args, kwargs) tuples that will be called upon
            timer events.  This list is accessible as ``timer.callbacks`` and
            can be manipulated directly, or the functions `add_callback` and
            `remove_callback` can be used.
        Ni  F)copy	callbacksintervalsingle_shot)r-   r   r   r   r   r    r*   6  s    zTimerBase.__init__c             C   s   | j   dS )z1Need to stop timer and possibly disconnect timer.N)_timer_stop)r-   r   r   r    __del__H  s    zTimerBase.__del__c             C   s   |dk	r|| _ | j  dS )z
        Start the timer object.

        Parameters
        ----------
        interval : int, optional
            Timer interval in milliseconds; overrides a previously set interval
            if provided.
        N)r   _timer_start)r-   r   r   r   r    startL  s    
zTimerBase.startc             C   s   | j   dS )zStop the timer.N)r   )r-   r   r   r    stopZ  s    zTimerBase.stopc             C   s   d S )Nr   )r-   r   r   r    r   ^  s    zTimerBase._timer_startc             C   s   d S )Nr   )r-   r   r   r    r   a  s    zTimerBase._timer_stopc             C   s   | j S )z/The time between timer events, in milliseconds.)	_interval)r-   r   r   r    r   d  s    zTimerBase.intervalc             C   s   t |}|| _| j  d S )N)r   r   _timer_set_interval)r-   r   r   r   r    r   i  s    c             C   s   | j S )z2Whether this timer should stop after a single run.)_single)r-   r   r   r    r   q  s    zTimerBase.single_shotc             C   s   || _ | j  d S )N)r  _timer_set_single_shot)r-   ssr   r   r    r   v  s    c             O   s   | j j|||f |S )z
        Register *func* to be called by timer when the event fires. Any
        additional arguments provided will be passed to *func*.

        This function returns *func*, which makes it possible to use it as a
        decorator.
        )r   append)r-   funcr   r   r   r   r    add_callback{  s    zTimerBase.add_callbackc             O   sX   |s|r*t jddd | jj|||f n*dd | jD }||krT| jj|j| dS )a  
        Remove *func* from list of callbacks.

        *args* and *kwargs* are optional and used to distinguish between copies
        of the same function registered to be called with different arguments.
        This behavior is deprecated.  In the future, ``*args, **kwargs`` won't
        be considered anymore; to keep a specific callback removable by itself,
        pass it to `add_callback` as a `functools.partial` object.
        z3.1zIn a future version, Timer.remove_callback will not take *args, **kwargs anymore, but remove all callbacks where the callable matches; to keep a specific callback removable by itself, pass it to add_callback as a functools.partial object.)rl   c             S   s   g | ]}|d  qS )r   r   )r   cr   r   r    
<listcomp>  s    z-TimerBase.remove_callback.<locals>.<listcomp>N)r   ro   r   removepopindex)r-   r  r   r   funcsr   r   r    remove_callback  s    

zTimerBase.remove_callbackc             C   s   dS )z0Used to set interval on underlying timer object.Nr   )r-   r   r   r    r     s    zTimerBase._timer_set_intervalc             C   s   dS )z3Used to set single shot on underlying timer object.Nr   )r-   r   r   r    r    s    z TimerBase._timer_set_single_shotc             C   sT   x8| j D ].\}}}|||}|dkr| j j|||f qW t| j dkrP| j  dS )z
        Runs all function that have been registered as callbacks. Functions
        can return False (or 0) if they should not be called any more. If there
        are no callbacks, the timer is automatically stopped.
        r   N)r   r	  r;   r   )r-   r  r   r   retr   r   r    	_on_timer  s    
zTimerBase._on_timer)NN)N)r   r   r   r   r*   r   r   r   r   r   propertyr   setterr   r  r  r   r  r  r   r   r   r    r     s    

r   c               @   s   e Zd ZdZdddZdS )Eventa  
    A Matplotlib event.  Attach additional attributes as defined in
    :meth:`FigureCanvasBase.mpl_connect`.  The following attributes
    are defined and shown with their default values

    Attributes
    ----------
    name : str
        The event name.
    canvas : `FigureCanvasBase`
        The backend-specific canvas instance generating the event.
    guiEvent
        The GUI event that triggered the Matplotlib event.
    Nc             C   s   || _ || _|| _d S )N)namecanvasguiEvent)r-   r  r  r  r   r   r    r*     s    zEvent.__init__)N)r   r   r   r   r*   r   r   r   r    r    s   r  c               @   s   e Zd ZdZdd ZdS )	DrawEventa  
    An event triggered by a draw operation on the canvas

    In most backends callbacks subscribed to this callback will be
    fired after the rendering is complete but before the screen is
    updated.  Any extra artists drawn to the canvas's renderer will
    be reflected without an explicit call to ``blit``.

    .. warning::

       Calling ``canvas.draw`` and ``canvas.blit`` in these callbacks may
       not be safe with all backends and may cause infinite recursion.

    In addition to the `Event` attributes, the following event
    attributes are defined:

    Attributes
    ----------
    renderer : `RendererBase`
        The renderer for the draw event.
    c             C   s   t j| || || _d S )N)r  r*   r   )r-   r  r  r   r   r   r    r*     s    zDrawEvent.__init__N)r   r   r   r   r*   r   r   r   r    r    s   r  c               @   s   e Zd ZdZdd ZdS )ResizeEventa  
    An event triggered by a canvas resize

    In addition to the `Event` attributes, the following event
    attributes are defined:

    Attributes
    ----------
    width : int
        Width of the canvas in pixels.
    height : int
        Height of the canvas in pixels.
    c             C   s"   t j| || |j \| _| _d S )N)r  r*   r   r   r   )r-   r  r  r   r   r    r*     s    zResizeEvent.__init__N)r   r   r   r   r*   r   r   r   r    r    s   r  c               @   s   e Zd ZdZdS )
CloseEventz,An event triggered by a figure being closed.N)r   r   r   r   r   r   r   r    r    s   r  c               @   s&   e Zd ZdZdZdddZdd ZdS )LocationEventan  
    An event that has a screen location.

    The following additional attributes are defined and shown with
    their default values.

    In addition to the `Event` attributes, the following
    event attributes are defined:

    Attributes
    ----------
    x : int
        x position - pixels from left of canvas.
    y : int
        y position - pixels from bottom of canvas.
    inaxes : `~.axes.Axes` or None
        The `~.axes.Axes` instance over which the mouse is, if any.
    xdata : float or None
        x data coordinate of the mouse.
    ydata : float or None
        y data coordinate of the mouse.
    Nc       	      C   s   t j| |||d |dk	r"t|n|| _|dk	r8t|n|| _d| _d| _d| _|dks`|dkrl| j  dS | j	j
dkr| j	j||f| _n
| j	j
| _| jdk	ry"| jjj }|j||f\}}W n tk
r   Y nX || _|| _| j  dS )zE
        (*x*, *y*) in figure coords ((0, 0) = bottom left).
        )r  N)r  r*   r   r?   r@   inaxesxdataydata_update_enter_leaver  mouse_grabberZ	transDatainvertedr6   r   )	r-   r  r  r?   r@   r  r=   r  r  r   r   r    r*     s*    

zLocationEvent.__init__c             C   s   t jdk	rlt j}|j| jkry|jdk	r8|jjjd| W n tk
rN   Y nX | jdk	r| jjjd|  n| jdk	r| jjjd|  | t _dS )z+Process the figure/axes enter leave events.Naxes_leave_eventaxes_enter_event)r  	lasteventr  r  r   process	Exception)r-   lastr   r   r    r  ;  s    



z!LocationEvent._update_enter_leave)N)r   r   r   r   r"  r*   r  r   r   r   r    r    s   
#r  c               @   s    e Zd ZdZdZdZdZdZdS )MouseButtonri   r9   rn      	   N)r   r   r   LEFTZMIDDLERIGHTBACKFORWARDr   r   r   r    r&  V  s
   r&  c               @   s"   e Zd ZdZd	ddZdd ZdS )

MouseEventa@  
    A mouse event ('button_press_event',
                   'button_release_event',
                   'scroll_event',
                   'motion_notify_event').

    In addition to the `Event` and `LocationEvent`
    attributes, the following attributes are defined:

    Attributes
    ----------
    button : None or `MouseButton` or {'up', 'down'}
        The button pressed. 'up' and 'down' are used for scroll events.
        Note that in the nbagg backend, both the middle and right clicks
        return RIGHT since right clicking will bring up the context menu in
        some browsers.
        Note that LEFT and RIGHT actually refer to the "primary" and
        "secondary" buttons, i.e. if the user inverts their left and right
        buttons ("left-handed setting") then the LEFT button will be the one
        physically on the right.

    key : None or str
        The key pressed when the mouse event triggered, e.g. 'shift'.
        See `KeyEvent`.

        .. warning::
           This key is currently obtained from the last 'key_press_event' or
           'key_release_event' that occurred within the canvas.  Thus, if the
           last change of keyboard state occurred while the canvas did not have
           focus, this attribute will be wrong.

    step : float
        The number of scroll steps (positive for 'up', negative for 'down').
        This applies only to 'scroll_event' and defaults to 0 otherwise.

    dblclick : bool
        Whether the event is a double-click. This applies only to
        'button_press_event' and is False otherwise. In particular, it's
        not used in 'button_release_event'.

    Examples
    --------
    ::

        def on_press(event):
            print('you pressed', event.button, event.xdata, event.ydata)

        cid = fig.canvas.mpl_connect('button_press_event', on_press)
    Nr   Fc
       
      C   sH   |t jj krt |}|| _|| _|| _|| _tj| |||||	d dS )zw
        (*x*, *y*) in figure coords ((0, 0) = bottom left)
        button pressed None, 1, 2, 3, 'up', 'down'
        )r  N)	r&  __members__valuesbuttonkeystepdblclickr  r*   )
r-   r  r  r?   r@   r0  r1  r2  r3  r  r   r   r    r*     s    zMouseEvent.__init__c             C   sB   | j  d| j d| j d| j d| j d| j d| j d| j S )Nz: xy=(z, z
) xydata=(z	) button=z
 dblclick=z inaxes=)r  r?   r@   r  r  r0  r3  r  )r-   r   r   r    __str__  s    zMouseEvent.__str__)NNr   FN)r   r   r   r   r*   r4  r   r   r   r    r-  ^  s   1 
r-  c               @   s   e Zd ZdZdddZdS )	PickEventa  
    A pick event, fired when the user picks a location on the canvas
    sufficiently close to an artist.

    Attrs: all the `Event` attributes plus

    Attributes
    ----------
    mouseevent : `MouseEvent`
        The mouse event that generated the pick.
    artist : `matplotlib.artist.Artist`
        The picked artist.
    other
        Additional attributes may be present depending on the type of the
        picked object; e.g., a `~.Line2D` pick may define different extra
        attributes than a `~.PatchCollection` pick.

    Examples
    --------
    Bind a function ``on_pick()`` to pick events, that prints the coordinates
    of the picked data point::

        ax.plot(np.rand(100), 'o', picker=5)  # 5 points tolerance

        def on_pick(event):
            line = event.artist
            xdata, ydata = line.get_data()
            ind = event.ind
            print('on pick line:', np.array([xdata[ind], ydata[ind]]).T)

        cid = fig.canvas.mpl_connect('pick_event', on_pick)
    Nc             K   s,   t j| ||| || _|| _| jj| d S )N)r  r*   
mouseeventartist__dict__update)r-   r  r  r6  r7  r  r   r   r   r    r*     s    zPickEvent.__init__)N)r   r   r   r   r*   r   r   r   r    r5    s    r5  c               @   s   e Zd ZdZdddZdS )KeyEventa  
    A key event (key press, key release).

    Attach additional attributes as defined in
    :meth:`FigureCanvasBase.mpl_connect`.

    In addition to the `Event` and `LocationEvent`
    attributes, the following attributes are defined:

    Attributes
    ----------
    key : None or str
        the key(s) pressed. Could be **None**, a single case sensitive ascii
        character ("g", "G", "#", etc.), a special key
        ("control", "shift", "f1", "up", etc.) or a
        combination of the above (e.g., "ctrl+alt+g", "ctrl+alt+G").

    Notes
    -----
    Modifier keys will be prefixed to the pressed key and will be in the order
    "ctrl", "alt", "super". The exception to this rule is when the pressed key
    is itself a modifier key, therefore "ctrl+alt" and "alt+control" can both
    be valid key values.

    Examples
    --------
    ::

        def on_key(event):
            print('you pressed', event.key, event.xdata, event.ydata)

        cid = fig.canvas.mpl_connect('key_press_event', on_key)
    r   Nc             C   s    || _ tj| |||||d d S )N)r  )r1  r  r*   )r-   r  r  r1  r?   r@   r  r   r   r    r*     s    zKeyEvent.__init__)r   r   N)r   r   r   r   r*   r   r   r   r    r:    s   !r:  c                s   G dd dt   fdd}tj| |d | j}|dkr^| jj }t| jjd|d| }zZy|tj | j	d W n0  k
r } z|j
 \}\| _|S d}~X nX t| d	W d|| _X W dQ R X dS )
z
    Get the renderer that would be used to save a `~.Figure`, and cache it on
    the figure.

    If you need a renderer without any active draw methods use
    renderer._draw_disabled to temporary patch them out at your call site.
    c               @   s   e Zd ZdS )z_get_renderer.<locals>.DoneN)r   r   r   r   r   r   r    Done  s   r;  c                s    | d S )Nr   )r   )r;  r   r    _draw  s    z_get_renderer.<locals>._draw)drawNprint_)r   z6 did not call Figure.draw, so no renderer is available)r$  r   r   r  get_default_filetypegetattr_get_output_canvasioBytesIOr   r   Z_cachedRendererRuntimeError)figureprint_methodr<  Zorig_canvasfmtexcr   r   )r;  r    _get_renderer  s    
rI  c             C   s&   t | do$| jdk	o$t| jdddkS )aP  
    Return whether we are in a a terminal IPython, but non interactive.

    When in _terminal_ IPython, ip.parent will have and `interact` attribute,
    if this attribute is False we do not setup eventloop integration as the
    user will _not_ interact with IPython. In all other case (ZMQKernel, or is
    interactive), we do.
    parentNZinteractF)hasattrrJ  r@  )ipr   r   r    $_is_non_interactive_terminal_ipython  s    	

rM  c                s>   dkrt jt dS tjt j fdd}|S )ae  
    Decorator for the final print_* methods that accept keyword arguments.

    If any unused keyword arguments are left, this decorator will warn about
    them, and as part of the warning, will attempt to specify the function that
    the user actually called, instead of the backend-specific method. If unable
    to determine which function the user called, it will specify `.savefig`.

    For compatibility across backends, this does not warn about keyword
    arguments added by `FigureCanvasBase.print_figure` for use in a subset of
    backends, because the user would not have added them directly.
    N)extra_kwargsc        
         s   d}t jd}d}x\tjd D ]N\}}|d kr0P t jd|jjddrj|j|jjrl|jj}|dkrld}qP qW j	 }|rx dD ]}||kr|j
|d  qW x<t|D ]0}	|	|krqtjd|d|	 d d |j
|	 qW | |S )NZsavefigz^savefig|print_[A-Za-z0-9]+$Fz-\A(matplotlib|mpl_toolkits)(\Z|\.(?!tests\.))r   r   print_figureTr   	facecolor	edgecolororientationbbox_inches_restorez3.3z,%(name)s() got unexpected keyword argument "zS" which is no longer supported as of %(since)s and will become an error %(removal)s)r  rl   )r   rP  rQ  rR  rS  )recompile	traceback
walk_stackmatch	f_globalsgetf_codeco_name
parametersr
  rD   r   ro   )
r   r   r  Z
public_apiZseen_print_figureframelineZaccepted_kwargskwarg)rN  r  old_sigr   r    wrapper@  s6    

z*_check_savefig_extra_args.<locals>.wrapper)	functoolspartial_check_savefig_extra_argsinspect	signaturewraps)r  rN  rc  r   )rN  r  rb  r    rf  ,  s    
)rf  c               @   s  e Zd ZdZdZddddddd	d
ddddddgZdZeZe	j
dd Zdd Zeej dd Zedd Zdd Zdd ZdjddZdd  Zd!d" Zd#d$ Zdkd%d&Zdld'd(Zdmd)d*Zd+d, Zdnd-d.Zdod0d1Zdpd2d3Zdqd4d5Z drd6d7Z!dsd8d9Z"d:d; Z#d<d= Z$d>d? Z%d@dA Z&dBdC Z'e	j(dDdEdF Z)dGdH Z*edIdJ Z+edKdL Z,dMdN Z-dtdddddPdQdRZ.edSdT Z/dUdV Z0dWdX Z1dYdZ Z2d[d\ Z3d]d^ Z4d_d` Z5e6Z7dudadbZ8dcdd Z9dvdfdgZ:dhdi Z;dS )wFigureCanvasBasez
    The canvas the figure renders into.

    Attributes
    ----------
    figure : `matplotlib.figure.Figure`
        A high-level figure instance.
    Nresize_event
draw_eventkey_press_eventkey_release_eventbutton_press_eventbutton_release_eventscroll_eventmotion_notify_event
pick_eventfigure_enter_eventfigure_leave_eventr!  r   close_eventc             C   s   t | dot | dS )z+If this Canvas sub-class supports blitting.Zcopy_from_bboxZrestore_region)rK  )clsr   r   r    supports_blit  s    
zFigureCanvasBase.supports_blitc             C   s   | j   d| _d| _|j|  || _d | _tj | _t	j
 | _d | _d | _d\| _| _| jd| j| _| jd| j| _d | _d | _d| _d S )NTFro  rq  )NN)_fix_ipython_backend2gui_is_idle_drawing
_is_saving
set_canvasrE  managerr   ZCallbackRegistryr   r   ZLockDraw
widgetlock_button_key_lastx_lastympl_connectpickZbutton_pick_idZscroll_pick_idr  toolbar)r-   rE  r   r   r    r*     s     


zFigureCanvasBase.__init__c             C   s   dt jkrd S dd l}|j }|s&d S ddlm} t|d sJt|d rNd S t| dd }dddd	d
dj|}|rt	|r|j
| d S )NIPythonr   )
pylabtoolsZbackend2guiZenable_matplotlibrequired_interactive_frameworkZqtgtk3wxZosx)Zqt5Zqt4r  r  macosx)sysmodulesr  Zget_ipythonZIPython.corer  rK  r@  rZ  rM  Z
enable_gui)rw  r  rL  ptZrifZbackend2gui_rifr   r   r    ry    s     
z)FigureCanvasBase._fix_ipython_backend2guic             c   s   d| _ z
d V  W d d| _ X d S )NTF)rz  )r-   r   r   r    _idle_draw_cntx  s    
z FigureCanvasBase._idle_draw_cntxc             C   s   | j S )z
        Return whether the renderer is in the process of saving
        to a file, rather than rendering for an on-screen buffer.
        )r{  )r-   r   r   r    	is_saving  s    zFigureCanvasBase.is_savingc             C   s   | j j s| jj| d S )N)r~  lockedrE  r  )r-   r6  r   r   r    r    s    
zFigureCanvasBase.pickc             C   s   dS )z0Blit the canvas in bbox (default entire canvas).Nr   )r-   bboxr   r   r    blit  s    zFigureCanvasBase.blitc             C   s   dS )zSet the canvas size in pixels.Nr   )r-   r   r   r   r   r    resize  s    zFigureCanvasBase.resizec             C   s"   d}t || |}| jj|| dS )z@Pass a `DrawEvent` to all functions connected to ``draw_event``.rl  N)r  r   r#  )r-   r   r/   eventr   r   r    rl    s    zFigureCanvasBase.draw_eventc             C   s(   d}t || }| jj|| | j  dS )zV
        Pass a `ResizeEvent` to all functions connected to ``resize_event``.
        rk  N)r  r   r#  	draw_idle)r-   r/   r  r   r   r    rk    s    
zFigureCanvasBase.resize_eventc             C   sB   d}y t || |d}| jj|| W n ttfk
r<   Y nX dS )zT
        Pass a `CloseEvent` to all functions connected to ``close_event``.
        rv  )r  N)r  r   r#  	TypeErrorAttributeError)r-   r  r/   r  r   r   r    rv    s    zFigureCanvasBase.close_eventc             C   s4   || _ d}t|| || j| j|d}| jj|| dS )zV
        Pass a `KeyEvent` to all functions connected to ``key_press_event``.
        rm  )r  N)r  r:  r  r  r   r#  )r-   r1  r  r/   r  r   r   r    rm    s
    z FigureCanvasBase.key_press_eventc             C   s4   d}t || || j| j|d}| jj|| d| _dS )zX
        Pass a `KeyEvent` to all functions connected to ``key_release_event``.
        rn  )r  N)r:  r  r  r   r#  r  )r-   r1  r  r/   r  r   r   r    rn    s
    z"FigureCanvasBase.key_release_eventc             K   s2   d}t || ||fd|ji|}| jj|| dS )z
        Callback processing for pick events.

        This method will be called by artists who are picked and will
        fire off `PickEvent` callbacks registered listeners.
        rs  r  N)r5  r  r   r#  )r-   r6  r7  r   r/   r  r   r   r    rs    s
    zFigureCanvasBase.pick_eventc          
   C   sH   |dkrd| _ nd| _ d}t|| ||| j | j||d}| jj|| dS )a{  
        Callback processing for scroll events.

        Backend derived classes should call this function on any
        scroll wheel event.  (*x*, *y*) are the canvas coords ((0, 0) is lower
        left).  button and key are as defined in `MouseEvent`.

        This method will call all functions connected to the 'scroll_event'
        with a `MouseEvent` instance.
        r   ZupZdownrq  )r2  r  N)r  r-  r  r   r#  )r-   r?   r@   r2  r  r/   r6  r   r   r    rq    s    
zFigureCanvasBase.scroll_eventFc          
   C   s6   || _ d}t|| |||| j||d}| jj|| dS )a  
        Callback processing for mouse button press events.

        Backend derived classes should call this function on any mouse
        button press.  (*x*, *y*) are the canvas coords ((0, 0) is lower left).
        button and key are as defined in `MouseEvent`.

        This method will call all functions connected to the
        'button_press_event' with a `MouseEvent` instance.
        ro  )r3  r  N)r  r-  r  r   r#  )r-   r?   r@   r0  r3  r  r/   r6  r   r   r    ro  /  s
    
z#FigureCanvasBase.button_press_eventc          	   C   s4   d}t || |||| j|d}| jj|| d| _dS )a&  
        Callback processing for mouse button release events.

        Backend derived classes should call this function on any mouse
        button release.

        This method will call all functions connected to the
        'button_release_event' with a `MouseEvent` instance.

        Parameters
        ----------
        x : float
            The canvas coordinates where 0=left.
        y : float
            The canvas coordinates where 0=bottom.
        guiEvent
            The native UI event that generated the Matplotlib event.
        rp  )r  N)r-  r  r   r#  r  )r-   r?   r@   r0  r  r/   r  r   r   r    rp  @  s    z%FigureCanvasBase.button_release_eventc          	   C   s>   || | _ | _d}t|| ||| j| j|d}| jj|| dS )a  
        Callback processing for mouse movement events.

        Backend derived classes should call this function on any
        motion-notify-event.

        This method will call all functions connected to the
        'motion_notify_event' with a `MouseEvent` instance.

        Parameters
        ----------
        x : float
            The canvas coordinates where 0=left.
        y : float
            The canvas coordinates where 0=bottom.
        guiEvent
            The native UI event that generated the Matplotlib event.
        rr  )r  N)r  r  r-  r  r  r   r#  )r-   r?   r@   r  r/   r  r   r   r    rr  X  s
    z$FigureCanvasBase.motion_notify_eventc             C   s&   | j jdtj dt_d\| _| _dS )a#  
        Callback processing for the mouse cursor leaving the canvas.

        Backend derived classes should call this function when leaving
        canvas.

        Parameters
        ----------
        guiEvent
            The native UI event that generated the Matplotlib event.
        ru  N)NN)r   r#  r  r"  r  r  )r-   r  r   r   r    leave_notify_eventq  s    z#FigureCanvasBase.leave_notify_eventc             C   s\   |dk	r |\}}|| | _ | _nd}d}tjddddd td| |||}| jjd| dS )a  
        Callback processing for the mouse cursor entering the canvas.

        Backend derived classes should call this function when entering
        canvas.

        Parameters
        ----------
        guiEvent
            The native UI event that generated the Matplotlib event.
        xy : (float, float)
            The coordinate location of the pointer when the canvas is entered.
        Nz3.0z3.5enter_notify_eventzvSince %(since)s, %(name)s expects a location but your backend did not pass one. This will become an error %(removal)s.)Zremovalr  rl   rt  )r  r  r   ro   r  r   r#  )r-   r  xyr?   r@   r  r   r   r    r    s    z#FigureCanvasBase.enter_notify_eventc                s0    fdd| j j D }|r(tj|}nd}|S )as  
        Return the topmost visible `~.axes.Axes` containing the point *xy*.

        Parameters
        ----------
        xy : (float, float)
            (x, y) pixel positions from left/bottom of the canvas.

        Returns
        -------
        `~matplotlib.axes.Axes` or None
            The topmost visible axes containing the point, or None if no axes.
        c                s$   g | ]}|j j r|j r|qS r   )patchZcontains_pointget_visible)r   a)r  r   r    r    s    z+FigureCanvasBase.inaxes.<locals>.<listcomp>N)rE  get_axesr   _topmost_artist)r-   r  Z	axes_listaxesr   )r  r    r    s
    zFigureCanvasBase.inaxesc             C   s    | j d|fkrtd|| _ dS )z
        Set the child `~.axes.Axes` which is grabbing the mouse events.

        Usually called by the widgets themselves. It is an error to call this
        if the mouse is already grabbed by another axes.
        Nz&Another Axes already grabs mouse input)r  rD  )r-   axr   r   r    
grab_mouse  s    zFigureCanvasBase.grab_mousec             C   s   | j |krd| _ dS )z
        Release the mouse grab held by the `~.axes.Axes` *ax*.

        Usually called by the widgets. It is ok to call this even if *ax*
        doesn't have the mouse grab currently.
        N)r  )r-   r  r   r   r    release_mouse  s    
zFigureCanvasBase.release_mousec             O   s   dS )zRender the `.Figure`.Nr   )r-   r   r   r   r   r    r=    s    zFigureCanvasBase.drawc          
   O   s*   | j s&| j  | j|| W dQ R X dS )a  
        Request a widget redraw once control returns to the GUI event loop.

        Even if multiple calls to `draw_idle` occur before control returns
        to the GUI event loop, the figure will only be rendered once.

        Notes
        -----
        Backends may choose to override the method and implement their own
        strategy to prevent multiple renderings.

        N)rz  r  r=  )r-   r   r   r   r   r    r    s    
zFigureCanvasBase.draw_idlez3.2c             C   s   dS )z
        Draw a cursor in the event.axes if inaxes is not None.  Use
        native GUI drawing for efficiency if possible
        Nr   )r-   r  r   r   r    draw_cursor  s    zFigureCanvasBase.draw_cursorc             C   s   t | jjjt | jjjfS )z
        Return the figure width and height in points or pixels
        (depending on the backend), truncated to integers.
        )r   rE  r  r   r   )r-   r   r   r    r     s    z!FigureCanvasBase.get_width_heightc             C   s   | j S )z>Return dict of savefig file formats supported by this backend.)	filetypes)rw  r   r   r    get_supported_filetypes  s    z(FigureCanvasBase.get_supported_filetypesc             C   s>   i }x4| j j D ]&\}}|j|g j| || j  qW |S )a  
        Return a dict of savefig file formats supported by this backend,
        where the keys are a file type name, such as 'Joint Photographic
        Experts Group', and the values are a list of filename extensions used
        for that filetype, such as ['jpg', 'jpeg'].
        )r  items
setdefaultr  sort)rw  Z	groupingsextr  r   r   r    get_supported_filetypes_grouped  s
    z0FigureCanvasBase.get_supported_filetypes_groupedc             C   s   |dk	rBt jtj|j}t|d| s^td|d| dnt| d| rV| S t|}|rl| j|S tdj	|dj
t| j dS )a3  
        Set the canvas in preparation for saving the figure.

        Parameters
        ----------
        backend : str or None
            If not None, switch the figure canvas to the ``FigureCanvas`` class
            of the given backend.
        fmt : str
            If *backend* is None, then determine a suitable canvas class for
            saving to format *fmt* -- either the current canvas class, if it
            supports *fmt*, or whatever `get_registered_canvas_class` returns;
            switch the figure canvas to that canvas class.
        Nr>  zThe z backend does not support z outputz4Format {!r} is not supported (supported formats: {})z, )r$   r%   r   Z_backend_module_namer&   rK  r   r'   switch_backendsr   joinsortedr  )r-   r   rG  Zcanvas_classr   r   r    rA    s    
z#FigureCanvasBase._get_output_canvasportrait)bbox_inches
pad_inchesbbox_extra_artistsr   c         *   K   s  |dkrtt |tjrtj|}t |tr@tjj|d dd }|dksP|dkrt| j }t |trt|jdd | }|j	 }| j
|
|}t|d| }|dkrtd }|dkrt| jd| jj}tj| dd	 tj| j|d
 tj|dd | jj }| jj }|dkrtd }tj|dr0|}|dkrBtd }tj|drT|}| jj| | jj| |dkr~td }|r"|dkrt| jtj||d}t|dr|j nt }| | jj| W dQ R X | jj||	d}|dkrtd }|j|}tj | j||j!}||f}nd}z ||f|||||d|}W d|rZ|rZ|  | jj| | jj| | jj"|  X |S Q R X W dQ R X W dQ R X dS )a  
        Render the figure to hardcopy. Set the figure patch face and edge
        colors.  This is useful because some of the GUIs have a gray figure
        face color background and you'll probably want to override this on
        hardcopy.

        Parameters
        ----------
        filename : str or path-like or file-like
            The file where the figure is saved.

        dpi : float, default: :rc:`savefig.dpi`
            The dots per inch to save the figure in.

        facecolor : color or 'auto', default: :rc:`savefig.facecolor`
            The facecolor of the figure.  If 'auto', use the current figure
            facecolor.

        edgecolor : color or 'auto', default: :rc:`savefig.edgecolor`
            The edgecolor of the figure.  If 'auto', use the current figure
            edgecolor.

        orientation : {'landscape', 'portrait'}, default: 'portrait'
            Only currently applies to PostScript printing.

        format : str, optional
            Force a specific file format. If not given, the format is inferred
            from the *filename* extension, and if that fails from
            :rc:`savefig.format`.

        bbox_inches : 'tight' or `.Bbox`, default: :rc:`savefig.bbox`
            Bounding box in inches: only the given portion of the figure is
            saved.  If 'tight', try to figure out the tight bbox of the figure.

        pad_inches : float, default: :rc:`savefig.pad_inches`
            Amount of padding around the figure when *bbox_inches* is 'tight'.

        bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
            A list of extra artists that will be considered when the
            tight bbox is calculated.

        backend : str, optional
            Use a non-default backend to render the file, e.g. to render a
            png file with the "cairo" backend rather than the default "agg",
            or a pdf file with the "pgf" backend rather than the default
            "pdf".  Note that the default backend is normally sufficient.  See
            :ref:`the-builtin-backends` for a list of valid backends for each
            file format.  Custom backends can be referenced as "module://...".
        Nri   r   .zprint_%szsavefig.dpirE  Z_original_dpi)r}  )r   T)r{  zsavefig.facecolorautozsavefig.edgecolorzsavefig.bboxZtight)rR  r   )r  zsavefig.pad_inches)r   rP  rQ  rR  rS  )#r"   osPathLikefspathr#   r5   splitextr?  rstriplowerrA  r@  r   rE  r   r   r   Zget_facecolorZget_edgecolorZ
_str_equalZset_facecolorZset_edgecolorrI  rd  re  rK  r   r   r=  Zget_tightbboxZpaddedr   Zadjust_bbox	fixed_dpir|  )r-   filenamer   rP  rQ  rR  r   r  r  r  r   r   r  rF  ZorigfacecolorZorigedgecolorr   ctxZrestore_bboxZ_bbox_inches_restoreresultr   r   r    rO  #  s    6













zFigureCanvasBase.print_figurec             C   s   t d S )z
        Return the default savefig file format as specified in
        :rc:`savefig.format`.

        The returned string does not include a period. This method is
        overridden in backends that only support a single file type.
        zsavefig.format)r   )rw  r   r   r    r?    s    	z%FigureCanvasBase.get_default_filetypec             C   s   | j dk	r| j j S dS )z
        Return the title text of the window containing the figure, or None
        if there is no window (e.g., a PS backend).
        N)r}  get_window_title)r-   r   r   r    r    s    
z!FigureCanvasBase.get_window_titlec             C   s   | j dk	r| j j| dS )z
        Set the title text of the window containing the figure.  Note that
        this has no effect if there is no window (e.g., a PS backend).
        N)r}  set_window_title)r-   titler   r   r    r    s    
z!FigureCanvasBase.set_window_titlec             C   s0   | j  p
d}|jdd}| j }|d | }|S )zl
        Return a string, which includes extension, suitable for use as
        a default filename.
        image _r  )r  replacer?  )r-   Zdefault_basenameZdefault_filetypedefault_filenamer   r   r    get_default_filename  s
    z%FigureCanvasBase.get_default_filenamec             C   s   || j }| j|_|S )aS  
        Instantiate an instance of FigureCanvasClass

        This is used for backend switching, e.g., to instantiate a
        FigureCanvasPS from a FigureCanvasGTK.  Note, deep copying is
        not done, so any changes to one of the instances (e.g., setting
        figure size or line props), will be reflected in the other
        )rE  r{  )r-   ZFigureCanvasClassZ	newCanvasr   r   r    r    s    	
z FigureCanvasBase.switch_backendsc             C   s   | j j||S )a.  
        Bind function *func* to event *s*.

        Parameters
        ----------
        s : str
            One of the following events ids:

            - 'button_press_event'
            - 'button_release_event'
            - 'draw_event'
            - 'key_press_event'
            - 'key_release_event'
            - 'motion_notify_event'
            - 'pick_event'
            - 'resize_event'
            - 'scroll_event'
            - 'figure_enter_event',
            - 'figure_leave_event',
            - 'axes_enter_event',
            - 'axes_leave_event'
            - 'close_event'.

        func : callable
            The callback function to be executed, which must have the
            signature::

                def func(event: Event) -> Any

            For the location events (button and key press/release), if the
            mouse is over the axes, the ``inaxes`` attribute of the event will
            be set to the `~matplotlib.axes.Axes` the event occurs is over, and
            additionally, the variables ``xdata`` and ``ydata`` attributes will
            be set to the mouse location in data coordinates.  See `.KeyEvent`
            and `.MouseEvent` for more info.

        Returns
        -------
        cid
            A connection id that can be used with
            `.FigureCanvasBase.mpl_disconnect`.

        Examples
        --------
        ::

            def on_press(event):
                print('you pressed', event.button, event.xdata, event.ydata)

            cid = canvas.mpl_connect('button_press_event', on_press)
        )r   connect)r-   r/   r  r   r   r    r    s    5zFigureCanvasBase.mpl_connectc             C   s   | j j|S )z
        Disconnect the callback with id *cid*.

        Examples
        --------
        ::

            cid = canvas.mpl_connect('button_press_event', on_press)
            # ... later
            canvas.mpl_disconnect(cid)
        )r   Z
disconnect)r-   cidr   r   r    mpl_disconnect	  s    zFigureCanvasBase.mpl_disconnectc             C   s   | j ||dS )a  
        Create a new backend-specific subclass of `.Timer`.

        This is useful for getting periodic events through the backend's native
        event loop.  Implemented only for backends with GUIs.

        Parameters
        ----------
        interval : int
            Timer interval in milliseconds.

        callbacks : List[Tuple[callable, Tuple, Dict]]
            Sequence of (func, args, kwargs) where ``func(*args, **kwargs)``
            will be executed by the timer every *interval*.

            Callbacks which return ``False`` or ``0`` will be removed from the
            timer.

        Examples
        --------
        >>> timer = fig.canvas.new_timer(callbacks=[(f1, (1,), {'a': 3})])
        )r   r   )
_timer_cls)r-   r   r   r   r   r    	new_timer/	  s    zFigureCanvasBase.new_timerc             C   s   dS )zu
        Flush the GUI events for the figure.

        Interactive backends need to reimplement this method.
        Nr   )r-   r   r   r    flush_eventsH	  s    zFigureCanvasBase.flush_eventsr   c             C   sR   |dkrt j}d}d}d| _x0| jrL|| |k rL| j  tj| |d7 }qW dS )aK  
        Start a blocking event loop.

        Such an event loop is used by interactive functions, such as
        `~.Figure.ginput` and `~.Figure.waitforbuttonpress`, to wait for
        events.

        The event loop blocks until a callback function triggers
        `stop_event_loop`, or *timeout* is reached.

        If *timeout* is 0 or negative, never timeout.

        Only interactive backends need to reimplement this method and it relies
        on `flush_events` being properly implemented.

        Interactive backends should implement this in a more native way.
        r   g{Gz?Tri   N)rY   inf_loopingr  timesleep)r-   timeoutZtimestepcounterr   r   r    start_event_loopO	  s    
z!FigureCanvasBase.start_event_loopc             C   s
   d| _ dS )z
        Stop the current blocking event loop.

        Interactive backends need to reimplement this to match
        `start_event_loop`
        FN)r  )r-   r   r   r    stop_event_loopk	  s    z FigureCanvasBase.stop_event_loop)N)N)N)N)N)FN)N)N)N)NN)NNNr  N)NN)r   )<r   r   r   r   r  eventsr  r   r  r   Z_classpropertyrx  r*   classmethodrd  	lru_cachery  r   r  r  r  r  r  rl  rk  rv  rm  rn  rs  rq  ro  rp  rr  r  r  r  r  r  r=  r  
deprecatedr  r   r  r  rA  rO  r?  r  r  r  r  r  r  r   r  r  r  r  r  r   r   r   r    rj  l  s   
	











%  7

rj  c              C   sd  | j dkrdS |dkr| j}|dkr*|j}td }td }td }td }td }td }td }	td	 }
td
 }td }td }td }td }tjtd}| j |kry|jj  W n tk
r   Y nX | j |
krt	j
|j | j |krt	j  |dk	r| j |kr|j  n| j |kr*|j  nj| j |kr@|j  nT| j |kr`|j  |j|  n4| j |kr|j  |j|  n| j |	kr|j  | jdkrdS dd }| j}| j |krzd||jj||jjgkrz||jj}||jj}d d!d"d#g}y&||j||fd t|  \}}W n tk
r<   Y n>X |j||rNdnddd |j||rhdnddd |j  | j |kr2d||jj||jjgkr2||jj}||jj}d$d%d&d'g}y&||j||fd t|  \}}W n tk
r   Y n*X |j|ddd |j|ddd |j  n.| j |kr|j }|dkrh|jd |jjj  nb|dkr`y|jd W n< tk
r } zt j!t"| |jd W Y dd}~X nX |jjj  n| j |krh|j# }|dkr|j$d |jjj  nb|dkr`y|j$d W n< tk
rX } zt j!t"| |j$d W Y dd}~X nX |jjj  n| j |krx|jj% D ]B}| j&dk	r| j'dk	r|j(| rt)j*ddd |j+d qW n| j j, r`| j dkr`t-| j d }|t|jj% k r`x\t.|jj% D ]J\}}| j&dk	r| j'dk	r|j(| rt)j*ddd |j+||k qW dS )(a  
    Implement the default Matplotlib key bindings for the canvas and toolbar
    described at :ref:`key-event-handling`.

    Parameters
    ----------
    event : `KeyEvent`
        A key press/release event.
    canvas : `FigureCanvasBase`, default: ``event.canvas``
        The backend-specific canvas instance.  This parameter is kept for
        back-compatibility, but, if set, should always be equal to
        ``event.canvas``.
    toolbar : `NavigationToolbar2`, default: ``event.canvas.toolbar``
        The navigation cursor toolbar.  This parameter is kept for
        back-compatibility, but, if set, should always be equal to
        ``event.canvas.toolbar``.
    Nzkeymap.fullscreenzkeymap.homezkeymap.backzkeymap.forwardz
keymap.panzkeymap.zoomzkeymap.savezkeymap.quitzkeymap.quit_allzkeymap.gridzkeymap.grid_minorzkeymap.yscalezkeymap.xscalezkeymap.all_axesc             S   s4   t dd | D rdS tdd | D s,dS d S d S )Nc             s   s   | ]}|j j V  qd S )N)gridliner  )r   tickr   r   r    	<genexpr>	  s    zDkey_press_handler.<locals>._get_uniform_gridstate.<locals>.<genexpr>Tc             s   s   | ]}|j j V  qd S )N)r  r  )r   r  r   r   r    r  	  s    F)allr   )Zticksr   r   r    _get_uniform_gridstate	  s
    z1key_press_handler.<locals>._get_uniform_gridstateFTri   majorZbothr?   )whichZaxisr@   logZlinearz3.3ziToggling axes navigation from the keyboard is deprecated since %(since)s and will be removed %(removal)s.)rl   0)FF)TF)TT)FT)FF)TF)TT)FT)/r1  r  r  r   dict__getitem__r}  full_screen_toggler  r   Zdestroy_figrE  Zdestroy_allhomebackforwardpan_update_cursorzoomsave_figurer  xaxisZ
minorTicksyaxisZ
majorTicksr  r;   r   Zgridr  Z
get_yscaleZ
set_yscale_logwarningr#   Z
get_xscaleZ
set_xscaler  r?   r@   in_axesr   ro   Zset_navigateisdigitr   	enumerate)r  r  r  Zfullscreen_keysZ	home_keysZ	back_keysZforward_keysZpan_keysZ	zoom_keysZ	save_keysZ	quit_keysZquit_all_keysZ	grid_keysZgrid_minor_keysZtoggle_yscale_keysZtoggle_xscale_keysZall_keysr  r  Zx_stateZy_statecycler   rH  Zscalexr  nrh   r   r   r    key_press_handleru	  s    








&&







r  c             C   s`   |dkr| j }|dkr|j}|dk	r\tt| j}|td krH|j  n|td kr\|j  dS )z
    The default Matplotlib button actions for extra mouse buttons.

    Parameters are as for `key_press_handler`, except that *event* is a
    `MouseEvent`.
    Nzkeymap.backzkeymap.forward)r  r  r#   r&  r0  r   r  r  )r  r  r  Zbutton_namer   r   r    button_press_handler.
  s    
r  c               @   s   e Zd ZdZdS )NonGuiExceptionz6Raised when trying show a figure in a non-GUI backend.N)r   r   r   r   r   r   r   r    r  A
  s   r  c               @   sn   e Zd ZdZdd Zejdedd Zdd Z	d	d
 Z
dd Zdd Zdd Zdd Zdd Zdd ZdS )FigureManagerBasea(  
    A backend-independent abstraction of a figure container and controller.

    The figure manager is used by pyplot to interact with the window in a
    backend-independent way. It's an adapter for the real (GUI) framework that
    represents the visual figure on screen.

    GUI backends define from this class to translate common operations such
    as *show* or *resize* to the GUI-specific code. Non-GUI backends do not
    support these operations an can just use the base class.

    This following basic operations are accessible:

    **Window operations**

    - `~.FigureManagerBase.show`
    - `~.FigureManagerBase.destroy`
    - `~.FigureManagerBase.full_screen_toggle`
    - `~.FigureManagerBase.resize`
    - `~.FigureManagerBase.get_window_title`
    - `~.FigureManagerBase.set_window_title`

    **Key and mouse button press handling**

    The figure manager sets up default key and mouse button press handling by
    hooking up the `.key_press_handler` to the matplotlib event system. This
    ensures the same shortcuts and mouse actions across backends.

    **Other operations**

    Subclasses will have additional attributes and functions to access
    additional functionality. This is of course backend-specific. For example,
    most GUI backends have ``window`` and ``toolbar`` attributes that give
    access to the native GUI widgets of the respective framework.

    Attributes
    ----------
    canvas : `FigureCanvasBase`
        The backend-specific canvas instance.

    num : int or str
        The figure number.

    key_press_handler_id : int
        The default key handler cid, when using the toolmanager.
        To disable the default key press handling use::

            figure.canvas.mpl_disconnect(
                figure.canvas.manager.key_press_handler_id)

    button_press_handler_id : int
        The default mouse button handler cid, when using the toolmanager.
        To disable the default button press handling use::

            figure.canvas.mpl_disconnect(
                figure.canvas.manager.button_press_handler_id)
    c                s   | _  |_| _d  _d  _td dkrN j jd j _ j jd j _t	jd dkrft
|jnd  _d  _ j jj fdd}d S )Nr  toolmanagerrm  ro  c                s"    j d kr jd k	r jj  d S )N)r  r  r9  )fig)r-   r   r    notify_axes_change
  s    z6FigureManagerBase.__init__.<locals>.notify_axes_change)r  r}  numZkey_press_handler_idZbutton_press_handler_idr   r  	key_pressbutton_pressmplr   rE  r  r  Zadd_axobserver)r-   r  r  r  r   )r-   r    r*   
  s     

zFigureManagerBase.__init__z3.3c             C   s   d S )Nr   )r-   r   r   r    	statusbar
  s    zFigureManagerBase.statusbarc             C   s"   t j dkrtdt  ddS )a  
        For GUI backends, show the figure window and redraw.
        For non-GUI backends, raise an exception, unless running headless (i.e.
        on Linux with an unset DISPLAY); this exception is converted to a
        warning in `.Figure.show`.
        ZheadlesszMatplotlib is currently using z8, which is a non-GUI backend, so cannot show the figure.N)r   Z"_get_running_interactive_frameworkr  r   )r-   r   r   r    show
  s    zFigureManagerBase.showc             C   s   d S )Nr   )r-   r   r   r    destroy
  s    zFigureManagerBase.destroyc             C   s   d S )Nr   )r-   r   r   r    r  
  s    z$FigureManagerBase.full_screen_togglec             C   s   dS )z0For GUI backends, resize the window (in pixels).Nr   )r-   r   r   r   r   r    r  
  s    zFigureManagerBase.resizec             C   s   t d dkrt| dS )zm
        Implement the default Matplotlib key bindings defined at
        :ref:`key-event-handling`.
        r  r  N)r   r  )r-   r  r   r   r    r  
  s    zFigureManagerBase.key_pressc             C   s   t d dkrt| dS )z>The default Matplotlib button actions for extra mouse buttons.r  r  N)r   r  )r-   r  r   r   r    r   
  s    zFigureManagerBase.button_pressc             C   s   dS )z
        Return the title text of the window containing the figure, or None
        if there is no window (e.g., a PS backend).
        r  r   )r-   r   r   r    r  
  s    z"FigureManagerBase.get_window_titlec             C   s   dS )z
        Set the title text of the window containing the figure.

        This has no effect for non-GUI (e.g., PS) backends.
        Nr   )r-   r  r   r   r    r  
  s    z"FigureManagerBase.set_window_titleN)r   r   r   r   r*   r   r  r  r  r  r  r  r  r  r   r  r  r   r   r   r    r  F
  s   9r  c               @   s,   e Zd ZdZdZdZdd Zedd ZdS )	_Moder   zpan/zoomz	zoom rectc             C   s   | j S )N)value)r-   r   r   r    r4  
  s    z_Mode.__str__c             C   s   | t jk	r| jS d S )N)r  NONEr  )r-   r   r   r    _navigate_mode
  s    z_Mode._navigate_modeN)	r   r   r   r  PANZOOMr4  r  r  r   r   r   r    r  
  s
   r  c                   sP  e Zd ZdZdeZ fddZdd Zd d! Zd"d# Zd$d% Z	d&d' Z
d(d) Zejd*d+d,d-d. Zd/d0 Zed1d2 Zd3d4 Zd5d6 Zejd*d7d8 Zejd*d9d: Zd;d< Z fd=d>Zd?d@ Z fdAdBZdCdD Z fdEdFZdGdH Z fdIdJZdKdL Zejd*dMd,dNdO ZdPdQ Z dRdS Z!dTdU Z"dVdW Z#dXdY Z$dZd[ Z%  Z&S )fNavigationToolbar2a?  
    Base class for the navigation cursor, version 2.

    Backends must implement a canvas that handles connections for
    'button_press_event' and 'button_release_event'.  See
    :meth:`FigureCanvasBase.mpl_connect` for more information.

    They must also define

      :meth:`save_figure`
         save the current figure

      :meth:`set_cursor`
         if you want the pointer icon to change

      :meth:`draw_rubberband` (optional)
         draw the zoom to rect "rubberband" rectangle

      :meth:`set_message` (optional)
         display message

      :meth:`set_history_buttons` (optional)
         you can change the history back / forward buttons to
         indicate disabled / enabled state.

    and override ``__init__`` to set up the toolbar -- without forgetting to
    call the base-class init.  Typically, ``__init__`` needs to set up toolbar
    buttons connected to the `home`, `back`, `forward`, `pan`, `zoom`, and
    `save_figure` methods and using standard icons in the "images" subdirectory
    of the data path.

    That's it, we'll do the rest!
    HomeReset original viewr  BackBack to previous viewr  ForwardForward to next viewr  NPanFLeft button pans, Right button zooms
x/y fixes axis, CTRL fixes aspectmover  Zoom3Zoom to rectangle
x/y fixes axis, CTRL fixes aspectzoom_to_rectr  SubplotsConfigure subplotssubplotsconfigure_subplotsSaveSave the figurefilesaver  c                s   || _ | |_tj | _d | _tj| _tj	 j
| dddd}|rD|  | j jd| j| _| j jd| j| _| j jd| j| _d | _d | _tj| _| j  d S )NTz3.3zPlease fully initialize the toolbar in your subclass' __init__; a fully empty _init_toolbar implementation may be kept for compatibility with earlier versions of Matplotlib.)Zallow_emptysinceZaddendumro  rp  rr  )r  r  r   ZStack
_nav_stack_xypresscursorsPOINTER_lastCursor_deprecate_method_override_init_toolbarr  _zoom_pan_handlerZ	_id_pressZ_id_release
mouse_move_id_drag
_zoom_info_button_pressedr  r  modeset_history_buttons)r-   r  init)r.   r   r    r*     s(    

zNavigationToolbar2.__init__c             C   s   dS )z.Display a message on toolbar or in status bar.Nr   )r-   r/   r   r   r    set_message8  s    zNavigationToolbar2.set_messagec             C   s   dS )z
        Draw a rectangle rubberband to indicate zoom limits.

        Note that it is not guaranteed that ``x0 <= x1`` and ``y0 <= y1``.
        Nr   )r-   r  Zx0Zy0x1y1r   r   r    draw_rubberband;  s    z"NavigationToolbar2.draw_rubberbandc             C   s   dS )zRemove the rubberband.Nr   )r-   r   r   r    remove_rubberbandB  s    z$NavigationToolbar2.remove_rubberbandc             G   s   | j j  | j  | j  dS )z
        Restore the original view.

        For convenience of being directly connected as a GUI callback, which
        often get passed additional parameters, this method accepts arbitrary
        parameters, but does not use them.
        N)r   r  r-  _update_view)r-   r   r   r   r    r  E  s    
zNavigationToolbar2.homec             G   s   | j j  | j  | j  dS )z
        Move back up the view lim stack.

        For convenience of being directly connected as a GUI callback, which
        often get passed additional parameters, this method accepts arbitrary
        parameters, but does not use them.
        N)r   r  r-  r4  )r-   r   r   r   r    r  Q  s    
zNavigationToolbar2.backc             G   s   | j j  | j  | j  dS )z
        Move forward in the view lim stack.

        For convenience of being directly connected as a GUI callback, which
        often get passed additional parameters, this method accepts arbitrary
        parameters, but does not use them.
        N)r   r  r-  r4  )r-   r   r   r   r    r  ]  s    
zNavigationToolbar2.forwardz3.3r*   )alternativec             C   s   t dS )a  
        This is where you actually build the GUI widgets (called by
        __init__).  The icons ``home.xpm``, ``back.xpm``, ``forward.xpm``,
        ``hand.xpm``, ``zoom_to_rect.xpm`` and ``filesave.xpm`` are standard
        across backends (there are ppm versions in CVS also).

        You just need to set the callbacks

        home         : self.home
        back         : self.back
        forward      : self.forward
        hand         : self.pan
        zoom_to_rect : self.zoom
        filesave     : self.save_figure

        You only need to define the last one - the others are in the base
        class implementation.

        N)r3   )r-   r   r   r    r&  i  s    z NavigationToolbar2._init_toolbarc             C   s   |j  s| j r2| jtjkr| jtj tj| _nZ| jtjkr`| jtjkr`| jtj tj| _n,| jtj	kr| jtj
kr| jtj
 tj
| _dS )zV
        Update the cursor after a mouse move event or a tool (de)activation.
        N)r  r,  r$  r"  r#  
set_cursorr  r
  ZSELECT_REGIONr	  ZMOVE)r-   r  r   r   r    r    s    

z!NavigationToolbar2._update_cursorc             c   s\   t j  t| dtj  | _}| j| dkrRz| jtj dV  W d| j| j X ndV  dS )a  
        Set the cursor to a wait cursor when drawing the canvas.

        In order to avoid constantly changing the cursor when the canvas
        changes frequently, do nothing if this context was triggered during the
        last second.  (Optimally we'd prefer only setting the wait cursor if
        the *current* draw takes too long, but the current draw blocks the GUI
        thread).
        
_draw_timeri   N)	r  r@  rY   r  r7  r6  r"  ZWAITr$  )r-   Zlast_draw_timer   r   r    _wait_cursor_for_draw_cm  s    
z+NavigationToolbar2._wait_cursor_for_draw_cmc                s   | j    jr jj ry jj j j}W n ttfk
rH   Y qX |j } fdd jj	D }|rt
j|}| jjk	r|j }|d k	r|j|j }|r|d | }| j| n| j| j d S )Nc                s&   g | ]}|j  d  r|j r|qS )r   )containsr  )r   r  )r  r   r    r    s    z1NavigationToolbar2.mouse_move.<locals>.<listcomp>
)r  r  get_navigateZformat_coordr  r  r   OverflowErrorr  Z_mouseover_setr   r  r  Zget_cursor_dataZformat_cursor_datar/  r,  )r-   r  r/   Zartistsr  rk   Zdata_strr   )r  r    r(    s$    


zNavigationToolbar2.mouse_movec             C   sp   | j tjkr6|jdkr"| j| n|jdkr6| j| | j tjkrl|jdkrX| j| n|jdkrl| j| d S )Nro  rp  )	r,  r  r	  r  	press_panrelease_panr
  
press_zoomrelease_zoom)r-   r  r   r   r    r'    s    




z$NavigationToolbar2._zoom_pan_handlerc             C   s   dS )z*Called whenever a mouse button is pressed.Nr   )r-   r  r   r   r    press  s    zNavigationToolbar2.pressc             C   s   dS )z"Callback for mouse button release.Nr   )r-   r  r   r   r    release  s    zNavigationToolbar2.releasec             G   sl   | j tjkr$tj| _ | jjj|  ntj| _ | jj|  x"| jjj D ]}|j	| j j
 qFW | j| j  dS )z[
        Toggle the pan/zoom tool.

        Pan with left button, zoom with right.
        N)r,  r  r	  r  r  r~  rB  rE  r  set_navigate_moder  r/  )r-   r   r  r   r   r    r    s    zNavigationToolbar2.panc                s   |j dkr|j | _n
d| _dS | j dkr2| j  |j|j }}g | _xt| jj	j
 D ]r\}}|dk	rX|dk	rX|j|rX|j rX|j rX|j|||j  | jj||f | jj| j | jjd| j| _qXW tj j| ddd}|dk	r|| dS )	z1Callback for mouse button press in pan/zoom mode.ri   rn   Nrr  z3.3zCalling an overridden press() at pan start is deprecated since %(since)s and will be removed %(removal)s; override press_pan() instead.)r  rl   )ri   rn   )r0  r+  r   push_currentr?   r@   r!  r  r  rE  r  r  r;  Zcan_panZ	start_panr  r  r)  r  drag_panr   r%  rA  )r-   r  r?   r@   rh   r  rA  )r.   r   r    r=    s(    

zNavigationToolbar2.press_panc             C   s:   x*| j D ] \}}|j| j|j|j|j qW | jj  dS )z'Callback for dragging in pan/zoom mode.N)r!  rE  r+  r1  r?   r@   r  r  )r-   r  r  indr   r   r    rE     s    zNavigationToolbar2.drag_panc                s   | j dkrdS | jj| j | jjd| j| _x| jD ]\}}|j  q6W | jsTdS g | _d| _ | j  t	j
 j| ddd}|dk	r|| | j  dS )z3Callback for mouse button release in pan/zoom mode.Nrr  z3.3zCalling an overridden release() at pan stop is deprecated since %(since)s and will be removed %(removal)s; override release_pan() instead.)r  rl   )r+  r  r  r)  r  r(  r!  Zend_panrD  r   r%  rA  r<  )r-   r  r  rF  rB  )r.   r   r    r>    s"    
zNavigationToolbar2.release_panc             G   sl   | j tjkr$tj| _ | jjj|  ntj| _ | jj|  x"| jjj D ]}|j	| j j
 qFW | j| j  dS )zToggle zoom to rect mode.N)r,  r  r
  r  r  r~  rB  rE  r  rC  r  r/  )r-   r   r  r   r   r    r    s    zNavigationToolbar2.zoomc                s    j dkrdS  jdks" jdkr&dS  fdd| jjj D }|sHdS | j dkr\| j  | jjd| j	} j dkrzdnd j jf||d	| _
tjj| d
dd}|dk	r|  dS )z5Callback for mouse button press in zoom to rect mode.ri   rn   Nc                s*   g | ]"}|j  r|j r|j r|qS r   )r  r;  Zcan_zoom)r   r  )r  r   r    r  1  s    z1NavigationToolbar2.press_zoom.<locals>.<listcomp>rr  inout)	directionstart_xyr  r  z3.3zCalling an overridden press() at zoom start is deprecated since %(since)s and will be removed %(removal)s; override press_zoom() instead.)r  rl   )ri   rn   )r0  r?   r@   r  rE  r  r   rD  r  	drag_zoomr*  r   r%  rA  )r-   r  r  Zid_zoomrA  )r.   )r  r    r?  +  s&    



zNavigationToolbar2.press_zoomc             C   s   | j d }| j d d }tj||j|jgg|jj|jj\\}}\}}|jdkr^|jj	\}}n|jdkrt|jj
\}}| j||||| dS )z#Callback for dragging in zoom mode.rJ  r  r   r?   r@   N)r*  rY   Zclipr?   r@   r  minrc   r1  Z	intervalyZ	intervalxr2  )r-   r  rJ  r  r0  r1  Zx2y2r   r   r    rK  F  s    
*

zNavigationToolbar2.drag_zoomc       
         st  | j dkrdS | jj| j d  | j  | j d \}}xt| j d D ]\} |j|j }}t|| dk rv|jdkst|| dk r|jdkrd| _	t
jj| dd	d
}|dk	r|| | j  dS t fdd| j d d| D }t fdd| j d d| D }	 j||||f| j d |j||	 qFW | j  d| _ | j  t
jj| dd	d
}|dk	rp|| dS )z7Callback for mouse button release in zoom to rect mode.Nr  rJ  r     r@   r?   z3.3zCalling an overridden release() at zoom stop is deprecated since %(since)s and will be removed %(removal)s; override release_zoom() instead.)r  rl   c             3   s   | ]} j  j |V  qd S )N)Zget_shared_x_axesjoined)r   prev)r  r   r    r  r  s   z2NavigationToolbar2.release_zoom.<locals>.<genexpr>c             3   s   | ]} j  j |V  qd S )N)Zget_shared_y_axesrO  )r   rP  )r  r   r    r  t  s   rI  )r*  r  r  r3  r  r?   r@   absr1  r!  r   r%  rA  r<  r   Z_set_view_from_bboxrD  rB  )
r-   r  Zstart_xZstart_yrh   r?   r@   rB  ZtwinxZtwiny)r.   )r  r    r@  R  s<    

zNavigationToolbar2.release_zoomc             C   s,   | j jtdd | jjjD  | j  dS )z9Push the current view limits and position onto the stack.c             S   s0   i | ](}|j  |jd j |j j ff|qS )T)Z	_get_viewget_positionrE   )r   r  r   r   r    r     s   z3NavigationToolbar2.push_current.<locals>.<dictcomp>N)r   pushr   r  rE  r  r-  )r-   r   r   r    rD    s
    zNavigationToolbar2.push_currentztoolbar.canvas.draw_idle()c             C   s   | j   dS )z)Redraw the canvases, update the locators.N)r<  )r-   r   r   r    r=    s    zNavigationToolbar2.drawc             C   s   x| j jj D ]}t|dd }t|dd }g }|d k	rR|j|j  |j|j  |d k	rv|j|j  |j|j  x|D ]}tjj	| q|W qW | j j
  d S )Nr  r  )r  rE  r  r@  r  Zget_major_locatorZget_minor_locatorr  ZtickerZ+_if_refresh_overridden_call_and_emit_deprecr  )r-   r  r  r  Zlocatorslocr   r   r    r<    s    
zNavigationToolbar2._drawc             C   sj   | j  }|dkrdS t|j }x:|D ]2\}\}\}}|j| |j|d |j|d q&W | jj  dS )zi
        Update the viewlim and position from the view and position stack for
        each axes.
        Noriginalactive)r   rD   r  Z	_set_viewZ_set_positionr  r  )r-   Znav_infor  r  viewZpos_origZ
pos_activer   r   r    r4    s    
zNavigationToolbar2._update_viewc             G   s   t dS )zSave the current figure.N)r3   )r-   r   r   r   r    r    s    zNavigationToolbar2.save_figurec             C   s   dS )aL  
        Set the current cursor to one of the :class:`Cursors` enums values.

        If required by the backend, this method should trigger an update in
        the backend event loop after the cursor is set, as this method may be
        called e.g. before a long-running task during which the GUI is not
        updated.
        Nr   )r-   cursorr   r   r    r6    s    zNavigationToolbar2.set_cursorc             C   s   | j j  | j  dS )zReset the axes stack.N)r   clearr-  )r-   r   r   r    r9    s    
zNavigationToolbar2.updatec             C   s   dS )z*Enable or disable the back/forward button.Nr   )r-   r   r   r    r-    s    z&NavigationToolbar2.set_history_buttonsr  r  r  r  r  r  r  r  r  r  r  r  NNNNr  r  r  r  r  r  r  r  r  r  r  r  NNNNr  r  r  r  )	rZ  r[  r\  r]  r^  r_  r`  ra  rb  )'r   r   r   r   Z	toolitemsr*   r/  r2  r3  r  r  r  r   r  r&  r  r   r8  r(  r'  rA  rB  r  r=  rE  r>  r  r?  rK  r@  rD  r=  r<  r4  r  r6  r9  r-  r   r   r   )r.   r    r  
  sV   !
           5
r  c               @   s^   e Zd ZdZdZdd Zdd Zddd	Zd
d Zdd Z	dd Z
dd Zdd Zdd ZdS )ToolContainerBasez
    Base class for all tool containers, e.g. toolbars.

    Attributes
    ----------
    toolmanager : `.ToolManager`
        The tools with which this `ToolContainer` wants to communicate.
    z.pngc                s2   | _ |jd fdd |jd fdd d S )Ntool_message_eventc                s    j | jS )N)r/  rl   )r  )r-   r   r    r     s    z,ToolContainerBase.__init__.<locals>.<lambda>Ztool_removed_eventc                s    j | jjS )N)remove_toolitemtoolr  )r  )r-   r   r    r     s    )r  toolmanager_connect)r-   r  r   )r-   r    r*     s    zToolContainerBase.__init__c             C   s   | j |jj|jj dS )zc
        Capture the 'tool_trigger_[name]'

        This only gets used for toggled tools.
        N)toggle_toolitemrf  r  toggled)r-   r  r   r   r    _tool_toggled_cbk  s    z#ToolContainerBase._tool_toggled_cbkri   c             C   sr   | j j|}| j|j}t|dddk	}| j|j||||j| |rn| j jd|j | j	 |j
rn| j|jd dS )aV  
        Add a tool to this container.

        Parameters
        ----------
        tool : tool_like
            The tool to add, see `.ToolManager.get_tool`.
        group : str
            The name of the group to add this tool to.
        position : int, default: -1
            The position within the group to place this tool.
        ri  Nztool_trigger_%sT)r  Zget_tool_get_image_filenamer  r@  add_toolitemr  r   rg  rj  ri  rh  )r-   rf  grouppositionr  toggler   r   r    add_tool  s    zToolContainerBase.add_toolc             C   sX   |sdS t jd}x@||| j t|| t||| j  gD ]}tjj|r<|S q<W dS )z!Find the image based on its name.NZimages)r   Z_get_data_path_icon_extensionr#   r  r5   isfile)r-   r  basedirfnamer   r   r    rk    s    

z%ToolContainerBase._get_image_filenamec             C   s   | j j|| d dS )z
        Trigger the tool.

        Parameters
        ----------
        name : str
            Name (id) of the tool triggered from within the container.
        )ZsenderN)r  trigger_tool)r-   r  r   r   r    ru    s    	zToolContainerBase.trigger_toolc             C   s   t dS )a  
        Add a toolitem to the container.

        This method must be implemented per backend.

        The callback associated with the button click event,
        must be *exactly* ``self.trigger_tool(name)``.

        Parameters
        ----------
        name : str
            Name of the tool to add, this gets used as the tool's ID and as the
            default label of the buttons.
        group : str
            Name of the group that this tool belongs to.
        position : int
            Position of the tool within its group, if -1 it goes at the end.
        image_file : str
            Filename of the image for the button or `None`.
        description : str
            Description of the tool, used for the tooltips.
        toggle : bool
            * `True` : The button is a toggle (change the pressed/unpressed
              state between consecutive clicks).
            * `False` : The button is a normal button (returns to unpressed
              state after release).
        N)r3   )r-   r  rm  rn  r  r   ro  r   r   r    rl  '  s    zToolContainerBase.add_toolitemc             C   s   t dS )z
        Toggle the toolitem without firing event.

        Parameters
        ----------
        name : str
            Id of the tool to toggle.
        toggled : bool
            Whether to set this tool as toggled or not.
        N)r3   )r-   r  ri  r   r   r    rh  E  s    z!ToolContainerBase.toggle_toolitemc             C   s   t dS )a  
        Remove a toolitem from the `ToolContainer`.

        This method must get implemented per backend.

        Called when `.ToolManager` emits a `tool_removed_event`.

        Parameters
        ----------
        name : str
            Name of the tool to remove.
        N)r3   )r-   r  r   r   r    re  R  s    z!ToolContainerBase.remove_toolitemc             C   s   t dS )z
        Display a message on the toolbar.

        Parameters
        ----------
        s : str
            Message text.
        N)r3   )r-   r/   r   r   r    r/  a  s    	zToolContainerBase.set_messageN)rv  )r   r   r   r   rq  r*   rj  rp  rk  ru  rl  rh  re  r/  r   r   r   r    rc    s   	
rc  z3.3c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	StatusbarBasezBase class for the statusbar.c             C   s   || _ | j jd| j d S )Nrd  )r  rg  _message_cbk)r-   r  r   r   r    r*   p  s    zStatusbarBase.__init__c             C   s   | j |j dS )z5Capture the 'tool_message_event' and set the message.N)r/  rl   )r-   r  r   r   r    rx  u  s    zStatusbarBase._message_cbkc             C   s   dS )z
        Display a message on toolbar or in status bar.

        Parameters
        ----------
        s : str
            Message text.
        Nr   )r-   r/   r   r   r    r/  y  s    zStatusbarBase.set_messageN)r   r   r   r   r*   rx  r/  r   r   r   r    rw  m  s   rw  c               @   sb   e Zd ZdZdZeZdZdZe	dd Z
e	dd Ze	dd Ze	dd	d
dZedd ZdS )_BackendunknownNc             O   s.   ddl m} |jd|}|||}| j||S )z%Create a new figure manager instance.r   )FigureZFigureClass)Zmatplotlib.figurer{  r
  new_figure_manager_given_figure)rw  r  r   r   r{  Zfig_clsr  r   r   r    new_figure_manager  s    
z_Backend.new_figure_managerc             C   s   | j |}| j||}|S )z:Create a new figure manager instance for the given figure.)r&   FigureManager)rw  r  rE  r  r}  r   r   r    r|    s    
z(_Backend.new_figure_manager_given_figurec             C   s*   | j d k	r&t r&tj }|r&| j | d S )N)trigger_manager_drawr   r   Z
get_active)rw  r}  r   r   r    draw_if_interactive  s    z_Backend.draw_if_interactive)blockc            C   s   t j }|sdS xJ|D ]B}y|j  W q tk
rV } ztjt| W Y dd}~X qX qW | jdkrjdS |dkrddlm	} y|jj
 }W n tk
r   d}Y nX | ot  }t dkrd}|r| j  dS )z
        Show all figures.

        `show` blocks by calling `mainloop` if *block* is ``True``, or if it
        is ``None`` and we are neither in IPython's ``%pylab`` mode, nor in
        `interactive` mode.
        Nr   )pyplotFZWebAggT)r   Zget_all_fig_managersr  r  r   Z_warn_externalr#   mainloop
matplotlibr  Z	_needmainr  r   r   )rw  r  Zmanagersr}  rH  r  Zipython_pylabr   r   r    r    s*    	
$


z_Backend.showc                sT   x&d
D ]}t tj j |t | qW G  fdd	d	t}t tj j d	|  S )Nbackend_versionr&   r~  r}  r|  r  r  c                   s   e Zd Z fddZdS )z_Backend.export.<locals>.Showc                s    j  S )N)r  )r-   )rw  r   r    r    s    z&_Backend.export.<locals>.Show.mainloopN)r   r   r   r  r   )rw  r   r    Show  s   r  )r  r&   r~  r}  r|  r  r  )setattrr  r  r   r@  ShowBase)rw  r  r  r   )rw  r    export  s          z_Backend.export)r   r   r   r  r&   r  r~  r  r  r  r}  r|  r  r  staticmethodr  r   r   r   r    ry    s   	%ry  c               @   s   e Zd ZdZdddZdS )r  z}
    Simple base class to generate a ``show()`` function in backends.

    Subclass must override ``mainloop()`` method.
    Nc             C   s   | j |dS )N)r  )r  )r-   r  r   r   r    __call__  s    zShowBase.__call__)N)r   r   r   r   r  r   r   r   r    r    s   r  )N)N)NN)NN)Qr   
contextlibr   r   enumr   r   rd  r$   rg  rB  loggingr  rT  r  r  rV  weakrefr   numpyrY   r  r  r   toolsr   r	   r
   r   r   r   r   r   r   Zmatplotlib._pylab_helpersr   Zmatplotlib.backend_managersr   Zmatplotlib.transformsr   Zmatplotlib.pathr   Zmatplotlib.cbookr   	getLoggerr   r  r   r   r!   r'   r(   r   r   r  r  r  r  r  r&  r-  r5  r:  rI  rM  rf  rj  r  r  r$  r  r  r"  r#   r  r  rc  r  rw  ry  r  r   r   r   r    <module>   s   0

    h  A XK)(
$@      
 :
    t o