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