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