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