platform.rs

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