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