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    /// The brightest value the content needs, in units of SDR white. macOS tags the layer with it
2211    /// so the system raises the screen's headroom no further; Windows and wgpu ignore it.
2212    pub content_headroom: f32,
2213}
2214
2215/// vue-native fork: IEEE binary16 bits to `f32`, for the renderers' half-float readbacks.
2216#[doc(hidden)]
2217pub fn half_to_f32(bits: u16) -> f32 {
2218    let exponent = (bits >> 10) & 0x1f;
2219    let mantissa = u32::from(bits & 0x3ff);
2220    let magnitude = match exponent {
2221        0 => mantissa as f32 / 16_777_216.0,
2222        31 if mantissa == 0 => f32::INFINITY,
2223        31 => f32::NAN,
2224        _ => f32::from_bits(((u32::from(exponent) + 112) << 23) | (mantissa << 13)),
2225    };
2226    if bits & 0x8000 != 0 {
2227        -magnitude
2228    } else {
2229        magnitude
2230    }
2231}
2232
2233/// vue-native fork: where [`crate::Window::write_image_tile`] takes a frame's
2234/// pixels from.
2235#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2236pub enum TileSource {
2237    /// The image's own bytes (BGRA, straight alpha, as every sprite tile
2238    /// holds them), e.g. from
2239    /// [`crate::RenderImage::successor`].
2240    Bytes,
2241    /// A texture already on the renderer's device, with the contract of
2242    /// [`PlatformAtlas::upload_from_gpu`].
2243    Gpu(GpuTextureHandle),
2244}
2245
2246/// vue-native fork: what [`crate::Window::write_image_tile`] did with a frame.
2247#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2248pub enum TileWrite {
2249    /// The tile the key had was overwritten where it lies. A scene that
2250    /// painted the image samples the new pixels on its next present
2251    /// ([`crate::Window::request_present`]).
2252    InPlace,
2253    /// The frame went into a tile the key did not have before this write (the
2254    /// first write, a new size, a backend with no in-place path, a tile the
2255    /// atlas had dropped). Only a draw shows it.
2256    Placed,
2257    /// The backend refused the GPU texture; nothing was written. The caller
2258    /// falls back to [`TileSource::Bytes`].
2259    Refused,
2260}
2261
2262impl GpuTextureHandle {
2263    /// The null handle — "there is no texture", which every backend rejects.
2264    pub const NULL: Self = Self(std::ptr::null_mut());
2265
2266    /// Is this the null handle?
2267    pub fn is_null(&self) -> bool {
2268        self.0.is_null()
2269    }
2270}
2271
2272#[doc(hidden)]
2273pub trait AtlasBackend {
2274    fn insert(
2275        &mut self,
2276        kind: AtlasTextureKind,
2277        size: Size<DevicePixels>,
2278        bytes: &[u8],
2279    ) -> Result<AtlasTile>;
2280
2281    fn remove(&mut self, tile: AtlasTile);
2282}
2283
2284#[doc(hidden)]
2285pub struct AtlasState<Backend> {
2286    tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
2287    pub backend: Backend,
2288}
2289
2290impl<Backend> AtlasState<Backend> {
2291    pub fn new(backend: Backend) -> Self {
2292        Self {
2293            tiles_by_key: FxHashMap::default(),
2294            backend,
2295        }
2296    }
2297
2298    pub fn contains(&self, key: &AtlasKey) -> bool {
2299        self.tiles_by_key.contains_key(key)
2300    }
2301
2302    pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
2303        self.tiles_by_key.clear();
2304        reset_backend(&mut self.backend);
2305    }
2306
2307    /// vue-native fork: the tile `key` maps to, if any. For a backend's
2308    /// [`PlatformAtlas::upload_from_gpu`], which reuses one tile per key in
2309    /// place rather than memoising a build.
2310    pub fn tile(&self, key: &AtlasKey) -> Option<AtlasTile> {
2311        self.tiles_by_key.get(key).copied()
2312    }
2313
2314    /// vue-native fork: records a tile the backend allocated itself (the
2315    /// `upload_from_gpu` path) so [`AtlasState::remove`] and [`AtlasState::clear`]
2316    /// free it like any other.
2317    pub fn insert_tile(&mut self, key: AtlasKey, tile: AtlasTile) {
2318        self.tiles_by_key.insert(key, tile);
2319    }
2320
2321    /// vue-native fork: fills the key counts of an [`AtlasStats`] — how many
2322    /// keys map to a tile, and how many of those are image frames and what
2323    /// they cover. The backend fills the per-kind pages.
2324    pub fn count_keys(&self, stats: &mut AtlasStats) {
2325        stats.keys = self.tiles_by_key.len() as u32;
2326        for (key, tile) in &self.tiles_by_key {
2327            let pixels =
2328                (tile.bounds.size.width.0.max(0) as u64) * (tile.bounds.size.height.0.max(0) as u64);
2329            stats.kinds[tile.texture_id.kind as usize].tile_pixels += pixels;
2330            if let AtlasKey::Image(_) = key {
2331                stats.image_keys += 1;
2332                stats.image_pixels += pixels;
2333            }
2334        }
2335    }
2336}
2337
2338impl<Backend: Default> Default for AtlasState<Backend> {
2339    fn default() -> Self {
2340        Self::new(Backend::default())
2341    }
2342}
2343
2344impl<Backend: AtlasBackend> AtlasState<Backend> {
2345    pub fn get_or_insert_with<'a>(
2346        &mut self,
2347        key: AtlasKey,
2348        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2349    ) -> Result<Option<AtlasTile>> {
2350        match self.tiles_by_key.entry(key) {
2351            Entry::Occupied(entry) => Ok(Some(*entry.get())),
2352            Entry::Vacant(entry) => {
2353                profiling::scope!("new tile");
2354                let Some((size, bytes)) = build()? else {
2355                    return Ok(None);
2356                };
2357                let tile = self
2358                    .backend
2359                    .insert(entry.key().texture_kind(), size, &bytes)?;
2360                entry.insert(tile);
2361                Ok(Some(tile))
2362            }
2363        }
2364    }
2365
2366    pub fn remove(&mut self, key: &AtlasKey) {
2367        if let Some(tile) = self.tiles_by_key.remove(key) {
2368            self.backend.remove(tile);
2369        }
2370    }
2371}
2372
2373/// A sprite atlas for windows without a GPU. It hands out uniquely identified
2374/// tiles without uploading any pixels, so glyph, SVG, and image painting can
2375/// run to completion in tests and headless platforms.
2376#[derive(Default)]
2377pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
2378
2379#[doc(hidden)]
2380#[derive(Default)]
2381pub struct HeadlessAtlasBackend {
2382    next_id: u32,
2383}
2384
2385impl AtlasBackend for HeadlessAtlasBackend {
2386    fn insert(
2387        &mut self,
2388        kind: AtlasTextureKind,
2389        size: Size<DevicePixels>,
2390        _bytes: &[u8],
2391    ) -> Result<AtlasTile> {
2392        self.next_id += 1;
2393        let texture_id = self.next_id;
2394        self.next_id += 1;
2395        let tile_id = self.next_id;
2396        Ok(AtlasTile {
2397            texture_id: AtlasTextureId {
2398                index: texture_id,
2399                kind,
2400            },
2401            tile_id: TileId(tile_id),
2402            padding: 0,
2403            bounds: Bounds {
2404                origin: Point::default(),
2405                size,
2406            },
2407        })
2408    }
2409
2410    fn remove(&mut self, _tile: AtlasTile) {}
2411}
2412
2413impl PlatformAtlas for HeadlessAtlas {
2414    fn get_or_insert_with<'a>(
2415        &self,
2416        key: AtlasKey,
2417        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2418    ) -> Result<Option<AtlasTile>> {
2419        self.0.lock().get_or_insert_with(key, build)
2420    }
2421
2422    fn remove(&self, key: &AtlasKey) {
2423        self.0.lock().remove(key);
2424    }
2425
2426    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2427    fn contains(&self, key: &AtlasKey) -> bool {
2428        self.0.lock().contains(key)
2429    }
2430}
2431
2432#[doc(hidden)]
2433pub struct AtlasTextureList<T> {
2434    pub textures: Vec<Option<T>>,
2435    pub free_list: Vec<usize>,
2436}
2437
2438impl<T> Default for AtlasTextureList<T> {
2439    fn default() -> Self {
2440        Self {
2441            textures: Vec::default(),
2442            free_list: Vec::default(),
2443        }
2444    }
2445}
2446
2447impl<T> ops::Index<usize> for AtlasTextureList<T> {
2448    type Output = Option<T>;
2449
2450    fn index(&self, index: usize) -> &Self::Output {
2451        &self.textures[index]
2452    }
2453}
2454
2455impl<T> AtlasTextureList<T> {
2456    #[allow(unused)]
2457    pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2458        self.free_list.clear();
2459        self.textures.drain(..)
2460    }
2461
2462    #[allow(dead_code)]
2463    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2464        self.textures.iter_mut().flatten()
2465    }
2466}
2467
2468#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2469#[repr(C)]
2470#[expect(missing_docs)]
2471pub struct AtlasTile {
2472    /// The texture this tile belongs to.
2473    pub texture_id: AtlasTextureId,
2474    /// The unique ID of this tile within its texture.
2475    pub tile_id: TileId,
2476    /// Padding around the tile content in pixels.
2477    pub padding: u32,
2478    /// The bounds of this tile within the texture.
2479    pub bounds: Bounds<DevicePixels>,
2480}
2481
2482#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2483#[repr(C)]
2484#[expect(missing_docs)]
2485pub struct AtlasTextureId {
2486    // We use u32 instead of usize for Metal Shader Language compatibility
2487    /// The index of this texture in the atlas.
2488    pub index: u32,
2489    /// The kind of content stored in this texture.
2490    pub kind: AtlasTextureKind,
2491}
2492
2493#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2494#[repr(C)]
2495#[cfg_attr(
2496    all(
2497        any(target_os = "linux", target_os = "freebsd"),
2498        not(any(feature = "x11", feature = "wayland"))
2499    ),
2500    allow(dead_code)
2501)]
2502#[expect(missing_docs)]
2503pub enum AtlasTextureKind {
2504    Monochrome = 0,
2505    Polychrome = 1,
2506    Subpixel = 2,
2507    /// vue-native fork: RGBA half floats in linear extended sRGB (1.0 is SDR white), straight
2508    /// alpha. A sprite encodes them to sRGB after clamping to its [`PolychromeSprite`]'s
2509    /// headroom, so values above 1.0 reach an HDR target ([`HdrOutput`]).
2510    ///
2511    /// [`PolychromeSprite`]: crate::PolychromeSprite
2512    PolychromeHdr = 3,
2513}
2514
2515#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2516#[repr(C)]
2517#[expect(missing_docs)]
2518pub struct TileId(pub u32);
2519
2520impl From<etagere::AllocId> for TileId {
2521    fn from(id: etagere::AllocId) -> Self {
2522        Self(id.serialize())
2523    }
2524}
2525
2526impl From<TileId> for etagere::AllocId {
2527    fn from(id: TileId) -> Self {
2528        Self::deserialize(id.0)
2529    }
2530}
2531
2532#[expect(missing_docs)]
2533pub struct PlatformInputHandler {
2534    cx: AsyncWindowContext,
2535    handler: Box<dyn InputHandler>,
2536    focus_id: Option<crate::FocusId>,
2537}
2538
2539#[expect(missing_docs)]
2540#[cfg_attr(
2541    all(
2542        any(target_os = "linux", target_os = "freebsd"),
2543        not(any(feature = "x11", feature = "wayland"))
2544    ),
2545    allow(dead_code)
2546)]
2547impl PlatformInputHandler {
2548    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2549        Self {
2550            cx,
2551            handler,
2552            focus_id: None,
2553        }
2554    }
2555
2556    pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2557        self.focus_id = Some(focus_id);
2558        self
2559    }
2560
2561    /// Identifies the input field registered through [`Window::handle_input`].
2562    ///
2563    /// This identity survives adapter replacement during repaint. Backends can
2564    /// use it to detect a field change without restarting the keyboard session.
2565    pub fn focus_id(&self) -> Option<crate::FocusId> {
2566        self.focus_id
2567    }
2568
2569    pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2570        self.cx
2571            .update(|window, cx| {
2572                self.handler
2573                    .selected_text_range(ignore_disabled_input, window, cx)
2574            })
2575            .ok()
2576            .flatten()
2577    }
2578
2579    #[cfg_attr(target_os = "windows", allow(dead_code))]
2580    pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2581        self.cx
2582            .update(|window, cx| self.handler.marked_text_range(window, cx))
2583            .ok()
2584            .flatten()
2585    }
2586
2587    #[cfg_attr(
2588        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2589        allow(dead_code)
2590    )]
2591    pub fn text_for_range(
2592        &mut self,
2593        range_utf16: Range<usize>,
2594        adjusted: &mut Option<Range<usize>>,
2595    ) -> Option<String> {
2596        self.cx
2597            .update(|window, cx| {
2598                self.handler
2599                    .text_for_range(range_utf16, adjusted, window, cx)
2600            })
2601            .ok()
2602            .flatten()
2603    }
2604
2605    pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2606        self.cx
2607            .update(|window, cx| {
2608                self.handler
2609                    .replace_text_in_range(replacement_range, text, window, cx);
2610            })
2611            .ok();
2612    }
2613
2614    pub fn replace_and_mark_text_in_range(
2615        &mut self,
2616        range_utf16: Option<Range<usize>>,
2617        new_text: &str,
2618        new_selected_range: Option<Range<usize>>,
2619    ) {
2620        self.cx
2621            .update(|window, cx| {
2622                self.handler.replace_and_mark_text_in_range(
2623                    range_utf16,
2624                    new_text,
2625                    new_selected_range,
2626                    window,
2627                    cx,
2628                )
2629            })
2630            .ok();
2631    }
2632
2633    #[cfg_attr(target_os = "windows", allow(dead_code))]
2634    pub fn unmark_text(&mut self) {
2635        self.cx
2636            .update(|window, cx| self.handler.unmark_text(window, cx))
2637            .ok();
2638    }
2639
2640    pub fn paste(&mut self, item: ClipboardItem) {
2641        self.cx
2642            .update(|window, cx| self.handler.paste(item, window, cx))
2643            .ok();
2644    }
2645
2646    pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2647        self.cx
2648            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2649            .ok()
2650            .flatten()
2651    }
2652
2653    pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2654        self.cx
2655            .update(|window, cx| {
2656                self.handler
2657                    .selection_bounds_for_range(range_utf16, window, cx)
2658            })
2659            .unwrap_or_default()
2660    }
2661
2662    #[allow(dead_code)]
2663    pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2664        self.handler.apple_press_and_hold_enabled()
2665    }
2666
2667    pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2668        self.handler.replace_text_in_range(None, input, window, cx);
2669    }
2670
2671    pub fn compute_ime_candidate_bounds(
2672        marked_range: Option<Range<usize>>,
2673        selection: &UTF16Selection,
2674        mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2675    ) -> Option<Bounds<Pixels>> {
2676        if let Some(marked_range) = marked_range {
2677            // Default to the start of the marked (composing) range.
2678            let mut line_start = marked_range.start;
2679
2680            // Walk backward from the caret looking for a line break. A change in
2681            // the Y coordinate means we crossed into the previous visual line, so
2682            // the line start is one position after the break point.
2683            let caret = selection.range.end;
2684            if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2685                for i in (marked_range.start..caret).rev() {
2686                    if let Some(b) = bounds_for_range(i..i) {
2687                        if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2688                            line_start = i + 1;
2689                            break;
2690                        }
2691                    }
2692                }
2693            }
2694            bounds_for_range(line_start..line_start)
2695        } else {
2696            // No active composition — use the selection endpoint.
2697            let offset = if selection.reversed {
2698                selection.range.start
2699            } else {
2700                selection.range.end
2701            };
2702            bounds_for_range(offset..offset)
2703        }
2704    }
2705
2706    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2707        let marked_range = self.handler.marked_text_range(window, cx);
2708        let selection = self.handler.selected_text_range(true, window, cx)?;
2709        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2710            self.handler.bounds_for_range(range, window, cx)
2711        })
2712    }
2713
2714    pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2715        let marked_range = self.marked_text_range();
2716        let selection = self.selected_text_range(true)?;
2717        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2718            self.bounds_for_range(range)
2719        })
2720    }
2721
2722    #[allow(unused)]
2723    pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2724        self.cx
2725            .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2726            .ok()
2727            .flatten()
2728    }
2729
2730    /// See [`InputHandler::set_selected_text_range`].
2731    pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2732        self.cx
2733            .update(|window, cx| {
2734                self.handler
2735                    .set_selected_text_range(range_utf16, window, cx)
2736            })
2737            .ok();
2738    }
2739
2740    /// See [`InputHandler::element_bounds`].
2741    pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2742        self.cx
2743            .update(|window, cx| self.handler.element_bounds(window, cx))
2744            .ok()
2745            .flatten()
2746    }
2747
2748    /// See [`InputHandler::text_length_utf16`].
2749    pub fn text_length_utf16(&mut self) -> Option<usize> {
2750        self.cx
2751            .update(|window, cx| self.handler.text_length_utf16(window, cx))
2752            .ok()
2753            .flatten()
2754    }
2755
2756    #[allow(dead_code)]
2757    pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2758        self.handler.accepts_text_input(window, cx)
2759    }
2760
2761    #[allow(dead_code)]
2762    pub fn query_accepts_text_input(&mut self) -> bool {
2763        self.cx
2764            .update(|window, cx| self.handler.accepts_text_input(window, cx))
2765            .unwrap_or(true)
2766    }
2767
2768    /// Checks eligibility against the current focus, including before the next frame is drawn.
2769    ///
2770    /// Unlike the legacy acceptance query, this fails closed when the window cannot
2771    /// be updated and requires registration through `Window::handle_input`.
2772    pub fn query_accepts_focused_text_input(&mut self) -> bool {
2773        let focus_id = self.focus_id;
2774        self.cx
2775            .update(|window, cx| {
2776                focus_id.is_some()
2777                    && window.focus == focus_id
2778                    && self.handler.accepts_text_input(window, cx)
2779            })
2780            .unwrap_or(false)
2781    }
2782
2783    /// See [`InputHandler::prefers_ime_for_printable_keys`].
2784    ///
2785    /// This is not a pure delegation to the handler: while a multi-stroke binding is pending this
2786    /// returns `false` regardless of the handler's preference, because the next printable key may
2787    /// complete a binding whose prefix already bypassed the IME.
2788    pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2789        self.cx
2790            .update(|window, cx| {
2791                // The next printable key may complete a chord whose prefix bypassed the IME.
2792                !window.has_pending_keystrokes()
2793                    && self.handler.prefers_ime_for_printable_keys(window, cx)
2794            })
2795            .unwrap_or(false)
2796    }
2797
2798    /// See [`InputHandler::text_input_configuration`].
2799    pub fn text_input_configuration(
2800        &mut self,
2801        window: &mut Window,
2802        cx: &mut App,
2803    ) -> TextInputConfiguration {
2804        self.handler.text_input_configuration(window, cx)
2805    }
2806
2807    /// See [`InputHandler::text_input_editable_range`].
2808    pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2809        self.cx
2810            .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2811            .ok()
2812            .flatten()
2813    }
2814}
2815
2816/// A struct representing a selection in a text buffer, in UTF16 characters.
2817/// This is different from a range because the head may be before the tail.
2818#[derive(Debug)]
2819pub struct UTF16Selection {
2820    /// The range of text in the document this selection corresponds to
2821    /// in UTF16 characters.
2822    pub range: Range<usize>,
2823    /// Whether the head of this selection is at the start (true), or end (false)
2824    /// of the range
2825    pub reversed: bool,
2826}
2827
2828/// GPUI's interface for native text input, IME composition, and selection.
2829/// Platform backends translate their native text protocols into these operations.
2830///
2831/// Text offsets and ranges use UTF-16 code units unless stated otherwise.
2832pub trait InputHandler: 'static {
2833    /// Get the range of the user's currently selected text, if any
2834    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
2835    ///
2836    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
2837    fn selected_text_range(
2838        &mut self,
2839        ignore_disabled_input: bool,
2840        window: &mut Window,
2841        cx: &mut App,
2842    ) -> Option<UTF16Selection>;
2843
2844    /// Get the range of the currently marked text, if any
2845    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
2846    ///
2847    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
2848    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2849
2850    /// Get the text for the given document range in UTF-16 characters
2851    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
2852    ///
2853    /// range_utf16 is in terms of UTF-16 characters
2854    fn text_for_range(
2855        &mut self,
2856        range_utf16: Range<usize>,
2857        adjusted_range: &mut Option<Range<usize>>,
2858        window: &mut Window,
2859        cx: &mut App,
2860    ) -> Option<String>;
2861
2862    /// Replace the text in the given document range with the given text
2863    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
2864    ///
2865    /// replacement_range is in terms of UTF-16 characters
2866    fn replace_text_in_range(
2867        &mut self,
2868        replacement_range: Option<Range<usize>>,
2869        text: &str,
2870        window: &mut Window,
2871        cx: &mut App,
2872    );
2873
2874    /// Replace the text in the given document range with the given text,
2875    /// and mark the given text as part of an IME 'composing' state
2876    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
2877    ///
2878    /// range_utf16 is in terms of UTF-16 characters
2879    /// new_selected_range is in terms of UTF-16 characters
2880    fn replace_and_mark_text_in_range(
2881        &mut self,
2882        range_utf16: Option<Range<usize>>,
2883        new_text: &str,
2884        new_selected_range: Option<Range<usize>>,
2885        window: &mut Window,
2886        cx: &mut App,
2887    );
2888
2889    /// Remove the IME 'composing' state from the document
2890    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
2891    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2892
2893    /// Insert a platform-initiated paste at the current selection.
2894    ///
2895    /// Platforms that deliver paste as an input event rather than through an
2896    /// application-defined action (e.g. the DOM `paste` event on web) call
2897    /// this with the full clipboard contents. The default implementation
2898    /// inserts only the plain-text portion of the item.
2899    fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2900        if let Some(text) = item.text() {
2901            self.replace_text_in_range(None, &text, window, cx);
2902        }
2903    }
2904
2905    /// Get the bounds of the given document range in window coordinates.
2906    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
2907    ///
2908    /// This is used for positioning the IME candidate window
2909    fn bounds_for_range(
2910        &mut self,
2911        range_utf16: Range<usize>,
2912        window: &mut Window,
2913        cx: &mut App,
2914    ) -> Option<Bounds<Pixels>>;
2915
2916    /// Returns selection rectangles in document order, in window coordinates.
2917    ///
2918    /// Return line or shaped-run fragments, not one rectangle per character. The
2919    /// first and last rectangles contain the range's start and end respectively.
2920    /// Empty means native selection geometry is unavailable; caret/IME geometry can
2921    /// still be supplied by `bounds_for_range`.
2922    fn selection_bounds_for_range(
2923        &mut self,
2924        _range_utf16: Range<usize>,
2925        _window: &mut Window,
2926        _cx: &mut App,
2927    ) -> Vec<Bounds<Pixels>> {
2928        Vec::new()
2929    }
2930
2931    /// Get the character offset for the given point in terms of UTF16 characters
2932    ///
2933    /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
2934    fn character_index_for_point(
2935        &mut self,
2936        point: Point<Pixels>,
2937        window: &mut Window,
2938        cx: &mut App,
2939    ) -> Option<usize>;
2940
2941    /// Set the range of the user's currently selected text.
2942    ///
2943    /// This is the reverse data-flow direction from [`Self::selected_text_range`]:
2944    /// platforms call it when the system text machinery moves the selection on the
2945    /// application's behalf — e.g. the user drags a system selection handle or
2946    /// invokes Select All from system UI (iOS `UITextInput setSelectedTextRange:`,
2947    /// Android `InputConnection.setSelection`).
2948    ///
2949    /// range_utf16 is in terms of UTF-16 characters, from 0 to the length of the document
2950    fn set_selected_text_range(
2951        &mut self,
2952        _range_utf16: Range<usize>,
2953        _window: &mut Window,
2954        _cx: &mut App,
2955    ) {
2956    }
2957
2958    /// Get the bounds of the focused text element in window coordinates, if known.
2959    ///
2960    /// This is the pull counterpart to the [`PlatformWindow::update_ime_position`]
2961    /// push: mobile platforms ask for the focused element's geometry when they
2962    /// need it (e.g. to frame system text-interaction UI overlaid on the focused
2963    /// element).
2964    fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2965        None
2966    }
2967
2968    /// Get the length of the document in UTF-16 characters, if known.
2969    fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2970        None
2971    }
2972
2973    /// Allows a given input context to opt into getting raw key repeats instead of
2974    /// sending these to the platform.
2975    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
2976    /// (which is how iTerm does it) but it doesn't seem to work for me.
2977    #[allow(dead_code)]
2978    fn apple_press_and_hold_enabled(&mut self) -> bool {
2979        true
2980    }
2981
2982    /// Returns whether this handler is accepting text input to be inserted.
2983    fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2984        true
2985    }
2986
2987    /// The contiguous range of text, in UTF-16 code units, that platform text
2988    /// input may read and edit around the current selection.
2989    ///
2990    /// Platforms that mirror document text into an IME-editable buffer clamp
2991    /// the mirrored window to this range, so multi-step IME edit gestures
2992    /// (word deletion, autocorrect rewrites, suggestion picks) cannot reach
2993    /// content outside it. The range should contain the current selection;
2994    /// when it cannot (a selection spanning a region boundary), platforms
2995    /// degrade the mirrored IME context rather than widening the range.
2996    /// `None` places no bound.
2997    fn text_input_editable_range(
2998        &mut self,
2999        _window: &mut Window,
3000        _cx: &mut App,
3001    ) -> Option<Range<usize>> {
3002        None
3003    }
3004
3005    /// Returns whether printable keys should be routed to the IME before keybinding
3006    /// matching when a non-ASCII input source (e.g. Japanese, Korean, Chinese IME)
3007    /// is active. This prevents multi-stroke keybindings like `jj` from intercepting
3008    /// keys that the IME should compose.
3009    ///
3010    /// Defaults to `false`. The editor overrides this based on whether it expects
3011    /// character input (e.g. Vim insert mode returns `true`, normal mode returns `false`).
3012    /// The terminal keeps the default `false` so that raw keys reach the terminal process.
3013    fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
3014        false
3015    }
3016
3017    /// Get this handler's preferences for platform text assistance.
3018    ///
3019    /// GPUI re-queries this every frame and forwards it to the platform window
3020    /// only when it changes, so implementations must be cheap and may vary the
3021    /// result with application state (e.g. with the cursor's position).
3022    fn text_input_configuration(
3023        &mut self,
3024        _window: &mut Window,
3025        _cx: &mut App,
3026    ) -> TextInputConfiguration {
3027        TextInputConfiguration::default()
3028    }
3029}
3030
3031/// Platform text-assistance preferences for the focused text region.
3032///
3033/// Returned by [`InputHandler::text_input_configuration`] and forwarded to the
3034/// platform whenever it changes; the platform maps the fields onto its native
3035/// input-session attributes (on web, DOM attributes of the hidden editable
3036/// element such as `autocorrect` and `enterkeyhint`).
3037///
3038/// The default disables all text assistance and requests no particular action
3039/// key presentation.
3040#[derive(Clone, Debug, Default, PartialEq, Eq)]
3041pub struct TextInputConfiguration {
3042    /// Whether the platform may automatically correct entered text.
3043    pub autocorrect: bool,
3044    /// How software keyboards automatically capitalize entered text.
3045    pub autocapitalize: Autocapitalize,
3046    /// Whether software keyboards may offer word suggestions and spellcheck.
3047    pub suggestions: bool,
3048    /// The action advertised on a software keyboard's confirm ("enter") key.
3049    pub input_action: TextInputAction,
3050}
3051
3052/// Automatic capitalization applied by software keyboards.
3053#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3054pub enum Autocapitalize {
3055    /// No automatic capitalization.
3056    #[default]
3057    None,
3058    /// Capitalize the first letter of each word.
3059    Words,
3060    /// Capitalize the first letter of each sentence.
3061    Sentences,
3062    /// Capitalize every letter.
3063    Characters,
3064}
3065
3066/// The action a software keyboard advertises on its confirm ("enter") key.
3067///
3068/// This affects only how the key is presented (icon or label); pressing it is
3069/// still delivered as ordinary input.
3070///
3071/// The variants are the HTML `enterkeyhint` attribute's value set
3072/// (<https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-enterkeyhint-attribute>),
3073/// which also maps onto Android's `IME_ACTION_*` constants and iOS's
3074/// `UIReturnKeyType`; [`TextInputAction::Unspecified`] means "emit no hint".
3075#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3076pub enum TextInputAction {
3077    /// Let the platform choose its default presentation.
3078    #[default]
3079    Unspecified,
3080    /// Inserting a line break.
3081    Enter,
3082    /// Committing the field's value.
3083    Done,
3084    /// Navigating to the typed target.
3085    Go,
3086    /// Moving to the next field.
3087    Next,
3088    /// Moving to the previous field.
3089    Previous,
3090    /// Executing a search.
3091    Search,
3092    /// Sending a message.
3093    Send,
3094}
3095
3096/// The variables that can be configured when creating a new window
3097#[derive(Debug)]
3098pub struct WindowOptions {
3099    /// Specifies the state and bounds of the window in screen coordinates.
3100    /// - `None`: Inherit the bounds.
3101    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
3102    pub window_bounds: Option<WindowBounds>,
3103
3104    /// The titlebar configuration of the window
3105    pub titlebar: Option<TitlebarOptions>,
3106
3107    /// Whether the window should be focused when created
3108    pub focus: bool,
3109
3110    /// Whether the window should be shown when created
3111    pub show: bool,
3112
3113    /// The kind of window to create
3114    pub kind: WindowKind,
3115
3116    /// Whether the window can be moved by the user. When `false`, the user cannot drag
3117    /// the window (on macOS this sets `NSWindow.isMovable`, which also disables the
3118    /// Window-menu tiling items); programmatic moves are still allowed.
3119    pub is_movable: bool,
3120
3121    /// Whether the application owns dragging of the (custom) titlebar, rather than
3122    /// AppKit. Only has an effect on macOS.
3123    ///
3124    /// Set this to `true` for windows that draw their own titlebar and move the window
3125    /// themselves via [`Window::start_window_move`]. It marks the whole content view as
3126    /// app-owned titlebar content, so AppKit neither drags the window from the titlebar
3127    /// nor delays titlebar clicks while disambiguating double-clicks (a delay first
3128    /// observed on macOS 27). It is independent of `is_movable`, so such windows stay
3129    /// user-movable (via their own drag) and keep the Window-menu tiling items enabled.
3130    ///
3131    /// Leave this `false` for windows that rely on AppKit's native titlebar dragging.
3132    pub app_owns_titlebar_drag: bool,
3133
3134    /// The minimum frame interval while inactive without sustained high-rate input.
3135    ///
3136    /// Defaults to approximately 30 fps. Set to `None` to disable this limit.
3137    /// The longest applicable interval wins; mandatory platform presentations bypass all limits.
3138    pub inactive_frame_interval: Option<Duration>,
3139
3140    /// The minimum frame interval while the platform reports Low Power Mode.
3141    ///
3142    /// Defaults to approximately 30 fps. Set to `None` to disable this limit.
3143    /// The longest applicable interval wins; mandatory platform presentations bypass all limits.
3144    pub low_power_frame_interval: Option<Duration>,
3145
3146    /// The minimum frame interval under serious or critical thermal pressure.
3147    ///
3148    /// Defaults to approximately 60 fps. Set to `None` to disable this limit.
3149    /// The longest applicable interval wins; mandatory platform presentations bypass all limits.
3150    pub thermal_frame_interval: Option<Duration>,
3151
3152    /// Whether the window should be resizable by the user
3153    pub is_resizable: bool,
3154
3155    /// Whether the window should be minimized by the user
3156    pub is_minimizable: bool,
3157
3158    /// The display to create the window on. If neither this nor `window_bounds` is set, the window
3159    /// is created on the active window's display. Otherwise, it falls back to the primary display.
3160    pub display_id: Option<DisplayId>,
3161
3162    /// The appearance of the window background.
3163    pub window_background: WindowBackgroundAppearance,
3164
3165    /// Application identifier of the window. Can by used by desktop environments to group applications together.
3166    pub app_id: Option<String>,
3167
3168    /// Window minimum size
3169    pub window_min_size: Option<Size<Pixels>>,
3170
3171    /// Whether to use client or server-side decorations on X11 and Wayland.
3172    /// The platform may ignore requests it cannot satisfy.
3173    pub window_decorations: Option<WindowDecorations>,
3174
3175    /// Icon image (X11 only)
3176    pub icon: Option<Arc<image::RgbaImage>>,
3177
3178    /// 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.
3179    pub tabbing_identifier: Option<String>,
3180
3181    /// Whether to render the window using the Display P3 color space on macOS.
3182    pub use_display_p3: bool,
3183}
3184
3185/// The variables that can be configured when creating a new window
3186#[derive(Debug)]
3187#[cfg_attr(
3188    all(
3189        any(target_os = "linux", target_os = "freebsd"),
3190        not(any(feature = "x11", feature = "wayland"))
3191    ),
3192    allow(dead_code)
3193)]
3194#[allow(missing_docs)]
3195pub struct WindowParams {
3196    pub bounds: Bounds<Pixels>,
3197
3198    /// The titlebar configuration of the window
3199    #[cfg_attr(feature = "wayland", allow(dead_code))]
3200    pub titlebar: Option<TitlebarOptions>,
3201
3202    /// The kind of window to create
3203    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3204    pub kind: WindowKind,
3205
3206    /// Whether the window should be movable by the user
3207    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3208    pub is_movable: bool,
3209
3210    /// Whether the application owns dragging of the (custom) titlebar (macOS only)
3211    #[cfg_attr(
3212        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3213        allow(dead_code)
3214    )]
3215    pub app_owns_titlebar_drag: bool,
3216
3217    /// Whether the window should be resizable by the user
3218    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3219    pub is_resizable: bool,
3220
3221    /// Whether the window should be minimized by the user
3222    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3223    pub is_minimizable: bool,
3224
3225    #[cfg_attr(
3226        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3227        allow(dead_code)
3228    )]
3229    pub focus: bool,
3230
3231    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3232    pub show: bool,
3233
3234    /// An image to set as the window icon (x11 only)
3235    #[cfg_attr(feature = "wayland", allow(dead_code))]
3236    pub icon: Option<Arc<image::RgbaImage>>,
3237
3238    #[cfg_attr(feature = "wayland", allow(dead_code))]
3239    pub display_id: Option<DisplayId>,
3240
3241    #[cfg_attr(feature = "wayland", allow(dead_code))]
3242    pub app_id: Option<String>,
3243
3244    pub window_min_size: Option<Size<Pixels>>,
3245
3246    #[cfg(target_os = "macos")]
3247    pub tabbing_identifier: Option<String>,
3248
3249    #[cfg(target_os = "macos")]
3250    pub use_display_p3: bool,
3251}
3252
3253/// Represents the status of how a window should be opened.
3254#[derive(Debug, Copy, Clone, PartialEq)]
3255pub enum WindowBounds {
3256    /// Indicates that the window should open in a windowed state with the given bounds.
3257    Windowed(Bounds<Pixels>),
3258    /// Indicates that the window should open in a maximized state.
3259    /// The bounds provided here represent the restore size of the window.
3260    Maximized(Bounds<Pixels>),
3261    /// Indicates that the window should open in fullscreen mode.
3262    /// The bounds provided here represent the restore size of the window.
3263    Fullscreen(Bounds<Pixels>),
3264}
3265
3266impl Default for WindowBounds {
3267    fn default() -> Self {
3268        WindowBounds::Windowed(Bounds::default())
3269    }
3270}
3271
3272impl WindowBounds {
3273    /// Retrieve the inner bounds
3274    pub fn get_bounds(&self) -> Bounds<Pixels> {
3275        match self {
3276            WindowBounds::Windowed(bounds) => *bounds,
3277            WindowBounds::Maximized(bounds) => *bounds,
3278            WindowBounds::Fullscreen(bounds) => *bounds,
3279        }
3280    }
3281
3282    /// Creates window bounds centered on the given display, or the primary display if none is
3283    /// provided.
3284    pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
3285        WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
3286    }
3287}
3288
3289impl Default for WindowOptions {
3290    fn default() -> Self {
3291        Self {
3292            window_bounds: None,
3293            titlebar: Some(TitlebarOptions {
3294                title: Default::default(),
3295                appears_transparent: Default::default(),
3296                traffic_light_position: Default::default(),
3297            }),
3298            focus: true,
3299            show: true,
3300            kind: WindowKind::Normal,
3301            is_movable: true,
3302            app_owns_titlebar_drag: false,
3303            inactive_frame_interval: Some(Duration::from_micros(33_333)),
3304            low_power_frame_interval: Some(Duration::from_micros(33_333)),
3305            thermal_frame_interval: Some(Duration::from_micros(16_667)),
3306            is_resizable: true,
3307            is_minimizable: true,
3308            display_id: None,
3309            window_background: WindowBackgroundAppearance::default(),
3310            icon: None,
3311            app_id: None,
3312            window_min_size: None,
3313            window_decorations: None,
3314            tabbing_identifier: None,
3315            use_display_p3: false,
3316        }
3317    }
3318}
3319
3320/// The options that can be configured for a window's titlebar
3321#[derive(Debug, Default)]
3322pub struct TitlebarOptions {
3323    /// The initial title of the window
3324    pub title: Option<SharedString>,
3325
3326    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
3327    /// Refer to [`WindowOptions::window_decorations`] on Linux
3328    pub appears_transparent: bool,
3329
3330    /// The position of the macOS traffic light buttons
3331    pub traffic_light_position: Option<Point<Pixels>>,
3332}
3333
3334/// The kind of window to create
3335#[derive(Clone, Debug, PartialEq, Eq)]
3336pub enum WindowKind {
3337    /// A normal application window
3338    Normal,
3339
3340    /// A window that appears above all other windows, usually used for alerts or popups
3341    /// use sparingly!
3342    PopUp,
3343
3344    /// A parent-anchored, platform-native popup window for menus, comboboxes, context menus and
3345    /// tooltips. Unlike [`WindowKind::PopUp`], it is positioned relative to a parent window.
3346    ///
3347    /// The popup's size comes from [`WindowOptions::window_bounds`], whose origin is ignored.
3348    /// See [`popup::PopupOptions`] for the placement options. Platforms without a native
3349    /// implementation reject it with [`popup::PopupNotSupportedError`].
3350    AnchoredPopup(popup::PopupOptions),
3351
3352    /// A floating window that appears on top of its parent window
3353    Floating,
3354
3355    /// A Wayland LayerShell window, used to draw overlays or backgrounds for applications such as
3356    /// docks, notifications or wallpapers.
3357    #[cfg(all(target_os = "linux", feature = "wayland"))]
3358    LayerShell(layer_shell::LayerShellOptions),
3359
3360    /// A window that appears on top of its parent window and blocks interaction with it
3361    /// until the modal window is closed
3362    Dialog,
3363}
3364
3365/// The appearance of the window, as defined by the operating system.
3366///
3367/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
3368/// values.
3369#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3370pub enum WindowAppearance {
3371    /// A light appearance.
3372    ///
3373    /// On macOS, this corresponds to the `aqua` appearance.
3374    #[default]
3375    Light,
3376
3377    /// A light appearance with vibrant colors.
3378    ///
3379    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
3380    VibrantLight,
3381
3382    /// A dark appearance.
3383    ///
3384    /// On macOS, this corresponds to the `darkAqua` appearance.
3385    Dark,
3386
3387    /// A dark appearance with vibrant colors.
3388    ///
3389    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
3390    VibrantDark,
3391}
3392
3393/// The appearance of the background of the window itself, when there is
3394/// no content or the content is transparent.
3395#[derive(Copy, Clone, Debug, Default, PartialEq)]
3396pub enum WindowBackgroundAppearance {
3397    /// Opaque.
3398    ///
3399    /// This lets the window manager know that content behind this
3400    /// window does not need to be drawn.
3401    ///
3402    /// Actual color depends on the system and themes should define a fully
3403    /// opaque background color instead.
3404    #[default]
3405    Opaque,
3406    /// Plain alpha transparency.
3407    Transparent,
3408    /// Transparency, but the contents behind the window are blurred.
3409    ///
3410    /// Not always supported.
3411    Blurred,
3412    /// The Mica backdrop material, supported on Windows 11.
3413    MicaBackdrop,
3414    /// The Mica Alt backdrop material, supported on Windows 11.
3415    MicaAltBackdrop,
3416    /// The Acrylic backdrop material: DWM's own, on Windows 11 22H2 (build
3417    /// 22621) and later. Earlier Windows draws `Blurred` instead.
3418    AcrylicBackdrop,
3419}
3420
3421/// The text rendering mode to use for drawing glyphs.
3422#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3423pub enum TextRenderingMode {
3424    /// Use the platform's default text rendering mode.
3425    #[default]
3426    PlatformDefault,
3427    /// Use subpixel (ClearType-style) text rendering.
3428    Subpixel,
3429    /// Use grayscale text rendering.
3430    Grayscale,
3431}
3432
3433/// The options that can be configured for a file dialog prompt
3434#[derive(Clone, Debug)]
3435pub struct PathPromptOptions {
3436    /// Should the prompt allow files to be selected?
3437    pub files: bool,
3438    /// Should the prompt allow directories to be selected?
3439    pub directories: bool,
3440    /// Should the prompt allow multiple files to be selected?
3441    pub multiple: bool,
3442    /// The prompt to show to a user when selecting a path
3443    pub prompt: Option<SharedString>,
3444}
3445
3446/// What kind of prompt styling to show
3447#[derive(Copy, Clone, Debug, PartialEq)]
3448pub enum PromptLevel {
3449    /// A prompt that is shown when the user should be notified of something
3450    Info,
3451
3452    /// A prompt that is shown when the user needs to be warned of a potential problem
3453    Warning,
3454
3455    /// A prompt that is shown when a critical problem has occurred
3456    Critical,
3457}
3458
3459/// Prompt Button
3460#[derive(Clone, Debug, PartialEq)]
3461pub enum PromptButton {
3462    /// Ok button
3463    Ok(SharedString),
3464    /// Cancel button
3465    Cancel(SharedString),
3466    /// Other button
3467    Other(SharedString),
3468}
3469
3470impl PromptButton {
3471    /// Create a button with label
3472    pub fn new(label: impl Into<SharedString>) -> Self {
3473        PromptButton::Other(label.into())
3474    }
3475
3476    /// Create an Ok button
3477    pub fn ok(label: impl Into<SharedString>) -> Self {
3478        PromptButton::Ok(label.into())
3479    }
3480
3481    /// Create a Cancel button
3482    pub fn cancel(label: impl Into<SharedString>) -> Self {
3483        PromptButton::Cancel(label.into())
3484    }
3485
3486    /// Returns true if this button is a cancel button.
3487    #[allow(dead_code)]
3488    pub fn is_cancel(&self) -> bool {
3489        matches!(self, PromptButton::Cancel(_))
3490    }
3491
3492    /// Returns the label of the button
3493    pub fn label(&self) -> &SharedString {
3494        match self {
3495            PromptButton::Ok(label) => label,
3496            PromptButton::Cancel(label) => label,
3497            PromptButton::Other(label) => label,
3498        }
3499    }
3500}
3501
3502impl From<&str> for PromptButton {
3503    fn from(value: &str) -> Self {
3504        match value.to_lowercase().as_str() {
3505            "ok" => PromptButton::Ok("OK".into()),
3506            "cancel" => PromptButton::Cancel("Cancel".into()),
3507            _ => PromptButton::Other(SharedString::from(value.to_owned())),
3508        }
3509    }
3510}
3511
3512/// The style of the cursor (pointer)
3513#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
3514#[cfg_attr(feature = "schemars", derive(JsonSchema))]
3515pub enum CursorStyle {
3516    /// The default cursor
3517    #[default]
3518    Arrow,
3519
3520    /// A text input cursor
3521    /// corresponds to the CSS cursor value `text`
3522    IBeam,
3523
3524    /// A crosshair cursor
3525    /// corresponds to the CSS cursor value `crosshair`
3526    Crosshair,
3527
3528    /// A closed hand cursor
3529    /// corresponds to the CSS cursor value `grabbing`
3530    ClosedHand,
3531
3532    /// An open hand cursor
3533    /// corresponds to the CSS cursor value `grab`
3534    OpenHand,
3535
3536    /// A pointing hand cursor
3537    /// corresponds to the CSS cursor value `pointer`
3538    PointingHand,
3539
3540    /// A resize left cursor
3541    /// corresponds to the CSS cursor value `w-resize`
3542    ResizeLeft,
3543
3544    /// A resize right cursor
3545    /// corresponds to the CSS cursor value `e-resize`
3546    ResizeRight,
3547
3548    /// A resize cursor to the left and right
3549    /// corresponds to the CSS cursor value `ew-resize`
3550    ResizeLeftRight,
3551
3552    /// A resize up cursor
3553    /// corresponds to the CSS cursor value `n-resize`
3554    ResizeUp,
3555
3556    /// A resize down cursor
3557    /// corresponds to the CSS cursor value `s-resize`
3558    ResizeDown,
3559
3560    /// A resize cursor directing up and down
3561    /// corresponds to the CSS cursor value `ns-resize`
3562    ResizeUpDown,
3563
3564    /// A resize cursor directing up-left and down-right
3565    /// corresponds to the CSS cursor value `nesw-resize`
3566    ResizeUpLeftDownRight,
3567
3568    /// A resize cursor directing up-right and down-left
3569    /// corresponds to the CSS cursor value `nwse-resize`
3570    ResizeUpRightDownLeft,
3571
3572    /// A cursor indicating that the item/column can be resized horizontally.
3573    /// corresponds to the CSS cursor value `col-resize`
3574    ResizeColumn,
3575
3576    /// A cursor indicating that the item/row can be resized vertically.
3577    /// corresponds to the CSS cursor value `row-resize`
3578    ResizeRow,
3579
3580    /// A text input cursor for vertical layout
3581    /// corresponds to the CSS cursor value `vertical-text`
3582    IBeamCursorForVerticalLayout,
3583
3584    /// A cursor indicating that the operation is not allowed
3585    /// corresponds to the CSS cursor value `not-allowed`
3586    OperationNotAllowed,
3587
3588    /// A cursor indicating that the operation will result in a link
3589    /// corresponds to the CSS cursor value `alias`
3590    DragLink,
3591
3592    /// A cursor indicating that the operation will result in a copy
3593    /// corresponds to the CSS cursor value `copy`
3594    DragCopy,
3595
3596    /// A cursor indicating that the operation will result in a context menu
3597    /// corresponds to the CSS cursor value `context-menu`
3598    ContextualMenu,
3599
3600    /// corresponds to the CSS cursor value `help`
3601    Help,
3602
3603    /// Busy, but the user can still interact
3604    /// corresponds to the CSS cursor value `progress`
3605    Progress,
3606
3607    /// corresponds to the CSS cursor value `wait`
3608    Wait,
3609
3610    /// corresponds to the CSS cursor value `move`
3611    Move,
3612
3613    /// corresponds to the CSS cursor value `all-scroll`
3614    AllScroll,
3615
3616    /// corresponds to the CSS cursor value `cell`
3617    Cell,
3618
3619    /// corresponds to the CSS cursor value `zoom-in`
3620    ZoomIn,
3621
3622    /// corresponds to the CSS cursor value `zoom-out`
3623    ZoomOut,
3624
3625    /// corresponds to the CSS cursor value `no-drop`
3626    NoDrop,
3627
3628    /// No cursor is shown
3629    /// corresponds to the CSS cursor value `none`
3630    Hidden,
3631}
3632
3633impl CursorStyle {
3634    /// Every style.
3635    pub const ALL: [Self; 31] = [
3636        Self::Arrow,
3637        Self::IBeam,
3638        Self::Crosshair,
3639        Self::ClosedHand,
3640        Self::OpenHand,
3641        Self::PointingHand,
3642        Self::ResizeLeft,
3643        Self::ResizeRight,
3644        Self::ResizeLeftRight,
3645        Self::ResizeUp,
3646        Self::ResizeDown,
3647        Self::ResizeUpDown,
3648        Self::ResizeUpLeftDownRight,
3649        Self::ResizeUpRightDownLeft,
3650        Self::ResizeColumn,
3651        Self::ResizeRow,
3652        Self::IBeamCursorForVerticalLayout,
3653        Self::OperationNotAllowed,
3654        Self::DragLink,
3655        Self::DragCopy,
3656        Self::ContextualMenu,
3657        Self::Help,
3658        Self::Progress,
3659        Self::Wait,
3660        Self::Move,
3661        Self::AllScroll,
3662        Self::Cell,
3663        Self::ZoomIn,
3664        Self::ZoomOut,
3665        Self::NoDrop,
3666        Self::Hidden,
3667    ];
3668
3669    /// Iterates over [`Self::ALL`], in place of strum's `EnumIter`, which gpui does not depend on.
3670    pub fn iter() -> impl Iterator<Item = Self> {
3671        Self::ALL.into_iter()
3672    }
3673}
3674
3675/// A clipboard item that should be copied to the clipboard
3676#[derive(Clone, Debug, Eq, PartialEq)]
3677pub struct ClipboardItem {
3678    /// The entries in this clipboard item.
3679    pub entries: Vec<ClipboardEntry>,
3680}
3681
3682/// An error produced by [`Platform::read_from_clipboard_async`].
3683///
3684/// Callers surface these failures to users, so the variants distinguish
3685/// conditions that call for different user-facing guidance.
3686#[derive(Clone, Debug, PartialEq, Eq)]
3687pub enum ClipboardReadError {
3688    /// The platform clipboard is not available in this context, e.g. the
3689    /// browser does not expose the async clipboard API or the page is not a
3690    /// secure context.
3691    Unavailable,
3692    /// The platform refused access, e.g. the user declined the browser's
3693    /// clipboard permission prompt or paste confirmation.
3694    Denied(String),
3695    /// The clipboard contents could not be converted into a
3696    /// [`ClipboardItem`].
3697    UnsupportedContent,
3698}
3699
3700impl std::fmt::Display for ClipboardReadError {
3701    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3702        match self {
3703            Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3704            Self::Denied(message) => {
3705                write!(formatter, "clipboard access was denied: {message}")
3706            }
3707            Self::UnsupportedContent => {
3708                formatter.write_str("the clipboard contents are unsupported")
3709            }
3710        }
3711    }
3712}
3713
3714impl std::error::Error for ClipboardReadError {}
3715
3716/// Either a ClipboardString or a ClipboardImage
3717#[derive(Clone, Debug, Eq, PartialEq)]
3718pub enum ClipboardEntry {
3719    /// A string entry
3720    String(ClipboardString),
3721    /// An image entry
3722    Image(Image),
3723    /// A file entry
3724    ExternalPaths(crate::ExternalPaths),
3725}
3726
3727impl ClipboardItem {
3728    /// Create a new ClipboardItem::String with no associated metadata
3729    pub fn new_string(text: String) -> Self {
3730        Self {
3731            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3732        }
3733    }
3734
3735    /// Create a new ClipboardItem::String with the given text and associated metadata
3736    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3737        Self {
3738            entries: vec![ClipboardEntry::String(ClipboardString {
3739                text,
3740                metadata: Some(metadata),
3741            })],
3742        }
3743    }
3744
3745    /// Create a new ClipboardItem::String with the given text and associated metadata
3746    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3747        Self {
3748            entries: vec![ClipboardEntry::String(
3749                ClipboardString::new(text).with_json_metadata(metadata),
3750            )],
3751        }
3752    }
3753
3754    /// Create a new ClipboardItem::Image with the given image with no associated metadata
3755    pub fn new_image(image: &Image) -> Self {
3756        Self {
3757            entries: vec![ClipboardEntry::Image(image.clone())],
3758        }
3759    }
3760
3761    /// Concatenates together all the ClipboardString entries in the item.
3762    /// Returns None if there were no ClipboardString entries.
3763    pub fn text(&self) -> Option<String> {
3764        let mut answer = String::new();
3765
3766        for entry in self.entries.iter() {
3767            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3768                answer.push_str(text);
3769            }
3770        }
3771
3772        if answer.is_empty() {
3773            for entry in self.entries.iter() {
3774                if let ClipboardEntry::ExternalPaths(paths) = entry {
3775                    for path in &paths.0 {
3776                        use std::fmt::Write as _;
3777                        _ = write!(answer, "{}", path.display());
3778                    }
3779                }
3780            }
3781        }
3782
3783        if !answer.is_empty() {
3784            Some(answer)
3785        } else {
3786            None
3787        }
3788    }
3789
3790    /// If this item is one ClipboardEntry::String, returns its metadata.
3791    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3792    pub fn metadata(&self) -> Option<&String> {
3793        match self.entries().first() {
3794            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3795                clipboard_string.metadata.as_ref()
3796            }
3797            _ => None,
3798        }
3799    }
3800
3801    /// Get the item's entries
3802    pub fn entries(&self) -> &[ClipboardEntry] {
3803        &self.entries
3804    }
3805
3806    /// Get owned versions of the item's entries
3807    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3808        self.entries.into_iter()
3809    }
3810}
3811
3812impl From<ClipboardString> for ClipboardEntry {
3813    fn from(value: ClipboardString) -> Self {
3814        Self::String(value)
3815    }
3816}
3817
3818impl From<String> for ClipboardEntry {
3819    fn from(value: String) -> Self {
3820        Self::from(ClipboardString::from(value))
3821    }
3822}
3823
3824impl From<Image> for ClipboardEntry {
3825    fn from(value: Image) -> Self {
3826        Self::Image(value)
3827    }
3828}
3829
3830impl From<ClipboardEntry> for ClipboardItem {
3831    fn from(value: ClipboardEntry) -> Self {
3832        Self {
3833            entries: vec![value],
3834        }
3835    }
3836}
3837
3838impl From<String> for ClipboardItem {
3839    fn from(value: String) -> Self {
3840        Self::from(ClipboardEntry::from(value))
3841    }
3842}
3843
3844impl From<Image> for ClipboardItem {
3845    fn from(value: Image) -> Self {
3846        Self::from(ClipboardEntry::from(value))
3847    }
3848}
3849
3850/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
3851#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3852pub enum ImageFormat {
3853    // Sorted from most to least likely to be pasted into an editor,
3854    // which matters when we iterate through them trying to see if
3855    // clipboard content matches them.
3856    /// .png
3857    Png,
3858    /// .jpeg or .jpg
3859    Jpeg,
3860    /// .webp
3861    Webp,
3862    /// .gif
3863    Gif,
3864    /// .svg
3865    Svg,
3866    /// .bmp
3867    Bmp,
3868    /// .tif or .tiff
3869    Tiff,
3870    /// .ico
3871    Ico,
3872    /// Netpbm image formats (.pbm, .ppm, .pgm).
3873    Pnm,
3874}
3875
3876impl ImageFormat {
3877    /// Every format, in the order clipboard readers should try them.
3878    pub const ALL: [Self; 9] = [
3879        Self::Png,
3880        Self::Jpeg,
3881        Self::Webp,
3882        Self::Gif,
3883        Self::Svg,
3884        Self::Bmp,
3885        Self::Tiff,
3886        Self::Ico,
3887        Self::Pnm,
3888    ];
3889
3890    /// Iterates over [`Self::ALL`].
3891    pub fn iter() -> impl Iterator<Item = Self> {
3892        Self::ALL.into_iter()
3893    }
3894
3895    /// Returns the mime type for the ImageFormat
3896    pub const fn mime_type(self) -> &'static str {
3897        match self {
3898            ImageFormat::Png => "image/png",
3899            ImageFormat::Jpeg => "image/jpeg",
3900            ImageFormat::Webp => "image/webp",
3901            ImageFormat::Gif => "image/gif",
3902            ImageFormat::Svg => "image/svg+xml",
3903            ImageFormat::Bmp => "image/bmp",
3904            ImageFormat::Tiff => "image/tiff",
3905            ImageFormat::Ico => "image/ico",
3906            ImageFormat::Pnm => "image/x-portable-anymap",
3907        }
3908    }
3909
3910    /// Returns the file extension for this image format (without leading dot).
3911    pub const fn extension(self) -> &'static str {
3912        match self {
3913            ImageFormat::Png => "png",
3914            ImageFormat::Jpeg => "jpg",
3915            ImageFormat::Webp => "webp",
3916            ImageFormat::Gif => "gif",
3917            ImageFormat::Svg => "svg",
3918            ImageFormat::Bmp => "bmp",
3919            ImageFormat::Tiff => "tiff",
3920            ImageFormat::Ico => "ico",
3921            ImageFormat::Pnm => "pnm",
3922        }
3923    }
3924
3925    /// Returns the ImageFormat for the given mime type, including known aliases.
3926    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3927        Self::iter()
3928            .find(|format| format.mime_type() == mime_type)
3929            .or_else(|| Self::from_mime_type_alias(mime_type))
3930    }
3931
3932    /// Non-canonical mime types that some producers use in the wild.
3933    /// Unlike `mime_type()` which returns the single canonical form,
3934    /// these are legacy or shortened variants we still need to recognize.
3935    fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3936        match mime_type {
3937            "image/jpg" => Some(Self::Jpeg),
3938            "image/tif" => Some(Self::Tiff),
3939            _ => None,
3940        }
3941    }
3942}
3943
3944/// An image, with a format and certain bytes
3945#[derive(Clone, Debug, PartialEq, Eq)]
3946pub struct Image {
3947    /// The image format the bytes represent (e.g. PNG)
3948    pub format: ImageFormat,
3949    /// The raw image bytes
3950    pub bytes: Vec<u8>,
3951    /// The unique ID for the image
3952    pub id: u64,
3953}
3954
3955pub(crate) fn decode_static_image(
3956    bytes: &[u8],
3957    format: image::ImageFormat,
3958) -> Result<SmallVec<[Frame; 1]>> {
3959    let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3960        .into_decoder()
3961        .context("creating image decoder")?;
3962    decode_static_image_from_decoder(decoder)
3963}
3964
3965pub(crate) fn decode_static_image_from_decoder(
3966    mut decoder: impl image::ImageDecoder,
3967) -> Result<SmallVec<[Frame; 1]>> {
3968    let orientation = decoder
3969        .orientation()
3970        .context("reading decoder's orientation")?;
3971    let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3972    image.apply_orientation(orientation);
3973
3974    let mut data = image.into_rgba8();
3975    for pixel in data.chunks_exact_mut(4) {
3976        pixel.swap(0, 2);
3977    }
3978
3979    Ok(SmallVec::from_elem(Frame::new(data), 1))
3980}
3981
3982fn decode_animated_frames<'a>(
3983    decoder: impl image::AnimationDecoder<'a>,
3984    format_name: &str,
3985) -> Result<SmallVec<[Frame; 1]>> {
3986    let mut frames = SmallVec::new();
3987
3988    for frame in decoder.into_frames() {
3989        match frame {
3990            Ok(mut frame) => {
3991                // Convert from RGBA to BGRA.
3992                for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3993                    pixel.swap(0, 2);
3994                }
3995                frames.push(frame);
3996            }
3997            Err(err) => {
3998                log::debug!("Skipping {format_name} frame due to decode error: {err}");
3999            }
4000        }
4001    }
4002
4003    if frames.is_empty() {
4004        anyhow::bail!("{format_name} could not be decoded: all frames failed");
4005    }
4006
4007    Ok(frames)
4008}
4009
4010pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
4011    let decoder = GifDecoder::new(Cursor::new(bytes))?;
4012    decode_animated_frames(decoder, "GIF")
4013}
4014
4015pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
4016    let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
4017
4018    if decoder.has_animation() {
4019        let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
4020        decode_animated_frames(decoder, "WebP")
4021    } else {
4022        decode_static_image_from_decoder(decoder)
4023    }
4024}
4025
4026impl Hash for Image {
4027    fn hash<H: Hasher>(&self, state: &mut H) {
4028        state.write_u64(self.id);
4029    }
4030}
4031
4032impl Image {
4033    /// An empty image containing no data
4034    pub fn empty() -> Self {
4035        Self::from_bytes(ImageFormat::Png, Vec::new())
4036    }
4037
4038    /// Create an image from a format and bytes
4039    pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
4040        Self {
4041            id: hash(&bytes),
4042            format,
4043            bytes,
4044        }
4045    }
4046
4047    /// Get this image's ID
4048    pub fn id(&self) -> u64 {
4049        self.id
4050    }
4051
4052    /// Use the GPUI `use_asset` API to make this image renderable
4053    pub fn use_render_image(
4054        self: Arc<Self>,
4055        window: &mut Window,
4056        cx: &mut App,
4057    ) -> Option<Arc<RenderImage>> {
4058        ImageSource::Image(self)
4059            .use_data(None, window, cx)
4060            .and_then(|result| result.ok())
4061    }
4062
4063    /// Use the GPUI `get_asset` API to make this image renderable
4064    pub fn get_render_image(
4065        self: Arc<Self>,
4066        window: &mut Window,
4067        cx: &mut App,
4068    ) -> Option<Arc<RenderImage>> {
4069        ImageSource::Image(self)
4070            .get_data(None, window, cx)
4071            .and_then(|result| result.ok())
4072    }
4073
4074    /// Use the GPUI `remove_asset` API to drop this image, if possible.
4075    pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
4076        ImageSource::Image(self).remove_asset(cx);
4077    }
4078
4079    /// Check whether this image is present in GPUI's asset cache (loading or
4080    /// loaded), without fetching it.
4081    #[cfg(any(test, feature = "test-support"))]
4082    pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
4083        ImageSource::Image(self.clone()).is_asset_cached(cx)
4084    }
4085
4086    /// Convert the clipboard image to an `ImageData` object.
4087    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
4088        let frames = match self.format {
4089            ImageFormat::Gif => decode_gif_image(&self.bytes)?,
4090            ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
4091            ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
4092            ImageFormat::Webp => decode_webp_image(&self.bytes)?,
4093            ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
4094            ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
4095            ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
4096            ImageFormat::Svg => {
4097                return svg_renderer
4098                    .render_single_frame(&self.bytes, 1.0)
4099                    .map_err(Into::into);
4100            }
4101            ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
4102        };
4103
4104        Ok(Arc::new(RenderImage::new(frames)))
4105    }
4106
4107    /// Get the format of the clipboard image
4108    pub fn format(&self) -> ImageFormat {
4109        self.format
4110    }
4111
4112    /// Get the raw bytes of the clipboard image
4113    pub fn bytes(&self) -> &[u8] {
4114        self.bytes.as_slice()
4115    }
4116}
4117
4118/// A clipboard item that should be copied to the clipboard
4119#[derive(Clone, Debug, Eq, PartialEq)]
4120pub struct ClipboardString {
4121    /// The text content.
4122    pub text: String,
4123    /// Optional metadata associated with this clipboard string.
4124    pub metadata: Option<String>,
4125}
4126
4127impl ClipboardString {
4128    /// Create a new clipboard string with the given text
4129    pub fn new(text: String) -> Self {
4130        Self {
4131            text,
4132            metadata: None,
4133        }
4134    }
4135
4136    /// Return a new clipboard item with the metadata replaced by the given metadata,
4137    /// after serializing it as JSON.
4138    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
4139        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
4140        self
4141    }
4142
4143    /// Get the text of the clipboard string
4144    pub fn text(&self) -> &String {
4145        &self.text
4146    }
4147
4148    /// Get the owned text of the clipboard string
4149    pub fn into_text(self) -> String {
4150        self.text
4151    }
4152
4153    /// Get the metadata of the clipboard string, formatted as JSON
4154    pub fn metadata_json<T>(&self) -> Option<T>
4155    where
4156        T: for<'a> Deserialize<'a>,
4157    {
4158        self.metadata
4159            .as_ref()
4160            .and_then(|m| serde_json::from_str(m).ok())
4161    }
4162
4163    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
4164    /// Compute a hash of the given text for clipboard change detection.
4165    pub fn text_hash(text: &str) -> u64 {
4166        let mut hasher = SeaHasher::new();
4167        text.hash(&mut hasher);
4168        hasher.finish()
4169    }
4170}
4171
4172impl From<String> for ClipboardString {
4173    fn from(value: String) -> Self {
4174        Self {
4175            text: value,
4176            metadata: None,
4177        }
4178    }
4179}
4180
4181#[cfg(test)]
4182mod image_tests {
4183    use super::*;
4184    use std::sync::Arc;
4185
4186    #[test]
4187    fn test_image_to_image_data_applies_exif_orientation() {
4188        let image = Image::from_bytes(
4189            ImageFormat::Jpeg,
4190            include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
4191        );
4192
4193        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4194
4195        assert_eq!(render_image.size(0), size(16.into(), 32.into()));
4196
4197        let bytes = render_image.as_bytes(0).unwrap();
4198        assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
4199        assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
4200    }
4201
4202    #[test]
4203    fn test_svg_image_to_image_data_converts_to_bgra() {
4204        let image = Image::from_bytes(
4205            ImageFormat::Svg,
4206            br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
4207<rect width="1" height="1" fill="#38BDF8"/>
4208</svg>"##
4209                .to_vec(),
4210        );
4211
4212        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4213        let bytes = render_image.as_bytes(0).unwrap();
4214
4215        for pixel in bytes.chunks_exact(4) {
4216            assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
4217        }
4218    }
4219
4220    #[test]
4221    fn test_animated_webp_image_to_image_data_decodes_frames() {
4222        // 1x1 2-frame animated WebP (frame 0: red, frame 1: blue, 100ms delay each).
4223        const ANIMATED_WEBP: &[u8] = &[
4224            82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
4225            0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
4226            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,
4227            0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
4228            176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
4229            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,
4230            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,
4231            0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
4232            31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
4233        ];
4234
4235        let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
4236        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4237
4238        assert_eq!(render_image.frame_count(), 2);
4239        assert_eq!(render_image.size(0), size(1.into(), 1.into()));
4240        assert_eq!(
4241            Duration::from(render_image.delay(0)),
4242            Duration::from_millis(100)
4243        );
4244        assert_eq!(
4245            Duration::from(render_image.delay(1)),
4246            Duration::from_millis(100)
4247        );
4248    }
4249}
4250
4251#[cfg(test)]
4252mod atlas_tests {
4253    use super::*;
4254
4255    const TILE_SIZE: Size<DevicePixels> = Size {
4256        width: DevicePixels(1),
4257        height: DevicePixels(1),
4258    };
4259
4260    #[derive(Default)]
4261    struct RecordingAtlasBackend {
4262        insert_calls: u32,
4263        fail_next_insert: bool,
4264        removed_tiles: Vec<AtlasTile>,
4265    }
4266
4267    impl AtlasBackend for RecordingAtlasBackend {
4268        fn insert(
4269            &mut self,
4270            kind: AtlasTextureKind,
4271            size: Size<DevicePixels>,
4272            _bytes: &[u8],
4273        ) -> Result<AtlasTile> {
4274            self.insert_calls += 1;
4275            if std::mem::take(&mut self.fail_next_insert) {
4276                anyhow::bail!("backend failed");
4277            }
4278            Ok(AtlasTile {
4279                texture_id: AtlasTextureId { index: 0, kind },
4280                tile_id: TileId(self.insert_calls),
4281                padding: 0,
4282                bounds: Bounds {
4283                    origin: Point::default(),
4284                    size,
4285                },
4286            })
4287        }
4288
4289        fn remove(&mut self, tile: AtlasTile) {
4290            self.removed_tiles.push(tile);
4291        }
4292    }
4293
4294    fn image_key(image_id: usize) -> AtlasKey {
4295        AtlasKey::Image(RenderImageParams {
4296            image_id: crate::ImageId(image_id),
4297            frame_index: 0,
4298        })
4299    }
4300
4301    fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
4302        Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
4303    }
4304
4305    #[test]
4306    fn only_successful_inserts_are_cached() -> Result<()> {
4307        let mut state = AtlasState::new(RecordingAtlasBackend::default());
4308        let key = image_key(1);
4309
4310        assert_eq!(
4311            state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
4312            None
4313        );
4314        state
4315            .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
4316            .expect_err("builder error should propagate");
4317        assert!(!state.contains(&key));
4318        assert_eq!(state.backend.insert_calls, 0);
4319
4320        state.backend.fail_next_insert = true;
4321        state
4322            .get_or_insert_with(key.clone(), &mut build_tile)
4323            .expect_err("backend error should propagate");
4324        assert!(!state.contains(&key));
4325        assert_eq!(state.backend.insert_calls, 1);
4326
4327        let tile = state
4328            .get_or_insert_with(key.clone(), &mut build_tile)?
4329            .context("builder should produce a tile")?;
4330        assert_eq!(tile.texture_id.kind, key.texture_kind());
4331        assert_eq!(
4332            state.get_or_insert_with(key.clone(), &mut || {
4333                anyhow::bail!("cache hit must not call the builder")
4334            })?,
4335            Some(tile)
4336        );
4337        assert!(state.contains(&key));
4338        assert_eq!(state.backend.insert_calls, 2);
4339        Ok(())
4340    }
4341
4342    #[test]
4343    fn remove_and_clear_invalidate_keys() -> Result<()> {
4344        let mut state = AtlasState::new(RecordingAtlasBackend::default());
4345        let key = image_key(1);
4346        let other_key = image_key(2);
4347        let tile = state
4348            .get_or_insert_with(key.clone(), &mut build_tile)?
4349            .context("builder should produce a tile")?;
4350        state
4351            .get_or_insert_with(other_key.clone(), &mut build_tile)?
4352            .context("builder should produce another tile")?;
4353
4354        state.remove(&key);
4355        state.remove(&key);
4356        assert!(!state.contains(&key));
4357        assert!(state.contains(&other_key));
4358        assert_eq!(state.backend.removed_tiles, vec![tile]);
4359
4360        let mut reset_calls = 0;
4361        state.clear(|_| reset_calls += 1);
4362        assert_eq!(reset_calls, 1);
4363        assert!(!state.contains(&other_key));
4364        assert_eq!(state.backend.removed_tiles, vec![tile]);
4365        Ok(())
4366    }
4367}
4368
4369#[cfg(test)]
4370mod frame_signal_tests {
4371    use super::*;
4372
4373    #[cfg(feature = "profiler")]
4374    #[test]
4375    fn coalesced_signals_retain_the_earliest_until_drained() {
4376        for (first_source, later_source) in [
4377            (
4378                FrameRequestSource::NativeCallback,
4379                FrameRequestSource::LocalSchedule,
4380            ),
4381            (
4382                FrameRequestSource::LocalSchedule,
4383                FrameRequestSource::NativeCallback,
4384            ),
4385        ] {
4386            let signal = PlatformFrameSignal::new();
4387            let first =
4388                PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
4389            assert_eq!(signal.take(), None);
4390            signal.record(first + Duration::from_millis(16), later_source);
4391            signal.record(first, first_source);
4392            signal.record(first + Duration::from_millis(32), later_source);
4393            assert_eq!(signal.take(), Some((first, first_source)));
4394            assert_eq!(signal.take(), None);
4395            let next = first + Duration::from_millis(48);
4396            signal.record(next, later_source);
4397            assert_eq!(signal.take(), Some((next, later_source)));
4398        }
4399    }
4400
4401    #[cfg(not(feature = "profiler"))]
4402    #[test]
4403    fn disabled_profiling_does_not_capture_or_store_timestamps() {
4404        let captured = PlatformFrameSignal::capture(|| {
4405            panic!("profiler-disabled builds must not evaluate the capture closure");
4406        });
4407        assert_eq!(captured, None);
4408        let signal = PlatformFrameSignal::new();
4409        signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
4410        assert_eq!(signal.take(), None);
4411    }
4412}
4413
4414#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
4415mod tests {
4416    use super::*;
4417    use std::collections::HashSet;
4418
4419    #[test]
4420    fn test_refresh_interval_from_hz() {
4421        assert_eq!(
4422            refresh_interval_from_hz(50.0),
4423            Some(Duration::from_millis(20))
4424        );
4425        assert_eq!(
4426            refresh_interval_from_hz(120.0),
4427            Some(Duration::from_secs(1) / 120)
4428        );
4429        for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
4430            assert_eq!(refresh_interval_from_hz(unknown), None);
4431        }
4432    }
4433
4434    #[test]
4435    fn test_window_button_layout_parse_standard() {
4436        let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
4437        assert_eq!(
4438            layout.left,
4439            [
4440                Some(WindowButton::Close),
4441                Some(WindowButton::Minimize),
4442                None
4443            ]
4444        );
4445        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4446    }
4447
4448    #[test]
4449    fn test_window_button_layout_parse_right_only() {
4450        let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
4451        assert_eq!(layout.left, [None, None, None]);
4452        assert_eq!(
4453            layout.right,
4454            [
4455                Some(WindowButton::Minimize),
4456                Some(WindowButton::Maximize),
4457                Some(WindowButton::Close)
4458            ]
4459        );
4460    }
4461
4462    #[test]
4463    fn test_window_button_layout_parse_left_only() {
4464        let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
4465        assert_eq!(
4466            layout.left,
4467            [
4468                Some(WindowButton::Close),
4469                Some(WindowButton::Minimize),
4470                Some(WindowButton::Maximize)
4471            ]
4472        );
4473        assert_eq!(layout.right, [None, None, None]);
4474    }
4475
4476    #[test]
4477    fn test_window_button_layout_parse_with_whitespace() {
4478        let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
4479        assert_eq!(
4480            layout.left,
4481            [
4482                Some(WindowButton::Close),
4483                Some(WindowButton::Minimize),
4484                None
4485            ]
4486        );
4487        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4488    }
4489
4490    #[test]
4491    fn test_window_button_layout_parse_empty() {
4492        let layout = WindowButtonLayout::parse("").unwrap();
4493        assert_eq!(layout.left, [None, None, None]);
4494        assert_eq!(layout.right, [None, None, None]);
4495    }
4496
4497    #[test]
4498    fn test_window_button_layout_parse_intentionally_empty() {
4499        let layout = WindowButtonLayout::parse(":").unwrap();
4500        assert_eq!(layout.left, [None, None, None]);
4501        assert_eq!(layout.right, [None, None, None]);
4502    }
4503
4504    #[test]
4505    fn test_window_button_layout_parse_invalid_buttons() {
4506        let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
4507        assert_eq!(
4508            layout.left,
4509            [
4510                Some(WindowButton::Close),
4511                Some(WindowButton::Minimize),
4512                None
4513            ]
4514        );
4515        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4516    }
4517
4518    #[test]
4519    fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
4520        let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
4521        assert_eq!(
4522            layout.right,
4523            [
4524                Some(WindowButton::Close),
4525                Some(WindowButton::Minimize),
4526                None
4527            ]
4528        );
4529        assert_eq!(layout.format(), ":close,minimize");
4530    }
4531
4532    #[test]
4533    fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
4534        let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
4535        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4536        assert_eq!(
4537            layout.right,
4538            [
4539                Some(WindowButton::Maximize),
4540                Some(WindowButton::Minimize),
4541                None
4542            ]
4543        );
4544
4545        let button_ids: Vec<_> = layout
4546            .left
4547            .iter()
4548            .chain(layout.right.iter())
4549            .flatten()
4550            .map(WindowButton::id)
4551            .collect();
4552        let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4553        assert_eq!(unique_button_ids.len(), button_ids.len());
4554        assert_eq!(layout.format(), "close:maximize,minimize");
4555    }
4556
4557    #[test]
4558    fn test_window_button_layout_parse_gnome_style() {
4559        let layout = WindowButtonLayout::parse("close").unwrap();
4560        assert_eq!(layout.left, [None, None, None]);
4561        assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4562    }
4563
4564    #[test]
4565    fn test_window_button_layout_parse_elementary_style() {
4566        let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4567        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4568        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4569    }
4570
4571    #[test]
4572    fn test_window_button_layout_round_trip() {
4573        let cases = [
4574            "close:minimize,maximize",
4575            "minimize,maximize,close:",
4576            ":close",
4577            "close:",
4578            "close:maximize",
4579            ":",
4580        ];
4581
4582        for case in cases {
4583            let layout = WindowButtonLayout::parse(case).unwrap();
4584            assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4585        }
4586    }
4587
4588    #[test]
4589    fn test_window_button_layout_linux_default() {
4590        let layout = WindowButtonLayout::linux_default();
4591        assert_eq!(layout.left, [None, None, None]);
4592        assert_eq!(
4593            layout.right,
4594            [
4595                Some(WindowButton::Minimize),
4596                Some(WindowButton::Maximize),
4597                Some(WindowButton::Close)
4598            ]
4599        );
4600
4601        let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4602        assert_eq!(round_tripped, layout);
4603    }
4604
4605    #[test]
4606    fn test_window_button_layout_parse_all_invalid() {
4607        assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4608    }
4609}