a
    õ£Ben4  ã                   @  sh  d Z ddlmZ ddlZddlZddlZddlmZ ddlmZm	Z	m
Z
mZ ddlmZmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZ ddlmZ ddlmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ dgZ0dddœdd„Z1dddœdd„Z2G dd„ dƒZ3G dd„ dƒZ4dddœd d!„Z5G d"d„ dƒZ6dS )#z
Telnet server.
é    )ÚannotationsN)Úget_running_loop)Ú	AwaitableÚCallableÚTextIOÚcast)Úcreate_app_sessionÚget_app)Úrun_in_terminal)ÚSize)ÚAnyFormattedTextÚto_formatted_text)Ú	PipeInputÚcreate_pipe_input)ÚVt100_Output)Úprint_formatted_text)Ú	BaseStyleÚ
DummyStyleé   )Úlogger)ÚDOÚECHOÚIACÚLINEMODEÚMODEÚNAWSÚSBÚSEÚSENDÚSUPPRESS_GO_AHEADÚTTYPEÚWILLÚTelnetProtocolParserÚTelnetServerÚintÚbytes)ÚnumberÚreturnc                 C  s
   t | fƒS ©N)r%   )r&   © r)   úg/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/prompt_toolkit/contrib/telnet/server.pyÚint2byte+   s    r+   úsocket.socketÚNone)Ú
connectionr'   c                 C  s¬   t  d¡ |  tt t ¡ |  tt t ¡ |  tt t t	 t
dƒ t t ¡ |  tt t ¡ |  tt t ¡ |  tt t ¡ |  tt t t t t ¡ d S )NzInitializing telnet connectionr   )r   ÚinfoÚsendr   r   r   r!   r   r   r   r+   r   r   r   r    r   ©r.   r)   r)   r*   Ú_initialize_telnet/   s    
&r2   c                   @  s€   e Zd ZdZddddœdd„Zdddœd	d
„Zddœdd„Zddœdd„Zddœdd„Ze	ddœdd„ƒZ
e	ddœdd„ƒZdS )Ú_ConnectionStdoutzk
    Wrapper around socket which provides `write` and `flush` methods for the
    Vt100_Output output.
    r,   Ústrr-   )r.   Úencodingr'   c                 C  s"   || _ || _d| _g | _d| _d S )NÚstrictF)Ú	_encodingÚ_connectionÚ_errorsÚ_bufferÚ_closed)Úselfr.   r5   r)   r)   r*   Ú__init__R   s
    z_ConnectionStdout.__init__©Údatar'   c                 C  s2   |  dd¡}| j |j| j| jd�¡ |  ¡  d S )NÚ
z
)Úerrors)Úreplacer:   ÚappendÚencoder7   r9   Úflush©r<   r?   r)   r)   r*   ÚwriteY   s    z_ConnectionStdout.writeÚbool©r'   c                 C  s   dS ©NTr)   ©r<   r)   r)   r*   Úisatty^   s    z_ConnectionStdout.isattyc              
   C  s\   z| j s| j d | j¡¡ W n2 tyP } zt d| ¡ W Y d }~n
d }~0 0 g | _d S )Nó    z"Couldn't send data over socket: %s)r;   r8   r0   Újoinr:   ÚOSErrorr   Úwarning)r<   Úer)   r)   r*   rE   a   s    $z_ConnectionStdout.flushc                 C  s
   d| _ d S rJ   )r;   rK   r)   r)   r*   Úclosej   s    z_ConnectionStdout.closec                 C  s   | j S r(   )r7   rK   r)   r)   r*   r5   m   s    z_ConnectionStdout.encodingc                 C  s   | j S r(   )r9   rK   r)   r)   r*   rA   q   s    z_ConnectionStdout.errorsN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r=   rG   rL   rE   rR   Úpropertyr5   rA   r)   r)   r)   r*   r3   L   s   	r3   c                   @  sš   e Zd ZdZ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„Zdddœdd„Zdddœdd„Z	dddœd d!„Z
ddœd"d#„Zd$S )&ÚTelnetConnectionz6
    Class that represents one Telnet connection.
    Tr,   ztuple[str, int]ú-Callable[[TelnetConnection], Awaitable[None]]r#   r4   úBaseStyle | Noner   rH   r-   )	ÚconnÚaddrÚinteractÚserverr5   ÚstyleÚvt100_inputÚ
enable_cprr'   c	                   sÜ   |ˆ_ |ˆ_|ˆ_|ˆ_|ˆ_|ˆ_dˆ_t ¡ ˆ_	|ˆ_
ˆ ˆ_d ˆ_tddd�ˆ_t|ƒ ddœ‡fdd„‰ttt||d	�ƒˆ_d
ddœ‡fdd„}	ddddœ‡fdd„}
dddœ‡ ‡‡fdd„}t|	|
|ƒˆ_d ˆ_d S )NFé(   éO   ©ÚrowsÚcolumnsr   rI   c                     s   ˆ j S r(   )Úsizer)   rK   r)   r*   Úget_size™   s    z+TelnetConnection.__init__.<locals>.get_size)r5   r%   r-   r>   c                   s   ˆ j  | ¡ dS )z-TelnetProtocolParser 'data_received' callbackN)r`   Z
send_bytes©r?   rK   r)   r*   Údata_receivedž   s    z0TelnetConnection.__init__.<locals>.data_receivedr$   )re   rf   r'   c                   s2   t | |d�ˆ _ˆ jdur.ˆ jr.ˆ j dd„ ¡ dS )z-TelnetProtocolParser 'size_received' callbackrd   Nc                   S  s
   t ƒ  ¡ S r(   )r	   Z
_on_resizer)   r)   r)   r*   Ú<lambda>¦   rM   zBTelnetConnection.__init__.<locals>.size_received.<locals>.<lambda>)r   rg   Úvt100_outputÚcontextÚrunrd   rK   r)   r*   Úsize_received¢   s    z0TelnetConnection.__init__.<locals>.size_receivedr4   )Úttyper'   c                   s"   t ˆjˆ| ˆ d�ˆ_ˆj ¡  dS )z.TelnetProtocolParser 'ttype_received' callback)Útermra   N)r   Ústdoutrl   Ú_readyÚset)rp   ©ra   rh   r<   r)   r*   Úttype_received¨   s    
ÿz1TelnetConnection.__init__.<locals>.ttype_received)r[   r\   r]   r^   r5   r_   r;   ÚasyncioÚEventrs   r`   ra   rl   r   rg   r2   r   r   r3   rr   r"   Úparserrm   )r<   r[   r\   r]   r^   r5   r_   r`   ra   rj   ro   rv   r)   ru   r*   r=   {   s(    
zTelnetConnection.__init__rI   c                 ƒ  sœ   ddœ‡ fdd„}t ƒ }| ˆ j|¡ zfˆ j ¡ I dH  tˆ jˆ jd��* t 	¡ ˆ _
ˆ  ˆ ¡I dH  W d  ƒ n1 sx0    Y  W ˆ  ¡  n
ˆ  ¡  0 dS )z"
        Run application.
        r-   rI   c                    s8   ˆ j  d¡} | rˆ  | ¡ nt dˆ j ¡ ˆ  ¡  d S )Ni   z"Connection closed by client. %r %r)r[   ÚrecvÚfeedr   r/   r\   rR   ri   rK   r)   r*   Úhandle_incoming_data·   s
    z>TelnetConnection.run_application.<locals>.handle_incoming_dataN)ÚinputÚoutput)r   Ú
add_readerr[   rs   Úwaitr   r`   rl   ÚcontextvarsÚcopy_contextrm   r]   rR   )r<   r|   Úloopr)   rK   r*   Úrun_application²   s    

0z TelnetConnection.run_applicationr%   r>   c                 C  s   | j  |¡ dS )zF
        Handler for incoming data. (Called by TelnetServer.)
        N)ry   r{   rF   r)   r)   r*   r{   Í   s    zTelnetConnection.feedc                 C  s<   | j s8d| _ | j ¡  tƒ  | j¡ | j ¡  | j ¡  dS )z#
        Closed by client.
        TN)r;   r`   rR   r   Úremove_readerr[   rr   rK   r)   r)   r*   rR   Ó   s    

zTelnetConnection.closer   )Úformatted_textr'   c                 C  s0   | j du rdS t|ƒ}t| j || jp(tƒ ƒ dS )z*
        Send text to the client.
        N)rl   r   r   r_   r   ©r<   r†   r)   r)   r*   r0   ß   s    
ÿzTelnetConnection.sendc                   s   t ˆ ƒ‰ ˆ ‡ ‡fdd„¡S )z\
        Send text to the client.
        This is asynchronous, returns a `Future`.
        c                     s
   ˆ  ˆ ¡S r(   )r0   r)   ©r†   r<   r)   r*   rk   ð   rM   z4TelnetConnection.send_above_prompt.<locals>.<lambda>)r   Ú_run_in_terminalr‡   r)   rˆ   r*   Úsend_above_promptê   s    z"TelnetConnection.send_above_promptzCallable[[], None])Úfuncr'   c                 C  s"   | j r| j  t|¡ ntdƒ‚d S )Nz2Called _run_in_terminal outside `run_application`.)rm   rn   r
   ÚRuntimeError)r<   r‹   r)   r)   r*   r‰   ò   s    z!TelnetConnection._run_in_terminalc                 C  s4   | j du rdS | j  ¡  | j  dd¡ | j  ¡  dS )zB
        Erase the screen and move the cursor to the top.
        Nr   )rl   Úerase_screenZcursor_gotorE   rK   r)   r)   r*   r�   ú   s
    

zTelnetConnection.erase_screenN)T)rS   rT   rU   rV   r=   r„   r{   rR   r0   rŠ   r‰   r�   r)   r)   r)   r*   rX   v   s    ÷ 7rX   c                 Ã  s   d S r(   r)   r1   r)   r)   r*   Ú_dummy_interact  s    rŽ   c                	   @  sŒ   e Zd ZdZddedddfddd	dd
dddœdd„Ze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ddœdd„ZdS )!r#   a¥  
    Telnet server implementation.

    Example::

        async def interact(connection):
            connection.send("Welcome")
            session = PromptSession()
            result = await session.prompt_async(message="Say something: ")
            connection.send(f"You said: {result}
")

        async def main():
            server = TelnetServer(interact=interact, port=2323)
            await server.run()
    z	127.0.0.1é   zutf-8NTr4   r$   rY   rZ   rH   r-   )ÚhostÚportr]   r5   r_   ra   r'   c                 C  s<   || _ || _|| _|| _|| _|| _d | _g | _tƒ | _	d S r(   )
r�   r‘   r]   r5   r_   ra   Ú	_run_taskÚ_application_tasksrt   Úconnections)r<   r�   r‘   r]   r5   r_   ra   r)   r)   r*   r=     s    	zTelnetServer.__init__r,   )r�   r‘   r'   c                 C  s>   t   t jt j¡}| t jt jd¡ | ||f¡ | d¡ |S )Nr   é   )ÚsocketÚAF_INETÚSOCK_STREAMÚ
setsockoptÚ
SOL_SOCKETÚSO_REUSEADDRÚbindÚlisten)Úclsr�   r‘   Úsr)   r)   r*   Ú_create_socket/  s
    
zTelnetServer._create_socketzCallable[[], None] | None)Úready_cbr'   c                 ƒ  sþ   ˆ   ˆ jˆ j¡‰t dˆ jˆ j¡ tƒ  ˆ‡ ‡fdd„¡ |rD|ƒ  zbt ¡ I dH  W tƒ  	ˆ¡ ˆ 
¡  ˆ jD ]}| ¡  qptˆ jƒdkrútjˆ jdtjd�I dH  nRtƒ  	ˆ¡ ˆ 
¡  ˆ jD ]}| ¡  qÂtˆ jƒdkrøtjˆ jdtjd�I dH  0 dS )z²
        Run the telnet server, until this gets cancelled.

        :param ready_cb: Callback that will be called at the point that we're
            actually listening.
        z.Listening for telnet connections on %s port %rc                     s
   ˆ   ˆ¡S r(   )Ú_acceptr)   ©r<   r–   r)   r*   rk   E  rM   z"TelnetServer.run.<locals>.<lambda>Nr   )ÚtimeoutÚreturn_when)r    r�   r‘   r   r/   r   r   rw   ÚFuturer…   rR   r“   ÚcancelÚlenr€   ÚALL_COMPLETED)r<   r¡   Útr)   r£   r*   rn   9  s:    
ÿ

ýô

ýzTelnetServer.runrI   c                 C  s$   | j durdS tƒ  |  ¡ ¡| _ dS )z}
        Deprecated: Use `.run()` instead.

        Start the telnet server (stop by calling and awaiting `stop()`).
        N)r’   r   Úcreate_taskrn   rK   r)   r)   r*   Ústart`  s    
zTelnetServer.startc                 Ã  s>   | j dur:| j  ¡  z| j I dH  W n tjy8   Y n0 dS )z¦
        Deprecated: Use `.run()` instead.

        Stop a telnet server that was started using `.start()` and wait for the
        cancellation to complete.
        N)r’   r§   rw   ÚCancelledErrorrK   r)   r)   r*   Ústopl  s    

zTelnetServer.stop)Úlisten_socketr'   c                   sT   |  ¡ \‰‰ tjdgˆ ¢R Ž  ddœ‡ ‡‡‡fdd„}tƒ  |ƒ ¡‰ˆj ˆ¡ dS )z1
        Accept new incoming connection.
        zNew connection %r %rr-   rI   c                  “  s`  �zJzºt ƒ � } tˆˆ ˆjˆˆjˆj| ˆjd�}ˆj |¡ tj	dgˆ ¢R Ž  z0| 
¡ I d H  W ˆj |¡ tj	dgˆ ¢R Ž  n ˆj |¡ tj	dgˆ ¢R Ž  0 W d   ƒ n1 s²0    Y  W n~ tyÚ   t 	d¡ Y nd tyô   t 	d¡ Y nJ t�y< } z0tdt|ƒj |ƒ dd l}| ¡  W Y d }~n
d }~0 0 W ˆj ˆ¡ nˆj ˆ¡ 0 d S )N)r5   r_   r`   ra   zStarting interaction %r %rzStopping interaction %r %rz)Unhandled EOFError in telnet application.z2Unhandled KeyboardInterrupt in telnet application.zGot %sr   )r   rX   r]   r5   r_   ra   r”   Úaddr   r/   r„   ÚremoveÚEOFErrorÚKeyboardInterruptÚBaseExceptionÚprintÚtyperS   Ú	tracebackÚ	print_excr“   )r`   r.   rQ   r·   ©r\   r[   r<   Útaskr)   r*   rn   ‚  s:    ø
ÿ6 z!TelnetServer._accept.<locals>.runN)Úacceptr   r/   r   r«   r“   rC   )r<   r¯   rn   r)   r¹   r*   r¢   z  s
    &zTelnetServer._accept)N)rS   rT   rU   rV   rŽ   r=   Úclassmethodr    rn   r¬   r®   r¢   r)   r)   r)   r*   r#   	  s   ù	')7rV   Ú
__future__r   rw   r�   r–   r   Útypingr   r   r   r   Z"prompt_toolkit.application.currentr   r	   Z*prompt_toolkit.application.run_in_terminalr
   Zprompt_toolkit.data_structuresr   Zprompt_toolkit.formatted_textr   r   Zprompt_toolkit.inputr   r   Zprompt_toolkit.output.vt100r   Zprompt_toolkit.rendererr   Zprompt_toolkit.stylesr   r   Úlogr   Úprotocolr   r   r   r   r   r   r   r   r   r   r    r!   r"   Ú__all__r+   r2   r3   rX   rŽ   r#   r)   r)   r)   r*   Ú<module>   s2   <ÿ* 