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