| 1 |
.. _guide_events: |
| 2 |
|
| 3 |
Event dispatching & handling |
| 4 |
============================ |
| 5 |
|
| 6 |
The :py:mod:`pyglet.event` module provides a framework for uniformly dispatching |
| 7 |
and handling events. For our purposes, an "event dispatcher" is an object that has |
| 8 |
events it needs to notify other objects about, and an "event handler" is some code |
| 9 |
(a function or method) that can be registered (or "attached") to receive those events. |
| 10 |
|
| 11 |
Event Dispatchers are created by subclassing the :py:class:`~pyglet.event.EventDispatcher` |
| 12 |
base class. Many of pyglet's built-in modules, such as :py:mod:`pyglet.window`, |
| 13 |
:py:mod:`pyglet.media`, :py:mod:`pyglet.app`, :py:mod:`pyglet.text`, :py:mod:`pyglet.input`, |
| 14 |
:py:mod:`pyglet.gui` and others make use of this pattern. You can also reuse this in |
| 15 |
your own classes easily. |
| 16 |
|
| 17 |
Event handlers are simply functions or methods that are written to accept the same |
| 18 |
arguments as the dispatched event. Event handlers can be registered or unregistered |
| 19 |
during runtime. More than one handler can be registered to receive the same events, |
| 20 |
which is described in the following sections. Event dispatchers can *optionally* have |
| 21 |
default handlers for some of their events. Your own handlers can replace these entirely, |
| 22 |
or just be added on. |
| 23 |
|
| 24 |
|
| 25 |
Setting event handlers |
| 26 |
---------------------- |
| 27 |
|
| 28 |
For an example, lets look at the :py:class:`~pyglet.window.Window` class. |
| 29 |
:py:class:`~pyglet.window.Window` subclasses :py:class:`~pyglet.event.EventDispatcher` |
| 30 |
and, being a Window, has a variety of different events which it dispatches. |
| 31 |
For instance, the :py:meth:`pyglet.window.Window.on_resize` event. Every time a |
| 32 |
resizeable Window is resized (and once when first created), this event is dispatched |
| 33 |
with two parameters: ``(width, height)``. Therefore, an event handler for this event |
| 34 |
should be written to accept these two values. For example:: |
| 35 |
|
| 36 |
def on_resize(width, height): |
| 37 |
pass |
| 38 |
|
| 39 |
There are a few different ways in which event handlers can be attached to receive them. |
| 40 |
The simplest way is to directly attach the event handler to the corresponding attribute |
| 41 |
on the object. This will completely replace the default event handler:: |
| 42 |
|
| 43 |
window = pyglet.window.Window() |
| 44 |
|
| 45 |
def on_resize(width, height): |
| 46 |
# Set some custom projection |
| 47 |
|
| 48 |
window.on_resize = on_resize |
| 49 |
|
| 50 |
Sometimes replacing the default handler is desired, but not in all cases. |
| 51 |
For example the default `Window.on_resize` handler is responsible for setting up a |
| 52 |
orthographic 2D projection for drawing graphics. If you replace it entirely, you must |
| 53 |
also handle setting the projection yourself. |
| 54 |
|
| 55 |
Another way to replace a default event handler is when subclassing pyglet objects. |
| 56 |
This is common do do with Window class, as shown in :ref:`guide_subclassing-window`. |
| 57 |
If your methods have the same name as the default event, they will be replaced:: |
| 58 |
|
| 59 |
class MyWindow(pyglet.window.Window): |
| 60 |
def on_resize(self, width, height): |
| 61 |
# set a custom projection there |
| 62 |
|
| 63 |
|
| 64 |
You can of course still call the default handler with `super()`, and then add |
| 65 |
your custom code before/after that:: |
| 66 |
|
| 67 |
class MyWindow(pyglet.window.Window): |
| 68 |
|
| 69 |
def on_resize(self, width, height): |
| 70 |
super().on_resize(width, height) |
| 71 |
# do something else |
| 72 |
|
| 73 |
The event decorator |
| 74 |
^^^^^^^^^^^^^^^^^^^ |
| 75 |
|
| 76 |
Instead of replacing default handlers, you can just also add an additional handler. |
| 77 |
pyglet provides a shortcut using the :py:class:`~pyglet.event.EventDispatcher.event` |
| 78 |
decorator. Your custom event handler will run, followed by the default event handler:: |
| 79 |
|
| 80 |
window = window.Window() |
| 81 |
|
| 82 |
@window.event |
| 83 |
def on_resize(width, height): |
| 84 |
print(f"Window was resized to: {width}x{height}") |
| 85 |
|
| 86 |
or if your handler has a different name, pass the event name to the decorator:: |
| 87 |
|
| 88 |
@window.event('on_resize') |
| 89 |
def my_resize_handler(width, height): |
| 90 |
pass |
| 91 |
|
| 92 |
|
| 93 |
In most simple cases, the :py:class:`~pyglet.event.EventDispatcher.event` |
| 94 |
decorator is most convenient. One limitation of using the decorator, |
| 95 |
however, is that you can only add one additional event handler. |
| 96 |
If you want to add multiple additional event handlers, the next section |
| 97 |
describes how to accomplish that. |
| 98 |
|
| 99 |
|
| 100 |
Stacking event handlers |
| 101 |
----------------------- |
| 102 |
|
| 103 |
It is often convenient to attach more than one event handler for an event. |
| 104 |
:py:class:`~pyglet.event.EventDispatcher` allows you to stack event handlers |
| 105 |
upon one another, rather than replacing them outright. The event will |
| 106 |
propagate from the top of the stack to the bottom, but can be stopped |
| 107 |
by any handler along the way by returning `pyglet.event.EVENT_HANDLED`. |
| 108 |
|
| 109 |
To push an event handler onto the stack, |
| 110 |
use the :py:meth:`~pyglet.event.EventDispatcher.push_handlers` method:: |
| 111 |
|
| 112 |
def on_key_press(symbol, modifiers): |
| 113 |
if symbol == key.SPACE: |
| 114 |
fire_laser() |
| 115 |
|
| 116 |
window.push_handlers(on_key_press) |
| 117 |
|
| 118 |
One use for pushing handlers instead of setting them is to handle different |
| 119 |
parameterisations of events in different functions. In the above example, if |
| 120 |
the spacebar is pressed, the laser will be fired. After the event handler |
| 121 |
returns control is passed to the next handler on the stack, which on a |
| 122 |
:py:class:`~pyglet.window.Window` is a function that checks for the ESC key |
| 123 |
and sets the ``has_exit`` attribute if it is pressed. By pushing the event |
| 124 |
handler instead of setting it, the application keeps the default behaviour |
| 125 |
while adding additional functionality. |
| 126 |
|
| 127 |
You can prevent the remaining event handlers in the stack from receiving the |
| 128 |
event by returning a true value. The following event handler, when pushed |
| 129 |
onto the window, will prevent the escape key from exiting the program:: |
| 130 |
|
| 131 |
def on_key_press(symbol, modifiers): |
| 132 |
if symbol == key.ESCAPE: |
| 133 |
return True |
| 134 |
|
| 135 |
window.push_handlers(on_key_press) |
| 136 |
|
| 137 |
You can push more than one event handler at a time, which is especially useful |
| 138 |
when coupled with the :py:meth:`~pyglet.event.EventDispatcher.pop_handlers` |
| 139 |
function. In the following example, when the game starts some additional |
| 140 |
event handlers are pushed onto the stack. When the game ends (perhaps |
| 141 |
returning to some menu screen) the handlers are popped off in one go:: |
| 142 |
|
| 143 |
def start_game(): |
| 144 |
def on_key_press(symbol, modifiers): |
| 145 |
print('Key pressed in game') |
| 146 |
return True |
| 147 |
|
| 148 |
def on_mouse_press(x, y, button, modifiers): |
| 149 |
print('Mouse button pressed in game') |
| 150 |
return True |
| 151 |
|
| 152 |
window.push_handlers(on_key_press, on_mouse_press) |
| 153 |
|
| 154 |
def end_game(): |
| 155 |
window.pop_handlers() |
| 156 |
|
| 157 |
Note that you do not specify which handlers to pop off the stack -- the entire |
| 158 |
top "level" (consisting of all handlers specified in a single call to |
| 159 |
:py:meth:`~pyglet.event.EventDispatcher.push_handlers`) is popped. |
| 160 |
|
| 161 |
You can apply the same pattern in an object-oriented fashion by grouping |
| 162 |
related event handlers in a single class. In the following example, a |
| 163 |
``GameEventHandler`` class is defined. An instance of that class can be |
| 164 |
pushed on and popped off of a window:: |
| 165 |
|
| 166 |
class GameEventHandler: |
| 167 |
def on_key_press(self, symbol, modifiers): |
| 168 |
print('Key pressed in game') |
| 169 |
return True |
| 170 |
|
| 171 |
def on_mouse_press(self, x, y, button, modifiers): |
| 172 |
print('Mouse button pressed in game') |
| 173 |
return True |
| 174 |
|
| 175 |
game_handlers = GameEventHandler() |
| 176 |
|
| 177 |
def start_game() |
| 178 |
window.push_handlers(game_handlers) |
| 179 |
|
| 180 |
def stop_game() |
| 181 |
window.pop_handlers() |
| 182 |
|
| 183 |
.. note:: |
| 184 |
|
| 185 |
In order to prevent issues with garbage collection, the |
| 186 |
:py:class:`~pyglet.event.EventDispatcher` class only holds weak |
| 187 |
references to pushed event handlers. That means the following example |
| 188 |
will not work, because the pushed object will fall out of scope and be |
| 189 |
collected:: |
| 190 |
|
| 191 |
dispatcher.push_handlers(MyHandlerClass()) |
| 192 |
|
| 193 |
Instead, you must make sure to keep a reference to the object before pushing |
| 194 |
it. For example:: |
| 195 |
|
| 196 |
my_handler_instance = MyHandlerClass() |
| 197 |
dispatcher.push_handlers(my_handler_instance) |
| 198 |
|
| 199 |
Creating your own event dispatcher |
| 200 |
---------------------------------- |
| 201 |
|
| 202 |
pyglet provides the :py:class:`~pyglet.window.Window`, |
| 203 |
:py:class:`~pyglet.media.player.Player`, and other event dispatchers, |
| 204 |
but exposes a public interface for creating and dispatching your own events. |
| 205 |
|
| 206 |
The steps for creating an event dispatcher are: |
| 207 |
|
| 208 |
1. Subclass :py:class:`~pyglet.event.EventDispatcher` |
| 209 |
2. Call the :py:meth:`~pyglet.event.EventDispatcher.register_event_type` |
| 210 |
class method on your subclass for each event your subclass will recognise. |
| 211 |
3. Call :py:meth:`~pyglet.event.EventDispatcher. dispatch_event` to create and |
| 212 |
dispatch an event as needed. |
| 213 |
|
| 214 |
In the following example, a hypothetical GUI widget provides several events:: |
| 215 |
|
| 216 |
class ClankingWidget(pyglet.event.EventDispatcher): |
| 217 |
def clank(self): |
| 218 |
self.dispatch_event('on_clank') |
| 219 |
|
| 220 |
def click(self, clicks): |
| 221 |
self.dispatch_event('on_clicked', clicks) |
| 222 |
|
| 223 |
def on_clank(self): |
| 224 |
print('Default clank handler.') |
| 225 |
|
| 226 |
ClankingWidget.register_event_type('on_clank') |
| 227 |
ClankingWidget.register_event_type('on_clicked') |
| 228 |
|
| 229 |
Event handlers can then be attached as described in the preceding sections:: |
| 230 |
|
| 231 |
widget = ClankingWidget() |
| 232 |
|
| 233 |
@widget.event |
| 234 |
def on_clank(): |
| 235 |
pass |
| 236 |
|
| 237 |
@widget.event |
| 238 |
def on_clicked(clicks): |
| 239 |
pass |
| 240 |
|
| 241 |
def override_on_clicked(clicks): |
| 242 |
pass |
| 243 |
|
| 244 |
widget.push_handlers(on_clicked=override_on_clicked) |
| 245 |
|
| 246 |
The :py:class:`~pyglet.event.EventDispatcher` takes care of propagating the |
| 247 |
event to all attached handlers or ignoring it if there are no handlers for |
| 248 |
that event. |
| 249 |
|
| 250 |
There is zero instance overhead on objects that have no event handlers |
| 251 |
attached (the event stack is created only when required). This makes |
| 252 |
:py:class:`~pyglet.event.EventDispatcher` suitable for use even on light-weight |
| 253 |
objects that may not always have handlers. For example, |
| 254 |
:py:class:`~pyglet.media.player.Player` is an |
| 255 |
:py:class:`~pyglet.event.EventDispatcher` even though potentially hundreds |
| 256 |
of these objects may be created and destroyed each second, and most will |
| 257 |
not need an event handler. |
| 258 |
|
| 259 |
Implementing the Observer pattern |
| 260 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 261 |
|
| 262 |
The Observer design pattern, also known as Publisher/Subscriber, is a |
| 263 |
simple way to decouple software components. It is used extensively in many |
| 264 |
large software projects; for example, Java's AWT and Swing GUI toolkits and the |
| 265 |
Python ``logging`` module; and is fundamental to any Model-View-Controller |
| 266 |
architecture. |
| 267 |
|
| 268 |
:py:class:`~pyglet.event.EventDispatcher` can be used to easily add |
| 269 |
observerable components to your application. The following example recreates |
| 270 |
the `ClockTimer` example from `Design Patterns` (pages 300-301), though |
| 271 |
without needing the bulky ``Attach``, ``Detach`` and ``Notify`` methods:: |
| 272 |
|
| 273 |
# The subject |
| 274 |
class ClockTimer(pyglet.event.EventDispatcher): |
| 275 |
def tick(self): |
| 276 |
self.dispatch_event('on_update') |
| 277 |
|
| 278 |
ClockTimer.register_event_type('on_update') |
| 279 |
|
| 280 |
# Abstract observer class |
| 281 |
class Observer: |
| 282 |
def __init__(self, subject): |
| 283 |
subject.push_handlers(self) |
| 284 |
|
| 285 |
# Concrete observer |
| 286 |
class DigitalClock(Observer): |
| 287 |
def on_update(self): |
| 288 |
pass |
| 289 |
|
| 290 |
# Concrete observer |
| 291 |
class AnalogClock(Observer): |
| 292 |
def on_update(self): |
| 293 |
pass |
| 294 |
|
| 295 |
timer = ClockTimer() |
| 296 |
digital_clock = DigitalClock(timer) |
| 297 |
analog_clock = AnalogClock(timer) |
| 298 |
|
| 299 |
The two clock objects will be notified whenever the timer is "ticked", though |
| 300 |
neither the timer nor the clocks needed prior knowledge of the other. During |
| 301 |
object construction any relationships between subjects and observers can be |
| 302 |
created. |