Blender V5.3
GHOST_SystemWayland.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2020-2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
10#include "GHOST_Context.hh"
11#include "GHOST_Event.hh"
12#include "GHOST_EventButton.hh"
13#include "GHOST_EventCursor.hh"
15#include "GHOST_EventKey.hh"
17#include "GHOST_EventWheel.hh"
18#include "GHOST_PathUtils.hh"
19#include "GHOST_TimerManager.hh"
20#include "GHOST_WaylandUtils.hh"
22#include "GHOST_utildefines.hh"
23
24#ifdef WITH_OPENGL_BACKEND
25# include "GHOST_ContextEGL.hh"
26#endif
27
28#ifdef WITH_VULKAN_BACKEND
29# include "GHOST_ContextVK.hh"
30#endif
31
32#ifdef WITH_INPUT_NDOF
34#endif
35
36#ifdef WITH_GHOST_CSD
38#endif
39
40#ifdef WITH_GHOST_WAYLAND_DYNLOAD
41# include <wayland_dynload_API.h> /* For `ghost_wl_dynload_libraries`. */
42#endif
43
44#ifdef WITH_OPENGL_BACKEND
45# ifdef WITH_GHOST_WAYLAND_DYNLOAD
46# include <wayland_dynload_egl.h>
47# endif
48# include <wayland-egl.h>
49#endif /* WITH_OPENGL_BACKEND */
50
51#include <algorithm>
52#include <atomic>
53#include <optional>
54#include <string_view>
55#include <thread>
56#include <unordered_set>
57#include <variant>
58
59#ifdef WITH_GHOST_WAYLAND_DYNLOAD
61#endif
62#include <wayland-cursor.h>
63
64#include <xkbcommon/xkbcommon-compose.h>
65#include <xkbcommon/xkbcommon.h>
66
67/* Generated by `wayland-scanner`. */
68#include <color-management-v1-client-protocol.h>
69#include <cursor-shape-v1-client-protocol.h>
70#include <fractional-scale-v1-client-protocol.h>
71#include <pointer-constraints-unstable-v1-client-protocol.h>
72#include <pointer-gestures-unstable-v1-client-protocol.h>
73#include <primary-selection-unstable-v1-client-protocol.h>
74#include <relative-pointer-unstable-v1-client-protocol.h>
75#include <tablet-v2-client-protocol.h>
76#include <viewporter-client-protocol.h>
77#include <xdg-activation-v1-client-protocol.h>
78#include <xdg-output-unstable-v1-client-protocol.h>
79#include <xdg-toplevel-icon-v1-client-protocol.h>
80#ifdef WITH_INPUT_IME
81# include <text-input-unstable-v3-client-protocol.h>
82#endif
83
84/* Decorations `xdg_decor`. */
85#include <xdg-decoration-unstable-v1-client-protocol.h>
86#include <xdg-shell-client-protocol.h>
87/* End `xdg_decor`. */
88
89#include <fcntl.h>
90#include <sys/mman.h>
91#include <unistd.h>
92
93#include <cstdlib> /* For `exit`. */
94#include <cstring>
95#include <mutex>
96
97#include <pthread.h> /* For setting the thread priority. */
98
99#include <poll.h>
100
101/* Logging, use `ghost.wl.*` prefix. */
102#include "CLG_log.h"
103
104#include "GHOST_TimerTask.hh"
105
107
108#include "IMB_imbuf.hh"
109#include "IMB_imbuf_types.hh"
110
111static CLG_LogRef LOG = {"ghost.dbus"};
112
113/* -------------------------------------------------------------------- */
116
117#ifdef WITH_GHOST_CSD
119// # define USE_GHOST_CSD_FORCE
120#endif
121
123
124/* -------------------------------------------------------------------- */
127
129
130static void output_handle_done(void *data, wl_output *wl_output);
131
135
137 uint32_t name,
138 int *r_interface_slot);
139static void gwl_registry_entry_remove_all(GWL_Display *display);
140
143static int gwl_registry_handler_interface_slot_from_string(const char *interface);
144static const GWL_RegistryHandler *gwl_registry_handler_from_interface_slot(int interface_slot);
145
147 xkb_compose_state *compose_state,
148 xkb_state *state,
149 const xkb_keycode_t key,
150 char r_utf8_buf[sizeof(GHOST_TEventKeyData::utf8_buf)]);
151
152#ifdef USE_EVENT_BACKGROUND_THREAD
154
156constexpr size_t events_pending_default_size = 4096 / sizeof(void *);
157
158#endif /* USE_EVENT_BACKGROUND_THREAD */
159
162#define pushEvent DONT_USE
163
165
166/* -------------------------------------------------------------------- */
169
177#define USE_GNOME_CONFINE_HACK
182// #define USE_GNOME_CONFINE_HACK_ALWAYS_ON
183
184#ifdef USE_GNOME_CONFINE_HACK
185static bool use_gnome_confine_hack = false;
186#endif
187
193#define USE_KDE_TABLET_HIDDEN_CURSOR_HACK
194#ifdef USE_KDE_TABLET_HIDDEN_CURSOR_HACK
196#endif
197
198#ifdef WITH_VULKAN_BACKEND
207# define USE_KDE_VULKAN_UNGRAB_CURSOR_HACK
208#endif
209#ifdef USE_KDE_VULKAN_UNGRAB_CURSOR_HACK
210static bool use_kde_vulkan_ungrab_cursor_hack = false;
211#endif
212
217#define USE_GNOME_MOTION_MISSING_TIME_HACK
218
219#ifdef USE_GNOME_MOTION_MISSING_TIME_HACK
221#endif
222
224
225/* -------------------------------------------------------------------- */
230
244// #define USE_VERBOSE_OLD_IFACE_PRINT
245
246#ifdef USE_VERBOSE_OLD_IFACE_PRINT
247# define _VERBOSE_OLD_IFACE_PRINT(params_version, version_max) \
248 ((params_version > version_max) ? \
249 fprintf(stderr, \
250 "%s: version_max=%u, is smaller than run-time version=%u\n", \
251 __func__, \
252 version_max, \
253 params_version) : \
254 0)
255#else
256# define _VERBOSE_OLD_IFACE_PRINT(params_version, version_max) \
257 ((void)(params_version), (version_max))
258#endif
259
260#define GWL_IFACE_VERSION_CLAMP(params_version, version_min, version_max) \
261 ((void)_VERBOSE_OLD_IFACE_PRINT(params_version, version_max), \
262 std::clamp(params_version, version_min, version_max))
263
268#define USE_NON_LATIN_KB_WORKAROUND
269
270constexpr uint32_t WL_NAME_UNSET = uint32_t(-1);
271
272constexpr uint32_t WL_SERIAL_NONE = uint32_t(0);
273
278#define WL_FIXED_TO_INT_FOR_WINDOW_V2(win, xy) \
279 wl_fixed_to_int((win)->wl_fixed_to_window((xy)[0])), \
280 wl_fixed_to_int((win)->wl_fixed_to_window((xy)[1])),
281
283
284/* -------------------------------------------------------------------- */
291
295enum {
296 BTN_LEFT = 0x110,
297 BTN_RIGHT = 0x111,
298 BTN_MIDDLE = 0x112,
299 BTN_SIDE = 0x113,
300 BTN_EXTRA = 0x114,
301 BTN_FORWARD = 0x115,
302 BTN_BACK = 0x116
303};
304// #define BTN_TASK 0x117 /* UNUSED. */
305
306#define BTN_RANGE_MIN BTN_LEFT
307#define BTN_RANGE_MAX BTN_BACK
308
317enum {
319 BTN_STYLUS = 0x14b,
321 BTN_STYLUS2 = 0x14c,
323 BTN_STYLUS3 = 0x149,
324};
325
331enum {
339
340#ifdef USE_NON_LATIN_KB_WORKAROUND
341 KEY_1 = 2,
342 KEY_2 = 3,
343 KEY_3 = 4,
344 KEY_4 = 5,
345 KEY_5 = 6,
346 KEY_6 = 7,
347 KEY_7 = 8,
348 KEY_8 = 9,
349 KEY_9 = 10,
350 KEY_0 = 11,
351#endif
352};
353
354/* Only defined in XKB 1.8x and newer, it seems XKB doesn't provide a version define. */
355#ifndef XKB_VMOD_NAME_HYPER
356# define XKB_VMOD_NAME_HYPER "Hyper"
357#endif
358
360
361/* -------------------------------------------------------------------- */
366
367enum {
373};
374constexpr int MOD_INDEX_NUM = MOD_INDEX_HYPER + 1;
375
383
385 /*MOD_INDEX_SHIFT*/
386 {
387 /*display_name*/ "Shift",
388 /*xkb_id*/ XKB_MOD_NAME_SHIFT,
389 /*key_l*/ GHOST_kKeyLeftShift,
390 /*key_r*/ GHOST_kKeyRightShift,
393 },
394 /*MOD_INDEX_ALT*/
395 {
396 /*display_name*/ "Alt",
397 /*xkb_id*/ XKB_MOD_NAME_ALT,
398 /*key_l*/ GHOST_kKeyLeftAlt,
399 /*key_r*/ GHOST_kKeyRightAlt,
402 },
403 /*MOD_INDEX_CTRL*/
404 {
405 /*display_name*/ "Control",
406 /*xkb_id*/ XKB_MOD_NAME_CTRL,
407 /*key_l*/ GHOST_kKeyLeftControl,
408 /*key_r*/ GHOST_kKeyRightControl,
411 },
412 /*MOD_INDEX_OS*/
413 {
414 /*display_name*/ "OS",
415 /*xkb_id*/ XKB_MOD_NAME_LOGO,
416 /*key_l*/ GHOST_kKeyLeftOS,
417 /*key_r*/ GHOST_kKeyRightOS,
418 /*mod_l*/ GHOST_kModifierKeyLeftOS,
420 },
421 /*MOD_INDEX_HYPER*/
422 {
423 /*display_name*/ "Hyper",
424 /*xkb_id*/ XKB_VMOD_NAME_HYPER,
425 /*key_l*/ GHOST_kKeyLeftHyper,
426 /*key_r*/ GHOST_kKeyRightHyper,
429 },
430};
431
433
434/* -------------------------------------------------------------------- */
437
440 const char *data = nullptr;
441 size_t data_size = 0;
442};
443
445{
446 free(const_cast<char *>(buffer->data));
447 buffer->data = nullptr;
448 buffer->data_size = 0;
449}
450
452{
453 free(const_cast<char *>(buffer->data));
454 buffer->data_size = strlen(str);
455 char *data = static_cast<char *>(malloc(buffer->data_size));
456 std::memcpy(data, str, buffer->data_size);
457 buffer->data = data;
458}
459
461
462/* -------------------------------------------------------------------- */
465
470constexpr int EVDEV_OFFSET = 8;
471
481 wp_cursor_shape_device_v1_shape enum_id = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT;
482 wp_cursor_shape_device_v1 *device = nullptr;
483};
484
486
488 struct {
489 /* Everything below in this wl struct is used for custom cursor shapes. */
490 wl_surface *surface_cursor = nullptr;
491 wl_buffer *buffer = nullptr;
492 wl_cursor_image image = {0};
493 } wl;
494
496
497 bool visible = false;
504 bool is_hardware = true;
506 bool is_custom = false;
507 void *custom_data = nullptr;
510
513
519 int theme_size = 0;
523 bool use_dark_theme = false;
524};
525
527
528/* -------------------------------------------------------------------- */
531
539
541
542 /* NOTE: Keep buttons last (simplifies switch statement). */
543
544 /* Left mouse button. */
547 /* Middle mouse button. */
550 /* Right mouse button. */
553 /* Mouse button number 4. */
556};
558
560 GHOST_kButtonMaskLeft, /* `Stylus0_*`. */
561 GHOST_kButtonMaskMiddle, /* `Stylus1_*`. */
562 GHOST_kButtonMaskRight, /* `Stylus2_*`. */
563 GHOST_kButtonMaskButton4, /* `Stylus3_*`. */
564};
565
572
574 struct {
579 wl_surface *surface_cursor = nullptr;
580 } wl;
581
583
584 GWL_Seat *seat = nullptr;
585
587 uint32_t serial = 0;
588
590 bool proximity = false;
591
592 GHOST_TabletData data = GHOST_TABLET_DATA_NONE;
593
595 int32_t xy[2] = {0};
596 bool has_xy = false;
597
614};
615
618 const uint32_t serial)
619{
620 const int ty_mask = 1 << int(ty);
621 /* Motion callback may run multiple times. */
622 if (tablet_tool->frame_pending.frame_types_mask & ty_mask) {
623 return;
624 }
625 tablet_tool->frame_pending.frame_types_mask |= ty_mask;
626 int i = tablet_tool->frame_pending.frame_types_num++;
627 tablet_tool->frame_pending.frame_types[i] = ty;
628 tablet_tool->frame_pending.frame_serial[i] = serial;
629}
630
632{
633 tablet_tool->frame_pending.frame_types_num = 0;
634 tablet_tool->frame_pending.frame_types_mask = 0;
635}
636
638
639/* -------------------------------------------------------------------- */
642
647
649 struct {
650 wl_data_offer *id = nullptr;
651 } wl;
652
653 std::unordered_set<std::string> types;
654
655 struct {
663 enum wl_data_device_manager_dnd_action source_actions = WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE;
664 enum wl_data_device_manager_dnd_action action = WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE;
666 wl_fixed_t xy[2] = {0, 0};
668};
669
671
672/* -------------------------------------------------------------------- */
675
677
679 struct {
680 wl_data_source *source = nullptr;
681 } wl;
682
684};
685
687
688/* -------------------------------------------------------------------- */
691
701 GWL_Seat *seat = nullptr;
702
703 xkb_keycode_t key_code;
704
707
712 struct {
715};
716
719 bool use_lock = false;
720 bool use_confine = false;
721};
722
727
729 struct {
734 wl_surface *surface_window = nullptr;
735#ifdef WITH_GHOST_CSD
741 wl_surface *surface_window_csd_margin = nullptr;
742#endif
743 } wl;
744
758 wl_fixed_t xy[2] = {0, 0};
759
761 std::unordered_set<const GWL_Output *> outputs;
762
764
770 uint32_t serial = 0;
771
773};
774
777
784 Scroll,
785
786 /* NOTE: Keep buttons last (simplifies switch statement). */
787
788 /* #BTN_LEFT mouse button. */
791 /* #BTN_RIGHT mouse button. */
794 /* #BTN_MIDDLE mouse button. */
797 /* #BTN_SIDE mouse button. */
800 /* #BTN_EXTRA mouse button. */
803 /* #BTN_FORWARD mouse button. */
806 /* #BTN_BACK mouse button. */
809
810#define GWL_SeatStatePointer_EventTypes_NUM (int(GWL_Pointer_EventTypes::Button6_Up) + 1)
811};
812
814 GHOST_kButtonMaskLeft, /* `Button0_*` / #BTN_LEFT. */
815 GHOST_kButtonMaskRight, /* `Button1_*` / #BTN_RIGHT. */
816 GHOST_kButtonMaskMiddle, /* `Button2_*` / #BTN_MIDDLE. */
817 GHOST_kButtonMaskButton4, /* `Button3_*` / #BTN_SIDE. */
818 GHOST_kButtonMaskButton5, /* `Button4_*` / #BTN_EXTRA. */
819 GHOST_kButtonMaskButton6, /* `Button5_*` / #BTN_FORWARD. */
820 GHOST_kButtonMaskButton7, /* `Button6_*` / #BTN_BACK. */
821};
822
824 "Buttons missing");
825
840
842 const GWL_Pointer_EventTypes ty,
843 const uint32_t serial,
844 const uint64_t event_ms)
845{
846 /* It's a quirk of WAYLAND that most scroll events don't have a time-stamp.
847 * Scroll events use their own time-stamp (see #GWL_SeatStatePointerScroll::event_ms usage).
848 * Ensure the API is used as intended. */
850 GHOST_ASSERT(event_ms == 0, "Scroll events must not have a time-stamp");
851 }
852 else {
853 GHOST_ASSERT(event_ms != 0, "Non-scroll events must have a time-stamp");
854 }
855
856 const int ty_mask = 1 << int(ty);
857 /* Motion callback may run multiple times. */
858 if (pointer_events->frame_pending.frame_types_mask & ty_mask) {
859 return;
860 }
861 pointer_events->frame_pending.frame_types_mask |= ty_mask;
862 int i = pointer_events->frame_pending.frame_types_num++;
863 pointer_events->frame_pending.frame_types[i] = ty;
864 pointer_events->frame_pending.frame_serial[i] = serial;
865 pointer_events->frame_pending.frame_event_ms[i] = event_ms;
866}
867
869{
870 pointer_events->frame_pending.frame_types_num = 0;
871 pointer_events->frame_pending.frame_types_mask = 0;
872}
873
880
881static constexpr int smooth_as_discrete_steps = 2400;
882
889 wl_fixed_t smooth_xy[2] = {0, 0};
891 int32_t discrete_xy[2] = {0, 0};
897 bool inverted_xy[2] = {false, false};
899 enum wl_pointer_axis_source axis_source = WL_POINTER_AXIS_SOURCE_WHEEL;
900
905 bool has_event_ms = false;
908
910};
911
923 wl_fixed_t value = 0;
924 wl_fixed_t factor = 1;
925};
926
928 const wl_fixed_t add)
929{
930 const int result_prev = wl_fixed_to_int(sf->value * sf->factor);
931 sf->value += add;
932 const int result_curr = wl_fixed_to_int(sf->value * sf->factor);
933 return result_curr - result_prev;
934}
935
944
949
951 struct {
956 wl_surface *surface_window = nullptr;
957 } wl;
958
960 uint32_t serial = 0;
961};
962
971
973 xdg_wm_base *shell = nullptr;
975
976 zxdg_decoration_manager_v1 *manager = nullptr;
978};
979
981{
982 if (decor->manager) {
983 gwl_registry_entry_remove_by_name(display, decor->manager_name, nullptr);
984 GHOST_ASSERT(decor->manager == nullptr, "Internal registry error");
985 }
986 if (decor->shell) {
987 gwl_registry_entry_remove_by_name(display, decor->shell_name, nullptr);
988 GHOST_ASSERT(decor->shell == nullptr, "Internal registry error");
989 }
990 delete decor;
991}
992
994
996 struct {
997 zwp_primary_selection_offer_v1 *id = nullptr;
998 } wp;
999
1000 std::unordered_set<std::string> types;
1001};
1002
1004
1006 struct {
1007 zwp_primary_selection_source_v1 *source = nullptr;
1009
1011};
1012
1022
1024{
1025 if (primary->data_offer == nullptr) {
1026 return;
1027 }
1028 zwp_primary_selection_offer_v1_destroy(primary->data_offer->wp.id);
1029 delete primary->data_offer;
1030 primary->data_offer = nullptr;
1031}
1032
1034{
1035 GWL_PrimarySelection_DataSource *data_source = primary->data_source;
1036 if (data_source == nullptr) {
1037 return;
1038 }
1040 if (data_source->wp.source) {
1041 zwp_primary_selection_source_v1_destroy(data_source->wp.source);
1042 }
1043 delete primary->data_source;
1044 primary->data_source = nullptr;
1045}
1046
1047#ifdef WITH_INPUT_IME
1048struct GWL_SeatIME {
1056 wl_surface *surface_window = nullptr;
1057 GHOST_TEventImeData event_ime_data = {
1058 /* Storage for #GHOST_TEventImeData::result
1059 * (the result of the `commit_string` callback). */
1060 /*result*/ "",
1061 /* Storage for #GHOST_TEventImeData::composite
1062 * (the result of the `preedit_string` callback). */
1063 /*composite*/ "",
1064 /*cursor_position*/ -1,
1065 /*target_start*/ -1,
1066 /*target_end*/ -1,
1067 };
1069 bool is_enabled = false;
1074 bool has_preedit = false;
1075
1077 bool result_is_null = false;
1079 bool composite_is_null = false;
1080
1082 bool has_preedit_string_callback = false;
1084 bool has_commit_string_callback = false;
1085
1087 struct {
1088 int x = -1;
1089 int y = -1;
1090 int w = -1;
1091 int h = -1;
1092 } rect;
1093};
1094#endif /* WITH_INPUT_IME */
1095
1096struct GWL_Seat {
1097
1099 struct {
1100 wl_seat *seat = nullptr;
1101 wl_pointer *pointer = nullptr;
1102 wl_touch *touch = nullptr;
1103 wl_keyboard *keyboard = nullptr;
1104
1106 wl_data_device *data_device = nullptr;
1108
1110 struct {
1111 zwp_tablet_seat_v2 *tablet_seat = nullptr;
1112
1113#ifdef ZWP_POINTER_GESTURE_HOLD_V1_INTERFACE
1114 zwp_pointer_gesture_hold_v1 *pointer_gesture_hold = nullptr;
1115#endif
1116#ifdef ZWP_POINTER_GESTURE_PINCH_V1_INTERFACE
1117 zwp_pointer_gesture_pinch_v1 *pointer_gesture_pinch = nullptr;
1118#endif
1119#ifdef ZWP_POINTER_GESTURE_SWIPE_V1_INTERFACE
1120 zwp_pointer_gesture_swipe_v1 *pointer_gesture_swipe = nullptr;
1121#endif
1122
1123 zwp_relative_pointer_v1 *relative_pointer = nullptr;
1124 zwp_locked_pointer_v1 *locked_pointer = nullptr;
1125 zwp_confined_pointer_v1 *confined_pointer = nullptr;
1126
1127 zwp_primary_selection_device_v1 *primary_selection_device = nullptr;
1128
1130 std::unordered_set<zwp_tablet_tool_v2 *> tablet_tools;
1131
1132#ifdef WITH_INPUT_IME
1133 zwp_text_input_v3 *text_input = nullptr;
1134#endif
1136
1138 struct {
1139 xkb_context *context = nullptr;
1140
1142 xkb_compose_table *compose_table = nullptr;
1143
1145 xkb_compose_state *compose_state = nullptr;
1146
1147 xkb_state *state = nullptr;
1151 xkb_state *state_empty = nullptr;
1152
1157 xkb_state *state_empty_with_shift = nullptr;
1162 xkb_state *state_empty_with_numlock = nullptr;
1163
1167 xkb_layout_index_t layout_active = 0;
1173 xkb_layout_index_t layout_fallback = XKB_LAYOUT_INVALID;
1175
1176#ifdef WITH_INPUT_IME
1177 GWL_SeatIME ime;
1178#endif
1179
1181
1182 std::string name;
1183
1186
1192
1205
1207
1215 struct {
1216 bool is_touching = false;
1217 uint32_t down_id = 0;
1218 bool down_pending = false;
1221 bool up_pending = false;
1224 bool motion_pending = false;
1227
1228#ifdef USE_GNOME_CONFINE_HACK
1230#endif
1232 wl_fixed_t grab_lock_xy[2] = {0, 0};
1233
1235
1236#ifdef USE_NON_LATIN_KB_WORKAROUND
1238#endif
1239
1242
1248 xkb_mod_index_t xkb_keymap_mod_index[MOD_INDEX_NUM] = {XKB_MOD_INVALID};
1249
1250 /* Cache result for other modifiers which aren't stored in `xkb_keymap_mod_index`
1251 * since their depressed state isn't tracked. */
1252
1254 xkb_mod_index_t xkb_keymap_mod_index_mod2 = XKB_MOD_INVALID;
1256 xkb_mod_index_t xkb_keymap_mod_index_numlock = XKB_MOD_INVALID;
1257
1258 struct {
1260 int32_t rate = 0;
1262 int32_t delay = 0;
1269 GHOST_ITimerTask *timer = nullptr;
1271
1275
1279
1285 std::optional<GHOST_TSuccess> data_offer_copy_paste_has_image = std::nullopt;
1286
1289
1291
1299};
1300
1302{
1303 if (seat->pointer.serial == seat->cursor_source_serial) {
1304 return &seat->pointer;
1305 }
1306 if (seat->tablet.serial == seat->cursor_source_serial) {
1307 return &seat->tablet;
1308 }
1309 if (seat->touch.serial == seat->cursor_source_serial) {
1310 return &seat->touch;
1311 }
1312 return nullptr;
1313}
1314
1316 GWL_Seat *seat, const wl_surface *wl_surface)
1317{
1319 return &seat->pointer;
1320 }
1322 return &seat->tablet;
1323 }
1324 GHOST_ASSERT(0, "Surface found without pointer/tablet tag");
1325 return nullptr;
1326}
1327
1334{
1335 seat_state_pointer->wl.surface_window = wl_surface;
1336#ifdef WITH_GHOST_CSD
1337 seat_state_pointer->wl.surface_window_csd_margin = nullptr;
1338#endif
1339}
1340
1341#ifdef USE_NON_LATIN_KB_WORKAROUND
1342static xkb_layout_index_t xkb_keymap_get_fallback_layout(xkb_keymap *keymap,
1343 const xkb_layout_index_t layout_active);
1344#endif
1345
1353{
1354 const xkb_layout_index_t group = seat->xkb.layout_active;
1355 const xkb_mod_index_t mod_shift = seat->xkb_keymap_mod_index[MOD_INDEX_SHIFT];
1356 const xkb_mod_index_t mod_mod2 = seat->xkb_keymap_mod_index_mod2;
1357 const xkb_mod_index_t mod_numlock = seat->xkb_keymap_mod_index_numlock;
1358
1359 /* Handle `state_empty`. */
1360 xkb_state_update_mask(seat->xkb.state_empty, 0, 0, 0, 0, 0, group);
1361
1362 /* Handle `state_empty_with_shift`. */
1363 GHOST_ASSERT((mod_shift == XKB_MOD_INVALID) == (seat->xkb.state_empty_with_shift == nullptr),
1364 "Invalid state for SHIFT");
1365 if (seat->xkb.state_empty_with_shift) {
1366 xkb_state_update_mask(seat->xkb.state_empty_with_shift, 1 << mod_shift, 0, 0, 0, 0, group);
1367 }
1368
1369 /* Handle `state_empty_with_numlock`. */
1370 GHOST_ASSERT((mod_mod2 == XKB_MOD_INVALID || mod_numlock == XKB_MOD_INVALID) ==
1371 (seat->xkb.state_empty_with_numlock == nullptr),
1372 "Invalid state for NUMLOCK");
1373 if (seat->xkb.state_empty_with_numlock) {
1374 xkb_state_update_mask(
1375 seat->xkb.state_empty_with_numlock, 1 << mod_mod2, 0, 1 << mod_numlock, 0, 0, group);
1376 }
1377
1378#ifdef USE_NON_LATIN_KB_WORKAROUND
1379 /* Re-evaluate against the now-current active layout. The flag must track the active layout
1380 * (not just layout 0) because `state_empty_with_shift` follows the active layout and the
1381 * digit-row workaround reads from it. */
1382 seat->xkb_use_non_latin_workaround = false;
1383 if (seat->xkb.state_empty_with_shift) {
1384 seat->xkb_use_non_latin_workaround = true;
1385 for (xkb_keycode_t key_code = KEY_1 + EVDEV_OFFSET; key_code <= KEY_0 + EVDEV_OFFSET;
1386 key_code++)
1387 {
1388 const xkb_keysym_t sym_test = xkb_state_key_get_one_sym(seat->xkb.state_empty_with_shift,
1389 key_code);
1390 if (!(sym_test >= XKB_KEY_0 && sym_test <= XKB_KEY_9)) {
1391 seat->xkb_use_non_latin_workaround = false;
1392 break;
1393 }
1394 }
1395 }
1396
1397 /* The fall-back layout is selected relative to the active layout, so recompute on change. */
1398 seat->xkb.layout_fallback = xkb_keymap_get_fallback_layout(xkb_state_get_keymap(seat->xkb.state),
1399 group);
1400#endif
1401}
1402
1405{
1406 GWL_KeyRepeatPlayload *payload = static_cast<GWL_KeyRepeatPlayload *>(task->getUserData());
1407
1408 GWL_Seat *seat = payload->seat;
1409 wl_surface *wl_surface_focus = seat->keyboard.wl.surface_window;
1410 if (wl_surface_focus == nullptr) [[unlikely]] {
1411 return;
1412 }
1413
1414 GHOST_IWindow *win = ghost_wl_surface_user_data(wl_surface_focus);
1415 GHOST_SystemWayland *system = seat->system;
1416 const uint64_t event_ms = payload->time_ms_init + time_ms;
1417 /* Calculate this value every time in case modifier keys are pressed. */
1418
1419 char utf8_buf[sizeof(GHOST_TEventKeyData::utf8_buf)] = {'\0'};
1420 if (seat->xkb.compose_state &&
1422 seat->xkb.compose_state, seat->xkb.state, payload->key_code, utf8_buf))
1423 {
1424 /* `utf8_buf` has been filled by a compose action. */
1425 }
1426 else {
1427 xkb_state_key_get_utf8(seat->xkb.state, payload->key_code, utf8_buf, sizeof(utf8_buf));
1428 }
1429
1430 system->pushEvent_maybe_pending(std::make_unique<GHOST_EventKey>(
1431 event_ms, GHOST_kEventKeyDown, win, payload->key_data.gkey, true, utf8_buf));
1432}
1433
1442 GHOST_TimerProcPtr key_repeat_fn,
1443 GHOST_TUserDataPtr payload,
1444 const bool use_delay)
1445{
1446 /* Caller is expected to ensure this. */
1447 GHOST_ASSERT(seat->key_repeat.rate > 0, "invalid rate");
1448 GHOST_SystemWayland *system = seat->system;
1449 const uint64_t time_now = system->getMilliSeconds();
1450 const uint64_t time_step = 1000 / seat->key_repeat.rate;
1451 const uint64_t time_start = use_delay ? seat->key_repeat.delay : time_step;
1452
1453 static_cast<GWL_KeyRepeatPlayload *>(payload)->time_ms_init = time_now;
1454
1455 GHOST_TimerTask *timer = new GHOST_TimerTask(
1456 time_now + time_start, time_step, key_repeat_fn, payload);
1457 seat->key_repeat.timer = timer;
1458 system->key_repeat_timer_manager()->addTimer(timer);
1459}
1460
1465{
1466 GHOST_SystemWayland *system = seat->system;
1468 static_cast<GHOST_TimerTask *>(seat->key_repeat.timer));
1469 seat->key_repeat.timer = nullptr;
1470}
1471
1472#ifdef WITH_INPUT_IME
1473
1474static void gwl_seat_ime_full_reset(GWL_Seat *seat)
1475{
1476 const GWL_SeatIME ime_default{};
1477 /* Preserve the following members since they represent the state of the connection to Wayland.
1478 * or which callbacks have run (which shouldn't be reset). */
1479 wl_surface *surface_window = seat->ime.surface_window;
1480 const bool is_enabled = seat->ime.is_enabled;
1481 const bool has_preedit_string_callback = seat->ime.has_preedit_string_callback;
1482 const bool has_commit_string_callback = seat->ime.has_commit_string_callback;
1483
1484 seat->ime = ime_default;
1485
1486 seat->ime.surface_window = surface_window;
1487 seat->ime.is_enabled = is_enabled;
1488 seat->ime.has_preedit_string_callback = has_preedit_string_callback;
1489 seat->ime.has_commit_string_callback = has_commit_string_callback;
1490}
1491
1492static void gwl_seat_ime_result_reset(GWL_Seat *seat)
1493{
1494 GHOST_TEventImeData &event_ime_data = seat->ime.event_ime_data;
1495 event_ime_data.result.clear();
1496 seat->ime.result_is_null = false;
1497}
1498
1499static void gwl_seat_ime_preedit_reset(GWL_Seat *seat)
1500{
1501
1502 GHOST_TEventImeData &event_ime_data = seat->ime.event_ime_data;
1503 event_ime_data.composite.clear();
1504 seat->ime.composite_is_null = false;
1505
1506 event_ime_data.cursor_position = -1;
1507 event_ime_data.target_start = -1;
1508 event_ime_data.target_end = -1;
1509}
1510
1511static void gwl_seat_ime_rect_reset(GWL_Seat *seat)
1512{
1513 seat->ime.rect.x = -1;
1514 seat->ime.rect.y = -1;
1515 seat->ime.rect.w = -1;
1516 seat->ime.rect.h = -1;
1517}
1518
1519#endif /* WITH_INPUT_IME */
1520
1522
1523#ifdef WITH_GHOST_DBUS
1524/* -------------------------------------------------------------------- */
1527
1532struct GWL_DBusEvent {
1533 struct CursorSize {
1534 int32_t size;
1535 };
1536 struct CSD_ButtonLayout {
1537 std::string layout;
1538 };
1539
1540 std::variant<CursorSize, CSD_ButtonLayout> data;
1541};
1542
1544#endif /* WITH_GHOST_DBUS */
1545
1546/* -------------------------------------------------------------------- */
1549
1550struct GWL_RegistryEntry;
1551
1563 bool exact_match = false;
1564 uint32_t last = 0;
1566};
1567
1569
1571 struct {
1572 wl_registry *registry = nullptr;
1573 wl_display *display = nullptr;
1574 wl_compositor *compositor = nullptr;
1575 wl_subcompositor *subcompositor = nullptr;
1576 wl_shm *shm = nullptr;
1577
1578 /* Managers. */
1579 wl_data_device_manager *data_device_manager = nullptr;
1581
1583 struct {
1584 /* Managers. */
1585 zwp_tablet_manager_v2 *tablet_manager = nullptr;
1586 zwp_relative_pointer_manager_v1 *relative_pointer_manager = nullptr;
1587 zwp_primary_selection_device_manager_v1 *primary_selection_device_manager = nullptr;
1588 wp_fractional_scale_manager_v1 *fractional_scale_manager = nullptr;
1589 wp_viewporter *viewporter = nullptr;
1590 wp_color_manager_v1 *color_manager = nullptr;
1596 wl_event_queue *color_manager_queue = nullptr;
1597 zwp_pointer_constraints_v1 *pointer_constraints = nullptr;
1598 zwp_pointer_gestures_v1 *pointer_gestures = nullptr;
1599#ifdef WITH_INPUT_IME
1600 zwp_text_input_manager_v3 *text_input_manager = nullptr;
1601#endif
1602 wp_cursor_shape_manager_v1 *cursor_shape_manager = nullptr;
1604
1606 struct {
1607 /* Managers. */
1608 zxdg_output_manager_v1 *output_manager = nullptr;
1609 xdg_activation_v1 *activation_manager = nullptr;
1610 xdg_toplevel_icon_manager_v1 *toplevel_icon_manager = nullptr;
1614
1616
1618
1624
1627
1629
1635 std::vector<GWL_Output *> outputs;
1636 std::vector<GWL_Seat *> seats;
1649
1658 bool background = false;
1659
1663 bool use_window_frame = false;
1673 struct {
1675 int cursor_size = 0;
1676#ifdef WITH_GHOST_CSD
1678 GHOST_CSD_Layout csd_button_layout = {0};
1679#endif
1681
1682#ifdef WITH_GHOST_DBUS
1683 struct {
1688 std::vector<GWL_DBusEvent> events;
1690 std::mutex events_mutex;
1695 std::atomic<bool> has_events = false;
1696 } dbus;
1697#endif /* WITH_GHOST_DBUS */
1698
1699 /* Threaded event handling. */
1700#ifdef USE_EVENT_BACKGROUND_THREAD
1707 pthread_t events_pthread = 0;
1718 int events_pipe[2] = {-1, -1};
1719
1724 std::vector<std::unique_ptr<const GHOST_IEvent>> events_pending;
1727#endif /* USE_EVENT_BACKGROUND_THREAD */
1728
1747
1750};
1751
1759{
1760#ifdef USE_EVENT_BACKGROUND_THREAD
1761 /* End the event thread first, everything below frees memory it accesses. */
1762 if (!display->background) {
1763 if (display->events_pthread) {
1765 }
1766 }
1767#endif
1768
1769 /* For typical WAYLAND use this will always be set.
1770 * However when WAYLAND isn't running, this will early-exit and be null. */
1771 if (display->wl.registry) {
1772 wl_registry_destroy(display->wl.registry);
1773 display->wl.registry = nullptr;
1774 }
1775
1776 /* Unregister items in reverse order. */
1778 if (display->xdg_decor) {
1779 gwl_xdg_decor_system_destroy(display, display->xdg_decor);
1780 display->xdg_decor = nullptr;
1781 }
1782
1783#ifdef WITH_OPENGL_BACKEND
1784 if (display->wl.display) {
1785 if (eglGetDisplay) {
1786 ::eglTerminate(eglGetDisplay(EGLNativeDisplayType(display->wl.display)));
1787 }
1788 }
1789#endif
1790
1791 /* Important to remove after the seats which may have key repeat timers active. */
1792 if (display->key_repeat_timer_manager) {
1793 delete display->key_repeat_timer_manager;
1794 display->key_repeat_timer_manager = nullptr;
1795 }
1796
1797 if (display->wl.display) {
1798 wl_display_disconnect(display->wl.display);
1799 }
1800
1801 delete display;
1802}
1803
1804static int gwl_display_seat_index(GWL_Display *display, const GWL_Seat *seat)
1805{
1806 const auto iter = std::ranges::find(display->seats, seat);
1807 const int index = (iter != display->seats.cend()) ? int(iter - display->seats.begin()) : -1;
1808 GHOST_ASSERT(index != -1, "invalid internal state");
1809 return index;
1810}
1811
1820{
1821 if (display->seats.empty()) [[unlikely]] {
1822 return nullptr;
1823 }
1824 return display->seats[display->seats_active_index];
1825}
1826
1827static bool gwl_display_seat_active_set(GWL_Display *display, const GWL_Seat *seat)
1828{
1829 if (display->seats.empty()) [[unlikely]] {
1830 return false;
1831 }
1832 const int index = gwl_display_seat_index(display, seat);
1833 if (index == display->seats_active_index) {
1834 return false;
1835 }
1836 display->seats_active_index = index;
1837 return true;
1838}
1839
1841
1842/* -------------------------------------------------------------------- */
1845
1847 uint32_t name = 0;
1850 uint32_t version = 0;
1851};
1852
1861using GWL_RegistryHandler_AddFn = void (*)(GWL_Display *display,
1862 const GWL_RegistryAdd_Params &params);
1863
1865 uint32_t name = 0;
1868 uint32_t version = 0;
1869
1871 void *user_data = nullptr;
1872};
1873
1881 const GWL_RegistryUpdate_Params &params);
1882
1893using GWL_RegistryEntry_RemoveFn = void (*)(GWL_Display *display, void *user_data, bool on_exit);
1894
1906
1908
1909/* -------------------------------------------------------------------- */
1912
1924 void *user_data = nullptr;
1932 uint32_t version;
1938};
1939
1941 const GWL_RegistryAdd_Params &params,
1942 void *user_data)
1943{
1945
1946 reg->interface_slot = params.interface_slot;
1947 reg->name = params.name;
1948 reg->version = params.version;
1949 reg->user_data = user_data;
1950
1951 reg->next = display->registry_entry;
1952 display->registry_entry = reg;
1953}
1954
1956 uint32_t name,
1957 int *r_interface_slot)
1958{
1959 GWL_RegistryEntry *reg = display->registry_entry;
1960 GWL_RegistryEntry **reg_link_p = &display->registry_entry;
1961 bool found = false;
1962
1963 if (r_interface_slot) {
1964 *r_interface_slot = -1;
1965 }
1966
1967 while (reg) {
1968 if (reg->name == name) {
1969 GWL_RegistryEntry *reg_next = reg->next;
1971 reg->interface_slot);
1972 handler->remove_fn(display, reg->user_data, false);
1973 if (r_interface_slot) {
1974 *r_interface_slot = reg->interface_slot;
1975 }
1976 delete reg;
1977 *reg_link_p = reg_next;
1978 found = true;
1979 break;
1980 }
1981 reg_link_p = &reg->next;
1982 reg = reg->next;
1983 }
1984 return found;
1985}
1986
1988 const int interface_slot,
1989 const bool on_exit)
1990{
1991 GWL_RegistryEntry *reg = display->registry_entry;
1992 GWL_RegistryEntry **reg_link_p = &display->registry_entry;
1993 bool found = false;
1994
1995 while (reg) {
1996 if (reg->interface_slot == interface_slot) {
1997 GWL_RegistryEntry *reg_next = reg->next;
1999 interface_slot);
2000 handler->remove_fn(display, reg->user_data, on_exit);
2001 delete reg;
2002 *reg_link_p = reg_next;
2003 reg = reg_next;
2004 found = true;
2005 continue;
2006 }
2007 reg_link_p = &reg->next;
2008 reg = reg->next;
2009 }
2010 return found;
2011}
2012
2017{
2018 const bool on_exit = true;
2019
2020 /* NOTE(@ideasman42): Free by slot instead of simply looping over
2021 * `display->registry_entry` so the order of freeing is always predictable.
2022 * Otherwise global objects would be feed in the order they are registered.
2023 * While this works in my tests, it could cause difficult to reproduce bugs
2024 * where lesser used compositors or changes to existing compositors could
2025 * crash on exit based on the order of freeing objects is out of our control.
2026 *
2027 * To give a concrete example of how this could fail, it's possible removing
2028 * a tablet interface could reference the pointer interface, or the output interface.
2029 * Even though references between interfaces shouldn't be necessary in most cases
2030 * when `on_exit` is enabled. */
2031 int interface_slot = gwl_registry_handler_interface_slot_max();
2032 while (interface_slot--) {
2033 gwl_registry_entry_remove_by_interface_slot(display, interface_slot, on_exit);
2034 }
2035
2036 GHOST_ASSERT(display->registry_entry == nullptr, "Failed to remove all entries!");
2037 display->registry_entry = nullptr;
2038}
2039
2056static void gwl_registry_entry_update_all(GWL_Display *display, const int interface_slot_exclude)
2057{
2058 GHOST_ASSERT(interface_slot_exclude == -1 || (uint(interface_slot_exclude) <
2060 "Invalid exclude slot");
2061
2062 for (GWL_RegistryEntry *reg = display->registry_entry; reg; reg = reg->next) {
2063 if (reg->interface_slot == interface_slot_exclude) {
2064 continue;
2065 }
2067 reg->interface_slot);
2068 if (handler->update_fn == nullptr) {
2069 continue;
2070 }
2071
2073 params.name = reg->name;
2074 params.interface_slot = reg->interface_slot;
2075 params.version = reg->version;
2076 params.user_data = reg->user_data;
2077
2078 handler->update_fn(display, params);
2079 }
2080}
2081
2083
2084/* -------------------------------------------------------------------- */
2087
2088static uint32_t round_up_uint(const uint32_t x, const uint32_t multiple)
2089{
2090 return ((x + multiple - 1) / multiple) * multiple;
2091}
2092
2093static uint32_t rgba_straight_to_premul(uint32_t rgba_uint)
2094{
2095 uint8_t *rgba = reinterpret_cast<uint8_t *>(&rgba_uint);
2096 const uint32_t alpha = uint32_t(rgba[3]);
2097 rgba[0] = uint8_t(((alpha * rgba[0]) + (0xff / 2)) / 0xff);
2098 rgba[1] = uint8_t(((alpha * rgba[1]) + (0xff / 2)) / 0xff);
2099 rgba[2] = uint8_t(((alpha * rgba[2]) + (0xff / 2)) / 0xff);
2100 return rgba_uint;
2101}
2102
2103static uint32_t rgba_straight_to_premul_inverted(uint32_t rgba_uint)
2104{
2105 uint8_t *rgba = reinterpret_cast<uint8_t *>(&rgba_uint);
2106 const uint32_t alpha = uint32_t(rgba[3]);
2107 rgba[0] = uint8_t(((alpha * (0xff - rgba[0])) + (0xff / 2)) / 0xff);
2108 rgba[1] = uint8_t(((alpha * (0xff - rgba[1])) + (0xff / 2)) / 0xff);
2109 rgba[2] = uint8_t(((alpha * (0xff - rgba[2])) + (0xff / 2)) / 0xff);
2110 return rgba_uint;
2111}
2112
2114{
2115 return a > b ? a - b : b - a;
2116}
2117
2121static uint64_t ghost_wl_ms_from_utime_pair(uint32_t utime_hi, uint32_t utime_lo)
2122{
2123 return ((uint64_t(utime_hi) << 32) | uint64_t(utime_lo)) / 1000;
2124}
2125
2130{
2131 const char *locale = getenv("LC_ALL");
2132 if (!locale || !*locale) {
2133 locale = getenv("LC_CTYPE");
2134 if (!locale || !*locale) {
2135 locale = getenv("LANG");
2136 if (!locale || !*locale) {
2137 locale = "C";
2138 }
2139 }
2140 }
2141 return locale;
2142}
2143
2144static void ghost_wl_display_report_error_from_code(wl_display *display, const int ecode)
2145{
2146 GHOST_ASSERT(ecode, "Error not set!");
2147 if (ELEM(ecode, EPIPE, ECONNRESET)) {
2148 fprintf(stderr, "The Wayland connection broke. Did the Wayland compositor die?\n");
2149 return;
2150 }
2151
2152 if (ecode == EPROTO) {
2153 const wl_interface *interface = nullptr;
2154 const int ecode_proto = wl_display_get_protocol_error(display, &interface, nullptr);
2155 fprintf(stderr,
2156 "The Wayland connection experienced a protocol error %d in interface: %s\n",
2157 ecode_proto,
2158 interface ? interface->name : "<nil>");
2159 const char *env_debug = "WAYLAND_DEBUG";
2160 if (getenv(env_debug) == nullptr) {
2161 fprintf(stderr, "Run with the environment variable \"%s=1\" for details.\n", env_debug);
2162 }
2163 return;
2164 }
2165
2166 fprintf(stderr, "The Wayland connection experienced a fatal error: %s\n", strerror(ecode));
2167}
2168
2170{
2171 int ecode = wl_display_get_error(display);
2172 GHOST_ASSERT(ecode, "Error not set!");
2174
2175 /* NOTE(@ideasman42): The application is running,
2176 * however an error closes all windows and most importantly:
2177 * shuts down the GPU context (losing all GPU state - shaders, bind codes etc),
2178 * so recovering from this effectively involves restarting.
2179 *
2180 * Keeping the GPU state alive doesn't seem to be supported as windows EGL context must use the
2181 * same connection as the used for all other WAYLAND interactions (see #wl_display_connect).
2182 * So in practice re-connecting to the display server isn't an option.
2183 *
2184 * Exit since leaving the process open will simply flood the output and do nothing.
2185 * Although as the process is in a valid state, auto-save for example is possible, see: #100855.
2186 */
2187 ::exit(-1);
2188}
2189
2191{
2192 const int ecode = wl_display_get_error(display);
2193 if (ecode == 0) {
2194 return false;
2195 }
2197 return true;
2198}
2199
2200#ifdef __GNUC__
2201static void ghost_wayland_log_handler(const char *msg, va_list arg)
2202 __attribute__((format(printf, 1, 0)));
2203static void ghost_wayland_log_handler_background(const char *msg, va_list arg)
2204 __attribute__((format(printf, 1, 0)));
2205#endif
2206
2213static void ghost_wayland_log_handler(const char *msg, va_list arg)
2214{
2215 fprintf(stderr, "GHOST/Wayland: ");
2216 vfprintf(stderr, msg, arg); /* Includes newline. */
2217
2219 if (backtrace_fn) {
2220 backtrace_fn(stderr); /* Includes newline. */
2221 }
2222}
2223
2225static void ghost_wayland_log_handler_background(const char *msg, va_list arg)
2226{
2227 /* This is fine in background mode, we will try to fall back to headless GPU context.
2228 * Happens when render farm process runs without user login session. */
2229 const std::string_view msg_view(msg);
2230 if (msg_view.find("error: XDG_RUNTIME_DIR not set in the environment") !=
2231 std::string_view::npos ||
2232 msg_view.find("error: XDG_RUNTIME_DIR is invalid or not set in the environment") !=
2233 std::string_view::npos)
2234 {
2235 return;
2236 }
2237 ghost_wayland_log_handler(msg, arg);
2238}
2239
2240static GHOST_TKey xkb_map_gkey(const xkb_keysym_t sym)
2241{
2242
2243 GHOST_TKey gkey;
2244 if (sym >= XKB_KEY_0 && sym <= XKB_KEY_9) {
2245 gkey = GHOST_TKey(sym);
2246 }
2247 else if (sym >= XKB_KEY_KP_0 && sym <= XKB_KEY_KP_9) {
2248 gkey = GHOST_TKey(GHOST_kKeyNumpad0 + sym - XKB_KEY_KP_0);
2249 }
2250 else if (sym >= XKB_KEY_A && sym <= XKB_KEY_Z) {
2251 gkey = GHOST_TKey(sym);
2252 }
2253 else if (sym >= XKB_KEY_a && sym <= XKB_KEY_z) {
2254 gkey = GHOST_TKey(sym - XKB_KEY_a + XKB_KEY_A);
2255 }
2256 else if (sym >= XKB_KEY_F1 && sym <= XKB_KEY_F24) {
2257 gkey = GHOST_TKey(GHOST_kKeyF1 + sym - XKB_KEY_F1);
2258 }
2259 else {
2260
2261#define GXMAP(k, x, y) \
2262 case x: \
2263 k = y; \
2264 break
2265
2266 switch (sym) {
2267 GXMAP(gkey, XKB_KEY_BackSpace, GHOST_kKeyBackSpace);
2268 GXMAP(gkey, XKB_KEY_Tab, GHOST_kKeyTab);
2269 GXMAP(gkey, XKB_KEY_Linefeed, GHOST_kKeyLinefeed);
2270 GXMAP(gkey, XKB_KEY_Clear, GHOST_kKeyClear);
2271 GXMAP(gkey, XKB_KEY_Return, GHOST_kKeyEnter);
2272
2273 GXMAP(gkey, XKB_KEY_Escape, GHOST_kKeyEsc);
2274 GXMAP(gkey, XKB_KEY_space, GHOST_kKeySpace);
2275 GXMAP(gkey, XKB_KEY_apostrophe, GHOST_kKeyQuote);
2276 GXMAP(gkey, XKB_KEY_comma, GHOST_kKeyComma);
2277 GXMAP(gkey, XKB_KEY_minus, GHOST_kKeyMinus);
2278 GXMAP(gkey, XKB_KEY_plus, GHOST_kKeyPlus);
2279 GXMAP(gkey, XKB_KEY_period, GHOST_kKeyPeriod);
2280 GXMAP(gkey, XKB_KEY_slash, GHOST_kKeySlash);
2281
2282 GXMAP(gkey, XKB_KEY_semicolon, GHOST_kKeySemicolon);
2283 GXMAP(gkey, XKB_KEY_equal, GHOST_kKeyEqual);
2284
2285 GXMAP(gkey, XKB_KEY_bracketleft, GHOST_kKeyLeftBracket);
2286 GXMAP(gkey, XKB_KEY_bracketright, GHOST_kKeyRightBracket);
2287 GXMAP(gkey, XKB_KEY_backslash, GHOST_kKeyBackslash);
2288 GXMAP(gkey, XKB_KEY_grave, GHOST_kKeyAccentGrave);
2289
2290 GXMAP(gkey, XKB_KEY_Shift_L, GHOST_kKeyLeftShift);
2291 GXMAP(gkey, XKB_KEY_Shift_R, GHOST_kKeyRightShift);
2292 GXMAP(gkey, XKB_KEY_Control_L, GHOST_kKeyLeftControl);
2293 GXMAP(gkey, XKB_KEY_Control_R, GHOST_kKeyRightControl);
2294 GXMAP(gkey, XKB_KEY_Alt_L, GHOST_kKeyLeftAlt);
2295 GXMAP(gkey, XKB_KEY_Alt_R, GHOST_kKeyRightAlt);
2296 GXMAP(gkey, XKB_KEY_Super_L, GHOST_kKeyLeftOS);
2297 GXMAP(gkey, XKB_KEY_Super_R, GHOST_kKeyRightOS);
2298 GXMAP(gkey, XKB_KEY_Hyper_L, GHOST_kKeyLeftHyper);
2299 GXMAP(gkey, XKB_KEY_Hyper_R, GHOST_kKeyRightHyper);
2300 GXMAP(gkey, XKB_KEY_Menu, GHOST_kKeyApp);
2301
2302 GXMAP(gkey, XKB_KEY_Caps_Lock, GHOST_kKeyCapsLock);
2303 GXMAP(gkey, XKB_KEY_Num_Lock, GHOST_kKeyNumLock);
2304 GXMAP(gkey, XKB_KEY_Scroll_Lock, GHOST_kKeyScrollLock);
2305
2306 GXMAP(gkey, XKB_KEY_Left, GHOST_kKeyLeftArrow);
2307 GXMAP(gkey, XKB_KEY_Right, GHOST_kKeyRightArrow);
2308 GXMAP(gkey, XKB_KEY_Up, GHOST_kKeyUpArrow);
2309 GXMAP(gkey, XKB_KEY_Down, GHOST_kKeyDownArrow);
2310
2311 GXMAP(gkey, XKB_KEY_Print, GHOST_kKeyPrintScreen);
2312 GXMAP(gkey, XKB_KEY_Pause, GHOST_kKeyPause);
2313
2314 GXMAP(gkey, XKB_KEY_Insert, GHOST_kKeyInsert);
2315 GXMAP(gkey, XKB_KEY_Delete, GHOST_kKeyDelete);
2316 GXMAP(gkey, XKB_KEY_Home, GHOST_kKeyHome);
2317 GXMAP(gkey, XKB_KEY_End, GHOST_kKeyEnd);
2318 GXMAP(gkey, XKB_KEY_Page_Up, GHOST_kKeyUpPage);
2319 GXMAP(gkey, XKB_KEY_Page_Down, GHOST_kKeyDownPage);
2320
2321 GXMAP(gkey, XKB_KEY_KP_Decimal, GHOST_kKeyNumpadPeriod);
2322 GXMAP(gkey, XKB_KEY_KP_Enter, GHOST_kKeyNumpadEnter);
2323 GXMAP(gkey, XKB_KEY_KP_Add, GHOST_kKeyNumpadPlus);
2324 GXMAP(gkey, XKB_KEY_KP_Subtract, GHOST_kKeyNumpadMinus);
2325 GXMAP(gkey, XKB_KEY_KP_Multiply, GHOST_kKeyNumpadAsterisk);
2326 GXMAP(gkey, XKB_KEY_KP_Divide, GHOST_kKeyNumpadSlash);
2327
2328 GXMAP(gkey, XKB_KEY_XF86AudioPlay, GHOST_kKeyMediaPlay);
2329 GXMAP(gkey, XKB_KEY_XF86AudioStop, GHOST_kKeyMediaStop);
2330 GXMAP(gkey, XKB_KEY_XF86AudioPrev, GHOST_kKeyMediaFirst);
2331 GXMAP(gkey, XKB_KEY_XF86AudioNext, GHOST_kKeyMediaLast);
2332
2333 /* Additional keys for non US layouts. */
2334
2335 /* Uses the same physical key as #XKB_KEY_KP_Decimal for QWERTZ layout, see: #102287. */
2336 GXMAP(gkey, XKB_KEY_KP_Separator, GHOST_kKeyNumpadPeriod);
2337 GXMAP(gkey, XKB_KEY_less, GHOST_kKeyGrLess);
2338
2339 default: {
2340 /* Rely on #xkb_map_gkey_or_scan_code to report when no key can be found. */
2341 gkey = GHOST_kKeyUnknown;
2342 }
2343 }
2344#undef GXMAP
2345 }
2346
2347 return gkey;
2348}
2349
2357static GHOST_TKey xkb_map_gkey_or_scan_code(const xkb_keysym_t sym, const uint32_t key)
2358{
2359 GHOST_TKey gkey = xkb_map_gkey(sym);
2360
2361 if (gkey == GHOST_kKeyUnknown) [[unlikely]] {
2362 /* Fall back to physical location for keys that would otherwise do nothing. */
2363 switch (key) {
2364 case KEY_GRAVE: {
2365 gkey = GHOST_kKeyAccentGrave;
2366 break;
2367 }
2368 case KEY_102ND: {
2369 gkey = GHOST_kKeyGrLess;
2370 break;
2371 }
2372 default: {
2374 /* Key-code. */
2375 "unhandled key: " << std::hex << std::showbase << sym << /* Hex. */
2376 std::dec << " (" << sym << "), " << /* Decimal. */
2377 /* Scan-code. */
2378 "scan-code: " << std::hex << std::showbase << key << /* Hex. */
2379 std::dec << " (" << key << ")" << /* Decimal. */
2380 std::endl);
2381 break;
2382 }
2383 }
2384 }
2385
2386 return gkey;
2387}
2388
2389#ifdef USE_NON_LATIN_KB_WORKAROUND
2398static xkb_layout_index_t xkb_keymap_get_fallback_layout(xkb_keymap *keymap,
2399 const xkb_layout_index_t layout_active)
2400{
2401 const xkb_layout_index_t layouts_num = xkb_keymap_num_layouts(keymap);
2402 if (layouts_num <= 1) {
2403 return XKB_LAYOUT_INVALID;
2404 }
2405 const xkb_keycode_t keycode_min = xkb_keymap_min_keycode(keymap);
2406 const xkb_keycode_t keycode_max = xkb_keymap_max_keycode(keymap);
2407 xkb_layout_index_t layout_best = 0;
2408 int score_best = -1;
2409 /* Value should always be set, if `layout_active` is invalid,
2410 * return #XKB_LAYOUT_INVALID because the result can't be reasoned about usefully. */
2411 int score_active = std::numeric_limits<int>::max();
2412 for (xkb_layout_index_t layout_test = 0; layout_test < layouts_num; layout_test++) {
2413 int score_test = 0;
2414 for (xkb_keycode_t key = keycode_min; key <= keycode_max; key++) {
2415 const xkb_keysym_t *syms;
2416 if (xkb_keymap_key_get_syms_by_level(keymap, key, layout_test, 0, &syms) > 0 &&
2417 xkb_map_gkey(syms[0]) != GHOST_kKeyUnknown)
2418 {
2419 score_test++;
2420 }
2421 }
2422 /* Strict `>` keeps the lower layout index on ties. */
2423 if (score_test > score_best) {
2424 score_best = score_test;
2425 layout_best = layout_test;
2426 }
2427 if (layout_test == layout_active) {
2428 score_active = score_test;
2429 }
2430 }
2431 GHOST_ASSERT(score_active != std::numeric_limits<int>::max(),
2432 "Invalid `layout_active` passed in.");
2433
2434 /* The fallback layout must be an improvement over the active layout. */
2435 if (score_best <= score_active) {
2436 return XKB_LAYOUT_INVALID;
2437 }
2438 return layout_best;
2439}
2440#endif
2441
2447static xkb_keysym_t xkb_keymap_get_one_sym_with_fallback(const xkb_keysym_t sym,
2448 xkb_keymap *keymap,
2449 const xkb_keycode_t key,
2450 const xkb_layout_index_t layout_fallback)
2451{
2452#ifndef USE_NON_LATIN_KB_WORKAROUND
2453 GHOST_ASSERT(layout_fallback == XKB_LAYOUT_INVALID,
2454 "Fallback key-map is expected to be disabled!");
2455#endif
2456
2457 if (layout_fallback == XKB_LAYOUT_INVALID || xkb_map_gkey(sym) != GHOST_kKeyUnknown) {
2458 return sym;
2459 }
2460 const xkb_keysym_t *syms;
2461 if (xkb_keymap_key_get_syms_by_level(keymap, key, layout_fallback, 0, &syms) > 0 &&
2462 xkb_map_gkey(syms[0]) != GHOST_kKeyUnknown)
2463 {
2464 return syms[0];
2465 }
2466 return sym;
2467}
2468
2473 xkb_state *state, const xkb_keycode_t key, const xkb_layout_index_t layout_fallback)
2474{
2476 xkb_state_key_get_one_sym(state, key), xkb_state_get_keymap(state), key, layout_fallback);
2477}
2478
2479static int pointer_axis_as_index(const uint32_t axis)
2480{
2481 switch (axis) {
2482 case WL_POINTER_AXIS_HORIZONTAL_SCROLL: {
2483 return 0;
2484 }
2485 case WL_POINTER_AXIS_VERTICAL_SCROLL: {
2486 return 1;
2487 }
2488 default: {
2489 return -1;
2490 }
2491 }
2492}
2493
2494static GHOST_TTabletMode tablet_tool_map_type(enum zwp_tablet_tool_v2_type wp_tablet_tool_type)
2495{
2496 switch (wp_tablet_tool_type) {
2497 case ZWP_TABLET_TOOL_V2_TYPE_ERASER: {
2499 }
2500 case ZWP_TABLET_TOOL_V2_TYPE_PEN:
2501 case ZWP_TABLET_TOOL_V2_TYPE_BRUSH:
2502 case ZWP_TABLET_TOOL_V2_TYPE_PENCIL:
2503 case ZWP_TABLET_TOOL_V2_TYPE_AIRBRUSH:
2504 case ZWP_TABLET_TOOL_V2_TYPE_FINGER:
2505 case ZWP_TABLET_TOOL_V2_TYPE_MOUSE:
2506 case ZWP_TABLET_TOOL_V2_TYPE_LENS: {
2508 }
2509 }
2510
2511 GHOST_PRINT("unknown tablet tool: " << wp_tablet_tool_type << std::endl);
2513}
2514
2515static const int default_cursor_size = 24;
2516
2517#ifdef WITH_GHOST_DBUS
2519static const int dbus_initial_timeout_ms = 100;
2521static const size_t dbus_events_default_size = 8;
2522#endif
2523
2530static std::optional<int> cursor_size_from_env()
2531{
2532 const char *env = getenv("XCURSOR_SIZE");
2533 if (!env || (*env == '\0')) {
2534 return std::nullopt;
2535 }
2536 char *env_end = nullptr;
2537 const long value = strtol(env, &env_end, 10);
2538 /* While clamping is not needed on the WAYLAND side,
2539 * GHOST's internal logic may get confused by negative values, so ensure it's at least 1. */
2540 if ((*env_end != '\0') || (value <= 0)) {
2541 return std::nullopt;
2542 }
2543 return int(value);
2544}
2545
2546static constexpr const char *ghost_wl_mime_text_plain = "text/plain";
2547static constexpr const char *ghost_wl_mime_text_utf8 = "text/plain;charset=utf-8";
2548static constexpr const char *ghost_wl_mime_text_uri_list = "text/uri-list";
2549
2555/* Aligned to `ghost_wl_mime_preference_order`. */
2561
2562static const char *ghost_wl_mime_send[] = {
2563 "UTF8_STRING",
2564 "COMPOUND_TEXT",
2565 "TEXT",
2566 "STRING",
2567 "text/plain;charset=utf-8",
2568 "text/plain",
2569};
2570
2575static std::vector<std::string_view> gwl_clipboard_uri_ranges(const char *data_buf,
2576 size_t data_buf_len)
2577{
2578 std::vector<std::string_view> uris;
2579 const char file_proto[] = "file://";
2580 /* NOTE: some applications CRLF (`\r\n`) GTK3 for example & others don't `pcmanfm-qt`.
2581 * So support both, once `\n` is found, strip the preceding `\r` if found. */
2582 const char lf = '\n';
2583
2584 const std::string_view data = std::string_view(data_buf, data_buf_len);
2585
2586 size_t pos = 0;
2587 while (pos != std::string::npos) {
2588 pos = data.find(file_proto, pos);
2589 if (pos == std::string::npos) {
2590 break;
2591 }
2592 const size_t start = pos + sizeof(file_proto) - 1;
2593 pos = data.find(lf, pos);
2594
2595 size_t end = pos;
2596 if (end == std::string::npos) [[unlikely]] {
2597 /* Note that most well behaved file managers will add a trailing newline,
2598 * Gnome's web browser (44.3) doesn't, so support reading up until the last byte. */
2599 end = data.size();
2600 }
2601 /* Account for 'CRLF' case. */
2602 if ((end > 0) && (data[end - 1] == '\r')) {
2603 end -= 1;
2604 }
2605
2606 std::string_view data_substr = data.substr(start, end - start);
2607 uris.push_back(data_substr);
2608 }
2609 return uris;
2610}
2611
2612#ifdef USE_EVENT_BACKGROUND_THREAD
2613static void pthread_set_min_priority(pthread_t handle)
2614{
2615 int policy;
2616 sched_param sch_params;
2617 if (pthread_getschedparam(handle, &policy, &sch_params) == 0) {
2618 sch_params.sched_priority = sched_get_priority_min(policy);
2619 pthread_setschedparam(handle, policy, &sch_params);
2620 }
2621}
2622
2623#endif /* USE_EVENT_BACKGROUND_THREAD */
2624
2625static int memfd_create_sealed(const char *name)
2626{
2627#ifdef HAVE_MEMFD_CREATE
2628 const int fd = memfd_create(name, MFD_CLOEXEC | MFD_ALLOW_SEALING);
2629 if (fd >= 0) {
2630 fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_SEAL);
2631 }
2632 return fd;
2633#else /* HAVE_MEMFD_CREATE */
2634 char *path = getenv("XDG_RUNTIME_DIR");
2635 if (!path) {
2636 errno = ENOENT;
2637 return -1;
2638 }
2639 char *tmpname;
2640 asprintf(&tmpname, "%s/%s-XXXXXX", path, name);
2641 const int fd = mkostemp(tmpname, O_CLOEXEC);
2642 if (fd >= 0) {
2643 unlink(tmpname);
2644 }
2645 free(tmpname);
2646 return fd;
2647#endif /* !HAVE_MEMFD_CREATE */
2648}
2649
2650enum {
2654};
2655
2660 const int fd, const int fd_stop, const int flags, const int timeout_ms, bool *r_stop)
2661{
2662 int result;
2663
2664 GHOST_ASSERT(flags & (GWL_IOR_READ | GWL_IOR_WRITE), "X");
2665
2666 /* NOTE: We don't bother to account for elapsed time if we get #EINTR. */
2667 do {
2668 pollfd info[2];
2669
2670 info[0].fd = fd;
2671 info[0].events = 0;
2672 if (flags & GWL_IOR_READ) {
2673 info[0].events |= POLLIN | POLLPRI;
2674 }
2675 if (flags & GWL_IOR_WRITE) {
2676 info[0].events |= POLLOUT;
2677 }
2678 /* A negative descriptor is ignored with `revents` zeroed, so -1 needs no special case.
2679 * #POLLHUP is reported without asking for it, which is what closing the write end gives. */
2680 info[1] = {fd_stop, POLLIN, 0};
2681
2682 result = poll(info, 2, timeout_ms);
2683 if ((result > 0) && (info[1].revents != 0)) {
2684 *r_stop = true;
2685 }
2686 } while (result < 0 && errno == EINTR && !(flags & GWL_IOR_NO_RETRY));
2687
2688 return result;
2689}
2690
2691static int file_descriptor_is_io_ready(const int fd, const int flags, const int timeout_ms)
2692{
2693 return file_descriptor_is_io_ready_ex(fd, -1, flags, timeout_ms, nullptr);
2694}
2695
2697{
2698 /* Based on SDL's `Wayland_PumpEvents`. */
2699 int err;
2700
2701 /* NOTE: Without this, interactions with window borders aren't handled. */
2703
2705 /* Use #GWL_IOR_NO_RETRY to ensure #SIGINT will break us out of our wait. */
2708 {
2710 }
2711 else {
2713 err = 0;
2714 }
2715 }
2716 else {
2718 }
2719 return err;
2720}
2721
2722#ifdef USE_KDE_VULKAN_UNGRAB_CURSOR_HACK
2723
2724static void surface_frame_apply_handle_done(void *data,
2725 wl_callback * /*wl_callback*/,
2726 uint32_t /*time*/)
2727{
2728 *static_cast<bool *>(data) = true;
2729}
2730
2731static const wl_callback_listener surface_frame_apply_listener = {
2732 /*done*/ surface_frame_apply_handle_done,
2733};
2734
2744static bool ghost_wl_surface_commit_and_wait_for_apply(GHOST_SystemWayland *system,
2745 wl_surface *surface,
2746 const int timeout_ms)
2747{
2749
2750 /* A dedicated event queue is used so only the frame callback is dispatched while
2751 * waiting, leaving all other events queued for the main event loop.
2752 * Based on SDL-3.4's `Wayland_GLES_SwapWindow`. */
2753 wl_event_queue *frame_queue = wl_display_create_queue(wl_display);
2754 wl_surface *surface_wrapper = static_cast<wl_surface *>(wl_proxy_create_wrapper(surface));
2755 wl_proxy_set_queue(reinterpret_cast<wl_proxy *>(surface_wrapper), frame_queue);
2756
2757 bool apply_done = false;
2758
2759 /* The callback inherits the wrapper's queue. */
2760 wl_callback *frame_callback = wl_surface_frame(surface_wrapper);
2761 wl_callback_add_listener(frame_callback, &surface_frame_apply_listener, &apply_done);
2762 wl_surface_commit(surface);
2763
2764 const uint64_t time_end = system->getMilliSeconds() + uint64_t(timeout_ms);
2765 const int fd = wl_display_get_fd(wl_display);
2766 while (!apply_done) {
2767 /* Ignore errors: on `EAGAIN` (a full send buffer) the flush is retried next iteration,
2768 * hard errors will cause the read/dispatch to fail (next). */
2770
2771 /* A non-zero return means there are pending events, dispatch them in case
2772 * the frame callback is among them. Otherwise the display is prepared for
2773 * reading and *must* be finished with a read or cancel. */
2774 if (wl_display_prepare_read_queue(wl_display, frame_queue) != 0) {
2775 if (wl_display_dispatch_queue_pending(wl_display, frame_queue) == -1) [[unlikely]] {
2776 break;
2777 }
2778 continue;
2779 }
2780
2781 const uint64_t time_now = system->getMilliSeconds();
2782 if (time_now >= time_end) {
2784 break;
2785 }
2786
2787 /* Use #GWL_IOR_NO_RETRY to ensure #SIGINT will break us out of our wait. */
2789 fd, GWL_IOR_READ | GWL_IOR_NO_RETRY, int(time_end - time_now)) <= 0)
2790 {
2791 /* Time-out (or error). */
2793 break;
2794 }
2795
2797 if (wl_display_dispatch_queue_pending(wl_display, frame_queue) == -1) [[unlikely]] {
2798 break;
2799 }
2800 }
2801
2802 wl_callback_destroy(frame_callback);
2803 wl_proxy_wrapper_destroy(surface_wrapper);
2804 wl_event_queue_destroy(frame_queue);
2805 return apply_done;
2806}
2807
2808#endif /* USE_KDE_VULKAN_UNGRAB_CURSOR_HACK */
2809
2810#ifdef USE_EVENT_BACKGROUND_THREAD
2811
2819 const int fd,
2820 const int fd_stop,
2821 std::mutex *server_mutex)
2822{
2823 GHOST_ASSERT(fd_stop != -1, "Expected to be set");
2824
2825 /* Based on SDL's `Wayland_PumpEvents`. */
2826 server_mutex->lock();
2827 int err = 0;
2828 bool stop = false;
2830 bool wait_on_fd = false;
2831 /* Use #GWL_IOR_NO_RETRY to ensure #SIGINT will break us out of our wait. */
2834 }
2835 else {
2837 /* Without this, the thread will loop continuously, 100% CPU. */
2838 wait_on_fd = true;
2839 }
2840
2841 server_mutex->unlock();
2842
2843 if (wait_on_fd) {
2844 /* Important this runs after unlocking,
2845 * the read was canceled above so nothing is left prepared while waiting. */
2847 fd, fd_stop, GWL_IOR_READ | GWL_IOR_NO_RETRY, INT32_MAX, &stop);
2848 }
2849 }
2850 else {
2851 server_mutex->unlock();
2852
2853 /* Wait for input (unlocked, so as not to block other threads). */
2855 fd, fd_stop, GWL_IOR_READ | GWL_IOR_NO_RETRY, INT32_MAX, &stop);
2856 /* Re-check `state` with a lock held, needed to avoid holding the lock. */
2857 if (!stop && state > 0) {
2858 server_mutex->lock();
2860 if (state > 0) {
2862 }
2863 server_mutex->unlock();
2864 }
2865 }
2866
2867 return stop ? -1 : err;
2868}
2869#endif /* USE_EVENT_BACKGROUND_THREAD */
2870
2871static size_t ghost_wl_shm_format_as_size(enum wl_shm_format format)
2872{
2873 switch (format) {
2874 case WL_SHM_FORMAT_ARGB8888: {
2875 return 4;
2876 }
2877 default: {
2878 /* Support other formats as needed. */
2879 GHOST_ASSERT(0, "Unexpected format passed in!");
2880 return 4;
2881 }
2882 }
2883}
2884
2892static wl_buffer *ghost_wl_buffer_create_for_image(wl_shm *shm,
2893 const int32_t size_xy[2],
2894 enum wl_shm_format format,
2895 void **r_buffer_data,
2896 size_t *r_buffer_data_size)
2897{
2898 const int fd = memfd_create_sealed("ghost-wl-buffer");
2899 wl_buffer *buffer = nullptr;
2900 if (fd >= 0) {
2901 const int32_t buffer_stride = size_xy[0] * ghost_wl_shm_format_as_size(format);
2902 const int32_t buffer_size = buffer_stride * size_xy[1];
2903 if (posix_fallocate(fd, 0, buffer_size) == 0) {
2904 void *buffer_data = mmap(nullptr, buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2905 if (buffer_data != MAP_FAILED) {
2906 if (wl_shm_pool *pool = wl_shm_create_pool(shm, fd, buffer_size)) {
2907 buffer = wl_shm_pool_create_buffer(pool, 0, UNPACK2(size_xy), buffer_stride, format);
2908 wl_shm_pool_destroy(pool);
2909 if (buffer) {
2910 *r_buffer_data = buffer_data;
2911 *r_buffer_data_size = size_t(buffer_size);
2912 }
2913 }
2914 if (buffer == nullptr) [[unlikely]] {
2915 munmap(buffer_data, buffer_size);
2916 }
2917 }
2918 }
2919 close(fd);
2920 }
2921 return buffer;
2922}
2923
2925{
2926 const int32_t size_xy[2] = {1, 1};
2927 void *buffer_data = nullptr;
2928 size_t buffer_data_size = 0;
2929 wl_buffer *buffer = ghost_wl_buffer_create_for_image(
2930 shm, size_xy, WL_SHM_FORMAT_ARGB8888, &buffer_data, &buffer_data_size);
2931 if (buffer == nullptr) [[unlikely]] {
2932 return nullptr;
2933 }
2934 memset(buffer_data, 0, buffer_data_size);
2935 munmap(buffer_data, buffer_data_size);
2936 return buffer;
2937}
2938
2943static ssize_t read_exhaustive(const int fd, void *data, size_t nbytes)
2944{
2945 ssize_t nbytes_read = read(fd, data, nbytes);
2946 if (nbytes_read > 0) {
2947 while (nbytes_read < nbytes) {
2948 const ssize_t nbytes_extra = read(
2949 fd, static_cast<char *>(data) + nbytes_read, nbytes - nbytes_read);
2950 if (nbytes_extra > 0) {
2951 nbytes_read += nbytes_extra;
2952 }
2953 else {
2954 if (nbytes_extra < 0) [[unlikely]] {
2955 nbytes_read = nbytes_extra; /* Error. */
2956 }
2957 break;
2958 }
2959 }
2960 }
2961 return nbytes_read;
2962}
2963
2971static char *read_file_as_buffer(const int fd, const bool nil_terminate, size_t *r_len)
2972{
2973 struct ByteChunk {
2974 ByteChunk *next;
2975 char data[4096 - sizeof(ByteChunk *)];
2976 };
2977 bool ok = true;
2978 size_t len = 0;
2979
2980 ByteChunk *chunk_first = static_cast<ByteChunk *>(malloc(sizeof(ByteChunk)));
2981 {
2982 ByteChunk **chunk_link_p = &chunk_first;
2983 ByteChunk *chunk = chunk_first;
2984 while (true) {
2985 if (chunk == nullptr) [[unlikely]] {
2986 errno = ENOMEM;
2987 ok = false;
2988 break;
2989 }
2990 chunk->next = nullptr;
2991 /* Using `read` causes issues with GNOME, see: #106040. */
2992 const ssize_t len_chunk = read_exhaustive(fd, chunk->data, sizeof(ByteChunk::data));
2993 if (len_chunk <= 0) {
2994 if (len_chunk < 0) [[unlikely]] {
2995 ok = false;
2996 }
2997 if (chunk == chunk_first) {
2998 chunk_first = nullptr;
2999 }
3000 free(chunk);
3001 break;
3002 }
3003 *chunk_link_p = chunk;
3004 chunk_link_p = &chunk->next;
3005 len += len_chunk;
3006
3007 if (len_chunk != sizeof(ByteChunk::data)) {
3008 break;
3009 }
3010 chunk = static_cast<ByteChunk *>(malloc(sizeof(ByteChunk)));
3011 }
3012 }
3013
3014 char *buf = nullptr;
3015 if (ok) {
3016 buf = static_cast<char *>(malloc(len + (nil_terminate ? 1 : 0)));
3017 if (buf == nullptr) [[unlikely]] {
3018 errno = ENOMEM;
3019 ok = false;
3020 }
3021 }
3022
3023 if (ok) {
3024 *r_len = len;
3025 if (nil_terminate) {
3026 buf[len] = '\0';
3027 }
3028 }
3029 else {
3030 *r_len = 0;
3031 }
3032
3033 char *buf_stride = buf;
3034 while (chunk_first) {
3035 if (ok) {
3036 const size_t len_chunk = std::min(len, sizeof(chunk_first->data));
3037 memcpy(buf_stride, chunk_first->data, len_chunk);
3038 buf_stride += len_chunk;
3039 len -= len_chunk;
3040 }
3041 ByteChunk *chunk = chunk_first->next;
3042 free(chunk_first);
3043 chunk_first = chunk;
3044 }
3045
3046 return buf;
3047}
3048
3049static bool string_elem_split_by_delim(std::string_view haystack,
3050 const char delim,
3051 std::string_view needle)
3052{
3053 /* Local copy of #BLI_string_elem_split_by_delim (would be a bad level call). */
3054
3055 /* May be zero, returns true when an empty span exists. */
3056 while (!haystack.empty()) {
3057 const size_t pos = haystack.find(delim);
3058 if (haystack.substr(0, pos) == needle) {
3059 return true;
3060 }
3061 if (pos == std::string_view::npos) {
3062 break;
3063 }
3064 haystack.remove_prefix(pos + 1);
3065 }
3066 return false;
3067}
3068
3070
3071/* -------------------------------------------------------------------- */
3074
3075static void cursor_buffer_set_surface_impl(const wl_cursor_image *wl_image,
3076 wl_buffer *buffer,
3078 const int scale)
3079{
3080 const int32_t image_size_x = int32_t(wl_image->width);
3081 const int32_t image_size_y = int32_t(wl_image->height);
3082 GHOST_ASSERT((image_size_x % scale) == 0 && (image_size_y % scale) == 0,
3083 "The size must be a multiple of the scale!");
3084 (void)image_size_x;
3085 (void)image_size_y;
3086
3087 wl_surface_set_buffer_scale(wl_surface, scale);
3088 wl_surface_attach(wl_surface, buffer, 0, 0);
3089 if (wl_surface_get_version(wl_surface) >= WL_SURFACE_DAMAGE_BUFFER_SINCE_VERSION) {
3090 wl_surface_damage_buffer(wl_surface,
3091 0,
3092 0,
3093 std::numeric_limits<int32_t>::max(),
3094 std::numeric_limits<int32_t>::max());
3095 }
3096 else {
3097 /* Effectively deprecated according to documentation. */
3098 wl_surface_damage(wl_surface,
3099 0,
3100 0,
3101 std::numeric_limits<int32_t>::max(),
3102 std::numeric_limits<int32_t>::max());
3103 }
3104 wl_surface_commit(wl_surface);
3105}
3106
3107static std::optional<wp_cursor_shape_device_v1_shape> gwl_seat_cursor_find_wl_shape_from_ghost(
3108 const GHOST_TStandardCursor shape)
3109{
3110 /* Cases that return `std::nullopt` mean the cursor is not available. */
3111
3112 /* Unused WAYLAND cursors:
3113 *
3114 * #WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_PROGRESS.
3115 * #WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CELL.
3116 * #WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NO_DROP.
3117 * #WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE.
3118 * #WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE.
3119 * #WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DND_ASK.
3120 * #WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_RESIZE.
3121 */
3122
3123 switch (shape) {
3125 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT;
3127 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_E_RESIZE;
3129 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_W_RESIZE;
3131 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CONTEXT_MENU;
3133 return std::nullopt;
3135 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_HELP;
3137 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_WAIT;
3139 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT;
3141 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR;
3143 return std::nullopt;
3145 return std::nullopt;
3147 return std::nullopt;
3149 return std::nullopt;
3151 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_N_RESIZE;
3153 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_S_RESIZE;
3155 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_COL_RESIZE;
3157 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ROW_RESIZE;
3159 return std::nullopt;
3161 return std::nullopt;
3163 return std::nullopt;
3165 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ZOOM_IN;
3167 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ZOOM_OUT;
3169 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_MOVE;
3171 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_GRAB;
3173 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_GRABBING;
3175 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER;
3177 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_SCROLL;
3179 return std::nullopt;
3181 return std::nullopt;
3183 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED;
3185 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE;
3187 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE;
3189 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_N_RESIZE;
3191 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_S_RESIZE;
3193 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_W_RESIZE;
3195 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_E_RESIZE;
3197 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NW_RESIZE;
3199 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NE_RESIZE;
3201 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SE_RESIZE;
3203 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SW_RESIZE;
3205 return WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_COPY;
3207 return std::nullopt;
3209 return std::nullopt;
3211 return std::nullopt;
3213 return std::nullopt;
3215 return std::nullopt;
3217 return std::nullopt;
3218 }
3219 GHOST_ASSERT(0, "Unhandled GHOST cursor shape!");
3220 /* Shape not found. */
3221 return std::nullopt;
3222}
3223
3231{
3232 int scale = 1;
3233 if (seat->wl.pointer) {
3234 scale = std::max(scale, seat->pointer.buffer_scale);
3235 }
3236 if (seat->wp.tablet_seat) {
3237 scale = std::max(scale, seat->tablet.buffer_scale);
3238 }
3239 return scale;
3240}
3241
3249{
3250 const GWL_Cursor *cursor = &seat->cursor;
3251
3252 if (seat->wl.pointer) {
3253 if (seat->cursor.shape.device) {
3254 wp_cursor_shape_device_v1_set_shape(
3255 seat->cursor.shape.device, seat->pointer.serial, seat->cursor.shape.enum_id);
3256 }
3257 else {
3258 /* TODO: use `seat->pointer.buffer_scale`, give each device it's own buffer. */
3259 const int scale = gwl_seat_cursor_buffer_scale_calc(seat);
3260
3261 const int32_t hotspot_x = int32_t(cursor->wl.image.hotspot_x) / scale;
3262 const int32_t hotspot_y = int32_t(cursor->wl.image.hotspot_y) / scale;
3263 wl_pointer_set_cursor(
3264 seat->wl.pointer, seat->pointer.serial, cursor->wl.surface_cursor, hotspot_x, hotspot_y);
3265 }
3266 }
3267
3268 if (!seat->wp.tablet_tools.empty()) {
3269 /* TODO: use `seat->tablet.buffer_scale`, give each device it's own buffer. */
3270 const int scale = gwl_seat_cursor_buffer_scale_calc(seat);
3271 const int32_t hotspot_x = int32_t(cursor->wl.image.hotspot_x) / scale;
3272 const int32_t hotspot_y = int32_t(cursor->wl.image.hotspot_y) / scale;
3273 for (zwp_tablet_tool_v2 *zwp_tablet_tool_v2 : seat->wp.tablet_tools) {
3274 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(
3275 zwp_tablet_tool_v2_get_user_data(zwp_tablet_tool_v2));
3276 if (tablet_tool->shape.device) {
3277 wp_cursor_shape_device_v1_set_shape(
3278 tablet_tool->shape.device, tablet_tool->serial, tablet_tool->shape.enum_id);
3279 }
3280 else {
3281 zwp_tablet_tool_v2_set_cursor(zwp_tablet_tool_v2,
3282 tablet_tool->serial,
3283 tablet_tool->wl.surface_cursor,
3284 hotspot_x,
3285 hotspot_y);
3286#ifdef USE_KDE_TABLET_HIDDEN_CURSOR_HACK
3288 wl_surface_commit(tablet_tool->wl.surface_cursor);
3289 }
3290#endif
3291 }
3292 }
3293 }
3294}
3295
3303{
3304 wl_pointer_set_cursor(seat->wl.pointer, seat->pointer.serial, nullptr, 0, 0);
3305 for (zwp_tablet_tool_v2 *zwp_tablet_tool_v2 : seat->wp.tablet_tools) {
3306 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(
3307 zwp_tablet_tool_v2_get_user_data(zwp_tablet_tool_v2));
3308 zwp_tablet_tool_v2_set_cursor(zwp_tablet_tool_v2, tablet_tool->serial, nullptr, 0, 0);
3309 }
3310}
3311
3312static void gwl_seat_cursor_buffer_set(const GWL_Seat *seat,
3313 const wl_cursor_image *wl_image,
3314 wl_buffer *buffer)
3315{
3316 const GWL_Cursor *cursor = &seat->cursor;
3317 const bool visible = (cursor->visible && cursor->is_hardware);
3318
3319 const int scale = gwl_seat_cursor_buffer_scale_calc(seat);
3320
3321 /* This is a requirement of WAYLAND, when this isn't the case,
3322 * it causes Blender's window to close intermittently. */
3323 if (seat->wl.pointer) {
3324 const int32_t hotspot_x = int32_t(wl_image->hotspot_x) / scale;
3325 const int32_t hotspot_y = int32_t(wl_image->hotspot_y) / scale;
3326 cursor_buffer_set_surface_impl(wl_image, buffer, cursor->wl.surface_cursor, scale);
3327 wl_pointer_set_cursor(seat->wl.pointer,
3328 seat->pointer.serial,
3329 visible ? cursor->wl.surface_cursor : nullptr,
3330 hotspot_x,
3331 hotspot_y);
3332 }
3333
3334 /* Set the cursor for all tablet tools as well. */
3335 if (!seat->wp.tablet_tools.empty()) {
3336 const int32_t hotspot_x = int32_t(wl_image->hotspot_x) / scale;
3337 const int32_t hotspot_y = int32_t(wl_image->hotspot_y) / scale;
3338 for (zwp_tablet_tool_v2 *zwp_tablet_tool_v2 : seat->wp.tablet_tools) {
3339 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(
3340 zwp_tablet_tool_v2_get_user_data(zwp_tablet_tool_v2));
3341 cursor_buffer_set_surface_impl(wl_image, buffer, tablet_tool->wl.surface_cursor, scale);
3342 zwp_tablet_tool_v2_set_cursor(zwp_tablet_tool_v2,
3343 tablet_tool->serial,
3344 visible ? tablet_tool->wl.surface_cursor : nullptr,
3345 hotspot_x,
3346 hotspot_y);
3347 }
3348 }
3349}
3350
3352{
3353 const GWL_Cursor *cursor = &seat->cursor;
3354 gwl_seat_cursor_buffer_set(seat, &cursor->wl.image, cursor->wl.buffer);
3355}
3356
3362
3364 const bool visible,
3365 const bool is_hardware,
3366 const enum eCursorSetMode set_mode)
3367{
3368 GWL_Cursor *cursor = &seat->cursor;
3369 const bool was_visible = cursor->is_hardware && cursor->visible;
3370 const bool use_visible = is_hardware && visible;
3371
3372 if (set_mode == CURSOR_VISIBLE_ALWAYS_SET) {
3373 /* Pass. */
3374 }
3375 else if (set_mode == CURSOR_VISIBLE_ONLY_SHOW) {
3376 if (!use_visible) {
3377 return;
3378 }
3379 }
3380 else if (set_mode == CURSOR_VISIBLE_ONLY_HIDE) {
3381 if (use_visible) {
3382 return;
3383 }
3384 }
3385
3386 if (use_visible) {
3387 if (!was_visible) {
3389 }
3390 }
3391 else {
3392 if (was_visible) {
3394 }
3395 }
3396 cursor->visible = visible;
3397 cursor->is_hardware = is_hardware;
3398}
3399
3401
3402/* -------------------------------------------------------------------- */
3409
3410static CLG_LogRef LOG_WL_KEYBOARD_DEPRESSED_STATE = {"ghost.wl.keyboard.depressed"};
3411#define LOG (&LOG_WL_KEYBOARD_DEPRESSED_STATE)
3412
3414{
3415 for (int i = 0; i < GHOST_KEY_MODIFIER_NUM; i++) {
3416 seat->key_depressed.mods[i] = 0;
3417 }
3418}
3419
3421 const GHOST_TKey gkey,
3422 const GHOST_TEventType etype)
3423{
3424 if (GHOST_KEY_MODIFIER_CHECK(gkey)) {
3425 const int index = GHOST_KEY_MODIFIER_TO_INDEX(gkey);
3426 int16_t &value = seat->key_depressed.mods[index];
3427 if (etype == GHOST_kEventKeyUp) {
3428 value -= 1;
3429 if (value < 0) [[unlikely]] {
3430 CLOG_WARN(LOG, "modifier (%d) has negative keys held (%d)!", index, value);
3431 value = 0;
3432 }
3433 }
3434 else {
3435 value += 1;
3436 }
3437 }
3438}
3439
3441 GWL_Seat *seat,
3442 GHOST_IWindow *win,
3443 const uint64_t event_ms,
3444 const GWL_KeyboardDepressedState &key_depressed_prev)
3445{
3446 /* Separate key up and down into separate passes so key down events always come after key up.
3447 * Do this so users of GHOST can use the last pressed or released modifier to check
3448 * if the modifier is held instead of counting modifiers pressed as is done here,
3449 * this isn't perfect but works well enough in practice. */
3450 for (int i = 0; i < GHOST_KEY_MODIFIER_NUM; i++) {
3451 for (int d = seat->key_depressed.mods[i] - key_depressed_prev.mods[i]; d < 0; d++) {
3454 std::make_unique<GHOST_EventKey>(event_ms, GHOST_kEventKeyUp, win, gkey, false));
3455
3456 CLOG_DEBUG(LOG, "modifier (%d) up", i);
3457 }
3458 }
3459
3460 for (int i = 0; i < GHOST_KEY_MODIFIER_NUM; i++) {
3461 for (int d = seat->key_depressed.mods[i] - key_depressed_prev.mods[i]; d > 0; d--) {
3464 std::make_unique<GHOST_EventKey>(event_ms, GHOST_kEventKeyDown, win, gkey, false));
3465 CLOG_DEBUG(LOG, "modifier (%d) down", i);
3466 }
3467 }
3468}
3469
3470#undef LOG
3471
3473
3474/* -------------------------------------------------------------------- */
3477
3478#ifdef WITH_GHOST_CSD
3479
3480static int32_t gwl_window_dpi_scale_value(GHOST_WindowWayland *win, const int32_t value)
3481{
3482 /* NOTE: `getDPIHint` should be `const` so `win` can be `const` too. */
3483 return (value * win->getDPIHint()) / GHOST_CSD_DPI_FRACTIONAL_BASE;
3484}
3485
3490static bool gwl_window_csd_active_elem_type_apply(GWL_Seat *seat,
3492 const GHOST_TCSD_Type type)
3493{
3494 if (type == win->csd_elem_active_type_get()) {
3495 return false;
3496 }
3497 win->csd_elem_active_type_set(type);
3498
3499 /* Set the cursor unless grabbed. */
3500 if (win->getCursorGrabMode() == GHOST_kGrabDisable) {
3502 switch (type) {
3503 case GHOST_kCSDTypeBody: {
3504 win->cursor_shape_refresh();
3505 break;
3506 }
3509 break;
3510 }
3513 break;
3514 }
3517 break;
3518 }
3521 break;
3522 }
3525 break;
3526 }
3529 break;
3530 }
3533 break;
3534 }
3537 break;
3538 }
3541 break;
3542 }
3545 break;
3546 }
3549 break;
3550 }
3553 break;
3554 }
3557 break;
3558 }
3559 }
3560
3561 if (cursor != GHOST_kStandardCursorCustom) {
3562 seat->system->cursor_shape_set(cursor);
3563 return true;
3564 }
3565 }
3566 return false;
3567}
3568
3574static bool gwl_window_csd_active_elem_motion(GWL_Seat *seat,
3576 const int event_xy[2])
3577{
3578 /* Caller must lock `server_mutex`. */
3579
3580 GHOST_TCSD_Type active_type_next = GHOST_kCSDTypeBody;
3581 int elems_num = 0;
3582 const GHOST_CSD_Elem *csd_elems = win->csd_layout(&elems_num);
3583
3584 int i;
3585 for (i = 0; i < elems_num; i++) {
3586 const GHOST_CSD_Elem &elem = csd_elems[i];
3587
3588 if ((event_xy[0] >= elem.bounds[0][0] && event_xy[0] <= elem.bounds[0][1]) &&
3589 (event_xy[1] >= elem.bounds[1][0] && event_xy[1] <= elem.bounds[1][1]))
3590 {
3591 active_type_next = elem.type;
3592 break;
3593 }
3594 }
3595 /* Ignore this function if the event doesn't overlap anything. */
3596 if (i == elems_num) [[unlikely]] {
3597 return false;
3598 }
3599
3600 /* Update motion. */
3601 GHOST_CSD_EventState &event_state = win->csd_eventstate_get();
3602 event_state.event_xy[0] = event_xy[0];
3603 event_state.event_xy[1] = event_xy[1];
3604
3605 {
3606 /* Detect press-drag. */
3607 GHOST_CSD_EventState_Button &event_button = event_state.buttons[GHOST_kButtonMaskLeft];
3608 if (event_button.action_history_num > 0) {
3609 GHOST_CSD_EventState_ButtonAction &press = event_button.action_history[0];
3610 if (press.is_press && (press.type == GHOST_kCSDTypeTitlebar)) {
3611 const GHOST_CSD_Params &params = seat->system->getWindowCSD();
3612 if ((std::abs(press.xy[0] - event_xy[0]) + std::abs(press.xy[1] - event_xy[1])) >
3613 gwl_window_dpi_scale_value(win, params.cursor_drag_threshold))
3614 {
3615 xdg_toplevel_move(win->xdg_toplevel_get(), seat->wl.seat, press.serial);
3616 }
3617 }
3618 }
3619 }
3620
3621 return gwl_window_csd_active_elem_type_apply(seat, win, active_type_next);
3622}
3623
3627static void gwl_window_csd_active_elem_clear(GHOST_WindowWayland *win)
3628{
3629 win->csd_elem_active_type_set(GHOST_kCSDTypeBody);
3630}
3631static void gwl_window_csd_buttons_clear(GHOST_WindowWayland *win)
3632{
3633 GHOST_CSD_EventState &event_state = win->csd_eventstate_get();
3634 for (int i = 0; i < ARRAY_SIZE(event_state.buttons); i += 1) {
3635 GHOST_CSD_EventState_Button &event_button = event_state.buttons[i];
3636 event_button.action_history_num = 0;
3637 }
3638}
3639
3643static void gwl_window_csd_active_elem_button(GWL_Seat *seat,
3645 const GHOST_TButton ebutton,
3646 const bool is_press,
3647 const uint32_t serial,
3648 const uint64_t event_ms)
3649{
3650 /* Only these button types are handled. */
3652 return;
3653 }
3654
3655 /* When the cursor is grabbed, don't interact with the window decorations.
3656 * Although in most cases wrapping prevents it anyway,
3657 * it may not with absolute pointing devices. */
3658 if (win->getCursorGrabMode() != GHOST_kGrabDisable) {
3659 return;
3660 }
3661
3662 const GHOST_TCSD_Type active_type = win->csd_elem_active_type_get();
3663 /* Use on release events to check the press was on the same type. */
3665
3666 bool is_double_click = false;
3667 GHOST_CSD_EventState &event_state = win->csd_eventstate_get();
3668 if (ebutton < ARRAY_SIZE(event_state.buttons)) {
3669 const GHOST_CSD_Params &params = seat->system->getWindowCSD();
3670 GHOST_CSD_EventState_Button &event_button = event_state.buttons[ebutton];
3671
3672 if (event_button.action_history_num >= 1) {
3673 const GHOST_CSD_EventState_ButtonAction *actions = event_button.action_history;
3674 if (actions[0].is_press) {
3675 press_type = actions[0].type;
3676 }
3677 }
3678
3679 if (event_button.action_history_num >= 3) {
3680 const GHOST_CSD_EventState_ButtonAction *actions = event_button.action_history;
3681
3682 if ((is_press == false) && (actions[0].is_press == true && actions[1].is_press == false &&
3683 actions[2].is_press == true))
3684 {
3685 if ((active_type == actions[0].type) &&
3686 ((actions[0].type == actions[1].type) && (actions[1].type == actions[2].type)))
3687 {
3688 if ((actions[0].ms - actions[1].ms) <= params.cursor_double_click_ms &&
3689 (actions[1].ms - actions[2].ms) <= params.cursor_double_click_ms)
3690 {
3691 if ((std::abs(actions[0].xy[0] - actions[2].xy[0]) +
3692 std::abs(actions[0].xy[1] - actions[2].xy[1])) <=
3693 gwl_window_dpi_scale_value(win, params.cursor_drag_threshold))
3694 {
3695 is_double_click = true;
3696 }
3697 }
3698 }
3699 }
3700 }
3701
3702 if (event_button.action_history_num < ARRAY_SIZE(event_button.action_history)) {
3703 event_button.action_history_num += 1;
3704 }
3705 for (int i = event_button.action_history_num - 1; i > 0; i -= 1) {
3706 event_button.action_history[i] = event_button.action_history[i - 1];
3707 }
3708
3709 GHOST_CSD_EventState_ButtonAction &action = event_button.action_history[0];
3710
3711 action.ms = event_ms;
3712 action.is_press = is_press;
3713 action.xy[0] = event_state.event_xy[0];
3714 action.xy[1] = event_state.event_xy[1];
3715 action.serial = serial;
3716 action.type = active_type;
3717
3718 if (is_double_click) {
3719 event_button.action_history_num = 0;
3720 }
3721 }
3722
3723 if (ebutton == GHOST_kButtonMaskLeft) {
3724 switch (active_type) {
3725 case GHOST_kCSDTypeBody: {
3726 break;
3727 }
3729 if (is_press) {
3730 xdg_toplevel_resize(
3731 win->xdg_toplevel_get(), seat->wl.seat, serial, XDG_TOPLEVEL_RESIZE_EDGE_TOP);
3732 }
3733 break;
3734 }
3736 if (is_press) {
3737 xdg_toplevel_resize(
3738 win->xdg_toplevel_get(), seat->wl.seat, serial, XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM);
3739 }
3740 break;
3741 }
3743 if (is_press) {
3744 xdg_toplevel_resize(
3745 win->xdg_toplevel_get(), seat->wl.seat, serial, XDG_TOPLEVEL_RESIZE_EDGE_LEFT);
3746 }
3747 break;
3748 }
3750 if (is_press) {
3751 xdg_toplevel_resize(
3752 win->xdg_toplevel_get(), seat->wl.seat, serial, XDG_TOPLEVEL_RESIZE_EDGE_RIGHT);
3753 }
3754 break;
3755 }
3757 if (is_press) {
3758 xdg_toplevel_resize(
3759 win->xdg_toplevel_get(), seat->wl.seat, serial, XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT);
3760 }
3761 break;
3762 }
3764 if (is_press) {
3765 xdg_toplevel_resize(
3766 win->xdg_toplevel_get(), seat->wl.seat, serial, XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT);
3767 }
3768 break;
3769 }
3771 if (is_press) {
3772 xdg_toplevel_resize(win->xdg_toplevel_get(),
3773 seat->wl.seat,
3774 serial,
3775 XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT);
3776 }
3777 break;
3778 }
3780 if (is_press) {
3781 xdg_toplevel_resize(win->xdg_toplevel_get(),
3782 seat->wl.seat,
3783 serial,
3784 XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT);
3785 }
3786 break;
3787 }
3789 if (is_double_click) {
3790 if (win->xdg_toplevel_state_get() == GHOST_kWindowStateNormal) {
3791 xdg_toplevel_set_maximized(win->xdg_toplevel_get());
3792 }
3793 else {
3794 xdg_toplevel_unset_maximized(win->xdg_toplevel_get());
3795 }
3796 }
3797 break;
3798 }
3800 if (is_press == false && (active_type == press_type)) {
3801 xdg_toplevel_set_minimized(win->xdg_toplevel_get());
3802 }
3803 break;
3804 }
3806 if (is_press == false && (active_type == press_type)) {
3807 if (win->xdg_toplevel_state_get() == GHOST_kWindowStateNormal) {
3808 xdg_toplevel_set_maximized(win->xdg_toplevel_get());
3809 }
3810 else {
3811 xdg_toplevel_unset_maximized(win->xdg_toplevel_get());
3812 }
3813 }
3814 break;
3815 }
3817 if (is_press == false && (active_type == press_type)) {
3818 win->close();
3819 }
3820 break;
3821 }
3823 if (is_press == false) {
3824 /* Note that for GNOME 49 it's important the `serial` used is from the "press" event
3825 * (not this "release" event). Otherwise the menu won't show at all. */
3826 const GHOST_CSD_EventState &event_state = win->csd_eventstate_get();
3827 const GHOST_CSD_EventState_Button &event_button =
3828 event_state.buttons[GHOST_kButtonMaskLeft];
3829 if (event_button.action_history_num > 1) {
3830 const GHOST_CSD_EventState_ButtonAction &action = event_button.action_history[1];
3831 if (action.is_press && (active_type == action.type)) {
3832 int elems_num;
3833 const GHOST_CSD_Elem *csd_elems = win->csd_layout(&elems_num);
3834 int i_menu = -1;
3835 for (int i = 0; i < elems_num; i += 1) {
3836 if (csd_elems[i].type == GHOST_kCSDTypeButtonMenu) {
3837 i_menu = i;
3838 break;
3839 }
3840 }
3841 if (i_menu != -1) {
3842 /* Position the menu at the buttons (X-min, Y-max). */
3843 const GWL_WindowScaleParams &scale_params = win->scale_params_get();
3844 const int button_xy[2] = {
3845 gwl_window_scale_wl_fixed_from(scale_params, csd_elems[i_menu].bounds[0][0]),
3846 gwl_window_scale_wl_fixed_from(scale_params, csd_elems[i_menu].bounds[1][1]),
3847 };
3848 xdg_toplevel_show_window_menu(
3849 win->xdg_toplevel_get(), seat->wl.seat, action.serial, UNPACK2(button_xy));
3850 }
3851 }
3852 }
3853 }
3854 break;
3855 }
3856 }
3857 }
3858 else if (ebutton == GHOST_kButtonMaskRight) {
3859 switch (active_type) {
3860 case GHOST_kCSDTypeBody: {
3861 break;
3862 }
3864 if (is_press) {
3865 const GHOST_CSD_EventState &event_state = win->csd_eventstate_get();
3866 const GWL_WindowScaleParams &scale_params = win->scale_params_get();
3867 const int event_xy[2] = {
3868 gwl_window_scale_wl_fixed_from(scale_params, event_state.event_xy[0]),
3869 gwl_window_scale_wl_fixed_from(scale_params, event_state.event_xy[1]),
3870 };
3871 xdg_toplevel_show_window_menu(
3872 win->xdg_toplevel_get(), seat->wl.seat, serial, UNPACK2(event_xy));
3873 }
3874 break;
3875 }
3876 default: {
3877 break;
3878 }
3879 }
3880 }
3881}
3882
3887static bool ghost_wl_surface_own_csd_margin_with_null_check(const wl_surface *wl_surface)
3888{
3889 return wl_surface && ghost_wl_surface_own_csd_margin(wl_surface);
3890}
3891
3896static GHOST_WindowWayland *ghost_wl_surface_csd_margin_user_data(wl_surface *wl_surface)
3897{
3898 GHOST_ASSERT(wl_surface, "wl_surface must not be nullptr");
3899 GHOST_ASSERT(ghost_wl_surface_own_csd_margin(wl_surface),
3900 "wl_surface is not the CSD margin surface");
3901 return static_cast<GHOST_WindowWayland *>(wl_surface_get_user_data(wl_surface));
3902}
3903
3908static GHOST_WindowWayland *gwl_window_csd_margin_focus_set(
3909 GWL_Seat *seat,
3910 GWL_SeatStatePointer *seat_state_pointer,
3911 const uint32_t serial,
3913{
3914 GHOST_WindowWayland *win = ghost_wl_surface_csd_margin_user_data(wl_surface);
3915
3917 seat_state_pointer->serial = serial;
3918 seat_state_pointer->wl.surface_window = nullptr;
3919 seat_state_pointer->wl.surface_window_csd_margin = wl_surface;
3920
3921 seat->system->seat_active_set(seat);
3922
3923 /* On enter there is logically no prior state that needs to be taken into account.
3924 * Note that this is mostly likely cleared when leaving, setting here to account
3925 * for badly behaved compositors. */
3926 win->csd_elem_active_type_set(GHOST_kCSDTypeBody);
3927 gwl_window_csd_buttons_clear(win);
3928
3929 return win;
3930}
3931
3936static void gwl_window_csd_margin_focus_clear(GWL_SeatStatePointer *seat_state_pointer,
3938{
3939 GHOST_WindowWayland *win = ghost_wl_surface_csd_margin_user_data(wl_surface);
3940 gwl_window_csd_active_elem_clear(win);
3941 gwl_window_csd_buttons_clear(win);
3942 seat_state_pointer->wl.surface_window_csd_margin = nullptr;
3943}
3944
3954static bool gwl_window_csd_margin_elem_motion(GWL_Seat *seat,
3956 const wl_fixed_t xy[2])
3957{
3958 int32_t margin_size = 0;
3959 int32_t window_size[2] = {0, 0};
3960 win->csd_margin_geometry_get(margin_size, window_size);
3961
3962 /* The window rectangle in margin surface local coordinates. */
3963 const wl_fixed_t xy_min = wl_fixed_from_int(margin_size);
3964 const wl_fixed_t xy_max[2] = {
3965 wl_fixed_from_int(margin_size + window_size[0]),
3966 wl_fixed_from_int(margin_size + window_size[1]),
3967 };
3968
3969 GHOST_TCSD_Type type;
3970 if (xy[1] < xy_min) {
3971 type = (xy[0] < xy_min) ? GHOST_kCSDTypeBorderTopLeft :
3972 (xy[0] >= xy_max[0]) ? GHOST_kCSDTypeBorderTopRight :
3974 }
3975 else if (xy[1] >= xy_max[1]) {
3976 type = (xy[0] < xy_min) ? GHOST_kCSDTypeBorderBottomLeft :
3977 (xy[0] >= xy_max[0]) ? GHOST_kCSDTypeBorderBottomRight :
3979 }
3980 else if (xy[0] < xy_min) {
3982 }
3983 else if (xy[0] >= xy_max[0]) {
3985 }
3986 else {
3987 /* Points within the window rectangle are handled by the window surface above,
3988 * should practically never happen. */
3989 return false;
3990 }
3991
3992 return gwl_window_csd_active_elem_type_apply(seat, win, type);
3993}
3994
3995#endif /* WITH_GHOST_CSD */
3996
3998
3999/* -------------------------------------------------------------------- */
4002
4004{
4005 const char *xdg_current_desktop = [] {
4006 /* Account for VSCode overriding this value (TSK!), see: #133921. */
4007 const char *key = "ORIGINAL_XDG_CURRENT_DESKTOP";
4008 const char *value = getenv(key);
4009 return value ? value : getenv(key + 9);
4010 }();
4011
4012 if (xdg_current_desktop) {
4013 /* See the free-desktop specifications for details on `XDG_CURRENT_DESKTOP`.
4014 * https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html
4015 */
4016 if (string_elem_split_by_delim(xdg_current_desktop, ':', "GNOME")) {
4018 }
4019 else if (string_elem_split_by_delim(xdg_current_desktop, ':', "KDE")) {
4021 }
4022 }
4024}
4025
4027
4028/* -------------------------------------------------------------------- */
4034
4035static CLG_LogRef LOG_WL_RELATIVE_POINTER = {"ghost.wl.handle.relative_pointer"};
4036#define LOG (&LOG_WL_RELATIVE_POINTER)
4037
4043 const wl_fixed_t xy[2],
4044 const uint64_t event_ms)
4045{
4046 seat->pointer.xy[0] = xy[0];
4047 seat->pointer.xy[1] = xy[1];
4048
4049#ifdef USE_GNOME_CONFINE_HACK
4050 if (seat->use_pointer_software_confine) {
4052 win->getClientBounds(bounds);
4053 /* Needed or the cursor is considered outside the window and doesn't restore the location. */
4054 bounds.r_ -= 1;
4055 bounds.b_ -= 1;
4056 bounds.l_ = win->wl_fixed_from_window(wl_fixed_from_int(bounds.l_));
4057 bounds.t_ = win->wl_fixed_from_window(wl_fixed_from_int(bounds.t_));
4058 bounds.r_ = win->wl_fixed_from_window(wl_fixed_from_int(bounds.r_));
4059 bounds.b_ = win->wl_fixed_from_window(wl_fixed_from_int(bounds.b_));
4061 }
4062#endif
4063 const int event_xy[2] = {WL_FIXED_TO_INT_FOR_WINDOW_V2(win, seat->pointer.xy)};
4064 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventCursor>(
4065 event_ms, GHOST_kEventCursorMove, win, UNPACK2(event_xy), GHOST_TABLET_DATA_NONE));
4066}
4067
4069 void *data,
4070 zwp_relative_pointer_v1 * /*zwp_relative_pointer_v1*/,
4071 const uint32_t utime_hi,
4072 const uint32_t utime_lo,
4073 const wl_fixed_t dx,
4074 const wl_fixed_t dy,
4075 const wl_fixed_t /*dx_unaccel*/,
4076 const wl_fixed_t /*dy_unaccel*/)
4077{
4078 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4079 const uint64_t time = ghost_wl_ms_from_utime_pair(utime_hi, utime_lo);
4080 const uint64_t event_ms = seat->system->ms_from_input_time(time);
4081
4082 if (wl_surface *wl_surface_focus = seat->pointer.wl.surface_window) {
4083 CLOG_DEBUG(LOG, "relative_motion");
4084 GHOST_WindowWayland *win = ghost_wl_surface_user_data(wl_surface_focus);
4085 /* In most cases `wl_fixed_t` values are scaled by the window: `win->wl_fixed_from_window(..)`
4086 * In this case however, it's desired behavior that the mouse moves faster on outputs that
4087 * use scaling, scaling here makes the pointers relative motion too slow, see: #129230. */
4088 const wl_fixed_t xy_next[2] = {
4089 seat->pointer.xy[0] + dx,
4090 seat->pointer.xy[1] + dy,
4091 };
4092 relative_pointer_handle_relative_motion_impl(seat, win, xy_next, event_ms);
4093 }
4094 else {
4095 CLOG_DEBUG(LOG, "relative_motion (skipped)");
4096 }
4097}
4098
4099static const zwp_relative_pointer_v1_listener relative_pointer_listener = {
4101};
4102
4103#undef LOG
4104
4106
4107/* -------------------------------------------------------------------- */
4110
4111static CLG_LogRef LOG_WL_DATA_SOURCE = {"ghost.wl.handle.data_source"};
4112#define LOG (&LOG_WL_DATA_SOURCE)
4113
4114static void dnd_events(const GWL_Seat *const seat,
4115 const GHOST_TEventType event,
4116 const uint64_t event_ms)
4117{
4118 /* NOTE: `seat->data_offer_dnd_mutex` must already be locked. */
4119 if (wl_surface *wl_surface_focus = seat->wl.surface_window_focus_dnd) {
4120 GHOST_WindowWayland *win = ghost_wl_surface_user_data(wl_surface_focus);
4121 const int event_xy[2] = {WL_FIXED_TO_INT_FOR_WINDOW_V2(win, seat->data_offer_dnd->dnd.xy)};
4122 for (size_t i = 0; i < ARRAY_SIZE(ghost_wl_mime_preference_order_type); i++) {
4124 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventDragnDrop>(
4125 event_ms, event, type, win, UNPACK2(event_xy), nullptr));
4126 }
4127 }
4128}
4129
4131 const char *mime_receive,
4132 std::mutex *mutex,
4133 const bool nil_terminate,
4134 size_t *r_len)
4135{
4136 int pipefd[2];
4137 const bool pipefd_ok = pipe(pipefd) == 0;
4138 if (pipefd_ok) {
4139 wl_data_offer_receive(data_offer->wl.id, mime_receive, pipefd[1]);
4140 close(pipefd[1]);
4141 }
4142 else {
4143 CLOG_WARN(LOG, "error creating pipe: %s", std::strerror(errno));
4144 }
4145
4146 if (mutex) {
4147 mutex->unlock();
4148 }
4149 /* NOTE: Regarding `data_offer`:
4150 * - In the case of the clipboard - unlocking the `mutex` means, it may be feed from now on.
4151 * - In the case of drag & drop - the caller owns & no locking is needed
4152 * (locking is performed while transferring the ownership).
4153 */
4154 char *buf = nullptr;
4155 if (pipefd_ok) {
4156 buf = read_file_as_buffer(pipefd[0], nil_terminate, r_len);
4157 if (buf == nullptr) {
4158 CLOG_WARN(LOG, "unable to pipe into buffer: %s", std::strerror(errno));
4159 }
4160 close(pipefd[0]);
4161 }
4162 else {
4163 *r_len = 0;
4164 }
4165 return buf;
4166}
4167
4169 const char *mime_receive,
4170 std::mutex *mutex,
4171 const bool nil_terminate,
4172 size_t *r_len)
4173{
4174 int pipefd[2];
4175 const bool pipefd_ok = pipe(pipefd) == 0;
4176 if (pipefd_ok) {
4177 zwp_primary_selection_offer_v1_receive(data_offer->wp.id, mime_receive, pipefd[1]);
4178 close(pipefd[1]);
4179 }
4180 else {
4181 CLOG_WARN(LOG, "error creating pipe: %s", std::strerror(errno));
4182 }
4183
4184 if (mutex) {
4185 mutex->unlock();
4186 }
4187 /* WARNING: `data_offer` may be freed from now on. */
4188 char *buf = nullptr;
4189 if (pipefd_ok) {
4190 buf = read_file_as_buffer(pipefd[0], nil_terminate, r_len);
4191 if (buf == nullptr) {
4192 CLOG_WARN(LOG, "unable to pipe into buffer: %s", std::strerror(errno));
4193 }
4194 close(pipefd[0]);
4195 }
4196 return buf;
4197}
4198
4205static void data_source_handle_target(void * /*data*/,
4206 wl_data_source * /*wl_data_source*/,
4207 const char * /*mime_type*/)
4208{
4209 CLOG_DEBUG(LOG, "target");
4210}
4211
4212static void data_source_handle_send(void *data,
4213 wl_data_source * /*wl_data_source*/,
4214 const char * /*mime_type*/,
4215 const int32_t fd)
4216{
4217 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4218
4219 CLOG_DEBUG(LOG, "send");
4220
4221 auto write_file_fn = [](GWL_Seat *seat, const int fd) {
4222 if (write(fd, seat->data_source->buffer_out.data, seat->data_source->buffer_out.data_size) < 0)
4223 [[unlikely]]
4224 {
4225 CLOG_WARN(LOG, "error writing to clipboard: %s", std::strerror(errno));
4226 }
4227 close(fd);
4228 seat->data_source_mutex.unlock();
4229 };
4230
4231 seat->data_source_mutex.lock();
4232 std::thread write_thread(write_file_fn, seat, fd);
4233 write_thread.detach();
4234}
4235
4236static void data_source_handle_cancelled(void *data, wl_data_source *wl_data_source)
4237{
4238 CLOG_DEBUG(LOG, "cancelled");
4239 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4240 std::lock_guard lock{seat->data_source_mutex};
4241
4242 GWL_DataSource *data_source = seat->data_source;
4243 if (seat->data_source->wl.source == wl_data_source) {
4244 data_source->wl.source = nullptr;
4245 }
4246
4247 wl_data_source_destroy(wl_data_source);
4248}
4249
4257static void data_source_handle_dnd_drop_performed(void * /*data*/,
4258 wl_data_source * /*wl_data_source*/)
4259{
4260 CLOG_DEBUG(LOG, "dnd_drop_performed");
4261}
4262
4270static void data_source_handle_dnd_finished(void * /*data*/, wl_data_source * /*wl_data_source*/)
4271{
4272 CLOG_DEBUG(LOG, "dnd_finished");
4273}
4274
4282static void data_source_handle_action(void * /*data*/,
4283 wl_data_source * /*wl_data_source*/,
4284 const uint32_t dnd_action)
4285{
4286 CLOG_DEBUG(LOG, "handle_action (dnd_action=%u)", dnd_action);
4287}
4288
4289static const wl_data_source_listener data_source_listener = {
4290 /*target*/ data_source_handle_target,
4291 /*send*/ data_source_handle_send,
4292 /*cancelled*/ data_source_handle_cancelled,
4293 /*dnd_drop_performed*/ data_source_handle_dnd_drop_performed,
4294 /*dnd_finished*/ data_source_handle_dnd_finished,
4295 /*action*/ data_source_handle_action,
4296};
4297
4298#undef LOG
4299
4301
4302/* -------------------------------------------------------------------- */
4305
4306static CLG_LogRef LOG_WL_DATA_OFFER = {"ghost.wl.handle.data_offer"};
4307#define LOG (&LOG_WL_DATA_OFFER)
4308
4309static void data_offer_handle_offer(void *data,
4310 wl_data_offer * /*wl_data_offer*/,
4311 const char *mime_type)
4312{
4313 /* NOTE: locking isn't needed as the #GWL_DataOffer wont have been assigned to the #GWL_Seat. */
4314 CLOG_DEBUG(LOG, "offer (mime_type=%s)", mime_type);
4315 GWL_DataOffer *data_offer = static_cast<GWL_DataOffer *>(data);
4316 data_offer->types.insert(mime_type);
4317}
4318
4320 wl_data_offer * /*wl_data_offer*/,
4321 const uint32_t source_actions)
4322{
4323 /* NOTE: locking isn't needed as the #GWL_DataOffer wont have been assigned to the #GWL_Seat. */
4324 CLOG_DEBUG(LOG, "source_actions (%u)", source_actions);
4325 GWL_DataOffer *data_offer = static_cast<GWL_DataOffer *>(data);
4326 data_offer->dnd.source_actions = (enum wl_data_device_manager_dnd_action)source_actions;
4327}
4328
4329static void data_offer_handle_action(void *data,
4330 wl_data_offer * /*wl_data_offer*/,
4331 const uint32_t dnd_action)
4332{
4333 /* NOTE: locking isn't needed as the #GWL_DataOffer wont have been assigned to the #GWL_Seat. */
4334 CLOG_DEBUG(LOG, "actions (%u)", dnd_action);
4335 GWL_DataOffer *data_offer = static_cast<GWL_DataOffer *>(data);
4336 data_offer->dnd.action = (enum wl_data_device_manager_dnd_action)dnd_action;
4337}
4338
4339static const wl_data_offer_listener data_offer_listener = {
4340 /*offer*/ data_offer_handle_offer,
4341 /*source_actions*/ data_offer_handle_source_actions,
4342 /*action*/ data_offer_handle_action,
4343};
4344
4345#undef LOG
4346
4348
4349/* -------------------------------------------------------------------- */
4352
4353static CLG_LogRef LOG_WL_DATA_DEVICE = {"ghost.wl.handle.data_device"};
4354#define LOG (&LOG_WL_DATA_DEVICE)
4355
4356static void data_device_handle_data_offer(void * /*data*/,
4357 wl_data_device * /*wl_data_device*/,
4358 wl_data_offer *id)
4359{
4360 CLOG_DEBUG(LOG, "data_offer");
4361
4362 /* The ownership of data-offer isn't so obvious:
4363 * At this point it's not known if this will be used for drag & drop or selection.
4364 *
4365 * The API docs state that the following callbacks run immediately after this callback:
4366 * - #wl_data_device_listener::enter (for drag & drop).
4367 * - #wl_data_device_listener::selection (for copy & paste).
4368 *
4369 * In the case of GHOST, this means they will be assigned to either:
4370 * - #GWL_Seat::data_offer_dnd
4371 * - #GWL_Seat::data_offer_copy_paste
4372 */
4373 GWL_DataOffer *data_offer = new GWL_DataOffer;
4374 data_offer->wl.id = id;
4375 wl_data_offer_add_listener(id, &data_offer_listener, data_offer);
4376}
4377
4378static void data_device_handle_enter(void *data,
4379 wl_data_device * /*wl_data_device*/,
4380 const uint32_t serial,
4382 const wl_fixed_t x,
4383 const wl_fixed_t y,
4384 wl_data_offer *id)
4385{
4386 /* Always clear the current data-offer no matter what else happens. */
4387 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4388 const uint64_t event_ms = seat->system->getMilliSeconds();
4389
4390 std::lock_guard lock{seat->data_offer_dnd_mutex};
4391 if (seat->data_offer_dnd) {
4392 wl_data_offer_destroy(seat->data_offer_dnd->wl.id);
4393 delete seat->data_offer_dnd;
4394 seat->data_offer_dnd = nullptr;
4395 }
4396 /* Clearing complete. */
4397
4398 /* Handle the new offer. */
4399 GWL_DataOffer *data_offer = static_cast<GWL_DataOffer *>(wl_data_offer_get_user_data(id));
4401 CLOG_DEBUG(LOG, "enter (skipped)");
4402 wl_data_offer_destroy(data_offer->wl.id);
4403 delete data_offer;
4404 return;
4405 }
4406 CLOG_DEBUG(LOG, "enter");
4407
4408 /* Transfer ownership of the `data_offer`. */
4409 seat->data_offer_dnd = data_offer;
4410
4411 data_offer->dnd.xy[0] = x;
4412 data_offer->dnd.xy[1] = y;
4413
4414 wl_data_offer_set_actions(id,
4415 WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY |
4416 WL_DATA_DEVICE_MANAGER_DND_ACTION_MOVE,
4417 WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY);
4418
4419 for (size_t i = 0; i < ARRAY_SIZE(ghost_wl_mime_preference_order); i++) {
4420 const char *type = ghost_wl_mime_preference_order[i];
4421 if (!data_offer->types.contains(type)) {
4422 /* Not required by the spec but SMITHAY based compositors fail to drop without this.
4423 * See bug 1953, reported upstream. */
4424 continue;
4425 }
4426 wl_data_offer_accept(id, serial, type);
4427 }
4428
4429 seat->wl.surface_window_focus_dnd = wl_surface;
4430
4431 seat->system->seat_active_set(seat);
4432
4433 dnd_events(seat, GHOST_kEventDraggingEntered, event_ms);
4434}
4435
4436static void data_device_handle_leave(void *data, wl_data_device * /*wl_data_device*/)
4437{
4438 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4439 const uint64_t event_ms = seat->system->getMilliSeconds();
4440
4441 std::lock_guard lock{seat->data_offer_dnd_mutex};
4442 /* The user may have only dragged over the window decorations. */
4443 if (seat->data_offer_dnd == nullptr) {
4444 return;
4445 }
4446 CLOG_DEBUG(LOG, "leave");
4447
4448 dnd_events(seat, GHOST_kEventDraggingExited, event_ms);
4449 seat->wl.surface_window_focus_dnd = nullptr;
4450
4451 if (seat->data_offer_dnd) {
4452 wl_data_offer_destroy(seat->data_offer_dnd->wl.id);
4453 delete seat->data_offer_dnd;
4454 seat->data_offer_dnd = nullptr;
4455 }
4456}
4457
4458static void data_device_handle_motion(void *data,
4459 wl_data_device * /*wl_data_device*/,
4460 const uint32_t time,
4461 const wl_fixed_t x,
4462 const wl_fixed_t y)
4463{
4464 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4465 const uint64_t event_ms = seat->system->ms_from_input_time(time);
4466
4467 std::lock_guard lock{seat->data_offer_dnd_mutex};
4468 /* The user may have only dragged over the window decorations. */
4469 if (seat->data_offer_dnd == nullptr) {
4470 return;
4471 }
4472
4473 CLOG_DEBUG(LOG, "motion");
4474
4475 seat->data_offer_dnd->dnd.xy[0] = x;
4476 seat->data_offer_dnd->dnd.xy[1] = y;
4477
4478 dnd_events(seat, GHOST_kEventDraggingUpdated, event_ms);
4479}
4480
4481static void data_device_handle_drop(void *data, wl_data_device * /*wl_data_device*/)
4482{
4483 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4484 std::lock_guard lock{seat->data_offer_dnd_mutex};
4485
4486 /* No need to check this for null (as other callbacks do).
4487 * because the data-offer has not been accepted (actions set... etc). */
4488 GWL_DataOffer *data_offer = seat->data_offer_dnd;
4489
4490 /* Take ownership of `data_offer` to prevent a double-free, see: #128766.
4491 * The thread this function spawns is responsible for freeing it. */
4492 seat->data_offer_dnd = nullptr;
4493
4494 /* Use a blank string for `mime_receive` to prevent crashes, although could also be `nullptr`.
4495 * Failure to set this to a known type just means the file won't have any special handling.
4496 * GHOST still generates a dropped file event.
4497 * NOTE: this string can be compared with `mime_text_plain`, `mime_text_uri` etc...
4498 * as this always points to the same values. */
4499 const char *mime_receive = "";
4500 for (size_t i = 0; i < ARRAY_SIZE(ghost_wl_mime_preference_order); i++) {
4501 const char *type = ghost_wl_mime_preference_order[i];
4502 if (data_offer->types.contains(type)) {
4503 mime_receive = type;
4504 break;
4505 }
4506 }
4507
4508 CLOG_DEBUG(LOG, "drop mime_receive=%s", mime_receive);
4509
4510 auto read_drop_data_fn = [](GWL_Seat *const seat,
4511 GWL_DataOffer *data_offer,
4512 wl_surface *wl_surface_window,
4513 const char *mime_receive) {
4514 const uint64_t event_ms = seat->system->getMilliSeconds();
4515 const wl_fixed_t xy[2] = {UNPACK2(data_offer->dnd.xy)};
4516
4517 const bool nil_terminate = (mime_receive != ghost_wl_mime_text_uri_list);
4518 size_t data_buf_len = 0;
4519 const char *data_buf = read_buffer_from_data_offer(
4520 data_offer, mime_receive, nullptr, nil_terminate, &data_buf_len);
4521
4522 CLOG_DEBUG(LOG, "read_drop_data mime_receive=%s, data_len=%zu", mime_receive, data_buf_len);
4523
4524 wl_data_offer_finish(data_offer->wl.id);
4525 wl_data_offer_destroy(data_offer->wl.id);
4526
4527 delete data_offer;
4528 data_offer = nullptr;
4529
4530 /* Don't generate a drop event if the data could not be read,
4531 * an error will have been logged. */
4532 if (data_buf != nullptr) {
4534 void *ghost_dnd_data = nullptr;
4535
4536 /* Failure to receive drop data. */
4537 if (mime_receive == ghost_wl_mime_text_uri_list) {
4538 std::vector<std::string_view> uris = gwl_clipboard_uri_ranges(data_buf, data_buf_len);
4539
4540 GHOST_TStringArray *flist = static_cast<GHOST_TStringArray *>(
4541 malloc(sizeof(GHOST_TStringArray)));
4542 flist->count = int(uris.size());
4543 flist->strings = static_cast<uint8_t **>(malloc(uris.size() * sizeof(uint8_t *)));
4544 for (size_t i = 0; i < uris.size(); i++) {
4545 flist->strings[i] = reinterpret_cast<uint8_t *>(
4546 GHOST_URL_decode_alloc(uris[i].data(), uris[i].size()));
4547 }
4548
4549 CLOG_DEBUG(LOG, "read_drop_data file_count=%d", flist->count);
4550 ghost_dnd_type = GHOST_kDragnDropTypeFilenames;
4551 ghost_dnd_data = flist;
4552 }
4553 else if (ELEM(mime_receive, ghost_wl_mime_text_plain, ghost_wl_mime_text_utf8)) {
4554 ghost_dnd_type = GHOST_kDragnDropTypeString;
4555 ghost_dnd_data = (void *)data_buf; /* Move ownership to the event. */
4556 data_buf = nullptr;
4557 }
4558
4559 if (ghost_dnd_type != GHOST_kDragnDropTypeUnknown) {
4560 GHOST_SystemWayland *const system = seat->system;
4561 GHOST_WindowWayland *win = ghost_wl_surface_user_data(wl_surface_window);
4562 const int event_xy[2] = {WL_FIXED_TO_INT_FOR_WINDOW_V2(win, xy)};
4563
4565 std::make_unique<GHOST_EventDragnDrop>(event_ms,
4567 ghost_dnd_type,
4568 win,
4569 UNPACK2(event_xy),
4570 ghost_dnd_data));
4571
4573 }
4574 else {
4575 CLOG_DEBUG(LOG, "read_drop_data, unhandled!");
4576 }
4577
4578 free(const_cast<char *>(data_buf));
4579 }
4580 };
4581
4582 /* Pass in `seat->wl_surface_window_focus_dnd` instead of accessing it from `seat` since the
4583 * leave callback (#data_device_handle_leave) will clear the value once this function starts. */
4584 std::thread read_thread(
4585 read_drop_data_fn, seat, data_offer, seat->wl.surface_window_focus_dnd, mime_receive);
4586 read_thread.detach();
4587}
4588
4589static void data_device_handle_selection(void *data,
4590 wl_data_device * /*wl_data_device*/,
4591 wl_data_offer *id)
4592{
4593 /* Always clear the current data-offer no matter what else happens. */
4594 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4595 std::lock_guard lock{seat->data_offer_copy_paste_mutex};
4596 if (seat->data_offer_copy_paste) {
4597 wl_data_offer_destroy(seat->data_offer_copy_paste->wl.id);
4598 delete seat->data_offer_copy_paste;
4599 seat->data_offer_copy_paste = nullptr;
4600 seat->data_offer_copy_paste_has_image = std::nullopt;
4601 }
4602 /* Clearing complete. */
4603
4604 /* Handle the new offer. */
4605 if (id == nullptr) {
4606 CLOG_DEBUG(LOG, "selection: (skipped)");
4607 return;
4608 }
4609
4610 CLOG_DEBUG(LOG, "selection");
4611 GWL_DataOffer *data_offer = static_cast<GWL_DataOffer *>(wl_data_offer_get_user_data(id));
4612 /* Transfer ownership of the `data_offer`. */
4613 seat->data_offer_copy_paste = data_offer;
4614 seat->data_offer_copy_paste_has_image = std::nullopt;
4615}
4616
4617static const wl_data_device_listener data_device_listener = {
4618 /*data_offer*/ data_device_handle_data_offer,
4619 /*enter*/ data_device_handle_enter,
4620 /*leave*/ data_device_handle_leave,
4621 /*motion*/ data_device_handle_motion,
4622 /*drop*/ data_device_handle_drop,
4623 /*selection*/ data_device_handle_selection,
4624};
4625
4626#undef LOG
4627
4629
4630/* -------------------------------------------------------------------- */
4633
4634static CLG_LogRef LOG_WL_CURSOR_BUFFER = {"ghost.wl.handle.cursor_buffer"};
4635#define LOG (&LOG_WL_CURSOR_BUFFER)
4636
4637static void cursor_buffer_handle_release(void *data, wl_buffer *wl_buffer)
4638{
4639 CLOG_DEBUG(LOG, "release");
4640
4641 GWL_Cursor *cursor = static_cast<GWL_Cursor *>(data);
4642 wl_buffer_destroy(wl_buffer);
4643
4644 if (wl_buffer == cursor->wl.buffer) {
4645 /* The mapped buffer was from a custom cursor. */
4646 cursor->wl.buffer = nullptr;
4647 }
4648}
4649
4650static const wl_buffer_listener cursor_buffer_listener = {
4651 /*release*/ cursor_buffer_handle_release,
4652};
4653
4654#undef LOG
4655
4657
4658/* -------------------------------------------------------------------- */
4661
4662static CLG_LogRef LOG_WL_CURSOR_SURFACE = {"ghost.wl.handle.cursor_surface"};
4663#define LOG (&LOG_WL_CURSOR_SURFACE)
4664
4669 const GWL_SeatStatePointer *seat_state_pointer)
4670{
4671 if (!seat->cursor.is_custom) {
4672 return;
4673 }
4674 wl_surface *wl_surface_focus = seat_state_pointer->wl.surface_window;
4675 if (!wl_surface_focus) {
4676 return;
4677 }
4678 GHOST_WindowWayland *win = ghost_wl_surface_user_data(wl_surface_focus);
4679 if (win) {
4680 win->cursor_shape_refresh();
4681 }
4682}
4683
4685 GWL_Cursor &cursor,
4686 GWL_SeatStatePointer *seat_state_pointer)
4687{
4688 /* NOTE: currently there is no special handling for fractional scaling.
4689 * This could be supported however the default behavior of generating a cursor
4690 * rounded up to the nearest integer scaling works fairly well. */
4691 int scale = 0;
4692 for (const GWL_Output *output : seat_state_pointer->outputs) {
4693 scale = std::max(scale, output->scale);
4694 }
4695 if (scale > 0 && seat_state_pointer->buffer_scale != scale) {
4696 seat_state_pointer->buffer_scale = scale;
4697 }
4698
4700
4701 if (scale > 0 && cursor.custom_cursor_scale != scale) {
4702 cursor.custom_cursor_scale = scale;
4703 cursor_shape_refresh_for_pointer(seat, seat_state_pointer);
4704 return true;
4705 }
4706 return false;
4707}
4708
4709#ifdef WITH_GHOST_DBUS
4711static void cursor_size_set(GWL_Seat *seat, const int size_new)
4712{
4713 if (seat->cursor.theme_size == size_new) {
4714 return;
4715 }
4716 seat->cursor.theme_size = size_new;
4719}
4720#endif /* WITH_GHOST_DBUS */
4721
4722static void cursor_surface_handle_enter(void *data, wl_surface *wl_surface, wl_output *wl_output)
4723{
4724 if (!ghost_wl_output_own(wl_output)) {
4725 CLOG_DEBUG(LOG, "handle_enter (skipped)");
4726 return;
4727 }
4728 CLOG_DEBUG(LOG, "handle_enter");
4729
4730 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4732 seat, wl_surface);
4733 const GWL_Output *reg_output = ghost_wl_output_user_data(wl_output);
4734 seat_state_pointer->outputs.insert(reg_output);
4735 update_cursor_scale(seat, seat->cursor, seat_state_pointer);
4736}
4737
4738static void cursor_surface_handle_leave(void *data, wl_surface *wl_surface, wl_output *wl_output)
4739{
4740 if (!(wl_output && ghost_wl_output_own(wl_output))) {
4741 CLOG_DEBUG(LOG, "handle_leave (skipped)");
4742 return;
4743 }
4744 CLOG_DEBUG(LOG, "handle_leave");
4745
4746 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4748 seat, wl_surface);
4749 const GWL_Output *reg_output = ghost_wl_output_user_data(wl_output);
4750 seat_state_pointer->outputs.erase(reg_output);
4751 update_cursor_scale(seat, seat->cursor, seat_state_pointer);
4752}
4753
4755 wl_surface * /*wl_surface*/,
4756 const int32_t factor)
4757{
4758 /* Only available in interface version 6. */
4759 CLOG_DEBUG(LOG, "handle_preferred_buffer_scale (factor=%d)", factor);
4760}
4761
4762#if defined(WL_SURFACE_PREFERRED_BUFFER_SCALE_SINCE_VERSION) && \
4763 defined(WL_SURFACE_PREFERRED_BUFFER_TRANSFORM_SINCE_VERSION)
4764static void cursor_surface_handle_preferred_buffer_transform(void * /*data*/,
4765 wl_surface * /*wl_surface*/,
4766 uint32_t transform)
4767{
4768 /* Only available in interface version 6. */
4769 CLOG_DEBUG(LOG, "handle_preferred_buffer_transform (transform=%u)", transform);
4770}
4771#endif /* WL_SURFACE_PREFERRED_BUFFER_SCALE_SINCE_VERSION && \
4772 * WL_SURFACE_PREFERRED_BUFFER_TRANSFORM_SINCE_VERSION */
4773
4774static const wl_surface_listener cursor_surface_listener = {
4777#if defined(WL_SURFACE_PREFERRED_BUFFER_SCALE_SINCE_VERSION) && \
4778 defined(WL_SURFACE_PREFERRED_BUFFER_TRANSFORM_SINCE_VERSION)
4779 /*preferred_buffer_scale*/ cursor_surface_handle_preferred_buffer_scale,
4780 /*preferred_buffer_transform*/ cursor_surface_handle_preferred_buffer_transform,
4781#endif
4782};
4783
4784#undef LOG
4785
4787
4788/* -------------------------------------------------------------------- */
4791
4792static CLG_LogRef LOG_WL_POINTER = {"ghost.wl.handle.pointer"};
4793#define LOG (&LOG_WL_POINTER)
4794
4795#ifdef WITH_GHOST_CSD
4803static void pointer_handle_enter_csd_margin(GWL_Seat *seat,
4804 const uint32_t serial,
4806 const wl_fixed_t surface_x,
4807 const wl_fixed_t surface_y)
4808{
4809 GHOST_WindowWayland *win = gwl_window_csd_margin_focus_set(
4810 seat, &seat->pointer, serial, wl_surface);
4811
4812 seat->pointer.xy[0] = surface_x;
4813 seat->pointer.xy[1] = surface_y;
4814
4815 /* Resetting scroll events is likely unnecessary,
4816 * do this to avoid any possible problems as it's harmless. */
4818
4819 if (!gwl_window_csd_margin_elem_motion(seat, win, seat->pointer.xy)) {
4820 win->cursor_shape_refresh();
4821 }
4822}
4823#endif /* WITH_GHOST_CSD */
4824
4825static void pointer_handle_enter(void *data,
4826 wl_pointer * /*wl_pointer*/,
4827 const uint32_t serial,
4829 const wl_fixed_t surface_x,
4830 const wl_fixed_t surface_y)
4831{
4832 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4833
4834#ifdef WITH_GHOST_CSD
4835 if (ghost_wl_surface_own_csd_margin_with_null_check(wl_surface)) {
4836 CLOG_DEBUG(LOG, "enter (csd margin)");
4837 pointer_handle_enter_csd_margin(seat, serial, wl_surface, surface_x, surface_y);
4838 return;
4839 }
4840#endif
4841
4842 const uint64_t event_ms = seat->system->getMilliSeconds();
4843
4844 /* Null when just destroyed. */
4846 CLOG_DEBUG(LOG, "enter (skipped)");
4847 return;
4848 }
4849 CLOG_DEBUG(LOG, "enter");
4850
4852
4853 seat->cursor_source_serial = serial;
4854 seat->pointer.serial = serial;
4855 seat->pointer.xy[0] = surface_x;
4856 seat->pointer.xy[1] = surface_y;
4857
4858 /* Resetting scroll events is likely unnecessary,
4859 * do this to avoid any possible problems as it's harmless. */
4861
4863
4864 seat->system->seat_active_set(seat);
4865
4866 bool cursor_shape_refresh = true;
4867 const int event_xy[2] = {WL_FIXED_TO_INT_FOR_WINDOW_V2(win, seat->pointer.xy)};
4868
4869#ifdef WITH_GHOST_CSD
4870 if (seat->system->use_window_frame_csd_get()) {
4871 /* On enter there is logically no prior state that needs to be taken into account.
4872 * Note that this is mostly likely cleared when leaving, setting here to account
4873 * for badly behaved compositors. */
4874 win->csd_elem_active_type_set(GHOST_kCSDTypeBody);
4875 gwl_window_csd_buttons_clear(win);
4876
4877 if (gwl_window_csd_active_elem_motion(seat, win, event_xy)) {
4878 /* Already handled. */
4879 cursor_shape_refresh = false;
4880 }
4881 }
4882#endif /* WITH_GHOST_CSD */
4883 if (cursor_shape_refresh) {
4884 win->cursor_shape_refresh();
4885 }
4886 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventCursor>(
4887 event_ms, GHOST_kEventCursorMove, win, UNPACK2(event_xy), GHOST_TABLET_DATA_NONE));
4888}
4889
4890static void pointer_handle_leave(void *data,
4891 wl_pointer * /*wl_pointer*/,
4892 const uint32_t /*serial*/,
4894{
4895 /* First clear the `pointer.wl_surface`, since the window won't exist when closing the window. */
4896 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4898
4899#ifdef WITH_GHOST_CSD
4900 if (ghost_wl_surface_own_csd_margin_with_null_check(wl_surface)) {
4901 CLOG_DEBUG(LOG, "leave (csd margin)");
4902 gwl_window_csd_margin_focus_clear(&seat->pointer, wl_surface);
4903 return;
4904 }
4905#endif
4906
4908 CLOG_DEBUG(LOG, "leave (skipped)");
4909 return;
4910 }
4911 CLOG_DEBUG(LOG, "leave");
4912
4913#ifdef WITH_GHOST_CSD
4914 if (seat->system->use_window_frame_csd_get()) {
4916 gwl_window_csd_active_elem_clear(win);
4917 gwl_window_csd_buttons_clear(win);
4918 }
4919#endif
4920}
4921
4922static void pointer_handle_motion(void *data,
4923 wl_pointer * /*wl_pointer*/,
4924 const uint32_t time,
4925 const wl_fixed_t surface_x,
4926 const wl_fixed_t surface_y)
4927{
4928 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4929 const uint64_t event_ms = seat->system->ms_from_input_time(time);
4930
4931 seat->pointer.xy[0] = surface_x;
4932 seat->pointer.xy[1] = surface_y;
4933
4934 CLOG_DEBUG(LOG, "motion");
4935
4936#ifdef USE_GNOME_MOTION_MISSING_TIME_HACK
4938 if (event_ms == 0) [[unlikely]] {
4939 /* Only occur when the `relative_pointer` is released, ignore
4940 * because GHOST already adds a motion event. */
4941 return;
4942 }
4943 }
4944#endif
4945
4948}
4949
4950static void pointer_handle_button(void *data,
4951 wl_pointer * /*wl_pointer*/,
4952 const uint32_t serial,
4953 const uint32_t time,
4954 const uint32_t button,
4955 const uint32_t state)
4956{
4957 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4958
4959 CLOG_DEBUG(LOG, "button (button=%u, state=%u)", button, state);
4960
4961 /* Always set the serial, even if the button event is not sent. */
4962 seat->data_source_serial = serial;
4963
4964 int button_release;
4965 switch (state) {
4966 case WL_POINTER_BUTTON_STATE_RELEASED: {
4967 button_release = 1;
4968 break;
4969 }
4970 case WL_POINTER_BUTTON_STATE_PRESSED: {
4971 button_release = 0;
4972 break;
4973 }
4974 default: {
4975 return;
4976 }
4977 }
4978
4979 const uint32_t button_index = button - BTN_RANGE_MIN;
4980 if (button_index >= (BTN_RANGE_MAX - BTN_RANGE_MIN)) {
4981 return;
4982 }
4983
4985 int(GWL_Pointer_EventTypes::Button0_Down) + ((button_index * 2) + button_release));
4986
4987 const uint64_t event_ms = seat->system->ms_from_input_time(time);
4988 gwl_pointer_handle_frame_event_add(&seat->pointer_events, ty, serial, event_ms);
4989}
4990
4991static void pointer_handle_axis(void *data,
4992 wl_pointer * /*wl_pointer*/,
4993 const uint32_t time,
4994 const uint32_t axis,
4995 const wl_fixed_t value)
4996{
4997 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
4998 seat->pointer_scroll.event_ms = seat->system->ms_from_input_time(time);
4999 seat->pointer_scroll.has_event_ms = true;
5000
5001 /* NOTE: this is used for touch based scrolling - or other input that doesn't scroll with
5002 * discrete "steps". This allows supporting smooth-scrolling without "touch" gesture support. */
5003 CLOG_DEBUG(LOG, "axis (axis=%u, value=%d)", axis, value);
5004 const int index = pointer_axis_as_index(axis);
5005 if (index == -1) [[unlikely]] {
5006 return;
5007 }
5008 seat->pointer_scroll.smooth_xy[index] = value;
5009
5012}
5013
5014#ifdef WITH_GHOST_CSD
5022static void pointer_handle_frame_csd_margin(GWL_Seat *seat, wl_surface *wl_surface)
5023{
5024 GHOST_WindowWayland *win = ghost_wl_surface_csd_margin_user_data(wl_surface);
5025
5026 for (int ty_index = 0; ty_index < seat->pointer_events.frame_pending.frame_types_num; ty_index++)
5027 {
5028 const GWL_Pointer_EventTypes ty = seat->pointer_events.frame_pending.frame_types[ty_index];
5029 const uint64_t event_ms = seat->pointer_events.frame_pending.frame_event_ms[ty_index];
5030 const uint32_t serial = seat->pointer_events.frame_pending.frame_serial[ty_index];
5031 switch (ty) {
5032 using enum GWL_Pointer_EventTypes;
5033 case Motion: {
5034 gwl_window_csd_margin_elem_motion(seat, win, seat->pointer.xy);
5035 break;
5036 }
5037 case Scroll: {
5038 break;
5039 }
5040# ifdef NDEBUG
5041 default:
5042# else /* Warn when any events aren't handled (in debug builds). */
5043 case Button0_Down:
5044 case Button0_Up:
5045 case Button1_Down:
5046 case Button1_Up:
5047 case Button2_Down:
5048 case Button2_Up:
5049 case Button3_Down:
5050 case Button3_Up:
5051 case Button4_Down:
5052 case Button4_Up:
5053 case Button5_Down:
5054 case Button5_Up:
5055 case Button6_Down:
5056 case Button6_Up:
5057# endif
5058 {
5059 const int button_enum_offset = int(ty) - int(Button0_Down);
5060 const int button_index = button_enum_offset / 2;
5061 const bool button_down = (button_index * 2) == button_enum_offset;
5062 const GHOST_TButton ebutton = gwl_pointer_events_ebutton[button_index];
5063 GHOST_ASSERT(serial != WL_SERIAL_NONE || !button_down,
5064 "Button down events must have a serial");
5065 gwl_window_csd_active_elem_button(seat, win, ebutton, button_down, serial, event_ms);
5066 break;
5067 }
5068 }
5069 }
5070}
5071#endif /* WITH_GHOST_CSD */
5072
5073static void pointer_handle_frame(void *data, wl_pointer * /*wl_pointer*/)
5074{
5075 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5076
5077 CLOG_DEBUG(LOG, "frame");
5078
5079#ifdef WITH_GHOST_CSD
5080 if (wl_surface *wl_surface_focus = seat->pointer.wl.surface_window_csd_margin) {
5081 pointer_handle_frame_csd_margin(seat, wl_surface_focus);
5083 return;
5084 }
5085#endif
5086
5087 if (wl_surface *wl_surface_focus = seat->pointer.wl.surface_window) {
5088 GHOST_WindowWayland *win = ghost_wl_surface_user_data(wl_surface_focus);
5089 for (int ty_index = 0; ty_index < seat->pointer_events.frame_pending.frame_types_num;
5090 ty_index++)
5091 {
5092 const GWL_Pointer_EventTypes ty = seat->pointer_events.frame_pending.frame_types[ty_index];
5093 const uint64_t event_ms = seat->pointer_events.frame_pending.frame_event_ms[ty_index];
5094#ifdef WITH_GHOST_CSD
5095 const uint32_t serial = seat->pointer_events.frame_pending.frame_serial[ty_index];
5096#endif
5097 switch (ty) {
5098 using enum GWL_Pointer_EventTypes;
5099 /* Use motion for pressure and tilt as there are no explicit event types for these. */
5100 case Motion: {
5101 const int event_xy[2] = {WL_FIXED_TO_INT_FOR_WINDOW_V2(win, seat->pointer.xy)};
5102 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventCursor>(
5103 event_ms, GHOST_kEventCursorMove, win, UNPACK2(event_xy), GHOST_TABLET_DATA_NONE));
5104#ifdef WITH_GHOST_CSD
5105 if (seat->system->use_window_frame_csd_get()) {
5106 if (gwl_window_csd_active_elem_motion(seat, win, event_xy)) {
5107 /* Already handled. */
5108 }
5109 }
5110#endif /* WITH_GHOST_CSD */
5111 break;
5112 }
5113 case Scroll: {
5115
5116 /* The scroll data is "interpreted" before generating the events,
5117 * this is needed because data is accumulated
5118 * with support for handling smooth scroll as discrete events (for example). */
5119
5120 /* Most scroll events have no time, use `ps.event_ms` instead.
5121 * This is assigned for the scroll events that do set a time.
5122 * In practice the values tends to be set but fall back to the current time. */
5123 GHOST_ASSERT(event_ms == 0, "Scroll events are not expected to have a time!");
5124 /* Handle value120 to discrete steps first. */
5125 if (ps.discrete120_xy[0] || ps.discrete120_xy[1]) {
5126 for (int i = 0; i < 2; i++) {
5127 ps.discrete120_xy_accum[i] += ps.discrete120_xy[i];
5128 ps.discrete120_xy[i] = 0;
5129 /* The values will have been normalized so 120 represents a single click-step. */
5130 ps.discrete_xy[i] = ps.discrete120_xy_accum[i] / 120;
5131 ps.discrete120_xy_accum[i] -= ps.discrete_xy[i] * 120;
5132 }
5133 }
5134
5135 /* Multiple wheel events may have been generated and it's not known which.
5136 * The logic here handles prioritizing how they should be handled. */
5137 if (ps.axis_source == WL_POINTER_AXIS_SOURCE_WHEEL) {
5138 /* We never want mouse wheel events to be treated as smooth scrolling as this
5139 * causes mouse wheel scroll to orbit the view, see #120587.
5140 * Although it could be supported if the event system would forward
5141 * the source of the scroll action (a wheel or touch device). */
5142 ps.smooth_xy[0] = 0;
5143 ps.smooth_xy[1] = 0;
5144 }
5145 else if (ps.axis_source == WL_POINTER_AXIS_SOURCE_FINGER) {
5149 /* If discrete steps have been sent, use them as-is. */
5150 if ((ps.discrete_xy[0] == 0) && (ps.discrete_xy[1] == 0)) {
5151 /* Convert smooth to discrete. */
5152 for (int i = 0; i < 2; i++) {
5153 smooth_as_discrete.smooth_xy_accum[i] += ps.smooth_xy[i];
5154 if (std::abs(smooth_as_discrete.smooth_xy_accum[i]) >= smooth_as_discrete_steps)
5155 {
5156 ps.discrete_xy[i] = smooth_as_discrete.smooth_xy_accum[i] /
5158 smooth_as_discrete.smooth_xy_accum[i] -= ps.discrete_xy[i] *
5160 }
5161 }
5162 }
5163 ps.smooth_xy[0] = 0;
5164 ps.smooth_xy[1] = 0;
5165 }
5166 }
5167
5168 /* Both discrete and smooth events may be set at once, never generate events for both
5169 * as this will be handling the same event in two different ways.
5170 * Prioritize discrete axis events for the mouse wheel, otherwise smooth scroll. */
5171 if (ps.axis_source == WL_POINTER_AXIS_SOURCE_WHEEL) {
5172 if (ps.discrete_xy[0]) {
5173 ps.smooth_xy[0] = 0;
5174 }
5175 if (ps.discrete_xy[1]) {
5176 ps.smooth_xy[1] = 0;
5177 }
5178 }
5179 else {
5180 if (ps.smooth_xy[0]) {
5181 ps.discrete_xy[0] = 0;
5182 }
5183 if (ps.smooth_xy[1]) {
5184 ps.discrete_xy[1] = 0;
5185 }
5186 }
5187
5188 /* Done evaluating scroll input, generate the events. */
5189 if (ps.discrete_xy[0] || ps.discrete_xy[1]) {
5190 if (ps.discrete_xy[0]) {
5191 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventWheel>(
5192 ps.has_event_ms ? ps.event_ms : seat->system->getMilliSeconds(),
5193 win,
5195 ps.discrete_xy[0]));
5196 }
5197 if (ps.discrete_xy[1]) {
5198 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventWheel>(
5199 ps.has_event_ms ? ps.event_ms : seat->system->getMilliSeconds(),
5200 win,
5202 -ps.discrete_xy[1]));
5203 }
5204 ps.discrete_xy[0] = 0;
5205 ps.discrete_xy[1] = 0;
5206 }
5207
5208 if (ps.smooth_xy[0] || ps.smooth_xy[1]) {
5209 const int event_xy[2] = {WL_FIXED_TO_INT_FOR_WINDOW_V2(win, seat->pointer.xy)};
5210 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventTrackpad>(
5211 ps.has_event_ms ? ps.event_ms : seat->system->getMilliSeconds(),
5212 win,
5214 UNPACK2(event_xy),
5215 /* NOTE: scaling the delta doesn't seem necessary.
5216 * NOTE: inverting delta gives correct results, see: QTBUG-85767.
5217 * NOTE: the preference to invert scrolling (in GNOME at least)
5218 * has already been applied so there is no need to read this preference. */
5219 -wl_fixed_to_int(ps.smooth_xy[0]),
5220 -wl_fixed_to_int(ps.smooth_xy[1]),
5221 /* NOTE: GHOST does not support per-axis inversion.
5222 * Assume inversion is used or not. */
5223 ps.inverted_xy[0] || ps.inverted_xy[1]));
5224
5225 ps.smooth_xy[0] = 0;
5226 ps.smooth_xy[1] = 0;
5227 }
5228
5229 ps.axis_source = WL_POINTER_AXIS_SOURCE_WHEEL;
5230 ps.inverted_xy[0] = false;
5231 ps.inverted_xy[1] = false;
5232
5233 ps.event_ms = 0;
5234 ps.has_event_ms = false;
5235
5236 break;
5237 }
5238#ifdef NDEBUG
5239 default:
5240#else /* Warn when any events aren't handled (in debug builds). */
5241 case Button0_Down:
5242 case Button0_Up:
5243 case Button1_Down:
5244 case Button1_Up:
5245 case Button2_Down:
5246 case Button2_Up:
5247 case Button3_Down:
5248 case Button3_Up:
5249 case Button4_Down:
5250 case Button4_Up:
5251 case Button5_Down:
5252 case Button5_Up:
5253 case Button6_Down:
5254 case Button6_Up:
5255#endif
5256 {
5257 const int button_enum_offset = int(ty) - int(Button0_Down);
5258 const int button_index = button_enum_offset / 2;
5259 const bool button_down = (button_index * 2) == button_enum_offset;
5260 const GHOST_TButton ebutton = gwl_pointer_events_ebutton[button_index];
5261 const GHOST_TEventType etype = button_down ? GHOST_kEventButtonDown :
5263 seat->pointer.buttons.set(ebutton, button_down);
5264 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventButton>(
5265 event_ms, etype, win, ebutton, GHOST_TABLET_DATA_NONE));
5266
5267#ifdef WITH_GHOST_CSD
5268 if (seat->system->use_window_frame_csd_get()) {
5269 gwl_window_csd_active_elem_button(seat, win, ebutton, button_down, serial, event_ms);
5270 }
5271#endif
5272 break;
5273 }
5274 }
5275 }
5276 }
5277
5279}
5280static void pointer_handle_axis_source(void *data,
5281 wl_pointer * /*wl_pointer*/,
5282 const uint32_t axis_source)
5283{
5284 CLOG_DEBUG(LOG, "axis_source (axis_source=%u)", axis_source);
5285 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5286 seat->pointer_scroll.axis_source = (enum wl_pointer_axis_source)axis_source;
5287}
5288static void pointer_handle_axis_stop(void *data,
5289 wl_pointer * /*wl_pointer*/,
5290 const uint32_t time,
5291 const uint32_t axis)
5292{
5293 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5294 seat->pointer_scroll.event_ms = seat->system->ms_from_input_time(time);
5295 seat->pointer_scroll.has_event_ms = true;
5296
5298 /* Reset the scroll steps when the touch event ends.
5299 * Done so the user doesn't accidentally bump smooth scroll input a small number of steps
5300 * causing an unexpected discrete step caused by a very small amount of smooth-scrolling. */
5303 smooth_as_discrete.smooth_xy_accum[0] = 0;
5304 smooth_as_discrete.smooth_xy_accum[1] = 0;
5305 }
5306
5307 CLOG_DEBUG(LOG, "axis_stop (axis=%u)", axis);
5308}
5309static void pointer_handle_axis_discrete(void *data,
5310 wl_pointer * /*wl_pointer*/,
5311 const uint32_t axis,
5312 const int32_t discrete)
5313{
5314 /* NOTE: a discrete axis are typically mouse wheel events.
5315 * The non-discrete version of this function is used for touch-pad. */
5316 CLOG_DEBUG(LOG, "axis_discrete (axis=%u, discrete=%d)", axis, discrete);
5317 const int index = pointer_axis_as_index(axis);
5318 if (index == -1) [[unlikely]] {
5319 return;
5320 }
5321 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5322 seat->pointer_scroll.discrete_xy[index] = discrete;
5323
5326}
5327static void pointer_handle_axis_value120(void *data,
5328 wl_pointer * /*wl_pointer*/,
5329 const uint32_t axis,
5330 const int32_t value120)
5331{
5332 /* Only available in interface version 8. */
5333 CLOG_DEBUG(LOG, "axis_value120 (axis=%u, value120=%d)", axis, value120);
5334 const int index = pointer_axis_as_index(axis);
5335 if (index == -1) [[unlikely]] {
5336 return;
5337 }
5338 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5339 seat->pointer_scroll.discrete120_xy[index] = value120;
5340
5343}
5344#ifdef WL_POINTER_AXIS_RELATIVE_DIRECTION_ENUM /* Requires WAYLAND 1.22 or newer. */
5345static void pointer_handle_axis_relative_direction(void *data,
5346 wl_pointer * /*wl_pointer*/,
5347 const uint32_t axis,
5348 const uint32_t direction)
5349{
5350 /* Only available in interface version 9. */
5351 CLOG_DEBUG(LOG, "axis_relative_direction (axis=%u, direction=%u)", axis, direction);
5352 const int index = pointer_axis_as_index(axis);
5353 if (index == -1) [[unlikely]] {
5354 return;
5355 }
5356 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5357 seat->pointer_scroll.inverted_xy[index] = (direction ==
5358 WL_POINTER_AXIS_RELATIVE_DIRECTION_INVERTED);
5359}
5360#endif /* WL_POINTER_AXIS_RELATIVE_DIRECTION_ENUM */
5361
5362static const wl_pointer_listener pointer_listener = {
5363 /*enter*/ pointer_handle_enter,
5364 /*leave*/ pointer_handle_leave,
5365 /*motion*/ pointer_handle_motion,
5366 /*button*/ pointer_handle_button,
5367 /*axis*/ pointer_handle_axis,
5368 /*frame*/ pointer_handle_frame,
5369 /*axis_source*/ pointer_handle_axis_source,
5370 /*axis_stop*/ pointer_handle_axis_stop,
5371 /*axis_discrete*/ pointer_handle_axis_discrete,
5372 /*axis_value120*/ pointer_handle_axis_value120,
5373#ifdef WL_POINTER_AXIS_RELATIVE_DIRECTION_ENUM
5374 /*axis_relative_direction*/ pointer_handle_axis_relative_direction,
5375#endif
5376};
5377
5378#undef LOG
5379
5381
5382/* -------------------------------------------------------------------- */
5385
5386#ifdef ZWP_POINTER_GESTURE_HOLD_V1_INTERFACE
5387static CLG_LogRef LOG_WL_POINTER_GESTURE_HOLD = {"ghost.wl.handle.pointer_gesture.hold"};
5388# define LOG (&LOG_WL_POINTER_GESTURE_HOLD)
5389
5390static void gesture_hold_handle_begin(
5391 void * /*data*/,
5392 zwp_pointer_gesture_hold_v1 * /*zwp_pointer_gesture_hold_v1*/,
5393 const uint32_t /*serial*/,
5394 const uint32_t /*time*/,
5395 wl_surface * /*surface*/,
5396 const uint32_t fingers)
5397{
5398 CLOG_DEBUG(LOG, "begin (fingers=%u)", fingers);
5399}
5400
5401static void gesture_hold_handle_end(void * /*data*/,
5402 zwp_pointer_gesture_hold_v1 * /*zwp_pointer_gesture_hold_v1*/,
5403 const uint32_t /*serial*/,
5404 const uint32_t /*time*/,
5405 const int32_t cancelled)
5406{
5407 CLOG_DEBUG(LOG, "end (cancelled=%i)", cancelled);
5408}
5409
5410static const zwp_pointer_gesture_hold_v1_listener gesture_hold_listener = {
5411 /*begin*/ gesture_hold_handle_begin,
5412 /*end*/ gesture_hold_handle_end,
5413};
5414
5415# undef LOG
5416#endif /* ZWP_POINTER_GESTURE_HOLD_V1_INTERFACE */
5417
5419
5420/* -------------------------------------------------------------------- */
5423
5424#ifdef ZWP_POINTER_GESTURE_PINCH_V1_INTERFACE
5425static CLG_LogRef LOG_WL_POINTER_GESTURE_PINCH = {"ghost.wl.handle.pointer_gesture.pinch"};
5426# define LOG (&LOG_WL_POINTER_GESTURE_PINCH)
5427
5428static void gesture_pinch_handle_begin(void *data,
5429 zwp_pointer_gesture_pinch_v1 * /*pinch*/,
5430 const uint32_t /*serial*/,
5431 const uint32_t time,
5432 wl_surface * /*surface*/,
5433 const uint32_t fingers)
5434{
5435 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5436 (void)seat->system->ms_from_input_time(time); /* Only update internal time. */
5437
5438 CLOG_DEBUG(LOG, "begin (fingers=%u)", fingers);
5439
5440 /* Reset defaults. */
5442
5443 const GHOST_WindowWayland *win = nullptr;
5444 if (wl_surface *wl_surface_focus = seat->pointer.wl.surface_window) {
5445 win = ghost_wl_surface_user_data(wl_surface_focus);
5446 }
5447
5448 /* NOTE(@ideasman42): Scale factors match Blender's operators & default preferences.
5449 * For these values to work correctly, operator logic will need to be changed not to scale input
5450 * by the region size (as with 3D view zoom) or preference for 3D view orbit sensitivity.
5451 *
5452 * By working "correctly" I mean that a rotation action where the users fingers rotate to
5453 * opposite locations should always rotate the viewport 180d, since users will expect the
5454 * physical location of their fingers to match the viewport.
5455 * Similarly with zoom, the scale value from the pinch action can be mapped to a zoom level
5456 * although unlike rotation, an inexact mapping is less noticeable.
5457 * Users may even prefer the zoom level to be scaled - which could be a preference. */
5458 seat->pointer_gesture_pinch.scale.value = wl_fixed_from_int(1);
5459 /* The value 300 matches a value used in clip & image zoom operators.
5460 * It seems OK for the 3D view too. */
5462 /* The value 5 is used on macOS and roughly maps 1:1 with turntable rotation,
5463 * although preferences can scale the sensitivity (which would be skipped ideally). */
5465
5466 if (win) {
5467 /* NOTE(@ideasman42): Blender's use of trackpad coordinates is inconsistent and needs work.
5468 * This isn't specific to WAYLAND, in practice they tend to work well enough in most cases.
5469 * Some operators scale by the UI scale, some don't.
5470 * Even though the window scale is correct, it doesn't account for the UI scale preference
5471 * (which GHOST doesn't know about).
5472 *
5473 * If support for this were all that was needed it could be handled in GHOST,
5474 * however as the operators are not even using coordinates compatible with each other,
5475 * it would be better to resolve this by passing rotation & zoom levels directly,
5476 * instead of attempting to handle them as cursor coordinates. */
5477 const GWL_WindowScaleParams &scale_params = win->scale_params_get();
5479 scale_params, seat->pointer_gesture_pinch.scale.factor);
5481 scale_params, seat->pointer_gesture_pinch.rotation.factor);
5482 }
5483}
5484
5485static void gesture_pinch_handle_update(void *data,
5486 zwp_pointer_gesture_pinch_v1 * /*pinch*/,
5487 const uint32_t time,
5488 const wl_fixed_t dx,
5489 const wl_fixed_t dy,
5490 const wl_fixed_t scale,
5491 const wl_fixed_t rotation)
5492{
5493 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5494 const uint64_t event_ms = seat->system->ms_from_input_time(time);
5495
5497 "update (dx=%.3f, dy=%.3f, scale=%.3f, rotation=%.3f)",
5498 wl_fixed_to_double(dx),
5499 wl_fixed_to_double(dy),
5500 wl_fixed_to_double(scale),
5501 wl_fixed_to_double(rotation));
5502
5503 GHOST_WindowWayland *win = nullptr;
5504
5505 if (wl_surface *wl_surface_focus = seat->pointer.wl.surface_window) {
5506 win = ghost_wl_surface_user_data(wl_surface_focus);
5507 }
5508
5509 /* Scale defaults to `wl_fixed_from_int(1)` which may change while pinching.
5510 * This needs to be converted to a delta. */
5511 const wl_fixed_t scale_delta = scale - seat->pointer_gesture_pinch.scale.value;
5512 const int scale_as_delta_px = gwl_scaled_fixed_t_add_and_calc_rounded_delta(
5513 &seat->pointer_gesture_pinch.scale, scale_delta);
5514
5515 /* Rotation in degrees, unlike scale this is a delta. */
5516 const int rotation_as_delta_px = gwl_scaled_fixed_t_add_and_calc_rounded_delta(
5517 &seat->pointer_gesture_pinch.rotation, rotation);
5518
5519 if (win) {
5520 const int event_xy[2] = {WL_FIXED_TO_INT_FOR_WINDOW_V2(win, seat->pointer.xy)};
5521 if (scale_as_delta_px) {
5523 std::make_unique<GHOST_EventTrackpad>(event_ms,
5524 win,
5526 event_xy[0],
5527 event_xy[1],
5528 scale_as_delta_px,
5529 0,
5530 false));
5531 }
5532
5533 if (rotation_as_delta_px) {
5535 std::make_unique<GHOST_EventTrackpad>(event_ms,
5536 win,
5538 event_xy[0],
5539 event_xy[1],
5540 rotation_as_delta_px,
5541 0,
5542 false));
5543 }
5544 }
5545}
5546
5547static void gesture_pinch_handle_end(void *data,
5548 zwp_pointer_gesture_pinch_v1 * /*pinch*/,
5549 const uint32_t /*serial*/,
5550 const uint32_t time,
5551 const int32_t cancelled)
5552{
5553 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5554 (void)seat->system->ms_from_input_time(time); /* Only update internal time. */
5555
5556 CLOG_DEBUG(LOG, "end (cancelled=%i)", cancelled);
5557}
5558
5559static const zwp_pointer_gesture_pinch_v1_listener gesture_pinch_listener = {
5560 /*begin*/ gesture_pinch_handle_begin,
5561 /*update*/ gesture_pinch_handle_update,
5562 /*end*/ gesture_pinch_handle_end,
5563};
5564
5565# undef LOG
5566#endif /* ZWP_POINTER_GESTURE_PINCH_V1_INTERFACE */
5567
5569
5570/* -------------------------------------------------------------------- */
5578
5579#ifdef ZWP_POINTER_GESTURE_SWIPE_V1_INTERFACE
5580static CLG_LogRef LOG_WL_POINTER_GESTURE_SWIPE = {"ghost.wl.handle.pointer_gesture.swipe"};
5581# define LOG (&LOG_WL_POINTER_GESTURE_SWIPE)
5582
5583static void gesture_swipe_handle_begin(
5584 void * /*data*/,
5585 zwp_pointer_gesture_swipe_v1 * /*zwp_pointer_gesture_swipe_v1*/,
5586 uint32_t /*serial*/,
5587 uint32_t /*time*/,
5588 wl_surface * /*surface*/,
5589 uint32_t fingers)
5590{
5591 CLOG_DEBUG(LOG, "begin (fingers=%u)", fingers);
5592}
5593
5594static void gesture_swipe_handle_update(
5595 void * /*data*/,
5596 zwp_pointer_gesture_swipe_v1 * /*zwp_pointer_gesture_swipe_v1*/,
5597 uint32_t /*time*/,
5598 wl_fixed_t dx,
5599 wl_fixed_t dy)
5600{
5601 CLOG_DEBUG(LOG, "update (dx=%.3f, dy=%.3f)", wl_fixed_to_double(dx), wl_fixed_to_double(dy));
5602}
5603
5604static void gesture_swipe_handle_end(
5605 void * /*data*/,
5606 zwp_pointer_gesture_swipe_v1 * /*zwp_pointer_gesture_swipe_v1*/,
5607 uint32_t /*serial*/,
5608 uint32_t /*time*/,
5609 int32_t cancelled)
5610{
5611 CLOG_DEBUG(LOG, "end (cancelled=%i)", cancelled);
5612}
5613
5614static const zwp_pointer_gesture_swipe_v1_listener gesture_swipe_listener = {
5615 /*begin*/ gesture_swipe_handle_begin,
5616 /*update*/ gesture_swipe_handle_update,
5617 /*end*/ gesture_swipe_handle_end,
5618};
5619
5620# undef LOG
5621#endif /* ZWP_POINTER_GESTURE_SWIPE_V1_INTERFACE */
5622
5624
5625/* -------------------------------------------------------------------- */
5636
5637static CLG_LogRef LOG_WL_TOUCH = {"ghost.wl.handle.touch"};
5638#define LOG (&LOG_WL_TOUCH)
5639
5640#ifdef WITH_GHOST_CSD
5646static void touch_seat_handle_down_csd_margin(GWL_Seat *seat,
5647 const uint32_t serial,
5648 const uint32_t time,
5649 const int32_t id,
5651 const wl_fixed_t x,
5652 const wl_fixed_t y)
5653{
5654 const uint64_t event_ms = seat->system->ms_from_input_time(time);
5655
5656 gwl_window_csd_margin_focus_set(seat, &seat->touch, serial, wl_surface);
5657 seat->touch.xy[0] = x;
5658 seat->touch.xy[1] = y;
5659
5660 /* Set touch-tracking state. */
5661 seat->touch_state.is_touching = true;
5662 seat->touch_state.down_id = id;
5663 seat->touch_state.motion_pending = true;
5664 seat->touch_state.motion_event_time_ms = event_ms;
5665 seat->touch_state.down_pending = true;
5666 seat->touch_state.down_event_time_ms = event_ms;
5667 seat->touch_state.down_event_serial = serial;
5668}
5669#endif /* WITH_GHOST_CSD */
5670
5671static void touch_seat_handle_down(void *data,
5672 wl_touch * /*touch*/,
5673 const uint32_t serial,
5674 const uint32_t time,
5675 wl_surface *surface,
5676 const int32_t id,
5677 const wl_fixed_t x,
5678 const wl_fixed_t y)
5679{
5680 /* Touching down is equivalent to moving a pointer and holding its left mouse button. */
5681
5682 CLOG_DEBUG(LOG, "down");
5683 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5684
5685#ifdef WITH_GHOST_CSD
5686 if (ghost_wl_surface_own_csd_margin_with_null_check(surface)) {
5687 /* Only track one point at a time. */
5688 if (seat->touch_state.is_touching) {
5689 return;
5690 }
5691 CLOG_DEBUG(LOG, "down (csd margin)");
5692 touch_seat_handle_down_csd_margin(seat, serial, time, id, surface, x, y);
5693 return;
5694 }
5695#endif
5696
5697 /* Null when just destroyed. */
5699 CLOG_DEBUG(LOG, "down (skipped on empty surface)");
5700 return;
5701 }
5702
5703 /* Only track one point at a time.
5704 * At some point *full* touch supported could be. */
5705 if (seat->touch_state.is_touching) {
5706 return;
5707 }
5708
5709 const uint64_t event_ms = seat->system->ms_from_input_time(time);
5710
5711 /* Set generic pointer state. */
5712 seat->touch.xy[0] = x;
5713 seat->touch.xy[1] = y;
5714 seat->touch.serial = serial;
5716
5717 /* Set the active pointer. */
5718 seat->cursor_source_serial = serial;
5719
5720 /* Set touch-tracking state. */
5721 seat->touch_state.is_touching = true;
5722 seat->touch_state.down_id = id;
5723 seat->touch_state.motion_pending = true;
5724 seat->touch_state.motion_event_time_ms = event_ms;
5725 seat->touch_state.down_pending = true;
5726 seat->touch_state.down_event_time_ms = event_ms;
5727 seat->touch_state.down_event_serial = serial;
5728
5729 /* Signal the window manager to update the cursor shape
5730 * into whatever shape it considers correct for the touchscreen's pointer. */
5731 GHOST_WindowWayland *win = ghost_wl_surface_user_data(seat->touch.wl.surface_window);
5732 win->cursor_shape_refresh();
5733}
5734
5736 void *data, wl_touch * /*touch*/, const uint32_t serial, const uint32_t time, const int32_t id)
5737{
5738 CLOG_DEBUG(LOG, "up");
5739 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5740
5741 /* Only track one contact point at a time. */
5742 if (seat->touch_state.down_id != id) {
5743 return;
5744 }
5745
5746 const uint64_t event_ms = seat->system->ms_from_input_time(time);
5747 seat->touch_state.is_touching = false;
5748 seat->touch_state.up_pending = true;
5749 seat->touch_state.up_event_time_ms = event_ms;
5750 seat->touch_state.up_event_serial = serial;
5751}
5752
5753static void touch_seat_handle_motion(void *data,
5754 wl_touch * /*touch*/,
5755 const uint32_t time,
5756 const int32_t id,
5757 const wl_fixed_t x,
5758 const wl_fixed_t y)
5759{
5760 CLOG_DEBUG(LOG, "motion");
5761 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5762
5763 /* Only track one contact point at a time. */
5764 if (seat->touch_state.down_id != id) {
5765 return;
5766 }
5767 if (seat->touch_state.is_touching == false) {
5768 return;
5769 }
5770
5771 const uint64_t event_ms = seat->system->ms_from_input_time(time);
5772 seat->touch.xy[0] = x;
5773 seat->touch.xy[1] = y;
5774
5775 seat->touch_state.motion_event_time_ms = event_ms;
5776 seat->touch_state.motion_pending = true;
5777}
5778
5779#ifdef WITH_GHOST_CSD
5784static void touch_seat_handle_frame_csd_margin(GWL_Seat *seat, wl_surface *wl_surface)
5785{
5786 GHOST_WindowWayland *win = ghost_wl_surface_csd_margin_user_data(wl_surface);
5787
5788 /* Run before the "down" handling so pressing resolves to a border element. */
5789 if (seat->touch_state.motion_pending == true) {
5790 gwl_window_csd_margin_elem_motion(seat, win, seat->touch.xy);
5791
5792 seat->touch_state.motion_pending = false;
5793 seat->touch_state.motion_event_time_ms = 0;
5794 }
5795
5796 if (seat->touch_state.down_pending == true) {
5797 const uint32_t serial = seat->touch_state.down_event_serial;
5798 GHOST_ASSERT(serial != WL_SERIAL_NONE, "Button down events must have a serial");
5799 gwl_window_csd_active_elem_button(
5800 seat, win, GHOST_kButtonMaskLeft, true, serial, seat->touch_state.down_event_time_ms);
5801
5802 seat->touch_state.down_pending = false;
5803 seat->touch_state.down_event_time_ms = 0;
5804 seat->touch_state.down_event_serial = WL_SERIAL_NONE;
5805 }
5806
5807 if (seat->touch_state.up_pending == true) {
5808 const uint32_t serial = seat->touch_state.up_event_serial;
5809 GHOST_ASSERT(serial != WL_SERIAL_NONE, "Button up events must have a serial");
5810 gwl_window_csd_active_elem_button(
5811 seat, win, GHOST_kButtonMaskLeft, false, serial, seat->touch_state.up_event_time_ms);
5812 gwl_window_csd_margin_focus_clear(&seat->touch, wl_surface);
5813
5814 seat->touch_state.up_pending = false;
5815 seat->touch_state.up_event_time_ms = 0;
5816 seat->touch_state.up_event_serial = WL_SERIAL_NONE;
5817 }
5818}
5819#endif /* WITH_GHOST_CSD */
5820
5821static void touch_seat_handle_frame(void *data, wl_touch * /*touch*/)
5822{
5823 CLOG_DEBUG(LOG, "frame");
5824 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5825
5826#ifdef WITH_GHOST_CSD
5827 if (wl_surface *wl_surface_focus = seat->touch.wl.surface_window_csd_margin) {
5828 touch_seat_handle_frame_csd_margin(seat, wl_surface_focus);
5829 return;
5830 }
5831#endif
5832
5833 if (wl_surface *wl_surface_focus = seat->touch.wl.surface_window) {
5834 GHOST_WindowWayland *win = ghost_wl_surface_user_data(wl_surface_focus);
5835
5836 std::unique_ptr<GHOST_Event> touch_events[3];
5837 int touch_events_num = 0;
5838
5839 /* For a finger move, generate a cursor move. */
5840 if (seat->touch_state.motion_pending == true) {
5841 const int event_xy[2] = {WL_FIXED_TO_INT_FOR_WINDOW_V2(win, seat->touch.xy)};
5842 touch_events[touch_events_num++] = std::make_unique<GHOST_EventCursor>(
5843 seat->touch_state.motion_event_time_ms,
5845 win,
5846 UNPACK2(event_xy),
5848
5849#ifdef WITH_GHOST_CSD
5850 if (seat->system->use_window_frame_csd_get()) {
5851 if (gwl_window_csd_active_elem_motion(seat, win, event_xy)) {
5852 /* Already handled. */
5853 }
5854 }
5855#endif /* WITH_GHOST_CSD */
5856
5857 seat->touch_state.motion_pending = false;
5858 seat->touch_state.motion_event_time_ms = 0;
5859 }
5860
5861 /* For a finger press, generate left-mouse button press. */
5862 if (seat->touch_state.down_pending == true) {
5864
5865 touch_events[touch_events_num++] = std::make_unique<GHOST_EventButton>(
5866 seat->touch_state.down_event_time_ms,
5868 win,
5871
5872#ifdef WITH_GHOST_CSD
5873 if (seat->system->use_window_frame_csd_get()) {
5874 const uint32_t serial = seat->touch_state.down_event_serial;
5875 GHOST_ASSERT(serial != WL_SERIAL_NONE, "Button down events must have a serial");
5876 gwl_window_csd_active_elem_button(
5877 seat, win, GHOST_kButtonMaskLeft, true, serial, seat->touch_state.down_event_time_ms);
5878 }
5879#endif
5880 seat->touch_state.down_pending = false;
5881 seat->touch_state.down_event_time_ms = 0;
5882 seat->touch_state.down_event_serial = WL_SERIAL_NONE;
5883 }
5884
5885 /* For a finger release, generate a left-mouse button release. */
5886 if (seat->touch_state.up_pending == true) {
5887 seat->touch.buttons.set(GHOST_kButtonMaskLeft, false);
5888
5889 touch_events[touch_events_num++] = std::make_unique<GHOST_EventButton>(
5890 seat->touch_state.up_event_time_ms,
5892 win,
5895#ifdef WITH_GHOST_CSD
5896 if (seat->system->use_window_frame_csd_get()) {
5897 const uint32_t serial = seat->touch_state.up_event_serial;
5898 GHOST_ASSERT(serial != WL_SERIAL_NONE, "Button up events must have a serial");
5899 gwl_window_csd_active_elem_button(
5900 seat, win, GHOST_kButtonMaskLeft, false, serial, seat->touch_state.up_event_time_ms);
5901 }
5902#endif
5903 seat->touch_state.up_pending = false;
5904 seat->touch_state.up_event_time_ms = 0;
5905 seat->touch_state.up_event_serial = WL_SERIAL_NONE;
5906 seat->touch.wl.surface_window = nullptr;
5907 }
5908
5909 GHOST_ASSERT(touch_events_num <= ARRAY_SIZE(touch_events), "Buffer overflow");
5910
5911 /* Ensure events are ordered in time. */
5912 if (touch_events_num > 1) [[unlikely]] {
5913 std::ranges::sort(std::span(touch_events, touch_events_num),
5914 [](const std::unique_ptr<GHOST_Event> &event_a,
5915 const std::unique_ptr<GHOST_Event> &event_b) {
5916 return event_a->getTime() < event_b->getTime();
5917 });
5918 }
5919
5920 for (int i = 0; i < touch_events_num; i++) {
5921 seat->system->pushEvent_maybe_pending(std::move(touch_events[i]));
5922 }
5923 }
5924}
5925
5926static void touch_seat_handle_cancel(void *data, wl_touch * /*wl_touch*/)
5927{
5928 CLOG_DEBUG(LOG, "cancel");
5929
5930#ifdef WITH_GHOST_CSD
5931 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
5932 /* Starting a border resize cancels the touch (no further events arrive),
5933 * reset tracking so new contact points aren't ignored.
5934 * Cancellation with a window surface focused is left as-is,
5935 * it would involve generating a button release for the window. */
5936 if (wl_surface *wl_surface_focus = seat->touch.wl.surface_window_csd_margin) {
5937 gwl_window_csd_margin_focus_clear(&seat->touch, wl_surface_focus);
5938 seat->touch_state = {};
5939 }
5940#else
5941 (void)data;
5942#endif
5943}
5944
5945static void touch_seat_handle_shape(void * /*data*/,
5946 wl_touch * /*touch*/,
5947 const int32_t /*id*/,
5948 const wl_fixed_t /*major*/,
5949 const wl_fixed_t /*minor*/)
5950{
5951 CLOG_DEBUG(LOG, "shape");
5952}
5953
5954static void touch_seat_handle_orientation(void * /*data*/,
5955 wl_touch * /*touch*/,
5956 const int32_t /*id*/,
5957 const wl_fixed_t /*orientation*/)
5958{
5959 CLOG_DEBUG(LOG, "orientation");
5960}
5961
5962static const wl_touch_listener touch_seat_listener = {
5963 /*down*/ touch_seat_handle_down,
5964 /*up*/ touch_seat_handle_up,
5965 /*motion*/ touch_seat_handle_motion,
5966 /*frame*/ touch_seat_handle_frame,
5967 /*cancel*/ touch_seat_handle_cancel,
5968 /*shape*/ touch_seat_handle_shape,
5969 /*orientation*/ touch_seat_handle_orientation,
5970};
5971
5972#undef LOG
5973
5975
5976/* -------------------------------------------------------------------- */
5979
5980static CLG_LogRef LOG_WL_TABLET_TOOL = {"ghost.wl.handle.tablet_tool"};
5981#define LOG (&LOG_WL_TABLET_TOOL)
5982
5983static void tablet_tool_handle_type(void *data,
5984 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
5985 const uint32_t tool_type)
5986{
5987 CLOG_DEBUG(LOG, "type (type=%u)", tool_type);
5988
5989 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
5990
5991 tablet_tool->data.Active = tablet_tool_map_type((enum zwp_tablet_tool_v2_type)tool_type);
5992}
5993
5994static void tablet_tool_handle_hardware_serial(void * /*data*/,
5995 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
5996 const uint32_t /*hardware_serial_hi*/,
5997 const uint32_t /*hardware_serial_lo*/)
5998{
5999 CLOG_DEBUG(LOG, "hardware_serial");
6000}
6001
6002static void tablet_tool_handle_hardware_id_wacom(void * /*data*/,
6003 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6004 const uint32_t /*hardware_id_hi*/,
6005 const uint32_t /*hardware_id_lo*/)
6006{
6007 CLOG_DEBUG(LOG, "hardware_id_wacom");
6008}
6009
6010static void tablet_tool_handle_capability(void * /*data*/,
6011 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6012 const uint32_t capability)
6013{
6015 "capability (tilt=%d, distance=%d, rotation=%d, slider=%d, wheel=%d)",
6016 (capability & ZWP_TABLET_TOOL_V2_CAPABILITY_TILT) != 0,
6017 (capability & ZWP_TABLET_TOOL_V2_CAPABILITY_DISTANCE) != 0,
6018 (capability & ZWP_TABLET_TOOL_V2_CAPABILITY_ROTATION) != 0,
6019 (capability & ZWP_TABLET_TOOL_V2_CAPABILITY_SLIDER) != 0,
6020 (capability & ZWP_TABLET_TOOL_V2_CAPABILITY_WHEEL) != 0);
6021}
6022
6023static void tablet_tool_handle_done(void * /*data*/, zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/)
6024{
6025 CLOG_DEBUG(LOG, "done");
6026}
6027static void tablet_tool_handle_removed(void *data, zwp_tablet_tool_v2 *zwp_tablet_tool_v2)
6028{
6029 CLOG_DEBUG(LOG, "removed");
6030
6031 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6032 GWL_Seat *seat = tablet_tool->seat;
6033
6034 if (tablet_tool->wl.surface_cursor) {
6035 wl_surface_destroy(tablet_tool->wl.surface_cursor);
6036 }
6037 if (tablet_tool->shape.device) {
6038 wp_cursor_shape_device_v1_destroy(tablet_tool->shape.device);
6039 }
6040 seat->wp.tablet_tools.erase(zwp_tablet_tool_v2);
6041
6042 delete tablet_tool;
6043}
6044#ifdef WITH_GHOST_CSD
6050static void tablet_tool_handle_proximity_in_csd_margin(GWL_TabletTool *tablet_tool,
6051 const uint32_t serial,
6053{
6054 GWL_Seat *seat = tablet_tool->seat;
6055
6056 tablet_tool->proximity = true;
6057 tablet_tool->serial = serial;
6058
6059 gwl_window_csd_margin_focus_set(seat, &seat->tablet, serial, wl_surface);
6060
6061 seat->data_source_serial = serial;
6062}
6063#endif /* WITH_GHOST_CSD */
6064
6065static void tablet_tool_handle_proximity_in(void *data,
6066 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6067 const uint32_t serial,
6068 zwp_tablet_v2 * /*tablet*/,
6070{
6071 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6072
6073#ifdef WITH_GHOST_CSD
6074 if (ghost_wl_surface_own_csd_margin_with_null_check(wl_surface)) {
6075 CLOG_DEBUG(LOG, "proximity_in (csd margin)");
6076 tablet_tool_handle_proximity_in_csd_margin(tablet_tool, serial, wl_surface);
6077 return;
6078 }
6079#endif
6080
6082 CLOG_DEBUG(LOG, "proximity_in (skipped)");
6083 return;
6084 }
6085 CLOG_DEBUG(LOG, "proximity_in");
6086
6087 tablet_tool->proximity = true;
6088 tablet_tool->serial = serial;
6089
6090 GWL_Seat *seat = tablet_tool->seat;
6091 seat->cursor_source_serial = serial;
6093 seat->tablet.serial = serial;
6094
6095 seat->data_source_serial = serial;
6096
6097 seat->system->seat_active_set(seat);
6098
6099 GHOST_WindowWayland *win = ghost_wl_surface_user_data(seat->tablet.wl.surface_window);
6100 win->cursor_shape_refresh();
6101
6102 /* Update #GHOST_TabletData. */
6103 GHOST_TabletData &td = tablet_tool->data;
6104 /* Reset, to avoid using stale tilt/pressure. */
6105 td.Xtilt = 0.0f;
6106 td.Ytilt = 0.0f;
6107 /* In case pressure isn't supported. */
6108 td.Pressure = 1.0f;
6109}
6111 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/)
6112{
6113 CLOG_DEBUG(LOG, "proximity_out");
6114 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6115 /* Defer clearing the wl_surface until the frame is handled.
6116 * Without this, the frame can not access the wl_surface. */
6117 tablet_tool->proximity = false;
6118 tablet_tool->serial = 0;
6119}
6120
6121static void tablet_tool_handle_down(void *data,
6122 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6123 const uint32_t serial)
6124{
6125 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6126 GWL_Seat *seat = tablet_tool->seat;
6127
6128 CLOG_DEBUG(LOG, "down");
6129
6130 seat->data_source_serial = serial;
6131
6133}
6134
6135static void tablet_tool_handle_up(void *data, zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/)
6136{
6137 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6138
6139 CLOG_DEBUG(LOG, "up");
6140
6143}
6144
6145static void tablet_tool_handle_motion(void *data,
6146 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6147 const wl_fixed_t x,
6148 const wl_fixed_t y)
6149{
6150 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6151
6152 CLOG_DEBUG(LOG, "motion");
6153
6154 tablet_tool->xy[0] = x;
6155 tablet_tool->xy[1] = y;
6156 tablet_tool->has_xy = true;
6157
6159}
6160
6161static void tablet_tool_handle_pressure(void *data,
6162 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6163 const uint32_t pressure)
6164{
6165 const float pressure_unit = float(pressure) / 65535;
6166 CLOG_DEBUG(LOG, "pressure (%.4f)", pressure_unit);
6167
6168 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6169 GHOST_TabletData &td = tablet_tool->data;
6170 td.Pressure = pressure_unit;
6171
6174}
6175
6176static void tablet_tool_handle_distance(void * /*data*/,
6177 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6178 const uint32_t distance)
6179{
6180 CLOG_DEBUG(LOG, "distance (distance=%u)", distance);
6181}
6182
6183static void tablet_tool_handle_tilt(void *data,
6184 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6185 const wl_fixed_t tilt_x,
6186 const wl_fixed_t tilt_y)
6187{
6188 /* Map X tilt to `-1.0 (left)..1.0 (right)`.
6189 * Map Y tilt to `-1.0 (away from user)..1.0 (toward user)`. */
6190 const float tilt_unit[2] = {
6191 float(wl_fixed_to_double(tilt_x) / 90.0f),
6192 float(wl_fixed_to_double(tilt_y) / 90.0f),
6193 };
6194 CLOG_DEBUG(LOG, "tilt (x=%.4f, y=%.4f)", UNPACK2(tilt_unit));
6195 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6196 GHOST_TabletData &td = tablet_tool->data;
6197 td.Xtilt = std::clamp(tilt_unit[0], -1.0f, 1.0f);
6198 td.Ytilt = std::clamp(tilt_unit[1], -1.0f, 1.0f);
6199
6201}
6202
6203static void tablet_tool_handle_rotation(void * /*data*/,
6204 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6205 const wl_fixed_t degrees)
6206{
6207 CLOG_DEBUG(LOG, "rotation (degrees=%.4f)", wl_fixed_to_double(degrees));
6208}
6209
6210static void tablet_tool_handle_slider(void * /*data*/,
6211 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6212 const int32_t position)
6213{
6214 CLOG_DEBUG(LOG, "slider (position=%d)", position);
6215}
6216static void tablet_tool_handle_wheel(void *data,
6217 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6218 const wl_fixed_t /*degrees*/,
6219 const int32_t clicks)
6220{
6221 if (clicks == 0) {
6222 return;
6223 }
6224
6225 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6226
6227 CLOG_DEBUG(LOG, "wheel (clicks=%d)", clicks);
6228
6229 tablet_tool->frame_pending.wheel.clicks = clicks;
6230
6232}
6233
6234static void tablet_tool_handle_button(void *data,
6235 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6236 const uint32_t serial,
6237 const uint32_t button,
6238 const uint32_t state)
6239{
6240 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6241 GWL_Seat *seat = tablet_tool->seat;
6242
6243 CLOG_DEBUG(LOG, "button (button=%u, state=%u)", button, state);
6244
6245 bool is_press = false;
6246 switch (state) {
6247 case WL_POINTER_BUTTON_STATE_RELEASED: {
6248 is_press = false;
6249 break;
6250 }
6251 case WL_POINTER_BUTTON_STATE_PRESSED: {
6252 is_press = true;
6253 break;
6254 }
6255 }
6256
6257 seat->data_source_serial = serial;
6258
6260 switch (button) {
6261 case BTN_STYLUS: {
6264 break;
6265 }
6266 case BTN_STYLUS2: {
6269 break;
6270 }
6271 case BTN_STYLUS3: {
6274 break;
6275 }
6276 }
6277
6279 gwl_tablet_tool_frame_event_add(tablet_tool, ty, serial);
6280 }
6281}
6282#ifdef WITH_GHOST_CSD
6288static void tablet_tool_handle_frame_csd_margin(GWL_TabletTool *tablet_tool,
6290 const uint64_t event_ms)
6291{
6292 GWL_Seat *seat = tablet_tool->seat;
6293 GHOST_WindowWayland *win = ghost_wl_surface_csd_margin_user_data(wl_surface);
6294
6295 for (int ty_index = 0; ty_index < tablet_tool->frame_pending.frame_types_num; ty_index++) {
6296 const GWL_TabletTool_EventTypes ty = tablet_tool->frame_pending.frame_types[ty_index];
6297 const uint32_t serial = tablet_tool->frame_pending.frame_serial[ty_index];
6298 switch (ty) {
6299 using enum GWL_TabletTool_EventTypes;
6300 case Motion: {
6301 /* Can happen when there is pressure/tilt without motion. */
6302 if (tablet_tool->has_xy == false) {
6303 break;
6304 }
6305 seat->tablet.xy[0] = tablet_tool->xy[0];
6306 seat->tablet.xy[1] = tablet_tool->xy[1];
6307
6308 gwl_window_csd_margin_elem_motion(seat, win, tablet_tool->xy);
6309 break;
6310 }
6311 case Pressure:
6312 case Tilt:
6313 case Wheel: {
6314 break;
6315 }
6316# ifdef NDEBUG
6317 default:
6318# else /* Warn when any events aren't handled (in debug builds). */
6319 case Stylus0_Down:
6320 case Stylus0_Up:
6321 case Stylus1_Down:
6322 case Stylus1_Up:
6323 case Stylus2_Down:
6324 case Stylus2_Up:
6325 case Stylus3_Down:
6326 case Stylus3_Up:
6327# endif
6328 {
6329 const int button_enum_offset = int(ty) - int(Stylus0_Down);
6330 const int button_index = button_enum_offset / 2;
6331 const bool button_down = (button_index * 2) == button_enum_offset;
6332 const GHOST_TButton ebutton = gwl_tablet_tool_ebutton[button_index];
6333 GHOST_ASSERT(serial != WL_SERIAL_NONE || !button_down,
6334 "Button down events must have a serial");
6335 gwl_window_csd_active_elem_button(seat, win, ebutton, button_down, serial, event_ms);
6336 break;
6337 }
6338 }
6339 }
6340}
6341#endif /* WITH_GHOST_CSD */
6342
6343static void tablet_tool_handle_frame(void *data,
6344 zwp_tablet_tool_v2 * /*zwp_tablet_tool_v2*/,
6345 const uint32_t time)
6346{
6347 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(data);
6348 GWL_Seat *seat = tablet_tool->seat;
6349 const uint64_t event_ms = seat->system->ms_from_input_time(time);
6350
6351 CLOG_DEBUG(LOG, "frame");
6352
6353#ifdef WITH_GHOST_CSD
6354 if (wl_surface *wl_surface_focus = seat->tablet.wl.surface_window_csd_margin) {
6355 tablet_tool_handle_frame_csd_margin(tablet_tool, wl_surface_focus, event_ms);
6356 if (tablet_tool->proximity == false) {
6357 gwl_window_csd_margin_focus_clear(&seat->tablet, wl_surface_focus);
6358 }
6360 return;
6361 }
6362#endif
6363
6364 /* No need to check the surfaces origin, it's already known to be owned by GHOST. */
6365 if (wl_surface *wl_surface_focus = seat->tablet.wl.surface_window) {
6366 GHOST_WindowWayland *win = ghost_wl_surface_user_data(wl_surface_focus);
6367 bool has_motion = false;
6368
6369 for (int ty_index = 0; ty_index < tablet_tool->frame_pending.frame_types_num; ty_index++) {
6370 const GWL_TabletTool_EventTypes ty = tablet_tool->frame_pending.frame_types[ty_index];
6371#ifdef WITH_GHOST_CSD
6372 const uint32_t serial = tablet_tool->frame_pending.frame_serial[ty_index];
6373#endif
6374 switch (ty) {
6375 using enum GWL_TabletTool_EventTypes;
6376 /* Use motion for pressure and tilt as there are no explicit event types for these. */
6377 case Motion:
6378 case Pressure:
6379 case Tilt: {
6380 /* Only one motion event per frame. */
6381 if (has_motion) {
6382 break;
6383 }
6384 /* Can happen when there is pressure/tilt without motion. */
6385 if (tablet_tool->has_xy == false) {
6386 break;
6387 }
6388
6389 seat->tablet.xy[0] = tablet_tool->xy[0];
6390 seat->tablet.xy[1] = tablet_tool->xy[1];
6391
6392 const int event_xy[2] = {WL_FIXED_TO_INT_FOR_WINDOW_V2(win, tablet_tool->xy)};
6393 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventCursor>(
6394 event_ms, GHOST_kEventCursorMove, win, UNPACK2(event_xy), tablet_tool->data));
6395 has_motion = true;
6396
6397#ifdef WITH_GHOST_CSD
6398 if (seat->system->use_window_frame_csd_get()) {
6399 if (gwl_window_csd_active_elem_motion(seat, win, event_xy)) {
6400 /* Already handled. */
6401 }
6402 }
6403#endif /* WITH_GHOST_CSD */
6404 break;
6405 }
6406#ifdef NDEBUG
6407 default:
6408#else /* Warn when any events aren't handled (in debug builds). */
6409 case Stylus0_Down:
6410 case Stylus0_Up:
6411 case Stylus1_Down:
6412 case Stylus1_Up:
6413 case Stylus2_Down:
6414 case Stylus2_Up:
6415 case Stylus3_Down:
6416 case Stylus3_Up:
6417#endif
6418 {
6419 const int button_enum_offset = int(ty) - int(Stylus0_Down);
6420 const int button_index = button_enum_offset / 2;
6421 const bool button_down = (button_index * 2) == button_enum_offset;
6422 const GHOST_TButton ebutton = gwl_tablet_tool_ebutton[button_index];
6423 const GHOST_TEventType etype = button_down ? GHOST_kEventButtonDown :
6425 seat->tablet.buttons.set(ebutton, button_down);
6426 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventButton>(
6427 event_ms, etype, win, ebutton, tablet_tool->data));
6428
6429#ifdef WITH_GHOST_CSD
6430 GHOST_ASSERT(serial != WL_SERIAL_NONE || !button_down,
6431 "Button down events must have a serial");
6432 if (seat->system->use_window_frame_csd_get()) {
6433 gwl_window_csd_active_elem_button(seat, win, ebutton, button_down, serial, event_ms);
6434 }
6435#endif
6436 break;
6437 }
6438 case Wheel: {
6440 std::make_unique<GHOST_EventWheel>(event_ms,
6441 win,
6443 -tablet_tool->frame_pending.wheel.clicks));
6444 break;
6445 }
6446 }
6447 }
6448
6449 if (tablet_tool->proximity == false) {
6450 win->cursor_shape_refresh();
6451 }
6452 }
6453
6454 if (tablet_tool->proximity == false) {
6455 seat->tablet.wl.surface_window = nullptr;
6456 }
6457
6459}
6460
6461static const zwp_tablet_tool_v2_listener tablet_tool_listener = {
6462 /*type*/ tablet_tool_handle_type,
6463 /*hardware_serial*/ tablet_tool_handle_hardware_serial,
6464 /*hardware_id_wacom*/ tablet_tool_handle_hardware_id_wacom,
6465 /*capability*/ tablet_tool_handle_capability,
6466 /*done*/ tablet_tool_handle_done,
6467 /*removed*/ tablet_tool_handle_removed,
6468 /*proximity_in*/ tablet_tool_handle_proximity_in,
6469 /*proximity_out*/ tablet_tool_handle_proximity_out,
6470 /*down*/ tablet_tool_handle_down,
6471 /*up*/ tablet_tool_handle_up,
6472 /*motion*/ tablet_tool_handle_motion,
6473 /*pressure*/ tablet_tool_handle_pressure,
6474 /*distance*/ tablet_tool_handle_distance,
6475 /*tilt*/ tablet_tool_handle_tilt,
6476 /*rotation*/ tablet_tool_handle_rotation,
6477 /*slider*/ tablet_tool_handle_slider,
6478 /*wheel*/ tablet_tool_handle_wheel,
6479 /*button*/ tablet_tool_handle_button,
6480 /*frame*/ tablet_tool_handle_frame,
6481};
6482
6483#undef LOG
6484
6486
6487/* -------------------------------------------------------------------- */
6490
6491static CLG_LogRef LOG_WL_TABLET_SEAT = {"ghost.wl.handle.tablet_seat"};
6492#define LOG (&LOG_WL_TABLET_SEAT)
6493
6494static void tablet_seat_handle_tablet_added(void * /*data*/,
6495 zwp_tablet_seat_v2 * /*zwp_tablet_seat_v2*/,
6496 zwp_tablet_v2 *id)
6497{
6498 CLOG_DEBUG(LOG, "tablet_added (id=%p)", id);
6499}
6500
6501static void tablet_seat_handle_tool_added(void *data,
6502 zwp_tablet_seat_v2 * /*zwp_tablet_seat_v2*/,
6503 zwp_tablet_tool_v2 *id)
6504{
6505 CLOG_DEBUG(LOG, "tool_added (id=%p)", id);
6506
6507 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
6508 GWL_TabletTool *tablet_tool = new GWL_TabletTool();
6509 tablet_tool->seat = seat;
6510
6511 /* Every tool has its own cursor wl_surface. */
6512 tablet_tool->wl.surface_cursor = wl_compositor_create_surface(seat->system->wl_compositor_get());
6513 ghost_wl_surface_tag_cursor_tablet(tablet_tool->wl.surface_cursor);
6514
6515 wl_surface_add_listener(
6516 tablet_tool->wl.surface_cursor, &cursor_surface_listener, static_cast<void *>(seat));
6517
6518 zwp_tablet_tool_v2_add_listener(id, &tablet_tool_listener, tablet_tool);
6519
6520 seat->wp.tablet_tools.insert(id);
6521}
6522
6523static void tablet_seat_handle_pad_added(void * /*data*/,
6524 zwp_tablet_seat_v2 * /*zwp_tablet_seat_v2*/,
6525 zwp_tablet_pad_v2 *id)
6526{
6527 CLOG_DEBUG(LOG, "pad_added (id=%p)", id);
6528}
6529
6530static const zwp_tablet_seat_v2_listener tablet_seat_listener = {
6531 /*tablet_added*/ tablet_seat_handle_tablet_added,
6532 /*tool_added*/ tablet_seat_handle_tool_added,
6533 /*pad_added*/ tablet_seat_handle_pad_added,
6534};
6535
6536#undef LOG
6537
6539
6540/* -------------------------------------------------------------------- */
6543
6544static CLG_LogRef LOG_WL_KEYBOARD = {"ghost.wl.handle.keyboard"};
6545#define LOG (&LOG_WL_KEYBOARD)
6546
6547static void keyboard_handle_keymap(void *data,
6548 wl_keyboard * /*wl_keyboard*/,
6549 const uint32_t format,
6550 const int32_t fd,
6551 const uint32_t size)
6552{
6553 if ((!data) || (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1)) {
6554 CLOG_DEBUG(LOG, "keymap (no data or wrong version)");
6555 close(fd);
6556 return;
6557 }
6558
6559 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
6560
6561 char *map_str = static_cast<char *>(mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0));
6562 if (map_str == MAP_FAILED) {
6563 close(fd);
6564 CLOG_DEBUG(LOG, "keymap mmap failed: %s", std::strerror(errno));
6565 return;
6566 }
6567
6568 xkb_keymap *keymap = xkb_keymap_new_from_string(
6569 seat->xkb.context, map_str, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
6570 munmap(map_str, size);
6571 close(fd);
6572
6573 if (!keymap) {
6574 CLOG_DEBUG(LOG, "keymap (not found)");
6575 return;
6576 }
6577
6578 CLOG_DEBUG(LOG, "keymap");
6579
6580 /* Reset in case there was a previous non-zero active layout for the last key-map.
6581 * Note that this is set later by `wl_keyboard_listener::modifiers`, it's possible that handling
6582 * the first modifier will run #xkb_state_update_mask again (if the active layout is non-zero)
6583 * however as this is only done when the layout changed, it's harmless.
6584 * With a single layout - in practice the active layout will be zero. */
6585 seat->xkb.layout_active = 0;
6586
6587 if (seat->xkb.compose_state) {
6588 xkb_compose_state_reset(seat->xkb.compose_state);
6589 }
6590 else if (seat->xkb.compose_table) {
6591 seat->xkb.compose_state = xkb_compose_state_new(seat->xkb.compose_table,
6592 XKB_COMPOSE_STATE_NO_FLAGS);
6593 }
6594
6595 /* In practice we can assume `xkb_state_new` always succeeds. */
6596 xkb_state_unref(seat->xkb.state);
6597 seat->xkb.state = xkb_state_new(keymap);
6598
6599 xkb_state_unref(seat->xkb.state_empty);
6600 seat->xkb.state_empty = xkb_state_new(keymap);
6601
6602 for (int i = 0; i < MOD_INDEX_NUM; i++) {
6603 const GWL_ModifierInfo &mod_info = g_modifier_info_table[i];
6604 seat->xkb_keymap_mod_index[i] = xkb_keymap_mod_get_index(keymap, mod_info.xkb_id);
6605 }
6606 seat->xkb_keymap_mod_index_mod2 = xkb_keymap_mod_get_index(keymap, XKB_MOD_NAME_NUM);
6607 seat->xkb_keymap_mod_index_numlock = xkb_keymap_mod_get_index(keymap, "NumLock");
6608
6609 xkb_state_unref(seat->xkb.state_empty_with_shift);
6610 seat->xkb.state_empty_with_shift = nullptr;
6611 if (seat->xkb_keymap_mod_index[MOD_INDEX_SHIFT] != XKB_MOD_INVALID) {
6612 seat->xkb.state_empty_with_shift = xkb_state_new(keymap);
6613 }
6614
6615 xkb_state_unref(seat->xkb.state_empty_with_numlock);
6616 seat->xkb.state_empty_with_numlock = nullptr;
6617 if ((seat->xkb_keymap_mod_index_mod2 != XKB_MOD_INVALID) &&
6618 (seat->xkb_keymap_mod_index_numlock != XKB_MOD_INVALID))
6619 {
6620 seat->xkb.state_empty_with_numlock = xkb_state_new(keymap);
6621 }
6622
6624
6626
6627 xkb_keymap_unref(keymap);
6628}
6629
6635static void keyboard_handle_enter(void *data,
6636 wl_keyboard * /*wl_keyboard*/,
6637 const uint32_t serial,
6639 wl_array *keys)
6640{
6641 /* Null when just destroyed. */
6643 CLOG_DEBUG(LOG, "enter (skipped)");
6644 return;
6645 }
6646 CLOG_DEBUG(LOG, "enter");
6647
6648 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
6650
6651 seat->keyboard.serial = serial;
6652 seat->keyboard.wl.surface_window = wl_surface;
6653
6654 seat->system->seat_active_set(seat);
6655
6656 /* If there are any keys held when activating the window,
6657 * modifiers will be compared against the seat state,
6658 * only enabling modifiers that were previously disabled. */
6659 GWL_KeyboardDepressedState key_depressed_prev = seat->key_depressed;
6661
6662 /* Keep track of the last held repeating key, start the repeat timer if one exists. */
6663 struct {
6664 uint32_t key = std::numeric_limits<uint32_t>::max();
6665 xkb_keysym_t sym = 0;
6666 } repeat;
6667
6668 uint32_t *key;
6669 WL_ARRAY_FOR_EACH (key, keys) {
6670 const xkb_keycode_t key_code = *key + EVDEV_OFFSET;
6671 CLOG_DEBUG(LOG, "enter (key_held=%d)", int(key_code));
6672 const xkb_keysym_t sym = xkb_state_key_get_one_sym_with_fallback(
6673 seat->xkb.state, key_code, seat->xkb.layout_fallback);
6674 const GHOST_TKey gkey = xkb_map_gkey_or_scan_code(sym, *key);
6675 if (gkey != GHOST_kKeyUnknown) {
6677 }
6678
6679 if (xkb_keymap_key_repeats(xkb_state_get_keymap(seat->xkb.state), key_code)) {
6680 repeat.key = *key;
6681 repeat.sym = sym;
6682 }
6683 }
6684
6685 /* Caller has no time-stamp, set from system. */
6686 const uint64_t event_ms = seat->system->getMilliSeconds();
6687 keyboard_depressed_state_push_events_from_change(seat, win, event_ms, key_depressed_prev);
6688
6689 if ((repeat.key != std::numeric_limits<uint32_t>::max()) && (seat->key_repeat.rate > 0)) {
6690 /* Since the key has been held, immediately send a press event.
6691 * This also ensures the key will be registered as pressed, see #117896. */
6692#ifdef USE_EVENT_BACKGROUND_THREAD
6693 std::lock_guard lock_timer_guard{*seat->system->timer_mutex};
6694#endif
6695 /* Should have been cleared on leave, set here just in case. */
6696 if (seat->key_repeat.timer) [[unlikely]] {
6698 }
6699
6700 const xkb_keycode_t key_code = repeat.key + EVDEV_OFFSET;
6701 const GHOST_TKey gkey = xkb_map_gkey_or_scan_code(repeat.sym, repeat.key);
6702
6703 GWL_KeyRepeatPlayload *key_repeat_payload = new GWL_KeyRepeatPlayload();
6704 key_repeat_payload->seat = seat;
6705 key_repeat_payload->key_code = key_code;
6706 key_repeat_payload->key_data.gkey = gkey;
6707
6708 gwl_seat_key_repeat_timer_add(seat, gwl_seat_key_repeat_timer_fn, key_repeat_payload, false);
6709 /* Ensure there is a press event on enter so this is known to be held before any mouse
6710 * button events which may use a key-binding that depends on this key being held. */
6712 }
6713}
6714
6720static void keyboard_handle_leave(void *data,
6721 wl_keyboard * /*wl_keyboard*/,
6722 const uint32_t /*serial*/,
6724{
6726 CLOG_DEBUG(LOG, "leave (skipped)");
6727 return;
6728 }
6729 CLOG_DEBUG(LOG, "leave");
6730
6731 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
6732 seat->keyboard.wl.surface_window = nullptr;
6733
6734 {
6735#ifdef USE_EVENT_BACKGROUND_THREAD
6736 std::lock_guard lock_timer_guard{*seat->system->timer_mutex};
6737#endif
6738 /* Losing focus must stop repeating text. */
6739 if (seat->key_repeat.timer) {
6741 }
6742 }
6743}
6744
6750 xkb_state *xkb_state_empty,
6751 xkb_state *xkb_state_empty_with_numlock,
6752 xkb_state *xkb_state_empty_with_shift,
6753 const xkb_layout_index_t layout_fallback,
6754 const bool xkb_use_non_latin_workaround,
6755 const xkb_keycode_t key)
6756{
6757 /* Use an empty keyboard state to access key symbol without modifiers. */
6758 xkb_keysym_t sym = xkb_state_key_get_one_sym(xkb_state_empty, key);
6759
6760 /* NOTE(@ideasman42): Only perform the number-locked lookup as a fallback
6761 * when a number-pad key has been pressed. This is important as some key-maps use number lock
6762 * for switching other layers (in particular `de(neo_qwertz)` turns on layer-4), see: #96170.
6763 * Alternative solutions could be to inspect the layout however this could get involved
6764 * and turning on the number-lock is only needed for a limited set of keys. */
6765
6766 /* Accounts for key-pad keys typically swapped for numbers when number-lock is enabled:
6767 * `Home Left Up Right Down Prior Page_Up Next Page_Dow End Begin Insert Delete`. */
6768 if (sym >= XKB_KEY_KP_Home && sym <= XKB_KEY_KP_Delete) {
6769 if (xkb_state_empty_with_numlock) {
6770 const xkb_keysym_t sym_test = xkb_state_key_get_one_sym(xkb_state_empty_with_numlock, key);
6771 if (sym_test != XKB_KEY_NoSymbol) {
6772 sym = sym_test;
6773 }
6774 }
6775 }
6776 else {
6777#ifdef USE_NON_LATIN_KB_WORKAROUND
6778 if (key >= (KEY_1 + EVDEV_OFFSET) && key <= (KEY_0 + EVDEV_OFFSET)) {
6779 if (xkb_state_empty_with_shift && xkb_use_non_latin_workaround) {
6780 const xkb_keysym_t sym_test = xkb_state_key_get_one_sym(xkb_state_empty_with_shift, key);
6781 if (sym_test != XKB_KEY_NoSymbol) {
6782 /* Should never happen as enabling `xkb_use_non_latin_workaround` checks this. */
6783 GHOST_ASSERT(sym_test >= XKB_KEY_0 && sym_test <= XKB_KEY_9, "Unexpected key");
6784 sym = sym_test;
6785 }
6786 }
6787 }
6788#else
6789 (void)xkb_state_empty_with_shift;
6790 (void)xkb_use_non_latin_workaround;
6791#endif
6792 }
6793
6794 /* Layout fall-back follows the number-pad and #USE_NON_LATIN_KB_WORKAROUND handling so
6795 * those operate on the un-substituted active-layout `sym` (required for non-Latin layouts). */
6797 sym, xkb_state_get_keymap(xkb_state_empty), key, layout_fallback);
6798}
6799
6801 xkb_compose_state *compose_state,
6802 xkb_state *state,
6803 const xkb_keycode_t key,
6804 char r_utf8_buf[sizeof(GHOST_TEventKeyData::utf8_buf)])
6805{
6806 const xkb_keysym_t sym = xkb_state_key_get_one_sym(state, key);
6807 const xkb_compose_feed_result result = xkb_compose_state_feed(compose_state, sym);
6808 bool handled = false;
6809
6810 if (result == XKB_COMPOSE_FEED_ACCEPTED) {
6811 switch (xkb_compose_state_get_status(compose_state)) {
6812 case XKB_COMPOSE_NOTHING: {
6813 break;
6814 }
6815 case XKB_COMPOSE_COMPOSING: {
6816 r_utf8_buf[0] = '\0';
6817 handled = true;
6818 break;
6819 }
6820 case XKB_COMPOSE_COMPOSED: {
6821 char utf8_buf_compose[sizeof(GHOST_TEventKeyData::utf8_buf) + 1] = {'\0'};
6822 const int utf8_buf_compose_len = xkb_compose_state_get_utf8(
6823 compose_state, utf8_buf_compose, sizeof(utf8_buf_compose));
6824 if (utf8_buf_compose_len > 0) {
6825 if (utf8_buf_compose_len > sizeof(GHOST_TEventKeyData::utf8_buf)) {
6826 /* TODO(@ideasman42): keyboard events in GHOST only support a single character.
6827 *
6828 * - In the case XKB compose enters multiple code-points only the first will be used.
6829 *
6830 * - Besides supporting multiple characters per key input,
6831 * one possible solution would be to generate an IME event.
6832 *
6833 * - In practice I'm not sure how common these are.
6834 * So far no bugs have been reported about this.
6835 */
6836 CLOG_WARN(LOG, "key (compose_size=%d) exceeds the maximum size", utf8_buf_compose_len);
6837 }
6838 memcpy(r_utf8_buf, utf8_buf_compose, sizeof(GHOST_TEventKeyData::utf8_buf));
6839 handled = true;
6840 }
6841 break;
6842 }
6843 case XKB_COMPOSE_CANCELLED: {
6844 /* NOTE(@ideasman42): QT & GTK ignore these events as well as not inputting any text
6845 * so `<Compose><Backspace>` for example causes a cancel and *not* back-space.
6846 * This isn't supported under GHOST at the moment.
6847 * The key-event could also be ignored but this means tracking held state of
6848 * keys wont work properly, so don't do any input and pass in the key-symbol. */
6849 r_utf8_buf[0] = '\0';
6850 handled = true;
6851 break;
6852 }
6853 }
6854 }
6855 return handled;
6856}
6857
6862{
6863 GHOST_ASSERT(seat->key_repeat.timer != nullptr, "Caller must check for timer");
6864 delete static_cast<GWL_KeyRepeatPlayload *>(seat->key_repeat.timer->getUserData());
6865
6867}
6868
6876static void keyboard_handle_key_repeat_reset(GWL_Seat *seat, const bool use_delay)
6877{
6878 GHOST_ASSERT(seat->key_repeat.timer != nullptr, "Caller must check for timer");
6879 GHOST_TimerProcPtr key_repeat_fn = seat->key_repeat.timer->getTimerProc();
6880 GHOST_TUserDataPtr payload = seat->key_repeat.timer->getUserData();
6881
6883 gwl_seat_key_repeat_timer_add(seat, key_repeat_fn, payload, use_delay);
6884}
6885
6886static void keyboard_handle_key(void *data,
6887 wl_keyboard * /*wl_keyboard*/,
6888 const uint32_t serial,
6889 const uint32_t time,
6890 const uint32_t key,
6891 const uint32_t state)
6892{
6893 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
6894 const uint64_t event_ms = seat->system->ms_from_input_time(time);
6895
6896 const xkb_keycode_t key_code = key + EVDEV_OFFSET;
6897
6898 const xkb_keysym_t sym = xkb_state_key_get_one_sym_without_modifiers(
6899 seat->xkb.state_empty,
6900 seat->xkb.state_empty_with_numlock,
6901 seat->xkb.state_empty_with_shift,
6902 seat->xkb.layout_fallback,
6905#else
6906 false,
6907#endif
6908 key_code);
6909 if (sym == XKB_KEY_NoSymbol) {
6910 CLOG_DEBUG(LOG, "key (code=%d, state=%u, no symbol, skipped)", int(key_code), state);
6911 return;
6912 }
6913 CLOG_DEBUG(LOG, "key (code=%d, state=%u)", int(key_code), state);
6914
6916 bool is_repeat = false;
6917 switch (state) {
6918 case WL_KEYBOARD_KEY_STATE_RELEASED: {
6919 etype = GHOST_kEventKeyUp;
6920 break;
6921 }
6922#ifdef WL_KEYBOARD_KEY_STATE_REPEATED_SINCE_VERSION
6923 case WL_KEYBOARD_KEY_STATE_REPEATED: {
6924 /* Server side key repeat. */
6925 is_repeat = true;
6926 [[fallthrough]];
6927 }
6928#endif
6929 case WL_KEYBOARD_KEY_STATE_PRESSED: {
6930 etype = GHOST_kEventKeyDown;
6931 break;
6932 }
6933 }
6934
6935#ifdef USE_EVENT_BACKGROUND_THREAD
6936 /* Any access to `seat->key_repeat.timer` must lock. */
6937 std::lock_guard lock_timer_guard{*seat->system->timer_mutex};
6938#endif
6939
6940 GWL_KeyRepeatPlayload *key_repeat_payload = nullptr;
6941
6942 /* Delete previous timer. */
6943 if (seat->key_repeat.timer) {
6944 enum { NOP = 1, RESET, CANCEL } timer_action = NOP;
6945 key_repeat_payload = static_cast<GWL_KeyRepeatPlayload *>(
6946 seat->key_repeat.timer->getUserData());
6947
6948 if (seat->key_repeat.rate == 0) {
6949 /* Repeat was disabled (unlikely but possible). */
6950 timer_action = CANCEL;
6951 }
6952 else if (key_code == key_repeat_payload->key_code) {
6953 /* Releasing the key that was held always cancels. */
6954 timer_action = CANCEL;
6955 }
6956 else if (xkb_keymap_key_repeats(xkb_state_get_keymap(seat->xkb.state), key_code)) {
6957 if (etype == GHOST_kEventKeyDown) {
6958 /* Any other key-down always cancels (and may start its own repeat timer). */
6959 timer_action = CANCEL;
6960 }
6961 else {
6962 /* Key-up from keys that were not repeating cause the repeat timer to pause.
6963 *
6964 * NOTE(@ideasman42): This behavior isn't universal, some text input systems will
6965 * stop the repeat entirely. Choose to pause repeat instead as this is what GTK/WIN32 do,
6966 * and it fits better for keyboard input that isn't related to text entry. */
6967 timer_action = RESET;
6968 }
6969 }
6970
6971 switch (timer_action) {
6972 case NOP: {
6973 /* Don't add a new timer, leave the existing timer owning this `key_repeat_payload`. */
6974 key_repeat_payload = nullptr;
6975 break;
6976 }
6977 case RESET: {
6978 /* The payload will be added again. */
6980 break;
6981 }
6982 case CANCEL: {
6983 delete key_repeat_payload;
6984 key_repeat_payload = nullptr;
6986 break;
6987 }
6988 }
6989 }
6990
6991 const GHOST_TKey gkey = xkb_map_gkey_or_scan_code(sym, key);
6992
6993 char utf8_buf[sizeof(GHOST_TEventKeyData::utf8_buf)] = {'\0'};
6994 if (etype == GHOST_kEventKeyDown) {
6995 /* Handle key-compose (dead-keys). */
6996 if (seat->xkb.compose_state &&
6998 seat->xkb.compose_state, seat->xkb.state, key_code, utf8_buf))
6999 {
7000 /* `utf8_buf` has been filled by a compose action. */
7001 }
7002 else {
7003 xkb_state_key_get_utf8(seat->xkb.state, key_code, utf8_buf, sizeof(utf8_buf));
7004 }
7005 }
7006
7007 seat->data_source_serial = serial;
7008
7009 keyboard_depressed_state_key_event(seat, gkey, etype);
7010
7011 if (wl_surface *wl_surface_focus = seat->keyboard.wl.surface_window) {
7012 GHOST_IWindow *win = ghost_wl_surface_user_data(wl_surface_focus);
7014 std::make_unique<GHOST_EventKey>(event_ms, etype, win, gkey, is_repeat, utf8_buf));
7015 }
7016
7017 /* An existing payload means the key repeat timer is reset and will be added again. */
7018 if (key_repeat_payload == nullptr) {
7019 /* Start timer for repeating key, if applicable. */
7020 if ((seat->key_repeat.rate > 0) && (etype == GHOST_kEventKeyDown) &&
7021 xkb_keymap_key_repeats(xkb_state_get_keymap(seat->xkb.state), key_code))
7022 {
7023 key_repeat_payload = new GWL_KeyRepeatPlayload();
7024 key_repeat_payload->seat = seat;
7025 key_repeat_payload->key_code = key_code;
7026 key_repeat_payload->key_data.gkey = gkey;
7027 }
7028 }
7029
7030 if (key_repeat_payload) {
7031 gwl_seat_key_repeat_timer_add(seat, gwl_seat_key_repeat_timer_fn, key_repeat_payload, true);
7032 }
7033}
7034
7035static void keyboard_handle_modifiers(void *data,
7036 wl_keyboard * /*wl_keyboard*/,
7037 const uint32_t serial,
7038 const uint32_t mods_depressed,
7039 const uint32_t mods_latched,
7040 const uint32_t mods_locked,
7041 const uint32_t group)
7042{
7044 "modifiers (depressed=%u, latched=%u, locked=%u, group=%u)",
7045 mods_depressed,
7046 mods_latched,
7047 mods_locked,
7048 group);
7049
7050 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
7051 xkb_state_update_mask(seat->xkb.state, mods_depressed, mods_latched, mods_locked, 0, 0, group);
7052
7053 /* Account for the active layout changing within the same key-map,
7054 * needed so modifiers are detected from the expected layout, see: #115160. */
7055 if (group != seat->xkb.layout_active) {
7056 seat->xkb.layout_active = group;
7058 }
7059
7060 /* A modifier changed so reset the timer,
7061 * see comment in #keyboard_handle_key regarding this behavior. */
7062 {
7063#ifdef USE_EVENT_BACKGROUND_THREAD
7064 std::lock_guard lock_timer_guard{*seat->system->timer_mutex};
7065#endif
7066 if (seat->key_repeat.timer) {
7068 }
7069 }
7070
7071 seat->data_source_serial = serial;
7072}
7073
7074static void keyboard_handle_repeat_info(void *data,
7075 wl_keyboard * /*wl_keyboard*/,
7076 const int32_t rate,
7077 const int32_t delay)
7078{
7079 CLOG_DEBUG(LOG, "info (rate=%d, delay=%d)", rate, delay);
7080
7081 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
7082#ifdef USE_EVENT_BACKGROUND_THREAD
7083 std::lock_guard lock_timer_guard{*seat->system->timer_mutex};
7084#endif
7085 seat->key_repeat.rate = rate;
7086 seat->key_repeat.delay = delay;
7087
7088 /* Unlikely possible this setting changes while repeating. */
7089 if (seat->key_repeat.timer) {
7090 if (rate > 0) {
7092 }
7093 else {
7094 /* A zero rate disables. */
7096 }
7097 }
7098}
7099
7100static const wl_keyboard_listener keyboard_listener = {
7101 /*keymap*/ keyboard_handle_keymap,
7102 /*enter*/ keyboard_handle_enter,
7103 /*leave*/ keyboard_handle_leave,
7104 /*key*/ keyboard_handle_key,
7105 /*modifiers*/ keyboard_handle_modifiers,
7106 /*repeat_info*/ keyboard_handle_repeat_info,
7107};
7108
7109#undef LOG
7110
7112
7113/* -------------------------------------------------------------------- */
7116
7117static CLG_LogRef LOG_WL_PRIMARY_SELECTION_OFFER = {"ghost.wl.handle.primary_selection_offer"};
7118#define LOG (&LOG_WL_PRIMARY_SELECTION_OFFER)
7119
7120static void primary_selection_offer_offer(void *data,
7121 zwp_primary_selection_offer_v1 *id,
7122 const char *type)
7123{
7124 /* NOTE: locking isn't needed as the #GWL_DataOffer wont have been assigned to the #GWL_Seat. */
7125 GWL_PrimarySelection_DataOffer *data_offer = static_cast<GWL_PrimarySelection_DataOffer *>(data);
7126 if (data_offer->wp.id != id) {
7127 CLOG_DEBUG(LOG, "offer: %p: offer for unknown selection %p of %s (skipped)", data, id, type);
7128 return;
7129 }
7130
7131 data_offer->types.insert(std::string(type));
7132}
7133
7134static const zwp_primary_selection_offer_v1_listener primary_selection_offer_listener = {
7136};
7137
7138#undef LOG
7139
7141
7142/* -------------------------------------------------------------------- */
7145
7146static CLG_LogRef LOG_WL_PRIMARY_SELECTION_DEVICE = {"ghost.wl.handle.primary_selection_device"};
7147#define LOG (&LOG_WL_PRIMARY_SELECTION_DEVICE)
7148
7150 void * /*data*/,
7151 zwp_primary_selection_device_v1 * /*zwp_primary_selection_device_v1*/,
7152 zwp_primary_selection_offer_v1 *id)
7153{
7154 CLOG_DEBUG(LOG, "data_offer");
7155
7157 data_offer->wp.id = id;
7158 zwp_primary_selection_offer_v1_add_listener(id, &primary_selection_offer_listener, data_offer);
7159}
7160
7162 void *data,
7163 zwp_primary_selection_device_v1 * /*zwp_primary_selection_device_v1*/,
7164 zwp_primary_selection_offer_v1 *id)
7165{
7166 GWL_PrimarySelection *primary = static_cast<GWL_PrimarySelection *>(data);
7167
7168 std::lock_guard lock{primary->data_offer_mutex};
7169
7170 /* Delete old data offer. */
7171 if (primary->data_offer != nullptr) {
7173 }
7174
7175 if (id == nullptr) {
7176 CLOG_DEBUG(LOG, "selection: (skipped)");
7177 return;
7178 }
7179 CLOG_DEBUG(LOG, "selection");
7180 /* Transfer ownership of the `data_offer`. */
7182 zwp_primary_selection_offer_v1_get_user_data(id));
7183 primary->data_offer = data_offer;
7184}
7185
7186static const zwp_primary_selection_device_v1_listener primary_selection_device_listener = {
7189};
7190
7191#undef LOG
7192
7194
7195/* -------------------------------------------------------------------- */
7198
7199static CLG_LogRef LOG_WL_PRIMARY_SELECTION_SOURCE = {"ghost.wl.handle.primary_selection_source"};
7200#define LOG (&LOG_WL_PRIMARY_SELECTION_SOURCE)
7201
7202static void primary_selection_source_send(void *data,
7203 zwp_primary_selection_source_v1 * /*source*/,
7204 const char * /*mime_type*/,
7205 const int32_t fd)
7206{
7207 CLOG_DEBUG(LOG, "send");
7208
7209 GWL_PrimarySelection *primary = static_cast<GWL_PrimarySelection *>(data);
7210
7211 auto write_file_fn = [](GWL_PrimarySelection *primary, const int fd) {
7212 if (write(fd,
7213 primary->data_source->buffer_out.data,
7214 primary->data_source->buffer_out.data_size) < 0) [[unlikely]]
7215 {
7216 CLOG_WARN(LOG, "error writing to primary clipboard: %s", std::strerror(errno));
7217 }
7218 close(fd);
7219 primary->data_source_mutex.unlock();
7220 };
7221
7222 primary->data_source_mutex.lock();
7223 std::thread write_thread(write_file_fn, primary, fd);
7224 write_thread.detach();
7225}
7226
7227static void primary_selection_source_cancelled(void *data, zwp_primary_selection_source_v1 *source)
7228{
7229 CLOG_DEBUG(LOG, "cancelled");
7230
7231 GWL_PrimarySelection *primary = static_cast<GWL_PrimarySelection *>(data);
7232 std::lock_guard lock{primary->data_source_mutex};
7233
7234 if (source == primary->data_source->wp.source) {
7236 }
7237}
7238
7239static const zwp_primary_selection_source_v1_listener primary_selection_source_listener = {
7242};
7243
7244#undef LOG
7245
7247
7248/* -------------------------------------------------------------------- */
7251
7252#ifdef WITH_INPUT_IME
7253
7254class GHOST_EventIME : public GHOST_Event {
7255 protected:
7256 GHOST_TEventImeData event_ime_data;
7257
7258 public:
7266 GHOST_EventIME(uint64_t msec,
7267 GHOST_TEventType type,
7268 GHOST_IWindow *window,
7269 const GHOST_TEventImeData *customdata)
7270 : GHOST_Event(msec, type, window)
7271 {
7272 /* Make sure that we keep a copy of the IME input. Otherwise it might get lost
7273 * because we overwrite it before it can be read in Blender. (See #137346). */
7274 this->event_ime_data = *customdata;
7275 this->data_ = &this->event_ime_data;
7276 }
7277};
7278
7279static CLG_LogRef LOG_WL_TEXT_INPUT = {"ghost.wl.handle.text_input"};
7280# define LOG (&LOG_WL_TEXT_INPUT)
7281
7282static void text_input_handle_enter(void *data,
7283 zwp_text_input_v3 * /*zwp_text_input_v3*/,
7284 wl_surface *surface)
7285{
7286 /* Can be null when closing a window, see: #141777. */
7288 return;
7289 }
7290 CLOG_DEBUG(LOG, "enter");
7291 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
7292 seat->ime.surface_window = surface;
7293 /* If text input is enabled, should call `enable` after receive `enter` event.
7294 * This support switch input method during input, otherwise input method will not work. */
7295 if (seat->ime.is_enabled) {
7296 zwp_text_input_v3_enable(seat->wp.text_input);
7297 zwp_text_input_v3_commit(seat->wp.text_input);
7298 }
7299}
7300
7301static void text_input_handle_leave(void *data,
7302 zwp_text_input_v3 * /*zwp_text_input_v3*/,
7303 wl_surface *surface)
7304{
7305 /* Can be null when closing a window. */
7307 return;
7308 }
7309 CLOG_DEBUG(LOG, "leave");
7310 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
7311 if (seat->ime.surface_window == surface) {
7312 seat->ime.surface_window = nullptr;
7313 }
7314 /* Always call `disable` after receive `leave` event. */
7315 zwp_text_input_v3_disable(seat->wp.text_input);
7316 zwp_text_input_v3_commit(seat->wp.text_input);
7317}
7318
7319static void text_input_handle_preedit_string(void *data,
7320 zwp_text_input_v3 * /*zwp_text_input_v3*/,
7321 const char *text,
7322 const int32_t cursor_begin,
7323 const int32_t cursor_end)
7324{
7326 "preedit_string (text=\"%s\", cursor_begin=%d, cursor_end=%d)",
7327 text ? text : "<null>",
7328 cursor_begin,
7329 cursor_end);
7330
7331 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
7332 if (seat->ime.has_preedit == false) {
7333 /* Starting IME input. */
7334 gwl_seat_ime_full_reset(seat);
7335 }
7336
7337 seat->ime.composite_is_null = (text == nullptr);
7338 if (!seat->ime.composite_is_null) {
7339 seat->ime.event_ime_data.composite = text;
7340
7341 seat->ime.event_ime_data.cursor_position = cursor_begin;
7342 seat->ime.event_ime_data.target_start = cursor_begin;
7343 seat->ime.event_ime_data.target_end = cursor_end;
7344 }
7345
7346 seat->ime.has_preedit_string_callback = true;
7347}
7348
7349static void text_input_handle_commit_string(void *data,
7350 zwp_text_input_v3 * /*zwp_text_input_v3*/,
7351 const char *text)
7352{
7353 CLOG_DEBUG(LOG, "commit_string (text=\"%s\")", text ? text : "<null>");
7354
7355 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
7356 seat->ime.result_is_null = (text == nullptr);
7357 seat->ime.event_ime_data.result = text ? text : "";
7358 seat->ime.event_ime_data.cursor_position = seat->ime.event_ime_data.result.size();
7359
7360 seat->ime.has_commit_string_callback = true;
7361}
7362
7363static void text_input_handle_delete_surrounding_text(void * /*data*/,
7364 zwp_text_input_v3 * /*zwp_text_input_v3*/,
7365 const uint32_t before_length,
7366 const uint32_t after_length)
7367{
7369 "delete_surrounding_text (before_length=%u, after_length=%u)",
7370 before_length,
7371 after_length);
7372
7373 /* NOTE: Currently unused, do we care about this event?
7374 * SDL ignores this event. */
7375}
7376
7377static void text_input_handle_done(void *data,
7378 zwp_text_input_v3 * /*zwp_text_input_v3*/,
7379 const uint32_t /*serial*/)
7380{
7381 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
7382 GHOST_SystemWayland *system = seat->system;
7383 const uint64_t event_ms = seat->system->getMilliSeconds();
7384
7385 CLOG_DEBUG(LOG, "done");
7386
7387 GHOST_WindowWayland *win = seat->ime.surface_window ?
7388 ghost_wl_surface_user_data(seat->ime.surface_window) :
7389 nullptr;
7390 if (seat->ime.has_commit_string_callback) {
7391 if (seat->ime.has_preedit) {
7392 const bool is_end = seat->ime.composite_is_null;
7393 if (is_end) {
7394 seat->ime.has_preedit = false;
7395 /* `commit_string` (end). */
7396 system->pushEvent_maybe_pending(std::make_unique<GHOST_EventIME>(
7397 event_ms, GHOST_kEventImeComposition, win, &seat->ime.event_ime_data));
7398 system->pushEvent_maybe_pending(std::make_unique<GHOST_EventIME>(
7399 event_ms, GHOST_kEventImeCompositionEnd, win, &seat->ime.event_ime_data));
7400 }
7401 else {
7402 /* `commit_string` (continues). */
7403 system->pushEvent_maybe_pending(std::make_unique<GHOST_EventIME>(
7404 event_ms, GHOST_kEventImeComposition, win, &seat->ime.event_ime_data));
7405 }
7406 }
7407 else {
7408 /* `commit_string` ran with no active IME popup, start & end to insert text. */
7409 system->pushEvent_maybe_pending(std::make_unique<GHOST_EventIME>(
7410 event_ms, GHOST_kEventImeCompositionStart, win, &seat->ime.event_ime_data));
7411 system->pushEvent_maybe_pending(std::make_unique<GHOST_EventIME>(
7412 event_ms, GHOST_kEventImeComposition, win, &seat->ime.event_ime_data));
7413 system->pushEvent_maybe_pending(std::make_unique<GHOST_EventIME>(
7414 event_ms, GHOST_kEventImeCompositionEnd, win, &seat->ime.event_ime_data));
7415 }
7416
7417 if (seat->ime.has_preedit == false) {
7418 gwl_seat_ime_preedit_reset(seat);
7419 }
7420 }
7421 else if (seat->ime.has_preedit_string_callback) {
7422 const bool is_end = seat->ime.composite_is_null;
7423 if (is_end) {
7424 /* `preedit_string` (end). */
7425 seat->ime.has_preedit = false;
7426 system->pushEvent_maybe_pending(std::make_unique<GHOST_EventIME>(
7427 event_ms, GHOST_kEventImeCompositionEnd, win, &seat->ime.event_ime_data));
7428 }
7429 else {
7430 const bool is_start = seat->ime.has_preedit == false;
7431 /* `preedit_string` (start or continue). */
7432 seat->ime.has_preedit = true;
7433 system->pushEvent_maybe_pending(std::make_unique<GHOST_EventIME>(
7434 event_ms,
7436 win,
7437 &seat->ime.event_ime_data));
7438 }
7439 }
7440
7441 seat->ime.has_preedit_string_callback = false;
7442 seat->ime.has_commit_string_callback = false;
7443}
7444
7445static zwp_text_input_v3_listener text_input_listener = {
7446 /*enter*/ text_input_handle_enter,
7447 /*leave*/ text_input_handle_leave,
7448 /*preedit_string*/ text_input_handle_preedit_string,
7449 /*commit_string*/ text_input_handle_commit_string,
7450 /*delete_surrounding_text*/ text_input_handle_delete_surrounding_text,
7451 /*done*/ text_input_handle_done,
7452};
7453
7454# undef LOG
7455
7456#endif /* WITH_INPUT_IME. */
7457
7459
7460/* -------------------------------------------------------------------- */
7463
7464static CLG_LogRef LOG_WL_SEAT = {"ghost.wl.handle.seat"};
7465#define LOG (&LOG_WL_SEAT)
7466
7467static bool gwl_seat_capability_pointer_multitouch_check(const GWL_Seat *seat, const bool fallback)
7468{
7469 const zwp_pointer_gestures_v1 *pointer_gestures = seat->system->wp_pointer_gestures_get();
7470 if (pointer_gestures == nullptr) {
7471 return fallback;
7472 }
7473
7474 bool found = false;
7475#ifdef ZWP_POINTER_GESTURE_HOLD_V1_INTERFACE
7476 if (seat->wp.pointer_gesture_hold) {
7477 return true;
7478 }
7479 found = true;
7480#endif
7481#ifdef ZWP_POINTER_GESTURE_PINCH_V1_INTERFACE
7482 if (seat->wp.pointer_gesture_pinch) {
7483 return true;
7484 }
7485 found = true;
7486#endif
7487#ifdef ZWP_POINTER_GESTURE_SWIPE_V1_INTERFACE
7488 if (seat->wp.pointer_gesture_swipe) {
7489 return true;
7490 }
7491 found = true;
7492#endif
7493 if (seat->use_pointer_scroll_smooth_as_discrete == false) {
7494 return true;
7495 }
7496
7497 if (found == false) {
7498 return fallback;
7499 }
7500 return false;
7501}
7502
7504{
7505 /* Smooth to discrete handling. */
7508
7509 zwp_pointer_gestures_v1 *pointer_gestures = seat->system->wp_pointer_gestures_get();
7510 if (pointer_gestures == nullptr) {
7511 return;
7512 }
7513
7514 const uint pointer_gestures_version = zwp_pointer_gestures_v1_get_version(pointer_gestures);
7515#ifdef ZWP_POINTER_GESTURE_HOLD_V1_INTERFACE
7516 if (pointer_gestures_version >= ZWP_POINTER_GESTURES_V1_GET_HOLD_GESTURE_SINCE_VERSION)
7517
7518 { /* Hold gesture. */
7519 zwp_pointer_gesture_hold_v1 *gesture = zwp_pointer_gestures_v1_get_hold_gesture(
7520 pointer_gestures, seat->wl.pointer);
7521 zwp_pointer_gesture_hold_v1_set_user_data(gesture, seat);
7522 zwp_pointer_gesture_hold_v1_add_listener(gesture, &gesture_hold_listener, seat);
7523 seat->wp.pointer_gesture_hold = gesture;
7524 }
7525#endif
7526#ifdef ZWP_POINTER_GESTURE_PINCH_V1_INTERFACE
7527 { /* Pinch gesture. */
7528 zwp_pointer_gesture_pinch_v1 *gesture = zwp_pointer_gestures_v1_get_pinch_gesture(
7529 pointer_gestures, seat->wl.pointer);
7530 zwp_pointer_gesture_pinch_v1_set_user_data(gesture, seat);
7531 zwp_pointer_gesture_pinch_v1_add_listener(gesture, &gesture_pinch_listener, seat);
7532 seat->wp.pointer_gesture_pinch = gesture;
7533 }
7534#endif
7535#ifdef ZWP_POINTER_GESTURE_SWIPE_V1_INTERFACE
7536 { /* Swipe gesture. */
7537 zwp_pointer_gesture_swipe_v1 *gesture = zwp_pointer_gestures_v1_get_swipe_gesture(
7538 pointer_gestures, seat->wl.pointer);
7539 zwp_pointer_gesture_swipe_v1_set_user_data(gesture, seat);
7540 zwp_pointer_gesture_swipe_v1_add_listener(gesture, &gesture_swipe_listener, seat);
7541 seat->wp.pointer_gesture_swipe = gesture;
7542 }
7543#endif
7544}
7545
7547{
7548 /* Smooth to discrete handling. */
7551 seat->pointer_scroll.smooth_xy[0] = 0;
7552 seat->pointer_scroll.smooth_xy[1] = 0;
7553
7554 const zwp_pointer_gestures_v1 *pointer_gestures = seat->system->wp_pointer_gestures_get();
7555 if (pointer_gestures == nullptr) {
7556 return;
7557 }
7558#ifdef ZWP_POINTER_GESTURE_HOLD_V1_INTERFACE
7559 { /* Hold gesture. */
7560 zwp_pointer_gesture_hold_v1 **gesture_p = &seat->wp.pointer_gesture_hold;
7561 if (*gesture_p) {
7562 zwp_pointer_gesture_hold_v1_destroy(*gesture_p);
7563 *gesture_p = nullptr;
7564 }
7565 }
7566#endif
7567#ifdef ZWP_POINTER_GESTURE_PINCH_V1_INTERFACE
7568 { /* Pinch gesture. */
7569 zwp_pointer_gesture_pinch_v1 **gesture_p = &seat->wp.pointer_gesture_pinch;
7570 if (*gesture_p) {
7571 zwp_pointer_gesture_pinch_v1_destroy(*gesture_p);
7572 *gesture_p = nullptr;
7573 }
7574 }
7575#endif
7576#ifdef ZWP_POINTER_GESTURE_SWIPE_V1_INTERFACE
7577 { /* Swipe gesture. */
7578 zwp_pointer_gesture_swipe_v1 **gesture_p = &seat->wp.pointer_gesture_swipe;
7579 if (*gesture_p) {
7580 zwp_pointer_gesture_swipe_v1_destroy(*gesture_p);
7581 *gesture_p = nullptr;
7582 }
7583 }
7584#endif
7585}
7586
7588{
7589 if (seat->wl.pointer) {
7590 return;
7591 }
7592 seat->wl.pointer = wl_seat_get_pointer(seat->wl.seat);
7593 seat->cursor.wl.surface_cursor = wl_compositor_create_surface(seat->system->wl_compositor_get());
7594 seat->cursor.visible = true;
7595 seat->cursor.wl.buffer = nullptr;
7596 wl_pointer_add_listener(seat->wl.pointer, &pointer_listener, seat);
7597
7598 wl_surface_add_listener(seat->cursor.wl.surface_cursor, &cursor_surface_listener, seat);
7599 ghost_wl_surface_tag_cursor_pointer(seat->cursor.wl.surface_cursor);
7600
7602 {
7604
7605 /* TODO: detect this from the system.
7606 * We *could* have weak support based on checking for known themes. */
7607 seat->cursor.use_dark_theme = true;
7608 }
7609}
7610
7612{
7613 if (!seat->wl.pointer) {
7614 return;
7615 }
7616
7617 if (seat->cursor.shape.device) {
7618 wp_cursor_shape_device_v1_destroy(seat->cursor.shape.device);
7619 seat->cursor.shape.device = nullptr;
7620 }
7621
7623
7624 if (seat->cursor.wl.surface_cursor) {
7625 wl_surface_destroy(seat->cursor.wl.surface_cursor);
7626 seat->cursor.wl.surface_cursor = nullptr;
7627 }
7628
7629 wl_pointer_destroy(seat->wl.pointer);
7630 seat->wl.pointer = nullptr;
7631}
7632
7634{
7635 if (seat->wl.keyboard) {
7636 return;
7637 }
7638 seat->wl.keyboard = wl_seat_get_keyboard(seat->wl.seat);
7639 wl_keyboard_add_listener(seat->wl.keyboard, &keyboard_listener, seat);
7640}
7641
7643{
7644 if (!seat->wl.keyboard) {
7645 return;
7646 }
7647
7648 {
7649#ifdef USE_EVENT_BACKGROUND_THREAD
7650 std::lock_guard lock_timer_guard{*seat->system->timer_mutex};
7651#endif
7652 if (seat->key_repeat.timer) {
7654 }
7655 }
7656 wl_keyboard_destroy(seat->wl.keyboard);
7657 seat->wl.keyboard = nullptr;
7658}
7659
7661{
7662 if (seat->wl.touch) {
7663 return;
7664 }
7665 seat->wl.touch = wl_seat_get_touch(seat->wl.seat);
7666 wl_touch_set_user_data(seat->wl.touch, seat);
7667 wl_touch_add_listener(seat->wl.touch, &touch_seat_listener, seat);
7668}
7669
7671{
7672 if (!seat->wl.touch) {
7673 return;
7674 }
7675 wl_touch_destroy(seat->wl.touch);
7676 seat->wl.touch = nullptr;
7677}
7678
7679static void seat_handle_capabilities(void *data,
7680 /* Only used in an assert. */
7681 [[maybe_unused]] wl_seat *wl_seat,
7682 const uint32_t capabilities)
7683{
7685 "capabilities (pointer=%d, keyboard=%d, touch=%d)",
7686 (capabilities & WL_SEAT_CAPABILITY_POINTER) != 0,
7687 (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) != 0,
7688 (capabilities & WL_SEAT_CAPABILITY_TOUCH) != 0);
7689
7690 GWL_Seat *seat = static_cast<GWL_Seat *>(data);
7691 GHOST_ASSERT(seat->wl.seat == wl_seat, "Seat mismatch");
7692
7693 if (capabilities & WL_SEAT_CAPABILITY_POINTER) {
7695 }
7696 else {
7698 }
7699
7700 if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {
7702 }
7703 else {
7705 }
7706
7707 if (capabilities & WL_SEAT_CAPABILITY_TOUCH) {
7709 }
7710 else {
7712 }
7713}
7714
7715static void seat_handle_name(void *data, wl_seat * /*wl_seat*/, const char *name)
7716{
7717 CLOG_DEBUG(LOG, "name (name=\"%s\")", name);
7718 static_cast<GWL_Seat *>(data)->name = std::string(name);
7719}
7720
7721static const wl_seat_listener seat_listener = {
7722 /*capabilities*/ seat_handle_capabilities,
7723 /*name*/ seat_handle_name,
7724};
7725
7726#undef LOG
7727
7729
7730/* -------------------------------------------------------------------- */
7733
7734static CLG_LogRef LOG_WL_XDG_OUTPUT = {"ghost.wl.handle.xdg_output"};
7735#define LOG (&LOG_WL_XDG_OUTPUT)
7736
7738 zxdg_output_v1 * /*xdg_output*/,
7739 const int32_t x,
7740 const int32_t y)
7741{
7742 CLOG_DEBUG(LOG, "logical_position [%d, %d]", x, y);
7743
7744 GWL_Output *output = static_cast<GWL_Output *>(data);
7745 output->position_logical[0] = x;
7746 output->position_logical[1] = y;
7747 output->has_position_logical = true;
7748}
7749
7750static void xdg_output_handle_logical_size(void *data,
7751 zxdg_output_v1 * /*xdg_output*/,
7752 const int32_t width,
7753 const int32_t height)
7754{
7755 CLOG_DEBUG(LOG, "logical_size [%d, %d]", width, height);
7756
7757 GWL_Output *output = static_cast<GWL_Output *>(data);
7758 if (output->size_native[0] != 0 && output->size_native[1] != 0) {
7759 /* Original comment from SDL. */
7760 /* FIXME(@flibit): GNOME has a bug where the logical size does not account for
7761 * scale, resulting in bogus viewport sizes.
7762 *
7763 * Until this is fixed, validate that _some_ kind of scaling is being
7764 * done (we can't match exactly because fractional scaling can't be
7765 * detected otherwise), then override if necessary. */
7766 int width_native = output->size_native[(output->transform & WL_OUTPUT_TRANSFORM_90) ? 1 : 0];
7767 if ((width_native == width) && (output->scale_fractional == (1 * FRACTIONAL_DENOMINATOR))) {
7768 GHOST_PRINT("xdg_output scale did not match, overriding with wl_output scale\n");
7769
7770#ifdef USE_GNOME_CONFINE_HACK
7771 /* Use a bug in GNOME-42 (and prior) to check if this workaround is needed, see: #98793. */
7773#endif
7774
7775 return;
7776 }
7777 }
7778
7779 output->size_logical[0] = width;
7780 output->size_logical[1] = height;
7781 output->has_size_logical = true;
7782}
7783
7784static void xdg_output_handle_done(void *data, zxdg_output_v1 * /*xdg_output*/)
7785{
7786 CLOG_DEBUG(LOG, "done");
7787 /* NOTE: `xdg-output.done` events are deprecated and only apply below version 3 of the protocol.
7788 * `wl-output.done` event will be emitted in version 3 or higher. */
7789 GWL_Output *output = static_cast<GWL_Output *>(data);
7790 if (zxdg_output_v1_get_version(output->xdg.output) < 3) {
7791 output_handle_done(data, output->wl.output);
7792 }
7793}
7794
7795static void xdg_output_handle_name(void * /*data*/,
7796 zxdg_output_v1 * /*xdg_output*/,
7797 const char *name)
7798{
7799 CLOG_DEBUG(LOG, "name (name=\"%s\")", name);
7800}
7801
7802static void xdg_output_handle_description(void * /*data*/,
7803 zxdg_output_v1 * /*xdg_output*/,
7804 const char *description)
7805{
7806 CLOG_DEBUG(LOG, "description (description=\"%s\")", description);
7807}
7808
7809static const zxdg_output_v1_listener xdg_output_listener = {
7810 /*logical_position*/ xdg_output_handle_logical_position,
7811 /*logical_size*/ xdg_output_handle_logical_size,
7812 /*done*/ xdg_output_handle_done,
7813 /*name*/ xdg_output_handle_name,
7814 /*description*/ xdg_output_handle_description,
7815};
7816
7817#undef LOG
7818
7820
7821/* -------------------------------------------------------------------- */
7824
7825static CLG_LogRef LOG_WL_OUTPUT = {"ghost.wl.handle.output"};
7826#define LOG (&LOG_WL_OUTPUT)
7827
7828static void output_handle_geometry(void *data,
7829 wl_output * /*wl_output*/,
7830 const int32_t /*x*/,
7831 const int32_t /*y*/,
7832 const int32_t physical_width,
7833 const int32_t physical_height,
7834 const int32_t /*subpixel*/,
7835 const char *make,
7836 const char *model,
7837 const int32_t transform)
7838{
7840 "geometry (make=\"%s\", model=\"%s\", transform=%d, size=[%d, %d])",
7841 make,
7842 model,
7843 transform,
7844 physical_width,
7845 physical_height);
7846
7847 GWL_Output *output = static_cast<GWL_Output *>(data);
7848 output->transform = transform;
7849 output->make = std::string(make);
7850 output->model = std::string(model);
7851 output->size_mm[0] = physical_width;
7852 output->size_mm[1] = physical_height;
7853}
7854
7855static void output_handle_mode(void *data,
7856 wl_output * /*wl_output*/,
7857 const uint32_t flags,
7858 const int32_t width,
7859 const int32_t height,
7860 const int32_t /*refresh*/)
7861{
7862 if ((flags & WL_OUTPUT_MODE_CURRENT) == 0) {
7863 CLOG_DEBUG(LOG, "mode (skipped)");
7864 return;
7865 }
7866 CLOG_DEBUG(LOG, "mode (size=[%d, %d], flags=%u)", width, height, flags);
7867
7868 GWL_Output *output = static_cast<GWL_Output *>(data);
7869 output->size_native[0] = width;
7870 output->size_native[1] = height;
7871}
7872
7881static void output_handle_done(void *data, wl_output * /*wl_output*/)
7882{
7883 CLOG_DEBUG(LOG, "done");
7884
7885 GWL_Output *output = static_cast<GWL_Output *>(data);
7886 int32_t size_native[2] = {UNPACK2(output->size_native)};
7887 if (output->transform & WL_OUTPUT_TRANSFORM_90) {
7888 std::swap(size_native[0], size_native[1]);
7889 }
7890
7891 /* If `xdg-output` is present, calculate the true scale of the desktop */
7892 if (output->has_size_logical) {
7893
7894 /* NOTE: it's not necessary to divide these values by their greatest-common-denominator
7895 * as even a 64k screen resolution doesn't approach overflowing an `int32_t`. */
7896
7897 GHOST_ASSERT(size_native[0] && output->size_logical[0],
7898 "Screen size values were not set when they were expected to be.");
7899
7900 output->scale_fractional = (size_native[0] * FRACTIONAL_DENOMINATOR) / output->size_logical[0];
7901 output->has_scale_fractional = true;
7902 }
7903}
7904
7905static void output_handle_scale(void *data, wl_output * /*wl_output*/, const int32_t factor)
7906{
7907 CLOG_DEBUG(LOG, "scale");
7908 GWL_Output *output = static_cast<GWL_Output *>(data);
7909 output->scale = factor;
7910 output->system->output_scale_update(output);
7911}
7912
7913static void output_handle_name(void * /*data*/, wl_output * /*wl_output*/, const char *name)
7914{
7915 /* Only available in interface version 4. */
7916 CLOG_DEBUG(LOG, "name (%s)", name);
7917}
7918static void output_handle_description(void * /*data*/,
7919 wl_output * /*wl_output*/,
7920 const char *description)
7921{
7922 /* Only available in interface version 4. */
7923 CLOG_DEBUG(LOG, "description (%s)", description);
7924}
7925
7926static const wl_output_listener output_listener = {
7927 /*geometry*/ output_handle_geometry,
7928 /*mode*/ output_handle_mode,
7929 /*done*/ output_handle_done,
7930 /*scale*/ output_handle_scale,
7931 /*name*/ output_handle_name,
7932 /*description*/ output_handle_description,
7933};
7934
7937 std::unordered_set<uint32_t> supported_intents;
7938 std::unordered_set<uint32_t> supported_features;
7939 std::unordered_set<uint32_t> supported_transfers;
7940 std::unordered_set<uint32_t> supported_primaries;
7941};
7942
7944 wp_color_manager_v1 * /*wp_color_manager_v1*/,
7945 uint32_t render_intent)
7946{
7947 ColorManagerV1Data *cm_data = static_cast<ColorManagerV1Data *>(data);
7948 cm_data->supported_intents.insert(render_intent);
7949}
7950
7952 wp_color_manager_v1 * /*wp_color_manager_v1*/,
7953 uint32_t feature)
7954{
7955 ColorManagerV1Data *cm_data = static_cast<ColorManagerV1Data *>(data);
7956 cm_data->supported_features.insert(feature);
7957}
7959 wp_color_manager_v1 * /*wp_color_manager_v1*/,
7960 uint32_t tf)
7961{
7962 ColorManagerV1Data *cm_data = static_cast<ColorManagerV1Data *>(data);
7963 cm_data->supported_transfers.insert(tf);
7964}
7966 void *data, wp_color_manager_v1 * /*wp_color_manager_v1*/, uint32_t primaries)
7967{
7968 ColorManagerV1Data *cm_data = static_cast<ColorManagerV1Data *>(data);
7969 cm_data->supported_primaries.insert(primaries);
7970}
7971static void color_manager_v1_done(void *data, wp_color_manager_v1 * /*wp_color_manager_v1*/)
7972{
7973 ColorManagerV1Data *cm_data = static_cast<ColorManagerV1Data *>(data);
7974
7975 if (cm_data->supported_intents.contains(WP_COLOR_MANAGER_V1_RENDER_INTENT_PERCEPTUAL) &&
7976 cm_data->supported_features.contains(WP_COLOR_MANAGER_V1_FEATURE_PARAMETRIC) &&
7977 cm_data->supported_features.contains(WP_COLOR_MANAGER_V1_FEATURE_SET_PRIMARIES) &&
7978 cm_data->supported_primaries.contains(WP_COLOR_MANAGER_V1_PRIMARIES_SRGB) &&
7979 cm_data->supported_transfers.contains(WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_EXT_LINEAR))
7980 {
7982 }
7983
7984 if (cm_data->supported_intents.contains(WP_COLOR_MANAGER_V1_RENDER_INTENT_PERCEPTUAL) &&
7985 cm_data->supported_features.contains(WP_COLOR_MANAGER_V1_FEATURE_WINDOWS_SCRGB))
7986 {
7988 }
7989
7990 delete cm_data;
7991}
7992
7993static const wp_color_manager_v1_listener color_manager_v1_listener = {
7994 /*supported_intent*/ color_manager_v1_supported_intent,
7995 /*supported_feature*/ color_manager_v1_supported_feature,
7996 /*supported_tf_named*/ color_manager_v1_supported_tf_named,
7997 /*supported_primaries_named*/ color_manager_v1_supported_primaries_named,
7998 /*done*/ color_manager_v1_done,
7999};
8000
8001#undef LOG
8002
8004
8005/* -------------------------------------------------------------------- */
8008
8009static CLG_LogRef LOG_WL_XDG_WM_BASE = {"ghost.wl.handle.xdg_wm_base"};
8010#define LOG (&LOG_WL_XDG_WM_BASE)
8011
8012static void shell_handle_ping(void * /*data*/, xdg_wm_base *xdg_wm_base, const uint32_t serial)
8013{
8014 CLOG_DEBUG(LOG, "ping");
8015 xdg_wm_base_pong(xdg_wm_base, serial);
8016}
8017
8018static const xdg_wm_base_listener shell_listener = {
8019 /*ping*/ shell_handle_ping,
8020};
8021
8022#undef LOG
8023
8025
8026/* -------------------------------------------------------------------- */
8029
8030static CLG_LogRef LOG_WL_REGISTRY = {"ghost.wl.handle.registry"};
8031#define LOG (&LOG_WL_REGISTRY)
8032
8033/* #GWL_Display.wl_compositor */
8034
8036{
8037 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 3u, 6u);
8038
8039 display->wl.compositor = static_cast<wl_compositor *>(
8040 wl_registry_bind(display->wl.registry, params.name, &wl_compositor_interface, version));
8041 gwl_registry_entry_add(display, params, nullptr);
8042}
8044 void * /*user_data*/,
8045 const bool /*on_exit*/)
8046{
8047 wl_compositor **value_p = &display->wl.compositor;
8048 wl_compositor_destroy(*value_p);
8049 *value_p = nullptr;
8050}
8051
8052/* #GWL_Display.wl_subcompositor */
8053
8055 const GWL_RegistryAdd_Params &params)
8056{
8057 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8058
8059 display->wl.subcompositor = static_cast<wl_subcompositor *>(
8060 wl_registry_bind(display->wl.registry, params.name, &wl_subcompositor_interface, version));
8061 gwl_registry_entry_add(display, params, nullptr);
8062}
8064 void * /*user_data*/,
8065 const bool /*on_exit*/)
8066{
8067 wl_subcompositor **value_p = &display->wl.subcompositor;
8068 wl_subcompositor_destroy(*value_p);
8069 *value_p = nullptr;
8070}
8071
8072/* #GWL_Display.xdg_decor.shell */
8073
8075 const GWL_RegistryAdd_Params &params)
8076{
8077 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 6u);
8078
8079 GWL_XDG_Decor_System &decor = *display->xdg_decor;
8080 decor.shell = static_cast<xdg_wm_base *>(
8081 wl_registry_bind(display->wl.registry, params.name, &xdg_wm_base_interface, version));
8082 xdg_wm_base_add_listener(decor.shell, &shell_listener, nullptr);
8083 decor.shell_name = params.name;
8084 gwl_registry_entry_add(display, params, nullptr);
8085}
8087 void * /*user_data*/,
8088 const bool /*on_exit*/)
8089{
8090 GWL_XDG_Decor_System &decor = *display->xdg_decor;
8091 xdg_wm_base **value_p = &decor.shell;
8092 uint32_t *name_p = &decor.shell_name;
8093 xdg_wm_base_destroy(*value_p);
8094 *value_p = nullptr;
8095 *name_p = WL_NAME_UNSET;
8096}
8097
8098/* #GWL_Display.xdg_decor.manager */
8099
8101 const GWL_RegistryAdd_Params &params)
8102{
8103 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8104
8105 GWL_XDG_Decor_System &decor = *display->xdg_decor;
8106 decor.manager = static_cast<zxdg_decoration_manager_v1 *>(wl_registry_bind(
8107 display->wl.registry, params.name, &zxdg_decoration_manager_v1_interface, version));
8108 decor.manager_name = params.name;
8109 gwl_registry_entry_add(display, params, nullptr);
8110}
8112 void * /*user_data*/,
8113 const bool /*on_exit*/)
8114{
8115 GWL_XDG_Decor_System &decor = *display->xdg_decor;
8116 zxdg_decoration_manager_v1 **value_p = &decor.manager;
8117 uint32_t *name_p = &decor.manager_name;
8118 zxdg_decoration_manager_v1_destroy(*value_p);
8119 *value_p = nullptr;
8120 *name_p = WL_NAME_UNSET;
8121}
8122
8123/* #GWL_Display.xdg_output_manager */
8124
8126 const GWL_RegistryAdd_Params &params)
8127{
8128 /* NOTE(@ideasman42): only version 3 and over is well supported.
8129 * Support version 1 so GNOME-32 (on the build-bots Rocky8) can be used.
8130 * Use `zxdg_output_v1_get_version` to ensure feature support at runtime. */
8131 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 3u);
8132
8133 display->xdg.output_manager = static_cast<zxdg_output_manager_v1 *>(wl_registry_bind(
8134 display->wl.registry, params.name, &zxdg_output_manager_v1_interface, version));
8135 gwl_registry_entry_add(display, params, nullptr);
8136}
8138 void * /*user_data*/,
8139 const bool /*on_exit*/)
8140{
8141 zxdg_output_manager_v1 **value_p = &display->xdg.output_manager;
8142 zxdg_output_manager_v1_destroy(*value_p);
8143 *value_p = nullptr;
8144}
8145
8146/* #GWL_Display.wl_output */
8147
8149{
8150 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 2u, 4u);
8151
8153 output->system = display->system;
8154 output->wl.output = static_cast<wl_output *>(
8155 wl_registry_bind(display->wl.registry, params.name, &wl_output_interface, version));
8156 ghost_wl_output_tag(output->wl.output);
8157 wl_output_set_user_data(output->wl.output, output);
8158
8159 display->outputs.push_back(output);
8160 wl_output_add_listener(output->wl.output, &output_listener, output);
8161 gwl_registry_entry_add(display, params, static_cast<void *>(output));
8162}
8164 const GWL_RegistryUpdate_Params &params)
8165{
8166 GWL_Output *output = static_cast<GWL_Output *>(params.user_data);
8167 if (display->xdg.output_manager) {
8168 if (output->xdg.output == nullptr) {
8169 output->xdg.output = zxdg_output_manager_v1_get_xdg_output(display->xdg.output_manager,
8170 output->wl.output);
8171 zxdg_output_v1_add_listener(output->xdg.output, &xdg_output_listener, output);
8172 }
8173 }
8174 else {
8175 output->xdg.output = nullptr;
8176 }
8177}
8179 void *user_data,
8180 const bool on_exit)
8181{
8182 /* While windows & cursors hold references to outputs, there is no need to manually remove
8183 * these references as the compositor will remove references via #wl_surface_listener.leave.
8184 *
8185 * WARNING: this is not the case for WLROOTS based compositors which have a (bug?)
8186 * where surface leave events don't run. So `system->output_leave(..)` is needed
8187 * until the issue is resolved in WLROOTS. */
8188 GWL_Output *output = static_cast<GWL_Output *>(user_data);
8189
8190 if (!on_exit) {
8191 /* Needed for WLROOTS, does nothing if surface leave callbacks have already run. */
8192 if (output->system->output_unref(output->wl.output)) {
8193 CLOG_WARN(LOG,
8194 "mis-behaving compositor failed to call \"surface_listener.leave\" "
8195 "window scale may be invalid!");
8196 }
8197 }
8198
8199 if (output->xdg.output) {
8200 zxdg_output_v1_destroy(output->xdg.output);
8201 }
8202 wl_output_destroy(output->wl.output);
8203 /* NOTE: always erase even when `on_exit` because `output->xdg_output` is cleared later. */
8204 GHOST_ASSERT(std::ranges::find(display->outputs, output) != display->outputs.end(),
8205 "invalid internal state");
8206 std::erase(display->outputs, output);
8207 delete output;
8208}
8209
8210/* #GWL_Display.wp_color_manager */
8211
8213 const GWL_RegistryAdd_Params &params)
8214{
8215 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8217 data->display = display;
8218
8219 display->wp.color_manager = static_cast<wp_color_manager_v1 *>(wl_registry_bind(
8220 display->wl.registry, params.name, &wp_color_manager_v1_interface, version));
8221 wp_color_manager_v1_add_listener(display->wp.color_manager, &color_manager_v1_listener, data);
8222 display->wp.color_manager_queue = wl_display_create_queue(display->wl.display);
8223 gwl_registry_entry_add(display, params, nullptr);
8224}
8226 void * /*user_data*/,
8227 const bool /*on_exit*/)
8228{
8229 if (display->wp.color_manager_queue) {
8230 wl_event_queue_destroy(display->wp.color_manager_queue);
8231 display->wp.color_manager_queue = nullptr;
8232 }
8233 wp_color_manager_v1 **value_p = &display->wp.color_manager;
8234 wp_color_manager_v1_destroy(*value_p);
8235 *value_p = nullptr;
8236}
8237
8238/* #GWL_Display.seats */
8239
8241{
8242 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 5u, 9u);
8243
8244 GWL_Seat *seat = new GWL_Seat;
8245 seat->system = display->system;
8246 seat->xkb.context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
8247
8248 /* May be null (skip dead-key support in this case). */
8249 seat->xkb.compose_table = xkb_compose_table_new_from_locale(
8250 seat->xkb.context, ghost_wl_locale_from_env_with_default(), XKB_COMPOSE_COMPILE_NO_FLAGS);
8251
8252 seat->data_source = new GWL_DataSource;
8253 seat->wl.seat = static_cast<wl_seat *>(
8254 wl_registry_bind(display->wl.registry, params.name, &wl_seat_interface, version));
8255 display->seats.push_back(seat);
8256 wl_seat_add_listener(seat->wl.seat, &seat_listener, seat);
8257 gwl_registry_entry_add(display, params, static_cast<void *>(seat));
8258
8260}
8262 const GWL_RegistryUpdate_Params &params)
8263{
8264 GWL_Seat *seat = static_cast<GWL_Seat *>(params.user_data);
8265
8266 /* Register data device per seat for IPC between WAYLAND clients. */
8267 if (display->wl.data_device_manager) {
8268 if (seat->wl.data_device == nullptr) {
8269 seat->wl.data_device = wl_data_device_manager_get_data_device(
8270 display->wl.data_device_manager, seat->wl.seat);
8271 wl_data_device_add_listener(seat->wl.data_device, &data_device_listener, seat);
8272 }
8273 }
8274 else {
8275 seat->wl.data_device = nullptr;
8276 }
8277
8278 if (display->wp.tablet_manager) {
8279 if (seat->wp.tablet_seat == nullptr) {
8280 seat->wp.tablet_seat = zwp_tablet_manager_v2_get_tablet_seat(display->wp.tablet_manager,
8281 seat->wl.seat);
8282 zwp_tablet_seat_v2_add_listener(seat->wp.tablet_seat, &tablet_seat_listener, seat);
8283 }
8284 }
8285 else {
8286 seat->wp.tablet_seat = nullptr;
8287 }
8288
8289 if (display->wp.primary_selection_device_manager) {
8290 if (seat->wp.primary_selection_device == nullptr) {
8291 seat->wp.primary_selection_device = zwp_primary_selection_device_manager_v1_get_device(
8292 display->wp.primary_selection_device_manager, seat->wl.seat);
8293
8294 zwp_primary_selection_device_v1_add_listener(seat->wp.primary_selection_device,
8296 &seat->primary_selection);
8297 }
8298 }
8299 else {
8300 seat->wp.primary_selection_device = nullptr;
8301 }
8302
8303#ifdef WITH_INPUT_IME
8304 if (display->wp.text_input_manager) {
8305 if (seat->wp.text_input == nullptr) {
8306 seat->wp.text_input = zwp_text_input_manager_v3_get_text_input(
8307 display->wp.text_input_manager, seat->wl.seat);
8308 zwp_text_input_v3_set_user_data(seat->wp.text_input, seat);
8309 zwp_text_input_v3_add_listener(seat->wp.text_input, &text_input_listener, seat);
8310 }
8311 }
8312 else {
8313 seat->wp.text_input = nullptr;
8314 }
8315#endif /* WITH_INPUT_IME */
8316}
8317static void gwl_registry_wl_seat_remove(GWL_Display *display, void *user_data, const bool on_exit)
8318{
8319 GWL_Seat *seat = static_cast<GWL_Seat *>(user_data);
8320
8321 /* First handle members that require locking.
8322 * While highly unlikely, it's possible they are being used while this function runs. */
8323 {
8324 std::lock_guard lock{seat->data_source_mutex};
8325 if (seat->data_source) {
8327 if (seat->data_source->wl.source) {
8328 wl_data_source_destroy(seat->data_source->wl.source);
8329 }
8330 delete seat->data_source;
8331 }
8332 }
8333
8334 {
8335 std::lock_guard lock{seat->data_offer_dnd_mutex};
8336 if (seat->data_offer_dnd) {
8337 wl_data_offer_destroy(seat->data_offer_dnd->wl.id);
8338 delete seat->data_offer_dnd;
8339 }
8340 }
8341
8342 {
8343 std::lock_guard lock{seat->data_offer_copy_paste_mutex};
8344 if (seat->data_offer_copy_paste) {
8345 wl_data_offer_destroy(seat->data_offer_copy_paste->wl.id);
8346 delete seat->data_offer_copy_paste;
8347 }
8348 }
8349
8350 {
8351 GWL_PrimarySelection *primary = &seat->primary_selection;
8352 std::lock_guard lock{primary->data_offer_mutex};
8354 }
8355
8356 {
8357 GWL_PrimarySelection *primary = &seat->primary_selection;
8358 std::lock_guard lock{primary->data_source_mutex};
8360 }
8361
8362 if (seat->wp.primary_selection_device) {
8363 zwp_primary_selection_device_v1_destroy(seat->wp.primary_selection_device);
8364 }
8365
8366#ifdef WITH_INPUT_IME
8367 if (seat->wp.text_input) {
8368 zwp_text_input_v3_destroy(seat->wp.text_input);
8369 }
8370#endif
8371
8372 if (seat->wl.data_device) {
8373 wl_data_device_release(seat->wl.data_device);
8374 }
8375
8376 if (seat->wp.tablet_seat) {
8377 zwp_tablet_seat_v2_destroy(seat->wp.tablet_seat);
8378 }
8379
8380 /* Disable all capabilities as a way to free:
8381 * - `seat.wl_pointer` (and related cursor variables).
8382 * - `seat.wl_touch`.
8383 * - `seat.wl_keyboard`.
8384 */
8388
8389 /* Run after tablet & input devices have been disabled
8390 * to ensure the buffer from a *visible* cursor never destroyed.
8391 *
8392 * Note that most compositors will have already released the buffer,
8393 * in that case this will have been set to null.
8394 * However this isn't guaranteed, see: #145557. */
8395 if (seat->cursor.wl.buffer) {
8396 wl_buffer_destroy(seat->cursor.wl.buffer);
8397 }
8398
8399 if (seat->cursor.custom_data) {
8400 munmap(seat->cursor.custom_data, seat->cursor.custom_data_size);
8401 }
8402
8403 /* Un-referencing checks for nullptr case. */
8404 xkb_state_unref(seat->xkb.state);
8405 xkb_state_unref(seat->xkb.state_empty);
8406 xkb_state_unref(seat->xkb.state_empty_with_shift);
8407 xkb_state_unref(seat->xkb.state_empty_with_numlock);
8408
8409 xkb_compose_state_unref(seat->xkb.compose_state);
8410 xkb_compose_table_unref(seat->xkb.compose_table);
8411
8412 xkb_context_unref(seat->xkb.context);
8413
8414 /* Remove the seat. */
8415 wl_seat_destroy(seat->wl.seat);
8416
8417 const auto iter = std::ranges::find(display->seats, seat);
8418 GHOST_ASSERT(iter != display->seats.end(), "invalid internal state");
8419
8420 if (!on_exit) {
8421 const int index = int(iter - display->seats.begin());
8422 if (display->seats_active_index >= index) {
8423 display->seats_active_index -= 1;
8424 }
8425 display->seats.erase(iter);
8426 }
8427 delete seat;
8428}
8429
8430/* #GWL_Display.wl_shm */
8431
8433{
8434 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8435
8436 display->wl.shm = static_cast<wl_shm *>(
8437 wl_registry_bind(display->wl.registry, params.name, &wl_shm_interface, version));
8438 gwl_registry_entry_add(display, params, nullptr);
8439}
8441 void * /*user_data*/,
8442 const bool /*on_exit*/)
8443{
8444 wl_shm **value_p = &display->wl.shm;
8445 wl_shm_destroy(*value_p);
8446 *value_p = nullptr;
8447}
8448
8449/* #GWL_Display.wl_data_device_manager */
8450
8452 const GWL_RegistryAdd_Params &params)
8453{
8454 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 3u, 3u);
8455
8456 display->wl.data_device_manager = static_cast<wl_data_device_manager *>(wl_registry_bind(
8457 display->wl.registry, params.name, &wl_data_device_manager_interface, version));
8458 gwl_registry_entry_add(display, params, nullptr);
8459}
8461 void * /*user_data*/,
8462 const bool /*on_exit*/)
8463{
8464 wl_data_device_manager **value_p = &display->wl.data_device_manager;
8465 wl_data_device_manager_destroy(*value_p);
8466 *value_p = nullptr;
8467}
8468
8469/* #GWL_Display.wp_tablet_manager */
8470
8472 const GWL_RegistryAdd_Params &params)
8473{
8474 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8475
8476 display->wp.tablet_manager = static_cast<zwp_tablet_manager_v2 *>(wl_registry_bind(
8477 display->wl.registry, params.name, &zwp_tablet_manager_v2_interface, version));
8478 gwl_registry_entry_add(display, params, nullptr);
8479}
8481 void * /*user_data*/,
8482 const bool /*on_exit*/)
8483{
8484 zwp_tablet_manager_v2 **value_p = &display->wp.tablet_manager;
8485 zwp_tablet_manager_v2_destroy(*value_p);
8486 *value_p = nullptr;
8487}
8488
8489/* #GWL_Display.wp_relative_pointer_manager */
8490
8492 const GWL_RegistryAdd_Params &params)
8493{
8494 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8495
8496 display->wp.relative_pointer_manager = static_cast<zwp_relative_pointer_manager_v1 *>(
8497 wl_registry_bind(
8498 display->wl.registry, params.name, &zwp_relative_pointer_manager_v1_interface, version));
8499 gwl_registry_entry_add(display, params, nullptr);
8500}
8502 void * /*user_data*/,
8503 const bool /*on_exit*/)
8504{
8505 zwp_relative_pointer_manager_v1 **value_p = &display->wp.relative_pointer_manager;
8506 zwp_relative_pointer_manager_v1_destroy(*value_p);
8507 *value_p = nullptr;
8508}
8509
8510/* #GWL_Display.wp_pointer_constraints */
8511
8513 const GWL_RegistryAdd_Params &params)
8514{
8515 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8516
8517 display->wp.pointer_constraints = static_cast<zwp_pointer_constraints_v1 *>(wl_registry_bind(
8518 display->wl.registry, params.name, &zwp_pointer_constraints_v1_interface, version));
8519 gwl_registry_entry_add(display, params, nullptr);
8520}
8522 void * /*user_data*/,
8523 const bool /*on_exit*/)
8524{
8525 zwp_pointer_constraints_v1 **value_p = &display->wp.pointer_constraints;
8526 zwp_pointer_constraints_v1_destroy(*value_p);
8527 *value_p = nullptr;
8528}
8529
8530/* #GWL_Display.wp_pointer_gestures */
8531
8533 const GWL_RegistryAdd_Params &params)
8534{
8535 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 3u, 3u);
8536
8537 display->wp.pointer_gestures = static_cast<zwp_pointer_gestures_v1 *>(
8538 wl_registry_bind(display->wl.registry,
8539 params.name,
8540 &zwp_pointer_gestures_v1_interface,
8541 std::min(params.version, version)));
8542 gwl_registry_entry_add(display, params, nullptr);
8543}
8545 void * /*user_data*/,
8546 const bool /*on_exit*/)
8547{
8548 zwp_pointer_gestures_v1 **value_p = &display->wp.pointer_gestures;
8549 zwp_pointer_gestures_v1_destroy(*value_p);
8550 *value_p = nullptr;
8551}
8552
8553/* #GWL_Display.xdg_activation */
8554
8556 const GWL_RegistryAdd_Params &params)
8557{
8558 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8559
8560 display->xdg.activation_manager = static_cast<xdg_activation_v1 *>(
8561 wl_registry_bind(display->wl.registry, params.name, &xdg_activation_v1_interface, version));
8562 gwl_registry_entry_add(display, params, nullptr);
8563}
8565 void * /*user_data*/,
8566 const bool /*on_exit*/)
8567{
8568 xdg_activation_v1 **value_p = &display->xdg.activation_manager;
8569 xdg_activation_v1_destroy(*value_p);
8570 *value_p = nullptr;
8571}
8572
8573/* #GWL_Display.xdg_toplevel_icon_manager */
8574
8576 xdg_toplevel_icon_manager_v1 * /*manager*/,
8577 int32_t size)
8578{
8579 GWL_Display *display = static_cast<GWL_Display *>(data);
8580 /* Use the largest size the compositor requests. */
8581 if (size > display->xdg.toplevel_icon_logical_size_max) {
8582 display->xdg.toplevel_icon_logical_size_max = size;
8583 }
8584}
8585
8586static void xdg_toplevel_icon_manager_handle_done(void * /*data*/,
8587 xdg_toplevel_icon_manager_v1 * /*manager*/)
8588{
8589}
8590
8591static const xdg_toplevel_icon_manager_v1_listener xdg_toplevel_icon_manager_listener = {
8594};
8595
8597 const GWL_RegistryAdd_Params &params)
8598{
8599 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8600
8601 display->xdg.toplevel_icon_manager = static_cast<xdg_toplevel_icon_manager_v1 *>(
8602 wl_registry_bind(
8603 display->wl.registry, params.name, &xdg_toplevel_icon_manager_v1_interface, version));
8604 xdg_toplevel_icon_manager_v1_add_listener(
8605 display->xdg.toplevel_icon_manager, &xdg_toplevel_icon_manager_listener, display);
8606 gwl_registry_entry_add(display, params, nullptr);
8607}
8609 void * /*user_data*/,
8610 const bool /*on_exit*/)
8611{
8612 xdg_toplevel_icon_manager_v1 **value_p = &display->xdg.toplevel_icon_manager;
8613 xdg_toplevel_icon_manager_v1_destroy(*value_p);
8614 *value_p = nullptr;
8615}
8616
8617/* #GWL_Display.wp_fractional_scale_manger */
8618
8620 const GWL_RegistryAdd_Params &params)
8621{
8622 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8623
8624 display->wp.fractional_scale_manager = static_cast<wp_fractional_scale_manager_v1 *>(
8625 wl_registry_bind(
8626 display->wl.registry, params.name, &wp_fractional_scale_manager_v1_interface, version));
8627 gwl_registry_entry_add(display, params, nullptr);
8628}
8630 void * /*user_data*/,
8631 const bool /*on_exit*/)
8632{
8633 wp_fractional_scale_manager_v1 **value_p = &display->wp.fractional_scale_manager;
8634 wp_fractional_scale_manager_v1_destroy(*value_p);
8635 *value_p = nullptr;
8636}
8637
8638/* #GWL_Display.wl_viewport */
8639
8641 const GWL_RegistryAdd_Params &params)
8642{
8643 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8644
8645 display->wp.viewporter = static_cast<wp_viewporter *>(
8646 wl_registry_bind(display->wl.registry, params.name, &wp_viewporter_interface, version));
8647 gwl_registry_entry_add(display, params, nullptr);
8648}
8650 void * /*user_data*/,
8651 const bool /*on_exit*/)
8652{
8653 wp_viewporter **value_p = &display->wp.viewporter;
8654 wp_viewporter_destroy(*value_p);
8655 *value_p = nullptr;
8656}
8657
8658/* #GWL_Display.wp_primary_selection_device_manager */
8659
8661 GWL_Display *display, const GWL_RegistryAdd_Params &params)
8662{
8663 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8664
8665 display->wp.primary_selection_device_manager =
8666 static_cast<zwp_primary_selection_device_manager_v1 *>(
8667 wl_registry_bind(display->wl.registry,
8668 params.name,
8669 &zwp_primary_selection_device_manager_v1_interface,
8670 version));
8671 gwl_registry_entry_add(display, params, nullptr);
8672}
8674 void * /*user_data*/,
8675 const bool /*on_exit*/)
8676{
8677 zwp_primary_selection_device_manager_v1 **value_p =
8678 &display->wp.primary_selection_device_manager;
8679 zwp_primary_selection_device_manager_v1_destroy(*value_p);
8680 *value_p = nullptr;
8681}
8682
8683#ifdef WITH_INPUT_IME
8684
8685/* #GWL_Display.wp_text_input_manager */
8686
8687static void gwl_registry_wp_text_input_manager_add(GWL_Display *display,
8688 const GWL_RegistryAdd_Params &params)
8689{
8690 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8691
8692 display->wp.text_input_manager = static_cast<zwp_text_input_manager_v3 *>(wl_registry_bind(
8693 display->wl.registry, params.name, &zwp_text_input_manager_v3_interface, version));
8694 gwl_registry_entry_add(display, params, nullptr);
8695}
8696static void gwl_registry_wp_text_input_manager_remove(GWL_Display *display,
8697 void * /*user_data*/,
8698 const bool /*on_exit*/)
8699{
8700 zwp_text_input_manager_v3 **value_p = &display->wp.text_input_manager;
8701 zwp_text_input_manager_v3_destroy(*value_p);
8702 *value_p = nullptr;
8703}
8704
8705#endif /* WITH_INPUT_IME */
8706
8707/* #GWL_Display.wp_cursor_shape_manager */
8708
8710 const GWL_RegistryAdd_Params &params)
8711{
8712 const uint version = GWL_IFACE_VERSION_CLAMP(params.version, 1u, 1u);
8713
8714 display->wp.cursor_shape_manager = static_cast<wp_cursor_shape_manager_v1 *>(wl_registry_bind(
8715 display->wl.registry, params.name, &wp_cursor_shape_manager_v1_interface, version));
8716 gwl_registry_entry_add(display, params, nullptr);
8717}
8719 void * /*user_data*/,
8720 const bool /*on_exit*/)
8721{
8722 wp_cursor_shape_manager_v1 **value_p = &display->wp.cursor_shape_manager;
8723 wp_cursor_shape_manager_v1_destroy(*value_p);
8724 *value_p = nullptr;
8725}
8726
8738 /* Low level interfaces. */
8739 {
8740 /*interface_p*/ &wl_compositor_interface.name,
8741 /*add_fn*/ gwl_registry_compositor_add,
8742 /*update_fn*/ nullptr,
8743 /*remove_fn*/ gwl_registry_compositor_remove,
8744 },
8745 {
8746 /*interface_p*/ &wl_subcompositor_interface.name,
8748 /*update_fn*/ nullptr,
8750 },
8751 {
8752 /*interface_p*/ &wl_shm_interface.name,
8753 /*add_fn*/ gwl_registry_wl_shm_add,
8754 /*update_fn*/ nullptr,
8755 /*remove_fn*/ gwl_registry_wl_shm_remove,
8756 },
8757 {
8758 /*interface_p*/ &xdg_wm_base_interface.name,
8760 /*update_fn*/ nullptr,
8761 /*remove_fn*/ gwl_registry_xdg_wm_base_remove,
8762 },
8763 /* Managers. */
8764 {
8765 /*interface_p*/ &zxdg_decoration_manager_v1_interface.name,
8767 /*update_fn*/ nullptr,
8769 },
8770 {
8771 /*interface_p*/ &zxdg_output_manager_v1_interface.name,
8773 /*update_fn*/ nullptr,
8775 },
8776 {
8777 /*interface_p*/ &wl_data_device_manager_interface.name,
8779 /*update_fn*/ nullptr,
8781 },
8782 {
8783 /*interface_p*/ &zwp_primary_selection_device_manager_v1_interface.name,
8785 /*update_fn*/ nullptr,
8787 },
8788 {
8789 /*interface_p*/ &zwp_tablet_manager_v2_interface.name,
8791 /*update_fn*/ nullptr,
8793 },
8794 {
8795 /*interface_p*/ &zwp_relative_pointer_manager_v1_interface.name,
8797 /*update_fn*/ nullptr,
8799 },
8800#ifdef WITH_INPUT_IME
8801 {
8802 /*interface_p*/ &zwp_text_input_manager_v3_interface.name,
8803 /*add_fn*/ gwl_registry_wp_text_input_manager_add,
8804 /*update_fn*/ nullptr,
8805 /*remove_fn*/ gwl_registry_wp_text_input_manager_remove,
8806 },
8807#endif
8808 {
8809 /*interface_p*/ &wp_cursor_shape_manager_v1_interface.name,
8811 /*update_fn*/ nullptr,
8813 },
8814 /* Higher level interfaces. */
8815 {
8816 /*interface_p*/ &zwp_pointer_constraints_v1_interface.name,
8818 /*update_fn*/ nullptr,
8820 },
8821 {
8822 /*interface_p*/ &zwp_pointer_gestures_v1_interface.name,
8824 /*update_fn*/ nullptr,
8826 },
8827 {
8828 /*interface_p*/ &xdg_activation_v1_interface.name,
8830 /*update_fn*/ nullptr,
8832 },
8833 {
8834 /*interface_p*/ &xdg_toplevel_icon_manager_v1_interface.name,
8836 /*update_fn*/ nullptr,
8838 },
8839 {
8840 /*interface_p*/ &wp_fractional_scale_manager_v1_interface.name,
8842 /*update_fn*/ nullptr,
8844 },
8845 {
8846 /*interface_p*/ &wp_viewporter_interface.name,
8848 /*update_fn*/ nullptr,
8850 },
8851 /* Display outputs. */
8852 {
8853 /*interface_p*/ &wl_output_interface.name,
8854 /*add_fn*/ gwl_registry_wl_output_add,
8855 /*update_fn*/ gwl_registry_wl_output_update,
8856 /*remove_fn*/ gwl_registry_wl_output_remove,
8857 },
8858 {
8859 /*interface_p*/ &wp_color_manager_v1_interface.name,
8861 /*update_fn*/ nullptr,
8863 },
8864 /* Seats.
8865 * Keep the seat near the end to ensure other types are created first.
8866 * as the seat creates data based on other interfaces. */
8867 {
8868 /*interface_p*/ &wl_seat_interface.name,
8869 /*add_fn*/ gwl_registry_wl_seat_add,
8870 /*update_fn*/ gwl_registry_wl_seat_update,
8871 /*remove_fn*/ gwl_registry_wl_seat_remove,
8872 },
8873
8874 {nullptr},
8875};
8876
8885
8887{
8888 for (const GWL_RegistryHandler *handler = gwl_registry_handlers; handler->interface_p != nullptr;
8889 handler++)
8890 {
8891 if (STREQ(interface, *handler->interface_p)) {
8892 return int(handler - gwl_registry_handlers);
8893 }
8894 }
8895 return -1;
8896}
8897
8899{
8900 GHOST_ASSERT(uint32_t(interface_slot) < uint32_t(gwl_registry_handler_interface_slot_max()),
8901 "Index out of range");
8902 return &gwl_registry_handlers[interface_slot];
8903}
8904
8905static void global_handle_add(void *data,
8906 [[maybe_unused]] wl_registry *wl_registry,
8907 const uint32_t name,
8908 const char *interface,
8909 const uint32_t version)
8910{
8911 /* Log last since it's useful to know if the interface was handled or not. */
8912 GWL_Display *display = static_cast<GWL_Display *>(data);
8913 GHOST_ASSERT(display->wl.registry == wl_registry, "Registry argument must match!");
8914
8915 const int interface_slot = gwl_registry_handler_interface_slot_from_string(interface);
8916 bool added = false;
8917
8918 if (interface_slot != -1) {
8919 const GWL_RegistryHandler *handler = &gwl_registry_handlers[interface_slot];
8920 const GWL_RegistryEntry *registry_entry_prev = display->registry_entry;
8921
8922 /* The interface name that is ensured not to be freed. */
8923 GWL_RegistryAdd_Params params{};
8924 params.name = name;
8925 params.interface_slot = interface_slot;
8926 params.version = version;
8927
8928 handler->add_fn(display, params);
8929
8930 added = display->registry_entry != registry_entry_prev;
8931 }
8932
8934 "add %s(interface=%s, version=%u, name=%u)",
8935 (interface_slot != -1) ? (added ? "" : "(found but not added)") : "(skipped), ",
8936 interface,
8937 version,
8938 name);
8939
8940 /* Initialization avoids excessive calls by calling update after all have been initialized. */
8941 if (added) {
8942 if (display->registry_skip_update_all == false) {
8943 /* See docstring for rationale on updating all on add/removal. */
8944 gwl_registry_entry_update_all(display, interface_slot);
8945 }
8946 }
8947}
8948
8958static void global_handle_remove(void *data,
8959 [[maybe_unused]] wl_registry *wl_registry,
8960 const uint32_t name)
8961{
8962 GWL_Display *display = static_cast<GWL_Display *>(data);
8963 GHOST_ASSERT(display->wl.registry == wl_registry, "Registry argument must match!");
8964
8965 int interface_slot = 0;
8966 const bool removed = gwl_registry_entry_remove_by_name(display, name, &interface_slot);
8967
8969 "remove (name=%u, interface=%s)",
8970 name,
8971 removed ? *gwl_registry_handlers[interface_slot].interface_p : "(unknown)");
8972
8973 if (removed) {
8974 if (display->registry_skip_update_all == false) {
8975 /* See docstring for rationale on updating all on add/removal. */
8976 gwl_registry_entry_update_all(display, interface_slot);
8977 }
8978 }
8979}
8980
8981static const wl_registry_listener registry_listener = {
8982 /*global*/ global_handle_add,
8983 /*global_remove*/ global_handle_remove,
8984};
8985
8986#undef LOG
8987
8989
8990/* -------------------------------------------------------------------- */
8993
8994#ifdef USE_EVENT_BACKGROUND_THREAD
8995
8996static void *gwl_display_event_thread_fn(void *display_voidp)
8997{
8998 GWL_Display *display = static_cast<GWL_Display *>(display_voidp);
8999 GHOST_ASSERT(!display->background, "Foreground only");
9000
9001 /* Read once, the main thread joins before freeing these. */
9002 wl_display *wl_display = display->wl.display;
9003 std::mutex *server_mutex = display->system->server_mutex;
9004 const int fd = wl_display_get_fd(wl_display);
9005 const int fd_stop = display->events_pipe[0];
9006
9007 /* Wait for events, this thread is dedicated to event handling.
9008 * Ends via `fd_stop`, see #gwl_display_event_thread_destroy. */
9009 while (ghost_wl_display_event_pump_from_thread(wl_display, fd, fd_stop, server_mutex) != -1) {
9010 /* Pass. */
9011 }
9012
9013 return nullptr;
9014}
9015
9016/* Event reading thread. */
9018{
9019 GHOST_ASSERT(!display->background, "Foreground only");
9020 GHOST_ASSERT(display->events_pthread == 0, "Only call once");
9021
9022 /* Fatal, the thread can't be ended without a way to wake it. Only expected on descriptor
9023 * exhaustion, where start-up is doomed anyway.
9024 *
9025 * `O_CLOEXEC` is not optional, a sub-process inheriting the write end would keep it
9026 * open, so closing it here wouldn't end the thread & the join would never return. */
9027 if (pipe2(display->events_pipe, O_CLOEXEC) != 0) {
9028 display->events_pipe[0] = display->events_pipe[1] = -1;
9029 return false;
9030 }
9031
9033 if (pthread_create(&display->events_pthread, nullptr, gwl_display_event_thread_fn, display) != 0)
9034 {
9035 close(display->events_pipe[0]);
9036 close(display->events_pipe[1]);
9037 display->events_pipe[0] = display->events_pipe[1] = -1;
9038 display->events_pthread = 0;
9039 return false;
9040 }
9041 /* Application logic should take priority, this only ensures events don't accumulate when busy
9042 * which typically takes a while (5+ seconds of frantic mouse motion for example). */
9044 return true;
9045}
9046
9048{
9049 GHOST_ASSERT(!display->background, "Foreground only");
9050
9051 /* Close the write end, the read end then reports end-of-file.
9052 * Closing the read end wouldn't do, that doesn't wake the threads `poll`. */
9053 close(display->events_pipe[1]);
9054 display->events_pipe[1] = -1;
9055
9056 pthread_join(display->events_pthread, nullptr);
9057 display->events_pthread = 0;
9058
9059 close(display->events_pipe[0]);
9060 display->events_pipe[0] = -1;
9061}
9062
9063#endif /* USE_EVENT_BACKGROUND_THREAD */
9064
9066
9067/* -------------------------------------------------------------------- */
9072
9074 : GHOST_System(),
9076 server_mutex(new std::mutex),
9077 timer_mutex(new std::mutex),
9078 main_thread_id(std::this_thread::get_id()),
9079#endif
9080 display_(new GWL_Display)
9081{
9084
9085 const bool use_window_frame = GHOST_ISystem::getUseWindowFrame();
9086
9087 display_->system = this;
9088 display_->background = background;
9089 display_->use_window_frame = use_window_frame;
9090
9091 /* Connect to the Wayland server. */
9092
9093 display_->wl.display = wl_display_connect(nullptr);
9094 if (!display_->wl.display) {
9095 display_destroy_and_free_all();
9096 throw std::runtime_error("unable to connect to display!");
9097 }
9098
9099 const GWL_CurrentDesktopType current_desktop = ghost_wayland_current_desktop();
9100 if (current_desktop == GWL_CurrentDesktopType::KDE) {
9101#ifdef USE_KDE_TABLET_HIDDEN_CURSOR_HACK
9103#endif
9104#ifdef USE_KDE_VULKAN_UNGRAB_CURSOR_HACK
9105 use_kde_vulkan_ungrab_cursor_hack = true;
9106#endif
9107 }
9108
9109#ifdef WITH_GHOST_CSD
9110 if (use_window_frame) {
9111# ifdef USE_GHOST_CSD_FORCE
9112 display_->use_window_frame_csd = true;
9113# else
9114 display_->use_window_frame_csd = GHOST_WindowCSD_Check(current_desktop);
9115# endif
9116 }
9117#endif /* WITH_GHOST_CSD */
9118
9119 const std::optional<int> cursor_size_env = cursor_size_from_env();
9120
9121 /* The portal may replace these, see #dbus_event_handle. */
9122 display_->preferences.cursor_size = cursor_size_env.value_or(default_cursor_size);
9123#ifdef WITH_GHOST_CSD
9124 if (display_->use_window_frame_csd) {
9125 GHOST_CSD_Layout csd_button_layout = {0};
9126 GHOST_WindowCSD_LayoutDefault(csd_button_layout);
9127
9128 this->setWindowCSD_Layout(csd_button_layout);
9129 display_->preferences.csd_button_layout = csd_button_layout;
9130 }
9131#endif /* WITH_GHOST_CSD */
9132
9133#ifdef WITH_GHOST_DBUS
9134 /* Like the WAYLAND event thread, there's no need for this in background mode. */
9135 if (!background) {
9136 dbus_watcher_start(!cursor_size_env.has_value());
9137 }
9138#endif /* WITH_GHOST_DBUS */
9139
9140 /* This may be removed later if decorations are required, needed as part of registration. */
9141 display_->xdg_decor = new GWL_XDG_Decor_System;
9142
9143 /* Register interfaces. */
9144 {
9145 display_->registry_skip_update_all = true;
9146 wl_registry *registry = wl_display_get_registry(display_->wl.display);
9147 display_->wl.registry = registry;
9148 wl_registry_add_listener(registry, &registry_listener, display_);
9149 /* First round-trip to receive all registry objects. */
9150 wl_display_roundtrip(display_->wl.display);
9151 /* Second round-trip to receive all output events. */
9152 wl_display_roundtrip(display_->wl.display);
9153
9154 /* Account for dependencies between interfaces. */
9155 gwl_registry_entry_update_all(display_, -1);
9156
9157 display_->registry_skip_update_all = false;
9158 }
9159
9160#ifdef USE_GNOME_MOTION_MISSING_TIME_HACK
9161 if (current_desktop == GWL_CurrentDesktopType::Gnome) {
9163 }
9164#endif
9165
9166 {
9167 const GWL_XDG_Decor_System &decor = *display_->xdg_decor;
9168 if (!decor.shell) {
9169 display_destroy_and_free_all();
9170 throw std::runtime_error("unable to access xdg_shell!");
9171 }
9172 }
9173
9174 /* Without this, the output fractional size from `display->xdg.output_manager` isn't known,
9175 * while this isn't essential, the first window creation uses this for setting the size.
9176 * Supporting both XDG initialized/uninitialized outputs is possible it complicates logic.
9177 * see: #113328 for an example of size on startup issues. */
9178 wl_display_roundtrip(display_->wl.display);
9179
9180#ifdef USE_EVENT_BACKGROUND_THREAD
9181 /* There is no need for an event handling thread in background mode
9182 * because there no polling for user input. */
9183 if (background) {
9184 GHOST_ASSERT(display_->events_pthread == 0, "Expected to be unset");
9185 }
9186 else if (!gwl_display_event_thread_create(display_)) {
9187 display_destroy_and_free_all();
9188 throw std::runtime_error("unable to create the event thread!");
9189 }
9190#endif
9191 /* Could be null in background mode, however there are enough
9192 * references to the timer-manager that it's safer to create it. */
9193 display_->key_repeat_timer_manager = new GHOST_TimerManager();
9194}
9195
9196void GHOST_SystemWayland::display_destroy_and_free_all()
9197{
9198#ifdef WITH_GHOST_DBUS
9199 /* Stop the watcher first: its callbacks (which can still run up until this returns)
9200 * capture `this` & push into `display_->dbus`. */
9201 dbus_watcher_.reset();
9202#endif
9203
9204 gwl_display_destroy(display_);
9205
9206#ifdef USE_EVENT_BACKGROUND_THREAD
9207 delete server_mutex;
9208 delete timer_mutex;
9209#endif
9210}
9211
9213{
9214 display_destroy_and_free_all();
9215}
9216
9218{
9220
9221 if (success) {
9222#ifdef WITH_INPUT_NDOF
9223 ndof_manager_ = new GHOST_NDOFManagerUnix(*this);
9224#endif
9225 return GHOST_kSuccess;
9226 }
9227
9228 return GHOST_kFailure;
9229}
9230
9231#undef pushEvent
9232
9234{
9235 bool any_processed = false;
9236
9237#ifdef USE_EVENT_BACKGROUND_THREAD
9238 if (has_pending_actions_for_window.exchange(false)) [[unlikely]] {
9239 std::lock_guard lock_server_guard{*server_mutex};
9240 for (GHOST_IWindow *iwin : getWindowManager()->getWindows()) {
9241 GHOST_WindowWayland *win = static_cast<GHOST_WindowWayland *>(iwin);
9243 }
9244 }
9245
9246 if (!display_->background) {
9247 std::lock_guard lock{display_->events_pending_mutex};
9248 for (std::unique_ptr<const GHOST_IEvent> &event : display_->events_pending) {
9249
9250 /* Perform actions that aren't handled in a thread. */
9251 switch (event->getType()) {
9253 getWindowManager()->setActiveWindow(event->getWindow());
9254 break;
9255 }
9257 getWindowManager()->setWindowInactive(event->getWindow());
9258 break;
9259 }
9260 default: {
9261 break;
9262 }
9263 }
9264
9265 pushEvent(std::move(event));
9266 }
9267 display_->events_pending.clear();
9268
9269 if (display_->events_pending.capacity() > events_pending_default_size) [[unlikely]] {
9270 /* Avoid over allocation in the case of occasional delay between processing events
9271 * causing many events to be collected and making this into a large array. */
9272 display_->events_pending.shrink_to_fit();
9273 display_->events_pending.reserve(events_pending_default_size);
9274 }
9275 }
9276#endif /* USE_EVENT_BACKGROUND_THREAD */
9277
9278#ifdef WITH_GHOST_DBUS
9279 dbus_events_handle_pending();
9280#endif
9281
9282 const uint64_t now = getMilliSeconds();
9283 {
9284 if (getTimerManager()->fireTimers(now)) {
9285 any_processed = true;
9286 }
9287 }
9288
9289#ifdef WITH_INPUT_NDOF
9290 if (static_cast<GHOST_NDOFManagerUnix *>(ndof_manager_)->processEvents()) {
9291 /* As NDOF bypasses WAYLAND event handling,
9292 * never wait for an event when an NDOF event was found. */
9293 waitForEvent = false;
9294 any_processed = true;
9295 }
9296#endif /* WITH_INPUT_NDOF */
9297
9298 if (waitForEvent) {
9299#ifdef USE_EVENT_BACKGROUND_THREAD
9300 std::lock_guard lock_server_guard{*server_mutex};
9301#endif
9302 if (wl_display_dispatch(display_->wl.display) == -1) {
9303 ghost_wl_display_report_error(display_->wl.display);
9304 }
9305 }
9306 else {
9307#ifdef USE_EVENT_BACKGROUND_THREAD
9308 /* NOTE: this works, but as the events are being read in a thread,
9309 * this could be removed and event handling still works.. */
9310 if (server_mutex->try_lock()) {
9311 if (ghost_wl_display_event_pump(display_->wl.display) == -1) {
9312 ghost_wl_display_report_error(display_->wl.display);
9313 }
9314 server_mutex->unlock();
9315 }
9316#else
9317 if (ghost_wl_display_event_pump(display_->wl.display) == -1) {
9318 ghost_wl_display_report_error(display_->wl.display);
9319 }
9320#endif /* !USE_EVENT_BACKGROUND_THREAD */
9321 }
9322
9323 /* It's important to fire the repeat timers after handing events,
9324 * otherwise any key-release events may not have been consumed,
9325 * causing repeat events to be generated for keys the user has released, see: #151359. */
9326 {
9327#ifdef USE_EVENT_BACKGROUND_THREAD
9328 std::lock_guard lock_timer_guard{*display_->system->timer_mutex};
9329#endif
9330 if (key_repeat_timer_manager()->fireTimers(now)) {
9331 any_processed = true;
9332 }
9333 }
9334
9335 if (getEventManager()->getNumEvents() > 0) {
9336 any_processed = true;
9337 }
9338
9339 return any_processed;
9340}
9341
9343{
9344 return false;
9345}
9346
9348{
9349#ifdef USE_EVENT_BACKGROUND_THREAD
9350 std::lock_guard lock_server_guard{*server_mutex};
9351#endif
9352
9353 GWL_Seat *seat = gwl_display_seat_active_get(display_);
9354 if (!seat) [[unlikely]] {
9355 return GHOST_kFailure;
9356 }
9357
9358 /* Only read the underlying `seat->xkb_state` when there is an active window.
9359 * Without this, the following situation occurs:
9360 *
9361 * - A window is activated (before the #wl_keyboard_listener::enter has run).
9362 * - The modifiers from `seat->xkb_state` don't match `seat->key_depressed`.
9363 * - Dummy values are written into `seat->key_depressed` to account for the discrepancy
9364 * (as `seat->xkb_state` is the source of truth), however the number of held modifiers
9365 * is not longer valid (because it's not known from dummy values).
9366 * - #wl_keyboard_listener::enter runs, however the events generated from the state change
9367 * may not match the physically held keys because the dummy values are not accurate.
9368 *
9369 * As this is an edge-case caused by the order of callbacks that run on window activation,
9370 * don't attempt to *fix* the values in `seat->key_depressed` before the keyboard enter
9371 * handler runs. This means the result of `getModifierKeys` may be momentarily incorrect
9372 * however it's corrected once #wl_keyboard_listener::enter runs.
9373 */
9374 const bool is_keyboard_active = seat->keyboard.wl.surface_window != nullptr;
9375 const xkb_mod_mask_t state = is_keyboard_active ?
9376 xkb_state_serialize_mods(seat->xkb.state,
9377 XKB_STATE_MODS_DEPRESSED) :
9378 0;
9379
9380 /* Use local #GWL_KeyboardDepressedState to check which key is pressed.
9381 * Use XKB as the source of truth, if there is any discrepancy. */
9382 for (int i = 0; i < MOD_INDEX_NUM; i++) {
9383 if (seat->xkb_keymap_mod_index[i] == XKB_MOD_INVALID) [[unlikely]] {
9384 continue;
9385 }
9386
9387 const GWL_ModifierInfo &mod_info = g_modifier_info_table[i];
9388 /* NOTE(@ideasman42): it's important to write the XKB state back to #GWL_KeyboardDepressedState
9389 * otherwise changes to modifiers in the future wont generate events.
9390 * This can cause modifiers to be stuck when switching between windows in GNOME because
9391 * window activation is handled before the keyboard enter callback runs, see: #107314.
9392 * Now resolved upstream, keep this for GNOME 45 and older releases & misbehaving compositors
9393 * as the workaround doesn't have significant down-sides. */
9394 int16_t &depressed_l = seat->key_depressed.mods[GHOST_KEY_MODIFIER_TO_INDEX(mod_info.key_l)];
9395 int16_t &depressed_r = seat->key_depressed.mods[GHOST_KEY_MODIFIER_TO_INDEX(mod_info.key_r)];
9396 bool val_l = depressed_l > 0;
9397 bool val_r = depressed_r > 0;
9398
9399 if (is_keyboard_active) {
9400 const bool val = (state & (1 << seat->xkb_keymap_mod_index[i])) != 0;
9401 /* This shouldn't be needed, but guard against any possibility of modifiers being stuck.
9402 * Warn so if this happens it can be investigated. */
9403 if (val) {
9404 if (!(val_l || val_r)) [[unlikely]] {
9406 "modifier (%s) state is inconsistent (GHOST held keys do not match XKB)",
9407 mod_info.display_name);
9408
9409 /* Picking the left is arbitrary. */
9410 val_l = true;
9411 depressed_l = 1;
9412 }
9413 }
9414 else {
9415 if (val_l || val_r) [[unlikely]] {
9417 "modifier (%s) state is inconsistent (GHOST released keys do not match XKB)",
9418 mod_info.display_name);
9419 val_l = false;
9420 val_r = false;
9421 depressed_l = 0;
9422 depressed_r = 0;
9423 }
9424 }
9425 }
9426
9427 keys.set(mod_info.mod_l, val_l);
9428 keys.set(mod_info.mod_r, val_r);
9429 }
9430
9431 return GHOST_kSuccess;
9432}
9433
9435{
9436#ifdef USE_EVENT_BACKGROUND_THREAD
9437 std::lock_guard lock_server_guard{*server_mutex};
9438#endif
9439
9440 GWL_Seat *seat = gwl_display_seat_active_get(display_);
9441 if (!seat) [[unlikely]] {
9442 return GHOST_kFailure;
9443 }
9444 const GWL_SeatStatePointer *seat_state_pointer = gwl_seat_state_pointer_active(seat);
9445 if (!seat_state_pointer) {
9446 return GHOST_kFailure;
9447 }
9448
9449 buttons = seat_state_pointer->buttons;
9450 return GHOST_kSuccess;
9451}
9452
9458 const std::unordered_set<std::string> &data_offer_types)
9459{
9460 const char *ghost_supported_types[] = {ghost_wl_mime_text_utf8, ghost_wl_mime_text_plain};
9461 for (size_t i = 0; i < ARRAY_SIZE(ghost_supported_types); i++) {
9462 if (data_offer_types.contains(ghost_supported_types[i])) {
9463 return ghost_supported_types[i];
9464 }
9465 }
9466 return nullptr;
9467}
9468
9470 const bool nil_terminate,
9471 const char *mime_receive_override,
9472 size_t *r_data_len)
9473{
9474 GWL_Seat *seat = gwl_display_seat_active_get(display);
9475 if (!seat) [[unlikely]] {
9476 return nullptr;
9477 }
9478 GWL_PrimarySelection *primary = &seat->primary_selection;
9479 std::mutex &mutex = primary->data_offer_mutex;
9480
9481 mutex.lock();
9482 bool mutex_locked = true;
9483 char *data = nullptr;
9484
9485 GWL_PrimarySelection_DataOffer *data_offer = primary->data_offer;
9486 if (data_offer != nullptr) {
9487 const char *mime_receive = mime_receive_override ?
9488 mime_receive_override :
9490 GHOST_ASSERT((mime_receive_override == nullptr) ||
9491 data_offer->types.contains(mime_receive_override),
9492 "Mime type override not found in data offer, caller must check");
9493
9494 if (mime_receive) {
9495 /* Receive the clipboard in a thread, performing round-trips while waiting.
9496 * This is needed so pasting contents from our own `primary->data_source` doesn't hang. */
9497 struct ThreadResult {
9498 char *data = nullptr;
9499 size_t data_len = 0;
9500 std::atomic<bool> done = false;
9501 } thread_result;
9502 auto read_clipboard_fn = [](GWL_PrimarySelection_DataOffer *data_offer,
9503 const bool nil_terminate,
9504 const char *mime_receive,
9505 std::mutex *mutex,
9506 ThreadResult *thread_result) {
9507 thread_result->data = read_buffer_from_primary_selection_offer(
9508 data_offer, mime_receive, mutex, nil_terminate, &thread_result->data_len);
9509 thread_result->done = true;
9510 };
9511 std::thread read_thread(
9512 read_clipboard_fn, data_offer, nil_terminate, mime_receive, &mutex, &thread_result);
9513 read_thread.detach();
9514
9515 while (!thread_result.done) {
9516 wl_display_roundtrip(display->wl.display);
9517 }
9518 data = thread_result.data;
9519 *r_data_len = thread_result.data_len;
9520
9521 /* Reading the data offer unlocks the mutex. */
9522 mutex_locked = false;
9523 }
9524 }
9525 if (mutex_locked) {
9526 mutex.unlock();
9527 }
9528 return data;
9529}
9530
9531static char *system_clipboard_get(GWL_Display *display,
9532 const bool nil_terminate,
9533 const char *mime_receive_override,
9534 size_t *r_data_len)
9535{
9536 GWL_Seat *seat = gwl_display_seat_active_get(display);
9537 if (!seat) [[unlikely]] {
9538 return nullptr;
9539 }
9540 std::mutex &mutex = seat->data_offer_copy_paste_mutex;
9541
9542 mutex.lock();
9543 bool mutex_locked = true;
9544 char *data = nullptr;
9545
9546 GWL_DataOffer *data_offer = seat->data_offer_copy_paste;
9547 if (data_offer != nullptr) {
9548 const char *mime_receive = mime_receive_override ?
9549 mime_receive_override :
9551 GHOST_ASSERT((mime_receive_override == nullptr) ||
9552 data_offer->types.contains(mime_receive_override),
9553 "Mime type override not found in data offer, caller must check");
9554
9555 if (mime_receive) {
9556 /* Receive the clipboard in a thread, performing round-trips while waiting.
9557 * This is needed so pasting contents from our own `seat->data_source` doesn't hang. */
9558 struct ThreadResult {
9559 char *data = nullptr;
9560 size_t data_len = 0;
9561 std::atomic<bool> done = false;
9562 } thread_result;
9563 auto read_clipboard_fn = [](GWL_DataOffer *data_offer,
9564 const bool nil_terminate,
9565 const char *mime_receive,
9566 std::mutex *mutex,
9567 ThreadResult *thread_result) {
9568 thread_result->data = read_buffer_from_data_offer(
9569 data_offer, mime_receive, mutex, nil_terminate, &thread_result->data_len);
9570 thread_result->done = true;
9571 };
9572 std::thread read_thread(
9573 read_clipboard_fn, data_offer, nil_terminate, mime_receive, &mutex, &thread_result);
9574 read_thread.detach();
9575
9576 while (!thread_result.done) {
9577 wl_display_roundtrip(display->wl.display);
9578 }
9579 data = thread_result.data;
9580 *r_data_len = thread_result.data_len;
9581
9582 /* Reading the data offer unlocks the mutex. */
9583 mutex_locked = false;
9584 }
9585 }
9586 if (mutex_locked) {
9587 mutex.unlock();
9588 }
9589 return data;
9590}
9591
9592char *GHOST_SystemWayland::getClipboard(const bool selection) const
9593{
9594#ifdef USE_EVENT_BACKGROUND_THREAD
9595 std::lock_guard lock_server_guard{*server_mutex};
9596#endif
9597
9598 const bool nil_terminate = true;
9599 char *data = nullptr;
9600 size_t data_len = 0;
9601 if (selection) {
9602 data = system_clipboard_get_primary_selection(display_, nil_terminate, nullptr, &data_len);
9603 }
9604 else {
9605 data = system_clipboard_get(display_, nil_terminate, nullptr, &data_len);
9606 }
9607 return data;
9608}
9609
9610static void system_clipboard_put_primary_selection(GWL_Display *display, const char *buffer)
9611{
9612 if (!display->wp.primary_selection_device_manager) {
9613 return;
9614 }
9615 GWL_Seat *seat = gwl_display_seat_active_get(display);
9616 if (!seat) [[unlikely]] {
9617 return;
9618 }
9619 GWL_PrimarySelection *primary = &seat->primary_selection;
9620
9621 std::lock_guard lock{primary->data_source_mutex};
9622
9624
9626 primary->data_source = data_source;
9627
9628 /* Copy buffer. */
9629 gwl_simple_buffer_set_from_string(&data_source->buffer_out, buffer);
9630
9631 data_source->wp.source = zwp_primary_selection_device_manager_v1_create_source(
9632 display->wp.primary_selection_device_manager);
9633
9634 zwp_primary_selection_source_v1_add_listener(
9635 data_source->wp.source, &primary_selection_source_listener, primary);
9636
9637 for (size_t i = 0; i < ARRAY_SIZE(ghost_wl_mime_send); i++) {
9638 zwp_primary_selection_source_v1_offer(data_source->wp.source, ghost_wl_mime_send[i]);
9639 }
9640
9641 if (seat->wp.primary_selection_device) {
9642 zwp_primary_selection_device_v1_set_selection(
9643 seat->wp.primary_selection_device, data_source->wp.source, seat->data_source_serial);
9644 }
9645}
9646
9647static void system_clipboard_put(GWL_Display *display, const char *buffer)
9648{
9649 if (!display->wl.data_device_manager) {
9650 return;
9651 }
9652 GWL_Seat *seat = gwl_display_seat_active_get(display);
9653 if (!seat) [[unlikely]] {
9654 return;
9655 }
9656 std::lock_guard lock{seat->data_source_mutex};
9657
9658 GWL_DataSource *data_source = seat->data_source;
9659
9660 /* Copy buffer. */
9661 gwl_simple_buffer_set_from_string(&data_source->buffer_out, buffer);
9662
9663 data_source->wl.source = wl_data_device_manager_create_data_source(
9664 display->wl.data_device_manager);
9665
9666 wl_data_source_add_listener(data_source->wl.source, &data_source_listener, seat);
9667
9668 for (size_t i = 0; i < ARRAY_SIZE(ghost_wl_mime_send); i++) {
9669 wl_data_source_offer(data_source->wl.source, ghost_wl_mime_send[i]);
9670 }
9671
9672 if (seat->wl.data_device) {
9673 wl_data_device_set_selection(
9674 seat->wl.data_device, data_source->wl.source, seat->data_source_serial);
9675 }
9676}
9677
9678void GHOST_SystemWayland::putClipboard(const char *buffer, const bool selection) const
9679{
9680#ifdef USE_EVENT_BACKGROUND_THREAD
9681 std::lock_guard lock_server_guard{*server_mutex};
9682#endif
9683
9684 if (selection) {
9686 }
9687 else {
9688 system_clipboard_put(display_, buffer);
9689 }
9690}
9691
9692static constexpr const char *ghost_wl_mime_img_png = "image/png";
9693
9695{
9696#ifdef USE_EVENT_BACKGROUND_THREAD
9697 std::lock_guard lock_server_guard{*server_mutex};
9698#endif
9699
9700 GWL_Seat *seat = gwl_display_seat_active_get(display_);
9701 if (!seat) [[unlikely]] {
9702 return GHOST_kFailure;
9703 }
9704
9705 if (seat->data_offer_copy_paste_has_image.has_value()) {
9706 return *seat->data_offer_copy_paste_has_image;
9707 }
9708
9710
9711 GWL_DataOffer *data_offer = seat->data_offer_copy_paste;
9712 if (data_offer) {
9713 if (data_offer->types.contains(ghost_wl_mime_img_png)) {
9714 result = GHOST_kSuccess;
9715 }
9716 else if (data_offer->types.contains(ghost_wl_mime_text_uri_list)) {
9717 const bool nil_terminate = true;
9718 size_t data_buf_len = 0;
9719 char *data = system_clipboard_get(
9720 display_, nil_terminate, ghost_wl_mime_text_uri_list, &data_buf_len);
9721
9722 if (data) {
9723 std::vector<std::string_view> uris = gwl_clipboard_uri_ranges(data, data_buf_len);
9724 if (!uris.empty()) {
9725 const std::string_view &uri = uris.front();
9726 char *filepath = GHOST_URL_decode_alloc(uri.data(), uri.size());
9727 if (blender::IMB_test_image(filepath)) {
9728 result = GHOST_kSuccess;
9729 }
9730 free(filepath);
9731 }
9732 free(data);
9733 }
9734 }
9735 }
9736
9737 seat->data_offer_copy_paste_has_image = result;
9738
9739 return result;
9740}
9741
9742uint *GHOST_SystemWayland::getClipboardImage(int *r_width, int *r_height) const
9743{
9744#ifdef USE_EVENT_BACKGROUND_THREAD
9745 std::lock_guard lock_server_guard{*server_mutex};
9746#endif
9747
9748 GWL_Seat *seat = gwl_display_seat_active_get(display_);
9749 if (!seat) [[unlikely]] {
9750 return nullptr;
9751 }
9752
9753 uint *rgba = nullptr;
9754
9755 GWL_DataOffer *data_offer = seat->data_offer_copy_paste;
9756 if (data_offer) {
9757 blender::ImBuf *ibuf = nullptr;
9758
9759 /* Check if the source offers a supported mime type.
9760 * This check could be skipped, because the paste option is not supposed to be enabled
9761 * otherwise. */
9762 if (data_offer->types.contains(ghost_wl_mime_img_png)) {
9763 size_t data_len = 0;
9764 char *data = system_clipboard_get(display_, false, ghost_wl_mime_img_png, &data_len);
9765
9766 if (data) {
9767 /* Generate the image buffer with the received data. */
9769 (const uint8_t *)data, data_len, blender::ImBufFlags::ByteData, "<clipboard>");
9770 free(data);
9771 }
9772 }
9773 else if (data_offer->types.contains(ghost_wl_mime_text_uri_list)) {
9774 const bool nil_terminate = true;
9775 size_t data_len = 0;
9776 char *data = system_clipboard_get(
9777 display_, nil_terminate, ghost_wl_mime_text_uri_list, &data_len);
9778
9779 if (data) {
9780 std::vector<std::string_view> uris = gwl_clipboard_uri_ranges(data, data_len);
9781 if (!uris.empty()) {
9782 const std::string_view &uri = uris.front();
9783 char *filepath = GHOST_URL_decode_alloc(uri.data(), uri.size());
9785 free(filepath);
9786 }
9787 free(data);
9788 }
9789 }
9790
9791 if (ibuf) {
9792 *r_width = ibuf->x;
9793 *r_height = ibuf->y;
9794 const size_t byte_count = size_t(ibuf->x) * size_t(ibuf->y) * 4;
9795 rgba = (uint *)malloc(byte_count);
9796 std::memcpy(rgba, ibuf->byte_data(), byte_count);
9798 }
9799 }
9800
9801 return rgba;
9802}
9803
9804GHOST_TSuccess GHOST_SystemWayland::putClipboardImage(uint *rgba, int width, int height) const
9805{
9806#ifdef USE_EVENT_BACKGROUND_THREAD
9807 std::lock_guard lock_server_guard{*server_mutex};
9808#endif
9809
9810 /* Create a #wl_data_source object. */
9811 GWL_Seat *seat = gwl_display_seat_active_get(display_);
9812 if (!seat) [[unlikely]] {
9813 return GHOST_kFailure;
9814 }
9815 std::lock_guard lock(seat->data_source_mutex);
9816
9817 GWL_DataSource *data_source = seat->data_source;
9818
9819 /* Load buffer into an #ImBuf and convert to PNG. */
9821 reinterpret_cast<uint8_t *>(rgba), nullptr, width, height, 32);
9823 ibuf->foptions.quality = 15;
9826 if (encoded.is_empty()) {
9828 return GHOST_kFailure;
9829 }
9830
9831 /* Copy encoded buffer to data source. */
9832 GWL_SimpleBuffer *imgbuffer = &data_source->buffer_out;
9833 gwl_simple_buffer_free_data(imgbuffer);
9834 imgbuffer->data_size = encoded.size();
9835 char *data = static_cast<char *>(malloc(imgbuffer->data_size));
9836 std::memcpy(data, encoded.data(), encoded.size());
9837 imgbuffer->data = data;
9838
9839 data_source->wl.source = wl_data_device_manager_create_data_source(
9840 display_->wl.data_device_manager);
9841 wl_data_source_add_listener(data_source->wl.source, &data_source_listener, seat);
9842
9843 /* Advertise the mime types supported. */
9844 wl_data_source_offer(data_source->wl.source, ghost_wl_mime_img_png);
9845
9846 if (seat->wl.data_device) {
9847 wl_data_device_set_selection(
9848 seat->wl.data_device, data_source->wl.source, seat->data_source_serial);
9849 }
9850
9852 return GHOST_kSuccess;
9853}
9854
9856{
9857#ifdef USE_EVENT_BACKGROUND_THREAD
9858 std::lock_guard lock_server_guard{*server_mutex};
9859#endif
9860
9861 return display_ ? uint8_t(display_->outputs.size()) : 0;
9862}
9863
9865{
9866 /* Match the timing method used by LIBINPUT, so the result is closer to WAYLAND's time-stamps. */
9867 timespec ts = {0, 0};
9868 clock_gettime(CLOCK_MONOTONIC, &ts);
9869 return (uint64_t(ts.tv_sec) * 1000) + uint64_t(ts.tv_nsec / 1000000);
9870}
9871
9873 const GWL_SeatStatePointer *seat_state_pointer,
9874 const GHOST_WindowWayland *win,
9875 int32_t &x,
9876 int32_t &y)
9877{
9878
9879 if (win->getCursorGrabModeIsWarp()) {
9880 /* As the cursor is restored at the warped location,
9881 * apply warping when requesting the cursor location. */
9882 GHOST_Rect wrap_bounds{};
9883 if (win->getCursorGrabBounds(wrap_bounds) == GHOST_kFailure) {
9884 win->getClientBounds(wrap_bounds);
9885 }
9886 wl_fixed_t xy_wrap[2] = {
9887 seat_state_pointer->xy[0],
9888 seat_state_pointer->xy[1],
9889 };
9890
9891 GHOST_Rect wrap_bounds_scale;
9892
9893 wrap_bounds_scale.l_ = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.l_));
9894 wrap_bounds_scale.t_ = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.t_));
9895 wrap_bounds_scale.r_ = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.r_));
9896 wrap_bounds_scale.b_ = win->wl_fixed_from_window(wl_fixed_from_int(wrap_bounds.b_));
9897 wrap_bounds_scale.wrapPoint(UNPACK2(xy_wrap), 0, win->getCursorGrabAxis());
9898
9899 x = wl_fixed_to_int(win->wl_fixed_to_window(xy_wrap[0]));
9900 y = wl_fixed_to_int(win->wl_fixed_to_window(xy_wrap[1]));
9901 }
9902 else {
9903 x = wl_fixed_to_int(win->wl_fixed_to_window(seat_state_pointer->xy[0]));
9904 y = wl_fixed_to_int(win->wl_fixed_to_window(seat_state_pointer->xy[1]));
9905 }
9906
9907 return GHOST_kSuccess;
9908}
9909
9912 const int32_t x,
9913 const int32_t y)
9914{
9915 /* NOTE(@ideasman42): Regarding Cursor Warp Support:
9916 *
9917 * Before Wayland Protocols 1.45, (`wp_pointer_warp_v1`) cursor warping wasn't supported,
9918 * although at time of writing (2025) no mainstream compositors support it.
9919 * As an alternative, a software cursor is used which can be warped while "grabbed"
9920 * (see `relative_pointer` & `pointer_constraints`).
9921 * Other backends use warping to implement grabbing,
9922 * however this is error-prone with issues such as:
9923 *
9924 * - Fast motion can exit the window.
9925 * - Absolute input devices don't work with warping, causing erratic cursor motion glitches.
9926 * - Motion events may be in the queue which need to be handled before the warp is handled.
9927 *
9928 * These issues can be mitigated but avoiding problems gets involved and isn't foolproof:
9929 * Input may be clamped, tablets can be assumed absolute & motion event timestamps
9930 * can be used to detect events that were in the queue before the artificial warp motion.
9931 *
9932 * Given the trouble cursor warping has caused on other platforms over the years
9933 * I believe we're better off avoiding cursor warping (`wp_pointer_warp_v1`)
9934 * and accept limited support for warping.
9935 *
9936 * See: #134818, #113511, #102346, #89399, #82870, #49498. */
9937
9938 /* When grab is enabled, we already simulate a cursor location,
9939 * so cursor warping can be supported in this case. */
9940 if (!seat->wp.relative_pointer) {
9941 return GHOST_kFailure;
9942 }
9943 const wl_fixed_t xy_next[2]{
9944 win->wl_fixed_from_window(wl_fixed_from_int(x)),
9945 win->wl_fixed_from_window(wl_fixed_from_int(y)),
9946 };
9947
9948 /* As the cursor was "warped" generate an event at the new location. */
9949 const uint64_t event_ms = seat->system->getMilliSeconds();
9950 relative_pointer_handle_relative_motion_impl(seat, win, xy_next, event_ms);
9951
9952 return GHOST_kSuccess;
9953}
9954
9956 int32_t &x,
9957 int32_t &y) const
9958{
9959#ifdef USE_EVENT_BACKGROUND_THREAD
9960 std::lock_guard lock_server_guard{*server_mutex};
9961#endif
9962
9963 GWL_Seat *seat = gwl_display_seat_active_get(display_);
9964 if (!seat) [[unlikely]] {
9965 return GHOST_kFailure;
9966 }
9967 const GWL_SeatStatePointer *seat_state_pointer = gwl_seat_state_pointer_active(seat);
9968 if (!seat_state_pointer || !seat_state_pointer->wl.surface_window) {
9969 return GHOST_kFailure;
9970 }
9971 const GHOST_WindowWayland *win = static_cast<const GHOST_WindowWayland *>(window);
9972 return getCursorPositionClientRelative_impl(seat_state_pointer, win, x, y);
9973}
9974
9976 const int32_t x,
9977 const int32_t y)
9978{
9979#ifdef USE_EVENT_BACKGROUND_THREAD
9980 std::lock_guard lock_server_guard{*server_mutex};
9981#endif
9982
9983 GWL_Seat *seat = gwl_display_seat_active_get(display_);
9984 if (!seat) [[unlikely]] {
9985 return GHOST_kFailure;
9986 }
9987 GHOST_WindowWayland *win = static_cast<GHOST_WindowWayland *>(window);
9988 return setCursorPositionClientRelative_impl(seat, win, x, y);
9989}
9990
9992{
9993#ifdef USE_EVENT_BACKGROUND_THREAD
9994 std::lock_guard lock_server_guard{*server_mutex};
9995#endif
9996
9997 GWL_Seat *seat = gwl_display_seat_active_get(display_);
9998 if (!seat) [[unlikely]] {
9999 return GHOST_kFailure;
10000 }
10001 const GWL_SeatStatePointer *seat_state_pointer = gwl_seat_state_pointer_active(seat);
10002 if (!seat_state_pointer) {
10003 return GHOST_kFailure;
10004 }
10005
10006 if (wl_surface *wl_surface_focus = seat_state_pointer->wl.surface_window) {
10007 const GHOST_WindowWayland *win = ghost_wl_surface_user_data(wl_surface_focus);
10008 return getCursorPositionClientRelative_impl(seat_state_pointer, win, x, y);
10009 }
10010 return GHOST_kFailure;
10011}
10012
10014{
10015 /* See comments in the body of #setCursorPositionClientRelative_impl
10016 * for an explanation of the state of this functionality. */
10017
10018#ifdef USE_EVENT_BACKGROUND_THREAD
10019 std::lock_guard lock_server_guard{*server_mutex};
10020#endif
10021
10022 GWL_Seat *seat = gwl_display_seat_active_get(display_);
10023 if (!seat) [[unlikely]] {
10024 return GHOST_kFailure;
10025 }
10026
10027 /* Intentionally different from `getCursorPosition` which supports both tablet & pointer.
10028 * In the case of setting the cursor location, tablets don't support this. */
10029 if (wl_surface *wl_surface_focus = seat->pointer.wl.surface_window) {
10030 GHOST_WindowWayland *win = ghost_wl_surface_user_data(wl_surface_focus);
10031 return setCursorPositionClientRelative_impl(seat, win, x, y);
10032 }
10033 return GHOST_kFailure;
10034}
10035
10037{
10038#ifdef USE_EVENT_BACKGROUND_THREAD
10039 std::lock_guard lock_server_guard{*server_mutex};
10040#endif
10041 GWL_Seat *seat = gwl_display_seat_active_get(display_);
10042 return seat->cursor.theme_size;
10043}
10044
10045void GHOST_SystemWayland::getMainDisplayDimensions(uint32_t &width, uint32_t &height) const
10046{
10047#ifdef USE_EVENT_BACKGROUND_THREAD
10048 std::lock_guard lock_server_guard{*server_mutex};
10049#endif
10050
10051 if (!display_->outputs.empty()) {
10052 /* We assume first output as main. */
10053 const GWL_Output *output = display_->outputs[0];
10054 int32_t size_native[2] = {UNPACK2(output->size_native)};
10055 if (output->transform & WL_OUTPUT_TRANSFORM_90) {
10056 std::swap(size_native[0], size_native[1]);
10057 }
10058 width = uint32_t(size_native[0]);
10059 height = uint32_t(size_native[1]);
10060 }
10061}
10062
10063void GHOST_SystemWayland::getAllDisplayDimensions(uint32_t &width, uint32_t &height) const
10064{
10065#ifdef USE_EVENT_BACKGROUND_THREAD
10066 std::lock_guard lock_server_guard{*server_mutex};
10067#endif
10068 if (!display_->outputs.empty()) {
10069 int32_t xy_min[2] = {INT32_MAX, INT32_MAX};
10070 int32_t xy_max[2] = {INT32_MIN, INT32_MIN};
10071
10072 for (const GWL_Output *output : display_->outputs) {
10073 int32_t xy[2] = {0, 0};
10074 int32_t size_native[2] = {UNPACK2(output->size_native)};
10075 if (output->has_position_logical) {
10076 xy[0] = output->position_logical[0];
10077 xy[1] = output->position_logical[1];
10078 }
10079 if (output->transform & WL_OUTPUT_TRANSFORM_90) {
10080 std::swap(size_native[0], size_native[1]);
10081 }
10082 xy_min[0] = std::min(xy_min[0], xy[0]);
10083 xy_min[1] = std::min(xy_min[1], xy[1]);
10084 xy_max[0] = std::max(xy_max[0], xy[0] + size_native[0]);
10085 xy_max[1] = std::max(xy_max[1], xy[1] + size_native[1]);
10086 }
10087
10088 width = xy_max[0] - xy_min[0];
10089 height = xy_max[1] - xy_min[1];
10090 }
10091}
10092
10094{
10095#ifdef USE_EVENT_BACKGROUND_THREAD
10096 std::lock_guard lock_server_guard{*server_mutex};
10097#endif
10098
10099 const GHOST_ContextParams context_params_offscreen =
10101
10102 switch (gpu_settings.context_type) {
10103
10104#ifdef WITH_VULKAN_BACKEND
10105 case GHOST_kDrawingContextTypeVulkan: {
10106 /* Create new off-screen surface only for vulkan. */
10107 wl_surface *wl_surface = wl_compositor_create_surface(wl_compositor_get());
10108
10109 GHOST_Context *context = new GHOST_ContextVK(context_params_offscreen,
10110 GHOST_kVulkanPlatformWayland,
10111 0,
10112 nullptr,
10113 wl_surface,
10114 display_->wl.display,
10115 nullptr,
10116 1,
10117 1,
10118 gpu_settings.preferred_device);
10119
10120 if (context->initializeDrawingContext()) {
10121 context->setUserData(wl_surface);
10122 return context;
10123 }
10124 delete context;
10125
10126 if (wl_surface) {
10127 wl_surface_destroy(wl_surface);
10128 }
10129 return nullptr;
10130 }
10131#endif /* WITH_VULKAN_BACKEND */
10132
10133#ifdef WITH_OPENGL_BACKEND
10134 case GHOST_kDrawingContextTypeOpenGL: {
10135 /* Create new off-screen window. */
10136 wl_surface *wl_surface = wl_compositor_create_surface(wl_compositor_get());
10137 wl_egl_window *egl_window = wl_surface ? wl_egl_window_create(wl_surface, 1, 1) : nullptr;
10138
10139 for (int minor = 6; minor >= 3; --minor) {
10140 /* Caller must lock `system->server_mutex`. */
10141 GHOST_Context *context = new GHOST_ContextEGL(
10142 this,
10143 context_params_offscreen,
10144 EGLNativeWindowType(egl_window),
10145 EGLNativeDisplayType(display_->wl.display),
10146 EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
10147 4,
10148 minor,
10150 (context_params_offscreen.is_debug ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : 0),
10152 EGL_OPENGL_API);
10153
10154 if (context->initializeDrawingContext()) {
10155 wl_surface_set_user_data(wl_surface, egl_window);
10156 context->setUserData(wl_surface);
10157 return context;
10158 }
10159 delete context;
10160 }
10161
10162 GHOST_PRINT("Cannot create off-screen EGL context" << std::endl);
10163 if (wl_surface) {
10164 wl_surface_destroy(wl_surface);
10165 }
10166 if (egl_window) {
10167 wl_egl_window_destroy(egl_window);
10168 }
10169 return nullptr;
10170 }
10171#endif /* WITH_OPENGL_BACKEND */
10172
10173 default: {
10174 /* Unsupported backend. */
10175 return nullptr;
10176 }
10177 }
10178}
10179
10181{
10182#ifdef USE_EVENT_BACKGROUND_THREAD
10183 std::lock_guard lock_server_guard{*server_mutex};
10184#endif
10185
10187#ifdef WITH_OPENGL_BACKEND
10188 if (dynamic_cast<GHOST_ContextEGL *>(context)) {
10189 type = GHOST_kDrawingContextTypeOpenGL;
10190 }
10191#endif /* WITH_OPENGL_BACKEND */
10192#ifdef WITH_VULKAN_BACKEND
10193 if (dynamic_cast<GHOST_ContextVK *>(context)) {
10194 type = GHOST_kDrawingContextTypeVulkan;
10195 }
10196#endif /* WITH_VULKAN_BACKEND */
10197
10198 wl_surface *wl_surface = static_cast<struct wl_surface *>(
10199 (static_cast<GHOST_Context *>(context))->getUserData());
10200
10201 /* Delete the context before the window so the context is able to release
10202 * native resources (such as the #EGLSurface) before WAYLAND frees them. */
10203 delete context;
10204
10205#ifdef WITH_OPENGL_BACKEND
10206 if (type == GHOST_kDrawingContextTypeOpenGL) {
10207 wl_egl_window *egl_window = static_cast<wl_egl_window *>(wl_surface_get_user_data(wl_surface));
10208 if (egl_window != nullptr) {
10209 wl_egl_window_destroy(egl_window);
10210 }
10211 }
10212#endif /* WITH_OPENGL_BACKEND */
10213
10214 wl_surface_destroy(wl_surface);
10215
10216 (void)type; /* Maybe unused. */
10217
10218 return GHOST_kSuccess;
10219}
10220
10222 const int32_t left,
10223 const int32_t top,
10224 const uint32_t width,
10225 const uint32_t height,
10227 const GHOST_GPUSettings gpu_settings,
10228 const bool exclusive,
10229 const bool is_dialog,
10230 const GHOST_IWindow *parent_window)
10231{
10232 const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings);
10233
10234#ifdef WITH_GHOST_DBUS
10235 /* The desktop settings decide the decorations, apply them before the first window draws.
10236 * Normally the values have arrived long before now so this doesn't wait. */
10237 if (dbus_watcher_) {
10238 dbus_watcher_->wait_initial(dbus_initial_timeout_ms);
10239 dbus_events_handle_pending();
10240 }
10241#endif
10242
10243 /* Globally store pointer to window manager. */
10244 GHOST_WindowWayland *window = new GHOST_WindowWayland(this,
10245 title,
10246 left,
10247 top,
10248 width,
10249 height,
10250 state,
10251 parent_window,
10252 gpu_settings.context_type,
10253 is_dialog,
10254 context_params,
10255 exclusive,
10256 gpu_settings.preferred_device);
10257
10258 if (window) {
10259 if (window->getValid()) {
10260 window_manager_->addWindow(window);
10262 const uint64_t event_ms = getMilliSeconds();
10263 pushEvent(std::make_unique<GHOST_Event>(event_ms, GHOST_kEventWindowSize, window));
10264 }
10265 else {
10266 delete window;
10267 window = nullptr;
10268 }
10269 }
10270
10271 return window;
10272}
10273
10274static bool cursor_is_software(const GHOST_TGrabCursorMode mode, const bool use_software_confine)
10275{
10276 if (mode == GHOST_kGrabWrap) {
10277 return true;
10278 }
10279#ifdef USE_GNOME_CONFINE_HACK
10280 if (mode == GHOST_kGrabNormal) {
10281 if (use_software_confine) {
10282 return true;
10283 }
10284 }
10285#else
10286 (void)use_software_confine;
10287#endif
10288 return false;
10289}
10290
10292{
10293 /* Caller must lock `server_mutex`. */
10294
10295 GWL_Seat *seat = gwl_display_seat_active_get(display_);
10296 if (!seat) [[unlikely]] {
10297 return GHOST_kFailure;
10298 }
10299
10300 if (!display_->wp.cursor_shape_manager) {
10301 return GHOST_kFailure;
10302 }
10303
10304 const std::optional<wp_cursor_shape_device_v1_shape> wl_shape =
10306 if (wl_shape == std::nullopt) {
10307 return GHOST_kFailure;
10308 }
10309
10310 if (seat->wl.pointer) {
10311 /* Set cursor for the pointer device. */
10312 if (seat->cursor.shape.device == nullptr) {
10313 seat->cursor.shape.device = wp_cursor_shape_manager_v1_get_pointer(
10314 display_->wp.cursor_shape_manager, seat->wl.pointer);
10315 }
10316 if (seat->cursor.shape.device) {
10317 if (seat->cursor.is_hardware) {
10318 wp_cursor_shape_device_v1_set_shape(
10319 seat->cursor.shape.device, seat->pointer.serial, *wl_shape);
10320 }
10321 }
10322 /* Set this to make sure we remember which shape we set when unhiding cursors. */
10323 seat->cursor.shape.enum_id = *wl_shape;
10324
10325 GWL_Cursor *cursor = &seat->cursor;
10326 cursor->visible = true;
10327 cursor->is_custom = false;
10328 }
10329
10330 /* Set cursor for all tablet tool devices. */
10331 for (zwp_tablet_tool_v2 *zwp_tablet_tool_v2 : seat->wp.tablet_tools) {
10332 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(
10333 zwp_tablet_tool_v2_get_user_data(zwp_tablet_tool_v2));
10334 if (tablet_tool->shape.device == nullptr) {
10335 tablet_tool->shape.device = wp_cursor_shape_manager_v1_get_tablet_tool_v2(
10336 display_->wp.cursor_shape_manager, zwp_tablet_tool_v2);
10337 }
10338 if (tablet_tool->shape.device) {
10339 if (seat->cursor.is_hardware) {
10340 wp_cursor_shape_device_v1_set_shape(
10341 tablet_tool->shape.device, tablet_tool->serial, *wl_shape);
10342 }
10343 }
10344 /* Set this to make sure we remember which shape we set when unhiding cursors. */
10345 tablet_tool->shape.enum_id = *wl_shape;
10346 }
10347 return GHOST_kSuccess;
10348}
10349
10351{
10352 /* No need to lock `server_mutex`. */
10353 GWL_Seat *seat = gwl_display_seat_active_get(display_);
10354 if (!seat) [[unlikely]] {
10355 return GHOST_kFailure;
10356 }
10357
10358 if (!display_->wp.cursor_shape_manager) {
10359 return GHOST_kFailure;
10360 }
10361
10362 const std::optional<wp_cursor_shape_device_v1_shape> wl_shape =
10364 if (wl_shape == std::nullopt) {
10365 return GHOST_kFailure;
10366 }
10367 return GHOST_kSuccess;
10368}
10369
10371 wl_shm *shm,
10372 void **buffer_data_p,
10373 size_t *buffer_data_size_p,
10374 const int cursor_size,
10375 const int cursor_size_max,
10376 const int use_dark_theme,
10377 const int scale,
10378 int r_bitmap_size[2],
10379 int r_hot_spot[2])
10380{
10381 if (*buffer_data_p) {
10382 munmap(*buffer_data_p, *buffer_data_size_p);
10383 *buffer_data_p = nullptr;
10384 *buffer_data_size_p = 0; /* Not needed, but the value is no longer meaningful. */
10385 }
10386
10387 int bitmap_size_src[2];
10388 int hot_spot[2];
10389 bool can_invert_color = false;
10390
10391 uint8_t *bitmap_src = cg.generate_fn(
10392 &cg,
10393 cursor_size,
10394 cursor_size_max,
10395 [](size_t size) -> uint8_t * { return new uint8_t[size]; },
10396 bitmap_size_src,
10397 hot_spot,
10398 &can_invert_color);
10399
10400 if (bitmap_src == nullptr) {
10401 return nullptr;
10402 }
10403
10404 const bool invert_color = can_invert_color && use_dark_theme;
10405
10406 /* There is no need to adjust the hot-spot when resizing. */
10407 int bitmap_size_dst[2] = {
10408 int(round_up_uint(bitmap_size_src[0], scale)),
10409 int(round_up_uint(bitmap_size_src[1], scale)),
10410 };
10411
10412 wl_buffer *buffer = ghost_wl_buffer_create_for_image(
10413 shm, bitmap_size_dst, WL_SHM_FORMAT_ARGB8888, buffer_data_p, buffer_data_size_p);
10414
10415 if (buffer != nullptr) {
10416 const bool is_trivial_copy = (bitmap_size_src[0] == bitmap_size_dst[0]) &&
10417 (bitmap_size_src[1] == bitmap_size_dst[1]);
10418 /* NOTE: the copy could be skipped in trivial cases.
10419 * Since it's such a small amount of data it hardly seems worth it. */
10420 if (is_trivial_copy) {
10421 /* RGBA color. */
10422 const uint32_t *px_src = reinterpret_cast<const uint32_t *>(bitmap_src);
10423 uint32_t *px_dst = static_cast<uint32_t *>(*buffer_data_p);
10424 if (invert_color) {
10425 for (int y = 0; y < bitmap_size_src[1]; y++) {
10426 for (int x = 0; x < bitmap_size_src[0]; x++) {
10427 *px_dst++ = rgba_straight_to_premul_inverted(*px_src++);
10428 }
10429 }
10430 }
10431 else {
10432 for (int y = 0; y < bitmap_size_src[1]; y++) {
10433 for (int x = 0; x < bitmap_size_src[0]; x++) {
10434 *px_dst++ = rgba_straight_to_premul(*px_src++);
10435 }
10436 }
10437 }
10438 }
10439 else {
10440 /* RGBA color, copy into an expanded buffer. */
10441 const uint32_t *px_src = reinterpret_cast<const uint32_t *>(bitmap_src);
10442 uint32_t *px_dst = static_cast<uint32_t *>(*buffer_data_p);
10443 if (invert_color) {
10444 for (int y = 0; y < bitmap_size_dst[1]; y++) {
10445 for (int x = 0; x < bitmap_size_dst[0]; x++) {
10446 *px_dst++ = (x >= bitmap_size_src[0] || y >= bitmap_size_src[1]) ?
10447 0x0 :
10449 }
10450 }
10451 }
10452 else {
10453 for (int y = 0; y < bitmap_size_dst[1]; y++) {
10454 for (int x = 0; x < bitmap_size_dst[0]; x++) {
10455 *px_dst++ = (x >= bitmap_size_src[0] || y >= bitmap_size_src[1]) ?
10456 0x0 :
10457 rgba_straight_to_premul(*px_src++);
10458 }
10459 }
10460 }
10461 }
10462
10463 r_bitmap_size[0] = bitmap_size_dst[0];
10464 r_bitmap_size[1] = bitmap_size_dst[1];
10465
10466 r_hot_spot[0] = hot_spot[0];
10467 r_hot_spot[1] = hot_spot[1];
10468 }
10469
10470 delete[] bitmap_src;
10471 return buffer;
10472}
10473
10475{
10476 /* Caller needs to lock `server_mutex`. */
10477 GWL_Seat *seat = gwl_display_seat_active_get(display_);
10478 if (!seat) [[unlikely]] {
10479 return GHOST_kFailure;
10480 }
10481 /* If we were using a wayland cursor shape, be sure to free it up before we try to use any
10482 * custom shapes. */
10483 if (seat->cursor.shape.device) {
10484 wp_cursor_shape_device_v1_destroy(seat->cursor.shape.device);
10485 seat->cursor.shape.device = nullptr;
10486 }
10487
10488 /* If we were using a wayland cursor shape, be sure to free it for the tablet tools
10489 * before we try to use any custom shapes. */
10490 for (zwp_tablet_tool_v2 *zwp_tablet_tool_v2 : seat->wp.tablet_tools) {
10491 GWL_TabletTool *tablet_tool = static_cast<GWL_TabletTool *>(
10492 zwp_tablet_tool_v2_get_user_data(zwp_tablet_tool_v2));
10493 if (tablet_tool->shape.device) {
10494 wp_cursor_shape_device_v1_destroy(tablet_tool->shape.device);
10495 tablet_tool->shape.device = nullptr;
10496 }
10497 }
10498
10499 /* Generate the buffer. */
10500 GWL_Cursor &cursor = seat->cursor;
10501
10502 int bitmap_size[2] = {0, 0};
10503 int hot_spot[2] = {0, 0};
10504
10505 const int scale = gwl_seat_cursor_buffer_scale_calc(seat);
10506 const int cursor_size = seat->cursor.theme_size * scale;
10507 /* NOTE: Regarding the maximum cursor size.
10508 * - 256 seems to be a hardware limit.
10509 * - Twice the cursor size to allow "text" cursor to display wider than a typical cursor
10510 * without being *very* large - as that looks strange.
10511 */
10512 const int cursor_size_max = std::min(256, cursor_size * 2);
10513
10514 wl_buffer *buffer = ghost_wl_buffer_from_cursor_generator(cg,
10515 display_->wl.shm,
10516 &cursor.custom_data,
10517 &cursor.custom_data_size,
10518 cursor_size,
10519 cursor_size_max,
10520 cursor.use_dark_theme,
10521 scale,
10522 bitmap_size,
10523 hot_spot);
10524 if (buffer == nullptr) [[unlikely]] {
10525 return GHOST_kFailure;
10526 }
10527
10528 wl_buffer_add_listener(buffer, &cursor_buffer_listener, &cursor);
10529
10530 cursor.visible = true;
10531 cursor.is_custom = true;
10532
10533 cursor.wl.buffer = buffer;
10534 cursor.wl.image.width = uint32_t(bitmap_size[0]);
10535 cursor.wl.image.height = uint32_t(bitmap_size[1]);
10536 cursor.wl.image.hotspot_x = uint32_t(hot_spot[0]);
10537 cursor.wl.image.hotspot_y = uint32_t(hot_spot[1]);
10538
10540
10541 return GHOST_kSuccess;
10542}
10543
10545{
10546 /* Caller must lock `server_mutex`. */
10547 GWL_Seat *seat = gwl_display_seat_active_get(display_);
10548 if (!seat) [[unlikely]] {
10549 return GHOST_kFailure;
10550 }
10551
10552 GWL_Cursor *cursor = &seat->cursor;
10553 if (cursor->custom_data == nullptr) {
10554 return GHOST_kFailure;
10555 }
10556 if (!cursor->is_custom) {
10557 return GHOST_kFailure;
10558 }
10559
10560 bitmap->data_size[0] = cursor->wl.image.width;
10561 bitmap->data_size[1] = cursor->wl.image.height;
10562
10563 bitmap->hot_spot[0] = cursor->wl.image.hotspot_x;
10564 bitmap->hot_spot[1] = cursor->wl.image.hotspot_y;
10565
10566 bitmap->data = static_cast<const uint8_t *>(cursor->custom_data);
10567
10568 return GHOST_kSuccess;
10569}
10570
10572{
10573 /* Caller must lock `server_mutex`. */
10574 GWL_Seat *seat = gwl_display_seat_active_get(display_);
10575 if (!seat) [[unlikely]] {
10576 return GHOST_kFailure;
10577 }
10578
10580 return GHOST_kSuccess;
10581}
10582
10584{
10585 /* It's possible there are no seats, ignore the value in this case. */
10586 GHOST_ASSERT(((gwl_display_seat_active_get(display_) == nullptr) ||
10588 "The trackpad direction was expected to be initialized");
10589
10590 return GHOST_TCapabilityFlag(
10592 /* NOTE: order the following flags as they they're declared in the source. */
10593 ~(
10594 /* WAYLAND doesn't support accessing the window position. */
10596 /* WAYLAND cannot precisely place windows among multiple monitors. */
10598 /* WAYLAND doesn't support setting the cursor position directly,
10599 * this is an intentional choice, forcing us to use a software cursor in this case.
10600 * For details see comments in: #setCursorPositionClientRelative_impl. */
10602 /* Some drivers don't support front-buffer reading, see: #98462 & #106264.
10603 *
10604 * NOTE(@ideasman42): the EGL flag `EGL_BUFFER_PRESERVED` is intended request support for
10605 * front-buffer reading however in my tests requesting the flag didn't work with AMD,
10606 * and it's not even requirement - so we can't rely on this feature being supported.
10607 *
10608 * Instead of assuming this is not supported, the graphics card driver could be inspected
10609 * (enable for NVIDIA for example), but the advantage in supporting this is minimal.
10610 * In practice it means an off-screen buffer is used to redraw the window for the
10611 * screen-shot and eye-dropper sampling logic, both operations where the overhead
10612 * is negligible. */
10614 /* This WAYLAND back-end has not yet implemented desktop color sample. */
10616 /* This flag will eventually be removed when support
10617 * for the old track-pad protocol is dropped. */
10619 0 :
10621 /* The title bar is drawn by Blender itself via CSD, so the backend does not need to
10622 * support this. */
10624 /* No support for window path meta-data. */
10626 /* Check if we should use Client Side Decorations (CSD.) */
10628}
10629
10631{
10632 /* Caller must lock `server_mutex`. */
10633 const GWL_Seat *seat = gwl_display_seat_active_get(display_);
10634 if (!seat) [[unlikely]] {
10635 return false;
10636 }
10637
10638#ifdef USE_GNOME_CONFINE_HACK
10639 const bool use_software_confine = seat->use_pointer_software_confine;
10640#else
10641 const bool use_software_confine = false;
10642#endif
10643
10644 return cursor_is_software(mode, use_software_confine);
10645}
10646
10647#ifdef USE_GNOME_CONFINE_HACK
10650{
10651# ifndef USE_GNOME_CONFINE_HACK_ALWAYS_ON
10652 if (use_gnome_confine_hack == false) {
10653 return false;
10654 }
10655# endif
10656 if (mode != GHOST_kGrabNormal) {
10657 return false;
10658 }
10660 if (!win) {
10661 return false;
10662 }
10663
10664# ifndef USE_GNOME_CONFINE_HACK_ALWAYS_ON
10665 if (win->scale_get() <= 1) {
10666 return false;
10667 }
10668# endif
10669 return true;
10670}
10671#endif
10672
10674 const bool use_software_confine)
10675{
10676 /* Initialize all members. */
10677 GWL_SeatStateGrab grab_state;
10678 /* Warping happens to require software cursor which also hides. */
10679 grab_state.use_lock = ELEM(mode, GHOST_kGrabWrap, GHOST_kGrabHide) || use_software_confine;
10680 grab_state.use_confine = (mode == GHOST_kGrabNormal) && (use_software_confine == false);
10681 return grab_state;
10682}
10683
10685{
10686 if (multitouch_gestures_ == use) {
10687 return;
10688 }
10690
10691#ifdef USE_EVENT_BACKGROUND_THREAD
10692 /* Ensure this listeners aren't removed while events are generated. */
10693 std::lock_guard lock_server_guard{*server_mutex};
10694#endif
10695 for (GWL_Seat *seat : display_->seats) {
10696 if (use == gwl_seat_capability_pointer_multitouch_check(seat, use)) {
10697 continue;
10698 }
10699 if (use) {
10701 }
10702 else {
10704 }
10705 }
10706}
10707
10709
10710/* -------------------------------------------------------------------- */
10713
10714static const char *ghost_wl_output_tag_id = "GHOST-output";
10715static const char *ghost_wl_surface_tag_id = "GHOST-window";
10716static const char *ghost_wl_surface_cursor_pointer_tag_id = "GHOST-cursor-pointer";
10717static const char *ghost_wl_surface_cursor_tablet_tag_id = "GHOST-cursor-tablet";
10718#ifdef WITH_GHOST_CSD
10719static const char *ghost_wl_surface_csd_margin_tag_id = "GHOST-csd-margin";
10720#endif
10721
10722bool ghost_wl_output_own(const wl_output *wl_output)
10723{
10724 const wl_proxy *proxy = reinterpret_cast<const wl_proxy *>(wl_output);
10725 return wl_proxy_get_tag(const_cast<wl_proxy *>(proxy)) == &ghost_wl_output_tag_id;
10726}
10727
10729{
10730 const wl_proxy *proxy = reinterpret_cast<const wl_proxy *>(wl_surface);
10731 return wl_proxy_get_tag(const_cast<wl_proxy *>(proxy)) == &ghost_wl_surface_tag_id;
10732}
10733
10738
10740{
10741 const wl_proxy *proxy = reinterpret_cast<const wl_proxy *>(wl_surface);
10742 return wl_proxy_get_tag(const_cast<wl_proxy *>(proxy)) ==
10744}
10745
10747{
10748 const wl_proxy *proxy = reinterpret_cast<const wl_proxy *>(wl_surface);
10749 return wl_proxy_get_tag(const_cast<wl_proxy *>(proxy)) == &ghost_wl_surface_cursor_tablet_tag_id;
10750}
10751
10752#ifdef WITH_GHOST_CSD
10753bool ghost_wl_surface_own_csd_margin(const wl_surface *wl_surface)
10754{
10755 const wl_proxy *proxy = reinterpret_cast<const wl_proxy *>(wl_surface);
10756 return wl_proxy_get_tag(const_cast<wl_proxy *>(proxy)) == &ghost_wl_surface_csd_margin_tag_id;
10757}
10758#endif
10759
10760void ghost_wl_output_tag(wl_output *wl_output)
10761{
10762 wl_proxy *proxy = reinterpret_cast<wl_proxy *>(wl_output);
10764}
10765
10767{
10768 wl_proxy *proxy = reinterpret_cast<wl_proxy *>(wl_surface);
10770}
10771
10773{
10774 wl_proxy *proxy = reinterpret_cast<wl_proxy *>(wl_surface);
10776}
10777
10779{
10780 wl_proxy *proxy = reinterpret_cast<wl_proxy *>(wl_surface);
10782}
10783
10784#ifdef WITH_GHOST_CSD
10785void ghost_wl_surface_tag_csd_margin(wl_surface *wl_surface)
10786{
10787 wl_proxy *proxy = reinterpret_cast<wl_proxy *>(wl_surface);
10788 wl_proxy_set_tag(proxy, &ghost_wl_surface_csd_margin_tag_id);
10789}
10790#endif
10791
10793
10794/* -------------------------------------------------------------------- */
10799
10801{
10802 return display_->wl.display;
10803}
10804
10806{
10807 return display_->wl.compositor;
10808}
10809
10811{
10812 return display_->wl.subcompositor;
10813}
10814
10815zwp_primary_selection_device_manager_v1 *GHOST_SystemWayland::wp_primary_selection_manager_get()
10816{
10817 return display_->wp.primary_selection_device_manager;
10818}
10819
10821{
10822 return display_->xdg.activation_manager;
10823}
10824
10826{
10827 return display_->wp.fractional_scale_manager;
10828}
10830{
10831 return display_->wp.viewporter;
10832}
10834{
10835 return display_->wp.color_manager;
10836}
10838{
10839 return display_->wp.color_manager_queue;
10840}
10842{
10843 return display_->supports_color_manager_feature_windows_scrgb;
10844}
10846{
10847 return display_->supports_color_manager_extended_srgb_linear;
10848}
10849
10851{
10852 return display_->wp.pointer_gestures;
10853}
10854
10855/* This value is expected to match the base name of the `.desktop` file. see #101805.
10856 *
10857 * NOTE: the XDG desktop-entry-spec defines that this should follow the "reverse DNS" convention.
10858 * For example `org.blender.Blender` - however the `.desktop` file distributed with Blender is
10859 * simply called `blender.desktop`, so the it's important to follow that name.
10860 * Other distributions such as SNAP & FLATPAK may need to change this value #101779.
10861 * Currently there isn't a way to configure this, we may want to support that. */
10862static const char *ghost_wl_app_id = (
10863#ifdef WITH_GHOST_WAYLAND_APP_ID
10864 STRINGIFY(WITH_GHOST_WAYLAND_APP_ID)
10865#else
10866 "blender"
10867#endif
10868);
10869
10871{
10872 return ghost_wl_app_id;
10873}
10874
10876{
10877 return display_->xdg_decor->shell;
10878}
10879
10881{
10882 return display_->xdg_decor->manager;
10883}
10884
10885/* End `xdg_decor`. */
10886
10887const std::span<GWL_Output *const> GHOST_SystemWayland::outputs_get() const
10888{
10889 return display_->outputs;
10890}
10891
10893{
10894 return display_->wl.shm;
10895}
10896
10898{
10899 return display_->key_repeat_timer_manager;
10900}
10901
10903 xdg_toplevel *toplevel)
10904{
10905 /* Called during window creation and when the window scale changes. */
10906 xdg_toplevel_icon_manager_v1 *icon_manager = display_->xdg.toplevel_icon_manager;
10907 if (icon_manager == nullptr) {
10908 return;
10909 }
10910
10911 if (icon_generator_ == nullptr) {
10912 return;
10913 }
10914
10915 const int icon_logical_size = display_->xdg.toplevel_icon_logical_size_max > 0 ?
10916 display_->xdg.toplevel_icon_logical_size_max :
10917 32;
10918
10919 /* The icon size from the compositor is in logical coordinates,
10920 * scale to physical pixels using the window's scale. */
10921 int buffer_scale;
10922 const int icon_pixel_size = gwl_window_scale_buffer_size_to(
10923 window->scale_params_get(), icon_logical_size, &buffer_scale);
10924 GHOST_ASSERT(icon_pixel_size > 0, "Scale must be initialized before setting the icon!");
10925
10926 GWL_XDG_WindowIcon &icon = window->gwl_xdg_icon_get();
10927
10928 /* Re-generate the buffer if the size has changed or this is the first call. */
10929 if (icon.icon_pixel_size != icon_pixel_size) {
10931
10932 const int32_t size_xy[2] = {icon_pixel_size, icon_pixel_size};
10933 void *buffer_data = nullptr;
10934 size_t buffer_data_size = 0;
10935 wl_buffer *buffer = ghost_wl_buffer_create_for_image(
10936 display_->wl.shm, size_xy, WL_SHM_FORMAT_ARGB8888, &buffer_data, &buffer_data_size);
10937 /* SHM buffer allocation should practically never fail. */
10938 if (buffer == nullptr) [[unlikely]] {
10939 return;
10940 }
10941
10942 /* The callback fills an RGBA (straight alpha) buffer.
10943 * Convert to pre-multiplied ARGB for the Wayland SHM format,
10944 * swapping R and B since ARGB8888 stores B,G,R,A bytes on little-endian. */
10945 const int pixel_count = icon_pixel_size * icon_pixel_size;
10947 icon_generator_, window, static_cast<uint8_t *>(buffer_data), icon_pixel_size);
10948 uint32_t *pixels = static_cast<uint32_t *>(buffer_data);
10949 for (int i = 0; i < pixel_count; i++) {
10950 uint8_t *bytes = reinterpret_cast<uint8_t *>(&pixels[i]);
10951 std::swap(bytes[0], bytes[2]);
10952 pixels[i] = rgba_straight_to_premul(pixels[i]);
10953 }
10954
10955 /* Keep the buffer for reuse if this function is called again at the same size. */
10956 icon.buffer = buffer;
10957 icon.buffer_data = buffer_data;
10958 icon.buffer_size = buffer_data_size;
10959 icon.icon_pixel_size = icon_pixel_size;
10960 }
10961
10962 xdg_toplevel_icon_v1 *toplevel_icon = xdg_toplevel_icon_manager_v1_create_icon(icon_manager);
10963 xdg_toplevel_icon_v1_add_buffer(toplevel_icon, icon.buffer, buffer_scale);
10964 xdg_toplevel_icon_manager_v1_set_icon(icon_manager, toplevel, toplevel_icon);
10965 xdg_toplevel_icon_v1_destroy(toplevel_icon);
10966}
10967
10969{
10970 return display_->use_window_frame;
10971}
10972
10974{
10975 return display_->use_window_frame_csd;
10976}
10977
10979{
10980 return display_->preferences.cursor_size;
10981}
10982
10983#ifdef WITH_GHOST_CSD
10984const GHOST_CSD_Layout &GHOST_SystemWayland::preferences_csd_button_layout_get() const
10985{
10986 return display_->preferences.csd_button_layout;
10987}
10988
10989# ifdef WITH_GHOST_DBUS
10990static bool csd_layout_is_equal(const GHOST_CSD_Layout &a, const GHOST_CSD_Layout &b)
10991{
10992 return (a.buttons_num == b.buttons_num) &&
10993 std::equal(a.buttons, a.buttons + a.buttons_num, b.buttons);
10994}
10995# endif /* WITH_GHOST_DBUS */
10996#endif /* WITH_GHOST_CSD */
10997
10999
11000/* -------------------------------------------------------------------- */
11005
11006#ifdef WITH_INPUT_IME
11007
11009 const int32_t x,
11010 const int32_t y,
11011 const int32_t w,
11012 const int32_t h,
11013 const bool completed) const
11014{
11015 GWL_Seat *seat = gwl_display_seat_active_get(display_);
11016 if (!seat) [[unlikely]] {
11017 return;
11018 }
11019 if (seat->wp.text_input == nullptr) {
11020 return;
11021 }
11022
11023 /* Prevent a feedback loop because the commits from this function cause
11024 * #zwp_text_input_v3_listener::preedit_string to run again which sends an event,
11025 * refreshing the position, running this function again. */
11026 gwl_seat_ime_result_reset(seat);
11027
11028 /* Don't re-enable if we're already enabled. */
11029 if (seat->ime.is_enabled && completed) {
11030 return;
11031 }
11032
11033 bool force_rect_update = false;
11034 if (seat->ime.is_enabled == false) {
11035 seat->ime.has_preedit = false;
11036 seat->ime.is_enabled = true;
11037
11038 /* Don't commit here, bundle enable + cursor rectangle into a single commit below.
11039 * Otherwise the proper location wont be used. */
11040 zwp_text_input_v3_enable(seat->wp.text_input);
11041
11042 /* Now that it's enabled, set the input properties. */
11043 zwp_text_input_v3_set_content_type(seat->wp.text_input,
11044 ZWP_TEXT_INPUT_V3_CONTENT_HINT_NONE,
11045 ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_NORMAL);
11046
11047 gwl_seat_ime_rect_reset(seat);
11048 force_rect_update = true;
11049 }
11050
11051 if ((force_rect_update == false) && /* Was just created, always update. */
11052 (seat->ime.rect.x == x) && /* X. */
11053 (seat->ime.rect.y == y) && /* Y. */
11054 (seat->ime.rect.w == w) && /* W. */
11055 (seat->ime.rect.h == h)) /* H. */
11056 {
11057 /* Only re-update the rectangle as needed. */
11058 }
11059 else {
11060 const int rect_x = wl_fixed_to_int(win->wl_fixed_from_window(wl_fixed_from_int(x)));
11061 const int rect_y = wl_fixed_to_int(win->wl_fixed_from_window(wl_fixed_from_int(y)));
11062 const int rect_w = wl_fixed_to_int(win->wl_fixed_from_window(wl_fixed_from_int(w))) + 1;
11063 const int rect_h = wl_fixed_to_int(win->wl_fixed_from_window(wl_fixed_from_int(h))) + 1;
11064
11065 zwp_text_input_v3_set_cursor_rectangle(seat->wp.text_input, rect_x, rect_y, rect_w, rect_h);
11066
11067 zwp_text_input_v3_commit(seat->wp.text_input);
11068
11069 seat->ime.rect.x = x;
11070 seat->ime.rect.y = y;
11071 seat->ime.rect.w = w;
11072 seat->ime.rect.h = h;
11073 }
11074}
11075
11076void GHOST_SystemWayland::ime_end(const GHOST_WindowWayland * /*window*/) const
11077{
11078 GWL_Seat *seat = gwl_display_seat_active_get(display_);
11079 if (!seat) [[unlikely]] {
11080 return;
11081 }
11082
11083 seat->ime.is_enabled = false;
11084
11085 gwl_seat_ime_rect_reset(seat);
11086
11087 if (seat->wp.text_input == nullptr) {
11088 return;
11089 }
11090
11091 zwp_text_input_v3_disable(seat->wp.text_input);
11092 zwp_text_input_v3_commit(seat->wp.text_input);
11093}
11094
11095#endif /* WITH_INPUT_IME */
11096
11098
11099/* -------------------------------------------------------------------- */
11102
11104{
11105 GHOST_ASSERT(wl_output, "output must not be nullptr");
11106 GHOST_ASSERT(ghost_wl_output_own(wl_output), "output is not owned by GHOST");
11107 GWL_Output *output = static_cast<GWL_Output *>(wl_output_get_user_data(wl_output));
11108 return output;
11109}
11110
11112{
11113 GHOST_ASSERT(wl_surface, "wl_surface must not be nullptr");
11114 GHOST_ASSERT(ghost_wl_surface_own(wl_surface), "wl_surface is not owned by GHOST");
11115 GHOST_WindowWayland *win = static_cast<GHOST_WindowWayland *>(
11116 wl_surface_get_user_data(wl_surface));
11117 return win;
11118}
11119
11121
11122/* -------------------------------------------------------------------- */
11127
11128#ifdef WITH_GHOST_DBUS
11129void GHOST_SystemWayland::dbus_watcher_start(const bool watch_cursor_size)
11130{
11131 dbus_watcher_ = std::make_unique<GHOST_SystemDBusUnix>();
11132 display_->dbus.events.reserve(dbus_events_default_size);
11133 dbus_watcher_->setting_add(
11134 "org.freedesktop.appearance", "color-scheme", [this](const GHOST_DBusValue &value) {
11135 const uint32_t *value_uint = std::get_if<uint32_t>(&value);
11136 if (!value_uint) {
11137 return;
11138 }
11139 if (dbus_.color_scheme.exchange(*value_uint) == *value_uint) {
11140 return;
11141 }
11142 CLOG_INFO(&LOG, "XDG: color-scheme changed: %u", *value_uint);
11143 });
11144 if (watch_cursor_size) {
11145 const auto on_change = [this](const GHOST_DBusValue &value) {
11146 const int32_t *value_int = std::get_if<int32_t>(&value);
11147 if (!value_int || (*value_int <= 0)) {
11148 return;
11149 }
11150 this->dbus_event_push(GWL_DBusEvent{
11151 .data =
11152 GWL_DBusEvent::CursorSize{
11153 .size = *value_int,
11154 },
11155 });
11156 };
11157 dbus_watcher_->setting_add("org.gnome.desktop.interface", "cursor-size", on_change);
11158 }
11159# ifdef WITH_GHOST_CSD
11160 if (display_->use_window_frame_csd) {
11161 const auto on_change = [this](const GHOST_DBusValue &value) {
11162 const std::string *value_str = std::get_if<std::string>(&value);
11163 if (!value_str) {
11164 return;
11165 }
11166 this->dbus_event_push(GWL_DBusEvent{
11167 .data =
11168 GWL_DBusEvent::CSD_ButtonLayout{
11169 .layout = *value_str,
11170 },
11171 });
11172 };
11173 dbus_watcher_->setting_add("org.gnome.desktop.wm.preferences", "button-layout", on_change);
11174 }
11175# endif
11176 /* Start early so the values are likely to have arrived by the time a window is created,
11177 * the callbacks only touch `display_->dbus` & `dbus_` which already exist. */
11178 dbus_watcher_->start();
11179}
11180
11181void GHOST_SystemWayland::dbus_event_push(GWL_DBusEvent dbus_event)
11182{
11183 std::lock_guard lock{display_->dbus.events_mutex};
11184 display_->dbus.events.push_back(std::move(dbus_event));
11185 display_->dbus.has_events.store(true);
11186}
11187
11188void GHOST_SystemWayland::dbus_events_handle_pending()
11189{
11190 if (display_->dbus.has_events.exchange(false)) [[unlikely]] {
11191 std::lock_guard lock{display_->dbus.events_mutex};
11192# ifdef USE_EVENT_BACKGROUND_THREAD
11193 std::lock_guard lock_server_guard{*server_mutex};
11194# endif
11195 for (const GWL_DBusEvent &dbus_event : display_->dbus.events) {
11196 dbus_event_handle(dbus_event);
11197 }
11198 display_->dbus.events.clear();
11199
11200 if (display_->dbus.events.capacity() > dbus_events_default_size) [[unlikely]] {
11201 display_->dbus.events.shrink_to_fit();
11202 display_->dbus.events.reserve(dbus_events_default_size);
11203 }
11204 }
11205}
11206
11207void GHOST_SystemWayland::dbus_event_handle(const GWL_DBusEvent &dbus_event)
11208{
11209 if (const GWL_DBusEvent::CursorSize *value = std::get_if<GWL_DBusEvent::CursorSize>(
11210 &dbus_event.data))
11211 {
11212 CLOG_INFO(&LOG, "XDG: cursor-size: %d", value->size);
11213 display_->preferences.cursor_size = value->size;
11214
11215 for (GWL_Seat *seat : display_->seats) {
11216 cursor_size_set(seat, value->size);
11217 }
11218 }
11219# ifdef WITH_GHOST_CSD
11220 else if (const GWL_DBusEvent::CSD_ButtonLayout *value =
11221 std::get_if<GWL_DBusEvent::CSD_ButtonLayout>(&dbus_event.data))
11222 {
11223 CLOG_INFO(&LOG, "XDG: button-layout: \"%s\"", value->layout.c_str());
11224 GHOST_CSD_Layout csd_button_layout = {0};
11225 if (!GHOST_WindowCSD_LayoutFromString(csd_button_layout, value->layout)) {
11226 CLOG_WARN(&LOG, "XDG: ignoring invalid button-layout: \"%s\"", value->layout.c_str());
11227 return;
11228 }
11229 if (csd_layout_is_equal(preferences_csd_button_layout_get(), csd_button_layout)) {
11230 return;
11231 }
11232 display_->preferences.csd_button_layout = csd_button_layout;
11233
11234 /* Each window overwrites this with the layout filtered by its own capabilities,
11235 * set it here too for the case there are no windows yet. */
11236 this->setWindowCSD_Layout(csd_button_layout);
11237
11238 for (GHOST_IWindow *iwin : getWindowManager()->getWindows()) {
11239 static_cast<GHOST_WindowWayland *>(iwin)->csd_layout_refresh();
11240 }
11241 }
11242# endif /* WITH_GHOST_CSD */
11243 else {
11244 GHOST_ASSERT(false, "Unhandled variant");
11245 }
11246}
11247#endif /* WITH_GHOST_DBUS */
11248
11249uint64_t GHOST_SystemWayland::ms_from_input_time(const uint32_t timestamp_as_uint)
11250{
11251 /* NOTE(@ideasman42): Return a time compatible with `getMilliSeconds()`,
11252 * this is needed as WAYLAND time-stamps don't have a well defined beginning
11253 * use `timestamp_as_uint` to calculate an offset which is applied to future events.
11254 * This is updated because time may have passed between generating the time-stamp and `now`.
11255 * The method here is used by SDL. */
11256 uint64_t timestamp = uint64_t(timestamp_as_uint);
11257
11258 GWL_DisplayTimeStamp &input_timestamp = display_->input_timestamp;
11259 if (timestamp_as_uint < input_timestamp.last) [[unlikely]] {
11260 /* NOTE(@ideasman42): Sometimes event times are out of order,
11261 * while this should _never_ happen, it occasionally does:
11262 * - With accepting IME text with GNOME-v45.2 the timestamp is in seconds, see:
11263 * https://gitlab.gnome.org/GNOME/mutter/-/issues/3214
11264 * Accept events must occur within ~25 days, out-of-order time-stamps above this time-frame
11265 * will be treated as a wrapped integer. */
11266 if (input_timestamp.last - timestamp_as_uint > std::numeric_limits<uint32_t>::max() / 2) {
11267 /* Finally check to avoid invalid rollover,
11268 * ensure the rolled over time is closer to "now" than it is currently. */
11269 const uint64_t offset_test = input_timestamp.offset +
11270 uint64_t(std::numeric_limits<uint32_t>::max()) + 1;
11271 const uint64_t now = getMilliSeconds();
11272 if (sub_abs_u64(now, timestamp + offset_test) <
11273 sub_abs_u64(now, timestamp + input_timestamp.offset))
11274 {
11275 /* 32-bit timer rollover, bump the offset. */
11276 input_timestamp.offset = offset_test;
11277 }
11278 }
11279 }
11280 input_timestamp.last = timestamp_as_uint;
11281
11282 if (input_timestamp.exact_match) {
11283 timestamp += input_timestamp.offset;
11284 }
11285 else {
11286 const uint64_t now = getMilliSeconds();
11287 const uint32_t now_as_uint32 = uint32_t(now);
11288 if (now_as_uint32 == timestamp_as_uint) {
11289 input_timestamp.exact_match = true;
11290 /* For systems with up times exceeding 47 days
11291 * it's possible we need to begin with an offset. */
11292 input_timestamp.offset = now - uint64_t(now_as_uint32);
11293 timestamp = now;
11294 }
11295 else {
11296 if (!input_timestamp.offset) {
11297 input_timestamp.offset = (now - timestamp);
11298 }
11299 timestamp += input_timestamp.offset;
11300
11301 if (timestamp > now) {
11302 input_timestamp.offset -= (timestamp - now);
11303 timestamp = now;
11304 }
11305 }
11306 }
11307
11308 return timestamp;
11309}
11310
11312 std::unique_ptr<const GHOST_IEvent> event)
11313{
11314#ifdef USE_EVENT_BACKGROUND_THREAD
11315 GHOST_ASSERT(!display_->background, "Foreground only");
11316 if (main_thread_id != std::this_thread::get_id()) {
11317 std::lock_guard lock{display_->events_pending_mutex};
11318 display_->events_pending.push_back(std::move(event));
11319 return GHOST_kSuccess;
11320 }
11321#endif
11322 return pushEvent(std::move(event));
11323}
11324
11326{
11327 gwl_display_seat_active_set(display_, seat);
11328}
11329
11331{
11332 GWL_Seat *seat = gwl_display_seat_active_get(display_);
11333 if (!seat) [[unlikely]] {
11334 return nullptr;
11335 }
11336
11337 serial = seat->data_source_serial;
11338 return seat->wl.seat;
11339}
11340
11342{
11343 bool changed = false;
11344#define SURFACE_CLEAR_PTR(surface_test) \
11345 if (surface_test == wl_surface) { \
11346 surface_test = nullptr; \
11347 changed = true; \
11348 } \
11349 ((void)0);
11350
11351 /* Only clear window surfaces (not cursors, off-screen surfaces etc). */
11352 for (GWL_Seat *seat : display_->seats) {
11353 SURFACE_CLEAR_PTR(seat->pointer.wl.surface_window);
11354 SURFACE_CLEAR_PTR(seat->tablet.wl.surface_window);
11355 SURFACE_CLEAR_PTR(seat->touch.wl.surface_window);
11356#ifdef WITH_GHOST_CSD
11357 SURFACE_CLEAR_PTR(seat->pointer.wl.surface_window_csd_margin);
11358 SURFACE_CLEAR_PTR(seat->tablet.wl.surface_window_csd_margin);
11359 SURFACE_CLEAR_PTR(seat->touch.wl.surface_window_csd_margin);
11360#endif
11361 SURFACE_CLEAR_PTR(seat->keyboard.wl.surface_window);
11362 SURFACE_CLEAR_PTR(seat->wl.surface_window_focus_dnd);
11363#ifdef WITH_INPUT_IME
11364 SURFACE_CLEAR_PTR(seat->ime.surface_window);
11365#endif
11366 }
11367#undef SURFACE_CLEAR_PTR
11368
11369 return changed;
11370}
11371
11372bool GHOST_SystemWayland::output_unref(wl_output *wl_output)
11373{
11374 bool changed = false;
11375 if (!ghost_wl_output_own(wl_output)) {
11376 return changed;
11377 }
11378
11379 /* NOTE: keep in sync with `output_scale_update`. */
11381 const GHOST_WindowManager *window_manager = getWindowManager();
11382 if (window_manager) {
11383 for (GHOST_IWindow *iwin : window_manager->getWindows()) {
11384 GHOST_WindowWayland *win = static_cast<GHOST_WindowWayland *>(iwin);
11385 if (win->outputs_leave(output)) {
11387 changed = true;
11388 }
11389 }
11390 }
11391 for (GWL_Seat *seat : display_->seats) {
11392 if (seat->pointer.outputs.erase(output)) {
11393 changed = true;
11394 }
11395 if (seat->tablet.outputs.erase(output)) {
11396 changed = true;
11397 }
11398 }
11399 return changed;
11400}
11401
11403{
11404 /* NOTE: keep in sync with `output_unref`. */
11405 const GHOST_WindowManager *window_manager = getWindowManager();
11406 if (window_manager) {
11407 for (GHOST_IWindow *iwin : window_manager->getWindows()) {
11408 GHOST_WindowWayland *win = static_cast<GHOST_WindowWayland *>(iwin);
11409 const std::span<GWL_Output *const> outputs = win->outputs_get();
11410 if (std::ranges::find(outputs, output) != outputs.end()) {
11412 }
11413 }
11414 }
11415 for (GWL_Seat *seat : display_->seats) {
11416 if (seat->pointer.outputs.contains(output)) {
11417 update_cursor_scale(seat, seat->cursor, &seat->pointer);
11418 }
11419
11420 if (seat->tablet.outputs.contains(output)) {
11421 update_cursor_scale(seat, seat->cursor, &seat->tablet);
11422 }
11423 }
11424}
11425
11427 const GHOST_TGrabCursorMode mode_current,
11428 int32_t init_grab_xy[2],
11429 const GHOST_Rect *wrap_bounds,
11430 const GHOST_TAxisFlag wrap_axis,
11432 const GWL_WindowScaleParams &scale_params,
11433 const GHOST_TDrawingContextType context_type)
11434{
11435 /* Caller must lock `server_mutex`. */
11436
11437 /* Ignore, if the required protocols are not supported. */
11438 if (!display_->wp.relative_pointer_manager || !display_->wp.pointer_constraints) [[unlikely]] {
11439 return false;
11440 }
11441
11442 GWL_Seat *seat = gwl_display_seat_active_get(display_);
11443 if (!seat) [[unlikely]] {
11444 return false;
11445 }
11446 /* No change, success. */
11447 if (mode == mode_current) {
11448 return true;
11449 }
11450
11451#ifndef USE_KDE_VULKAN_UNGRAB_CURSOR_HACK
11452 (void)context_type;
11453#endif
11454
11455#ifdef USE_GNOME_CONFINE_HACK
11456 const bool was_software_confine = seat->use_pointer_software_confine;
11457 const bool use_software_confine = setCursorGrab_use_software_confine(mode, wl_surface);
11458#else
11459 const bool was_software_confine = false;
11460 const bool use_software_confine = false;
11461#endif
11462
11463 const GWL_SeatStateGrab grab_state_prev = seat_grab_state_from_mode(mode_current,
11464 was_software_confine);
11465 const GWL_SeatStateGrab grab_state_next = seat_grab_state_from_mode(mode, use_software_confine);
11466
11467 /* Check for wrap as #GHOST_kCapabilityCursorWarp isn't supported. */
11468 const bool use_visible = !(ELEM(mode, GHOST_kGrabHide, GHOST_kGrabWrap) || use_software_confine);
11469 const bool is_hardware_cursor = !cursor_is_software(mode, use_software_confine);
11470
11471 /* Only hide so the cursor is not made visible before it's location is restored.
11472 * This function is called again at the end of this function which only shows. */
11473 gwl_seat_cursor_visible_set(seat, use_visible, is_hardware_cursor, CURSOR_VISIBLE_ONLY_HIDE);
11474
11475 /* Switching from one grab mode to another,
11476 * in this case disable the current locks as it makes logic confusing,
11477 * postpone changing the cursor to avoid flickering. */
11478 if (!grab_state_next.use_lock) {
11479 if (seat->wp.relative_pointer) {
11480 zwp_relative_pointer_v1_destroy(seat->wp.relative_pointer);
11481 seat->wp.relative_pointer = nullptr;
11482 }
11483 if (seat->wp.locked_pointer) {
11484 /* Potentially add a motion event so the application has updated X/Y coordinates. */
11485 wl_fixed_t xy_motion[2] = {0, 0};
11486 bool xy_motion_create_event = false;
11487 /* Set when a cursor position hint needs a commit before the lock is destroyed. */
11488 bool surface_needs_commit = false;
11489
11490 /* Request location to restore to. */
11491 if (mode_current == GHOST_kGrabWrap) {
11492 /* Since this call is initiated by Blender, we can be sure the window wasn't closed
11493 * by logic outside this function - as the window was needed to make this call. */
11494 wl_fixed_t xy_next[2] = {UNPACK2(seat->pointer.xy)};
11495
11496 GHOST_Rect bounds_scale;
11497
11498 bounds_scale.l_ = gwl_window_scale_wl_fixed_from(scale_params,
11499 wl_fixed_from_int(wrap_bounds->l_));
11500 bounds_scale.t_ = gwl_window_scale_wl_fixed_from(scale_params,
11501 wl_fixed_from_int(wrap_bounds->t_));
11502 bounds_scale.r_ = gwl_window_scale_wl_fixed_from(scale_params,
11503 wl_fixed_from_int(wrap_bounds->r_));
11504 bounds_scale.b_ = gwl_window_scale_wl_fixed_from(scale_params,
11505 wl_fixed_from_int(wrap_bounds->b_));
11506
11507 bounds_scale.wrapPoint(UNPACK2(xy_next), 0, wrap_axis);
11508
11509 /* Push an event so the new location is registered. */
11510 if ((xy_next[0] != seat->pointer.xy[0]) || (xy_next[1] != seat->pointer.xy[1])) {
11511 xy_motion[0] = xy_next[0];
11512 xy_motion[1] = xy_next[1];
11513 xy_motion_create_event = true;
11514 }
11515 seat->pointer.xy[0] = xy_next[0];
11516 seat->pointer.xy[1] = xy_next[1];
11517
11518 zwp_locked_pointer_v1_set_cursor_position_hint(seat->wp.locked_pointer, UNPACK2(xy_next));
11519 surface_needs_commit = true;
11520 }
11521 else if (mode_current == GHOST_kGrabHide) {
11522 const wl_fixed_t xy_next[2] = {
11523 gwl_window_scale_wl_fixed_from(scale_params, wl_fixed_from_int(init_grab_xy[0])),
11524 gwl_window_scale_wl_fixed_from(scale_params, wl_fixed_from_int(init_grab_xy[1])),
11525 };
11526
11527 if ((init_grab_xy[0] != seat->grab_lock_xy[0]) ||
11528 (init_grab_xy[1] != seat->grab_lock_xy[1]))
11529 {
11530 zwp_locked_pointer_v1_set_cursor_position_hint(seat->wp.locked_pointer,
11531 UNPACK2(xy_next));
11532 surface_needs_commit = true;
11533
11534 /* NOTE(@ideasman42): The new cursor position is a hint,
11535 * it's possible the hint is ignored. It doesn't seem like there is a good way to
11536 * know if the hint will be used or not, at least not immediately. */
11537 xy_motion[0] = xy_next[0];
11538 xy_motion[1] = xy_next[1];
11539 xy_motion_create_event = true;
11540 }
11541 else if (grab_state_prev.use_lock) {
11542 /* NOTE(@ideasman42): From WAYLAND's perspective the cursor did not move.
11543 * The application will have received "hidden" events to warped locations.
11544 * So generate event without setting the cursor position hint. */
11545 xy_motion[0] = xy_next[0];
11546 xy_motion[1] = xy_next[1];
11547 xy_motion_create_event = true;
11548 }
11549 }
11550#ifdef USE_GNOME_CONFINE_HACK
11551 else if (mode_current == GHOST_kGrabNormal) {
11552 if (was_software_confine) {
11553 zwp_locked_pointer_v1_set_cursor_position_hint(seat->wp.locked_pointer,
11554 UNPACK2(seat->pointer.xy));
11555 surface_needs_commit = true;
11556 }
11557 }
11558#endif
11559
11560 if (xy_motion_create_event) {
11561 /* Caller has no time-stamp. */
11562 const uint64_t event_ms = getMilliSeconds();
11563 seat->system->pushEvent_maybe_pending(std::make_unique<GHOST_EventCursor>(
11564 event_ms,
11567 wl_fixed_to_int(gwl_window_scale_wl_fixed_to(scale_params, xy_motion[0])),
11568 wl_fixed_to_int(gwl_window_scale_wl_fixed_to(scale_params, xy_motion[1])),
11569 GHOST_TABLET_DATA_NONE));
11570 }
11571
11572 if (surface_needs_commit) {
11573#ifdef USE_KDE_VULKAN_UNGRAB_CURSOR_HACK
11574 if (use_kde_vulkan_ungrab_cursor_hack && (context_type == GHOST_kDrawingContextTypeVulkan))
11575 {
11576 /* Failure to apply the commit within this time limit simply means
11577 * the cursor will be restored to the location the grab began instead
11578 * of the visual location the software cursor is shown.
11579 * (not great but not terrible), see define for details. */
11580 const int timeout_ms = 500;
11581 ghost_wl_surface_commit_and_wait_for_apply(this, wl_surface, timeout_ms);
11582 }
11583 else
11584#endif /* USE_KDE_VULKAN_UNGRAB_CURSOR_HACK */
11585 {
11586 wl_surface_commit(wl_surface);
11587 }
11588 }
11589
11590 zwp_locked_pointer_v1_destroy(seat->wp.locked_pointer);
11591 seat->wp.locked_pointer = nullptr;
11592 }
11593 }
11594
11595 if (!grab_state_next.use_confine) {
11596 if (seat->wp.confined_pointer) {
11597 zwp_confined_pointer_v1_destroy(seat->wp.confined_pointer);
11598 seat->wp.confined_pointer = nullptr;
11599 }
11600 }
11601
11602 if (mode != GHOST_kGrabDisable) {
11603 if (grab_state_next.use_lock) {
11604 if (!grab_state_prev.use_lock) {
11605 /* As WAYLAND does not support setting the cursor coordinates programmatically,
11606 * #GHOST_kGrabWrap cannot be supported by positioning the cursor directly.
11607 * Instead the cursor is locked in place, using a software cursor that is warped.
11608 * Then WAYLAND's #zwp_locked_pointer_v1_set_cursor_position_hint is used to restore
11609 * the cursor to the warped location. */
11610 seat->wp.relative_pointer = zwp_relative_pointer_manager_v1_get_relative_pointer(
11611 display_->wp.relative_pointer_manager, seat->wl.pointer);
11612 zwp_relative_pointer_v1_add_listener(
11613 seat->wp.relative_pointer, &relative_pointer_listener, seat);
11614 seat->wp.locked_pointer = zwp_pointer_constraints_v1_lock_pointer(
11615 display_->wp.pointer_constraints,
11616 wl_surface,
11617 seat->wl.pointer,
11618 nullptr,
11619 ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);
11620 }
11621 if (mode == GHOST_kGrabHide) {
11622 /* Set the initial position to detect any changes when un-grabbing,
11623 * otherwise the unlocked cursor defaults to un-locking in-place. */
11624 init_grab_xy[0] = wl_fixed_to_int(
11625 gwl_window_scale_wl_fixed_to(scale_params, seat->pointer.xy[0]));
11626 init_grab_xy[1] = wl_fixed_to_int(
11627 gwl_window_scale_wl_fixed_to(scale_params, seat->pointer.xy[1]));
11628 seat->grab_lock_xy[0] = init_grab_xy[0];
11629 seat->grab_lock_xy[1] = init_grab_xy[1];
11630 }
11631 }
11632 else if (grab_state_next.use_confine) {
11633 if (!grab_state_prev.use_confine) {
11634 seat->wp.confined_pointer = zwp_pointer_constraints_v1_confine_pointer(
11635 display_->wp.pointer_constraints,
11636 wl_surface,
11637 seat->wl.pointer,
11638 nullptr,
11639 ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT);
11640 }
11641 }
11642 }
11643
11644 /* Only show so the cursor is made visible as the last step. */
11645 gwl_seat_cursor_visible_set(seat, use_visible, is_hardware_cursor, CURSOR_VISIBLE_ONLY_SHOW);
11646
11647#ifdef USE_GNOME_CONFINE_HACK
11648 seat->use_pointer_software_confine = use_software_confine;
11649#endif
11650
11651 return true;
11652}
11653
11654#ifdef WITH_GHOST_WAYLAND_DYNLOAD
11655bool ghost_wl_dynload_libraries_init()
11656{
11657# ifdef WITH_GHOST_X11
11658 /* When running in WAYLAND, let the user know when a missing library is the only reason
11659 * WAYLAND could not be used. Otherwise it's not obvious why X11 is used as a fallback.
11660 * Otherwise when X11 is used, reporting WAYLAND library warnings is unwelcome noise. */
11661 bool verbose = getenv("WAYLAND_DISPLAY") != nullptr;
11662# else
11663 bool verbose = true;
11664# endif /* !WITH_GHOST_X11 */
11665
11666 if (wayland_dynload_client_init(verbose) && /* `libwayland-client`. */
11667 wayland_dynload_cursor_init(verbose) && /* `libwayland-cursor`. */
11668# ifdef WITH_OPENGL_BACKEND
11669 wayland_dynload_egl_init(verbose) /* `libwayland-egl`. */
11670# else
11671 true
11672# endif
11673 )
11674 {
11675 return true;
11676 }
11677
11680# ifdef WITH_OPENGL_BACKEND
11682# endif
11683
11684 return false;
11685}
11686
11687void ghost_wl_dynload_libraries_exit()
11688{
11691# ifdef WITH_OPENGL_BACKEND
11693# endif
11694}
11695
11696#endif /* WITH_GHOST_WAYLAND_DYNLOAD */
11697
#define INT32_MAX
#define INT32_MIN
#define CLOG_DEBUG(clg_ref,...)
Definition CLG_log.h:191
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define CLOG_INFO(clg_ref,...)
Definition CLG_log.h:190
#define GHOST_OPENGL_EGL_CONTEXT_FLAGS
#define GHOST_OPENGL_EGL_RESET_NOTIFICATION_STRATEGY
#define wl_display
#define wl_surface
#define GHOST_ASSERT(x, info)
#define GHOST_PRINT(x)
char * GHOST_URL_decode_alloc(const char *buf_src, const int buf_src_len)
#define GXMAP(k, x, y)
static void keyboard_handle_repeat_info(void *data, wl_keyboard *, const int32_t rate, const int32_t delay)
void(*)(GWL_Display *display, void *user_data, bool on_exit) GWL_RegistryEntry_RemoveFn
static constexpr int smooth_as_discrete_steps
static void gwl_registry_wp_viewporter_remove(GWL_Display *display, void *, const bool)
static void tablet_tool_handle_button(void *data, zwp_tablet_tool_v2 *, const uint32_t serial, const uint32_t button, const uint32_t state)
static void gwl_registry_subcompositor_remove(GWL_Display *display, void *, const bool)
static void gwl_registry_wl_seat_update(GWL_Display *display, const GWL_RegistryUpdate_Params &params)
static CLG_LogRef LOG_WL_PRIMARY_SELECTION_SOURCE
#define USE_NON_LATIN_KB_WORKAROUND
#define WL_FIXED_TO_INT_FOR_WINDOW_V2(win, xy)
static const char * ghost_wl_mime_send[]
static void cursor_surface_handle_enter(void *data, wl_surface *wl_surface, wl_output *wl_output)
static void tablet_tool_handle_distance(void *, zwp_tablet_tool_v2 *, const uint32_t distance)
static void data_source_handle_target(void *, wl_data_source *, const char *)
static void primary_selection_device_handle_selection(void *data, zwp_primary_selection_device_v1 *, zwp_primary_selection_offer_v1 *id)
static void global_handle_add(void *data, wl_registry *wl_registry, const uint32_t name, const char *interface, const uint32_t version)
static const xdg_toplevel_icon_manager_v1_listener xdg_toplevel_icon_manager_listener
static int gwl_registry_handler_interface_slot_from_string(const char *interface)
static const wl_keyboard_listener keyboard_listener
static CLG_LogRef LOG_WL_TABLET_TOOL
constexpr uint32_t WL_NAME_UNSET
static void gwl_registry_xdg_toplevel_icon_manager_remove(GWL_Display *display, void *, const bool)
static void keyboard_depressed_state_push_events_from_change(GWL_Seat *seat, GHOST_IWindow *win, const uint64_t event_ms, const GWL_KeyboardDepressedState &key_depressed_prev)
static GHOST_TTabletMode tablet_tool_map_type(enum zwp_tablet_tool_v2_type wp_tablet_tool_type)
#define BTN_RANGE_MAX
static void keyboard_handle_modifiers(void *data, wl_keyboard *, const uint32_t serial, const uint32_t mods_depressed, const uint32_t mods_latched, const uint32_t mods_locked, const uint32_t group)
static void seat_handle_capabilities(void *data, wl_seat *wl_seat, const uint32_t capabilities)
static void cursor_surface_handle_leave(void *data, wl_surface *wl_surface, wl_output *wl_output)
void(*)(GWL_Display *display, const GWL_RegistryAdd_Params &params) GWL_RegistryHandler_AddFn
static const char * ghost_wl_surface_cursor_tablet_tag_id
static const xdg_wm_base_listener shell_listener
static CLG_LogRef LOG_WL_KEYBOARD_DEPRESSED_STATE
static void keyboard_handle_keymap(void *data, wl_keyboard *, const uint32_t format, const int32_t fd, const uint32_t size)
static void data_source_handle_cancelled(void *data, wl_data_source *wl_data_source)
static int gwl_seat_cursor_buffer_scale_calc(const GWL_Seat *seat)
bool ghost_wl_surface_own(const wl_surface *wl_surface)
static char * system_clipboard_get(GWL_Display *display, const bool nil_terminate, const char *mime_receive_override, size_t *r_data_len)
static void tablet_seat_handle_tool_added(void *data, zwp_tablet_seat_v2 *, zwp_tablet_tool_v2 *id)
static void xdg_toplevel_icon_manager_handle_icon_size(void *data, xdg_toplevel_icon_manager_v1 *, int32_t size)
static void gwl_registry_xdg_decoration_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void pointer_handle_frame(void *data, wl_pointer *)
static void pointer_handle_axis(void *data, wl_pointer *, const uint32_t time, const uint32_t axis, const wl_fixed_t value)
static const char * ghost_wl_app_id
static void xdg_output_handle_name(void *, zxdg_output_v1 *, const char *name)
static GHOST_TSuccess getCursorPositionClientRelative_impl(const GWL_SeatStatePointer *seat_state_pointer, const GHOST_WindowWayland *win, int32_t &x, int32_t &y)
static void gwl_primary_selection_discard_offer(GWL_PrimarySelection *primary)
static void pthread_set_min_priority(pthread_t handle)
static void touch_seat_handle_down(void *data, wl_touch *, const uint32_t serial, const uint32_t time, wl_surface *surface, const int32_t id, const wl_fixed_t x, const wl_fixed_t y)
static void gwl_registry_wl_data_device_manager_remove(GWL_Display *display, void *, const bool)
static char * read_buffer_from_primary_selection_offer(GWL_PrimarySelection_DataOffer *data_offer, const char *mime_receive, std::mutex *mutex, const bool nil_terminate, size_t *r_len)
static void pointer_handle_axis_discrete(void *data, wl_pointer *, const uint32_t axis, const int32_t discrete)
static void gwl_seat_capability_keyboard_disable(GWL_Seat *seat)
static void gwl_pointer_handle_frame_event_add(GWL_SeatStatePointer_Events *pointer_events, const GWL_Pointer_EventTypes ty, const uint32_t serial, const uint64_t event_ms)
static void tablet_tool_handle_type(void *data, zwp_tablet_tool_v2 *, const uint32_t tool_type)
static bool gwl_registry_entry_remove_by_interface_slot(GWL_Display *display, const int interface_slot, const bool on_exit)
static void gwl_registry_wp_relative_pointer_manager_remove(GWL_Display *display, void *, const bool)
static CLG_LogRef LOG_WL_TABLET_SEAT
static void data_device_handle_drop(void *data, wl_data_device *)
static void data_source_handle_send(void *data, wl_data_source *, const char *, const int32_t fd)
static bool gwl_display_seat_active_set(GWL_Display *display, const GWL_Seat *seat)
static const zwp_relative_pointer_v1_listener relative_pointer_listener
static void tablet_tool_handle_proximity_out(void *data, zwp_tablet_tool_v2 *)
void ghost_wl_output_tag(wl_output *wl_output)
static xkb_keysym_t xkb_state_key_get_one_sym_without_modifiers(xkb_state *xkb_state_empty, xkb_state *xkb_state_empty_with_numlock, xkb_state *xkb_state_empty_with_shift, const xkb_layout_index_t layout_fallback, const bool xkb_use_non_latin_workaround, const xkb_keycode_t key)
static void gwl_registry_wp_color_manager_remove(GWL_Display *display, void *, const bool)
static void output_handle_geometry(void *data, wl_output *, const int32_t, const int32_t, const int32_t physical_width, const int32_t physical_height, const int32_t, const char *make, const char *model, const int32_t transform)
static void gwl_registry_xdg_decoration_manager_remove(GWL_Display *display, void *, const bool)
static CLG_LogRef LOG_WL_PRIMARY_SELECTION_OFFER
static void cursor_shape_refresh_for_pointer(const GWL_Seat *seat, const GWL_SeatStatePointer *seat_state_pointer)
static void data_device_handle_selection(void *data, wl_data_device *, wl_data_offer *id)
static GWL_CurrentDesktopType ghost_wayland_current_desktop()
static int memfd_create_sealed(const char *name)
static uint64_t ghost_wl_ms_from_utime_pair(uint32_t utime_hi, uint32_t utime_lo)
static void touch_seat_handle_motion(void *data, wl_touch *, const uint32_t time, const int32_t id, const wl_fixed_t x, const wl_fixed_t y)
static xkb_keysym_t xkb_state_key_get_one_sym_with_fallback(xkb_state *state, const xkb_keycode_t key, const xkb_layout_index_t layout_fallback)
static void keyboard_handle_key_repeat_cancel(GWL_Seat *seat)
GHOST_WindowWayland * ghost_wl_surface_user_data(wl_surface *wl_surface)
static void gwl_seat_key_repeat_timer_remove(GWL_Seat *seat)
static const GHOST_TButton gwl_pointer_events_ebutton[]
static void gwl_registry_wl_seat_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static CLG_LogRef LOG_WL_TOUCH
static void gwl_registry_wp_primary_selection_device_manager_remove(GWL_Display *display, void *, const bool)
static GHOST_TSuccess setCursorPositionClientRelative_impl(GWL_Seat *seat, GHOST_WindowWayland *win, const int32_t x, const int32_t y)
static const zxdg_output_v1_listener xdg_output_listener
static void keyboard_handle_key_repeat_reset(GWL_Seat *seat, const bool use_delay)
static void global_handle_remove(void *data, wl_registry *wl_registry, const uint32_t name)
static const wl_buffer_listener cursor_buffer_listener
static void gwl_registry_wp_pointer_constraints_remove(GWL_Display *display, void *, const bool)
static void gwl_registry_compositor_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void tablet_tool_handle_done(void *, zwp_tablet_tool_v2 *)
static void output_handle_done(void *data, wl_output *wl_output)
static void gwl_registry_wl_output_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void gwl_seat_capability_keyboard_enable(GWL_Seat *seat)
static ssize_t read_exhaustive(const int fd, void *data, size_t nbytes)
static uint32_t rgba_straight_to_premul(uint32_t rgba_uint)
static CLG_LogRef LOG_WL_RELATIVE_POINTER
static void relative_pointer_handle_relative_motion_impl(GWL_Seat *seat, GHOST_WindowWayland *win, const wl_fixed_t xy[2], const uint64_t event_ms)
static uint64_t sub_abs_u64(const uint64_t a, const uint64_t b)
static bool gwl_registry_entry_remove_by_name(GWL_Display *display, uint32_t name, int *r_interface_slot)
static wl_buffer * ghost_wl_buffer_from_cursor_generator(const GHOST_CursorGenerator &cg, wl_shm *shm, void **buffer_data_p, size_t *buffer_data_size_p, const int cursor_size, const int cursor_size_max, const int use_dark_theme, const int scale, int r_bitmap_size[2], int r_hot_spot[2])
void ghost_wl_surface_tag_cursor_tablet(wl_surface *wl_surface)
#define BTN_RANGE_MIN
static void touch_seat_handle_up(void *data, wl_touch *, const uint32_t serial, const uint32_t time, const int32_t id)
static void xdg_output_handle_description(void *, zxdg_output_v1 *, const char *description)
bool ghost_wl_surface_own_cursor_tablet(const wl_surface *wl_surface)
static CLG_LogRef LOG_WL_XDG_OUTPUT
static void gwl_seat_cursor_buffer_set(const GWL_Seat *seat, const wl_cursor_image *wl_image, wl_buffer *buffer)
static void gwl_registry_wp_cursor_shape_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void gwl_registry_xdg_wm_base_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void gwl_registry_entry_update_all(GWL_Display *display, const int interface_slot_exclude)
static CLG_LogRef LOG_WL_PRIMARY_SELECTION_DEVICE
GWL_Output * ghost_wl_output_user_data(wl_output *wl_output)
static void xdg_toplevel_icon_manager_handle_done(void *, xdg_toplevel_icon_manager_v1 *)
static char * read_buffer_from_data_offer(GWL_DataOffer *data_offer, const char *mime_receive, std::mutex *mutex, const bool nil_terminate, size_t *r_len)
static std::optional< int > cursor_size_from_env()
static bool gwl_seat_capability_pointer_multitouch_check(const GWL_Seat *seat, const bool fallback)
static const wl_registry_listener registry_listener
static void keyboard_depressed_state_reset(GWL_Seat *seat)
static void gwl_tablet_tool_frame_event_add(GWL_TabletTool *tablet_tool, const GWL_TabletTool_EventTypes ty, const uint32_t serial)
static const zwp_tablet_seat_v2_listener tablet_seat_listener
static bool use_kde_tablet_hidden_cursor_hack
static void gwl_tablet_tool_frame_event_reset(GWL_TabletTool *tablet_tool)
static void gwl_registry_xdg_activation_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static GWL_SeatStatePointer * gwl_seat_state_pointer_active(GWL_Seat *seat)
static constexpr const char * ghost_wl_mime_text_plain
static void tablet_seat_handle_tablet_added(void *, zwp_tablet_seat_v2 *, zwp_tablet_v2 *id)
static void tablet_tool_handle_frame(void *data, zwp_tablet_tool_v2 *, const uint32_t time)
static const zwp_primary_selection_offer_v1_listener primary_selection_offer_listener
static int pointer_axis_as_index(const uint32_t axis)
static GHOST_TKey xkb_map_gkey(const xkb_keysym_t sym)
static const wl_pointer_listener pointer_listener
static void system_clipboard_put_primary_selection(GWL_Display *display, const char *buffer)
static bool gwl_display_event_thread_create(GWL_Display *display)
static void data_source_handle_dnd_finished(void *, wl_data_source *)
static void color_manager_v1_done(void *data, wp_color_manager_v1 *)
static void gwl_registry_subcompositor_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static xkb_layout_index_t xkb_keymap_get_fallback_layout(xkb_keymap *keymap, const xkb_layout_index_t layout_active)
static void tablet_tool_handle_hardware_id_wacom(void *, zwp_tablet_tool_v2 *, const uint32_t, const uint32_t)
static void gwl_seat_capability_pointer_disable(GWL_Seat *seat)
static void gwl_registry_wp_pointer_gestures_remove(GWL_Display *display, void *, const bool)
static const wl_data_offer_listener data_offer_listener
static void ghost_wl_display_report_error_from_code(wl_display *display, const int ecode)
static void touch_seat_handle_cancel(void *data, wl_touch *)
static void gwl_registry_xdg_toplevel_icon_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void gwl_pointer_handle_frame_event_reset(GWL_SeatStatePointer_Events *pointer_events)
static void primary_selection_source_send(void *data, zwp_primary_selection_source_v1 *, const char *, const int32_t fd)
static void tablet_tool_handle_motion(void *data, zwp_tablet_tool_v2 *, const wl_fixed_t x, const wl_fixed_t y)
static const GWL_RegistryHandler * gwl_registry_handler_from_interface_slot(int interface_slot)
static void gwl_registry_wl_shm_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static CLG_LogRef LOG_WL_OUTPUT
static const wl_data_source_listener data_source_listener
static const zwp_tablet_tool_v2_listener tablet_tool_listener
static void ghost_wayland_log_handler_background(const char *msg, va_list arg)
static void gwl_registry_wl_seat_remove(GWL_Display *display, void *user_data, const bool on_exit)
static void keyboard_depressed_state_key_event(GWL_Seat *seat, const GHOST_TKey gkey, const GHOST_TEventType etype)
static void touch_seat_handle_frame(void *data, wl_touch *)
static void tablet_seat_handle_pad_added(void *, zwp_tablet_seat_v2 *, zwp_tablet_pad_v2 *id)
static void gwl_registry_wp_tablet_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void tablet_tool_handle_hardware_serial(void *, zwp_tablet_tool_v2 *, const uint32_t, const uint32_t)
static char * system_clipboard_get_primary_selection(GWL_Display *display, const bool nil_terminate, const char *mime_receive_override, size_t *r_data_len)
void ghost_wl_surface_tag(wl_surface *wl_surface)
static void gwl_registry_wp_pointer_constraints_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static wl_buffer * ghost_wl_buffer_create_for_image(wl_shm *shm, const int32_t size_xy[2], enum wl_shm_format format, void **r_buffer_data, size_t *r_buffer_data_size)
static bool cursor_is_software(const GHOST_TGrabCursorMode mode, const bool use_software_confine)
static const wl_data_device_listener data_device_listener
static void color_manager_v1_supported_intent(void *data, wp_color_manager_v1 *, uint32_t render_intent)
constexpr int MOD_INDEX_NUM
static void gwl_seat_capability_touch_disable(GWL_Seat *seat)
static void ghost_wl_display_report_error(wl_display *display)
static void tablet_tool_handle_tilt(void *data, zwp_tablet_tool_v2 *, const wl_fixed_t tilt_x, const wl_fixed_t tilt_y)
bool ghost_wl_display_report_error_if_set(wl_display *display)
static void tablet_tool_handle_removed(void *data, zwp_tablet_tool_v2 *zwp_tablet_tool_v2)
constexpr int EVDEV_OFFSET
static const wl_touch_listener touch_seat_listener
static void pointer_handle_button(void *data, wl_pointer *, const uint32_t serial, const uint32_t time, const uint32_t button, const uint32_t state)
static void gwl_seat_key_layout_active_state_update_mask(GWL_Seat *seat)
static void gwl_display_event_thread_destroy(GWL_Display *display)
static CLG_LogRef LOG_WL_KEYBOARD
static GHOST_TKey xkb_map_gkey_or_scan_code(const xkb_keysym_t sym, const uint32_t key)
static void keyboard_handle_key(void *data, wl_keyboard *, const uint32_t serial, const uint32_t time, const uint32_t key, const uint32_t state)
static bool string_elem_split_by_delim(std::string_view haystack, const char delim, std::string_view needle)
void ghost_wl_surface_tag_cursor_pointer(wl_surface *wl_surface)
static void ghost_wayland_log_handler(const char *msg, va_list arg)
static void gwl_seat_cursor_buffer_show(GWL_Seat *seat)
static CLG_LogRef LOG_WL_REGISTRY
static const wl_surface_listener cursor_surface_listener
static void primary_selection_source_cancelled(void *data, zwp_primary_selection_source_v1 *source)
@ CURSOR_VISIBLE_ONLY_HIDE
@ CURSOR_VISIBLE_ALWAYS_SET
@ CURSOR_VISIBLE_ONLY_SHOW
static CLG_LogRef LOG_WL_POINTER
static bool use_gnome_motion_missing_time_hack
static void gwl_seat_cursor_buffer_hide(GWL_Seat *seat)
static int file_descriptor_is_io_ready(const int fd, const int flags, const int timeout_ms)
static int ghost_wl_display_event_pump_from_thread(wl_display *wl_display, const int fd, const int fd_stop, std::mutex *server_mutex)
static void keyboard_handle_leave(void *data, wl_keyboard *, const uint32_t, wl_surface *wl_surface)
static void gwl_registry_wp_relative_pointer_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static constexpr const char * ghost_wl_mime_img_png
static void data_source_handle_action(void *, wl_data_source *, const uint32_t dnd_action)
@ GWL_IOR_NO_RETRY
#define XKB_VMOD_NAME_HYPER
static void gwl_registry_wp_tablet_manager_remove(GWL_Display *display, void *, const bool)
static void xdg_output_handle_logical_position(void *data, zxdg_output_v1 *, const int32_t x, const int32_t y)
static const zwp_primary_selection_source_v1_listener primary_selection_source_listener
static void data_device_handle_data_offer(void *, wl_data_device *, wl_data_offer *id)
static void pointer_handle_enter(void *data, wl_pointer *, const uint32_t serial, wl_surface *wl_surface, const wl_fixed_t surface_x, const wl_fixed_t surface_y)
static void tablet_tool_handle_capability(void *, zwp_tablet_tool_v2 *, const uint32_t capability)
static void cursor_buffer_set_surface_impl(const wl_cursor_image *wl_image, wl_buffer *buffer, wl_surface *wl_surface, const int scale)
static void gwl_registry_wl_output_remove(GWL_Display *display, void *user_data, const bool on_exit)
static void pointer_handle_motion(void *data, wl_pointer *, const uint32_t time, const wl_fixed_t surface_x, const wl_fixed_t surface_y)
static void primary_selection_device_handle_data_offer(void *, zwp_primary_selection_device_v1 *, zwp_primary_selection_offer_v1 *id)
static const zwp_primary_selection_device_v1_listener primary_selection_device_listener
static void color_manager_v1_supported_tf_named(void *data, wp_color_manager_v1 *, uint32_t tf)
static constexpr const char * ghost_wl_mime_text_uri_list
static void cursor_buffer_handle_release(void *data, wl_buffer *wl_buffer)
static const wp_color_manager_v1_listener color_manager_v1_listener
static const char * system_clipboard_text_mime_type(const std::unordered_set< std::string > &data_offer_types)
bool ghost_wl_output_own(const wl_output *wl_output)
static void * gwl_display_event_thread_fn(void *display_voidp)
static const char * ghost_wl_locale_from_env_with_default()
static void color_manager_v1_supported_primaries_named(void *data, wp_color_manager_v1 *, uint32_t primaries)
static void pointer_handle_axis_source(void *data, wl_pointer *, const uint32_t axis_source)
static uint32_t rgba_straight_to_premul_inverted(uint32_t rgba_uint)
static void pointer_handle_leave(void *data, wl_pointer *, const uint32_t, wl_surface *wl_surface)
static CLG_LogRef LOG_WL_DATA_OFFER
static void data_offer_handle_source_actions(void *data, wl_data_offer *, const uint32_t source_actions)
static void tablet_tool_handle_rotation(void *, zwp_tablet_tool_v2 *, const wl_fixed_t degrees)
static void gwl_seat_capability_pointer_enable(GWL_Seat *seat)
static void gwl_registry_wl_output_update(GWL_Display *display, const GWL_RegistryUpdate_Params &params)
static CLG_LogRef LOG_WL_SEAT
static void data_offer_handle_action(void *data, wl_data_offer *, const uint32_t dnd_action)
static void gwl_seat_cursor_buffer_set_current(GWL_Seat *seat)
static void tablet_tool_handle_proximity_in(void *data, zwp_tablet_tool_v2 *, const uint32_t serial, zwp_tablet_v2 *, wl_surface *wl_surface)
void(*)(GWL_Display *display, const GWL_RegistryUpdate_Params &params) GWL_RegistryHandler_UpdateFn
#define SURFACE_CLEAR_PTR(surface_test)
static void color_manager_v1_supported_feature(void *data, wp_color_manager_v1 *, uint32_t feature)
static void seat_handle_name(void *data, wl_seat *, const char *name)
static void tablet_tool_handle_wheel(void *data, zwp_tablet_tool_v2 *, const wl_fixed_t, const int32_t clicks)
static void pointer_handle_axis_stop(void *data, wl_pointer *, const uint32_t time, const uint32_t axis)
static void gwl_primary_selection_discard_source(GWL_PrimarySelection *primary)
static void tablet_tool_handle_down(void *data, zwp_tablet_tool_v2 *, const uint32_t serial)
static xkb_keysym_t xkb_keymap_get_one_sym_with_fallback(const xkb_keysym_t sym, xkb_keymap *keymap, const xkb_keycode_t key, const xkb_layout_index_t layout_fallback)
static void gwl_seat_cursor_visible_set(GWL_Seat *seat, const bool visible, const bool is_hardware, const enum eCursorSetMode set_mode)
static CLG_LogRef LOG_WL_CURSOR_SURFACE
static void gwl_registry_wp_primary_selection_device_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void output_handle_scale(void *data, wl_output *, const int32_t factor)
static void data_device_handle_leave(void *data, wl_data_device *)
static const char * ghost_wl_surface_cursor_pointer_tag_id
static void gwl_display_destroy(GWL_Display *display)
static void touch_seat_handle_shape(void *, wl_touch *, const int32_t, const wl_fixed_t, const wl_fixed_t)
static uint32_t round_up_uint(const uint32_t x, const uint32_t multiple)
static void gwl_registry_wp_color_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void gwl_seat_capability_touch_enable(GWL_Seat *seat)
constexpr uint32_t WL_SERIAL_NONE
static bool xkb_compose_state_feed_and_get_utf8(xkb_compose_state *compose_state, xkb_state *state, const xkb_keycode_t key, char r_utf8_buf[sizeof(GHOST_TEventKeyData::utf8_buf)])
static void primary_selection_offer_offer(void *data, zwp_primary_selection_offer_v1 *id, const char *type)
static const wl_output_listener output_listener
static void gwl_registry_entry_remove_all(GWL_Display *display)
static void keyboard_handle_enter(void *data, wl_keyboard *, const uint32_t serial, wl_surface *wl_surface, wl_array *keys)
static int ghost_wl_display_event_pump(wl_display *wl_display)
static CLG_LogRef LOG_WL_XDG_WM_BASE
static void gwl_registry_xdg_output_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void output_handle_mode(void *data, wl_output *, const uint32_t flags, const int32_t width, const int32_t height, const int32_t)
static void gwl_seat_key_repeat_timer_fn(GHOST_ITimerTask *task, uint64_t time_ms)
static void relative_pointer_handle_relative_motion(void *data, zwp_relative_pointer_v1 *, const uint32_t utime_hi, const uint32_t utime_lo, const wl_fixed_t dx, const wl_fixed_t dy, const wl_fixed_t, const wl_fixed_t)
static GWL_Seat * gwl_display_seat_active_get(const GWL_Display *display)
static const char * ghost_wl_surface_tag_id
static void gwl_registry_wp_fractional_scale_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static void xdg_output_handle_logical_size(void *data, zxdg_output_v1 *, const int32_t width, const int32_t height)
static void pointer_handle_axis_value120(void *data, wl_pointer *, const uint32_t axis, const int32_t value120)
static signed char has_wl_trackpad_physical_direction
constexpr size_t events_pending_default_size
static void gwl_registry_xdg_wm_base_remove(GWL_Display *display, void *, const bool)
static bool setCursorGrab_use_software_confine(const GHOST_TGrabCursorMode mode, wl_surface *wl_surface)
static void data_offer_handle_offer(void *data, wl_data_offer *, const char *mime_type)
static const GHOST_TDragnDropTypes ghost_wl_mime_preference_order_type[]
static char * read_file_as_buffer(const int fd, const bool nil_terminate, size_t *r_len)
static void data_device_handle_motion(void *data, wl_data_device *, const uint32_t time, const wl_fixed_t x, const wl_fixed_t y)
static void gwl_registry_wp_fractional_scale_manager_remove(GWL_Display *display, void *, const bool)
static void gwl_registry_wp_cursor_shape_manager_remove(GWL_Display *display, void *, const bool)
GWL_TabletTool_EventTypes
@ MOD_INDEX_HYPER
@ MOD_INDEX_SHIFT
@ MOD_INDEX_ALT
@ MOD_INDEX_CTRL
static void gwl_seat_capability_pointer_multitouch_disable(GWL_Seat *seat)
static void output_handle_description(void *, wl_output *, const char *description)
static std::vector< std::string_view > gwl_clipboard_uri_ranges(const char *data_buf, size_t data_buf_len)
static CLG_LogRef LOG_WL_DATA_SOURCE
bool ghost_wl_surface_own_cursor_pointer(const wl_surface *wl_surface)
static void gwl_simple_buffer_free_data(GWL_SimpleBuffer *buffer)
static void touch_seat_handle_orientation(void *, wl_touch *, const int32_t, const wl_fixed_t)
static CLG_LogRef LOG_WL_CURSOR_BUFFER
GWL_Pointer_EventTypes
static void gwl_registry_wp_pointer_gestures_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static CLG_LogRef LOG_WL_DATA_DEVICE
static void gwl_seat_capability_pointer_multitouch_enable(GWL_Seat *seat)
static const GHOST_TButton gwl_tablet_tool_ebutton[]
static void gwl_registry_xdg_output_manager_remove(GWL_Display *display, void *, const bool)
static GWL_SeatStateGrab seat_grab_state_from_mode(const GHOST_TGrabCursorMode mode, const bool use_software_confine)
static const int default_cursor_size
static const wl_seat_listener seat_listener
static bool update_cursor_scale(GWL_Seat *seat, GWL_Cursor &cursor, GWL_SeatStatePointer *seat_state_pointer)
static const GWL_ModifierInfo g_modifier_info_table[MOD_INDEX_NUM]
static constexpr const char * ghost_wl_mime_text_utf8
static void gwl_seat_key_repeat_timer_add(GWL_Seat *seat, GHOST_TimerProcPtr key_repeat_fn, GHOST_TUserDataPtr payload, const bool use_delay)
static void data_source_handle_dnd_drop_performed(void *, wl_data_source *)
static void tablet_tool_handle_up(void *data, zwp_tablet_tool_v2 *)
static void gwl_xdg_decor_system_destroy(GWL_Display *display, GWL_XDG_Decor_System *decor)
static void gwl_simple_buffer_set_from_string(GWL_SimpleBuffer *buffer, const char *str)
static GWL_SeatStatePointer * gwl_seat_state_pointer_from_cursor_surface(GWL_Seat *seat, const wl_surface *wl_surface)
static void gwl_registry_xdg_activation_remove(GWL_Display *display, void *, const bool)
static std::optional< wp_cursor_shape_device_v1_shape > gwl_seat_cursor_find_wl_shape_from_ghost(const GHOST_TStandardCursor shape)
wl_buffer * ghost_wl_buffer_create_transparent_pixel(wl_shm *shm)
static void gwl_registry_wp_viewporter_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
static int gwl_scaled_fixed_t_add_and_calc_rounded_delta(GWL_ScaledFixedT *sf, const wl_fixed_t add)
constexpr int GWL_TabletTool_FrameTypes_NUM
static const GWL_RegistryHandler gwl_registry_handlers[]
static int file_descriptor_is_io_ready_ex(const int fd, const int fd_stop, const int flags, const int timeout_ms, bool *r_stop)
static void gwl_registry_wl_shm_remove(GWL_Display *display, void *, const bool)
static bool use_gnome_confine_hack
static void tablet_tool_handle_slider(void *, zwp_tablet_tool_v2 *, const int32_t position)
bool ghost_wl_surface_own_with_null_check(const wl_surface *wl_surface)
static void output_handle_name(void *, wl_output *, const char *name)
static void data_device_handle_enter(void *data, wl_data_device *, const uint32_t serial, wl_surface *wl_surface, const wl_fixed_t x, const wl_fixed_t y, wl_data_offer *id)
static void system_clipboard_put(GWL_Display *display, const char *buffer)
static void gwl_seat_state_pointer_surface_window_set(GWL_SeatStatePointer *seat_state_pointer, wl_surface *wl_surface)
static int gwl_display_seat_index(GWL_Display *display, const GWL_Seat *seat)
static const char * ghost_wl_output_tag_id
static const char * ghost_wl_mime_preference_order[]
static void shell_handle_ping(void *, xdg_wm_base *xdg_wm_base, const uint32_t serial)
static void dnd_events(const GWL_Seat *const seat, const GHOST_TEventType event, const uint64_t event_ms)
static void tablet_tool_handle_pressure(void *data, zwp_tablet_tool_v2 *, const uint32_t pressure)
#define GWL_IFACE_VERSION_CLAMP(params_version, version_min, version_max)
static int gwl_registry_handler_interface_slot_max()
static void cursor_surface_handle_preferred_buffer_scale(void *, wl_surface *, const int32_t factor)
static void xdg_output_handle_done(void *data, zxdg_output_v1 *)
static void gwl_registry_entry_add(GWL_Display *display, const GWL_RegistryAdd_Params &params, void *user_data)
static size_t ghost_wl_shm_format_as_size(enum wl_shm_format format)
static void gwl_registry_compositor_remove(GWL_Display *display, void *, const bool)
static void gwl_registry_wl_data_device_manager_add(GWL_Display *display, const GWL_RegistryAdd_Params &params)
wl_fixed_t gwl_window_scale_wl_fixed_to(const GWL_WindowScaleParams &scale_params, wl_fixed_t value)
wl_fixed_t gwl_window_scale_wl_fixed_from(const GWL_WindowScaleParams &scale_params, wl_fixed_t value)
int gwl_window_scale_int_to(const GWL_WindowScaleParams &scale_params, int value)
#define FRACTIONAL_DENOMINATOR
int gwl_window_scale_buffer_size_to(const GWL_WindowScaleParams &scale_params, int logical_size, int *r_buffer_scale)
bool ghost_wl_output_own(const struct wl_output *wl_output)
struct GWL_Output * ghost_wl_output_user_data(struct wl_output *wl_output)
GHOST_WindowWayland * ghost_wl_surface_user_data(struct wl_surface *wl_surface)
GWL_CurrentDesktopType
@ GHOST_kEventWheelAxisVertical
@ GHOST_kEventWheelAxisHorizontal
void * GHOST_TUserDataPtr
#define GHOST_CSD_DPI_FRACTIONAL_BASE
@ GHOST_kTrackpadEventMagnify
@ GHOST_kTrackpadEventRotate
@ GHOST_kTrackpadEventScroll
GHOST_TWindowState
@ GHOST_kWindowStateNormal
GHOST_TStandardCursor
@ GHOST_kStandardCursorLeftHandle
@ GHOST_kStandardCursorHandClosed
@ GHOST_kStandardCursorHandOpen
@ GHOST_kStandardCursorBottomLeftCorner
@ GHOST_kStandardCursorZoomIn
@ GHOST_kStandardCursorVerticalSplit
@ GHOST_kStandardCursorHelp
@ GHOST_kStandardCursorCopy
@ GHOST_kStandardCursorWait
@ GHOST_kStandardCursorRightHandle
@ GHOST_kStandardCursorHorizontalSplit
@ GHOST_kStandardCursorTopSide
@ GHOST_kStandardCursorStop
@ GHOST_kStandardCursorCrosshair
@ GHOST_kStandardCursorCustom
@ GHOST_kStandardCursorNSEWScroll
@ GHOST_kStandardCursorLeftRight
@ GHOST_kStandardCursorPencil
@ GHOST_kStandardCursorNSScroll
@ GHOST_kStandardCursorCrosshairA
@ GHOST_kStandardCursorUpDown
@ GHOST_kStandardCursorUpArrow
@ GHOST_kStandardCursorHandPoint
@ GHOST_kStandardCursorBottomSide
@ GHOST_kStandardCursorBothHandles
@ GHOST_kStandardCursorInfo
@ GHOST_kStandardCursorTopLeftCorner
@ GHOST_kStandardCursorEyedropper
@ GHOST_kStandardCursorKnife
@ GHOST_kStandardCursorMove
@ GHOST_kStandardCursorCrosshairB
@ GHOST_kStandardCursorBlade
@ GHOST_kStandardCursorSlip
@ GHOST_kStandardCursorBottomRightCorner
@ GHOST_kStandardCursorDownArrow
@ GHOST_kStandardCursorEraser
@ GHOST_kStandardCursorDefault
@ GHOST_kStandardCursorEWScroll
@ GHOST_kStandardCursorRightSide
@ GHOST_kStandardCursorRightArrow
@ GHOST_kStandardCursorTopRightCorner
@ GHOST_kStandardCursorDestroy
@ GHOST_kStandardCursorCrosshairC
@ GHOST_kStandardCursorZoomOut
@ GHOST_kStandardCursorLeftSide
@ GHOST_kStandardCursorText
@ GHOST_kStandardCursorLeftArrow
#define GHOST_KEY_MODIFIER_TO_INDEX(key)
GHOST_TEventType
@ GHOST_kEventWindowSize
@ GHOST_kEventDraggingDropDone
@ GHOST_kEventDraggingExited
@ GHOST_kEventImeComposition
@ GHOST_kEventCursorMove
@ GHOST_kEventDraggingUpdated
@ GHOST_kEventDraggingEntered
@ GHOST_kEventButtonUp
@ GHOST_kEventWindowActivate
@ GHOST_kEventWindowDeactivate
@ GHOST_kEventButtonDown
@ GHOST_kEventKeyDown
@ GHOST_kEventImeCompositionStart
@ GHOST_kEventImeCompositionEnd
@ GHOST_kEventUnknown
@ GHOST_kEventKeyUp
void(*)(FILE *file_handle) GHOST_TBacktraceFn
static const GHOST_TabletData GHOST_TABLET_DATA_NONE
#define GHOST_KEY_MODIFIER_CHECK(key)
#define GHOST_KEY_MODIFIER_NUM
GHOST_TTabletMode
@ GHOST_kTabletModeEraser
@ GHOST_kTabletModeStylus
#define GHOST_kButtonNum
GHOST_TCSD_Type
@ GHOST_kCSDTypeBody
@ GHOST_kCSDTypeBorderBottomRight
@ GHOST_kCSDTypeButtonClose
@ GHOST_kCSDTypeBorderBottomLeft
@ GHOST_kCSDTypeButtonMinimize
@ GHOST_kCSDTypeBorderBottom
@ GHOST_kCSDTypeBorderTopRight
@ GHOST_kCSDTypeBorderTop
@ GHOST_kCSDTypeBorderLeft
@ GHOST_kCSDTypeButtonMaximize
@ GHOST_kCSDTypeBorderTopLeft
@ GHOST_kCSDTypeButtonMenu
@ GHOST_kCSDTypeBorderRight
@ GHOST_kCSDTypeTitlebar
GHOST_TCapabilityFlag
@ GHOST_kCapabilityWindowDecorationServerSide
@ GHOST_kCapabilityWindowPosition
@ GHOST_kCapabilityGPUReadFrontBuffer
@ GHOST_kCapabilityCursorWarp
@ GHOST_kCapabilityWindowPath
@ GHOST_kCapabilityTrackpadPhysicalDirection
@ GHOST_kCapabilityMultiMonitorPlacement
@ GHOST_kCapabilityWindowDecorationStyles
@ GHOST_kCapabilityDesktopSample
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings)
GHOST_TAxisFlag
#define GHOST_CAPABILITY_FLAG_ALL
#define GHOST_KEY_MODIFIER_FROM_INDEX(key)
GHOST_TKey
@ GHOST_kKeyLeftOS
@ GHOST_kKeyInsert
@ GHOST_kKeySemicolon
@ GHOST_kKeyMediaPlay
@ GHOST_kKeyQuote
@ GHOST_kKeyAccentGrave
@ GHOST_kKeyLeftAlt
@ GHOST_kKeyRightShift
@ GHOST_kKeyNumLock
@ GHOST_kKeyEnter
@ GHOST_kKeyNumpadSlash
@ GHOST_kKeyRightArrow
@ GHOST_kKeyPause
@ GHOST_kKeyCapsLock
@ GHOST_kKeyApp
@ GHOST_kKeyMinus
@ GHOST_kKeyMediaStop
@ GHOST_kKeyBackSpace
@ GHOST_kKeyDownPage
@ GHOST_kKeyGrLess
@ GHOST_kKeyDownArrow
@ GHOST_kKeyRightOS
@ GHOST_kKeyClear
@ GHOST_kKeyNumpadPeriod
@ GHOST_kKeyF1
@ GHOST_kKeyNumpadAsterisk
@ GHOST_kKeyPrintScreen
@ GHOST_kKeyLeftControl
@ GHOST_kKeyLeftBracket
@ GHOST_kKeyTab
@ GHOST_kKeyComma
@ GHOST_kKeyRightBracket
@ GHOST_kKeyBackslash
@ GHOST_kKeyLinefeed
@ GHOST_kKeyLeftHyper
@ GHOST_kKeyRightAlt
@ GHOST_kKeyPeriod
@ GHOST_kKeyNumpadPlus
@ GHOST_kKeyUpPage
@ GHOST_kKeyLeftArrow
@ GHOST_kKeyEqual
@ GHOST_kKeyHome
@ GHOST_kKeyEnd
@ GHOST_kKeyUpArrow
@ GHOST_kKeyDelete
@ GHOST_kKeyNumpad0
@ GHOST_kKeyMediaFirst
@ GHOST_kKeyRightControl
@ GHOST_kKeyEsc
@ GHOST_kKeyPlus
@ GHOST_kKeyUnknown
@ GHOST_kKeyScrollLock
@ GHOST_kKeySlash
@ GHOST_kKeyNumpadEnter
@ GHOST_kKeyNumpadMinus
@ GHOST_kKeyRightHyper
@ GHOST_kKeyLeftShift
@ GHOST_kKeyMediaLast
@ GHOST_kKeySpace
GHOST_TDrawingContextType
@ GHOST_kDrawingContextTypeNone
GHOST_TModifierKey
@ GHOST_kModifierKeyRightControl
@ GHOST_kModifierKeyLeftControl
@ GHOST_kModifierKeyRightHyper
@ GHOST_kModifierKeyRightAlt
@ GHOST_kModifierKeyRightShift
@ GHOST_kModifierKeyLeftAlt
@ GHOST_kModifierKeyLeftShift
@ GHOST_kModifierKeyLeftOS
@ GHOST_kModifierKeyRightOS
@ GHOST_kModifierKeyLeftHyper
GHOST_TSuccess
@ GHOST_kFailure
@ GHOST_kSuccess
GHOST_TGrabCursorMode
@ GHOST_kGrabWrap
@ GHOST_kGrabDisable
@ GHOST_kGrabHide
@ GHOST_kGrabNormal
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings)
GHOST_TDragnDropTypes
@ GHOST_kDragnDropTypeUnknown
@ GHOST_kDragnDropTypeFilenames
@ GHOST_kDragnDropTypeString
GHOST_TButton
@ GHOST_kButtonMaskRight
@ GHOST_kButtonMaskButton4
@ GHOST_kButtonMaskLeft
@ GHOST_kButtonMaskButton7
@ GHOST_kButtonMaskButton6
@ GHOST_kButtonMaskButton5
@ GHOST_kButtonMaskMiddle
void(*)(GHOST_ITimerTask *task, uint64_t time) GHOST_TimerProcPtr
GHOST_TConsoleWindowState
#define WL_ARRAY_FOR_EACH(pos, array)
bool GHOST_WindowCSD_LayoutFromString(GHOST_CSD_Layout &layout, const std::string_view buttons)
bool GHOST_WindowCSD_Check(GWL_CurrentDesktopType desktop_type)
void GHOST_WindowCSD_LayoutDefault(GHOST_CSD_Layout &layout)
void gwl_xdg_window_icon_free(GWL_XDG_WindowIcon &icon)
#define USE_EVENT_BACKGROUND_THREAD
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
struct AtomicSpinLock __attribute__((aligned(32))) AtomicSpinLock
volatile int lock
#define UNPACK2(a)
#define STRINGIFY(x)
#define ELEM(...)
#define STREQ(a, b)
SIMD_FORCE_INLINE btVector3 transform(const btVector3 &point) const
unsigned long long int uint64_t
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
Definition btDbvt.cpp:52
static btDbvtVolume bounds(btDbvtNode **leaves, int count)
Definition btDbvt.cpp:299
#define output
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Definition btQuadWord.h:119
static void add(btAlignedObjectArray< T > &items, const Q &value)
GHOST_ContextEGL(const GHOST_System *const system, const GHOST_ContextParams &context_params, EGLNativeWindowType nativeWindow, EGLNativeDisplayType nativeDisplay, EGLint contextProfileMask, EGLint contextMajorVersion, EGLint contextMinorVersion, EGLint contextFlags, EGLint contextResetNotificationStrategy, EGLenum api)
GHOST_ContextVK(const GHOST_ContextParams &context_params, GHOST_TVulkanPlatformType platform, Window window, Display *display, wl_surface *wayland_surface, wl_display *wayland_display, const GHOST_ContextVK_WindowInfo *wayland_window_info, int contextMajorVersion, int contextMinorVersion, const GHOST_GPUDevice &preferred_device, const GHOST_WindowHDRInfo *hdr_info_=nullptr)
static GHOST_TBacktraceFn getBacktraceFn()
static bool getUseWindowFrame()
virtual GHOST_TUserDataPtr getUserData() const =0
GHOST_NDOFManagerUnix(GHOST_System &)
int32_t t_
int32_t r_
virtual void wrapPoint(int32_t &x, int32_t &y, int32_t ofs, GHOST_TAxisFlag axis)
virtual void clampPoint(int32_t &x, int32_t &y)
int32_t b_
int32_t l_
struct zwp_primary_selection_device_manager_v1 * wp_primary_selection_manager_get()
static const char * xdg_app_id_get()
GHOST_TSuccess init() override
bool supports_color_manager_extended_srgb_linear() const
struct wl_event_queue * wp_color_manager_queue_get()
void xdg_toplevel_icon_update(GHOST_WindowWayland *window, struct xdg_toplevel *toplevel)
bool supports_color_manager_feature_windows_scrgb() const
bool window_surface_unref(const wl_surface *wl_surface)
uint64_t getMilliSeconds() const override
GHOST_IContext * createOffscreenContext(GHOST_GPUSettings gpu_settings) override
GHOST_TSuccess getModifierKeys(GHOST_ModifierKeys &keys) const override
GHOST_TSuccess cursor_visibility_set(bool visible)
std::thread::id main_thread_id
struct wl_display * wl_display_get()
char * getClipboard(bool selection) const override
GHOST_TSuccess setCursorPosition(int32_t x, int32_t y) override
GHOST_TimerManager * key_repeat_timer_manager()
const std::span< GWL_Output *const > outputs_get() const
bool cursor_grab_use_software_display_get(const GHOST_TGrabCursorMode mode)
uint64_t ms_from_input_time(const uint32_t timestamp_as_uint)
GHOST_IWindow * createWindow(const char *title, int32_t left, int32_t top, uint32_t width, uint32_t height, GHOST_TWindowState state, GHOST_GPUSettings gpu_settings, const bool exclusive, const bool is_dialog, const GHOST_IWindow *parent_window) override
uint * getClipboardImage(int *r_width, int *r_height) const override
struct xdg_wm_base * xdg_decor_shell_get()
struct wl_compositor * wl_compositor_get()
struct wp_fractional_scale_manager_v1 * wp_fractional_scale_manager_get()
struct wl_subcompositor * wl_subcompositor_get()
void setMultitouchGestures(const bool use) override
struct wl_shm * wl_shm_get() const
GHOST_TSuccess getButtons(GHOST_Buttons &buttons) const override
GHOST_TSuccess cursor_shape_set(GHOST_TStandardCursor shape)
GHOST_TSuccess disposeContext(GHOST_IContext *context) override
struct wp_viewporter * wp_viewporter_get()
struct zxdg_decoration_manager_v1 * xdg_decor_manager_get()
struct wl_seat * wl_seat_active_get_with_input_serial(uint32_t &serial)
GHOST_TSuccess cursor_bitmap_get(GHOST_CursorBitmapRef *bitmap)
GHOST_TSuccess pushEvent_maybe_pending(std::unique_ptr< const GHOST_IEvent > event)
GHOST_TSuccess cursor_shape_custom_set(const GHOST_CursorGenerator &cg)
GHOST_TSuccess getCursorPosition(int32_t &x, int32_t &y) const override
void ime_begin(const GHOST_WindowWayland *win, int32_t x, int32_t y, int32_t w, int32_t h, bool completed) const
uint8_t getNumDisplays() const override
bool output_unref(struct wl_output *wl_output)
void putClipboard(const char *buffer, bool selection) const override
void output_scale_update(GWL_Output *output)
GHOST_TCapabilityFlag getCapabilities() const override
struct wp_color_manager_v1 * wp_color_manager_get()
bool window_cursor_grab_set(const GHOST_TGrabCursorMode mode, const GHOST_TGrabCursorMode mode_current, int32_t init_grab_xy[2], const GHOST_Rect *wrap_bounds, GHOST_TAxisFlag wrap_axis, wl_surface *wl_surface, const struct GWL_WindowScaleParams &scale_params, const GHOST_TDrawingContextType context_type)
std::atomic< bool > has_pending_actions_for_window
bool processEvents(bool waitForEvent) override
void seat_active_set(const struct GWL_Seat *seat)
GHOST_TSuccess getCursorPositionClientRelative(const GHOST_IWindow *window, int32_t &x, int32_t &y) const override
GHOST_TSuccess cursor_shape_check(GHOST_TStandardCursor cursor_shape)
GHOST_TSuccess setCursorPositionClientRelative(GHOST_IWindow *window, int32_t x, int32_t y) override
GHOST_TSuccess hasClipboardImage() const override
bool setConsoleWindowState(GHOST_TConsoleWindowState action) override
void getMainDisplayDimensions(uint32_t &width, uint32_t &height) const override
struct xdg_activation_v1 * xdg_activation_manager_get()
uint32_t getCursorPreferredLogicalSize() const override
struct zwp_pointer_gestures_v1 * wp_pointer_gestures_get()
void ime_end(const GHOST_WindowWayland *win) const
void getAllDisplayDimensions(uint32_t &width, uint32_t &height) const override
GHOST_TSuccess putClipboardImage(uint *rgba, int width, int height) const override
GHOST_EventManager * getEventManager() const
GHOST_WindowManager * getWindowManager() const
const GHOST_CSD_Params & getWindowCSD() const
GHOST_WindowManager * window_manager_
GHOST_TSuccess init() override
GHOST_TimerManager * getTimerManager() const
GHOST_TSuccess pushEvent(std::unique_ptr< const GHOST_IEvent > event)
bool multitouch_gestures_
const GHOST_IconGenerator * icon_generator_
void setWindowCSD_Layout(const GHOST_CSD_Layout &csd_layout)
GHOST_TSuccess removeTimer(GHOST_TimerTask *timer)
GHOST_TSuccess addTimer(GHOST_TimerTask *timer)
GHOST_TimerTask(uint64_t start, uint64_t interval, GHOST_TimerProcPtr timer_proc, GHOST_TUserDataPtr user_data=nullptr)
GHOST_TSuccess addWindow(GHOST_IWindow *window)
const std::vector< GHOST_IWindow * > & getWindows() const
GHOST_TSuccess setActiveWindow(GHOST_IWindow *window)
void setWindowInactive(const GHOST_IWindow *window)
const struct GWL_WindowScaleParams & scale_params_get() const
bool outputs_leave(GWL_Output *output)
wl_fixed_t wl_fixed_to_window(wl_fixed_t value) const
GHOST_WindowWayland(GHOST_SystemWayland *system, const char *title, int32_t left, int32_t top, uint32_t width, uint32_t height, GHOST_TWindowState state, const GHOST_IWindow *parent_window, GHOST_TDrawingContextType type, const bool is_dialog, const GHOST_ContextParams &context_params, const bool exclusive, const GHOST_GPUDevice &preferred_device)
bool getValid() const override
wl_fixed_t wl_fixed_from_window(wl_fixed_t value) const
void getClientBounds(GHOST_Rect &bounds) const override
const std::span< GWL_Output *const > outputs_get() const
uint16_t getDPIHint() override
GHOST_TSuccess cursor_shape_refresh()
GWL_XDG_WindowIcon & gwl_xdg_icon_get()
virtual GHOST_TSuccess getCursorGrabBounds(GHOST_Rect &bounds) const
GHOST_TAxisFlag getCursorGrabAxis() const
GHOST_TGrabCursorMode getCursorGrabMode() const
bool getCursorGrabModeIsWarp() const
int64_t size() const
bool is_empty() const
#define printf
#define str(s)
#define position
#define index(i)
float distance(float, float) RET
constexpr T degrees(T) RET
float3x3 scale(float3x3 mat, float2 scale)
const int state
#define LOG(level)
Definition log.h:97
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
bool is_enabled(const Scene &scene, ExecutionMode mode)
int size(const AssetLibraryReference *library_reference)
constexpr Serial serial
constexpr toml::spec version
Definition recents.cc:33
unsigned int uint
Definition BKE_text.h:55
Vector< uint8_t > IMB_save_image_to_buffer(ImBuf *ibuf, ImBufFlags flags)
Definition writeimage.cc:64
ImBuf * IMB_load_image_from_filepath(const char *filepath, ImBufFlags flags, ColorManagedColorspaceSettings *colorspace_settings=nullptr)
Definition readimage.cc:201
unsigned int uint32_t
Definition BKE_text.h:81
void IMB_freeImBuf(ImBuf *ibuf)
BMesh const char void * data
ImBuf * IMB_load_image_from_memory(const unsigned char *mem, size_t size, ImBufFlags flags, const char *descr, const char *filepath=nullptr, ColorManagedColorspaceSettings *colorspace_settings=nullptr)
Definition readimage.cc:132
ImBuf * IMB_allocFromBuffer(const uint8_t *byte_buffer, const float *float_buffer, unsigned int w, unsigned int h, unsigned int channels)
bool IMB_test_image(const char *filepath)
std::string format(const std::string &fmt, Args &&...args)
Definition diagnostic.hh:43
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
std::unordered_set< uint32_t > supported_features
std::unordered_set< uint32_t > supported_intents
std::unordered_set< uint32_t > supported_transfers
std::unordered_set< uint32_t > supported_primaries
void set(GHOST_TButton mask, bool down)
int32_t bounds[2][2]
GHOST_TCSD_Type type
GHOST_CSD_EventState_ButtonAction action_history[3]
GHOST_CSD_EventState_Button buttons[1]
GHOST_TCSD_Type buttons[5]
const uint8_t * data
uint8_t *(*) generate_fn(const struct GHOST_CursorGenerator *cursor_generator, int cursor_size, int cursor_size_max, uint8_t *(*alloc_fn)(size_t size), int r_bitmap_size[2], int r_hot_spot[2], bool *r_can_invert_color)
GHOST_TDrawingContextType context_type
GHOST_GPUDevice preferred_device
void(*) generate_fn(const struct GHOST_IconGenerator *icon_generator, GHOST_IWindow *window, uint8_t *pixels, int icon_size)
void set(GHOST_TModifierKey mask, bool down)
std::string composite
GHOST_TTabletMode Active
wp_cursor_shape_device_v1_shape enum_id
wp_cursor_shape_device_v1 * device
wl_surface * surface_cursor
wl_cursor_image image
struct GWL_Cursor::@314323000336233220053044211217215260043022110370 wl
GWL_CursorShape shape
enum wl_data_device_manager_dnd_action action
enum wl_data_device_manager_dnd_action source_actions
std::unordered_set< std::string > types
struct GWL_DataOffer::@147314011101112272276200161236160363120320024113 dnd
struct GWL_DataOffer::@330245371112075341223137156202074106325150315265 wl
GWL_SimpleBuffer buffer_out
struct GWL_DataSource::@125015032307213225102306360346203116110370120237 wl
wl_compositor * compositor
wl_subcompositor * subcompositor
wl_data_device_manager * data_device_manager
wp_color_manager_v1 * color_manager
wp_fractional_scale_manager_v1 * fractional_scale_manager
zwp_tablet_manager_v2 * tablet_manager
zwp_pointer_constraints_v1 * pointer_constraints
wp_viewporter * viewporter
zwp_relative_pointer_manager_v1 * relative_pointer_manager
wp_cursor_shape_manager_v1 * cursor_shape_manager
zwp_primary_selection_device_manager_v1 * primary_selection_device_manager
zwp_pointer_gestures_v1 * pointer_gestures
wl_event_queue * color_manager_queue
xdg_activation_v1 * activation_manager
zxdg_output_manager_v1 * output_manager
xdg_toplevel_icon_manager_v1 * toplevel_icon_manager
std::vector< GWL_Seat * > seats
struct GWL_Display::@277165256066036227055246100260074022344031031116 wl
bool supports_color_manager_extended_srgb_linear
struct GWL_Display::@334354154372233112110216243051323015254071064001 xdg
std::vector< GWL_Output * > outputs
bool supports_color_manager_feature_windows_scrgb
GWL_DisplayTimeStamp input_timestamp
GWL_XDG_Decor_System * xdg_decor
GWL_RegistryEntry * registry_entry
struct GWL_Display::@343256373343037257351064040231203210353357104223 preferences
GHOST_TimerManager * key_repeat_timer_manager
struct GWL_Display::@175264057036315311150262170030065173245371075342 wp
GHOST_SystemWayland * system
std::mutex events_pending_mutex
std::vector< std::unique_ptr< const GHOST_IEvent > > events_pending
struct GWL_KeyRepeatPlayload::@143313365314317262065200322120246146007031257122 key_data
int16_t mods[GHOST_KEY_MODIFIER_NUM]
GHOST_TModifierKey mod_l
GHOST_TModifierKey mod_r
std::unordered_set< std::string > types
struct GWL_PrimarySelection_DataOffer::@304056113042126166305355272212365024044000320333 wp
zwp_primary_selection_source_v1 * source
struct GWL_PrimarySelection_DataSource::@262172322224217140223156023104024361151202160341 wp
GWL_PrimarySelection_DataSource * data_source
GWL_PrimarySelection_DataOffer * data_offer
GWL_RegistryEntry * next
GWL_RegistryHandler_AddFn add_fn
const char *const * interface_p
GWL_RegistryEntry_RemoveFn remove_fn
GWL_RegistryHandler_UpdateFn update_fn
struct GWL_SeatStateKeyboard::@002236227201217376126360362076131233146143306151 wl
enum wl_pointer_axis_source axis_source
GWL_SeatStatePointerScroll_SmoothAsDiscrete smooth_as_discrete
uint32_t frame_serial[GWL_TabletTool_FrameTypes_NUM]
GWL_Pointer_EventTypes frame_types[GWL_TabletTool_FrameTypes_NUM]
uint64_t frame_event_ms[GWL_TabletTool_FrameTypes_NUM]
struct GWL_SeatStatePointer_Events::@271006335365153047125127025353303353266201161350 frame_pending
struct GWL_SeatStatePointer::@176021020360003204014146270025272344077006150320 wl
std::unordered_set< const GWL_Output * > outputs
GHOST_ITimerTask * timer
wl_surface * surface_window_focus_dnd
wl_pointer * pointer
wl_data_device * data_device
wl_keyboard * keyboard
zwp_relative_pointer_v1 * relative_pointer
zwp_primary_selection_device_v1 * primary_selection_device
std::unordered_set< zwp_tablet_tool_v2 * > tablet_tools
zwp_tablet_seat_v2 * tablet_seat
zwp_locked_pointer_v1 * locked_pointer
zwp_confined_pointer_v1 * confined_pointer
xkb_layout_index_t layout_fallback
xkb_layout_index_t layout_active
xkb_compose_state * compose_state
xkb_context * context
xkb_state * state_empty_with_numlock
xkb_compose_table * compose_table
xkb_state * state_empty_with_shift
struct GWL_Seat::@077323275360216145363375106070375251161004153061 key_repeat
struct GWL_Seat::@152027136010022314057316376113115357364375226120 wp
GHOST_SystemWayland * system
GWL_SeatStatePointerScroll pointer_scroll
GWL_KeyboardDepressedState key_depressed
GWL_SeatStatePointer_Events pointer_events
GWL_DataSource * data_source
GWL_SeatStatePointer touch
uint32_t data_source_serial
GWL_DataOffer * data_offer_copy_paste
struct GWL_Seat::@161057270257110375042361055064237015070232240153 wl
GWL_SeatStatePointer pointer
std::mutex data_source_mutex
xkb_mod_index_t xkb_keymap_mod_index[MOD_INDEX_NUM]
std::optional< GHOST_TSuccess > data_offer_copy_paste_has_image
std::mutex data_offer_dnd_mutex
GWL_PrimarySelection primary_selection
std::mutex data_offer_copy_paste_mutex
uint32_t cursor_source_serial
GWL_SeatStatePointer tablet
bool use_pointer_scroll_smooth_as_discrete
struct GWL_Seat::@311222234142063271106307226121357254360171231034 touch_state
xkb_mod_index_t xkb_keymap_mod_index_numlock
bool xkb_use_non_latin_workaround
wl_fixed_t grab_lock_xy[2]
GWL_DataOffer * data_offer_dnd
xkb_mod_index_t xkb_keymap_mod_index_mod2
GWL_SeatStatePointerGesture_Pinch pointer_gesture_pinch
struct GWL_Seat::@317134123165032204353254344161063045010227232131 xkb
GWL_SeatStateKeyboard keyboard
bool use_pointer_software_confine
uint32_t frame_serial[GWL_TabletTool_FrameTypes_NUM]
struct GWL_TabletTool::@140147224327332122261230001224033040016232074210::@050137376222371001256241222343132144210001050377 wheel
GWL_TabletTool_EventTypes frame_types[GWL_TabletTool_FrameTypes_NUM]
GWL_CursorShape shape
struct GWL_TabletTool::@166163171265245064266340334273040151351113325035 wl
GHOST_TabletData data
struct GWL_TabletTool::@140147224327332122261230001224033040016232074210 frame_pending
zxdg_decoration_manager_v1 * manager
struct wl_buffer * buffer
ImbFormatOptions foptions
const uint8_t * byte_data() const
eImbFileType ftype
void wayland_dynload_client_exit(void)
void wayland_dynload_cursor_exit(void)
bool wayland_dynload_cursor_init(bool verbose)
bool wayland_dynload_client_init(bool verbose)
#define wl_proxy_get_tag(...)
#define wl_display_connect(...)
#define wl_log_set_handler_client(...)
#define wl_display_dispatch_pending(...)
#define wl_proxy_set_tag(...)
#define wl_proxy_create_wrapper(...)
#define wl_display_get_error(...)
#define wl_display_cancel_read(...)
#define wl_display_dispatch(...)
#define wl_display_dispatch_queue_pending(...)
#define wl_display_get_fd(...)
#define wl_display_prepare_read_queue(...)
#define wl_display_prepare_read(...)
#define wl_display_create_queue(...)
#define wl_proxy_wrapper_destroy(...)
#define wl_display_flush(...)
#define wl_display_get_protocol_error(...)
#define wl_display_disconnect(...)
#define wl_display_read_events(...)
#define wl_proxy_set_queue(...)
#define wl_display_roundtrip(...)
#define wl_event_queue_destroy(...)
void wayland_dynload_egl_exit(void)
#define wl_egl_window_create(...)
#define wl_egl_window_destroy(...)