Skip to main content

gpui/
platform.rs

1mod app_menu;
2mod keyboard;
3mod keystroke;
4mod platform_info;
5
6#[cfg(all(target_os = "linux", feature = "wayland"))]
7#[expect(missing_docs)]
8pub mod layer_shell;
9
10/// Types for configuring parent-anchored popup windows such as menus, dropdowns and tooltips.
11pub mod popup;
12
13#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
14mod threaded_dispatcher;
15
16#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
17mod test;
18
19#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
20mod visual_test;
21
22#[cfg(any(test, feature = "test-support"))]
23#[doc(hidden)]
24pub mod hdr_test_scene;
25
26#[cfg(all(
27    feature = "screen-capture",
28    any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
29))]
30pub mod scap_screen_capture;
31
32#[cfg(all(
33    any(target_os = "windows", target_os = "linux"),
34    feature = "screen-capture"
35))]
36pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
37#[cfg(not(feature = "screen-capture"))]
38pub(crate) type PlatformScreenCaptureFrame = ();
39#[cfg(all(target_os = "macos", feature = "screen-capture"))]
40pub(crate) type PlatformScreenCaptureFrame =
41    objc2_core_foundation::CFRetained<objc2_core_video::CVImageBuffer>;
42
43use crate::{
44    Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds, Corners,
45    DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
46    FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GlyphShadowParams, GpuSpecs, Hsla,
47    ImageSource, Keymap,
48    LineLayout, MissingGlyphSink, Pixels, PlatformGestures, PlatformInput, Point, Priority,
49    RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph,
50    ShapedRun, SharedString, Size, SvgRenderer, SystemWindowTab, Task, Window, WindowControlArea,
51    hash, point, px, size,
52};
53#[cfg(any(target_os = "linux", target_os = "freebsd"))]
54use anyhow::bail;
55use anyhow::{Context as _, Result};
56use async_task::Runnable;
57use collections::FxHashMap;
58use futures::channel::oneshot;
59// vue-native: ungated along with `PlatformWindow::render_to_image`.
60use image::RgbaImage;
61use image::codecs::{gif::GifDecoder, webp::WebPDecoder};
62use image::{DynamicImage, Frame, Rgba};
63use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
64use scheduler::Instant;
65pub use scheduler::RunnableMeta;
66#[cfg(feature = "schemars")]
67use schemars::JsonSchema;
68use seahash::SeaHasher;
69use serde::{Deserialize, Serialize};
70use smallvec::SmallVec;
71use std::borrow::Cow;
72use std::collections::hash_map::Entry;
73use std::hash::{Hash, Hasher};
74use std::io::Cursor;
75use std::ops;
76use std::time::Duration;
77use std::{
78    ffi::OsString,
79    fmt::{self, Debug},
80    ops::Range,
81    path::{Path, PathBuf},
82    rc::Rc,
83    sync::Arc,
84};
85use uuid::Uuid;
86
87pub use app_menu::*;
88pub use keyboard::*;
89pub use keystroke::*;
90
91/// Whether the platform is presenting a window's frames.
92///
93/// This is about presentation, not the window's shown/hidden state: a shown
94/// window that is fully covered by other windows, minimized, on another
95/// Space or virtual desktop, or on a display that is asleep is `Hidden`. A
96/// window only partly covered by other windows is `Visible`.
97///
98/// Each platform reports from a single source, and what that source can see
99/// differs:
100///
101/// * macOS: `NSWindow.occlusionState`. Covers all of the cases above.
102/// * Windows: `WS_VISIBLE` and the minimized state. Windows keeps compositing
103///   covered windows for thumbnails and Alt-Tab and offers no occlusion
104///   notification, so a fully covered window stays `Visible`. Display sleep is
105///   not reported either.
106/// * Wayland: the `xdg_toplevel` `suspended` state (xdg-shell v6). Compositors
107///   that don't support it never report `Hidden`.
108/// * X11: mapped state plus `VisibilityNotify`. Compositing window managers
109///   generally never report a window as fully obscured, so covering is only
110///   detected without compositing.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum WindowVisibility {
113    /// At least part of the window is being presented; frames drawn for it
114    /// will be shown.
115    Visible,
116    /// No part of the window is being presented. The platform will not
117    /// request frames for it until it becomes visible again.
118    Hidden,
119}
120
121impl WindowVisibility {
122    /// Whether frames drawn for the window will be shown.
123    pub fn is_visible(self) -> bool {
124        self == Self::Visible
125    }
126}
127
128/// A change to the connected displays, reported through
129/// [`App::observe_displays`](crate::App::observe_displays).
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
131#[non_exhaustive]
132pub enum DisplayEvent {
133    /// A display was connected.
134    Added(DisplayId),
135    /// A display was disconnected. Windows on it are moved to another
136    /// display by the platform.
137    Removed(DisplayId),
138    /// A connected display's properties changed.
139    Changed {
140        /// The display that changed.
141        id: DisplayId,
142        /// Which of its properties changed.
143        changes: DisplayChanges,
144    },
145}
146
147bitflags::bitflags! {
148    /// The properties of a display that a [`DisplayEvent::Changed`] reports.
149    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150    pub struct DisplayChanges: u8 {
151        /// [`PlatformDisplay::bounds`] changed.
152        const BOUNDS = 1 << 0;
153        /// [`PlatformDisplay::refresh_interval`] changed.
154        const REFRESH_INTERVAL = 1 << 1;
155    }
156}
157
158/// Converts a refresh rate in hertz to the time between refreshes, rejecting
159/// the zero, negative, and non-finite rates platforms use to mean "unknown".
160pub fn refresh_interval_from_hz(hertz: f64) -> Option<Duration> {
161    (hertz.is_finite() && hertz > 0.0).then(|| Duration::from_secs_f64(1.0 / hertz))
162}
163
164/// Controls whether the application participates in the system's foreground UI.
165///
166/// Only has an effect on macOS; other platforms ignore this setting. There,
167/// [`App::request_windowing`] sets it: `Accessory` while headless and `Regular` while windowed.
168/// Set it directly with [`App::set_activation_policy`] for the one case that doesn't cover: an
169/// accessory app that shows windows, such as a menu bar utility.
170#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
171pub enum ActivationPolicy {
172    /// Participate in foreground application UI, such as the Dock and menu bar on macOS.
173    #[default]
174    Regular,
175    /// Run without foreground application UI while retaining the ability to open windows.
176    Accessory,
177}
178
179#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
180pub(crate) use test::*;
181
182#[cfg(any(test, feature = "test-support"))]
183pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
184
185#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
186pub use threaded_dispatcher::ThreadedDispatcher;
187
188#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
189pub use visual_test::VisualTestPlatform;
190
191/// Keeps an operating system activity, such as an idle sleep inhibitor, alive until dropped.
192pub struct ActivityGuard {
193    _release: gpui_util::Deferred<Box<dyn FnOnce() + Send>>,
194}
195
196impl ActivityGuard {
197    /// Runs `release` when the guard is dropped.
198    pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
199        Self {
200            _release: gpui_util::defer(Box::new(release)),
201        }
202    }
203
204    /// A guard for platforms without a corresponding activity.
205    pub fn noop() -> Self {
206        Self::new(|| {})
207    }
208}
209
210// TODO(jk): return an enum instead of a string
211/// Return which compositor we're guessing we'll use.
212/// Does not attempt to connect to the given compositor.
213#[cfg(any(target_os = "linux", target_os = "freebsd"))]
214#[inline]
215pub fn guess_compositor() -> &'static str {
216    if std::env::var_os("ZED_HEADLESS").is_some() {
217        return "headless";
218    }
219    GraphicalEnvironment::detect().guess_compositor()
220}
221
222/// The graphical session to connect to: the variables that locate its display server, as some
223/// process sees them.
224///
225/// A long-running process can outlive the graphical session it was started in, so a platform
226/// that attaches to a display server later can be given a fresher environment than its own.
227/// While connected, programs the platform launches (for example to open a URL) get these
228/// variables instead of the ones this process started with. Apply
229/// [`App::graphical_environment`] to the programs an app launches, for the same reason.
230#[cfg(any(target_os = "linux", target_os = "freebsd"))]
231#[derive(Clone, Debug, Default)]
232pub struct GraphicalEnvironment {
233    /// `WAYLAND_DISPLAY`: a socket name relative to `xdg_runtime_dir`, or an absolute path.
234    pub wayland_display: Option<OsString>,
235    /// `DISPLAY`: the X11 display name.
236    pub x11_display: Option<OsString>,
237    /// `XDG_RUNTIME_DIR`: the directory containing Wayland sockets.
238    pub xdg_runtime_dir: Option<OsString>,
239    /// `XDG_CURRENT_DESKTOP`: the session's desktop environment, such as `ubuntu:GNOME`.
240    ///
241    /// Only reported by [`GraphicalEnvironment::desktop_environment`]; [`GraphicalEnvironment::apply_to`]
242    /// leaves it alone.
243    pub current_desktop: Option<OsString>,
244    /// `XDG_ACTIVATION_TOKEN`: lets the first window take focus on Wayland.
245    ///
246    /// A platform takes this process's token from its environment when it's created, and uses
247    /// it if it starts windowed. Pass one here to switch to windowed mode later, for example
248    /// the token of the process that asked for a window.
249    pub activation_token: Option<String>,
250}
251
252/// The graphical session to connect to: the Windows session whose desktop windows appear on.
253///
254/// A process can only show windows in its own session, so switching to windowed mode fails if
255/// this names another one, for example when a process started over SSH is asked to show a
256/// window on the desktop.
257#[cfg(target_os = "windows")]
258#[derive(Clone, Debug, Default)]
259pub struct GraphicalEnvironment {
260    /// The session ID, as `ProcessIdToSessionId` reports it. `None` means this process's own
261    /// session.
262    pub session_id: Option<u32>,
263}
264
265#[cfg(target_os = "windows")]
266impl GraphicalEnvironment {
267    /// Returns the environment of this process's session.
268    pub fn detect() -> Self {
269        let mut session_id = 0;
270        // SAFETY: `session_id` is a valid pointer for the call's duration.
271        let result = unsafe {
272            windows_sys::Win32::System::RemoteDesktop::ProcessIdToSessionId(
273                windows_sys::Win32::System::Threading::GetCurrentProcessId(),
274                &mut session_id,
275            )
276        };
277        Self {
278            session_id: (result != 0).then_some(session_id),
279        }
280    }
281
282    /// Does nothing on this platform: programs inherit the session of the process that
283    /// starts them.
284    pub fn apply_to(&self, _command: &mut std::process::Command) {}
285
286    /// Returns `None`: this platform has no desktop environments to tell apart.
287    pub fn desktop_environment(&self) -> Option<String> {
288        None
289    }
290}
291
292/// The graphical session to connect to. Carries nothing yet on this platform.
293#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
294#[derive(Clone, Debug, Default)]
295pub struct GraphicalEnvironment;
296
297#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
298impl GraphicalEnvironment {
299    /// Returns the environment of this process's graphical session.
300    pub fn detect() -> Self {
301        Self
302    }
303
304    /// Does nothing on this platform.
305    pub fn apply_to(&self, _command: &mut std::process::Command) {}
306
307    /// Returns `None`: this platform has no desktop environments to tell apart.
308    pub fn desktop_environment(&self) -> Option<String> {
309        None
310    }
311}
312
313/// A display mode for [`App::request_windowing`] to switch to.
314#[derive(Clone, Debug)]
315pub enum WindowingRequest {
316    /// No display server. Windows lay out and handle input but draw nothing.
317    Headless,
318    /// Connected to the display server that the environment names.
319    Windowed(GraphicalEnvironment),
320}
321
322#[cfg(any(target_os = "linux", target_os = "freebsd"))]
323impl GraphicalEnvironment {
324    /// Reads the display variables from this process's environment.
325    ///
326    /// This only reads environment variables: whether they name a reachable display server is
327    /// checked when a platform connects. Leaves `activation_token` unset: see its documentation.
328    pub fn detect() -> Self {
329        Self {
330            wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
331            x11_display: std::env::var_os("DISPLAY"),
332            xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
333            current_desktop: std::env::var_os("XDG_CURRENT_DESKTOP"),
334            activation_token: None,
335        }
336    }
337
338    /// Sets this environment's display variables on `command`, and removes the ones it doesn't
339    /// set, so the program connects to this graphical session rather than the one this process
340    /// started in. Leaves `XDG_ACTIVATION_TOKEN` alone.
341    pub fn apply_to(&self, command: &mut std::process::Command) {
342        for (name, value) in [
343            ("WAYLAND_DISPLAY", &self.wayland_display),
344            ("DISPLAY", &self.x11_display),
345            ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
346        ] {
347            match value {
348                Some(value) => command.env(name, value),
349                None => command.env_remove(name),
350            };
351        }
352    }
353
354    /// Returns the session's desktop environment, if `XDG_CURRENT_DESKTOP` names one.
355    ///
356    /// The value is a colon-separated list ordered from most to least specific,
357    /// such as `ubuntu:GNOME`.
358    pub fn desktop_environment(&self) -> Option<String> {
359        self.current_desktop
360            .as_ref()
361            .and_then(|desktop| desktop.to_str())
362            .filter(|desktop| !desktop.is_empty())
363            .map(str::to_owned)
364    }
365
366    /// Returns the compositor this environment selects: Wayland, then X11, then headless.
367    ///
368    /// Does not attempt to connect to the compositor.
369    pub fn guess_compositor(&self) -> &'static str {
370        let is_set =
371            |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
372        if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
373            "Wayland"
374        } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
375            "X11"
376        } else {
377            "headless"
378        }
379    }
380}
381
382#[cfg(any(target_os = "linux", target_os = "freebsd"))]
383bitflags::bitflags! {
384    /// The windowing modes a platform may start in or switch to.
385    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
386    pub struct WindowingModes: u8 {
387        /// Connected to a Wayland compositor.
388        const WAYLAND = 1 << 0;
389        /// Connected to an X server.
390        const X11 = 1 << 1;
391        /// No display server. Windows lay out and handle input but draw nothing.
392        const HEADLESS = 1 << 2;
393    }
394}
395
396pub use platform_info::{OperatingSystem, PlatformInfo, PlatformTarget};
397
398#[expect(missing_docs)]
399pub trait Platform: 'static {
400    /// Returns the host OS and application target reported by this backend.
401    fn platform_info(&self) -> PlatformInfo;
402
403    fn background_executor(&self) -> BackgroundExecutor;
404    fn foreground_executor(&self) -> ForegroundExecutor;
405    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
406
407    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
408    fn quit(&self);
409    /// Switches a capable platform between headless and windowed modes. See
410    /// [`App::request_windowing`].
411    /// Sets the windowing mode the platform starts in. Called before `run`. See
412    /// [`Application::with_windowing`].
413    fn set_initial_windowing(&self, _request: WindowingRequest) {}
414    fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
415        Task::ready(Err(anyhow::anyhow!(
416            "this platform cannot switch between headless and windowed modes"
417        )))
418    }
419    fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
420    fn activate(&self, ignoring_other_apps: bool);
421    /// Sets the initial or current activation policy. Has no effect outside macOS.
422    fn set_activation_policy(&self, _policy: ActivationPolicy) {}
423    fn hide(&self);
424    fn hide_other_apps(&self);
425    fn unhide_other_apps(&self);
426
427    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
428    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
429    /// Registers the callback invoked when displays may have been added or
430    /// removed, or a display's properties may have changed. GPUI rereads
431    /// [`Self::displays`] to find out what changed, so calls may be spurious.
432    /// The callback runs on the main thread outside of any window update.
433    fn on_displays_changed(&self, callback: Box<dyn FnMut()>);
434    fn active_window(&self) -> Option<AnyWindowHandle>;
435    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
436        None
437    }
438
439    fn is_screen_capture_supported(&self) -> bool {
440        false
441    }
442
443    fn screen_capture_sources(
444        &self,
445    ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
446        let (sources_tx, sources_rx) = oneshot::channel();
447        sources_tx
448            .send(Err(anyhow::anyhow!(
449                "gpui was compiled without the screen-capture feature"
450            )))
451            .ok();
452        sources_rx
453    }
454
455    fn open_window(
456        &self,
457        handle: AnyWindowHandle,
458        options: WindowParams,
459    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
460
461    /// Returns the appearance of the application's windows.
462    fn window_appearance(&self) -> WindowAppearance;
463
464    /// Overrides the appearance (light/dark) applied to the app's windows, independent
465    /// of the OS-wide setting. Pass `None` to clear the override and follow the system
466    /// again. The override is reflected by [`Platform::window_appearance`].
467    ///
468    /// Currently only implemented on macOS, where it sets `NSApplication.appearance` so
469    /// the native window chrome (the window border and titlebar) of every window matches
470    /// a dark app theme even when the system is in light mode (or vice versa). A no-op on
471    /// other platforms.
472    fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
473
474    /// Returns the window button layout configuration when supported.
475    fn button_layout(&self) -> Option<WindowButtonLayout> {
476        None
477    }
478
479    fn open_url(&self, url: &str);
480    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
481    fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
482
483    fn prompt_for_paths(
484        &self,
485        options: PathPromptOptions,
486    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
487    fn prompt_for_new_path(
488        &self,
489        directory: &Path,
490        suggested_name: Option<&str>,
491    ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
492    fn can_select_mixed_files_and_dirs(&self) -> bool;
493    fn reveal_path(&self, path: &Path);
494    fn open_with_system(&self, path: &Path);
495
496    fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
497    fn on_reopen(&self, callback: Box<dyn FnMut()>);
498    /// Registers the callback invoked when the system is about to sleep.
499    fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
500    /// Registers the callback invoked when the system resumes from sleep.
501    fn on_system_wake(&self, callback: Box<dyn FnMut()>);
502
503    // Mobile platform methods. On mobile the OS owns the application
504    // lifecycle: apps are backgrounded, foregrounded, and killed at the
505    // system's discretion, and must react rather than decide.
506
507    /// Registers a callback invoked whenever the application's lifecycle
508    /// phase changes. See [`AppLifecyclePhase`] for the phase vocabulary and
509    /// its mapping onto iOS and Android.
510    ///
511    /// Desktop platforms never invoke this.
512    fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
513
514    /// Registers a callback invoked when the OS signals memory pressure
515    /// (iOS `didReceiveMemoryWarning`, Android `onTrimMemory`).
516    ///
517    /// Desktop platforms never invoke this.
518    fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
519
520    /// The platform's gesture recognition services, if it provides any
521    /// beyond gpui's portable recognizers. See
522    /// [`PlatformGestures`](crate::PlatformGestures).
523    fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
524        None
525    }
526
527    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
528    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
529        None
530    }
531
532    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
533    fn perform_dock_menu_action(&self, _action: usize) {}
534    fn add_recent_document(&self, _path: &Path) {}
535    fn update_jump_list(
536        &self,
537        _menus: Vec<MenuItem>,
538        _entries: Vec<SmallVec<[PathBuf; 2]>>,
539    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
540        Task::ready(Vec::new())
541    }
542    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
543    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
544    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
545
546    /// Platform-specific diagnostic state, for [`App::debug_state`].
547    fn debug_state(&self) -> serde_json::Value {
548        serde_json::Value::Null
549    }
550
551    fn thermal_state(&self) -> ThermalState;
552    fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
553    fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
554
555    /// Returns the operating system's power mode, or [`PowerMode::Unknown`]
556    /// when the platform cannot determine it.
557    fn power_mode(&self) -> PowerMode {
558        PowerMode::Unknown
559    }
560    /// Registers a callback invoked when the reported power mode changes.
561    fn on_power_mode_change(&self, _callback: Box<dyn FnMut()>) {}
562
563    /// Sets the application's process-wide identity and user-visible name.
564    ///
565    /// The identifier is used for platform identity mechanisms such as the
566    /// Windows AppUserModelID. The name is used wherever the operating system
567    /// presents the application to the user. Call this once, early in startup,
568    /// before opening windows or posting notifications.
569    fn set_app_identity(&self, identifier: &str, name: &str) {
570        _ = (identifier, name);
571    }
572
573    /// Posts a notification to the operating system's notification center.
574    ///
575    /// Posting a notification whose [`SystemNotification::tag`] matches an
576    /// earlier one replaces that notification where the platform supports it.
577    /// No-op on platforms without notification support, or when delivery is
578    /// unavailable (e.g. authorization was denied).
579    fn show_system_notification(&self, notification: SystemNotification) {
580        _ = notification;
581    }
582
583    /// Removes the delivered or pending notification with this tag.
584    ///
585    /// Best-effort: some platforms cannot retract a notification once shown,
586    /// in which case it ages out of the notification center on its own.
587    /// The task completes after the platform calls return, not after any
588    /// asynchronous work inside the operating system. Dropping it does not
589    /// cancel dismissal.
590    fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
591        _ = tag;
592        Task::ready(())
593    }
594
595    /// Registers the callback invoked when the user activates a system
596    /// notification, either by clicking its body or one of its action
597    /// buttons.
598    ///
599    /// Implementations must invoke the callback on the main thread.
600    fn on_system_notification_response(
601        &self,
602        callback: Box<dyn FnMut(SystemNotificationResponse)>,
603    ) {
604        _ = callback;
605    }
606
607    fn compositor_name(&self) -> &'static str {
608        ""
609    }
610    /// The environment of the display server a platform that can switch windowing modes is
611    /// connected to. See [`App::graphical_environment`].
612    fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
613        None
614    }
615    fn app_path(&self) -> Result<PathBuf>;
616    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
617
618    fn set_cursor_style(&self, style: CursorStyle);
619
620    /// Hides the mouse cursor until the user moves the mouse over one of
621    /// this application's windows.
622    fn hide_cursor_until_mouse_moves(&self);
623
624    /// Returns whether the mouse cursor is currently visible.
625    fn is_cursor_visible(&self) -> bool;
626
627    fn should_auto_hide_scrollbars(&self) -> bool;
628
629    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
630    fn write_to_clipboard(&self, item: ClipboardItem);
631
632    /// Reads the clipboard, resolving once its contents are available.
633    ///
634    /// Most platforms read synchronously and return a ready task. Platforms
635    /// whose clipboard access is inherently asynchronous and permission-gated
636    /// (e.g. the browser's async clipboard API) override this method; on those
637    /// platforms [`Platform::read_from_clipboard`] cannot return the clipboard
638    /// contents, so callers that can await should prefer this method.
639    fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
640        Task::ready(Ok(self.read_from_clipboard()))
641    }
642
643    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
644    fn read_from_primary(&self) -> Option<ClipboardItem>;
645    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
646    fn write_to_primary(&self, item: ClipboardItem);
647
648    #[cfg(target_os = "macos")]
649    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
650    #[cfg(target_os = "macos")]
651    fn write_to_find_pasteboard(&self, item: ClipboardItem);
652
653    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
654
655    /// Atomically writes credentials unless an item with this URL and username exists.
656    ///
657    /// Returns `true` if written, or `false` if the existing item was left unchanged.
658    #[cfg(target_os = "macos")]
659    fn write_credentials_if_not_exists(
660        &self,
661        _url: &str,
662        _username: &str,
663        _password: &[u8],
664    ) -> Task<Result<bool>> {
665        Task::ready(Err(anyhow::anyhow!(
666            "this platform does not support atomic credential writes"
667        )))
668    }
669
670    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
671    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
672
673    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
674    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
675    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
676}
677
678/// A handle to a platform's display, e.g. a monitor or laptop screen.
679pub trait PlatformDisplay: Debug {
680    /// Get the ID for this display
681    fn id(&self) -> DisplayId;
682
683    /// Returns a stable identifier for this display that can be persisted and used
684    /// across system restarts.
685    fn uuid(&self) -> Result<Uuid>;
686
687    /// Get the bounds for this display
688    fn bounds(&self) -> Bounds<Pixels>;
689
690    /// The time between the display's refreshes. Variable refresh rate
691    /// displays report their maximum rate. `None` when the platform doesn't
692    /// report it.
693    ///
694    /// May query the operating system; GPUI caches it per display, see
695    /// [`Window::refresh_interval`](crate::Window::refresh_interval).
696    fn refresh_interval(&self) -> Option<Duration>;
697
698    /// Get the visible bounds for this display, excluding taskbar/dock areas.
699    /// This is the usable area where windows can be placed without being obscured.
700    /// Defaults to the full display bounds if not overridden.
701    fn visible_bounds(&self) -> Bounds<Pixels> {
702        self.bounds()
703    }
704
705    /// Get the default bounds for this display to place a window
706    fn default_bounds(&self) -> Bounds<Pixels> {
707        let bounds = self.bounds();
708        let center = bounds.center();
709        let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
710
711        let offset = clipped_window_size / 2.0;
712        let origin = point(center.x - offset.width, center.y - offset.height);
713        Bounds::new(origin, clipped_window_size)
714    }
715}
716
717/// A notification posted to the operating system's notification center,
718/// rather than rendered as in-app UI.
719#[derive(Clone, Debug, PartialEq, Eq)]
720pub struct SystemNotification {
721    /// Stable identity for the notification. Posting a new notification with
722    /// the same tag replaces the previous one where the platform supports it,
723    /// and responses carry the tag back to the application.
724    pub tag: SharedString,
725    /// The notification's headline.
726    pub title: SharedString,
727    /// Additional text displayed below the title.
728    pub body: SharedString,
729    /// Buttons offered on the notification. Platforms that cannot display
730    /// action buttons show the notification without them.
731    pub actions: Vec<SystemNotificationAction>,
732}
733
734/// A button offered on a [`SystemNotification`].
735#[derive(Clone, Debug, PartialEq, Eq, Hash)]
736pub struct SystemNotificationAction {
737    /// Identifies the action in [`SystemNotificationResponse::action_id`]
738    /// when the user presses this button.
739    pub id: SharedString,
740    /// The button's user-visible label.
741    pub label: SharedString,
742}
743
744/// The user's activation of a [`SystemNotification`].
745#[derive(Clone, Debug, PartialEq, Eq)]
746pub struct SystemNotificationResponse {
747    /// The [`SystemNotification::tag`] of the activated notification.
748    pub tag: SharedString,
749    /// The pressed action button's [`SystemNotificationAction::id`], or
750    /// `None` when the user activated the notification body itself.
751    pub action_id: Option<SharedString>,
752}
753
754/// The operating system's preference for energy use versus performance.
755#[derive(Debug, Clone, Copy, PartialEq, Eq)]
756pub enum PowerMode {
757    /// The platform cannot determine the mode, or cannot distinguish the
758    /// active mode from other non-low-power modes.
759    Unknown,
760    /// The system prioritizes reducing energy use.
761    LowPower,
762    /// The system balances energy use and performance.
763    Balanced,
764    /// The system prioritizes performance over energy use.
765    HighPower,
766}
767
768/// Thermal state of the system
769#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770pub enum ThermalState {
771    /// System has no thermal constraints
772    Nominal,
773    /// System is slightly constrained, reduce discretionary work
774    Fair,
775    /// System is moderately constrained, reduce CPU/GPU intensive work
776    Serious,
777    /// System is critically constrained, minimize all resource usage
778    Critical,
779}
780
781/// Metadata for a given [ScreenCaptureSource]
782#[derive(Clone)]
783pub struct SourceMetadata {
784    /// Opaque identifier of this screen.
785    pub id: u64,
786    /// Human-readable label for this source.
787    pub label: Option<SharedString>,
788    /// Whether this source is the main display.
789    pub is_main: Option<bool>,
790    /// Video resolution of this source.
791    pub resolution: Size<DevicePixels>,
792}
793
794/// A source of on-screen video content that can be captured.
795pub trait ScreenCaptureSource {
796    /// Returns metadata for this source.
797    fn metadata(&self) -> Result<SourceMetadata>;
798
799    /// Start capture video from this source, invoking the given callback
800    /// with each frame.
801    fn stream(
802        &self,
803        foreground_executor: &ForegroundExecutor,
804        frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
805    ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
806}
807
808/// A video stream captured from a screen.
809pub trait ScreenCaptureStream {
810    /// Returns metadata for this source.
811    fn metadata(&self) -> Result<SourceMetadata>;
812}
813
814/// A frame of video captured from a screen.
815pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
816
817/// An opaque identifier for a hardware display
818#[derive(PartialEq, Eq, Hash, Copy, Clone)]
819pub struct DisplayId(pub(crate) u64);
820
821impl DisplayId {
822    /// Create a new `DisplayId` from a raw platform display identifier.
823    pub fn new(id: u64) -> Self {
824        Self(id)
825    }
826}
827
828impl From<u64> for DisplayId {
829    fn from(id: u64) -> Self {
830        Self(id)
831    }
832}
833
834impl From<DisplayId> for u64 {
835    fn from(id: DisplayId) -> Self {
836        id.0
837    }
838}
839
840impl Debug for DisplayId {
841    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
842        write!(f, "DisplayId({})", self.0)
843    }
844}
845
846/// Which part of the window to resize
847#[derive(Debug, Clone, Copy, PartialEq, Eq)]
848pub enum ResizeEdge {
849    /// The top edge
850    Top,
851    /// The top right corner
852    TopRight,
853    /// The right edge
854    Right,
855    /// The bottom right corner
856    BottomRight,
857    /// The bottom edge
858    Bottom,
859    /// The bottom left corner
860    BottomLeft,
861    /// The left edge
862    Left,
863    /// The top left corner
864    TopLeft,
865}
866
867/// A type to describe the appearance of a window
868#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
869pub enum WindowDecorations {
870    #[default]
871    /// Server side decorations
872    Server,
873    /// Client side decorations
874    Client,
875}
876
877/// A type to describe how this window is currently configured
878#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
879pub enum Decorations {
880    /// The window is configured to use server side decorations
881    #[default]
882    Server,
883    /// The window is configured to use client side decorations
884    Client {
885        /// The edge tiling state
886        tiling: Tiling,
887    },
888}
889
890/// What window controls this platform supports
891#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
892pub struct WindowControls {
893    /// Whether this platform supports fullscreen
894    pub fullscreen: bool,
895    /// Whether this platform supports maximize
896    pub maximize: bool,
897    /// Whether this platform supports minimize
898    pub minimize: bool,
899    /// Whether this platform supports a window menu
900    pub window_menu: bool,
901}
902
903impl Default for WindowControls {
904    fn default() -> Self {
905        // Assume that we can do anything, unless told otherwise
906        Self {
907            fullscreen: true,
908            maximize: true,
909            minimize: true,
910            window_menu: true,
911        }
912    }
913}
914
915/// A window control button type used in [`WindowButtonLayout`].
916#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
917pub enum WindowButton {
918    /// The minimize button
919    Minimize,
920    /// The maximize button
921    Maximize,
922    /// The close button
923    Close,
924}
925
926impl WindowButton {
927    /// Returns a stable element ID for rendering this button.
928    pub fn id(&self) -> &'static str {
929        match self {
930            WindowButton::Minimize => "minimize",
931            WindowButton::Maximize => "maximize",
932            WindowButton::Close => "close",
933        }
934    }
935
936    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
937    fn index(&self) -> usize {
938        match self {
939            WindowButton::Minimize => 0,
940            WindowButton::Maximize => 1,
941            WindowButton::Close => 2,
942        }
943    }
944}
945
946/// Maximum number of [`WindowButton`]s per side in the titlebar.
947pub const MAX_BUTTONS_PER_SIDE: usize = 3;
948
949/// Describes which [`WindowButton`]s appear on each side of the titlebar.
950///
951/// On Linux, this is read from the desktop environment's configuration
952/// (e.g. GNOME's `gtk-decoration-layout` gsetting) via [`WindowButtonLayout::parse`].
953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
954pub struct WindowButtonLayout {
955    /// Buttons on the left side of the titlebar.
956    pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
957    /// Buttons on the right side of the titlebar.
958    pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
959}
960
961#[cfg(any(target_os = "linux", target_os = "freebsd"))]
962impl WindowButtonLayout {
963    /// Returns Zed's built-in fallback button layout for Linux titlebars.
964    pub fn linux_default() -> Self {
965        Self {
966            left: [None; MAX_BUTTONS_PER_SIDE],
967            right: [
968                Some(WindowButton::Minimize),
969                Some(WindowButton::Maximize),
970                Some(WindowButton::Close),
971            ],
972        }
973    }
974
975    /// Parses a GNOME-style `button-layout` string (e.g. `"close,minimize:maximize"`).
976    pub fn parse(layout_string: &str) -> Result<Self> {
977        fn parse_side(
978            s: &str,
979            seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
980            unrecognized: &mut Vec<String>,
981        ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
982            let mut result = [None; MAX_BUTTONS_PER_SIDE];
983            let mut i = 0;
984            for name in s.split(',') {
985                let trimmed = name.trim();
986                if trimmed.is_empty() {
987                    continue;
988                }
989                let button = match trimmed {
990                    "minimize" => Some(WindowButton::Minimize),
991                    "maximize" => Some(WindowButton::Maximize),
992                    "close" => Some(WindowButton::Close),
993                    other => {
994                        unrecognized.push(other.to_string());
995                        None
996                    }
997                };
998                if let Some(button) = button {
999                    if seen_buttons[button.index()] {
1000                        continue;
1001                    }
1002                    if let Some(slot) = result.get_mut(i) {
1003                        *slot = Some(button);
1004                        seen_buttons[button.index()] = true;
1005                        i += 1;
1006                    }
1007                }
1008            }
1009            result
1010        }
1011
1012        let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1013        let mut unrecognized = Vec::new();
1014        let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1015        let layout = Self {
1016            left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1017            right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1018        };
1019
1020        if !unrecognized.is_empty()
1021            && layout.left.iter().all(Option::is_none)
1022            && layout.right.iter().all(Option::is_none)
1023        {
1024            bail!(
1025                "button layout string {:?} contains no valid buttons (unrecognized: {})",
1026                layout_string,
1027                unrecognized.join(", ")
1028            );
1029        }
1030
1031        Ok(layout)
1032    }
1033
1034    /// Formats the layout back into a GNOME-style `button-layout` string.
1035    #[cfg(test)]
1036    pub fn format(&self) -> String {
1037        fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1038            buttons
1039                .iter()
1040                .flatten()
1041                .map(|button| match button {
1042                    WindowButton::Minimize => "minimize",
1043                    WindowButton::Maximize => "maximize",
1044                    WindowButton::Close => "close",
1045                })
1046                .collect::<Vec<_>>()
1047                .join(",")
1048        }
1049
1050        format!("{}:{}", format_side(&self.left), format_side(&self.right))
1051    }
1052}
1053
1054/// A type to describe which sides of the window are currently tiled in some way
1055#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1056pub struct Tiling {
1057    /// Whether the top edge is tiled
1058    pub top: bool,
1059    /// Whether the left edge is tiled
1060    pub left: bool,
1061    /// Whether the right edge is tiled
1062    pub right: bool,
1063    /// Whether the bottom edge is tiled
1064    pub bottom: bool,
1065}
1066
1067impl Tiling {
1068    /// Initializes a [`Tiling`] type with all sides tiled
1069    pub fn tiled() -> Self {
1070        Self {
1071            top: true,
1072            left: true,
1073            right: true,
1074            bottom: true,
1075        }
1076    }
1077
1078    /// Whether any edge is tiled
1079    pub fn is_tiled(&self) -> bool {
1080        self.top || self.left || self.right || self.bottom
1081    }
1082}
1083
1084/// Callbacks for the accessibility adapter.
1085pub struct A11yCallbacks {
1086    /// Called when the adapter is activated (a screen reader connects).
1087    pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1088    /// Called when an action is requested by the screen reader.
1089    pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1090    /// Called when the adapter is deactivated (screen reader disconnects).
1091    pub deactivation: Box<dyn Fn() + Send + 'static>,
1092}
1093
1094/// The source of a platform frame request's timestamp.
1095#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1096pub enum FrameRequestSource {
1097    /// An OS callback or compositor-paced frame request.
1098    #[default]
1099    NativeCallback,
1100    /// A refresh timer, retry, queued wakeup, or fallback sleep paced by the app.
1101    LocalSchedule,
1102}
1103
1104#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1105#[expect(missing_docs)]
1106pub struct RequestFrameOptions {
1107    /// Whether a presentation is required.
1108    pub require_presentation: bool,
1109    /// Force refresh of all rendering states when true.
1110    pub force_render: bool,
1111    /// When the platform first requested this frame, before main-thread dispatch.
1112    ///
1113    /// `None` means the captured request time is unavailable.
1114    /// Coalesced requests carry their first request time, not their delivery time.
1115    /// Built-in backends collect timestamps only with the `profiler` feature.
1116    pub signal_at: Option<Instant>,
1117    /// Distinguishes native callbacks from local scheduling requests.
1118    pub signal_source: FrameRequestSource,
1119}
1120
1121/// Preserves the first platform frame request time across coalesced notifications.
1122///
1123/// Producers may record from a platform thread without waiting for the UI thread.
1124/// The consumer drains the timestamp before dispatching the request on the UI thread.
1125/// The timestamp offset and source share one atomic word so coalescing cannot
1126/// mix a request's time with another request's source. The low bit encodes the
1127/// source; the remaining bits encode nanoseconds from `origin`. `u64::MAX` is empty.
1128/// Without the `profiler` feature, this accumulator has no timestamp storage.
1129pub struct PlatformFrameSignal {
1130    #[cfg(feature = "profiler")]
1131    origin: Instant,
1132    #[cfg(feature = "profiler")]
1133    first_signal: std::sync::atomic::AtomicU64,
1134}
1135
1136impl Default for PlatformFrameSignal {
1137    fn default() -> Self {
1138        Self::new()
1139    }
1140}
1141
1142impl PlatformFrameSignal {
1143    /// Creates an empty signal accumulator.
1144    pub fn new() -> Self {
1145        Self {
1146            #[cfg(feature = "profiler")]
1147            origin: Instant::now(),
1148            #[cfg(feature = "profiler")]
1149            first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1150        }
1151    }
1152
1153    /// Captures a platform request timestamp only when profiling is enabled.
1154    ///
1155    /// The closure is not invoked in profiler-disabled builds.
1156    #[inline]
1157    pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1158        if cfg!(feature = "profiler") {
1159            Some(capture())
1160        } else {
1161            None
1162        }
1163    }
1164
1165    /// Records a platform frame request, retaining the first undrained timestamp.
1166    #[inline]
1167    #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1168    pub fn record(&self, at: Instant, source: FrameRequestSource) {
1169        #[cfg(feature = "profiler")]
1170        {
1171            let nanoseconds = at
1172                .saturating_duration_since(self.origin)
1173                .as_nanos()
1174                .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1175            let source_bit = match source {
1176                FrameRequestSource::NativeCallback => 0,
1177                FrameRequestSource::LocalSchedule => 1,
1178            };
1179            self.first_signal.fetch_min(
1180                (nanoseconds << 1) | source_bit,
1181                std::sync::atomic::Ordering::Relaxed,
1182            );
1183        }
1184    }
1185
1186    /// Drains the first platform frame request time and source, leaving the accumulator empty.
1187    #[inline]
1188    pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1189        #[cfg(feature = "profiler")]
1190        {
1191            let signal = self
1192                .first_signal
1193                .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1194            (signal != u64::MAX).then(|| {
1195                let source = match signal & 1 {
1196                    0 => FrameRequestSource::NativeCallback,
1197                    _ => FrameRequestSource::LocalSchedule,
1198                };
1199                (self.origin + Duration::from_nanos(signal >> 1), source)
1200            })
1201        }
1202        #[cfg(not(feature = "profiler"))]
1203        {
1204            None
1205        }
1206    }
1207}
1208
1209/// The application's lifecycle phase, as owned and reported by a mobile OS.
1210///
1211/// `Inactive` means visible but not receiving input (a system dialog on
1212/// top), while `Background` means not visible at all, with process death
1213/// possible at any time thereafter.
1214///
1215/// | Phase        | iOS                          | Android      |
1216/// |--------------|------------------------------|--------------|
1217/// | `Active`     | `didBecomeActive`            | `onResume`   |
1218/// | `Inactive`   | `willResignActive`           | `onPause`    |
1219/// | `Background` | `didEnterBackground`         | `onStop`     |
1220/// | `Foreground` | `willEnterForeground`        | `onStart`    |
1221#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1222pub enum AppLifecyclePhase {
1223    /// Foreground and receiving input.
1224    Active,
1225    /// Foreground (visible) but not receiving input.
1226    Inactive,
1227    /// Not visible. The GPU surface may be destroyed while backgrounded and
1228    /// the process may be killed without further notice.
1229    Background,
1230    /// Becoming visible again, before input is restored.
1231    Foreground,
1232    /// The native scene has disconnected. Its windows may reconnect later.
1233    /// This is not a process-termination notification or a guaranteed final
1234    /// opportunity to save state.
1235    Disconnected,
1236}
1237
1238/// Regions of a window that are obscured or reserved by the system.
1239///
1240/// Mobile applications often share space in their window with system-specific
1241/// geometry, from keyboards to camera notches. In GPUI, all this is abstracted
1242/// into a single "inset" which should be overlaid on the window's bounds.
1243/// It is up to the application develop to determine how to handle these cases.
1244#[derive(Debug, Clone, Default, PartialEq)]
1245pub struct WindowInsets {
1246    /// Regions covered by system UI or hardware: status bar, display
1247    /// cutouts/notch, home indicator, navigation bars.
1248    /// (iOS: `safeAreaInsets`. Android: `WindowInsets` of types
1249    /// `systemBars() | displayCutout()`.)
1250    pub safe_area: Edges<Pixels>,
1251    /// The region covered by the keyboard, when present.
1252    /// (iOS: derived from `keyboardWillShow`/frame-change notifications.
1253    /// Android: `WindowInsets.Type.ime()`.)
1254    pub ime: Edges<Pixels>,
1255    /// The radii of the window's visible corners where the display rounds
1256    /// them, and zero where corners are square or the platform can't say.
1257    /// Content inset from an edge by `d` lines up with the display by using a
1258    /// radius of `radius - d`. (iOS 26+: a concentric `UICornerConfiguration`.)
1259    pub corner_radii: Corners<Pixels>,
1260}
1261
1262impl WindowInsets {
1263    /// The combined inset content should avoid.
1264    pub fn effective(&self) -> Edges<Pixels> {
1265        Edges {
1266            top: self.safe_area.top.max(self.ime.top),
1267            right: self.safe_area.right.max(self.ime.right),
1268            bottom: self.safe_area.bottom.max(self.ime.bottom),
1269            left: self.safe_area.left.max(self.ime.left),
1270        }
1271    }
1272}
1273
1274/// A change in the state of the focused text input.
1275#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1276pub enum TextInputStateChange {
1277    /// The window changed from having no active text input to having one.
1278    FocusGained,
1279    /// The window no longer has an active text input.
1280    FocusLost,
1281    /// The selection or caret moved
1282    SelectionChanged,
1283    /// The document content changed outside of platform-initiated edits.
1284    ContentChanged,
1285}
1286
1287#[expect(missing_docs)]
1288pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1289    fn bounds(&self) -> Bounds<Pixels>;
1290    fn is_maximized(&self) -> bool;
1291    fn window_bounds(&self) -> WindowBounds;
1292    fn content_size(&self) -> Size<Pixels>;
1293    /// Returns the visible viewport in logical pixels relative to the content origin.
1294    ///
1295    /// This may be smaller or offset when a keyboard or zoom obscures content;
1296    /// it must not change the full layout size returned by `content_size`.
1297    /// Implementations should return a frame snapshot, not query platform layout here.
1298    fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1299        Bounds::new(Point::default(), self.content_size())
1300    }
1301    /// Registers a callback when visible geometry may have changed.
1302    ///
1303    /// This requests a frame; backends can sample the new viewport and safe-area
1304    /// geometry in `prepare_frame` rather than updating it inside the callback.
1305    fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1306    /// Samples platform geometry before a draw, returning whether view caches must be invalidated.
1307    ///
1308    /// Geometry getters must remain consistent throughout the ensuing draw.
1309    /// Do not invoke callbacks here: GPUI is already updating this window.
1310    fn prepare_frame(&self) -> bool {
1311        false
1312    }
1313    fn resize(&mut self, size: Size<Pixels>);
1314    fn scale_factor(&self) -> f32;
1315    fn appearance(&self) -> WindowAppearance;
1316    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1317    fn mouse_position(&self) -> Point<Pixels>;
1318    fn modifiers(&self) -> Modifiers;
1319    fn capslock(&self) -> Capslock;
1320    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1321    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1322    /// Apply the focused text region's [`TextInputConfiguration`] to the
1323    /// platform's text input session (e.g. attributes of the hidden editable
1324    /// element on web). Called only when the configuration changes, because
1325    /// reconfiguring a live input session can restart the IME connection.
1326    fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1327    fn prompt(
1328        &self,
1329        level: PromptLevel,
1330        msg: &str,
1331        detail: Option<&str>,
1332        answers: &[PromptButton],
1333    ) -> Option<oneshot::Receiver<usize>>;
1334    fn activate(&self);
1335    /// Shows a previously hidden window without synthesizing input. Returns
1336    /// false when unsupported. A supported backend calls `completed` after the
1337    /// native show, or with false if showing was cancelled or failed. A queued
1338    /// show checks `should_show` immediately before touching the native window.
1339    /// `activate` requests focus; false preserves the current foreground window.
1340    fn show_window(
1341        &self,
1342        _activate: bool,
1343        _should_show: Box<dyn FnOnce() -> bool>,
1344        _completed: Box<dyn FnOnce(bool)>,
1345    ) -> bool {
1346        false
1347    }
1348    /// Requests that the operating system draw attention to this window.
1349    fn request_attention(&self) {}
1350    fn is_active(&self) -> bool;
1351    /// The current [`WindowVisibility`]. Read once when the window is created;
1352    /// afterwards changes arrive through [`Self::on_visibility_change`].
1353    fn visibility(&self) -> WindowVisibility;
1354    fn is_hovered(&self) -> bool;
1355    fn background_appearance(&self) -> WindowBackgroundAppearance;
1356    fn set_title(&mut self, title: &str);
1357    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1358    /// Whether the window currently draws its [`WindowBackgroundAppearance`].
1359    /// `false` while a backend has to stand in for it: on macOS, a blurred
1360    /// window in native fullscreen whose desktop picture could not be shown
1361    /// behind the blur is drawn with the system window background instead.
1362    fn is_background_appearance_drawn(&self) -> bool {
1363        true
1364    }
1365    fn minimize(&self);
1366    fn zoom(&self);
1367    fn toggle_fullscreen(&self);
1368    fn is_fullscreen(&self) -> bool;
1369    /// Platform-specific diagnostic state, for [`App::debug_state`].
1370    fn debug_state(&self) -> serde_json::Value {
1371        serde_json::Value::Null
1372    }
1373    fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1374        None
1375    }
1376    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1377    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1378    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1379    /// Registers the callback invoked when [`Self::visibility`] changes. Only
1380    /// transitions are reported; the callback runs on the main thread outside
1381    /// of any window update.
1382    fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1383    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1384    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1385    fn on_moved(&self, callback: Box<dyn FnMut()>);
1386    /// Registers the callback invoked when the window moves to another
1387    /// display. Calls may be spurious. The callback runs on the main thread
1388    /// outside of any window update.
1389    fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1390    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1391    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1392    /// Caption hit-test position, when supplied by the native event. Existing
1393    /// backends may keep their coordinate-less callback implementation.
1394    fn on_hit_test_window_control_at(
1395        &self,
1396        mut callback: Box<dyn FnMut(Option<Point<Pixels>>) -> Option<WindowControlArea>>,
1397    ) {
1398        self.on_hit_test_window_control(Box::new(move || callback(None)));
1399    }
1400    fn on_close(&self, callback: Box<dyn FnOnce()>);
1401    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1402    fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1403    fn draw(&self, scene: &Scene);
1404    fn schedule_frame(&self) {}
1405    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1406    fn is_subpixel_rendering_supported(&self) -> bool;
1407
1408    // macOS specific methods
1409    fn get_title(&self) -> String {
1410        String::new()
1411    }
1412    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1413        None
1414    }
1415    fn tab_bar_visible(&self) -> bool {
1416        false
1417    }
1418    fn set_edited(&mut self, _edited: bool) {}
1419    fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1420    fn toggle_simple_fullscreen(&self) {}
1421    fn is_simple_fullscreen(&self) -> bool {
1422        false
1423    }
1424    #[cfg(target_os = "macos")]
1425    fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1426    #[cfg(target_os = "macos")]
1427    fn set_native_titlebar_visibility(&self, _visible: bool) {}
1428    fn show_character_palette(&self) {}
1429    fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1430    fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1431    fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1432    fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1433    fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1434    fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1435    fn merge_all_windows(&self) {}
1436    fn move_tab_to_new_window(&self) {}
1437    fn toggle_window_tab_overview(&self) {}
1438    fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1439
1440    fn native_window_state(&self) -> Option<Vec<u8>> {
1441        None
1442    }
1443    fn restore_native_window_state(&self, _state: &[u8]) {}
1444
1445    /// vue-native: Windows' composition device and the container visual drawn
1446    /// UNDER the app's surface, as owned `IDCompositionDevice` /
1447    /// `IDCompositionVisual` pointers the caller releases. `None` where the
1448    /// window does not present through DirectComposition.
1449    fn vn_composition_underlay(&self) -> Option<(usize, usize)> {
1450        None
1451    }
1452
1453    /// vue-native fork: maximizes or leaves the maximized state; unlike [`Self::zoom`], never toggles.
1454    fn vn_set_maximized(&self, maximized: bool) {
1455        if self.is_maximized() != maximized {
1456            self.zoom();
1457        }
1458    }
1459    /// vue-native fork: the platform's own maximized (zoomed) state.
1460    fn vn_is_zoomed(&self) -> bool {
1461        self.is_maximized()
1462    }
1463    /// vue-native fork: minimized, where the platform reports it.
1464    fn vn_is_minimized(&self) -> bool {
1465        false
1466    }
1467    /// vue-native fork: leaves the minimized state.
1468    fn vn_unminimize(&self) {}
1469    /// vue-native fork: hides the window without minimizing it. False where unsupported.
1470    fn vn_hide(&self) -> bool {
1471        false
1472    }
1473    /// vue-native fork: false while hidden by [`Self::vn_hide`] or not yet shown.
1474    fn vn_is_shown(&self) -> bool {
1475        true
1476    }
1477    /// vue-native fork: moves and/or resizes the outer frame, in the space of [`Self::bounds`].
1478    /// False when the platform does not let a client do what was asked.
1479    fn vn_set_frame(&self, _origin: Option<Point<Pixels>>, _size: Option<Size<Pixels>>) -> bool {
1480        false
1481    }
1482    /// vue-native fork: keeps the window above normal windows. False where unsupported.
1483    fn vn_set_always_on_top(&self, _on: bool) -> bool {
1484        false
1485    }
1486    /// vue-native fork: whether the platform's own maximize control is enabled.
1487    fn vn_set_maximizable(&self, _maximizable: bool) {}
1488    /// vue-native fork: lets pointer input pass through to what is below. False where unsupported.
1489    fn vn_set_ignore_mouse(&self, _ignore: bool) -> bool {
1490        false
1491    }
1492    /// vue-native fork: keeps the window's contents out of screen capture. False where unsupported.
1493    fn vn_set_content_protection(&self, _on: bool) -> bool {
1494        false
1495    }
1496    /// vue-native fork: closes as the platform's own close button would, so the should-close
1497    /// callback decides. Deferred: never runs inside the caller's update.
1498    fn vn_request_close(&self) {}
1499
1500    /// vue-native fork: hides the cursor and holds it in this window; mouse moves keep coming,
1501    /// their motion in [`PlatformWindow::take_pointer_motion`]. `unadjusted` asks for the
1502    /// device's own counts, without pointer acceleration. The platform lets go by itself when
1503    /// the window loses activation or closes.
1504    fn lock_pointer(&self, _unadjusted: bool) -> Result<(), PointerLockError> {
1505        Err(PointerLockError::Unsupported)
1506    }
1507    /// vue-native fork: shows the cursor again where it was when locked.
1508    fn unlock_pointer(&self) {}
1509    /// vue-native fork: still held ([`PlatformWindow::lock_pointer`])?
1510    fn is_pointer_locked(&self) -> bool {
1511        false
1512    }
1513    /// vue-native fork: the motion behind the mouse move being delivered while the pointer is
1514    /// locked, logical pixels (device counts when unadjusted).
1515    fn take_pointer_motion(&self) -> Option<Point<Pixels>> {
1516        None
1517    }
1518    /// vue-native fork: [`crate::Window::set_draws_while_occluded`].
1519    fn set_draws_while_occluded(&self, _on: bool) {}
1520    /// vue-native fork: [`crate::Window::set_hdr_output`]. False where the renderer has no HDR
1521    /// output.
1522    fn set_hdr_output(&self, _output: Option<HdrOutput>) -> bool {
1523        false
1524    }
1525
1526    // Linux specific methods
1527    fn inner_window_bounds(&self) -> WindowBounds {
1528        self.window_bounds()
1529    }
1530    fn request_decorations(&self, _decorations: WindowDecorations) {}
1531    fn show_window_menu(&self, _position: Point<Pixels>) {}
1532    fn start_window_move(&self) {}
1533    fn can_start_external_drag(&self) -> bool {
1534        false
1535    }
1536    fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1537        false
1538    }
1539    fn start_window_resize(&self, _edge: ResizeEdge) {}
1540    fn set_exclusive_zone(&self, _zone: Pixels) {}
1541    #[cfg(all(target_os = "linux", feature = "wayland"))]
1542    fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1543    fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1544    fn window_decorations(&self) -> Decorations {
1545        Decorations::Server
1546    }
1547    fn set_app_id(&mut self, _app_id: &str) {}
1548    fn map_window(&mut self) -> anyhow::Result<()> {
1549        Ok(())
1550    }
1551    fn window_controls(&self) -> WindowControls {
1552        WindowControls::default()
1553    }
1554    fn set_client_inset(&self, _inset: Pixels) {}
1555    fn set_client_corner_radii(&self, _radii: Corners<Pixels>) {}
1556    fn gpu_specs(&self) -> Option<GpuSpecs>;
1557
1558    fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1559
1560    // Mobile platform methods.
1561
1562    /// The regions of this window currently obscured or reserved by the
1563    /// system. Zero on platforms without such regions.
1564    fn insets(&self) -> WindowInsets {
1565        WindowInsets::default()
1566    }
1567
1568    /// Registers a callback invoked whenever [`Self::insets`] change.
1569    ///
1570    /// Contract: fires continuously during animated transitions (Android
1571    /// `WindowInsetsAnimation` progress; on iOS the platform interpolates
1572    /// the keyboard animation curve on frame ticks) and is exact at rest.
1573    fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1574
1575    /// Sets the handler for the system back action (Android back
1576    /// button/gesture; no source on iOS or desktop).
1577    fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1578
1579    /// Declares whether the application would currently handle the system
1580    /// back action (e.g. navigation depth > 0).
1581    fn set_back_enabled(&self, _enabled: bool) {}
1582
1583    /// Requests that the soft keyboard be shown.
1584    fn show_soft_keyboard(&self) {}
1585
1586    /// Requests that the soft keyboard be hidden.
1587    fn hide_soft_keyboard(&self) {}
1588
1589    /// Inform the operating system that the text input state has changed
1590    fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1591
1592    fn play_system_bell(&self) {}
1593
1594    /// Initialize the accessibility adapter with callbacks.
1595    fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1596
1597    /// Provide a TreeUpdate to the accessibility adapter.
1598    fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1599
1600    /// Inform the adapter of updated window bounds.
1601    fn a11y_update_window_bounds(&self) {}
1602
1603    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1604    fn as_test(&mut self) -> Option<&mut TestWindow> {
1605        None
1606    }
1607
1608    /// Renders the given scene to a texture and returns the pixel data as an RGBA image.
1609    /// This does not present the frame to screen - useful for visual testing where we want
1610    /// to capture what would be rendered without displaying it or requiring the window to be visible.
1611    // vue-native: ungated, see `Window::render_to_image`.
1612    fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1613        anyhow::bail!("render_to_image not implemented for this platform")
1614    }
1615
1616    /// vue-native fork: whether the renderer draws [`Scene::vn_captures`]
1617    /// and keeps them as snapshots for later frames.
1618    fn vn_supports_snapshots(&self) -> bool {
1619        false
1620    }
1621}
1622
1623/// vue-native fork: why [`PlatformWindow::lock_pointer`] did not lock.
1624#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1625pub enum PointerLockError {
1626    /// This platform (or this mode, `unadjusted`) cannot lock the pointer.
1627    Unsupported,
1628    /// The system refused: the window is not the active one, or a call failed.
1629    Refused,
1630}
1631
1632/// A renderer for headless windows that can produce real rendered output.
1633#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1634pub trait PlatformHeadlessRenderer {
1635    /// Render a scene and return the result as an RGBA image.
1636    fn render_scene_to_image(
1637        &mut self,
1638        scene: &Scene,
1639        size: Size<DevicePixels>,
1640    ) -> Result<RgbaImage>;
1641
1642    /// Render a scene to an offscreen target without reading the result back.
1643    ///
1644    /// This is the headless analogue of presenting a frame: it performs the
1645    /// same CPU-side scene encoding and GPU submission as drawing to a real
1646    /// window, but doesn't block on GPU completion or copy pixels back.
1647    fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1648
1649    /// Returns the sprite atlas used by this renderer.
1650    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1651}
1652
1653/// Type alias for runnables with metadata.
1654/// Previously an enum with a single variant, now simplified to a direct type alias.
1655#[doc(hidden)]
1656pub type RunnableVariant = Runnable<RunnableMeta>;
1657
1658#[doc(hidden)]
1659pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1660
1661#[doc(hidden)]
1662pub enum TasksIncluded {
1663    OnlyCompleted,
1664    CompletedAndRunning,
1665}
1666
1667/// This type is public so that our test macro can generate and use it, but it should not
1668/// be considered part of our public API.
1669#[doc(hidden)]
1670pub trait PlatformDispatcher: Send + Sync {
1671    fn is_main_thread(&self) -> bool;
1672    fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1673    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1674    fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1675
1676    fn dispatch_on_main_thread_when_idle(
1677        &self,
1678        runnable: RunnableVariant,
1679        timeout: Option<Duration>,
1680    ) {
1681        let _ = timeout;
1682        self.dispatch_on_main_thread(runnable, Priority::Low);
1683    }
1684
1685    fn idle_time_remaining(&self) -> Option<Duration> {
1686        None
1687    }
1688
1689    fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1690
1691    fn now(&self) -> Instant {
1692        Instant::now()
1693    }
1694
1695    fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1696        gpui_util::defer(Box::new(|| {}))
1697    }
1698
1699    fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1700        ActivityGuard::noop()
1701    }
1702
1703    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1704    fn as_test(&self) -> Option<&TestDispatcher> {
1705        None
1706    }
1707
1708    // This cfg must match the `threaded_dispatcher` module's, which implements
1709    // this method whenever it compiles.
1710    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1711    fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1712        None
1713    }
1714}
1715
1716#[expect(missing_docs)]
1717pub trait PlatformTextSystem: Send + Sync {
1718    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1719    /// vue-native fork: replaces the composed families
1720    /// ([`crate::TextSystem::set_composed_families`]). A platform that does
1721    /// not implement them resolves such a family by its name, as any other.
1722    fn set_composed_families(&self, _families: Vec<(SharedString, crate::FamilyComposer)>) {}
1723    /// Installs a nonblocking sink for unresolved grapheme clusters.
1724    fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1725    /// Get all available font names.
1726    fn all_font_names(&self) -> Vec<String>;
1727    /// Get the font ID for a font descriptor.
1728    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1729    /// Prewarm any system font caches needed to shape text.
1730    fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1731    /// Get metrics for a font.
1732    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1733    /// Get typographic bounds for a glyph.
1734    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1735    /// Get the advance width for a glyph.
1736    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1737    /// Get the glyph ID for a character.
1738    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1739    /// Get raster bounds for a glyph.
1740    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1741    /// Rasterize a glyph.
1742    fn rasterize_glyph(
1743        &self,
1744        params: &RenderGlyphParams,
1745        raster_bounds: Bounds<DevicePixels>,
1746    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1747    /// Layout a line of text with the given font runs.
1748    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1749    /// Returns the recommended text rendering mode for the given font and size.
1750    fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1751    -> TextRenderingMode;
1752    /// Returns the dilation level to use for a glyph painted in the given color.
1753    fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1754        0
1755    }
1756}
1757
1758#[expect(missing_docs)]
1759pub struct NoopTextSystem;
1760
1761#[expect(missing_docs)]
1762impl NoopTextSystem {
1763    #[allow(dead_code)]
1764    pub fn new() -> Self {
1765        Self
1766    }
1767}
1768
1769impl PlatformTextSystem for NoopTextSystem {
1770    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1771        Ok(())
1772    }
1773
1774    fn all_font_names(&self) -> Vec<String> {
1775        Vec::new()
1776    }
1777
1778    fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1779        Ok(FontId(1))
1780    }
1781
1782    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1783        FontMetrics {
1784            units_per_em: 1000,
1785            ascent: 1025.0,
1786            descent: -275.0,
1787            line_gap: 0.0,
1788            underline_position: -95.0,
1789            underline_thickness: 60.0,
1790            cap_height: 698.0,
1791            x_height: 516.0,
1792            bounding_box: Bounds {
1793                origin: Point {
1794                    x: -260.0,
1795                    y: -245.0,
1796                },
1797                size: Size {
1798                    width: 1501.0,
1799                    height: 1364.0,
1800                },
1801            },
1802        }
1803    }
1804
1805    fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1806        Ok(Bounds {
1807            origin: Point { x: 54.0, y: 0.0 },
1808            size: size(392.0, 528.0),
1809        })
1810    }
1811
1812    fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1813        Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1814    }
1815
1816    fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1817        Some(GlyphId(ch.len_utf16() as u32))
1818    }
1819
1820    fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1821        Ok(Default::default())
1822    }
1823
1824    fn rasterize_glyph(
1825        &self,
1826        _params: &RenderGlyphParams,
1827        raster_bounds: Bounds<DevicePixels>,
1828    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1829        Ok((raster_bounds.size, Vec::new()))
1830    }
1831
1832    fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1833        let mut position = px(0.);
1834        let metrics = self.font_metrics(FontId(0));
1835        let em_width = font_size
1836            * self
1837                .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1838                .unwrap()
1839                .width
1840            / metrics.units_per_em as f32;
1841        let mut glyphs = Vec::new();
1842        for (ix, c) in text.char_indices() {
1843            if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1844                glyphs.push(ShapedGlyph {
1845                    id: glyph,
1846                    position: point(position, px(0.)),
1847                    index: ix,
1848                    is_emoji: glyph.0 == 2,
1849                });
1850                if glyph.0 == 2 {
1851                    position += em_width * 2.0;
1852                } else {
1853                    position += em_width;
1854                }
1855            } else {
1856                position += em_width
1857            }
1858        }
1859        let mut runs = Vec::default();
1860        if !glyphs.is_empty() {
1861            runs.push(ShapedRun {
1862                font_id: FontId(0),
1863                glyphs,
1864            });
1865        } else {
1866            position = px(0.);
1867        }
1868
1869        LineLayout {
1870            font_size,
1871            width: position,
1872            ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1873            descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1874            runs,
1875            len: text.len(),
1876        }
1877    }
1878
1879    fn recommended_rendering_mode(
1880        &self,
1881        _font_id: FontId,
1882        _font_size: Pixels,
1883    ) -> TextRenderingMode {
1884        TextRenderingMode::Grayscale
1885    }
1886}
1887
1888// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.cpp
1889// Copyright (c) Microsoft Corporation.
1890// Licensed under the MIT license.
1891/// Compute gamma correction ratios for subpixel text rendering.
1892#[allow(dead_code)]
1893pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1894    const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1895        [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], // gamma = 1.0
1896        [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], // gamma = 1.1
1897        [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], // gamma = 1.2
1898        [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], // gamma = 1.3
1899        [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], // gamma = 1.4
1900        [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], // gamma = 1.5
1901        [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], // gamma = 1.6
1902        [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], // gamma = 1.7
1903        [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], // gamma = 1.8
1904        [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], // gamma = 1.9
1905        [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], // gamma = 2.0
1906        [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], // gamma = 2.1
1907        [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], // gamma = 2.2
1908    ];
1909
1910    const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1911    const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1912
1913    let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1914    let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1915
1916    [
1917        ratios[0] * NORM13,
1918        ratios[1] * NORM24,
1919        ratios[2] * NORM13,
1920        ratios[3] * NORM24,
1921    ]
1922}
1923
1924#[derive(PartialEq, Eq, Hash, Clone)]
1925#[expect(missing_docs)]
1926pub enum AtlasKey {
1927    Glyph(RenderGlyphParams),
1928    GlyphShadow(GlyphShadowParams),
1929    Svg(RenderSvgParams),
1930    Image(RenderImageParams),
1931}
1932
1933impl AtlasKey {
1934    /// Returns the texture kind for this atlas key.
1935    pub fn texture_kind(&self) -> AtlasTextureKind {
1936        match self {
1937            AtlasKey::Glyph(params) => {
1938                if params.is_emoji {
1939                    AtlasTextureKind::Polychrome
1940                } else if params.subpixel_rendering {
1941                    AtlasTextureKind::Subpixel
1942                } else {
1943                    AtlasTextureKind::Monochrome
1944                }
1945            }
1946            AtlasKey::GlyphShadow(_) | AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1947            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1948        }
1949    }
1950}
1951
1952impl From<RenderGlyphParams> for AtlasKey {
1953    fn from(params: RenderGlyphParams) -> Self {
1954        Self::Glyph(params)
1955    }
1956}
1957
1958impl From<RenderSvgParams> for AtlasKey {
1959    fn from(params: RenderSvgParams) -> Self {
1960        Self::Svg(params)
1961    }
1962}
1963
1964impl From<RenderImageParams> for AtlasKey {
1965    fn from(params: RenderImageParams) -> Self {
1966        Self::Image(params)
1967    }
1968}
1969
1970#[expect(missing_docs)]
1971pub trait PlatformAtlas {
1972    /// The builder runs with the atlas locked and must not re-enter the same atlas.
1973    fn get_or_insert_with<'a>(
1974        &self,
1975        key: AtlasKey,
1976        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1977    ) -> Result<Option<AtlasTile>>;
1978    fn remove(&self, key: &AtlasKey);
1979
1980    /// Fill the tile for `key` from a texture that is ALREADY in the renderer's
1981    /// own GPU memory, with no CPU round trip — the tile is allocated on the
1982    /// first call and overwritten in place on every call after it.
1983    ///
1984    /// This is the escape hatch for producers that decode straight onto the
1985    /// renderer's device (a hardware video decoder, a compute pass). The
1986    /// ordinary [`PlatformAtlas::get_or_insert_with`] path can only accept
1987    /// `Cow<[u8]>`, which for such a producer means GPU → system memory → GPU
1988    /// for pixels that never needed to leave VRAM.
1989    ///
1990    /// Unlike `get_or_insert_with` this is **not** memoised on the key: a
1991    /// caller that keeps ONE key per element and calls this once per frame gets
1992    /// one stable tile updated in place, which is the point — a fresh key per
1993    /// frame would allocate and free an atlas tile every frame.
1994    ///
1995    /// Returns `Ok(None)` when the backend has no GPU path, when the handle is
1996    /// null, or when the texture is not one this atlas can copy from (wrong
1997    /// device, wrong format, too small). `None` is not an error: the caller is
1998    /// expected to have a CPU fallback, and the reason is logged once.
1999    ///
2000    /// # Contract
2001    ///
2002    /// `texture` is BORROWED for the duration of the call. On Windows it must
2003    /// be an `ID3D11Texture2D` created on the device that
2004    /// `gpui_windows::renderer_d3d11_device()` publishes, in
2005    /// `DXGI_FORMAT_B8G8R8A8_UNORM`, at least `size` in each dimension.
2006    fn upload_from_gpu(
2007        &self,
2008        _key: &AtlasKey,
2009        _size: Size<DevicePixels>,
2010        _texture: GpuTextureHandle,
2011    ) -> Result<Option<AtlasTile>> {
2012        Ok(None)
2013    }
2014
2015    /// Copies a straight-alpha BGRA8 D3D12 texture on this atlas's device.
2016    /// The source is in RENDER_TARGET state before and after the copy. Its
2017    /// producer signals `ready_fence` at `ready_value`; the consumer waits on
2018    /// its GPU queue. `owner` retains the producer allocation and fence until
2019    /// the copy completes, not merely until this function returns.
2020    fn upload_from_d3d12(
2021        &self,
2022        _key: &AtlasKey,
2023        _size: Size<DevicePixels>,
2024        _texture: D3D12TextureHandle,
2025        _owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2026    ) -> Result<Option<AtlasTile>> {
2027        Ok(None)
2028    }
2029
2030    /// vue-native fork: copies a straight-alpha `BGRA8Unorm` (or `_sRGB`)
2031    /// `id<MTLTexture>` on this atlas's device into the tile for `key`, on the
2032    /// renderer's queue. With `ready` (an `id<MTLSharedEvent>` and a value)
2033    /// the copy waits on the GPU until the event reaches it; without, the
2034    /// texture must already be written. `owner` is retained until the copy
2035    /// completes.
2036    fn upload_from_metal(
2037        &self,
2038        _key: &AtlasKey,
2039        _size: Size<DevicePixels>,
2040        _texture: GpuTextureHandle,
2041        _ready: Option<(*mut std::ffi::c_void, u64)>,
2042        _owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2043    ) -> Result<Option<AtlasTile>> {
2044        Ok(None)
2045    }
2046
2047    /// vue-native fork: the tile `key` maps to now, if any. `None` from a
2048    /// backend that does not say, which makes every
2049    /// [`crate::Window::write_image_tile`] report a moved tile: correct, only
2050    /// never the cheap path.
2051    fn tile(&self, _key: &AtlasKey) -> Option<AtlasTile> {
2052        None
2053    }
2054
2055    /// vue-native fork: writes `bytes` (`size`, in the key's texture format,
2056    /// rows packed) into the tile for `key`, overwriting it in place when it
2057    /// exists at this size and taking a new one otherwise. The CPU twin of
2058    /// [`PlatformAtlas::upload_from_gpu`]: not memoised, one tile per key.
2059    ///
2060    /// `Ok(None)` when the backend has no such path; the caller then removes
2061    /// the key and inserts it again, which always works but moves the tile.
2062    fn write_bytes(
2063        &self,
2064        _key: &AtlasKey,
2065        _size: Size<DevicePixels>,
2066        _bytes: &[u8],
2067    ) -> Result<Option<AtlasTile>> {
2068        Ok(None)
2069    }
2070
2071    /// vue-native fork: [`PlatformAtlas::write_bytes`] into an
2072    /// [`AtlasTextureKind::PolychromeHdr`] tile: `bytes` are RGBA half floats, 8 a pixel.
2073    /// `Ok(None)` from a backend without HDR tiles.
2074    fn write_hdr_bytes(
2075        &self,
2076        _key: &AtlasKey,
2077        _size: Size<DevicePixels>,
2078        _bytes: &[u8],
2079    ) -> Result<Option<AtlasTile>> {
2080        Ok(None)
2081    }
2082
2083    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2084    fn contains(&self, _key: &AtlasKey) -> bool {
2085        false
2086    }
2087
2088    /// vue-native fork: the atlas's footprint, per texture kind — for an
2089    /// embedder's memory report. `None` from a backend that does not keep
2090    /// count.
2091    fn stats(&self) -> Option<AtlasStats> {
2092        None
2093    }
2094}
2095
2096/// vue-native fork: one [`AtlasTextureKind`]'s pages in a sprite atlas.
2097#[derive(Clone, Copy, Debug, Default)]
2098pub struct AtlasKindStats {
2099    /// Live texture pages of this kind.
2100    pub pages: u32,
2101    /// Their GPU bytes: width × height × bytes per pixel, one mip level.
2102    pub bytes: u64,
2103    /// Tiles allocated in them.
2104    pub tiles: u32,
2105    /// The pixels those tiles cover, padding included — against `bytes`, how
2106    /// full the pages are.
2107    pub tile_pixels: u64,
2108}
2109
2110/// vue-native fork: a sprite atlas's footprint, indexed by
2111/// `AtlasTextureKind as usize` (monochrome, polychrome, subpixel, polychrome HDR).
2112#[derive(Clone, Copy, Debug, Default)]
2113pub struct AtlasStats {
2114    /// Per kind.
2115    pub kinds: [AtlasKindStats; 4],
2116    /// Keys mapped to a tile (glyphs, SVG rasters, image frames).
2117    pub keys: u32,
2118    /// Of those, image frames (`AtlasKey::Image`) and their tile pixels.
2119    pub image_keys: u32,
2120    /// Pixels the image tiles cover.
2121    pub image_pixels: u64,
2122}
2123
2124/// A borrowed, platform-defined handle to a texture that already lives in the
2125/// GPU memory of the renderer's own device. See
2126/// [`PlatformAtlas::upload_from_gpu`].
2127///
2128/// Deliberately a raw pointer rather than a typed COM/Metal object: the
2129/// producer is usually a different crate compiled against a different version
2130/// of the platform bindings, and a COM interface pointer is an ABI, not a type.
2131/// Same reasoning as `gpui_windows::renderer_d3d11_device`.
2132#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2133pub struct GpuTextureHandle(pub *mut std::ffi::c_void);
2134
2135/// Borrowed D3D12 resource and producer fence. Both pointers remain valid
2136/// through the owner passed to [`PlatformAtlas::upload_from_d3d12`].
2137#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2138pub struct D3D12TextureHandle {
2139    /// ID3D12Resource, BGRA8_UNORM, RENDER_TARGET state.
2140    pub resource: *mut std::ffi::c_void,
2141    /// ID3D12Fence signalled by the producer queue after its last write.
2142    pub ready_fence: *mut std::ffi::c_void,
2143    /// Producer submission fence value.
2144    pub ready_value: u64,
2145}
2146
2147/// vue-native fork: the Metal device and a command queue the renderer draws
2148/// with (`id<MTLDevice>`, `id<MTLCommandQueue>`), retained by `keep_alive`.
2149/// `generation` changes when a renderer comes up on another device.
2150#[derive(Clone)]
2151pub struct MetalDeviceLease {
2152    /// `id<MTLDevice>`.
2153    pub device: *mut std::ffi::c_void,
2154    /// `id<MTLCommandQueue>` of the first renderer on that device.
2155    pub queue: *mut std::ffi::c_void,
2156    /// Starts at 1.
2157    pub generation: u64,
2158    /// Retains both objects.
2159    pub keep_alive: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2160}
2161
2162// SAFETY: Metal devices and command queues are thread-safe; `keep_alive` retains them.
2163unsafe impl Send for MetalDeviceLease {}
2164unsafe impl Sync for MetalDeviceLease {}
2165
2166static RENDERER_METAL_DEVICE: std::sync::Mutex<Option<MetalDeviceLease>> =
2167    std::sync::Mutex::new(None);
2168
2169/// vue-native fork: the Metal device the newest renderer draws with, once a
2170/// window has made one; `None` on other backends.
2171pub fn renderer_metal_device() -> Option<MetalDeviceLease> {
2172    RENDERER_METAL_DEVICE
2173        .lock()
2174        .unwrap_or_else(|p| p.into_inner())
2175        .clone()
2176}
2177
2178/// vue-native fork: called by the Metal renderer when it is created. A
2179/// renderer on the published device keeps the lease as it is.
2180#[doc(hidden)]
2181pub fn publish_renderer_metal_device(
2182    device: *mut std::ffi::c_void,
2183    queue: *mut std::ffi::c_void,
2184    keep_alive: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2185) {
2186    let mut published = RENDERER_METAL_DEVICE
2187        .lock()
2188        .unwrap_or_else(|p| p.into_inner());
2189    let generation = match published.as_ref() {
2190        Some(lease) if lease.device == device => return,
2191        Some(lease) => lease.generation + 1,
2192        None => 1,
2193    };
2194    *published = Some(MetalDeviceLease {
2195        device,
2196        queue,
2197        generation,
2198        keep_alive,
2199    });
2200}
2201
2202/// vue-native fork: a window drawing high dynamic range. The scene still blends in sRGB-encoded
2203/// space, into a half-float target where [`AtlasTextureKind::PolychromeHdr`] sprites can exceed
2204/// 1.0; the output is that linearised and multiplied by `sdr_white`.
2205#[derive(Copy, Clone, Debug, PartialEq)]
2206pub struct HdrOutput {
2207    /// SDR white in the swap chain's linear unit: SDR white nits / 80 for Windows' scRGB, 1.0 for
2208    /// macOS EDR.
2209    pub sdr_white: f32,
2210}
2211
2212/// vue-native fork: IEEE binary16 bits to `f32`, for the renderers' half-float readbacks.
2213#[doc(hidden)]
2214pub fn half_to_f32(bits: u16) -> f32 {
2215    let exponent = (bits >> 10) & 0x1f;
2216    let mantissa = u32::from(bits & 0x3ff);
2217    let magnitude = match exponent {
2218        0 => mantissa as f32 / 16_777_216.0,
2219        31 if mantissa == 0 => f32::INFINITY,
2220        31 => f32::NAN,
2221        _ => f32::from_bits(((u32::from(exponent) + 112) << 23) | (mantissa << 13)),
2222    };
2223    if bits & 0x8000 != 0 {
2224        -magnitude
2225    } else {
2226        magnitude
2227    }
2228}
2229
2230/// vue-native fork: where [`crate::Window::write_image_tile`] takes a frame's
2231/// pixels from.
2232#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2233pub enum TileSource {
2234    /// The image's own bytes (BGRA, straight alpha, as every sprite tile
2235    /// holds them), e.g. from
2236    /// [`crate::RenderImage::successor`].
2237    Bytes,
2238    /// A texture already on the renderer's device, with the contract of
2239    /// [`PlatformAtlas::upload_from_gpu`].
2240    Gpu(GpuTextureHandle),
2241}
2242
2243/// vue-native fork: what [`crate::Window::write_image_tile`] did with a frame.
2244#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2245pub enum TileWrite {
2246    /// The tile the key had was overwritten where it lies. A scene that
2247    /// painted the image samples the new pixels on its next present
2248    /// ([`crate::Window::request_present`]).
2249    InPlace,
2250    /// The frame went into a tile the key did not have before this write (the
2251    /// first write, a new size, a backend with no in-place path, a tile the
2252    /// atlas had dropped). Only a draw shows it.
2253    Placed,
2254    /// The backend refused the GPU texture; nothing was written. The caller
2255    /// falls back to [`TileSource::Bytes`].
2256    Refused,
2257}
2258
2259impl GpuTextureHandle {
2260    /// The null handle — "there is no texture", which every backend rejects.
2261    pub const NULL: Self = Self(std::ptr::null_mut());
2262
2263    /// Is this the null handle?
2264    pub fn is_null(&self) -> bool {
2265        self.0.is_null()
2266    }
2267}
2268
2269#[doc(hidden)]
2270pub trait AtlasBackend {
2271    fn insert(
2272        &mut self,
2273        kind: AtlasTextureKind,
2274        size: Size<DevicePixels>,
2275        bytes: &[u8],
2276    ) -> Result<AtlasTile>;
2277
2278    fn remove(&mut self, tile: AtlasTile);
2279}
2280
2281#[doc(hidden)]
2282pub struct AtlasState<Backend> {
2283    tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
2284    pub backend: Backend,
2285}
2286
2287impl<Backend> AtlasState<Backend> {
2288    pub fn new(backend: Backend) -> Self {
2289        Self {
2290            tiles_by_key: FxHashMap::default(),
2291            backend,
2292        }
2293    }
2294
2295    pub fn contains(&self, key: &AtlasKey) -> bool {
2296        self.tiles_by_key.contains_key(key)
2297    }
2298
2299    pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
2300        self.tiles_by_key.clear();
2301        reset_backend(&mut self.backend);
2302    }
2303
2304    /// vue-native fork: the tile `key` maps to, if any. For a backend's
2305    /// [`PlatformAtlas::upload_from_gpu`], which reuses one tile per key in
2306    /// place rather than memoising a build.
2307    pub fn tile(&self, key: &AtlasKey) -> Option<AtlasTile> {
2308        self.tiles_by_key.get(key).copied()
2309    }
2310
2311    /// vue-native fork: records a tile the backend allocated itself (the
2312    /// `upload_from_gpu` path) so [`AtlasState::remove`] and [`AtlasState::clear`]
2313    /// free it like any other.
2314    pub fn insert_tile(&mut self, key: AtlasKey, tile: AtlasTile) {
2315        self.tiles_by_key.insert(key, tile);
2316    }
2317
2318    /// vue-native fork: fills the key counts of an [`AtlasStats`] — how many
2319    /// keys map to a tile, and how many of those are image frames and what
2320    /// they cover. The backend fills the per-kind pages.
2321    pub fn count_keys(&self, stats: &mut AtlasStats) {
2322        stats.keys = self.tiles_by_key.len() as u32;
2323        for (key, tile) in &self.tiles_by_key {
2324            let pixels =
2325                (tile.bounds.size.width.0.max(0) as u64) * (tile.bounds.size.height.0.max(0) as u64);
2326            stats.kinds[tile.texture_id.kind as usize].tile_pixels += pixels;
2327            if let AtlasKey::Image(_) = key {
2328                stats.image_keys += 1;
2329                stats.image_pixels += pixels;
2330            }
2331        }
2332    }
2333}
2334
2335impl<Backend: Default> Default for AtlasState<Backend> {
2336    fn default() -> Self {
2337        Self::new(Backend::default())
2338    }
2339}
2340
2341impl<Backend: AtlasBackend> AtlasState<Backend> {
2342    pub fn get_or_insert_with<'a>(
2343        &mut self,
2344        key: AtlasKey,
2345        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2346    ) -> Result<Option<AtlasTile>> {
2347        match self.tiles_by_key.entry(key) {
2348            Entry::Occupied(entry) => Ok(Some(*entry.get())),
2349            Entry::Vacant(entry) => {
2350                profiling::scope!("new tile");
2351                let Some((size, bytes)) = build()? else {
2352                    return Ok(None);
2353                };
2354                let tile = self
2355                    .backend
2356                    .insert(entry.key().texture_kind(), size, &bytes)?;
2357                entry.insert(tile);
2358                Ok(Some(tile))
2359            }
2360        }
2361    }
2362
2363    pub fn remove(&mut self, key: &AtlasKey) {
2364        if let Some(tile) = self.tiles_by_key.remove(key) {
2365            self.backend.remove(tile);
2366        }
2367    }
2368}
2369
2370/// A sprite atlas for windows without a GPU. It hands out uniquely identified
2371/// tiles without uploading any pixels, so glyph, SVG, and image painting can
2372/// run to completion in tests and headless platforms.
2373#[derive(Default)]
2374pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
2375
2376#[doc(hidden)]
2377#[derive(Default)]
2378pub struct HeadlessAtlasBackend {
2379    next_id: u32,
2380}
2381
2382impl AtlasBackend for HeadlessAtlasBackend {
2383    fn insert(
2384        &mut self,
2385        kind: AtlasTextureKind,
2386        size: Size<DevicePixels>,
2387        _bytes: &[u8],
2388    ) -> Result<AtlasTile> {
2389        self.next_id += 1;
2390        let texture_id = self.next_id;
2391        self.next_id += 1;
2392        let tile_id = self.next_id;
2393        Ok(AtlasTile {
2394            texture_id: AtlasTextureId {
2395                index: texture_id,
2396                kind,
2397            },
2398            tile_id: TileId(tile_id),
2399            padding: 0,
2400            bounds: Bounds {
2401                origin: Point::default(),
2402                size,
2403            },
2404        })
2405    }
2406
2407    fn remove(&mut self, _tile: AtlasTile) {}
2408}
2409
2410impl PlatformAtlas for HeadlessAtlas {
2411    fn get_or_insert_with<'a>(
2412        &self,
2413        key: AtlasKey,
2414        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2415    ) -> Result<Option<AtlasTile>> {
2416        self.0.lock().get_or_insert_with(key, build)
2417    }
2418
2419    fn remove(&self, key: &AtlasKey) {
2420        self.0.lock().remove(key);
2421    }
2422
2423    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2424    fn contains(&self, key: &AtlasKey) -> bool {
2425        self.0.lock().contains(key)
2426    }
2427}
2428
2429#[doc(hidden)]
2430pub struct AtlasTextureList<T> {
2431    pub textures: Vec<Option<T>>,
2432    pub free_list: Vec<usize>,
2433}
2434
2435impl<T> Default for AtlasTextureList<T> {
2436    fn default() -> Self {
2437        Self {
2438            textures: Vec::default(),
2439            free_list: Vec::default(),
2440        }
2441    }
2442}
2443
2444impl<T> ops::Index<usize> for AtlasTextureList<T> {
2445    type Output = Option<T>;
2446
2447    fn index(&self, index: usize) -> &Self::Output {
2448        &self.textures[index]
2449    }
2450}
2451
2452impl<T> AtlasTextureList<T> {
2453    #[allow(unused)]
2454    pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2455        self.free_list.clear();
2456        self.textures.drain(..)
2457    }
2458
2459    #[allow(dead_code)]
2460    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2461        self.textures.iter_mut().flatten()
2462    }
2463}
2464
2465#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2466#[repr(C)]
2467#[expect(missing_docs)]
2468pub struct AtlasTile {
2469    /// The texture this tile belongs to.
2470    pub texture_id: AtlasTextureId,
2471    /// The unique ID of this tile within its texture.
2472    pub tile_id: TileId,
2473    /// Padding around the tile content in pixels.
2474    pub padding: u32,
2475    /// The bounds of this tile within the texture.
2476    pub bounds: Bounds<DevicePixels>,
2477}
2478
2479#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2480#[repr(C)]
2481#[expect(missing_docs)]
2482pub struct AtlasTextureId {
2483    // We use u32 instead of usize for Metal Shader Language compatibility
2484    /// The index of this texture in the atlas.
2485    pub index: u32,
2486    /// The kind of content stored in this texture.
2487    pub kind: AtlasTextureKind,
2488}
2489
2490#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2491#[repr(C)]
2492#[cfg_attr(
2493    all(
2494        any(target_os = "linux", target_os = "freebsd"),
2495        not(any(feature = "x11", feature = "wayland"))
2496    ),
2497    allow(dead_code)
2498)]
2499#[expect(missing_docs)]
2500pub enum AtlasTextureKind {
2501    Monochrome = 0,
2502    Polychrome = 1,
2503    Subpixel = 2,
2504    /// vue-native fork: RGBA half floats in linear extended sRGB (1.0 is SDR white), straight
2505    /// alpha. A sprite encodes them to sRGB after clamping to its [`PolychromeSprite`]'s
2506    /// headroom, so values above 1.0 reach an HDR target ([`HdrOutput`]).
2507    ///
2508    /// [`PolychromeSprite`]: crate::PolychromeSprite
2509    PolychromeHdr = 3,
2510}
2511
2512#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2513#[repr(C)]
2514#[expect(missing_docs)]
2515pub struct TileId(pub u32);
2516
2517impl From<etagere::AllocId> for TileId {
2518    fn from(id: etagere::AllocId) -> Self {
2519        Self(id.serialize())
2520    }
2521}
2522
2523impl From<TileId> for etagere::AllocId {
2524    fn from(id: TileId) -> Self {
2525        Self::deserialize(id.0)
2526    }
2527}
2528
2529#[expect(missing_docs)]
2530pub struct PlatformInputHandler {
2531    cx: AsyncWindowContext,
2532    handler: Box<dyn InputHandler>,
2533    focus_id: Option<crate::FocusId>,
2534}
2535
2536#[expect(missing_docs)]
2537#[cfg_attr(
2538    all(
2539        any(target_os = "linux", target_os = "freebsd"),
2540        not(any(feature = "x11", feature = "wayland"))
2541    ),
2542    allow(dead_code)
2543)]
2544impl PlatformInputHandler {
2545    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2546        Self {
2547            cx,
2548            handler,
2549            focus_id: None,
2550        }
2551    }
2552
2553    pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2554        self.focus_id = Some(focus_id);
2555        self
2556    }
2557
2558    /// Identifies the input field registered through [`Window::handle_input`].
2559    ///
2560    /// This identity survives adapter replacement during repaint. Backends can
2561    /// use it to detect a field change without restarting the keyboard session.
2562    pub fn focus_id(&self) -> Option<crate::FocusId> {
2563        self.focus_id
2564    }
2565
2566    pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2567        self.cx
2568            .update(|window, cx| {
2569                self.handler
2570                    .selected_text_range(ignore_disabled_input, window, cx)
2571            })
2572            .ok()
2573            .flatten()
2574    }
2575
2576    #[cfg_attr(target_os = "windows", allow(dead_code))]
2577    pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2578        self.cx
2579            .update(|window, cx| self.handler.marked_text_range(window, cx))
2580            .ok()
2581            .flatten()
2582    }
2583
2584    #[cfg_attr(
2585        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2586        allow(dead_code)
2587    )]
2588    pub fn text_for_range(
2589        &mut self,
2590        range_utf16: Range<usize>,
2591        adjusted: &mut Option<Range<usize>>,
2592    ) -> Option<String> {
2593        self.cx
2594            .update(|window, cx| {
2595                self.handler
2596                    .text_for_range(range_utf16, adjusted, window, cx)
2597            })
2598            .ok()
2599            .flatten()
2600    }
2601
2602    pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2603        self.cx
2604            .update(|window, cx| {
2605                self.handler
2606                    .replace_text_in_range(replacement_range, text, window, cx);
2607            })
2608            .ok();
2609    }
2610
2611    pub fn replace_and_mark_text_in_range(
2612        &mut self,
2613        range_utf16: Option<Range<usize>>,
2614        new_text: &str,
2615        new_selected_range: Option<Range<usize>>,
2616    ) {
2617        self.cx
2618            .update(|window, cx| {
2619                self.handler.replace_and_mark_text_in_range(
2620                    range_utf16,
2621                    new_text,
2622                    new_selected_range,
2623                    window,
2624                    cx,
2625                )
2626            })
2627            .ok();
2628    }
2629
2630    #[cfg_attr(target_os = "windows", allow(dead_code))]
2631    pub fn unmark_text(&mut self) {
2632        self.cx
2633            .update(|window, cx| self.handler.unmark_text(window, cx))
2634            .ok();
2635    }
2636
2637    pub fn paste(&mut self, item: ClipboardItem) {
2638        self.cx
2639            .update(|window, cx| self.handler.paste(item, window, cx))
2640            .ok();
2641    }
2642
2643    pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2644        self.cx
2645            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2646            .ok()
2647            .flatten()
2648    }
2649
2650    pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2651        self.cx
2652            .update(|window, cx| {
2653                self.handler
2654                    .selection_bounds_for_range(range_utf16, window, cx)
2655            })
2656            .unwrap_or_default()
2657    }
2658
2659    #[allow(dead_code)]
2660    pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2661        self.handler.apple_press_and_hold_enabled()
2662    }
2663
2664    pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2665        self.handler.replace_text_in_range(None, input, window, cx);
2666    }
2667
2668    pub fn compute_ime_candidate_bounds(
2669        marked_range: Option<Range<usize>>,
2670        selection: &UTF16Selection,
2671        mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2672    ) -> Option<Bounds<Pixels>> {
2673        if let Some(marked_range) = marked_range {
2674            // Default to the start of the marked (composing) range.
2675            let mut line_start = marked_range.start;
2676
2677            // Walk backward from the caret looking for a line break. A change in
2678            // the Y coordinate means we crossed into the previous visual line, so
2679            // the line start is one position after the break point.
2680            let caret = selection.range.end;
2681            if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2682                for i in (marked_range.start..caret).rev() {
2683                    if let Some(b) = bounds_for_range(i..i) {
2684                        if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2685                            line_start = i + 1;
2686                            break;
2687                        }
2688                    }
2689                }
2690            }
2691            bounds_for_range(line_start..line_start)
2692        } else {
2693            // No active composition — use the selection endpoint.
2694            let offset = if selection.reversed {
2695                selection.range.start
2696            } else {
2697                selection.range.end
2698            };
2699            bounds_for_range(offset..offset)
2700        }
2701    }
2702
2703    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2704        let marked_range = self.handler.marked_text_range(window, cx);
2705        let selection = self.handler.selected_text_range(true, window, cx)?;
2706        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2707            self.handler.bounds_for_range(range, window, cx)
2708        })
2709    }
2710
2711    pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2712        let marked_range = self.marked_text_range();
2713        let selection = self.selected_text_range(true)?;
2714        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2715            self.bounds_for_range(range)
2716        })
2717    }
2718
2719    #[allow(unused)]
2720    pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2721        self.cx
2722            .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2723            .ok()
2724            .flatten()
2725    }
2726
2727    /// See [`InputHandler::set_selected_text_range`].
2728    pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2729        self.cx
2730            .update(|window, cx| {
2731                self.handler
2732                    .set_selected_text_range(range_utf16, window, cx)
2733            })
2734            .ok();
2735    }
2736
2737    /// See [`InputHandler::element_bounds`].
2738    pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2739        self.cx
2740            .update(|window, cx| self.handler.element_bounds(window, cx))
2741            .ok()
2742            .flatten()
2743    }
2744
2745    /// See [`InputHandler::text_length_utf16`].
2746    pub fn text_length_utf16(&mut self) -> Option<usize> {
2747        self.cx
2748            .update(|window, cx| self.handler.text_length_utf16(window, cx))
2749            .ok()
2750            .flatten()
2751    }
2752
2753    #[allow(dead_code)]
2754    pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2755        self.handler.accepts_text_input(window, cx)
2756    }
2757
2758    #[allow(dead_code)]
2759    pub fn query_accepts_text_input(&mut self) -> bool {
2760        self.cx
2761            .update(|window, cx| self.handler.accepts_text_input(window, cx))
2762            .unwrap_or(true)
2763    }
2764
2765    /// Checks eligibility against the current focus, including before the next frame is drawn.
2766    ///
2767    /// Unlike the legacy acceptance query, this fails closed when the window cannot
2768    /// be updated and requires registration through `Window::handle_input`.
2769    pub fn query_accepts_focused_text_input(&mut self) -> bool {
2770        let focus_id = self.focus_id;
2771        self.cx
2772            .update(|window, cx| {
2773                focus_id.is_some()
2774                    && window.focus == focus_id
2775                    && self.handler.accepts_text_input(window, cx)
2776            })
2777            .unwrap_or(false)
2778    }
2779
2780    /// See [`InputHandler::prefers_ime_for_printable_keys`].
2781    ///
2782    /// This is not a pure delegation to the handler: while a multi-stroke binding is pending this
2783    /// returns `false` regardless of the handler's preference, because the next printable key may
2784    /// complete a binding whose prefix already bypassed the IME.
2785    pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2786        self.cx
2787            .update(|window, cx| {
2788                // The next printable key may complete a chord whose prefix bypassed the IME.
2789                !window.has_pending_keystrokes()
2790                    && self.handler.prefers_ime_for_printable_keys(window, cx)
2791            })
2792            .unwrap_or(false)
2793    }
2794
2795    /// See [`InputHandler::text_input_configuration`].
2796    pub fn text_input_configuration(
2797        &mut self,
2798        window: &mut Window,
2799        cx: &mut App,
2800    ) -> TextInputConfiguration {
2801        self.handler.text_input_configuration(window, cx)
2802    }
2803
2804    /// See [`InputHandler::text_input_editable_range`].
2805    pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2806        self.cx
2807            .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2808            .ok()
2809            .flatten()
2810    }
2811}
2812
2813/// A struct representing a selection in a text buffer, in UTF16 characters.
2814/// This is different from a range because the head may be before the tail.
2815#[derive(Debug)]
2816pub struct UTF16Selection {
2817    /// The range of text in the document this selection corresponds to
2818    /// in UTF16 characters.
2819    pub range: Range<usize>,
2820    /// Whether the head of this selection is at the start (true), or end (false)
2821    /// of the range
2822    pub reversed: bool,
2823}
2824
2825/// GPUI's interface for native text input, IME composition, and selection.
2826/// Platform backends translate their native text protocols into these operations.
2827///
2828/// Text offsets and ranges use UTF-16 code units unless stated otherwise.
2829pub trait InputHandler: 'static {
2830    /// Get the range of the user's currently selected text, if any
2831    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
2832    ///
2833    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
2834    fn selected_text_range(
2835        &mut self,
2836        ignore_disabled_input: bool,
2837        window: &mut Window,
2838        cx: &mut App,
2839    ) -> Option<UTF16Selection>;
2840
2841    /// Get the range of the currently marked text, if any
2842    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
2843    ///
2844    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
2845    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2846
2847    /// Get the text for the given document range in UTF-16 characters
2848    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
2849    ///
2850    /// range_utf16 is in terms of UTF-16 characters
2851    fn text_for_range(
2852        &mut self,
2853        range_utf16: Range<usize>,
2854        adjusted_range: &mut Option<Range<usize>>,
2855        window: &mut Window,
2856        cx: &mut App,
2857    ) -> Option<String>;
2858
2859    /// Replace the text in the given document range with the given text
2860    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
2861    ///
2862    /// replacement_range is in terms of UTF-16 characters
2863    fn replace_text_in_range(
2864        &mut self,
2865        replacement_range: Option<Range<usize>>,
2866        text: &str,
2867        window: &mut Window,
2868        cx: &mut App,
2869    );
2870
2871    /// Replace the text in the given document range with the given text,
2872    /// and mark the given text as part of an IME 'composing' state
2873    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
2874    ///
2875    /// range_utf16 is in terms of UTF-16 characters
2876    /// new_selected_range is in terms of UTF-16 characters
2877    fn replace_and_mark_text_in_range(
2878        &mut self,
2879        range_utf16: Option<Range<usize>>,
2880        new_text: &str,
2881        new_selected_range: Option<Range<usize>>,
2882        window: &mut Window,
2883        cx: &mut App,
2884    );
2885
2886    /// Remove the IME 'composing' state from the document
2887    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
2888    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2889
2890    /// Insert a platform-initiated paste at the current selection.
2891    ///
2892    /// Platforms that deliver paste as an input event rather than through an
2893    /// application-defined action (e.g. the DOM `paste` event on web) call
2894    /// this with the full clipboard contents. The default implementation
2895    /// inserts only the plain-text portion of the item.
2896    fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2897        if let Some(text) = item.text() {
2898            self.replace_text_in_range(None, &text, window, cx);
2899        }
2900    }
2901
2902    /// Get the bounds of the given document range in window coordinates.
2903    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
2904    ///
2905    /// This is used for positioning the IME candidate window
2906    fn bounds_for_range(
2907        &mut self,
2908        range_utf16: Range<usize>,
2909        window: &mut Window,
2910        cx: &mut App,
2911    ) -> Option<Bounds<Pixels>>;
2912
2913    /// Returns selection rectangles in document order, in window coordinates.
2914    ///
2915    /// Return line or shaped-run fragments, not one rectangle per character. The
2916    /// first and last rectangles contain the range's start and end respectively.
2917    /// Empty means native selection geometry is unavailable; caret/IME geometry can
2918    /// still be supplied by `bounds_for_range`.
2919    fn selection_bounds_for_range(
2920        &mut self,
2921        _range_utf16: Range<usize>,
2922        _window: &mut Window,
2923        _cx: &mut App,
2924    ) -> Vec<Bounds<Pixels>> {
2925        Vec::new()
2926    }
2927
2928    /// Get the character offset for the given point in terms of UTF16 characters
2929    ///
2930    /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
2931    fn character_index_for_point(
2932        &mut self,
2933        point: Point<Pixels>,
2934        window: &mut Window,
2935        cx: &mut App,
2936    ) -> Option<usize>;
2937
2938    /// Set the range of the user's currently selected text.
2939    ///
2940    /// This is the reverse data-flow direction from [`Self::selected_text_range`]:
2941    /// platforms call it when the system text machinery moves the selection on the
2942    /// application's behalf — e.g. the user drags a system selection handle or
2943    /// invokes Select All from system UI (iOS `UITextInput setSelectedTextRange:`,
2944    /// Android `InputConnection.setSelection`).
2945    ///
2946    /// range_utf16 is in terms of UTF-16 characters, from 0 to the length of the document
2947    fn set_selected_text_range(
2948        &mut self,
2949        _range_utf16: Range<usize>,
2950        _window: &mut Window,
2951        _cx: &mut App,
2952    ) {
2953    }
2954
2955    /// Get the bounds of the focused text element in window coordinates, if known.
2956    ///
2957    /// This is the pull counterpart to the [`PlatformWindow::update_ime_position`]
2958    /// push: mobile platforms ask for the focused element's geometry when they
2959    /// need it (e.g. to frame system text-interaction UI overlaid on the focused
2960    /// element).
2961    fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2962        None
2963    }
2964
2965    /// Get the length of the document in UTF-16 characters, if known.
2966    fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2967        None
2968    }
2969
2970    /// Allows a given input context to opt into getting raw key repeats instead of
2971    /// sending these to the platform.
2972    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
2973    /// (which is how iTerm does it) but it doesn't seem to work for me.
2974    #[allow(dead_code)]
2975    fn apple_press_and_hold_enabled(&mut self) -> bool {
2976        true
2977    }
2978
2979    /// Returns whether this handler is accepting text input to be inserted.
2980    fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2981        true
2982    }
2983
2984    /// The contiguous range of text, in UTF-16 code units, that platform text
2985    /// input may read and edit around the current selection.
2986    ///
2987    /// Platforms that mirror document text into an IME-editable buffer clamp
2988    /// the mirrored window to this range, so multi-step IME edit gestures
2989    /// (word deletion, autocorrect rewrites, suggestion picks) cannot reach
2990    /// content outside it. The range should contain the current selection;
2991    /// when it cannot (a selection spanning a region boundary), platforms
2992    /// degrade the mirrored IME context rather than widening the range.
2993    /// `None` places no bound.
2994    fn text_input_editable_range(
2995        &mut self,
2996        _window: &mut Window,
2997        _cx: &mut App,
2998    ) -> Option<Range<usize>> {
2999        None
3000    }
3001
3002    /// Returns whether printable keys should be routed to the IME before keybinding
3003    /// matching when a non-ASCII input source (e.g. Japanese, Korean, Chinese IME)
3004    /// is active. This prevents multi-stroke keybindings like `jj` from intercepting
3005    /// keys that the IME should compose.
3006    ///
3007    /// Defaults to `false`. The editor overrides this based on whether it expects
3008    /// character input (e.g. Vim insert mode returns `true`, normal mode returns `false`).
3009    /// The terminal keeps the default `false` so that raw keys reach the terminal process.
3010    fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
3011        false
3012    }
3013
3014    /// Get this handler's preferences for platform text assistance.
3015    ///
3016    /// GPUI re-queries this every frame and forwards it to the platform window
3017    /// only when it changes, so implementations must be cheap and may vary the
3018    /// result with application state (e.g. with the cursor's position).
3019    fn text_input_configuration(
3020        &mut self,
3021        _window: &mut Window,
3022        _cx: &mut App,
3023    ) -> TextInputConfiguration {
3024        TextInputConfiguration::default()
3025    }
3026}
3027
3028/// Platform text-assistance preferences for the focused text region.
3029///
3030/// Returned by [`InputHandler::text_input_configuration`] and forwarded to the
3031/// platform whenever it changes; the platform maps the fields onto its native
3032/// input-session attributes (on web, DOM attributes of the hidden editable
3033/// element such as `autocorrect` and `enterkeyhint`).
3034///
3035/// The default disables all text assistance and requests no particular action
3036/// key presentation.
3037#[derive(Clone, Debug, Default, PartialEq, Eq)]
3038pub struct TextInputConfiguration {
3039    /// Whether the platform may automatically correct entered text.
3040    pub autocorrect: bool,
3041    /// How software keyboards automatically capitalize entered text.
3042    pub autocapitalize: Autocapitalize,
3043    /// Whether software keyboards may offer word suggestions and spellcheck.
3044    pub suggestions: bool,
3045    /// The action advertised on a software keyboard's confirm ("enter") key.
3046    pub input_action: TextInputAction,
3047}
3048
3049/// Automatic capitalization applied by software keyboards.
3050#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3051pub enum Autocapitalize {
3052    /// No automatic capitalization.
3053    #[default]
3054    None,
3055    /// Capitalize the first letter of each word.
3056    Words,
3057    /// Capitalize the first letter of each sentence.
3058    Sentences,
3059    /// Capitalize every letter.
3060    Characters,
3061}
3062
3063/// The action a software keyboard advertises on its confirm ("enter") key.
3064///
3065/// This affects only how the key is presented (icon or label); pressing it is
3066/// still delivered as ordinary input.
3067///
3068/// The variants are the HTML `enterkeyhint` attribute's value set
3069/// (<https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-enterkeyhint-attribute>),
3070/// which also maps onto Android's `IME_ACTION_*` constants and iOS's
3071/// `UIReturnKeyType`; [`TextInputAction::Unspecified`] means "emit no hint".
3072#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3073pub enum TextInputAction {
3074    /// Let the platform choose its default presentation.
3075    #[default]
3076    Unspecified,
3077    /// Inserting a line break.
3078    Enter,
3079    /// Committing the field's value.
3080    Done,
3081    /// Navigating to the typed target.
3082    Go,
3083    /// Moving to the next field.
3084    Next,
3085    /// Moving to the previous field.
3086    Previous,
3087    /// Executing a search.
3088    Search,
3089    /// Sending a message.
3090    Send,
3091}
3092
3093/// The variables that can be configured when creating a new window
3094#[derive(Debug)]
3095pub struct WindowOptions {
3096    /// Specifies the state and bounds of the window in screen coordinates.
3097    /// - `None`: Inherit the bounds.
3098    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
3099    pub window_bounds: Option<WindowBounds>,
3100
3101    /// The titlebar configuration of the window
3102    pub titlebar: Option<TitlebarOptions>,
3103
3104    /// Whether the window should be focused when created
3105    pub focus: bool,
3106
3107    /// Whether the window should be shown when created
3108    pub show: bool,
3109
3110    /// The kind of window to create
3111    pub kind: WindowKind,
3112
3113    /// Whether the window can be moved by the user. When `false`, the user cannot drag
3114    /// the window (on macOS this sets `NSWindow.isMovable`, which also disables the
3115    /// Window-menu tiling items); programmatic moves are still allowed.
3116    pub is_movable: bool,
3117
3118    /// Whether the application owns dragging of the (custom) titlebar, rather than
3119    /// AppKit. Only has an effect on macOS.
3120    ///
3121    /// Set this to `true` for windows that draw their own titlebar and move the window
3122    /// themselves via [`Window::start_window_move`]. It marks the whole content view as
3123    /// app-owned titlebar content, so AppKit neither drags the window from the titlebar
3124    /// nor delays titlebar clicks while disambiguating double-clicks (a delay first
3125    /// observed on macOS 27). It is independent of `is_movable`, so such windows stay
3126    /// user-movable (via their own drag) and keep the Window-menu tiling items enabled.
3127    ///
3128    /// Leave this `false` for windows that rely on AppKit's native titlebar dragging.
3129    pub app_owns_titlebar_drag: bool,
3130
3131    /// The minimum frame interval while inactive without sustained high-rate input.
3132    ///
3133    /// Defaults to approximately 30 fps. Set to `None` to disable this limit.
3134    /// The longest applicable interval wins; mandatory platform presentations bypass all limits.
3135    pub inactive_frame_interval: Option<Duration>,
3136
3137    /// The minimum frame interval while the platform reports Low Power Mode.
3138    ///
3139    /// Defaults to approximately 30 fps. Set to `None` to disable this limit.
3140    /// The longest applicable interval wins; mandatory platform presentations bypass all limits.
3141    pub low_power_frame_interval: Option<Duration>,
3142
3143    /// The minimum frame interval under serious or critical thermal pressure.
3144    ///
3145    /// Defaults to approximately 60 fps. Set to `None` to disable this limit.
3146    /// The longest applicable interval wins; mandatory platform presentations bypass all limits.
3147    pub thermal_frame_interval: Option<Duration>,
3148
3149    /// Whether the window should be resizable by the user
3150    pub is_resizable: bool,
3151
3152    /// Whether the window should be minimized by the user
3153    pub is_minimizable: bool,
3154
3155    /// The display to create the window on. If neither this nor `window_bounds` is set, the window
3156    /// is created on the active window's display. Otherwise, it falls back to the primary display.
3157    pub display_id: Option<DisplayId>,
3158
3159    /// The appearance of the window background.
3160    pub window_background: WindowBackgroundAppearance,
3161
3162    /// Application identifier of the window. Can by used by desktop environments to group applications together.
3163    pub app_id: Option<String>,
3164
3165    /// Window minimum size
3166    pub window_min_size: Option<Size<Pixels>>,
3167
3168    /// Whether to use client or server-side decorations on X11 and Wayland.
3169    /// The platform may ignore requests it cannot satisfy.
3170    pub window_decorations: Option<WindowDecorations>,
3171
3172    /// Icon image (X11 only)
3173    pub icon: Option<Arc<image::RgbaImage>>,
3174
3175    /// 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.
3176    pub tabbing_identifier: Option<String>,
3177
3178    /// Whether to render the window using the Display P3 color space on macOS.
3179    pub use_display_p3: bool,
3180}
3181
3182/// The variables that can be configured when creating a new window
3183#[derive(Debug)]
3184#[cfg_attr(
3185    all(
3186        any(target_os = "linux", target_os = "freebsd"),
3187        not(any(feature = "x11", feature = "wayland"))
3188    ),
3189    allow(dead_code)
3190)]
3191#[allow(missing_docs)]
3192pub struct WindowParams {
3193    pub bounds: Bounds<Pixels>,
3194
3195    /// The titlebar configuration of the window
3196    #[cfg_attr(feature = "wayland", allow(dead_code))]
3197    pub titlebar: Option<TitlebarOptions>,
3198
3199    /// The kind of window to create
3200    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3201    pub kind: WindowKind,
3202
3203    /// Whether the window should be movable by the user
3204    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3205    pub is_movable: bool,
3206
3207    /// Whether the application owns dragging of the (custom) titlebar (macOS only)
3208    #[cfg_attr(
3209        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3210        allow(dead_code)
3211    )]
3212    pub app_owns_titlebar_drag: bool,
3213
3214    /// Whether the window should be resizable by the user
3215    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3216    pub is_resizable: bool,
3217
3218    /// Whether the window should be minimized by the user
3219    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3220    pub is_minimizable: bool,
3221
3222    #[cfg_attr(
3223        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3224        allow(dead_code)
3225    )]
3226    pub focus: bool,
3227
3228    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3229    pub show: bool,
3230
3231    /// An image to set as the window icon (x11 only)
3232    #[cfg_attr(feature = "wayland", allow(dead_code))]
3233    pub icon: Option<Arc<image::RgbaImage>>,
3234
3235    #[cfg_attr(feature = "wayland", allow(dead_code))]
3236    pub display_id: Option<DisplayId>,
3237
3238    #[cfg_attr(feature = "wayland", allow(dead_code))]
3239    pub app_id: Option<String>,
3240
3241    pub window_min_size: Option<Size<Pixels>>,
3242
3243    #[cfg(target_os = "macos")]
3244    pub tabbing_identifier: Option<String>,
3245
3246    #[cfg(target_os = "macos")]
3247    pub use_display_p3: bool,
3248}
3249
3250/// Represents the status of how a window should be opened.
3251#[derive(Debug, Copy, Clone, PartialEq)]
3252pub enum WindowBounds {
3253    /// Indicates that the window should open in a windowed state with the given bounds.
3254    Windowed(Bounds<Pixels>),
3255    /// Indicates that the window should open in a maximized state.
3256    /// The bounds provided here represent the restore size of the window.
3257    Maximized(Bounds<Pixels>),
3258    /// Indicates that the window should open in fullscreen mode.
3259    /// The bounds provided here represent the restore size of the window.
3260    Fullscreen(Bounds<Pixels>),
3261}
3262
3263impl Default for WindowBounds {
3264    fn default() -> Self {
3265        WindowBounds::Windowed(Bounds::default())
3266    }
3267}
3268
3269impl WindowBounds {
3270    /// Retrieve the inner bounds
3271    pub fn get_bounds(&self) -> Bounds<Pixels> {
3272        match self {
3273            WindowBounds::Windowed(bounds) => *bounds,
3274            WindowBounds::Maximized(bounds) => *bounds,
3275            WindowBounds::Fullscreen(bounds) => *bounds,
3276        }
3277    }
3278
3279    /// Creates window bounds centered on the given display, or the primary display if none is
3280    /// provided.
3281    pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
3282        WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
3283    }
3284}
3285
3286impl Default for WindowOptions {
3287    fn default() -> Self {
3288        Self {
3289            window_bounds: None,
3290            titlebar: Some(TitlebarOptions {
3291                title: Default::default(),
3292                appears_transparent: Default::default(),
3293                traffic_light_position: Default::default(),
3294            }),
3295            focus: true,
3296            show: true,
3297            kind: WindowKind::Normal,
3298            is_movable: true,
3299            app_owns_titlebar_drag: false,
3300            inactive_frame_interval: Some(Duration::from_micros(33_333)),
3301            low_power_frame_interval: Some(Duration::from_micros(33_333)),
3302            thermal_frame_interval: Some(Duration::from_micros(16_667)),
3303            is_resizable: true,
3304            is_minimizable: true,
3305            display_id: None,
3306            window_background: WindowBackgroundAppearance::default(),
3307            icon: None,
3308            app_id: None,
3309            window_min_size: None,
3310            window_decorations: None,
3311            tabbing_identifier: None,
3312            use_display_p3: false,
3313        }
3314    }
3315}
3316
3317/// The options that can be configured for a window's titlebar
3318#[derive(Debug, Default)]
3319pub struct TitlebarOptions {
3320    /// The initial title of the window
3321    pub title: Option<SharedString>,
3322
3323    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
3324    /// Refer to [`WindowOptions::window_decorations`] on Linux
3325    pub appears_transparent: bool,
3326
3327    /// The position of the macOS traffic light buttons
3328    pub traffic_light_position: Option<Point<Pixels>>,
3329}
3330
3331/// The kind of window to create
3332#[derive(Clone, Debug, PartialEq, Eq)]
3333pub enum WindowKind {
3334    /// A normal application window
3335    Normal,
3336
3337    /// A window that appears above all other windows, usually used for alerts or popups
3338    /// use sparingly!
3339    PopUp,
3340
3341    /// A parent-anchored, platform-native popup window for menus, comboboxes, context menus and
3342    /// tooltips. Unlike [`WindowKind::PopUp`], it is positioned relative to a parent window.
3343    ///
3344    /// The popup's size comes from [`WindowOptions::window_bounds`], whose origin is ignored.
3345    /// See [`popup::PopupOptions`] for the placement options. Platforms without a native
3346    /// implementation reject it with [`popup::PopupNotSupportedError`].
3347    AnchoredPopup(popup::PopupOptions),
3348
3349    /// A floating window that appears on top of its parent window
3350    Floating,
3351
3352    /// A Wayland LayerShell window, used to draw overlays or backgrounds for applications such as
3353    /// docks, notifications or wallpapers.
3354    #[cfg(all(target_os = "linux", feature = "wayland"))]
3355    LayerShell(layer_shell::LayerShellOptions),
3356
3357    /// A window that appears on top of its parent window and blocks interaction with it
3358    /// until the modal window is closed
3359    Dialog,
3360}
3361
3362/// The appearance of the window, as defined by the operating system.
3363///
3364/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
3365/// values.
3366#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3367pub enum WindowAppearance {
3368    /// A light appearance.
3369    ///
3370    /// On macOS, this corresponds to the `aqua` appearance.
3371    #[default]
3372    Light,
3373
3374    /// A light appearance with vibrant colors.
3375    ///
3376    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
3377    VibrantLight,
3378
3379    /// A dark appearance.
3380    ///
3381    /// On macOS, this corresponds to the `darkAqua` appearance.
3382    Dark,
3383
3384    /// A dark appearance with vibrant colors.
3385    ///
3386    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
3387    VibrantDark,
3388}
3389
3390/// The appearance of the background of the window itself, when there is
3391/// no content or the content is transparent.
3392#[derive(Copy, Clone, Debug, Default, PartialEq)]
3393pub enum WindowBackgroundAppearance {
3394    /// Opaque.
3395    ///
3396    /// This lets the window manager know that content behind this
3397    /// window does not need to be drawn.
3398    ///
3399    /// Actual color depends on the system and themes should define a fully
3400    /// opaque background color instead.
3401    #[default]
3402    Opaque,
3403    /// Plain alpha transparency.
3404    Transparent,
3405    /// Transparency, but the contents behind the window are blurred.
3406    ///
3407    /// Not always supported.
3408    Blurred,
3409    /// The Mica backdrop material, supported on Windows 11.
3410    MicaBackdrop,
3411    /// The Mica Alt backdrop material, supported on Windows 11.
3412    MicaAltBackdrop,
3413    /// The Acrylic backdrop material: DWM's own, on Windows 11 22H2 (build
3414    /// 22621) and later. Earlier Windows draws `Blurred` instead.
3415    AcrylicBackdrop,
3416}
3417
3418/// The text rendering mode to use for drawing glyphs.
3419#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3420pub enum TextRenderingMode {
3421    /// Use the platform's default text rendering mode.
3422    #[default]
3423    PlatformDefault,
3424    /// Use subpixel (ClearType-style) text rendering.
3425    Subpixel,
3426    /// Use grayscale text rendering.
3427    Grayscale,
3428}
3429
3430/// The options that can be configured for a file dialog prompt
3431#[derive(Clone, Debug)]
3432pub struct PathPromptOptions {
3433    /// Should the prompt allow files to be selected?
3434    pub files: bool,
3435    /// Should the prompt allow directories to be selected?
3436    pub directories: bool,
3437    /// Should the prompt allow multiple files to be selected?
3438    pub multiple: bool,
3439    /// The prompt to show to a user when selecting a path
3440    pub prompt: Option<SharedString>,
3441}
3442
3443/// What kind of prompt styling to show
3444#[derive(Copy, Clone, Debug, PartialEq)]
3445pub enum PromptLevel {
3446    /// A prompt that is shown when the user should be notified of something
3447    Info,
3448
3449    /// A prompt that is shown when the user needs to be warned of a potential problem
3450    Warning,
3451
3452    /// A prompt that is shown when a critical problem has occurred
3453    Critical,
3454}
3455
3456/// Prompt Button
3457#[derive(Clone, Debug, PartialEq)]
3458pub enum PromptButton {
3459    /// Ok button
3460    Ok(SharedString),
3461    /// Cancel button
3462    Cancel(SharedString),
3463    /// Other button
3464    Other(SharedString),
3465}
3466
3467impl PromptButton {
3468    /// Create a button with label
3469    pub fn new(label: impl Into<SharedString>) -> Self {
3470        PromptButton::Other(label.into())
3471    }
3472
3473    /// Create an Ok button
3474    pub fn ok(label: impl Into<SharedString>) -> Self {
3475        PromptButton::Ok(label.into())
3476    }
3477
3478    /// Create a Cancel button
3479    pub fn cancel(label: impl Into<SharedString>) -> Self {
3480        PromptButton::Cancel(label.into())
3481    }
3482
3483    /// Returns true if this button is a cancel button.
3484    #[allow(dead_code)]
3485    pub fn is_cancel(&self) -> bool {
3486        matches!(self, PromptButton::Cancel(_))
3487    }
3488
3489    /// Returns the label of the button
3490    pub fn label(&self) -> &SharedString {
3491        match self {
3492            PromptButton::Ok(label) => label,
3493            PromptButton::Cancel(label) => label,
3494            PromptButton::Other(label) => label,
3495        }
3496    }
3497}
3498
3499impl From<&str> for PromptButton {
3500    fn from(value: &str) -> Self {
3501        match value.to_lowercase().as_str() {
3502            "ok" => PromptButton::Ok("OK".into()),
3503            "cancel" => PromptButton::Cancel("Cancel".into()),
3504            _ => PromptButton::Other(SharedString::from(value.to_owned())),
3505        }
3506    }
3507}
3508
3509/// The style of the cursor (pointer)
3510#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
3511#[cfg_attr(feature = "schemars", derive(JsonSchema))]
3512pub enum CursorStyle {
3513    /// The default cursor
3514    #[default]
3515    Arrow,
3516
3517    /// A text input cursor
3518    /// corresponds to the CSS cursor value `text`
3519    IBeam,
3520
3521    /// A crosshair cursor
3522    /// corresponds to the CSS cursor value `crosshair`
3523    Crosshair,
3524
3525    /// A closed hand cursor
3526    /// corresponds to the CSS cursor value `grabbing`
3527    ClosedHand,
3528
3529    /// An open hand cursor
3530    /// corresponds to the CSS cursor value `grab`
3531    OpenHand,
3532
3533    /// A pointing hand cursor
3534    /// corresponds to the CSS cursor value `pointer`
3535    PointingHand,
3536
3537    /// A resize left cursor
3538    /// corresponds to the CSS cursor value `w-resize`
3539    ResizeLeft,
3540
3541    /// A resize right cursor
3542    /// corresponds to the CSS cursor value `e-resize`
3543    ResizeRight,
3544
3545    /// A resize cursor to the left and right
3546    /// corresponds to the CSS cursor value `ew-resize`
3547    ResizeLeftRight,
3548
3549    /// A resize up cursor
3550    /// corresponds to the CSS cursor value `n-resize`
3551    ResizeUp,
3552
3553    /// A resize down cursor
3554    /// corresponds to the CSS cursor value `s-resize`
3555    ResizeDown,
3556
3557    /// A resize cursor directing up and down
3558    /// corresponds to the CSS cursor value `ns-resize`
3559    ResizeUpDown,
3560
3561    /// A resize cursor directing up-left and down-right
3562    /// corresponds to the CSS cursor value `nesw-resize`
3563    ResizeUpLeftDownRight,
3564
3565    /// A resize cursor directing up-right and down-left
3566    /// corresponds to the CSS cursor value `nwse-resize`
3567    ResizeUpRightDownLeft,
3568
3569    /// A cursor indicating that the item/column can be resized horizontally.
3570    /// corresponds to the CSS cursor value `col-resize`
3571    ResizeColumn,
3572
3573    /// A cursor indicating that the item/row can be resized vertically.
3574    /// corresponds to the CSS cursor value `row-resize`
3575    ResizeRow,
3576
3577    /// A text input cursor for vertical layout
3578    /// corresponds to the CSS cursor value `vertical-text`
3579    IBeamCursorForVerticalLayout,
3580
3581    /// A cursor indicating that the operation is not allowed
3582    /// corresponds to the CSS cursor value `not-allowed`
3583    OperationNotAllowed,
3584
3585    /// A cursor indicating that the operation will result in a link
3586    /// corresponds to the CSS cursor value `alias`
3587    DragLink,
3588
3589    /// A cursor indicating that the operation will result in a copy
3590    /// corresponds to the CSS cursor value `copy`
3591    DragCopy,
3592
3593    /// A cursor indicating that the operation will result in a context menu
3594    /// corresponds to the CSS cursor value `context-menu`
3595    ContextualMenu,
3596
3597    /// corresponds to the CSS cursor value `help`
3598    Help,
3599
3600    /// Busy, but the user can still interact
3601    /// corresponds to the CSS cursor value `progress`
3602    Progress,
3603
3604    /// corresponds to the CSS cursor value `wait`
3605    Wait,
3606
3607    /// corresponds to the CSS cursor value `move`
3608    Move,
3609
3610    /// corresponds to the CSS cursor value `all-scroll`
3611    AllScroll,
3612
3613    /// corresponds to the CSS cursor value `cell`
3614    Cell,
3615
3616    /// corresponds to the CSS cursor value `zoom-in`
3617    ZoomIn,
3618
3619    /// corresponds to the CSS cursor value `zoom-out`
3620    ZoomOut,
3621
3622    /// corresponds to the CSS cursor value `no-drop`
3623    NoDrop,
3624
3625    /// No cursor is shown
3626    /// corresponds to the CSS cursor value `none`
3627    Hidden,
3628}
3629
3630impl CursorStyle {
3631    /// Every style.
3632    pub const ALL: [Self; 31] = [
3633        Self::Arrow,
3634        Self::IBeam,
3635        Self::Crosshair,
3636        Self::ClosedHand,
3637        Self::OpenHand,
3638        Self::PointingHand,
3639        Self::ResizeLeft,
3640        Self::ResizeRight,
3641        Self::ResizeLeftRight,
3642        Self::ResizeUp,
3643        Self::ResizeDown,
3644        Self::ResizeUpDown,
3645        Self::ResizeUpLeftDownRight,
3646        Self::ResizeUpRightDownLeft,
3647        Self::ResizeColumn,
3648        Self::ResizeRow,
3649        Self::IBeamCursorForVerticalLayout,
3650        Self::OperationNotAllowed,
3651        Self::DragLink,
3652        Self::DragCopy,
3653        Self::ContextualMenu,
3654        Self::Help,
3655        Self::Progress,
3656        Self::Wait,
3657        Self::Move,
3658        Self::AllScroll,
3659        Self::Cell,
3660        Self::ZoomIn,
3661        Self::ZoomOut,
3662        Self::NoDrop,
3663        Self::Hidden,
3664    ];
3665
3666    /// Iterates over [`Self::ALL`], in place of strum's `EnumIter`, which gpui does not depend on.
3667    pub fn iter() -> impl Iterator<Item = Self> {
3668        Self::ALL.into_iter()
3669    }
3670}
3671
3672/// A clipboard item that should be copied to the clipboard
3673#[derive(Clone, Debug, Eq, PartialEq)]
3674pub struct ClipboardItem {
3675    /// The entries in this clipboard item.
3676    pub entries: Vec<ClipboardEntry>,
3677}
3678
3679/// An error produced by [`Platform::read_from_clipboard_async`].
3680///
3681/// Callers surface these failures to users, so the variants distinguish
3682/// conditions that call for different user-facing guidance.
3683#[derive(Clone, Debug, PartialEq, Eq)]
3684pub enum ClipboardReadError {
3685    /// The platform clipboard is not available in this context, e.g. the
3686    /// browser does not expose the async clipboard API or the page is not a
3687    /// secure context.
3688    Unavailable,
3689    /// The platform refused access, e.g. the user declined the browser's
3690    /// clipboard permission prompt or paste confirmation.
3691    Denied(String),
3692    /// The clipboard contents could not be converted into a
3693    /// [`ClipboardItem`].
3694    UnsupportedContent,
3695}
3696
3697impl std::fmt::Display for ClipboardReadError {
3698    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3699        match self {
3700            Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3701            Self::Denied(message) => {
3702                write!(formatter, "clipboard access was denied: {message}")
3703            }
3704            Self::UnsupportedContent => {
3705                formatter.write_str("the clipboard contents are unsupported")
3706            }
3707        }
3708    }
3709}
3710
3711impl std::error::Error for ClipboardReadError {}
3712
3713/// Either a ClipboardString or a ClipboardImage
3714#[derive(Clone, Debug, Eq, PartialEq)]
3715pub enum ClipboardEntry {
3716    /// A string entry
3717    String(ClipboardString),
3718    /// An image entry
3719    Image(Image),
3720    /// A file entry
3721    ExternalPaths(crate::ExternalPaths),
3722}
3723
3724impl ClipboardItem {
3725    /// Create a new ClipboardItem::String with no associated metadata
3726    pub fn new_string(text: String) -> Self {
3727        Self {
3728            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3729        }
3730    }
3731
3732    /// Create a new ClipboardItem::String with the given text and associated metadata
3733    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3734        Self {
3735            entries: vec![ClipboardEntry::String(ClipboardString {
3736                text,
3737                metadata: Some(metadata),
3738            })],
3739        }
3740    }
3741
3742    /// Create a new ClipboardItem::String with the given text and associated metadata
3743    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3744        Self {
3745            entries: vec![ClipboardEntry::String(
3746                ClipboardString::new(text).with_json_metadata(metadata),
3747            )],
3748        }
3749    }
3750
3751    /// Create a new ClipboardItem::Image with the given image with no associated metadata
3752    pub fn new_image(image: &Image) -> Self {
3753        Self {
3754            entries: vec![ClipboardEntry::Image(image.clone())],
3755        }
3756    }
3757
3758    /// Concatenates together all the ClipboardString entries in the item.
3759    /// Returns None if there were no ClipboardString entries.
3760    pub fn text(&self) -> Option<String> {
3761        let mut answer = String::new();
3762
3763        for entry in self.entries.iter() {
3764            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3765                answer.push_str(text);
3766            }
3767        }
3768
3769        if answer.is_empty() {
3770            for entry in self.entries.iter() {
3771                if let ClipboardEntry::ExternalPaths(paths) = entry {
3772                    for path in &paths.0 {
3773                        use std::fmt::Write as _;
3774                        _ = write!(answer, "{}", path.display());
3775                    }
3776                }
3777            }
3778        }
3779
3780        if !answer.is_empty() {
3781            Some(answer)
3782        } else {
3783            None
3784        }
3785    }
3786
3787    /// If this item is one ClipboardEntry::String, returns its metadata.
3788    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3789    pub fn metadata(&self) -> Option<&String> {
3790        match self.entries().first() {
3791            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3792                clipboard_string.metadata.as_ref()
3793            }
3794            _ => None,
3795        }
3796    }
3797
3798    /// Get the item's entries
3799    pub fn entries(&self) -> &[ClipboardEntry] {
3800        &self.entries
3801    }
3802
3803    /// Get owned versions of the item's entries
3804    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3805        self.entries.into_iter()
3806    }
3807}
3808
3809impl From<ClipboardString> for ClipboardEntry {
3810    fn from(value: ClipboardString) -> Self {
3811        Self::String(value)
3812    }
3813}
3814
3815impl From<String> for ClipboardEntry {
3816    fn from(value: String) -> Self {
3817        Self::from(ClipboardString::from(value))
3818    }
3819}
3820
3821impl From<Image> for ClipboardEntry {
3822    fn from(value: Image) -> Self {
3823        Self::Image(value)
3824    }
3825}
3826
3827impl From<ClipboardEntry> for ClipboardItem {
3828    fn from(value: ClipboardEntry) -> Self {
3829        Self {
3830            entries: vec![value],
3831        }
3832    }
3833}
3834
3835impl From<String> for ClipboardItem {
3836    fn from(value: String) -> Self {
3837        Self::from(ClipboardEntry::from(value))
3838    }
3839}
3840
3841impl From<Image> for ClipboardItem {
3842    fn from(value: Image) -> Self {
3843        Self::from(ClipboardEntry::from(value))
3844    }
3845}
3846
3847/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
3848#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3849pub enum ImageFormat {
3850    // Sorted from most to least likely to be pasted into an editor,
3851    // which matters when we iterate through them trying to see if
3852    // clipboard content matches them.
3853    /// .png
3854    Png,
3855    /// .jpeg or .jpg
3856    Jpeg,
3857    /// .webp
3858    Webp,
3859    /// .gif
3860    Gif,
3861    /// .svg
3862    Svg,
3863    /// .bmp
3864    Bmp,
3865    /// .tif or .tiff
3866    Tiff,
3867    /// .ico
3868    Ico,
3869    /// Netpbm image formats (.pbm, .ppm, .pgm).
3870    Pnm,
3871}
3872
3873impl ImageFormat {
3874    /// Every format, in the order clipboard readers should try them.
3875    pub const ALL: [Self; 9] = [
3876        Self::Png,
3877        Self::Jpeg,
3878        Self::Webp,
3879        Self::Gif,
3880        Self::Svg,
3881        Self::Bmp,
3882        Self::Tiff,
3883        Self::Ico,
3884        Self::Pnm,
3885    ];
3886
3887    /// Iterates over [`Self::ALL`].
3888    pub fn iter() -> impl Iterator<Item = Self> {
3889        Self::ALL.into_iter()
3890    }
3891
3892    /// Returns the mime type for the ImageFormat
3893    pub const fn mime_type(self) -> &'static str {
3894        match self {
3895            ImageFormat::Png => "image/png",
3896            ImageFormat::Jpeg => "image/jpeg",
3897            ImageFormat::Webp => "image/webp",
3898            ImageFormat::Gif => "image/gif",
3899            ImageFormat::Svg => "image/svg+xml",
3900            ImageFormat::Bmp => "image/bmp",
3901            ImageFormat::Tiff => "image/tiff",
3902            ImageFormat::Ico => "image/ico",
3903            ImageFormat::Pnm => "image/x-portable-anymap",
3904        }
3905    }
3906
3907    /// Returns the file extension for this image format (without leading dot).
3908    pub const fn extension(self) -> &'static str {
3909        match self {
3910            ImageFormat::Png => "png",
3911            ImageFormat::Jpeg => "jpg",
3912            ImageFormat::Webp => "webp",
3913            ImageFormat::Gif => "gif",
3914            ImageFormat::Svg => "svg",
3915            ImageFormat::Bmp => "bmp",
3916            ImageFormat::Tiff => "tiff",
3917            ImageFormat::Ico => "ico",
3918            ImageFormat::Pnm => "pnm",
3919        }
3920    }
3921
3922    /// Returns the ImageFormat for the given mime type, including known aliases.
3923    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3924        Self::iter()
3925            .find(|format| format.mime_type() == mime_type)
3926            .or_else(|| Self::from_mime_type_alias(mime_type))
3927    }
3928
3929    /// Non-canonical mime types that some producers use in the wild.
3930    /// Unlike `mime_type()` which returns the single canonical form,
3931    /// these are legacy or shortened variants we still need to recognize.
3932    fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3933        match mime_type {
3934            "image/jpg" => Some(Self::Jpeg),
3935            "image/tif" => Some(Self::Tiff),
3936            _ => None,
3937        }
3938    }
3939}
3940
3941/// An image, with a format and certain bytes
3942#[derive(Clone, Debug, PartialEq, Eq)]
3943pub struct Image {
3944    /// The image format the bytes represent (e.g. PNG)
3945    pub format: ImageFormat,
3946    /// The raw image bytes
3947    pub bytes: Vec<u8>,
3948    /// The unique ID for the image
3949    pub id: u64,
3950}
3951
3952pub(crate) fn decode_static_image(
3953    bytes: &[u8],
3954    format: image::ImageFormat,
3955) -> Result<SmallVec<[Frame; 1]>> {
3956    let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3957        .into_decoder()
3958        .context("creating image decoder")?;
3959    decode_static_image_from_decoder(decoder)
3960}
3961
3962pub(crate) fn decode_static_image_from_decoder(
3963    mut decoder: impl image::ImageDecoder,
3964) -> Result<SmallVec<[Frame; 1]>> {
3965    let orientation = decoder
3966        .orientation()
3967        .context("reading decoder's orientation")?;
3968    let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3969    image.apply_orientation(orientation);
3970
3971    let mut data = image.into_rgba8();
3972    for pixel in data.chunks_exact_mut(4) {
3973        pixel.swap(0, 2);
3974    }
3975
3976    Ok(SmallVec::from_elem(Frame::new(data), 1))
3977}
3978
3979fn decode_animated_frames<'a>(
3980    decoder: impl image::AnimationDecoder<'a>,
3981    format_name: &str,
3982) -> Result<SmallVec<[Frame; 1]>> {
3983    let mut frames = SmallVec::new();
3984
3985    for frame in decoder.into_frames() {
3986        match frame {
3987            Ok(mut frame) => {
3988                // Convert from RGBA to BGRA.
3989                for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3990                    pixel.swap(0, 2);
3991                }
3992                frames.push(frame);
3993            }
3994            Err(err) => {
3995                log::debug!("Skipping {format_name} frame due to decode error: {err}");
3996            }
3997        }
3998    }
3999
4000    if frames.is_empty() {
4001        anyhow::bail!("{format_name} could not be decoded: all frames failed");
4002    }
4003
4004    Ok(frames)
4005}
4006
4007pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
4008    let decoder = GifDecoder::new(Cursor::new(bytes))?;
4009    decode_animated_frames(decoder, "GIF")
4010}
4011
4012pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
4013    let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
4014
4015    if decoder.has_animation() {
4016        let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
4017        decode_animated_frames(decoder, "WebP")
4018    } else {
4019        decode_static_image_from_decoder(decoder)
4020    }
4021}
4022
4023impl Hash for Image {
4024    fn hash<H: Hasher>(&self, state: &mut H) {
4025        state.write_u64(self.id);
4026    }
4027}
4028
4029impl Image {
4030    /// An empty image containing no data
4031    pub fn empty() -> Self {
4032        Self::from_bytes(ImageFormat::Png, Vec::new())
4033    }
4034
4035    /// Create an image from a format and bytes
4036    pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
4037        Self {
4038            id: hash(&bytes),
4039            format,
4040            bytes,
4041        }
4042    }
4043
4044    /// Get this image's ID
4045    pub fn id(&self) -> u64 {
4046        self.id
4047    }
4048
4049    /// Use the GPUI `use_asset` API to make this image renderable
4050    pub fn use_render_image(
4051        self: Arc<Self>,
4052        window: &mut Window,
4053        cx: &mut App,
4054    ) -> Option<Arc<RenderImage>> {
4055        ImageSource::Image(self)
4056            .use_data(None, window, cx)
4057            .and_then(|result| result.ok())
4058    }
4059
4060    /// Use the GPUI `get_asset` API to make this image renderable
4061    pub fn get_render_image(
4062        self: Arc<Self>,
4063        window: &mut Window,
4064        cx: &mut App,
4065    ) -> Option<Arc<RenderImage>> {
4066        ImageSource::Image(self)
4067            .get_data(None, window, cx)
4068            .and_then(|result| result.ok())
4069    }
4070
4071    /// Use the GPUI `remove_asset` API to drop this image, if possible.
4072    pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
4073        ImageSource::Image(self).remove_asset(cx);
4074    }
4075
4076    /// Check whether this image is present in GPUI's asset cache (loading or
4077    /// loaded), without fetching it.
4078    #[cfg(any(test, feature = "test-support"))]
4079    pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
4080        ImageSource::Image(self.clone()).is_asset_cached(cx)
4081    }
4082
4083    /// Convert the clipboard image to an `ImageData` object.
4084    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
4085        let frames = match self.format {
4086            ImageFormat::Gif => decode_gif_image(&self.bytes)?,
4087            ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
4088            ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
4089            ImageFormat::Webp => decode_webp_image(&self.bytes)?,
4090            ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
4091            ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
4092            ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
4093            ImageFormat::Svg => {
4094                return svg_renderer
4095                    .render_single_frame(&self.bytes, 1.0)
4096                    .map_err(Into::into);
4097            }
4098            ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
4099        };
4100
4101        Ok(Arc::new(RenderImage::new(frames)))
4102    }
4103
4104    /// Get the format of the clipboard image
4105    pub fn format(&self) -> ImageFormat {
4106        self.format
4107    }
4108
4109    /// Get the raw bytes of the clipboard image
4110    pub fn bytes(&self) -> &[u8] {
4111        self.bytes.as_slice()
4112    }
4113}
4114
4115/// A clipboard item that should be copied to the clipboard
4116#[derive(Clone, Debug, Eq, PartialEq)]
4117pub struct ClipboardString {
4118    /// The text content.
4119    pub text: String,
4120    /// Optional metadata associated with this clipboard string.
4121    pub metadata: Option<String>,
4122}
4123
4124impl ClipboardString {
4125    /// Create a new clipboard string with the given text
4126    pub fn new(text: String) -> Self {
4127        Self {
4128            text,
4129            metadata: None,
4130        }
4131    }
4132
4133    /// Return a new clipboard item with the metadata replaced by the given metadata,
4134    /// after serializing it as JSON.
4135    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
4136        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
4137        self
4138    }
4139
4140    /// Get the text of the clipboard string
4141    pub fn text(&self) -> &String {
4142        &self.text
4143    }
4144
4145    /// Get the owned text of the clipboard string
4146    pub fn into_text(self) -> String {
4147        self.text
4148    }
4149
4150    /// Get the metadata of the clipboard string, formatted as JSON
4151    pub fn metadata_json<T>(&self) -> Option<T>
4152    where
4153        T: for<'a> Deserialize<'a>,
4154    {
4155        self.metadata
4156            .as_ref()
4157            .and_then(|m| serde_json::from_str(m).ok())
4158    }
4159
4160    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
4161    /// Compute a hash of the given text for clipboard change detection.
4162    pub fn text_hash(text: &str) -> u64 {
4163        let mut hasher = SeaHasher::new();
4164        text.hash(&mut hasher);
4165        hasher.finish()
4166    }
4167}
4168
4169impl From<String> for ClipboardString {
4170    fn from(value: String) -> Self {
4171        Self {
4172            text: value,
4173            metadata: None,
4174        }
4175    }
4176}
4177
4178#[cfg(test)]
4179mod image_tests {
4180    use super::*;
4181    use std::sync::Arc;
4182
4183    #[test]
4184    fn test_image_to_image_data_applies_exif_orientation() {
4185        let image = Image::from_bytes(
4186            ImageFormat::Jpeg,
4187            include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
4188        );
4189
4190        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4191
4192        assert_eq!(render_image.size(0), size(16.into(), 32.into()));
4193
4194        let bytes = render_image.as_bytes(0).unwrap();
4195        assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
4196        assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
4197    }
4198
4199    #[test]
4200    fn test_svg_image_to_image_data_converts_to_bgra() {
4201        let image = Image::from_bytes(
4202            ImageFormat::Svg,
4203            br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
4204<rect width="1" height="1" fill="#38BDF8"/>
4205</svg>"##
4206                .to_vec(),
4207        );
4208
4209        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4210        let bytes = render_image.as_bytes(0).unwrap();
4211
4212        for pixel in bytes.chunks_exact(4) {
4213            assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
4214        }
4215    }
4216
4217    #[test]
4218    fn test_animated_webp_image_to_image_data_decodes_frames() {
4219        // 1x1 2-frame animated WebP (frame 0: red, frame 1: blue, 100ms delay each).
4220        const ANIMATED_WEBP: &[u8] = &[
4221            82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
4222            0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
4223            72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 2, 86, 80, 56, 32, 48, 0,
4224            0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
4225            176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
4226            128, 255, 248, 242, 0, 0, 0, 65, 78, 77, 70, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4227            0, 0, 100, 0, 0, 0, 86, 80, 56, 32, 44, 0, 0, 0, 148, 1, 0, 157, 1, 42, 1, 0, 1, 0, 0,
4228            0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
4229            31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
4230        ];
4231
4232        let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
4233        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4234
4235        assert_eq!(render_image.frame_count(), 2);
4236        assert_eq!(render_image.size(0), size(1.into(), 1.into()));
4237        assert_eq!(
4238            Duration::from(render_image.delay(0)),
4239            Duration::from_millis(100)
4240        );
4241        assert_eq!(
4242            Duration::from(render_image.delay(1)),
4243            Duration::from_millis(100)
4244        );
4245    }
4246}
4247
4248#[cfg(test)]
4249mod atlas_tests {
4250    use super::*;
4251
4252    const TILE_SIZE: Size<DevicePixels> = Size {
4253        width: DevicePixels(1),
4254        height: DevicePixels(1),
4255    };
4256
4257    #[derive(Default)]
4258    struct RecordingAtlasBackend {
4259        insert_calls: u32,
4260        fail_next_insert: bool,
4261        removed_tiles: Vec<AtlasTile>,
4262    }
4263
4264    impl AtlasBackend for RecordingAtlasBackend {
4265        fn insert(
4266            &mut self,
4267            kind: AtlasTextureKind,
4268            size: Size<DevicePixels>,
4269            _bytes: &[u8],
4270        ) -> Result<AtlasTile> {
4271            self.insert_calls += 1;
4272            if std::mem::take(&mut self.fail_next_insert) {
4273                anyhow::bail!("backend failed");
4274            }
4275            Ok(AtlasTile {
4276                texture_id: AtlasTextureId { index: 0, kind },
4277                tile_id: TileId(self.insert_calls),
4278                padding: 0,
4279                bounds: Bounds {
4280                    origin: Point::default(),
4281                    size,
4282                },
4283            })
4284        }
4285
4286        fn remove(&mut self, tile: AtlasTile) {
4287            self.removed_tiles.push(tile);
4288        }
4289    }
4290
4291    fn image_key(image_id: usize) -> AtlasKey {
4292        AtlasKey::Image(RenderImageParams {
4293            image_id: crate::ImageId(image_id),
4294            frame_index: 0,
4295        })
4296    }
4297
4298    fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
4299        Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
4300    }
4301
4302    #[test]
4303    fn only_successful_inserts_are_cached() -> Result<()> {
4304        let mut state = AtlasState::new(RecordingAtlasBackend::default());
4305        let key = image_key(1);
4306
4307        assert_eq!(
4308            state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
4309            None
4310        );
4311        state
4312            .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
4313            .expect_err("builder error should propagate");
4314        assert!(!state.contains(&key));
4315        assert_eq!(state.backend.insert_calls, 0);
4316
4317        state.backend.fail_next_insert = true;
4318        state
4319            .get_or_insert_with(key.clone(), &mut build_tile)
4320            .expect_err("backend error should propagate");
4321        assert!(!state.contains(&key));
4322        assert_eq!(state.backend.insert_calls, 1);
4323
4324        let tile = state
4325            .get_or_insert_with(key.clone(), &mut build_tile)?
4326            .context("builder should produce a tile")?;
4327        assert_eq!(tile.texture_id.kind, key.texture_kind());
4328        assert_eq!(
4329            state.get_or_insert_with(key.clone(), &mut || {
4330                anyhow::bail!("cache hit must not call the builder")
4331            })?,
4332            Some(tile)
4333        );
4334        assert!(state.contains(&key));
4335        assert_eq!(state.backend.insert_calls, 2);
4336        Ok(())
4337    }
4338
4339    #[test]
4340    fn remove_and_clear_invalidate_keys() -> Result<()> {
4341        let mut state = AtlasState::new(RecordingAtlasBackend::default());
4342        let key = image_key(1);
4343        let other_key = image_key(2);
4344        let tile = state
4345            .get_or_insert_with(key.clone(), &mut build_tile)?
4346            .context("builder should produce a tile")?;
4347        state
4348            .get_or_insert_with(other_key.clone(), &mut build_tile)?
4349            .context("builder should produce another tile")?;
4350
4351        state.remove(&key);
4352        state.remove(&key);
4353        assert!(!state.contains(&key));
4354        assert!(state.contains(&other_key));
4355        assert_eq!(state.backend.removed_tiles, vec![tile]);
4356
4357        let mut reset_calls = 0;
4358        state.clear(|_| reset_calls += 1);
4359        assert_eq!(reset_calls, 1);
4360        assert!(!state.contains(&other_key));
4361        assert_eq!(state.backend.removed_tiles, vec![tile]);
4362        Ok(())
4363    }
4364}
4365
4366#[cfg(test)]
4367mod frame_signal_tests {
4368    use super::*;
4369
4370    #[cfg(feature = "profiler")]
4371    #[test]
4372    fn coalesced_signals_retain_the_earliest_until_drained() {
4373        for (first_source, later_source) in [
4374            (
4375                FrameRequestSource::NativeCallback,
4376                FrameRequestSource::LocalSchedule,
4377            ),
4378            (
4379                FrameRequestSource::LocalSchedule,
4380                FrameRequestSource::NativeCallback,
4381            ),
4382        ] {
4383            let signal = PlatformFrameSignal::new();
4384            let first =
4385                PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
4386            assert_eq!(signal.take(), None);
4387            signal.record(first + Duration::from_millis(16), later_source);
4388            signal.record(first, first_source);
4389            signal.record(first + Duration::from_millis(32), later_source);
4390            assert_eq!(signal.take(), Some((first, first_source)));
4391            assert_eq!(signal.take(), None);
4392            let next = first + Duration::from_millis(48);
4393            signal.record(next, later_source);
4394            assert_eq!(signal.take(), Some((next, later_source)));
4395        }
4396    }
4397
4398    #[cfg(not(feature = "profiler"))]
4399    #[test]
4400    fn disabled_profiling_does_not_capture_or_store_timestamps() {
4401        let captured = PlatformFrameSignal::capture(|| {
4402            panic!("profiler-disabled builds must not evaluate the capture closure");
4403        });
4404        assert_eq!(captured, None);
4405        let signal = PlatformFrameSignal::new();
4406        signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
4407        assert_eq!(signal.take(), None);
4408    }
4409}
4410
4411#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
4412mod tests {
4413    use super::*;
4414    use std::collections::HashSet;
4415
4416    #[test]
4417    fn test_refresh_interval_from_hz() {
4418        assert_eq!(
4419            refresh_interval_from_hz(50.0),
4420            Some(Duration::from_millis(20))
4421        );
4422        assert_eq!(
4423            refresh_interval_from_hz(120.0),
4424            Some(Duration::from_secs(1) / 120)
4425        );
4426        for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
4427            assert_eq!(refresh_interval_from_hz(unknown), None);
4428        }
4429    }
4430
4431    #[test]
4432    fn test_window_button_layout_parse_standard() {
4433        let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
4434        assert_eq!(
4435            layout.left,
4436            [
4437                Some(WindowButton::Close),
4438                Some(WindowButton::Minimize),
4439                None
4440            ]
4441        );
4442        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4443    }
4444
4445    #[test]
4446    fn test_window_button_layout_parse_right_only() {
4447        let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
4448        assert_eq!(layout.left, [None, None, None]);
4449        assert_eq!(
4450            layout.right,
4451            [
4452                Some(WindowButton::Minimize),
4453                Some(WindowButton::Maximize),
4454                Some(WindowButton::Close)
4455            ]
4456        );
4457    }
4458
4459    #[test]
4460    fn test_window_button_layout_parse_left_only() {
4461        let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
4462        assert_eq!(
4463            layout.left,
4464            [
4465                Some(WindowButton::Close),
4466                Some(WindowButton::Minimize),
4467                Some(WindowButton::Maximize)
4468            ]
4469        );
4470        assert_eq!(layout.right, [None, None, None]);
4471    }
4472
4473    #[test]
4474    fn test_window_button_layout_parse_with_whitespace() {
4475        let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
4476        assert_eq!(
4477            layout.left,
4478            [
4479                Some(WindowButton::Close),
4480                Some(WindowButton::Minimize),
4481                None
4482            ]
4483        );
4484        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4485    }
4486
4487    #[test]
4488    fn test_window_button_layout_parse_empty() {
4489        let layout = WindowButtonLayout::parse("").unwrap();
4490        assert_eq!(layout.left, [None, None, None]);
4491        assert_eq!(layout.right, [None, None, None]);
4492    }
4493
4494    #[test]
4495    fn test_window_button_layout_parse_intentionally_empty() {
4496        let layout = WindowButtonLayout::parse(":").unwrap();
4497        assert_eq!(layout.left, [None, None, None]);
4498        assert_eq!(layout.right, [None, None, None]);
4499    }
4500
4501    #[test]
4502    fn test_window_button_layout_parse_invalid_buttons() {
4503        let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
4504        assert_eq!(
4505            layout.left,
4506            [
4507                Some(WindowButton::Close),
4508                Some(WindowButton::Minimize),
4509                None
4510            ]
4511        );
4512        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4513    }
4514
4515    #[test]
4516    fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
4517        let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
4518        assert_eq!(
4519            layout.right,
4520            [
4521                Some(WindowButton::Close),
4522                Some(WindowButton::Minimize),
4523                None
4524            ]
4525        );
4526        assert_eq!(layout.format(), ":close,minimize");
4527    }
4528
4529    #[test]
4530    fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
4531        let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
4532        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4533        assert_eq!(
4534            layout.right,
4535            [
4536                Some(WindowButton::Maximize),
4537                Some(WindowButton::Minimize),
4538                None
4539            ]
4540        );
4541
4542        let button_ids: Vec<_> = layout
4543            .left
4544            .iter()
4545            .chain(layout.right.iter())
4546            .flatten()
4547            .map(WindowButton::id)
4548            .collect();
4549        let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4550        assert_eq!(unique_button_ids.len(), button_ids.len());
4551        assert_eq!(layout.format(), "close:maximize,minimize");
4552    }
4553
4554    #[test]
4555    fn test_window_button_layout_parse_gnome_style() {
4556        let layout = WindowButtonLayout::parse("close").unwrap();
4557        assert_eq!(layout.left, [None, None, None]);
4558        assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4559    }
4560
4561    #[test]
4562    fn test_window_button_layout_parse_elementary_style() {
4563        let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4564        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4565        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4566    }
4567
4568    #[test]
4569    fn test_window_button_layout_round_trip() {
4570        let cases = [
4571            "close:minimize,maximize",
4572            "minimize,maximize,close:",
4573            ":close",
4574            "close:",
4575            "close:maximize",
4576            ":",
4577        ];
4578
4579        for case in cases {
4580            let layout = WindowButtonLayout::parse(case).unwrap();
4581            assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4582        }
4583    }
4584
4585    #[test]
4586    fn test_window_button_layout_linux_default() {
4587        let layout = WindowButtonLayout::linux_default();
4588        assert_eq!(layout.left, [None, None, None]);
4589        assert_eq!(
4590            layout.right,
4591            [
4592                Some(WindowButton::Minimize),
4593                Some(WindowButton::Maximize),
4594                Some(WindowButton::Close)
4595            ]
4596        );
4597
4598        let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4599        assert_eq!(round_tripped, layout);
4600    }
4601
4602    #[test]
4603    fn test_window_button_layout_parse_all_invalid() {
4604        assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4605    }
4606}