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