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    pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
 692        self.handler.replace_text_in_range(None, input, cx);
 693    }
 694
 695    pub fn selected_bounds(&mut self, cx: &mut WindowContext) -> Option<Bounds<Pixels>> {
 696        let selection = self.handler.selected_text_range(true, cx)?;
 697        self.handler.bounds_for_range(
 698            if selection.reversed {
 699                selection.range.start..selection.range.start
 700            } else {
 701                selection.range.end..selection.range.end
 702            },
 703            cx,
 704        )
 705    }
 706}
 707
 708/// A struct representing a selection in a text buffer, in UTF16 characters.
 709/// This is different from a range because the head may be before the tail.
 710pub struct UTF16Selection {
 711    /// The range of text in the document this selection corresponds to
 712    /// in UTF16 characters.
 713    pub range: Range<usize>,
 714    /// Whether the head of this selection is at the start (true), or end (false)
 715    /// of the range
 716    pub reversed: bool,
 717}
 718
 719/// Zed's interface for handling text input from the platform's IME system
 720/// This is currently a 1:1 exposure of the NSTextInputClient API:
 721///
 722/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
 723pub trait InputHandler: 'static {
 724    /// Get the range of the user's currently selected text, if any
 725    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
 726    ///
 727    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 728    fn selected_text_range(
 729        &mut self,
 730        ignore_disabled_input: bool,
 731        cx: &mut WindowContext,
 732    ) -> Option<UTF16Selection>;
 733
 734    /// Get the range of the currently marked text, if any
 735    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
 736    ///
 737    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 738    fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
 739
 740    /// Get the text for the given document range in UTF-16 characters
 741    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
 742    ///
 743    /// range_utf16 is in terms of UTF-16 characters
 744    fn text_for_range(
 745        &mut self,
 746        range_utf16: Range<usize>,
 747        cx: &mut WindowContext,
 748    ) -> Option<String>;
 749
 750    /// Replace the text in the given document range with the given text
 751    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
 752    ///
 753    /// replacement_range is in terms of UTF-16 characters
 754    fn replace_text_in_range(
 755        &mut self,
 756        replacement_range: Option<Range<usize>>,
 757        text: &str,
 758        cx: &mut WindowContext,
 759    );
 760
 761    /// Replace the text in the given document range with the given text,
 762    /// and mark the given text as part of an IME 'composing' state
 763    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
 764    ///
 765    /// range_utf16 is in terms of UTF-16 characters
 766    /// new_selected_range is in terms of UTF-16 characters
 767    fn replace_and_mark_text_in_range(
 768        &mut self,
 769        range_utf16: Option<Range<usize>>,
 770        new_text: &str,
 771        new_selected_range: Option<Range<usize>>,
 772        cx: &mut WindowContext,
 773    );
 774
 775    /// Remove the IME 'composing' state from the document
 776    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
 777    fn unmark_text(&mut self, cx: &mut WindowContext);
 778
 779    /// Get the bounds of the given document range in screen coordinates
 780    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
 781    ///
 782    /// This is used for positioning the IME candidate window
 783    fn bounds_for_range(
 784        &mut self,
 785        range_utf16: Range<usize>,
 786        cx: &mut WindowContext,
 787    ) -> Option<Bounds<Pixels>>;
 788}
 789
 790/// The variables that can be configured when creating a new window
 791#[derive(Debug)]
 792pub struct WindowOptions {
 793    /// Specifies the state and bounds of the window in screen coordinates.
 794    /// - `None`: Inherit the bounds.
 795    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
 796    pub window_bounds: Option<WindowBounds>,
 797
 798    /// The titlebar configuration of the window
 799    pub titlebar: Option<TitlebarOptions>,
 800
 801    /// Whether the window should be focused when created
 802    pub focus: bool,
 803
 804    /// Whether the window should be shown when created
 805    pub show: bool,
 806
 807    /// The kind of window to create
 808    pub kind: WindowKind,
 809
 810    /// Whether the window should be movable by the user
 811    pub is_movable: bool,
 812
 813    /// The display to create the window on, if this is None,
 814    /// the window will be created on the main display
 815    pub display_id: Option<DisplayId>,
 816
 817    /// The appearance of the window background.
 818    pub window_background: WindowBackgroundAppearance,
 819
 820    /// Application identifier of the window. Can by used by desktop environments to group applications together.
 821    pub app_id: Option<String>,
 822
 823    /// Window minimum size
 824    pub window_min_size: Option<Size<Pixels>>,
 825
 826    /// Whether to use client or server side decorations. Wayland only
 827    /// Note that this may be ignored.
 828    pub window_decorations: Option<WindowDecorations>,
 829}
 830
 831/// The variables that can be configured when creating a new window
 832#[derive(Debug)]
 833#[cfg_attr(
 834    all(
 835        any(target_os = "linux", target_os = "freebsd"),
 836        not(any(feature = "x11", feature = "wayland"))
 837    ),
 838    allow(dead_code)
 839)]
 840pub(crate) struct WindowParams {
 841    pub bounds: Bounds<Pixels>,
 842
 843    /// The titlebar configuration of the window
 844    #[cfg_attr(feature = "wayland", allow(dead_code))]
 845    pub titlebar: Option<TitlebarOptions>,
 846
 847    /// The kind of window to create
 848    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 849    pub kind: WindowKind,
 850
 851    /// Whether the window should be movable by the user
 852    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 853    pub is_movable: bool,
 854
 855    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 856    pub focus: bool,
 857
 858    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 859    pub show: bool,
 860
 861    #[cfg_attr(feature = "wayland", allow(dead_code))]
 862    pub display_id: Option<DisplayId>,
 863
 864    pub window_min_size: Option<Size<Pixels>>,
 865}
 866
 867/// Represents the status of how a window should be opened.
 868#[derive(Debug, Copy, Clone, PartialEq)]
 869pub enum WindowBounds {
 870    /// Indicates that the window should open in a windowed state with the given bounds.
 871    Windowed(Bounds<Pixels>),
 872    /// Indicates that the window should open in a maximized state.
 873    /// The bounds provided here represent the restore size of the window.
 874    Maximized(Bounds<Pixels>),
 875    /// Indicates that the window should open in fullscreen mode.
 876    /// The bounds provided here represent the restore size of the window.
 877    Fullscreen(Bounds<Pixels>),
 878}
 879
 880impl Default for WindowBounds {
 881    fn default() -> Self {
 882        WindowBounds::Windowed(Bounds::default())
 883    }
 884}
 885
 886impl WindowBounds {
 887    /// Retrieve the inner bounds
 888    pub fn get_bounds(&self) -> Bounds<Pixels> {
 889        match self {
 890            WindowBounds::Windowed(bounds) => *bounds,
 891            WindowBounds::Maximized(bounds) => *bounds,
 892            WindowBounds::Fullscreen(bounds) => *bounds,
 893        }
 894    }
 895}
 896
 897impl Default for WindowOptions {
 898    fn default() -> Self {
 899        Self {
 900            window_bounds: None,
 901            titlebar: Some(TitlebarOptions {
 902                title: Default::default(),
 903                appears_transparent: Default::default(),
 904                traffic_light_position: Default::default(),
 905            }),
 906            focus: true,
 907            show: true,
 908            kind: WindowKind::Normal,
 909            is_movable: true,
 910            display_id: None,
 911            window_background: WindowBackgroundAppearance::default(),
 912            app_id: None,
 913            window_min_size: None,
 914            window_decorations: None,
 915        }
 916    }
 917}
 918
 919/// The options that can be configured for a window's titlebar
 920#[derive(Debug, Default)]
 921pub struct TitlebarOptions {
 922    /// The initial title of the window
 923    pub title: Option<SharedString>,
 924
 925    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
 926    /// Refer to [`WindowOptions::window_decorations`] on Linux
 927    pub appears_transparent: bool,
 928
 929    /// The position of the macOS traffic light buttons
 930    pub traffic_light_position: Option<Point<Pixels>>,
 931}
 932
 933/// The kind of window to create
 934#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 935pub enum WindowKind {
 936    /// A normal application window
 937    Normal,
 938
 939    /// A window that appears above all other windows, usually used for alerts or popups
 940    /// use sparingly!
 941    PopUp,
 942}
 943
 944/// The appearance of the window, as defined by the operating system.
 945///
 946/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
 947/// values.
 948#[derive(Copy, Clone, Debug)]
 949pub enum WindowAppearance {
 950    /// A light appearance.
 951    ///
 952    /// On macOS, this corresponds to the `aqua` appearance.
 953    Light,
 954
 955    /// A light appearance with vibrant colors.
 956    ///
 957    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
 958    VibrantLight,
 959
 960    /// A dark appearance.
 961    ///
 962    /// On macOS, this corresponds to the `darkAqua` appearance.
 963    Dark,
 964
 965    /// A dark appearance with vibrant colors.
 966    ///
 967    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
 968    VibrantDark,
 969}
 970
 971impl Default for WindowAppearance {
 972    fn default() -> Self {
 973        Self::Light
 974    }
 975}
 976
 977/// The appearance of the background of the window itself, when there is
 978/// no content or the content is transparent.
 979#[derive(Copy, Clone, Debug, Default, PartialEq)]
 980pub enum WindowBackgroundAppearance {
 981    /// Opaque.
 982    ///
 983    /// This lets the window manager know that content behind this
 984    /// window does not need to be drawn.
 985    ///
 986    /// Actual color depends on the system and themes should define a fully
 987    /// opaque background color instead.
 988    #[default]
 989    Opaque,
 990    /// Plain alpha transparency.
 991    Transparent,
 992    /// Transparency, but the contents behind the window are blurred.
 993    ///
 994    /// Not always supported.
 995    Blurred,
 996}
 997
 998/// The options that can be configured for a file dialog prompt
 999#[derive(Copy, Clone, Debug)]
1000pub struct PathPromptOptions {
1001    /// Should the prompt allow files to be selected?
1002    pub files: bool,
1003    /// Should the prompt allow directories to be selected?
1004    pub directories: bool,
1005    /// Should the prompt allow multiple files to be selected?
1006    pub multiple: bool,
1007}
1008
1009/// What kind of prompt styling to show
1010#[derive(Copy, Clone, Debug, PartialEq)]
1011pub enum PromptLevel {
1012    /// A prompt that is shown when the user should be notified of something
1013    Info,
1014
1015    /// A prompt that is shown when the user needs to be warned of a potential problem
1016    Warning,
1017
1018    /// A prompt that is shown when a critical problem has occurred
1019    Critical,
1020}
1021
1022/// The style of the cursor (pointer)
1023#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1024pub enum CursorStyle {
1025    /// The default cursor
1026    Arrow,
1027
1028    /// A text input cursor
1029    /// corresponds to the CSS cursor value `text`
1030    IBeam,
1031
1032    /// A crosshair cursor
1033    /// corresponds to the CSS cursor value `crosshair`
1034    Crosshair,
1035
1036    /// A closed hand cursor
1037    /// corresponds to the CSS cursor value `grabbing`
1038    ClosedHand,
1039
1040    /// An open hand cursor
1041    /// corresponds to the CSS cursor value `grab`
1042    OpenHand,
1043
1044    /// A pointing hand cursor
1045    /// corresponds to the CSS cursor value `pointer`
1046    PointingHand,
1047
1048    /// A resize left cursor
1049    /// corresponds to the CSS cursor value `w-resize`
1050    ResizeLeft,
1051
1052    /// A resize right cursor
1053    /// corresponds to the CSS cursor value `e-resize`
1054    ResizeRight,
1055
1056    /// A resize cursor to the left and right
1057    /// corresponds to the CSS cursor value `ew-resize`
1058    ResizeLeftRight,
1059
1060    /// A resize up cursor
1061    /// corresponds to the CSS cursor value `n-resize`
1062    ResizeUp,
1063
1064    /// A resize down cursor
1065    /// corresponds to the CSS cursor value `s-resize`
1066    ResizeDown,
1067
1068    /// A resize cursor directing up and down
1069    /// corresponds to the CSS cursor value `ns-resize`
1070    ResizeUpDown,
1071
1072    /// A resize cursor directing up-left and down-right
1073    /// corresponds to the CSS cursor value `nesw-resize`
1074    ResizeUpLeftDownRight,
1075
1076    /// A resize cursor directing up-right and down-left
1077    /// corresponds to the CSS cursor value `nwse-resize`
1078    ResizeUpRightDownLeft,
1079
1080    /// A cursor indicating that the item/column can be resized horizontally.
1081    /// corresponds to the CSS cursor value `col-resize`
1082    ResizeColumn,
1083
1084    /// A cursor indicating that the item/row can be resized vertically.
1085    /// corresponds to the CSS cursor value `row-resize`
1086    ResizeRow,
1087
1088    /// A text input cursor for vertical layout
1089    /// corresponds to the CSS cursor value `vertical-text`
1090    IBeamCursorForVerticalLayout,
1091
1092    /// A cursor indicating that the operation is not allowed
1093    /// corresponds to the CSS cursor value `not-allowed`
1094    OperationNotAllowed,
1095
1096    /// A cursor indicating that the operation will result in a link
1097    /// corresponds to the CSS cursor value `alias`
1098    DragLink,
1099
1100    /// A cursor indicating that the operation will result in a copy
1101    /// corresponds to the CSS cursor value `copy`
1102    DragCopy,
1103
1104    /// A cursor indicating that the operation will result in a context menu
1105    /// corresponds to the CSS cursor value `context-menu`
1106    ContextualMenu,
1107}
1108
1109impl Default for CursorStyle {
1110    fn default() -> Self {
1111        Self::Arrow
1112    }
1113}
1114
1115/// A clipboard item that should be copied to the clipboard
1116#[derive(Clone, Debug, Eq, PartialEq)]
1117pub struct ClipboardItem {
1118    entries: Vec<ClipboardEntry>,
1119}
1120
1121/// Either a ClipboardString or a ClipboardImage
1122#[derive(Clone, Debug, Eq, PartialEq)]
1123pub enum ClipboardEntry {
1124    /// A string entry
1125    String(ClipboardString),
1126    /// An image entry
1127    Image(Image),
1128}
1129
1130impl ClipboardItem {
1131    /// Create a new ClipboardItem::String with no associated metadata
1132    pub fn new_string(text: String) -> Self {
1133        Self {
1134            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1135        }
1136    }
1137
1138    /// Create a new ClipboardItem::String with the given text and associated metadata
1139    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1140        Self {
1141            entries: vec![ClipboardEntry::String(ClipboardString {
1142                text,
1143                metadata: Some(metadata),
1144            })],
1145        }
1146    }
1147
1148    /// Create a new ClipboardItem::String with the given text and associated metadata
1149    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1150        Self {
1151            entries: vec![ClipboardEntry::String(
1152                ClipboardString::new(text).with_json_metadata(metadata),
1153            )],
1154        }
1155    }
1156
1157    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1158    pub fn new_image(image: &Image) -> Self {
1159        Self {
1160            entries: vec![ClipboardEntry::Image(image.clone())],
1161        }
1162    }
1163
1164    /// Concatenates together all the ClipboardString entries in the item.
1165    /// Returns None if there were no ClipboardString entries.
1166    pub fn text(&self) -> Option<String> {
1167        let mut answer = String::new();
1168        let mut any_entries = false;
1169
1170        for entry in self.entries.iter() {
1171            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1172                answer.push_str(text);
1173                any_entries = true;
1174            }
1175        }
1176
1177        if any_entries {
1178            Some(answer)
1179        } else {
1180            None
1181        }
1182    }
1183
1184    /// If this item is one ClipboardEntry::String, returns its metadata.
1185    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1186    pub fn metadata(&self) -> Option<&String> {
1187        match self.entries().first() {
1188            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1189                clipboard_string.metadata.as_ref()
1190            }
1191            _ => None,
1192        }
1193    }
1194
1195    /// Get the item's entries
1196    pub fn entries(&self) -> &[ClipboardEntry] {
1197        &self.entries
1198    }
1199
1200    /// Get owned versions of the item's entries
1201    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1202        self.entries.into_iter()
1203    }
1204}
1205
1206/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1207#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1208pub enum ImageFormat {
1209    // Sorted from most to least likely to be pasted into an editor,
1210    // which matters when we iterate through them trying to see if
1211    // clipboard content matches them.
1212    /// .png
1213    Png,
1214    /// .jpeg or .jpg
1215    Jpeg,
1216    /// .webp
1217    Webp,
1218    /// .gif
1219    Gif,
1220    /// .svg
1221    Svg,
1222    /// .bmp
1223    Bmp,
1224    /// .tif or .tiff
1225    Tiff,
1226}
1227
1228/// An image, with a format and certain bytes
1229#[derive(Clone, Debug, PartialEq, Eq)]
1230pub struct Image {
1231    /// The image format the bytes represent (e.g. PNG)
1232    pub format: ImageFormat,
1233    /// The raw image bytes
1234    pub bytes: Vec<u8>,
1235    /// The unique ID for the image
1236    pub id: u64,
1237}
1238
1239impl Hash for Image {
1240    fn hash<H: Hasher>(&self, state: &mut H) {
1241        state.write_u64(self.id);
1242    }
1243}
1244
1245impl Image {
1246    /// Get this image's ID
1247    pub fn id(&self) -> u64 {
1248        self.id
1249    }
1250
1251    /// Use the GPUI `use_asset` API to make this image renderable
1252    pub fn use_render_image(self: Arc<Self>, cx: &mut WindowContext) -> Option<Arc<RenderImage>> {
1253        ImageSource::Image(self).use_data(cx)
1254    }
1255
1256    /// Convert the clipboard image to an `ImageData` object.
1257    pub fn to_image_data(&self, cx: &AppContext) -> Result<Arc<RenderImage>> {
1258        fn frames_for_image(
1259            bytes: &[u8],
1260            format: image::ImageFormat,
1261        ) -> Result<SmallVec<[Frame; 1]>> {
1262            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1263
1264            // Convert from RGBA to BGRA.
1265            for pixel in data.chunks_exact_mut(4) {
1266                pixel.swap(0, 2);
1267            }
1268
1269            Ok(SmallVec::from_elem(Frame::new(data), 1))
1270        }
1271
1272        let frames = match self.format {
1273            ImageFormat::Gif => {
1274                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1275                let mut frames = SmallVec::new();
1276
1277                for frame in decoder.into_frames() {
1278                    let mut frame = frame?;
1279                    // Convert from RGBA to BGRA.
1280                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1281                        pixel.swap(0, 2);
1282                    }
1283                    frames.push(frame);
1284                }
1285
1286                frames
1287            }
1288            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1289            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1290            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1291            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1292            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1293            ImageFormat::Svg => {
1294                // TODO: Fix this
1295                let pixmap = cx
1296                    .svg_renderer()
1297                    .render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1298
1299                let buffer =
1300                    image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1301                        .unwrap();
1302
1303                SmallVec::from_elem(Frame::new(buffer), 1)
1304            }
1305        };
1306
1307        Ok(Arc::new(RenderImage::new(frames)))
1308    }
1309
1310    /// Get the format of the clipboard image
1311    pub fn format(&self) -> ImageFormat {
1312        self.format
1313    }
1314
1315    /// Get the raw bytes of the clipboard image
1316    pub fn bytes(&self) -> &[u8] {
1317        self.bytes.as_slice()
1318    }
1319}
1320
1321/// A clipboard item that should be copied to the clipboard
1322#[derive(Clone, Debug, Eq, PartialEq)]
1323pub struct ClipboardString {
1324    pub(crate) text: String,
1325    pub(crate) metadata: Option<String>,
1326}
1327
1328impl ClipboardString {
1329    /// Create a new clipboard string with the given text
1330    pub fn new(text: String) -> Self {
1331        Self {
1332            text,
1333            metadata: None,
1334        }
1335    }
1336
1337    /// Return a new clipboard item with the metadata replaced by the given metadata,
1338    /// after serializing it as JSON.
1339    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1340        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1341        self
1342    }
1343
1344    /// Get the text of the clipboard string
1345    pub fn text(&self) -> &String {
1346        &self.text
1347    }
1348
1349    /// Get the owned text of the clipboard string
1350    pub fn into_text(self) -> String {
1351        self.text
1352    }
1353
1354    /// Get the metadata of the clipboard string, formatted as JSON
1355    pub fn metadata_json<T>(&self) -> Option<T>
1356    where
1357        T: for<'a> Deserialize<'a>,
1358    {
1359        self.metadata
1360            .as_ref()
1361            .and_then(|m| serde_json::from_str(m).ok())
1362    }
1363
1364    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1365    pub(crate) fn text_hash(text: &str) -> u64 {
1366        let mut hasher = SeaHasher::new();
1367        text.hash(&mut hasher);
1368        hasher.finish()
1369    }
1370}