Skip to content

Fix Xwayland keyboard grabs for applications like dmenu#221

Merged
paperbenni merged 1 commit intomainfrom
fix/xwayland-keyboard-grab-689128807718661313
Mar 13, 2026
Merged

Fix Xwayland keyboard grabs for applications like dmenu#221
paperbenni merged 1 commit intomainfrom
fix/xwayland-keyboard-grab-689128807718661313

Conversation

@paperbenni
Copy link
Copy Markdown
Member

@paperbenni paperbenni commented Mar 13, 2026

Added support for the zwp_xwayland_keyboard_grab_v1 protocol in the Smithay Wayland backend. This fixes an issue where Xwayland applications (like dmenu forks launched via keybindings) fail to secure an exclusive keyboard grab, leading to dropped keystrokes or requiring the user to hold down the launcher shortcut.

Changes include:

  • Adding XWaylandKeyboardGrabState to WaylandState.
  • Implementing XWaylandKeyboardGrabHandler for WaylandState to properly map a WlSurface to its corresponding Window using window_id_for_surface.
  • Adding the delegate_xwayland_keyboard_grab! macro to wire up the protocol globally.

PR created automatically by Jules for task 689128807718661313 started by @paperbenni

Summary by Sourcery

Add support for the XWayland keyboard grab protocol in the Wayland backend to ensure XWayland clients can acquire proper exclusive keyboard focus.

New Features:

  • Introduce XWayland keyboard grab state management in WaylandState to back the zwp_xwayland_keyboard_grab_v1 protocol.
  • Implement keyboard focus resolution for XWayland surfaces so they can map to the corresponding compositor window and receive grabs.
  • Wire the XWayland keyboard grab protocol into the compositor via the delegate_xwayland_keyboard_grab! macro.

Summary by CodeRabbit

  • New Features
    • Added keyboard grab support for X11 applications running on Wayland, enabling improved keyboard input handling and focus management for X11 windows.

Added support for the zwp_xwayland_keyboard_grab_v1 protocol in the
Wayland backend. This allows X11/Xwayland applications like dmenu to
properly acquire exclusive keyboard grabs without dropping focus or
requiring the user to hold down launcher keys.

Integrated XWaylandKeyboardGrabState into WaylandState, implemented
XWaylandKeyboardGrabHandler to route grabs to the correct window,
and wired up the protocol handler with delegate_xwayland_keyboard_grab!.

Co-authored-by: paperbenni <15818888+paperbenni@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Mar 13, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adds support for Smithay's zwp_xwayland_keyboard_grab_v1 protocol in the Wayland backend by wiring the new XWaylandKeyboardGrabState into WaylandState, implementing the XWaylandKeyboardGrabHandler to resolve keyboard focus from wl_surface to internal windows, and delegating the new protocol globally so Xwayland clients like dmenu can reliably obtain exclusive keyboard grabs.

Sequence diagram for Xwayland dmenu keyboard grab using zwp_xwayland_keyboard_grab_v1

sequenceDiagram
    actor User
    participant Compositor_WaylandState as Compositor_WaylandState
    participant Xwayland
    participant DmenuXwaylandApp as Dmenu_Xwayland_app
    participant XWaylandKeyboardGrabProto as XWaylandKeyboardGrab_proto

    User->>Compositor_WaylandState: Keybinding pressed
    Compositor_WaylandState->>Xwayland: Launch dmenu Xwayland client
    Xwayland->>DmenuXwaylandApp: Start X11 application

    DmenuXwaylandApp->>Xwayland: Request exclusive keyboard grab
    Xwayland->>XWaylandKeyboardGrabProto: zwp_xwayland_keyboard_grab_v1 request
    XWaylandKeyboardGrabProto->>Compositor_WaylandState: keyboard_focus_for_xsurface(surface)

    Compositor_WaylandState->>Compositor_WaylandState: win = window_id_for_surface(surface)
    Compositor_WaylandState->>Compositor_WaylandState: window = window_index.get(win)
    Compositor_WaylandState-->>XWaylandKeyboardGrabProto: KeyboardFocusTarget_Window(window)
    XWaylandKeyboardGrabProto-->>Xwayland: Keyboard grab established

    User->>DmenuXwaylandApp: Type characters
    DmenuXwaylandApp-->>User: Receives all keystrokes without drops
Loading

Class diagram for updated WaylandState with XWaylandKeyboardGrab support

classDiagram
    class WaylandState {
        +OutputManagerState output_manager_state
        +DataDeviceState data_device_state
        +XWaylandShellState xwayland_shell_state
        +XWaylandKeyboardGrabState xwayland_keyboard_grab_state
        +WlrLayerShellState wlr_layer_shell_state
        +DmabufState dmabuf_state
        +Option_dmabuf_global dmabuf_global
        +KeyboardFocusTarget keyboard_focus_for_xsurface(surface)
        +WindowId window_id_for_surface(surface)
        +WindowIndexMap window_index
    }

    class XWaylandKeyboardGrabState {
        +new_WaylandState(display_handle)
    }

    class XWaylandKeyboardGrabHandler {
        <<interface>>
        +keyboard_focus_for_xsurface(surface) KeyboardFocusTarget
    }

    class KeyboardFocusTarget {
        <<enum>>
        Window
    }

    class Window {
    }

    class WindowIndexMap {
        <<map>>
        WindowId ~ Window
    }

    WaylandState ..|> XWaylandKeyboardGrabHandler
    WaylandState --> XWaylandKeyboardGrabState : has
    WaylandState --> WindowIndexMap : has
    WindowIndexMap --> Window : maps_to
    XWaylandKeyboardGrabState ..> WaylandState : generic_new
    KeyboardFocusTarget --> Window : wraps
Loading

File-Level Changes

Change Details Files
Wire Smithay XWayland keyboard grab protocol state into WaylandState lifecycle.
  • Import XWaylandKeyboardGrabState from smithay compositor protocols.
  • Extend WaylandState struct with an xwayland_keyboard_grab_state field.
  • Initialize XWaylandKeyboardGrabState in WaylandState::new using the display handle.
  • Pass the initialized xwayland_keyboard_grab_state into the constructed WaylandState instance.
src/backend/wayland/compositor/state.rs
Implement XWaylandKeyboardGrabHandler to resolve keyboard focus targets from wl_surface to internal Window instances.
  • Import XWaylandKeyboardGrabHandler in compositor handlers module.
  • Implement keyboard_focus_for_xsurface for WaylandState using window_id_for_surface to look up the window id from the provided WlSurface.
  • Fetch the corresponding window from window_index and wrap it in KeyboardFocusTarget::Window when found.
src/backend/wayland/compositor/handlers.rs
Expose the XWayland keyboard grab protocol through the Wayland compositor by delegating the handler macros.
  • Add delegate_xwayland_keyboard_grab!(WaylandState) invocation to the compositor module so Smithay wires up the global and dispatch for the protocol.
src/backend/wayland/compositor/mod.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 13, 2026

📝 Walkthrough

Walkthrough

The changes add XWayland keyboard grab protocol support to the Wayland compositor backend by introducing state management, implementing the XWaylandKeyboardGrabHandler trait, and registering the corresponding Wayland delegate.

Changes

Cohort / File(s) Summary
XWayland Keyboard Grab Support
src/backend/wayland/compositor/state.rs, src/backend/wayland/compositor/handlers.rs, src/backend/wayland/compositor/mod.rs
Adds infrastructure for XWayland keyboard grab handling: introduces XWaylandKeyboardGrabState field to WaylandState, implements XWaylandKeyboardGrabHandler trait with keyboard_focus_for_xsurface() method that maps wl_surface to keyboard focus targets, and registers the delegate_xwayland_keyboard_grab! macro for protocol delegation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A keyboard's gentle grab takes flight,
Through XWayland surfaces, focused right,
State and delegates now intertwine,
Focus flows smoothly, protocol-divine!
Windows answer, their attention signs. 🪟✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix Xwayland keyboard grabs for applications like dmenu' accurately describes the main change: adding support for XWayland keyboard grabs to fix issues with applications like dmenu.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/xwayland-keyboard-grab-689128807718661313
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • In keyboard_focus_for_xsurface, consider whether you can return a reference-based KeyboardFocusTarget instead of cloning the window to avoid potential unnecessary allocations if Window is large or clone-expensive.
  • In WaylandState, you might want to group the new xwayland_keyboard_grab_state field next to other Xwayland-related fields (e.g., xwayland_shell_state) consistently in both the struct definition and initializer to keep related protocol state localized and easier to reason about.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `keyboard_focus_for_xsurface`, consider whether you can return a reference-based `KeyboardFocusTarget` instead of cloning the window to avoid potential unnecessary allocations if `Window` is large or clone-expensive.
- In `WaylandState`, you might want to group the new `xwayland_keyboard_grab_state` field next to other Xwayland-related fields (e.g., `xwayland_shell_state`) consistently in both the struct definition and initializer to keep related protocol state localized and easier to reason about.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/backend/wayland/compositor/handlers.rs`:
- Around line 753-755: The current focus path uses window_id_for_surface ->
window_index.get(...) and drops the grab when window_index lacks entries for
unmanaged X11 overlays; update the logic in the handler so that after let win =
self.window_id_for_surface(surface)? you attempt window_index.get(&win) and, if
that returns None, fall back to checking the compositor's space mapping (e.g.
self.space or equivalent structure that holds mapped override-redirect/X11
overlay windows) to find the window record for win and return
Some(KeyboardFocusTarget::Window(cloned_window)) instead of failing; ensure you
only treat it as missing if neither window_index nor the space mapping contain
win so the keyboard grab is not dropped for overlay windows.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b6f0ad3e-896c-455a-b609-19b00dc27d61

📥 Commits

Reviewing files that changed from the base of the PR and between 2672731 and 7b1f8fc.

📒 Files selected for processing (3)
  • src/backend/wayland/compositor/handlers.rs
  • src/backend/wayland/compositor/mod.rs
  • src/backend/wayland/compositor/state.rs

Comment on lines +753 to +755
let win = self.window_id_for_surface(surface)?;
let window = self.window_index.get(&win)?;
Some(KeyboardFocusTarget::Window(window.clone()))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Overlay X11 windows are currently excluded from keyboard-grab focus lookup.

At Line 753, focus resolution goes through window_id_for_surface + window_index. Unmanaged X11 overlays (e.g., dmenu/override-redirect) are mapped in space but not indexed there, so this can return None and drop the grab.

Proposed fix
 impl XWaylandKeyboardGrabHandler for WaylandState {
     fn keyboard_focus_for_xsurface(
         &self,
         surface: &smithay::reexports::wayland_server::protocol::wl_surface::WlSurface,
     ) -> Option<Self::KeyboardFocus> {
-        let win = self.window_id_for_surface(surface)?;
-        let window = self.window_index.get(&win)?;
-        Some(KeyboardFocusTarget::Window(window.clone()))
+        if let Some(window) = self
+            .window_id_for_surface(surface)
+            .and_then(|win| self.window_index.get(&win))
+        {
+            return Some(KeyboardFocusTarget::Window(window.clone()));
+        }
+
+        // Fallback for unmanaged X11 overlays mapped directly in Space.
+        self.space
+            .elements()
+            .find(|w| {
+                w.wl_surface().as_deref() == Some(surface)
+                    || w
+                        .surface_under((0.0, 0.0), WindowSurfaceType::ALL)
+                        .map(|(hit_surface, _)| hit_surface == *surface)
+                        .unwrap_or(false)
+            })
+            .cloned()
+            .map(KeyboardFocusTarget::Window)
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let win = self.window_id_for_surface(surface)?;
let window = self.window_index.get(&win)?;
Some(KeyboardFocusTarget::Window(window.clone()))
impl XWaylandKeyboardGrabHandler for WaylandState {
fn keyboard_focus_for_xsurface(
&self,
surface: &smithay::reexports::wayland_server::protocol::wl_surface::WlSurface,
) -> Option<Self::KeyboardFocus> {
if let Some(window) = self
.window_id_for_surface(surface)
.and_then(|win| self.window_index.get(&win))
{
return Some(KeyboardFocusTarget::Window(window.clone()));
}
// Fallback for unmanaged X11 overlays mapped directly in Space.
self.space
.elements()
.find(|w| {
w.wl_surface().as_deref() == Some(surface)
|| w
.surface_under((0.0, 0.0), WindowSurfaceType::ALL)
.map(|(hit_surface, _)| hit_surface == *surface)
.unwrap_or(false)
})
.cloned()
.map(KeyboardFocusTarget::Window)
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/backend/wayland/compositor/handlers.rs` around lines 753 - 755, The
current focus path uses window_id_for_surface -> window_index.get(...) and drops
the grab when window_index lacks entries for unmanaged X11 overlays; update the
logic in the handler so that after let win =
self.window_id_for_surface(surface)? you attempt window_index.get(&win) and, if
that returns None, fall back to checking the compositor's space mapping (e.g.
self.space or equivalent structure that holds mapped override-redirect/X11
overlay windows) to find the window record for win and return
Some(KeyboardFocusTarget::Window(cloned_window)) instead of failing; ensure you
only treat it as missing if neither window_index nor the space mapping contain
win so the keyboard grab is not dropped for overlay windows.

@paperbenni paperbenni merged commit ab23687 into main Mar 13, 2026
5 checks passed
@paperbenni paperbenni deleted the fix/xwayland-keyboard-grab-689128807718661313 branch March 13, 2026 15:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant