
    jjb)                       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m	Z	 ej                  dk  rddlmZ ej                  r ddlZddlmZmZmZmZ dd	lmZmZ  ed
      ZdZ G d dej2                  j4                        Z G d de      Zy)zMTrio Runner based urwid EventLoop implementation.

Trio library is required.
    )annotationsN   )	EventLoopExitMainLoop)      )BaseExceptionGroup)	AwaitableCallableHashableMapping)Concatenate	ParamSpec_Spec)TrioEventLoopc                  $    e Zd ZdZdZddZddZy)_TrioIdleCallbackInstrumentz IDLE callbacks emulation helper.idle_callbacksc                    || _         y )Nr   )selfr   s     c/home/ubuntu/.cache/pipx/cdb5059130eadca/lib/python3.12/site-packages/urwid/event_loop/trio_loop.py__init__z$_TrioIdleCallbackInstrument.__init__7   s
    ,    c                \    |dkD  r'| j                   j                         D ]	  } |         y y )Nr   )r   values)r   timeoutidle_callbacks      r   before_io_waitz*_TrioIdleCallbackInstrument.before_io_wait:   s1    Q;!%!4!4!;!;!=    r   N)r   z+Mapping[Hashable, Callable[[], typing.Any]])r   floatreturnNone)__name__
__module____qualname____doc__	__slots__r   r    r   r   r   r   2   s    *#I- r   r   c                       e Zd ZdZd f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 xZS )r   zn
    Event loop based on the ``trio`` module.

    ``trio`` is an async library for Python 3.5 and later.
    c                D   t         |           t        j                  t              j                  | j                  j                        | _        d| _        i | _	        g | _
        d| _        t        j                  | _        t        j                  j                   | _        y)zConstructor.r   N)superr   logging	getLoggerr#   getChild	__class__logger_idle_handle_idle_callbacks_pending_tasks_nurserytriosleep_sleeplowlevelwait_readable_wait_readable)r   r/   s    r   r   zTrioEventLoop.__init__G   sq    ''1::4>>;R;RSDFeg-1jj"mm99r   c                <    | j                  | j                  ||      S )a  Calls `callback()` a given time from now.

        :param seconds: time in seconds to wait before calling the callback
        :type seconds: float
        :param callback: function to call from the event loop
        :type callback: Callable[[], typing.Any]
        :return: a handle that may be passed to `remove_alarm()`
        :rtype: trio.CancelScope

        No parameters are passed to the callback.
        )_start_task_alarm_task)r   secondscallbacks      r   alarmzTrioEventLoop.alarmU   s       0 0'8DDr   c                v    | xj                   dz  c_         || j                  | j                   <   | j                   S )zCalls `callback()` when the event loop enters the idle state.

        There is no such thing as being idle in a Trio event loop so we
        simulate it by repeatedly calling `callback()` with a short delay.
        r   )r1   r2   )r   r?   s     r   
enter_idlezTrioEventLoop.enter_idleg   s7     	Q2:T../   r   c                $    | j                  |      S )zeRemoves an alarm.

        Parameters:
            handle: the handle of the alarm to remove
        _cancel_scoper   handles     r   remove_alarmzTrioEventLoop.remove_alarmq   s     !!&))r   c                >    	 | j                   |= y# t        $ r Y yw xY w)zuRemoves an idle callback.

        Parameters:
            handle: the handle of the idle callback to remove
        FT)r2   KeyErrorrF   s     r   remove_enter_idlezTrioEventLoop.remove_enter_idley   s.    	$$V,   		s    	c                $    | j                  |      S )zRemoves a file descriptor being watched for input.

        Parameters:
            handle: the handle of the file descriptor callback to remove

        Returns:
            True if the file descriptor was watched, False otherwise
        rD   rF   s     r   remove_watch_filezTrioEventLoop.remove_watch_file   s     !!&))r   c                @    |j                    }|j                          |S )zCancels the given Trio cancellation scope.

        Returns:
            True if the scope was cancelled, False if it was cancelled already
            before invoking this function
        )cancel_calledcancel)r   scopeexisteds      r   rE   zTrioEventLoop._cancel_scope   s      )))r   c                    t        | j                        }	 t        j                  | j                  |g       y# t
        $ r}| j                  |       Y d}~yd}~ww xY w)zStarts the event loop. Exits the loop when any callback raises an
        exception. If ExitMainLoop is raised, exits cleanly.
        )instrumentsN)r   r2   r5   run
_main_taskBaseException_handle_main_loop_exceptionr   emulate_idle_callbacksexcs      r   rU   zTrioEventLoop.run   sQ    
 "=T=Q=Q!R	2HHT__3I2JK 	2,,S11	2s   ": 	AAAc                  K   t        | j                        }	 t        j                  j	                  |       	 | j                          d{    t        j                  j                  |       y7 $# t        j                  j                  |       w xY w# t        $ r}| j                  |       Y d}~yd}~ww xY ww)aB  Starts the main loop and blocks asynchronously until the main loop exits.

        This allows one to embed an urwid app in a Trio app even if the Trio event loop is already running.
        Example::

            with trio.open_nursery() as nursery:
                event_loop = urwid.TrioEventLoop()

                # [...launch other async tasks in the nursery...]

                loop = urwid.MainLoop(widget, event_loop=event_loop)
                with loop.start():
                    await event_loop.run_async()

                nursery.cancel_scope.cancel()
        N)	r   r2   r5   r8   add_instrumentrV   remove_instrumentrW   rX   rY   s      r   	run_asynczTrioEventLoop.run_async   s     $ "=T=Q=Q!R	2MM(()?@Hoo'''//0FG (//0FG 	2,,S11	2sW   B>B A3 A1A3 B 0B>1A3 3!BB 	B; B61B>6B;;B>c                <    | j                  | j                  ||      S )ab  Calls `callback()` when the given file descriptor has some data
        to read. No parameters are passed to the callback.

        Parameters:
            fd: file descriptor to watch for input
            callback: function to call when some input is available

        Returns:
            a handle that may be passed to `remove_watch_file()`
        )r<   _watch_task)r   fdr?   s      r   
watch_filezTrioEventLoop.watch_file   s      0 0"h??r   c                ~   K   |5  | j                  |       d{     |        ddd       y7 # 1 sw Y   yxY ww)a0  Asynchronous task that sleeps for a given number of seconds and then
        calls the given callback.

        Parameters:
            scope: the cancellation scope that can be used to cancel the task
            seconds: the number of seconds to wait
            callback: the callback to call
        N)r7   )r   rQ   r>   r?   s       r   r=   zTrioEventLoop._alarm_task   s?       	++g&&&J	 	&	 	s    =1/1	=1:=c                    | j                   j                          t        |t              r't	        |j
                        dk(  r|j
                  d   }t        |t              ry|j                  |j                        d)a5  Handles exceptions raised from the main loop, catching ExitMainLoop
        instead of letting it propagate through.

        Note that since Trio may collect multiple exceptions from tasks into an ExceptionGroup,
        we cannot simply use a try..catch clause, we need a helper function like this.
        r   r   N)	r2   clear
isinstancer	   len
exceptionsr   with_traceback__traceback__)r   r[   s     r   rX   z)TrioEventLoop._handle_main_loop_exception   se     	""$c-.3s~~3F!3K..#Cc<(  !2!23=r   c                &  K   	 t        j                         4 d{   | _        | j                          t        j                          d{    ddd      d{    d| _        y7 M7 7 # 1 d{  7  sw Y    xY w# d| _        w xY ww)zzMain Trio task that opens a nursery and then sleeps until the user
        exits the app by raising ExitMainLoop.
        N)r5   open_nurseryr4   _schedule_pending_taskssleep_forever)r   s    r   rV   zTrioEventLoop._main_task   s     	!((* + +dm,,.((***+ + !DM	+*+ + + + !DMss   BB A*B -A0A,A0B A.B "B*B ,A0.B 0B6A97B>B 	BBc                    | j                   D ]$  \  }}} | j                  j                  ||g|  & | j                   j                          y)zSchedules all pending asynchronous tasks that were created before
        the nursery to be executed on the nursery soon.
        N)r3   r4   
start_soonrf   )r   taskrQ   argss       r   rn   z%TrioEventLoop._schedule_pending_tasks  sM     "&!4!4 	9D%$DMM$$T5848	9!!#r   c                    t        j                         }| j                  r  | j                  j                  ||g|  |S | j                  j                  |||f       |S )ap  Starts an asynchronous task in the Trio nursery managed by the
        main loop. If the nursery has not started yet, store a reference to
        the task and the arguments so we can start the task when the nursery
        is open.

        Parameters:
            task: a Trio task to run

        Returns:
            a cancellation scope for the Trio task
        )r5   CancelScoper4   rq   r3   append)r   rr   rs   rQ   s       r   r<   zTrioEventLoop._start_task
  s]        "==$DMM$$T5848  &&eT':;r   c                   K   |5  |j                   s-| j                  |       d{     |        |j                   s-ddd       y7 !# 1 sw Y   yxY ww)aP  Asynchronous task that watches the given file descriptor and calls
        the given callback whenever the file descriptor becomes readable.

        Parameters:
            scope: the cancellation scope that can be used to cancel the task
            fd: the file descriptor to watch
            callback: the callback to call
        N)rO   r:   )r   rQ   rb   r?   s       r   ra   zTrioEventLoop._watch_task!  sY       	 ))))"---
 ))		 	
 .	 	s+   A!A
AA
	AA

AA)r!   r"   )r>   r    r?   Callable[[], typing.Any]r!   trio.CancelScope)r?   rx   r!   int)rG   ry   r!   bool)rG   rz   r!   r{   )rQ   ry   r!   r{   )rb   int | io.IOBaser?   rx   r!   ry   )rQ   ry   r>   r    r?   rx   r!   r"   )r[   rW   r!   r"   )rr   z9Callable[Concatenate[trio.CancelScope, _Spec], Awaitable]rs   z
_Spec.argsr!   ry   )rQ   ry   rb   r|   r?   rx   r!   r"   )r#   r$   r%   r&   r   r@   rB   rH   rK   rM   rE   rU   r_   rc   r=   rX   rV   rn   r<   ra   __classcell__)r/   s   @r   r   r   @   s    :EE +E 
	E$!*
	*	
22:@@ +@ 
	@"  +	
 
$> 	!$G  
	.  +	
 
r   r   )r&   
__future__r   r,   systypingr5   abstract_loopr   r   version_infoexceptiongroupr	   TYPE_CHECKINGiocollections.abcr
   r   r   r   typing_extensionsr   r   r   __all__abc
Instrumentr   r   r(   r   r   <module>r      sw   *
 #  
   2g1	FF8gE
 $(("5"5  uI ur   