SDL: x11: Avoid duplicate mouse events when using a pen device.

From 72f4dd17bed986ccf448c5ad59056ab7f7a41988 Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Fri, 11 Jul 2025 14:27:12 -0400
Subject: [PATCH] x11: Avoid duplicate mouse events when using a pen device.

Fixes #12968.
---
 src/video/x11/SDL_x11xinput2.c | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/src/video/x11/SDL_x11xinput2.c b/src/video/x11/SDL_x11xinput2.c
index afe4a7c85b674..98080ccfd8362 100644
--- a/src/video/x11/SDL_x11xinput2.c
+++ b/src/video/x11/SDL_x11xinput2.c
@@ -406,11 +406,15 @@ void X11_HandleXinput2Event(SDL_VideoDevice *_this, XGenericEventCookie *cookie)
     case XI_ButtonRelease:
     {
         const XIDeviceEvent *xev = (const XIDeviceEvent *)cookie->data;
-        X11_PenHandle *pen = X11_FindPenByDeviceID(xev->deviceid);
+        X11_PenHandle *pen = X11_FindPenByDeviceID(xev->sourceid);
         const int button = xev->detail;
         const bool down = (cookie->evtype == XI_ButtonPress);
 
         if (pen) {
+            if (xev->deviceid != xev->sourceid) {
+                // Discard events from "Master" devices to avoid duplicates.
+                break;
+            }
             // Only report button event; if there was also pen movement / pressure changes, we expect an XI_Motion event first anyway.
             SDL_Window *window = xinput2_get_sdlwindow(videodata, xev->event);
             if (button == 1) { // button 1 is the pen tip
@@ -422,11 +426,6 @@ void X11_HandleXinput2Event(SDL_VideoDevice *_this, XGenericEventCookie *cookie)
             // Otherwise assume a regular mouse
             SDL_WindowData *windowdata = xinput2_get_sdlwindowdata(videodata, xev->event);
 
-            if (xev->deviceid != xev->sourceid) {
-                // Discard events from "Master" devices to avoid duplicates.
-                break;
-            }
-
             if (down) {
                 X11_HandleButtonPress(_this, windowdata, (SDL_MouseID)xev->sourceid, button,
                                       (float)xev->event_x, (float)xev->event_y, xev->time);
@@ -449,7 +448,8 @@ void X11_HandleXinput2Event(SDL_VideoDevice *_this, XGenericEventCookie *cookie)
 
         videodata->global_mouse_changed = true;
 
-        X11_PenHandle *pen = X11_FindPenByDeviceID(xev->deviceid);
+        X11_PenHandle *pen = X11_FindPenByDeviceID(xev->sourceid);
+
         if (pen) {
             if (xev->deviceid != xev->sourceid) {
                 // Discard events from "Master" devices to avoid duplicates.