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