Skip to content

Wayland layer-shell overlays compile the seat's XKB keymap again for every keyboard surface #3296

In review

Description

@purian23

Problem

Every layer-shell overlay that takes keys binds its own wl_keyboard (State::update_seat), and the compositor sends
each new wl_keyboard the seat's keymap. Dispatch<WlKeyboard> (platform/layer_shell/devices.rs) then makes a new
xkb::Context and compiles the payload with xkb::Keymap::new_from_string every time, although the payload is the
same until the user changes layout.

An app that re-makes an overlay's layer surface on every show (a launcher, a menu, a lock surface) pays this on each
show. Measured with heaptrack on a launcher-style overlay shown and hidden ten times (niri, us layout):

  • each show: one keymap compile, 8,038 allocations (465 KiB) on the UI thread;
  • about 1,740 small allocations (135 KiB) of each compiled keymap stay live until the next show re-makes the surface,
    placed among the overlay's own short-lived allocations. After the overlay hides they keep those heap pages from
    going back to the system (glibc), so the process's anonymous memory after a hide is higher than before the show
    by more than the overlay ever kept.

What we built

A one-entry, per-thread cache of the last compiled keymap beside read_keymap_fd in platform/layer_shell.rs:

  • compile_keymap(text: String) -> Option<xkb::Keymap> returns the cached xkb::Keymap (a reference-counted
    handle) when the payload's length and hash match the cached entry, and otherwise compiles it and replaces the entry;
  • a failed compile returns None and leaves the entry;
  • Dispatch<WlKeyboard> uses it for wl_keyboard.keymap; each surface still makes its own xkb::State;
  • thread-local, like the compose-table pool, since libxkbcommon's reference counts are not atomic.

Bounded: one compiled keymap per UI thread (about 135 KiB for a us layout), which every keyboard surface already
holds while it lives. A layout change sends a new payload, which is compiled and replaces the entry.

Test: platform::layer_shell::tests::a_keyboard_surface_reuses_the_compiled_keymap_until_the_seat_sends_another
(same payload twice is one keymap; a new payload compiles, replaces the entry and gives the new layout's symbol; a
payload that does not compile gives no keymap and leaves the entry). It fails on the current code (two compiles).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions