platform.rs

   1mod app_menu;
   2mod keyboard;
   3mod keystroke;
   4
   5#[cfg(any(target_os = "linux", target_os = "freebsd"))]
   6mod linux;
   7
   8#[cfg(target_os = "macos")]
   9mod mac;
  10
  11#[cfg(any(
  12    all(
  13        any(target_os = "linux", target_os = "freebsd"),
  14        any(feature = "x11", feature = "wayland")
  15    ),
  16    all(target_os = "macos", feature = "macos-blade")
  17))]
  18mod blade;
  19
  20#[cfg(any(test, feature = "test-support"))]
  21mod test;
  22
  23#[cfg(target_os = "windows")]
  24mod windows;
  25
  26#[cfg(all(
  27    feature = "screen-capture",
  28    any(
  29        target_os = "windows",
  30        all(
  31            any(target_os = "linux", target_os = "freebsd"),
  32            any(feature = "wayland", feature = "x11"),
  33        )
  34    )
  35))]
  36pub(crate) mod scap_screen_capture;
  37
  38use crate::{
  39    Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
  40    DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun,
  41    ForegroundExecutor, GlyphId, GpuSpecs, ImageSource, Keymap, LineLayout, Pixels, PlatformInput,
  42    Point, Priority, RealtimePriority, RenderGlyphParams, RenderImage, RenderImageParams,
  43    RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString, Size, SvgRenderer,
  44    SystemWindowTab, Task, TaskLabel, TaskTiming, ThreadTaskTimings, Window, WindowControlArea,
  45    hash, point, px, size,
  46};
  47use anyhow::Result;
  48use async_task::Runnable;
  49use futures::channel::oneshot;
  50#[cfg(any(test, feature = "test-support"))]
  51use image::RgbaImage;
  52use image::codecs::gif::GifDecoder;
  53use image::{AnimationDecoder as _, Frame};
  54use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
  55use schemars::JsonSchema;
  56use seahash::SeaHasher;
  57use serde::{Deserialize, Serialize};
  58use smallvec::SmallVec;
  59use std::borrow::Cow;
  60use std::hash::{Hash, Hasher};
  61use std::io::Cursor;
  62use std::ops;
  63use std::time::{Duration, Instant};
  64use std::{
  65    fmt::{self, Debug},
  66    ops::Range,
  67    path::{Path, PathBuf},
  68    rc::Rc,
  69    sync::Arc,
  70};
  71use strum::EnumIter;
  72use uuid::Uuid;
  73
  74pub use app_menu::*;
  75pub use keyboard::*;
  76pub use keystroke::*;
  77
  78#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  79pub(crate) use linux::*;
  80#[cfg(target_os = "macos")]
  81pub(crate) use mac::*;
  82#[cfg(any(test, feature = "test-support"))]
  83pub(crate) use test::*;
  84#[cfg(target_os = "windows")]
  85pub(crate) use windows::*;
  86
  87#[cfg(all(target_os = "linux", feature = "wayland"))]
  88pub use linux::layer_shell;
  89
  90#[cfg(any(test, feature = "test-support"))]
  91pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
  92
  93#[cfg(all(
  94    target_os = "macos",
  95    feature = "screen-capture",
  96    any(test, feature = "test-support")
  97))]
  98pub use mac::{
  99    capture_window_screenshot, cv_pixel_buffer_to_rgba_image, screen_capture_frame_to_rgba_image,
 100};
 101
 102/// Returns a background executor for the current platform.
 103pub fn background_executor() -> BackgroundExecutor {
 104    current_platform(true).background_executor()
 105}
 106
 107#[cfg(target_os = "macos")]
 108pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
 109    Rc::new(MacPlatform::new(headless))
 110}
 111
 112#[cfg(any(target_os = "linux", target_os = "freebsd"))]
 113pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
 114    #[cfg(feature = "x11")]
 115    use anyhow::Context as _;
 116
 117    if headless {
 118        return Rc::new(HeadlessClient::new());
 119    }
 120
 121    match guess_compositor() {
 122        #[cfg(feature = "wayland")]
 123        "Wayland" => Rc::new(WaylandClient::new()),
 124
 125        #[cfg(feature = "x11")]
 126        "X11" => Rc::new(
 127            X11Client::new()
 128                .context("Failed to initialize X11 client.")
 129                .unwrap(),
 130        ),
 131
 132        "Headless" => Rc::new(HeadlessClient::new()),
 133        _ => unreachable!(),
 134    }
 135}
 136
 137#[cfg(target_os = "windows")]
 138pub(crate) fn current_platform(_headless: bool) -> Rc<dyn Platform> {
 139    Rc::new(
 140        WindowsPlatform::new()
 141            .inspect_err(|err| show_error("Failed to launch", err.to_string()))
 142            .unwrap(),
 143    )
 144}
 145
 146/// Return which compositor we're guessing we'll use.
 147/// Does not attempt to connect to the given compositor
 148#[cfg(any(target_os = "linux", target_os = "freebsd"))]
 149#[inline]
 150pub fn guess_compositor() -> &'static str {
 151    if std::env::var_os("ZED_HEADLESS").is_some() {
 152        return "Headless";
 153    }
 154
 155    #[cfg(feature = "wayland")]
 156    let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
 157    #[cfg(not(feature = "wayland"))]
 158    let wayland_display: Option<std::ffi::OsString> = None;
 159
 160    #[cfg(feature = "x11")]
 161    let x11_display = std::env::var_os("DISPLAY");
 162    #[cfg(not(feature = "x11"))]
 163    let x11_display: Option<std::ffi::OsString> = None;
 164
 165    let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
 166    let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
 167
 168    if use_wayland {
 169        "Wayland"
 170    } else if use_x11 {
 171        "X11"
 172    } else {
 173        "Headless"
 174    }
 175}
 176
 177pub(crate) trait Platform: 'static {
 178    fn background_executor(&self) -> BackgroundExecutor;
 179    fn foreground_executor(&self) -> ForegroundExecutor;
 180    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
 181
 182    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
 183    fn quit(&self);
 184    fn restart(&self, binary_path: Option<PathBuf>);
 185    fn activate(&self, ignoring_other_apps: bool);
 186    fn hide(&self);
 187    fn hide_other_apps(&self);
 188    fn unhide_other_apps(&self);
 189
 190    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
 191    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 192    fn active_window(&self) -> Option<AnyWindowHandle>;
 193    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 194        None
 195    }
 196
 197    #[cfg(feature = "screen-capture")]
 198    fn is_screen_capture_supported(&self) -> bool;
 199    #[cfg(not(feature = "screen-capture"))]
 200    fn is_screen_capture_supported(&self) -> bool {
 201        false
 202    }
 203    #[cfg(feature = "screen-capture")]
 204    fn screen_capture_sources(&self)
 205    -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>>;
 206    #[cfg(not(feature = "screen-capture"))]
 207    fn screen_capture_sources(
 208        &self,
 209    ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
 210        let (sources_tx, sources_rx) = oneshot::channel();
 211        sources_tx
 212            .send(Err(anyhow::anyhow!(
 213                "gpui was compiled without the screen-capture feature"
 214            )))
 215            .ok();
 216        sources_rx
 217    }
 218
 219    fn open_window(
 220        &self,
 221        handle: AnyWindowHandle,
 222        options: WindowParams,
 223    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
 224
 225    /// Returns the appearance of the application's windows.
 226    fn window_appearance(&self) -> WindowAppearance;
 227
 228    fn open_url(&self, url: &str);
 229    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
 230    fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
 231
 232    fn prompt_for_paths(
 233        &self,
 234        options: PathPromptOptions,
 235    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
 236    fn prompt_for_new_path(
 237        &self,
 238        directory: &Path,
 239        suggested_name: Option<&str>,
 240    ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
 241    fn can_select_mixed_files_and_dirs(&self) -> bool;
 242    fn reveal_path(&self, path: &Path);
 243    fn open_with_system(&self, path: &Path);
 244
 245    fn on_quit(&self, callback: Box<dyn FnMut()>);
 246    fn on_reopen(&self, callback: Box<dyn FnMut()>);
 247
 248    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
 249    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 250        None
 251    }
 252
 253    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
 254    fn perform_dock_menu_action(&self, _action: usize) {}
 255    fn add_recent_document(&self, _path: &Path) {}
 256    fn update_jump_list(
 257        &self,
 258        _menus: Vec<MenuItem>,
 259        _entries: Vec<SmallVec<[PathBuf; 2]>>,
 260    ) -> Vec<SmallVec<[PathBuf; 2]>> {
 261        Vec::new()
 262    }
 263    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
 264    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
 265    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
 266
 267    fn compositor_name(&self) -> &'static str {
 268        ""
 269    }
 270    fn app_path(&self) -> Result<PathBuf>;
 271    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
 272
 273    fn set_cursor_style(&self, style: CursorStyle);
 274    fn should_auto_hide_scrollbars(&self) -> bool;
 275
 276    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 277    fn write_to_primary(&self, item: ClipboardItem);
 278    fn write_to_clipboard(&self, item: ClipboardItem);
 279    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 280    fn read_from_primary(&self) -> Option<ClipboardItem>;
 281    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 282
 283    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
 284    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
 285    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
 286
 287    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
 288    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
 289    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
 290}
 291
 292/// A handle to a platform's display, e.g. a monitor or laptop screen.
 293pub trait PlatformDisplay: Send + Sync + Debug {
 294    /// Get the ID for this display
 295    fn id(&self) -> DisplayId;
 296
 297    /// Returns a stable identifier for this display that can be persisted and used
 298    /// across system restarts.
 299    fn uuid(&self) -> Result<Uuid>;
 300
 301    /// Get the bounds for this display
 302    fn bounds(&self) -> Bounds<Pixels>;
 303
 304    /// Get the visible bounds for this display, excluding taskbar/dock areas.
 305    /// This is the usable area where windows can be placed without being obscured.
 306    /// Defaults to the full display bounds if not overridden.
 307    fn visible_bounds(&self) -> Bounds<Pixels> {
 308        self.bounds()
 309    }
 310
 311    /// Get the default bounds for this display to place a window
 312    fn default_bounds(&self) -> Bounds<Pixels> {
 313        let bounds = self.bounds();
 314        let center = bounds.center();
 315        let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
 316
 317        let offset = clipped_window_size / 2.0;
 318        let origin = point(center.x - offset.width, center.y - offset.height);
 319        Bounds::new(origin, clipped_window_size)
 320    }
 321}
 322
 323/// Metadata for a given [ScreenCaptureSource]
 324#[derive(Clone)]
 325pub struct SourceMetadata {
 326    /// Opaque identifier of this screen.
 327    pub id: u64,
 328    /// Human-readable label for this source.
 329    pub label: Option<SharedString>,
 330    /// Whether this source is the main display.
 331    pub is_main: Option<bool>,
 332    /// Video resolution of this source.
 333    pub resolution: Size<DevicePixels>,
 334}
 335
 336/// A source of on-screen video content that can be captured.
 337pub trait ScreenCaptureSource {
 338    /// Returns metadata for this source.
 339    fn metadata(&self) -> Result<SourceMetadata>;
 340
 341    /// Start capture video from this source, invoking the given callback
 342    /// with each frame.
 343    fn stream(
 344        &self,
 345        foreground_executor: &ForegroundExecutor,
 346        frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
 347    ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
 348}
 349
 350/// A video stream captured from a screen.
 351pub trait ScreenCaptureStream {
 352    /// Returns metadata for this source.
 353    fn metadata(&self) -> Result<SourceMetadata>;
 354}
 355
 356/// A frame of video captured from a screen.
 357pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
 358
 359/// An opaque identifier for a hardware display
 360#[derive(PartialEq, Eq, Hash, Copy, Clone)]
 361pub struct DisplayId(pub(crate) u32);
 362
 363impl From<DisplayId> for u32 {
 364    fn from(id: DisplayId) -> Self {
 365        id.0
 366    }
 367}
 368
 369impl Debug for DisplayId {
 370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 371        write!(f, "DisplayId({})", self.0)
 372    }
 373}
 374
 375/// Which part of the window to resize
 376#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 377pub enum ResizeEdge {
 378    /// The top edge
 379    Top,
 380    /// The top right corner
 381    TopRight,
 382    /// The right edge
 383    Right,
 384    /// The bottom right corner
 385    BottomRight,
 386    /// The bottom edge
 387    Bottom,
 388    /// The bottom left corner
 389    BottomLeft,
 390    /// The left edge
 391    Left,
 392    /// The top left corner
 393    TopLeft,
 394}
 395
 396/// A type to describe the appearance of a window
 397#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 398pub enum WindowDecorations {
 399    #[default]
 400    /// Server side decorations
 401    Server,
 402    /// Client side decorations
 403    Client,
 404}
 405
 406/// A type to describe how this window is currently configured
 407#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 408pub enum Decorations {
 409    /// The window is configured to use server side decorations
 410    #[default]
 411    Server,
 412    /// The window is configured to use client side decorations
 413    Client {
 414        /// The edge tiling state
 415        tiling: Tiling,
 416    },
 417}
 418
 419/// What window controls this platform supports
 420#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
 421pub struct WindowControls {
 422    /// Whether this platform supports fullscreen
 423    pub fullscreen: bool,
 424    /// Whether this platform supports maximize
 425    pub maximize: bool,
 426    /// Whether this platform supports minimize
 427    pub minimize: bool,
 428    /// Whether this platform supports a window menu
 429    pub window_menu: bool,
 430}
 431
 432impl Default for WindowControls {
 433    fn default() -> Self {
 434        // Assume that we can do anything, unless told otherwise
 435        Self {
 436            fullscreen: true,
 437            maximize: true,
 438            minimize: true,
 439            window_menu: true,
 440        }
 441    }
 442}
 443
 444/// A type to describe which sides of the window are currently tiled in some way
 445#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 446pub struct Tiling {
 447    /// Whether the top edge is tiled
 448    pub top: bool,
 449    /// Whether the left edge is tiled
 450    pub left: bool,
 451    /// Whether the right edge is tiled
 452    pub right: bool,
 453    /// Whether the bottom edge is tiled
 454    pub bottom: bool,
 455}
 456
 457impl Tiling {
 458    /// Initializes a [`Tiling`] type with all sides tiled
 459    pub fn tiled() -> Self {
 460        Self {
 461            top: true,
 462            left: true,
 463            right: true,
 464            bottom: true,
 465        }
 466    }
 467
 468    /// Whether any edge is tiled
 469    pub fn is_tiled(&self) -> bool {
 470        self.top || self.left || self.right || self.bottom
 471    }
 472}
 473
 474#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
 475pub(crate) struct RequestFrameOptions {
 476    pub(crate) require_presentation: bool,
 477    /// Force refresh of all rendering states when true
 478    pub(crate) force_render: bool,
 479}
 480
 481pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
 482    fn bounds(&self) -> Bounds<Pixels>;
 483    fn is_maximized(&self) -> bool;
 484    fn window_bounds(&self) -> WindowBounds;
 485    fn content_size(&self) -> Size<Pixels>;
 486    fn resize(&mut self, size: Size<Pixels>);
 487    fn scale_factor(&self) -> f32;
 488    fn appearance(&self) -> WindowAppearance;
 489    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 490    fn mouse_position(&self) -> Point<Pixels>;
 491    fn modifiers(&self) -> Modifiers;
 492    fn capslock(&self) -> Capslock;
 493    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
 494    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
 495    fn prompt(
 496        &self,
 497        level: PromptLevel,
 498        msg: &str,
 499        detail: Option<&str>,
 500        answers: &[PromptButton],
 501    ) -> Option<oneshot::Receiver<usize>>;
 502    fn activate(&self);
 503    fn is_active(&self) -> bool;
 504    fn is_hovered(&self) -> bool;
 505    fn set_title(&mut self, title: &str);
 506    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
 507    fn minimize(&self);
 508    fn zoom(&self);
 509    fn toggle_fullscreen(&self);
 510    fn is_fullscreen(&self) -> bool;
 511    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
 512    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
 513    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
 514    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
 515    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
 516    fn on_moved(&self, callback: Box<dyn FnMut()>);
 517    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
 518    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
 519    fn on_close(&self, callback: Box<dyn FnOnce()>);
 520    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
 521    fn draw(&self, scene: &Scene);
 522    fn completed_frame(&self) {}
 523    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
 524
 525    // macOS specific methods
 526    fn get_title(&self) -> String {
 527        String::new()
 528    }
 529    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
 530        None
 531    }
 532    fn tab_bar_visible(&self) -> bool {
 533        false
 534    }
 535    fn set_edited(&mut self, _edited: bool) {}
 536    fn show_character_palette(&self) {}
 537    fn titlebar_double_click(&self) {}
 538    fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
 539    fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
 540    fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
 541    fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
 542    fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
 543    fn merge_all_windows(&self) {}
 544    fn move_tab_to_new_window(&self) {}
 545    fn toggle_window_tab_overview(&self) {}
 546    fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
 547
 548    #[cfg(target_os = "windows")]
 549    fn get_raw_handle(&self) -> windows::HWND;
 550
 551    // Linux specific methods
 552    fn inner_window_bounds(&self) -> WindowBounds {
 553        self.window_bounds()
 554    }
 555    fn request_decorations(&self, _decorations: WindowDecorations) {}
 556    fn show_window_menu(&self, _position: Point<Pixels>) {}
 557    fn start_window_move(&self) {}
 558    fn start_window_resize(&self, _edge: ResizeEdge) {}
 559    fn window_decorations(&self) -> Decorations {
 560        Decorations::Server
 561    }
 562    fn set_app_id(&mut self, _app_id: &str) {}
 563    fn map_window(&mut self) -> anyhow::Result<()> {
 564        Ok(())
 565    }
 566    fn window_controls(&self) -> WindowControls {
 567        WindowControls::default()
 568    }
 569    fn set_client_inset(&self, _inset: Pixels) {}
 570    fn gpu_specs(&self) -> Option<GpuSpecs>;
 571
 572    fn update_ime_position(&self, _bounds: Bounds<Pixels>);
 573
 574    #[cfg(any(test, feature = "test-support"))]
 575    fn as_test(&mut self) -> Option<&mut TestWindow> {
 576        None
 577    }
 578
 579    /// Returns the native window ID (CGWindowID on macOS) for window capture.
 580    /// This is used by visual testing infrastructure to capture window screenshots.
 581    #[cfg(any(test, feature = "test-support"))]
 582    fn native_window_id(&self) -> Option<u32> {
 583        None
 584    }
 585
 586    /// Renders the given scene to a texture and returns the pixel data as an RGBA image.
 587    /// This does not present the frame to screen - useful for visual testing where we want
 588    /// to capture what would be rendered without displaying it or requiring the window to be visible.
 589    #[cfg(any(test, feature = "test-support"))]
 590    fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
 591        anyhow::bail!("render_to_image not implemented for this platform")
 592    }
 593}
 594
 595/// This type is public so that our test macro can generate and use it, but it should not
 596/// be considered part of our public API.
 597#[doc(hidden)]
 598#[derive(Debug)]
 599pub struct RunnableMeta {
 600    /// Location of the runnable
 601    pub location: &'static core::panic::Location<'static>,
 602}
 603
 604#[doc(hidden)]
 605pub enum RunnableVariant {
 606    Meta(Runnable<RunnableMeta>),
 607    Compat(Runnable),
 608}
 609
 610/// This type is public so that our test macro can generate and use it, but it should not
 611/// be considered part of our public API.
 612#[doc(hidden)]
 613pub trait PlatformDispatcher: Send + Sync {
 614    fn get_all_timings(&self) -> Vec<ThreadTaskTimings>;
 615    fn get_current_thread_timings(&self) -> Vec<TaskTiming>;
 616    fn is_main_thread(&self) -> bool;
 617    fn dispatch(&self, runnable: RunnableVariant, label: Option<TaskLabel>, priority: Priority);
 618    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
 619    fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
 620    fn spawn_realtime(&self, priority: RealtimePriority, f: Box<dyn FnOnce() + Send>);
 621
 622    fn now(&self) -> Instant {
 623        Instant::now()
 624    }
 625
 626    #[cfg(any(test, feature = "test-support"))]
 627    fn as_test(&self) -> Option<&TestDispatcher> {
 628        None
 629    }
 630}
 631
 632pub(crate) trait PlatformTextSystem: Send + Sync {
 633    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
 634    fn all_font_names(&self) -> Vec<String>;
 635    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
 636    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
 637    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
 638    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
 639    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
 640    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
 641    fn rasterize_glyph(
 642        &self,
 643        params: &RenderGlyphParams,
 644        raster_bounds: Bounds<DevicePixels>,
 645    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
 646    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
 647}
 648
 649pub(crate) struct NoopTextSystem;
 650
 651impl NoopTextSystem {
 652    #[allow(dead_code)]
 653    pub fn new() -> Self {
 654        Self
 655    }
 656}
 657
 658impl PlatformTextSystem for NoopTextSystem {
 659    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 660        Ok(())
 661    }
 662
 663    fn all_font_names(&self) -> Vec<String> {
 664        Vec::new()
 665    }
 666
 667    fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
 668        Ok(FontId(1))
 669    }
 670
 671    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
 672        FontMetrics {
 673            units_per_em: 1000,
 674            ascent: 1025.0,
 675            descent: -275.0,
 676            line_gap: 0.0,
 677            underline_position: -95.0,
 678            underline_thickness: 60.0,
 679            cap_height: 698.0,
 680            x_height: 516.0,
 681            bounding_box: Bounds {
 682                origin: Point {
 683                    x: -260.0,
 684                    y: -245.0,
 685                },
 686                size: Size {
 687                    width: 1501.0,
 688                    height: 1364.0,
 689                },
 690            },
 691        }
 692    }
 693
 694    fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
 695        Ok(Bounds {
 696            origin: Point { x: 54.0, y: 0.0 },
 697            size: size(392.0, 528.0),
 698        })
 699    }
 700
 701    fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
 702        Ok(size(600.0 * glyph_id.0 as f32, 0.0))
 703    }
 704
 705    fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
 706        Some(GlyphId(ch.len_utf16() as u32))
 707    }
 708
 709    fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 710        Ok(Default::default())
 711    }
 712
 713    fn rasterize_glyph(
 714        &self,
 715        _params: &RenderGlyphParams,
 716        raster_bounds: Bounds<DevicePixels>,
 717    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 718        Ok((raster_bounds.size, Vec::new()))
 719    }
 720
 721    fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
 722        let mut position = px(0.);
 723        let metrics = self.font_metrics(FontId(0));
 724        let em_width = font_size
 725            * self
 726                .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
 727                .unwrap()
 728                .width
 729            / metrics.units_per_em as f32;
 730        let mut glyphs = Vec::new();
 731        for (ix, c) in text.char_indices() {
 732            if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
 733                glyphs.push(ShapedGlyph {
 734                    id: glyph,
 735                    position: point(position, px(0.)),
 736                    index: ix,
 737                    is_emoji: glyph.0 == 2,
 738                });
 739                if glyph.0 == 2 {
 740                    position += em_width * 2.0;
 741                } else {
 742                    position += em_width;
 743                }
 744            } else {
 745                position += em_width
 746            }
 747        }
 748        let mut runs = Vec::default();
 749        if !glyphs.is_empty() {
 750            runs.push(ShapedRun {
 751                font_id: FontId(0),
 752                glyphs,
 753            });
 754        } else {
 755            position = px(0.);
 756        }
 757
 758        LineLayout {
 759            font_size,
 760            width: position,
 761            ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
 762            descent: font_size * (metrics.descent / metrics.units_per_em as f32),
 763            runs,
 764            len: text.len(),
 765        }
 766    }
 767}
 768
 769// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.cpp
 770// Copyright (c) Microsoft Corporation.
 771// Licensed under the MIT license.
 772#[allow(dead_code)]
 773pub(crate) fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
 774    const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
 775        [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], // gamma = 1.0
 776        [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], // gamma = 1.1
 777        [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], // gamma = 1.2
 778        [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], // gamma = 1.3
 779        [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], // gamma = 1.4
 780        [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], // gamma = 1.5
 781        [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], // gamma = 1.6
 782        [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], // gamma = 1.7
 783        [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], // gamma = 1.8
 784        [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], // gamma = 1.9
 785        [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], // gamma = 2.0
 786        [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], // gamma = 2.1
 787        [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], // gamma = 2.2
 788    ];
 789
 790    const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
 791    const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
 792
 793    let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
 794    let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
 795
 796    [
 797        ratios[0] * NORM13,
 798        ratios[1] * NORM24,
 799        ratios[2] * NORM13,
 800        ratios[3] * NORM24,
 801    ]
 802}
 803
 804#[derive(PartialEq, Eq, Hash, Clone)]
 805pub(crate) enum AtlasKey {
 806    Glyph(RenderGlyphParams),
 807    Svg(RenderSvgParams),
 808    Image(RenderImageParams),
 809}
 810
 811impl AtlasKey {
 812    #[cfg_attr(
 813        all(
 814            any(target_os = "linux", target_os = "freebsd"),
 815            not(any(feature = "x11", feature = "wayland"))
 816        ),
 817        allow(dead_code)
 818    )]
 819    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
 820        match self {
 821            AtlasKey::Glyph(params) => {
 822                if params.is_emoji {
 823                    AtlasTextureKind::Polychrome
 824                } else {
 825                    AtlasTextureKind::Monochrome
 826                }
 827            }
 828            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
 829            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
 830        }
 831    }
 832}
 833
 834impl From<RenderGlyphParams> for AtlasKey {
 835    fn from(params: RenderGlyphParams) -> Self {
 836        Self::Glyph(params)
 837    }
 838}
 839
 840impl From<RenderSvgParams> for AtlasKey {
 841    fn from(params: RenderSvgParams) -> Self {
 842        Self::Svg(params)
 843    }
 844}
 845
 846impl From<RenderImageParams> for AtlasKey {
 847    fn from(params: RenderImageParams) -> Self {
 848        Self::Image(params)
 849    }
 850}
 851
 852pub(crate) trait PlatformAtlas: Send + Sync {
 853    fn get_or_insert_with<'a>(
 854        &self,
 855        key: &AtlasKey,
 856        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 857    ) -> Result<Option<AtlasTile>>;
 858    fn remove(&self, key: &AtlasKey);
 859}
 860
 861struct AtlasTextureList<T> {
 862    textures: Vec<Option<T>>,
 863    free_list: Vec<usize>,
 864}
 865
 866impl<T> Default for AtlasTextureList<T> {
 867    fn default() -> Self {
 868        Self {
 869            textures: Vec::default(),
 870            free_list: Vec::default(),
 871        }
 872    }
 873}
 874
 875impl<T> ops::Index<usize> for AtlasTextureList<T> {
 876    type Output = Option<T>;
 877
 878    fn index(&self, index: usize) -> &Self::Output {
 879        &self.textures[index]
 880    }
 881}
 882
 883impl<T> AtlasTextureList<T> {
 884    #[allow(unused)]
 885    fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
 886        self.free_list.clear();
 887        self.textures.drain(..)
 888    }
 889
 890    #[allow(dead_code)]
 891    fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
 892        self.textures.iter_mut().flatten()
 893    }
 894}
 895
 896#[derive(Clone, Debug, PartialEq, Eq)]
 897#[repr(C)]
 898pub(crate) struct AtlasTile {
 899    pub(crate) texture_id: AtlasTextureId,
 900    pub(crate) tile_id: TileId,
 901    pub(crate) padding: u32,
 902    pub(crate) bounds: Bounds<DevicePixels>,
 903}
 904
 905#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 906#[repr(C)]
 907pub(crate) struct AtlasTextureId {
 908    // We use u32 instead of usize for Metal Shader Language compatibility
 909    pub(crate) index: u32,
 910    pub(crate) kind: AtlasTextureKind,
 911}
 912
 913#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 914#[repr(C)]
 915#[cfg_attr(
 916    all(
 917        any(target_os = "linux", target_os = "freebsd"),
 918        not(any(feature = "x11", feature = "wayland"))
 919    ),
 920    allow(dead_code)
 921)]
 922pub(crate) enum AtlasTextureKind {
 923    Monochrome = 0,
 924    Polychrome = 1,
 925}
 926
 927#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 928#[repr(C)]
 929pub(crate) struct TileId(pub(crate) u32);
 930
 931impl From<etagere::AllocId> for TileId {
 932    fn from(id: etagere::AllocId) -> Self {
 933        Self(id.serialize())
 934    }
 935}
 936
 937impl From<TileId> for etagere::AllocId {
 938    fn from(id: TileId) -> Self {
 939        Self::deserialize(id.0)
 940    }
 941}
 942
 943pub(crate) struct PlatformInputHandler {
 944    cx: AsyncWindowContext,
 945    handler: Box<dyn InputHandler>,
 946}
 947
 948#[cfg_attr(
 949    all(
 950        any(target_os = "linux", target_os = "freebsd"),
 951        not(any(feature = "x11", feature = "wayland"))
 952    ),
 953    allow(dead_code)
 954)]
 955impl PlatformInputHandler {
 956    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
 957        Self { cx, handler }
 958    }
 959
 960    fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
 961        self.cx
 962            .update(|window, cx| {
 963                self.handler
 964                    .selected_text_range(ignore_disabled_input, window, cx)
 965            })
 966            .ok()
 967            .flatten()
 968    }
 969
 970    #[cfg_attr(target_os = "windows", allow(dead_code))]
 971    fn marked_text_range(&mut self) -> Option<Range<usize>> {
 972        self.cx
 973            .update(|window, cx| self.handler.marked_text_range(window, cx))
 974            .ok()
 975            .flatten()
 976    }
 977
 978    #[cfg_attr(
 979        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
 980        allow(dead_code)
 981    )]
 982    fn text_for_range(
 983        &mut self,
 984        range_utf16: Range<usize>,
 985        adjusted: &mut Option<Range<usize>>,
 986    ) -> Option<String> {
 987        self.cx
 988            .update(|window, cx| {
 989                self.handler
 990                    .text_for_range(range_utf16, adjusted, window, cx)
 991            })
 992            .ok()
 993            .flatten()
 994    }
 995
 996    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
 997        self.cx
 998            .update(|window, cx| {
 999                self.handler
1000                    .replace_text_in_range(replacement_range, text, window, cx);
1001            })
1002            .ok();
1003    }
1004
1005    pub fn replace_and_mark_text_in_range(
1006        &mut self,
1007        range_utf16: Option<Range<usize>>,
1008        new_text: &str,
1009        new_selected_range: Option<Range<usize>>,
1010    ) {
1011        self.cx
1012            .update(|window, cx| {
1013                self.handler.replace_and_mark_text_in_range(
1014                    range_utf16,
1015                    new_text,
1016                    new_selected_range,
1017                    window,
1018                    cx,
1019                )
1020            })
1021            .ok();
1022    }
1023
1024    #[cfg_attr(target_os = "windows", allow(dead_code))]
1025    fn unmark_text(&mut self) {
1026        self.cx
1027            .update(|window, cx| self.handler.unmark_text(window, cx))
1028            .ok();
1029    }
1030
1031    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
1032        self.cx
1033            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
1034            .ok()
1035            .flatten()
1036    }
1037
1038    #[allow(dead_code)]
1039    fn apple_press_and_hold_enabled(&mut self) -> bool {
1040        self.handler.apple_press_and_hold_enabled()
1041    }
1042
1043    pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1044        self.handler.replace_text_in_range(None, input, window, cx);
1045    }
1046
1047    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
1048        let selection = self.handler.selected_text_range(true, window, cx)?;
1049        self.handler.bounds_for_range(
1050            if selection.reversed {
1051                selection.range.start..selection.range.start
1052            } else {
1053                selection.range.end..selection.range.end
1054            },
1055            window,
1056            cx,
1057        )
1058    }
1059
1060    #[allow(unused)]
1061    pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
1062        self.cx
1063            .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
1064            .ok()
1065            .flatten()
1066    }
1067
1068    #[allow(dead_code)]
1069    pub(crate) fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
1070        self.handler.accepts_text_input(window, cx)
1071    }
1072}
1073
1074/// A struct representing a selection in a text buffer, in UTF16 characters.
1075/// This is different from a range because the head may be before the tail.
1076#[derive(Debug)]
1077pub struct UTF16Selection {
1078    /// The range of text in the document this selection corresponds to
1079    /// in UTF16 characters.
1080    pub range: Range<usize>,
1081    /// Whether the head of this selection is at the start (true), or end (false)
1082    /// of the range
1083    pub reversed: bool,
1084}
1085
1086/// Zed's interface for handling text input from the platform's IME system
1087/// This is currently a 1:1 exposure of the NSTextInputClient API:
1088///
1089/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
1090pub trait InputHandler: 'static {
1091    /// Get the range of the user's currently selected text, if any
1092    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
1093    ///
1094    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1095    fn selected_text_range(
1096        &mut self,
1097        ignore_disabled_input: bool,
1098        window: &mut Window,
1099        cx: &mut App,
1100    ) -> Option<UTF16Selection>;
1101
1102    /// Get the range of the currently marked text, if any
1103    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
1104    ///
1105    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1106    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
1107
1108    /// Get the text for the given document range in UTF-16 characters
1109    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
1110    ///
1111    /// range_utf16 is in terms of UTF-16 characters
1112    fn text_for_range(
1113        &mut self,
1114        range_utf16: Range<usize>,
1115        adjusted_range: &mut Option<Range<usize>>,
1116        window: &mut Window,
1117        cx: &mut App,
1118    ) -> Option<String>;
1119
1120    /// Replace the text in the given document range with the given text
1121    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
1122    ///
1123    /// replacement_range is in terms of UTF-16 characters
1124    fn replace_text_in_range(
1125        &mut self,
1126        replacement_range: Option<Range<usize>>,
1127        text: &str,
1128        window: &mut Window,
1129        cx: &mut App,
1130    );
1131
1132    /// Replace the text in the given document range with the given text,
1133    /// and mark the given text as part of an IME 'composing' state
1134    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
1135    ///
1136    /// range_utf16 is in terms of UTF-16 characters
1137    /// new_selected_range is in terms of UTF-16 characters
1138    fn replace_and_mark_text_in_range(
1139        &mut self,
1140        range_utf16: Option<Range<usize>>,
1141        new_text: &str,
1142        new_selected_range: Option<Range<usize>>,
1143        window: &mut Window,
1144        cx: &mut App,
1145    );
1146
1147    /// Remove the IME 'composing' state from the document
1148    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
1149    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
1150
1151    /// Get the bounds of the given document range in screen coordinates
1152    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
1153    ///
1154    /// This is used for positioning the IME candidate window
1155    fn bounds_for_range(
1156        &mut self,
1157        range_utf16: Range<usize>,
1158        window: &mut Window,
1159        cx: &mut App,
1160    ) -> Option<Bounds<Pixels>>;
1161
1162    /// Get the character offset for the given point in terms of UTF16 characters
1163    ///
1164    /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
1165    fn character_index_for_point(
1166        &mut self,
1167        point: Point<Pixels>,
1168        window: &mut Window,
1169        cx: &mut App,
1170    ) -> Option<usize>;
1171
1172    /// Allows a given input context to opt into getting raw key repeats instead of
1173    /// sending these to the platform.
1174    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1175    /// (which is how iTerm does it) but it doesn't seem to work for me.
1176    #[allow(dead_code)]
1177    fn apple_press_and_hold_enabled(&mut self) -> bool {
1178        true
1179    }
1180
1181    /// Returns whether this handler is accepting text input to be inserted.
1182    fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1183        true
1184    }
1185}
1186
1187/// The variables that can be configured when creating a new window
1188#[derive(Debug)]
1189pub struct WindowOptions {
1190    /// Specifies the state and bounds of the window in screen coordinates.
1191    /// - `None`: Inherit the bounds.
1192    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1193    pub window_bounds: Option<WindowBounds>,
1194
1195    /// The titlebar configuration of the window
1196    pub titlebar: Option<TitlebarOptions>,
1197
1198    /// Whether the window should be focused when created
1199    pub focus: bool,
1200
1201    /// Whether the window should be shown when created
1202    pub show: bool,
1203
1204    /// The kind of window to create
1205    pub kind: WindowKind,
1206
1207    /// Whether the window should be movable by the user
1208    pub is_movable: bool,
1209
1210    /// Whether the window should be resizable by the user
1211    pub is_resizable: bool,
1212
1213    /// Whether the window should be minimized by the user
1214    pub is_minimizable: bool,
1215
1216    /// The display to create the window on, if this is None,
1217    /// the window will be created on the main display
1218    pub display_id: Option<DisplayId>,
1219
1220    /// The appearance of the window background.
1221    pub window_background: WindowBackgroundAppearance,
1222
1223    /// Application identifier of the window. Can by used by desktop environments to group applications together.
1224    pub app_id: Option<String>,
1225
1226    /// Window minimum size
1227    pub window_min_size: Option<Size<Pixels>>,
1228
1229    /// Whether to use client or server side decorations. Wayland only
1230    /// Note that this may be ignored.
1231    pub window_decorations: Option<WindowDecorations>,
1232
1233    /// Tab group name, allows opening the window as a native tab on macOS 10.12+. Windows with the same tabbing identifier will be grouped together.
1234    pub tabbing_identifier: Option<String>,
1235}
1236
1237/// The variables that can be configured when creating a new window
1238#[derive(Debug)]
1239#[cfg_attr(
1240    all(
1241        any(target_os = "linux", target_os = "freebsd"),
1242        not(any(feature = "x11", feature = "wayland"))
1243    ),
1244    allow(dead_code)
1245)]
1246pub(crate) struct WindowParams {
1247    pub bounds: Bounds<Pixels>,
1248
1249    /// The titlebar configuration of the window
1250    #[cfg_attr(feature = "wayland", allow(dead_code))]
1251    pub titlebar: Option<TitlebarOptions>,
1252
1253    /// The kind of window to create
1254    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1255    pub kind: WindowKind,
1256
1257    /// Whether the window should be movable by the user
1258    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1259    pub is_movable: bool,
1260
1261    /// Whether the window should be resizable by the user
1262    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1263    pub is_resizable: bool,
1264
1265    /// Whether the window should be minimized by the user
1266    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1267    pub is_minimizable: bool,
1268
1269    #[cfg_attr(
1270        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1271        allow(dead_code)
1272    )]
1273    pub focus: bool,
1274
1275    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1276    pub show: bool,
1277
1278    #[cfg_attr(feature = "wayland", allow(dead_code))]
1279    pub display_id: Option<DisplayId>,
1280
1281    pub window_min_size: Option<Size<Pixels>>,
1282    #[cfg(target_os = "macos")]
1283    pub tabbing_identifier: Option<String>,
1284}
1285
1286/// Represents the status of how a window should be opened.
1287#[derive(Debug, Copy, Clone, PartialEq)]
1288pub enum WindowBounds {
1289    /// Indicates that the window should open in a windowed state with the given bounds.
1290    Windowed(Bounds<Pixels>),
1291    /// Indicates that the window should open in a maximized state.
1292    /// The bounds provided here represent the restore size of the window.
1293    Maximized(Bounds<Pixels>),
1294    /// Indicates that the window should open in fullscreen mode.
1295    /// The bounds provided here represent the restore size of the window.
1296    Fullscreen(Bounds<Pixels>),
1297}
1298
1299impl Default for WindowBounds {
1300    fn default() -> Self {
1301        WindowBounds::Windowed(Bounds::default())
1302    }
1303}
1304
1305impl WindowBounds {
1306    /// Retrieve the inner bounds
1307    pub fn get_bounds(&self) -> Bounds<Pixels> {
1308        match self {
1309            WindowBounds::Windowed(bounds) => *bounds,
1310            WindowBounds::Maximized(bounds) => *bounds,
1311            WindowBounds::Fullscreen(bounds) => *bounds,
1312        }
1313    }
1314
1315    /// Creates a new window bounds that centers the window on the screen.
1316    pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
1317        WindowBounds::Windowed(Bounds::centered(None, size, cx))
1318    }
1319}
1320
1321impl Default for WindowOptions {
1322    fn default() -> Self {
1323        Self {
1324            window_bounds: None,
1325            titlebar: Some(TitlebarOptions {
1326                title: Default::default(),
1327                appears_transparent: Default::default(),
1328                traffic_light_position: Default::default(),
1329            }),
1330            focus: true,
1331            show: true,
1332            kind: WindowKind::Normal,
1333            is_movable: true,
1334            is_resizable: true,
1335            is_minimizable: true,
1336            display_id: None,
1337            window_background: WindowBackgroundAppearance::default(),
1338            app_id: None,
1339            window_min_size: None,
1340            window_decorations: None,
1341            tabbing_identifier: None,
1342        }
1343    }
1344}
1345
1346/// The options that can be configured for a window's titlebar
1347#[derive(Debug, Default)]
1348pub struct TitlebarOptions {
1349    /// The initial title of the window
1350    pub title: Option<SharedString>,
1351
1352    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
1353    /// Refer to [`WindowOptions::window_decorations`] on Linux
1354    pub appears_transparent: bool,
1355
1356    /// The position of the macOS traffic light buttons
1357    pub traffic_light_position: Option<Point<Pixels>>,
1358}
1359
1360/// The kind of window to create
1361#[derive(Clone, Debug, PartialEq, Eq)]
1362pub enum WindowKind {
1363    /// A normal application window
1364    Normal,
1365
1366    /// A window that appears above all other windows, usually used for alerts or popups
1367    /// use sparingly!
1368    PopUp,
1369
1370    /// A floating window that appears on top of its parent window
1371    Floating,
1372
1373    /// A Wayland LayerShell window, used to draw overlays or backgrounds for applications such as
1374    /// docks, notifications or wallpapers.
1375    #[cfg(all(target_os = "linux", feature = "wayland"))]
1376    LayerShell(layer_shell::LayerShellOptions),
1377}
1378
1379/// The appearance of the window, as defined by the operating system.
1380///
1381/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
1382/// values.
1383#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1384pub enum WindowAppearance {
1385    /// A light appearance.
1386    ///
1387    /// On macOS, this corresponds to the `aqua` appearance.
1388    #[default]
1389    Light,
1390
1391    /// A light appearance with vibrant colors.
1392    ///
1393    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
1394    VibrantLight,
1395
1396    /// A dark appearance.
1397    ///
1398    /// On macOS, this corresponds to the `darkAqua` appearance.
1399    Dark,
1400
1401    /// A dark appearance with vibrant colors.
1402    ///
1403    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
1404    VibrantDark,
1405}
1406
1407/// The appearance of the background of the window itself, when there is
1408/// no content or the content is transparent.
1409#[derive(Copy, Clone, Debug, Default, PartialEq)]
1410pub enum WindowBackgroundAppearance {
1411    /// Opaque.
1412    ///
1413    /// This lets the window manager know that content behind this
1414    /// window does not need to be drawn.
1415    ///
1416    /// Actual color depends on the system and themes should define a fully
1417    /// opaque background color instead.
1418    #[default]
1419    Opaque,
1420    /// Plain alpha transparency.
1421    Transparent,
1422    /// Transparency, but the contents behind the window are blurred.
1423    ///
1424    /// Not always supported.
1425    Blurred,
1426    /// The Mica backdrop material, supported on Windows 11.
1427    MicaBackdrop,
1428    /// The Mica Alt backdrop material, supported on Windows 11.
1429    MicaAltBackdrop,
1430}
1431
1432/// The options that can be configured for a file dialog prompt
1433#[derive(Clone, Debug)]
1434pub struct PathPromptOptions {
1435    /// Should the prompt allow files to be selected?
1436    pub files: bool,
1437    /// Should the prompt allow directories to be selected?
1438    pub directories: bool,
1439    /// Should the prompt allow multiple files to be selected?
1440    pub multiple: bool,
1441    /// The prompt to show to a user when selecting a path
1442    pub prompt: Option<SharedString>,
1443}
1444
1445/// What kind of prompt styling to show
1446#[derive(Copy, Clone, Debug, PartialEq)]
1447pub enum PromptLevel {
1448    /// A prompt that is shown when the user should be notified of something
1449    Info,
1450
1451    /// A prompt that is shown when the user needs to be warned of a potential problem
1452    Warning,
1453
1454    /// A prompt that is shown when a critical problem has occurred
1455    Critical,
1456}
1457
1458/// Prompt Button
1459#[derive(Clone, Debug, PartialEq)]
1460pub enum PromptButton {
1461    /// Ok button
1462    Ok(SharedString),
1463    /// Cancel button
1464    Cancel(SharedString),
1465    /// Other button
1466    Other(SharedString),
1467}
1468
1469impl PromptButton {
1470    /// Create a button with label
1471    pub fn new(label: impl Into<SharedString>) -> Self {
1472        PromptButton::Other(label.into())
1473    }
1474
1475    /// Create an Ok button
1476    pub fn ok(label: impl Into<SharedString>) -> Self {
1477        PromptButton::Ok(label.into())
1478    }
1479
1480    /// Create a Cancel button
1481    pub fn cancel(label: impl Into<SharedString>) -> Self {
1482        PromptButton::Cancel(label.into())
1483    }
1484
1485    #[allow(dead_code)]
1486    pub(crate) fn is_cancel(&self) -> bool {
1487        matches!(self, PromptButton::Cancel(_))
1488    }
1489
1490    /// Returns the label of the button
1491    pub fn label(&self) -> &SharedString {
1492        match self {
1493            PromptButton::Ok(label) => label,
1494            PromptButton::Cancel(label) => label,
1495            PromptButton::Other(label) => label,
1496        }
1497    }
1498}
1499
1500impl From<&str> for PromptButton {
1501    fn from(value: &str) -> Self {
1502        match value.to_lowercase().as_str() {
1503            "ok" => PromptButton::Ok("Ok".into()),
1504            "cancel" => PromptButton::Cancel("Cancel".into()),
1505            _ => PromptButton::Other(SharedString::from(value.to_owned())),
1506        }
1507    }
1508}
1509
1510/// The style of the cursor (pointer)
1511#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1512pub enum CursorStyle {
1513    /// The default cursor
1514    #[default]
1515    Arrow,
1516
1517    /// A text input cursor
1518    /// corresponds to the CSS cursor value `text`
1519    IBeam,
1520
1521    /// A crosshair cursor
1522    /// corresponds to the CSS cursor value `crosshair`
1523    Crosshair,
1524
1525    /// A closed hand cursor
1526    /// corresponds to the CSS cursor value `grabbing`
1527    ClosedHand,
1528
1529    /// An open hand cursor
1530    /// corresponds to the CSS cursor value `grab`
1531    OpenHand,
1532
1533    /// A pointing hand cursor
1534    /// corresponds to the CSS cursor value `pointer`
1535    PointingHand,
1536
1537    /// A resize left cursor
1538    /// corresponds to the CSS cursor value `w-resize`
1539    ResizeLeft,
1540
1541    /// A resize right cursor
1542    /// corresponds to the CSS cursor value `e-resize`
1543    ResizeRight,
1544
1545    /// A resize cursor to the left and right
1546    /// corresponds to the CSS cursor value `ew-resize`
1547    ResizeLeftRight,
1548
1549    /// A resize up cursor
1550    /// corresponds to the CSS cursor value `n-resize`
1551    ResizeUp,
1552
1553    /// A resize down cursor
1554    /// corresponds to the CSS cursor value `s-resize`
1555    ResizeDown,
1556
1557    /// A resize cursor directing up and down
1558    /// corresponds to the CSS cursor value `ns-resize`
1559    ResizeUpDown,
1560
1561    /// A resize cursor directing up-left and down-right
1562    /// corresponds to the CSS cursor value `nesw-resize`
1563    ResizeUpLeftDownRight,
1564
1565    /// A resize cursor directing up-right and down-left
1566    /// corresponds to the CSS cursor value `nwse-resize`
1567    ResizeUpRightDownLeft,
1568
1569    /// A cursor indicating that the item/column can be resized horizontally.
1570    /// corresponds to the CSS cursor value `col-resize`
1571    ResizeColumn,
1572
1573    /// A cursor indicating that the item/row can be resized vertically.
1574    /// corresponds to the CSS cursor value `row-resize`
1575    ResizeRow,
1576
1577    /// A text input cursor for vertical layout
1578    /// corresponds to the CSS cursor value `vertical-text`
1579    IBeamCursorForVerticalLayout,
1580
1581    /// A cursor indicating that the operation is not allowed
1582    /// corresponds to the CSS cursor value `not-allowed`
1583    OperationNotAllowed,
1584
1585    /// A cursor indicating that the operation will result in a link
1586    /// corresponds to the CSS cursor value `alias`
1587    DragLink,
1588
1589    /// A cursor indicating that the operation will result in a copy
1590    /// corresponds to the CSS cursor value `copy`
1591    DragCopy,
1592
1593    /// A cursor indicating that the operation will result in a context menu
1594    /// corresponds to the CSS cursor value `context-menu`
1595    ContextualMenu,
1596
1597    /// Hide the cursor
1598    None,
1599}
1600
1601/// A clipboard item that should be copied to the clipboard
1602#[derive(Clone, Debug, Eq, PartialEq)]
1603pub struct ClipboardItem {
1604    entries: Vec<ClipboardEntry>,
1605}
1606
1607/// Either a ClipboardString or a ClipboardImage
1608#[derive(Clone, Debug, Eq, PartialEq)]
1609pub enum ClipboardEntry {
1610    /// A string entry
1611    String(ClipboardString),
1612    /// An image entry
1613    Image(Image),
1614    /// A file entry
1615    ExternalPaths(crate::ExternalPaths),
1616}
1617
1618impl ClipboardItem {
1619    /// Create a new ClipboardItem::String with no associated metadata
1620    pub fn new_string(text: String) -> Self {
1621        Self {
1622            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1623        }
1624    }
1625
1626    /// Create a new ClipboardItem::String with the given text and associated metadata
1627    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1628        Self {
1629            entries: vec![ClipboardEntry::String(ClipboardString {
1630                text,
1631                metadata: Some(metadata),
1632            })],
1633        }
1634    }
1635
1636    /// Create a new ClipboardItem::String with the given text and associated metadata
1637    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1638        Self {
1639            entries: vec![ClipboardEntry::String(
1640                ClipboardString::new(text).with_json_metadata(metadata),
1641            )],
1642        }
1643    }
1644
1645    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1646    pub fn new_image(image: &Image) -> Self {
1647        Self {
1648            entries: vec![ClipboardEntry::Image(image.clone())],
1649        }
1650    }
1651
1652    /// Concatenates together all the ClipboardString entries in the item.
1653    /// Returns None if there were no ClipboardString entries.
1654    pub fn text(&self) -> Option<String> {
1655        let mut answer = String::new();
1656
1657        for entry in self.entries.iter() {
1658            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1659                answer.push_str(text);
1660            }
1661        }
1662
1663        if answer.is_empty() {
1664            for entry in self.entries.iter() {
1665                if let ClipboardEntry::ExternalPaths(paths) = entry {
1666                    for path in &paths.0 {
1667                        use std::fmt::Write as _;
1668                        _ = write!(answer, "{}", path.display());
1669                    }
1670                }
1671            }
1672        }
1673
1674        if !answer.is_empty() {
1675            Some(answer)
1676        } else {
1677            None
1678        }
1679    }
1680
1681    /// If this item is one ClipboardEntry::String, returns its metadata.
1682    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1683    pub fn metadata(&self) -> Option<&String> {
1684        match self.entries().first() {
1685            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1686                clipboard_string.metadata.as_ref()
1687            }
1688            _ => None,
1689        }
1690    }
1691
1692    /// Get the item's entries
1693    pub fn entries(&self) -> &[ClipboardEntry] {
1694        &self.entries
1695    }
1696
1697    /// Get owned versions of the item's entries
1698    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1699        self.entries.into_iter()
1700    }
1701}
1702
1703impl From<ClipboardString> for ClipboardEntry {
1704    fn from(value: ClipboardString) -> Self {
1705        Self::String(value)
1706    }
1707}
1708
1709impl From<String> for ClipboardEntry {
1710    fn from(value: String) -> Self {
1711        Self::from(ClipboardString::from(value))
1712    }
1713}
1714
1715impl From<Image> for ClipboardEntry {
1716    fn from(value: Image) -> Self {
1717        Self::Image(value)
1718    }
1719}
1720
1721impl From<ClipboardEntry> for ClipboardItem {
1722    fn from(value: ClipboardEntry) -> Self {
1723        Self {
1724            entries: vec![value],
1725        }
1726    }
1727}
1728
1729impl From<String> for ClipboardItem {
1730    fn from(value: String) -> Self {
1731        Self::from(ClipboardEntry::from(value))
1732    }
1733}
1734
1735impl From<Image> for ClipboardItem {
1736    fn from(value: Image) -> Self {
1737        Self::from(ClipboardEntry::from(value))
1738    }
1739}
1740
1741/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1742#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1743pub enum ImageFormat {
1744    // Sorted from most to least likely to be pasted into an editor,
1745    // which matters when we iterate through them trying to see if
1746    // clipboard content matches them.
1747    /// .png
1748    Png,
1749    /// .jpeg or .jpg
1750    Jpeg,
1751    /// .webp
1752    Webp,
1753    /// .gif
1754    Gif,
1755    /// .svg
1756    Svg,
1757    /// .bmp
1758    Bmp,
1759    /// .tif or .tiff
1760    Tiff,
1761    /// .ico
1762    Ico,
1763}
1764
1765impl ImageFormat {
1766    /// Returns the mime type for the ImageFormat
1767    pub const fn mime_type(self) -> &'static str {
1768        match self {
1769            ImageFormat::Png => "image/png",
1770            ImageFormat::Jpeg => "image/jpeg",
1771            ImageFormat::Webp => "image/webp",
1772            ImageFormat::Gif => "image/gif",
1773            ImageFormat::Svg => "image/svg+xml",
1774            ImageFormat::Bmp => "image/bmp",
1775            ImageFormat::Tiff => "image/tiff",
1776            ImageFormat::Ico => "image/ico",
1777        }
1778    }
1779
1780    /// Returns the ImageFormat for the given mime type
1781    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
1782        match mime_type {
1783            "image/png" => Some(Self::Png),
1784            "image/jpeg" | "image/jpg" => Some(Self::Jpeg),
1785            "image/webp" => Some(Self::Webp),
1786            "image/gif" => Some(Self::Gif),
1787            "image/svg+xml" => Some(Self::Svg),
1788            "image/bmp" => Some(Self::Bmp),
1789            "image/tiff" | "image/tif" => Some(Self::Tiff),
1790            "image/ico" => Some(Self::Ico),
1791            _ => None,
1792        }
1793    }
1794}
1795
1796/// An image, with a format and certain bytes
1797#[derive(Clone, Debug, PartialEq, Eq)]
1798pub struct Image {
1799    /// The image format the bytes represent (e.g. PNG)
1800    pub format: ImageFormat,
1801    /// The raw image bytes
1802    pub bytes: Vec<u8>,
1803    /// The unique ID for the image
1804    id: u64,
1805}
1806
1807impl Hash for Image {
1808    fn hash<H: Hasher>(&self, state: &mut H) {
1809        state.write_u64(self.id);
1810    }
1811}
1812
1813impl Image {
1814    /// An empty image containing no data
1815    pub fn empty() -> Self {
1816        Self::from_bytes(ImageFormat::Png, Vec::new())
1817    }
1818
1819    /// Create an image from a format and bytes
1820    pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
1821        Self {
1822            id: hash(&bytes),
1823            format,
1824            bytes,
1825        }
1826    }
1827
1828    /// Get this image's ID
1829    pub fn id(&self) -> u64 {
1830        self.id
1831    }
1832
1833    /// Use the GPUI `use_asset` API to make this image renderable
1834    pub fn use_render_image(
1835        self: Arc<Self>,
1836        window: &mut Window,
1837        cx: &mut App,
1838    ) -> Option<Arc<RenderImage>> {
1839        ImageSource::Image(self)
1840            .use_data(None, window, cx)
1841            .and_then(|result| result.ok())
1842    }
1843
1844    /// Use the GPUI `get_asset` API to make this image renderable
1845    pub fn get_render_image(
1846        self: Arc<Self>,
1847        window: &mut Window,
1848        cx: &mut App,
1849    ) -> Option<Arc<RenderImage>> {
1850        ImageSource::Image(self)
1851            .get_data(None, window, cx)
1852            .and_then(|result| result.ok())
1853    }
1854
1855    /// Use the GPUI `remove_asset` API to drop this image, if possible.
1856    pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
1857        ImageSource::Image(self).remove_asset(cx);
1858    }
1859
1860    /// Convert the clipboard image to an `ImageData` object.
1861    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1862        fn frames_for_image(
1863            bytes: &[u8],
1864            format: image::ImageFormat,
1865        ) -> Result<SmallVec<[Frame; 1]>> {
1866            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1867
1868            // Convert from RGBA to BGRA.
1869            for pixel in data.chunks_exact_mut(4) {
1870                pixel.swap(0, 2);
1871            }
1872
1873            Ok(SmallVec::from_elem(Frame::new(data), 1))
1874        }
1875
1876        let frames = match self.format {
1877            ImageFormat::Gif => {
1878                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1879                let mut frames = SmallVec::new();
1880
1881                for frame in decoder.into_frames() {
1882                    let mut frame = frame?;
1883                    // Convert from RGBA to BGRA.
1884                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1885                        pixel.swap(0, 2);
1886                    }
1887                    frames.push(frame);
1888                }
1889
1890                frames
1891            }
1892            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1893            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1894            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1895            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1896            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1897            ImageFormat::Ico => frames_for_image(&self.bytes, image::ImageFormat::Ico)?,
1898            ImageFormat::Svg => {
1899                return svg_renderer
1900                    .render_single_frame(&self.bytes, 1.0, false)
1901                    .map_err(Into::into);
1902            }
1903        };
1904
1905        Ok(Arc::new(RenderImage::new(frames)))
1906    }
1907
1908    /// Get the format of the clipboard image
1909    pub fn format(&self) -> ImageFormat {
1910        self.format
1911    }
1912
1913    /// Get the raw bytes of the clipboard image
1914    pub fn bytes(&self) -> &[u8] {
1915        self.bytes.as_slice()
1916    }
1917}
1918
1919/// A clipboard item that should be copied to the clipboard
1920#[derive(Clone, Debug, Eq, PartialEq)]
1921pub struct ClipboardString {
1922    pub(crate) text: String,
1923    pub(crate) metadata: Option<String>,
1924}
1925
1926impl ClipboardString {
1927    /// Create a new clipboard string with the given text
1928    pub fn new(text: String) -> Self {
1929        Self {
1930            text,
1931            metadata: None,
1932        }
1933    }
1934
1935    /// Return a new clipboard item with the metadata replaced by the given metadata,
1936    /// after serializing it as JSON.
1937    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1938        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1939        self
1940    }
1941
1942    /// Get the text of the clipboard string
1943    pub fn text(&self) -> &String {
1944        &self.text
1945    }
1946
1947    /// Get the owned text of the clipboard string
1948    pub fn into_text(self) -> String {
1949        self.text
1950    }
1951
1952    /// Get the metadata of the clipboard string, formatted as JSON
1953    pub fn metadata_json<T>(&self) -> Option<T>
1954    where
1955        T: for<'a> Deserialize<'a>,
1956    {
1957        self.metadata
1958            .as_ref()
1959            .and_then(|m| serde_json::from_str(m).ok())
1960    }
1961
1962    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1963    pub(crate) fn text_hash(text: &str) -> u64 {
1964        let mut hasher = SeaHasher::new();
1965        text.hash(&mut hasher);
1966        hasher.finish()
1967    }
1968}
1969
1970impl From<String> for ClipboardString {
1971    fn from(value: String) -> Self {
1972        Self {
1973            text: value,
1974            metadata: None,
1975        }
1976    }
1977}