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