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