pygame-ce icon indicating copy to clipboard operation
pygame-ce copied to clipboard

Add Event Watchers and Filters

Open SuperRedingBros opened this issue 2 weeks ago • 3 comments
trafficstars

Adds pygame.event.add_event_watcher, pygame.event.remove_event_watcher, pygame.event.add_event_filter, and pygame.event.remove_event_filter as loose wrappers around the corresponding SDL functions as a potential new way to handle events.

This has two primary rationales. Firstly, to allow using an event handler paradigm if desired while having no impact on the standard event loop structure. As this PR does nothing without explicitly opting into it opens up more options while not having any impact on other methods of handling events.

Secondarily, event watchers can be used as an effective solution for the quirk of the Windows version of SDL of the main thread freezing while the OS is sending resize or window movement events. This allows for more advanced users who may be impacted by the issue to resolve it without having to mess with the windows APIs directly. An example of the issue from upstream pygame can be found here.

A simple example that will print out all events that are added to the queue could be done like this:

@pygame.event.add_event_watcher
def event_logger(ev):
     print(ev)

and an example of a filter that will block only left click events:

@pygame.event.add_event_filter
def left_click_filter(ev):
     if ev.type == pygame.MOUSEBUTTONDOWN and ev.button == BUTTON_LEFT:
         return True # Returns true to filter out the event
     return False

I have also created a more complex demo implementation showcasing the event watchers as well as demonstrating both the windows issue and an example solution for the issue here.

Summary by CodeRabbit

  • New Features

    • Added event watcher API to register callbacks that receive converted events in real time.
    • Added event filter API to register filters that can block or allow events before delivery (thread-safe, short-circuiting).
  • Documentation

    • Added reference docs describing watcher/filter signatures, behavior, threading notes, return semantics, and error handling.
  • Tests

    • Added unit tests covering add/remove semantics, multiple watchers, filter behavior, and error cases.

SuperRedingBros avatar Nov 05 '25 00:11 SuperRedingBros