SDL: Fixed keyboard focus on visionOS

From d8c0bd465ec20b93130de42a031013668d37fa79 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Tue, 27 Oct 2026 13:09:25 -0700
Subject: [PATCH] Fixed keyboard focus on visionOS

On visionOS it's possible for the Swift ornaments to become key. In this case we want the SDL window to stay focused.
---
 src/video/uikit/SDL_uikitwindow.m | 33 +++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)

diff --git a/src/video/uikit/SDL_uikitwindow.m b/src/video/uikit/SDL_uikitwindow.m
index b9814c3717b14..1f45bfb461edb 100644
--- a/src/video/uikit/SDL_uikitwindow.m
+++ b/src/video/uikit/SDL_uikitwindow.m
@@ -84,6 +84,22 @@ static bool UIKit_IsFocusableWindow(UIWindow *uiwindow)
     return NULL;
 }
 
+#ifdef SDL_PLATFORM_VISIONOS
+static SDL_Window *UIKit_GetSDLWindowForScene(UIWindowScene *scene)
+{
+    SDL_VideoDevice *_this = SDL_GetVideoDevice();
+    if (_this && scene) {
+        for (SDL_Window *window = _this->windows; window; window = window->next) {
+            SDL_UIKitWindowData *data = (__bridge SDL_UIKitWindowData *)window->internal;
+            if (data && data.uiwindow.windowScene == scene) {
+                return window;
+            }
+        }
+    }
+    return NULL;
+}
+#endif
+
 static id SDL_BecomeKeyObserver;
 static id SDL_ResignKeyObserver;
 
@@ -98,6 +114,17 @@ void UIKit_InitWindowFocus(void)
                                             usingBlock:^(NSNotification *notification) {
         UIWindow *uiwindow = (UIWindow *)notification.object;
         SDL_Window *window = UIKit_GetSDLWindow(uiwindow);
+#ifdef SDL_PLATFORM_VISIONOS
+        if (!window) {
+            // The uiwindow may be an ornament that has become key in the scene
+            window = UIKit_GetSDLWindowForScene(uiwindow.windowScene);
+            if (!window) {
+                // A different scene without an SDL window has become key
+                SDL_SetKeyboardFocus(NULL);
+                return;
+            }
+        }
+#endif
         if (window && UIKit_IsFocusableWindow(uiwindow)) {
             SDL_SetKeyboardFocus(window);
         }
@@ -110,6 +137,12 @@ void UIKit_InitWindowFocus(void)
         UIWindow *uiwindow = (UIWindow *)notification.object;
         SDL_Window *window = UIKit_GetSDLWindow(uiwindow);
         if (window && SDL_GetKeyboardFocus() == window) {
+#ifdef SDL_PLATFORM_VISIONOS
+            if (uiwindow.windowScene.activationState == UISceneActivationStateForegroundActive) {
+                // The key window may be moving to one of our ornaments, so keep focus on this window
+                return;
+            }
+#endif
             SDL_SetKeyboardFocus(NULL);
         }
     }];