client.rs

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