client.rs

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