
    ^j	K                        d Z ddlmZ ddlZddlZddlmZ ddlm	Z	m
Z
mZ ddlmZ ddlZe	r
ddlmZmZmZ dZdZee
d         df         Z G d	 d
e          Z G d d          ZdS )a  Event dispatch framework.

All objects that produce events in pyglet implement :py:class:`~pyglet.event.EventDispatcher`,
providing a consistent interface for registering and manipulating event
handlers.  A commonly used event dispatcher is `pyglet.window.Window`.

Event types
===========

For each event dispatcher there is a set of events that it dispatches; these
correspond with the type of event handlers you can attach.  Event types are
identified by their name, for example, ''on_resize''.  If you are creating a
new class which implements :py:class:`~pyglet.event.EventDispatcher`, you must call
`EventDispatcher.register_event_type` for each event type.

Attaching event handlers
========================

An event handler is simply a function or method.  You can attach an event
handler by setting the appropriate function on the instance::

    def on_resize(width, height):
        # ...
    dispatcher.on_resize = on_resize

There is also a convenience decorator that reduces typing::

    @dispatcher.event
    def on_resize(width, height):
        # ...

You may prefer to subclass and override the event handlers instead::

    class MyDispatcher(DispatcherClass):
        def on_resize(self, width, height):
            # ...

Event handler stack
===================

When attaching an event handler to a dispatcher using the above methods, it
replaces any existing handler (causing the original handler to no longer be
called).  Each dispatcher maintains a stack of event handlers, allowing you to
insert an event handler "above" the existing one rather than replacing it.

There are two main use cases for "pushing" event handlers:

* Temporarily intercepting the events coming from the dispatcher by pushing a
  custom set of handlers onto the dispatcher, then later "popping" them all
  off at once.
* Creating "chains" of event handlers, where the event propagates from the
  top-most (most recently added) handler to the bottom, until a handler
  takes care of it.

Use `EventDispatcher.push_handlers` to create a new level in the stack and
attach handlers to it.  You can push several handlers at once::

    dispatcher.push_handlers(on_resize, on_key_press)

If your function handlers have different names to the events they handle, use
keyword arguments::

    dispatcher.push_handlers(on_resize=my_resize, on_key_press=my_key_press)

After an event handler has processed an event, it is passed on to the
next-lowest event handler, unless the handler returns `EVENT_HANDLED`, which
prevents further propagation.

To remove all handlers on the top stack level, use
`EventDispatcher.pop_handlers`.

Note that any handlers pushed onto the stack have precedence over the
handlers set directly on the instance (for example, using the methods
described in the previous section), regardless of when they were set.
For example, handler ``foo`` is called before handler ``bar`` in the following
example::

    dispatcher.push_handlers(on_resize=foo)
    dispatcher.on_resize = bar

Dispatching events
==================

pyglet uses a single-threaded model for all application code.  Event
handlers are only ever invoked as a result of calling
EventDispatcher.dispatch_events`.

It is up to the specific event dispatcher to queue relevant events until they
can be dispatched, at which point the handlers are called in the order the
events were originally generated.

This implies that your application runs with a main loop that continuously
updates the application state and checks for new events::

    while True:
        dispatcher.dispatch_events()
        # ... additional per-frame processing

Not all event dispatchers require the call to ``dispatch_events``; check with
the particular class documentation.

.. note::

    In order to prevent issues with garbage collection, the
    :py:class:`~pyglet.event.EventDispatcher` class only holds weak
    references to pushed event handlers. That means the following example
    will not work, because the pushed object will fall out of scope and be
    collected::

        dispatcher.push_handlers(MyHandlerClass())

    Instead, you must make sure to keep a reference to the object before pushing
    it. For example::

        my_handler_instance = MyHandlerClass()
        dispatcher.push_handlers(my_handler_instance)

    )annotationsN)partial)TYPE_CHECKINGLiteralUnion)
WeakMethod)AnyCallable	GeneratorTc                      e Zd ZdZdS )EventExceptionz@An exception raised when an event handler could not be attached.N)__name__
__module____qualname____doc__     G/home/agentuser/manim-venv/lib/python3.11/site-packages/pyglet/event.pyr   r      s        JJJJr   r   c                      e Zd ZU dZded<   dZded<   e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&S )/EventDispatcherzQGeneric event dispatcher interface.

    See the module docstring for usage.
    listevent_typesr   ztuple | list_event_stackclstype[object]namestrreturnc                h    t          | d          sg | _        | j                            |           |S )a1  Register an event type with the dispatcher.

        Before dispatching events, they must first be registered by name.
        Registering event types allows the dispatcher to validate event
        handler names as they are attached, and to search attached objects
        for suitable handlers.
        r   )hasattrr   append)r   r   s     r   register_event_typez#EventDispatcher.register_event_type   s8     sM** 	! COt$$$r   argsr	   kwargsNonec                    t          | j                  t          u rg | _        | j                            di             | j        |i | dS )a  Push a new level onto the handler stack, and add 0 or more handlers.

        This method first pushes a new level to the top of the handler stack.
        It then attaches any handlers that were passed to this new level.

        If keyword arguments are given, they name the event type to attach.
        Otherwise, a callable's ``__name__`` attribute will be used. Any
        other object may also be specified, in which case it will be searched
        for callables with event names.
        r   N)typer   tupleinsertset_handlers)selfr#   r$   s      r   push_handlerszEventDispatcher.push_handlers   s[     !""e++ "D 	  B'''4*6*****r   dict+Generator[tuple[str, Callable], None, None]c           
   #    K   |D ]}t          j        |          rh|j        }|| j        vrd| d}t	          |          t          j        |          r(|t          |t          | j        |                    fV  w||fV  ~t          |          D ]B}|| j        v r7t          ||          }|t          |t          | j        |                    fV  C|                                D ]e\  }}|| j        vrd| d}t	          |          t          j        |          r(|t          |t          | j        |                    fV  _||fV  fdS )zMImplement handler matching on arguments for set_handlers and remove_handlers.zUnknown event ""N)inspect	isroutiner   r   r   ismethodr   r   _remove_handlerdirgetattritems)r+   r#   r$   objr   msgmethhandlers           r   _get_handlerszEventDispatcher._get_handlers   s      	Z 	ZC %% ZLt///3D333C(---#C(( $
38Ld0S0S T TTTTTT)OOOO  HH Z ZDt///&sD11"JtWT=QSW5X5X$Y$YYYYYZ
 $\\^^ 	$ 	$MD'4+++////$S)))(( $Jw8Ld0S0STTTTTTTGm####	$ 	$r   c                    t          | j                  t          u ri g| _        |                     ||          D ]\  }}|                     ||           dS )zAttach one or more event handlers to the top level of the handler stack.

        See :py:meth:`~pyglet.event.EventDispatcher.push_handlers` for the accepted
        argument types.
        N)r'   r   r(   r<   set_handler)r+   r#   r$   r   r;   s        r   r*   zEventDispatcher.set_handlers   sj     !""e++!#D!//f== 	, 	,MD'T7++++	, 	,r   r;   r
   c                l    t          | j                  t          u ri g| _        || j        d         |<   dS )zAttach a single event handler.r   N)r'   r   r(   )r+   r   r;   s      r   r>   zEventDispatcher.set_handler   s<     !""e++!#D%,!T"""r   c                8    | j         s
J d            | j         d= dS )z2Pop the top level of event handlers off the stack.zNo handlers pushedr   Nr   )r+   s    r   pop_handlerszEventDispatcher.pop_handlers   s+     66"666 a   r   c                    t                               ||                    d fd} |            }|sdS D ]%\  }}	 ||         |k    r||= # t          $ r Y "w xY w|s j                            |           dS dS )a  Remove event handlers from the event stack.

        See :py:meth:`~pyglet.event.EventDispatcher.push_handlers` for the
        accepted argument types. All handlers are removed from the first stack
        frame that contains any of the given handlers. No error is raised if
        any handler does not appear in that frame, or if no stack frame
        contains any of the given handlers.

        If the stack frame is empty after removing the handlers, it is
        removed from the stack.  Note that this interferes with the expected
        symmetry of :py:meth:`~pyglet.event.EventDispatcher.push_handlers` and
        :py:meth:`~pyglet.event.EventDispatcher.pop_handlers`.
        r   dict | Nonec                 Z    j         D ]!} D ]\  }}|| vr
| |         |k    r| c c S "d S NrA   )_frame_name_handlerhandlersr+   s      r   
find_framez3EventDispatcher.remove_handlers.<locals>.find_frame  sc    + & &'/ & &OE8F** e}00% 1&
 4r   N)r   rD   )r   r<   KeyErrorr   remove)r+   r#   r$   rK   framer   r;   rJ   s   `      @r   remove_handlerszEventDispatcher.remove_handlers   s     **48899	 	 	 	 	 	 	 
  	F & 	 	MD';'))d     	,$$U+++++	, 	,s   A
A A c                `    | j         D ]%}	 ||         |k    r||=  dS # t          $ r Y "w xY wdS )a  Remove a single event handler.

        The given event handler is removed from the first handler stack frame
        it appears in.  The handler must be the exact same callable as passed
        to `set_handler`, `set_handlers` or
        :py:meth:`~pyglet.event.EventDispatcher.push_handlers`; and the name
        must match the event type it is bound to.

        No error is raised if the event handler is not set.
        N)r   rL   r+   r   r;   rN   s       r   remove_handlerzEventDispatcher.remove_handler  si     & 	 	E;'))dEE *    	 	s   
++c                    t          | j                  D ]C}||v r=	 ||         |k    r||= |s| j                            |           3# t          $ r Y ?w xY wDdS )zUsed internally to remove all handler instances for the given event name.

        This is normally called from a dead ``WeakMethod`` to remove itself from the
        event stack.
        N)r   r   rM   	TypeErrorrQ   s       r   r4   zEventDispatcher._remove_handler2  s     $+,, 
	 
	Eu}}T{g--!$K$ < -44U;;;    D 
	 
	s   +A
AA
event_typebool | Nonec           	        t          | d          s
J d            || j        v sJ | d|  d| j                     d}t          | j                  D ]~}|                    |d          }|st          |t                    r |            }|J 	 d} || r	t          c S P# t          $ r"}| 	                    ||||           Y d}~wd}~ww xY w	  t          | |          | rt          S 	 d}nq# t          $ r,}t          | |d          }t          |          r|Y d}~n@d}~wt          $ r0}| 	                    ||t          | |          |           Y d}~nd}~ww xY w|rt          S dS )a  Dispatch an event to the attached event handlers.

        The event is propagated to all registered event handlers
        in the stack, starting and the top and going down. If any
        registered event handler returns ``EVENT_HANDLED``, no further
        handlers down the stack will receive this event.

        This method has several possible return values. If any event
        handler has returned ``EVENT_HANDLED``, then this method will
        also return ``EVENT_HANDLED``. If not, this method will return
        ``EVENT_UNHANDLED``. If there were no events registered to
        receive this event, ``False`` is returned.

        Returns:
            ``EVENT_HANDLED`` if any event handler returned ``EVENT_HANDLED``;
            ``EVENT_UNHANDLED`` if one or more event handlers were invoked
            without any of them returning `EVENT_HANDLED`; ``False`` if no
            event handlers were registered.
        r   zNo events registered on this EventDispatcher. You need to register events with the class method EventDispatcher.register_event_type('event_name').z not found in z.event_types == FNT)r    r   r   r   get
isinstancer   EVENT_HANDLEDrT   _raise_dispatch_exceptionr6   AttributeErrorcallableEVENT_UNHANDLED)	r+   rU   r#   invokedrN   r;   	exceptioneevent_ops	            r   dispatch_eventzEventDispatcher.dispatch_eventE  s;   ( t]++ 	
 	
A	
 	
+
 T----*/t/tD/t/tbfbr/t/t--- $+,, 	U 	UEii
D11G ':.. +!'))***U7D> )(((() U U U..z4)TTTTTTTTU
	(wtZ(($/ %$$% GG  	 	 	tZ66H!!      	c 	c 	c**:tWT:=V=VXabbbbbbbb	c
  	#""us<   B!!
C+CCC/ /
E9"D  E-&EEc                @    t          j        j        j        | |g|R   dS )a  Post an event to the main application thread.

        Unlike the :py:meth:`~pyglet.event.EventDispatcher.dispatch_event`
        method, this method does not dispatch events directly. Instead, it
        hands off the dispatch call to the main application thread. This
        ensures that any event handlers are also executed in the main thread.

        This method aliases :py:meth:`~pyglet.app.PlatformEventLoop.post_event`,
        which can be seen for more information on behavior.
        N)pygletappplatform_event_loop
post_event)r+   rU   r#   s      r   rh   zEventDispatcher.post_event  s*     	
&1$
JTJJJJJJr   r`   	Exceptionc                   t          |          }t          j        |          }|j        }|j        }|j        }	t          |          }
t          j        |          r|j        r|
dz  }
|rt          |
|          }
|	r"|
|cxk    r|
t          |	          z
  k    rn n|}
|
|k    rt          j	        |          st          j        |          rGt          j                            |j        j                  \  }}d|j         d| d|j        j         }nt#          |          }d|v r|                    d           | j        j         d| }d| d| d	t)          |           d
| d|
 d| }t+          |          |)N   'z' in :r+   .zThe 'z' event was dispatched with z arguments:  z,
but your handler z is written to expect z arguments: )lenr1   getfullargspecr#   varargsdefaultsr3   __self__max
isfunctionospathsplit__code__co_filenamer   co_firstlinenoreprrM   	__class__r   rT   )r+   rU   r#   r;   r`   n_argsargspecshandler_argshandler_varargshandler_defaultsn_handler_args_filenamedescrcaller_namer9   s                   r   r[   z)EventDispatcher._raise_dispatch_exception  s    T )'22}"*#,\** G$$ 	 )9 	 aN  	9 88N  	$ a a a a>CP`LaLa;a a a a a a#N V##!'** &g.>w.G.G & gmmG,<,HII8_G,__8__g>N>]__W%%##F+++!^4CCzCCKo; o oF o oY]^bYcYc o o',o oDRo o`lo oCC.. r   c                    t          | j                  D ]F\  }}t          d|            |                                D ]\  }}t          d| d|            Gd S )Nzlevel: z - 'z': )	enumerater   printr7   )r+   levelrJ   rU   r;   s        r   _dump_handlerszEventDispatcher._dump_handlers  s    ():;; 	7 	7OE8#E##$$$'/~~'7'7 7 7#
G5Z55G5566667	7 	7r   c                D    t          |          dk    rd	 fd}|S t          j        |d                   r-|d         }|j                             |           |d         S t          |d         t                    r|d         d	 fd}|S d}t          |          )
a?  Function decorator for an event handler.

        If the function or method name matches the event name,
        the decorator can be added without arguments. Likewise,
        if the name does not match, you can provide the target
        event name by passing it as an argument.

        Name matches::

            win = window.Window()

            @win.event
            def on_resize(self, width, height):
                # ...

        Name does not match::

            @win.event('on_resize')
            def foo(self, width, height):
                # ...

        r   functionr
   r   c                B    | j         }                    ||            | S rF   )r   r>   )r   	func_namer+   s     r   	decoratorz(EventDispatcher.event.<locals>.decorator  s&    $-	  H555r   c                4                         |            | S rF   )r>   )r   r   r+   s    r   r   z(EventDispatcher.event.<locals>.decorator  s      x000r   z2Argument must be the name of the event as a `str`.N)r   r
   r   r
   )ro   r1   r2   r   r>   rY   r   rT   )r+   r#   r   funcr9   r   s   `    @r   eventzEventDispatcher.event  s    0 t99>>           
  T!W%% 	7D=DT4(((7N d1gs## 	7D              Bnnr   N)r   r   r   r   r   r   )r#   r	   r$   r	   r   r%   )r#   r   r$   r-   r   r.   )r   r   r;   r
   r   r%   )r   r%   )rU   r   r#   r	   r   rV   )
rU   r   r#   r	   r;   r
   r`   ri   r   r%   )r#   r	   r   r
   )r   r   r   r   __annotations__r   classmethodr"   r,   r<   r*   r>   rB   rO   rR   r4   rc   rh   r[   r   r   r   r   r   r   r      sh          !#L####   [+ + + +&$ $ $ $<, , , ,- - - -! ! ! !*, *, *, *,X   &   &< < < <|K K K K0 0 0 0d7 7 7 73 3 3 3 3 3r   r   )r   
__future__r   r1   os.pathrv   	functoolsr   typingr   r   r   weakrefr   re   r	   r
   r   rZ   r^   EVENT_HANDLE_STATEri   r   r   r   r   r   <module>r      s7  u ul # " " " " "         0 0 0 0 0 0 0 0 0 0        0////////// 74=$./ K K K K KY K K Ko o o o o o o o o or   