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