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