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