B
    ]”t\to ã               @   sŒ  d Z ddlZddlmZ ddlZddlmZ ddlm	Z	 ddl
mZmZmZ ddlm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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*eƒZ!G d+d,„ d,eƒZ"G d-d.„ d.eƒZ#d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 a :class:`matplotlib.axes.Axes`
instance and pass that as the first arg.  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.
é    N)ÚIntegralé   )ÚrcParams)ÚLine2D)ÚCircleÚ	RectangleÚEllipse)Úblended_transform_factoryc               @   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   ú1lib/python3.7/site-packages/matplotlib/widgets.pyÚ__init__!   s    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__$   s    
zLockDraw.__call__c             C   s   |   |¡stdƒ‚d| _dS )zRelease the lock from *o*.zyou do not own this lockN)r   r   r   )r   r   r   r   r   Úrelease*   s    
zLockDraw.releasec             C   s   |   ¡  p|  |¡S )z+Return whether drawing is available to *o*.)ÚlockedÚisowner)r   r   r   r   r   r   0   s    zLockDraw.availablec             C   s
   | j |kS )z"Return whether *o* owns this lock.)r   )r   r   r   r   r   r   4   s    zLockDraw.isownerc             C   s
   | j dk	S )z6Return whether the lock is currently held by an owner.N)r   )r   r   r   r   r   8   s    zLockDraw.lockedN)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r   r   r   r   r   r
      s   r
   c               @   sF   e Zd ZdZdZdZdZdd„ Zdd„ Ze	edd„ d	d
Z
dd„ ZdS )ÚWidgetz5
    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_activeE   s    zWidget.set_activec             C   s   | j S )z*Get whether the widget is active.
        )r   )r   r   r   r   Ú
get_activeJ   s    zWidget.get_activec             C   s
   |   |¡S )N)r   )r   r   r   r   r   Ú<lambda>P   s    zWidget.<lambda>zIs the widget active?)Údocc             C   s   | j  S )z›Return True if event should be ignored.

        This method (or a version of it) should be called at the beginning
        of any event callback.
        )r   )r   Úeventr   r   r   ÚignoreS   s    zWidget.ignoreN)r   r   r   r   ÚdrawonÚeventsonr   r   r   Úpropertyr   r#   r   r   r   r   r   =   s   
r   c               @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	Ú
AxesWidgeta  Widget that is connected to a single
    :class:`~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* : :class:`~matplotlib.axes.Axes`
        The parent axes for the widget
    *canvas* : :class:`~matplotlib.backend_bases.FigureCanvasBase` subclass
        The parent figure canvas for the widget.
    *active* : bool
        If False, the widget does not respond to events.
    c             C   s   || _ |jj| _g | _d S )N)ÚaxÚfigureÚcanvasÚcids)r   r(   r   r   r   r   r   s    
zAxesWidget.__init__c             C   s   | j  ||¡}| j |¡ dS )z°Connect callback 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)r*   Úmpl_connectr+   Úappend)r   r"   ÚcallbackÚcidr   r   r   Úconnect_eventw   s    zAxesWidget.connect_eventc             C   s    x| j D ]}| j |¡ qW dS )z-Disconnect all events created by this widget.N)r+   r*   Úmpl_disconnect)r   Úcr   r   r   Údisconnect_events€   s    zAxesWidget.disconnect_eventsN)r   r   r   r   r   r0   r3   r   r   r   r   r'   \   s   	r'   c               @   sB   e Zd ZdZddd„Zdd„ Zd	d
„ Zdd„ Zdd„ Zdd„ Z	dS )ÚButtonaÇ  
    A GUI neutral button.

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

    Attributes
    ----------
    ax :
        The :class:`matplotlib.axes.Axes` the button renders into.
    label :
        A :class:`matplotlib.text.Text` instance.
    color :
        The color of the button when not hovering.
    hovercolor :
        The color of the button when hovering.
    Nú0.85ú0.95c             C   s¬   t  | |¡ |dk	r| |¡ |jdd|dd|jd| _d| _i | _|  d| j	¡ |  d| j
¡ |  d| j¡ | d	¡ | |¡ | g ¡ | g ¡ || _|| _|| _dS )
a}  
        Parameters
        ----------
        ax : matplotlib.axes.Axes
            The :class:`matplotlib.axes.Axes` instance the button
            will be placed into.

        label : str
            The button text. Accepts string.

        image : array, mpl image, Pillow Image
            The image to place in the button, if not *None*.
            Can be any legal arg to imshow (numpy array,
            matplotlib Image instance, or Pillow Image).

        color : color
            The color of the button when not activated

        hovercolor : color
            The color of the button when the mouse is over it
        Ng      à?Úcenter)ÚverticalalignmentÚhorizontalalignmentÚ	transformr   Úbutton_press_eventÚbutton_release_eventÚmotion_notify_eventF)r'   r   ZimshowÚtextÚ	transAxesÚlabelÚcntÚ	observersr0   Ú_clickÚ_releaseÚ_motionÚset_navigateÚset_facecolorÚ
set_xticksÚ
set_yticksÚcolorÚ
hovercolorÚ
_lastcolor)r   r(   r@   ZimagerJ   rK   r   r   r   r   ™   s&    





zButton.__init__c             C   sH   |   |¡rd S |j| jkrd S | js(d S |jj| jkrD|j | j¡ d S )N)r#   Úinaxesr(   r%   r*   Úmouse_grabberÚ
grab_mouse)r   r"   r   r   r   rC   È   s    
zButton._clickc             C   sl   |   |¡rd S |jj| jkr d S |j | j¡ | js8d S |j| jkrHd S x| j ¡ D ]\}}||ƒ qTW d S )N)	r#   r*   rN   r(   Úrelease_mouser%   rM   rB   Úitems)r   r"   r/   Úfuncr   r   r   rD   Ò   s    
zButton._releasec             C   s\   |   |¡rd S |j| jkr"| j}n| j}|| jkrX| j |¡ || _| jrX| jjj	 
¡  d S )N)r#   rM   r(   rK   rJ   rL   rG   r$   r)   r*   Údraw)r   r"   r2   r   r   r   rE   ß   s    

zButton._motionc             C   s"   | j }|| j|< |  j d7  _ |S )z³
        When the button is clicked, call this *func* with event.

        A connection id is returned. It can be used to disconnect
        the button from its callback.
        r   )rA   rB   )r   rR   r/   r   r   r   Ú
on_clickedì   s    
zButton.on_clickedc             C   s&   y| j |= W n tk
r    Y nX dS )z,remove the observer with connection id *cid*N)rB   ÚKeyError)r   r/   r   r   r   Ú
disconnectø   s    zButton.disconnect)Nr5   r6   )
r   r   r   r   r   rC   rD   rE   rT   rV   r   r   r   r   r4   †   s    
.
r4   c               @   sJ   e Zd ZdZddd„Zdd	„ Zd
d„ Zdd„ Zdd„ Zdd„ Z	dd„ Z
dS )Ú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.
    ç      à?ú%1.2fTNc             K   s†  t  | |¡ |	dk	r0t|	dƒs0td t|	ƒ¡ƒ‚|
dk	rTt|
dƒsTtd t|
ƒ¡ƒ‚|| _|| _|	| _|
| _	d| _
|| _|| _|| _|  |¡}|dkrš|}|| _|| _|j||ddf|Ž| _|j|ddddd	| _|| _| g ¡ | ||f¡ | g ¡ | d¡ |  d
| j¡ |  d| j¡ |r4|  d| j¡ |jdd||jddd| _|jdd|| |jddd| _d| _ i | _!|  "|¡ dS )al  
        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, optional, default: 0.5
            The slider initial position.

        valfmt : str, optional, default: "%1.2f"
            Used to format the slider value, fprint format string.

        closedmin : bool, optional, default: True
            Indicate whether the slider interval is closed on the bottom.

        closedmax : bool, optional, default: True
            Indicate whether the slider interval is closed on the top.

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

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

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

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

        Notes
        -----
        Additional kwargs are passed on to ``self.poly`` which is the
        :class:`~matplotlib.patches.Rectangle` that draws the slider
        knob.  See the :class:`~matplotlib.patches.Rectangle` documentation for
        valid property names (e.g., `facecolor`, `edgecolor`, `alpha`).
        NÚvalz$Argument slidermin ({}) has no 'val'z$Argument slidermax ({}) has no 'val'Fr   r   Úr)rJ   Úlwr;   r<   r=   g{®Gáz”¿g      à?r7   Úright)r:   r8   r9   gR¸…ëQð?Úleft)#r'   r   Úhasattrr   ÚformatÚtypeÚ	closedminÚ	closedmaxÚ	sliderminÚ	slidermaxÚdrag_activeÚvalminÚvalmaxÚvalstepÚ_value_in_boundsrZ   ÚvalinitZaxvspanÚpolyÚaxvlineZvlineÚvalfmtrI   Úset_xlimrH   rF   r0   Ú_updater>   r?   r@   ÚvaltextrA   rB   Úset_val)r   r(   r@   rg   rh   rk   rn   rb   rc   rd   re   Zdraggingri   Úkwargsr   r   r   r     sR    3





zSlider.__init__c             C   s¶   | j r,t || j | j  ¡| j  }|| j7 }|| jkrH| js@dS | j}n|| jkrb| js\dS | j}| jdk	rŠ|| jjkrŠ| js‚dS | jj}| j	dk	r²|| j	jkr²| jsªdS | j	j}|S )z* Makes sure self.val is with given bounds.N)
ri   ÚnpÚroundrg   rb   rh   rc   rd   rZ   re   )r   rZ   r   r   r   rj   p  s(    


zSlider._value_in_boundsc             C   s°   |   |¡rdS |jdkrdS |jdkrF|j| jkrFd| _|j | j¡ | jsPdS |jdksp|jdkrˆ|j| jkrˆd| _|j | j¡ dS |  	|j
¡}|d| jgkr¬|  |¡ dS )zupdate the slider positionNr   r;   Tr<   F)r#   ÚbuttonÚnamerM   r(   rf   r*   rO   rP   rj   ÚxdatarZ   rr   )r   r"   rZ   r   r   r   rp   Š  s$    



zSlider._updatec             C   s‚   | j j}|df|d< |df|d< || j _| j | j| ¡ | jrN| jjj 	¡  || _
| js^dS x| j ¡ D ]\}}||ƒ qjW dS )zf
        Set slider value to *val*

        Parameters
        ----------
        val : float
        r   é   r   é   N)rl   Úxyrq   Zset_textrn   r$   r(   r)   r*   Ú	draw_idlerZ   r%   rB   rQ   )r   rZ   r{   r/   rR   r   r   r   rr   £  s    zSlider.set_valc             C   s"   | j }|| j|< |  j d7  _ |S )a  
        When the slider value is changed call *func* with the new
        slider value

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

        Returns
        -------
        cid : int
            Connection id (which can be used to disconnect *func*)
        r   )rA   rB   )r   rR   r/   r   r   r   Ú
on_changed¸  s    
zSlider.on_changedc             C   s&   y| j |= W n tk
r    Y nX dS )z¯
        Remove the observer with connection id *cid*

        Parameters
        ----------
        cid : int
            Connection id of the observer to be removed
        N)rB   rU   )r   r/   r   r   r   rV   Í  s    	zSlider.disconnectc             C   s   | j | jkr|  | j¡ dS )z%Reset the slider to the initial valueN)rZ   rk   rr   )r   r   r   r   ÚresetÛ  s    zSlider.reset)rX   rY   TTNNTN)r   r   r   r   r   rj   rp   rr   r}   rV   r~   r   r   r   r   rW      s     
arW   c               @   sB   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dS )ÚCheckButtonsaµ  
    A GUI neutral set of check buttons.

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

    The following attributes are exposed

     *ax*
        The :class:`matplotlib.axes.Axes` instance the buttons are
        located in

     *labels*
        List of :class:`matplotlib.text.Text` instances

     *lines*
        List of (line1, line2) tuples for the x's in the check boxes.
        These lines exist for each box, but have ``set_visible(False)``
        when its box is not checked.

     *rectangles*
        List of :class:`matplotlib.patches.Rectangle` instances

    Connect to the CheckButtons with the :meth:`on_clicked` method
    Nc          	   C   sÐ  t  | |¡ | g ¡ | g ¡ | d¡ |dkr@dgt|ƒ }t|ƒdkrtdt|ƒd  }t d| |t|ƒ¡}n
d}dg}| ¡ }g | _	g | _
g | _dd|jd	d
œ}xt|||ƒD ]ö\}}	}
|jd||	|jddd}|d |d  }}d||d   }}t||f||d||jd}t||| g|| |gf|Ž}t||| g||| gf|Ž}| |
¡ | |
¡ | j	 |¡ | j |¡ | j
 ||f¡ | |¡ | |¡ | |¡ q¸W |  d| j¡ d| _i | _dS )aÕ  
        Add check buttons to :class:`matplotlib.axes.Axes` instance *ax*

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

        labels : List[str]
            The labels of the check buttons.

        actives : List[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.
        FNr   g      ð?g      Ð?g      à?Úkg      ô?Zbutt)rJ   Ú	linewidthr:   Zsolid_capstyler^   r7   )r:   r9   r8   ry   gš™™™™™©?Úblack)r{   ÚwidthÚheightÚ	edgecolorÚ	facecolorr:   r;   r   )r'   r   rH   rI   rF   Úlenrt   ÚlinspaceÚget_facecolorÚlabelsÚlinesÚ
rectanglesr?   Úzipr>   r   r   Úset_visibler-   Ú	add_patchÚadd_liner0   Ú_clickedrA   rB   )r   r(   rŠ   ZactivesÚdyÚysÚaxcolorZ
lineparamsÚyr@   r   ÚtÚwÚhÚxÚpÚl1Úl2r   r   r   r   û  sL    






zCheckButtons.__init__c             C   s€   |   |¡s |jdks |j| jkr$d S xVtt| j| jƒƒD ]@\}\}}| ¡  	|j
|j¡sl| ¡  	|j
|j¡r8|  |¡ P q8W d S )Nr   )r#   rv   rM   r(   Ú	enumerater   rŒ   rŠ   Úget_window_extentÚcontainsr™   r•   r   )r   r"   Úirš   r–   r   r   r   r‘   ?  s      
zCheckButtons._clickedc             C   s¤   d|  krt | jƒkr*n ntd| ƒ‚| j| \}}| | ¡  ¡ | | ¡  ¡ | jrl| jjj	 
¡  | jsvdS x(| j ¡ D ]\}}|| j|  ¡ ƒ q‚W dS )a%  
        Directly (de)activate a check button by index.

        *index* is an index into the original label list
            that this object was constructed with.
            Raises ValueError if *index* is invalid.

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

        r   zInvalid CheckButton index: %dN)r‡   rŠ   r   r‹   rŽ   Úget_visibler$   r(   r)   r*   rS   r%   rB   rQ   Úget_text)r   Úindexr›   rœ   r/   rR   r   r   r   r   H  s    zCheckButtons.set_activec             C   s   dd„ | j D ƒS )zX
        returns a tuple of the status (True/False) of all of the check buttons
        c             S   s   g | ]\}}|  ¡ ‘qS r   )r¡   )Ú.0r›   rœ   r   r   r   ú
<listcomp>f  s    z+CheckButtons.get_status.<locals>.<listcomp>)r‹   )r   r   r   r   Ú
get_statusb  s    zCheckButtons.get_statusc             C   s"   | j }|| j|< |  j d7  _ |S )z
        When the button is clicked, call *func* with button label

        A connection id is returned which can be used to disconnect
        r   )rA   rB   )r   rR   r/   r   r   r   rT   h  s    
zCheckButtons.on_clickedc             C   s&   y| j |= W n tk
r    Y nX dS )z,remove the observer with connection id *cid*N)rB   rU   )r   r/   r   r   r   rV   s  s    zCheckButtons.disconnect)N)
r   r   r   r   r   r‘   r   r¦   rT   rV   r   r   r   r   r   á  s   
D	r   c               @   sš   e Zd ZdZd)dd„Zdd	„ Zd
d„ Zdd„ Zdd„ Zdd„ Z	dd„ Z
d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(S )*ÚTextBoxao  
    A GUI neutral text input box.

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

    The following attributes are accessible:

      *ax*
        The :class:`matplotlib.axes.Axes` the button renders into.

      *label*
        A :class:`matplotlib.text.Text` instance.

      *color*
        The color of the text box when not hovering.

      *hovercolor*
        The color of the text box when hovering.

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

    Call :meth:`on_submit` to be updated whenever the user hits enter or
    leaves the text entry field.
    Ú ú.95Ú1ç{®Gáz„?c             C   s.  t  | |¡ d| _dd„ tD ƒ| _|| _|j| d|dd|jd| _|  | j¡| _	d| _
i | _i | _| j dd	¡ | j dd	¡ d| _| j ddd¡| _| j d
¡ |  d| j¡ |  d| j¡ |  d| j¡ |  d| j¡ |  d| j¡ | d
¡ | |¡ | g ¡ | g ¡ || _|| _|| _ d
| _!dS )a6  
        Parameters
        ----------
        ax : matplotlib.axes.Axes
            The :class:`matplotlib.axes.Axes` instance the button
            will be placed into.

        label : str
            Label for this text box. Accepts string.

        initial : str
            Initial value in the text box

        color : color
            The color of the box

        hovercolor : 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
        gš™™™™™©?c             S   s   g | ]}d |kr|‘qS )Zkeymapr   )r¤   Úkeyr   r   r   r¥   ±  s    z$TextBox.__init__.<locals>.<listcomp>g      à?r7   r]   )r8   r9   r:   r   r   Fr;   r<   r=   Úkey_press_eventZresize_eventN)"r'   r   ÚDIST_FROM_LEFTr   Úparams_to_disabler>   r?   r@   Ú_make_text_dispÚ	text_disprA   Úchange_observersÚsubmit_observersr(   ro   Zset_ylimÚcursor_indexÚvlinesÚcursorrŽ   r0   rC   rD   rE   Ú	_keypressÚ_resizerF   rG   rH   rI   rJ   rK   rL   Úcapturekeystrokes)r   r(   r@   ÚinitialrJ   rK   Z	label_padr   r   r   r   •  s<    



zTextBox.__init__c             C   s   | j j| jd|dd| j jdS )Ng      à?r7   r^   )r8   r9   r:   )r(   r>   r®   r?   )r   Ústringr   r   r   r°   Ú  s    zTextBox._make_text_dispc             C   sÄ   | j d | j… }d}|dks,|dks,|dkr8|dk}d}|  |¡}| jjj ¡  | ¡ }| jj 	¡ }| 
|¡}| d¡ |rˆ|d |d< | j d¡ | j |d |d |d	 ¡| _| jjj ¡  d S )
NFr¨   ú z  ú,)r   r   )r   r   )r   r   )r   r   )r>   r´   r°   r(   r)   r*   rS   rž   Ú	transDataÚinvertedr:   rŽ   r¶   rµ   )r   Z	widthtextZno_textZwt_dispÚbbÚinvr   r   r   Ú_rendercursorà  s     


zTextBox._rendercursorc             C   s&   x | j  ¡ D ]\}}|| jƒ qW d S )N)r³   rQ   r>   )r   r/   rR   r   r   r   Ú_notify_submit_observersû  s    z TextBox._notify_submit_observersc             C   s2   |   |¡rd S |jj| jkr d S |j | j¡ d S )N)r#   r*   rN   r(   rP   )r   r"   r   r   r   rD   ÿ  s
    
zTextBox._releasec             C   sš  |   |¡rd S | jr–|j}t|ƒdkr^| jd | j… | | j| jd …  | _|  jd7  _nþ|dkr†| jt| jƒkr„|  jd7  _nÖ|dkr¨| jdkr¦|  jd8  _n´|dkr¸d| _n¤|dkrÎt| jƒ| _nŽ|dkr| jdkr\| jd | jd … | j| jd …  | _|  jd8  _nB|dkr\| jt| jƒkr\| jd | j… | j| jd d …  | _| j ¡  |  | j¡| _|  	¡  |  
¡  |d	kr–|  ¡  d S )
Nr   r]   r^   r   ÚhomeÚendZ	backspaceÚdeleteZenter)r#   r¹   r¬   r‡   r>   r´   r±   Úremover°   rÂ   Ú_notify_change_observersrÃ   )r   r"   r¬   r   r   r   r·     sB    





zTextBox._keypressc             C   sP   t |ƒ}| j|krd S || _| j ¡  |  | j¡| _|  ¡  |  ¡  |  ¡  d S )N)Ústrr>   r±   rÇ   r°   rÂ   rÈ   rÃ   )r   rZ   Znewvalr   r   r   rr   +  s    

zTextBox.set_valc             C   s&   x | j  ¡ D ]\}}|| jƒ qW d S )N)r²   rQ   r>   )r   r/   rR   r   r   r   rÈ   6  s    z TextBox._notify_change_observersc             C   s6   d| _ i | _x$| jD ]}t| | j|< g t|< qW d S )NT)r¹   Úreset_paramsr¯   r   )r   r™   r¬   r   r   r   Úbegin_typing:  s
    zTextBox.begin_typingc             C   s\   d}| j r,x| jD ]}| j| t|< qW d}d| _ | j d¡ | jjj 	¡  |rX|  
¡  d S )NFT)r¹   r¯   rÊ   r   r¶   rŽ   r(   r)   r*   rS   rÃ   )r   Znotifysubmitr¬   r   r   r   Ústop_typingC  s    zTextBox.stop_typingc             C   sœ   t | jƒdkrd| _nz| j ¡ }| jj}| jj ¡ }| | |¡¡}|d }|d }|| ||  }|dk rpd}|dkr|d}t	t | jƒ| ƒ| _|  
¡  d S )Nr   )r   r   )r   r   r   )r‡   r>   r´   r±   rž   r(   r¾   r¿   r:   ÚintrÂ   )r   r™   rÀ   ÚtransrÁ   Z
text_startZtext_endZratior   r   r   Úposition_cursorT  s    
zTextBox.position_cursorc             C   sn   |   |¡rd S |j| jkr&|  ¡  d S | js0d S |jj| jkrL|j | j¡ | js^|  	|j
¡ |  |j
¡ d S )N)r#   rM   r(   rÌ   r%   r*   rN   rO   r¹   rË   r™   rÏ   )r   r"   r   r   r   rC   n  s    
zTextBox._clickc             C   s   |   ¡  d S )N)rÌ   )r   r"   r   r   r   r¸   |  s    zTextBox._resizec             C   s\   |   |¡rd S |j| jkr"| j}n| j}|| jkrX| j |¡ || _| jrX| jjj	 
¡  d S )N)r#   rM   r(   rK   rJ   rL   rG   r$   r)   r*   rS   )r   r"   r2   r   r   r   rE     s    

zTextBox._motionc             C   s"   | j }|| j|< |  j d7  _ |S )z‹
        When the text changes, call this *func* with event.

        A connection id is returned which can be used to disconnect.
        r   )rA   r²   )r   rR   r/   r   r   r   Úon_text_changeŒ  s    
zTextBox.on_text_changec             C   s"   | j }|| j|< |  j d7  _ |S )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   )rA   r³   )r   rR   r/   r   r   r   Ú	on_submit—  s    
zTextBox.on_submitc          	   C   s:   x4| j | jgD ]$}y
||= W q tk
r0   Y qX qW dS )z-Remove the observer with connection id *cid*.N)r²   r³   rU   )r   r/   Zregr   r   r   rV   £  s
    
zTextBox.disconnectN)r¨   r©   rª   r«   )r   r   r   r   r   r°   rÂ   rÃ   rD   r·   rr   rÈ   rË   rÌ   rÏ   rC   r¸   rE   rÐ   rÑ   rV   r   r   r   r   r§   {  s&    
D%	r§   c               @   s:   e Zd ZdZddd„Zdd„ Zdd	„ Zd
d„ Zdd„ ZdS )ÚRadioButtonsaa  
    A GUI neutral radio button.

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

    The following attributes are exposed:

     *ax*
        The :class:`matplotlib.axes.Axes` instance the buttons are in

     *activecolor*
        The color of the button when clicked

     *labels*
        A list of :class:`matplotlib.text.Text` instances

     *circles*
        A list of :class:`matplotlib.patches.Circle` instances

     *value_selected*
        A string listing the current value selected

    Connect to the RadioButtons with the :meth:`on_clicked` method
    r   Úbluec          	   C   s4  t  | |¡ || _d| _| g ¡ | g ¡ | d¡ dt|ƒd  }t 	d| |t|ƒ¡}d}| 
¡ }|d d }	|	dkr€d}	g | _g | _xˆt||ƒD ]z\}
}|jd	|
||jd
dd}||krÌ|| _|}n|}td|
f|	d||jd}| j |¡ | j |¡ | |¡ |d7 }q˜W |  d| j¡ d| _i | _dS )a3  
        Add radio buttons to :class:`matplotlib.axes.Axes` instance *ax*

        *labels*
            A len(buttons) list of labels as strings

        *active*
            The index into labels for the button that is active

        *activecolor*
            The color of the button when clicked
        NFg      ð?r   r   ry   g{®Gáz„?gš™™™™™©?g      Ð?r^   r7   )r:   r9   r8   g333333Ã?r‚   )r{   Úradiusr…   r†   r:   r;   )r'   r   ÚactivecolorÚvalue_selectedrH   rI   rF   r‡   rt   rˆ   r‰   rŠ   Úcirclesr   r>   r?   r   r-   r   r0   r‘   rA   rB   )r   r(   rŠ   r   rÕ   r’   r“   rA   r”   Zcircle_radiusr•   r@   r–   r†   rš   r   r   r   r   Æ  s@    



zRadioButtons.__init__c             C   s´   |   |¡s |jdks |j| jkr$d S | jj ¡  |j|jf¡}t	 
|d |d g¡}xZtt| j| jƒƒD ]D\}\}}| ¡  |j|j¡s t	j ||j ¡|jk rh|  |¡ P qhW d S )Nr   r   )r#   rv   rM   r(   r?   r¿   Útransform_pointr™   r•   rt   Úarrayr   r   r×   rŠ   rž   rŸ   ZlinalgZnormr7   rÔ   r   )r   r"   r{   Zpclickedr    rš   r–   r   r   r   r‘      s      
zRadioButtons._clickedc             C   sÂ   d|  krt | jƒkr*n ntd| ƒ‚| j|  ¡ | _x:t| jƒD ],\}}||kr^| j}n
| j 	¡ }| 
|¡ qFW | jrŠ| jjj ¡  | js”dS x(| j ¡ D ]\}}|| j|  ¡ ƒ q W dS )a"  
        Trigger which radio button to make active.

        *index* is an index into the original label list
            that this object was constructed with.
            Raise ValueError if the index is invalid.

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

        r   zInvalid RadioButton index: %dN)r‡   rŠ   r   r¢   rÖ   r   r×   rÕ   r(   r‰   rG   r$   r)   r*   rS   r%   rB   rQ   )r   r£   r    rš   rJ   r/   rR   r   r   r   r     s    
zRadioButtons.set_activec             C   s"   | j }|| j|< |  j d7  _ |S )z
        When the button is clicked, call *func* with button label

        A connection id is returned which can be used to disconnect
        r   )rA   rB   )r   rR   r/   r   r   r   rT   *  s    
zRadioButtons.on_clickedc             C   s&   y| j |= W n tk
r    Y nX dS )z,remove the observer with connection id *cid*N)rB   rU   )r   r/   r   r   r   rV   5  s    zRadioButtons.disconnectN)r   rÓ   )	r   r   r   r   r   r‘   r   rT   rV   r   r   r   r   rÒ   ¬  s   
:rÒ   c               @   sH   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dS )ÚSubplotToolzU
    A tool to adjust the subplot params of a :class:`matplotlib.figure.Figure`.
    c                sT  |ˆ _ ˆjddd G dd„ dƒ}ˆ d¡ˆ _ˆ j d¡ ˆ j d¡ tˆ jd	d
d|jjddˆ _	ˆ j	 
ˆ j¡ ˆ d¡ˆ _ˆ j d¡ tˆ jdd
d|jjddˆ _ˆ j 
ˆ j¡ ˆ d¡ˆ _ˆ j d¡ tˆ jdd
d|jjddˆ _ˆ j 
ˆ j¡ ˆ d¡ˆ _ˆ j d¡ tˆ jdd
d|jjddˆ _ˆ j 
ˆ j¡ ˆ d¡ˆ _ˆ j d¡ tˆ jdd
d|jjddˆ _ˆ j 
ˆ j¡ ˆ d¡ˆ _ˆ j d¡ tˆ jdd
d|jjddˆ _ˆ j 
ˆ j¡ ˆ jˆ j	_ ˆ j	ˆ j_!ˆ jˆ j_ ˆ jˆ j_!ˆ "ddddg¡}t#|dƒˆ _$ˆ j	ˆ jˆ jˆ jˆ jˆ jf‰‡ ‡‡fdd„}ˆjj%}dˆj_%ˆ j$ &|¡ |ˆj_%dS ) a  
        *targetfig*
            The figure instance to adjust.

        *toolfig*
            The figure instance to embed the subplot tool into. If
            *None*, a default figure will be created. If you are using
            this from the GUI
        gš™™™™™É?gÍÌÌÌÌÌì?)r^   r]   c               @   s   e Zd Zdd„ Zdd„ ZdS )z(SubplotTool.__init__.<locals>.toolbarfmtc             S   s
   || _ d S )N)Úslider)r   rÛ   r   r   r   r   Q  s    z1SubplotTool.__init__.<locals>.toolbarfmt.__init__c             S   s    d| j j ¡ | j jf }|| S )Nz%s=%s)rÛ   r@   r¢   rn   )r   r™   r•   Zfmtr   r   r   r   T  s    z1SubplotTool.__init__.<locals>.toolbarfmt.__call__N)r   r   r   r   r   r   r   r   r   Ú
toolbarfmtP  s   rÜ   iÇ  z'Click on slider to adjust subplot paramFr^   r   r   )rc   iÈ  ÚbottomiÉ  r]   )rb   iÊ  ÚtopiË  ÚwspaceiÌ  Úhspacegš™™™™™é?gš™™™™™©?g333333Ã?g333333³?ZResetc                sŠ   ˆ j }dˆ _ g }xˆD ]}| |j ¡ d|_ qW xˆD ]}| ¡  q6W xtˆ|ƒD ]\}}||_ qRW |ˆ _ ˆ j r†ˆj ¡  ˆ jj ¡  d S )NF)r$   r-   r~   r   r*   rS   Ú	targetfig)r"   Z
thisdrawonZbsrÛ   Úb)r   ÚslidersÚtoolfigr   r   rR   ’  s    




z"SubplotTool.__init__.<locals>.funcN)'rá   Úsubplots_adjustZadd_subplotZaxleftZ	set_titlerF   rW   Zsubplotparsr^   Z
sliderleftr}   ÚfuncleftZaxbottomrÝ   ZsliderbottomÚ
funcbottomZaxrightr]   ZsliderrightÚ	funcrightZaxtoprÞ   Z	slidertopÚfunctopZaxwspacerß   ZsliderwspaceÚ
funcwspaceZaxhspacerà   ZsliderhspaceÚ
funchspacere   rd   Zadd_axesr4   ZbuttonresetÚvalidaterT   )r   rá   rä   rÜ   ZbaxrR   rì   r   )r   rã   rä   r   r   A  sl    	












zSubplotTool.__init__c             C   s$   | j j|d | jr | j j ¡  d S )N)r^   )rá   rå   r$   r*   rS   )r   rZ   r   r   r   ræ   ³  s    zSubplotTool.funcleftc             C   s$   | j j|d | jr | j j ¡  d S )N)r]   )rá   rå   r$   r*   rS   )r   rZ   r   r   r   rè   ¸  s    zSubplotTool.funcrightc             C   s$   | j j|d | jr | j j ¡  d S )N)rÝ   )rá   rå   r$   r*   rS   )r   rZ   r   r   r   rç   ½  s    zSubplotTool.funcbottomc             C   s$   | j j|d | jr | j j ¡  d S )N)rÞ   )rá   rå   r$   r*   rS   )r   rZ   r   r   r   ré   Â  s    zSubplotTool.functopc             C   s$   | j j|d | jr | j j ¡  d S )N)rß   )rá   rå   r$   r*   rS   )r   rZ   r   r   r   rê   Ç  s    zSubplotTool.funcwspacec             C   s$   | j j|d | jr | j j ¡  d S )N)rà   )rá   rå   r$   r*   rS   )r   rZ   r   r   r   rë   Ì  s    zSubplotTool.funchspaceN)r   r   r   r   r   ræ   rè   rç   ré   rê   rë   r   r   r   r   rÚ   =  s   rrÚ   c               @   s2   e Zd ZdZddd„Zdd„ Zdd	„ Zd
d„ ZdS )ÚCursoraÙ  
    A horizontal and vertical line that spans the axes and moves with
    the pointer.  You can turn off the hline or vline respectively with
    the following attributes:

      *horizOn*
        Controls the visibility of the horizontal line

      *vertOn*
        Controls the visibility of the horizontal line

    and the visibility of the cursor itself with the *visible* attribute.

    For the cursor to remain responsive you must keep a reference to
    it.
    TFc             K   s¦   t  | |¡ |  d| j¡ |  d| j¡ d| _|| _|| _|oD| jj	| _
| j
rVd|d< |j| ¡ d fddi|—Ž| _|j| ¡ d fddi|—Ž| _d| _d| _dS )	z¾
        Add a cursor to *ax*.  If ``useblit=True``, use the backend-dependent
        blitting features for faster updates.  *lineprops* is a dictionary of
        line properties.
        r=   Ú
draw_eventTÚanimatedr   ÚvisibleFN)r'   r   r0   ÚonmoveÚclearrð   ÚhorizOnÚvertOnr*   Úsupports_blitÚuseblitÚaxhlineÚ
get_yboundÚlinehrm   Ú
get_xboundÚlinevÚ
backgroundÚ	needclear)r   r(   ró   rô   rö   Ú	linepropsr   r   r   r   ã  s      zCursor.__init__c             C   sB   |   |¡rdS | jr&| j | jj¡| _| j d¡ | j	 d¡ dS )zclear the cursorNF)
r#   rö   r*   Úcopy_from_bboxr(   Úbboxrü   rû   rŽ   rù   )r   r"   r   r   r   rò   ü  s    
zCursor.clearc             C   sÊ   |   |¡rdS | jj | ¡s dS |j| jkr^| j d¡ | j d¡ | j	rZ| j 
¡  d| _	dS d| _	| jsndS | j |j|jf¡ | j |j|jf¡ | j | jo¦| j¡ | j | joº| j¡ |  ¡  dS )z*on mouse motion draw the cursor if visibleNFT)r#   r*   Ú
widgetlockr   rM   r(   rû   rŽ   rù   rý   rS   rð   Ú	set_xdatarx   Ú	set_ydataÚydatarô   ró   rp   )r   r"   r   r   r   rñ     s&    

zCursor.onmovec             C   sZ   | j rL| jd k	r| j | j¡ | j | j¡ | j | j¡ | j | jj	¡ n
| j 
¡  dS )NF)rö   rü   r*   Úrestore_regionr(   Údraw_artistrû   rù   Úblitr   r|   )r   r   r   r   rp     s    

zCursor._updateN)TTF)r   r   r   r   r   rò   rñ   rp   r   r   r   r   rí   Ò  s
   
	rí   c               @   sB   e Zd ZdZddd„Z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.

    Example usage::

        from matplotlib.widgets import MultiCursor
        import matplotlib.pyplot as plt
        import numpy as np

        fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
        t = np.arange(0.0, 2.0, 0.01)
        ax1.plot(t, np.sin(2*np.pi*t))
        ax2.plot(t, np.sin(4*np.pi*t))

        multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1,
                            horizOn=False, vertOn=True)
        plt.show()

    TFc                sÎ   || _ || _|| _|| _|d  ¡ \}}|d  ¡ \}	}
d||  ‰d|	|
  ‰d| _|o`| j j| _d | _	d| _
| jr~dˆ d< |rš‡ ‡fdd„|D ƒ| _ng | _|r¼‡ ‡fdd„|D ƒ| _ng | _|  ¡  d S )	Néÿÿÿÿg      à?TFrï   c                s"   g | ]}|j ˆfd diˆ —Ž‘qS )rð   F)rm   )r¤   r(   )rþ   Úxmidr   r   r¥   [  s   z(MultiCursor.__init__.<locals>.<listcomp>c                s"   g | ]}|j ˆfd diˆ —Ž‘qS )rð   F)r÷   )r¤   r(   )rþ   Úymidr   r   r¥   a  s   )r*   Úaxesró   rô   Úget_xlimÚget_ylimrð   rõ   rö   rü   rý   rµ   ÚhlinesÚconnect)r   r*   r  rö   ró   rô   rþ   ÚxminÚxmaxÚyminÚymaxr   )rþ   r
  r  r   r   E  s.    zMultiCursor.__init__c             C   s(   | j  d| j¡| _| j  d| j¡| _dS )zconnect eventsr=   rî   N)r*   r,   rñ   Ú
_cidmotionrò   Ú_ciddraw)r   r   r   r   r  h  s    
zMultiCursor.connectc             C   s    | j  | j¡ | j  | j¡ dS )zdisconnect eventsN)r*   r1   r  r  )r   r   r   r   rV   n  s    zMultiCursor.disconnectc             C   sL   |   |¡rdS | jr(| j | jjj¡| _x| j| j D ]}| 	d¡ q6W dS )zclear the cursorNF)
r#   rö   r*   rÿ   r)   r   rü   rµ   r  rŽ   )r   r"   Úliner   r   r   rò   s  s    
zMultiCursor.clearc             C   s²   |   |¡rd S |jd krd S | jj | ¡s.d S d| _| js>d S | jrrx,| jD ]"}| 	|j
|j
f¡ | | j¡ qLW | jr¦x,| jD ]"}| |j|jf¡ | | j¡ q€W |  ¡  d S )NT)r#   rM   r*   r  r   rý   rð   rô   rµ   r  rx   rŽ   ró   r  r  r  rp   )r   r"   r  r   r   r   rñ   }  s$    

zMultiCursor.onmovec             C   s˜   | j rŠ| jd k	r| j | j¡ | jrJx$t| j| jƒD ]\}}| |¡ q4W | j	rvx$t| j| j
ƒD ]\}}| |¡ q`W | j | jjj¡ n
| j ¡  d S )N)rö   rü   r*   r  rô   r   r  rµ   r  ró   r  r  r)   r   r|   )r   r(   r  r   r   r   rp   ‘  s    
zMultiCursor._updateN)TFT)
r   r   r   r   r   r  rV   rò   rñ   rp   r   r   r   r   r  -  s   
#
r  c               @   s¶   e Zd Zd-dd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Zdd„ Z	d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S ).Ú_SelectorWidgetFNc             C   s”   t  | |¡ d| _|| _|o"| jj| _|  ¡  tddddd| _	| j	 
|pLi ¡ d | _g | _t|tƒrp|g| _n|| _d | _d | _d | _tƒ | _d S )NTr¼   ÚescapeÚshiftÚcontrol)Úmoverò   Úsquarer7   )r'   r   rð   Úonselectr*   rõ   rö   Úconnect_default_eventsÚdictÚstate_modifier_keysÚupdaterü   ÚartistsÚ
isinstancer   ÚvalidButtonsÚ
eventpressÚeventreleaseÚ_prev_eventÚsetÚstate)r   r(   r  rö   rv   r!  r   r   r   r   ¢  s"    

z_SelectorWidget.__init__c             C   s   t  | |¡ |r|  d ¡ d S )N)r'   r   Úupdate_background)r   r   r   r   r   r   ¾  s    z_SelectorWidget.set_activec             C   s   | j r| j | jj¡| _dS )z!force an update of the backgroundN)rö   r*   rÿ   r(   r   rü   )r   r"   r   r   r   r+  Ã  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.r=   r;   r<   rî   r­   Zkey_release_eventZscroll_eventN)r0   rñ   Úpressr   r+  Úon_key_pressÚon_key_releaseÚ	on_scroll)r   r   r   r   r  Ê  s    z&_SelectorWidget.connect_default_eventsc             C   s’   | j r| j ¡ sdS | jj | ¡s&dS t|dƒs6d|_| jdk	rP|j| jkrPdS | j	dkrf|j
| jkS |j| j	jkrxdS |j
| jkp|j| j	jkS )z*return *True* if *event* should be ignoredTrv   NF)r   r(   r¡   r*   r  r   r_   rv   r%  r&  rM   )r   r"   r   r   r   r#   Ô  s    


z_SelectorWidget.ignorec             C   sh   | j  ¡ sdS | jrZ| jdk	r,| j | j¡ x| jD ]}| j  |¡ q4W | j | j j	¡ n
| j 
¡  dS )zTdraw using newfangled blit or oldfangled draw depending on
        useblit

        FN)r(   r¡   rö   rü   r*   r  r#  r  r  r   r|   )r   Úartistr   r   r   r"  õ  s    


z_SelectorWidget.updatec             C   s^   |j dkrdS | j ¡ \}}| j ¡ \}}t||j ƒ}t||ƒ}t||jƒ}t||ƒ}||fS )z.Get the xdata and ydata for event, with limitsN)NN)rx   r(   rú   rø   ÚmaxÚminr  )r   r"   Úx0Úx1Úy0Úy1rx   r  r   r   r   Ú	_get_data	  s    


z_SelectorWidget._get_datac             C   s8   |j dkr| j}n
t |¡}|  |¡\|_ |_|| _|S )z—Clean up an event

        Use prev event if there is no xdata
        Limit the xdata and ydata to the axes limits
        Set the prev event
        N)rx   r(  Úcopyr7  r  )r   r"   r   r   r   Ú_clean_event  s    

z_SelectorWidget._clean_eventc             C   sb   |   |¡s^|  |¡}|| _|| _|jp(d}| dd¡}|| jd krP| j d¡ |  	|¡ dS dS )z"Button press handler and validatorr¨   Úctrlr  r  TF)
r#   r9  r&  r(  r¬   Úreplacer!  r*  ÚaddÚ_press)r   r"   r¬   r   r   r   r,  %  s    



z_SelectorWidget.pressc             C   s   dS )zButton press handlerNr   )r   r"   r   r   r   r=  4  s    z_SelectorWidget._pressc             C   sJ   |   |¡sF| jrF|  |¡}|| _|  |¡ d| _d| _| j d¡ dS dS )z*Button release event handler and validatorNr  TF)r#   r&  r9  r'  rD   r*  Údiscard)r   r"   r   r   r   r   8  s    

z_SelectorWidget.releasec             C   s   dS )zButton release event handlerNr   )r   r"   r   r   r   rD   D  s    z_SelectorWidget._releasec             C   s,   |   |¡s(| jr(|  |¡}|  |¡ dS dS )z'Cursor move event handler and validatorTF)r#   r&  r9  Ú_onmove)r   r"   r   r   r   rñ   H  s
    

z_SelectorWidget.onmovec             C   s   dS )zCursor move event handlerNr   )r   r"   r   r   r   r?  P  s    z_SelectorWidget._onmovec             C   s   |   |¡s|  |¡ dS )z(Mouse scroll event handler and validatorN)r#   Ú
_on_scroll)r   r"   r   r   r   r/  T  s    
z_SelectorWidget.on_scrollc             C   s   dS )zMouse scroll event handlerNr   )r   r"   r   r   r   r@  Y  s    z_SelectorWidget._on_scrollc             C   sŠ   | j r†|jpd}| dd¡}|| jd krPx| jD ]}| d¡ q2W |  ¡  dS x*| j ¡ D ]\}}||kr\| j 	|¡ q\W |  
|¡ dS )z?Key press event handler and validator for all selection widgetsr¨   r:  r  rò   FN)r   r¬   r;  r!  r#  rŽ   r"  rQ   r*  r<  Ú_on_key_press)r   r"   r¬   r0  r*  Úmodifierr   r   r   r-  ]  s    
z_SelectorWidget.on_key_pressc             C   s   dS )zMKey press event handler - use for widget-specific key press actions.
        Nr   )r   r"   r   r   r   rA  l  s    z_SelectorWidget._on_key_pressc             C   sJ   | j rF|jpd}x*| j ¡ D ]\}}||kr| j |¡ qW |  |¡ dS )z'Key release event handler and validatorr¨   N)r   r¬   r!  rQ   r*  r>  Ú_on_key_release)r   r"   r¬   r*  rB  r   r   r   r.  q  s    
z_SelectorWidget.on_key_releasec             C   s   dS )zKey release event handlerNr   )r   r"   r   r   r   rC  z  s    z_SelectorWidget._on_key_releasec             C   s$   || _ x| jD ]}| |¡ qW dS )z# Set the visibility of our artists N)rð   r#  rŽ   )r   rð   r0  r   r   r   rŽ   ~  s    z_SelectorWidget.set_visible)FNN)r   r   r   r   r   r+  r  r#   r"  r7  r9  r,  r=  r   rD   rñ   r?  r/  r@  r-  rA  r.  rC  rŽ   r   r   r   r   r     s,    

!	r  c               @   sJ   e Zd ZdZddd„Zdd„ Zdd	„ Zd
d„ Zdd„ Zdd„ Z	dd„ Z
dS )Ú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=False`. To
    turn it back on, set `span_selector.active=True`.

    Parameters
    ----------
    ax :  :class:`matplotlib.axes.Axes` object

    onselect : func(min, max), min/max are floats

    direction : "horizontal" or "vertical"
      The axis along which to draw the span selector

    minspan : float, default is None
     If selection is less than *minspan*, do not call *onselect*

    useblit : bool, default is False
      If True, use the backend-dependent blitting features for faster
      canvas updates.

    rectprops : dict, default is None
      Dictionary of :class:`matplotlib.patches.Patch` properties

    onmove_callback : func(min, max), min/max are floats, default is None
      Called on mouse move while the span is being selected

    span_stays : bool, default is False
      If True, the span stays visible after the mouse is released

    button : int or list of ints
      Determines which mouse buttons activate the span selector
        1 = left mouse button

        2 = center mouse button (scroll wheel)

        3 = right mouse button


    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)
    >>> rectprops = dict(facecolor='blue', alpha=0.5)
    >>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal',
    ...                              rectprops=rectprops)
    >>> fig.show()

    See also: :doc:`/gallery/widgets/span_selector`

    NFc
       
      C   s†   t j| ||||	d |d kr(tddd}| j|d< |dkrBtdƒ‚|| _d | _d | _|| _|| _	|| _
|| _d| _d | _|  |¡ d S )	N)rö   rv   Úredg      à?)r†   Úalpharï   )Ú
horizontalZverticalz,direction must be 'horizontal' or 'vertical')r   r   )r  r   r   rö   r   Ú	directionÚrectÚpressvÚ	rectpropsÚonmove_callbackÚminspanÚ
span_staysÚprevr*   Únew_axes)
r   r(   r  rH  rM  rö   rK  rL  rN  rv   r   r   r   r   ¿  s"    
zSpanSelector.__init__c             C   sð   || _ | j|jjk	r8| jdk	r&|  ¡  |jj| _|  ¡  | jdkr^t| j j| j jƒ}d\}}nt| j j| j jƒ}d\}}t	d||f|ddœ| j
—Ž| _| jrÔt	d||f|ddœ| j
—Ž| _| j d¡ | j  | j¡ | j  | j¡ | jg| _dS )z)Set SpanSelector to operate on a new AxesNrG  )r   r   )r   r   )r   r   F)r:   rð   )r(   r*   r)   r3   r  rH  r	   r¾   r?   r   rK  rI  rN  Ú	stay_rectÚset_animatedr   r#  )r   r(   rÎ   r—   r˜   r   r   r   rP  Þ  s4    







zSpanSelector.new_axesc             C   s   t  | |¡p| j S )z*return *True* if *event* should be ignored)r  r#   rð   )r   r"   r   r   r   r#   ÿ  s    zSpanSelector.ignorec             C   sd   | j  | j¡ | jr0| j d¡ | jr0| j ¡  |  |¡\}}| j	dkrP|| _
n|| _
|  |¡ dS )zon button press eventFrG  )rI  rŽ   rð   rN  rQ  rö   r*   rS   r7  rH  rJ  Ú_set_span_xy)r   r"   rx   r  r   r   r   r=    s    


zSpanSelector._pressc             C   s  | j dkrdS d| _| j d¡ | jrz| j | j ¡ ¡ | j | j 	¡ ¡ | j 
| j ¡ ¡ | j | j ¡ ¡ | j d¡ | j ¡  | j }|  |¡\}}| jdkr²|p®| jd }n|p¾| jd }||krÒ|| }}|| }| jdk	rò|| jk ròdS |  ||¡ d| _ dS )zon button release eventNFTrG  r   r   )rJ  Z
buttonDownrI  rŽ   rN  rQ  Úset_xÚget_xÚset_yÚget_yÚ	set_widthÚ	get_widthÚ
set_heightÚ
get_heightr*   r|   r7  rH  rO  rM  r  )r   r"   Úvminrx   r  ÚvmaxÚspanr   r   r   rD     s0    



zSpanSelector._releasec             C   sˆ   | j dkrdS |  |¡ | jdk	r|| j }|  |¡\}}| jdkrP|pL| jd }n|p\| jd }||krp|| }}|  ||¡ |  ¡  dS )zon motion notify eventNrG  r   r   F)rJ  rS  rL  r7  rH  rO  r"  )r   r"   r\  rx   r  r]  r   r   r   r?  5  s    




zSpanSelector._onmovec             C   sž   |   |¡\}}|dkrdS ||f| _| jdkr4|}n|}|| j }}||krV|| }}| jdkr~| j |¡ | j || ¡ n| j |¡ | j || ¡ dS )zSetting the span coordinatesNrG  )	r7  rO  rH  rJ  rI  rT  rX  rV  rZ  )r   r"   r™   r•   ÚvZminvZmaxvr   r   r   rS  K  s    



zSpanSelector._set_span_xy)NFNNFN)r   r   r   r   r   rP  r#   r=  rD   r?  rS  r   r   r   r   rD  …  s   8  
! rD  c               @   sT   e Zd ZdZd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 )ÚToolHandlesa¦  Control handles for canvas tools.

    Parameters
    ----------
    ax : :class:`matplotlib.axes.Axes`
        Matplotlib axes where tool handles are displayed.
    x, y : 1D arrays
        Coordinates of control handles.
    marker : str
        Shape of marker used to display handle. See `matplotlib.pyplot.plot`.
    marker_props : dict
        Additional marker properties. See :class:`matplotlib.lines.Line2D`.
    r   NTc          	   C   sd   || _ t|ddddddd}| |d k	r,|ni ¡ t||fd|i|—Ž| _| j  | j¡ | j| _d S )	Né   r—   Únoneg      à?FZ
_nolegend_)ÚmarkerZ
markersizeÚmfcZlsrF  rð   r@   rï   )r(   r   r"  r   Ú_markersr   r0  )r   r(   r™   r•   rc  Úmarker_propsrö   Úpropsr   r   r   r   q  s    
zToolHandles.__init__c             C   s
   | j  ¡ S )N)re  Z	get_xdata)r   r   r   r   r™   {  s    zToolHandles.xc             C   s
   | j  ¡ S )N)re  Z	get_ydata)r   r   r   r   r•     s    zToolHandles.yc             C   s*   |dk	r|}t  ||g¡}| j |¡ dS )z Set x and y positions of handlesN)rt   rÙ   re  Úset_data)r   Úptsr•   r™   r   r   r   rh  ƒ  s    zToolHandles.set_datac             C   s   | j  |¡ d S )N)re  rŽ   )r   rZ   r   r   r   rŽ   Š  s    zToolHandles.set_visiblec             C   s   | j  |¡ d S )N)re  rR  )r   rZ   r   r   r   rR    s    zToolHandles.set_animatedc             C   s~   t  | j| jf¡}| jj |¡}|||f }|jdkrbt  t j	|d dd¡}t  
|¡t  |¡fS dt  t  	|d ¡¡fS dS )z1Return index and pixel distance to closest index.ry   r   )Zaxisr   N)rt   Z	transposer™   r•   r(   r¾   r:   ÚndimÚsqrtÚsumZargminr2  )r   r™   r•   ri  ZdiffZdistr   r   r   Úclosest  s    
zToolHandles.closest)r   NT)N)r   r   r   r   r   r&   r™   r•   rh  rŽ   rR  rm  r   r   r   r   r`  b  s   


r`  c               @   sœ   e Zd ZdZeZd dd„Z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
dd„ ƒZejdd„ ƒZdd„ Zdd„ Ze
dd„ ƒZdS )!ÚRectangleSelectora  
    Select a rectangular region of an axes.

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

    Example usage::

        import numpy as np
        import matplotlib.pyplot as plt
        from matplotlib.widgets import RectangleSelector

        def onselect(eclick, erelease):
            "eclick and erelease are matplotlib events at press and release."
            print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
            print('endposition  : (%f, %f)' % (erelease.xdata, erelease.ydata))
            print('used button  : ', eclick.button)

        def toggle_selector(event):
            print('Key pressed.')
            if event.key in ['Q', 'q'] and toggle_selector.RS.active:
                print('RectangleSelector deactivated.')
                toggle_selector.RS.set_active(False)
            if event.key in ['A', 'a'] and not toggle_selector.RS.active:
                print('RectangleSelector activated.')
                toggle_selector.RS.set_active(True)

        x = np.arange(100.) / 99
        y = np.sin(x)
        fig, ax = plt.subplots()
        ax.plot(x, y)

        toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='line')
        fig.canvas.connect('key_press_event', toggle_selector)
        plt.show()
    ÚboxNFÚdataé
   c             C   s  t j| ||||
|d d| _d| _|| _|dkr:d}d| _|dkr|dkrZtdd	d
dd}| j|d< || _| jd%ddi| j—Ž| _| j	 
| j¡ |dkrð|dkr°td	dddd}| j|d< || _tddgddgfddi| j—Ž| _| j	 | j¡ || _|| _|	dkrtdƒ‚|	| _|| _|| _|dkr6tdd}nt| dd¡d}ddddg| _| j\}}t| j	|||| jd| _dd d!d"g| _| j\}}t| j	||d#|| jd$| _| j\}}t| j	|g|gd#|| jd$| _d| _| j| jj| jj| jjg| _ | js| jg| _ d| _!dS )&aä  
        Create a selector in *ax*.  When a selection is made, clear
        the span and call onselect with::

          onselect(pos_1, pos_2)

        and clear the drawn box/line. The ``pos_1`` and ``pos_2`` are
        arrays of length 2 containing the x- and y-coordinate.

        If *minspanx* is not *None* then events smaller than *minspanx*
        in x direction are ignored (it's the same for y).

        The rectangle is drawn with *rectprops*; default::

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

        The line is drawn with *lineprops*; default::

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

        Use *drawtype* if you want the mouse to draw a line,
        a box or nothing between click and actual position by setting

        ``drawtype = 'line'``, ``drawtype='box'`` or ``drawtype = 'none'``.
        Drawing a line would result in a line from vertex A to vertex C in
        a rectangle ABCD.

        *spancoords* is one of 'data' or 'pixels'.  If 'data', *minspanx*
        and *minspanx* will be interpreted in the same coordinates as
        the x and y axis. If 'pixels', they are in pixels.

        *button* is a list of integers indicating which mouse buttons should
        be used for rectangle selection.  You can also specify a single
        integer if only a single button is desired.  Default is *None*,
        which does not limit which button can be used.

        Note, typically:
         1 = left mouse button
         2 = center mouse button (scroll wheel)
         3 = right mouse button

        *interactive* will draw a set of handles and allow you interact
        with the widget after it is drawn.

        *state_modifier_keys* are keyboard modifiers that affect the behavior
        of the widget.

        The defaults are:
        dict(move=' ', clear='escape', square='shift', center='ctrl')

        Keyboard modifiers, which:
        'move': Move the existing shape.
        'clear': Clear the current shape.
        'square': Makes the shape square.
        'center': Make the initial point the center of the shape.
        'square' and 'center' can be combined.
        )rö   rv   r!  NTrb  r  Fro  rE  r‚   gš™™™™™É?)r†   r…   rF  Zfillrï   ©r   r   r   r   rð   ú-ry   g      à?)rJ   Ú	linestyler   rF  )rp  Úpixelsz''spancoords' must be 'data' or 'pixels'r[   )Úmecr…   ÚNWÚNEZSEÚSW)rf  rö   ÚWÚNÚEÚSÚs)rc  rf  rö   )rr  r   r   )"r  r   Úto_drawrð   Úinteractiver   rö   rK  Ú_shape_klassr(   r   rþ   r   r   ÚminspanxÚminspanyr   Ú
spancoordsÚdrawtypeÚmaxdistÚgetÚ_corner_orderÚcornersr`  Ú_corner_handlesÚ_edge_orderÚedge_centersÚ_edge_handlesr7   Ú_center_handleÚactive_handler0  r#  Ú_extents_on_press)r   r(   r  r…  r‚  rƒ  rö   rþ   rK  r„  rv   r†  rf  r€  r!  rg  ÚxcÚycÚxeÚyer   r   r   r   Å  sr    A










zRectangleSelector.__init__c             C   sj   | j r| j ¡ r|  |¡ nd| _| jdks2| j s:|  ¡  | j sZ|j}|j}||||f| _|  	| j
¡ dS )zon button press eventN)r€  r  r¡   Ú_set_active_handler  r"  rx   r  ÚextentsrŽ   rð   )r   r"   r™   r•   r   r   r   r=  O  s    zRectangleSelector._pressc             C   s¬  | j s| j d¡ | j\}}}}|| j_|| j_| jj 	||g¡}|\| j_
| j_|| j_|| j_| jj 	||g¡}|\| j_
| j_| jdkr´| jj| jj }}	| jj| jj }
}n8| jdkrä| jj
| jj }}	| jj
| jj }
}ntdƒ‚||
kr |
| }}
|	|kr||	 }	}|
| }||	 }| jdk	o8|| jk }| jdk	oN|| jk }| jdkr|sh|rx| jD ]}| d¡ qpW |  ¡  dS |  | j| j¡ |  ¡  dS )zon button release eventFrp  ru  z%spancoords must be "data" or "pixels"Nrb  )r€  r  rŽ   r–  r&  rx   r  r(   r¾   rØ   r™   r•   r'  r„  r   r‚  rƒ  r…  r#  r"  r  )r   r"   r4  Úx2r6  Úy2Zxy1Zxy2r  r  r  r  ZspanxZspanyZ	xproblemsZ	yproblemsr0  r   r   r   rD   c  sD    





zRectangleSelector._releasec             C   s  | j rV| j dksV| j\}}}}| j ddg| j kr8|j}| j ddg| j krR|j}n²d| jksj| j dkrÂ| jdk	rÂ| j\}}}}|j| jj }|j| jj }||7 }||7 }||7 }||7 }nF| jj| jjg}| jj| jjg}	|j|d  d	 }|j|d
  d	 }d| jkr–t	|j|	d  ƒ}
t	|j|	d
  ƒ}|
s@dS t
t	|
ƒt	|ƒƒ}t	|
ƒ|k rt||t	|
ƒd  9 }t	|ƒ|k r–||t	|ƒd  9 }d| jkr´|d9 }|d9 }n |d  |7  < |d
  |7  < |d | |d | |d
 | |d
 | f\}}}}||||f| _dS )z,on motion notify event if box/line is wantedÚCr|  rz  r{  r}  r  Nr   g       @r   r  gíµ ÷Æ°>r7   ry   )r  r  rˆ  rx   r  r*  r&  r™   r•   Úabsr1  r–  )r   r"   r4  r—  r6  r˜  Údxr’   r7   Z
center_pixZdx_pixZdy_pixZmaxdr   r   r   r?  —  sJ    


 zRectangleSelector._onmovec       	      C   sˆ   | j dkr>| j ¡ }| j ¡ }| j ¡ }| j ¡ }||||fS | j ¡ \}}t|ƒt|ƒ }}t|ƒt|ƒ }}|||| || fS d S )Nro  )	r…  r  rU  rW  rY  r[  Úget_datar2  r1  )	r   r3  r5  rƒ   r„   r™   r•   r4  r6  r   r   r   Ú
_rect_bboxÎ  s    




zRectangleSelector._rect_bboxc             C   s>   | j \}}}}||| || |f}|||| || f}||fS )z7Corners of rectangle from lower left, moving clockwise.)r  )r   r3  r5  rƒ   r„   r‘  r’  r   r   r   r‰  Ü  s    zRectangleSelector.cornersc       	      C   sV   | j \}}}}|d }|d }||| || || f}|| ||| || f}||fS )z8Midpoint of rectangle edges from left, moving clockwise.g       @)r  )	r   r3  r5  rƒ   r„   r—   r˜   r“  r”  r   r   r   rŒ  ä  s    zRectangleSelector.edge_centersc             C   s&   | j \}}}}||d  ||d  fS )zCenter of rectangleg       @)r  )r   r3  r5  rƒ   r„   r   r   r   r7   î  s    zRectangleSelector.centerc       	      C   sB   | j \}}}}t||| gƒ\}}t||| gƒ\}}||||fS )z Return (xmin, xmax, ymin, ymax).)r  Úsorted)	r   r3  r5  rƒ   r„   r  r  r  r  r   r   r   r–  ô  s    zRectangleSelector.extentsc             C   sL   |   |¡ | jj| jŽ  | jj| jŽ  | jj| jŽ  |  | j	¡ |  
¡  d S )N)Ú
draw_shaperŠ  rh  r‰  r  rŒ  rŽ  r7   rŽ   rð   r"  )r   r–  r   r   r   r–  ü  s    
c             C   sè   |\}}}}t ||gƒ\}}t ||gƒ\}}	t | j ¡ ƒ}
t | j ¡ ƒ}t|
d |ƒ}t|d |ƒ}t||
d ƒ}t|	|d ƒ}	| jdkrÄ| j |¡ | j 	|¡ | j 
|| ¡ | j |	| ¡ n | jdkrä| j ||g||	g¡ d S )Nr   r   ro  r  )rž  r(   r  r  r1  r2  r…  r  rT  rV  rX  rZ  rh  )r   r–  r3  r4  r5  r6  r  r  r  r  ZxlimZylimr   r   r   rŸ  	  s     

zRectangleSelector.draw_shapec             C   sþ   | j  |j|j¡\}}| j |j|j¡\}}| j |j|j¡\}}d| jkr\d| _| j| _	nV|| j
d k rrd| _n@|| j
kr|| j
krd| _dS ||k r¦| j| | _n| j| | _| j\}}	}
}| jdkrÖ|	|j }}	| jdkrì||j }
}||	|
|f| _	dS )z:Set active handle based on the location of the mouse eventr  r™  ry   N)rz  ry  rw  )r{  rw  rx  )rŠ  rm  r™   r•   r  rŽ  r*  r  r–  r  r†  rˆ  r‹  rx   r  )r   r"   Zc_idxZc_distZe_idxZe_distZm_idxZm_distr4  r—  r6  r˜  r   r   r   r•  	  s(    



z$RectangleSelector._set_active_handlec             C   sP   t | jdƒr<| jj ¡ }| | j ¡ ¡j\}}t 	||g¡S t 	| j 
¡ ¡S dS )a  
        Returns numpy.ndarray of shape (2,5) containing
        x (``RectangleSelector.geometry[1,:]``) and
        y (``RectangleSelector.geometry[0,:]``)
        coordinates of the four corners of the rectangle starting
        and ending in the top left corner.
        Ú	get_vertsN)r_   r  r(   r¾   r¿   r:   r   ÚTrt   rÙ   rœ  )r   Zxfmr•   r™   r   r   r   Úgeometry;	  s
    	zRectangleSelector.geometry)ro  NNFNNrp  Nrq  NFN)r   r   r   r   r   r  r   r=  rD   r?  r&   r  r‰  rŒ  r7   r–  ÚsetterrŸ  r•  r¢  r   r   r   r   rn    s(   $    
 47
rn  c               @   s(   e Zd ZdZeZdd„ Zedd„ ƒZdS )ÚEllipseSelectora  
    Select an elliptical region of an axes.

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

    Example usage::

        import numpy as np
        import matplotlib.pyplot as plt
        from matplotlib.widgets import EllipseSelector

        def onselect(eclick, erelease):
            "eclick and erelease are matplotlib events at press and release."
            print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
            print('endposition  : (%f, %f)' % (erelease.xdata, erelease.ydata))
            print('used button  : ', eclick.button)

        def toggle_selector(event):
            print(' Key pressed.')
            if event.key in ['Q', 'q'] and toggle_selector.ES.active:
                print('EllipseSelector deactivated.')
                toggle_selector.RS.set_active(False)
            if event.key in ['A', 'a'] and not toggle_selector.ES.active:
                print('EllipseSelector activated.')
                toggle_selector.ES.set_active(True)

        x = np.arange(100.) / 99
        y = np.sin(x)
        fig, ax = plt.subplots()
        ax.plot(x, y)

        toggle_selector.ES = EllipseSelector(ax, onselect, drawtype='line')
        fig.canvas.connect('key_press_event', toggle_selector)
        plt.show()
    c             C   sâ   |\}}}}t ||gƒ\}}t ||gƒ\}}	||| d  ||| d  g}
|| d }|	| d }| jdkr|
| j_d| | j_d| | j_nNt t d¡d ¡}|t 	|¡ |
d  }|t 
|¡ |
d  }| j ||¡ d S )Ng       @ro  ry   é   é   r   r   )rž  r…  r  r7   rƒ   r„   rt   Zdeg2radZarangeZcosZsinrh  )r   r–  r4  r—  r6  r˜  r  r  r  r  r7   Úarâ   Zradr™   r•   r   r   r   rŸ  s	  s     
zEllipseSelector.draw_shapec       	      C   sŒ   | j dkrB| jj\}}| jj}| jj}||d  ||d  ||fS | j ¡ \}}t|ƒt|ƒ }}t|ƒt|ƒ }}|||| || fS d S )Nro  g       @)r…  r  r7   rƒ   r„   rœ  r2  r1  )	r   r™   r•   rƒ   r„   r3  r4  r5  r6  r   r   r   r  …	  s    
zEllipseSelector._rect_bboxN)	r   r   r   r   r   r  rŸ  r&   r  r   r   r   r   r¤  L	  s   $r¤  c               @   sB   e Zd ZdZddd„Zdd„ Zdd	„ Zd
d„ Zdd„ Zdd„ Z	d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 = subplot(111)
        ax.plot(x,y)

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

    Parameters
    ----------
    ax : :class:`~matplotlib.axes.Axes`
        The parent axes for the widget.
    onselect : function
        Whenever the lasso is released, the *onselect* function is called and
        passed the vertices of the selected path.
    button : List[Int], optional
        A list of integers indicating which mouse buttons should be used for
        rectangle selection. You can also specify a single integer if only a
        single button is desired.  Default is ``None``, which does not limit
        which button can be used.

        Note, typically:

        - 1 = left mouse button
        - 2 = center mouse button (scroll wheel)
        - 3 = right mouse button

    NTc             C   sl   t j| ||||d d | _|d kr(tƒ }|r4d|d< tg g f|Ž| _| j d¡ | j | j¡ | jg| _	d S )N)rö   rv   Trï   F)
r  r   Úvertsr   r   r  rŽ   r(   r   r#  )r   r(   r  rö   rþ   rv   r   r   r   r   ¾	  s    zLassoSelector.__init__c             C   s   |   |¡ d S )N)r,  )r   r"   r   r   r   ÚonpressÎ	  s    zLassoSelector.onpressc             C   s   |   |¡g| _| j d¡ d S )NT)r7  r©  r  rŽ   )r   r"   r   r   r   r=  Ñ	  s    zLassoSelector._pressc             C   s   |   |¡ d S )N)r   )r   r"   r   r   r   Ú	onreleaseÕ	  s    zLassoSelector.onreleasec             C   sN   | j d k	r(| j  |  |¡¡ |  | j ¡ | j g g g¡ | j d¡ d | _ d S )NF)r©  r-   r7  r  r  rh  rŽ   )r   r"   r   r   r   rD   Ø	  s    
zLassoSelector._releasec             C   sB   | j d krd S | j  |  |¡¡ | j tt| j Ž ƒ¡ |  ¡  d S )N)r©  r-   r7  r  rh  Úlistr   r"  )r   r"   r   r   r   r?  à	  s
    
zLassoSelector._onmove)NTNN)
r   r   r   r   r   rª  r=  r«  rD   r?  r   r   r   r   r¨  “	  s   ) 
r¨  c               @   s^   e Zd ZdZddd„Zdd„ Zd	d
„ Zdd„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zedd„ ƒZdS )ÚPolygonSelectoraq  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). Hold the *ctrl* key and click
    and drag a vertex to reposition it (the *ctrl* key is not necessary if the
    polygon has already 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 : :class:`~matplotlib.axes.Axes`
        The parent axes for the widget.
    onselect : function
        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, optional
    lineprops : dict, optional
        The line for the sides of the polygon is drawn with the properties
        given by `lineprops`. The default is ``dict(color='k', linestyle='-',
        linewidth=2, alpha=0.5)``.
    markerprops : dict, optional
        The markers for the vertices of the polygon are drawn with the
        properties given by `markerprops`. The default is ``dict(marker='o',
        markersize=7, mec='k', mfc='k', alpha=0.5)``.
    vertex_select_radius : float, optional
        A vertex is selected (to complete the polygon or to move a vertex)
        if the mouse click is within `vertex_select_radius` pixels of the
        vertex. The default radius is 15 pixels.

    Examples
    --------
    :doc:`/gallery/widgets/polygon_selector_demo`
    FNé   c             C   sæ   t ddddddd}tj| ||||d dgdg | _| _d| _|d krXt d	d
ddd}| j|d< t| j| jf|Ž| _| j	 
| j¡ |d kr t d	| dd	¡d}t| j	| j| j| j|d| _d| _|| _| j| jjg| _|  d¡ d S )Nr  r  r  znot-applicable)rò   Úmove_vertexÚmove_allr  r  r7   )rö   r!  r   Fr€   rs  ry   g      à?)rJ   rt  r   rF  rï   rJ   )rv  rd  )rö   rf  r	  T)r   r  r   Ú_xsÚ_ysÚ_polygon_completedrö   r   r  r(   r   r‡  r`  Ú_polygon_handlesÚ_active_handle_idxÚvertex_select_radiusr0  r#  rŽ   )r   r(   r  rö   rþ   Zmarkerpropsr¶  r!  r   r   r   r   
  s,    

zPolygonSelector.__init__c             C   sj   | j sd| jkrDt| jƒdkrD| j |j|j¡\}}|| jk rD|| _	| jdd… | j
dd…  | _| _dS )zButton press event handlerr¯  r   N)r³  r*  r‡   r±  r´  rm  r™   r•   r¶  rµ  r²  Ú_xs_at_pressÚ_ys_at_press)r   r"   Zh_idxZh_distr   r   r   r=  5
  s    
zPolygonSelector._pressc             C   s    | j dkrd| _ nxt| jƒdkrP| jd | jd krP| jd | jd krPd| _n:| jsŠd| jkrŠd| jkrŠ| j d|j¡ | j d|j¡ | jrœ|  	| j
¡ dS )zButton release event handlerr   r	  rz   Tr°  r¯  N)rµ  r‡   r±  r²  r³  r*  Úinsertrx   r  r  r©  )r   r"   r   r   r   rD   A
  s    


zPolygonSelector._releasec             C   s&   |   |¡s"|  |¡}|  |¡ dS dS )z'Cursor move event handler and validatorTF)r#   r9  r?  )r   r"   r   r   r   rñ   W
  s
    


zPolygonSelector.onmovec       	      C   sŽ  | j dkrV| j }|j|j | j|< | j|< |dkrR| jrR|j|j | jd< | jd< n,d| jkrÄ| jrÄ|j| jj }|j| jj }x>tt	| jƒƒD ],}| j
| | | j|< | j| | | j|< q’W n¾| jsÞd| jksÞd| jkrâdS | j ¡  | jd | jd f¡\}}t ||j d ||j d  ¡}t	| jƒdkrh|| jk rh| jd | jd  | jd< | jd< n|j|j | jd< | jd< |  ¡  dS )zCursor move event handlerr   r	  r°  r¯  Nry   rz   )rµ  rx   r  r±  r²  r³  r*  r&  Úranger‡   r·  r¸  r  Zget_transformr:   rt   rk  r™   r•   r¶  Ú_draw_polygon)	r   r"   Úidxr›  r’   r€   r3  r5  Zv0_distr   r   r   r?  c
  s*    
"$zPolygonSelector._onmovec             C   sH   | j sDd| jksd| jkrD| jdd… | jdd…  | _| _|  ¡  dS )zKey press event handlerr¯  r°  Nr	  )r³  r*  r±  r²  r»  )r   r"   r   r   r   rA  ‰
  s    "zPolygonSelector._on_key_pressc             C   s–   | j sP|j| j d¡ks*|j| j d¡krP| j |j¡ | j |j¡ |  	¡  nB|j| j d¡kr’|  
|¡}|jg|jg | _| _d| _ |  d¡ dS )zKey release event handlerr¯  r°  rò   FTN)r³  r¬   r!  r‡  r±  r-   rx   r²  r  r»  r9  rŽ   )r   r"   r   r   r   rC  ’
  s    

zPolygonSelector._on_key_releasec             C   s   | j  | j| j¡ | jsNt| jƒdkrr| jd | jd krr| jd | jd krr| j | jdd… | jdd… ¡ n| j | j| j¡ |  ¡  dS )z5Redraw the polygon based on the new vertex positions.rz   r	  r   N)r  rh  r±  r²  r³  r‡   r´  r"  )r   r   r   r   r»  ¤
  s    $zPolygonSelector._draw_polygonc             C   s"   t t| jdd… | jdd… ƒƒS )z Get the polygon vertices.

        Returns
        -------
        list
            A list of the vertices of the polygon as ``(xdata, ydata)`` tuples.
        Nr	  )r¬  r   r±  r²  )r   r   r   r   r©  ³
  s    	zPolygonSelector.verts)FNNr®  )r   r   r   r   r   r=  rD   rñ   r?  rA  rC  r»  r&   r©  r   r   r   r   r­  ê	  s   & 
"&	r­  c               @   s*   e Zd ZdZd
dd„Zdd„ Zdd	„ ZdS )ÚLassoa“  Selection curve of an arbitrary shape.

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

    Unlike :class:`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.
    NTc             C   s’   t  | |¡ |o| jj| _| jr2| j | jj¡| _|\}}||fg| _	t
|g|gdddd| _| j | j¡ || _|  d| j¡ |  d| j¡ d S )Nrs  r‚   ry   )rt  rJ   r\   r<   r=   )r'   r   r*   rõ   rö   rÿ   r(   r   rü   r©  r   r  r   r.   r0   r«  rñ   )r   r(   r{   r.   rö   r™   r•   r   r   r   r   Ô
  s    zLasso.__init__c             C   sh   |   |¡rd S | jd k	rV| j |j|jf¡ t| jƒdkrF|  | j¡ | jj 	| j
¡ d | _|  ¡  d S )Nry   )r#   r©  r-   rx   r  r‡   r.   r(   r‹   rÇ   r  r3   )r   r"   r   r   r   r«  ã
  s    

zLasso.onreleasec             C   s¦   |   |¡rd S | jd krd S |j| jkr,d S |jdkr:d S | j |j|jf¡ | j 	t
t| jŽ ƒ¡ | jr˜| j | j¡ | j | j¡ | j | jj¡ n
| j ¡  d S )Nr   )r#   r©  rM   r(   rv   r-   rx   r  r  rh  r¬  r   rö   r*   r  rü   r  r  r   r|   )r   r"   r   r   r   rñ   î
  s    


zLasso.onmove)NT)r   r   r   r   r   r«  rñ   r   r   r   r   r½  ¿
  s   
r½  )$r   r8  Znumbersr   Znumpyrt   r¨   r   r‹   r   Zpatchesr   r   r   Z
transformsr	   Úobjectr
   r   r'   r4   rW   r   r§   rÒ   rÚ   rí   r  r  rD  r`  rn  r¤  r¨  r­  r½  r   r   r   r   Ú<module>
   sL   &*z b   3  [s f ^;   2GW V