SDL: Relative mouse mode grab is based on the window with the input focus

From 6a1e1ed9aea632e1988a8196f5b0e695f8e253a0 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Fri, 13 Aug 2021 23:36:13 -0700
Subject: [PATCH] Relative mouse mode grab is based on the window with the
 input focus

This fixes restoring the cursor clip rectangle after the mouse has moved off of the window.

Also try to better synchronize cursor visibility with mouse position changes when changing relative mode. This doesn't work perfectly, but it seems to improve things on Windows.
---
 src/events/SDL_mouse.c | 19 +++++++++++++------
 1 file changed, 13 insertions(+), 6 deletions(-)

diff --git a/src/events/SDL_mouse.c b/src/events/SDL_mouse.c
index 184942e2f1..aad433dc1f 100644
--- a/src/events/SDL_mouse.c
+++ b/src/events/SDL_mouse.c
@@ -820,6 +820,11 @@ SDL_SetRelativeMouseMode(SDL_bool enabled)
     mouse->scale_accum_x = 0.0f;
     mouse->scale_accum_y = 0.0f;
 
+    if (enabled) {
+        /* Update cursor visibility before we potentially warp the mouse */
+        SDL_SetCursor(NULL);
+    }
+
     if (enabled && focusWindow) {
         SDL_SetMouseFocus(focusWindow);
 
@@ -827,21 +832,23 @@ SDL_SetRelativeMouseMode(SDL_bool enabled)
             SDL_WarpMouseInWindow(focusWindow, focusWindow->w/2, focusWindow->h/2);
     }
 
-    if (mouse->focus) {
-        SDL_UpdateWindowGrab(mouse->focus);
+    if (focusWindow) {
+        SDL_UpdateWindowGrab(focusWindow);
 
         /* Put the cursor back to where the application expects it */
         if (!enabled) {
-            SDL_WarpMouseInWindow(mouse->focus, mouse->x, mouse->y);
+            SDL_WarpMouseInWindow(focusWindow, mouse->x, mouse->y);
         }
     }
 
+    if (!enabled) {
+        /* Update cursor visibility after we restore the mouse position */
+        SDL_SetCursor(NULL);
+    }
+
     /* Flush pending mouse motion - ideally we would pump events, but that's not always safe */
     SDL_FlushEvent(SDL_MOUSEMOTION);
 
-    /* Update cursor visibility */
-    SDL_SetCursor(NULL);
-
     return 0;
 }