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                // Prevent keyboard events from repeating after opening e.g. a file chooser and closing it quickly
1123                state.repeat.current_id += 1;
1124                state.clipboard.set_offer(None);
1125                state.clipboard.set_primary_offer(None);
1126
1127                if let Some(window) = keyboard_focused_window {
1128                    if let Some(ref mut compose) = state.compose_state {
1129                        compose.reset();
1130                    }
1131                    state.pre_edit_text.take();
1132                    drop(state);
1133                    window.handle_ime(ImeInput::DeleteText);
1134                    window.set_focused(false);
1135                }
1136            }
1137            wl_keyboard::Event::Modifiers {
1138                mods_depressed,
1139                mods_latched,
1140                mods_locked,
1141                group,
1142                ..
1143            } => {
1144                let focused_window = state.keyboard_focused_window.clone();
1145
1146                let keymap_state = state.keymap_state.as_mut().unwrap();
1147                keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1148                state.modifiers = Modifiers::from_xkb(keymap_state);
1149
1150                let Some(focused_window) = focused_window else {
1151                    return;
1152                };
1153
1154                let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1155                    modifiers: state.modifiers,
1156                });
1157
1158                drop(state);
1159                focused_window.handle_input(input);
1160            }
1161            wl_keyboard::Event::Key {
1162                serial,
1163                key,
1164                state: WEnum::Value(key_state),
1165                ..
1166            } => {
1167                state.serial_tracker.update(SerialKind::KeyPress, serial);
1168
1169                let focused_window = state.keyboard_focused_window.clone();
1170                let Some(focused_window) = focused_window else {
1171                    return;
1172                };
1173                let focused_window = focused_window.clone();
1174
1175                let keymap_state = state.keymap_state.as_ref().unwrap();
1176                let keycode = Keycode::from(key + MIN_KEYCODE);
1177                let keysym = keymap_state.key_get_one_sym(keycode);
1178
1179                match key_state {
1180                    wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
1181                        let mut keystroke =
1182                            Keystroke::from_xkb(&keymap_state, state.modifiers, keycode);
1183                        if let Some(mut compose) = state.compose_state.take() {
1184                            compose.feed(keysym);
1185                            match compose.status() {
1186                                xkb::Status::Composing => {
1187                                    keystroke.ime_key = None;
1188                                    state.pre_edit_text =
1189                                        compose.utf8().or(Keystroke::underlying_dead_key(keysym));
1190                                    let pre_edit =
1191                                        state.pre_edit_text.clone().unwrap_or(String::default());
1192                                    drop(state);
1193                                    focused_window.handle_ime(ImeInput::SetMarkedText(pre_edit));
1194                                    state = client.borrow_mut();
1195                                }
1196
1197                                xkb::Status::Composed => {
1198                                    state.pre_edit_text.take();
1199                                    keystroke.ime_key = compose.utf8();
1200                                    if let Some(keysym) = compose.keysym() {
1201                                        keystroke.key = xkb::keysym_get_name(keysym);
1202                                    }
1203                                }
1204                                xkb::Status::Cancelled => {
1205                                    let pre_edit = state.pre_edit_text.take();
1206                                    drop(state);
1207                                    if let Some(pre_edit) = pre_edit {
1208                                        focused_window.handle_ime(ImeInput::InsertText(pre_edit));
1209                                    }
1210                                    if let Some(current_key) =
1211                                        Keystroke::underlying_dead_key(keysym)
1212                                    {
1213                                        focused_window
1214                                            .handle_ime(ImeInput::SetMarkedText(current_key));
1215                                    }
1216                                    compose.feed(keysym);
1217                                    state = client.borrow_mut();
1218                                }
1219                                _ => {}
1220                            }
1221                            state.compose_state = Some(compose);
1222                        }
1223                        let input = PlatformInput::KeyDown(KeyDownEvent {
1224                            keystroke: keystroke.clone(),
1225                            is_held: false,
1226                        });
1227
1228                        state.repeat.current_id += 1;
1229                        state.repeat.current_keycode = Some(keycode);
1230
1231                        let rate = state.repeat.characters_per_second;
1232                        let id = state.repeat.current_id;
1233                        state
1234                            .loop_handle
1235                            .insert_source(Timer::from_duration(state.repeat.delay), {
1236                                let input = PlatformInput::KeyDown(KeyDownEvent {
1237                                    keystroke,
1238                                    is_held: true,
1239                                });
1240                                move |_event, _metadata, this| {
1241                                    let mut client = this.get_client();
1242                                    let mut state = client.borrow_mut();
1243                                    let is_repeating = id == state.repeat.current_id
1244                                        && state.repeat.current_keycode.is_some()
1245                                        && state.keyboard_focused_window.is_some();
1246
1247                                    if !is_repeating || rate == 0 {
1248                                        return TimeoutAction::Drop;
1249                                    }
1250
1251                                    let focused_window =
1252                                        state.keyboard_focused_window.as_ref().unwrap().clone();
1253
1254                                    drop(state);
1255                                    focused_window.handle_input(input.clone());
1256
1257                                    TimeoutAction::ToDuration(Duration::from_secs(1) / rate)
1258                                }
1259                            })
1260                            .unwrap();
1261
1262                        drop(state);
1263                        focused_window.handle_input(input);
1264                    }
1265                    wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
1266                        let input = PlatformInput::KeyUp(KeyUpEvent {
1267                            keystroke: Keystroke::from_xkb(keymap_state, state.modifiers, keycode),
1268                        });
1269
1270                        if state.repeat.current_keycode == Some(keycode) {
1271                            state.repeat.current_keycode = None;
1272                        }
1273
1274                        drop(state);
1275                        focused_window.handle_input(input);
1276                    }
1277                    _ => {}
1278                }
1279            }
1280            _ => {}
1281        }
1282    }
1283}
1284impl Dispatch<zwp_text_input_v3::ZwpTextInputV3, ()> for WaylandClientStatePtr {
1285    fn event(
1286        this: &mut Self,
1287        text_input: &zwp_text_input_v3::ZwpTextInputV3,
1288        event: <zwp_text_input_v3::ZwpTextInputV3 as Proxy>::Event,
1289        _: &(),
1290        _: &Connection,
1291        _: &QueueHandle<Self>,
1292    ) {
1293        let client = this.get_client();
1294        let mut state = client.borrow_mut();
1295        match event {
1296            zwp_text_input_v3::Event::Enter { .. } => {
1297                drop(state);
1298                this.enable_ime();
1299            }
1300            zwp_text_input_v3::Event::Leave { .. } => {
1301                drop(state);
1302                this.disable_ime();
1303            }
1304            zwp_text_input_v3::Event::CommitString { text } => {
1305                state.composing = false;
1306                let Some(window) = state.keyboard_focused_window.clone() else {
1307                    return;
1308                };
1309
1310                if let Some(commit_text) = text {
1311                    drop(state);
1312                    // IBus Intercepts keys like `a`, `b`, but those keys are needed for vim mode.
1313                    // We should only send ASCII characters to Zed, otherwise a user could remap a letter like `か` or `相`.
1314                    if commit_text.len() == 1 {
1315                        window.handle_input(PlatformInput::KeyDown(KeyDownEvent {
1316                            keystroke: Keystroke {
1317                                modifiers: Modifiers::default(),
1318                                key: commit_text.clone(),
1319                                ime_key: Some(commit_text),
1320                            },
1321                            is_held: false,
1322                        }));
1323                    } else {
1324                        window.handle_ime(ImeInput::InsertText(commit_text));
1325                    }
1326                }
1327            }
1328            zwp_text_input_v3::Event::PreeditString { text, .. } => {
1329                state.composing = true;
1330                state.pre_edit_text = text;
1331            }
1332            zwp_text_input_v3::Event::Done { serial } => {
1333                let last_serial = state.serial_tracker.get(SerialKind::InputMethod);
1334                state.serial_tracker.update(SerialKind::InputMethod, serial);
1335                let Some(window) = state.keyboard_focused_window.clone() else {
1336                    return;
1337                };
1338
1339                if let Some(text) = state.pre_edit_text.take() {
1340                    drop(state);
1341                    window.handle_ime(ImeInput::SetMarkedText(text));
1342                    if let Some(area) = window.get_ime_area() {
1343                        text_input.set_cursor_rectangle(
1344                            area.origin.x.0 as i32,
1345                            area.origin.y.0 as i32,
1346                            area.size.width.0 as i32,
1347                            area.size.height.0 as i32,
1348                        );
1349                        if last_serial == serial {
1350                            text_input.commit();
1351                        }
1352                    }
1353                } else {
1354                    drop(state);
1355                    window.handle_ime(ImeInput::DeleteText);
1356                }
1357            }
1358            _ => {}
1359        }
1360    }
1361}
1362
1363fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
1364    // These values are coming from <linux/input-event-codes.h>.
1365    const BTN_LEFT: u32 = 0x110;
1366    const BTN_RIGHT: u32 = 0x111;
1367    const BTN_MIDDLE: u32 = 0x112;
1368    const BTN_SIDE: u32 = 0x113;
1369    const BTN_EXTRA: u32 = 0x114;
1370    const BTN_FORWARD: u32 = 0x115;
1371    const BTN_BACK: u32 = 0x116;
1372
1373    Some(match button {
1374        BTN_LEFT => MouseButton::Left,
1375        BTN_RIGHT => MouseButton::Right,
1376        BTN_MIDDLE => MouseButton::Middle,
1377        BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
1378        BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
1379        _ => return None,
1380    })
1381}
1382
1383impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
1384    fn event(
1385        this: &mut Self,
1386        wl_pointer: &wl_pointer::WlPointer,
1387        event: wl_pointer::Event,
1388        _: &(),
1389        _: &Connection,
1390        _: &QueueHandle<Self>,
1391    ) {
1392        let mut client = this.get_client();
1393        let mut state = client.borrow_mut();
1394
1395        match event {
1396            wl_pointer::Event::Enter {
1397                serial,
1398                surface,
1399                surface_x,
1400                surface_y,
1401                ..
1402            } => {
1403                state.serial_tracker.update(SerialKind::MouseEnter, serial);
1404                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1405                state.button_pressed = None;
1406
1407                if let Some(window) = get_window(&mut state, &surface.id()) {
1408                    state.mouse_focused_window = Some(window.clone());
1409
1410                    if state.enter_token.is_some() {
1411                        state.enter_token = None;
1412                    }
1413                    if let Some(style) = state.cursor_style {
1414                        if let Some(cursor_shape_device) = &state.cursor_shape_device {
1415                            cursor_shape_device.set_shape(serial, style.to_shape());
1416                        } else {
1417                            state
1418                                .cursor
1419                                .set_icon(&wl_pointer, serial, &style.to_icon_name());
1420                        }
1421                    }
1422                    drop(state);
1423                    window.set_hovered(true);
1424                }
1425            }
1426            wl_pointer::Event::Leave { .. } => {
1427                if let Some(focused_window) = state.mouse_focused_window.clone() {
1428                    let input = PlatformInput::MouseExited(MouseExitEvent {
1429                        position: state.mouse_location.unwrap(),
1430                        pressed_button: state.button_pressed,
1431                        modifiers: state.modifiers,
1432                    });
1433                    state.mouse_focused_window = None;
1434                    state.mouse_location = None;
1435                    state.button_pressed = None;
1436
1437                    drop(state);
1438                    focused_window.handle_input(input);
1439                    focused_window.set_hovered(false);
1440                }
1441            }
1442            wl_pointer::Event::Motion {
1443                surface_x,
1444                surface_y,
1445                ..
1446            } => {
1447                if state.mouse_focused_window.is_none() {
1448                    return;
1449                }
1450                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1451
1452                if let Some(window) = state.mouse_focused_window.clone() {
1453                    if state
1454                        .keyboard_focused_window
1455                        .as_ref()
1456                        .map_or(false, |keyboard_window| window.ptr_eq(&keyboard_window))
1457                    {
1458                        state.enter_token = None;
1459                    }
1460                    let input = PlatformInput::MouseMove(MouseMoveEvent {
1461                        position: state.mouse_location.unwrap(),
1462                        pressed_button: state.button_pressed,
1463                        modifiers: state.modifiers,
1464                    });
1465                    drop(state);
1466                    window.handle_input(input);
1467                }
1468            }
1469            wl_pointer::Event::Button {
1470                serial,
1471                button,
1472                state: WEnum::Value(button_state),
1473                ..
1474            } => {
1475                state.serial_tracker.update(SerialKind::MousePress, serial);
1476                let button = linux_button_to_gpui(button);
1477                let Some(button) = button else { return };
1478                if state.mouse_focused_window.is_none() {
1479                    return;
1480                }
1481                match button_state {
1482                    wl_pointer::ButtonState::Pressed => {
1483                        if let Some(window) = state.keyboard_focused_window.clone() {
1484                            if state.composing && state.text_input.is_some() {
1485                                drop(state);
1486                                // text_input_v3 don't have something like a reset function
1487                                this.disable_ime();
1488                                this.enable_ime();
1489                                window.handle_ime(ImeInput::UnmarkText);
1490                                state = client.borrow_mut();
1491                            } else if let (Some(text), Some(compose)) =
1492                                (state.pre_edit_text.take(), state.compose_state.as_mut())
1493                            {
1494                                compose.reset();
1495                                drop(state);
1496                                window.handle_ime(ImeInput::InsertText(text));
1497                                state = client.borrow_mut();
1498                            }
1499                        }
1500                        let click_elapsed = state.click.last_click.elapsed();
1501
1502                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1503                            && is_within_click_distance(
1504                                state.click.last_location,
1505                                state.mouse_location.unwrap(),
1506                            )
1507                        {
1508                            state.click.current_count += 1;
1509                        } else {
1510                            state.click.current_count = 1;
1511                        }
1512
1513                        state.click.last_click = Instant::now();
1514                        state.click.last_location = state.mouse_location.unwrap();
1515
1516                        state.button_pressed = Some(button);
1517
1518                        if let Some(window) = state.mouse_focused_window.clone() {
1519                            let input = PlatformInput::MouseDown(MouseDownEvent {
1520                                button,
1521                                position: state.mouse_location.unwrap(),
1522                                modifiers: state.modifiers,
1523                                click_count: state.click.current_count,
1524                                first_mouse: state.enter_token.take().is_some(),
1525                            });
1526                            drop(state);
1527                            window.handle_input(input);
1528                        }
1529                    }
1530                    wl_pointer::ButtonState::Released => {
1531                        state.button_pressed = None;
1532
1533                        if let Some(window) = state.mouse_focused_window.clone() {
1534                            let input = PlatformInput::MouseUp(MouseUpEvent {
1535                                button,
1536                                position: state.mouse_location.unwrap(),
1537                                modifiers: state.modifiers,
1538                                click_count: state.click.current_count,
1539                            });
1540                            drop(state);
1541                            window.handle_input(input);
1542                        }
1543                    }
1544                    _ => {}
1545                }
1546            }
1547
1548            // Axis Events
1549            wl_pointer::Event::AxisSource {
1550                axis_source: WEnum::Value(axis_source),
1551            } => {
1552                state.axis_source = axis_source;
1553            }
1554            wl_pointer::Event::Axis {
1555                axis: WEnum::Value(axis),
1556                value,
1557                ..
1558            } => {
1559                if state.axis_source == AxisSource::Wheel {
1560                    return;
1561                }
1562                let axis = if state.modifiers.shift {
1563                    wl_pointer::Axis::HorizontalScroll
1564                } else {
1565                    axis
1566                };
1567                let axis_modifier = match axis {
1568                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1569                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1570                    _ => 1.0,
1571                };
1572                state.scroll_event_received = true;
1573                let scroll_delta = state
1574                    .continuous_scroll_delta
1575                    .get_or_insert(point(px(0.0), px(0.0)));
1576                let modifier = 3.0;
1577                match axis {
1578                    wl_pointer::Axis::VerticalScroll => {
1579                        scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1580                    }
1581                    wl_pointer::Axis::HorizontalScroll => {
1582                        scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1583                    }
1584                    _ => unreachable!(),
1585                }
1586            }
1587            wl_pointer::Event::AxisDiscrete {
1588                axis: WEnum::Value(axis),
1589                discrete,
1590            } => {
1591                state.scroll_event_received = true;
1592                let axis = if state.modifiers.shift {
1593                    wl_pointer::Axis::HorizontalScroll
1594                } else {
1595                    axis
1596                };
1597                let axis_modifier = match axis {
1598                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1599                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1600                    _ => 1.0,
1601                };
1602
1603                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1604                match axis {
1605                    wl_pointer::Axis::VerticalScroll => {
1606                        scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES as f32;
1607                    }
1608                    wl_pointer::Axis::HorizontalScroll => {
1609                        scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES as f32;
1610                    }
1611                    _ => unreachable!(),
1612                }
1613            }
1614            wl_pointer::Event::AxisValue120 {
1615                axis: WEnum::Value(axis),
1616                value120,
1617            } => {
1618                state.scroll_event_received = true;
1619                let axis = if state.modifiers.shift {
1620                    wl_pointer::Axis::HorizontalScroll
1621                } else {
1622                    axis
1623                };
1624                let axis_modifier = match axis {
1625                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1626                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1627                    _ => unreachable!(),
1628                };
1629
1630                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1631                let wheel_percent = value120 as f32 / 120.0;
1632                match axis {
1633                    wl_pointer::Axis::VerticalScroll => {
1634                        scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES as f32;
1635                    }
1636                    wl_pointer::Axis::HorizontalScroll => {
1637                        scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES as f32;
1638                    }
1639                    _ => unreachable!(),
1640                }
1641            }
1642            wl_pointer::Event::Frame => {
1643                if state.scroll_event_received {
1644                    state.scroll_event_received = false;
1645                    let continuous = state.continuous_scroll_delta.take();
1646                    let discrete = state.discrete_scroll_delta.take();
1647                    if let Some(continuous) = continuous {
1648                        if let Some(window) = state.mouse_focused_window.clone() {
1649                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1650                                position: state.mouse_location.unwrap(),
1651                                delta: ScrollDelta::Pixels(continuous),
1652                                modifiers: state.modifiers,
1653                                touch_phase: TouchPhase::Moved,
1654                            });
1655                            drop(state);
1656                            window.handle_input(input);
1657                        }
1658                    } else if let Some(discrete) = discrete {
1659                        if let Some(window) = state.mouse_focused_window.clone() {
1660                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1661                                position: state.mouse_location.unwrap(),
1662                                delta: ScrollDelta::Lines(discrete),
1663                                modifiers: state.modifiers,
1664                                touch_phase: TouchPhase::Moved,
1665                            });
1666                            drop(state);
1667                            window.handle_input(input);
1668                        }
1669                    }
1670                }
1671            }
1672            _ => {}
1673        }
1674    }
1675}
1676
1677impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1678    fn event(
1679        this: &mut Self,
1680        _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1681        event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1682        surface_id: &ObjectId,
1683        _: &Connection,
1684        _: &QueueHandle<Self>,
1685    ) {
1686        let client = this.get_client();
1687        let mut state = client.borrow_mut();
1688
1689        let Some(window) = get_window(&mut state, surface_id) else {
1690            return;
1691        };
1692
1693        drop(state);
1694        window.handle_fractional_scale_event(event);
1695    }
1696}
1697
1698impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1699    for WaylandClientStatePtr
1700{
1701    fn event(
1702        this: &mut Self,
1703        _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1704        event: zxdg_toplevel_decoration_v1::Event,
1705        surface_id: &ObjectId,
1706        _: &Connection,
1707        _: &QueueHandle<Self>,
1708    ) {
1709        let client = this.get_client();
1710        let mut state = client.borrow_mut();
1711        let Some(window) = get_window(&mut state, surface_id) else {
1712            return;
1713        };
1714
1715        drop(state);
1716        window.handle_toplevel_decoration_event(event);
1717    }
1718}
1719
1720impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1721    fn event(
1722        this: &mut Self,
1723        _: &wl_data_device::WlDataDevice,
1724        event: wl_data_device::Event,
1725        _: &(),
1726        _: &Connection,
1727        _: &QueueHandle<Self>,
1728    ) {
1729        let client = this.get_client();
1730        let mut state = client.borrow_mut();
1731
1732        match event {
1733            // Clipboard
1734            wl_data_device::Event::DataOffer { id: data_offer } => {
1735                state.data_offers.push(DataOffer::new(data_offer));
1736                if state.data_offers.len() > 2 {
1737                    // At most we store a clipboard offer and a drag and drop offer.
1738                    state.data_offers.remove(0).inner.destroy();
1739                }
1740            }
1741            wl_data_device::Event::Selection { id: data_offer } => {
1742                if let Some(offer) = data_offer {
1743                    let offer = state
1744                        .data_offers
1745                        .iter()
1746                        .find(|wrapper| wrapper.inner.id() == offer.id());
1747                    let offer = offer.cloned();
1748                    state.clipboard.set_offer(offer);
1749                } else {
1750                    state.clipboard.set_offer(None);
1751                }
1752            }
1753
1754            // Drag and drop
1755            wl_data_device::Event::Enter {
1756                serial,
1757                surface,
1758                x,
1759                y,
1760                id: data_offer,
1761            } => {
1762                state.serial_tracker.update(SerialKind::DataDevice, serial);
1763                if let Some(data_offer) = data_offer {
1764                    let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1765                        return;
1766                    };
1767
1768                    const ACTIONS: DndAction = DndAction::Copy;
1769                    data_offer.set_actions(ACTIONS, ACTIONS);
1770
1771                    let pipe = Pipe::new().unwrap();
1772                    data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1773                        BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1774                    });
1775                    let fd = pipe.read;
1776                    drop(pipe.write);
1777
1778                    let read_task = state
1779                        .common
1780                        .background_executor
1781                        .spawn(async { unsafe { read_fd(fd) } });
1782
1783                    let this = this.clone();
1784                    state
1785                        .common
1786                        .foreground_executor
1787                        .spawn(async move {
1788                            let file_list = match read_task.await {
1789                                Ok(list) => list,
1790                                Err(err) => {
1791                                    log::error!("error reading drag and drop pipe: {err:?}");
1792                                    return;
1793                                }
1794                            };
1795
1796                            let paths: SmallVec<[_; 2]> = file_list
1797                                .lines()
1798                                .map(|path| PathBuf::from(path.replace("file://", "")))
1799                                .collect();
1800                            let position = Point::new(x.into(), y.into());
1801
1802                            // Prevent dropping text from other programs.
1803                            if paths.is_empty() {
1804                                data_offer.finish();
1805                                data_offer.destroy();
1806                                return;
1807                            }
1808
1809                            let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1810                                position,
1811                                paths: crate::ExternalPaths(paths),
1812                            });
1813
1814                            let client = this.get_client();
1815                            let mut state = client.borrow_mut();
1816                            state.drag.data_offer = Some(data_offer);
1817                            state.drag.window = Some(drag_window.clone());
1818                            state.drag.position = position;
1819
1820                            drop(state);
1821                            drag_window.handle_input(input);
1822                        })
1823                        .detach();
1824                }
1825            }
1826            wl_data_device::Event::Motion { x, y, .. } => {
1827                let Some(drag_window) = state.drag.window.clone() else {
1828                    return;
1829                };
1830                let position = Point::new(x.into(), y.into());
1831                state.drag.position = position;
1832
1833                let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
1834                drop(state);
1835                drag_window.handle_input(input);
1836            }
1837            wl_data_device::Event::Leave => {
1838                let Some(drag_window) = state.drag.window.clone() else {
1839                    return;
1840                };
1841                let data_offer = state.drag.data_offer.clone().unwrap();
1842                data_offer.destroy();
1843
1844                state.drag.data_offer = None;
1845                state.drag.window = None;
1846
1847                let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
1848                drop(state);
1849                drag_window.handle_input(input);
1850            }
1851            wl_data_device::Event::Drop => {
1852                let Some(drag_window) = state.drag.window.clone() else {
1853                    return;
1854                };
1855                let data_offer = state.drag.data_offer.clone().unwrap();
1856                data_offer.finish();
1857                data_offer.destroy();
1858
1859                state.drag.data_offer = None;
1860                state.drag.window = None;
1861
1862                let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1863                    position: state.drag.position,
1864                });
1865                drop(state);
1866                drag_window.handle_input(input);
1867            }
1868            _ => {}
1869        }
1870    }
1871
1872    event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
1873        wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
1874    ]);
1875}
1876
1877impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
1878    fn event(
1879        this: &mut Self,
1880        data_offer: &wl_data_offer::WlDataOffer,
1881        event: wl_data_offer::Event,
1882        _: &(),
1883        _: &Connection,
1884        _: &QueueHandle<Self>,
1885    ) {
1886        let client = this.get_client();
1887        let mut state = client.borrow_mut();
1888
1889        match event {
1890            wl_data_offer::Event::Offer { mime_type } => {
1891                // Drag and drop
1892                if mime_type == FILE_LIST_MIME_TYPE {
1893                    let serial = state.serial_tracker.get(SerialKind::DataDevice);
1894                    let mime_type = mime_type.clone();
1895                    data_offer.accept(serial, Some(mime_type));
1896                }
1897
1898                // Clipboard
1899                if let Some(offer) = state
1900                    .data_offers
1901                    .iter_mut()
1902                    .find(|wrapper| wrapper.inner.id() == data_offer.id())
1903                {
1904                    offer.add_mime_type(mime_type);
1905                }
1906            }
1907            _ => {}
1908        }
1909    }
1910}
1911
1912impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
1913    fn event(
1914        this: &mut Self,
1915        data_source: &wl_data_source::WlDataSource,
1916        event: wl_data_source::Event,
1917        _: &(),
1918        _: &Connection,
1919        _: &QueueHandle<Self>,
1920    ) {
1921        let client = this.get_client();
1922        let mut state = client.borrow_mut();
1923
1924        match event {
1925            wl_data_source::Event::Send { mime_type, fd } => {
1926                state.clipboard.send(mime_type, fd);
1927            }
1928            wl_data_source::Event::Cancelled => {
1929                data_source.destroy();
1930            }
1931            _ => {}
1932        }
1933    }
1934}
1935
1936impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
1937    for WaylandClientStatePtr
1938{
1939    fn event(
1940        this: &mut Self,
1941        _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
1942        event: zwp_primary_selection_device_v1::Event,
1943        _: &(),
1944        _: &Connection,
1945        _: &QueueHandle<Self>,
1946    ) {
1947        let client = this.get_client();
1948        let mut state = client.borrow_mut();
1949
1950        match event {
1951            zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
1952                let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
1953                if let Some(old_offer) = old_offer {
1954                    old_offer.inner.destroy();
1955                }
1956            }
1957            zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
1958                if data_offer.is_some() {
1959                    let offer = state.primary_data_offer.clone();
1960                    state.clipboard.set_primary_offer(offer);
1961                } else {
1962                    state.clipboard.set_primary_offer(None);
1963                }
1964            }
1965            _ => {}
1966        }
1967    }
1968
1969    event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
1970        zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
1971    ]);
1972}
1973
1974impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
1975    for WaylandClientStatePtr
1976{
1977    fn event(
1978        this: &mut Self,
1979        _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
1980        event: zwp_primary_selection_offer_v1::Event,
1981        _: &(),
1982        _: &Connection,
1983        _: &QueueHandle<Self>,
1984    ) {
1985        let client = this.get_client();
1986        let mut state = client.borrow_mut();
1987
1988        match event {
1989            zwp_primary_selection_offer_v1::Event::Offer { mime_type } => {
1990                if let Some(offer) = state.primary_data_offer.as_mut() {
1991                    offer.add_mime_type(mime_type);
1992                }
1993            }
1994            _ => {}
1995        }
1996    }
1997}
1998
1999impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2000    for WaylandClientStatePtr
2001{
2002    fn event(
2003        this: &mut Self,
2004        selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2005        event: zwp_primary_selection_source_v1::Event,
2006        _: &(),
2007        _: &Connection,
2008        _: &QueueHandle<Self>,
2009    ) {
2010        let client = this.get_client();
2011        let mut state = client.borrow_mut();
2012
2013        match event {
2014            zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2015                state.clipboard.send_primary(mime_type, fd);
2016            }
2017            zwp_primary_selection_source_v1::Event::Cancelled => {
2018                selection_source.destroy();
2019            }
2020            _ => {}
2021        }
2022    }
2023}