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