Path: blob/master/platform/linuxbsd/wayland/wayland_thread.cpp
22224 views
/**************************************************************************/1/* wayland_thread.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "wayland_thread.h"3132#include "core/config/engine.h"3334#ifdef WAYLAND_ENABLED3536#ifdef __FreeBSD__37#include <dev/evdev/input-event-codes.h>38#else39// Assume Linux.40#include <linux/input-event-codes.h>41#endif4243// For the actual polling thread.44#include <poll.h>4546// For shared memory buffer creation.47#include <fcntl.h>48#include <sys/mman.h>49#include <unistd.h>5051// Fix the wl_array_for_each macro to work with C++. This is based on the52// original from `wayland-util.h` in the Wayland client library.53#undef wl_array_for_each54#define wl_array_for_each(pos, array) \55for (pos = (decltype(pos))(array)->data; (const char *)pos < ((const char *)(array)->data + (array)->size); (pos)++)5657#define WAYLAND_THREAD_DEBUG_LOGS_ENABLED58#ifdef WAYLAND_THREAD_DEBUG_LOGS_ENABLED59#define DEBUG_LOG_WAYLAND_THREAD(...) print_verbose(__VA_ARGS__)60#else61#define DEBUG_LOG_WAYLAND_THREAD(...)62#endif6364// Since we're never going to use this interface directly, it's not worth65// generating the whole deal.66#define FIFO_INTERFACE_NAME "wp_fifo_manager_v1"6768// Read the content pointed by fd into a Vector<uint8_t>.69Vector<uint8_t> WaylandThread::_read_fd(int fd) {70// This is pretty much an arbitrary size.71uint32_t chunk_size = 2048;7273LocalVector<uint8_t> data;74data.resize(chunk_size);7576uint32_t bytes_read = 0;7778while (true) {79ssize_t last_bytes_read = read(fd, data.ptr() + bytes_read, chunk_size);80if (last_bytes_read < 0) {81ERR_PRINT(vformat("Read error %d.", errno));8283data.clear();84break;85}8687if (last_bytes_read == 0) {88// We're done, we've reached the EOF.89DEBUG_LOG_WAYLAND_THREAD(vformat("Done reading %d bytes.", bytes_read));9091close(fd);9293data.resize(bytes_read);94break;95}9697DEBUG_LOG_WAYLAND_THREAD(vformat("Read chunk of %d bytes.", last_bytes_read));9899bytes_read += last_bytes_read;100101// Increase the buffer size by one chunk in preparation of the next read.102data.resize(bytes_read + chunk_size);103}104105return Vector<uint8_t>(data);106}107108// Based on the wayland book's shared memory boilerplate (PD/CC0).109// See: https://wayland-book.com/surfaces/shared-memory.html110int WaylandThread::_allocate_shm_file(size_t size) {111int retries = 100;112113do {114// Generate a random name.115char name[] = "/wl_shm-godot-XXXXXX";116for (long unsigned int i = sizeof(name) - 7; i < sizeof(name) - 1; i++) {117name[i] = Math::random('A', 'Z');118}119120// Try to open a shared memory object with that name.121int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);122if (fd >= 0) {123// Success, unlink its name as we just need the file descriptor.124shm_unlink(name);125126// Resize the file to the requested length.127int ret;128do {129ret = ftruncate(fd, size);130} while (ret < 0 && errno == EINTR);131132if (ret < 0) {133close(fd);134return -1;135}136137return fd;138}139140retries--;141} while (retries > 0 && errno == EEXIST);142143return -1;144}145146// Return the content of a wl_data_offer.147Vector<uint8_t> WaylandThread::_wl_data_offer_read(struct wl_display *p_display, const char *p_mime, struct wl_data_offer *p_offer) {148if (!p_offer) {149return Vector<uint8_t>();150}151152int fds[2];153if (pipe(fds) == 0) {154wl_data_offer_receive(p_offer, p_mime, fds[1]);155156// Let the compositor know about the pipe.157// NOTE: It's important to just flush and not roundtrip here as we would risk158// running some cleanup event, like for example `wl_data_device::leave`. We're159// going to wait for the message anyways as the read will probably block if160// the compositor doesn't read from the other end of the pipe.161wl_display_flush(p_display);162163// Close the write end of the pipe, which we don't need and would otherwise164// just stall our next `read`s.165close(fds[1]);166167return _read_fd(fds[0]);168}169170return Vector<uint8_t>();171}172173// Read the content of a wp_primary_selection_offer.174Vector<uint8_t> WaylandThread::_wp_primary_selection_offer_read(struct wl_display *p_display, const char *p_mime, struct zwp_primary_selection_offer_v1 *p_offer) {175if (!p_offer) {176return Vector<uint8_t>();177}178179int fds[2];180if (pipe(fds) == 0) {181zwp_primary_selection_offer_v1_receive(p_offer, p_mime, fds[1]);182183// NOTE: It's important to just flush and not roundtrip here as we would risk184// running some cleanup event, like for example `wl_data_device::leave`. We're185// going to wait for the message anyways as the read will probably block if186// the compositor doesn't read from the other end of the pipe.187wl_display_flush(p_display);188189// Close the write end of the pipe, which we don't need and would otherwise190// just stall our next `read`s.191close(fds[1]);192193return _read_fd(fds[0]);194}195196return Vector<uint8_t>();197}198199Ref<InputEventKey> WaylandThread::_seat_state_get_key_event(SeatState *p_ss, xkb_keycode_t p_keycode, bool p_pressed) {200Ref<InputEventKey> event;201202ERR_FAIL_NULL_V(p_ss, event);203204Key shifted_key = KeyMappingXKB::get_keycode(xkb_state_key_get_one_sym(p_ss->xkb_state, p_keycode));205206Key plain_key = Key::NONE;207// NOTE: xkbcommon's API really encourages to apply the modifier state but we208// only want a "plain" symbol so that we can convert it into a godot keycode.209const xkb_keysym_t *syms = nullptr;210int num_sys = xkb_keymap_key_get_syms_by_level(p_ss->xkb_keymap, p_keycode, p_ss->current_layout_index, 0, &syms);211if (num_sys > 0 && syms) {212plain_key = KeyMappingXKB::get_keycode(syms[0]);213}214215Key physical_keycode = KeyMappingXKB::get_scancode(p_keycode);216KeyLocation key_location = KeyMappingXKB::get_location(p_keycode);217uint32_t unicode = xkb_state_key_get_utf32(p_ss->xkb_state, p_keycode);218219Key keycode = Key::NONE;220221if ((shifted_key & Key::SPECIAL) != Key::NONE || (plain_key & Key::SPECIAL) != Key::NONE) {222keycode = shifted_key;223}224225if (keycode == Key::NONE) {226keycode = plain_key;227}228229if (keycode == Key::NONE) {230keycode = physical_keycode;231}232233if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {234keycode -= 'a' - 'A';235}236237if (physical_keycode == Key::NONE && keycode == Key::NONE && unicode == 0) {238return event;239}240241event.instantiate();242243event->set_window_id(p_ss->focused_id);244245// Set all pressed modifiers.246event->set_shift_pressed(p_ss->shift_pressed);247event->set_ctrl_pressed(p_ss->ctrl_pressed);248event->set_alt_pressed(p_ss->alt_pressed);249event->set_meta_pressed(p_ss->meta_pressed);250251event->set_pressed(p_pressed);252event->set_keycode(keycode);253event->set_physical_keycode(physical_keycode);254event->set_location(key_location);255256if (unicode != 0) {257event->set_key_label(fix_key_label(unicode, keycode));258} else {259event->set_key_label(keycode);260}261262if (p_pressed) {263event->set_unicode(fix_unicode(unicode));264}265266// Taken from DisplayServerX11.267if (event->get_keycode() == Key::BACKTAB) {268// Make it consistent across platforms.269event->set_keycode(Key::TAB);270event->set_physical_keycode(Key::TAB);271event->set_shift_pressed(true);272}273274return event;275}276277// NOTE: Due to the nature of the way keys are encoded, there's an ambiguity278// regarding "special" keys. In other words: there's no reliable way of279// switching between a special key and a character key if not marking a280// different Godot keycode, even if we're actually using the same XKB raw281// keycode. This means that, during this switch, the old key will get "stuck",282// as it will never receive a release event. This method returns the necessary283// event to fix this if needed.284Ref<InputEventKey> WaylandThread::_seat_state_get_unstuck_key_event(SeatState *p_ss, xkb_keycode_t p_keycode, bool p_pressed, Key p_key) {285Ref<InputEventKey> event;286287if (p_pressed) {288Key *old_key = p_ss->pressed_keycodes.getptr(p_keycode);289if (old_key != nullptr && *old_key != p_key) {290print_verbose(vformat("%s and %s have same keycode. Generating release event for %s", keycode_get_string(*old_key), keycode_get_string(p_key), keycode_get_string(*old_key)));291event = _seat_state_get_key_event(p_ss, p_keycode, false);292if (event.is_valid()) {293event->set_keycode(*old_key);294}295}296p_ss->pressed_keycodes[p_keycode] = p_key;297} else {298p_ss->pressed_keycodes.erase(p_keycode);299}300301return event;302}303304void WaylandThread::_seat_state_handle_xkb_keycode(SeatState *p_ss, xkb_keycode_t p_xkb_keycode, bool p_pressed, bool p_echo) {305ERR_FAIL_NULL(p_ss);306307WaylandThread *wayland_thread = p_ss->wayland_thread;308ERR_FAIL_NULL(wayland_thread);309310Key last_key = Key::NONE;311xkb_compose_status compose_status = xkb_compose_state_get_status(p_ss->xkb_compose_state);312313if (p_pressed) {314xkb_keysym_t keysym = xkb_state_key_get_one_sym(p_ss->xkb_state, p_xkb_keycode);315xkb_compose_feed_result compose_result = xkb_compose_state_feed(p_ss->xkb_compose_state, keysym);316compose_status = xkb_compose_state_get_status(p_ss->xkb_compose_state);317318if (compose_result == XKB_COMPOSE_FEED_ACCEPTED && compose_status == XKB_COMPOSE_COMPOSED) {319// We need to generate multiple key events to report the composed result, One320// per character.321char str_xkb[256] = {};322int str_xkb_size = xkb_compose_state_get_utf8(p_ss->xkb_compose_state, str_xkb, 255);323324String decoded_str = String::utf8(str_xkb, str_xkb_size);325for (int i = 0; i < decoded_str.length(); ++i) {326Ref<InputEventKey> k = _seat_state_get_key_event(p_ss, p_xkb_keycode, p_pressed);327if (k.is_null()) {328continue;329}330331k->set_unicode(decoded_str[i]);332k->set_echo(p_echo);333334Ref<InputEventMessage> msg;335msg.instantiate();336msg->event = k;337wayland_thread->push_message(msg);338339last_key = k->get_keycode();340}341}342}343344if (last_key == Key::NONE && compose_status == XKB_COMPOSE_NOTHING) {345// If we continued with other compose status (e.g. XKB_COMPOSE_COMPOSING) we346// would get the composing keys _and_ the result.347Ref<InputEventKey> k = _seat_state_get_key_event(p_ss, p_xkb_keycode, p_pressed);348if (k.is_valid()) {349k->set_echo(p_echo);350351Ref<InputEventMessage> msg;352msg.instantiate();353msg->event = k;354wayland_thread->push_message(msg);355356last_key = k->get_keycode();357}358}359360if (last_key != Key::NONE) {361Ref<InputEventKey> uk = _seat_state_get_unstuck_key_event(p_ss, p_xkb_keycode, p_pressed, last_key);362if (uk.is_valid()) {363Ref<InputEventMessage> u_msg;364u_msg.instantiate();365u_msg->event = uk;366wayland_thread->push_message(u_msg);367}368}369}370371void WaylandThread::_set_current_seat(struct wl_seat *p_seat) {372if (p_seat == wl_seat_current) {373return;374}375376SeatState *old_state = wl_seat_get_seat_state(wl_seat_current);377378if (old_state) {379seat_state_unlock_pointer(old_state);380}381382SeatState *new_state = wl_seat_get_seat_state(p_seat);383seat_state_unlock_pointer(new_state);384385wl_seat_current = p_seat;386pointer_set_constraint(pointer_constraint);387}388389// Returns whether it loaded the theme or not.390bool WaylandThread::_load_cursor_theme(int p_cursor_size) {391if (wl_cursor_theme) {392wl_cursor_theme_destroy(wl_cursor_theme);393wl_cursor_theme = nullptr;394}395396if (cursor_theme_name.is_empty()) {397cursor_theme_name = "default";398}399400print_verbose(vformat("Loading cursor theme \"%s\" size %d.", cursor_theme_name, p_cursor_size));401402wl_cursor_theme = wl_cursor_theme_load(cursor_theme_name.utf8().get_data(), p_cursor_size, registry.wl_shm);403404ERR_FAIL_NULL_V_MSG(wl_cursor_theme, false, "Can't load any cursor theme.");405406static const char *cursor_names[] = {407"left_ptr",408"xterm",409"hand2",410"cross",411"watch",412"left_ptr_watch",413"fleur",414"dnd-move",415"crossed_circle",416"v_double_arrow",417"h_double_arrow",418"size_bdiag",419"size_fdiag",420"move",421"row_resize",422"col_resize",423"question_arrow"424};425426static const char *cursor_names_fallback[] = {427nullptr,428nullptr,429"pointer",430"cross",431"wait",432"progress",433"grabbing",434"hand1",435"forbidden",436"ns-resize",437"ew-resize",438"fd_double_arrow",439"bd_double_arrow",440"fleur",441"sb_v_double_arrow",442"sb_h_double_arrow",443"help"444};445446for (int i = 0; i < DisplayServer::CURSOR_MAX; i++) {447struct wl_cursor *cursor = wl_cursor_theme_get_cursor(wl_cursor_theme, cursor_names[i]);448449if (!cursor && cursor_names_fallback[i]) {450cursor = wl_cursor_theme_get_cursor(wl_cursor_theme, cursor_names_fallback[i]);451}452453if (cursor && cursor->image_count > 0) {454wl_cursors[i] = cursor;455} else {456wl_cursors[i] = nullptr;457print_verbose("Failed loading cursor: " + String(cursor_names[i]));458}459}460461return true;462}463464void WaylandThread::_update_scale(int p_scale) {465if (p_scale <= cursor_scale) {466return;467}468469print_verbose(vformat("Bumping cursor scale to %d", p_scale));470471// There's some display that's bigger than the cache, let's update it.472cursor_scale = p_scale;473474if (wl_cursor_theme == nullptr) {475// Ugh. Either we're still initializing (this must've been called from the476// first roundtrips) or we had some error while doing so. We'll trust that it477// will be updated for us if needed.478return;479}480481int cursor_size = unscaled_cursor_size * p_scale;482483if (_load_cursor_theme(cursor_size)) {484for (struct wl_seat *wl_seat : registry.wl_seats) {485SeatState *ss = wl_seat_get_seat_state(wl_seat);486ERR_FAIL_NULL(ss);487488seat_state_update_cursor(ss);489}490}491}492493void WaylandThread::_wl_registry_on_global(void *data, struct wl_registry *wl_registry, uint32_t name, const char *interface, uint32_t version) {494RegistryState *registry = (RegistryState *)data;495ERR_FAIL_NULL(registry);496497if (strcmp(interface, wl_shm_interface.name) == 0) {498registry->wl_shm = (struct wl_shm *)wl_registry_bind(wl_registry, name, &wl_shm_interface, 1);499registry->wl_shm_name = name;500return;501}502503// NOTE: Deprecated.504if (strcmp(interface, zxdg_exporter_v1_interface.name) == 0) {505registry->xdg_exporter_v1 = (struct zxdg_exporter_v1 *)wl_registry_bind(wl_registry, name, &zxdg_exporter_v1_interface, 1);506registry->xdg_exporter_v1_name = name;507return;508}509510if (strcmp(interface, zxdg_exporter_v2_interface.name) == 0) {511registry->xdg_exporter_v2 = (struct zxdg_exporter_v2 *)wl_registry_bind(wl_registry, name, &zxdg_exporter_v2_interface, 1);512registry->xdg_exporter_v2_name = name;513return;514}515516if (strcmp(interface, wl_compositor_interface.name) == 0) {517registry->wl_compositor = (struct wl_compositor *)wl_registry_bind(wl_registry, name, &wl_compositor_interface, CLAMP((int)version, 1, 6));518registry->wl_compositor_name = name;519return;520}521522if (strcmp(interface, wl_data_device_manager_interface.name) == 0) {523registry->wl_data_device_manager = (struct wl_data_device_manager *)wl_registry_bind(wl_registry, name, &wl_data_device_manager_interface, CLAMP((int)version, 1, 3));524registry->wl_data_device_manager_name = name;525526// This global creates some seat data. Let's do that for the ones already available.527for (struct wl_seat *wl_seat : registry->wl_seats) {528SeatState *ss = wl_seat_get_seat_state(wl_seat);529ERR_FAIL_NULL(ss);530531if (ss->wl_data_device == nullptr) {532ss->wl_data_device = wl_data_device_manager_get_data_device(registry->wl_data_device_manager, wl_seat);533wl_data_device_add_listener(ss->wl_data_device, &wl_data_device_listener, ss);534}535}536return;537}538539if (strcmp(interface, wl_output_interface.name) == 0) {540struct wl_output *wl_output = (struct wl_output *)wl_registry_bind(wl_registry, name, &wl_output_interface, CLAMP((int)version, 1, 4));541wl_proxy_tag_godot((struct wl_proxy *)wl_output);542543registry->wl_outputs.push_back(wl_output);544545ScreenState *ss = memnew(ScreenState);546ss->wl_output_name = name;547ss->wayland_thread = registry->wayland_thread;548549wl_proxy_tag_godot((struct wl_proxy *)wl_output);550wl_output_add_listener(wl_output, &wl_output_listener, ss);551return;552}553554if (strcmp(interface, wl_seat_interface.name) == 0) {555struct wl_seat *wl_seat = (struct wl_seat *)wl_registry_bind(wl_registry, name, &wl_seat_interface, CLAMP((int)version, 1, 9));556wl_proxy_tag_godot((struct wl_proxy *)wl_seat);557558SeatState *ss = memnew(SeatState);559ss->wl_seat = wl_seat;560ss->wl_seat_name = name;561562ss->registry = registry;563ss->wayland_thread = registry->wayland_thread;564565// Some extra stuff depends on other globals. We'll initialize them if the566// globals are already there, otherwise we'll have to do that once and if they567// get announced.568//569// NOTE: Don't forget to also bind/destroy with the respective global.570if (!ss->wl_data_device && registry->wl_data_device_manager) {571// Clipboard & DnD.572ss->wl_data_device = wl_data_device_manager_get_data_device(registry->wl_data_device_manager, wl_seat);573wl_data_device_add_listener(ss->wl_data_device, &wl_data_device_listener, ss);574}575576if (!ss->wp_primary_selection_device && registry->wp_primary_selection_device_manager) {577// Primary selection.578ss->wp_primary_selection_device = zwp_primary_selection_device_manager_v1_get_device(registry->wp_primary_selection_device_manager, wl_seat);579zwp_primary_selection_device_v1_add_listener(ss->wp_primary_selection_device, &wp_primary_selection_device_listener, ss);580}581582if (!ss->wp_tablet_seat && registry->wp_tablet_manager) {583// Tablet.584ss->wp_tablet_seat = zwp_tablet_manager_v2_get_tablet_seat(registry->wp_tablet_manager, wl_seat);585zwp_tablet_seat_v2_add_listener(ss->wp_tablet_seat, &wp_tablet_seat_listener, ss);586}587588if (!ss->wp_text_input && registry->wp_text_input_manager) {589// IME.590ss->wp_text_input = zwp_text_input_manager_v3_get_text_input(registry->wp_text_input_manager, wl_seat);591zwp_text_input_v3_add_listener(ss->wp_text_input, &wp_text_input_listener, ss);592}593594registry->wl_seats.push_back(wl_seat);595596wl_seat_add_listener(wl_seat, &wl_seat_listener, ss);597598if (registry->wayland_thread->wl_seat_current == nullptr) {599registry->wayland_thread->_set_current_seat(wl_seat);600}601602return;603}604605if (strcmp(interface, xdg_wm_base_interface.name) == 0) {606registry->xdg_wm_base = (struct xdg_wm_base *)wl_registry_bind(wl_registry, name, &xdg_wm_base_interface, CLAMP((int)version, 1, 6));607registry->xdg_wm_base_name = name;608609xdg_wm_base_add_listener(registry->xdg_wm_base, &xdg_wm_base_listener, nullptr);610return;611}612613if (strcmp(interface, wp_viewporter_interface.name) == 0) {614registry->wp_viewporter = (struct wp_viewporter *)wl_registry_bind(wl_registry, name, &wp_viewporter_interface, 1);615registry->wp_viewporter_name = name;616}617618if (strcmp(interface, wp_cursor_shape_manager_v1_interface.name) == 0) {619registry->wp_cursor_shape_manager = (struct wp_cursor_shape_manager_v1 *)wl_registry_bind(wl_registry, name, &wp_cursor_shape_manager_v1_interface, 1);620registry->wp_cursor_shape_manager_name = name;621return;622}623624if (strcmp(interface, wp_fractional_scale_manager_v1_interface.name) == 0) {625registry->wp_fractional_scale_manager = (struct wp_fractional_scale_manager_v1 *)wl_registry_bind(wl_registry, name, &wp_fractional_scale_manager_v1_interface, 1);626registry->wp_fractional_scale_manager_name = name;627628// NOTE: We're not mapping the fractional scale object here because this is629// supposed to be a "startup global". If for some reason this isn't true (who630// knows), add a conditional branch for creating the add-on object.631}632633if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {634registry->xdg_decoration_manager = (struct zxdg_decoration_manager_v1 *)wl_registry_bind(wl_registry, name, &zxdg_decoration_manager_v1_interface, 1);635registry->xdg_decoration_manager_name = name;636return;637}638639if (strcmp(interface, xdg_system_bell_v1_interface.name) == 0) {640registry->xdg_system_bell = (struct xdg_system_bell_v1 *)wl_registry_bind(wl_registry, name, &xdg_system_bell_v1_interface, 1);641registry->xdg_system_bell_name = name;642return;643}644645if (strcmp(interface, xdg_toplevel_icon_manager_v1_interface.name) == 0) {646registry->xdg_toplevel_icon_manager = (struct xdg_toplevel_icon_manager_v1 *)wl_registry_bind(wl_registry, name, &xdg_toplevel_icon_manager_v1_interface, 1);647registry->xdg_toplevel_icon_manager_name = name;648return;649}650651if (strcmp(interface, xdg_activation_v1_interface.name) == 0) {652registry->xdg_activation = (struct xdg_activation_v1 *)wl_registry_bind(wl_registry, name, &xdg_activation_v1_interface, 1);653registry->xdg_activation_name = name;654return;655}656657if (strcmp(interface, zwp_primary_selection_device_manager_v1_interface.name) == 0) {658registry->wp_primary_selection_device_manager = (struct zwp_primary_selection_device_manager_v1 *)wl_registry_bind(wl_registry, name, &zwp_primary_selection_device_manager_v1_interface, 1);659660// This global creates some seat data. Let's do that for the ones already available.661for (struct wl_seat *wl_seat : registry->wl_seats) {662SeatState *ss = wl_seat_get_seat_state(wl_seat);663ERR_FAIL_NULL(ss);664665if (!ss->wp_primary_selection_device && registry->wp_primary_selection_device_manager) {666ss->wp_primary_selection_device = zwp_primary_selection_device_manager_v1_get_device(registry->wp_primary_selection_device_manager, wl_seat);667zwp_primary_selection_device_v1_add_listener(ss->wp_primary_selection_device, &wp_primary_selection_device_listener, ss);668}669}670}671672if (strcmp(interface, zwp_relative_pointer_manager_v1_interface.name) == 0) {673registry->wp_relative_pointer_manager = (struct zwp_relative_pointer_manager_v1 *)wl_registry_bind(wl_registry, name, &zwp_relative_pointer_manager_v1_interface, 1);674registry->wp_relative_pointer_manager_name = name;675return;676}677678if (strcmp(interface, zwp_pointer_constraints_v1_interface.name) == 0) {679registry->wp_pointer_constraints = (struct zwp_pointer_constraints_v1 *)wl_registry_bind(wl_registry, name, &zwp_pointer_constraints_v1_interface, 1);680registry->wp_pointer_constraints_name = name;681return;682}683684if (strcmp(interface, zwp_pointer_gestures_v1_interface.name) == 0) {685registry->wp_pointer_gestures = (struct zwp_pointer_gestures_v1 *)wl_registry_bind(wl_registry, name, &zwp_pointer_gestures_v1_interface, 1);686registry->wp_pointer_gestures_name = name;687return;688}689690if (strcmp(interface, zwp_idle_inhibit_manager_v1_interface.name) == 0) {691registry->wp_idle_inhibit_manager = (struct zwp_idle_inhibit_manager_v1 *)wl_registry_bind(wl_registry, name, &zwp_idle_inhibit_manager_v1_interface, 1);692registry->wp_idle_inhibit_manager_name = name;693return;694}695696if (strcmp(interface, zwp_tablet_manager_v2_interface.name) == 0) {697registry->wp_tablet_manager = (struct zwp_tablet_manager_v2 *)wl_registry_bind(wl_registry, name, &zwp_tablet_manager_v2_interface, 1);698registry->wp_tablet_manager_name = name;699700// This global creates some seat data. Let's do that for the ones already available.701for (struct wl_seat *wl_seat : registry->wl_seats) {702SeatState *ss = wl_seat_get_seat_state(wl_seat);703ERR_FAIL_NULL(ss);704705ss->wp_tablet_seat = zwp_tablet_manager_v2_get_tablet_seat(registry->wp_tablet_manager, wl_seat);706zwp_tablet_seat_v2_add_listener(ss->wp_tablet_seat, &wp_tablet_seat_listener, ss);707}708709return;710}711712if (strcmp(interface, zwp_text_input_manager_v3_interface.name) == 0) {713registry->wp_text_input_manager = (struct zwp_text_input_manager_v3 *)wl_registry_bind(wl_registry, name, &zwp_text_input_manager_v3_interface, 1);714registry->wp_text_input_manager_name = name;715716// This global creates some seat data. Let's do that for the ones already available.717for (struct wl_seat *wl_seat : registry->wl_seats) {718SeatState *ss = wl_seat_get_seat_state(wl_seat);719ERR_FAIL_NULL(ss);720721ss->wp_text_input = zwp_text_input_manager_v3_get_text_input(registry->wp_text_input_manager, wl_seat);722zwp_text_input_v3_add_listener(ss->wp_text_input, &wp_text_input_listener, ss);723}724725return;726}727728if (strcmp(interface, wp_pointer_warp_v1_interface.name) == 0) {729registry->wp_pointer_warp = (struct wp_pointer_warp_v1 *)wl_registry_bind(wl_registry, name, &wp_pointer_warp_v1_interface, 1);730registry->wp_pointer_warp_name = name;731return;732}733734if (strcmp(interface, FIFO_INTERFACE_NAME) == 0) {735registry->wp_fifo_manager_name = name;736}737738if (strcmp(interface, godot_embedding_compositor_interface.name) == 0) {739registry->godot_embedding_compositor = (struct godot_embedding_compositor *)wl_registry_bind(wl_registry, name, &godot_embedding_compositor_interface, 1);740registry->godot_embedding_compositor_name = name;741742godot_embedding_compositor_add_listener(registry->godot_embedding_compositor, &godot_embedding_compositor_listener, memnew(EmbeddingCompositorState));743}744}745746void WaylandThread::_wl_registry_on_global_remove(void *data, struct wl_registry *wl_registry, uint32_t name) {747RegistryState *registry = (RegistryState *)data;748ERR_FAIL_NULL(registry);749750if (name == registry->wl_shm_name) {751if (registry->wl_shm) {752wl_shm_destroy(registry->wl_shm);753registry->wl_shm = nullptr;754}755756registry->wl_shm_name = 0;757758return;759}760761// NOTE: Deprecated.762if (name == registry->xdg_exporter_v1_name) {763if (registry->xdg_exporter_v1) {764zxdg_exporter_v1_destroy(registry->xdg_exporter_v1);765registry->xdg_exporter_v1 = nullptr;766}767768registry->xdg_exporter_v1_name = 0;769770return;771}772773if (name == registry->xdg_exporter_v2_name) {774if (registry->xdg_exporter_v2) {775zxdg_exporter_v2_destroy(registry->xdg_exporter_v2);776registry->xdg_exporter_v2 = nullptr;777}778779registry->xdg_exporter_v2_name = 0;780781return;782}783784if (name == registry->wl_compositor_name) {785if (registry->wl_compositor) {786wl_compositor_destroy(registry->wl_compositor);787registry->wl_compositor = nullptr;788}789790registry->wl_compositor_name = 0;791792return;793}794795if (name == registry->wl_data_device_manager_name) {796if (registry->wl_data_device_manager) {797wl_data_device_manager_destroy(registry->wl_data_device_manager);798registry->wl_data_device_manager = nullptr;799}800801registry->wl_data_device_manager_name = 0;802803// This global is used to create some seat data. Let's clean it.804for (struct wl_seat *wl_seat : registry->wl_seats) {805SeatState *ss = wl_seat_get_seat_state(wl_seat);806ERR_FAIL_NULL(ss);807808if (ss->wl_data_device) {809wl_data_device_destroy(ss->wl_data_device);810ss->wl_data_device = nullptr;811}812813ss->wl_data_device = nullptr;814}815816return;817}818819if (name == registry->xdg_wm_base_name) {820if (registry->xdg_wm_base) {821xdg_wm_base_destroy(registry->xdg_wm_base);822registry->xdg_wm_base = nullptr;823}824825registry->xdg_wm_base_name = 0;826827return;828}829830if (name == registry->wp_viewporter_name) {831for (KeyValue<DisplayServer::WindowID, WindowState> &pair : registry->wayland_thread->windows) {832WindowState &ws = pair.value;833if (registry->wp_viewporter) {834wp_viewporter_destroy(registry->wp_viewporter);835registry->wp_viewporter = nullptr;836}837838if (ws.wp_viewport) {839wp_viewport_destroy(ws.wp_viewport);840ws.wp_viewport = nullptr;841}842}843844registry->wp_viewporter_name = 0;845846return;847}848849if (name == registry->wp_cursor_shape_manager_name) {850if (registry->wp_cursor_shape_manager) {851wp_cursor_shape_manager_v1_destroy(registry->wp_cursor_shape_manager);852registry->wp_cursor_shape_manager = nullptr;853}854855registry->wp_cursor_shape_manager_name = 0;856857for (struct wl_seat *wl_seat : registry->wl_seats) {858SeatState *ss = wl_seat_get_seat_state(wl_seat);859ERR_FAIL_NULL(ss);860861if (ss->wp_cursor_shape_device) {862wp_cursor_shape_device_v1_destroy(ss->wp_cursor_shape_device);863ss->wp_cursor_shape_device = nullptr;864}865}866}867868if (name == registry->wp_fractional_scale_manager_name) {869for (KeyValue<DisplayServer::WindowID, WindowState> &pair : registry->wayland_thread->windows) {870WindowState &ws = pair.value;871872if (registry->wp_fractional_scale_manager) {873wp_fractional_scale_manager_v1_destroy(registry->wp_fractional_scale_manager);874registry->wp_fractional_scale_manager = nullptr;875}876877if (ws.wp_fractional_scale) {878wp_fractional_scale_v1_destroy(ws.wp_fractional_scale);879ws.wp_fractional_scale = nullptr;880}881}882883registry->wp_fractional_scale_manager_name = 0;884}885886if (name == registry->xdg_decoration_manager_name) {887if (registry->xdg_decoration_manager) {888zxdg_decoration_manager_v1_destroy(registry->xdg_decoration_manager);889registry->xdg_decoration_manager = nullptr;890}891892registry->xdg_decoration_manager_name = 0;893894return;895}896897if (name == registry->xdg_system_bell_name) {898if (registry->xdg_system_bell) {899xdg_system_bell_v1_destroy(registry->xdg_system_bell);900registry->xdg_system_bell = nullptr;901}902903registry->xdg_system_bell_name = 0;904905return;906}907908if (name == registry->xdg_toplevel_icon_manager_name) {909if (registry->xdg_toplevel_icon_manager) {910xdg_toplevel_icon_manager_v1_destroy(registry->xdg_toplevel_icon_manager);911registry->xdg_toplevel_icon_manager = nullptr;912}913914if (registry->wayland_thread->xdg_icon) {915xdg_toplevel_icon_v1_destroy(registry->wayland_thread->xdg_icon);916}917918if (registry->wayland_thread->icon_buffer) {919wl_buffer_destroy(registry->wayland_thread->icon_buffer);920}921922registry->xdg_toplevel_icon_manager_name = 0;923924return;925}926927if (name == registry->xdg_activation_name) {928if (registry->xdg_activation) {929xdg_activation_v1_destroy(registry->xdg_activation);930registry->xdg_activation = nullptr;931}932933registry->xdg_activation_name = 0;934935return;936}937938if (name == registry->wp_primary_selection_device_manager_name) {939if (registry->wp_primary_selection_device_manager) {940zwp_primary_selection_device_manager_v1_destroy(registry->wp_primary_selection_device_manager);941registry->wp_primary_selection_device_manager = nullptr;942}943944registry->wp_primary_selection_device_manager_name = 0;945946// This global is used to create some seat data. Let's clean it.947for (struct wl_seat *wl_seat : registry->wl_seats) {948SeatState *ss = wl_seat_get_seat_state(wl_seat);949ERR_FAIL_NULL(ss);950951if (ss->wp_primary_selection_device) {952zwp_primary_selection_device_v1_destroy(ss->wp_primary_selection_device);953ss->wp_primary_selection_device = nullptr;954}955956if (ss->wp_primary_selection_source) {957zwp_primary_selection_source_v1_destroy(ss->wp_primary_selection_source);958ss->wp_primary_selection_source = nullptr;959}960961if (ss->wp_primary_selection_offer) {962memfree(wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer));963zwp_primary_selection_offer_v1_destroy(ss->wp_primary_selection_offer);964ss->wp_primary_selection_offer = nullptr;965}966}967968return;969}970971if (name == registry->wp_relative_pointer_manager_name) {972if (registry->wp_relative_pointer_manager) {973zwp_relative_pointer_manager_v1_destroy(registry->wp_relative_pointer_manager);974registry->wp_relative_pointer_manager = nullptr;975}976977registry->wp_relative_pointer_manager_name = 0;978979// This global is used to create some seat data. Let's clean it.980for (struct wl_seat *wl_seat : registry->wl_seats) {981SeatState *ss = wl_seat_get_seat_state(wl_seat);982ERR_FAIL_NULL(ss);983984if (ss->wp_relative_pointer) {985zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);986ss->wp_relative_pointer = nullptr;987}988}989990return;991}992993if (name == registry->wp_pointer_constraints_name) {994if (registry->wp_pointer_constraints) {995zwp_pointer_constraints_v1_destroy(registry->wp_pointer_constraints);996registry->wp_pointer_constraints = nullptr;997}998999registry->wp_pointer_constraints_name = 0;10001001// This global is used to create some seat data. Let's clean it.1002for (struct wl_seat *wl_seat : registry->wl_seats) {1003SeatState *ss = wl_seat_get_seat_state(wl_seat);1004ERR_FAIL_NULL(ss);10051006if (ss->wp_relative_pointer) {1007zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);1008ss->wp_relative_pointer = nullptr;1009}10101011if (ss->wp_locked_pointer) {1012zwp_locked_pointer_v1_destroy(ss->wp_locked_pointer);1013ss->wp_locked_pointer = nullptr;1014}10151016if (ss->wp_confined_pointer) {1017zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);1018ss->wp_confined_pointer = nullptr;1019}1020}10211022return;1023}10241025if (name == registry->wp_pointer_gestures_name) {1026if (registry->wp_pointer_gestures) {1027zwp_pointer_gestures_v1_destroy(registry->wp_pointer_gestures);1028}10291030registry->wp_pointer_gestures = nullptr;1031registry->wp_pointer_gestures_name = 0;10321033// This global is used to create some seat data. Let's clean it.1034for (struct wl_seat *wl_seat : registry->wl_seats) {1035SeatState *ss = wl_seat_get_seat_state(wl_seat);1036ERR_FAIL_NULL(ss);10371038if (ss->wp_pointer_gesture_pinch) {1039zwp_pointer_gesture_pinch_v1_destroy(ss->wp_pointer_gesture_pinch);1040ss->wp_pointer_gesture_pinch = nullptr;1041}1042}10431044return;1045}10461047if (name == registry->wp_idle_inhibit_manager_name) {1048if (registry->wp_idle_inhibit_manager) {1049zwp_idle_inhibit_manager_v1_destroy(registry->wp_idle_inhibit_manager);1050registry->wp_idle_inhibit_manager = nullptr;1051}10521053registry->wp_idle_inhibit_manager_name = 0;10541055return;1056}10571058if (name == registry->wp_tablet_manager_name) {1059if (registry->wp_tablet_manager) {1060zwp_tablet_manager_v2_destroy(registry->wp_tablet_manager);1061registry->wp_tablet_manager = nullptr;1062}10631064registry->wp_tablet_manager_name = 0;10651066// This global is used to create some seat data. Let's clean it.1067for (struct wl_seat *wl_seat : registry->wl_seats) {1068SeatState *ss = wl_seat_get_seat_state(wl_seat);1069ERR_FAIL_NULL(ss);10701071for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {1072TabletToolState *state = wp_tablet_tool_get_state(tool);1073if (state) {1074memdelete(state);1075}10761077zwp_tablet_tool_v2_destroy(tool);1078}10791080ss->tablet_tools.clear();1081}10821083return;1084}10851086if (name == registry->wp_text_input_manager_name) {1087if (registry->wp_text_input_manager) {1088zwp_text_input_manager_v3_destroy(registry->wp_text_input_manager);1089registry->wp_text_input_manager = nullptr;1090}10911092registry->wp_text_input_manager_name = 0;10931094for (struct wl_seat *wl_seat : registry->wl_seats) {1095SeatState *ss = wl_seat_get_seat_state(wl_seat);1096ERR_FAIL_NULL(ss);10971098zwp_text_input_v3_destroy(ss->wp_text_input);1099ss->wp_text_input = nullptr;1100}11011102return;1103}11041105if (name == registry->wp_pointer_warp_name) {1106if (registry->wp_pointer_warp) {1107wp_pointer_warp_v1_destroy(registry->wp_pointer_warp);1108registry->wp_pointer_warp = nullptr;1109}11101111registry->wp_pointer_warp_name = 0;11121113return;1114}11151116{1117// Iterate through all of the seats to find if any got removed.1118List<struct wl_seat *>::Element *E = registry->wl_seats.front();1119while (E) {1120struct wl_seat *wl_seat = E->get();1121List<struct wl_seat *>::Element *N = E->next();11221123SeatState *ss = wl_seat_get_seat_state(wl_seat);1124ERR_FAIL_NULL(ss);11251126if (ss->wl_seat_name == name) {1127if (wl_seat) {1128wl_seat_destroy(wl_seat);1129}11301131if (ss->wl_data_device) {1132wl_data_device_destroy(ss->wl_data_device);1133}11341135if (ss->wp_tablet_seat) {1136zwp_tablet_seat_v2_destroy(ss->wp_tablet_seat);11371138for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {1139TabletToolState *state = wp_tablet_tool_get_state(tool);1140if (state) {1141memdelete(state);1142}11431144zwp_tablet_tool_v2_destroy(tool);1145}1146}11471148memdelete(ss);11491150registry->wl_seats.erase(E);1151return;1152}11531154E = N;1155}1156}11571158{1159// Iterate through all of the outputs to find if any got removed.1160// FIXME: This is a very bruteforce approach.1161List<struct wl_output *>::Element *it = registry->wl_outputs.front();1162while (it) {1163// Iterate through all of the screens to find if any got removed.1164struct wl_output *wl_output = it->get();1165ERR_FAIL_NULL(wl_output);11661167ScreenState *ss = wl_output_get_screen_state(wl_output);11681169if (ss->wl_output_name == name) {1170registry->wl_outputs.erase(it);11711172memdelete(ss);1173wl_output_destroy(wl_output);11741175return;1176}11771178it = it->next();1179}1180}11811182if (name == registry->wp_fifo_manager_name) {1183registry->wp_fifo_manager_name = 0;1184}11851186if (name == registry->godot_embedding_compositor_name) {1187registry->godot_embedding_compositor_name = 0;11881189EmbeddingCompositorState *es = godot_embedding_compositor_get_state(registry->godot_embedding_compositor);1190ERR_FAIL_NULL(es);11911192es->mapped_clients.clear();11931194for (struct godot_embedded_client *client : es->clients) {1195godot_embedded_client_destroy(client);1196}1197es->clients.clear();11981199memdelete(es);12001201godot_embedding_compositor_destroy(registry->godot_embedding_compositor);1202registry->godot_embedding_compositor = nullptr;1203}1204}12051206void WaylandThread::_wl_surface_on_enter(void *data, struct wl_surface *wl_surface, struct wl_output *wl_output) {1207if (!wl_output || !wl_proxy_is_godot((struct wl_proxy *)wl_output)) {1208// This won't have the right data bound to it. Not worth it and would probably1209// just break everything.1210return;1211}12121213WindowState *ws = (WindowState *)data;1214ERR_FAIL_NULL(ws);12151216DEBUG_LOG_WAYLAND_THREAD(vformat("Window entered output %x.", (size_t)wl_output));12171218ws->wl_outputs.insert(wl_output);12191220// Workaround for buffer scaling as there's no guaranteed way of knowing the1221// preferred scale.1222// TODO: Skip this branch for newer `wl_surface`s once we add support for1223// `wl_surface::preferred_buffer_scale`1224if (ws->preferred_fractional_scale == 0) {1225window_state_update_size(ws, ws->rect.size.width, ws->rect.size.height);1226}1227}12281229void WaylandThread::_frame_wl_callback_on_done(void *data, struct wl_callback *wl_callback, uint32_t callback_data) {1230wl_callback_destroy(wl_callback);12311232WindowState *ws = (WindowState *)data;1233ERR_FAIL_NULL(ws);1234ERR_FAIL_NULL(ws->wayland_thread);1235ERR_FAIL_NULL(ws->wl_surface);12361237ws->last_frame_time = OS::get_singleton()->get_ticks_usec();1238ws->wayland_thread->set_frame();12391240ws->frame_callback = wl_surface_frame(ws->wl_surface);1241wl_callback_add_listener(ws->frame_callback, &frame_wl_callback_listener, ws);12421243if (ws->wl_surface && ws->buffer_scale_changed) {1244// NOTE: We're only now setting the buffer scale as the idea is to get this1245// data committed together with the new frame, all by the rendering driver.1246// This is important because we might otherwise set an invalid combination of1247// buffer size and scale (e.g. odd size and 2x scale). We're pretty much1248// guaranteed to get a proper buffer in the next render loop as the rescaling1249// method also informs the engine of a "window rect change", triggering1250// rendering if needed.1251wl_surface_set_buffer_scale(ws->wl_surface, window_state_get_preferred_buffer_scale(ws));1252}1253}12541255void WaylandThread::_wl_surface_on_leave(void *data, struct wl_surface *wl_surface, struct wl_output *wl_output) {1256if (!wl_output || !wl_proxy_is_godot((struct wl_proxy *)wl_output)) {1257// This won't have the right data bound to it. Not worth it and would probably1258// just break everything.1259return;1260}12611262WindowState *ws = (WindowState *)data;1263ERR_FAIL_NULL(ws);12641265ws->wl_outputs.erase(wl_output);12661267DEBUG_LOG_WAYLAND_THREAD(vformat("Window left output %x.\n", (size_t)wl_output));1268}12691270// TODO: Add support to this event.1271void WaylandThread::_wl_surface_on_preferred_buffer_scale(void *data, struct wl_surface *wl_surface, int32_t factor) {1272}12731274// TODO: Add support to this event.1275void WaylandThread::_wl_surface_on_preferred_buffer_transform(void *data, struct wl_surface *wl_surface, uint32_t transform) {1276}12771278void WaylandThread::_wl_output_on_geometry(void *data, struct wl_output *wl_output, int32_t x, int32_t y, int32_t physical_width, int32_t physical_height, int32_t subpixel, const char *make, const char *model, int32_t transform) {1279ScreenState *ss = (ScreenState *)data;1280ERR_FAIL_NULL(ss);12811282ss->pending_data.position.x = x;12831284ss->pending_data.position.x = x;1285ss->pending_data.position.y = y;12861287ss->pending_data.physical_size.width = physical_width;1288ss->pending_data.physical_size.height = physical_height;12891290ss->pending_data.make.clear();1291ss->pending_data.make.append_utf8(make);1292ss->pending_data.model.clear();1293ss->pending_data.model.append_utf8(model);12941295// `wl_output::done` is a version 2 addition. We'll directly update the data1296// for compatibility.1297if (wl_output_get_version(wl_output) == 1) {1298ss->data = ss->pending_data;1299}1300}13011302void WaylandThread::_wl_output_on_mode(void *data, struct wl_output *wl_output, uint32_t flags, int32_t width, int32_t height, int32_t refresh) {1303ScreenState *ss = (ScreenState *)data;1304ERR_FAIL_NULL(ss);13051306if (!(flags & WL_OUTPUT_MODE_CURRENT)) {1307return;1308}13091310ss->pending_data.size.width = width;1311ss->pending_data.size.height = height;13121313ss->pending_data.refresh_rate = refresh ? refresh / 1000.0f : -1;13141315// `wl_output::done` is a version 2 addition. We'll directly update the data1316// for compatibility.1317if (wl_output_get_version(wl_output) == 1) {1318ss->data = ss->pending_data;1319}1320}13211322// NOTE: The following `wl_output` events are only for version 2 onwards, so we1323// can assume that they're "atomic" (i.e. rely on the `wl_output::done` event).13241325void WaylandThread::_wl_output_on_done(void *data, struct wl_output *wl_output) {1326ScreenState *ss = (ScreenState *)data;1327ERR_FAIL_NULL(ss);13281329ss->data = ss->pending_data;13301331ss->wayland_thread->_update_scale(ss->data.scale);13321333DEBUG_LOG_WAYLAND_THREAD(vformat("Output %x done.", (size_t)wl_output));1334}13351336void WaylandThread::_wl_output_on_scale(void *data, struct wl_output *wl_output, int32_t factor) {1337ScreenState *ss = (ScreenState *)data;1338ERR_FAIL_NULL(ss);13391340ss->pending_data.scale = factor;13411342DEBUG_LOG_WAYLAND_THREAD(vformat("Output %x scale %d", (size_t)wl_output, factor));1343}13441345void WaylandThread::_wl_output_on_name(void *data, struct wl_output *wl_output, const char *name) {1346}13471348void WaylandThread::_wl_output_on_description(void *data, struct wl_output *wl_output, const char *description) {1349}13501351void WaylandThread::_xdg_wm_base_on_ping(void *data, struct xdg_wm_base *xdg_wm_base, uint32_t serial) {1352xdg_wm_base_pong(xdg_wm_base, serial);1353}13541355void WaylandThread::_xdg_surface_on_configure(void *data, struct xdg_surface *xdg_surface, uint32_t serial) {1356xdg_surface_ack_configure(xdg_surface, serial);13571358WindowState *ws = (WindowState *)data;1359ERR_FAIL_NULL(ws);13601361DEBUG_LOG_WAYLAND_THREAD(vformat("xdg surface on configure rect %s", ws->rect));1362}13631364void WaylandThread::_xdg_toplevel_on_configure(void *data, struct xdg_toplevel *xdg_toplevel, int32_t width, int32_t height, struct wl_array *states) {1365WindowState *ws = (WindowState *)data;1366ERR_FAIL_NULL(ws);13671368// Expect the window to be in a plain state. It will get properly set if the1369// compositor reports otherwise below.1370ws->mode = DisplayServer::WINDOW_MODE_WINDOWED;1371ws->maximized = false;1372ws->fullscreen = false;1373ws->resizing = false;1374ws->tiled_left = false;1375ws->tiled_right = false;1376ws->tiled_top = false;1377ws->tiled_bottom = false;1378ws->suspended = false;13791380uint32_t *state = nullptr;1381wl_array_for_each(state, states) {1382switch (*state) {1383case XDG_TOPLEVEL_STATE_MAXIMIZED: {1384ws->mode = DisplayServer::WINDOW_MODE_MAXIMIZED;1385ws->maximized = true;1386} break;13871388case XDG_TOPLEVEL_STATE_FULLSCREEN: {1389ws->mode = DisplayServer::WINDOW_MODE_FULLSCREEN;1390ws->fullscreen = true;1391} break;13921393case XDG_TOPLEVEL_STATE_RESIZING: {1394ws->resizing = true;1395} break;13961397case XDG_TOPLEVEL_STATE_TILED_LEFT: {1398ws->tiled_left = true;1399} break;14001401case XDG_TOPLEVEL_STATE_TILED_RIGHT: {1402ws->tiled_right = true;1403} break;14041405case XDG_TOPLEVEL_STATE_TILED_TOP: {1406ws->tiled_top = true;1407} break;14081409case XDG_TOPLEVEL_STATE_TILED_BOTTOM: {1410ws->tiled_bottom = true;1411} break;14121413case XDG_TOPLEVEL_STATE_SUSPENDED: {1414ws->suspended = true;1415} break;14161417default: {1418// We don't care about the other states (for now).1419} break;1420}1421}14221423if (width != 0 && height != 0) {1424window_state_update_size(ws, width, height);1425}14261427DEBUG_LOG_WAYLAND_THREAD(vformat("XDG toplevel on configure width %d height %d.", width, height));1428}14291430void WaylandThread::_xdg_toplevel_on_close(void *data, struct xdg_toplevel *xdg_toplevel) {1431WindowState *ws = (WindowState *)data;1432ERR_FAIL_NULL(ws);14331434Ref<WindowEventMessage> msg;1435msg.instantiate();1436msg->id = ws->id;1437msg->event = DisplayServer::WINDOW_EVENT_CLOSE_REQUEST;1438ws->wayland_thread->push_message(msg);1439}14401441void WaylandThread::_xdg_toplevel_on_configure_bounds(void *data, struct xdg_toplevel *xdg_toplevel, int32_t width, int32_t height) {1442}14431444void WaylandThread::_xdg_toplevel_on_wm_capabilities(void *data, struct xdg_toplevel *xdg_toplevel, struct wl_array *capabilities) {1445WindowState *ws = (WindowState *)data;1446ERR_FAIL_NULL(ws);14471448ws->can_maximize = false;1449ws->can_fullscreen = false;1450ws->can_minimize = false;14511452uint32_t *capability = nullptr;1453wl_array_for_each(capability, capabilities) {1454switch (*capability) {1455case XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE: {1456ws->can_maximize = true;1457} break;1458case XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN: {1459ws->can_fullscreen = true;1460} break;14611462case XDG_TOPLEVEL_WM_CAPABILITIES_MINIMIZE: {1463ws->can_minimize = true;1464} break;14651466default: {1467} break;1468}1469}1470}14711472void WaylandThread::_xdg_popup_on_configure(void *data, struct xdg_popup *xdg_popup, int32_t x, int32_t y, int32_t width, int32_t height) {1473WindowState *ws = (WindowState *)data;1474ERR_FAIL_NULL(ws);14751476if (width != 0 && height != 0) {1477window_state_update_size(ws, width, height);1478}14791480WindowState *parent = ws->wayland_thread->window_get_state(ws->parent_id);1481ERR_FAIL_NULL(parent);14821483Point2i pos = Point2i(x, y);1484#ifdef LIBDECOR_ENABLED1485if (parent->libdecor_frame) {1486int translated_x = x;1487int translated_y = y;1488libdecor_frame_translate_coordinate(parent->libdecor_frame, x, y, &translated_x, &translated_y);14891490pos.x = translated_x;1491pos.y = translated_y;1492}1493#endif14941495// Looks like the position returned here is relative to the parent. We have to1496// accumulate it or there's gonna be a lot of confusion godot-side.1497pos += parent->rect.position;14981499if (ws->rect.position != pos) {1500DEBUG_LOG_WAYLAND_THREAD(vformat("Repositioning popup %d from %s to %s", ws->id, ws->rect.position, pos));15011502double parent_scale = window_state_get_scale_factor(parent);15031504ws->rect.position = pos;15051506Ref<WindowRectMessage> rect_msg;1507rect_msg.instantiate();1508rect_msg->id = ws->id;1509rect_msg->rect.position = scale_vector2i(ws->rect.position, parent_scale);1510rect_msg->rect.size = scale_vector2i(ws->rect.size, parent_scale);15111512ws->wayland_thread->push_message(rect_msg);1513}15141515DEBUG_LOG_WAYLAND_THREAD(vformat("xdg popup on configure x%d y%d w%d h%d", x, y, width, height));1516}15171518void WaylandThread::_xdg_popup_on_popup_done(void *data, struct xdg_popup *xdg_popup) {1519WindowState *ws = (WindowState *)data;1520ERR_FAIL_NULL(ws);15211522Ref<WindowEventMessage> ev_msg;1523ev_msg.instantiate();1524ev_msg->id = ws->id;1525ev_msg->event = DisplayServer::WINDOW_EVENT_FORCE_CLOSE;15261527ws->wayland_thread->push_message(ev_msg);1528}15291530void WaylandThread::_xdg_popup_on_repositioned(void *data, struct xdg_popup *xdg_popup, uint32_t token) {1531DEBUG_LOG_WAYLAND_THREAD(vformat("stub xdg popup repositioned %x", token));1532}15331534// NOTE: Deprecated.1535void WaylandThread::_xdg_exported_v1_on_handle(void *data, zxdg_exported_v1 *exported, const char *handle) {1536WindowState *ws = (WindowState *)data;1537ERR_FAIL_NULL(ws);15381539ws->exported_handle = vformat("wayland:%s", String::utf8(handle));1540}15411542void WaylandThread::_xdg_exported_v2_on_handle(void *data, zxdg_exported_v2 *exported, const char *handle) {1543WindowState *ws = (WindowState *)data;1544ERR_FAIL_NULL(ws);15451546ws->exported_handle = vformat("wayland:%s", String::utf8(handle));1547}15481549void WaylandThread::_xdg_toplevel_decoration_on_configure(void *data, struct zxdg_toplevel_decoration_v1 *xdg_toplevel_decoration, uint32_t mode) {1550if (mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE) {1551#ifdef LIBDECOR_ENABLED1552WARN_PRINT_ONCE("Native client side decorations are not yet supported without libdecor!");1553#else1554WARN_PRINT_ONCE("Native client side decorations are not yet supported!");1555#endif // LIBDECOR_ENABLED1556}1557}15581559#ifdef LIBDECOR_ENABLED1560void WaylandThread::libdecor_on_error(struct libdecor *context, enum libdecor_error error, const char *message) {1561ERR_PRINT(vformat("libdecor error %d: %s", error, message));1562}15631564// NOTE: This is pretty much a reimplementation of _xdg_surface_on_configure1565// and _xdg_toplevel_on_configure. Libdecor really likes wrapping everything,1566// forcing us to do stuff like this.1567void WaylandThread::libdecor_frame_on_configure(struct libdecor_frame *frame, struct libdecor_configuration *configuration, void *user_data) {1568WindowState *ws = (WindowState *)user_data;1569ERR_FAIL_NULL(ws);15701571int width = 0;1572int height = 0;15731574ws->pending_libdecor_configuration = configuration;15751576if (!libdecor_configuration_get_content_size(configuration, frame, &width, &height)) {1577// The configuration doesn't have a size. We'll use the one already set in the window.1578width = ws->rect.size.width;1579height = ws->rect.size.height;1580}15811582ERR_FAIL_COND_MSG(width == 0 || height == 0, "Window has invalid size.");15831584libdecor_window_state window_state = LIBDECOR_WINDOW_STATE_NONE;15851586// Expect the window to be in a plain state. It will get properly set if the1587// compositor reports otherwise below.1588ws->mode = DisplayServer::WINDOW_MODE_WINDOWED;1589ws->maximized = false;1590ws->fullscreen = false;1591ws->resizing = false;1592ws->tiled_left = false;1593ws->tiled_right = false;1594ws->tiled_top = false;1595ws->tiled_bottom = false;1596ws->suspended = false;15971598if (libdecor_configuration_get_window_state(configuration, &window_state)) {1599if (window_state & LIBDECOR_WINDOW_STATE_MAXIMIZED) {1600ws->mode = DisplayServer::WINDOW_MODE_MAXIMIZED;1601ws->maximized = true;1602}16031604if (window_state & LIBDECOR_WINDOW_STATE_FULLSCREEN) {1605ws->mode = DisplayServer::WINDOW_MODE_FULLSCREEN;1606ws->fullscreen = true;1607}16081609// libdecor doesn't have the resizing state for whatever reason.16101611if (window_state & LIBDECOR_WINDOW_STATE_TILED_LEFT) {1612ws->tiled_left = true;1613}16141615if (window_state & LIBDECOR_WINDOW_STATE_TILED_RIGHT) {1616ws->tiled_right = true;1617}16181619if (window_state & LIBDECOR_WINDOW_STATE_TILED_TOP) {1620ws->tiled_top = true;1621}16221623if (window_state & LIBDECOR_WINDOW_STATE_TILED_BOTTOM) {1624ws->tiled_bottom = true;1625}16261627if (window_state & LIBDECOR_WINDOW_STATE_SUSPENDED) {1628ws->suspended = true;1629}1630}16311632window_state_update_size(ws, width, height);16331634DEBUG_LOG_WAYLAND_THREAD(vformat("libdecor frame on configure rect %s", ws->rect));1635}16361637void WaylandThread::libdecor_frame_on_close(struct libdecor_frame *frame, void *user_data) {1638WindowState *ws = (WindowState *)user_data;1639ERR_FAIL_NULL(ws);16401641Ref<WindowEventMessage> winevent_msg;1642winevent_msg.instantiate();1643winevent_msg->id = ws->id;1644winevent_msg->event = DisplayServer::WINDOW_EVENT_CLOSE_REQUEST;16451646ws->wayland_thread->push_message(winevent_msg);16471648DEBUG_LOG_WAYLAND_THREAD("libdecor frame on close");1649}16501651void WaylandThread::libdecor_frame_on_commit(struct libdecor_frame *frame, void *user_data) {1652// We're skipping this as we don't really care about libdecor's commit for1653// atomicity reasons. See `_frame_wl_callback_on_done` for more info.16541655DEBUG_LOG_WAYLAND_THREAD("libdecor frame on commit");1656}16571658void WaylandThread::libdecor_frame_on_dismiss_popup(struct libdecor_frame *frame, const char *seat_name, void *user_data) {1659}1660#endif // LIBDECOR_ENABLED16611662void WaylandThread::_wl_seat_on_capabilities(void *data, struct wl_seat *wl_seat, uint32_t capabilities) {1663SeatState *ss = (SeatState *)data;16641665ERR_FAIL_NULL(ss);16661667// TODO: Handle touch.16681669// Pointer handling.1670if (capabilities & WL_SEAT_CAPABILITY_POINTER) {1671if (!ss->wl_pointer) {1672ss->cursor_surface = wl_compositor_create_surface(ss->registry->wl_compositor);1673wl_surface_commit(ss->cursor_surface);16741675ss->wl_pointer = wl_seat_get_pointer(wl_seat);1676wl_pointer_add_listener(ss->wl_pointer, &wl_pointer_listener, ss);16771678if (ss->registry->wp_cursor_shape_manager) {1679ss->wp_cursor_shape_device = wp_cursor_shape_manager_v1_get_pointer(ss->registry->wp_cursor_shape_manager, ss->wl_pointer);1680}16811682if (ss->registry->wp_relative_pointer_manager) {1683ss->wp_relative_pointer = zwp_relative_pointer_manager_v1_get_relative_pointer(ss->registry->wp_relative_pointer_manager, ss->wl_pointer);1684zwp_relative_pointer_v1_add_listener(ss->wp_relative_pointer, &wp_relative_pointer_listener, ss);1685}16861687if (ss->registry->wp_pointer_gestures) {1688ss->wp_pointer_gesture_pinch = zwp_pointer_gestures_v1_get_pinch_gesture(ss->registry->wp_pointer_gestures, ss->wl_pointer);1689zwp_pointer_gesture_pinch_v1_add_listener(ss->wp_pointer_gesture_pinch, &wp_pointer_gesture_pinch_listener, ss);1690}16911692// TODO: Constrain new pointers if the global mouse mode is constrained.1693}1694} else {1695if (ss->cursor_frame_callback) {1696// Just in case. I got bitten by weird race-like conditions already.1697wl_callback_set_user_data(ss->cursor_frame_callback, nullptr);16981699wl_callback_destroy(ss->cursor_frame_callback);1700ss->cursor_frame_callback = nullptr;1701}17021703if (ss->cursor_surface) {1704wl_surface_destroy(ss->cursor_surface);1705ss->cursor_surface = nullptr;1706}17071708if (ss->wl_pointer) {1709wl_pointer_destroy(ss->wl_pointer);1710ss->wl_pointer = nullptr;1711}17121713if (ss->wp_cursor_shape_device) {1714wp_cursor_shape_device_v1_destroy(ss->wp_cursor_shape_device);1715ss->wp_cursor_shape_device = nullptr;1716}17171718if (ss->wp_relative_pointer) {1719zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);1720ss->wp_relative_pointer = nullptr;1721}17221723if (ss->wp_confined_pointer) {1724zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);1725ss->wp_confined_pointer = nullptr;1726}17271728if (ss->wp_locked_pointer) {1729zwp_locked_pointer_v1_destroy(ss->wp_locked_pointer);1730ss->wp_locked_pointer = nullptr;1731}1732}17331734// Keyboard handling.1735if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {1736if (!ss->wl_keyboard) {1737ss->xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);1738ERR_FAIL_NULL(ss->xkb_context);17391740ss->wl_keyboard = wl_seat_get_keyboard(wl_seat);1741wl_keyboard_add_listener(ss->wl_keyboard, &wl_keyboard_listener, ss);1742}1743} else {1744if (ss->xkb_context) {1745xkb_context_unref(ss->xkb_context);1746ss->xkb_context = nullptr;1747}17481749if (ss->xkb_compose_table) {1750xkb_compose_table_unref(ss->xkb_compose_table);1751ss->xkb_compose_table = nullptr;1752}17531754if (ss->xkb_compose_state) {1755xkb_compose_state_unref(ss->xkb_compose_state);1756ss->xkb_compose_state = nullptr;1757}17581759if (ss->xkb_keymap) {1760xkb_keymap_unref(ss->xkb_keymap);1761ss->xkb_keymap = nullptr;1762}17631764if (ss->xkb_state) {1765xkb_state_unref(ss->xkb_state);1766ss->xkb_state = nullptr;1767}17681769if (ss->wl_keyboard) {1770wl_keyboard_destroy(ss->wl_keyboard);1771ss->wl_keyboard = nullptr;1772}1773}1774}17751776void WaylandThread::_wl_seat_on_name(void *data, struct wl_seat *wl_seat, const char *name) {1777}17781779void WaylandThread::_cursor_frame_callback_on_done(void *data, struct wl_callback *wl_callback, uint32_t time_ms) {1780wl_callback_destroy(wl_callback);17811782SeatState *ss = (SeatState *)data;1783ERR_FAIL_NULL(ss);17841785ss->cursor_frame_callback = nullptr;17861787ss->cursor_time_ms = time_ms;17881789seat_state_update_cursor(ss);1790}17911792void WaylandThread::_wl_pointer_on_enter(void *data, struct wl_pointer *wl_pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t surface_x, wl_fixed_t surface_y) {1793WindowState *ws = wl_surface_get_window_state(surface);1794if (!ws) {1795return;1796}17971798SeatState *ss = (SeatState *)data;1799ERR_FAIL_NULL(ss);18001801ERR_FAIL_NULL(ss->cursor_surface);18021803PointerData &pd = ss->pointer_data_buffer;18041805ss->pointer_enter_serial = serial;1806pd.pointed_id = ws->id;1807pd.last_pointed_id = ws->id;1808pd.position.x = wl_fixed_to_double(surface_x);1809pd.position.y = wl_fixed_to_double(surface_y);18101811seat_state_update_cursor(ss);18121813DEBUG_LOG_WAYLAND_THREAD(vformat("Pointer entered window %d.", ws->id));18141815if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1816_wl_pointer_on_frame(data, wl_pointer);1817}1818}18191820void WaylandThread::_wl_pointer_on_leave(void *data, struct wl_pointer *wl_pointer, uint32_t serial, struct wl_surface *surface) {1821// NOTE: `surface` will probably be null when the surface is destroyed.1822// See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/3661823// See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/46518241825SeatState *ss = (SeatState *)data;1826ERR_FAIL_NULL(ss);18271828PointerData &pd = ss->pointer_data_buffer;18291830if (pd.pointed_id == DisplayServer::INVALID_WINDOW_ID) {1831// We're probably on a decoration or some other third-party thing.1832return;1833}18341835DisplayServer::WindowID id = pd.pointed_id;18361837pd.pointed_id = DisplayServer::INVALID_WINDOW_ID;1838pd.pressed_button_mask.clear();18391840DEBUG_LOG_WAYLAND_THREAD(vformat("Pointer left window %d.", id));18411842if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1843_wl_pointer_on_frame(data, wl_pointer);1844}1845}18461847void WaylandThread::_wl_pointer_on_motion(void *data, struct wl_pointer *wl_pointer, uint32_t time, wl_fixed_t surface_x, wl_fixed_t surface_y) {1848SeatState *ss = (SeatState *)data;1849ERR_FAIL_NULL(ss);18501851PointerData &pd = ss->pointer_data_buffer;18521853pd.position.x = wl_fixed_to_double(surface_x);1854pd.position.y = wl_fixed_to_double(surface_y);18551856pd.motion_time = time;18571858if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1859_wl_pointer_on_frame(data, wl_pointer);1860}1861}18621863void WaylandThread::_wl_pointer_on_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state) {1864SeatState *ss = (SeatState *)data;1865ERR_FAIL_NULL(ss);18661867PointerData &pd = ss->pointer_data_buffer;18681869MouseButton button_pressed = MouseButton::NONE;18701871switch (button) {1872case BTN_LEFT:1873button_pressed = MouseButton::LEFT;1874break;18751876case BTN_RIGHT:1877button_pressed = MouseButton::RIGHT;1878break;18791880case BTN_MIDDLE:1881button_pressed = MouseButton::MIDDLE;1882break;18831884case BTN_SIDE:1885button_pressed = MouseButton::MB_XBUTTON1;1886break;18871888case BTN_EXTRA:1889button_pressed = MouseButton::MB_XBUTTON2;1890break;18911892default: {1893}1894}18951896MouseButtonMask mask = mouse_button_to_mask(button_pressed);18971898if (state & WL_POINTER_BUTTON_STATE_PRESSED) {1899pd.pressed_button_mask.set_flag(mask);1900pd.last_button_pressed = button_pressed;1901pd.double_click_begun = true;1902} else {1903pd.pressed_button_mask.clear_flag(mask);1904}19051906pd.button_time = time;1907pd.button_serial = serial;19081909if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1910_wl_pointer_on_frame(data, wl_pointer);1911}1912}19131914void WaylandThread::_wl_pointer_on_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {1915SeatState *ss = (SeatState *)data;1916ERR_FAIL_NULL(ss);19171918PointerData &pd = ss->pointer_data_buffer;19191920switch (axis) {1921case WL_POINTER_AXIS_VERTICAL_SCROLL: {1922pd.scroll_vector.y = wl_fixed_to_double(value);1923} break;19241925case WL_POINTER_AXIS_HORIZONTAL_SCROLL: {1926pd.scroll_vector.x = wl_fixed_to_double(value);1927} break;1928}19291930pd.button_time = time;19311932if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1933_wl_pointer_on_frame(data, wl_pointer);1934}1935}19361937void WaylandThread::_wl_pointer_on_frame(void *data, struct wl_pointer *wl_pointer) {1938SeatState *ss = (SeatState *)data;1939ERR_FAIL_NULL(ss);19401941WaylandThread *wayland_thread = ss->wayland_thread;1942ERR_FAIL_NULL(wayland_thread);19431944PointerData &old_pd = ss->pointer_data;1945PointerData &pd = ss->pointer_data_buffer;19461947if (pd.pointed_id != old_pd.pointed_id) {1948if (old_pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {1949Ref<WindowEventMessage> msg;1950msg.instantiate();1951msg->id = old_pd.pointed_id;1952msg->event = DisplayServer::WINDOW_EVENT_MOUSE_EXIT;19531954wayland_thread->push_message(msg);1955}19561957if (pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {1958Ref<WindowEventMessage> msg;1959msg.instantiate();1960msg->id = pd.pointed_id;1961msg->event = DisplayServer::WINDOW_EVENT_MOUSE_ENTER;19621963wayland_thread->push_message(msg);1964}1965}19661967WindowState *ws = nullptr;19681969// NOTE: At least on sway, with wl_pointer version 5 or greater,1970// wl_pointer::leave might be emitted with other events (like1971// wl_pointer::button) within the same wl_pointer::frame. Because of this, we1972// need to account for when the currently pointed window might be invalid1973// (third-party or even none) and fall back to the old one.1974if (pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {1975ws = ss->wayland_thread->window_get_state(pd.pointed_id);1976ERR_FAIL_NULL(ws);1977} else if (old_pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {1978ws = ss->wayland_thread->window_get_state(old_pd.pointed_id);1979ERR_FAIL_NULL(ws);1980}19811982if (ws == nullptr) {1983// We're probably on a decoration or some other third-party thing. Let's1984// "commit" the data and call it a day.1985old_pd = pd;1986return;1987}19881989double scale = window_state_get_scale_factor(ws);19901991wayland_thread->_set_current_seat(ss->wl_seat);19921993if (old_pd.motion_time != pd.motion_time || old_pd.relative_motion_time != pd.relative_motion_time) {1994Ref<InputEventMouseMotion> mm;1995mm.instantiate();19961997// Set all pressed modifiers.1998mm->set_shift_pressed(ss->shift_pressed);1999mm->set_ctrl_pressed(ss->ctrl_pressed);2000mm->set_alt_pressed(ss->alt_pressed);2001mm->set_meta_pressed(ss->meta_pressed);20022003mm->set_window_id(ws->id);20042005mm->set_button_mask(pd.pressed_button_mask);20062007mm->set_position(pd.position * scale);2008mm->set_global_position(pd.position * scale);20092010Vector2 pos_delta = (pd.position - old_pd.position) * scale;20112012if (old_pd.relative_motion_time != pd.relative_motion_time) {2013uint32_t time_delta = pd.relative_motion_time - old_pd.relative_motion_time;20142015mm->set_relative(pd.relative_motion * scale);2016mm->set_velocity((Vector2)pos_delta / time_delta);2017} else {2018// The spec includes the possibility of having motion events without an2019// associated relative motion event. If that's the case, fallback to a2020// simple delta of the position. The captured mouse won't report the2021// relative speed anymore though.2022uint32_t time_delta = pd.motion_time - old_pd.motion_time;20232024mm->set_relative(pos_delta);2025mm->set_velocity((Vector2)pos_delta / time_delta);2026}2027mm->set_relative_screen_position(mm->get_relative());2028mm->set_screen_velocity(mm->get_velocity());20292030Ref<InputEventMessage> msg;2031msg.instantiate();20322033msg->event = mm;20342035wayland_thread->push_message(msg);2036}20372038if (pd.discrete_scroll_vector_120 - old_pd.discrete_scroll_vector_120 != Vector2i()) {2039// This is a discrete scroll (eg. from a scroll wheel), so we'll just emit2040// scroll wheel buttons.2041if (pd.scroll_vector.y != 0) {2042MouseButton button = pd.scroll_vector.y > 0 ? MouseButton::WHEEL_DOWN : MouseButton::WHEEL_UP;2043pd.pressed_button_mask.set_flag(mouse_button_to_mask(button));2044}20452046if (pd.scroll_vector.x != 0) {2047MouseButton button = pd.scroll_vector.x > 0 ? MouseButton::WHEEL_RIGHT : MouseButton::WHEEL_LEFT;2048pd.pressed_button_mask.set_flag(mouse_button_to_mask(button));2049}2050} else {2051if (pd.scroll_vector - old_pd.scroll_vector != Vector2()) {2052// This is a continuous scroll, so we'll emit a pan gesture.2053Ref<InputEventPanGesture> pg;2054pg.instantiate();20552056// Set all pressed modifiers.2057pg->set_shift_pressed(ss->shift_pressed);2058pg->set_ctrl_pressed(ss->ctrl_pressed);2059pg->set_alt_pressed(ss->alt_pressed);2060pg->set_meta_pressed(ss->meta_pressed);20612062pg->set_position(pd.position * scale);20632064pg->set_window_id(ws->id);20652066pg->set_delta(pd.scroll_vector);20672068Ref<InputEventMessage> msg;2069msg.instantiate();20702071msg->event = pg;20722073wayland_thread->push_message(msg);2074}2075}20762077if (old_pd.pressed_button_mask != pd.pressed_button_mask) {2078BitField<MouseButtonMask> pressed_mask_delta = old_pd.pressed_button_mask.get_different(pd.pressed_button_mask);20792080const MouseButton buttons_to_test[] = {2081MouseButton::LEFT,2082MouseButton::MIDDLE,2083MouseButton::RIGHT,2084MouseButton::WHEEL_UP,2085MouseButton::WHEEL_DOWN,2086MouseButton::WHEEL_LEFT,2087MouseButton::WHEEL_RIGHT,2088MouseButton::MB_XBUTTON1,2089MouseButton::MB_XBUTTON2,2090};20912092for (MouseButton test_button : buttons_to_test) {2093MouseButtonMask test_button_mask = mouse_button_to_mask(test_button);2094if (pressed_mask_delta.has_flag(test_button_mask)) {2095Ref<InputEventMouseButton> mb;2096mb.instantiate();20972098// Set all pressed modifiers.2099mb->set_shift_pressed(ss->shift_pressed);2100mb->set_ctrl_pressed(ss->ctrl_pressed);2101mb->set_alt_pressed(ss->alt_pressed);2102mb->set_meta_pressed(ss->meta_pressed);21032104mb->set_window_id(ws->id);2105mb->set_position(pd.position * scale);2106mb->set_global_position(pd.position * scale);21072108if (test_button == MouseButton::WHEEL_UP || test_button == MouseButton::WHEEL_DOWN) {2109// If this is a discrete scroll, specify how many "clicks" it did for this2110// pointer frame.2111mb->set_factor(Math::abs(pd.discrete_scroll_vector_120.y / (float)120));2112}21132114if (test_button == MouseButton::WHEEL_RIGHT || test_button == MouseButton::WHEEL_LEFT) {2115// If this is a discrete scroll, specify how many "clicks" it did for this2116// pointer frame.2117mb->set_factor(std::abs(pd.discrete_scroll_vector_120.x / (float)120));2118}21192120mb->set_button_mask(pd.pressed_button_mask);21212122mb->set_button_index(test_button);2123mb->set_pressed(pd.pressed_button_mask.has_flag(test_button_mask));21242125// We have to set the last position pressed here as we can't take for2126// granted what the individual events might have seen due to them not having2127// a guaranteed order.2128if (mb->is_pressed()) {2129pd.last_pressed_position = pd.position;2130}21312132if (old_pd.double_click_begun && mb->is_pressed() && pd.last_button_pressed == old_pd.last_button_pressed && (pd.button_time - old_pd.button_time) < 400 && Vector2(old_pd.last_pressed_position * scale).distance_to(Vector2(pd.last_pressed_position * scale)) < 5) {2133pd.double_click_begun = false;2134mb->set_double_click(true);2135}21362137Ref<InputEventMessage> msg;2138msg.instantiate();21392140msg->event = mb;21412142wayland_thread->push_message(msg);21432144// Send an event resetting immediately the wheel key.2145// Wayland specification defines axis_stop events as optional and says to2146// treat all axis events as unterminated. As such, we have to manually do2147// it ourselves.2148if (test_button == MouseButton::WHEEL_UP || test_button == MouseButton::WHEEL_DOWN || test_button == MouseButton::WHEEL_LEFT || test_button == MouseButton::WHEEL_RIGHT) {2149// FIXME: This is ugly, I can't find a clean way to clone an InputEvent.2150// This works for now, despite being horrible.2151Ref<InputEventMouseButton> wh_up;2152wh_up.instantiate();21532154wh_up->set_window_id(ws->id);2155wh_up->set_position(pd.position * scale);2156wh_up->set_global_position(pd.position * scale);21572158// We have to unset the button to avoid it getting stuck.2159pd.pressed_button_mask.clear_flag(test_button_mask);2160wh_up->set_button_mask(pd.pressed_button_mask);21612162wh_up->set_button_index(test_button);2163wh_up->set_pressed(false);21642165Ref<InputEventMessage> msg_up;2166msg_up.instantiate();2167msg_up->event = wh_up;2168wayland_thread->push_message(msg_up);2169}2170}2171}2172}21732174// Reset the scroll vectors as we already handled them.2175pd.scroll_vector = Vector2();2176pd.discrete_scroll_vector_120 = Vector2i();21772178// Update the data all getters read. Wayland's specification requires us to do2179// this, since all pointer actions are sent in individual events.2180old_pd = pd;2181}21822183void WaylandThread::_wl_pointer_on_axis_source(void *data, struct wl_pointer *wl_pointer, uint32_t axis_source) {2184SeatState *ss = (SeatState *)data;2185ERR_FAIL_NULL(ss);21862187ss->pointer_data_buffer.scroll_type = axis_source;2188}21892190void WaylandThread::_wl_pointer_on_axis_stop(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis) {2191}21922193// NOTE: This event is deprecated since version 8 and superseded by2194// `wl_pointer::axis_value120`. This thus converts the data to its2195// fraction-of-120 format.2196void WaylandThread::_wl_pointer_on_axis_discrete(void *data, struct wl_pointer *wl_pointer, uint32_t axis, int32_t discrete) {2197SeatState *ss = (SeatState *)data;2198ERR_FAIL_NULL(ss);21992200PointerData &pd = ss->pointer_data_buffer;22012202// NOTE: We can allow ourselves to not accumulate this data (and thus just2203// assign it) as the spec guarantees only one event per axis type.22042205if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) {2206pd.discrete_scroll_vector_120.y = discrete * 120;2207}22082209if (axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL) {2210pd.discrete_scroll_vector_120.x = discrete * 120;2211}2212}22132214// Supersedes `wl_pointer::axis_discrete` Since version 8.2215void WaylandThread::_wl_pointer_on_axis_value120(void *data, struct wl_pointer *wl_pointer, uint32_t axis, int32_t value120) {2216SeatState *ss = (SeatState *)data;2217ERR_FAIL_NULL(ss);22182219PointerData &pd = ss->pointer_data_buffer;22202221if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) {2222pd.discrete_scroll_vector_120.y += value120;2223}22242225if (axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL) {2226pd.discrete_scroll_vector_120.x += value120;2227}2228}22292230// TODO: Add support to this event.2231void WaylandThread::_wl_pointer_on_axis_relative_direction(void *data, struct wl_pointer *wl_pointer, uint32_t axis, uint32_t direction) {2232}22332234void WaylandThread::_wl_keyboard_on_keymap(void *data, struct wl_keyboard *wl_keyboard, uint32_t format, int32_t fd, uint32_t size) {2235ERR_FAIL_COND_MSG(format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, "Unsupported keymap format announced from the Wayland compositor.");22362237SeatState *ss = (SeatState *)data;2238ERR_FAIL_NULL(ss);22392240if (ss->keymap_buffer) {2241// We have already a mapped buffer, so we unmap it. There's no need to reset2242// its pointer or size, as we're gonna set them below.2243munmap((void *)ss->keymap_buffer, ss->keymap_buffer_size);2244ss->keymap_buffer = nullptr;2245}22462247ss->keymap_buffer = (const char *)mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);2248ss->keymap_buffer_size = size;22492250xkb_keymap_unref(ss->xkb_keymap);2251ss->xkb_keymap = xkb_keymap_new_from_string(ss->xkb_context, ss->keymap_buffer,2252XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);22532254xkb_state_unref(ss->xkb_state);2255ss->xkb_state = xkb_state_new(ss->xkb_keymap);22562257xkb_compose_table_unref(ss->xkb_compose_table);2258const char *locale = getenv("LC_ALL");2259if (!locale || !*locale) {2260locale = getenv("LC_CTYPE");2261}2262if (!locale || !*locale) {2263locale = getenv("LANG");2264}2265if (!locale || !*locale) {2266locale = "C";2267}2268ss->xkb_compose_table = xkb_compose_table_new_from_locale(ss->xkb_context, locale, XKB_COMPOSE_COMPILE_NO_FLAGS);22692270xkb_compose_state_unref(ss->xkb_compose_state);2271ss->xkb_compose_state = xkb_compose_state_new(ss->xkb_compose_table, XKB_COMPOSE_STATE_NO_FLAGS);22722273xkb_state_update_mask(ss->xkb_state, ss->mods_depressed, ss->mods_latched, ss->mods_locked, 0, 0, ss->current_layout_index);2274}22752276void WaylandThread::_wl_keyboard_on_enter(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, struct wl_surface *surface, struct wl_array *keys) {2277WindowState *ws = wl_surface_get_window_state(surface);2278if (!ws) {2279return;2280}22812282SeatState *ss = (SeatState *)data;2283ERR_FAIL_NULL(ss);22842285WaylandThread *wayland_thread = ss->wayland_thread;2286ERR_FAIL_NULL(wayland_thread);22872288ss->focused_id = ws->id;22892290wayland_thread->_set_current_seat(ss->wl_seat);22912292Ref<WindowEventMessage> msg;2293msg.instantiate();2294msg->id = ws->id;2295msg->event = DisplayServer::WINDOW_EVENT_FOCUS_IN;2296wayland_thread->push_message(msg);22972298DEBUG_LOG_WAYLAND_THREAD(vformat("Keyboard focused window %d.", ws->id));2299}23002301void WaylandThread::_wl_keyboard_on_leave(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, struct wl_surface *surface) {2302// NOTE: `surface` will probably be null when the surface is destroyed.2303// See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/3662304// See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/46523052306if (surface && !wl_proxy_is_godot((struct wl_proxy *)surface)) {2307return;2308}23092310SeatState *ss = (SeatState *)data;2311ERR_FAIL_NULL(ss);23122313WaylandThread *wayland_thread = ss->wayland_thread;2314ERR_FAIL_NULL(wayland_thread);23152316ss->repeating_keycode = XKB_KEYCODE_INVALID;23172318if (ss->focused_id == DisplayServer::INVALID_WINDOW_ID) {2319// We're probably on a decoration or some other third-party thing.2320return;2321}23222323WindowState *ws = wayland_thread->window_get_state(ss->focused_id);2324ERR_FAIL_NULL(ws);23252326ss->focused_id = DisplayServer::INVALID_WINDOW_ID;23272328Ref<WindowEventMessage> msg;2329msg.instantiate();2330msg->id = ws->id;2331msg->event = DisplayServer::WINDOW_EVENT_FOCUS_OUT;2332wayland_thread->push_message(msg);23332334ss->shift_pressed = false;2335ss->ctrl_pressed = false;2336ss->alt_pressed = false;2337ss->meta_pressed = false;23382339if (ss->xkb_state != nullptr) {2340xkb_state_update_mask(ss->xkb_state, 0, 0, 0, 0, 0, 0);2341}23422343DEBUG_LOG_WAYLAND_THREAD(vformat("Keyboard unfocused window %d.", ws->id));2344}23452346void WaylandThread::_wl_keyboard_on_key(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) {2347SeatState *ss = (SeatState *)data;2348ERR_FAIL_NULL(ss);23492350if (ss->focused_id == DisplayServer::INVALID_WINDOW_ID) {2351return;2352}23532354// We have to add 8 to the scancode to get an XKB-compatible keycode.2355xkb_keycode_t xkb_keycode = key + 8;23562357bool pressed = state & WL_KEYBOARD_KEY_STATE_PRESSED;23582359if (pressed) {2360if (xkb_keymap_key_repeats(ss->xkb_keymap, xkb_keycode)) {2361ss->last_repeat_start_msec = OS::get_singleton()->get_ticks_msec();2362ss->repeating_keycode = xkb_keycode;2363}23642365ss->last_key_pressed_serial = serial;2366} else if (ss->repeating_keycode == xkb_keycode) {2367ss->repeating_keycode = XKB_KEYCODE_INVALID;2368}23692370_seat_state_handle_xkb_keycode(ss, xkb_keycode, pressed);2371}23722373void WaylandThread::_wl_keyboard_on_modifiers(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {2374SeatState *ss = (SeatState *)data;2375ERR_FAIL_NULL(ss);23762377ss->mods_depressed = mods_depressed;2378ss->mods_latched = mods_latched;2379ss->mods_locked = mods_locked;2380ss->current_layout_index = group;23812382if (ss->xkb_state == nullptr) {2383return;2384}23852386xkb_state_update_mask(ss->xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group);23872388ss->shift_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_SHIFT, XKB_STATE_MODS_EFFECTIVE);2389ss->ctrl_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_EFFECTIVE);2390ss->alt_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_ALT, XKB_STATE_MODS_EFFECTIVE);2391ss->meta_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_LOGO, XKB_STATE_MODS_EFFECTIVE);2392}23932394void WaylandThread::_wl_keyboard_on_repeat_info(void *data, struct wl_keyboard *wl_keyboard, int32_t rate, int32_t delay) {2395SeatState *ss = (SeatState *)data;2396ERR_FAIL_NULL(ss);23972398ss->repeat_key_delay_msec = rate ? 1000 / rate : 0;2399ss->repeat_start_delay_msec = delay;2400}24012402// NOTE: Don't forget to `memfree` the offer's state.2403void WaylandThread::_wl_data_device_on_data_offer(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *id) {2404wl_proxy_tag_godot((struct wl_proxy *)id);2405wl_data_offer_add_listener(id, &wl_data_offer_listener, memnew(OfferState));2406}24072408void WaylandThread::_wl_data_device_on_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) {2409WindowState *ws = wl_surface_get_window_state(surface);2410if (!ws) {2411return;2412}24132414SeatState *ss = (SeatState *)data;2415ERR_FAIL_NULL(ss);24162417ss->dnd_id = ws->id;24182419ss->dnd_enter_serial = serial;2420ss->wl_data_offer_dnd = id;24212422// Godot only supports DnD file copying for now.2423wl_data_offer_accept(id, serial, "text/uri-list");2424wl_data_offer_set_actions(id, WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY, WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY);2425}24262427void WaylandThread::_wl_data_device_on_leave(void *data, struct wl_data_device *wl_data_device) {2428SeatState *ss = (SeatState *)data;2429ERR_FAIL_NULL(ss);24302431if (ss->wl_data_offer_dnd) {2432memdelete(wl_data_offer_get_offer_state(ss->wl_data_offer_dnd));2433wl_data_offer_destroy(ss->wl_data_offer_dnd);2434ss->wl_data_offer_dnd = nullptr;2435ss->dnd_id = DisplayServer::INVALID_WINDOW_ID;2436}2437}24382439void WaylandThread::_wl_data_device_on_motion(void *data, struct wl_data_device *wl_data_device, uint32_t time, wl_fixed_t x, wl_fixed_t y) {2440}24412442void WaylandThread::_wl_data_device_on_drop(void *data, struct wl_data_device *wl_data_device) {2443SeatState *ss = (SeatState *)data;2444ERR_FAIL_NULL(ss);24452446WaylandThread *wayland_thread = ss->wayland_thread;2447ERR_FAIL_NULL(wayland_thread);24482449OfferState *os = wl_data_offer_get_offer_state(ss->wl_data_offer_dnd);2450ERR_FAIL_NULL(os);24512452if (os) {2453Ref<DropFilesEventMessage> msg;2454msg.instantiate();2455msg->id = ss->dnd_id;24562457Vector<uint8_t> list_data = _wl_data_offer_read(wayland_thread->wl_display, "text/uri-list", ss->wl_data_offer_dnd);24582459msg->files = String::utf8((const char *)list_data.ptr(), list_data.size()).split("\r\n", false);2460for (int i = 0; i < msg->files.size(); i++) {2461msg->files.write[i] = msg->files[i].replace("file://", "").uri_file_decode();2462}24632464wayland_thread->push_message(msg);24652466wl_data_offer_finish(ss->wl_data_offer_dnd);2467}24682469memdelete(wl_data_offer_get_offer_state(ss->wl_data_offer_dnd));2470wl_data_offer_destroy(ss->wl_data_offer_dnd);2471ss->wl_data_offer_dnd = nullptr;2472ss->dnd_id = DisplayServer::INVALID_WINDOW_ID;2473}24742475void WaylandThread::_wl_data_device_on_selection(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *id) {2476SeatState *ss = (SeatState *)data;2477ERR_FAIL_NULL(ss);24782479if (ss->wl_data_offer_selection) {2480memdelete(wl_data_offer_get_offer_state(ss->wl_data_offer_selection));2481wl_data_offer_destroy(ss->wl_data_offer_selection);2482}24832484ss->wl_data_offer_selection = id;2485}24862487void WaylandThread::_wl_data_offer_on_offer(void *data, struct wl_data_offer *wl_data_offer, const char *mime_type) {2488OfferState *os = (OfferState *)data;2489ERR_FAIL_NULL(os);24902491if (os) {2492os->mime_types.insert(String::utf8(mime_type));2493}2494}24952496void WaylandThread::_wl_data_offer_on_source_actions(void *data, struct wl_data_offer *wl_data_offer, uint32_t source_actions) {2497}24982499void WaylandThread::_wl_data_offer_on_action(void *data, struct wl_data_offer *wl_data_offer, uint32_t dnd_action) {2500}25012502void WaylandThread::_wl_data_source_on_target(void *data, struct wl_data_source *wl_data_source, const char *mime_type) {2503}25042505void WaylandThread::_wl_data_source_on_send(void *data, struct wl_data_source *wl_data_source, const char *mime_type, int32_t fd) {2506SeatState *ss = (SeatState *)data;2507ERR_FAIL_NULL(ss);25082509Vector<uint8_t> *data_to_send = nullptr;25102511if (wl_data_source == ss->wl_data_source_selection) {2512data_to_send = &ss->selection_data;2513DEBUG_LOG_WAYLAND_THREAD("Clipboard: requested selection.");2514}25152516if (data_to_send) {2517ssize_t written_bytes = 0;25182519bool valid_mime = false;25202521if (strcmp(mime_type, "text/plain;charset=utf-8") == 0) {2522valid_mime = true;2523} else if (strcmp(mime_type, "text/plain") == 0) {2524valid_mime = true;2525}25262527if (valid_mime) {2528written_bytes = write(fd, data_to_send->ptr(), data_to_send->size());2529}25302531if (written_bytes > 0) {2532DEBUG_LOG_WAYLAND_THREAD(vformat("Clipboard: sent %d bytes.", written_bytes));2533} else if (written_bytes == 0) {2534DEBUG_LOG_WAYLAND_THREAD("Clipboard: no bytes sent.");2535} else {2536ERR_PRINT(vformat("Clipboard: write error %d.", errno));2537}2538}25392540close(fd);2541}25422543void WaylandThread::_wl_data_source_on_cancelled(void *data, struct wl_data_source *wl_data_source) {2544SeatState *ss = (SeatState *)data;2545ERR_FAIL_NULL(ss);25462547wl_data_source_destroy(wl_data_source);25482549if (wl_data_source == ss->wl_data_source_selection) {2550ss->wl_data_source_selection = nullptr;2551ss->selection_data.clear();25522553DEBUG_LOG_WAYLAND_THREAD("Clipboard: selection set by another program.");2554return;2555}2556}25572558void WaylandThread::_wl_data_source_on_dnd_drop_performed(void *data, struct wl_data_source *wl_data_source) {2559}25602561void WaylandThread::_wl_data_source_on_dnd_finished(void *data, struct wl_data_source *wl_data_source) {2562}25632564void WaylandThread::_wl_data_source_on_action(void *data, struct wl_data_source *wl_data_source, uint32_t dnd_action) {2565}25662567void WaylandThread::_wp_fractional_scale_on_preferred_scale(void *data, struct wp_fractional_scale_v1 *wp_fractional_scale_v1, uint32_t scale) {2568WindowState *ws = (WindowState *)data;2569ERR_FAIL_NULL(ws);25702571ws->preferred_fractional_scale = (double)scale / 120;25722573window_state_update_size(ws, ws->rect.size.width, ws->rect.size.height);2574}25752576void WaylandThread::_wp_relative_pointer_on_relative_motion(void *data, struct zwp_relative_pointer_v1 *wp_relative_pointer, uint32_t uptime_hi, uint32_t uptime_lo, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t dx_unaccel, wl_fixed_t dy_unaccel) {2577SeatState *ss = (SeatState *)data;2578ERR_FAIL_NULL(ss);25792580PointerData &pd = ss->pointer_data_buffer;25812582pd.relative_motion.x = wl_fixed_to_double(dx);2583pd.relative_motion.y = wl_fixed_to_double(dy);25842585pd.relative_motion_time = uptime_lo;2586}25872588void WaylandThread::_wp_pointer_gesture_pinch_on_begin(void *data, struct zwp_pointer_gesture_pinch_v1 *wp_pointer_gesture_pinch_v1, uint32_t serial, uint32_t time, struct wl_surface *surface, uint32_t fingers) {2589SeatState *ss = (SeatState *)data;2590ERR_FAIL_NULL(ss);25912592if (fingers == 2) {2593ss->old_pinch_scale = wl_fixed_from_int(1);2594ss->active_gesture = Gesture::MAGNIFY;2595}2596}25972598void WaylandThread::_wp_pointer_gesture_pinch_on_update(void *data, struct zwp_pointer_gesture_pinch_v1 *wp_pointer_gesture_pinch_v1, uint32_t time, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t scale, wl_fixed_t rotation) {2599SeatState *ss = (SeatState *)data;2600ERR_FAIL_NULL(ss);26012602// NOTE: From what I can tell, this and all other pointer gestures are separate2603// from the "frame" mechanism of regular pointers. Thus, let's just assume we2604// can read from the "committed" state.2605const PointerData &pd = ss->pointer_data;26062607WaylandThread *wayland_thread = ss->wayland_thread;2608ERR_FAIL_NULL(wayland_thread);26092610WindowState *ws = wayland_thread->window_get_state(pd.pointed_id);2611ERR_FAIL_NULL(ws);26122613double win_scale = window_state_get_scale_factor(ws);26142615if (ss->active_gesture == Gesture::MAGNIFY) {2616Ref<InputEventMagnifyGesture> mg;2617mg.instantiate();26182619mg->set_window_id(pd.pointed_id);26202621if (ws) {2622mg->set_window_id(ws->id);2623}26242625// Set all pressed modifiers.2626mg->set_shift_pressed(ss->shift_pressed);2627mg->set_ctrl_pressed(ss->ctrl_pressed);2628mg->set_alt_pressed(ss->alt_pressed);2629mg->set_meta_pressed(ss->meta_pressed);26302631mg->set_position(pd.position * win_scale);26322633wl_fixed_t scale_delta = scale - ss->old_pinch_scale;2634mg->set_factor(1 + wl_fixed_to_double(scale_delta));26352636Ref<InputEventMessage> magnify_msg;2637magnify_msg.instantiate();2638magnify_msg->event = mg;26392640// Since Wayland allows only one gesture at a time and godot instead expects2641// both of them, we'll have to create two separate input events: one for2642// magnification and one for panning.26432644Ref<InputEventPanGesture> pg;2645pg.instantiate();26462647// Set all pressed modifiers.2648pg->set_shift_pressed(ss->shift_pressed);2649pg->set_ctrl_pressed(ss->ctrl_pressed);2650pg->set_alt_pressed(ss->alt_pressed);2651pg->set_meta_pressed(ss->meta_pressed);26522653pg->set_position(pd.position * win_scale);2654pg->set_delta(Vector2(wl_fixed_to_double(dx), wl_fixed_to_double(dy)));26552656Ref<InputEventMessage> pan_msg;2657pan_msg.instantiate();2658pan_msg->event = pg;26592660wayland_thread->push_message(magnify_msg);2661wayland_thread->push_message(pan_msg);26622663ss->old_pinch_scale = scale;2664}2665}26662667void WaylandThread::_wp_pointer_gesture_pinch_on_end(void *data, struct zwp_pointer_gesture_pinch_v1 *wp_pointer_gesture_pinch_v1, uint32_t serial, uint32_t time, int32_t cancelled) {2668SeatState *ss = (SeatState *)data;2669ERR_FAIL_NULL(ss);26702671ss->active_gesture = Gesture::NONE;2672}26732674// NOTE: Don't forget to `memfree` the offer's state.2675void WaylandThread::_wp_primary_selection_device_on_data_offer(void *data, struct zwp_primary_selection_device_v1 *wp_primary_selection_device_v1, struct zwp_primary_selection_offer_v1 *offer) {2676wl_proxy_tag_godot((struct wl_proxy *)offer);2677zwp_primary_selection_offer_v1_add_listener(offer, &wp_primary_selection_offer_listener, memnew(OfferState));2678}26792680void WaylandThread::_wp_primary_selection_device_on_selection(void *data, struct zwp_primary_selection_device_v1 *wp_primary_selection_device_v1, struct zwp_primary_selection_offer_v1 *id) {2681SeatState *ss = (SeatState *)data;2682ERR_FAIL_NULL(ss);26832684if (ss->wp_primary_selection_offer) {2685memfree(wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer));2686zwp_primary_selection_offer_v1_destroy(ss->wp_primary_selection_offer);2687}26882689ss->wp_primary_selection_offer = id;2690}26912692void WaylandThread::_wp_primary_selection_offer_on_offer(void *data, struct zwp_primary_selection_offer_v1 *wp_primary_selection_offer_v1, const char *mime_type) {2693OfferState *os = (OfferState *)data;2694ERR_FAIL_NULL(os);26952696if (os) {2697os->mime_types.insert(String::utf8(mime_type));2698}2699}27002701void WaylandThread::_wp_primary_selection_source_on_send(void *data, struct zwp_primary_selection_source_v1 *wp_primary_selection_source_v1, const char *mime_type, int32_t fd) {2702SeatState *ss = (SeatState *)data;2703ERR_FAIL_NULL(ss);27042705Vector<uint8_t> *data_to_send = nullptr;27062707if (wp_primary_selection_source_v1 == ss->wp_primary_selection_source) {2708data_to_send = &ss->primary_data;2709DEBUG_LOG_WAYLAND_THREAD("Clipboard: requested primary selection.");2710}27112712if (data_to_send) {2713ssize_t written_bytes = 0;27142715if (strcmp(mime_type, "text/plain") == 0) {2716written_bytes = write(fd, data_to_send->ptr(), data_to_send->size());2717}27182719if (written_bytes > 0) {2720DEBUG_LOG_WAYLAND_THREAD(vformat("Clipboard: sent %d bytes.", written_bytes));2721} else if (written_bytes == 0) {2722DEBUG_LOG_WAYLAND_THREAD("Clipboard: no bytes sent.");2723} else {2724ERR_PRINT(vformat("Clipboard: write error %d.", errno));2725}2726}27272728close(fd);2729}27302731void WaylandThread::_wp_primary_selection_source_on_cancelled(void *data, struct zwp_primary_selection_source_v1 *wp_primary_selection_source_v1) {2732SeatState *ss = (SeatState *)data;2733ERR_FAIL_NULL(ss);27342735if (wp_primary_selection_source_v1 == ss->wp_primary_selection_source) {2736zwp_primary_selection_source_v1_destroy(ss->wp_primary_selection_source);2737ss->wp_primary_selection_source = nullptr;27382739ss->primary_data.clear();27402741DEBUG_LOG_WAYLAND_THREAD("Clipboard: primary selection set by another program.");2742return;2743}2744}27452746void WaylandThread::_wp_tablet_seat_on_tablet_added(void *data, struct zwp_tablet_seat_v2 *wp_tablet_seat_v2, struct zwp_tablet_v2 *id) {2747}27482749void WaylandThread::_wp_tablet_seat_on_tool_added(void *data, struct zwp_tablet_seat_v2 *wp_tablet_seat_v2, struct zwp_tablet_tool_v2 *id) {2750SeatState *ss = (SeatState *)data;2751ERR_FAIL_NULL(ss);27522753TabletToolState *state = memnew(TabletToolState);2754state->wl_seat = ss->wl_seat;27552756wl_proxy_tag_godot((struct wl_proxy *)id);2757zwp_tablet_tool_v2_add_listener(id, &wp_tablet_tool_listener, state);2758ss->tablet_tools.push_back(id);2759}27602761void WaylandThread::_wp_tablet_seat_on_pad_added(void *data, struct zwp_tablet_seat_v2 *wp_tablet_seat_v2, struct zwp_tablet_pad_v2 *id) {2762}27632764void WaylandThread::_wp_tablet_tool_on_type(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t tool_type) {2765TabletToolState *state = wp_tablet_tool_get_state(wp_tablet_tool_v2);27662767if (state && tool_type == ZWP_TABLET_TOOL_V2_TYPE_ERASER) {2768state->is_eraser = true;2769}2770}27712772void WaylandThread::_wp_tablet_tool_on_hardware_serial(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t hardware_serial_hi, uint32_t hardware_serial_lo) {2773}27742775void WaylandThread::_wp_tablet_tool_on_hardware_id_wacom(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t hardware_id_hi, uint32_t hardware_id_lo) {2776}27772778void WaylandThread::_wp_tablet_tool_on_capability(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t capability) {2779}27802781void WaylandThread::_wp_tablet_tool_on_done(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {2782}27832784void WaylandThread::_wp_tablet_tool_on_removed(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {2785TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2786if (!ts) {2787return;2788}27892790SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);2791if (!ss) {2792return;2793}27942795List<struct zwp_tablet_tool_v2 *>::Element *E = ss->tablet_tools.find(wp_tablet_tool_v2);27962797if (E && E->get()) {2798struct zwp_tablet_tool_v2 *tool = E->get();2799TabletToolState *state = wp_tablet_tool_get_state(tool);2800if (state) {2801memdelete(state);2802}28032804zwp_tablet_tool_v2_destroy(tool);2805ss->tablet_tools.erase(E);2806}2807}28082809void WaylandThread::_wp_tablet_tool_on_proximity_in(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t serial, struct zwp_tablet_v2 *tablet, struct wl_surface *surface) {2810// NOTE: Works pretty much like wl_pointer::enter.28112812WindowState *ws = wl_surface_get_window_state(surface);2813if (!ws) {2814return;2815}28162817TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2818ERR_FAIL_NULL(ts);28192820ts->data_pending.proximity_serial = serial;2821ts->data_pending.proximal_id = ws->id;2822ts->data_pending.last_proximal_id = ws->id;28232824DEBUG_LOG_WAYLAND_THREAD(vformat("Tablet tool entered window %d.", ts->data_pending.proximal_id));2825}28262827void WaylandThread::_wp_tablet_tool_on_proximity_out(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {2828// NOTE: Works pretty much like wl_pointer::leave.28292830TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2831ERR_FAIL_NULL(ts);28322833if (ts->data_pending.proximal_id == DisplayServer::INVALID_WINDOW_ID) {2834// We're probably on a decoration or some other third-party thing.2835return;2836}28372838DisplayServer::WindowID id = ts->data_pending.proximal_id;28392840ts->data_pending.proximal_id = DisplayServer::INVALID_WINDOW_ID;2841ts->data_pending.pressed_button_mask.clear();28422843DEBUG_LOG_WAYLAND_THREAD(vformat("Tablet tool left window %d.", id));2844}28452846void WaylandThread::_wp_tablet_tool_on_down(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t serial) {2847// NOTE: Works pretty much like wl_pointer::button but only for a pressed left2848// button.28492850TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2851ERR_FAIL_NULL(ts);28522853TabletToolData &td = ts->data_pending;28542855td.pressed_button_mask.set_flag(mouse_button_to_mask(MouseButton::LEFT));2856td.last_button_pressed = MouseButton::LEFT;2857td.double_click_begun = true;28582859// The protocol doesn't cover this, but we can use this funky hack to make2860// double clicking work.2861td.button_time = OS::get_singleton()->get_ticks_msec();2862}28632864void WaylandThread::_wp_tablet_tool_on_up(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {2865// NOTE: Works pretty much like wl_pointer::button but only for a released left2866// button.28672868TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2869ERR_FAIL_NULL(ts);28702871TabletToolData &td = ts->data_pending;28722873td.pressed_button_mask.clear_flag(mouse_button_to_mask(MouseButton::LEFT));28742875// The protocol doesn't cover this, but we can use this funky hack to make2876// double clicking work.2877td.button_time = OS::get_singleton()->get_ticks_msec();2878}28792880void WaylandThread::_wp_tablet_tool_on_motion(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t x, wl_fixed_t y) {2881// NOTE: Works pretty much like wl_pointer::motion.28822883TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2884ERR_FAIL_NULL(ts);28852886TabletToolData &td = ts->data_pending;28872888td.position.x = wl_fixed_to_double(x);2889td.position.y = wl_fixed_to_double(y);2890}28912892void WaylandThread::_wp_tablet_tool_on_pressure(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t pressure) {2893TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2894ERR_FAIL_NULL(ts);28952896ts->data_pending.pressure = pressure;2897}28982899void WaylandThread::_wp_tablet_tool_on_distance(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t distance) {2900// Unsupported2901}29022903void WaylandThread::_wp_tablet_tool_on_tilt(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t tilt_x, wl_fixed_t tilt_y) {2904TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2905ERR_FAIL_NULL(ts);29062907TabletToolData &td = ts->data_pending;29082909td.tilt.x = wl_fixed_to_double(tilt_x);2910td.tilt.y = wl_fixed_to_double(tilt_y);2911}29122913void WaylandThread::_wp_tablet_tool_on_rotation(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t degrees) {2914// Unsupported.2915}29162917void WaylandThread::_wp_tablet_tool_on_slider(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, int32_t position) {2918// Unsupported.2919}29202921void WaylandThread::_wp_tablet_tool_on_wheel(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t degrees, int32_t clicks) {2922// TODO2923}29242925void WaylandThread::_wp_tablet_tool_on_button(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t serial, uint32_t button, uint32_t state) {2926// NOTE: Works pretty much like wl_pointer::button.29272928TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2929ERR_FAIL_NULL(ts);29302931TabletToolData &td = ts->data_pending;29322933MouseButton mouse_button = MouseButton::NONE;29342935if (button == BTN_STYLUS) {2936mouse_button = MouseButton::LEFT;2937}29382939if (button == BTN_STYLUS2) {2940mouse_button = MouseButton::RIGHT;2941}29422943if (mouse_button != MouseButton::NONE) {2944MouseButtonMask mask = mouse_button_to_mask(mouse_button);29452946if (state == ZWP_TABLET_TOOL_V2_BUTTON_STATE_PRESSED) {2947td.pressed_button_mask.set_flag(mask);2948td.last_button_pressed = mouse_button;2949td.double_click_begun = true;2950} else {2951td.pressed_button_mask.clear_flag(mask);2952}29532954// The protocol doesn't cover this, but we can use this funky hack to make2955// double clicking work.2956td.button_time = OS::get_singleton()->get_ticks_msec();2957}2958}29592960void WaylandThread::_wp_tablet_tool_on_frame(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t time) {2961// NOTE: Works pretty much like wl_pointer::frame.29622963TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2964ERR_FAIL_NULL(ts);29652966SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);2967ERR_FAIL_NULL(ss);29682969WaylandThread *wayland_thread = ss->wayland_thread;2970ERR_FAIL_NULL(wayland_thread);29712972TabletToolData &old_td = ts->data;2973TabletToolData &td = ts->data_pending;29742975if (td.proximal_id != old_td.proximal_id) {2976if (old_td.proximal_id != DisplayServer::INVALID_WINDOW_ID) {2977Ref<WindowEventMessage> msg;2978msg.instantiate();2979msg->id = old_td.proximal_id;2980msg->event = DisplayServer::WINDOW_EVENT_MOUSE_EXIT;29812982wayland_thread->push_message(msg);2983}29842985if (td.proximal_id != DisplayServer::INVALID_WINDOW_ID) {2986Ref<WindowEventMessage> msg;2987msg.instantiate();2988msg->id = td.proximal_id;2989msg->event = DisplayServer::WINDOW_EVENT_MOUSE_ENTER;29902991wayland_thread->push_message(msg);2992}2993}29942995if (td.proximal_id == DisplayServer::INVALID_WINDOW_ID) {2996// We're probably on a decoration or some other third-party thing. Let's2997// "commit" the data and call it a day.2998old_td = td;2999return;3000}30013002WindowState *ws = wayland_thread->window_get_state(td.proximal_id);3003ERR_FAIL_NULL(ws);30043005double scale = window_state_get_scale_factor(ws);3006if (old_td.position != td.position || old_td.tilt != td.tilt || old_td.pressure != td.pressure) {3007td.motion_time = time;30083009Ref<InputEventMouseMotion> mm;3010mm.instantiate();30113012mm->set_window_id(td.proximal_id);30133014// Set all pressed modifiers.3015mm->set_shift_pressed(ss->shift_pressed);3016mm->set_ctrl_pressed(ss->ctrl_pressed);3017mm->set_alt_pressed(ss->alt_pressed);3018mm->set_meta_pressed(ss->meta_pressed);30193020mm->set_button_mask(td.pressed_button_mask);30213022mm->set_global_position(td.position * scale);3023mm->set_position(td.position * scale);30243025// NOTE: The Godot API expects normalized values and we store them raw,3026// straight from the compositor, so we have to normalize them here.30273028// According to the tablet proto spec, tilt is expressed in degrees relative3029// to the Z axis of the tablet, so it shouldn't go over 90 degrees either way,3030// I think. We'll clamp it just in case.3031td.tilt = td.tilt.clampf(-90, 90);30323033mm->set_tilt(td.tilt / 90);30343035// The tablet proto spec explicitly says that pressure is defined as a value3036// between 0 to 65535.3037mm->set_pressure(td.pressure / (float)65535);30383039mm->set_pen_inverted(ts->is_eraser);30403041Vector2 pos_delta = (td.position - old_td.position) * scale;30423043mm->set_relative(pos_delta);3044mm->set_relative_screen_position(pos_delta);30453046uint32_t time_delta = td.motion_time - old_td.motion_time;3047mm->set_velocity((Vector2)pos_delta / time_delta);30483049Ref<InputEventMessage> inputev_msg;3050inputev_msg.instantiate();30513052inputev_msg->event = mm;30533054wayland_thread->push_message(inputev_msg);3055}30563057if (old_td.pressed_button_mask != td.pressed_button_mask) {3058td.button_time = time;30593060BitField<MouseButtonMask> pressed_mask_delta = old_td.pressed_button_mask.get_different(td.pressed_button_mask);30613062for (MouseButton test_button : { MouseButton::LEFT, MouseButton::RIGHT }) {3063MouseButtonMask test_button_mask = mouse_button_to_mask(test_button);30643065if (pressed_mask_delta.has_flag(test_button_mask)) {3066Ref<InputEventMouseButton> mb;3067mb.instantiate();30683069// Set all pressed modifiers.3070mb->set_shift_pressed(ss->shift_pressed);3071mb->set_ctrl_pressed(ss->ctrl_pressed);3072mb->set_alt_pressed(ss->alt_pressed);3073mb->set_meta_pressed(ss->meta_pressed);30743075mb->set_window_id(td.proximal_id);3076mb->set_position(td.position * scale);3077mb->set_global_position(td.position * scale);30783079mb->set_button_mask(td.pressed_button_mask);3080mb->set_button_index(test_button);3081mb->set_pressed(td.pressed_button_mask.has_flag(test_button_mask));30823083// We have to set the last position pressed here as we can't take for3084// granted what the individual events might have seen due to them not having3085// a garaunteed order.3086if (mb->is_pressed()) {3087td.last_pressed_position = td.position;3088}30893090if (old_td.double_click_begun && mb->is_pressed() && td.last_button_pressed == old_td.last_button_pressed && (td.button_time - old_td.button_time) < 400 && Vector2(td.last_pressed_position * scale).distance_to(Vector2(old_td.last_pressed_position * scale)) < 5) {3091td.double_click_begun = false;3092mb->set_double_click(true);3093}30943095Ref<InputEventMessage> msg;3096msg.instantiate();30973098msg->event = mb;30993100wayland_thread->push_message(msg);3101}3102}3103}31043105old_td = td;3106}31073108void WaylandThread::_wp_text_input_on_enter(void *data, struct zwp_text_input_v3 *wp_text_input_v3, struct wl_surface *surface) {3109SeatState *ss = (SeatState *)data;3110if (!ss) {3111return;3112}31133114WindowState *ws = wl_surface_get_window_state(surface);3115if (!ws) {3116return;3117}31183119ss->ime_window_id = ws->id;3120ss->ime_enabled = true;3121}31223123// NOTE: From now on, we must ignore all further events until an enter event.3124void WaylandThread::_wp_text_input_on_leave(void *data, struct zwp_text_input_v3 *wp_text_input_v3, struct wl_surface *surface) {3125SeatState *ss = (SeatState *)data;3126if (!ss) {3127return;3128}31293130if (ss->ime_window_id == DisplayServer::INVALID_WINDOW_ID) {3131return;3132}31333134Ref<IMEUpdateEventMessage> msg;3135msg.instantiate();3136msg->id = ss->ime_window_id;3137msg->text = String();3138msg->selection = Vector2i();3139ss->wayland_thread->push_message(msg);31403141ss->ime_window_id = DisplayServer::INVALID_WINDOW_ID;3142ss->ime_enabled = false;3143ss->ime_active = false;3144ss->ime_text = String();3145ss->ime_text_commit = String();3146ss->ime_cursor = Vector2i();3147}31483149void WaylandThread::_wp_text_input_on_preedit_string(void *data, struct zwp_text_input_v3 *wp_text_input_v3, const char *text, int32_t cursor_begin, int32_t cursor_end) {3150SeatState *ss = (SeatState *)data;3151if (!ss) {3152return;3153}31543155if (ss->ime_window_id == DisplayServer::INVALID_WINDOW_ID) {3156return;3157}31583159ss->ime_text = String::utf8(text);31603161// Convert cursor positions from UTF-8 to UTF-32 offset.3162int32_t cursor_begin_utf32 = 0;3163int32_t cursor_end_utf32 = 0;3164for (int i = 0; i < ss->ime_text.length(); i++) {3165uint32_t c = ss->ime_text[i];3166if (c <= 0x7f) { // 7 bits.3167cursor_begin -= 1;3168cursor_end -= 1;3169} else if (c <= 0x7ff) { // 11 bits3170cursor_begin -= 2;3171cursor_end -= 2;3172} else if (c <= 0xffff) { // 16 bits3173cursor_begin -= 3;3174cursor_end -= 3;3175} else if (c <= 0x001fffff) { // 21 bits3176cursor_begin -= 4;3177cursor_end -= 4;3178} else if (c <= 0x03ffffff) { // 26 bits3179cursor_begin -= 5;3180cursor_end -= 5;3181} else if (c <= 0x7fffffff) { // 31 bits3182cursor_begin -= 6;3183cursor_end -= 6;3184} else {3185cursor_begin -= 1;3186cursor_end -= 1;3187}3188if (cursor_begin == 0) {3189cursor_begin_utf32 = i + 1;3190}3191if (cursor_end == 0) {3192cursor_end_utf32 = i + 1;3193}3194if (cursor_begin <= 0 && cursor_end <= 0) {3195break;3196}3197}3198ss->ime_cursor = Vector2i(cursor_begin_utf32, cursor_end_utf32 - cursor_begin_utf32);3199}32003201void WaylandThread::_wp_text_input_on_commit_string(void *data, struct zwp_text_input_v3 *wp_text_input_v3, const char *text) {3202SeatState *ss = (SeatState *)data;3203if (!ss) {3204return;3205}32063207if (ss->ime_window_id == DisplayServer::INVALID_WINDOW_ID) {3208return;3209}32103211ss->ime_text_commit = String::utf8(text);3212}32133214void WaylandThread::_wp_text_input_on_delete_surrounding_text(void *data, struct zwp_text_input_v3 *wp_text_input_v3, uint32_t before_length, uint32_t after_length) {3215// Not implemented.3216}32173218void WaylandThread::_wp_text_input_on_done(void *data, struct zwp_text_input_v3 *wp_text_input_v3, uint32_t serial) {3219SeatState *ss = (SeatState *)data;3220if (!ss) {3221return;3222}32233224if (ss->ime_window_id == DisplayServer::INVALID_WINDOW_ID) {3225return;3226}32273228if (!ss->ime_text_commit.is_empty()) {3229Ref<IMECommitEventMessage> msg;3230msg.instantiate();3231msg->id = ss->ime_window_id;3232msg->text = ss->ime_text_commit;3233ss->wayland_thread->push_message(msg);3234} else {3235Ref<IMEUpdateEventMessage> msg;3236msg.instantiate();3237msg->id = ss->ime_window_id;3238msg->text = ss->ime_text;3239msg->selection = ss->ime_cursor;3240ss->wayland_thread->push_message(msg);3241}32423243ss->ime_text = String();3244ss->ime_text_commit = String();3245ss->ime_cursor = Vector2i();3246}32473248void WaylandThread::_xdg_activation_token_on_done(void *data, struct xdg_activation_token_v1 *xdg_activation_token, const char *token) {3249WindowState *ws = (WindowState *)data;3250ERR_FAIL_NULL(ws);3251ERR_FAIL_NULL(ws->wayland_thread);3252ERR_FAIL_NULL(ws->wl_surface);32533254xdg_activation_v1_activate(ws->wayland_thread->registry.xdg_activation, token, ws->wl_surface);3255xdg_activation_token_v1_destroy(xdg_activation_token);32563257DEBUG_LOG_WAYLAND_THREAD(vformat("Received activation token and requested window activation."));3258}32593260void WaylandThread::_godot_embedding_compositor_on_client(void *data, struct godot_embedding_compositor *godot_embedding_compositor, struct godot_embedded_client *godot_embedded_client, int32_t pid) {3261EmbeddingCompositorState *state = (EmbeddingCompositorState *)data;3262ERR_FAIL_NULL(state);32633264EmbeddedClientState *client_state = memnew(EmbeddedClientState);3265client_state->embedding_compositor = godot_embedding_compositor;3266client_state->pid = pid;3267godot_embedded_client_add_listener(godot_embedded_client, &godot_embedded_client_listener, client_state);32683269DEBUG_LOG_WAYLAND_THREAD(vformat("New client %d.", pid));3270state->clients.push_back(godot_embedded_client);3271}32723273void WaylandThread::_godot_embedded_client_on_disconnected(void *data, struct godot_embedded_client *godot_embedded_client) {3274EmbeddedClientState *state = (EmbeddedClientState *)data;3275ERR_FAIL_NULL(state);32763277EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);3278ERR_FAIL_NULL(ecomp_state);32793280ecomp_state->clients.erase_unordered(godot_embedded_client);3281ecomp_state->mapped_clients.erase(state->pid);32823283memfree(state);3284godot_embedded_client_destroy(godot_embedded_client);32853286DEBUG_LOG_WAYLAND_THREAD(vformat("Client %d disconnected.", state->pid));3287}32883289void WaylandThread::_godot_embedded_client_on_window_embedded(void *data, struct godot_embedded_client *godot_embedded_client) {3290EmbeddedClientState *state = (EmbeddedClientState *)data;3291ERR_FAIL_NULL(state);32923293EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);3294ERR_FAIL_NULL(ecomp_state);32953296state->window_mapped = true;32973298ERR_FAIL_COND_MSG(ecomp_state->mapped_clients.has(state->pid), "More than one Wayland client per PID tried to create a window.");32993300ecomp_state->mapped_clients[state->pid] = godot_embedded_client;3301}33023303void WaylandThread::_godot_embedded_client_on_window_focus_in(void *data, struct godot_embedded_client *godot_embedded_client) {3304EmbeddedClientState *state = (EmbeddedClientState *)data;3305ERR_FAIL_NULL(state);33063307EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);3308ERR_FAIL_NULL(ecomp_state);33093310ecomp_state->focused_pid = state->pid;3311DEBUG_LOG_WAYLAND_THREAD(vformat("Embedded client pid %d focus in", state->pid));3312}33133314void WaylandThread::_godot_embedded_client_on_window_focus_out(void *data, struct godot_embedded_client *godot_embedded_client) {3315EmbeddedClientState *state = (EmbeddedClientState *)data;3316ERR_FAIL_NULL(state);33173318EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);3319ERR_FAIL_NULL(ecomp_state);33203321ecomp_state->focused_pid = -1;3322DEBUG_LOG_WAYLAND_THREAD(vformat("Embedded client pid %d focus out", state->pid));3323}33243325// NOTE: This must be started after a valid wl_display is loaded.3326void WaylandThread::_poll_events_thread(void *p_data) {3327Thread::set_name("Wayland Events");33283329ThreadData *data = (ThreadData *)p_data;3330ERR_FAIL_NULL(data);3331ERR_FAIL_NULL(data->wl_display);33323333struct pollfd poll_fd = {};3334poll_fd.fd = wl_display_get_fd(data->wl_display);3335poll_fd.events = POLLIN;33363337while (true) {3338// Empty the event queue while it's full.3339while (wl_display_prepare_read(data->wl_display) != 0) {3340// We aren't using wl_display_dispatch(), instead "manually" handling events3341// through wl_display_dispatch_pending so that we can use a global mutex and3342// be sure that this and the main thread won't race over stuff, as long as3343// the main thread locks it too.3344//3345// Note that the main thread can still call wl_display_roundtrip as that3346// method directly handles all events, effectively bypassing this polling3347// loop and thus the mutex locking, avoiding a deadlock.3348//3349// WARNING: Never call `wl_display_roundtrip` inside event handlers or while3350// this mutex isn't held! `wl_display_roundtrip` manually handles new events3351// and if not properly gated it _will_ cause potentially stall-inducing race3352// conditions. Ask me how I know.3353MutexLock mutex_lock(data->mutex);33543355if (wl_display_dispatch_pending(data->wl_display) == -1) {3356// Oh no. We'll check and handle any display error below.3357break;3358}3359}33603361int werror = wl_display_get_error(data->wl_display);33623363if (werror) {3364if (werror == EPROTO) {3365struct wl_interface *wl_interface = nullptr;3366uint32_t id = 0;33673368int error_code = wl_display_get_protocol_error(data->wl_display, (const struct wl_interface **)&wl_interface, &id);3369CRASH_NOW_MSG(vformat("Wayland protocol error %d on interface %s@%d.", error_code, wl_interface ? wl_interface->name : "unknown", id));3370} else {3371CRASH_NOW_MSG(vformat("Wayland client error code %d.", werror));3372}3373}33743375wl_display_flush(data->wl_display);33763377// Wait for the event file descriptor to have new data.3378poll(&poll_fd, 1, -1);33793380if (data->thread_done.is_set()) {3381wl_display_cancel_read(data->wl_display);3382break;3383}33843385if (poll_fd.revents | POLLIN) {3386// Load the queues with fresh new data.3387wl_display_read_events(data->wl_display);3388} else {3389// Oh well... Stop signaling that we want to read.3390wl_display_cancel_read(data->wl_display);3391}33923393// The docs advise to redispatch unconditionally and it looks like that if we3394// don't do this we can't catch protocol errors, which is bad.3395MutexLock mutex_lock(data->mutex);3396wl_display_dispatch_pending(data->wl_display);3397}3398}33993400struct wl_display *WaylandThread::get_wl_display() const {3401return wl_display;3402}34033404// NOTE: Stuff like libdecor can (and will) register foreign proxies which3405// aren't formatted as we like. This method is needed to detect whether a proxy3406// has our tag. Also, be careful! The proxy has to be manually tagged or it3407// won't be recognized.3408bool WaylandThread::wl_proxy_is_godot(struct wl_proxy *p_proxy) {3409ERR_FAIL_NULL_V(p_proxy, false);34103411return wl_proxy_get_tag(p_proxy) == &proxy_tag;3412}34133414void WaylandThread::wl_proxy_tag_godot(struct wl_proxy *p_proxy) {3415ERR_FAIL_NULL(p_proxy);34163417wl_proxy_set_tag(p_proxy, &proxy_tag);3418}34193420// Returns the wl_surface's `WindowState`, otherwise `nullptr`.3421// NOTE: This will fail if the surface isn't tagged as ours.3422WaylandThread::WindowState *WaylandThread::wl_surface_get_window_state(struct wl_surface *p_surface) {3423if (p_surface && wl_proxy_is_godot((wl_proxy *)p_surface)) {3424return (WindowState *)wl_surface_get_user_data(p_surface);3425}34263427return nullptr;3428}34293430// Returns the wl_outputs's `ScreenState`, otherwise `nullptr`.3431// NOTE: This will fail if the output isn't tagged as ours.3432WaylandThread::ScreenState *WaylandThread::wl_output_get_screen_state(struct wl_output *p_output) {3433if (p_output && wl_proxy_is_godot((wl_proxy *)p_output)) {3434return (ScreenState *)wl_output_get_user_data(p_output);3435}34363437return nullptr;3438}34393440// Returns the wl_seat's `SeatState`, otherwise `nullptr`.3441// NOTE: This will fail if the output isn't tagged as ours.3442WaylandThread::SeatState *WaylandThread::wl_seat_get_seat_state(struct wl_seat *p_seat) {3443if (p_seat && wl_proxy_is_godot((wl_proxy *)p_seat)) {3444return (SeatState *)wl_seat_get_user_data(p_seat);3445}34463447return nullptr;3448}34493450// Returns the wp_tablet_tool's `TabletToolState`, otherwise `nullptr`.3451// NOTE: This will fail if the output isn't tagged as ours.3452WaylandThread::TabletToolState *WaylandThread::wp_tablet_tool_get_state(struct zwp_tablet_tool_v2 *p_tool) {3453if (p_tool && wl_proxy_is_godot((wl_proxy *)p_tool)) {3454return (TabletToolState *)zwp_tablet_tool_v2_get_user_data(p_tool);3455}34563457return nullptr;3458}3459// Returns the wl_data_offer's `OfferState`, otherwise `nullptr`.3460// NOTE: This will fail if the output isn't tagged as ours.3461WaylandThread::OfferState *WaylandThread::wl_data_offer_get_offer_state(struct wl_data_offer *p_offer) {3462if (p_offer && wl_proxy_is_godot((wl_proxy *)p_offer)) {3463return (OfferState *)wl_data_offer_get_user_data(p_offer);3464}34653466return nullptr;3467}34683469// Returns the wl_data_offer's `OfferState`, otherwise `nullptr`.3470// NOTE: This will fail if the output isn't tagged as ours.3471WaylandThread::OfferState *WaylandThread::wp_primary_selection_offer_get_offer_state(struct zwp_primary_selection_offer_v1 *p_offer) {3472if (p_offer && wl_proxy_is_godot((wl_proxy *)p_offer)) {3473return (OfferState *)zwp_primary_selection_offer_v1_get_user_data(p_offer);3474}34753476return nullptr;3477}34783479WaylandThread::EmbeddingCompositorState *WaylandThread::godot_embedding_compositor_get_state(struct godot_embedding_compositor *p_compositor) {3480// NOTE: No need for tag check as it's a "fake" interface - nothing else exposes it.3481if (p_compositor) {3482return (EmbeddingCompositorState *)godot_embedding_compositor_get_user_data(p_compositor);3483}34843485return nullptr;3486}34873488// This is implemented as a method because this is the simplest way of3489// accounting for dynamic output scale changes.3490int WaylandThread::window_state_get_preferred_buffer_scale(WindowState *p_ws) {3491ERR_FAIL_NULL_V(p_ws, 1);34923493if (p_ws->preferred_fractional_scale > 0) {3494// We're scaling fractionally. Per spec, the buffer scale is always 1.3495return 1;3496}34973498if (p_ws->wl_outputs.is_empty()) {3499DEBUG_LOG_WAYLAND_THREAD("Window has no output associated, returning buffer scale of 1.");3500return 1;3501}35023503// TODO: Cache value?3504int max_size = 1;35053506// ================================ IMPORTANT =================================3507// NOTE: Due to a Godot limitation, we can't really rescale the whole UI yet.3508// Because of this reason, all platforms have resorted to forcing the highest3509// scale possible of a system on any window, despite of what screen it's onto.3510// On this backend everything's already in place for dynamic window scale3511// handling, but in the meantime we'll just select the biggest _global_ output.3512// To restore dynamic scale selection, simply iterate over `p_ws->wl_outputs`3513// instead.3514for (struct wl_output *wl_output : p_ws->registry->wl_outputs) {3515ScreenState *ss = wl_output_get_screen_state(wl_output);35163517if (ss && ss->pending_data.scale > max_size) {3518// NOTE: For some mystical reason, wl_output.done is emitted _after_ windows3519// get resized but the scale event gets sent _before_ that. I'm still leaning3520// towards the idea that rescaling when a window gets a resolution change is a3521// pretty good approach, but this means that we'll have to use the screen data3522// before it's "committed".3523// FIXME: Use the committed data. Somehow.3524max_size = ss->pending_data.scale;3525}3526}35273528return max_size;3529}35303531double WaylandThread::window_state_get_scale_factor(const WindowState *p_ws) {3532ERR_FAIL_NULL_V(p_ws, 1);35333534if (p_ws->fractional_scale > 0) {3535// The fractional scale amount takes priority.3536return p_ws->fractional_scale;3537}35383539return p_ws->buffer_scale;3540}35413542void WaylandThread::window_state_update_size(WindowState *p_ws, int p_width, int p_height) {3543ERR_FAIL_NULL(p_ws);35443545int preferred_buffer_scale = window_state_get_preferred_buffer_scale(p_ws);3546bool using_fractional = p_ws->preferred_fractional_scale > 0;35473548// If neither is true we no-op.3549bool scale_changed = false;3550bool size_changed = false;35513552if (p_ws->rect.size.width != p_width || p_ws->rect.size.height != p_height) {3553p_ws->rect.size.width = p_width;3554p_ws->rect.size.height = p_height;35553556size_changed = true;3557}35583559if (using_fractional && p_ws->fractional_scale != p_ws->preferred_fractional_scale) {3560p_ws->fractional_scale = p_ws->preferred_fractional_scale;3561scale_changed = true;3562}35633564if (p_ws->buffer_scale != preferred_buffer_scale) {3565// The buffer scale is always important, even if we use frac scaling.3566p_ws->buffer_scale = preferred_buffer_scale;3567p_ws->buffer_scale_changed = true;35683569if (!using_fractional) {3570// We don't bother updating everything else if it's turned on though.3571scale_changed = true;3572}3573}35743575if (p_ws->wl_surface) {3576if (p_ws->wp_viewport) {3577wp_viewport_set_destination(p_ws->wp_viewport, p_width, p_height);3578}35793580if (p_ws->xdg_surface) {3581xdg_surface_set_window_geometry(p_ws->xdg_surface, 0, 0, p_width, p_height);3582}3583}35843585#ifdef LIBDECOR_ENABLED3586if (p_ws->libdecor_frame) {3587struct libdecor_state *state = libdecor_state_new(p_width, p_height);3588libdecor_frame_commit(p_ws->libdecor_frame, state, p_ws->pending_libdecor_configuration);3589libdecor_state_free(state);3590p_ws->pending_libdecor_configuration = nullptr;3591}3592#endif35933594if (size_changed || scale_changed) {3595double win_scale = window_state_get_scale_factor(p_ws);3596Size2i scaled_size = scale_vector2i(p_ws->rect.size, win_scale);35973598if (using_fractional) {3599DEBUG_LOG_WAYLAND_THREAD(vformat("Resizing the window from %s to %s (fractional scale x%f).", p_ws->rect.size, scaled_size, p_ws->fractional_scale));3600} else {3601DEBUG_LOG_WAYLAND_THREAD(vformat("Resizing the window from %s to %s (buffer scale x%d).", p_ws->rect.size, scaled_size, p_ws->buffer_scale));3602}36033604// FIXME: Actually resize the hint instead of centering it.3605p_ws->wayland_thread->pointer_set_hint(scaled_size / 2);36063607Ref<WindowRectMessage> rect_msg;3608rect_msg.instantiate();3609rect_msg->id = p_ws->id;3610rect_msg->rect.position = scale_vector2i(p_ws->rect.position, win_scale);3611rect_msg->rect.size = scaled_size;3612p_ws->wayland_thread->push_message(rect_msg);3613}36143615if (scale_changed) {3616Ref<WindowEventMessage> dpi_msg;3617dpi_msg.instantiate();3618dpi_msg->id = p_ws->id;3619dpi_msg->event = DisplayServer::WINDOW_EVENT_DPI_CHANGE;3620p_ws->wayland_thread->push_message(dpi_msg);3621}3622}36233624// Scales a vector according to wp_fractional_scale's rules, where coordinates3625// must be scaled with away from zero half-rounding.3626Vector2i WaylandThread::scale_vector2i(const Vector2i &p_vector, double p_amount) {3627// This snippet is tiny, I know, but this is done a lot.3628int x = std::round(p_vector.x * p_amount);3629int y = std::round(p_vector.y * p_amount);36303631return Vector2i(x, y);3632}36333634void WaylandThread::seat_state_unlock_pointer(SeatState *p_ss) {3635ERR_FAIL_NULL(p_ss);36363637if (p_ss->wl_pointer == nullptr) {3638return;3639}36403641if (p_ss->wp_locked_pointer) {3642zwp_locked_pointer_v1_destroy(p_ss->wp_locked_pointer);3643p_ss->wp_locked_pointer = nullptr;3644}36453646if (p_ss->wp_confined_pointer) {3647zwp_confined_pointer_v1_destroy(p_ss->wp_confined_pointer);3648p_ss->wp_confined_pointer = nullptr;3649}3650}36513652void WaylandThread::seat_state_lock_pointer(SeatState *p_ss) {3653ERR_FAIL_NULL(p_ss);36543655if (p_ss->wl_pointer == nullptr) {3656WARN_PRINT("Can't lock - no pointer?");3657return;3658}36593660if (registry.wp_pointer_constraints == nullptr) {3661WARN_PRINT("Can't lock - no constraints global.");3662return;3663}36643665if (p_ss->wp_locked_pointer == nullptr) {3666struct wl_surface *locked_surface = window_get_wl_surface(p_ss->pointer_data.last_pointed_id);3667if (locked_surface == nullptr) {3668locked_surface = window_get_wl_surface(DisplayServer::MAIN_WINDOW_ID);3669}3670ERR_FAIL_NULL(locked_surface);36713672p_ss->wp_locked_pointer = zwp_pointer_constraints_v1_lock_pointer(registry.wp_pointer_constraints, locked_surface, p_ss->wl_pointer, nullptr, ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);3673}3674}36753676void WaylandThread::seat_state_set_hint(SeatState *p_ss, int p_x, int p_y) {3677if (p_ss->wp_locked_pointer == nullptr) {3678return;3679}36803681zwp_locked_pointer_v1_set_cursor_position_hint(p_ss->wp_locked_pointer, wl_fixed_from_int(p_x), wl_fixed_from_int(p_y));3682}36833684void WaylandThread::seat_state_warp_pointer(SeatState *p_ss, int p_x, int p_y) {3685if (registry.wp_pointer_warp == nullptr) {3686return;3687}36883689if (p_ss->pointer_data.pointed_id == DisplayServer::INVALID_WINDOW_ID) {3690return;3691}36923693struct wl_surface *surface = window_get_wl_surface(p_ss->pointer_data.pointed_id);3694ERR_FAIL_NULL(surface);36953696wp_pointer_warp_v1_warp_pointer(registry.wp_pointer_warp, surface, p_ss->wl_pointer, wl_fixed_from_int(p_x), wl_fixed_from_int(p_y), p_ss->pointer_enter_serial);3697}36983699void WaylandThread::seat_state_confine_pointer(SeatState *p_ss) {3700ERR_FAIL_NULL(p_ss);37013702if (p_ss->wl_pointer == nullptr) {3703return;3704}37053706if (registry.wp_pointer_constraints == nullptr) {3707return;3708}37093710if (p_ss->wp_confined_pointer == nullptr) {3711struct wl_surface *confined_surface = window_get_wl_surface(p_ss->pointer_data.last_pointed_id);3712ERR_FAIL_NULL(confined_surface);37133714p_ss->wp_confined_pointer = zwp_pointer_constraints_v1_confine_pointer(registry.wp_pointer_constraints, confined_surface, p_ss->wl_pointer, nullptr, ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);3715}3716}37173718void WaylandThread::seat_state_update_cursor(SeatState *p_ss) {3719ERR_FAIL_NULL(p_ss);37203721WaylandThread *thread = p_ss->wayland_thread;3722ERR_FAIL_NULL(p_ss->wayland_thread);37233724if (!p_ss->wl_pointer || !p_ss->cursor_surface) {3725return;3726}37273728// NOTE: Those values are valid by default and will hide the cursor when3729// unchanged.3730struct wl_buffer *cursor_buffer = nullptr;3731uint32_t hotspot_x = 0;3732uint32_t hotspot_y = 0;3733int scale = 1;37343735if (thread->cursor_visible) {3736DisplayServer::CursorShape shape = thread->cursor_shape;37373738struct CustomCursor *custom_cursor = thread->custom_cursors.getptr(shape);37393740if (custom_cursor) {3741cursor_buffer = custom_cursor->wl_buffer;3742hotspot_x = custom_cursor->hotspot.x;3743hotspot_y = custom_cursor->hotspot.y;37443745// We can't really reasonably scale custom cursors, so we'll let the3746// compositor do it for us (badly).3747scale = 1;3748} else if (thread->registry.wp_cursor_shape_manager) {3749wp_cursor_shape_device_v1_shape wp_shape = thread->standard_cursors[shape];3750wp_cursor_shape_device_v1_set_shape(p_ss->wp_cursor_shape_device, p_ss->pointer_enter_serial, wp_shape);37513752// We should avoid calling the `wl_pointer_set_cursor` at the end of this method.3753return;3754} else {3755struct wl_cursor *wl_cursor = thread->wl_cursors[shape];37563757if (!wl_cursor) {3758return;3759}37603761int frame_idx = 0;37623763if (wl_cursor->image_count > 1) {3764// The cursor is animated.3765frame_idx = wl_cursor_frame(wl_cursor, p_ss->cursor_time_ms);37663767if (!p_ss->cursor_frame_callback) {3768// Since it's animated, we'll re-update it the next frame.3769p_ss->cursor_frame_callback = wl_surface_frame(p_ss->cursor_surface);3770wl_callback_add_listener(p_ss->cursor_frame_callback, &cursor_frame_callback_listener, p_ss);3771}3772}37733774struct wl_cursor_image *wl_cursor_image = wl_cursor->images[frame_idx];37753776scale = thread->cursor_scale;37773778cursor_buffer = wl_cursor_image_get_buffer(wl_cursor_image);37793780// As the surface's buffer is scaled (thus the surface is smaller) and the3781// hotspot must be expressed in surface-local coordinates, we need to scale3782// it down accordingly.3783hotspot_x = wl_cursor_image->hotspot_x / scale;3784hotspot_y = wl_cursor_image->hotspot_y / scale;3785}3786}37873788wl_pointer_set_cursor(p_ss->wl_pointer, p_ss->pointer_enter_serial, p_ss->cursor_surface, hotspot_x, hotspot_y);3789wl_surface_set_buffer_scale(p_ss->cursor_surface, scale);3790wl_surface_attach(p_ss->cursor_surface, cursor_buffer, 0, 0);3791wl_surface_damage_buffer(p_ss->cursor_surface, 0, 0, INT_MAX, INT_MAX);37923793wl_surface_commit(p_ss->cursor_surface);3794}37953796void WaylandThread::seat_state_echo_keys(SeatState *p_ss) {3797ERR_FAIL_NULL(p_ss);37983799if (p_ss->wl_keyboard == nullptr) {3800return;3801}38023803// TODO: Comment and document out properly this block of code.3804// In short, this implements key repeating.3805if (p_ss->repeat_key_delay_msec && p_ss->repeating_keycode != XKB_KEYCODE_INVALID) {3806uint64_t current_ticks = OS::get_singleton()->get_ticks_msec();3807uint64_t delayed_start_ticks = p_ss->last_repeat_start_msec + p_ss->repeat_start_delay_msec;38083809if (p_ss->last_repeat_msec < delayed_start_ticks) {3810p_ss->last_repeat_msec = delayed_start_ticks;3811}38123813if (current_ticks >= delayed_start_ticks) {3814uint64_t ticks_delta = current_ticks - p_ss->last_repeat_msec;38153816int keys_amount = (ticks_delta / p_ss->repeat_key_delay_msec);38173818for (int i = 0; i < keys_amount; i++) {3819_seat_state_handle_xkb_keycode(p_ss, p_ss->repeating_keycode, true, true);3820}38213822p_ss->last_repeat_msec += ticks_delta - (ticks_delta % p_ss->repeat_key_delay_msec);3823}3824}3825}38263827void WaylandThread::push_message(Ref<Message> message) {3828messages.push_back(message);3829}38303831bool WaylandThread::has_message() {3832return messages.front() != nullptr;3833}38343835Ref<WaylandThread::Message> WaylandThread::pop_message() {3836if (messages.front() != nullptr) {3837Ref<Message> msg = messages.front()->get();3838messages.pop_front();3839return msg;3840}38413842// This method should only be called if `has_messages` returns true but if3843// that isn't the case we'll just return an invalid `Ref`. After all, due to3844// its `InputEvent`-like interface, we still have to dynamically cast and check3845// the `Ref`'s validity anyways.3846return Ref<Message>();3847}38483849void WaylandThread::window_create(DisplayServer::WindowID p_window_id, const Size2i &p_size, DisplayServer::WindowID p_parent_id) {3850ERR_FAIL_COND(windows.has(p_window_id));3851WindowState &ws = windows[p_window_id];38523853ws.id = p_window_id;38543855ws.registry = ®istry;3856ws.wayland_thread = this;38573858ws.rect.size = p_size;38593860ws.wl_surface = wl_compositor_create_surface(registry.wl_compositor);3861wl_proxy_tag_godot((struct wl_proxy *)ws.wl_surface);3862wl_surface_add_listener(ws.wl_surface, &wl_surface_listener, &ws);38633864if (registry.wp_viewporter) {3865ws.wp_viewport = wp_viewporter_get_viewport(registry.wp_viewporter, ws.wl_surface);38663867if (registry.wp_fractional_scale_manager) {3868ws.wp_fractional_scale = wp_fractional_scale_manager_v1_get_fractional_scale(registry.wp_fractional_scale_manager, ws.wl_surface);3869wp_fractional_scale_v1_add_listener(ws.wp_fractional_scale, &wp_fractional_scale_listener, &ws);3870}3871}38723873bool decorated = false;38743875#ifdef LIBDECOR_ENABLED3876if (!decorated && libdecor_context) {3877ws.libdecor_frame = libdecor_decorate(libdecor_context, ws.wl_surface, (struct libdecor_frame_interface *)&libdecor_frame_interface, &ws);3878libdecor_frame_map(ws.libdecor_frame);38793880if (registry.xdg_toplevel_icon_manager) {3881xdg_toplevel *toplevel = libdecor_frame_get_xdg_toplevel(ws.libdecor_frame);3882if (toplevel != nullptr) {3883xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, toplevel, xdg_icon);3884}3885}38863887decorated = true;3888}3889#endif38903891if (!decorated) {3892// libdecor has failed loading or is disabled, we shall handle xdg_toplevel3893// creation and decoration ourselves (and by decorating for now I just mean3894// asking for SSDs and hoping for the best).3895ws.xdg_surface = xdg_wm_base_get_xdg_surface(registry.xdg_wm_base, ws.wl_surface);3896xdg_surface_add_listener(ws.xdg_surface, &xdg_surface_listener, &ws);38973898ws.xdg_toplevel = xdg_surface_get_toplevel(ws.xdg_surface);3899xdg_toplevel_add_listener(ws.xdg_toplevel, &xdg_toplevel_listener, &ws);39003901if (registry.xdg_decoration_manager) {3902ws.xdg_toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(registry.xdg_decoration_manager, ws.xdg_toplevel);3903zxdg_toplevel_decoration_v1_add_listener(ws.xdg_toplevel_decoration, &xdg_toplevel_decoration_listener, &ws);39043905decorated = true;3906}39073908if (registry.xdg_toplevel_icon_manager) {3909xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, ws.xdg_toplevel, xdg_icon);3910}3911}39123913if (p_parent_id != DisplayServer::INVALID_WINDOW_ID) {3914// NOTE: It's important to set the parent ASAP to avoid misunderstandings with3915// the compositor. For example, niri immediately resizes the window to full3916// size as soon as it's configured if it's not parented to another toplevel.3917window_set_parent(p_window_id, p_parent_id);3918}39193920ws.frame_callback = wl_surface_frame(ws.wl_surface);3921wl_callback_add_listener(ws.frame_callback, &frame_wl_callback_listener, &ws);39223923if (registry.xdg_exporter_v2) {3924ws.xdg_exported_v2 = zxdg_exporter_v2_export_toplevel(registry.xdg_exporter_v2, ws.wl_surface);3925zxdg_exported_v2_add_listener(ws.xdg_exported_v2, &xdg_exported_v2_listener, &ws);3926} else if (registry.xdg_exporter_v1) {3927ws.xdg_exported_v1 = zxdg_exporter_v1_export(registry.xdg_exporter_v1, ws.wl_surface);3928zxdg_exported_v1_add_listener(ws.xdg_exported_v1, &xdg_exported_v1_listener, &ws);3929}39303931wl_surface_commit(ws.wl_surface);39323933// Wait for the surface to be configured before continuing.3934wl_display_roundtrip(wl_display);39353936window_state_update_size(&ws, ws.rect.size.width, ws.rect.size.height);3937}39383939void WaylandThread::window_create_popup(DisplayServer::WindowID p_window_id, DisplayServer::WindowID p_parent_id, Rect2i p_rect) {3940ERR_FAIL_COND(windows.has(p_window_id));3941ERR_FAIL_COND(!windows.has(p_parent_id));39423943WindowState &ws = windows[p_window_id];3944WindowState &parent = windows[p_parent_id];39453946double parent_scale = window_state_get_scale_factor(&parent);39473948p_rect.position = scale_vector2i(p_rect.position, 1.0 / parent_scale);3949p_rect.size = scale_vector2i(p_rect.size, 1.0 / parent_scale);39503951// We manually scaled based on the parent. If we don't set the relevant fields,3952// the resizing routines will get confused and scale once more.3953ws.preferred_fractional_scale = parent.preferred_fractional_scale;3954ws.fractional_scale = parent.fractional_scale;3955ws.buffer_scale = parent.buffer_scale;39563957ws.id = p_window_id;3958ws.parent_id = p_parent_id;3959ws.registry = ®istry;3960ws.wayland_thread = this;39613962ws.rect = p_rect;39633964ws.wl_surface = wl_compositor_create_surface(registry.wl_compositor);3965wl_proxy_tag_godot((struct wl_proxy *)ws.wl_surface);3966wl_surface_add_listener(ws.wl_surface, &wl_surface_listener, &ws);39673968if (registry.wp_viewporter) {3969ws.wp_viewport = wp_viewporter_get_viewport(registry.wp_viewporter, ws.wl_surface);39703971if (registry.wp_fractional_scale_manager) {3972ws.wp_fractional_scale = wp_fractional_scale_manager_v1_get_fractional_scale(registry.wp_fractional_scale_manager, ws.wl_surface);3973wp_fractional_scale_v1_add_listener(ws.wp_fractional_scale, &wp_fractional_scale_listener, &ws);3974}3975}39763977ws.xdg_surface = xdg_wm_base_get_xdg_surface(registry.xdg_wm_base, ws.wl_surface);3978xdg_surface_add_listener(ws.xdg_surface, &xdg_surface_listener, &ws);39793980Rect2i positioner_rect;3981positioner_rect.size = parent.rect.size;3982struct xdg_surface *parent_xdg_surface = parent.xdg_surface;39833984Point2i offset = ws.rect.position - parent.rect.position;39853986#ifdef LIBDECOR_ENABLED3987if (!parent_xdg_surface && parent.libdecor_frame) {3988parent_xdg_surface = libdecor_frame_get_xdg_surface(parent.libdecor_frame);39893990int corner_x = 0;3991int corner_y = 0;3992libdecor_frame_translate_coordinate(parent.libdecor_frame, 0, 0, &corner_x, &corner_y);39933994positioner_rect.position.x = corner_x;3995positioner_rect.position.y = corner_y;39963997positioner_rect.size.width -= corner_x;3998positioner_rect.size.height -= corner_y;3999}4000#endif40014002ERR_FAIL_NULL(parent_xdg_surface);40034004struct xdg_positioner *xdg_positioner = xdg_wm_base_create_positioner(registry.xdg_wm_base);4005xdg_positioner_set_size(xdg_positioner, ws.rect.size.width, ws.rect.size.height);4006xdg_positioner_set_anchor(xdg_positioner, XDG_POSITIONER_ANCHOR_TOP_LEFT);4007xdg_positioner_set_gravity(xdg_positioner, XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT);4008xdg_positioner_set_constraint_adjustment(xdg_positioner, XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X | XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y | XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_X | XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_Y);4009xdg_positioner_set_anchor_rect(xdg_positioner, positioner_rect.position.x, positioner_rect.position.y, positioner_rect.size.width, positioner_rect.size.height);4010xdg_positioner_set_offset(xdg_positioner, offset.x, offset.y);40114012ws.xdg_popup = xdg_surface_get_popup(ws.xdg_surface, parent_xdg_surface, xdg_positioner);4013xdg_popup_add_listener(ws.xdg_popup, &xdg_popup_listener, &ws);40144015xdg_positioner_destroy(xdg_positioner);40164017ws.frame_callback = wl_surface_frame(ws.wl_surface);4018wl_callback_add_listener(ws.frame_callback, &frame_wl_callback_listener, &ws);40194020wl_surface_commit(ws.wl_surface);40214022// Wait for the surface to be configured before continuing.4023wl_display_roundtrip(wl_display);4024}40254026void WaylandThread::window_destroy(DisplayServer::WindowID p_window_id) {4027ERR_FAIL_COND(!windows.has(p_window_id));4028WindowState &ws = windows[p_window_id];40294030if (ws.xdg_popup) {4031xdg_popup_destroy(ws.xdg_popup);4032}40334034if (ws.xdg_toplevel_decoration) {4035zxdg_toplevel_decoration_v1_destroy(ws.xdg_toplevel_decoration);4036}40374038if (ws.xdg_toplevel) {4039xdg_toplevel_destroy(ws.xdg_toplevel);4040}40414042#ifdef LIBDECOR_ENABLED4043if (ws.libdecor_frame) {4044libdecor_frame_unref(ws.libdecor_frame);4045}4046#endif // LIBDECOR_ENABLED40474048if (ws.wp_fractional_scale) {4049wp_fractional_scale_v1_destroy(ws.wp_fractional_scale);4050}40514052if (ws.wp_viewport) {4053wp_viewport_destroy(ws.wp_viewport);4054}40554056if (ws.frame_callback) {4057wl_callback_destroy(ws.frame_callback);4058}40594060if (ws.xdg_surface) {4061xdg_surface_destroy(ws.xdg_surface);4062}40634064if (ws.wl_surface) {4065wl_surface_destroy(ws.wl_surface);4066}40674068// Before continuing, let's handle any leftover event that might still refer to4069// this window.4070wl_display_roundtrip(wl_display);40714072// We can already clean up here, we're done.4073windows.erase(p_window_id);4074}40754076struct wl_surface *WaylandThread::window_get_wl_surface(DisplayServer::WindowID p_window_id) const {4077const WindowState *ws = windows.getptr(p_window_id);4078if (ws) {4079return ws->wl_surface;4080}40814082return nullptr;4083}40844085WaylandThread::WindowState *WaylandThread::window_get_state(DisplayServer::WindowID p_window_id) {4086return windows.getptr(p_window_id);4087}40884089const WaylandThread::WindowState *WaylandThread::window_get_state(DisplayServer::WindowID p_window_id) const {4090return windows.getptr(p_window_id);4091}40924093Size2i WaylandThread::window_set_size(DisplayServer::WindowID p_window_id, const Size2i &p_size) {4094ERR_FAIL_COND_V(!windows.has(p_window_id), p_size);4095WindowState &ws = windows[p_window_id];40964097double window_scale = window_state_get_scale_factor(&ws);40984099if (ws.maximized) {4100// Can't do anything.4101return scale_vector2i(ws.rect.size, window_scale);4102}41034104Size2i new_size = scale_vector2i(p_size, 1 / window_scale);41054106if (ws.tiled_left && ws.tiled_right) {4107// Tiled left and right, we shouldn't change from our current width or else4108// it'll look wonky.4109new_size.width = ws.rect.size.width;4110}41114112if (ws.tiled_top && ws.tiled_bottom) {4113// Tiled top and bottom. Same as above, but for the height.4114new_size.height = ws.rect.size.height;4115}41164117if (ws.resizing && ws.rect.size.width > 0 && ws.rect.size.height > 0) {4118// The spec says that we shall not resize further than the config size. We can4119// resize less than that though.4120new_size = new_size.min(ws.rect.size);4121}41224123// NOTE: Older versions of libdecor (~2022) do not have a way to get the max4124// content size. Let's also check for its pointer so that we can preserve4125// compatibility with older distros.4126if (ws.libdecor_frame && libdecor_frame_get_max_content_size) {4127int max_width = new_size.width;4128int max_height = new_size.height;41294130// NOTE: Max content size is dynamic on libdecor, as plugins can override it4131// to accommodate their decorations.4132libdecor_frame_get_max_content_size(ws.libdecor_frame, &max_width, &max_height);41334134if (max_width > 0 && max_height > 0) {4135new_size.width = MIN(new_size.width, max_width);4136new_size.height = MIN(new_size.height, max_height);4137}4138}41394140window_state_update_size(&ws, new_size.width, new_size.height);41414142return scale_vector2i(new_size, window_scale);4143}41444145void WaylandThread::beep() const {4146if (registry.xdg_system_bell) {4147xdg_system_bell_v1_ring(registry.xdg_system_bell, nullptr);4148}4149}41504151void WaylandThread::window_start_drag(DisplayServer::WindowID p_window_id) {4152ERR_FAIL_COND(!windows.has(p_window_id));4153WindowState &ws = windows[p_window_id];4154SeatState *ss = wl_seat_get_seat_state(wl_seat_current);41554156if (ss && ws.xdg_toplevel) {4157xdg_toplevel_move(ws.xdg_toplevel, ss->wl_seat, ss->pointer_data.button_serial);4158}41594160#ifdef LIBDECOR_ENABLED4161if (ws.libdecor_frame) {4162libdecor_frame_move(ws.libdecor_frame, ss->wl_seat, ss->pointer_data.button_serial);4163}4164#endif4165}41664167void WaylandThread::window_start_resize(DisplayServer::WindowResizeEdge p_edge, DisplayServer::WindowID p_window) {4168ERR_FAIL_COND(!windows.has(p_window));4169WindowState &ws = windows[p_window];4170SeatState *ss = wl_seat_get_seat_state(wl_seat_current);41714172if (ss && ws.xdg_toplevel) {4173xdg_toplevel_resize_edge edge = XDG_TOPLEVEL_RESIZE_EDGE_NONE;4174switch (p_edge) {4175case DisplayServer::WINDOW_EDGE_TOP_LEFT: {4176edge = XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT;4177} break;4178case DisplayServer::WINDOW_EDGE_TOP: {4179edge = XDG_TOPLEVEL_RESIZE_EDGE_TOP;4180} break;4181case DisplayServer::WINDOW_EDGE_TOP_RIGHT: {4182edge = XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT;4183} break;4184case DisplayServer::WINDOW_EDGE_LEFT: {4185edge = XDG_TOPLEVEL_RESIZE_EDGE_LEFT;4186} break;4187case DisplayServer::WINDOW_EDGE_RIGHT: {4188edge = XDG_TOPLEVEL_RESIZE_EDGE_RIGHT;4189} break;4190case DisplayServer::WINDOW_EDGE_BOTTOM_LEFT: {4191edge = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT;4192} break;4193case DisplayServer::WINDOW_EDGE_BOTTOM: {4194edge = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM;4195} break;4196case DisplayServer::WINDOW_EDGE_BOTTOM_RIGHT: {4197edge = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT;4198} break;4199default:4200break;4201}4202xdg_toplevel_resize(ws.xdg_toplevel, ss->wl_seat, ss->pointer_data.button_serial, edge);4203}42044205#ifdef LIBDECOR_ENABLED4206if (ws.libdecor_frame) {4207libdecor_resize_edge edge = LIBDECOR_RESIZE_EDGE_NONE;4208switch (p_edge) {4209case DisplayServer::WINDOW_EDGE_TOP_LEFT: {4210edge = LIBDECOR_RESIZE_EDGE_TOP_LEFT;4211} break;4212case DisplayServer::WINDOW_EDGE_TOP: {4213edge = LIBDECOR_RESIZE_EDGE_TOP;4214} break;4215case DisplayServer::WINDOW_EDGE_TOP_RIGHT: {4216edge = LIBDECOR_RESIZE_EDGE_TOP_RIGHT;4217} break;4218case DisplayServer::WINDOW_EDGE_LEFT: {4219edge = LIBDECOR_RESIZE_EDGE_LEFT;4220} break;4221case DisplayServer::WINDOW_EDGE_RIGHT: {4222edge = LIBDECOR_RESIZE_EDGE_RIGHT;4223} break;4224case DisplayServer::WINDOW_EDGE_BOTTOM_LEFT: {4225edge = LIBDECOR_RESIZE_EDGE_BOTTOM_LEFT;4226} break;4227case DisplayServer::WINDOW_EDGE_BOTTOM: {4228edge = LIBDECOR_RESIZE_EDGE_BOTTOM;4229} break;4230case DisplayServer::WINDOW_EDGE_BOTTOM_RIGHT: {4231edge = LIBDECOR_RESIZE_EDGE_BOTTOM_RIGHT;4232} break;4233default:4234break;4235}4236libdecor_frame_resize(ws.libdecor_frame, ss->wl_seat, ss->pointer_data.button_serial, edge);4237}4238#endif4239}42404241void WaylandThread::window_set_parent(DisplayServer::WindowID p_window_id, DisplayServer::WindowID p_parent_id) {4242ERR_FAIL_COND(!windows.has(p_window_id));4243ERR_FAIL_COND(!windows.has(p_parent_id));42444245WindowState &child = windows[p_window_id];4246child.parent_id = p_parent_id;42474248WindowState &parent = windows[p_parent_id];42494250// NOTE: We can't really unparent as, at the time of writing, libdecor4251// segfaults when trying to set a null parent. Hopefully unparenting is not4252// that common. Bummer.42534254#ifdef LIBDECOR_ENABLED4255if (child.libdecor_frame && parent.libdecor_frame) {4256libdecor_frame_set_parent(child.libdecor_frame, parent.libdecor_frame);4257return;4258}4259#endif42604261if (child.xdg_toplevel && parent.xdg_toplevel) {4262xdg_toplevel_set_parent(child.xdg_toplevel, parent.xdg_toplevel);4263}4264}42654266void WaylandThread::window_set_max_size(DisplayServer::WindowID p_window_id, const Size2i &p_size) {4267ERR_FAIL_COND(!windows.has(p_window_id));4268WindowState &ws = windows[p_window_id];42694270Vector2i logical_max_size = scale_vector2i(p_size, 1 / window_state_get_scale_factor(&ws));42714272if (ws.wl_surface && ws.xdg_toplevel) {4273xdg_toplevel_set_max_size(ws.xdg_toplevel, logical_max_size.width, logical_max_size.height);4274}42754276#ifdef LIBDECOR_ENABLED4277if (ws.libdecor_frame) {4278libdecor_frame_set_max_content_size(ws.libdecor_frame, logical_max_size.width, logical_max_size.height);4279}42804281// FIXME: I'm not sure whether we have to commit the surface for this to apply.4282#endif4283}42844285void WaylandThread::window_set_min_size(DisplayServer::WindowID p_window_id, const Size2i &p_size) {4286ERR_FAIL_COND(!windows.has(p_window_id));4287WindowState &ws = windows[p_window_id];42884289Size2i logical_min_size = scale_vector2i(p_size, 1 / window_state_get_scale_factor(&ws));42904291if (ws.wl_surface && ws.xdg_toplevel) {4292xdg_toplevel_set_min_size(ws.xdg_toplevel, logical_min_size.width, logical_min_size.height);4293}42944295#ifdef LIBDECOR_ENABLED4296if (ws.libdecor_frame) {4297libdecor_frame_set_min_content_size(ws.libdecor_frame, logical_min_size.width, logical_min_size.height);4298}42994300// FIXME: I'm not sure whether we have to commit the surface for this to apply.4301#endif4302}43034304bool WaylandThread::window_can_set_mode(DisplayServer::WindowID p_window_id, DisplayServer::WindowMode p_window_mode) const {4305ERR_FAIL_COND_V(!windows.has(p_window_id), false);4306const WindowState &ws = windows[p_window_id];43074308switch (p_window_mode) {4309case DisplayServer::WINDOW_MODE_WINDOWED: {4310// Looks like it's guaranteed.4311return true;4312};43134314case DisplayServer::WINDOW_MODE_MINIMIZED: {4315#ifdef LIBDECOR_ENABLED4316if (ws.libdecor_frame) {4317return libdecor_frame_has_capability(ws.libdecor_frame, LIBDECOR_ACTION_MINIMIZE);4318}4319#endif // LIBDECOR_ENABLED43204321return ws.can_minimize;4322};43234324case DisplayServer::WINDOW_MODE_MAXIMIZED: {4325if (ws.libdecor_frame) {4326// NOTE: libdecor doesn't seem to have a maximize capability query?4327// The fact that there's a fullscreen one makes me suspicious. Anyways,4328// let's act as if we always can.4329return true;4330}4331return ws.can_maximize;4332};43334334case DisplayServer::WINDOW_MODE_FULLSCREEN:4335case DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN: {4336#ifdef LIBDECOR_ENABLED4337if (ws.libdecor_frame) {4338return libdecor_frame_has_capability(ws.libdecor_frame, LIBDECOR_ACTION_FULLSCREEN);4339}4340#endif // LIBDECOR_ENABLED43414342return ws.can_fullscreen;4343};4344}43454346return false;4347}43484349void WaylandThread::window_try_set_mode(DisplayServer::WindowID p_window_id, DisplayServer::WindowMode p_window_mode) {4350ERR_FAIL_COND(!windows.has(p_window_id));4351WindowState &ws = windows[p_window_id];43524353if (ws.mode == p_window_mode) {4354return;4355}43564357// Don't waste time with hidden windows and whatnot. Behave like it worked.4358#ifdef LIBDECOR_ENABLED4359if ((!ws.wl_surface || !ws.xdg_toplevel) && !ws.libdecor_frame) {4360#else4361if (!ws.wl_surface || !ws.xdg_toplevel) {4362#endif // LIBDECOR_ENABLED4363ws.mode = p_window_mode;4364return;4365}43664367// Return back to a windowed state so that we can apply what the user asked.4368switch (ws.mode) {4369case DisplayServer::WINDOW_MODE_WINDOWED: {4370// Do nothing.4371} break;43724373case DisplayServer::WINDOW_MODE_MINIMIZED: {4374// We can't do much according to the xdg_shell protocol. I have no idea4375// whether this implies that we should return or who knows what. For now4376// we'll do nothing.4377// TODO: Test this properly.4378} break;43794380case DisplayServer::WINDOW_MODE_MAXIMIZED: {4381// Try to unmaximize. This isn't garaunteed to work actually, so we'll have4382// to check whether something changed.4383if (ws.xdg_toplevel) {4384xdg_toplevel_unset_maximized(ws.xdg_toplevel);4385}43864387#ifdef LIBDECOR_ENABLED4388if (ws.libdecor_frame) {4389libdecor_frame_unset_maximized(ws.libdecor_frame);4390}4391#endif // LIBDECOR_ENABLED4392} break;43934394case DisplayServer::WINDOW_MODE_FULLSCREEN:4395case DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN: {4396// Same thing as above, unset fullscreen and check later if it worked.4397if (ws.xdg_toplevel) {4398xdg_toplevel_unset_fullscreen(ws.xdg_toplevel);4399}44004401#ifdef LIBDECOR_ENABLED4402if (ws.libdecor_frame) {4403libdecor_frame_unset_fullscreen(ws.libdecor_frame);4404}4405#endif // LIBDECOR_ENABLED4406} break;4407}44084409// Wait for a configure event and hope that something changed.4410wl_display_roundtrip(wl_display);44114412if (ws.mode != DisplayServer::WINDOW_MODE_WINDOWED) {4413// The compositor refused our "normalization" request. It'd be useless or4414// unpredictable to attempt setting a new state. We're done.4415return;4416}44174418// Ask the compositor to set the state indicated by the new mode.4419switch (p_window_mode) {4420case DisplayServer::WINDOW_MODE_WINDOWED: {4421// Do nothing. We're already windowed.4422} break;44234424case DisplayServer::WINDOW_MODE_MINIMIZED: {4425if (!window_can_set_mode(p_window_id, p_window_mode)) {4426// Minimization is special (read below). Better not mess with it if the4427// compositor explicitly announces that it doesn't support it.4428break;4429}44304431if (ws.xdg_toplevel) {4432xdg_toplevel_set_minimized(ws.xdg_toplevel);4433}44344435#ifdef LIBDECOR_ENABLED4436if (ws.libdecor_frame) {4437libdecor_frame_set_minimized(ws.libdecor_frame);4438}4439#endif // LIBDECOR_ENABLED4440// We have no way to actually detect this state, so we'll have to report it4441// manually to the engine (hoping that it worked). In the worst case it'll4442// get reset by the next configure event.4443ws.mode = DisplayServer::WINDOW_MODE_MINIMIZED;4444} break;44454446case DisplayServer::WINDOW_MODE_MAXIMIZED: {4447if (ws.xdg_toplevel) {4448xdg_toplevel_set_maximized(ws.xdg_toplevel);4449}44504451#ifdef LIBDECOR_ENABLED4452if (ws.libdecor_frame) {4453libdecor_frame_set_maximized(ws.libdecor_frame);4454}4455#endif // LIBDECOR_ENABLED4456} break;44574458case DisplayServer::WINDOW_MODE_FULLSCREEN:4459case DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN: {4460if (ws.xdg_toplevel) {4461xdg_toplevel_set_fullscreen(ws.xdg_toplevel, nullptr);4462}44634464#ifdef LIBDECOR_ENABLED4465if (ws.libdecor_frame) {4466libdecor_frame_set_fullscreen(ws.libdecor_frame, nullptr);4467}4468#endif // LIBDECOR_ENABLED4469} break;44704471default: {4472} break;4473}4474}44754476void WaylandThread::window_set_borderless(DisplayServer::WindowID p_window_id, bool p_borderless) {4477ERR_FAIL_COND(!windows.has(p_window_id));4478WindowState &ws = windows[p_window_id];44794480if (ws.xdg_toplevel_decoration) {4481if (p_borderless) {4482// We implement borderless windows by simply asking the compositor to let4483// us handle decorations (we don't).4484zxdg_toplevel_decoration_v1_set_mode(ws.xdg_toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE);4485} else {4486zxdg_toplevel_decoration_v1_set_mode(ws.xdg_toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);4487}4488}44894490#ifdef LIBDECOR_ENABLED4491if (ws.libdecor_frame) {4492bool visible_current = libdecor_frame_is_visible(ws.libdecor_frame);4493bool visible_target = !p_borderless;44944495// NOTE: We have to do this otherwise we trip on a libdecor bug where it's4496// possible to destroy the frame more than once, by setting the visibility4497// to false multiple times and thus crashing.4498if (visible_current != visible_target) {4499print_verbose(vformat("Setting libdecor frame visibility to %s", visible_target));4500libdecor_frame_set_visibility(ws.libdecor_frame, visible_target);4501}4502}4503#endif // LIBDECOR_ENABLED4504}45054506void WaylandThread::window_set_title(DisplayServer::WindowID p_window_id, const String &p_title) {4507ERR_FAIL_COND(!windows.has(p_window_id));4508WindowState &ws = windows[p_window_id];45094510#ifdef LIBDECOR_ENABLED4511if (ws.libdecor_frame) {4512libdecor_frame_set_title(ws.libdecor_frame, p_title.utf8().get_data());4513}4514#endif // LIBDECOR_ENABLE45154516if (ws.xdg_toplevel) {4517xdg_toplevel_set_title(ws.xdg_toplevel, p_title.utf8().get_data());4518}4519}45204521void WaylandThread::window_set_app_id(DisplayServer::WindowID p_window_id, const String &p_app_id) {4522ERR_FAIL_COND(!windows.has(p_window_id));4523WindowState &ws = windows[p_window_id];45244525#ifdef LIBDECOR_ENABLED4526if (ws.libdecor_frame) {4527libdecor_frame_set_app_id(ws.libdecor_frame, p_app_id.utf8().get_data());4528return;4529}4530#endif // LIBDECOR_ENABLED45314532if (ws.xdg_toplevel) {4533xdg_toplevel_set_app_id(ws.xdg_toplevel, p_app_id.utf8().get_data());4534return;4535}4536}45374538void WaylandThread::set_icon(const Ref<Image> &p_icon) {4539ERR_FAIL_COND(p_icon.is_null());45404541Size2i icon_size = p_icon->get_size();4542ERR_FAIL_COND(icon_size.width != icon_size.height);45434544if (!registry.xdg_toplevel_icon_manager) {4545return;4546}45474548if (xdg_icon) {4549xdg_toplevel_icon_v1_destroy(xdg_icon);4550}45514552if (icon_buffer) {4553wl_buffer_destroy(icon_buffer);4554}45554556// NOTE: The stride is the width of the icon in bytes.4557uint32_t icon_stride = icon_size.width * 4;4558uint32_t data_size = icon_stride * icon_size.height;45594560// We need a shared memory object file descriptor in order to create a4561// wl_buffer through wl_shm.4562int fd = WaylandThread::_allocate_shm_file(data_size);4563ERR_FAIL_COND(fd == -1);45644565uint32_t *buffer_data = (uint32_t *)mmap(nullptr, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);45664567// Create the Wayland buffer.4568struct wl_shm_pool *shm_pool = wl_shm_create_pool(registry.wl_shm, fd, data_size);4569icon_buffer = wl_shm_pool_create_buffer(shm_pool, 0, icon_size.width, icon_size.height, icon_stride, WL_SHM_FORMAT_ARGB8888);4570wl_shm_pool_destroy(shm_pool);45714572// Fill the cursor buffer with the image data.4573for (uint32_t index = 0; index < (uint32_t)(icon_size.width * icon_size.height); index++) {4574int row_index = index / icon_size.width;4575int column_index = (index % icon_size.width);45764577buffer_data[index] = p_icon->get_pixel(column_index, row_index).to_argb32();45784579// Wayland buffers, unless specified, require associated alpha, so we'll just4580// associate the alpha in-place.4581uint8_t *pixel_data = (uint8_t *)&buffer_data[index];4582pixel_data[0] = pixel_data[0] * pixel_data[3] / 255;4583pixel_data[1] = pixel_data[1] * pixel_data[3] / 255;4584pixel_data[2] = pixel_data[2] * pixel_data[3] / 255;4585}45864587xdg_icon = xdg_toplevel_icon_manager_v1_create_icon(registry.xdg_toplevel_icon_manager);4588xdg_toplevel_icon_v1_add_buffer(xdg_icon, icon_buffer, icon_size.width);45894590if (Engine::get_singleton()->is_editor_hint() || Engine::get_singleton()->is_project_manager_hint()) {4591// Setting a name allows the godot icon to be overridden by a system theme.4592// We only want the project manager and editor to get themed,4593// Games will get icons with the protocol and themed icons with .desktop entries.4594// NOTE: should be synced with the icon name in misc/dist/linuxbsd/Godot.desktop4595xdg_toplevel_icon_v1_set_name(xdg_icon, "godot");4596}45974598for (KeyValue<DisplayServer::WindowID, WindowState> &pair : windows) {4599WindowState &ws = pair.value;4600#ifdef LIBDECOR_ENABLED4601if (ws.libdecor_frame) {4602xdg_toplevel *toplevel = libdecor_frame_get_xdg_toplevel(ws.libdecor_frame);4603ERR_FAIL_NULL(toplevel);4604xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, toplevel, xdg_icon);4605}4606#endif4607if (ws.xdg_toplevel) {4608xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, ws.xdg_toplevel, xdg_icon);4609}4610}4611}46124613DisplayServer::WindowMode WaylandThread::window_get_mode(DisplayServer::WindowID p_window_id) const {4614ERR_FAIL_COND_V(!windows.has(p_window_id), DisplayServer::WINDOW_MODE_WINDOWED);4615const WindowState &ws = windows[p_window_id];46164617return ws.mode;4618}46194620void WaylandThread::window_request_attention(DisplayServer::WindowID p_window_id) {4621ERR_FAIL_COND(!windows.has(p_window_id));4622WindowState &ws = windows[p_window_id];46234624if (registry.xdg_activation) {4625// Window attention requests are done through the XDG activation protocol.4626xdg_activation_token_v1 *xdg_activation_token = xdg_activation_v1_get_activation_token(registry.xdg_activation);4627xdg_activation_token_v1_add_listener(xdg_activation_token, &xdg_activation_token_listener, &ws);4628xdg_activation_token_v1_commit(xdg_activation_token);4629}4630}46314632void WaylandThread::window_set_idle_inhibition(DisplayServer::WindowID p_window_id, bool p_enable) {4633ERR_FAIL_COND(!windows.has(p_window_id));4634WindowState &ws = windows[p_window_id];46354636if (p_enable) {4637if (ws.registry->wp_idle_inhibit_manager && !ws.wp_idle_inhibitor) {4638ERR_FAIL_NULL(ws.wl_surface);4639ws.wp_idle_inhibitor = zwp_idle_inhibit_manager_v1_create_inhibitor(ws.registry->wp_idle_inhibit_manager, ws.wl_surface);4640}4641} else {4642if (ws.wp_idle_inhibitor) {4643zwp_idle_inhibitor_v1_destroy(ws.wp_idle_inhibitor);4644ws.wp_idle_inhibitor = nullptr;4645}4646}4647}46484649bool WaylandThread::window_get_idle_inhibition(DisplayServer::WindowID p_window_id) const {4650ERR_FAIL_COND_V(!windows.has(p_window_id), false);4651const WindowState &ws = windows[p_window_id];46524653return ws.wp_idle_inhibitor != nullptr;4654}46554656WaylandThread::ScreenData WaylandThread::screen_get_data(int p_screen) const {4657ERR_FAIL_INDEX_V(p_screen, registry.wl_outputs.size(), ScreenData());46584659return wl_output_get_screen_state(registry.wl_outputs.get(p_screen))->data;4660}46614662int WaylandThread::get_screen_count() const {4663return registry.wl_outputs.size();4664}46654666DisplayServer::WindowID WaylandThread::pointer_get_pointed_window_id() const {4667SeatState *ss = wl_seat_get_seat_state(wl_seat_current);46684669if (ss) {4670// Let's determine the most recently used tablet tool.4671TabletToolState *max_ts = nullptr;4672for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {4673TabletToolState *ts = wp_tablet_tool_get_state(tool);4674ERR_CONTINUE(ts == nullptr);46754676TabletToolData &td = ts->data;46774678if (!max_ts) {4679max_ts = ts;4680continue;4681}46824683if (MAX(td.button_time, td.motion_time) > MAX(max_ts->data.button_time, max_ts->data.motion_time)) {4684max_ts = ts;4685}4686}46874688const PointerData &pd = ss->pointer_data;46894690if (max_ts) {4691TabletToolData &td = max_ts->data;4692if (MAX(td.button_time, td.motion_time) > MAX(pd.button_time, pd.motion_time)) {4693return td.proximal_id;4694}4695}46964697return ss->pointer_data.pointed_id;4698}46994700return DisplayServer::INVALID_WINDOW_ID;4701}4702DisplayServer::WindowID WaylandThread::pointer_get_last_pointed_window_id() const {4703SeatState *ss = wl_seat_get_seat_state(wl_seat_current);47044705if (ss) {4706// Let's determine the most recently used tablet tool.4707TabletToolState *max_ts = nullptr;4708for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {4709TabletToolState *ts = wp_tablet_tool_get_state(tool);4710ERR_CONTINUE(ts == nullptr);47114712TabletToolData &td = ts->data;47134714if (!max_ts) {4715max_ts = ts;4716continue;4717}47184719if (MAX(td.button_time, td.motion_time) > MAX(max_ts->data.button_time, max_ts->data.motion_time)) {4720max_ts = ts;4721}4722}47234724const PointerData &pd = ss->pointer_data;47254726if (max_ts) {4727TabletToolData &td = max_ts->data;4728if (MAX(td.button_time, td.motion_time) > MAX(pd.button_time, pd.motion_time)) {4729return td.last_proximal_id;4730}4731}47324733return ss->pointer_data.last_pointed_id;4734}47354736return DisplayServer::INVALID_WINDOW_ID;4737}47384739void WaylandThread::pointer_set_constraint(PointerConstraint p_constraint) {4740SeatState *ss = wl_seat_get_seat_state(wl_seat_current);47414742if (ss) {4743seat_state_unlock_pointer(ss);47444745if (p_constraint == PointerConstraint::LOCKED) {4746seat_state_lock_pointer(ss);4747} else if (p_constraint == PointerConstraint::CONFINED) {4748seat_state_confine_pointer(ss);4749}4750}47514752pointer_constraint = p_constraint;4753}47544755void WaylandThread::pointer_set_hint(const Point2i &p_hint) {4756SeatState *ss = wl_seat_get_seat_state(wl_seat_current);4757if (!ss) {4758return;4759}47604761WindowState *ws = window_get_state(ss->pointer_data.pointed_id);4762if (!ws) {4763return;4764}47654766// NOTE: It looks like it's not really recommended to convert from4767// "godot-space" to "wayland-space" and in general I received mixed feelings4768// discussing about this. I'm not really sure about the maths behind this but,4769// oh well, we're setting a cursor hint. ¯\_(ツ)_/¯4770// See: https://oftc.irclog.whitequark.org/wayland/2023-08-23#1692756914-16928168184771int hint_x = Math::round(p_hint.x / window_state_get_scale_factor(ws));4772int hint_y = Math::round(p_hint.y / window_state_get_scale_factor(ws));47734774if (ss) {4775seat_state_set_hint(ss, hint_x, hint_y);4776}4777}47784779void WaylandThread::pointer_warp(const Point2i &p_to) {4780// NOTE: This is for compositors that don't support the pointer-warp protocol.4781// It's hacked together and not guaranteed to work.4782if (registry.wp_pointer_warp == nullptr) {4783PointerConstraint old_constraint = pointer_get_constraint();47844785pointer_set_constraint(PointerConstraint::LOCKED);4786pointer_set_hint(p_to);47874788pointer_set_constraint(old_constraint);47894790return;4791}47924793SeatState *ss = wl_seat_get_seat_state(wl_seat_current);4794if (!ss) {4795return;4796}47974798WindowState *ws = window_get_state(ss->pointer_data.pointed_id);4799if (!ws) {4800return;4801}48024803// NOTE: It looks like it's not really recommended to convert from4804// "godot-space" to "wayland-space" and in general I received mixed feelings4805// discussing about this. I'm not really sure about the maths behind this but,4806// oh well. ¯\_(ツ)_/¯4807// See: https://oftc.irclog.whitequark.org/wayland/2023-08-23#1692756914-16928168184808int wl_pos_x = Math::round(p_to.x / window_state_get_scale_factor(ws));4809int wl_pos_y = Math::round(p_to.y / window_state_get_scale_factor(ws));48104811if (ss) {4812seat_state_warp_pointer(ss, wl_pos_x, wl_pos_y);4813}4814}48154816WaylandThread::PointerConstraint WaylandThread::pointer_get_constraint() const {4817return pointer_constraint;4818}48194820BitField<MouseButtonMask> WaylandThread::pointer_get_button_mask() const {4821SeatState *ss = wl_seat_get_seat_state(wl_seat_current);48224823if (ss) {4824return ss->pointer_data.pressed_button_mask;4825}48264827return BitField<MouseButtonMask>();4828}48294830Error WaylandThread::init() {4831#ifdef SOWRAP_ENABLED4832#ifdef DEBUG_ENABLED4833int dylibloader_verbose = 1;4834#else4835int dylibloader_verbose = 0;4836#endif // DEBUG_ENABLED48374838if (initialize_wayland_client(dylibloader_verbose) != 0) {4839WARN_PRINT("Can't load the Wayland client library.");4840return ERR_CANT_CREATE;4841}48424843if (initialize_wayland_cursor(dylibloader_verbose) != 0) {4844WARN_PRINT("Can't load the Wayland cursor library.");4845return ERR_CANT_CREATE;4846}48474848if (initialize_xkbcommon(dylibloader_verbose) != 0) {4849WARN_PRINT("Can't load the XKBcommon library.");4850return ERR_CANT_CREATE;4851}4852#endif // SOWRAP_ENABLED48534854KeyMappingXKB::initialize();48554856String embedder_socket_path;48574858#ifdef TOOLS_ENABLED4859bool embedder_enabled = true;48604861if (OS::get_singleton()->get_environment("GODOT_WAYLAND_DISABLE_EMBEDDER") == "1") {4862print_verbose("Disabling Wayland embedder as per GODOT_WAYLAND_DISABLE_EMBEDDER.");4863embedder_enabled = false;4864}48654866if (embedder_enabled && Engine::get_singleton()->is_editor_hint() && !Engine::get_singleton()->is_project_manager_hint()) {4867print_verbose("Initializing Wayland embedder.");4868Error embedder_status = embedder.init();4869ERR_FAIL_COND_V_MSG(embedder_status != OK, ERR_CANT_CREATE, "Can't initialize Wayland embedder.");48704871embedder_socket_path = embedder.get_socket_path();4872ERR_FAIL_COND_V_MSG(embedder_socket_path.is_empty(), ERR_CANT_CREATE, "Wayland embedder returned invalid path.");48734874OS::get_singleton()->set_environment("GODOT_WAYLAND_DISPLAY", embedder_socket_path);4875}4876#endif // TOOLS_ENABLED48774878if (Engine::get_singleton()->is_embedded_in_editor()) {4879embedder_socket_path = OS::get_singleton()->get_environment("GODOT_WAYLAND_DISPLAY");4880#if 04881// Debug4882OS::get_singleton()->set_environment("WAYLAND_DEBUG", "1");4883int fd = open("/tmp/gdembedded.log", O_CREAT | O_RDWR, 0666);4884dup2(fd, 1);4885dup2(fd, 2);4886#endif4887}48884889if (embedder_socket_path.is_empty()) {4890print_verbose("Connecting to the default Wayland display.");4891wl_display = wl_display_connect(nullptr);4892} else {4893print_verbose("Connecting to the Wayland embedder display.");4894wl_display = wl_display_connect(embedder_socket_path.utf8().get_data());4895}48964897ERR_FAIL_NULL_V_MSG(wl_display, ERR_CANT_CREATE, "Can't connect to a Wayland display.");48984899thread_data.wl_display = wl_display;49004901wl_registry = wl_display_get_registry(wl_display);49024903ERR_FAIL_NULL_V_MSG(wl_registry, ERR_UNAVAILABLE, "Can't obtain the Wayland registry global.");49044905registry.wayland_thread = this;49064907wl_registry_add_listener(wl_registry, &wl_registry_listener, ®istry);49084909// Wait for registry to get notified from the compositor.4910wl_display_roundtrip(wl_display);49114912ERR_FAIL_NULL_V_MSG(registry.wl_shm, ERR_UNAVAILABLE, "Can't obtain the Wayland shared memory global.");4913ERR_FAIL_NULL_V_MSG(registry.wl_compositor, ERR_UNAVAILABLE, "Can't obtain the Wayland compositor global.");4914ERR_FAIL_NULL_V_MSG(registry.xdg_wm_base, ERR_UNAVAILABLE, "Can't obtain the Wayland XDG shell global.");49154916// Embedded games can't access the decoration and icon protocol.4917if (!Engine::get_singleton()->is_embedded_in_editor()) {4918if (!registry.xdg_decoration_manager) {4919#ifdef LIBDECOR_ENABLED4920WARN_PRINT("Can't obtain the XDG decoration manager. Libdecor will be used for drawing CSDs, if available.");4921#else4922WARN_PRINT("Can't obtain the XDG decoration manager. Decorations won't show up.");4923#endif // LIBDECOR_ENABLED4924}49254926if (!registry.xdg_toplevel_icon_manager_name) {4927WARN_PRINT("xdg-toplevel-icon protocol not found! Cannot set window icon.");4928}4929}49304931if (!registry.xdg_activation) {4932WARN_PRINT("Can't obtain the XDG activation global. Attention requesting won't work!");4933}49344935#ifndef DBUS_ENABLED4936if (!registry.wp_idle_inhibit_manager) {4937WARN_PRINT("Can't obtain the idle inhibition manager. The screen might turn off even after calling screen_set_keep_on()!");4938}4939#endif // DBUS_ENABLED49404941if (!registry.wp_fifo_manager_name) {4942WARN_PRINT("FIFO protocol not found! Frame pacing will be degraded.");4943}49444945// Wait for seat capabilities.4946wl_display_roundtrip(wl_display);49474948#ifdef LIBDECOR_ENABLED4949bool libdecor_found = true;49504951bool skip_libdecor = OS::get_singleton()->get_environment("GODOT_WAYLAND_DISABLE_LIBDECOR") == "1";49524953#ifdef SOWRAP_ENABLED4954if (!skip_libdecor && initialize_libdecor(dylibloader_verbose) != 0) {4955libdecor_found = false;4956}4957#endif // SOWRAP_ENABLED49584959if (skip_libdecor) {4960print_verbose("Skipping libdecor check because GODOT_WAYLAND_DISABLE_LIBDECOR is set to 1.");4961} else {4962if (libdecor_found) {4963libdecor_context = libdecor_new(wl_display, (struct libdecor_interface *)&libdecor_interface);4964} else {4965print_verbose("libdecor not found. Client-side decorations disabled.");4966}4967}4968#endif // LIBDECOR_ENABLED49694970cursor_theme_name = OS::get_singleton()->get_environment("XCURSOR_THEME");49714972unscaled_cursor_size = OS::get_singleton()->get_environment("XCURSOR_SIZE").to_int();4973if (unscaled_cursor_size <= 0) {4974print_verbose("Detected invalid cursor size preference, defaulting to 24.");4975unscaled_cursor_size = 24;4976}49774978// NOTE: The scale is useful here as it might've been updated by _update_scale.4979bool cursor_theme_loaded = _load_cursor_theme(unscaled_cursor_size * cursor_scale);49804981if (!cursor_theme_loaded) {4982return ERR_CANT_CREATE;4983}49844985// Update the cursor.4986cursor_set_shape(DisplayServer::CURSOR_ARROW);49874988events_thread.start(_poll_events_thread, &thread_data);49894990initialized = true;4991return OK;4992}49934994void WaylandThread::cursor_set_visible(bool p_visible) {4995cursor_visible = p_visible;49964997for (struct wl_seat *wl_seat : registry.wl_seats) {4998SeatState *ss = wl_seat_get_seat_state(wl_seat);4999ERR_FAIL_NULL(ss);50005001seat_state_update_cursor(ss);5002}5003}50045005void WaylandThread::cursor_set_shape(DisplayServer::CursorShape p_cursor_shape) {5006cursor_shape = p_cursor_shape;50075008for (struct wl_seat *wl_seat : registry.wl_seats) {5009SeatState *ss = wl_seat_get_seat_state(wl_seat);5010ERR_FAIL_NULL(ss);50115012seat_state_update_cursor(ss);5013}5014}50155016void WaylandThread::cursor_shape_set_custom_image(DisplayServer::CursorShape p_cursor_shape, Ref<Image> p_image, const Point2i &p_hotspot) {5017ERR_FAIL_COND(p_image.is_null());50185019Size2i image_size = p_image->get_size();50205021// NOTE: The stride is the width of the image in bytes.5022unsigned int image_stride = image_size.width * 4;5023unsigned int data_size = image_stride * image_size.height;50245025// We need a shared memory object file descriptor in order to create a5026// wl_buffer through wl_shm.5027int fd = WaylandThread::_allocate_shm_file(data_size);5028ERR_FAIL_COND(fd == -1);50295030CustomCursor &cursor = custom_cursors[p_cursor_shape];5031cursor.hotspot = p_hotspot;50325033if (cursor.wl_buffer) {5034// Clean up the old Wayland buffer.5035wl_buffer_destroy(cursor.wl_buffer);5036}50375038if (cursor.buffer_data) {5039// Clean up the old buffer data.5040munmap(cursor.buffer_data, cursor.buffer_data_size);5041}50425043cursor.buffer_data = (uint32_t *)mmap(nullptr, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);5044cursor.buffer_data_size = data_size;50455046// Create the Wayland buffer.5047struct wl_shm_pool *wl_shm_pool = wl_shm_create_pool(registry.wl_shm, fd, data_size);5048// TODO: Make sure that WL_SHM_FORMAT_ARGB8888 format is supported. It5049// technically isn't garaunteed to be supported, but I think that'd be a5050// pretty unlikely thing to stumble upon.5051cursor.wl_buffer = wl_shm_pool_create_buffer(wl_shm_pool, 0, image_size.width, image_size.height, image_stride, WL_SHM_FORMAT_ARGB8888);5052wl_shm_pool_destroy(wl_shm_pool);50535054// Fill the cursor buffer with the image data.5055for (unsigned int index = 0; index < (unsigned int)(image_size.width * image_size.height); index++) {5056int row_index = std::floor(index / image_size.width);5057int column_index = (index % int(image_size.width));50585059cursor.buffer_data[index] = p_image->get_pixel(column_index, row_index).to_argb32();50605061// Wayland buffers, unless specified, require associated alpha, so we'll just5062// associate the alpha in-place.5063uint8_t *pixel_data = (uint8_t *)&cursor.buffer_data[index];5064pixel_data[0] = pixel_data[0] * pixel_data[3] / 255;5065pixel_data[1] = pixel_data[1] * pixel_data[3] / 255;5066pixel_data[2] = pixel_data[2] * pixel_data[3] / 255;5067}5068}50695070void WaylandThread::cursor_shape_clear_custom_image(DisplayServer::CursorShape p_cursor_shape) {5071if (custom_cursors.has(p_cursor_shape)) {5072CustomCursor cursor = custom_cursors[p_cursor_shape];5073custom_cursors.erase(p_cursor_shape);50745075if (cursor.wl_buffer) {5076wl_buffer_destroy(cursor.wl_buffer);5077}50785079if (cursor.buffer_data) {5080munmap(cursor.buffer_data, cursor.buffer_data_size);5081}5082}5083}50845085void WaylandThread::window_set_ime_active(const bool p_active, DisplayServer::WindowID p_window_id) {5086SeatState *ss = wl_seat_get_seat_state(wl_seat_current);50875088if (ss && ss->wp_text_input && ss->ime_enabled) {5089if (p_active) {5090ss->ime_active = true;5091zwp_text_input_v3_enable(ss->wp_text_input);5092zwp_text_input_v3_set_cursor_rectangle(ss->wp_text_input, ss->ime_rect.position.x, ss->ime_rect.position.y, ss->ime_rect.size.x, ss->ime_rect.size.y);5093} else {5094ss->ime_active = false;5095ss->ime_text = String();5096ss->ime_text_commit = String();5097ss->ime_cursor = Vector2i();5098zwp_text_input_v3_disable(ss->wp_text_input);5099}5100zwp_text_input_v3_commit(ss->wp_text_input);5101}5102}51035104void WaylandThread::window_set_ime_position(const Point2i &p_pos, DisplayServer::WindowID p_window_id) {5105SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51065107if (ss && ss->wp_text_input && ss->ime_enabled) {5108ss->ime_rect = Rect2i(p_pos, Size2i(1, 10));5109zwp_text_input_v3_set_cursor_rectangle(ss->wp_text_input, ss->ime_rect.position.x, ss->ime_rect.position.y, ss->ime_rect.size.x, ss->ime_rect.size.y);5110zwp_text_input_v3_commit(ss->wp_text_input);5111}5112}51135114int WaylandThread::keyboard_get_layout_count() const {5115SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51165117if (ss && ss->xkb_keymap) {5118return xkb_keymap_num_layouts(ss->xkb_keymap);5119}51205121return 0;5122}51235124int WaylandThread::keyboard_get_current_layout_index() const {5125SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51265127if (ss) {5128return ss->current_layout_index;5129}51305131return 0;5132}51335134void WaylandThread::keyboard_set_current_layout_index(int p_index) {5135SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51365137if (ss) {5138ss->current_layout_index = p_index;5139}5140}51415142String WaylandThread::keyboard_get_layout_name(int p_index) const {5143SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51445145if (ss && ss->xkb_keymap) {5146return String::utf8(xkb_keymap_layout_get_name(ss->xkb_keymap, p_index));5147}51485149return "";5150}51515152Key WaylandThread::keyboard_get_key_from_physical(Key p_key) const {5153SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51545155if (ss && ss->xkb_state) {5156Key modifiers = p_key & KeyModifierMask::MODIFIER_MASK;5157Key keycode_no_mod = p_key & KeyModifierMask::CODE_MASK;51585159xkb_keycode_t xkb_keycode = KeyMappingXKB::get_xkb_keycode(keycode_no_mod);5160Key key = KeyMappingXKB::get_keycode(xkb_state_key_get_one_sym(ss->xkb_state, xkb_keycode));5161return (Key)(key | modifiers);5162}51635164return p_key;5165}51665167Key WaylandThread::keyboard_get_label_from_physical(Key p_key) const {5168SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51695170if (ss && ss->xkb_state) {5171Key modifiers = p_key & KeyModifierMask::MODIFIER_MASK;5172Key keycode_no_mod = p_key & KeyModifierMask::CODE_MASK;51735174xkb_keycode_t xkb_keycode = KeyMappingXKB::get_xkb_keycode(keycode_no_mod);5175xkb_keycode_t xkb_keysym = xkb_state_key_get_one_sym(ss->xkb_state, xkb_keycode);5176char32_t chr = xkb_keysym_to_utf32(xkb_keysym_to_upper(xkb_keysym));5177if (chr != 0) {5178String keysym = String::chr(chr);5179Key key = fix_key_label(keysym[0], KeyMappingXKB::get_keycode(xkb_keysym));5180return (Key)(key | modifiers);5181}5182}51835184return p_key;5185}51865187void WaylandThread::keyboard_echo_keys() {5188SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51895190if (ss) {5191seat_state_echo_keys(ss);5192}5193}51945195void WaylandThread::selection_set_text(const String &p_text) {5196SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51975198if (registry.wl_data_device_manager == nullptr) {5199DEBUG_LOG_WAYLAND_THREAD("Couldn't set selection, wl_data_device_manager global not available.");5200return;5201}52025203if (ss == nullptr) {5204DEBUG_LOG_WAYLAND_THREAD("Couldn't set selection, current seat not set.");5205return;5206}52075208if (ss->wl_data_device == nullptr) {5209DEBUG_LOG_WAYLAND_THREAD("Couldn't set selection, seat doesn't have wl_data_device.");5210return;5211}52125213ss->selection_data = p_text.to_utf8_buffer();52145215if (ss->wl_data_source_selection == nullptr) {5216ss->wl_data_source_selection = wl_data_device_manager_create_data_source(registry.wl_data_device_manager);5217wl_data_source_add_listener(ss->wl_data_source_selection, &wl_data_source_listener, ss);5218wl_data_source_offer(ss->wl_data_source_selection, "text/plain;charset=utf-8");5219wl_data_source_offer(ss->wl_data_source_selection, "text/plain");52205221// TODO: Implement a good way of getting the latest serial from the user.5222wl_data_device_set_selection(ss->wl_data_device, ss->wl_data_source_selection, MAX(ss->pointer_data.button_serial, ss->last_key_pressed_serial));5223}52245225// Wait for the message to get to the server before continuing, otherwise the5226// clipboard update might come with a delay.5227wl_display_roundtrip(wl_display);5228}52295230bool WaylandThread::selection_has_mime(const String &p_mime) const {5231SeatState *ss = wl_seat_get_seat_state(wl_seat_current);52325233if (ss == nullptr) {5234DEBUG_LOG_WAYLAND_THREAD("Couldn't get selection, current seat not set.");5235return false;5236}52375238OfferState *os = wl_data_offer_get_offer_state(ss->wl_data_offer_selection);5239if (!os) {5240return false;5241}52425243return os->mime_types.has(p_mime);5244}52455246Vector<uint8_t> WaylandThread::selection_get_mime(const String &p_mime) const {5247SeatState *ss = wl_seat_get_seat_state(wl_seat_current);5248if (ss == nullptr) {5249DEBUG_LOG_WAYLAND_THREAD("Couldn't get selection, current seat not set.");5250return Vector<uint8_t>();5251}52525253if (ss->wl_data_source_selection) {5254// We have a source so the stuff we're pasting is ours. We'll have to pass the5255// data directly or we'd stall waiting for Godot (ourselves) to send us the5256// data :P52575258OfferState *os = wl_data_offer_get_offer_state(ss->wl_data_offer_selection);5259ERR_FAIL_NULL_V(os, Vector<uint8_t>());52605261if (os->mime_types.has(p_mime)) {5262// All righty, we're offering this type. Let's just return the data as is.5263return ss->selection_data;5264}52655266// ... we don't offer that type. Oh well.5267return Vector<uint8_t>();5268}52695270return _wl_data_offer_read(wl_display, p_mime.utf8().get_data(), ss->wl_data_offer_selection);5271}52725273bool WaylandThread::primary_has_mime(const String &p_mime) const {5274SeatState *ss = wl_seat_get_seat_state(wl_seat_current);52755276if (ss == nullptr) {5277DEBUG_LOG_WAYLAND_THREAD("Couldn't get selection, current seat not set.");5278return false;5279}52805281OfferState *os = wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer);5282if (!os) {5283return false;5284}52855286return os->mime_types.has(p_mime);5287}52885289Vector<uint8_t> WaylandThread::primary_get_mime(const String &p_mime) const {5290SeatState *ss = wl_seat_get_seat_state(wl_seat_current);5291if (ss == nullptr) {5292DEBUG_LOG_WAYLAND_THREAD("Couldn't get primary, current seat not set.");5293return Vector<uint8_t>();5294}52955296if (ss->wp_primary_selection_source) {5297// We have a source so the stuff we're pasting is ours. We'll have to pass the5298// data directly or we'd stall waiting for Godot (ourselves) to send us the5299// data :P53005301OfferState *os = wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer);5302ERR_FAIL_NULL_V(os, Vector<uint8_t>());53035304if (os->mime_types.has(p_mime)) {5305// All righty, we're offering this type. Let's just return the data as is.5306return ss->selection_data;5307}53085309// ... we don't offer that type. Oh well.5310return Vector<uint8_t>();5311}53125313return _wp_primary_selection_offer_read(wl_display, p_mime.utf8().get_data(), ss->wp_primary_selection_offer);5314}53155316void WaylandThread::primary_set_text(const String &p_text) {5317SeatState *ss = wl_seat_get_seat_state(wl_seat_current);53185319if (registry.wp_primary_selection_device_manager == nullptr) {5320DEBUG_LOG_WAYLAND_THREAD("Couldn't set primary, protocol not available.");5321return;5322}53235324if (ss == nullptr) {5325DEBUG_LOG_WAYLAND_THREAD("Couldn't set primary, current seat not set.");5326return;5327}53285329if (ss->wp_primary_selection_device == nullptr) {5330DEBUG_LOG_WAYLAND_THREAD("Couldn't set primary selection, seat doesn't have wp_primary_selection_device.");5331return;5332}53335334ss->primary_data = p_text.to_utf8_buffer();53355336if (ss->wp_primary_selection_source == nullptr) {5337ss->wp_primary_selection_source = zwp_primary_selection_device_manager_v1_create_source(registry.wp_primary_selection_device_manager);5338zwp_primary_selection_source_v1_add_listener(ss->wp_primary_selection_source, &wp_primary_selection_source_listener, ss);5339zwp_primary_selection_source_v1_offer(ss->wp_primary_selection_source, "text/plain;charset=utf-8");5340zwp_primary_selection_source_v1_offer(ss->wp_primary_selection_source, "text/plain");53415342// TODO: Implement a good way of getting the latest serial from the user.5343zwp_primary_selection_device_v1_set_selection(ss->wp_primary_selection_device, ss->wp_primary_selection_source, MAX(ss->pointer_data.button_serial, ss->last_key_pressed_serial));5344}53455346// Wait for the message to get to the server before continuing, otherwise the5347// clipboard update might come with a delay.5348wl_display_roundtrip(wl_display);5349}53505351void WaylandThread::commit_surfaces() {5352for (KeyValue<DisplayServer::WindowID, WindowState> &pair : windows) {5353wl_surface_commit(pair.value.wl_surface);5354}5355}53565357void WaylandThread::set_frame() {5358frame = true;5359}53605361bool WaylandThread::get_reset_frame() {5362bool old_frame = frame;5363frame = false;53645365return old_frame;5366}53675368// Dispatches events until a frame event is received, a window is reported as5369// suspended or the timeout expires.5370bool WaylandThread::wait_frame_suspend_ms(int p_timeout) {5371// This is a bit of a chicken and egg thing... Looks like the main event loop5372// has to call its rightfully forever-blocking poll right in between5373// `wl_display_prepare_read` and `wl_display_read`. This means, that it will5374// basically be guaranteed to stay stuck in a "prepare read" state, where it5375// will block any other attempt at reading the display fd, such as ours. The5376// solution? Let's make sure the mutex is locked (it should) and unblock the5377// main thread with a roundtrip!5378MutexLock mutex_lock(mutex);5379wl_display_roundtrip(wl_display);53805381if (is_suspended()) {5382// All windows are suspended! The compositor is telling us _explicitly_ that5383// we don't need to draw, without letting us guess through the frame event's5384// timing and stuff like that. Our job here is done.5385return false;5386}53875388if (frame) {5389// We already have a frame! Probably it got there while the caller locked :D5390frame = false;5391return true;5392}53935394struct pollfd poll_fd;5395poll_fd.fd = wl_display_get_fd(wl_display);5396poll_fd.events = POLLIN | POLLHUP;53975398int begin_ms = OS::get_singleton()->get_ticks_msec();5399int remaining_ms = p_timeout;54005401while (remaining_ms > 0) {5402// Empty the event queue while it's full.5403while (wl_display_prepare_read(wl_display) != 0) {5404if (wl_display_dispatch_pending(wl_display) == -1) {5405// Oh no. We'll check and handle any display error below.5406break;5407}54085409if (is_suspended()) {5410return false;5411}54125413if (frame) {5414// We had a frame event in the queue :D5415frame = false;5416return true;5417}5418}54195420int werror = wl_display_get_error(wl_display);54215422if (werror) {5423if (werror == EPROTO) {5424struct wl_interface *wl_interface = nullptr;5425uint32_t id = 0;54265427int error_code = wl_display_get_protocol_error(wl_display, (const struct wl_interface **)&wl_interface, &id);5428CRASH_NOW_MSG(vformat("Wayland protocol error %d on interface %s@%d.", error_code, wl_interface ? wl_interface->name : "unknown", id));5429} else {5430CRASH_NOW_MSG(vformat("Wayland client error code %d.", werror));5431}5432}54335434wl_display_flush(wl_display);54355436// Wait for the event file descriptor to have new data.5437poll(&poll_fd, 1, remaining_ms);54385439if (poll_fd.revents | POLLIN) {5440// Load the queues with fresh new data.5441wl_display_read_events(wl_display);5442} else {5443// Oh well... Stop signaling that we want to read.5444wl_display_cancel_read(wl_display);54455446// We've got no new events :(5447// We won't even bother with checking the frame flag.5448return false;5449}54505451// Let's try dispatching now...5452wl_display_dispatch_pending(wl_display);54535454if (is_suspended()) {5455return false;5456}54575458if (frame) {5459frame = false;5460return true;5461}54625463remaining_ms -= OS::get_singleton()->get_ticks_msec() - begin_ms;5464}54655466DEBUG_LOG_WAYLAND_THREAD("Frame timeout.");5467return false;5468}54695470uint64_t WaylandThread::window_get_last_frame_time(DisplayServer::WindowID p_window_id) const {5471ERR_FAIL_COND_V(!windows.has(p_window_id), false);5472return windows[p_window_id].last_frame_time;5473}54745475bool WaylandThread::window_is_suspended(DisplayServer::WindowID p_window_id) const {5476ERR_FAIL_COND_V(!windows.has(p_window_id), false);5477return windows[p_window_id].suspended;5478}54795480bool WaylandThread::is_fifo_available() const {5481return registry.wp_fifo_manager_name != 0;5482}54835484bool WaylandThread::is_suspended() const {5485for (const KeyValue<DisplayServer::WindowID, WindowState> &E : windows) {5486if (!E.value.suspended) {5487return false;5488}5489}54905491return true;5492}54935494struct godot_embedding_compositor *WaylandThread::get_embedding_compositor() {5495return registry.godot_embedding_compositor;5496}54975498OS::ProcessID WaylandThread::embedded_compositor_get_focused_pid() {5499EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(registry.godot_embedding_compositor);5500ERR_FAIL_NULL_V(ecomp_state, -1);55015502return ecomp_state->focused_pid;5503}55045505void WaylandThread::destroy() {5506if (!initialized) {5507return;5508}55095510if (wl_display && events_thread.is_started()) {5511thread_data.thread_done.set();55125513// By sending a roundtrip message we're unblocking the polling thread so that5514// it can realize that it's done and also handle every event that's left.5515wl_display_roundtrip(wl_display);55165517events_thread.wait_to_finish();5518}55195520for (KeyValue<DisplayServer::WindowID, WindowState> &pair : windows) {5521WindowState &ws = pair.value;5522if (ws.wp_fractional_scale) {5523wp_fractional_scale_v1_destroy(ws.wp_fractional_scale);5524}55255526if (ws.wp_viewport) {5527wp_viewport_destroy(ws.wp_viewport);5528}55295530if (ws.frame_callback) {5531wl_callback_destroy(ws.frame_callback);5532}55335534#ifdef LIBDECOR_ENABLED5535if (ws.libdecor_frame) {5536libdecor_frame_close(ws.libdecor_frame);5537}5538#endif // LIBDECOR_ENABLED55395540if (ws.xdg_toplevel_decoration) {5541zxdg_toplevel_decoration_v1_destroy(ws.xdg_toplevel_decoration);5542}55435544if (ws.xdg_toplevel) {5545xdg_toplevel_destroy(ws.xdg_toplevel);5546}55475548if (ws.xdg_surface) {5549xdg_surface_destroy(ws.xdg_surface);5550}55515552if (ws.wl_surface) {5553wl_surface_destroy(ws.wl_surface);5554}5555}55565557for (struct wl_seat *wl_seat : registry.wl_seats) {5558SeatState *ss = wl_seat_get_seat_state(wl_seat);5559ERR_FAIL_NULL(ss);55605561wl_seat_destroy(wl_seat);55625563xkb_context_unref(ss->xkb_context);5564xkb_state_unref(ss->xkb_state);5565xkb_keymap_unref(ss->xkb_keymap);5566xkb_compose_table_unref(ss->xkb_compose_table);5567xkb_compose_state_unref(ss->xkb_compose_state);55685569if (ss->wl_keyboard) {5570wl_keyboard_destroy(ss->wl_keyboard);5571}55725573if (ss->keymap_buffer) {5574munmap((void *)ss->keymap_buffer, ss->keymap_buffer_size);5575}55765577if (ss->wl_pointer) {5578wl_pointer_destroy(ss->wl_pointer);5579}55805581if (ss->cursor_frame_callback) {5582// We don't need to set a null userdata for safety as the thread is done.5583wl_callback_destroy(ss->cursor_frame_callback);5584}55855586if (ss->cursor_surface) {5587wl_surface_destroy(ss->cursor_surface);5588}55895590if (ss->wl_data_device) {5591wl_data_device_destroy(ss->wl_data_device);5592}55935594if (ss->wp_cursor_shape_device) {5595wp_cursor_shape_device_v1_destroy(ss->wp_cursor_shape_device);5596}55975598if (ss->wp_relative_pointer) {5599zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);5600}56015602if (ss->wp_locked_pointer) {5603zwp_locked_pointer_v1_destroy(ss->wp_locked_pointer);5604}56055606if (ss->wp_confined_pointer) {5607zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);5608}56095610if (ss->wp_tablet_seat) {5611zwp_tablet_seat_v2_destroy(ss->wp_tablet_seat);5612}56135614for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {5615TabletToolState *state = wp_tablet_tool_get_state(tool);5616if (state) {5617memdelete(state);5618}56195620zwp_tablet_tool_v2_destroy(tool);5621}56225623if (ss->wp_text_input) {5624zwp_text_input_v3_destroy(ss->wp_text_input);5625}56265627memdelete(ss);5628}56295630if (registry.wp_tablet_manager) {5631zwp_tablet_manager_v2_destroy(registry.wp_tablet_manager);5632}56335634if (registry.wp_text_input_manager) {5635zwp_text_input_manager_v3_destroy(registry.wp_text_input_manager);5636}56375638for (struct wl_output *wl_output : registry.wl_outputs) {5639ERR_FAIL_NULL(wl_output);56405641memdelete(wl_output_get_screen_state(wl_output));5642wl_output_destroy(wl_output);5643}56445645if (registry.godot_embedding_compositor) {5646EmbeddingCompositorState *es = godot_embedding_compositor_get_state(registry.godot_embedding_compositor);5647ERR_FAIL_NULL(es);56485649es->mapped_clients.clear();56505651for (struct godot_embedded_client *client : es->clients) {5652godot_embedded_client_destroy(client);5653}5654es->clients.clear();56555656memdelete(es);56575658godot_embedding_compositor_destroy(registry.godot_embedding_compositor);5659}56605661if (wl_cursor_theme) {5662wl_cursor_theme_destroy(wl_cursor_theme);5663}56645665if (registry.wp_idle_inhibit_manager) {5666zwp_idle_inhibit_manager_v1_destroy(registry.wp_idle_inhibit_manager);5667}56685669if (registry.wp_pointer_constraints) {5670zwp_pointer_constraints_v1_destroy(registry.wp_pointer_constraints);5671}56725673if (registry.wp_pointer_gestures) {5674zwp_pointer_gestures_v1_destroy(registry.wp_pointer_gestures);5675}56765677if (registry.wp_relative_pointer_manager) {5678zwp_relative_pointer_manager_v1_destroy(registry.wp_relative_pointer_manager);5679}56805681if (registry.wp_pointer_warp) {5682wp_pointer_warp_v1_destroy(registry.wp_pointer_warp);5683}56845685if (registry.xdg_activation) {5686xdg_activation_v1_destroy(registry.xdg_activation);5687}56885689if (registry.xdg_system_bell) {5690xdg_system_bell_v1_destroy(registry.xdg_system_bell);5691}56925693if (registry.xdg_toplevel_icon_manager) {5694xdg_toplevel_icon_manager_v1_destroy(registry.xdg_toplevel_icon_manager);56955696if (xdg_icon) {5697xdg_toplevel_icon_v1_destroy(xdg_icon);5698}56995700if (icon_buffer) {5701wl_buffer_destroy(icon_buffer);5702}5703}57045705if (registry.xdg_decoration_manager) {5706zxdg_decoration_manager_v1_destroy(registry.xdg_decoration_manager);5707}57085709if (registry.wp_cursor_shape_manager) {5710wp_cursor_shape_manager_v1_destroy(registry.wp_cursor_shape_manager);5711}57125713if (registry.wp_fractional_scale_manager) {5714wp_fractional_scale_manager_v1_destroy(registry.wp_fractional_scale_manager);5715}57165717if (registry.wp_viewporter) {5718wp_viewporter_destroy(registry.wp_viewporter);5719}57205721if (registry.xdg_wm_base) {5722xdg_wm_base_destroy(registry.xdg_wm_base);5723}57245725// NOTE: Deprecated.5726if (registry.xdg_exporter_v1) {5727zxdg_exporter_v1_destroy(registry.xdg_exporter_v1);5728}57295730if (registry.xdg_exporter_v2) {5731zxdg_exporter_v2_destroy(registry.xdg_exporter_v2);5732}5733if (registry.wl_shm) {5734wl_shm_destroy(registry.wl_shm);5735}57365737if (registry.wl_compositor) {5738wl_compositor_destroy(registry.wl_compositor);5739}57405741if (wl_registry) {5742wl_registry_destroy(wl_registry);5743}57445745wl_display_roundtrip(wl_display);57465747if (wl_display) {5748wl_display_disconnect(wl_display);5749}5750}57515752#endif // WAYLAND_ENABLED575357545755