U
    e»{j¢�  ã                	   @   s²  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
z ddlZddlZddlZdZW n ek
rŒ   dZY nX ddlmZ ddlmZ ddlmZ d	d
dddddddg	ZdZG dd„ dƒZd6dd„Zdd	„ Zd7dd„Zdd„ Zdd„ Zdd„ Zdd œd!d
„Zd"d#„ Z d$d„ Z!d%d„ Z"G d&d'„ d'ƒZ#G d(d„ dƒZ$G d)d„ dƒZ%G d*d„ dƒZ&d8d-d„Z'G d.d/„ d/ƒZ(G d0d1„ d1ƒZ)G d2d3„ d3ƒZ*G d4d5„ d5ƒZ+dS )9z)
Utilities for console input and output.
é    NTF)Úconfé   )Úclassproperty)Ú
isiterableÚisattyÚcolor_printÚ
human_timeÚhuman_file_sizeÚProgressBarÚSpinnerÚprint_code_lineÚProgressBarOrSpinnerÚterminal_sizezutf-8c                   @   s@   e Zd ZdZedd„ ƒZedd„ ƒZedd„ ƒZedd	„ ƒZ	d
S )Ú_IPythonz5Singleton class given access to IPython streams, etc.c                 C   s*   zddl m} W n tk
r$   Y nX |S )Nr   )Úget_ipython)ÚIPythonr   ÚImportError)Úclsr   © r   úT/var/www/html/bwave/python/venv/lib/python3.8/site-packages/astropy/utils/console.pyr   4   s
    z_IPython.get_ipythonc                 C   sØ   t | dƒsÒd | _z|  ¡  W n tk
r2   Y d S X zddlm} W n† tk
rÊ   zddlm} W n` tk
rÄ   ddlm	} |d dkr”Y Y d S zddl
m} W n tk
r¾   Y Y Y d S X Y nX Y nX || _| jS )NÚ
_OutStreamr   )Ú	OutStream©Úversion_infoé   )Úhasattrr   r   Ú	NameErrorZipykernel.iostreamr   r   ZIPython.zmq.iostreamr   r   ZIPython.kernel.zmq.iostream)r   r   r   r   r   r   r   <   s*    
z_IPython.OutStreamc                 C   sB   t | dƒs<zddlm} W n tk
r4   d | _Y nX || _| jS )NÚ_ipyior   )Úio)r   ZIPython.utilsr   r   r   )r   r   r   r   r   ÚipyioY   s    
z_IPython.ipyioc                 C   s   t | j|ƒS ©N)Úgetattrr   )r   Ústreamr   r   r   Ú
get_streamd   s    z_IPython.get_streamN)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   Úclassmethodr#   r   r   r   r   r   1   s   



r   c                 C   s   | r
d}nd}t t|ƒ}|S )a_  
    This utility function contains the logic to determine what streams to use
    by default for standard out/err.

    Typically this will just return `sys.stdout`, but it contains additional
    logic for use in IPython on Windows to determine the correct stream to use
    (usually ``IPython.util.io.stdout`` but only if sys.stdout is a TTY).
    ÚstderrÚstdout)r!   Úsys)r)   r"   Z
sys_streamr   r   r   Ú_get_stdouti   s
    

r,   c                 C   s¢   t  ¡ jdkst ¡ jdkr dS t| dƒr2|  ¡ S tjdksHt	| tjƒsLdS t
| ddƒdkr`dS t| d	ƒržzd
dlm} W n tk
r�   Y dS X t	| j|ƒS dS )zÄ
    Returns `True` if ``file`` is a tty.

    Most built-in Python file-like objects have an `isatty` member,
    but some user-defined types may not, so this assumes those are not
    ttys.
    ÚMainProcessÚ
MainThreadFr   NÚnamer*   Tr"   r   )ÚConsole)ÚmultiprocessingÚcurrent_processr/   Ú	threadingÚcurrent_threadr   r   r   r   Ú
isinstancer!   Zpyreadline.consoler0   r   r"   )ÚfileZPyreadlineConsoler   r   r   r   |   s$    	ÿþ

c                 C   s  | dkrt ƒ } zxt ddddd¡}t | tj|¡}t d|¡\}}}}|dkrV|d8 }|dkrf|d8 }|dksv|dkr~tdƒ‚||fW S  tk
�r
   z&t	t
j d	¡ƒt	t
j d
¡ƒfW  Y S  tk
�r   tj}tj}|dkrèd}|dkrôd}||f Y  Y S X Y nX dS )zõ
    Returns a tuple (height, width) containing the height and width of
    the terminal.

    This function will look for the width in height in multiple areas
    before falling back on the width and height in astropy's
    configuration.
    NZHHHHr   é   é   é
   r   zunable to get terminal sizeÚLINESÚCOLUMNSé   éP   )r,   ÚstructÚpackÚfcntlZioctlÚtermiosÚ
TIOCGWINSZÚunpackÚ	ExceptionÚintÚosÚenvironÚgetÚ	TypeErrorr   Ú	max_linesÚ	max_width)r6   ÚsÚxÚlinesÚwidthZxpixelsZypixelsr   r   r   r   ¦   s0    

&c                 C   s^   ddddddddd	d
ddddddddœ}t jdkr@tjdkr@| S | |d	¡}d|› d| › d�S )ag  
    Returns a string wrapped in ANSI color codes for coloring the
    text in a terminal::

        colored_text = color_text('Here is a message', 'blue')

    This won't actually effect the text until it is printed to the
    terminal.

    Parameters
    ----------
    text : str
        The string to return, bounded by the color codes.
    color : str
        An ANSI terminal color name. Must be one of:
        black, red, green, brown, blue, magenta, cyan, lightgrey,
        default, darkgrey, lightred, lightgreen, yellow, lightblue,
        lightmagenta, lightcyan, white, or '' (the empty string).
    z0;30z0;31z0;32z0;33z0;34z0;35z0;36z0;37z0;39z1;30z1;31z1;32z1;33z1;34z1;35z1;36z1;37)ÚblackÚredÚgreenZbrownÚblueÚmagentaÚcyanZ	lightgreyÚdefaultÚdarkgreyZlightredZ
lightgreenÚyellowZ	lightblueZlightmagentaZ	lightcyanÚwhiteÚwin32Nz[Úmz[0m)r+   Úplatformr   r   rH   )ÚtextÚcolorZcolor_mappingZ
color_coder   r   r   Ú_color_textÎ   s,    ïr_   c                 C   s`   t  ¡ }z4z|  |¡W W S  tk
r0   t}Y nX |  |¡W S  tk
rZ   |  d¡ Y S X dS )zûDecode the supplied byte string using the preferred encoding
    for the locale (`locale.getpreferredencoding`) or, if the default encoding
    is invalid, fall back first on utf-8, then on latin-1 if the message cannot
    be decoded with utf-8.
    úlatin-1N)ÚlocaleÚgetpreferredencodingÚdecodeÚLookupErrorÚ_DEFAULT_ENCODINGÚUnicodeDecodeError)rL   Úencr   r   r   Ú_decode_preferred_encodingþ   s    
rh   c                 C   s°   z|| ƒ |W S  t k
r"   Y nX t ¡ }zt |¡}W n tk
rX   t t¡}Y nX ||ƒ}|j}z|| ƒ |W S  t k
r¢   t d¡}||ƒ}|j}Y nX || ƒ |S )zëWrite the supplied string with the given write function like
    ``write(s)``, but use a writer for the locale's preferred encoding in case
    of a UnicodeEncodeError.  Failing that attempt to write with 'utf-8' or
    'latin-1'.
    r`   )ÚUnicodeEncodeErrorra   rb   ÚcodecsÚ	getwriterrd   re   Úwrite)rL   rl   Úfileobjrg   ÚWriterÚfr   r   r   Ú_write_with_fallback  s*    
rp   Ú
)Úendc                 O   s¸   |  dtƒ ¡}|j}t|ƒr†tjr†tdt|ƒdƒD ]H}|| }|d t|ƒkrTd}n||d  }|rnt||ƒ}t	|||ƒ}q2|| ƒ n.tdt|ƒdƒD ]}|| }||ƒ q–|| ƒ dS )a  
    Prints colors and styles to the terminal uses ANSI escape
    sequences.

    ::

       color_print('This is the color ', 'default', 'GREEN', 'green')

    Parameters
    ----------
    positional args : str
        The positional arguments come in pairs (*msg*, *color*), where
        *msg* is the string to display and *color* is the color to
        display it in.

        *color* is an ANSI terminal color name.  Must be one of:
        black, red, green, brown, blue, magenta, cyan, lightgrey,
        default, darkgrey, lightred, lightgreen, yellow, lightblue,
        lightmagenta, lightcyan, white, or '' (the empty string).

    file : writable file-like, optional
        Where to write to.  Defaults to `sys.stdout`.  If file is not
        a tty (as determined by calling its `isatty` member, if one
        exists), no coloring will be included.

    end : str, optional
        The ending of the message.  Defaults to ``\n``.  The end will
        be printed after resetting any color or font state.
    r6   r   é   r   Ú N)
rH   r,   rl   r   r   Z	use_colorÚrangeÚlenr_   rp   )rr   ÚargsÚkwargsr6   rl   ÚiÚmsgr^   r   r   r   r   3  s     


c                 C   s   t  dd| ¡S )z2
    Remove ANSI color codes from the string.
    z\[([0-9]+)(;[0-9]+)*mrt   )ÚreÚsub)rL   r   r   r   Ústrip_ansi_codesn  s    r}   c                 C   sŒ   ddddddg}t | ƒ} | dk r.d| d	›d
�S tt|ƒd ƒD ]H}|| \}}||d  \}}| |kr>d | | || | | |¡  S q>dS )a  
    Returns a human-friendly time string that is always exactly 6
    characters long.

    Depending on the number of seconds given, can be one of::

        1w 3d
        2d 4h
        1h 5m
        1m 4s
          15s

    Will be in color if console coloring is turned on.

    Parameters
    ----------
    seconds : int
        The number of seconds to represent

    Returns
    -------
    time : str
        A human-friendly representation of the given number of seconds
        that is always exactly 6 characters.
    )Úyi âß)Úwi€:	 )Údi€Q )Úhi  )r[   é<   )rL   r   r‚   z   Z2drL   r   z{:2d}{}{:2d}{}z  ~inf)rE   ru   rv   Úformat)ÚsecondsÚunitsry   Zunit1Zlimit1Zunit2Zlimit2r   r   r   r   u  s*    ú	  
 ÿ
c                 C   sÜ   t | dƒr&ddlm} | | |j¡j} d}| dkr8d}ntt t 	| ¡t 	d¡ ¡ƒ}|dkrdd}n|| }tt 
d|¡ƒ}| | }t|ƒ}|dkr¨|d	| d
¡… }n&|d d
krÂ|d	d… }n|d	d… }|d›|› �S )a–  
    Returns a human-friendly string representing a file size
    that is 2-4 characters long.

    For example, depending on the number of bytes given, can be one
    of::

        256b
        64k
        1.1G

    Parameters
    ----------
    size : int
        The size of the file (in bytes)

    Returns
    -------
    size : str
        A human-friendly representation of the size of the file
    Úunitr   )r…   z	 kMGTPEZYiè  é   ú?ú NÚ.rs   é   z>3s)r   Úastropyr…   ZQuantityÚbyteÚvaluerE   ÚmathÚfloorÚlogÚpowÚstrÚindex)ÚsizeÚuÚsuffixesZ	num_scaleÚsuffixrŽ   Z	str_valuer   r   r   r	   ¦  s&    
c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )Ú_mapfuncz:
    A function wrapper to support ProgressBar.map().
    c                 C   s
   || _ d S r    ©Z_func)ÚselfÚfuncr   r   r   Ú__init__Ý  s    z_mapfunc.__init__c                 C   s   |\}}||   |¡fS r    rš   )r›   Zi_argry   Úargr   r   r   Ú__call__à  s    z_mapfunc.__call__N©r$   r%   r&   r'   r�   rŸ   r   r   r   r   r™   Ø  s   r™   c                   @   sˆ   e Zd ZdZddd„Zddd„Zdd	„ Zd
d„ Zdd„ Zdd„ Z	ddd„Z
d dd„Zd!dd„Zd"dd„Zed#dd„ƒZed$dd„ƒZdS )%r
   aR  
    A class to display a progress bar in the terminal.

    It is designed to be used either with the ``with`` statement::

        with ProgressBar(len(items)) as bar:
            for item in enumerate(items):
                bar.update()

    or as a generator::

        for item in ProgressBar(items):
            item.process()
    FNc                 C   sø   |dkrt ƒ }|s*t|ƒs*| j| _d| _nd| _t|ƒrNt|ƒ| _t|ƒ| _	n<zt
|ƒ| _	W n tk
rx   tdƒ‚Y nX tt| j	ƒƒ| _|| _t ¡ | _t| j	ƒ| _|| _d| _|sêtoÂ| j ¡ | _|  ¡  | jrêt tj| j¡ d| _|  d¡ dS )aÄ  
        Parameters
        ----------
        total_or_items : int or sequence
            If an int, the number of increments in the process being
            tracked.  If a sequence, the items to iterate over.

        ipython_widget : bool, optional
            If `True`, the progress bar will display as an IPython
            notebook widget.

        file : writable file-like, optional
            The file to write the progress bar to.  Defaults to
            `sys.stdout`.  If ``file`` is not a tty (as determined by
            calling its `isatty` member, if any, or special case hacks
            to detect the IPython console), the progress bar will be
            completely silent.
        NTFz&First argument must be int or sequencer   )r,   r   Ú_silent_updateÚupdateÚ_silentr   ÚiterÚ_itemsrv   Ú_totalrE   rI   ru   Ú_fileÚtimeÚ_start_timer	   Ú_human_totalÚ_ipython_widgetÚ_signal_setÚ_CAN_RESIZE_TERMINALZ_should_handle_resizeÚ_handle_resizeÚsignalÚSIGWINCH)r›   Ztotal_or_itemsÚipython_widgetr6   r   r   r   r�   õ  s4    

zProgressBar.__init__c                 C   s   t | jƒd }|d | _d S )Nr   é%   )r   r§   Ú_bar_length)r›   ÚsignumÚframeÚterminal_widthr   r   r   r®   +  s    zProgressBar._handle_resizec                 C   s   | S r    r   ©r›   r   r   r   Ú	__enter__/  s    zProgressBar.__enter__c                 C   sJ   | j sF|d kr|  | j¡ | j d¡ | j ¡  | jrFt tjtj	¡ d S )Nrq   )
r£   r¢   r¦   r§   rl   Úflushr¬   r¯   r°   ÚSIG_DFL©r›   Úexc_typeÚ	exc_valueÚ	tracebackr   r   r   Ú__exit__2  s    
zProgressBar.__exit__c                 C   s   | S r    r   r·   r   r   r   Ú__iter__;  s    zProgressBar.__iter__c                 C   sD   zt | jƒ}W n$ tk
r2   |  d d d ¡ ‚ Y nX |  ¡  |S d S r    )Únextr¥   ÚStopIterationr¿   r¢   )r›   Úrvr   r   r   Ú__next__>  s    zProgressBar.__next__c                 C   s8   |dkr| j d }|| _ | jr*|  |¡ n
|  |¡ dS )zN
        Update progress bar via the console or notebook accordingly.
        Nr   )Z_current_valuer«   Ú_update_ipython_widgetÚ_update_console©r›   rŽ   r   r   r   r¢   H  s    
zProgressBar.updatec                 C   sR  | j dkrd}nt|ƒt| j ƒ }| j}|j}|dkrBt| jƒ}ntt| jƒ| ƒ}|dƒ td| d|dd� || jk r td	d
|dd� |d| j| d  ƒ |dƒ || j krÆt ¡ | j }d}n0|dkrØd}d}nt ¡ | j d|  | }d}|dt	|ƒd›d| j
d›�ƒ |d|d›d�ƒ ||ƒ |dk	�rD|t|ƒƒ | j ¡  dS )zq
        Update the progress bar to the given value (out of the total
        given to the constructor).
        r   g      ð?r   z|ú=rS   rt   ©r6   rr   ú>rR   ú-ú|z     Nz ETA r‰   z>4sú/ú (ú>6.2%ú))r¦   Úfloatr§   rl   rE   r³   r   r¨   r©   r	   rª   r   r¹   )r›   rŽ   Úfracr6   rl   Zbar_fillÚtÚprefixr   r   r   rÆ   X  s8    



zProgressBar._update_consolec                 C   s¢   t | dƒsvddlm} |d dk r:ddlm} | ¡ | _nt ¡  ddl	m} | 
¡ | _ddlm} || jƒ d| j_|| j }|d | j_d|d	›d
�| j_dS )z«
        Update the progress bar to the given value (out of a total
        given to the constructor).

        This method is for use in the IPython notebook 2+.
        Ú_widgetr   r   r   )Úwidgets)Údisplayéd   rÎ   rÏ   rÐ   N)r   r   r   ZIPython.htmlrÖ   ZFloatProgressWidgetrÕ   r   r   Ú
ipywidgetsZFloatProgressÚIPython.displayr×   rŽ   r¦   Údescription)r›   rŽ   r   rÖ   r×   rÒ   r   r   r   rÅ   �  s    




z"ProgressBar._update_ipython_widgetc                 C   s   d S r    r   rÇ   r   r   r   r¡   ¢  s    zProgressBar._silent_updaterØ   c           
   	   C   sP   |rt |ƒ}tt|ƒƒ}| j|||||||d�}|rLtt|ƒŽ \}	}t|ƒ}|S )a¸  Map function over items while displaying a progress bar with percentage complete.

        The map operation may run in arbitrary order on the items, but the results are
        returned in sequential order.

        ::

            def work(i):
                print(i)

            ProgressBar.map(work, range(50))

        Parameters
        ----------
        function : function
            Function to call for each step

        items : sequence
            Sequence where each element is a tuple of arguments to pass to
            *function*.

        multiprocess : bool, int, optional
            If `True`, use the `multiprocessing` module to distribute each task
            to a different processor core. If a number greater than 1, then use
            that number of cores.

        ipython_widget : bool, optional
            If `True`, the progress bar will display as an IPython
            notebook widget.

        file : writable file-like, optional
            The file to write the progress bar to.  Defaults to
            `sys.stdout`.  If ``file`` is not a tty (as determined by
            calling its `isatty` member, if any), the scrollbar will
            be completely silent.

        step : int, optional
            Update the progress bar at least every *step* steps (default: 100).
            If ``multiprocess`` is `True`, this will affect the size
            of the chunks of ``items`` that are submitted as separate tasks
            to the process pool.  A large step size may make the job
            complete faster if ``items`` is very long.

        multiprocessing_start_method : str, optional
            Useful primarily for testing; if in doubt leave it as the default.
            When using multiprocessing, certain anomalies occur when starting
            processes with the "spawn" method (the only option on Windows);
            other anomalies occur with the "fork" method (the default on
            Linux).
        )Úmultiprocessr6   Ústepr±   Úmultiprocessing_start_method)r™   ÚlistÚ	enumerateÚmap_unorderedÚzipÚsorted)
r   ÚfunctionÚitemsrÜ   r6   rÝ   r±   rÞ   ÚresultsÚ_r   r   r   Úmap¥  s     >ù
zProgressBar.mapc              
      s<  ddl m}m}	 g }
|dkr"tƒ }| t|ƒ||d��þ}|jrB|}n&tttt|ƒƒ|j	 ƒdƒ}t
||ƒ}|rt|dk r¬t|ƒD ],\}}|
 ˆ |ƒ¡ || dkr|| |¡ q|n‚t |¡}t|d�}|f d|dk	rÖt|ƒndi|—Ž�F‰t|	‡ ‡fd	d
„|D ƒƒƒD ]"\}}| |¡ |
 | ¡ ¡ �q W 5 Q R X W 5 Q R X |
S )aò  Map function over items, reporting the progress.

        Does a `map` operation while displaying a progress bar with
        percentage complete. The map operation may run on arbitrary order
        on the items, and the results may be returned in arbitrary order.

        ::

            def work(i):
                print(i)

            ProgressBar.map(work, range(50))

        Parameters
        ----------
        function : function
            Function to call for each step

        items : sequence
            Sequence where each element is a tuple of arguments to pass to
            *function*.

        multiprocess : bool, int, optional
            If `True`, use the `multiprocessing` module to distribute each task
            to a different processor core. If a number greater than 1, then use
            that number of cores.

        ipython_widget : bool, optional
            If `True`, the progress bar will display as an IPython
            notebook widget.

        file : writable file-like, optional
            The file to write the progress bar to.  Defaults to
            `sys.stdout`.  If ``file`` is not a tty (as determined by
            calling its `isatty` member, if any), the scrollbar will
            be completely silent.

        step : int, optional
            Update the progress bar at least every *step* steps (default: 100).
            If ``multiprocess`` is `True`, this will affect the size
            of the chunks of ``items`` that are submitted as separate tasks
            to the process pool.  A large step size may make the job
            complete faster if ``items`` is very long.

        multiprocessing_start_method : str, optional
            Useful primarily for testing; if in doubt leave it as the default.
            When using multiprocessing, certain anomalies occur when starting
            processes with the "spawn" method (the only option on Windows);
            other anomalies occur with the "fork" method (the default on
            Linux).
        r   )ÚProcessPoolExecutorÚas_completedN)r±   r6   r   )Z
mp_contextÚmax_workersTc                 3   s   | ]}ˆ  ˆ |¡V  qd S r    )Zsubmit)Ú.0Úitem©rä   Úpr   r   Ú	<genexpr>T  s     z,ProgressBar.map_unordered.<locals>.<genexpr>)Úconcurrent.futuresré   rê   r,   rv   r«   ÚmaxrE   rÑ   r³   Úminrà   Úappendr¢   r1   Zget_contextÚdictÚresult)r   rä   rå   rÜ   r6   rÝ   r±   rÞ   ré   rê   ræ   ÚbarÚ	chunksizeZdefault_stepry   rí   Úctxrx   ro   r   rî   r   rá   ÷  s8    @


þüÿ
&zProgressBar.map_unordered)FN)NN)N)N)N)N)FNrØ   FN)FNrØ   FN)r$   r%   r&   r'   r�   r®   r¸   r¿   rÀ   rÄ   r¢   rÆ   rÅ   r¡   r(   rè   rá   r   r   r   r   r
   å  s2   
6
	


)
!
     øQ     øc                   @   s\   e Zd Zd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d„Zdd„ ZdS )r   zö
    A class to display a spinner in the terminal.

    It is designed to be used with the ``with`` statement::

        with Spinner("Reticulating splines", "green") as s:
            for item in enumerate(items):
                s.update()
    u   â—“â—‘â—’â—�z-/|\rV   Nr   c                 C   st   |dkrt ƒ }|| _|| _|| _|| _|dkrBtjr<| j}n| j}|| _	t
|ƒ | _| jrf|  ¡ | _n
|  ¡ | _dS )aw  
        Parameters
        ----------
        msg : str
            The message to print

        color : str, optional
            An ANSI terminal color name.  Must be one of: black, red,
            green, brown, blue, magenta, cyan, lightgrey, default,
            darkgrey, lightred, lightgreen, yellow, lightblue,
            lightmagenta, lightcyan, white.

        file : writable file-like, optional
            The file to write the spinner to.  Defaults to
            `sys.stdout`.  If ``file`` is not a tty (as determined by
            calling its `isatty` member, if any, or special case hacks
            to detect the IPython console), the spinner will be
            completely silent.

        step : int, optional
            Only update the spinner every *step* steps

        chars : str, optional
            The character sequence to use for the spinner
        N)r,   Ú_msgÚ_colorr§   Ú_stepr   Úunicode_outputÚ_default_unicode_charsÚ_default_ascii_charsÚ_charsr   r£   Ú_silent_iteratorÚ_iterÚ	_iterator)r›   rz   r^   r6   rÝ   Úcharsr   r   r   r�   j  s    zSpinner.__init__c                 c   sÎ   | j }d}| j}|j}|j}d}|dƒ t| j| j|dd� |dƒ z&|r\t|| ||ƒ}n||| ƒ W n* tk
r”   | j	}||| ƒ d}Y nX |ƒ  d V  t
| jƒD ]
}d V  q¬|d t|ƒ }q d S )	Nr   Túrt   rÉ   r‰   Fr   )r   r§   rl   r¹   r   rú   rû   rp   ÚUnicodeErrorrÿ   ru   rü   rv   )r›   r  r”   r6   rl   r¹   Ztry_fallbackry   r   r   r   r  š  s,    
zSpinner._iteratorc                 C   s   | S r    r   r·   r   r   r   r¸   ¹  s    zSpinner.__enter__c                 C   sd   | j }|j}|j}| js4|dƒ t| j| j|dd� |d krLtdd|d� ntdd|d� |ƒ  d S )	Nr  rt   rÉ   z [Done]rR   ©r6   z	 [Failed]rQ   )r§   rl   r¹   r£   r   rú   rû   )r›   r¼   r½   r¾   r6   rl   r¹   r   r   r   r¿   ¼  s    zSpinner.__exit__c                 C   s   | S r    r   r·   r   r   r   rÀ   Ê  s    zSpinner.__iter__c                 C   s   t | jƒ d S r    )rÁ   r  r·   r   r   r   rÄ   Í  s    zSpinner.__next__c                 C   s   t | ƒ dS )zÅUpdate the spin wheel in the terminal.

        Parameters
        ----------
        value : int, optional
            Ignored (present just for compatibility with `ProgressBar.update`).

        N)rÁ   rÇ   r   r   r   r¢   Ð  s    
zSpinner.updatec                 c   s,   t | j| j| jdd� | j ¡  d V  q d S )Nrt   rÉ   )r   rú   rû   r§   r¹   r·   r   r   r   r  Ü  s    
zSpinner._silent_iterator)rV   Nr   N)N)r$   r%   r&   r'   rþ   rÿ   r�   r  r¸   r¿   rÀ   rÄ   r¢   r  r   r   r   r   r   \  s   

0
c                   @   s2   e Zd ZdZddd„Zdd„ Zdd	„ Zd
d„ ZdS )r   aü  
    A class that displays either a `ProgressBar` or `Spinner`
    depending on whether the total size of the operation is
    known or not.

    It is designed to be used with the ``with`` statement::

        if file.has_length():
            length = file.get_length()
        else:
            length = None
        bytes_read = 0
        with ProgressBarOrSpinner(length) as bar:
            while file.read(blocksize):
                bytes_read += blocksize
                bar.update(bytes_read)
    rV   Nc                 C   s\   |dkrt ƒ }|dkst|ƒs6d| _t|||d�| _n"d| _t|||d� t||d�| _dS )aç  
        Parameters
        ----------
        total : int or None
            If an int, the number of increments in the process being
            tracked and a `ProgressBar` is displayed.  If `None`, a
            `Spinner` is displayed.

        msg : str
            The message to display above the `ProgressBar` or
            alongside the `Spinner`.

        color : str, optional
            The color of ``msg``, if any.  Must be an ANSI terminal
            color name.  Must be one of: black, red, green, brown,
            blue, magenta, cyan, lightgrey, default, darkgrey,
            lightred, lightgreen, yellow, lightblue, lightmagenta,
            lightcyan, white.

        file : writable file-like, optional
            The file to write the to.  Defaults to `sys.stdout`.  If
            ``file`` is not a tty (as determined by calling its `isatty`
            member, if any), only ``msg`` will be displayed: the
            `ProgressBar` or `Spinner` will be silent.
        NT)r^   r6   Fr  )r,   r   Z_is_spinnerr   Ú_objr   r
   )r›   Útotalrz   r^   r6   r   r   r   r�   ÷  s    zProgressBarOrSpinner.__init__c                 C   s   | S r    r   r·   r   r   r   r¸     s    zProgressBarOrSpinner.__enter__c                 C   s   | j  |||¡S r    )r  r¿   r»   r   r   r   r¿      s    zProgressBarOrSpinner.__exit__c                 C   s   | j  |¡ dS )zp
        Update the progress bar to the given value (out of the total
        given to the constructor.
        N)r  r¢   rÇ   r   r   r   r¢   #  s    zProgressBarOrSpinner.update)rV   N)r$   r%   r&   r'   r�   r¸   r¿   r¢   r   r   r   r   r   ä  s
   
&é   éF   c           
      C   sT  |dkrt ƒ }tjrd}nd}|j}|dk	rb|t| ƒkr@tdƒ‚| d|…  d¡}|||d  7 }|  d¡} |  dd| ¡} |dk	ræ||kræt	|d	 t| ƒ| ƒ}|| }	| |	t|ƒ d… } |t|ƒ8 }|}||	8 }t
|d
|dd� t| ƒ|k�r|| d|t|ƒ … ƒ t
|d
|d� n|| ƒ |dƒ |dk	�rP|d| ƒ t
dd|d� dS )ux  
    Prints a line of source code, highlighting a particular character
    position in the line.  Useful for displaying the context of error
    messages.

    If the line is more than ``width`` characters, the line is truncated
    accordingly and 'â€¦' characters are inserted at the front and/or
    end.

    It looks like this::

        there_is_a_syntax_error_here :
                                     ^

    Parameters
    ----------
    line : unicode
        The line of code to display

    col : int, optional
        The character in the line to highlight.  ``col`` must be less
        than ``len(line)``.

    file : writable file-like, optional
        Where to write to.  Defaults to `sys.stdout`.

    tabwidth : int, optional
        The number of spaces per tab (``'\t'``) character.  Default
        is 8.  All tabs will be converted to spaces to ensure that the
        caret lines up with the correct column.

    width : int, optional
        The width of the display, beyond which the line will be
        truncated.  Defaults to 70 (this matches the default in the
        standard library's `textwrap` module).
    Nu   â€¦z...z%col must be less the the line length.ú	r   rq   r‰   rs   rW   rt   rÉ   r  ú^rQ   )r,   r   rý   rl   rv   Ú
ValueErrorÚcountÚrstripÚreplaceró   r   )
ÚlineÚcolr6   ZtabwidthrO   Úellipsisrl   ZntabsZnew_colÚoffsetr   r   r   r   +  s:    &

c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )ÚGetchz|Get a single character from standard input without screen echo.

    Returns
    -------
    char : str (one character)
    c                 C   sT   zt ƒ | _W nB tk
rN   ztƒ | _W n  ttfk
rH   tƒ | _Y nX Y nX d S r    )Ú_GetchWindowsÚimplr   Ú_GetchMacCarbonÚAttributeErrorÚ
_GetchUnixr·   r   r   r   r�   ˆ  s    zGetch.__init__c                 C   s   |   ¡ S r    )r  r·   r   r   r   rŸ   ‘  s    zGetch.__call__Nr    r   r   r   r   r  €  s   	r  c                   @   s   e Zd Zdd„ Zdd„ ZdS )r  c                 C   s   dd l }dd l}dd l}d S ©Nr   )r+   rA   Útty)r›   r+   rA   r  r   r   r   r�   –  s    z_GetchUnix.__init__c                 C   sd   dd l }dd l}dd l}|j ¡ }| |¡}z | |j ¡ ¡ |j 	d¡}W 5 | ||j|¡ X |S )Nr   r   )
r+   rA   r  ÚstdinÚfilenoÚ	tcgetattrÚ	tcsetattrÚ	TCSADRAINZsetrawÚread)r›   r+   rA   r  ÚfdZold_settingsÚchr   r   r   rŸ   ž  s    

z_GetchUnix.__call__N©r$   r%   r&   r�   rŸ   r   r   r   r   r  •  s   r  c                   @   s   e Zd Zdd„ Zdd„ ZdS )r  c                 C   s   dd l }d S r  )Úmsvcrt©r›   r'  r   r   r   r�   ®  s    z_GetchWindows.__init__c                 C   s   dd l }| ¡ S r  )r'  Zgetchr(  r   r   r   rŸ   ±  s    z_GetchWindows.__call__Nr&  r   r   r   r   r  ­  s   r  c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )r  zô
    A function which returns the current ASCII key that is down;
    if no ASCII key is down, the null string is returned.  The
    page http://www.mactech.com/macintosh-c/chap02-1.html was
    very helpful in figuring out how to do this.
    c                 C   s   dd l }|j d S r  )ÚCarbonÚEvt)r›   r)  r   r   r   r�   ¿  s    z_GetchMacCarbon.__init__c                 C   sJ   dd l }|j d¡d dkr dS |j d¡d \}}}}}t|d@ ƒS d S )Nr   r
  rt   r   éÿ   )r)  r*  Z
EventAvailZGetNextEventÚchr)r›   r)  Úwhatrz   ÚwhenÚwhereÚmodr   r   r   rŸ   Ä  s
    z_GetchMacCarbon.__call__Nr    r   r   r   r   r  ·  s   r  )F)N)NNr
  r  ),r'   rj   ra   r�   r1   rF   r{   r>   r+   r3   r¨   r@   r¯   rA   r­   r   rŒ   r   Z
decoratorsr   Úmiscr   Ú__all__re   r   r,   r   r   r_   rh   rp   r   r}   r   r	   r™   r
   r   r   r   r  r  r  r  r   r   r   r   Ú<module>   sl   
÷8
*
(0#;12  y 	G
U
