client.rs

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