diff --git a/src/events/SDL_mouse.c b/src/events/SDL_mouse.c index 89ac786d2..ede6a6c46 100644 --- a/src/events/SDL_mouse.c +++ b/src/events/SDL_mouse.c @@ -415,6 +415,8 @@ int SDL_SetRelativeMouseMode(SDL_bool enabled) { SDL_Mouse *mouse = SDL_GetMouse(); + SDL_Window *focusWindow = SDL_GetKeyboardFocus(); + int original_x = mouse->x, original_y = mouse->y; if (enabled == mouse->relative_mode) { return 0; @@ -424,6 +426,14 @@ SDL_SetRelativeMouseMode(SDL_bool enabled) return SDL_Unsupported(); } + if (enabled && focusWindow) { + /* Center it in the focused window to prevent clicks from going through + * to background windows. + */ + SDL_SetMouseFocus(focusWindow); + SDL_WarpMouseInWindow(focusWindow, focusWindow->w/2, focusWindow->h/2); + } + if (mouse->SetRelativeMouseMode(enabled) < 0) { return -1; } @@ -433,8 +443,8 @@ SDL_SetRelativeMouseMode(SDL_bool enabled) if (enabled) { /* Save the expected mouse position */ - mouse->original_x = mouse->x; - mouse->original_y = mouse->y; + mouse->original_x = original_x; + mouse->original_y = original_y; } else if (mouse->focus) { /* Restore the expected mouse position */ SDL_WarpMouseInWindow(mouse->focus, mouse->original_x, mouse->original_y); diff --git a/src/video/SDL_video.c b/src/video/SDL_video.c index 694291022..9f0b03b3f 100644 --- a/src/video/SDL_video.c +++ b/src/video/SDL_video.c @@ -2044,10 +2044,17 @@ SDL_OnWindowLeave(SDL_Window * window) void SDL_OnWindowFocusGained(SDL_Window * window) { + SDL_Mouse *mouse = SDL_GetMouse(); + if (window->gamma && _this->SetWindowGammaRamp) { _this->SetWindowGammaRamp(_this, window, window->gamma); } + if (mouse && mouse->relative_mode) { + SDL_SetMouseFocus(window); + SDL_WarpMouseInWindow(window, window->w/2, window->h/2); + } + SDL_UpdateWindowGrab(window); } @@ -2067,10 +2074,17 @@ static SDL_bool ShouldMinimizeOnFocusLoss() void SDL_OnWindowFocusLost(SDL_Window * window) { + SDL_Mouse *mouse = SDL_GetMouse(); + if (window->gamma && _this->SetWindowGammaRamp) { _this->SetWindowGammaRamp(_this, window, window->saved_gamma); } + if (mouse && mouse->relative_mode) { + /* Restore the expected mouse position */ + SDL_WarpMouseInWindow(window, mouse->original_x, mouse->original_y); + } + SDL_UpdateWindowGrab(window); /* If we're fullscreen on a single-head system and lose focus, minimize */