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