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