
    \
jI                     h    d Z ddlZddlmZ ddlmZ dZd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)

    N)partial)
WeakMethodTc                       e Zd ZdZdS )EventExceptionzEAn exception raised when an event handler could not be attached.
    N)__name__
__module____qualname____doc__     F/DATA/AppData/hermes/venv/lib/python3.11/site-packages/pyglet/event.pyr   r      s         Dr   r   c                   ~    e Zd ZdZdZed             Zd Zd Zd Z	d Z
d Zd	 Zd
 Zd Zd Zed             Zd ZdS )EventDispatcherzQGeneric event dispatcher interface.

    See the module docstring for usage.
    r   c                 h    t          | d          sg | _        | j                            |           |S )aF  Register an event type with the dispatcher.

        Registering event types allows the dispatcher to validate event
        handler names as they are attached, and to search attached objects for
        suitable handlers.

        :Parameters:
            `name` : str
                Name of the event to register.

        event_types)hasattrr   append)clsnames     r   register_event_typez#EventDispatcher.register_event_type   s8     sM** 	! COt$$$r   c                     t          | j                  t          u rg | _        | j                            di             | j        |i | dS )at  Push a level onto the top of the handler stack, then attach zero or
        more event handlers.

        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)type_event_stacktupleinsertset_handlers)selfargskwargss      r   push_handlerszEventDispatcher.push_handlers   s[     !""e++ "D 	  B'''4*6*****r   c           
   #     K   |D ]}t          j        |          re|j        }|| j        vrt	          d|z            t          j        |          r(|t          |t          | j        |                    fV  t||fV  {t          |          D ]B}|| j        v r7t          ||          }|t          |t          | j        |                    fV  C|                                D ]b\  }}|| j        vrt	          d|z            t          j        |          r(|t          |t          | j        |                    fV  \||fV  cdS )z^Implement handler matching on arguments for set_handlers and
        remove_handlers.
        zUnknown event "%s"N)inspect	isroutiner   r   r   ismethodr   r   _remove_handlerdirgetattritems)r   r   r   objr   methhandlers          r   _get_handlerszEventDispatcher._get_handlers   s       	Z 	ZC %% Z|t///()=)DEEE#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+++$%9D%@AAA(( $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   c                 l    t          | j                  t          u ri g| _        || j        d         |<   dS )zAttach a single event handler.

        :Parameters:
            `name` : str
                Name of the event type to attach to.
            `handler` : callable
                Event handler to attach.

        r   N)r   r   r   )r   r   r+   s      r   r.   zEventDispatcher.set_handler   s<     !""e++!#D%,!T"""r   c                 *    | j         rnJ | j         d= dS )z;Pop the top level of event handlers off the stack.
        zNo handlers pushedr   N)r   )r   s    r   pop_handlerszEventDispatcher.pop_handlers  s'      9999a   r   c                     t                               ||                     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`.
        c                  r    j         D ]-} D ](\  }}	 | |         |k    r| c c S # t          $ r Y %w xY w.d S Nr   KeyError)framer   r+   handlersr   s      r   
find_framez3EventDispatcher.remove_handlers.<locals>.find_frame(  s}    *  %-  MD' ;'11#(LLLLL 2#   	 s   &
33N)listr,   r6   r   remove)r   r   r   r9   r7   r   r+   r8   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 )aW  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.

        :Parameters:
            `name` : str
                Name of the event type to remove.
            `handler` : callable
                Event handler to remove.
        Nr5   r   r   r+   r7   s       r   remove_handlerzEventDispatcher.remove_handlerC  si    " & 	 	E;'))dEE *    	 	s   
++c                     t          | j                  D ]1}||v r+||         |k    r||= |s| j                            |           2d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   r;   r>   s       r   r%   zEventDispatcher._remove_handler\  sf     $+,, 	4 	4Eu}}t!7!7$K 4%,,U333		4 	4r   c           	         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 a single event to the attached handlers.

        The event is propagated to all handlers from from the top of the stack
        until one returns `EVENT_HANDLED`.  This method should be used only by
        :py:class:`~pyglet.event.EventDispatcher` implementors; applications should call
        the ``dispatch_events`` method.

        Since pyglet 1.2, the method returns `EVENT_HANDLED` if an event
        handler returned `EVENT_HANDLED` or `EVENT_UNHANDLED` if all events
        returned `EVENT_UNHANDLED`.  If no matching event handlers are in the
        stack, ``False`` is returned.

        :Parameters:
            `event_type` : str
                Name of the event.
            `args` : sequence
                Arguments to pass to the event handler.

        :rtype: bool or None
        :return: (Since pyglet 1.2) `EVENT_HANDLED` if an event handler
            returned `EVENT_HANDLED`; `EVENT_UNHANDLED` if one or more event
            handlers were invoked but returned only `EVENT_UNHANDLED`;
            otherwise ``False``.  In pyglet 1.1 and earlier, the return value
            is always ``None``.

        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_HANDLED	TypeError_raise_dispatch_exceptionr'   AttributeErrorcallableEVENT_UNHANDLED)	r   
event_typer   invokedr7   r+   	exceptioneevent_ops	            r   dispatch_eventzEventDispatcher.dispatch_eventi  s;   6 t]++ 	
 	
A	
 	
+
 T----6@jj$$$HXHXY .--  $+,, 	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                 V   t          |          }t          j        |          }|j        }|j        }|j        }t          |          }	t          j        |          r|j        r|	dz  }	|rt          |	|          }	|	|cxk    r|	t          |          z
  k    rn n|r|}	|	|k    rt          j	        |          st          j        |          r%d|j
         d|j        j         d|j        j         }
nt          |          }
t          d|  dt          |           d|
 d|	 d		          |)
N   'z' at :zThe 'z' event was dispatched with z arguments,
but your handler z accepts only z arguments.)lenr"   getfullargspecr   varargsdefaultsr$   __self__max
isfunctionr   __code__co_filenameco_firstlinenoreprrE   )rJ   r   r+   rL   n_argsargspecshandler_argshandler_varargshandler_defaultsn_handler_argsdescrs              r   rF   z)EventDispatcher._raise_dispatch_exception  s    T )'22}"*#,\** G$$ 	 )9 	 aN  	9 88N FLLLLns;K7L7L&LLLLLLQaL#NV##!'** &g.>w.G.G &sG,ss73C3OssRYRbRqssW aJ a aCPTII a a05a aESa a a b b b Or   c                 "    t          |          dk    r fd}|S t          j        |d                   r-|d         }|j                             |           |d         S t          |d         t                    r|d          fd}|S dS )a7  Function decorator for an event handler.

        Usage::

            win = window.Window()

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

        or::

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

        r   c                 B    | j         }                    ||            | S r4   )r   r.   )func	func_namer   s     r   	decoratorz(EventDispatcher.event.<locals>.decorator  s%     M	  D111r   c                 4                         |            | S r4   )r.   )rh   r   r   s    r   rj   z(EventDispatcher.event.<locals>.decorator  s      t,,,r   N)rT   r"   r#   r   r.   rC   str)r   r   rj   rh   r   s   `   @r   eventzEventDispatcher.event  s    $ t99>>    
 tAw'' 	7D=DT4(((7NQ%% 	7D      	 	r   N)r   r   r	   r
   r   classmethodr   r    r,   r   r.   r1   r<   r?   r%   rO   staticmethodrF   rm   r   r   r   r   r      s         
 L  ["+ + +"$ $ $<, , ,- - - ! ! !*, *, *,X  24 4 4D D DL * * \*X% % % % %r   r   )r
   r"   	functoolsr   weakrefr   rD   rI   	Exceptionr   r   r   r   r   <module>rs      s   Hu un             	 	 	 	 	Y 	 	 	W W W W W W W W W Wr   