client.rs

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