a
    ¦ˆcŠa  ã                   @   s|  d 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Zddlm	Z	 ddl
Z
ddlZddlmZmZ ddlmZ dd	lmZ d
adadd„ Zdd„ ZG dd„ deƒZG dd„ deƒZeƒ ZejZejZejZ da!da"d+dd„Z#dd„ Z$dd„ Z%ej&dd„ ƒZ'G dd„ deƒZ(G dd„ de(ƒZ)G dd „ d e(ƒZ*G d!d"„ d"eƒZ+G d#d$„ d$e+ƒZ,G d%d&„ d&e+ƒZ-G d'd(„ d(e+ƒZ.d)d*„ Z/dS ),zM Classes that implement and support the Traits change notification mechanism
é    N)Úlocal)ÚThread)Ú
MethodTypeé   )ÚComparisonModeÚ	TraitKind)ÚUninitialized)ÚTraitNotificationErroréÿÿÿÿc                 C   s   | a t ¡ jadS )z0 Sets up the user interface thread handler.
    N)Ú
ui_handlerÚ	threadingÚcurrent_threadÚidentÚ	ui_thread)Úhandler© r   úY/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/traits/trait_notifiers.pyÚset_ui_handler%   s    r   c                 O   s8   t  ¡ jtkr| |i |¤Ž nt| g|¢R i |¤Ž d S ©N©r   r   r   r   r   )r   ÚargsÚkwr   r   r   Úui_dispatch.   s    r   c                   @   s   e Zd Zdd„ ZdS )Ú!NotificationExceptionHandlerStatec                 C   s   || _ || _|| _d S r   )r   Úreraise_exceptionsÚlocked)Úselfr   r   r   r   r   r   Ú__init__6   s    z*NotificationExceptionHandlerState.__init__N)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r   r   5   s   r   c                   @   sF   e Zd Zdd„ Zddd„Zdd„ Zd	d
„ Zdd„ Zdd„ Zdd„ Z	dS )ÚNotificationExceptionHandlerc                 C   s   d | _ d | _tƒ | _d S r   )Útraits_loggerÚmain_threadÚthread_local©r   r   r   r   r   =   s    z%NotificationExceptionHandler.__init__NFc                 C   sD   |   ¡ }|  |¡ |du r | j}| t|||ƒ¡ |r<|| _|d S )a~   Pushes a new traits notification exception handler onto the stack,
            making it the new exception handler. Returns a
            NotificationExceptionHandlerState object describing the previous
            exception handler.

            Parameters
            ----------
            handler : handler
                The new exception handler, which should be a callable or
                None. If None (the default), then the default traits
                notification exception handler is used. If *handler* is not
                None, then it must be a callable which can accept four
                arguments: object, trait_name, old_value, new_value.
            reraise_exceptions : bool
                Indicates whether exceptions should be reraised after the
                exception handler has executed. If True, exceptions will be
                re-raised after the specified handler has been executed.
                The default value is False.
            main : bool
                Indicates whether the caller represents the main application
                thread. If True, then the caller's exception handler is
                made the default handler for any other threads that are
                created. Note that a thread can explicitly set its own
                exception handler if desired. The *main* flag is provided to
                make it easier to set a global application policy without
                having to explicitly set it for each thread. The default
                value is False.
            locked : bool
                Indicates whether further changes to the Traits notification
                exception handler state should be allowed. If True, then
                any subsequent calls to _push_handler() or _pop_handler() for
                that thread will raise a TraitNotificationError. The default
                value is False.
        Néþÿÿÿ)Ú_get_handlersÚ_check_lockÚ_log_exceptionÚappendr   r#   )r   r   r   Úmainr   Úhandlersr   r   r   Ú_push_handlerD   s    %
ÿÿz*NotificationExceptionHandler._push_handlerc                 C   s4   |   ¡ }|  |¡ t|ƒdkr(| ¡  ntdƒ‚dS )aµ   Pops the traits notification exception handler stack, restoring
            the exception handler in effect prior to the most recent
            _push_handler() call. If the stack is empty or locked, a
            TraitNotificationError exception is raised.

            Note that each thread has its own independent stack. See the
            description of the _push_handler() method for more information on
            this.
        r   zFAttempted to pop an empty traits notification exception handler stack.N)r'   r(   ÚlenÚpopr	   ©r   r,   r   r   r   Ú_pop_handlerw   s    


ÿz)NotificationExceptionHandler._pop_handlerc                 C   sH   t  ¡ dd… \}}|  ¡ d }| ||||¡ |js@t|tƒrD|‚dS )z� Handles a traits notification exception using the handler defined
            by the topmost stack entry for the corresponding thread.
        Né   r
   )ÚsysÚexc_infor'   r   r   Ú
isinstancer	   )r   ÚobjectÚ
trait_nameÚoldÚnewÚ
excp_classÚexcpZhandler_infor   r   r   Ú_handle_exception‹   s    ÿz.NotificationExceptionHandler._handle_exceptionc                 C   s‚   | j }t|tƒr&t ¡ j}| |¡}nt|ddƒ}|du r~| jdurP| jd }nt	| j
ddƒ}|g}t|tƒrx|||< n||_|S )z_ Returns the handler stack associated with the currently executing
            thread.
        r,   Nr
   F)r$   r5   Údictr   r   r   ÚgetÚgetattrr#   r   r)   r,   )r   r$   Úidr,   r   r   r   r   r'   —   s     


ÿ

z*NotificationExceptionHandler._get_handlersc                 C   s   |d j rtdƒ‚dS )zG Raises an exception if the specified handler stack is locked.
        r
   zLThe traits notification exception handler is locked. No changes are allowed.N)r   r	   r0   r   r   r   r(   ±   s    
ÿz(NotificationExceptionHandler._check_lockc                 C   s²   t  ¡ dd… \}}|tu rbt|jƒdkrb|jd dkrbt j d||||d tj	t  ¡ Ž ¡f ¡ | j
}|du r€t d¡ | _
}z| d||||f ¡ W n ty¬   Y n0 dS )	a   Logs any exceptions generated in a trait notification handler.

        This method defines the default notification exception handling
        behavior of traits. However, it can be completely overridden by pushing
        a new handler using the '_push_handler' method.
        Nr2   r   z maximum recursion depth exceededznException occurred in traits notification handler for object: %s, trait: %s, old value: %s, new value: %s.
%s
Ú ZtraitsziException occurred in traits notification handler for object: %s, trait: %s, old value: %s, new value: %s)r3   r4   ÚRuntimeErrorr.   r   Ú
__stderr__ÚwriteÚjoinÚ	tracebackÚformat_exceptionr"   ÚloggingÚ	getLoggerÚ	exceptionÚ	Exception)r   r6   r7   r8   r9   r:   r;   Úloggerr   r   r   r)   º   s8    	ÿþýûýÿ
þÿz+NotificationExceptionHandler._log_exception)NFFF)
r   r   r    r   r-   r1   r<   r'   r(   r)   r   r   r   r   r!   <   s    ÿ
3	r!   c                 C   s   | a |adS )aÊ   Set the global trait change event tracers.

    The global tracers are called whenever a trait change event is dispatched.
    There are two tracers: `pre_tracer` is called before the notification is
    sent; `post_tracer` is called after the notification is sent, even if the
    notification failed with an exception (in which case the `post_tracer` is
    called with a reference to the exception, then the exception is sent to
    the `notification_exception_handler`).

    The tracers should be a callable taking 5 arguments:
    ::
      tracer(obj, trait_name, old, new, handler)

    `obj` is the source object, on which trait `trait_name` was changed from
    value `old` to value `new`. `handler` is the function or method that will
    be notified of the change.

    The post-notification tracer also has a keyword argument, `exception`,
    that is `None` if no exception has been raised, and the a reference to the
    raise exception otherwise.
    ::
      post_tracer(obj, trait_name, old, new, handler, exception=None)

    Note that for static trait change listeners, `handler` is not a method, but
    rather the function before class creation, since this is the way Traits
    works at the moment.
    N©Ú_pre_change_event_tracerÚ_post_change_event_tracer)Ú
pre_tracerÚpost_tracerr   r   r   Úset_change_event_tracersó   s    rR   c                   C   s   t tfS )z= Get the currently active global trait change event tracers. rM   r   r   r   r   Úget_change_event_tracers  s    rS   c                   C   s   da dadS )z- Clear the global trait change event tracer. NrM   r   r   r   r   Úclear_change_event_tracers  s    rT   c              	   c   s:   t ƒ \}}t| |ƒ zdV  W t||ƒ nt||ƒ 0 dS )zA Context manager to temporarily change the global event tracers. N)rS   rR   )rP   rQ   Zold_pre_tracerZold_post_tracerr   r   r   Úchange_event_tracers"  s
    

rU   c                   @   s,   e Zd ZdZi Zdd„ Zdd„ Zdd„ ZdS )	Ú!AbstractStaticChangeNotifyWrappera   
    Concrete implementation must define the 'argument_transforms' class
    argument, a dictionary mapping the number of arguments in the event
    handler to a function that takes the arguments (obj, trait_name, old, new)
    and returns the arguments tuple for the actual handler.
    c                 C   s8   |j j}|dkr"td|j|f ƒ‚| j| | _|| _d S )Né   z�Invalid number of arguments for the static anytrait change notification handler: %s. A maximum of 4 arguments is allowed, but %s were specified.)Ú__code__Úco_argcountr	   r   Úargument_transformsÚargument_transformr   )r   r   Ú	arg_countr   r   r   r   7  s    ûÿz*AbstractStaticChangeNotifyWrapper.__init__c                 C   sº   t ||||ƒr¶|  ||||¡}tdur8t||||| jƒ z| j|Ž  W nP ty– } z8tdurtt||||| j|d� t||||ƒ W Y d}~n(d}~0 0 tdur¶t||||| jdd� dS )z- Dispatch to the appropriate handler method. N©rJ   )Ú_change_acceptedr[   rN   r   rK   rO   Úhandle_exception)r   r6   r7   r8   r9   r   Úer   r   r   Ú__call__F  s.    ÿÿ$úz*AbstractStaticChangeNotifyWrapper.__call__c                 C   s   dS )NFr   ©r   r   r   r   r   Úequalsh  s    z(AbstractStaticChangeNotifyWrapper.equalsN)r   r   r    Ú__doc__Zarguments_transformsr   ra   rc   r   r   r   r   rV   -  s
   "rV   c                   @   s0   e Zd Zdd„ dd„ dd„ dd„ dd„ dœZdS )	Ú!StaticAnytraitChangeNotifyWrapperc                 C   s   dS ©Nr   r   ©ÚobjÚnamer8   r9   r   r   r   Ú<lambda>r  ó    z*StaticAnytraitChangeNotifyWrapper.<lambda>c                 C   s   | fS r   r   rg   r   r   r   rj   s  rk   c                 C   s   | |fS r   r   rg   r   r   r   rj   t  rk   c                 C   s
   | ||fS r   r   rg   r   r   r   rj   u  rk   c                 C   s   | |||fS r   r   rg   r   r   r   rj   v  rk   ©r   r   r2   é   rW   N©r   r   r    rZ   r   r   r   r   re   l  s   ûre   c                   @   s0   e Zd Zdd„ dd„ dd„ dd„ dd„ dœZdS )	ÚStaticTraitChangeNotifyWrapperc                 C   s   dS rf   r   rg   r   r   r   rj   €  rk   z'StaticTraitChangeNotifyWrapper.<lambda>c                 C   s   | fS r   r   rg   r   r   r   rj   �  rk   c                 C   s   | |fS r   r   rg   r   r   r   rj   ‚  rk   c                 C   s
   | ||fS r   r   rg   r   r   r   rj   ƒ  rk   c                 C   s   | |||fS r   r   rg   r   r   r   rj   „  rk   rl   Nrn   r   r   r   r   ro   z  s   ûro   c                   @   sˆ   e Zd ZdZdd„ dd„ dd„ dd„ dd„ dœZdd
d„Zd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	S ) ÚTraitChangeNotifyWrapperzÙ Dynamic change notify wrapper.

    This class is in charge to dispatch trait change events to dynamic
    listener, typically created using the `on_trait_change` method, or
    the decorator with the same name.
    c                 C   s   dS rf   r   rg   r   r   r   rj   ”  rk   z!TraitChangeNotifyWrapper.<lambda>c                 C   s   |fS r   r   rg   r   r   r   rj   •  rk   c                 C   s   ||fS r   r   rg   r   r   r   rj   –  rk   c                 C   s
   | ||fS r   r   rg   r   r   r   rj   —  rk   c                 C   s   | |||fS r   r   rg   r   r   r   rj   ˜  rk   rl   Nc                 C   s   |   |||¡ d S r   )Úinit)r   r   ÚownerÚtargetr   r   r   r   ›  s    z!TraitChangeNotifyWrapper.__init__c                 C   sê   t |ƒtu r‚|j}|j}|d ur t || j¡| _|j| _	|| _
|jjd }|dkrdtd|j|f ƒ‚t | ƒj| _| j| | _|S n|d ur t || j¡| _|| _
|jj}|dkrÂtd|j|f ƒ‚d | _	|| _t | ƒj| _| j| | _|S )Nr   rW   zŽInvalid number of arguments for the dynamic trait change notification handler: %s. A maximum of 4 arguments is allowed, but %s were specified.)Útyper   Ú__func__Ú__self__ÚweakrefÚrefÚlistener_deletedr6   r   ri   rr   rX   rY   r	   Ú_notify_method_listenerÚnotify_listenerrZ   r[   r   Ú_notify_function_listener)r   r   rr   rs   Úfuncr6   r\   r   r   r   rq   ž  s@    ûÿûÿ	zTraitChangeNotifyWrapper.initc                 C   s   |   | ||||¡ dS )zª Dispatch to the appropriate method.

        We do explicit dispatch instead of assigning to the .__call__ instance
        attribute to avoid reference cycles.
        N)r{   ©r   r6   r7   r8   r9   r   r   r   ra   Ô  s    
z!TraitChangeNotifyWrapper.__call__c                 G   s   ||Ž  dS )z½ Dispatch the event to the listener.

        This method is normally the only one that needs to be overridden in
        a subclass to implement the subclass's dispatch mechanism.
        Nr   ©r   r   r   r   r   r   Údispatchà  s    z!TraitChangeNotifyWrapper.dispatchc                 C   sP   || u rdS t |ƒtu r<|jd ur<|j| jko:|j|  ¡ u S | jd u oN|| jkS )NT)rt   r   rv   r   ri   r6   r   rb   r   r   r   rc   è  s    ÿzTraitChangeNotifyWrapper.equalsc                 C   s4   z| j  | ¡ W n ty"   Y n0 d  | _| _ d S r   )rr   ÚremoveÚ
ValueErrorr6   )r   rx   r   r   r   ry   ó  s
    z)TraitChangeNotifyWrapper.listener_deletedc                 C   s
   d | _ d S r   )r6   r%   r   r   r   Údisposeý  s    z TraitChangeNotifyWrapper.disposec                 C   s®   |   ||||¡}tdur(t|||||ƒ z| j|g|¢R Ž  W nN tyŒ } z6tdurjt||||||d� t||||ƒ W Y d}~n&d}~0 0 tdurªt|||||dd� dS )ú: Prepare and dispatch a trait change event to a listener. Nr]   )r[   rN   r€   rK   rO   r_   )r   r6   r7   r8   r9   r   r   r`   r   r   r   Ú_dispatch_change_event   s    ÿ$ÿz/TraitChangeNotifyWrapper._dispatch_change_eventc                 C   sL   | j }|durHt||||ƒrH|ƒ }|durHt|| jƒ}|  |||||¡ dS ©z5 Dispatch a trait change event to a method listener. N)r6   r^   r?   ri   r…   ©r   r6   r7   r8   r9   Zobj_weak_refrh   Zlistenerr   r   r   rz     s    ÿ
ÿz0TraitChangeNotifyWrapper._notify_method_listenerc                 C   s&   t ||||ƒr"|  ||||| j¡ dS ©z7 Dispatch a trait change event to a function listener. N)r^   r…   r   r~   r   r   r   r|   ,  s    ÿz2TraitChangeNotifyWrapper._notify_function_listener)N)N)r   r   r    rd   rZ   r   rq   ra   r€   rc   ry   rƒ   r…   rz   r|   r   r   r   r   rp   ˆ  s"   û

6
rp   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	Ú ExtendedTraitChangeNotifyWrappera]   Change notify wrapper for "extended" trait change events..

    The "extended notifiers" are set up internally when using extended traits,
    to add/remove traits listeners when one of the intermediate traits changes.

    For example, in a listener for the extended trait `a.b`, we need to
    add/remove listeners to `a:b` when `a` changes.
    c                 C   sL   |   ||||¡}z| j|g|¢R Ž  W n  tyF   t||||ƒ Y n0 dS )r„   N)r[   r€   rK   r_   )r   r6   r7   r8   r9   r   r   r   r   r   r…   ?  s
    z7ExtendedTraitChangeNotifyWrapper._dispatch_change_eventc                 C   s>   | j }|dur:|ƒ }|dur:t|| jƒ}|  |||||¡ dS r†   )r6   r?   ri   r…   r‡   r   r   r   rz   K  s    
ÿz8ExtendedTraitChangeNotifyWrapper._notify_method_listenerc                 C   s   |   ||||| j¡ dS rˆ   )r…   r   r~   r   r   r   r|   [  s    z:ExtendedTraitChangeNotifyWrapper._notify_function_listenerN)r   r   r    rd   r…   rz   r|   r   r   r   r   r‰   5  s   	r‰   c                   @   s   e Zd ZdZdd„ ZdS )ÚFastUITraitChangeNotifyWrappera   Dynamic change notify wrapper, dispatching on the UI thread.

    This class is in charge to dispatch trait change events to dynamic
    listener, typically created using the `on_trait_change` method and the
    `dispatch` parameter set to 'ui' or 'fast_ui'.
    c                 G   s,   t  ¡ jtkr||Ž  nt|g|¢R Ž  d S r   r   r   r   r   r   r€   i  s    
z'FastUITraitChangeNotifyWrapper.dispatchN©r   r   r    rd   r€   r   r   r   r   rŠ   a  s   rŠ   c                   @   s   e Zd ZdZdd„ ZdS )ÚNewTraitChangeNotifyWrapperzû Dynamic change notify wrapper, dispatching on a new thread.

    This class is in charge to dispatch trait change events to dynamic
    listener, typically created using the `on_trait_change` method and the
    `dispatch` parameter set to 'new'.
    c                 G   s   t ||d� ¡  d S )N)rs   r   )r   Ústartr   r   r   r   r€   x  s    z$NewTraitChangeNotifyWrapper.dispatchNr‹   r   r   r   r   rŒ   p  s   rŒ   c                 C   sX   |t u rdS |  |d¡}|jtjjkrT|jtjkrTzt	||kƒW S  t
yR   Y n0 dS )a„   Return true if notifications should be emitted for the change.

    Parameters
    ----------
    object : HasTraits
        The object on which the trait is changed.
    name : str
        The name of the trait changed.
    old : any
        The old value
    new : any
        The new value

    Returns
    -------
    accepted : bool
        Whether the event should be emitted.
    Fr2   T)r   Z_traitrt   r   Útraitri   Zcomparison_moder   ZequalityÚboolrK   )r6   ri   r8   r9   rŽ   r   r   r   r^   |  s    
ÿr^   )NN)0rd   Ú
contextlibrH   r   r   r$   r   rF   Útypesr   rw   r3   Ú	constantsr   r   Z
trait_baser   Ztrait_errorsr	   r   r   r   r   r6   r   r!   Znotification_exception_handlerr-   Zpush_exception_handlerr1   Zpop_exception_handlerr<   r_   rN   rO   rR   rS   rT   ÚcontextmanagerrU   rV   re   ro   rp   r‰   rŠ   rŒ   r^   r   r   r   r   Ú<module>   sN   	 ,
"

? .,