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}
1148
1149/// Regions of a window that are obscured or reserved by the system.
1150///
1151/// Mobile applications often share space in their window with system-specific
1152/// geometry, from keyboards to camera notches. In GPUI, all this is abstracted
1153/// into a single "inset" which should be overlaid on the window's bounds.
1154/// It is up to the application develop to determine how to handle these cases.
1155#[derive(Debug, Clone, Default, PartialEq)]
1156pub struct WindowInsets {
1157    /// Regions covered by system UI or hardware: status bar, display
1158    /// cutouts/notch, home indicator, navigation bars.
1159    /// (iOS: `safeAreaInsets`. Android: `WindowInsets` of types
1160    /// `systemBars() | displayCutout()`.)
1161    pub safe_area: Edges<Pixels>,
1162    /// The region covered by the keyboard, when present.
1163    /// (iOS: derived from `keyboardWillShow`/frame-change notifications.
1164    /// Android: `WindowInsets.Type.ime()`.)
1165    pub ime: Edges<Pixels>,
1166}
1167
1168impl WindowInsets {
1169    /// The combined inset content should avoid.
1170    pub fn effective(&self) -> Edges<Pixels> {
1171        Edges {
1172            top: self.safe_area.top.max(self.ime.top),
1173            right: self.safe_area.right.max(self.ime.right),
1174            bottom: self.safe_area.bottom.max(self.ime.bottom),
1175            left: self.safe_area.left.max(self.ime.left),
1176        }
1177    }
1178}
1179
1180/// A change in the state of the focused text input.
1181#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1182pub enum TextInputStateChange {
1183    /// The window changed from having no active text input to having one.
1184    FocusGained,
1185    /// The window no longer has an active text input.
1186    FocusLost,
1187    /// The selection or caret moved
1188    SelectionChanged,
1189    /// The document content changed outside of platform-initiated edits.
1190    ContentChanged,
1191}
1192
1193#[expect(missing_docs)]
1194pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1195    fn bounds(&self) -> Bounds<Pixels>;
1196    fn is_maximized(&self) -> bool;
1197    fn window_bounds(&self) -> WindowBounds;
1198    fn content_size(&self) -> Size<Pixels>;
1199    /// Returns the visible viewport in logical pixels relative to the content origin.
1200    ///
1201    /// This may be smaller or offset when a keyboard or zoom obscures content;
1202    /// it must not change the full layout size returned by `content_size`.
1203    /// Implementations should return a frame snapshot, not query platform layout here.
1204    fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1205        Bounds::new(Point::default(), self.content_size())
1206    }
1207    /// Registers a callback when visible geometry may have changed.
1208    ///
1209    /// This requests a frame; backends can sample the new viewport and safe-area
1210    /// geometry in `prepare_frame` rather than updating it inside the callback.
1211    fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1212    /// Samples platform geometry before a draw, returning whether view caches must be invalidated.
1213    ///
1214    /// Geometry getters must remain consistent throughout the ensuing draw.
1215    /// Do not invoke callbacks here: GPUI is already updating this window.
1216    fn prepare_frame(&self) -> bool {
1217        false
1218    }
1219    fn resize(&mut self, size: Size<Pixels>);
1220    fn scale_factor(&self) -> f32;
1221    fn appearance(&self) -> WindowAppearance;
1222    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1223    fn mouse_position(&self) -> Point<Pixels>;
1224    fn modifiers(&self) -> Modifiers;
1225    fn capslock(&self) -> Capslock;
1226    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1227    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1228    /// Apply the focused text region's [`TextInputConfiguration`] to the
1229    /// platform's text input session (e.g. attributes of the hidden editable
1230    /// element on web). Called only when the configuration changes, because
1231    /// reconfiguring a live input session can restart the IME connection.
1232    fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1233    fn prompt(
1234        &self,
1235        level: PromptLevel,
1236        msg: &str,
1237        detail: Option<&str>,
1238        answers: &[PromptButton],
1239    ) -> Option<oneshot::Receiver<usize>>;
1240    fn activate(&self);
1241    /// Requests that the operating system draw attention to this window.
1242    fn request_attention(&self) {}
1243    fn is_active(&self) -> bool;
1244    /// The current [`WindowVisibility`]. Read once when the window is created;
1245    /// afterwards changes arrive through [`Self::on_visibility_change`].
1246    fn visibility(&self) -> WindowVisibility;
1247    fn is_hovered(&self) -> bool;
1248    fn background_appearance(&self) -> WindowBackgroundAppearance;
1249    fn set_title(&mut self, title: &str);
1250    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1251    fn minimize(&self);
1252    fn zoom(&self);
1253    fn toggle_fullscreen(&self);
1254    fn is_fullscreen(&self) -> bool;
1255    fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1256        None
1257    }
1258    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1259    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1260    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1261    /// Registers the callback invoked when [`Self::visibility`] changes. Only
1262    /// transitions are reported; the callback runs on the main thread outside
1263    /// of any window update.
1264    fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1265    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1266    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1267    fn on_moved(&self, callback: Box<dyn FnMut()>);
1268    /// Registers the callback invoked when the window moves to another
1269    /// display. Calls may be spurious. The callback runs on the main thread
1270    /// outside of any window update.
1271    fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1272    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1273    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1274    fn on_close(&self, callback: Box<dyn FnOnce()>);
1275    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1276    fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1277    fn draw(&self, scene: &Scene);
1278    fn draw_composed(&self, scene: crate::fast::composition::ComposedScene<'_>) {
1279        crate::fast::composition::draw_uncomposed(self, scene)
1280    }
1281    fn enable_window_composition(&self) -> Result<()> {
1282        crate::fast::composition::unsupported("window composition")
1283    }
1284    fn create_native_surface(
1285        &self,
1286    ) -> Result<Rc<dyn crate::fast::composition::PlatformSurfaceAttachment>> {
1287        crate::fast::composition::unsupported("native surface portals")
1288    }
1289    fn set_composition_order(
1290        &self,
1291        _fast_surfaces: &[crate::fast::composition::PlatformCompositionSurface],
1292    ) -> Result<()> {
1293        crate::fast::composition::unsupported("surface ordering")
1294    }
1295    fn schedule_frame(&self) {}
1296    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1297    fn is_subpixel_rendering_supported(&self) -> bool;
1298
1299    // macOS specific methods
1300    fn get_title(&self) -> String {
1301        String::new()
1302    }
1303    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1304        None
1305    }
1306    fn tab_bar_visible(&self) -> bool {
1307        false
1308    }
1309    fn set_edited(&mut self, _edited: bool) {}
1310    fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1311    fn toggle_simple_fullscreen(&self) {}
1312    fn is_simple_fullscreen(&self) -> bool {
1313        false
1314    }
1315    #[cfg(target_os = "macos")]
1316    fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1317    fn show_character_palette(&self) {}
1318    fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1319    fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1320    fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1321    fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1322    fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1323    fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1324    fn merge_all_windows(&self) {}
1325    fn move_tab_to_new_window(&self) {}
1326    fn toggle_window_tab_overview(&self) {}
1327    fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1328
1329    fn native_window_state(&self) -> Option<Vec<u8>> {
1330        None
1331    }
1332    fn restore_native_window_state(&self, _state: &[u8]) {}
1333
1334    #[cfg(target_os = "windows")]
1335    fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1336
1337    // Linux specific methods
1338    fn inner_window_bounds(&self) -> WindowBounds {
1339        self.window_bounds()
1340    }
1341    fn request_decorations(&self, _decorations: WindowDecorations) {}
1342    fn show_window_menu(&self, _position: Point<Pixels>) {}
1343    fn start_window_move(&self) {}
1344    fn can_start_external_drag(&self) -> bool {
1345        false
1346    }
1347    fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1348        false
1349    }
1350    fn start_window_resize(&self, _edge: ResizeEdge) {}
1351    fn set_exclusive_zone(&self, _zone: Pixels) {}
1352    #[cfg(all(target_os = "linux", feature = "wayland"))]
1353    fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1354    fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1355    fn window_decorations(&self) -> Decorations {
1356        Decorations::Server
1357    }
1358    fn set_app_id(&mut self, _app_id: &str) {}
1359    fn map_window(&mut self) -> anyhow::Result<()> {
1360        Ok(())
1361    }
1362    fn window_controls(&self) -> WindowControls {
1363        WindowControls::default()
1364    }
1365    fn set_client_inset(&self, _inset: Pixels) {}
1366    fn gpu_specs(&self) -> Option<GpuSpecs>;
1367
1368    fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1369
1370    // Mobile platform methods.
1371
1372    /// The regions of this window currently obscured or reserved by the
1373    /// system. Zero on platforms without such regions.
1374    fn insets(&self) -> WindowInsets {
1375        WindowInsets::default()
1376    }
1377
1378    /// Registers a callback invoked whenever [`Self::insets`] change.
1379    ///
1380    /// Contract: fires continuously during animated transitions (Android
1381    /// `WindowInsetsAnimation` progress; on iOS the platform interpolates
1382    /// the keyboard animation curve on frame ticks) and is exact at rest.
1383    fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1384
1385    /// Sets the handler for the system back action (Android back
1386    /// button/gesture; no source on iOS or desktop).
1387    fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1388
1389    /// Declares whether the application would currently handle the system
1390    /// back action (e.g. navigation depth > 0).
1391    fn set_back_enabled(&self, _enabled: bool) {}
1392
1393    /// Requests that the soft keyboard be shown.
1394    fn show_soft_keyboard(&self) {}
1395
1396    /// Requests that the soft keyboard be hidden.
1397    fn hide_soft_keyboard(&self) {}
1398
1399    /// Inform the operating system that the text input state has changed
1400    fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1401
1402    fn play_system_bell(&self) {}
1403
1404    /// Initialize the accessibility adapter with callbacks.
1405    fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1406
1407    /// Provide a TreeUpdate to the accessibility adapter.
1408    fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1409
1410    /// Inform the adapter of updated window bounds.
1411    fn a11y_update_window_bounds(&self) {}
1412
1413    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1414    fn as_test(&mut self) -> Option<&mut TestWindow> {
1415        None
1416    }
1417
1418    /// Renders the given scene to a texture and returns the pixel data as an RGBA image.
1419    /// This does not present the frame to screen - useful for visual testing where we want
1420    /// to capture what would be rendered without displaying it or requiring the window to be visible.
1421    #[cfg(any(test, feature = "test-support"))]
1422    fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1423        anyhow::bail!("render_to_image not implemented for this platform")
1424    }
1425}
1426
1427/// A renderer for headless windows that can produce real rendered output.
1428#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1429pub trait PlatformHeadlessRenderer {
1430    /// Render a scene and return the result as an RGBA image.
1431    fn render_scene_to_image(
1432        &mut self,
1433        scene: &Scene,
1434        size: Size<DevicePixels>,
1435    ) -> Result<RgbaImage>;
1436
1437    /// Render a scene to an offscreen target without reading the result back.
1438    ///
1439    /// This is the headless analogue of presenting a frame: it performs the
1440    /// same CPU-side scene encoding and GPU submission as drawing to a real
1441    /// window, but doesn't block on GPU completion or copy pixels back.
1442    fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1443
1444    /// Returns the sprite atlas used by this renderer.
1445    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1446}
1447
1448/// Type alias for runnables with metadata.
1449/// Previously an enum with a single variant, now simplified to a direct type alias.
1450#[doc(hidden)]
1451pub type RunnableVariant = Runnable<RunnableMeta>;
1452
1453#[doc(hidden)]
1454pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1455
1456#[doc(hidden)]
1457pub enum TasksIncluded {
1458    OnlyCompleted,
1459    CompletedAndRunning,
1460}
1461
1462/// This type is public so that our test macro can generate and use it, but it should not
1463/// be considered part of our public API.
1464#[doc(hidden)]
1465pub trait PlatformDispatcher: Send + Sync {
1466    fn is_main_thread(&self) -> bool;
1467    fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1468    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1469    fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1470
1471    fn dispatch_on_main_thread_when_idle(
1472        &self,
1473        runnable: RunnableVariant,
1474        timeout: Option<Duration>,
1475    ) {
1476        let _ = timeout;
1477        self.dispatch_on_main_thread(runnable, Priority::Low);
1478    }
1479
1480    fn idle_time_remaining(&self) -> Option<Duration> {
1481        None
1482    }
1483
1484    fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1485
1486    fn now(&self) -> Instant {
1487        Instant::now()
1488    }
1489
1490    fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1491        gpui_util::defer(Box::new(|| {}))
1492    }
1493
1494    fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1495        ActivityGuard::noop()
1496    }
1497
1498    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1499    fn as_test(&self) -> Option<&TestDispatcher> {
1500        None
1501    }
1502
1503    // This cfg must match the `threaded_dispatcher` module's, which implements
1504    // this method whenever it compiles.
1505    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1506    fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1507        None
1508    }
1509}
1510
1511#[expect(missing_docs)]
1512pub trait PlatformTextSystem: Send + Sync {
1513    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1514    /// Installs a nonblocking sink for unresolved grapheme clusters.
1515    fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1516    /// Get all available font names.
1517    fn all_font_names(&self) -> Vec<String>;
1518    /// Get the font ID for a font descriptor.
1519    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1520    /// Prewarm any system font caches needed to shape text.
1521    fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1522    /// Get metrics for a font.
1523    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1524    /// Get typographic bounds for a glyph.
1525    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1526    /// Get the advance width for a glyph.
1527    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1528    /// Get the glyph ID for a character.
1529    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1530    /// Get raster bounds for a glyph.
1531    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1532    /// Rasterize a glyph.
1533    fn rasterize_glyph(
1534        &self,
1535        params: &RenderGlyphParams,
1536        raster_bounds: Bounds<DevicePixels>,
1537    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1538    /// Layout a line of text with the given font runs.
1539    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1540    /// Returns the recommended text rendering mode for the given font and size.
1541    fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1542    -> TextRenderingMode;
1543    /// Returns the dilation level to use for a glyph painted in the given color.
1544    fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1545        0
1546    }
1547}
1548
1549#[expect(missing_docs)]
1550pub struct NoopTextSystem;
1551
1552#[expect(missing_docs)]
1553impl NoopTextSystem {
1554    #[allow(dead_code)]
1555    pub fn new() -> Self {
1556        Self
1557    }
1558}
1559
1560impl PlatformTextSystem for NoopTextSystem {
1561    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1562        Ok(())
1563    }
1564
1565    fn all_font_names(&self) -> Vec<String> {
1566        Vec::new()
1567    }
1568
1569    fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1570        Ok(FontId(1))
1571    }
1572
1573    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1574        FontMetrics {
1575            units_per_em: 1000,
1576            ascent: 1025.0,
1577            descent: -275.0,
1578            line_gap: 0.0,
1579            underline_position: -95.0,
1580            underline_thickness: 60.0,
1581            cap_height: 698.0,
1582            x_height: 516.0,
1583            bounding_box: Bounds {
1584                origin: Point {
1585                    x: -260.0,
1586                    y: -245.0,
1587                },
1588                size: Size {
1589                    width: 1501.0,
1590                    height: 1364.0,
1591                },
1592            },
1593        }
1594    }
1595
1596    fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1597        Ok(Bounds {
1598            origin: Point { x: 54.0, y: 0.0 },
1599            size: size(392.0, 528.0),
1600        })
1601    }
1602
1603    fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1604        Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1605    }
1606
1607    fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1608        Some(GlyphId(ch.len_utf16() as u32))
1609    }
1610
1611    fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1612        Ok(Default::default())
1613    }
1614
1615    fn rasterize_glyph(
1616        &self,
1617        _params: &RenderGlyphParams,
1618        raster_bounds: Bounds<DevicePixels>,
1619    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1620        Ok((raster_bounds.size, Vec::new()))
1621    }
1622
1623    fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1624        let mut position = px(0.);
1625        let metrics = self.font_metrics(FontId(0));
1626        let em_width = font_size
1627            * self
1628                .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1629                .unwrap()
1630                .width
1631            / metrics.units_per_em as f32;
1632        let mut glyphs = Vec::new();
1633        for (ix, c) in text.char_indices() {
1634            if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1635                glyphs.push(ShapedGlyph {
1636                    id: glyph,
1637                    position: point(position, px(0.)),
1638                    index: ix,
1639                    is_emoji: glyph.0 == 2,
1640                });
1641                if glyph.0 == 2 {
1642                    position += em_width * 2.0;
1643                } else {
1644                    position += em_width;
1645                }
1646            } else {
1647                position += em_width
1648            }
1649        }
1650        let mut runs = Vec::default();
1651        if !glyphs.is_empty() {
1652            runs.push(ShapedRun {
1653                font_id: FontId(0),
1654                glyphs,
1655            });
1656        } else {
1657            position = px(0.);
1658        }
1659
1660        LineLayout {
1661            font_size,
1662            width: position,
1663            ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1664            descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1665            runs,
1666            len: text.len(),
1667        }
1668    }
1669
1670    fn recommended_rendering_mode(
1671        &self,
1672        _font_id: FontId,
1673        _font_size: Pixels,
1674    ) -> TextRenderingMode {
1675        TextRenderingMode::Grayscale
1676    }
1677}
1678
1679// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.cpp
1680// Copyright (c) Microsoft Corporation.
1681// Licensed under the MIT license.
1682/// Compute gamma correction ratios for subpixel text rendering.
1683#[allow(dead_code)]
1684pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1685    const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1686        [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], // gamma = 1.0
1687        [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], // gamma = 1.1
1688        [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], // gamma = 1.2
1689        [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], // gamma = 1.3
1690        [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], // gamma = 1.4
1691        [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], // gamma = 1.5
1692        [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], // gamma = 1.6
1693        [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], // gamma = 1.7
1694        [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], // gamma = 1.8
1695        [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], // gamma = 1.9
1696        [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], // gamma = 2.0
1697        [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], // gamma = 2.1
1698        [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], // gamma = 2.2
1699    ];
1700
1701    const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1702    const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1703
1704    let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1705    let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1706
1707    [
1708        ratios[0] * NORM13,
1709        ratios[1] * NORM24,
1710        ratios[2] * NORM13,
1711        ratios[3] * NORM24,
1712    ]
1713}
1714
1715#[derive(PartialEq, Eq, Hash, Clone)]
1716#[expect(missing_docs)]
1717pub enum AtlasKey {
1718    Glyph(RenderGlyphParams),
1719    Svg(RenderSvgParams),
1720    Image(RenderImageParams),
1721}
1722
1723impl AtlasKey {
1724    /// Returns the texture kind for this atlas key.
1725    pub fn texture_kind(&self) -> AtlasTextureKind {
1726        match self {
1727            AtlasKey::Glyph(params) => {
1728                if params.is_emoji {
1729                    AtlasTextureKind::Polychrome
1730                } else if params.subpixel_rendering {
1731                    AtlasTextureKind::Subpixel
1732                } else {
1733                    AtlasTextureKind::Monochrome
1734                }
1735            }
1736            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1737            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1738        }
1739    }
1740}
1741
1742impl From<RenderGlyphParams> for AtlasKey {
1743    fn from(params: RenderGlyphParams) -> Self {
1744        Self::Glyph(params)
1745    }
1746}
1747
1748impl From<RenderSvgParams> for AtlasKey {
1749    fn from(params: RenderSvgParams) -> Self {
1750        Self::Svg(params)
1751    }
1752}
1753
1754impl From<RenderImageParams> for AtlasKey {
1755    fn from(params: RenderImageParams) -> Self {
1756        Self::Image(params)
1757    }
1758}
1759
1760#[expect(missing_docs)]
1761pub trait PlatformAtlas {
1762    /// The builder runs with the atlas locked and must not re-enter the same atlas.
1763    fn get_or_insert_with<'a>(
1764        &self,
1765        key: AtlasKey,
1766        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1767    ) -> Result<Option<AtlasTile>>;
1768    fn remove(&self, key: &AtlasKey);
1769
1770    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1771    fn contains(&self, _key: &AtlasKey) -> bool {
1772        false
1773    }
1774}
1775
1776#[doc(hidden)]
1777pub trait AtlasBackend {
1778    fn insert(
1779        &mut self,
1780        kind: AtlasTextureKind,
1781        size: Size<DevicePixels>,
1782        bytes: &[u8],
1783    ) -> Result<AtlasTile>;
1784
1785    fn remove(&mut self, tile: AtlasTile);
1786}
1787
1788#[doc(hidden)]
1789pub struct AtlasState<Backend> {
1790    tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1791    pub backend: Backend,
1792}
1793
1794impl<Backend> AtlasState<Backend> {
1795    pub fn new(backend: Backend) -> Self {
1796        Self {
1797            tiles_by_key: FxHashMap::default(),
1798            backend,
1799        }
1800    }
1801
1802    pub fn contains(&self, key: &AtlasKey) -> bool {
1803        self.tiles_by_key.contains_key(key)
1804    }
1805
1806    pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1807        self.tiles_by_key.clear();
1808        reset_backend(&mut self.backend);
1809    }
1810}
1811
1812impl<Backend: Default> Default for AtlasState<Backend> {
1813    fn default() -> Self {
1814        Self::new(Backend::default())
1815    }
1816}
1817
1818impl<Backend: AtlasBackend> AtlasState<Backend> {
1819    pub fn get_or_insert_with<'a>(
1820        &mut self,
1821        key: AtlasKey,
1822        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1823    ) -> Result<Option<AtlasTile>> {
1824        match self.tiles_by_key.entry(key) {
1825            Entry::Occupied(entry) => Ok(Some(*entry.get())),
1826            Entry::Vacant(entry) => {
1827                profiling::scope!("new tile");
1828                let Some((size, bytes)) = build()? else {
1829                    return Ok(None);
1830                };
1831                let tile = self
1832                    .backend
1833                    .insert(entry.key().texture_kind(), size, &bytes)?;
1834                entry.insert(tile);
1835                Ok(Some(tile))
1836            }
1837        }
1838    }
1839
1840    pub fn remove(&mut self, key: &AtlasKey) {
1841        if let Some(tile) = self.tiles_by_key.remove(key) {
1842            self.backend.remove(tile);
1843        }
1844    }
1845}
1846
1847/// A sprite atlas for windows without a GPU. It hands out uniquely identified
1848/// tiles without uploading any pixels, so glyph, SVG, and image painting can
1849/// run to completion in tests and headless platforms.
1850#[derive(Default)]
1851pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1852
1853#[doc(hidden)]
1854#[derive(Default)]
1855pub struct HeadlessAtlasBackend {
1856    next_id: u32,
1857}
1858
1859impl AtlasBackend for HeadlessAtlasBackend {
1860    fn insert(
1861        &mut self,
1862        kind: AtlasTextureKind,
1863        size: Size<DevicePixels>,
1864        _bytes: &[u8],
1865    ) -> Result<AtlasTile> {
1866        self.next_id += 1;
1867        let texture_id = self.next_id;
1868        self.next_id += 1;
1869        let tile_id = self.next_id;
1870        Ok(AtlasTile {
1871            texture_id: AtlasTextureId {
1872                index: texture_id,
1873                kind,
1874            },
1875            tile_id: TileId(tile_id),
1876            padding: 0,
1877            bounds: Bounds {
1878                origin: Point::default(),
1879                size,
1880            },
1881        })
1882    }
1883
1884    fn remove(&mut self, _tile: AtlasTile) {}
1885}
1886
1887impl PlatformAtlas for HeadlessAtlas {
1888    fn get_or_insert_with<'a>(
1889        &self,
1890        key: AtlasKey,
1891        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1892    ) -> Result<Option<AtlasTile>> {
1893        self.0.lock().get_or_insert_with(key, build)
1894    }
1895
1896    fn remove(&self, key: &AtlasKey) {
1897        self.0.lock().remove(key);
1898    }
1899
1900    #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1901    fn contains(&self, key: &AtlasKey) -> bool {
1902        self.0.lock().contains(key)
1903    }
1904}
1905
1906#[doc(hidden)]
1907pub struct AtlasTextureList<T> {
1908    pub textures: Vec<Option<T>>,
1909    pub free_list: Vec<usize>,
1910}
1911
1912impl<T> Default for AtlasTextureList<T> {
1913    fn default() -> Self {
1914        Self {
1915            textures: Vec::default(),
1916            free_list: Vec::default(),
1917        }
1918    }
1919}
1920
1921impl<T> ops::Index<usize> for AtlasTextureList<T> {
1922    type Output = Option<T>;
1923
1924    fn index(&self, index: usize) -> &Self::Output {
1925        &self.textures[index]
1926    }
1927}
1928
1929impl<T> AtlasTextureList<T> {
1930    #[allow(unused)]
1931    pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1932        self.free_list.clear();
1933        self.textures.drain(..)
1934    }
1935
1936    #[allow(dead_code)]
1937    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1938        self.textures.iter_mut().flatten()
1939    }
1940}
1941
1942#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1943#[repr(C)]
1944#[expect(missing_docs)]
1945pub struct AtlasTile {
1946    /// The texture this tile belongs to.
1947    pub texture_id: AtlasTextureId,
1948    /// The unique ID of this tile within its texture.
1949    pub tile_id: TileId,
1950    /// Padding around the tile content in pixels.
1951    pub padding: u32,
1952    /// The bounds of this tile within the texture.
1953    pub bounds: Bounds<DevicePixels>,
1954}
1955
1956#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1957#[repr(C)]
1958#[expect(missing_docs)]
1959pub struct AtlasTextureId {
1960    // We use u32 instead of usize for Metal Shader Language compatibility
1961    /// The index of this texture in the atlas.
1962    pub index: u32,
1963    /// The kind of content stored in this texture.
1964    pub kind: AtlasTextureKind,
1965}
1966
1967#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1968#[repr(C)]
1969#[cfg_attr(
1970    all(
1971        any(target_os = "linux", target_os = "freebsd"),
1972        not(any(feature = "x11", feature = "wayland"))
1973    ),
1974    allow(dead_code)
1975)]
1976#[expect(missing_docs)]
1977pub enum AtlasTextureKind {
1978    Monochrome = 0,
1979    Polychrome = 1,
1980    Subpixel = 2,
1981}
1982
1983#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1984#[repr(C)]
1985#[expect(missing_docs)]
1986pub struct TileId(pub u32);
1987
1988impl From<etagere::AllocId> for TileId {
1989    fn from(id: etagere::AllocId) -> Self {
1990        Self(id.serialize())
1991    }
1992}
1993
1994impl From<TileId> for etagere::AllocId {
1995    fn from(id: TileId) -> Self {
1996        Self::deserialize(id.0)
1997    }
1998}
1999
2000#[expect(missing_docs)]
2001pub struct PlatformInputHandler {
2002    cx: AsyncWindowContext,
2003    handler: Box<dyn InputHandler>,
2004}
2005
2006#[expect(missing_docs)]
2007#[cfg_attr(
2008    all(
2009        any(target_os = "linux", target_os = "freebsd"),
2010        not(any(feature = "x11", feature = "wayland"))
2011    ),
2012    allow(dead_code)
2013)]
2014impl PlatformInputHandler {
2015    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2016        Self { cx, handler }
2017    }
2018
2019    pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2020        self.cx
2021            .update(|window, cx| {
2022                self.handler
2023                    .selected_text_range(ignore_disabled_input, window, cx)
2024            })
2025            .ok()
2026            .flatten()
2027    }
2028
2029    #[cfg_attr(target_os = "windows", allow(dead_code))]
2030    pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2031        self.cx
2032            .update(|window, cx| self.handler.marked_text_range(window, cx))
2033            .ok()
2034            .flatten()
2035    }
2036
2037    #[cfg_attr(
2038        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2039        allow(dead_code)
2040    )]
2041    pub fn text_for_range(
2042        &mut self,
2043        range_utf16: Range<usize>,
2044        adjusted: &mut Option<Range<usize>>,
2045    ) -> Option<String> {
2046        self.cx
2047            .update(|window, cx| {
2048                self.handler
2049                    .text_for_range(range_utf16, adjusted, window, cx)
2050            })
2051            .ok()
2052            .flatten()
2053    }
2054
2055    pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2056        self.cx
2057            .update(|window, cx| {
2058                self.handler
2059                    .replace_text_in_range(replacement_range, text, window, cx);
2060            })
2061            .ok();
2062    }
2063
2064    pub fn replace_and_mark_text_in_range(
2065        &mut self,
2066        range_utf16: Option<Range<usize>>,
2067        new_text: &str,
2068        new_selected_range: Option<Range<usize>>,
2069    ) {
2070        self.cx
2071            .update(|window, cx| {
2072                self.handler.replace_and_mark_text_in_range(
2073                    range_utf16,
2074                    new_text,
2075                    new_selected_range,
2076                    window,
2077                    cx,
2078                )
2079            })
2080            .ok();
2081    }
2082
2083    #[cfg_attr(target_os = "windows", allow(dead_code))]
2084    pub fn unmark_text(&mut self) {
2085        self.cx
2086            .update(|window, cx| self.handler.unmark_text(window, cx))
2087            .ok();
2088    }
2089
2090    pub fn paste(&mut self, item: ClipboardItem) {
2091        self.cx
2092            .update(|window, cx| self.handler.paste(item, window, cx))
2093            .ok();
2094    }
2095
2096    pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2097        self.cx
2098            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2099            .ok()
2100            .flatten()
2101    }
2102
2103    #[allow(dead_code)]
2104    pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2105        self.handler.apple_press_and_hold_enabled()
2106    }
2107
2108    pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2109        self.handler.replace_text_in_range(None, input, window, cx);
2110    }
2111
2112    pub fn compute_ime_candidate_bounds(
2113        marked_range: Option<Range<usize>>,
2114        selection: &UTF16Selection,
2115        mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2116    ) -> Option<Bounds<Pixels>> {
2117        if let Some(marked_range) = marked_range {
2118            // Default to the start of the marked (composing) range.
2119            let mut line_start = marked_range.start;
2120
2121            // Walk backward from the caret looking for a line break. A change in
2122            // the Y coordinate means we crossed into the previous visual line, so
2123            // the line start is one position after the break point.
2124            let caret = selection.range.end;
2125            if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2126                for i in (marked_range.start..caret).rev() {
2127                    if let Some(b) = bounds_for_range(i..i) {
2128                        if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2129                            line_start = i + 1;
2130                            break;
2131                        }
2132                    }
2133                }
2134            }
2135            bounds_for_range(line_start..line_start)
2136        } else {
2137            // No active composition — use the selection endpoint.
2138            let offset = if selection.reversed {
2139                selection.range.start
2140            } else {
2141                selection.range.end
2142            };
2143            bounds_for_range(offset..offset)
2144        }
2145    }
2146
2147    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2148        let marked_range = self.handler.marked_text_range(window, cx);
2149        let selection = self.handler.selected_text_range(true, window, cx)?;
2150        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2151            self.handler.bounds_for_range(range, window, cx)
2152        })
2153    }
2154
2155    pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2156        let marked_range = self.marked_text_range();
2157        let selection = self.selected_text_range(true)?;
2158        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2159            self.bounds_for_range(range)
2160        })
2161    }
2162
2163    #[allow(unused)]
2164    pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2165        self.cx
2166            .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2167            .ok()
2168            .flatten()
2169    }
2170
2171    /// See [`InputHandler::set_selected_text_range`].
2172    pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2173        self.cx
2174            .update(|window, cx| {
2175                self.handler
2176                    .set_selected_text_range(range_utf16, window, cx)
2177            })
2178            .ok();
2179    }
2180
2181    /// See [`InputHandler::element_bounds`].
2182    pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2183        self.cx
2184            .update(|window, cx| self.handler.element_bounds(window, cx))
2185            .ok()
2186            .flatten()
2187    }
2188
2189    /// See [`InputHandler::text_length_utf16`].
2190    pub fn text_length_utf16(&mut self) -> Option<usize> {
2191        self.cx
2192            .update(|window, cx| self.handler.text_length_utf16(window, cx))
2193            .ok()
2194            .flatten()
2195    }
2196
2197    #[allow(dead_code)]
2198    pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2199        self.handler.accepts_text_input(window, cx)
2200    }
2201
2202    #[allow(dead_code)]
2203    pub fn query_accepts_text_input(&mut self) -> bool {
2204        self.cx
2205            .update(|window, cx| self.handler.accepts_text_input(window, cx))
2206            .unwrap_or(true)
2207    }
2208
2209    /// See [`InputHandler::prefers_ime_for_printable_keys`].
2210    ///
2211    /// This is not a pure delegation to the handler: while a multi-stroke binding is pending this
2212    /// returns `false` regardless of the handler's preference, because the next printable key may
2213    /// complete a binding whose prefix already bypassed the IME.
2214    pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2215        self.cx
2216            .update(|window, cx| {
2217                // The next printable key may complete a chord whose prefix bypassed the IME.
2218                !window.has_pending_keystrokes()
2219                    && self.handler.prefers_ime_for_printable_keys(window, cx)
2220            })
2221            .unwrap_or(false)
2222    }
2223
2224    /// See [`InputHandler::text_input_configuration`].
2225    pub fn text_input_configuration(
2226        &mut self,
2227        window: &mut Window,
2228        cx: &mut App,
2229    ) -> TextInputConfiguration {
2230        self.handler.text_input_configuration(window, cx)
2231    }
2232
2233    /// See [`InputHandler::text_input_editable_range`].
2234    pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2235        self.cx
2236            .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2237            .ok()
2238            .flatten()
2239    }
2240}
2241
2242/// A struct representing a selection in a text buffer, in UTF16 characters.
2243/// This is different from a range because the head may be before the tail.
2244#[derive(Debug)]
2245pub struct UTF16Selection {
2246    /// The range of text in the document this selection corresponds to
2247    /// in UTF16 characters.
2248    pub range: Range<usize>,
2249    /// Whether the head of this selection is at the start (true), or end (false)
2250    /// of the range
2251    pub reversed: bool,
2252}
2253
2254/// Zed's interface for handling text input from the platform's IME system
2255/// This is currently a 1:1 exposure of the NSTextInputClient API:
2256///
2257/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
2258pub trait InputHandler: 'static {
2259    /// Get the range of the user's currently selected text, if any
2260    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
2261    ///
2262    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
2263    fn selected_text_range(
2264        &mut self,
2265        ignore_disabled_input: bool,
2266        window: &mut Window,
2267        cx: &mut App,
2268    ) -> Option<UTF16Selection>;
2269
2270    /// Get the range of the currently marked text, if any
2271    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
2272    ///
2273    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
2274    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2275
2276    /// Get the text for the given document range in UTF-16 characters
2277    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
2278    ///
2279    /// range_utf16 is in terms of UTF-16 characters
2280    fn text_for_range(
2281        &mut self,
2282        range_utf16: Range<usize>,
2283        adjusted_range: &mut Option<Range<usize>>,
2284        window: &mut Window,
2285        cx: &mut App,
2286    ) -> Option<String>;
2287
2288    /// Replace the text in the given document range with the given text
2289    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
2290    ///
2291    /// replacement_range is in terms of UTF-16 characters
2292    fn replace_text_in_range(
2293        &mut self,
2294        replacement_range: Option<Range<usize>>,
2295        text: &str,
2296        window: &mut Window,
2297        cx: &mut App,
2298    );
2299
2300    /// Replace the text in the given document range with the given text,
2301    /// and mark the given text as part of an IME 'composing' state
2302    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
2303    ///
2304    /// range_utf16 is in terms of UTF-16 characters
2305    /// new_selected_range is in terms of UTF-16 characters
2306    fn replace_and_mark_text_in_range(
2307        &mut self,
2308        range_utf16: Option<Range<usize>>,
2309        new_text: &str,
2310        new_selected_range: Option<Range<usize>>,
2311        window: &mut Window,
2312        cx: &mut App,
2313    );
2314
2315    /// Remove the IME 'composing' state from the document
2316    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
2317    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2318
2319    /// Insert a platform-initiated paste at the current selection.
2320    ///
2321    /// Platforms that deliver paste as an input event rather than through an
2322    /// application-defined action (e.g. the DOM `paste` event on web) call
2323    /// this with the full clipboard contents. The default implementation
2324    /// inserts only the plain-text portion of the item.
2325    fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2326        if let Some(text) = item.text() {
2327            self.replace_text_in_range(None, &text, window, cx);
2328        }
2329    }
2330
2331    /// Get the bounds of the given document range in screen coordinates
2332    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
2333    ///
2334    /// This is used for positioning the IME candidate window
2335    fn bounds_for_range(
2336        &mut self,
2337        range_utf16: Range<usize>,
2338        window: &mut Window,
2339        cx: &mut App,
2340    ) -> Option<Bounds<Pixels>>;
2341
2342    /// Get the character offset for the given point in terms of UTF16 characters
2343    ///
2344    /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
2345    fn character_index_for_point(
2346        &mut self,
2347        point: Point<Pixels>,
2348        window: &mut Window,
2349        cx: &mut App,
2350    ) -> Option<usize>;
2351
2352    /// Set the range of the user's currently selected text.
2353    ///
2354    /// This is the reverse data-flow direction from [`Self::selected_text_range`]:
2355    /// platforms call it when the system text machinery moves the selection on the
2356    /// application's behalf — e.g. the user drags a system selection handle or
2357    /// invokes Select All from system UI (iOS `UITextInput setSelectedTextRange:`,
2358    /// Android `InputConnection.setSelection`).
2359    ///
2360    /// range_utf16 is in terms of UTF-16 characters, from 0 to the length of the document
2361    fn set_selected_text_range(
2362        &mut self,
2363        _range_utf16: Range<usize>,
2364        _window: &mut Window,
2365        _cx: &mut App,
2366    ) {
2367    }
2368
2369    /// Get the bounds of the focused text element in window coordinates, if known.
2370    ///
2371    /// This is the pull counterpart to the [`PlatformWindow::update_ime_position`]
2372    /// push: mobile platforms ask for the focused element's geometry when they
2373    /// need it (e.g. to frame system text-interaction UI overlaid on the focused
2374    /// element).
2375    fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2376        None
2377    }
2378
2379    /// Get the length of the document in UTF-16 characters, if known.
2380    fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2381        None
2382    }
2383
2384    /// Allows a given input context to opt into getting raw key repeats instead of
2385    /// sending these to the platform.
2386    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
2387    /// (which is how iTerm does it) but it doesn't seem to work for me.
2388    #[allow(dead_code)]
2389    fn apple_press_and_hold_enabled(&mut self) -> bool {
2390        true
2391    }
2392
2393    /// Returns whether this handler is accepting text input to be inserted.
2394    fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2395        true
2396    }
2397
2398    /// The contiguous range of text, in UTF-16 code units, that platform text
2399    /// input may read and edit around the current selection.
2400    ///
2401    /// Platforms that mirror document text into an IME-editable buffer clamp
2402    /// the mirrored window to this range, so multi-step IME edit gestures
2403    /// (word deletion, autocorrect rewrites, suggestion picks) cannot reach
2404    /// content outside it. The range should contain the current selection;
2405    /// when it cannot (a selection spanning a region boundary), platforms
2406    /// degrade the mirrored IME context rather than widening the range.
2407    /// `None` places no bound.
2408    fn text_input_editable_range(
2409        &mut self,
2410        _window: &mut Window,
2411        _cx: &mut App,
2412    ) -> Option<Range<usize>> {
2413        None
2414    }
2415
2416    /// Returns whether printable keys should be routed to the IME before keybinding
2417    /// matching when a non-ASCII input source (e.g. Japanese, Korean, Chinese IME)
2418    /// is active. This prevents multi-stroke keybindings like `jj` from intercepting
2419    /// keys that the IME should compose.
2420    ///
2421    /// Defaults to `false`. The editor overrides this based on whether it expects
2422    /// character input (e.g. Vim insert mode returns `true`, normal mode returns `false`).
2423    /// The terminal keeps the default `false` so that raw keys reach the terminal process.
2424    fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2425        false
2426    }
2427
2428    /// Get this handler's preferences for platform text assistance.
2429    ///
2430    /// GPUI re-queries this every frame and forwards it to the platform window
2431    /// only when it changes, so implementations must be cheap and may vary the
2432    /// result with application state (e.g. with the cursor's position).
2433    fn text_input_configuration(
2434        &mut self,
2435        _window: &mut Window,
2436        _cx: &mut App,
2437    ) -> TextInputConfiguration {
2438        TextInputConfiguration::default()
2439    }
2440}
2441
2442/// Platform text-assistance preferences for the focused text region.
2443///
2444/// Returned by [`InputHandler::text_input_configuration`] and forwarded to the
2445/// platform whenever it changes; the platform maps the fields onto its native
2446/// input-session attributes (on web, DOM attributes of the hidden editable
2447/// element such as `autocorrect` and `enterkeyhint`).
2448///
2449/// The default disables all text assistance and requests no particular action
2450/// key presentation.
2451#[derive(Clone, Debug, Default, PartialEq, Eq)]
2452pub struct TextInputConfiguration {
2453    /// Whether the platform may automatically correct entered text.
2454    pub autocorrect: bool,
2455    /// How software keyboards automatically capitalize entered text.
2456    pub autocapitalize: Autocapitalize,
2457    /// Whether software keyboards may offer word suggestions and spellcheck.
2458    pub suggestions: bool,
2459    /// The action advertised on a software keyboard's confirm ("enter") key.
2460    pub input_action: TextInputAction,
2461}
2462
2463/// Automatic capitalization applied by software keyboards.
2464#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2465pub enum Autocapitalize {
2466    /// No automatic capitalization.
2467    #[default]
2468    None,
2469    /// Capitalize the first letter of each word.
2470    Words,
2471    /// Capitalize the first letter of each sentence.
2472    Sentences,
2473    /// Capitalize every letter.
2474    Characters,
2475}
2476
2477/// The action a software keyboard advertises on its confirm ("enter") key.
2478///
2479/// This affects only how the key is presented (icon or label); pressing it is
2480/// still delivered as ordinary input.
2481///
2482/// The variants are the HTML `enterkeyhint` attribute's value set
2483/// (<https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-enterkeyhint-attribute>),
2484/// which also maps onto Android's `IME_ACTION_*` constants and iOS's
2485/// `UIReturnKeyType`; [`TextInputAction::Unspecified`] means "emit no hint".
2486#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2487pub enum TextInputAction {
2488    /// Let the platform choose its default presentation.
2489    #[default]
2490    Unspecified,
2491    /// Inserting a line break.
2492    Enter,
2493    /// Committing the field's value.
2494    Done,
2495    /// Navigating to the typed target.
2496    Go,
2497    /// Moving to the next field.
2498    Next,
2499    /// Moving to the previous field.
2500    Previous,
2501    /// Executing a search.
2502    Search,
2503    /// Sending a message.
2504    Send,
2505}
2506
2507/// The variables that can be configured when creating a new window
2508#[derive(Debug)]
2509pub struct WindowOptions {
2510    /// Specifies the state and bounds of the window in screen coordinates.
2511    /// - `None`: Inherit the bounds.
2512    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
2513    pub window_bounds: Option<WindowBounds>,
2514
2515    /// The titlebar configuration of the window
2516    pub titlebar: Option<TitlebarOptions>,
2517
2518    /// Whether the window should be focused when created
2519    pub focus: bool,
2520
2521    /// Whether the window should be shown when created
2522    pub show: bool,
2523
2524    /// The kind of window to create
2525    pub kind: WindowKind,
2526
2527    /// Whether the window can be moved by the user. When `false`, the user cannot drag
2528    /// the window (on macOS this sets `NSWindow.isMovable`, which also disables the
2529    /// Window-menu tiling items); programmatic moves are still allowed.
2530    pub is_movable: bool,
2531
2532    /// Whether the application owns dragging of the (custom) titlebar, rather than
2533    /// AppKit. Only has an effect on macOS.
2534    ///
2535    /// Set this to `true` for windows that draw their own titlebar and move the window
2536    /// themselves via [`Window::start_window_move`]. It marks the whole content view as
2537    /// app-owned titlebar content, so AppKit neither drags the window from the titlebar
2538    /// nor delays titlebar clicks while disambiguating double-clicks (a delay first
2539    /// observed on macOS 27). It is independent of `is_movable`, so such windows stay
2540    /// user-movable (via their own drag) and keep the Window-menu tiling items enabled.
2541    ///
2542    /// Leave this `false` for windows that rely on AppKit's native titlebar dragging.
2543    pub app_owns_titlebar_drag: bool,
2544
2545    /// The minimum interval between animation frames while the window is inactive.
2546    ///
2547    /// Set to `None` to disable inactive-window animation frame throttling.
2548    pub inactive_frame_interval: Option<Duration>,
2549
2550    /// Whether the window should be resizable by the user
2551    pub is_resizable: bool,
2552
2553    /// Whether the window should be minimized by the user
2554    pub is_minimizable: bool,
2555
2556    /// The display to create the window on, if this is None,
2557    /// the window will be created on the main display
2558    pub display_id: Option<DisplayId>,
2559
2560    /// The appearance of the window background.
2561    pub window_background: WindowBackgroundAppearance,
2562
2563    /// Application identifier of the window. Can by used by desktop environments to group applications together.
2564    pub app_id: Option<String>,
2565
2566    /// Window minimum size
2567    pub window_min_size: Option<Size<Pixels>>,
2568
2569    /// Whether to use client or server-side decorations on X11 and Wayland.
2570    /// The platform may ignore requests it cannot satisfy.
2571    pub window_decorations: Option<WindowDecorations>,
2572
2573    /// Icon image (X11 only)
2574    pub icon: Option<Arc<image::RgbaImage>>,
2575
2576    /// 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.
2577    pub tabbing_identifier: Option<String>,
2578}
2579
2580/// The variables that can be configured when creating a new window
2581#[derive(Debug)]
2582#[cfg_attr(
2583    all(
2584        any(target_os = "linux", target_os = "freebsd"),
2585        not(any(feature = "x11", feature = "wayland"))
2586    ),
2587    allow(dead_code)
2588)]
2589#[allow(missing_docs)]
2590pub struct WindowParams {
2591    pub bounds: Bounds<Pixels>,
2592
2593    /// The titlebar configuration of the window
2594    #[cfg_attr(feature = "wayland", allow(dead_code))]
2595    pub titlebar: Option<TitlebarOptions>,
2596
2597    /// The kind of window to create
2598    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2599    pub kind: WindowKind,
2600
2601    /// Whether the window should be movable by the user
2602    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2603    pub is_movable: bool,
2604
2605    /// Whether the application owns dragging of the (custom) titlebar (macOS only)
2606    #[cfg_attr(
2607        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2608        allow(dead_code)
2609    )]
2610    pub app_owns_titlebar_drag: bool,
2611
2612    /// Whether the window should be resizable by the user
2613    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2614    pub is_resizable: bool,
2615
2616    /// Whether the window should be minimized by the user
2617    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2618    pub is_minimizable: bool,
2619
2620    #[cfg_attr(
2621        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2622        allow(dead_code)
2623    )]
2624    pub focus: bool,
2625
2626    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2627    pub show: bool,
2628
2629    /// An image to set as the window icon (x11 only)
2630    #[cfg_attr(feature = "wayland", allow(dead_code))]
2631    pub icon: Option<Arc<image::RgbaImage>>,
2632
2633    #[cfg_attr(feature = "wayland", allow(dead_code))]
2634    pub display_id: Option<DisplayId>,
2635
2636    #[cfg_attr(feature = "wayland", allow(dead_code))]
2637    pub app_id: Option<String>,
2638
2639    pub window_min_size: Option<Size<Pixels>>,
2640
2641    #[cfg(target_os = "macos")]
2642    pub tabbing_identifier: Option<String>,
2643}
2644
2645/// Represents the status of how a window should be opened.
2646#[derive(Debug, Copy, Clone, PartialEq)]
2647pub enum WindowBounds {
2648    /// Indicates that the window should open in a windowed state with the given bounds.
2649    Windowed(Bounds<Pixels>),
2650    /// Indicates that the window should open in a maximized state.
2651    /// The bounds provided here represent the restore size of the window.
2652    Maximized(Bounds<Pixels>),
2653    /// Indicates that the window should open in fullscreen mode.
2654    /// The bounds provided here represent the restore size of the window.
2655    Fullscreen(Bounds<Pixels>),
2656}
2657
2658impl Default for WindowBounds {
2659    fn default() -> Self {
2660        WindowBounds::Windowed(Bounds::default())
2661    }
2662}
2663
2664impl WindowBounds {
2665    /// Retrieve the inner bounds
2666    pub fn get_bounds(&self) -> Bounds<Pixels> {
2667        match self {
2668            WindowBounds::Windowed(bounds) => *bounds,
2669            WindowBounds::Maximized(bounds) => *bounds,
2670            WindowBounds::Fullscreen(bounds) => *bounds,
2671        }
2672    }
2673
2674    /// Creates a new window bounds that centers the window on the screen.
2675    pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
2676        WindowBounds::Windowed(Bounds::centered(None, size, cx))
2677    }
2678}
2679
2680impl Default for WindowOptions {
2681    fn default() -> Self {
2682        Self {
2683            window_bounds: None,
2684            titlebar: Some(TitlebarOptions {
2685                title: Default::default(),
2686                appears_transparent: Default::default(),
2687                traffic_light_position: Default::default(),
2688            }),
2689            focus: true,
2690            show: true,
2691            kind: WindowKind::Normal,
2692            is_movable: true,
2693            app_owns_titlebar_drag: false,
2694            inactive_frame_interval: Some(Duration::from_micros(33_333)),
2695            is_resizable: true,
2696            is_minimizable: true,
2697            display_id: None,
2698            window_background: WindowBackgroundAppearance::default(),
2699            icon: None,
2700            app_id: None,
2701            window_min_size: None,
2702            window_decorations: None,
2703            tabbing_identifier: None,
2704        }
2705    }
2706}
2707
2708/// The options that can be configured for a window's titlebar
2709#[derive(Debug, Default)]
2710pub struct TitlebarOptions {
2711    /// The initial title of the window
2712    pub title: Option<SharedString>,
2713
2714    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
2715    /// Refer to [`WindowOptions::window_decorations`] on Linux
2716    pub appears_transparent: bool,
2717
2718    /// The position of the macOS traffic light buttons
2719    pub traffic_light_position: Option<Point<Pixels>>,
2720}
2721
2722/// The kind of window to create
2723#[derive(Clone, Debug, PartialEq, Eq)]
2724pub enum WindowKind {
2725    /// A normal application window
2726    Normal,
2727
2728    /// A window that appears above all other windows, usually used for alerts or popups
2729    /// use sparingly!
2730    PopUp,
2731
2732    /// A parent-anchored, platform-native popup window for menus, comboboxes, context menus and
2733    /// tooltips. Unlike [`WindowKind::PopUp`], it is positioned relative to a parent window.
2734    ///
2735    /// The popup's size comes from [`WindowOptions::window_bounds`], whose origin is ignored.
2736    /// See [`popup::PopupOptions`] for the placement options. Platforms without a native
2737    /// implementation reject it with [`popup::PopupNotSupportedError`].
2738    AnchoredPopup(popup::PopupOptions),
2739
2740    /// A floating window that appears on top of its parent window
2741    Floating,
2742
2743    /// A Wayland LayerShell window, used to draw overlays or backgrounds for applications such as
2744    /// docks, notifications or wallpapers.
2745    #[cfg(all(target_os = "linux", feature = "wayland"))]
2746    LayerShell(layer_shell::LayerShellOptions),
2747
2748    /// A window that appears on top of its parent window and blocks interaction with it
2749    /// until the modal window is closed
2750    Dialog,
2751}
2752
2753/// The appearance of the window, as defined by the operating system.
2754///
2755/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
2756/// values.
2757#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2758pub enum WindowAppearance {
2759    /// A light appearance.
2760    ///
2761    /// On macOS, this corresponds to the `aqua` appearance.
2762    #[default]
2763    Light,
2764
2765    /// A light appearance with vibrant colors.
2766    ///
2767    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
2768    VibrantLight,
2769
2770    /// A dark appearance.
2771    ///
2772    /// On macOS, this corresponds to the `darkAqua` appearance.
2773    Dark,
2774
2775    /// A dark appearance with vibrant colors.
2776    ///
2777    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
2778    VibrantDark,
2779}
2780
2781/// The appearance of the background of the window itself, when there is
2782/// no content or the content is transparent.
2783#[derive(Copy, Clone, Debug, Default, PartialEq)]
2784pub enum WindowBackgroundAppearance {
2785    /// Opaque.
2786    ///
2787    /// This lets the window manager know that content behind this
2788    /// window does not need to be drawn.
2789    ///
2790    /// Actual color depends on the system and themes should define a fully
2791    /// opaque background color instead.
2792    #[default]
2793    Opaque,
2794    /// Plain alpha transparency.
2795    Transparent,
2796    /// Transparency, but the contents behind the window are blurred.
2797    ///
2798    /// Not always supported.
2799    Blurred,
2800    /// The Mica backdrop material, supported on Windows 11.
2801    MicaBackdrop,
2802    /// The Mica Alt backdrop material, supported on Windows 11.
2803    MicaAltBackdrop,
2804}
2805
2806/// The text rendering mode to use for drawing glyphs.
2807#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2808pub enum TextRenderingMode {
2809    /// Use the platform's default text rendering mode.
2810    #[default]
2811    PlatformDefault,
2812    /// Use subpixel (ClearType-style) text rendering.
2813    Subpixel,
2814    /// Use grayscale text rendering.
2815    Grayscale,
2816}
2817
2818/// The options that can be configured for a file dialog prompt
2819#[derive(Clone, Debug)]
2820pub struct PathPromptOptions {
2821    /// Should the prompt allow files to be selected?
2822    pub files: bool,
2823    /// Should the prompt allow directories to be selected?
2824    pub directories: bool,
2825    /// Should the prompt allow multiple files to be selected?
2826    pub multiple: bool,
2827    /// The prompt to show to a user when selecting a path
2828    pub prompt: Option<SharedString>,
2829}
2830
2831/// What kind of prompt styling to show
2832#[derive(Copy, Clone, Debug, PartialEq)]
2833pub enum PromptLevel {
2834    /// A prompt that is shown when the user should be notified of something
2835    Info,
2836
2837    /// A prompt that is shown when the user needs to be warned of a potential problem
2838    Warning,
2839
2840    /// A prompt that is shown when a critical problem has occurred
2841    Critical,
2842}
2843
2844/// Prompt Button
2845#[derive(Clone, Debug, PartialEq)]
2846pub enum PromptButton {
2847    /// Ok button
2848    Ok(SharedString),
2849    /// Cancel button
2850    Cancel(SharedString),
2851    /// Other button
2852    Other(SharedString),
2853}
2854
2855impl PromptButton {
2856    /// Create a button with label
2857    pub fn new(label: impl Into<SharedString>) -> Self {
2858        PromptButton::Other(label.into())
2859    }
2860
2861    /// Create an Ok button
2862    pub fn ok(label: impl Into<SharedString>) -> Self {
2863        PromptButton::Ok(label.into())
2864    }
2865
2866    /// Create a Cancel button
2867    pub fn cancel(label: impl Into<SharedString>) -> Self {
2868        PromptButton::Cancel(label.into())
2869    }
2870
2871    /// Returns true if this button is a cancel button.
2872    #[allow(dead_code)]
2873    pub fn is_cancel(&self) -> bool {
2874        matches!(self, PromptButton::Cancel(_))
2875    }
2876
2877    /// Returns the label of the button
2878    pub fn label(&self) -> &SharedString {
2879        match self {
2880            PromptButton::Ok(label) => label,
2881            PromptButton::Cancel(label) => label,
2882            PromptButton::Other(label) => label,
2883        }
2884    }
2885}
2886
2887impl From<&str> for PromptButton {
2888    fn from(value: &str) -> Self {
2889        match value.to_lowercase().as_str() {
2890            "ok" => PromptButton::Ok("OK".into()),
2891            "cancel" => PromptButton::Cancel("Cancel".into()),
2892            _ => PromptButton::Other(SharedString::from(value.to_owned())),
2893        }
2894    }
2895}
2896
2897/// The style of the cursor (pointer)
2898#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2899pub enum CursorStyle {
2900    /// The default cursor
2901    #[default]
2902    Arrow,
2903
2904    /// A text input cursor
2905    /// corresponds to the CSS cursor value `text`
2906    IBeam,
2907
2908    /// A crosshair cursor
2909    /// corresponds to the CSS cursor value `crosshair`
2910    Crosshair,
2911
2912    /// A closed hand cursor
2913    /// corresponds to the CSS cursor value `grabbing`
2914    ClosedHand,
2915
2916    /// An open hand cursor
2917    /// corresponds to the CSS cursor value `grab`
2918    OpenHand,
2919
2920    /// A pointing hand cursor
2921    /// corresponds to the CSS cursor value `pointer`
2922    PointingHand,
2923
2924    /// A resize left cursor
2925    /// corresponds to the CSS cursor value `w-resize`
2926    ResizeLeft,
2927
2928    /// A resize right cursor
2929    /// corresponds to the CSS cursor value `e-resize`
2930    ResizeRight,
2931
2932    /// A resize cursor to the left and right
2933    /// corresponds to the CSS cursor value `ew-resize`
2934    ResizeLeftRight,
2935
2936    /// A resize up cursor
2937    /// corresponds to the CSS cursor value `n-resize`
2938    ResizeUp,
2939
2940    /// A resize down cursor
2941    /// corresponds to the CSS cursor value `s-resize`
2942    ResizeDown,
2943
2944    /// A resize cursor directing up and down
2945    /// corresponds to the CSS cursor value `ns-resize`
2946    ResizeUpDown,
2947
2948    /// A resize cursor directing up-left and down-right
2949    /// corresponds to the CSS cursor value `nesw-resize`
2950    ResizeUpLeftDownRight,
2951
2952    /// A resize cursor directing up-right and down-left
2953    /// corresponds to the CSS cursor value `nwse-resize`
2954    ResizeUpRightDownLeft,
2955
2956    /// A cursor indicating that the item/column can be resized horizontally.
2957    /// corresponds to the CSS cursor value `col-resize`
2958    ResizeColumn,
2959
2960    /// A cursor indicating that the item/row can be resized vertically.
2961    /// corresponds to the CSS cursor value `row-resize`
2962    ResizeRow,
2963
2964    /// A text input cursor for vertical layout
2965    /// corresponds to the CSS cursor value `vertical-text`
2966    IBeamCursorForVerticalLayout,
2967
2968    /// A cursor indicating that the operation is not allowed
2969    /// corresponds to the CSS cursor value `not-allowed`
2970    OperationNotAllowed,
2971
2972    /// A cursor indicating that the operation will result in a link
2973    /// corresponds to the CSS cursor value `alias`
2974    DragLink,
2975
2976    /// A cursor indicating that the operation will result in a copy
2977    /// corresponds to the CSS cursor value `copy`
2978    DragCopy,
2979
2980    /// A cursor indicating that the operation will result in a context menu
2981    /// corresponds to the CSS cursor value `context-menu`
2982    ContextualMenu,
2983}
2984
2985/// A clipboard item that should be copied to the clipboard
2986#[derive(Clone, Debug, Eq, PartialEq)]
2987pub struct ClipboardItem {
2988    /// The entries in this clipboard item.
2989    pub entries: Vec<ClipboardEntry>,
2990}
2991
2992/// An error produced by [`Platform::read_from_clipboard_async`].
2993///
2994/// Callers surface these failures to users, so the variants distinguish
2995/// conditions that call for different user-facing guidance.
2996#[derive(Clone, Debug, PartialEq, Eq)]
2997pub enum ClipboardReadError {
2998    /// The platform clipboard is not available in this context, e.g. the
2999    /// browser does not expose the async clipboard API or the page is not a
3000    /// secure context.
3001    Unavailable,
3002    /// The platform refused access, e.g. the user declined the browser's
3003    /// clipboard permission prompt or paste confirmation.
3004    Denied(String),
3005    /// The clipboard contents could not be converted into a
3006    /// [`ClipboardItem`].
3007    UnsupportedContent,
3008}
3009
3010impl std::fmt::Display for ClipboardReadError {
3011    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3012        match self {
3013            Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3014            Self::Denied(message) => {
3015                write!(formatter, "clipboard access was denied: {message}")
3016            }
3017            Self::UnsupportedContent => {
3018                formatter.write_str("the clipboard contents are unsupported")
3019            }
3020        }
3021    }
3022}
3023
3024impl std::error::Error for ClipboardReadError {}
3025
3026/// Either a ClipboardString or a ClipboardImage
3027#[derive(Clone, Debug, Eq, PartialEq)]
3028pub enum ClipboardEntry {
3029    /// A string entry
3030    String(ClipboardString),
3031    /// An image entry
3032    Image(Image),
3033    /// A file entry
3034    ExternalPaths(crate::ExternalPaths),
3035}
3036
3037impl ClipboardItem {
3038    /// Create a new ClipboardItem::String with no associated metadata
3039    pub fn new_string(text: String) -> Self {
3040        Self {
3041            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3042        }
3043    }
3044
3045    /// Create a new ClipboardItem::String with the given text and associated metadata
3046    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3047        Self {
3048            entries: vec![ClipboardEntry::String(ClipboardString {
3049                text,
3050                metadata: Some(metadata),
3051            })],
3052        }
3053    }
3054
3055    /// Create a new ClipboardItem::String with the given text and associated metadata
3056    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3057        Self {
3058            entries: vec![ClipboardEntry::String(
3059                ClipboardString::new(text).with_json_metadata(metadata),
3060            )],
3061        }
3062    }
3063
3064    /// Create a new ClipboardItem::Image with the given image with no associated metadata
3065    pub fn new_image(image: &Image) -> Self {
3066        Self {
3067            entries: vec![ClipboardEntry::Image(image.clone())],
3068        }
3069    }
3070
3071    /// Concatenates together all the ClipboardString entries in the item.
3072    /// Returns None if there were no ClipboardString entries.
3073    pub fn text(&self) -> Option<String> {
3074        let mut answer = String::new();
3075
3076        for entry in self.entries.iter() {
3077            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3078                answer.push_str(text);
3079            }
3080        }
3081
3082        if answer.is_empty() {
3083            for entry in self.entries.iter() {
3084                if let ClipboardEntry::ExternalPaths(paths) = entry {
3085                    for path in &paths.0 {
3086                        use std::fmt::Write as _;
3087                        _ = write!(answer, "{}", path.display());
3088                    }
3089                }
3090            }
3091        }
3092
3093        if !answer.is_empty() {
3094            Some(answer)
3095        } else {
3096            None
3097        }
3098    }
3099
3100    /// If this item is one ClipboardEntry::String, returns its metadata.
3101    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3102    pub fn metadata(&self) -> Option<&String> {
3103        match self.entries().first() {
3104            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3105                clipboard_string.metadata.as_ref()
3106            }
3107            _ => None,
3108        }
3109    }
3110
3111    /// Get the item's entries
3112    pub fn entries(&self) -> &[ClipboardEntry] {
3113        &self.entries
3114    }
3115
3116    /// Get owned versions of the item's entries
3117    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3118        self.entries.into_iter()
3119    }
3120}
3121
3122impl From<ClipboardString> for ClipboardEntry {
3123    fn from(value: ClipboardString) -> Self {
3124        Self::String(value)
3125    }
3126}
3127
3128impl From<String> for ClipboardEntry {
3129    fn from(value: String) -> Self {
3130        Self::from(ClipboardString::from(value))
3131    }
3132}
3133
3134impl From<Image> for ClipboardEntry {
3135    fn from(value: Image) -> Self {
3136        Self::Image(value)
3137    }
3138}
3139
3140impl From<ClipboardEntry> for ClipboardItem {
3141    fn from(value: ClipboardEntry) -> Self {
3142        Self {
3143            entries: vec![value],
3144        }
3145    }
3146}
3147
3148impl From<String> for ClipboardItem {
3149    fn from(value: String) -> Self {
3150        Self::from(ClipboardEntry::from(value))
3151    }
3152}
3153
3154impl From<Image> for ClipboardItem {
3155    fn from(value: Image) -> Self {
3156        Self::from(ClipboardEntry::from(value))
3157    }
3158}
3159
3160/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
3161#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3162pub enum ImageFormat {
3163    // Sorted from most to least likely to be pasted into an editor,
3164    // which matters when we iterate through them trying to see if
3165    // clipboard content matches them.
3166    /// .png
3167    Png,
3168    /// .jpeg or .jpg
3169    Jpeg,
3170    /// .webp
3171    Webp,
3172    /// .gif
3173    Gif,
3174    /// .svg
3175    Svg,
3176    /// .bmp
3177    Bmp,
3178    /// .tif or .tiff
3179    Tiff,
3180    /// .ico
3181    Ico,
3182    /// Netpbm image formats (.pbm, .ppm, .pgm).
3183    Pnm,
3184}
3185
3186impl ImageFormat {
3187    /// Returns the mime type for the ImageFormat
3188    pub const fn mime_type(self) -> &'static str {
3189        match self {
3190            ImageFormat::Png => "image/png",
3191            ImageFormat::Jpeg => "image/jpeg",
3192            ImageFormat::Webp => "image/webp",
3193            ImageFormat::Gif => "image/gif",
3194            ImageFormat::Svg => "image/svg+xml",
3195            ImageFormat::Bmp => "image/bmp",
3196            ImageFormat::Tiff => "image/tiff",
3197            ImageFormat::Ico => "image/ico",
3198            ImageFormat::Pnm => "image/x-portable-anymap",
3199        }
3200    }
3201
3202    /// Returns the file extension for this image format (without leading dot).
3203    pub const fn extension(self) -> &'static str {
3204        match self {
3205            ImageFormat::Png => "png",
3206            ImageFormat::Jpeg => "jpg",
3207            ImageFormat::Webp => "webp",
3208            ImageFormat::Gif => "gif",
3209            ImageFormat::Svg => "svg",
3210            ImageFormat::Bmp => "bmp",
3211            ImageFormat::Tiff => "tiff",
3212            ImageFormat::Ico => "ico",
3213            ImageFormat::Pnm => "pnm",
3214        }
3215    }
3216
3217    /// Returns the ImageFormat for the given mime type, including known aliases.
3218    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3219        use strum::IntoEnumIterator;
3220        Self::iter()
3221            .find(|format| format.mime_type() == mime_type)
3222            .or_else(|| Self::from_mime_type_alias(mime_type))
3223    }
3224
3225    /// Non-canonical mime types that some producers use in the wild.
3226    /// Unlike `mime_type()` which returns the single canonical form,
3227    /// these are legacy or shortened variants we still need to recognize.
3228    fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3229        match mime_type {
3230            "image/jpg" => Some(Self::Jpeg),
3231            "image/tif" => Some(Self::Tiff),
3232            _ => None,
3233        }
3234    }
3235}
3236
3237/// An image, with a format and certain bytes
3238#[derive(Clone, Debug, PartialEq, Eq)]
3239pub struct Image {
3240    /// The image format the bytes represent (e.g. PNG)
3241    pub format: ImageFormat,
3242    /// The raw image bytes
3243    pub bytes: Vec<u8>,
3244    /// The unique ID for the image
3245    pub id: u64,
3246}
3247
3248pub(crate) fn decode_static_image(
3249    bytes: &[u8],
3250    format: image::ImageFormat,
3251) -> Result<SmallVec<[Frame; 1]>> {
3252    let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3253        .into_decoder()
3254        .context("creating image decoder")?;
3255    decode_static_image_from_decoder(decoder)
3256}
3257
3258pub(crate) fn decode_static_image_from_decoder(
3259    mut decoder: impl image::ImageDecoder,
3260) -> Result<SmallVec<[Frame; 1]>> {
3261    let orientation = decoder
3262        .orientation()
3263        .context("reading decoder's orientation")?;
3264    let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3265    image.apply_orientation(orientation);
3266
3267    let mut data = image.into_rgba8();
3268    for pixel in data.chunks_exact_mut(4) {
3269        pixel.swap(0, 2);
3270    }
3271
3272    Ok(SmallVec::from_elem(Frame::new(data), 1))
3273}
3274
3275impl Hash for Image {
3276    fn hash<H: Hasher>(&self, state: &mut H) {
3277        state.write_u64(self.id);
3278    }
3279}
3280
3281impl Image {
3282    /// An empty image containing no data
3283    pub fn empty() -> Self {
3284        Self::from_bytes(ImageFormat::Png, Vec::new())
3285    }
3286
3287    /// Create an image from a format and bytes
3288    pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3289        Self {
3290            id: hash(&bytes),
3291            format,
3292            bytes,
3293        }
3294    }
3295
3296    /// Get this image's ID
3297    pub fn id(&self) -> u64 {
3298        self.id
3299    }
3300
3301    /// Use the GPUI `use_asset` API to make this image renderable
3302    pub fn use_render_image(
3303        self: Arc<Self>,
3304        window: &mut Window,
3305        cx: &mut App,
3306    ) -> Option<Arc<RenderImage>> {
3307        ImageSource::Image(self)
3308            .use_data(None, window, cx)
3309            .and_then(|result| result.ok())
3310    }
3311
3312    /// Use the GPUI `get_asset` API to make this image renderable
3313    pub fn get_render_image(
3314        self: Arc<Self>,
3315        window: &mut Window,
3316        cx: &mut App,
3317    ) -> Option<Arc<RenderImage>> {
3318        ImageSource::Image(self)
3319            .get_data(None, window, cx)
3320            .and_then(|result| result.ok())
3321    }
3322
3323    /// Use the GPUI `remove_asset` API to drop this image, if possible.
3324    pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3325        ImageSource::Image(self).remove_asset(cx);
3326    }
3327
3328    /// Check whether this image is present in GPUI's asset cache (loading or
3329    /// loaded), without fetching it.
3330    #[cfg(any(test, feature = "test-support"))]
3331    pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3332        ImageSource::Image(self.clone()).is_asset_cached(cx)
3333    }
3334
3335    /// Convert the clipboard image to an `ImageData` object.
3336    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3337        let frames = match self.format {
3338            ImageFormat::Gif => {
3339                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
3340                let mut frames = SmallVec::new();
3341
3342                for frame in decoder.into_frames() {
3343                    match frame {
3344                        Ok(mut frame) => {
3345                            // Convert from RGBA to BGRA.
3346                            for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3347                                pixel.swap(0, 2);
3348                            }
3349                            frames.push(frame);
3350                        }
3351                        Err(err) => {
3352                            log::debug!("Skipping GIF frame due to decode error: {err}");
3353                        }
3354                    }
3355                }
3356
3357                if frames.is_empty() {
3358                    anyhow::bail!("GIF could not be decoded: all frames failed");
3359                }
3360
3361                frames
3362            }
3363            ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3364            ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3365            ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
3366            ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3367            ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3368            ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3369            ImageFormat::Svg => {
3370                return svg_renderer
3371                    .render_single_frame(&self.bytes, 1.0)
3372                    .map_err(Into::into);
3373            }
3374            ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3375        };
3376
3377        Ok(Arc::new(RenderImage::new(frames)))
3378    }
3379
3380    /// Get the format of the clipboard image
3381    pub fn format(&self) -> ImageFormat {
3382        self.format
3383    }
3384
3385    /// Get the raw bytes of the clipboard image
3386    pub fn bytes(&self) -> &[u8] {
3387        self.bytes.as_slice()
3388    }
3389}
3390
3391/// A clipboard item that should be copied to the clipboard
3392#[derive(Clone, Debug, Eq, PartialEq)]
3393pub struct ClipboardString {
3394    /// The text content.
3395    pub text: String,
3396    /// Optional metadata associated with this clipboard string.
3397    pub metadata: Option<String>,
3398}
3399
3400impl ClipboardString {
3401    /// Create a new clipboard string with the given text
3402    pub fn new(text: String) -> Self {
3403        Self {
3404            text,
3405            metadata: None,
3406        }
3407    }
3408
3409    /// Return a new clipboard item with the metadata replaced by the given metadata,
3410    /// after serializing it as JSON.
3411    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3412        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3413        self
3414    }
3415
3416    /// Get the text of the clipboard string
3417    pub fn text(&self) -> &String {
3418        &self.text
3419    }
3420
3421    /// Get the owned text of the clipboard string
3422    pub fn into_text(self) -> String {
3423        self.text
3424    }
3425
3426    /// Get the metadata of the clipboard string, formatted as JSON
3427    pub fn metadata_json<T>(&self) -> Option<T>
3428    where
3429        T: for<'a> Deserialize<'a>,
3430    {
3431        self.metadata
3432            .as_ref()
3433            .and_then(|m| serde_json::from_str(m).ok())
3434    }
3435
3436    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3437    /// Compute a hash of the given text for clipboard change detection.
3438    pub fn text_hash(text: &str) -> u64 {
3439        let mut hasher = SeaHasher::new();
3440        text.hash(&mut hasher);
3441        hasher.finish()
3442    }
3443}
3444
3445impl From<String> for ClipboardString {
3446    fn from(value: String) -> Self {
3447        Self {
3448            text: value,
3449            metadata: None,
3450        }
3451    }
3452}
3453
3454#[cfg(test)]
3455mod image_tests {
3456    use super::*;
3457    use std::sync::Arc;
3458
3459    #[test]
3460    fn test_image_to_image_data_applies_exif_orientation() {
3461        let image = Image::from_bytes(
3462            ImageFormat::Jpeg,
3463            include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3464        );
3465
3466        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3467
3468        assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3469
3470        let bytes = render_image.as_bytes(0).unwrap();
3471        assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3472        assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3473    }
3474
3475    #[test]
3476    fn test_svg_image_to_image_data_converts_to_bgra() {
3477        let image = Image::from_bytes(
3478            ImageFormat::Svg,
3479            br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3480<rect width="1" height="1" fill="#38BDF8"/>
3481</svg>"##
3482                .to_vec(),
3483        );
3484
3485        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3486        let bytes = render_image.as_bytes(0).unwrap();
3487
3488        for pixel in bytes.chunks_exact(4) {
3489            assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3490        }
3491    }
3492}
3493
3494#[cfg(test)]
3495mod atlas_tests {
3496    use super::*;
3497
3498    const TILE_SIZE: Size<DevicePixels> = Size {
3499        width: DevicePixels(1),
3500        height: DevicePixels(1),
3501    };
3502
3503    #[derive(Default)]
3504    struct RecordingAtlasBackend {
3505        insert_calls: u32,
3506        fail_next_insert: bool,
3507        removed_tiles: Vec<AtlasTile>,
3508    }
3509
3510    impl AtlasBackend for RecordingAtlasBackend {
3511        fn insert(
3512            &mut self,
3513            kind: AtlasTextureKind,
3514            size: Size<DevicePixels>,
3515            _bytes: &[u8],
3516        ) -> Result<AtlasTile> {
3517            self.insert_calls += 1;
3518            if std::mem::take(&mut self.fail_next_insert) {
3519                anyhow::bail!("backend failed");
3520            }
3521            Ok(AtlasTile {
3522                texture_id: AtlasTextureId { index: 0, kind },
3523                tile_id: TileId(self.insert_calls),
3524                padding: 0,
3525                bounds: Bounds {
3526                    origin: Point::default(),
3527                    size,
3528                },
3529            })
3530        }
3531
3532        fn remove(&mut self, tile: AtlasTile) {
3533            self.removed_tiles.push(tile);
3534        }
3535    }
3536
3537    fn image_key(image_id: usize) -> AtlasKey {
3538        AtlasKey::Image(RenderImageParams {
3539            image_id: crate::ImageId(image_id),
3540            frame_index: 0,
3541        })
3542    }
3543
3544    fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3545        Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3546    }
3547
3548    #[test]
3549    fn only_successful_inserts_are_cached() -> Result<()> {
3550        let mut state = AtlasState::new(RecordingAtlasBackend::default());
3551        let key = image_key(1);
3552
3553        assert_eq!(
3554            state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3555            None
3556        );
3557        state
3558            .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3559            .expect_err("builder error should propagate");
3560        assert!(!state.contains(&key));
3561        assert_eq!(state.backend.insert_calls, 0);
3562
3563        state.backend.fail_next_insert = true;
3564        state
3565            .get_or_insert_with(key.clone(), &mut build_tile)
3566            .expect_err("backend error should propagate");
3567        assert!(!state.contains(&key));
3568        assert_eq!(state.backend.insert_calls, 1);
3569
3570        let tile = state
3571            .get_or_insert_with(key.clone(), &mut build_tile)?
3572            .context("builder should produce a tile")?;
3573        assert_eq!(tile.texture_id.kind, key.texture_kind());
3574        assert_eq!(
3575            state.get_or_insert_with(key.clone(), &mut || {
3576                anyhow::bail!("cache hit must not call the builder")
3577            })?,
3578            Some(tile)
3579        );
3580        assert!(state.contains(&key));
3581        assert_eq!(state.backend.insert_calls, 2);
3582        Ok(())
3583    }
3584
3585    #[test]
3586    fn remove_and_clear_invalidate_keys() -> Result<()> {
3587        let mut state = AtlasState::new(RecordingAtlasBackend::default());
3588        let key = image_key(1);
3589        let other_key = image_key(2);
3590        let tile = state
3591            .get_or_insert_with(key.clone(), &mut build_tile)?
3592            .context("builder should produce a tile")?;
3593        state
3594            .get_or_insert_with(other_key.clone(), &mut build_tile)?
3595            .context("builder should produce another tile")?;
3596
3597        state.remove(&key);
3598        state.remove(&key);
3599        assert!(!state.contains(&key));
3600        assert!(state.contains(&other_key));
3601        assert_eq!(state.backend.removed_tiles, vec![tile]);
3602
3603        let mut reset_calls = 0;
3604        state.clear(|_| reset_calls += 1);
3605        assert_eq!(reset_calls, 1);
3606        assert!(!state.contains(&other_key));
3607        assert_eq!(state.backend.removed_tiles, vec![tile]);
3608        Ok(())
3609    }
3610}
3611
3612#[cfg(test)]
3613mod frame_signal_tests {
3614    use super::*;
3615
3616    #[cfg(feature = "profiler")]
3617    #[test]
3618    fn coalesced_signals_retain_the_earliest_until_drained() {
3619        for (first_source, later_source) in [
3620            (
3621                FrameRequestSource::NativeCallback,
3622                FrameRequestSource::LocalSchedule,
3623            ),
3624            (
3625                FrameRequestSource::LocalSchedule,
3626                FrameRequestSource::NativeCallback,
3627            ),
3628        ] {
3629            let signal = PlatformFrameSignal::new();
3630            let first =
3631                PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3632            assert_eq!(signal.take(), None);
3633            signal.record(first + Duration::from_millis(16), later_source);
3634            signal.record(first, first_source);
3635            signal.record(first + Duration::from_millis(32), later_source);
3636            assert_eq!(signal.take(), Some((first, first_source)));
3637            assert_eq!(signal.take(), None);
3638            let next = first + Duration::from_millis(48);
3639            signal.record(next, later_source);
3640            assert_eq!(signal.take(), Some((next, later_source)));
3641        }
3642    }
3643
3644    #[cfg(not(feature = "profiler"))]
3645    #[test]
3646    fn disabled_profiling_does_not_capture_or_store_timestamps() {
3647        let captured = PlatformFrameSignal::capture(|| {
3648            panic!("profiler-disabled builds must not evaluate the capture closure");
3649        });
3650        assert_eq!(captured, None);
3651        let signal = PlatformFrameSignal::new();
3652        signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3653        assert_eq!(signal.take(), None);
3654    }
3655}
3656
3657#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3658mod tests {
3659    use super::*;
3660    use std::collections::HashSet;
3661
3662    #[test]
3663    fn test_refresh_interval_from_hz() {
3664        assert_eq!(
3665            refresh_interval_from_hz(50.0),
3666            Some(Duration::from_millis(20))
3667        );
3668        assert_eq!(
3669            refresh_interval_from_hz(120.0),
3670            Some(Duration::from_secs(1) / 120)
3671        );
3672        for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
3673            assert_eq!(refresh_interval_from_hz(unknown), None);
3674        }
3675    }
3676
3677    #[test]
3678    fn test_window_button_layout_parse_standard() {
3679        let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3680        assert_eq!(
3681            layout.left,
3682            [
3683                Some(WindowButton::Close),
3684                Some(WindowButton::Minimize),
3685                None
3686            ]
3687        );
3688        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3689    }
3690
3691    #[test]
3692    fn test_window_button_layout_parse_right_only() {
3693        let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3694        assert_eq!(layout.left, [None, None, None]);
3695        assert_eq!(
3696            layout.right,
3697            [
3698                Some(WindowButton::Minimize),
3699                Some(WindowButton::Maximize),
3700                Some(WindowButton::Close)
3701            ]
3702        );
3703    }
3704
3705    #[test]
3706    fn test_window_button_layout_parse_left_only() {
3707        let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3708        assert_eq!(
3709            layout.left,
3710            [
3711                Some(WindowButton::Close),
3712                Some(WindowButton::Minimize),
3713                Some(WindowButton::Maximize)
3714            ]
3715        );
3716        assert_eq!(layout.right, [None, None, None]);
3717    }
3718
3719    #[test]
3720    fn test_window_button_layout_parse_with_whitespace() {
3721        let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3722        assert_eq!(
3723            layout.left,
3724            [
3725                Some(WindowButton::Close),
3726                Some(WindowButton::Minimize),
3727                None
3728            ]
3729        );
3730        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3731    }
3732
3733    #[test]
3734    fn test_window_button_layout_parse_empty() {
3735        let layout = WindowButtonLayout::parse("").unwrap();
3736        assert_eq!(layout.left, [None, None, None]);
3737        assert_eq!(layout.right, [None, None, None]);
3738    }
3739
3740    #[test]
3741    fn test_window_button_layout_parse_intentionally_empty() {
3742        let layout = WindowButtonLayout::parse(":").unwrap();
3743        assert_eq!(layout.left, [None, None, None]);
3744        assert_eq!(layout.right, [None, None, None]);
3745    }
3746
3747    #[test]
3748    fn test_window_button_layout_parse_invalid_buttons() {
3749        let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
3750        assert_eq!(
3751            layout.left,
3752            [
3753                Some(WindowButton::Close),
3754                Some(WindowButton::Minimize),
3755                None
3756            ]
3757        );
3758        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3759    }
3760
3761    #[test]
3762    fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
3763        let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
3764        assert_eq!(
3765            layout.right,
3766            [
3767                Some(WindowButton::Close),
3768                Some(WindowButton::Minimize),
3769                None
3770            ]
3771        );
3772        assert_eq!(layout.format(), ":close,minimize");
3773    }
3774
3775    #[test]
3776    fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
3777        let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
3778        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3779        assert_eq!(
3780            layout.right,
3781            [
3782                Some(WindowButton::Maximize),
3783                Some(WindowButton::Minimize),
3784                None
3785            ]
3786        );
3787
3788        let button_ids: Vec<_> = layout
3789            .left
3790            .iter()
3791            .chain(layout.right.iter())
3792            .flatten()
3793            .map(WindowButton::id)
3794            .collect();
3795        let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
3796        assert_eq!(unique_button_ids.len(), button_ids.len());
3797        assert_eq!(layout.format(), "close:maximize,minimize");
3798    }
3799
3800    #[test]
3801    fn test_window_button_layout_parse_gnome_style() {
3802        let layout = WindowButtonLayout::parse("close").unwrap();
3803        assert_eq!(layout.left, [None, None, None]);
3804        assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
3805    }
3806
3807    #[test]
3808    fn test_window_button_layout_parse_elementary_style() {
3809        let layout = WindowButtonLayout::parse("close:maximize").unwrap();
3810        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3811        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3812    }
3813
3814    #[test]
3815    fn test_window_button_layout_round_trip() {
3816        let cases = [
3817            "close:minimize,maximize",
3818            "minimize,maximize,close:",
3819            ":close",
3820            "close:",
3821            "close:maximize",
3822            ":",
3823        ];
3824
3825        for case in cases {
3826            let layout = WindowButtonLayout::parse(case).unwrap();
3827            assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
3828        }
3829    }
3830
3831    #[test]
3832    fn test_window_button_layout_linux_default() {
3833        let layout = WindowButtonLayout::linux_default();
3834        assert_eq!(layout.left, [None, None, None]);
3835        assert_eq!(
3836            layout.right,
3837            [
3838                Some(WindowButton::Minimize),
3839                Some(WindowButton::Maximize),
3840                Some(WindowButton::Close)
3841            ]
3842        );
3843
3844        let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
3845        assert_eq!(round_tripped, layout);
3846    }
3847
3848    #[test]
3849    fn test_window_button_layout_parse_all_invalid() {
3850        assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
3851    }
3852}