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                    if state.enter_token.is_some() {
1407                        state.enter_token = None;
1408                    }
1409                    if let Some(style) = state.cursor_style {
1410                        if let Some(cursor_shape_device) = &state.cursor_shape_device {
1411                            cursor_shape_device.set_shape(serial, style.to_shape());
1412                        } else {
1413                            state
1414                                .cursor
1415                                .set_icon(&wl_pointer, serial, &style.to_icon_name());
1416                        }
1417                    }
1418                    drop(state);
1419                    window.set_focused(true);
1420                }
1421            }
1422            wl_pointer::Event::Leave { .. } => {
1423                if let Some(focused_window) = state.mouse_focused_window.clone() {
1424                    let input = PlatformInput::MouseExited(MouseExitEvent {
1425                        position: state.mouse_location.unwrap(),
1426                        pressed_button: state.button_pressed,
1427                        modifiers: state.modifiers,
1428                    });
1429                    state.mouse_focused_window = None;
1430                    state.mouse_location = None;
1431                    state.button_pressed = None;
1432
1433                    drop(state);
1434                    focused_window.handle_input(input);
1435                    focused_window.set_focused(false);
1436                }
1437            }
1438            wl_pointer::Event::Motion {
1439                surface_x,
1440                surface_y,
1441                ..
1442            } => {
1443                if state.mouse_focused_window.is_none() {
1444                    return;
1445                }
1446                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1447
1448                if let Some(window) = state.mouse_focused_window.clone() {
1449                    if state
1450                        .keyboard_focused_window
1451                        .as_ref()
1452                        .map_or(false, |keyboard_window| window.ptr_eq(&keyboard_window))
1453                    {
1454                        state.enter_token = None;
1455                    }
1456                    let input = PlatformInput::MouseMove(MouseMoveEvent {
1457                        position: state.mouse_location.unwrap(),
1458                        pressed_button: state.button_pressed,
1459                        modifiers: state.modifiers,
1460                    });
1461                    drop(state);
1462                    window.handle_input(input);
1463                }
1464            }
1465            wl_pointer::Event::Button {
1466                serial,
1467                button,
1468                state: WEnum::Value(button_state),
1469                ..
1470            } => {
1471                state.serial_tracker.update(SerialKind::MousePress, serial);
1472                let button = linux_button_to_gpui(button);
1473                let Some(button) = button else { return };
1474                if state.mouse_focused_window.is_none() {
1475                    return;
1476                }
1477                match button_state {
1478                    wl_pointer::ButtonState::Pressed => {
1479                        if let Some(window) = state.keyboard_focused_window.clone() {
1480                            if state.composing && state.text_input.is_some() {
1481                                drop(state);
1482                                // text_input_v3 don't have something like a reset function
1483                                this.disable_ime();
1484                                this.enable_ime();
1485                                window.handle_ime(ImeInput::UnmarkText);
1486                                state = client.borrow_mut();
1487                            } else if let (Some(text), Some(compose)) =
1488                                (state.pre_edit_text.take(), state.compose_state.as_mut())
1489                            {
1490                                compose.reset();
1491                                drop(state);
1492                                window.handle_ime(ImeInput::InsertText(text));
1493                                state = client.borrow_mut();
1494                            }
1495                        }
1496                        let click_elapsed = state.click.last_click.elapsed();
1497
1498                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1499                            && is_within_click_distance(
1500                                state.click.last_location,
1501                                state.mouse_location.unwrap(),
1502                            )
1503                        {
1504                            state.click.current_count += 1;
1505                        } else {
1506                            state.click.current_count = 1;
1507                        }
1508
1509                        state.click.last_click = Instant::now();
1510                        state.click.last_location = state.mouse_location.unwrap();
1511
1512                        state.button_pressed = Some(button);
1513
1514                        if let Some(window) = state.mouse_focused_window.clone() {
1515                            let input = PlatformInput::MouseDown(MouseDownEvent {
1516                                button,
1517                                position: state.mouse_location.unwrap(),
1518                                modifiers: state.modifiers,
1519                                click_count: state.click.current_count,
1520                                first_mouse: state.enter_token.take().is_some(),
1521                            });
1522                            drop(state);
1523                            window.handle_input(input);
1524                        }
1525                    }
1526                    wl_pointer::ButtonState::Released => {
1527                        state.button_pressed = None;
1528
1529                        if let Some(window) = state.mouse_focused_window.clone() {
1530                            let input = PlatformInput::MouseUp(MouseUpEvent {
1531                                button,
1532                                position: state.mouse_location.unwrap(),
1533                                modifiers: state.modifiers,
1534                                click_count: state.click.current_count,
1535                            });
1536                            drop(state);
1537                            window.handle_input(input);
1538                        }
1539                    }
1540                    _ => {}
1541                }
1542            }
1543
1544            // Axis Events
1545            wl_pointer::Event::AxisSource {
1546                axis_source: WEnum::Value(axis_source),
1547            } => {
1548                state.axis_source = axis_source;
1549            }
1550            wl_pointer::Event::Axis {
1551                axis: WEnum::Value(axis),
1552                value,
1553                ..
1554            } => {
1555                if state.axis_source == AxisSource::Wheel {
1556                    return;
1557                }
1558                let axis = if state.modifiers.shift {
1559                    wl_pointer::Axis::HorizontalScroll
1560                } else {
1561                    axis
1562                };
1563                let axis_modifier = match axis {
1564                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1565                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1566                    _ => 1.0,
1567                };
1568                state.scroll_event_received = true;
1569                let scroll_delta = state
1570                    .continuous_scroll_delta
1571                    .get_or_insert(point(px(0.0), px(0.0)));
1572                let modifier = 3.0;
1573                match axis {
1574                    wl_pointer::Axis::VerticalScroll => {
1575                        scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1576                    }
1577                    wl_pointer::Axis::HorizontalScroll => {
1578                        scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1579                    }
1580                    _ => unreachable!(),
1581                }
1582            }
1583            wl_pointer::Event::AxisDiscrete {
1584                axis: WEnum::Value(axis),
1585                discrete,
1586            } => {
1587                state.scroll_event_received = true;
1588                let axis = if state.modifiers.shift {
1589                    wl_pointer::Axis::HorizontalScroll
1590                } else {
1591                    axis
1592                };
1593                let axis_modifier = match axis {
1594                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1595                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1596                    _ => 1.0,
1597                };
1598
1599                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1600                match axis {
1601                    wl_pointer::Axis::VerticalScroll => {
1602                        scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES as f32;
1603                    }
1604                    wl_pointer::Axis::HorizontalScroll => {
1605                        scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES as f32;
1606                    }
1607                    _ => unreachable!(),
1608                }
1609            }
1610            wl_pointer::Event::AxisValue120 {
1611                axis: WEnum::Value(axis),
1612                value120,
1613            } => {
1614                state.scroll_event_received = true;
1615                let axis = if state.modifiers.shift {
1616                    wl_pointer::Axis::HorizontalScroll
1617                } else {
1618                    axis
1619                };
1620                let axis_modifier = match axis {
1621                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1622                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1623                    _ => unreachable!(),
1624                };
1625
1626                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1627                let wheel_percent = value120 as f32 / 120.0;
1628                match axis {
1629                    wl_pointer::Axis::VerticalScroll => {
1630                        scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES as f32;
1631                    }
1632                    wl_pointer::Axis::HorizontalScroll => {
1633                        scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES as f32;
1634                    }
1635                    _ => unreachable!(),
1636                }
1637            }
1638            wl_pointer::Event::Frame => {
1639                if state.scroll_event_received {
1640                    state.scroll_event_received = false;
1641                    let continuous = state.continuous_scroll_delta.take();
1642                    let discrete = state.discrete_scroll_delta.take();
1643                    if let Some(continuous) = continuous {
1644                        if let Some(window) = state.mouse_focused_window.clone() {
1645                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1646                                position: state.mouse_location.unwrap(),
1647                                delta: ScrollDelta::Pixels(continuous),
1648                                modifiers: state.modifiers,
1649                                touch_phase: TouchPhase::Moved,
1650                            });
1651                            drop(state);
1652                            window.handle_input(input);
1653                        }
1654                    } else if let Some(discrete) = discrete {
1655                        if let Some(window) = state.mouse_focused_window.clone() {
1656                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1657                                position: state.mouse_location.unwrap(),
1658                                delta: ScrollDelta::Lines(discrete),
1659                                modifiers: state.modifiers,
1660                                touch_phase: TouchPhase::Moved,
1661                            });
1662                            drop(state);
1663                            window.handle_input(input);
1664                        }
1665                    }
1666                }
1667            }
1668            _ => {}
1669        }
1670    }
1671}
1672
1673impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1674    fn event(
1675        this: &mut Self,
1676        _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1677        event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1678        surface_id: &ObjectId,
1679        _: &Connection,
1680        _: &QueueHandle<Self>,
1681    ) {
1682        let client = this.get_client();
1683        let mut state = client.borrow_mut();
1684
1685        let Some(window) = get_window(&mut state, surface_id) else {
1686            return;
1687        };
1688
1689        drop(state);
1690        window.handle_fractional_scale_event(event);
1691    }
1692}
1693
1694impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1695    for WaylandClientStatePtr
1696{
1697    fn event(
1698        this: &mut Self,
1699        _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1700        event: zxdg_toplevel_decoration_v1::Event,
1701        surface_id: &ObjectId,
1702        _: &Connection,
1703        _: &QueueHandle<Self>,
1704    ) {
1705        let client = this.get_client();
1706        let mut state = client.borrow_mut();
1707        let Some(window) = get_window(&mut state, surface_id) else {
1708            return;
1709        };
1710
1711        drop(state);
1712        window.handle_toplevel_decoration_event(event);
1713    }
1714}
1715
1716impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1717    fn event(
1718        this: &mut Self,
1719        _: &wl_data_device::WlDataDevice,
1720        event: wl_data_device::Event,
1721        _: &(),
1722        _: &Connection,
1723        _: &QueueHandle<Self>,
1724    ) {
1725        let client = this.get_client();
1726        let mut state = client.borrow_mut();
1727
1728        match event {
1729            // Clipboard
1730            wl_data_device::Event::DataOffer { id: data_offer } => {
1731                state.data_offers.push(DataOffer::new(data_offer));
1732                if state.data_offers.len() > 2 {
1733                    // At most we store a clipboard offer and a drag and drop offer.
1734                    state.data_offers.remove(0).inner.destroy();
1735                }
1736            }
1737            wl_data_device::Event::Selection { id: data_offer } => {
1738                if let Some(offer) = data_offer {
1739                    let offer = state
1740                        .data_offers
1741                        .iter()
1742                        .find(|wrapper| wrapper.inner.id() == offer.id());
1743                    let offer = offer.cloned();
1744                    state.clipboard.set_offer(offer);
1745                } else {
1746                    state.clipboard.set_offer(None);
1747                }
1748            }
1749
1750            // Drag and drop
1751            wl_data_device::Event::Enter {
1752                serial,
1753                surface,
1754                x,
1755                y,
1756                id: data_offer,
1757            } => {
1758                state.serial_tracker.update(SerialKind::DataDevice, serial);
1759                if let Some(data_offer) = data_offer {
1760                    let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1761                        return;
1762                    };
1763
1764                    const ACTIONS: DndAction = DndAction::Copy;
1765                    data_offer.set_actions(ACTIONS, ACTIONS);
1766
1767                    let pipe = Pipe::new().unwrap();
1768                    data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1769                        BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1770                    });
1771                    let fd = pipe.read;
1772                    drop(pipe.write);
1773
1774                    let read_task = state
1775                        .common
1776                        .background_executor
1777                        .spawn(async { unsafe { read_fd(fd) } });
1778
1779                    let this = this.clone();
1780                    state
1781                        .common
1782                        .foreground_executor
1783                        .spawn(async move {
1784                            let file_list = match read_task.await {
1785                                Ok(list) => list,
1786                                Err(err) => {
1787                                    log::error!("error reading drag and drop pipe: {err:?}");
1788                                    return;
1789                                }
1790                            };
1791
1792                            let paths: SmallVec<[_; 2]> = file_list
1793                                .lines()
1794                                .map(|path| PathBuf::from(path.replace("file://", "")))
1795                                .collect();
1796                            let position = Point::new(x.into(), y.into());
1797
1798                            // Prevent dropping text from other programs.
1799                            if paths.is_empty() {
1800                                data_offer.finish();
1801                                data_offer.destroy();
1802                                return;
1803                            }
1804
1805                            let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1806                                position,
1807                                paths: crate::ExternalPaths(paths),
1808                            });
1809
1810                            let client = this.get_client();
1811                            let mut state = client.borrow_mut();
1812                            state.drag.data_offer = Some(data_offer);
1813                            state.drag.window = Some(drag_window.clone());
1814                            state.drag.position = position;
1815
1816                            drop(state);
1817                            drag_window.handle_input(input);
1818                        })
1819                        .detach();
1820                }
1821            }
1822            wl_data_device::Event::Motion { x, y, .. } => {
1823                let Some(drag_window) = state.drag.window.clone() else {
1824                    return;
1825                };
1826                let position = Point::new(x.into(), y.into());
1827                state.drag.position = position;
1828
1829                let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
1830                drop(state);
1831                drag_window.handle_input(input);
1832            }
1833            wl_data_device::Event::Leave => {
1834                let Some(drag_window) = state.drag.window.clone() else {
1835                    return;
1836                };
1837                let data_offer = state.drag.data_offer.clone().unwrap();
1838                data_offer.destroy();
1839
1840                state.drag.data_offer = None;
1841                state.drag.window = None;
1842
1843                let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
1844                drop(state);
1845                drag_window.handle_input(input);
1846            }
1847            wl_data_device::Event::Drop => {
1848                let Some(drag_window) = state.drag.window.clone() else {
1849                    return;
1850                };
1851                let data_offer = state.drag.data_offer.clone().unwrap();
1852                data_offer.finish();
1853                data_offer.destroy();
1854
1855                state.drag.data_offer = None;
1856                state.drag.window = None;
1857
1858                let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1859                    position: state.drag.position,
1860                });
1861                drop(state);
1862                drag_window.handle_input(input);
1863            }
1864            _ => {}
1865        }
1866    }
1867
1868    event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
1869        wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
1870    ]);
1871}
1872
1873impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
1874    fn event(
1875        this: &mut Self,
1876        data_offer: &wl_data_offer::WlDataOffer,
1877        event: wl_data_offer::Event,
1878        _: &(),
1879        _: &Connection,
1880        _: &QueueHandle<Self>,
1881    ) {
1882        let client = this.get_client();
1883        let mut state = client.borrow_mut();
1884
1885        match event {
1886            wl_data_offer::Event::Offer { mime_type } => {
1887                // Drag and drop
1888                if mime_type == FILE_LIST_MIME_TYPE {
1889                    let serial = state.serial_tracker.get(SerialKind::DataDevice);
1890                    let mime_type = mime_type.clone();
1891                    data_offer.accept(serial, Some(mime_type));
1892                }
1893
1894                // Clipboard
1895                if let Some(offer) = state
1896                    .data_offers
1897                    .iter_mut()
1898                    .find(|wrapper| wrapper.inner.id() == data_offer.id())
1899                {
1900                    offer.add_mime_type(mime_type);
1901                }
1902            }
1903            _ => {}
1904        }
1905    }
1906}
1907
1908impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
1909    fn event(
1910        this: &mut Self,
1911        data_source: &wl_data_source::WlDataSource,
1912        event: wl_data_source::Event,
1913        _: &(),
1914        _: &Connection,
1915        _: &QueueHandle<Self>,
1916    ) {
1917        let client = this.get_client();
1918        let mut state = client.borrow_mut();
1919
1920        match event {
1921            wl_data_source::Event::Send { mime_type, fd } => {
1922                state.clipboard.send(mime_type, fd);
1923            }
1924            wl_data_source::Event::Cancelled => {
1925                data_source.destroy();
1926            }
1927            _ => {}
1928        }
1929    }
1930}
1931
1932impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
1933    for WaylandClientStatePtr
1934{
1935    fn event(
1936        this: &mut Self,
1937        _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
1938        event: zwp_primary_selection_device_v1::Event,
1939        _: &(),
1940        _: &Connection,
1941        _: &QueueHandle<Self>,
1942    ) {
1943        let client = this.get_client();
1944        let mut state = client.borrow_mut();
1945
1946        match event {
1947            zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
1948                let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
1949                if let Some(old_offer) = old_offer {
1950                    old_offer.inner.destroy();
1951                }
1952            }
1953            zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
1954                if data_offer.is_some() {
1955                    let offer = state.primary_data_offer.clone();
1956                    state.clipboard.set_primary_offer(offer);
1957                } else {
1958                    state.clipboard.set_primary_offer(None);
1959                }
1960            }
1961            _ => {}
1962        }
1963    }
1964
1965    event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
1966        zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
1967    ]);
1968}
1969
1970impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
1971    for WaylandClientStatePtr
1972{
1973    fn event(
1974        this: &mut Self,
1975        _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
1976        event: zwp_primary_selection_offer_v1::Event,
1977        _: &(),
1978        _: &Connection,
1979        _: &QueueHandle<Self>,
1980    ) {
1981        let client = this.get_client();
1982        let mut state = client.borrow_mut();
1983
1984        match event {
1985            zwp_primary_selection_offer_v1::Event::Offer { mime_type } => {
1986                if let Some(offer) = state.primary_data_offer.as_mut() {
1987                    offer.add_mime_type(mime_type);
1988                }
1989            }
1990            _ => {}
1991        }
1992    }
1993}
1994
1995impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
1996    for WaylandClientStatePtr
1997{
1998    fn event(
1999        this: &mut Self,
2000        selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2001        event: zwp_primary_selection_source_v1::Event,
2002        _: &(),
2003        _: &Connection,
2004        _: &QueueHandle<Self>,
2005    ) {
2006        let client = this.get_client();
2007        let mut state = client.borrow_mut();
2008
2009        match event {
2010            zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2011                state.clipboard.send_primary(mime_type, fd);
2012            }
2013            zwp_primary_selection_source_v1::Event::Cancelled => {
2014                selection_source.destroy();
2015            }
2016            _ => {}
2017        }
2018    }
2019}