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        let mut cursor = Cursor::new(&conn, &globals, 24);
 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());
 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_mouse_button: None,
 539                last_location: Point::default(),
 540                current_count: 0,
 541            },
 542            repeat: KeyRepeat {
 543                characters_per_second: 16,
 544                delay: Duration::from_millis(500),
 545                current_id: 0,
 546                current_keycode: None,
 547            },
 548            modifiers: Modifiers {
 549                shift: false,
 550                control: false,
 551                alt: false,
 552                function: false,
 553                platform: false,
 554            },
 555            scroll_event_received: false,
 556            axis_source: AxisSource::Wheel,
 557            mouse_location: None,
 558            continuous_scroll_delta: None,
 559            discrete_scroll_delta: None,
 560            vertical_modifier: -1.0,
 561            horizontal_modifier: -1.0,
 562            button_pressed: None,
 563            mouse_focused_window: None,
 564            keyboard_focused_window: None,
 565            loop_handle: handle.clone(),
 566            enter_token: None,
 567            cursor_style: None,
 568            clipboard: Clipboard::new(conn.clone(), handle.clone()),
 569            data_offers: Vec::new(),
 570            primary_data_offer: None,
 571            cursor,
 572            pending_activation: None,
 573            event_loop: Some(event_loop),
 574        }));
 575
 576        WaylandSource::new(conn, event_queue)
 577            .insert(handle)
 578            .unwrap();
 579
 580        Self(state)
 581    }
 582}
 583
 584impl LinuxClient for WaylandClient {
 585    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 586        self.0
 587            .borrow()
 588            .outputs
 589            .iter()
 590            .map(|(id, output)| {
 591                Rc::new(WaylandDisplay {
 592                    id: id.clone(),
 593                    name: output.name.clone(),
 594                    bounds: output.bounds.to_pixels(output.scale as f32),
 595                }) as Rc<dyn PlatformDisplay>
 596            })
 597            .collect()
 598    }
 599
 600    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 601        self.0
 602            .borrow()
 603            .outputs
 604            .iter()
 605            .find_map(|(object_id, output)| {
 606                (object_id.protocol_id() == id.0).then(|| {
 607                    Rc::new(WaylandDisplay {
 608                        id: object_id.clone(),
 609                        name: output.name.clone(),
 610                        bounds: output.bounds.to_pixels(output.scale as f32),
 611                    }) as Rc<dyn PlatformDisplay>
 612                })
 613            })
 614    }
 615
 616    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 617        None
 618    }
 619
 620    fn open_window(
 621        &self,
 622        handle: AnyWindowHandle,
 623        params: WindowParams,
 624    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
 625        let mut state = self.0.borrow_mut();
 626
 627        let (window, surface_id) = WaylandWindow::new(
 628            handle,
 629            state.globals.clone(),
 630            WaylandClientStatePtr(Rc::downgrade(&self.0)),
 631            params,
 632            state.common.appearance,
 633        )?;
 634        state.windows.insert(surface_id, window.0.clone());
 635
 636        Ok(Box::new(window))
 637    }
 638
 639    fn set_cursor_style(&self, style: CursorStyle) {
 640        let mut state = self.0.borrow_mut();
 641
 642        let need_update = state
 643            .cursor_style
 644            .map_or(true, |current_style| current_style != style);
 645
 646        if need_update {
 647            let serial = state.serial_tracker.get(SerialKind::MouseEnter);
 648            state.cursor_style = Some(style);
 649
 650            if let Some(cursor_shape_device) = &state.cursor_shape_device {
 651                cursor_shape_device.set_shape(serial, style.to_shape());
 652            } else if let Some(focused_window) = &state.mouse_focused_window {
 653                // cursor-shape-v1 isn't supported, set the cursor using a surface.
 654                let wl_pointer = state
 655                    .wl_pointer
 656                    .clone()
 657                    .expect("window is focused by pointer");
 658                let scale = focused_window.primary_output_scale();
 659                state
 660                    .cursor
 661                    .set_icon(&wl_pointer, serial, &style.to_icon_name(), scale);
 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.key_char = 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.key_char = 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                                key_char: 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                            let scale = window.primary_output_scale();
1444                            state.cursor.set_icon(
1445                                &wl_pointer,
1446                                serial,
1447                                &style.to_icon_name(),
1448                                scale,
1449                            );
1450                        }
1451                    }
1452                    drop(state);
1453                    window.set_hovered(true);
1454                }
1455            }
1456            wl_pointer::Event::Leave { .. } => {
1457                if let Some(focused_window) = state.mouse_focused_window.clone() {
1458                    let input = PlatformInput::MouseExited(MouseExitEvent {
1459                        position: state.mouse_location.unwrap(),
1460                        pressed_button: state.button_pressed,
1461                        modifiers: state.modifiers,
1462                    });
1463                    state.mouse_focused_window = None;
1464                    state.mouse_location = None;
1465                    state.button_pressed = None;
1466
1467                    drop(state);
1468                    focused_window.handle_input(input);
1469                    focused_window.set_hovered(false);
1470                }
1471            }
1472            wl_pointer::Event::Motion {
1473                surface_x,
1474                surface_y,
1475                ..
1476            } => {
1477                if state.mouse_focused_window.is_none() {
1478                    return;
1479                }
1480                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1481
1482                if let Some(window) = state.mouse_focused_window.clone() {
1483                    if state
1484                        .keyboard_focused_window
1485                        .as_ref()
1486                        .map_or(false, |keyboard_window| window.ptr_eq(&keyboard_window))
1487                    {
1488                        state.enter_token = None;
1489                    }
1490                    let input = PlatformInput::MouseMove(MouseMoveEvent {
1491                        position: state.mouse_location.unwrap(),
1492                        pressed_button: state.button_pressed,
1493                        modifiers: state.modifiers,
1494                    });
1495                    drop(state);
1496                    window.handle_input(input);
1497                }
1498            }
1499            wl_pointer::Event::Button {
1500                serial,
1501                button,
1502                state: WEnum::Value(button_state),
1503                ..
1504            } => {
1505                state.serial_tracker.update(SerialKind::MousePress, serial);
1506                let button = linux_button_to_gpui(button);
1507                let Some(button) = button else { return };
1508                if state.mouse_focused_window.is_none() {
1509                    return;
1510                }
1511                match button_state {
1512                    wl_pointer::ButtonState::Pressed => {
1513                        if let Some(window) = state.keyboard_focused_window.clone() {
1514                            if state.composing && state.text_input.is_some() {
1515                                drop(state);
1516                                // text_input_v3 don't have something like a reset function
1517                                this.disable_ime();
1518                                this.enable_ime();
1519                                window.handle_ime(ImeInput::UnmarkText);
1520                                state = client.borrow_mut();
1521                            } else if let (Some(text), Some(compose)) =
1522                                (state.pre_edit_text.take(), state.compose_state.as_mut())
1523                            {
1524                                compose.reset();
1525                                drop(state);
1526                                window.handle_ime(ImeInput::InsertText(text));
1527                                state = client.borrow_mut();
1528                            }
1529                        }
1530                        let click_elapsed = state.click.last_click.elapsed();
1531
1532                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1533                            && state
1534                                .click
1535                                .last_mouse_button
1536                                .is_some_and(|prev_button| prev_button == button)
1537                            && is_within_click_distance(
1538                                state.click.last_location,
1539                                state.mouse_location.unwrap(),
1540                            )
1541                        {
1542                            state.click.current_count += 1;
1543                        } else {
1544                            state.click.current_count = 1;
1545                        }
1546
1547                        state.click.last_click = Instant::now();
1548                        state.click.last_mouse_button = Some(button);
1549                        state.click.last_location = state.mouse_location.unwrap();
1550
1551                        state.button_pressed = Some(button);
1552
1553                        if let Some(window) = state.mouse_focused_window.clone() {
1554                            let input = PlatformInput::MouseDown(MouseDownEvent {
1555                                button,
1556                                position: state.mouse_location.unwrap(),
1557                                modifiers: state.modifiers,
1558                                click_count: state.click.current_count,
1559                                first_mouse: state.enter_token.take().is_some(),
1560                            });
1561                            drop(state);
1562                            window.handle_input(input);
1563                        }
1564                    }
1565                    wl_pointer::ButtonState::Released => {
1566                        state.button_pressed = None;
1567
1568                        if let Some(window) = state.mouse_focused_window.clone() {
1569                            let input = PlatformInput::MouseUp(MouseUpEvent {
1570                                button,
1571                                position: state.mouse_location.unwrap(),
1572                                modifiers: state.modifiers,
1573                                click_count: state.click.current_count,
1574                            });
1575                            drop(state);
1576                            window.handle_input(input);
1577                        }
1578                    }
1579                    _ => {}
1580                }
1581            }
1582
1583            // Axis Events
1584            wl_pointer::Event::AxisSource {
1585                axis_source: WEnum::Value(axis_source),
1586            } => {
1587                state.axis_source = axis_source;
1588            }
1589            wl_pointer::Event::Axis {
1590                axis: WEnum::Value(axis),
1591                value,
1592                ..
1593            } => {
1594                if state.axis_source == AxisSource::Wheel {
1595                    return;
1596                }
1597                let axis = if state.modifiers.shift {
1598                    wl_pointer::Axis::HorizontalScroll
1599                } else {
1600                    axis
1601                };
1602                let axis_modifier = match axis {
1603                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1604                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1605                    _ => 1.0,
1606                };
1607                state.scroll_event_received = true;
1608                let scroll_delta = state
1609                    .continuous_scroll_delta
1610                    .get_or_insert(point(px(0.0), px(0.0)));
1611                let modifier = 3.0;
1612                match axis {
1613                    wl_pointer::Axis::VerticalScroll => {
1614                        scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1615                    }
1616                    wl_pointer::Axis::HorizontalScroll => {
1617                        scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1618                    }
1619                    _ => unreachable!(),
1620                }
1621            }
1622            wl_pointer::Event::AxisDiscrete {
1623                axis: WEnum::Value(axis),
1624                discrete,
1625            } => {
1626                state.scroll_event_received = true;
1627                let axis = if state.modifiers.shift {
1628                    wl_pointer::Axis::HorizontalScroll
1629                } else {
1630                    axis
1631                };
1632                let axis_modifier = match axis {
1633                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1634                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1635                    _ => 1.0,
1636                };
1637
1638                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1639                match axis {
1640                    wl_pointer::Axis::VerticalScroll => {
1641                        scroll_delta.y += discrete as f32 * axis_modifier * SCROLL_LINES;
1642                    }
1643                    wl_pointer::Axis::HorizontalScroll => {
1644                        scroll_delta.x += discrete as f32 * axis_modifier * SCROLL_LINES;
1645                    }
1646                    _ => unreachable!(),
1647                }
1648            }
1649            wl_pointer::Event::AxisValue120 {
1650                axis: WEnum::Value(axis),
1651                value120,
1652            } => {
1653                state.scroll_event_received = true;
1654                let axis = if state.modifiers.shift {
1655                    wl_pointer::Axis::HorizontalScroll
1656                } else {
1657                    axis
1658                };
1659                let axis_modifier = match axis {
1660                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1661                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1662                    _ => unreachable!(),
1663                };
1664
1665                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1666                let wheel_percent = value120 as f32 / 120.0;
1667                match axis {
1668                    wl_pointer::Axis::VerticalScroll => {
1669                        scroll_delta.y += wheel_percent * axis_modifier * SCROLL_LINES;
1670                    }
1671                    wl_pointer::Axis::HorizontalScroll => {
1672                        scroll_delta.x += wheel_percent * axis_modifier * SCROLL_LINES;
1673                    }
1674                    _ => unreachable!(),
1675                }
1676            }
1677            wl_pointer::Event::Frame => {
1678                if state.scroll_event_received {
1679                    state.scroll_event_received = false;
1680                    let continuous = state.continuous_scroll_delta.take();
1681                    let discrete = state.discrete_scroll_delta.take();
1682                    if let Some(continuous) = continuous {
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::Pixels(continuous),
1687                                modifiers: state.modifiers,
1688                                touch_phase: TouchPhase::Moved,
1689                            });
1690                            drop(state);
1691                            window.handle_input(input);
1692                        }
1693                    } else if let Some(discrete) = discrete {
1694                        if let Some(window) = state.mouse_focused_window.clone() {
1695                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1696                                position: state.mouse_location.unwrap(),
1697                                delta: ScrollDelta::Lines(discrete),
1698                                modifiers: state.modifiers,
1699                                touch_phase: TouchPhase::Moved,
1700                            });
1701                            drop(state);
1702                            window.handle_input(input);
1703                        }
1704                    }
1705                }
1706            }
1707            _ => {}
1708        }
1709    }
1710}
1711
1712impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1713    fn event(
1714        this: &mut Self,
1715        _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1716        event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1717        surface_id: &ObjectId,
1718        _: &Connection,
1719        _: &QueueHandle<Self>,
1720    ) {
1721        let client = this.get_client();
1722        let mut state = client.borrow_mut();
1723
1724        let Some(window) = get_window(&mut state, surface_id) else {
1725            return;
1726        };
1727
1728        drop(state);
1729        window.handle_fractional_scale_event(event);
1730    }
1731}
1732
1733impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1734    for WaylandClientStatePtr
1735{
1736    fn event(
1737        this: &mut Self,
1738        _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1739        event: zxdg_toplevel_decoration_v1::Event,
1740        surface_id: &ObjectId,
1741        _: &Connection,
1742        _: &QueueHandle<Self>,
1743    ) {
1744        let client = this.get_client();
1745        let mut state = client.borrow_mut();
1746        let Some(window) = get_window(&mut state, surface_id) else {
1747            return;
1748        };
1749
1750        drop(state);
1751        window.handle_toplevel_decoration_event(event);
1752    }
1753}
1754
1755impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1756    fn event(
1757        this: &mut Self,
1758        _: &wl_data_device::WlDataDevice,
1759        event: wl_data_device::Event,
1760        _: &(),
1761        _: &Connection,
1762        _: &QueueHandle<Self>,
1763    ) {
1764        let client = this.get_client();
1765        let mut state = client.borrow_mut();
1766
1767        match event {
1768            // Clipboard
1769            wl_data_device::Event::DataOffer { id: data_offer } => {
1770                state.data_offers.push(DataOffer::new(data_offer));
1771                if state.data_offers.len() > 2 {
1772                    // At most we store a clipboard offer and a drag and drop offer.
1773                    state.data_offers.remove(0).inner.destroy();
1774                }
1775            }
1776            wl_data_device::Event::Selection { id: data_offer } => {
1777                if let Some(offer) = data_offer {
1778                    let offer = state
1779                        .data_offers
1780                        .iter()
1781                        .find(|wrapper| wrapper.inner.id() == offer.id());
1782                    let offer = offer.cloned();
1783                    state.clipboard.set_offer(offer);
1784                } else {
1785                    state.clipboard.set_offer(None);
1786                }
1787            }
1788
1789            // Drag and drop
1790            wl_data_device::Event::Enter {
1791                serial,
1792                surface,
1793                x,
1794                y,
1795                id: data_offer,
1796            } => {
1797                state.serial_tracker.update(SerialKind::DataDevice, serial);
1798                if let Some(data_offer) = data_offer {
1799                    let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1800                        return;
1801                    };
1802
1803                    const ACTIONS: DndAction = DndAction::Copy;
1804                    data_offer.set_actions(ACTIONS, ACTIONS);
1805
1806                    let pipe = Pipe::new().unwrap();
1807                    data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1808                        BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1809                    });
1810                    let fd = pipe.read;
1811                    drop(pipe.write);
1812
1813                    let read_task = state.common.background_executor.spawn(async {
1814                        let buffer = unsafe { read_fd(fd)? };
1815                        let text = String::from_utf8(buffer)?;
1816                        anyhow::Ok(text)
1817                    });
1818
1819                    let this = this.clone();
1820                    state
1821                        .common
1822                        .foreground_executor
1823                        .spawn(async move {
1824                            let file_list = match read_task.await {
1825                                Ok(list) => list,
1826                                Err(err) => {
1827                                    log::error!("error reading drag and drop pipe: {err:?}");
1828                                    return;
1829                                }
1830                            };
1831
1832                            let paths: SmallVec<[_; 2]> = file_list
1833                                .lines()
1834                                .filter_map(|path| Url::parse(path).log_err())
1835                                .filter_map(|url| url.to_file_path().log_err())
1836                                .collect();
1837                            let position = Point::new(x.into(), y.into());
1838
1839                            // Prevent dropping text from other programs.
1840                            if paths.is_empty() {
1841                                data_offer.destroy();
1842                                return;
1843                            }
1844
1845                            let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1846                                position,
1847                                paths: crate::ExternalPaths(paths),
1848                            });
1849
1850                            let client = this.get_client();
1851                            let mut state = client.borrow_mut();
1852                            state.drag.data_offer = Some(data_offer);
1853                            state.drag.window = Some(drag_window.clone());
1854                            state.drag.position = position;
1855
1856                            drop(state);
1857                            drag_window.handle_input(input);
1858                        })
1859                        .detach();
1860                }
1861            }
1862            wl_data_device::Event::Motion { x, y, .. } => {
1863                let Some(drag_window) = state.drag.window.clone() else {
1864                    return;
1865                };
1866                let position = Point::new(x.into(), y.into());
1867                state.drag.position = position;
1868
1869                let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
1870                drop(state);
1871                drag_window.handle_input(input);
1872            }
1873            wl_data_device::Event::Leave => {
1874                let Some(drag_window) = state.drag.window.clone() else {
1875                    return;
1876                };
1877                let data_offer = state.drag.data_offer.clone().unwrap();
1878                data_offer.destroy();
1879
1880                state.drag.data_offer = None;
1881                state.drag.window = None;
1882
1883                let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
1884                drop(state);
1885                drag_window.handle_input(input);
1886            }
1887            wl_data_device::Event::Drop => {
1888                let Some(drag_window) = state.drag.window.clone() else {
1889                    return;
1890                };
1891                let data_offer = state.drag.data_offer.clone().unwrap();
1892                data_offer.finish();
1893                data_offer.destroy();
1894
1895                state.drag.data_offer = None;
1896                state.drag.window = None;
1897
1898                let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1899                    position: state.drag.position,
1900                });
1901                drop(state);
1902                drag_window.handle_input(input);
1903            }
1904            _ => {}
1905        }
1906    }
1907
1908    event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
1909        wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
1910    ]);
1911}
1912
1913impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
1914    fn event(
1915        this: &mut Self,
1916        data_offer: &wl_data_offer::WlDataOffer,
1917        event: wl_data_offer::Event,
1918        _: &(),
1919        _: &Connection,
1920        _: &QueueHandle<Self>,
1921    ) {
1922        let client = this.get_client();
1923        let mut state = client.borrow_mut();
1924
1925        match event {
1926            wl_data_offer::Event::Offer { mime_type } => {
1927                // Drag and drop
1928                if mime_type == FILE_LIST_MIME_TYPE {
1929                    let serial = state.serial_tracker.get(SerialKind::DataDevice);
1930                    let mime_type = mime_type.clone();
1931                    data_offer.accept(serial, Some(mime_type));
1932                }
1933
1934                // Clipboard
1935                if let Some(offer) = state
1936                    .data_offers
1937                    .iter_mut()
1938                    .find(|wrapper| wrapper.inner.id() == data_offer.id())
1939                {
1940                    offer.add_mime_type(mime_type);
1941                }
1942            }
1943            _ => {}
1944        }
1945    }
1946}
1947
1948impl Dispatch<wl_data_source::WlDataSource, ()> for WaylandClientStatePtr {
1949    fn event(
1950        this: &mut Self,
1951        data_source: &wl_data_source::WlDataSource,
1952        event: wl_data_source::Event,
1953        _: &(),
1954        _: &Connection,
1955        _: &QueueHandle<Self>,
1956    ) {
1957        let client = this.get_client();
1958        let mut state = client.borrow_mut();
1959
1960        match event {
1961            wl_data_source::Event::Send { mime_type, fd } => {
1962                state.clipboard.send(mime_type, fd);
1963            }
1964            wl_data_source::Event::Cancelled => {
1965                data_source.destroy();
1966            }
1967            _ => {}
1968        }
1969    }
1970}
1971
1972impl Dispatch<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, ()>
1973    for WaylandClientStatePtr
1974{
1975    fn event(
1976        this: &mut Self,
1977        _: &zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
1978        event: zwp_primary_selection_device_v1::Event,
1979        _: &(),
1980        _: &Connection,
1981        _: &QueueHandle<Self>,
1982    ) {
1983        let client = this.get_client();
1984        let mut state = client.borrow_mut();
1985
1986        match event {
1987            zwp_primary_selection_device_v1::Event::DataOffer { offer } => {
1988                let old_offer = state.primary_data_offer.replace(DataOffer::new(offer));
1989                if let Some(old_offer) = old_offer {
1990                    old_offer.inner.destroy();
1991                }
1992            }
1993            zwp_primary_selection_device_v1::Event::Selection { id: data_offer } => {
1994                if data_offer.is_some() {
1995                    let offer = state.primary_data_offer.clone();
1996                    state.clipboard.set_primary_offer(offer);
1997                } else {
1998                    state.clipboard.set_primary_offer(None);
1999                }
2000            }
2001            _ => {}
2002        }
2003    }
2004
2005    event_created_child!(WaylandClientStatePtr, zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1, [
2006        zwp_primary_selection_device_v1::EVT_DATA_OFFER_OPCODE => (zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()),
2007    ]);
2008}
2009
2010impl Dispatch<zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1, ()>
2011    for WaylandClientStatePtr
2012{
2013    fn event(
2014        this: &mut Self,
2015        _data_offer: &zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1,
2016        event: zwp_primary_selection_offer_v1::Event,
2017        _: &(),
2018        _: &Connection,
2019        _: &QueueHandle<Self>,
2020    ) {
2021        let client = this.get_client();
2022        let mut state = client.borrow_mut();
2023
2024        match event {
2025            zwp_primary_selection_offer_v1::Event::Offer { mime_type } => {
2026                if let Some(offer) = state.primary_data_offer.as_mut() {
2027                    offer.add_mime_type(mime_type);
2028                }
2029            }
2030            _ => {}
2031        }
2032    }
2033}
2034
2035impl Dispatch<zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1, ()>
2036    for WaylandClientStatePtr
2037{
2038    fn event(
2039        this: &mut Self,
2040        selection_source: &zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
2041        event: zwp_primary_selection_source_v1::Event,
2042        _: &(),
2043        _: &Connection,
2044        _: &QueueHandle<Self>,
2045    ) {
2046        let client = this.get_client();
2047        let mut state = client.borrow_mut();
2048
2049        match event {
2050            zwp_primary_selection_source_v1::Event::Send { mime_type, fd } => {
2051                state.clipboard.send_primary(mime_type, fd);
2052            }
2053            zwp_primary_selection_source_v1::Event::Cancelled => {
2054                selection_source.destroy();
2055            }
2056            _ => {}
2057        }
2058    }
2059}