From 5a079a2d114f96d4847d1ee305d5b7c16eeec50e Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Sat, 27 Dec 2025 12:03:39 -0800 Subject: Initial commit --- .../src/video/wayland/SDL_waylandclipboard.c | 174 + .../src/video/wayland/SDL_waylandclipboard.h | 34 + .../SDL-3.2.8/src/video/wayland/SDL_waylandcolor.c | 303 ++ .../SDL-3.2.8/src/video/wayland/SDL_waylandcolor.h | 35 + .../src/video/wayland/SDL_waylanddatamanager.c | 619 ++++ .../src/video/wayland/SDL_waylanddatamanager.h | 162 + .../SDL-3.2.8/src/video/wayland/SDL_waylanddyn.c | 176 + .../SDL-3.2.8/src/video/wayland/SDL_waylanddyn.h | 195 ++ .../src/video/wayland/SDL_waylandevents.c | 3408 ++++++++++++++++++++ .../src/video/wayland/SDL_waylandevents_c.h | 195 ++ .../src/video/wayland/SDL_waylandkeyboard.c | 209 ++ .../src/video/wayland/SDL_waylandkeyboard.h | 40 + .../src/video/wayland/SDL_waylandmessagebox.c | 196 ++ .../src/video/wayland/SDL_waylandmessagebox.h | 31 + .../SDL-3.2.8/src/video/wayland/SDL_waylandmouse.c | 1057 ++++++ .../SDL-3.2.8/src/video/wayland/SDL_waylandmouse.h | 34 + .../src/video/wayland/SDL_waylandopengles.c | 220 ++ .../src/video/wayland/SDL_waylandopengles.h | 48 + .../src/video/wayland/SDL_waylandshmbuffer.c | 170 + .../src/video/wayland/SDL_waylandshmbuffer.h | 38 + .../SDL-3.2.8/src/video/wayland/SDL_waylandsym.h | 242 ++ .../SDL-3.2.8/src/video/wayland/SDL_waylandvideo.c | 1692 ++++++++++ .../SDL-3.2.8/src/video/wayland/SDL_waylandvideo.h | 140 + .../src/video/wayland/SDL_waylandvulkan.c | 203 ++ .../src/video/wayland/SDL_waylandvulkan.h | 55 + .../src/video/wayland/SDL_waylandwindow.c | 3125 ++++++++++++++++++ .../src/video/wayland/SDL_waylandwindow.h | 248 ++ 27 files changed, 13049 insertions(+) create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandclipboard.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandclipboard.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandcolor.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandcolor.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddatamanager.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddatamanager.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddyn.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddyn.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandevents.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandevents_c.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandkeyboard.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandkeyboard.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmessagebox.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmessagebox.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmouse.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmouse.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandopengles.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandopengles.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandshmbuffer.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandshmbuffer.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandsym.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvideo.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvideo.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvulkan.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvulkan.h create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandwindow.c create mode 100644 contrib/SDL-3.2.8/src/video/wayland/SDL_waylandwindow.h (limited to 'contrib/SDL-3.2.8/src/video/wayland') diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandclipboard.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandclipboard.c new file mode 100644 index 0000000..6218733 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandclipboard.c @@ -0,0 +1,174 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#include "SDL_waylanddatamanager.h" +#include "SDL_waylandevents_c.h" +#include "SDL_waylandclipboard.h" +#include "../SDL_clipboard_c.h" +#include "../../events/SDL_events_c.h" + + +bool Wayland_SetClipboardData(SDL_VideoDevice *_this) +{ + SDL_VideoData *video_data = _this->internal; + SDL_WaylandDataDevice *data_device = NULL; + bool result = true; + + if (video_data->input && video_data->input->data_device) { + data_device = video_data->input->data_device; + + if (_this->clipboard_callback && _this->clipboard_mime_types) { + SDL_WaylandDataSource *source = Wayland_data_source_create(_this); + Wayland_data_source_set_callback(source, _this->clipboard_callback, _this->clipboard_userdata, _this->clipboard_sequence); + + result = Wayland_data_device_set_selection(data_device, source, (const char **)_this->clipboard_mime_types, _this->num_clipboard_mime_types); + if (!result) { + Wayland_data_source_destroy(source); + } + } else { + result = Wayland_data_device_clear_selection(data_device); + } + } + + return result; +} + +void *Wayland_GetClipboardData(SDL_VideoDevice *_this, const char *mime_type, size_t *length) +{ + SDL_VideoData *video_data = _this->internal; + SDL_WaylandDataDevice *data_device = NULL; + void *buffer = NULL; + + if (video_data->input && video_data->input->data_device) { + data_device = video_data->input->data_device; + if (data_device->selection_source) { + buffer = SDL_GetInternalClipboardData(_this, mime_type, length); + } else if (Wayland_data_offer_has_mime(data_device->selection_offer, mime_type)) { + buffer = Wayland_data_offer_receive(data_device->selection_offer, mime_type, length); + } + } + + return buffer; +} + +bool Wayland_HasClipboardData(SDL_VideoDevice *_this, const char *mime_type) +{ + SDL_VideoData *video_data = _this->internal; + SDL_WaylandDataDevice *data_device = NULL; + bool result = false; + + if (video_data->input && video_data->input->data_device) { + data_device = video_data->input->data_device; + if (data_device->selection_source) { + result = SDL_HasInternalClipboardData(_this, mime_type); + } else { + result = Wayland_data_offer_has_mime(data_device->selection_offer, mime_type); + } + } + return result; +} + +static const char *text_mime_types[] = { + TEXT_MIME, + "text/plain", + "TEXT", + "UTF8_STRING", + "STRING" +}; + +const char **Wayland_GetTextMimeTypes(SDL_VideoDevice *_this, size_t *num_mime_types) +{ + *num_mime_types = SDL_arraysize(text_mime_types); + return text_mime_types; +} + +bool Wayland_SetPrimarySelectionText(SDL_VideoDevice *_this, const char *text) +{ + SDL_VideoData *video_data = _this->internal; + SDL_WaylandPrimarySelectionDevice *primary_selection_device = NULL; + bool result; + + if (video_data->input && video_data->input->primary_selection_device) { + primary_selection_device = video_data->input->primary_selection_device; + if (text[0] != '\0') { + SDL_WaylandPrimarySelectionSource *source = Wayland_primary_selection_source_create(_this); + Wayland_primary_selection_source_set_callback(source, SDL_ClipboardTextCallback, SDL_strdup(text)); + + result = Wayland_primary_selection_device_set_selection(primary_selection_device, + source, + text_mime_types, + SDL_arraysize(text_mime_types)); + if (!result) { + Wayland_primary_selection_source_destroy(source); + } + } else { + result = Wayland_primary_selection_device_clear_selection(primary_selection_device); + } + } else { + result = SDL_SetError("Primary selection not supported"); + } + return result; +} + +char *Wayland_GetPrimarySelectionText(SDL_VideoDevice *_this) +{ + SDL_VideoData *video_data = _this->internal; + SDL_WaylandPrimarySelectionDevice *primary_selection_device = NULL; + char *text = NULL; + size_t length = 0; + + if (video_data->input && video_data->input->primary_selection_device) { + primary_selection_device = video_data->input->primary_selection_device; + if (primary_selection_device->selection_source) { + text = Wayland_primary_selection_source_get_data(primary_selection_device->selection_source, TEXT_MIME, &length); + } else if (Wayland_primary_selection_offer_has_mime(primary_selection_device->selection_offer, TEXT_MIME)) { + text = Wayland_primary_selection_offer_receive(primary_selection_device->selection_offer, TEXT_MIME, &length); + } + } + + if (!text) { + text = SDL_strdup(""); + } + + return text; +} + +bool Wayland_HasPrimarySelectionText(SDL_VideoDevice *_this) +{ + SDL_VideoData *video_data = _this->internal; + SDL_WaylandPrimarySelectionDevice *primary_selection_device = NULL; + bool result = false; + + if (video_data->input && video_data->input->primary_selection_device) { + primary_selection_device = video_data->input->primary_selection_device; + if (primary_selection_device->selection_source) { + result = true; + } else { + result = Wayland_primary_selection_offer_has_mime(primary_selection_device->selection_offer, TEXT_MIME); + } + } + return result; +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandclipboard.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandclipboard.h new file mode 100644 index 0000000..ed6546f --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandclipboard.h @@ -0,0 +1,34 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_waylandclipboard_h_ +#define SDL_waylandclipboard_h_ + +extern const char **Wayland_GetTextMimeTypes(SDL_VideoDevice *_this, size_t *num_mime_types); +extern bool Wayland_SetClipboardData(SDL_VideoDevice *_this); +extern void *Wayland_GetClipboardData(SDL_VideoDevice *_this, const char *mime_type, size_t *length); +extern bool Wayland_HasClipboardData(SDL_VideoDevice *_this, const char *mime_type); +extern bool Wayland_SetPrimarySelectionText(SDL_VideoDevice *_this, const char *text); +extern char *Wayland_GetPrimarySelectionText(SDL_VideoDevice *_this); +extern bool Wayland_HasPrimarySelectionText(SDL_VideoDevice *_this); + +#endif // SDL_waylandclipboard_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandcolor.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandcolor.c new file mode 100644 index 0000000..dfc69bb --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandcolor.c @@ -0,0 +1,303 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#include "SDL_waylandcolor.h" +#include "SDL_waylandvideo.h" +#include "SDL_waylandwindow.h" +#include "color-management-v1-client-protocol.h" +#include "../../events/SDL_windowevents_c.h" + +typedef struct Wayland_ColorInfoState +{ + struct wp_image_description_v1 *wp_image_description; + struct wp_image_description_info_v1 *wp_image_description_info; + + union + { + SDL_WindowData *window_data; + SDL_DisplayData *display_data; + }; + + enum + { + WAYLAND_COLOR_OBJECT_TYPE_WINDOW, + WAYLAND_COLOR_OBJECT_TYPE_DISPLAY + } object_type; + + SDL_HDROutputProperties HDR; + + // The ICC fd is only valid if the size is non-zero. + int icc_fd; + Uint32 icc_size; + + bool deferred_event_processing; +} Wayland_ColorInfoState; + +static void Wayland_CancelColorInfoRequest(Wayland_ColorInfoState *state) +{ + if (state) { + if (state->wp_image_description_info) { + wp_image_description_info_v1_destroy(state->wp_image_description_info); + state->wp_image_description_info = NULL; + } + if (state->wp_image_description) { + wp_image_description_v1_destroy(state->wp_image_description); + state->wp_image_description = NULL; + } + } +} + +void Wayland_FreeColorInfoState(Wayland_ColorInfoState *state) +{ + if (state) { + Wayland_CancelColorInfoRequest(state); + + switch (state->object_type) { + case WAYLAND_COLOR_OBJECT_TYPE_WINDOW: + state->window_data->color_info_state = NULL; + break; + case WAYLAND_COLOR_OBJECT_TYPE_DISPLAY: + state->display_data->color_info_state = NULL; + break; + } + + SDL_free(state); + } +} + +static void image_description_info_handle_done(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1) +{ + Wayland_ColorInfoState *state = (Wayland_ColorInfoState *)data; + Wayland_CancelColorInfoRequest(state); + + switch (state->object_type) { + case WAYLAND_COLOR_OBJECT_TYPE_WINDOW: + { + SDL_SetWindowHDRProperties(state->window_data->sdlwindow, &state->HDR, true); + if (state->icc_size) { + state->window_data->icc_fd = state->icc_fd; + state->window_data->icc_size = state->icc_size; + SDL_SendWindowEvent(state->window_data->sdlwindow, SDL_EVENT_WINDOW_ICCPROF_CHANGED, 0, 0); + } + } break; + case WAYLAND_COLOR_OBJECT_TYPE_DISPLAY: + { + SDL_copyp(&state->display_data->HDR, &state->HDR); + } break; + } +} + +static void image_description_info_handle_icc_file(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + int32_t icc, uint32_t icc_size) +{ + Wayland_ColorInfoState *state = (Wayland_ColorInfoState *)data; + + state->icc_fd = icc; + state->icc_size = icc_size; +} + +static void image_description_info_handle_primaries(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + int32_t r_x, int32_t r_y, + int32_t g_x, int32_t g_y, + int32_t b_x, int32_t b_y, + int32_t w_x, int32_t w_y) +{ + // NOP +} + +static void image_description_info_handle_primaries_named(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + uint32_t primaries) +{ + // NOP +} + +static void image_description_info_handle_tf_power(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + uint32_t eexp) +{ + // NOP +} + +static void image_description_info_handle_tf_named(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + uint32_t tf) +{ + // NOP +} + +static void image_description_info_handle_luminances(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + uint32_t min_lum, + uint32_t max_lum, + uint32_t reference_lum) +{ + Wayland_ColorInfoState *state = (Wayland_ColorInfoState *)data; + state->HDR.HDR_headroom = (float)max_lum / (float)reference_lum; +} + +static void image_description_info_handle_target_primaries(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + int32_t r_x, int32_t r_y, + int32_t g_x, int32_t g_y, + int32_t b_x, int32_t b_y, + int32_t w_x, int32_t w_y) +{ + // NOP +} + +static void image_description_info_handle_target_luminance(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + uint32_t min_lum, + uint32_t max_lum) +{ + // NOP +} + +static void image_description_info_handle_target_max_cll(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + uint32_t max_cll) +{ + // NOP +} + +static void image_description_info_handle_target_max_fall(void *data, + struct wp_image_description_info_v1 *wp_image_description_info_v1, + uint32_t max_fall) +{ + // NOP +} + +static const struct wp_image_description_info_v1_listener image_description_info_listener = { + image_description_info_handle_done, + image_description_info_handle_icc_file, + image_description_info_handle_primaries, + image_description_info_handle_primaries_named, + image_description_info_handle_tf_power, + image_description_info_handle_tf_named, + image_description_info_handle_luminances, + image_description_info_handle_target_primaries, + image_description_info_handle_target_luminance, + image_description_info_handle_target_max_cll, + image_description_info_handle_target_max_fall +}; + +static void PumpColorspaceEvents(Wayland_ColorInfoState *state) +{ + SDL_VideoData *vid = SDL_GetVideoDevice()->internal; + + // Run the image description sequence to completion in its own queue. + struct wl_event_queue *queue = WAYLAND_wl_display_create_queue(vid->display); + if (state->deferred_event_processing) { + WAYLAND_wl_proxy_set_queue((struct wl_proxy *)state->wp_image_description_info, queue); + } else { + WAYLAND_wl_proxy_set_queue((struct wl_proxy *)state->wp_image_description, queue); + } + + while (state->wp_image_description) { + WAYLAND_wl_display_dispatch_queue(vid->display, queue); + } + + WAYLAND_wl_event_queue_destroy(queue); + Wayland_FreeColorInfoState(state); +} + +static void image_description_handle_failed(void *data, + struct wp_image_description_v1 *wp_image_description_v1, + uint32_t cause, + const char *msg) +{ + Wayland_ColorInfoState *state = (Wayland_ColorInfoState *)data; + Wayland_CancelColorInfoRequest(state); + + if (state->deferred_event_processing) { + Wayland_FreeColorInfoState(state); + } +} + +static void image_description_handle_ready(void *data, + struct wp_image_description_v1 *wp_image_description_v1, + uint32_t identity) +{ + Wayland_ColorInfoState *state = (Wayland_ColorInfoState *)data; + + // This will inherit the queue of the factory image description object. + state->wp_image_description_info = wp_image_description_v1_get_information(state->wp_image_description); + wp_image_description_info_v1_add_listener(state->wp_image_description_info, &image_description_info_listener, data); + + if (state->deferred_event_processing) { + PumpColorspaceEvents(state); + } +} + +static const struct wp_image_description_v1_listener image_description_listener = { + image_description_handle_failed, + image_description_handle_ready +}; + +void Wayland_GetColorInfoForWindow(SDL_WindowData *window_data, bool defer_event_processing) +{ + // Cancel any pending request, as it is out-of-date. + Wayland_FreeColorInfoState(window_data->color_info_state); + Wayland_ColorInfoState *state = SDL_calloc(1, sizeof(Wayland_ColorInfoState)); + + if (state) { + window_data->color_info_state = state; + state->window_data = window_data; + state->object_type = WAYLAND_COLOR_OBJECT_TYPE_WINDOW; + state->deferred_event_processing = defer_event_processing; + state->wp_image_description = wp_color_management_surface_feedback_v1_get_preferred(window_data->wp_color_management_surface_feedback); + wp_image_description_v1_add_listener(state->wp_image_description, &image_description_listener, state); + + if (!defer_event_processing) { + PumpColorspaceEvents(state); + } + } +} + +void Wayland_GetColorInfoForOutput(SDL_DisplayData *display_data, bool defer_event_processing) +{ + // Cancel any pending request, as it is out-of-date. + Wayland_FreeColorInfoState(display_data->color_info_state); + Wayland_ColorInfoState *state = SDL_calloc(1, sizeof(Wayland_ColorInfoState)); + + if (state) { + display_data->color_info_state = state; + state->display_data = display_data; + state->object_type = WAYLAND_COLOR_OBJECT_TYPE_DISPLAY; + state->deferred_event_processing = defer_event_processing; + state->wp_image_description = wp_color_management_output_v1_get_image_description(display_data->wp_color_management_output); + wp_image_description_v1_add_listener(state->wp_image_description, &image_description_listener, state); + + if (!defer_event_processing) { + PumpColorspaceEvents(state); + } + } +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandcolor.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandcolor.h new file mode 100644 index 0000000..bef5d8c --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandcolor.h @@ -0,0 +1,35 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_waylandcolor_h_ +#define SDL_waylandcolor_h_ + +#include "../SDL_sysvideo.h" + +struct Wayland_ColorInfoState; + +extern void Wayland_FreeColorInfoState(struct Wayland_ColorInfoState *state); +extern void Wayland_GetColorInfoForWindow(SDL_WindowData *window_data, bool defer_event_processing); +extern void Wayland_GetColorInfoForOutput(SDL_DisplayData *display_data, bool defer_event_processing); + +#endif // SDL_waylandcolor_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddatamanager.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddatamanager.c new file mode 100644 index 0000000..6f5b32b --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddatamanager.c @@ -0,0 +1,619 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#include +#include +#include +#include + +#include "../../core/unix/SDL_poll.h" +#include "../../events/SDL_events_c.h" +#include "../SDL_clipboard_c.h" + +#include "SDL_waylandvideo.h" +#include "SDL_waylanddatamanager.h" +#include "primary-selection-unstable-v1-client-protocol.h" + +/* FIXME: This is arbitrary, but we want this to be less than a frame because + * any longer can potentially spin an infinite loop of PumpEvents (!) + */ +#define PIPE_TIMEOUT_NS SDL_MS_TO_NS(14) + +static ssize_t write_pipe(int fd, const void *buffer, size_t total_length, size_t *pos) +{ + int ready = 0; + ssize_t bytes_written = 0; + ssize_t length = total_length - *pos; + + sigset_t sig_set; + sigset_t old_sig_set; + struct timespec zerotime = { 0 }; + + ready = SDL_IOReady(fd, SDL_IOR_WRITE, PIPE_TIMEOUT_NS); + + sigemptyset(&sig_set); + sigaddset(&sig_set, SIGPIPE); + +#ifdef SDL_THREADS_DISABLED + sigprocmask(SIG_BLOCK, &sig_set, &old_sig_set); +#else + pthread_sigmask(SIG_BLOCK, &sig_set, &old_sig_set); +#endif + + if (ready == 0) { + bytes_written = SDL_SetError("Pipe timeout"); + } else if (ready < 0) { + bytes_written = SDL_SetError("Pipe select error"); + } else { + if (length > 0) { + bytes_written = write(fd, (Uint8 *)buffer + *pos, SDL_min(length, PIPE_BUF)); + } + + if (bytes_written > 0) { + *pos += bytes_written; + } + } + + sigtimedwait(&sig_set, 0, &zerotime); + +#ifdef SDL_THREADS_DISABLED + sigprocmask(SIG_SETMASK, &old_sig_set, NULL); +#else + pthread_sigmask(SIG_SETMASK, &old_sig_set, NULL); +#endif + + return bytes_written; +} + +static ssize_t read_pipe(int fd, void **buffer, size_t *total_length) +{ + int ready = 0; + void *output_buffer = NULL; + char temp[PIPE_BUF]; + size_t new_buffer_length = 0; + ssize_t bytes_read = 0; + size_t pos = 0; + + ready = SDL_IOReady(fd, SDL_IOR_READ, PIPE_TIMEOUT_NS); + + if (ready == 0) { + bytes_read = SDL_SetError("Pipe timeout"); + } else if (ready < 0) { + bytes_read = SDL_SetError("Pipe select error"); + } else { + bytes_read = read(fd, temp, sizeof(temp)); + } + + if (bytes_read > 0) { + pos = *total_length; + *total_length += bytes_read; + + new_buffer_length = *total_length + sizeof(Uint32); + + if (!*buffer) { + output_buffer = SDL_malloc(new_buffer_length); + } else { + output_buffer = SDL_realloc(*buffer, new_buffer_length); + } + + if (!output_buffer) { + bytes_read = -1; + } else { + SDL_memcpy((Uint8 *)output_buffer + pos, temp, bytes_read); + SDL_memset((Uint8 *)output_buffer + (new_buffer_length - sizeof(Uint32)), 0, sizeof(Uint32)); + + *buffer = output_buffer; + } + } + + return bytes_read; +} + +static SDL_MimeDataList *mime_data_list_find(struct wl_list *list, + const char *mime_type) +{ + SDL_MimeDataList *found = NULL; + + SDL_MimeDataList *mime_list = NULL; + wl_list_for_each (mime_list, list, link) { + if (SDL_strcmp(mime_list->mime_type, mime_type) == 0) { + found = mime_list; + break; + } + } + return found; +} + +static bool mime_data_list_add(struct wl_list *list, + const char *mime_type, + const void *buffer, size_t length) +{ + bool result = true; + size_t mime_type_length = 0; + SDL_MimeDataList *mime_data = NULL; + void *internal_buffer = NULL; + + if (buffer) { + internal_buffer = SDL_malloc(length); + if (!internal_buffer) { + return false; + } + SDL_memcpy(internal_buffer, buffer, length); + } + + mime_data = mime_data_list_find(list, mime_type); + + if (!mime_data) { + mime_data = SDL_calloc(1, sizeof(*mime_data)); + if (!mime_data) { + result = false; + } else { + WAYLAND_wl_list_insert(list, &(mime_data->link)); + + mime_type_length = SDL_strlen(mime_type) + 1; + mime_data->mime_type = SDL_malloc(mime_type_length); + if (!mime_data->mime_type) { + result = false; + } else { + SDL_memcpy(mime_data->mime_type, mime_type, mime_type_length); + } + } + } + + if (mime_data && buffer && length > 0) { + if (mime_data->data) { + SDL_free(mime_data->data); + } + mime_data->data = internal_buffer; + mime_data->length = length; + } else { + SDL_free(internal_buffer); + } + + return result; +} + +static void mime_data_list_free(struct wl_list *list) +{ + SDL_MimeDataList *mime_data = NULL; + SDL_MimeDataList *next = NULL; + + wl_list_for_each_safe (mime_data, next, list, link) { + if (mime_data->data) { + SDL_free(mime_data->data); + } + if (mime_data->mime_type) { + SDL_free(mime_data->mime_type); + } + SDL_free(mime_data); + } +} + +static size_t Wayland_send_data(const void *data, size_t length, int fd) +{ + size_t result = 0; + + if (length > 0 && data) { + while (write_pipe(fd, data, length, &result) > 0) { + // Just keep spinning + } + } + close(fd); + + return result; +} + +ssize_t Wayland_data_source_send(SDL_WaylandDataSource *source, const char *mime_type, int fd) +{ + const void *data = NULL; + size_t length = 0; + + if (source->callback) { + data = source->callback(source->userdata.data, mime_type, &length); + } + + return Wayland_send_data(data, length, fd); +} + +ssize_t Wayland_primary_selection_source_send(SDL_WaylandPrimarySelectionSource *source, const char *mime_type, int fd) +{ + const void *data = NULL; + size_t length = 0; + + if (source->callback) { + data = source->callback(source->userdata.data, mime_type, &length); + } + + return Wayland_send_data(data, length, fd); +} + +void Wayland_data_source_set_callback(SDL_WaylandDataSource *source, + SDL_ClipboardDataCallback callback, + void *userdata, + Uint32 sequence) +{ + if (source) { + source->callback = callback; + source->userdata.sequence = sequence; + source->userdata.data = userdata; + } +} + +void Wayland_primary_selection_source_set_callback(SDL_WaylandPrimarySelectionSource *source, + SDL_ClipboardDataCallback callback, + void *userdata) +{ + if (source) { + source->callback = callback; + source->userdata.sequence = 0; + source->userdata.data = userdata; + } +} + +static void *Wayland_clone_data_buffer(const void *buffer, const size_t *len) +{ + void *clone = NULL; + if (*len > 0 && buffer) { + clone = SDL_malloc((*len)+sizeof(Uint32)); + if (clone) { + SDL_memcpy(clone, buffer, *len); + SDL_memset((Uint8 *)clone + *len, 0, sizeof(Uint32)); + } + } + return clone; +} + +void *Wayland_data_source_get_data(SDL_WaylandDataSource *source, + const char *mime_type, size_t *length) +{ + void *buffer = NULL; + const void *internal_buffer; + *length = 0; + + if (!source) { + SDL_SetError("Invalid data source"); + } else if (source->callback) { + internal_buffer = source->callback(source->userdata.data, mime_type, length); + buffer = Wayland_clone_data_buffer(internal_buffer, length); + } + + return buffer; +} + +void *Wayland_primary_selection_source_get_data(SDL_WaylandPrimarySelectionSource *source, + const char *mime_type, size_t *length) +{ + void *buffer = NULL; + const void *internal_buffer; + *length = 0; + + if (!source) { + SDL_SetError("Invalid primary selection source"); + } else if (source->callback) { + internal_buffer = source->callback(source->userdata.data, mime_type, length); + buffer = Wayland_clone_data_buffer(internal_buffer, length); + } + + return buffer; +} + +void Wayland_data_source_destroy(SDL_WaylandDataSource *source) +{ + if (source) { + SDL_WaylandDataDevice *data_device = (SDL_WaylandDataDevice *)source->data_device; + if (data_device && (data_device->selection_source == source)) { + data_device->selection_source = NULL; + } + wl_data_source_destroy(source->source); + if (source->userdata.sequence) { + SDL_CancelClipboardData(source->userdata.sequence); + } else { + SDL_free(source->userdata.data); + } + SDL_free(source); + } +} + +void Wayland_primary_selection_source_destroy(SDL_WaylandPrimarySelectionSource *source) +{ + if (source) { + SDL_WaylandPrimarySelectionDevice *primary_selection_device = (SDL_WaylandPrimarySelectionDevice *)source->primary_selection_device; + if (primary_selection_device && (primary_selection_device->selection_source == source)) { + primary_selection_device->selection_source = NULL; + } + zwp_primary_selection_source_v1_destroy(source->source); + if (source->userdata.sequence == 0) { + SDL_free(source->userdata.data); + } + SDL_free(source); + } +} + +void *Wayland_data_offer_receive(SDL_WaylandDataOffer *offer, + const char *mime_type, size_t *length) +{ + SDL_WaylandDataDevice *data_device = NULL; + + int pipefd[2]; + void *buffer = NULL; + *length = 0; + + if (!offer) { + SDL_SetError("Invalid data offer"); + return NULL; + } + data_device = offer->data_device; + if (!data_device) { + SDL_SetError("Data device not initialized"); + } else if (pipe2(pipefd, O_CLOEXEC | O_NONBLOCK) == -1) { + SDL_SetError("Could not read pipe"); + } else { + wl_data_offer_receive(offer->offer, mime_type, pipefd[1]); + + // TODO: Needs pump and flush? + WAYLAND_wl_display_flush(data_device->video_data->display); + + close(pipefd[1]); + + while (read_pipe(pipefd[0], &buffer, length) > 0) { + } + close(pipefd[0]); + } + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In Wayland_data_offer_receive for '%s', buffer (%zu) at %p", + mime_type, *length, buffer); + return buffer; +} + +void *Wayland_primary_selection_offer_receive(SDL_WaylandPrimarySelectionOffer *offer, + const char *mime_type, size_t *length) +{ + SDL_WaylandPrimarySelectionDevice *primary_selection_device = NULL; + + int pipefd[2]; + void *buffer = NULL; + *length = 0; + + if (!offer) { + SDL_SetError("Invalid data offer"); + return NULL; + } + primary_selection_device = offer->primary_selection_device; + if (!primary_selection_device) { + SDL_SetError("Primary selection device not initialized"); + } else if (pipe2(pipefd, O_CLOEXEC | O_NONBLOCK) == -1) { + SDL_SetError("Could not read pipe"); + } else { + zwp_primary_selection_offer_v1_receive(offer->offer, mime_type, pipefd[1]); + + // TODO: Needs pump and flush? + WAYLAND_wl_display_flush(primary_selection_device->video_data->display); + + close(pipefd[1]); + + while (read_pipe(pipefd[0], &buffer, length) > 0) { + } + close(pipefd[0]); + } + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In Wayland_primary_selection_offer_receive for '%s', buffer (%zu) at %p", + mime_type, *length, buffer); + return buffer; +} + +bool Wayland_data_offer_add_mime(SDL_WaylandDataOffer *offer, + const char *mime_type) +{ + return mime_data_list_add(&offer->mimes, mime_type, NULL, 0); +} + +bool Wayland_primary_selection_offer_add_mime(SDL_WaylandPrimarySelectionOffer *offer, + const char *mime_type) +{ + return mime_data_list_add(&offer->mimes, mime_type, NULL, 0); +} + +bool Wayland_data_offer_has_mime(SDL_WaylandDataOffer *offer, + const char *mime_type) +{ + bool found = false; + + if (offer) { + found = mime_data_list_find(&offer->mimes, mime_type) != NULL; + } + return found; +} + +bool Wayland_primary_selection_offer_has_mime(SDL_WaylandPrimarySelectionOffer *offer, + const char *mime_type) +{ + bool found = false; + + if (offer) { + found = mime_data_list_find(&offer->mimes, mime_type) != NULL; + } + return found; +} + +void Wayland_data_offer_destroy(SDL_WaylandDataOffer *offer) +{ + if (offer) { + wl_data_offer_destroy(offer->offer); + mime_data_list_free(&offer->mimes); + SDL_free(offer); + } +} + +void Wayland_primary_selection_offer_destroy(SDL_WaylandPrimarySelectionOffer *offer) +{ + if (offer) { + zwp_primary_selection_offer_v1_destroy(offer->offer); + mime_data_list_free(&offer->mimes); + SDL_free(offer); + } +} + +bool Wayland_data_device_clear_selection(SDL_WaylandDataDevice *data_device) +{ + bool result = true; + + if (!data_device || !data_device->data_device) { + result = SDL_SetError("Invalid Data Device"); + } else if (data_device->selection_source) { + wl_data_device_set_selection(data_device->data_device, NULL, 0); + Wayland_data_source_destroy(data_device->selection_source); + data_device->selection_source = NULL; + } + return result; +} + +bool Wayland_primary_selection_device_clear_selection(SDL_WaylandPrimarySelectionDevice *primary_selection_device) +{ + bool result = true; + + if (!primary_selection_device || !primary_selection_device->primary_selection_device) { + result = SDL_SetError("Invalid Primary Selection Device"); + } else if (primary_selection_device->selection_source) { + zwp_primary_selection_device_v1_set_selection(primary_selection_device->primary_selection_device, + NULL, 0); + Wayland_primary_selection_source_destroy(primary_selection_device->selection_source); + primary_selection_device->selection_source = NULL; + } + return result; +} + +bool Wayland_data_device_set_selection(SDL_WaylandDataDevice *data_device, + SDL_WaylandDataSource *source, + const char **mime_types, + size_t mime_count) +{ + bool result = true; + + if (!data_device) { + result = SDL_SetError("Invalid Data Device"); + } else if (!source) { + result = SDL_SetError("Invalid source"); + } else { + size_t index = 0; + const char *mime_type; + + for (index = 0; index < mime_count; ++index) { + mime_type = mime_types[index]; + wl_data_source_offer(source->source, + mime_type); + } + + if (index == 0) { + Wayland_data_device_clear_selection(data_device); + result = SDL_SetError("No mime data"); + } else { + // Only set if there is a valid serial if not set it later + if (data_device->selection_serial != 0) { + wl_data_device_set_selection(data_device->data_device, + source->source, + data_device->selection_serial); + } + if (data_device->selection_source) { + Wayland_data_source_destroy(data_device->selection_source); + } + data_device->selection_source = source; + source->data_device = data_device; + } + } + + return result; +} + +bool Wayland_primary_selection_device_set_selection(SDL_WaylandPrimarySelectionDevice *primary_selection_device, + SDL_WaylandPrimarySelectionSource *source, + const char **mime_types, + size_t mime_count) +{ + bool result = true; + + if (!primary_selection_device) { + result = SDL_SetError("Invalid Primary Selection Device"); + } else if (!source) { + result = SDL_SetError("Invalid source"); + } else { + size_t index = 0; + const char *mime_type = mime_types[index]; + + for (index = 0; index < mime_count; ++index) { + mime_type = mime_types[index]; + zwp_primary_selection_source_v1_offer(source->source, mime_type); + } + + if (index == 0) { + Wayland_primary_selection_device_clear_selection(primary_selection_device); + result = SDL_SetError("No mime data"); + } else { + // Only set if there is a valid serial if not set it later + if (primary_selection_device->selection_serial != 0) { + zwp_primary_selection_device_v1_set_selection(primary_selection_device->primary_selection_device, + source->source, + primary_selection_device->selection_serial); + } + if (primary_selection_device->selection_source) { + Wayland_primary_selection_source_destroy(primary_selection_device->selection_source); + } + primary_selection_device->selection_source = source; + source->primary_selection_device = primary_selection_device; + } + } + + return result; +} + +void Wayland_data_device_set_serial(SDL_WaylandDataDevice *data_device, uint32_t serial) +{ + if (data_device) { + // If there was no serial and there is a pending selection set it now. + if (data_device->selection_serial == 0 && data_device->selection_source) { + wl_data_device_set_selection(data_device->data_device, + data_device->selection_source->source, + data_device->selection_serial); + } + + data_device->selection_serial = serial; + } +} + +void Wayland_primary_selection_device_set_serial(SDL_WaylandPrimarySelectionDevice *primary_selection_device, + uint32_t serial) +{ + if (primary_selection_device) { + // If there was no serial and there is a pending selection set it now. + if (primary_selection_device->selection_serial == 0 && primary_selection_device->selection_source) { + zwp_primary_selection_device_v1_set_selection(primary_selection_device->primary_selection_device, + primary_selection_device->selection_source->source, + primary_selection_device->selection_serial); + } + + primary_selection_device->selection_serial = serial; + } +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddatamanager.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddatamanager.h new file mode 100644 index 0000000..adca17b --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddatamanager.h @@ -0,0 +1,162 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_waylanddatamanager_h_ +#define SDL_waylanddatamanager_h_ + +#include "SDL_waylandvideo.h" +#include "SDL_waylandwindow.h" + +#define TEXT_MIME "text/plain;charset=utf-8" +#define FILE_MIME "text/uri-list" +#define FILE_PORTAL_MIME "application/vnd.portal.filetransfer" + +typedef struct +{ + char *mime_type; + void *data; + size_t length; + struct wl_list link; +} SDL_MimeDataList; + +typedef struct SDL_WaylandUserdata +{ + Uint32 sequence; + void *data; +} SDL_WaylandUserdata; + +typedef struct +{ + struct wl_data_source *source; + void *data_device; + SDL_ClipboardDataCallback callback; + SDL_WaylandUserdata userdata; +} SDL_WaylandDataSource; + +typedef struct +{ + struct zwp_primary_selection_source_v1 *source; + void *data_device; + void *primary_selection_device; + SDL_ClipboardDataCallback callback; + SDL_WaylandUserdata userdata; +} SDL_WaylandPrimarySelectionSource; + +typedef struct +{ + struct wl_data_offer *offer; + struct wl_list mimes; + void *data_device; +} SDL_WaylandDataOffer; + +typedef struct +{ + struct zwp_primary_selection_offer_v1 *offer; + struct wl_list mimes; + void *primary_selection_device; +} SDL_WaylandPrimarySelectionOffer; + +typedef struct +{ + struct wl_data_device *data_device; + SDL_VideoData *video_data; + + // Drag and Drop + uint32_t drag_serial; + SDL_WaylandDataOffer *drag_offer; + SDL_WaylandDataOffer *selection_offer; + bool has_mime_file, has_mime_text; + SDL_Window *dnd_window; + + // Clipboard and Primary Selection + uint32_t selection_serial; + SDL_WaylandDataSource *selection_source; +} SDL_WaylandDataDevice; + +typedef struct +{ + struct zwp_primary_selection_device_v1 *primary_selection_device; + SDL_VideoData *video_data; + + uint32_t selection_serial; + SDL_WaylandPrimarySelectionSource *selection_source; + SDL_WaylandPrimarySelectionOffer *selection_offer; +} SDL_WaylandPrimarySelectionDevice; + +// Wayland Data Source / Primary Selection Source - (Sending) +extern SDL_WaylandDataSource *Wayland_data_source_create(SDL_VideoDevice *_this); +extern SDL_WaylandPrimarySelectionSource *Wayland_primary_selection_source_create(SDL_VideoDevice *_this); +extern ssize_t Wayland_data_source_send(SDL_WaylandDataSource *source, + const char *mime_type, int fd); +extern ssize_t Wayland_primary_selection_source_send(SDL_WaylandPrimarySelectionSource *source, + const char *mime_type, int fd); +extern void Wayland_data_source_set_callback(SDL_WaylandDataSource *source, + SDL_ClipboardDataCallback callback, + void *userdata, + Uint32 sequence); +extern void Wayland_primary_selection_source_set_callback(SDL_WaylandPrimarySelectionSource *source, + SDL_ClipboardDataCallback callback, + void *userdata); +extern void *Wayland_data_source_get_data(SDL_WaylandDataSource *source, + const char *mime_type, + size_t *length); +extern void *Wayland_primary_selection_source_get_data(SDL_WaylandPrimarySelectionSource *source, + const char *mime_type, + size_t *length); +extern void Wayland_data_source_destroy(SDL_WaylandDataSource *source); +extern void Wayland_primary_selection_source_destroy(SDL_WaylandPrimarySelectionSource *source); + +// Wayland Data / Primary Selection Offer - (Receiving) +extern void *Wayland_data_offer_receive(SDL_WaylandDataOffer *offer, + const char *mime_type, + size_t *length); +extern void *Wayland_primary_selection_offer_receive(SDL_WaylandPrimarySelectionOffer *offer, + const char *mime_type, + size_t *length); +extern bool Wayland_data_offer_has_mime(SDL_WaylandDataOffer *offer, + const char *mime_type); +extern bool Wayland_primary_selection_offer_has_mime(SDL_WaylandPrimarySelectionOffer *offer, + const char *mime_type); +extern bool Wayland_data_offer_add_mime(SDL_WaylandDataOffer *offer, + const char *mime_type); +extern bool Wayland_primary_selection_offer_add_mime(SDL_WaylandPrimarySelectionOffer *offer, + const char *mime_type); +extern void Wayland_data_offer_destroy(SDL_WaylandDataOffer *offer); +extern void Wayland_primary_selection_offer_destroy(SDL_WaylandPrimarySelectionOffer *offer); + +// Clipboard / Primary Selection +extern bool Wayland_data_device_clear_selection(SDL_WaylandDataDevice *device); +extern bool Wayland_primary_selection_device_clear_selection(SDL_WaylandPrimarySelectionDevice *device); +extern bool Wayland_data_device_set_selection(SDL_WaylandDataDevice *device, + SDL_WaylandDataSource *source, + const char **mime_types, + size_t mime_count); +extern bool Wayland_primary_selection_device_set_selection(SDL_WaylandPrimarySelectionDevice *device, + SDL_WaylandPrimarySelectionSource *source, + const char **mime_types, + size_t mime_count); +extern void Wayland_data_device_set_serial(SDL_WaylandDataDevice *device, + uint32_t serial); +extern void Wayland_primary_selection_device_set_serial(SDL_WaylandPrimarySelectionDevice *device, + uint32_t serial); +#endif // SDL_waylanddatamanager_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddyn.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddyn.c new file mode 100644 index 0000000..7d6d42f --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddyn.c @@ -0,0 +1,176 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#define DEBUG_DYNAMIC_WAYLAND 0 + +#include "SDL_waylanddyn.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC + +typedef struct +{ + SDL_SharedObject *lib; + const char *libname; +} waylanddynlib; + +static waylanddynlib waylandlibs[] = { + { NULL, SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC }, +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL + { NULL, SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL }, +#endif +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR + { NULL, SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR }, +#endif +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON + { NULL, SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON }, +#endif +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR + { NULL, SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR }, +#endif + { NULL, NULL } +}; + +static void *WAYLAND_GetSym(const char *fnname, int *pHasModule, bool required) +{ + void *fn = NULL; + waylanddynlib *dynlib; + for (dynlib = waylandlibs; dynlib->libname; dynlib++) { + if (dynlib->lib) { + fn = SDL_LoadFunction(dynlib->lib, fnname); + if (fn) { + break; + } + } + } + +#if DEBUG_DYNAMIC_WAYLAND + if (fn) { + SDL_Log("WAYLAND: Found '%s' in %s (%p)", fnname, dynlib->libname, fn); + } else { + SDL_Log("WAYLAND: Symbol '%s' NOT FOUND!", fnname); + } +#endif + + if (!fn && required) { + *pHasModule = 0; // kill this module. + } + + return fn; +} + +#else + +#include + +#endif // SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC + +// Define all the function pointers and wrappers... +#define SDL_WAYLAND_MODULE(modname) int SDL_WAYLAND_HAVE_##modname = 0; +#define SDL_WAYLAND_SYM(rc, fn, params) SDL_DYNWAYLANDFN_##fn WAYLAND_##fn = NULL; +#define SDL_WAYLAND_SYM_OPT(rc, fn, params) SDL_DYNWAYLANDFN_##fn WAYLAND_##fn = NULL; +#define SDL_WAYLAND_INTERFACE(iface) const struct wl_interface *WAYLAND_##iface = NULL; +#include "SDL_waylandsym.h" + +static int wayland_load_refcount = 0; + +void SDL_WAYLAND_UnloadSymbols(void) +{ + // Don't actually unload if more than one module is using the libs... + if (wayland_load_refcount > 0) { + if (--wayland_load_refcount == 0) { +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC + int i; +#endif + + // set all the function pointers to NULL. +#define SDL_WAYLAND_MODULE(modname) SDL_WAYLAND_HAVE_##modname = 0; +#define SDL_WAYLAND_SYM(rc, fn, params) WAYLAND_##fn = NULL; +#define SDL_WAYLAND_SYM_OPT(rc, fn, params) WAYLAND_##fn = NULL; +#define SDL_WAYLAND_INTERFACE(iface) WAYLAND_##iface = NULL; +#include "SDL_waylandsym.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC + for (i = 0; i < SDL_arraysize(waylandlibs); i++) { + if (waylandlibs[i].lib) { + SDL_UnloadObject(waylandlibs[i].lib); + waylandlibs[i].lib = NULL; + } + } +#endif + } + } +} + +// returns non-zero if all needed symbols were loaded. +bool SDL_WAYLAND_LoadSymbols(void) +{ + bool result = true; // always succeed if not using Dynamic WAYLAND stuff. + + // deal with multiple modules (dga, wayland, etc) needing these symbols... + if (wayland_load_refcount++ == 0) { +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC + int i; + int *thismod = NULL; + for (i = 0; i < SDL_arraysize(waylandlibs); i++) { + if (waylandlibs[i].libname) { + waylandlibs[i].lib = SDL_LoadObject(waylandlibs[i].libname); + } + } + +#define SDL_WAYLAND_MODULE(modname) SDL_WAYLAND_HAVE_##modname = 1; // default yes +#include "SDL_waylandsym.h" + +#define SDL_WAYLAND_MODULE(modname) thismod = &SDL_WAYLAND_HAVE_##modname; +#define SDL_WAYLAND_SYM(rc, fn, params) WAYLAND_##fn = (SDL_DYNWAYLANDFN_##fn)WAYLAND_GetSym(#fn, thismod, true); +#define SDL_WAYLAND_SYM_OPT(rc, fn, params) WAYLAND_##fn = (SDL_DYNWAYLANDFN_##fn)WAYLAND_GetSym(#fn, thismod, false); +#define SDL_WAYLAND_INTERFACE(iface) WAYLAND_##iface = (struct wl_interface *)WAYLAND_GetSym(#iface, thismod, true); +#include "SDL_waylandsym.h" + + if (SDL_WAYLAND_HAVE_WAYLAND_CLIENT && + SDL_WAYLAND_HAVE_WAYLAND_CURSOR && + SDL_WAYLAND_HAVE_WAYLAND_EGL && + SDL_WAYLAND_HAVE_WAYLAND_XKB) { + // All required symbols loaded, only libdecor is optional. + SDL_ClearError(); + } else { + // in case something got loaded... + SDL_WAYLAND_UnloadSymbols(); + result = false; + } + +#else // no dynamic WAYLAND + +#define SDL_WAYLAND_MODULE(modname) SDL_WAYLAND_HAVE_##modname = 1; // default yes +#define SDL_WAYLAND_SYM(rc, fn, params) WAYLAND_##fn = fn; +#define SDL_WAYLAND_SYM_OPT(rc, fn, params) WAYLAND_##fn = fn; +#define SDL_WAYLAND_INTERFACE(iface) WAYLAND_##iface = &iface; +#include "SDL_waylandsym.h" + +#endif + } + + return result; +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddyn.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddyn.h new file mode 100644 index 0000000..fd85a7c --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylanddyn.h @@ -0,0 +1,195 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#ifndef SDL_waylanddyn_h_ +#define SDL_waylanddyn_h_ + +#include "SDL_internal.h" + +/* We can't include wayland-client.h here + * but we need some structs from it + */ +struct wl_interface; +struct wl_proxy; +struct wl_event_queue; +struct wl_display; +struct wl_surface; +struct wl_shm; + +// We also need some for libdecor +struct wl_seat; +struct wl_output; +struct libdecor; +struct libdecor_frame; +struct libdecor_state; +struct libdecor_configuration; +struct libdecor_interface; +struct libdecor_frame_interface; +enum libdecor_resize_edge; +enum libdecor_capabilities; +enum libdecor_window_state; + +#include "wayland-cursor.h" +#include "wayland-util.h" +#include "xkbcommon/xkbcommon.h" +#include "xkbcommon/xkbcommon-compose.h" + +// Must be included before our #defines, see Bugzilla #4957 +#include "wayland-client-core.h" + +#define SDL_WAYLAND_CHECK_VERSION(x, y, z) \ + (WAYLAND_VERSION_MAJOR > x || \ + (WAYLAND_VERSION_MAJOR == x && WAYLAND_VERSION_MINOR > y) || \ + (WAYLAND_VERSION_MAJOR == x && WAYLAND_VERSION_MINOR == y && WAYLAND_VERSION_MICRO >= z)) + +#ifdef HAVE_LIBDECOR_H +#define SDL_LIBDECOR_CHECK_VERSION(x, y, z) \ + (SDL_LIBDECOR_VERSION_MAJOR > x || \ + (SDL_LIBDECOR_VERSION_MAJOR == x && SDL_LIBDECOR_VERSION_MINOR > y) || \ + (SDL_LIBDECOR_VERSION_MAJOR == x && SDL_LIBDECOR_VERSION_MINOR == y && SDL_LIBDECOR_VERSION_PATCH >= z)) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +extern bool SDL_WAYLAND_LoadSymbols(void); +extern void SDL_WAYLAND_UnloadSymbols(void); + +#define SDL_WAYLAND_MODULE(modname) extern int SDL_WAYLAND_HAVE_##modname; +#define SDL_WAYLAND_SYM(rc, fn, params) \ + typedef rc(*SDL_DYNWAYLANDFN_##fn) params; \ + extern SDL_DYNWAYLANDFN_##fn WAYLAND_##fn; +#define SDL_WAYLAND_SYM_OPT(rc, fn, params) \ + typedef rc(*SDL_DYNWAYLANDFN_##fn) params; \ + extern SDL_DYNWAYLANDFN_##fn WAYLAND_##fn; +#define SDL_WAYLAND_INTERFACE(iface) extern const struct wl_interface *WAYLAND_##iface; +#include "SDL_waylandsym.h" + +#ifdef __cplusplus +} +#endif + +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC + +#if defined(_WAYLAND_CLIENT_H) || defined(WAYLAND_CLIENT_H) +#error Do not include wayland-client ahead of SDL_waylanddyn.h in dynamic loading mode +#endif + +/* wayland-client-protocol.h included from wayland-client.h + * has inline functions that require these to be defined in dynamic loading mode + */ + +#define wl_proxy_create (*WAYLAND_wl_proxy_create) +#define wl_proxy_destroy (*WAYLAND_wl_proxy_destroy) +#define wl_proxy_marshal (*WAYLAND_wl_proxy_marshal) +#define wl_proxy_set_user_data (*WAYLAND_wl_proxy_set_user_data) +#define wl_proxy_get_user_data (*WAYLAND_wl_proxy_get_user_data) +#define wl_proxy_get_version (*WAYLAND_wl_proxy_get_version) +#define wl_proxy_add_listener (*WAYLAND_wl_proxy_add_listener) +#define wl_proxy_marshal_constructor (*WAYLAND_wl_proxy_marshal_constructor) +#define wl_proxy_marshal_constructor_versioned (*WAYLAND_wl_proxy_marshal_constructor_versioned) +#define wl_proxy_set_tag (*WAYLAND_wl_proxy_set_tag) +#define wl_proxy_get_tag (*WAYLAND_wl_proxy_get_tag) +#define wl_proxy_marshal_flags (*WAYLAND_wl_proxy_marshal_flags) +#define wl_proxy_marshal_array_flags (*WAYLAND_wl_proxy_marshal_array_flags) +#define wl_display_reconnect (*WAYLAND_wl_display_reconnect) + +#define wl_seat_interface (*WAYLAND_wl_seat_interface) +#define wl_surface_interface (*WAYLAND_wl_surface_interface) +#define wl_shm_pool_interface (*WAYLAND_wl_shm_pool_interface) +#define wl_buffer_interface (*WAYLAND_wl_buffer_interface) +#define wl_registry_interface (*WAYLAND_wl_registry_interface) +#define wl_region_interface (*WAYLAND_wl_region_interface) +#define wl_pointer_interface (*WAYLAND_wl_pointer_interface) +#define wl_keyboard_interface (*WAYLAND_wl_keyboard_interface) +#define wl_compositor_interface (*WAYLAND_wl_compositor_interface) +#define wl_output_interface (*WAYLAND_wl_output_interface) +#define wl_shm_interface (*WAYLAND_wl_shm_interface) +#define wl_data_device_interface (*WAYLAND_wl_data_device_interface) +#define wl_data_offer_interface (*WAYLAND_wl_data_offer_interface) +#define wl_data_source_interface (*WAYLAND_wl_data_source_interface) +#define wl_data_device_manager_interface (*WAYLAND_wl_data_device_manager_interface) + +/* + * These must be included before libdecor.h, otherwise the libdecor header + * pulls in the system Wayland protocol headers instead of ours. + */ +#include "wayland-client-protocol.h" +#include "wayland-egl.h" + +#ifdef HAVE_LIBDECOR_H +// Must be included before our defines +#include + +#define libdecor_unref (*WAYLAND_libdecor_unref) +#define libdecor_new (*WAYLAND_libdecor_new) +#define libdecor_decorate (*WAYLAND_libdecor_decorate) +#define libdecor_frame_unref (*WAYLAND_libdecor_frame_unref) +#define libdecor_frame_set_title (*WAYLAND_libdecor_frame_set_title) +#define libdecor_frame_set_app_id (*WAYLAND_libdecor_frame_set_app_id) +#define libdecor_frame_set_max_content_size (*WAYLAND_libdecor_frame_set_max_content_size) +#define libdecor_frame_get_max_content_size (*WAYLAND_libdecor_frame_get_max_content_size) +#define libdecor_frame_set_min_content_size (*WAYLAND_libdecor_frame_set_min_content_size) +#define libdecor_frame_get_min_content_size (*WAYLAND_libdecor_frame_get_min_content_size) +#define libdecor_frame_resize (*WAYLAND_libdecor_frame_resize) +#define libdecor_frame_move (*WAYLAND_libdecor_frame_move) +#define libdecor_frame_commit (*WAYLAND_libdecor_frame_commit) +#define libdecor_frame_set_minimized (*WAYLAND_libdecor_frame_set_minimized) +#define libdecor_frame_set_maximized (*WAYLAND_libdecor_frame_set_maximized) +#define libdecor_frame_unset_maximized (*WAYLAND_libdecor_frame_unset_maximized) +#define libdecor_frame_set_fullscreen (*WAYLAND_libdecor_frame_set_fullscreen) +#define libdecor_frame_unset_fullscreen (*WAYLAND_libdecor_frame_unset_fullscreen) +#define libdecor_frame_set_capabilities (*WAYLAND_libdecor_frame_set_capabilities) +#define libdecor_frame_unset_capabilities (*WAYLAND_libdecor_frame_unset_capabilities) +#define libdecor_frame_has_capability (*WAYLAND_libdecor_frame_has_capability) +#define libdecor_frame_set_visibility (*WAYLAND_libdecor_frame_set_visibility) +#define libdecor_frame_is_visible (*WAYLAND_libdecor_frame_is_visible) +#define libdecor_frame_is_floating (*WAYLAND_libdecor_frame_is_floating) +#define libdecor_frame_set_parent (*WAYLAND_libdecor_frame_set_parent) +#define libdecor_frame_show_window_menu (*WAYLAND_libdecor_frame_show_window_menu) +#define libdecor_frame_get_wm_capabilities (*WAYLAND_libdecor_frame_get_wm_capabilities) +#define libdecor_frame_get_xdg_surface (*WAYLAND_libdecor_frame_get_xdg_surface) +#define libdecor_frame_get_xdg_toplevel (*WAYLAND_libdecor_frame_get_xdg_toplevel) +#define libdecor_frame_translate_coordinate (*WAYLAND_libdecor_frame_translate_coordinate) +#define libdecor_frame_map (*WAYLAND_libdecor_frame_map) +#define libdecor_state_new (*WAYLAND_libdecor_state_new) +#define libdecor_state_free (*WAYLAND_libdecor_state_free) +#define libdecor_configuration_get_content_size (*WAYLAND_libdecor_configuration_get_content_size) +#define libdecor_configuration_get_window_state (*WAYLAND_libdecor_configuration_get_window_state) +#define libdecor_dispatch (*WAYLAND_libdecor_dispatch) +#endif + +#else // SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC + +/* + * These must be included before libdecor.h, otherwise the libdecor header + * pulls in the system Wayland protocol headers instead of ours. + */ +#include "wayland-client-protocol.h" +#include "wayland-egl.h" + +#ifdef HAVE_LIBDECOR_H +#include +#endif + +#endif // SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC + +#endif // SDL_waylanddyn_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandevents.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandevents.c new file mode 100644 index 0000000..83c414f --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandevents.c @@ -0,0 +1,3408 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#include "../../core/unix/SDL_poll.h" +#include "../../events/SDL_events_c.h" +#include "../../events/SDL_scancode_tables_c.h" +#include "../../events/SDL_keysym_to_keycode_c.h" +#include "../../core/linux/SDL_system_theme.h" +#include "../SDL_sysvideo.h" + +#include "SDL_waylandvideo.h" +#include "SDL_waylandevents_c.h" +#include "SDL_waylandwindow.h" +#include "SDL_waylandmouse.h" + +#include "pointer-constraints-unstable-v1-client-protocol.h" +#include "relative-pointer-unstable-v1-client-protocol.h" +#include "xdg-shell-client-protocol.h" +#include "keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h" +#include "text-input-unstable-v3-client-protocol.h" +#include "tablet-v2-client-protocol.h" +#include "primary-selection-unstable-v1-client-protocol.h" +#include "input-timestamps-unstable-v1-client-protocol.h" + +#ifdef HAVE_LIBDECOR_H +#include +#endif + +#ifdef SDL_INPUT_LINUXEV +#include +#else +#define BTN_LEFT (0x110) +#define BTN_RIGHT (0x111) +#define BTN_MIDDLE (0x112) +#define BTN_SIDE (0x113) +#define BTN_EXTRA (0x114) +#endif +#include "../../events/SDL_keysym_to_scancode_c.h" +#include "../../events/imKStoUCS.h" +#include +#include +#include +#include +#include +#include "cursor-shape-v1-client-protocol.h" + +// Weston uses a ratio of 10 units per scroll tick +#define WAYLAND_WHEEL_AXIS_UNIT 10 + +#ifndef XKB_MOD_NAME_MOD3 +#define XKB_MOD_NAME_MOD3 "Mod3" +#endif + +#ifndef XKB_MOD_NAME_MOD5 +#define XKB_MOD_NAME_MOD5 "Mod5" +#endif + +// Keyboard and mouse names to match XWayland +#define WAYLAND_DEFAULT_KEYBOARD_NAME "Virtual core keyboard" +#define WAYLAND_DEFAULT_POINTER_NAME "Virtual core pointer" + +// Focus clickthrough timeout +#define WAYLAND_FOCUS_CLICK_TIMEOUT_NS SDL_MS_TO_NS(10) + +struct SDL_WaylandTouchPoint +{ + SDL_TouchID id; + wl_fixed_t fx; + wl_fixed_t fy; + struct wl_surface *surface; + + struct wl_list link; +}; + +static struct wl_list touch_points; + +static void touch_add(SDL_TouchID id, wl_fixed_t fx, wl_fixed_t fy, struct wl_surface *surface) +{ + struct SDL_WaylandTouchPoint *tp = SDL_malloc(sizeof(struct SDL_WaylandTouchPoint)); + + SDL_zerop(tp); + tp->id = id; + tp->fx = fx; + tp->fy = fy; + tp->surface = surface; + + WAYLAND_wl_list_insert(&touch_points, &tp->link); +} + +static void touch_update(SDL_TouchID id, wl_fixed_t fx, wl_fixed_t fy, struct wl_surface **surface) +{ + struct SDL_WaylandTouchPoint *tp; + + wl_list_for_each (tp, &touch_points, link) { + if (tp->id == id) { + tp->fx = fx; + tp->fy = fy; + if (surface) { + *surface = tp->surface; + } + break; + } + } +} + +static void touch_del(SDL_TouchID id, wl_fixed_t *fx, wl_fixed_t *fy, struct wl_surface **surface) +{ + struct SDL_WaylandTouchPoint *tp; + + wl_list_for_each (tp, &touch_points, link) { + if (tp->id == id) { + if (fx) { + *fx = tp->fx; + } + if (fy) { + *fy = tp->fy; + } + if (surface) { + *surface = tp->surface; + } + + WAYLAND_wl_list_remove(&tp->link); + SDL_free(tp); + break; + } + } +} + +static bool Wayland_SurfaceHasActiveTouches(struct wl_surface *surface) +{ + struct SDL_WaylandTouchPoint *tp; + + wl_list_for_each (tp, &touch_points, link) { + if (tp->surface == surface) { + return true; + } + } + + return false; +} + +static Uint64 Wayland_GetEventTimestamp(Uint64 nsTimestamp) +{ + static Uint64 last; + static Uint64 timestamp_offset; + const Uint64 now = SDL_GetTicksNS(); + + if (nsTimestamp < last) { + // 32-bit timer rollover, bump the offset + timestamp_offset += SDL_MS_TO_NS(0x100000000LLU); + } + last = nsTimestamp; + + if (!timestamp_offset) { + timestamp_offset = (now - nsTimestamp); + } + nsTimestamp += timestamp_offset; + + if (nsTimestamp > now) { + timestamp_offset -= (nsTimestamp - now); + nsTimestamp = now; + } + + return nsTimestamp; +} + +static void Wayland_input_timestamp_listener(void *data, struct zwp_input_timestamps_v1 *zwp_input_timestamps_v1, + uint32_t tv_sec_hi, uint32_t tv_sec_lo, uint32_t tv_nsec) +{ + *((Uint64 *)data) = ((((Uint64)tv_sec_hi << 32) | (Uint64)tv_sec_lo) * SDL_NS_PER_SECOND) + tv_nsec; +} + +static const struct zwp_input_timestamps_v1_listener timestamp_listener = { + Wayland_input_timestamp_listener +}; + +static Uint64 Wayland_GetKeyboardTimestamp(struct SDL_WaylandInput *input, Uint32 wl_timestamp_ms) +{ + if (wl_timestamp_ms) { + return Wayland_GetEventTimestamp(input->keyboard_timestamp_ns ? input->keyboard_timestamp_ns : SDL_MS_TO_NS(wl_timestamp_ms)); + } + + return 0; +} + +static Uint64 Wayland_GetKeyboardTimestampRaw(struct SDL_WaylandInput *input, Uint32 wl_timestamp_ms) +{ + if (wl_timestamp_ms) { + return input->keyboard_timestamp_ns ? input->keyboard_timestamp_ns : SDL_MS_TO_NS(wl_timestamp_ms); + } + + return 0; +} + +static Uint64 Wayland_GetPointerTimestamp(struct SDL_WaylandInput *input, Uint32 wl_timestamp_ms) +{ + if (wl_timestamp_ms) { + return Wayland_GetEventTimestamp(input->pointer_timestamp_ns ? input->pointer_timestamp_ns : SDL_MS_TO_NS(wl_timestamp_ms)); + } + + return 0; +} + +Uint64 Wayland_GetTouchTimestamp(struct SDL_WaylandInput *input, Uint32 wl_timestamp_ms) +{ + if (wl_timestamp_ms) { + return Wayland_GetEventTimestamp(input->touch_timestamp_ns ? input->touch_timestamp_ns : SDL_MS_TO_NS(wl_timestamp_ms)); + } + + return 0; +} + +void Wayland_RegisterTimestampListeners(struct SDL_WaylandInput *input) +{ + SDL_VideoData *viddata = input->display; + + if (viddata->input_timestamps_manager) { + if (input->keyboard && !input->keyboard_timestamps) { + input->keyboard_timestamps = zwp_input_timestamps_manager_v1_get_keyboard_timestamps(viddata->input_timestamps_manager, input->keyboard); + zwp_input_timestamps_v1_add_listener(input->keyboard_timestamps, ×tamp_listener, &input->keyboard_timestamp_ns); + } + + if (input->pointer && !input->pointer_timestamps) { + input->pointer_timestamps = zwp_input_timestamps_manager_v1_get_pointer_timestamps(viddata->input_timestamps_manager, input->pointer); + zwp_input_timestamps_v1_add_listener(input->pointer_timestamps, ×tamp_listener, &input->pointer_timestamp_ns); + } + + if (input->touch && !input->touch_timestamps) { + input->touch_timestamps = zwp_input_timestamps_manager_v1_get_touch_timestamps(viddata->input_timestamps_manager, input->touch); + zwp_input_timestamps_v1_add_listener(input->touch_timestamps, ×tamp_listener, &input->touch_timestamp_ns); + } + } +} + +void Wayland_CreateCursorShapeDevice(struct SDL_WaylandInput *input) +{ + SDL_VideoData *viddata = input->display; + + if (viddata->cursor_shape_manager) { + if (input->pointer && !input->cursor_shape) { + input->cursor_shape = wp_cursor_shape_manager_v1_get_pointer(viddata->cursor_shape_manager, input->pointer); + } + } +} + +// Returns true if a key repeat event was due +static bool keyboard_repeat_handle(SDL_WaylandKeyboardRepeat *repeat_info, Uint64 elapsed) +{ + bool ret = false; + while (elapsed >= repeat_info->next_repeat_ns) { + if (repeat_info->scancode != SDL_SCANCODE_UNKNOWN) { + const Uint64 timestamp = repeat_info->wl_press_time_ns + repeat_info->next_repeat_ns; + SDL_SendKeyboardKeyIgnoreModifiers(Wayland_GetEventTimestamp(timestamp), repeat_info->keyboard_id, repeat_info->key, repeat_info->scancode, true); + } + if (repeat_info->text[0]) { + SDL_SendKeyboardText(repeat_info->text); + } + repeat_info->next_repeat_ns += SDL_NS_PER_SECOND / (Uint64)repeat_info->repeat_rate; + ret = true; + } + return ret; +} + +static void keyboard_repeat_clear(SDL_WaylandKeyboardRepeat *repeat_info) +{ + if (!repeat_info->is_initialized) { + return; + } + repeat_info->is_key_down = false; +} + +static void keyboard_repeat_set(SDL_WaylandKeyboardRepeat *repeat_info, Uint32 keyboard_id, uint32_t key, Uint64 wl_press_time_ns, + uint32_t scancode, bool has_text, char text[8]) +{ + if (!repeat_info->is_initialized || !repeat_info->repeat_rate) { + return; + } + repeat_info->is_key_down = true; + repeat_info->keyboard_id = keyboard_id; + repeat_info->key = key; + repeat_info->wl_press_time_ns = wl_press_time_ns; + repeat_info->sdl_press_time_ns = SDL_GetTicksNS(); + repeat_info->next_repeat_ns = SDL_MS_TO_NS(repeat_info->repeat_delay_ms); + repeat_info->scancode = scancode; + if (has_text) { + SDL_copyp(repeat_info->text, text); + } else { + repeat_info->text[0] = '\0'; + } +} + +static uint32_t keyboard_repeat_get_key(SDL_WaylandKeyboardRepeat *repeat_info) +{ + if (repeat_info->is_initialized && repeat_info->is_key_down) { + return repeat_info->key; + } + + return 0; +} + +static void keyboard_repeat_set_text(SDL_WaylandKeyboardRepeat *repeat_info, const char text[8]) +{ + if (repeat_info->is_initialized) { + SDL_copyp(repeat_info->text, text); + } +} + +static bool keyboard_repeat_is_set(SDL_WaylandKeyboardRepeat *repeat_info) +{ + return repeat_info->is_initialized && repeat_info->is_key_down; +} + +static bool keyboard_repeat_key_is_set(SDL_WaylandKeyboardRepeat *repeat_info, uint32_t key) +{ + return repeat_info->is_initialized && repeat_info->is_key_down && key == repeat_info->key; +} + +static void sync_done_handler(void *data, struct wl_callback *callback, uint32_t callback_data) +{ + // Nothing to do, just destroy the callback + wl_callback_destroy(callback); +} + +static struct wl_callback_listener sync_listener = { + sync_done_handler +}; + +void Wayland_SendWakeupEvent(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_VideoData *d = _this->internal; + + /* Queue a sync event to unblock the event queue fd if it's empty and being waited on. + * TODO: Maybe use a pipe to avoid the compositor roundtrip? + */ + struct wl_callback *cb = wl_display_sync(d->display); + wl_callback_add_listener(cb, &sync_listener, NULL); + WAYLAND_wl_display_flush(d->display); +} + +static int dispatch_queued_events(SDL_VideoData *viddata) +{ + int rc; + + /* + * NOTE: When reconnection is implemented, check if libdecor needs to be + * involved in the reconnection process. + */ +#ifdef HAVE_LIBDECOR_H + if (viddata->shell.libdecor) { + libdecor_dispatch(viddata->shell.libdecor, 0); + } +#endif + + rc = WAYLAND_wl_display_dispatch_pending(viddata->display); + return rc >= 0 ? 1 : rc; +} + +int Wayland_WaitEventTimeout(SDL_VideoDevice *_this, Sint64 timeoutNS) +{ + SDL_VideoData *d = _this->internal; + struct SDL_WaylandInput *input = d->input; + bool key_repeat_active = false; + + WAYLAND_wl_display_flush(d->display); + +#ifdef SDL_USE_IME + SDL_Window *keyboard_focus = SDL_GetKeyboardFocus(); + if (!d->text_input_manager && keyboard_focus && SDL_TextInputActive(keyboard_focus)) { + SDL_IME_PumpEvents(); + } +#endif + +#ifdef SDL_USE_LIBDBUS + SDL_DBus_PumpEvents(); +#endif + + // If key repeat is active, we'll need to cap our maximum wait time to handle repeats + if (input && keyboard_repeat_is_set(&input->keyboard_repeat)) { + const Uint64 elapsed = SDL_GetTicksNS() - input->keyboard_repeat.sdl_press_time_ns; + if (keyboard_repeat_handle(&input->keyboard_repeat, elapsed)) { + // A repeat key event was already due + return 1; + } else { + const Uint64 next_repeat_wait_time = (input->keyboard_repeat.next_repeat_ns - elapsed) + 1; + if (timeoutNS >= 0) { + timeoutNS = SDL_min(timeoutNS, next_repeat_wait_time); + } else { + timeoutNS = next_repeat_wait_time; + } + key_repeat_active = true; + } + } + + /* wl_display_prepare_read() will return -1 if the default queue is not empty. + * If the default queue is empty, it will prepare us for our SDL_IOReady() call. */ + if (WAYLAND_wl_display_prepare_read(d->display) == 0) { + // Use SDL_IOR_NO_RETRY to ensure SIGINT will break us out of our wait + int err = SDL_IOReady(WAYLAND_wl_display_get_fd(d->display), SDL_IOR_READ | SDL_IOR_NO_RETRY, timeoutNS); + if (err > 0) { + // There are new events available to read + WAYLAND_wl_display_read_events(d->display); + return dispatch_queued_events(d); + } else if (err == 0) { + // No events available within the timeout + WAYLAND_wl_display_cancel_read(d->display); + + // If key repeat is active, we might have woken up to generate a key event + if (key_repeat_active) { + const Uint64 elapsed = SDL_GetTicksNS() - input->keyboard_repeat.sdl_press_time_ns; + if (keyboard_repeat_handle(&input->keyboard_repeat, elapsed)) { + return 1; + } + } + + return 0; + } else { + // Error returned from poll()/select() + WAYLAND_wl_display_cancel_read(d->display); + + if (errno == EINTR) { + /* If the wait was interrupted by a signal, we may have generated a + * SDL_EVENT_QUIT event. Let the caller know to call SDL_PumpEvents(). */ + return 1; + } else { + return err; + } + } + } else { + // We already had pending events + return dispatch_queued_events(d); + } +} + +void Wayland_PumpEvents(SDL_VideoDevice *_this) +{ + SDL_VideoData *d = _this->internal; + struct SDL_WaylandInput *input = d->input; + int err; + +#ifdef SDL_USE_IME + SDL_Window *keyboard_focus = SDL_GetKeyboardFocus(); + if (!d->text_input_manager && keyboard_focus && SDL_TextInputActive(keyboard_focus)) { + SDL_IME_PumpEvents(); + } +#endif + +#ifdef SDL_USE_LIBDBUS + SDL_DBus_PumpEvents(); +#endif + +#ifdef HAVE_LIBDECOR_H + if (d->shell.libdecor) { + libdecor_dispatch(d->shell.libdecor, 0); + } +#endif + + WAYLAND_wl_display_flush(d->display); + + /* wl_display_prepare_read() will return -1 if the default queue is not empty. + * If the default queue is empty, it will prepare us for our SDL_IOReady() call. */ + if (WAYLAND_wl_display_prepare_read(d->display) == 0) { + if (SDL_IOReady(WAYLAND_wl_display_get_fd(d->display), SDL_IOR_READ, 0) > 0) { + WAYLAND_wl_display_read_events(d->display); + } else { + WAYLAND_wl_display_cancel_read(d->display); + } + } + + // Dispatch any pre-existing pending events or new events we may have read + err = WAYLAND_wl_display_dispatch_pending(d->display); + + if (input && keyboard_repeat_is_set(&input->keyboard_repeat)) { + const Uint64 elapsed = SDL_GetTicksNS() - input->keyboard_repeat.sdl_press_time_ns; + keyboard_repeat_handle(&input->keyboard_repeat, elapsed); + } + + if (err < 0 && !d->display_disconnected) { + /* Something has failed with the Wayland connection -- for example, + * the compositor may have shut down and closed its end of the socket, + * or there is a library-specific error. + * + * Try to recover once, then quit. + */ + if (!Wayland_VideoReconnect(_this)) { + d->display_disconnected = 1; + SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Wayland display connection closed by server (fatal)"); + + /* Only send a single quit message, as application shutdown might call + * SDL_PumpEvents + */ + SDL_SendQuit(); + } + } +} + +static void pointer_handle_motion(void *data, struct wl_pointer *pointer, + uint32_t time, wl_fixed_t sx_w, wl_fixed_t sy_w) +{ + struct SDL_WaylandInput *input = data; + SDL_WindowData *window_data = input->pointer_focus; + SDL_Window *window = window_data ? window_data->sdlwindow : NULL; + + input->sx_w = sx_w; + input->sy_w = sy_w; + if (input->pointer_focus) { + const float sx = (float)(wl_fixed_to_double(sx_w) * window_data->pointer_scale.x); + const float sy = (float)(wl_fixed_to_double(sy_w) * window_data->pointer_scale.y); + SDL_SendMouseMotion(Wayland_GetPointerTimestamp(input, time), window_data->sdlwindow, input->pointer_id, false, sx, sy); + } + + if (window && window->hit_test) { + const SDL_Point point = { (int)SDL_floor(wl_fixed_to_double(sx_w) * window_data->pointer_scale.x), + (int)SDL_floor(wl_fixed_to_double(sy_w) * window_data->pointer_scale.y) }; + SDL_HitTestResult rc = window->hit_test(window, &point, window->hit_test_data); + if (rc == window_data->hit_test_result) { + return; + } + + Wayland_SetHitTestCursor(rc); + window_data->hit_test_result = rc; + } +} + +static void pointer_handle_enter(void *data, struct wl_pointer *pointer, + uint32_t serial, struct wl_surface *surface, + wl_fixed_t sx_w, wl_fixed_t sy_w) +{ + struct SDL_WaylandInput *input = data; + SDL_WindowData *window; + + if (!surface) { + // enter event for a window we've just destroyed + return; + } + + /* This handler will be called twice in Wayland 1.4 + * Once for the window surface which has valid user data + * and again for the mouse cursor surface which does not have valid user data + * We ignore the later + */ + window = Wayland_GetWindowDataForOwnedSurface(surface); + + if (window) { + input->pointer_focus = window; + input->pointer_enter_serial = serial; + SDL_SetMouseFocus(window->sdlwindow); + /* In the case of e.g. a pointer confine warp, we may receive an enter + * event with no following motion event, but with the new coordinates + * as part of the enter event. + * + * FIXME: This causes a movement event with an anomalous timestamp when + * the cursor enters the window. + */ + pointer_handle_motion(data, pointer, 0, sx_w, sy_w); + /* If the cursor was changed while our window didn't have pointer + * focus, we might need to trigger another call to + * wl_pointer_set_cursor() for the new cursor to be displayed. */ + Wayland_SetHitTestCursor(window->hit_test_result); + } +} + +static void pointer_handle_leave(void *data, struct wl_pointer *pointer, + uint32_t serial, struct wl_surface *surface) +{ + struct SDL_WaylandInput *input = data; + + if (!surface) { + return; + } + + if (input->pointer_focus) { + SDL_WindowData *wind = Wayland_GetWindowDataForOwnedSurface(surface); + + if (wind) { + // Clear the capture flag and raise all buttons + wind->sdlwindow->flags &= ~SDL_WINDOW_MOUSE_CAPTURE; + + input->buttons_pressed = 0; + SDL_SendMouseButton(Wayland_GetPointerTimestamp(input, 0), wind->sdlwindow, input->pointer_id, SDL_BUTTON_LEFT, false); + SDL_SendMouseButton(Wayland_GetPointerTimestamp(input, 0), wind->sdlwindow, input->pointer_id, SDL_BUTTON_RIGHT, false); + SDL_SendMouseButton(Wayland_GetPointerTimestamp(input, 0), wind->sdlwindow, input->pointer_id, SDL_BUTTON_MIDDLE, false); + SDL_SendMouseButton(Wayland_GetPointerTimestamp(input, 0), wind->sdlwindow, input->pointer_id, SDL_BUTTON_X1, false); + SDL_SendMouseButton(Wayland_GetPointerTimestamp(input, 0), wind->sdlwindow, input->pointer_id, SDL_BUTTON_X2, false); + } + + /* A pointer leave event may be emitted if the compositor hides the pointer in response to receiving a touch event. + * Don't relinquish focus if the surface has active touches, as the compositor is just transitioning from mouse to touch mode. + */ + if (!Wayland_SurfaceHasActiveTouches(surface)) { + SDL_SetMouseFocus(NULL); + } + input->pointer_focus = NULL; + } +} + +static bool ProcessHitTest(SDL_WindowData *window_data, + struct wl_seat *seat, + wl_fixed_t sx_w, wl_fixed_t sy_w, + uint32_t serial) +{ + SDL_Window *window = window_data->sdlwindow; + + if (window->hit_test) { + static const uint32_t directions[] = { + XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT, XDG_TOPLEVEL_RESIZE_EDGE_TOP, + XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT, XDG_TOPLEVEL_RESIZE_EDGE_RIGHT, + XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT, XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM, + XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT, XDG_TOPLEVEL_RESIZE_EDGE_LEFT + }; + +#ifdef HAVE_LIBDECOR_H + static const uint32_t directions_libdecor[] = { + LIBDECOR_RESIZE_EDGE_TOP_LEFT, LIBDECOR_RESIZE_EDGE_TOP, + LIBDECOR_RESIZE_EDGE_TOP_RIGHT, LIBDECOR_RESIZE_EDGE_RIGHT, + LIBDECOR_RESIZE_EDGE_BOTTOM_RIGHT, LIBDECOR_RESIZE_EDGE_BOTTOM, + LIBDECOR_RESIZE_EDGE_BOTTOM_LEFT, LIBDECOR_RESIZE_EDGE_LEFT + }; +#endif + + switch (window_data->hit_test_result) { + case SDL_HITTEST_DRAGGABLE: +#ifdef HAVE_LIBDECOR_H + if (window_data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (window_data->shell_surface.libdecor.frame) { + libdecor_frame_move(window_data->shell_surface.libdecor.frame, + seat, + serial); + } + } else +#endif + if (window_data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + if (window_data->shell_surface.xdg.toplevel.xdg_toplevel) { + xdg_toplevel_move(window_data->shell_surface.xdg.toplevel.xdg_toplevel, + seat, + serial); + } + } + return true; + + case SDL_HITTEST_RESIZE_TOPLEFT: + case SDL_HITTEST_RESIZE_TOP: + case SDL_HITTEST_RESIZE_TOPRIGHT: + case SDL_HITTEST_RESIZE_RIGHT: + case SDL_HITTEST_RESIZE_BOTTOMRIGHT: + case SDL_HITTEST_RESIZE_BOTTOM: + case SDL_HITTEST_RESIZE_BOTTOMLEFT: + case SDL_HITTEST_RESIZE_LEFT: +#ifdef HAVE_LIBDECOR_H + if (window_data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (window_data->shell_surface.libdecor.frame) { + libdecor_frame_resize(window_data->shell_surface.libdecor.frame, + seat, + serial, + directions_libdecor[window_data->hit_test_result - SDL_HITTEST_RESIZE_TOPLEFT]); + } + } else +#endif + if (window_data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + if (window_data->shell_surface.xdg.toplevel.xdg_toplevel) { + xdg_toplevel_resize(window_data->shell_surface.xdg.toplevel.xdg_toplevel, + seat, + serial, + directions[window_data->hit_test_result - SDL_HITTEST_RESIZE_TOPLEFT]); + } + } + return true; + + default: + return false; + } + } + + return false; +} + +static void pointer_handle_button_common(struct SDL_WaylandInput *input, uint32_t serial, + uint32_t time, uint32_t button, uint32_t state_w) +{ + SDL_WindowData *window = input->pointer_focus; + enum wl_pointer_button_state state = state_w; + Uint64 timestamp = Wayland_GetPointerTimestamp(input, time); + Uint8 sdl_button; + const bool down = (state != 0); + + switch (button) { + case BTN_LEFT: + sdl_button = SDL_BUTTON_LEFT; + break; + case BTN_MIDDLE: + sdl_button = SDL_BUTTON_MIDDLE; + break; + case BTN_RIGHT: + sdl_button = SDL_BUTTON_RIGHT; + break; + case BTN_SIDE: + sdl_button = SDL_BUTTON_X1; + break; + case BTN_EXTRA: + sdl_button = SDL_BUTTON_X2; + break; + default: + return; + } + + if (window) { + SDL_VideoData *viddata = window->waylandData; + bool ignore_click = false; + + if (state) { + Wayland_UpdateImplicitGrabSerial(input, serial); + input->buttons_pressed |= SDL_BUTTON_MASK(sdl_button); + } else { + input->buttons_pressed &= ~(SDL_BUTTON_MASK(sdl_button)); + } + + if (sdl_button == SDL_BUTTON_LEFT && + ProcessHitTest(input->pointer_focus, input->seat, input->sx_w, input->sy_w, serial)) { + return; // don't pass this event on to app. + } + + // Possibly ignore this click if it was to gain focus. + if (window->last_focus_event_time_ns) { + if (state == WL_POINTER_BUTTON_STATE_PRESSED && + (SDL_GetTicksNS() - window->last_focus_event_time_ns) < WAYLAND_FOCUS_CLICK_TIMEOUT_NS) { + ignore_click = !SDL_GetHintBoolean(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, false); + } + + window->last_focus_event_time_ns = 0; + } + + /* Wayland won't let you "capture" the mouse, but it will automatically track + * the mouse outside the window if you drag outside of it, until you let go + * of all buttons (even if you add or remove presses outside the window, as + * long as any button is still down, the capture remains). + * + * The mouse is not captured in relative mode. + */ + if (!viddata->relative_mouse_mode) { + if (input->buttons_pressed != 0) { + window->sdlwindow->flags |= SDL_WINDOW_MOUSE_CAPTURE; + } else { + window->sdlwindow->flags &= ~SDL_WINDOW_MOUSE_CAPTURE; + } + } + + if (!ignore_click) { + SDL_SendMouseButton(timestamp, window->sdlwindow, input->pointer_id, sdl_button, down); + } + } +} + +static void pointer_handle_button(void *data, struct wl_pointer *pointer, uint32_t serial, + uint32_t time, uint32_t button, uint32_t state_w) +{ + struct SDL_WaylandInput *input = data; + + pointer_handle_button_common(input, serial, time, button, state_w); +} + +static void pointer_handle_axis_common_v1(struct SDL_WaylandInput *input, + uint32_t time, uint32_t axis, wl_fixed_t value) +{ + SDL_WindowData *window = input->pointer_focus; + const Uint64 timestamp = Wayland_GetPointerTimestamp(input, time); + const enum wl_pointer_axis a = axis; + + if (input->pointer_focus) { + float x, y; + + switch (a) { + case WL_POINTER_AXIS_VERTICAL_SCROLL: + x = 0; + y = 0 - (float)wl_fixed_to_double(value); + break; + case WL_POINTER_AXIS_HORIZONTAL_SCROLL: + x = (float)wl_fixed_to_double(value); + y = 0; + break; + default: + return; + } + + x /= WAYLAND_WHEEL_AXIS_UNIT; + y /= WAYLAND_WHEEL_AXIS_UNIT; + + SDL_SendMouseWheel(timestamp, window->sdlwindow, input->pointer_id, x, y, SDL_MOUSEWHEEL_NORMAL); + } +} + +static void pointer_handle_axis_common(struct SDL_WaylandInput *input, enum SDL_WaylandAxisEvent type, + uint32_t axis, wl_fixed_t value) +{ + const enum wl_pointer_axis a = axis; + + if (input->pointer_focus) { + switch (a) { + case WL_POINTER_AXIS_VERTICAL_SCROLL: + switch (type) { + case AXIS_EVENT_VALUE120: + /* + * High resolution scroll event. The spec doesn't state that axis_value120 + * events are limited to one per frame, so the values are accumulated. + */ + if (input->pointer_curr_axis_info.y_axis_type != AXIS_EVENT_VALUE120) { + input->pointer_curr_axis_info.y_axis_type = AXIS_EVENT_VALUE120; + input->pointer_curr_axis_info.y = 0.0f; + } + input->pointer_curr_axis_info.y += 0 - (float)wl_fixed_to_double(value); + break; + case AXIS_EVENT_DISCRETE: + /* + * This is a discrete axis event, so we process it and set the + * flag to ignore future continuous axis events in this frame. + */ + if (input->pointer_curr_axis_info.y_axis_type != AXIS_EVENT_DISCRETE) { + input->pointer_curr_axis_info.y_axis_type = AXIS_EVENT_DISCRETE; + input->pointer_curr_axis_info.y = 0 - (float)wl_fixed_to_double(value); + } + break; + case AXIS_EVENT_CONTINUOUS: + // Only process continuous events if no discrete events have been received. + if (input->pointer_curr_axis_info.y_axis_type == AXIS_EVENT_CONTINUOUS) { + input->pointer_curr_axis_info.y = 0 - (float)wl_fixed_to_double(value); + } + break; + } + break; + case WL_POINTER_AXIS_HORIZONTAL_SCROLL: + switch (type) { + case AXIS_EVENT_VALUE120: + /* + * High resolution scroll event. The spec doesn't state that axis_value120 + * events are limited to one per frame, so the values are accumulated. + */ + if (input->pointer_curr_axis_info.x_axis_type != AXIS_EVENT_VALUE120) { + input->pointer_curr_axis_info.x_axis_type = AXIS_EVENT_VALUE120; + input->pointer_curr_axis_info.x = 0.0f; + } + input->pointer_curr_axis_info.x += (float)wl_fixed_to_double(value); + break; + case AXIS_EVENT_DISCRETE: + /* + * This is a discrete axis event, so we process it and set the + * flag to ignore future continuous axis events in this frame. + */ + if (input->pointer_curr_axis_info.x_axis_type != AXIS_EVENT_DISCRETE) { + input->pointer_curr_axis_info.x_axis_type = AXIS_EVENT_DISCRETE; + input->pointer_curr_axis_info.x = (float)wl_fixed_to_double(value); + } + break; + case AXIS_EVENT_CONTINUOUS: + // Only process continuous events if no discrete events have been received. + if (input->pointer_curr_axis_info.x_axis_type == AXIS_EVENT_CONTINUOUS) { + input->pointer_curr_axis_info.x = (float)wl_fixed_to_double(value); + } + break; + } + break; + } + } +} + +static void pointer_handle_axis(void *data, struct wl_pointer *pointer, + uint32_t time, uint32_t axis, wl_fixed_t value) +{ + struct SDL_WaylandInput *input = data; + + if (wl_seat_get_version(input->seat) >= WL_POINTER_FRAME_SINCE_VERSION) { + input->pointer_curr_axis_info.timestamp_ns = Wayland_GetPointerTimestamp(input, time); + pointer_handle_axis_common(input, AXIS_EVENT_CONTINUOUS, axis, value); + } else { + pointer_handle_axis_common_v1(input, time, axis, value); + } +} + +static void pointer_handle_axis_relative_direction(void *data, struct wl_pointer *pointer, + uint32_t axis, uint32_t axis_relative_direction) +{ + struct SDL_WaylandInput *input = data; + if (axis != WL_POINTER_AXIS_VERTICAL_SCROLL) { + return; + } + switch (axis_relative_direction) { + case WL_POINTER_AXIS_RELATIVE_DIRECTION_IDENTICAL: + input->pointer_curr_axis_info.direction = SDL_MOUSEWHEEL_NORMAL; + break; + case WL_POINTER_AXIS_RELATIVE_DIRECTION_INVERTED: + input->pointer_curr_axis_info.direction = SDL_MOUSEWHEEL_FLIPPED; + break; + } +} + +static void pointer_handle_frame(void *data, struct wl_pointer *pointer) +{ + struct SDL_WaylandInput *input = data; + SDL_WindowData *window = input->pointer_focus; + float x, y; + SDL_MouseWheelDirection direction = input->pointer_curr_axis_info.direction; + + switch (input->pointer_curr_axis_info.x_axis_type) { + case AXIS_EVENT_CONTINUOUS: + x = input->pointer_curr_axis_info.x / WAYLAND_WHEEL_AXIS_UNIT; + break; + case AXIS_EVENT_DISCRETE: + x = input->pointer_curr_axis_info.x; + break; + case AXIS_EVENT_VALUE120: + x = input->pointer_curr_axis_info.x / 120.0f; + break; + default: + x = 0.0f; + break; + } + + switch (input->pointer_curr_axis_info.y_axis_type) { + case AXIS_EVENT_CONTINUOUS: + y = input->pointer_curr_axis_info.y / WAYLAND_WHEEL_AXIS_UNIT; + break; + case AXIS_EVENT_DISCRETE: + y = input->pointer_curr_axis_info.y; + break; + case AXIS_EVENT_VALUE120: + y = input->pointer_curr_axis_info.y / 120.0f; + break; + default: + y = 0.0f; + break; + } + + // clear pointer_curr_axis_info for next frame + SDL_memset(&input->pointer_curr_axis_info, 0, sizeof(input->pointer_curr_axis_info)); + + if (x != 0.0f || y != 0.0f) { + SDL_SendMouseWheel(input->pointer_curr_axis_info.timestamp_ns, + window->sdlwindow, input->pointer_id, x, y, direction); + } +} + +static void pointer_handle_axis_source(void *data, struct wl_pointer *pointer, + uint32_t axis_source) +{ + // unimplemented +} + +static void pointer_handle_axis_stop(void *data, struct wl_pointer *pointer, + uint32_t time, uint32_t axis) +{ + // unimplemented +} + +static void pointer_handle_axis_discrete(void *data, struct wl_pointer *pointer, + uint32_t axis, int32_t discrete) +{ + struct SDL_WaylandInput *input = data; + + pointer_handle_axis_common(input, AXIS_EVENT_DISCRETE, axis, wl_fixed_from_int(discrete)); +} + +static void pointer_handle_axis_value120(void *data, struct wl_pointer *pointer, + uint32_t axis, int32_t value120) +{ + struct SDL_WaylandInput *input = data; + + pointer_handle_axis_common(input, AXIS_EVENT_VALUE120, axis, wl_fixed_from_int(value120)); +} + +static const struct wl_pointer_listener pointer_listener = { + pointer_handle_enter, + pointer_handle_leave, + pointer_handle_motion, + pointer_handle_button, + pointer_handle_axis, + pointer_handle_frame, // Version 5 + pointer_handle_axis_source, // Version 5 + pointer_handle_axis_stop, // Version 5 + pointer_handle_axis_discrete, // Version 5 + pointer_handle_axis_value120, // Version 8 + pointer_handle_axis_relative_direction // Version 9 +}; + +static void relative_pointer_handle_relative_motion(void *data, + struct zwp_relative_pointer_v1 *pointer, + uint32_t time_hi, + uint32_t time_lo, + wl_fixed_t dx_w, + wl_fixed_t dy_w, + wl_fixed_t dx_unaccel_w, + wl_fixed_t dy_unaccel_w) +{ + struct SDL_WaylandInput *input = data; + SDL_VideoData *d = input->display; + SDL_WindowData *window = input->pointer_focus; + + // Relative pointer event times are in microsecond granularity. + const Uint64 timestamp = Wayland_GetEventTimestamp(SDL_US_TO_NS(((Uint64)time_hi << 32) | (Uint64)time_lo)); + + if (input->pointer_focus && d->relative_mouse_mode) { + double dx; + double dy; + if (!SDL_GetMouse()->enable_relative_system_scale) { + dx = wl_fixed_to_double(dx_unaccel_w); + dy = wl_fixed_to_double(dy_unaccel_w); + } else { + dx = wl_fixed_to_double(dx_w); + dy = wl_fixed_to_double(dy_w); + } + + SDL_SendMouseMotion(timestamp, window->sdlwindow, input->pointer_id, true, (float)dx, (float)dy); + } +} + +static const struct zwp_relative_pointer_v1_listener relative_pointer_listener = { + relative_pointer_handle_relative_motion, +}; + +static void locked_pointer_locked(void *data, + struct zwp_locked_pointer_v1 *locked_pointer) +{ +} + +static void locked_pointer_unlocked(void *data, + struct zwp_locked_pointer_v1 *locked_pointer) +{ +} + +static const struct zwp_locked_pointer_v1_listener locked_pointer_listener = { + locked_pointer_locked, + locked_pointer_unlocked, +}; + +bool Wayland_input_lock_pointer(struct SDL_WaylandInput *input, SDL_Window *window) +{ + SDL_WindowData *w = window->internal; + SDL_VideoData *d = input->display; + + if (!d->pointer_constraints || !input->pointer) { + return false; + } + + if (!w->locked_pointer) { + if (w->confined_pointer) { + // If the pointer is already confined to the surface, the lock will fail with a protocol error. + Wayland_input_unconfine_pointer(input, window); + } + + w->locked_pointer = zwp_pointer_constraints_v1_lock_pointer(d->pointer_constraints, + w->surface, + input->pointer, + NULL, + ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT); + zwp_locked_pointer_v1_add_listener(w->locked_pointer, + &locked_pointer_listener, + window); + } + + return true; +} + +bool Wayland_input_unlock_pointer(struct SDL_WaylandInput *input, SDL_Window *window) +{ + SDL_WindowData *w = window->internal; + + if (w->locked_pointer) { + zwp_locked_pointer_v1_destroy(w->locked_pointer); + w->locked_pointer = NULL; + } + + // Restore existing pointer confinement. + Wayland_input_confine_pointer(input, window); + + return true; +} + +static void pointer_confine_destroy(SDL_Window *window) +{ + SDL_WindowData *w = window->internal; + if (w->confined_pointer) { + zwp_confined_pointer_v1_destroy(w->confined_pointer); + w->confined_pointer = NULL; + } +} + +static void confined_pointer_confined(void *data, + struct zwp_confined_pointer_v1 *confined_pointer) +{ +} + +static void confined_pointer_unconfined(void *data, + struct zwp_confined_pointer_v1 *confined_pointer) +{ +} + +static const struct zwp_confined_pointer_v1_listener confined_pointer_listener = { + confined_pointer_confined, + confined_pointer_unconfined, +}; + +static void touch_handler_down(void *data, struct wl_touch *touch, uint32_t serial, + uint32_t timestamp, struct wl_surface *surface, + int id, wl_fixed_t fx, wl_fixed_t fy) +{ + struct SDL_WaylandInput *input = (struct SDL_WaylandInput *)data; + SDL_WindowData *window_data; + + // Check that this surface is valid. + if (!surface) { + return; + } + + touch_add(id, fx, fy, surface); + Wayland_UpdateImplicitGrabSerial(input, serial); + window_data = Wayland_GetWindowDataForOwnedSurface(surface); + + if (window_data) { + float x, y; + + if (window_data->current.logical_width <= 1) { + x = 0.5f; + } else { + x = (float)wl_fixed_to_double(fx) / (window_data->current.logical_width - 1); + } + if (window_data->current.logical_height <= 1) { + y = 0.5f; + } else { + y = (float)wl_fixed_to_double(fy) / (window_data->current.logical_height - 1); + } + + SDL_SetMouseFocus(window_data->sdlwindow); + + SDL_SendTouch(Wayland_GetTouchTimestamp(input, timestamp), (SDL_TouchID)(uintptr_t)touch, + (SDL_FingerID)(id + 1), window_data->sdlwindow, SDL_EVENT_FINGER_DOWN, x, y, 1.0f); + } +} + +static void touch_handler_up(void *data, struct wl_touch *touch, uint32_t serial, + uint32_t timestamp, int id) +{ + struct SDL_WaylandInput *input = (struct SDL_WaylandInput *)data; + wl_fixed_t fx = 0, fy = 0; + struct wl_surface *surface = NULL; + + touch_del(id, &fx, &fy, &surface); + + if (surface) { + SDL_WindowData *window_data = (SDL_WindowData *)wl_surface_get_user_data(surface); + + if (window_data) { + const float x = (float)wl_fixed_to_double(fx) / window_data->current.logical_width; + const float y = (float)wl_fixed_to_double(fy) / window_data->current.logical_height; + + SDL_SendTouch(Wayland_GetTouchTimestamp(input, timestamp), (SDL_TouchID)(uintptr_t)touch, + (SDL_FingerID)(id + 1), window_data->sdlwindow, SDL_EVENT_FINGER_UP, x, y, 0.0f); + + /* If the seat lacks pointer focus, the seat's keyboard focus is another window or NULL, this window currently + * has mouse focus, and the surface has no active touch events, consider mouse focus to be lost. + */ + if (!input->pointer_focus && input->keyboard_focus != window_data && + SDL_GetMouseFocus() == window_data->sdlwindow && !Wayland_SurfaceHasActiveTouches(surface)) { + SDL_SetMouseFocus(NULL); + } + } + } +} + +static void touch_handler_motion(void *data, struct wl_touch *touch, uint32_t timestamp, + int id, wl_fixed_t fx, wl_fixed_t fy) +{ + struct SDL_WaylandInput *input = (struct SDL_WaylandInput *)data; + struct wl_surface *surface = NULL; + + touch_update(id, fx, fy, &surface); + + if (surface) { + SDL_WindowData *window_data = (SDL_WindowData *)wl_surface_get_user_data(surface); + + if (window_data) { + const float x = (float)wl_fixed_to_double(fx) / window_data->current.logical_width; + const float y = (float)wl_fixed_to_double(fy) / window_data->current.logical_height; + + SDL_SendTouchMotion(Wayland_GetPointerTimestamp(input, timestamp), (SDL_TouchID)(uintptr_t)touch, + (SDL_FingerID)(id + 1), window_data->sdlwindow, x, y, 1.0f); + } + } +} + +static void touch_handler_frame(void *data, struct wl_touch *touch) +{ +} + +static void touch_handler_cancel(void *data, struct wl_touch *touch) +{ + struct SDL_WaylandInput *input = (struct SDL_WaylandInput *)data; + struct SDL_WaylandTouchPoint *tp, *temp; + + wl_list_for_each_safe (tp, temp, &touch_points, link) { + bool removed = false; + + if (tp->surface) { + SDL_WindowData *window_data = (SDL_WindowData *)wl_surface_get_user_data(tp->surface); + + if (window_data) { + const float x = (float)(wl_fixed_to_double(tp->fx) / window_data->current.logical_width); + const float y = (float)(wl_fixed_to_double(tp->fy) / window_data->current.logical_height); + + SDL_SendTouch(0, (SDL_TouchID)(uintptr_t)touch, + (SDL_FingerID)(tp->id + 1), window_data->sdlwindow, SDL_EVENT_FINGER_CANCELED, x, y, 0.0f); + + // Remove the touch from the list before checking for still-active touches on the surface. + WAYLAND_wl_list_remove(&tp->link); + removed = true; + + /* If the seat lacks pointer focus, the seat's keyboard focus is another window or NULL, this window currently + * has mouse focus, and the surface has no active touch events, consider mouse focus to be lost. + */ + if (!input->pointer_focus && input->keyboard_focus != window_data && + SDL_GetMouseFocus() == window_data->sdlwindow && !Wayland_SurfaceHasActiveTouches(tp->surface)) { + SDL_SetMouseFocus(NULL); + } + } + } + + if (!removed) { + WAYLAND_wl_list_remove(&tp->link); + } + SDL_free(tp); + } +} + +static const struct wl_touch_listener touch_listener = { + touch_handler_down, + touch_handler_up, + touch_handler_motion, + touch_handler_frame, + touch_handler_cancel, + NULL, // shape + NULL, // orientation +}; + +typedef struct Wayland_Keymap +{ + SDL_Keymap *keymap; + struct xkb_state *state; + SDL_Keymod modstate; +} Wayland_Keymap; + +static void Wayland_keymap_iter(struct xkb_keymap *keymap, xkb_keycode_t key, void *data) +{ + Wayland_Keymap *sdlKeymap = (Wayland_Keymap *)data; + const xkb_keysym_t *syms; + const SDL_Scancode scancode = SDL_GetScancodeFromTable(SDL_SCANCODE_TABLE_XFREE86_2, (key - 8)); + if (scancode == SDL_SCANCODE_UNKNOWN) { + return; + } + + if (WAYLAND_xkb_state_key_get_syms(sdlKeymap->state, key, &syms) > 0) { + SDL_Keycode keycode = SDL_GetKeyCodeFromKeySym(syms[0], key, sdlKeymap->modstate); + + if (!keycode) { + switch (scancode) { + case SDL_SCANCODE_RETURN: + keycode = SDLK_RETURN; + break; + case SDL_SCANCODE_ESCAPE: + keycode = SDLK_ESCAPE; + break; + case SDL_SCANCODE_BACKSPACE: + keycode = SDLK_BACKSPACE; + break; + case SDL_SCANCODE_DELETE: + keycode = SDLK_DELETE; + break; + default: + keycode = SDL_SCANCODE_TO_KEYCODE(scancode); + break; + } + } + + SDL_SetKeymapEntry(sdlKeymap->keymap, scancode, sdlKeymap->modstate, keycode); + } +} + +static void Wayland_UpdateKeymap(struct SDL_WaylandInput *input) +{ + struct Keymod_masks + { + SDL_Keymod sdl_mask; + xkb_mod_mask_t xkb_mask; + } const keymod_masks[] = { + { SDL_KMOD_NONE, 0 }, + { SDL_KMOD_SHIFT, input->xkb.idx_shift }, + { SDL_KMOD_CAPS, input->xkb.idx_caps }, + { SDL_KMOD_SHIFT | SDL_KMOD_CAPS, input->xkb.idx_shift | input->xkb.idx_caps }, + { SDL_KMOD_MODE, input->xkb.idx_mod5 }, + { SDL_KMOD_MODE | SDL_KMOD_SHIFT, input->xkb.idx_mod5 | input->xkb.idx_shift }, + { SDL_KMOD_MODE | SDL_KMOD_CAPS, input->xkb.idx_mod5 | input->xkb.idx_caps }, + { SDL_KMOD_MODE | SDL_KMOD_SHIFT | SDL_KMOD_CAPS, input->xkb.idx_mod5 | input->xkb.idx_shift | input->xkb.idx_caps }, + { SDL_KMOD_LEVEL5, input->xkb.idx_mod3 }, + { SDL_KMOD_LEVEL5 | SDL_KMOD_SHIFT, input->xkb.idx_mod3 | input->xkb.idx_shift }, + { SDL_KMOD_LEVEL5 | SDL_KMOD_CAPS, input->xkb.idx_mod3 | input->xkb.idx_caps }, + { SDL_KMOD_LEVEL5 | SDL_KMOD_SHIFT | SDL_KMOD_CAPS, input->xkb.idx_mod3 | input->xkb.idx_shift | input->xkb.idx_caps }, + { SDL_KMOD_LEVEL5 | SDL_KMOD_MODE, input->xkb.idx_mod3 | input->xkb.idx_mod5 }, + { SDL_KMOD_LEVEL5 | SDL_KMOD_MODE | SDL_KMOD_SHIFT, input->xkb.idx_mod3 | input->xkb.idx_mod5 | input->xkb.idx_shift }, + { SDL_KMOD_LEVEL5 | SDL_KMOD_MODE | SDL_KMOD_CAPS, input->xkb.idx_mod3 | input->xkb.idx_mod5 | input->xkb.idx_caps }, + { SDL_KMOD_LEVEL5 | SDL_KMOD_MODE | SDL_KMOD_SHIFT | SDL_KMOD_CAPS, input->xkb.idx_mod3 | input->xkb.idx_mod5 | input->xkb.idx_shift | input->xkb.idx_caps }, + }; + + if (!input->keyboard_is_virtual) { + Wayland_Keymap keymap; + + keymap.keymap = SDL_CreateKeymap(); + if (!keymap.keymap) { + return; + } + + keymap.state = WAYLAND_xkb_state_new(input->xkb.keymap); + if (!keymap.state) { + SDL_SetError("failed to create XKB state"); + SDL_DestroyKeymap(keymap.keymap); + return; + } + + for (int i = 0; i < SDL_arraysize(keymod_masks); ++i) { + keymap.modstate = keymod_masks[i].sdl_mask; + WAYLAND_xkb_state_update_mask(keymap.state, + keymod_masks[i].xkb_mask & (input->xkb.idx_shift | input->xkb.idx_mod5 | input->xkb.idx_mod3), 0, keymod_masks[i].xkb_mask & input->xkb.idx_caps, + 0, 0, input->xkb.current_group); + WAYLAND_xkb_keymap_key_for_each(input->xkb.keymap, + Wayland_keymap_iter, + &keymap); + } + + WAYLAND_xkb_state_unref(keymap.state); + SDL_SetKeymap(keymap.keymap, true); + } else { + // Virtual keyboards use the default keymap. + SDL_SetKeymap(NULL, true); + } +} + +static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, + uint32_t format, int fd, uint32_t size) +{ + struct SDL_WaylandInput *input = data; + char *map_str; + const char *locale; + + if (!data) { + close(fd); + return; + } + + if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) { + close(fd); + return; + } + + map_str = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0); + if (map_str == MAP_FAILED) { + close(fd); + return; + } + + if (input->xkb.keymap != NULL) { + /* if there's already a keymap loaded, throw it away rather than leaking it before + * parsing the new one + */ + WAYLAND_xkb_keymap_unref(input->xkb.keymap); + input->xkb.keymap = NULL; + } + input->xkb.keymap = WAYLAND_xkb_keymap_new_from_string(input->display->xkb_context, + map_str, + XKB_KEYMAP_FORMAT_TEXT_V1, + 0); + munmap(map_str, size); + close(fd); + + if (!input->xkb.keymap) { + SDL_SetError("failed to compile keymap"); + return; + } + +#define GET_MOD_INDEX(mod) \ + WAYLAND_xkb_keymap_mod_get_index(input->xkb.keymap, XKB_MOD_NAME_##mod) + input->xkb.idx_shift = 1 << GET_MOD_INDEX(SHIFT); + input->xkb.idx_ctrl = 1 << GET_MOD_INDEX(CTRL); + input->xkb.idx_alt = 1 << GET_MOD_INDEX(ALT); + input->xkb.idx_gui = 1 << GET_MOD_INDEX(LOGO); + input->xkb.idx_mod3 = 1 << GET_MOD_INDEX(MOD3); + input->xkb.idx_mod5 = 1 << GET_MOD_INDEX(MOD5); + input->xkb.idx_num = 1 << GET_MOD_INDEX(NUM); + input->xkb.idx_caps = 1 << GET_MOD_INDEX(CAPS); +#undef GET_MOD_INDEX + + if (input->xkb.state != NULL) { + /* if there's already a state, throw it away rather than leaking it before + * trying to create a new one with the new keymap. + */ + WAYLAND_xkb_state_unref(input->xkb.state); + input->xkb.state = NULL; + } + input->xkb.state = WAYLAND_xkb_state_new(input->xkb.keymap); + if (!input->xkb.state) { + SDL_SetError("failed to create XKB state"); + WAYLAND_xkb_keymap_unref(input->xkb.keymap); + input->xkb.keymap = NULL; + return; + } + + /* + * Assume that a nameless layout implies a virtual keyboard with an arbitrary layout. + * TODO: Use a better method of detection? + */ + input->keyboard_is_virtual = WAYLAND_xkb_keymap_layout_get_name(input->xkb.keymap, 0) == NULL; + + // Update the keymap if changed. + if (input->xkb.current_group != XKB_GROUP_INVALID) { + Wayland_UpdateKeymap(input); + } + + /* + * See https://blogs.s-osg.org/compose-key-support-weston/ + * for further explanation on dead keys in Wayland. + */ + + // Look up the preferred locale, falling back to "C" as default + locale = SDL_getenv("LC_ALL"); + if (!locale) { + locale = SDL_getenv("LC_CTYPE"); + if (!locale) { + locale = SDL_getenv("LANG"); + if (!locale) { + locale = "C"; + } + } + } + + // Set up XKB compose table + if (input->xkb.compose_table != NULL) { + WAYLAND_xkb_compose_table_unref(input->xkb.compose_table); + input->xkb.compose_table = NULL; + } + input->xkb.compose_table = WAYLAND_xkb_compose_table_new_from_locale(input->display->xkb_context, + locale, XKB_COMPOSE_COMPILE_NO_FLAGS); + if (input->xkb.compose_table) { + // Set up XKB compose state + if (input->xkb.compose_state != NULL) { + WAYLAND_xkb_compose_state_unref(input->xkb.compose_state); + input->xkb.compose_state = NULL; + } + input->xkb.compose_state = WAYLAND_xkb_compose_state_new(input->xkb.compose_table, + XKB_COMPOSE_STATE_NO_FLAGS); + if (!input->xkb.compose_state) { + SDL_SetError("could not create XKB compose state"); + WAYLAND_xkb_compose_table_unref(input->xkb.compose_table); + input->xkb.compose_table = NULL; + } + } +} + +/* + * Virtual keyboards can have arbitrary layouts, arbitrary scancodes/keycodes, etc... + * Key presses from these devices must be looked up by their keysym value. + */ +static SDL_Scancode Wayland_GetScancodeForKey(struct SDL_WaylandInput *input, uint32_t key) +{ + SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN; + + if (!input->keyboard_is_virtual) { + scancode = SDL_GetScancodeFromTable(SDL_SCANCODE_TABLE_XFREE86_2, key); + } else { + const xkb_keysym_t *syms; + if (WAYLAND_xkb_keymap_key_get_syms_by_level(input->xkb.keymap, key + 8, input->xkb.current_group, 0, &syms) > 0) { + scancode = SDL_GetScancodeFromKeySym(syms[0], key); + } + } + + return scancode; +} + +static void Wayland_ReconcileModifiers(struct SDL_WaylandInput *input, bool key_pressed) +{ + /* Handle explicit pressed modifier state. This will correct the modifier state + * if common modifier keys were remapped and the modifiers presumed to be set + * during a key press event were incorrect, or if the modifier was set to the + * pressed state via means other than pressing the physical key. + */ + if (!key_pressed) { + if (input->xkb.wl_pressed_modifiers & input->xkb.idx_shift) { + if (!(input->pressed_modifiers & SDL_KMOD_SHIFT)) { + input->pressed_modifiers |= SDL_KMOD_SHIFT; + } + } else { + input->pressed_modifiers &= ~SDL_KMOD_SHIFT; + } + + if (input->xkb.wl_pressed_modifiers & input->xkb.idx_ctrl) { + if (!(input->pressed_modifiers & SDL_KMOD_CTRL)) { + input->pressed_modifiers |= SDL_KMOD_CTRL; + } + } else { + input->pressed_modifiers &= ~SDL_KMOD_CTRL; + } + + if (input->xkb.wl_pressed_modifiers & input->xkb.idx_alt) { + if (!(input->pressed_modifiers & SDL_KMOD_ALT)) { + input->pressed_modifiers |= SDL_KMOD_ALT; + } + } else { + input->pressed_modifiers &= ~SDL_KMOD_ALT; + } + + if (input->xkb.wl_pressed_modifiers & input->xkb.idx_gui) { + if (!(input->pressed_modifiers & SDL_KMOD_GUI)) { + input->pressed_modifiers |= SDL_KMOD_GUI; + } + } else { + input->pressed_modifiers &= ~SDL_KMOD_GUI; + } + + /* Note: This is not backwards: in the default keymap, Mod5 is typically + * level 3 shift, and Mod3 is typically level 5 shift. + */ + if (input->xkb.wl_pressed_modifiers & input->xkb.idx_mod3) { + if (!(input->pressed_modifiers & SDL_KMOD_LEVEL5)) { + input->pressed_modifiers |= SDL_KMOD_LEVEL5; + } + } else { + input->pressed_modifiers &= ~SDL_KMOD_LEVEL5; + } + + if (input->xkb.wl_pressed_modifiers & input->xkb.idx_mod5) { + if (!(input->pressed_modifiers & SDL_KMOD_MODE)) { + input->pressed_modifiers |= SDL_KMOD_MODE; + } + } else { + input->pressed_modifiers &= ~SDL_KMOD_MODE; + } + } + + /* If a latch or lock was activated by a keypress, the latch/lock will + * be tied to the specific left/right key that initiated it. Otherwise, + * the ambiguous left/right combo is used. + * + * The modifier will remain active until the latch/lock is released by + * the system. + */ + if (input->xkb.wl_locked_modifiers & input->xkb.idx_shift) { + if (input->pressed_modifiers & SDL_KMOD_SHIFT) { + input->locked_modifiers &= ~SDL_KMOD_SHIFT; + input->locked_modifiers |= (input->pressed_modifiers & SDL_KMOD_SHIFT); + } else if (!(input->locked_modifiers & SDL_KMOD_SHIFT)) { + input->locked_modifiers |= SDL_KMOD_SHIFT; + } + } else { + input->locked_modifiers &= ~SDL_KMOD_SHIFT; + } + + if (input->xkb.wl_locked_modifiers & input->xkb.idx_ctrl) { + if (input->pressed_modifiers & SDL_KMOD_CTRL) { + input->locked_modifiers &= ~SDL_KMOD_CTRL; + input->locked_modifiers |= (input->pressed_modifiers & SDL_KMOD_CTRL); + } else if (!(input->locked_modifiers & SDL_KMOD_CTRL)) { + input->locked_modifiers |= SDL_KMOD_CTRL; + } + } else { + input->locked_modifiers &= ~SDL_KMOD_CTRL; + } + + if (input->xkb.wl_locked_modifiers & input->xkb.idx_alt) { + if (input->pressed_modifiers & SDL_KMOD_ALT) { + input->locked_modifiers &= ~SDL_KMOD_ALT; + input->locked_modifiers |= (input->pressed_modifiers & SDL_KMOD_ALT); + } else if (!(input->locked_modifiers & SDL_KMOD_ALT)) { + input->locked_modifiers |= SDL_KMOD_ALT; + } + } else { + input->locked_modifiers &= ~SDL_KMOD_ALT; + } + + if (input->xkb.wl_locked_modifiers & input->xkb.idx_gui) { + if (input->pressed_modifiers & SDL_KMOD_GUI) { + input->locked_modifiers &= ~SDL_KMOD_GUI; + input->locked_modifiers |= (input->pressed_modifiers & SDL_KMOD_GUI); + } else if (!(input->locked_modifiers & SDL_KMOD_GUI)) { + input->locked_modifiers |= SDL_KMOD_GUI; + } + } else { + input->locked_modifiers &= ~SDL_KMOD_GUI; + } + + // As above, this is correct: Mod3 is typically level 5 shift, and Mod5 is typically level 3 shift. + if (input->xkb.wl_locked_modifiers & input->xkb.idx_mod3) { + input->locked_modifiers |= SDL_KMOD_LEVEL5; + } else { + input->locked_modifiers &= ~SDL_KMOD_LEVEL5; + } + + if (input->xkb.wl_locked_modifiers & input->xkb.idx_mod5) { + input->locked_modifiers |= SDL_KMOD_MODE; + } else { + input->locked_modifiers &= ~SDL_KMOD_MODE; + } + + // Capslock and Numlock can only be locked, not pressed. + if (input->xkb.wl_locked_modifiers & input->xkb.idx_caps) { + input->locked_modifiers |= SDL_KMOD_CAPS; + } else { + input->locked_modifiers &= ~SDL_KMOD_CAPS; + } + + if (input->xkb.wl_locked_modifiers & input->xkb.idx_num) { + input->locked_modifiers |= SDL_KMOD_NUM; + } else { + input->locked_modifiers &= ~SDL_KMOD_NUM; + } + + SDL_SetModState(input->pressed_modifiers | input->locked_modifiers); +} + +static void Wayland_HandleModifierKeys(struct SDL_WaylandInput *input, SDL_Scancode scancode, bool pressed) +{ + const SDL_Keycode keycode = SDL_GetKeyFromScancode(scancode, SDL_KMOD_NONE, false); + SDL_Keymod mod; + + /* SDL clients expect modifier state to be activated at the same time as the + * source keypress, so we set pressed modifier state with the usual modifier + * keys here, as the explicit modifier event won't arrive until after the + * keypress event. If this is wrong, it will be corrected when the explicit + * modifier state is sent at a later time. + */ + switch (keycode) { + case SDLK_LSHIFT: + mod = SDL_KMOD_LSHIFT; + break; + case SDLK_RSHIFT: + mod = SDL_KMOD_RSHIFT; + break; + case SDLK_LCTRL: + mod = SDL_KMOD_LCTRL; + break; + case SDLK_RCTRL: + mod = SDL_KMOD_RCTRL; + break; + case SDLK_LALT: + mod = SDL_KMOD_LALT; + break; + case SDLK_RALT: + mod = SDL_KMOD_RALT; + break; + case SDLK_LGUI: + mod = SDL_KMOD_LGUI; + break; + case SDLK_RGUI: + mod = SDL_KMOD_RGUI; + break; + case SDLK_MODE: + mod = SDL_KMOD_MODE; + break; + case SDLK_LEVEL5_SHIFT: + mod = SDL_KMOD_LEVEL5; + break; + default: + return; + } + + if (pressed) { + input->pressed_modifiers |= mod; + } else { + input->pressed_modifiers &= ~mod; + } + + Wayland_ReconcileModifiers(input, true); +} + +static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, + uint32_t serial, struct wl_surface *surface, + struct wl_array *keys) +{ + struct SDL_WaylandInput *input = data; + SDL_WindowData *window; + uint32_t *key; + + if (!surface) { + // enter event for a window we've just destroyed + return; + } + + window = Wayland_GetWindowDataForOwnedSurface(surface); + + if (!window) { + return; + } + + input->keyboard_focus = window; + window->keyboard_device = input; + + // Restore the keyboard focus to the child popup that was holding it + SDL_SetKeyboardFocus(window->keyboard_focus ? window->keyboard_focus : window->sdlwindow); + +#ifdef SDL_USE_IME + if (!input->text_input) { + SDL_IME_SetFocus(true); + } +#endif + + Uint64 timestamp = SDL_GetTicksNS(); + window->last_focus_event_time_ns = timestamp; + + wl_array_for_each (key, keys) { + const SDL_Scancode scancode = Wayland_GetScancodeForKey(input, *key); + const SDL_Keycode keycode = SDL_GetKeyFromScancode(scancode, SDL_KMOD_NONE, false); + + switch (keycode) { + case SDLK_LSHIFT: + case SDLK_RSHIFT: + case SDLK_LCTRL: + case SDLK_RCTRL: + case SDLK_LALT: + case SDLK_RALT: + case SDLK_LGUI: + case SDLK_RGUI: + case SDLK_MODE: + case SDLK_LEVEL5_SHIFT: + Wayland_HandleModifierKeys(input, scancode, true); + SDL_SendKeyboardKeyIgnoreModifiers(timestamp, input->keyboard_id, *key, scancode, true); + break; + default: + break; + } + } +} + +static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, + uint32_t serial, struct wl_surface *surface) +{ + struct SDL_WaylandInput *input = data; + SDL_WindowData *wind; + SDL_Window *window = NULL; + + if (!surface) { + return; + } + + wind = Wayland_GetWindowDataForOwnedSurface(surface); + if (!wind) { + return; + } + + wind->keyboard_device = NULL; + window = wind->sdlwindow; + + // Stop key repeat before clearing keyboard focus + keyboard_repeat_clear(&input->keyboard_repeat); + + // This will release any keys still pressed + SDL_SetKeyboardFocus(NULL); + input->keyboard_focus = NULL; + + // Clear the pressed modifiers. + input->pressed_modifiers = SDL_KMOD_NONE; + +#ifdef SDL_USE_IME + if (!input->text_input) { + SDL_IME_SetFocus(false); + } +#endif + + /* If the surface had a pointer leave event while still having active touch events, it retained mouse focus. + * Clear it now if all touch events are raised. + */ + if (!input->pointer_focus && SDL_GetMouseFocus() == window && !Wayland_SurfaceHasActiveTouches(surface)) { + SDL_SetMouseFocus(NULL); + } +} + +static bool keyboard_input_get_text(char text[8], const struct SDL_WaylandInput *input, uint32_t key, bool down, bool *handled_by_ime) +{ + SDL_WindowData *window = input->keyboard_focus; + const xkb_keysym_t *syms; + xkb_keysym_t sym; + + if (!window || window->keyboard_device != input || !input->xkb.state) { + return false; + } + + // TODO: Can this happen? + if (WAYLAND_xkb_state_key_get_syms(input->xkb.state, key + 8, &syms) != 1) { + return false; + } + sym = syms[0]; + +#ifdef SDL_USE_IME + if (SDL_IME_ProcessKeyEvent(sym, key + 8, down)) { + if (handled_by_ime) { + *handled_by_ime = true; + } + return true; + } +#endif + + if (!down) { + return false; + } + + if (input->xkb.compose_state && WAYLAND_xkb_compose_state_feed(input->xkb.compose_state, sym) == XKB_COMPOSE_FEED_ACCEPTED) { + switch (WAYLAND_xkb_compose_state_get_status(input->xkb.compose_state)) { + case XKB_COMPOSE_COMPOSING: + if (handled_by_ime) { + *handled_by_ime = true; + } + return true; + case XKB_COMPOSE_CANCELLED: + default: + sym = XKB_KEY_NoSymbol; + break; + case XKB_COMPOSE_NOTHING: + break; + case XKB_COMPOSE_COMPOSED: + sym = WAYLAND_xkb_compose_state_get_one_sym(input->xkb.compose_state); + break; + } + } + + return WAYLAND_xkb_keysym_to_utf8(sym, text, 8) > 0; +} + +static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, + uint32_t serial, uint32_t time, uint32_t key, + uint32_t state_w) +{ + struct SDL_WaylandInput *input = data; + enum wl_keyboard_key_state state = state_w; + char text[8]; + bool has_text = false; + bool handled_by_ime = false; + const Uint64 timestamp_raw_ns = Wayland_GetKeyboardTimestampRaw(input, time); + + Wayland_UpdateImplicitGrabSerial(input, serial); + + if (state == WL_KEYBOARD_KEY_STATE_PRESSED) { + SDL_Window *keyboard_focus = SDL_GetKeyboardFocus(); + if (keyboard_focus && SDL_TextInputActive(keyboard_focus)) { + has_text = keyboard_input_get_text(text, input, key, true, &handled_by_ime); + } + } else { + if (keyboard_repeat_key_is_set(&input->keyboard_repeat, key)) { + /* Send any due key repeat events before stopping the repeat and generating the key up event. + * Compute time based on the Wayland time, as it reports when the release event happened. + * Using SDL_GetTicks would be wrong, as it would report when the release event is processed, + * which may be off if the application hasn't pumped events for a while. + */ + keyboard_repeat_handle(&input->keyboard_repeat, timestamp_raw_ns - input->keyboard_repeat.wl_press_time_ns); + keyboard_repeat_clear(&input->keyboard_repeat); + } + keyboard_input_get_text(text, input, key, false, &handled_by_ime); + } + + const SDL_Scancode scancode = Wayland_GetScancodeForKey(input, key); + Wayland_HandleModifierKeys(input, scancode, state == WL_KEYBOARD_KEY_STATE_PRESSED); + Uint64 timestamp = Wayland_GetKeyboardTimestamp(input, time); + + SDL_SendKeyboardKeyIgnoreModifiers(timestamp, input->keyboard_id, key, scancode, state == WL_KEYBOARD_KEY_STATE_PRESSED); + + if (state == WL_KEYBOARD_KEY_STATE_PRESSED) { + if (has_text && !(SDL_GetModState() & SDL_KMOD_CTRL)) { + if (!handled_by_ime) { + SDL_SendKeyboardText(text); + } + } + if (input->xkb.keymap && WAYLAND_xkb_keymap_key_repeats(input->xkb.keymap, key + 8)) { + keyboard_repeat_set(&input->keyboard_repeat, input->keyboard_id, key, timestamp_raw_ns, scancode, has_text, text); + } + } +} + +static void keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard, + uint32_t serial, uint32_t mods_depressed, + uint32_t mods_latched, uint32_t mods_locked, + uint32_t group) +{ + struct SDL_WaylandInput *input = data; + + if (input->xkb.state == NULL) { + /* if we get a modifier notification before the keymap, there's nothing we can do with the information + */ + return; + } + + WAYLAND_xkb_state_update_mask(input->xkb.state, mods_depressed, mods_latched, + mods_locked, 0, 0, group); + + input->xkb.wl_pressed_modifiers = mods_depressed; + input->xkb.wl_locked_modifiers = mods_latched | mods_locked; + + Wayland_ReconcileModifiers(input, false); + + // If a key is repeating, update the text to apply the modifier. + if (keyboard_repeat_is_set(&input->keyboard_repeat)) { + char text[8]; + const uint32_t key = keyboard_repeat_get_key(&input->keyboard_repeat); + + if (keyboard_input_get_text(text, input, key, true, NULL)) { + keyboard_repeat_set_text(&input->keyboard_repeat, text); + } + } + + if (group == input->xkb.current_group) { + return; + } + + // The layout changed, remap and fire an event. Virtual keyboards use the default keymap. + input->xkb.current_group = group; + Wayland_UpdateKeymap(input); +} + +static void keyboard_handle_repeat_info(void *data, struct wl_keyboard *wl_keyboard, + int32_t rate, int32_t delay) +{ + struct SDL_WaylandInput *input = data; + input->keyboard_repeat.repeat_rate = SDL_clamp(rate, 0, 1000); + input->keyboard_repeat.repeat_delay_ms = delay; + input->keyboard_repeat.is_initialized = true; +} + +static const struct wl_keyboard_listener keyboard_listener = { + keyboard_handle_keymap, + keyboard_handle_enter, + keyboard_handle_leave, + keyboard_handle_key, + keyboard_handle_modifiers, + keyboard_handle_repeat_info, // Version 4 +}; + +void Wayland_input_init_relative_pointer(SDL_VideoData *d) +{ + struct SDL_WaylandInput *input = d->input; + + if (!d->relative_pointer_manager) { + return; + } + + if (input->pointer && !input->relative_pointer) { + input->relative_pointer = zwp_relative_pointer_manager_v1_get_relative_pointer(input->display->relative_pointer_manager, input->pointer); + zwp_relative_pointer_v1_add_listener(input->relative_pointer, + &relative_pointer_listener, + input); + } +} + +static void seat_handle_capabilities(void *data, struct wl_seat *seat, + enum wl_seat_capability caps) +{ + struct SDL_WaylandInput *input = data; + + if ((caps & WL_SEAT_CAPABILITY_POINTER) && !input->pointer) { + input->pointer = wl_seat_get_pointer(seat); + SDL_memset(&input->pointer_curr_axis_info, 0, sizeof(input->pointer_curr_axis_info)); + input->display->pointer = input->pointer; + + Wayland_CreateCursorShapeDevice(input); + + wl_pointer_set_user_data(input->pointer, input); + wl_pointer_add_listener(input->pointer, &pointer_listener, input); + + Wayland_input_init_relative_pointer(input->display); + + input->pointer_id = SDL_GetNextObjectID(); + SDL_AddMouse(input->pointer_id, WAYLAND_DEFAULT_POINTER_NAME, !input->display->initializing); + } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && input->pointer) { + if (input->relative_pointer) { + zwp_relative_pointer_v1_destroy(input->relative_pointer); + input->relative_pointer = NULL; + } + if (input->cursor_shape) { + wp_cursor_shape_device_v1_destroy(input->cursor_shape); + input->cursor_shape = NULL; + } + if (wl_pointer_get_version(input->pointer) >= WL_POINTER_RELEASE_SINCE_VERSION) { + wl_pointer_release(input->pointer); + } else { + wl_pointer_destroy(input->pointer); + } + input->pointer = NULL; + input->display->pointer = NULL; + + SDL_RemoveMouse(input->pointer_id, true); + input->pointer_id = 0; + } + + if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !input->touch) { + input->touch = wl_seat_get_touch(seat); + SDL_AddTouch((SDL_TouchID)(uintptr_t)input->touch, SDL_TOUCH_DEVICE_DIRECT, "wayland_touch"); + wl_touch_set_user_data(input->touch, input); + wl_touch_add_listener(input->touch, &touch_listener, + input); + } else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && input->touch) { + SDL_DelTouch((SDL_TouchID)(intptr_t)input->touch); + wl_touch_destroy(input->touch); + input->touch = NULL; + } + + if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !input->keyboard) { + input->keyboard = wl_seat_get_keyboard(seat); + wl_keyboard_set_user_data(input->keyboard, input); + wl_keyboard_add_listener(input->keyboard, &keyboard_listener, + input); + + input->keyboard_id = SDL_GetNextObjectID(); + SDL_AddKeyboard(input->keyboard_id, WAYLAND_DEFAULT_KEYBOARD_NAME, !input->display->initializing); + } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && input->keyboard) { + wl_keyboard_destroy(input->keyboard); + input->keyboard = NULL; + + SDL_RemoveKeyboard(input->keyboard_id, true); + input->keyboard_id = 0; + } + + Wayland_RegisterTimestampListeners(input); +} + +static void seat_handle_name(void *data, struct wl_seat *wl_seat, const char *name) +{ + // unimplemented +} + +static const struct wl_seat_listener seat_listener = { + seat_handle_capabilities, + seat_handle_name, // Version 2 +}; + +static void data_source_handle_target(void *data, struct wl_data_source *wl_data_source, + const char *mime_type) +{ +} + +static void data_source_handle_send(void *data, struct wl_data_source *wl_data_source, + const char *mime_type, int32_t fd) +{ + Wayland_data_source_send((SDL_WaylandDataSource *)data, mime_type, fd); +} + +static void data_source_handle_cancelled(void *data, struct wl_data_source *wl_data_source) +{ + SDL_WaylandDataSource *source = data; + if (source) { + Wayland_data_source_destroy(source); + } +} + +static void data_source_handle_dnd_drop_performed(void *data, struct wl_data_source *wl_data_source) +{ +} + +static void data_source_handle_dnd_finished(void *data, struct wl_data_source *wl_data_source) +{ +} + +static void data_source_handle_action(void *data, struct wl_data_source *wl_data_source, + uint32_t dnd_action) +{ +} + +static const struct wl_data_source_listener data_source_listener = { + data_source_handle_target, + data_source_handle_send, + data_source_handle_cancelled, + data_source_handle_dnd_drop_performed, // Version 3 + data_source_handle_dnd_finished, // Version 3 + data_source_handle_action, // Version 3 +}; + +static void primary_selection_source_send(void *data, struct zwp_primary_selection_source_v1 *zwp_primary_selection_source_v1, + const char *mime_type, int32_t fd) +{ + Wayland_primary_selection_source_send((SDL_WaylandPrimarySelectionSource *)data, + mime_type, fd); +} + +static void primary_selection_source_cancelled(void *data, struct zwp_primary_selection_source_v1 *zwp_primary_selection_source_v1) +{ + Wayland_primary_selection_source_destroy(data); +} + +static const struct zwp_primary_selection_source_v1_listener primary_selection_source_listener = { + primary_selection_source_send, + primary_selection_source_cancelled, +}; + +SDL_WaylandDataSource *Wayland_data_source_create(SDL_VideoDevice *_this) +{ + SDL_WaylandDataSource *data_source = NULL; + SDL_VideoData *driver_data = NULL; + struct wl_data_source *id = NULL; + + if (!_this || !_this->internal) { + SDL_SetError("Video driver uninitialized"); + } else { + driver_data = _this->internal; + + if (driver_data->data_device_manager) { + id = wl_data_device_manager_create_data_source( + driver_data->data_device_manager); + } + + if (!id) { + SDL_SetError("Wayland unable to create data source"); + } else { + data_source = SDL_calloc(1, sizeof(*data_source)); + if (!data_source) { + wl_data_source_destroy(id); + } else { + data_source->source = id; + wl_data_source_set_user_data(id, data_source); + wl_data_source_add_listener(id, &data_source_listener, + data_source); + } + } + } + return data_source; +} + +SDL_WaylandPrimarySelectionSource *Wayland_primary_selection_source_create(SDL_VideoDevice *_this) +{ + SDL_WaylandPrimarySelectionSource *primary_selection_source = NULL; + SDL_VideoData *driver_data = NULL; + struct zwp_primary_selection_source_v1 *id = NULL; + + if (!_this || !_this->internal) { + SDL_SetError("Video driver uninitialized"); + } else { + driver_data = _this->internal; + + if (driver_data->primary_selection_device_manager) { + id = zwp_primary_selection_device_manager_v1_create_source( + driver_data->primary_selection_device_manager); + } + + if (!id) { + SDL_SetError("Wayland unable to create primary selection source"); + } else { + primary_selection_source = SDL_calloc(1, sizeof(*primary_selection_source)); + if (!primary_selection_source) { + zwp_primary_selection_source_v1_destroy(id); + } else { + primary_selection_source->source = id; + zwp_primary_selection_source_v1_add_listener(id, &primary_selection_source_listener, + primary_selection_source); + } + } + } + return primary_selection_source; +} + +static void data_offer_handle_offer(void *data, struct wl_data_offer *wl_data_offer, + const char *mime_type) +{ + SDL_WaylandDataOffer *offer = data; + Wayland_data_offer_add_mime(offer, mime_type); + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_offer_listener . data_offer_handle_offer on data_offer 0x%08x for MIME '%s'", + (wl_data_offer ? WAYLAND_wl_proxy_get_id((struct wl_proxy *)wl_data_offer) : -1), + mime_type); +} + +static void data_offer_handle_source_actions(void *data, struct wl_data_offer *wl_data_offer, + uint32_t source_actions) +{ + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_offer_listener . data_offer_handle_source_actions on data_offer 0x%08x for Source Actions '%d'", + (wl_data_offer ? WAYLAND_wl_proxy_get_id((struct wl_proxy *)wl_data_offer) : -1), + source_actions); +} + +static void data_offer_handle_actions(void *data, struct wl_data_offer *wl_data_offer, + uint32_t dnd_action) +{ + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_offer_listener . data_offer_handle_actions on data_offer 0x%08x for DND Actions '%d'", + (wl_data_offer ? WAYLAND_wl_proxy_get_id((struct wl_proxy *)wl_data_offer) : -1), + dnd_action); +} + +static const struct wl_data_offer_listener data_offer_listener = { + data_offer_handle_offer, + data_offer_handle_source_actions, // Version 3 + data_offer_handle_actions, // Version 3 +}; + +static void primary_selection_offer_handle_offer(void *data, struct zwp_primary_selection_offer_v1 *zwp_primary_selection_offer_v1, + const char *mime_type) +{ + SDL_WaylandPrimarySelectionOffer *offer = data; + Wayland_primary_selection_offer_add_mime(offer, mime_type); + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In zwp_primary_selection_offer_v1_listener . primary_selection_offer_handle_offer on primary_selection_offer 0x%08x for MIME '%s'", + (zwp_primary_selection_offer_v1 ? WAYLAND_wl_proxy_get_id((struct wl_proxy *)zwp_primary_selection_offer_v1) : -1), + mime_type); +} + +static const struct zwp_primary_selection_offer_v1_listener primary_selection_offer_listener = { + primary_selection_offer_handle_offer, +}; + +static void data_device_handle_data_offer(void *data, struct wl_data_device *wl_data_device, + struct wl_data_offer *id) +{ + SDL_WaylandDataOffer *data_offer = SDL_calloc(1, sizeof(*data_offer)); + if (data_offer) { + data_offer->offer = id; + data_offer->data_device = data; + WAYLAND_wl_list_init(&(data_offer->mimes)); + wl_data_offer_set_user_data(id, data_offer); + wl_data_offer_add_listener(id, &data_offer_listener, data_offer); + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_data_offer on data_offer 0x%08x", + (id ? WAYLAND_wl_proxy_get_id((struct wl_proxy *)id) : -1)); + } +} + +static void data_device_handle_enter(void *data, struct wl_data_device *wl_data_device, + uint32_t serial, struct wl_surface *surface, + wl_fixed_t x, wl_fixed_t y, struct wl_data_offer *id) +{ + SDL_WaylandDataDevice *data_device = data; + data_device->has_mime_file = false; + data_device->has_mime_text = false; + uint32_t dnd_action = WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE; + + data_device->drag_serial = serial; + + if (id) { + data_device->drag_offer = wl_data_offer_get_user_data(id); + + // TODO: SDL Support more mime types +#ifdef SDL_USE_LIBDBUS + if (Wayland_data_offer_has_mime(data_device->drag_offer, FILE_PORTAL_MIME)) { + data_device->has_mime_file = true; + wl_data_offer_accept(id, serial, FILE_PORTAL_MIME); + } +#endif + if (Wayland_data_offer_has_mime(data_device->drag_offer, FILE_MIME)) { + data_device->has_mime_file = true; + wl_data_offer_accept(id, serial, FILE_MIME); + } + + if (Wayland_data_offer_has_mime(data_device->drag_offer, TEXT_MIME)) { + data_device->has_mime_text = true; + wl_data_offer_accept(id, serial, TEXT_MIME); + } + + // SDL only supports "copy" style drag and drop + if (data_device->has_mime_file || data_device->has_mime_text) { + dnd_action = WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY; + } else { + // drag_mime is NULL this will decline the offer + wl_data_offer_accept(id, serial, NULL); + } + if (wl_data_offer_get_version(data_device->drag_offer->offer) >= + WL_DATA_OFFER_SET_ACTIONS_SINCE_VERSION) { + wl_data_offer_set_actions(data_device->drag_offer->offer, + dnd_action, dnd_action); + } + + // find the current window + if (surface) { + SDL_WindowData *window = Wayland_GetWindowDataForOwnedSurface(surface); + if (window) { + data_device->dnd_window = window->sdlwindow; + const float dx = (float)wl_fixed_to_double(x); + const float dy = (float)wl_fixed_to_double(y); + SDL_SendDropPosition(data_device->dnd_window, dx, dy); + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_enter on data_offer 0x%08x at %d x %d into window %d for serial %d", + WAYLAND_wl_proxy_get_id((struct wl_proxy *)id), + wl_fixed_to_int(x), wl_fixed_to_int(y), SDL_GetWindowID(data_device->dnd_window), serial); + } else { + data_device->dnd_window = NULL; + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_enter on data_offer 0x%08x at %d x %d for serial %d", + WAYLAND_wl_proxy_get_id((struct wl_proxy *)id), + wl_fixed_to_int(x), wl_fixed_to_int(y), serial); + } + } else { + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_enter on data_offer 0x%08x at %d x %d for serial %d", + WAYLAND_wl_proxy_get_id((struct wl_proxy *)id), + wl_fixed_to_int(x), wl_fixed_to_int(y), serial); + } + } else { + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_enter on data_offer 0x%08x at %d x %d for serial %d", + -1, wl_fixed_to_int(x), wl_fixed_to_int(y), serial); + } +} + +static void data_device_handle_leave(void *data, struct wl_data_device *wl_data_device) +{ + SDL_WaylandDataDevice *data_device = data; + + if (data_device->drag_offer) { + if (data_device->dnd_window) { + SDL_SendDropComplete(data_device->dnd_window); + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_leave on data_offer 0x%08x from window %d for serial %d", + WAYLAND_wl_proxy_get_id((struct wl_proxy *)data_device->drag_offer->offer), + SDL_GetWindowID(data_device->dnd_window), data_device->drag_serial); + } else { + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_leave on data_offer 0x%08x for serial %d", + WAYLAND_wl_proxy_get_id((struct wl_proxy *)data_device->drag_offer->offer), + data_device->drag_serial); + } + Wayland_data_offer_destroy(data_device->drag_offer); + data_device->drag_offer = NULL; + } else { + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_leave on data_offer 0x%08x for serial %d", + -1, -1); + } + data_device->has_mime_file = false; + data_device->has_mime_text = false; +} + +static void data_device_handle_motion(void *data, struct wl_data_device *wl_data_device, + uint32_t time, wl_fixed_t x, wl_fixed_t y) +{ + SDL_WaylandDataDevice *data_device = data; + + if (data_device->drag_offer && data_device->dnd_window && (data_device->has_mime_file || data_device->has_mime_text)) { + const float dx = (float)wl_fixed_to_double(x); + const float dy = (float)wl_fixed_to_double(y); + + /* XXX: Send the filename here if the event system ever starts passing it though. + * Any future implementation should cache the filenames, as otherwise this could + * hammer the DBus interface hundreds or even thousands of times per second. + */ + SDL_SendDropPosition(data_device->dnd_window, dx, dy); + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_motion on data_offer 0x%08x at %d x %d in window %d serial %d", + WAYLAND_wl_proxy_get_id((struct wl_proxy *)data_device->drag_offer->offer), + wl_fixed_to_int(x), wl_fixed_to_int(y), + SDL_GetWindowID(data_device->dnd_window), data_device->drag_serial); + } else { + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_motion on data_offer 0x%08x at %d x %d serial %d", + -1, wl_fixed_to_int(x), wl_fixed_to_int(y), -1); + } +} + +static void data_device_handle_drop(void *data, struct wl_data_device *wl_data_device) +{ + SDL_WaylandDataDevice *data_device = data; + + if (data_device->drag_offer && data_device->dnd_window && (data_device->has_mime_file || data_device->has_mime_text)) { + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_drop on data_offer 0x%08x in window %d serial %d", + WAYLAND_wl_proxy_get_id((struct wl_proxy *)data_device->drag_offer->offer), + SDL_GetWindowID(data_device->dnd_window), data_device->drag_serial); + // TODO: SDL Support more mime types + size_t length; + bool drop_handled = false; +#ifdef SDL_USE_LIBDBUS + if (Wayland_data_offer_has_mime(data_device->drag_offer, FILE_PORTAL_MIME)) { + void *buffer = Wayland_data_offer_receive(data_device->drag_offer, + FILE_PORTAL_MIME, &length); + if (buffer) { + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + if (dbus) { + int path_count = 0; + char **paths = SDL_DBus_DocumentsPortalRetrieveFiles(buffer, &path_count); + // If dropped files contain a directory the list is empty + if (paths && path_count > 0) { + int i; + for (i = 0; i < path_count; i++) { + SDL_SendDropFile(data_device->dnd_window, NULL, paths[i]); + } + dbus->free_string_array(paths); + SDL_SendDropComplete(data_device->dnd_window); + drop_handled = true; + } + } + SDL_free(buffer); + } + } +#endif + /* If XDG document portal fails fallback. + * When running a flatpak sandbox this will most likely be a list of + * non paths that are not visible to the application + */ + if (!drop_handled) { + const char *mime_type = data_device->has_mime_file ? FILE_MIME : (data_device->has_mime_text ? TEXT_MIME : ""); + void *buffer = Wayland_data_offer_receive(data_device->drag_offer, + mime_type, &length); + if (data_device->has_mime_file) { + if (buffer) { + char *saveptr = NULL; + char *token = SDL_strtok_r((char *)buffer, "\r\n", &saveptr); + while (token) { + if (SDL_URIToLocal(token, token) >= 0) { + SDL_SendDropFile(data_device->dnd_window, NULL, token); + } + token = SDL_strtok_r(NULL, "\r\n", &saveptr); + } + SDL_free(buffer); + SDL_SendDropComplete(data_device->dnd_window); + } else { + SDL_SendDropComplete(data_device->dnd_window); + } + drop_handled = true; + } else if (data_device->has_mime_text) { + if (buffer) { + char *saveptr = NULL; + char *token = SDL_strtok_r((char *)buffer, "\r\n", &saveptr); + while (token) { + SDL_SendDropText(data_device->dnd_window, token); + token = SDL_strtok_r(NULL, "\r\n", &saveptr); + } + SDL_free(buffer); + SDL_SendDropComplete(data_device->dnd_window); + } else { + /* Even though there has been a valid data offer, + * and there have been valid Enter, Motion, and Drop callbacks, + * Wayland_data_offer_receive may return an empty buffer, + * because the data is actually in the primary selection device, + * not in the data device. + */ + SDL_SendDropComplete(data_device->dnd_window); + } + drop_handled = true; + } + } + + if (drop_handled && wl_data_offer_get_version(data_device->drag_offer->offer) >= WL_DATA_OFFER_FINISH_SINCE_VERSION) { + wl_data_offer_finish(data_device->drag_offer->offer); + } + } else { + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In wl_data_device_listener . data_device_handle_drop on data_offer 0x%08x serial %d", + -1, -1); + } + + Wayland_data_offer_destroy(data_device->drag_offer); + data_device->drag_offer = NULL; +} + +static void notifyFromMimes(struct wl_list *mimes) +{ + int nformats = 0; + char **new_mime_types = NULL; + if (mimes) { + nformats = WAYLAND_wl_list_length(mimes); + size_t alloc_size = (nformats + 1) * sizeof(char *); + + /* do a first pass to compute allocation size */ + SDL_MimeDataList *item = NULL; + wl_list_for_each(item, mimes, link) { + alloc_size += SDL_strlen(item->mime_type) + 1; + } + + new_mime_types = SDL_AllocateTemporaryMemory(alloc_size); + if (!new_mime_types) { + SDL_LogError(SDL_LOG_CATEGORY_INPUT, "unable to allocate new_mime_types"); + return; + } + + /* second pass to fill*/ + char *strPtr = (char *)(new_mime_types + nformats + 1); + item = NULL; + int i = 0; + wl_list_for_each(item, mimes, link) { + new_mime_types[i] = strPtr; + strPtr = stpcpy(strPtr, item->mime_type) + 1; + i++; + } + new_mime_types[nformats] = NULL; + } + + SDL_SendClipboardUpdate(false, new_mime_types, nformats); +} + +static void data_device_handle_selection(void *data, struct wl_data_device *wl_data_device, + struct wl_data_offer *id) +{ + SDL_WaylandDataDevice *data_device = data; + SDL_WaylandDataOffer *offer = NULL; + + if (id) { + offer = wl_data_offer_get_user_data(id); + } + + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In data_device_listener . data_device_handle_selection on data_offer 0x%08x", + (id ? WAYLAND_wl_proxy_get_id((struct wl_proxy *)id) : -1)); + if (data_device->selection_offer != offer) { + Wayland_data_offer_destroy(data_device->selection_offer); + data_device->selection_offer = offer; + } + + notifyFromMimes(offer ? &offer->mimes : NULL); +} + +static const struct wl_data_device_listener data_device_listener = { + data_device_handle_data_offer, + data_device_handle_enter, + data_device_handle_leave, + data_device_handle_motion, + data_device_handle_drop, + data_device_handle_selection +}; + +static void primary_selection_device_handle_offer(void *data, struct zwp_primary_selection_device_v1 *zwp_primary_selection_device_v1, + struct zwp_primary_selection_offer_v1 *id) +{ + SDL_WaylandPrimarySelectionOffer *primary_selection_offer = SDL_calloc(1, sizeof(*primary_selection_offer)); + if (primary_selection_offer) { + primary_selection_offer->offer = id; + primary_selection_offer->primary_selection_device = data; + WAYLAND_wl_list_init(&(primary_selection_offer->mimes)); + zwp_primary_selection_offer_v1_set_user_data(id, primary_selection_offer); + zwp_primary_selection_offer_v1_add_listener(id, &primary_selection_offer_listener, primary_selection_offer); + } + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In zwp_primary_selection_device_v1_listener . primary_selection_device_handle_offer on primary_selection_offer 0x%08x", + (id ? WAYLAND_wl_proxy_get_id((struct wl_proxy *)id) : -1)); +} + +static void primary_selection_device_handle_selection(void *data, struct zwp_primary_selection_device_v1 *zwp_primary_selection_device_v1, + struct zwp_primary_selection_offer_v1 *id) +{ + SDL_WaylandPrimarySelectionDevice *primary_selection_device = data; + SDL_WaylandPrimarySelectionOffer *offer = NULL; + + if (id) { + offer = zwp_primary_selection_offer_v1_get_user_data(id); + } + + if (primary_selection_device->selection_offer != offer) { + Wayland_primary_selection_offer_destroy(primary_selection_device->selection_offer); + primary_selection_device->selection_offer = offer; + } + SDL_LogTrace(SDL_LOG_CATEGORY_INPUT, + ". In zwp_primary_selection_device_v1_listener . primary_selection_device_handle_selection on primary_selection_offer 0x%08x", + (id ? WAYLAND_wl_proxy_get_id((struct wl_proxy *)id) : -1)); +} + +static const struct zwp_primary_selection_device_v1_listener primary_selection_device_listener = { + primary_selection_device_handle_offer, + primary_selection_device_handle_selection +}; + +static void text_input_enter(void *data, + struct zwp_text_input_v3 *zwp_text_input_v3, + struct wl_surface *surface) +{ + // No-op +} + +static void text_input_leave(void *data, + struct zwp_text_input_v3 *zwp_text_input_v3, + struct wl_surface *surface) +{ + // No-op +} + +static void text_input_preedit_string(void *data, + struct zwp_text_input_v3 *zwp_text_input_v3, + const char *text, + int32_t cursor_begin, + int32_t cursor_end) +{ + SDL_WaylandTextInput *text_input = data; + text_input->has_preedit = true; + if (text) { + int cursor_begin_utf8 = cursor_begin >= 0 ? (int)SDL_utf8strnlen(text, cursor_begin) : -1; + int cursor_end_utf8 = cursor_end >= 0 ? (int)SDL_utf8strnlen(text, cursor_end) : -1; + int cursor_size_utf8; + if (cursor_end_utf8 >= 0) { + if (cursor_begin_utf8 >= 0) { + cursor_size_utf8 = cursor_end_utf8 - cursor_begin_utf8; + } else { + cursor_size_utf8 = cursor_end_utf8; + } + } else { + cursor_size_utf8 = -1; + } + SDL_SendEditingText(text, cursor_begin_utf8, cursor_size_utf8); + } else { + SDL_SendEditingText("", 0, 0); + } +} + +static void text_input_commit_string(void *data, + struct zwp_text_input_v3 *zwp_text_input_v3, + const char *text) +{ + SDL_SendKeyboardText(text); +} + +static void text_input_delete_surrounding_text(void *data, + struct zwp_text_input_v3 *zwp_text_input_v3, + uint32_t before_length, + uint32_t after_length) +{ + // FIXME: Do we care about this event? +} + +static void text_input_done(void *data, + struct zwp_text_input_v3 *zwp_text_input_v3, + uint32_t serial) +{ + SDL_WaylandTextInput *text_input = data; + if (!text_input->has_preedit) { + SDL_SendEditingText("", 0, 0); + } + text_input->has_preedit = false; +} + +static const struct zwp_text_input_v3_listener text_input_listener = { + text_input_enter, + text_input_leave, + text_input_preedit_string, + text_input_commit_string, + text_input_delete_surrounding_text, + text_input_done +}; + +void Wayland_create_data_device(SDL_VideoData *d) +{ + SDL_WaylandDataDevice *data_device = NULL; + + if (!d->input->seat) { + // No seat yet, will be initialized later. + return; + } + + data_device = SDL_calloc(1, sizeof(*data_device)); + if (!data_device) { + return; + } + + data_device->data_device = wl_data_device_manager_get_data_device( + d->data_device_manager, d->input->seat); + data_device->video_data = d; + + if (!data_device->data_device) { + SDL_free(data_device); + } else { + wl_data_device_set_user_data(data_device->data_device, data_device); + wl_data_device_add_listener(data_device->data_device, + &data_device_listener, data_device); + d->input->data_device = data_device; + } +} + +void Wayland_create_primary_selection_device(SDL_VideoData *d) +{ + SDL_WaylandPrimarySelectionDevice *primary_selection_device = NULL; + + if (!d->input->seat) { + // No seat yet, will be initialized later. + return; + } + + primary_selection_device = SDL_calloc(1, sizeof(*primary_selection_device)); + if (!primary_selection_device) { + return; + } + + primary_selection_device->primary_selection_device = zwp_primary_selection_device_manager_v1_get_device( + d->primary_selection_device_manager, d->input->seat); + primary_selection_device->video_data = d; + + if (!primary_selection_device->primary_selection_device) { + SDL_free(primary_selection_device); + } else { + zwp_primary_selection_device_v1_set_user_data(primary_selection_device->primary_selection_device, + primary_selection_device); + zwp_primary_selection_device_v1_add_listener(primary_selection_device->primary_selection_device, + &primary_selection_device_listener, primary_selection_device); + d->input->primary_selection_device = primary_selection_device; + } +} + +static void Wayland_create_text_input(SDL_VideoData *d) +{ + SDL_WaylandTextInput *text_input = NULL; + + if (!d->input->seat) { + // No seat yet, will be initialized later. + return; + } + + text_input = SDL_calloc(1, sizeof(*text_input)); + if (!text_input) { + return; + } + + text_input->text_input = zwp_text_input_manager_v3_get_text_input( + d->text_input_manager, d->input->seat); + + if (!text_input->text_input) { + SDL_free(text_input); + } else { + zwp_text_input_v3_set_user_data(text_input->text_input, text_input); + zwp_text_input_v3_add_listener(text_input->text_input, + &text_input_listener, text_input); + d->input->text_input = text_input; + } +} + +void Wayland_create_text_input_manager(SDL_VideoData *d, uint32_t id) +{ +#ifdef HAVE_FCITX + const char *im_module = SDL_getenv("SDL_IM_MODULE"); + if (im_module && SDL_strcmp(im_module, "fcitx") == 0) { + /* Override the Wayland text-input protocol when Fcitx is enabled, like how GTK_IM_MODULE does. + * + * The Fcitx wiki discourages enabling it under Wayland via SDL_IM_MODULE, so its presence must + * be intentional, and this workaround is needed for fixing key repeat detection. + */ + return; + } +#endif + + d->text_input_manager = wl_registry_bind(d->registry, id, &zwp_text_input_manager_v3_interface, 1); + Wayland_create_text_input(d); +} + +// Pen/Tablet support... + +typedef struct SDL_WaylandPenTool // a stylus, etc, on a tablet. +{ + SDL_PenID instance_id; + SDL_PenInfo info; + SDL_Window *tool_focus; + struct zwp_tablet_tool_v2 *wltool; + float x; + float y; + bool frame_motion_set; + float frame_axes[SDL_PEN_AXIS_COUNT]; + Uint32 frame_axes_set; + int frame_pen_down; + int frame_buttons[3]; +} SDL_WaylandPenTool; + +static void tablet_tool_handle_type(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t type) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + switch (type) { + #define CASE(typ) case ZWP_TABLET_TOOL_V2_TYPE_##typ: sdltool->info.subtype = SDL_PEN_TYPE_##typ; return + CASE(ERASER); + CASE(PEN); + CASE(PENCIL); + CASE(AIRBRUSH); + CASE(BRUSH); + #undef CASE + default: sdltool->info.subtype = SDL_PEN_TYPE_UNKNOWN; // we'll decline to add this when the `done` event comes through. + } +} + +static void tablet_tool_handle_hardware_serial(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t serial_hi, uint32_t serial_lo) +{ + // don't care about this atm. +} + +static void tablet_tool_handle_hardware_id_wacom(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t id_hi, uint32_t id_lo) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + sdltool->info.wacom_id = id_lo; +} + +static void tablet_tool_handle_capability(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t capability) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + switch (capability) { + #define CASE(wltyp,sdltyp) case ZWP_TABLET_TOOL_V2_CAPABILITY_##wltyp: sdltool->info.capabilities |= sdltyp; return + CASE(TILT, SDL_PEN_CAPABILITY_XTILT | SDL_PEN_CAPABILITY_YTILT); + CASE(PRESSURE, SDL_PEN_CAPABILITY_PRESSURE); + CASE(DISTANCE, SDL_PEN_CAPABILITY_DISTANCE); + CASE(ROTATION, SDL_PEN_CAPABILITY_ROTATION); + CASE(SLIDER, SDL_PEN_CAPABILITY_SLIDER); + #undef CASE + default: break; // unsupported here. + } +} + +static void tablet_tool_handle_done(void *data, struct zwp_tablet_tool_v2 *tool) +{ +} + +static void tablet_tool_handle_removed(void *data, struct zwp_tablet_tool_v2 *tool) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + if (sdltool->instance_id) { + SDL_RemovePenDevice(0, sdltool->instance_id); + } + zwp_tablet_tool_v2_destroy(tool); + SDL_free(sdltool); +} + +static void tablet_tool_handle_proximity_in(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t serial, struct zwp_tablet_v2 *tablet, struct wl_surface *surface) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + SDL_WindowData *windowdata = surface ? Wayland_GetWindowDataForOwnedSurface(surface) : NULL; + sdltool->tool_focus = windowdata ? windowdata->sdlwindow : NULL; + + SDL_assert(sdltool->instance_id == 0); // shouldn't be added at this point. + if (sdltool->info.subtype != SDL_PEN_TYPE_UNKNOWN) { // don't tell SDL about it if we don't know its role. + sdltool->instance_id = SDL_AddPenDevice(0, NULL, &sdltool->info, sdltool); + } + + // According to the docs, this should be followed by a motion event, where we'll send our SDL events. +} + +static void tablet_tool_handle_proximity_out(void *data, struct zwp_tablet_tool_v2 *tool) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + sdltool->tool_focus = NULL; + + if (sdltool->instance_id) { + SDL_RemovePenDevice(0, sdltool->instance_id); + sdltool->instance_id = 0; + } +} + +static void tablet_tool_handle_down(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t serial) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + sdltool->frame_pen_down = 1; +} + +static void tablet_tool_handle_up(void *data, struct zwp_tablet_tool_v2 *tool) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + sdltool->frame_pen_down = 0; +} + +static void tablet_tool_handle_motion(void *data, struct zwp_tablet_tool_v2 *tool, wl_fixed_t sx_w, wl_fixed_t sy_w) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + SDL_Window *window = sdltool->tool_focus; + if (window) { + const SDL_WindowData *windowdata = window->internal; + sdltool->x = (float)(wl_fixed_to_double(sx_w) * windowdata->pointer_scale.x); + sdltool->y = (float)(wl_fixed_to_double(sy_w) * windowdata->pointer_scale.y); + sdltool->frame_motion_set = true; + } +} + +static void tablet_tool_handle_pressure(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t pressure) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + sdltool->frame_axes[SDL_PEN_AXIS_PRESSURE] = ((float) pressure) / 65535.0f; + sdltool->frame_axes_set |= (1u << SDL_PEN_AXIS_PRESSURE); + if (pressure) { + sdltool->frame_axes[SDL_PEN_AXIS_DISTANCE] = 0.0f; + sdltool->frame_axes_set |= (1u << SDL_PEN_AXIS_DISTANCE); + } +} + +static void tablet_tool_handle_distance(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t distance) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + sdltool->frame_axes[SDL_PEN_AXIS_DISTANCE] = ((float) distance) / 65535.0f; + sdltool->frame_axes_set |= (1u << SDL_PEN_AXIS_DISTANCE); + if (distance) { + sdltool->frame_axes[SDL_PEN_AXIS_PRESSURE] = 0.0f; + sdltool->frame_axes_set |= (1u << SDL_PEN_AXIS_PRESSURE); + } +} + +static void tablet_tool_handle_tilt(void *data, struct zwp_tablet_tool_v2 *tool, wl_fixed_t xtilt, wl_fixed_t ytilt) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + sdltool->frame_axes[SDL_PEN_AXIS_XTILT] = (float)(wl_fixed_to_double(xtilt)); + sdltool->frame_axes[SDL_PEN_AXIS_YTILT] = (float)(wl_fixed_to_double(ytilt)); + sdltool->frame_axes_set |= (1u << SDL_PEN_AXIS_XTILT) | (1u << SDL_PEN_AXIS_YTILT); +} + +static void tablet_tool_handle_button(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t serial, uint32_t button, uint32_t state) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + int sdlbutton; + + switch (button) { + // see %{_includedir}/linux/input-event-codes.h + case 0x14b: // BTN_STYLUS + sdlbutton = 1; + break; + case 0x14c: // BTN_STYLUS2 + sdlbutton = 2; + break; + case 0x149: // BTN_STYLUS3 + sdlbutton = 3; + break; + default: + return; // don't care about this button, I guess. + } + + SDL_assert((sdlbutton >= 1) && (sdlbutton <= SDL_arraysize(sdltool->frame_buttons))); + sdltool->frame_buttons[sdlbutton-1] = (state == ZWP_TABLET_PAD_V2_BUTTON_STATE_PRESSED) ? 1 : 0; +} + +static void tablet_tool_handle_rotation(void *data, struct zwp_tablet_tool_v2 *tool, wl_fixed_t degrees) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + const float rotation = (float)(wl_fixed_to_double(degrees)); + sdltool->frame_axes[SDL_PEN_AXIS_ROTATION] = (rotation > 180.0f) ? (rotation - 360.0f) : rotation; // map to -180.0f ... 179.0f range + sdltool->frame_axes_set |= (1u << SDL_PEN_AXIS_ROTATION); +} + +static void tablet_tool_handle_slider(void *data, struct zwp_tablet_tool_v2 *tool, int32_t position) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + sdltool->frame_axes[SDL_PEN_AXIS_SLIDER] = position / 65535.f; + sdltool->frame_axes_set |= (1u << SDL_PEN_AXIS_SLIDER); +} + +static void tablet_tool_handle_wheel(void *data, struct zwp_tablet_tool_v2 *tool, int32_t degrees, int32_t clicks) +{ + // not supported at the moment +} + +static void tablet_tool_handle_frame(void *data, struct zwp_tablet_tool_v2 *tool, uint32_t time) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) data; + + if (!sdltool->instance_id) { + return; // Not a pen we report on. + } + + const Uint64 timestamp = Wayland_GetEventTimestamp(SDL_MS_TO_NS(time)); + const SDL_PenID instance_id = sdltool->instance_id; + SDL_Window *window = sdltool->tool_focus; + + // I don't know if this is necessary (or makes sense), but send motion before pen downs, but after pen ups, so you don't get unexpected lines drawn. + if (sdltool->frame_motion_set && (sdltool->frame_pen_down != -1)) { + if (sdltool->frame_pen_down) { + SDL_SendPenMotion(timestamp, instance_id, window, sdltool->x, sdltool->y); + SDL_SendPenTouch(timestamp, instance_id, window, false, true); // !!! FIXME: how do we know what tip is in use? + } else { + SDL_SendPenTouch(timestamp, instance_id, window, false, false); // !!! FIXME: how do we know what tip is in use? + SDL_SendPenMotion(timestamp, instance_id, window, sdltool->x, sdltool->y); + } + } else { + if (sdltool->frame_pen_down != -1) { + SDL_SendPenTouch(timestamp, instance_id, window, false, (sdltool->frame_pen_down != 0)); // !!! FIXME: how do we know what tip is in use? + } + + if (sdltool->frame_motion_set) { + SDL_SendPenMotion(timestamp, instance_id, window, sdltool->x, sdltool->y); + } + } + + for (SDL_PenAxis i = 0; i < SDL_PEN_AXIS_COUNT; i++) { + if (sdltool->frame_axes_set & (1u << i)) { + SDL_SendPenAxis(timestamp, instance_id, window, i, sdltool->frame_axes[i]); + } + } + + for (int i = 0; i < SDL_arraysize(sdltool->frame_buttons); i++) { + const int state = sdltool->frame_buttons[i]; + if (state != -1) { + SDL_SendPenButton(timestamp, instance_id, window, (Uint8)(i + 1), (state != 0)); + sdltool->frame_buttons[i] = -1; + } + } + + // reset for next frame. + sdltool->frame_pen_down = -1; + sdltool->frame_motion_set = false; + sdltool->frame_axes_set = 0; +} + +static const struct zwp_tablet_tool_v2_listener tablet_tool_listener = { + tablet_tool_handle_type, + tablet_tool_handle_hardware_serial, + tablet_tool_handle_hardware_id_wacom, + tablet_tool_handle_capability, + tablet_tool_handle_done, + tablet_tool_handle_removed, + tablet_tool_handle_proximity_in, + tablet_tool_handle_proximity_out, + tablet_tool_handle_down, + tablet_tool_handle_up, + tablet_tool_handle_motion, + tablet_tool_handle_pressure, + tablet_tool_handle_distance, + tablet_tool_handle_tilt, + tablet_tool_handle_rotation, + tablet_tool_handle_slider, + tablet_tool_handle_wheel, + tablet_tool_handle_button, + tablet_tool_handle_frame +}; + + +static void tablet_seat_handle_tablet_added(void *data, struct zwp_tablet_seat_v2 *seat, struct zwp_tablet_v2 *tablet) +{ + // don't care atm. +} + +static void tablet_seat_handle_tool_added(void *data, struct zwp_tablet_seat_v2 *seat, struct zwp_tablet_tool_v2 *tool) +{ + SDL_WaylandPenTool *sdltool = SDL_calloc(1, sizeof(*sdltool)); + + if (sdltool) { // if allocation failed, oh well, we won't report this device. + sdltool->wltool = tool; + sdltool->info.max_tilt = -1.0f; + sdltool->info.num_buttons = -1; + sdltool->frame_pen_down = -1; + for (int i = 0; i < SDL_arraysize(sdltool->frame_buttons); i++) { + sdltool->frame_buttons[i] = -1; + } + + // this will send a bunch of zwp_tablet_tool_v2 events right up front to tell + // us device details, with a "done" event to let us know we have everything. + zwp_tablet_tool_v2_add_listener(tool, &tablet_tool_listener, sdltool); + } +} + +static void tablet_seat_handle_pad_added(void *data, struct zwp_tablet_seat_v2 *seat, struct zwp_tablet_pad_v2 *pad) +{ + // we don't care atm. +} + +static const struct zwp_tablet_seat_v2_listener tablet_seat_listener = { + tablet_seat_handle_tablet_added, + tablet_seat_handle_tool_added, + tablet_seat_handle_pad_added +}; + +void Wayland_input_init_tablet_support(struct SDL_WaylandInput *input, struct zwp_tablet_manager_v2 *tablet_manager) +{ + if (!tablet_manager || !input->seat) { + return; + } + + SDL_WaylandTabletInput *tablet_input = SDL_calloc(1, sizeof(*tablet_input)); + if (!tablet_input) { + return; + } + + tablet_input->input = input; + tablet_input->seat = zwp_tablet_manager_v2_get_tablet_seat(tablet_manager, input->seat); + + zwp_tablet_seat_v2_add_listener(tablet_input->seat, &tablet_seat_listener, tablet_input); + + input->tablet_input = tablet_input; +} + +static void Wayland_remove_all_pens_callback(SDL_PenID instance_id, void *handle, void *userdata) +{ + SDL_WaylandPenTool *sdltool = (SDL_WaylandPenTool *) handle; + zwp_tablet_tool_v2_destroy(sdltool->wltool); + SDL_free(sdltool); +} + +void Wayland_input_quit_tablet_support(struct SDL_WaylandInput *input) +{ + SDL_RemoveAllPenDevices(Wayland_remove_all_pens_callback, NULL); + + if (input && input->tablet_input) { + zwp_tablet_seat_v2_destroy(input->tablet_input->seat); + SDL_free(input->tablet_input); + input->tablet_input = NULL; + } +} + +void Wayland_input_initialize_seat(SDL_VideoData *d) +{ + struct SDL_WaylandInput *input = d->input; + + WAYLAND_wl_list_init(&touch_points); + + if (d->data_device_manager) { + Wayland_create_data_device(d); + } + if (d->primary_selection_device_manager) { + Wayland_create_primary_selection_device(d); + } + if (d->text_input_manager) { + Wayland_create_text_input(d); + } + + wl_seat_add_listener(input->seat, &seat_listener, input); + wl_seat_set_user_data(input->seat, input); + + if (d->tablet_manager) { + Wayland_input_init_tablet_support(d->input, d->tablet_manager); + } + + WAYLAND_wl_display_flush(d->display); +} + +void Wayland_display_destroy_input(SDL_VideoData *d) +{ + struct SDL_WaylandInput *input = d->input; + + if (input->keyboard_timestamps) { + zwp_input_timestamps_v1_destroy(input->keyboard_timestamps); + } + if (input->pointer_timestamps) { + zwp_input_timestamps_v1_destroy(input->pointer_timestamps); + } + if (input->touch_timestamps) { + zwp_input_timestamps_v1_destroy(input->touch_timestamps); + } + + if (input->data_device) { + Wayland_data_device_clear_selection(input->data_device); + if (input->data_device->selection_offer) { + Wayland_data_offer_destroy(input->data_device->selection_offer); + } + if (input->data_device->drag_offer) { + Wayland_data_offer_destroy(input->data_device->drag_offer); + } + if (input->data_device->data_device) { + if (wl_data_device_get_version(input->data_device->data_device) >= WL_DATA_DEVICE_RELEASE_SINCE_VERSION) { + wl_data_device_release(input->data_device->data_device); + } else { + wl_data_device_destroy(input->data_device->data_device); + } + } + SDL_free(input->data_device); + } + + if (input->primary_selection_device) { + if (input->primary_selection_device->selection_offer) { + Wayland_primary_selection_offer_destroy(input->primary_selection_device->selection_offer); + } + if (input->primary_selection_device->selection_source) { + Wayland_primary_selection_source_destroy(input->primary_selection_device->selection_source); + } + if (input->primary_selection_device->primary_selection_device) { + zwp_primary_selection_device_v1_destroy(input->primary_selection_device->primary_selection_device); + } + SDL_free(input->primary_selection_device); + } + + if (input->text_input) { + zwp_text_input_v3_destroy(input->text_input->text_input); + SDL_free(input->text_input); + } + + if (input->keyboard) { + if (wl_keyboard_get_version(input->keyboard) >= WL_KEYBOARD_RELEASE_SINCE_VERSION) { + wl_keyboard_release(input->keyboard); + } else { + wl_keyboard_destroy(input->keyboard); + } + } + + if (input->relative_pointer) { + zwp_relative_pointer_v1_destroy(input->relative_pointer); + } + + if (input->cursor_shape) { + wp_cursor_shape_device_v1_destroy(input->cursor_shape); + } + + if (input->pointer) { + if (wl_pointer_get_version(input->pointer) >= WL_POINTER_RELEASE_SINCE_VERSION) { + wl_pointer_release(input->pointer); + } else { + wl_pointer_destroy(input->pointer); + } + } + + if (input->touch) { + struct SDL_WaylandTouchPoint *tp, *tmp; + + SDL_DelTouch(1); + if (wl_touch_get_version(input->touch) >= WL_TOUCH_RELEASE_SINCE_VERSION) { + wl_touch_release(input->touch); + } else { + wl_touch_destroy(input->touch); + } + + wl_list_for_each_safe (tp, tmp, &touch_points, link) { + WAYLAND_wl_list_remove(&tp->link); + SDL_free(tp); + } + } + + if (input->tablet_input) { + Wayland_input_quit_tablet_support(input); + } + + if (input->seat) { + if (wl_seat_get_version(input->seat) >= WL_SEAT_RELEASE_SINCE_VERSION) { + wl_seat_release(input->seat); + } else { + wl_seat_destroy(input->seat); + } + } + + if (input->xkb.compose_state) { + WAYLAND_xkb_compose_state_unref(input->xkb.compose_state); + } + + if (input->xkb.compose_table) { + WAYLAND_xkb_compose_table_unref(input->xkb.compose_table); + } + + if (input->xkb.state) { + WAYLAND_xkb_state_unref(input->xkb.state); + } + + if (input->xkb.keymap) { + WAYLAND_xkb_keymap_unref(input->xkb.keymap); + } + + SDL_free(input); + d->input = NULL; +} + +bool Wayland_input_enable_relative_pointer(struct SDL_WaylandInput *input) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *d = input->display; + SDL_Window *window; + + if (!d->relative_pointer_manager) { + return false; + } + + if (!d->pointer_constraints) { + return false; + } + + if (!input->pointer) { + return false; + } + + /* If we have a pointer confine active, we must destroy it here because + * creating a locked pointer otherwise would be a protocol error. + */ + for (window = vd->windows; window; window = window->next) { + pointer_confine_destroy(window); + } + + for (window = vd->windows; window; window = window->next) { + Wayland_input_lock_pointer(input, window); + } + + d->relative_mouse_mode = 1; + + return true; +} + +bool Wayland_input_disable_relative_pointer(struct SDL_WaylandInput *input) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *d = input->display; + SDL_Window *window; + + for (window = vd->windows; window; window = window->next) { + Wayland_input_unlock_pointer(input, window); + } + + d->relative_mouse_mode = 0; + + for (window = vd->windows; window; window = window->next) { + Wayland_input_confine_pointer(input, window); + } + + return true; +} + +bool Wayland_input_confine_pointer(struct SDL_WaylandInput *input, SDL_Window *window) +{ + SDL_WindowData *w = window->internal; + SDL_VideoData *d = input->display; + struct wl_region *confine_rect; + + if (!d->pointer_constraints) { + return SDL_SetError("Failed to confine pointer: compositor lacks support for the required zwp_pointer_constraints_v1 protocol"); + } + + if (!input->pointer) { + return SDL_SetError("No pointer to confine"); + } + + /* A confine may already be active, in which case we should destroy it and + * create a new one. + */ + pointer_confine_destroy(window); + + /* We cannot create a confine if the pointer is already locked. Defer until + * the pointer is unlocked. + */ + if (d->relative_mouse_mode) { + return true; + } + + // Don't confine the pointer if it shouldn't be confined. + if (SDL_RectEmpty(&window->mouse_rect) && !(window->flags & SDL_WINDOW_MOUSE_GRABBED)) { + return true; + } + + if (SDL_RectEmpty(&window->mouse_rect)) { + confine_rect = NULL; + } else { + SDL_Rect scaled_mouse_rect; + + scaled_mouse_rect.x = (int)SDL_floor(window->mouse_rect.x / w->pointer_scale.x); + scaled_mouse_rect.y = (int)SDL_floor(window->mouse_rect.y / w->pointer_scale.y); + scaled_mouse_rect.w = (int)SDL_ceil(window->mouse_rect.w / w->pointer_scale.x); + scaled_mouse_rect.h = (int)SDL_ceil(window->mouse_rect.h / w->pointer_scale.y); + + confine_rect = wl_compositor_create_region(d->compositor); + wl_region_add(confine_rect, + scaled_mouse_rect.x, + scaled_mouse_rect.y, + scaled_mouse_rect.w, + scaled_mouse_rect.h); + } + + struct zwp_confined_pointer_v1 *confined_pointer = + zwp_pointer_constraints_v1_confine_pointer(d->pointer_constraints, + w->surface, + input->pointer, + confine_rect, + ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT); + zwp_confined_pointer_v1_add_listener(confined_pointer, + &confined_pointer_listener, + window); + + if (confine_rect) { + wl_region_destroy(confine_rect); + } + + w->confined_pointer = confined_pointer; + return true; +} + +bool Wayland_input_unconfine_pointer(struct SDL_WaylandInput *input, SDL_Window *window) +{ + pointer_confine_destroy(window); + return true; +} + +bool Wayland_input_grab_keyboard(SDL_Window *window, struct SDL_WaylandInput *input) +{ + SDL_WindowData *w = window->internal; + SDL_VideoData *d = input->display; + + if (!d->key_inhibitor_manager) { + return SDL_SetError("Failed to grab keyboard: compositor lacks support for the required zwp_keyboard_shortcuts_inhibit_manager_v1 protocol"); + } + + if (w->key_inhibitor) { + return true; + } + + w->key_inhibitor = + zwp_keyboard_shortcuts_inhibit_manager_v1_inhibit_shortcuts(d->key_inhibitor_manager, + w->surface, + input->seat); + + return true; +} + +bool Wayland_input_ungrab_keyboard(SDL_Window *window) +{ + SDL_WindowData *w = window->internal; + + if (w->key_inhibitor) { + zwp_keyboard_shortcuts_inhibitor_v1_destroy(w->key_inhibitor); + w->key_inhibitor = NULL; + } + + return true; +} + +void Wayland_UpdateImplicitGrabSerial(struct SDL_WaylandInput *input, Uint32 serial) +{ + if (serial > input->last_implicit_grab_serial) { + input->last_implicit_grab_serial = serial; + Wayland_data_device_set_serial(input->data_device, serial); + Wayland_primary_selection_device_set_serial(input->primary_selection_device, serial); + } +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandevents_c.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandevents_c.h new file mode 100644 index 0000000..6158882 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandevents_c.h @@ -0,0 +1,195 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_waylandevents_h_ +#define SDL_waylandevents_h_ + +#include "../../events/SDL_mouse_c.h" +#include "../../events/SDL_pen_c.h" + +#include "SDL_waylandvideo.h" +#include "SDL_waylandwindow.h" +#include "SDL_waylanddatamanager.h" +#include "SDL_waylandkeyboard.h" + +enum SDL_WaylandAxisEvent +{ + AXIS_EVENT_CONTINUOUS = 0, + AXIS_EVENT_DISCRETE, + AXIS_EVENT_VALUE120 +}; + +struct SDL_WaylandTabletSeat; + +typedef struct SDL_WaylandTabletInput +{ + struct SDL_WaylandInput *input; + struct zwp_tablet_seat_v2 *seat; +} SDL_WaylandTabletInput; + +typedef struct +{ + int32_t repeat_rate; // Repeat rate in range of [1, 1000] character(s) per second + int32_t repeat_delay_ms; // Time to first repeat event in milliseconds + Uint32 keyboard_id; // ID of the source keyboard. + bool is_initialized; + + bool is_key_down; + uint32_t key; + Uint64 wl_press_time_ns; // Key press time as reported by the Wayland API + Uint64 sdl_press_time_ns; // Key press time expressed in SDL ticks + Uint64 next_repeat_ns; // Next repeat event in nanoseconds + uint32_t scancode; + char text[8]; +} SDL_WaylandKeyboardRepeat; + +struct SDL_WaylandInput +{ + SDL_VideoData *display; + struct wl_seat *seat; + struct wl_pointer *pointer; + struct wl_touch *touch; + struct wl_keyboard *keyboard; + SDL_WaylandDataDevice *data_device; + SDL_WaylandPrimarySelectionDevice *primary_selection_device; + SDL_WaylandTextInput *text_input; + struct wp_cursor_shape_device_v1 *cursor_shape; + struct zwp_relative_pointer_v1 *relative_pointer; + struct zwp_input_timestamps_v1 *keyboard_timestamps; + struct zwp_input_timestamps_v1 *pointer_timestamps; + struct zwp_input_timestamps_v1 *touch_timestamps; + SDL_WindowData *pointer_focus; + SDL_WindowData *keyboard_focus; + SDL_CursorData *current_cursor; + SDL_KeyboardID keyboard_id; + SDL_MouseID pointer_id; + uint32_t pointer_enter_serial; + + // High-resolution event timestamps + Uint64 keyboard_timestamp_ns; + Uint64 pointer_timestamp_ns; + Uint64 touch_timestamp_ns; + + // Last motion location + wl_fixed_t sx_w; + wl_fixed_t sy_w; + + SDL_MouseButtonFlags buttons_pressed; + + // The serial of the last implicit grab event for window activation and selection data. + Uint32 last_implicit_grab_serial; + + struct + { + struct xkb_keymap *keymap; + struct xkb_state *state; + struct xkb_compose_table *compose_table; + struct xkb_compose_state *compose_state; + + // Keyboard layout "group" + uint32_t current_group; + + // Modifier bitshift values + uint32_t idx_shift; + uint32_t idx_ctrl; + uint32_t idx_alt; + uint32_t idx_gui; + uint32_t idx_mod3; + uint32_t idx_mod5; + uint32_t idx_num; + uint32_t idx_caps; + + // Current system modifier flags + uint32_t wl_pressed_modifiers; + uint32_t wl_locked_modifiers; + } xkb; + + // information about axis events on current frame + struct + { + enum SDL_WaylandAxisEvent x_axis_type; + float x; + + enum SDL_WaylandAxisEvent y_axis_type; + float y; + + // Event timestamp in nanoseconds + Uint64 timestamp_ns; + SDL_MouseWheelDirection direction; + } pointer_curr_axis_info; + + SDL_WaylandKeyboardRepeat keyboard_repeat; + + SDL_WaylandTabletInput *tablet_input; + + bool keyboard_is_virtual; + + // Current SDL modifier flags + SDL_Keymod pressed_modifiers; + SDL_Keymod locked_modifiers; +}; + + +extern Uint64 Wayland_GetTouchTimestamp(struct SDL_WaylandInput *input, Uint32 wl_timestamp_ms); + +extern void Wayland_PumpEvents(SDL_VideoDevice *_this); +extern void Wayland_SendWakeupEvent(SDL_VideoDevice *_this, SDL_Window *window); +extern int Wayland_WaitEventTimeout(SDL_VideoDevice *_this, Sint64 timeoutNS); + +extern void Wayland_create_data_device(SDL_VideoData *d); +extern void Wayland_create_primary_selection_device(SDL_VideoData *d); + +extern void Wayland_create_text_input_manager(SDL_VideoData *d, uint32_t id); + +extern void Wayland_input_initialize_seat(SDL_VideoData *d); +extern void Wayland_display_destroy_input(SDL_VideoData *d); + +extern void Wayland_input_init_relative_pointer(SDL_VideoData *d); +extern bool Wayland_input_enable_relative_pointer(struct SDL_WaylandInput *input); +extern bool Wayland_input_disable_relative_pointer(struct SDL_WaylandInput *input); + +extern bool Wayland_input_lock_pointer(struct SDL_WaylandInput *input, SDL_Window *window); +extern bool Wayland_input_unlock_pointer(struct SDL_WaylandInput *input, SDL_Window *window); + +extern bool Wayland_input_confine_pointer(struct SDL_WaylandInput *input, SDL_Window *window); +extern bool Wayland_input_unconfine_pointer(struct SDL_WaylandInput *input, SDL_Window *window); + +extern bool Wayland_input_grab_keyboard(SDL_Window *window, struct SDL_WaylandInput *input); +extern bool Wayland_input_ungrab_keyboard(SDL_Window *window); + +extern void Wayland_input_init_tablet_support(struct SDL_WaylandInput *input, struct zwp_tablet_manager_v2 *tablet_manager); +extern void Wayland_input_quit_tablet_support(struct SDL_WaylandInput *input); + +extern void Wayland_RegisterTimestampListeners(struct SDL_WaylandInput *input); +extern void Wayland_CreateCursorShapeDevice(struct SDL_WaylandInput *input); + +/* The implicit grab serial needs to be updated on: + * - Keyboard key down/up + * - Mouse button down + * - Touch event down + * - Tablet tool down + * - Tablet tool button down/up + */ +extern void Wayland_UpdateImplicitGrabSerial(struct SDL_WaylandInput *input, Uint32 serial); + +#endif // SDL_waylandevents_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandkeyboard.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandkeyboard.c new file mode 100644 index 0000000..df1628c --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandkeyboard.c @@ -0,0 +1,209 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if SDL_VIDEO_DRIVER_WAYLAND + +#include "../SDL_sysvideo.h" +#include "SDL_waylandvideo.h" +#include "SDL_waylandevents_c.h" +#include "../../events/SDL_keyboard_c.h" +#include "text-input-unstable-v3-client-protocol.h" + +bool Wayland_InitKeyboard(SDL_VideoDevice *_this) +{ +#ifdef SDL_USE_IME + SDL_VideoData *internal = _this->internal; + if (!internal->text_input_manager) { + SDL_IME_Init(); + } +#endif + SDL_SetScancodeName(SDL_SCANCODE_APPLICATION, "Menu"); + + return true; +} + +void Wayland_QuitKeyboard(SDL_VideoDevice *_this) +{ +#ifdef SDL_USE_IME + SDL_VideoData *internal = _this->internal; + if (!internal->text_input_manager) { + SDL_IME_Quit(); + } +#endif +} + +bool Wayland_StartTextInput(SDL_VideoDevice *_this, SDL_Window *window, SDL_PropertiesID props) +{ + SDL_VideoData *internal = _this->internal; + struct SDL_WaylandInput *input = internal->input; + + if (internal->text_input_manager) { + if (input && input->text_input) { + const SDL_Rect *rect = &input->text_input->cursor_rect; + enum zwp_text_input_v3_content_hint hint = ZWP_TEXT_INPUT_V3_CONTENT_HINT_NONE; + enum zwp_text_input_v3_content_purpose purpose; + + switch (SDL_GetTextInputType(props)) { + default: + case SDL_TEXTINPUT_TYPE_TEXT: + purpose = ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_NORMAL; + break; + case SDL_TEXTINPUT_TYPE_TEXT_NAME: + purpose = ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_NAME; + break; + case SDL_TEXTINPUT_TYPE_TEXT_EMAIL: + purpose = ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_EMAIL; + break; + case SDL_TEXTINPUT_TYPE_TEXT_USERNAME: + purpose = ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_NORMAL; + hint |= ZWP_TEXT_INPUT_V3_CONTENT_HINT_SENSITIVE_DATA; + break; + case SDL_TEXTINPUT_TYPE_TEXT_PASSWORD_HIDDEN: + purpose = ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_PASSWORD; + hint |= (ZWP_TEXT_INPUT_V3_CONTENT_HINT_HIDDEN_TEXT | ZWP_TEXT_INPUT_V3_CONTENT_HINT_SENSITIVE_DATA); + break; + case SDL_TEXTINPUT_TYPE_TEXT_PASSWORD_VISIBLE: + purpose = ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_PASSWORD; + hint |= ZWP_TEXT_INPUT_V3_CONTENT_HINT_SENSITIVE_DATA; + break; + case SDL_TEXTINPUT_TYPE_NUMBER: + purpose = ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_NUMBER; + break; + case SDL_TEXTINPUT_TYPE_NUMBER_PASSWORD_HIDDEN: + purpose = ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_PIN; + hint |= (ZWP_TEXT_INPUT_V3_CONTENT_HINT_HIDDEN_TEXT | ZWP_TEXT_INPUT_V3_CONTENT_HINT_SENSITIVE_DATA); + break; + case SDL_TEXTINPUT_TYPE_NUMBER_PASSWORD_VISIBLE: + purpose = ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_PIN; + hint |= ZWP_TEXT_INPUT_V3_CONTENT_HINT_SENSITIVE_DATA; + break; + } + + switch (SDL_GetTextInputCapitalization(props)) { + default: + case SDL_CAPITALIZE_NONE: + break; + case SDL_CAPITALIZE_LETTERS: + hint |= ZWP_TEXT_INPUT_V3_CONTENT_HINT_UPPERCASE; + break; + case SDL_CAPITALIZE_WORDS: + hint |= ZWP_TEXT_INPUT_V3_CONTENT_HINT_TITLECASE; + break; + case SDL_CAPITALIZE_SENTENCES: + hint |= ZWP_TEXT_INPUT_V3_CONTENT_HINT_AUTO_CAPITALIZATION; + break; + } + + if (SDL_GetTextInputAutocorrect(props)) { + hint |= (ZWP_TEXT_INPUT_V3_CONTENT_HINT_COMPLETION | ZWP_TEXT_INPUT_V3_CONTENT_HINT_SPELLCHECK); + } + if (SDL_GetTextInputMultiline(props)) { + hint |= ZWP_TEXT_INPUT_V3_CONTENT_HINT_MULTILINE; + } + + zwp_text_input_v3_enable(input->text_input->text_input); + + // Now that it's enabled, set the input properties + zwp_text_input_v3_set_content_type(input->text_input->text_input, hint, purpose); + if (!SDL_RectEmpty(rect)) { + // This gets reset on enable so we have to cache it + zwp_text_input_v3_set_cursor_rectangle(input->text_input->text_input, + rect->x, + rect->y, + rect->w, + rect->h); + } + zwp_text_input_v3_commit(input->text_input->text_input); + } + } + + if (input && input->xkb.compose_state) { + // Reset compose state so composite and dead keys don't carry over + WAYLAND_xkb_compose_state_reset(input->xkb.compose_state); + } + + return Wayland_UpdateTextInputArea(_this, window); +} + +bool Wayland_StopTextInput(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_VideoData *internal = _this->internal; + struct SDL_WaylandInput *input = internal->input; + + if (internal->text_input_manager) { + if (input && input->text_input) { + zwp_text_input_v3_disable(input->text_input->text_input); + zwp_text_input_v3_commit(input->text_input->text_input); + } + } +#ifdef SDL_USE_IME + else { + SDL_IME_Reset(); + } +#endif + + if (input && input->xkb.compose_state) { + // Reset compose state so composite and dead keys don't carry over + WAYLAND_xkb_compose_state_reset(input->xkb.compose_state); + } + return true; +} + +bool Wayland_UpdateTextInputArea(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_VideoData *internal = _this->internal; + if (internal->text_input_manager) { + struct SDL_WaylandInput *input = internal->input; + if (input && input->text_input) { + if (!SDL_RectsEqual(&window->text_input_rect, &input->text_input->cursor_rect)) { + SDL_copyp(&input->text_input->cursor_rect, &window->text_input_rect); + zwp_text_input_v3_set_cursor_rectangle(input->text_input->text_input, + window->text_input_rect.x, + window->text_input_rect.y, + window->text_input_rect.w, + window->text_input_rect.h); + zwp_text_input_v3_commit(input->text_input->text_input); + } + } + } + +#ifdef SDL_USE_IME + else { + SDL_IME_UpdateTextInputArea(window); + } +#endif + return true; +} + +bool Wayland_HasScreenKeyboardSupport(SDL_VideoDevice *_this) +{ + /* In reality we just want to return true when the screen keyboard is the + * _only_ way to get text input. So, in addition to checking for the text + * input protocol, make sure we don't have any physical keyboards either. + */ + SDL_VideoData *internal = _this->internal; + bool haskeyboard = (internal->input != NULL) && (internal->input->keyboard != NULL); + bool hastextmanager = (internal->text_input_manager != NULL); + return !haskeyboard && hastextmanager; +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandkeyboard.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandkeyboard.h new file mode 100644 index 0000000..f570edb --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandkeyboard.h @@ -0,0 +1,40 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_waylandkeyboard_h_ +#define SDL_waylandkeyboard_h_ + +typedef struct SDL_WaylandTextInput +{ + struct zwp_text_input_v3 *text_input; + SDL_Rect cursor_rect; + bool has_preedit; +} SDL_WaylandTextInput; + +extern bool Wayland_InitKeyboard(SDL_VideoDevice *_this); +extern void Wayland_QuitKeyboard(SDL_VideoDevice *_this); +extern bool Wayland_StartTextInput(SDL_VideoDevice *_this, SDL_Window *window, SDL_PropertiesID props); +extern bool Wayland_StopTextInput(SDL_VideoDevice *_this, SDL_Window *window); +extern bool Wayland_UpdateTextInputArea(SDL_VideoDevice *_this, SDL_Window *window); +extern bool Wayland_HasScreenKeyboardSupport(SDL_VideoDevice *_this); + +#endif // SDL_waylandkeyboard_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmessagebox.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmessagebox.c new file mode 100644 index 0000000..3d6f1f8 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmessagebox.c @@ -0,0 +1,196 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#include "SDL_waylandmessagebox.h" + +#define ZENITY_VERSION_LEN 32 // Number of bytes to read from zenity --version (including NUL) + +#define MAX_BUTTONS 8 // Maximum number of buttons supported + +static bool parse_zenity_version(const char *version, int *major, int *minor) +{ + /* We expect the version string is in the form of MAJOR.MINOR.MICRO + * as described in meson.build. We'll ignore everything after that. + */ + const char *version_ptr = version; + char *end_ptr = NULL; + int tmp = (int) SDL_strtol(version_ptr, &end_ptr, 10); + if (tmp == 0 && end_ptr == version_ptr) { + return SDL_SetError("failed to get zenity major version number"); + } + *major = tmp; + + if (*end_ptr == '.') { + version_ptr = end_ptr + 1; // skip the dot + tmp = (int) SDL_strtol(version_ptr, &end_ptr, 10); + if (tmp == 0 && end_ptr == version_ptr) { + return SDL_SetError("failed to get zenity minor version number"); + } + *minor = tmp; + } else { + *minor = 0; + } + return true; +} + +static bool get_zenity_version(int *major, int *minor) +{ + const char *argv[] = { "zenity", "--version", NULL }; + bool result = false; + + SDL_Process *process = SDL_CreateProcess(argv, true); + if (!process) { + return false; + } + + char *output = SDL_ReadProcess(process, NULL, NULL); + if (output) { + result = parse_zenity_version(output, major, minor); + SDL_free(output); + } + SDL_DestroyProcess(process); + + return result; +} + +bool Wayland_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonID) +{ + int zenity_major = 0, zenity_minor = 0, output_len = 0; + int argc = 5, i; + const char *argv[5 + 2 /* icon name */ + 2 /* title */ + 2 /* message */ + 2 * MAX_BUTTONS + 1 /* NULL */] = { + "zenity", "--question", "--switch", "--no-wrap", "--no-markup" + }; + SDL_Process *process; + + // Are we trying to connect to or are currently in a Wayland session? + if (!SDL_getenv("WAYLAND_DISPLAY")) { + const char *session = SDL_getenv("XDG_SESSION_TYPE"); + if (session && SDL_strcasecmp(session, "wayland") != 0) { + return SDL_SetError("Not on a wayland display"); + } + } + + if (messageboxdata->numbuttons > MAX_BUTTONS) { + return SDL_SetError("Too many buttons (%d max allowed)", MAX_BUTTONS); + } + + // get zenity version so we know which arg to use + if (!get_zenity_version(&zenity_major, &zenity_minor)) { + return false; // get_zenity_version() calls SDL_SetError(), so message is already set + } + + /* https://gitlab.gnome.org/GNOME/zenity/-/commit/c686bdb1b45e95acf010efd9ca0c75527fbb4dea + * This commit removed --icon-name without adding a deprecation notice. + * We need to handle it gracefully, otherwise no message box will be shown. + */ + argv[argc++] = zenity_major > 3 || (zenity_major == 3 && zenity_minor >= 90) ? "--icon" : "--icon-name"; + switch (messageboxdata->flags & (SDL_MESSAGEBOX_ERROR | SDL_MESSAGEBOX_WARNING | SDL_MESSAGEBOX_INFORMATION)) { + case SDL_MESSAGEBOX_ERROR: + argv[argc++] = "dialog-error"; + break; + case SDL_MESSAGEBOX_WARNING: + argv[argc++] = "dialog-warning"; + break; + case SDL_MESSAGEBOX_INFORMATION: + default: + argv[argc++] = "dialog-information"; + break; + } + + if (messageboxdata->title && messageboxdata->title[0]) { + argv[argc++] = "--title"; + argv[argc++] = messageboxdata->title; + } else { + argv[argc++] = "--title="; + } + + if (messageboxdata->message && messageboxdata->message[0]) { + argv[argc++] = "--text"; + argv[argc++] = messageboxdata->message; + } else { + argv[argc++] = "--text="; + } + + for (i = 0; i < messageboxdata->numbuttons; ++i) { + if (messageboxdata->buttons[i].text && messageboxdata->buttons[i].text[0]) { + int len = SDL_strlen(messageboxdata->buttons[i].text); + if (len > output_len) { + output_len = len; + } + + argv[argc++] = "--extra-button"; + argv[argc++] = messageboxdata->buttons[i].text; + } else { + argv[argc++] = "--extra-button="; + } + } + if (messageboxdata->numbuttons == 0) { + argv[argc++] = "--extra-button=OK"; + } + argv[argc] = NULL; + + SDL_PropertiesID props = SDL_CreateProperties(); + if (!props) { + return false; + } + SDL_SetPointerProperty(props, SDL_PROP_PROCESS_CREATE_ARGS_POINTER, argv); + // If buttonID is set we need to wait and read the results + if (buttonID) { + SDL_SetNumberProperty(props, SDL_PROP_PROCESS_CREATE_STDOUT_NUMBER, SDL_PROCESS_STDIO_APP); + } else { + SDL_SetNumberProperty(props, SDL_PROP_PROCESS_CREATE_STDOUT_NUMBER, SDL_PROCESS_STDIO_NULL); + } + process = SDL_CreateProcessWithProperties(props); + SDL_DestroyProperties(props); + if (!process) { + return false; + } + if (buttonID) { + char *output = SDL_ReadProcess(process, NULL, NULL); + if (output) { + // It likes to add a newline... + char *tmp = SDL_strrchr(output, '\n'); + if (tmp) { + *tmp = '\0'; + } + + // Check which button got pressed + for (i = 0; i < messageboxdata->numbuttons; i += 1) { + if (messageboxdata->buttons[i].text) { + if (SDL_strcmp(output, messageboxdata->buttons[i].text) == 0) { + *buttonID = messageboxdata->buttons[i].buttonID; + break; + } + } + } + SDL_free(output); + } + } + SDL_DestroyProcess(process); + + return true; +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmessagebox.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmessagebox.h new file mode 100644 index 0000000..af3012f --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmessagebox.h @@ -0,0 +1,31 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_waylandmessagebox_h_ +#define SDL_waylandmessagebox_h_ + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +extern bool Wayland_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonID); + +#endif // SDL_VIDEO_DRIVER_WAYLAND + +#endif // SDL_waylandmessagebox_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmouse.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmouse.c new file mode 100644 index 0000000..8075c3a --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmouse.c @@ -0,0 +1,1057 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#include "../SDL_sysvideo.h" +#include "../SDL_video_c.h" + +#include "../../events/SDL_mouse_c.h" +#include "SDL_waylandvideo.h" +#include "../SDL_pixels_c.h" +#include "SDL_waylandevents_c.h" + +#include "wayland-cursor.h" +#include "SDL_waylandmouse.h" +#include "SDL_waylandshmbuffer.h" + +#include "cursor-shape-v1-client-protocol.h" +#include "pointer-constraints-unstable-v1-client-protocol.h" +#include "viewporter-client-protocol.h" + +#include "../../SDL_hints_c.h" + +static SDL_Cursor *sys_cursors[SDL_HITTEST_RESIZE_LEFT + 1]; + +static bool Wayland_SetRelativeMouseMode(bool enabled); + +typedef struct +{ + struct Wayland_SHMBuffer shmBuffer; + double scale; + struct wl_list node; +} Wayland_ScaledCustomCursor; + +typedef struct +{ + SDL_Surface *sdl_cursor_surface; + int hot_x; + int hot_y; + struct wl_list scaled_cursor_cache; +} Wayland_CustomCursor; + +typedef struct +{ + struct wl_buffer *wl_buffer; + Uint32 duration; +} Wayland_SystemCursorFrame; + +typedef struct +{ + Wayland_SystemCursorFrame *frames; + struct wl_callback *frame_callback; + Uint64 last_frame_callback_time_ms; + Uint64 current_frame_time_ms; + Uint32 total_duration; + int num_frames; + int current_frame; + SDL_SystemCursor id; +} Wayland_SystemCursor; + +struct SDL_CursorData +{ + union + { + Wayland_CustomCursor custom; + Wayland_SystemCursor system; + } cursor_data; + + struct wl_surface *surface; + struct wp_viewport *viewport; + + bool is_system_cursor; +}; + +static int dbus_cursor_size; +static char *dbus_cursor_theme; + +static void Wayland_FreeCursorThemes(SDL_VideoData *vdata) +{ + for (int i = 0; i < vdata->num_cursor_themes; i += 1) { + WAYLAND_wl_cursor_theme_destroy(vdata->cursor_themes[i].theme); + } + vdata->num_cursor_themes = 0; + SDL_free(vdata->cursor_themes); + vdata->cursor_themes = NULL; +} + +#ifdef SDL_USE_LIBDBUS + +#include "../../core/linux/SDL_dbus.h" + +#define CURSOR_NODE "org.freedesktop.portal.Desktop" +#define CURSOR_PATH "/org/freedesktop/portal/desktop" +#define CURSOR_INTERFACE "org.freedesktop.portal.Settings" +#define CURSOR_NAMESPACE "org.gnome.desktop.interface" +#define CURSOR_SIGNAL_NAME "SettingChanged" +#define CURSOR_SIZE_KEY "cursor-size" +#define CURSOR_THEME_KEY "cursor-theme" + +static DBusMessage *Wayland_ReadDBusProperty(SDL_DBusContext *dbus, const char *key) +{ + static const char *iface = "org.gnome.desktop.interface"; + + DBusMessage *reply = NULL; + DBusMessage *msg = dbus->message_new_method_call(CURSOR_NODE, + CURSOR_PATH, + CURSOR_INTERFACE, + "Read"); // Method + + if (msg) { + if (dbus->message_append_args(msg, DBUS_TYPE_STRING, &iface, DBUS_TYPE_STRING, &key, DBUS_TYPE_INVALID)) { + reply = dbus->connection_send_with_reply_and_block(dbus->session_conn, msg, DBUS_TIMEOUT_USE_DEFAULT, NULL); + } + dbus->message_unref(msg); + } + + return reply; +} + +static bool Wayland_ParseDBusReply(SDL_DBusContext *dbus, DBusMessage *reply, int type, void *value) +{ + DBusMessageIter iter[3]; + + dbus->message_iter_init(reply, &iter[0]); + if (dbus->message_iter_get_arg_type(&iter[0]) != DBUS_TYPE_VARIANT) { + return false; + } + + dbus->message_iter_recurse(&iter[0], &iter[1]); + if (dbus->message_iter_get_arg_type(&iter[1]) != DBUS_TYPE_VARIANT) { + return false; + } + + dbus->message_iter_recurse(&iter[1], &iter[2]); + if (dbus->message_iter_get_arg_type(&iter[2]) != type) { + return false; + } + + dbus->message_iter_get_basic(&iter[2], value); + + return true; +} + +static DBusHandlerResult Wayland_DBusCursorMessageFilter(DBusConnection *conn, DBusMessage *msg, void *data) +{ + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + SDL_VideoData *vdata = (SDL_VideoData *)data; + + if (dbus->message_is_signal(msg, CURSOR_INTERFACE, CURSOR_SIGNAL_NAME)) { + DBusMessageIter signal_iter, variant_iter; + const char *namespace, *key; + + dbus->message_iter_init(msg, &signal_iter); + // Check if the parameters are what we expect + if (dbus->message_iter_get_arg_type(&signal_iter) != DBUS_TYPE_STRING) { + goto not_our_signal; + } + dbus->message_iter_get_basic(&signal_iter, &namespace); + if (SDL_strcmp(CURSOR_NAMESPACE, namespace) != 0) { + goto not_our_signal; + } + if (!dbus->message_iter_next(&signal_iter)) { + goto not_our_signal; + } + if (dbus->message_iter_get_arg_type(&signal_iter) != DBUS_TYPE_STRING) { + goto not_our_signal; + } + dbus->message_iter_get_basic(&signal_iter, &key); + if (SDL_strcmp(CURSOR_SIZE_KEY, key) == 0) { + int new_cursor_size; + + if (!dbus->message_iter_next(&signal_iter)) { + goto not_our_signal; + } + if (dbus->message_iter_get_arg_type(&signal_iter) != DBUS_TYPE_VARIANT) { + goto not_our_signal; + } + dbus->message_iter_recurse(&signal_iter, &variant_iter); + if (dbus->message_iter_get_arg_type(&variant_iter) != DBUS_TYPE_INT32) { + goto not_our_signal; + } + dbus->message_iter_get_basic(&variant_iter, &new_cursor_size); + + if (dbus_cursor_size != new_cursor_size) { + dbus_cursor_size = new_cursor_size; + SDL_SetCursor(NULL); // Force cursor update + } + } else if (SDL_strcmp(CURSOR_THEME_KEY, key) == 0) { + const char *new_cursor_theme = NULL; + + if (!dbus->message_iter_next(&signal_iter)) { + goto not_our_signal; + } + if (dbus->message_iter_get_arg_type(&signal_iter) != DBUS_TYPE_VARIANT) { + goto not_our_signal; + } + dbus->message_iter_recurse(&signal_iter, &variant_iter); + if (dbus->message_iter_get_arg_type(&variant_iter) != DBUS_TYPE_STRING) { + goto not_our_signal; + } + dbus->message_iter_get_basic(&variant_iter, &new_cursor_theme); + + if (!dbus_cursor_theme || !new_cursor_theme || SDL_strcmp(dbus_cursor_theme, new_cursor_theme) != 0) { + SDL_free(dbus_cursor_theme); + if (new_cursor_theme) { + dbus_cursor_theme = SDL_strdup(new_cursor_theme); + } else { + dbus_cursor_theme = NULL; + } + + // Purge the current cached themes and force a cursor refresh. + Wayland_FreeCursorThemes(vdata); + SDL_SetCursor(NULL); + } + } else { + goto not_our_signal; + } + + return DBUS_HANDLER_RESULT_HANDLED; + } + +not_our_signal: + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +static void Wayland_DBusInitCursorProperties(SDL_VideoData *vdata) +{ + DBusMessage *reply; + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + bool add_filter = false; + + if (!dbus) { + return; + } + + if ((reply = Wayland_ReadDBusProperty(dbus, CURSOR_SIZE_KEY))) { + if (Wayland_ParseDBusReply(dbus, reply, DBUS_TYPE_INT32, &dbus_cursor_size)) { + add_filter = true; + } + dbus->message_unref(reply); + } + + if ((reply = Wayland_ReadDBusProperty(dbus, CURSOR_THEME_KEY))) { + const char *temp = NULL; + if (Wayland_ParseDBusReply(dbus, reply, DBUS_TYPE_STRING, &temp)) { + add_filter = true; + + if (temp) { + dbus_cursor_theme = SDL_strdup(temp); + } + } + dbus->message_unref(reply); + } + + // Only add the filter if at least one of the settings we want is present. + if (add_filter) { + dbus->bus_add_match(dbus->session_conn, + "type='signal', interface='" CURSOR_INTERFACE "'," + "member='" CURSOR_SIGNAL_NAME "', arg0='" CURSOR_NAMESPACE "'", + NULL); + dbus->connection_add_filter(dbus->session_conn, &Wayland_DBusCursorMessageFilter, vdata, NULL); + dbus->connection_flush(dbus->session_conn); + } +} + +static void Wayland_DBusFinishCursorProperties(void) +{ + SDL_free(dbus_cursor_theme); + dbus_cursor_theme = NULL; +} + +#endif + +static void cursor_frame_done(void *data, struct wl_callback *cb, uint32_t time); +struct wl_callback_listener cursor_frame_listener = { + cursor_frame_done +}; + +static void cursor_frame_done(void *data, struct wl_callback *cb, uint32_t time) +{ + SDL_CursorData *c = (SDL_CursorData *)data; + + const Uint64 now = SDL_GetTicks(); + const Uint64 elapsed = (now - c->cursor_data.system.last_frame_callback_time_ms) % c->cursor_data.system.total_duration; + Uint64 advance = 0; + int next = c->cursor_data.system.current_frame; + + wl_callback_destroy(cb); + c->cursor_data.system.frame_callback = wl_surface_frame(c->surface); + wl_callback_add_listener(c->cursor_data.system.frame_callback, &cursor_frame_listener, data); + + c->cursor_data.system.current_frame_time_ms += elapsed; + + // Calculate the next frame based on the elapsed duration. + for (Uint64 t = c->cursor_data.system.frames[next].duration; t <= c->cursor_data.system.current_frame_time_ms; t += c->cursor_data.system.frames[next].duration) { + next = (next + 1) % c->cursor_data.system.num_frames; + advance = t; + + // Make sure we don't end up in an infinite loop if a cursor has frame durations of 0. + if (!c->cursor_data.system.frames[next].duration) { + break; + } + } + + c->cursor_data.system.current_frame_time_ms -= advance; + c->cursor_data.system.last_frame_callback_time_ms = now; + c->cursor_data.system.current_frame = next; + wl_surface_attach(c->surface, c->cursor_data.system.frames[next].wl_buffer, 0, 0); + if (wl_surface_get_version(c->surface) >= WL_SURFACE_DAMAGE_BUFFER_SINCE_VERSION) { + wl_surface_damage_buffer(c->surface, 0, 0, SDL_MAX_SINT32, SDL_MAX_SINT32); + } else { + wl_surface_damage(c->surface, 0, 0, SDL_MAX_SINT32, SDL_MAX_SINT32); + } + wl_surface_commit(c->surface); +} + +static bool Wayland_GetSystemCursor(SDL_VideoData *vdata, SDL_CursorData *cdata, int *scale, int *dst_size, int *hot_x, int *hot_y) +{ + struct wl_cursor_theme *theme = NULL; + struct wl_cursor *cursor; + const char *css_name = "default"; + const char *fallback_name = NULL; + double scale_factor = 1.0; + int theme_size = dbus_cursor_size; + + // Fallback envvar if the DBus properties don't exist + if (theme_size <= 0) { + const char *xcursor_size = SDL_getenv("XCURSOR_SIZE"); + if (xcursor_size) { + theme_size = SDL_atoi(xcursor_size); + } + } + if (theme_size <= 0) { + theme_size = 24; + } + // First, find the appropriate theme based on the current scale... + SDL_Window *focus = SDL_GetMouse()->focus; + if (focus) { + // TODO: Use the fractional scale once GNOME supports viewports on cursor surfaces. + scale_factor = SDL_ceil(focus->internal->scale_factor); + } + + const int scaled_size = (int)SDL_lround(theme_size * scale_factor); + for (int i = 0; i < vdata->num_cursor_themes; ++i) { + if (vdata->cursor_themes[i].size == scaled_size) { + theme = vdata->cursor_themes[i].theme; + break; + } + } + if (!theme) { + const char *xcursor_theme = dbus_cursor_theme; + + SDL_WaylandCursorTheme *new_cursor_themes = SDL_realloc(vdata->cursor_themes, + sizeof(SDL_WaylandCursorTheme) * (vdata->num_cursor_themes + 1)); + if (!new_cursor_themes) { + return false; + } + vdata->cursor_themes = new_cursor_themes; + + // Fallback envvar if the DBus properties don't exist + if (!xcursor_theme) { + xcursor_theme = SDL_getenv("XCURSOR_THEME"); + } + + theme = WAYLAND_wl_cursor_theme_load(xcursor_theme, scaled_size, vdata->shm); + vdata->cursor_themes[vdata->num_cursor_themes].size = scaled_size; + vdata->cursor_themes[vdata->num_cursor_themes++].theme = theme; + } + + css_name = SDL_GetCSSCursorName(cdata->cursor_data.system.id, &fallback_name); + cursor = WAYLAND_wl_cursor_theme_get_cursor(theme, css_name); + if (!cursor && fallback_name) { + cursor = WAYLAND_wl_cursor_theme_get_cursor(theme, fallback_name); + } + + // Fallback to the default cursor if the chosen one wasn't found + if (!cursor) { + cursor = WAYLAND_wl_cursor_theme_get_cursor(theme, "default"); + } + // Try the old X11 name as a last resort + if (!cursor) { + cursor = WAYLAND_wl_cursor_theme_get_cursor(theme, "left_ptr"); + } + if (!cursor) { + return false; + } + + if (cdata->cursor_data.system.num_frames != cursor->image_count) { + SDL_free(cdata->cursor_data.system.frames); + cdata->cursor_data.system.frames = SDL_calloc(cursor->image_count, sizeof(Wayland_SystemCursorFrame)); + if (!cdata->cursor_data.system.frames) { + return false; + } + } + + // ... Set the cursor data, finally. + cdata->cursor_data.system.num_frames = cursor->image_count; + cdata->cursor_data.system.total_duration = 0; + for (int i = 0; i < cursor->image_count; ++i) { + cdata->cursor_data.system.frames[i].wl_buffer = WAYLAND_wl_cursor_image_get_buffer(cursor->images[i]); + cdata->cursor_data.system.frames[i].duration = cursor->images[i]->delay; + cdata->cursor_data.system.total_duration += cursor->images[i]->delay; + } + + *scale = SDL_ceil(scale_factor) == scale_factor ? (int)scale_factor : 0; + + if (scaled_size != cursor->images[0]->width) { + /* If the cursor size isn't an exact match for the target size, use a viewport + * to avoid a possible "Buffer size is not divisible by scale" protocol error. + * + * If viewports are unavailable, find an integer scale that works. + */ + if (vdata->viewporter) { + // A scale of 0 indicates that a viewport set to the destination size should be used. + *scale = 0; + } else { + for (; *scale > 1; --*scale) { + if (cursor->images[0]->width % *scale == 0) { + break; + } + } + // Set the scale factor to the new value for the hotspot calculations. + scale_factor = *scale; + } + } + + *dst_size = (int)SDL_lround(cursor->images[0]->width / scale_factor); + + *hot_x = (int)SDL_lround(cursor->images[0]->hotspot_x / scale_factor); + *hot_y = (int)SDL_lround(cursor->images[0]->hotspot_y / scale_factor); + + return true; +} + +static Wayland_ScaledCustomCursor *Wayland_CacheScaledCustomCursor(SDL_CursorData *cdata, double scale) +{ + Wayland_ScaledCustomCursor *cache = NULL; + + // Is this cursor already cached at the target scale? + if (!WAYLAND_wl_list_empty(&cdata->cursor_data.custom.scaled_cursor_cache)) { + Wayland_ScaledCustomCursor *c = NULL; + wl_list_for_each (c, &cdata->cursor_data.custom.scaled_cursor_cache, node) { + if (c->scale == scale) { + cache = c; + break; + } + } + } + + if (!cache) { + cache = SDL_calloc(1, sizeof(Wayland_ScaledCustomCursor)); + if (!cache) { + return NULL; + } + + SDL_Surface *surface = SDL_GetSurfaceImage(cdata->cursor_data.custom.sdl_cursor_surface, (float)scale); + if (!surface) { + SDL_free(cache); + return NULL; + } + + // Allocate the shared memory buffer for this cursor. + if (!Wayland_AllocSHMBuffer(surface->w, surface->h, &cache->shmBuffer)) { + SDL_free(cache); + SDL_DestroySurface(surface); + return NULL; + } + + // Wayland requires premultiplied alpha for its surfaces. + SDL_PremultiplyAlpha(surface->w, surface->h, + surface->format, surface->pixels, surface->pitch, + SDL_PIXELFORMAT_ARGB8888, cache->shmBuffer.shm_data, surface->w * 4, true); + + cache->scale = scale; + WAYLAND_wl_list_insert(&cdata->cursor_data.custom.scaled_cursor_cache, &cache->node); + SDL_DestroySurface(surface); + } + + return cache; +} + +static bool Wayland_GetCustomCursor(SDL_Cursor *cursor, struct wl_buffer **buffer, int *scale, int *dst_width, int *dst_height, int *hot_x, int *hot_y) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *wd = vd->internal; + SDL_CursorData *data = cursor->internal; + SDL_Window *focus = SDL_GetMouseFocus(); + double scale_factor = 1.0; + + if (focus && SDL_SurfaceHasAlternateImages(data->cursor_data.custom.sdl_cursor_surface)) { + scale_factor = focus->internal->scale_factor; + } + + // Only use fractional scale values if viewports are available. + if (!wd->viewporter) { + scale_factor = SDL_ceil(scale_factor); + } + + Wayland_ScaledCustomCursor *c = Wayland_CacheScaledCustomCursor(data, scale_factor); + if (!c) { + return false; + } + + *buffer = c->shmBuffer.wl_buffer; + *scale = SDL_ceil(scale_factor) == scale_factor ? (int)scale_factor : 0; + *dst_width = data->cursor_data.custom.sdl_cursor_surface->w; + *dst_height = data->cursor_data.custom.sdl_cursor_surface->h; + *hot_x = data->cursor_data.custom.hot_x; + *hot_y = data->cursor_data.custom.hot_y; + + return true; +} + +static SDL_Cursor *Wayland_CreateCursor(SDL_Surface *surface, int hot_x, int hot_y) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *wd = vd->internal; + + SDL_Cursor *cursor = SDL_calloc(1, sizeof(*cursor)); + if (cursor) { + SDL_CursorData *data = SDL_calloc(1, sizeof(*data)); + if (!data) { + SDL_free(cursor); + return NULL; + } + cursor->internal = data; + WAYLAND_wl_list_init(&data->cursor_data.custom.scaled_cursor_cache); + data->cursor_data.custom.hot_x = hot_x; + data->cursor_data.custom.hot_y = hot_y; + data->surface = wl_compositor_create_surface(wd->compositor); + + data->cursor_data.custom.sdl_cursor_surface = surface; + ++surface->refcount; + + // If the cursor has only one size, just prepare it now. + if (!SDL_SurfaceHasAlternateImages(surface)) { + Wayland_CacheScaledCustomCursor(data, 1.0); + } + } + + return cursor; +} + +static SDL_Cursor *Wayland_CreateSystemCursor(SDL_SystemCursor id) +{ + SDL_VideoData *data = SDL_GetVideoDevice()->internal; + SDL_Cursor *cursor = SDL_calloc(1, sizeof(*cursor)); + if (cursor) { + SDL_CursorData *cdata = SDL_calloc(1, sizeof(*cdata)); + if (!cdata) { + SDL_free(cursor); + return NULL; + } + cursor->internal = cdata; + + /* The surface is only necessary if the cursor shape manager is not present. + * + * Note that we can't actually set any other cursor properties, as this + * is window-specific. See Wayland_GetSystemCursor for the rest! + */ + if (!data->cursor_shape_manager) { + cdata->surface = wl_compositor_create_surface(data->compositor); + wl_surface_set_user_data(cdata->surface, NULL); + } + + cdata->cursor_data.system.id = id; + cdata->is_system_cursor = true; + } + + return cursor; +} + +static SDL_Cursor *Wayland_CreateDefaultCursor(void) +{ + SDL_SystemCursor id = SDL_GetDefaultSystemCursor(); + return Wayland_CreateSystemCursor(id); +} + +static void Wayland_FreeCursorData(SDL_CursorData *d) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + struct SDL_WaylandInput *input = vd->internal->input; + + if (input->current_cursor == d) { + input->current_cursor = NULL; + } + + // Buffers for system cursors must not be destroyed. + if (d->is_system_cursor) { + if (d->cursor_data.system.frame_callback) { + wl_callback_destroy(d->cursor_data.system.frame_callback); + } + SDL_free(d->cursor_data.system.frames); + } else { + Wayland_ScaledCustomCursor *c, *temp; + wl_list_for_each_safe(c, temp, &d->cursor_data.custom.scaled_cursor_cache, node) { + Wayland_ReleaseSHMBuffer(&c->shmBuffer); + SDL_free(c); + } + + SDL_DestroySurface(d->cursor_data.custom.sdl_cursor_surface); + } + + if (d->viewport) { + wp_viewport_destroy(d->viewport); + d->viewport = NULL; + } + + if (d->surface) { + wl_surface_destroy(d->surface); + d->surface = NULL; + } +} + +static void Wayland_FreeCursor(SDL_Cursor *cursor) +{ + if (!cursor) { + return; + } + + // Probably not a cursor we own + if (!cursor->internal) { + return; + } + + Wayland_FreeCursorData(cursor->internal); + + SDL_free(cursor->internal); + SDL_free(cursor); +} + +static void Wayland_SetSystemCursorShape(struct SDL_WaylandInput *input, SDL_SystemCursor id) +{ + Uint32 shape; + + switch (id) { + case SDL_SYSTEM_CURSOR_DEFAULT: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT; + break; + case SDL_SYSTEM_CURSOR_TEXT: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT; + break; + case SDL_SYSTEM_CURSOR_WAIT: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_WAIT; + break; + case SDL_SYSTEM_CURSOR_CROSSHAIR: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR; + break; + case SDL_SYSTEM_CURSOR_PROGRESS: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_PROGRESS; + break; + case SDL_SYSTEM_CURSOR_NWSE_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE; + break; + case SDL_SYSTEM_CURSOR_NESW_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE; + break; + case SDL_SYSTEM_CURSOR_EW_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE; + break; + case SDL_SYSTEM_CURSOR_NS_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE; + break; + case SDL_SYSTEM_CURSOR_MOVE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_SCROLL; + break; + case SDL_SYSTEM_CURSOR_NOT_ALLOWED: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED; + break; + case SDL_SYSTEM_CURSOR_POINTER: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER; + break; + case SDL_SYSTEM_CURSOR_NW_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NW_RESIZE; + break; + case SDL_SYSTEM_CURSOR_N_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_N_RESIZE; + break; + case SDL_SYSTEM_CURSOR_NE_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NE_RESIZE; + break; + case SDL_SYSTEM_CURSOR_E_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_E_RESIZE; + break; + case SDL_SYSTEM_CURSOR_SE_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SE_RESIZE; + break; + case SDL_SYSTEM_CURSOR_S_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_S_RESIZE; + break; + case SDL_SYSTEM_CURSOR_SW_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SW_RESIZE; + break; + case SDL_SYSTEM_CURSOR_W_RESIZE: + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_W_RESIZE; + break; + default: + SDL_assert(0); // Should never be here... + shape = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT; + } + + wp_cursor_shape_device_v1_set_shape(input->cursor_shape, input->pointer_enter_serial, shape); +} + +static bool Wayland_ShowCursor(SDL_Cursor *cursor) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *d = vd->internal; + struct SDL_WaylandInput *input = d->input; + struct wl_pointer *pointer = d->pointer; + struct wl_buffer *buffer = NULL; + int scale = 1; + int dst_width = 0; + int dst_height = 0; + int hot_x; + int hot_y; + + if (!pointer) { + return false; + } + + // Stop the frame callback for old animated cursors. + if (input->current_cursor && input->current_cursor->is_system_cursor && + input->current_cursor->cursor_data.system.frame_callback) { + wl_callback_destroy(input->current_cursor->cursor_data.system.frame_callback); + input->current_cursor->cursor_data.system.frame_callback = NULL; + } + + if (cursor) { + SDL_CursorData *data = cursor->internal; + + if (data->is_system_cursor) { + // If the cursor shape protocol is supported, the compositor will draw nicely scaled cursors for us, so nothing more to do. + if (input->cursor_shape) { + Wayland_SetSystemCursorShape(input, data->cursor_data.system.id); + input->current_cursor = data; + return true; + } + + if (!Wayland_GetSystemCursor(d, data, &scale, &dst_width, &hot_x, &hot_y)) { + return false; + } + + dst_height = dst_width; + wl_surface_attach(data->surface, data->cursor_data.system.frames[0].wl_buffer, 0, 0); + + // If more than one frame is available, create a frame callback to run the animation. + if (data->cursor_data.system.num_frames > 1) { + data->cursor_data.system.last_frame_callback_time_ms = SDL_GetTicks(); + data->cursor_data.system.current_frame_time_ms = 0; + data->cursor_data.system.current_frame = 0; + data->cursor_data.system.frame_callback = wl_surface_frame(data->surface); + wl_callback_add_listener(data->cursor_data.system.frame_callback, &cursor_frame_listener, data); + } + } else { + if (!Wayland_GetCustomCursor(cursor, &buffer, &scale, &dst_width, &dst_height, &hot_x, &hot_y)) { + return false; + } + + wl_surface_attach(data->surface, buffer, 0, 0); + } + + // A scale value of 0 indicates that a viewport with the returned destination size should be used. + if (!scale) { + if (!data->viewport) { + data->viewport = wp_viewporter_get_viewport(d->viewporter, data->surface); + } + wl_surface_set_buffer_scale(data->surface, 1); + wp_viewport_set_source(data->viewport, wl_fixed_from_int(-1), wl_fixed_from_int(-1), wl_fixed_from_int(-1), wl_fixed_from_int(-1)); + wp_viewport_set_destination(data->viewport, dst_width, dst_height); + } else { + if (data->viewport) { + wp_viewport_destroy(data->viewport); + data->viewport = NULL; + } + wl_surface_set_buffer_scale(data->surface, scale); + } + + wl_pointer_set_cursor(pointer, input->pointer_enter_serial, data->surface, hot_x, hot_y); + + if (wl_surface_get_version(data->surface) >= WL_SURFACE_DAMAGE_BUFFER_SINCE_VERSION) { + wl_surface_damage_buffer(data->surface, 0, 0, SDL_MAX_SINT32, SDL_MAX_SINT32); + } else { + wl_surface_damage(data->surface, 0, 0, SDL_MAX_SINT32, SDL_MAX_SINT32); + } + + wl_surface_commit(data->surface); + input->current_cursor = data; + } else { + input->current_cursor = NULL; + wl_pointer_set_cursor(pointer, input->pointer_enter_serial, NULL, 0, 0); + } + + return true; +} + +static bool Wayland_WarpMouse(SDL_Window *window, float x, float y) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *d = vd->internal; + SDL_WindowData *wind = window->internal; + struct SDL_WaylandInput *input = d->input; + + if (d->pointer_constraints) { + const bool toggle_lock = !wind->locked_pointer; + + /* The pointer confinement protocol allows setting a hint to warp the pointer, + * but only when the pointer is locked. + * + * Lock the pointer, set the position hint, unlock, and hope for the best. + */ + if (toggle_lock) { + Wayland_input_lock_pointer(input, window); + } + if (wind->locked_pointer) { + const wl_fixed_t f_x = wl_fixed_from_double(x / wind->pointer_scale.x); + const wl_fixed_t f_y = wl_fixed_from_double(y / wind->pointer_scale.y); + zwp_locked_pointer_v1_set_cursor_position_hint(wind->locked_pointer, f_x, f_y); + wl_surface_commit(wind->surface); + } + if (toggle_lock) { + Wayland_input_unlock_pointer(input, window); + } + + /* NOTE: There is a pending warp event under discussion that should replace this when available. + * https://gitlab.freedesktop.org/wayland/wayland/-/merge_requests/340 + */ + SDL_SendMouseMotion(0, window, SDL_GLOBAL_MOUSE_ID, false, x, y); + } else { + return SDL_SetError("wayland: mouse warp failed; compositor lacks support for the required zwp_pointer_confinement_v1 protocol"); + } + + return true; +} + +static bool Wayland_WarpMouseGlobal(float x, float y) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *d = vd->internal; + struct SDL_WaylandInput *input = d->input; + SDL_WindowData *wind = input->pointer_focus; + + // If the client wants the coordinates warped to within the focused window, just convert the coordinates to relative. + if (wind) { + SDL_Window *window = wind->sdlwindow; + return Wayland_WarpMouse(window, x - (float)window->x, y - (float)window->y); + } + + return SDL_SetError("wayland: can't warp the mouse when a window does not have focus"); +} + +static bool Wayland_SetRelativeMouseMode(bool enabled) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *data = vd->internal; + + if (enabled) { + return Wayland_input_enable_relative_pointer(data->input); + } else { + return Wayland_input_disable_relative_pointer(data->input); + } +} + +/* Wayland doesn't support getting the true global cursor position, but it can + * be faked well enough for what most applications use it for: querying the + * global cursor coordinates and transforming them to the window-relative + * coordinates manually. + * + * The global position is derived by taking the cursor position relative to the + * toplevel window, and offsetting it by the origin of the output the window is + * currently considered to be on. The cursor position and button state when the + * cursor is outside an application window are unknown, but this gives 'correct' + * coordinates when the window has focus, which is good enough for most + * applications. + */ +static SDL_MouseButtonFlags SDLCALL Wayland_GetGlobalMouseState(float *x, float *y) +{ + SDL_Window *focus = SDL_GetMouseFocus(); + SDL_MouseButtonFlags result = 0; + + if (focus) { + SDL_VideoData *viddata = SDL_GetVideoDevice()->internal; + int off_x, off_y; + + result = viddata->input->buttons_pressed; + SDL_RelativeToGlobalForWindow(focus, focus->x, focus->y, &off_x, &off_y); + *x += off_x; + *y += off_y; + } + + return result; +} + +#if 0 // TODO RECONNECT: See waylandvideo.c for more information! +static void Wayland_RecreateCursor(SDL_Cursor *cursor, SDL_VideoData *vdata) +{ + SDL_CursorData *cdata = cursor->internal; + + // Probably not a cursor we own + if (cdata == NULL) { + return; + } + + Wayland_FreeCursorData(cdata); + + // We're not currently freeing this, so... yolo? + if (cdata->shm_data != NULL) { + void *old_data_pointer = cdata->shm_data; + int stride = cdata->w * 4; + + create_buffer_from_shm(cdata, cdata->w, cdata->h, WL_SHM_FORMAT_ARGB8888); + + SDL_memcpy(cdata->shm_data, old_data_pointer, stride * cdata->h); + } + cdata->surface = wl_compositor_create_surface(vdata->compositor); + wl_surface_set_user_data(cdata->surface, NULL); +} + +void Wayland_RecreateCursors(void) +{ + SDL_Cursor *cursor; + SDL_Mouse *mouse = SDL_GetMouse(); + SDL_VideoData *vdata = SDL_GetVideoDevice()->internal; + + if (vdata && vdata->cursor_themes) { + SDL_free(vdata->cursor_themes); + vdata->cursor_themes = NULL; + vdata->num_cursor_themes = 0; + } + + if (mouse == NULL) { + return; + } + + for (cursor = mouse->cursors; cursor != NULL; cursor = cursor->next) { + Wayland_RecreateCursor(cursor, vdata); + } + if (mouse->def_cursor) { + Wayland_RecreateCursor(mouse->def_cursor, vdata); + } + if (mouse->cur_cursor) { + Wayland_RecreateCursor(mouse->cur_cursor, vdata); + if (mouse->cursor_shown) { + Wayland_ShowCursor(mouse->cur_cursor); + } + } +} +#endif // 0 + +void Wayland_InitMouse(void) +{ + SDL_Mouse *mouse = SDL_GetMouse(); + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *d = vd->internal; + + mouse->CreateCursor = Wayland_CreateCursor; + mouse->CreateSystemCursor = Wayland_CreateSystemCursor; + mouse->ShowCursor = Wayland_ShowCursor; + mouse->FreeCursor = Wayland_FreeCursor; + mouse->WarpMouse = Wayland_WarpMouse; + mouse->WarpMouseGlobal = Wayland_WarpMouseGlobal; + mouse->SetRelativeMouseMode = Wayland_SetRelativeMouseMode; + mouse->GetGlobalMouseState = Wayland_GetGlobalMouseState; + + SDL_HitTestResult r = SDL_HITTEST_NORMAL; + while (r <= SDL_HITTEST_RESIZE_LEFT) { + switch (r) { + case SDL_HITTEST_NORMAL: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT); + break; + case SDL_HITTEST_DRAGGABLE: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT); + break; + case SDL_HITTEST_RESIZE_TOPLEFT: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_NW_RESIZE); + break; + case SDL_HITTEST_RESIZE_TOP: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_N_RESIZE); + break; + case SDL_HITTEST_RESIZE_TOPRIGHT: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_NE_RESIZE); + break; + case SDL_HITTEST_RESIZE_RIGHT: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_E_RESIZE); + break; + case SDL_HITTEST_RESIZE_BOTTOMRIGHT: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_SE_RESIZE); + break; + case SDL_HITTEST_RESIZE_BOTTOM: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_S_RESIZE); + break; + case SDL_HITTEST_RESIZE_BOTTOMLEFT: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_SW_RESIZE); + break; + case SDL_HITTEST_RESIZE_LEFT: + sys_cursors[r] = Wayland_CreateSystemCursor(SDL_SYSTEM_CURSOR_W_RESIZE); + break; + } + r++; + } + +#ifdef SDL_USE_LIBDBUS + /* The DBus cursor properties are only needed when manually loading themes and cursors. + * If the cursor shape protocol is present, the compositor will handle it internally. + */ + if (!d->cursor_shape_manager) { + Wayland_DBusInitCursorProperties(d); + } +#endif + + SDL_SetDefaultCursor(Wayland_CreateDefaultCursor()); +} + +void Wayland_FiniMouse(SDL_VideoData *data) +{ + Wayland_FreeCursorThemes(data); + +#ifdef SDL_USE_LIBDBUS + Wayland_DBusFinishCursorProperties(); +#endif + + for (int i = 0; i < SDL_arraysize(sys_cursors); i++) { + Wayland_FreeCursor(sys_cursors[i]); + sys_cursors[i] = NULL; + } +} + +void Wayland_SetHitTestCursor(SDL_HitTestResult rc) +{ + if (rc == SDL_HITTEST_NORMAL || rc == SDL_HITTEST_DRAGGABLE) { + SDL_SetCursor(NULL); + } else { + Wayland_ShowCursor(sys_cursors[rc]); + } +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmouse.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmouse.h new file mode 100644 index 0000000..58188c0 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandmouse.h @@ -0,0 +1,34 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_waylandmouse_h_ +#define SDL_waylandmouse_h_ + +extern void Wayland_InitMouse(void); +extern void Wayland_FiniMouse(SDL_VideoData *data); +extern void Wayland_SetHitTestCursor(SDL_HitTestResult rc); +#if 0 // TODO RECONNECT: See waylandvideo.c for more information! +extern void Wayland_RecreateCursors(void); +#endif // 0 + +#endif diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandopengles.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandopengles.c new file mode 100644 index 0000000..ac2b06d --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandopengles.c @@ -0,0 +1,220 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#if defined(SDL_VIDEO_DRIVER_WAYLAND) && defined(SDL_VIDEO_OPENGL_EGL) + +#include "../../core/unix/SDL_poll.h" +#include "../SDL_sysvideo.h" +#include "../../events/SDL_windowevents_c.h" +#include "SDL_waylandvideo.h" +#include "SDL_waylandopengles.h" +#include "SDL_waylandwindow.h" +#include "SDL_waylandevents_c.h" + +#include "xdg-shell-client-protocol.h" + +// EGL implementation of SDL OpenGL ES support + +bool Wayland_GLES_LoadLibrary(SDL_VideoDevice *_this, const char *path) +{ + bool result; + SDL_VideoData *data = _this->internal; + + result = SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType)data->display, _this->gl_config.egl_platform); + + Wayland_PumpEvents(_this); + WAYLAND_wl_display_flush(data->display); + + return result; +} + +SDL_GLContext Wayland_GLES_CreateContext(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_GLContext context; + context = SDL_EGL_CreateContext(_this, window->internal->egl_surface); + WAYLAND_wl_display_flush(_this->internal->display); + + return context; +} + +/* Wayland wants to tell you when to provide new frames, and if you have a non-zero + swap interval, Mesa will block until a callback tells it to do so. On some + compositors, they might decide that a minimized window _never_ gets a callback, + which causes apps to hang during swapping forever. So we always set the official + eglSwapInterval to zero to avoid blocking inside EGL, and manage this ourselves. + If a swap blocks for too long waiting on a callback, we just go on, under the + assumption the frame will be wasted, but this is better than freezing the app. + I frown upon platforms that dictate this sort of control inversion (the callback + is intended for _rendering_, not stalling until vsync), but we can work around + this for now. --ryan. */ +/* Addendum: several recent APIs demand this sort of control inversion: Emscripten, + libretro, Wayland, probably others...it feels like we're eventually going to have + to give in with a future SDL API revision, since we can bend the other APIs to + this style, but this style is much harder to bend the other way. :/ */ +bool Wayland_GLES_SetSwapInterval(SDL_VideoDevice *_this, int interval) +{ + if (!_this->egl_data) { + return SDL_SetError("EGL not initialized"); + } + + /* technically, this is _all_ adaptive vsync (-1), because we can't + actually wait for the _next_ vsync if you set 1, but things that + request 1 probably won't care _that_ much. I hope. No matter what + you do, though, you never see tearing on Wayland. */ + if (interval > 1) { + interval = 1; + } else if (interval < -1) { + interval = -1; + } + + // !!! FIXME: technically, this should be per-context, right? + _this->egl_data->egl_swapinterval = interval; + _this->egl_data->eglSwapInterval(_this->egl_data->egl_display, 0); + return true; +} + +bool Wayland_GLES_GetSwapInterval(SDL_VideoDevice *_this, int *interval) +{ + if (!_this->egl_data) { + return SDL_SetError("EGL not initialized"); + } + + *interval =_this->egl_data->egl_swapinterval; + return true; +} + +bool Wayland_GLES_SwapWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *data = window->internal; + const int swap_interval = _this->egl_data->egl_swapinterval; + + /* For windows that we know are hidden, skip swaps entirely, if we don't do + * this compositors will intentionally stall us indefinitely and there's no + * way for an end user to show the window, unlike other situations (i.e. + * the window is minimized, behind another window, etc.). + * + * FIXME: Request EGL_WAYLAND_swap_buffers_with_timeout. + * -flibit + */ + if (data->shell_surface_status != WAYLAND_SHELL_SURFACE_STATUS_SHOWN && + data->shell_surface_status != WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_FRAME) { + return true; + } + + /* By default, we wait for the Wayland frame callback and then issue the pageflip (eglSwapBuffers), + * but if we want low latency (double buffer scheme), we issue the pageflip and then wait + * immediately for the Wayland frame callback. + */ + if (data->double_buffer) { + // Feed the frame to Wayland. This will set it so the wl_surface_frame callback can fire again. + if (!_this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, data->egl_surface)) { + return SDL_EGL_SetError("unable to show color buffer in an OS-native window", "eglSwapBuffers"); + } + + WAYLAND_wl_display_flush(data->waylandData->display); + } + + // Control swap interval ourselves. See comments on Wayland_GLES_SetSwapInterval + if (swap_interval != 0 && data->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_SHOWN) { + SDL_VideoData *videodata = _this->internal; + struct wl_display *display = videodata->display; + // 20hz, so we'll progress even if throttled to zero. + const Uint64 max_wait = SDL_GetTicksNS() + (SDL_NS_PER_SECOND / 20); + while (SDL_GetAtomicInt(&data->swap_interval_ready) == 0) { + Uint64 now; + + WAYLAND_wl_display_flush(display); + + /* wl_display_prepare_read_queue() will return false if the event queue is not empty. + * If the event queue is empty, it will prepare us for our SDL_IOReady() call. */ + if (WAYLAND_wl_display_prepare_read_queue(display, data->gles_swap_frame_event_queue) != 0) { + // We have some pending events. Check if the frame callback happened. + WAYLAND_wl_display_dispatch_queue_pending(display, data->gles_swap_frame_event_queue); + continue; + } + + // Beyond this point, we must either call wl_display_cancel_read() or wl_display_read_events() + + now = SDL_GetTicksNS(); + if (now >= max_wait) { + // Timeout expired. Cancel the read. + WAYLAND_wl_display_cancel_read(display); + break; + } + + if (SDL_IOReady(WAYLAND_wl_display_get_fd(display), SDL_IOR_READ, max_wait - now) <= 0) { + // Error or timeout expired without any events for us. Cancel the read. + WAYLAND_wl_display_cancel_read(display); + break; + } + + // We have events. Read and dispatch them. + WAYLAND_wl_display_read_events(display); + WAYLAND_wl_display_dispatch_queue_pending(display, data->gles_swap_frame_event_queue); + } + SDL_SetAtomicInt(&data->swap_interval_ready, 0); + } + + if (!data->double_buffer) { + // Feed the frame to Wayland. This will set it so the wl_surface_frame callback can fire again. + if (!_this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, data->egl_surface)) { + return SDL_EGL_SetError("unable to show color buffer in an OS-native window", "eglSwapBuffers"); + } + + WAYLAND_wl_display_flush(data->waylandData->display); + } + + return true; +} + +bool Wayland_GLES_MakeCurrent(SDL_VideoDevice *_this, SDL_Window *window, SDL_GLContext context) +{ + bool result; + + if (window && context) { + result = SDL_EGL_MakeCurrent(_this, window->internal->egl_surface, context); + } else { + result = SDL_EGL_MakeCurrent(_this, NULL, NULL); + } + + WAYLAND_wl_display_flush(_this->internal->display); + + _this->egl_data->eglSwapInterval(_this->egl_data->egl_display, 0); // see comments on Wayland_GLES_SetSwapInterval. + + return result; +} + +bool Wayland_GLES_DestroyContext(SDL_VideoDevice *_this, SDL_GLContext context) +{ + bool result = SDL_EGL_DestroyContext(_this, context); + WAYLAND_wl_display_flush(_this->internal->display); + return result; +} + +EGLSurface Wayland_GLES_GetEGLSurface(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *windowdata = window->internal; + + return windowdata->egl_surface; +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND && SDL_VIDEO_OPENGL_EGL diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandopengles.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandopengles.h new file mode 100644 index 0000000..ed2e927 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandopengles.h @@ -0,0 +1,48 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_waylandopengles_h_ +#define SDL_waylandopengles_h_ + +#include "../SDL_sysvideo.h" +#include "../SDL_egl_c.h" + +typedef struct SDL_PrivateGLESData +{ + int dummy; +} SDL_PrivateGLESData; + +// OpenGLES functions +#define Wayland_GLES_GetAttribute SDL_EGL_GetAttribute +#define Wayland_GLES_GetProcAddress SDL_EGL_GetProcAddressInternal +#define Wayland_GLES_UnloadLibrary SDL_EGL_UnloadLibrary + +extern bool Wayland_GLES_LoadLibrary(SDL_VideoDevice *_this, const char *path); +extern SDL_GLContext Wayland_GLES_CreateContext(SDL_VideoDevice *_this, SDL_Window *window); +extern bool Wayland_GLES_SetSwapInterval(SDL_VideoDevice *_this, int interval); +extern bool Wayland_GLES_GetSwapInterval(SDL_VideoDevice *_this, int *interval); +extern bool Wayland_GLES_SwapWindow(SDL_VideoDevice *_this, SDL_Window *window); +extern bool Wayland_GLES_MakeCurrent(SDL_VideoDevice *_this, SDL_Window *window, SDL_GLContext context); +extern bool Wayland_GLES_DestroyContext(SDL_VideoDevice *_this, SDL_GLContext context); +extern SDL_EGLSurface Wayland_GLES_GetEGLSurface(SDL_VideoDevice *_this, SDL_Window *window); + +#endif // SDL_waylandopengles_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandshmbuffer.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandshmbuffer.c new file mode 100644 index 0000000..8fc6d9e --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandshmbuffer.c @@ -0,0 +1,170 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#include +#include +#include +#include +#include +#include + +#include "SDL_waylandshmbuffer.h" +#include "SDL_waylandvideo.h" + +static bool SetTempFileSize(int fd, off_t size) +{ +#ifdef HAVE_POSIX_FALLOCATE + sigset_t set, old_set; + int ret; + + /* SIGALRM can potentially block a large posix_fallocate() operation + * from succeeding, so block it. + */ + sigemptyset(&set); + sigaddset(&set, SIGALRM); + sigprocmask(SIG_BLOCK, &set, &old_set); + + do { + ret = posix_fallocate(fd, 0, size); + } while (ret == EINTR); + + sigprocmask(SIG_SETMASK, &old_set, NULL); + + if (ret == 0) { + return true; + } else if (ret != EINVAL && errno != EOPNOTSUPP) { + return false; + } +#endif + + if (ftruncate(fd, size) < 0) { + return false; + } + return true; +} + +static int CreateTempFD(off_t size) +{ + int fd; + +#ifdef HAVE_MEMFD_CREATE + fd = memfd_create("SDL", MFD_CLOEXEC | MFD_ALLOW_SEALING); + if (fd >= 0) { + fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_SEAL); + } else +#endif + { + static const char template[] = "/sdl-shared-XXXXXX"; + const char *xdg_path; + char tmp_path[PATH_MAX]; + + xdg_path = SDL_getenv("XDG_RUNTIME_DIR"); + if (!xdg_path) { + return -1; + } + + SDL_strlcpy(tmp_path, xdg_path, PATH_MAX); + SDL_strlcat(tmp_path, template, PATH_MAX); + + fd = mkostemp(tmp_path, O_CLOEXEC); + if (fd < 0) { + return -1; + } + + // Need to manually unlink the temp files, or they can persist after close and fill up the temp storage. + unlink(tmp_path); + } + + if (!SetTempFileSize(fd, size)) { + close(fd); + return -1; + } + + return fd; +} + +static void buffer_handle_release(void *data, struct wl_buffer *wl_buffer) +{ + // NOP +} + +static struct wl_buffer_listener buffer_listener = { + buffer_handle_release +}; + +bool Wayland_AllocSHMBuffer(int width, int height, struct Wayland_SHMBuffer *shmBuffer) +{ + SDL_VideoDevice *vd = SDL_GetVideoDevice(); + SDL_VideoData *data = vd->internal; + struct wl_shm_pool *shm_pool; + const Uint32 SHM_FMT = WL_SHM_FORMAT_ARGB8888; + + if (!shmBuffer) { + return SDL_InvalidParamError("shmBuffer"); + } + + const int stride = width * 4; + shmBuffer->shm_data_size = stride * height; + + const int shm_fd = CreateTempFD(shmBuffer->shm_data_size); + if (shm_fd < 0) { + return SDL_SetError("Creating SHM buffer failed."); + } + + shmBuffer->shm_data = mmap(NULL, shmBuffer->shm_data_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); + if (shmBuffer->shm_data == MAP_FAILED) { + shmBuffer->shm_data = NULL; + close(shm_fd); + return SDL_SetError("mmap() failed."); + } + + SDL_assert(shmBuffer->shm_data != NULL); + + shm_pool = wl_shm_create_pool(data->shm, shm_fd, shmBuffer->shm_data_size); + shmBuffer->wl_buffer = wl_shm_pool_create_buffer(shm_pool, 0, width, height, stride, SHM_FMT); + wl_buffer_add_listener(shmBuffer->wl_buffer, &buffer_listener, shmBuffer); + + wl_shm_pool_destroy(shm_pool); + close(shm_fd); + + return true; +} + +void Wayland_ReleaseSHMBuffer(struct Wayland_SHMBuffer *shmBuffer) +{ + if (shmBuffer) { + if (shmBuffer->wl_buffer) { + wl_buffer_destroy(shmBuffer->wl_buffer); + shmBuffer->wl_buffer = NULL; + } + if (shmBuffer->shm_data) { + munmap(shmBuffer->shm_data, shmBuffer->shm_data_size); + shmBuffer->shm_data = NULL; + } + shmBuffer->shm_data_size = 0; + } +} + +#endif diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandshmbuffer.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandshmbuffer.h new file mode 100644 index 0000000..f6f49a4 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandshmbuffer.h @@ -0,0 +1,38 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_waylandshmbuffer_h_ +#define SDL_waylandshmbuffer_h_ + +struct Wayland_SHMBuffer +{ + struct wl_buffer *wl_buffer; + void *shm_data; + int shm_data_size; +}; + +// Allocates an SHM buffer with the format WL_SHM_FORMAT_ARGB8888 +extern bool Wayland_AllocSHMBuffer(int width, int height, struct Wayland_SHMBuffer *shmBuffer); +extern void Wayland_ReleaseSHMBuffer(struct Wayland_SHMBuffer *shmBuffer); + +#endif diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandsym.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandsym.h new file mode 100644 index 0000000..846c876 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandsym.h @@ -0,0 +1,242 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* *INDENT-OFF* */ // clang-format off + +#ifndef SDL_WAYLAND_MODULE +#define SDL_WAYLAND_MODULE(modname) +#endif + +#ifndef SDL_WAYLAND_SYM +#define SDL_WAYLAND_SYM(rc,fn,params) +#endif + +#ifndef SDL_WAYLAND_SYM_OPT +#define SDL_WAYLAND_SYM_OPT(rc,fn,params) +#endif + +#ifndef SDL_WAYLAND_INTERFACE +#define SDL_WAYLAND_INTERFACE(iface) +#endif + +SDL_WAYLAND_MODULE(WAYLAND_CLIENT) +SDL_WAYLAND_SYM(void, wl_proxy_marshal, (struct wl_proxy *, uint32_t, ...)) +SDL_WAYLAND_SYM(struct wl_proxy *, wl_proxy_create, (struct wl_proxy *, const struct wl_interface *)) +SDL_WAYLAND_SYM(void, wl_proxy_destroy, (struct wl_proxy *)) +SDL_WAYLAND_SYM(int, wl_proxy_add_listener, (struct wl_proxy *, void (**)(void), void *)) +SDL_WAYLAND_SYM(void, wl_proxy_set_user_data, (struct wl_proxy *, void *)) +SDL_WAYLAND_SYM(void *, wl_proxy_get_user_data, (struct wl_proxy *)) +SDL_WAYLAND_SYM(uint32_t, wl_proxy_get_version, (struct wl_proxy *)) +SDL_WAYLAND_SYM(uint32_t, wl_proxy_get_id, (struct wl_proxy *)) +SDL_WAYLAND_SYM(const char *, wl_proxy_get_class, (struct wl_proxy *)) +SDL_WAYLAND_SYM(void, wl_proxy_set_queue, (struct wl_proxy *, struct wl_event_queue *)) +SDL_WAYLAND_SYM(void *, wl_proxy_create_wrapper, (void *)) +SDL_WAYLAND_SYM(void, wl_proxy_wrapper_destroy, (void *)) +SDL_WAYLAND_SYM(struct wl_display *, wl_display_connect, (const char *)) +SDL_WAYLAND_SYM(struct wl_display *, wl_display_connect_to_fd, (int)) +SDL_WAYLAND_SYM(void, wl_display_disconnect, (struct wl_display *)) +SDL_WAYLAND_SYM(int, wl_display_get_fd, (struct wl_display *)) +SDL_WAYLAND_SYM(int, wl_display_dispatch, (struct wl_display *)) +SDL_WAYLAND_SYM(int, wl_display_dispatch_queue, (struct wl_display *, struct wl_event_queue *)) +SDL_WAYLAND_SYM(int, wl_display_dispatch_queue_pending, (struct wl_display *, struct wl_event_queue *)) +SDL_WAYLAND_SYM(int, wl_display_dispatch_pending, (struct wl_display *)) +SDL_WAYLAND_SYM(int, wl_display_prepare_read, (struct wl_display *)) +SDL_WAYLAND_SYM(int, wl_display_prepare_read_queue, (struct wl_display *, struct wl_event_queue *)) +SDL_WAYLAND_SYM(int, wl_display_read_events, (struct wl_display *)) +SDL_WAYLAND_SYM(void, wl_display_cancel_read, (struct wl_display *)) +SDL_WAYLAND_SYM(int, wl_display_get_error, (struct wl_display *)) +SDL_WAYLAND_SYM(int, wl_display_flush, (struct wl_display *)) +SDL_WAYLAND_SYM(int, wl_display_roundtrip, (struct wl_display *)) +SDL_WAYLAND_SYM(struct wl_event_queue *, wl_display_create_queue, (struct wl_display *)) +SDL_WAYLAND_SYM(void, wl_event_queue_destroy, (struct wl_event_queue *)) +SDL_WAYLAND_SYM(void, wl_log_set_handler_client, (wl_log_func_t)) +SDL_WAYLAND_SYM(void, wl_list_init, (struct wl_list *)) +SDL_WAYLAND_SYM(void, wl_list_insert, (struct wl_list *, struct wl_list *) ) +SDL_WAYLAND_SYM(void, wl_list_remove, (struct wl_list *)) +SDL_WAYLAND_SYM(int, wl_list_length, (const struct wl_list *)) +SDL_WAYLAND_SYM(int, wl_list_empty, (const struct wl_list *)) +SDL_WAYLAND_SYM(void, wl_list_insert_list, (struct wl_list *, struct wl_list *)) +SDL_WAYLAND_SYM(struct wl_proxy *, wl_proxy_marshal_constructor, (struct wl_proxy *, uint32_t opcode, const struct wl_interface *interface, ...)) +SDL_WAYLAND_SYM(struct wl_proxy *, wl_proxy_marshal_constructor_versioned, (struct wl_proxy *proxy, uint32_t opcode, const struct wl_interface *interface, uint32_t version, ...)) +SDL_WAYLAND_SYM(void, wl_proxy_set_tag, (struct wl_proxy *, const char * const *)) +SDL_WAYLAND_SYM(const char * const *, wl_proxy_get_tag, (struct wl_proxy *)) + +#if SDL_WAYLAND_CHECK_VERSION(1, 20, 0) +/* wayland-scanner 1.20 generates code that will call these, so these are + * non-optional when we are compiling against Wayland 1.20. We don't + * explicitly call them ourselves, though, so if we are only compiling + * against Wayland 1.18, they're unnecessary. */ +SDL_WAYLAND_SYM(struct wl_proxy*, wl_proxy_marshal_flags, (struct wl_proxy *proxy, uint32_t opcode, const struct wl_interface *interfac, uint32_t version, uint32_t flags, ...)) +SDL_WAYLAND_SYM(struct wl_proxy*, wl_proxy_marshal_array_flags, (struct wl_proxy *proxy, uint32_t opcode, const struct wl_interface *interface, uint32_t version, uint32_t flags, union wl_argument *args)) +#endif + +#if 0 // TODO RECONNECT: See waylandvideo.c for more information! +#if SDL_WAYLAND_CHECK_VERSION(broken, on, purpose) +SDL_WAYLAND_SYM(int, wl_display_reconnect, (struct wl_display*)) +#endif +#endif // 0 + +SDL_WAYLAND_INTERFACE(wl_seat_interface) +SDL_WAYLAND_INTERFACE(wl_surface_interface) +SDL_WAYLAND_INTERFACE(wl_shm_pool_interface) +SDL_WAYLAND_INTERFACE(wl_buffer_interface) +SDL_WAYLAND_INTERFACE(wl_registry_interface) +SDL_WAYLAND_INTERFACE(wl_region_interface) +SDL_WAYLAND_INTERFACE(wl_pointer_interface) +SDL_WAYLAND_INTERFACE(wl_keyboard_interface) +SDL_WAYLAND_INTERFACE(wl_compositor_interface) +SDL_WAYLAND_INTERFACE(wl_output_interface) +SDL_WAYLAND_INTERFACE(wl_shm_interface) +SDL_WAYLAND_INTERFACE(wl_data_device_interface) +SDL_WAYLAND_INTERFACE(wl_data_source_interface) +SDL_WAYLAND_INTERFACE(wl_data_offer_interface) +SDL_WAYLAND_INTERFACE(wl_data_device_manager_interface) + +SDL_WAYLAND_MODULE(WAYLAND_EGL) +SDL_WAYLAND_SYM(struct wl_egl_window *, wl_egl_window_create, (struct wl_surface *, int, int)) +SDL_WAYLAND_SYM(void, wl_egl_window_destroy, (struct wl_egl_window *)) +SDL_WAYLAND_SYM(void, wl_egl_window_resize, (struct wl_egl_window *, int, int, int, int)) +SDL_WAYLAND_SYM(void, wl_egl_window_get_attached_size, (struct wl_egl_window *, int *, int *)) + +SDL_WAYLAND_MODULE(WAYLAND_CURSOR) +SDL_WAYLAND_SYM(struct wl_cursor_theme *, wl_cursor_theme_load, (const char *, int , struct wl_shm *)) +SDL_WAYLAND_SYM(void, wl_cursor_theme_destroy, (struct wl_cursor_theme *)) +SDL_WAYLAND_SYM(struct wl_cursor *, wl_cursor_theme_get_cursor, (struct wl_cursor_theme *, const char *)) +SDL_WAYLAND_SYM(struct wl_buffer *, wl_cursor_image_get_buffer, (struct wl_cursor_image *)) +SDL_WAYLAND_SYM(int, wl_cursor_frame, (struct wl_cursor *, uint32_t)) + +SDL_WAYLAND_MODULE(WAYLAND_XKB) +SDL_WAYLAND_SYM(int, xkb_state_key_get_syms, (struct xkb_state *, xkb_keycode_t, const xkb_keysym_t **)) +SDL_WAYLAND_SYM(int, xkb_keysym_to_utf8, (xkb_keysym_t, char *, size_t) ) +SDL_WAYLAND_SYM(struct xkb_keymap *, xkb_keymap_new_from_string, (struct xkb_context *, const char *, enum xkb_keymap_format, enum xkb_keymap_compile_flags)) +SDL_WAYLAND_SYM(struct xkb_state *, xkb_state_new, (struct xkb_keymap *) ) +SDL_WAYLAND_SYM(int, xkb_keymap_key_repeats, (struct xkb_keymap *keymap, xkb_keycode_t key) ) +SDL_WAYLAND_SYM(void, xkb_keymap_unref, (struct xkb_keymap *) ) +SDL_WAYLAND_SYM(void, xkb_state_unref, (struct xkb_state *) ) +SDL_WAYLAND_SYM(void, xkb_context_unref, (struct xkb_context *) ) +SDL_WAYLAND_SYM(struct xkb_context *, xkb_context_new, (enum xkb_context_flags flags) ) +SDL_WAYLAND_SYM(enum xkb_state_component, xkb_state_update_mask, (struct xkb_state *state,\ + xkb_mod_mask_t depressed_mods,\ + xkb_mod_mask_t latched_mods,\ + xkb_mod_mask_t locked_mods,\ + xkb_layout_index_t depressed_layout,\ + xkb_layout_index_t latched_layout,\ + xkb_layout_index_t locked_layout) ) +SDL_WAYLAND_SYM(struct xkb_compose_table *, xkb_compose_table_new_from_locale, (struct xkb_context *,\ + const char *locale, enum xkb_compose_compile_flags) ) +SDL_WAYLAND_SYM(void, xkb_compose_state_reset, (struct xkb_compose_state *) ) +SDL_WAYLAND_SYM(void, xkb_compose_table_unref, (struct xkb_compose_table *) ) +SDL_WAYLAND_SYM(struct xkb_compose_state *, xkb_compose_state_new, (struct xkb_compose_table *, enum xkb_compose_state_flags) ) +SDL_WAYLAND_SYM(void, xkb_compose_state_unref, (struct xkb_compose_state *) ) +SDL_WAYLAND_SYM(enum xkb_compose_feed_result, xkb_compose_state_feed, (struct xkb_compose_state *, xkb_keysym_t) ) +SDL_WAYLAND_SYM(enum xkb_compose_status, xkb_compose_state_get_status, (struct xkb_compose_state *) ) +SDL_WAYLAND_SYM(xkb_keysym_t, xkb_compose_state_get_one_sym, (struct xkb_compose_state *) ) +SDL_WAYLAND_SYM(void, xkb_keymap_key_for_each, (struct xkb_keymap *, xkb_keymap_key_iter_t, void*) ) +SDL_WAYLAND_SYM(int, xkb_keymap_key_get_syms_by_level, (struct xkb_keymap *, + xkb_keycode_t, + xkb_layout_index_t, + xkb_layout_index_t, + const xkb_keysym_t **) ) +SDL_WAYLAND_SYM(uint32_t, xkb_keysym_to_utf32, (xkb_keysym_t) ) +SDL_WAYLAND_SYM(uint32_t, xkb_keymap_mod_get_index, (struct xkb_keymap *, + const char *) ) +SDL_WAYLAND_SYM(const char *, xkb_keymap_layout_get_name, (struct xkb_keymap*, xkb_layout_index_t)) + +#ifdef HAVE_LIBDECOR_H +SDL_WAYLAND_MODULE(WAYLAND_LIBDECOR) +SDL_WAYLAND_SYM(void, libdecor_unref, (struct libdecor *)) +SDL_WAYLAND_SYM(struct libdecor *, libdecor_new, (struct wl_display *, struct libdecor_interface *)) +SDL_WAYLAND_SYM(struct libdecor_frame *, libdecor_decorate, (struct libdecor *,\ + struct wl_surface *,\ + struct libdecor_frame_interface *,\ + void *)) +SDL_WAYLAND_SYM(void, libdecor_frame_unref, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_title, (struct libdecor_frame *, const char *)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_app_id, (struct libdecor_frame *, const char *)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_max_content_size, (struct libdecor_frame *frame,\ + int content_width,\ + int content_height)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_min_content_size, (struct libdecor_frame *frame,\ + int content_width,\ + int content_height)) +SDL_WAYLAND_SYM(void, libdecor_frame_resize, (struct libdecor_frame *,\ + struct wl_seat *,\ + uint32_t,\ + enum libdecor_resize_edge)) +SDL_WAYLAND_SYM(void, libdecor_frame_move, (struct libdecor_frame *,\ + struct wl_seat *,\ + uint32_t)) +SDL_WAYLAND_SYM(void, libdecor_frame_commit, (struct libdecor_frame *,\ + struct libdecor_state *,\ + struct libdecor_configuration *)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_minimized, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_maximized, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(void, libdecor_frame_unset_maximized, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_fullscreen, (struct libdecor_frame *, struct wl_output *)) +SDL_WAYLAND_SYM(void, libdecor_frame_unset_fullscreen, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_capabilities, (struct libdecor_frame *, \ + enum libdecor_capabilities)) +SDL_WAYLAND_SYM(void, libdecor_frame_unset_capabilities, (struct libdecor_frame *, \ + enum libdecor_capabilities)) +SDL_WAYLAND_SYM(bool, libdecor_frame_has_capability, (struct libdecor_frame *, \ + enum libdecor_capabilities)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_visibility, (struct libdecor_frame *, bool)) +SDL_WAYLAND_SYM(bool, libdecor_frame_is_visible, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(bool, libdecor_frame_is_floating, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(void, libdecor_frame_set_parent, (struct libdecor_frame *,\ + struct libdecor_frame *)) +SDL_WAYLAND_SYM(void, libdecor_frame_show_window_menu, (struct libdecor_frame *, struct wl_seat *, uint32_t, int, int)) +SDL_WAYLAND_SYM(struct xdg_surface *, libdecor_frame_get_xdg_surface, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(struct xdg_toplevel *, libdecor_frame_get_xdg_toplevel, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(void, libdecor_frame_translate_coordinate, (struct libdecor_frame *, int, int, int *, int *)) +SDL_WAYLAND_SYM(void, libdecor_frame_map, (struct libdecor_frame *)) +SDL_WAYLAND_SYM(struct libdecor_state *, libdecor_state_new, (int, int)) +SDL_WAYLAND_SYM(void, libdecor_state_free, (struct libdecor_state *)) +SDL_WAYLAND_SYM(bool, libdecor_configuration_get_content_size, (struct libdecor_configuration *,\ + struct libdecor_frame *,\ + int *,\ + int *)) +SDL_WAYLAND_SYM(bool, libdecor_configuration_get_window_state, (struct libdecor_configuration *,\ + enum libdecor_window_state *)) +SDL_WAYLAND_SYM(int, libdecor_dispatch, (struct libdecor *, int)) + +#if defined(SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR) || SDL_LIBDECOR_CHECK_VERSION(0, 2, 0) +// Only found in libdecor 0.1.1 or higher, so failure to load them is not fatal. +SDL_WAYLAND_SYM_OPT(void, libdecor_frame_get_min_content_size, (const struct libdecor_frame *,\ + int *,\ + int *)) +SDL_WAYLAND_SYM_OPT(void, libdecor_frame_get_max_content_size, (const struct libdecor_frame *,\ + int *,\ + int *)) +#endif + +#if defined(SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR) || SDL_LIBDECOR_CHECK_VERSION(0, 3, 0) +SDL_WAYLAND_SYM_OPT(enum libdecor_wm_capabilities, libdecor_frame_get_wm_capabilities, (struct libdecor_frame *)) +#endif + +#endif + +#undef SDL_WAYLAND_MODULE +#undef SDL_WAYLAND_SYM +#undef SDL_WAYLAND_SYM_OPT +#undef SDL_WAYLAND_INTERFACE + +/* *INDENT-ON* */ // clang-format on diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvideo.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvideo.c new file mode 100644 index 0000000..4301953 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvideo.c @@ -0,0 +1,1692 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#include "../../core/linux/SDL_system_theme.h" +#include "../../events/SDL_events_c.h" + +#include "SDL_waylandclipboard.h" +#include "SDL_waylandcolor.h" +#include "SDL_waylandevents_c.h" +#include "SDL_waylandkeyboard.h" +#include "SDL_waylandmessagebox.h" +#include "SDL_waylandmouse.h" +#include "SDL_waylandopengles.h" +#include "SDL_waylandvideo.h" +#include "SDL_waylandvulkan.h" +#include "SDL_waylandwindow.h" + +#include +#include +#include +#include + +#include + +#include "alpha-modifier-v1-client-protocol.h" +#include "cursor-shape-v1-client-protocol.h" +#include "fractional-scale-v1-client-protocol.h" +#include "frog-color-management-v1-client-protocol.h" +#include "idle-inhibit-unstable-v1-client-protocol.h" +#include "input-timestamps-unstable-v1-client-protocol.h" +#include "keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h" +#include "pointer-constraints-unstable-v1-client-protocol.h" +#include "primary-selection-unstable-v1-client-protocol.h" +#include "relative-pointer-unstable-v1-client-protocol.h" +#include "tablet-v2-client-protocol.h" +#include "text-input-unstable-v3-client-protocol.h" +#include "viewporter-client-protocol.h" +#include "xdg-activation-v1-client-protocol.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" +#include "xdg-dialog-v1-client-protocol.h" +#include "xdg-foreign-unstable-v2-client-protocol.h" +#include "xdg-output-unstable-v1-client-protocol.h" +#include "xdg-shell-client-protocol.h" +#include "xdg-toplevel-icon-v1-client-protocol.h" +#include "color-management-v1-client-protocol.h" + +#ifdef HAVE_LIBDECOR_H +#include +#endif + +#define WAYLANDVID_DRIVER_NAME "wayland" + +// Clamp certain core protocol versions on older versions of libwayland. +#if SDL_WAYLAND_CHECK_VERSION(1, 22, 0) +#define SDL_WL_COMPOSITOR_VERSION 6 +#else +#define SDL_WL_COMPOSITOR_VERSION 4 +#endif + +#if SDL_WAYLAND_CHECK_VERSION(1, 22, 0) +#define SDL_WL_SEAT_VERSION 9 +#elif SDL_WAYLAND_CHECK_VERSION(1, 21, 0) +#define SDL_WL_SEAT_VERSION 8 +#else +#define SDL_WL_SEAT_VERSION 5 +#endif + +#if SDL_WAYLAND_CHECK_VERSION(1, 20, 0) +#define SDL_WL_OUTPUT_VERSION 4 +#else +#define SDL_WL_OUTPUT_VERSION 3 +#endif + +#ifdef SDL_USE_LIBDBUS +#include "../../core/linux/SDL_dbus.h" + +#define DISPLAY_INFO_NODE "org.gnome.Mutter.DisplayConfig" +#define DISPLAY_INFO_PATH "/org/gnome/Mutter/DisplayConfig" +#define DISPLAY_INFO_METHOD "GetCurrentState" +#endif + +/* GNOME doesn't expose displays in any particular order, but we can find the + * primary display and its logical coordinates via a DBus method. + */ +static bool Wayland_GetGNOMEPrimaryDisplayCoordinates(int *x, int *y) +{ +#ifdef SDL_USE_LIBDBUS + SDL_DBusContext *dbus = SDL_DBus_GetContext(); + if (dbus == NULL) { + return false; + } + DBusMessage *reply = NULL; + DBusMessageIter iter[3]; + DBusMessage *msg = dbus->message_new_method_call(DISPLAY_INFO_NODE, + DISPLAY_INFO_PATH, + DISPLAY_INFO_NODE, + DISPLAY_INFO_METHOD); + + if (msg) { + reply = dbus->connection_send_with_reply_and_block(dbus->session_conn, msg, DBUS_TIMEOUT_USE_DEFAULT, NULL); + dbus->message_unref(msg); + } + + if (reply) { + // Serial (don't care) + dbus->message_iter_init(reply, &iter[0]); + if (dbus->message_iter_get_arg_type(&iter[0]) != DBUS_TYPE_UINT32) { + goto error; + } + + // Physical monitor array (don't care) + dbus->message_iter_next(&iter[0]); + if (dbus->message_iter_get_arg_type(&iter[0]) != DBUS_TYPE_ARRAY) { + goto error; + } + + // Logical monitor array of structs + dbus->message_iter_next(&iter[0]); + if (dbus->message_iter_get_arg_type(&iter[0]) != DBUS_TYPE_ARRAY) { + goto error; + } + + // First logical monitor struct + dbus->message_iter_recurse(&iter[0], &iter[1]); + if (dbus->message_iter_get_arg_type(&iter[1]) != DBUS_TYPE_STRUCT) { + goto error; + } + + do { + int logical_x, logical_y; + dbus_bool_t primary; + + // Logical X + dbus->message_iter_recurse(&iter[1], &iter[2]); + if (dbus->message_iter_get_arg_type(&iter[2]) != DBUS_TYPE_INT32) { + goto error; + } + dbus->message_iter_get_basic(&iter[2], &logical_x); + + // Logical Y + dbus->message_iter_next(&iter[2]); + if (dbus->message_iter_get_arg_type(&iter[2]) != DBUS_TYPE_INT32) { + goto error; + } + dbus->message_iter_get_basic(&iter[2], &logical_y); + + // Scale (don't care) + dbus->message_iter_next(&iter[2]); + if (dbus->message_iter_get_arg_type(&iter[2]) != DBUS_TYPE_DOUBLE) { + goto error; + } + + // Transform (don't care) + dbus->message_iter_next(&iter[2]); + if (dbus->message_iter_get_arg_type(&iter[2]) != DBUS_TYPE_UINT32) { + goto error; + } + + // Primary display boolean + dbus->message_iter_next(&iter[2]); + if (dbus->message_iter_get_arg_type(&iter[2]) != DBUS_TYPE_BOOLEAN) { + goto error; + } + dbus->message_iter_get_basic(&iter[2], &primary); + + if (primary) { + *x = logical_x; + *y = logical_y; + + // We found the primary display: success. + dbus->message_unref(reply); + return true; + } + } while (dbus->message_iter_next(&iter[1])); + } + +error: + if (reply) { + dbus->message_unref(reply); + } +#endif + return false; +} + +// Sort the list of displays into a deterministic order +static int SDLCALL Wayland_DisplayPositionCompare(const void *a, const void *b) +{ + const SDL_DisplayData *da = *(SDL_DisplayData **)a; + const SDL_DisplayData *db = *(SDL_DisplayData **)b; + + const bool a_at_origin = da->x == 0 && da->y == 0; + const bool b_at_origin = db->x == 0 && db->y == 0; + + // Sort the display at 0,0 to be beginning of the list, as that will be the fallback primary. + if (a_at_origin && !b_at_origin) { + return -1; + } + if (b_at_origin && !a_at_origin) { + return 1; + } + if (da->x < db->x) { + return -1; + } + if (da->x > db->x) { + return 1; + } + if (da->y < db->y) { + return -1; + } + if (da->y > db->y) { + return 1; + } + + // If no position information is available, use the connector name. + if (da->wl_output_name && db->wl_output_name) { + return SDL_strcmp(da->wl_output_name, db->wl_output_name); + } + + return 0; +} + +/* Wayland doesn't have the native concept of a primary display, but there are clients that + * will base their resolution lists on, or automatically make themselves fullscreen on, the + * first listed output, which can lead to problems if the first listed output isn't + * necessarily the best display for this. This attempts to find a primary display, first by + * querying the GNOME DBus property, then trying to determine the 'best' display if that fails. + * If all displays are equal, the one at position 0,0 will become the primary. + * + * The primary is determined by the following criteria, in order: + * - Landscape is preferred over portrait + * - The highest native resolution + * - A higher HDR range is preferred + * - Higher refresh is preferred (ignoring small differences) + * - Lower scale values are preferred (larger display) + */ +static int Wayland_GetPrimaryDisplay(SDL_VideoData *vid) +{ + static const int REFRESH_DELTA = 4000; + + // Query the DBus interface to see if the coordinates of the primary display are exposed. + int x, y; + if (Wayland_GetGNOMEPrimaryDisplayCoordinates(&x, &y)) { + for (int i = 0; i < vid->output_count; ++i) { + if (vid->output_list[i]->x == x && vid->output_list[i]->y == y) { + return i; + } + } + } + + // Otherwise, choose the 'best' display. + int best_width = 0; + int best_height = 0; + double best_scale = 0.0; + float best_headroom = 0.0f; + int best_refresh = 0; + bool best_is_landscape = false; + int best_index = 0; + + for (int i = 0; i < vid->output_count; ++i) { + const SDL_DisplayData *d = vid->output_list[i]; + const bool is_landscape = d->orientation != SDL_ORIENTATION_PORTRAIT && d->orientation != SDL_ORIENTATION_PORTRAIT_FLIPPED; + bool have_new_best = false; + + if (!best_is_landscape && is_landscape) { // Favor landscape over portrait displays. + have_new_best = true; + } else if (!best_is_landscape || is_landscape) { // Ignore portrait displays if a landscape was already found. + if (d->pixel_width > best_width || d->pixel_height > best_height) { + have_new_best = true; + } else if (d->pixel_width == best_width && d->pixel_height == best_height) { + if (d->HDR.HDR_headroom > best_headroom) { // Favor a higher HDR luminance range + have_new_best = true; + } else if (d->HDR.HDR_headroom == best_headroom) { + if (d->refresh - best_refresh > REFRESH_DELTA) { // Favor a higher refresh rate, but ignore small differences (e.g. 59.97 vs 60.1) + have_new_best = true; + } else if (d->scale_factor < best_scale && SDL_abs(d->refresh - best_refresh) <= REFRESH_DELTA) { + // Prefer a lower scale display if the difference in refresh rate is small. + have_new_best = true; + } + } + } + } + + if (have_new_best) { + best_width = d->pixel_width; + best_height = d->pixel_height; + best_scale = d->scale_factor; + best_headroom = d->HDR.HDR_headroom; + best_refresh = d->refresh; + best_is_landscape = is_landscape; + best_index = i; + } + } + + return best_index; +} + +static void Wayland_SortOutputsByPriorityHint(SDL_VideoData *vid) +{ + const char *name_hint = SDL_GetHint(SDL_HINT_VIDEO_DISPLAY_PRIORITY); + + if (name_hint) { + char *saveptr; + char *str = SDL_strdup(name_hint); + SDL_DisplayData **sorted_list = SDL_malloc(sizeof(SDL_DisplayData *) * vid->output_count); + + if (str && sorted_list) { + int sorted_index = 0; + + // Sort the requested displays to the front of the list. + const char *token = SDL_strtok_r(str, ",", &saveptr); + while (token) { + for (int i = 0; i < vid->output_count; ++i) { + SDL_DisplayData *d = vid->output_list[i]; + if (d && d->wl_output_name && SDL_strcmp(token, d->wl_output_name) == 0) { + sorted_list[sorted_index++] = d; + vid->output_list[i] = NULL; + break; + } + } + + token = SDL_strtok_r(NULL, ",", &saveptr); + } + + // Append the remaining outputs to the end of the list. + for (int i = 0; i < vid->output_count; ++i) { + if (vid->output_list[i]) { + sorted_list[sorted_index++] = vid->output_list[i]; + } + } + + // Copy the sorted list to the output list. + SDL_memcpy(vid->output_list, sorted_list, sizeof(SDL_DisplayData *) * vid->output_count); + } + + SDL_free(str); + SDL_free(sorted_list); + } +} + +static void Wayland_SortOutputs(SDL_VideoData *vid) +{ + // Sort by position or connector name, so the order of outputs is deterministic. + SDL_qsort(vid->output_list, vid->output_count, sizeof(SDL_DisplayData *), Wayland_DisplayPositionCompare); + + // Find a suitable primary display and move it to the front of the list. + const int primary_index = Wayland_GetPrimaryDisplay(vid); + if (primary_index) { + SDL_DisplayData *primary = vid->output_list[primary_index]; + SDL_memmove(&vid->output_list[1], &vid->output_list[0], sizeof(SDL_DisplayData *) * primary_index); + vid->output_list[0] = primary; + } + + // Apply the ordering hint, if specified. + Wayland_SortOutputsByPriorityHint(vid); +} + +static void display_handle_done(void *data, struct wl_output *output); + +// Initialization/Query functions +static bool Wayland_VideoInit(SDL_VideoDevice *_this); +static bool Wayland_GetDisplayBounds(SDL_VideoDevice *_this, SDL_VideoDisplay *display, SDL_Rect *rect); +static void Wayland_VideoQuit(SDL_VideoDevice *_this); + +static const char *SDL_WAYLAND_surface_tag = "sdl-window"; +static const char *SDL_WAYLAND_output_tag = "sdl-output"; + +void SDL_WAYLAND_register_surface(struct wl_surface *surface) +{ + wl_proxy_set_tag((struct wl_proxy *)surface, &SDL_WAYLAND_surface_tag); +} + +void SDL_WAYLAND_register_output(struct wl_output *output) +{ + wl_proxy_set_tag((struct wl_proxy *)output, &SDL_WAYLAND_output_tag); +} + +bool SDL_WAYLAND_own_surface(struct wl_surface *surface) +{ + return wl_proxy_get_tag((struct wl_proxy *)surface) == &SDL_WAYLAND_surface_tag; +} + +bool SDL_WAYLAND_own_output(struct wl_output *output) +{ + return wl_proxy_get_tag((struct wl_proxy *)output) == &SDL_WAYLAND_output_tag; +} + +/* External surfaces may have their own user data attached, the modification of which + * can cause problems with external toolkits. Instead, external windows are kept in + * their own list, and a search is conducted to find a matching surface. + */ +static struct wl_list external_window_list; + +void Wayland_AddWindowDataToExternalList(SDL_WindowData *data) +{ + WAYLAND_wl_list_insert(&external_window_list, &data->external_window_list_link); +} + +void Wayland_RemoveWindowDataFromExternalList(SDL_WindowData *data) +{ + WAYLAND_wl_list_remove(&data->external_window_list_link); +} + +SDL_WindowData *Wayland_GetWindowDataForOwnedSurface(struct wl_surface *surface) +{ + if (SDL_WAYLAND_own_surface(surface)) { + return (SDL_WindowData *)wl_surface_get_user_data(surface); + } else if (!WAYLAND_wl_list_empty(&external_window_list)) { + SDL_WindowData *p; + wl_list_for_each (p, &external_window_list, external_window_list_link) { + if (p->surface == surface) { + return p; + } + } + } + + return NULL; +} + +static void Wayland_DeleteDevice(SDL_VideoDevice *device) +{ + SDL_VideoData *data = device->internal; + if (data->display && !data->display_externally_owned) { + WAYLAND_wl_display_flush(data->display); + WAYLAND_wl_display_disconnect(data->display); + SDL_ClearProperty(SDL_GetGlobalProperties(), SDL_PROP_GLOBAL_VIDEO_WAYLAND_WL_DISPLAY_POINTER); + } + if (device->wakeup_lock) { + SDL_DestroyMutex(device->wakeup_lock); + } + SDL_free(data); + SDL_free(device); + SDL_WAYLAND_UnloadSymbols(); +} + +typedef struct +{ + bool has_fifo_v1; +} SDL_WaylandPreferredData; + +static void wayland_preferred_check_handle_global(void *data, struct wl_registry *registry, uint32_t id, + const char *interface, uint32_t version) +{ + SDL_WaylandPreferredData *d = data; + + if (SDL_strcmp(interface, "wp_fifo_manager_v1") == 0) { + d->has_fifo_v1 = true; + } +} + +static void wayland_preferred_check_remove_global(void *data, struct wl_registry *registry, uint32_t id) +{ + // No need to do anything here. +} + +static const struct wl_registry_listener preferred_registry_listener = { + wayland_preferred_check_handle_global, + wayland_preferred_check_remove_global +}; + +static bool Wayland_IsPreferred(struct wl_display *display) +{ + struct wl_registry *registry = wl_display_get_registry(display); + SDL_WaylandPreferredData preferred_data = { 0 }; + + if (!registry) { + SDL_SetError("Failed to get the Wayland registry"); + return false; + } + + wl_registry_add_listener(registry, &preferred_registry_listener, &preferred_data); + + WAYLAND_wl_display_roundtrip(display); + + wl_registry_destroy(registry); + + return preferred_data.has_fifo_v1; +} + +static SDL_VideoDevice *Wayland_CreateDevice(bool require_preferred_protocols) +{ + SDL_VideoDevice *device; + SDL_VideoData *data; + struct SDL_WaylandInput *input; + struct wl_display *display = SDL_GetPointerProperty(SDL_GetGlobalProperties(), + SDL_PROP_GLOBAL_VIDEO_WAYLAND_WL_DISPLAY_POINTER, NULL); + bool display_is_external = !!display; + + // Are we trying to connect to or are currently in a Wayland session? + if (!SDL_getenv("WAYLAND_DISPLAY")) { + const char *session = SDL_getenv("XDG_SESSION_TYPE"); + if (session && SDL_strcasecmp(session, "wayland") != 0) { + return NULL; + } + } + + if (!SDL_WAYLAND_LoadSymbols()) { + return NULL; + } + + if (!display) { + display = WAYLAND_wl_display_connect(NULL); + if (!display) { + SDL_WAYLAND_UnloadSymbols(); + return NULL; + } + } + + /* + * If we are checking for preferred Wayland, then let's query for + * fifo-v1's existence, so we don't regress GPU-bound performance + * and frame-pacing by default due to swapchain starvation. + */ + if (require_preferred_protocols && !Wayland_IsPreferred(display)) { + if (!display_is_external) { + WAYLAND_wl_display_disconnect(display); + } + SDL_WAYLAND_UnloadSymbols(); + return NULL; + } + + data = SDL_calloc(1, sizeof(*data)); + if (!data) { + if (!display_is_external) { + WAYLAND_wl_display_disconnect(display); + } + SDL_WAYLAND_UnloadSymbols(); + return NULL; + } + + input = SDL_calloc(1, sizeof(*input)); + if (!input) { + SDL_free(data); + if (!display_is_external) { + WAYLAND_wl_display_disconnect(display); + } + SDL_WAYLAND_UnloadSymbols(); + return NULL; + } + + input->display = data; + input->sx_w = wl_fixed_from_int(0); + input->sy_w = wl_fixed_from_int(0); + input->xkb.current_group = XKB_GROUP_INVALID; + + data->initializing = true; + data->display = display; + data->input = input; + data->display_externally_owned = display_is_external; + data->scale_to_display_enabled = SDL_GetHintBoolean(SDL_HINT_VIDEO_WAYLAND_SCALE_TO_DISPLAY, false); + WAYLAND_wl_list_init(&external_window_list); + + // Initialize all variables that we clean on shutdown + device = SDL_calloc(1, sizeof(SDL_VideoDevice)); + if (!device) { + SDL_free(input); + SDL_free(data); + if (!display_is_external) { + WAYLAND_wl_display_disconnect(display); + } + SDL_WAYLAND_UnloadSymbols(); + return NULL; + } + + if (!display_is_external) { + SDL_SetPointerProperty(SDL_GetGlobalProperties(), + SDL_PROP_GLOBAL_VIDEO_WAYLAND_WL_DISPLAY_POINTER, display); + } + + device->internal = data; + device->wakeup_lock = SDL_CreateMutex(); + + // Set the function pointers + device->VideoInit = Wayland_VideoInit; + device->VideoQuit = Wayland_VideoQuit; + device->GetDisplayBounds = Wayland_GetDisplayBounds; + device->SuspendScreenSaver = Wayland_SuspendScreenSaver; + + device->PumpEvents = Wayland_PumpEvents; + device->WaitEventTimeout = Wayland_WaitEventTimeout; + device->SendWakeupEvent = Wayland_SendWakeupEvent; + +#ifdef SDL_VIDEO_OPENGL_EGL + device->GL_SwapWindow = Wayland_GLES_SwapWindow; + device->GL_GetSwapInterval = Wayland_GLES_GetSwapInterval; + device->GL_SetSwapInterval = Wayland_GLES_SetSwapInterval; + device->GL_MakeCurrent = Wayland_GLES_MakeCurrent; + device->GL_CreateContext = Wayland_GLES_CreateContext; + device->GL_LoadLibrary = Wayland_GLES_LoadLibrary; + device->GL_UnloadLibrary = Wayland_GLES_UnloadLibrary; + device->GL_GetProcAddress = Wayland_GLES_GetProcAddress; + device->GL_DestroyContext = Wayland_GLES_DestroyContext; + device->GL_GetEGLSurface = Wayland_GLES_GetEGLSurface; +#endif + + device->CreateSDLWindow = Wayland_CreateWindow; + device->ShowWindow = Wayland_ShowWindow; + device->HideWindow = Wayland_HideWindow; + device->RaiseWindow = Wayland_RaiseWindow; + device->SetWindowFullscreen = Wayland_SetWindowFullscreen; + device->MaximizeWindow = Wayland_MaximizeWindow; + device->MinimizeWindow = Wayland_MinimizeWindow; + device->SetWindowMouseRect = Wayland_SetWindowMouseRect; + device->SetWindowMouseGrab = Wayland_SetWindowMouseGrab; + device->SetWindowKeyboardGrab = Wayland_SetWindowKeyboardGrab; + device->RestoreWindow = Wayland_RestoreWindow; + device->SetWindowBordered = Wayland_SetWindowBordered; + device->SetWindowResizable = Wayland_SetWindowResizable; + device->SetWindowPosition = Wayland_SetWindowPosition; + device->SetWindowSize = Wayland_SetWindowSize; + device->SetWindowMinimumSize = Wayland_SetWindowMinimumSize; + device->SetWindowMaximumSize = Wayland_SetWindowMaximumSize; + device->SetWindowParent = Wayland_SetWindowParent; + device->SetWindowModal = Wayland_SetWindowModal; + device->SetWindowOpacity = Wayland_SetWindowOpacity; + device->SetWindowTitle = Wayland_SetWindowTitle; + device->SetWindowIcon = Wayland_SetWindowIcon; + device->GetWindowSizeInPixels = Wayland_GetWindowSizeInPixels; + device->GetWindowContentScale = Wayland_GetWindowContentScale; + device->GetWindowICCProfile = Wayland_GetWindowICCProfile; + device->GetDisplayForWindow = Wayland_GetDisplayForWindow; + device->DestroyWindow = Wayland_DestroyWindow; + device->SetWindowHitTest = Wayland_SetWindowHitTest; + device->FlashWindow = Wayland_FlashWindow; + device->HasScreenKeyboardSupport = Wayland_HasScreenKeyboardSupport; + device->ShowWindowSystemMenu = Wayland_ShowWindowSystemMenu; + device->SyncWindow = Wayland_SyncWindow; + +#ifdef SDL_USE_LIBDBUS + if (SDL_SystemTheme_Init()) + device->system_theme = SDL_SystemTheme_Get(); +#endif + + device->GetTextMimeTypes = Wayland_GetTextMimeTypes; + device->SetClipboardData = Wayland_SetClipboardData; + device->GetClipboardData = Wayland_GetClipboardData; + device->HasClipboardData = Wayland_HasClipboardData; + device->StartTextInput = Wayland_StartTextInput; + device->StopTextInput = Wayland_StopTextInput; + device->UpdateTextInputArea = Wayland_UpdateTextInputArea; + +#ifdef SDL_VIDEO_VULKAN + device->Vulkan_LoadLibrary = Wayland_Vulkan_LoadLibrary; + device->Vulkan_UnloadLibrary = Wayland_Vulkan_UnloadLibrary; + device->Vulkan_GetInstanceExtensions = Wayland_Vulkan_GetInstanceExtensions; + device->Vulkan_CreateSurface = Wayland_Vulkan_CreateSurface; + device->Vulkan_DestroySurface = Wayland_Vulkan_DestroySurface; + device->Vulkan_GetPresentationSupport = Wayland_Vulkan_GetPresentationSupport; +#endif + + device->free = Wayland_DeleteDevice; + + device->device_caps = VIDEO_DEVICE_CAPS_MODE_SWITCHING_EMULATED | + VIDEO_DEVICE_CAPS_HAS_POPUP_WINDOW_SUPPORT | + VIDEO_DEVICE_CAPS_SENDS_FULLSCREEN_DIMENSIONS | + VIDEO_DEVICE_CAPS_SENDS_DISPLAY_CHANGES | + VIDEO_DEVICE_CAPS_DISABLE_MOUSE_WARP_ON_FULLSCREEN_TRANSITIONS | + VIDEO_DEVICE_CAPS_SENDS_HDR_CHANGES; + + return device; +} + +static SDL_VideoDevice *Wayland_Preferred_CreateDevice(void) +{ + return Wayland_CreateDevice(true); +} + +static SDL_VideoDevice *Wayland_Fallback_CreateDevice(void) +{ + return Wayland_CreateDevice(false); +} + +VideoBootStrap Wayland_preferred_bootstrap = { + WAYLANDVID_DRIVER_NAME, "SDL Wayland video driver", + Wayland_Preferred_CreateDevice, + Wayland_ShowMessageBox, + true +}; + +VideoBootStrap Wayland_bootstrap = { + WAYLANDVID_DRIVER_NAME, "SDL Wayland video driver", + Wayland_Fallback_CreateDevice, + Wayland_ShowMessageBox, + false +}; + +static void xdg_output_handle_logical_position(void *data, struct zxdg_output_v1 *xdg_output, + int32_t x, int32_t y) +{ + SDL_DisplayData *internal = (SDL_DisplayData *)data; + + internal->x = x; + internal->y = y; + internal->has_logical_position = true; +} + +static void xdg_output_handle_logical_size(void *data, struct zxdg_output_v1 *xdg_output, + int32_t width, int32_t height) +{ + SDL_DisplayData *internal = (SDL_DisplayData *)data; + + internal->logical_width = width; + internal->logical_height = height; + internal->has_logical_size = true; +} + +static void xdg_output_handle_done(void *data, struct zxdg_output_v1 *xdg_output) +{ + SDL_DisplayData *internal = data; + + /* + * xdg-output.done events are deprecated and only apply below version 3 of the protocol. + * A wl-output.done event will be emitted in version 3 or higher. + */ + if (zxdg_output_v1_get_version(internal->xdg_output) < 3) { + display_handle_done(data, internal->output); + } +} + +static void xdg_output_handle_name(void *data, struct zxdg_output_v1 *xdg_output, + const char *name) +{ + SDL_DisplayData *internal = (SDL_DisplayData *)data; + + // Deprecated as of wl_output v4. + if (wl_output_get_version(internal->output) < WL_OUTPUT_NAME_SINCE_VERSION && + internal->display == 0) { + SDL_free(internal->wl_output_name); + internal->wl_output_name = SDL_strdup(name); + } +} + +static void xdg_output_handle_description(void *data, struct zxdg_output_v1 *xdg_output, + const char *description) +{ + SDL_DisplayData *internal = (SDL_DisplayData *)data; + + // Deprecated as of wl_output v4. + if (wl_output_get_version(internal->output) < WL_OUTPUT_DESCRIPTION_SINCE_VERSION && + internal->display == 0) { + // xdg-output descriptions, if available, supersede wl-output model names. + SDL_free(internal->placeholder.name); + internal->placeholder.name = SDL_strdup(description); + } +} + +static const struct zxdg_output_v1_listener xdg_output_listener = { + xdg_output_handle_logical_position, + xdg_output_handle_logical_size, + xdg_output_handle_done, + xdg_output_handle_name, + xdg_output_handle_description, +}; + +static void AddEmulatedModes(SDL_DisplayData *dispdata, int native_width, int native_height) +{ + struct EmulatedMode + { + int w; + int h; + }; + + // Resolution lists courtesy of XWayland + const struct EmulatedMode mode_list[] = { + // 16:9 (1.77) + { 7680, 4320 }, + { 6144, 3160 }, + { 5120, 2880 }, + { 4096, 2304 }, + { 3840, 2160 }, + { 3200, 1800 }, + { 2880, 1620 }, + { 2560, 1440 }, + { 2048, 1152 }, + { 1920, 1080 }, + { 1600, 900 }, + { 1368, 768 }, + { 1280, 720 }, + { 864, 486 }, + + // 16:10 (1.6) + { 2560, 1600 }, + { 1920, 1200 }, + { 1680, 1050 }, + { 1440, 900 }, + { 1280, 800 }, + + // 3:2 (1.5) + { 720, 480 }, + + // 4:3 (1.33) + { 2048, 1536 }, + { 1920, 1440 }, + { 1600, 1200 }, + { 1440, 1080 }, + { 1400, 1050 }, + { 1280, 1024 }, + { 1280, 960 }, + { 1152, 864 }, + { 1024, 768 }, + { 800, 600 }, + { 640, 480 } + }; + + int i; + SDL_DisplayMode mode; + SDL_VideoDisplay *dpy = dispdata->display ? SDL_GetVideoDisplay(dispdata->display) : &dispdata->placeholder; + const bool rot_90 = native_width < native_height; // Reverse width/height for portrait displays. + + for (i = 0; i < SDL_arraysize(mode_list); ++i) { + SDL_zero(mode); + mode.format = dpy->desktop_mode.format; + mode.refresh_rate_numerator = dpy->desktop_mode.refresh_rate_numerator; + mode.refresh_rate_denominator = dpy->desktop_mode.refresh_rate_denominator; + + if (rot_90) { + mode.w = mode_list[i].h; + mode.h = mode_list[i].w; + } else { + mode.w = mode_list[i].w; + mode.h = mode_list[i].h; + } + + // Only add modes that are smaller than the native mode. + if ((mode.w < native_width && mode.h < native_height) || + (mode.w < native_width && mode.h == native_height) || + (mode.w == native_width && mode.h < native_height)) { + SDL_AddFullscreenDisplayMode(dpy, &mode); + } + } +} + +static void display_handle_geometry(void *data, + struct wl_output *output, + int x, int y, + int physical_width, + int physical_height, + int subpixel, + const char *make, + const char *model, + int transform) + +{ + SDL_DisplayData *internal = (SDL_DisplayData *)data; + + // Apply the change from wl-output only if xdg-output is not supported + if (!internal->has_logical_position) { + internal->x = x; + internal->y = y; + } + internal->physical_width_mm = physical_width; + internal->physical_height_mm = physical_height; + + // The model is only used for the output name if wl_output or xdg-output haven't provided a description. + if (internal->display == 0 && !internal->placeholder.name) { + internal->placeholder.name = SDL_strdup(model); + } + + internal->transform = transform; +#define TF_CASE(in, out) \ + case WL_OUTPUT_TRANSFORM_##in: \ + internal->orientation = SDL_ORIENTATION_##out; \ + break; + if (internal->physical_width_mm >= internal->physical_height_mm) { + switch (transform) { + TF_CASE(NORMAL, LANDSCAPE) + TF_CASE(90, PORTRAIT) + TF_CASE(180, LANDSCAPE_FLIPPED) + TF_CASE(270, PORTRAIT_FLIPPED) + TF_CASE(FLIPPED, LANDSCAPE_FLIPPED) + TF_CASE(FLIPPED_90, PORTRAIT_FLIPPED) + TF_CASE(FLIPPED_180, LANDSCAPE) + TF_CASE(FLIPPED_270, PORTRAIT) + } + } else { + switch (transform) { + TF_CASE(NORMAL, PORTRAIT) + TF_CASE(90, LANDSCAPE) + TF_CASE(180, PORTRAIT_FLIPPED) + TF_CASE(270, LANDSCAPE_FLIPPED) + TF_CASE(FLIPPED, PORTRAIT_FLIPPED) + TF_CASE(FLIPPED_90, LANDSCAPE_FLIPPED) + TF_CASE(FLIPPED_180, PORTRAIT) + TF_CASE(FLIPPED_270, LANDSCAPE) + } + } +#undef TF_CASE +} + +static void display_handle_mode(void *data, + struct wl_output *output, + uint32_t flags, + int width, + int height, + int refresh) +{ + SDL_DisplayData *internal = (SDL_DisplayData *)data; + + if (flags & WL_OUTPUT_MODE_CURRENT) { + internal->pixel_width = width; + internal->pixel_height = height; + + /* + * Don't rotate this yet, wl-output coordinates are transformed in + * handle_done and xdg-output coordinates are pre-transformed. + */ + if (!internal->has_logical_size) { + internal->logical_width = width; + internal->logical_height = height; + } + + internal->refresh = refresh; + } +} + +static void display_handle_done(void *data, + struct wl_output *output) +{ + const bool mode_emulation_enabled = SDL_GetHintBoolean(SDL_HINT_VIDEO_WAYLAND_MODE_EMULATION, true); + SDL_DisplayData *internal = (SDL_DisplayData *)data; + SDL_VideoData *video = internal->videodata; + SDL_DisplayMode native_mode, desktop_mode; + + /* + * When using xdg-output, two wl-output.done events will be emitted: + * one at the completion of wl-display and one at the completion of xdg-output. + * + * All required events must be received before proceeding. + */ + const int event_await_count = 1 + (internal->xdg_output != NULL); + + internal->wl_output_done_count = SDL_min(internal->wl_output_done_count + 1, event_await_count + 1); + + if (internal->wl_output_done_count < event_await_count) { + return; + } + + // If the display was already created, reset and rebuild the mode list. + SDL_VideoDisplay *dpy = SDL_GetVideoDisplay(internal->display); + if (dpy) { + SDL_ResetFullscreenDisplayModes(dpy); + } + + // The native display resolution + SDL_zero(native_mode); + native_mode.format = SDL_PIXELFORMAT_XRGB8888; + + // Transform the pixel values, if necessary. + if (internal->transform & WL_OUTPUT_TRANSFORM_90) { + native_mode.w = internal->pixel_height; + native_mode.h = internal->pixel_width; + } else { + native_mode.w = internal->pixel_width; + native_mode.h = internal->pixel_height; + } + native_mode.refresh_rate_numerator = internal->refresh; + native_mode.refresh_rate_denominator = 1000; + + if (internal->has_logical_size) { // If xdg-output is present... + if (native_mode.w != internal->logical_width || native_mode.h != internal->logical_height) { + // ...and the compositor scales the logical viewport... + if (video->viewporter) { + // ...and viewports are supported, calculate the true scale of the output. + internal->scale_factor = (double)native_mode.w / (double)internal->logical_width; + } else { + // ...otherwise, the 'native' pixel values are a multiple of the logical screen size. + internal->pixel_width = internal->logical_width * (int)internal->scale_factor; + internal->pixel_height = internal->logical_height * (int)internal->scale_factor; + } + } else { + /* ...and the output viewport is not scaled in the global compositing + * space, the output dimensions need to be divided by the scale factor. + */ + internal->logical_width /= (int)internal->scale_factor; + internal->logical_height /= (int)internal->scale_factor; + } + } else { + /* Calculate the points from the pixel values, if xdg-output isn't present. + * Use the native mode pixel values since they are pre-transformed. + */ + internal->logical_width = native_mode.w / (int)internal->scale_factor; + internal->logical_height = native_mode.h / (int)internal->scale_factor; + } + + // The scaled desktop mode + SDL_zero(desktop_mode); + desktop_mode.format = SDL_PIXELFORMAT_XRGB8888; + + if (!video->scale_to_display_enabled) { + desktop_mode.w = internal->logical_width; + desktop_mode.h = internal->logical_height; + desktop_mode.pixel_density = (float)internal->scale_factor; + } else { + desktop_mode.w = native_mode.w; + desktop_mode.h = native_mode.h; + desktop_mode.pixel_density = 1.0f; + } + + desktop_mode.refresh_rate_numerator = internal->refresh; + desktop_mode.refresh_rate_denominator = 1000; + + if (internal->display > 0) { + dpy = SDL_GetVideoDisplay(internal->display); + } else { + dpy = &internal->placeholder; + } + + if (video->scale_to_display_enabled) { + SDL_SetDisplayContentScale(dpy, (float)internal->scale_factor); + } + + // Set the desktop display mode. + SDL_SetDesktopDisplayMode(dpy, &desktop_mode); + + // Expose the unscaled, native resolution if the scale is 1.0 or viewports are available... + if (internal->scale_factor == 1.0 || video->viewporter) { + SDL_AddFullscreenDisplayMode(dpy, &native_mode); + if (native_mode.w != desktop_mode.w || + native_mode.h != desktop_mode.h) { + SDL_AddFullscreenDisplayMode(dpy, &desktop_mode); + } + } else { + // ...otherwise expose the integer scaled variants of the desktop resolution down to 1. + int i; + + desktop_mode.pixel_density = 1.0f; + + for (i = (int)internal->scale_factor; i > 0; --i) { + desktop_mode.w = internal->logical_width * i; + desktop_mode.h = internal->logical_height * i; + SDL_AddFullscreenDisplayMode(dpy, &desktop_mode); + } + } + + // Add emulated modes if wp_viewporter is supported and mode emulation is enabled. + if (video->viewporter && mode_emulation_enabled) { + // The transformed display pixel width/height must be used here. + AddEmulatedModes(internal, native_mode.w, native_mode.h); + } + + SDL_SetDisplayHDRProperties(dpy, &internal->HDR); + + if (internal->display == 0) { + // First time getting display info, initialize the VideoDisplay + if (internal->physical_width_mm >= internal->physical_height_mm) { + internal->placeholder.natural_orientation = SDL_ORIENTATION_LANDSCAPE; + } else { + internal->placeholder.natural_orientation = SDL_ORIENTATION_PORTRAIT; + } + internal->placeholder.current_orientation = internal->orientation; + internal->placeholder.internal = internal; + + // During initialization, the displays will be added after enumeration is complete. + if (!video->initializing) { + internal->display = SDL_AddVideoDisplay(&internal->placeholder, true); + SDL_free(internal->placeholder.name); + SDL_zero(internal->placeholder); + } + } else { + SDL_SendDisplayEvent(dpy, SDL_EVENT_DISPLAY_ORIENTATION, internal->orientation, 0); + } +} + +static void display_handle_scale(void *data, + struct wl_output *output, + int32_t factor) +{ + SDL_DisplayData *internal = (SDL_DisplayData *)data; + internal->scale_factor = factor; +} + +static void display_handle_name(void *data, struct wl_output *wl_output, const char *name) +{ + SDL_DisplayData *internal = (SDL_DisplayData *)data; + + SDL_free(internal->wl_output_name); + internal->wl_output_name = SDL_strdup(name); +} + +static void display_handle_description(void *data, struct wl_output *wl_output, const char *description) +{ + SDL_DisplayData *internal = (SDL_DisplayData *)data; + + if (internal->display == 0) { + // The description, if available, supersedes the model name. + SDL_free(internal->placeholder.name); + internal->placeholder.name = SDL_strdup(description); + } +} + +static const struct wl_output_listener output_listener = { + display_handle_geometry, // Version 1 + display_handle_mode, // Version 1 + display_handle_done, // Version 2 + display_handle_scale, // Version 2 + display_handle_name, // Version 4 + display_handle_description // Version 4 +}; + +static void handle_output_image_description_changed(void *data, + struct wp_color_management_output_v1 *wp_color_management_output_v1) +{ + SDL_DisplayData *display = (SDL_DisplayData *)data; + // wl_display.done is called after this event, so the display HDR status will be updated there. + Wayland_GetColorInfoForOutput(display, false); +} + +static const struct wp_color_management_output_v1_listener wp_color_management_output_listener = { + handle_output_image_description_changed +}; + +static bool Wayland_add_display(SDL_VideoData *d, uint32_t id, uint32_t version) +{ + struct wl_output *output; + SDL_DisplayData *data; + + output = wl_registry_bind(d->registry, id, &wl_output_interface, version); + if (!output) { + return SDL_SetError("Failed to retrieve output."); + } + data = (SDL_DisplayData *)SDL_calloc(1, sizeof(*data)); + data->videodata = d; + data->output = output; + data->registry_id = id; + data->scale_factor = 1.0f; + + wl_output_add_listener(output, &output_listener, data); + SDL_WAYLAND_register_output(output); + + // Keep a list of outputs for sorting and deferred protocol initialization. + if (d->output_count == d->output_max) { + d->output_max += 4; + d->output_list = SDL_realloc(d->output_list, sizeof(SDL_DisplayData *) * d->output_max); + } + d->output_list[d->output_count++] = data; + + if (data->videodata->xdg_output_manager) { + data->xdg_output = zxdg_output_manager_v1_get_xdg_output(data->videodata->xdg_output_manager, output); + zxdg_output_v1_add_listener(data->xdg_output, &xdg_output_listener, data); + } + if (data->videodata->wp_color_manager_v1) { + data->wp_color_management_output = wp_color_manager_v1_get_output(data->videodata->wp_color_manager_v1, output); + wp_color_management_output_v1_add_listener(data->wp_color_management_output, &wp_color_management_output_listener, data); + Wayland_GetColorInfoForOutput(data, true); + } + return true; +} + +static void Wayland_free_display(SDL_VideoDisplay *display, bool send_event) +{ + if (display) { + SDL_DisplayData *display_data = display->internal; + + /* A preceding surface leave event is not guaranteed when an output is removed, + * so ensure that no window continues to hold a reference to a removed output. + */ + for (SDL_Window *window = SDL_GetVideoDevice()->windows; window; window = window->next) { + Wayland_RemoveOutputFromWindow(window->internal, display_data); + } + + SDL_free(display_data->wl_output_name); + + if (display_data->wp_color_management_output) { + Wayland_FreeColorInfoState(display_data->color_info_state); + wp_color_management_output_v1_destroy(display_data->wp_color_management_output); + } + + if (display_data->xdg_output) { + zxdg_output_v1_destroy(display_data->xdg_output); + } + + if (wl_output_get_version(display_data->output) >= WL_OUTPUT_RELEASE_SINCE_VERSION) { + wl_output_release(display_data->output); + } else { + wl_output_destroy(display_data->output); + } + + SDL_DelVideoDisplay(display->id, send_event); + } +} + +static void Wayland_FinalizeDisplays(SDL_VideoData *vid) +{ + Wayland_SortOutputs(vid); + for(int i = 0; i < vid->output_count; ++i) { + SDL_DisplayData *d = vid->output_list[i]; + d->display = SDL_AddVideoDisplay(&d->placeholder, false); + SDL_free(d->placeholder.name); + SDL_zero(d->placeholder); + } +} + +static void Wayland_init_xdg_output(SDL_VideoData *d) +{ + for (int i = 0; i < d->output_count; ++i) { + SDL_DisplayData *disp = d->output_list[i]; + disp->xdg_output = zxdg_output_manager_v1_get_xdg_output(disp->videodata->xdg_output_manager, disp->output); + zxdg_output_v1_add_listener(disp->xdg_output, &xdg_output_listener, disp); + } +} + +static void Wayland_InitColorManager(SDL_VideoData *d) +{ + for (int i = 0; i < d->output_count; ++i) { + SDL_DisplayData *disp = d->output_list[i]; + disp->wp_color_management_output = wp_color_manager_v1_get_output(disp->videodata->wp_color_manager_v1, disp->output); + wp_color_management_output_v1_add_listener(disp->wp_color_management_output, &wp_color_management_output_listener, disp); + Wayland_GetColorInfoForOutput(disp, true); + } +} + +static void handle_ping_xdg_wm_base(void *data, struct xdg_wm_base *xdg, uint32_t serial) +{ + xdg_wm_base_pong(xdg, serial); +} + +static const struct xdg_wm_base_listener shell_listener_xdg = { + handle_ping_xdg_wm_base +}; + +#ifdef HAVE_LIBDECOR_H +static void libdecor_error(struct libdecor *context, + enum libdecor_error error, + const char *message) +{ + SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "libdecor error (%d): %s", error, message); +} + +static struct libdecor_interface libdecor_interface = { + libdecor_error, +}; +#endif + +static void display_handle_global(void *data, struct wl_registry *registry, uint32_t id, + const char *interface, uint32_t version) +{ + SDL_VideoData *d = data; + + // printf("WAYLAND INTERFACE: %s\n", interface); + + if (SDL_strcmp(interface, "wl_compositor") == 0) { + d->compositor = wl_registry_bind(d->registry, id, &wl_compositor_interface, SDL_min(SDL_WL_COMPOSITOR_VERSION, version)); + } else if (SDL_strcmp(interface, "wl_output") == 0) { + Wayland_add_display(d, id, SDL_min(version, SDL_WL_OUTPUT_VERSION)); + } else if (SDL_strcmp(interface, "wl_seat") == 0) { + d->input->seat = wl_registry_bind(d->registry, id, &wl_seat_interface, SDL_min(SDL_WL_SEAT_VERSION, version)); + Wayland_input_initialize_seat(d); + } else if (SDL_strcmp(interface, "xdg_wm_base") == 0) { + d->shell.xdg = wl_registry_bind(d->registry, id, &xdg_wm_base_interface, SDL_min(version, 6)); + xdg_wm_base_add_listener(d->shell.xdg, &shell_listener_xdg, NULL); + } else if (SDL_strcmp(interface, "wl_shm") == 0) { + d->shm = wl_registry_bind(registry, id, &wl_shm_interface, 1); + } else if (SDL_strcmp(interface, "zwp_relative_pointer_manager_v1") == 0) { + d->relative_pointer_manager = wl_registry_bind(d->registry, id, &zwp_relative_pointer_manager_v1_interface, 1); + Wayland_input_init_relative_pointer(d); + } else if (SDL_strcmp(interface, "zwp_pointer_constraints_v1") == 0) { + d->pointer_constraints = wl_registry_bind(d->registry, id, &zwp_pointer_constraints_v1_interface, 1); + } else if (SDL_strcmp(interface, "zwp_keyboard_shortcuts_inhibit_manager_v1") == 0) { + d->key_inhibitor_manager = wl_registry_bind(d->registry, id, &zwp_keyboard_shortcuts_inhibit_manager_v1_interface, 1); + } else if (SDL_strcmp(interface, "zwp_idle_inhibit_manager_v1") == 0) { + d->idle_inhibit_manager = wl_registry_bind(d->registry, id, &zwp_idle_inhibit_manager_v1_interface, 1); + } else if (SDL_strcmp(interface, "xdg_activation_v1") == 0) { + d->activation_manager = wl_registry_bind(d->registry, id, &xdg_activation_v1_interface, 1); + } else if (SDL_strcmp(interface, "zwp_text_input_manager_v3") == 0) { + Wayland_create_text_input_manager(d, id); + } else if (SDL_strcmp(interface, "wl_data_device_manager") == 0) { + d->data_device_manager = wl_registry_bind(d->registry, id, &wl_data_device_manager_interface, SDL_min(3, version)); + Wayland_create_data_device(d); + } else if (SDL_strcmp(interface, "zwp_primary_selection_device_manager_v1") == 0) { + d->primary_selection_device_manager = wl_registry_bind(d->registry, id, &zwp_primary_selection_device_manager_v1_interface, 1); + Wayland_create_primary_selection_device(d); + } else if (SDL_strcmp(interface, "zxdg_decoration_manager_v1") == 0) { + d->decoration_manager = wl_registry_bind(d->registry, id, &zxdg_decoration_manager_v1_interface, 1); + } else if (SDL_strcmp(interface, "zwp_tablet_manager_v2") == 0) { + d->tablet_manager = wl_registry_bind(d->registry, id, &zwp_tablet_manager_v2_interface, 1); + Wayland_input_init_tablet_support(d->input, d->tablet_manager); + } else if (SDL_strcmp(interface, "zxdg_output_manager_v1") == 0) { + version = SDL_min(version, 3); // Versions 1 through 3 are supported. + d->xdg_output_manager = wl_registry_bind(d->registry, id, &zxdg_output_manager_v1_interface, version); + Wayland_init_xdg_output(d); + } else if (SDL_strcmp(interface, "wp_viewporter") == 0) { + d->viewporter = wl_registry_bind(d->registry, id, &wp_viewporter_interface, 1); + } else if (SDL_strcmp(interface, "wp_fractional_scale_manager_v1") == 0) { + d->fractional_scale_manager = wl_registry_bind(d->registry, id, &wp_fractional_scale_manager_v1_interface, 1); + } else if (SDL_strcmp(interface, "zwp_input_timestamps_manager_v1") == 0) { + d->input_timestamps_manager = wl_registry_bind(d->registry, id, &zwp_input_timestamps_manager_v1_interface, 1); + if (d->input) { + Wayland_RegisterTimestampListeners(d->input); + } + } else if (SDL_strcmp(interface, "wp_cursor_shape_manager_v1") == 0) { + d->cursor_shape_manager = wl_registry_bind(d->registry, id, &wp_cursor_shape_manager_v1_interface, 1); + if (d->input) { + Wayland_CreateCursorShapeDevice(d->input); + } + } else if (SDL_strcmp(interface, "zxdg_exporter_v2") == 0) { + d->zxdg_exporter_v2 = wl_registry_bind(d->registry, id, &zxdg_exporter_v2_interface, 1); + } else if (SDL_strcmp(interface, "xdg_wm_dialog_v1") == 0) { + d->xdg_wm_dialog_v1 = wl_registry_bind(d->registry, id, &xdg_wm_dialog_v1_interface, 1); + } else if (SDL_strcmp(interface, "wp_alpha_modifier_v1") == 0) { + d->wp_alpha_modifier_v1 = wl_registry_bind(d->registry, id, &wp_alpha_modifier_v1_interface, 1); + } else if (SDL_strcmp(interface, "xdg_toplevel_icon_manager_v1") == 0) { + d->xdg_toplevel_icon_manager_v1 = wl_registry_bind(d->registry, id, &xdg_toplevel_icon_manager_v1_interface, 1); + } else if (SDL_strcmp(interface, "frog_color_management_factory_v1") == 0) { + d->frog_color_management_factory_v1 = wl_registry_bind(d->registry, id, &frog_color_management_factory_v1_interface, 1); + } else if (SDL_strcmp(interface, "wp_color_manager_v1") == 0) { + d->wp_color_manager_v1 = wl_registry_bind(d->registry, id, &wp_color_manager_v1_interface, 1); + Wayland_InitColorManager(d); + } +} + +static void display_remove_global(void *data, struct wl_registry *registry, uint32_t id) +{ + SDL_VideoData *d = data; + + // We don't get an interface, just an ID, so assume it's a wl_output :shrug: + for (int i = 0; i < d->output_count; ++i) { + SDL_DisplayData *disp = d->output_list[i]; + if (disp->registry_id == id) { + Wayland_free_display(SDL_GetVideoDisplay(disp->display), true); + + if (i < d->output_count) { + SDL_memmove(&d->output_list[i], &d->output_list[i + 1], sizeof(SDL_DisplayData *) * (d->output_count - i - 1)); + } + + d->output_count--; + break; + } + } +} + +static const struct wl_registry_listener registry_listener = { + display_handle_global, + display_remove_global +}; + +#ifdef HAVE_LIBDECOR_H +static bool should_use_libdecor(SDL_VideoData *data, bool ignore_xdg) +{ + if (!SDL_WAYLAND_HAVE_WAYLAND_LIBDECOR) { + return false; + } + + if (!SDL_GetHintBoolean(SDL_HINT_VIDEO_WAYLAND_ALLOW_LIBDECOR, true)) { + return false; + } + + if (SDL_GetHintBoolean(SDL_HINT_VIDEO_WAYLAND_PREFER_LIBDECOR, false)) { + return true; + } + + if (ignore_xdg) { + return true; + } + + if (data->decoration_manager) { + return false; + } + + return true; +} +#endif + +bool Wayland_LoadLibdecor(SDL_VideoData *data, bool ignore_xdg) +{ +#ifdef HAVE_LIBDECOR_H + if (data->shell.libdecor != NULL) { + return true; // Already loaded! + } + if (should_use_libdecor(data, ignore_xdg)) { + data->shell.libdecor = libdecor_new(data->display, &libdecor_interface); + return data->shell.libdecor != NULL; + } +#endif + return false; +} + +bool Wayland_VideoInit(SDL_VideoDevice *_this) +{ + SDL_VideoData *data = _this->internal; + + data->xkb_context = WAYLAND_xkb_context_new(0); + if (!data->xkb_context) { + return SDL_SetError("Failed to create XKB context"); + } + + data->registry = wl_display_get_registry(data->display); + if (!data->registry) { + return SDL_SetError("Failed to get the Wayland registry"); + } + + wl_registry_add_listener(data->registry, ®istry_listener, data); + + // First roundtrip to receive all registry objects. + WAYLAND_wl_display_roundtrip(data->display); + + // Require viewports and xdg-output for display scaling. + if (data->scale_to_display_enabled) { + if (!data->viewporter) { + SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "wayland: Display scaling requires the missing 'wp_viewporter' protocol: disabling"); + data->scale_to_display_enabled = false; + } + if (!data->xdg_output_manager) { + SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "wayland: Display scaling requires the missing 'zxdg_output_manager_v1' protocol: disabling"); + data->scale_to_display_enabled = false; + } + } + + // Now that we have all the protocols, load libdecor if applicable + Wayland_LoadLibdecor(data, false); + + // Second roundtrip to receive all output events. + WAYLAND_wl_display_roundtrip(data->display); + + Wayland_FinalizeDisplays(data); + + Wayland_InitMouse(); + + WAYLAND_wl_display_flush(data->display); + + Wayland_InitKeyboard(_this); + + if (data->primary_selection_device_manager) { + _this->SetPrimarySelectionText = Wayland_SetPrimarySelectionText; + _this->GetPrimarySelectionText = Wayland_GetPrimarySelectionText; + _this->HasPrimarySelectionText = Wayland_HasPrimarySelectionText; + } + + data->initializing = false; + + return true; +} + +static bool Wayland_GetDisplayBounds(SDL_VideoDevice *_this, SDL_VideoDisplay *display, SDL_Rect *rect) +{ + SDL_VideoData *viddata = _this->internal; + SDL_DisplayData *internal = display->internal; + rect->x = internal->x; + rect->y = internal->y; + + // When an emulated, exclusive fullscreen window has focus, treat the mode dimensions as the display bounds. + if (display->fullscreen_window && + display->fullscreen_window->fullscreen_exclusive && + display->fullscreen_window->internal->active && + display->fullscreen_window->current_fullscreen_mode.w != 0 && + display->fullscreen_window->current_fullscreen_mode.h != 0) { + rect->w = display->fullscreen_window->current_fullscreen_mode.w; + rect->h = display->fullscreen_window->current_fullscreen_mode.h; + } else { + if (!viddata->scale_to_display_enabled) { + rect->w = display->current_mode->w; + rect->h = display->current_mode->h; + } else if (internal->transform & WL_OUTPUT_TRANSFORM_90) { + rect->w = internal->pixel_height; + rect->h = internal->pixel_width; + } else { + rect->w = internal->pixel_width; + rect->h = internal->pixel_height; + } + } + return true; +} + +static void Wayland_VideoCleanup(SDL_VideoDevice *_this) +{ + SDL_VideoData *data = _this->internal; + int i; + + Wayland_FiniMouse(data); + + for (i = _this->num_displays - 1; i >= 0; --i) { + SDL_VideoDisplay *display = _this->displays[i]; + Wayland_free_display(display, false); + } + SDL_free(data->output_list); + + Wayland_display_destroy_input(data); + + if (data->pointer_constraints) { + zwp_pointer_constraints_v1_destroy(data->pointer_constraints); + data->pointer_constraints = NULL; + } + + if (data->relative_pointer_manager) { + zwp_relative_pointer_manager_v1_destroy(data->relative_pointer_manager); + data->relative_pointer_manager = NULL; + } + + if (data->activation_manager) { + xdg_activation_v1_destroy(data->activation_manager); + data->activation_manager = NULL; + } + + if (data->idle_inhibit_manager) { + zwp_idle_inhibit_manager_v1_destroy(data->idle_inhibit_manager); + data->idle_inhibit_manager = NULL; + } + + if (data->key_inhibitor_manager) { + zwp_keyboard_shortcuts_inhibit_manager_v1_destroy(data->key_inhibitor_manager); + data->key_inhibitor_manager = NULL; + } + + Wayland_QuitKeyboard(_this); + + if (data->text_input_manager) { + zwp_text_input_manager_v3_destroy(data->text_input_manager); + data->text_input_manager = NULL; + } + + if (data->xkb_context) { + WAYLAND_xkb_context_unref(data->xkb_context); + data->xkb_context = NULL; + } + + if (data->tablet_manager) { + zwp_tablet_manager_v2_destroy((struct zwp_tablet_manager_v2 *)data->tablet_manager); + data->tablet_manager = NULL; + } + + if (data->data_device_manager) { + wl_data_device_manager_destroy(data->data_device_manager); + data->data_device_manager = NULL; + } + + if (data->shm) { + wl_shm_destroy(data->shm); + data->shm = NULL; + } + + if (data->shell.xdg) { + xdg_wm_base_destroy(data->shell.xdg); + data->shell.xdg = NULL; + } + + if (data->decoration_manager) { + zxdg_decoration_manager_v1_destroy(data->decoration_manager); + data->decoration_manager = NULL; + } + + if (data->xdg_output_manager) { + zxdg_output_manager_v1_destroy(data->xdg_output_manager); + data->xdg_output_manager = NULL; + } + + if (data->viewporter) { + wp_viewporter_destroy(data->viewporter); + data->viewporter = NULL; + } + + if (data->primary_selection_device_manager) { + zwp_primary_selection_device_manager_v1_destroy(data->primary_selection_device_manager); + data->primary_selection_device_manager = NULL; + } + + if (data->fractional_scale_manager) { + wp_fractional_scale_manager_v1_destroy(data->fractional_scale_manager); + data->fractional_scale_manager = NULL; + } + + if (data->input_timestamps_manager) { + zwp_input_timestamps_manager_v1_destroy(data->input_timestamps_manager); + data->input_timestamps_manager = NULL; + } + + if (data->cursor_shape_manager) { + wp_cursor_shape_manager_v1_destroy(data->cursor_shape_manager); + data->cursor_shape_manager = NULL; + } + + if (data->zxdg_exporter_v2) { + zxdg_exporter_v2_destroy(data->zxdg_exporter_v2); + data->zxdg_exporter_v2 = NULL; + } + + if (data->xdg_wm_dialog_v1) { + xdg_wm_dialog_v1_destroy(data->xdg_wm_dialog_v1); + data->xdg_wm_dialog_v1 = NULL; + } + + if (data->wp_alpha_modifier_v1) { + wp_alpha_modifier_v1_destroy(data->wp_alpha_modifier_v1); + data->wp_alpha_modifier_v1 = NULL; + } + + if (data->xdg_toplevel_icon_manager_v1) { + xdg_toplevel_icon_manager_v1_destroy(data->xdg_toplevel_icon_manager_v1); + data->xdg_toplevel_icon_manager_v1 = NULL; + } + + if (data->frog_color_management_factory_v1) { + frog_color_management_factory_v1_destroy(data->frog_color_management_factory_v1); + data->frog_color_management_factory_v1 = NULL; + } + + if (data->wp_color_manager_v1) { + wp_color_manager_v1_destroy(data->wp_color_manager_v1); + data->wp_color_manager_v1 = NULL; + } + + if (data->compositor) { + wl_compositor_destroy(data->compositor); + data->compositor = NULL; + } + + if (data->registry) { + wl_registry_destroy(data->registry); + data->registry = NULL; + } +} + +bool Wayland_VideoReconnect(SDL_VideoDevice *_this) +{ +#if 0 // TODO RECONNECT: Uncomment all when https://invent.kde.org/plasma/kwin/-/wikis/Restarting is completed + SDL_VideoData *data = _this->internal; + + SDL_Window *window = NULL; + + SDL_GLContext current_ctx = SDL_GL_GetCurrentContext(); + SDL_Window *current_window = SDL_GL_GetCurrentWindow(); + + SDL_GL_MakeCurrent(NULL, NULL); + Wayland_VideoCleanup(_this); + + SDL_ResetKeyboard(); + SDL_ResetMouse(); + if (WAYLAND_wl_display_reconnect(data->display) < 0) { + return false; + } + + Wayland_VideoInit(_this); + + window = _this->windows; + while (window) { + /* We're going to cheat _just_ for a second and strip the OpenGL flag. + * The Wayland driver actually forces it in CreateWindow, and + * RecreateWindow does a bunch of unloading/loading of libGL, so just + * strip the flag so RecreateWindow doesn't mess with the GL context, + * and CreateWindow will add it right back! + * -flibit + */ + window->flags &= ~SDL_WINDOW_OPENGL; + + SDL_RecreateWindow(window, window->flags); + window = window->next; + } + + Wayland_RecreateCursors(); + + if (current_window && current_ctx) { + SDL_GL_MakeCurrent (current_window, current_ctx); + } + return true; +#else + return false; +#endif // 0 +} + +void Wayland_VideoQuit(SDL_VideoDevice *_this) +{ + Wayland_VideoCleanup(_this); + +#ifdef HAVE_LIBDECOR_H + SDL_VideoData *data = _this->internal; + if (data->shell.libdecor) { + libdecor_unref(data->shell.libdecor); + data->shell.libdecor = NULL; + } +#endif +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvideo.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvideo.h new file mode 100644 index 0000000..8cde64c --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvideo.h @@ -0,0 +1,140 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_waylandvideo_h_ +#define SDL_waylandvideo_h_ + +#include +#include "wayland-util.h" + +#include "../SDL_sysvideo.h" +#include "../../core/linux/SDL_dbus.h" +#include "../../core/linux/SDL_ime.h" + +struct xkb_context; +struct SDL_WaylandInput; + +typedef struct +{ + struct wl_cursor_theme *theme; + int size; +} SDL_WaylandCursorTheme; + +typedef struct +{ + struct wl_list link; + char wl_output_name[]; +} SDL_WaylandConnectorName; + +struct SDL_VideoData +{ + bool initializing; + struct wl_display *display; + int display_disconnected; + struct wl_registry *registry; + struct wl_compositor *compositor; + struct wl_shm *shm; + SDL_WaylandCursorTheme *cursor_themes; + int num_cursor_themes; + struct wl_pointer *pointer; + struct + { + struct xdg_wm_base *xdg; +#ifdef HAVE_LIBDECOR_H + struct libdecor *libdecor; +#endif + } shell; + struct zwp_relative_pointer_manager_v1 *relative_pointer_manager; + struct zwp_pointer_constraints_v1 *pointer_constraints; + struct wp_cursor_shape_manager_v1 *cursor_shape_manager; + struct wl_data_device_manager *data_device_manager; + struct zwp_primary_selection_device_manager_v1 *primary_selection_device_manager; + struct zxdg_decoration_manager_v1 *decoration_manager; + struct zwp_keyboard_shortcuts_inhibit_manager_v1 *key_inhibitor_manager; + struct zwp_idle_inhibit_manager_v1 *idle_inhibit_manager; + struct xdg_activation_v1 *activation_manager; + struct zwp_text_input_manager_v3 *text_input_manager; + struct zxdg_output_manager_v1 *xdg_output_manager; + struct wp_viewporter *viewporter; + struct wp_fractional_scale_manager_v1 *fractional_scale_manager; + struct zwp_input_timestamps_manager_v1 *input_timestamps_manager; + struct zxdg_exporter_v2 *zxdg_exporter_v2; + struct xdg_wm_dialog_v1 *xdg_wm_dialog_v1; + struct wp_alpha_modifier_v1 *wp_alpha_modifier_v1; + struct xdg_toplevel_icon_manager_v1 *xdg_toplevel_icon_manager_v1; + struct frog_color_management_factory_v1 *frog_color_management_factory_v1; + struct wp_color_manager_v1 *wp_color_manager_v1; + struct zwp_tablet_manager_v2 *tablet_manager; + + struct xkb_context *xkb_context; + struct SDL_WaylandInput *input; + SDL_DisplayData **output_list; + int output_count; + int output_max; + + int relative_mouse_mode; + bool display_externally_owned; + + bool scale_to_display_enabled; +}; + +struct SDL_DisplayData +{ + SDL_VideoData *videodata; + struct wl_output *output; + struct zxdg_output_v1 *xdg_output; + struct wp_color_management_output_v1 *wp_color_management_output; + char *wl_output_name; + double scale_factor; + uint32_t registry_id; + int logical_width, logical_height; + int pixel_width, pixel_height; + int x, y, refresh, transform; + SDL_DisplayOrientation orientation; + int physical_width_mm, physical_height_mm; + bool has_logical_position, has_logical_size; + bool running_colorspace_event_queue; + SDL_HDROutputProperties HDR; + SDL_DisplayID display; + SDL_VideoDisplay placeholder; + int wl_output_done_count; + struct Wayland_ColorInfoState *color_info_state; +}; + +// Needed here to get wl_surface declaration, fixes GitHub#4594 +#include "SDL_waylanddyn.h" + +extern void SDL_WAYLAND_register_surface(struct wl_surface *surface); +extern void SDL_WAYLAND_register_output(struct wl_output *output); +extern bool SDL_WAYLAND_own_surface(struct wl_surface *surface); +extern bool SDL_WAYLAND_own_output(struct wl_output *output); + +extern SDL_WindowData *Wayland_GetWindowDataForOwnedSurface(struct wl_surface *surface); +void Wayland_AddWindowDataToExternalList(SDL_WindowData *data); +void Wayland_RemoveWindowDataFromExternalList(SDL_WindowData *data); + +extern bool Wayland_LoadLibdecor(SDL_VideoData *data, bool ignore_xdg); + +extern bool Wayland_VideoReconnect(SDL_VideoDevice *_this); + +#endif // SDL_waylandvideo_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvulkan.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvulkan.c new file mode 100644 index 0000000..956be46 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvulkan.c @@ -0,0 +1,203 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's + * SDL_x11vulkan.c. + */ + +#include "SDL_internal.h" + +#if defined(SDL_VIDEO_VULKAN) && defined(SDL_VIDEO_DRIVER_WAYLAND) + +#include "../SDL_vulkan_internal.h" + +#include "SDL_waylandvideo.h" +#include "SDL_waylandwindow.h" + +#include "SDL_waylandvulkan.h" + +#ifdef SDL_PLATFORM_OPENBSD +#define DEFAULT_VULKAN "libvulkan.so" +#else +#define DEFAULT_VULKAN "libvulkan.so.1" +#endif + +bool Wayland_Vulkan_LoadLibrary(SDL_VideoDevice *_this, const char *path) +{ + VkExtensionProperties *extensions = NULL; + Uint32 i, extensionCount = 0; + bool hasSurfaceExtension = false; + bool hasWaylandSurfaceExtension = false; + PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL; + if (_this->vulkan_config.loader_handle) { + return SDL_SetError("Vulkan already loaded"); + } + + // Load the Vulkan loader library + if (!path) { + path = SDL_GetHint(SDL_HINT_VULKAN_LIBRARY); + } + if (!path) { + path = DEFAULT_VULKAN; + } + _this->vulkan_config.loader_handle = SDL_LoadObject(path); + if (!_this->vulkan_config.loader_handle) { + return false; + } + SDL_strlcpy(_this->vulkan_config.loader_path, path, + SDL_arraysize(_this->vulkan_config.loader_path)); + vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction( + _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr"); + if (!vkGetInstanceProcAddr) { + goto fail; + } + _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr; + _this->vulkan_config.vkEnumerateInstanceExtensionProperties = + (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)( + VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"); + if (!_this->vulkan_config.vkEnumerateInstanceExtensionProperties) { + goto fail; + } + extensions = SDL_Vulkan_CreateInstanceExtensionsList( + (PFN_vkEnumerateInstanceExtensionProperties) + _this->vulkan_config.vkEnumerateInstanceExtensionProperties, + &extensionCount); + if (!extensions) { + goto fail; + } + for (i = 0; i < extensionCount; i++) { + if (SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) { + hasSurfaceExtension = true; + } else if (SDL_strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) { + hasWaylandSurfaceExtension = true; + } + } + SDL_free(extensions); + if (!hasSurfaceExtension) { + SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_SURFACE_EXTENSION_NAME " extension"); + goto fail; + } else if (!hasWaylandSurfaceExtension) { + SDL_SetError("Installed Vulkan doesn't implement the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME "extension"); + goto fail; + } + return true; + +fail: + SDL_UnloadObject(_this->vulkan_config.loader_handle); + _this->vulkan_config.loader_handle = NULL; + return false; +} + +void Wayland_Vulkan_UnloadLibrary(SDL_VideoDevice *_this) +{ + if (_this->vulkan_config.loader_handle) { + SDL_UnloadObject(_this->vulkan_config.loader_handle); + _this->vulkan_config.loader_handle = NULL; + } +} + +char const* const* Wayland_Vulkan_GetInstanceExtensions(SDL_VideoDevice *_this, Uint32 *count) +{ + static const char *const extensionsForWayland[] = { + VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME + }; + + if (count) { + *count = SDL_arraysize(extensionsForWayland); + } + + return extensionsForWayland; +} + +bool Wayland_Vulkan_CreateSurface(SDL_VideoDevice *_this, + SDL_Window *window, + VkInstance instance, + const struct VkAllocationCallbacks *allocator, + VkSurfaceKHR *surface) +{ + SDL_WindowData *windowData = window->internal; + PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = + (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr; + PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR = + (PFN_vkCreateWaylandSurfaceKHR)vkGetInstanceProcAddr( + instance, + "vkCreateWaylandSurfaceKHR"); + VkWaylandSurfaceCreateInfoKHR createInfo; + VkResult result; + + if (!_this->vulkan_config.loader_handle) { + return SDL_SetError("Vulkan is not loaded"); + } + + if (!vkCreateWaylandSurfaceKHR) { + return SDL_SetError(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME + " extension is not enabled in the Vulkan instance."); + } + SDL_zero(createInfo); + createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; + createInfo.pNext = NULL; + createInfo.flags = 0; + createInfo.display = windowData->waylandData->display; + createInfo.surface = windowData->surface; + result = vkCreateWaylandSurfaceKHR(instance, &createInfo, allocator, surface); + if (result != VK_SUCCESS) { + return SDL_SetError("vkCreateWaylandSurfaceKHR failed: %s", SDL_Vulkan_GetResultString(result)); + } + return true; +} + +void Wayland_Vulkan_DestroySurface(SDL_VideoDevice *_this, + VkInstance instance, + VkSurfaceKHR surface, + const struct VkAllocationCallbacks *allocator) +{ + if (_this->vulkan_config.loader_handle) { + SDL_Vulkan_DestroySurface_Internal(_this->vulkan_config.vkGetInstanceProcAddr, instance, surface, allocator); + } +} + +bool Wayland_Vulkan_GetPresentationSupport(SDL_VideoDevice *_this, + VkInstance instance, + VkPhysicalDevice physicalDevice, + Uint32 queueFamilyIndex) +{ + PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = + (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr; + PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR vkGetPhysicalDeviceWaylandPresentationSupportKHR = + (PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR)vkGetInstanceProcAddr( + instance, + "vkGetPhysicalDeviceWaylandPresentationSupportKHR"); + + if (!_this->vulkan_config.loader_handle) { + return SDL_SetError("Vulkan is not loaded"); + } + + if (!vkGetPhysicalDeviceWaylandPresentationSupportKHR) { + return SDL_SetError(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME " extension is not enabled in the Vulkan instance."); + } + + return vkGetPhysicalDeviceWaylandPresentationSupportKHR(physicalDevice, + queueFamilyIndex, + _this->internal->display); +} + +#endif diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvulkan.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvulkan.h new file mode 100644 index 0000000..58be0bc --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandvulkan.h @@ -0,0 +1,55 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's + * SDL_x11vulkan.h. + */ + +#include "SDL_internal.h" + +#ifndef SDL_waylandvulkan_h_ +#define SDL_waylandvulkan_h_ + +#include + +#if defined(SDL_VIDEO_VULKAN) && defined(SDL_VIDEO_DRIVER_WAYLAND) + +extern bool Wayland_Vulkan_LoadLibrary(SDL_VideoDevice *_this, const char *path); +extern void Wayland_Vulkan_UnloadLibrary(SDL_VideoDevice *_this); +extern char const* const* Wayland_Vulkan_GetInstanceExtensions(SDL_VideoDevice *_this, Uint32 *count); +extern bool Wayland_Vulkan_CreateSurface(SDL_VideoDevice *_this, + SDL_Window *window, + VkInstance instance, + const struct VkAllocationCallbacks *allocator, + VkSurfaceKHR *surface); +extern void Wayland_Vulkan_DestroySurface(SDL_VideoDevice *_this, + VkInstance instance, + VkSurfaceKHR surface, + const struct VkAllocationCallbacks *allocator); +extern bool Wayland_Vulkan_GetPresentationSupport(SDL_VideoDevice *_this, + VkInstance instance, + VkPhysicalDevice physicalDevice, + Uint32 queueFamilyIndex); + +#endif + +#endif // SDL_waylandvulkan_h_ diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandwindow.c b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandwindow.c new file mode 100644 index 0000000..212fd54 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandwindow.c @@ -0,0 +1,3125 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifdef SDL_VIDEO_DRIVER_WAYLAND + +#include + +#include "../SDL_sysvideo.h" +#include "../../events/SDL_events_c.h" +#include "../../core/unix/SDL_appid.h" +#include "../SDL_egl_c.h" +#include "SDL_waylandevents_c.h" +#include "SDL_waylandwindow.h" +#include "SDL_waylandvideo.h" +#include "../../SDL_hints_c.h" +#include "SDL_waylandcolor.h" + +#include "alpha-modifier-v1-client-protocol.h" +#include "xdg-shell-client-protocol.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" +#include "idle-inhibit-unstable-v1-client-protocol.h" +#include "xdg-activation-v1-client-protocol.h" +#include "viewporter-client-protocol.h" +#include "fractional-scale-v1-client-protocol.h" +#include "xdg-foreign-unstable-v2-client-protocol.h" +#include "xdg-dialog-v1-client-protocol.h" +#include "frog-color-management-v1-client-protocol.h" +#include "xdg-toplevel-icon-v1-client-protocol.h" +#include "color-management-v1-client-protocol.h" + +#ifdef HAVE_LIBDECOR_H +#include +#endif + +static double GetWindowScale(SDL_Window *window) +{ + return (window->flags & SDL_WINDOW_HIGH_PIXEL_DENSITY) || window->internal->scale_to_display ? window->internal->scale_factor : 1.0; +} + +// These are point->pixel->point round trip safe; the inverse is not round trip safe due to rounding. +static int PointToPixel(SDL_Window *window, int point) +{ + /* Rounds halfway away from zero as per the Wayland fractional scaling protocol spec. + * Wayland scale units are in units of 1/120, so the offset is required to correct for + * rounding errors when using certain scale values. + */ + return point ? SDL_max((int)SDL_lround((double)point * GetWindowScale(window) + 1e-6), 1) : 0; +} + +static int PixelToPoint(SDL_Window *window, int pixel) +{ + return pixel ? SDL_max((int)SDL_lround((double)pixel / GetWindowScale(window)), 1) : 0; +} + +/* According to the Wayland spec: + * + * "If the [fullscreen] surface doesn't cover the whole output, the compositor will + * position the surface in the center of the output and compensate with border fill + * covering the rest of the output. The content of the border fill is undefined, but + * should be assumed to be in some way that attempts to blend into the surrounding area + * (e.g. solid black)." + * + * - KDE, as of 5.27, still doesn't do this + * - GNOME prior to 43 didn't do this (older versions are still found in many LTS distros) + * + * Default to 'stretch' for now, until things have moved forward enough that the default + * can be changed to 'aspect'. + */ +enum WaylandModeScale +{ + WAYLAND_MODE_SCALE_UNDEFINED, + WAYLAND_MODE_SCALE_ASPECT, + WAYLAND_MODE_SCALE_STRETCH, + WAYLAND_MODE_SCALE_NONE +}; + +static enum WaylandModeScale GetModeScaleMethod(void) +{ + static enum WaylandModeScale scale_mode = WAYLAND_MODE_SCALE_UNDEFINED; + + if (scale_mode == WAYLAND_MODE_SCALE_UNDEFINED) { + const char *scale_hint = SDL_GetHint(SDL_HINT_VIDEO_WAYLAND_MODE_SCALING); + + if (scale_hint) { + if (!SDL_strcasecmp(scale_hint, "aspect")) { + scale_mode = WAYLAND_MODE_SCALE_ASPECT; + } else if (!SDL_strcasecmp(scale_hint, "none")) { + scale_mode = WAYLAND_MODE_SCALE_NONE; + } else { + scale_mode = WAYLAND_MODE_SCALE_STRETCH; + } + } else { + scale_mode = WAYLAND_MODE_SCALE_STRETCH; + } + } + + return scale_mode; +} + +static void GetBufferSize(SDL_Window *window, int *width, int *height) +{ + SDL_WindowData *data = window->internal; + int buf_width; + int buf_height; + + // Exclusive fullscreen modes always have a pixel density of 1 + if (data->is_fullscreen && window->fullscreen_exclusive) { + buf_width = window->current_fullscreen_mode.w; + buf_height = window->current_fullscreen_mode.h; + } else if (!data->scale_to_display) { + // Round fractional backbuffer sizes halfway away from zero. + buf_width = PointToPixel(window, data->requested.logical_width); + buf_height = PointToPixel(window, data->requested.logical_height); + } else { + buf_width = data->requested.pixel_width; + buf_height = data->requested.pixel_height; + } + + if (width) { + *width = buf_width; + } + if (height) { + *height = buf_height; + } +} + +static void SetMinMaxDimensions(SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + int min_width, min_height, max_width, max_height; + + if ((window->flags & SDL_WINDOW_FULLSCREEN) || wind->fullscreen_deadline_count) { + min_width = 0; + min_height = 0; + max_width = 0; + max_height = 0; + } else if (window->flags & SDL_WINDOW_RESIZABLE) { + int adj_w = SDL_max(window->min_w, wind->system_limits.min_width); + int adj_h = SDL_max(window->min_h, wind->system_limits.min_height); + if (wind->scale_to_display) { + adj_w = PixelToPoint(window, adj_w); + adj_h = PixelToPoint(window, adj_h); + } + min_width = adj_w; + min_height = adj_h; + + adj_w = window->max_w ? SDL_max(window->max_w, wind->system_limits.min_width) : 0; + adj_h = window->max_h ? SDL_max(window->max_h, wind->system_limits.min_height) : 0; + if (wind->scale_to_display) { + adj_w = PixelToPoint(window, adj_w); + adj_h = PixelToPoint(window, adj_h); + } + max_width = adj_w; + max_height = adj_h; + } else { + min_width = wind->current.logical_width; + min_height = wind->current.logical_height; + max_width = wind->current.logical_width; + max_height = wind->current.logical_height; + } + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (!wind->shell_surface.libdecor.initial_configure_seen || !wind->shell_surface.libdecor.frame) { + return; // Can't do anything yet, wait for ShowWindow + } + /* No need to change these values if the window is non-resizable, + * as libdecor will just overwrite them internally. + */ + if (libdecor_frame_has_capability(wind->shell_surface.libdecor.frame, LIBDECOR_ACTION_RESIZE)) { + libdecor_frame_set_min_content_size(wind->shell_surface.libdecor.frame, + min_width, + min_height); + libdecor_frame_set_max_content_size(wind->shell_surface.libdecor.frame, + max_width, + max_height); + } + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + if (wind->shell_surface.xdg.toplevel.xdg_toplevel == NULL) { + return; // Can't do anything yet, wait for ShowWindow + } + xdg_toplevel_set_min_size(wind->shell_surface.xdg.toplevel.xdg_toplevel, + min_width, + min_height); + xdg_toplevel_set_max_size(wind->shell_surface.xdg.toplevel.xdg_toplevel, + max_width, + max_height); + } +} + +static void EnsurePopupPositionIsValid(SDL_Window *window, int *x, int *y) +{ + int adj_count = 0; + + /* Per the xdg-positioner spec, child popup windows must intersect or at + * least be partially adjacent to the parent window. + * + * Failure to ensure this on a compositor that enforces this restriction + * can result in behavior ranging from the window being spuriously closed + * to a protocol violation. + */ + if (*x + window->w < 0) { + *x = -window->w; + ++adj_count; + } + if (*y + window->h < 0) { + *y = -window->h; + ++adj_count; + } + if (*x > window->parent->w) { + *x = window->parent->w; + ++adj_count; + } + if (*y > window->parent->h) { + *y = window->parent->h; + ++adj_count; + } + + /* If adjustment was required on the x and y axes, the popup is aligned with + * the parent corner-to-corner and is neither overlapping nor adjacent, so it + * must be nudged by 1 to be considered adjacent. + */ + if (adj_count > 1) { + *x += *x < 0 ? 1 : -1; + } +} + +static void AdjustPopupOffset(SDL_Window *popup, int *x, int *y) +{ + // Adjust the popup positioning, if necessary +#ifdef HAVE_LIBDECOR_H + if (popup->parent->internal->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + int adj_x, adj_y; + libdecor_frame_translate_coordinate(popup->parent->internal->shell_surface.libdecor.frame, + *x, *y, &adj_x, &adj_y); + *x = adj_x; + *y = adj_y; + } +#endif +} + +static void RepositionPopup(SDL_Window *window, bool use_current_position) +{ + SDL_WindowData *wind = window->internal; + + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP && + wind->shell_surface.xdg.popup.xdg_positioner && + xdg_popup_get_version(wind->shell_surface.xdg.popup.xdg_popup) >= XDG_POPUP_REPOSITION_SINCE_VERSION) { + int x = use_current_position ? window->x : window->pending.x; + int y = use_current_position ? window->y : window->pending.y; + + EnsurePopupPositionIsValid(window, &x, &y); + if (wind->scale_to_display) { + x = PixelToPoint(window->parent, x); + y = PixelToPoint(window->parent, y); + } + AdjustPopupOffset(window, &x, &y); + xdg_positioner_set_anchor_rect(wind->shell_surface.xdg.popup.xdg_positioner, 0, 0, window->parent->internal->current.logical_width, window->parent->internal->current.logical_height); + xdg_positioner_set_size(wind->shell_surface.xdg.popup.xdg_positioner, wind->current.logical_width, wind->current.logical_height); + xdg_positioner_set_offset(wind->shell_surface.xdg.popup.xdg_positioner, x, y); + xdg_popup_reposition(wind->shell_surface.xdg.popup.xdg_popup, + wind->shell_surface.xdg.popup.xdg_positioner, + 0); + } +} + +static void SetSurfaceOpaqueRegion(SDL_WindowData *wind, bool is_opaque) +{ + SDL_VideoData *viddata = wind->waylandData; + + if (is_opaque) { + struct wl_region *region = wl_compositor_create_region(viddata->compositor); + wl_region_add(region, 0, 0, + wind->current.logical_width, wind->current.logical_height); + wl_surface_set_opaque_region(wind->surface, region); + wl_region_destroy(region); + } else { + wl_surface_set_opaque_region(wind->surface, NULL); + } +} + +static bool ConfigureWindowGeometry(SDL_Window *window) +{ + SDL_WindowData *data = window->internal; + const double scale_factor = GetWindowScale(window); + const int old_pixel_width = data->current.pixel_width; + const int old_pixel_height = data->current.pixel_height; + int window_width, window_height; + bool window_size_changed; + + // Throttle interactive resize events to once per refresh cycle to prevent lag. + if (data->resizing) { + data->resizing = false; + + if (data->drop_interactive_resizes) { + return false; + } else { + data->drop_interactive_resizes = true; + } + } + + // Set the drawable backbuffer size. + GetBufferSize(window, &data->current.pixel_width, &data->current.pixel_height); + const bool buffer_size_changed = data->current.pixel_width != old_pixel_width || + data->current.pixel_height != old_pixel_height; + + if (data->egl_window && buffer_size_changed) { + WAYLAND_wl_egl_window_resize(data->egl_window, + data->current.pixel_width, + data->current.pixel_height, + 0, 0); + } + + if (data->is_fullscreen && window->fullscreen_exclusive) { + int output_width; + int output_height; + window_width = window->current_fullscreen_mode.w; + window_height = window->current_fullscreen_mode.h; + + output_width = data->requested.logical_width; + output_height = data->requested.logical_height; + + switch (GetModeScaleMethod()) { + case WAYLAND_MODE_SCALE_NONE: + /* The Wayland spec states that the advertised fullscreen dimensions are a maximum. + * Windows can request a smaller size, but exceeding these dimensions is a protocol violation, + * thus, modes that exceed the output size still need to be scaled with a viewport. + */ + if (window_width <= output_width && window_height <= output_height) { + output_width = window_width; + output_height = window_height; + + break; + } + SDL_FALLTHROUGH; + case WAYLAND_MODE_SCALE_ASPECT: + { + const float output_ratio = (float)output_width / (float)output_height; + const float mode_ratio = (float)window_width / (float)window_height; + + if (output_ratio > mode_ratio) { + output_width = SDL_lroundf((float)window_width * ((float)output_height / (float)window_height)); + } else if (output_ratio < mode_ratio) { + output_height = SDL_lroundf((float)window_height * ((float)output_width / (float)window_width)); + } + } break; + default: + break; + } + + window_size_changed = window_width != window->w || window_height != window->h || + data->current.logical_width != output_width || data->current.logical_height != output_height; + + if (window_size_changed || buffer_size_changed) { + if (data->viewport) { + wp_viewport_set_destination(data->viewport, output_width, output_height); + + data->current.logical_width = output_width; + data->current.logical_height = output_height; + } else { + // Calculate the integer scale from the mode and output. + const int32_t int_scale = SDL_max(window->current_fullscreen_mode.w / output_width, 1); + + wl_surface_set_buffer_scale(data->surface, int_scale); + data->current.logical_width = window->current_fullscreen_mode.w; + data->current.logical_height = window->current_fullscreen_mode.h; + } + + data->pointer_scale.x = (double)window_width / (double)data->current.logical_width; + data->pointer_scale.y = (double)window_height / (double)data->current.logical_height; + } + } else { + window_width = data->requested.logical_width; + window_height = data->requested.logical_height; + + window_size_changed = window_width != data->current.logical_width || window_height != data->current.logical_height; + + if (window_size_changed || buffer_size_changed) { + if (data->viewport) { + wp_viewport_set_destination(data->viewport, window_width, window_height); + } else if (window->flags & SDL_WINDOW_HIGH_PIXEL_DENSITY) { + // Don't change this if the DPI awareness flag is unset, as an application may have set this manually on a custom or external surface. + wl_surface_set_buffer_scale(data->surface, (int32_t)scale_factor); + } + + // Clamp the physical window size to the system minimum required size. + data->current.logical_width = SDL_max(window_width, data->system_limits.min_width); + data->current.logical_height = SDL_max(window_height, data->system_limits.min_height); + + if (!data->scale_to_display) { + data->pointer_scale.x = 1.0; + data->pointer_scale.y = 1.0; + } else { + data->pointer_scale.x = scale_factor; + data->pointer_scale.y = scale_factor; + } + } + } + + /* + * The surface geometry, opaque region and pointer confinement region only + * need to be recalculated if the output size has changed. + */ + if (window_size_changed) { + /* XXX: This is a hack and only set on the xdg-toplevel path when viewports + * aren't supported to avoid a potential protocol violation if a buffer + * with an old size is committed. + */ + if (!data->viewport && data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL && data->shell_surface.xdg.surface) { + xdg_surface_set_window_geometry(data->shell_surface.xdg.surface, 0, 0, data->current.logical_width, data->current.logical_height); + } + + SetSurfaceOpaqueRegion(data, !(window->flags & SDL_WINDOW_TRANSPARENT) && window->opacity == 1.0f); + + // Ensure that child popup windows are still in bounds. + for (SDL_Window *child = window->first_child; child; child = child->next_sibling) { + RepositionPopup(child, true); + } + } + + /* Update the min/max dimensions, primarily if the state was changed, and for non-resizable + * xdg-toplevel windows where the limits should match the window size. + */ + SetMinMaxDimensions(window); + + // Unconditionally send the window and drawable size, the video core will deduplicate when required. + if (!data->scale_to_display) { + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_RESIZED, window_width, window_height); + } else { + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_RESIZED, data->current.pixel_width, data->current.pixel_height); + } + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED, data->current.pixel_width, data->current.pixel_height); + + /* Send an exposure event if the window is in the shown state and the size has changed, + * even if the window is occluded, as the client needs to commit a new frame for the + * changes to take effect. + * + * The occlusion state is immediately set again afterward, if necessary. + */ + if (data->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_SHOWN) { + if ((buffer_size_changed || window_size_changed) || + (!data->suspended && (window->flags & SDL_WINDOW_OCCLUDED))) { + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_EXPOSED, 0, 0); + } + + if (data->suspended) { + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_OCCLUDED, 0, 0); + } + } + + return true; +} + +static void CommitLibdecorFrame(SDL_Window *window) +{ +#ifdef HAVE_LIBDECOR_H + SDL_WindowData *wind = window->internal; + + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR && wind->shell_surface.libdecor.frame) { + struct libdecor_state *state = libdecor_state_new(wind->current.logical_width, wind->current.logical_height); + libdecor_frame_commit(wind->shell_surface.libdecor.frame, state, NULL); + libdecor_state_free(state); + } +#endif +} + +static void fullscreen_deadline_handler(void *data, struct wl_callback *callback, uint32_t callback_data) +{ + // Get the window from the ID as it may have been destroyed + SDL_WindowID windowID = (SDL_WindowID)((uintptr_t)data); + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (window && window->internal) { + window->internal->fullscreen_deadline_count--; + } + + wl_callback_destroy(callback); +} + +static struct wl_callback_listener fullscreen_deadline_listener = { + fullscreen_deadline_handler +}; + +static void maximized_restored_deadline_handler(void *data, struct wl_callback *callback, uint32_t callback_data) +{ + // Get the window from the ID as it may have been destroyed + SDL_WindowID windowID = (SDL_WindowID)((uintptr_t)data); + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (window && window->internal) { + window->internal->maximized_restored_deadline_count--; + } + + wl_callback_destroy(callback); +} + +static struct wl_callback_listener maximized_restored_deadline_listener = { + maximized_restored_deadline_handler +}; + +static void FlushPendingEvents(SDL_Window *window) +{ + // Serialize and restore the pending flags, as they may be overwritten while flushing. + const bool last_position_pending = window->last_position_pending; + const bool last_size_pending = window->last_size_pending; + + while (window->internal->fullscreen_deadline_count || window->internal->maximized_restored_deadline_count) { + WAYLAND_wl_display_roundtrip(window->internal->waylandData->display); + } + + window->last_position_pending = last_position_pending; + window->last_size_pending = last_size_pending; +} + +/* While we can't get window position from the compositor, we do at least know + * what monitor we're on, so let's send move events that put the window at the + * center of the whatever display the wl_surface_listener events give us. + */ +static void Wayland_move_window(SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + SDL_DisplayData *display; + SDL_DisplayID *displays; + + if (wind->outputs && wind->num_outputs) { + display = wind->outputs[wind->num_outputs - 1]; + } else { + // A window may not be on any displays if minimized. + return; + } + + displays = SDL_GetDisplays(NULL); + if (displays) { + for (int i = 0; displays[i]; ++i) { + if (SDL_GetDisplayDriverData(displays[i]) == display) { + /* We want to send a very very specific combination here: + * + * 1. A coordinate that tells the application what display we're on + * 2. Exactly (0, 0) + * + * Part 1 is useful information but is also really important for + * ensuring we end up on the right display for fullscreen, while + * part 2 is important because numerous applications use a specific + * combination of GetWindowPosition and GetGlobalMouseState, and of + * course neither are supported by Wayland. Since global mouse will + * fall back to just GetMouseState, we need the window position to + * be zero so the cursor math works without it going off in some + * random direction. See UE5 Editor for a notable example of this! + * + * This may be an issue some day if we're ever able to implement + * SDL_GetDisplayUsableBounds! + * + * -flibit + */ + + if (wind->last_displayID != displays[i]) { + wind->last_displayID = displays[i]; + if (wind->shell_surface_type != WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP) { + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_MOVED, display->x, display->y); + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_DISPLAY_CHANGED, wind->last_displayID, 0); + } + } + break; + } + } + SDL_free(displays); + } +} + +static void SetFullscreen(SDL_Window *window, struct wl_output *output) +{ + SDL_WindowData *wind = window->internal; + SDL_VideoData *viddata = wind->waylandData; + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (!wind->shell_surface.libdecor.frame) { + return; // Can't do anything yet, wait for ShowWindow + } + + wind->fullscreen_exclusive = output ? window->fullscreen_exclusive : false; + ++wind->fullscreen_deadline_count; + if (output) { + Wayland_SetWindowResizable(SDL_GetVideoDevice(), window, true); + wl_surface_commit(wind->surface); + + libdecor_frame_set_fullscreen(wind->shell_surface.libdecor.frame, output); + } else { + libdecor_frame_unset_fullscreen(wind->shell_surface.libdecor.frame); + } + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + if (wind->shell_surface.xdg.toplevel.xdg_toplevel == NULL) { + return; // Can't do anything yet, wait for ShowWindow + } + + wind->fullscreen_exclusive = output ? window->fullscreen_exclusive : false; + ++wind->fullscreen_deadline_count; + if (output) { + Wayland_SetWindowResizable(SDL_GetVideoDevice(), window, true); + wl_surface_commit(wind->surface); + + xdg_toplevel_set_fullscreen(wind->shell_surface.xdg.toplevel.xdg_toplevel, output); + } else { + xdg_toplevel_unset_fullscreen(wind->shell_surface.xdg.toplevel.xdg_toplevel); + } + } + + // Queue a deadline event + struct wl_callback *cb = wl_display_sync(viddata->display); + wl_callback_add_listener(cb, &fullscreen_deadline_listener, (void *)((uintptr_t)window->id)); +} + +static void UpdateWindowFullscreen(SDL_Window *window, bool fullscreen) +{ + SDL_WindowData *wind = window->internal; + + wind->is_fullscreen = fullscreen; + + if (fullscreen) { + if (!(window->flags & SDL_WINDOW_FULLSCREEN)) { + SDL_copyp(&window->current_fullscreen_mode, &window->requested_fullscreen_mode); + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_ENTER_FULLSCREEN, 0, 0); + SDL_UpdateFullscreenMode(window, SDL_FULLSCREEN_OP_ENTER, false); + + /* Set the output for exclusive fullscreen windows when entering fullscreen from a + * compositor event, or if the fullscreen parameters were changed between the initial + * fullscreen request and now, to ensure that the window is on the correct output, + * as requested by the client. + */ + if (window->fullscreen_exclusive && (!wind->fullscreen_exclusive || !wind->fullscreen_was_positioned)) { + SDL_VideoDisplay *disp = SDL_GetVideoDisplay(window->current_fullscreen_mode.displayID); + if (disp) { + wind->fullscreen_was_positioned = true; + SetFullscreen(window, disp->internal->output); + } + } + } + } else { + // Don't change the fullscreen flags if the window is hidden or being hidden. + if ((window->flags & SDL_WINDOW_FULLSCREEN) && !window->is_hiding && !(window->flags & SDL_WINDOW_HIDDEN)) { + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_LEAVE_FULLSCREEN, 0, 0); + SDL_UpdateFullscreenMode(window, SDL_FULLSCREEN_OP_LEAVE, false); + wind->fullscreen_was_positioned = false; + + /* Send a move event, in case it was deferred while the fullscreen window was moving and + * on multiple outputs. + */ + Wayland_move_window(window); + } + } +} + +static const struct wl_callback_listener surface_frame_listener; + +static void surface_frame_done(void *data, struct wl_callback *cb, uint32_t time) +{ + SDL_WindowData *wind = (SDL_WindowData *)data; + + /* XXX: This is needed to work around an Nvidia egl-wayland bug due to buffer coordinates + * being used with wl_surface_damage, which causes part of the output to not be + * updated when using a viewport with an output region larger than the source region. + */ + if (wl_compositor_get_version(wind->waylandData->compositor) >= WL_SURFACE_DAMAGE_BUFFER_SINCE_VERSION) { + wl_surface_damage_buffer(wind->surface, 0, 0, SDL_MAX_SINT32, SDL_MAX_SINT32); + } else { + wl_surface_damage(wind->surface, 0, 0, SDL_MAX_SINT32, SDL_MAX_SINT32); + } + + wind->drop_interactive_resizes = false; + + if (wind->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_FRAME) { + wind->shell_surface_status = WAYLAND_SHELL_SURFACE_STATUS_SHOWN; + + // If any child windows are waiting on this window to be shown, show them now + for (SDL_Window *w = wind->sdlwindow->first_child; w; w = w->next_sibling) { + if (w->internal->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_SHOW_PENDING) { + Wayland_ShowWindow(SDL_GetVideoDevice(), w); + } else if (w->internal->reparenting_required) { + Wayland_SetWindowParent(SDL_GetVideoDevice(), w, w->parent); + if (w->flags & SDL_WINDOW_MODAL) { + Wayland_SetWindowModal(SDL_GetVideoDevice(), w, true); + } + } + } + + /* If the window was initially set to the suspended state, send the occluded event now, + * as we don't want to mark the window as occluded until at least one frame has been submitted. + */ + if (wind->suspended) { + SDL_SendWindowEvent(wind->sdlwindow, SDL_EVENT_WINDOW_OCCLUDED, 0, 0); + } + } + + wl_callback_destroy(cb); + wind->surface_frame_callback = wl_surface_frame(wind->surface); + wl_callback_add_listener(wind->surface_frame_callback, &surface_frame_listener, data); +} + +static const struct wl_callback_listener surface_frame_listener = { + surface_frame_done +}; + +static const struct wl_callback_listener gles_swap_frame_listener; + +static void gles_swap_frame_done(void *data, struct wl_callback *cb, uint32_t time) +{ + SDL_WindowData *wind = (SDL_WindowData *)data; + SDL_SetAtomicInt(&wind->swap_interval_ready, 1); // mark window as ready to present again. + + // reset this callback to fire again once a new frame was presented and compositor wants the next one. + wind->gles_swap_frame_callback = wl_surface_frame(wind->gles_swap_frame_surface_wrapper); + wl_callback_destroy(cb); + wl_callback_add_listener(wind->gles_swap_frame_callback, &gles_swap_frame_listener, data); +} + +static const struct wl_callback_listener gles_swap_frame_listener = { + gles_swap_frame_done +}; + +static void handle_configure_xdg_shell_surface(void *data, struct xdg_surface *xdg, uint32_t serial) +{ + SDL_WindowData *wind = (SDL_WindowData *)data; + SDL_Window *window = wind->sdlwindow; + + if (ConfigureWindowGeometry(window)) { + xdg_surface_ack_configure(xdg, serial); + } + + wind->shell_surface.xdg.initial_configure_seen = true; +} + +static const struct xdg_surface_listener shell_surface_listener_xdg = { + handle_configure_xdg_shell_surface +}; + +static void handle_configure_xdg_toplevel(void *data, + struct xdg_toplevel *xdg_toplevel, + int32_t width, + int32_t height, + struct wl_array *states) +{ + SDL_WindowData *wind = (SDL_WindowData *)data; + SDL_Window *window = wind->sdlwindow; + + enum xdg_toplevel_state *state; + bool fullscreen = false; + bool maximized = false; + bool floating = true; + bool tiled = false; + bool active = false; + bool resizing = false; + bool suspended = false; + wl_array_for_each (state, states) { + switch (*state) { + case XDG_TOPLEVEL_STATE_FULLSCREEN: + fullscreen = true; + floating = false; + break; + case XDG_TOPLEVEL_STATE_MAXIMIZED: + maximized = true; + floating = false; + break; + case XDG_TOPLEVEL_STATE_RESIZING: + resizing = true; + break; + case XDG_TOPLEVEL_STATE_ACTIVATED: + active = true; + break; + case XDG_TOPLEVEL_STATE_TILED_LEFT: + case XDG_TOPLEVEL_STATE_TILED_RIGHT: + case XDG_TOPLEVEL_STATE_TILED_TOP: + case XDG_TOPLEVEL_STATE_TILED_BOTTOM: + tiled = true; + floating = false; + break; + case XDG_TOPLEVEL_STATE_SUSPENDED: + suspended = true; + break; + default: + break; + } + } + + UpdateWindowFullscreen(window, fullscreen); + + /* Always send a maximized/restore event; if the event is redundant it will + * automatically be discarded (see src/events/SDL_windowevents.c) + * + * No, we do not get minimize events from xdg-shell, however, the minimized + * state can be programmatically set. The meaning of 'minimized' is compositor + * dependent, but in general, we can assume that the flag should remain set until + * the next focused configure event occurs. + */ + if (active || !(window->flags & SDL_WINDOW_MINIMIZED)) { + if (window->flags & SDL_WINDOW_MINIMIZED) { + // If we were minimized, send a restored event before possibly sending maximized. + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_RESTORED, 0, 0); + } + SDL_SendWindowEvent(window, + (maximized && !fullscreen) ? SDL_EVENT_WINDOW_MAXIMIZED : SDL_EVENT_WINDOW_RESTORED, + 0, 0); + } + + if (!fullscreen) { + /* xdg_toplevel spec states that this is a suggestion. + * Ignore if less than or greater than max/min size. + */ + if (window->flags & SDL_WINDOW_RESIZABLE) { + if (width == 0 || height == 0) { + /* This happens when the compositor indicates that the size is + * up to the client, so use the cached window size here. + */ + if (floating) { + width = window->floating.w; + height = window->floating.h; + + // Clamp the window to the toplevel bounds, if any are set. + if (wind->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_CONFIGURE && + wind->toplevel_bounds.width && wind->toplevel_bounds.height) { + width = SDL_min(wind->toplevel_bounds.width, width); + height = SDL_min(wind->toplevel_bounds.height, height); + } + } else { + width = window->windowed.w; + height = window->windowed.h; + } + + if (!wind->scale_to_display) { + wind->requested.logical_width = width; + wind->requested.logical_height = height; + } else { + wind->requested.pixel_width = width; + wind->requested.pixel_height = height; + width = wind->requested.logical_width = PixelToPoint(window, width); + height = wind->requested.logical_height = PixelToPoint(window, height); + } + } else { + /* Don't apply the supplied dimensions if they haven't changed from the last configuration + * event, or a newer size set programmatically can be overwritten by old data. + */ + if (width != wind->last_configure.width || height != wind->last_configure.height) { + wind->requested.logical_width = width; + wind->requested.logical_height = height; + + if (wind->scale_to_display) { + wind->requested.pixel_width = PointToPixel(window, width); + wind->requested.pixel_height = PointToPixel(window, height); + } + } + } + } else { + /* If we're a fixed-size window, we know our size for sure. + * Always assume the configure is wrong. + */ + if (!wind->scale_to_display) { + width = wind->requested.logical_width = window->floating.w; + height = wind->requested.logical_height = window->floating.h; + } else { + wind->requested.pixel_width = window->floating.w; + wind->requested.pixel_height = window->floating.h; + width = wind->requested.logical_width = PixelToPoint(window, window->floating.w); + height = wind->requested.logical_height = PixelToPoint(window, window->floating.h); + } + } + + /* Notes on the spec: + * + * - The content limits are only a hint, which the compositor is free to ignore, + * so apply them manually when appropriate. + * + * - Maximized windows must have their exact dimensions respected, thus they must + * not be resized, or a protocol violation can occur. + * + * - When resizing a window, the width/height are maximum values, so aspect ratio + * correction can't resize beyond the existing dimensions, or a protocol violation + * can occur. In practice, nothing seems to kill clients that do this, but doing + * so causes GNOME to glitch out. + */ + if (!maximized) { + if (!wind->scale_to_display) { + if (window->max_w > 0) { + wind->requested.logical_width = SDL_min(wind->requested.logical_width, window->max_w); + } + wind->requested.logical_width = SDL_max(wind->requested.logical_width, window->min_w); + + if (window->max_h > 0) { + wind->requested.logical_height = SDL_min(wind->requested.logical_height, window->max_h); + } + wind->requested.logical_height = SDL_max(wind->requested.logical_height, window->min_h); + + // Aspect correction. + const float aspect = (float)wind->requested.logical_width / (float)wind->requested.logical_height; + + if (window->min_aspect != 0.f && aspect < window->min_aspect) { + wind->requested.logical_height = SDL_lroundf((float)wind->requested.logical_width / window->min_aspect); + } else if (window->max_aspect != 0.f && aspect > window->max_aspect) { + wind->requested.logical_width = SDL_lroundf((float)wind->requested.logical_height * window->max_aspect); + } + } else { + if (window->max_w > 0) { + wind->requested.pixel_width = SDL_min(wind->requested.pixel_width, window->max_w); + } + wind->requested.pixel_width = SDL_max(wind->requested.pixel_width, window->min_w); + + if (window->max_h > 0) { + wind->requested.pixel_height = SDL_min(wind->requested.pixel_height, window->max_h); + } + wind->requested.pixel_height = SDL_max(wind->requested.pixel_height, window->min_h); + + // Aspect correction. + const float aspect = (float)wind->requested.pixel_width / (float)wind->requested.pixel_height; + + if (window->min_aspect != 0.f && aspect < window->min_aspect) { + wind->requested.pixel_height = SDL_lroundf((float)wind->requested.pixel_width / window->min_aspect); + } else if (window->max_aspect != 0.f && aspect > window->max_aspect) { + wind->requested.pixel_width = SDL_lroundf((float)wind->requested.pixel_height * window->max_aspect); + } + + wind->requested.logical_width = PixelToPoint(window, wind->requested.pixel_width); + wind->requested.logical_height = PixelToPoint(window, wind->requested.pixel_height); + } + } + } else { + // Fullscreen windows know their exact size. + if (width == 0 || height == 0) { + width = wind->requested.logical_width; + height = wind->requested.logical_height; + } else { + wind->requested.logical_width = width; + wind->requested.logical_height = height; + } + + if (wind->scale_to_display) { + wind->requested.pixel_width = PointToPixel(window, width); + wind->requested.pixel_height = PointToPixel(window, height); + } + } + + wind->last_configure.width = width; + wind->last_configure.height = height; + wind->floating = floating; + wind->suspended = suspended; + wind->active = active; + window->tiled = tiled; + wind->resizing = resizing; + + if (wind->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_CONFIGURE) { + wind->shell_surface_status = WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_FRAME; + } +} + +static void handle_close_xdg_toplevel(void *data, struct xdg_toplevel *xdg_toplevel) +{ + SDL_WindowData *window = (SDL_WindowData *)data; + SDL_SendWindowEvent(window->sdlwindow, SDL_EVENT_WINDOW_CLOSE_REQUESTED, 0, 0); +} + +static void handle_xdg_configure_toplevel_bounds(void *data, + struct xdg_toplevel *xdg_toplevel, + int32_t width, int32_t height) +{ + SDL_WindowData *window = (SDL_WindowData *)data; + window->toplevel_bounds.width = width; + window->toplevel_bounds.height = height; +} + +static void handle_xdg_toplevel_wm_capabilities(void *data, + struct xdg_toplevel *xdg_toplevel, + struct wl_array *capabilities) +{ + SDL_WindowData *wind = (SDL_WindowData *)data; + enum xdg_toplevel_wm_capabilities *wm_cap; + + wind->wm_caps = 0; + + wl_array_for_each (wm_cap, capabilities) { + switch (*wm_cap) { + case XDG_TOPLEVEL_WM_CAPABILITIES_WINDOW_MENU: + wind->wm_caps |= WAYLAND_WM_CAPS_WINDOW_MENU; + break; + case XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE: + wind->wm_caps |= WAYLAND_WM_CAPS_MAXIMIZE; + break; + case XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN: + wind->wm_caps |= WAYLAND_WM_CAPS_FULLSCREEN; + break; + case XDG_TOPLEVEL_WM_CAPABILITIES_MINIMIZE: + wind->wm_caps |= WAYLAND_WM_CAPS_MINIMIZE; + break; + default: + break; + } + } +} + +static const struct xdg_toplevel_listener toplevel_listener_xdg = { + handle_configure_xdg_toplevel, + handle_close_xdg_toplevel, + handle_xdg_configure_toplevel_bounds, // Version 4 + handle_xdg_toplevel_wm_capabilities // Version 5 +}; + +static void handle_configure_xdg_popup(void *data, + struct xdg_popup *xdg_popup, + int32_t x, + int32_t y, + int32_t width, + int32_t height) +{ + SDL_WindowData *wind = (SDL_WindowData *)data; + int offset_x = 0, offset_y = 0; + + // Adjust the position if it was offset for libdecor + AdjustPopupOffset(wind->sdlwindow, &offset_x, &offset_y); + x -= offset_x; + y -= offset_y; + + /* This happens when the compositor indicates that the size is + * up to the client, so use the cached window size here. + */ + if (width == 0 || height == 0) { + width = wind->sdlwindow->floating.w; + height = wind->sdlwindow->floating.h; + } + + /* Don't apply the supplied dimensions if they haven't changed from the last configuration + * event, or a newer size set programmatically can be overwritten by old data. + */ + if (width != wind->last_configure.width || height != wind->last_configure.height) { + wind->requested.logical_width = width; + wind->requested.logical_height = height; + + if (wind->scale_to_display) { + wind->requested.pixel_width = PointToPixel(wind->sdlwindow, width); + wind->requested.pixel_height = PointToPixel(wind->sdlwindow, height); + } + } + + if (wind->scale_to_display) { + x = PointToPixel(wind->sdlwindow->parent, x); + y = PointToPixel(wind->sdlwindow->parent, y); + } + + SDL_SendWindowEvent(wind->sdlwindow, SDL_EVENT_WINDOW_MOVED, x, y); + + wind->last_configure.width = width; + wind->last_configure.height = height; + + if (wind->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_CONFIGURE) { + wind->shell_surface_status = WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_FRAME; + } +} + +static void handle_done_xdg_popup(void *data, struct xdg_popup *xdg_popup) +{ + SDL_WindowData *window = (SDL_WindowData *)data; + SDL_SendWindowEvent(window->sdlwindow, SDL_EVENT_WINDOW_CLOSE_REQUESTED, 0, 0); +} + +static void handle_repositioned_xdg_popup(void *data, + struct xdg_popup *xdg_popup, + uint32_t token) +{ + // No-op, configure does all the work we care about +} + +static const struct xdg_popup_listener popup_listener_xdg = { + handle_configure_xdg_popup, + handle_done_xdg_popup, + handle_repositioned_xdg_popup +}; + +static void handle_configure_zxdg_decoration(void *data, + struct zxdg_toplevel_decoration_v1 *zxdg_toplevel_decoration_v1, + uint32_t mode) +{ + SDL_Window *window = (SDL_Window *)data; + SDL_WindowData *internal = window->internal; + SDL_VideoDevice *device = SDL_GetVideoDevice(); + + /* If the compositor tries to force CSD anyway, bail on direct XDG support + * and fall back to libdecor, it will handle these events from then on. + * + * To do this we have to fully unmap, then map with libdecor loaded. + */ + if (mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE) { + if (window->flags & SDL_WINDOW_BORDERLESS) { + // borderless windows do request CSD, so we got what we wanted + return; + } + if (!Wayland_LoadLibdecor(internal->waylandData, true)) { + // libdecor isn't available, so no borders for you... oh well + return; + } + WAYLAND_wl_display_roundtrip(internal->waylandData->display); + + Wayland_HideWindow(device, window); + SDL_zero(internal->shell_surface); + internal->shell_surface_type = WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR; + + Wayland_ShowWindow(device, window); + } +} + +static const struct zxdg_toplevel_decoration_v1_listener decoration_listener = { + handle_configure_zxdg_decoration +}; + +#ifdef HAVE_LIBDECOR_H +/* + * XXX: Hack for older versions of libdecor that lack the function to query the + * minimum content size limit. The internal limits must always be overridden + * to ensure that very small windows don't cause errors or crashes. + * + * On libdecor >= 0.1.2, which exposes the function to get the minimum content + * size limit, this function is a no-op. + * + * Can be removed if the minimum required version of libdecor is raised to + * 0.1.2 or higher. + */ +static void OverrideLibdecorLimits(SDL_Window *window) +{ +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR + if (!libdecor_frame_get_min_content_size) { + libdecor_frame_set_min_content_size(window->internal->shell_surface.libdecor.frame, window->min_w, window->min_h); + } +#elif !SDL_LIBDECOR_CHECK_VERSION(0, 2, 0) + libdecor_frame_set_min_content_size(window->internal->shell_surface.libdecor.frame, window->min_w, window->min_h); +#endif +} + +/* + * NOTE: Retrieves the minimum content size limits, if the function for doing so is available. + * On versions of libdecor that lack the minimum content size retrieval function, this + * function is a no-op. + * + * Can be replaced with a direct call if the minimum required version of libdecor is raised + * to 0.1.2 or higher. + */ +static void LibdecorGetMinContentSize(struct libdecor_frame *frame, int *min_w, int *min_h) +{ +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR + if (libdecor_frame_get_min_content_size != NULL) { + libdecor_frame_get_min_content_size(frame, min_w, min_h); + } +#elif SDL_LIBDECOR_CHECK_VERSION(0, 2, 0) + libdecor_frame_get_min_content_size(frame, min_w, min_h); +#endif +} + +static void decoration_frame_configure(struct libdecor_frame *frame, + struct libdecor_configuration *configuration, + void *user_data) +{ + SDL_WindowData *wind = (SDL_WindowData *)user_data; + SDL_Window *window = wind->sdlwindow; + + enum libdecor_window_state window_state; + int width, height; + + bool prev_fullscreen = wind->is_fullscreen; + bool active = false; + bool fullscreen = false; + bool maximized = false; + bool tiled = false; + bool suspended = false; + bool resizing = false; + + static const enum libdecor_window_state tiled_states = (LIBDECOR_WINDOW_STATE_TILED_LEFT | LIBDECOR_WINDOW_STATE_TILED_RIGHT | + LIBDECOR_WINDOW_STATE_TILED_TOP | LIBDECOR_WINDOW_STATE_TILED_BOTTOM); + + // Window State + if (libdecor_configuration_get_window_state(configuration, &window_state)) { + fullscreen = (window_state & LIBDECOR_WINDOW_STATE_FULLSCREEN) != 0; + maximized = (window_state & LIBDECOR_WINDOW_STATE_MAXIMIZED) != 0; + active = (window_state & LIBDECOR_WINDOW_STATE_ACTIVE) != 0; + tiled = (window_state & tiled_states) != 0; +#if SDL_LIBDECOR_CHECK_VERSION(0, 2, 0) + suspended = (window_state & LIBDECOR_WINDOW_STATE_SUSPENDED) != 0; +#endif +#if SDL_LIBDECOR_CHECK_VERSION(0, 3, 0) + resizing = (window_state & LIBDECOR_WINDOW_STATE_RESIZING) != 0; +#endif + } + const bool floating = !(fullscreen || maximized || tiled); + + UpdateWindowFullscreen(window, fullscreen); + + /* Always send a maximized/restore event; if the event is redundant it will + * automatically be discarded (see src/events/SDL_windowevents.c) + * + * No, we do not get minimize events from libdecor, however, the minimized + * state can be programmatically set. The meaning of 'minimized' is compositor + * dependent, but in general, we can assume that the flag should remain set until + * the next focused configure event occurs. + */ + if (active || !(window->flags & SDL_WINDOW_MINIMIZED)) { + if (window->flags & SDL_WINDOW_MINIMIZED) { + // If we were minimized, send a restored event before possibly sending maximized. + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_RESTORED, 0, 0); + } + SDL_SendWindowEvent(window, + (maximized && !fullscreen) ? SDL_EVENT_WINDOW_MAXIMIZED : SDL_EVENT_WINDOW_RESTORED, + 0, 0); + } + + /* For fullscreen or fixed-size windows we know our size. + * Always assume the configure is wrong. + */ + if (fullscreen) { + if (!libdecor_configuration_get_content_size(configuration, frame, &width, &height)) { + width = wind->requested.logical_width; + height = wind->requested.logical_height; + } else { + // Fullscreen windows know their exact size. + wind->requested.logical_width = width; + wind->requested.logical_height = height; + + if (wind->scale_to_display) { + wind->requested.pixel_width = PointToPixel(window, width); + wind->requested.pixel_height = PointToPixel(window, height); + } + } + } else { + if (!(window->flags & SDL_WINDOW_RESIZABLE)) { + /* If we're a fixed-size window, we know our size for sure. + * Always assume the configure is wrong. + */ + if (!wind->scale_to_display) { + width = wind->requested.logical_width = window->floating.w; + height = wind->requested.logical_height = window->floating.h; + } else { + wind->requested.pixel_width = window->floating.w; + wind->requested.pixel_height = window->floating.h; + width = wind->requested.logical_width = PixelToPoint(window, window->floating.w); + height = wind->requested.logical_height = PixelToPoint(window, window->floating.h); + } + + OverrideLibdecorLimits(window); + } else { + /* XXX: The libdecor cairo plugin sends bogus content sizes that add the + * height of the title bar when transitioning from a fixed-size to + * floating state. Ignore the sent window dimensions in this case, + * in favor of the cached value to avoid the window increasing in + * size after every state transition. + * + * https://gitlab.freedesktop.org/libdecor/libdecor/-/issues/34 + */ + if ((floating && (!wind->floating && !(window->flags & SDL_WINDOW_BORDERLESS))) || + !libdecor_configuration_get_content_size(configuration, frame, &width, &height)) { + /* This happens when we're being restored from a non-floating state, + * or the compositor indicates that the size is up to the client, so + * used the cached window size here. + */ + if (floating) { + width = window->floating.w; + height = window->floating.h; + } else { + width = window->windowed.w; + height = window->windowed.h; + } + + if (!wind->scale_to_display) { + wind->requested.logical_width = width; + wind->requested.logical_height = height; + } else { + wind->requested.pixel_width = width; + wind->requested.pixel_height = height; + width = wind->requested.logical_width = PixelToPoint(window, width); + height = wind->requested.logical_height = PixelToPoint(window, height); + } + } else { + /* Don't apply the supplied dimensions if they haven't changed from the last configuration + * event, or a newer size set programmatically can be overwritten by old data. + */ + if (width != wind->last_configure.width || height != wind->last_configure.height) { + wind->requested.logical_width = width; + wind->requested.logical_height = height; + + if (wind->scale_to_display) { + wind->requested.pixel_width = PointToPixel(window, width); + wind->requested.pixel_height = PointToPixel(window, height); + } + } + } + } + + /* Notes on the spec: + * + * - The content limits are only a hint, which the compositor is free to ignore, + * so apply them manually when appropriate. + * + * - Maximized windows must have their exact dimensions respected, thus they must + * not be resized, or a protocol violation can occur. + * + * - When resizing a window, the width/height are maximum values, so aspect ratio + * correction can't resize beyond the existing dimensions, or a protocol violation + * can occur. In practice, nothing seems to kill clients that do this, but doing + * so causes GNOME to glitch out. + */ + if (!maximized) { + if (!wind->scale_to_display) { + if (window->max_w > 0) { + wind->requested.logical_width = SDL_min(wind->requested.logical_width, window->max_w); + } + wind->requested.logical_width = SDL_max(wind->requested.logical_width, window->min_w); + + if (window->max_h > 0) { + wind->requested.logical_height = SDL_min(wind->requested.logical_height, window->max_h); + } + wind->requested.logical_height = SDL_max(wind->requested.logical_height, window->min_h); + + // Aspect correction. + const float aspect = (float)wind->requested.logical_width / (float)wind->requested.logical_height; + + if (window->min_aspect != 0.f && aspect < window->min_aspect) { + wind->requested.logical_height = SDL_lroundf((float)wind->requested.logical_width / window->min_aspect); + } else if (window->max_aspect != 0.f && aspect > window->max_aspect) { + wind->requested.logical_width = SDL_lroundf((float)wind->requested.logical_height * window->max_aspect); + } + } else { + if (window->max_w > 0) { + wind->requested.pixel_width = SDL_min(wind->requested.pixel_width, window->max_w); + } + wind->requested.pixel_width = SDL_max(wind->requested.pixel_width, window->min_w); + + if (window->max_h > 0) { + wind->requested.pixel_height = SDL_min(wind->requested.pixel_height, window->max_h); + } + wind->requested.pixel_height = SDL_max(wind->requested.pixel_height, window->min_h); + + // Aspect correction. + const float aspect = (float)wind->requested.pixel_width / (float)wind->requested.pixel_height; + + if (window->min_aspect != 0.f && aspect < window->min_aspect) { + wind->requested.pixel_height = SDL_lroundf((float)wind->requested.pixel_width / window->min_aspect); + } else if (window->max_aspect != 0.f && aspect > window->max_aspect) { + wind->requested.pixel_width = SDL_lroundf((float)wind->requested.pixel_height * window->max_aspect); + } + + wind->requested.logical_width = PixelToPoint(window, wind->requested.pixel_width); + wind->requested.logical_height = PixelToPoint(window, wind->requested.pixel_height); + } + } + } + + // Store the new state. + wind->last_configure.width = width; + wind->last_configure.height = height; + wind->floating = floating; + wind->suspended = suspended; + wind->active = active; + window->tiled = tiled; + wind->resizing = resizing; + + // Update the window manager capabilities. +#if SDL_LIBDECOR_CHECK_VERSION(0, 3, 0) + enum libdecor_wm_capabilities caps; +#ifdef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR + if (libdecor_frame_get_wm_capabilities) { + caps = libdecor_frame_get_wm_capabilities(wind->shell_surface.libdecor.frame); +#else + caps = libdecor_frame_get_wm_capabilities(wind->shell_surface.libdecor.frame); + { +#endif + wind->wm_caps = 0; + wind->wm_caps |= caps & LIBDECOR_WM_CAPABILITIES_WINDOW_MENU ? WAYLAND_WM_CAPS_WINDOW_MENU : 0; + wind->wm_caps |= caps & LIBDECOR_WM_CAPABILITIES_MAXIMIZE ? WAYLAND_WM_CAPS_MAXIMIZE : 0; + wind->wm_caps |= caps & LIBDECOR_WM_CAPABILITIES_FULLSCREEN ? WAYLAND_WM_CAPS_FULLSCREEN : 0; + wind->wm_caps |= caps & LIBDECOR_WM_CAPABILITIES_MINIMIZE ? WAYLAND_WM_CAPS_MINIMIZE : 0; + } +#endif + + // Calculate the new window geometry + if (ConfigureWindowGeometry(window)) { + // ... then commit the changes on the libdecor side. + struct libdecor_state *state = libdecor_state_new(wind->current.logical_width, wind->current.logical_height); + libdecor_frame_commit(frame, state, configuration); + libdecor_state_free(state); + } + + if (!wind->shell_surface.libdecor.initial_configure_seen) { + LibdecorGetMinContentSize(frame, &wind->system_limits.min_width, &wind->system_limits.min_height); + wind->shell_surface.libdecor.initial_configure_seen = true; + } + if (wind->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_CONFIGURE) { + wind->shell_surface_status = WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_FRAME; + } + + /* Update the resize capability if this config event was the result of the + * compositor taking a window out of fullscreen. Since this will change the + * capabilities and commit a new frame state with the last known content + * dimension, this has to be called after the new state has been committed + * and the new content dimensions were updated. + */ + if (prev_fullscreen && !wind->is_fullscreen) { + Wayland_SetWindowResizable(SDL_GetVideoDevice(), window, + !!(window->flags & SDL_WINDOW_RESIZABLE)); + } +} + +static void decoration_frame_close(struct libdecor_frame *frame, void *user_data) +{ + SDL_SendWindowEvent(((SDL_WindowData *)user_data)->sdlwindow, SDL_EVENT_WINDOW_CLOSE_REQUESTED, 0, 0); +} + +static void decoration_frame_commit(struct libdecor_frame *frame, void *user_data) +{ + /* libdecor decoration subsurfaces are synchronous, so the client needs to + * commit a frame to trigger an update of the decoration surfaces. + */ + SDL_WindowData *wind = (SDL_WindowData *)user_data; + if (!wind->suspended && wind->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_SHOWN) { + SDL_SendWindowEvent(wind->sdlwindow, SDL_EVENT_WINDOW_EXPOSED, 0, 0); + } +} + +static void decoration_dismiss_popup(struct libdecor_frame *frame, const char *seat_name, void *user_data) +{ + // NOP +} + +static struct libdecor_frame_interface libdecor_frame_interface = { + decoration_frame_configure, + decoration_frame_close, + decoration_frame_commit, + decoration_dismiss_popup +}; +#endif + +static void Wayland_HandlePreferredScaleChanged(SDL_WindowData *window_data, double factor) +{ + const double old_factor = window_data->scale_factor; + + // Round the scale factor if viewports aren't available. + if (!window_data->viewport) { + factor = SDL_ceil(factor); + } + + if (factor != old_factor) { + window_data->scale_factor = factor; + + if (window_data->scale_to_display) { + /* If the window is in the floating state with a user/application specified size, calculate the new + * logical size from the backbuffer size. Otherwise, use the fixed underlying logical size to calculate + * the new backbuffer dimensions. + */ + if (window_data->floating) { + window_data->requested.logical_width = PixelToPoint(window_data->sdlwindow, window_data->requested.pixel_width); + window_data->requested.logical_height = PixelToPoint(window_data->sdlwindow, window_data->requested.pixel_height); + } else { + window_data->requested.pixel_width = PointToPixel(window_data->sdlwindow, window_data->requested.logical_width); + window_data->requested.pixel_height = PointToPixel(window_data->sdlwindow, window_data->requested.logical_height); + } + } + + if (window_data->sdlwindow->flags & SDL_WINDOW_HIGH_PIXEL_DENSITY || window_data->scale_to_display) { + ConfigureWindowGeometry(window_data->sdlwindow); + CommitLibdecorFrame(window_data->sdlwindow); + } + } +} + +static void Wayland_MaybeUpdateScaleFactor(SDL_WindowData *window) +{ + double factor; + int i; + + /* If the fractional scale protocol is present or the core protocol supports the + * preferred buffer scale event, the compositor will explicitly tell the application + * what scale it wants via these events, so don't try to determine the scale factor + * from which displays the surface has entered. + */ + if (window->fractional_scale || wl_surface_get_version(window->surface) >= WL_SURFACE_PREFERRED_BUFFER_SCALE_SINCE_VERSION) { + return; + } + + if (window->num_outputs != 0) { + // Check every display's factor, use the highest + factor = 0.0; + for (i = 0; i < window->num_outputs; i++) { + SDL_DisplayData *internal = window->outputs[i]; + factor = SDL_max(factor, internal->scale_factor); + } + } else { + // All outputs removed, just fall back. + factor = window->scale_factor; + } + + Wayland_HandlePreferredScaleChanged(window, factor); +} + +void Wayland_RemoveOutputFromWindow(SDL_WindowData *window, SDL_DisplayData *display_data) +{ + for (int i = 0; i < window->num_outputs; i++) { + if (window->outputs[i] == display_data) { // remove this one + if (i == (window->num_outputs - 1)) { + window->outputs[i] = NULL; + } else { + SDL_memmove(&window->outputs[i], + &window->outputs[i + 1], + sizeof(SDL_DisplayData *) * ((window->num_outputs - i) - 1)); + } + window->num_outputs--; + i--; + } + } + + if (window->num_outputs == 0) { + SDL_free(window->outputs); + window->outputs = NULL; + } else if (!window->is_fullscreen || window->num_outputs == 1) { + Wayland_move_window(window->sdlwindow); + Wayland_MaybeUpdateScaleFactor(window); + } +} + +static void handle_surface_enter(void *data, struct wl_surface *surface, struct wl_output *output) +{ + SDL_WindowData *window = data; + SDL_DisplayData *internal = wl_output_get_user_data(output); + SDL_DisplayData **new_outputs; + + if (!SDL_WAYLAND_own_output(output) || !SDL_WAYLAND_own_surface(surface)) { + return; + } + + new_outputs = SDL_realloc(window->outputs, + sizeof(SDL_DisplayData *) * (window->num_outputs + 1)); + if (!new_outputs) { + return; + } + window->outputs = new_outputs; + window->outputs[window->num_outputs++] = internal; + + // Update the scale factor after the move so that fullscreen outputs are updated. + if (!window->is_fullscreen || window->num_outputs == 1) { + Wayland_move_window(window->sdlwindow); + Wayland_MaybeUpdateScaleFactor(window); + } +} + +static void handle_surface_leave(void *data, struct wl_surface *surface, struct wl_output *output) +{ + SDL_WindowData *window = (SDL_WindowData *)data; + + if (!SDL_WAYLAND_own_output(output) || !SDL_WAYLAND_own_surface(surface)) { + return; + } + + Wayland_RemoveOutputFromWindow(window, (SDL_DisplayData *)wl_output_get_user_data(output)); +} + +static void handle_preferred_buffer_scale(void *data, struct wl_surface *wl_surface, int32_t factor) +{ + SDL_WindowData *wind = data; + + /* The spec is unclear on how this interacts with the fractional scaling protocol, + * so, for now, assume that the fractional scaling protocol takes priority and + * only listen to this event if the fractional scaling protocol is not present. + */ + if (!wind->fractional_scale) { + Wayland_HandlePreferredScaleChanged(data, (double)factor); + } +} + +static void handle_preferred_buffer_transform(void *data, struct wl_surface *wl_surface, uint32_t transform) +{ + // Nothing to do here. +} + +static const struct wl_surface_listener surface_listener = { + handle_surface_enter, + handle_surface_leave, + handle_preferred_buffer_scale, + handle_preferred_buffer_transform +}; + +static void handle_preferred_fractional_scale(void *data, struct wp_fractional_scale_v1 *wp_fractional_scale_v1, uint32_t scale) +{ + const double factor = (double)scale / 120.; // 120 is a magic number defined in the spec as a common denominator + Wayland_HandlePreferredScaleChanged(data, factor); +} + +static const struct wp_fractional_scale_v1_listener fractional_scale_listener = { + handle_preferred_fractional_scale +}; + +static void frog_preferred_metadata_handler(void *data, struct frog_color_managed_surface *frog_color_managed_surface, uint32_t transfer_function, + uint32_t output_display_primary_red_x, uint32_t output_display_primary_red_y, + uint32_t output_display_primary_green_x, uint32_t output_display_primary_green_y, + uint32_t output_display_primary_blue_x, uint32_t output_display_primary_blue_y, + uint32_t output_white_point_x, uint32_t output_white_point_y, + uint32_t max_luminance, uint32_t min_luminance, + uint32_t max_full_frame_luminance) +{ + SDL_WindowData *wind = (SDL_WindowData *)data; + SDL_HDROutputProperties HDR; + + SDL_zero(HDR); + + switch (transfer_function) { + case FROG_COLOR_MANAGED_SURFACE_TRANSFER_FUNCTION_ST2084_PQ: + /* ITU-R BT.2408-7 (Sept 2023) has the reference PQ white level at 203 nits, + * while older Dolby documentation claims a reference level of 100 nits. + * + * Use 203 nits for now. + */ + HDR.HDR_headroom = max_luminance / 203.0f; + break; + case FROG_COLOR_MANAGED_SURFACE_TRANSFER_FUNCTION_SCRGB_LINEAR: + HDR.HDR_headroom = max_luminance / 80.0f; + break; + case FROG_COLOR_MANAGED_SURFACE_TRANSFER_FUNCTION_UNDEFINED: + case FROG_COLOR_MANAGED_SURFACE_TRANSFER_FUNCTION_SRGB: + case FROG_COLOR_MANAGED_SURFACE_TRANSFER_FUNCTION_GAMMA_22: + default: + HDR.HDR_headroom = 1.0f; + break; + } + + HDR.SDR_white_level = 1.0f; + SDL_SetWindowHDRProperties(wind->sdlwindow, &HDR, true); +} + +static const struct frog_color_managed_surface_listener frog_surface_listener = { + frog_preferred_metadata_handler +}; + +static void feedback_surface_preferred_changed(void *data, + struct wp_color_management_surface_feedback_v1 *wp_color_management_surface_feedback_v1, + uint32_t identity) +{ + SDL_WindowData *wind = (SDL_WindowData *)data; + Wayland_GetColorInfoForWindow(wind, false); +} + +static const struct wp_color_management_surface_feedback_v1_listener color_management_surface_feedback_listener = { + feedback_surface_preferred_changed +}; + +static void SetKeyboardFocus(SDL_Window *window, bool set_focus) +{ + SDL_Window *toplevel = window; + + // Find the toplevel parent + while (SDL_WINDOW_IS_POPUP(toplevel)) { + toplevel = toplevel->parent; + } + + toplevel->internal->keyboard_focus = window; + + if (set_focus && !window->is_hiding && !window->is_destroying) { + SDL_SetKeyboardFocus(window); + } +} + +bool Wayland_SetWindowHitTest(SDL_Window *window, bool enabled) +{ + return true; // just succeed, the real work is done elsewhere. +} + +static struct xdg_toplevel *GetToplevelForWindow(SDL_WindowData *wind) +{ + if (wind) { + /* Libdecor crashes on attempts to unset the parent by passing null, which is allowed by the + * toplevel spec, so just use the raw xdg-toplevel instead (that's what libdecor does + * internally anyways). + */ +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR && wind->shell_surface.libdecor.frame) { + return libdecor_frame_get_xdg_toplevel(wind->shell_surface.libdecor.frame); + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL && wind->shell_surface.xdg.toplevel.xdg_toplevel) { + return wind->shell_surface.xdg.toplevel.xdg_toplevel; + } + } + + return NULL; +} + +bool Wayland_SetWindowParent(SDL_VideoDevice *_this, SDL_Window *window, SDL_Window *parent_window) +{ + SDL_WindowData *child_data = window->internal; + SDL_WindowData *parent_data = parent_window ? parent_window->internal : NULL; + + child_data->reparenting_required = false; + + if (parent_data && parent_data->shell_surface_status != WAYLAND_SHELL_SURFACE_STATUS_SHOWN) { + // Need to wait for the parent to become mapped, or it's the same as setting a null parent. + child_data->reparenting_required = true; + return true; + } + + struct xdg_toplevel *child_toplevel = GetToplevelForWindow(child_data); + struct xdg_toplevel *parent_toplevel = GetToplevelForWindow(parent_data); + + if (child_toplevel) { + xdg_toplevel_set_parent(child_toplevel, parent_toplevel); + } + + return true; +} + +bool Wayland_SetWindowModal(SDL_VideoDevice *_this, SDL_Window *window, bool modal) +{ + SDL_VideoData *viddata = _this->internal; + SDL_WindowData *data = window->internal; + SDL_WindowData *parent_data = window->parent->internal; + + if (parent_data->shell_surface_status != WAYLAND_SHELL_SURFACE_STATUS_SHOWN) { + // Need to wait for the parent to become mapped before changing modal status. + data->reparenting_required = true; + return true; + } else { + data->reparenting_required = false; + } + + struct xdg_toplevel *toplevel = GetToplevelForWindow(data); + + if (toplevel) { + if (viddata->xdg_wm_dialog_v1) { + if (modal) { + if (!data->xdg_dialog_v1) { + data->xdg_dialog_v1 = xdg_wm_dialog_v1_get_xdg_dialog(viddata->xdg_wm_dialog_v1, toplevel); + } + + xdg_dialog_v1_set_modal(data->xdg_dialog_v1); + } else if (data->xdg_dialog_v1) { + xdg_dialog_v1_unset_modal(data->xdg_dialog_v1); + } + } + } + + return true; +} + +static void show_hide_sync_handler(void *data, struct wl_callback *callback, uint32_t callback_data) +{ + // Get the window from the ID as it may have been destroyed + SDL_WindowID windowID = (SDL_WindowID)((uintptr_t)data); + SDL_Window *window = SDL_GetWindowFromID(windowID); + + if (window && window->internal) { + SDL_WindowData *wind = window->internal; + wind->show_hide_sync_required = false; + } + + wl_callback_destroy(callback); +} + +static struct wl_callback_listener show_hide_sync_listener = { + show_hide_sync_handler +}; + +static void exported_handle_handler(void *data, struct zxdg_exported_v2 *zxdg_exported_v2, const char *handle) +{ + SDL_WindowData *wind = (SDL_WindowData*)data; + SDL_PropertiesID props = SDL_GetWindowProperties(wind->sdlwindow); + + SDL_SetStringProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_EXPORT_HANDLE_STRING, handle); +} + +static struct zxdg_exported_v2_listener exported_v2_listener = { + exported_handle_handler +}; + +void Wayland_ShowWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_VideoData *c = _this->internal; + SDL_WindowData *data = window->internal; + SDL_PropertiesID props = SDL_GetWindowProperties(window); + + // Custom surfaces don't get toplevels and are always considered 'shown'; nothing to do here. + if (data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_CUSTOM) { + return; + } + + /* If this is a child window, the parent *must* be in the final shown state, + * meaning that it has received a configure event, followed by a frame callback. + * If not, a race condition can result, with effects ranging from the child + * window to spuriously closing to protocol errors. + * + * If waiting on the parent window, set the pending status and the window will + * be shown when the parent is in the shown state. + */ + if (window->parent) { + if (window->parent->internal->shell_surface_status != WAYLAND_SHELL_SURFACE_STATUS_SHOWN) { + data->shell_surface_status = WAYLAND_SHELL_SURFACE_STATUS_SHOW_PENDING; + return; + } + } + + /* The window was hidden, but the sync point hasn't yet been reached. + * Pump events to avoid a possible protocol violation. + */ + if (data->show_hide_sync_required) { + WAYLAND_wl_display_roundtrip(c->display); + } + + data->shell_surface_status = WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_CONFIGURE; + + /* Detach any previous buffers before resetting everything, otherwise when + * calling this a second time you'll get an annoying protocol error! + * + * FIXME: This was originally moved to HideWindow, which _should_ make + * sense, but for whatever reason UE5's popups require that this actually + * be in both places at once? Possibly from renderers making commits? I can't + * fully remember if this location caused crashes or if I was fixing a pair + * of Hide/Show calls. In any case, UE gives us a pretty good test and having + * both detach calls passes. This bug may be relevant if I'm wrong: + * + * https://bugs.kde.org/show_bug.cgi?id=448856 + * + * -flibit + */ + wl_surface_attach(data->surface, NULL, 0, 0); + wl_surface_commit(data->surface); + + // Create the shell surface and map the toplevel/popup +#ifdef HAVE_LIBDECOR_H + if (data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + data->shell_surface.libdecor.frame = libdecor_decorate(c->shell.libdecor, + data->surface, + &libdecor_frame_interface, + data); + if (!data->shell_surface.libdecor.frame) { + SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Failed to create libdecor frame!"); + } else { + libdecor_frame_set_app_id(data->shell_surface.libdecor.frame, data->app_id); + libdecor_frame_map(data->shell_surface.libdecor.frame); + if (window->flags & SDL_WINDOW_BORDERLESS) { + // Note: Calling this with 'true' immediately after mapping will cause the libdecor Cairo plugin to crash. + libdecor_frame_set_visibility(data->shell_surface.libdecor.frame, false); + } + + if (c->zxdg_exporter_v2) { + data->exported = zxdg_exporter_v2_export_toplevel(c->zxdg_exporter_v2, data->surface); + zxdg_exported_v2_add_listener(data->exported, &exported_v2_listener, data); + } + + if (c->xdg_toplevel_icon_manager_v1 && data->xdg_toplevel_icon_v1) { + xdg_toplevel_icon_manager_v1_set_icon(_this->internal->xdg_toplevel_icon_manager_v1, + libdecor_frame_get_xdg_toplevel(data->shell_surface.libdecor.frame), + data->xdg_toplevel_icon_v1); + } + + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_SURFACE_POINTER, libdecor_frame_get_xdg_surface(data->shell_surface.libdecor.frame)); + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_POINTER, libdecor_frame_get_xdg_toplevel(data->shell_surface.libdecor.frame)); + } + } else +#endif + if (data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL || data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP) { + data->shell_surface.xdg.surface = xdg_wm_base_get_xdg_surface(c->shell.xdg, data->surface); + xdg_surface_set_user_data(data->shell_surface.xdg.surface, data); + xdg_surface_add_listener(data->shell_surface.xdg.surface, &shell_surface_listener_xdg, data); + SDL_SetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WAYLAND_XDG_SURFACE_POINTER, data->shell_surface.xdg.surface); + + if (data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP) { + SDL_Window *parent = window->parent; + SDL_WindowData *parent_data = parent->internal; + struct xdg_surface *parent_xdg_surface = NULL; + int position_x = 0, position_y = 0; + + // Configure the popup parameters +#ifdef HAVE_LIBDECOR_H + if (parent_data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + parent_xdg_surface = libdecor_frame_get_xdg_surface(parent_data->shell_surface.libdecor.frame); + } else +#endif + if (parent_data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL || + parent_data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP) { + parent_xdg_surface = parent_data->shell_surface.xdg.surface; + } + + // Set up the positioner for the popup and configure the constraints + data->shell_surface.xdg.popup.xdg_positioner = xdg_wm_base_create_positioner(c->shell.xdg); + xdg_positioner_set_anchor(data->shell_surface.xdg.popup.xdg_positioner, XDG_POSITIONER_ANCHOR_TOP_LEFT); + xdg_positioner_set_anchor_rect(data->shell_surface.xdg.popup.xdg_positioner, 0, 0, parent->internal->current.logical_width, parent->internal->current.logical_width); + xdg_positioner_set_constraint_adjustment(data->shell_surface.xdg.popup.xdg_positioner, + XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X | XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y); + xdg_positioner_set_gravity(data->shell_surface.xdg.popup.xdg_positioner, XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT); + xdg_positioner_set_size(data->shell_surface.xdg.popup.xdg_positioner, data->current.logical_width, data->current.logical_height); + + // Set the popup initial position + position_x = window->last_position_pending ? window->pending.x : window->x; + position_y = window->last_position_pending ? window->pending.y : window->y; + EnsurePopupPositionIsValid(window, &position_x, &position_y); + if (data->scale_to_display) { + position_x = PixelToPoint(window->parent, position_x); + position_y = PixelToPoint(window->parent, position_y); + } + AdjustPopupOffset(window, &position_x, &position_y); + xdg_positioner_set_offset(data->shell_surface.xdg.popup.xdg_positioner, position_x, position_y); + + // Assign the popup role + data->shell_surface.xdg.popup.xdg_popup = xdg_surface_get_popup(data->shell_surface.xdg.surface, + parent_xdg_surface, + data->shell_surface.xdg.popup.xdg_positioner); + xdg_popup_add_listener(data->shell_surface.xdg.popup.xdg_popup, &popup_listener_xdg, data); + + if (window->flags & SDL_WINDOW_TOOLTIP) { + struct wl_region *region; + + // Tooltips can't be interacted with, so turn off the input region to avoid blocking anything behind them + region = wl_compositor_create_region(c->compositor); + wl_region_add(region, 0, 0, 0, 0); + wl_surface_set_input_region(data->surface, region); + wl_region_destroy(region); + } else if (window->flags & SDL_WINDOW_POPUP_MENU) { + SetKeyboardFocus(window, window->parent == SDL_GetKeyboardFocus()); + } + + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_POPUP_POINTER, data->shell_surface.xdg.popup.xdg_popup); + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_POSITIONER_POINTER, data->shell_surface.xdg.popup.xdg_positioner); + } else { + data->shell_surface.xdg.toplevel.xdg_toplevel = xdg_surface_get_toplevel(data->shell_surface.xdg.surface); + xdg_toplevel_set_app_id(data->shell_surface.xdg.toplevel.xdg_toplevel, data->app_id); + xdg_toplevel_add_listener(data->shell_surface.xdg.toplevel.xdg_toplevel, &toplevel_listener_xdg, data); + + // Create the window decorations + if (c->decoration_manager) { + data->server_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(c->decoration_manager, data->shell_surface.xdg.toplevel.xdg_toplevel); + zxdg_toplevel_decoration_v1_add_listener(data->server_decoration, &decoration_listener, window); + const enum zxdg_toplevel_decoration_v1_mode mode = !(window->flags & SDL_WINDOW_BORDERLESS) ? ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE : ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE; + zxdg_toplevel_decoration_v1_set_mode(data->server_decoration, mode); + } + + if (c->zxdg_exporter_v2) { + data->exported = zxdg_exporter_v2_export_toplevel(c->zxdg_exporter_v2, data->surface); + zxdg_exported_v2_add_listener(data->exported, &exported_v2_listener, data); + } + + if (c->xdg_toplevel_icon_manager_v1 && data->xdg_toplevel_icon_v1) { + xdg_toplevel_icon_manager_v1_set_icon(_this->internal->xdg_toplevel_icon_manager_v1, + data->shell_surface.xdg.toplevel.xdg_toplevel, + data->xdg_toplevel_icon_v1); + } + + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_POINTER, data->shell_surface.xdg.toplevel.xdg_toplevel); + } + } + + // Restore state that was set prior to this call + Wayland_SetWindowParent(_this, window, window->parent); + + if (window->flags & SDL_WINDOW_MODAL) { + Wayland_SetWindowModal(_this, window, true); + } + + Wayland_SetWindowTitle(_this, window); + + /* We have to wait until the surface gets a "configure" event, or use of + * this surface will fail. This is a new rule for xdg_shell. + */ +#ifdef HAVE_LIBDECOR_H + if (data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (data->shell_surface.libdecor.frame) { + while (!data->shell_surface.libdecor.initial_configure_seen) { + WAYLAND_wl_display_flush(c->display); + WAYLAND_wl_display_dispatch(c->display); + } + } + } else +#endif + if (data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP || data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + /* Unlike libdecor we need to call this explicitly to prevent a deadlock. + * libdecor will call this as part of their configure event! + * -flibit + */ + wl_surface_commit(data->surface); + if (data->shell_surface.xdg.surface) { + while (!data->shell_surface.xdg.initial_configure_seen) { + WAYLAND_wl_display_flush(c->display); + WAYLAND_wl_display_dispatch(c->display); + } + } + } else { + // Nothing to see here, just commit. + wl_surface_commit(data->surface); + } + + // Make sure the window can't be resized to 0 or it can be spuriously closed by the window manager. + data->system_limits.min_width = SDL_max(data->system_limits.min_width, 1); + data->system_limits.min_height = SDL_max(data->system_limits.min_height, 1); + + /* Unlike the rest of window state we have to set this _after_ flushing the + * display, because we need to create the decorations before possibly hiding + * them immediately afterward. + */ +#ifdef HAVE_LIBDECOR_H + if (data->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + // Libdecor plugins can enforce minimum window sizes, so adjust if the initial window size is too small. + if (window->windowed.w < data->system_limits.min_width || + window->windowed.h < data->system_limits.min_height) { + + // Warn if the window frame will be larger than the content surface. + SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, + "Window dimensions (%i, %i) are smaller than the system enforced minimum (%i, %i); window borders will be larger than the content surface.", + window->windowed.w, window->windowed.h, data->system_limits.min_width, data->system_limits.min_height); + + data->current.logical_width = SDL_max(window->windowed.w, data->system_limits.min_width); + data->current.logical_height = SDL_max(window->windowed.h, data->system_limits.min_height); + CommitLibdecorFrame(window); + } + } +#endif + Wayland_SetWindowResizable(_this, window, !!(window->flags & SDL_WINDOW_RESIZABLE)); + + // We're finally done putting the window together, raise if possible + if (c->activation_manager) { + /* Note that we don't check for empty strings, as that is still + * considered a valid activation token! + */ + const char *activation_token = SDL_getenv("XDG_ACTIVATION_TOKEN"); + if (activation_token) { + xdg_activation_v1_activate(c->activation_manager, + activation_token, + data->surface); + + // Clear this variable, per the protocol's request + SDL_unsetenv_unsafe("XDG_ACTIVATION_TOKEN"); + } + } + + data->show_hide_sync_required = true; + struct wl_callback *cb = wl_display_sync(_this->internal->display); + wl_callback_add_listener(cb, &show_hide_sync_listener, (void*)((uintptr_t)window->id)); + + // Send an exposure event to signal that the client should draw. + if (data->shell_surface_status == WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_FRAME) { + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_EXPOSED, 0, 0); + } +} + +static void Wayland_ReleasePopup(SDL_VideoDevice *_this, SDL_Window *popup) +{ + SDL_WindowData *popupdata; + + // Basic sanity checks to weed out the weird popup closures + if (!SDL_ObjectValid(popup, SDL_OBJECT_TYPE_WINDOW)) { + return; + } + popupdata = popup->internal; + if (!popupdata) { + return; + } + + // This may already be freed by a parent popup! + if (popupdata->shell_surface.xdg.popup.xdg_popup == NULL) { + return; + } + + if (popup->flags & SDL_WINDOW_POPUP_MENU) { + SDL_Window *new_focus = popup->parent; + bool set_focus = popup == SDL_GetKeyboardFocus(); + + // Find the highest level window, up to the toplevel parent, that isn't being hidden or destroyed. + while (SDL_WINDOW_IS_POPUP(new_focus) && (new_focus->is_hiding || new_focus->is_destroying)) { + new_focus = new_focus->parent; + + // If some window in the chain currently had focus, set it to the new lowest-level window. + if (!set_focus) { + set_focus = new_focus == SDL_GetKeyboardFocus(); + } + } + + SetKeyboardFocus(new_focus, set_focus); + } + + xdg_popup_destroy(popupdata->shell_surface.xdg.popup.xdg_popup); + xdg_positioner_destroy(popupdata->shell_surface.xdg.popup.xdg_positioner); + popupdata->shell_surface.xdg.popup.xdg_popup = NULL; + popupdata->shell_surface.xdg.popup.xdg_positioner = NULL; + + SDL_PropertiesID props = SDL_GetWindowProperties(popup); + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_POPUP_POINTER, NULL); + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_POSITIONER_POINTER, NULL); +} + +void Wayland_HideWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_VideoData *data = _this->internal; + SDL_WindowData *wind = window->internal; + SDL_PropertiesID props = SDL_GetWindowProperties(window); + + // Custom surfaces have nothing to destroy and are always considered to be 'shown'; nothing to do here. + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_CUSTOM) { + return; + } + + /* The window was shown, but the sync point hasn't yet been reached. + * Pump events to avoid a possible protocol violation. + */ + if (wind->show_hide_sync_required) { + WAYLAND_wl_display_roundtrip(data->display); + } + + wind->shell_surface_status = WAYLAND_SHELL_SURFACE_STATUS_HIDDEN; + + if (wind->server_decoration) { + zxdg_toplevel_decoration_v1_destroy(wind->server_decoration); + wind->server_decoration = NULL; + } + + // Be sure to detach after this is done, otherwise ShowWindow crashes! + if (wind->shell_surface_type != WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP) { + wl_surface_attach(wind->surface, NULL, 0, 0); + wl_surface_commit(wind->surface); + } + + // Clean up the export handle. + if (wind->exported) { + zxdg_exported_v2_destroy(wind->exported); + wind->exported = NULL; + + SDL_SetStringProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_EXPORT_HANDLE_STRING, NULL); + } + + if (wind->xdg_dialog_v1) { + xdg_dialog_v1_destroy(wind->xdg_dialog_v1); + wind->xdg_dialog_v1 = NULL; + } + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (wind->shell_surface.libdecor.frame) { + libdecor_frame_unref(wind->shell_surface.libdecor.frame); + wind->shell_surface.libdecor.frame = NULL; + + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_SURFACE_POINTER, NULL); + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_POINTER, NULL); + } + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP) { + Wayland_ReleasePopup(_this, window); + } else if (wind->shell_surface.xdg.toplevel.xdg_toplevel) { + xdg_toplevel_destroy(wind->shell_surface.xdg.toplevel.xdg_toplevel); + wind->shell_surface.xdg.toplevel.xdg_toplevel = NULL; + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_POINTER, NULL); + } + if (wind->shell_surface.xdg.surface) { + xdg_surface_destroy(wind->shell_surface.xdg.surface); + wind->shell_surface.xdg.surface = NULL; + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_SURFACE_POINTER, NULL); + } + + wind->show_hide_sync_required = true; + struct wl_callback *cb = wl_display_sync(_this->internal->display); + wl_callback_add_listener(cb, &show_hide_sync_listener, (void*)((uintptr_t)window->id)); +} + +static void handle_xdg_activation_done(void *data, + struct xdg_activation_token_v1 *xdg_activation_token_v1, + const char *token) +{ + SDL_WindowData *window = data; + if (xdg_activation_token_v1 == window->activation_token) { + xdg_activation_v1_activate(window->waylandData->activation_manager, + token, + window->surface); + xdg_activation_token_v1_destroy(window->activation_token); + window->activation_token = NULL; + } +} + +static const struct xdg_activation_token_v1_listener activation_listener_xdg = { + handle_xdg_activation_done +}; + +/* The xdg-activation protocol considers "activation" to be one of two things: + * + * 1: Raising a window to the top and flashing the titlebar + * 2: Flashing the titlebar while keeping the window where it is + * + * As you might expect from Wayland, the general policy is to go with #2 unless + * the client can prove to the compositor beyond a reasonable doubt that raising + * the window will not be malicuous behavior. + * + * For SDL this means RaiseWindow and FlashWindow both use the same protocol, + * but in different ways: RaiseWindow will provide as _much_ information as + * possible while FlashWindow will provide as _little_ information as possible, + * to nudge the compositor into doing what we want. + * + * This isn't _strictly_ what the protocol says will happen, but this is what + * current implementations are doing (as of writing, YMMV in the far distant + * future). + * + * -flibit + */ +static void Wayland_activate_window(SDL_VideoData *data, SDL_WindowData *target_wind, bool set_serial) +{ + struct SDL_WaylandInput * input = data->input; + SDL_Window *focus = SDL_GetKeyboardFocus(); + struct wl_surface *requesting_surface = focus ? focus->internal->surface : NULL; + + if (data->activation_manager) { + if (target_wind->activation_token) { + // We're about to overwrite this with a new request + xdg_activation_token_v1_destroy(target_wind->activation_token); + } + + target_wind->activation_token = xdg_activation_v1_get_activation_token(data->activation_manager); + xdg_activation_token_v1_add_listener(target_wind->activation_token, + &activation_listener_xdg, + target_wind); + + /* Note that we are not setting the app_id here. + * + * Hypothetically we could set the app_id from data->classname, but + * that part of the API is for _external_ programs, not ourselves. + * + * -flibit + */ + if (requesting_surface) { + // This specifies the surface from which the activation request is originating, not the activation target surface. + xdg_activation_token_v1_set_surface(target_wind->activation_token, requesting_surface); + } + if (set_serial && input && input->seat) { + xdg_activation_token_v1_set_serial(target_wind->activation_token, input->last_implicit_grab_serial, input->seat); + } + xdg_activation_token_v1_commit(target_wind->activation_token); + } +} + +void Wayland_RaiseWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + Wayland_activate_window(_this->internal, window->internal, true); +} + +bool Wayland_FlashWindow(SDL_VideoDevice *_this, SDL_Window *window, SDL_FlashOperation operation) +{ + /* Not setting the serial will specify 'urgency' without switching focus as per + * https://gitlab.freedesktop.org/wayland/wayland-protocols/-/merge_requests/9#note_854977 + */ + Wayland_activate_window(_this->internal, window->internal, false); + return true; +} + +SDL_FullscreenResult Wayland_SetWindowFullscreen(SDL_VideoDevice *_this, SDL_Window *window, + SDL_VideoDisplay *display, SDL_FullscreenOp fullscreen) +{ + SDL_WindowData *wind = window->internal; + struct wl_output *output = display->internal->output; + + // Custom surfaces have no toplevel to make fullscreen. + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_CUSTOM) { + return SDL_FULLSCREEN_FAILED; + } + + if (wind->show_hide_sync_required) { + WAYLAND_wl_display_roundtrip(_this->internal->display); + } + + // Flushing old events pending a new one, ignore this request. + if (wind->drop_fullscreen_requests) { + return SDL_FULLSCREEN_SUCCEEDED; + } + + wind->drop_fullscreen_requests = true; + FlushPendingEvents(window); + wind->drop_fullscreen_requests = false; + + // Nothing to do if the window is not fullscreen, and this isn't an explicit enter request. + if (!wind->is_fullscreen) { + if (fullscreen == SDL_FULLSCREEN_OP_UPDATE) { + // Request was out of date; signal the video core not to update any state. + return SDL_FULLSCREEN_PENDING; + } else if (fullscreen == SDL_FULLSCREEN_OP_LEAVE) { + // Already not fullscreen; nothing to do. + return SDL_FULLSCREEN_SUCCEEDED; + } + } + + // Don't send redundant fullscreen set/unset events. + if (fullscreen != wind->is_fullscreen) { + wind->fullscreen_was_positioned = fullscreen; + SetFullscreen(window, fullscreen ? output : NULL); + } else if (wind->is_fullscreen) { + /* + * If the window is already fullscreen, this is likely a request to switch between + * fullscreen and fullscreen desktop, change outputs, or change the video mode. + * + * If the window is already positioned on the target output, just update the + * window geometry. + */ + if (wind->last_displayID != display->id) { + wind->fullscreen_was_positioned = true; + SetFullscreen(window, output); + } else { + ConfigureWindowGeometry(window); + CommitLibdecorFrame(window); + + return SDL_FULLSCREEN_SUCCEEDED; + } + } + + return SDL_FULLSCREEN_PENDING; +} + +void Wayland_RestoreWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + + // Not currently fullscreen or maximized, and no state pending; nothing to do. + if (!(window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_MAXIMIZED)) && + !wind->fullscreen_deadline_count && !wind->maximized_restored_deadline_count) { + return; + } + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (!wind->shell_surface.libdecor.frame) { + return; // Can't do anything yet, wait for ShowWindow + } + libdecor_frame_unset_maximized(wind->shell_surface.libdecor.frame); + + ++wind->maximized_restored_deadline_count; + struct wl_callback *cb = wl_display_sync(_this->internal->display); + wl_callback_add_listener(cb, &maximized_restored_deadline_listener, (void *)((uintptr_t)window->id)); + } else +#endif + // Note that xdg-shell does NOT provide a way to unset minimize! + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + if (wind->shell_surface.xdg.toplevel.xdg_toplevel == NULL) { + return; // Can't do anything yet, wait for ShowWindow + } + xdg_toplevel_unset_maximized(wind->shell_surface.xdg.toplevel.xdg_toplevel); + + ++wind->maximized_restored_deadline_count; + struct wl_callback *cb = wl_display_sync(_this->internal->display); + wl_callback_add_listener(cb, &maximized_restored_deadline_listener, (void *)((uintptr_t)window->id)); + } +} + +void Wayland_SetWindowBordered(SDL_VideoDevice *_this, SDL_Window *window, bool bordered) +{ + SDL_WindowData *wind = window->internal; + const SDL_VideoData *viddata = (const SDL_VideoData *)_this->internal; + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (wind->shell_surface.libdecor.frame) { + libdecor_frame_set_visibility(wind->shell_surface.libdecor.frame, bordered); + } + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + if ((viddata->decoration_manager) && (wind->server_decoration)) { + const enum zxdg_toplevel_decoration_v1_mode mode = bordered ? ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE : ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE; + zxdg_toplevel_decoration_v1_set_mode(wind->server_decoration, mode); + } + } +} + +void Wayland_SetWindowResizable(SDL_VideoDevice *_this, SDL_Window *window, bool resizable) +{ +#ifdef HAVE_LIBDECOR_H + const SDL_WindowData *wind = window->internal; + + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (!wind->shell_surface.libdecor.frame) { + return; // Can't do anything yet, wait for ShowWindow + } + if (libdecor_frame_has_capability(wind->shell_surface.libdecor.frame, LIBDECOR_ACTION_RESIZE)) { + if (!resizable) { + libdecor_frame_unset_capabilities(wind->shell_surface.libdecor.frame, LIBDECOR_ACTION_RESIZE); + } + } else if (resizable) { + libdecor_frame_set_capabilities(wind->shell_surface.libdecor.frame, LIBDECOR_ACTION_RESIZE); + } + } +#endif + + /* When changing the resize capability on libdecor windows, the limits must always + * be reapplied, as when libdecor changes states, it overwrites the values internally. + */ + SetMinMaxDimensions(window); + CommitLibdecorFrame(window); +} + +void Wayland_MaximizeWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_VideoData *viddata = _this->internal; + SDL_WindowData *wind = window->internal; + + if (wind->show_hide_sync_required) { + WAYLAND_wl_display_roundtrip(_this->internal->display); + } + + // Not fullscreen, already maximized, and no state pending; nothing to do. + if (!(window->flags & SDL_WINDOW_FULLSCREEN) && (window->flags & SDL_WINDOW_MAXIMIZED) && + !wind->fullscreen_deadline_count && !wind->maximized_restored_deadline_count) { + return; + } + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (!wind->shell_surface.libdecor.frame) { + return; // Can't do anything yet, wait for ShowWindow + } + + // Commit to preserve any pending size data. + wl_surface_commit(wind->surface); + libdecor_frame_set_maximized(wind->shell_surface.libdecor.frame); + + ++wind->maximized_restored_deadline_count; + struct wl_callback *cb = wl_display_sync(viddata->display); + wl_callback_add_listener(cb, &maximized_restored_deadline_listener, (void *)((uintptr_t)window->id)); + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + if (wind->shell_surface.xdg.toplevel.xdg_toplevel == NULL) { + return; // Can't do anything yet, wait for ShowWindow + } + + // Commit to preserve any pending size data. + wl_surface_commit(wind->surface); + xdg_toplevel_set_maximized(wind->shell_surface.xdg.toplevel.xdg_toplevel); + + ++wind->maximized_restored_deadline_count; + struct wl_callback *cb = wl_display_sync(viddata->display); + wl_callback_add_listener(cb, &maximized_restored_deadline_listener, (void *)((uintptr_t)window->id)); + } +} + +void Wayland_MinimizeWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + + if (!(wind->wm_caps & WAYLAND_WM_CAPS_MINIMIZE)) { + return; + } + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (!wind->shell_surface.libdecor.frame) { + return; // Can't do anything yet, wait for ShowWindow + } + libdecor_frame_set_minimized(wind->shell_surface.libdecor.frame); + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_MINIMIZED, 0, 0); + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + if (wind->shell_surface.xdg.toplevel.xdg_toplevel == NULL) { + return; // Can't do anything yet, wait for ShowWindow + } + xdg_toplevel_set_minimized(wind->shell_surface.xdg.toplevel.xdg_toplevel); + SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_MINIMIZED, 0, 0); + } +} + +bool Wayland_SetWindowMouseRect(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_VideoData *data = _this->internal; + + /* This may look suspiciously like SetWindowGrab, despite SetMouseRect not + * implicitly doing a grab. And you're right! Wayland doesn't let us mess + * around with mouse focus whatsoever, so it just happens to be that the + * work that we can do in these two functions ends up being the same. + * + * Just know that this call lets you confine with a rect, SetWindowGrab + * lets you confine without a rect. + */ + if (SDL_RectEmpty(&window->mouse_rect) && !(window->flags & SDL_WINDOW_MOUSE_GRABBED)) { + return Wayland_input_unconfine_pointer(data->input, window); + } else { + return Wayland_input_confine_pointer(data->input, window); + } +} + +bool Wayland_SetWindowMouseGrab(SDL_VideoDevice *_this, SDL_Window *window, bool grabbed) +{ + SDL_VideoData *data = _this->internal; + + if (grabbed) { + return Wayland_input_confine_pointer(data->input, window); + } else if (SDL_RectEmpty(&window->mouse_rect)) { + return Wayland_input_unconfine_pointer(data->input, window); + } + + return true; +} + +bool Wayland_SetWindowKeyboardGrab(SDL_VideoDevice *_this, SDL_Window *window, bool grabbed) +{ + SDL_VideoData *data = _this->internal; + + if (grabbed) { + return Wayland_input_grab_keyboard(window, data->input); + } else { + return Wayland_input_ungrab_keyboard(window); + } +} + +bool Wayland_CreateWindow(SDL_VideoDevice *_this, SDL_Window *window, SDL_PropertiesID create_props) +{ + SDL_WindowData *data; + SDL_VideoData *c = _this->internal; + struct wl_surface *external_surface = (struct wl_surface *)SDL_GetPointerProperty(create_props, SDL_PROP_WINDOW_CREATE_WAYLAND_WL_SURFACE_POINTER, + (struct wl_surface *)SDL_GetPointerProperty(create_props, "sdl2-compat.external_window", NULL)); + const bool custom_surface_role = (external_surface != NULL) || SDL_GetBooleanProperty(create_props, SDL_PROP_WINDOW_CREATE_WAYLAND_SURFACE_ROLE_CUSTOM_BOOLEAN, false); + const bool create_egl_window = !!(window->flags & SDL_WINDOW_OPENGL) || + SDL_GetBooleanProperty(create_props, SDL_PROP_WINDOW_CREATE_WAYLAND_CREATE_EGL_WINDOW_BOOLEAN, false); + + data = SDL_calloc(1, sizeof(*data)); + if (!data) { + return false; + } + + window->internal = data; + + if (window->x == SDL_WINDOWPOS_UNDEFINED) { + window->x = 0; + } + if (window->y == SDL_WINDOWPOS_UNDEFINED) { + window->y = 0; + } + + data->waylandData = c; + data->sdlwindow = window; + + // Default to all capabilities + data->wm_caps = WAYLAND_WM_CAPS_ALL; + + data->scale_factor = 1.0; + + if (SDL_WINDOW_IS_POPUP(window)) { + data->scale_to_display = window->parent->internal->scale_to_display; + data->scale_factor = window->parent->internal->scale_factor; + EnsurePopupPositionIsValid(window, &window->x, &window->y); + } else { + for (int i = 0; i < _this->num_displays; i++) { + data->scale_factor = SDL_max(data->scale_factor, _this->displays[i]->internal->scale_factor); + } + } + + data->outputs = NULL; + data->num_outputs = 0; + data->scale_to_display = c->scale_to_display_enabled; + + // Cache the app_id at creation time, as it may change before the window is mapped. + data->app_id = SDL_strdup(SDL_GetAppID()); + + if (!data->scale_to_display) { + data->requested.logical_width = window->floating.w; + data->requested.logical_height = window->floating.h; + } else { + data->requested.logical_width = PixelToPoint(window, window->floating.w); + data->requested.logical_height = PixelToPoint(window, window->floating.h); + data->requested.pixel_width = window->floating.w; + data->requested.pixel_height = window->floating.h; + } + + if (!external_surface) { + data->surface = wl_compositor_create_surface(c->compositor); + wl_surface_add_listener(data->surface, &surface_listener, data); + wl_surface_set_user_data(data->surface, data); + SDL_WAYLAND_register_surface(data->surface); + } else { + window->flags |= SDL_WINDOW_EXTERNAL; + data->surface = external_surface; + + /* External surfaces are registered by being put in a list, as changing tags or userdata + * can cause problems with external toolkits. + */ + Wayland_AddWindowDataToExternalList(data); + } + + /* Always attach a viewport and fractional scale manager if available and the surface is not custom/external, + * or the custom/external surface was explicitly flagged as high pixel density aware, which signals that the + * application wants SDL to handle scaling. + */ + if (!custom_surface_role || (window->flags & SDL_WINDOW_HIGH_PIXEL_DENSITY)) { + if (c->viewporter) { + data->viewport = wp_viewporter_get_viewport(c->viewporter, data->surface); + + // The viewport always uses the entire buffer. + wp_viewport_set_source(data->viewport, + wl_fixed_from_int(-1), wl_fixed_from_int(-1), + wl_fixed_from_int(-1), wl_fixed_from_int(-1)); + } + if (c->fractional_scale_manager) { + data->fractional_scale = wp_fractional_scale_manager_v1_get_fractional_scale(c->fractional_scale_manager, data->surface); + wp_fractional_scale_v1_add_listener(data->fractional_scale, &fractional_scale_listener, data); + } + } + + if (!custom_surface_role) { + if (c->wp_color_manager_v1) { + data->wp_color_management_surface_feedback = wp_color_manager_v1_get_surface_feedback(c->wp_color_manager_v1, data->surface); + wp_color_management_surface_feedback_v1_add_listener(data->wp_color_management_surface_feedback, &color_management_surface_feedback_listener, data); + Wayland_GetColorInfoForWindow(data, true); + } else if (c->frog_color_management_factory_v1) { + data->frog_color_managed_surface = frog_color_management_factory_v1_get_color_managed_surface(c->frog_color_management_factory_v1, data->surface); + frog_color_managed_surface_add_listener(data->frog_color_managed_surface, &frog_surface_listener, data); + } + + if (c->wp_alpha_modifier_v1) { + data->wp_alpha_modifier_surface_v1 = wp_alpha_modifier_v1_get_surface(c->wp_alpha_modifier_v1, data->surface); + wp_alpha_modifier_surface_v1_set_multiplier(data->wp_alpha_modifier_surface_v1, SDL_MAX_UINT32); + } + } + + // Must be called before EGL configuration to set the drawable backbuffer size. + ConfigureWindowGeometry(window); + + /* Fire a callback when the compositor wants a new frame rendered. + * Right now this only matters for OpenGL; we use this callback to add a + * wait timeout that avoids getting deadlocked by the compositor when the + * window isn't visible. + */ + if (window->flags & SDL_WINDOW_OPENGL) { + data->gles_swap_frame_event_queue = WAYLAND_wl_display_create_queue(data->waylandData->display); + data->gles_swap_frame_surface_wrapper = WAYLAND_wl_proxy_create_wrapper(data->surface); + WAYLAND_wl_proxy_set_queue((struct wl_proxy *)data->gles_swap_frame_surface_wrapper, data->gles_swap_frame_event_queue); + data->gles_swap_frame_callback = wl_surface_frame(data->gles_swap_frame_surface_wrapper); + wl_callback_add_listener(data->gles_swap_frame_callback, &gles_swap_frame_listener, data); + } + + // No frame callback on external surfaces as it may already have one attached. + if (!external_surface) { + // Fire a callback when the compositor wants a new frame to set the surface damage region. + data->surface_frame_callback = wl_surface_frame(data->surface); + wl_callback_add_listener(data->surface_frame_callback, &surface_frame_listener, data); + } + + if (window->flags & SDL_WINDOW_TRANSPARENT) { + if (_this->gl_config.alpha_size == 0) { + _this->gl_config.alpha_size = 8; + } + } + + if (create_egl_window) { + data->egl_window = WAYLAND_wl_egl_window_create(data->surface, data->current.pixel_width, data->current.pixel_height); + } + +#ifdef SDL_VIDEO_OPENGL_EGL + if (window->flags & SDL_WINDOW_OPENGL) { + // Create the GLES window surface + data->egl_surface = SDL_EGL_CreateSurface(_this, window, (NativeWindowType)data->egl_window); + + if (data->egl_surface == EGL_NO_SURFACE) { + return false; // SDL_EGL_CreateSurface should have set error + } + } +#endif + + if (c->relative_mouse_mode) { + Wayland_input_enable_relative_pointer(c->input); + } + + // We may need to create an idle inhibitor for this new window + Wayland_SuspendScreenSaver(_this); + + if (!custom_surface_role) { +#ifdef HAVE_LIBDECOR_H + if (c->shell.libdecor && !SDL_WINDOW_IS_POPUP(window)) { + data->shell_surface_type = WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR; + } else +#endif + if (c->shell.xdg) { + if (SDL_WINDOW_IS_POPUP(window)) { + data->shell_surface_type = WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP; + } else { + data->shell_surface_type = WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL; + } + } // All other cases will be WAYLAND_SURFACE_UNKNOWN + } else { + // Roleless and external surfaces are always considered to be in the shown state by the backend. + data->shell_surface_type = WAYLAND_SHELL_SURFACE_TYPE_CUSTOM; + data->shell_surface_status = WAYLAND_SHELL_SURFACE_STATUS_SHOWN; + } + + if (SDL_GetHintBoolean(SDL_HINT_VIDEO_DOUBLE_BUFFER, false)) { + data->double_buffer = true; + } + + SDL_PropertiesID props = SDL_GetWindowProperties(window); + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_DISPLAY_POINTER, data->waylandData->display); + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER, data->surface); + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_VIEWPORT_POINTER, data->viewport); + SDL_SetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_EGL_WINDOW_POINTER, data->egl_window); + + data->hit_test_result = SDL_HITTEST_NORMAL; + + return true; +} + +void Wayland_SetWindowMinimumSize(SDL_VideoDevice *_this, SDL_Window *window) +{ + // Will be committed when Wayland_SetWindowSize() is called by the video core. + SetMinMaxDimensions(window); +} + +void Wayland_SetWindowMaximumSize(SDL_VideoDevice *_this, SDL_Window *window) +{ + // Will be committed when Wayland_SetWindowSize() is called by the video core. + SetMinMaxDimensions(window); +} + +bool Wayland_SetWindowPosition(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + + // Only popup windows can be positioned relative to the parent. + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP) { + if (wind->shell_surface.xdg.popup.xdg_popup && + xdg_popup_get_version(wind->shell_surface.xdg.popup.xdg_popup) < XDG_POPUP_REPOSITION_SINCE_VERSION) { + return SDL_Unsupported(); + } + + RepositionPopup(window, false); + return true; + } else if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR || wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + /* Catch up on any pending state before attempting to change the fullscreen window + * display via a set fullscreen call to make sure the window doesn't have a pending + * leave fullscreen event that it might override. + */ + FlushPendingEvents(window); + + if (wind->is_fullscreen) { + SDL_VideoDisplay *display = SDL_GetVideoDisplayForFullscreenWindow(window); + if (display && wind->last_displayID != display->id) { + struct wl_output *output = display->internal->output; + SetFullscreen(window, output); + + return true; + } + } + } + return SDL_SetError("wayland cannot position non-popup windows"); +} + +void Wayland_SetWindowSize(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + + /* Flush any pending state operations, as fullscreen windows do not get + * explicitly resized, not strictly obeying the size of a maximized window + * is a protocol violation, and pending restore events might result in a + * configure event overwriting the requested size. + * + * Calling this on a custom surface is informative, so the size must + * always be passed through. + */ + FlushPendingEvents(window); + + // Maximized and fullscreen windows don't get resized. + if (!(window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_MAXIMIZED)) || + wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_CUSTOM) { + if (!wind->scale_to_display) { + wind->requested.logical_width = window->pending.w; + wind->requested.logical_height = window->pending.h; + } else { + wind->requested.logical_width = PixelToPoint(window, window->pending.w); + wind->requested.logical_height = PixelToPoint(window, window->pending.h); + wind->requested.pixel_width = window->pending.w; + wind->requested.pixel_height = window->pending.h; + } + + ConfigureWindowGeometry(window); + } else { + // Can't resize the window. + window->last_size_pending = false; + } + + // Always commit, as this may be in response to a min/max limit change. + CommitLibdecorFrame(window); +} + +void Wayland_GetWindowSizeInPixels(SDL_VideoDevice *_this, SDL_Window *window, int *w, int *h) +{ + SDL_WindowData *data = window->internal; + + *w = data->current.pixel_width; + *h = data->current.pixel_height; +} + +float Wayland_GetWindowContentScale(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + + if (window->flags & SDL_WINDOW_HIGH_PIXEL_DENSITY || wind->scale_to_display || wind->fullscreen_exclusive) { + return (float)wind->scale_factor; + } + + return 1.0f; +} + +SDL_DisplayID Wayland_GetDisplayForWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + + if (wind) { + return wind->last_displayID; + } + + return 0; +} + +bool Wayland_SetWindowOpacity(SDL_VideoDevice *_this, SDL_Window *window, float opacity) +{ + SDL_WindowData *wind = window->internal; + + if (wind->wp_alpha_modifier_surface_v1) { + SetSurfaceOpaqueRegion(wind, !(window->flags & SDL_WINDOW_TRANSPARENT) && opacity == 1.0f); + wp_alpha_modifier_surface_v1_set_multiplier(wind->wp_alpha_modifier_surface_v1, (Uint32)((double)SDL_MAX_UINT32 * (double)opacity)); + + return true; + } + + return SDL_SetError("wayland: set window opacity failed; compositor lacks support for the required wp_alpha_modifier_v1 protocol"); +} + +void Wayland_SetWindowTitle(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + const char *title = window->title ? window->title : ""; + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR && wind->shell_surface.libdecor.frame) { + libdecor_frame_set_title(wind->shell_surface.libdecor.frame, title); + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL && wind->shell_surface.xdg.toplevel.xdg_toplevel) { + xdg_toplevel_set_title(wind->shell_surface.xdg.toplevel.xdg_toplevel, title); + } +} + +bool Wayland_SetWindowIcon(SDL_VideoDevice *_this, SDL_Window *window, SDL_Surface *icon) +{ + SDL_WindowData *wind = window->internal; + struct xdg_toplevel *toplevel = NULL; + + if (!_this->internal->xdg_toplevel_icon_manager_v1) { + return SDL_SetError("wayland: cannot set icon; required xdg_toplevel_icon_v1 protocol not supported"); + } + + if (icon->w != icon->h) { + return SDL_SetError("wayland: icon width and height must be equal, got %ix%i", icon->w, icon->h); + } + + int image_count = 0; + SDL_Surface **images = SDL_GetSurfaceImages(icon, &image_count); + if (!images || !image_count) { + return false; + } + + // Release the old icon resources. + if (wind->xdg_toplevel_icon_v1) { + xdg_toplevel_icon_v1_destroy(wind->xdg_toplevel_icon_v1); + wind->xdg_toplevel_icon_v1 = NULL; + } + + for (int i = 0; i < wind->icon_buffer_count; ++i) { + Wayland_ReleaseSHMBuffer(&wind->icon_buffers[i]); + } + SDL_free(wind->icon_buffers); + wind->icon_buffer_count = 0; + + wind->xdg_toplevel_icon_v1 = xdg_toplevel_icon_manager_v1_create_icon(_this->internal->xdg_toplevel_icon_manager_v1); + wind->icon_buffers = SDL_calloc(image_count, sizeof(struct Wayland_SHMBuffer)); + if (!wind->icon_buffers) { + goto failure_cleanup; + } + + for (int i = 0; i < image_count; ++i) { + if (images[i]->w == images[i]->h) { + struct Wayland_SHMBuffer *buffer = &wind->icon_buffers[wind->icon_buffer_count]; + + if (!Wayland_AllocSHMBuffer(images[i]->w, images[i]->h, buffer)) { + SDL_SetError("wayland: failed to allocate SHM buffer for the icon"); + goto failure_cleanup; + } + + SDL_PremultiplyAlpha(images[i]->w, images[i]->h, images[i]->format, images[i]->pixels, images[i]->pitch, SDL_PIXELFORMAT_ARGB8888, buffer->shm_data, images[i]->w * 4, true); + const int scale = (int)SDL_ceil((double)images[i]->w / (double)icon->w); + xdg_toplevel_icon_v1_add_buffer(wind->xdg_toplevel_icon_v1, buffer->wl_buffer, scale); + wind->icon_buffer_count++; + } else { + SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "wayland: icon width and height must be equal, got %ix%i for image level %i; skipping", images[i]->w, images[i]->h, i); + } + } + + SDL_free(images); + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR && wind->shell_surface.libdecor.frame) { + toplevel = libdecor_frame_get_xdg_toplevel(wind->shell_surface.libdecor.frame); + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL && wind->shell_surface.xdg.toplevel.xdg_toplevel) { + toplevel = wind->shell_surface.xdg.toplevel.xdg_toplevel; + } + + if (toplevel) { + xdg_toplevel_icon_manager_v1_set_icon(_this->internal->xdg_toplevel_icon_manager_v1, toplevel, wind->xdg_toplevel_icon_v1); + } + + return true; + +failure_cleanup: + + if (wind->xdg_toplevel_icon_v1) { + xdg_toplevel_icon_v1_destroy(wind->xdg_toplevel_icon_v1); + wind->xdg_toplevel_icon_v1 = NULL; + } + + for (int i = 0; i < wind->icon_buffer_count; ++i) { + Wayland_ReleaseSHMBuffer(&wind->icon_buffers[i]); + } + SDL_free(wind->icon_buffers); + wind->icon_buffers = NULL; + wind->icon_buffer_count = 0; + + return false; +} + +void *Wayland_GetWindowICCProfile(SDL_VideoDevice *_this, SDL_Window *window, size_t *size) +{ + SDL_WindowData *wind = window->internal; + void *ret = NULL; + + if (wind->icc_size > 0) { + void *icc_map = mmap(NULL, wind->icc_size, PROT_READ, MAP_PRIVATE, wind->icc_fd, 0); + if (icc_map != MAP_FAILED) { + ret = SDL_malloc(wind->icc_size); + if (ret) { + *size = wind->icc_size; + SDL_memcpy(ret, icc_map, *size); + } + munmap(icc_map, wind->icc_size); + } + } + + return ret; +} + +bool Wayland_SyncWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_WindowData *wind = window->internal; + + do { + WAYLAND_wl_display_roundtrip(_this->internal->display); + } while (wind->fullscreen_deadline_count || wind->maximized_restored_deadline_count); + + return true; +} + +void Wayland_ShowWindowSystemMenu(SDL_Window *window, int x, int y) +{ + SDL_WindowData *wind = window->internal; + + if (wind->scale_to_display) { + x = PixelToPoint(window, x); + y = PixelToPoint(window, y); + } + +#ifdef HAVE_LIBDECOR_H + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR) { + if (wind->shell_surface.libdecor.frame) { + libdecor_frame_show_window_menu(wind->shell_surface.libdecor.frame, wind->waylandData->input->seat, wind->waylandData->input->last_implicit_grab_serial, x, y); + } + } else +#endif + if (wind->shell_surface_type == WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL) { + if (wind->shell_surface.xdg.toplevel.xdg_toplevel) { + xdg_toplevel_show_window_menu(wind->shell_surface.xdg.toplevel.xdg_toplevel, wind->waylandData->input->seat, wind->waylandData->input->last_implicit_grab_serial, x, y); + } + } +} + +bool Wayland_SuspendScreenSaver(SDL_VideoDevice *_this) +{ + SDL_VideoData *data = _this->internal; + +#ifdef SDL_USE_LIBDBUS + if (SDL_DBus_ScreensaverInhibit(_this->suspend_screensaver)) { + return true; + } +#endif + + /* The idle_inhibit_unstable_v1 protocol suspends the screensaver + on a per wl_surface basis, but SDL assumes that suspending + the screensaver can be done independently of any window. + + To reconcile these differences, we propagate the idle inhibit + state to each window. If there is no window active, we will + be able to inhibit idle once the first window is created. + */ + if (data->idle_inhibit_manager) { + SDL_Window *window = _this->windows; + while (window) { + SDL_WindowData *win_data = window->internal; + + if (_this->suspend_screensaver && !win_data->idle_inhibitor) { + win_data->idle_inhibitor = + zwp_idle_inhibit_manager_v1_create_inhibitor(data->idle_inhibit_manager, + win_data->surface); + } else if (!_this->suspend_screensaver && win_data->idle_inhibitor) { + zwp_idle_inhibitor_v1_destroy(win_data->idle_inhibitor); + win_data->idle_inhibitor = NULL; + } + + window = window->next; + } + } + + return true; +} + +void Wayland_DestroyWindow(SDL_VideoDevice *_this, SDL_Window *window) +{ + SDL_VideoData *data = _this->internal; + SDL_WindowData *wind = window->internal; + + if (data && wind) { + /* Roundtrip before destroying the window to make sure that it has received input leave events, so that + * no internal structures are left pointing to the destroyed window. + */ + if (wind->show_hide_sync_required) { + WAYLAND_wl_display_roundtrip(data->display); + } + +#ifdef SDL_VIDEO_OPENGL_EGL + if (wind->egl_surface) { + SDL_EGL_DestroySurface(_this, wind->egl_surface); + } +#endif + if (wind->egl_window) { + WAYLAND_wl_egl_window_destroy(wind->egl_window); + } + + if (wind->idle_inhibitor) { + zwp_idle_inhibitor_v1_destroy(wind->idle_inhibitor); + } + + if (wind->activation_token) { + xdg_activation_token_v1_destroy(wind->activation_token); + } + + if (wind->viewport) { + wp_viewport_destroy(wind->viewport); + } + + if (wind->fractional_scale) { + wp_fractional_scale_v1_destroy(wind->fractional_scale); + } + + if (wind->wp_alpha_modifier_surface_v1) { + wp_alpha_modifier_surface_v1_destroy(wind->wp_alpha_modifier_surface_v1); + } + + if (wind->frog_color_managed_surface) { + frog_color_managed_surface_destroy(wind->frog_color_managed_surface); + } + + if (wind->wp_color_management_surface_feedback) { + Wayland_FreeColorInfoState(wind->color_info_state); + wp_color_management_surface_feedback_v1_destroy(wind->wp_color_management_surface_feedback); + } + + SDL_free(wind->outputs); + SDL_free(wind->app_id); + + if (wind->gles_swap_frame_callback) { + wl_callback_destroy(wind->gles_swap_frame_callback); + WAYLAND_wl_proxy_wrapper_destroy(wind->gles_swap_frame_surface_wrapper); + WAYLAND_wl_event_queue_destroy(wind->gles_swap_frame_event_queue); + } + + if (wind->surface_frame_callback) { + wl_callback_destroy(wind->surface_frame_callback); + } + + if (!(window->flags & SDL_WINDOW_EXTERNAL)) { + wl_surface_destroy(wind->surface); + } else { + Wayland_RemoveWindowDataFromExternalList(wind); + } + + if (wind->xdg_toplevel_icon_v1) { + xdg_toplevel_icon_v1_destroy(wind->xdg_toplevel_icon_v1); + } + + for (int i = 0; i < wind->icon_buffer_count; ++i) { + Wayland_ReleaseSHMBuffer(&wind->icon_buffers[i]); + } + SDL_free(wind->icon_buffers); + wind->icon_buffer_count = 0; + + SDL_free(wind); + WAYLAND_wl_display_flush(data->display); + } + window->internal = NULL; +} + +#endif // SDL_VIDEO_DRIVER_WAYLAND diff --git a/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandwindow.h b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandwindow.h new file mode 100644 index 0000000..619fd79 --- /dev/null +++ b/contrib/SDL-3.2.8/src/video/wayland/SDL_waylandwindow.h @@ -0,0 +1,248 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "SDL_internal.h" + +#ifndef SDL_waylandwindow_h_ +#define SDL_waylandwindow_h_ + +#include "../SDL_sysvideo.h" +#include "../../events/SDL_touch_c.h" + +#include "SDL_waylandvideo.h" +#include "SDL_waylandshmbuffer.h" + +struct SDL_WaylandInput; + +struct SDL_WindowData +{ + SDL_Window *sdlwindow; + SDL_VideoData *waylandData; + struct wl_surface *surface; + struct wl_callback *gles_swap_frame_callback; + struct wl_event_queue *gles_swap_frame_event_queue; + struct wl_surface *gles_swap_frame_surface_wrapper; + struct wl_callback *surface_frame_callback; + + union + { +#ifdef HAVE_LIBDECOR_H + struct + { + struct libdecor_frame *frame; + bool initial_configure_seen; + } libdecor; +#endif + struct + { + struct xdg_surface *surface; + union + { + struct + { + struct xdg_toplevel *xdg_toplevel; + } toplevel; + struct + { + struct xdg_popup *xdg_popup; + struct xdg_positioner *xdg_positioner; + } popup; + }; + bool initial_configure_seen; + } xdg; + } shell_surface; + enum + { + WAYLAND_SHELL_SURFACE_TYPE_UNKNOWN = 0, + WAYLAND_SHELL_SURFACE_TYPE_XDG_TOPLEVEL, + WAYLAND_SHELL_SURFACE_TYPE_XDG_POPUP, + WAYLAND_SHELL_SURFACE_TYPE_LIBDECOR, + WAYLAND_SHELL_SURFACE_TYPE_CUSTOM + } shell_surface_type; + enum + { + WAYLAND_SHELL_SURFACE_STATUS_HIDDEN = 0, + WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_CONFIGURE, + WAYLAND_SHELL_SURFACE_STATUS_WAITING_FOR_FRAME, + WAYLAND_SHELL_SURFACE_STATUS_SHOW_PENDING, + WAYLAND_SHELL_SURFACE_STATUS_SHOWN + } shell_surface_status; + enum + { + WAYLAND_WM_CAPS_WINDOW_MENU = 0x01, + WAYLAND_WM_CAPS_MAXIMIZE = 0x02, + WAYLAND_WM_CAPS_FULLSCREEN = 0x04, + WAYLAND_WM_CAPS_MINIMIZE = 0x08, + + WAYLAND_WM_CAPS_ALL = WAYLAND_WM_CAPS_WINDOW_MENU | + WAYLAND_WM_CAPS_MAXIMIZE | + WAYLAND_WM_CAPS_FULLSCREEN | + WAYLAND_WM_CAPS_MINIMIZE + } wm_caps; + + struct wl_egl_window *egl_window; + struct SDL_WaylandInput *keyboard_device; +#ifdef SDL_VIDEO_OPENGL_EGL + EGLSurface egl_surface; +#endif + struct zwp_locked_pointer_v1 *locked_pointer; + struct zwp_confined_pointer_v1 *confined_pointer; + struct zxdg_toplevel_decoration_v1 *server_decoration; + struct zwp_keyboard_shortcuts_inhibitor_v1 *key_inhibitor; + struct zwp_idle_inhibitor_v1 *idle_inhibitor; + struct xdg_activation_token_v1 *activation_token; + struct wp_viewport *viewport; + struct wp_fractional_scale_v1 *fractional_scale; + struct zxdg_exported_v2 *exported; + struct xdg_dialog_v1 *xdg_dialog_v1; + struct wp_alpha_modifier_surface_v1 *wp_alpha_modifier_surface_v1; + struct xdg_toplevel_icon_v1 *xdg_toplevel_icon_v1; + struct frog_color_managed_surface *frog_color_managed_surface; + struct wp_color_management_surface_feedback_v1 *wp_color_management_surface_feedback; + + struct Wayland_ColorInfoState *color_info_state; + + SDL_AtomicInt swap_interval_ready; + + SDL_DisplayData **outputs; + int num_outputs; + + SDL_Window *keyboard_focus; + + char *app_id; + double scale_factor; + + struct Wayland_SHMBuffer *icon_buffers; + int icon_buffer_count; + + struct + { + double x; + double y; + } pointer_scale; + + // The in-flight window size request. + struct + { + // The requested logical window size. + int logical_width; + int logical_height; + + // The size of the window in pixels, when using screen space scaling. + int pixel_width; + int pixel_height; + } requested; + + // The current size of the window and drawable backing store. + struct + { + // The size of the underlying window. + int logical_width; + int logical_height; + + // The size of the window backbuffer in pixels. + int pixel_width; + int pixel_height; + } current; + + // The last compositor requested parameters; used for deduplication of window geometry configuration. + struct + { + int width; + int height; + } last_configure; + + // System enforced window size limits. + struct + { + // Minimum allowed logical window size. + int min_width; + int min_height; + } system_limits; + + struct + { + int width; + int height; + } toplevel_bounds; + + SDL_DisplayID last_displayID; + int fullscreen_deadline_count; + int maximized_restored_deadline_count; + Uint64 last_focus_event_time_ns; + int icc_fd; + Uint32 icc_size; + bool floating; + bool suspended; + bool resizing; + bool active; + bool drop_interactive_resizes; + bool is_fullscreen; + bool fullscreen_exclusive; + bool drop_fullscreen_requests; + bool fullscreen_was_positioned; + bool show_hide_sync_required; + bool scale_to_display; + bool reparenting_required; + bool double_buffer; + + SDL_HitTestResult hit_test_result; + + struct wl_list external_window_list_link; +}; + +extern void Wayland_ShowWindow(SDL_VideoDevice *_this, SDL_Window *window); +extern void Wayland_HideWindow(SDL_VideoDevice *_this, SDL_Window *window); +extern void Wayland_RaiseWindow(SDL_VideoDevice *_this, SDL_Window *window); +extern SDL_FullscreenResult Wayland_SetWindowFullscreen(SDL_VideoDevice *_this, SDL_Window *window, SDL_VideoDisplay *_display, SDL_FullscreenOp fullscreen); +extern void Wayland_MaximizeWindow(SDL_VideoDevice *_this, SDL_Window *window); +extern void Wayland_MinimizeWindow(SDL_VideoDevice *_this, SDL_Window *window); +extern bool Wayland_SetWindowMouseRect(SDL_VideoDevice *_this, SDL_Window *window); +extern bool Wayland_SetWindowMouseGrab(SDL_VideoDevice *_this, SDL_Window *window, bool grabbed); +extern bool Wayland_SetWindowKeyboardGrab(SDL_VideoDevice *_this, SDL_Window *window, bool grabbed); +extern void Wayland_RestoreWindow(SDL_VideoDevice *_this, SDL_Window *window); +extern void Wayland_SetWindowBordered(SDL_VideoDevice *_this, SDL_Window *window, bool bordered); +extern void Wayland_SetWindowResizable(SDL_VideoDevice *_this, SDL_Window *window, bool resizable); +extern bool Wayland_CreateWindow(SDL_VideoDevice *_this, SDL_Window *window, SDL_PropertiesID create_props); +extern bool Wayland_SetWindowPosition(SDL_VideoDevice *_this, SDL_Window *window); +extern void Wayland_SetWindowSize(SDL_VideoDevice *_this, SDL_Window *window); +extern void Wayland_SetWindowMinimumSize(SDL_VideoDevice *_this, SDL_Window *window); +extern void Wayland_SetWindowMaximumSize(SDL_VideoDevice *_this, SDL_Window *window); +extern void Wayland_GetWindowSizeInPixels(SDL_VideoDevice *_this, SDL_Window *window, int *w, int *h); +extern SDL_DisplayID Wayland_GetDisplayForWindow(SDL_VideoDevice *_this, SDL_Window *window); +extern bool Wayland_SetWindowParent(SDL_VideoDevice *_this, SDL_Window *window, SDL_Window *parent_window); +extern bool Wayland_SetWindowModal(SDL_VideoDevice *_this, SDL_Window *window, bool modal); +extern bool Wayland_SetWindowOpacity(SDL_VideoDevice *_this, SDL_Window *window, float opacity); +extern void Wayland_SetWindowTitle(SDL_VideoDevice *_this, SDL_Window *window); +extern void Wayland_ShowWindowSystemMenu(SDL_Window *window, int x, int y); +extern void Wayland_DestroyWindow(SDL_VideoDevice *_this, SDL_Window *window); +extern bool Wayland_SuspendScreenSaver(SDL_VideoDevice *_this); +extern bool Wayland_SetWindowIcon(SDL_VideoDevice *_this, SDL_Window *window, SDL_Surface *icon); +extern float Wayland_GetWindowContentScale(SDL_VideoDevice *_this, SDL_Window *window); +extern void *Wayland_GetWindowICCProfile(SDL_VideoDevice *_this, SDL_Window *window, size_t *size); + +extern bool Wayland_SetWindowHitTest(SDL_Window *window, bool enabled); +extern bool Wayland_FlashWindow(SDL_VideoDevice *_this, SDL_Window *window, SDL_FlashOperation operation); +extern bool Wayland_SyncWindow(SDL_VideoDevice *_this, SDL_Window *window); + +extern void Wayland_RemoveOutputFromWindow(SDL_WindowData *window, SDL_DisplayData *display_data); + +#endif // SDL_waylandwindow_h_ -- cgit v1.2.3