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