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