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 anyhow::anyhow;
  11use calloop::{
  12    EventLoop, LoopHandle,
  13    timer::{TimeoutAction, Timer},
  14};
  15use calloop_wayland_source::WaylandSource;
  16use collections::HashMap;
  17use filedescriptor::Pipe;
  18use futures::channel::oneshot;
  19use http_client::Url;
  20use smallvec::SmallVec;
  21use util::ResultExt;
  22use wayland_backend::client::ObjectId;
  23use wayland_backend::protocol::WEnum;
  24use wayland_client::event_created_child;
  25use wayland_client::globals::{GlobalList, GlobalListContents, registry_queue_init};
  26use wayland_client::protocol::wl_callback::{self, WlCallback};
  27use wayland_client::protocol::wl_data_device_manager::DndAction;
  28use wayland_client::protocol::wl_data_offer::WlDataOffer;
  29use wayland_client::protocol::wl_pointer::AxisSource;
  30use wayland_client::protocol::{
  31    wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_output, wl_region,
  32};
  33use wayland_client::{
  34    Connection, Dispatch, Proxy, QueueHandle, delegate_noop,
  35    protocol::{
  36        wl_buffer, wl_compositor, wl_keyboard, wl_pointer, wl_registry, wl_seat, wl_shm,
  37        wl_shm_pool, wl_surface,
  38    },
  39};
  40use wayland_protocols::wp::cursor_shape::v1::client::{
  41    wp_cursor_shape_device_v1, wp_cursor_shape_manager_v1,
  42};
  43use wayland_protocols::wp::fractional_scale::v1::client::{
  44    wp_fractional_scale_manager_v1, wp_fractional_scale_v1,
  45};
  46use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::{
  47    self, ZwpPrimarySelectionOfferV1,
  48};
  49use wayland_protocols::wp::primary_selection::zv1::client::{
  50    zwp_primary_selection_device_manager_v1, zwp_primary_selection_device_v1,
  51    zwp_primary_selection_source_v1,
  52};
  53use wayland_protocols::wp::text_input::zv3::client::zwp_text_input_v3::{
  54    ContentHint, ContentPurpose,
  55};
  56use wayland_protocols::wp::text_input::zv3::client::{
  57    zwp_text_input_manager_v3, zwp_text_input_v3,
  58};
  59use wayland_protocols::wp::viewporter::client::{wp_viewport, wp_viewporter};
  60use wayland_protocols::xdg::activation::v1::client::{xdg_activation_token_v1, xdg_activation_v1};
  61use wayland_protocols::xdg::decoration::zv1::client::{
  62    zxdg_decoration_manager_v1, zxdg_toplevel_decoration_v1,
  63};
  64use wayland_protocols::xdg::shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base};
  65use wayland_protocols_plasma::blur::client::{org_kde_kwin_blur, org_kde_kwin_blur_manager};
  66use xkbcommon::xkb::ffi::XKB_KEYMAP_FORMAT_TEXT_V1;
  67use xkbcommon::xkb::{self, KEYMAP_COMPILE_NO_FLAGS, Keycode};
  68
  69use super::{
  70    display::WaylandDisplay,
  71    window::{ImeInput, WaylandWindowStatePtr},
  72};
  73
  74use crate::platform::{PlatformWindow, blade::BladeContext};
  75use crate::{
  76    AnyWindowHandle, Bounds, CursorStyle, DOUBLE_CLICK_INTERVAL, DevicePixels, DisplayId,
  77    FileDropEvent, ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke, LinuxCommon,
  78    LinuxKeyboardLayout, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
  79    MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels, PlatformDisplay,
  80    PlatformInput, PlatformKeyboardLayout, Point, SCROLL_LINES, ScaledPixels, ScreenCaptureSource,
  81    ScrollDelta, ScrollWheelEvent, Size, TouchPhase, WindowParams, point, px, size,
  82};
  83use crate::{
  84    SharedString,
  85    platform::linux::{
  86        LinuxClient, get_xkb_compose_state, is_within_click_distance, open_uri_internal, read_fd,
  87        reveal_path_internal,
  88        wayland::{
  89            clipboard::{Clipboard, DataOffer, FILE_LIST_MIME_TYPE, TEXT_MIME_TYPES},
  90            cursor::Cursor,
  91            serial::{SerialKind, SerialTracker},
  92            window::WaylandWindow,
  93        },
  94        xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
  95    },
  96};
  97
  98/// Used to convert evdev scancode to xkb scancode
  99const MIN_KEYCODE: u32 = 8;
 100
 101const UNKNOWN_KEYBOARD_LAYOUT_NAME: SharedString = SharedString::new_static("unknown");
 102
 103#[derive(Clone)]
 104pub struct Globals {
 105    pub qh: QueueHandle<WaylandClientStatePtr>,
 106    pub activation: Option<xdg_activation_v1::XdgActivationV1>,
 107    pub compositor: wl_compositor::WlCompositor,
 108    pub cursor_shape_manager: Option<wp_cursor_shape_manager_v1::WpCursorShapeManagerV1>,
 109    pub data_device_manager: Option<wl_data_device_manager::WlDataDeviceManager>,
 110    pub primary_selection_manager:
 111        Option<zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1>,
 112    pub wm_base: xdg_wm_base::XdgWmBase,
 113    pub shm: wl_shm::WlShm,
 114    pub seat: wl_seat::WlSeat,
 115    pub viewporter: Option<wp_viewporter::WpViewporter>,
 116    pub fractional_scale_manager:
 117        Option<wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1>,
 118    pub decoration_manager: Option<zxdg_decoration_manager_v1::ZxdgDecorationManagerV1>,
 119    pub blur_manager: Option<org_kde_kwin_blur_manager::OrgKdeKwinBlurManager>,
 120    pub text_input_manager: Option<zwp_text_input_manager_v3::ZwpTextInputManagerV3>,
 121    pub executor: ForegroundExecutor,
 122}
 123
 124impl Globals {
 125    fn new(
 126        globals: GlobalList,
 127        executor: ForegroundExecutor,
 128        qh: QueueHandle<WaylandClientStatePtr>,
 129        seat: wl_seat::WlSeat,
 130    ) -> Self {
 131        Globals {
 132            activation: globals.bind(&qh, 1..=1, ()).ok(),
 133            compositor: globals
 134                .bind(
 135                    &qh,
 136                    wl_surface::REQ_SET_BUFFER_SCALE_SINCE
 137                        ..=wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE,
 138                    (),
 139                )
 140                .unwrap(),
 141            cursor_shape_manager: globals.bind(&qh, 1..=1, ()).ok(),
 142            data_device_manager: globals
 143                .bind(
 144                    &qh,
 145                    WL_DATA_DEVICE_MANAGER_VERSION..=WL_DATA_DEVICE_MANAGER_VERSION,
 146                    (),
 147                )
 148                .ok(),
 149            primary_selection_manager: globals.bind(&qh, 1..=1, ()).ok(),
 150            shm: globals.bind(&qh, 1..=1, ()).unwrap(),
 151            seat,
 152            wm_base: globals.bind(&qh, 2..=5, ()).unwrap(),
 153            viewporter: globals.bind(&qh, 1..=1, ()).ok(),
 154            fractional_scale_manager: globals.bind(&qh, 1..=1, ()).ok(),
 155            decoration_manager: globals.bind(&qh, 1..=1, ()).ok(),
 156            blur_manager: globals.bind(&qh, 1..=1, ()).ok(),
 157            text_input_manager: globals.bind(&qh, 1..=1, ()).ok(),
 158            executor,
 159            qh,
 160        }
 161    }
 162}
 163
 164#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
 165pub struct InProgressOutput {
 166    name: Option<String>,
 167    scale: Option<i32>,
 168    position: Option<Point<DevicePixels>>,
 169    size: Option<Size<DevicePixels>>,
 170}
 171
 172impl InProgressOutput {
 173    fn complete(&self) -> Option<Output> {
 174        if let Some((position, size)) = self.position.zip(self.size) {
 175            let scale = self.scale.unwrap_or(1);
 176            Some(Output {
 177                name: self.name.clone(),
 178                scale,
 179                bounds: Bounds::new(position, size),
 180            })
 181        } else {
 182            None
 183        }
 184    }
 185}
 186
 187#[derive(Debug, Clone, Eq, PartialEq, Hash)]
 188pub struct Output {
 189    pub name: Option<String>,
 190    pub scale: i32,
 191    pub bounds: Bounds<DevicePixels>,
 192}
 193
 194pub(crate) struct WaylandClientState {
 195    serial_tracker: SerialTracker,
 196    globals: Globals,
 197    gpu_context: BladeContext,
 198    wl_seat: wl_seat::WlSeat, // TODO: Multi seat support
 199    wl_pointer: Option<wl_pointer::WlPointer>,
 200    wl_keyboard: Option<wl_keyboard::WlKeyboard>,
 201    cursor_shape_device: Option<wp_cursor_shape_device_v1::WpCursorShapeDeviceV1>,
 202    data_device: Option<wl_data_device::WlDataDevice>,
 203    primary_selection: Option<zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1>,
 204    text_input: Option<zwp_text_input_v3::ZwpTextInputV3>,
 205    pre_edit_text: Option<String>,
 206    ime_pre_edit: Option<String>,
 207    composing: bool,
 208    // Surface to Window mapping
 209    windows: HashMap<ObjectId, WaylandWindowStatePtr>,
 210    // Output to scale mapping
 211    outputs: HashMap<ObjectId, Output>,
 212    in_progress_outputs: HashMap<ObjectId, InProgressOutput>,
 213    keyboard_layout: LinuxKeyboardLayout,
 214    keymap_state: Option<xkb::State>,
 215    compose_state: Option<xkb::compose::State>,
 216    drag: DragState,
 217    click: ClickState,
 218    repeat: KeyRepeat,
 219    pub modifiers: Modifiers,
 220    axis_source: AxisSource,
 221    pub mouse_location: Option<Point<Pixels>>,
 222    continuous_scroll_delta: Option<Point<Pixels>>,
 223    discrete_scroll_delta: Option<Point<f32>>,
 224    vertical_modifier: f32,
 225    horizontal_modifier: f32,
 226    scroll_event_received: bool,
 227    enter_token: Option<()>,
 228    button_pressed: Option<MouseButton>,
 229    mouse_focused_window: Option<WaylandWindowStatePtr>,
 230    keyboard_focused_window: Option<WaylandWindowStatePtr>,
 231    loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
 232    cursor_style: Option<CursorStyle>,
 233    clipboard: Clipboard,
 234    data_offers: Vec<DataOffer<WlDataOffer>>,
 235    primary_data_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>,
 236    cursor: Cursor,
 237    pending_activation: Option<PendingActivation>,
 238    event_loop: Option<EventLoop<'static, WaylandClientStatePtr>>,
 239    common: LinuxCommon,
 240}
 241
 242pub struct DragState {
 243    data_offer: Option<wl_data_offer::WlDataOffer>,
 244    window: Option<WaylandWindowStatePtr>,
 245    position: Point<Pixels>,
 246}
 247
 248pub struct ClickState {
 249    last_mouse_button: Option<MouseButton>,
 250    last_click: Instant,
 251    last_location: Point<Pixels>,
 252    current_count: usize,
 253}
 254
 255pub(crate) struct KeyRepeat {
 256    characters_per_second: u32,
 257    delay: Duration,
 258    current_id: u64,
 259    current_keycode: Option<xkb::Keycode>,
 260}
 261
 262pub(crate) enum PendingActivation {
 263    /// URI to open in the web browser.
 264    Uri(String),
 265    /// Path to open in the file explorer.
 266    Path(PathBuf),
 267    /// A window from ourselves to raise.
 268    Window(ObjectId),
 269}
 270
 271/// This struct is required to conform to Rust's orphan rules, so we can dispatch on the state but hand the
 272/// window to GPUI.
 273#[derive(Clone)]
 274pub struct WaylandClientStatePtr(Weak<RefCell<WaylandClientState>>);
 275
 276impl WaylandClientStatePtr {
 277    pub fn get_client(&self) -> Rc<RefCell<WaylandClientState>> {
 278        self.0
 279            .upgrade()
 280            .expect("The pointer should always be valid when dispatching in wayland")
 281    }
 282
 283    pub fn get_serial(&self, kind: SerialKind) -> u32 {
 284        self.0.upgrade().unwrap().borrow().serial_tracker.get(kind)
 285    }
 286
 287    pub fn set_pending_activation(&self, window: ObjectId) {
 288        self.0.upgrade().unwrap().borrow_mut().pending_activation =
 289            Some(PendingActivation::Window(window));
 290    }
 291
 292    pub fn enable_ime(&self) {
 293        let client = self.get_client();
 294        let mut state = client.borrow_mut();
 295        let Some(mut text_input) = state.text_input.take() else {
 296            return;
 297        };
 298
 299        text_input.enable();
 300        text_input.set_content_type(ContentHint::None, ContentPurpose::Normal);
 301        if let Some(window) = state.keyboard_focused_window.clone() {
 302            drop(state);
 303            if let Some(area) = window.get_ime_area() {
 304                text_input.set_cursor_rectangle(
 305                    area.origin.x.0 as i32,
 306                    area.origin.y.0 as i32,
 307                    area.size.width.0 as i32,
 308                    area.size.height.0 as i32,
 309                );
 310            }
 311            state = client.borrow_mut();
 312        }
 313        text_input.commit();
 314        state.text_input = Some(text_input);
 315    }
 316
 317    pub fn disable_ime(&self) {
 318        let client = self.get_client();
 319        let mut state = client.borrow_mut();
 320        state.composing = false;
 321        if let Some(text_input) = &state.text_input {
 322            text_input.disable();
 323            text_input.commit();
 324        }
 325    }
 326
 327    pub fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
 328        let client = self.get_client();
 329        let mut state = client.borrow_mut();
 330        if state.composing || state.text_input.is_none() || state.pre_edit_text.is_some() {
 331            return;
 332        }
 333
 334        let text_input = state.text_input.as_ref().unwrap();
 335        text_input.set_cursor_rectangle(
 336            bounds.origin.x.0 as i32,
 337            bounds.origin.y.0 as i32,
 338            bounds.size.width.0 as i32,
 339            bounds.size.height.0 as i32,
 340        );
 341        text_input.commit();
 342    }
 343
 344    pub fn handle_keyboard_layout_change(&self) {
 345        let client = self.get_client();
 346        let mut state = client.borrow_mut();
 347        let changed = if let Some(keymap_state) = &state.keymap_state {
 348            let layout_idx = keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
 349            let keymap = keymap_state.get_keymap();
 350            let layout_name = keymap.layout_get_name(layout_idx);
 351            let changed = layout_name != state.keyboard_layout.name();
 352            if changed {
 353                state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
 354            }
 355            changed
 356        } else {
 357            let changed = &UNKNOWN_KEYBOARD_LAYOUT_NAME != state.keyboard_layout.name();
 358            if changed {
 359                state.keyboard_layout = LinuxKeyboardLayout::new(UNKNOWN_KEYBOARD_LAYOUT_NAME);
 360            }
 361            changed
 362        };
 363        if changed {
 364            if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
 365                drop(state);
 366                callback();
 367                state = client.borrow_mut();
 368                state.common.callbacks.keyboard_layout_change = Some(callback);
 369            }
 370        }
 371    }
 372
 373    pub fn drop_window(&self, surface_id: &ObjectId) {
 374        let mut client = self.get_client();
 375        let mut state = client.borrow_mut();
 376        let closed_window = state.windows.remove(surface_id).unwrap();
 377        if let Some(window) = state.mouse_focused_window.take() {
 378            if !window.ptr_eq(&closed_window) {
 379                state.mouse_focused_window = Some(window);
 380            }
 381        }
 382        if let Some(window) = state.keyboard_focused_window.take() {
 383            if !window.ptr_eq(&closed_window) {
 384                state.keyboard_focused_window = Some(window);
 385            }
 386        }
 387        if state.windows.is_empty() {
 388            state.common.signal.stop();
 389        }
 390    }
 391}
 392
 393#[derive(Clone)]
 394pub struct WaylandClient(Rc<RefCell<WaylandClientState>>);
 395
 396impl Drop for WaylandClient {
 397    fn drop(&mut self) {
 398        let mut state = self.0.borrow_mut();
 399        state.windows.clear();
 400
 401        if let Some(wl_pointer) = &state.wl_pointer {
 402            wl_pointer.release();
 403        }
 404        if let Some(cursor_shape_device) = &state.cursor_shape_device {
 405            cursor_shape_device.destroy();
 406        }
 407        if let Some(data_device) = &state.data_device {
 408            data_device.release();
 409        }
 410        if let Some(text_input) = &state.text_input {
 411            text_input.destroy();
 412        }
 413    }
 414}
 415
 416const WL_DATA_DEVICE_MANAGER_VERSION: u32 = 3;
 417
 418fn wl_seat_version(version: u32) -> u32 {
 419    // We rely on the wl_pointer.frame event
 420    const WL_SEAT_MIN_VERSION: u32 = 5;
 421    const WL_SEAT_MAX_VERSION: u32 = 9;
 422
 423    if version < WL_SEAT_MIN_VERSION {
 424        panic!(
 425            "wl_seat below required version: {} < {}",
 426            version, WL_SEAT_MIN_VERSION
 427        );
 428    }
 429
 430    version.clamp(WL_SEAT_MIN_VERSION, WL_SEAT_MAX_VERSION)
 431}
 432
 433fn wl_output_version(version: u32) -> u32 {
 434    const WL_OUTPUT_MIN_VERSION: u32 = 2;
 435    const WL_OUTPUT_MAX_VERSION: u32 = 4;
 436
 437    if version < WL_OUTPUT_MIN_VERSION {
 438        panic!(
 439            "wl_output below required version: {} < {}",
 440            version, WL_OUTPUT_MIN_VERSION
 441        );
 442    }
 443
 444    version.clamp(WL_OUTPUT_MIN_VERSION, WL_OUTPUT_MAX_VERSION)
 445}
 446
 447impl WaylandClient {
 448    pub(crate) fn new() -> Self {
 449        let conn = Connection::connect_to_env().unwrap();
 450
 451        let (globals, mut event_queue) =
 452            registry_queue_init::<WaylandClientStatePtr>(&conn).unwrap();
 453        let qh = event_queue.handle();
 454
 455        let mut seat: Option<wl_seat::WlSeat> = None;
 456        #[allow(clippy::mutable_key_type)]
 457        let mut in_progress_outputs = HashMap::default();
 458        globals.contents().with_list(|list| {
 459            for global in list {
 460                match &global.interface[..] {
 461                    "wl_seat" => {
 462                        seat = Some(globals.registry().bind::<wl_seat::WlSeat, _, _>(
 463                            global.name,
 464                            wl_seat_version(global.version),
 465                            &qh,
 466                            (),
 467                        ));
 468                    }
 469                    "wl_output" => {
 470                        let output = globals.registry().bind::<wl_output::WlOutput, _, _>(
 471                            global.name,
 472                            wl_output_version(global.version),
 473                            &qh,
 474                            (),
 475                        );
 476                        in_progress_outputs.insert(output.id(), InProgressOutput::default());
 477                    }
 478                    _ => {}
 479                }
 480            }
 481        });
 482
 483        let event_loop = EventLoop::<WaylandClientStatePtr>::try_new().unwrap();
 484
 485        let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
 486
 487        let handle = event_loop.handle();
 488        handle
 489            .insert_source(main_receiver, {
 490                let handle = handle.clone();
 491                move |event, _, _: &mut WaylandClientStatePtr| {
 492                    if let calloop::channel::Event::Msg(runnable) = event {
 493                        handle.insert_idle(|_| {
 494                            runnable.run();
 495                        });
 496                    }
 497                }
 498            })
 499            .unwrap();
 500
 501        let gpu_context = BladeContext::new().expect("Unable to init GPU context");
 502
 503        let seat = seat.unwrap();
 504        let globals = Globals::new(
 505            globals,
 506            common.foreground_executor.clone(),
 507            qh.clone(),
 508            seat.clone(),
 509        );
 510
 511        let data_device = globals
 512            .data_device_manager
 513            .as_ref()
 514            .map(|data_device_manager| data_device_manager.get_data_device(&seat, &qh, ()));
 515
 516        let primary_selection = globals
 517            .primary_selection_manager
 518            .as_ref()
 519            .map(|primary_selection_manager| primary_selection_manager.get_device(&seat, &qh, ()));
 520
 521        let mut cursor = Cursor::new(&conn, &globals, 24);
 522
 523        handle
 524            .insert_source(XDPEventSource::new(&common.background_executor), {
 525                move |event, _, client| match event {
 526                    XDPEvent::WindowAppearance(appearance) => {
 527                        if let Some(client) = client.0.upgrade() {
 528                            let mut client = client.borrow_mut();
 529
 530                            client.common.appearance = appearance;
 531
 532                            for (_, window) in &mut client.windows {
 533                                window.set_appearance(appearance);
 534                            }
 535                        }
 536                    }
 537                    XDPEvent::CursorTheme(theme) => {
 538                        if let Some(client) = client.0.upgrade() {
 539                            let mut client = client.borrow_mut();
 540                            client.cursor.set_theme(theme.as_str());
 541                        }
 542                    }
 543                    XDPEvent::CursorSize(size) => {
 544                        if let Some(client) = client.0.upgrade() {
 545                            let mut client = client.borrow_mut();
 546                            client.cursor.set_size(size);
 547                        }
 548                    }
 549                }
 550            })
 551            .unwrap();
 552
 553        let mut state = Rc::new(RefCell::new(WaylandClientState {
 554            serial_tracker: SerialTracker::new(),
 555            globals,
 556            gpu_context,
 557            wl_seat: seat,
 558            wl_pointer: None,
 559            wl_keyboard: None,
 560            cursor_shape_device: None,
 561            data_device,
 562            primary_selection,
 563            text_input: None,
 564            pre_edit_text: None,
 565            ime_pre_edit: None,
 566            composing: false,
 567            outputs: HashMap::default(),
 568            in_progress_outputs,
 569            windows: HashMap::default(),
 570            common,
 571            keyboard_layout: LinuxKeyboardLayout::new(UNKNOWN_KEYBOARD_LAYOUT_NAME),
 572            keymap_state: None,
 573            compose_state: None,
 574            drag: DragState {
 575                data_offer: None,
 576                window: None,
 577                position: Point::default(),
 578            },
 579            click: ClickState {
 580                last_click: Instant::now(),
 581                last_mouse_button: None,
 582                last_location: Point::default(),
 583                current_count: 0,
 584            },
 585            repeat: KeyRepeat {
 586                characters_per_second: 16,
 587                delay: Duration::from_millis(500),
 588                current_id: 0,
 589                current_keycode: None,
 590            },
 591            modifiers: Modifiers {
 592                shift: false,
 593                control: false,
 594                alt: false,
 595                function: false,
 596                platform: false,
 597            },
 598            scroll_event_received: false,
 599            axis_source: AxisSource::Wheel,
 600            mouse_location: None,
 601            continuous_scroll_delta: None,
 602            discrete_scroll_delta: None,
 603            vertical_modifier: -1.0,
 604            horizontal_modifier: -1.0,
 605            button_pressed: None,
 606            mouse_focused_window: None,
 607            keyboard_focused_window: None,
 608            loop_handle: handle.clone(),
 609            enter_token: None,
 610            cursor_style: None,
 611            clipboard: Clipboard::new(conn.clone(), handle.clone()),
 612            data_offers: Vec::new(),
 613            primary_data_offer: None,
 614            cursor,
 615            pending_activation: None,
 616            event_loop: Some(event_loop),
 617        }));
 618
 619        WaylandSource::new(conn, event_queue)
 620            .insert(handle)
 621            .unwrap();
 622
 623        Self(state)
 624    }
 625}
 626
 627impl LinuxClient for WaylandClient {
 628    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 629        Box::new(self.0.borrow().keyboard_layout.clone())
 630    }
 631
 632    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 633        self.0
 634            .borrow()
 635            .outputs
 636            .iter()
 637            .map(|(id, output)| {
 638                Rc::new(WaylandDisplay {
 639                    id: id.clone(),
 640                    name: output.name.clone(),
 641                    bounds: output.bounds.to_pixels(output.scale as f32),
 642                }) as Rc<dyn PlatformDisplay>
 643            })
 644            .collect()
 645    }
 646
 647    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 648        self.0
 649            .borrow()
 650            .outputs
 651            .iter()
 652            .find_map(|(object_id, output)| {
 653                (object_id.protocol_id() == id.0).then(|| {
 654                    Rc::new(WaylandDisplay {
 655                        id: object_id.clone(),
 656                        name: output.name.clone(),
 657                        bounds: output.bounds.to_pixels(output.scale as f32),
 658                    }) as Rc<dyn PlatformDisplay>
 659                })
 660            })
 661    }
 662
 663    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 664        None
 665    }
 666
 667    fn is_screen_capture_supported(&self) -> bool {
 668        false
 669    }
 670
 671    fn screen_capture_sources(
 672        &self,
 673    ) -> oneshot::Receiver<anyhow::Result<Vec<Box<dyn ScreenCaptureSource>>>> {
 674        // TODO: Get screen capture working on wayland. Be sure to try window resizing as that may
 675        // be tricky.
 676        //
 677        // start_scap_default_target_source()
 678        let (sources_tx, sources_rx) = oneshot::channel();
 679        sources_tx
 680            .send(Err(anyhow!("Wayland screen capture not yet implemented.")))
 681            .ok();
 682        sources_rx
 683    }
 684
 685    fn open_window(
 686        &self,
 687        handle: AnyWindowHandle,
 688        params: WindowParams,
 689    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
 690        let mut state = self.0.borrow_mut();
 691
 692        let (window, surface_id) = WaylandWindow::new(
 693            handle,
 694            state.globals.clone(),
 695            &state.gpu_context,
 696            WaylandClientStatePtr(Rc::downgrade(&self.0)),
 697            params,
 698            state.common.appearance,
 699        )?;
 700        state.windows.insert(surface_id, window.0.clone());
 701
 702        Ok(Box::new(window))
 703    }
 704
 705    fn set_cursor_style(&self, style: CursorStyle) {
 706        let mut state = self.0.borrow_mut();
 707
 708        let need_update = state
 709            .cursor_style
 710            .map_or(true, |current_style| current_style != style);
 711
 712        if need_update {
 713            let serial = state.serial_tracker.get(SerialKind::MouseEnter);
 714            state.cursor_style = Some(style);
 715
 716            if let CursorStyle::None = style {
 717                let wl_pointer = state
 718                    .wl_pointer
 719                    .clone()
 720                    .expect("window is focused by pointer");
 721                wl_pointer.set_cursor(serial, None, 0, 0);
 722            } else if let Some(cursor_shape_device) = &state.cursor_shape_device {
 723                cursor_shape_device.set_shape(serial, style.to_shape());
 724            } else if let Some(focused_window) = &state.mouse_focused_window {
 725                // cursor-shape-v1 isn't supported, set the cursor using a surface.
 726                let wl_pointer = state
 727                    .wl_pointer
 728                    .clone()
 729                    .expect("window is focused by pointer");
 730                let scale = focused_window.primary_output_scale();
 731                state
 732                    .cursor
 733                    .set_icon(&wl_pointer, serial, style.to_icon_names(), scale);
 734            }
 735        }
 736    }
 737
 738    fn open_uri(&self, uri: &str) {
 739        let mut state = self.0.borrow_mut();
 740        if let (Some(activation), Some(window)) = (
 741            state.globals.activation.clone(),
 742            state.mouse_focused_window.clone(),
 743        ) {
 744            state.pending_activation = Some(PendingActivation::Uri(uri.to_string()));
 745            let token = activation.get_activation_token(&state.globals.qh, ());
 746            let serial = state.serial_tracker.get(SerialKind::MousePress);
 747            token.set_serial(serial, &state.wl_seat);
 748            token.set_surface(&window.surface());
 749            token.commit();
 750        } else {
 751            let executor = state.common.background_executor.clone();
 752            open_uri_internal(executor, uri, None);
 753        }
 754    }
 755
 756    fn reveal_path(&self, path: PathBuf) {
 757        let mut state = self.0.borrow_mut();
 758        if let (Some(activation), Some(window)) = (
 759            state.globals.activation.clone(),
 760            state.mouse_focused_window.clone(),
 761        ) {
 762            state.pending_activation = Some(PendingActivation::Path(path));
 763            let token = activation.get_activation_token(&state.globals.qh, ());
 764            let serial = state.serial_tracker.get(SerialKind::MousePress);
 765            token.set_serial(serial, &state.wl_seat);
 766            token.set_surface(&window.surface());
 767            token.commit();
 768        } else {
 769            let executor = state.common.background_executor.clone();
 770            reveal_path_internal(executor, path, None);
 771        }
 772    }
 773
 774    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
 775        f(&mut self.0.borrow_mut().common)
 776    }
 777
 778    fn run(&self) {
 779        let mut event_loop = self
 780            .0
 781            .borrow_mut()
 782            .event_loop
 783            .take()
 784            .expect("App is already running");
 785
 786        event_loop
 787            .run(
 788                None,
 789                &mut WaylandClientStatePtr(Rc::downgrade(&self.0)),
 790                |_| {},
 791            )
 792            .log_err();
 793    }
 794
 795    fn write_to_primary(&self, item: crate::ClipboardItem) {
 796        let mut state = self.0.borrow_mut();
 797        let (Some(primary_selection_manager), Some(primary_selection)) = (
 798            state.globals.primary_selection_manager.clone(),
 799            state.primary_selection.clone(),
 800        ) else {
 801            return;
 802        };
 803        if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
 804            state.clipboard.set_primary(item);
 805            let serial = state.serial_tracker.get(SerialKind::KeyPress);
 806            let data_source = primary_selection_manager.create_source(&state.globals.qh, ());
 807            for mime_type in TEXT_MIME_TYPES {
 808                data_source.offer(mime_type.to_string());
 809            }
 810            data_source.offer(state.clipboard.self_mime());
 811            primary_selection.set_selection(Some(&data_source), serial);
 812        }
 813    }
 814
 815    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
 816        let mut state = self.0.borrow_mut();
 817        let (Some(data_device_manager), Some(data_device)) = (
 818            state.globals.data_device_manager.clone(),
 819            state.data_device.clone(),
 820        ) else {
 821            return;
 822        };
 823        if state.mouse_focused_window.is_some() || state.keyboard_focused_window.is_some() {
 824            state.clipboard.set(item);
 825            let serial = state.serial_tracker.get(SerialKind::KeyPress);
 826            let data_source = data_device_manager.create_data_source(&state.globals.qh, ());
 827            for mime_type in TEXT_MIME_TYPES {
 828                data_source.offer(mime_type.to_string());
 829            }
 830            data_source.offer(state.clipboard.self_mime());
 831            data_device.set_selection(Some(&data_source), serial);
 832        }
 833    }
 834
 835    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
 836        self.0.borrow_mut().clipboard.read_primary()
 837    }
 838
 839    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
 840        self.0.borrow_mut().clipboard.read()
 841    }
 842
 843    fn active_window(&self) -> Option<AnyWindowHandle> {
 844        self.0
 845            .borrow_mut()
 846            .keyboard_focused_window
 847            .as_ref()
 848            .map(|window| window.handle())
 849    }
 850
 851    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 852        None
 853    }
 854
 855    fn compositor_name(&self) -> &'static str {
 856        "Wayland"
 857    }
 858}
 859
 860impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStatePtr {
 861    fn event(
 862        this: &mut Self,
 863        registry: &wl_registry::WlRegistry,
 864        event: wl_registry::Event,
 865        _: &GlobalListContents,
 866        _: &Connection,
 867        qh: &QueueHandle<Self>,
 868    ) {
 869        let mut client = this.get_client();
 870        let mut state = client.borrow_mut();
 871
 872        match event {
 873            wl_registry::Event::Global {
 874                name,
 875                interface,
 876                version,
 877            } => match &interface[..] {
 878                "wl_seat" => {
 879                    if let Some(wl_pointer) = state.wl_pointer.take() {
 880                        wl_pointer.release();
 881                    }
 882                    if let Some(wl_keyboard) = state.wl_keyboard.take() {
 883                        wl_keyboard.release();
 884                    }
 885                    state.wl_seat.release();
 886                    state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(
 887                        name,
 888                        wl_seat_version(version),
 889                        qh,
 890                        (),
 891                    );
 892                }
 893                "wl_output" => {
 894                    let output = registry.bind::<wl_output::WlOutput, _, _>(
 895                        name,
 896                        wl_output_version(version),
 897                        qh,
 898                        (),
 899                    );
 900
 901                    state
 902                        .in_progress_outputs
 903                        .insert(output.id(), InProgressOutput::default());
 904                }
 905                _ => {}
 906            },
 907            wl_registry::Event::GlobalRemove { name: _ } => {
 908                // TODO: handle global removal
 909            }
 910            _ => {}
 911        }
 912    }
 913}
 914
 915delegate_noop!(WaylandClientStatePtr: ignore xdg_activation_v1::XdgActivationV1);
 916delegate_noop!(WaylandClientStatePtr: ignore wl_compositor::WlCompositor);
 917delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_device_v1::WpCursorShapeDeviceV1);
 918delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_manager_v1::WpCursorShapeManagerV1);
 919delegate_noop!(WaylandClientStatePtr: ignore wl_data_device_manager::WlDataDeviceManager);
 920delegate_noop!(WaylandClientStatePtr: ignore zwp_primary_selection_device_manager_v1::ZwpPrimarySelectionDeviceManagerV1);
 921delegate_noop!(WaylandClientStatePtr: ignore wl_shm::WlShm);
 922delegate_noop!(WaylandClientStatePtr: ignore wl_shm_pool::WlShmPool);
 923delegate_noop!(WaylandClientStatePtr: ignore wl_buffer::WlBuffer);
 924delegate_noop!(WaylandClientStatePtr: ignore wl_region::WlRegion);
 925delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
 926delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
 927delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur_manager::OrgKdeKwinBlurManager);
 928delegate_noop!(WaylandClientStatePtr: ignore zwp_text_input_manager_v3::ZwpTextInputManagerV3);
 929delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur::OrgKdeKwinBlur);
 930delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
 931delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
 932
 933impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
 934    fn event(
 935        state: &mut WaylandClientStatePtr,
 936        _: &wl_callback::WlCallback,
 937        event: wl_callback::Event,
 938        surface_id: &ObjectId,
 939        _: &Connection,
 940        _: &QueueHandle<Self>,
 941    ) {
 942        let client = state.get_client();
 943        let mut state = client.borrow_mut();
 944        let Some(window) = get_window(&mut state, surface_id) else {
 945            return;
 946        };
 947        drop(state);
 948
 949        match event {
 950            wl_callback::Event::Done { .. } => {
 951                window.frame();
 952            }
 953            _ => {}
 954        }
 955    }
 956}
 957
 958fn get_window(
 959    mut state: &mut RefMut<WaylandClientState>,
 960    surface_id: &ObjectId,
 961) -> Option<WaylandWindowStatePtr> {
 962    state.windows.get(surface_id).cloned()
 963}
 964
 965impl Dispatch<wl_surface::WlSurface, ()> for WaylandClientStatePtr {
 966    fn event(
 967        this: &mut Self,
 968        surface: &wl_surface::WlSurface,
 969        event: <wl_surface::WlSurface as Proxy>::Event,
 970        _: &(),
 971        _: &Connection,
 972        _: &QueueHandle<Self>,
 973    ) {
 974        let mut client = this.get_client();
 975        let mut state = client.borrow_mut();
 976
 977        let Some(window) = get_window(&mut state, &surface.id()) else {
 978            return;
 979        };
 980        #[allow(clippy::mutable_key_type)]
 981        let outputs = state.outputs.clone();
 982        drop(state);
 983
 984        window.handle_surface_event(event, outputs);
 985    }
 986}
 987
 988impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
 989    fn event(
 990        this: &mut Self,
 991        output: &wl_output::WlOutput,
 992        event: <wl_output::WlOutput as Proxy>::Event,
 993        _: &(),
 994        _: &Connection,
 995        _: &QueueHandle<Self>,
 996    ) {
 997        let mut client = this.get_client();
 998        let mut state = client.borrow_mut();
 999
1000        let Some(mut in_progress_output) = state.in_progress_outputs.get_mut(&output.id()) else {
1001            return;
1002        };
1003
1004        match event {
1005            wl_output::Event::Name { name } => {
1006                in_progress_output.name = Some(name);
1007            }
1008            wl_output::Event::Scale { factor } => {
1009                in_progress_output.scale = Some(factor);
1010            }
1011            wl_output::Event::Geometry { x, y, .. } => {
1012                in_progress_output.position = Some(point(DevicePixels(x), DevicePixels(y)))
1013            }
1014            wl_output::Event::Mode { width, height, .. } => {
1015                in_progress_output.size = Some(size(DevicePixels(width), DevicePixels(height)))
1016            }
1017            wl_output::Event::Done => {
1018                if let Some(complete) = in_progress_output.complete() {
1019                    state.outputs.insert(output.id(), complete);
1020                }
1021                state.in_progress_outputs.remove(&output.id());
1022            }
1023            _ => {}
1024        }
1025    }
1026}
1027
1028impl Dispatch<xdg_surface::XdgSurface, ObjectId> for WaylandClientStatePtr {
1029    fn event(
1030        state: &mut Self,
1031        _: &xdg_surface::XdgSurface,
1032        event: xdg_surface::Event,
1033        surface_id: &ObjectId,
1034        _: &Connection,
1035        _: &QueueHandle<Self>,
1036    ) {
1037        let client = state.get_client();
1038        let mut state = client.borrow_mut();
1039        let Some(window) = get_window(&mut state, surface_id) else {
1040            return;
1041        };
1042        drop(state);
1043        window.handle_xdg_surface_event(event);
1044    }
1045}
1046
1047impl Dispatch<xdg_toplevel::XdgToplevel, ObjectId> for WaylandClientStatePtr {
1048    fn event(
1049        this: &mut Self,
1050        _: &xdg_toplevel::XdgToplevel,
1051        event: <xdg_toplevel::XdgToplevel as Proxy>::Event,
1052        surface_id: &ObjectId,
1053        _: &Connection,
1054        _: &QueueHandle<Self>,
1055    ) {
1056        let client = this.get_client();
1057        let mut state = client.borrow_mut();
1058        let Some(window) = get_window(&mut state, surface_id) else {
1059            return;
1060        };
1061
1062        drop(state);
1063        let should_close = window.handle_toplevel_event(event);
1064
1065        if should_close {
1066            // The close logic will be handled in drop_window()
1067            window.close();
1068        }
1069    }
1070}
1071
1072impl Dispatch<xdg_wm_base::XdgWmBase, ()> for WaylandClientStatePtr {
1073    fn event(
1074        _: &mut Self,
1075        wm_base: &xdg_wm_base::XdgWmBase,
1076        event: <xdg_wm_base::XdgWmBase as Proxy>::Event,
1077        _: &(),
1078        _: &Connection,
1079        _: &QueueHandle<Self>,
1080    ) {
1081        if let xdg_wm_base::Event::Ping { serial } = event {
1082            wm_base.pong(serial);
1083        }
1084    }
1085}
1086
1087impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClientStatePtr {
1088    fn event(
1089        this: &mut Self,
1090        token: &xdg_activation_token_v1::XdgActivationTokenV1,
1091        event: <xdg_activation_token_v1::XdgActivationTokenV1 as Proxy>::Event,
1092        _: &(),
1093        _: &Connection,
1094        _: &QueueHandle<Self>,
1095    ) {
1096        let client = this.get_client();
1097        let mut state = client.borrow_mut();
1098
1099        if let xdg_activation_token_v1::Event::Done { token } = event {
1100            let executor = state.common.background_executor.clone();
1101            match state.pending_activation.take() {
1102                Some(PendingActivation::Uri(uri)) => open_uri_internal(executor, &uri, Some(token)),
1103                Some(PendingActivation::Path(path)) => {
1104                    reveal_path_internal(executor, path, Some(token))
1105                }
1106                Some(PendingActivation::Window(window)) => {
1107                    let Some(window) = get_window(&mut state, &window) else {
1108                        return;
1109                    };
1110                    let activation = state.globals.activation.as_ref().unwrap();
1111                    activation.activate(token, &window.surface());
1112                }
1113                None => log::error!("activation token received with no pending activation"),
1114            }
1115        }
1116
1117        token.destroy();
1118    }
1119}
1120
1121impl Dispatch<wl_seat::WlSeat, ()> for WaylandClientStatePtr {
1122    fn event(
1123        state: &mut Self,
1124        seat: &wl_seat::WlSeat,
1125        event: wl_seat::Event,
1126        _: &(),
1127        _: &Connection,
1128        qh: &QueueHandle<Self>,
1129    ) {
1130        if let wl_seat::Event::Capabilities {
1131            capabilities: WEnum::Value(capabilities),
1132        } = event
1133        {
1134            let client = state.get_client();
1135            let mut state = client.borrow_mut();
1136            if capabilities.contains(wl_seat::Capability::Keyboard) {
1137                let keyboard = seat.get_keyboard(qh, ());
1138
1139                state.text_input = state
1140                    .globals
1141                    .text_input_manager
1142                    .as_ref()
1143                    .map(|text_input_manager| text_input_manager.get_text_input(&seat, qh, ()));
1144
1145                if let Some(wl_keyboard) = &state.wl_keyboard {
1146                    wl_keyboard.release();
1147                }
1148
1149                state.wl_keyboard = Some(keyboard);
1150            }
1151            if capabilities.contains(wl_seat::Capability::Pointer) {
1152                let pointer = seat.get_pointer(qh, ());
1153                state.cursor_shape_device = state
1154                    .globals
1155                    .cursor_shape_manager
1156                    .as_ref()
1157                    .map(|cursor_shape_manager| cursor_shape_manager.get_pointer(&pointer, qh, ()));
1158
1159                if let Some(wl_pointer) = &state.wl_pointer {
1160                    wl_pointer.release();
1161                }
1162
1163                state.wl_pointer = Some(pointer);
1164            }
1165        }
1166    }
1167}
1168
1169impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
1170    fn event(
1171        this: &mut Self,
1172        _: &wl_keyboard::WlKeyboard,
1173        event: wl_keyboard::Event,
1174        _: &(),
1175        _: &Connection,
1176        _: &QueueHandle<Self>,
1177    ) {
1178        let mut client = this.get_client();
1179        let mut state = client.borrow_mut();
1180        match event {
1181            wl_keyboard::Event::RepeatInfo { rate, delay } => {
1182                state.repeat.characters_per_second = rate as u32;
1183                state.repeat.delay = Duration::from_millis(delay as u64);
1184            }
1185            wl_keyboard::Event::Keymap {
1186                format: WEnum::Value(format),
1187                fd,
1188                size,
1189                ..
1190            } => {
1191                if format != wl_keyboard::KeymapFormat::XkbV1 {
1192                    log::error!("Received keymap format {:?}, expected XkbV1", format);
1193                    return;
1194                }
1195                let xkb_context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
1196                let keymap = unsafe {
1197                    xkb::Keymap::new_from_fd(
1198                        &xkb_context,
1199                        fd,
1200                        size as usize,
1201                        XKB_KEYMAP_FORMAT_TEXT_V1,
1202                        KEYMAP_COMPILE_NO_FLAGS,
1203                    )
1204                    .log_err()
1205                    .flatten()
1206                    .expect("Failed to create keymap")
1207                };
1208                state.keymap_state = Some(xkb::State::new(&keymap));
1209                state.compose_state = get_xkb_compose_state(&xkb_context);
1210                drop(state);
1211
1212                this.handle_keyboard_layout_change();
1213            }
1214            wl_keyboard::Event::Enter { surface, .. } => {
1215                state.keyboard_focused_window = get_window(&mut state, &surface.id());
1216                state.enter_token = Some(());
1217
1218                if let Some(window) = state.keyboard_focused_window.clone() {
1219                    drop(state);
1220                    window.set_focused(true);
1221                }
1222            }
1223            wl_keyboard::Event::Leave { surface, .. } => {
1224                let keyboard_focused_window = get_window(&mut state, &surface.id());
1225                state.keyboard_focused_window = None;
1226                state.enter_token.take();
1227                // Prevent keyboard events from repeating after opening e.g. a file chooser and closing it quickly
1228                state.repeat.current_id += 1;
1229
1230                if let Some(window) = keyboard_focused_window {
1231                    if let Some(ref mut compose) = state.compose_state {
1232                        compose.reset();
1233                    }
1234                    state.pre_edit_text.take();
1235                    drop(state);
1236                    window.handle_ime(ImeInput::DeleteText);
1237                    window.set_focused(false);
1238                }
1239            }
1240            wl_keyboard::Event::Modifiers {
1241                mods_depressed,
1242                mods_latched,
1243                mods_locked,
1244                group,
1245                ..
1246            } => {
1247                let focused_window = state.keyboard_focused_window.clone();
1248
1249                let keymap_state = state.keymap_state.as_mut().unwrap();
1250                let old_layout =
1251                    keymap_state.serialize_layout(xkbcommon::xkb::STATE_LAYOUT_EFFECTIVE);
1252                keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
1253                state.modifiers = Modifiers::from_xkb(keymap_state);
1254
1255                let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1256                    modifiers: state.modifiers,
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}