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