SDL: Modifies WaitEvent and WaitEventTimeout to actually wait instead of polling

From 0dd7024d55019182b9e92d65221824a7a4dac992 Mon Sep 17 00:00:00 2001
From: Francesco Abbate <[EMAIL REDACTED]>
Date: Fri, 12 Mar 2021 21:58:20 +0100
Subject: [PATCH] Modifies WaitEvent and WaitEventTimeout to actually wait
 instead of polling

When possible use native os functions to make a blocking call waiting for
an incoming event. Previous behavior was to continuously poll the event
queue with a small delay between each poll.

The blocking call uses a new optional video driver event,
WaitEventTimeout, if available. It is called only if an window
already shown is available. If present the window is designated
using the variable wakeup_window to receive a wakeup event if
needed.

The WaitEventTimeout function accept a timeout parameter. If
positive the call will wait for an event or return if the timeout
expired without any event. If the timeout is zero it will
implement a polling behavior. If the timeout is negative the
function will block indefinetely waiting for an event.

To let the main thread sees events sent form a different thread
a "wake-up" signal is sent to the main thread if the main thread
is in a blocking state. The wake-up event is sent to the designated
wakeup_window if present.

The wake-up event is sent only if the PushEvent call is coming
from a different thread. Before sending the wake-up event
the ID of the thread making the blocking call is saved using the
variable blocking_thread_id and it is compared to the current
thread's id to decide if the wake-up event should be sent.

Two new optional video device methods are introduced:

WaitEventTimeout
SendWakeupEvent

in addition the mutex

wakeup_lock

which is defined and initialized but only for the drivers supporting the
methods above.

If the methods are not present the system behaves as previously
performing a periodic polling of the events queue.

The blocking call is disabled if a joystick or sensor is detected
and falls back to previous behavior.
---
 src/events/SDL_events.c               | 106 +++++++++
 src/video/SDL_sysvideo.h              |   5 +
 src/video/cocoa/SDL_cocoaevents.h     |   2 +
 src/video/cocoa/SDL_cocoaevents.m     |  54 ++++-
 src/video/cocoa/SDL_cocoavideo.m      |   6 +
 src/video/windows/SDL_windowsevents.c |  39 ++++
 src/video/windows/SDL_windowsevents.h |   2 +
 src/video/windows/SDL_windowsvideo.c  |  11 +-
 src/video/windows/SDL_windowsvideo.h  |   1 +
 src/video/x11/SDL_x11events.c         | 317 ++++++++++++++++----------
 src/video/x11/SDL_x11events.h         |   2 +
 src/video/x11/SDL_x11video.c          |  21 ++
 src/video/x11/SDL_x11video.h          |   2 +
 test/CMakeLists.txt                   |   1 +
 test/Makefile.in                      |   4 +
 test/checkkeysthreads.c               | 275 ++++++++++++++++++++++
 16 files changed, 716 insertions(+), 132 deletions(-)
 create mode 100644 test/checkkeysthreads.c

diff --git a/src/events/SDL_events.c b/src/events/SDL_events.c
index ec8c0b1855..7f34cbc3b0 100644
--- a/src/events/SDL_events.c
+++ b/src/events/SDL_events.c
@@ -759,6 +759,80 @@ SDL_PollEvent(SDL_Event * event)
     return SDL_WaitEventTimeout(event, 0);
 }
 
+static int
+SDL_WaitEventTimeout_Device(_THIS, SDL_Window *wakeup_window, SDL_Event * event, int timeout)
+{
+    /* Release any keys held down from last frame */
+    SDL_ReleaseAutoReleaseKeys();
+
+    for (;;) {
+        if (!_this->wakeup_lock || SDL_LockMutex(_this->wakeup_lock) == 0) {
+            int status = SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT);
+            /* If status == 0 we are going to block so wakeup will be needed. */
+            if (status == 0) {
+                _this->wakeup_window = wakeup_window;
+                _this->blocking_thread_id = SDL_ThreadID();
+            } else {
+                _this->wakeup_window = NULL;
+                _this->blocking_thread_id = 0;
+            }
+            if (_this->wakeup_lock) {
+                SDL_UnlockMutex(_this->wakeup_lock);
+            }
+            if (status < 0) {
+                /* Got an error: return */
+                break;
+            }
+            if (status > 0) {
+                /* There is an event, we can return. */
+                SDL_SendPendingSignalEvents();  /* in case we had a signal handler fire, etc. */
+                return 1;
+            }
+            /* No events found in the queue, call WaitEventTimeout to wait for an event. */
+            status = _this->WaitEventTimeout(_this, timeout);
+            /* Set wakeup_window to NULL without holding the lock. */
+            _this->wakeup_window = NULL;
+            if (status <= 0) {
+                /* There is either an error or the timeout is elapsed: return */
+                return 0;
+            }
+            /* An event was found and pumped into the SDL events queue. Continue the loop
+              to let SDL_PeepEvents pick it up .*/
+        }
+    }
+    return 0;
+}
+
+static int
+SDL_events_need_polling() {
+    SDL_bool need_polling = SDL_FALSE;
+
+#if !SDL_JOYSTICK_DISABLED
+    need_polling = \
+        (!SDL_disabled_events[SDL_JOYAXISMOTION >> 8] || SDL_JoystickEventState(SDL_QUERY)) \
+        && (SDL_NumJoysticks() > 0);
+#endif
+
+#if !SDL_SENSOR_DISABLED
+    need_polling = need_polling || (!SDL_disabled_events[SDL_SENSORUPDATE >> 8] && \
+        (SDL_NumSensors() > 0));
+#endif
+
+    return need_polling;
+}
+
+static SDL_Window *
+SDL_find_active_window(SDL_VideoDevice * _this)
+{
+    SDL_Window *window;
+    for (window = _this->windows; window; window = window->next) {
+        if (!window->is_destroying) {
+            return window;
+        }
+    }
+    return NULL;
+}
+
 int
 SDL_WaitEvent(SDL_Event * event)
 {
@@ -768,11 +842,24 @@ SDL_WaitEvent(SDL_Event * event)
 int
 SDL_WaitEventTimeout(SDL_Event * event, int timeout)
 {
+    SDL_VideoDevice *_this = SDL_GetVideoDevice();
+    SDL_bool need_polling = SDL_events_need_polling();
+    SDL_Window *wakeup_window = NULL;
     Uint32 expiration = 0;
 
     if (timeout > 0)
         expiration = SDL_GetTicks() + timeout;
 
+    if (!need_polling && _this) {
+        /* Look if a shown window is available to send the wakeup event. */
+        wakeup_window = SDL_find_active_window(_this);
+        need_polling = (wakeup_window == NULL);
+    }
+
+    if (!need_polling && _this && _this->WaitEventTimeout && _this->SendWakeupEvent) {
+        return SDL_WaitEventTimeout_Device(_this, wakeup_window, event, timeout);
+    }
+
     for (;;) {
         SDL_PumpEvents();
         switch (SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT)) {
@@ -796,6 +883,24 @@ SDL_WaitEventTimeout(SDL_Event * event, int timeout)
     }
 }
 
+static int
+SDL_SendWakeupEvent()
+{
+    SDL_VideoDevice *_this = SDL_GetVideoDevice();
+    if (!_this || !_this->SendWakeupEvent) {
+        return 0;
+    }
+    if (!_this->wakeup_lock || SDL_LockMutex(_this->wakeup_lock) == 0) {
+        if (_this->wakeup_window && _this->blocking_thread_id != 0 && _this->blocking_thread_id != SDL_ThreadID()) {
+            _this->SendWakeupEvent(_this, _this->wakeup_window);
+        }
+        if (_this->wakeup_lock) {
+            SDL_UnlockMutex(_this->wakeup_lock);
+        }
+    }
+    return 0;
+}
+
 int
 SDL_PushEvent(SDL_Event * event)
 {
@@ -845,6 +950,7 @@ SDL_PushEvent(SDL_Event * event)
         return -1;
     }
 
+    SDL_SendWakeupEvent();
     SDL_GestureProcessEvent(event);
 
     return 1;
diff --git a/src/video/SDL_sysvideo.h b/src/video/SDL_sysvideo.h
index 682e525929..8395e86804 100644
--- a/src/video/SDL_sysvideo.h
+++ b/src/video/SDL_sysvideo.h
@@ -290,6 +290,8 @@ struct SDL_VideoDevice
     /*
      * Event manager functions
      */
+    int (*WaitEventTimeout) (_THIS, int timeout);
+    void (*SendWakeupEvent) (_THIS, SDL_Window *window);
     void (*PumpEvents) (_THIS);
 
     /* Suspend the screensaver */
@@ -324,6 +326,9 @@ struct SDL_VideoDevice
     /* Data common to all drivers */
     SDL_bool is_dummy;
     SDL_bool suspend_screensaver;
+    SDL_Window *wakeup_window;
+    SDL_threadID blocking_thread_id;
+    SDL_mutex *wakeup_lock; /* Initialized only if WaitEventTimeout/SendWakeupEvent are supported */
     int num_displays;
     SDL_VideoDisplay *displays;
     SDL_Window *windows;
diff --git a/src/video/cocoa/SDL_cocoaevents.h b/src/video/cocoa/SDL_cocoaevents.h
index ece463c197..f4694269cf 100644
--- a/src/video/cocoa/SDL_cocoaevents.h
+++ b/src/video/cocoa/SDL_cocoaevents.h
@@ -25,6 +25,8 @@
 
 extern void Cocoa_RegisterApp(void);
 extern void Cocoa_PumpEvents(_THIS);
+extern int  Cocoa_WaitEventTimeout(_THIS, int timeout);
+extern void Cocoa_SendWakeupEvent(_THIS, SDL_Window *window);
 extern void Cocoa_SuspendScreenSaver(_THIS);
 
 #endif /* SDL_cocoaevents_h_ */
diff --git a/src/video/cocoa/SDL_cocoaevents.m b/src/video/cocoa/SDL_cocoaevents.m
index f496cb24f8..5a0ab1fb46 100644
--- a/src/video/cocoa/SDL_cocoaevents.m
+++ b/src/video/cocoa/SDL_cocoaevents.m
@@ -512,9 +512,8 @@ - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEv
     }
 }}
 
-void
-Cocoa_PumpEvents(_THIS)
-{ @autoreleasepool
+int
+Cocoa_PumpEventsUntilDate(_THIS, NSDate *expiration, bool accumulate)
 {
 #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070
     /* Update activity every 30 seconds to prevent screensaver */
@@ -530,9 +529,9 @@ - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEv
 #endif
 
     for ( ; ; ) {
-        NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES ];
+        NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:expiration inMode:NSDefaultRunLoopMode dequeue:YES ];
         if ( event == nil ) {
-            break;
+            return 0;
         }
 
         if (!s_bShouldHandleEventsInSDLApplication) {
@@ -541,7 +540,52 @@ - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEv
 
         // Pass events down to SDLApplication to be handled in sendEvent:
         [NSApp sendEvent:event];
+        if ( !accumulate) {
+            break;
+        }
+    }
+    return 1;
+}
+
+int
+Cocoa_WaitEventTimeout(_THIS, int timeout)
+{ @autoreleasepool
+{
+    if (timeout > 0) {
+        NSDate *limitDate = [NSDate dateWithTimeIntervalSinceNow: (double) timeout / 1000.0];
+        return Cocoa_PumpEventsUntilDate(_this, limitDate, false);
+    } else if (timeout == 0) {
+        return Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], false);
+    } else {
+        while (Cocoa_PumpEventsUntilDate(_this, [NSDate distantFuture], false) == 0) {
+        }
     }
+    return 1;
+}}
+
+void
+Cocoa_PumpEvents(_THIS)
+{ @autoreleasepool
+{
+    Cocoa_PumpEventsUntilDate(_this, [NSDate distantPast], true);
+}}
+
+void Cocoa_SendWakeupEvent(_THIS, SDL_Window *window)
+{ @autoreleasepool
+{
+    NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
+
+    NSEvent* event = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
+                                    location: NSMakePoint(0,0)
+                               modifierFlags: 0
+                                   timestamp: 0.0
+                                windowNumber: nswindow.windowNumber
+                                     context: nil
+                                     subtype: 0
+                                       data1: 0
+                                       data2: 0];
+
+    [NSApp postEvent: event atStart: YES];
 }}
 
 void
diff --git a/src/video/cocoa/SDL_cocoavideo.m b/src/video/cocoa/SDL_cocoavideo.m
index 5019d3e7c8..f16b8aa663 100644
--- a/src/video/cocoa/SDL_cocoavideo.m
+++ b/src/video/cocoa/SDL_cocoavideo.m
@@ -38,6 +38,9 @@
 static void
 Cocoa_DeleteDevice(SDL_VideoDevice * device)
 {
+    if (device->wakeup_lock) {
+        SDL_DestroyMutex(device->wakeup_lock);
+    }
     SDL_free(device->driverdata);
     SDL_free(device);
 }
@@ -63,6 +66,7 @@
         return NULL;
     }
     device->driverdata = data;
+    device->wakeup_lock = SDL_CreateMutex();
 
     /* Set the function pointers */
     device->VideoInit = Cocoa_VideoInit;
@@ -73,6 +77,8 @@
     device->GetDisplayModes = Cocoa_GetDisplayModes;
     device->SetDisplayMode = Cocoa_SetDisplayMode;
     device->PumpEvents = Cocoa_PumpEvents;
+    device->WaitEventTimeout = Cocoa_WaitEventTimeout;
+    device->SendWakeupEvent = Cocoa_SendWakeupEvent;
     device->SuspendScreenSaver = Cocoa_SuspendScreenSaver;
 
     device->CreateSDLWindow = Cocoa_CreateWindow;
diff --git a/src/video/windows/SDL_windowsevents.c b/src/video/windows/SDL_windowsevents.c
index bb86108a3e..a8108a8ea8 100644
--- a/src/video/windows/SDL_windowsevents.c
+++ b/src/video/windows/SDL_windowsevents.c
@@ -1276,6 +1276,45 @@ void SDL_SetWindowsMessageHook(SDL_WindowsMessageHook callback, void *userdata)
     g_WindowsMessageHookData = userdata;
 }
 
+int
+WIN_WaitEventTimeout(_THIS, int timeout)
+{
+    MSG msg;
+    if (g_WindowsEnableMessageLoop) {
+        BOOL message_result;
+        UINT_PTR timer_id = 0;
+        if (timeout > 0) {
+            timer_id = SetTimer(NULL, 0, timeout, NULL);
+            message_result = GetMessage(&msg, 0, 0, 0);
+            KillTimer(NULL, timer_id);
+        } else if (timeout == 0) {
+            message_result = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
+        } else {
+            message_result = GetMessage(&msg, 0, 0, 0);
+        }
+        if (message_result) {
+            if (msg.message == WM_TIMER && msg.hwnd == NULL && msg.wParam == timer_id) {
+                return 0;
+            }
+            if (g_WindowsMessageHook) {
+                g_WindowsMessageHook(g_WindowsMessageHookData, msg.hwnd, msg.message, msg.wParam, msg.lParam);
+            }
+            /* Always translate the message in case it's a non-SDL window (e.g. with Qt integration) */
+            TranslateMessage(&msg);
+            DispatchMessage(&msg);
+            return 1;
+        }
+    }
+    return 0;
+}
+
+void
+WIN_SendWakeupEvent(_THIS, SDL_Window *window)
+{
+    SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
+    PostMessage(data->hwnd, data->videodata->_SDL_WAKEUP, 0, 0);
+}
+
 void
 WIN_PumpEvents(_THIS)
 {
diff --git a/src/video/windows/SDL_windowsevents.h b/src/video/windows/SDL_windowsevents.h
index fcd716dcf0..93b41e4dcf 100644
--- a/src/video/windows/SDL_windowsevents.h
+++ b/src/video/windows/SDL_windowsevents.h
@@ -31,6 +31,8 @@ extern LRESULT CALLBACK WIN_KeyboardHookProc(int nCode, WPARAM wParam, LPARAM lP
 extern LRESULT CALLBACK WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam,
                                        LPARAM lParam);
 extern void WIN_PumpEvents(_THIS);
+extern void WIN_SendWakeupEvent(_THIS, SDL_Window *window);
+extern int  WIN_WaitEventTimeout(_THIS, int timeout);
 
 #endif /* SDL_windowsevents_h_ */
 
diff --git a/src/video/windows/SDL_windowsvideo.c b/src/video/windows/SDL_windowsvideo.c
index 8eb32b2efd..4956ced701 100644
--- a/src/video/windows/SDL_windowsvideo.c
+++ b/src/video/windows/SDL_windowsvideo.c
@@ -87,7 +87,9 @@ WIN_DeleteDevice(SDL_VideoDevice * device)
     if (data->shcoreDLL) {
         SDL_UnloadObject(data->shcoreDLL);
     }
-
+    if (device->wakeup_lock) {
+        SDL_DestroyMutex(device->wakeup_lock);
+    }
     SDL_free(device->driverdata);
     SDL_free(device);
 }
@@ -113,6 +115,7 @@ WIN_CreateDevice(int devindex)
         return NULL;
     }
     device->driverdata = data;
+    device->wakeup_lock = SDL_CreateMutex();
 
     data->userDLL = SDL_LoadObject("USER32.DLL");
     if (data->userDLL) {
@@ -139,6 +142,8 @@ WIN_CreateDevice(int devindex)
     device->GetDisplayModes = WIN_GetDisplayModes;
     device->SetDisplayMode = WIN_SetDisplayMode;
     device->PumpEvents = WIN_PumpEvents;
+    device->WaitEventTimeout = WIN_WaitEventTimeout;
+    device->SendWakeupEvent = WIN_SendWakeupEvent;
     device->SuspendScreenSaver = WIN_SuspendScreenSaver;
 
     device->CreateSDLWindow = WIN_CreateWindow;
@@ -226,6 +231,8 @@ VideoBootStrap WINDOWS_bootstrap = {
 int
 WIN_VideoInit(_THIS)
 {
+    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
+
     if (WIN_InitModes(_this) < 0) {
         return -1;
     }
@@ -236,6 +243,8 @@ WIN_VideoInit(_THIS)
     SDL_AddHintCallback(SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP, UpdateWindowsEnableMessageLoop, NULL);
     SDL_AddHintCallback(SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN, UpdateWindowFrameUsableWhileCursorHidden, NULL);
 
+    data->_SDL_WAKEUP = RegisterWindowMessageA("_SDL_WAKEUP");
+
     return 0;
 }
 
diff --git a/src/video/windows/SDL_windowsvideo.h b/src/video/windows/SDL_windowsvideo.h
index c7c4caaf29..5f4bd4a6c0 100644
--- a/src/video/windows/SDL_windowsvideo.h
+++ b/src/video/windows/SDL_windowsvideo.h
@@ -190,6 +190,7 @@ typedef struct SDL_VideoData
     TSFSink *ime_ippasink;
 
     BYTE pre_hook_key_state[256];
+    UINT _SDL_WAKEUP;
 } SDL_VideoData;
 
 extern SDL_bool g_WindowsEnableMessageLoop;
diff --git a/src/video/x11/SDL_x11events.c b/src/video/x11/SDL_x11events.c
index 37c76c5e98..8c654f23d3 100644
--- a/src/video/x11/SDL_x11events.c
+++ b/src/video/x11/SDL_x11events.c
@@ -670,42 +670,35 @@ isReparentNotify(Display *display, XEvent *ev, XPointer arg)
 }
 
 static void
-X11_DispatchEvent(_THIS)
+X11_DispatchEvent(_THIS, XEvent *xevent)
 {
     SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
+    XkbEvent* xkbEvent = (XkbEvent*) xevent;
     Display *display;
     SDL_WindowData *data;
-    XEvent xevent;
-    XkbEvent* xkbEvent;
     int orig_event_type;
     KeyCode orig_keycode;
     XClientMessageEvent m;
     int i;
 
-    if (!videodata) {
-        return;
-    }
+    SDL_assert(videodata != NULL);
     display = videodata->display;
 
-    SDL_zero(xevent);           /* valgrind fix. --ryan. */
-    X11_XNextEvent(display, &xevent);
-    xkbEvent = (XkbEvent*) &xevent;
-
     /* Save the original keycode for dead keys, which are filtered out by
        the XFilterEvent() call below.
     */
-    orig_event_type = xevent.type;
+    orig_event_type = xevent->type;
     if (orig_event_type == KeyPress || orig_event_type == KeyRelease) {
-        orig_keycode = xevent.xkey.keycode;
+        orig_keycode = xevent->xkey.keycode;
     } else {
         orig_keycode = 0;
     }
 
     /* filter events catchs XIM events and sends them to the correct handler */
-    if (X11_XFilterEvent(&xevent, None) == True) {
+    if (X11_XFilterEvent(xevent, None) == True) {
 #if 0
         printf("Filtered event type = %d display = %d window = %d\n",
-               xevent.type, xevent.xany.display, xevent.xany.window);
+               xevent->type, xevent->xany.display, xevent->xany.window);
 #endif
         /* Make sure dead key press/release events are sent */
         /* But only if we're using one of the DBus IMEs, otherwise
@@ -714,7 +707,7 @@ X11_DispatchEvent(_THIS)
 #if defined(HAVE_IBUS_IBUS_H) || defined(HAVE_FCITX)
             SDL_Scancode scancode = videodata->key_layout[orig_keycode];
             videodata->filter_code = orig_keycode;
-            videodata->filter_time = xevent.xkey.time;
+            videodata->filter_time = xevent->xkey.time;
 
             if (orig_event_type == KeyPress) {
                 SDL_SendKeyboardKey(SDL_PRESSED, scancode);
@@ -727,8 +720,8 @@ X11_DispatchEvent(_THIS)
     }
 
 #if SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
-    if(xevent.type == GenericEvent) {
-        X11_HandleGenericEvent(videodata, &xevent);
+    if(xevent->type == GenericEvent) {
+        X11_HandleGenericEvent(videodata, xevent);
         return;
     }
 #endif
@@ -739,18 +732,18 @@ X11_DispatchEvent(_THIS)
 
         SDL_VERSION(&wmmsg.version);
         wmmsg.subsystem = SDL_SYSWM_X11;
-        wmmsg.msg.x11.event = xevent;
+        wmmsg.msg.x11.event = *xevent;
         SDL_SendSysWMEvent(&wmmsg);
     }
 
 #if 0
     printf("type = %d display = %d window = %d\n",
-           xevent.type, xevent.xany.display, xevent.xany.window);
+           xevent->type, xevent->xany.display, xevent->xany.window);
 #endif
 
     if ((videodata->clipboard_window != None) &&
-        (videodata->clipboard_window == xevent.xany.window)) {
-        X11_HandleClipboardEvent(_this, &xevent);
+        (videodata->clipboard_window == xevent->xany.window)) {
+        X11_HandleClipboardEvent(_this, xevent);
         return;
     }
 
@@ -758,7 +751,7 @@ X11_DispatchEvent(_THIS)
     if (videodata && videodata->windowlist) {
         for (i = 0; i < videodata->numwindows; ++i) {
             if ((videodata->windowlist[i] != NULL) &&
-                (videodata->windowlist[i]->xwindow == xevent.xany.window)) {
+                (videodata->windowlist[i]->xwindow == xevent->xany.window)) {
                 data = videodata->windowlist[i];
                 break;
             }
@@ -766,19 +759,19 @@ X11_DispatchEvent(_THIS)
     }
     if (!data) {
         /* The window for KeymapNotify, etc events is 0 */
-        if (xevent.type == KeymapNotify) {
+        if (xevent->type == KeymapNotify) {
             if (SDL_GetKeyboardFocus() != NULL) {
                 X11_ReconcileKeyboardState(_this);
             }
-        } else if (xevent.type == MappingNotify || xkbEvent->any.xkb_type == XkbStateNotify) {
+        } else if (xevent->type == MappingNotify || xkbEvent->any.xkb_type == XkbStateNotify) {
             /* Has the keyboard layout changed? */
-            const int request = xevent.xmapping.request;
+            const int request = xevent->xmapping.request;
 
 #ifdef DEBUG_XEVENTS
             printf("window %p: MappingNotify!\n", data);
 #endif
             if ((request == MappingKeyboard) || (request == MappingModifier)) {
-                X11_XRefreshKeyboardMapping(&xevent.xmapping);
+                X11_XRefreshKeyboardMapping(&xevent->xmapping);
             }
 
             X11_UpdateKeymap(_this);
@@ -787,28 +780,28 @@ X11_DispatchEvent(_THIS)
         return;
     }
 
-    switch (xevent.type) {
+    switch (xevent->type) {
 
         /* Gaining mouse coverage? */
     case EnterNotify:{
             SDL_Mouse *mouse = SDL_GetMouse();
 #ifdef DEBUG_XEVENTS
             printf("window %p: EnterNotify! (%d,%d,%d)\n", data,
-                   xevent.xcrossing.x,
-                   xevent.xcrossing.y,
-                   xevent.xcrossing.mode);
-            if (xevent.xcrossing.mode == NotifyGrab)
+                   xevent->xcrossing.x,
+                   xevent->xcrossing.y,
+                   xevent->xcrossing.mode);
+            if (xevent->xcrossing.mode == NotifyGrab)
                 printf("Mode: NotifyGrab\n");
-            if (xevent.xcrossing.mode == NotifyUngrab)
+            if (xevent->xcrossing.mode == NotifyUngrab)
                 printf("Mode: NotifyUngrab\n");
 #endif
             SDL_SetMouseFocus(data->window);
 
-            mouse->last_x = xevent.xcrossing.x;
-            mouse->last_y = xevent.xcrossing.y;
+            mouse->last_x = xevent->xcrossing.x;
+            mouse->last_y = xevent->xcrossing.y;
 
             if (!mouse->relative_mode) {
-                SDL_SendMouseMotion(data->window, 0, 0, xevent.xcrossing.x, xevent.xcrossing.y);
+                SDL_SendMouseMotion(data->window, 0, 0, xevent->xcrossing.x, xevent->xcrossing.y);
             }
 
             /* We ungrab in LeaveNotify, so we may need to grab again here */
@@ -819,21 +812,21 @@ X11_DispatchEvent(_THIS)
     case LeaveNotify:{
 #ifdef DEBUG_XEVENTS
             printf("window %p: LeaveNotify! (%d,%d,%d)\n", data,
-                   xevent.xcrossing.x,
-                   xevent.xcrossing.y,
-                   xevent.xcrossing.mode);
-            if (xevent.xcrossing.mode == NotifyGrab)
+                   xevent->xcrossing.x,
+                   xevent->xcrossing.y,
+                   xevent->xcrossing.mode);
+            if (xevent->xcrossing.mode == NotifyGrab)
                 printf("Mode: NotifyGrab\n");
-            if (xevent.xcrossing.mode == NotifyUngrab)
+            if (xevent->xcrossing.mode == NotifyUngrab)
                 printf("Mode: NotifyUngrab\n");
 #endif
             if (!SDL_GetMouse()->relative_mode) {
-                SDL_SendMouseMotion(data->window, 0, 0, xevent.xcrossing.x, xevent.xcrossing.y);
+                SDL_SendMouseMotion(data->window, 0, 0, xevent->xcrossing.x, xevent->xcrossing.y);
             }
 
-            if (xevent.xcrossing.mode != NotifyGrab &&
-                xevent.xcrossing.mode != NotifyUngrab &&
-                xevent.xcrossing.detail != NotifyInferior) {
+            if (xevent->xcrossing.mode != NotifyGrab &&
+                xevent->xcrossing.mode != NotifyUngrab &&
+                xevent->xcrossing.detail != NotifyInferior) {
                 
                 /* In order for interaction with the window decorations and menu to work properly
                    on Mutter, we need to ungrab the keyboard when the the mouse leaves. */
@@ -848,7 +841,7 @@ X11_DispatchEvent(_THIS)
 
         /* Gaining input focus? */
     case FocusIn:{
-            if (xevent.xfocus.mode == NotifyGrab || xevent.xfocus.mode == NotifyUngrab) {
+            if (xevent->xfocus.mode == NotifyGrab || xevent->xfocus.mode == NotifyUngrab) {
                 /* Someone is handling a global hotkey, ignore it */
 #ifdef DEBUG_XEVENTS
                 printf("window %p: FocusIn (NotifyGrab/NotifyUngrab, ignoring)\n", data);
@@ -856,7 +849,7 @@ X11_DispatchEvent(_THIS)
                 break;
             }
 
-            if (xevent.xfocus.detail == NotifyInferior || xevent.xfocus.detail == NotifyPointer) {
+            if (xevent->xfocus.detail == NotifyInferior || xevent->xfocus.detail == NotifyPointer) {
 #ifdef DEBUG_XEVENTS
                 printf("window %p: FocusIn (NotifyInferior/NotifyPointer, ignoring)\n", data);
 #endif
@@ -882,14 +875,14 @@ X11_DispatchEvent(_THIS)
 
         /* Losing input focus? */
     case FocusOut:{
-            if (xevent.xfocus.mode == NotifyGrab || xevent.xfocus.mode == NotifyUngrab) {
+            if (xevent->xfocus.mode == NotifyGrab || xevent->xfocus.mode == NotifyUngrab) {
                 /* Someone is handling a global hotkey, ignore it */
 #ifdef DEBUG_XEVENTS
                 printf("window %p: FocusOut (NotifyGrab/NotifyUngrab, ignoring)\n", data);
 #endif
                 break;
             }
-            if (xevent.xfocus.detail == NotifyInferior || xevent.xfocus.detail == NotifyPointer) {
+            if (xevent->xfocus.detail == NotifyInferior || xevent->xfocus.detail == NotifyPointer) {
                 /* We still have focus if a child gets focus. We also don't
                    care about the position of the pointer when the keyboard
                    focus changed. */
@@ -917,20 +910,20 @@ X11_DispatchEvent(_THIS)
 
         /* Key press? */
     case KeyPress:{
-            KeyCode keycode = xevent.xkey.keycode;
+            KeyCode keycode = xevent->xkey.keycode;
             KeySym keysym = NoSymbol;
             char text[SDL_TEXTINPUTEVENT_TEXT_SIZE];
             Status status = 0;
             SDL_bool handled_by_ime = SDL_FALSE;
 
 #ifdef DEBUG_XEVENTS
-            printf("window %p: KeyPress (X11 keycode = 0x%X)\n", data, xevent.xkey.keycode);
+            printf("window %p: KeyPress (X11 keycode = 0x%X)\n", data, xevent->xkey.keycode);
 #endif
 #if 1
             if (videodata->key_layout[keycode] == SDL_SCANCODE_UNKNOWN && keycode) {
                 int min_keycode, max_keycode;
                 X11_XDisplayKeycodes(display, &min_keycode, &max_keycode);
-                keysym = X11_KeyCodeToSym(_this, keycode, xevent.xkey.state >> 13);
+                keysym = X11_KeyCodeToSym(_this, keycode, xevent->xkey.state >> 13);
                 fprintf(stderr,
                         "The key you just pressed is not recognized by SDL. To help get this fixed, please report this to the SDL forums/mailing list <https://discourse.libsdl.org/> X11 KeyCode %d (%d), X11 KeySym 0x%lX (%s).\n",
                         keycode, keycode - min_keycode, keysym,
@@ -941,13 +934,13 @@ X11_DispatchEvent(_THIS)
             SDL_zeroa(text);
 #ifdef X_HAVE_UTF8_STRING
             if (data->ic) {
-                X11_Xutf8LookupString(data->ic, &xevent.xkey, text, sizeof(text),
+                X11_Xutf8LookupString(data->ic, &xevent->xkey, text, sizeof(text),
                                   &keysym, &status);
             } else {
-                X11_XLookupString(&xevent.xkey, text, sizeof(text), &keysym, NULL);
+                X11_XLookupString(&xevent->xkey, text, sizeof(text), &keysym, NULL);
             }
 #else
-            X11_XLookupString(&xevent.xkey, text, sizeof(text), &keysym, NULL);
+            X11_XLookupString(&xevent->xkey, text, sizeof(text), &keysym, NULL);
 #endif
 
 #ifdef SDL_USE_IME
@@ -957,7 +950,7 @@ X11_DispatchEvent(_THIS)
 #endif
             if (!handled_by_ime) {
                 /* Don't send the key if it looks like a duplicate of a filtered key sent by an IME */
-                if (xevent.xkey.keycode != videodata->filter_code || xevent.xkey.time != videodata->filter_time) {
+                if (xevent->xkey.keycode != videodata->filter_code || xevent->xkey.time != videodata->filter_time) {
                     SDL_SendKeyboardKey(SDL_PRESSED, videodata->key_layout[keycode]);
                 }
                 if(*text) {
@@ -965,18 +958,18 @@ X11_DispatchEvent(_THIS)
                 }
             }
 
-            X11_UpdateUserTime(data, xevent.xkey.time);
+            X11_UpdateUserTime(data, xevent->xkey.time);
         }
         break;
 
         /* Key release? */
     case KeyRelease:{
-            KeyCode keycode = xevent.xkey.keycode;
+            KeyCode keycode = xevent->xkey.keycode;
 
 #ifdef DEBUG_XEVENTS
-            printf("window %p: KeyRelease (X11 keycode = 0x%X)\n", data, xevent.xkey.keycode);
+            printf("window %p: KeyRelease (X11 keycode = 0x%X)\n", data, xevent->xkey.keycode);
 #endif
-            if (X11_KeyRepeat(display, &xevent)) {
+            if (X11_KeyRepeat(display, xevent)) {
                 /* We're about to get a repeated key down, ignore the key up */
                 break;
             }
@@ -992,8 +985,8 @@ X11_DispatchEvent(_THIS)
             printf("window %p: UnmapNotify!\n", data);
 #endif
 
-            if (X11_XCheckIfEvent(display, &ev, &isReparentNotify, (XPointer)&xevent.xunmap)) {
-                X11_XCheckIfEvent(display, &ev, &isMapNotify, (XPointer)&xevent.xunmap);
+            if (X11_XCheckIfEvent(display, &ev, &isReparentNotify, (XPointer)&xevent->xunmap)) {
+                X11_XCheckIfEvent(display, &ev, &isMapNotify, (XPointer)&xevent->xunmap);
             } else {
                 X11_DispatchUnmapNotify(data);
             }
@@ -1013,27 +1006,27 @@ X11_DispatchEvent(_THIS)
     case ConfigureNotify:{
 #ifdef DEBUG_XEVENTS
             printf("window %p: ConfigureNotify! (position: %d,%d, size: %dx%d)\n", data,
-                   xevent.xconfigure.x, xevent.xconfigure.y,
-                   xevent.xconfigure.width, xevent.xconfigure.height);
+                   xevent->xconfigure.x, xevent->xconfigure.y,
+                   xevent->xconfigure.width, xevent->xconfigure.height);
 #endif
             /* Real configure notify events are relative to the parent, synthetic events are absolute. */
-            if (!xevent.xconfigure.send_event) {
+            if (!xevent->xconfigure.send_event) {
                 unsigned int NumChildren;
                 Window ChildReturn, Root, Parent;
                 Window * Children;
                 /* Translate these coodinates back to

(Patch may be truncated, please check the link at the top of this post.)