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, SystemWindowTab, Task,
  44    TaskLabel, Window, 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 get_title(&self) -> String {
 506        String::new()
 507    }
 508    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
 509        None
 510    }
 511    fn tab_bar_visible(&self) -> bool {
 512        false
 513    }
 514    fn set_edited(&mut self, _edited: bool) {}
 515    fn show_character_palette(&self) {}
 516    fn titlebar_double_click(&self) {}
 517    fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
 518    fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
 519    fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
 520    fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
 521    fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
 522    fn merge_all_windows(&self) {}
 523    fn move_tab_to_new_window(&self) {}
 524    fn toggle_window_tab_overview(&self) {}
 525
 526    #[cfg(target_os = "windows")]
 527    fn get_raw_handle(&self) -> windows::HWND;
 528
 529    // Linux specific methods
 530    fn inner_window_bounds(&self) -> WindowBounds {
 531        self.window_bounds()
 532    }
 533    fn request_decorations(&self, _decorations: WindowDecorations) {}
 534    fn show_window_menu(&self, _position: Point<Pixels>) {}
 535    fn start_window_move(&self) {}
 536    fn start_window_resize(&self, _edge: ResizeEdge) {}
 537    fn window_decorations(&self) -> Decorations {
 538        Decorations::Server
 539    }
 540    fn set_app_id(&mut self, _app_id: &str) {}
 541    fn map_window(&mut self) -> anyhow::Result<()> {
 542        Ok(())
 543    }
 544    fn window_controls(&self) -> WindowControls {
 545        WindowControls::default()
 546    }
 547    fn set_client_inset(&self, _inset: Pixels) {}
 548    fn gpu_specs(&self) -> Option<GpuSpecs>;
 549
 550    fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>);
 551
 552    #[cfg(any(test, feature = "test-support"))]
 553    fn as_test(&mut self) -> Option<&mut TestWindow> {
 554        None
 555    }
 556}
 557
 558/// This type is public so that our test macro can generate and use it, but it should not
 559/// be considered part of our public API.
 560#[doc(hidden)]
 561pub trait PlatformDispatcher: Send + Sync {
 562    fn is_main_thread(&self) -> bool;
 563    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
 564    fn dispatch_on_main_thread(&self, runnable: Runnable);
 565    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
 566    fn park(&self, timeout: Option<Duration>) -> bool;
 567    fn unparker(&self) -> Unparker;
 568    fn now(&self) -> Instant {
 569        Instant::now()
 570    }
 571
 572    #[cfg(any(test, feature = "test-support"))]
 573    fn as_test(&self) -> Option<&TestDispatcher> {
 574        None
 575    }
 576}
 577
 578pub(crate) trait PlatformTextSystem: Send + Sync {
 579    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
 580    fn all_font_names(&self) -> Vec<String>;
 581    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
 582    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
 583    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
 584    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
 585    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
 586    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
 587    fn rasterize_glyph(
 588        &self,
 589        params: &RenderGlyphParams,
 590        raster_bounds: Bounds<DevicePixels>,
 591    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
 592    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
 593}
 594
 595pub(crate) struct NoopTextSystem;
 596
 597impl NoopTextSystem {
 598    #[allow(dead_code)]
 599    pub fn new() -> Self {
 600        Self
 601    }
 602}
 603
 604impl PlatformTextSystem for NoopTextSystem {
 605    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 606        Ok(())
 607    }
 608
 609    fn all_font_names(&self) -> Vec<String> {
 610        Vec::new()
 611    }
 612
 613    fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
 614        Ok(FontId(1))
 615    }
 616
 617    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
 618        FontMetrics {
 619            units_per_em: 1000,
 620            ascent: 1025.0,
 621            descent: -275.0,
 622            line_gap: 0.0,
 623            underline_position: -95.0,
 624            underline_thickness: 60.0,
 625            cap_height: 698.0,
 626            x_height: 516.0,
 627            bounding_box: Bounds {
 628                origin: Point {
 629                    x: -260.0,
 630                    y: -245.0,
 631                },
 632                size: Size {
 633                    width: 1501.0,
 634                    height: 1364.0,
 635                },
 636            },
 637        }
 638    }
 639
 640    fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
 641        Ok(Bounds {
 642            origin: Point { x: 54.0, y: 0.0 },
 643            size: size(392.0, 528.0),
 644        })
 645    }
 646
 647    fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
 648        Ok(size(600.0 * glyph_id.0 as f32, 0.0))
 649    }
 650
 651    fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
 652        Some(GlyphId(ch.len_utf16() as u32))
 653    }
 654
 655    fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 656        Ok(Default::default())
 657    }
 658
 659    fn rasterize_glyph(
 660        &self,
 661        _params: &RenderGlyphParams,
 662        raster_bounds: Bounds<DevicePixels>,
 663    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 664        Ok((raster_bounds.size, Vec::new()))
 665    }
 666
 667    fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
 668        let mut position = px(0.);
 669        let metrics = self.font_metrics(FontId(0));
 670        let em_width = font_size
 671            * self
 672                .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
 673                .unwrap()
 674                .width
 675            / metrics.units_per_em as f32;
 676        let mut glyphs = Vec::new();
 677        for (ix, c) in text.char_indices() {
 678            if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
 679                glyphs.push(ShapedGlyph {
 680                    id: glyph,
 681                    position: point(position, px(0.)),
 682                    index: ix,
 683                    is_emoji: glyph.0 == 2,
 684                });
 685                if glyph.0 == 2 {
 686                    position += em_width * 2.0;
 687                } else {
 688                    position += em_width;
 689                }
 690            } else {
 691                position += em_width
 692            }
 693        }
 694        let mut runs = Vec::default();
 695        if !glyphs.is_empty() {
 696            runs.push(ShapedRun {
 697                font_id: FontId(0),
 698                glyphs,
 699            });
 700        } else {
 701            position = px(0.);
 702        }
 703
 704        LineLayout {
 705            font_size,
 706            width: position,
 707            ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
 708            descent: font_size * (metrics.descent / metrics.units_per_em as f32),
 709            runs,
 710            len: text.len(),
 711        }
 712    }
 713}
 714
 715#[derive(PartialEq, Eq, Hash, Clone)]
 716pub(crate) enum AtlasKey {
 717    Glyph(RenderGlyphParams),
 718    Svg(RenderSvgParams),
 719    Image(RenderImageParams),
 720}
 721
 722impl AtlasKey {
 723    #[cfg_attr(
 724        all(
 725            any(target_os = "linux", target_os = "freebsd"),
 726            not(any(feature = "x11", feature = "wayland"))
 727        ),
 728        allow(dead_code)
 729    )]
 730    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
 731        match self {
 732            AtlasKey::Glyph(params) => {
 733                if params.is_emoji {
 734                    AtlasTextureKind::Polychrome
 735                } else {
 736                    AtlasTextureKind::Monochrome
 737                }
 738            }
 739            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
 740            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
 741        }
 742    }
 743}
 744
 745impl From<RenderGlyphParams> for AtlasKey {
 746    fn from(params: RenderGlyphParams) -> Self {
 747        Self::Glyph(params)
 748    }
 749}
 750
 751impl From<RenderSvgParams> for AtlasKey {
 752    fn from(params: RenderSvgParams) -> Self {
 753        Self::Svg(params)
 754    }
 755}
 756
 757impl From<RenderImageParams> for AtlasKey {
 758    fn from(params: RenderImageParams) -> Self {
 759        Self::Image(params)
 760    }
 761}
 762
 763pub(crate) trait PlatformAtlas: Send + Sync {
 764    fn get_or_insert_with<'a>(
 765        &self,
 766        key: &AtlasKey,
 767        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 768    ) -> Result<Option<AtlasTile>>;
 769    fn remove(&self, key: &AtlasKey);
 770}
 771
 772struct AtlasTextureList<T> {
 773    textures: Vec<Option<T>>,
 774    free_list: Vec<usize>,
 775}
 776
 777impl<T> Default for AtlasTextureList<T> {
 778    fn default() -> Self {
 779        Self {
 780            textures: Vec::default(),
 781            free_list: Vec::default(),
 782        }
 783    }
 784}
 785
 786impl<T> ops::Index<usize> for AtlasTextureList<T> {
 787    type Output = Option<T>;
 788
 789    fn index(&self, index: usize) -> &Self::Output {
 790        &self.textures[index]
 791    }
 792}
 793
 794impl<T> AtlasTextureList<T> {
 795    #[allow(unused)]
 796    fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
 797        self.free_list.clear();
 798        self.textures.drain(..)
 799    }
 800
 801    #[allow(dead_code)]
 802    fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
 803        self.textures.iter_mut().flatten()
 804    }
 805}
 806
 807#[derive(Clone, Debug, PartialEq, Eq)]
 808#[repr(C)]
 809pub(crate) struct AtlasTile {
 810    pub(crate) texture_id: AtlasTextureId,
 811    pub(crate) tile_id: TileId,
 812    pub(crate) padding: u32,
 813    pub(crate) bounds: Bounds<DevicePixels>,
 814}
 815
 816#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 817#[repr(C)]
 818pub(crate) struct AtlasTextureId {
 819    // We use u32 instead of usize for Metal Shader Language compatibility
 820    pub(crate) index: u32,
 821    pub(crate) kind: AtlasTextureKind,
 822}
 823
 824#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 825#[repr(C)]
 826#[cfg_attr(
 827    all(
 828        any(target_os = "linux", target_os = "freebsd"),
 829        not(any(feature = "x11", feature = "wayland"))
 830    ),
 831    allow(dead_code)
 832)]
 833pub(crate) enum AtlasTextureKind {
 834    Monochrome = 0,
 835    Polychrome = 1,
 836}
 837
 838#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 839#[repr(C)]
 840pub(crate) struct TileId(pub(crate) u32);
 841
 842impl From<etagere::AllocId> for TileId {
 843    fn from(id: etagere::AllocId) -> Self {
 844        Self(id.serialize())
 845    }
 846}
 847
 848impl From<TileId> for etagere::AllocId {
 849    fn from(id: TileId) -> Self {
 850        Self::deserialize(id.0)
 851    }
 852}
 853
 854pub(crate) struct PlatformInputHandler {
 855    cx: AsyncWindowContext,
 856    handler: Box<dyn InputHandler>,
 857}
 858
 859#[cfg_attr(
 860    all(
 861        any(target_os = "linux", target_os = "freebsd"),
 862        not(any(feature = "x11", feature = "wayland"))
 863    ),
 864    allow(dead_code)
 865)]
 866impl PlatformInputHandler {
 867    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
 868        Self { cx, handler }
 869    }
 870
 871    fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
 872        self.cx
 873            .update(|window, cx| {
 874                self.handler
 875                    .selected_text_range(ignore_disabled_input, window, cx)
 876            })
 877            .ok()
 878            .flatten()
 879    }
 880
 881    #[cfg_attr(target_os = "windows", allow(dead_code))]
 882    fn marked_text_range(&mut self) -> Option<Range<usize>> {
 883        self.cx
 884            .update(|window, cx| self.handler.marked_text_range(window, cx))
 885            .ok()
 886            .flatten()
 887    }
 888
 889    #[cfg_attr(
 890        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
 891        allow(dead_code)
 892    )]
 893    fn text_for_range(
 894        &mut self,
 895        range_utf16: Range<usize>,
 896        adjusted: &mut Option<Range<usize>>,
 897    ) -> Option<String> {
 898        self.cx
 899            .update(|window, cx| {
 900                self.handler
 901                    .text_for_range(range_utf16, adjusted, window, cx)
 902            })
 903            .ok()
 904            .flatten()
 905    }
 906
 907    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
 908        self.cx
 909            .update(|window, cx| {
 910                self.handler
 911                    .replace_text_in_range(replacement_range, text, window, cx);
 912            })
 913            .ok();
 914    }
 915
 916    pub fn replace_and_mark_text_in_range(
 917        &mut self,
 918        range_utf16: Option<Range<usize>>,
 919        new_text: &str,
 920        new_selected_range: Option<Range<usize>>,
 921    ) {
 922        self.cx
 923            .update(|window, cx| {
 924                self.handler.replace_and_mark_text_in_range(
 925                    range_utf16,
 926                    new_text,
 927                    new_selected_range,
 928                    window,
 929                    cx,
 930                )
 931            })
 932            .ok();
 933    }
 934
 935    #[cfg_attr(target_os = "windows", allow(dead_code))]
 936    fn unmark_text(&mut self) {
 937        self.cx
 938            .update(|window, cx| self.handler.unmark_text(window, cx))
 939            .ok();
 940    }
 941
 942    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
 943        self.cx
 944            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
 945            .ok()
 946            .flatten()
 947    }
 948
 949    #[allow(dead_code)]
 950    fn apple_press_and_hold_enabled(&mut self) -> bool {
 951        self.handler.apple_press_and_hold_enabled()
 952    }
 953
 954    pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
 955        self.handler.replace_text_in_range(None, input, window, cx);
 956    }
 957
 958    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
 959        let selection = self.handler.selected_text_range(true, window, cx)?;
 960        self.handler.bounds_for_range(
 961            if selection.reversed {
 962                selection.range.start..selection.range.start
 963            } else {
 964                selection.range.end..selection.range.end
 965            },
 966            window,
 967            cx,
 968        )
 969    }
 970
 971    #[allow(unused)]
 972    pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
 973        self.cx
 974            .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
 975            .ok()
 976            .flatten()
 977    }
 978}
 979
 980/// A struct representing a selection in a text buffer, in UTF16 characters.
 981/// This is different from a range because the head may be before the tail.
 982#[derive(Debug)]
 983pub struct UTF16Selection {
 984    /// The range of text in the document this selection corresponds to
 985    /// in UTF16 characters.
 986    pub range: Range<usize>,
 987    /// Whether the head of this selection is at the start (true), or end (false)
 988    /// of the range
 989    pub reversed: bool,
 990}
 991
 992/// Zed's interface for handling text input from the platform's IME system
 993/// This is currently a 1:1 exposure of the NSTextInputClient API:
 994///
 995/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
 996pub trait InputHandler: 'static {
 997    /// Get the range of the user's currently selected text, if any
 998    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
 999    ///
1000    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1001    fn selected_text_range(
1002        &mut self,
1003        ignore_disabled_input: bool,
1004        window: &mut Window,
1005        cx: &mut App,
1006    ) -> Option<UTF16Selection>;
1007
1008    /// Get the range of the currently marked text, if any
1009    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
1010    ///
1011    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1012    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
1013
1014    /// Get the text for the given document range in UTF-16 characters
1015    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
1016    ///
1017    /// range_utf16 is in terms of UTF-16 characters
1018    fn text_for_range(
1019        &mut self,
1020        range_utf16: Range<usize>,
1021        adjusted_range: &mut Option<Range<usize>>,
1022        window: &mut Window,
1023        cx: &mut App,
1024    ) -> Option<String>;
1025
1026    /// Replace the text in the given document range with the given text
1027    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
1028    ///
1029    /// replacement_range is in terms of UTF-16 characters
1030    fn replace_text_in_range(
1031        &mut self,
1032        replacement_range: Option<Range<usize>>,
1033        text: &str,
1034        window: &mut Window,
1035        cx: &mut App,
1036    );
1037
1038    /// Replace the text in the given document range with the given text,
1039    /// and mark the given text as part of an IME 'composing' state
1040    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
1041    ///
1042    /// range_utf16 is in terms of UTF-16 characters
1043    /// new_selected_range is in terms of UTF-16 characters
1044    fn replace_and_mark_text_in_range(
1045        &mut self,
1046        range_utf16: Option<Range<usize>>,
1047        new_text: &str,
1048        new_selected_range: Option<Range<usize>>,
1049        window: &mut Window,
1050        cx: &mut App,
1051    );
1052
1053    /// Remove the IME 'composing' state from the document
1054    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
1055    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
1056
1057    /// Get the bounds of the given document range in screen coordinates
1058    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
1059    ///
1060    /// This is used for positioning the IME candidate window
1061    fn bounds_for_range(
1062        &mut self,
1063        range_utf16: Range<usize>,
1064        window: &mut Window,
1065        cx: &mut App,
1066    ) -> Option<Bounds<Pixels>>;
1067
1068    /// Get the character offset for the given point in terms of UTF16 characters
1069    ///
1070    /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
1071    fn character_index_for_point(
1072        &mut self,
1073        point: Point<Pixels>,
1074        window: &mut Window,
1075        cx: &mut App,
1076    ) -> Option<usize>;
1077
1078    /// Allows a given input context to opt into getting raw key repeats instead of
1079    /// sending these to the platform.
1080    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1081    /// (which is how iTerm does it) but it doesn't seem to work for me.
1082    #[allow(dead_code)]
1083    fn apple_press_and_hold_enabled(&mut self) -> bool {
1084        true
1085    }
1086}
1087
1088/// The variables that can be configured when creating a new window
1089#[derive(Debug)]
1090pub struct WindowOptions {
1091    /// Specifies the state and bounds of the window in screen coordinates.
1092    /// - `None`: Inherit the bounds.
1093    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1094    pub window_bounds: Option<WindowBounds>,
1095
1096    /// The titlebar configuration of the window
1097    pub titlebar: Option<TitlebarOptions>,
1098
1099    /// Whether the window should be focused when created
1100    pub focus: bool,
1101
1102    /// Whether the window should be shown when created
1103    pub show: bool,
1104
1105    /// The kind of window to create
1106    pub kind: WindowKind,
1107
1108    /// Whether the window should be movable by the user
1109    pub is_movable: bool,
1110
1111    /// Whether the window should be resizable by the user
1112    pub is_resizable: bool,
1113
1114    /// Whether the window should be minimized by the user
1115    pub is_minimizable: bool,
1116
1117    /// The display to create the window on, if this is None,
1118    /// the window will be created on the main display
1119    pub display_id: Option<DisplayId>,
1120
1121    /// The appearance of the window background.
1122    pub window_background: WindowBackgroundAppearance,
1123
1124    /// Application identifier of the window. Can by used by desktop environments to group applications together.
1125    pub app_id: Option<String>,
1126
1127    /// Window minimum size
1128    pub window_min_size: Option<Size<Pixels>>,
1129
1130    /// Whether to use client or server side decorations. Wayland only
1131    /// Note that this may be ignored.
1132    pub window_decorations: Option<WindowDecorations>,
1133
1134    /// Tab group name, allows opening the window as a native tab on macOS 10.12+. Windows with the same tabbing identifier will be grouped together.
1135    pub tabbing_identifier: Option<String>,
1136}
1137
1138/// The variables that can be configured when creating a new window
1139#[derive(Debug)]
1140#[cfg_attr(
1141    all(
1142        any(target_os = "linux", target_os = "freebsd"),
1143        not(any(feature = "x11", feature = "wayland"))
1144    ),
1145    allow(dead_code)
1146)]
1147pub(crate) struct WindowParams {
1148    pub bounds: Bounds<Pixels>,
1149
1150    /// The titlebar configuration of the window
1151    #[cfg_attr(feature = "wayland", allow(dead_code))]
1152    pub titlebar: Option<TitlebarOptions>,
1153
1154    /// The kind of window to create
1155    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1156    pub kind: WindowKind,
1157
1158    /// Whether the window should be movable by the user
1159    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1160    pub is_movable: bool,
1161
1162    /// Whether the window should be resizable by the user
1163    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1164    pub is_resizable: bool,
1165
1166    /// Whether the window should be minimized by the user
1167    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1168    pub is_minimizable: bool,
1169
1170    #[cfg_attr(
1171        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1172        allow(dead_code)
1173    )]
1174    pub focus: bool,
1175
1176    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1177    pub show: bool,
1178
1179    #[cfg_attr(feature = "wayland", allow(dead_code))]
1180    pub display_id: Option<DisplayId>,
1181
1182    pub window_min_size: Option<Size<Pixels>>,
1183    #[cfg(target_os = "macos")]
1184    pub tabbing_identifier: Option<String>,
1185}
1186
1187/// Represents the status of how a window should be opened.
1188#[derive(Debug, Copy, Clone, PartialEq)]
1189pub enum WindowBounds {
1190    /// Indicates that the window should open in a windowed state with the given bounds.
1191    Windowed(Bounds<Pixels>),
1192    /// Indicates that the window should open in a maximized state.
1193    /// The bounds provided here represent the restore size of the window.
1194    Maximized(Bounds<Pixels>),
1195    /// Indicates that the window should open in fullscreen mode.
1196    /// The bounds provided here represent the restore size of the window.
1197    Fullscreen(Bounds<Pixels>),
1198}
1199
1200impl Default for WindowBounds {
1201    fn default() -> Self {
1202        WindowBounds::Windowed(Bounds::default())
1203    }
1204}
1205
1206impl WindowBounds {
1207    /// Retrieve the inner bounds
1208    pub fn get_bounds(&self) -> Bounds<Pixels> {
1209        match self {
1210            WindowBounds::Windowed(bounds) => *bounds,
1211            WindowBounds::Maximized(bounds) => *bounds,
1212            WindowBounds::Fullscreen(bounds) => *bounds,
1213        }
1214    }
1215}
1216
1217impl Default for WindowOptions {
1218    fn default() -> Self {
1219        Self {
1220            window_bounds: None,
1221            titlebar: Some(TitlebarOptions {
1222                title: Default::default(),
1223                appears_transparent: Default::default(),
1224                traffic_light_position: Default::default(),
1225            }),
1226            focus: true,
1227            show: true,
1228            kind: WindowKind::Normal,
1229            is_movable: true,
1230            is_resizable: true,
1231            is_minimizable: true,
1232            display_id: None,
1233            window_background: WindowBackgroundAppearance::default(),
1234            app_id: None,
1235            window_min_size: None,
1236            window_decorations: None,
1237            tabbing_identifier: None,
1238        }
1239    }
1240}
1241
1242/// The options that can be configured for a window's titlebar
1243#[derive(Debug, Default)]
1244pub struct TitlebarOptions {
1245    /// The initial title of the window
1246    pub title: Option<SharedString>,
1247
1248    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
1249    /// Refer to [`WindowOptions::window_decorations`] on Linux
1250    pub appears_transparent: bool,
1251
1252    /// The position of the macOS traffic light buttons
1253    pub traffic_light_position: Option<Point<Pixels>>,
1254}
1255
1256/// The kind of window to create
1257#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1258pub enum WindowKind {
1259    /// A normal application window
1260    Normal,
1261
1262    /// A window that appears above all other windows, usually used for alerts or popups
1263    /// use sparingly!
1264    PopUp,
1265}
1266
1267/// The appearance of the window, as defined by the operating system.
1268///
1269/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
1270/// values.
1271#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1272pub enum WindowAppearance {
1273    /// A light appearance.
1274    ///
1275    /// On macOS, this corresponds to the `aqua` appearance.
1276    Light,
1277
1278    /// A light appearance with vibrant colors.
1279    ///
1280    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
1281    VibrantLight,
1282
1283    /// A dark appearance.
1284    ///
1285    /// On macOS, this corresponds to the `darkAqua` appearance.
1286    Dark,
1287
1288    /// A dark appearance with vibrant colors.
1289    ///
1290    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
1291    VibrantDark,
1292}
1293
1294impl Default for WindowAppearance {
1295    fn default() -> Self {
1296        Self::Light
1297    }
1298}
1299
1300/// The appearance of the background of the window itself, when there is
1301/// no content or the content is transparent.
1302#[derive(Copy, Clone, Debug, Default, PartialEq)]
1303pub enum WindowBackgroundAppearance {
1304    /// Opaque.
1305    ///
1306    /// This lets the window manager know that content behind this
1307    /// window does not need to be drawn.
1308    ///
1309    /// Actual color depends on the system and themes should define a fully
1310    /// opaque background color instead.
1311    #[default]
1312    Opaque,
1313    /// Plain alpha transparency.
1314    Transparent,
1315    /// Transparency, but the contents behind the window are blurred.
1316    ///
1317    /// Not always supported.
1318    Blurred,
1319}
1320
1321/// The options that can be configured for a file dialog prompt
1322#[derive(Clone, Debug)]
1323pub struct PathPromptOptions {
1324    /// Should the prompt allow files to be selected?
1325    pub files: bool,
1326    /// Should the prompt allow directories to be selected?
1327    pub directories: bool,
1328    /// Should the prompt allow multiple files to be selected?
1329    pub multiple: bool,
1330    /// The prompt to show to a user when selecting a path
1331    pub prompt: Option<SharedString>,
1332}
1333
1334/// What kind of prompt styling to show
1335#[derive(Copy, Clone, Debug, PartialEq)]
1336pub enum PromptLevel {
1337    /// A prompt that is shown when the user should be notified of something
1338    Info,
1339
1340    /// A prompt that is shown when the user needs to be warned of a potential problem
1341    Warning,
1342
1343    /// A prompt that is shown when a critical problem has occurred
1344    Critical,
1345}
1346
1347/// Prompt Button
1348#[derive(Clone, Debug, PartialEq)]
1349pub enum PromptButton {
1350    /// Ok button
1351    Ok(SharedString),
1352    /// Cancel button
1353    Cancel(SharedString),
1354    /// Other button
1355    Other(SharedString),
1356}
1357
1358impl PromptButton {
1359    /// Create a button with label
1360    pub fn new(label: impl Into<SharedString>) -> Self {
1361        PromptButton::Other(label.into())
1362    }
1363
1364    /// Create an Ok button
1365    pub fn ok(label: impl Into<SharedString>) -> Self {
1366        PromptButton::Ok(label.into())
1367    }
1368
1369    /// Create a Cancel button
1370    pub fn cancel(label: impl Into<SharedString>) -> Self {
1371        PromptButton::Cancel(label.into())
1372    }
1373
1374    #[allow(dead_code)]
1375    pub(crate) fn is_cancel(&self) -> bool {
1376        matches!(self, PromptButton::Cancel(_))
1377    }
1378
1379    /// Returns the label of the button
1380    pub fn label(&self) -> &SharedString {
1381        match self {
1382            PromptButton::Ok(label) => label,
1383            PromptButton::Cancel(label) => label,
1384            PromptButton::Other(label) => label,
1385        }
1386    }
1387}
1388
1389impl From<&str> for PromptButton {
1390    fn from(value: &str) -> Self {
1391        match value.to_lowercase().as_str() {
1392            "ok" => PromptButton::Ok("Ok".into()),
1393            "cancel" => PromptButton::Cancel("Cancel".into()),
1394            _ => PromptButton::Other(SharedString::from(value.to_owned())),
1395        }
1396    }
1397}
1398
1399/// The style of the cursor (pointer)
1400#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1401pub enum CursorStyle {
1402    /// The default cursor
1403    Arrow,
1404
1405    /// A text input cursor
1406    /// corresponds to the CSS cursor value `text`
1407    IBeam,
1408
1409    /// A crosshair cursor
1410    /// corresponds to the CSS cursor value `crosshair`
1411    Crosshair,
1412
1413    /// A closed hand cursor
1414    /// corresponds to the CSS cursor value `grabbing`
1415    ClosedHand,
1416
1417    /// An open hand cursor
1418    /// corresponds to the CSS cursor value `grab`
1419    OpenHand,
1420
1421    /// A pointing hand cursor
1422    /// corresponds to the CSS cursor value `pointer`
1423    PointingHand,
1424
1425    /// A resize left cursor
1426    /// corresponds to the CSS cursor value `w-resize`
1427    ResizeLeft,
1428
1429    /// A resize right cursor
1430    /// corresponds to the CSS cursor value `e-resize`
1431    ResizeRight,
1432
1433    /// A resize cursor to the left and right
1434    /// corresponds to the CSS cursor value `ew-resize`
1435    ResizeLeftRight,
1436
1437    /// A resize up cursor
1438    /// corresponds to the CSS cursor value `n-resize`
1439    ResizeUp,
1440
1441    /// A resize down cursor
1442    /// corresponds to the CSS cursor value `s-resize`
1443    ResizeDown,
1444
1445    /// A resize cursor directing up and down
1446    /// corresponds to the CSS cursor value `ns-resize`
1447    ResizeUpDown,
1448
1449    /// A resize cursor directing up-left and down-right
1450    /// corresponds to the CSS cursor value `nesw-resize`
1451    ResizeUpLeftDownRight,
1452
1453    /// A resize cursor directing up-right and down-left
1454    /// corresponds to the CSS cursor value `nwse-resize`
1455    ResizeUpRightDownLeft,
1456
1457    /// A cursor indicating that the item/column can be resized horizontally.
1458    /// corresponds to the CSS cursor value `col-resize`
1459    ResizeColumn,
1460
1461    /// A cursor indicating that the item/row can be resized vertically.
1462    /// corresponds to the CSS cursor value `row-resize`
1463    ResizeRow,
1464
1465    /// A text input cursor for vertical layout
1466    /// corresponds to the CSS cursor value `vertical-text`
1467    IBeamCursorForVerticalLayout,
1468
1469    /// A cursor indicating that the operation is not allowed
1470    /// corresponds to the CSS cursor value `not-allowed`
1471    OperationNotAllowed,
1472
1473    /// A cursor indicating that the operation will result in a link
1474    /// corresponds to the CSS cursor value `alias`
1475    DragLink,
1476
1477    /// A cursor indicating that the operation will result in a copy
1478    /// corresponds to the CSS cursor value `copy`
1479    DragCopy,
1480
1481    /// A cursor indicating that the operation will result in a context menu
1482    /// corresponds to the CSS cursor value `context-menu`
1483    ContextualMenu,
1484
1485    /// Hide the cursor
1486    None,
1487}
1488
1489impl Default for CursorStyle {
1490    fn default() -> Self {
1491        Self::Arrow
1492    }
1493}
1494
1495/// A clipboard item that should be copied to the clipboard
1496#[derive(Clone, Debug, Eq, PartialEq)]
1497pub struct ClipboardItem {
1498    entries: Vec<ClipboardEntry>,
1499}
1500
1501/// Either a ClipboardString or a ClipboardImage
1502#[derive(Clone, Debug, Eq, PartialEq)]
1503pub enum ClipboardEntry {
1504    /// A string entry
1505    String(ClipboardString),
1506    /// An image entry
1507    Image(Image),
1508}
1509
1510impl ClipboardItem {
1511    /// Create a new ClipboardItem::String with no associated metadata
1512    pub fn new_string(text: String) -> Self {
1513        Self {
1514            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1515        }
1516    }
1517
1518    /// Create a new ClipboardItem::String with the given text and associated metadata
1519    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1520        Self {
1521            entries: vec![ClipboardEntry::String(ClipboardString {
1522                text,
1523                metadata: Some(metadata),
1524            })],
1525        }
1526    }
1527
1528    /// Create a new ClipboardItem::String with the given text and associated metadata
1529    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1530        Self {
1531            entries: vec![ClipboardEntry::String(
1532                ClipboardString::new(text).with_json_metadata(metadata),
1533            )],
1534        }
1535    }
1536
1537    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1538    pub fn new_image(image: &Image) -> Self {
1539        Self {
1540            entries: vec![ClipboardEntry::Image(image.clone())],
1541        }
1542    }
1543
1544    /// Concatenates together all the ClipboardString entries in the item.
1545    /// Returns None if there were no ClipboardString entries.
1546    pub fn text(&self) -> Option<String> {
1547        let mut answer = String::new();
1548        let mut any_entries = false;
1549
1550        for entry in self.entries.iter() {
1551            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1552                answer.push_str(text);
1553                any_entries = true;
1554            }
1555        }
1556
1557        if any_entries { Some(answer) } else { None }
1558    }
1559
1560    /// If this item is one ClipboardEntry::String, returns its metadata.
1561    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1562    pub fn metadata(&self) -> Option<&String> {
1563        match self.entries().first() {
1564            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1565                clipboard_string.metadata.as_ref()
1566            }
1567            _ => None,
1568        }
1569    }
1570
1571    /// Get the item's entries
1572    pub fn entries(&self) -> &[ClipboardEntry] {
1573        &self.entries
1574    }
1575
1576    /// Get owned versions of the item's entries
1577    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1578        self.entries.into_iter()
1579    }
1580}
1581
1582impl From<ClipboardString> for ClipboardEntry {
1583    fn from(value: ClipboardString) -> Self {
1584        Self::String(value)
1585    }
1586}
1587
1588impl From<String> for ClipboardEntry {
1589    fn from(value: String) -> Self {
1590        Self::from(ClipboardString::from(value))
1591    }
1592}
1593
1594impl From<Image> for ClipboardEntry {
1595    fn from(value: Image) -> Self {
1596        Self::Image(value)
1597    }
1598}
1599
1600impl From<ClipboardEntry> for ClipboardItem {
1601    fn from(value: ClipboardEntry) -> Self {
1602        Self {
1603            entries: vec![value],
1604        }
1605    }
1606}
1607
1608impl From<String> for ClipboardItem {
1609    fn from(value: String) -> Self {
1610        Self::from(ClipboardEntry::from(value))
1611    }
1612}
1613
1614impl From<Image> for ClipboardItem {
1615    fn from(value: Image) -> Self {
1616        Self::from(ClipboardEntry::from(value))
1617    }
1618}
1619
1620/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1621#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1622pub enum ImageFormat {
1623    // Sorted from most to least likely to be pasted into an editor,
1624    // which matters when we iterate through them trying to see if
1625    // clipboard content matches them.
1626    /// .png
1627    Png,
1628    /// .jpeg or .jpg
1629    Jpeg,
1630    /// .webp
1631    Webp,
1632    /// .gif
1633    Gif,
1634    /// .svg
1635    Svg,
1636    /// .bmp
1637    Bmp,
1638    /// .tif or .tiff
1639    Tiff,
1640}
1641
1642impl ImageFormat {
1643    /// Returns the mime type for the ImageFormat
1644    pub const fn mime_type(self) -> &'static str {
1645        match self {
1646            ImageFormat::Png => "image/png",
1647            ImageFormat::Jpeg => "image/jpeg",
1648            ImageFormat::Webp => "image/webp",
1649            ImageFormat::Gif => "image/gif",
1650            ImageFormat::Svg => "image/svg+xml",
1651            ImageFormat::Bmp => "image/bmp",
1652            ImageFormat::Tiff => "image/tiff",
1653        }
1654    }
1655
1656    /// Returns the ImageFormat for the given mime type
1657    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
1658        match mime_type {
1659            "image/png" => Some(Self::Png),
1660            "image/jpeg" | "image/jpg" => Some(Self::Jpeg),
1661            "image/webp" => Some(Self::Webp),
1662            "image/gif" => Some(Self::Gif),
1663            "image/svg+xml" => Some(Self::Svg),
1664            "image/bmp" => Some(Self::Bmp),
1665            "image/tiff" | "image/tif" => Some(Self::Tiff),
1666            _ => None,
1667        }
1668    }
1669}
1670
1671/// An image, with a format and certain bytes
1672#[derive(Clone, Debug, PartialEq, Eq)]
1673pub struct Image {
1674    /// The image format the bytes represent (e.g. PNG)
1675    pub format: ImageFormat,
1676    /// The raw image bytes
1677    pub bytes: Vec<u8>,
1678    /// The unique ID for the image
1679    id: u64,
1680}
1681
1682impl Hash for Image {
1683    fn hash<H: Hasher>(&self, state: &mut H) {
1684        state.write_u64(self.id);
1685    }
1686}
1687
1688impl Image {
1689    /// An empty image containing no data
1690    pub fn empty() -> Self {
1691        Self::from_bytes(ImageFormat::Png, Vec::new())
1692    }
1693
1694    /// Create an image from a format and bytes
1695    pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
1696        Self {
1697            id: hash(&bytes),
1698            format,
1699            bytes,
1700        }
1701    }
1702
1703    /// Get this image's ID
1704    pub fn id(&self) -> u64 {
1705        self.id
1706    }
1707
1708    /// Use the GPUI `use_asset` API to make this image renderable
1709    pub fn use_render_image(
1710        self: Arc<Self>,
1711        window: &mut Window,
1712        cx: &mut App,
1713    ) -> Option<Arc<RenderImage>> {
1714        ImageSource::Image(self)
1715            .use_data(None, window, cx)
1716            .and_then(|result| result.ok())
1717    }
1718
1719    /// Use the GPUI `get_asset` API to make this image renderable
1720    pub fn get_render_image(
1721        self: Arc<Self>,
1722        window: &mut Window,
1723        cx: &mut App,
1724    ) -> Option<Arc<RenderImage>> {
1725        ImageSource::Image(self)
1726            .get_data(None, window, cx)
1727            .and_then(|result| result.ok())
1728    }
1729
1730    /// Use the GPUI `remove_asset` API to drop this image, if possible.
1731    pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
1732        ImageSource::Image(self).remove_asset(cx);
1733    }
1734
1735    /// Convert the clipboard image to an `ImageData` object.
1736    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1737        fn frames_for_image(
1738            bytes: &[u8],
1739            format: image::ImageFormat,
1740        ) -> Result<SmallVec<[Frame; 1]>> {
1741            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1742
1743            // Convert from RGBA to BGRA.
1744            for pixel in data.chunks_exact_mut(4) {
1745                pixel.swap(0, 2);
1746            }
1747
1748            Ok(SmallVec::from_elem(Frame::new(data), 1))
1749        }
1750
1751        let frames = match self.format {
1752            ImageFormat::Gif => {
1753                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1754                let mut frames = SmallVec::new();
1755
1756                for frame in decoder.into_frames() {
1757                    let mut frame = frame?;
1758                    // Convert from RGBA to BGRA.
1759                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1760                        pixel.swap(0, 2);
1761                    }
1762                    frames.push(frame);
1763                }
1764
1765                frames
1766            }
1767            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1768            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1769            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1770            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1771            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1772            ImageFormat::Svg => {
1773                let pixmap = svg_renderer.render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1774
1775                let buffer =
1776                    image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1777                        .unwrap();
1778
1779                SmallVec::from_elem(Frame::new(buffer), 1)
1780            }
1781        };
1782
1783        Ok(Arc::new(RenderImage::new(frames)))
1784    }
1785
1786    /// Get the format of the clipboard image
1787    pub fn format(&self) -> ImageFormat {
1788        self.format
1789    }
1790
1791    /// Get the raw bytes of the clipboard image
1792    pub fn bytes(&self) -> &[u8] {
1793        self.bytes.as_slice()
1794    }
1795}
1796
1797/// A clipboard item that should be copied to the clipboard
1798#[derive(Clone, Debug, Eq, PartialEq)]
1799pub struct ClipboardString {
1800    pub(crate) text: String,
1801    pub(crate) metadata: Option<String>,
1802}
1803
1804impl ClipboardString {
1805    /// Create a new clipboard string with the given text
1806    pub fn new(text: String) -> Self {
1807        Self {
1808            text,
1809            metadata: None,
1810        }
1811    }
1812
1813    /// Return a new clipboard item with the metadata replaced by the given metadata,
1814    /// after serializing it as JSON.
1815    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1816        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1817        self
1818    }
1819
1820    /// Get the text of the clipboard string
1821    pub fn text(&self) -> &String {
1822        &self.text
1823    }
1824
1825    /// Get the owned text of the clipboard string
1826    pub fn into_text(self) -> String {
1827        self.text
1828    }
1829
1830    /// Get the metadata of the clipboard string, formatted as JSON
1831    pub fn metadata_json<T>(&self) -> Option<T>
1832    where
1833        T: for<'a> Deserialize<'a>,
1834    {
1835        self.metadata
1836            .as_ref()
1837            .and_then(|m| serde_json::from_str(m).ok())
1838    }
1839
1840    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1841    pub(crate) fn text_hash(text: &str) -> u64 {
1842        let mut hasher = SeaHasher::new();
1843        text.hash(&mut hasher);
1844        hasher.finish()
1845    }
1846}
1847
1848impl From<String> for ClipboardString {
1849    fn from(value: String) -> Self {
1850        Self {
1851            text: value,
1852            metadata: None,
1853        }
1854    }
1855}