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