client.rs

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