Skip to main content

gpui/
platform.rs

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