client.rs

   1use std::{
   2    cell::{RefCell, RefMut},
   3    hash::Hash,
   4    os::fd::{AsRawFd, BorrowedFd},
   5    path::PathBuf,
   6    rc::{Rc, Weak},
   7    time::{Duration, Instant},
   8};
   9
  10use ashpd::WindowIdentifier;
  11use calloop::{
  12    EventLoop, LoopHandle,
  13    timer::{TimeoutAction, Timer},
  14};
  15use calloop_wayland_source::WaylandSource;
  16use collections::HashMap;
  17use filedescriptor::Pipe;
  18use http_client::Url;
  19use smallvec::SmallVec;
  20use util::ResultExt;
  21use wayland_backend::client::ObjectId;
  22use wayland_backend::protocol::WEnum;
  23use wayland_client::event_created_child;
  24use wayland_client::globals::{GlobalList, GlobalListContents, registry_queue_init};
  25use wayland_client::protocol::wl_callback::{self, WlCallback};
  26use wayland_client::protocol::wl_data_device_manager::DndAction;
  27use wayland_client::protocol::wl_data_offer::WlDataOffer;
  28use wayland_client::protocol::wl_pointer::AxisSource;
  29use wayland_client::protocol::{
  30    wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_output, wl_region,
  31};
  32use wayland_client::{
  33    Connection, Dispatch, Proxy, QueueHandle, delegate_noop,
  34    protocol::{
  35        wl_buffer, wl_compositor, wl_keyboard, wl_pointer, wl_registry, wl_seat, wl_shm,
  36        wl_shm_pool, wl_surface,
  37    },
  38};
  39use wayland_protocols::wp::cursor_shape::v1::client::{
  40    wp_cursor_shape_device_v1, wp_cursor_shape_manager_v1,
  41};
  42use wayland_protocols::wp::fractional_scale::v1::client::{
  43    wp_fractional_scale_manager_v1, wp_fractional_scale_v1,
  44};
  45use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::{
  46    self, ZwpPrimarySelectionOfferV1,
  47};
  48use wayland_protocols::wp::primary_selection::zv1::client::{
  49    zwp_primary_selection_device_manager_v1, zwp_primary_selection_device_v1,
  50    zwp_primary_selection_source_v1,
  51};
  52use wayland_protocols::wp::text_input::zv3::client::zwp_text_input_v3::{
  53    ContentHint, ContentPurpose,
  54};
  55use wayland_protocols::wp::text_input::zv3::client::{
  56    zwp_text_input_manager_v3, zwp_text_input_v3,
  57};
  58use wayland_protocols::wp::viewporter::client::{wp_viewport, wp_viewporter};
  59use wayland_protocols::xdg::activation::v1::client::{xdg_activation_token_v1, xdg_activation_v1};
  60use wayland_protocols::xdg::decoration::zv1::client::{
  61    zxdg_decoration_manager_v1, zxdg_toplevel_decoration_v1,
  62};
  63use wayland_protocols::xdg::shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base};
  64use wayland_protocols_plasma::blur::client::{org_kde_kwin_blur, org_kde_kwin_blur_manager};
  65use wayland_protocols_wlr::layer_shell::v1::client::{zwlr_layer_shell_v1, zwlr_layer_surface_v1};
  66use xkbcommon::xkb::ffi::XKB_KEYMAP_FORMAT_TEXT_V1;
  67use xkbcommon::xkb::{self, KEYMAP_COMPILE_NO_FLAGS, Keycode};
  68
  69use super::{
  70    display::WaylandDisplay,
  71    window::{ImeInput, WaylandWindowStatePtr},
  72};
  73
  74use crate::{
  75    AnyWindowHandle, Bounds, Capslock, CursorStyle, DOUBLE_CLICK_INTERVAL, DevicePixels, DisplayId,
  76    FileDropEvent, ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke, LinuxCommon,
  77    LinuxKeyboardLayout, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
  78    MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels, PlatformDisplay,
  79    PlatformInput, PlatformKeyboardLayout, Point, SCROLL_LINES, ScrollDelta, ScrollWheelEvent,
  80    Size, TouchPhase, WindowParams, point, px, size,
  81};
  82use crate::{
  83    LinuxDispatcher, RunnableVariant, TaskTiming,
  84    platform::{PlatformWindow, blade::BladeContext},
  85};
  86use crate::{
  87    SharedString,
  88    platform::linux::{
  89        LinuxClient, get_xkb_compose_state, is_within_click_distance, open_uri_internal, read_fd,
  90        reveal_path_internal,
  91        wayland::{
  92            clipboard::{Clipboard, DataOffer, FILE_LIST_MIME_TYPE, TEXT_MIME_TYPES},
  93            cursor::Cursor,
  94            serial::{SerialKind, SerialTracker},
  95            window::WaylandWindow,
  96        },
  97        xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
  98    },
  99};
 100
 101/// Used to convert evdev scancode to xkb scancode
 102const MIN_KEYCODE: u32 = 8;
 103
 104const UNKNOWN_KEYBOARD_LAYOUT_NAME: SharedString = SharedString::new_static("unknown");
 105
 106#[derive(Clone)]
 107pub struct Globals {
 108    pub qh: QueueHandle<WaylandClientStatePtr>,
 109    pub activation: Option<xdg_activation_v1::XdgActivationV1>,
 110    pub compositor: wl_compositor::WlCompositor,
 111    pub cursor_shape_manager: Option<wp_cursor_shape_manager_v1::WpCursorShapeManagerV1>,
 112    pub data_device_manager: Option<wl_data_device_manager::WlDataDeviceManager>,
 113    pub primary_selection_manager:
 114        Option<zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1>,
 115    pub wm_base: xdg_wm_base::XdgWmBase,
 116    pub shm: wl_shm::WlShm,
 117    pub seat: wl_seat::WlSeat,
 118    pub viewporter: Option<wp_viewporter::WpViewporter>,
 119    pub fractional_scale_manager:
 120        Option<wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1>,
 121    pub decoration_manager: Option<zxdg_decoration_manager_v1::ZxdgDecorationManagerV1>,
 122    pub layer_shell: Option<zwlr_layer_shell_v1::ZwlrLayerShellV1>,
 123    pub blur_manager: Option<org_kde_kwin_blur_manager::OrgKdeKwinBlurManager>,
 124    pub text_input_manager: Option<zwp_text_input_manager_v3::ZwpTextInputManagerV3>,
 125    pub executor: ForegroundExecutor,
 126}
 127
 128impl Globals {
 129    fn new(
 130        globals: GlobalList,
 131        executor: ForegroundExecutor,
 132        qh: QueueHandle<WaylandClientStatePtr>,
 133        seat: wl_seat::WlSeat,
 134    ) -> Self {
 135        Globals {
 136            activation: globals.bind(&qh, 1..=1, ()).ok(),
 137            compositor: globals
 138                .bind(
 139                    &qh,
 140                    wl_surface::REQ_SET_BUFFER_SCALE_SINCE
 141                        ..=wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE,
 142                    (),
 143                )
 144                .unwrap(),
 145            cursor_shape_manager: globals.bind(&qh, 1..=1, ()).ok(),
 146            data_device_manager: globals
 147                .bind(
 148                    &qh,
 149                    WL_DATA_DEVICE_MANAGER_VERSION..=WL_DATA_DEVICE_MANAGER_VERSION,
 150                    (),
 151                )
 152                .ok(),
 153            primary_selection_manager: globals.bind(&qh, 1..=1, ()).ok(),
 154            shm: globals.bind(&qh, 1..=1, ()).unwrap(),
 155            seat,
 156            wm_base: globals.bind(&qh, 2..=5, ()).unwrap(),
 157            viewporter: globals.bind(&qh, 1..=1, ()).ok(),
 158            fractional_scale_manager: globals.bind(&qh, 1..=1, ()).ok(),
 159            decoration_manager: globals.bind(&qh, 1..=1, ()).ok(),
 160            layer_shell: globals.bind(&qh, 1..=5, ()).ok(),
 161            blur_manager: globals.bind(&qh, 1..=1, ()).ok(),
 162            text_input_manager: globals.bind(&qh, 1..=1, ()).ok(),
 163            executor,
 164            qh,
 165        }
 166    }
 167}
 168
 169#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
 170pub struct InProgressOutput {
 171    name: Option<String>,
 172    scale: Option<i32>,
 173    position: Option<Point<DevicePixels>>,
 174    size: Option<Size<DevicePixels>>,
 175}
 176
 177impl InProgressOutput {
 178    fn complete(&self) -> Option<Output> {
 179        if let Some((position, size)) = self.position.zip(self.size) {
 180            let scale = self.scale.unwrap_or(1);
 181            Some(Output {
 182                name: self.name.clone(),
 183                scale,
 184                bounds: Bounds::new(position, size),
 185            })
 186        } else {
 187            None
 188        }
 189    }
 190}
 191
 192#[derive(Debug, Clone, Eq, PartialEq, Hash)]
 193pub struct Output {
 194    pub name: Option<String>,
 195    pub scale: i32,
 196    pub bounds: Bounds<DevicePixels>,
 197}
 198
 199pub(crate) struct WaylandClientState {
 200    serial_tracker: SerialTracker,
 201    globals: Globals,
 202    gpu_context: BladeContext,
 203    wl_seat: wl_seat::WlSeat, // TODO: Multi seat support
 204    wl_pointer: Option<wl_pointer::WlPointer>,
 205    wl_keyboard: Option<wl_keyboard::WlKeyboard>,
 206    cursor_shape_device: Option<wp_cursor_shape_device_v1::WpCursorShapeDeviceV1>,
 207    data_device: Option<wl_data_device::WlDataDevice>,
 208    primary_selection: Option<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1>,
 209    text_input: Option<zwp_text_input_v3::ZwpTextInputV3>,
 210    pre_edit_text: Option<String>,
 211    ime_pre_edit: Option<String>,
 212    composing: bool,
 213    // Surface to Window mapping
 214    windows: HashMap<ObjectId, WaylandWindowStatePtr>,
 215    // Output to scale mapping
 216    outputs: HashMap<ObjectId, Output>,
 217    in_progress_outputs: HashMap<ObjectId, InProgressOutput>,
 218    keyboard_layout: LinuxKeyboardLayout,
 219    keymap_state: Option<xkb::State>,
 220    compose_state: Option<xkb::compose::State>,
 221    drag: DragState,
 222    click: ClickState,
 223    repeat: KeyRepeat,
 224    pub modifiers: Modifiers,
 225    pub capslock: Capslock,
 226    axis_source: AxisSource,
 227    pub mouse_location: Option<Point<Pixels>>,
 228    continuous_scroll_delta: Option<Point<Pixels>>,
 229    discrete_scroll_delta: Option<Point<f32>>,
 230    vertical_modifier: f32,
 231    horizontal_modifier: f32,
 232    scroll_event_received: bool,
 233    enter_token: Option<()>,
 234    button_pressed: Option<MouseButton>,
 235    mouse_focused_window: Option<WaylandWindowStatePtr>,
 236    keyboard_focused_window: Option<WaylandWindowStatePtr>,
 237    loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
 238    cursor_style: Option<CursorStyle>,
 239    clipboard: Clipboard,
 240    data_offers: Vec<DataOffer<WlDataOffer>>,
 241    primary_data_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>,
 242    cursor: Cursor,
 243    pending_activation: Option<PendingActivation>,
 244    event_loop: Option<EventLoop<'static, WaylandClientStatePtr>>,
 245    common: LinuxCommon,
 246}
 247
 248pub struct DragState {
 249    data_offer: Option<wl_data_offer::WlDataOffer>,
 250    window: Option<WaylandWindowStatePtr>,
 251    position: Point<Pixels>,
 252}
 253
 254pub struct ClickState {
 255    last_mouse_button: Option<MouseButton>,
 256    last_click: Instant,
 257    last_location: Point<Pixels>,
 258    current_count: usize,
 259}
 260
 261pub(crate) struct KeyRepeat {
 262    characters_per_second: u32,
 263    delay: Duration,
 264    current_id: u64,
 265    current_keycode: Option<xkb::Keycode>,
 266}
 267
 268pub(crate) enum PendingActivation {
 269    /// URI to open in the web browser.
 270    Uri(String),
 271    /// Path to open in the file explorer.
 272    Path(PathBuf),
 273    /// A window from ourselves to raise.
 274    Window(ObjectId),
 275}
 276
 277/// This struct is required to conform to Rust's orphan rules, so we can dispatch on the state but hand the
 278/// window to GPUI.
 279#[derive(Clone)]
 280pub struct WaylandClientStatePtr(Weak<RefCell<WaylandClientState>>);
 281
 282impl WaylandClientStatePtr {
 283    pub fn get_client(&self) -> Rc<RefCell<WaylandClientState>> {
 284        self.0
 285            .upgrade()
 286            .expect("The pointer should always be valid when dispatching in wayland")
 287    }
 288
 289    pub fn get_serial(&self, kind: SerialKind) -> u32 {
 290        self.0.upgrade().unwrap().borrow().serial_tracker.get(kind)
 291    }
 292
 293    pub fn set_pending_activation(&self, window: ObjectId) {
 294        self.0.upgrade().unwrap().borrow_mut().pending_activation =
 295            Some(PendingActivation::Window(window));
 296    }
 297
 298    pub fn enable_ime(&self) {
 299        let client = self.get_client();
 300        let mut state = client.borrow_mut();
 301        let Some(mut text_input) = state.text_input.take() else {
 302            return;
 303        };
 304
 305        text_input.enable();
 306        text_input.set_content_type(ContentHint::None, ContentPurpose::Normal);
 307        if let Some(window) = state.keyboard_focused_window.clone() {
 308            drop(state);
 309            if let Some(area) = window.get_ime_area() {
 310                text_input.set_cursor_rectangle(
 311                    area.origin.x.0 as i32,
 312                    area.origin.y.0 as i32,
 313                    area.size.width.0 as i32,
 314                    area.size.height.0 as i32,
 315                );
 316            }
 317            state = client.borrow_mut();
 318        }
 319        text_input.commit();
 320        state.text_input = Some(text_input);
 321    }
 322
 323    pub fn disable_ime(&self) {
 324        let client = self.get_client();
 325        let mut state = client.borrow_mut();
 326        state.composing = false;
 327        if let Some(text_input) = &state.text_input {
 328            text_input.disable();
 329            text_input.commit();
 330        }
 331    }
 332
 333    pub fn update_ime_position(&self, bounds: Bounds<Pixels>) {
 334        let client = self.get_client();
 335        let mut state = client.borrow_mut();
 336        if state.composing || state.text_input.is_none() || state.pre_edit_text.is_some() {
 337            return;
 338        }
 339
 340        let text_input = state.text_input.as_ref().unwrap();
 341        text_input.set_cursor_rectangle(
 342            bounds.origin.x.0 as i32,
 343            bounds.origin.y.0 as i32,
 344            bounds.size.width.0 as i32,
 345            bounds.size.height.0 as i32,
 346        );
 347        text_input.commit();
 348    }
 349
 350    pub fn handle_keyboard_layout_change(&self) {
 351        let client = self.get_client();
 352        let mut state = client.borrow_mut();
 353        let changed = if let Some(keymap_state) = &state.keymap_state {
 354            let layout_idx = keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
 355            let keymap = keymap_state.get_keymap();
 356            let layout_name = keymap.layout_get_name(layout_idx);
 357            let changed = layout_name != state.keyboard_layout.name();
 358            if changed {
 359                state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
 360            }
 361            changed
 362        } else {
 363            let changed = &UNKNOWN_KEYBOARD_LAYOUT_NAME != state.keyboard_layout.name();
 364            if changed {
 365                state.keyboard_layout = LinuxKeyboardLayout::new(UNKNOWN_KEYBOARD_LAYOUT_NAME);
 366            }
 367            changed
 368        };
 369
 370        if changed && let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take()
 371        {
 372            drop(state);
 373            callback();
 374            state = client.borrow_mut();
 375            state.common.callbacks.keyboard_layout_change = Some(callback);
 376        }
 377    }
 378
 379    pub fn drop_window(&self, surface_id: &ObjectId) {
 380        let mut client = self.get_client();
 381        let mut state = client.borrow_mut();
 382        let closed_window = state.windows.remove(surface_id).unwrap();
 383        if let Some(window) = state.mouse_focused_window.take()
 384            && !window.ptr_eq(&closed_window)
 385        {
 386            state.mouse_focused_window = Some(window);
 387        }
 388        if let Some(window) = state.keyboard_focused_window.take()
 389            && !window.ptr_eq(&closed_window)
 390        {
 391            state.keyboard_focused_window = Some(window);
 392        }
 393    }
 394}
 395
 396#[derive(Clone)]
 397pub struct WaylandClient(Rc<RefCell<WaylandClientState>>);
 398
 399impl Drop for WaylandClient {
 400    fn drop(&mut self) {
 401        let mut state = self.0.borrow_mut();
 402        state.windows.clear();
 403
 404        if let Some(wl_pointer) = &state.wl_pointer {
 405            wl_pointer.release();
 406        }
 407        if let Some(cursor_shape_device) = &state.cursor_shape_device {
 408            cursor_shape_device.destroy();
 409        }
 410        if let Some(data_device) = &state.data_device {
 411            data_device.release();
 412        }
 413        if let Some(text_input) = &state.text_input {
 414            text_input.destroy();
 415        }
 416    }
 417}
 418
 419const WL_DATA_DEVICE_MANAGER_VERSION: u32 = 3;
 420
 421fn wl_seat_version(version: u32) -> u32 {
 422    // We rely on the wl_pointer.frame event
 423    const WL_SEAT_MIN_VERSION: u32 = 5;
 424    const WL_SEAT_MAX_VERSION: u32 = 9;
 425
 426    if version < WL_SEAT_MIN_VERSION {
 427        panic!(
 428            "wl_seat below required version: {} < {}",
 429            version, WL_SEAT_MIN_VERSION
 430        );
 431    }
 432
 433    version.clamp(WL_SEAT_MIN_VERSION, WL_SEAT_MAX_VERSION)
 434}
 435
 436fn wl_output_version(version: u32) -> u32 {
 437    const WL_OUTPUT_MIN_VERSION: u32 = 2;
 438    const WL_OUTPUT_MAX_VERSION: u32 = 4;
 439
 440    if version < WL_OUTPUT_MIN_VERSION {
 441        panic!(
 442            "wl_output below required version: {} < {}",
 443            version, WL_OUTPUT_MIN_VERSION
 444        );
 445    }
 446
 447    version.clamp(WL_OUTPUT_MIN_VERSION, WL_OUTPUT_MAX_VERSION)
 448}
 449
 450impl WaylandClient {
 451    pub(crate) fn new() -> Self {
 452        let conn = Connection::connect_to_env().unwrap();
 453
 454        let (globals, mut event_queue) =
 455            registry_queue_init::<WaylandClientStatePtr>(&conn).unwrap();
 456        let qh = event_queue.handle();
 457
 458        let mut seat: Option<wl_seat::WlSeat> = None;
 459        #[allow(clippy::mutable_key_type)]
 460        let mut in_progress_outputs = HashMap::default();
 461        globals.contents().with_list(|list| {
 462            for global in list {
 463                match &global.interface[..] {
 464                    "wl_seat" => {
 465                        seat = Some(globals.registry().bind::<wl_seat::WlSeat, _, _>(
 466                            global.name,
 467                            wl_seat_version(global.version),
 468                            &qh,
 469                            (),
 470                        ));
 471                    }
 472                    "wl_output" => {
 473                        let output = globals.registry().bind::<wl_output::WlOutput, _, _>(
 474                            global.name,
 475                            wl_output_version(global.version),
 476                            &qh,
 477                            (),
 478                        );
 479                        in_progress_outputs.insert(output.id(), InProgressOutput::default());
 480                    }
 481                    _ => {}
 482                }
 483            }
 484        });
 485
 486        let event_loop = EventLoop::<WaylandClientStatePtr>::try_new().unwrap();
 487
 488        let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
 489
 490        let handle = event_loop.handle();
 491        handle
 492            .insert_source(main_receiver, {
 493                let handle = handle.clone();
 494                move |event, _, _: &mut WaylandClientStatePtr| {
 495                    if let calloop::channel::Event::Msg(runnable) = event {
 496                        handle.insert_idle(|_| {
 497                            let start = Instant::now();
 498                            let mut timing = match runnable {
 499                                RunnableVariant::Meta(runnable) => {
 500                                    let location = runnable.metadata().location;
 501                                    let timing = TaskTiming {
 502                                        location,
 503                                        start,
 504                                        end: None,
 505                                    };
 506                                    LinuxDispatcher::add_task_timing(timing);
 507
 508                                    runnable.run();
 509                                    timing
 510                                }
 511                                RunnableVariant::Compat(runnable) => {
 512                                    let location = core::panic::Location::caller();
 513                                    let timing = TaskTiming {
 514                                        location,
 515                                        start,
 516                                        end: None,
 517                                    };
 518                                    LinuxDispatcher::add_task_timing(timing);
 519
 520                                    runnable.run();
 521                                    timing
 522                                }
 523                            };
 524
 525                            let end = Instant::now();
 526                            timing.end = Some(end);
 527                            LinuxDispatcher::add_task_timing(timing);
 528                        });
 529                    }
 530                }
 531            })
 532            .unwrap();
 533
 534        let gpu_context = BladeContext::new().expect("Unable to init GPU context");
 535
 536        let seat = seat.unwrap();
 537        let globals = Globals::new(
 538            globals,
 539            common.foreground_executor.clone(),
 540            qh.clone(),
 541            seat.clone(),
 542        );
 543
 544        let data_device = globals
 545            .data_device_manager
 546            .as_ref()
 547            .map(|data_device_manager| data_device_manager.get_data_device(&seat, &qh, ()));
 548
 549        let primary_selection = globals
 550            .primary_selection_manager
 551            .as_ref()
 552            .map(|primary_selection_manager| primary_selection_manager.get_device(&seat, &qh, ()));
 553
 554        let mut cursor = Cursor::new(&conn, &globals, 24);
 555
 556        handle
 557            .insert_source(XDPEventSource::new(&common.background_executor), {
 558                move |event, _, client| match event {
 559                    XDPEvent::WindowAppearance(appearance) => {
 560                        if let Some(client) = client.0.upgrade() {
 561                            let mut client = client.borrow_mut();
 562
 563                            client.common.appearance = appearance;
 564
 565                            for window in client.windows.values_mut() {
 566                                window.set_appearance(appearance);
 567                            }
 568                        }
 569                    }
 570                    XDPEvent::CursorTheme(theme) => {
 571                        if let Some(client) = client.0.upgrade() {
 572                            let mut client = client.borrow_mut();
 573                            client.cursor.set_theme(theme);
 574                        }
 575                    }
 576                    XDPEvent::CursorSize(size) => {
 577                        if let Some(client) = client.0.upgrade() {
 578                            let mut client = client.borrow_mut();
 579                            client.cursor.set_size(size);
 580                        }
 581                    }
 582                }
 583            })
 584            .unwrap();
 585
 586        let mut state = Rc::new(RefCell::new(WaylandClientState {
 587            serial_tracker: SerialTracker::new(),
 588            globals,
 589            gpu_context,
 590            wl_seat: seat,
 591            wl_pointer: None,
 592            wl_keyboard: None,
 593            cursor_shape_device: None,
 594            data_device,
 595            primary_selection,
 596            text_input: None,
 597            pre_edit_text: None,
 598            ime_pre_edit: None,
 599            composing: false,
 600            outputs: HashMap::default(),
 601            in_progress_outputs,
 602            windows: HashMap::default(),
 603            common,
 604            keyboard_layout: LinuxKeyboardLayout::new(UNKNOWN_KEYBOARD_LAYOUT_NAME),
 605            keymap_state: None,
 606            compose_state: None,
 607            drag: DragState {
 608                data_offer: None,
 609                window: None,
 610                position: Point::default(),
 611            },
 612            click: ClickState {
 613                last_click: Instant::now(),
 614                last_mouse_button: None,
 615                last_location: Point::default(),
 616                current_count: 0,
 617            },
 618            repeat: KeyRepeat {
 619                characters_per_second: 16,
 620                delay: Duration::from_millis(500),
 621                current_id: 0,
 622                current_keycode: None,
 623            },
 624            modifiers: Modifiers {
 625                shift: false,
 626                control: false,
 627                alt: false,
 628                function: false,
 629                platform: false,
 630            },
 631            capslock: Capslock { on: false },
 632            scroll_event_received: false,
 633            axis_source: AxisSource::Wheel,
 634            mouse_location: None,
 635            continuous_scroll_delta: None,
 636            discrete_scroll_delta: None,
 637            vertical_modifier: -1.0,
 638            horizontal_modifier: -1.0,
 639            button_pressed: None,
 640            mouse_focused_window: None,
 641            keyboard_focused_window: None,
 642            loop_handle: handle.clone(),
 643            enter_token: None,
 644            cursor_style: None,
 645            clipboard: Clipboard::new(conn.clone(), handle.clone()),
 646            data_offers: Vec::new(),
 647            primary_data_offer: None,
 648            cursor,
 649            pending_activation: None,
 650            event_loop: Some(event_loop),
 651        }));
 652
 653        WaylandSource::new(conn, event_queue)
 654            .insert(handle)
 655            .unwrap();
 656
 657        Self(state)
 658    }
 659}
 660
 661impl LinuxClient for WaylandClient {
 662    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 663        Box::new(self.0.borrow().keyboard_layout.clone())
 664    }
 665
 666    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 667        self.0
 668            .borrow()
 669            .outputs
 670            .iter()
 671            .map(|(id, output)| {
 672                Rc::new(WaylandDisplay {
 673                    id: id.clone(),
 674                    name: output.name.clone(),
 675                    bounds: output.bounds.to_pixels(output.scale as f32),
 676                }) as Rc<dyn PlatformDisplay>
 677            })
 678            .collect()
 679    }
 680
 681    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 682        self.0
 683            .borrow()
 684            .outputs
 685            .iter()
 686            .find_map(|(object_id, output)| {
 687                (object_id.protocol_id() == id.0).then(|| {
 688                    Rc::new(WaylandDisplay {
 689                        id: object_id.clone(),
 690                        name: output.name.clone(),
 691                        bounds: output.bounds.to_pixels(output.scale as f32),
 692                    }) as Rc<dyn PlatformDisplay>
 693                })
 694            })
 695    }
 696
 697    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 698        None
 699    }
 700
 701    #[cfg(feature = "screen-capture")]
 702    fn is_screen_capture_supported(&self) -> bool {
 703        false
 704    }
 705
 706    #[cfg(feature = "screen-capture")]
 707    fn screen_capture_sources(
 708        &self,
 709    ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn crate::ScreenCaptureSource>>>>
 710    {
 711        // TODO: Get screen capture working on wayland. Be sure to try window resizing as that may
 712        // be tricky.
 713        //
 714        // start_scap_default_target_source()
 715        let (sources_tx, sources_rx) = futures::channel::oneshot::channel();
 716        sources_tx
 717            .send(Err(anyhow::anyhow!(
 718                "Wayland screen capture not yet implemented."
 719            )))
 720            .ok();
 721        sources_rx
 722    }
 723
 724    fn open_window(
 725        &self,
 726        handle: AnyWindowHandle,
 727        params: WindowParams,
 728    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
 729        let mut state = self.0.borrow_mut();
 730
 731        let parent = state
 732            .keyboard_focused_window
 733            .as_ref()
 734            .and_then(|w| w.toplevel());
 735
 736        let (window, surface_id) = WaylandWindow::new(
 737            handle,
 738            state.globals.clone(),
 739            &state.gpu_context,
 740            WaylandClientStatePtr(Rc::downgrade(&self.0)),
 741            params,
 742            state.common.appearance,
 743            parent,
 744        )?;
 745        state.windows.insert(surface_id, window.0.clone());
 746
 747        Ok(Box::new(window))
 748    }
 749
 750    fn set_cursor_style(&self, style: CursorStyle) {
 751        let mut state = self.0.borrow_mut();
 752
 753        let need_update = state.cursor_style != Some(style);
 754
 755        if need_update {
 756            let serial = state.serial_tracker.get(SerialKind::MouseEnter);
 757            state.cursor_style = Some(style);
 758
 759            if let CursorStyle::None = style {
 760                let wl_pointer = state
 761                    .wl_pointer
 762                    .clone()
 763                    .expect("window is focused by pointer");
 764                wl_pointer.set_cursor(serial, None, 0, 0);
 765            } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
 766                cursor_shape_device.set_shape(serial, style.to_shape());
 767            } else if let Some(focused_window) = &state.mouse_focused_window {
 768                // cursor-shape-v1 isn't supported, set the cursor using a surface.
 769                let wl_pointer = state
 770                    .wl_pointer
 771                    .clone()
 772                    .expect("window is focused by pointer");
 773                let scale = focused_window.primary_output_scale();
 774                state
 775                    .cursor
 776                    .set_icon(&wl_pointer, serial, style.to_icon_names(), scale);
 777            }
 778        }
 779    }
 780
 781    fn open_uri(&self, uri: &str) {
 782        let mut state = self.0.borrow_mut();
 783        if let (Some(activation), Some(window)) = (
 784            state.globals.activation.clone(),
 785            state.mouse_focused_window.clone(),
 786        ) {
 787            state.pending_activation = Some(PendingActivation::Uri(uri.to_string()));
 788            let token = activation.get_activation_token(&state.globals.qh, ());
 789            let serial = state.serial_tracker.get(SerialKind::MousePress);
 790            token.set_serial(serial, &state.wl_seat);
 791            token.set_surface(&window.surface());
 792            token.commit();
 793        } else {
 794            let executor = state.common.background_executor.clone();
 795            open_uri_internal(executor, uri, None);
 796        }
 797    }
 798
 799    fn reveal_path(&self, path: PathBuf) {
 800        let mut state = self.0.borrow_mut();
 801        if let (Some(activation), Some(window)) = (
 802            state.globals.activation.clone(),
 803            state.mouse_focused_window.clone(),
 804        ) {
 805            state.pending_activation = Some(PendingActivation::Path(path));
 806            let token = activation.get_activation_token(&state.globals.qh, ());
 807            let serial = state.serial_tracker.get(SerialKind::MousePress);
 808            token.set_serial(serial, &state.wl_seat);
 809            token.set_surface(&window.surface());
 810            token.commit();
 811        } else {
 812            let executor = state.common.background_executor.clone();
 813            reveal_path_internal(executor, path, None);
 814        }
 815    }
 816
 817    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
 818        f(&mut self.0.borrow_mut().common)
 819    }
 820
 821    fn run(&self) {
 822        let mut event_loop = self
 823            .0
 824            .borrow_mut()
 825            .event_loop
 826            .take()
 827            .expect("App is already running");
 828
 829        event_loop
 830            .run(
 831                None,
 832                &mut WaylandClientStatePtr(Rc::downgrade(&self.0)),
 833                |_| {},
 834            )
 835            .log_err();
 836    }
 837
 838    fn write_to_primary(&self, item: crate::ClipboardItem) {
 839        let mut state = self.0.borrow_mut();
 840        let (Some(primary_selection_manager), Some(primary_selection)) = (
 841            state.globals.primary_selection_manager.clone(),
 842            state.primary_selection.clone(),
 843        ) else {
 844            return;
 845        };
 846        if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
 847            state.clipboard.set_primary(item);
 848            let serial = state.serial_tracker.get(SerialKind::KeyPress);
 849            let data_source = primary_selection_manager.create_source(&state.globals.qh, ());
 850            for mime_type in TEXT_MIME_TYPES {
 851                data_source.offer(mime_type.to_string());
 852            }
 853            data_source.offer(state.clipboard.self_mime());
 854            primary_selection.set_selection(Some(&data_source), serial);
 855        }
 856    }
 857
 858    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
 859        let mut state = self.0.borrow_mut();
 860        let (Some(data_device_manager), Some(data_device)) = (
 861            state.globals.data_device_manager.clone(),
 862            state.data_device.clone(),
 863        ) else {
 864            return;
 865        };
 866        if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
 867            state.clipboard.set(item);
 868            let serial = state.serial_tracker.get(SerialKind::KeyPress);
 869            let data_source = data_device_manager.create_data_source(&state.globals.qh, ());
 870            for mime_type in TEXT_MIME_TYPES {
 871                data_source.offer(mime_type.to_string());
 872            }
 873            data_source.offer(state.clipboard.self_mime());
 874            data_device.set_selection(Some(&data_source), serial);
 875        }
 876    }
 877
 878    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
 879        self.0.borrow_mut().clipboard.read_primary()
 880    }
 881
 882    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
 883        self.0.borrow_mut().clipboard.read()
 884    }
 885
 886    fn active_window(&self) -> Option<AnyWindowHandle> {
 887        self.0
 888            .borrow_mut()
 889            .keyboard_focused_window
 890            .as_ref()
 891            .map(|window| window.handle())
 892    }
 893
 894    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 895        None
 896    }
 897
 898    fn compositor_name(&self) -> &'static str {
 899        "Wayland"
 900    }
 901
 902    fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
 903        async fn inner(surface: Option<wl_surface::WlSurface>) -> Option<WindowIdentifier> {
 904            if let Some(surface) = surface {
 905                ashpd::WindowIdentifier::from_wayland(&surface).await
 906            } else {
 907                None
 908            }
 909        }
 910
 911        let client_state = self.0.borrow();
 912        let active_window = client_state.keyboard_focused_window.as_ref();
 913        inner(active_window.map(|aw| aw.surface()))
 914    }
 915}
 916
 917impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStatePtr {
 918    fn event(
 919        this: &mut Self,
 920        registry: &wl_registry::WlRegistry,
 921        event: wl_registry::Event,
 922        _: &GlobalListContents,
 923        _: &Connection,
 924        qh: &QueueHandle<Self>,
 925    ) {
 926        let mut client = this.get_client();
 927        let mut state = client.borrow_mut();
 928
 929        match event {
 930            wl_registry::Event::Global {
 931                name,
 932                interface,
 933                version,
 934            } => match &interface[..] {
 935                "wl_seat" => {
 936                    if let Some(wl_pointer) = state.wl_pointer.take() {
 937                        wl_pointer.release();
 938                    }
 939                    if let Some(wl_keyboard) = state.wl_keyboard.take() {
 940                        wl_keyboard.release();
 941                    }
 942                    state.wl_seat.release();
 943                    state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(
 944                        name,
 945                        wl_seat_version(version),
 946                        qh,
 947                        (),
 948                    );
 949                }
 950                "wl_output" => {
 951                    let output = registry.bind::<wl_output::WlOutput, _, _>(
 952                        name,
 953                        wl_output_version(version),
 954                        qh,
 955                        (),
 956                    );
 957
 958                    state
 959                        .in_progress_outputs
 960                        .insert(output.id(), InProgressOutput::default());
 961                }
 962                _ => {}
 963            },
 964            wl_registry::Event::GlobalRemove { name: _ } => {
 965                // TODO: handle global removal
 966            }
 967            _ => {}
 968        }
 969    }
 970}
 971
 972delegate_noop!(WaylandClientStatePtr: ignore xdg_activation_v1::XdgActivationV1);
 973delegate_noop!(WaylandClientStatePtr: ignore wl_compositor::WlCompositor);
 974delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_device_v1::WpCursorShapeDeviceV1);
 975delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_manager_v1::WpCursorShapeManagerV1);
 976delegate_noop!(WaylandClientStatePtr: ignore wl_data_device_manager::WlDataDeviceManager);
 977delegate_noop!(WaylandClientStatePtr: ignore zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1);
 978delegate_noop!(WaylandClientStatePtr: ignore wl_shm::WlShm);
 979delegate_noop!(WaylandClientStatePtr: ignore wl_shm_pool::WlShmPool);
 980delegate_noop!(WaylandClientStatePtr: ignore wl_buffer::WlBuffer);
 981delegate_noop!(WaylandClientStatePtr: ignore wl_region::WlRegion);
 982delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
 983delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
 984delegate_noop!(WaylandClientStatePtr: ignore zwlr_layer_shell_v1::ZwlrLayerShellV1);
 985delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur_manager::OrgKdeKwinBlurManager);
 986delegate_noop!(WaylandClientStatePtr: ignore zwp_text_input_manager_v3::ZwpTextInputManagerV3);
 987delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur::OrgKdeKwinBlur);
 988delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
 989delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
 990
 991impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
 992    fn event(
 993        state: &mut WaylandClientStatePtr,
 994        _: &wl_callback::WlCallback,
 995        event: wl_callback::Event,
 996        surface_id: &ObjectId,
 997        _: &Connection,
 998        _: &QueueHandle<Self>,
 999    ) {
1000        let client = state.get_client();
1001        let mut state = client.borrow_mut();
1002        let Some(window) = get_window(&mut state, surface_id) else {
1003            return;
1004        };
1005        drop(state);
1006
1007        if let wl_callback::Event::Done { .. } = event {
1008            window.frame();
1009        }
1010    }
1011}
1012
1013fn get_window(
1014    mut state: &mut RefMut<WaylandClientState>,
1015    surface_id: &ObjectId,
1016) -> Option<WaylandWindowStatePtr> {
1017    state.windows.get(surface_id).cloned()
1018}
1019
1020impl Dispatch<wl_surface::WlSurface, ()> for WaylandClientStatePtr {
1021    fn event(
1022        this: &mut Self,
1023        surface: &wl_surface::WlSurface,
1024        event: <wl_surface::WlSurface as Proxy>::Event,
1025        _: &(),
1026        _: &Connection,
1027        _: &QueueHandle<Self>,
1028    ) {
1029        let mut client = this.get_client();
1030        let mut state = client.borrow_mut();
1031
1032        let Some(window) = get_window(&mut state, &surface.id()) else {
1033            return;
1034        };
1035        #[allow(clippy::mutable_key_type)]
1036        let outputs = state.outputs.clone();
1037        drop(state);
1038
1039        window.handle_surface_event(event, outputs);
1040    }
1041}
1042
1043impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
1044    fn event(
1045        this: &mut Self,
1046        output: &wl_output::WlOutput,
1047        event: <wl_output::WlOutput as Proxy>::Event,
1048        _: &(),
1049        _: &Connection,
1050        _: &QueueHandle<Self>,
1051    ) {
1052        let mut client = this.get_client();
1053        let mut state = client.borrow_mut();
1054
1055        let Some(mut in_progress_output) = state.in_progress_outputs.get_mut(&output.id()) else {
1056            return;
1057        };
1058
1059        match event {
1060            wl_output::Event::Name { name } => {
1061                in_progress_output.name = Some(name);
1062            }
1063            wl_output::Event::Scale { factor } => {
1064                in_progress_output.scale = Some(factor);
1065            }
1066            wl_output::Event::Geometry { x, y, .. } => {
1067                in_progress_output.position = Some(point(DevicePixels(x), DevicePixels(y)))
1068            }
1069            wl_output::Event::Mode { width, height, .. } => {
1070                in_progress_output.size = Some(size(DevicePixels(width), DevicePixels(height)))
1071            }
1072            wl_output::Event::Done => {
1073                if let Some(complete) = in_progress_output.complete() {
1074                    state.outputs.insert(output.id(), complete);
1075                }
1076                state.in_progress_outputs.remove(&output.id());
1077            }
1078            _ => {}
1079        }
1080    }
1081}
1082
1083impl Dispatch<xdg_surface::XdgSurface, ObjectId> for WaylandClientStatePtr {
1084    fn event(
1085        state: &mut Self,
1086        _: &xdg_surface::XdgSurface,
1087        event: xdg_surface::Event,
1088        surface_id: &ObjectId,
1089        _: &Connection,
1090        _: &QueueHandle<Self>,
1091    ) {
1092        let client = state.get_client();
1093        let mut state = client.borrow_mut();
1094        let Some(window) = get_window(&mut state, surface_id) else {
1095            return;
1096        };
1097        drop(state);
1098        window.handle_xdg_surface_event(event);
1099    }
1100}
1101
1102impl Dispatch<xdg_toplevel::XdgToplevel, ObjectId> for WaylandClientStatePtr {
1103    fn event(
1104        this: &mut Self,
1105        _: &xdg_toplevel::XdgToplevel,
1106        event: <xdg_toplevel::XdgToplevel as Proxy>::Event,
1107        surface_id: &ObjectId,
1108        _: &Connection,
1109        _: &QueueHandle<Self>,
1110    ) {
1111        let client = this.get_client();
1112        let mut state = client.borrow_mut();
1113        let Some(window) = get_window(&mut state, surface_id) else {
1114            return;
1115        };
1116
1117        drop(state);
1118        let should_close = window.handle_toplevel_event(event);
1119
1120        if should_close {
1121            // The close logic will be handled in drop_window()
1122            window.close();
1123        }
1124    }
1125}
1126
1127impl Dispatch<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, ObjectId> for WaylandClientStatePtr {
1128    fn event(
1129        this: &mut Self,
1130        _: &zwlr_layer_surface_v1::ZwlrLayerSurfaceV1,
1131        event: <zwlr_layer_surface_v1::ZwlrLayerSurfaceV1 as Proxy>::Event,
1132        surface_id: &ObjectId,
1133        _: &Connection,
1134        _: &QueueHandle<Self>,
1135    ) {
1136        let client = this.get_client();
1137        let mut state = client.borrow_mut();
1138        let Some(window) = get_window(&mut state, surface_id) else {
1139            return;
1140        };
1141
1142        drop(state);
1143        let should_close = window.handle_layersurface_event(event);
1144
1145        if should_close {
1146            // The close logic will be handled in drop_window()
1147            window.close();
1148        }
1149    }
1150}
1151
1152impl Dispatch<xdg_wm_base::XdgWmBase, ()> for WaylandClientStatePtr {
1153    fn event(
1154        _: &mut Self,
1155        wm_base: &xdg_wm_base::XdgWmBase,
1156        event: <xdg_wm_base::XdgWmBase as Proxy>::Event,
1157        _: &(),
1158        _: &Connection,
1159        _: &QueueHandle<Self>,
1160    ) {
1161        if let xdg_wm_base::Event::Ping { serial } = event {
1162            wm_base.pong(serial);
1163        }
1164    }
1165}
1166
1167impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClientStatePtr {
1168    fn event(
1169        this: &mut Self,
1170        token: &xdg_activation_token_v1::XdgActivationTokenV1,
1171        event: <xdg_activation_token_v1::XdgActivationTokenV1 as Proxy>::Event,
1172        _: &(),
1173        _: &Connection,
1174        _: &QueueHandle<Self>,
1175    ) {
1176        let client = this.get_client();
1177        let mut state = client.borrow_mut();
1178
1179        if let xdg_activation_token_v1::Event::Done { token } = event {
1180            let executor = state.common.background_executor.clone();
1181            match state.pending_activation.take() {
1182                Some(PendingActivation::Uri(uri)) => open_uri_internal(executor, &uri, Some(token)),
1183                Some(PendingActivation::Path(path)) => {
1184                    reveal_path_internal(executor, path, Some(token))
1185                }
1186                Some(PendingActivation::Window(window)) => {
1187                    let Some(window) = get_window(&mut state, &window) else {
1188                        return;
1189                    };
1190                    let activation = state.globals.activation.as_ref().unwrap();
1191                    activation.activate(token, &window.surface());
1192                }
1193                None => log::error!("activation token received with no pending activation"),
1194            }
1195        }
1196
1197        token.destroy();
1198    }
1199}
1200
1201impl Dispatch<wl_seat::WlSeat, ()> for WaylandClientStatePtr {
1202    fn event(
1203        state: &mut Self,
1204        seat: &wl_seat::WlSeat,
1205        event: wl_seat::Event,
1206        _: &(),
1207        _: &Connection,
1208        qh: &QueueHandle<Self>,
1209    ) {
1210        if let wl_seat::Event::Capabilities {
1211            capabilities: WEnum::Value(capabilities),
1212        } = event
1213        {
1214            let client = state.get_client();
1215            let mut state = client.borrow_mut();
1216            if capabilities.contains(wl_seat::Capability::Keyboard) {
1217                let keyboard = seat.get_keyboard(qh, ());
1218
1219                state.text_input = state
1220                    .globals
1221                    .text_input_manager
1222                    .as_ref()
1223                    .map(|text_input_manager| text_input_manager.get_text_input(seat, qh, ()));
1224
1225                if let Some(wl_keyboard) = &state.wl_keyboard {
1226                    wl_keyboard.release();
1227                }
1228
1229                state.wl_keyboard = Some(keyboard);
1230            }
1231            if capabilities.contains(wl_seat::Capability::Pointer) {
1232                let pointer = seat.get_pointer(qh, ());
1233                state.cursor_shape_device = state
1234                    .globals
1235                    .cursor_shape_manager
1236                    .as_ref()
1237                    .map(|cursor_shape_manager| cursor_shape_manager.get_pointer(&pointer, qh, ()));
1238
1239                if let Some(wl_pointer) = &state.wl_pointer {
1240                    wl_pointer.release();
1241                }
1242
1243                state.wl_pointer = Some(pointer);
1244            }
1245        }
1246    }
1247}
1248
1249impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
1250    fn event(
1251        this: &mut Self,
1252        _: &wl_keyboard::WlKeyboard,
1253        event: wl_keyboard::Event,
1254        _: &(),
1255        _: &Connection,
1256        _: &QueueHandle<Self>,
1257    ) {
1258        let mut client = this.get_client();
1259        let mut state = client.borrow_mut();
1260        match event {
1261            wl_keyboard::Event::RepeatInfo { rate, delay } => {
1262                state.repeat.characters_per_second = rate as u32;
1263                state.repeat.delay = Duration::from_millis(delay as u64);
1264            }
1265            wl_keyboard::Event::Keymap {
1266                format: WEnum::Value(format),
1267                fd,
1268                size,
1269                ..
1270            } => {
1271                if format != wl_keyboard::KeymapFormat::XkbV1 {
1272                    log::error!("Received keymap format {:?}, expected XkbV1", format);
1273                    return;
1274                }
1275                let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
1276                let keymap = unsafe {
1277                    xkb::Keymap::new_from_fd(
1278                        &xkb_context,
1279                        fd,
1280                        size as usize,
1281                        XKB_KEYMAP_FORMAT_TEXT_V1,
1282                        KEYMAP_COMPILE_NO_FLAGS,
1283                    )
1284                    .log_err()
1285                    .flatten()
1286                    .expect("Failed to create keymap")
1287                };
1288                state.keymap_state = Some(xkb::State::new(&keymap));
1289                state.compose_state = get_xkb_compose_state(&xkb_context);
1290                drop(state);
1291
1292                this.handle_keyboard_layout_change();
1293            }
1294            wl_keyboard::Event::Enter { surface, .. } => {
1295                state.keyboard_focused_window = get_window(&mut state, &surface.id());
1296                state.enter_token = Some(());
1297
1298                if let Some(window) = state.keyboard_focused_window.clone() {
1299                    drop(state);
1300                    window.set_focused(true);
1301                }
1302            }
1303            wl_keyboard::Event::Leave { surface, .. } => {
1304                let keyboard_focused_window = get_window(&mut state, &surface.id());
1305                state.keyboard_focused_window = None;
1306                state.enter_token.take();
1307                // Prevent keyboard events from repeating after opening e.g. a file chooser and closing it quickly
1308                state.repeat.current_id += 1;
1309
1310                if let Some(window) = keyboard_focused_window {
1311                    if let Some(ref mut compose) = state.compose_state {
1312                        compose.reset();
1313                    }
1314                    state.pre_edit_text.take();
1315                    drop(state);
1316                    window.handle_ime(ImeInput::DeleteText);
1317                    window.set_focused(false);
1318                }
1319            }
1320            wl_keyboard::Event::Modifiers {
1321                mods_depressed,
1322                mods_latched,
1323                mods_locked,
1324                group,
1325                ..
1326            } => {
1327                let focused_window = state.keyboard_focused_window.clone();
1328
1329                let keymap_state = state.keymap_state.as_mut().unwrap();
1330                let old_layout =
1331                    keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
1332                keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1333                state.modifiers = Modifiers::from_xkb(keymap_state);
1334                let keymap_state = state.keymap_state.as_mut().unwrap();
1335                state.capslock = Capslock::from_xkb(keymap_state);
1336
1337                let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1338                    modifiers: state.modifiers,
1339                    capslock: state.capslock,
1340                });
1341                drop(state);
1342
1343                if let Some(focused_window) = focused_window {
1344                    focused_window.handle_input(input);
1345                }
1346
1347                if group != old_layout {
1348                    this.handle_keyboard_layout_change();
1349                }
1350            }
1351            wl_keyboard::Event::Key {
1352                serial,
1353                key,
1354                state: WEnum::Value(key_state),
1355                ..
1356            } => {
1357                state.serial_tracker.update(SerialKind::KeyPress, serial);
1358
1359                let focused_window = state.keyboard_focused_window.clone();
1360                let Some(focused_window) = focused_window else {
1361                    return;
1362                };
1363
1364                let keymap_state = state.keymap_state.as_ref().unwrap();
1365                let keycode = Keycode::from(key + MIN_KEYCODE);
1366                let keysym = keymap_state.key_get_one_sym(keycode);
1367
1368                match key_state {
1369                    wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1370                        let mut keystroke =
1371                            Keystroke::from_xkb(keymap_state, state.modifiers, keycode);
1372                        if let Some(mut compose) = state.compose_state.take() {
1373                            compose.feed(keysym);
1374                            match compose.status() {
1375                                xkb::Status::Composing => {
1376                                    keystroke.key_char = None;
1377                                    state.pre_edit_text =
1378                                        compose.utf8().or(Keystroke::underlying_dead_key(keysym));
1379                                    let pre_edit =
1380                                        state.pre_edit_text.clone().unwrap_or(String::default());
1381                                    drop(state);
1382                                    focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1383                                    state = client.borrow_mut();
1384                                }
1385
1386                                xkb::Status::Composed => {
1387                                    state.pre_edit_text.take();
1388                                    keystroke.key_char = compose.utf8();
1389                                    if let Some(keysym) = compose.keysym() {
1390                                        keystroke.key = xkb::keysym_get_name(keysym);
1391                                    }
1392                                }
1393                                xkb::Status::Cancelled => {
1394                                    let pre_edit = state.pre_edit_text.take();
1395                                    let new_pre_edit = Keystroke::underlying_dead_key(keysym);
1396                                    state.pre_edit_text = new_pre_edit.clone();
1397                                    drop(state);
1398                                    if let Some(pre_edit) = pre_edit {
1399                                        focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1400                                    }
1401                                    if let Some(current_key) = new_pre_edit {
1402                                        focused_window
1403                                            .handle_ime(ImeInput::SetMarkedText(current_key));
1404                                    }
1405                                    compose.feed(keysym);
1406                                    state = client.borrow_mut();
1407                                }
1408                                _ => {}
1409                            }
1410                            state.compose_state = Some(compose);
1411                        }
1412                        let input = PlatformInput::KeyDown(KeyDownEvent {
1413                            keystroke: keystroke.clone(),
1414                            is_held: false,
1415                            prefer_character_input: false,
1416                        });
1417
1418                        state.repeat.current_id += 1;
1419                        state.repeat.current_keycode = Some(keycode);
1420
1421                        let rate = state.repeat.characters_per_second;
1422                        let repeat_interval = Duration::from_secs(1) / rate;
1423                        let id = state.repeat.current_id;
1424                        state
1425                            .loop_handle
1426                            .insert_source(Timer::from_duration(state.repeat.delay), {
1427                                let input = PlatformInput::KeyDown(KeyDownEvent {
1428                                    keystroke,
1429                                    is_held: true,
1430                                    prefer_character_input: false,
1431                                });
1432                                move |event_timestamp, _metadata, this| {
1433                                    let mut client = this.get_client();
1434                                    let mut state = client.borrow_mut();
1435                                    let is_repeating = id == state.repeat.current_id
1436                                        && state.repeat.current_keycode.is_some()
1437                                        && state.keyboard_focused_window.is_some();
1438
1439                                    if !is_repeating || rate == 0 {
1440                                        return TimeoutAction::Drop;
1441                                    }
1442
1443                                    let focused_window =
1444                                        state.keyboard_focused_window.as_ref().unwrap().clone();
1445
1446                                    drop(state);
1447                                    focused_window.handle_input(input.clone());
1448
1449                                    // If the new scheduled time is in the past the event will repeat as soon as possible
1450                                    TimeoutAction::ToInstant(event_timestamp + repeat_interval)
1451                                }
1452                            })
1453                            .unwrap();
1454
1455                        drop(state);
1456                        focused_window.handle_input(input);
1457                    }
1458                    wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1459                        let input = PlatformInput::KeyUp(KeyUpEvent {
1460                            keystroke: Keystroke::from_xkb(keymap_state, state.modifiers, keycode),
1461                        });
1462
1463                        if state.repeat.current_keycode == Some(keycode) {
1464                            state.repeat.current_keycode = None;
1465                        }
1466
1467                        drop(state);
1468                        focused_window.handle_input(input);
1469                    }
1470                    _ => {}
1471                }
1472            }
1473            _ => {}
1474        }
1475    }
1476}
1477
1478impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1479    fn event(
1480        this: &mut Self,
1481        text_input: &zwp_text_input_v3::ZwpTextInputV3,
1482        event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1483        _: &(),
1484        _: &Connection,
1485        _: &QueueHandle<Self>,
1486    ) {
1487        let client = this.get_client();
1488        let mut state = client.borrow_mut();
1489        match event {
1490            zwp_text_input_v3::Event::Enter { .. } => {
1491                drop(state);
1492                this.enable_ime();
1493            }
1494            zwp_text_input_v3::Event::Leave { .. } => {
1495                drop(state);
1496                this.disable_ime();
1497            }
1498            zwp_text_input_v3::Event::CommitString { text } => {
1499                state.composing = false;
1500                let Some(window) = state.keyboard_focused_window.clone() else {
1501                    return;
1502                };
1503
1504                if let Some(commit_text) = text {
1505                    drop(state);
1506                    // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1507                    // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1508                    if commit_text.len() == 1 {
1509                        window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1510                            keystroke: Keystroke {
1511                                modifiers: Modifiers::default(),
1512                                key: commit_text.clone(),
1513                                key_char: Some(commit_text),
1514                            },
1515                            is_held: false,
1516                            prefer_character_input: false,
1517                        }));
1518                    } else {
1519                        window.handle_ime(ImeInput::InsertText(commit_text));
1520                    }
1521                }
1522            }
1523            zwp_text_input_v3::Event::PreeditString { text, .. } => {
1524                state.composing = true;
1525                state.ime_pre_edit = text;
1526            }
1527            zwp_text_input_v3::Event::Done { serial } => {
1528                let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1529                state.serial_tracker.update(SerialKind::InputMethod, serial);
1530                let Some(window) = state.keyboard_focused_window.clone() else {
1531                    return;
1532                };
1533
1534                if let Some(text) = state.ime_pre_edit.take() {
1535                    drop(state);
1536                    window.handle_ime(ImeInput::SetMarkedText(text));
1537                    if let Some(area) = window.get_ime_area() {
1538                        text_input.set_cursor_rectangle(
1539                            area.origin.x.0 as i32,
1540                            area.origin.y.0 as i32,
1541                            area.size.width.0 as i32,
1542                            area.size.height.0 as i32,
1543                        );
1544                        if last_serial == serial {
1545                            text_input.commit();
1546                        }
1547                    }
1548                } else {
1549                    state.composing = false;
1550                    drop(state);
1551                    window.handle_ime(ImeInput::DeleteText);
1552                }
1553            }
1554            _ => {}
1555        }
1556    }
1557}
1558
1559fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1560    // These values are coming from <linux/input-event-codes.h>.
1561    const BTN_LEFT: u32 = 0x110;
1562    const BTN_RIGHT: u32 = 0x111;
1563    const BTN_MIDDLE: u32 = 0x112;
1564    const BTN_SIDE: u32 = 0x113;
1565    const BTN_EXTRA: u32 = 0x114;
1566    const BTN_FORWARD: u32 = 0x115;
1567    const BTN_BACK: u32 = 0x116;
1568
1569    Some(match button {
1570        BTN_LEFT => MouseButton::Left,
1571        BTN_RIGHT => MouseButton::Right,
1572        BTN_MIDDLE => MouseButton::Middle,
1573        BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1574        BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1575        _ => return None,
1576    })
1577}
1578
1579impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1580    fn event(
1581        this: &mut Self,
1582        wl_pointer: &wl_pointer::WlPointer,
1583        event: wl_pointer::Event,
1584        _: &(),
1585        _: &Connection,
1586        _: &QueueHandle<Self>,
1587    ) {
1588        let mut client = this.get_client();
1589        let mut state = client.borrow_mut();
1590
1591        match event {
1592            wl_pointer::Event::Enter {
1593                serial,
1594                surface,
1595                surface_x,
1596                surface_y,
1597                ..
1598            } => {
1599                state.serial_tracker.update(SerialKind::MouseEnter, serial);
1600                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1601                state.button_pressed = None;
1602
1603                if let Some(window) = get_window(&mut state, &surface.id()) {
1604                    state.mouse_focused_window = Some(window.clone());
1605
1606                    if state.enter_token.is_some() {
1607                        state.enter_token = None;
1608                    }
1609                    if let Some(style) = state.cursor_style {
1610                        if let CursorStyle::None = style {
1611                            let wl_pointer = state
1612                                .wl_pointer
1613                                .clone()
1614                                .expect("window is focused by pointer");
1615                            wl_pointer.set_cursor(serial, None, 0, 0);
1616                        } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
1617                            cursor_shape_device.set_shape(serial, style.to_shape());
1618                        } else {
1619                            let scale = window.primary_output_scale();
1620                            state
1621                                .cursor
1622                                .set_icon(wl_pointer, serial, style.to_icon_names(), scale);
1623                        }
1624                    }
1625                    drop(state);
1626                    window.set_hovered(true);
1627                }
1628            }
1629            wl_pointer::Event::Leave { .. } => {
1630                if let Some(focused_window) = state.mouse_focused_window.clone() {
1631                    let input = PlatformInput::MouseExited(MouseExitEvent {
1632                        position: state.mouse_location.unwrap(),
1633                        pressed_button: state.button_pressed,
1634                        modifiers: state.modifiers,
1635                    });
1636                    state.mouse_focused_window = None;
1637                    state.mouse_location = None;
1638                    state.button_pressed = None;
1639
1640                    drop(state);
1641                    focused_window.handle_input(input);
1642                    focused_window.set_hovered(false);
1643                }
1644            }
1645            wl_pointer::Event::Motion {
1646                surface_x,
1647                surface_y,
1648                ..
1649            } => {
1650                if state.mouse_focused_window.is_none() {
1651                    return;
1652                }
1653                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1654
1655                if let Some(window) = state.mouse_focused_window.clone() {
1656                    if state
1657                        .keyboard_focused_window
1658                        .as_ref()
1659                        .is_some_and(|keyboard_window| window.ptr_eq(keyboard_window))
1660                    {
1661                        state.enter_token = None;
1662                    }
1663                    let input = PlatformInput::MouseMove(MouseMoveEvent {
1664                        position: state.mouse_location.unwrap(),
1665                        pressed_button: state.button_pressed,
1666                        modifiers: state.modifiers,
1667                    });
1668                    drop(state);
1669                    window.handle_input(input);
1670                }
1671            }
1672            wl_pointer::Event::Button {
1673                serial,
1674                button,
1675                state: WEnum::Value(button_state),
1676                ..
1677            } => {
1678                state.serial_tracker.update(SerialKind::MousePress, serial);
1679                let button = linux_button_to_gpui(button);
1680                let Some(button) = button else { return };
1681                if state.mouse_focused_window.is_none() {
1682                    return;
1683                }
1684                match button_state {
1685                    wl_pointer::ButtonState::Pressed => {
1686                        if let Some(window) = state.keyboard_focused_window.clone() {
1687                            if state.composing && state.text_input.is_some() {
1688                                drop(state);
1689                                // text_input_v3 don't have something like a reset function
1690                                this.disable_ime();
1691                                this.enable_ime();
1692                                window.handle_ime(ImeInput::UnmarkText);
1693                                state = client.borrow_mut();
1694                            } else if let (Some(text), Some(compose)) =
1695                                (state.pre_edit_text.take(), state.compose_state.as_mut())
1696                            {
1697                                compose.reset();
1698                                drop(state);
1699                                window.handle_ime(ImeInput::InsertText(text));
1700                                state = client.borrow_mut();
1701                            }
1702                        }
1703                        let click_elapsed = state.click.last_click.elapsed();
1704
1705                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1706                            && state
1707                                .click
1708                                .last_mouse_button
1709                                .is_some_and(|prev_button| prev_button == button)
1710                            && is_within_click_distance(
1711                                state.click.last_location,
1712                                state.mouse_location.unwrap(),
1713                            )
1714                        {
1715                            state.click.current_count += 1;
1716                        } else {
1717                            state.click.current_count = 1;
1718                        }
1719
1720                        state.click.last_click = Instant::now();
1721                        state.click.last_mouse_button = Some(button);
1722                        state.click.last_location = state.mouse_location.unwrap();
1723
1724                        state.button_pressed = Some(button);
1725
1726                        if let Some(window) = state.mouse_focused_window.clone() {
1727                            let input = PlatformInput::MouseDown(MouseDownEvent {
1728                                button,
1729                                position: state.mouse_location.unwrap(),
1730                                modifiers: state.modifiers,
1731                                click_count: state.click.current_count,
1732                                first_mouse: state.enter_token.take().is_some(),
1733                            });
1734                            drop(state);
1735                            window.handle_input(input);
1736                        }
1737                    }
1738                    wl_pointer::ButtonState::Released => {
1739                        state.button_pressed = None;
1740
1741                        if let Some(window) = state.mouse_focused_window.clone() {
1742                            let input = PlatformInput::MouseUp(MouseUpEvent {
1743                                button,
1744                                position: state.mouse_location.unwrap(),
1745                                modifiers: state.modifiers,
1746                                click_count: state.click.current_count,
1747                            });
1748                            drop(state);
1749                            window.handle_input(input);
1750                        }
1751                    }
1752                    _ => {}
1753                }
1754            }
1755
1756            // Axis Events
1757            wl_pointer::Event::AxisSource {
1758                axis_source: WEnum::Value(axis_source),
1759            } => {
1760                state.axis_source = axis_source;
1761            }
1762            wl_pointer::Event::Axis {
1763                axis: WEnum::Value(axis),
1764                value,
1765                ..
1766            } => {
1767                if state.axis_source == AxisSource::Wheel {
1768                    return;
1769                }
1770                let axis = if state.modifiers.shift {
1771                    wl_pointer::Axis::HorizontalScroll
1772                } else {
1773                    axis
1774                };
1775                let axis_modifier = match axis {
1776                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1777                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1778                    _ => 1.0,
1779                };
1780                state.scroll_event_received = true;
1781                let scroll_delta = state
1782                    .continuous_scroll_delta
1783                    .get_or_insert(point(px(0.0), px(0.0)));
1784                let modifier = 3.0;
1785                match axis {
1786                    wl_pointer::Axis::VerticalScroll => {
1787                        scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1788                    }
1789                    wl_pointer::Axis::HorizontalScroll => {
1790                        scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1791                    }
1792                    _ => unreachable!(),
1793                }
1794            }
1795            wl_pointer::Event::AxisDiscrete {
1796                axis: WEnum::Value(axis),
1797                discrete,
1798            } => {
1799                state.scroll_event_received = true;
1800                let axis = if state.modifiers.shift {
1801                    wl_pointer::Axis::HorizontalScroll
1802                } else {
1803                    axis
1804                };
1805                let axis_modifier = match axis {
1806                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1807                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1808                    _ => 1.0,
1809                };
1810
1811                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1812                match axis {
1813                    wl_pointer::Axis::VerticalScroll => {
1814                        scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES;
1815                    }
1816                    wl_pointer::Axis::HorizontalScroll => {
1817                        scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES;
1818                    }
1819                    _ => unreachable!(),
1820                }
1821            }
1822            wl_pointer::Event::AxisValue120 {
1823                axis: WEnum::Value(axis),
1824                value120,
1825            } => {
1826                state.scroll_event_received = true;
1827                let axis = if state.modifiers.shift {
1828                    wl_pointer::Axis::HorizontalScroll
1829                } else {
1830                    axis
1831                };
1832                let axis_modifier = match axis {
1833                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1834                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1835                    _ => unreachable!(),
1836                };
1837
1838                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1839                let wheel_percent = value120 as f32 / 120.0;
1840                match axis {
1841                    wl_pointer::Axis::VerticalScroll => {
1842                        scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES;
1843                    }
1844                    wl_pointer::Axis::HorizontalScroll => {
1845                        scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES;
1846                    }
1847                    _ => unreachable!(),
1848                }
1849            }
1850            wl_pointer::Event::Frame => {
1851                if state.scroll_event_received {
1852                    state.scroll_event_received = false;
1853                    let continuous = state.continuous_scroll_delta.take();
1854                    let discrete = state.discrete_scroll_delta.take();
1855                    if let Some(continuous) = continuous {
1856                        if let Some(window) = state.mouse_focused_window.clone() {
1857                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1858                                position: state.mouse_location.unwrap(),
1859                                delta: ScrollDelta::Pixels(continuous),
1860                                modifiers: state.modifiers,
1861                                touch_phase: TouchPhase::Moved,
1862                            });
1863                            drop(state);
1864                            window.handle_input(input);
1865                        }
1866                    } else if let Some(discrete) = discrete
1867                        && let Some(window) = state.mouse_focused_window.clone()
1868                    {
1869                        let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1870                            position: state.mouse_location.unwrap(),
1871                            delta: ScrollDelta::Lines(discrete),
1872                            modifiers: state.modifiers,
1873                            touch_phase: TouchPhase::Moved,
1874                        });
1875                        drop(state);
1876                        window.handle_input(input);
1877                    }
1878                }
1879            }
1880            _ => {}
1881        }
1882    }
1883}
1884
1885impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1886    fn event(
1887        this: &mut Self,
1888        _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1889        event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1890        surface_id: &ObjectId,
1891        _: &Connection,
1892        _: &QueueHandle<Self>,
1893    ) {
1894        let client = this.get_client();
1895        let mut state = client.borrow_mut();
1896
1897        let Some(window) = get_window(&mut state, surface_id) else {
1898            return;
1899        };
1900
1901        drop(state);
1902        window.handle_fractional_scale_event(event);
1903    }
1904}
1905
1906impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1907    for WaylandClientStatePtr
1908{
1909    fn event(
1910        this: &mut Self,
1911        _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1912        event: zxdg_toplevel_decoration_v1::Event,
1913        surface_id: &ObjectId,
1914        _: &Connection,
1915        _: &QueueHandle<Self>,
1916    ) {
1917        let client = this.get_client();
1918        let mut state = client.borrow_mut();
1919        let Some(window) = get_window(&mut state, surface_id) else {
1920            return;
1921        };
1922
1923        drop(state);
1924        window.handle_toplevel_decoration_event(event);
1925    }
1926}
1927
1928impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1929    fn event(
1930        this: &mut Self,
1931        _: &wl_data_device::WlDataDevice,
1932        event: wl_data_device::Event,
1933        _: &(),
1934        _: &Connection,
1935        _: &QueueHandle<Self>,
1936    ) {
1937        let client = this.get_client();
1938        let mut state = client.borrow_mut();
1939
1940        match event {
1941            // Clipboard
1942            wl_data_device::Event::DataOffer { id: data_offer } => {
1943                state.data_offers.push(DataOffer::new(data_offer));
1944                if state.data_offers.len() > 2 {
1945                    // At most we store a clipboard offer and a drag and drop offer.
1946                    state.data_offers.remove(0).inner.destroy();
1947                }
1948            }
1949            wl_data_device::Event::Selection { id: data_offer } => {
1950                if let Some(offer) = data_offer {
1951                    let offer = state
1952                        .data_offers
1953                        .iter()
1954                        .find(|wrapper| wrapper.inner.id() == offer.id());
1955                    let offer = offer.cloned();
1956                    state.clipboard.set_offer(offer);
1957                } else {
1958                    state.clipboard.set_offer(None);
1959                }
1960            }
1961
1962            // Drag and drop
1963            wl_data_device::Event::Enter {
1964                serial,
1965                surface,
1966                x,
1967                y,
1968                id: data_offer,
1969            } => {
1970                state.serial_tracker.update(SerialKind::DataDevice, serial);
1971                if let Some(data_offer) = data_offer {
1972                    let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1973                        return;
1974                    };
1975
1976                    const ACTIONS: DndAction = DndAction::Copy;
1977                    data_offer.set_actions(ACTIONS, ACTIONS);
1978
1979                    let pipe = Pipe::new().unwrap();
1980                    data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1981                        BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1982                    });
1983                    let fd = pipe.read;
1984                    drop(pipe.write);
1985
1986                    let read_task = state.common.background_executor.spawn(async {
1987                        let buffer = unsafe { read_fd(fd)? };
1988                        let text = String::from_utf8(buffer)?;
1989                        anyhow::Ok(text)
1990                    });
1991
1992                    let this = this.clone();
1993                    state
1994                        .common
1995                        .foreground_executor
1996                        .spawn(async move {
1997                            let file_list = match read_task.await {
1998                                Ok(list) => list,
1999                                Err(err) => {
2000                                    log::error!("error reading drag and drop pipe: {err:?}");
2001                                    return;
2002                                }
2003                            };
2004
2005                            let paths: SmallVec<[_; 2]> = file_list
2006                                .lines()
2007                                .filter_map(|path| Url::parse(path).log_err())
2008                                .filter_map(|url| url.to_file_path().log_err())
2009                                .collect();
2010                            let position = Point::new(x.into(), y.into());
2011
2012                            // Prevent dropping text from other programs.
2013                            if paths.is_empty() {
2014                                data_offer.destroy();
2015                                return;
2016                            }
2017
2018                            let input = PlatformInput::FileDrop(FileDropEvent::Entered {
2019                                position,
2020                                paths: crate::ExternalPaths(paths),
2021                            });
2022
2023                            let client = this.get_client();
2024                            let mut state = client.borrow_mut();
2025                            state.drag.data_offer = Some(data_offer);
2026                            state.drag.window = Some(drag_window.clone());
2027                            state.drag.position = position;
2028
2029                            drop(state);
2030                            drag_window.handle_input(input);
2031                        })
2032                        .detach();
2033                }
2034            }
2035            wl_data_device::Event::Motion { x, y, .. } => {
2036                let Some(drag_window) = state.drag.window.clone() else {
2037                    return;
2038                };
2039                let position = Point::new(x.into(), y.into());
2040                state.drag.position = position;
2041
2042                let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
2043                drop(state);
2044                drag_window.handle_input(input);
2045            }
2046            wl_data_device::Event::Leave => {
2047                let Some(drag_window) = state.drag.window.clone() else {
2048                    return;
2049                };
2050                let data_offer = state.drag.data_offer.clone().unwrap();
2051                data_offer.destroy();
2052
2053                state.drag.data_offer = None;
2054                state.drag.window = None;
2055
2056                let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
2057                drop(state);
2058                drag_window.handle_input(input);
2059            }
2060            wl_data_device::Event::Drop => {
2061                let Some(drag_window) = state.drag.window.clone() else {
2062                    return;
2063                };
2064                let data_offer = state.drag.data_offer.clone().unwrap();
2065                data_offer.finish();
2066                data_offer.destroy();
2067
2068                state.drag.data_offer = None;
2069                state.drag.window = None;
2070
2071                let input = PlatformInput::FileDrop(FileDropEvent::Submit {
2072                    position: state.drag.position,
2073                });
2074                drop(state);
2075                drag_window.handle_input(input);
2076            }
2077            _ => {}
2078        }
2079    }
2080
2081    event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
2082        wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
2083    ]);
2084}
2085
2086impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
2087    fn event(
2088        this: &mut Self,
2089        data_offer: &wl_data_offer::WlDataOffer,
2090        event: wl_data_offer::Event,
2091        _: &(),
2092        _: &Connection,
2093        _: &QueueHandle<Self>,
2094    ) {
2095        let client = this.get_client();
2096        let mut state = client.borrow_mut();
2097
2098        if let wl_data_offer::Event::Offer { mime_type } = event {
2099            // Drag and drop
2100            if mime_type == FILE_LIST_MIME_TYPE {
2101                let serial = state.serial_tracker.get(SerialKind::DataDevice);
2102                let mime_type = mime_type.clone();
2103                data_offer.accept(serial, Some(mime_type));
2104            }
2105
2106            // Clipboard
2107            if let Some(offer) = state
2108                .data_offers
2109                .iter_mut()
2110                .find(|wrapper| wrapper.inner.id() == data_offer.id())
2111            {
2112                offer.add_mime_type(mime_type);
2113            }
2114        }
2115    }
2116}
2117
2118impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
2119    fn event(
2120        this: &mut Self,
2121        data_source: &wl_data_source::WlDataSource,
2122        event: wl_data_source::Event,
2123        _: &(),
2124        _: &Connection,
2125        _: &QueueHandle<Self>,
2126    ) {
2127        let client = this.get_client();
2128        let mut state = client.borrow_mut();
2129
2130        match event {
2131            wl_data_source::Event::Send { mime_type, fd } => {
2132                state.clipboard.send(mime_type, fd);
2133            }
2134            wl_data_source::Event::Cancelled => {
2135                data_source.destroy();
2136            }
2137            _ => {}
2138        }
2139    }
2140}
2141
2142impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
2143    for WaylandClientStatePtr
2144{
2145    fn event(
2146        this: &mut Self,
2147        _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
2148        event: zwp_primary_selection_device_v1::Event,
2149        _: &(),
2150        _: &Connection,
2151        _: &QueueHandle<Self>,
2152    ) {
2153        let client = this.get_client();
2154        let mut state = client.borrow_mut();
2155
2156        match event {
2157            zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
2158                let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
2159                if let Some(old_offer) = old_offer {
2160                    old_offer.inner.destroy();
2161                }
2162            }
2163            zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
2164                if data_offer.is_some() {
2165                    let offer = state.primary_data_offer.clone();
2166                    state.clipboard.set_primary_offer(offer);
2167                } else {
2168                    state.clipboard.set_primary_offer(None);
2169                }
2170            }
2171            _ => {}
2172        }
2173    }
2174
2175    event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
2176        zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
2177    ]);
2178}
2179
2180impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
2181    for WaylandClientStatePtr
2182{
2183    fn event(
2184        this: &mut Self,
2185        _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
2186        event: zwp_primary_selection_offer_v1::Event,
2187        _: &(),
2188        _: &Connection,
2189        _: &QueueHandle<Self>,
2190    ) {
2191        let client = this.get_client();
2192        let mut state = client.borrow_mut();
2193
2194        if let zwp_primary_selection_offer_v1::Event::Offer { mime_type } = event
2195            && let Some(offer) = state.primary_data_offer.as_mut()
2196        {
2197            offer.add_mime_type(mime_type);
2198        }
2199    }
2200}
2201
2202impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2203    for WaylandClientStatePtr
2204{
2205    fn event(
2206        this: &mut Self,
2207        selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2208        event: zwp_primary_selection_source_v1::Event,
2209        _: &(),
2210        _: &Connection,
2211        _: &QueueHandle<Self>,
2212    ) {
2213        let client = this.get_client();
2214        let mut state = client.borrow_mut();
2215
2216        match event {
2217            zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2218                state.clipboard.send_primary(mime_type, fd);
2219            }
2220            zwp_primary_selection_source_v1::Event::Cancelled => {
2221                selection_source.destroy();
2222            }
2223            _ => {}
2224        }
2225    }
2226}