client.rs

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