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_TYPES},
  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            for mime_type in TEXT_MIME_TYPES {
 782                data_source.offer(mime_type.to_string());
 783            }
 784            data_source.offer(state.clipboard.self_mime());
 785            primary_selection.set_selection(Some(&data_source), serial);
 786        }
 787    }
 788
 789    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
 790        let mut state = self.0.borrow_mut();
 791        let (Some(data_device_manager), Some(data_device)) = (
 792            state.globals.data_device_manager.clone(),
 793            state.data_device.clone(),
 794        ) else {
 795            return;
 796        };
 797        if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
 798            state.clipboard.set(item);
 799            let serial = state.serial_tracker.get(SerialKind::KeyPress);
 800            let data_source = data_device_manager.create_data_source(&state.globals.qh, ());
 801            for mime_type in TEXT_MIME_TYPES {
 802                data_source.offer(mime_type.to_string());
 803            }
 804            data_source.offer(state.clipboard.self_mime());
 805            data_device.set_selection(Some(&data_source), serial);
 806        }
 807    }
 808
 809    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
 810        self.0.borrow_mut().clipboard.read_primary()
 811    }
 812
 813    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
 814        self.0.borrow_mut().clipboard.read()
 815    }
 816
 817    fn active_window(&self) -> Option<AnyWindowHandle> {
 818        self.0
 819            .borrow_mut()
 820            .keyboard_focused_window
 821            .as_ref()
 822            .map(|window| window.handle())
 823    }
 824
 825    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 826        None
 827    }
 828
 829    fn compositor_name(&self) -> &'static str {
 830        "Wayland"
 831    }
 832}
 833
 834impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStatePtr {
 835    fn event(
 836        this: &mut Self,
 837        registry: &wl_registry::WlRegistry,
 838        event: wl_registry::Event,
 839        _: &GlobalListContents,
 840        _: &Connection,
 841        qh: &QueueHandle<Self>,
 842    ) {
 843        let mut client = this.get_client();
 844        let mut state = client.borrow_mut();
 845
 846        match event {
 847            wl_registry::Event::Global {
 848                name,
 849                interface,
 850                version,
 851            } => match &interface[..] {
 852                "wl_seat" => {
 853                    if let Some(wl_pointer) = state.wl_pointer.take() {
 854                        wl_pointer.release();
 855                    }
 856                    if let Some(wl_keyboard) = state.wl_keyboard.take() {
 857                        wl_keyboard.release();
 858                    }
 859                    state.wl_seat.release();
 860                    state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(
 861                        name,
 862                        wl_seat_version(version),
 863                        qh,
 864                        (),
 865                    );
 866                }
 867                "wl_output" => {
 868                    let output = registry.bind::<wl_output::WlOutput, _, _>(
 869                        name,
 870                        wl_output_version(version),
 871                        qh,
 872                        (),
 873                    );
 874
 875                    state
 876                        .in_progress_outputs
 877                        .insert(output.id(), InProgressOutput::default());
 878                }
 879                _ => {}
 880            },
 881            wl_registry::Event::GlobalRemove { name: _ } => {
 882                // TODO: handle global removal
 883            }
 884            _ => {}
 885        }
 886    }
 887}
 888
 889delegate_noop!(WaylandClientStatePtr: ignore xdg_activation_v1::XdgActivationV1);
 890delegate_noop!(WaylandClientStatePtr: ignore wl_compositor::WlCompositor);
 891delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_device_v1::WpCursorShapeDeviceV1);
 892delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_manager_v1::WpCursorShapeManagerV1);
 893delegate_noop!(WaylandClientStatePtr: ignore wl_data_device_manager::WlDataDeviceManager);
 894delegate_noop!(WaylandClientStatePtr: ignore zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1);
 895delegate_noop!(WaylandClientStatePtr: ignore wl_shm::WlShm);
 896delegate_noop!(WaylandClientStatePtr: ignore wl_shm_pool::WlShmPool);
 897delegate_noop!(WaylandClientStatePtr: ignore wl_buffer::WlBuffer);
 898delegate_noop!(WaylandClientStatePtr: ignore wl_region::WlRegion);
 899delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
 900delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
 901delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur_manager::OrgKdeKwinBlurManager);
 902delegate_noop!(WaylandClientStatePtr: ignore zwp_text_input_manager_v3::ZwpTextInputManagerV3);
 903delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur::OrgKdeKwinBlur);
 904delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
 905delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
 906
 907impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
 908    fn event(
 909        state: &mut WaylandClientStatePtr,
 910        _: &wl_callback::WlCallback,
 911        event: wl_callback::Event,
 912        surface_id: &ObjectId,
 913        _: &Connection,
 914        _: &QueueHandle<Self>,
 915    ) {
 916        let client = state.get_client();
 917        let mut state = client.borrow_mut();
 918        let Some(window) = get_window(&mut state, surface_id) else {
 919            return;
 920        };
 921        drop(state);
 922
 923        match event {
 924            wl_callback::Event::Done { .. } => {
 925                window.frame();
 926            }
 927            _ => {}
 928        }
 929    }
 930}
 931
 932fn get_window(
 933    mut state: &mut RefMut<WaylandClientState>,
 934    surface_id: &ObjectId,
 935) -> Option<WaylandWindowStatePtr> {
 936    state.windows.get(surface_id).cloned()
 937}
 938
 939impl Dispatch<wl_surface::WlSurface, ()> for WaylandClientStatePtr {
 940    fn event(
 941        this: &mut Self,
 942        surface: &wl_surface::WlSurface,
 943        event: <wl_surface::WlSurface as Proxy>::Event,
 944        _: &(),
 945        _: &Connection,
 946        _: &QueueHandle<Self>,
 947    ) {
 948        let mut client = this.get_client();
 949        let mut state = client.borrow_mut();
 950
 951        let Some(window) = get_window(&mut state, &surface.id()) else {
 952            return;
 953        };
 954        #[allow(clippy::mutable_key_type)]
 955        let outputs = state.outputs.clone();
 956        drop(state);
 957
 958        window.handle_surface_event(event, outputs);
 959    }
 960}
 961
 962impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
 963    fn event(
 964        this: &mut Self,
 965        output: &wl_output::WlOutput,
 966        event: <wl_output::WlOutput as Proxy>::Event,
 967        _: &(),
 968        _: &Connection,
 969        _: &QueueHandle<Self>,
 970    ) {
 971        let mut client = this.get_client();
 972        let mut state = client.borrow_mut();
 973
 974        let Some(mut in_progress_output) = state.in_progress_outputs.get_mut(&output.id()) else {
 975            return;
 976        };
 977
 978        match event {
 979            wl_output::Event::Name { name } => {
 980                in_progress_output.name = Some(name);
 981            }
 982            wl_output::Event::Scale { factor } => {
 983                in_progress_output.scale = Some(factor);
 984            }
 985            wl_output::Event::Geometry { x, y, .. } => {
 986                in_progress_output.position = Some(point(DevicePixels(x), DevicePixels(y)))
 987            }
 988            wl_output::Event::Mode { width, height, .. } => {
 989                in_progress_output.size = Some(size(DevicePixels(width), DevicePixels(height)))
 990            }
 991            wl_output::Event::Done => {
 992                if let Some(complete) = in_progress_output.complete() {
 993                    state.outputs.insert(output.id(), complete);
 994                }
 995                state.in_progress_outputs.remove(&output.id());
 996            }
 997            _ => {}
 998        }
 999    }
1000}
1001
1002impl Dispatch<xdg_surface::XdgSurface, ObjectId> for WaylandClientStatePtr {
1003    fn event(
1004        state: &mut Self,
1005        _: &xdg_surface::XdgSurface,
1006        event: xdg_surface::Event,
1007        surface_id: &ObjectId,
1008        _: &Connection,
1009        _: &QueueHandle<Self>,
1010    ) {
1011        let client = state.get_client();
1012        let mut state = client.borrow_mut();
1013        let Some(window) = get_window(&mut state, surface_id) else {
1014            return;
1015        };
1016        drop(state);
1017        window.handle_xdg_surface_event(event);
1018    }
1019}
1020
1021impl Dispatch<xdg_toplevel::XdgToplevel, ObjectId> for WaylandClientStatePtr {
1022    fn event(
1023        this: &mut Self,
1024        _: &xdg_toplevel::XdgToplevel,
1025        event: <xdg_toplevel::XdgToplevel as Proxy>::Event,
1026        surface_id: &ObjectId,
1027        _: &Connection,
1028        _: &QueueHandle<Self>,
1029    ) {
1030        let client = this.get_client();
1031        let mut state = client.borrow_mut();
1032        let Some(window) = get_window(&mut state, surface_id) else {
1033            return;
1034        };
1035
1036        drop(state);
1037        let should_close = window.handle_toplevel_event(event);
1038
1039        if should_close {
1040            // The close logic will be handled in drop_window()
1041            window.close();
1042        }
1043    }
1044}
1045
1046impl Dispatch<xdg_wm_base::XdgWmBase, ()> for WaylandClientStatePtr {
1047    fn event(
1048        _: &mut Self,
1049        wm_base: &xdg_wm_base::XdgWmBase,
1050        event: <xdg_wm_base::XdgWmBase as Proxy>::Event,
1051        _: &(),
1052        _: &Connection,
1053        _: &QueueHandle<Self>,
1054    ) {
1055        if let xdg_wm_base::Event::Ping { serial } = event {
1056            wm_base.pong(serial);
1057        }
1058    }
1059}
1060
1061impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClientStatePtr {
1062    fn event(
1063        this: &mut Self,
1064        token: &xdg_activation_token_v1::XdgActivationTokenV1,
1065        event: <xdg_activation_token_v1::XdgActivationTokenV1 as Proxy>::Event,
1066        _: &(),
1067        _: &Connection,
1068        _: &QueueHandle<Self>,
1069    ) {
1070        let client = this.get_client();
1071        let mut state = client.borrow_mut();
1072
1073        if let xdg_activation_token_v1::Event::Done { token } = event {
1074            let executor = state.common.background_executor.clone();
1075            match state.pending_activation.take() {
1076                Some(PendingActivation::Uri(uri)) => open_uri_internal(executor, &uri, Some(token)),
1077                Some(PendingActivation::Path(path)) => {
1078                    reveal_path_internal(executor, path, Some(token))
1079                }
1080                Some(PendingActivation::Window(window)) => {
1081                    let Some(window) = get_window(&mut state, &window) else {
1082                        return;
1083                    };
1084                    let activation = state.globals.activation.as_ref().unwrap();
1085                    activation.activate(token, &window.surface());
1086                }
1087                None => log::error!("activation token received with no pending activation"),
1088            }
1089        }
1090
1091        token.destroy();
1092    }
1093}
1094
1095impl Dispatch<wl_seat::WlSeat, ()> for WaylandClientStatePtr {
1096    fn event(
1097        state: &mut Self,
1098        seat: &wl_seat::WlSeat,
1099        event: wl_seat::Event,
1100        _: &(),
1101        _: &Connection,
1102        qh: &QueueHandle<Self>,
1103    ) {
1104        if let wl_seat::Event::Capabilities {
1105            capabilities: WEnum::Value(capabilities),
1106        } = event
1107        {
1108            let client = state.get_client();
1109            let mut state = client.borrow_mut();
1110            if capabilities.contains(wl_seat::Capability::Keyboard) {
1111                let keyboard = seat.get_keyboard(qh, ());
1112
1113                state.text_input = state
1114                    .globals
1115                    .text_input_manager
1116                    .as_ref()
1117                    .map(|text_input_manager| text_input_manager.get_text_input(&seat, qh, ()));
1118
1119                if let Some(wl_keyboard) = &state.wl_keyboard {
1120                    wl_keyboard.release();
1121                }
1122
1123                state.wl_keyboard = Some(keyboard);
1124            }
1125            if capabilities.contains(wl_seat::Capability::Pointer) {
1126                let pointer = seat.get_pointer(qh, ());
1127                state.cursor_shape_device = state
1128                    .globals
1129                    .cursor_shape_manager
1130                    .as_ref()
1131                    .map(|cursor_shape_manager| cursor_shape_manager.get_pointer(&pointer, qh, ()));
1132
1133                if let Some(wl_pointer) = &state.wl_pointer {
1134                    wl_pointer.release();
1135                }
1136
1137                state.wl_pointer = Some(pointer);
1138            }
1139        }
1140    }
1141}
1142
1143impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
1144    fn event(
1145        this: &mut Self,
1146        _: &wl_keyboard::WlKeyboard,
1147        event: wl_keyboard::Event,
1148        _: &(),
1149        _: &Connection,
1150        _: &QueueHandle<Self>,
1151    ) {
1152        let mut client = this.get_client();
1153        let mut state = client.borrow_mut();
1154        match event {
1155            wl_keyboard::Event::RepeatInfo { rate, delay } => {
1156                state.repeat.characters_per_second = rate as u32;
1157                state.repeat.delay = Duration::from_millis(delay as u64);
1158            }
1159            wl_keyboard::Event::Keymap {
1160                format: WEnum::Value(format),
1161                fd,
1162                size,
1163                ..
1164            } => {
1165                if format != wl_keyboard::KeymapFormat::XkbV1 {
1166                    log::error!("Received keymap format {:?}, expected XkbV1", format);
1167                    return;
1168                }
1169                let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
1170                let keymap = unsafe {
1171                    xkb::Keymap::new_from_fd(
1172                        &xkb_context,
1173                        fd,
1174                        size as usize,
1175                        XKB_KEYMAP_FORMAT_TEXT_V1,
1176                        KEYMAP_COMPILE_NO_FLAGS,
1177                    )
1178                    .log_err()
1179                    .flatten()
1180                    .expect("Failed to create keymap")
1181                };
1182                state.keymap_state = Some(xkb::State::new(&keymap));
1183                state.compose_state = get_xkb_compose_state(&xkb_context);
1184
1185                if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
1186                    drop(state);
1187                    callback();
1188                    state = client.borrow_mut();
1189                    state.common.callbacks.keyboard_layout_change = Some(callback);
1190                }
1191            }
1192            wl_keyboard::Event::Enter { surface, .. } => {
1193                state.keyboard_focused_window = get_window(&mut state, &surface.id());
1194                state.enter_token = Some(());
1195
1196                if let Some(window) = state.keyboard_focused_window.clone() {
1197                    drop(state);
1198                    window.set_focused(true);
1199                }
1200            }
1201            wl_keyboard::Event::Leave { surface, .. } => {
1202                let keyboard_focused_window = get_window(&mut state, &surface.id());
1203                state.keyboard_focused_window = None;
1204                state.enter_token.take();
1205                // Prevent keyboard events from repeating after opening e.g. a file chooser and closing it quickly
1206                state.repeat.current_id += 1;
1207
1208                if let Some(window) = keyboard_focused_window {
1209                    if let Some(ref mut compose) = state.compose_state {
1210                        compose.reset();
1211                    }
1212                    state.pre_edit_text.take();
1213                    drop(state);
1214                    window.handle_ime(ImeInput::DeleteText);
1215                    window.set_focused(false);
1216                }
1217            }
1218            wl_keyboard::Event::Modifiers {
1219                mods_depressed,
1220                mods_latched,
1221                mods_locked,
1222                group,
1223                ..
1224            } => {
1225                let focused_window = state.keyboard_focused_window.clone();
1226
1227                let keymap_state = state.keymap_state.as_mut().unwrap();
1228                let old_layout =
1229                    keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
1230                keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1231                state.modifiers = Modifiers::from_xkb(keymap_state);
1232
1233                if group != old_layout {
1234                    if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take()
1235                    {
1236                        drop(state);
1237                        callback();
1238                        state = client.borrow_mut();
1239                        state.common.callbacks.keyboard_layout_change = Some(callback);
1240                    }
1241                }
1242
1243                let Some(focused_window) = focused_window else {
1244                    return;
1245                };
1246
1247                let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1248                    modifiers: state.modifiers,
1249                });
1250
1251                drop(state);
1252                focused_window.handle_input(input);
1253            }
1254            wl_keyboard::Event::Key {
1255                serial,
1256                key,
1257                state: WEnum::Value(key_state),
1258                ..
1259            } => {
1260                state.serial_tracker.update(SerialKind::KeyPress, serial);
1261
1262                let focused_window = state.keyboard_focused_window.clone();
1263                let Some(focused_window) = focused_window else {
1264                    return;
1265                };
1266                let focused_window = focused_window.clone();
1267
1268                let keymap_state = state.keymap_state.as_ref().unwrap();
1269                let keycode = Keycode::from(key + MIN_KEYCODE);
1270                let keysym = keymap_state.key_get_one_sym(keycode);
1271
1272                match key_state {
1273                    wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1274                        let mut keystroke =
1275                            Keystroke::from_xkb(&keymap_state, state.modifiers, keycode);
1276                        if let Some(mut compose) = state.compose_state.take() {
1277                            compose.feed(keysym);
1278                            match compose.status() {
1279                                xkb::Status::Composing => {
1280                                    keystroke.key_char = None;
1281                                    state.pre_edit_text =
1282                                        compose.utf8().or(Keystroke::underlying_dead_key(keysym));
1283                                    let pre_edit =
1284                                        state.pre_edit_text.clone().unwrap_or(String::default());
1285                                    drop(state);
1286                                    focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1287                                    state = client.borrow_mut();
1288                                }
1289
1290                                xkb::Status::Composed => {
1291                                    state.pre_edit_text.take();
1292                                    keystroke.key_char = compose.utf8();
1293                                    if let Some(keysym) = compose.keysym() {
1294                                        keystroke.key = xkb::keysym_get_name(keysym);
1295                                    }
1296                                }
1297                                xkb::Status::Cancelled => {
1298                                    let pre_edit = state.pre_edit_text.take();
1299                                    let new_pre_edit = Keystroke::underlying_dead_key(keysym);
1300                                    state.pre_edit_text = new_pre_edit.clone();
1301                                    drop(state);
1302                                    if let Some(pre_edit) = pre_edit {
1303                                        focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1304                                    }
1305                                    if let Some(current_key) = new_pre_edit {
1306                                        focused_window
1307                                            .handle_ime(ImeInput::SetMarkedText(current_key));
1308                                    }
1309                                    compose.feed(keysym);
1310                                    state = client.borrow_mut();
1311                                }
1312                                _ => {}
1313                            }
1314                            state.compose_state = Some(compose);
1315                        }
1316                        let input = PlatformInput::KeyDown(KeyDownEvent {
1317                            keystroke: keystroke.clone(),
1318                            is_held: false,
1319                        });
1320
1321                        state.repeat.current_id += 1;
1322                        state.repeat.current_keycode = Some(keycode);
1323
1324                        let rate = state.repeat.characters_per_second;
1325                        let id = state.repeat.current_id;
1326                        state
1327                            .loop_handle
1328                            .insert_source(Timer::from_duration(state.repeat.delay), {
1329                                let input = PlatformInput::KeyDown(KeyDownEvent {
1330                                    keystroke,
1331                                    is_held: true,
1332                                });
1333                                move |_event, _metadata, this| {
1334                                    let mut client = this.get_client();
1335                                    let mut state = client.borrow_mut();
1336                                    let is_repeating = id == state.repeat.current_id
1337                                        && state.repeat.current_keycode.is_some()
1338                                        && state.keyboard_focused_window.is_some();
1339
1340                                    if !is_repeating || rate == 0 {
1341                                        return TimeoutAction::Drop;
1342                                    }
1343
1344                                    let focused_window =
1345                                        state.keyboard_focused_window.as_ref().unwrap().clone();
1346
1347                                    drop(state);
1348                                    focused_window.handle_input(input.clone());
1349
1350                                    TimeoutAction::ToDuration(Duration::from_secs(1) / rate)
1351                                }
1352                            })
1353                            .unwrap();
1354
1355                        drop(state);
1356                        focused_window.handle_input(input);
1357                    }
1358                    wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1359                        let input = PlatformInput::KeyUp(KeyUpEvent {
1360                            keystroke: Keystroke::from_xkb(keymap_state, state.modifiers, keycode),
1361                        });
1362
1363                        if state.repeat.current_keycode == Some(keycode) {
1364                            state.repeat.current_keycode = None;
1365                        }
1366
1367                        drop(state);
1368                        focused_window.handle_input(input);
1369                    }
1370                    _ => {}
1371                }
1372            }
1373            _ => {}
1374        }
1375    }
1376}
1377impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1378    fn event(
1379        this: &mut Self,
1380        text_input: &zwp_text_input_v3::ZwpTextInputV3,
1381        event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1382        _: &(),
1383        _: &Connection,
1384        _: &QueueHandle<Self>,
1385    ) {
1386        let client = this.get_client();
1387        let mut state = client.borrow_mut();
1388        match event {
1389            zwp_text_input_v3::Event::Enter { .. } => {
1390                drop(state);
1391                this.enable_ime();
1392            }
1393            zwp_text_input_v3::Event::Leave { .. } => {
1394                drop(state);
1395                this.disable_ime();
1396            }
1397            zwp_text_input_v3::Event::CommitString { text } => {
1398                state.composing = false;
1399                let Some(window) = state.keyboard_focused_window.clone() else {
1400                    return;
1401                };
1402
1403                if let Some(commit_text) = text {
1404                    drop(state);
1405                    // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1406                    // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1407                    if commit_text.len() == 1 {
1408                        window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1409                            keystroke: Keystroke {
1410                                modifiers: Modifiers::default(),
1411                                key: commit_text.clone(),
1412                                key_char: Some(commit_text),
1413                            },
1414                            is_held: false,
1415                        }));
1416                    } else {
1417                        window.handle_ime(ImeInput::InsertText(commit_text));
1418                    }
1419                }
1420            }
1421            zwp_text_input_v3::Event::PreeditString { text, .. } => {
1422                state.composing = true;
1423                state.ime_pre_edit = text;
1424            }
1425            zwp_text_input_v3::Event::Done { serial } => {
1426                let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1427                state.serial_tracker.update(SerialKind::InputMethod, serial);
1428                let Some(window) = state.keyboard_focused_window.clone() else {
1429                    return;
1430                };
1431
1432                if let Some(text) = state.ime_pre_edit.take() {
1433                    drop(state);
1434                    window.handle_ime(ImeInput::SetMarkedText(text));
1435                    if let Some(area) = window.get_ime_area() {
1436                        text_input.set_cursor_rectangle(
1437                            area.origin.x.0 as i32,
1438                            area.origin.y.0 as i32,
1439                            area.size.width.0 as i32,
1440                            area.size.height.0 as i32,
1441                        );
1442                        if last_serial == serial {
1443                            text_input.commit();
1444                        }
1445                    }
1446                } else {
1447                    state.composing = false;
1448                    drop(state);
1449                    window.handle_ime(ImeInput::DeleteText);
1450                }
1451            }
1452            _ => {}
1453        }
1454    }
1455}
1456
1457fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1458    // These values are coming from <linux/input-event-codes.h>.
1459    const BTN_LEFT: u32 = 0x110;
1460    const BTN_RIGHT: u32 = 0x111;
1461    const BTN_MIDDLE: u32 = 0x112;
1462    const BTN_SIDE: u32 = 0x113;
1463    const BTN_EXTRA: u32 = 0x114;
1464    const BTN_FORWARD: u32 = 0x115;
1465    const BTN_BACK: u32 = 0x116;
1466
1467    Some(match button {
1468        BTN_LEFT => MouseButton::Left,
1469        BTN_RIGHT => MouseButton::Right,
1470        BTN_MIDDLE => MouseButton::Middle,
1471        BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1472        BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1473        _ => return None,
1474    })
1475}
1476
1477impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1478    fn event(
1479        this: &mut Self,
1480        wl_pointer: &wl_pointer::WlPointer,
1481        event: wl_pointer::Event,
1482        _: &(),
1483        _: &Connection,
1484        _: &QueueHandle<Self>,
1485    ) {
1486        let mut client = this.get_client();
1487        let mut state = client.borrow_mut();
1488
1489        match event {
1490            wl_pointer::Event::Enter {
1491                serial,
1492                surface,
1493                surface_x,
1494                surface_y,
1495                ..
1496            } => {
1497                state.serial_tracker.update(SerialKind::MouseEnter, serial);
1498                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1499                state.button_pressed = None;
1500
1501                if let Some(window) = get_window(&mut state, &surface.id()) {
1502                    state.mouse_focused_window = Some(window.clone());
1503
1504                    if state.enter_token.is_some() {
1505                        state.enter_token = None;
1506                    }
1507                    if let Some(style) = state.cursor_style {
1508                        if let CursorStyle::None = style {
1509                            let wl_pointer = state
1510                                .wl_pointer
1511                                .clone()
1512                                .expect("window is focused by pointer");
1513                            wl_pointer.set_cursor(serial, None, 0, 0);
1514                        } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
1515                            cursor_shape_device.set_shape(serial, style.to_shape());
1516                        } else {
1517                            let scale = window.primary_output_scale();
1518                            state
1519                                .cursor
1520                                .set_icon(&wl_pointer, serial, style.to_icon_name(), scale);
1521                        }
1522                    }
1523                    drop(state);
1524                    window.set_hovered(true);
1525                }
1526            }
1527            wl_pointer::Event::Leave { .. } => {
1528                if let Some(focused_window) = state.mouse_focused_window.clone() {
1529                    let input = PlatformInput::MouseExited(MouseExitEvent {
1530                        position: state.mouse_location.unwrap(),
1531                        pressed_button: state.button_pressed,
1532                        modifiers: state.modifiers,
1533                    });
1534                    state.mouse_focused_window = None;
1535                    state.mouse_location = None;
1536                    state.button_pressed = None;
1537
1538                    drop(state);
1539                    focused_window.handle_input(input);
1540                    focused_window.set_hovered(false);
1541                }
1542            }
1543            wl_pointer::Event::Motion {
1544                surface_x,
1545                surface_y,
1546                ..
1547            } => {
1548                if state.mouse_focused_window.is_none() {
1549                    return;
1550                }
1551                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1552
1553                if let Some(window) = state.mouse_focused_window.clone() {
1554                    if state
1555                        .keyboard_focused_window
1556                        .as_ref()
1557                        .map_or(false, |keyboard_window| window.ptr_eq(&keyboard_window))
1558                    {
1559                        state.enter_token = None;
1560                    }
1561                    let input = PlatformInput::MouseMove(MouseMoveEvent {
1562                        position: state.mouse_location.unwrap(),
1563                        pressed_button: state.button_pressed,
1564                        modifiers: state.modifiers,
1565                    });
1566                    drop(state);
1567                    window.handle_input(input);
1568                }
1569            }
1570            wl_pointer::Event::Button {
1571                serial,
1572                button,
1573                state: WEnum::Value(button_state),
1574                ..
1575            } => {
1576                state.serial_tracker.update(SerialKind::MousePress, serial);
1577                let button = linux_button_to_gpui(button);
1578                let Some(button) = button else { return };
1579                if state.mouse_focused_window.is_none() {
1580                    return;
1581                }
1582                match button_state {
1583                    wl_pointer::ButtonState::Pressed => {
1584                        if let Some(window) = state.keyboard_focused_window.clone() {
1585                            if state.composing && state.text_input.is_some() {
1586                                drop(state);
1587                                // text_input_v3 don't have something like a reset function
1588                                this.disable_ime();
1589                                this.enable_ime();
1590                                window.handle_ime(ImeInput::UnmarkText);
1591                                state = client.borrow_mut();
1592                            } else if let (Some(text), Some(compose)) =
1593                                (state.pre_edit_text.take(), state.compose_state.as_mut())
1594                            {
1595                                compose.reset();
1596                                drop(state);
1597                                window.handle_ime(ImeInput::InsertText(text));
1598                                state = client.borrow_mut();
1599                            }
1600                        }
1601                        let click_elapsed = state.click.last_click.elapsed();
1602
1603                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1604                            && state
1605                                .click
1606                                .last_mouse_button
1607                                .is_some_and(|prev_button| prev_button == button)
1608                            && is_within_click_distance(
1609                                state.click.last_location,
1610                                state.mouse_location.unwrap(),
1611                            )
1612                        {
1613                            state.click.current_count += 1;
1614                        } else {
1615                            state.click.current_count = 1;
1616                        }
1617
1618                        state.click.last_click = Instant::now();
1619                        state.click.last_mouse_button = Some(button);
1620                        state.click.last_location = state.mouse_location.unwrap();
1621
1622                        state.button_pressed = Some(button);
1623
1624                        if let Some(window) = state.mouse_focused_window.clone() {
1625                            let input = PlatformInput::MouseDown(MouseDownEvent {
1626                                button,
1627                                position: state.mouse_location.unwrap(),
1628                                modifiers: state.modifiers,
1629                                click_count: state.click.current_count,
1630                                first_mouse: state.enter_token.take().is_some(),
1631                            });
1632                            drop(state);
1633                            window.handle_input(input);
1634                        }
1635                    }
1636                    wl_pointer::ButtonState::Released => {
1637                        state.button_pressed = None;
1638
1639                        if let Some(window) = state.mouse_focused_window.clone() {
1640                            let input = PlatformInput::MouseUp(MouseUpEvent {
1641                                button,
1642                                position: state.mouse_location.unwrap(),
1643                                modifiers: state.modifiers,
1644                                click_count: state.click.current_count,
1645                            });
1646                            drop(state);
1647                            window.handle_input(input);
1648                        }
1649                    }
1650                    _ => {}
1651                }
1652            }
1653
1654            // Axis Events
1655            wl_pointer::Event::AxisSource {
1656                axis_source: WEnum::Value(axis_source),
1657            } => {
1658                state.axis_source = axis_source;
1659            }
1660            wl_pointer::Event::Axis {
1661                axis: WEnum::Value(axis),
1662                value,
1663                ..
1664            } => {
1665                if state.axis_source == AxisSource::Wheel {
1666                    return;
1667                }
1668                let axis = if state.modifiers.shift {
1669                    wl_pointer::Axis::HorizontalScroll
1670                } else {
1671                    axis
1672                };
1673                let axis_modifier = match axis {
1674                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1675                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1676                    _ => 1.0,
1677                };
1678                state.scroll_event_received = true;
1679                let scroll_delta = state
1680                    .continuous_scroll_delta
1681                    .get_or_insert(point(px(0.0), px(0.0)));
1682                let modifier = 3.0;
1683                match axis {
1684                    wl_pointer::Axis::VerticalScroll => {
1685                        scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1686                    }
1687                    wl_pointer::Axis::HorizontalScroll => {
1688                        scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1689                    }
1690                    _ => unreachable!(),
1691                }
1692            }
1693            wl_pointer::Event::AxisDiscrete {
1694                axis: WEnum::Value(axis),
1695                discrete,
1696            } => {
1697                state.scroll_event_received = true;
1698                let axis = if state.modifiers.shift {
1699                    wl_pointer::Axis::HorizontalScroll
1700                } else {
1701                    axis
1702                };
1703                let axis_modifier = match axis {
1704                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1705                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1706                    _ => 1.0,
1707                };
1708
1709                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1710                match axis {
1711                    wl_pointer::Axis::VerticalScroll => {
1712                        scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES;
1713                    }
1714                    wl_pointer::Axis::HorizontalScroll => {
1715                        scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES;
1716                    }
1717                    _ => unreachable!(),
1718                }
1719            }
1720            wl_pointer::Event::AxisValue120 {
1721                axis: WEnum::Value(axis),
1722                value120,
1723            } => {
1724                state.scroll_event_received = true;
1725                let axis = if state.modifiers.shift {
1726                    wl_pointer::Axis::HorizontalScroll
1727                } else {
1728                    axis
1729                };
1730                let axis_modifier = match axis {
1731                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1732                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1733                    _ => unreachable!(),
1734                };
1735
1736                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1737                let wheel_percent = value120 as f32 / 120.0;
1738                match axis {
1739                    wl_pointer::Axis::VerticalScroll => {
1740                        scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES;
1741                    }
1742                    wl_pointer::Axis::HorizontalScroll => {
1743                        scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES;
1744                    }
1745                    _ => unreachable!(),
1746                }
1747            }
1748            wl_pointer::Event::Frame => {
1749                if state.scroll_event_received {
1750                    state.scroll_event_received = false;
1751                    let continuous = state.continuous_scroll_delta.take();
1752                    let discrete = state.discrete_scroll_delta.take();
1753                    if let Some(continuous) = continuous {
1754                        if let Some(window) = state.mouse_focused_window.clone() {
1755                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1756                                position: state.mouse_location.unwrap(),
1757                                delta: ScrollDelta::Pixels(continuous),
1758                                modifiers: state.modifiers,
1759                                touch_phase: TouchPhase::Moved,
1760                            });
1761                            drop(state);
1762                            window.handle_input(input);
1763                        }
1764                    } else if let Some(discrete) = discrete {
1765                        if let Some(window) = state.mouse_focused_window.clone() {
1766                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1767                                position: state.mouse_location.unwrap(),
1768                                delta: ScrollDelta::Lines(discrete),
1769                                modifiers: state.modifiers,
1770                                touch_phase: TouchPhase::Moved,
1771                            });
1772                            drop(state);
1773                            window.handle_input(input);
1774                        }
1775                    }
1776                }
1777            }
1778            _ => {}
1779        }
1780    }
1781}
1782
1783impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1784    fn event(
1785        this: &mut Self,
1786        _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1787        event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1788        surface_id: &ObjectId,
1789        _: &Connection,
1790        _: &QueueHandle<Self>,
1791    ) {
1792        let client = this.get_client();
1793        let mut state = client.borrow_mut();
1794
1795        let Some(window) = get_window(&mut state, surface_id) else {
1796            return;
1797        };
1798
1799        drop(state);
1800        window.handle_fractional_scale_event(event);
1801    }
1802}
1803
1804impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1805    for WaylandClientStatePtr
1806{
1807    fn event(
1808        this: &mut Self,
1809        _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1810        event: zxdg_toplevel_decoration_v1::Event,
1811        surface_id: &ObjectId,
1812        _: &Connection,
1813        _: &QueueHandle<Self>,
1814    ) {
1815        let client = this.get_client();
1816        let mut state = client.borrow_mut();
1817        let Some(window) = get_window(&mut state, surface_id) else {
1818            return;
1819        };
1820
1821        drop(state);
1822        window.handle_toplevel_decoration_event(event);
1823    }
1824}
1825
1826impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1827    fn event(
1828        this: &mut Self,
1829        _: &wl_data_device::WlDataDevice,
1830        event: wl_data_device::Event,
1831        _: &(),
1832        _: &Connection,
1833        _: &QueueHandle<Self>,
1834    ) {
1835        let client = this.get_client();
1836        let mut state = client.borrow_mut();
1837
1838        match event {
1839            // Clipboard
1840            wl_data_device::Event::DataOffer { id: data_offer } => {
1841                state.data_offers.push(DataOffer::new(data_offer));
1842                if state.data_offers.len() > 2 {
1843                    // At most we store a clipboard offer and a drag and drop offer.
1844                    state.data_offers.remove(0).inner.destroy();
1845                }
1846            }
1847            wl_data_device::Event::Selection { id: data_offer } => {
1848                if let Some(offer) = data_offer {
1849                    let offer = state
1850                        .data_offers
1851                        .iter()
1852                        .find(|wrapper| wrapper.inner.id() == offer.id());
1853                    let offer = offer.cloned();
1854                    state.clipboard.set_offer(offer);
1855                } else {
1856                    state.clipboard.set_offer(None);
1857                }
1858            }
1859
1860            // Drag and drop
1861            wl_data_device::Event::Enter {
1862                serial,
1863                surface,
1864                x,
1865                y,
1866                id: data_offer,
1867            } => {
1868                state.serial_tracker.update(SerialKind::DataDevice, serial);
1869                if let Some(data_offer) = data_offer {
1870                    let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1871                        return;
1872                    };
1873
1874                    const ACTIONS: DndAction = DndAction::Copy;
1875                    data_offer.set_actions(ACTIONS, ACTIONS);
1876
1877                    let pipe = Pipe::new().unwrap();
1878                    data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1879                        BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1880                    });
1881                    let fd = pipe.read;
1882                    drop(pipe.write);
1883
1884                    let read_task = state.common.background_executor.spawn(async {
1885                        let buffer = unsafe { read_fd(fd)? };
1886                        let text = String::from_utf8(buffer)?;
1887                        anyhow::Ok(text)
1888                    });
1889
1890                    let this = this.clone();
1891                    state
1892                        .common
1893                        .foreground_executor
1894                        .spawn(async move {
1895                            let file_list = match read_task.await {
1896                                Ok(list) => list,
1897                                Err(err) => {
1898                                    log::error!("error reading drag and drop pipe: {err:?}");
1899                                    return;
1900                                }
1901                            };
1902
1903                            let paths: SmallVec<[_; 2]> = file_list
1904                                .lines()
1905                                .filter_map(|path| Url::parse(path).log_err())
1906                                .filter_map(|url| url.to_file_path().log_err())
1907                                .collect();
1908                            let position = Point::new(x.into(), y.into());
1909
1910                            // Prevent dropping text from other programs.
1911                            if paths.is_empty() {
1912                                data_offer.destroy();
1913                                return;
1914                            }
1915
1916                            let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1917                                position,
1918                                paths: crate::ExternalPaths(paths),
1919                            });
1920
1921                            let client = this.get_client();
1922                            let mut state = client.borrow_mut();
1923                            state.drag.data_offer = Some(data_offer);
1924                            state.drag.window = Some(drag_window.clone());
1925                            state.drag.position = position;
1926
1927                            drop(state);
1928                            drag_window.handle_input(input);
1929                        })
1930                        .detach();
1931                }
1932            }
1933            wl_data_device::Event::Motion { x, y, .. } => {
1934                let Some(drag_window) = state.drag.window.clone() else {
1935                    return;
1936                };
1937                let position = Point::new(x.into(), y.into());
1938                state.drag.position = position;
1939
1940                let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
1941                drop(state);
1942                drag_window.handle_input(input);
1943            }
1944            wl_data_device::Event::Leave => {
1945                let Some(drag_window) = state.drag.window.clone() else {
1946                    return;
1947                };
1948                let data_offer = state.drag.data_offer.clone().unwrap();
1949                data_offer.destroy();
1950
1951                state.drag.data_offer = None;
1952                state.drag.window = None;
1953
1954                let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
1955                drop(state);
1956                drag_window.handle_input(input);
1957            }
1958            wl_data_device::Event::Drop => {
1959                let Some(drag_window) = state.drag.window.clone() else {
1960                    return;
1961                };
1962                let data_offer = state.drag.data_offer.clone().unwrap();
1963                data_offer.finish();
1964                data_offer.destroy();
1965
1966                state.drag.data_offer = None;
1967                state.drag.window = None;
1968
1969                let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1970                    position: state.drag.position,
1971                });
1972                drop(state);
1973                drag_window.handle_input(input);
1974            }
1975            _ => {}
1976        }
1977    }
1978
1979    event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
1980        wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
1981    ]);
1982}
1983
1984impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
1985    fn event(
1986        this: &mut Self,
1987        data_offer: &wl_data_offer::WlDataOffer,
1988        event: wl_data_offer::Event,
1989        _: &(),
1990        _: &Connection,
1991        _: &QueueHandle<Self>,
1992    ) {
1993        let client = this.get_client();
1994        let mut state = client.borrow_mut();
1995
1996        match event {
1997            wl_data_offer::Event::Offer { mime_type } => {
1998                // Drag and drop
1999                if mime_type == FILE_LIST_MIME_TYPE {
2000                    let serial = state.serial_tracker.get(SerialKind::DataDevice);
2001                    let mime_type = mime_type.clone();
2002                    data_offer.accept(serial, Some(mime_type));
2003                }
2004
2005                // Clipboard
2006                if let Some(offer) = state
2007                    .data_offers
2008                    .iter_mut()
2009                    .find(|wrapper| wrapper.inner.id() == data_offer.id())
2010                {
2011                    offer.add_mime_type(mime_type);
2012                }
2013            }
2014            _ => {}
2015        }
2016    }
2017}
2018
2019impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
2020    fn event(
2021        this: &mut Self,
2022        data_source: &wl_data_source::WlDataSource,
2023        event: wl_data_source::Event,
2024        _: &(),
2025        _: &Connection,
2026        _: &QueueHandle<Self>,
2027    ) {
2028        let client = this.get_client();
2029        let mut state = client.borrow_mut();
2030
2031        match event {
2032            wl_data_source::Event::Send { mime_type, fd } => {
2033                state.clipboard.send(mime_type, fd);
2034            }
2035            wl_data_source::Event::Cancelled => {
2036                data_source.destroy();
2037            }
2038            _ => {}
2039        }
2040    }
2041}
2042
2043impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
2044    for WaylandClientStatePtr
2045{
2046    fn event(
2047        this: &mut Self,
2048        _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
2049        event: zwp_primary_selection_device_v1::Event,
2050        _: &(),
2051        _: &Connection,
2052        _: &QueueHandle<Self>,
2053    ) {
2054        let client = this.get_client();
2055        let mut state = client.borrow_mut();
2056
2057        match event {
2058            zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
2059                let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
2060                if let Some(old_offer) = old_offer {
2061                    old_offer.inner.destroy();
2062                }
2063            }
2064            zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
2065                if data_offer.is_some() {
2066                    let offer = state.primary_data_offer.clone();
2067                    state.clipboard.set_primary_offer(offer);
2068                } else {
2069                    state.clipboard.set_primary_offer(None);
2070                }
2071            }
2072            _ => {}
2073        }
2074    }
2075
2076    event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
2077        zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
2078    ]);
2079}
2080
2081impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
2082    for WaylandClientStatePtr
2083{
2084    fn event(
2085        this: &mut Self,
2086        _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
2087        event: zwp_primary_selection_offer_v1::Event,
2088        _: &(),
2089        _: &Connection,
2090        _: &QueueHandle<Self>,
2091    ) {
2092        let client = this.get_client();
2093        let mut state = client.borrow_mut();
2094
2095        match event {
2096            zwp_primary_selection_offer_v1::Event::Offer { mime_type } => {
2097                if let Some(offer) = state.primary_data_offer.as_mut() {
2098                    offer.add_mime_type(mime_type);
2099                }
2100            }
2101            _ => {}
2102        }
2103    }
2104}
2105
2106impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2107    for WaylandClientStatePtr
2108{
2109    fn event(
2110        this: &mut Self,
2111        selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2112        event: zwp_primary_selection_source_v1::Event,
2113        _: &(),
2114        _: &Connection,
2115        _: &QueueHandle<Self>,
2116    ) {
2117        let client = this.get_client();
2118        let mut state = client.borrow_mut();
2119
2120        match event {
2121            zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2122                state.clipboard.send_primary(mime_type, fd);
2123            }
2124            zwp_primary_selection_source_v1::Event::Cancelled => {
2125                selection_source.destroy();
2126            }
2127            _ => {}
2128        }
2129    }
2130}