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
 342pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
 343    fn bounds(&self) -> Bounds<Pixels>;
 344    fn is_maximized(&self) -> bool;
 345    fn window_bounds(&self) -> WindowBounds;
 346    fn content_size(&self) -> Size<Pixels>;
 347    fn scale_factor(&self) -> f32;
 348    fn appearance(&self) -> WindowAppearance;
 349    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 350    fn mouse_position(&self) -> Point<Pixels>;
 351    fn modifiers(&self) -> Modifiers;
 352    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
 353    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
 354    fn prompt(
 355        &self,
 356        level: PromptLevel,
 357        msg: &str,
 358        detail: Option<&str>,
 359        answers: &[&str],
 360    ) -> Option<oneshot::Receiver<usize>>;
 361    fn activate(&self);
 362    fn is_active(&self) -> bool;
 363    fn is_hovered(&self) -> bool;
 364    fn set_title(&mut self, title: &str);
 365    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
 366    fn minimize(&self);
 367    fn zoom(&self);
 368    fn toggle_fullscreen(&self);
 369    fn is_fullscreen(&self) -> bool;
 370    fn on_request_frame(&self, callback: Box<dyn FnMut()>);
 371    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
 372    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
 373    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
 374    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
 375    fn on_moved(&self, callback: Box<dyn FnMut()>);
 376    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
 377    fn on_close(&self, callback: Box<dyn FnOnce()>);
 378    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
 379    fn draw(&self, scene: &Scene);
 380    fn completed_frame(&self) {}
 381    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
 382
 383    // macOS specific methods
 384    fn set_edited(&mut self, _edited: bool) {}
 385    fn show_character_palette(&self) {}
 386
 387    #[cfg(target_os = "windows")]
 388    fn get_raw_handle(&self) -> windows::HWND;
 389
 390    // Linux specific methods
 391    fn request_decorations(&self, _decorations: WindowDecorations) {}
 392    fn show_window_menu(&self, _position: Point<Pixels>) {}
 393    fn start_window_move(&self) {}
 394    fn start_window_resize(&self, _edge: ResizeEdge) {}
 395    fn window_decorations(&self) -> Decorations {
 396        Decorations::Server
 397    }
 398    fn set_app_id(&mut self, _app_id: &str) {}
 399    fn window_controls(&self) -> WindowControls {
 400        WindowControls::default()
 401    }
 402    fn set_client_inset(&self, _inset: Pixels) {}
 403    fn gpu_specs(&self) -> Option<GPUSpecs>;
 404
 405    fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>);
 406
 407    #[cfg(any(test, feature = "test-support"))]
 408    fn as_test(&mut self) -> Option<&mut TestWindow> {
 409        None
 410    }
 411}
 412
 413/// This type is public so that our test macro can generate and use it, but it should not
 414/// be considered part of our public API.
 415#[doc(hidden)]
 416pub trait PlatformDispatcher: Send + Sync {
 417    fn is_main_thread(&self) -> bool;
 418    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
 419    fn dispatch_on_main_thread(&self, runnable: Runnable);
 420    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
 421    fn park(&self, timeout: Option<Duration>) -> bool;
 422    fn unparker(&self) -> Unparker;
 423    fn now(&self) -> Instant {
 424        Instant::now()
 425    }
 426
 427    #[cfg(any(test, feature = "test-support"))]
 428    fn as_test(&self) -> Option<&TestDispatcher> {
 429        None
 430    }
 431}
 432
 433pub(crate) trait PlatformTextSystem: Send + Sync {
 434    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
 435    fn all_font_names(&self) -> Vec<String>;
 436    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
 437    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
 438    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
 439    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
 440    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
 441    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
 442    fn rasterize_glyph(
 443        &self,
 444        params: &RenderGlyphParams,
 445        raster_bounds: Bounds<DevicePixels>,
 446    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
 447    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
 448}
 449
 450pub(crate) struct NoopTextSystem;
 451
 452impl NoopTextSystem {
 453    #[allow(dead_code)]
 454    pub fn new() -> Self {
 455        Self
 456    }
 457}
 458
 459impl PlatformTextSystem for NoopTextSystem {
 460    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 461        Ok(())
 462    }
 463
 464    fn all_font_names(&self) -> Vec<String> {
 465        Vec::new()
 466    }
 467
 468    fn font_id(&self, descriptor: &Font) -> Result<FontId> {
 469        Err(anyhow!("No font found for {:?}", descriptor))
 470    }
 471
 472    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
 473        unimplemented!()
 474    }
 475
 476    fn typographic_bounds(&self, font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
 477        Err(anyhow!("No font found for {:?}", font_id))
 478    }
 479
 480    fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> Result<Size<f32>> {
 481        Err(anyhow!("No font found for {:?}", font_id))
 482    }
 483
 484    fn glyph_for_char(&self, _font_id: FontId, _ch: char) -> Option<GlyphId> {
 485        None
 486    }
 487
 488    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 489        Err(anyhow!("No font found for {:?}", params))
 490    }
 491
 492    fn rasterize_glyph(
 493        &self,
 494        params: &RenderGlyphParams,
 495        _raster_bounds: Bounds<DevicePixels>,
 496    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 497        Err(anyhow!("No font found for {:?}", params))
 498    }
 499
 500    fn layout_line(&self, _text: &str, _font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
 501        unimplemented!()
 502    }
 503}
 504
 505#[derive(PartialEq, Eq, Hash, Clone)]
 506pub(crate) enum AtlasKey {
 507    Glyph(RenderGlyphParams),
 508    Svg(RenderSvgParams),
 509    Image(RenderImageParams),
 510}
 511
 512impl AtlasKey {
 513    #[cfg_attr(
 514        all(
 515            any(target_os = "linux", target_os = "freebsd"),
 516            not(any(feature = "x11", feature = "wayland"))
 517        ),
 518        allow(dead_code)
 519    )]
 520    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
 521        match self {
 522            AtlasKey::Glyph(params) => {
 523                if params.is_emoji {
 524                    AtlasTextureKind::Polychrome
 525                } else {
 526                    AtlasTextureKind::Monochrome
 527                }
 528            }
 529            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
 530            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
 531        }
 532    }
 533}
 534
 535impl From<RenderGlyphParams> for AtlasKey {
 536    fn from(params: RenderGlyphParams) -> Self {
 537        Self::Glyph(params)
 538    }
 539}
 540
 541impl From<RenderSvgParams> for AtlasKey {
 542    fn from(params: RenderSvgParams) -> Self {
 543        Self::Svg(params)
 544    }
 545}
 546
 547impl From<RenderImageParams> for AtlasKey {
 548    fn from(params: RenderImageParams) -> Self {
 549        Self::Image(params)
 550    }
 551}
 552
 553pub(crate) trait PlatformAtlas: Send + Sync {
 554    fn get_or_insert_with<'a>(
 555        &self,
 556        key: &AtlasKey,
 557        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 558    ) -> Result<Option<AtlasTile>>;
 559}
 560
 561#[derive(Clone, Debug, PartialEq, Eq)]
 562#[repr(C)]
 563pub(crate) struct AtlasTile {
 564    pub(crate) texture_id: AtlasTextureId,
 565    pub(crate) tile_id: TileId,
 566    pub(crate) padding: u32,
 567    pub(crate) bounds: Bounds<DevicePixels>,
 568}
 569
 570#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 571#[repr(C)]
 572pub(crate) struct AtlasTextureId {
 573    // We use u32 instead of usize for Metal Shader Language compatibility
 574    pub(crate) index: u32,
 575    pub(crate) kind: AtlasTextureKind,
 576}
 577
 578#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 579#[repr(C)]
 580#[cfg_attr(
 581    all(
 582        any(target_os = "linux", target_os = "freebsd"),
 583        not(any(feature = "x11", feature = "wayland"))
 584    ),
 585    allow(dead_code)
 586)]
 587pub(crate) enum AtlasTextureKind {
 588    Monochrome = 0,
 589    Polychrome = 1,
 590    Path = 2,
 591}
 592
 593#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 594#[repr(C)]
 595pub(crate) struct TileId(pub(crate) u32);
 596
 597impl From<etagere::AllocId> for TileId {
 598    fn from(id: etagere::AllocId) -> Self {
 599        Self(id.serialize())
 600    }
 601}
 602
 603impl From<TileId> for etagere::AllocId {
 604    fn from(id: TileId) -> Self {
 605        Self::deserialize(id.0)
 606    }
 607}
 608
 609pub(crate) struct PlatformInputHandler {
 610    cx: AsyncWindowContext,
 611    handler: Box<dyn InputHandler>,
 612}
 613
 614#[cfg_attr(
 615    all(
 616        any(target_os = "linux", target_os = "freebsd"),
 617        not(any(feature = "x11", feature = "wayland"))
 618    ),
 619    allow(dead_code)
 620)]
 621impl PlatformInputHandler {
 622    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
 623        Self { cx, handler }
 624    }
 625
 626    fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
 627        self.cx
 628            .update(|cx| self.handler.selected_text_range(ignore_disabled_input, cx))
 629            .ok()
 630            .flatten()
 631    }
 632
 633    fn marked_text_range(&mut self) -> Option<Range<usize>> {
 634        self.cx
 635            .update(|cx| self.handler.marked_text_range(cx))
 636            .ok()
 637            .flatten()
 638    }
 639
 640    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 641    fn text_for_range(&mut self, range_utf16: Range<usize>) -> Option<String> {
 642        self.cx
 643            .update(|cx| self.handler.text_for_range(range_utf16, cx))
 644            .ok()
 645            .flatten()
 646    }
 647
 648    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
 649        self.cx
 650            .update(|cx| {
 651                self.handler
 652                    .replace_text_in_range(replacement_range, text, cx);
 653            })
 654            .ok();
 655    }
 656
 657    fn replace_and_mark_text_in_range(
 658        &mut self,
 659        range_utf16: Option<Range<usize>>,
 660        new_text: &str,
 661        new_selected_range: Option<Range<usize>>,
 662    ) {
 663        self.cx
 664            .update(|cx| {
 665                self.handler.replace_and_mark_text_in_range(
 666                    range_utf16,
 667                    new_text,
 668                    new_selected_range,
 669                    cx,
 670                )
 671            })
 672            .ok();
 673    }
 674
 675    fn unmark_text(&mut self) {
 676        self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
 677    }
 678
 679    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
 680        self.cx
 681            .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
 682            .ok()
 683            .flatten()
 684    }
 685
 686    #[allow(dead_code)]
 687    fn apple_press_and_hold_enabled(&mut self) -> bool {
 688        self.handler.apple_press_and_hold_enabled()
 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    /// Allows a given input context to opt into getting raw key repeats instead of
 790    /// sending these to the platform.
 791    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
 792    /// (which is how iTerm does it) but it doesn't seem to work for me.
 793    #[allow(dead_code)]
 794    fn apple_press_and_hold_enabled(&mut self) -> bool {
 795        true
 796    }
 797}
 798
 799/// The variables that can be configured when creating a new window
 800#[derive(Debug)]
 801pub struct WindowOptions {
 802    /// Specifies the state and bounds of the window in screen coordinates.
 803    /// - `None`: Inherit the bounds.
 804    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
 805    pub window_bounds: Option<WindowBounds>,
 806
 807    /// The titlebar configuration of the window
 808    pub titlebar: Option<TitlebarOptions>,
 809
 810    /// Whether the window should be focused when created
 811    pub focus: bool,
 812
 813    /// Whether the window should be shown when created
 814    pub show: bool,
 815
 816    /// The kind of window to create
 817    pub kind: WindowKind,
 818
 819    /// Whether the window should be movable by the user
 820    pub is_movable: bool,
 821
 822    /// The display to create the window on, if this is None,
 823    /// the window will be created on the main display
 824    pub display_id: Option<DisplayId>,
 825
 826    /// The appearance of the window background.
 827    pub window_background: WindowBackgroundAppearance,
 828
 829    /// Application identifier of the window. Can by used by desktop environments to group applications together.
 830    pub app_id: Option<String>,
 831
 832    /// Window minimum size
 833    pub window_min_size: Option<Size<Pixels>>,
 834
 835    /// Whether to use client or server side decorations. Wayland only
 836    /// Note that this may be ignored.
 837    pub window_decorations: Option<WindowDecorations>,
 838}
 839
 840/// The variables that can be configured when creating a new window
 841#[derive(Debug)]
 842#[cfg_attr(
 843    all(
 844        any(target_os = "linux", target_os = "freebsd"),
 845        not(any(feature = "x11", feature = "wayland"))
 846    ),
 847    allow(dead_code)
 848)]
 849pub(crate) struct WindowParams {
 850    pub bounds: Bounds<Pixels>,
 851
 852    /// The titlebar configuration of the window
 853    #[cfg_attr(feature = "wayland", allow(dead_code))]
 854    pub titlebar: Option<TitlebarOptions>,
 855
 856    /// The kind of window to create
 857    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 858    pub kind: WindowKind,
 859
 860    /// Whether the window should be movable by the user
 861    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 862    pub is_movable: bool,
 863
 864    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 865    pub focus: bool,
 866
 867    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 868    pub show: bool,
 869
 870    #[cfg_attr(feature = "wayland", allow(dead_code))]
 871    pub display_id: Option<DisplayId>,
 872
 873    pub window_min_size: Option<Size<Pixels>>,
 874}
 875
 876/// Represents the status of how a window should be opened.
 877#[derive(Debug, Copy, Clone, PartialEq)]
 878pub enum WindowBounds {
 879    /// Indicates that the window should open in a windowed state with the given bounds.
 880    Windowed(Bounds<Pixels>),
 881    /// Indicates that the window should open in a maximized state.
 882    /// The bounds provided here represent the restore size of the window.
 883    Maximized(Bounds<Pixels>),
 884    /// Indicates that the window should open in fullscreen mode.
 885    /// The bounds provided here represent the restore size of the window.
 886    Fullscreen(Bounds<Pixels>),
 887}
 888
 889impl Default for WindowBounds {
 890    fn default() -> Self {
 891        WindowBounds::Windowed(Bounds::default())
 892    }
 893}
 894
 895impl WindowBounds {
 896    /// Retrieve the inner bounds
 897    pub fn get_bounds(&self) -> Bounds<Pixels> {
 898        match self {
 899            WindowBounds::Windowed(bounds) => *bounds,
 900            WindowBounds::Maximized(bounds) => *bounds,
 901            WindowBounds::Fullscreen(bounds) => *bounds,
 902        }
 903    }
 904}
 905
 906impl Default for WindowOptions {
 907    fn default() -> Self {
 908        Self {
 909            window_bounds: None,
 910            titlebar: Some(TitlebarOptions {
 911                title: Default::default(),
 912                appears_transparent: Default::default(),
 913                traffic_light_position: Default::default(),
 914            }),
 915            focus: true,
 916            show: true,
 917            kind: WindowKind::Normal,
 918            is_movable: true,
 919            display_id: None,
 920            window_background: WindowBackgroundAppearance::default(),
 921            app_id: None,
 922            window_min_size: None,
 923            window_decorations: None,
 924        }
 925    }
 926}
 927
 928/// The options that can be configured for a window's titlebar
 929#[derive(Debug, Default)]
 930pub struct TitlebarOptions {
 931    /// The initial title of the window
 932    pub title: Option<SharedString>,
 933
 934    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
 935    /// Refer to [`WindowOptions::window_decorations`] on Linux
 936    pub appears_transparent: bool,
 937
 938    /// The position of the macOS traffic light buttons
 939    pub traffic_light_position: Option<Point<Pixels>>,
 940}
 941
 942/// The kind of window to create
 943#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 944pub enum WindowKind {
 945    /// A normal application window
 946    Normal,
 947
 948    /// A window that appears above all other windows, usually used for alerts or popups
 949    /// use sparingly!
 950    PopUp,
 951}
 952
 953/// The appearance of the window, as defined by the operating system.
 954///
 955/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
 956/// values.
 957#[derive(Copy, Clone, Debug)]
 958pub enum WindowAppearance {
 959    /// A light appearance.
 960    ///
 961    /// On macOS, this corresponds to the `aqua` appearance.
 962    Light,
 963
 964    /// A light appearance with vibrant colors.
 965    ///
 966    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
 967    VibrantLight,
 968
 969    /// A dark appearance.
 970    ///
 971    /// On macOS, this corresponds to the `darkAqua` appearance.
 972    Dark,
 973
 974    /// A dark appearance with vibrant colors.
 975    ///
 976    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
 977    VibrantDark,
 978}
 979
 980impl Default for WindowAppearance {
 981    fn default() -> Self {
 982        Self::Light
 983    }
 984}
 985
 986/// The appearance of the background of the window itself, when there is
 987/// no content or the content is transparent.
 988#[derive(Copy, Clone, Debug, Default, PartialEq)]
 989pub enum WindowBackgroundAppearance {
 990    /// Opaque.
 991    ///
 992    /// This lets the window manager know that content behind this
 993    /// window does not need to be drawn.
 994    ///
 995    /// Actual color depends on the system and themes should define a fully
 996    /// opaque background color instead.
 997    #[default]
 998    Opaque,
 999    /// Plain alpha transparency.
1000    Transparent,
1001    /// Transparency, but the contents behind the window are blurred.
1002    ///
1003    /// Not always supported.
1004    Blurred,
1005}
1006
1007/// The options that can be configured for a file dialog prompt
1008#[derive(Copy, Clone, Debug)]
1009pub struct PathPromptOptions {
1010    /// Should the prompt allow files to be selected?
1011    pub files: bool,
1012    /// Should the prompt allow directories to be selected?
1013    pub directories: bool,
1014    /// Should the prompt allow multiple files to be selected?
1015    pub multiple: bool,
1016}
1017
1018/// What kind of prompt styling to show
1019#[derive(Copy, Clone, Debug, PartialEq)]
1020pub enum PromptLevel {
1021    /// A prompt that is shown when the user should be notified of something
1022    Info,
1023
1024    /// A prompt that is shown when the user needs to be warned of a potential problem
1025    Warning,
1026
1027    /// A prompt that is shown when a critical problem has occurred
1028    Critical,
1029}
1030
1031/// The style of the cursor (pointer)
1032#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1033pub enum CursorStyle {
1034    /// The default cursor
1035    Arrow,
1036
1037    /// A text input cursor
1038    /// corresponds to the CSS cursor value `text`
1039    IBeam,
1040
1041    /// A crosshair cursor
1042    /// corresponds to the CSS cursor value `crosshair`
1043    Crosshair,
1044
1045    /// A closed hand cursor
1046    /// corresponds to the CSS cursor value `grabbing`
1047    ClosedHand,
1048
1049    /// An open hand cursor
1050    /// corresponds to the CSS cursor value `grab`
1051    OpenHand,
1052
1053    /// A pointing hand cursor
1054    /// corresponds to the CSS cursor value `pointer`
1055    PointingHand,
1056
1057    /// A resize left cursor
1058    /// corresponds to the CSS cursor value `w-resize`
1059    ResizeLeft,
1060
1061    /// A resize right cursor
1062    /// corresponds to the CSS cursor value `e-resize`
1063    ResizeRight,
1064
1065    /// A resize cursor to the left and right
1066    /// corresponds to the CSS cursor value `ew-resize`
1067    ResizeLeftRight,
1068
1069    /// A resize up cursor
1070    /// corresponds to the CSS cursor value `n-resize`
1071    ResizeUp,
1072
1073    /// A resize down cursor
1074    /// corresponds to the CSS cursor value `s-resize`
1075    ResizeDown,
1076
1077    /// A resize cursor directing up and down
1078    /// corresponds to the CSS cursor value `ns-resize`
1079    ResizeUpDown,
1080
1081    /// A resize cursor directing up-left and down-right
1082    /// corresponds to the CSS cursor value `nesw-resize`
1083    ResizeUpLeftDownRight,
1084
1085    /// A resize cursor directing up-right and down-left
1086    /// corresponds to the CSS cursor value `nwse-resize`
1087    ResizeUpRightDownLeft,
1088
1089    /// A cursor indicating that the item/column can be resized horizontally.
1090    /// corresponds to the CSS cursor value `col-resize`
1091    ResizeColumn,
1092
1093    /// A cursor indicating that the item/row can be resized vertically.
1094    /// corresponds to the CSS cursor value `row-resize`
1095    ResizeRow,
1096
1097    /// A text input cursor for vertical layout
1098    /// corresponds to the CSS cursor value `vertical-text`
1099    IBeamCursorForVerticalLayout,
1100
1101    /// A cursor indicating that the operation is not allowed
1102    /// corresponds to the CSS cursor value `not-allowed`
1103    OperationNotAllowed,
1104
1105    /// A cursor indicating that the operation will result in a link
1106    /// corresponds to the CSS cursor value `alias`
1107    DragLink,
1108
1109    /// A cursor indicating that the operation will result in a copy
1110    /// corresponds to the CSS cursor value `copy`
1111    DragCopy,
1112
1113    /// A cursor indicating that the operation will result in a context menu
1114    /// corresponds to the CSS cursor value `context-menu`
1115    ContextualMenu,
1116}
1117
1118impl Default for CursorStyle {
1119    fn default() -> Self {
1120        Self::Arrow
1121    }
1122}
1123
1124/// A clipboard item that should be copied to the clipboard
1125#[derive(Clone, Debug, Eq, PartialEq)]
1126pub struct ClipboardItem {
1127    entries: Vec<ClipboardEntry>,
1128}
1129
1130/// Either a ClipboardString or a ClipboardImage
1131#[derive(Clone, Debug, Eq, PartialEq)]
1132pub enum ClipboardEntry {
1133    /// A string entry
1134    String(ClipboardString),
1135    /// An image entry
1136    Image(Image),
1137}
1138
1139impl ClipboardItem {
1140    /// Create a new ClipboardItem::String with no associated metadata
1141    pub fn new_string(text: String) -> Self {
1142        Self {
1143            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1144        }
1145    }
1146
1147    /// Create a new ClipboardItem::String with the given text and associated metadata
1148    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1149        Self {
1150            entries: vec![ClipboardEntry::String(ClipboardString {
1151                text,
1152                metadata: Some(metadata),
1153            })],
1154        }
1155    }
1156
1157    /// Create a new ClipboardItem::String with the given text and associated metadata
1158    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1159        Self {
1160            entries: vec![ClipboardEntry::String(
1161                ClipboardString::new(text).with_json_metadata(metadata),
1162            )],
1163        }
1164    }
1165
1166    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1167    pub fn new_image(image: &Image) -> Self {
1168        Self {
1169            entries: vec![ClipboardEntry::Image(image.clone())],
1170        }
1171    }
1172
1173    /// Concatenates together all the ClipboardString entries in the item.
1174    /// Returns None if there were no ClipboardString entries.
1175    pub fn text(&self) -> Option<String> {
1176        let mut answer = String::new();
1177        let mut any_entries = false;
1178
1179        for entry in self.entries.iter() {
1180            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1181                answer.push_str(text);
1182                any_entries = true;
1183            }
1184        }
1185
1186        if any_entries {
1187            Some(answer)
1188        } else {
1189            None
1190        }
1191    }
1192
1193    /// If this item is one ClipboardEntry::String, returns its metadata.
1194    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1195    pub fn metadata(&self) -> Option<&String> {
1196        match self.entries().first() {
1197            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1198                clipboard_string.metadata.as_ref()
1199            }
1200            _ => None,
1201        }
1202    }
1203
1204    /// Get the item's entries
1205    pub fn entries(&self) -> &[ClipboardEntry] {
1206        &self.entries
1207    }
1208
1209    /// Get owned versions of the item's entries
1210    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1211        self.entries.into_iter()
1212    }
1213}
1214
1215/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1216#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1217pub enum ImageFormat {
1218    // Sorted from most to least likely to be pasted into an editor,
1219    // which matters when we iterate through them trying to see if
1220    // clipboard content matches them.
1221    /// .png
1222    Png,
1223    /// .jpeg or .jpg
1224    Jpeg,
1225    /// .webp
1226    Webp,
1227    /// .gif
1228    Gif,
1229    /// .svg
1230    Svg,
1231    /// .bmp
1232    Bmp,
1233    /// .tif or .tiff
1234    Tiff,
1235}
1236
1237/// An image, with a format and certain bytes
1238#[derive(Clone, Debug, PartialEq, Eq)]
1239pub struct Image {
1240    /// The image format the bytes represent (e.g. PNG)
1241    pub format: ImageFormat,
1242    /// The raw image bytes
1243    pub bytes: Vec<u8>,
1244    /// The unique ID for the image
1245    pub id: u64,
1246}
1247
1248impl Hash for Image {
1249    fn hash<H: Hasher>(&self, state: &mut H) {
1250        state.write_u64(self.id);
1251    }
1252}
1253
1254impl Image {
1255    /// Get this image's ID
1256    pub fn id(&self) -> u64 {
1257        self.id
1258    }
1259
1260    /// Use the GPUI `use_asset` API to make this image renderable
1261    pub fn use_render_image(self: Arc<Self>, cx: &mut WindowContext) -> Option<Arc<RenderImage>> {
1262        ImageSource::Image(self).use_data(cx)
1263    }
1264
1265    /// Convert the clipboard image to an `ImageData` object.
1266    pub fn to_image_data(&self, cx: &AppContext) -> Result<Arc<RenderImage>> {
1267        fn frames_for_image(
1268            bytes: &[u8],
1269            format: image::ImageFormat,
1270        ) -> Result<SmallVec<[Frame; 1]>> {
1271            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1272
1273            // Convert from RGBA to BGRA.
1274            for pixel in data.chunks_exact_mut(4) {
1275                pixel.swap(0, 2);
1276            }
1277
1278            Ok(SmallVec::from_elem(Frame::new(data), 1))
1279        }
1280
1281        let frames = match self.format {
1282            ImageFormat::Gif => {
1283                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1284                let mut frames = SmallVec::new();
1285
1286                for frame in decoder.into_frames() {
1287                    let mut frame = frame?;
1288                    // Convert from RGBA to BGRA.
1289                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1290                        pixel.swap(0, 2);
1291                    }
1292                    frames.push(frame);
1293                }
1294
1295                frames
1296            }
1297            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1298            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1299            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1300            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1301            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1302            ImageFormat::Svg => {
1303                // TODO: Fix this
1304                let pixmap = cx
1305                    .svg_renderer()
1306                    .render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1307
1308                let buffer =
1309                    image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1310                        .unwrap();
1311
1312                SmallVec::from_elem(Frame::new(buffer), 1)
1313            }
1314        };
1315
1316        Ok(Arc::new(RenderImage::new(frames)))
1317    }
1318
1319    /// Get the format of the clipboard image
1320    pub fn format(&self) -> ImageFormat {
1321        self.format
1322    }
1323
1324    /// Get the raw bytes of the clipboard image
1325    pub fn bytes(&self) -> &[u8] {
1326        self.bytes.as_slice()
1327    }
1328}
1329
1330/// A clipboard item that should be copied to the clipboard
1331#[derive(Clone, Debug, Eq, PartialEq)]
1332pub struct ClipboardString {
1333    pub(crate) text: String,
1334    pub(crate) metadata: Option<String>,
1335}
1336
1337impl ClipboardString {
1338    /// Create a new clipboard string with the given text
1339    pub fn new(text: String) -> Self {
1340        Self {
1341            text,
1342            metadata: None,
1343        }
1344    }
1345
1346    /// Return a new clipboard item with the metadata replaced by the given metadata,
1347    /// after serializing it as JSON.
1348    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1349        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1350        self
1351    }
1352
1353    /// Get the text of the clipboard string
1354    pub fn text(&self) -> &String {
1355        &self.text
1356    }
1357
1358    /// Get the owned text of the clipboard string
1359    pub fn into_text(self) -> String {
1360        self.text
1361    }
1362
1363    /// Get the metadata of the clipboard string, formatted as JSON
1364    pub fn metadata_json<T>(&self) -> Option<T>
1365    where
1366        T: for<'a> Deserialize<'a>,
1367    {
1368        self.metadata
1369            .as_ref()
1370            .and_then(|m| serde_json::from_str(m).ok())
1371    }
1372
1373    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1374    pub(crate) fn text_hash(text: &str) -> u64 {
1375        let mut hasher = SeaHasher::new();
1376        text.hash(&mut hasher);
1377        hasher.finish()
1378    }
1379}