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