platform.rs

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