platform.rs

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