U
    .eA8                     @  s  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZmZmZmZmZmZmZmZmZ ddlmZ ddlmZ ddlmZmZmZ ddlmZmZmZ dd	l m!Z! dd
l"m#Z# ddl$m%Z% ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z;m<Z< dgZ=e%Z>e?eddZ@dddddZAedZBG dd dZCG dd de/ZDedd d!ZEG d"d# d#eeE ZFdS )$z
Progress bar implementation on top of prompt_toolkit.

::

    with ProgressBar(...) as pb:
        for item in pb(data):
            ...
    )annotationsN)	CallableGenericIterableIteratorSequenceSizedTextIOTypeVarcast)Application)get_app_session)	Conditionis_donerenderer_height_is_known)AnyFormattedTextStyleAndTextTuplesto_formatted_text)Input)KeyBindings)KeyPressEvent)ConditionalContainerFormattedTextControlHSplitLayoutVSplitWindow)	UIContent	UIControl)AnyDimensionD)
ColorDepthOutput)	BaseStyle)in_main_thread   )	Formattercreate_default_formattersProgressBarSIGWINCHCallable[[], None] | Noner   )cancel_callbackreturnc                   sJ   t  }|dddddd} dk	rF|dddd fd	d
}|S )zu
    Key bindings handled by the progress bar.
    (The main thread is not supposed to handle any key bindings.)
    zc-lENone)eventr,   c                 S  s   | j j  d S N)appZrendererclearr/    r4   N/tmp/pip-unpacked-wheel-_x9ru1vw/prompt_toolkit/shortcuts/progress_bar/base.py_clearH   s    z#create_key_bindings.<locals>._clearNzc-cc                   s    dk	st    dS )zMKill the 'body' of the progress bar, but only if we run from the main thread.N)AssertionErrorr3   r+   r4   r5   
_interruptN   s    z'create_key_bindings.<locals>._interrupt)r   add)r+   kbr6   r9   r4   r8   r5   create_key_bindingsA   s    r<   _Tc                   @  sx   e Zd ZdZd"dddddddd	d
dddddZd dddZdddddZd#ddddddddZddd d!ZdS )$r(   a.  
    Progress bar context manager.

    Usage ::

        with ProgressBar(...) as pb:
            for item in pb(data):
                ...

    :param title: Text to be displayed above the progress bars. This can be a
        callable or formatted text as well.
    :param formatters: List of :class:`.Formatter` instances.
    :param bottom_toolbar: Text to be displayed in the bottom toolbar. This
        can be a callable or formatted text.
    :param style: :class:`prompt_toolkit.styles.BaseStyle` instance.
    :param key_bindings: :class:`.KeyBindings` instance.
    :param cancel_callback: Callback function that's called when control-c is
        pressed by the user. This can be used for instance to start "proper"
        cancellation if the wrapped code supports it.
    :param file: The file object used for rendering, by default `sys.stderr` is used.

    :param color_depth: `prompt_toolkit` `ColorDepth` instance.
    :param output: :class:`~prompt_toolkit.output.Output` instance.
    :param input: :class:`~prompt_toolkit.input.Input` instance.
    Nr   zSequence[Formatter] | NonezBaseStyle | NonezKeyBindings | Noner*   zTextIO | NonezColorDepth | NonezOutput | NonezInput | Noner.   )title
formattersbottom_toolbarstylekey_bindingsr+   filecolor_depthoutputinputr,   c                 C  s   || _ |pt | _|| _g | _|| _|| _|| _| jd krTt rTdddd}|| _|| _	|	pdt
 j| _|
prt
 j| _d | _d| _t | _d S )Nr.   r,   c                   S  s   t t  tj d S r0   )oskillgetpidsignalSIGINTr4   r4   r4   r5   !keyboard_interrupt_to_main_thread   s    z?ProgressBar.__init__.<locals>.keyboard_interrupt_to_main_threadF)r>   r'   r?   r@   countersrA   rB   r+   r$   rD   r   rE   rF   _threadZ_has_sigwinch	threadingEvent_app_started)selfr>   r?   r@   rA   rB   r+   rC   rD   rE   rF   rM   r4   r4   r5   __init__u   s     zProgressBar.__init__rG   c              
     s  t tt fdddddt fddd}t tt fddd	d
dddt t@ t fdd@ d}ddd fdd fdd jD }tdtt	|t
| fdddt |g j jd j j jd _dd fdd}t }tj|j|fd _ j   S )Nc                     s    j S r0   r>   r4   rS   r4   r5   <lambda>       z'ProgressBar.__enter__.<locals>.<lambda>r%   zclass:progressbar,title)heightrA   c                     s
    j d k	S r0   rU   r4   rV   r4   r5   rW      rX   )filterc                     s    j S r0   r@   r4   rV   r4   r5   rW      rX   zclass:bottom-toolbar.text)rA   zclass:bottom-toolbar)rA   rY   c                     s
    j d k	S r0   r[   r4   rV   r4   r5   rW      rX   r&   r   )	formatterr,   c                   s   | j  dS )N)progress_bar)Z	get_width)r\   rV   r4   r5   width_for_formatter   s    z2ProgressBar.__enter__.<locals>.width_for_formatterc                   s*   g | ]"}t t | jt|d qS ))contentwidth)r   _ProgressControlr+   	functoolspartial).0frS   r^   r4   r5   
<listcomp>   s
   
z)ProgressBar.__enter__.<locals>.<listcomp>g?c                     s   t t jt jdS )N)	preferredmax)r    lenrN   r4   rV   r4   r5   rW      s    )rY   g333333?)Zmin_redraw_intervalZlayoutrA   rB   Zrefresh_intervalrD   rE   rF   r.   rG   c               
     sN   z j j jjd W n2 tk
rH }  zt  t|  W 5 d } ~ X Y nX d S )N)Zpre_run)r1   runrR   setBaseException	traceback	print_excprint)erV   r4   r5   rk      s
    z"ProgressBar.__enter__.<locals>.run)targetargs)r   r   r   r   r   r   r?   r   r   r   r   rA   rB   rD   rE   rF   r1   contextvarsZcopy_contextrP   Threadrk   rO   start)rS   Ztitle_toolbarr@   Zprogress_controlsrk   ctxr4   rf   r5   	__enter__   sj    	
 

zProgressBar.__enter__object)ar,   c                 G  sH   | j   | jjr0| jjd k	r0| jj| jj | jd k	rD| j  d S r0   )	rR   waitr1   Z
is_runningZloopZcall_soon_threadsafeexitrO   join)rS   rz   r4   r4   r5   __exit__   s
    

zProgressBar.__exit__ FzIterable[_T] | Nonebool
int | NonezProgressBarCounter[_T])datalabelremove_when_donetotalr,   c                 C  s"   t | ||||d}| j| |S )aL  
        Start a new counter.

        :param label: Title text or description for this progress. (This can be
            formatted text as well).
        :param remove_when_done: When `True`, hide this progress bar.
        :param total: Specify the maximum value if it can't be calculated by
            calling ``len``.
        )r   r   r   )ProgressBarCounterrN   append)rS   r   r   r   r   counterr4   r4   r5   __call__   s        zProgressBar.__call__c                 C  s   | j   d S r0   )r1   
invalidaterV   r4   r4   r5   r     s    zProgressBar.invalidate)
NNNNNNNNNN)Nr   FN)	__name__
__module____qualname____doc__rT   rx   r~   r   r   r4   r4   r4   r5   r(   Z   s(             $*M    c                   @  sR   e Zd ZdZdddddddZd	d	d
dddZddddZddddZdS )ra   z,
    User control for the progress bar.
    r(   r&   r*   r.   )r]   r\   r+   r,   c                 C  s   || _ || _t|| _d S r0   )r]   r\   r<   _key_bindings)rS   r]   r\   r+   r4   r4   r5   rT     s    z_ProgressControl.__init__intr   )r`   rY   r,   c              	     s~   g  | j jD ]J}z| j| j ||}W n  tk
rF   t  d}Y nX  t| qddd fdd}t	|t
 ddS )	NERRORr   r   )ir,   c                   s    |  S r0   r4   )r   itemsr4   r5   get_line.  s    z1_ProgressControl.create_content.<locals>.get_lineF)r   
line_countZshow_cursor)r]   rN   r\   formatrm   rn   ro   r   r   r   rj   )rS   r`   rY   prtextr   r4   r   r5   create_content"  s    
z_ProgressControl.create_contentr   rG   c                 C  s   dS )NTr4   rV   r4   r4   r5   is_focusable3  s    z_ProgressControl.is_focusabler   c                 C  s   | j S r0   )r   rV   r4   r4   r5   get_key_bindings6  s    z!_ProgressControl.get_key_bindingsN)r   r   r   r   rT   r   r   r   r4   r4   r4   r5   ra     s
   
ra   _CounterItemT)	covariantc                   @  s   e Zd ZdZd$ddddd	d
dddZddddZd
dddZeddddZej	dd
dddZeddddZ
e
j	dd
dddZ
eddddZedddd Zed!dd"d#ZdS )%r   zL
    An individual counter (A progress bar can have multiple counters).
    Nr   Fr(   zIterable[_CounterItem] | Noner   r   r   r.   )r]   r   r   r   r   r,   c                 C  s~   t j  | _d | _|| _|| _d| _|| _|| _d| _	|  |d krtzt
tt|| _W qz tk
rp   d | _Y qzX n|| _d S )Nr   F)datetimenow
start_time	stop_timer]   r   items_completedr   r   _donerj   r   r   r   	TypeError)rS   r]   r   r   r   r   r4   r4   r5   rT   B  s    zProgressBarCounter.__init__zIterator[_CounterItem]rG   c                 c  sF   | j d k	r:z$| j D ]}|V  |   qd| _W 5 d| _X ntdd S )NTz No data defined to iterate over.)r   stoppeditem_completeddoneNotImplementedError)rS   itemr4   r4   r5   __iter__\  s    




zProgressBarCounter.__iter__c                 C  s   |  j d7  _ | j  dS )z
        Start handling the next item.

        (Can be called manually in case we don't have a collection to loop through.)
        r%   N)r   r]   r   rV   r4   r4   r5   r   l  s    z!ProgressBarCounter.item_completedc                 C  s   | j S )a6  Whether a counter has been completed.

        Done counter have been stopped (see stopped) and removed depending on
        remove_when_done value.

        Contrast this with stopped. A stopped counter may be terminated before
        100% completion. A done counter has reached its 100% completion.
        )r   rV   r4   r4   r5   r   u  s    
zProgressBarCounter.done)valuer,   c                 C  s(   || _ || _|r$| jr$| jj|  d S r0   )r   r   r   r]   rN   removerS   r   r4   r4   r5   r     s    
c                 C  s
   | j dk	S )a  Whether a counter has been stopped.

        Stopped counters no longer have increasing time_elapsed. This distinction is
        also used to prevent the Bar formatter with unknown totals from continuing to run.

        A stopped counter (but not done) can be used to signal that a given counter has
        encountered an error but allows other counters to continue
        (e.g. download X of Y failed). Given how only done counters are removed
        (see remove_when_done) this can help aggregate failures from a large number of
        successes.

        Contrast this with done. A done counter has reached its 100% completion.
        A stopped counter may be terminated before 100% completion.
        N)r   rV   r4   r4   r5   r     s    zProgressBarCounter.stoppedc                 C  s"   |r| j stj | _ nd | _ d S r0   )r   r   r   r   r4   r4   r5   r     s    floatc                 C  s(   | j d krdS | jd t| j d S d S )Nr   d   r%   )r   r   ri   rV   r4   r4   r5   
percentage  s    
zProgressBarCounter.percentagezdatetime.timedeltac                 C  s*   | j dkrtj | j S | j | j S dS )zH
        Return how much time has been elapsed since the start.
        N)r   r   r   r   rV   r4   r4   r5   time_elapsed  s    
zProgressBarCounter.time_elapsedzdatetime.timedelta | Nonec                 C  sD   | j dks| jsdS | js | jr*tdS | jd| j  | j S dS )z7
        Timedelta representing the time left.
        Nr   r   )r   r   r   r   r   	timedeltar   rV   r4   r4   r5   	time_left  s
    
zProgressBarCounter.time_left)Nr   FN)r   r   r   r   rT   r   r   propertyr   setterr   r   r   r   r4   r4   r4   r5   r   =  s,       			r   )Gr   
__future__r   rt   r   rb   rH   rK   rP   rn   typingr   r   r   r   r   r   r	   r
   r   Zprompt_toolkit.applicationr   Z"prompt_toolkit.application.currentr   Zprompt_toolkit.filtersr   r   r   Zprompt_toolkit.formatted_textr   r   r   Zprompt_toolkit.inputr   Zprompt_toolkit.key_bindingr   Z(prompt_toolkit.key_binding.key_processorr   Zprompt_toolkit.layoutr   r   r   r   r   r   Zprompt_toolkit.layout.controlsr   r   Zprompt_toolkit.layout.dimensionr   r    Zprompt_toolkit.outputr!   r"   Zprompt_toolkit.stylesr#   Zprompt_toolkit.utilsr$   r?   r&   r'   __all__r-   getattrZ	_SIGWINCHr<   r=   r(   ra   r   r   r4   r4   r4   r5   <module>   sB   	,  :'