a
    Sic`                    @   s  d Z ddlmZ ddlmZ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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#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/ ddl0m1Z1 ddl2m3Z3m4Z4 e5e6Z7dddddddddddddddZ8dddddddddddddddZ9dd  Z:d[d!d"Z;d#d$ Z<G d%d& d&Z=G d'd( d(Z>G d)d* d*Z?G d+d, d,Z@G d-d. d.e@ZAG d/d0 d0e@ZBG d1d2 d2e@ZCG d3d4 d4e@ZDG d5d6 d6e	ZEG d7d8 d8eDZFG d9d: d:e@ZGG d;d< d<eDZHd=d> ZId?d@ ZJd\dAdBZKdCdD ZLdEdF ZMG dGdH dHZNd]dIdJZOd^dKdLZPG dMdN dNeQZRG dOdP dPZSejTZTG dQdR dReUeZVG dSdT dTZWG dUdV dVZXG dWdX dXZYG dYdZ dZeYZZdS )_a  
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.
    )
namedtuple)	ExitStackcontextmanagernullcontext)EnumIntEnumN)WeakKeyDictionary)_apibackend_toolscbookcolors
_docstringtextpath_tight_bbox
transformswidgetsget_backendis_interactivercParams)Gcf)ToolManager)_setattr_cm)Path)
TexManager)Affine2D)	JoinStyleCapStylez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 FormatzWebP Image Format)epsjpgjpegpdfpgfpngpsrawrgbasvgZsvgztiftiffZwebpzmatplotlib.backends.backend_pszmatplotlib.backends.backend_aggzmatplotlib.backends.backend_pdfzmatplotlib.backends.backend_pgfzmatplotlib.backends.backend_svgc                  C   st   zddl m}  W n^ tyn   t }|du r0 ddddddd	d
}|| }| td< tjd< ddl m}  Y n0 | S )zc
    Import and return ``pyplot``, correctly setting the backend if one is
    already forced.
    r   Nqtagggtk3agggtk4aggwxaggtkaggmacosxagg)qtgtk3gtk4wxtkr.   headlessbackend)matplotlib.pyplotpyplotImportErrorr   "_get_running_interactive_frameworkr   mplrcParamsOrig)pltcurrent_frameworkZbackend_mappingr6    r?   T/var/www/html/django/DPS/env/lib/python3.9/site-packages/matplotlib/backend_bases.py_safe_pyplot_import\   s$    	rA   c                 C   s    |du 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)formatr6   descriptionr?   r?   r@   register_backendv   s    rG   c                 C   s6   | t vrdS t |  }t|tr2t|j}|t | < |S )zv
    Return the registered default canvas for given file format.
    Handles deferred import of required backend.
    N)rC   
isinstancestr	importlibimport_moduleFigureCanvas)rE   Zbackend_classr?   r?   r@   get_registered_canvas_class   s    
rM   c                       s   e Zd ZdZ fddZdCddZdd ZdDd	d
ZdEd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dFddZdd  Zd!d" Zdd#d$d%ZdGd'd(Zd)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"  Z#S )H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 `draw_path` alone would give a
    highly capable backend):

    * `draw_path`
    * `draw_image`
    * `draw_gouraud_triangle`

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

    * `draw_text`
    * `draw_markers`
    * `draw_path_collection`
    * `draw_quad_mesh`
    c                    s*   t    d | _t | _d| _d| _d S )Nr   F)super__init___texmanagerr   Z
TextToPath
_text2path_raster_depth_rasterizingself	__class__r?   r@   rP      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?   )rV   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?   rV   rY   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)rV   gcpath	transformrgbFacer?   r?   r@   	draw_path   s    zRendererBase.draw_pathc              
   C   sT   |j |ddD ]@\}}t|r|dd \}	}
| |||t |	|
 | qdS )aj  
        Draw a marker at each of *path*'s vertices (excluding control points).

        The base (fallback) implementation makes multiple calls to `draw_path`.
        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)simplifyN)iter_segmentslenrd   r   r   	translate)rV   r`   marker_pathmarker_transra   transrc   verticescodesxyr?   r?   r@   draw_markers   s    zRendererBase.draw_markersc                 C   s   |  |||}| |t||||||	|
|||D ]J\}}}}}|\}}|dksV|dkrj| }||| | |||| q0dS )a  
        Draw a collection of *paths*.

        Each path is first transformed by the corresponding entry
        in *all_transforms* (a list of (3, 3) matrices) and then by
        *master_transform*.  They are then translated by the corresponding
        entry in *offsets*, which has been first transformed by *offset_trans*.

        *facecolors*, *edgecolors*, *linewidths*, *linestyles*, and
        *antialiased* are lists that set the corresponding properties.

        *offset_position* is unused now, but the argument is kept for
        backwards compatibility.

        The base (fallback) implementation makes multiple calls to `draw_path`.
        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
        `_iter_collection_raw_paths` and `_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 `draw_path_collection` can be made globally.
        r   N)_iter_collection_raw_paths_iter_collectionlistfrozenri   rd   )rV   r`   master_transformpathsall_transformsoffsetsoffset_trans
facecolors
edgecolors
linewidths
linestylesantialiasedsurlsoffset_positionpath_idsxoyoZpath_idgc0rc   ra   rb   r?   r?   r@   draw_path_collection   s    z!RendererBase.draw_path_collectionc                 C   sZ   ddl m} ||}|
du r"|}
t| gt}| |||g ||||
|g |	gdgdS )z
        Draw a quadmesh.

        The base (fallback) implementation converts the quadmesh to paths and
        then calls `draw_path_collection`.
        r   )QuadMeshNscreen)matplotlib.collectionsr   _convert_mesh_to_pathsnparrayget_linewidthfloatr   )rV   r`   rv   	meshWidth
meshHeightcoordinatesry   ZoffsetTransr{   antialiasedr|   r   rw   r}   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 : (3, 2) array-like
            Array of (x, y) points for the triangle.
        colors : (3, 4) array-like
            RGBA colors for each point of the triangle.
        transform : `matplotlib.transforms.Transform`
            An affine transform to apply to the points.
        Nr^   )rV   r`   pointsr   rb   r?   r?   r@   draw_gouraud_triangle!  s    z"RendererBase.draw_gouraud_trianglec                 C   s0   |  }t||D ]\}}| |||| qdS )a  
        Draw a series of Gouraud triangles.

        Parameters
        ----------
        points : (N, 3, 2) array-like
            Array of *N* (x, y) points for the triangles.
        colors : (N, 3, 4) array-like
            Array of *N* RGBA colors for each point of the triangles.
        transform : `matplotlib.transforms.Transform`
            An affine transform to apply to the points.
        N)ru   zipr   )rV   r`   Ztriangles_arrayZcolors_arrayrb   tricolr?   r?   r@   draw_gouraud_triangles2  s    z#RendererBase.draw_gouraud_trianglesc           
      c   sn   t |}t |}t||}|dkr&dS t }t|D ]2}|||  }	|rZt|||  }|	|| fV  q6dS )a  
        Helper method (along with `_iter_collection`) to implement
        `draw_path_collection` in a memory-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
        `draw_path_collection`.

        The backend should take each yielded path and transform and create an
        object that can be referenced (reused) later.
        r   N)rh   maxr   IdentityTransformranger   )
rV   rv   rw   rx   NpathsZNtransformsNrb   ira   r?   r?   r@   rr   D  s    
z'RendererBase._iter_collection_raw_pathsc           	      C   s`   t |}|dks0t |t |  kr,dkr4n nd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      )rh   r   )	rV   rw   rx   ry   r{   r|   r   Z	Npath_idsr   r?   r?   r@   _iter_collection_uses_per_patha  s    
(z+RendererBase._iter_collection_uses_per_pathc           &      c   s  t |}t |}t||}t |}t |}t |}t |}t |
}|dkrR|dksZ|dkr^dS |  }|| d	dd}||}|||d}||}||}||}||}||	}||
}
|dkr|d tt||||||||
|D ]\}\}}} }!}"}#}$}%t	
|rt	
|s"q|rz|r8||" |rH|j|#  t |!dkrp|!d dkrp|d n
||! | durt | dkr| d dkrd} ||$ |r||% ||||| fV  q|  dS )
a  
        Helper method (along with `_iter_collection_raw_paths`) to implement
        `draw_path_collection` in a memory-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 `_iter_collection_raw_paths` to draw
        this collection.

        The arguments should be the same as that passed into
        `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 `_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.
        r   Nc                 S   s   t | rt| S t|S N)rh   	itertoolscyclerepeat)seqdefaultr?   r?   r@   cycle_or_default  s    z7RendererBase._iter_collection.<locals>.cycle_or_default)r   r                 )N)rh   r   new_gccopy_propertiesrb   set_linewidthr   islicer   r   isfinite
set_dashesset_foregroundset_antialiasedset_urlrestore)&rV   r`   r   ry   rz   r{   r|   r}   r~   r   r   r   r   ZNoffsetsr   ZNfacecolorsZNedgecolorsZNlinewidthsZNlinestylesZNurlsr   r   ZpathidsZtoffsetsZfcsZecsZlwsZlssZaasZpathidr   r   fceclwlsaaurlr?   r?   r@   rs   r  sV    






&

zRendererBase._iter_collectionc                 C   s   dS )z
        Get the factor by which to magnify images passed to `draw_image`.
        Allows a backend to have images at a different resolution to other
        artists.
              ?r?   rU   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 : (N, M, 4) array-like of np.uint8
            An array of RGBA pixels.

        transform : `matplotlib.transforms.Affine2DBase`
            If and only if the concrete backend is written such that
            `option_scale_image` returns ``True``, an affine transformation
            (i.e., an `.Affine2DBase`) *may* be passed to `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*).
        Nr^   )rV   r`   ro   rp   imrb   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?   rU   r?   r?   r@   option_image_nocomposite  s    z%RendererBase.option_image_nocompositec                 C   s   dS )z
        Return whether arbitrary affine transformations in `draw_image` are
        supported (True for most vector backends).
        Fr?   rU   r?   r?   r@   option_scale_image  s    zRendererBase.option_scale_image)mtextc             	   C   s   | j ||||||dd dS )z	
        TeXismathN_draw_text_as_path)rV   r`   ro   rp   rY   propangler   r?   r?   r@   draw_tex  s    zRendererBase.draw_texFc	           	   	   C   s   |  ||||||| dS )a  
        Draw a 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.
        Nr   )	rV   r`   ro   rp   rY   r   r   r   r   r?   r?   r@   	draw_text  s    #zRendererBase.draw_textc                 C   s   | j }| | }|j|||d\}	}
t|	|
}t|}|  rv|  \}}t	 
||j |||| }n t	 
||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   )rR   points_to_pixelsget_size_in_pointsZget_text_pathr   r   deg2radflipyget_canvas_width_heightr   scaleZ
FONT_SCALErotateri   )rV   ro   rp   rY   r   r   r   Z	text2pathfontsizevertsrn   ra   widthheightrb   r?   r?   r@   _get_text_path_transform#  s,    

z%RendererBase._get_text_path_transformc                 C   s@   |  ||||||\}}	| }
|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.
        r   )rc   N)r   get_rgbr   rd   )rV   r`   ro   rp   rY   r   r   r   ra   rb   colorr?   r?   r@   r   E  s    
zRendererBase._draw_text_as_pathc                 C   s   |  }|dkr"t j||| dS | d}|rN| jj|||}|dd S | j }| j|}|	|| |j
|d|d | \}	}
| }|	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   r   r   )flagsg      P@)r   r   get_text_width_height_descentr   rR   Zmathtext_parserparseZ_get_hinting_flagZ	_get_fontset_sizeset_textget_width_heightget_descent)rV   rY   r   r   r   dpidimsr   fontwhdr?   r?   r@   r   Z  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.
        Tr?   rU   r?   r?   r@   r   x  s    zRendererBase.flipyc                 C   s   dS )z5Return the canvas width and height in display coords.)r   r   r?   rU   r?   r?   r@   r     s    z$RendererBase.get_canvas_width_heightc                 C   s   | j du rt | _ | j S )z"Return the `.TexManager` instance.N)rQ   r   rU   r?   r?   r@   get_texmanager  s    
zRendererBase.get_texmanagerc                 C   s   t  S )z/Return an instance of a `.GraphicsContextBase`.)GraphicsContextBaserU   r?   r?   r@   r     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?   )rV   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?   rU   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?   rU   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?   rU   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?   )rV   filter_funcr?   r?   r@   stop_filter  s    zRendererBase.stop_filterc                 C   s"   dd t tD }t| fi |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 | ] }| d s|dv r|dd qS )Zdraw_)r[   r]   c                  _   s   d S r   r?   argskwargsr?   r?   r@   <lambda>      z8RendererBase._draw_disabled.<locals>.<dictcomp>.<lambda>)
startswith).0	meth_namer?   r?   r@   
<dictcomp>  s   
z/RendererBase._draw_disabled.<locals>.<dictcomp>)dirrN   r   )rV   Zno_opsr?   r?   r@   _draw_disabled  s    zRendererBase._draw_disabled)N)N)N)N)FN)$__name__
__module____qualname____doc__rP   r[   r]   rd   rq   r   r   r   r   rr   r   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r?   r?   rW   r@   rN      sB   

 
-N
 

%"	rN   c                   @   sB  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ejd&d' Zd(d) Zd*d+ Zd,d- ZdMd/d0Zej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| _td| _d | _d | _d| _td| _	d| _
d| _d| _d | _ttd	 | _td
 | _d | _d | _d | _d | _d S )Nr   Fr   butt)r   Nroundsolid)r   r   r   r   zhatch.colorzhatch.linewidth)_alpha_forced_alpha_antialiasedr   	_capstyle	_cliprect	_clippath_dashesr   
_joinstyle
_linestyle
_linewidth_rgb_hatchr   to_rgbar   _hatch_color_hatch_linewidth_url_gid_snap_sketchrU   r?   r?   r@   rP     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  )rV   r`   r?   r?   r@   r     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?   rU   r?   r?   r@   r      s    zGraphicsContextBase.restorec                 C   s   | j S )zc
        Return the alpha value used for blending - not supported on all
        backends.
        )r  rU   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  rU   r?   r?   r@   get_antialiased  s    z#GraphicsContextBase.get_antialiasedc                 C   s   | j jS )zReturn the `.CapStyle`.)r  namerU   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  rU   r?   r?   r@   get_clip_rectangle  s    z&GraphicsContextBase.get_clip_rectanglec                 C   sD   | j dur@| j  \}}tt|jr2||fS td d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.
        Nz/Ill-defined clip_path detected. Returning None.NN)r	  get_transformed_path_and_affiner   allr   rm   _logwarning)rV   tpathtrr?   r?   r@   get_clip_path  s    

z!GraphicsContextBase.get_clip_pathc                 C   s   | j S )z
        Return the dash style as an (offset, dash-list) pair.

        See `.set_dashes` for details.

        Default value is (None, None).
        )r
  rU   r?   r?   r@   
get_dashes*  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  rU   r?   r?   r@   get_forced_alpha4  s    z$GraphicsContextBase.get_forced_alphac                 C   s   | j jS )zReturn the `.JoinStyle`.)r  r  rU   r?   r?   r@   get_joinstyle;  s    z!GraphicsContextBase.get_joinstylec                 C   s   | j S )z Return the line width in points.)r  rU   r?   r?   r@   r   ?  s    z!GraphicsContextBase.get_linewidthc                 C   s   | j S )z0Return a tuple of three or four floats from 0-1.)r  rU   r?   r?   r@   r   C  s    zGraphicsContextBase.get_rgbc                 C   s   | j S )z+Return a url if one is set, None otherwise.r  rU   r?   r?   r@   get_urlG  s    zGraphicsContextBase.get_urlc                 C   s   | j S )z;Return the object identifier if one is set, None otherwise.r  rU   r?   r?   r@   get_gidK  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  rU   r?   r?   r@   get_snapO  s    	zGraphicsContextBase.get_snapc                 C   s6   |du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.
        NTr   F)isRGBA)r  r  r   r  )rV   alphar?   r?   r@   	set_alphaZ  s    	zGraphicsContextBase.set_alphac                 C   s   t t|| _dS )z>Set whether object should be drawn with antialiased rendering.N)intboolr  )rV   br?   r?   r@   r   k  s    z#GraphicsContextBase.set_antialiasedc                 C   s   t || _dS )z
        Set how to draw endpoints of lines.

        Parameters
        ----------
        cs : `.CapStyle` or %(CapStyle)s
        N)r   r  )rV   csr?   r?   r@   set_capstylep  s    	z GraphicsContextBase.set_capstylec                 C   s
   || _ dS )z,Set the clip rectangle to a `.Bbox` or None.Nr  )rV   Z	rectangler?   r?   r@   set_clip_rectangle{  s    z&GraphicsContextBase.set_clip_rectanglec                 C   s   t jtjdf|d || _dS )z2Set the clip path to a `.TransformedPath` or None.N)ra   )r	   check_isinstancer   TransformedPathr	  )rV   ra   r?   r?   r@   set_clip_path  s    z!GraphicsContextBase.set_clip_pathc                 C   sR   |durDt |}t |dk r(td|jrDt |dksDtd||f| _dS )a]  
        Set the dash style for the gc.

        Parameters
        ----------
        dash_offset : float
            Distance, in points, into the dash pattern at which to
            start the pattern. It is usually set to 0.
        dash_list : array-like or None
            The on-off sequence as points.  None specifies a solid line. All
            values must otherwise be non-negative (:math:`\ge 0`).

        Notes
        -----
        See p. 666 of the PostScript
        `Language Reference
        <https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf>`_
        for more info.
        Nr   z0All values in the dash list must be non-negativez4At least one value in the dash list must be positive)r   asarrayany
ValueErrorsizer
  )rV   Zdash_offsetZ	dash_listdlr?   r?   r@   r     s    
zGraphicsContextBase.set_dashesFc                 C   sV   | j r"|r"|dd | jf | _n0| j r:t|| j| _n|rF|| _nt|| _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.
        Nr   )r  r  r  r   r  )rV   fgr.  r?   r?   r@   r     s    
z"GraphicsContextBase.set_foregroundc                 C   s   t || _dS )z
        Set how to draw connections between line segments.

        Parameters
        ----------
        js : `.JoinStyle` or %(JoinStyle)s
        N)r   r  )rV   jsr?   r?   r@   set_joinstyle  s    	z!GraphicsContextBase.set_joinstylec                 C   s   t || _dS )zSet the linewidth in points.N)r   r  )rV   r   r?   r?   r@   r     s    z!GraphicsContextBase.set_linewidthc                 C   s
   || _ dS )z-Set the url for links in compatible backends.Nr(  )rV   r   r?   r?   r@   r     s    zGraphicsContextBase.set_urlc                 C   s
   || _ dS )zSet the id.Nr*  )rV   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
        Nr,  )rV   snapr?   r?   r@   set_snap  s    	zGraphicsContextBase.set_snapc                 C   s
   || _ dS )z Set the hatch style (for fills).Nr  )rV   hatchr?   r?   r@   	set_hatch  s    zGraphicsContextBase.set_hatchc                 C   s   | j S )zGet the current hatch style.rF  rU   r?   r?   r@   	get_hatch  s    zGraphicsContextBase.get_hatch      @c                 C   s    |   }|du rdS t||S )z'Return a `.Path` for the current hatch.N)rI  r   rG  )rV   densityrG  r?   r?   r@   get_hatch_path  s    z"GraphicsContextBase.get_hatch_pathc                 C   s   | j S )zGet the hatch color.r  rU   r?   r?   r@   get_hatch_color  s    z#GraphicsContextBase.get_hatch_colorc                 C   s
   || _ dS )zSet the hatch color.NrM  )rV   Zhatch_colorr?   r?   r@   set_hatch_color  s    z#GraphicsContextBase.set_hatch_colorc                 C   s   | j S )zGet the hatch linewidth.)r  rU   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  rU   r?   r?   r@   get_sketch_params  s    z%GraphicsContextBase.get_sketch_paramsNc                 C   s$   |du 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@rQ  )rV   r   length
randomnessr?   r?   r@   set_sketch_params  s    z%GraphicsContextBase.set_sketch_params)F)rJ  )NNN)*r   r   r   r   rP   r   r   r  r  r  r  r$  r%  r&  r'  r   r   r)  r+  r-  r0  r   r   interpdr5  r6  r9  r   r   rA  r   r   rC  rE  rH  rI  rL  rN  rO  rP  rR  rU  r?   r?   r?   r@   r     sN   






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u rg n|  | _|du 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rV   rZ  rY  r?   r?   r@   rP   5  s    zTimerBase.__init__c                 C   s   |    dS )z1Need to stop timer and possibly disconnect timer.N_timer_stoprU   r?   r?   r@   __del__G  s    zTimerBase.__del__c                 C   s   |dur|| _ |   dS )z
        Start the timer object.

        Parameters
        ----------
        interval : int, optional
            Timer interval in milliseconds; overrides a previously set interval
            if provided.
        N)rZ  _timer_startrV   rZ  r?   r?   r@   startK  s    
zTimerBase.startc                 C   s   |    dS )zStop the timer.Nr]  rU   r?   r?   r@   stopY  s    zTimerBase.stopc                 C   s   d S r   r?   rU   r?   r?   r@   r`  ]  s    zTimerBase._timer_startc                 C   s   d S r   r?   rU   r?   r?   r@   r^  `  s    zTimerBase._timer_stopc                 C   s   | j S )z/The time between timer events, in milliseconds.)	_intervalrU   r?   r?   r@   rZ  c  s    zTimerBase.intervalc                 C   s   t |}|| _|   d S r   )r1  rd  _timer_set_intervalra  r?   r?   r@   rZ  h  s    c                 C   s   | j S )z2Whether this timer should stop after a single run.)_singlerU   r?   r?   r@   r[  p  s    zTimerBase.single_shotc                 C   s   || _ |   d S r   )rf  _timer_set_single_shot)rV   ssr?   r?   r@   r[  u  s    c                 O   s   | 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.
        )rY  append)rV   funcr   r   r?   r?   r@   add_callbackz  s    zTimerBase.add_callbackc                 O   sX   |s|r*t jddd | j|||f n*dd | jD }||v rT| 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.)messagec                 S   s   g | ]}|d  qS r   r?   )r   cr?   r?   r@   
<listcomp>  r   z-TimerBase.remove_callback.<locals>.<listcomp>N)r	   warn_deprecatedrY  removepopindex)rV   rj  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?   rU   r?   r?   r@   re    s    zTimerBase._timer_set_intervalc                 C   s   dS )z3Used to set single shot on underlying timer object.Nr?   rU   r?   r?   r@   rg    s    z TimerBase._timer_set_single_shotc                 C   sT   | j D ]2\}}}||i |}|dkr| j |||f qt| j dkrP|   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)rY  rq  rh   rc  )rV   rj  r   r   retr?   r?   r@   	_on_timer  s    zTimerBase._on_timer)NN)N)r   r   r   r   rP   r_  rb  rc  r`  r^  propertyrZ  setterr[  rk  ru  re  rg  rw  r?   r?   r?   r@   rW    s(   





rW  c                   @   s"   e Zd ZdZdddZdd ZdS )Eventa  
    A Matplotlib event.

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

    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 r   )r  canvasguiEvent)rV   r  r{  r|  r?   r?   r@   rP     s    zEvent.__init__c                 C   s   | j j| j|  dS )z=Generate an event with name ``self.name`` on ``self.canvas``.N)r{  rY  processr  rU   r?   r?   r@   _process  s    zEvent._process)N)r   r   r   r   rP   r~  r?   r?   r?   r@   rz    s   
rz  c                       s    e Zd ZdZ fddZ  ZS )	DrawEventa  
    An event triggered by a draw operation on the canvas.

    In most backends, callbacks subscribed to this event 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.

    A DrawEvent has a number of special attributes in addition to those defined
    by the parent `Event` class.

    Attributes
    ----------
    renderer : `RendererBase`
        The renderer for the draw event.
    c                    s   t  || || _d S r   )rO   rP   r   )rV   r  r{  r   rW   r?   r@   rP     s    zDrawEvent.__init__r   r   r   r   rP   r   r?   r?   rW   r@   r    s   r  c                       s    e Zd ZdZ fddZ  ZS )ResizeEventa3  
    An event triggered by a canvas resize.

    A ResizeEvent has a number of special attributes in addition to those
    defined by the parent `Event` class.

    Attributes
    ----------
    width : int
        Width of the canvas in pixels.
    height : int
        Height of the canvas in pixels.
    c                    s"   t  || | \| _| _d S r   )rO   rP   r   r   r   )rV   r  r{  rW   r?   r@   rP     s    zResizeEvent.__init__r  r?   r?   rW   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 fdd	Z  ZS )LocationEventa
  
    An event that has a screen location.

    A LocationEvent has a number of special attributes in addition to those
    defined by the parent `Event` class.

    Attributes
    ----------
    x, y : int or None
        Event location in pixels from bottom left of canvas.
    inaxes : `~.axes.Axes` or None
        The `~.axes.Axes` instance over which the mouse is, if any.
    xdata, ydata : float or None
        Data coordinates of the mouse within *inaxes*, or *None* if the mouse
        is not over an Axes.
    Nc           	         s   t  j|||d |d ur"t|n|| _|d ur8t|n|| _d | _d | _d | _|d u s`|d u rdd S | jj	d u r| j||f| _n
| jj	| _| jd urz"| jj
 }|||f\}}W n ty   Y n0 || _|| _d S Nr|  )rO   rP   r1  ro   rp   inaxesxdataydatar{  mouse_grabber	transDatainvertedrb   r<  )	rV   r  r{  ro   rp   r|  rl   r  r  rW   r?   r@   rP     s&    

zLocationEvent.__init__)N)r   r   r   r   	lasteventrP   r   r?   r?   rW   r@   r    s   r  c                   @   s    e Zd ZdZdZdZdZdZdS )MouseButtonr      r      	   N)r   r   r   LEFTMIDDLERIGHTZBACKFORWARDr?   r?   r?   r@   r  6  s
   r  c                       s*   e Zd ZdZd	 fdd	Zdd Z  ZS )

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

    A MouseEvent has a number of special attributes in addition to those
    defined by the parent `Event` and `LocationEvent` classes.

    Attributes
    ----------
    button : None or `MouseButton` or {'up', 'down'}
        The button pressed. 'up' and 'down' are used for scroll events.

        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.

        If this is unset, *name* is "scroll_event", and *step* is nonzero, then
        this will be set to "up" or "down" depending on the sign of *step*.

    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
           
         sr   t  j|||||	d |tj v r,t|}|dkrV|d u rV|dkrJd}n|dk rVd}|| _|| _|| _|| _d S )Nr  scroll_eventr   updown)	rO   rP   r  __members__valuesbuttonkeystepdblclick)
rV   r  r{  ro   rp   r  r  r  r  r|  rW   r?   r@   rP   p  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
) xydata=(z	) button=z
 dblclick=z inaxes=)r  ro   rp   r  r  r  r  r  rU   r?   r?   r@   __str__  s    zMouseEvent.__str__)NNr   FN)r   r   r   r   rP   r  r   r?   r?   rW   r@   r  >  s
   1  r  c                       s"   e Zd ZdZd fdd	Z  ZS )	PickEventa  
    A pick event.

    This event is fired when the user picks a location on the canvas
    sufficiently close to an artist that has been made pickable with
    `.Artist.set_picker`.

    A PickEvent has a number of special attributes in addition to those defined
    by the parent `Event` class.

    Attributes
    ----------
    mouseevent : `MouseEvent`
        The mouse event that generated the pick.
    artist : `matplotlib.artist.Artist`
        The picked artist.  Note that artists are not pickable by default
        (see `.Artist.set_picker`).
    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                    s:   |d u r|j }t ||| || _|| _| j| d S r   )r|  rO   rP   
mouseeventartist__dict__update)rV   r  r{  r  r  r|  r   rW   r?   r@   rP     s    zPickEvent.__init__)Nr  r?   r?   rW   r@   r    s   ' r  c                       s"   e Zd ZdZd fdd	Z  ZS )KeyEventa  
    A key event (key press, key release).

    A KeyEvent has a number of special attributes in addition to those defined
    by the parent `Event` and `LocationEvent` classes.

    Attributes
    ----------
    key : None or str
        The key(s) pressed. Could be *None*, a single case sensitive Unicode
        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                    s    t  j|||||d || _d S r  )rO   rP   r  )rV   r  r{  r  ro   rp   r|  rW   r?   r@   rP     s    zKeyEvent.__init__)r   r   Nr  r?   r?   rW   r@   r    s   r  c                 C   s,   | j dkr| j| j_n| j dkr(d | j_d S )Nkey_press_eventkey_release_event)r  r  r{  _keyeventr?   r?   r@   _key_handler  s    

r  c                 C   s   | j dkr| j| j_n2| j dkr*d | j_n| j dkrH| jd u rH| jj| _| jd u r\| jj| _| j dkrtj}|d urz|jnd }|| jkr|d urz|jj	
d| W n ty   Y n0 | jd ur| jj	
d|  | j dkrd n| t_d S )Nbutton_press_eventbutton_release_eventmotion_notify_eventaxes_leave_eventaxes_enter_eventfigure_leave_event)r  r  r{  _buttonr  r  r  r  r  rY  r}  	Exception)r  lastZ	last_axesr?   r?   r@   _mouse_handler  s*    








r  c                    s  G dd dt   fdd}tj| |d t }|du rX| j }|| j|}z|t	  W nL  y } z4|j
\}|W  Y d}~W  d   W  d   S d}~0 0 t| dW d   n1 s0    Y  W d   n1  s0    Y  dS )z
    Get the renderer that would be used to save a `.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 r   r?   r   r  r?   r@   _draw  r   z_get_renderer.<locals>._draw)drawNz6 did not call Figure.draw, so no renderer is available)r  r   r   r   r{  get_default_filetypeenter_context&_switch_canvas_and_return_print_methodioBytesIOr   RuntimeError)figureprint_methodr  stackfmtexcr   r?   r  r@   _get_renderer   s    


6r  c                 C   s   |    d S r   )Zdraw_without_rendering)r  r?   r?   r@   _no_output_draw   s    r  c                 C   s&   t | do$| jduo$t| jdddu S )aN  
    Return whether we are in 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.
    parentNinteractF)hasattrr  getattr)ipr?   r?   r@   $_is_non_interactive_terminal_ipython&  s
    	
r  c                       s  e Zd ZdZdZedd Zg dZdZ	e
Zejdd Zds fdd		Zed
d Zedd Zedd Zee dd Zedd Zedd Zdd Zejddddd ZdtddZ fddZejddddd  Zejdd!dd"d# Zejdd$ddud%d&Z ejdd'ddvd(d)Z!ejdd*ddwd+d,Z"ejdd-dd.d/ Z#ejdd0ddxd1d2Z$ejdd3ddyd5d6Z%ejdd7ddzd8d9Z&ejdd:dd{d;d<Z'ejdd=dd|d>d?Z(ejdd@dd}dAdBZ)dCdD Z*dEdF Z+dGdH Z,dIdJ Z-dKdL Z.dMdN Z/edOdP Z0dQdR Z1d4dSdTdUZ2edVdW Z3edXdY Z4ed~dZd[Z5dddddd]d^d_Z6ed`da Z7dbdc Z8ddde Z9dfdg Z:dhdi Z;e<Z=ddjdkZ>dldm Z?ddodpZ@dqdr ZA  ZBS )FigureCanvasBasez
    The canvas the figure renders into.

    Attributes
    ----------
    figure : `matplotlib.figure.Figure`
        A high-level figure instance.
    Nc                 C   s   t S r   )FigureManagerBaseclsr?   r?   r@   r   G  r   zFigureCanvasBase.<lambda>)resize_event
draw_eventr  r  r  r  r  r  
pick_eventfigure_enter_eventr  r  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)r  r  r?   r?   r@   supports_blit^  s    
zFigureCanvasBase.supports_blitc                    s   ddl m} |   d| _d| _|d u r.| }||  || _d | _t	 | _
d | _d | _d\| _| _d | _d | _d| _|j|_d| _t   d S )Nr   FigureTFr  r   )matplotlib.figurer  _fix_ipython_backend2gui_is_idle_drawing
_is_savingZ
set_canvasr  managerr   ZLockDraw
widgetlockr  r  _lastx_lastyr  toolbarr   _original_dpi_device_pixel_ratiorO   rP   )rV   r  r  rW   r?   r@   rP   d  s&    

zFigureCanvasBase.__init__c                 C   s   | j jS r   )r  Z_canvas_callbacksrU   r?   r?   r@   r   z  r   c                 C   s   | j jS r   )r  Z_button_pick_idrU   r?   r?   r@   r   {  r   c                 C   s   | j jS r   )r  Z_scroll_pick_idrU   r?   r?   r@   r   |  r   c                 C   s   t jdd u rd S dd l}| }|s,d S ddlm} t|drLt|dsPd S dddd	d
d| j}|r~t	|r~|
| d S )NIPythonr   )
pylabtoolsbackend2guiZenable_matplotlibr0   r1   r2   r3   Zosx)r0   r1   r2   r3   r.   )sysmodulesgetr  get_ipythonZIPython.corer  r  required_interactive_frameworkr  
enable_gui)r  r  r  ptZbackend2gui_rifr?   r?   r@   r  ~  s,    
z)FigureCanvasBase._fix_ipython_backend2guic                 C   s   | j | ||S )a&  
        Create a new figure manager for *figure*, using this canvas class.

        Notes
        -----
        This method should not be reimplemented in subclasses.  If
        custom manager creation logic is needed, please reimplement
        ``FigureManager.create_with_canvas``.
        )manager_classcreate_with_canvas)r  r  numr?   r?   r@   new_manager  s    zFigureCanvasBase.new_managerc                 c   s$   d| _ zd V  W d| _ nd| _ 0 d S )NTF)r  rU   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  rU   r?   r?   r@   	is_saving  s    zFigureCanvasBase.is_saving3.6zcanvas.figure.pickalternativec                 C   s   | j  s| j| d S r   )r  lockedr  pick)rV   r  r?   r?   r@   r    s    
zFigureCanvasBase.pickc                 C   s   dS )z0Blit the canvas in bbox (default entire canvas).Nr?   )rV   bboxr?   r?   r@   blit  s    zFigureCanvasBase.blitc                    s0   t t drt ||S tjddddd dS )z
        UNUSED: Set the canvas size in pixels.

        Certain backends may implement a similar method internally, but this is
        not a requirement of, nor is it used by, Matplotlib itself.
        resizer  methodFigureManagerBase.resize)r  obj_typer  N)r  rO   r  r	   rp  rV   r   r   rW   r?   r@   r    s
    	
zFigureCanvasBase.resizez/callbacks.process('draw_event', DrawEvent(...))c                 C   s"   d}t || |}| j|| dS )z@Pass a `DrawEvent` to all functions connected to ``draw_event``.r  N)r  rY  r}  )rV   r   rY   r  r?   r?   r@   r    s    zFigureCanvasBase.draw_eventz3callbacks.process('resize_event', ResizeEvent(...))c                 C   s(   d}t || }| j|| |   dS )zV
        Pass a `ResizeEvent` to all functions connected to ``resize_event``.
        r  N)r  rY  r}  	draw_idle)rV   rY   r  r?   r?   r@   r    s    
zFigureCanvasBase.resize_eventz1callbacks.process('close_event', CloseEvent(...))c              	   C   s@   d}z t || |d}| j|| W n ttfy:   Y n0 dS )zT
        Pass a `CloseEvent` to all functions connected to ``close_event``.
        r  r  N)r  rY  r}  	TypeErrorAttributeError)rV   r|  rY   r  r?   r?   r@   r    s    zFigureCanvasBase.close_eventz3callbacks.process('key_press_event', KeyEvent(...))c                 C   s4   || _ d}t|| || j| j|d}| j|| dS )zV
        Pass a `KeyEvent` to all functions connected to ``key_press_event``.
        r  r  N)r  r  r  r  rY  r}  rV   r  r|  rY   r  r?   r?   r@   r    s    z FigureCanvasBase.key_press_eventz5callbacks.process('key_release_event', KeyEvent(...))c                 C   s4   d}t || || j| j|d}| j|| d| _dS )zX
        Pass a `KeyEvent` to all functions connected to ``key_release_event``.
        r  r  N)r  r  r  rY  r}  r  r  r?   r?   r@   r     s    z"FigureCanvasBase.key_release_eventz/callbacks.process('pick_event', PickEvent(...))c                 K   s2   d}t || ||fd|ji|}| j|| dS )a  
        Callback processing for pick events.

        This method will be called by artists who are picked and will
        fire off `PickEvent` callbacks registered listeners.

        Note that artists are not pickable by default (see
        `.Artist.set_picker`).
        r  r|  N)r  r|  rY  r}  )rV   r  r  r   rY   r  r?   r?   r@   r    s    zFigureCanvasBase.pick_eventz2callbacks.process('scroll_event', MouseEvent(...))c              
   C   sH   |dkrd| _ nd| _ d}t|| ||| j | j||d}| 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   r  r  r  )r  r|  Nr  r  r  rY  r}  )rV   ro   rp   r  r|  rY   r  r?   r?   r@   r    s    zFigureCanvasBase.scroll_eventz8callbacks.process('button_press_event', MouseEvent(...))Fc              
   C   s6   || _ d}t|| |||| j||d}| 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.
        r  )r  r|  Nr  )rV   ro   rp   r  r  r|  rY   r  r?   r?   r@   r  4  s    z#FigureCanvasBase.button_press_eventz:callbacks.process('button_release_event', MouseEvent(...))c              	   C   s4   d}t || |||| j|d}| 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.
        r  r  N)r  r  rY  r}  r  )rV   ro   rp   r  r|  rY   r  r?   r?   r@   r  G  s    z%FigureCanvasBase.button_release_eventz9callbacks.process('motion_notify_event', MouseEvent(...))c              	   C   s>   || | _ | _d}t|| ||| j| j|d}| 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.
        r  r  N)r  r  r  r  r  rY  r}  )rV   ro   rp   r|  rY   r  r?   r?   r@   r  b  s    z$FigureCanvasBase.motion_notify_eventz;callbacks.process('leave_notify_event', LocationEvent(...))c                 C   s&   | 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.
        r  Nr  )rY  r}  r  r  r  r  )rV   r|  r?   r?   r@   leave_notify_event}  s    z#FigureCanvasBase.leave_notify_eventz;callbacks.process('enter_notify_event', LocationEvent(...))c                 C   s\   |dur |\}}|| | _ | _nd}d}tjddddd td| |||}| 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.0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.)removalr  rl  r  )r  r  r	   rp  r  rY  r}  )rV   r|  xyro   rp   r  r?   r?   r@   r
    s    z#FigureCanvasBase.enter_notify_eventc                    s0    fdd| j  D }|r(t|}nd}|S )a  
        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 there
            is no Axes at the point.
        c                    s$   g | ]}|j  r| r|qS r?   )patchcontains_pointget_visibler   ar  r?   r@   ro    s   z+FigureCanvasBase.inaxes.<locals>.<listcomp>N)r  get_axesr   _topmost_artist)rV   r  	axes_listaxesr?   r  r@   r    s
    zFigureCanvasBase.inaxesc                 C   s    | j d|fv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  r  rV   axr?   r?   r@   
grab_mouse  s    zFigureCanvasBase.grab_mousec                 C   s   | j |u 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@   release_mouse  s    
zFigureCanvasBase.release_mousec                 C   s   dS )a.  
        Set the current cursor.

        This may have no effect if the backend does not display anything.

        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.

        Parameters
        ----------
        cursor : `.Cursors`
            The cursor to display over the canvas. Note: some backends may
            change the cursor for the entire window.
        Nr?   rV   cursorr?   r?   r@   
set_cursor  s    zFigureCanvasBase.set_cursorc                 O   s   dS )a(  
        Render the `.Figure`.

        This method must walk the artist tree, even if no output is produced,
        because it triggers deferred work that users may want to access
        before saving output to disk. For example computing limits,
        auto-limits, and tick values.
        Nr?   rV   r   r   r?   r?   r@   r    s    zFigureCanvasBase.drawc                 O   sB   | j s>|    | j|i | W d   n1 s40    Y  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)r  r  r  r  r?   r?   r@   r    s    
zFigureCanvasBase.draw_idlec                 C   s   | j S )a  
        The ratio of physical to logical pixels used for the canvas on screen.

        By default, this is 1, meaning physical and logical pixels are the same
        size. Subclasses that support High DPI screens may set this property to
        indicate that said ratio is different. All Matplotlib interaction,
        unless working directly with the canvas, remains in logical pixels.

        r  rU   r?   r?   r@   device_pixel_ratio  s    z#FigureCanvasBase.device_pixel_ratioc                 C   s4   | j |krdS || jj }| jj|dd || _ dS )a  
        Set the ratio of physical to logical pixels used for the canvas.

        Subclasses that support High DPI screens can set this property to
        indicate that said ratio is different. The canvas itself will be
        created at the physical size, while the client side will use the
        logical size. Thus the DPI of the Figure will change to be scaled by
        this ratio. Implementations that support High DPI screens should use
        physical pixels for events so that transforms back to Axes space are
        correct.

        By default, this is 1, meaning physical and logical pixels are the same
        size.

        Parameters
        ----------
        ratio : float
            The ratio of logical to physical pixels used for the canvas.

        Returns
        -------
        bool
            Whether the ratio has changed. Backends may interpret this as a
            signal to resize the window, repaint the canvas, or change any
            other relevant properties.
        F)forwardT)r  r  r  Z_set_dpi)rV   ratior   r?   r?   r@   _set_device_pixel_ratio  s    
z(FigureCanvasBase._set_device_pixel_ratio)physicalc                   s   t  fddjjjD S )a  
        Return the figure width and height in integral points or pixels.

        When the figure is used on High DPI screens (and the backend supports
        it), the truncation to integers occurs after scaling by the device
        pixel ratio.

        Parameters
        ----------
        physical : bool, default: False
            Whether to return true physical pixels or logical pixels. Physical
            pixels may be used by backends that support HiDPI, but still
            configure the canvas using its actual size.

        Returns
        -------
        width, height : int
            The size of the figure, in points or pixels, depending on the
            backend.
        c                 3   s$   | ]}t | rd nj V  qdS )r   N)r1  r   )r   r=  r$  rV   r?   r@   	<genexpr>P  s   z4FigureCanvasBase.get_width_height.<locals>.<genexpr>)tupler  r  r   )rV   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.)	filetypesr  r?   r?   r@   get_supported_filetypesS  s    z(FigureCanvasBase.get_supported_filetypesc                 C   s:   i }| j  D ]&\}}||g | ||   q|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
setdefaultri  sort)r  	groupingsextr  r?   r?   r@   get_supported_filetypes_groupedX  s
    z0FigureCanvasBase.get_supported_filetypes_groupedc              	   #   s,  d}|durFt t|j}t|d| shtd|d| dn"t| d| r`| }d}nt|}|rv| |}|du rtd	|d
t|  t|d|  t dr jjn j}|d	rh d
}|h t j t  fdd}n }z|V  W | | j_n
| | j_0 dS )a   
        Context manager temporarily setting the canvas for saving the figure::

            with canvas._switch_canvas_and_return_print_method(fmt, backend) \
                    as print_method:
                # ``print_method`` is a suitable ``print_{fmt}`` method, and
                # the figure's canvas is temporarily switched to the method's
                # canvas within the with... block.  ``print_method`` is also
                # wrapped to suppress extra kwargs passed by ``print_figure``.

        Parameters
        ----------
        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.
        backend : str or None, default: None
            If not None, switch the figure canvas to the ``FigureCanvas`` class
            of the given backend.
        Nprint_zThe z backend does not support z outputz4Format {!r} is not supported (supported formats: {})r  rj  )zmatplotlib.zmpl_toolkits.>   orientation	facecolorbbox_inches_restorer   	edgecolorc                     s     | i fdd|  D S )Nc                    s   i | ]\}}| vr||qS r?   r?   )r   kv)skipr?   r@   r     r   z]FigureCanvasBase._switch_canvas_and_return_print_method.<locals>.<lambda>.<locals>.<dictcomp>)r*  r   methr7  r?   r@   r     s   zIFigureCanvasBase._switch_canvas_and_return_print_method.<locals>.<lambda>)rJ   rK   r   _backend_module_namerL   r  r<  rM   switch_backendsrE   joinsortedr)  r  rj  r   r   inspect	signature
parameters	functoolswrapsr  r{  )rV   r  r6   r{  canvas_classmodZoptional_kwsr  r?   r8  r@   r  f  sB    

z7FigureCanvasBase._switch_canvas_and_return_print_methodportrait)bbox_inches
pad_inchesbbox_extra_artistsr6   c                K   s  |du rtt |tjrt|}t |tr@tj|d dd }|du sP|dkrt|  }t |trt|dd | }|	 }|du rt
d }|dkrt| jd| jj}tj| dd | ||
}tj| j|d	 tj| jjdd
| tj| jjddF t }dD ]R}t | }|du r<t
d|  }t|ds|| jjf i ||i q|du r|t
d }| j dus|dkrt| jtj||d}t|dt  | j| W d   n1 s0    Y  |rD|dkr$| jj||	d}|du rt
d }||}t | j|| jjj!}||f}nd}|| jjdd zbtj| j|d	* ||f||||d|}W d   n1 s0    Y  W |r|r|  n|r|r|  0 |W  d   W  d   W  d   W  d   W  d   W  d   S 1 s40    Y  W d   n1 sT0    Y  W d   n1 st0    Y  W d   n1 s0    Y  W d   n1 s0    Y  W d   n1 s0    Y  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://...".
        Nr   rB   .zsavefig.dpir  r  r  )r   r  Tr  )r2  r4  zsavefig.autozsavefig.bboxtight)r1  r   )rH  zsavefig.pad_inches)Zlayout_engine)r2  r4  r1  r3  )"rH   osPathLikefspathrI   ra   splitextr  rstriplowerr   r  r  r   r   r   r  r{  r   locals
_str_equalr  _cm_setZget_layout_enginer  rA  partialr   r  get_tightbboxpaddedr   Zadjust_bbox	fixed_dpi)rV   filenamer   r2  r4  r1  rE   rF  rG  rH  r6   r   r  r  r   r   r   Zrestore_bboxZ_bbox_inches_restoreresultr?   r?   r@   print_figure  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   r  r?   r?   r@   r  /	  s    	z%FigureCanvasBase.get_default_filetypec                 C   s@   | j dur| j  nd}|pddd}|  }|d | }|S )zl
        Return a string, which includes extension, suitable for use as
        a default filename.
        NrB   image _rI  )r  get_window_titlereplacer  )rV   basenamefiletyperZ  r?   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
        )r  r  )rV   ZFigureCanvasClassZ	newCanvasr?   r?   r@   r;  F	  s    	
z FigureCanvasBase.switch_backendsc                 C   s   | 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)
        )rY  connect)rV   rY   rj  r?   r?   r@   mpl_connectS	  s    5zFigureCanvasBase.mpl_connectc                 C   s   | j |S )z
        Disconnect the callback with id *cid*.

        Examples
        --------
        ::

            cid = canvas.mpl_connect('button_press_event', on_press)
            # ... later
            canvas.mpl_disconnect(cid)
        )rY  
disconnect)rV   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})])
        )rZ  rY  )
_timer_clsr\  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?   rU   r?   r?   r@   flush_events	  s    zFigureCanvasBase.flush_eventsr   c                 C   sN   |dkrt j}d}d}d| _| jrJ|| |k rJ|   t| |d7 }q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?Tr   N)r   inf_loopingrl  timesleep)rV   timeoutZtimestepcounterr?   r?   r@   start_event_loop	  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)rn  rU   r?   r?   r@   stop_event_loop	  s    z FigureCanvasBase.stop_event_loop)N)N)N)N)N)N)FN)N)N)N)NN)N)NNNrE  N)NN)r   )Cr   r   r   r   r  r	   classpropertyr  eventsrY  rD   r(  r  rP   rx  rY  Zbutton_pick_idZscroll_pick_idclassmethodrA  	lru_cacher  r  r   r  r  
deprecatedr  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r  r  r  r   r#  r   r)  r/  r  r\  r  rd  r;  rf  ri  rW  rj  rk  rl  rs  rt  r   r?   r?   rW   r@   r  4  s   






	





&

?   

7

r  c              
   C   sR  | j du rdS |du r| j}|du 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 }| j |v rz|j  W n ty   Y n0 | j |
v rt|j	 | j |v rt
  |dur| j |v r|  n| j |v r|  nj| j |v r2|  nT| j |v rR|  ||  n4| j |v rr|  ||  n| j |	v r|  | jdu rdS dd }| j}| j |v rfd||jj||jjfvrf||jj}||jj}g d}z&||||fd t|  \}}W n ty(   Y n>0 |j||r:dnddd |j||rTdnddd |  | j |v rd||jj||jjfvr||jj}||jj}g d}z&||||fd t|  \}}W n ty   Y n*0 |j|ddd |j|ddd |  n6| j |v r| }|dkrN|d |j	j  nd|dkrNz|d W n> ty } z$tt | |d W Y d}~n
d}~0 0 |j	j  n| j |v rN|! }|dkr|"d |j	j  nd|dkrNz|"d W n> ty@ } z$tt | |"d W Y d}~n
d}~0 0 |j	j  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.homekeymap.backkeymap.forwardz
keymap.panzkeymap.zoomzkeymap.savezkeymap.quitzkeymap.quit_allzkeymap.gridzkeymap.grid_minorzkeymap.yscalezkeymap.xscalec                 S   s4   t dd | D rdS tdd | D s,dS d S d S )Nc                 s   s   | ]}|j  V  qd S r   Zgridliner  r   tickr?   r?   r@   r&  7
  r   zDkey_press_handler.<locals>._get_uniform_gridstate.<locals>.<genexpr>Tc                 s   s   | ]}|j  V  qd S r   r|  r}  r?   r?   r@   r&  9
  r   F)r  r;  )ticksr?   r?   r@   _get_uniform_gridstate4
  s
    z1key_press_handler.<locals>._get_uniform_gridstate))FF)TF)TT)FTr   majorbothro   )whichaxisrp   loglinear)#r  r{  r  r   r  full_screen_toggler  r   destroy_figr  destroy_allhomebackr!  pan_update_cursorzoomsave_figurer  xaxisZ
minorTicksyaxisZ
majorTicksrs  rh   r<  gridr  Z
get_yscale
set_yscaler   r!  rI   
get_xscale
set_xscale)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_keysr  r  Zx_stateZy_stater   r   r  scalexr?   r?   r@   key_press_handler	  s    















 


 r  c                 C   s`   |du r| j }|du r|j}|dur\tt| j}|td v rH|  n|td v r\|  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`.
    Nrz  r{  )r{  r  rI   r  r  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.Nr  r?   r?   r?   r@   r  
  s   r  c                   @   s\   e Zd ZdZdZdZdd Zedd Zdd Z	d	d
 Z
dd Zdd Zdd Zdd ZdS )r  a(  
    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)
    Nc                    s  | _  |_| _ d|d d  _d  _td dkr\ j dt _ j dt	 _t
jd dkrtt|jnd  _t
jd dkr jr  j  _n*t
jd dkr jr  j _nd  _ jrt j  jrt j  j jj fdd	}d S )
NzFigure r   r  toolmanagerr  r  toolbar2c                    s"    j d u r jd ur j  d S r   )r  r  r  )figrU   r?   r@   notify_axes_change
  s    z6FigureManagerBase.__init__.<locals>.notify_axes_change)r{  r  r  set_window_titleZkey_press_handler_idZbutton_press_handler_idr   rf  r  r  r;   r   r  r  _toolbar2_classr  _toolmanager_toolbar_classtoolsZadd_tools_to_managerZadd_tools_to_containerZadd_axobserver)rV   r{  r  r  r?   rU   r@   rP   
  s@    zFigureManagerBase.__init__c                 C   s   | |||S )z
        Create a manager for a given *figure* using a specific *canvas_class*.

        Backends should override this method if they have specific needs for
        setting up the canvas or the manager.
        r?   )r  rC  r  r  r?   r?   r@   r  
  s    z$FigureManagerBase.create_with_canvasc                 C   s0   t jdkrtjdsdS 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`.
        linuxZDISPLAYNzMatplotlib is currently using z8, which is a non-GUI backend, so cannot show the figure.)r  platformrM  environr  r  r   rU   r?   r?   r@   show  s
    zFigureManagerBase.showc                 C   s   d S r   r?   rU   r?   r?   r@   destroy  s    zFigureManagerBase.destroyc                 C   s   d S r   r?   rU   r?   r?   r@   r    s    z$FigureManagerBase.full_screen_togglec                 C   s   dS )z9For GUI backends, resize the window (in physical pixels).Nr?   r  r?   r?   r@   r     s    r   c                 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?   rU   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?   )rV   titler?   r?   r@   r  *  s    z"FigureManagerBase.set_window_title)r   r   r   r   r  r  rP   rw  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d Zedd ZdS )	_ModerB   zpan/zoomz	zoom rectc                 C   s   | j S r   )valuerU   r?   r?   r@   r  :  s    z_Mode.__str__c                 C   s   | t jur| jS d S r   )r  NONEr  rU   r?   r?   r@   _navigate_mode=  s    z_Mode._navigate_modeN)	r   r   r   r  PANZOOMr  rx  r  r?   r?   r?   r@   r  5  s   r  c                   @   s  e Zd 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edd Zedd Zdd Zdd Zdd ZeddZdd  Zd!d" Zd#d$ Zd%d& Zed'd(Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Z d5d6 Z!e"j#d7d8d9d:d; Z$d<d= Z%d>d? Z&d@S )A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:`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!
    )	)ZHomezReset original viewr  r  )ZBackzBack to previous viewr  r  )ForwardzForward to next viewr!  r!  NNNN)PanzFLeft button pans, Right button zooms
x/y fixes axis, CTRL fixes aspectmover  )ZZoomz Zoom to rectangle
x/y fixes axisZzoom_to_rectr  )ZSubplotszConfigure subplotssubplotsconfigure_subplotsr  )SavezSave the figureZfilesaver  c                 C   sv   || _ | |_t | _tjj| _| j 	d| j
| _| j 	d| j
| _| j 	d| j| _d | _d | _tj| _|   d S )Nr  r  r  )r{  r  r   Stack
_nav_stackr  CursorsPOINTER_last_cursorrf  _zoom_pan_handlerZ	_id_pressZ_id_release
mouse_move_id_drag	_pan_info
_zoom_infor  r  modeset_history_buttons)rV   r{  r?   r?   r@   rP   x  s"    

zNavigationToolbar2.__init__c                 C   s   dS )z.Display a message on toolbar or in status bar.Nr?   r\   r?   r?   r@   set_message  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?   )rV   r  x0y0x1y1r?   r?   r@   draw_rubberband  s    z"NavigationToolbar2.draw_rubberbandc                 C   s   dS )zRemove the rubberband.Nr?   rU   r?   r?   r@   remove_rubberband  s    z$NavigationToolbar2.remove_rubberbandc                 G   s   | 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rV   r   r?   r?   r@   r    s    
zNavigationToolbar2.homec                 G   s   | 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  r  r  r?   r?   r@   r    s    
zNavigationToolbar2.backc                 G   s   | 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  r  r  r?   r?   r@   r!    s    
zNavigationToolbar2.forwardc                 C   s   | j r|jr|j r| j tjkrL| jtjjkrL| j	
tjj tjj| _q| j tjkr| jtjjkr| j	
tjj tjj| _n(| jtjjkr| j	
tjj tjj| _dS )zV
        Update the cursor after a mouse move event or a tool (de)activation.
        N)r  r  get_navigater  r  r  r  r  ZSELECT_REGIONr{  r  r  MOVEr  rV   r  r?   r?   r@   r    s    z!NavigationToolbar2._update_cursorc              	   c   sp   t   t| dtj  | _}| j| dkrfz(| jtjj	 dV  W | j| j
 ql| j| j
 0 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_timer   N)ro  r  r   rm  r  r{  r  r  r  ZWAITr  )rV   Zlast_draw_timer?   r?   r@   _wait_cursor_for_draw_cm  s    "z+NavigationToolbar2._wait_cursor_for_draw_cmc              	      s    j r j  rz j  j j}W n ttfy<   Y nn0 | } fdd j jD }|rt	
|}| j jur| }|d ur|| }|r|d | }|S d S )Nc                    s&   g | ]}|  d  r| r|qS rm  )containsr  r  r  r?   r@   ro    s   z>NavigationToolbar2._mouse_event_to_message.<locals>.<listcomp>
)r  r  Zformat_coordr  r  r<  OverflowErrorrQ  _mouseover_setr   r  r  get_cursor_dataformat_cursor_data)r  rY   artistsr  datadata_strr?   r  r@   _mouse_event_to_message  s     

z*NavigationToolbar2._mouse_event_to_messagec                 C   s8   |  | | |}|d ur(| | n| | j d S r   )r  r  r  r  )rV   r  rY   r?   r?   r@   r    s
    

zNavigationToolbar2.mouse_movec                 C   sp   | j tjkr6|jdkr"| | n|jdkr6| | | j tjkrl|jdkrX| | n|jdkrl| | d S )Nr  r  )	r  r  r  r  	press_panrelease_panr  
press_zoomrelease_zoomr  r?   r?   r@   r    s    




z$NavigationToolbar2._zoom_pan_handlerc                 G   s   | j j| s| d dS | jtjkr@tj| _| j j|  ntj| _| j |  | j j	
 D ]}|| jj q`| | j dS )z[
        Toggle the pan/zoom tool.

        Pan with left button, zoom with right.
        zpan unavailableN)r{  r  	availabler  r  r  r  r  releaser  r  set_navigate_moder  rV   r   r  r?   r?   r@   r    s    
zNavigationToolbar2.pan_PanInfozbutton axes cidc                    s    j tjtjfvs& jdu s& jdu r*dS  fdd| jj D }|sLdS | 	 du r`| 
  |D ]}| j j j  qd| j| j | jd| j}| j j ||d| _dS )z1Callback for mouse button press in pan/zoom mode.Nc                    s*   g | ]"}|  r| r| r|qS r?   )in_axesr  Zcan_panr  r  r?   r@   ro  '  s   z0NavigationToolbar2.press_pan.<locals>.<listcomp>r  )r  r  rh  )r  r  r  r  ro   rp   r{  r  r  r  push_currentZ	start_panri  r  rf  drag_panr  r  )rV   r  r  r  Zid_dragr?   r  r@   r  "  s$    zNavigationToolbar2.press_panc                 C   s6   | j jD ]}|| j j|j|j|j q| j  dS )z'Callback for dragging in pan/zoom mode.N)	r  r  r  r  r  ro   rp   r{  r  rV   r  r  r?   r?   r@   r  4  s    zNavigationToolbar2.drag_panc                 C   sb   | j du rdS | j| j j | jd| j| _| j jD ]}|  q8| j	  d| _ | 
  dS )z3Callback for mouse button release in pan/zoom mode.Nr  )r  r{  ri  rh  rf  r  r  r  Zend_panr  r  r  r?   r?   r@   r  <  s    


zNavigationToolbar2.release_panc                 G   s   | j j| s| d d S | jtjkr@tj| _| j j|  ntj| _| j |  | j j	
 D ]}|| jj q`| | j d S )Nzzoom unavailable)r{  r  r  r  r  r  r  r  r  r  r  r  r  r  r?   r?   r@   r  I  s    
zNavigationToolbar2.zoom	_ZoomInfoz direction start_xy axes cid cbarc                    s    j tjtjfvs& jdu s& jdu r*dS  fdd| jj D }|sLdS | 	 du r`| 
  | jd| j}t|d dr|d jj}nd}| j j dkrdnd	 j jf|||d
| _dS )z5Callback for mouse button press in zoom to rect mode.Nc                    s*   g | ]"}|  r| r| r|qS r?   )r  r  Zcan_zoomr  r  r?   r@   ro  _  s   z1NavigationToolbar2.press_zoom.<locals>.<listcomp>r  r   	_colorbarr   inout)	directionstart_xyr  rh  cbar)r  r  r  r  ro   rp   r{  r  r  r  r  rf  	drag_zoomr  r  r1  r  r  )rV   r  r  Zid_zoomr  r?   r  r@   r  Z  s*    zNavigationToolbar2.press_zoomc           	      C   s   | j j}| j jd }t||j|jgg|jj|jj	\\}}\}}|j
}| j jdkrZd}n| j jdkrjd}|dkr|jj\}}n|dkr|jj\}}| ||||| dS )z#Callback for dragging in zoom mode.r   
horizontalro   verticalrp   N)r  r  r  r   clipro   rp   r  minr   r  r  	intervaly	intervalxr  )	rV   r  r  r  r  r  x2y2r  r?   r?   r@   r  r  s    zNavigationToolbar2.drag_zoomc                    s:  | j du rdS | j| j j |   | j j\}}|j}| j jdkrJd}n| j jdkrZd}t|j	| dk rt|dkst|j
| dk r|dkr| j  d| _ dS t| j jD ]n\} t fdd| j jd| D }t fd	d| j jd| D } |||j	|j
f| j j||| q| j  d| _ |   dS )
z7Callback for mouse button release in zoom to rect mode.Nr  ro   r  rp      c                 3   s   | ]}    |V  qd S r   )Zget_shared_x_axesjoinedr   prevr  r?   r@   r&    s   z2NavigationToolbar2.release_zoom.<locals>.<genexpr>c                 3   s   | ]}    |V  qd S r   )Zget_shared_y_axesr  r  r  r?   r@   r&    s   )r  r{  ri  rh  r  r  r  r  absro   rp   r  	enumerater  r;  _set_view_from_bboxr  r  )rV   r  Zstart_xZstart_yr  r   twinxtwinyr?   r  r@   r    s@    


zNavigationToolbar2.release_zoomc                 C   s,   | j tdd | jjjD  |   dS )z9Push the current view limits and position onto the stack.c                 S   s0   i | ](}||  |d  |  ffqS )T)	_get_viewget_positionru   )r   r  r?   r?   r@   r     s   
z3NavigationToolbar2.push_current.<locals>.<dictcomp>N)r  pushr   r{  r  r  r  rU   r?   r?   r@   r    s    zNavigationToolbar2.push_currentc                 C   sf   |   }|du rdS t| }|D ]2\}\}\}}|| ||d ||d q$| j  dS )zi
        Update the viewlim and position from the view and position stack for
        each Axes.
        Noriginalactive)r  rt   r*  	_set_view_set_positionr{  r  )rV   Znav_infor*  r  viewZpos_origZ
pos_activer?   r?   r@   r    s    
zNavigationToolbar2._update_viewc                    s   t drjjjj  d S ddlm} t	ddi( t
j|ddd W d    n1 sf0    Y   d	  jj}|jd
d tjj|_|jdfdd jd fdd    jS )Nsubplot_toolr   r  r  none)   r   )figsizezSubplot configuration toolg?)topr  c                    s
   t  dS )Nr	  )delattrerU   r?   r@   r     r   z7NavigationToolbar2.configure_subplots.<locals>.<lambda>c                    s      S r   )r  r  rJ  r?   r@   r     r   )r  r	  r  r{  r  r  r  r  r;   
rc_contexttyper  r  subplots_adjustr   ZSubplotToolrf  )rV   r   r  Ztool_figr?   )r  rV   r@   r    s$    
6
z%NavigationToolbar2.configure_subplotsc                 G   s   t dS )zSave the current figure.Nr^   r  r?   r?   r@   r    s    zNavigationToolbar2.save_figurer	  z`.FigureCanvasBase.set_cursor`r  c                 C   s   | j | 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.
        N)r{  r  r  r?   r?   r@   r    s    
zNavigationToolbar2.set_cursorc                 C   s   | j   |   dS )zReset the Axes stack.N)r  clearr  rU   r?   r?   r@   r    s    
zNavigationToolbar2.updatec                 C   s   dS )z*Enable or disable the back/forward button.Nr?   rU   r?   r?   r@   r    s    z&NavigationToolbar2.set_history_buttonsN)'r   r   r   r   Z	toolitemsrP   r  r  r  r  r  r!  r  r   r  staticmethodr  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r	   ry  r  r  r  r?   r?   r?   r@   r  B  sD   &

	

)
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   | _ |d fdd |d fdd d S )NZtool_message_eventc                    s     | jS r   )r  rl  r  rU   r?   r@   r     r   z,ToolContainerBase.__init__.<locals>.<lambda>Ztool_removed_eventc                    s     | jjS r   )remove_toolitemtoolr  r  rU   r?   r@   r     r   )r  toolmanager_connect)rV   r  r?   rU   r@   rP     s    

zToolContainerBase.__init__c                 C   s   |  |jj|jj dS )zc
        Capture the 'tool_trigger_[name]'

        This only gets used for toggled tools.
        N)toggle_toolitemr  r  toggledr  r?   r?   r@   _tool_toggled_cbk  s    z#ToolContainerBase._tool_toggled_cbkr  c                 C   sr   | j |}| |j}t|dddu}| |j||||j| |rn| j d|j | j	 |j
rn| |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.
        r  Nztool_trigger_%sT)r  Zget_tool_get_image_filenamer]  r  add_toolitemr  rF   r  r  r  r  )rV   r  grouppositionr]  toggler?   r?   r@   add_tool  s    zToolContainerBase.add_toolc                 C   sX   |sdS t d}||| j t|| t||| j  fD ]}tj|r:|  S q:dS )z!Find the image based on its name.Nimages)r   _get_data_path_icon_extensionrI   rM  ra   isfile)rV   r]  Zbasedirfnamer?   r?   r@   r  2  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.
        )senderN)r  trigger_toolrV   r  r?   r?   r@   r*  A  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 : 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).
        Nr^   )rV   r  r   r!  r]  rF   r"  r?   r?   r@   r  L  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.
        Nr^   )rV   r  r  r?   r?   r@   r  j  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.
        Nr^   r+  r?   r?   r@   r  w  s    z!ToolContainerBase.remove_toolitemc                 C   s   t dS )z
        Display a message on the toolbar.

        Parameters
        ----------
        s : str
            Message text.
        Nr^   r\   r?   r?   r@   r    s    	zToolContainerBase.set_messageN)r  )r   r   r   r   r&  rP   r  r#  r  r*  r  r  r  r  r?   r?   r?   r@   r    s   		
r  c                   @   s^   e Zd ZdZdZe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   s2   ddl m} |d|}||i |}| ||S )z%Create a new figure manager instance.r   r  FigureClass)r  r  rr  new_figure_manager_given_figure)r  r  r   r   r  Zfig_clsr  r?   r?   r@   new_figure_manager  s    z_Backend.new_figure_managerc                 C   s   | j ||S )z:Create a new figure manager instance for the given figure.)rL   r  )r  r  r  r?   r?   r@   r/    s    z(_Backend.new_figure_manager_given_figurec                 C   s*   | j d ur&t r&t }|r&|j  d S r   )mainloopr   r   
get_activer{  r  )r  r  r?   r?   r@   draw_if_interactive  s    z_Backend.draw_if_interactiveblockc                C   s   t  }|sdS |D ]D}z|  W q tyV } ztt| W Y d}~qd}~0 0 q| jdu rhdS |du rddlm	} t
|jd}| ot  }|r|   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   )r8   Z	_needmain)r   get_all_fig_managersr  r  r	   warn_externalrI   r1  
matplotlibr8   r  r   )r  r5  managersr  r  r8   Zipython_pylabr?   r?   r@   r    s     	&
z_Backend.showc                    sP   dD ]}t tj j |t | qG  fdddt}t tj j d|  S )N)backend_versionrL   FigureManagerr0  r/  r3  r  c                       s   e Zd Z fddZdS )z_Backend.export.<locals>.Showc                    s      S r   )r1  rU   r  r?   r@   r1    s    z&_Backend.export.<locals>.Show.mainloopN)r   r   r   r1  r?   r  r?   r@   Show  s   r<  )setattrr  r  r   r  ShowBase)r  r  r<  r?   r  r@   export  s
    	z_Backend.export)r   r   r   r:  rL   r  r;  r1  rw  r0  r/  r3  r  r  r?  r?   r?   r?   r@   r,    s   


r,  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 )Nr4  )r  )rV   r5  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)[r   collectionsr   
contextlibr   r   r   enumr   r   rA  rJ   r>  r  r   loggingrM  r  ro  weakrefr   numpyr   r8  r;   r	   r
   r  r   r   r   r   r   r   r   r   r   r   Zmatplotlib._pylab_helpersr   Zmatplotlib.backend_managersr   matplotlib.cbookr   matplotlib.pathr   Zmatplotlib.texmanagerr   matplotlib.transformsr   matplotlib._enumsr   r   	getLoggerr   r   rD   rC   rA   rG   rM   rN   r   rW  rz  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  cursorsrI   r  r  r  r,  r>  r?   r?   r?   r@   <module>   s   8

    A  I 2H1&	
        5
 "
    8 c