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