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