Path: blob/master/platform/linuxbsd/wayland/wayland_thread.cpp
21052 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, FIFO_INTERFACE_NAME) == 0) {729registry->wp_fifo_manager_name = name;730}731732if (strcmp(interface, godot_embedding_compositor_interface.name) == 0) {733registry->godot_embedding_compositor = (struct godot_embedding_compositor *)wl_registry_bind(wl_registry, name, &godot_embedding_compositor_interface, 1);734registry->godot_embedding_compositor_name = name;735736godot_embedding_compositor_add_listener(registry->godot_embedding_compositor, &godot_embedding_compositor_listener, memnew(EmbeddingCompositorState));737}738}739740void WaylandThread::_wl_registry_on_global_remove(void *data, struct wl_registry *wl_registry, uint32_t name) {741RegistryState *registry = (RegistryState *)data;742ERR_FAIL_NULL(registry);743744if (name == registry->wl_shm_name) {745if (registry->wl_shm) {746wl_shm_destroy(registry->wl_shm);747registry->wl_shm = nullptr;748}749750registry->wl_shm_name = 0;751752return;753}754755// NOTE: Deprecated.756if (name == registry->xdg_exporter_v1_name) {757if (registry->xdg_exporter_v1) {758zxdg_exporter_v1_destroy(registry->xdg_exporter_v1);759registry->xdg_exporter_v1 = nullptr;760}761762registry->xdg_exporter_v1_name = 0;763764return;765}766767if (name == registry->xdg_exporter_v2_name) {768if (registry->xdg_exporter_v2) {769zxdg_exporter_v2_destroy(registry->xdg_exporter_v2);770registry->xdg_exporter_v2 = nullptr;771}772773registry->xdg_exporter_v2_name = 0;774775return;776}777778if (name == registry->wl_compositor_name) {779if (registry->wl_compositor) {780wl_compositor_destroy(registry->wl_compositor);781registry->wl_compositor = nullptr;782}783784registry->wl_compositor_name = 0;785786return;787}788789if (name == registry->wl_data_device_manager_name) {790if (registry->wl_data_device_manager) {791wl_data_device_manager_destroy(registry->wl_data_device_manager);792registry->wl_data_device_manager = nullptr;793}794795registry->wl_data_device_manager_name = 0;796797// This global is used to create some seat data. Let's clean it.798for (struct wl_seat *wl_seat : registry->wl_seats) {799SeatState *ss = wl_seat_get_seat_state(wl_seat);800ERR_FAIL_NULL(ss);801802if (ss->wl_data_device) {803wl_data_device_destroy(ss->wl_data_device);804ss->wl_data_device = nullptr;805}806807ss->wl_data_device = nullptr;808}809810return;811}812813if (name == registry->xdg_wm_base_name) {814if (registry->xdg_wm_base) {815xdg_wm_base_destroy(registry->xdg_wm_base);816registry->xdg_wm_base = nullptr;817}818819registry->xdg_wm_base_name = 0;820821return;822}823824if (name == registry->wp_viewporter_name) {825for (KeyValue<DisplayServer::WindowID, WindowState> &pair : registry->wayland_thread->windows) {826WindowState &ws = pair.value;827if (registry->wp_viewporter) {828wp_viewporter_destroy(registry->wp_viewporter);829registry->wp_viewporter = nullptr;830}831832if (ws.wp_viewport) {833wp_viewport_destroy(ws.wp_viewport);834ws.wp_viewport = nullptr;835}836}837838registry->wp_viewporter_name = 0;839840return;841}842843if (name == registry->wp_cursor_shape_manager_name) {844if (registry->wp_cursor_shape_manager) {845wp_cursor_shape_manager_v1_destroy(registry->wp_cursor_shape_manager);846registry->wp_cursor_shape_manager = nullptr;847}848849registry->wp_cursor_shape_manager_name = 0;850851for (struct wl_seat *wl_seat : registry->wl_seats) {852SeatState *ss = wl_seat_get_seat_state(wl_seat);853ERR_FAIL_NULL(ss);854855if (ss->wp_cursor_shape_device) {856wp_cursor_shape_device_v1_destroy(ss->wp_cursor_shape_device);857ss->wp_cursor_shape_device = nullptr;858}859}860}861862if (name == registry->wp_fractional_scale_manager_name) {863for (KeyValue<DisplayServer::WindowID, WindowState> &pair : registry->wayland_thread->windows) {864WindowState &ws = pair.value;865866if (registry->wp_fractional_scale_manager) {867wp_fractional_scale_manager_v1_destroy(registry->wp_fractional_scale_manager);868registry->wp_fractional_scale_manager = nullptr;869}870871if (ws.wp_fractional_scale) {872wp_fractional_scale_v1_destroy(ws.wp_fractional_scale);873ws.wp_fractional_scale = nullptr;874}875}876877registry->wp_fractional_scale_manager_name = 0;878}879880if (name == registry->xdg_decoration_manager_name) {881if (registry->xdg_decoration_manager) {882zxdg_decoration_manager_v1_destroy(registry->xdg_decoration_manager);883registry->xdg_decoration_manager = nullptr;884}885886registry->xdg_decoration_manager_name = 0;887888return;889}890891if (name == registry->xdg_system_bell_name) {892if (registry->xdg_system_bell) {893xdg_system_bell_v1_destroy(registry->xdg_system_bell);894registry->xdg_system_bell = nullptr;895}896897registry->xdg_system_bell_name = 0;898899return;900}901902if (name == registry->xdg_toplevel_icon_manager_name) {903if (registry->xdg_toplevel_icon_manager) {904xdg_toplevel_icon_manager_v1_destroy(registry->xdg_toplevel_icon_manager);905registry->xdg_toplevel_icon_manager = nullptr;906}907908if (registry->wayland_thread->xdg_icon) {909xdg_toplevel_icon_v1_destroy(registry->wayland_thread->xdg_icon);910}911912if (registry->wayland_thread->icon_buffer) {913wl_buffer_destroy(registry->wayland_thread->icon_buffer);914}915916registry->xdg_toplevel_icon_manager_name = 0;917918return;919}920921if (name == registry->xdg_activation_name) {922if (registry->xdg_activation) {923xdg_activation_v1_destroy(registry->xdg_activation);924registry->xdg_activation = nullptr;925}926927registry->xdg_activation_name = 0;928929return;930}931932if (name == registry->wp_primary_selection_device_manager_name) {933if (registry->wp_primary_selection_device_manager) {934zwp_primary_selection_device_manager_v1_destroy(registry->wp_primary_selection_device_manager);935registry->wp_primary_selection_device_manager = nullptr;936}937938registry->wp_primary_selection_device_manager_name = 0;939940// This global is used to create some seat data. Let's clean it.941for (struct wl_seat *wl_seat : registry->wl_seats) {942SeatState *ss = wl_seat_get_seat_state(wl_seat);943ERR_FAIL_NULL(ss);944945if (ss->wp_primary_selection_device) {946zwp_primary_selection_device_v1_destroy(ss->wp_primary_selection_device);947ss->wp_primary_selection_device = nullptr;948}949950if (ss->wp_primary_selection_source) {951zwp_primary_selection_source_v1_destroy(ss->wp_primary_selection_source);952ss->wp_primary_selection_source = nullptr;953}954955if (ss->wp_primary_selection_offer) {956memfree(wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer));957zwp_primary_selection_offer_v1_destroy(ss->wp_primary_selection_offer);958ss->wp_primary_selection_offer = nullptr;959}960}961962return;963}964965if (name == registry->wp_relative_pointer_manager_name) {966if (registry->wp_relative_pointer_manager) {967zwp_relative_pointer_manager_v1_destroy(registry->wp_relative_pointer_manager);968registry->wp_relative_pointer_manager = nullptr;969}970971registry->wp_relative_pointer_manager_name = 0;972973// This global is used to create some seat data. Let's clean it.974for (struct wl_seat *wl_seat : registry->wl_seats) {975SeatState *ss = wl_seat_get_seat_state(wl_seat);976ERR_FAIL_NULL(ss);977978if (ss->wp_relative_pointer) {979zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);980ss->wp_relative_pointer = nullptr;981}982}983984return;985}986987if (name == registry->wp_pointer_constraints_name) {988if (registry->wp_pointer_constraints) {989zwp_pointer_constraints_v1_destroy(registry->wp_pointer_constraints);990registry->wp_pointer_constraints = nullptr;991}992993registry->wp_pointer_constraints_name = 0;994995// This global is used to create some seat data. Let's clean it.996for (struct wl_seat *wl_seat : registry->wl_seats) {997SeatState *ss = wl_seat_get_seat_state(wl_seat);998ERR_FAIL_NULL(ss);9991000if (ss->wp_relative_pointer) {1001zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);1002ss->wp_relative_pointer = nullptr;1003}10041005if (ss->wp_locked_pointer) {1006zwp_locked_pointer_v1_destroy(ss->wp_locked_pointer);1007ss->wp_locked_pointer = nullptr;1008}10091010if (ss->wp_confined_pointer) {1011zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);1012ss->wp_confined_pointer = nullptr;1013}1014}10151016return;1017}10181019if (name == registry->wp_pointer_gestures_name) {1020if (registry->wp_pointer_gestures) {1021zwp_pointer_gestures_v1_destroy(registry->wp_pointer_gestures);1022}10231024registry->wp_pointer_gestures = nullptr;1025registry->wp_pointer_gestures_name = 0;10261027// This global is used to create some seat data. Let's clean it.1028for (struct wl_seat *wl_seat : registry->wl_seats) {1029SeatState *ss = wl_seat_get_seat_state(wl_seat);1030ERR_FAIL_NULL(ss);10311032if (ss->wp_pointer_gesture_pinch) {1033zwp_pointer_gesture_pinch_v1_destroy(ss->wp_pointer_gesture_pinch);1034ss->wp_pointer_gesture_pinch = nullptr;1035}1036}10371038return;1039}10401041if (name == registry->wp_idle_inhibit_manager_name) {1042if (registry->wp_idle_inhibit_manager) {1043zwp_idle_inhibit_manager_v1_destroy(registry->wp_idle_inhibit_manager);1044registry->wp_idle_inhibit_manager = nullptr;1045}10461047registry->wp_idle_inhibit_manager_name = 0;10481049return;1050}10511052if (name == registry->wp_tablet_manager_name) {1053if (registry->wp_tablet_manager) {1054zwp_tablet_manager_v2_destroy(registry->wp_tablet_manager);1055registry->wp_tablet_manager = nullptr;1056}10571058registry->wp_tablet_manager_name = 0;10591060// This global is used to create some seat data. Let's clean it.1061for (struct wl_seat *wl_seat : registry->wl_seats) {1062SeatState *ss = wl_seat_get_seat_state(wl_seat);1063ERR_FAIL_NULL(ss);10641065for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {1066TabletToolState *state = wp_tablet_tool_get_state(tool);1067if (state) {1068memdelete(state);1069}10701071zwp_tablet_tool_v2_destroy(tool);1072}10731074ss->tablet_tools.clear();1075}10761077return;1078}10791080if (name == registry->wp_text_input_manager_name) {1081if (registry->wp_text_input_manager) {1082zwp_text_input_manager_v3_destroy(registry->wp_text_input_manager);1083registry->wp_text_input_manager = nullptr;1084}10851086registry->wp_text_input_manager_name = 0;10871088for (struct wl_seat *wl_seat : registry->wl_seats) {1089SeatState *ss = wl_seat_get_seat_state(wl_seat);1090ERR_FAIL_NULL(ss);10911092zwp_text_input_v3_destroy(ss->wp_text_input);1093ss->wp_text_input = nullptr;1094}10951096return;1097}10981099{1100// Iterate through all of the seats to find if any got removed.1101List<struct wl_seat *>::Element *E = registry->wl_seats.front();1102while (E) {1103struct wl_seat *wl_seat = E->get();1104List<struct wl_seat *>::Element *N = E->next();11051106SeatState *ss = wl_seat_get_seat_state(wl_seat);1107ERR_FAIL_NULL(ss);11081109if (ss->wl_seat_name == name) {1110if (wl_seat) {1111wl_seat_destroy(wl_seat);1112}11131114if (ss->wl_data_device) {1115wl_data_device_destroy(ss->wl_data_device);1116}11171118if (ss->wp_tablet_seat) {1119zwp_tablet_seat_v2_destroy(ss->wp_tablet_seat);11201121for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {1122TabletToolState *state = wp_tablet_tool_get_state(tool);1123if (state) {1124memdelete(state);1125}11261127zwp_tablet_tool_v2_destroy(tool);1128}1129}11301131memdelete(ss);11321133registry->wl_seats.erase(E);1134return;1135}11361137E = N;1138}1139}11401141{1142// Iterate through all of the outputs to find if any got removed.1143// FIXME: This is a very bruteforce approach.1144List<struct wl_output *>::Element *it = registry->wl_outputs.front();1145while (it) {1146// Iterate through all of the screens to find if any got removed.1147struct wl_output *wl_output = it->get();1148ERR_FAIL_NULL(wl_output);11491150ScreenState *ss = wl_output_get_screen_state(wl_output);11511152if (ss->wl_output_name == name) {1153registry->wl_outputs.erase(it);11541155memdelete(ss);1156wl_output_destroy(wl_output);11571158return;1159}11601161it = it->next();1162}1163}11641165if (name == registry->wp_fifo_manager_name) {1166registry->wp_fifo_manager_name = 0;1167}11681169if (name == registry->godot_embedding_compositor_name) {1170registry->godot_embedding_compositor_name = 0;11711172EmbeddingCompositorState *es = godot_embedding_compositor_get_state(registry->godot_embedding_compositor);1173ERR_FAIL_NULL(es);11741175es->mapped_clients.clear();11761177for (struct godot_embedded_client *client : es->clients) {1178godot_embedded_client_destroy(client);1179}1180es->clients.clear();11811182memdelete(es);11831184godot_embedding_compositor_destroy(registry->godot_embedding_compositor);1185registry->godot_embedding_compositor = nullptr;1186}1187}11881189void WaylandThread::_wl_surface_on_enter(void *data, struct wl_surface *wl_surface, struct wl_output *wl_output) {1190if (!wl_output || !wl_proxy_is_godot((struct wl_proxy *)wl_output)) {1191// This won't have the right data bound to it. Not worth it and would probably1192// just break everything.1193return;1194}11951196WindowState *ws = (WindowState *)data;1197ERR_FAIL_NULL(ws);11981199DEBUG_LOG_WAYLAND_THREAD(vformat("Window entered output %x.", (size_t)wl_output));12001201ws->wl_outputs.insert(wl_output);12021203// Workaround for buffer scaling as there's no guaranteed way of knowing the1204// preferred scale.1205// TODO: Skip this branch for newer `wl_surface`s once we add support for1206// `wl_surface::preferred_buffer_scale`1207if (ws->preferred_fractional_scale == 0) {1208window_state_update_size(ws, ws->rect.size.width, ws->rect.size.height);1209}1210}12111212void WaylandThread::_frame_wl_callback_on_done(void *data, struct wl_callback *wl_callback, uint32_t callback_data) {1213wl_callback_destroy(wl_callback);12141215WindowState *ws = (WindowState *)data;1216ERR_FAIL_NULL(ws);1217ERR_FAIL_NULL(ws->wayland_thread);1218ERR_FAIL_NULL(ws->wl_surface);12191220ws->last_frame_time = OS::get_singleton()->get_ticks_usec();1221ws->wayland_thread->set_frame();12221223ws->frame_callback = wl_surface_frame(ws->wl_surface);1224wl_callback_add_listener(ws->frame_callback, &frame_wl_callback_listener, ws);12251226if (ws->wl_surface && ws->buffer_scale_changed) {1227// NOTE: We're only now setting the buffer scale as the idea is to get this1228// data committed together with the new frame, all by the rendering driver.1229// This is important because we might otherwise set an invalid combination of1230// buffer size and scale (e.g. odd size and 2x scale). We're pretty much1231// guaranteed to get a proper buffer in the next render loop as the rescaling1232// method also informs the engine of a "window rect change", triggering1233// rendering if needed.1234wl_surface_set_buffer_scale(ws->wl_surface, window_state_get_preferred_buffer_scale(ws));1235}1236}12371238void WaylandThread::_wl_surface_on_leave(void *data, struct wl_surface *wl_surface, struct wl_output *wl_output) {1239if (!wl_output || !wl_proxy_is_godot((struct wl_proxy *)wl_output)) {1240// This won't have the right data bound to it. Not worth it and would probably1241// just break everything.1242return;1243}12441245WindowState *ws = (WindowState *)data;1246ERR_FAIL_NULL(ws);12471248ws->wl_outputs.erase(wl_output);12491250DEBUG_LOG_WAYLAND_THREAD(vformat("Window left output %x.\n", (size_t)wl_output));1251}12521253// TODO: Add support to this event.1254void WaylandThread::_wl_surface_on_preferred_buffer_scale(void *data, struct wl_surface *wl_surface, int32_t factor) {1255}12561257// TODO: Add support to this event.1258void WaylandThread::_wl_surface_on_preferred_buffer_transform(void *data, struct wl_surface *wl_surface, uint32_t transform) {1259}12601261void 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) {1262ScreenState *ss = (ScreenState *)data;1263ERR_FAIL_NULL(ss);12641265ss->pending_data.position.x = x;12661267ss->pending_data.position.x = x;1268ss->pending_data.position.y = y;12691270ss->pending_data.physical_size.width = physical_width;1271ss->pending_data.physical_size.height = physical_height;12721273ss->pending_data.make.clear();1274ss->pending_data.make.append_utf8(make);1275ss->pending_data.model.clear();1276ss->pending_data.model.append_utf8(model);12771278// `wl_output::done` is a version 2 addition. We'll directly update the data1279// for compatibility.1280if (wl_output_get_version(wl_output) == 1) {1281ss->data = ss->pending_data;1282}1283}12841285void WaylandThread::_wl_output_on_mode(void *data, struct wl_output *wl_output, uint32_t flags, int32_t width, int32_t height, int32_t refresh) {1286ScreenState *ss = (ScreenState *)data;1287ERR_FAIL_NULL(ss);12881289ss->pending_data.size.width = width;1290ss->pending_data.size.height = height;12911292ss->pending_data.refresh_rate = refresh ? refresh / 1000.0f : -1;12931294// `wl_output::done` is a version 2 addition. We'll directly update the data1295// for compatibility.1296if (wl_output_get_version(wl_output) == 1) {1297ss->data = ss->pending_data;1298}1299}13001301// NOTE: The following `wl_output` events are only for version 2 onwards, so we1302// can assume that they're "atomic" (i.e. rely on the `wl_output::done` event).13031304void WaylandThread::_wl_output_on_done(void *data, struct wl_output *wl_output) {1305ScreenState *ss = (ScreenState *)data;1306ERR_FAIL_NULL(ss);13071308ss->data = ss->pending_data;13091310ss->wayland_thread->_update_scale(ss->data.scale);13111312DEBUG_LOG_WAYLAND_THREAD(vformat("Output %x done.", (size_t)wl_output));1313}13141315void WaylandThread::_wl_output_on_scale(void *data, struct wl_output *wl_output, int32_t factor) {1316ScreenState *ss = (ScreenState *)data;1317ERR_FAIL_NULL(ss);13181319ss->pending_data.scale = factor;13201321DEBUG_LOG_WAYLAND_THREAD(vformat("Output %x scale %d", (size_t)wl_output, factor));1322}13231324void WaylandThread::_wl_output_on_name(void *data, struct wl_output *wl_output, const char *name) {1325}13261327void WaylandThread::_wl_output_on_description(void *data, struct wl_output *wl_output, const char *description) {1328}13291330void WaylandThread::_xdg_wm_base_on_ping(void *data, struct xdg_wm_base *xdg_wm_base, uint32_t serial) {1331xdg_wm_base_pong(xdg_wm_base, serial);1332}13331334void WaylandThread::_xdg_surface_on_configure(void *data, struct xdg_surface *xdg_surface, uint32_t serial) {1335xdg_surface_ack_configure(xdg_surface, serial);13361337WindowState *ws = (WindowState *)data;1338ERR_FAIL_NULL(ws);13391340DEBUG_LOG_WAYLAND_THREAD(vformat("xdg surface on configure rect %s", ws->rect));1341}13421343void WaylandThread::_xdg_toplevel_on_configure(void *data, struct xdg_toplevel *xdg_toplevel, int32_t width, int32_t height, struct wl_array *states) {1344WindowState *ws = (WindowState *)data;1345ERR_FAIL_NULL(ws);13461347// Expect the window to be in a plain state. It will get properly set if the1348// compositor reports otherwise below.1349ws->mode = DisplayServer::WINDOW_MODE_WINDOWED;1350ws->maximized = false;1351ws->fullscreen = false;1352ws->resizing = false;1353ws->tiled_left = false;1354ws->tiled_right = false;1355ws->tiled_top = false;1356ws->tiled_bottom = false;1357ws->suspended = false;13581359uint32_t *state = nullptr;1360wl_array_for_each(state, states) {1361switch (*state) {1362case XDG_TOPLEVEL_STATE_MAXIMIZED: {1363ws->mode = DisplayServer::WINDOW_MODE_MAXIMIZED;1364ws->maximized = true;1365} break;13661367case XDG_TOPLEVEL_STATE_FULLSCREEN: {1368ws->mode = DisplayServer::WINDOW_MODE_FULLSCREEN;1369ws->fullscreen = true;1370} break;13711372case XDG_TOPLEVEL_STATE_RESIZING: {1373ws->resizing = true;1374} break;13751376case XDG_TOPLEVEL_STATE_TILED_LEFT: {1377ws->tiled_left = true;1378} break;13791380case XDG_TOPLEVEL_STATE_TILED_RIGHT: {1381ws->tiled_right = true;1382} break;13831384case XDG_TOPLEVEL_STATE_TILED_TOP: {1385ws->tiled_top = true;1386} break;13871388case XDG_TOPLEVEL_STATE_TILED_BOTTOM: {1389ws->tiled_bottom = true;1390} break;13911392case XDG_TOPLEVEL_STATE_SUSPENDED: {1393ws->suspended = true;1394} break;13951396default: {1397// We don't care about the other states (for now).1398} break;1399}1400}14011402if (width != 0 && height != 0) {1403window_state_update_size(ws, width, height);1404}14051406DEBUG_LOG_WAYLAND_THREAD(vformat("XDG toplevel on configure width %d height %d.", width, height));1407}14081409void WaylandThread::_xdg_toplevel_on_close(void *data, struct xdg_toplevel *xdg_toplevel) {1410WindowState *ws = (WindowState *)data;1411ERR_FAIL_NULL(ws);14121413Ref<WindowEventMessage> msg;1414msg.instantiate();1415msg->id = ws->id;1416msg->event = DisplayServer::WINDOW_EVENT_CLOSE_REQUEST;1417ws->wayland_thread->push_message(msg);1418}14191420void WaylandThread::_xdg_toplevel_on_configure_bounds(void *data, struct xdg_toplevel *xdg_toplevel, int32_t width, int32_t height) {1421}14221423void WaylandThread::_xdg_toplevel_on_wm_capabilities(void *data, struct xdg_toplevel *xdg_toplevel, struct wl_array *capabilities) {1424WindowState *ws = (WindowState *)data;1425ERR_FAIL_NULL(ws);14261427ws->can_maximize = false;1428ws->can_fullscreen = false;1429ws->can_minimize = false;14301431uint32_t *capability = nullptr;1432wl_array_for_each(capability, capabilities) {1433switch (*capability) {1434case XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE: {1435ws->can_maximize = true;1436} break;1437case XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN: {1438ws->can_fullscreen = true;1439} break;14401441case XDG_TOPLEVEL_WM_CAPABILITIES_MINIMIZE: {1442ws->can_minimize = true;1443} break;14441445default: {1446} break;1447}1448}1449}14501451void WaylandThread::_xdg_popup_on_configure(void *data, struct xdg_popup *xdg_popup, int32_t x, int32_t y, int32_t width, int32_t height) {1452WindowState *ws = (WindowState *)data;1453ERR_FAIL_NULL(ws);14541455if (width != 0 && height != 0) {1456window_state_update_size(ws, width, height);1457}14581459WindowState *parent = ws->wayland_thread->window_get_state(ws->parent_id);1460ERR_FAIL_NULL(parent);14611462Point2i pos = Point2i(x, y);1463#ifdef LIBDECOR_ENABLED1464if (parent->libdecor_frame) {1465int translated_x = x;1466int translated_y = y;1467libdecor_frame_translate_coordinate(parent->libdecor_frame, x, y, &translated_x, &translated_y);14681469pos.x = translated_x;1470pos.y = translated_y;1471}1472#endif14731474// Looks like the position returned here is relative to the parent. We have to1475// accumulate it or there's gonna be a lot of confusion godot-side.1476pos += parent->rect.position;14771478if (ws->rect.position != pos) {1479DEBUG_LOG_WAYLAND_THREAD(vformat("Repositioning popup %d from %s to %s", ws->id, ws->rect.position, pos));14801481double parent_scale = window_state_get_scale_factor(parent);14821483ws->rect.position = pos;14841485Ref<WindowRectMessage> rect_msg;1486rect_msg.instantiate();1487rect_msg->id = ws->id;1488rect_msg->rect.position = scale_vector2i(ws->rect.position, parent_scale);1489rect_msg->rect.size = scale_vector2i(ws->rect.size, parent_scale);14901491ws->wayland_thread->push_message(rect_msg);1492}14931494DEBUG_LOG_WAYLAND_THREAD(vformat("xdg popup on configure x%d y%d w%d h%d", x, y, width, height));1495}14961497void WaylandThread::_xdg_popup_on_popup_done(void *data, struct xdg_popup *xdg_popup) {1498WindowState *ws = (WindowState *)data;1499ERR_FAIL_NULL(ws);15001501Ref<WindowEventMessage> ev_msg;1502ev_msg.instantiate();1503ev_msg->id = ws->id;1504ev_msg->event = DisplayServer::WINDOW_EVENT_FORCE_CLOSE;15051506ws->wayland_thread->push_message(ev_msg);1507}15081509void WaylandThread::_xdg_popup_on_repositioned(void *data, struct xdg_popup *xdg_popup, uint32_t token) {1510DEBUG_LOG_WAYLAND_THREAD(vformat("stub xdg popup repositioned %x", token));1511}15121513// NOTE: Deprecated.1514void WaylandThread::_xdg_exported_v1_on_handle(void *data, zxdg_exported_v1 *exported, const char *handle) {1515WindowState *ws = (WindowState *)data;1516ERR_FAIL_NULL(ws);15171518ws->exported_handle = vformat("wayland:%s", String::utf8(handle));1519}15201521void WaylandThread::_xdg_exported_v2_on_handle(void *data, zxdg_exported_v2 *exported, const char *handle) {1522WindowState *ws = (WindowState *)data;1523ERR_FAIL_NULL(ws);15241525ws->exported_handle = vformat("wayland:%s", String::utf8(handle));1526}15271528void WaylandThread::_xdg_toplevel_decoration_on_configure(void *data, struct zxdg_toplevel_decoration_v1 *xdg_toplevel_decoration, uint32_t mode) {1529if (mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE) {1530#ifdef LIBDECOR_ENABLED1531WARN_PRINT_ONCE("Native client side decorations are not yet supported without libdecor!");1532#else1533WARN_PRINT_ONCE("Native client side decorations are not yet supported!");1534#endif // LIBDECOR_ENABLED1535}1536}15371538#ifdef LIBDECOR_ENABLED1539void WaylandThread::libdecor_on_error(struct libdecor *context, enum libdecor_error error, const char *message) {1540ERR_PRINT(vformat("libdecor error %d: %s", error, message));1541}15421543// NOTE: This is pretty much a reimplementation of _xdg_surface_on_configure1544// and _xdg_toplevel_on_configure. Libdecor really likes wrapping everything,1545// forcing us to do stuff like this.1546void WaylandThread::libdecor_frame_on_configure(struct libdecor_frame *frame, struct libdecor_configuration *configuration, void *user_data) {1547WindowState *ws = (WindowState *)user_data;1548ERR_FAIL_NULL(ws);15491550int width = 0;1551int height = 0;15521553ws->pending_libdecor_configuration = configuration;15541555if (!libdecor_configuration_get_content_size(configuration, frame, &width, &height)) {1556// The configuration doesn't have a size. We'll use the one already set in the window.1557width = ws->rect.size.width;1558height = ws->rect.size.height;1559}15601561ERR_FAIL_COND_MSG(width == 0 || height == 0, "Window has invalid size.");15621563libdecor_window_state window_state = LIBDECOR_WINDOW_STATE_NONE;15641565// Expect the window to be in a plain state. It will get properly set if the1566// compositor reports otherwise below.1567ws->mode = DisplayServer::WINDOW_MODE_WINDOWED;1568ws->maximized = false;1569ws->fullscreen = false;1570ws->resizing = false;1571ws->tiled_left = false;1572ws->tiled_right = false;1573ws->tiled_top = false;1574ws->tiled_bottom = false;1575ws->suspended = false;15761577if (libdecor_configuration_get_window_state(configuration, &window_state)) {1578if (window_state & LIBDECOR_WINDOW_STATE_MAXIMIZED) {1579ws->mode = DisplayServer::WINDOW_MODE_MAXIMIZED;1580ws->maximized = true;1581}15821583if (window_state & LIBDECOR_WINDOW_STATE_FULLSCREEN) {1584ws->mode = DisplayServer::WINDOW_MODE_FULLSCREEN;1585ws->fullscreen = true;1586}15871588// libdecor doesn't have the resizing state for whatever reason.15891590if (window_state & LIBDECOR_WINDOW_STATE_TILED_LEFT) {1591ws->tiled_left = true;1592}15931594if (window_state & LIBDECOR_WINDOW_STATE_TILED_RIGHT) {1595ws->tiled_right = true;1596}15971598if (window_state & LIBDECOR_WINDOW_STATE_TILED_TOP) {1599ws->tiled_top = true;1600}16011602if (window_state & LIBDECOR_WINDOW_STATE_TILED_BOTTOM) {1603ws->tiled_bottom = true;1604}16051606if (window_state & LIBDECOR_WINDOW_STATE_SUSPENDED) {1607ws->suspended = true;1608}1609}16101611window_state_update_size(ws, width, height);16121613DEBUG_LOG_WAYLAND_THREAD(vformat("libdecor frame on configure rect %s", ws->rect));1614}16151616void WaylandThread::libdecor_frame_on_close(struct libdecor_frame *frame, void *user_data) {1617WindowState *ws = (WindowState *)user_data;1618ERR_FAIL_NULL(ws);16191620Ref<WindowEventMessage> winevent_msg;1621winevent_msg.instantiate();1622winevent_msg->id = ws->id;1623winevent_msg->event = DisplayServer::WINDOW_EVENT_CLOSE_REQUEST;16241625ws->wayland_thread->push_message(winevent_msg);16261627DEBUG_LOG_WAYLAND_THREAD("libdecor frame on close");1628}16291630void WaylandThread::libdecor_frame_on_commit(struct libdecor_frame *frame, void *user_data) {1631// We're skipping this as we don't really care about libdecor's commit for1632// atomicity reasons. See `_frame_wl_callback_on_done` for more info.16331634DEBUG_LOG_WAYLAND_THREAD("libdecor frame on commit");1635}16361637void WaylandThread::libdecor_frame_on_dismiss_popup(struct libdecor_frame *frame, const char *seat_name, void *user_data) {1638}1639#endif // LIBDECOR_ENABLED16401641void WaylandThread::_wl_seat_on_capabilities(void *data, struct wl_seat *wl_seat, uint32_t capabilities) {1642SeatState *ss = (SeatState *)data;16431644ERR_FAIL_NULL(ss);16451646// TODO: Handle touch.16471648// Pointer handling.1649if (capabilities & WL_SEAT_CAPABILITY_POINTER) {1650if (!ss->wl_pointer) {1651ss->cursor_surface = wl_compositor_create_surface(ss->registry->wl_compositor);1652wl_surface_commit(ss->cursor_surface);16531654ss->wl_pointer = wl_seat_get_pointer(wl_seat);1655wl_pointer_add_listener(ss->wl_pointer, &wl_pointer_listener, ss);16561657if (ss->registry->wp_cursor_shape_manager) {1658ss->wp_cursor_shape_device = wp_cursor_shape_manager_v1_get_pointer(ss->registry->wp_cursor_shape_manager, ss->wl_pointer);1659}16601661if (ss->registry->wp_relative_pointer_manager) {1662ss->wp_relative_pointer = zwp_relative_pointer_manager_v1_get_relative_pointer(ss->registry->wp_relative_pointer_manager, ss->wl_pointer);1663zwp_relative_pointer_v1_add_listener(ss->wp_relative_pointer, &wp_relative_pointer_listener, ss);1664}16651666if (ss->registry->wp_pointer_gestures) {1667ss->wp_pointer_gesture_pinch = zwp_pointer_gestures_v1_get_pinch_gesture(ss->registry->wp_pointer_gestures, ss->wl_pointer);1668zwp_pointer_gesture_pinch_v1_add_listener(ss->wp_pointer_gesture_pinch, &wp_pointer_gesture_pinch_listener, ss);1669}16701671// TODO: Constrain new pointers if the global mouse mode is constrained.1672}1673} else {1674if (ss->cursor_frame_callback) {1675// Just in case. I got bitten by weird race-like conditions already.1676wl_callback_set_user_data(ss->cursor_frame_callback, nullptr);16771678wl_callback_destroy(ss->cursor_frame_callback);1679ss->cursor_frame_callback = nullptr;1680}16811682if (ss->cursor_surface) {1683wl_surface_destroy(ss->cursor_surface);1684ss->cursor_surface = nullptr;1685}16861687if (ss->wl_pointer) {1688wl_pointer_destroy(ss->wl_pointer);1689ss->wl_pointer = nullptr;1690}16911692if (ss->wp_cursor_shape_device) {1693wp_cursor_shape_device_v1_destroy(ss->wp_cursor_shape_device);1694ss->wp_cursor_shape_device = nullptr;1695}16961697if (ss->wp_relative_pointer) {1698zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);1699ss->wp_relative_pointer = nullptr;1700}17011702if (ss->wp_confined_pointer) {1703zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);1704ss->wp_confined_pointer = nullptr;1705}17061707if (ss->wp_locked_pointer) {1708zwp_locked_pointer_v1_destroy(ss->wp_locked_pointer);1709ss->wp_locked_pointer = nullptr;1710}1711}17121713// Keyboard handling.1714if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {1715if (!ss->wl_keyboard) {1716ss->xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);1717ERR_FAIL_NULL(ss->xkb_context);17181719ss->wl_keyboard = wl_seat_get_keyboard(wl_seat);1720wl_keyboard_add_listener(ss->wl_keyboard, &wl_keyboard_listener, ss);1721}1722} else {1723if (ss->xkb_context) {1724xkb_context_unref(ss->xkb_context);1725ss->xkb_context = nullptr;1726}17271728if (ss->xkb_compose_table) {1729xkb_compose_table_unref(ss->xkb_compose_table);1730ss->xkb_compose_table = nullptr;1731}17321733if (ss->xkb_compose_state) {1734xkb_compose_state_unref(ss->xkb_compose_state);1735ss->xkb_compose_state = nullptr;1736}17371738if (ss->xkb_keymap) {1739xkb_keymap_unref(ss->xkb_keymap);1740ss->xkb_keymap = nullptr;1741}17421743if (ss->xkb_state) {1744xkb_state_unref(ss->xkb_state);1745ss->xkb_state = nullptr;1746}17471748if (ss->wl_keyboard) {1749wl_keyboard_destroy(ss->wl_keyboard);1750ss->wl_keyboard = nullptr;1751}1752}1753}17541755void WaylandThread::_wl_seat_on_name(void *data, struct wl_seat *wl_seat, const char *name) {1756}17571758void WaylandThread::_cursor_frame_callback_on_done(void *data, struct wl_callback *wl_callback, uint32_t time_ms) {1759wl_callback_destroy(wl_callback);17601761SeatState *ss = (SeatState *)data;1762ERR_FAIL_NULL(ss);17631764ss->cursor_frame_callback = nullptr;17651766ss->cursor_time_ms = time_ms;17671768seat_state_update_cursor(ss);1769}17701771void 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) {1772WindowState *ws = wl_surface_get_window_state(surface);1773if (!ws) {1774return;1775}17761777SeatState *ss = (SeatState *)data;1778ERR_FAIL_NULL(ss);17791780ERR_FAIL_NULL(ss->cursor_surface);17811782PointerData &pd = ss->pointer_data_buffer;17831784ss->pointer_enter_serial = serial;1785pd.pointed_id = ws->id;1786pd.last_pointed_id = ws->id;1787pd.position.x = wl_fixed_to_double(surface_x);1788pd.position.y = wl_fixed_to_double(surface_y);17891790seat_state_update_cursor(ss);17911792DEBUG_LOG_WAYLAND_THREAD(vformat("Pointer entered window %d.", ws->id));17931794if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1795_wl_pointer_on_frame(data, wl_pointer);1796}1797}17981799void WaylandThread::_wl_pointer_on_leave(void *data, struct wl_pointer *wl_pointer, uint32_t serial, struct wl_surface *surface) {1800// NOTE: `surface` will probably be null when the surface is destroyed.1801// See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/3661802// See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/46518031804SeatState *ss = (SeatState *)data;1805ERR_FAIL_NULL(ss);18061807PointerData &pd = ss->pointer_data_buffer;18081809if (pd.pointed_id == DisplayServer::INVALID_WINDOW_ID) {1810// We're probably on a decoration or some other third-party thing.1811return;1812}18131814DisplayServer::WindowID id = pd.pointed_id;18151816pd.pointed_id = DisplayServer::INVALID_WINDOW_ID;1817pd.pressed_button_mask.clear();18181819DEBUG_LOG_WAYLAND_THREAD(vformat("Pointer left window %d.", id));18201821if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1822_wl_pointer_on_frame(data, wl_pointer);1823}1824}18251826void 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) {1827SeatState *ss = (SeatState *)data;1828ERR_FAIL_NULL(ss);18291830PointerData &pd = ss->pointer_data_buffer;18311832pd.position.x = wl_fixed_to_double(surface_x);1833pd.position.y = wl_fixed_to_double(surface_y);18341835pd.motion_time = time;18361837if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1838_wl_pointer_on_frame(data, wl_pointer);1839}1840}18411842void WaylandThread::_wl_pointer_on_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t state) {1843SeatState *ss = (SeatState *)data;1844ERR_FAIL_NULL(ss);18451846PointerData &pd = ss->pointer_data_buffer;18471848MouseButton button_pressed = MouseButton::NONE;18491850switch (button) {1851case BTN_LEFT:1852button_pressed = MouseButton::LEFT;1853break;18541855case BTN_MIDDLE:1856button_pressed = MouseButton::MIDDLE;1857break;18581859case BTN_RIGHT:1860button_pressed = MouseButton::RIGHT;1861break;18621863case BTN_EXTRA:1864button_pressed = MouseButton::MB_XBUTTON1;1865break;18661867case BTN_SIDE:1868button_pressed = MouseButton::MB_XBUTTON2;1869break;18701871default: {1872}1873}18741875MouseButtonMask mask = mouse_button_to_mask(button_pressed);18761877if (state & WL_POINTER_BUTTON_STATE_PRESSED) {1878pd.pressed_button_mask.set_flag(mask);1879pd.last_button_pressed = button_pressed;1880pd.double_click_begun = true;1881} else {1882pd.pressed_button_mask.clear_flag(mask);1883}18841885pd.button_time = time;1886pd.button_serial = serial;18871888if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1889_wl_pointer_on_frame(data, wl_pointer);1890}1891}18921893void WaylandThread::_wl_pointer_on_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {1894SeatState *ss = (SeatState *)data;1895ERR_FAIL_NULL(ss);18961897PointerData &pd = ss->pointer_data_buffer;18981899switch (axis) {1900case WL_POINTER_AXIS_VERTICAL_SCROLL: {1901pd.scroll_vector.y = wl_fixed_to_double(value);1902} break;19031904case WL_POINTER_AXIS_HORIZONTAL_SCROLL: {1905pd.scroll_vector.x = wl_fixed_to_double(value);1906} break;1907}19081909pd.button_time = time;19101911if (wl_pointer_get_version(wl_pointer) < WL_POINTER_FRAME_SINCE_VERSION) {1912_wl_pointer_on_frame(data, wl_pointer);1913}1914}19151916void WaylandThread::_wl_pointer_on_frame(void *data, struct wl_pointer *wl_pointer) {1917SeatState *ss = (SeatState *)data;1918ERR_FAIL_NULL(ss);19191920WaylandThread *wayland_thread = ss->wayland_thread;1921ERR_FAIL_NULL(wayland_thread);19221923PointerData &old_pd = ss->pointer_data;1924PointerData &pd = ss->pointer_data_buffer;19251926if (pd.pointed_id != old_pd.pointed_id) {1927if (old_pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {1928Ref<WindowEventMessage> msg;1929msg.instantiate();1930msg->id = old_pd.pointed_id;1931msg->event = DisplayServer::WINDOW_EVENT_MOUSE_EXIT;19321933wayland_thread->push_message(msg);1934}19351936if (pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {1937Ref<WindowEventMessage> msg;1938msg.instantiate();1939msg->id = pd.pointed_id;1940msg->event = DisplayServer::WINDOW_EVENT_MOUSE_ENTER;19411942wayland_thread->push_message(msg);1943}1944}19451946WindowState *ws = nullptr;19471948// NOTE: At least on sway, with wl_pointer version 5 or greater,1949// wl_pointer::leave might be emitted with other events (like1950// wl_pointer::button) within the same wl_pointer::frame. Because of this, we1951// need to account for when the currently pointed window might be invalid1952// (third-party or even none) and fall back to the old one.1953if (pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {1954ws = ss->wayland_thread->window_get_state(pd.pointed_id);1955ERR_FAIL_NULL(ws);1956} else if (old_pd.pointed_id != DisplayServer::INVALID_WINDOW_ID) {1957ws = ss->wayland_thread->window_get_state(old_pd.pointed_id);1958ERR_FAIL_NULL(ws);1959}19601961if (ws == nullptr) {1962// We're probably on a decoration or some other third-party thing. Let's1963// "commit" the data and call it a day.1964old_pd = pd;1965return;1966}19671968double scale = window_state_get_scale_factor(ws);19691970wayland_thread->_set_current_seat(ss->wl_seat);19711972if (old_pd.motion_time != pd.motion_time || old_pd.relative_motion_time != pd.relative_motion_time) {1973Ref<InputEventMouseMotion> mm;1974mm.instantiate();19751976// Set all pressed modifiers.1977mm->set_shift_pressed(ss->shift_pressed);1978mm->set_ctrl_pressed(ss->ctrl_pressed);1979mm->set_alt_pressed(ss->alt_pressed);1980mm->set_meta_pressed(ss->meta_pressed);19811982mm->set_window_id(ws->id);19831984mm->set_button_mask(pd.pressed_button_mask);19851986mm->set_position(pd.position * scale);1987mm->set_global_position(pd.position * scale);19881989Vector2 pos_delta = (pd.position - old_pd.position) * scale;19901991if (old_pd.relative_motion_time != pd.relative_motion_time) {1992uint32_t time_delta = pd.relative_motion_time - old_pd.relative_motion_time;19931994mm->set_relative(pd.relative_motion * scale);1995mm->set_velocity((Vector2)pos_delta / time_delta);1996} else {1997// The spec includes the possibility of having motion events without an1998// associated relative motion event. If that's the case, fallback to a1999// simple delta of the position. The captured mouse won't report the2000// relative speed anymore though.2001uint32_t time_delta = pd.motion_time - old_pd.motion_time;20022003mm->set_relative(pos_delta);2004mm->set_velocity((Vector2)pos_delta / time_delta);2005}2006mm->set_relative_screen_position(mm->get_relative());2007mm->set_screen_velocity(mm->get_velocity());20082009Ref<InputEventMessage> msg;2010msg.instantiate();20112012msg->event = mm;20132014wayland_thread->push_message(msg);2015}20162017if (pd.discrete_scroll_vector_120 - old_pd.discrete_scroll_vector_120 != Vector2i()) {2018// This is a discrete scroll (eg. from a scroll wheel), so we'll just emit2019// scroll wheel buttons.2020if (pd.scroll_vector.y != 0) {2021MouseButton button = pd.scroll_vector.y > 0 ? MouseButton::WHEEL_DOWN : MouseButton::WHEEL_UP;2022pd.pressed_button_mask.set_flag(mouse_button_to_mask(button));2023}20242025if (pd.scroll_vector.x != 0) {2026MouseButton button = pd.scroll_vector.x > 0 ? MouseButton::WHEEL_RIGHT : MouseButton::WHEEL_LEFT;2027pd.pressed_button_mask.set_flag(mouse_button_to_mask(button));2028}2029} else {2030if (pd.scroll_vector - old_pd.scroll_vector != Vector2()) {2031// This is a continuous scroll, so we'll emit a pan gesture.2032Ref<InputEventPanGesture> pg;2033pg.instantiate();20342035// Set all pressed modifiers.2036pg->set_shift_pressed(ss->shift_pressed);2037pg->set_ctrl_pressed(ss->ctrl_pressed);2038pg->set_alt_pressed(ss->alt_pressed);2039pg->set_meta_pressed(ss->meta_pressed);20402041pg->set_position(pd.position * scale);20422043pg->set_window_id(ws->id);20442045pg->set_delta(pd.scroll_vector);20462047Ref<InputEventMessage> msg;2048msg.instantiate();20492050msg->event = pg;20512052wayland_thread->push_message(msg);2053}2054}20552056if (old_pd.pressed_button_mask != pd.pressed_button_mask) {2057BitField<MouseButtonMask> pressed_mask_delta = old_pd.pressed_button_mask.get_different(pd.pressed_button_mask);20582059const MouseButton buttons_to_test[] = {2060MouseButton::LEFT,2061MouseButton::MIDDLE,2062MouseButton::RIGHT,2063MouseButton::WHEEL_UP,2064MouseButton::WHEEL_DOWN,2065MouseButton::WHEEL_LEFT,2066MouseButton::WHEEL_RIGHT,2067MouseButton::MB_XBUTTON1,2068MouseButton::MB_XBUTTON2,2069};20702071for (MouseButton test_button : buttons_to_test) {2072MouseButtonMask test_button_mask = mouse_button_to_mask(test_button);2073if (pressed_mask_delta.has_flag(test_button_mask)) {2074Ref<InputEventMouseButton> mb;2075mb.instantiate();20762077// Set all pressed modifiers.2078mb->set_shift_pressed(ss->shift_pressed);2079mb->set_ctrl_pressed(ss->ctrl_pressed);2080mb->set_alt_pressed(ss->alt_pressed);2081mb->set_meta_pressed(ss->meta_pressed);20822083mb->set_window_id(ws->id);2084mb->set_position(pd.position * scale);2085mb->set_global_position(pd.position * scale);20862087if (test_button == MouseButton::WHEEL_UP || test_button == MouseButton::WHEEL_DOWN) {2088// If this is a discrete scroll, specify how many "clicks" it did for this2089// pointer frame.2090mb->set_factor(Math::abs(pd.discrete_scroll_vector_120.y / (float)120));2091}20922093if (test_button == MouseButton::WHEEL_RIGHT || test_button == MouseButton::WHEEL_LEFT) {2094// If this is a discrete scroll, specify how many "clicks" it did for this2095// pointer frame.2096mb->set_factor(std::abs(pd.discrete_scroll_vector_120.x / (float)120));2097}20982099mb->set_button_mask(pd.pressed_button_mask);21002101mb->set_button_index(test_button);2102mb->set_pressed(pd.pressed_button_mask.has_flag(test_button_mask));21032104// We have to set the last position pressed here as we can't take for2105// granted what the individual events might have seen due to them not having2106// a guaranteed order.2107if (mb->is_pressed()) {2108pd.last_pressed_position = pd.position;2109}21102111if (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) {2112pd.double_click_begun = false;2113mb->set_double_click(true);2114}21152116Ref<InputEventMessage> msg;2117msg.instantiate();21182119msg->event = mb;21202121wayland_thread->push_message(msg);21222123// Send an event resetting immediately the wheel key.2124// Wayland specification defines axis_stop events as optional and says to2125// treat all axis events as unterminated. As such, we have to manually do2126// it ourselves.2127if (test_button == MouseButton::WHEEL_UP || test_button == MouseButton::WHEEL_DOWN || test_button == MouseButton::WHEEL_LEFT || test_button == MouseButton::WHEEL_RIGHT) {2128// FIXME: This is ugly, I can't find a clean way to clone an InputEvent.2129// This works for now, despite being horrible.2130Ref<InputEventMouseButton> wh_up;2131wh_up.instantiate();21322133wh_up->set_window_id(ws->id);2134wh_up->set_position(pd.position * scale);2135wh_up->set_global_position(pd.position * scale);21362137// We have to unset the button to avoid it getting stuck.2138pd.pressed_button_mask.clear_flag(test_button_mask);2139wh_up->set_button_mask(pd.pressed_button_mask);21402141wh_up->set_button_index(test_button);2142wh_up->set_pressed(false);21432144Ref<InputEventMessage> msg_up;2145msg_up.instantiate();2146msg_up->event = wh_up;2147wayland_thread->push_message(msg_up);2148}2149}2150}2151}21522153// Reset the scroll vectors as we already handled them.2154pd.scroll_vector = Vector2();2155pd.discrete_scroll_vector_120 = Vector2i();21562157// Update the data all getters read. Wayland's specification requires us to do2158// this, since all pointer actions are sent in individual events.2159old_pd = pd;2160}21612162void WaylandThread::_wl_pointer_on_axis_source(void *data, struct wl_pointer *wl_pointer, uint32_t axis_source) {2163SeatState *ss = (SeatState *)data;2164ERR_FAIL_NULL(ss);21652166ss->pointer_data_buffer.scroll_type = axis_source;2167}21682169void WaylandThread::_wl_pointer_on_axis_stop(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis) {2170}21712172// NOTE: This event is deprecated since version 8 and superseded by2173// `wl_pointer::axis_value120`. This thus converts the data to its2174// fraction-of-120 format.2175void WaylandThread::_wl_pointer_on_axis_discrete(void *data, struct wl_pointer *wl_pointer, uint32_t axis, int32_t discrete) {2176SeatState *ss = (SeatState *)data;2177ERR_FAIL_NULL(ss);21782179PointerData &pd = ss->pointer_data_buffer;21802181// NOTE: We can allow ourselves to not accumulate this data (and thus just2182// assign it) as the spec guarantees only one event per axis type.21832184if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) {2185pd.discrete_scroll_vector_120.y = discrete * 120;2186}21872188if (axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL) {2189pd.discrete_scroll_vector_120.x = discrete * 120;2190}2191}21922193// Supersedes `wl_pointer::axis_discrete` Since version 8.2194void WaylandThread::_wl_pointer_on_axis_value120(void *data, struct wl_pointer *wl_pointer, uint32_t axis, int32_t value120) {2195SeatState *ss = (SeatState *)data;2196ERR_FAIL_NULL(ss);21972198PointerData &pd = ss->pointer_data_buffer;21992200if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) {2201pd.discrete_scroll_vector_120.y += value120;2202}22032204if (axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL) {2205pd.discrete_scroll_vector_120.x += value120;2206}2207}22082209// TODO: Add support to this event.2210void WaylandThread::_wl_pointer_on_axis_relative_direction(void *data, struct wl_pointer *wl_pointer, uint32_t axis, uint32_t direction) {2211}22122213void WaylandThread::_wl_keyboard_on_keymap(void *data, struct wl_keyboard *wl_keyboard, uint32_t format, int32_t fd, uint32_t size) {2214ERR_FAIL_COND_MSG(format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, "Unsupported keymap format announced from the Wayland compositor.");22152216SeatState *ss = (SeatState *)data;2217ERR_FAIL_NULL(ss);22182219if (ss->keymap_buffer) {2220// We have already a mapped buffer, so we unmap it. There's no need to reset2221// its pointer or size, as we're gonna set them below.2222munmap((void *)ss->keymap_buffer, ss->keymap_buffer_size);2223ss->keymap_buffer = nullptr;2224}22252226ss->keymap_buffer = (const char *)mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);2227ss->keymap_buffer_size = size;22282229xkb_keymap_unref(ss->xkb_keymap);2230ss->xkb_keymap = xkb_keymap_new_from_string(ss->xkb_context, ss->keymap_buffer,2231XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);22322233xkb_state_unref(ss->xkb_state);2234ss->xkb_state = xkb_state_new(ss->xkb_keymap);22352236xkb_compose_table_unref(ss->xkb_compose_table);2237const char *locale = getenv("LC_ALL");2238if (!locale || !*locale) {2239locale = getenv("LC_CTYPE");2240}2241if (!locale || !*locale) {2242locale = getenv("LANG");2243}2244if (!locale || !*locale) {2245locale = "C";2246}2247ss->xkb_compose_table = xkb_compose_table_new_from_locale(ss->xkb_context, locale, XKB_COMPOSE_COMPILE_NO_FLAGS);22482249xkb_compose_state_unref(ss->xkb_compose_state);2250ss->xkb_compose_state = xkb_compose_state_new(ss->xkb_compose_table, XKB_COMPOSE_STATE_NO_FLAGS);22512252xkb_state_update_mask(ss->xkb_state, ss->mods_depressed, ss->mods_latched, ss->mods_locked, 0, 0, ss->current_layout_index);2253}22542255void WaylandThread::_wl_keyboard_on_enter(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, struct wl_surface *surface, struct wl_array *keys) {2256WindowState *ws = wl_surface_get_window_state(surface);2257if (!ws) {2258return;2259}22602261SeatState *ss = (SeatState *)data;2262ERR_FAIL_NULL(ss);22632264WaylandThread *wayland_thread = ss->wayland_thread;2265ERR_FAIL_NULL(wayland_thread);22662267ss->focused_id = ws->id;22682269wayland_thread->_set_current_seat(ss->wl_seat);22702271Ref<WindowEventMessage> msg;2272msg.instantiate();2273msg->id = ws->id;2274msg->event = DisplayServer::WINDOW_EVENT_FOCUS_IN;2275wayland_thread->push_message(msg);22762277DEBUG_LOG_WAYLAND_THREAD(vformat("Keyboard focused window %d.", ws->id));2278}22792280void WaylandThread::_wl_keyboard_on_leave(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, struct wl_surface *surface) {2281// NOTE: `surface` will probably be null when the surface is destroyed.2282// See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/3662283// See: https://gitlab.freedesktop.org/wayland/wayland/-/issues/46522842285if (surface && !wl_proxy_is_godot((struct wl_proxy *)surface)) {2286return;2287}22882289SeatState *ss = (SeatState *)data;2290ERR_FAIL_NULL(ss);22912292WaylandThread *wayland_thread = ss->wayland_thread;2293ERR_FAIL_NULL(wayland_thread);22942295ss->repeating_keycode = XKB_KEYCODE_INVALID;22962297if (ss->focused_id == DisplayServer::INVALID_WINDOW_ID) {2298// We're probably on a decoration or some other third-party thing.2299return;2300}23012302WindowState *ws = wayland_thread->window_get_state(ss->focused_id);2303ERR_FAIL_NULL(ws);23042305ss->focused_id = DisplayServer::INVALID_WINDOW_ID;23062307Ref<WindowEventMessage> msg;2308msg.instantiate();2309msg->id = ws->id;2310msg->event = DisplayServer::WINDOW_EVENT_FOCUS_OUT;2311wayland_thread->push_message(msg);23122313ss->shift_pressed = false;2314ss->ctrl_pressed = false;2315ss->alt_pressed = false;2316ss->meta_pressed = false;23172318if (ss->xkb_state != nullptr) {2319xkb_state_update_mask(ss->xkb_state, 0, 0, 0, 0, 0, 0);2320}23212322DEBUG_LOG_WAYLAND_THREAD(vformat("Keyboard unfocused window %d.", ws->id));2323}23242325void WaylandThread::_wl_keyboard_on_key(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) {2326SeatState *ss = (SeatState *)data;2327ERR_FAIL_NULL(ss);23282329if (ss->focused_id == DisplayServer::INVALID_WINDOW_ID) {2330return;2331}23322333// We have to add 8 to the scancode to get an XKB-compatible keycode.2334xkb_keycode_t xkb_keycode = key + 8;23352336bool pressed = state & WL_KEYBOARD_KEY_STATE_PRESSED;23372338if (pressed) {2339if (xkb_keymap_key_repeats(ss->xkb_keymap, xkb_keycode)) {2340ss->last_repeat_start_msec = OS::get_singleton()->get_ticks_msec();2341ss->repeating_keycode = xkb_keycode;2342}23432344ss->last_key_pressed_serial = serial;2345} else if (ss->repeating_keycode == xkb_keycode) {2346ss->repeating_keycode = XKB_KEYCODE_INVALID;2347}23482349_seat_state_handle_xkb_keycode(ss, xkb_keycode, pressed);2350}23512352void 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) {2353SeatState *ss = (SeatState *)data;2354ERR_FAIL_NULL(ss);23552356ss->mods_depressed = mods_depressed;2357ss->mods_latched = mods_latched;2358ss->mods_locked = mods_locked;2359ss->current_layout_index = group;23602361if (ss->xkb_state == nullptr) {2362return;2363}23642365xkb_state_update_mask(ss->xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group);23662367ss->shift_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_SHIFT, XKB_STATE_MODS_EFFECTIVE);2368ss->ctrl_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_EFFECTIVE);2369ss->alt_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_ALT, XKB_STATE_MODS_EFFECTIVE);2370ss->meta_pressed = xkb_state_mod_name_is_active(ss->xkb_state, XKB_MOD_NAME_LOGO, XKB_STATE_MODS_EFFECTIVE);2371}23722373void WaylandThread::_wl_keyboard_on_repeat_info(void *data, struct wl_keyboard *wl_keyboard, int32_t rate, int32_t delay) {2374SeatState *ss = (SeatState *)data;2375ERR_FAIL_NULL(ss);23762377ss->repeat_key_delay_msec = rate ? 1000 / rate : 0;2378ss->repeat_start_delay_msec = delay;2379}23802381// NOTE: Don't forget to `memfree` the offer's state.2382void WaylandThread::_wl_data_device_on_data_offer(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *id) {2383wl_proxy_tag_godot((struct wl_proxy *)id);2384wl_data_offer_add_listener(id, &wl_data_offer_listener, memnew(OfferState));2385}23862387void 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) {2388WindowState *ws = wl_surface_get_window_state(surface);2389if (!ws) {2390return;2391}23922393SeatState *ss = (SeatState *)data;2394ERR_FAIL_NULL(ss);23952396ss->dnd_id = ws->id;23972398ss->dnd_enter_serial = serial;2399ss->wl_data_offer_dnd = id;24002401// Godot only supports DnD file copying for now.2402wl_data_offer_accept(id, serial, "text/uri-list");2403wl_data_offer_set_actions(id, WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY, WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY);2404}24052406void WaylandThread::_wl_data_device_on_leave(void *data, struct wl_data_device *wl_data_device) {2407SeatState *ss = (SeatState *)data;2408ERR_FAIL_NULL(ss);24092410if (ss->wl_data_offer_dnd) {2411memdelete(wl_data_offer_get_offer_state(ss->wl_data_offer_dnd));2412wl_data_offer_destroy(ss->wl_data_offer_dnd);2413ss->wl_data_offer_dnd = nullptr;2414ss->dnd_id = DisplayServer::INVALID_WINDOW_ID;2415}2416}24172418void 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) {2419}24202421void WaylandThread::_wl_data_device_on_drop(void *data, struct wl_data_device *wl_data_device) {2422SeatState *ss = (SeatState *)data;2423ERR_FAIL_NULL(ss);24242425WaylandThread *wayland_thread = ss->wayland_thread;2426ERR_FAIL_NULL(wayland_thread);24272428OfferState *os = wl_data_offer_get_offer_state(ss->wl_data_offer_dnd);2429ERR_FAIL_NULL(os);24302431if (os) {2432Ref<DropFilesEventMessage> msg;2433msg.instantiate();2434msg->id = ss->dnd_id;24352436Vector<uint8_t> list_data = _wl_data_offer_read(wayland_thread->wl_display, "text/uri-list", ss->wl_data_offer_dnd);24372438msg->files = String::utf8((const char *)list_data.ptr(), list_data.size()).split("\r\n", false);2439for (int i = 0; i < msg->files.size(); i++) {2440msg->files.write[i] = msg->files[i].replace("file://", "").uri_file_decode();2441}24422443wayland_thread->push_message(msg);24442445wl_data_offer_finish(ss->wl_data_offer_dnd);2446}24472448memdelete(wl_data_offer_get_offer_state(ss->wl_data_offer_dnd));2449wl_data_offer_destroy(ss->wl_data_offer_dnd);2450ss->wl_data_offer_dnd = nullptr;2451ss->dnd_id = DisplayServer::INVALID_WINDOW_ID;2452}24532454void WaylandThread::_wl_data_device_on_selection(void *data, struct wl_data_device *wl_data_device, struct wl_data_offer *id) {2455SeatState *ss = (SeatState *)data;2456ERR_FAIL_NULL(ss);24572458if (ss->wl_data_offer_selection) {2459memdelete(wl_data_offer_get_offer_state(ss->wl_data_offer_selection));2460wl_data_offer_destroy(ss->wl_data_offer_selection);2461}24622463ss->wl_data_offer_selection = id;2464}24652466void WaylandThread::_wl_data_offer_on_offer(void *data, struct wl_data_offer *wl_data_offer, const char *mime_type) {2467OfferState *os = (OfferState *)data;2468ERR_FAIL_NULL(os);24692470if (os) {2471os->mime_types.insert(String::utf8(mime_type));2472}2473}24742475void WaylandThread::_wl_data_offer_on_source_actions(void *data, struct wl_data_offer *wl_data_offer, uint32_t source_actions) {2476}24772478void WaylandThread::_wl_data_offer_on_action(void *data, struct wl_data_offer *wl_data_offer, uint32_t dnd_action) {2479}24802481void WaylandThread::_wl_data_source_on_target(void *data, struct wl_data_source *wl_data_source, const char *mime_type) {2482}24832484void WaylandThread::_wl_data_source_on_send(void *data, struct wl_data_source *wl_data_source, const char *mime_type, int32_t fd) {2485SeatState *ss = (SeatState *)data;2486ERR_FAIL_NULL(ss);24872488Vector<uint8_t> *data_to_send = nullptr;24892490if (wl_data_source == ss->wl_data_source_selection) {2491data_to_send = &ss->selection_data;2492DEBUG_LOG_WAYLAND_THREAD("Clipboard: requested selection.");2493}24942495if (data_to_send) {2496ssize_t written_bytes = 0;24972498bool valid_mime = false;24992500if (strcmp(mime_type, "text/plain;charset=utf-8") == 0) {2501valid_mime = true;2502} else if (strcmp(mime_type, "text/plain") == 0) {2503valid_mime = true;2504}25052506if (valid_mime) {2507written_bytes = write(fd, data_to_send->ptr(), data_to_send->size());2508}25092510if (written_bytes > 0) {2511DEBUG_LOG_WAYLAND_THREAD(vformat("Clipboard: sent %d bytes.", written_bytes));2512} else if (written_bytes == 0) {2513DEBUG_LOG_WAYLAND_THREAD("Clipboard: no bytes sent.");2514} else {2515ERR_PRINT(vformat("Clipboard: write error %d.", errno));2516}2517}25182519close(fd);2520}25212522void WaylandThread::_wl_data_source_on_cancelled(void *data, struct wl_data_source *wl_data_source) {2523SeatState *ss = (SeatState *)data;2524ERR_FAIL_NULL(ss);25252526wl_data_source_destroy(wl_data_source);25272528if (wl_data_source == ss->wl_data_source_selection) {2529ss->wl_data_source_selection = nullptr;2530ss->selection_data.clear();25312532DEBUG_LOG_WAYLAND_THREAD("Clipboard: selection set by another program.");2533return;2534}2535}25362537void WaylandThread::_wl_data_source_on_dnd_drop_performed(void *data, struct wl_data_source *wl_data_source) {2538}25392540void WaylandThread::_wl_data_source_on_dnd_finished(void *data, struct wl_data_source *wl_data_source) {2541}25422543void WaylandThread::_wl_data_source_on_action(void *data, struct wl_data_source *wl_data_source, uint32_t dnd_action) {2544}25452546void WaylandThread::_wp_fractional_scale_on_preferred_scale(void *data, struct wp_fractional_scale_v1 *wp_fractional_scale_v1, uint32_t scale) {2547WindowState *ws = (WindowState *)data;2548ERR_FAIL_NULL(ws);25492550ws->preferred_fractional_scale = (double)scale / 120;25512552window_state_update_size(ws, ws->rect.size.width, ws->rect.size.height);2553}25542555void 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) {2556SeatState *ss = (SeatState *)data;2557ERR_FAIL_NULL(ss);25582559PointerData &pd = ss->pointer_data_buffer;25602561pd.relative_motion.x = wl_fixed_to_double(dx);2562pd.relative_motion.y = wl_fixed_to_double(dy);25632564pd.relative_motion_time = uptime_lo;2565}25662567void 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) {2568SeatState *ss = (SeatState *)data;2569ERR_FAIL_NULL(ss);25702571if (fingers == 2) {2572ss->old_pinch_scale = wl_fixed_from_int(1);2573ss->active_gesture = Gesture::MAGNIFY;2574}2575}25762577void 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) {2578SeatState *ss = (SeatState *)data;2579ERR_FAIL_NULL(ss);25802581// NOTE: From what I can tell, this and all other pointer gestures are separate2582// from the "frame" mechanism of regular pointers. Thus, let's just assume we2583// can read from the "committed" state.2584const PointerData &pd = ss->pointer_data;25852586WaylandThread *wayland_thread = ss->wayland_thread;2587ERR_FAIL_NULL(wayland_thread);25882589WindowState *ws = wayland_thread->window_get_state(pd.pointed_id);2590ERR_FAIL_NULL(ws);25912592double win_scale = window_state_get_scale_factor(ws);25932594if (ss->active_gesture == Gesture::MAGNIFY) {2595Ref<InputEventMagnifyGesture> mg;2596mg.instantiate();25972598mg->set_window_id(pd.pointed_id);25992600if (ws) {2601mg->set_window_id(ws->id);2602}26032604// Set all pressed modifiers.2605mg->set_shift_pressed(ss->shift_pressed);2606mg->set_ctrl_pressed(ss->ctrl_pressed);2607mg->set_alt_pressed(ss->alt_pressed);2608mg->set_meta_pressed(ss->meta_pressed);26092610mg->set_position(pd.position * win_scale);26112612wl_fixed_t scale_delta = scale - ss->old_pinch_scale;2613mg->set_factor(1 + wl_fixed_to_double(scale_delta));26142615Ref<InputEventMessage> magnify_msg;2616magnify_msg.instantiate();2617magnify_msg->event = mg;26182619// Since Wayland allows only one gesture at a time and godot instead expects2620// both of them, we'll have to create two separate input events: one for2621// magnification and one for panning.26222623Ref<InputEventPanGesture> pg;2624pg.instantiate();26252626// Set all pressed modifiers.2627pg->set_shift_pressed(ss->shift_pressed);2628pg->set_ctrl_pressed(ss->ctrl_pressed);2629pg->set_alt_pressed(ss->alt_pressed);2630pg->set_meta_pressed(ss->meta_pressed);26312632pg->set_position(pd.position * win_scale);2633pg->set_delta(Vector2(wl_fixed_to_double(dx), wl_fixed_to_double(dy)));26342635Ref<InputEventMessage> pan_msg;2636pan_msg.instantiate();2637pan_msg->event = pg;26382639wayland_thread->push_message(magnify_msg);2640wayland_thread->push_message(pan_msg);26412642ss->old_pinch_scale = scale;2643}2644}26452646void 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) {2647SeatState *ss = (SeatState *)data;2648ERR_FAIL_NULL(ss);26492650ss->active_gesture = Gesture::NONE;2651}26522653// NOTE: Don't forget to `memfree` the offer's state.2654void 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) {2655wl_proxy_tag_godot((struct wl_proxy *)offer);2656zwp_primary_selection_offer_v1_add_listener(offer, &wp_primary_selection_offer_listener, memnew(OfferState));2657}26582659void 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) {2660SeatState *ss = (SeatState *)data;2661ERR_FAIL_NULL(ss);26622663if (ss->wp_primary_selection_offer) {2664memfree(wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer));2665zwp_primary_selection_offer_v1_destroy(ss->wp_primary_selection_offer);2666}26672668ss->wp_primary_selection_offer = id;2669}26702671void WaylandThread::_wp_primary_selection_offer_on_offer(void *data, struct zwp_primary_selection_offer_v1 *wp_primary_selection_offer_v1, const char *mime_type) {2672OfferState *os = (OfferState *)data;2673ERR_FAIL_NULL(os);26742675if (os) {2676os->mime_types.insert(String::utf8(mime_type));2677}2678}26792680void 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) {2681SeatState *ss = (SeatState *)data;2682ERR_FAIL_NULL(ss);26832684Vector<uint8_t> *data_to_send = nullptr;26852686if (wp_primary_selection_source_v1 == ss->wp_primary_selection_source) {2687data_to_send = &ss->primary_data;2688DEBUG_LOG_WAYLAND_THREAD("Clipboard: requested primary selection.");2689}26902691if (data_to_send) {2692ssize_t written_bytes = 0;26932694if (strcmp(mime_type, "text/plain") == 0) {2695written_bytes = write(fd, data_to_send->ptr(), data_to_send->size());2696}26972698if (written_bytes > 0) {2699DEBUG_LOG_WAYLAND_THREAD(vformat("Clipboard: sent %d bytes.", written_bytes));2700} else if (written_bytes == 0) {2701DEBUG_LOG_WAYLAND_THREAD("Clipboard: no bytes sent.");2702} else {2703ERR_PRINT(vformat("Clipboard: write error %d.", errno));2704}2705}27062707close(fd);2708}27092710void WaylandThread::_wp_primary_selection_source_on_cancelled(void *data, struct zwp_primary_selection_source_v1 *wp_primary_selection_source_v1) {2711SeatState *ss = (SeatState *)data;2712ERR_FAIL_NULL(ss);27132714if (wp_primary_selection_source_v1 == ss->wp_primary_selection_source) {2715zwp_primary_selection_source_v1_destroy(ss->wp_primary_selection_source);2716ss->wp_primary_selection_source = nullptr;27172718ss->primary_data.clear();27192720DEBUG_LOG_WAYLAND_THREAD("Clipboard: primary selection set by another program.");2721return;2722}2723}27242725void WaylandThread::_wp_tablet_seat_on_tablet_added(void *data, struct zwp_tablet_seat_v2 *wp_tablet_seat_v2, struct zwp_tablet_v2 *id) {2726}27272728void WaylandThread::_wp_tablet_seat_on_tool_added(void *data, struct zwp_tablet_seat_v2 *wp_tablet_seat_v2, struct zwp_tablet_tool_v2 *id) {2729SeatState *ss = (SeatState *)data;2730ERR_FAIL_NULL(ss);27312732TabletToolState *state = memnew(TabletToolState);2733state->wl_seat = ss->wl_seat;27342735wl_proxy_tag_godot((struct wl_proxy *)id);2736zwp_tablet_tool_v2_add_listener(id, &wp_tablet_tool_listener, state);2737ss->tablet_tools.push_back(id);2738}27392740void WaylandThread::_wp_tablet_seat_on_pad_added(void *data, struct zwp_tablet_seat_v2 *wp_tablet_seat_v2, struct zwp_tablet_pad_v2 *id) {2741}27422743void WaylandThread::_wp_tablet_tool_on_type(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t tool_type) {2744TabletToolState *state = wp_tablet_tool_get_state(wp_tablet_tool_v2);27452746if (state && tool_type == ZWP_TABLET_TOOL_V2_TYPE_ERASER) {2747state->is_eraser = true;2748}2749}27502751void 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) {2752}27532754void 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) {2755}27562757void WaylandThread::_wp_tablet_tool_on_capability(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t capability) {2758}27592760void WaylandThread::_wp_tablet_tool_on_done(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {2761}27622763void WaylandThread::_wp_tablet_tool_on_removed(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {2764TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2765if (!ts) {2766return;2767}27682769SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);2770if (!ss) {2771return;2772}27732774List<struct zwp_tablet_tool_v2 *>::Element *E = ss->tablet_tools.find(wp_tablet_tool_v2);27752776if (E && E->get()) {2777struct zwp_tablet_tool_v2 *tool = E->get();2778TabletToolState *state = wp_tablet_tool_get_state(tool);2779if (state) {2780memdelete(state);2781}27822783zwp_tablet_tool_v2_destroy(tool);2784ss->tablet_tools.erase(E);2785}2786}27872788void 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) {2789// NOTE: Works pretty much like wl_pointer::enter.27902791WindowState *ws = wl_surface_get_window_state(surface);2792if (!ws) {2793return;2794}27952796TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2797ERR_FAIL_NULL(ts);27982799ts->data_pending.proximity_serial = serial;2800ts->data_pending.proximal_id = ws->id;2801ts->data_pending.last_proximal_id = ws->id;28022803DEBUG_LOG_WAYLAND_THREAD(vformat("Tablet tool entered window %d.", ts->data_pending.proximal_id));2804}28052806void WaylandThread::_wp_tablet_tool_on_proximity_out(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {2807// NOTE: Works pretty much like wl_pointer::leave.28082809TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2810ERR_FAIL_NULL(ts);28112812if (ts->data_pending.proximal_id == DisplayServer::INVALID_WINDOW_ID) {2813// We're probably on a decoration or some other third-party thing.2814return;2815}28162817DisplayServer::WindowID id = ts->data_pending.proximal_id;28182819ts->data_pending.proximal_id = DisplayServer::INVALID_WINDOW_ID;2820ts->data_pending.pressed_button_mask.clear();28212822DEBUG_LOG_WAYLAND_THREAD(vformat("Tablet tool left window %d.", id));2823}28242825void WaylandThread::_wp_tablet_tool_on_down(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t serial) {2826// NOTE: Works pretty much like wl_pointer::button but only for a pressed left2827// button.28282829TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2830ERR_FAIL_NULL(ts);28312832TabletToolData &td = ts->data_pending;28332834td.pressed_button_mask.set_flag(mouse_button_to_mask(MouseButton::LEFT));2835td.last_button_pressed = MouseButton::LEFT;2836td.double_click_begun = true;28372838// The protocol doesn't cover this, but we can use this funky hack to make2839// double clicking work.2840td.button_time = OS::get_singleton()->get_ticks_msec();2841}28422843void WaylandThread::_wp_tablet_tool_on_up(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2) {2844// NOTE: Works pretty much like wl_pointer::button but only for a released left2845// button.28462847TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2848ERR_FAIL_NULL(ts);28492850TabletToolData &td = ts->data_pending;28512852td.pressed_button_mask.clear_flag(mouse_button_to_mask(MouseButton::LEFT));28532854// The protocol doesn't cover this, but we can use this funky hack to make2855// double clicking work.2856td.button_time = OS::get_singleton()->get_ticks_msec();2857}28582859void 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) {2860// NOTE: Works pretty much like wl_pointer::motion.28612862TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2863ERR_FAIL_NULL(ts);28642865TabletToolData &td = ts->data_pending;28662867td.position.x = wl_fixed_to_double(x);2868td.position.y = wl_fixed_to_double(y);2869}28702871void WaylandThread::_wp_tablet_tool_on_pressure(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t pressure) {2872TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2873ERR_FAIL_NULL(ts);28742875ts->data_pending.pressure = pressure;2876}28772878void WaylandThread::_wp_tablet_tool_on_distance(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t distance) {2879// Unsupported2880}28812882void 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) {2883TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2884ERR_FAIL_NULL(ts);28852886TabletToolData &td = ts->data_pending;28872888td.tilt.x = wl_fixed_to_double(tilt_x);2889td.tilt.y = wl_fixed_to_double(tilt_y);2890}28912892void WaylandThread::_wp_tablet_tool_on_rotation(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t degrees) {2893// Unsupported.2894}28952896void WaylandThread::_wp_tablet_tool_on_slider(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, int32_t position) {2897// Unsupported.2898}28992900void WaylandThread::_wp_tablet_tool_on_wheel(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, wl_fixed_t degrees, int32_t clicks) {2901// TODO2902}29032904void 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) {2905// NOTE: Works pretty much like wl_pointer::button.29062907TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2908ERR_FAIL_NULL(ts);29092910TabletToolData &td = ts->data_pending;29112912MouseButton mouse_button = MouseButton::NONE;29132914if (button == BTN_STYLUS) {2915mouse_button = MouseButton::LEFT;2916}29172918if (button == BTN_STYLUS2) {2919mouse_button = MouseButton::RIGHT;2920}29212922if (mouse_button != MouseButton::NONE) {2923MouseButtonMask mask = mouse_button_to_mask(mouse_button);29242925if (state == ZWP_TABLET_TOOL_V2_BUTTON_STATE_PRESSED) {2926td.pressed_button_mask.set_flag(mask);2927td.last_button_pressed = mouse_button;2928td.double_click_begun = true;2929} else {2930td.pressed_button_mask.clear_flag(mask);2931}29322933// The protocol doesn't cover this, but we can use this funky hack to make2934// double clicking work.2935td.button_time = OS::get_singleton()->get_ticks_msec();2936}2937}29382939void WaylandThread::_wp_tablet_tool_on_frame(void *data, struct zwp_tablet_tool_v2 *wp_tablet_tool_v2, uint32_t time) {2940// NOTE: Works pretty much like wl_pointer::frame.29412942TabletToolState *ts = wp_tablet_tool_get_state(wp_tablet_tool_v2);2943ERR_FAIL_NULL(ts);29442945SeatState *ss = wl_seat_get_seat_state(ts->wl_seat);2946ERR_FAIL_NULL(ss);29472948WaylandThread *wayland_thread = ss->wayland_thread;2949ERR_FAIL_NULL(wayland_thread);29502951TabletToolData &old_td = ts->data;2952TabletToolData &td = ts->data_pending;29532954if (td.proximal_id != old_td.proximal_id) {2955if (old_td.proximal_id != DisplayServer::INVALID_WINDOW_ID) {2956Ref<WindowEventMessage> msg;2957msg.instantiate();2958msg->id = old_td.proximal_id;2959msg->event = DisplayServer::WINDOW_EVENT_MOUSE_EXIT;29602961wayland_thread->push_message(msg);2962}29632964if (td.proximal_id != DisplayServer::INVALID_WINDOW_ID) {2965Ref<WindowEventMessage> msg;2966msg.instantiate();2967msg->id = td.proximal_id;2968msg->event = DisplayServer::WINDOW_EVENT_MOUSE_ENTER;29692970wayland_thread->push_message(msg);2971}2972}29732974if (td.proximal_id == DisplayServer::INVALID_WINDOW_ID) {2975// We're probably on a decoration or some other third-party thing. Let's2976// "commit" the data and call it a day.2977old_td = td;2978return;2979}29802981WindowState *ws = wayland_thread->window_get_state(td.proximal_id);2982ERR_FAIL_NULL(ws);29832984double scale = window_state_get_scale_factor(ws);2985if (old_td.position != td.position || old_td.tilt != td.tilt || old_td.pressure != td.pressure) {2986td.motion_time = time;29872988Ref<InputEventMouseMotion> mm;2989mm.instantiate();29902991mm->set_window_id(td.proximal_id);29922993// Set all pressed modifiers.2994mm->set_shift_pressed(ss->shift_pressed);2995mm->set_ctrl_pressed(ss->ctrl_pressed);2996mm->set_alt_pressed(ss->alt_pressed);2997mm->set_meta_pressed(ss->meta_pressed);29982999mm->set_button_mask(td.pressed_button_mask);30003001mm->set_global_position(td.position * scale);3002mm->set_position(td.position * scale);30033004// NOTE: The Godot API expects normalized values and we store them raw,3005// straight from the compositor, so we have to normalize them here.30063007// According to the tablet proto spec, tilt is expressed in degrees relative3008// to the Z axis of the tablet, so it shouldn't go over 90 degrees either way,3009// I think. We'll clamp it just in case.3010td.tilt = td.tilt.clampf(-90, 90);30113012mm->set_tilt(td.tilt / 90);30133014// The tablet proto spec explicitly says that pressure is defined as a value3015// between 0 to 65535.3016mm->set_pressure(td.pressure / (float)65535);30173018mm->set_pen_inverted(ts->is_eraser);30193020Vector2 pos_delta = (td.position - old_td.position) * scale;30213022mm->set_relative(pos_delta);3023mm->set_relative_screen_position(pos_delta);30243025uint32_t time_delta = td.motion_time - old_td.motion_time;3026mm->set_velocity((Vector2)pos_delta / time_delta);30273028Ref<InputEventMessage> inputev_msg;3029inputev_msg.instantiate();30303031inputev_msg->event = mm;30323033wayland_thread->push_message(inputev_msg);3034}30353036if (old_td.pressed_button_mask != td.pressed_button_mask) {3037td.button_time = time;30383039BitField<MouseButtonMask> pressed_mask_delta = old_td.pressed_button_mask.get_different(td.pressed_button_mask);30403041for (MouseButton test_button : { MouseButton::LEFT, MouseButton::RIGHT }) {3042MouseButtonMask test_button_mask = mouse_button_to_mask(test_button);30433044if (pressed_mask_delta.has_flag(test_button_mask)) {3045Ref<InputEventMouseButton> mb;3046mb.instantiate();30473048// Set all pressed modifiers.3049mb->set_shift_pressed(ss->shift_pressed);3050mb->set_ctrl_pressed(ss->ctrl_pressed);3051mb->set_alt_pressed(ss->alt_pressed);3052mb->set_meta_pressed(ss->meta_pressed);30533054mb->set_window_id(td.proximal_id);3055mb->set_position(td.position * scale);3056mb->set_global_position(td.position * scale);30573058mb->set_button_mask(td.pressed_button_mask);3059mb->set_button_index(test_button);3060mb->set_pressed(td.pressed_button_mask.has_flag(test_button_mask));30613062// We have to set the last position pressed here as we can't take for3063// granted what the individual events might have seen due to them not having3064// a garaunteed order.3065if (mb->is_pressed()) {3066td.last_pressed_position = td.position;3067}30683069if (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) {3070td.double_click_begun = false;3071mb->set_double_click(true);3072}30733074Ref<InputEventMessage> msg;3075msg.instantiate();30763077msg->event = mb;30783079wayland_thread->push_message(msg);3080}3081}3082}30833084old_td = td;3085}30863087void WaylandThread::_wp_text_input_on_enter(void *data, struct zwp_text_input_v3 *wp_text_input_v3, struct wl_surface *surface) {3088SeatState *ss = (SeatState *)data;3089if (!ss) {3090return;3091}30923093WindowState *ws = wl_surface_get_window_state(surface);3094if (!ws) {3095return;3096}30973098ss->ime_window_id = ws->id;3099ss->ime_enabled = true;3100}31013102// NOTE: From now on, we must ignore all further events until an enter event.3103void WaylandThread::_wp_text_input_on_leave(void *data, struct zwp_text_input_v3 *wp_text_input_v3, struct wl_surface *surface) {3104SeatState *ss = (SeatState *)data;3105if (!ss) {3106return;3107}31083109if (ss->ime_window_id == DisplayServer::INVALID_WINDOW_ID) {3110return;3111}31123113Ref<IMEUpdateEventMessage> msg;3114msg.instantiate();3115msg->id = ss->ime_window_id;3116msg->text = String();3117msg->selection = Vector2i();3118ss->wayland_thread->push_message(msg);31193120ss->ime_window_id = DisplayServer::INVALID_WINDOW_ID;3121ss->ime_enabled = false;3122ss->ime_active = false;3123ss->ime_text = String();3124ss->ime_text_commit = String();3125ss->ime_cursor = Vector2i();3126}31273128void 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) {3129SeatState *ss = (SeatState *)data;3130if (!ss) {3131return;3132}31333134if (ss->ime_window_id == DisplayServer::INVALID_WINDOW_ID) {3135return;3136}31373138ss->ime_text = String::utf8(text);31393140// Convert cursor positions from UTF-8 to UTF-32 offset.3141int32_t cursor_begin_utf32 = 0;3142int32_t cursor_end_utf32 = 0;3143for (int i = 0; i < ss->ime_text.length(); i++) {3144uint32_t c = ss->ime_text[i];3145if (c <= 0x7f) { // 7 bits.3146cursor_begin -= 1;3147cursor_end -= 1;3148} else if (c <= 0x7ff) { // 11 bits3149cursor_begin -= 2;3150cursor_end -= 2;3151} else if (c <= 0xffff) { // 16 bits3152cursor_begin -= 3;3153cursor_end -= 3;3154} else if (c <= 0x001fffff) { // 21 bits3155cursor_begin -= 4;3156cursor_end -= 4;3157} else if (c <= 0x03ffffff) { // 26 bits3158cursor_begin -= 5;3159cursor_end -= 5;3160} else if (c <= 0x7fffffff) { // 31 bits3161cursor_begin -= 6;3162cursor_end -= 6;3163} else {3164cursor_begin -= 1;3165cursor_end -= 1;3166}3167if (cursor_begin == 0) {3168cursor_begin_utf32 = i + 1;3169}3170if (cursor_end == 0) {3171cursor_end_utf32 = i + 1;3172}3173if (cursor_begin <= 0 && cursor_end <= 0) {3174break;3175}3176}3177ss->ime_cursor = Vector2i(cursor_begin_utf32, cursor_end_utf32 - cursor_begin_utf32);3178}31793180void WaylandThread::_wp_text_input_on_commit_string(void *data, struct zwp_text_input_v3 *wp_text_input_v3, const char *text) {3181SeatState *ss = (SeatState *)data;3182if (!ss) {3183return;3184}31853186if (ss->ime_window_id == DisplayServer::INVALID_WINDOW_ID) {3187return;3188}31893190ss->ime_text_commit = String::utf8(text);3191}31923193void 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) {3194// Not implemented.3195}31963197void WaylandThread::_wp_text_input_on_done(void *data, struct zwp_text_input_v3 *wp_text_input_v3, uint32_t serial) {3198SeatState *ss = (SeatState *)data;3199if (!ss) {3200return;3201}32023203if (ss->ime_window_id == DisplayServer::INVALID_WINDOW_ID) {3204return;3205}32063207if (!ss->ime_text_commit.is_empty()) {3208Ref<IMECommitEventMessage> msg;3209msg.instantiate();3210msg->id = ss->ime_window_id;3211msg->text = ss->ime_text_commit;3212ss->wayland_thread->push_message(msg);3213} else {3214Ref<IMEUpdateEventMessage> msg;3215msg.instantiate();3216msg->id = ss->ime_window_id;3217msg->text = ss->ime_text;3218msg->selection = ss->ime_cursor;3219ss->wayland_thread->push_message(msg);3220}32213222ss->ime_text = String();3223ss->ime_text_commit = String();3224ss->ime_cursor = Vector2i();3225}32263227void WaylandThread::_xdg_activation_token_on_done(void *data, struct xdg_activation_token_v1 *xdg_activation_token, const char *token) {3228WindowState *ws = (WindowState *)data;3229ERR_FAIL_NULL(ws);3230ERR_FAIL_NULL(ws->wayland_thread);3231ERR_FAIL_NULL(ws->wl_surface);32323233xdg_activation_v1_activate(ws->wayland_thread->registry.xdg_activation, token, ws->wl_surface);3234xdg_activation_token_v1_destroy(xdg_activation_token);32353236DEBUG_LOG_WAYLAND_THREAD(vformat("Received activation token and requested window activation."));3237}32383239void 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) {3240EmbeddingCompositorState *state = (EmbeddingCompositorState *)data;3241ERR_FAIL_NULL(state);32423243EmbeddedClientState *client_state = memnew(EmbeddedClientState);3244client_state->embedding_compositor = godot_embedding_compositor;3245client_state->pid = pid;3246godot_embedded_client_add_listener(godot_embedded_client, &godot_embedded_client_listener, client_state);32473248DEBUG_LOG_WAYLAND_THREAD(vformat("New client %d.", pid));3249state->clients.push_back(godot_embedded_client);3250}32513252void WaylandThread::_godot_embedded_client_on_disconnected(void *data, struct godot_embedded_client *godot_embedded_client) {3253EmbeddedClientState *state = (EmbeddedClientState *)data;3254ERR_FAIL_NULL(state);32553256EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);3257ERR_FAIL_NULL(ecomp_state);32583259ecomp_state->clients.erase_unordered(godot_embedded_client);3260ecomp_state->mapped_clients.erase(state->pid);32613262memfree(state);3263godot_embedded_client_destroy(godot_embedded_client);32643265DEBUG_LOG_WAYLAND_THREAD(vformat("Client %d disconnected.", state->pid));3266}32673268void WaylandThread::_godot_embedded_client_on_window_embedded(void *data, struct godot_embedded_client *godot_embedded_client) {3269EmbeddedClientState *state = (EmbeddedClientState *)data;3270ERR_FAIL_NULL(state);32713272EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);3273ERR_FAIL_NULL(ecomp_state);32743275state->window_mapped = true;32763277ERR_FAIL_COND_MSG(ecomp_state->mapped_clients.has(state->pid), "More than one Wayland client per PID tried to create a window.");32783279ecomp_state->mapped_clients[state->pid] = godot_embedded_client;3280}32813282void WaylandThread::_godot_embedded_client_on_window_focus_in(void *data, struct godot_embedded_client *godot_embedded_client) {3283EmbeddedClientState *state = (EmbeddedClientState *)data;3284ERR_FAIL_NULL(state);32853286EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);3287ERR_FAIL_NULL(ecomp_state);32883289ecomp_state->focused_pid = state->pid;3290DEBUG_LOG_WAYLAND_THREAD(vformat("Embedded client pid %d focus in", state->pid));3291}32923293void WaylandThread::_godot_embedded_client_on_window_focus_out(void *data, struct godot_embedded_client *godot_embedded_client) {3294EmbeddedClientState *state = (EmbeddedClientState *)data;3295ERR_FAIL_NULL(state);32963297EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(state->embedding_compositor);3298ERR_FAIL_NULL(ecomp_state);32993300ecomp_state->focused_pid = -1;3301DEBUG_LOG_WAYLAND_THREAD(vformat("Embedded client pid %d focus out", state->pid));3302}33033304// NOTE: This must be started after a valid wl_display is loaded.3305void WaylandThread::_poll_events_thread(void *p_data) {3306Thread::set_name("Wayland Events");33073308ThreadData *data = (ThreadData *)p_data;3309ERR_FAIL_NULL(data);3310ERR_FAIL_NULL(data->wl_display);33113312struct pollfd poll_fd = {};3313poll_fd.fd = wl_display_get_fd(data->wl_display);3314poll_fd.events = POLLIN;33153316while (true) {3317// Empty the event queue while it's full.3318while (wl_display_prepare_read(data->wl_display) != 0) {3319// We aren't using wl_display_dispatch(), instead "manually" handling events3320// through wl_display_dispatch_pending so that we can use a global mutex and3321// be sure that this and the main thread won't race over stuff, as long as3322// the main thread locks it too.3323//3324// Note that the main thread can still call wl_display_roundtrip as that3325// method directly handles all events, effectively bypassing this polling3326// loop and thus the mutex locking, avoiding a deadlock.3327//3328// WARNING: Never call `wl_display_roundtrip` inside event handlers or while3329// this mutex isn't held! `wl_display_roundtrip` manually handles new events3330// and if not properly gated it _will_ cause potentially stall-inducing race3331// conditions. Ask me how I know.3332MutexLock mutex_lock(data->mutex);33333334if (wl_display_dispatch_pending(data->wl_display) == -1) {3335// Oh no. We'll check and handle any display error below.3336break;3337}3338}33393340int werror = wl_display_get_error(data->wl_display);33413342if (werror) {3343if (werror == EPROTO) {3344struct wl_interface *wl_interface = nullptr;3345uint32_t id = 0;33463347int error_code = wl_display_get_protocol_error(data->wl_display, (const struct wl_interface **)&wl_interface, &id);3348CRASH_NOW_MSG(vformat("Wayland protocol error %d on interface %s@%d.", error_code, wl_interface ? wl_interface->name : "unknown", id));3349} else {3350CRASH_NOW_MSG(vformat("Wayland client error code %d.", werror));3351}3352}33533354wl_display_flush(data->wl_display);33553356// Wait for the event file descriptor to have new data.3357poll(&poll_fd, 1, -1);33583359if (data->thread_done.is_set()) {3360wl_display_cancel_read(data->wl_display);3361break;3362}33633364if (poll_fd.revents | POLLIN) {3365// Load the queues with fresh new data.3366wl_display_read_events(data->wl_display);3367} else {3368// Oh well... Stop signaling that we want to read.3369wl_display_cancel_read(data->wl_display);3370}33713372// The docs advise to redispatch unconditionally and it looks like that if we3373// don't do this we can't catch protocol errors, which is bad.3374MutexLock mutex_lock(data->mutex);3375wl_display_dispatch_pending(data->wl_display);3376}3377}33783379struct wl_display *WaylandThread::get_wl_display() const {3380return wl_display;3381}33823383// NOTE: Stuff like libdecor can (and will) register foreign proxies which3384// aren't formatted as we like. This method is needed to detect whether a proxy3385// has our tag. Also, be careful! The proxy has to be manually tagged or it3386// won't be recognized.3387bool WaylandThread::wl_proxy_is_godot(struct wl_proxy *p_proxy) {3388ERR_FAIL_NULL_V(p_proxy, false);33893390return wl_proxy_get_tag(p_proxy) == &proxy_tag;3391}33923393void WaylandThread::wl_proxy_tag_godot(struct wl_proxy *p_proxy) {3394ERR_FAIL_NULL(p_proxy);33953396wl_proxy_set_tag(p_proxy, &proxy_tag);3397}33983399// Returns the wl_surface's `WindowState`, otherwise `nullptr`.3400// NOTE: This will fail if the surface isn't tagged as ours.3401WaylandThread::WindowState *WaylandThread::wl_surface_get_window_state(struct wl_surface *p_surface) {3402if (p_surface && wl_proxy_is_godot((wl_proxy *)p_surface)) {3403return (WindowState *)wl_surface_get_user_data(p_surface);3404}34053406return nullptr;3407}34083409// Returns the wl_outputs's `ScreenState`, otherwise `nullptr`.3410// NOTE: This will fail if the output isn't tagged as ours.3411WaylandThread::ScreenState *WaylandThread::wl_output_get_screen_state(struct wl_output *p_output) {3412if (p_output && wl_proxy_is_godot((wl_proxy *)p_output)) {3413return (ScreenState *)wl_output_get_user_data(p_output);3414}34153416return nullptr;3417}34183419// Returns the wl_seat's `SeatState`, otherwise `nullptr`.3420// NOTE: This will fail if the output isn't tagged as ours.3421WaylandThread::SeatState *WaylandThread::wl_seat_get_seat_state(struct wl_seat *p_seat) {3422if (p_seat && wl_proxy_is_godot((wl_proxy *)p_seat)) {3423return (SeatState *)wl_seat_get_user_data(p_seat);3424}34253426return nullptr;3427}34283429// Returns the wp_tablet_tool's `TabletToolState`, otherwise `nullptr`.3430// NOTE: This will fail if the output isn't tagged as ours.3431WaylandThread::TabletToolState *WaylandThread::wp_tablet_tool_get_state(struct zwp_tablet_tool_v2 *p_tool) {3432if (p_tool && wl_proxy_is_godot((wl_proxy *)p_tool)) {3433return (TabletToolState *)zwp_tablet_tool_v2_get_user_data(p_tool);3434}34353436return nullptr;3437}3438// Returns the wl_data_offer's `OfferState`, otherwise `nullptr`.3439// NOTE: This will fail if the output isn't tagged as ours.3440WaylandThread::OfferState *WaylandThread::wl_data_offer_get_offer_state(struct wl_data_offer *p_offer) {3441if (p_offer && wl_proxy_is_godot((wl_proxy *)p_offer)) {3442return (OfferState *)wl_data_offer_get_user_data(p_offer);3443}34443445return nullptr;3446}34473448// Returns the wl_data_offer's `OfferState`, otherwise `nullptr`.3449// NOTE: This will fail if the output isn't tagged as ours.3450WaylandThread::OfferState *WaylandThread::wp_primary_selection_offer_get_offer_state(struct zwp_primary_selection_offer_v1 *p_offer) {3451if (p_offer && wl_proxy_is_godot((wl_proxy *)p_offer)) {3452return (OfferState *)zwp_primary_selection_offer_v1_get_user_data(p_offer);3453}34543455return nullptr;3456}34573458WaylandThread::EmbeddingCompositorState *WaylandThread::godot_embedding_compositor_get_state(struct godot_embedding_compositor *p_compositor) {3459// NOTE: No need for tag check as it's a "fake" interface - nothing else exposes it.3460if (p_compositor) {3461return (EmbeddingCompositorState *)godot_embedding_compositor_get_user_data(p_compositor);3462}34633464return nullptr;3465}34663467// This is implemented as a method because this is the simplest way of3468// accounting for dynamic output scale changes.3469int WaylandThread::window_state_get_preferred_buffer_scale(WindowState *p_ws) {3470ERR_FAIL_NULL_V(p_ws, 1);34713472if (p_ws->preferred_fractional_scale > 0) {3473// We're scaling fractionally. Per spec, the buffer scale is always 1.3474return 1;3475}34763477if (p_ws->wl_outputs.is_empty()) {3478DEBUG_LOG_WAYLAND_THREAD("Window has no output associated, returning buffer scale of 1.");3479return 1;3480}34813482// TODO: Cache value?3483int max_size = 1;34843485// ================================ IMPORTANT =================================3486// NOTE: Due to a Godot limitation, we can't really rescale the whole UI yet.3487// Because of this reason, all platforms have resorted to forcing the highest3488// scale possible of a system on any window, despite of what screen it's onto.3489// On this backend everything's already in place for dynamic window scale3490// handling, but in the meantime we'll just select the biggest _global_ output.3491// To restore dynamic scale selection, simply iterate over `p_ws->wl_outputs`3492// instead.3493for (struct wl_output *wl_output : p_ws->registry->wl_outputs) {3494ScreenState *ss = wl_output_get_screen_state(wl_output);34953496if (ss && ss->pending_data.scale > max_size) {3497// NOTE: For some mystical reason, wl_output.done is emitted _after_ windows3498// get resized but the scale event gets sent _before_ that. I'm still leaning3499// towards the idea that rescaling when a window gets a resolution change is a3500// pretty good approach, but this means that we'll have to use the screen data3501// before it's "committed".3502// FIXME: Use the committed data. Somehow.3503max_size = ss->pending_data.scale;3504}3505}35063507return max_size;3508}35093510double WaylandThread::window_state_get_scale_factor(const WindowState *p_ws) {3511ERR_FAIL_NULL_V(p_ws, 1);35123513if (p_ws->fractional_scale > 0) {3514// The fractional scale amount takes priority.3515return p_ws->fractional_scale;3516}35173518return p_ws->buffer_scale;3519}35203521void WaylandThread::window_state_update_size(WindowState *p_ws, int p_width, int p_height) {3522ERR_FAIL_NULL(p_ws);35233524int preferred_buffer_scale = window_state_get_preferred_buffer_scale(p_ws);3525bool using_fractional = p_ws->preferred_fractional_scale > 0;35263527// If neither is true we no-op.3528bool scale_changed = false;3529bool size_changed = false;35303531if (p_ws->rect.size.width != p_width || p_ws->rect.size.height != p_height) {3532p_ws->rect.size.width = p_width;3533p_ws->rect.size.height = p_height;35343535size_changed = true;3536}35373538if (using_fractional && p_ws->fractional_scale != p_ws->preferred_fractional_scale) {3539p_ws->fractional_scale = p_ws->preferred_fractional_scale;3540scale_changed = true;3541}35423543if (p_ws->buffer_scale != preferred_buffer_scale) {3544// The buffer scale is always important, even if we use frac scaling.3545p_ws->buffer_scale = preferred_buffer_scale;3546p_ws->buffer_scale_changed = true;35473548if (!using_fractional) {3549// We don't bother updating everything else if it's turned on though.3550scale_changed = true;3551}3552}35533554if (p_ws->wl_surface) {3555if (p_ws->wp_viewport) {3556wp_viewport_set_destination(p_ws->wp_viewport, p_width, p_height);3557}35583559if (p_ws->xdg_surface) {3560xdg_surface_set_window_geometry(p_ws->xdg_surface, 0, 0, p_width, p_height);3561}3562}35633564#ifdef LIBDECOR_ENABLED3565if (p_ws->libdecor_frame) {3566struct libdecor_state *state = libdecor_state_new(p_width, p_height);3567libdecor_frame_commit(p_ws->libdecor_frame, state, p_ws->pending_libdecor_configuration);3568libdecor_state_free(state);3569p_ws->pending_libdecor_configuration = nullptr;3570}3571#endif35723573if (size_changed || scale_changed) {3574double win_scale = window_state_get_scale_factor(p_ws);3575Size2i scaled_size = scale_vector2i(p_ws->rect.size, win_scale);35763577if (using_fractional) {3578DEBUG_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));3579} else {3580DEBUG_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));3581}35823583// FIXME: Actually resize the hint instead of centering it.3584p_ws->wayland_thread->pointer_set_hint(scaled_size / 2);35853586Ref<WindowRectMessage> rect_msg;3587rect_msg.instantiate();3588rect_msg->id = p_ws->id;3589rect_msg->rect.position = scale_vector2i(p_ws->rect.position, win_scale);3590rect_msg->rect.size = scaled_size;3591p_ws->wayland_thread->push_message(rect_msg);3592}35933594if (scale_changed) {3595Ref<WindowEventMessage> dpi_msg;3596dpi_msg.instantiate();3597dpi_msg->id = p_ws->id;3598dpi_msg->event = DisplayServer::WINDOW_EVENT_DPI_CHANGE;3599p_ws->wayland_thread->push_message(dpi_msg);3600}3601}36023603// Scales a vector according to wp_fractional_scale's rules, where coordinates3604// must be scaled with away from zero half-rounding.3605Vector2i WaylandThread::scale_vector2i(const Vector2i &p_vector, double p_amount) {3606// This snippet is tiny, I know, but this is done a lot.3607int x = std::round(p_vector.x * p_amount);3608int y = std::round(p_vector.y * p_amount);36093610return Vector2i(x, y);3611}36123613void WaylandThread::seat_state_unlock_pointer(SeatState *p_ss) {3614ERR_FAIL_NULL(p_ss);36153616if (p_ss->wl_pointer == nullptr) {3617return;3618}36193620if (p_ss->wp_locked_pointer) {3621zwp_locked_pointer_v1_destroy(p_ss->wp_locked_pointer);3622p_ss->wp_locked_pointer = nullptr;3623}36243625if (p_ss->wp_confined_pointer) {3626zwp_confined_pointer_v1_destroy(p_ss->wp_confined_pointer);3627p_ss->wp_confined_pointer = nullptr;3628}3629}36303631void WaylandThread::seat_state_lock_pointer(SeatState *p_ss) {3632ERR_FAIL_NULL(p_ss);36333634if (p_ss->wl_pointer == nullptr) {3635WARN_PRINT("Can't lock - no pointer?");3636return;3637}36383639if (registry.wp_pointer_constraints == nullptr) {3640WARN_PRINT("Can't lock - no constraints global.");3641return;3642}36433644if (p_ss->wp_locked_pointer == nullptr) {3645struct wl_surface *locked_surface = window_get_wl_surface(p_ss->pointer_data.last_pointed_id);3646if (locked_surface == nullptr) {3647locked_surface = window_get_wl_surface(DisplayServer::MAIN_WINDOW_ID);3648}3649ERR_FAIL_NULL(locked_surface);36503651p_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);3652}3653}36543655void WaylandThread::seat_state_set_hint(SeatState *p_ss, int p_x, int p_y) {3656if (p_ss->wp_locked_pointer == nullptr) {3657return;3658}36593660zwp_locked_pointer_v1_set_cursor_position_hint(p_ss->wp_locked_pointer, wl_fixed_from_int(p_x), wl_fixed_from_int(p_y));3661}36623663void WaylandThread::seat_state_confine_pointer(SeatState *p_ss) {3664ERR_FAIL_NULL(p_ss);36653666if (p_ss->wl_pointer == nullptr) {3667return;3668}36693670if (registry.wp_pointer_constraints == nullptr) {3671return;3672}36733674if (p_ss->wp_confined_pointer == nullptr) {3675struct wl_surface *confined_surface = window_get_wl_surface(p_ss->pointer_data.last_pointed_id);3676ERR_FAIL_NULL(confined_surface);36773678p_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);3679}3680}36813682void WaylandThread::seat_state_update_cursor(SeatState *p_ss) {3683ERR_FAIL_NULL(p_ss);36843685WaylandThread *thread = p_ss->wayland_thread;3686ERR_FAIL_NULL(p_ss->wayland_thread);36873688if (!p_ss->wl_pointer || !p_ss->cursor_surface) {3689return;3690}36913692// NOTE: Those values are valid by default and will hide the cursor when3693// unchanged.3694struct wl_buffer *cursor_buffer = nullptr;3695uint32_t hotspot_x = 0;3696uint32_t hotspot_y = 0;3697int scale = 1;36983699if (thread->cursor_visible) {3700DisplayServer::CursorShape shape = thread->cursor_shape;37013702struct CustomCursor *custom_cursor = thread->custom_cursors.getptr(shape);37033704if (custom_cursor) {3705cursor_buffer = custom_cursor->wl_buffer;3706hotspot_x = custom_cursor->hotspot.x;3707hotspot_y = custom_cursor->hotspot.y;37083709// We can't really reasonably scale custom cursors, so we'll let the3710// compositor do it for us (badly).3711scale = 1;3712} else if (thread->registry.wp_cursor_shape_manager) {3713wp_cursor_shape_device_v1_shape wp_shape = thread->standard_cursors[shape];3714wp_cursor_shape_device_v1_set_shape(p_ss->wp_cursor_shape_device, p_ss->pointer_enter_serial, wp_shape);37153716// We should avoid calling the `wl_pointer_set_cursor` at the end of this method.3717return;3718} else {3719struct wl_cursor *wl_cursor = thread->wl_cursors[shape];37203721if (!wl_cursor) {3722return;3723}37243725int frame_idx = 0;37263727if (wl_cursor->image_count > 1) {3728// The cursor is animated.3729frame_idx = wl_cursor_frame(wl_cursor, p_ss->cursor_time_ms);37303731if (!p_ss->cursor_frame_callback) {3732// Since it's animated, we'll re-update it the next frame.3733p_ss->cursor_frame_callback = wl_surface_frame(p_ss->cursor_surface);3734wl_callback_add_listener(p_ss->cursor_frame_callback, &cursor_frame_callback_listener, p_ss);3735}3736}37373738struct wl_cursor_image *wl_cursor_image = wl_cursor->images[frame_idx];37393740scale = thread->cursor_scale;37413742cursor_buffer = wl_cursor_image_get_buffer(wl_cursor_image);37433744// As the surface's buffer is scaled (thus the surface is smaller) and the3745// hotspot must be expressed in surface-local coordinates, we need to scale3746// it down accordingly.3747hotspot_x = wl_cursor_image->hotspot_x / scale;3748hotspot_y = wl_cursor_image->hotspot_y / scale;3749}3750}37513752wl_pointer_set_cursor(p_ss->wl_pointer, p_ss->pointer_enter_serial, p_ss->cursor_surface, hotspot_x, hotspot_y);3753wl_surface_set_buffer_scale(p_ss->cursor_surface, scale);3754wl_surface_attach(p_ss->cursor_surface, cursor_buffer, 0, 0);3755wl_surface_damage_buffer(p_ss->cursor_surface, 0, 0, INT_MAX, INT_MAX);37563757wl_surface_commit(p_ss->cursor_surface);3758}37593760void WaylandThread::seat_state_echo_keys(SeatState *p_ss) {3761ERR_FAIL_NULL(p_ss);37623763if (p_ss->wl_keyboard == nullptr) {3764return;3765}37663767// TODO: Comment and document out properly this block of code.3768// In short, this implements key repeating.3769if (p_ss->repeat_key_delay_msec && p_ss->repeating_keycode != XKB_KEYCODE_INVALID) {3770uint64_t current_ticks = OS::get_singleton()->get_ticks_msec();3771uint64_t delayed_start_ticks = p_ss->last_repeat_start_msec + p_ss->repeat_start_delay_msec;37723773if (p_ss->last_repeat_msec < delayed_start_ticks) {3774p_ss->last_repeat_msec = delayed_start_ticks;3775}37763777if (current_ticks >= delayed_start_ticks) {3778uint64_t ticks_delta = current_ticks - p_ss->last_repeat_msec;37793780int keys_amount = (ticks_delta / p_ss->repeat_key_delay_msec);37813782for (int i = 0; i < keys_amount; i++) {3783_seat_state_handle_xkb_keycode(p_ss, p_ss->repeating_keycode, true, true);3784}37853786p_ss->last_repeat_msec += ticks_delta - (ticks_delta % p_ss->repeat_key_delay_msec);3787}3788}3789}37903791void WaylandThread::push_message(Ref<Message> message) {3792messages.push_back(message);3793}37943795bool WaylandThread::has_message() {3796return messages.front() != nullptr;3797}37983799Ref<WaylandThread::Message> WaylandThread::pop_message() {3800if (messages.front() != nullptr) {3801Ref<Message> msg = messages.front()->get();3802messages.pop_front();3803return msg;3804}38053806// This method should only be called if `has_messages` returns true but if3807// that isn't the case we'll just return an invalid `Ref`. After all, due to3808// its `InputEvent`-like interface, we still have to dynamically cast and check3809// the `Ref`'s validity anyways.3810return Ref<Message>();3811}38123813void WaylandThread::window_create(DisplayServer::WindowID p_window_id, const Size2i &p_size, DisplayServer::WindowID p_parent_id) {3814ERR_FAIL_COND(windows.has(p_window_id));3815WindowState &ws = windows[p_window_id];38163817ws.id = p_window_id;38183819ws.registry = ®istry;3820ws.wayland_thread = this;38213822ws.rect.size = p_size;38233824ws.wl_surface = wl_compositor_create_surface(registry.wl_compositor);3825wl_proxy_tag_godot((struct wl_proxy *)ws.wl_surface);3826wl_surface_add_listener(ws.wl_surface, &wl_surface_listener, &ws);38273828if (registry.wp_viewporter) {3829ws.wp_viewport = wp_viewporter_get_viewport(registry.wp_viewporter, ws.wl_surface);38303831if (registry.wp_fractional_scale_manager) {3832ws.wp_fractional_scale = wp_fractional_scale_manager_v1_get_fractional_scale(registry.wp_fractional_scale_manager, ws.wl_surface);3833wp_fractional_scale_v1_add_listener(ws.wp_fractional_scale, &wp_fractional_scale_listener, &ws);3834}3835}38363837bool decorated = false;38383839#ifdef LIBDECOR_ENABLED3840if (!decorated && libdecor_context) {3841ws.libdecor_frame = libdecor_decorate(libdecor_context, ws.wl_surface, (struct libdecor_frame_interface *)&libdecor_frame_interface, &ws);3842libdecor_frame_map(ws.libdecor_frame);38433844if (registry.xdg_toplevel_icon_manager) {3845xdg_toplevel *toplevel = libdecor_frame_get_xdg_toplevel(ws.libdecor_frame);3846if (toplevel != nullptr) {3847xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, toplevel, xdg_icon);3848}3849}38503851decorated = true;3852}3853#endif38543855if (!decorated) {3856// libdecor has failed loading or is disabled, we shall handle xdg_toplevel3857// creation and decoration ourselves (and by decorating for now I just mean3858// asking for SSDs and hoping for the best).3859ws.xdg_surface = xdg_wm_base_get_xdg_surface(registry.xdg_wm_base, ws.wl_surface);3860xdg_surface_add_listener(ws.xdg_surface, &xdg_surface_listener, &ws);38613862ws.xdg_toplevel = xdg_surface_get_toplevel(ws.xdg_surface);3863xdg_toplevel_add_listener(ws.xdg_toplevel, &xdg_toplevel_listener, &ws);38643865if (registry.xdg_decoration_manager) {3866ws.xdg_toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(registry.xdg_decoration_manager, ws.xdg_toplevel);3867zxdg_toplevel_decoration_v1_add_listener(ws.xdg_toplevel_decoration, &xdg_toplevel_decoration_listener, &ws);38683869decorated = true;3870}38713872if (registry.xdg_toplevel_icon_manager) {3873xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, ws.xdg_toplevel, xdg_icon);3874}3875}38763877if (p_parent_id != DisplayServer::INVALID_WINDOW_ID) {3878// NOTE: It's important to set the parent ASAP to avoid misunderstandings with3879// the compositor. For example, niri immediately resizes the window to full3880// size as soon as it's configured if it's not parented to another toplevel.3881window_set_parent(p_window_id, p_parent_id);3882}38833884ws.frame_callback = wl_surface_frame(ws.wl_surface);3885wl_callback_add_listener(ws.frame_callback, &frame_wl_callback_listener, &ws);38863887if (registry.xdg_exporter_v2) {3888ws.xdg_exported_v2 = zxdg_exporter_v2_export_toplevel(registry.xdg_exporter_v2, ws.wl_surface);3889zxdg_exported_v2_add_listener(ws.xdg_exported_v2, &xdg_exported_v2_listener, &ws);3890} else if (registry.xdg_exporter_v1) {3891ws.xdg_exported_v1 = zxdg_exporter_v1_export(registry.xdg_exporter_v1, ws.wl_surface);3892zxdg_exported_v1_add_listener(ws.xdg_exported_v1, &xdg_exported_v1_listener, &ws);3893}38943895wl_surface_commit(ws.wl_surface);38963897// Wait for the surface to be configured before continuing.3898wl_display_roundtrip(wl_display);38993900window_state_update_size(&ws, ws.rect.size.width, ws.rect.size.height);3901}39023903void WaylandThread::window_create_popup(DisplayServer::WindowID p_window_id, DisplayServer::WindowID p_parent_id, Rect2i p_rect) {3904ERR_FAIL_COND(windows.has(p_window_id));3905ERR_FAIL_COND(!windows.has(p_parent_id));39063907WindowState &ws = windows[p_window_id];3908WindowState &parent = windows[p_parent_id];39093910double parent_scale = window_state_get_scale_factor(&parent);39113912p_rect.position = scale_vector2i(p_rect.position, 1.0 / parent_scale);3913p_rect.size = scale_vector2i(p_rect.size, 1.0 / parent_scale);39143915// We manually scaled based on the parent. If we don't set the relevant fields,3916// the resizing routines will get confused and scale once more.3917ws.preferred_fractional_scale = parent.preferred_fractional_scale;3918ws.fractional_scale = parent.fractional_scale;3919ws.buffer_scale = parent.buffer_scale;39203921ws.id = p_window_id;3922ws.parent_id = p_parent_id;3923ws.registry = ®istry;3924ws.wayland_thread = this;39253926ws.rect = p_rect;39273928ws.wl_surface = wl_compositor_create_surface(registry.wl_compositor);3929wl_proxy_tag_godot((struct wl_proxy *)ws.wl_surface);3930wl_surface_add_listener(ws.wl_surface, &wl_surface_listener, &ws);39313932if (registry.wp_viewporter) {3933ws.wp_viewport = wp_viewporter_get_viewport(registry.wp_viewporter, ws.wl_surface);39343935if (registry.wp_fractional_scale_manager) {3936ws.wp_fractional_scale = wp_fractional_scale_manager_v1_get_fractional_scale(registry.wp_fractional_scale_manager, ws.wl_surface);3937wp_fractional_scale_v1_add_listener(ws.wp_fractional_scale, &wp_fractional_scale_listener, &ws);3938}3939}39403941ws.xdg_surface = xdg_wm_base_get_xdg_surface(registry.xdg_wm_base, ws.wl_surface);3942xdg_surface_add_listener(ws.xdg_surface, &xdg_surface_listener, &ws);39433944Rect2i positioner_rect;3945positioner_rect.size = parent.rect.size;3946struct xdg_surface *parent_xdg_surface = parent.xdg_surface;39473948Point2i offset = ws.rect.position - parent.rect.position;39493950#ifdef LIBDECOR_ENABLED3951if (!parent_xdg_surface && parent.libdecor_frame) {3952parent_xdg_surface = libdecor_frame_get_xdg_surface(parent.libdecor_frame);39533954int corner_x = 0;3955int corner_y = 0;3956libdecor_frame_translate_coordinate(parent.libdecor_frame, 0, 0, &corner_x, &corner_y);39573958positioner_rect.position.x = corner_x;3959positioner_rect.position.y = corner_y;39603961positioner_rect.size.width -= corner_x;3962positioner_rect.size.height -= corner_y;3963}3964#endif39653966ERR_FAIL_NULL(parent_xdg_surface);39673968struct xdg_positioner *xdg_positioner = xdg_wm_base_create_positioner(registry.xdg_wm_base);3969xdg_positioner_set_size(xdg_positioner, ws.rect.size.width, ws.rect.size.height);3970xdg_positioner_set_anchor(xdg_positioner, XDG_POSITIONER_ANCHOR_TOP_LEFT);3971xdg_positioner_set_gravity(xdg_positioner, XDG_POSITIONER_GRAVITY_BOTTOM_RIGHT);3972xdg_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);3973xdg_positioner_set_anchor_rect(xdg_positioner, positioner_rect.position.x, positioner_rect.position.y, positioner_rect.size.width, positioner_rect.size.height);3974xdg_positioner_set_offset(xdg_positioner, offset.x, offset.y);39753976ws.xdg_popup = xdg_surface_get_popup(ws.xdg_surface, parent_xdg_surface, xdg_positioner);3977xdg_popup_add_listener(ws.xdg_popup, &xdg_popup_listener, &ws);39783979xdg_positioner_destroy(xdg_positioner);39803981ws.frame_callback = wl_surface_frame(ws.wl_surface);3982wl_callback_add_listener(ws.frame_callback, &frame_wl_callback_listener, &ws);39833984wl_surface_commit(ws.wl_surface);39853986// Wait for the surface to be configured before continuing.3987wl_display_roundtrip(wl_display);3988}39893990void WaylandThread::window_destroy(DisplayServer::WindowID p_window_id) {3991ERR_FAIL_COND(!windows.has(p_window_id));3992WindowState &ws = windows[p_window_id];39933994if (ws.xdg_popup) {3995xdg_popup_destroy(ws.xdg_popup);3996}39973998if (ws.xdg_toplevel_decoration) {3999zxdg_toplevel_decoration_v1_destroy(ws.xdg_toplevel_decoration);4000}40014002if (ws.xdg_toplevel) {4003xdg_toplevel_destroy(ws.xdg_toplevel);4004}40054006#ifdef LIBDECOR_ENABLED4007if (ws.libdecor_frame) {4008libdecor_frame_unref(ws.libdecor_frame);4009}4010#endif // LIBDECOR_ENABLED40114012if (ws.wp_fractional_scale) {4013wp_fractional_scale_v1_destroy(ws.wp_fractional_scale);4014}40154016if (ws.wp_viewport) {4017wp_viewport_destroy(ws.wp_viewport);4018}40194020if (ws.frame_callback) {4021wl_callback_destroy(ws.frame_callback);4022}40234024if (ws.xdg_surface) {4025xdg_surface_destroy(ws.xdg_surface);4026}40274028if (ws.wl_surface) {4029wl_surface_destroy(ws.wl_surface);4030}40314032// Before continuing, let's handle any leftover event that might still refer to4033// this window.4034wl_display_roundtrip(wl_display);40354036// We can already clean up here, we're done.4037windows.erase(p_window_id);4038}40394040struct wl_surface *WaylandThread::window_get_wl_surface(DisplayServer::WindowID p_window_id) const {4041const WindowState *ws = windows.getptr(p_window_id);4042if (ws) {4043return ws->wl_surface;4044}40454046return nullptr;4047}40484049WaylandThread::WindowState *WaylandThread::window_get_state(DisplayServer::WindowID p_window_id) {4050return windows.getptr(p_window_id);4051}40524053const WaylandThread::WindowState *WaylandThread::window_get_state(DisplayServer::WindowID p_window_id) const {4054return windows.getptr(p_window_id);4055}40564057Size2i WaylandThread::window_set_size(DisplayServer::WindowID p_window_id, const Size2i &p_size) {4058ERR_FAIL_COND_V(!windows.has(p_window_id), p_size);4059WindowState &ws = windows[p_window_id];40604061double window_scale = window_state_get_scale_factor(&ws);40624063if (ws.maximized) {4064// Can't do anything.4065return scale_vector2i(ws.rect.size, window_scale);4066}40674068Size2i new_size = scale_vector2i(p_size, 1 / window_scale);40694070if (ws.tiled_left && ws.tiled_right) {4071// Tiled left and right, we shouldn't change from our current width or else4072// it'll look wonky.4073new_size.width = ws.rect.size.width;4074}40754076if (ws.tiled_top && ws.tiled_bottom) {4077// Tiled top and bottom. Same as above, but for the height.4078new_size.height = ws.rect.size.height;4079}40804081if (ws.resizing && ws.rect.size.width > 0 && ws.rect.size.height > 0) {4082// The spec says that we shall not resize further than the config size. We can4083// resize less than that though.4084new_size = new_size.min(ws.rect.size);4085}40864087// NOTE: Older versions of libdecor (~2022) do not have a way to get the max4088// content size. Let's also check for its pointer so that we can preserve4089// compatibility with older distros.4090if (ws.libdecor_frame && libdecor_frame_get_max_content_size) {4091int max_width = new_size.width;4092int max_height = new_size.height;40934094// NOTE: Max content size is dynamic on libdecor, as plugins can override it4095// to accommodate their decorations.4096libdecor_frame_get_max_content_size(ws.libdecor_frame, &max_width, &max_height);40974098if (max_width > 0 && max_height > 0) {4099new_size.width = MIN(new_size.width, max_width);4100new_size.height = MIN(new_size.height, max_height);4101}4102}41034104window_state_update_size(&ws, new_size.width, new_size.height);41054106return scale_vector2i(new_size, window_scale);4107}41084109void WaylandThread::beep() const {4110if (registry.xdg_system_bell) {4111xdg_system_bell_v1_ring(registry.xdg_system_bell, nullptr);4112}4113}41144115void WaylandThread::window_start_drag(DisplayServer::WindowID p_window_id) {4116ERR_FAIL_COND(!windows.has(p_window_id));4117WindowState &ws = windows[p_window_id];4118SeatState *ss = wl_seat_get_seat_state(wl_seat_current);41194120if (ss && ws.xdg_toplevel) {4121xdg_toplevel_move(ws.xdg_toplevel, ss->wl_seat, ss->pointer_data.button_serial);4122}41234124#ifdef LIBDECOR_ENABLED4125if (ws.libdecor_frame) {4126libdecor_frame_move(ws.libdecor_frame, ss->wl_seat, ss->pointer_data.button_serial);4127}4128#endif4129}41304131void WaylandThread::window_start_resize(DisplayServer::WindowResizeEdge p_edge, DisplayServer::WindowID p_window) {4132ERR_FAIL_COND(!windows.has(p_window));4133WindowState &ws = windows[p_window];4134SeatState *ss = wl_seat_get_seat_state(wl_seat_current);41354136if (ss && ws.xdg_toplevel) {4137xdg_toplevel_resize_edge edge = XDG_TOPLEVEL_RESIZE_EDGE_NONE;4138switch (p_edge) {4139case DisplayServer::WINDOW_EDGE_TOP_LEFT: {4140edge = XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT;4141} break;4142case DisplayServer::WINDOW_EDGE_TOP: {4143edge = XDG_TOPLEVEL_RESIZE_EDGE_TOP;4144} break;4145case DisplayServer::WINDOW_EDGE_TOP_RIGHT: {4146edge = XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT;4147} break;4148case DisplayServer::WINDOW_EDGE_LEFT: {4149edge = XDG_TOPLEVEL_RESIZE_EDGE_LEFT;4150} break;4151case DisplayServer::WINDOW_EDGE_RIGHT: {4152edge = XDG_TOPLEVEL_RESIZE_EDGE_RIGHT;4153} break;4154case DisplayServer::WINDOW_EDGE_BOTTOM_LEFT: {4155edge = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT;4156} break;4157case DisplayServer::WINDOW_EDGE_BOTTOM: {4158edge = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM;4159} break;4160case DisplayServer::WINDOW_EDGE_BOTTOM_RIGHT: {4161edge = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT;4162} break;4163default:4164break;4165}4166xdg_toplevel_resize(ws.xdg_toplevel, ss->wl_seat, ss->pointer_data.button_serial, edge);4167}41684169#ifdef LIBDECOR_ENABLED4170if (ws.libdecor_frame) {4171libdecor_resize_edge edge = LIBDECOR_RESIZE_EDGE_NONE;4172switch (p_edge) {4173case DisplayServer::WINDOW_EDGE_TOP_LEFT: {4174edge = LIBDECOR_RESIZE_EDGE_TOP_LEFT;4175} break;4176case DisplayServer::WINDOW_EDGE_TOP: {4177edge = LIBDECOR_RESIZE_EDGE_TOP;4178} break;4179case DisplayServer::WINDOW_EDGE_TOP_RIGHT: {4180edge = LIBDECOR_RESIZE_EDGE_TOP_RIGHT;4181} break;4182case DisplayServer::WINDOW_EDGE_LEFT: {4183edge = LIBDECOR_RESIZE_EDGE_LEFT;4184} break;4185case DisplayServer::WINDOW_EDGE_RIGHT: {4186edge = LIBDECOR_RESIZE_EDGE_RIGHT;4187} break;4188case DisplayServer::WINDOW_EDGE_BOTTOM_LEFT: {4189edge = LIBDECOR_RESIZE_EDGE_BOTTOM_LEFT;4190} break;4191case DisplayServer::WINDOW_EDGE_BOTTOM: {4192edge = LIBDECOR_RESIZE_EDGE_BOTTOM;4193} break;4194case DisplayServer::WINDOW_EDGE_BOTTOM_RIGHT: {4195edge = LIBDECOR_RESIZE_EDGE_BOTTOM_RIGHT;4196} break;4197default:4198break;4199}4200libdecor_frame_resize(ws.libdecor_frame, ss->wl_seat, ss->pointer_data.button_serial, edge);4201}4202#endif4203}42044205void WaylandThread::window_set_parent(DisplayServer::WindowID p_window_id, DisplayServer::WindowID p_parent_id) {4206ERR_FAIL_COND(!windows.has(p_window_id));4207ERR_FAIL_COND(!windows.has(p_parent_id));42084209WindowState &child = windows[p_window_id];4210child.parent_id = p_parent_id;42114212WindowState &parent = windows[p_parent_id];42134214// NOTE: We can't really unparent as, at the time of writing, libdecor4215// segfaults when trying to set a null parent. Hopefully unparenting is not4216// that common. Bummer.42174218#ifdef LIBDECOR_ENABLED4219if (child.libdecor_frame && parent.libdecor_frame) {4220libdecor_frame_set_parent(child.libdecor_frame, parent.libdecor_frame);4221return;4222}4223#endif42244225if (child.xdg_toplevel && parent.xdg_toplevel) {4226xdg_toplevel_set_parent(child.xdg_toplevel, parent.xdg_toplevel);4227}4228}42294230void WaylandThread::window_set_max_size(DisplayServer::WindowID p_window_id, const Size2i &p_size) {4231ERR_FAIL_COND(!windows.has(p_window_id));4232WindowState &ws = windows[p_window_id];42334234Vector2i logical_max_size = scale_vector2i(p_size, 1 / window_state_get_scale_factor(&ws));42354236if (ws.wl_surface && ws.xdg_toplevel) {4237xdg_toplevel_set_max_size(ws.xdg_toplevel, logical_max_size.width, logical_max_size.height);4238}42394240#ifdef LIBDECOR_ENABLED4241if (ws.libdecor_frame) {4242libdecor_frame_set_max_content_size(ws.libdecor_frame, logical_max_size.width, logical_max_size.height);4243}42444245// FIXME: I'm not sure whether we have to commit the surface for this to apply.4246#endif4247}42484249void WaylandThread::window_set_min_size(DisplayServer::WindowID p_window_id, const Size2i &p_size) {4250ERR_FAIL_COND(!windows.has(p_window_id));4251WindowState &ws = windows[p_window_id];42524253Size2i logical_min_size = scale_vector2i(p_size, 1 / window_state_get_scale_factor(&ws));42544255if (ws.wl_surface && ws.xdg_toplevel) {4256xdg_toplevel_set_min_size(ws.xdg_toplevel, logical_min_size.width, logical_min_size.height);4257}42584259#ifdef LIBDECOR_ENABLED4260if (ws.libdecor_frame) {4261libdecor_frame_set_min_content_size(ws.libdecor_frame, logical_min_size.width, logical_min_size.height);4262}42634264// FIXME: I'm not sure whether we have to commit the surface for this to apply.4265#endif4266}42674268bool WaylandThread::window_can_set_mode(DisplayServer::WindowID p_window_id, DisplayServer::WindowMode p_window_mode) const {4269ERR_FAIL_COND_V(!windows.has(p_window_id), false);4270const WindowState &ws = windows[p_window_id];42714272switch (p_window_mode) {4273case DisplayServer::WINDOW_MODE_WINDOWED: {4274// Looks like it's guaranteed.4275return true;4276};42774278case DisplayServer::WINDOW_MODE_MINIMIZED: {4279#ifdef LIBDECOR_ENABLED4280if (ws.libdecor_frame) {4281return libdecor_frame_has_capability(ws.libdecor_frame, LIBDECOR_ACTION_MINIMIZE);4282}4283#endif // LIBDECOR_ENABLED42844285return ws.can_minimize;4286};42874288case DisplayServer::WINDOW_MODE_MAXIMIZED: {4289if (ws.libdecor_frame) {4290// NOTE: libdecor doesn't seem to have a maximize capability query?4291// The fact that there's a fullscreen one makes me suspicious. Anyways,4292// let's act as if we always can.4293return true;4294}4295return ws.can_maximize;4296};42974298case DisplayServer::WINDOW_MODE_FULLSCREEN:4299case DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN: {4300#ifdef LIBDECOR_ENABLED4301if (ws.libdecor_frame) {4302return libdecor_frame_has_capability(ws.libdecor_frame, LIBDECOR_ACTION_FULLSCREEN);4303}4304#endif // LIBDECOR_ENABLED43054306return ws.can_fullscreen;4307};4308}43094310return false;4311}43124313void WaylandThread::window_try_set_mode(DisplayServer::WindowID p_window_id, DisplayServer::WindowMode p_window_mode) {4314ERR_FAIL_COND(!windows.has(p_window_id));4315WindowState &ws = windows[p_window_id];43164317if (ws.mode == p_window_mode) {4318return;4319}43204321// Don't waste time with hidden windows and whatnot. Behave like it worked.4322#ifdef LIBDECOR_ENABLED4323if ((!ws.wl_surface || !ws.xdg_toplevel) && !ws.libdecor_frame) {4324#else4325if (!ws.wl_surface || !ws.xdg_toplevel) {4326#endif // LIBDECOR_ENABLED4327ws.mode = p_window_mode;4328return;4329}43304331// Return back to a windowed state so that we can apply what the user asked.4332switch (ws.mode) {4333case DisplayServer::WINDOW_MODE_WINDOWED: {4334// Do nothing.4335} break;43364337case DisplayServer::WINDOW_MODE_MINIMIZED: {4338// We can't do much according to the xdg_shell protocol. I have no idea4339// whether this implies that we should return or who knows what. For now4340// we'll do nothing.4341// TODO: Test this properly.4342} break;43434344case DisplayServer::WINDOW_MODE_MAXIMIZED: {4345// Try to unmaximize. This isn't garaunteed to work actually, so we'll have4346// to check whether something changed.4347if (ws.xdg_toplevel) {4348xdg_toplevel_unset_maximized(ws.xdg_toplevel);4349}43504351#ifdef LIBDECOR_ENABLED4352if (ws.libdecor_frame) {4353libdecor_frame_unset_maximized(ws.libdecor_frame);4354}4355#endif // LIBDECOR_ENABLED4356} break;43574358case DisplayServer::WINDOW_MODE_FULLSCREEN:4359case DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN: {4360// Same thing as above, unset fullscreen and check later if it worked.4361if (ws.xdg_toplevel) {4362xdg_toplevel_unset_fullscreen(ws.xdg_toplevel);4363}43644365#ifdef LIBDECOR_ENABLED4366if (ws.libdecor_frame) {4367libdecor_frame_unset_fullscreen(ws.libdecor_frame);4368}4369#endif // LIBDECOR_ENABLED4370} break;4371}43724373// Wait for a configure event and hope that something changed.4374wl_display_roundtrip(wl_display);43754376if (ws.mode != DisplayServer::WINDOW_MODE_WINDOWED) {4377// The compositor refused our "normalization" request. It'd be useless or4378// unpredictable to attempt setting a new state. We're done.4379return;4380}43814382// Ask the compositor to set the state indicated by the new mode.4383switch (p_window_mode) {4384case DisplayServer::WINDOW_MODE_WINDOWED: {4385// Do nothing. We're already windowed.4386} break;43874388case DisplayServer::WINDOW_MODE_MINIMIZED: {4389if (!window_can_set_mode(p_window_id, p_window_mode)) {4390// Minimization is special (read below). Better not mess with it if the4391// compositor explicitly announces that it doesn't support it.4392break;4393}43944395if (ws.xdg_toplevel) {4396xdg_toplevel_set_minimized(ws.xdg_toplevel);4397}43984399#ifdef LIBDECOR_ENABLED4400if (ws.libdecor_frame) {4401libdecor_frame_set_minimized(ws.libdecor_frame);4402}4403#endif // LIBDECOR_ENABLED4404// We have no way to actually detect this state, so we'll have to report it4405// manually to the engine (hoping that it worked). In the worst case it'll4406// get reset by the next configure event.4407ws.mode = DisplayServer::WINDOW_MODE_MINIMIZED;4408} break;44094410case DisplayServer::WINDOW_MODE_MAXIMIZED: {4411if (ws.xdg_toplevel) {4412xdg_toplevel_set_maximized(ws.xdg_toplevel);4413}44144415#ifdef LIBDECOR_ENABLED4416if (ws.libdecor_frame) {4417libdecor_frame_set_maximized(ws.libdecor_frame);4418}4419#endif // LIBDECOR_ENABLED4420} break;44214422case DisplayServer::WINDOW_MODE_FULLSCREEN:4423case DisplayServer::WINDOW_MODE_EXCLUSIVE_FULLSCREEN: {4424if (ws.xdg_toplevel) {4425xdg_toplevel_set_fullscreen(ws.xdg_toplevel, nullptr);4426}44274428#ifdef LIBDECOR_ENABLED4429if (ws.libdecor_frame) {4430libdecor_frame_set_fullscreen(ws.libdecor_frame, nullptr);4431}4432#endif // LIBDECOR_ENABLED4433} break;44344435default: {4436} break;4437}4438}44394440void WaylandThread::window_set_borderless(DisplayServer::WindowID p_window_id, bool p_borderless) {4441ERR_FAIL_COND(!windows.has(p_window_id));4442WindowState &ws = windows[p_window_id];44434444if (ws.xdg_toplevel_decoration) {4445if (p_borderless) {4446// We implement borderless windows by simply asking the compositor to let4447// us handle decorations (we don't).4448zxdg_toplevel_decoration_v1_set_mode(ws.xdg_toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE);4449} else {4450zxdg_toplevel_decoration_v1_set_mode(ws.xdg_toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);4451}4452}44534454#ifdef LIBDECOR_ENABLED4455if (ws.libdecor_frame) {4456bool visible_current = libdecor_frame_is_visible(ws.libdecor_frame);4457bool visible_target = !p_borderless;44584459// NOTE: We have to do this otherwise we trip on a libdecor bug where it's4460// possible to destroy the frame more than once, by setting the visibility4461// to false multiple times and thus crashing.4462if (visible_current != visible_target) {4463print_verbose(vformat("Setting libdecor frame visibility to %s", visible_target));4464libdecor_frame_set_visibility(ws.libdecor_frame, visible_target);4465}4466}4467#endif // LIBDECOR_ENABLED4468}44694470void WaylandThread::window_set_title(DisplayServer::WindowID p_window_id, const String &p_title) {4471ERR_FAIL_COND(!windows.has(p_window_id));4472WindowState &ws = windows[p_window_id];44734474#ifdef LIBDECOR_ENABLED4475if (ws.libdecor_frame) {4476libdecor_frame_set_title(ws.libdecor_frame, p_title.utf8().get_data());4477}4478#endif // LIBDECOR_ENABLE44794480if (ws.xdg_toplevel) {4481xdg_toplevel_set_title(ws.xdg_toplevel, p_title.utf8().get_data());4482}4483}44844485void WaylandThread::window_set_app_id(DisplayServer::WindowID p_window_id, const String &p_app_id) {4486ERR_FAIL_COND(!windows.has(p_window_id));4487WindowState &ws = windows[p_window_id];44884489#ifdef LIBDECOR_ENABLED4490if (ws.libdecor_frame) {4491libdecor_frame_set_app_id(ws.libdecor_frame, p_app_id.utf8().get_data());4492return;4493}4494#endif // LIBDECOR_ENABLED44954496if (ws.xdg_toplevel) {4497xdg_toplevel_set_app_id(ws.xdg_toplevel, p_app_id.utf8().get_data());4498return;4499}4500}45014502void WaylandThread::set_icon(const Ref<Image> &p_icon) {4503ERR_FAIL_COND(p_icon.is_null());45044505Size2i icon_size = p_icon->get_size();4506ERR_FAIL_COND(icon_size.width != icon_size.height);45074508if (!registry.xdg_toplevel_icon_manager) {4509return;4510}45114512if (xdg_icon) {4513xdg_toplevel_icon_v1_destroy(xdg_icon);4514}45154516if (icon_buffer) {4517wl_buffer_destroy(icon_buffer);4518}45194520// NOTE: The stride is the width of the icon in bytes.4521uint32_t icon_stride = icon_size.width * 4;4522uint32_t data_size = icon_stride * icon_size.height;45234524// We need a shared memory object file descriptor in order to create a4525// wl_buffer through wl_shm.4526int fd = WaylandThread::_allocate_shm_file(data_size);4527ERR_FAIL_COND(fd == -1);45284529uint32_t *buffer_data = (uint32_t *)mmap(nullptr, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);45304531// Create the Wayland buffer.4532struct wl_shm_pool *shm_pool = wl_shm_create_pool(registry.wl_shm, fd, data_size);4533icon_buffer = wl_shm_pool_create_buffer(shm_pool, 0, icon_size.width, icon_size.height, icon_stride, WL_SHM_FORMAT_ARGB8888);4534wl_shm_pool_destroy(shm_pool);45354536// Fill the cursor buffer with the image data.4537for (uint32_t index = 0; index < (uint32_t)(icon_size.width * icon_size.height); index++) {4538int row_index = index / icon_size.width;4539int column_index = (index % icon_size.width);45404541buffer_data[index] = p_icon->get_pixel(column_index, row_index).to_argb32();45424543// Wayland buffers, unless specified, require associated alpha, so we'll just4544// associate the alpha in-place.4545uint8_t *pixel_data = (uint8_t *)&buffer_data[index];4546pixel_data[0] = pixel_data[0] * pixel_data[3] / 255;4547pixel_data[1] = pixel_data[1] * pixel_data[3] / 255;4548pixel_data[2] = pixel_data[2] * pixel_data[3] / 255;4549}45504551xdg_icon = xdg_toplevel_icon_manager_v1_create_icon(registry.xdg_toplevel_icon_manager);4552xdg_toplevel_icon_v1_add_buffer(xdg_icon, icon_buffer, icon_size.width);45534554if (Engine::get_singleton()->is_editor_hint() || Engine::get_singleton()->is_project_manager_hint()) {4555// Setting a name allows the godot icon to be overridden by a system theme.4556// We only want the project manager and editor to get themed,4557// Games will get icons with the protocol and themed icons with .desktop entries.4558// NOTE: should be synced with the icon name in misc/dist/linuxbsd/Godot.desktop4559xdg_toplevel_icon_v1_set_name(xdg_icon, "godot");4560}45614562for (KeyValue<DisplayServer::WindowID, WindowState> &pair : windows) {4563WindowState &ws = pair.value;4564#ifdef LIBDECOR_ENABLED4565if (ws.libdecor_frame) {4566xdg_toplevel *toplevel = libdecor_frame_get_xdg_toplevel(ws.libdecor_frame);4567ERR_FAIL_NULL(toplevel);4568xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, toplevel, xdg_icon);4569}4570#endif4571if (ws.xdg_toplevel) {4572xdg_toplevel_icon_manager_v1_set_icon(registry.xdg_toplevel_icon_manager, ws.xdg_toplevel, xdg_icon);4573}4574}4575}45764577DisplayServer::WindowMode WaylandThread::window_get_mode(DisplayServer::WindowID p_window_id) const {4578ERR_FAIL_COND_V(!windows.has(p_window_id), DisplayServer::WINDOW_MODE_WINDOWED);4579const WindowState &ws = windows[p_window_id];45804581return ws.mode;4582}45834584void WaylandThread::window_request_attention(DisplayServer::WindowID p_window_id) {4585ERR_FAIL_COND(!windows.has(p_window_id));4586WindowState &ws = windows[p_window_id];45874588if (registry.xdg_activation) {4589// Window attention requests are done through the XDG activation protocol.4590xdg_activation_token_v1 *xdg_activation_token = xdg_activation_v1_get_activation_token(registry.xdg_activation);4591xdg_activation_token_v1_add_listener(xdg_activation_token, &xdg_activation_token_listener, &ws);4592xdg_activation_token_v1_commit(xdg_activation_token);4593}4594}45954596void WaylandThread::window_set_idle_inhibition(DisplayServer::WindowID p_window_id, bool p_enable) {4597ERR_FAIL_COND(!windows.has(p_window_id));4598WindowState &ws = windows[p_window_id];45994600if (p_enable) {4601if (ws.registry->wp_idle_inhibit_manager && !ws.wp_idle_inhibitor) {4602ERR_FAIL_NULL(ws.wl_surface);4603ws.wp_idle_inhibitor = zwp_idle_inhibit_manager_v1_create_inhibitor(ws.registry->wp_idle_inhibit_manager, ws.wl_surface);4604}4605} else {4606if (ws.wp_idle_inhibitor) {4607zwp_idle_inhibitor_v1_destroy(ws.wp_idle_inhibitor);4608ws.wp_idle_inhibitor = nullptr;4609}4610}4611}46124613bool WaylandThread::window_get_idle_inhibition(DisplayServer::WindowID p_window_id) const {4614ERR_FAIL_COND_V(!windows.has(p_window_id), false);4615const WindowState &ws = windows[p_window_id];46164617return ws.wp_idle_inhibitor != nullptr;4618}46194620WaylandThread::ScreenData WaylandThread::screen_get_data(int p_screen) const {4621ERR_FAIL_INDEX_V(p_screen, registry.wl_outputs.size(), ScreenData());46224623return wl_output_get_screen_state(registry.wl_outputs.get(p_screen))->data;4624}46254626int WaylandThread::get_screen_count() const {4627return registry.wl_outputs.size();4628}46294630DisplayServer::WindowID WaylandThread::pointer_get_pointed_window_id() const {4631SeatState *ss = wl_seat_get_seat_state(wl_seat_current);46324633if (ss) {4634// Let's determine the most recently used tablet tool.4635TabletToolState *max_ts = nullptr;4636for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {4637TabletToolState *ts = wp_tablet_tool_get_state(tool);4638ERR_CONTINUE(ts == nullptr);46394640TabletToolData &td = ts->data;46414642if (!max_ts) {4643max_ts = ts;4644continue;4645}46464647if (MAX(td.button_time, td.motion_time) > MAX(max_ts->data.button_time, max_ts->data.motion_time)) {4648max_ts = ts;4649}4650}46514652const PointerData &pd = ss->pointer_data;46534654if (max_ts) {4655TabletToolData &td = max_ts->data;4656if (MAX(td.button_time, td.motion_time) > MAX(pd.button_time, pd.motion_time)) {4657return td.proximal_id;4658}4659}46604661return ss->pointer_data.pointed_id;4662}46634664return DisplayServer::INVALID_WINDOW_ID;4665}4666DisplayServer::WindowID WaylandThread::pointer_get_last_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.last_proximal_id;4694}4695}46964697return ss->pointer_data.last_pointed_id;4698}46994700return DisplayServer::INVALID_WINDOW_ID;4701}47024703void WaylandThread::pointer_set_constraint(PointerConstraint p_constraint) {4704SeatState *ss = wl_seat_get_seat_state(wl_seat_current);47054706if (ss) {4707seat_state_unlock_pointer(ss);47084709if (p_constraint == PointerConstraint::LOCKED) {4710seat_state_lock_pointer(ss);4711} else if (p_constraint == PointerConstraint::CONFINED) {4712seat_state_confine_pointer(ss);4713}4714}47154716pointer_constraint = p_constraint;4717}47184719void WaylandThread::pointer_set_hint(const Point2i &p_hint) {4720SeatState *ss = wl_seat_get_seat_state(wl_seat_current);4721if (!ss) {4722return;4723}47244725WindowState *ws = window_get_state(ss->pointer_data.pointed_id);47264727int hint_x = 0;4728int hint_y = 0;47294730if (ws) {4731// NOTE: It looks like it's not really recommended to convert from4732// "godot-space" to "wayland-space" and in general I received mixed feelings4733// discussing about this. I'm not really sure about the maths behind this but,4734// oh well, we're setting a cursor hint. ¯\_(ツ)_/¯4735// See: https://oftc.irclog.whitequark.org/wayland/2023-08-23#1692756914-16928168184736hint_x = std::round(p_hint.x / window_state_get_scale_factor(ws));4737hint_y = std::round(p_hint.y / window_state_get_scale_factor(ws));4738}47394740if (ss) {4741seat_state_set_hint(ss, hint_x, hint_y);4742}4743}47444745WaylandThread::PointerConstraint WaylandThread::pointer_get_constraint() const {4746return pointer_constraint;4747}47484749BitField<MouseButtonMask> WaylandThread::pointer_get_button_mask() const {4750SeatState *ss = wl_seat_get_seat_state(wl_seat_current);47514752if (ss) {4753return ss->pointer_data.pressed_button_mask;4754}47554756return BitField<MouseButtonMask>();4757}47584759Error WaylandThread::init() {4760#ifdef SOWRAP_ENABLED4761#ifdef DEBUG_ENABLED4762int dylibloader_verbose = 1;4763#else4764int dylibloader_verbose = 0;4765#endif // DEBUG_ENABLED47664767if (initialize_wayland_client(dylibloader_verbose) != 0) {4768WARN_PRINT("Can't load the Wayland client library.");4769return ERR_CANT_CREATE;4770}47714772if (initialize_wayland_cursor(dylibloader_verbose) != 0) {4773WARN_PRINT("Can't load the Wayland cursor library.");4774return ERR_CANT_CREATE;4775}47764777if (initialize_xkbcommon(dylibloader_verbose) != 0) {4778WARN_PRINT("Can't load the XKBcommon library.");4779return ERR_CANT_CREATE;4780}4781#endif // SOWRAP_ENABLED47824783KeyMappingXKB::initialize();47844785String embedder_socket_path;47864787#ifdef TOOLS_ENABLED4788bool embedder_enabled = true;47894790if (OS::get_singleton()->get_environment("GODOT_WAYLAND_DISABLE_EMBEDDER") == "1") {4791print_verbose("Disabling Wayland embedder as per GODOT_WAYLAND_DISABLE_EMBEDDER.");4792embedder_enabled = false;4793}47944795if (embedder_enabled && Engine::get_singleton()->is_editor_hint() && !Engine::get_singleton()->is_project_manager_hint()) {4796print_verbose("Initializing Wayland embedder.");4797Error embedder_status = embedder.init();4798ERR_FAIL_COND_V_MSG(embedder_status != OK, ERR_CANT_CREATE, "Can't initialize Wayland embedder.");47994800embedder_socket_path = embedder.get_socket_path();4801ERR_FAIL_COND_V_MSG(embedder_socket_path.is_empty(), ERR_CANT_CREATE, "Wayland embedder returned invalid path.");48024803OS::get_singleton()->set_environment("GODOT_WAYLAND_DISPLAY", embedder_socket_path);4804}4805#endif // TOOLS_ENABLED48064807if (Engine::get_singleton()->is_embedded_in_editor()) {4808embedder_socket_path = OS::get_singleton()->get_environment("GODOT_WAYLAND_DISPLAY");4809#if 04810// Debug4811OS::get_singleton()->set_environment("WAYLAND_DEBUG", "1");4812int fd = open("/tmp/gdembedded.log", O_CREAT | O_RDWR, 0666);4813dup2(fd, 1);4814dup2(fd, 2);4815#endif4816}48174818if (embedder_socket_path.is_empty()) {4819print_verbose("Connecting to the default Wayland display.");4820wl_display = wl_display_connect(nullptr);4821} else {4822print_verbose("Connecting to the Wayland embedder display.");4823wl_display = wl_display_connect(embedder_socket_path.utf8().get_data());4824}48254826ERR_FAIL_NULL_V_MSG(wl_display, ERR_CANT_CREATE, "Can't connect to a Wayland display.");48274828thread_data.wl_display = wl_display;48294830wl_registry = wl_display_get_registry(wl_display);48314832ERR_FAIL_NULL_V_MSG(wl_registry, ERR_UNAVAILABLE, "Can't obtain the Wayland registry global.");48334834registry.wayland_thread = this;48354836wl_registry_add_listener(wl_registry, &wl_registry_listener, ®istry);48374838// Wait for registry to get notified from the compositor.4839wl_display_roundtrip(wl_display);48404841ERR_FAIL_NULL_V_MSG(registry.wl_shm, ERR_UNAVAILABLE, "Can't obtain the Wayland shared memory global.");4842ERR_FAIL_NULL_V_MSG(registry.wl_compositor, ERR_UNAVAILABLE, "Can't obtain the Wayland compositor global.");4843ERR_FAIL_NULL_V_MSG(registry.xdg_wm_base, ERR_UNAVAILABLE, "Can't obtain the Wayland XDG shell global.");48444845// Embedded games can't access the decoration and icon protocol.4846if (!Engine::get_singleton()->is_embedded_in_editor()) {4847if (!registry.xdg_decoration_manager) {4848#ifdef LIBDECOR_ENABLED4849WARN_PRINT("Can't obtain the XDG decoration manager. Libdecor will be used for drawing CSDs, if available.");4850#else4851WARN_PRINT("Can't obtain the XDG decoration manager. Decorations won't show up.");4852#endif // LIBDECOR_ENABLED4853}48544855if (!registry.xdg_toplevel_icon_manager_name) {4856WARN_PRINT("xdg-toplevel-icon protocol not found! Cannot set window icon.");4857}4858}48594860if (!registry.xdg_activation) {4861WARN_PRINT("Can't obtain the XDG activation global. Attention requesting won't work!");4862}48634864#ifndef DBUS_ENABLED4865if (!registry.wp_idle_inhibit_manager) {4866WARN_PRINT("Can't obtain the idle inhibition manager. The screen might turn off even after calling screen_set_keep_on()!");4867}4868#endif // DBUS_ENABLED48694870if (!registry.wp_fifo_manager_name) {4871WARN_PRINT("FIFO protocol not found! Frame pacing will be degraded.");4872}48734874// Wait for seat capabilities.4875wl_display_roundtrip(wl_display);48764877#ifdef LIBDECOR_ENABLED4878bool libdecor_found = true;48794880bool skip_libdecor = OS::get_singleton()->get_environment("GODOT_WAYLAND_DISABLE_LIBDECOR") == "1";48814882#ifdef SOWRAP_ENABLED4883if (!skip_libdecor && initialize_libdecor(dylibloader_verbose) != 0) {4884libdecor_found = false;4885}4886#endif // SOWRAP_ENABLED48874888if (skip_libdecor) {4889print_verbose("Skipping libdecor check because GODOT_WAYLAND_DISABLE_LIBDECOR is set to 1.");4890} else {4891if (libdecor_found) {4892libdecor_context = libdecor_new(wl_display, (struct libdecor_interface *)&libdecor_interface);4893} else {4894print_verbose("libdecor not found. Client-side decorations disabled.");4895}4896}4897#endif // LIBDECOR_ENABLED48984899cursor_theme_name = OS::get_singleton()->get_environment("XCURSOR_THEME");49004901unscaled_cursor_size = OS::get_singleton()->get_environment("XCURSOR_SIZE").to_int();4902if (unscaled_cursor_size <= 0) {4903print_verbose("Detected invalid cursor size preference, defaulting to 24.");4904unscaled_cursor_size = 24;4905}49064907// NOTE: The scale is useful here as it might've been updated by _update_scale.4908bool cursor_theme_loaded = _load_cursor_theme(unscaled_cursor_size * cursor_scale);49094910if (!cursor_theme_loaded) {4911return ERR_CANT_CREATE;4912}49134914// Update the cursor.4915cursor_set_shape(DisplayServer::CURSOR_ARROW);49164917events_thread.start(_poll_events_thread, &thread_data);49184919initialized = true;4920return OK;4921}49224923void WaylandThread::cursor_set_visible(bool p_visible) {4924cursor_visible = p_visible;49254926for (struct wl_seat *wl_seat : registry.wl_seats) {4927SeatState *ss = wl_seat_get_seat_state(wl_seat);4928ERR_FAIL_NULL(ss);49294930seat_state_update_cursor(ss);4931}4932}49334934void WaylandThread::cursor_set_shape(DisplayServer::CursorShape p_cursor_shape) {4935cursor_shape = p_cursor_shape;49364937for (struct wl_seat *wl_seat : registry.wl_seats) {4938SeatState *ss = wl_seat_get_seat_state(wl_seat);4939ERR_FAIL_NULL(ss);49404941seat_state_update_cursor(ss);4942}4943}49444945void WaylandThread::cursor_shape_set_custom_image(DisplayServer::CursorShape p_cursor_shape, Ref<Image> p_image, const Point2i &p_hotspot) {4946ERR_FAIL_COND(p_image.is_null());49474948Size2i image_size = p_image->get_size();49494950// NOTE: The stride is the width of the image in bytes.4951unsigned int image_stride = image_size.width * 4;4952unsigned int data_size = image_stride * image_size.height;49534954// We need a shared memory object file descriptor in order to create a4955// wl_buffer through wl_shm.4956int fd = WaylandThread::_allocate_shm_file(data_size);4957ERR_FAIL_COND(fd == -1);49584959CustomCursor &cursor = custom_cursors[p_cursor_shape];4960cursor.hotspot = p_hotspot;49614962if (cursor.wl_buffer) {4963// Clean up the old Wayland buffer.4964wl_buffer_destroy(cursor.wl_buffer);4965}49664967if (cursor.buffer_data) {4968// Clean up the old buffer data.4969munmap(cursor.buffer_data, cursor.buffer_data_size);4970}49714972cursor.buffer_data = (uint32_t *)mmap(nullptr, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);4973cursor.buffer_data_size = data_size;49744975// Create the Wayland buffer.4976struct wl_shm_pool *wl_shm_pool = wl_shm_create_pool(registry.wl_shm, fd, data_size);4977// TODO: Make sure that WL_SHM_FORMAT_ARGB8888 format is supported. It4978// technically isn't garaunteed to be supported, but I think that'd be a4979// pretty unlikely thing to stumble upon.4980cursor.wl_buffer = wl_shm_pool_create_buffer(wl_shm_pool, 0, image_size.width, image_size.height, image_stride, WL_SHM_FORMAT_ARGB8888);4981wl_shm_pool_destroy(wl_shm_pool);49824983// Fill the cursor buffer with the image data.4984for (unsigned int index = 0; index < (unsigned int)(image_size.width * image_size.height); index++) {4985int row_index = std::floor(index / image_size.width);4986int column_index = (index % int(image_size.width));49874988cursor.buffer_data[index] = p_image->get_pixel(column_index, row_index).to_argb32();49894990// Wayland buffers, unless specified, require associated alpha, so we'll just4991// associate the alpha in-place.4992uint8_t *pixel_data = (uint8_t *)&cursor.buffer_data[index];4993pixel_data[0] = pixel_data[0] * pixel_data[3] / 255;4994pixel_data[1] = pixel_data[1] * pixel_data[3] / 255;4995pixel_data[2] = pixel_data[2] * pixel_data[3] / 255;4996}4997}49984999void WaylandThread::cursor_shape_clear_custom_image(DisplayServer::CursorShape p_cursor_shape) {5000if (custom_cursors.has(p_cursor_shape)) {5001CustomCursor cursor = custom_cursors[p_cursor_shape];5002custom_cursors.erase(p_cursor_shape);50035004if (cursor.wl_buffer) {5005wl_buffer_destroy(cursor.wl_buffer);5006}50075008if (cursor.buffer_data) {5009munmap(cursor.buffer_data, cursor.buffer_data_size);5010}5011}5012}50135014void WaylandThread::window_set_ime_active(const bool p_active, DisplayServer::WindowID p_window_id) {5015SeatState *ss = wl_seat_get_seat_state(wl_seat_current);50165017if (ss && ss->wp_text_input && ss->ime_enabled) {5018if (p_active) {5019ss->ime_active = true;5020zwp_text_input_v3_enable(ss->wp_text_input);5021zwp_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);5022} else {5023ss->ime_active = false;5024ss->ime_text = String();5025ss->ime_text_commit = String();5026ss->ime_cursor = Vector2i();5027zwp_text_input_v3_disable(ss->wp_text_input);5028}5029zwp_text_input_v3_commit(ss->wp_text_input);5030}5031}50325033void WaylandThread::window_set_ime_position(const Point2i &p_pos, DisplayServer::WindowID p_window_id) {5034SeatState *ss = wl_seat_get_seat_state(wl_seat_current);50355036if (ss && ss->wp_text_input && ss->ime_enabled) {5037ss->ime_rect = Rect2i(p_pos, Size2i(1, 10));5038zwp_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);5039zwp_text_input_v3_commit(ss->wp_text_input);5040}5041}50425043int WaylandThread::keyboard_get_layout_count() const {5044SeatState *ss = wl_seat_get_seat_state(wl_seat_current);50455046if (ss && ss->xkb_keymap) {5047return xkb_keymap_num_layouts(ss->xkb_keymap);5048}50495050return 0;5051}50525053int WaylandThread::keyboard_get_current_layout_index() const {5054SeatState *ss = wl_seat_get_seat_state(wl_seat_current);50555056if (ss) {5057return ss->current_layout_index;5058}50595060return 0;5061}50625063void WaylandThread::keyboard_set_current_layout_index(int p_index) {5064SeatState *ss = wl_seat_get_seat_state(wl_seat_current);50655066if (ss) {5067ss->current_layout_index = p_index;5068}5069}50705071String WaylandThread::keyboard_get_layout_name(int p_index) const {5072SeatState *ss = wl_seat_get_seat_state(wl_seat_current);50735074if (ss && ss->xkb_keymap) {5075return String::utf8(xkb_keymap_layout_get_name(ss->xkb_keymap, p_index));5076}50775078return "";5079}50805081Key WaylandThread::keyboard_get_key_from_physical(Key p_key) const {5082SeatState *ss = wl_seat_get_seat_state(wl_seat_current);50835084if (ss && ss->xkb_state) {5085Key modifiers = p_key & KeyModifierMask::MODIFIER_MASK;5086Key keycode_no_mod = p_key & KeyModifierMask::CODE_MASK;50875088xkb_keycode_t xkb_keycode = KeyMappingXKB::get_xkb_keycode(keycode_no_mod);5089Key key = KeyMappingXKB::get_keycode(xkb_state_key_get_one_sym(ss->xkb_state, xkb_keycode));5090return (Key)(key | modifiers);5091}50925093return p_key;5094}50955096Key WaylandThread::keyboard_get_label_from_physical(Key p_key) const {5097SeatState *ss = wl_seat_get_seat_state(wl_seat_current);50985099if (ss && ss->xkb_state) {5100Key modifiers = p_key & KeyModifierMask::MODIFIER_MASK;5101Key keycode_no_mod = p_key & KeyModifierMask::CODE_MASK;51025103xkb_keycode_t xkb_keycode = KeyMappingXKB::get_xkb_keycode(keycode_no_mod);5104xkb_keycode_t xkb_keysym = xkb_state_key_get_one_sym(ss->xkb_state, xkb_keycode);5105char32_t chr = xkb_keysym_to_utf32(xkb_keysym_to_upper(xkb_keysym));5106if (chr != 0) {5107String keysym = String::chr(chr);5108Key key = fix_key_label(keysym[0], KeyMappingXKB::get_keycode(xkb_keysym));5109return (Key)(key | modifiers);5110}5111}51125113return p_key;5114}51155116void WaylandThread::keyboard_echo_keys() {5117SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51185119if (ss) {5120seat_state_echo_keys(ss);5121}5122}51235124void WaylandThread::selection_set_text(const String &p_text) {5125SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51265127if (registry.wl_data_device_manager == nullptr) {5128DEBUG_LOG_WAYLAND_THREAD("Couldn't set selection, wl_data_device_manager global not available.");5129return;5130}51315132if (ss == nullptr) {5133DEBUG_LOG_WAYLAND_THREAD("Couldn't set selection, current seat not set.");5134return;5135}51365137if (ss->wl_data_device == nullptr) {5138DEBUG_LOG_WAYLAND_THREAD("Couldn't set selection, seat doesn't have wl_data_device.");5139return;5140}51415142ss->selection_data = p_text.to_utf8_buffer();51435144if (ss->wl_data_source_selection == nullptr) {5145ss->wl_data_source_selection = wl_data_device_manager_create_data_source(registry.wl_data_device_manager);5146wl_data_source_add_listener(ss->wl_data_source_selection, &wl_data_source_listener, ss);5147wl_data_source_offer(ss->wl_data_source_selection, "text/plain;charset=utf-8");5148wl_data_source_offer(ss->wl_data_source_selection, "text/plain");51495150// TODO: Implement a good way of getting the latest serial from the user.5151wl_data_device_set_selection(ss->wl_data_device, ss->wl_data_source_selection, MAX(ss->pointer_data.button_serial, ss->last_key_pressed_serial));5152}51535154// Wait for the message to get to the server before continuing, otherwise the5155// clipboard update might come with a delay.5156wl_display_roundtrip(wl_display);5157}51585159bool WaylandThread::selection_has_mime(const String &p_mime) const {5160SeatState *ss = wl_seat_get_seat_state(wl_seat_current);51615162if (ss == nullptr) {5163DEBUG_LOG_WAYLAND_THREAD("Couldn't get selection, current seat not set.");5164return false;5165}51665167OfferState *os = wl_data_offer_get_offer_state(ss->wl_data_offer_selection);5168if (!os) {5169return false;5170}51715172return os->mime_types.has(p_mime);5173}51745175Vector<uint8_t> WaylandThread::selection_get_mime(const String &p_mime) const {5176SeatState *ss = wl_seat_get_seat_state(wl_seat_current);5177if (ss == nullptr) {5178DEBUG_LOG_WAYLAND_THREAD("Couldn't get selection, current seat not set.");5179return Vector<uint8_t>();5180}51815182if (ss->wl_data_source_selection) {5183// We have a source so the stuff we're pasting is ours. We'll have to pass the5184// data directly or we'd stall waiting for Godot (ourselves) to send us the5185// data :P51865187OfferState *os = wl_data_offer_get_offer_state(ss->wl_data_offer_selection);5188ERR_FAIL_NULL_V(os, Vector<uint8_t>());51895190if (os->mime_types.has(p_mime)) {5191// All righty, we're offering this type. Let's just return the data as is.5192return ss->selection_data;5193}51945195// ... we don't offer that type. Oh well.5196return Vector<uint8_t>();5197}51985199return _wl_data_offer_read(wl_display, p_mime.utf8().get_data(), ss->wl_data_offer_selection);5200}52015202bool WaylandThread::primary_has_mime(const String &p_mime) const {5203SeatState *ss = wl_seat_get_seat_state(wl_seat_current);52045205if (ss == nullptr) {5206DEBUG_LOG_WAYLAND_THREAD("Couldn't get selection, current seat not set.");5207return false;5208}52095210OfferState *os = wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer);5211if (!os) {5212return false;5213}52145215return os->mime_types.has(p_mime);5216}52175218Vector<uint8_t> WaylandThread::primary_get_mime(const String &p_mime) const {5219SeatState *ss = wl_seat_get_seat_state(wl_seat_current);5220if (ss == nullptr) {5221DEBUG_LOG_WAYLAND_THREAD("Couldn't get primary, current seat not set.");5222return Vector<uint8_t>();5223}52245225if (ss->wp_primary_selection_source) {5226// We have a source so the stuff we're pasting is ours. We'll have to pass the5227// data directly or we'd stall waiting for Godot (ourselves) to send us the5228// data :P52295230OfferState *os = wp_primary_selection_offer_get_offer_state(ss->wp_primary_selection_offer);5231ERR_FAIL_NULL_V(os, Vector<uint8_t>());52325233if (os->mime_types.has(p_mime)) {5234// All righty, we're offering this type. Let's just return the data as is.5235return ss->selection_data;5236}52375238// ... we don't offer that type. Oh well.5239return Vector<uint8_t>();5240}52415242return _wp_primary_selection_offer_read(wl_display, p_mime.utf8().get_data(), ss->wp_primary_selection_offer);5243}52445245void WaylandThread::primary_set_text(const String &p_text) {5246SeatState *ss = wl_seat_get_seat_state(wl_seat_current);52475248if (registry.wp_primary_selection_device_manager == nullptr) {5249DEBUG_LOG_WAYLAND_THREAD("Couldn't set primary, protocol not available.");5250return;5251}52525253if (ss == nullptr) {5254DEBUG_LOG_WAYLAND_THREAD("Couldn't set primary, current seat not set.");5255return;5256}52575258if (ss->wp_primary_selection_device == nullptr) {5259DEBUG_LOG_WAYLAND_THREAD("Couldn't set primary selection, seat doesn't have wp_primary_selection_device.");5260return;5261}52625263ss->primary_data = p_text.to_utf8_buffer();52645265if (ss->wp_primary_selection_source == nullptr) {5266ss->wp_primary_selection_source = zwp_primary_selection_device_manager_v1_create_source(registry.wp_primary_selection_device_manager);5267zwp_primary_selection_source_v1_add_listener(ss->wp_primary_selection_source, &wp_primary_selection_source_listener, ss);5268zwp_primary_selection_source_v1_offer(ss->wp_primary_selection_source, "text/plain;charset=utf-8");5269zwp_primary_selection_source_v1_offer(ss->wp_primary_selection_source, "text/plain");52705271// TODO: Implement a good way of getting the latest serial from the user.5272zwp_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));5273}52745275// Wait for the message to get to the server before continuing, otherwise the5276// clipboard update might come with a delay.5277wl_display_roundtrip(wl_display);5278}52795280void WaylandThread::commit_surfaces() {5281for (KeyValue<DisplayServer::WindowID, WindowState> &pair : windows) {5282wl_surface_commit(pair.value.wl_surface);5283}5284}52855286void WaylandThread::set_frame() {5287frame = true;5288}52895290bool WaylandThread::get_reset_frame() {5291bool old_frame = frame;5292frame = false;52935294return old_frame;5295}52965297// Dispatches events until a frame event is received, a window is reported as5298// suspended or the timeout expires.5299bool WaylandThread::wait_frame_suspend_ms(int p_timeout) {5300// This is a bit of a chicken and egg thing... Looks like the main event loop5301// has to call its rightfully forever-blocking poll right in between5302// `wl_display_prepare_read` and `wl_display_read`. This means, that it will5303// basically be guaranteed to stay stuck in a "prepare read" state, where it5304// will block any other attempt at reading the display fd, such as ours. The5305// solution? Let's make sure the mutex is locked (it should) and unblock the5306// main thread with a roundtrip!5307MutexLock mutex_lock(mutex);5308wl_display_roundtrip(wl_display);53095310if (is_suspended()) {5311// All windows are suspended! The compositor is telling us _explicitly_ that5312// we don't need to draw, without letting us guess through the frame event's5313// timing and stuff like that. Our job here is done.5314return false;5315}53165317if (frame) {5318// We already have a frame! Probably it got there while the caller locked :D5319frame = false;5320return true;5321}53225323struct pollfd poll_fd;5324poll_fd.fd = wl_display_get_fd(wl_display);5325poll_fd.events = POLLIN | POLLHUP;53265327int begin_ms = OS::get_singleton()->get_ticks_msec();5328int remaining_ms = p_timeout;53295330while (remaining_ms > 0) {5331// Empty the event queue while it's full.5332while (wl_display_prepare_read(wl_display) != 0) {5333if (wl_display_dispatch_pending(wl_display) == -1) {5334// Oh no. We'll check and handle any display error below.5335break;5336}53375338if (is_suspended()) {5339return false;5340}53415342if (frame) {5343// We had a frame event in the queue :D5344frame = false;5345return true;5346}5347}53485349int werror = wl_display_get_error(wl_display);53505351if (werror) {5352if (werror == EPROTO) {5353struct wl_interface *wl_interface = nullptr;5354uint32_t id = 0;53555356int error_code = wl_display_get_protocol_error(wl_display, (const struct wl_interface **)&wl_interface, &id);5357CRASH_NOW_MSG(vformat("Wayland protocol error %d on interface %s@%d.", error_code, wl_interface ? wl_interface->name : "unknown", id));5358} else {5359CRASH_NOW_MSG(vformat("Wayland client error code %d.", werror));5360}5361}53625363wl_display_flush(wl_display);53645365// Wait for the event file descriptor to have new data.5366poll(&poll_fd, 1, remaining_ms);53675368if (poll_fd.revents | POLLIN) {5369// Load the queues with fresh new data.5370wl_display_read_events(wl_display);5371} else {5372// Oh well... Stop signaling that we want to read.5373wl_display_cancel_read(wl_display);53745375// We've got no new events :(5376// We won't even bother with checking the frame flag.5377return false;5378}53795380// Let's try dispatching now...5381wl_display_dispatch_pending(wl_display);53825383if (is_suspended()) {5384return false;5385}53865387if (frame) {5388frame = false;5389return true;5390}53915392remaining_ms -= OS::get_singleton()->get_ticks_msec() - begin_ms;5393}53945395DEBUG_LOG_WAYLAND_THREAD("Frame timeout.");5396return false;5397}53985399uint64_t WaylandThread::window_get_last_frame_time(DisplayServer::WindowID p_window_id) const {5400ERR_FAIL_COND_V(!windows.has(p_window_id), false);5401return windows[p_window_id].last_frame_time;5402}54035404bool WaylandThread::window_is_suspended(DisplayServer::WindowID p_window_id) const {5405ERR_FAIL_COND_V(!windows.has(p_window_id), false);5406return windows[p_window_id].suspended;5407}54085409bool WaylandThread::is_fifo_available() const {5410return registry.wp_fifo_manager_name != 0;5411}54125413bool WaylandThread::is_suspended() const {5414for (const KeyValue<DisplayServer::WindowID, WindowState> &E : windows) {5415if (!E.value.suspended) {5416return false;5417}5418}54195420return true;5421}54225423struct godot_embedding_compositor *WaylandThread::get_embedding_compositor() {5424return registry.godot_embedding_compositor;5425}54265427OS::ProcessID WaylandThread::embedded_compositor_get_focused_pid() {5428EmbeddingCompositorState *ecomp_state = godot_embedding_compositor_get_state(registry.godot_embedding_compositor);5429ERR_FAIL_NULL_V(ecomp_state, -1);54305431return ecomp_state->focused_pid;5432}54335434void WaylandThread::destroy() {5435if (!initialized) {5436return;5437}54385439if (wl_display && events_thread.is_started()) {5440thread_data.thread_done.set();54415442// By sending a roundtrip message we're unblocking the polling thread so that5443// it can realize that it's done and also handle every event that's left.5444wl_display_roundtrip(wl_display);54455446events_thread.wait_to_finish();5447}54485449for (KeyValue<DisplayServer::WindowID, WindowState> &pair : windows) {5450WindowState &ws = pair.value;5451if (ws.wp_fractional_scale) {5452wp_fractional_scale_v1_destroy(ws.wp_fractional_scale);5453}54545455if (ws.wp_viewport) {5456wp_viewport_destroy(ws.wp_viewport);5457}54585459if (ws.frame_callback) {5460wl_callback_destroy(ws.frame_callback);5461}54625463#ifdef LIBDECOR_ENABLED5464if (ws.libdecor_frame) {5465libdecor_frame_close(ws.libdecor_frame);5466}5467#endif // LIBDECOR_ENABLED54685469if (ws.xdg_toplevel_decoration) {5470zxdg_toplevel_decoration_v1_destroy(ws.xdg_toplevel_decoration);5471}54725473if (ws.xdg_toplevel) {5474xdg_toplevel_destroy(ws.xdg_toplevel);5475}54765477if (ws.xdg_surface) {5478xdg_surface_destroy(ws.xdg_surface);5479}54805481if (ws.wl_surface) {5482wl_surface_destroy(ws.wl_surface);5483}5484}54855486for (struct wl_seat *wl_seat : registry.wl_seats) {5487SeatState *ss = wl_seat_get_seat_state(wl_seat);5488ERR_FAIL_NULL(ss);54895490wl_seat_destroy(wl_seat);54915492xkb_context_unref(ss->xkb_context);5493xkb_state_unref(ss->xkb_state);5494xkb_keymap_unref(ss->xkb_keymap);5495xkb_compose_table_unref(ss->xkb_compose_table);5496xkb_compose_state_unref(ss->xkb_compose_state);54975498if (ss->wl_keyboard) {5499wl_keyboard_destroy(ss->wl_keyboard);5500}55015502if (ss->keymap_buffer) {5503munmap((void *)ss->keymap_buffer, ss->keymap_buffer_size);5504}55055506if (ss->wl_pointer) {5507wl_pointer_destroy(ss->wl_pointer);5508}55095510if (ss->cursor_frame_callback) {5511// We don't need to set a null userdata for safety as the thread is done.5512wl_callback_destroy(ss->cursor_frame_callback);5513}55145515if (ss->cursor_surface) {5516wl_surface_destroy(ss->cursor_surface);5517}55185519if (ss->wl_data_device) {5520wl_data_device_destroy(ss->wl_data_device);5521}55225523if (ss->wp_cursor_shape_device) {5524wp_cursor_shape_device_v1_destroy(ss->wp_cursor_shape_device);5525}55265527if (ss->wp_relative_pointer) {5528zwp_relative_pointer_v1_destroy(ss->wp_relative_pointer);5529}55305531if (ss->wp_locked_pointer) {5532zwp_locked_pointer_v1_destroy(ss->wp_locked_pointer);5533}55345535if (ss->wp_confined_pointer) {5536zwp_confined_pointer_v1_destroy(ss->wp_confined_pointer);5537}55385539if (ss->wp_tablet_seat) {5540zwp_tablet_seat_v2_destroy(ss->wp_tablet_seat);5541}55425543for (struct zwp_tablet_tool_v2 *tool : ss->tablet_tools) {5544TabletToolState *state = wp_tablet_tool_get_state(tool);5545if (state) {5546memdelete(state);5547}55485549zwp_tablet_tool_v2_destroy(tool);5550}55515552if (ss->wp_text_input) {5553zwp_text_input_v3_destroy(ss->wp_text_input);5554}55555556memdelete(ss);5557}55585559if (registry.wp_tablet_manager) {5560zwp_tablet_manager_v2_destroy(registry.wp_tablet_manager);5561}55625563if (registry.wp_text_input_manager) {5564zwp_text_input_manager_v3_destroy(registry.wp_text_input_manager);5565}55665567for (struct wl_output *wl_output : registry.wl_outputs) {5568ERR_FAIL_NULL(wl_output);55695570memdelete(wl_output_get_screen_state(wl_output));5571wl_output_destroy(wl_output);5572}55735574if (registry.godot_embedding_compositor) {5575EmbeddingCompositorState *es = godot_embedding_compositor_get_state(registry.godot_embedding_compositor);5576ERR_FAIL_NULL(es);55775578es->mapped_clients.clear();55795580for (struct godot_embedded_client *client : es->clients) {5581godot_embedded_client_destroy(client);5582}5583es->clients.clear();55845585memdelete(es);55865587godot_embedding_compositor_destroy(registry.godot_embedding_compositor);5588}55895590if (wl_cursor_theme) {5591wl_cursor_theme_destroy(wl_cursor_theme);5592}55935594if (registry.wp_idle_inhibit_manager) {5595zwp_idle_inhibit_manager_v1_destroy(registry.wp_idle_inhibit_manager);5596}55975598if (registry.wp_pointer_constraints) {5599zwp_pointer_constraints_v1_destroy(registry.wp_pointer_constraints);5600}56015602if (registry.wp_pointer_gestures) {5603zwp_pointer_gestures_v1_destroy(registry.wp_pointer_gestures);5604}56055606if (registry.wp_relative_pointer_manager) {5607zwp_relative_pointer_manager_v1_destroy(registry.wp_relative_pointer_manager);5608}56095610if (registry.xdg_activation) {5611xdg_activation_v1_destroy(registry.xdg_activation);5612}56135614if (registry.xdg_system_bell) {5615xdg_system_bell_v1_destroy(registry.xdg_system_bell);5616}56175618if (registry.xdg_toplevel_icon_manager) {5619xdg_toplevel_icon_manager_v1_destroy(registry.xdg_toplevel_icon_manager);56205621if (xdg_icon) {5622xdg_toplevel_icon_v1_destroy(xdg_icon);5623}56245625if (icon_buffer) {5626wl_buffer_destroy(icon_buffer);5627}5628}56295630if (registry.xdg_decoration_manager) {5631zxdg_decoration_manager_v1_destroy(registry.xdg_decoration_manager);5632}56335634if (registry.wp_cursor_shape_manager) {5635wp_cursor_shape_manager_v1_destroy(registry.wp_cursor_shape_manager);5636}56375638if (registry.wp_fractional_scale_manager) {5639wp_fractional_scale_manager_v1_destroy(registry.wp_fractional_scale_manager);5640}56415642if (registry.wp_viewporter) {5643wp_viewporter_destroy(registry.wp_viewporter);5644}56455646if (registry.xdg_wm_base) {5647xdg_wm_base_destroy(registry.xdg_wm_base);5648}56495650// NOTE: Deprecated.5651if (registry.xdg_exporter_v1) {5652zxdg_exporter_v1_destroy(registry.xdg_exporter_v1);5653}56545655if (registry.xdg_exporter_v2) {5656zxdg_exporter_v2_destroy(registry.xdg_exporter_v2);5657}5658if (registry.wl_shm) {5659wl_shm_destroy(registry.wl_shm);5660}56615662if (registry.wl_compositor) {5663wl_compositor_destroy(registry.wl_compositor);5664}56655666if (wl_registry) {5667wl_registry_destroy(wl_registry);5668}56695670wl_display_roundtrip(wl_display);56715672if (wl_display) {5673wl_display_disconnect(wl_display);5674}5675}56765677#endif // WAYLAND_ENABLED567856795680