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::{
  70    display::WaylandDisplay,
  71    window::{ImeInput, WaylandWindowStatePtr},
  72};
  73
  74use crate::platform::linux::{
  75    LinuxClient, get_xkb_compose_state, is_within_click_distance, open_uri_internal, read_fd,
  76    reveal_path_internal,
  77    wayland::{
  78        clipboard::{Clipboard, DataOffer, FILE_LIST_MIME_TYPE, TEXT_MIME_TYPE},
  79        cursor::Cursor,
  80        serial::{SerialKind, SerialTracker},
  81        window::WaylandWindow,
  82    },
  83    xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
  84};
  85use crate::platform::{PlatformWindow, blade::BladeContext};
  86use crate::{
  87    AnyWindowHandle, Bounds, CursorStyle, DOUBLE_CLICK_INTERVAL, DevicePixels, DisplayId,
  88    FileDropEvent, ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke, LinuxCommon,
  89    LinuxKeyboardLayout, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
  90    MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels, PlatformDisplay,
  91    PlatformInput, PlatformKeyboardLayout, Point, SCROLL_LINES, ScaledPixels, ScreenCaptureSource,
  92    ScrollDelta, ScrollWheelEvent, Size, TouchPhase, WindowParams, point, px, size,
  93};
  94
  95/// Used to convert evdev scancode to xkb scancode
  96const MIN_KEYCODE: u32 = 8;
  97
  98#[derive(Clone)]
  99pub struct Globals {
 100    pub qh: QueueHandle<WaylandClientStatePtr>,
 101    pub activation: Option<xdg_activation_v1::XdgActivationV1>,
 102    pub compositor: wl_compositor::WlCompositor,
 103    pub cursor_shape_manager: Option<wp_cursor_shape_manager_v1::WpCursorShapeManagerV1>,
 104    pub data_device_manager: Option<wl_data_device_manager::WlDataDeviceManager>,
 105    pub primary_selection_manager:
 106        Option<zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1>,
 107    pub wm_base: xdg_wm_base::XdgWmBase,
 108    pub shm: wl_shm::WlShm,
 109    pub seat: wl_seat::WlSeat,
 110    pub viewporter: Option<wp_viewporter::WpViewporter>,
 111    pub fractional_scale_manager:
 112        Option<wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1>,
 113    pub decoration_manager: Option<zxdg_decoration_manager_v1::ZxdgDecorationManagerV1>,
 114    pub blur_manager: Option<org_kde_kwin_blur_manager::OrgKdeKwinBlurManager>,
 115    pub text_input_manager: Option<zwp_text_input_manager_v3::ZwpTextInputManagerV3>,
 116    pub executor: ForegroundExecutor,
 117}
 118
 119impl Globals {
 120    fn new(
 121        globals: GlobalList,
 122        executor: ForegroundExecutor,
 123        qh: QueueHandle<WaylandClientStatePtr>,
 124        seat: wl_seat::WlSeat,
 125    ) -> Self {
 126        Globals {
 127            activation: globals.bind(&qh, 1..=1, ()).ok(),
 128            compositor: globals
 129                .bind(
 130                    &qh,
 131                    wl_surface::REQ_SET_BUFFER_SCALE_SINCE
 132                        ..=wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE,
 133                    (),
 134                )
 135                .unwrap(),
 136            cursor_shape_manager: globals.bind(&qh, 1..=1, ()).ok(),
 137            data_device_manager: globals
 138                .bind(
 139                    &qh,
 140                    WL_DATA_DEVICE_MANAGER_VERSION..=WL_DATA_DEVICE_MANAGER_VERSION,
 141                    (),
 142                )
 143                .ok(),
 144            primary_selection_manager: globals.bind(&qh, 1..=1, ()).ok(),
 145            shm: globals.bind(&qh, 1..=1, ()).unwrap(),
 146            seat,
 147            wm_base: globals.bind(&qh, 2..=5, ()).unwrap(),
 148            viewporter: globals.bind(&qh, 1..=1, ()).ok(),
 149            fractional_scale_manager: globals.bind(&qh, 1..=1, ()).ok(),
 150            decoration_manager: globals.bind(&qh, 1..=1, ()).ok(),
 151            blur_manager: globals.bind(&qh, 1..=1, ()).ok(),
 152            text_input_manager: globals.bind(&qh, 1..=1, ()).ok(),
 153            executor,
 154            qh,
 155        }
 156    }
 157}
 158
 159#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
 160pub struct InProgressOutput {
 161    name: Option<String>,
 162    scale: Option<i32>,
 163    position: Option<Point<DevicePixels>>,
 164    size: Option<Size<DevicePixels>>,
 165}
 166
 167impl InProgressOutput {
 168    fn complete(&self) -> Option<Output> {
 169        if let Some((position, size)) = self.position.zip(self.size) {
 170            let scale = self.scale.unwrap_or(1);
 171            Some(Output {
 172                name: self.name.clone(),
 173                scale,
 174                bounds: Bounds::new(position, size),
 175            })
 176        } else {
 177            None
 178        }
 179    }
 180}
 181
 182#[derive(Debug, Clone, Eq, PartialEq, Hash)]
 183pub struct Output {
 184    pub name: Option<String>,
 185    pub scale: i32,
 186    pub bounds: Bounds<DevicePixels>,
 187}
 188
 189pub(crate) struct WaylandClientState {
 190    serial_tracker: SerialTracker,
 191    globals: Globals,
 192    gpu_context: BladeContext,
 193    wl_seat: wl_seat::WlSeat, // TODO: Multi seat support
 194    wl_pointer: Option<wl_pointer::WlPointer>,
 195    wl_keyboard: Option<wl_keyboard::WlKeyboard>,
 196    cursor_shape_device: Option<wp_cursor_shape_device_v1::WpCursorShapeDeviceV1>,
 197    data_device: Option<wl_data_device::WlDataDevice>,
 198    primary_selection: Option<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1>,
 199    text_input: Option<zwp_text_input_v3::ZwpTextInputV3>,
 200    pre_edit_text: Option<String>,
 201    ime_pre_edit: Option<String>,
 202    composing: bool,
 203    // Surface to Window mapping
 204    windows: HashMap<ObjectId, WaylandWindowStatePtr>,
 205    // Output to scale mapping
 206    outputs: HashMap<ObjectId, Output>,
 207    in_progress_outputs: HashMap<ObjectId, InProgressOutput>,
 208    keymap_state: Option<xkb::State>,
 209    compose_state: Option<xkb::compose::State>,
 210    drag: DragState,
 211    click: ClickState,
 212    repeat: KeyRepeat,
 213    pub modifiers: Modifiers,
 214    axis_source: AxisSource,
 215    pub mouse_location: Option<Point<Pixels>>,
 216    continuous_scroll_delta: Option<Point<Pixels>>,
 217    discrete_scroll_delta: Option<Point<f32>>,
 218    vertical_modifier: f32,
 219    horizontal_modifier: f32,
 220    scroll_event_received: bool,
 221    enter_token: Option<()>,
 222    button_pressed: Option<MouseButton>,
 223    mouse_focused_window: Option<WaylandWindowStatePtr>,
 224    keyboard_focused_window: Option<WaylandWindowStatePtr>,
 225    loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
 226    cursor_style: Option<CursorStyle>,
 227    clipboard: Clipboard,
 228    data_offers: Vec<DataOffer<WlDataOffer>>,
 229    primary_data_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>,
 230    cursor: Cursor,
 231    pending_activation: Option<PendingActivation>,
 232    event_loop: Option<EventLoop<'static, WaylandClientStatePtr>>,
 233    common: LinuxCommon,
 234}
 235
 236pub struct DragState {
 237    data_offer: Option<wl_data_offer::WlDataOffer>,
 238    window: Option<WaylandWindowStatePtr>,
 239    position: Point<Pixels>,
 240}
 241
 242pub struct ClickState {
 243    last_mouse_button: Option<MouseButton>,
 244    last_click: Instant,
 245    last_location: Point<Pixels>,
 246    current_count: usize,
 247}
 248
 249pub(crate) struct KeyRepeat {
 250    characters_per_second: u32,
 251    delay: Duration,
 252    current_id: u64,
 253    current_keycode: Option<xkb::Keycode>,
 254}
 255
 256pub(crate) enum PendingActivation {
 257    /// URI to open in the web browser.
 258    Uri(String),
 259    /// Path to open in the file explorer.
 260    Path(PathBuf),
 261    /// A window from ourselves to raise.
 262    Window(ObjectId),
 263}
 264
 265/// This struct is required to conform to Rust's orphan rules, so we can dispatch on the state but hand the
 266/// window to GPUI.
 267#[derive(Clone)]
 268pub struct WaylandClientStatePtr(Weak<RefCell<WaylandClientState>>);
 269
 270impl WaylandClientStatePtr {
 271    pub fn get_client(&self) -> Rc<RefCell<WaylandClientState>> {
 272        self.0
 273            .upgrade()
 274            .expect("The pointer should always be valid when dispatching in wayland")
 275    }
 276
 277    pub fn get_serial(&self, kind: SerialKind) -> u32 {
 278        self.0.upgrade().unwrap().borrow().serial_tracker.get(kind)
 279    }
 280
 281    pub fn set_pending_activation(&self, window: ObjectId) {
 282        self.0.upgrade().unwrap().borrow_mut().pending_activation =
 283            Some(PendingActivation::Window(window));
 284    }
 285
 286    pub fn enable_ime(&self) {
 287        let client = self.get_client();
 288        let mut state = client.borrow_mut();
 289        let Some(mut text_input) = state.text_input.take() else {
 290            return;
 291        };
 292
 293        text_input.enable();
 294        text_input.set_content_type(ContentHint::None, ContentPurpose::Normal);
 295        if let Some(window) = state.keyboard_focused_window.clone() {
 296            drop(state);
 297            if let Some(area) = window.get_ime_area() {
 298                text_input.set_cursor_rectangle(
 299                    area.origin.x.0 as i32,
 300                    area.origin.y.0 as i32,
 301                    area.size.width.0 as i32,
 302                    area.size.height.0 as i32,
 303                );
 304            }
 305            state = client.borrow_mut();
 306        }
 307        text_input.commit();
 308        state.text_input = Some(text_input);
 309    }
 310
 311    pub fn disable_ime(&self) {
 312        let client = self.get_client();
 313        let mut state = client.borrow_mut();
 314        state.composing = false;
 315        if let Some(text_input) = &state.text_input {
 316            text_input.disable();
 317            text_input.commit();
 318        }
 319    }
 320
 321    pub fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
 322        let client = self.get_client();
 323        let mut state = client.borrow_mut();
 324        if state.composing || state.text_input.is_none() || state.pre_edit_text.is_some() {
 325            return;
 326        }
 327
 328        let text_input = state.text_input.as_ref().unwrap();
 329        text_input.set_cursor_rectangle(
 330            bounds.origin.x.0 as i32,
 331            bounds.origin.y.0 as i32,
 332            bounds.size.width.0 as i32,
 333            bounds.size.height.0 as i32,
 334        );
 335        text_input.commit();
 336    }
 337
 338    pub fn drop_window(&self, surface_id: &ObjectId) {
 339        let mut client = self.get_client();
 340        let mut state = client.borrow_mut();
 341        let closed_window = state.windows.remove(surface_id).unwrap();
 342        if let Some(window) = state.mouse_focused_window.take() {
 343            if !window.ptr_eq(&closed_window) {
 344                state.mouse_focused_window = Some(window);
 345            }
 346        }
 347        if let Some(window) = state.keyboard_focused_window.take() {
 348            if !window.ptr_eq(&closed_window) {
 349                state.keyboard_focused_window = Some(window);
 350            }
 351        }
 352        if state.windows.is_empty() {
 353            state.common.signal.stop();
 354        }
 355    }
 356}
 357
 358#[derive(Clone)]
 359pub struct WaylandClient(Rc<RefCell<WaylandClientState>>);
 360
 361impl Drop for WaylandClient {
 362    fn drop(&mut self) {
 363        let mut state = self.0.borrow_mut();
 364        state.windows.clear();
 365
 366        if let Some(wl_pointer) = &state.wl_pointer {
 367            wl_pointer.release();
 368        }
 369        if let Some(cursor_shape_device) = &state.cursor_shape_device {
 370            cursor_shape_device.destroy();
 371        }
 372        if let Some(data_device) = &state.data_device {
 373            data_device.release();
 374        }
 375        if let Some(text_input) = &state.text_input {
 376            text_input.destroy();
 377        }
 378    }
 379}
 380
 381const WL_DATA_DEVICE_MANAGER_VERSION: u32 = 3;
 382
 383fn wl_seat_version(version: u32) -> u32 {
 384    // We rely on the wl_pointer.frame event
 385    const WL_SEAT_MIN_VERSION: u32 = 5;
 386    const WL_SEAT_MAX_VERSION: u32 = 9;
 387
 388    if version < WL_SEAT_MIN_VERSION {
 389        panic!(
 390            "wl_seat below required version: {} < {}",
 391            version, WL_SEAT_MIN_VERSION
 392        );
 393    }
 394
 395    version.clamp(WL_SEAT_MIN_VERSION, WL_SEAT_MAX_VERSION)
 396}
 397
 398fn wl_output_version(version: u32) -> u32 {
 399    const WL_OUTPUT_MIN_VERSION: u32 = 2;
 400    const WL_OUTPUT_MAX_VERSION: u32 = 4;
 401
 402    if version < WL_OUTPUT_MIN_VERSION {
 403        panic!(
 404            "wl_output below required version: {} < {}",
 405            version, WL_OUTPUT_MIN_VERSION
 406        );
 407    }
 408
 409    version.clamp(WL_OUTPUT_MIN_VERSION, WL_OUTPUT_MAX_VERSION)
 410}
 411
 412impl WaylandClient {
 413    pub(crate) fn new() -> Self {
 414        let conn = Connection::connect_to_env().unwrap();
 415
 416        let (globals, mut event_queue) =
 417            registry_queue_init::<WaylandClientStatePtr>(&conn).unwrap();
 418        let qh = event_queue.handle();
 419
 420        let mut seat: Option<wl_seat::WlSeat> = None;
 421        #[allow(clippy::mutable_key_type)]
 422        let mut in_progress_outputs = HashMap::default();
 423        globals.contents().with_list(|list| {
 424            for global in list {
 425                match &global.interface[..] {
 426                    "wl_seat" => {
 427                        seat = Some(globals.registry().bind::<wl_seat::WlSeat, _, _>(
 428                            global.name,
 429                            wl_seat_version(global.version),
 430                            &qh,
 431                            (),
 432                        ));
 433                    }
 434                    "wl_output" => {
 435                        let output = globals.registry().bind::<wl_output::WlOutput, _, _>(
 436                            global.name,
 437                            wl_output_version(global.version),
 438                            &qh,
 439                            (),
 440                        );
 441                        in_progress_outputs.insert(output.id(), InProgressOutput::default());
 442                    }
 443                    _ => {}
 444                }
 445            }
 446        });
 447
 448        let event_loop = EventLoop::<WaylandClientStatePtr>::try_new().unwrap();
 449
 450        let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
 451
 452        let handle = event_loop.handle();
 453        handle
 454            .insert_source(main_receiver, {
 455                let handle = handle.clone();
 456                move |event, _, _: &mut WaylandClientStatePtr| {
 457                    if let calloop::channel::Event::Msg(runnable) = event {
 458                        handle.insert_idle(|_| {
 459                            runnable.run();
 460                        });
 461                    }
 462                }
 463            })
 464            .unwrap();
 465
 466        let gpu_context = BladeContext::new().expect("Unable to init GPU context");
 467
 468        let seat = seat.unwrap();
 469        let globals = Globals::new(
 470            globals,
 471            common.foreground_executor.clone(),
 472            qh.clone(),
 473            seat.clone(),
 474        );
 475
 476        let data_device = globals
 477            .data_device_manager
 478            .as_ref()
 479            .map(|data_device_manager| data_device_manager.get_data_device(&seat, &qh, ()));
 480
 481        let primary_selection = globals
 482            .primary_selection_manager
 483            .as_ref()
 484            .map(|primary_selection_manager| primary_selection_manager.get_device(&seat, &qh, ()));
 485
 486        let mut cursor = Cursor::new(&conn, &globals, 24);
 487
 488        handle
 489            .insert_source(XDPEventSource::new(&common.background_executor), {
 490                move |event, _, client| match event {
 491                    XDPEvent::WindowAppearance(appearance) => {
 492                        if let Some(client) = client.0.upgrade() {
 493                            let mut client = client.borrow_mut();
 494
 495                            client.common.appearance = appearance;
 496
 497                            for (_, window) in &mut client.windows {
 498                                window.set_appearance(appearance);
 499                            }
 500                        }
 501                    }
 502                    XDPEvent::CursorTheme(theme) => {
 503                        if let Some(client) = client.0.upgrade() {
 504                            let mut client = client.borrow_mut();
 505                            client.cursor.set_theme(theme.as_str());
 506                        }
 507                    }
 508                    XDPEvent::CursorSize(size) => {
 509                        if let Some(client) = client.0.upgrade() {
 510                            let mut client = client.borrow_mut();
 511                            client.cursor.set_size(size);
 512                        }
 513                    }
 514                }
 515            })
 516            .unwrap();
 517
 518        let mut state = Rc::new(RefCell::new(WaylandClientState {
 519            serial_tracker: SerialTracker::new(),
 520            globals,
 521            gpu_context,
 522            wl_seat: seat,
 523            wl_pointer: None,
 524            wl_keyboard: None,
 525            cursor_shape_device: None,
 526            data_device,
 527            primary_selection,
 528            text_input: None,
 529            pre_edit_text: None,
 530            ime_pre_edit: None,
 531            composing: false,
 532            outputs: HashMap::default(),
 533            in_progress_outputs,
 534            windows: HashMap::default(),
 535            common,
 536            keymap_state: None,
 537            compose_state: None,
 538            drag: DragState {
 539                data_offer: None,
 540                window: None,
 541                position: Point::default(),
 542            },
 543            click: ClickState {
 544                last_click: Instant::now(),
 545                last_mouse_button: None,
 546                last_location: Point::default(),
 547                current_count: 0,
 548            },
 549            repeat: KeyRepeat {
 550                characters_per_second: 16,
 551                delay: Duration::from_millis(500),
 552                current_id: 0,
 553                current_keycode: None,
 554            },
 555            modifiers: Modifiers {
 556                shift: false,
 557                control: false,
 558                alt: false,
 559                function: false,
 560                platform: false,
 561            },
 562            scroll_event_received: false,
 563            axis_source: AxisSource::Wheel,
 564            mouse_location: None,
 565            continuous_scroll_delta: None,
 566            discrete_scroll_delta: None,
 567            vertical_modifier: -1.0,
 568            horizontal_modifier: -1.0,
 569            button_pressed: None,
 570            mouse_focused_window: None,
 571            keyboard_focused_window: None,
 572            loop_handle: handle.clone(),
 573            enter_token: None,
 574            cursor_style: None,
 575            clipboard: Clipboard::new(conn.clone(), handle.clone()),
 576            data_offers: Vec::new(),
 577            primary_data_offer: None,
 578            cursor,
 579            pending_activation: None,
 580            event_loop: Some(event_loop),
 581        }));
 582
 583        WaylandSource::new(conn, event_queue)
 584            .insert(handle)
 585            .unwrap();
 586
 587        Self(state)
 588    }
 589}
 590
 591impl LinuxClient for WaylandClient {
 592    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 593        let state = self.0.borrow();
 594        let id = if let Some(keymap_state) = &state.keymap_state {
 595            let layout_idx = keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
 596            keymap_state
 597                .get_keymap()
 598                .layout_get_name(layout_idx)
 599                .to_string()
 600        } else {
 601            "unknown".to_string()
 602        };
 603        Box::new(LinuxKeyboardLayout::new(id))
 604    }
 605
 606    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 607        self.0
 608            .borrow()
 609            .outputs
 610            .iter()
 611            .map(|(id, output)| {
 612                Rc::new(WaylandDisplay {
 613                    id: id.clone(),
 614                    name: output.name.clone(),
 615                    bounds: output.bounds.to_pixels(output.scale as f32),
 616                }) as Rc<dyn PlatformDisplay>
 617            })
 618            .collect()
 619    }
 620
 621    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 622        self.0
 623            .borrow()
 624            .outputs
 625            .iter()
 626            .find_map(|(object_id, output)| {
 627                (object_id.protocol_id() == id.0).then(|| {
 628                    Rc::new(WaylandDisplay {
 629                        id: object_id.clone(),
 630                        name: output.name.clone(),
 631                        bounds: output.bounds.to_pixels(output.scale as f32),
 632                    }) as Rc<dyn PlatformDisplay>
 633                })
 634            })
 635    }
 636
 637    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 638        None
 639    }
 640
 641    fn is_screen_capture_supported(&self) -> bool {
 642        false
 643    }
 644
 645    fn screen_capture_sources(
 646        &self,
 647    ) -> oneshot::Receiver<anyhow::Result<Vec<Box<dyn ScreenCaptureSource>>>> {
 648        // TODO: Get screen capture working on wayland. Be sure to try window resizing as that may
 649        // be tricky.
 650        //
 651        // start_scap_default_target_source()
 652        let (sources_tx, sources_rx) = oneshot::channel();
 653        sources_tx
 654            .send(Err(anyhow!("Wayland screen capture not yet implemented.")))
 655            .ok();
 656        sources_rx
 657    }
 658
 659    fn open_window(
 660        &self,
 661        handle: AnyWindowHandle,
 662        params: WindowParams,
 663    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
 664        let mut state = self.0.borrow_mut();
 665
 666        let (window, surface_id) = WaylandWindow::new(
 667            handle,
 668            state.globals.clone(),
 669            &state.gpu_context,
 670            WaylandClientStatePtr(Rc::downgrade(&self.0)),
 671            params,
 672            state.common.appearance,
 673        )?;
 674        state.windows.insert(surface_id, window.0.clone());
 675
 676        Ok(Box::new(window))
 677    }
 678
 679    fn set_cursor_style(&self, style: CursorStyle) {
 680        let mut state = self.0.borrow_mut();
 681
 682        let need_update = state
 683            .cursor_style
 684            .map_or(true, |current_style| current_style != style);
 685
 686        if need_update {
 687            let serial = state.serial_tracker.get(SerialKind::MouseEnter);
 688            state.cursor_style = Some(style);
 689
 690            if let CursorStyle::None = style {
 691                let wl_pointer = state
 692                    .wl_pointer
 693                    .clone()
 694                    .expect("window is focused by pointer");
 695                wl_pointer.set_cursor(serial, None, 0, 0);
 696            } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
 697                cursor_shape_device.set_shape(serial, style.to_shape());
 698            } else if let Some(focused_window) = &state.mouse_focused_window {
 699                // cursor-shape-v1 isn't supported, set the cursor using a surface.
 700                let wl_pointer = state
 701                    .wl_pointer
 702                    .clone()
 703                    .expect("window is focused by pointer");
 704                let scale = focused_window.primary_output_scale();
 705                state
 706                    .cursor
 707                    .set_icon(&wl_pointer, serial, style.to_icon_name(), scale);
 708            }
 709        }
 710    }
 711
 712    fn open_uri(&self, uri: &str) {
 713        let mut state = self.0.borrow_mut();
 714        if let (Some(activation), Some(window)) = (
 715            state.globals.activation.clone(),
 716            state.mouse_focused_window.clone(),
 717        ) {
 718            state.pending_activation = Some(PendingActivation::Uri(uri.to_string()));
 719            let token = activation.get_activation_token(&state.globals.qh, ());
 720            let serial = state.serial_tracker.get(SerialKind::MousePress);
 721            token.set_serial(serial, &state.wl_seat);
 722            token.set_surface(&window.surface());
 723            token.commit();
 724        } else {
 725            let executor = state.common.background_executor.clone();
 726            open_uri_internal(executor, uri, None);
 727        }
 728    }
 729
 730    fn reveal_path(&self, path: PathBuf) {
 731        let mut state = self.0.borrow_mut();
 732        if let (Some(activation), Some(window)) = (
 733            state.globals.activation.clone(),
 734            state.mouse_focused_window.clone(),
 735        ) {
 736            state.pending_activation = Some(PendingActivation::Path(path));
 737            let token = activation.get_activation_token(&state.globals.qh, ());
 738            let serial = state.serial_tracker.get(SerialKind::MousePress);
 739            token.set_serial(serial, &state.wl_seat);
 740            token.set_surface(&window.surface());
 741            token.commit();
 742        } else {
 743            let executor = state.common.background_executor.clone();
 744            reveal_path_internal(executor, path, None);
 745        }
 746    }
 747
 748    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
 749        f(&mut self.0.borrow_mut().common)
 750    }
 751
 752    fn run(&self) {
 753        let mut event_loop = self
 754            .0
 755            .borrow_mut()
 756            .event_loop
 757            .take()
 758            .expect("App is already running");
 759
 760        event_loop
 761            .run(
 762                None,
 763                &mut WaylandClientStatePtr(Rc::downgrade(&self.0)),
 764                |_| {},
 765            )
 766            .log_err();
 767    }
 768
 769    fn write_to_primary(&self, item: crate::ClipboardItem) {
 770        let mut state = self.0.borrow_mut();
 771        let (Some(primary_selection_manager), Some(primary_selection)) = (
 772            state.globals.primary_selection_manager.clone(),
 773            state.primary_selection.clone(),
 774        ) else {
 775            return;
 776        };
 777        if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
 778            state.clipboard.set_primary(item);
 779            let serial = state.serial_tracker.get(SerialKind::KeyPress);
 780            let data_source = primary_selection_manager.create_source(&state.globals.qh, ());
 781            data_source.offer(state.clipboard.self_mime());
 782            data_source.offer(TEXT_MIME_TYPE.to_string());
 783            primary_selection.set_selection(Some(&data_source), serial);
 784        }
 785    }
 786
 787    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
 788        let mut state = self.0.borrow_mut();
 789        let (Some(data_device_manager), Some(data_device)) = (
 790            state.globals.data_device_manager.clone(),
 791            state.data_device.clone(),
 792        ) else {
 793            return;
 794        };
 795        if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
 796            state.clipboard.set(item);
 797            let serial = state.serial_tracker.get(SerialKind::KeyPress);
 798            let data_source = data_device_manager.create_data_source(&state.globals.qh, ());
 799            data_source.offer(state.clipboard.self_mime());
 800            data_source.offer(TEXT_MIME_TYPE.to_string());
 801            data_device.set_selection(Some(&data_source), serial);
 802        }
 803    }
 804
 805    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
 806        self.0.borrow_mut().clipboard.read_primary()
 807    }
 808
 809    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
 810        self.0.borrow_mut().clipboard.read()
 811    }
 812
 813    fn active_window(&self) -> Option<AnyWindowHandle> {
 814        self.0
 815            .borrow_mut()
 816            .keyboard_focused_window
 817            .as_ref()
 818            .map(|window| window.handle())
 819    }
 820
 821    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 822        None
 823    }
 824
 825    fn compositor_name(&self) -> &'static str {
 826        "Wayland"
 827    }
 828}
 829
 830impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStatePtr {
 831    fn event(
 832        this: &mut Self,
 833        registry: &wl_registry::WlRegistry,
 834        event: wl_registry::Event,
 835        _: &GlobalListContents,
 836        _: &Connection,
 837        qh: &QueueHandle<Self>,
 838    ) {
 839        let mut client = this.get_client();
 840        let mut state = client.borrow_mut();
 841
 842        match event {
 843            wl_registry::Event::Global {
 844                name,
 845                interface,
 846                version,
 847            } => match &interface[..] {
 848                "wl_seat" => {
 849                    if let Some(wl_pointer) = state.wl_pointer.take() {
 850                        wl_pointer.release();
 851                    }
 852                    if let Some(wl_keyboard) = state.wl_keyboard.take() {
 853                        wl_keyboard.release();
 854                    }
 855                    state.wl_seat.release();
 856                    state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(
 857                        name,
 858                        wl_seat_version(version),
 859                        qh,
 860                        (),
 861                    );
 862                }
 863                "wl_output" => {
 864                    let output = registry.bind::<wl_output::WlOutput, _, _>(
 865                        name,
 866                        wl_output_version(version),
 867                        qh,
 868                        (),
 869                    );
 870
 871                    state
 872                        .in_progress_outputs
 873                        .insert(output.id(), InProgressOutput::default());
 874                }
 875                _ => {}
 876            },
 877            wl_registry::Event::GlobalRemove { name: _ } => {
 878                // TODO: handle global removal
 879            }
 880            _ => {}
 881        }
 882    }
 883}
 884
 885delegate_noop!(WaylandClientStatePtr: ignore xdg_activation_v1::XdgActivationV1);
 886delegate_noop!(WaylandClientStatePtr: ignore wl_compositor::WlCompositor);
 887delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_device_v1::WpCursorShapeDeviceV1);
 888delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_manager_v1::WpCursorShapeManagerV1);
 889delegate_noop!(WaylandClientStatePtr: ignore wl_data_device_manager::WlDataDeviceManager);
 890delegate_noop!(WaylandClientStatePtr: ignore zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1);
 891delegate_noop!(WaylandClientStatePtr: ignore wl_shm::WlShm);
 892delegate_noop!(WaylandClientStatePtr: ignore wl_shm_pool::WlShmPool);
 893delegate_noop!(WaylandClientStatePtr: ignore wl_buffer::WlBuffer);
 894delegate_noop!(WaylandClientStatePtr: ignore wl_region::WlRegion);
 895delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
 896delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
 897delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur_manager::OrgKdeKwinBlurManager);
 898delegate_noop!(WaylandClientStatePtr: ignore zwp_text_input_manager_v3::ZwpTextInputManagerV3);
 899delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur::OrgKdeKwinBlur);
 900delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
 901delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
 902
 903impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
 904    fn event(
 905        state: &mut WaylandClientStatePtr,
 906        _: &wl_callback::WlCallback,
 907        event: wl_callback::Event,
 908        surface_id: &ObjectId,
 909        _: &Connection,
 910        _: &QueueHandle<Self>,
 911    ) {
 912        let client = state.get_client();
 913        let mut state = client.borrow_mut();
 914        let Some(window) = get_window(&mut state, surface_id) else {
 915            return;
 916        };
 917        drop(state);
 918
 919        match event {
 920            wl_callback::Event::Done { .. } => {
 921                window.frame();
 922            }
 923            _ => {}
 924        }
 925    }
 926}
 927
 928fn get_window(
 929    mut state: &mut RefMut<WaylandClientState>,
 930    surface_id: &ObjectId,
 931) -> Option<WaylandWindowStatePtr> {
 932    state.windows.get(surface_id).cloned()
 933}
 934
 935impl Dispatch<wl_surface::WlSurface, ()> for WaylandClientStatePtr {
 936    fn event(
 937        this: &mut Self,
 938        surface: &wl_surface::WlSurface,
 939        event: <wl_surface::WlSurface as Proxy>::Event,
 940        _: &(),
 941        _: &Connection,
 942        _: &QueueHandle<Self>,
 943    ) {
 944        let mut client = this.get_client();
 945        let mut state = client.borrow_mut();
 946
 947        let Some(window) = get_window(&mut state, &surface.id()) else {
 948            return;
 949        };
 950        #[allow(clippy::mutable_key_type)]
 951        let outputs = state.outputs.clone();
 952        drop(state);
 953
 954        window.handle_surface_event(event, outputs);
 955    }
 956}
 957
 958impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
 959    fn event(
 960        this: &mut Self,
 961        output: &wl_output::WlOutput,
 962        event: <wl_output::WlOutput as Proxy>::Event,
 963        _: &(),
 964        _: &Connection,
 965        _: &QueueHandle<Self>,
 966    ) {
 967        let mut client = this.get_client();
 968        let mut state = client.borrow_mut();
 969
 970        let Some(mut in_progress_output) = state.in_progress_outputs.get_mut(&output.id()) else {
 971            return;
 972        };
 973
 974        match event {
 975            wl_output::Event::Name { name } => {
 976                in_progress_output.name = Some(name);
 977            }
 978            wl_output::Event::Scale { factor } => {
 979                in_progress_output.scale = Some(factor);
 980            }
 981            wl_output::Event::Geometry { x, y, .. } => {
 982                in_progress_output.position = Some(point(DevicePixels(x), DevicePixels(y)))
 983            }
 984            wl_output::Event::Mode { width, height, .. } => {
 985                in_progress_output.size = Some(size(DevicePixels(width), DevicePixels(height)))
 986            }
 987            wl_output::Event::Done => {
 988                if let Some(complete) = in_progress_output.complete() {
 989                    state.outputs.insert(output.id(), complete);
 990                }
 991                state.in_progress_outputs.remove(&output.id());
 992            }
 993            _ => {}
 994        }
 995    }
 996}
 997
 998impl Dispatch<xdg_surface::XdgSurface, ObjectId> for WaylandClientStatePtr {
 999    fn event(
1000        state: &mut Self,
1001        _: &xdg_surface::XdgSurface,
1002        event: xdg_surface::Event,
1003        surface_id: &ObjectId,
1004        _: &Connection,
1005        _: &QueueHandle<Self>,
1006    ) {
1007        let client = state.get_client();
1008        let mut state = client.borrow_mut();
1009        let Some(window) = get_window(&mut state, surface_id) else {
1010            return;
1011        };
1012        drop(state);
1013        window.handle_xdg_surface_event(event);
1014    }
1015}
1016
1017impl Dispatch<xdg_toplevel::XdgToplevel, ObjectId> for WaylandClientStatePtr {
1018    fn event(
1019        this: &mut Self,
1020        _: &xdg_toplevel::XdgToplevel,
1021        event: <xdg_toplevel::XdgToplevel as Proxy>::Event,
1022        surface_id: &ObjectId,
1023        _: &Connection,
1024        _: &QueueHandle<Self>,
1025    ) {
1026        let client = this.get_client();
1027        let mut state = client.borrow_mut();
1028        let Some(window) = get_window(&mut state, surface_id) else {
1029            return;
1030        };
1031
1032        drop(state);
1033        let should_close = window.handle_toplevel_event(event);
1034
1035        if should_close {
1036            // The close logic will be handled in drop_window()
1037            window.close();
1038        }
1039    }
1040}
1041
1042impl Dispatch<xdg_wm_base::XdgWmBase, ()> for WaylandClientStatePtr {
1043    fn event(
1044        _: &mut Self,
1045        wm_base: &xdg_wm_base::XdgWmBase,
1046        event: <xdg_wm_base::XdgWmBase as Proxy>::Event,
1047        _: &(),
1048        _: &Connection,
1049        _: &QueueHandle<Self>,
1050    ) {
1051        if let xdg_wm_base::Event::Ping { serial } = event {
1052            wm_base.pong(serial);
1053        }
1054    }
1055}
1056
1057impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClientStatePtr {
1058    fn event(
1059        this: &mut Self,
1060        token: &xdg_activation_token_v1::XdgActivationTokenV1,
1061        event: <xdg_activation_token_v1::XdgActivationTokenV1 as Proxy>::Event,
1062        _: &(),
1063        _: &Connection,
1064        _: &QueueHandle<Self>,
1065    ) {
1066        let client = this.get_client();
1067        let mut state = client.borrow_mut();
1068
1069        if let xdg_activation_token_v1::Event::Done { token } = event {
1070            let executor = state.common.background_executor.clone();
1071            match state.pending_activation.take() {
1072                Some(PendingActivation::Uri(uri)) => open_uri_internal(executor, &uri, Some(token)),
1073                Some(PendingActivation::Path(path)) => {
1074                    reveal_path_internal(executor, path, Some(token))
1075                }
1076                Some(PendingActivation::Window(window)) => {
1077                    let Some(window) = get_window(&mut state, &window) else {
1078                        return;
1079                    };
1080                    let activation = state.globals.activation.as_ref().unwrap();
1081                    activation.activate(token, &window.surface());
1082                }
1083                None => log::error!("activation token received with no pending activation"),
1084            }
1085        }
1086
1087        token.destroy();
1088    }
1089}
1090
1091impl Dispatch<wl_seat::WlSeat, ()> for WaylandClientStatePtr {
1092    fn event(
1093        state: &mut Self,
1094        seat: &wl_seat::WlSeat,
1095        event: wl_seat::Event,
1096        _: &(),
1097        _: &Connection,
1098        qh: &QueueHandle<Self>,
1099    ) {
1100        if let wl_seat::Event::Capabilities {
1101            capabilities: WEnum::Value(capabilities),
1102        } = event
1103        {
1104            let client = state.get_client();
1105            let mut state = client.borrow_mut();
1106            if capabilities.contains(wl_seat::Capability::Keyboard) {
1107                let keyboard = seat.get_keyboard(qh, ());
1108
1109                state.text_input = state
1110                    .globals
1111                    .text_input_manager
1112                    .as_ref()
1113                    .map(|text_input_manager| text_input_manager.get_text_input(&seat, qh, ()));
1114
1115                if let Some(wl_keyboard) = &state.wl_keyboard {
1116                    wl_keyboard.release();
1117                }
1118
1119                state.wl_keyboard = Some(keyboard);
1120            }
1121            if capabilities.contains(wl_seat::Capability::Pointer) {
1122                let pointer = seat.get_pointer(qh, ());
1123                state.cursor_shape_device = state
1124                    .globals
1125                    .cursor_shape_manager
1126                    .as_ref()
1127                    .map(|cursor_shape_manager| cursor_shape_manager.get_pointer(&pointer, qh, ()));
1128
1129                if let Some(wl_pointer) = &state.wl_pointer {
1130                    wl_pointer.release();
1131                }
1132
1133                state.wl_pointer = Some(pointer);
1134            }
1135        }
1136    }
1137}
1138
1139impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
1140    fn event(
1141        this: &mut Self,
1142        _: &wl_keyboard::WlKeyboard,
1143        event: wl_keyboard::Event,
1144        _: &(),
1145        _: &Connection,
1146        _: &QueueHandle<Self>,
1147    ) {
1148        let mut client = this.get_client();
1149        let mut state = client.borrow_mut();
1150        match event {
1151            wl_keyboard::Event::RepeatInfo { rate, delay } => {
1152                state.repeat.characters_per_second = rate as u32;
1153                state.repeat.delay = Duration::from_millis(delay as u64);
1154            }
1155            wl_keyboard::Event::Keymap {
1156                format: WEnum::Value(format),
1157                fd,
1158                size,
1159                ..
1160            } => {
1161                if format != wl_keyboard::KeymapFormat::XkbV1 {
1162                    log::error!("Received keymap format {:?}, expected XkbV1", format);
1163                    return;
1164                }
1165                let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
1166                let keymap = unsafe {
1167                    xkb::Keymap::new_from_fd(
1168                        &xkb_context,
1169                        fd,
1170                        size as usize,
1171                        XKB_KEYMAP_FORMAT_TEXT_V1,
1172                        KEYMAP_COMPILE_NO_FLAGS,
1173                    )
1174                    .log_err()
1175                    .flatten()
1176                    .expect("Failed to create keymap")
1177                };
1178                state.keymap_state = Some(xkb::State::new(&keymap));
1179                state.compose_state = get_xkb_compose_state(&xkb_context);
1180
1181                if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1182                    drop(state);
1183                    callback();
1184                    state = client.borrow_mut();
1185                    state.common.callbacks.keyboard_layout_change = Some(callback);
1186                }
1187            }
1188            wl_keyboard::Event::Enter { surface, .. } => {
1189                state.keyboard_focused_window = get_window(&mut state, &surface.id());
1190                state.enter_token = Some(());
1191
1192                if let Some(window) = state.keyboard_focused_window.clone() {
1193                    drop(state);
1194                    window.set_focused(true);
1195                }
1196            }
1197            wl_keyboard::Event::Leave { surface, .. } => {
1198                let keyboard_focused_window = get_window(&mut state, &surface.id());
1199                state.keyboard_focused_window = None;
1200                state.enter_token.take();
1201                // Prevent keyboard events from repeating after opening e.g. a file chooser and closing it quickly
1202                state.repeat.current_id += 1;
1203
1204                if let Some(window) = keyboard_focused_window {
1205                    if let Some(ref mut compose) = state.compose_state {
1206                        compose.reset();
1207                    }
1208                    state.pre_edit_text.take();
1209                    drop(state);
1210                    window.handle_ime(ImeInput::DeleteText);
1211                    window.set_focused(false);
1212                }
1213            }
1214            wl_keyboard::Event::Modifiers {
1215                mods_depressed,
1216                mods_latched,
1217                mods_locked,
1218                group,
1219                ..
1220            } => {
1221                let focused_window = state.keyboard_focused_window.clone();
1222
1223                let keymap_state = state.keymap_state.as_mut().unwrap();
1224                let old_layout =
1225                    keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
1226                keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1227                state.modifiers = Modifiers::from_xkb(keymap_state);
1228
1229                if group != old_layout {
1230                    if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take()
1231                    {
1232                        drop(state);
1233                        callback();
1234                        state = client.borrow_mut();
1235                        state.common.callbacks.keyboard_layout_change = Some(callback);
1236                    }
1237                }
1238
1239                let Some(focused_window) = focused_window else {
1240                    return;
1241                };
1242
1243                let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1244                    modifiers: state.modifiers,
1245                });
1246
1247                drop(state);
1248                focused_window.handle_input(input);
1249            }
1250            wl_keyboard::Event::Key {
1251                serial,
1252                key,
1253                state: WEnum::Value(key_state),
1254                ..
1255            } => {
1256                state.serial_tracker.update(SerialKind::KeyPress, serial);
1257
1258                let focused_window = state.keyboard_focused_window.clone();
1259                let Some(focused_window) = focused_window else {
1260                    return;
1261                };
1262                let focused_window = focused_window.clone();
1263
1264                let keymap_state = state.keymap_state.as_ref().unwrap();
1265                let keycode = Keycode::from(key + MIN_KEYCODE);
1266                let keysym = keymap_state.key_get_one_sym(keycode);
1267
1268                match key_state {
1269                    wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1270                        let mut keystroke =
1271                            Keystroke::from_xkb(&keymap_state, state.modifiers, keycode);
1272                        if let Some(mut compose) = state.compose_state.take() {
1273                            compose.feed(keysym);
1274                            match compose.status() {
1275                                xkb::Status::Composing => {
1276                                    keystroke.key_char = None;
1277                                    state.pre_edit_text =
1278                                        compose.utf8().or(Keystroke::underlying_dead_key(keysym));
1279                                    let pre_edit =
1280                                        state.pre_edit_text.clone().unwrap_or(String::default());
1281                                    drop(state);
1282                                    focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1283                                    state = client.borrow_mut();
1284                                }
1285
1286                                xkb::Status::Composed => {
1287                                    state.pre_edit_text.take();
1288                                    keystroke.key_char = compose.utf8();
1289                                    if let Some(keysym) = compose.keysym() {
1290                                        keystroke.key = xkb::keysym_get_name(keysym);
1291                                    }
1292                                }
1293                                xkb::Status::Cancelled => {
1294                                    let pre_edit = state.pre_edit_text.take();
1295                                    let new_pre_edit = Keystroke::underlying_dead_key(keysym);
1296                                    state.pre_edit_text = new_pre_edit.clone();
1297                                    drop(state);
1298                                    if let Some(pre_edit) = pre_edit {
1299                                        focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1300                                    }
1301                                    if let Some(current_key) = new_pre_edit {
1302                                        focused_window
1303                                            .handle_ime(ImeInput::SetMarkedText(current_key));
1304                                    }
1305                                    compose.feed(keysym);
1306                                    state = client.borrow_mut();
1307                                }
1308                                _ => {}
1309                            }
1310                            state.compose_state = Some(compose);
1311                        }
1312                        let input = PlatformInput::KeyDown(KeyDownEvent {
1313                            keystroke: keystroke.clone(),
1314                            is_held: false,
1315                        });
1316
1317                        state.repeat.current_id += 1;
1318                        state.repeat.current_keycode = Some(keycode);
1319
1320                        let rate = state.repeat.characters_per_second;
1321                        let id = state.repeat.current_id;
1322                        state
1323                            .loop_handle
1324                            .insert_source(Timer::from_duration(state.repeat.delay), {
1325                                let input = PlatformInput::KeyDown(KeyDownEvent {
1326                                    keystroke,
1327                                    is_held: true,
1328                                });
1329                                move |_event, _metadata, this| {
1330                                    let mut client = this.get_client();
1331                                    let mut state = client.borrow_mut();
1332                                    let is_repeating = id == state.repeat.current_id
1333                                        && state.repeat.current_keycode.is_some()
1334                                        && state.keyboard_focused_window.is_some();
1335
1336                                    if !is_repeating || rate == 0 {
1337                                        return TimeoutAction::Drop;
1338                                    }
1339
1340                                    let focused_window =
1341                                        state.keyboard_focused_window.as_ref().unwrap().clone();
1342
1343                                    drop(state);
1344                                    focused_window.handle_input(input.clone());
1345
1346                                    TimeoutAction::ToDuration(Duration::from_secs(1) / rate)
1347                                }
1348                            })
1349                            .unwrap();
1350
1351                        drop(state);
1352                        focused_window.handle_input(input);
1353                    }
1354                    wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1355                        let input = PlatformInput::KeyUp(KeyUpEvent {
1356                            keystroke: Keystroke::from_xkb(keymap_state, state.modifiers, keycode),
1357                        });
1358
1359                        if state.repeat.current_keycode == Some(keycode) {
1360                            state.repeat.current_keycode = None;
1361                        }
1362
1363                        drop(state);
1364                        focused_window.handle_input(input);
1365                    }
1366                    _ => {}
1367                }
1368            }
1369            _ => {}
1370        }
1371    }
1372}
1373impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1374    fn event(
1375        this: &mut Self,
1376        text_input: &zwp_text_input_v3::ZwpTextInputV3,
1377        event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1378        _: &(),
1379        _: &Connection,
1380        _: &QueueHandle<Self>,
1381    ) {
1382        let client = this.get_client();
1383        let mut state = client.borrow_mut();
1384        match event {
1385            zwp_text_input_v3::Event::Enter { .. } => {
1386                drop(state);
1387                this.enable_ime();
1388            }
1389            zwp_text_input_v3::Event::Leave { .. } => {
1390                drop(state);
1391                this.disable_ime();
1392            }
1393            zwp_text_input_v3::Event::CommitString { text } => {
1394                state.composing = false;
1395                let Some(window) = state.keyboard_focused_window.clone() else {
1396                    return;
1397                };
1398
1399                if let Some(commit_text) = text {
1400                    drop(state);
1401                    // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1402                    // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1403                    if commit_text.len() == 1 {
1404                        window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1405                            keystroke: Keystroke {
1406                                modifiers: Modifiers::default(),
1407                                key: commit_text.clone(),
1408                                key_char: Some(commit_text),
1409                            },
1410                            is_held: false,
1411                        }));
1412                    } else {
1413                        window.handle_ime(ImeInput::InsertText(commit_text));
1414                    }
1415                }
1416            }
1417            zwp_text_input_v3::Event::PreeditString { text, .. } => {
1418                state.composing = true;
1419                state.ime_pre_edit = text;
1420            }
1421            zwp_text_input_v3::Event::Done { serial } => {
1422                let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1423                state.serial_tracker.update(SerialKind::InputMethod, serial);
1424                let Some(window) = state.keyboard_focused_window.clone() else {
1425                    return;
1426                };
1427
1428                if let Some(text) = state.ime_pre_edit.take() {
1429                    drop(state);
1430                    window.handle_ime(ImeInput::SetMarkedText(text));
1431                    if let Some(area) = window.get_ime_area() {
1432                        text_input.set_cursor_rectangle(
1433                            area.origin.x.0 as i32,
1434                            area.origin.y.0 as i32,
1435                            area.size.width.0 as i32,
1436                            area.size.height.0 as i32,
1437                        );
1438                        if last_serial == serial {
1439                            text_input.commit();
1440                        }
1441                    }
1442                } else {
1443                    state.composing = false;
1444                    drop(state);
1445                    window.handle_ime(ImeInput::DeleteText);
1446                }
1447            }
1448            _ => {}
1449        }
1450    }
1451}
1452
1453fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1454    // These values are coming from <linux/input-event-codes.h>.
1455    const BTN_LEFT: u32 = 0x110;
1456    const BTN_RIGHT: u32 = 0x111;
1457    const BTN_MIDDLE: u32 = 0x112;
1458    const BTN_SIDE: u32 = 0x113;
1459    const BTN_EXTRA: u32 = 0x114;
1460    const BTN_FORWARD: u32 = 0x115;
1461    const BTN_BACK: u32 = 0x116;
1462
1463    Some(match button {
1464        BTN_LEFT => MouseButton::Left,
1465        BTN_RIGHT => MouseButton::Right,
1466        BTN_MIDDLE => MouseButton::Middle,
1467        BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1468        BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1469        _ => return None,
1470    })
1471}
1472
1473impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1474    fn event(
1475        this: &mut Self,
1476        wl_pointer: &wl_pointer::WlPointer,
1477        event: wl_pointer::Event,
1478        _: &(),
1479        _: &Connection,
1480        _: &QueueHandle<Self>,
1481    ) {
1482        let mut client = this.get_client();
1483        let mut state = client.borrow_mut();
1484
1485        match event {
1486            wl_pointer::Event::Enter {
1487                serial,
1488                surface,
1489                surface_x,
1490                surface_y,
1491                ..
1492            } => {
1493                state.serial_tracker.update(SerialKind::MouseEnter, serial);
1494                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1495                state.button_pressed = None;
1496
1497                if let Some(window) = get_window(&mut state, &surface.id()) {
1498                    state.mouse_focused_window = Some(window.clone());
1499
1500                    if state.enter_token.is_some() {
1501                        state.enter_token = None;
1502                    }
1503                    if let Some(style) = state.cursor_style {
1504                        if let CursorStyle::None = style {
1505                            let wl_pointer = state
1506                                .wl_pointer
1507                                .clone()
1508                                .expect("window is focused by pointer");
1509                            wl_pointer.set_cursor(serial, None, 0, 0);
1510                        } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
1511                            cursor_shape_device.set_shape(serial, style.to_shape());
1512                        } else {
1513                            let scale = window.primary_output_scale();
1514                            state
1515                                .cursor
1516                                .set_icon(&wl_pointer, serial, style.to_icon_name(), scale);
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}