Skip to content

Fix crash when opening rofi in wayland backend#239

Merged
paperbenni merged 2 commits intomainfrom
fix-rofi-crash-wayland-4843312196377472437
Mar 20, 2026
Merged

Fix crash when opening rofi in wayland backend#239
paperbenni merged 2 commits intomainfrom
fix-rofi-crash-wayland-4843312196377472437

Conversation

@paperbenni
Copy link
Copy Markdown
Member

@paperbenni paperbenni commented Mar 20, 2026

Fix crash when opening rofi in wayland backend

When KeyboardFocusTarget is converted to PointerFocusTarget for layer shells or XWayland unmanaged windows like rofi, w.wl_surface() can return None. Calling .unwrap() caused a panic that crashed the compositor.

This commit safely handles Window(w) by adding it as a variant to PointerFocusTarget. This defers the retrieval of the surface until the pointer or touch events are actually dispatched, where it can safely check if let Some(surface) = w.wl_surface().


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

Summary by Sourcery

Bug Fixes:

  • Prevent compositor panics when converting keyboard focus on certain windows (e.g. layer shells or unmanaged XWayland windows) into pointer or touch focus by avoiding unconditional wl_surface() unwrapping.

Summary by CodeRabbit

  • Refactor
    • Streamlined how pointer and touch events are delivered to windows, improving responsiveness and efficiency of cursor and touch interactions.
  • Bug Fixes
    • Events for windows without a valid surface are now safely ignored (with trace logging), reducing dropped or misrouted input and improving stability.

When `KeyboardFocusTarget` is converted to `PointerFocusTarget` for layer shells or XWayland unmanaged windows like rofi, `w.wl_surface()` can return `None`. Calling `.unwrap()` caused a panic that crashed the compositor.

This commit safely handles `Window(w)` by adding it as a variant to `PointerFocusTarget`. This defers the retrieval of the surface until the pointer or touch events are actually dispatched, where it can safely check `if let Some(surface) = w.wl_surface()`.

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 20, 2026

Reviewer's Guide

This PR makes pointer and touch focus handling robust for windows whose Wayland surface may be absent (e.g., layer shells or XWayland unmanaged windows like rofi) by introducing a Window variant to PointerFocusTarget and deferring wl_surface resolution until event dispatch, avoiding panics from unwrap().

Sequence diagram for pointer motion with lazy wl_surface resolution

sequenceDiagram
    participant Seat
    participant WaylandState
    participant PointerFocusTarget
    participant Window
    participant WlSurface

    Seat->>WaylandState: motion_event
    WaylandState->>PointerFocusTarget: handle_motion(seat, data, event)
    alt PointerFocusTarget_Window
        PointerFocusTarget->>Window: wl_surface()
        alt wl_surface_some
            Window-->>PointerFocusTarget: Some(surface)
            PointerFocusTarget->>WlSurface: pointer_motion(seat, data, event)
            WlSurface-->>Seat: motion_delivered
        else wl_surface_none
            Window-->>PointerFocusTarget: None
            PointerFocusTarget-->>WaylandState: no_op_avoid_panic
        end
    else PointerFocusTarget_WlSurface
        PointerFocusTarget->>WlSurface: pointer_motion(seat, data, event)
        WlSurface-->>Seat: motion_delivered
    else PointerFocusTarget_Popup
        PointerFocusTarget->>WlSurface: popup_wl_surface()
        WlSurface-->>Seat: motion_delivered
    end
Loading

Class diagram for updated focus targets and event dispatch

classDiagram
    class Window {
        +wl_surface() Option_Cow_WlSurface
        +alive() bool
    }

    class WlSurface {
        +alive() bool
    }

    class PopupKind {
        +wl_surface() WlSurface
        +alive() bool
    }

    class KeyboardFocusTarget {
        <<enum>>
        Window
        WlSurface
        Popup
    }

    class PointerFocusTarget {
        <<enum>>
        Window
        WlSurface
        Popup
    }

    class IsAlive {
        <<interface>>
        +alive() bool
    }

    class WaylandFocus {
        <<interface>>
        +wl_surface() Option_Cow_WlSurface
    }

    class PointerTarget_WaylandState {
        <<interface>>
        +enter(seat, data, event)
        +motion(seat, data, event)
        +relative_motion(seat, data, event)
        +button(seat, data, event)
        +axis(seat, data, frame)
        +frame(seat, data)
        +gesture_swipe_begin(seat, data, event)
        +gesture_swipe_update(seat, data, event)
        +gesture_swipe_end(seat, data, event)
        +gesture_pinch_begin(seat, data, event)
        +gesture_pinch_update(seat, data, event)
        +gesture_pinch_end(seat, data, event)
        +gesture_hold_begin(seat, data, event)
        +gesture_hold_end(seat, data, event)
        +leave(seat, data, serial, time)
    }

    class TouchTarget_WaylandState {
        <<interface>>
        +down(seat, data, event, seq)
        +up(seat, data, event, seq)
        +motion(seat, data, event, seq)
        +frame(seat, data, seq)
        +cancel(seat, data, seq)
        +shape(seat, data, event, seq)
        +orientation(seat, data, event, seq)
    }

    KeyboardFocusTarget ..> Window
    KeyboardFocusTarget ..> WlSurface
    KeyboardFocusTarget ..> PopupKind

    PointerFocusTarget ..> Window
    PointerFocusTarget ..> WlSurface
    PointerFocusTarget ..> PopupKind

    KeyboardFocusTarget ..|> IsAlive
    PointerFocusTarget ..|> IsAlive

    KeyboardFocusTarget ..|> WaylandFocus
    PointerFocusTarget ..|> WaylandFocus

    PointerFocusTarget ..|> PointerTarget_WaylandState
    PointerFocusTarget ..|> TouchTarget_WaylandState

    KeyboardFocusTarget --> PointerFocusTarget : From_KeyboardFocusTarget
    PopupKind --> PointerFocusTarget : From_PopupKind
    PopupKind --> KeyboardFocusTarget : From_PopupKind
Loading

File-Level Changes

Change Details Files
Add a Window variant to PointerFocusTarget and defer wl_surface lookup from conversion time to event-dispatch time to avoid panics when wl_surface() is None.
  • Extend PointerFocusTarget enum with a Window(Window) variant alongside WlSurface and Popup.
  • Change From for PointerFocusTarget to store the Window directly instead of converting to WlSurface via wl_surface().unwrap().
  • Update IsAlive implementation for PointerFocusTarget to delegate to Window::alive() when targeting a Window.
  • Update WaylandFocus implementation for PointerFocusTarget to call w.wl_surface() for the Window variant, returning an Option, instead of assuming a surface exists.
  • In all smithay::input::pointer::PointerTarget methods, handle the Window variant by checking if let Some(surface) = w.wl_surface() and only forwarding the event if a surface is present.
  • In all smithay::input::touch::TouchTarget methods, mirror the Window handling by conditionally resolving wl_surface and forwarding events only when it exists.
src/backend/wayland/compositor/focus.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 20, 2026

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Adds a Window(Window) variant to PointerFocusTarget, updates conversions and trait impls (IsAlive, WaylandFocus, pointer/touch target impls) to use window methods and to forward pointer/touch events only when wl_surface() is present via a new with_surface helper.

Changes

Cohort / File(s) Summary
Pointer and Touch Focus Handling
src/backend/wayland/compositor/focus.rs
Introduce PointerFocusTarget::Window; change From<KeyboardFocusTarget> to preserve Window; add PointerFocusTarget::with_surface and refactor pointer/touch dispatch to call the closure only when wl_surface() exists, replacing direct match-based forwarding to Smithay.

Sequence Diagram(s)

sequenceDiagram
    participant Input as Input Device
    participant Comp as Compositor / PointerFocusTarget
    participant Win as Window
    participant Smith as Smithay

    Input->>Comp: pointer/touch event
    Comp->>Comp: resolve PointerFocusTarget (Surface/Popup/Window)
    alt target is Window
        Comp->>Win: w.wl_surface()
        alt wl_surface exists
            Comp->>Smith: forward event to Smithay with surface
        else no surface
            Comp-->>Input: drop event (trace)
        end
    else target is Surface/Popup
        Comp->>Smith: forward event to Smithay
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Fix dmenu keyboard grab on Wayland #227: Modifies focus mapping between windows and surfaces and provides a surface→Window fallback that aligns with this PR's window-aware pointer/touch dispatch.

Poem

🐰 I nudge the focus, soft paws on the rim,
A window kept whole, no surface torn slim,
Events hop along only where surfaces gleam,
Smithay receives them tidy — a rabbit's dream. 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 clearly identifies the main issue: fixing a crash when opening rofi in the wayland backend. This directly corresponds to the changeset's core purpose of preventing compositor panics by safely handling window focus conversions.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-rofi-crash-wayland-4843312196377472437
📝 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:

  • There is a lot of repeated match PointerFocusTarget::Window(w) { if let Some(surface) = w.wl_surface() { … } } boilerplate across all pointer and touch event methods; consider factoring this into a small helper (e.g. a method on PointerFocusTarget or a closure-taking with_surface function) to centralize the wl_surface lookup and reduce duplication.
  • When w.wl_surface() returns None the events are now silently dropped; if this is expected but rare, you may want to add a trace-level log in the Window branch to make diagnosing unexpected None cases easier without reintroducing a crash.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- There is a lot of repeated `match PointerFocusTarget::Window(w) { if let Some(surface) = w.wl_surface() { … } }` boilerplate across all pointer and touch event methods; consider factoring this into a small helper (e.g. a method on `PointerFocusTarget` or a closure-taking `with_surface` function) to centralize the `wl_surface` lookup and reduce duplication.
- When `w.wl_surface()` returns `None` the events are now silently dropped; if this is expected but rare, you may want to add a trace-level log in the `Window` branch to make diagnosing unexpected `None` cases easier without reintroducing a crash.

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.

@paperbenni
Copy link
Copy Markdown
Member Author

@jules

Please address the comments from this code review:

Overall Comments

  • There is a lot of repeated match PointerFocusTarget::Window(w) { if let Some(surface) = w.wl_surface() { … } } boilerplate across all pointer and touch event methods; consider factoring this into a small helper (e.g. a method on PointerFocusTarget or a closure-taking with_surface function) to centralize the wl_surface lookup and reduce duplication.
  • When w.wl_surface() returns None the events are now silently dropped; if this is expected but rare, you may want to add a trace-level log in the Window branch to make diagnosing unexpected None cases easier without reintroducing a crash.

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.

🧹 Nitpick comments (1)
src/backend/wayland/compositor/focus.rs (1)

257-661: Nice guard; consider extracting the Window forwarding pattern.

The if let Some(surface) checks are the right safety net, but the same block is now repeated across every pointer/touch callback. A tiny helper would make future event additions less error-prone.

♻️ Refactor sketch
+fn with_window_surface(window: &Window, f: impl FnOnce(&WlSurface)) {
+    if let Some(surface) = window.wl_surface() {
+        f(surface.as_ref());
+    }
+}
+
 impl smithay::input::pointer::PointerTarget<WaylandState> for PointerFocusTarget {
     fn enter(
         &self,
         seat: &Seat<WaylandState>,
         data: &mut WaylandState,
         event: &smithay::input::pointer::MotionEvent,
     ) {
         match self {
-            PointerFocusTarget::Window(w) => {
-                if let Some(surface) = w.wl_surface() {
-                    smithay::input::pointer::PointerTarget::enter(
-                        surface.as_ref(),
-                        seat,
-                        data,
-                        event,
-                    );
-                }
-            }
+            PointerFocusTarget::Window(w) => with_window_surface(w, |surface| {
+                smithay::input::pointer::PointerTarget::enter(surface, seat, data, event);
+            }),
             PointerFocusTarget::WlSurface(s) => {
                 smithay::input::pointer::PointerTarget::enter(s, seat, data, event);
             }
             PointerFocusTarget::Popup(p) => {
                 smithay::input::pointer::PointerTarget::enter(p.wl_surface(), seat, data, event);
             }
         }
     }

Apply the same helper to the remaining pointer and touch branches.

Also applies to: 689-843

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/backend/wayland/compositor/focus.rs` around lines 257 - 661, Extract a
small helper on PointerFocusTarget (e.g. fn as_surface(&self) ->
Option<&wl_surface::WlSurface> or Option<&T> matching your wl_surface type) that
returns Some(surface) for PointerFocusTarget::Window (calling
w.wl_surface().map(|s| s.as_ref())) and for PointerFocusTarget::WlSurface/Popup
returns the surface directly, then replace the repeated if let Some(surface) {
smithay::input::pointer::PointerTarget::<event>(surface.as_ref(), seat, data,
event) } blocks in methods enter, motion, relative_motion, button, axis, frame,
gesture_*, leave, etc., with a single call guarded by the helper (e.g. if let
Some(surface) = self.as_surface() { PointerTarget::enter(surface, seat, data,
event) }), applying the same change to the pointer and touch branches mentioned.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/backend/wayland/compositor/focus.rs`:
- Around line 257-661: Extract a small helper on PointerFocusTarget (e.g. fn
as_surface(&self) -> Option<&wl_surface::WlSurface> or Option<&T> matching your
wl_surface type) that returns Some(surface) for PointerFocusTarget::Window
(calling w.wl_surface().map(|s| s.as_ref())) and for
PointerFocusTarget::WlSurface/Popup returns the surface directly, then replace
the repeated if let Some(surface) {
smithay::input::pointer::PointerTarget::<event>(surface.as_ref(), seat, data,
event) } blocks in methods enter, motion, relative_motion, button, axis, frame,
gesture_*, leave, etc., with a single call guarded by the helper (e.g. if let
Some(surface) = self.as_surface() { PointerTarget::enter(surface, seat, data,
event) }), applying the same change to the pointer and touch branches mentioned.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 63c4c53e-54e4-40f5-9528-f2fe207f94e8

📥 Commits

Reviewing files that changed from the base of the PR and between 30728b6 and 3af9107.

📒 Files selected for processing (1)
  • src/backend/wayland/compositor/focus.rs

@google-labs-jules
Copy link
Copy Markdown
Contributor

@jules

Please address the comments from this code review:

Overall Comments

  • There is a lot of repeated match PointerFocusTarget::Window(w) { if let Some(surface) = w.wl_surface() { … } } boilerplate across all pointer and touch event methods; consider factoring this into a small helper (e.g. a method on PointerFocusTarget or a closure-taking with_surface function) to centralize the wl_surface lookup and reduce duplication.
  • When w.wl_surface() returns None the events are now silently dropped; if this is expected but rare, you may want to add a trace-level log in the Window branch to make diagnosing unexpected None cases easier without reintroducing a crash.

I have factored the logic into a with_surface helper method on PointerFocusTarget. This centralizes the wl_surface() lookup and replaces the repetitive boilerplate in all PointerTarget and TouchTarget trait implementations with a single line using a closure. It also adds a log::trace! when the WlSurface is None to make diagnosing dropped events easier without crashing.

Following code review feedback, a `with_surface` helper function was added to `PointerFocusTarget`. This centralizes the lookup for `wl_surface()` and reduces the boilerplate previously repeated across all pointer and touch event handlers.
It additionally logs a trace message when a surface is missing instead of silently dropping the event, making future diagnostics easier.

Co-authored-by: paperbenni <15818888+paperbenni@users.noreply.github.com>
@paperbenni paperbenni merged commit cbfbc4b into main Mar 20, 2026
3 of 5 checks passed
@paperbenni paperbenni deleted the fix-rofi-crash-wayland-4843312196377472437 branch March 20, 2026 20:25
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