SDL: Make sure the window is valid in SDL_SetKeyboardFocus()

From e3d90c694c2ae1136764ab95b67aa0704fd21dad Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Fri, 3 Mar 2023 09:09:11 -0800
Subject: [PATCH] Make sure the window is valid in SDL_SetKeyboardFocus()

---
 src/events/SDL_keyboard.c   | 11 +++++++++--
 src/events/SDL_keyboard_c.h |  2 +-
 2 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/src/events/SDL_keyboard.c b/src/events/SDL_keyboard.c
index 32b8d3b49943..93c8efe962c1 100644
--- a/src/events/SDL_keyboard.c
+++ b/src/events/SDL_keyboard.c
@@ -746,10 +746,17 @@ SDL_GetKeyboardFocus(void)
     return keyboard->focus;
 }
 
-void SDL_SetKeyboardFocus(SDL_Window *window)
+int SDL_SetKeyboardFocus(SDL_Window *window)
 {
+    SDL_VideoDevice *video = SDL_GetVideoDevice();
     SDL_Keyboard *keyboard = &SDL_keyboard;
 
+    if (window) {
+        if (!video || window->magic != &video->window_magic || window->is_destroying) {
+            return SDL_SetError("Invalid window");
+        }
+    }
+
     if (keyboard->focus && window == NULL) {
         /* We won't get anymore keyboard messages, so reset keyboard state */
         SDL_ResetKeyboard();
@@ -773,7 +780,6 @@ void SDL_SetKeyboardFocus(SDL_Window *window)
 
         /* Ensures IME compositions are committed */
         if (SDL_EventEnabled(SDL_EVENT_TEXT_INPUT)) {
-            SDL_VideoDevice *video = SDL_GetVideoDevice();
             if (video && video->StopTextInput) {
                 video->StopTextInput(video);
             }
@@ -793,6 +799,7 @@ void SDL_SetKeyboardFocus(SDL_Window *window)
             }
         }
     }
+    return 0;
 }
 
 static int SDL_SendKeyboardKeyInternal(Uint64 timestamp, SDL_KeyboardFlags flags, Uint8 state, SDL_Scancode scancode, SDL_Keycode keycode)
diff --git a/src/events/SDL_keyboard_c.h b/src/events/SDL_keyboard_c.h
index 4a572a97b2cc..9381932c70d3 100644
--- a/src/events/SDL_keyboard_c.h
+++ b/src/events/SDL_keyboard_c.h
@@ -42,7 +42,7 @@ extern void SDL_SetKeymap(int start, const SDL_Keycode *keys, int length, SDL_bo
 extern void SDL_SetScancodeName(SDL_Scancode scancode, const char *name);
 
 /* Set the keyboard focus window */
-extern void SDL_SetKeyboardFocus(SDL_Window *window);
+extern int SDL_SetKeyboardFocus(SDL_Window *window);
 
 /* Send a character from an on-screen keyboard as scancode and modifier key events,
    currently assuming ASCII characters on a US keyboard layout