platform.rs

   1// todo(windows): remove
   2#![cfg_attr(windows, allow(dead_code))]
   3
   4mod app_menu;
   5mod keystroke;
   6
   7#[cfg(any(target_os = "linux", target_os = "freebsd"))]
   8mod linux;
   9
  10#[cfg(target_os = "macos")]
  11mod mac;
  12
  13#[cfg(any(
  14    all(
  15        any(target_os = "linux", target_os = "freebsd"),
  16        any(feature = "x11", feature = "wayland")
  17    ),
  18    target_os = "windows",
  19    feature = "macos-blade"
  20))]
  21mod blade;
  22
  23#[cfg(any(test, feature = "test-support"))]
  24mod test;
  25
  26#[cfg(target_os = "windows")]
  27mod windows;
  28
  29use crate::{
  30    point, Action, AnyWindowHandle, AsyncWindowContext, BackgroundExecutor, Bounds, DevicePixels,
  31    DispatchEventResult, Font, FontId, FontMetrics, FontRun, ForegroundExecutor, GPUSpecs, GlyphId,
  32    ImageSource, Keymap, LineLayout, Pixels, PlatformInput, Point, RenderGlyphParams, RenderImage,
  33    RenderImageParams, RenderSvgParams, ScaledPixels, Scene, SharedString, Size, SvgRenderer,
  34    SvgSize, Task, TaskLabel, WindowContext, DEFAULT_WINDOW_SIZE,
  35};
  36use anyhow::{anyhow, Result};
  37use async_task::Runnable;
  38use futures::channel::oneshot;
  39use image::codecs::gif::GifDecoder;
  40use image::{AnimationDecoder as _, Frame};
  41use parking::Unparker;
  42use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
  43use seahash::SeaHasher;
  44use serde::{Deserialize, Serialize};
  45use smallvec::SmallVec;
  46use std::borrow::Cow;
  47use std::hash::{Hash, Hasher};
  48use std::io::Cursor;
  49use std::time::{Duration, Instant};
  50use std::{
  51    fmt::{self, Debug},
  52    ops::Range,
  53    path::{Path, PathBuf},
  54    rc::Rc,
  55    sync::Arc,
  56};
  57use strum::EnumIter;
  58use uuid::Uuid;
  59
  60pub use app_menu::*;
  61pub use keystroke::*;
  62
  63#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  64pub(crate) use linux::*;
  65#[cfg(target_os = "macos")]
  66pub(crate) use mac::*;
  67pub use semantic_version::SemanticVersion;
  68#[cfg(any(test, feature = "test-support"))]
  69pub(crate) use test::*;
  70#[cfg(target_os = "windows")]
  71pub(crate) use windows::*;
  72
  73#[cfg(any(test, feature = "test-support"))]
  74pub use test::TestScreenCaptureSource;
  75
  76#[cfg(target_os = "macos")]
  77pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
  78    Rc::new(MacPlatform::new(headless))
  79}
  80
  81#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  82pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
  83    if headless {
  84        return Rc::new(HeadlessClient::new());
  85    }
  86
  87    match guess_compositor() {
  88        #[cfg(feature = "wayland")]
  89        "Wayland" => Rc::new(WaylandClient::new()),
  90
  91        #[cfg(feature = "x11")]
  92        "X11" => Rc::new(X11Client::new()),
  93
  94        "Headless" => Rc::new(HeadlessClient::new()),
  95        _ => unreachable!(),
  96    }
  97}
  98
  99/// Return which compositor we're guessing we'll use.
 100/// Does not attempt to connect to the given compositor
 101#[cfg(any(target_os = "linux", target_os = "freebsd"))]
 102#[inline]
 103pub fn guess_compositor() -> &'static str {
 104    if std::env::var_os("ZED_HEADLESS").is_some() {
 105        return "Headless";
 106    }
 107
 108    #[cfg(feature = "wayland")]
 109    let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
 110    #[cfg(not(feature = "wayland"))]
 111    let wayland_display: Option<std::ffi::OsString> = None;
 112
 113    #[cfg(feature = "x11")]
 114    let x11_display = std::env::var_os("DISPLAY");
 115    #[cfg(not(feature = "x11"))]
 116    let x11_display: Option<std::ffi::OsString> = None;
 117
 118    let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
 119    let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
 120
 121    if use_wayland {
 122        "Wayland"
 123    } else if use_x11 {
 124        "X11"
 125    } else {
 126        "Headless"
 127    }
 128}
 129
 130#[cfg(target_os = "windows")]
 131pub(crate) fn current_platform(_headless: bool) -> Rc<dyn Platform> {
 132    Rc::new(WindowsPlatform::new())
 133}
 134
 135pub(crate) trait Platform: 'static {
 136    fn background_executor(&self) -> BackgroundExecutor;
 137    fn foreground_executor(&self) -> ForegroundExecutor;
 138    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
 139
 140    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
 141    fn quit(&self);
 142    fn restart(&self, binary_path: Option<PathBuf>);
 143    fn activate(&self, ignoring_other_apps: bool);
 144    fn hide(&self);
 145    fn hide_other_apps(&self);
 146    fn unhide_other_apps(&self);
 147
 148    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
 149    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 150    fn active_window(&self) -> Option<AnyWindowHandle>;
 151    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 152        None
 153    }
 154
 155    fn screen_capture_sources(
 156        &self,
 157    ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>>;
 158
 159    fn open_window(
 160        &self,
 161        handle: AnyWindowHandle,
 162        options: WindowParams,
 163    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
 164
 165    /// Returns the appearance of the application's windows.
 166    fn window_appearance(&self) -> WindowAppearance;
 167
 168    fn open_url(&self, url: &str);
 169    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
 170    fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
 171
 172    fn prompt_for_paths(
 173        &self,
 174        options: PathPromptOptions,
 175    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
 176    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>>;
 177    fn reveal_path(&self, path: &Path);
 178    fn open_with_system(&self, path: &Path);
 179
 180    fn on_quit(&self, callback: Box<dyn FnMut()>);
 181    fn on_reopen(&self, callback: Box<dyn FnMut()>);
 182    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
 183
 184    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
 185    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 186        None
 187    }
 188
 189    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
 190    fn add_recent_document(&self, _path: &Path) {}
 191    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
 192    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
 193    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
 194    fn keyboard_layout(&self) -> String;
 195
 196    fn compositor_name(&self) -> &'static str {
 197        ""
 198    }
 199    fn app_path(&self) -> Result<PathBuf>;
 200    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
 201
 202    fn set_cursor_style(&self, style: CursorStyle);
 203    fn should_auto_hide_scrollbars(&self) -> bool;
 204
 205    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 206    fn write_to_primary(&self, item: ClipboardItem);
 207    fn write_to_clipboard(&self, item: ClipboardItem);
 208    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 209    fn read_from_primary(&self) -> Option<ClipboardItem>;
 210    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 211
 212    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
 213    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
 214    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
 215}
 216
 217/// A handle to a platform's display, e.g. a monitor or laptop screen.
 218pub trait PlatformDisplay: Send + Sync + Debug {
 219    /// Get the ID for this display
 220    fn id(&self) -> DisplayId;
 221
 222    /// Returns a stable identifier for this display that can be persisted and used
 223    /// across system restarts.
 224    fn uuid(&self) -> Result<Uuid>;
 225
 226    /// Get the bounds for this display
 227    fn bounds(&self) -> Bounds<Pixels>;
 228
 229    /// Get the default bounds for this display to place a window
 230    fn default_bounds(&self) -> Bounds<Pixels> {
 231        let center = self.bounds().center();
 232        let offset = DEFAULT_WINDOW_SIZE / 2.0;
 233        let origin = point(center.x - offset.width, center.y - offset.height);
 234        Bounds::new(origin, DEFAULT_WINDOW_SIZE)
 235    }
 236}
 237
 238/// A source of on-screen video content that can be captured.
 239pub trait ScreenCaptureSource {
 240    /// Returns the video resolution of this source.
 241    fn resolution(&self) -> Result<Size<Pixels>>;
 242
 243    /// Start capture video from this source, invoking the given callback
 244    /// with each frame.
 245    fn stream(
 246        &self,
 247        frame_callback: Box<dyn Fn(ScreenCaptureFrame)>,
 248    ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
 249}
 250
 251/// A video stream captured from a screen.
 252pub trait ScreenCaptureStream {}
 253
 254/// A frame of video captured from a screen.
 255pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
 256
 257/// An opaque identifier for a hardware display
 258#[derive(PartialEq, Eq, Hash, Copy, Clone)]
 259pub struct DisplayId(pub(crate) u32);
 260
 261impl Debug for DisplayId {
 262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 263        write!(f, "DisplayId({})", self.0)
 264    }
 265}
 266
 267unsafe impl Send for DisplayId {}
 268
 269/// Which part of the window to resize
 270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 271pub enum ResizeEdge {
 272    /// The top edge
 273    Top,
 274    /// The top right corner
 275    TopRight,
 276    /// The right edge
 277    Right,
 278    /// The bottom right corner
 279    BottomRight,
 280    /// The bottom edge
 281    Bottom,
 282    /// The bottom left corner
 283    BottomLeft,
 284    /// The left edge
 285    Left,
 286    /// The top left corner
 287    TopLeft,
 288}
 289
 290/// A type to describe the appearance of a window
 291#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 292pub enum WindowDecorations {
 293    #[default]
 294    /// Server side decorations
 295    Server,
 296    /// Client side decorations
 297    Client,
 298}
 299
 300/// A type to describe how this window is currently configured
 301#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 302pub enum Decorations {
 303    /// The window is configured to use server side decorations
 304    #[default]
 305    Server,
 306    /// The window is configured to use client side decorations
 307    Client {
 308        /// The edge tiling state
 309        tiling: Tiling,
 310    },
 311}
 312
 313/// What window controls this platform supports
 314#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
 315pub struct WindowControls {
 316    /// Whether this platform supports fullscreen
 317    pub fullscreen: bool,
 318    /// Whether this platform supports maximize
 319    pub maximize: bool,
 320    /// Whether this platform supports minimize
 321    pub minimize: bool,
 322    /// Whether this platform supports a window menu
 323    pub window_menu: bool,
 324}
 325
 326impl Default for WindowControls {
 327    fn default() -> Self {
 328        // Assume that we can do anything, unless told otherwise
 329        Self {
 330            fullscreen: true,
 331            maximize: true,
 332            minimize: true,
 333            window_menu: true,
 334        }
 335    }
 336}
 337
 338/// A type to describe which sides of the window are currently tiled in some way
 339#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 340pub struct Tiling {
 341    /// Whether the top edge is tiled
 342    pub top: bool,
 343    /// Whether the left edge is tiled
 344    pub left: bool,
 345    /// Whether the right edge is tiled
 346    pub right: bool,
 347    /// Whether the bottom edge is tiled
 348    pub bottom: bool,
 349}
 350
 351impl Tiling {
 352    /// Initializes a [`Tiling`] type with all sides tiled
 353    pub fn tiled() -> Self {
 354        Self {
 355            top: true,
 356            left: true,
 357            right: true,
 358            bottom: true,
 359        }
 360    }
 361
 362    /// Whether any edge is tiled
 363    pub fn is_tiled(&self) -> bool {
 364        self.top || self.left || self.right || self.bottom
 365    }
 366}
 367
 368#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
 369pub(crate) struct RequestFrameOptions {
 370    pub(crate) require_presentation: bool,
 371}
 372
 373pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
 374    fn bounds(&self) -> Bounds<Pixels>;
 375    fn is_maximized(&self) -> bool;
 376    fn window_bounds(&self) -> WindowBounds;
 377    fn content_size(&self) -> Size<Pixels>;
 378    fn scale_factor(&self) -> f32;
 379    fn appearance(&self) -> WindowAppearance;
 380    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 381    fn mouse_position(&self) -> Point<Pixels>;
 382    fn modifiers(&self) -> Modifiers;
 383    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
 384    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
 385    fn prompt(
 386        &self,
 387        level: PromptLevel,
 388        msg: &str,
 389        detail: Option<&str>,
 390        answers: &[&str],
 391    ) -> Option<oneshot::Receiver<usize>>;
 392    fn activate(&self);
 393    fn is_active(&self) -> bool;
 394    fn is_hovered(&self) -> bool;
 395    fn set_title(&mut self, title: &str);
 396    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
 397    fn minimize(&self);
 398    fn zoom(&self);
 399    fn toggle_fullscreen(&self);
 400    fn is_fullscreen(&self) -> bool;
 401    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
 402    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
 403    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
 404    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
 405    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
 406    fn on_moved(&self, callback: Box<dyn FnMut()>);
 407    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
 408    fn on_close(&self, callback: Box<dyn FnOnce()>);
 409    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
 410    fn draw(&self, scene: &Scene);
 411    fn completed_frame(&self) {}
 412    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
 413
 414    // macOS specific methods
 415    fn set_edited(&mut self, _edited: bool) {}
 416    fn show_character_palette(&self) {}
 417
 418    #[cfg(target_os = "windows")]
 419    fn get_raw_handle(&self) -> windows::HWND;
 420
 421    // Linux specific methods
 422    fn request_decorations(&self, _decorations: WindowDecorations) {}
 423    fn show_window_menu(&self, _position: Point<Pixels>) {}
 424    fn start_window_move(&self) {}
 425    fn start_window_resize(&self, _edge: ResizeEdge) {}
 426    fn window_decorations(&self) -> Decorations {
 427        Decorations::Server
 428    }
 429    fn set_app_id(&mut self, _app_id: &str) {}
 430    fn window_controls(&self) -> WindowControls {
 431        WindowControls::default()
 432    }
 433    fn set_client_inset(&self, _inset: Pixels) {}
 434    fn gpu_specs(&self) -> Option<GPUSpecs>;
 435
 436    fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>);
 437
 438    #[cfg(any(test, feature = "test-support"))]
 439    fn as_test(&mut self) -> Option<&mut TestWindow> {
 440        None
 441    }
 442}
 443
 444/// This type is public so that our test macro can generate and use it, but it should not
 445/// be considered part of our public API.
 446#[doc(hidden)]
 447pub trait PlatformDispatcher: Send + Sync {
 448    fn is_main_thread(&self) -> bool;
 449    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
 450    fn dispatch_on_main_thread(&self, runnable: Runnable);
 451    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
 452    fn park(&self, timeout: Option<Duration>) -> bool;
 453    fn unparker(&self) -> Unparker;
 454    fn now(&self) -> Instant {
 455        Instant::now()
 456    }
 457
 458    #[cfg(any(test, feature = "test-support"))]
 459    fn as_test(&self) -> Option<&TestDispatcher> {
 460        None
 461    }
 462}
 463
 464pub(crate) trait PlatformTextSystem: Send + Sync {
 465    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
 466    fn all_font_names(&self) -> Vec<String>;
 467    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
 468    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
 469    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
 470    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
 471    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
 472    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
 473    fn rasterize_glyph(
 474        &self,
 475        params: &RenderGlyphParams,
 476        raster_bounds: Bounds<DevicePixels>,
 477    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
 478    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
 479}
 480
 481pub(crate) struct NoopTextSystem;
 482
 483impl NoopTextSystem {
 484    #[allow(dead_code)]
 485    pub fn new() -> Self {
 486        Self
 487    }
 488}
 489
 490impl PlatformTextSystem for NoopTextSystem {
 491    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 492        Ok(())
 493    }
 494
 495    fn all_font_names(&self) -> Vec<String> {
 496        Vec::new()
 497    }
 498
 499    fn font_id(&self, descriptor: &Font) -> Result<FontId> {
 500        Err(anyhow!("No font found for {:?}", descriptor))
 501    }
 502
 503    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
 504        unimplemented!()
 505    }
 506
 507    fn typographic_bounds(&self, font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
 508        Err(anyhow!("No font found for {:?}", font_id))
 509    }
 510
 511    fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> Result<Size<f32>> {
 512        Err(anyhow!("No font found for {:?}", font_id))
 513    }
 514
 515    fn glyph_for_char(&self, _font_id: FontId, _ch: char) -> Option<GlyphId> {
 516        None
 517    }
 518
 519    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 520        Err(anyhow!("No font found for {:?}", params))
 521    }
 522
 523    fn rasterize_glyph(
 524        &self,
 525        params: &RenderGlyphParams,
 526        _raster_bounds: Bounds<DevicePixels>,
 527    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 528        Err(anyhow!("No font found for {:?}", params))
 529    }
 530
 531    fn layout_line(&self, _text: &str, _font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
 532        unimplemented!()
 533    }
 534}
 535
 536#[derive(PartialEq, Eq, Hash, Clone)]
 537pub(crate) enum AtlasKey {
 538    Glyph(RenderGlyphParams),
 539    Svg(RenderSvgParams),
 540    Image(RenderImageParams),
 541}
 542
 543impl AtlasKey {
 544    #[cfg_attr(
 545        all(
 546            any(target_os = "linux", target_os = "freebsd"),
 547            not(any(feature = "x11", feature = "wayland"))
 548        ),
 549        allow(dead_code)
 550    )]
 551    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
 552        match self {
 553            AtlasKey::Glyph(params) => {
 554                if params.is_emoji {
 555                    AtlasTextureKind::Polychrome
 556                } else {
 557                    AtlasTextureKind::Monochrome
 558                }
 559            }
 560            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
 561            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
 562        }
 563    }
 564}
 565
 566impl From<RenderGlyphParams> for AtlasKey {
 567    fn from(params: RenderGlyphParams) -> Self {
 568        Self::Glyph(params)
 569    }
 570}
 571
 572impl From<RenderSvgParams> for AtlasKey {
 573    fn from(params: RenderSvgParams) -> Self {
 574        Self::Svg(params)
 575    }
 576}
 577
 578impl From<RenderImageParams> for AtlasKey {
 579    fn from(params: RenderImageParams) -> Self {
 580        Self::Image(params)
 581    }
 582}
 583
 584pub(crate) trait PlatformAtlas: Send + Sync {
 585    fn get_or_insert_with<'a>(
 586        &self,
 587        key: &AtlasKey,
 588        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 589    ) -> Result<Option<AtlasTile>>;
 590}
 591
 592#[derive(Clone, Debug, PartialEq, Eq)]
 593#[repr(C)]
 594pub(crate) struct AtlasTile {
 595    pub(crate) texture_id: AtlasTextureId,
 596    pub(crate) tile_id: TileId,
 597    pub(crate) padding: u32,
 598    pub(crate) bounds: Bounds<DevicePixels>,
 599}
 600
 601#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 602#[repr(C)]
 603pub(crate) struct AtlasTextureId {
 604    // We use u32 instead of usize for Metal Shader Language compatibility
 605    pub(crate) index: u32,
 606    pub(crate) kind: AtlasTextureKind,
 607}
 608
 609#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 610#[repr(C)]
 611#[cfg_attr(
 612    all(
 613        any(target_os = "linux", target_os = "freebsd"),
 614        not(any(feature = "x11", feature = "wayland"))
 615    ),
 616    allow(dead_code)
 617)]
 618pub(crate) enum AtlasTextureKind {
 619    Monochrome = 0,
 620    Polychrome = 1,
 621    Path = 2,
 622}
 623
 624#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 625#[repr(C)]
 626pub(crate) struct TileId(pub(crate) u32);
 627
 628impl From<etagere::AllocId> for TileId {
 629    fn from(id: etagere::AllocId) -> Self {
 630        Self(id.serialize())
 631    }
 632}
 633
 634impl From<TileId> for etagere::AllocId {
 635    fn from(id: TileId) -> Self {
 636        Self::deserialize(id.0)
 637    }
 638}
 639
 640pub(crate) struct PlatformInputHandler {
 641    cx: AsyncWindowContext,
 642    handler: Box<dyn InputHandler>,
 643}
 644
 645#[cfg_attr(
 646    all(
 647        any(target_os = "linux", target_os = "freebsd"),
 648        not(any(feature = "x11", feature = "wayland"))
 649    ),
 650    allow(dead_code)
 651)]
 652impl PlatformInputHandler {
 653    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
 654        Self { cx, handler }
 655    }
 656
 657    fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
 658        self.cx
 659            .update(|cx| self.handler.selected_text_range(ignore_disabled_input, cx))
 660            .ok()
 661            .flatten()
 662    }
 663
 664    fn marked_text_range(&mut self) -> Option<Range<usize>> {
 665        self.cx
 666            .update(|cx| self.handler.marked_text_range(cx))
 667            .ok()
 668            .flatten()
 669    }
 670
 671    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 672    fn text_for_range(&mut self, range_utf16: Range<usize>) -> Option<String> {
 673        self.cx
 674            .update(|cx| self.handler.text_for_range(range_utf16, cx))
 675            .ok()
 676            .flatten()
 677    }
 678
 679    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
 680        self.cx
 681            .update(|cx| {
 682                self.handler
 683                    .replace_text_in_range(replacement_range, text, cx);
 684            })
 685            .ok();
 686    }
 687
 688    fn replace_and_mark_text_in_range(
 689        &mut self,
 690        range_utf16: Option<Range<usize>>,
 691        new_text: &str,
 692        new_selected_range: Option<Range<usize>>,
 693    ) {
 694        self.cx
 695            .update(|cx| {
 696                self.handler.replace_and_mark_text_in_range(
 697                    range_utf16,
 698                    new_text,
 699                    new_selected_range,
 700                    cx,
 701                )
 702            })
 703            .ok();
 704    }
 705
 706    fn unmark_text(&mut self) {
 707        self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
 708    }
 709
 710    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
 711        self.cx
 712            .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
 713            .ok()
 714            .flatten()
 715    }
 716
 717    #[allow(dead_code)]
 718    fn apple_press_and_hold_enabled(&mut self) -> bool {
 719        self.handler.apple_press_and_hold_enabled()
 720    }
 721
 722    pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
 723        self.handler.replace_text_in_range(None, input, cx);
 724    }
 725
 726    pub fn selected_bounds(&mut self, cx: &mut WindowContext) -> Option<Bounds<Pixels>> {
 727        let selection = self.handler.selected_text_range(true, cx)?;
 728        self.handler.bounds_for_range(
 729            if selection.reversed {
 730                selection.range.start..selection.range.start
 731            } else {
 732                selection.range.end..selection.range.end
 733            },
 734            cx,
 735        )
 736    }
 737}
 738
 739/// A struct representing a selection in a text buffer, in UTF16 characters.
 740/// This is different from a range because the head may be before the tail.
 741pub struct UTF16Selection {
 742    /// The range of text in the document this selection corresponds to
 743    /// in UTF16 characters.
 744    pub range: Range<usize>,
 745    /// Whether the head of this selection is at the start (true), or end (false)
 746    /// of the range
 747    pub reversed: bool,
 748}
 749
 750/// Zed's interface for handling text input from the platform's IME system
 751/// This is currently a 1:1 exposure of the NSTextInputClient API:
 752///
 753/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
 754pub trait InputHandler: 'static {
 755    /// Get the range of the user's currently selected text, if any
 756    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
 757    ///
 758    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 759    fn selected_text_range(
 760        &mut self,
 761        ignore_disabled_input: bool,
 762        cx: &mut WindowContext,
 763    ) -> Option<UTF16Selection>;
 764
 765    /// Get the range of the currently marked text, if any
 766    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
 767    ///
 768    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 769    fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
 770
 771    /// Get the text for the given document range in UTF-16 characters
 772    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
 773    ///
 774    /// range_utf16 is in terms of UTF-16 characters
 775    fn text_for_range(
 776        &mut self,
 777        range_utf16: Range<usize>,
 778        cx: &mut WindowContext,
 779    ) -> Option<String>;
 780
 781    /// Replace the text in the given document range with the given text
 782    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
 783    ///
 784    /// replacement_range is in terms of UTF-16 characters
 785    fn replace_text_in_range(
 786        &mut self,
 787        replacement_range: Option<Range<usize>>,
 788        text: &str,
 789        cx: &mut WindowContext,
 790    );
 791
 792    /// Replace the text in the given document range with the given text,
 793    /// and mark the given text as part of an IME 'composing' state
 794    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
 795    ///
 796    /// range_utf16 is in terms of UTF-16 characters
 797    /// new_selected_range is in terms of UTF-16 characters
 798    fn replace_and_mark_text_in_range(
 799        &mut self,
 800        range_utf16: Option<Range<usize>>,
 801        new_text: &str,
 802        new_selected_range: Option<Range<usize>>,
 803        cx: &mut WindowContext,
 804    );
 805
 806    /// Remove the IME 'composing' state from the document
 807    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
 808    fn unmark_text(&mut self, cx: &mut WindowContext);
 809
 810    /// Get the bounds of the given document range in screen coordinates
 811    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
 812    ///
 813    /// This is used for positioning the IME candidate window
 814    fn bounds_for_range(
 815        &mut self,
 816        range_utf16: Range<usize>,
 817        cx: &mut WindowContext,
 818    ) -> Option<Bounds<Pixels>>;
 819
 820    /// Allows a given input context to opt into getting raw key repeats instead of
 821    /// sending these to the platform.
 822    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
 823    /// (which is how iTerm does it) but it doesn't seem to work for me.
 824    #[allow(dead_code)]
 825    fn apple_press_and_hold_enabled(&mut self) -> bool {
 826        true
 827    }
 828}
 829
 830/// The variables that can be configured when creating a new window
 831#[derive(Debug)]
 832pub struct WindowOptions {
 833    /// Specifies the state and bounds of the window in screen coordinates.
 834    /// - `None`: Inherit the bounds.
 835    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
 836    pub window_bounds: Option<WindowBounds>,
 837
 838    /// The titlebar configuration of the window
 839    pub titlebar: Option<TitlebarOptions>,
 840
 841    /// Whether the window should be focused when created
 842    pub focus: bool,
 843
 844    /// Whether the window should be shown when created
 845    pub show: bool,
 846
 847    /// The kind of window to create
 848    pub kind: WindowKind,
 849
 850    /// Whether the window should be movable by the user
 851    pub is_movable: bool,
 852
 853    /// The display to create the window on, if this is None,
 854    /// the window will be created on the main display
 855    pub display_id: Option<DisplayId>,
 856
 857    /// The appearance of the window background.
 858    pub window_background: WindowBackgroundAppearance,
 859
 860    /// Application identifier of the window. Can by used by desktop environments to group applications together.
 861    pub app_id: Option<String>,
 862
 863    /// Window minimum size
 864    pub window_min_size: Option<Size<Pixels>>,
 865
 866    /// Whether to use client or server side decorations. Wayland only
 867    /// Note that this may be ignored.
 868    pub window_decorations: Option<WindowDecorations>,
 869}
 870
 871/// The variables that can be configured when creating a new window
 872#[derive(Debug)]
 873#[cfg_attr(
 874    all(
 875        any(target_os = "linux", target_os = "freebsd"),
 876        not(any(feature = "x11", feature = "wayland"))
 877    ),
 878    allow(dead_code)
 879)]
 880pub(crate) struct WindowParams {
 881    pub bounds: Bounds<Pixels>,
 882
 883    /// The titlebar configuration of the window
 884    #[cfg_attr(feature = "wayland", allow(dead_code))]
 885    pub titlebar: Option<TitlebarOptions>,
 886
 887    /// The kind of window to create
 888    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 889    pub kind: WindowKind,
 890
 891    /// Whether the window should be movable by the user
 892    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 893    pub is_movable: bool,
 894
 895    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 896    pub focus: bool,
 897
 898    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 899    pub show: bool,
 900
 901    #[cfg_attr(feature = "wayland", allow(dead_code))]
 902    pub display_id: Option<DisplayId>,
 903
 904    pub window_min_size: Option<Size<Pixels>>,
 905}
 906
 907/// Represents the status of how a window should be opened.
 908#[derive(Debug, Copy, Clone, PartialEq)]
 909pub enum WindowBounds {
 910    /// Indicates that the window should open in a windowed state with the given bounds.
 911    Windowed(Bounds<Pixels>),
 912    /// Indicates that the window should open in a maximized state.
 913    /// The bounds provided here represent the restore size of the window.
 914    Maximized(Bounds<Pixels>),
 915    /// Indicates that the window should open in fullscreen mode.
 916    /// The bounds provided here represent the restore size of the window.
 917    Fullscreen(Bounds<Pixels>),
 918}
 919
 920impl Default for WindowBounds {
 921    fn default() -> Self {
 922        WindowBounds::Windowed(Bounds::default())
 923    }
 924}
 925
 926impl WindowBounds {
 927    /// Retrieve the inner bounds
 928    pub fn get_bounds(&self) -> Bounds<Pixels> {
 929        match self {
 930            WindowBounds::Windowed(bounds) => *bounds,
 931            WindowBounds::Maximized(bounds) => *bounds,
 932            WindowBounds::Fullscreen(bounds) => *bounds,
 933        }
 934    }
 935}
 936
 937impl Default for WindowOptions {
 938    fn default() -> Self {
 939        Self {
 940            window_bounds: None,
 941            titlebar: Some(TitlebarOptions {
 942                title: Default::default(),
 943                appears_transparent: Default::default(),
 944                traffic_light_position: Default::default(),
 945            }),
 946            focus: true,
 947            show: true,
 948            kind: WindowKind::Normal,
 949            is_movable: true,
 950            display_id: None,
 951            window_background: WindowBackgroundAppearance::default(),
 952            app_id: None,
 953            window_min_size: None,
 954            window_decorations: None,
 955        }
 956    }
 957}
 958
 959/// The options that can be configured for a window's titlebar
 960#[derive(Debug, Default)]
 961pub struct TitlebarOptions {
 962    /// The initial title of the window
 963    pub title: Option<SharedString>,
 964
 965    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
 966    /// Refer to [`WindowOptions::window_decorations`] on Linux
 967    pub appears_transparent: bool,
 968
 969    /// The position of the macOS traffic light buttons
 970    pub traffic_light_position: Option<Point<Pixels>>,
 971}
 972
 973/// The kind of window to create
 974#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 975pub enum WindowKind {
 976    /// A normal application window
 977    Normal,
 978
 979    /// A window that appears above all other windows, usually used for alerts or popups
 980    /// use sparingly!
 981    PopUp,
 982}
 983
 984/// The appearance of the window, as defined by the operating system.
 985///
 986/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
 987/// values.
 988#[derive(Copy, Clone, Debug)]
 989pub enum WindowAppearance {
 990    /// A light appearance.
 991    ///
 992    /// On macOS, this corresponds to the `aqua` appearance.
 993    Light,
 994
 995    /// A light appearance with vibrant colors.
 996    ///
 997    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
 998    VibrantLight,
 999
1000    /// A dark appearance.
1001    ///
1002    /// On macOS, this corresponds to the `darkAqua` appearance.
1003    Dark,
1004
1005    /// A dark appearance with vibrant colors.
1006    ///
1007    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
1008    VibrantDark,
1009}
1010
1011impl Default for WindowAppearance {
1012    fn default() -> Self {
1013        Self::Light
1014    }
1015}
1016
1017/// The appearance of the background of the window itself, when there is
1018/// no content or the content is transparent.
1019#[derive(Copy, Clone, Debug, Default, PartialEq)]
1020pub enum WindowBackgroundAppearance {
1021    /// Opaque.
1022    ///
1023    /// This lets the window manager know that content behind this
1024    /// window does not need to be drawn.
1025    ///
1026    /// Actual color depends on the system and themes should define a fully
1027    /// opaque background color instead.
1028    #[default]
1029    Opaque,
1030    /// Plain alpha transparency.
1031    Transparent,
1032    /// Transparency, but the contents behind the window are blurred.
1033    ///
1034    /// Not always supported.
1035    Blurred,
1036}
1037
1038/// The options that can be configured for a file dialog prompt
1039#[derive(Copy, Clone, Debug)]
1040pub struct PathPromptOptions {
1041    /// Should the prompt allow files to be selected?
1042    pub files: bool,
1043    /// Should the prompt allow directories to be selected?
1044    pub directories: bool,
1045    /// Should the prompt allow multiple files to be selected?
1046    pub multiple: bool,
1047}
1048
1049/// What kind of prompt styling to show
1050#[derive(Copy, Clone, Debug, PartialEq)]
1051pub enum PromptLevel {
1052    /// A prompt that is shown when the user should be notified of something
1053    Info,
1054
1055    /// A prompt that is shown when the user needs to be warned of a potential problem
1056    Warning,
1057
1058    /// A prompt that is shown when a critical problem has occurred
1059    Critical,
1060}
1061
1062/// The style of the cursor (pointer)
1063#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1064pub enum CursorStyle {
1065    /// The default cursor
1066    Arrow,
1067
1068    /// A text input cursor
1069    /// corresponds to the CSS cursor value `text`
1070    IBeam,
1071
1072    /// A crosshair cursor
1073    /// corresponds to the CSS cursor value `crosshair`
1074    Crosshair,
1075
1076    /// A closed hand cursor
1077    /// corresponds to the CSS cursor value `grabbing`
1078    ClosedHand,
1079
1080    /// An open hand cursor
1081    /// corresponds to the CSS cursor value `grab`
1082    OpenHand,
1083
1084    /// A pointing hand cursor
1085    /// corresponds to the CSS cursor value `pointer`
1086    PointingHand,
1087
1088    /// A resize left cursor
1089    /// corresponds to the CSS cursor value `w-resize`
1090    ResizeLeft,
1091
1092    /// A resize right cursor
1093    /// corresponds to the CSS cursor value `e-resize`
1094    ResizeRight,
1095
1096    /// A resize cursor to the left and right
1097    /// corresponds to the CSS cursor value `ew-resize`
1098    ResizeLeftRight,
1099
1100    /// A resize up cursor
1101    /// corresponds to the CSS cursor value `n-resize`
1102    ResizeUp,
1103
1104    /// A resize down cursor
1105    /// corresponds to the CSS cursor value `s-resize`
1106    ResizeDown,
1107
1108    /// A resize cursor directing up and down
1109    /// corresponds to the CSS cursor value `ns-resize`
1110    ResizeUpDown,
1111
1112    /// A resize cursor directing up-left and down-right
1113    /// corresponds to the CSS cursor value `nesw-resize`
1114    ResizeUpLeftDownRight,
1115
1116    /// A resize cursor directing up-right and down-left
1117    /// corresponds to the CSS cursor value `nwse-resize`
1118    ResizeUpRightDownLeft,
1119
1120    /// A cursor indicating that the item/column can be resized horizontally.
1121    /// corresponds to the CSS cursor value `col-resize`
1122    ResizeColumn,
1123
1124    /// A cursor indicating that the item/row can be resized vertically.
1125    /// corresponds to the CSS cursor value `row-resize`
1126    ResizeRow,
1127
1128    /// A text input cursor for vertical layout
1129    /// corresponds to the CSS cursor value `vertical-text`
1130    IBeamCursorForVerticalLayout,
1131
1132    /// A cursor indicating that the operation is not allowed
1133    /// corresponds to the CSS cursor value `not-allowed`
1134    OperationNotAllowed,
1135
1136    /// A cursor indicating that the operation will result in a link
1137    /// corresponds to the CSS cursor value `alias`
1138    DragLink,
1139
1140    /// A cursor indicating that the operation will result in a copy
1141    /// corresponds to the CSS cursor value `copy`
1142    DragCopy,
1143
1144    /// A cursor indicating that the operation will result in a context menu
1145    /// corresponds to the CSS cursor value `context-menu`
1146    ContextualMenu,
1147}
1148
1149impl Default for CursorStyle {
1150    fn default() -> Self {
1151        Self::Arrow
1152    }
1153}
1154
1155/// A clipboard item that should be copied to the clipboard
1156#[derive(Clone, Debug, Eq, PartialEq)]
1157pub struct ClipboardItem {
1158    entries: Vec<ClipboardEntry>,
1159}
1160
1161/// Either a ClipboardString or a ClipboardImage
1162#[derive(Clone, Debug, Eq, PartialEq)]
1163pub enum ClipboardEntry {
1164    /// A string entry
1165    String(ClipboardString),
1166    /// An image entry
1167    Image(Image),
1168}
1169
1170impl ClipboardItem {
1171    /// Create a new ClipboardItem::String with no associated metadata
1172    pub fn new_string(text: String) -> Self {
1173        Self {
1174            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1175        }
1176    }
1177
1178    /// Create a new ClipboardItem::String with the given text and associated metadata
1179    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1180        Self {
1181            entries: vec![ClipboardEntry::String(ClipboardString {
1182                text,
1183                metadata: Some(metadata),
1184            })],
1185        }
1186    }
1187
1188    /// Create a new ClipboardItem::String with the given text and associated metadata
1189    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1190        Self {
1191            entries: vec![ClipboardEntry::String(
1192                ClipboardString::new(text).with_json_metadata(metadata),
1193            )],
1194        }
1195    }
1196
1197    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1198    pub fn new_image(image: &Image) -> Self {
1199        Self {
1200            entries: vec![ClipboardEntry::Image(image.clone())],
1201        }
1202    }
1203
1204    /// Concatenates together all the ClipboardString entries in the item.
1205    /// Returns None if there were no ClipboardString entries.
1206    pub fn text(&self) -> Option<String> {
1207        let mut answer = String::new();
1208        let mut any_entries = false;
1209
1210        for entry in self.entries.iter() {
1211            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1212                answer.push_str(text);
1213                any_entries = true;
1214            }
1215        }
1216
1217        if any_entries {
1218            Some(answer)
1219        } else {
1220            None
1221        }
1222    }
1223
1224    /// If this item is one ClipboardEntry::String, returns its metadata.
1225    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1226    pub fn metadata(&self) -> Option<&String> {
1227        match self.entries().first() {
1228            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1229                clipboard_string.metadata.as_ref()
1230            }
1231            _ => None,
1232        }
1233    }
1234
1235    /// Get the item's entries
1236    pub fn entries(&self) -> &[ClipboardEntry] {
1237        &self.entries
1238    }
1239
1240    /// Get owned versions of the item's entries
1241    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1242        self.entries.into_iter()
1243    }
1244}
1245
1246/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1247#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1248pub enum ImageFormat {
1249    // Sorted from most to least likely to be pasted into an editor,
1250    // which matters when we iterate through them trying to see if
1251    // clipboard content matches them.
1252    /// .png
1253    Png,
1254    /// .jpeg or .jpg
1255    Jpeg,
1256    /// .webp
1257    Webp,
1258    /// .gif
1259    Gif,
1260    /// .svg
1261    Svg,
1262    /// .bmp
1263    Bmp,
1264    /// .tif or .tiff
1265    Tiff,
1266}
1267
1268/// An image, with a format and certain bytes
1269#[derive(Clone, Debug, PartialEq, Eq)]
1270pub struct Image {
1271    /// The image format the bytes represent (e.g. PNG)
1272    pub format: ImageFormat,
1273    /// The raw image bytes
1274    pub bytes: Vec<u8>,
1275    /// The unique ID for the image
1276    pub id: u64,
1277}
1278
1279impl Hash for Image {
1280    fn hash<H: Hasher>(&self, state: &mut H) {
1281        state.write_u64(self.id);
1282    }
1283}
1284
1285impl Image {
1286    /// Get this image's ID
1287    pub fn id(&self) -> u64 {
1288        self.id
1289    }
1290
1291    /// Use the GPUI `use_asset` API to make this image renderable
1292    pub fn use_render_image(self: Arc<Self>, cx: &mut WindowContext) -> Option<Arc<RenderImage>> {
1293        ImageSource::Image(self)
1294            .use_data(cx)
1295            .and_then(|result| result.ok())
1296    }
1297
1298    /// Convert the clipboard image to an `ImageData` object.
1299    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1300        fn frames_for_image(
1301            bytes: &[u8],
1302            format: image::ImageFormat,
1303        ) -> Result<SmallVec<[Frame; 1]>> {
1304            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1305
1306            // Convert from RGBA to BGRA.
1307            for pixel in data.chunks_exact_mut(4) {
1308                pixel.swap(0, 2);
1309            }
1310
1311            Ok(SmallVec::from_elem(Frame::new(data), 1))
1312        }
1313
1314        let frames = match self.format {
1315            ImageFormat::Gif => {
1316                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1317                let mut frames = SmallVec::new();
1318
1319                for frame in decoder.into_frames() {
1320                    let mut frame = frame?;
1321                    // Convert from RGBA to BGRA.
1322                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1323                        pixel.swap(0, 2);
1324                    }
1325                    frames.push(frame);
1326                }
1327
1328                frames
1329            }
1330            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1331            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1332            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1333            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1334            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1335            ImageFormat::Svg => {
1336                let pixmap = svg_renderer.render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1337
1338                let buffer =
1339                    image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1340                        .unwrap();
1341
1342                SmallVec::from_elem(Frame::new(buffer), 1)
1343            }
1344        };
1345
1346        Ok(Arc::new(RenderImage::new(frames)))
1347    }
1348
1349    /// Get the format of the clipboard image
1350    pub fn format(&self) -> ImageFormat {
1351        self.format
1352    }
1353
1354    /// Get the raw bytes of the clipboard image
1355    pub fn bytes(&self) -> &[u8] {
1356        self.bytes.as_slice()
1357    }
1358}
1359
1360/// A clipboard item that should be copied to the clipboard
1361#[derive(Clone, Debug, Eq, PartialEq)]
1362pub struct ClipboardString {
1363    pub(crate) text: String,
1364    pub(crate) metadata: Option<String>,
1365}
1366
1367impl ClipboardString {
1368    /// Create a new clipboard string with the given text
1369    pub fn new(text: String) -> Self {
1370        Self {
1371            text,
1372            metadata: None,
1373        }
1374    }
1375
1376    /// Return a new clipboard item with the metadata replaced by the given metadata,
1377    /// after serializing it as JSON.
1378    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1379        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1380        self
1381    }
1382
1383    /// Get the text of the clipboard string
1384    pub fn text(&self) -> &String {
1385        &self.text
1386    }
1387
1388    /// Get the owned text of the clipboard string
1389    pub fn into_text(self) -> String {
1390        self.text
1391    }
1392
1393    /// Get the metadata of the clipboard string, formatted as JSON
1394    pub fn metadata_json<T>(&self) -> Option<T>
1395    where
1396        T: for<'a> Deserialize<'a>,
1397    {
1398        self.metadata
1399            .as_ref()
1400            .and_then(|m| serde_json::from_str(m).ok())
1401    }
1402
1403    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1404    pub(crate) fn text_hash(text: &str) -> u64 {
1405        let mut hasher = SeaHasher::new();
1406        text.hash(&mut hasher);
1407        hasher.finish()
1408    }
1409}