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