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