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