client.rs

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