Skip to content
Myr

wayland.c

This file

Path

wayland.c

3,578 lines · 106.8 KiB · C

Last changed by

landed by oscabriel815d438

History of this file

Take it

1#include "wayland.h"2#include "char32.h"34#include <ctype.h>5#include <errno.h>6#include <locale.h>7#include <math.h>8#include <poll.h>9#include <stdlib.h>10#include <string.h>11#include <unistd.h>12#include <wctype.h>1314#include <sys/mman.h>15#include <sys/epoll.h>16#include <sys/timerfd.h>17#include <sys/time.h>1819#include <wayland-client.h>20#include <wayland-cursor.h>21#include <wayland-util.h>2223#include <linux/input-event-codes.h>24#include <xkbcommon/xkbcommon.h>25#include <xkbcommon/xkbcommon-keysyms.h>26#include <xkbcommon/xkbcommon-compose.h>27#include <fontconfig/fontconfig.h>2829#include <color-management-v1.h>30#include <cursor-shape-v1.h>31#include <fractional-scale-v1.h>32#include <primary-selection-unstable-v1.h>33#include <single-pixel-buffer-v1.h>34#include <text-input-unstable-v3.h>35#include <viewporter.h>36#include <wlr-layer-shell-unstable-v1.h>37#include <xdg-activation-v1.h>38#include <xdg-output-unstable-v1.h>3940#include <tllist.h>4142#define LOG_MODULE "wayland"43#define LOG_ENABLE_DBG 044#include "log.h"45#include "clipboard.h"46#include "dmenu.h"47#include "icon.h"48#include "key-binding.h"49#include "prompt.h"50#include "render.h"51#include "shm.h"52#include "xmalloc.h"53#include "xsnprintf.h"5455#include "timing.h"5657#define min(x, y) ((x) < (y) ? (x) : (y))5859struct font_spec {60    char *pattern;61    double pt_size;62    int px_size;63};6465struct monitor {66    struct wayland *wayl;67    struct wl_output *output;68    struct zxdg_output_v1 *xdg;69    uint32_t wl_name;7071    int x;72    int y;7374    struct {75        /* Physical size, in mm */76        struct {77            int width;78            int height;79        } mm;8081        /* Physical size, in pixels */82        struct {83            int width;84            int height;85        } px_real;8687        /* Scaled size, in pixels */88        struct {89            int width;90            int height;91        } px_scaled;92    } dim;9394    struct {95        /* PPI, based on physical size */96        struct {97            int x;98            int y;99        } real;100101        /* PPI, logical, based on scaled size */102        struct {103            int x;104            int y;105        } scaled;106    } ppi;107108    float dpi;109110    enum wl_output_transform transform;111112    /* From wl_output */113    char *make;114    char *model;115116    /* From xdg_output */117    char *name;118    char *description;119120    float inch;  /* e.g. 24" */121    float refresh;122123    int scale;124    enum fcft_subpixel subpixel;125};126127struct wayland {128    const struct config *conf;129    struct fdm *fdm;130    struct kb_manager *kb_manager;131    struct render *render;132    struct prompt *prompt;133    struct matches *matches;134135    struct font_spec *fonts;136    size_t font_count;137    struct {138        font_reloaded_t cb;139        void *data;140    } font_reloaded;141142    bool render_first_frame_transparent;143    int width;144    int height;145    int preferred_buffer_scale;         /* Legacy - from wl_surface v6 */146    float preferred_fractional_scale;   /* New - from wp_fractional_scale_v1 */147    float initial_scale_guess;          /* Scale used for initial commit */148    bool got_preferred_scale_early;     /* Did we get fractional scale before configure? */149    float scale;150    float dpi;151    enum fcft_subpixel subpixel;152    bool font_is_sized_by_dpi;153    bool hide_when_prompt_empty;154    bool enable_mouse;155156    enum { KEEP_RUNNING, EXIT_UPDATE_CACHE, EXIT} status;157    int exit_code;158    bool force_cache_update;159160    struct wl_callback *frame_cb;161    bool need_refresh;162    bool is_configured;163164    struct wl_display *display;165    struct wl_registry *registry;166    struct wl_compositor *compositor;167    bool has_wl_compositor_v6;168169    struct wp_fractional_scale_manager_v1 *fractional_scale_manager;170    struct wp_viewporter *viewporter;171172    struct wl_surface *surface;173    struct zwlr_layer_shell_v1 *layer_shell;174    struct zwlr_layer_surface_v1 *layer_surface;175    bool has_zwlr_layer_shell_kb_inter_on_demand;176177    struct wp_viewport *viewport;178    struct wp_fractional_scale_v1 *fractional_scale;179    struct wp_color_management_surface_v1 *color_management_surface;180181    struct wl_shm *shm;182    struct zxdg_output_manager_v1 *xdg_output_manager;183    struct xdg_activation_v1 *xdg_activation_v1;184    struct wp_cursor_shape_manager_v1 *cursor_shape_manager;185186    struct wl_data_device_manager *data_device_manager;187    struct zwp_primary_selection_device_manager_v1 *primary_selection_device_manager;188189    struct {190        struct wp_color_manager_v1 *manager;191        struct wp_image_description_v1 *img_description;192        bool have_intent_perceptual;193        bool have_feat_parametric;194        bool have_tf_ext_linear;195        bool have_primaries_srgb;196    } color_management;197198    struct wp_single_pixel_buffer_manager_v1 *single_pixel_manager;199    struct zwp_text_input_manager_v3 *text_input_manager;200201    /* Active preedit text (displayed inline in the prompt) */202    struct {203        char32_t *text;          /* NULL when no preedit is active */204        int32_t cursor;          /* glyph index for cursor (-1 = hidden) */205    } preedit;206207    tll(struct monitor) monitors;208    const struct monitor *monitor;209210    tll(struct seat) seats;211212    struct buffer_chain *chain;213214    bool shm_have_abgr161616;215    bool shm_have_xbgr161616;216217    bool ready_to_display;218};219220bool221repeat_start(struct repeat *repeat, uint32_t key)222{223    if (repeat->dont_re_repeat)224        return true;225226    if (repeat->rate == 0)227        return true;228229    struct itimerspec t = {230        .it_value = {.tv_sec = 0, .tv_nsec = repeat->delay * 1000000},231        .it_interval = {.tv_sec = 0, .tv_nsec = 1000000000 / repeat->rate},232    };233234    if (t.it_value.tv_nsec >= 1000000000) {235        t.it_value.tv_sec += t.it_value.tv_nsec / 1000000000;236        t.it_value.tv_nsec %= 1000000000;237    }238    if (t.it_interval.tv_nsec >= 1000000000) {239        t.it_interval.tv_sec += t.it_interval.tv_nsec / 1000000000;240        t.it_interval.tv_nsec %= 1000000000;241    }242    if (timerfd_settime(repeat->fd, 0, &t, NULL) < 0) {243        LOG_ERRNO("failed to arm keyboard repeat timer");244        return false;245    }246247    repeat->key = key;248    return true;249}250251bool252repeat_stop(struct repeat *repeat, uint32_t key)253{254    if (key != (uint32_t)-1 && key != repeat->key)255        return true;256257    if (timerfd_settime(repeat->fd, 0, &(struct itimerspec){{0}}, NULL) < 0) {258        LOG_ERRNO("failed to disarm keyboard repeat timer");259        return false;260    }261262    return true;263}264265static void266seat_destroy(struct seat *seat)267{268    if (seat == NULL)269        return;270271    kb_remove_seat(seat->wayl->kb_manager, seat);272273    if (seat->clipboard.data_source != NULL)274        wl_data_source_destroy(seat->clipboard.data_source);275    if (seat->clipboard.data_offer != NULL)276        wl_data_offer_destroy(seat->clipboard.data_offer);277    if (seat->primary.data_source != NULL)278        zwp_primary_selection_source_v1_destroy(seat->primary.data_source);279    if (seat->primary.data_offer != NULL)280        zwp_primary_selection_offer_v1_destroy(seat->primary.data_offer);281    if (seat->primary_selection_device != NULL)282        zwp_primary_selection_device_v1_destroy(seat->primary_selection_device);283    if (seat->data_device != NULL)284        wl_data_device_release(seat->data_device);285    if (seat->kbd.xkb_compose_state != NULL)286        xkb_compose_state_unref(seat->kbd.xkb_compose_state);287    if (seat->kbd.xkb_compose_table != NULL)288        xkb_compose_table_unref(seat->kbd.xkb_compose_table);289    if (seat->kbd.xkb_state != NULL)290        xkb_state_unref(seat->kbd.xkb_state);291    if (seat->kbd.xkb_keymap != NULL)292        xkb_keymap_unref(seat->kbd.xkb_keymap);293    if (seat->kbd.xkb != NULL)294        xkb_context_unref(seat->kbd.xkb);295    if (seat->kbd.repeat.fd > 0)296        fdm_del(seat->wayl->fdm, seat->kbd.repeat.fd);297    if (seat->wl_keyboard != NULL)298        wl_keyboard_release(seat->wl_keyboard);299300    if (seat->pointer.viewport != NULL)301        wp_viewport_destroy(seat->pointer.viewport);302    if (seat->pointer.theme != NULL)303        wl_cursor_theme_destroy(seat->pointer.theme);304    if (seat->pointer.surface != NULL)305        wl_surface_destroy(seat->pointer.surface);306    if (seat->wl_pointer != NULL)307        wl_pointer_release(seat->wl_pointer);308309    if (seat->wl_touch != NULL)310        wl_touch_release(seat->wl_touch);311312    if (seat->wl_seat != NULL)313        wl_seat_release(seat->wl_seat);314315    if (seat->text_input != NULL)316        zwp_text_input_v3_destroy(seat->text_input);317    free(seat->ime.preedit_pending.text);318    free(seat->ime.commit_pending);319320    free(seat->clipboard.text);321    free(seat->primary.text);322    free(seat->name);323}324325static void326update_cursor_surface(struct seat *seat)327{328    if (seat->pointer.surface == NULL || seat->pointer.theme == NULL)329        return;330331    if (seat->pointer.cursor == NULL) {332        seat->pointer.cursor = wl_cursor_theme_get_cursor(333            seat->pointer.theme, "left_ptr");334335        if (seat->pointer.cursor == NULL) {336            LOG_ERR("%s: failed to load cursor 'left_ptr'", seat->name);337            return;338        }339    }340341    struct wl_cursor_image *image = seat->pointer.cursor->images[0];342343    const struct wayland *wayl = seat->wayl;344    const float scale = seat->pointer.scale;345346    if (wayl->preferred_fractional_scale > 0) {347        LOG_DBG("scaling cursor pointer by a factor of %.2f "348                "using fractional scaling", scale);349350        wl_surface_set_buffer_scale(seat->pointer.surface, 1);351        wp_viewport_set_destination(seat->pointer.viewport,352                                    roundf(image->width / scale),353                                    roundf(image->height / scale));354    } else {355        LOG_DBG("scaling cursor pointer by a factor of %.2f "356                "using legacy mode", scale);357358        wl_surface_set_buffer_scale(seat->pointer.surface, scale);359    }360361    wl_surface_attach(362        seat->pointer.surface, wl_cursor_image_get_buffer(image), 0, 0);363364    wl_pointer_set_cursor(365        seat->wl_pointer, seat->pointer.serial, seat->pointer.surface,366        image->hotspot_x / scale, image->hotspot_y / scale);367368    wl_surface_damage_buffer(seat->pointer.surface, 0, 0, INT32_MAX, INT32_MAX);369370    wl_surface_commit(seat->pointer.surface);371    wl_display_flush(seat->wayl->display);372}373374static bool375reload_cursor_theme(struct seat *seat, float new_scale)376{377    assert(seat->pointer.surface != NULL);378379    if (seat->pointer.theme != NULL && seat->pointer.scale == new_scale)380        return true;381382    if (seat->pointer.theme != NULL) {383        wl_cursor_theme_destroy(seat->pointer.theme);384        seat->pointer.theme = NULL;385        seat->pointer.cursor = NULL;386    }387388    const char *xcursor_theme = getenv("XCURSOR_THEME");389    int xcursor_size = 24;390391    {392        const char *env_cursor_size = getenv("XCURSOR_SIZE");393        if (env_cursor_size != NULL) {394            unsigned size;395            if (sscanf(env_cursor_size, "%u", &size) == 1)396                xcursor_size = size;397        }398    }399400    LOG_INFO("cursor theme: %s, size: %u, scale: %0.2f",401             xcursor_theme, xcursor_size, new_scale);402403    seat->pointer.theme = wl_cursor_theme_load(404        xcursor_theme, xcursor_size * new_scale, seat->wayl->shm);405406    if (seat->pointer.theme == NULL) {407        LOG_ERR("failed to load cursor theme");408        return false;409    }410411    seat->pointer.scale = new_scale;412    return true;413}414415static void416shm_format(void *data, struct wl_shm *wl_shm, uint32_t format)417{418    struct wayland *wayl = data;419420    switch (format) {421#if 0  /* Don't bother with 10bpc formats right now, since they have too few alpha bits */422    case WL_SHM_FORMAT_XRGB2101010: wayl->shm_have_xrgb2101010 = true; break;423    case WL_SHM_FORMAT_ARGB2101010: wayl->shm_have_argb2101010 = true; break;424    case WL_SHM_FORMAT_XBGR2101010: wayl->shm_have_xbgr2101010 = true; break;425    case WL_SHM_FORMAT_ABGR2101010: wayl->shm_have_abgr2101010 = true; break;426#endif427    case WL_SHM_FORMAT_XBGR16161616: wayl->shm_have_xbgr161616 = true; break;428    case WL_SHM_FORMAT_ABGR16161616: wayl->shm_have_abgr161616 = true; break;429    }430}431432static const struct wl_shm_listener shm_listener = {433    .format = &shm_format,434};435436static void437keyboard_keymap(void *data, struct wl_keyboard *wl_keyboard,438                uint32_t format, int32_t fd, uint32_t size)439{440    struct seat *seat = data;441442    if (seat->kbd.xkb_compose_state != NULL) {443        xkb_compose_state_unref(seat->kbd.xkb_compose_state);444        seat->kbd.xkb_compose_state = NULL;445    }446    if (seat->kbd.xkb_compose_table != NULL) {447        xkb_compose_table_unref(seat->kbd.xkb_compose_table);448        seat->kbd.xkb_compose_table = NULL;449    }450    if (seat->kbd.xkb_keymap != NULL) {451        xkb_keymap_unref(seat->kbd.xkb_keymap);452        seat->kbd.xkb_keymap = NULL;453    }454    if (seat->kbd.xkb_state != NULL) {455        xkb_state_unref(seat->kbd.xkb_state);456        seat->kbd.xkb_state = NULL;457    }458    if (seat->kbd.xkb != NULL) {459        xkb_context_unref(seat->kbd.xkb);460        seat->kbd.xkb = NULL;461    }462463    kb_unload_keymap(seat->wayl->kb_manager, seat);464465    /* Verify keymap is in a format we understand */466    switch ((enum wl_keyboard_keymap_format)format) {467    case WL_KEYBOARD_KEYMAP_FORMAT_NO_KEYMAP:468        return;469470    case WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1:471        break;472473    default:474        LOG_WARN("unrecognized keymap format: %u", format);475        return;476    }477478    char *map_str = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);479    if (map_str == MAP_FAILED) {480        LOG_ERRNO("failed to mmap keyboard keymap");481        close(fd);482        return;483    }484485    while (map_str[size - 1] == '\0')486        size--;487488    seat->kbd.xkb = xkb_context_new(XKB_CONTEXT_NO_FLAGS);489    if (seat->kbd.xkb != NULL) {490        seat->kbd.xkb_keymap = xkb_keymap_new_from_buffer(491            seat->kbd.xkb, map_str, size, XKB_KEYMAP_FORMAT_TEXT_V1,492            XKB_KEYMAP_COMPILE_NO_FLAGS);493494        /* Compose (dead keys) */495        seat->kbd.xkb_compose_table = xkb_compose_table_new_from_locale(496            seat->kbd.xkb, setlocale(LC_CTYPE, NULL), XKB_COMPOSE_COMPILE_NO_FLAGS);497498        if (seat->kbd.xkb_compose_table == NULL) {499            LOG_WARN("failed to instantiate compose table; dead keys will not work");500        } else {501            seat->kbd.xkb_compose_state = xkb_compose_state_new(502                seat->kbd.xkb_compose_table, XKB_COMPOSE_STATE_NO_FLAGS);503        }504    }505506    if (seat->kbd.xkb_keymap != NULL) {507        /* TODO: initialize in enter? */508        seat->kbd.xkb_state = xkb_state_new(seat->kbd.xkb_keymap);509    }510511    munmap(map_str, size);512    close(fd);513514    if (seat->kbd.xkb_state != NULL && seat->kbd.xkb_keymap != NULL) {515        kb_load_keymap(seat->wayl->kb_manager, seat,516                       seat->kbd.xkb_state, seat->kbd.xkb_keymap);517    }518}519520static void521keyboard_enter(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial,522               struct wl_surface *surface, struct wl_array *keys)523{524    struct seat *seat = data;525    seat->kbd.serial = serial;526527    LOG_DBG("keyboard enter");528#if 0529    uint32_t *key;530    wl_array_for_each(key, keys)531        xkb_state_update_key(xkb_state, *key, 1);532#endif533}534535static void536keyboard_leave(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial,537               struct wl_surface *surface)538{539    struct seat *seat = data;540    repeat_stop(&seat->kbd.repeat, -1);541    seat->kbd.serial = 0;542543    if (seat->kbd.xkb_compose_state != NULL)544        xkb_compose_state_reset(seat->kbd.xkb_compose_state);545546    if (seat->kbd.xkb_state != NULL && seat->kbd.xkb_keymap != NULL) {547        const xkb_layout_index_t layout_count = xkb_keymap_num_layouts(seat->kbd.xkb_keymap);548549        for (xkb_layout_index_t i = 0; i < layout_count; i++)550            xkb_state_update_mask(seat->kbd.xkb_state, 0, 0, 0, i, i, i);551    }552553    if (seat->wayl->conf->exit_on_kb_focus_loss)554        seat->wayl->status = EXIT;555}556557static void558token_done(void *data, struct xdg_activation_token_v1 *token,559           const char *name)560{561    char **xdg_activation_token = data;562    *xdg_activation_token = xstrdup(name);563}564565static const struct xdg_activation_token_v1_listener token_listener = {566    .done = token_done567};568569570/* Synchronously grab a token from the compositor. The compositor may refuse to571 * grant a token by not sending the done event. In this case, the572 * xdg_activation_token return parameter will not be modified.573 */574static void575get_xdg_activation_token(struct seat *seat, const char *app_id,576                         char **xdg_activation_token)577{578    struct wayland *wayl = seat->wayl;579    struct xdg_activation_token_v1 *token =580        xdg_activation_v1_get_activation_token(wayl->xdg_activation_v1);581582    xdg_activation_token_v1_set_serial(token, seat->kbd.serial, seat->wl_seat);583    xdg_activation_token_v1_set_surface(token, wayl->surface);584585    if (app_id != NULL)586        xdg_activation_token_v1_set_app_id(token, app_id);587588    xdg_activation_token_v1_add_listener(589        token, &token_listener, xdg_activation_token);590591    xdg_activation_token_v1_commit(token);592    wl_display_roundtrip(wayl->display);593    xdg_activation_token_v1_destroy(token);594}595596static void execute_selected(struct seat *seat, bool as_is, int custom_success_exit_code);597598static bool599check_auto_select(struct seat *seat, bool refresh)600{601    struct wayland *wayl = seat->wayl;602603    /* Check for auto-select after key binding execution */604    if (refresh && wayl->conf->auto_select) {605        if (matches_get_total_count(wayl->matches) == 1) {606            execute_selected(seat, false, -1);607            return true;608        }609    }610    return false;611}612613/*614 * NOTE: this function is expected to be called from an outside615 * context. It MUST NOT be called while inside a fdm_handler()616 * callchain */617bool618wayl_check_auto_select(struct wayland *wayl)619{620    if (tll_length(wayl->seats) == 0)621        return false;622623    struct seat *seat = &tll_front(wayl->seats);624625    /*626     * This is finicky... check_auto_select() _may_ result in an627     * application being executed.628     *629     * Part of this involves retrieving and XDG activation token. This630     * requires a display roundtrip. The roundtrip will *not* work631     * wl_display_prepare_read() is active.632     *633     * So, we need to cancel the pending read, do our thing, and then634     * re-endter prepare_read().635     *636     * This will *not* work if wl_display_prepare_read() is *not*637     * active, hence the warning above, that this function must not be638     * called while inside an fdm_handler() callchain, since639     * fdm_handler() does read from the wayland socket.640     */641    wl_display_cancel_read(wayl->display);642    bool ret = check_auto_select(seat, true);643    wl_display_prepare_read(wayl->display);644    return ret;645}646647static void648execute_selected(struct seat *seat, bool as_is, int custom_success_exit_code)649{650    struct wayland *wayl = seat->wayl;651    wayl->status = EXIT;652653    const struct match *match = !as_is ? matches_get_match(wayl->matches) : NULL;654    struct application *app = match != NULL ? match->application : NULL;655    ssize_t index = app != NULL ? app->index : -1;656657    if (wayl->conf->dmenu.enabled) {658        dmenu_execute(app, index, wayl->prompt, wayl->conf->dmenu.mode,659                      wayl->conf->dmenu.accept_nth_format,660                      wayl->conf->dmenu.nth_delim);661        wayl->exit_code = custom_success_exit_code >= 0662            ? custom_success_exit_code663            : EXIT_SUCCESS;664        wayl->status = EXIT_UPDATE_CACHE;665        if (app != NULL)666            app->count++;667    } else {668        char *xdg_activation_token = NULL;669        if (wayl->xdg_activation_v1 != NULL && app != NULL && app->startup_notify)670            get_xdg_activation_token(seat, app->app_id, &xdg_activation_token);671672        bool success = application_execute(673            app, wayl->prompt, wayl->conf->launch_prefix, xdg_activation_token);674        free(xdg_activation_token);675676        wayl->exit_code = success677            ? (custom_success_exit_code >= 0678               ? custom_success_exit_code679               : EXIT_SUCCESS)680            : EXIT_FAILURE;681682        if (success) {683            wayl->status = EXIT_UPDATE_CACHE;684            if (app != NULL)685                app->count++;686        }687    }688}689690static bool691execute_binding(struct seat *seat, const struct key_binding *binding, bool *refresh)692{693    const enum bind_action action = binding->action;694    struct wayland *wayl = seat->wayl;695696    *refresh = false;697698    switch (action) {699    case BIND_ACTION_NONE:700        return true;701702    case BIND_ACTION_CANCEL:703        wayl->status = EXIT;704        if (wayl->conf->dmenu.enabled)705            wayl->exit_code = 2;706        return true;707708    case BIND_ACTION_CURSOR_HOME:709        *refresh = prompt_cursor_home(wayl->prompt);710        return true;711712    case BIND_ACTION_CURSOR_END:713        *refresh = prompt_cursor_end(wayl->prompt);714        return true;715716    case BIND_ACTION_CURSOR_LEFT:717        *refresh = prompt_cursor_prev_char(wayl->prompt);718        return true;719720    case BIND_ACTION_CURSOR_LEFT_WORD:721        *refresh = prompt_cursor_prev_word(wayl->prompt);722        return true;723724    case BIND_ACTION_CURSOR_RIGHT:725        *refresh = prompt_cursor_next_char(wayl->prompt);726        return true;727728    case BIND_ACTION_CURSOR_RIGHT_WORD:729        *refresh = prompt_cursor_next_word(wayl->prompt);730        return true;731732    case BIND_ACTION_DELETE_LINE:733        *refresh = prompt_erase_all(wayl->prompt);734        if (*refresh)735            matches_update(wayl->matches);736        return true;737738    case BIND_ACTION_DELETE_PREV:739        *refresh = prompt_erase_prev_char(wayl->prompt);740        if (*refresh)741            matches_update(wayl->matches);742        return true;743744    case BIND_ACTION_DELETE_PREV_WORD:745        *refresh = prompt_erase_prev_word(wayl->prompt);746        if (*refresh)747            matches_update(wayl->matches);748        return true;749750    case BIND_ACTION_DELETE_LINE_BACKWARD:751        *refresh = prompt_erase_before_cursor(wayl->prompt);752        if (*refresh)753            matches_update(wayl->matches);754        return true;755756    case BIND_ACTION_DELETE_NEXT:757        *refresh = prompt_erase_next_char(wayl->prompt);758        if (*refresh)759            matches_update(wayl->matches);760        return true;761762    case BIND_ACTION_DELETE_NEXT_WORD:763        *refresh = prompt_erase_next_word(wayl->prompt);764        if (*refresh)765            matches_update(wayl->matches);766        return true;767768    case BIND_ACTION_DELETE_LINE_FORWARD:769        *refresh = prompt_erase_after_cursor(wayl->prompt);770        if (*refresh)771            matches_update(wayl->matches);772        return true;773774    case BIND_ACTION_INSERT_SELECTED: {775        const struct match *match = matches_get_match(wayl->matches);776        if (match == NULL)777            return true;778779        prompt_erase_all(wayl->prompt);780781        if (wayl->conf->dmenu.enabled) {782            char *chars = ac32tombs(match->application->title);783            if (chars != NULL) {784                prompt_insert_chars(wayl->prompt, chars, strlen(chars));785                *refresh = true;786                free(chars);787            }788        } else if (match->application->exec != NULL) {789            const char *chars = match->application->exec;790            prompt_insert_chars(wayl->prompt, chars, strlen(chars));791            *refresh = true;792        }793794        if (*refresh)795            matches_update(wayl->matches);796        return true;797    }798799    case BIND_ACTION_EXPUNGE: {800        const struct match *match = matches_get_match(wayl->matches);801        if (match != NULL) {802            match->application->count = 0;803            matches_update(wayl->matches);804            wayl->force_cache_update = true;805            *refresh = true;806        } else807            *refresh = false;808        return true;809    }810811    case BIND_ACTION_CLIPBOARD_PASTE:812        paste_from_clipboard(seat);813        return true;814815    case BIND_ACTION_PRIMARY_PASTE:816        paste_from_primary(seat);817        return true;818819    case BIND_ACTION_MATCHES_EXECUTE: {820        const size_t match_count = matches_get_total_count(wayl->matches);821822        if (prompt_text(wayl->prompt)[0] == '\0' && match_count == 0) {823            /* Empty prompt, and no matches -> do nothing */824            return true;825        }826827        const bool dmenu_enabled = wayl->conf->dmenu.enabled;828        const bool only_match = wayl->conf->dmenu.only_match;829830        if (dmenu_enabled && only_match && match_count == 0) {831            /* --only-match, and no matches -> do nothing */832            return true;833        }834835        execute_selected(seat, false, -1);836        return true;837    }838839    case BIND_ACTION_MATCHES_EXECUTE_OR_NEXT:840        if (matches_get_total_count(wayl->matches) == 1)841            execute_selected(seat, false, -1);842        else843            *refresh = matches_selected_next(wayl->matches, true);844        return true;845846    case BIND_ACTION_MATCHES_EXECUTE_INPUT:847        execute_selected(seat, true, -1);848        return true;849850    case BIND_ACTION_MATCHES_PREV:851        *refresh = matches_selected_prev(wayl->matches, false);852        return true;853854    case BIND_ACTION_MATCHES_PREV_WITH_WRAP:855        *refresh = matches_selected_prev(wayl->matches, true);856        return true;857858    case BIND_ACTION_MATCHES_PREV_PAGE:859        *refresh = matches_selected_prev_page(wayl->matches, false);860        return true;861862    case BIND_ACTION_MATCHES_NEXT:863        *refresh = matches_selected_next(wayl->matches, false);864        return true;865866    case BIND_ACTION_MATCHES_NEXT_WITH_WRAP:867        *refresh = matches_selected_next(wayl->matches, true);868        return true;869870    case BIND_ACTION_MATCHES_NEXT_PAGE:871        *refresh = matches_selected_next_page(wayl->matches, false);872        return true;873874    case BIND_ACTION_MATCHES_FIRST:875        *refresh = matches_selected_first(wayl->matches);876        return true;877878    case BIND_ACTION_MATCHES_LAST:879        *refresh = matches_selected_last(wayl->matches);880        return true;881882    case BIND_ACTION_CUSTOM_1:883    case BIND_ACTION_CUSTOM_2:884    case BIND_ACTION_CUSTOM_3:885    case BIND_ACTION_CUSTOM_4:886    case BIND_ACTION_CUSTOM_5:887    case BIND_ACTION_CUSTOM_6:888    case BIND_ACTION_CUSTOM_7:889    case BIND_ACTION_CUSTOM_8:890    case BIND_ACTION_CUSTOM_9:891    case BIND_ACTION_CUSTOM_10:892    case BIND_ACTION_CUSTOM_11:893    case BIND_ACTION_CUSTOM_12:894    case BIND_ACTION_CUSTOM_13:895    case BIND_ACTION_CUSTOM_14:896    case BIND_ACTION_CUSTOM_15:897    case BIND_ACTION_CUSTOM_16:898    case BIND_ACTION_CUSTOM_17:899    case BIND_ACTION_CUSTOM_18:900    case BIND_ACTION_CUSTOM_19: {901        const size_t idx = action - BIND_ACTION_CUSTOM_1;902        execute_selected(seat, false, 10 + idx);903        return true;904    }905906    case BIND_ACTION_COUNT:907        assert(false);908        return false;909    }910911    return false;912}913914static void915keyboard_key(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial,916             uint32_t time, uint32_t key, uint32_t state)917{918    struct seat *seat = data;919    struct wayland *wayl = seat->wayl;920921    if (seat->kbd.xkb == NULL ||922        seat->kbd.xkb_keymap == NULL ||923        seat->kbd.xkb_state == NULL)924    {925        return;926    }927928    if (state == XKB_KEY_UP) {929        repeat_stop(&seat->kbd.repeat, key);930        return;931    }932933    key += 8;934    bool should_repeat = xkb_keymap_key_repeats(seat->kbd.xkb_keymap, key);935    xkb_keysym_t sym = xkb_state_key_get_one_sym(seat->kbd.xkb_state, key);936937    enum xkb_compose_status compose_status = XKB_COMPOSE_NOTHING;938939    if (seat->kbd.xkb_compose_state != NULL) {940        xkb_compose_state_feed(seat->kbd.xkb_compose_state, sym);941        compose_status = xkb_compose_state_get_status(942            seat->kbd.xkb_compose_state);943    }944945    if (compose_status == XKB_COMPOSE_COMPOSING) {946        /* TODO: goto maybe_repeat? */947        return;948    }949950    xkb_mod_mask_t mods = xkb_state_serialize_mods(951        seat->kbd.xkb_state, XKB_STATE_MODS_EFFECTIVE);952    xkb_mod_mask_t consumed = xkb_state_key_get_consumed_mods2(953        seat->kbd.xkb_state, key, XKB_CONSUMED_MODE_XKB);954    const xkb_mod_mask_t locked = xkb_state_serialize_mods(955        seat->kbd.xkb_state, XKB_STATE_MODS_LOCKED);956957    mods &= ~locked;958    consumed &= ~locked;959960    const xkb_layout_index_t layout_idx =961        xkb_state_key_get_layout(seat->kbd.xkb_state, key);962963    const xkb_keysym_t *raw_syms = NULL;964    const size_t raw_count = xkb_keymap_key_get_syms_by_level(965        seat->kbd.xkb_keymap, key, layout_idx, 0, &raw_syms);966967#if 0968    for (size_t i = 0; i < 32; i++) {969        if (mods & (1 << i)) {970            LOG_DBG("%s", xkb_keymap_mod_get_name(seat->kbd.xkb_keymap, i));971        }972    }973#endif974975    LOG_DBG("sym=%u, mod=0x%08x, consumed=0x%08x, locked=0x%08x",976            sym, mods, consumed, locked);977978    const struct key_binding_set *bindings =979        key_binding_for(wayl->kb_manager, seat);980    assert(bindings != NULL);981982    bool refresh = false;983    seat->kbd.serial = serial;984985    /* Untranslated (unshifted matching, check *exact* modifiers) */986    tll_foreach(bindings->key, it) {987        const struct key_binding *bind = &it->item;988989        if (bind->mods != mods || bind->mods == 0)990            continue;991992        for (size_t i = 0; i < raw_count; i++) {993            if (bind->k.sym == raw_syms[i] &&994                execute_binding(seat, bind, &refresh))995            {996                if (refresh)997                    wayl_refresh(wayl);998999                if (check_auto_select(seat, refresh))1000                    goto maybe_repeat;10011002                goto maybe_repeat;1003            }1004        }1005    }10061007    /* Translated (exact matching, check *consumed* modifiers) */1008    tll_foreach(bindings->key, it) {1009        const struct key_binding *bind = &it->item;10101011        if (bind->k.sym == sym &&1012            bind->mods == (mods & ~consumed) &&1013            execute_binding(seat, bind, &refresh))1014        {1015            if (refresh)1016                wayl_refresh(wayl);10171018            if (check_auto_select(seat, refresh))1019                goto maybe_repeat;10201021            goto maybe_repeat;1022        }1023    }102410251026    /* Raw key-code (check *exact* modifiers) */1027    tll_foreach(bindings->key, it) {1028        const struct key_binding *bind = &it->item;10291030        if (bind->mods != mods || bind->mods == 0)1031            continue;10321033        tll_foreach(bind->k.key_codes, code) {1034            if (code->item == key &&1035                execute_binding(seat, bind, &refresh))1036            {1037                if (refresh)1038                    wayl_refresh(wayl);10391040                if (check_auto_select(seat, refresh))1041                    goto maybe_repeat;10421043                goto maybe_repeat;1044            }1045        }1046    }10471048    xkb_mod_mask_t unconsumed = mods & ~consumed;10491050    /*1051     * Most layouts inherit the one-level <SPCE> definition from pc(pc),1052     * so XKB never reports shift as consumed for the space key, and the1053     * event would be dropped despite resolving to a printable space.1054     *1055     * Layouts that do define shifted levels on <SPCE> consume shift1056     * themselves, making this a no-op, and those that map shift+space to1057     * something else (e.g. fr(bepo), or any layout with nbsp:level2)1058     * resolve to a different keysym and never reach here.1059     */1060    if (sym == XKB_KEY_space || sym == XKB_KEY_KP_Space) {1061        xkb_mod_index_t shift = xkb_keymap_mod_get_index(1062            seat->kbd.xkb_keymap, XKB_MOD_NAME_SHIFT);10631064        if (shift != XKB_MOD_INVALID)1065            unconsumed &= ~(1u << shift);1066    }10671068    if (unconsumed != 0)1069        goto maybe_repeat;10701071    /*1072     * Compose, and maybe emit "normal" character1073     */10741075    char buf[64] = {0};1076    int count = 0;10771078    if (compose_status == XKB_COMPOSE_COMPOSED) {1079        count = xkb_compose_state_get_utf8(1080            seat->kbd.xkb_compose_state, buf, sizeof(buf));1081        xkb_compose_state_reset(seat->kbd.xkb_compose_state);1082    } else if (compose_status == XKB_COMPOSE_CANCELLED) {1083        goto maybe_repeat;1084    } else {1085        count = xkb_state_key_get_utf8(1086            seat->kbd.xkb_state, key, buf, sizeof(buf));1087    }10881089    if (count == 0)1090        return;10911092    prompt_insert_chars(wayl->prompt, buf, count);10931094    matches_update_incremental(wayl->matches);1095    matches_selected_set(wayl->matches, 0);1096    wayl_refresh(wayl);1097    check_auto_select(seat, true);10981099maybe_repeat:11001101    if (should_repeat)1102        repeat_start(&seat->kbd.repeat, key - 8);11031104}11051106static void1107keyboard_modifiers(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial,1108                   uint32_t mods_depressed, uint32_t mods_latched,1109                   uint32_t mods_locked, uint32_t group)1110{1111    struct seat *seat = data;11121113    LOG_DBG("modifiers: depressed=0x%x, latched=0x%x, locked=0x%x, group=%u",1114            mods_depressed, mods_latched, mods_locked, group);11151116    if (seat->kbd.xkb_state != NULL) {1117        xkb_state_update_mask(1118            seat->kbd.xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group);1119    }1120}11211122static void1123keyboard_repeat_info(void *data, struct wl_keyboard *wl_keyboard,1124                     int32_t rate, int32_t delay)1125{1126    struct seat *seat = data;1127    LOG_DBG("keyboard repeat: rate=%d, delay=%d", rate, delay);1128    seat->kbd.repeat.delay = delay;1129    seat->kbd.repeat.rate = rate;1130}11311132static const struct wl_keyboard_listener keyboard_listener = {1133    .keymap = &keyboard_keymap,1134    .enter = &keyboard_enter,1135    .leave = &keyboard_leave,1136    .key = &keyboard_key,1137    .modifiers = &keyboard_modifiers,1138    .repeat_info = &keyboard_repeat_info,1139};11401141static bool1142attempt_cursor_shape(struct wayland *wayl, struct wl_pointer *wl_pointer,1143                     uint32_t serial)1144{1145    if (wayl->cursor_shape_manager) {1146        struct wp_cursor_shape_device_v1 *device =1147            wp_cursor_shape_manager_v1_get_pointer(1148                wayl->cursor_shape_manager, wl_pointer);1149        wp_cursor_shape_device_v1_set_shape(1150            device, serial, WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT);1151        wp_cursor_shape_device_v1_destroy(device);1152        return true;1153    }11541155    return false;1156}11571158static void1159select_hovered_match(struct seat *seat, bool refresh_always)1160{1161    struct wayland *wayl = seat->wayl;11621163    ssize_t hovered_row = render_get_row_num(1164        wayl->render, wayl->width, seat->pointer.x, seat->pointer.y,1165        wayl->matches);11661167    if (hovered_row < 0)1168        return;11691170    if (hovered_row == matches_get_match_index(wayl->matches))1171        return;11721173    if (!matches_idx_select(wayl->matches, hovered_row))1174        return;11751176    wayl_refresh(wayl);1177}11781179static void1180wl_pointer_enter(void *data, struct wl_pointer *wl_pointer,1181                 uint32_t serial, struct wl_surface *surface,1182                 wl_fixed_t surface_x, wl_fixed_t surface_y)1183{1184    struct seat *seat = data;1185    if (!seat->wayl->enable_mouse)1186        return;1187    seat->pointer.serial = serial;11881189    /*1190     * Note: do *not* set seat->pointer.{x,y} here!1191     *1192     * We only use the coordinates to move the selection when the user1193     * moves the mouse.1194     *1195     * Since the compositor will send a) enter events if the mouse is1196     * where our layer appears even if the cursor is stationary, and1197     * b) since we might get motion events if we are forced to1198     * re-render the layer due to e.g. scale changes (or us guessing1199     * the scale wrong for the initial frame), the coordinates must1200     * remain 0,0 until the mouse is _actually_ moved.1201     *1202     * See wl_pointer_motion()1203     */12041205    if (!attempt_cursor_shape(seat->wayl, wl_pointer, serial)) {1206        reload_cursor_theme(seat, seat->wayl->scale);1207        update_cursor_surface(seat);1208    }1209}12101211static void1212wl_pointer_leave(void *data, struct wl_pointer *wl_pointer,1213                 uint32_t serial, struct wl_surface *surface)1214{1215    struct seat *seat = data;1216    if (!seat->wayl->enable_mouse)1217        return;1218    seat->pointer.serial = serial;1219}12201221static void1222wl_pointer_motion(void *data, struct wl_pointer *wl_pointer,1223                  uint32_t time, wl_fixed_t surface_x, wl_fixed_t surface_y)1224{1225    struct seat *seat = data;1226    if (!seat->wayl->enable_mouse)1227        return;12281229    const int x = wl_fixed_to_int(surface_x);1230    const int y = wl_fixed_to_int(surface_y);12311232    const int old_x = seat->pointer.x;1233    const int old_y = seat->pointer.y;12341235    seat->pointer.x = round(seat->wayl->scale * x);1236    seat->pointer.y = round(seat->wayl->scale * y);12371238    if (old_x != 0 && old_y != 0)1239        select_hovered_match(seat, false);1240}12411242static void1243wl_pointer_button(void *data, struct wl_pointer *wl_pointer,1244                  uint32_t serial, uint32_t time, uint32_t button, uint32_t state)1245{1246    struct seat *seat = data;1247    struct wayland *wayl = seat->wayl;1248    if (!wayl->enable_mouse)1249        return;12501251    if (state == WL_POINTER_BUTTON_STATE_RELEASED) {1252        if (button == BTN_LEFT) {1253            ssize_t clicked_row = render_get_row_num(1254                wayl->render, wayl->width, seat->pointer.x, seat->pointer.y,1255                wayl->matches);12561257            if (clicked_row >= 0) {1258                matches_idx_select(wayl->matches, clicked_row);1259                execute_selected(seat, false, -1);1260            }1261        }12621263        else if (button == BTN_RIGHT) {1264            // Same as pressing ESC1265            wayl->status = EXIT;1266            if (wayl->conf->dmenu.enabled)1267                wayl->exit_code = 2;1268        }12691270        else if (button == BTN_MIDDLE) {1271            paste_from_primary(seat);1272        }1273    }1274}12751276static void1277wl_pointer_axis(void *data, struct wl_pointer *wl_pointer,1278                uint32_t time, uint32_t axis, wl_fixed_t value)1279{1280    struct seat *seat = data;1281    struct wayland *wayl = seat->wayl;12821283    if (!wayl->enable_mouse)1284        return;12851286    if (axis != WL_POINTER_AXIS_VERTICAL_SCROLL)1287        return;12881289    const double amount = wl_fixed_to_double(value);12901291    if (signbit(seat->pointer.accumulated_scroll) != signbit(amount)) {1292        /* Reversed direction, reset accumulated */1293        seat->pointer.accumulated_scroll = 0.;1294    }12951296    seat->pointer.accumulated_scroll += amount;1297}12981299static void1300wl_pointer_frame(void *data, struct wl_pointer *wl_pointer)1301{1302    const double threshold = 20;13031304    struct seat *seat = data;1305    struct wayland *wayl = seat->wayl;13061307    if (seat->pointer.discrete_used) {1308        seat->pointer.discrete_used = false;1309        return;1310    }13111312    if (!wayl->enable_mouse)1313        return;13141315    bool refresh = false;13161317    while (fabs(seat->pointer.accumulated_scroll) > threshold) {1318        if (seat->pointer.accumulated_scroll > 0.) {1319            seat->pointer.accumulated_scroll -= threshold;1320            refresh = matches_selected_next(wayl->matches, true);1321        } else {1322            seat->pointer.accumulated_scroll += threshold;1323            refresh = matches_selected_prev(wayl->matches, true);1324        }1325    }13261327    if (refresh)1328        select_hovered_match(seat, true);1329}13301331static void1332wl_pointer_axis_source(void *data, struct wl_pointer *wl_pointer,1333                       uint32_t axis_source)1334{1335}13361337static void1338wl_pointer_axis_stop(void *data, struct wl_pointer *wl_pointer,1339                     uint32_t time, uint32_t axis)1340{1341}13421343static void1344wl_pointer_axis_discrete(void *data, struct wl_pointer *wl_pointer,1345                         uint32_t axis, int32_t discrete)1346{1347    struct seat *seat = data;1348    struct wayland *wayl = seat->wayl;13491350    if (!wayl->enable_mouse)1351        return;13521353    if (axis != WL_POINTER_AXIS_VERTICAL_SCROLL)1354        return;13551356    seat->pointer.discrete_used = true;13571358    bool refresh = false;1359    if (discrete > 0) {1360        for (int i = 0; i < discrete; i++)1361            refresh = matches_selected_next(wayl->matches, true);1362    } else {1363        for (int i = 0; i < -discrete; i++)1364            refresh = matches_selected_prev(wayl->matches, true);1365    }13661367    if (refresh)1368        select_hovered_match(seat, true);1369}13701371static const struct wl_pointer_listener pointer_listener = {1372    .enter = wl_pointer_enter,1373    .leave = wl_pointer_leave,1374    .motion = wl_pointer_motion,1375    .button = wl_pointer_button,1376    .axis = wl_pointer_axis,1377    .frame = wl_pointer_frame,1378    .axis_source = wl_pointer_axis_source,1379    .axis_stop = wl_pointer_axis_stop,1380    .axis_discrete = wl_pointer_axis_discrete,1381};13821383static void1384wl_touch_down(void *data, struct wl_touch *wl_touch, uint32_t serial,1385              uint32_t time, struct wl_surface *surface, int32_t id,1386              wl_fixed_t x, wl_fixed_t y)1387{1388    struct seat *seat = data;13891390    /* Only track one touch at a time */1391    if (seat->touch.active_touch.scrolling)1392        return;13931394    const float scale = seat->wayl->scale;13951396    seat->touch.active_touch.id = id;1397    seat->touch.active_touch.start_x = round(wl_fixed_to_double(x) * scale);1398    seat->touch.active_touch.start_y = round(wl_fixed_to_double(y) * scale);1399    seat->touch.active_touch.current_x = round(wl_fixed_to_double(x) * scale);1400    seat->touch.active_touch.current_y = round(wl_fixed_to_double(y) * scale);1401    seat->touch.active_touch.last_y = round(wl_fixed_to_double(y) * scale);1402    seat->touch.active_touch.scrolling = true;1403    seat->touch.active_touch.is_tap = true;1404    seat->touch.active_touch.start_time = time;1405    seat->touch.active_touch.accumulated_scroll = 0.0;1406    seat->touch.serial = serial;1407}14081409static void1410wl_touch_up(void *data, struct wl_touch *wl_touch, uint32_t serial,1411            uint32_t time, int32_t id)1412{1413    struct seat *seat = data;1414    struct wayland *wayl = seat->wayl;14151416    if (seat->touch.active_touch.id == id) {1417        /* Check if this was a tap (no significant movement and quick) */1418        if (seat->touch.active_touch.is_tap) {1419            double dx = seat->touch.active_touch.current_x - seat->touch.active_touch.start_x;1420            double dy = seat->touch.active_touch.current_y - seat->touch.active_touch.start_y;1421            double distance = sqrt(dx * dx + dy * dy);1422            uint32_t duration = time - seat->touch.active_touch.start_time;14231424            /* Tap threshold: less than 10 pixels movement and under 500ms */1425            if (distance < 10.0 && duration < 500) {1426                /* Convert touch coordinates to match selection */1427                int touch_x = (int)seat->touch.active_touch.start_x;1428                int touch_y = (int)seat->touch.active_touch.start_y;14291430                ssize_t tapped_row = render_get_row_num(1431                    wayl->render, wayl->width, touch_x, touch_y, wayl->matches);14321433                /* If user tapped on a valid row, select and execute it */1434                if (tapped_row >= 0 && matches_idx_select(wayl->matches, tapped_row)) {1435                    execute_selected(seat, false, -1);1436                }1437            }1438        }14391440        seat->touch.active_touch.scrolling = false;1441        seat->touch.active_touch.id = -1;1442    }1443}14441445static void1446wl_touch_motion(void *data, struct wl_touch *wl_touch, uint32_t time,1447                int32_t id, wl_fixed_t x, wl_fixed_t y)1448{1449    struct seat *seat = data;14501451    if (!seat->touch.active_touch.scrolling || seat->touch.active_touch.id != id)1452        return;14531454    const float scale = seat->wayl->scale;14551456    double new_x = round(wl_fixed_to_double(x) * scale);1457    double new_y = round(wl_fixed_to_double(y) * scale);14581459    /* Update current position */1460    seat->touch.active_touch.current_x = new_x;1461    seat->touch.active_touch.current_y = new_y;14621463    /* Check if movement is too large to be a tap */1464    double dx = new_x - seat->touch.active_touch.start_x;1465    double dy = new_y - seat->touch.active_touch.start_y;1466    double distance = sqrt(dx * dx + dy * dy);14671468    /* Prevents accidental selection while scrolling. */1469    if (distance > 10.0) {1470        seat->touch.active_touch.is_tap = false;1471    }14721473    /* Calculate accumulated scroll from last position */1474    double delta_y = new_y - seat->touch.active_touch.last_y;1475    seat->touch.active_touch.accumulated_scroll += delta_y;14761477    /* Reversed scrolling: positive delta_y (finger moving down) scrolls up in the list */1478    /* Threshold for scrolling - roughly equivalent to one line */1479    const double scroll_threshold = 15.0;14801481    if (seat->touch.active_touch.accumulated_scroll > scroll_threshold) {1482        /* Finger moving down - select previous item (scroll up in list) */1483        if (matches_selected_prev(seat->wayl->matches, true)) {1484            wayl_refresh(seat->wayl);1485        }1486        seat->touch.active_touch.accumulated_scroll = 0.0;1487    } else if (seat->touch.active_touch.accumulated_scroll < -scroll_threshold) {1488        /* Finger moving up - select next item (scroll down in list) */1489        if (matches_selected_next(seat->wayl->matches, true)) {1490            wayl_refresh(seat->wayl);1491        }1492        seat->touch.active_touch.accumulated_scroll = 0.0;1493    }14941495    /* Update last position for next delta calculation */1496    seat->touch.active_touch.last_y = new_y;1497}14981499static void1500wl_touch_frame(void *data, struct wl_touch *wl_touch)1501{1502    /* Touch frame events group related touch events */1503}15041505static void1506wl_touch_cancel(void *data, struct wl_touch *wl_touch)1507{1508    struct seat *seat = data;1509    seat->touch.active_touch.scrolling = false;1510    seat->touch.active_touch.id = -1;1511}15121513static void1514wl_touch_shape(void *data, struct wl_touch *wl_touch, int32_t id,1515               wl_fixed_t major, wl_fixed_t minor)1516{1517    /* Touch shape events - not needed for scrolling */1518}15191520static void1521wl_touch_orientation(void *data, struct wl_touch *wl_touch, int32_t id,1522                     wl_fixed_t orientation)1523{1524    /* Touch orientation events - not needed for scrolling */1525}15261527static const struct wl_touch_listener touch_listener = {1528    .down = wl_touch_down,1529    .up = wl_touch_up,1530    .motion = wl_touch_motion,1531    .frame = wl_touch_frame,1532    .cancel = wl_touch_cancel,1533    .shape = wl_touch_shape,1534    .orientation = wl_touch_orientation,1535};15361537/*---------------------------------------------------------------------------1538 * text-input-unstable-v3 listener1539 *---------------------------------------------------------------------------*/15401541/*1542 * Convert a UTF-8 byte offset within a preedit string to the corresponding1543 * char32_t (glyph) index.  Returns the glyph count if byte_offset is at or1544 * beyond the end of the string.1545 */1546static int32_t1547byte_offset_to_glyph_idx(const char *text, size_t byte_len, int32_t byte_offset)1548{1549    if (byte_offset < 0)1550        return -1;15511552    int32_t glyph_idx = 0;1553    size_t byte_idx = 0;15541555    while (byte_idx < byte_len) {1556        if ((int32_t)byte_idx == byte_offset)1557            return glyph_idx;15581559        int n = mblen(&text[byte_idx], byte_len - byte_idx);1560        if (n <= 0)1561            break;15621563        byte_idx += n;1564        glyph_idx++;1565    }15661567    /* byte_offset at or past end of string */1568    return glyph_idx;1569}15701571static void1572text_input_enter(void *data, struct zwp_text_input_v3 *text_input,1573                 struct wl_surface *surface)1574{1575    struct seat *seat = data;1576    struct wayland *wayl = seat->wayl;15771578    LOG_DBG("text_input enter");15791580    /* Reset any stale pending state */1581    free(seat->ime.preedit_pending.text);1582    seat->ime.preedit_pending.text = NULL;1583    free(seat->ime.commit_pending);1584    seat->ime.commit_pending = NULL;15851586    zwp_text_input_v3_enable(text_input);1587    zwp_text_input_v3_set_content_type(1588        text_input,1589        ZWP_TEXT_INPUT_V3_CONTENT_HINT_NONE,1590        ZWP_TEXT_INPUT_V3_CONTENT_PURPOSE_NORMAL);15911592    /* Send current cursor rect to position the IME popup */1593    int cx, cy, cw, ch;1594    render_get_cursor_rect(wayl->render, &cx, &cy, &cw, &ch);1595    const float scale = wayl->scale;1596    zwp_text_input_v3_set_cursor_rectangle(1597        text_input,1598        (int)(cx / scale), (int)(cy / scale),1599        (int)(cw / scale), (int)(ch / scale));16001601    zwp_text_input_v3_commit(text_input);1602    seat->ime.serial++;16031604    /* Record what we just sent */1605    seat->ime.cursor_rect.x = (int)(cx / scale);1606    seat->ime.cursor_rect.y = (int)(cy / scale);1607    seat->ime.cursor_rect.w = (int)(cw / scale);1608    seat->ime.cursor_rect.h = (int)(ch / scale);1609}16101611static void1612text_input_leave(void *data, struct zwp_text_input_v3 *text_input,1613                 struct wl_surface *surface)1614{1615    struct seat *seat = data;1616    struct wayland *wayl = seat->wayl;16171618    LOG_DBG("text_input leave");16191620    free(seat->ime.preedit_pending.text);1621    seat->ime.preedit_pending.text = NULL;1622    free(seat->ime.commit_pending);1623    seat->ime.commit_pending = NULL;16241625    /* Clear any active preedit */1626    if (wayl->preedit.text != NULL) {1627        free(wayl->preedit.text);1628        wayl->preedit.text = NULL;1629        wayl->preedit.cursor = -1;1630        wayl_refresh(wayl);1631    }16321633    zwp_text_input_v3_disable(text_input);1634    zwp_text_input_v3_commit(text_input);1635    seat->ime.serial++;1636}16371638static void1639text_input_preedit_string(void *data, struct zwp_text_input_v3 *text_input,1640                          const char *text, int32_t cursor_begin, int32_t cursor_end)1641{1642    struct seat *seat = data;16431644    LOG_DBG("preedit_string: text=%s begin=%d end=%d",1645            text ? text : "(null)", cursor_begin, cursor_end);16461647    free(seat->ime.preedit_pending.text);1648    seat->ime.preedit_pending.text = text ? xstrdup(text) : NULL;1649    seat->ime.preedit_pending.cursor_begin = cursor_begin;1650    seat->ime.preedit_pending.cursor_end   = cursor_end;1651}16521653static void1654text_input_commit_string(void *data, struct zwp_text_input_v3 *text_input,1655                         const char *text)1656{1657    struct seat *seat = data;16581659    LOG_DBG("commit_string: text=%s", text ? text : "(null)");16601661    free(seat->ime.commit_pending);1662    seat->ime.commit_pending = text ? xstrdup(text) : NULL;1663}16641665static void1666text_input_delete_surrounding_text(void *data,1667                                   struct zwp_text_input_v3 *text_input,1668                                   uint32_t before_length,1669                                   uint32_t after_length)1670{1671    /*1672     * We never call set_surrounding_text(), so the compositor should1673     * never request deletion of surrounding text.  Log it anyway.1674     */1675    LOG_DBG("delete_surrounding_text: before=%u after=%u (ignored)",1676            before_length, after_length);1677}16781679static void1680text_input_done(void *data, struct zwp_text_input_v3 *text_input,1681                uint32_t serial)1682{1683    struct seat *seat = data;1684    struct wayland *wayl = seat->wayl;16851686    LOG_DBG("done: serial=%u (expected=%u)", serial, seat->ime.serial);16871688    /*1689     * Ignore stale events.  The serial we track is the number of1690     * commit() calls we have made; the compositor echoes it back.1691     */1692    if (seat->ime.serial != serial) {1693        LOG_DBG("IME serial mismatch, discarding");1694        free(seat->ime.preedit_pending.text);1695        seat->ime.preedit_pending.text = NULL;1696        free(seat->ime.commit_pending);1697        seat->ime.commit_pending = NULL;1698        return;1699    }17001701    bool refresh = false;17021703    /*1704     * Apply protocol events in the required order:1705     *  1. Replace existing preedit with cursor.1706     *  2. Delete surrounding text (not implemented).1707     *  3. Insert commit string.1708     *  4. Calculate new surrounding text (not implemented).1709     *  5. Insert new preedit text at cursor.1710     *  6. Place cursor inside preedit.1711     */17121713    /* 1. Clear existing preedit */1714    if (wayl->preedit.text != NULL) {1715        free(wayl->preedit.text);1716        wayl->preedit.text = NULL;1717        wayl->preedit.cursor = -1;1718        refresh = true;1719    }17201721    /* 3. Insert commit string into the prompt */1722    bool did_commit = false;1723    if (seat->ime.commit_pending != NULL) {1724        const char *text = seat->ime.commit_pending;1725        prompt_insert_chars(wayl->prompt, text, strlen(text));1726        free(seat->ime.commit_pending);1727        seat->ime.commit_pending = NULL;1728        matches_update_incremental(wayl->matches);1729        matches_selected_set(wayl->matches, 0);1730        did_commit = true;1731        refresh = true;1732    }17331734    /* 5 & 6. Activate new preedit and compute cursor position */1735    if (seat->ime.preedit_pending.text != NULL &&1736        seat->ime.preedit_pending.text[0] != '\0')1737    {1738        const char *preedit_utf8 = seat->ime.preedit_pending.text;1739        const size_t byte_len    = strlen(preedit_utf8);17401741        char32_t *preedit_c32 = ambstoc32(preedit_utf8);1742        if (preedit_c32 != NULL) {1743            wayl->preedit.text = preedit_c32;17441745            const int32_t cb = seat->ime.preedit_pending.cursor_begin;1746            const int32_t ce = seat->ime.preedit_pending.cursor_end;17471748            if (cb < 0 || ce < 0) {1749                /* Compositor requests hidden cursor within preedit */1750                wayl->preedit.cursor = -1;1751            } else {1752                /* Map the byte offset to a glyph (char32_t) index */1753                wayl->preedit.cursor =1754                    byte_offset_to_glyph_idx(preedit_utf8, byte_len, cb);1755            }1756        }1757        free(seat->ime.preedit_pending.text);1758        seat->ime.preedit_pending.text = NULL;1759        refresh = true;1760    } else {1761        free(seat->ime.preedit_pending.text);1762        seat->ime.preedit_pending.text = NULL;1763    }17641765    if (refresh) {1766        wayl_refresh(wayl);1767        if (did_commit)1768            check_auto_select(seat, true);1769    }1770}17711772static const struct zwp_text_input_v3_listener text_input_listener = {1773    .enter                  = text_input_enter,1774    .leave                  = text_input_leave,1775    .preedit_string         = text_input_preedit_string,1776    .commit_string          = text_input_commit_string,1777    .delete_surrounding_text= text_input_delete_surrounding_text,1778    .done                   = text_input_done,1779};17801781static void1782seat_add_text_input(struct seat *seat)1783{1784    struct wayland *wayl = seat->wayl;17851786    if (wayl->text_input_manager == NULL)1787        return;1788    if (seat->text_input != NULL)1789        return;17901791    seat->text_input = zwp_text_input_manager_v3_get_text_input(1792        wayl->text_input_manager, seat->wl_seat);1793    if (seat->text_input == NULL) {1794        LOG_ERR("failed to create text_input object");1795        return;1796    }1797    zwp_text_input_v3_add_listener(1798        seat->text_input, &text_input_listener, seat);1799}18001801static void1802seat_handle_capabilities(void *data, struct wl_seat *wl_seat,1803                         enum wl_seat_capability caps)1804{1805    struct seat *seat = data;1806    assert(seat->wl_seat == wl_seat);18071808    if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {1809        if (seat->wl_keyboard == NULL) {1810            seat->wl_keyboard = wl_seat_get_keyboard(wl_seat);1811            wl_keyboard_add_listener(seat->wl_keyboard, &keyboard_listener, seat);1812            seat_add_text_input(seat);1813        }1814    } else {1815        if (seat->wl_keyboard != NULL) {1816            wl_keyboard_release(seat->wl_keyboard);1817            seat->wl_keyboard = NULL;1818        }1819        if (seat->text_input != NULL) {1820            zwp_text_input_v3_destroy(seat->text_input);1821            seat->text_input = NULL;1822        }1823    }18241825    if (caps & WL_SEAT_CAPABILITY_POINTER) {1826        if (seat->wl_pointer == NULL) {1827            assert(seat->pointer.surface == NULL);1828            seat->pointer.surface = wl_compositor_create_surface(seat->wayl->compositor);18291830            if (seat->pointer.surface == NULL) {1831                LOG_ERR("%s: failed to create pointer surface", seat->name);1832                return;1833            }18341835            if (seat->wayl->viewporter != NULL) {1836                assert(seat->pointer.viewport == NULL);1837                seat->pointer.viewport = wp_viewporter_get_viewport(1838                    seat->wayl->viewporter, seat->pointer.surface);18391840                if (seat->pointer.viewport == NULL) {1841                    LOG_ERR("%s: failed to create pointer viewport", seat->name);1842                    wl_surface_destroy(seat->pointer.surface);1843                    seat->pointer.surface = NULL;1844                    return;1845                }1846            }18471848            seat->wl_pointer = wl_seat_get_pointer(wl_seat);1849            wl_pointer_add_listener(seat->wl_pointer, &pointer_listener, seat);1850        }1851    } else {1852        if (seat->wl_pointer != NULL) {1853            wl_pointer_release(seat->wl_pointer);1854            wl_surface_destroy(seat->pointer.surface);18551856            if (seat->pointer.viewport != NULL) {1857                wp_viewport_destroy(seat->pointer.viewport);1858                seat->pointer.viewport = NULL;1859            }18601861            if (seat->pointer.theme != NULL)1862                wl_cursor_theme_destroy(seat->pointer.theme);18631864            seat->wl_pointer = NULL;1865            seat->pointer.surface = NULL;1866            seat->pointer.theme = NULL;1867            seat->pointer.cursor = NULL;1868        }1869    }18701871    if (caps & WL_SEAT_CAPABILITY_TOUCH) {1872        if (seat->wl_touch == NULL) {1873            seat->wl_touch = wl_seat_get_touch(wl_seat);1874            wl_touch_add_listener(seat->wl_touch, &touch_listener, seat);18751876            /* Initialize touch state */1877            seat->touch.active_touch.id = -1;1878            seat->touch.active_touch.scrolling = false;1879        }1880    } else {1881        if (seat->wl_touch != NULL) {1882            wl_touch_release(seat->wl_touch);1883            seat->wl_touch = NULL;1884        }1885    }1886}18871888static void1889seat_handle_name(void *data, struct wl_seat *wl_seat, const char *name)1890{1891    struct seat *seat = data;1892    free(seat->name);1893    seat->name = xstrdup(name);1894}18951896static const struct wl_seat_listener seat_listener = {1897    .capabilities = seat_handle_capabilities,1898    .name = seat_handle_name,1899};19001901static float1902guess_scale(const struct wayland *wayl)1903{1904    if (tll_length(wayl->monitors) == 0)1905        return 1;19061907    bool all_have_same_scale = true;1908    float last_scale = -1;19091910    tll_foreach(wayl->monitors, it) {1911        if (last_scale == -1)1912            last_scale = it->item.scale;1913        else if (last_scale != it->item.scale) {1914            all_have_same_scale = false;1915            break;1916        }1917    }19181919    if (all_have_same_scale) {1920        assert(last_scale >= 1);1921        return last_scale;1922    }19231924    return 1.;1925}19261927static enum fcft_subpixel1928guess_subpixel(const struct wayland *wayl)1929{1930    if (tll_length(wayl->monitors) == 0)1931        return FCFT_SUBPIXEL_DEFAULT;19321933    return tll_front(wayl->monitors).subpixel;1934}19351936static bool1937size_font_using_dpi(const struct wayland *wayl)1938{1939    switch (wayl->conf->dpi_aware) {1940    case DPI_AWARE_NO: return false;1941    case DPI_AWARE_YES: return true;19421943    case DPI_AWARE_AUTO:1944        tll_foreach(wayl->monitors, it) {1945            const struct monitor *mon = &it->item;1946            if (mon->scale > 1)1947                return false;1948        }19491950        return true;1951    }19521953    assert(false);1954    return false;1955}19561957static bool1958reload_font(struct wayland *wayl, float new_dpi, float new_scale)1959{1960    struct fcft_font *font = NULL;1961    struct fcft_font *font_bold = NULL;19621963    bool was_sized_using_dpi = wayl->font_is_sized_by_dpi;1964    bool will_size_using_dpi = size_font_using_dpi(wayl);19651966    bool need_font_reload =1967        was_sized_using_dpi != will_size_using_dpi ||1968        (will_size_using_dpi1969         ? wayl->dpi != new_dpi1970         : wayl->scale != new_scale);19711972    LOG_DBG(1973        "font reload: scale: %.2f -> %0.2f, dpi: %.2f -> %.2f size method: %s -> %s",1974        wayl->scale, new_scale, wayl->dpi, new_dpi,1975        was_sized_using_dpi ? "DPI" : "scaling factor",1976        will_size_using_dpi ? "DPI" : "scaling factor");19771978    wayl->font_is_sized_by_dpi = will_size_using_dpi;19791980    if (need_font_reload) {1981        char **names = xmalloc(wayl->font_count * sizeof(names[0]));19821983        /* Apply font size, possibly scaled using the scaling factor */1984        for (size_t i = 0; i < wayl->font_count; i++) {1985            const struct font_spec *spec = &wayl->fonts[i];1986            const bool use_px_size = spec->px_size > 0;1987            const float scale = wayl->font_is_sized_by_dpi ? 1. : new_scale;1988            if (use_px_size) {1989                int px = (int)roundf(spec->px_size * scale);1990                names[i] = xasprintf("%s:pixelsize=%d", spec->pattern, px);1991            } else {1992                double pt = spec->pt_size * scale;1993                names[i] = xasprintf("%s:size=%.2f", spec->pattern, pt);1994            }1995        }19961997        /* Font’s DPI */1998        float dpi = will_size_using_dpi ? new_dpi : 96.;1999        char attrs[256];2000        xsnprintf(attrs, sizeof(attrs), "dpi=%.2f", dpi);

The first 2,000 of 3,578 lines.