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 map_window(&mut self) -> anyhow::Result<()> {
 436        Ok(())
 437    }
 438    fn window_controls(&self) -> WindowControls {
 439        WindowControls::default()
 440    }
 441    fn set_client_inset(&self, _inset: Pixels) {}
 442    fn gpu_specs(&self) -> Option<GpuSpecs>;
 443
 444    fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>);
 445
 446    #[cfg(any(test, feature = "test-support"))]
 447    fn as_test(&mut self) -> Option<&mut TestWindow> {
 448        None
 449    }
 450}
 451
 452/// This type is public so that our test macro can generate and use it, but it should not
 453/// be considered part of our public API.
 454#[doc(hidden)]
 455pub trait PlatformDispatcher: Send + Sync {
 456    fn is_main_thread(&self) -> bool;
 457    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
 458    fn dispatch_on_main_thread(&self, runnable: Runnable);
 459    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
 460    fn park(&self, timeout: Option<Duration>) -> bool;
 461    fn unparker(&self) -> Unparker;
 462    fn now(&self) -> Instant {
 463        Instant::now()
 464    }
 465
 466    #[cfg(any(test, feature = "test-support"))]
 467    fn as_test(&self) -> Option<&TestDispatcher> {
 468        None
 469    }
 470}
 471
 472pub(crate) trait PlatformTextSystem: Send + Sync {
 473    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
 474    fn all_font_names(&self) -> Vec<String>;
 475    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
 476    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
 477    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
 478    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
 479    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
 480    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
 481    fn rasterize_glyph(
 482        &self,
 483        params: &RenderGlyphParams,
 484        raster_bounds: Bounds<DevicePixels>,
 485    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
 486    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
 487}
 488
 489pub(crate) struct NoopTextSystem;
 490
 491impl NoopTextSystem {
 492    #[allow(dead_code)]
 493    pub fn new() -> Self {
 494        Self
 495    }
 496}
 497
 498impl PlatformTextSystem for NoopTextSystem {
 499    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 500        Ok(())
 501    }
 502
 503    fn all_font_names(&self) -> Vec<String> {
 504        Vec::new()
 505    }
 506
 507    fn font_id(&self, descriptor: &Font) -> Result<FontId> {
 508        Err(anyhow!("No font found for {:?}", descriptor))
 509    }
 510
 511    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
 512        unimplemented!()
 513    }
 514
 515    fn typographic_bounds(&self, font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
 516        Err(anyhow!("No font found for {:?}", font_id))
 517    }
 518
 519    fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> Result<Size<f32>> {
 520        Err(anyhow!("No font found for {:?}", font_id))
 521    }
 522
 523    fn glyph_for_char(&self, _font_id: FontId, _ch: char) -> Option<GlyphId> {
 524        None
 525    }
 526
 527    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 528        Err(anyhow!("No font found for {:?}", params))
 529    }
 530
 531    fn rasterize_glyph(
 532        &self,
 533        params: &RenderGlyphParams,
 534        _raster_bounds: Bounds<DevicePixels>,
 535    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 536        Err(anyhow!("No font found for {:?}", params))
 537    }
 538
 539    fn layout_line(&self, _text: &str, _font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
 540        unimplemented!()
 541    }
 542}
 543
 544#[derive(PartialEq, Eq, Hash, Clone)]
 545pub(crate) enum AtlasKey {
 546    Glyph(RenderGlyphParams),
 547    Svg(RenderSvgParams),
 548    Image(RenderImageParams),
 549}
 550
 551impl AtlasKey {
 552    #[cfg_attr(
 553        all(
 554            any(target_os = "linux", target_os = "freebsd"),
 555            not(any(feature = "x11", feature = "wayland"))
 556        ),
 557        allow(dead_code)
 558    )]
 559    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
 560        match self {
 561            AtlasKey::Glyph(params) => {
 562                if params.is_emoji {
 563                    AtlasTextureKind::Polychrome
 564                } else {
 565                    AtlasTextureKind::Monochrome
 566                }
 567            }
 568            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
 569            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
 570        }
 571    }
 572}
 573
 574impl From<RenderGlyphParams> for AtlasKey {
 575    fn from(params: RenderGlyphParams) -> Self {
 576        Self::Glyph(params)
 577    }
 578}
 579
 580impl From<RenderSvgParams> for AtlasKey {
 581    fn from(params: RenderSvgParams) -> Self {
 582        Self::Svg(params)
 583    }
 584}
 585
 586impl From<RenderImageParams> for AtlasKey {
 587    fn from(params: RenderImageParams) -> Self {
 588        Self::Image(params)
 589    }
 590}
 591
 592pub(crate) trait PlatformAtlas: Send + Sync {
 593    fn get_or_insert_with<'a>(
 594        &self,
 595        key: &AtlasKey,
 596        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 597    ) -> Result<Option<AtlasTile>>;
 598    fn remove(&self, key: &AtlasKey);
 599}
 600
 601struct AtlasTextureList<T> {
 602    textures: Vec<Option<T>>,
 603    free_list: Vec<usize>,
 604}
 605
 606impl<T> Default for AtlasTextureList<T> {
 607    fn default() -> Self {
 608        Self {
 609            textures: Vec::default(),
 610            free_list: Vec::default(),
 611        }
 612    }
 613}
 614
 615impl<T> ops::Index<usize> for AtlasTextureList<T> {
 616    type Output = Option<T>;
 617
 618    fn index(&self, index: usize) -> &Self::Output {
 619        &self.textures[index]
 620    }
 621}
 622
 623impl<T> AtlasTextureList<T> {
 624    #[allow(unused)]
 625    fn drain(&mut self) -> std::vec::Drain<Option<T>> {
 626        self.free_list.clear();
 627        self.textures.drain(..)
 628    }
 629
 630    #[allow(dead_code)]
 631    fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
 632        self.textures.iter_mut().flatten()
 633    }
 634}
 635
 636#[derive(Clone, Debug, PartialEq, Eq)]
 637#[repr(C)]
 638pub(crate) struct AtlasTile {
 639    pub(crate) texture_id: AtlasTextureId,
 640    pub(crate) tile_id: TileId,
 641    pub(crate) padding: u32,
 642    pub(crate) bounds: Bounds<DevicePixels>,
 643}
 644
 645#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 646#[repr(C)]
 647pub(crate) struct AtlasTextureId {
 648    // We use u32 instead of usize for Metal Shader Language compatibility
 649    pub(crate) index: u32,
 650    pub(crate) kind: AtlasTextureKind,
 651}
 652
 653#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 654#[repr(C)]
 655#[cfg_attr(
 656    all(
 657        any(target_os = "linux", target_os = "freebsd"),
 658        not(any(feature = "x11", feature = "wayland"))
 659    ),
 660    allow(dead_code)
 661)]
 662pub(crate) enum AtlasTextureKind {
 663    Monochrome = 0,
 664    Polychrome = 1,
 665    Path = 2,
 666}
 667
 668#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 669#[repr(C)]
 670pub(crate) struct TileId(pub(crate) u32);
 671
 672impl From<etagere::AllocId> for TileId {
 673    fn from(id: etagere::AllocId) -> Self {
 674        Self(id.serialize())
 675    }
 676}
 677
 678impl From<TileId> for etagere::AllocId {
 679    fn from(id: TileId) -> Self {
 680        Self::deserialize(id.0)
 681    }
 682}
 683
 684pub(crate) struct PlatformInputHandler {
 685    cx: AsyncWindowContext,
 686    handler: Box<dyn InputHandler>,
 687}
 688
 689#[cfg_attr(
 690    all(
 691        any(target_os = "linux", target_os = "freebsd"),
 692        not(any(feature = "x11", feature = "wayland"))
 693    ),
 694    allow(dead_code)
 695)]
 696impl PlatformInputHandler {
 697    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
 698        Self { cx, handler }
 699    }
 700
 701    fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
 702        self.cx
 703            .update(|window, cx| {
 704                self.handler
 705                    .selected_text_range(ignore_disabled_input, window, cx)
 706            })
 707            .ok()
 708            .flatten()
 709    }
 710
 711    fn marked_text_range(&mut self) -> Option<Range<usize>> {
 712        self.cx
 713            .update(|window, cx| self.handler.marked_text_range(window, cx))
 714            .ok()
 715            .flatten()
 716    }
 717
 718    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 719    fn text_for_range(
 720        &mut self,
 721        range_utf16: Range<usize>,
 722        adjusted: &mut Option<Range<usize>>,
 723    ) -> Option<String> {
 724        self.cx
 725            .update(|window, cx| {
 726                self.handler
 727                    .text_for_range(range_utf16, adjusted, window, cx)
 728            })
 729            .ok()
 730            .flatten()
 731    }
 732
 733    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
 734        self.cx
 735            .update(|window, cx| {
 736                self.handler
 737                    .replace_text_in_range(replacement_range, text, window, cx);
 738            })
 739            .ok();
 740    }
 741
 742    fn replace_and_mark_text_in_range(
 743        &mut self,
 744        range_utf16: Option<Range<usize>>,
 745        new_text: &str,
 746        new_selected_range: Option<Range<usize>>,
 747    ) {
 748        self.cx
 749            .update(|window, cx| {
 750                self.handler.replace_and_mark_text_in_range(
 751                    range_utf16,
 752                    new_text,
 753                    new_selected_range,
 754                    window,
 755                    cx,
 756                )
 757            })
 758            .ok();
 759    }
 760
 761    fn unmark_text(&mut self) {
 762        self.cx
 763            .update(|window, cx| self.handler.unmark_text(window, cx))
 764            .ok();
 765    }
 766
 767    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
 768        self.cx
 769            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
 770            .ok()
 771            .flatten()
 772    }
 773
 774    #[allow(dead_code)]
 775    fn apple_press_and_hold_enabled(&mut self) -> bool {
 776        self.handler.apple_press_and_hold_enabled()
 777    }
 778
 779    pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
 780        self.handler.replace_text_in_range(None, input, window, cx);
 781    }
 782
 783    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
 784        let selection = self.handler.selected_text_range(true, window, cx)?;
 785        self.handler.bounds_for_range(
 786            if selection.reversed {
 787                selection.range.start..selection.range.start
 788            } else {
 789                selection.range.end..selection.range.end
 790            },
 791            window,
 792            cx,
 793        )
 794    }
 795}
 796
 797/// A struct representing a selection in a text buffer, in UTF16 characters.
 798/// This is different from a range because the head may be before the tail.
 799#[derive(Debug)]
 800pub struct UTF16Selection {
 801    /// The range of text in the document this selection corresponds to
 802    /// in UTF16 characters.
 803    pub range: Range<usize>,
 804    /// Whether the head of this selection is at the start (true), or end (false)
 805    /// of the range
 806    pub reversed: bool,
 807}
 808
 809/// Zed's interface for handling text input from the platform's IME system
 810/// This is currently a 1:1 exposure of the NSTextInputClient API:
 811///
 812/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
 813pub trait InputHandler: 'static {
 814    /// Get the range of the user's currently selected text, if any
 815    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
 816    ///
 817    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 818    fn selected_text_range(
 819        &mut self,
 820        ignore_disabled_input: bool,
 821        window: &mut Window,
 822        cx: &mut App,
 823    ) -> Option<UTF16Selection>;
 824
 825    /// Get the range of the currently marked text, if any
 826    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
 827    ///
 828    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 829    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
 830
 831    /// Get the text for the given document range in UTF-16 characters
 832    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
 833    ///
 834    /// range_utf16 is in terms of UTF-16 characters
 835    fn text_for_range(
 836        &mut self,
 837        range_utf16: Range<usize>,
 838        adjusted_range: &mut Option<Range<usize>>,
 839        window: &mut Window,
 840        cx: &mut App,
 841    ) -> Option<String>;
 842
 843    /// Replace the text in the given document range with the given text
 844    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
 845    ///
 846    /// replacement_range is in terms of UTF-16 characters
 847    fn replace_text_in_range(
 848        &mut self,
 849        replacement_range: Option<Range<usize>>,
 850        text: &str,
 851        window: &mut Window,
 852        cx: &mut App,
 853    );
 854
 855    /// Replace the text in the given document range with the given text,
 856    /// and mark the given text as part of an IME 'composing' state
 857    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
 858    ///
 859    /// range_utf16 is in terms of UTF-16 characters
 860    /// new_selected_range is in terms of UTF-16 characters
 861    fn replace_and_mark_text_in_range(
 862        &mut self,
 863        range_utf16: Option<Range<usize>>,
 864        new_text: &str,
 865        new_selected_range: Option<Range<usize>>,
 866        window: &mut Window,
 867        cx: &mut App,
 868    );
 869
 870    /// Remove the IME 'composing' state from the document
 871    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
 872    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
 873
 874    /// Get the bounds of the given document range in screen coordinates
 875    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
 876    ///
 877    /// This is used for positioning the IME candidate window
 878    fn bounds_for_range(
 879        &mut self,
 880        range_utf16: Range<usize>,
 881        window: &mut Window,
 882        cx: &mut App,
 883    ) -> Option<Bounds<Pixels>>;
 884
 885    /// Allows a given input context to opt into getting raw key repeats instead of
 886    /// sending these to the platform.
 887    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
 888    /// (which is how iTerm does it) but it doesn't seem to work for me.
 889    #[allow(dead_code)]
 890    fn apple_press_and_hold_enabled(&mut self) -> bool {
 891        true
 892    }
 893}
 894
 895/// The variables that can be configured when creating a new window
 896#[derive(Debug)]
 897pub struct WindowOptions {
 898    /// Specifies the state and bounds of the window in screen coordinates.
 899    /// - `None`: Inherit the bounds.
 900    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
 901    pub window_bounds: Option<WindowBounds>,
 902
 903    /// The titlebar configuration of the window
 904    pub titlebar: Option<TitlebarOptions>,
 905
 906    /// Whether the window should be focused when created
 907    pub focus: bool,
 908
 909    /// Whether the window should be shown when created
 910    pub show: bool,
 911
 912    /// The kind of window to create
 913    pub kind: WindowKind,
 914
 915    /// Whether the window should be movable by the user
 916    pub is_movable: bool,
 917
 918    /// The display to create the window on, if this is None,
 919    /// the window will be created on the main display
 920    pub display_id: Option<DisplayId>,
 921
 922    /// The appearance of the window background.
 923    pub window_background: WindowBackgroundAppearance,
 924
 925    /// Application identifier of the window. Can by used by desktop environments to group applications together.
 926    pub app_id: Option<String>,
 927
 928    /// Window minimum size
 929    pub window_min_size: Option<Size<Pixels>>,
 930
 931    /// Whether to use client or server side decorations. Wayland only
 932    /// Note that this may be ignored.
 933    pub window_decorations: Option<WindowDecorations>,
 934}
 935
 936/// The variables that can be configured when creating a new window
 937#[derive(Debug)]
 938#[cfg_attr(
 939    all(
 940        any(target_os = "linux", target_os = "freebsd"),
 941        not(any(feature = "x11", feature = "wayland"))
 942    ),
 943    allow(dead_code)
 944)]
 945pub(crate) struct WindowParams {
 946    pub bounds: Bounds<Pixels>,
 947
 948    /// The titlebar configuration of the window
 949    #[cfg_attr(feature = "wayland", allow(dead_code))]
 950    pub titlebar: Option<TitlebarOptions>,
 951
 952    /// The kind of window to create
 953    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 954    pub kind: WindowKind,
 955
 956    /// Whether the window should be movable by the user
 957    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 958    pub is_movable: bool,
 959
 960    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 961    pub focus: bool,
 962
 963    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
 964    pub show: bool,
 965
 966    #[cfg_attr(feature = "wayland", allow(dead_code))]
 967    pub display_id: Option<DisplayId>,
 968
 969    pub window_min_size: Option<Size<Pixels>>,
 970}
 971
 972/// Represents the status of how a window should be opened.
 973#[derive(Debug, Copy, Clone, PartialEq)]
 974pub enum WindowBounds {
 975    /// Indicates that the window should open in a windowed state with the given bounds.
 976    Windowed(Bounds<Pixels>),
 977    /// Indicates that the window should open in a maximized state.
 978    /// The bounds provided here represent the restore size of the window.
 979    Maximized(Bounds<Pixels>),
 980    /// Indicates that the window should open in fullscreen mode.
 981    /// The bounds provided here represent the restore size of the window.
 982    Fullscreen(Bounds<Pixels>),
 983}
 984
 985impl Default for WindowBounds {
 986    fn default() -> Self {
 987        WindowBounds::Windowed(Bounds::default())
 988    }
 989}
 990
 991impl WindowBounds {
 992    /// Retrieve the inner bounds
 993    pub fn get_bounds(&self) -> Bounds<Pixels> {
 994        match self {
 995            WindowBounds::Windowed(bounds) => *bounds,
 996            WindowBounds::Maximized(bounds) => *bounds,
 997            WindowBounds::Fullscreen(bounds) => *bounds,
 998        }
 999    }
1000}
1001
1002impl Default for WindowOptions {
1003    fn default() -> Self {
1004        Self {
1005            window_bounds: None,
1006            titlebar: Some(TitlebarOptions {
1007                title: Default::default(),
1008                appears_transparent: Default::default(),
1009                traffic_light_position: Default::default(),
1010            }),
1011            focus: true,
1012            show: true,
1013            kind: WindowKind::Normal,
1014            is_movable: true,
1015            display_id: None,
1016            window_background: WindowBackgroundAppearance::default(),
1017            app_id: None,
1018            window_min_size: None,
1019            window_decorations: None,
1020        }
1021    }
1022}
1023
1024/// The options that can be configured for a window's titlebar
1025#[derive(Debug, Default)]
1026pub struct TitlebarOptions {
1027    /// The initial title of the window
1028    pub title: Option<SharedString>,
1029
1030    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
1031    /// Refer to [`WindowOptions::window_decorations`] on Linux
1032    pub appears_transparent: bool,
1033
1034    /// The position of the macOS traffic light buttons
1035    pub traffic_light_position: Option<Point<Pixels>>,
1036}
1037
1038/// The kind of window to create
1039#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1040pub enum WindowKind {
1041    /// A normal application window
1042    Normal,
1043
1044    /// A window that appears above all other windows, usually used for alerts or popups
1045    /// use sparingly!
1046    PopUp,
1047}
1048
1049/// The appearance of the window, as defined by the operating system.
1050///
1051/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
1052/// values.
1053#[derive(Copy, Clone, Debug)]
1054pub enum WindowAppearance {
1055    /// A light appearance.
1056    ///
1057    /// On macOS, this corresponds to the `aqua` appearance.
1058    Light,
1059
1060    /// A light appearance with vibrant colors.
1061    ///
1062    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
1063    VibrantLight,
1064
1065    /// A dark appearance.
1066    ///
1067    /// On macOS, this corresponds to the `darkAqua` appearance.
1068    Dark,
1069
1070    /// A dark appearance with vibrant colors.
1071    ///
1072    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
1073    VibrantDark,
1074}
1075
1076impl Default for WindowAppearance {
1077    fn default() -> Self {
1078        Self::Light
1079    }
1080}
1081
1082/// The appearance of the background of the window itself, when there is
1083/// no content or the content is transparent.
1084#[derive(Copy, Clone, Debug, Default, PartialEq)]
1085pub enum WindowBackgroundAppearance {
1086    /// Opaque.
1087    ///
1088    /// This lets the window manager know that content behind this
1089    /// window does not need to be drawn.
1090    ///
1091    /// Actual color depends on the system and themes should define a fully
1092    /// opaque background color instead.
1093    #[default]
1094    Opaque,
1095    /// Plain alpha transparency.
1096    Transparent,
1097    /// Transparency, but the contents behind the window are blurred.
1098    ///
1099    /// Not always supported.
1100    Blurred,
1101}
1102
1103/// The options that can be configured for a file dialog prompt
1104#[derive(Copy, Clone, Debug)]
1105pub struct PathPromptOptions {
1106    /// Should the prompt allow files to be selected?
1107    pub files: bool,
1108    /// Should the prompt allow directories to be selected?
1109    pub directories: bool,
1110    /// Should the prompt allow multiple files to be selected?
1111    pub multiple: bool,
1112}
1113
1114/// What kind of prompt styling to show
1115#[derive(Copy, Clone, Debug, PartialEq)]
1116pub enum PromptLevel {
1117    /// A prompt that is shown when the user should be notified of something
1118    Info,
1119
1120    /// A prompt that is shown when the user needs to be warned of a potential problem
1121    Warning,
1122
1123    /// A prompt that is shown when a critical problem has occurred
1124    Critical,
1125}
1126
1127/// The style of the cursor (pointer)
1128#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1129pub enum CursorStyle {
1130    /// The default cursor
1131    Arrow,
1132
1133    /// A text input cursor
1134    /// corresponds to the CSS cursor value `text`
1135    IBeam,
1136
1137    /// A crosshair cursor
1138    /// corresponds to the CSS cursor value `crosshair`
1139    Crosshair,
1140
1141    /// A closed hand cursor
1142    /// corresponds to the CSS cursor value `grabbing`
1143    ClosedHand,
1144
1145    /// An open hand cursor
1146    /// corresponds to the CSS cursor value `grab`
1147    OpenHand,
1148
1149    /// A pointing hand cursor
1150    /// corresponds to the CSS cursor value `pointer`
1151    PointingHand,
1152
1153    /// A resize left cursor
1154    /// corresponds to the CSS cursor value `w-resize`
1155    ResizeLeft,
1156
1157    /// A resize right cursor
1158    /// corresponds to the CSS cursor value `e-resize`
1159    ResizeRight,
1160
1161    /// A resize cursor to the left and right
1162    /// corresponds to the CSS cursor value `ew-resize`
1163    ResizeLeftRight,
1164
1165    /// A resize up cursor
1166    /// corresponds to the CSS cursor value `n-resize`
1167    ResizeUp,
1168
1169    /// A resize down cursor
1170    /// corresponds to the CSS cursor value `s-resize`
1171    ResizeDown,
1172
1173    /// A resize cursor directing up and down
1174    /// corresponds to the CSS cursor value `ns-resize`
1175    ResizeUpDown,
1176
1177    /// A resize cursor directing up-left and down-right
1178    /// corresponds to the CSS cursor value `nesw-resize`
1179    ResizeUpLeftDownRight,
1180
1181    /// A resize cursor directing up-right and down-left
1182    /// corresponds to the CSS cursor value `nwse-resize`
1183    ResizeUpRightDownLeft,
1184
1185    /// A cursor indicating that the item/column can be resized horizontally.
1186    /// corresponds to the CSS cursor value `col-resize`
1187    ResizeColumn,
1188
1189    /// A cursor indicating that the item/row can be resized vertically.
1190    /// corresponds to the CSS cursor value `row-resize`
1191    ResizeRow,
1192
1193    /// A text input cursor for vertical layout
1194    /// corresponds to the CSS cursor value `vertical-text`
1195    IBeamCursorForVerticalLayout,
1196
1197    /// A cursor indicating that the operation is not allowed
1198    /// corresponds to the CSS cursor value `not-allowed`
1199    OperationNotAllowed,
1200
1201    /// A cursor indicating that the operation will result in a link
1202    /// corresponds to the CSS cursor value `alias`
1203    DragLink,
1204
1205    /// A cursor indicating that the operation will result in a copy
1206    /// corresponds to the CSS cursor value `copy`
1207    DragCopy,
1208
1209    /// A cursor indicating that the operation will result in a context menu
1210    /// corresponds to the CSS cursor value `context-menu`
1211    ContextualMenu,
1212}
1213
1214impl Default for CursorStyle {
1215    fn default() -> Self {
1216        Self::Arrow
1217    }
1218}
1219
1220/// A clipboard item that should be copied to the clipboard
1221#[derive(Clone, Debug, Eq, PartialEq)]
1222pub struct ClipboardItem {
1223    entries: Vec<ClipboardEntry>,
1224}
1225
1226/// Either a ClipboardString or a ClipboardImage
1227#[derive(Clone, Debug, Eq, PartialEq)]
1228pub enum ClipboardEntry {
1229    /// A string entry
1230    String(ClipboardString),
1231    /// An image entry
1232    Image(Image),
1233}
1234
1235impl ClipboardItem {
1236    /// Create a new ClipboardItem::String with no associated metadata
1237    pub fn new_string(text: String) -> Self {
1238        Self {
1239            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1240        }
1241    }
1242
1243    /// Create a new ClipboardItem::String with the given text and associated metadata
1244    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1245        Self {
1246            entries: vec![ClipboardEntry::String(ClipboardString {
1247                text,
1248                metadata: Some(metadata),
1249            })],
1250        }
1251    }
1252
1253    /// Create a new ClipboardItem::String with the given text and associated metadata
1254    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1255        Self {
1256            entries: vec![ClipboardEntry::String(
1257                ClipboardString::new(text).with_json_metadata(metadata),
1258            )],
1259        }
1260    }
1261
1262    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1263    pub fn new_image(image: &Image) -> Self {
1264        Self {
1265            entries: vec![ClipboardEntry::Image(image.clone())],
1266        }
1267    }
1268
1269    /// Concatenates together all the ClipboardString entries in the item.
1270    /// Returns None if there were no ClipboardString entries.
1271    pub fn text(&self) -> Option<String> {
1272        let mut answer = String::new();
1273        let mut any_entries = false;
1274
1275        for entry in self.entries.iter() {
1276            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1277                answer.push_str(&text);
1278                any_entries = true;
1279            }
1280        }
1281
1282        if any_entries {
1283            Some(answer)
1284        } else {
1285            None
1286        }
1287    }
1288
1289    /// If this item is one ClipboardEntry::String, returns its metadata.
1290    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1291    pub fn metadata(&self) -> Option<&String> {
1292        match self.entries().first() {
1293            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1294                clipboard_string.metadata.as_ref()
1295            }
1296            _ => None,
1297        }
1298    }
1299
1300    /// Get the item's entries
1301    pub fn entries(&self) -> &[ClipboardEntry] {
1302        &self.entries
1303    }
1304
1305    /// Get owned versions of the item's entries
1306    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1307        self.entries.into_iter()
1308    }
1309}
1310
1311/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1312#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1313pub enum ImageFormat {
1314    // Sorted from most to least likely to be pasted into an editor,
1315    // which matters when we iterate through them trying to see if
1316    // clipboard content matches them.
1317    /// .png
1318    Png,
1319    /// .jpeg or .jpg
1320    Jpeg,
1321    /// .webp
1322    Webp,
1323    /// .gif
1324    Gif,
1325    /// .svg
1326    Svg,
1327    /// .bmp
1328    Bmp,
1329    /// .tif or .tiff
1330    Tiff,
1331}
1332
1333/// An image, with a format and certain bytes
1334#[derive(Clone, Debug, PartialEq, Eq)]
1335pub struct Image {
1336    /// The image format the bytes represent (e.g. PNG)
1337    pub format: ImageFormat,
1338    /// The raw image bytes
1339    pub bytes: Vec<u8>,
1340    /// The unique ID for the image
1341    pub id: u64,
1342}
1343
1344impl Hash for Image {
1345    fn hash<H: Hasher>(&self, state: &mut H) {
1346        state.write_u64(self.id);
1347    }
1348}
1349
1350impl Image {
1351    /// Get this image's ID
1352    pub fn id(&self) -> u64 {
1353        self.id
1354    }
1355
1356    /// Use the GPUI `use_asset` API to make this image renderable
1357    pub fn use_render_image(
1358        self: Arc<Self>,
1359        window: &mut Window,
1360        cx: &mut App,
1361    ) -> Option<Arc<RenderImage>> {
1362        ImageSource::Image(self)
1363            .use_data(window, cx)
1364            .and_then(|result| result.ok())
1365    }
1366
1367    /// Convert the clipboard image to an `ImageData` object.
1368    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1369        fn frames_for_image(
1370            bytes: &[u8],
1371            format: image::ImageFormat,
1372        ) -> Result<SmallVec<[Frame; 1]>> {
1373            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1374
1375            // Convert from RGBA to BGRA.
1376            for pixel in data.chunks_exact_mut(4) {
1377                pixel.swap(0, 2);
1378            }
1379
1380            Ok(SmallVec::from_elem(Frame::new(data), 1))
1381        }
1382
1383        let frames = match self.format {
1384            ImageFormat::Gif => {
1385                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1386                let mut frames = SmallVec::new();
1387
1388                for frame in decoder.into_frames() {
1389                    let mut frame = frame?;
1390                    // Convert from RGBA to BGRA.
1391                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1392                        pixel.swap(0, 2);
1393                    }
1394                    frames.push(frame);
1395                }
1396
1397                frames
1398            }
1399            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1400            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1401            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1402            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1403            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1404            ImageFormat::Svg => {
1405                let pixmap = svg_renderer.render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1406
1407                let buffer =
1408                    image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1409                        .unwrap();
1410
1411                SmallVec::from_elem(Frame::new(buffer), 1)
1412            }
1413        };
1414
1415        Ok(Arc::new(RenderImage::new(frames)))
1416    }
1417
1418    /// Get the format of the clipboard image
1419    pub fn format(&self) -> ImageFormat {
1420        self.format
1421    }
1422
1423    /// Get the raw bytes of the clipboard image
1424    pub fn bytes(&self) -> &[u8] {
1425        self.bytes.as_slice()
1426    }
1427}
1428
1429/// A clipboard item that should be copied to the clipboard
1430#[derive(Clone, Debug, Eq, PartialEq)]
1431pub struct ClipboardString {
1432    pub(crate) text: String,
1433    pub(crate) metadata: Option<String>,
1434}
1435
1436impl ClipboardString {
1437    /// Create a new clipboard string with the given text
1438    pub fn new(text: String) -> Self {
1439        Self {
1440            text,
1441            metadata: None,
1442        }
1443    }
1444
1445    /// Return a new clipboard item with the metadata replaced by the given metadata,
1446    /// after serializing it as JSON.
1447    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1448        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1449        self
1450    }
1451
1452    /// Get the text of the clipboard string
1453    pub fn text(&self) -> &String {
1454        &self.text
1455    }
1456
1457    /// Get the owned text of the clipboard string
1458    pub fn into_text(self) -> String {
1459        self.text
1460    }
1461
1462    /// Get the metadata of the clipboard string, formatted as JSON
1463    pub fn metadata_json<T>(&self) -> Option<T>
1464    where
1465        T: for<'a> Deserialize<'a>,
1466    {
1467        self.metadata
1468            .as_ref()
1469            .and_then(|m| serde_json::from_str(m).ok())
1470    }
1471
1472    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1473    pub(crate) fn text_hash(text: &str) -> u64 {
1474        let mut hasher = SeaHasher::new();
1475        text.hash(&mut hasher);
1476        hasher.finish()
1477    }
1478}