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