client.rs

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