
    AHj5                    2   U 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	 ddl
mZ ddlmZmZmZmZmZmZmZmZ ddlZddlmZ dd	lmZ erdd
lmZ ddlmZ  ed      Zde d<   	  G d de!      Z" G d de!      Z# G d de#      Z$ G d de#      Z% G d de#      Z&d$dZ' G d dejP                        Z) ed      Z*eeg edde*f   f   eg e*f   ee*   f   Z+de d<   	  G d d       Z,ejZ                  j]                  d!"       G d# dee*                Z/y)%zx
This module contains the `Worker` class and related objects.

See the guide for how to use [workers](/guide/workers).

    )annotationsN)
ContextVar)Event)	monotonic)TYPE_CHECKING	AwaitableCallable	CoroutineGenericTypeVarUnioncast)	TypeAlias)Message)App)DOMNodeactive_workerzContextVar[Worker]c                      e Zd ZdZy)NoActiveWorkerzThere is no active worker.N__name__
__module____qualname____doc__     F/root/tools/cai/cai_env/lib/python3.12/site-packages/textual/worker.pyr   r   )   s    $r   r   c                      e Zd ZdZy)WorkerErrorzA worker related error.Nr   r   r   r   r   r   -   s    !r   r   c                  $     e Zd ZdZd fdZ xZS )WorkerFailedz4The worker raised an exception and did not complete.c                8    || _         t        | 	  d|       y )NzWorker raised exception: )errorsuper__init__)selfr#   	__class__s     r   r%   zWorkerFailed.__init__4   s    
4UI>?r   )r#   BaseExceptionreturnNone)r   r   r   r   r%   __classcell__r'   s   @r   r!   r!   1   s    >@ @r   r!   c                      e Zd ZdZy)DeadlockErrorz)The operation would result in a deadlock.Nr   r   r   r   r.   r.   9   s    3r   r.   c                      e Zd ZdZy)WorkerCancelledz.The worker was cancelled and did not complete.Nr   r   r   r   r0   r0   =   s    8r   r0   Workerc                 ^    	 t         j                         S # t        $ r t        d      dw xY w)zGet the currently active worker.

    Raises:
        NoActiveWorker: If there is no active worker.

    Returns:
        A Worker instance.
    z1There is no active worker in this task or thread.N)r   getLookupErrorr   r   r   r   get_current_workerr5   A   s8      "" ?
	s    ,c                  ,    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZy)WorkerStatez,A description of the worker's current state.               N)	r   r   r   r   PENDINGRUNNING	CANCELLEDERRORSUCCESSr   r   r   r7   r7   R   s-    6G1GI3E:G<r   r7   
ResultTyper   WorkTypec                       e Zd ZdZddZddZy)	_ReprTextz-Shim to insert a word into the Worker's repr.c                    || _         y Ntext)r&   rI   s     r   r%   z_ReprText.__init__o   s	    	r   c                    | j                   S rG   rH   r&   s    r   __repr__z_ReprText.__repr__r   s    yyr   N)rI   strr)   r*   )r)   rM   )r   r   r   r   r%   rL   r   r   r   rE   rE   l   s    7r   rE   T)angularc                     e Zd ZdZej
                  j                   G d dedd             Zdddd	dd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d"dZ	d#dZ
ed$d       Zed%d       Zej                  d&d       Zed'd       Zed'd       Zed'd       Zed(d       Zed)d       Zed*d       Zed+d       Zed,d       Z	 d-	 	 	 	 	 d.dZd/d0dZd1dZd1dZd1dZd2dZ	 d3	 	 	 	 	 d4dZd5d Zd1d!Zy)6r1   z>A class to manage concurrent work (either a task or a thread).c                  ,     e Zd ZdZd fdZddZ xZS )Worker.StateChangedzThe worker state changed.c                >    || _         || _        t        |           y)zInitialize the StateChanged message.

            Args:
                worker: The worker object.
                state: New state.
            N)workerstater$   r%   )r&   rS   rT   r'   s      r   r%   zWorker.StateChanged.__init__~   s     !DKDJGr   c              #  D   K   | j                    | j                   y wrG   )rS   rT   rK   s    r   __rich_repr__z!Worker.StateChanged.__rich_repr__   s     ++**s    )rS   r1   rT   r7   r)   r*   r)   zrich.repr.Result)r   r   r   r   r%   rV   r+   r,   s   @r   StateChangedrQ   z   s    '			r   rX   FrS   )bubble	namespace defaultT)namegroupdescriptionexit_on_errorthreadc                  || _         || _        || _        || _        t	        |      dk  r|n|dd dz   | _        || _        t               | _        	 || _	        t        j                  | _        | j                  | _        d| _        d| _        d| _        d| _        t%               | _        d| _        d| _        | j                   j-                  | j/                  | | j                               y)aA  Initialize a Worker.

        Args:
            node: The widget, screen, or App that initiated the work.
            work: A callable, coroutine, or other awaitable object to run in the worker.
            name: Name of the worker (short string to help identify when debugging).
            group: The worker group.
            description: Description of the worker (longer string with more details).
            exit_on_error: Exit the app if the worker raises an error. Set to `False` to suppress exceptions.
            thread: Mark the worker as a thread worker.
        i  Nz...r   F)_node_workr]   r^   lenr_   r`   r   cancelled_event_thread_workerr7   r=   _staterT   _error_completed_steps_total_steps
_cancelledr   _created_time_result_taskpost_messagerX   )r&   nodeworkr]   r^   r_   r`   ra   s           r   r%   zWorker.__init__   s    , 

	
{+t3KUd9Ke9S 	 +&+gA$!))[[
,0%&(, %&[*.*.


 1 1$ DEr   c              #     K   t        | j                  j                         d| j                  df d| j                  df d| j                  df dt        | j                  d      df y w)	Nr]   r[   r^   r\   r_   progressr8           )rE   rT   r]   r^   r_   roundrt   rK   s    r   rV   zWorker.__rich_repr__   sf     

((dii##tzz9,,T--r11%q1366s   A1A3c                    | j                   S )z(The node where this worker was run from.)rc   rK   s    r   rq   zWorker.node   s     zzr   c                    | j                   S )z The current state of the worker.)rh   rK   s    r   rT   zWorker.state        {{r   c                    || j                   k7  }|| _         |r,| j                  j                  | j                  | |             yy)z"Set the state, and send a message.N)rh   rc   rp   rX   )r&   rT   changeds      r   rT   zWorker.state   s@     4;;&JJ##D$5$5dE$BC r   c                    | j                   S )z]Has the work been cancelled?

        Note that cancelled work may still be running.
        )rl   rK   s    r   is_cancelledzWorker.is_cancelled   s     r   c                <    | j                   t        j                  k(  S )zIs the task running?)rT   r7   r>   rK   s    r   
is_runningzWorker.is_running   s     zz[0000r   c                x    | j                   t        j                  t        j                  t        j                  fv S )z5Has the task finished (cancelled, error, or success)?)rT   r7   r?   r@   rA   rK   s    r   is_finishedzWorker.is_finished   s5     zz!!
 
 	
r   c                    | j                   S )zThe number of completed steps.rj   rK   s    r   completed_stepszWorker.completed_steps   s     $$$r   c                    | j                   S )z4The number of total steps, or None if indeterminate.)rk   rK   s    r   total_stepszWorker.total_steps   s        r   c                |    | j                   syt        dt        d| j                  | j                   z  dz              S )zProgress as a percentage.

        If the total steps is None, then this will return 0. The percentage will be clamped between 0 and 100.
        ru   r   d   g      Y@)rk   maxminrj   rK   s    r   rt   zWorker.progress   s:       1c# 5 58I8I IURSTTr   c                    | j                   S )z:The result of the worker, or `None` if there is no result.)rn   rK   s    r   resultzWorker.result   s     ||r   c                    | j                   S )zDThe exception raised by the worker, or `None` if there was no error.)ri   rK   s    r   r#   zWorker.error  ry   r   Nc                h    || xj                   |z  c_         |dk7  r|dnt        d|      | _        yy)zUpdate the number of completed steps.

        Args:
            completed_steps: The number of completed seps, or `None` to not change.
            total_steps: The total number of steps, `None` for indeterminate, or -1 to leave unchanged.
        Nr   )rj   r   rk   )r&   r   r   s      r   updatezWorker.update  s>     &!!_4!"(3(;QATD r   c                .    | xj                   |z  c_         y)zmAdvance the number of completed steps.

        Args:
            steps: Number of steps to advance.
        Nr   )r&   stepss     r   advancezWorker.advance  s     	&r   c                   K   d fd	 	 	 	 dfd}d	 fd}t        j                   j                        s?t         j                  d      r,t        j                   j                  j                        r|}nEt        j
                   j                        r}n#t         j                        r|}nt        d      t        j                         }|J |j                  d| j                         d{   S 7 w)
zWRun a threaded worker.

        Returns:
            Return value of the work.
        c                H     d fd}t        j                   |             S )z.Set the active worker and await the awaitable.c                 N   K   t         j                           d {   S 7 wrG   r   set)r&   rr   s   r   do_workz<Worker._run_threaded.<locals>.run_awaitable.<locals>.do_work&  s     !!$'!z!zs   %#%r)   rB   )asynciorun)rr   r   r&   s   ` r   run_awaitablez+Worker._run_threaded.<locals>.run_awaitable#  s    " ;;wy))r   c                      |              S )z*Set the active worker and await coroutine.r   )rr   r   s    r   run_coroutinez+Worker._run_threaded.<locals>.run_coroutine,  s     !((r   c                <    t         j                          |        S )z-Set the active worker, and call the callable.r   )rr   r&   s    r   run_callablez*Worker._run_threaded.<locals>.run_callable2  s    d#6Mr   funcz*Unsupported attempt to run a thread workerN)rr   zAwaitable[ResultType]r)   rB   )rr   z/Callable[[], Coroutine[None, None, ResultType]]r)   rB   )rr   zCallable[[], ResultType]r)   rB   )inspectiscoroutinefunctionrd   hasattrr   isawaitablecallabler   r   get_running_looprun_in_executor)r&   r   r   runnerloopr   s   `    @r   _run_threadedzWorker._run_threaded  s     	*	)A	)	)	 ''

3tzz6*++DJJOO<"F  ,"Fdjj!!FJKK'')))$

CCCCs   C5D 9C>:D c                  K   t        j                  | j                        s?t        | j                  d      rAt        j                  | j                  j                        r| j                          d{   S t        j
                  | j                        r| j                   d{   S t        | j                        rt        d      t        d      7 b7 1w)zURun an async worker.

        Returns:
            Return value of the work.
        r   Nz6Request to run a non-async function as an async workerz*Unsupported attempt to run an async worker)r   r   rd   r   r   r   r   r   rK   s    r   
_run_asynczWorker._run_asyncH  s      ''

3tzz6*++DJJOO<%%  ,##djj!VWWFGG &#s$   A2C4C52C'C(0CCc                v   K   | j                   r| j                         n| j                          d{   S 7 w)zRun the work.

        Implement this method in a subclass, or pass a callable to the constructor.

        Returns:
            Return value of the work.
        N)rg   r   r   rK   s    r   r   z
Worker.runZ  s4      %)$7$7D T__=N
 	
 
s   0979c           	       K   |j                         5  t        j                  |        t        j                  | _        |j                  j                  |        	 | j                          d{   | _	        t        j                  | _        |j                  j                  |        ddd       y7 B# t        j                  $ rA}t        j                  | _        || _        |j                  j                  |        Y d}~Zd}~wt        $ r}t        j                   | _        || _        |j                  j                  | dt#        |             ddlm} |j                  j                   |              | j(                  r&t+        | j                        }|j-                  |       Y d}~d}~ww xY w# 1 sw Y   yxY ww)zFRun the worker.

        Args:
            app: App instance.
        Nfailedr   )	Traceback)_contextr   r   r7   r>   rT   logrS   r   rn   rA   r   CancelledErrorr?   ri   	Exceptionr@   reprrich.tracebackr   r`   r!   _handle_exception)r&   appr#   r   worker_faileds        r   _runzWorker._runf  s;     \\^ 	%d#$,,DJGGNN4 %%)XXZ/  )00
t$/	% 	%  0)) %(22
#t$$ 	9(..
#tXtE{;4y{+%%$0$=M))-8	9	% 	%sl   GAF5B2-B0.	B270F5'	G0B22F27D<F5F2BF-'F5-F22F55F>:Gc                      j                   yt        j                   _        t	        j
                   j                  |             _         d fd} j                   j                  |       y)zStart the worker.

        Args:
            app: An app instance.
            done_callback: A callback to call when the task is done.
        Nc                    	        yy)zRun the callback.

            Called by `Task.add_done_callback`.

            Args:
                The worker's task.
            Nr   )ro   done_callbackr&   s    r   task_done_callbackz)Worker._start.<locals>.task_done_callback  s     (d# )r   )ro   zasyncio.Taskr)   r*   )ro   r7   r>   rT   r   create_taskr   add_done_callback)r&   r   r   r   s   ` ` r   _startzWorker._start  sS     ::! ((
((38
		$ 	

$$%78r   c                    d| _         | j                  | j                  j                          | j                  j	                          y)zCancel the task.TN)rl   ro   cancelrf   r   rK   s    r   r   zWorker.cancel  s5    ::!JJ  "r   c                x  K   	 t         j                         | u rt        d      	 | j                  t
        j                  k(  rt        d      | j                  	 | j                   d{    | j                  t
        j                  k(  r#| j                  J t        | j                        | j                  t
        j                  k(  rt        d      t!        d| j"                        S # t        $ r Y w xY w7 # t        j                  $ r&}t
        j                  | _        || _        Y d}~d}~ww xY ww)zWait for the work to complete.

        Raises:
            WorkerFailed: If the Worker raised an exception.
            WorkerCancelled: If the Worker was cancelled before it completed.

        Returns:
            The return value of the work.
        z7Can't call worker.wait from within the worker function!z2Worker must be started before calling this method.Nz+Worker was cancelled, and did not complete.rB   )r   r3   r.   r4   rT   r7   r=   r   ro   r   r   r?   ri   r@   r!   r0   r   rn   )r&   r#   s     r   waitzWorker.wait  s    	  "d*#M  + ::,,,RSS::!$jj   ::***;;***t{{++ZZ;000!"OPPL$,,//#  		 !)) $(22
#$sd   D:!C- 5D:C> *C<+C> /A>D:-	C96D:8C99D:<C> >D7D2-D:2D77D:)rq   r   rr   rC   r]   rM   r^   rM   r_   rM   r`   boolra   r   r)   r*   rW   )r)   r   )r)   r7   )rT   r7   r)   r*   )r)   r   )r)   int)r)   
int | None)r)   float)r)   zResultType | None)r)   zBaseException | None)Nr   )r   r   r   r   r)   r*   )r8   )r   r   r)   r*   r   )r   r   r)   r*   rG   )r   r   r   zCallable[[Worker], None] | Noner)   r*   )r)   r*   ) r   r   r   r   richr   autor   rX   r%   rV   propertyrq   rT   setterr}   r   r   r   r   rt   r   r#   r   r   r   r   r   r   r   r   r   r   r   r   r1   r1   v   s   H	YY^^wu  . "*F*F *F
 *F *F *F *F *F 
*FX7     \\D D   1 1 
 
 % % ! ! U U    
 MOU)U?IU	U'*DXH$

%@ JN99'F9	96# 0r   )r)   r1   )0r   
__future__r   r   enumr   contextvarsr   	threadingr   timer   typingr   r   r	   r
   r   r   r   r   	rich.reprr   typing_extensionsr   textual.messager   textual.appr   textual.domr   r   __annotations__r   r   r   r!   r.   r0   r5   Enumr7   rB   rC   rE   r   r   r1   r   r   r   <module>r      s>   #    "  	 	 	  ' ## %/$?! ? *%Y %") "@; @4K 49k 9"=$)) = \"
 R4z1223R^j) 
 0  P0WZ  P0 P0r   