platform.rs

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