client.rs

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