o
    h%R                    @   s4  d Z ddlmZ ddlZddlZddlmZm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 ddlmZ dd	lmZmZmZ dd
lmZmZ G dd dZ G dd dZ!G dd de!Z"G dd de"Z#G dd de"Z$G dd de$Z%G dd de$Z&dd Z'G dd de"Z(G dd de"Z)G dd  d e"Z*G d!d" d"e!Z+G d#d$ d$e"Z,G d%d& d&e!Z-G d'd( d(e"Z.G d)d* d*e.Z/G d+d, d,Z0G d-d. d.Z1d/Z2e3e24d0d1G d2d3 d3e.Z5e3e24d0d4G d5d6 d6e5Z6G d7d8 d8e.Z7G d9d: d:e.Z8G d;d< d<e"Z9dS )=a|  
GUI neutral widgets
===================

Widgets that are designed to work for any of the GUI backends.
All of these widgets require you to predefine an `~.axes.Axes`
instance and pass that as the first parameter.  Matplotlib doesn't try to
be too smart with respect to layout -- you will have to figure out how
wide and tall you want your Axes to be to accommodate your widget.
    )	ExitStackN)IntegralNumber)cycler   )	_api
_docstringbackend_toolscbookcollectionscolorstextticker
transforms)Line2D)	RectangleEllipsePolygon)TransformedPatchPathAffine2Dc                   @   s@   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S )LockDrawa  
    Some widgets, like the cursor, draw onto the canvas, and this is not
    desirable under all circumstances, like when the toolbar is in zoom-to-rect
    mode and drawing a rectangle.  To avoid this, a widget can acquire a
    canvas' lock with ``canvas.widgetlock(widget)`` before drawing on the
    canvas; this will prevent other widgets from doing so at the same time (if
    they also try to acquire the lock first).
    c                 C   s
   d | _ d S N_ownerself r   f/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/matplotlib/widgets.py__init__&      
zLockDraw.__init__c                 C   s   |  |s	td|| _dS )zReserve the lock for *o*.zalready lockedN	available
ValueErrorr   r   or   r   r   __call__)      

zLockDraw.__call__c                 C   s   |  |s	tdd| _dS )zRelease the lock from *o*.zyou do not own this lockNr    r#   r   r   r   release/   r&   zLockDraw.releasec                 C   s   |    p	| |S )z+Return whether drawing is available to *o*.)lockedisownerr#   r   r   r   r!   5      zLockDraw.availablec                 C   s
   | j |u S )z"Return whether *o* owns this lock.r   r#   r   r   r   r)   9      
zLockDraw.isownerc                 C   s
   | j duS )z6Return whether the lock is currently held by an owner.Nr   r   r   r   r   r(   =   r+   zLockDraw.lockedN)
__name__
__module____qualname____doc__r   r%   r'   r!   r)   r(   r   r   r   r   r      s    	r   c                   @   sB   e Zd ZdZdZdZdZdd Zdd Ze	eeddZ
d	d
 ZdS )Widgetz6
    Abstract base class for GUI neutral widgets.
    Tc                 C   s
   || _ dS )z!Set whether the widget is active.N_activer   activer   r   r   
set_activeJ   r+   zWidget.set_activec                 C      | j S )z!Get whether the widget is active.r1   r   r   r   r   
get_activeN      zWidget.get_activezIs the widget active?)docc                 C   s   | j  S )z
        Return whether *event* should be ignored.

        This method should be called at the beginning of any event callback.
        r4   r   eventr   r   r   ignoreU   s   zWidget.ignoreN)r,   r-   r.   r/   drawoneventsonr2   r5   r7   propertyr4   r=   r   r   r   r   r0   B   s    r0   c                   @   s<   e Zd ZdZdd Zedd Zdd Zdd	 Zd
d Z	dS )
AxesWidgeta  
    Widget connected to a single `~matplotlib.axes.Axes`.

    To guarantee that the widget remains responsive and not garbage-collected,
    a reference to the object should be maintained by the user.

    This is necessary because the callback registry
    maintains only weak-refs to the functions, which are member
    functions of the widget.  If there are no references to the widget
    object it may be garbage collected which will disconnect the callbacks.

    Attributes
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent Axes for the widget.
    canvas : `~matplotlib.backend_bases.FigureCanvasBase`
        The parent figure canvas for the widget.
    active : bool
        If False, the widget does not respond to events.
    c                 C   s   || _ g | _d S r   )ax_cids)r   rB   r   r   r   r   t   s   
zAxesWidget.__init__c                 C   s   | j jddjS )NTroot)rB   
get_figurecanvasr   r   r   r   <lambda>x   s    zAxesWidget.<lambda>c                 C   s   | j ||}| j| dS )z
        Connect a callback function with an event.

        This should be used in lieu of ``figure.canvas.mpl_connect`` since this
        function stores callback ids for later clean up.
        N)rG   mpl_connectrC   append)r   r<   callbackcidr   r   r   connect_eventz   s   zAxesWidget.connect_eventc                 C   s   | j D ]}| j| qdS )z-Disconnect all events created by this widget.N)rC   rG   mpl_disconnect)r   cr   r   r   disconnect_events      
zAxesWidget.disconnect_eventsc                 C   s2   |j | ju r|j|jfS | jj |j|jfS )z8Return *event*'s data coordinates in this widget's Axes.)	inaxesrB   xdataydata	transDatainverted	transformxyr;   r   r   r   _get_data_coords   s   zAxesWidget._get_data_coordsN)
r,   r-   r.   r/   r   r@   rG   rM   rP   rZ   r   r   r   r   rA   ^   s    
rA   c                       sT   e Zd ZdZ		ddd fddZd	d
 Zdd Zdd Zdd Zdd Z	  Z
S )Buttona  
    A GUI neutral button.

    For the button to remain responsive you must keep a reference to it.
    Call `.on_clicked` to connect to the button.

    Attributes
    ----------
    ax
        The `~.axes.Axes` the button renders into.
    label
        A `.Text` instance.
    color
        The color of the button when not hovering.
    hovercolor
        The color of the button when hovering.
    N0.850.95T)useblitc                   s   t  | |dur|| |jdd|dd|jd| _|o!| jj| _t	j
dgd| _| d| j | d| j | d	| j |d
 || |g  |g  || _|| _dS )a  
        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            The `~.axes.Axes` instance the button will be placed into.
        label : str
            The button text.
        image : array-like or PIL Image
            The image to place in the button, if not *None*.  The parameter is
            directly forwarded to `~.axes.Axes.imshow`.
        color : :mpltype:`color`
            The color of the button when not activated.
        hovercolor : :mpltype:`color`
            The color of the button when the mouse is over it.
        useblit : bool, default: True
            Use blitting for faster drawing if supported by the backend.
            See the tutorial :ref:`blitting` for details.

            .. versionadded:: 3.7
        N      ?center)verticalalignmenthorizontalalignmentrW   clickedsignalsbutton_press_eventbutton_release_eventmotion_notify_eventF)superr   imshowr   	transAxeslabelrG   supports_blit_useblitr
   CallbackRegistry
_observersrM   _click_release_motionset_navigateset_facecolor
set_xticks
set_ytickscolor
hovercolor)r   rB   rl   imagerx   ry   r^   	__class__r   r   r      s&   






zButton.__init__c                 C   sH   | j r| |s| j|d sd S |jj| jkr"|j| j d S d S Nr   )r?   r=   rB   containsrG   mouse_grabber
grab_mouser;   r   r   r   rq      s
    zButton._clickc                 C   sZ   |  |s|jj| jkrd S |j| j | jr)| j|d r+| jd| d S d S d S )Nr   rc   )	r=   rG   r   rB   release_mouser?   r~   rp   processr;   r   r   r   rr      s   zButton._releasec                 C   s   |  |rd S | j|d r| jn| j}t|| j sB| j| | j	rD| j
r;| j| j | j| jj d S | j  d S d S d S r}   )r=   rB   r~   ry   rx   r   
same_colorget_facecolorru   r>   rn   draw_artistrG   blitbboxdrawr   r<   rO   r   r   r   rs      s   
zButton._motionc                       | j d fddS )z
        Connect the callback function *func* to button click events.

        Returns a connection id, which can be used to disconnect the callback.
        rc   c                        | S r   r   r<   funcr   r   rH          z#Button.on_clicked.<locals>.<lambda>rp   connectr   r   r   r   r   
on_clicked      zButton.on_clickedc                 C      | j | dS )z6Remove the callback function with connection id *cid*.Nrp   
disconnectr   rL   r   r   r   r         zButton.disconnect)Nr\   r]   )r,   r-   r.   r/   r   rq   rr   rs   r   r   __classcell__r   r   r{   r   r[      s    -r[   c                       s8   e Zd ZdZ fddZdd Zdd Zdd	 Z  ZS )

SliderBasez
    The base class for constructing Slider widgets. Not intended for direct
    usage.

    For the slider to remain responsive you must maintain a reference to it.
    c
                    s,  |j dkr	tdt | tjddg|d || _|| _|| _|| _	|| _
|	| _d| _|| _|dkr?|||f |j}
n
|||f |j}
|
 | _t| jtjs`t | _| j|
 | jd | jd |  |d | d| j | d	| j |r| d
| j tjdgd| _ d S )N3dz"Sliders cannot be added to 3D Axes
horizontalvertical)orientationFTrf   rg   rh   changedrd   )!namer"   ri   r   r   check_in_listr   	closedmin	closedmaxvalminvalmaxvalstepdrag_activevalfmtset_ylimyaxisset_xlimxaxisget_major_formatter_fmt
isinstancer   ScalarFormatterset_axisset_useOffsetset_useMathTextset_axis_offrt   rM   _updater
   ro   rp   )r   rB   r   r   r   r   r   r   draggingr   axisr{   r   r   r     s<   



zSliderBase.__init__c                 C   s|   t | jtr| jt|| j | j | j  }|S | jdur<t| j}|jdkr0td|j |t	t
||  }|S )z?Return *val* coerced to closest number in the ``valstep`` grid.Nr   z&valstep must have 1 dimension but has )r   r   r   r   roundnp
asanyarrayndimr"   argminabs)r   valr   r   r   r   _stepped_value*  s   	


zSliderBase._stepped_valuec                 C   r   )z
        Remove the observer with connection id *cid*.

        Parameters
        ----------
        cid : int
            Connection id of the observer to be removed.
        Nr   r   r   r   r   r   8  s   	zSliderBase.disconnectc                 C   s&   t | j| jkr| | j dS dS )z&Reset the slider to the initial value.N)r   anyr   valinitset_valr   r   r   r   resetC  s   zSliderBase.reset)	r,   r-   r.   r/   r   r   r   r   r   r   r   r{   r   r      s    (r   c                       sd   e Zd ZdZddddddddddddd fd	d

Zdd Zdd Zdd Zdd Zdd Z	  Z
S )SlideraB  
    A slider representing a floating point range.

    Create a slider from *valmin* to *valmax* in Axes *ax*. For the slider to
    remain responsive you must maintain a reference to it. Call
    :meth:`on_changed` to connect to the slider event.

    Attributes
    ----------
    val : float
        Slider value.
    r_   NTr   r	lightgrey)r   r   r   r   	slidermin	slidermaxr   r   r   	initcolortrack_colorhandle_stylec                   sV  t  |||||||||	 |	dur!t|	ds!tdt|	 d|
dur4t|
ds4tdt|
 d|	| _|
| _| |}|du rE|}|| _|| _	dddd	}|du rWi n|}d
d i ||
 D }|dkrtddd|j|d| _|| j |j||ddfi || _|j|dd|dt| jd| _dg|gg}n3tddd|j|d| _|| j |j||ddfi || _|j|dd|dt| jd| _|gdgg}|jg |dR i |ddi\| _|dkr|jdd||jddd| _|jdd| ||jddd| _n|jdd||jddd| _|jdd| ||jdd d| _| | dS )!ah  
        Parameters
        ----------
        ax : Axes
            The Axes to put the slider in.

        label : str
            Slider label.

        valmin : float
            The minimum value of the slider.

        valmax : float
            The maximum value of the slider.

        valinit : float, default: 0.5
            The slider initial position.

        valfmt : str, default: None
            %-format string used to format the slider value.  If None, a
            `.ScalarFormatter` is used instead.

        closedmin : bool, default: True
            Whether the slider interval is closed on the bottom.

        closedmax : bool, default: True
            Whether the slider interval is closed on the top.

        slidermin : Slider, default: None
            Do not allow the current slider to have a value less than
            the value of the Slider *slidermin*.

        slidermax : Slider, default: None
            Do not allow the current slider to have a value greater than
            the value of the Slider *slidermax*.

        dragging : bool, default: True
            If True the slider can be dragged by the mouse.

        valstep : float or array-like, default: None
            If a float, the slider will snap to multiples of *valstep*.
            If an array the slider will snap to the values in the array.

        orientation : {'horizontal', 'vertical'}, default: 'horizontal'
            The orientation of the slider.

        initcolor : :mpltype:`color`, default: 'r'
            The color of the line at the *valinit* position. Set to ``'none'``
            for no line.

        track_color : :mpltype:`color`, default: 'lightgrey'
            The color of the background track. The track is accessible for
            further styling via the *track* attribute.

        handle_style : dict
            Properties of the slider handle. Default values are

            ========= ===== ======= ========================================
            Key       Value Default Description
            ========= ===== ======= ========================================
            facecolor color 'white' The facecolor of the slider handle.
            edgecolor color '.75'   The edgecolor of the slider handle.
            size      int   10      The size of the slider handle in points.
            ========= ===== ======= ========================================

            Other values will be transformed as marker{foo} and passed to the
            `~.Line2D` constructor. e.g. ``handle_style = {'style'='x'}`` will
            result in ``markerstyle = 'x'``.

        Notes
        -----
        Additional kwargs are passed on to ``self.poly`` which is the
        `~matplotlib.patches.Rectangle` that draws the slider knob.  See the
        `.Rectangle` documentation for valid property names (``facecolor``,
        ``edgecolor``, ``alpha``, etc.).
        Nr   zArgument slidermin (z) has no 'val'zArgument slidermax (white.75
   	facecolor	edgecolorsizec                 S      i | ]
\}}d | |qS markerr   .0kvr   r   r   
<dictcomp>      z#Slider.__init__.<locals>.<dictcomp>r         ?r   r_   r   rW   r   r         ?r   )rx   lw	clip_pathr   r   r$   clip_onFRQ?bottomr`   rW   ra   rb   {Gztoprightleft)ri   r   hasattrr"   typer   r   _value_in_boundsr   r   itemsr   rk   track	add_patchaxhspanpolyaxhliner   hlineaxvspanaxvlinevlineplot_handler   rl   _formatvaltextr   )r   rB   rl   r   r   r   r   r   r   r   r   r   r   r   r   r   r   kwargsdefaultsmarker_propshandleXYr{   r   r   r   W  s   Q



zSlider.__init__c                 C   s   |  |}|| jkr| jsdS | j}n|| jkr | jsdS | j}| jdur4|| jjkr4| js0dS | jj}| jdurH|| jjkrH| jsDdS | jj}|S )z&Makes sure *val* is with given bounds.N)r   r   r   r   r   r   r   r   r   r   r   r   r   r     s$   


zSlider._value_in_boundsc                 C   s   |  |s
|jdkrdS |jdkr#| j|d r#d| _|j| j | js(dS |jdks:|jdkrF| j|d sFd| _|j| j dS | 	|\}}| 
| jdkrV|n|}|d| jfvrg| | dS dS )	Update the slider position.r   Nrf   r   Trg   Fr   )r=   buttonr   rB   r~   r   rG   r   r   rZ   r   r   r   r   )r   r<   rS   rT   r   r   r   r   r     s&   
zSlider._updatec                 C   s>   | j dur
| j | S | j| j|| jg\}}}|| j  S )Pretty-print *val*.Nr   r   format_ticksr   r   
get_offset)r   r   _sr   r   r   r   #  s   

zSlider._formatc                 C   s   | j dkr| j|| j   | j|g n| j|| j   | j|g | j	
| | | jr@| jjddj  || _| jrO| jd| dS dS )zg
        Set slider value to *val*.

        Parameters
        ----------
        val : float
        r   TrD   r   N)r   r   
set_heightget_yr   	set_ydata	set_widthget_x	set_xdatar   set_textr   r>   rB   rF   rG   	draw_idler   r?   rp   r   r  r   r   r   r   ,  s   
zSlider.set_valc                    r   )a  
        Connect *func* as callback function to changes of the slider value.

        Parameters
        ----------
        func : callable
            Function to call when slider is changed.
            The function must accept a single float as its arguments.

        Returns
        -------
        int
            Connection id (which can be used to disconnect *func*).
        r   c                    r   r   r   r   r   r   r   rH   P  r   z#Slider.on_changed.<locals>.<lambda>r   r   r   r   r   
on_changedA     zSlider.on_changed)r,   r-   r.   r/   r   r   r   r   r   r  r   r   r   r{   r   r   I  s     	r   c                
       s   e Zd ZdZdddddddddd	 f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  ZS )RangeSlidera  
    A slider representing a range of floating point values. Defines the min and
    max of the range via the *val* attribute as a tuple of (min, max).

    Create a slider that defines a range contained within [*valmin*, *valmax*]
    in Axes *ax*. For the slider to remain responsive you must maintain a
    reference to it. Call :meth:`on_changed` to connect to the slider event.

    Attributes
    ----------
    val : tuple of float
        Slider value.
    NTr   r   )	r   r   r   r   r   r   r   r   r   c       	            st  t  ||||||||	|
	 ||f| _|du r+|| }t||d  ||d  g}n| |}|| _|| _dddd}|du rBi n|}dd	 i || D }|d
krztddd|j	|d| _
|| j
 | jjdd}d|d g}d|d g}n$tddd|j	|d| _
|| j
 | jjdd}|d dg}|d dg}ttddgfi || _| j|  | j| d| j _| j| j | j  |jg |dR i |ddid |jg |dR i |ddid g| _|d
kr|jdd||j	ddd| _|jdd| ||j	ddd| _n|jdd||j	ddd| _|jdd| ||j	dd d| _d| _| | dS )!a	  
        Parameters
        ----------
        ax : Axes
            The Axes to put the slider in.

        label : str
            Slider label.

        valmin : float
            The minimum value of the slider.

        valmax : float
            The maximum value of the slider.

        valinit : tuple of float or None, default: None
            The initial positions of the slider. If None the initial positions
            will be at the 25th and 75th percentiles of the range.

        valfmt : str, default: None
            %-format string used to format the slider values.  If None, a
            `.ScalarFormatter` is used instead.

        closedmin : bool, default: True
            Whether the slider interval is closed on the bottom.

        closedmax : bool, default: True
            Whether the slider interval is closed on the top.

        dragging : bool, default: True
            If True the slider can be dragged by the mouse.

        valstep : float, default: None
            If given, the slider will snap to multiples of *valstep*.

        orientation : {'horizontal', 'vertical'}, default: 'horizontal'
            The orientation of the slider.

        track_color : :mpltype:`color`, default: 'lightgrey'
            The color of the background track. The track is accessible for
            further styling via the *track* attribute.

        handle_style : dict
            Properties of the slider handles. Default values are

            ========= ===== ======= =========================================
            Key       Value Default Description
            ========= ===== ======= =========================================
            facecolor color 'white' The facecolor of the slider handles.
            edgecolor color '.75'   The edgecolor of the slider handles.
            size      int   10      The size of the slider handles in points.
            ========= ===== ======= =========================================

            Other values will be transformed as marker{foo} and passed to the
            `~.Line2D` constructor. e.g. ``handle_style = {'style'='x'}`` will
            result in ``markerstyle = 'x'``.

        Notes
        -----
        Additional kwargs are passed on to ``self.poly`` which is the
        `~matplotlib.patches.Polygon` that draws the slider knob.  See the
        `.Polygon` documentation for valid property names (``facecolor``,
        ``edgecolor``, ``alpha``, etc.).
        Nr   r   r   r   r   r   c                 S   r   r   r   r   r   r   r   r     r   z(RangeSlider.__init__.<locals>.<dictcomp>r   r   r_      r   grid)whichr   r   r      d   r$   r   Fr   r   r`   r   r   r   r   r   )ri   r   r   r   arrayr   r   r   r   rk   r   r   rB   get_yaxis_transformget_xaxis_transformr   zerosr   _update_selection_polyset_transformget_path_interpolation_steps_request_autoscale_viewr   _handlesr   rl   r   r   _active_handler   )r   rB   rl   r   r   r   r   r   r   r   r   r   r   r   r   extentr   r   poly_transform
handleXY_1
handleXY_2r{   r   r   r   b  s   R






	
			zRangeSlider.__init__c                 C   s   | j j}| jdkr'd|f |d< |d< d|f|d< d|f|d< d|f|d< d	S |df |d< |d< |df|d< |df|d< |df|d< d	S )
zx
        Update the vertices of the *self.poly* slider in-place
        to cover the data range *vmin*, *vmax*.
        r   r   r      r   r   r     N)r   xyr   )r   vminvmaxvertsr   r   r   r    s   	
z"RangeSlider._update_selection_polyc                 C   sB   || j kr| js| jd S | j }|| jd kr| jd }| |S )z;Ensure the new min value is between valmin and self.val[1].r   r   )r   r   r   r   r   minr   r   r   _min_in_bounds/     



zRangeSlider._min_in_boundsc                 C   sB   || j kr| js| jd S | j }|| jd kr| jd }| |S )z;Ensure the new max value is between valmax and self.val[0].r   r   )r   r   r   r   r   maxr   r   r   _max_in_bounds:  r3  zRangeSlider._max_in_boundsc                 C   s   |  |d | |d fS )z#Clip min, max values to the bounds.r   r   )r2  r6  )r   valsr   r   r   r   E  s   zRangeSlider._value_in_boundsc                 C   s   t t | j| }|dkr| |}| | n
| |}| | | jr>| j	dkr5| j
|g dS | j|g dS dS )z2Update the slider value based on a given position.r   r   N)r   r   r   r   r2  set_minr6  set_maxr%  r   r  r  )r   posidxr   r   r   r   _update_val_from_posI  s   



z RangeSlider._update_val_from_posc                    s  |  |s
|jdkrdS |jdkr#| j|d r#d| _|j| j | js(dS |jdks:|jdkrI| j|d sId| _|j| j d| _	dS | 
|\ tt| jdkrc fd	d
| jD n	fdd
| jD }| j| }|| j	ur||| _	| | jdkr  dS  dS )r  r   Nrf   r   Trg   Fr   c                       g | ]
}|  d    qS r   )	get_xdatar   h)rS   r   r   
<listcomp>n      z'RangeSlider._update.<locals>.<listcomp>c                    r=  r>  )	get_ydatar@  )rT   r   r   rB  p  rC  )r=   r  r   rB   r~   r   rG   r   r   r%  rZ   r   r   r   r   r$  r<  )r   r<   handle_indexhandler   )rS   rT   r   r   X  s.   



"zRangeSlider._updatec                 C   s   | j durd| j |d   d| j |d   dS | j| jg|| j\}}}}|| j 7 }|| j 7 }d| d| dS )r  N(r   z, r   )r  )r   r   r  s1s2r   r   r   r   z  s   
&zRangeSlider._formatc                 C   s   |  || jd f dS )zx
        Set the lower value of the slider to *min*.

        Parameters
        ----------
        min : float
        r   Nr   r   r0  r   r   r   r8       zRangeSlider.set_minc                 C   s   |  | jd |f dS )zx
        Set the lower value of the slider to *max*.

        Parameters
        ----------
        max : float
        r   NrK  r4  r   r   r   r9    rL  zRangeSlider.set_maxc                 C   s   t |}tjd|d | j| jf| _| |\}}| || | j	dkr8| j
d |g | j
d |g n| j
d |g | j
d |g | j| ||f | jrb| jjddj  ||f| _| jru| jd||f d	S d	S )
z~
        Set slider value to *val*.

        Parameters
        ----------
        val : tuple or array-like of float
        )r  r  r   r   r   TrD   r   N)r   sortr   check_shaper   r   r   r   r  r   r$  r  r  r   r  r   r>   rB   rF   rG   r  r?   rp   r   )r   r   r-  r.  r   r   r   r     s"   


zRangeSlider.set_valc                    r   )a  
        Connect *func* as callback function to changes of the slider value.

        Parameters
        ----------
        func : callable
            Function to call when slider is changed. The function
            must accept a 2-tuple of floats as its argument.

        Returns
        -------
        int
            Connection id (which can be used to disconnect *func*).
        r   c                    r   r   r   r  r   r   r   rH     r   z(RangeSlider.on_changed.<locals>.<lambda>r   r   r   r   r   r    r  zRangeSlider.on_changed)r,   r-   r.   r/   r   r  r2  r6  r   r<  r   r   r8  r9  r   r  r   r   r   r{   r   r  S  s0     9"

r  c                 C   s,   t | tj} | rtdi |  S ti S Nr   )r
   normalize_kwargsmtextTextr   	itertoolsrepeatpropsr   r   r   _expand_text_props  s   rW  c                       s   e Zd ZdZdddddd fddZdd Zd	d
 Zd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  ZS ) CheckButtonsa  
    A GUI neutral set of check buttons.

    For the check buttons to remain responsive you must keep a
    reference to this object.

    Connect to the CheckButtons with the `.on_clicked` method.

    Attributes
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent Axes for the widget.
    labels : list of `~matplotlib.text.Text`
        The text label objects of the check buttons.
    NT)r^   label_propsframe_propscheck_propsc          
         s  t    tjtdf|||d  g   g   d |du r+dgt| }|o0| j	j
| _d| _tddt|d dd }t|} fdd	t|||D | _td
d	 | jD d }	|	d ddt|tjd jd}|d|dd |d|dd  jdgt| |fi || _d|	d dt|tjd j| jd}|d|dd  jdgt| |fi || _| | | d| j  | jr| d| j! tj"dgd| _#dS )aN  
        Add check buttons to `~.axes.Axes` instance *ax*.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            The parent Axes for the widget.
        labels : list of str
            The labels of the check buttons.
        actives : list of bool, optional
            The initial check states of the buttons. The list must have the
            same length as *labels*. If not given, all buttons are unchecked.
        useblit : bool, default: True
            Use blitting for faster drawing if supported by the backend.
            See the tutorial :ref:`blitting` for details.

            .. versionadded:: 3.7

        label_props : dict, optional
            Dictionary of `.Text` properties to be used for the labels.

            .. versionadded:: 3.7
        frame_props : dict, optional
            Dictionary of scatter `.Collection` properties to be used for the
            check button frame. Defaults (label font size / 2)**2 size, black
            edgecolor, no facecolor, and 1.0 linewidth.

            .. versionadded:: 3.7
        check_props : dict, optional
            Dictionary of scatter `.Collection` properties to be used for the
            check button check. Defaults to (label font size / 2)**2 size,
            black color, and 1.0 linewidth.

            .. versionadded:: 3.7
        N)rY  rZ  r[  Fr   r   r  c                    2   g | ]\}}} j d ||f jddd|qS r   r   r`   )rW   rb   ra   r   rk   r   rY   rl   rV  rB   r   r   rB        z)CheckButtons.__init__.<locals>.<listcomp>c                 S      g | ]}|  qS r   get_fontsizer   r   r   r   r   rB        )r	  	linewidthr	  )r   rW   r   rx   noner   black333333?)rh  r	  rX   r   rW   animatedrf   
draw_eventrc   rd   )$ri   r   r   check_isinstancedictrv   rw   rt   lenrG   rm   rn   _backgroundr   linspacerW  ziplabelsr  r
   rP  r   PathCollectionrk   
setdefaultgetpopscatter_frames_checks_init_statusrM   _clicked_clearro   rp   )
r   rB   ru  activesr^   rY  rZ  r[  ys	text_sizer{   ra  r   r     sX   %




  
zCheckButtons.__init__c                 C   <   |  |s
| j rdS | j| jj| _| j| j dS z,Internal event handler to clear the buttons.N)	r=   rG   	is_savingcopy_from_bboxrB   r   rr  r   r|  r;   r   r   r   r  >     zCheckButtons._clearc                       |   s jdks| j d sd S g | j d d  fddt| jD }|rQ| j | j	 }| 
| j jf||  d d   d S d S )Nr   r   indc                    "   g | ]\}}|  d  r|qS r>  r~   r   ir   r   r   r   rB  J     " z)CheckButtons._clicked.<locals>.<listcomp>r  r\  )r=   r  rB   r~   r{  	enumerateru  get_offset_transformrW   get_offsetsr5   rX   rY   sumr   r   r<   idxscoordsr   r   r   r~  E     $
$zCheckButtons._clickedc                 C   :   t jt|d t|}t| j|D ]	\}}|| qdS z
        Set properties of the `.Text` labels.

        .. versionadded:: 3.7

        Parameters
        ----------
        props : dict
            Dictionary of `.Text` properties to be used for the labels.
        rU  Nr   ro  rp  rW  rt  ru  updater   rV  r   propr   r   r   set_label_propsQ  
   zCheckButtons.set_label_propsc                 C   sB   t jt|d d|v rt|dt| j|d< | j	| dS )z
        Set properties of the check button frames.

        .. versionadded:: 3.7

        Parameters
        ----------
        props : dict
            Dictionary of `.Collection` properties to be used for the check
            button frames.
        rU  r	  sizesN)
r   ro  rp  r   broadcast_tory  rq  ru  r{  r  r   rV  r   r   r   set_frame_propsa  s   zCheckButtons.set_frame_propsc                 C   sT   t jt|d d|v rt|dt| j|d< |  }| j	
| | | dS )z
        Set properties of the check button checks.

        .. versionadded:: 3.7

        Parameters
        ----------
        props : dict
            Dictionary of `.Collection` properties to be used for the check
            button check.
        rU  r	  r  N)r   ro  rp  r   r  ry  rq  ru  
get_statusr|  r  r}  )r   rV  r  r   r   r   set_check_propsr  s   zCheckButtons.set_check_propsc                 C   s   |t t| jvrtd| tjtdf|d td}| j	
 }|du r/t|| |}|r6| j| n|||< | j	| | jrg| jrb| jdurR| j| j | j| j	 | j| jj n| j  | jrx| jd| j|   dS dS )a  
        Modify the state of a check button by index.

        Callbacks will be triggered if :attr:`eventson` is True.

        Parameters
        ----------
        index : int
            Index of the check button to toggle.

        state : bool, optional
            If a boolean value, set the state explicitly. If no value is
            provided, the state is toggled.

        Raises
        ------
        ValueError
            If *index* is invalid.
        TypeError
            If *state* is not boolean.
        zInvalid CheckButton index: Nstateri  rc   )rangerq  ru  r"   r   ro  boolr   to_rgbar|  r   r   _active_check_colorsru   r>   rn   rr  rG   restore_regionrB   r   r   r   r   r?   rp   r   get_text)r   indexr  	invisible
facecolorsr   r   r   r5     s&   



zCheckButtons.set_activec                 C   sT   | j  | _t| jdkrtj| jt|dd| _| j dd t| j|D  dS )a  
        Initialize properties to match active status.

        The user may have passed custom colours in *check_props* to the
        constructor, or to `.set_check_props`, so we need to modify the
        visibility after getting whatever the user set.
        r   r   r   c                 S   s   g | ]
\}}|r
|nd qS ri  r   )r   ecr4   r   r   r   rB    s    z-CheckButtons._init_status.<locals>.<listcomp>N)r|  r   r  rq  r   rT  ru   rt  )r   r  r   r   r   r}    s   
zCheckButtons._init_statusc                 C   sr   | j dgt| j  t| dr#| jD ]\}}|d |d q| jr+| j	  | j
r7| jdd dS dS )zUncheck all checkboxes.ri  _linesFrc   N)r|  ru   rq  r  r   r  set_visibler>   rG   r   r?   rp   r   )r   l1l2r   r   r   clear  s   


zCheckButtons.clearc                 C   s   dd | j  D S )zW
        Return a list of the status (True/False) of all of the check buttons.
        c                 S   s    g | ]}t |t d  qS r  )r   r   r  )r   rx   r   r   r   rB    s    z+CheckButtons.get_status.<locals>.<listcomp>)r|  get_facecolorsr   r   r   r   r    s   zCheckButtons.get_statusc                 C   s   dd t | j|  D S )z2Return a list of labels currently checked by user.c                 S   s   g | ]
\}}|r|  qS r   )r  )r   lbox_checkedr   r   r   rB    s    z3CheckButtons.get_checked_labels.<locals>.<listcomp>)rt  ru  r  r   r   r   r   get_checked_labels  s   zCheckButtons.get_checked_labelsc                    r   )   
        Connect the callback function *func* to button click events.

        Parameters
        ----------
        func : callable
            When the button is clicked, call *func* with button label.
            When all buttons are cleared, call *func* with None.
            The callback func must have the signature::

                def func(label: str | None) -> Any

            Return values may exist, but are ignored.

        Returns
        -------
        A connection id, which can be used to disconnect the callback.
        rc   c                    r   r   r   r   r   r   r   rH     r   z)CheckButtons.on_clicked.<locals>.<lambda>r   r   r   r   r   r     s   zCheckButtons.on_clickedc                 C   r   z-Remove the observer with connection id *cid*.Nr   r   r   r   r   r     r   zCheckButtons.disconnectr   )r,   r-   r.   r/   r   r  r~  r  r  r  r5   r}  r  r  r  r   r   r   r   r   r{   r   rX    s"    ]
.rX  c                       s   e Zd ZdZd$ddddd f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d Zdd Zdd Zdd Zd d! Zd"d# Z  ZS )%TextBoxaP  
    A GUI neutral text input box.

    For the text box to remain responsive you must keep a reference to it.

    Call `.on_text_change` to be updated whenever the text changes.

    Call `.on_submit` to be updated whenever the user hits enter or
    leaves the text entry field.

    Attributes
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent Axes for the widget.
    label : `~matplotlib.text.Text`

    color : :mpltype:`color`
        The color of the text box when not hovering.
    hovercolor : :mpltype:`color`
        The color of the text box when hovering.
     z.951g{Gz?r   )rx   ry   	label_padtextalignmentc             	      s  t  | tjdddd|d| _|j| d||jddd| _| jj| jd|| jjd|d	d
| _	t
jddgd| _|jddd	|g g d d| _|jdddd	ddtj d| _| d| j | d| j | d| j | d| j | d| j || _|| _d	| _dS )a  
        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            The `~.axes.Axes` instance the button will be placed into.
        label : str
            Label for this text box.
        initial : str
            Initial value in the text box.
        color : :mpltype:`color`
            The color of the box.
        hovercolor : :mpltype:`color`
            The color of the box when the mouse is over it.
        label_pad : float
            The distance between the label and the right side of the textbox.
        textalignment : {'left', 'center', 'right'}
            The horizontal location of the text.
        皙?r_   gffffff?)r   r`   r   )r  r`   r   r   F)rW   ra   rb   
parse_mathchangesubmitrd   r   r   )xlimylimnavigater   xticksyticksr   r   r   )visiblerx   r   rW   rf   rg   rh   key_press_eventresize_eventN)ri   r   r   check_getitem_text_positionr   rk   rl   rB   	text_dispr
   ro   rp   setcursor_indexvlinesmplr   IdentityTransformcursorrM   rq   rr   rs   	_keypress_resizerx   ry   capturekeystrokes)r   rB   rl   initialrx   ry   r  r  r{   r   r   r     s@   

zTextBox.__init__c                 C   
   | j  S r   )r  r  r   r   r   r   r   P  r+   zTextBox.textc                 C   s   | j jdd}| d u r|j  | j }|d | j }| j }| j	|p)d | j }|j
|jkrK| j
|jd 8  _
| j|jd 7  _n|sR|j|_n|j|j |_| jj|j|j
f|j|jfggdd | j	| |j  d S )NTrD   ,r  )segmentsr  )rB   rF   _get_rendererrG   r   r  r  r  get_window_extentr  y0y1heightx0x1widthr  r  )r   figr   	widthtextbb_textbb_widthtextr   r   r   _rendercursorT  s(   	




zTextBox._rendercursorc                 C   s2   |  |rd S |jj| jkrd S |j| j d S r   )r=   rG   r   rB   r   r;   r   r   r   rr   w  s
   
zTextBox._releasec                 C   s  |  |rd S | jr|j}| j}t|dkr.|d | j | || jd   }|  jd7  _ns|dkrA| jt|kr@|  jd7  _n`|dkrR| jdkrQ|  jd8  _nO|dkrZd| _nG|dkrdt|| _n=|dkr| jdkr|d | jd  || jd   }|  jd8  _n|dkr| jt| jkr|d | j || jd d   }| j| |   | j	r| j
d	| j |d
v r| j
d| j d S d S d S d S )Nr   r   r   r   homeend	backspacedeleter  )enterreturnr  )r=   r  keyr   rq  r  r  r  r  r?   rp   r   )r   r<   r  r   r   r   r   r  ~  sV   


zTextBox._keypressc                 C   sX   t |}| j|krd S | j| |   | jr*| jd| j | jd| j d S d S )Nr  r  )strr   r  r  r  r?   rp   r   )r   r   newvalr   r   r   r     s   
zTextBox.set_valc                 C   s   d| _ t }|j| _t| jjddjjdd }|d ur*|	|  |
|j	j|  d S t  |tdd tjD  W d    d S 1 sHw   Y  d S )NTrD   toolmanagerc                 S   s   i | ]
}| d r|g qS )zkeymap.)
startswith)r   r   r   r   r   r     rC  z(TextBox.begin_typing.<locals>.<dictcomp>)r  r   close_on_stop_typinggetattrrB   rF   rG   managerkeypresslockrK   r'   r   'suppress_matplotlib_deprecation_warningenter_contextr  
rc_contextrcParams)r   stackr  r   r   r   begin_typing  s   

"zTextBox.begin_typingc                 C   sj   | j r|   d | _d}nd}d| _ | jd | jjddj  |r1| jr3| j	
d| j d S d S d S )NTFrD   r  )r  r  r  r  rB   rF   rG   r   r?   rp   r   r   )r   notifysubmitr   r   r   stop_typing  s   
zTextBox.stop_typingc                 C   sz   |  |rd S | j|d s|   d S | jsd S |jj| jkr(|j| j | js/| 	  | j
|j| _|   d S r}   )r=   rB   r~   r  r?   rG   r   r   r  r  r  _char_index_atrX   r  r  r;   r   r   r   rq     s   
zTextBox._clickc                 C   s   |    d S r   )r  r;   r   r   r   r    s   zTextBox._resizec                 C   sn   |  |rd S | j|d r| jn| j}t|| j s3| j| | j	r5| jj
ddj  d S d S d S )Nr   TrD   )r=   rB   r~   ry   rx   r   r   r   ru   r>   rF   rG   r   r   r   r   r   rs     s   
zTextBox._motionc                    r   )z
        When the text changes, call this *func* with event.

        A connection id is returned which can be used to disconnect.
        r  c                    r   r   r   r  r   r   r   rH     r   z(TextBox.on_text_change.<locals>.<lambda>r   r   r   r   r   on_text_change  r   zTextBox.on_text_changec                    r   )z
        When the user hits enter or leaves the submission box, call this
        *func* with event.

        A connection id is returned which can be used to disconnect.
        r  c                    r   r   r   r  r   r   r   rH     r   z#TextBox.on_submit.<locals>.<lambda>r   r   r   r   r   	on_submit  s   zTextBox.on_submitc                 C   r   r  r   r   r   r   r   r     r   zTextBox.disconnect)r  )r,   r-   r.   r/   r   r@   r   r  rr   r  r   r  r  rq   r  rs   r  r  r   r   r   r   r{   r   r    s(    <
#$
		r  c                       s   e Zd ZdZddddd fddZdd	 Zd
d Zdd Zdd Ze	dd Z
e
jdd Z
dd Zdd Zdd Zdd Z  ZS )RadioButtonsa?  
    A GUI neutral radio button.

    For the buttons to remain responsive you must keep a reference to this
    object.

    Connect to the RadioButtons with the `.on_clicked` method.

    Attributes
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent Axes for the widget.
    activecolor : :mpltype:`color`
        The color of the selected button.
    labels : list of `.Text`
        The button labels.
    value_selected : str
        The label text of the currently selected button.
    index_selected : int
        The index of the selected button.
    r   NT)r^   rY  radio_propsc          
         s  t   tjtdf||d t|tj}|dur%d|v r$t	d nd}|| _
 | _|  | _ | _g  g  d tddt|d	 dd
 }|oX| jj| _d| _t|}fddt|||D | _tdd | jD d	 }	d|	d	 i|dj| jd}|d|dd |d|d| j dgt| |fi || _!| j!" | _#t| j#dkrtj$| j#t|dd| _#| j!% fddt&| j#D  | 'd| j( | jr| 'd| j) tj*dgd| _+dS )a<  
        Add radio buttons to an `~.axes.Axes`.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            The Axes to add the buttons to.
        labels : list of str
            The button labels.
        active : int
            The index of the initially selected button.
        activecolor : :mpltype:`color`
            The color of the selected button. The default is ``'blue'`` if not
            specified here or in *radio_props*.
        useblit : bool, default: True
            Use blitting for faster drawing if supported by the backend.
            See the tutorial :ref:`blitting` for details.

            .. versionadded:: 3.7

        label_props : dict or list of dict, optional
            Dictionary of `.Text` properties to be used for the labels.

            .. versionadded:: 3.7
        radio_props : dict, optional
            Dictionary of scatter `.Collection` properties to be used for the
            radio buttons. Defaults to (label font size / 2)**2 size, black
            edgecolor, and *activecolor* facecolor (when active).

            .. note::
                If a facecolor is supplied in *radio_props*, it will override
                *activecolor*. This may be used to provide an active color per
                button.

            .. versionadded:: 3.7
        N)rY  r
  r   zBoth the *activecolor* parameter and the *facecolor* key in the *radio_props* parameter has been specified. *activecolor* will be ignored.blueFr   r   r  r\  c                    r]  r^  r_  r`  ra  r   r   rB  ]  rb  z)RadioButtons.__init__.<locals>.<listcomp>c                 S   rc  r   rd  rf  r   r   r   rB  b  rg  r	  r$   rl  r   rx   rj  rk  r  c                    s    g | ]\}}| kr|nd qS r  r   )r   r  activecolorr:   r   r   rB  w  s    rf   rn  rc   rd   ),ri   r   r   ro  rp  r
   rP  r   rv  warn_external_activecolor_initial_activevalue_selectedindex_selectedrv   rw   rt   r   rs  rq  rG   rm   rn   rr  rW  rt  ru  r  rk   rw  rx  ry  rz  _buttonsr   _active_colorsrT  ru   r  rM   r~  r  ro   rp   )
r   rB   ru  r4   r  r^   rY  r
  r  r  r{   )r4   rB   r   r     sp   &






 
zRadioButtons.__init__c                 C   r  r  )	r=   rG   r  r  rB   r   rr  r   r  r;   r   r   r   r    r  zRadioButtons._clearc                    r  )Nr   r   r  c                    r  r>  r  r  r   r   r   rB    r  z)RadioButtons._clicked.<locals>.<listcomp>r  r\  )r=   r  rB   r~   r  r  ru  r  rW   r  r5   rX   rY   r  r   r  r   r   r   r~    r  zRadioButtons._clickedc                 C   r  r  r  r  r   r   r   r    r  zRadioButtons.set_label_propsc                    s   t jt|d d|v rt|dt j|d<  j	|  j
  _t jdkr9tj jt jdd _ j fddt j jD  d	S )
z
        Set properties of the `.Text` labels.

        .. versionadded:: 3.7

        Parameters
        ----------
        props : dict
            Dictionary of `.Collection` properties to be used for the radio
            buttons.
        rU  r	  r  r   r   r  c                    s&   g | ]\}}|   jkr|nd qS r  )r  r  )r   r   r  r   r   r   rB    s    z0RadioButtons.set_radio_props.<locals>.<listcomp>N)r   ro  rp  r   r  ry  rq  ru  r  r  r   r  rT  ru   rt  r  r   r   r   set_radio_props  s   

zRadioButtons.set_radio_propsc                 C   r6   r   )r  r   r   r   r   r    r8   zRadioButtons.activecolorc                 C   s$   t j|d || _| d|i d S )N)r  r   )r   _check_color_liker  r  )r   r  r   r   r   r    s   c                 C   s   |t t| jvrtd| | j|  | _|| _| j }t	
d|dd< t	
| j| ||< | j| | jr`| jr[| jdurK| j| j | j| j | j| jj n| j  | jrq| jd| j|   dS dS )a9  
        Select button with number *index*.

        Callbacks will be triggered if :attr:`eventson` is True.

        Parameters
        ----------
        index : int
            The index of the button to activate.

        Raises
        ------
        ValueError
            If the index is invalid.
        zInvalid RadioButton index: ri  Nrc   )r  rq  ru  r"   r  r  r  r  r   r   r  r  ru   r>   rn   rr  rG   r  rB   r   r   r   r   r?   rp   r   )r   r  button_facecolorsr   r   r   r5     s$   


zRadioButtons.set_activec                 C   s   |  | j dS )z4Reset the active button to the initially active one.N)r5   r  r   r   r   r   r    r   zRadioButtons.clearc                 C   s   | j d|S )r  rc   r   r   r   r   r   r     s   zRadioButtons.on_clickedc                 C   r   r  r   r   r   r   r   r     r   zRadioButtons.disconnect)r   N)r,   r-   r.   r/   r   r  r~  r  r  r@   r  setterr5   r  r   r   r   r   r   r{   r   r	    s"    h

%r	  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	SubplotToolz=
    A tool to adjust the subplot params of a `.Figure`.
    c              	   C   sH  || _ || _|jddd |d g | _g d}t||t|d D ]"\}}|d t	||ddt
|j|d	}|| j | j| q%|jd
   | j\| _| _| _| _| _| _| j| j| j| jfD ]}d|_qh| j| jfD ]}d|_qt| j| j_| j| j_| j| j_| j| j_|g d}t|d| _| j| j dS )z
        Parameters
        ----------
        targetfig : `~matplotlib.figure.Figure`
            The figure instance to adjust.
        toolfig : `~matplotlib.figure.Figure`
            The figure instance to embed the subplot tool into.
        皙?g?)r   r   z'Click on slider to adjust subplot param)r   r   r   r   wspacehspacer   Fr   )r   r\  )g?r  rk  g333333?ResetN) figure	targetfigsubplots_adjustsuptitle_slidersrt  subplotsrq  rt   r   r  subplotparsr  _on_slider_changedrJ   axesremove
sliderleftsliderbottomsliderright	slidertopsliderwspacesliderhspacer   r   r   r   add_axesr[   buttonresetr   	_on_reset)r   r  toolfignamesr   rB   sliderbaxr   r   r   r     s<   

 






zSubplotTool.__init__c                 C   s8   | j jdi dd | jD  | jr| j j  d S d S )Nc                 S   s   i | ]	}|j  |jqS r   )rl   r  r   )r   r2  r   r   r   r   :  s    z2SubplotTool._on_slider_changed.<locals>.<dictcomp>r   )r  r  r!  r>   rG   r   )r   r  r   r   r   r$  8  s   
zSubplotTool._on_slider_changedc              	   C   s   t  -}|tj| dd | jD ]}|tj|ddd q| jD ]}|  q"W d    n1 s3w   Y  | jr@|j  | 	d  d S )NF)r>   )r>   r?   )
r   r  r
   _setattr_cmr!  r   r>   rG   r   r$  )r   r<   r  r2  r   r   r   r/  ?  s   



zSubplotTool._on_resetN)r,   r-   r.   r/   r   r$  r/  r   r   r   r   r    s
    +r  c                       s:   e Zd ZdZdddd fdd
Zdd Zd	d
 Z  ZS )Cursora+  
    A crosshair cursor that spans the Axes and moves with mouse cursor.

    For the cursor to remain responsive you must keep a reference to it.

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        The `~.axes.Axes` to attach the cursor to.
    horizOn : bool, default: True
        Whether to draw the horizontal line.
    vertOn : bool, default: True
        Whether to draw the vertical line.
    useblit : bool, default: False
        Use blitting for faster drawing if supported by the backend.
        See the tutorial :ref:`blitting` for details.

    Other Parameters
    ----------------
    **lineprops
        `.Line2D` properties that control the appearance of the lines.
        See also `~.Axes.axhline`.

    Examples
    --------
    See :doc:`/gallery/widgets/cursor`.
    TF)horizOnvertOnr^   c                   s   t  | | d| j | d| j d| _|| _|| _|o"| jj	| _
| j
r+d|d< |j| d fddi|| _|j| d fddi|| _d | _d| _d S )Nrh   rn  Trm  r   r  F)ri   r   rM   onmover  r  r6  r7  rG   rm   r^   r   
get_yboundlinehr   
get_xboundlinev
background	needclear)r   rB   r6  r7  r^   	linepropsr{   r   r   r   l  s     
zCursor.__init__c                 C   s8   |  |s
| j rdS | jr| j| jj| _dS dS )z+Internal event handler to clear the cursor.N)r=   rG   r  r^   r  rB   r   r=  r;   r   r   r   r    s
   zCursor.clearc                 C   s0  |  |rdS | jj| sdS | j|d s1| jd | jd | j	r/| j
  d| _	dS d| _	| |\}}| j||f | j| joK| j | j||f | j| jo]| j | jrh| jsj| jsjdS | jr| jdury| j| j | j| j | j| j | j| jj dS | j  dS )z?Internal event handler to draw the cursor when the mouse moves.Nr   FT)r=   rG   
widgetlockr!   rB   r~   r<  r  r:  r>  r   rZ   r  r  r7  r  r6  r^   r=  r  r   r   r   r  r   r<   rS   rT   r   r   r   r8    s4   


zCursor.onmove)r,   r-   r.   r/   r   r  r8  r   r   r   r{   r   r5  P  s
    r5  c                   @   sB   e Zd ZdZddddddZdd Zd	d
 Zdd Zdd ZdS )MultiCursora  
    Provide a vertical (default) and/or horizontal line cursor shared between
    multiple Axes.

    For the cursor to remain responsive you must keep a reference to it.

    Parameters
    ----------
    canvas : object
        This parameter is entirely unused and only kept for back-compatibility.

    axes : list of `~matplotlib.axes.Axes`
        The `~.axes.Axes` to attach the cursor to.

    useblit : bool, default: True
        Use blitting for faster drawing if supported by the backend.
        See the tutorial :ref:`blitting`
        for details.

    horizOn : bool, default: False
        Whether to draw the horizontal line.

    vertOn : bool, default: True
        Whether to draw the vertical line.

    Other Parameters
    ----------------
    **lineprops
        `.Line2D` properties that control the appearance of the lines.
        See also `~.Axes.axhline`.

    Examples
    --------
    See :doc:`/gallery/widgets/multicursor`.
    TF)r^   r6  r7  c                   s   || _ || _|| _|| _dd |D | _|d  \}}|d  \}	}
d||  d|	|
  d| _|o>tdd | jD | _	| j	rGd d<  fd	d
|D | _
 fdd
|D | _|   d S )Nc                 S   s"   i | ]}|j d djg ddqS )TrD   N)cidsr=  )rF   rG   r   rB   r   r   r   r     s
    z(MultiCursor.__init__.<locals>.<dictcomp>r\  r_   Tc                 s   s    | ]}|j V  qd S r   )rm   )r   rG   r   r   r   	<genexpr>  s    z'MultiCursor.__init__.<locals>.<genexpr>rm  c                    "   g | ]}|j fd di qS r  F)r   rD  )r?  xmidr   r   rB        z(MultiCursor.__init__.<locals>.<listcomp>c                    rF  rG  )r   rD  )r?  ymidr   r   rB    rI  )_canvasr%  r6  r7  _canvas_infosget_xlimget_ylimr  allr^   r  hlinesr   )r   rG   r%  r^   r6  r7  r?  xminxmaxyminymaxr   )r?  rH  rJ  r   r     s0   zMultiCursor.__init__c                 C   s8   | j  D ]\}}|d| j|d| jg|d< qdS )zConnect events.rh   rn  rC  N)rL  r   rI   r8  r  )r   rG   infor   r   r   r     s
   
zMultiCursor.connectc                 C   s<   | j  D ]\}}|d D ]}|| q|d   qdS )zDisconnect events.rC  N)rL  r   rN   r  )r   rG   rU  rL   r   r   r   r     s
   zMultiCursor.disconnectc                 C   sP   |  |rdS | jr$| j D ]\}}||jjurq||jj|d< qdS dS )zClear the cursor.Nr=  )r=   r^   rL  r   r  rG   r  r   )r   r<   rG   rU  r   r   r   r    s   
zMultiCursor.clearc           	         s   fdd| j D }|  s|r jj| sd S t|} j|u r* j j	fn|j
  j jf\}}| jD ]}|||f || joK| j q;| jD ]}|||f || joa| j qQ| jrm| jso| jsod S | jr| j D ]\}}|d r||d  qw| jrt| j | jD ]	\}}|| q| jrt| j | jD ]	\}}|| q| jD ]}|  qd S | jD ]}|  qd S )Nc                    s   g | ]}|  d  r|qS r>  r  rD  r   r   r   rB    s    z&MultiCursor.onmove.<locals>.<listcomp>r=  )r%  r=   rG   r@  r!   r
   _topmost_artistrR   rS   rT   rU   rV   rW   rX   rY   r  r  r  r  r7  rP  r  r6  r^   rL  r   r  rt  r   r   r  )	r   r<   axsrB   rS   rT   linerG   rU  r   r   r   r8    s@   






zMultiCursor.onmoveN)	r,   r-   r.   r/   r   r   r   r  r8  r   r   r   r   rB    s    $"rB  c                       s  e Zd Z		dA fdd	Z fddZdd Zd	d
 Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zed5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z!d?d@ Z"  Z#S )B_SelectorWidgetNFc                    s   t  | d| _|d u rdd | _n|| _|o| jj| _|   tdddddd	| _	| j	
|p1i  || _d | _t|trC|g| _n|| _d
| _d | _d | _d | _t | _d S )NTc                  W   s   d S r   r   )argsr   r   r   rH   4      z*_SelectorWidget.__init__.<locals>.<lambda> escapeshiftcontrolr   )mover  squarer`   rotateF)ri   r   _visibleonselectrG   rm   r^   connect_default_eventsrp  _state_modifier_keysr  _use_data_coordinatesr=  r   r   validButtons_selection_completed_eventpress_eventrelease_prev_eventr  _state)r   rB   rd  r^   r  state_modifier_keysuse_data_coordinatesr{   r   r   r   .  s,   

z_SelectorWidget.__init__c                    s"   t  | |r| d  d S d S r   )ri   r5   update_backgroundr3   r{   r   r   r5   Q  s   z_SelectorWidget.set_activec                    s    t  fdd j  D S )aG  
        Convenience method to get all animated artists of the figure containing
        this widget, excluding those already present in self.artists.
        The returned tuple is not sorted by 'z_order': z_order sorting is
        valid only when considering all artists and not only a subset of all
        artists.
        c                 3   s4    | ]}|  D ]}| r| jvr|V  qqd S r   )get_childrenget_animatedartists)r   ax_ar   r   r   rE  ^  s    
z8_SelectorWidget._get_animated_artists.<locals>.<genexpr>)tuplerB   rF   get_axesr   r   r   r   _get_animated_artistsV  s    z%_SelectorWidget._get_animated_artistsc                 C   s   | j sdS t| j|   dd d}tdd |D }t &}|r4|D ]}||jdd q#| j	  | j
| jj| _W d   n1 sGw   Y  |rY|D ]
}| j| qPdS dS )	z"Force an update of the background.Nc                 S      |   S r   
get_zorderru  r   r   r   rH   p  r   z3_SelectorWidget.update_background.<locals>.<lambda>r  c                 s   s    | ]}|  V  qd S r   )get_visible)r   artistr   r   r   rE  q  s    z4_SelectorWidget.update_background.<locals>.<genexpr>F)r  )r^   sortedrs  rx  r   r   r  _cm_setrG   r   r  rB   r   r=  r   )r   r<   rs  needs_redrawr  r  r   r   r   rp  b  s$   
z!_SelectorWidget.update_backgroundc                 C   sf   |  d| j |  d| j |  d| j |  d| j |  d| j |  d| j |  d| j dS )	z+Connect the major canvas events to methods.rh   rf   rg   rn  r  key_release_eventscroll_eventN)rM   r8  pressr'   rp  on_key_presson_key_release	on_scrollr   r   r   r   re  |  s   z&_SelectorWidget.connect_default_eventsc                 C   s   | j r| j s
dS | jj| sdS t|dsd |_| jd ur(|j| jvr(dS | j	d u r6| j
|d  S |j| j	jkr?dS | j
|d  pN|j| j	jkS )NTr  r   F)r4   rB   r~  rG   r@  r!   r   r  rh  rj  r~   r;   r   r   r   r=     s    


z_SelectorWidget.ignorec                 C   s   | j  r| j jdd du rdS | jrI| jdur"| j| j n| d t	| j
|   dd d}|D ]}| j | q6| j| j j dS | j  dS )z@Draw using blit() or draw_idle(), depending on ``self.useblit``.TrD   Nc                 S   ry  r   rz  r|  r   r   r   rH     r   z(_SelectorWidget.update.<locals>.<lambda>r}  )rB   r~  rF   r  r^   r=  rG   r  rp  r  rs  rx  r   r   r   r  )r   rs  r  r   r   r   r    s   


z_SelectorWidget.updatec                 C   sT   |j du rdS | |\}}tj|g| j R  }tj|g| j R  }||fS )z/Get the xdata and ydata for event, with limits.N)NN)rS   rZ   r   cliprB   r;  r9  rA  r   r   r   	_get_data  s   
z_SelectorWidget._get_datac                 C   s8   |j du r	| j}nt|}| |\|_ |_|| _|S )a  
        Preprocess an event:

        - Replace *event* by the previous event if *event* has no ``xdata``.
        - Get ``xdata`` and ``ydata`` from this widget's Axes, and clip them to the axes
          limits.
        - Update the previous event.
        N)rS   rl  copyr  rT   r;   r   r   r   _clean_event  s   
	
z_SelectorWidget._clean_eventc                 C   sb   |  |s/| |}|| _|| _|jpd}|dd}|| jd kr(| jd | 	| dS dS )z#Button press handler and validator.r  ctrlr_  r`  TF)
r=   r  rj  rl  r  replacerf  rm  add_press)r   r<   r  r   r   r   r    s   



z_SelectorWidget.pressc                 C      dS )Button press event handler.Nr   r;   r   r   r   r    r[  z_SelectorWidget._pressc                 C   sJ   |  |s#| jr#| |}|| _| | d| _d| _| jd dS dS )z+Button release event handler and validator.Nr`  TF)r=   rj  r  rk  rr   rm  discardr;   r   r   r   r'     s   

z_SelectorWidget.releasec                 C   r  )Button release event handler.Nr   r;   r   r   r   rr     r[  z_SelectorWidget._releasec                 C   s,   |  |s| jr| |}| | dS dS )(Cursor move event handler and validator.TF)r=   rj  r  _onmover;   r   r   r   r8    s
   

z_SelectorWidget.onmovec                 C   r  )Cursor move event handler.Nr   r;   r   r   r   r    r[  z_SelectorWidget._onmovec                 C   s   |  |s| | dS dS )z)Mouse scroll event handler and validator.N)r=   
_on_scrollr;   r   r   r   r    rQ   z_SelectorWidget.on_scrollc                 C   r  )zMouse scroll event handler.Nr   r;   r   r   r   r    r[  z_SelectorWidget._on_scrollc                 C   s   | j rP|jpd}|dd}|| jd kr|   dS | j D ](\}}||dv rH|dkrB|| jv r;| j| q | j	| q | j	| q | 
| dS dS )z@Key press event handler and validator for all selection widgets.r  r  r_  r  N+rb  )r4   r  r  rf  r  r   splitrm  r  r  _on_key_pressr   r<   r  r  modifierr   r   r   r  	  s    

z_SelectorWidget.on_key_pressc                 C   r  )z@Key press event handler - for widget-specific key press actions.Nr   r;   r   r   r   r  	  r[  z_SelectorWidget._on_key_pressc                 C   sX   | j r*|jpd}| j D ]\}}||dv r"|dkr"| j| q| | dS dS )z(Key release event handler and validator.r  r  rb  N)r4   r  rf  r   r  rm  r  _on_key_releaser  r   r   r   r  	  s   
z_SelectorWidget.on_key_releasec                 C   r  )Key release event handler.Nr   r;   r   r   r   r  $	  r[  z_SelectorWidget._on_key_releasec                 C   s    || _ | jD ]}|| qdS )z+Set the visibility of the selector artists.N)rc  rs  r  )r   r  r  r   r   r   r  '	  s   
z_SelectorWidget.set_visiblec                 C   r6   )z+Get the visibility of the selector artists.)rc  r   r   r   r   r~  -	  r8   z_SelectorWidget.get_visiblec                 C      |    |   dS )zAClear the selection and set the selector ready to make a new one.N)_clear_without_updater  r   r   r   r   r  1	     z_SelectorWidget.clearc                 C   s   d| _ | d d S NF)ri  r  r   r   r   r   r  6	  s   z%_SelectorWidget._clear_without_updatec                 C   s   t | dd}| jf| S )z%Tuple of the artists of the selector._handles_artistsr   )r  _selection_artist)r   handles_artistsr   r   r   rs  :	  s   z_SelectorWidget.artistsc                 K   s8   | j }t||}|jdi | | jr|   dS dS )z
        Set the properties of the selector artist.

        See the *props* argument in the selector docstring to know which properties are
        supported.
        Nr   )r  r
   rP  r  r^   r  )r   rV  r  r   r   r   	set_props@	  s   z_SelectorWidget.set_propsc                 K   sb   t | ds	td| jd }t||}| jD ]
}|jdi | q| jr)|   | j| dS )z
        Set the properties of the handles selector artist. See the
        `handle_props` argument in the selector docstring to know which
        properties are supported.
        r  z#This selector doesn't have handles.r   Nr   )	r   NotImplementedErrorr  r
   rP  r  r^   r  _handle_props)r   handle_propsr  rF  r   r   r   set_handle_propsM	  s   


z _SelectorWidget.set_handle_propsc                 C   s&   dd | j  D }tj||d d S )Nc                 S   s$   g | ]\}}|d kr|dkr|qS )r  not-applicabler   )r   r  valuer   r   r   rB  _	  s
    z3_SelectorWidget._validate_state.<locals>.<listcomp>r  )rf  r   r   r   )r   r  supported_stater   r   r   _validate_state^	  s   z_SelectorWidget._validate_statec                 C      |  | | j| dS )a  
        Add a state to define the widget's behavior. See the
        `state_modifier_keys` parameters for details.

        Parameters
        ----------
        state : str
            Must be a supported state of the selector. See the
            `state_modifier_keys` parameters for details.

        Raises
        ------
        ValueError
            When the state is not supported by the selector.

        N)r  rm  r  r   r  r   r   r   	add_statee	     
z_SelectorWidget.add_statec                 C   r  )a  
        Remove a state to define the widget's behavior. See the
        `state_modifier_keys` parameters for details.

        Parameters
        ----------
        state : str
            Must be a supported state of the selector. See the
            `state_modifier_keys` parameters for details.

        Raises
        ------
        ValueError
            When the state is not supported by the selector.

        N)r  rm  r&  r  r   r   r   remove_statey	  r  z_SelectorWidget.remove_state)NFNNF)$r,   r-   r.   r   r5   rx  rp  re  r=   r  r  r  r  r  r'   rr   r8  r  r  r  r  r  r  r  r  r~  r  r  r@   rs  r  r  r  r  r  r   r   r   r{   r   rY  ,  sF    #
	
rY  c                       s   e Zd ZdZddddddddddddd fdd
Zddd	d
dZdd Zedd Zdd Z	 fddZ
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#d$ Zed%d& Zed'd( Zejd)d( Zd*d+ Z  ZS ),SpanSelectora  
    Visually select a min/max range on a single axis and call a function with
    those values.

    To guarantee that the selector remains responsive, keep a reference to it.

    In order to turn off the SpanSelector, set ``span_selector.active`` to
    False.  To turn it back on, set it to True.

    Press and release events triggered at the same coordinates outside the
    selection will clear the selector, except when
    ``ignore_event_outside=True``.

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`

    onselect : callable with signature ``func(min: float, max: float)``
        A callback function that is called after a release event and the
        selection is created, changed or removed.

    direction : {"horizontal", "vertical"}
        The direction along which to draw the span selector.

    minspan : float, default: 0
        If selection is less than or equal to *minspan*, the selection is
        removed (when already existing) or cancelled.

    useblit : bool, default: False
        If True, use the backend-dependent blitting features for faster
        canvas updates. See the tutorial :ref:`blitting` for details.

    props : dict, default: {'facecolor': 'red', 'alpha': 0.5}
        Dictionary of `.Patch` properties.

    onmove_callback : callable with signature ``func(min: float, max: float)``, optional
        Called on mouse move while the span is being selected.

    interactive : bool, default: False
        Whether to draw a set of handles that allow interaction with the
        widget after it is drawn.

    button : `.MouseButton` or list of `.MouseButton`, default: all buttons
        The mouse buttons which activate the span selector.

    handle_props : dict, default: None
        Properties of the handle lines at the edges of the span. Only used
        when *interactive* is True. See `.Line2D` for valid properties.

    grab_range : float, default: 10
        Distance in pixels within which the interactive tool handles can be activated.

    state_modifier_keys : dict, optional
        Keyboard modifiers which affect the widget's behavior.  Values
        amend the defaults, which are:

        - "clear": Clear the current shape, default: "escape".

    drag_from_anywhere : bool, default: False
        If `True`, the widget can be moved by clicking anywhere within its bounds.

    ignore_event_outside : bool, default: False
        If `True`, the event triggered outside the span selector will be ignored.

    snap_values : 1D array-like, optional
        Snap the selector edges to the given values.

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> import matplotlib.widgets as mwidgets
    >>> fig, ax = plt.subplots()
    >>> ax.plot([1, 2, 3], [10, 50, 100])
    >>> def onselect(vmin, vmax):
    ...     print(vmin, vmax)
    >>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal',
    ...                              props=dict(facecolor='blue', alpha=0.5))
    >>> fig.show()

    See also: :doc:`/gallery/widgets/span_selector`
    r   FNr   )minspanr^   rV  onmove_callbackinteractiver  r  
grab_rangern  drag_from_anywhereignore_event_outsidesnap_valuesc                   s   |d u rt ddddd}t j||||	|d |d u r!t ddd}| j|d< || _d | _|| _|| _|| _|| _	|| _
d | _|| _|| _| j||d	d
 d|ddit|
t| _| j
riddg| _| | j d | _d S )Nr]  r  )r  ra  r`   rb  )r^   r  rn  redr_   )r   alpharm  T_props_initrx   r   r   r1  r5  )rp  ri   r   r^   	direction_extents_on_pressr  r  r  r  _interactive_edge_handlesr  r  new_axesrx  r
   rP  r   r  _edge_order_setup_edge_handlesr%  )r   rB   rd  r  r  r^   rV  r  r  r  r  r  rn  r  r  r  r{   r   r   r   	  s>   



zSpanSelector.__init__r  c          	      C   s   d}|s| j |jddj ur| j dur|   d}|| _|r"|   d| _| jdkr3| }d\}}n| }d\}}t	d|||dd	}|durN|
| n| jdurY|| j | j| || _dS )
z*Set SpanSelector to operate on a new Axes.FTrD   Nr   r  )r   r   r   r   )rW   r  )rG   rF   rP   rB   re  ri  r  r  r  r   r  r  update_fromr   )	r   rB   r  r  	reconnecttranswrA  rect_artistr   r   r   r  
  s*   




zSpanSelector.new_axesc                 C   s>   | j dkr| j }n| j }t| j|| j || jd| _d S )Nr   )r  
line_propsr^   )r  rB   r;  r9  ToolLineHandlesr^   r  )r   rV  	positionsr   r   r   r  +
  s   

z SpanSelector._setup_edge_handlesc                 C   s   | j d ur	| j jS dS rO  )r  rs  r   r   r   r   r  6
  s   
zSpanSelector._handles_artistsc                 C   sB   |r| j dkrtjjntjj}ntjj}| jjddj	| dS )z<Update the canvas cursor based on direction of the selector.r   TrD   N)
r  r	   CursorsRESIZE_HORIZONTALRESIZE_VERTICALPOINTERrB   rF   rG   
set_cursor)r   enabledr  r   r   r   _set_cursor=
  s   
zSpanSelector._set_cursorc                    s,   t    t| ddr| d| j d S d S )Nr  Frh   )ri   re  r  rM   _hoverr   r{   r   r   re  H
  s   
z#SpanSelector.connect_default_eventsc                 C   s   |  d | jr| j r| | nd| _| jdu s| js"|   | |\}}| jdkr0|n|}| jdu rI| j	sId| _
| ||f d| _
dS | d dS )r  TNr   F)r  r  r  r~  _set_active_handler%  r  rZ   r  r  rc  _set_extentsr  )r   r<   rS   rT   r   r   r   r   r  N
  s   

zSpanSelector._pressc                 C   r6   )z;Direction of the span selector: 'vertical' or 'horizontal'.
_directionr   r   r   r   r  k
     zSpanSelector.directionc                 C   sv   t jddg|d t| dr6|| jkr6| j  | jr | j  || _| | j	 | jr4| 
| j dS dS || _dS )z'Set the direction of the span selector.r   r   r  r  N)r   r   r   r  r  r&  r  r  r  rB   r  r  )r   r  r   r   r   r  p
  s   


c                 C   s   |  d | js| jd | jdu r| jr| jrdS | j\}}|| }|| jkr;| d | jr7| 	|| d| _n	| 	|| d| _| 
  d| _dS )r  FNT)r  r  r  r  r%  ri  r  extentsr  rd  r  )r   r<   r-  r.  spanr   r   r   rr   
  s&   



zSpanSelector._releasec                 C   sL   |  |rdS | jdus| jsdS | j|j|j\}}| || jk dS )z/Update the canvas cursor if it's over a handle.N)	r=   r%  ri  r  closestrX   rY   r  r  )r   r<   r  e_distr   r   r   r  
  s   
zSpanSelector._hoverc           	      C   s   |  |\}}| jdkr|}| jj}n|}| jj}| jdkr5| jdur5| j\}}|| }||7 }||7 }n.| jrM| jdkrM| j\}}| jdkrJ|}n|}n| jrU| jrUdS ||}}||krc||}}| 	||f | j
duru| 
|| dS )zMotion notify event handler.r   CNr1  F)rZ   r  rj  rS   rT   r%  r  r  ri  r  r  )	r   r<   rS   rT   r   vpressr-  r.  dvr   r   r   r  
  s2   








zSpanSelector._onmovec                 C   s\   ||kr	||}}| j dkr| j| | j||  d S | j| | j||  d S )Nr   )r  r  set_xr  set_yr
  r   r-  r.  r   r   r   _draw_shape
  s   

zSpanSelector._draw_shapec                 C   sz   | j |j|j\}}d| jv rd| _n#|| jkr1d| _| jr,| |r,d| _| j	| _
nd| _dS | j| | _| j	| _
dS );Set active handle based on the location of the mouse event.r`  r  N)r  r  rX   rY   rm  r%  r  r  	_containsr  r  r  )r   r<   e_idxr  r   r   r   r  
  s   


zSpanSelector._set_active_handlec                 C      | j j|ddd S z)Return True if event is within the patch.r   )radiusr  r~   r;   r   r   r   r  
  r*   zSpanSelector._containsc                    s2   t t t d  t fdd| D S )z2Snap values to a given array values (snap_values).g-q=c                 3   s4    | ]}t | t |     V  qd S r   )r   r   signr   )r   r   epsr  r   r   rE    s
    "
z%SpanSelector._snap.<locals>.<genexpr>)r   r1  r   diffrv  )valuesr  r   r  r   _snap  s   zSpanSelector._snapc                 C   sJ   | j dkr| j }|| j  }||fS | j }|| j  }||fS )z
        (float, float)
            The values, in data coordinates, for the start and end points of the current
            selection. If there is no selection then the start and end values will be
            the same.
        r   )r  r  r  	get_widthr  
get_heightr  r   r   r   r    s   


zSpanSelector.extentsc                 C   s   |  | d| _d S NT)r  ri  r   r  r   r   r   r    s   

c                 C   sR   | j d urt| || j }| j|  | jr| j| j | | j	 | 
  d S r   )r  rv  r  r  r  r  set_datar  r  rc  r  r  r   r   r   r     s   

zSpanSelector._set_extents)r,   r-   r.   r/   r   r  r  r@   r  r  re  r  r  r  rr   r  r  r  r  r  staticmethodr  r  r  r   r   r   r{   r   r  	  s@    R-


,



r  c                   @   sl   e Zd ZdZdddddZedd Zed	d
 Zedd Zdd Z	dd Z
dd Zdd Zdd ZdS )r  a`  
    Control handles for canvas tools.

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        Matplotlib Axes where tool handles are displayed.
    positions : 1D array
        Positions of handles in data coordinates.
    direction : {"horizontal", "vertical"}
        Direction of handles, either 'vertical' or 'horizontal'
    line_props : dict, optional
        Additional line properties. See `.Line2D`.
    useblit : bool, default: True
        Whether to use blitting for faster drawing (if supported by the
        backend). See the tutorial :ref:`blitting`
        for details.
    NT)r  r^   c                   sl   || _ tjddg|d || _i d urni d|d| jdkr&|jn|j  fdd|D | _d S )Nr   r   r  F)r  rm  c                    s   g | ]
} |fi qS r   r   r   pline_funr  r   r   rB  O  rC  z,ToolLineHandles.__init__.<locals>.<listcomp>)rB   r   r   r  r  r   r   _artists)r   rB   r  r  r  r^   r   r   r   r   @  s   zToolLineHandles.__init__c                 C   s
   t | jS r   )rv  r  r   r   r   r   rs  Q  r+   zToolLineHandles.artistsc                    s&   | j dkrdnd  fdd| jD S )z,Positions of the handle in data coordinates.r   r?  rD  c                    s   g | ]
}t |  d  qS r>  )r  )r   rX  methodr   r   rB  Y  rC  z-ToolLineHandles.positions.<locals>.<listcomp>)r  rs  r   r   r  r   r  U  s   zToolLineHandles.positionsc                 C   r6   )z4Direction of the handle: 'vertical' or 'horizontal'.r  r   r   r   r   r  [  r  zToolLineHandles.directionc                 C   s>   | j dkrdnd}t| j|D ]\}}t||||g qdS )z
        Set x- or y-positions of handles, depending on if the lines are
        vertical or horizontal.

        Parameters
        ----------
        positions : tuple of length 2
            Set the positions of the handle in data coordinates
        r   r  r  N)r  rt  rs  r  )r   r  r  rX  r  r   r   r   r  `  s   
zToolLineHandles.set_datac                 C      | j D ]}|| qdS )z/Set the visibility state of the handles artist.N)rs  r  r   r  r  r   r   r   r  n     
zToolLineHandles.set_visiblec                 C   r  )z-Set the animated state of the handles artist.N)rs  set_animatedr  r   r   r   r  s  r  zToolLineHandles.set_animatedc                 C   s   | j D ]}|  qdS )z*Remove the handles artist from the figure.N)r  r&  )r   r  r   r   r   r&  x  s   

zToolLineHandles.removec                    sn    j dkrt fdd jD }t|| }nt fdd jD }t|| }t|}||| fS )ar  
        Return index and pixel distance to closest handle.

        Parameters
        ----------
        x, y : float
            x, y position from which the distance will be calculated to
            determinate the closest handle

        Returns
        -------
        index, distance : index of the handle and its distance from
            position x, y
        r   c                    s"   g | ]} j j|d fd  qS r>  rB   rU   rW   r  r   r   r   rB        z+ToolLineHandles.closest.<locals>.<listcomp>c                    s"   g | ]} j jd |fd qS r  r	  r  r   r   r   rB    r
  )r  r   r  r  r   r   )r   rX   rY   p_ptsdistr  r   r   r   r  }  s   

zToolLineHandles.closest)r,   r-   r.   r/   r   r@   rs  r  r  r  r  r  r&  r  r   r   r   r   r  ,  s     


r  c                   @   sh   e Zd ZdZddddddZedd	 Zed
d Zedd ZdddZ	dd Z
dd Zdd ZdS )ToolHandlesaO  
    Control handles for canvas tools.

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        Matplotlib Axes where tool handles are displayed.
    x, y : 1D arrays
        Coordinates of control handles.
    marker : str, default: 'o'
        Shape of marker used to display handle. See `~.pyplot.plot`.
    marker_props : dict, optional
        Additional marker properties. See `.Line2D`.
    useblit : bool, default: True
        Whether to use blitting for faster drawing (if supported by the
        backend). See the tutorial :ref:`blitting`
        for details.
    r$   NTr   r   r^   c                C   sR   || _ |dddddddt|tj}t||fd|i|| _| j | j d S )	N   r  ri  r_   F
_nolegend_)r   
markersizemarkerfacecolor	linestyler  r  rl   rm  )rB   r
   rP  r   
_alias_map_markersadd_line)r   rB   rX   rY   r   r   r^   rV  r   r   r   r     s   zToolHandles.__init__c                 C   r  r   )r  r?  r   r   r   r   rX     r+   zToolHandles.xc                 C   r  r   )r  rD  r   r   r   r   rY     r+   zToolHandles.yc                 C   s   | j fS r   )r  r   r   r   r   rs       zToolHandles.artistsc                 C   s*   |dur|}t ||g}| j| dS )z!Set x and y positions of handles.N)r   r  r  r  )r   ptsrY   rX   r   r   r   r    s   zToolHandles.set_datac                 C      | j | d S r   )r  r  r  r   r   r   r       zToolHandles.set_visiblec                 C   r  r   )r  r  r  r   r   r   r    r  zToolHandles.set_animatedc                 C   sN   t | j| jg}| jj|}|||g }t j|j }t 	|}||| fS )z1Return index and pixel distance to closest index.)
r   column_stackrX   rY   rB   rU   rW   hypotTr   )r   rX   rY   r  r  r  	min_indexr   r   r   r    s   
zToolHandles.closestr   )r,   r-   r.   r/   r   r@   rX   rY   rs  r  r  r  r  r   r   r   r   r    s    	



r  u  
    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent Axes for the widget.

    onselect : function, optional
        A callback function that is called after a release event and the
        selection is created, changed or removed.
        It must have the signature::

            def onselect(eclick: MouseEvent, erelease: MouseEvent)

        where *eclick* and *erelease* are the mouse click and release
        `.MouseEvent`\s that start and complete the selection.

    minspanx : float, default: 0
        Selections with an x-span less than or equal to *minspanx* are removed
        (when already existing) or cancelled.

    minspany : float, default: 0
        Selections with an y-span less than or equal to *minspanx* are removed
        (when already existing) or cancelled.

    useblit : bool, default: False
        Whether to use blitting for faster drawing (if supported by the
        backend). See the tutorial :ref:`blitting`
        for details.

    props : dict, optional
        Properties with which the __ARTIST_NAME__ is drawn. See
        `.Patch` for valid properties.
        Default:

        ``dict(facecolor='red', edgecolor='black', alpha=0.2, fill=True)``

    spancoords : {"data", "pixels"}, default: "data"
        Whether to interpret *minspanx* and *minspany* in data or in pixel
        coordinates.

    button : `.MouseButton`, list of `.MouseButton`, default: all buttons
        Button(s) that trigger rectangle selection.

    grab_range : float, default: 10
        Distance in pixels within which the interactive tool handles can be
        activated.

    handle_props : dict, optional
        Properties with which the interactive handles (marker artists) are
        drawn. See the marker arguments in `.Line2D` for valid
        properties.  Default values are defined in ``mpl.rcParams`` except for
        the default value of ``markeredgecolor`` which will be the same as the
        ``edgecolor`` property in *props*.

    interactive : bool, default: False
        Whether to draw a set of handles that allow interaction with the
        widget after it is drawn.

    state_modifier_keys : dict, optional
        Keyboard modifiers which affect the widget's behavior.  Values
        amend the defaults, which are:

        - "move": Move the existing shape, default: no modifier.
        - "clear": Clear the current shape, default: "escape".
        - "square": Make the shape square, default: "shift".
        - "center": change the shape around its center, default: "ctrl".
        - "rotate": Rotate the shape around its center between -45° and 45°,
          default: "r".

        "square" and "center" can be combined. The square shape can be defined
        in data or display coordinates as determined by the
        ``use_data_coordinates`` argument specified when creating the selector.

    drag_from_anywhere : bool, default: False
        If `True`, the widget can be moved by clicking anywhere within
        its bounds.

    ignore_event_outside : bool, default: False
        If `True`, the event triggered outside the span selector will be
        ignored.

    use_data_coordinates : bool, default: False
        If `True`, the "square" shape of the selector is defined in
        data coordinates instead of display coordinates.
    __ARTIST_NAME__	rectanglec                       s  e Zd ZdZd.dddddddddddddd f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edd Zedd Ze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ed,d- Z  ZS )/RectangleSelectora  
    Select a rectangular region of an Axes.

    For the cursor to remain responsive you must keep a reference to it.

    Press and release events triggered at the same coordinates outside the
    selection will clear the selector, except when
    ``ignore_event_outside=True``.

    %s

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> import matplotlib.widgets as mwidgets
    >>> fig, ax = plt.subplots()
    >>> ax.plot([1, 2, 3], [10, 50, 100])
    >>> def onselect(eclick, erelease):
    ...     print(eclick.xdata, eclick.ydata)
    ...     print(erelease.xdata, erelease.ydata)
    >>> props = dict(facecolor='blue', alpha=0.5)
    >>> rect = mwidgets.RectangleSelector(ax, onselect, interactive=True,
    ...                                   props=props)
    >>> fig.show()
    >>> rect.add_state('square')

    See also: :doc:`/gallery/widgets/rectangle_selector`
    Nr   Fdatar   )minspanxminspanyr^   rV  
spancoordsr  r  r  r  rn  r  r  ro  c                   s  t  j||||||d || _|| _|| _d| _d| _d| _|d u r*tddddd}i |d	| j	i}|
d
| j| _| jdi |}| j| || _|   || _|| _tjddg|d || _|	| _| jrd|pli ddit|
t| _g d| _| j\}}t| j||| j| j	d| _g d| _ | j!\}}t| j||d| j| j	d| _"| j#\}}t| j|g|gd| j| j	d| _$d | _%d | _&d S )N)r^   r  rn  ro  g        g      ?Tr  rj  r  )r   r   r  fillrm  r  r"  pixelsr%  markeredgecolorr   )SWSENENW)r   r^   )WSENr	  r  r   )'ri   r   r  r  r  	_rotation_aspect_ratio_correction_allow_creationrp  r^   ry  rc  _init_shaperB   r   r  _set_aspect_ratio_correctionr#  r$  r   r   r%  r  rx  r
   rP  r   r  _corner_ordercornersr  _corner_handlesr  edge_centersr  r`   _center_handler%  r  )r   rB   rd  r#  r$  r^   rV  r%  r  r  r  r  rn  r  r  ro  to_drawxcycxeyer{   r   r   r   S  sb   







zRectangleSelector.__init__c                 C   s   g | j j| jj| jjR S r   )r;  rs  r9  r  r   r   r   r   r    s   z"RectangleSelector._handles_artistsc                 K   s   t dddd|S )Nr  r   r   Fr`   )r  rotation_point)r   r  r   r   r   r5    s
   zRectangleSelector._init_shapec                 C   s   | j r| j r| | nd| _| jdu s| j s | jr |   | jdu r@| js@| jr@| |\}}d| _	||||f| _
d| _	n| d | j
| _| j| _|   dS )r  NFT)r  r  r~  r  r%  r4  r  r  rZ   rc  r  r  r  r2  _rotation_on_pressr6  )r   r<   rX   rY   r   r   r   r    s&   
zRectangleSelector._pressc           
      C   s|  | j s	| jd | jdu r| jr| jrdS | j\}}}}|| j_|| j_	| j
j||g}|\| j_| j_|| j_|| j_	| j
j||g}|\| j_| j_| jdkrit| jj| jj }t| jj	| jj	 }	n$| jdkrt| jj| jj }t| jj| jj }	n
tjddg| jd || jks|	| jkr| jr| | j| j |   n| | j| j d| _|   d| _d| _dS )r  FNr"  r'  r(  T)r  r  r  r%  ri  r  r  rj  rS   rT   rB   rU   rW   rX   rY   rk  r%  r   r   r   r#  r$  rd  r  r  r  )
r   r<   r  r  r  r  xy0xy1spanxspanyr   r   r   rr     sD   



zRectangleSelector._releasec                 C   s  | j }| j}d|v o| j| jv }| jdk}| jo| }| |\}}|r@|   }	|	||g\}}|	|j|j	f\|_|_	||j }
||j	 }d}| j
rU|
|}}n|j|j }|j|j }| j\}}}}|r|j|j	f}| j}||f}t|d |d  |d |d  t|d |d  |d |d   }t| j| | _n|r|| || g}||d d  ||d d  f}d|v rFd|v r| j| jv rt||td	}| jd
v s||kr||d  }|| j }n>||d  }|| j }n2|d d }|d d }| jddg| j v rt||d  }| jddg| j v r*t||d  }|d | |d | |d | |d | f\}}}}n d| jv rN|}d| jv rV|}| jddg| j v rc|}| jddg| j v rp|}d|v r| j| jv rt||td	}| jd
v s||krt|| }||t||  | j  }nt|| }||t||  | j  }n|r| j\}}}}||j }
||j	 }||
7 }||
7 }||7 }||7 }nd| _| jr| js| jsdS |j|j	g}||d  d }
||d  d }d|v r.t||td	}||kr"t|t|
 | j }nt|
t| | j }
d|v r<|
d9 }
|d9 }n|d  |
7  < |d  |7  < |d |
 |d |
 |d | |d | f\}}}}||||f| _dS )z
        Motion notify event handler.

        This can do one of four things:
        - Translate
        - Rotate
        - Re-size
        - Continue the creation of a new shape
        rb  r  Nr   r   r  r`   ra  r}  )r0  r.  r0  r.  r1  r/  )rj  rm  r%  r7  rZ   _get_rotation_transformrV   rW   rS   rT   rg  rX   rY   r  r`   r   arctan2rad2degrC  rotationr5  r   r3  r  r2  r  ri  r4  r  )r   r<   
eventpressr  rb  r`  resizerS   rT   inv_trdxdyrefmaxrefxrefyr  r  r  r  ru  brO   anglesize_on_pressr`   hwhhr  r   r   r   r    s   




"" 








zRectangleSelector._onmovec                 C   s   | j  jS r   )r  get_bboxboundsr   r   r   r   
_rect_bboxy  s   zRectangleSelector._rect_bboxc                 C   s,   | j  }|| j_| jrd| _d S || _d S )Nr   )rB   _get_aspect_ratior  r3  rg  r   aspect_ratior   r   r   r6  }  s
   


z.RectangleSelector._set_aspect_ratio_correctionc                 C   sL   | j  }t | jd  | jd  d|| jdd| j| j S Nr   r   )rB   r\  r   	translater`   scalerb  r2  r]  r   r   r   rH    s   
z)RectangleSelector._get_rotation_transformc           	      C   sf   | j \}}}}||| || |f}|||| || f}|  }|t||gjj}|d |d fS )ze
        Corners of rectangle in data coordinates from lower left,
        moving clockwise.
        r   r   r[  rH  rW   r   r  r  )	r   r  r  r  r  r=  r>  rW   r  r   r   r   r8    s   zRectangleSelector.cornersc                 C   s~   | j \}}}}|d }|d }||| || || f}|| ||| || f}|  }	|	t||gjj}
|
d |
d fS )zk
        Midpoint of rectangle edges in data coordinates from left,
        moving anti-clockwise.
               @r   r   rb  )r   r  r  r  r  r  rA  r?  r@  rW   r  r   r   r   r:    s   zRectangleSelector.edge_centersc                 C   s&   | j \}}}}||d  ||d  fS )z(Center of rectangle in data coordinates.rc  )r[  )r   r  r  r  r  r   r   r   r`     s   zRectangleSelector.centerc           	      C   sB   | j \}}}}t||| g\}}t||| g\}}||||fS )z}
        Return (xmin, xmax, ymin, ymax) in data coordinates as defined by the
        bounding box before rotation.
        )r[  r  )	r   r  r  r  r  rQ  rR  rS  rT  r   r   r   r    s   zRectangleSelector.extentsc                 C   s`   |  | | jr$| jj| j  | jj| j  | j\}}| j|g|g | 	| j
 |   d S r   )r  r  r9  r  r8  r  r:  r`   r;  r  rc  r  )r   r  rX   rY   r   r   r   r    s   

c                 C   s   t | jS )u   
        Rotation in degree in interval [-45°, 45°]. The rotation is limited in
        range to keep the implementation simple.
        )r   rJ  r2  r   r   r   r   rK    s   zRectangleSelector.rotationc                 C   s0   d|kr|dkrt || _| j| _d S d S d S )Ni-   )r   deg2radr2  r  )r   r  r   r   r   rK    s   c                 C   s   |\}}}}t ||g\}}t ||g\}}	t | j }
t | j }t|
d |}t|d |}t||
d }t|	|d }	| j| | j| | j	||  | j
|	|  | j| j d S r_  )r  rB   rM  rN  r5  r1  r  r  r  r  r
  	set_anglerK  )r   r  r  r  r  r  rQ  rR  rS  rT  r  r  r   r   r   r    s   zRectangleSelector._draw_shapec                 C   s   | j |j|j\}}| j|j|j\}}| j|j|j\}}d| jv r+d| _dS || jd k r7d| _dS || jkrS|| jkrS| j	rN| 
|rNd| _dS d| _dS ||k r_| j| | _dS | j| | _dS )r  r`  r  r  N)r9  r  rX   rY   r  r;  rm  r%  r  r  r  r7  r  )r   r<   c_idxc_distr  r  m_idxm_distr   r   r   r    s   



z$RectangleSelector._set_active_handlec                 C   r  r  r  r;   r   r   r   r    r*   zRectangleSelector._containsc                 C   sL   t | jdr| jj }|| j j\}}t	||gS t	| j
 S )a  
        Return an array of shape (2, 5) containing the
        x (``RectangleSelector.geometry[1, :]``) and
        y (``RectangleSelector.geometry[0, :]``) data coordinates of the four
        corners of the rectangle starting and ending in the top left corner.
        	get_verts)r   r  rB   rU   rV   rW   rk  r  r   r  get_data)r   xfmrY   rX   r   r   r   geometry
  s
   zRectangleSelector.geometryr   )r,   r-   r.   r/   r   r@   r  r5  r  rr   r  r[  r6  rH  r8  r:  r`   r  r  rK  r  r  r  rn  r   r   r   r{   r   r!  3  sN    B
0 








r!  ellipsec                   @   s,   e Zd ZdZdd Zdd Zedd ZdS )	EllipseSelectorao  
    Select an elliptical region of an Axes.

    For the cursor to remain responsive you must keep a reference to it.

    Press and release events triggered at the same coordinates outside the
    selection will clear the selector, except when
    ``ignore_event_outside=True``.

    %s

    Examples
    --------
    :doc:`/gallery/widgets/rectangle_selector`
    c                 K   s   t dddi|S )NrA  r  F)r   r  r   r   r   r5  ,  s   zEllipseSelector._init_shapec                 C   s   |\}}}}t ||g\}}t ||g\}}	||| d  ||| d  g}
|| d }|	| d }|
| j_d| | j_d| | j_| j| j_d S )Nrc  r  )r  r  r`   r  r  rK  rU  )r   r  r  r  r  r  rQ  rR  rS  rT  r`   ru  rT  r   r   r   r  /  s    zEllipseSelector._draw_shapec                 C   s8   | j j\}}| j j}| j j}||d  ||d  ||fS )Nrc  )r  r`   r  r  )r   rX   rY   r  r  r   r   r   r[  <  s   zEllipseSelector._rect_bboxN)r,   r-   r.   r/   r5  r  r@   r[  r   r   r   r   rp    s    rp  c                       sD   e Zd ZdZddddd fddZdd Zd	d
 Zdd Z  ZS )LassoSelectora  
    Selection curve of an arbitrary shape.

    For the selector to remain responsive you must keep a reference to it.

    The selected path can be used in conjunction with `~.Path.contains_point`
    to select data points from an image.

    In contrast to `Lasso`, `LassoSelector` is written with an interface
    similar to `RectangleSelector` and `SpanSelector`, and will continue to
    interact with the Axes until disconnected.

    Example usage::

        ax = plt.subplot()
        ax.plot(x, y)

        def onselect(verts):
            print(verts)
        lasso = LassoSelector(ax, onselect)

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent Axes for the widget.
    onselect : function, optional
        Whenever the lasso is released, the *onselect* function is called and
        passed the vertices of the selected path.
    useblit : bool, default: True
        Whether to use blitting for faster drawing (if supported by the
        backend). See the tutorial :ref:`blitting`
        for details.
    props : dict, optional
        Properties with which the line is drawn, see `.Line2D`
        for valid properties. Default values are defined in ``mpl.rcParams``.
    button : `.MouseButton` or list of `.MouseButton`, optional
        The mouse buttons used for rectangle selection.  Default is ``None``,
        which corresponds to all buttons.
    NT)r^   rV  r  c                   sb   t  j||||d d | _i |d ur|ni | jdd}tg g fi |}| j| || _d S )N)r^   r  F)rm  r  )ri   r   r/  r^   r   rB   r  r  )r   rB   rd  r^   rV  r  rX  r{   r   r   r   m  s   
zLassoSelector.__init__c                 C   s   |  |g| _| jd d S r  )r  r/  r  r  r;   r   r   r   r  z  s   zLassoSelector._pressc                 C   sN   | j d ur| j | | | | j  | jg g g | jd d | _ d S r  )r/  rJ   r  rd  r  r  r  r;   r   r   r   rr   ~  s   

zLassoSelector._releasec                 C   sB   | j d u rd S | j | | | jtt| j   |   d S r   )r/  rJ   r  r  r  listrt  r  r;   r   r   r   r    s
   
zLassoSelector._onmover   )	r,   r-   r.   r/   r   r  rr   r  r   r   r   r{   r   rq  D  s    (rq  c                	       s   e Zd ZdZd+dddddddd fddZ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d Zdd Zdd Zd d! Zd"d# Zd$d% Ze
d&d' Zejd(d' Zd)d* Z  ZS ),PolygonSelectora  
    Select a polygon region of an Axes.

    Place vertices with each mouse click, and make the selection by completing
    the polygon (clicking on the first vertex). Once drawn individual vertices
    can be moved by clicking and dragging with the left mouse button, or
    removed by clicking the right mouse button.

    In addition, the following modifier keys can be used:

    - Hold *ctrl* and click and drag a vertex to reposition it before the
      polygon has been completed.
    - Hold the *shift* key and click and drag anywhere in the Axes to move
      all vertices.
    - Press the *esc* key to start a new polygon.

    For the selector to remain responsive you must keep a reference to it.

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent Axes for the widget.

    onselect : function, optional
        When a polygon is completed or modified after completion,
        the *onselect* function is called and passed a list of the vertices as
        ``(xdata, ydata)`` tuples.

    useblit : bool, default: False
        Whether to use blitting for faster drawing (if supported by the
        backend). See the tutorial :ref:`blitting`
        for details.

    props : dict, optional
        Properties with which the line is drawn, see `.Line2D` for valid properties.
        Default::

            dict(color='k', linestyle='-', linewidth=2, alpha=0.5)

    handle_props : dict, optional
        Artist properties for the markers drawn at the vertices of the polygon.
        See the marker arguments in `.Line2D` for valid
        properties.  Default values are defined in ``mpl.rcParams`` except for
        the default value of ``markeredgecolor`` which will be the same as the
        ``color`` property in *props*.

    grab_range : float, default: 10
        A vertex is selected (to complete the polygon or to move a vertex) if
        the mouse click is within *grab_range* pixels of the vertex.

    draw_bounding_box : bool, optional
        If `True`, a bounding box will be drawn around the polygon selector
        once it is complete. This box can be used to move and resize the
        selector.

    box_handle_props : dict, optional
        Properties to set for the box handles. See the documentation for the
        *handle_props* argument to `RectangleSelector` for more info.

    box_props : dict, optional
        Properties to set for the box. See the documentation for the *props*
        argument to `RectangleSelector` for more info.

    Examples
    --------
    :doc:`/gallery/widgets/polygon_selector_simple`
    :doc:`/gallery/widgets/polygon_selector_demo`

    Notes
    -----
    If only one point remains after removing points, the selector reverts to an
    incomplete state and you can start drawing a new polygon from the existing
    point.
    NFr   )r^   rV  r  r  draw_bounding_boxbox_handle_props	box_propsc             	      s  t dddddddd}
t j||||
d dg| _|d u r%t dd	d
dd}i |d| ji}tg g fi | | _}| j| |d u rNt d|	ddd}|| _
t| jg g | j| j
d| _d| _|| _| d || _d | _|d u rui }| j
|| _|	| _d S )Nr]  r_  r^  r  )r  move_vertexmove_allr`  ra  r`   rb  )r^   rn  r  r   -r  r_   )rx   r  rh  r  rm  rx   )r)  r  )r^   r   r\  T)rp  ri   r   _xysr^   r   r  rB   r  rx  r  r  _polygon_handles_active_handle_idxr  r  	_draw_box_boxr  _box_handle_props
_box_props)r   rB   rd  r^   rV  r  r  rt  ru  rv  rn  rX  r{   r   r   r     sB   	



zPolygonSelector.__init__c                 C   r  r   )r  rY  r   r   r   r   	_get_bbox  r   zPolygonSelector._get_bboxc                 C   sb   t | j| j| j| j| jdd| _| jjd | j	d| j
 |   d| j_d| j_|   d S )NT)r^   r  r  rV  r  rb  rh   F)r!  rB   r^   r  r  r  r~  rf  ry  rM   _scale_polygon_update_boxr4  ri  _draw_polygonr   r   r   r   _add_box  s   zPolygonSelector._add_boxc                 C   s$   | j d ur| j d d | _ d S d S r  )r~  r  r   r   r   r   _remove_box  s   

zPolygonSelector._remove_boxc                 C   s<   | j d ur|  }|j|j|j|jg| j _| j j| _d S d S r   )r~  r  r  r  r  r  r  _old_box_extents)r   r   r   r   r   r     s
   
zPolygonSelector._update_boxc           	      C   s   | j sdS | j| jjkrdS | jj\}}}}|  }t |j	 |j
 d|j d|j ||||}dd |t| jD }g ||d | _|   | jj| _dS )z
        Scale the polygon selector points when the bounding box is moved or
        scaled.

        This is set as a callback on the bounding box RectangleSelector.
        Nr   c                 S   s   g | ]\}}||fqS r   r   )r   rX   rY   r   r   r   rB  ?  s    z2PolygonSelector._scale_polygon.<locals>.<listcomp>r   )ri  r  r~  r  r[  r  r   r   r`  r  r  ra  r  r  rW   r   r  r/  rz  r  )	r   r<   r  r  w1h1old_bboxt	new_vertsr   r   r   r  (  s    zPolygonSelector._scale_polygonc                 C   s   | j jS r   )r{  rs  r   r   r   r   r  D  r  z PolygonSelector._handles_artistsc                 C   s   t | jdkr+| jr+|dt | jd fv r+| jd | jd | j| jd  n| j| t | jdkrAd| _|   dS dS )zRemove vertex with index i.r  r   r   r\  FN)rq  rz  ri  ry  rJ   r  )r   r  r   r   r   _remove_vertexH  s   zPolygonSelector._remove_vertexc                 C   sT   | j sd| jv r"t| jdkr"| j|j|j\}}|| jk r"|| _	| j
 | _dS )r  rw  r   N)ri  rm  rq  rz  r{  r  rX   rY   r  r|  r  _xys_at_press)r   r<   h_idxh_distr   r   r   r  \  s   
zPolygonSelector._pressc                 C   s   | j dkr|jdkr| | j  |   d| _ n8t| jdkr9| jd | jd kr9d| _| jr8| jdu r8| 	  n| jsPd| j
vrPd| j
vrP| jd| | | jr[| | j dS dS )r  r   r+  r\  TNrx  rw  )r|  r  r  r  rq  rz  ri  r}  r~  r  rm  insertrZ   rd  r/  r;   r   r   r   rr   h  s"   

"

zPolygonSelector._releasec                 C   sT   |  |r| jj| s| jrtjtjf| jd< |   dS | |}| 	| dS )r  r\  FT)
r=   rG   r@  r!   rz  r   nanr  r  r  r;   r   r   r   r8    s   


zPolygonSelector.onmovec                 C   sF  | j dkr | j }| || j|< |dkr| jr| || jd< n}d| jv rX| jrX| |\}}|| jj }|| jj }tt	| jD ]}| j
| \}}	|| |	| f| j|< qBnE| jsed| jv sed| jv rgdS | j | jd \}
}t|
|j ||j }t	| jdkr|| jk r| jd | jd< n| || jd< |   dS )r  r   r\  rx  rw  Nr+  )r|  rZ   rz  ri  rm  rj  rS   rT   r  rq  r  r  get_transformrW   r   r  rX   rY   r  r  )r   r<   r;  rS   rT   rO  rP  r   
x_at_press
y_at_pressr  r  v0_distr   r   r   r    s0   
zPolygonSelector._onmovec                 C   s8   | j sd| jv sd| jv r| j  |   dS dS dS )zKey press event handler.rw  rx  N)ri  rm  rz  ry  r  r;   r   r   r   r    s   


zPolygonSelector._on_key_pressc                 C   s   | j s$|j| jdks|j| jdkr$| j| | |   dS |j| jdkrG| |}| |g| _d| _ | 	  | 
d dS dS )r  rw  rx  r  FTN)ri  r  rf  rx  rz  rJ   rZ   r  r  r  r  r;   r   r   r   r    s   
zPolygonSelector._on_key_releasec                 C   s   | j rt| j  ng g f\}}| j|| |   | js-t| j dkr>| j d | j d kr>| j|dd |dd  dS | j|| dS )z>Redraw the polygon based on new vertex positions, no update().r+  r\  r   N)rz  rt  r  r  r  ri  rq  r{  )r   xsr  r   r   r   _draw_polygon_without_update  s   "z,PolygonSelector._draw_polygon_without_updatec                 C   r  )z5Redraw the polygon based on the new vertex positions.N)r  r  r   r   r   r   r    r  zPolygonSelector._draw_polygonc                 C   s   | j dd S )z4The polygon vertices, as a list of ``(x, y)`` pairs.Nr\  )rz  r   r   r   r   r/    s   zPolygonSelector.vertsc                 C   sF   g ||d | _ d| _| d | jr| jdu r|   |   dS )z
        Set the polygon vertices.

        This will remove any preexisting vertices, creating a complete polygon
        with the new vertices.
        r   TN)rz  ri  r  r}  r~  r  r  )r   xysr   r   r   r/    s   
c                 C   s   d| _ dg| _|   d S )NFr  )ri  rz  r  r   r   r   r   r    s   z%PolygonSelector._clear_without_updater   )r,   r-   r.   r/   r   r  r  r  r  r  r@   r  r  r  rr   r8  r  r  r  r  r  r/  r  r  r   r   r   r{   r   rs    s8    K-
'


rs  c                       s8   e Zd ZdZddd fdd
Zdd Zd	d
 Z  ZS )Lassoa  
    Selection curve of an arbitrary shape.

    The selected path can be used in conjunction with
    `~matplotlib.path.Path.contains_point` to select data points from an image.

    Unlike `LassoSelector`, this must be initialized with a starting
    point *xy*, and the `Lasso` events are destroyed upon release.

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent Axes for the widget.
    xy : (float, float)
        Coordinates of the start of the lasso.
    callback : callable
        Whenever the lasso is released, the *callback* function is called and
        passed the vertices of the selected path.
    useblit : bool, default: True
        Whether to use blitting for faster drawing (if supported by the
        backend). See the tutorial :ref:`blitting`
        for details.
    props: dict, optional
        Lasso line properties. See `.Line2D` for valid properties.
        Default *props* are::

            {'linestyle' : '-', 'color' : 'black', 'lw' : 2}

        .. versionadded:: 3.9
    TN)r^   rV  c          	         s   t  | |o| jj| _| jr| j| jj| _dddd}|d ur(|	| |\}}||fg| _
t|g|gfi || _| j| j || _| d| j | d| j d S )Nry  rj  r  )r  rx   r   rg   rh   )ri   r   rG   rm   r^   r  rB   r   r=  r  r/  r   rX  r  rK   rM   	onreleaser8  )	r   rB   r,  rK   r^   rV  stylerX   rY   r{   r   r   r   "  s   
zLasso.__init__c                 C   s`   |  |rd S | jd ur'| j| | t| jdkr"| | j | j  d | _|   d S )Nr  )	r=   r/  rJ   rZ   rq  rK   rX  r&  rP   r;   r   r   r   r  6  s   


zLasso.onreleasec                 C   s   |  |s| jd u s|jdks| j|d sd S | j| | | jt	t
| j  | jrH| j| j | j| j | j| jj d S | j  d S )Nr   r   )r=   r/  r  rB   r~   rJ   rZ   rX  r  rr  rt  r^   rG   r  r=  r   r   r   r  r;   r   r   r   r8  A  s   


zLasso.onmove)r,   r-   r.   r/   r   r  r8  r   r   r   r{   r   r    s
    r  ):r/   
contextlibr   r  rS  numbersr   r   r   numpyr   
matplotlibr  r  r   r   r	   r
   r   r   r   rQ  r   r   linesr   patchesr   r   r   r   r   r   r0   rA   r[   r   r   r  rW  rX  r  r	  r  r5  rB  rY  r  r  r  '_RECTANGLESELECTOR_PARAMETERS_DOCSTRINGSubstitutionr  r!  rp  rq  rs  r  r   r   r   r   <module>   s    ,&6gN    z  /    	HW   d   !nBX   h(K  v