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