client.rs

   1use core::hash;
   2use std::cell::{RefCell, RefMut};
   3use std::os::fd::{AsRawFd, BorrowedFd};
   4use std::path::PathBuf;
   5use std::rc::{Rc, Weak};
   6use std::sync::Arc;
   7use std::time::{Duration, Instant};
   8
   9use async_task::Runnable;
  10use calloop::timer::{TimeoutAction, Timer};
  11use calloop::{EventLoop, LoopHandle};
  12use calloop_wayland_source::WaylandSource;
  13use collections::HashMap;
  14use copypasta::wayland_clipboard::{create_clipboards_from_external, Clipboard, Primary};
  15use copypasta::ClipboardProvider;
  16use filedescriptor::Pipe;
  17use smallvec::SmallVec;
  18use util::ResultExt;
  19use wayland_backend::client::ObjectId;
  20use wayland_backend::protocol::WEnum;
  21use wayland_client::event_created_child;
  22use wayland_client::globals::{registry_queue_init, GlobalList, GlobalListContents};
  23use wayland_client::protocol::wl_callback::{self, WlCallback};
  24use wayland_client::protocol::wl_data_device_manager::DndAction;
  25use wayland_client::protocol::wl_pointer::{AxisRelativeDirection, AxisSource};
  26use wayland_client::protocol::{
  27    wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_output,
  28};
  29use wayland_client::{
  30    delegate_noop,
  31    protocol::{
  32        wl_buffer, wl_compositor, wl_keyboard, wl_pointer, wl_registry, wl_seat, wl_shm,
  33        wl_shm_pool, wl_surface,
  34    },
  35    Connection, Dispatch, Proxy, QueueHandle,
  36};
  37use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::Shape;
  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::viewporter::client::{wp_viewport, wp_viewporter};
  45use wayland_protocols::xdg::activation::v1::client::{xdg_activation_token_v1, xdg_activation_v1};
  46use wayland_protocols::xdg::decoration::zv1::client::{
  47    zxdg_decoration_manager_v1, zxdg_toplevel_decoration_v1,
  48};
  49use wayland_protocols::xdg::shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base};
  50use xkbcommon::xkb::ffi::XKB_KEYMAP_FORMAT_TEXT_V1;
  51use xkbcommon::xkb::{self, Keycode, KEYMAP_COMPILE_NO_FLAGS};
  52
  53use super::super::{open_uri_internal, read_fd, DOUBLE_CLICK_INTERVAL};
  54use super::window::{WaylandWindowState, WaylandWindowStatePtr};
  55use crate::platform::linux::is_within_click_distance;
  56use crate::platform::linux::wayland::cursor::Cursor;
  57use crate::platform::linux::wayland::window::WaylandWindow;
  58use crate::platform::linux::LinuxClient;
  59use crate::platform::PlatformWindow;
  60use crate::{point, px, FileDropEvent, ForegroundExecutor, MouseExitEvent};
  61use crate::{
  62    AnyWindowHandle, CursorStyle, DisplayId, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
  63    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
  64    NavigationDirection, Pixels, PlatformDisplay, PlatformInput, Point, ScrollDelta,
  65    ScrollWheelEvent, TouchPhase,
  66};
  67use crate::{LinuxCommon, WindowParams};
  68
  69/// Used to convert evdev scancode to xkb scancode
  70const MIN_KEYCODE: u32 = 8;
  71
  72#[derive(Clone)]
  73pub struct Globals {
  74    pub qh: QueueHandle<WaylandClientStatePtr>,
  75    pub activation: Option<xdg_activation_v1::XdgActivationV1>,
  76    pub compositor: wl_compositor::WlCompositor,
  77    pub cursor_shape_manager: Option<wp_cursor_shape_manager_v1::WpCursorShapeManagerV1>,
  78    pub data_device_manager: Option<wl_data_device_manager::WlDataDeviceManager>,
  79    pub wm_base: xdg_wm_base::XdgWmBase,
  80    pub shm: wl_shm::WlShm,
  81    pub viewporter: Option<wp_viewporter::WpViewporter>,
  82    pub fractional_scale_manager:
  83        Option<wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1>,
  84    pub decoration_manager: Option<zxdg_decoration_manager_v1::ZxdgDecorationManagerV1>,
  85    pub executor: ForegroundExecutor,
  86}
  87
  88impl Globals {
  89    fn new(
  90        globals: GlobalList,
  91        executor: ForegroundExecutor,
  92        qh: QueueHandle<WaylandClientStatePtr>,
  93    ) -> Self {
  94        Globals {
  95            activation: globals.bind(&qh, 1..=1, ()).ok(),
  96            compositor: globals
  97                .bind(
  98                    &qh,
  99                    wl_surface::REQ_SET_BUFFER_SCALE_SINCE
 100                        ..=wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE,
 101                    (),
 102                )
 103                .unwrap(),
 104            cursor_shape_manager: globals.bind(&qh, 1..=1, ()).ok(),
 105            data_device_manager: globals
 106                .bind(
 107                    &qh,
 108                    WL_DATA_DEVICE_MANAGER_VERSION..=WL_DATA_DEVICE_MANAGER_VERSION,
 109                    (),
 110                )
 111                .ok(),
 112            shm: globals.bind(&qh, 1..=1, ()).unwrap(),
 113            wm_base: globals.bind(&qh, 1..=1, ()).unwrap(),
 114            viewporter: globals.bind(&qh, 1..=1, ()).ok(),
 115            fractional_scale_manager: globals.bind(&qh, 1..=1, ()).ok(),
 116            decoration_manager: globals.bind(&qh, 1..=1, ()).ok(),
 117            executor,
 118            qh,
 119        }
 120    }
 121}
 122
 123pub(crate) struct WaylandClientState {
 124    serial: u32, // todo(linux): storing a general serial is wrong
 125    pointer_serial: u32,
 126    globals: Globals,
 127    wl_seat: wl_seat::WlSeat, // todo(linux): multi-seat support
 128    wl_pointer: Option<wl_pointer::WlPointer>,
 129    cursor_shape_device: Option<wp_cursor_shape_device_v1::WpCursorShapeDeviceV1>,
 130    data_device: Option<wl_data_device::WlDataDevice>,
 131    // Surface to Window mapping
 132    windows: HashMap<ObjectId, WaylandWindowStatePtr>,
 133    // Output to scale mapping
 134    output_scales: HashMap<ObjectId, i32>,
 135    keymap_state: Option<xkb::State>,
 136    drag: DragState,
 137    click: ClickState,
 138    repeat: KeyRepeat,
 139    modifiers: Modifiers,
 140    axis_source: AxisSource,
 141    mouse_location: Option<Point<Pixels>>,
 142    continuous_scroll_delta: Option<Point<Pixels>>,
 143    discrete_scroll_delta: Option<Point<f32>>,
 144    vertical_modifier: f32,
 145    horizontal_modifier: f32,
 146    scroll_event_received: bool,
 147    enter_token: Option<()>,
 148    button_pressed: Option<MouseButton>,
 149    mouse_focused_window: Option<WaylandWindowStatePtr>,
 150    keyboard_focused_window: Option<WaylandWindowStatePtr>,
 151    loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
 152    cursor_style: Option<CursorStyle>,
 153    cursor: Cursor,
 154    clipboard: Option<Clipboard>,
 155    primary: Option<Primary>,
 156    event_loop: Option<EventLoop<'static, WaylandClientStatePtr>>,
 157    common: LinuxCommon,
 158
 159    pending_open_uri: Option<String>,
 160}
 161
 162pub struct DragState {
 163    data_offer: Option<wl_data_offer::WlDataOffer>,
 164    window: Option<WaylandWindowStatePtr>,
 165    position: Point<Pixels>,
 166}
 167
 168pub struct ClickState {
 169    last_click: Instant,
 170    last_location: Point<Pixels>,
 171    current_count: usize,
 172}
 173
 174pub(crate) struct KeyRepeat {
 175    characters_per_second: u32,
 176    delay: Duration,
 177    current_id: u64,
 178    current_keycode: Option<xkb::Keycode>,
 179}
 180
 181/// This struct is required to conform to Rust's orphan rules, so we can dispatch on the state but hand the
 182/// window to GPUI.
 183#[derive(Clone)]
 184pub struct WaylandClientStatePtr(Weak<RefCell<WaylandClientState>>);
 185
 186impl WaylandClientStatePtr {
 187    fn get_client(&self) -> Rc<RefCell<WaylandClientState>> {
 188        self.0
 189            .upgrade()
 190            .expect("The pointer should always be valid when dispatching in wayland")
 191    }
 192
 193    pub fn drop_window(&self, surface_id: &ObjectId) {
 194        let mut client = self.get_client();
 195        let mut state = client.borrow_mut();
 196        let closed_window = state.windows.remove(surface_id).unwrap();
 197        if let Some(window) = state.mouse_focused_window.take() {
 198            if !window.ptr_eq(&closed_window) {
 199                state.mouse_focused_window = Some(window);
 200            }
 201        }
 202        if let Some(window) = state.keyboard_focused_window.take() {
 203            if !window.ptr_eq(&closed_window) {
 204                state.mouse_focused_window = Some(window);
 205            }
 206        }
 207        if state.windows.is_empty() {
 208            state.common.signal.stop();
 209        }
 210    }
 211}
 212
 213#[derive(Clone)]
 214pub struct WaylandClient(Rc<RefCell<WaylandClientState>>);
 215
 216impl Drop for WaylandClient {
 217    fn drop(&mut self) {
 218        let mut state = self.0.borrow_mut();
 219        state.windows.clear();
 220
 221        // Drop the clipboard to prevent a seg fault after we've closed all Wayland connections.
 222        state.primary = None;
 223        state.clipboard = None;
 224        if let Some(wl_pointer) = &state.wl_pointer {
 225            wl_pointer.release();
 226        }
 227        if let Some(cursor_shape_device) = &state.cursor_shape_device {
 228            cursor_shape_device.destroy();
 229        }
 230        if let Some(data_device) = &state.data_device {
 231            data_device.release();
 232        }
 233    }
 234}
 235
 236const WL_DATA_DEVICE_MANAGER_VERSION: u32 = 3;
 237const WL_OUTPUT_VERSION: u32 = 2;
 238
 239fn wl_seat_version(version: u32) -> u32 {
 240    // We rely on the wl_pointer.frame event
 241    const WL_SEAT_MIN_VERSION: u32 = 5;
 242    const WL_SEAT_MAX_VERSION: u32 = 9;
 243
 244    if version < WL_SEAT_MIN_VERSION {
 245        panic!(
 246            "wl_seat below required version: {} < {}",
 247            version, WL_SEAT_MIN_VERSION
 248        );
 249    }
 250
 251    version.clamp(WL_SEAT_MIN_VERSION, WL_SEAT_MAX_VERSION)
 252}
 253
 254impl WaylandClient {
 255    pub(crate) fn new() -> Self {
 256        let conn = Connection::connect_to_env().unwrap();
 257
 258        let (globals, mut event_queue) =
 259            registry_queue_init::<WaylandClientStatePtr>(&conn).unwrap();
 260        let qh = event_queue.handle();
 261
 262        let mut seat: Option<wl_seat::WlSeat> = None;
 263        let mut outputs = HashMap::default();
 264        globals.contents().with_list(|list| {
 265            for global in list {
 266                match &global.interface[..] {
 267                    "wl_seat" => {
 268                        seat = Some(globals.registry().bind::<wl_seat::WlSeat, _, _>(
 269                            global.name,
 270                            wl_seat_version(global.version),
 271                            &qh,
 272                            (),
 273                        ));
 274                    }
 275                    "wl_output" => {
 276                        let output = globals.registry().bind::<wl_output::WlOutput, _, _>(
 277                            global.name,
 278                            WL_OUTPUT_VERSION,
 279                            &qh,
 280                            (),
 281                        );
 282                        outputs.insert(output.id(), 1);
 283                    }
 284                    _ => {}
 285                }
 286            }
 287        });
 288
 289        let display = conn.backend().display_ptr() as *mut std::ffi::c_void;
 290
 291        let event_loop = EventLoop::<WaylandClientStatePtr>::try_new().unwrap();
 292
 293        let (common, main_receiver) = LinuxCommon::new(event_loop.get_signal());
 294
 295        let handle = event_loop.handle();
 296        handle.insert_source(main_receiver, |event, _, _: &mut WaylandClientStatePtr| {
 297            if let calloop::channel::Event::Msg(runnable) = event {
 298                runnable.run();
 299            }
 300        });
 301
 302        let seat = seat.unwrap();
 303        let globals = Globals::new(globals, common.foreground_executor.clone(), qh.clone());
 304
 305        let data_device = globals
 306            .data_device_manager
 307            .as_ref()
 308            .map(|data_device_manager| data_device_manager.get_data_device(&seat, &qh, ()));
 309
 310        let (primary, clipboard) = unsafe { create_clipboards_from_external(display) };
 311
 312        let cursor = Cursor::new(&conn, &globals, 24);
 313
 314        let mut state = Rc::new(RefCell::new(WaylandClientState {
 315            serial: 0,
 316            pointer_serial: 0,
 317            globals,
 318            wl_seat: seat,
 319            wl_pointer: None,
 320            cursor_shape_device: None,
 321            data_device,
 322            output_scales: outputs,
 323            windows: HashMap::default(),
 324            common,
 325            keymap_state: None,
 326            drag: DragState {
 327                data_offer: None,
 328                window: None,
 329                position: Point::default(),
 330            },
 331            click: ClickState {
 332                last_click: Instant::now(),
 333                last_location: Point::default(),
 334                current_count: 0,
 335            },
 336            repeat: KeyRepeat {
 337                characters_per_second: 16,
 338                delay: Duration::from_millis(500),
 339                current_id: 0,
 340                current_keycode: None,
 341            },
 342            modifiers: Modifiers {
 343                shift: false,
 344                control: false,
 345                alt: false,
 346                function: false,
 347                platform: false,
 348            },
 349            scroll_event_received: false,
 350            axis_source: AxisSource::Wheel,
 351            mouse_location: None,
 352            continuous_scroll_delta: None,
 353            discrete_scroll_delta: None,
 354            vertical_modifier: -1.0,
 355            horizontal_modifier: -1.0,
 356            button_pressed: None,
 357            mouse_focused_window: None,
 358            keyboard_focused_window: None,
 359            loop_handle: handle.clone(),
 360            enter_token: None,
 361            cursor_style: None,
 362            cursor,
 363            clipboard: Some(clipboard),
 364            primary: Some(primary),
 365            event_loop: Some(event_loop),
 366
 367            pending_open_uri: None,
 368        }));
 369
 370        WaylandSource::new(conn, event_queue).insert(handle);
 371
 372        Self(state)
 373    }
 374}
 375
 376impl LinuxClient for WaylandClient {
 377    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 378        Vec::new()
 379    }
 380
 381    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
 382        unimplemented!()
 383    }
 384
 385    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 386        None
 387    }
 388
 389    fn open_window(
 390        &self,
 391        handle: AnyWindowHandle,
 392        params: WindowParams,
 393    ) -> Box<dyn PlatformWindow> {
 394        let mut state = self.0.borrow_mut();
 395
 396        let (window, surface_id) = WaylandWindow::new(
 397            state.globals.clone(),
 398            WaylandClientStatePtr(Rc::downgrade(&self.0)),
 399            params,
 400        );
 401        state.windows.insert(surface_id, window.0.clone());
 402
 403        Box::new(window)
 404    }
 405
 406    fn set_cursor_style(&self, style: CursorStyle) {
 407        let mut state = self.0.borrow_mut();
 408
 409        let need_update = state
 410            .cursor_style
 411            .map_or(true, |current_style| current_style != style);
 412
 413        if need_update {
 414            let serial = state.pointer_serial;
 415            state.cursor_style = Some(style);
 416
 417            if let Some(cursor_shape_device) = &state.cursor_shape_device {
 418                cursor_shape_device.set_shape(serial, style.to_shape());
 419            } else if state.mouse_focused_window.is_some() {
 420                // cursor-shape-v1 isn't supported, set the cursor using a surface.
 421                let wl_pointer = state
 422                    .wl_pointer
 423                    .clone()
 424                    .expect("window is focused by pointer");
 425                state
 426                    .cursor
 427                    .set_icon(&wl_pointer, serial, &style.to_icon_name());
 428            }
 429        }
 430    }
 431
 432    fn open_uri(&self, uri: &str) {
 433        let mut state = self.0.borrow_mut();
 434        if let (Some(activation), Some(window)) = (
 435            state.globals.activation.clone(),
 436            state.mouse_focused_window.clone(),
 437        ) {
 438            state.pending_open_uri = Some(uri.to_owned());
 439            let token = activation.get_activation_token(&state.globals.qh, ());
 440            token.set_serial(state.serial, &state.wl_seat);
 441            token.set_surface(&window.surface());
 442            token.commit();
 443        } else {
 444            open_uri_internal(uri, None);
 445        }
 446    }
 447
 448    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
 449        f(&mut self.0.borrow_mut().common)
 450    }
 451
 452    fn run(&self) {
 453        let mut event_loop = self
 454            .0
 455            .borrow_mut()
 456            .event_loop
 457            .take()
 458            .expect("App is already running");
 459
 460        event_loop
 461            .run(
 462                None,
 463                &mut WaylandClientStatePtr(Rc::downgrade(&self.0)),
 464                |_| {},
 465            )
 466            .log_err();
 467    }
 468
 469    fn write_to_primary(&self, item: crate::ClipboardItem) {
 470        self.0
 471            .borrow_mut()
 472            .primary
 473            .as_mut()
 474            .unwrap()
 475            .set_contents(item.text);
 476    }
 477
 478    fn write_to_clipboard(&self, item: crate::ClipboardItem) {
 479        self.0
 480            .borrow_mut()
 481            .clipboard
 482            .as_mut()
 483            .unwrap()
 484            .set_contents(item.text);
 485    }
 486
 487    fn read_from_primary(&self) -> Option<crate::ClipboardItem> {
 488        self.0
 489            .borrow_mut()
 490            .primary
 491            .as_mut()
 492            .unwrap()
 493            .get_contents()
 494            .ok()
 495            .map(|s| crate::ClipboardItem {
 496                text: s,
 497                metadata: None,
 498            })
 499    }
 500
 501    fn read_from_clipboard(&self) -> Option<crate::ClipboardItem> {
 502        self.0
 503            .borrow_mut()
 504            .clipboard
 505            .as_mut()
 506            .unwrap()
 507            .get_contents()
 508            .ok()
 509            .map(|s| crate::ClipboardItem {
 510                text: s,
 511                metadata: None,
 512            })
 513    }
 514}
 515
 516impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStatePtr {
 517    fn event(
 518        this: &mut Self,
 519        registry: &wl_registry::WlRegistry,
 520        event: wl_registry::Event,
 521        _: &GlobalListContents,
 522        _: &Connection,
 523        qh: &QueueHandle<Self>,
 524    ) {
 525        let mut client = this.get_client();
 526        let mut state = client.borrow_mut();
 527
 528        match event {
 529            wl_registry::Event::Global {
 530                name,
 531                interface,
 532                version,
 533            } => match &interface[..] {
 534                "wl_seat" => {
 535                    state.wl_pointer = None;
 536                    registry.bind::<wl_seat::WlSeat, _, _>(name, wl_seat_version(version), qh, ());
 537                }
 538                "wl_output" => {
 539                    let output =
 540                        registry.bind::<wl_output::WlOutput, _, _>(name, WL_OUTPUT_VERSION, qh, ());
 541
 542                    state.output_scales.insert(output.id(), 1);
 543                }
 544                _ => {}
 545            },
 546            wl_registry::Event::GlobalRemove { name: _ } => {}
 547            _ => {}
 548        }
 549    }
 550}
 551
 552delegate_noop!(WaylandClientStatePtr: ignore xdg_activation_v1::XdgActivationV1);
 553delegate_noop!(WaylandClientStatePtr: ignore wl_compositor::WlCompositor);
 554delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_device_v1::WpCursorShapeDeviceV1);
 555delegate_noop!(WaylandClientStatePtr: ignore wp_cursor_shape_manager_v1::WpCursorShapeManagerV1);
 556delegate_noop!(WaylandClientStatePtr: ignore wl_data_device_manager::WlDataDeviceManager);
 557delegate_noop!(WaylandClientStatePtr: ignore wl_shm::WlShm);
 558delegate_noop!(WaylandClientStatePtr: ignore wl_shm_pool::WlShmPool);
 559delegate_noop!(WaylandClientStatePtr: ignore wl_buffer::WlBuffer);
 560delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
 561delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
 562delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
 563delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
 564
 565impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
 566    fn event(
 567        state: &mut WaylandClientStatePtr,
 568        _: &wl_callback::WlCallback,
 569        event: wl_callback::Event,
 570        surface_id: &ObjectId,
 571        _: &Connection,
 572        qh: &QueueHandle<Self>,
 573    ) {
 574        let client = state.get_client();
 575        let mut state = client.borrow_mut();
 576        let Some(window) = get_window(&mut state, surface_id) else {
 577            return;
 578        };
 579        drop(state);
 580
 581        match event {
 582            wl_callback::Event::Done { callback_data } => {
 583                window.frame(true);
 584            }
 585            _ => {}
 586        }
 587    }
 588}
 589
 590fn get_window(
 591    mut state: &mut RefMut<WaylandClientState>,
 592    surface_id: &ObjectId,
 593) -> Option<WaylandWindowStatePtr> {
 594    state.windows.get(surface_id).cloned()
 595}
 596
 597impl Dispatch<wl_surface::WlSurface, ()> for WaylandClientStatePtr {
 598    fn event(
 599        this: &mut Self,
 600        surface: &wl_surface::WlSurface,
 601        event: <wl_surface::WlSurface as Proxy>::Event,
 602        _: &(),
 603        _: &Connection,
 604        _: &QueueHandle<Self>,
 605    ) {
 606        let mut client = this.get_client();
 607        let mut state = client.borrow_mut();
 608
 609        let Some(window) = get_window(&mut state, &surface.id()) else {
 610            return;
 611        };
 612        let scales = state.output_scales.clone();
 613        drop(state);
 614
 615        window.handle_surface_event(event, scales);
 616    }
 617}
 618
 619impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
 620    fn event(
 621        this: &mut Self,
 622        output: &wl_output::WlOutput,
 623        event: <wl_output::WlOutput as Proxy>::Event,
 624        _: &(),
 625        _: &Connection,
 626        _: &QueueHandle<Self>,
 627    ) {
 628        let mut client = this.get_client();
 629        let mut state = client.borrow_mut();
 630
 631        let Some(mut output_scale) = state.output_scales.get_mut(&output.id()) else {
 632            return;
 633        };
 634
 635        match event {
 636            wl_output::Event::Scale { factor } => {
 637                *output_scale = factor;
 638            }
 639            _ => {}
 640        }
 641    }
 642}
 643
 644impl Dispatch<xdg_surface::XdgSurface, ObjectId> for WaylandClientStatePtr {
 645    fn event(
 646        state: &mut Self,
 647        xdg_surface: &xdg_surface::XdgSurface,
 648        event: xdg_surface::Event,
 649        surface_id: &ObjectId,
 650        _: &Connection,
 651        _: &QueueHandle<Self>,
 652    ) {
 653        let client = state.get_client();
 654        let mut state = client.borrow_mut();
 655        let Some(window) = get_window(&mut state, surface_id) else {
 656            return;
 657        };
 658        drop(state);
 659        window.handle_xdg_surface_event(event);
 660    }
 661}
 662
 663impl Dispatch<xdg_toplevel::XdgToplevel, ObjectId> for WaylandClientStatePtr {
 664    fn event(
 665        this: &mut Self,
 666        xdg_toplevel: &xdg_toplevel::XdgToplevel,
 667        event: <xdg_toplevel::XdgToplevel as Proxy>::Event,
 668        surface_id: &ObjectId,
 669        _: &Connection,
 670        _: &QueueHandle<Self>,
 671    ) {
 672        let client = this.get_client();
 673        let mut state = client.borrow_mut();
 674        let Some(window) = get_window(&mut state, surface_id) else {
 675            return;
 676        };
 677
 678        drop(state);
 679        let should_close = window.handle_toplevel_event(event);
 680
 681        if should_close {
 682            this.drop_window(surface_id);
 683        }
 684    }
 685}
 686
 687impl Dispatch<xdg_wm_base::XdgWmBase, ()> for WaylandClientStatePtr {
 688    fn event(
 689        this: &mut Self,
 690        wm_base: &xdg_wm_base::XdgWmBase,
 691        event: <xdg_wm_base::XdgWmBase as Proxy>::Event,
 692        _: &(),
 693        _: &Connection,
 694        _: &QueueHandle<Self>,
 695    ) {
 696        if let xdg_wm_base::Event::Ping { serial } = event {
 697            let client = this.get_client();
 698            let mut state = client.borrow_mut();
 699            state.serial = serial;
 700            wm_base.pong(serial);
 701        }
 702    }
 703}
 704
 705impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClientStatePtr {
 706    fn event(
 707        this: &mut Self,
 708        token: &xdg_activation_token_v1::XdgActivationTokenV1,
 709        event: <xdg_activation_token_v1::XdgActivationTokenV1 as Proxy>::Event,
 710        _: &(),
 711        _: &Connection,
 712        _: &QueueHandle<Self>,
 713    ) {
 714        let client = this.get_client();
 715        let mut state = client.borrow_mut();
 716        if let xdg_activation_token_v1::Event::Done { token } = event {
 717            if let Some(uri) = state.pending_open_uri.take() {
 718                open_uri_internal(&uri, Some(&token));
 719            } else {
 720                log::error!("called while pending_open_uri is None");
 721            }
 722        }
 723        token.destroy();
 724    }
 725}
 726
 727impl Dispatch<wl_seat::WlSeat, ()> for WaylandClientStatePtr {
 728    fn event(
 729        state: &mut Self,
 730        seat: &wl_seat::WlSeat,
 731        event: wl_seat::Event,
 732        data: &(),
 733        conn: &Connection,
 734        qh: &QueueHandle<Self>,
 735    ) {
 736        if let wl_seat::Event::Capabilities {
 737            capabilities: WEnum::Value(capabilities),
 738        } = event
 739        {
 740            if capabilities.contains(wl_seat::Capability::Keyboard) {
 741                seat.get_keyboard(qh, ());
 742            }
 743            if capabilities.contains(wl_seat::Capability::Pointer) {
 744                let client = state.get_client();
 745                let mut state = client.borrow_mut();
 746                let pointer = seat.get_pointer(qh, ());
 747                state.cursor_shape_device = state
 748                    .globals
 749                    .cursor_shape_manager
 750                    .as_ref()
 751                    .map(|cursor_shape_manager| cursor_shape_manager.get_pointer(&pointer, qh, ()));
 752                state.wl_pointer = Some(pointer);
 753            }
 754        }
 755    }
 756}
 757
 758impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
 759    fn event(
 760        this: &mut Self,
 761        keyboard: &wl_keyboard::WlKeyboard,
 762        event: wl_keyboard::Event,
 763        data: &(),
 764        conn: &Connection,
 765        qh: &QueueHandle<Self>,
 766    ) {
 767        let mut client = this.get_client();
 768        let mut state = client.borrow_mut();
 769        match event {
 770            wl_keyboard::Event::RepeatInfo { rate, delay } => {
 771                state.repeat.characters_per_second = rate as u32;
 772                state.repeat.delay = Duration::from_millis(delay as u64);
 773            }
 774            wl_keyboard::Event::Keymap {
 775                format: WEnum::Value(format),
 776                fd,
 777                size,
 778                ..
 779            } => {
 780                assert_eq!(
 781                    format,
 782                    wl_keyboard::KeymapFormat::XkbV1,
 783                    "Unsupported keymap format"
 784                );
 785                let keymap = unsafe {
 786                    xkb::Keymap::new_from_fd(
 787                        &xkb::Context::new(xkb::CONTEXT_NO_FLAGS),
 788                        fd,
 789                        size as usize,
 790                        XKB_KEYMAP_FORMAT_TEXT_V1,
 791                        KEYMAP_COMPILE_NO_FLAGS,
 792                    )
 793                    .log_err()
 794                    .flatten()
 795                    .expect("Failed to create keymap")
 796                };
 797                state.keymap_state = Some(xkb::State::new(&keymap));
 798            }
 799            wl_keyboard::Event::Enter {
 800                serial, surface, ..
 801            } => {
 802                state.serial = serial;
 803                state.keyboard_focused_window = get_window(&mut state, &surface.id());
 804
 805                if let Some(window) = state.keyboard_focused_window.clone() {
 806                    drop(state);
 807                    window.set_focused(true);
 808                }
 809            }
 810            wl_keyboard::Event::Leave {
 811                serial, surface, ..
 812            } => {
 813                state.serial = serial;
 814                let keyboard_focused_window = get_window(&mut state, &surface.id());
 815                state.keyboard_focused_window = None;
 816
 817                if let Some(window) = keyboard_focused_window {
 818                    drop(state);
 819                    window.set_focused(false);
 820                }
 821            }
 822            wl_keyboard::Event::Modifiers {
 823                serial,
 824                mods_depressed,
 825                mods_latched,
 826                mods_locked,
 827                group,
 828                ..
 829            } => {
 830                state.serial = serial;
 831                let focused_window = state.keyboard_focused_window.clone();
 832                let Some(focused_window) = focused_window else {
 833                    return;
 834                };
 835
 836                let keymap_state = state.keymap_state.as_mut().unwrap();
 837                keymap_state.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group);
 838                state.modifiers = Modifiers::from_xkb(keymap_state);
 839
 840                let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
 841                    modifiers: state.modifiers,
 842                });
 843
 844                drop(state);
 845                focused_window.handle_input(input);
 846            }
 847            wl_keyboard::Event::Key {
 848                key,
 849                state: WEnum::Value(key_state),
 850                serial,
 851                ..
 852            } => {
 853                state.serial = serial;
 854
 855                let focused_window = state.keyboard_focused_window.clone();
 856                let Some(focused_window) = focused_window else {
 857                    return;
 858                };
 859                let focused_window = focused_window.clone();
 860
 861                let keymap_state = state.keymap_state.as_ref().unwrap();
 862                let keycode = Keycode::from(key + MIN_KEYCODE);
 863                let keysym = keymap_state.key_get_one_sym(keycode);
 864
 865                match key_state {
 866                    wl_keyboard::KeyState::Pressed if !keysym.is_modifier_key() => {
 867                        let input = PlatformInput::KeyDown(KeyDownEvent {
 868                            keystroke: Keystroke::from_xkb(keymap_state, state.modifiers, keycode),
 869                            is_held: false, // todo(linux)
 870                        });
 871
 872                        state.repeat.current_id += 1;
 873                        state.repeat.current_keycode = Some(keycode);
 874
 875                        let rate = state.repeat.characters_per_second;
 876                        let id = state.repeat.current_id;
 877                        state
 878                            .loop_handle
 879                            .insert_source(Timer::from_duration(state.repeat.delay), {
 880                                let input = input.clone();
 881                                move |event, _metadata, this| {
 882                                    let mut client = this.get_client();
 883                                    let mut state = client.borrow_mut();
 884                                    let is_repeating = id == state.repeat.current_id
 885                                        && state.repeat.current_keycode.is_some()
 886                                        && state.keyboard_focused_window.is_some();
 887
 888                                    if !is_repeating {
 889                                        return TimeoutAction::Drop;
 890                                    }
 891
 892                                    let focused_window =
 893                                        state.keyboard_focused_window.as_ref().unwrap().clone();
 894
 895                                    drop(state);
 896                                    focused_window.handle_input(input.clone());
 897
 898                                    TimeoutAction::ToDuration(Duration::from_secs(1) / rate)
 899                                }
 900                            })
 901                            .unwrap();
 902
 903                        drop(state);
 904                        focused_window.handle_input(input);
 905                    }
 906                    wl_keyboard::KeyState::Released if !keysym.is_modifier_key() => {
 907                        let input = PlatformInput::KeyUp(KeyUpEvent {
 908                            keystroke: Keystroke::from_xkb(keymap_state, state.modifiers, keycode),
 909                        });
 910
 911                        if state.repeat.current_keycode == Some(keycode) {
 912                            state.repeat.current_keycode = None;
 913                        }
 914
 915                        drop(state);
 916                        focused_window.handle_input(input);
 917                    }
 918                    _ => {}
 919                }
 920            }
 921            _ => {}
 922        }
 923    }
 924}
 925
 926fn linux_button_to_gpui(button: u32) -> Option<MouseButton> {
 927    // These values are coming from <linux/input-event-codes.h>.
 928    const BTN_LEFT: u32 = 0x110;
 929    const BTN_RIGHT: u32 = 0x111;
 930    const BTN_MIDDLE: u32 = 0x112;
 931    const BTN_SIDE: u32 = 0x113;
 932    const BTN_EXTRA: u32 = 0x114;
 933    const BTN_FORWARD: u32 = 0x115;
 934    const BTN_BACK: u32 = 0x116;
 935
 936    Some(match button {
 937        BTN_LEFT => MouseButton::Left,
 938        BTN_RIGHT => MouseButton::Right,
 939        BTN_MIDDLE => MouseButton::Middle,
 940        BTN_BACK | BTN_SIDE => MouseButton::Navigate(NavigationDirection::Back),
 941        BTN_FORWARD | BTN_EXTRA => MouseButton::Navigate(NavigationDirection::Forward),
 942        _ => return None,
 943    })
 944}
 945
 946impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
 947    fn event(
 948        this: &mut Self,
 949        wl_pointer: &wl_pointer::WlPointer,
 950        event: wl_pointer::Event,
 951        data: &(),
 952        conn: &Connection,
 953        qh: &QueueHandle<Self>,
 954    ) {
 955        let mut client = this.get_client();
 956        let mut state = client.borrow_mut();
 957
 958        match event {
 959            wl_pointer::Event::Enter {
 960                serial,
 961                surface,
 962                surface_x,
 963                surface_y,
 964                ..
 965            } => {
 966                state.pointer_serial = serial;
 967                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
 968
 969                if let Some(window) = get_window(&mut state, &surface.id()) {
 970                    state.enter_token = Some(());
 971                    state.mouse_focused_window = Some(window.clone());
 972                    if let Some(style) = state.cursor_style {
 973                        if let Some(cursor_shape_device) = &state.cursor_shape_device {
 974                            cursor_shape_device.set_shape(serial, style.to_shape());
 975                        } else {
 976                            state
 977                                .cursor
 978                                .set_icon(&wl_pointer, serial, &style.to_icon_name());
 979                        }
 980                    }
 981                    drop(state);
 982                    window.set_focused(true);
 983                }
 984            }
 985            wl_pointer::Event::Leave { surface, .. } => {
 986                if let Some(focused_window) = state.mouse_focused_window.clone() {
 987                    state.enter_token.take();
 988                    let input = PlatformInput::MouseExited(MouseExitEvent {
 989                        position: state.mouse_location.unwrap(),
 990                        pressed_button: state.button_pressed,
 991                        modifiers: state.modifiers,
 992                    });
 993                    state.mouse_focused_window = None;
 994                    state.mouse_location = None;
 995
 996                    drop(state);
 997                    focused_window.handle_input(input);
 998                    focused_window.set_focused(false);
 999                }
1000            }
1001            wl_pointer::Event::Motion {
1002                time,
1003                surface_x,
1004                surface_y,
1005                ..
1006            } => {
1007                if state.mouse_focused_window.is_none() {
1008                    return;
1009                }
1010                state.mouse_location = Some(point(px(surface_x as f32), px(surface_y as f32)));
1011
1012                if let Some(window) = state.mouse_focused_window.clone() {
1013                    let input = PlatformInput::MouseMove(MouseMoveEvent {
1014                        position: state.mouse_location.unwrap(),
1015                        pressed_button: state.button_pressed,
1016                        modifiers: state.modifiers,
1017                    });
1018                    drop(state);
1019                    window.handle_input(input);
1020                }
1021            }
1022            wl_pointer::Event::Button {
1023                serial,
1024                button,
1025                state: WEnum::Value(button_state),
1026                ..
1027            } => {
1028                state.serial = serial;
1029                let button = linux_button_to_gpui(button);
1030                let Some(button) = button else { return };
1031                if state.mouse_focused_window.is_none() {
1032                    return;
1033                }
1034                match button_state {
1035                    wl_pointer::ButtonState::Pressed => {
1036                        let click_elapsed = state.click.last_click.elapsed();
1037
1038                        if click_elapsed < DOUBLE_CLICK_INTERVAL
1039                            && is_within_click_distance(
1040                                state.click.last_location,
1041                                state.mouse_location.unwrap(),
1042                            )
1043                        {
1044                            state.click.current_count += 1;
1045                        } else {
1046                            state.click.current_count = 1;
1047                        }
1048
1049                        state.click.last_click = Instant::now();
1050                        state.click.last_location = state.mouse_location.unwrap();
1051
1052                        state.button_pressed = Some(button);
1053
1054                        if let Some(window) = state.mouse_focused_window.clone() {
1055                            let input = PlatformInput::MouseDown(MouseDownEvent {
1056                                button,
1057                                position: state.mouse_location.unwrap(),
1058                                modifiers: state.modifiers,
1059                                click_count: state.click.current_count,
1060                                first_mouse: state.enter_token.take().is_some(),
1061                            });
1062                            drop(state);
1063                            window.handle_input(input);
1064                        }
1065                    }
1066                    wl_pointer::ButtonState::Released => {
1067                        state.button_pressed = None;
1068
1069                        if let Some(window) = state.mouse_focused_window.clone() {
1070                            let input = PlatformInput::MouseUp(MouseUpEvent {
1071                                button,
1072                                position: state.mouse_location.unwrap(),
1073                                modifiers: state.modifiers,
1074                                click_count: state.click.current_count,
1075                            });
1076                            drop(state);
1077                            window.handle_input(input);
1078                        }
1079                    }
1080                    _ => {}
1081                }
1082            }
1083
1084            // Axis Events
1085            wl_pointer::Event::AxisSource {
1086                axis_source: WEnum::Value(axis_source),
1087            } => {
1088                state.axis_source = axis_source;
1089            }
1090            wl_pointer::Event::Axis {
1091                time,
1092                axis: WEnum::Value(axis),
1093                value,
1094                ..
1095            } => {
1096                let axis_source = state.axis_source;
1097                let axis_modifier = match axis {
1098                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1099                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1100                    _ => 1.0,
1101                };
1102                let supports_relative_direction =
1103                    wl_pointer.version() >= wl_pointer::EVT_AXIS_RELATIVE_DIRECTION_SINCE;
1104                state.scroll_event_received = true;
1105                let scroll_delta = state
1106                    .continuous_scroll_delta
1107                    .get_or_insert(point(px(0.0), px(0.0)));
1108                // TODO: Make nice feeling kinetic scrolling that integrates with the platform's scroll settings
1109                let modifier = 3.0;
1110                match axis {
1111                    wl_pointer::Axis::VerticalScroll => {
1112                        scroll_delta.y += px(value as f32 * modifier * axis_modifier);
1113                    }
1114                    wl_pointer::Axis::HorizontalScroll => {
1115                        scroll_delta.x += px(value as f32 * modifier * axis_modifier);
1116                    }
1117                    _ => unreachable!(),
1118                }
1119            }
1120            wl_pointer::Event::AxisDiscrete {
1121                axis: WEnum::Value(axis),
1122                discrete,
1123            } => {
1124                state.scroll_event_received = true;
1125                let axis_modifier = match axis {
1126                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1127                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1128                    _ => 1.0,
1129                };
1130
1131                // TODO: Make nice feeling kinetic scrolling that integrates with the platform's scroll settings
1132                let modifier = 3.0;
1133
1134                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1135                match axis {
1136                    wl_pointer::Axis::VerticalScroll => {
1137                        scroll_delta.y += discrete as f32 * axis_modifier * modifier;
1138                    }
1139                    wl_pointer::Axis::HorizontalScroll => {
1140                        scroll_delta.x += discrete as f32 * axis_modifier * modifier;
1141                    }
1142                    _ => unreachable!(),
1143                }
1144            }
1145            wl_pointer::Event::AxisRelativeDirection {
1146                axis: WEnum::Value(axis),
1147                direction: WEnum::Value(direction),
1148            } => match (axis, direction) {
1149                (wl_pointer::Axis::VerticalScroll, AxisRelativeDirection::Identical) => {
1150                    state.vertical_modifier = -1.0
1151                }
1152                (wl_pointer::Axis::VerticalScroll, AxisRelativeDirection::Inverted) => {
1153                    state.vertical_modifier = 1.0
1154                }
1155                (wl_pointer::Axis::HorizontalScroll, AxisRelativeDirection::Identical) => {
1156                    state.horizontal_modifier = -1.0
1157                }
1158                (wl_pointer::Axis::HorizontalScroll, AxisRelativeDirection::Inverted) => {
1159                    state.horizontal_modifier = 1.0
1160                }
1161                _ => unreachable!(),
1162            },
1163            wl_pointer::Event::AxisValue120 {
1164                axis: WEnum::Value(axis),
1165                value120,
1166            } => {
1167                state.scroll_event_received = true;
1168                let axis_modifier = match axis {
1169                    wl_pointer::Axis::VerticalScroll => state.vertical_modifier,
1170                    wl_pointer::Axis::HorizontalScroll => state.horizontal_modifier,
1171                    _ => unreachable!(),
1172                };
1173
1174                let scroll_delta = state.discrete_scroll_delta.get_or_insert(point(0.0, 0.0));
1175                let wheel_percent = value120 as f32 / 120.0;
1176                match axis {
1177                    wl_pointer::Axis::VerticalScroll => {
1178                        scroll_delta.y += wheel_percent * axis_modifier;
1179                    }
1180                    wl_pointer::Axis::HorizontalScroll => {
1181                        scroll_delta.x += wheel_percent * axis_modifier;
1182                    }
1183                    _ => unreachable!(),
1184                }
1185            }
1186            wl_pointer::Event::Frame => {
1187                if state.scroll_event_received {
1188                    state.scroll_event_received = false;
1189                    let continuous = state.continuous_scroll_delta.take();
1190                    let discrete = state.discrete_scroll_delta.take();
1191                    if let Some(continuous) = continuous {
1192                        if let Some(window) = state.mouse_focused_window.clone() {
1193                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1194                                position: state.mouse_location.unwrap(),
1195                                delta: ScrollDelta::Pixels(continuous),
1196                                modifiers: state.modifiers,
1197                                touch_phase: TouchPhase::Moved,
1198                            });
1199                            drop(state);
1200                            window.handle_input(input);
1201                        }
1202                    } else if let Some(discrete) = discrete {
1203                        if let Some(window) = state.mouse_focused_window.clone() {
1204                            let input = PlatformInput::ScrollWheel(ScrollWheelEvent {
1205                                position: state.mouse_location.unwrap(),
1206                                delta: ScrollDelta::Lines(discrete),
1207                                modifiers: state.modifiers,
1208                                touch_phase: TouchPhase::Moved,
1209                            });
1210                            drop(state);
1211                            window.handle_input(input);
1212                        }
1213                    }
1214                }
1215            }
1216            _ => {}
1217        }
1218    }
1219}
1220
1221impl Dispatch<wp_fractional_scale_v1::WpFractionalScaleV1, ObjectId> for WaylandClientStatePtr {
1222    fn event(
1223        this: &mut Self,
1224        _: &wp_fractional_scale_v1::WpFractionalScaleV1,
1225        event: <wp_fractional_scale_v1::WpFractionalScaleV1 as Proxy>::Event,
1226        surface_id: &ObjectId,
1227        _: &Connection,
1228        _: &QueueHandle<Self>,
1229    ) {
1230        let client = this.get_client();
1231        let mut state = client.borrow_mut();
1232
1233        let Some(window) = get_window(&mut state, surface_id) else {
1234            return;
1235        };
1236
1237        drop(state);
1238        window.handle_fractional_scale_event(event);
1239    }
1240}
1241
1242impl Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, ObjectId>
1243    for WaylandClientStatePtr
1244{
1245    fn event(
1246        this: &mut Self,
1247        _: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
1248        event: zxdg_toplevel_decoration_v1::Event,
1249        surface_id: &ObjectId,
1250        _: &Connection,
1251        _: &QueueHandle<Self>,
1252    ) {
1253        let client = this.get_client();
1254        let mut state = client.borrow_mut();
1255        let Some(window) = get_window(&mut state, surface_id) else {
1256            return;
1257        };
1258
1259        drop(state);
1260        window.handle_toplevel_decoration_event(event);
1261    }
1262}
1263
1264const FILE_LIST_MIME_TYPE: &str = "text/uri-list";
1265
1266impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
1267    fn event(
1268        this: &mut Self,
1269        _: &wl_data_device::WlDataDevice,
1270        event: wl_data_device::Event,
1271        _: &(),
1272        _: &Connection,
1273        _: &QueueHandle<Self>,
1274    ) {
1275        let client = this.get_client();
1276        let mut state = client.borrow_mut();
1277
1278        match event {
1279            wl_data_device::Event::Enter {
1280                serial,
1281                surface,
1282                x,
1283                y,
1284                id: data_offer,
1285            } => {
1286                state.serial = serial;
1287                if let Some(data_offer) = data_offer {
1288                    let Some(drag_window) = get_window(&mut state, &surface.id()) else {
1289                        return;
1290                    };
1291
1292                    const ACTIONS: DndAction = DndAction::Copy;
1293                    data_offer.set_actions(ACTIONS, ACTIONS);
1294
1295                    let pipe = Pipe::new().unwrap();
1296                    data_offer.receive(FILE_LIST_MIME_TYPE.to_string(), unsafe {
1297                        BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
1298                    });
1299                    let fd = pipe.read;
1300                    drop(pipe.write);
1301
1302                    let read_task = state
1303                        .common
1304                        .background_executor
1305                        .spawn(async { unsafe { read_fd(fd) } });
1306
1307                    let this = this.clone();
1308                    state
1309                        .common
1310                        .foreground_executor
1311                        .spawn(async move {
1312                            let file_list = match read_task.await {
1313                                Ok(list) => list,
1314                                Err(err) => {
1315                                    log::error!("error reading drag and drop pipe: {err:?}");
1316                                    return;
1317                                }
1318                            };
1319
1320                            let paths: SmallVec<[_; 2]> = file_list
1321                                .lines()
1322                                .map(|path| PathBuf::from(path.replace("file://", "")))
1323                                .collect();
1324                            let position = Point::new(x.into(), y.into());
1325
1326                            // Prevent dropping text from other programs.
1327                            if paths.is_empty() {
1328                                data_offer.finish();
1329                                data_offer.destroy();
1330                                return;
1331                            }
1332
1333                            let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1334                                position,
1335                                paths: crate::ExternalPaths(paths),
1336                            });
1337
1338                            let client = this.get_client();
1339                            let mut state = client.borrow_mut();
1340                            state.drag.data_offer = Some(data_offer);
1341                            state.drag.window = Some(drag_window.clone());
1342                            state.drag.position = position;
1343
1344                            drop(state);
1345                            drag_window.handle_input(input);
1346                        })
1347                        .detach();
1348                }
1349            }
1350            wl_data_device::Event::Motion { x, y, .. } => {
1351                let Some(drag_window) = state.drag.window.clone() else {
1352                    return;
1353                };
1354                let position = Point::new(x.into(), y.into());
1355                state.drag.position = position;
1356
1357                let input = PlatformInput::FileDrop(FileDropEvent::Pending { position });
1358                drop(state);
1359                drag_window.handle_input(input);
1360            }
1361            wl_data_device::Event::Leave => {
1362                let Some(drag_window) = state.drag.window.clone() else {
1363                    return;
1364                };
1365                let data_offer = state.drag.data_offer.clone().unwrap();
1366                data_offer.destroy();
1367
1368                state.drag.data_offer = None;
1369                state.drag.window = None;
1370
1371                let input = PlatformInput::FileDrop(FileDropEvent::Exited {});
1372                drop(state);
1373                drag_window.handle_input(input);
1374            }
1375            wl_data_device::Event::Drop => {
1376                let Some(drag_window) = state.drag.window.clone() else {
1377                    return;
1378                };
1379                let data_offer = state.drag.data_offer.clone().unwrap();
1380                data_offer.finish();
1381                data_offer.destroy();
1382
1383                state.drag.data_offer = None;
1384                state.drag.window = None;
1385
1386                let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1387                    position: state.drag.position,
1388                });
1389                drop(state);
1390                drag_window.handle_input(input);
1391            }
1392            _ => {}
1393        }
1394    }
1395
1396    event_created_child!(WaylandClientStatePtr, wl_data_device::WlDataDevice, [
1397        wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()),
1398    ]);
1399}
1400
1401impl Dispatch<wl_data_offer::WlDataOffer, ()> for WaylandClientStatePtr {
1402    fn event(
1403        this: &mut Self,
1404        data_offer: &wl_data_offer::WlDataOffer,
1405        event: wl_data_offer::Event,
1406        _: &(),
1407        _: &Connection,
1408        _: &QueueHandle<Self>,
1409    ) {
1410        let client = this.get_client();
1411        let mut state = client.borrow_mut();
1412
1413        match event {
1414            wl_data_offer::Event::Offer { mime_type } => {
1415                if mime_type == FILE_LIST_MIME_TYPE {
1416                    data_offer.accept(state.serial, Some(mime_type));
1417                }
1418            }
1419            _ => {}
1420        }
1421    }
1422}