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