Skip to main content

gpui/
platform.rs

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