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