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