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