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