U
    d4                     @  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m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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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 dgZ6dddddZ7dddddZ8G dd dZ9G dd dZ:dddd d!Z;G d"d dZ<dS )#z
Telnet server.
    )annotationsN)get_running_loop)	Any	AwaitableCallableListOptionalSetTextIOTuple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.   H/tmp/pip-unpacked-wheel-4x_7prb2/prompt_toolkit/contrib/telnet/server.pyint2byte,   s    r0   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   r0   r"   r   r    r%   r#   r3   r.   r.   r/   _initialize_telnet0   s    
&r7   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.
    r1   strr2   )r3   encodingr,   c                 C  s"   || _ || _d| _g | _d| _d S )NstrictF)	_encoding_connection_errors_buffer_closed)selfr3   r:   r.   r.   r/   __init__S   s
    z_ConnectionStdout.__init__datar,   c                 C  s2   | dd}| j|j| j| jd |   d S )N
z
)errors)replacer?   appendencoder<   r>   flushrA   rD   r.   r.   r/   writeZ   s    z_ConnectionStdout.writeboolr,   c                 C  s   dS NTr.   rA   r.   r.   r/   isatty_   s    z_ConnectionStdout.isattyc              
   C  sZ   z| j s| jd| j W n0 tk
rN } ztd|  W 5 d }~X Y nX g | _d S )N    z"Couldn't send data over socket: %s)r@   r=   r5   joinr?   OSErrorr   warning)rA   er.   r.   r/   rJ   b   s     z_ConnectionStdout.flushc                 C  s
   d| _ d S rO   )r@   rP   r.   r.   r/   closek   s    z_ConnectionStdout.closec                 C  s   | j S r-   )r<   rP   r.   r.   r/   r:   n   s    z_ConnectionStdout.encodingc                 C  s   | j S r-   )r>   rP   r.   r.   r/   rF   r   s    z_ConnectionStdout.errorsN)__name__
__module____qualname____doc__rB   rL   rQ   rJ   rW   propertyr:   rF   r.   r.   r.   r/   r8   M   s   	r8   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.
    Tr1   ztuple[str, int]-Callable[[TelnetConnection], Awaitable[None]]r(   r9   BaseStyle | Noner   rM   r2   )	connaddrinteractserverr:   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   rN   c                     s    j S r-   )sizer.   rP   r.   r/   get_size   s    z+TelnetConnection.__init__.<locals>.get_size)r:   r*   r2   rC   c                   s    j |  dS )z-TelnetProtocolParser 'data_received' callbackN)re   Z
send_bytesrD   rP   r.   r/   data_received   s    z0TelnetConnection.__init__.<locals>.data_receivedr)   )rj   rk   r,   c                   s2   t | |d _ jdk	r. jr. jdd  dS )z-TelnetProtocolParser 'size_received' callbackri   Nc                   S  s
   t   S r-   )r   Z
_on_resizer.   r.   r.   r/   <lambda>   rR   zBTelnetConnection.__init__.<locals>.size_received.<locals>.<lambda>)r   rl   vt100_outputcontextrunri   rP   r.   r/   size_received   s    z0TelnetConnection.__init__.<locals>.size_receivedr9   )ttyper,   c                   s"   t j|  d_j  dS )z.TelnetProtocolParser 'ttype_received' callback)Ztermrf   N)r   stdoutrq   _readyset)ru   rf   rm   rA   r.   r/   ttype_received   s       z1TelnetConnection.__init__.<locals>.ttype_received)r`   ra   rb   rc   r:   rd   r@   asyncioEventrw   re   rf   rq   r   rl   r7   r   r
   r8   rv   r'   parserrr   )rA   r`   ra   rb   rc   r:   rd   re   rf   ro   rt   rz   r.   ry   r/   rB   |   s(    
zTelnetConnection.__init__rN   c              	     s   dd fdd}t  }| j| zJ j I dH  t j jd  t	
  _  I dH  W 5 Q R X W 5    X dS )z"
        Run application.
        r2   rN   c                    s8    j d} | r |  ntd j     d S )Ni   z"Connection closed by client. %r %r)r`   recvfeedr   r4   ra   rW   rn   rP   r.   r/   handle_incoming_data   s
    z>TelnetConnection.run_application.<locals>.handle_incoming_dataN)inputoutput)r   
add_readerr`   rW   rw   waitr   re   rq   contextvarsZcopy_contextrr   rb   )rA   r   Zloopr.   rP   r/   run_application   s    

z TelnetConnection.run_applicationr*   rC   c                 C  s   | j | dS )zF
        Handler for incoming data. (Called by TelnetServer.)
        N)r}   r   rK   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@   re   rW   r   remove_readerr`   rv   rP   r.   r.   r/   rW      s    

zTelnetConnection.closer   )formatted_textr,   c                 C  s0   | j dkrdS t|}t| j || jp(t  dS )z*
        Send text to the client.
        N)rq   r   r   rd   r   rA   r   r.   r.   r/   r5      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-   )r5   r.   r   rA   r.   r/   rp      rR   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`.)rr   rs   r   RuntimeError)rA   r   r.   r.   r/   r      s    z!TelnetConnection._run_in_terminalc                 C  s4   | j dkrdS | j   | j dd | j   dS )zB
        Erase the screen and move the cursor to the top.
        Nr   )rq   erase_screenZcursor_gotorJ   rP   r.   r.   r/   r      s
    

zTelnetConnection.erase_screenN)T)rX   rY   rZ   r[   rB   r   r   rW   r5   r   r   r   r.   r.   r.   r/   r]   w   s     7r]   c                   s   d S r-   r.   r6   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-8NTr9   r)   r^   r_   rM   r2   )hostportrb   r:   rd   rf   r,   c                 C  s<   || _ || _|| _|| _|| _|| _d | _g | _t | _	d S r-   )
r   r   rb   r:   rd   rf   	_run_task_application_tasksrx   connections)rA   r   r   rb   r:   rd   rf   r.   r.   r/   rB     s    	zTelnetServer.__init__r1   )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_socket0  s
    
zTelnetServer._create_socketzCallable[[], None] | None)ready_cbr,   c                   s      j jtd j j t  fdd |rD|  zt I dH  W 5 t     j	D ]}|
  qrt j	dkrtj j	dtjdI dH  X 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.   rA   r   r.   r/   rp   F  rR   z"TelnetServer.run.<locals>.<lambda>r   N)timeoutZreturn_when)r   r   r   r   r4   r   r   r   rW   r   cancellenr{   r   ZALL_COMPLETEDZFuture)rA   r   tr.   r   r/   rs   :  s*      

zTelnetServer.runrN   c                 C  s$   | j dk	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_taskrs   rP   r.   r.   r/   starta  s    
zTelnetServer.startc                   s@   | j dk	r<| j   z| j I dH  W n tjk
r:   Y nX 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   r{   ZCancelledErrorrP   r.   r.   r/   stopm  s    

zTelnetServer.stop)listen_socketr,   c                   sP   |  \ tjd   dd fdd}t | j dS )z1
        Accept new incoming connection.
        New connection %r %rr2   rN   c                    s  zzt p} t jjj| jd}j	| t
jd   z| I d H  W 5 j| t
jd	   X W 5 Q R X W n tk
r   t
d Y nd tk
r   t
d Y nH tk
r } z(tdt|j | dd l}|  W 5 d }~X Y nX W 5 j  X d S )
N)r:   rd   re   rf   Starting interaction %r %rStopping interaction %r %rz)Unhandled EOFError in telnet application.z2Unhandled KeyboardInterrupt in telnet application.zGot %sr   )r   )r   )r   remover   r]   rb   r:   rd   rf   r   addr   r4   r   EOFErrorKeyboardInterruptBaseExceptionprinttyperX   	traceback	print_exc)re   r3   rV   r   ra   r`   rA   Ztaskr.   r/   rs     s6    
z!TelnetServer._accept.<locals>.runN)r   )acceptr   r4   r   r   r   rH   )rA   r   rs   r.   r   r/   r   {  s
    &zTelnetServer._accept)N)rX   rY   rZ   r[   r   rB   classmethodr   rs   r   r   r   r.   r.   r.   r/   r(   
  s   	')=r[   
__future__r   r{   r   r   sysr   typingr   r   r   r   r   r	   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__r0   r7   r8   r]   r   r(   r.   r.   r.   r/   <module>   s4   ,<* 