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