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