client.rs

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