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