Skip to main content

gpui/
platform.rs

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