Skip to main content

gpui/
platform.rs

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