platform.rs

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