platform.rs

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