client.rs

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