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