Skip to main content

gpui/
platform.rs

1mod app_menu;
2mod keyboard;
3mod keystroke;
4
5#[cfg(all(target_os = "linux", feature = "wayland"))]
6#[expect(missing_docs)]
7pub mod layer_shell;
8
9/// Types for configuring parent-anchored popup windows such as menus, dropdowns and tooltips.
10pub mod popup;
11
12#[cfg(any(test, feature = "bench"))]
13mod bench_dispatcher;
14
15#[cfg(any(test, feature = "test-support"))]
16mod test;
17
18#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
19mod visual_test;
20
21#[cfg(all(
22    feature = "screen-capture",
23    any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
24))]
25pub mod scap_screen_capture;
26
27#[cfg(all(
28    any(target_os = "windows", target_os = "linux"),
29    feature = "screen-capture"
30))]
31pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
32#[cfg(not(feature = "screen-capture"))]
33pub(crate) type PlatformScreenCaptureFrame = ();
34#[cfg(all(target_os = "macos", feature = "screen-capture"))]
35pub(crate) type PlatformScreenCaptureFrame = core_video::image_buffer::CVImageBuffer;
36
37use crate::{
38    Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
39    DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
40    FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap,
41    LineLayout, Pixels, PlatformGestures, PlatformInput, Point, Priority, RenderGlyphParams,
42    RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString,
43    Size, SvgRenderer, SystemWindowTab, Task, Window, WindowControlArea, hash, point, px, size,
44};
45#[cfg(any(target_os = "linux", target_os = "freebsd"))]
46use anyhow::bail;
47use anyhow::{Context as _, Result};
48use async_task::Runnable;
49use futures::channel::oneshot;
50#[cfg(any(test, feature = "test-support"))]
51use image::RgbaImage;
52use image::codecs::gif::GifDecoder;
53use image::{AnimationDecoder as _, DynamicImage, Frame};
54use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
55use scheduler::Instant;
56pub use scheduler::RunnableMeta;
57use schemars::JsonSchema;
58use seahash::SeaHasher;
59use serde::{Deserialize, Serialize};
60use smallvec::SmallVec;
61use std::borrow::Cow;
62use std::hash::{Hash, Hasher};
63use std::io::Cursor;
64use std::ops;
65use std::time::Duration;
66use std::{
67    fmt::{self, Debug},
68    ops::Range,
69    path::{Path, PathBuf},
70    rc::Rc,
71    sync::Arc,
72};
73use strum::EnumIter;
74use uuid::Uuid;
75
76pub use app_menu::*;
77pub use keyboard::*;
78pub use keystroke::*;
79
80#[cfg(any(test, feature = "test-support"))]
81pub(crate) use test::*;
82
83#[cfg(any(test, feature = "test-support"))]
84pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
85
86#[cfg(any(test, feature = "bench"))]
87pub use bench_dispatcher::BenchDispatcher;
88
89#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
90pub use visual_test::VisualTestPlatform;
91
92// TODO(jk): return an enum instead of a string
93/// Return which compositor we're guessing we'll use.
94/// Does not attempt to connect to the given compositor.
95#[cfg(any(target_os = "linux", target_os = "freebsd"))]
96#[inline]
97pub fn guess_compositor() -> &'static str {
98    if std::env::var_os("ZED_HEADLESS").is_some() {
99        return "Headless";
100    }
101
102    #[cfg(feature = "wayland")]
103    let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
104    #[cfg(not(feature = "wayland"))]
105    let wayland_display: Option<std::ffi::OsString> = None;
106
107    #[cfg(feature = "x11")]
108    let x11_display = std::env::var_os("DISPLAY");
109    #[cfg(not(feature = "x11"))]
110    let x11_display: Option<std::ffi::OsString> = None;
111
112    let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
113    let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
114
115    if use_wayland {
116        "Wayland"
117    } else if use_x11 {
118        "X11"
119    } else {
120        "Headless"
121    }
122}
123
124#[expect(missing_docs)]
125pub trait Platform: 'static {
126    fn background_executor(&self) -> BackgroundExecutor;
127    fn foreground_executor(&self) -> ForegroundExecutor;
128    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
129
130    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
131    fn quit(&self);
132    fn restart(&self, binary_path: Option<PathBuf>);
133    fn activate(&self, ignoring_other_apps: bool);
134    fn hide(&self);
135    fn hide_other_apps(&self);
136    fn unhide_other_apps(&self);
137
138    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
139    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
140    fn active_window(&self) -> Option<AnyWindowHandle>;
141    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
142        None
143    }
144
145    fn is_screen_capture_supported(&self) -> bool {
146        false
147    }
148
149    fn screen_capture_sources(
150        &self,
151    ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
152        let (sources_tx, sources_rx) = oneshot::channel();
153        sources_tx
154            .send(Err(anyhow::anyhow!(
155                "gpui was compiled without the screen-capture feature"
156            )))
157            .ok();
158        sources_rx
159    }
160
161    fn open_window(
162        &self,
163        handle: AnyWindowHandle,
164        options: WindowParams,
165    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
166
167    /// Returns the appearance of the application's windows.
168    fn window_appearance(&self) -> WindowAppearance;
169
170    /// Overrides the appearance (light/dark) applied to the app's windows, independent
171    /// of the OS-wide setting. Pass `None` to clear the override and follow the system
172    /// again. The override is reflected by [`Platform::window_appearance`].
173    ///
174    /// Currently only implemented on macOS, where it sets `NSApplication.appearance` so
175    /// the native window chrome (the window border and titlebar) of every window matches
176    /// a dark app theme even when the system is in light mode (or vice versa). A no-op on
177    /// other platforms.
178    fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
179
180    /// Returns the window button layout configuration when supported.
181    fn button_layout(&self) -> Option<WindowButtonLayout> {
182        None
183    }
184
185    fn open_url(&self, url: &str);
186    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
187    fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
188
189    fn prompt_for_paths(
190        &self,
191        options: PathPromptOptions,
192    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
193    fn prompt_for_new_path(
194        &self,
195        directory: &Path,
196        suggested_name: Option<&str>,
197    ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
198    fn can_select_mixed_files_and_dirs(&self) -> bool;
199    fn reveal_path(&self, path: &Path);
200    fn open_with_system(&self, path: &Path);
201
202    fn on_quit(&self, callback: Box<dyn FnMut()>);
203    fn on_reopen(&self, callback: Box<dyn FnMut()>);
204    fn on_system_wake(&self, callback: Box<dyn FnMut()>);
205
206    // Mobile platform methods. On mobile the OS owns the application
207    // lifecycle: apps are backgrounded, foregrounded, and killed at the
208    // system's discretion, and must react rather than decide.
209
210    /// Registers a callback invoked whenever the application's lifecycle
211    /// phase changes. See [`AppLifecyclePhase`] for the phase vocabulary and
212    /// its mapping onto iOS and Android.
213    ///
214    /// Desktop platforms never invoke this.
215    fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
216
217    /// Registers a callback invoked when the OS signals memory pressure
218    /// (iOS `didReceiveMemoryWarning`, Android `onTrimMemory`).
219    ///
220    /// Desktop platforms never invoke this.
221    fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
222
223    /// The platform's gesture recognition services, if it provides any
224    /// beyond gpui's portable recognizers. See
225    /// [`PlatformGestures`](crate::PlatformGestures).
226    fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
227        None
228    }
229
230    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
231    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
232        None
233    }
234
235    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
236    fn perform_dock_menu_action(&self, _action: usize) {}
237    fn add_recent_document(&self, _path: &Path) {}
238    fn update_jump_list(
239        &self,
240        _menus: Vec<MenuItem>,
241        _entries: Vec<SmallVec<[PathBuf; 2]>>,
242    ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
243        Task::ready(Vec::new())
244    }
245    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
246    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
247    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
248
249    fn thermal_state(&self) -> ThermalState;
250    fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
251
252    /// Sets the application's process-wide identity and user-visible name.
253    ///
254    /// The identifier is used for platform identity mechanisms such as the
255    /// Windows AppUserModelID. The name is used wherever the operating system
256    /// presents the application to the user. Call this once, early in startup,
257    /// before opening windows or posting notifications.
258    fn set_app_identity(&self, identifier: &str, name: &str) {
259        _ = (identifier, name);
260    }
261
262    /// Posts a notification to the operating system's notification center.
263    ///
264    /// Posting a notification whose [`SystemNotification::tag`] matches an
265    /// earlier one replaces that notification where the platform supports it.
266    /// No-op on platforms without notification support, or when delivery is
267    /// unavailable (e.g. authorization was denied).
268    fn show_system_notification(&self, notification: SystemNotification) {
269        _ = notification;
270    }
271
272    /// Removes the delivered or pending notification with this tag.
273    ///
274    /// Best-effort: some platforms cannot retract a notification once shown,
275    /// in which case it ages out of the notification center on its own.
276    fn dismiss_system_notification(&self, tag: &str) {
277        _ = tag;
278    }
279
280    /// Registers the callback invoked when the user activates a system
281    /// notification, either by clicking its body or one of its action
282    /// buttons.
283    ///
284    /// Implementations must invoke the callback on the main thread.
285    fn on_system_notification_response(
286        &self,
287        callback: Box<dyn FnMut(SystemNotificationResponse)>,
288    ) {
289        _ = callback;
290    }
291
292    fn compositor_name(&self) -> &'static str {
293        ""
294    }
295    fn app_path(&self) -> Result<PathBuf>;
296    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
297
298    fn set_cursor_style(&self, style: CursorStyle);
299
300    /// Hides the mouse cursor until the user moves the mouse over one of
301    /// this application's windows.
302    fn hide_cursor_until_mouse_moves(&self);
303
304    /// Returns whether the mouse cursor is currently visible.
305    fn is_cursor_visible(&self) -> bool;
306
307    fn should_auto_hide_scrollbars(&self) -> bool;
308
309    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
310    /// Reads clipboard text without waiting for native data transfer on the UI thread.
311    /// Custom backends retain the synchronous fallback unless they override this method.
312    fn read_text_from_clipboard_async(&self) -> Task<Option<String>> {
313        Task::ready(
314            self.read_from_clipboard()
315                .and_then(|item| item.plain_text()),
316        )
317    }
318
319    fn write_to_clipboard(&self, item: ClipboardItem);
320
321    /// Whether this backend can publish file paths with the requested intent.
322    /// Availability at the time of the write is reported separately by the writer.
323    fn supports_file_clipboard(&self, _operation: FileClipboardOperation) -> bool {
324        false
325    }
326
327    /// Publishes files to the native clipboard without performing filesystem operations.
328    fn write_files_to_clipboard(
329        &self,
330        _paths: crate::ExternalPaths,
331        _operation: FileClipboardOperation,
332    ) -> std::result::Result<(), FileClipboardError> {
333        Err(FileClipboardError::Unsupported)
334    }
335
336    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
337    fn read_from_primary(&self) -> Option<ClipboardItem>;
338    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
339    fn write_to_primary(&self, item: ClipboardItem);
340
341    #[cfg(target_os = "macos")]
342    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
343    #[cfg(target_os = "macos")]
344    fn write_to_find_pasteboard(&self, item: ClipboardItem);
345
346    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
347    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
348    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
349
350    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
351    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
352    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
353}
354
355/// A handle to a platform's display, e.g. a monitor or laptop screen.
356pub trait PlatformDisplay: Debug {
357    /// Get the ID for this display
358    fn id(&self) -> DisplayId;
359
360    /// Returns a stable identifier for this display that can be persisted and used
361    /// across system restarts.
362    fn uuid(&self) -> Result<Uuid>;
363
364    /// Get the bounds for this display
365    fn bounds(&self) -> Bounds<Pixels>;
366
367    /// Get the visible bounds for this display, excluding taskbar/dock areas.
368    /// This is the usable area where windows can be placed without being obscured.
369    /// Defaults to the full display bounds if not overridden.
370    fn visible_bounds(&self) -> Bounds<Pixels> {
371        self.bounds()
372    }
373
374    /// Get the default bounds for this display to place a window
375    fn default_bounds(&self) -> Bounds<Pixels> {
376        let bounds = self.bounds();
377        let center = bounds.center();
378        let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
379
380        let offset = clipped_window_size / 2.0;
381        let origin = point(center.x - offset.width, center.y - offset.height);
382        Bounds::new(origin, clipped_window_size)
383    }
384}
385
386/// A notification posted to the operating system's notification center,
387/// rather than rendered as in-app UI.
388#[derive(Clone, Debug, PartialEq, Eq)]
389pub struct SystemNotification {
390    /// Stable identity for the notification. Posting a new notification with
391    /// the same tag replaces the previous one where the platform supports it,
392    /// and responses carry the tag back to the application.
393    pub tag: SharedString,
394    /// The notification's headline.
395    pub title: SharedString,
396    /// Additional text displayed below the title.
397    pub body: SharedString,
398    /// Buttons offered on the notification. Platforms that cannot display
399    /// action buttons show the notification without them.
400    pub actions: Vec<SystemNotificationAction>,
401}
402
403/// A button offered on a [`SystemNotification`].
404#[derive(Clone, Debug, PartialEq, Eq, Hash)]
405pub struct SystemNotificationAction {
406    /// Identifies the action in [`SystemNotificationResponse::action_id`]
407    /// when the user presses this button.
408    pub id: SharedString,
409    /// The button's user-visible label.
410    pub label: SharedString,
411}
412
413/// The user's activation of a [`SystemNotification`].
414#[derive(Clone, Debug, PartialEq, Eq)]
415pub struct SystemNotificationResponse {
416    /// The [`SystemNotification::tag`] of the activated notification.
417    pub tag: SharedString,
418    /// The pressed action button's [`SystemNotificationAction::id`], or
419    /// `None` when the user activated the notification body itself.
420    pub action_id: Option<SharedString>,
421}
422
423/// Thermal state of the system
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425pub enum ThermalState {
426    /// System has no thermal constraints
427    Nominal,
428    /// System is slightly constrained, reduce discretionary work
429    Fair,
430    /// System is moderately constrained, reduce CPU/GPU intensive work
431    Serious,
432    /// System is critically constrained, minimize all resource usage
433    Critical,
434}
435
436/// Metadata for a given [ScreenCaptureSource]
437#[derive(Clone)]
438pub struct SourceMetadata {
439    /// Opaque identifier of this screen.
440    pub id: u64,
441    /// Human-readable label for this source.
442    pub label: Option<SharedString>,
443    /// Whether this source is the main display.
444    pub is_main: Option<bool>,
445    /// Video resolution of this source.
446    pub resolution: Size<DevicePixels>,
447}
448
449/// A source of on-screen video content that can be captured.
450pub trait ScreenCaptureSource {
451    /// Returns metadata for this source.
452    fn metadata(&self) -> Result<SourceMetadata>;
453
454    /// Start capture video from this source, invoking the given callback
455    /// with each frame.
456    fn stream(
457        &self,
458        foreground_executor: &ForegroundExecutor,
459        frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
460    ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
461}
462
463/// A video stream captured from a screen.
464pub trait ScreenCaptureStream {
465    /// Returns metadata for this source.
466    fn metadata(&self) -> Result<SourceMetadata>;
467}
468
469/// A frame of video captured from a screen.
470pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
471
472/// An opaque identifier for a hardware display
473#[derive(PartialEq, Eq, Hash, Copy, Clone)]
474pub struct DisplayId(pub(crate) u64);
475
476impl DisplayId {
477    /// Create a new `DisplayId` from a raw platform display identifier.
478    pub fn new(id: u64) -> Self {
479        Self(id)
480    }
481}
482
483impl From<u64> for DisplayId {
484    fn from(id: u64) -> Self {
485        Self(id)
486    }
487}
488
489impl From<DisplayId> for u64 {
490    fn from(id: DisplayId) -> Self {
491        id.0
492    }
493}
494
495impl Debug for DisplayId {
496    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497        write!(f, "DisplayId({})", self.0)
498    }
499}
500
501/// Which part of the window to resize
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub enum ResizeEdge {
504    /// The top edge
505    Top,
506    /// The top right corner
507    TopRight,
508    /// The right edge
509    Right,
510    /// The bottom right corner
511    BottomRight,
512    /// The bottom edge
513    Bottom,
514    /// The bottom left corner
515    BottomLeft,
516    /// The left edge
517    Left,
518    /// The top left corner
519    TopLeft,
520}
521
522/// A type to describe the appearance of a window
523#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
524pub enum WindowDecorations {
525    #[default]
526    /// Server side decorations
527    Server,
528    /// Client side decorations
529    Client,
530}
531
532/// A type to describe how this window is currently configured
533#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
534pub enum Decorations {
535    /// The window is configured to use server side decorations
536    #[default]
537    Server,
538    /// The window is configured to use client side decorations
539    Client {
540        /// The edge tiling state
541        tiling: Tiling,
542    },
543}
544
545/// What window controls this platform supports
546#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
547pub struct WindowControls {
548    /// Whether this platform supports fullscreen
549    pub fullscreen: bool,
550    /// Whether this platform supports maximize
551    pub maximize: bool,
552    /// Whether this platform supports minimize
553    pub minimize: bool,
554    /// Whether this platform supports a window menu
555    pub window_menu: bool,
556}
557
558impl Default for WindowControls {
559    fn default() -> Self {
560        // Assume that we can do anything, unless told otherwise
561        Self {
562            fullscreen: true,
563            maximize: true,
564            minimize: true,
565            window_menu: true,
566        }
567    }
568}
569
570/// A window control button type used in [`WindowButtonLayout`].
571#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
572pub enum WindowButton {
573    /// The minimize button
574    Minimize,
575    /// The maximize button
576    Maximize,
577    /// The close button
578    Close,
579}
580
581impl WindowButton {
582    /// Returns a stable element ID for rendering this button.
583    pub fn id(&self) -> &'static str {
584        match self {
585            WindowButton::Minimize => "minimize",
586            WindowButton::Maximize => "maximize",
587            WindowButton::Close => "close",
588        }
589    }
590
591    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
592    fn index(&self) -> usize {
593        match self {
594            WindowButton::Minimize => 0,
595            WindowButton::Maximize => 1,
596            WindowButton::Close => 2,
597        }
598    }
599}
600
601/// Maximum number of [`WindowButton`]s per side in the titlebar.
602pub const MAX_BUTTONS_PER_SIDE: usize = 3;
603
604/// Describes which [`WindowButton`]s appear on each side of the titlebar.
605///
606/// On Linux, this is read from the desktop environment's configuration
607/// (e.g. GNOME's `gtk-decoration-layout` gsetting) via [`WindowButtonLayout::parse`].
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub struct WindowButtonLayout {
610    /// Buttons on the left side of the titlebar.
611    pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
612    /// Buttons on the right side of the titlebar.
613    pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
614}
615
616#[cfg(any(target_os = "linux", target_os = "freebsd"))]
617impl WindowButtonLayout {
618    /// Returns Zed's built-in fallback button layout for Linux titlebars.
619    pub fn linux_default() -> Self {
620        Self {
621            left: [None; MAX_BUTTONS_PER_SIDE],
622            right: [
623                Some(WindowButton::Minimize),
624                Some(WindowButton::Maximize),
625                Some(WindowButton::Close),
626            ],
627        }
628    }
629
630    /// Parses a GNOME-style `button-layout` string (e.g. `"close,minimize:maximize"`).
631    pub fn parse(layout_string: &str) -> Result<Self> {
632        fn parse_side(
633            s: &str,
634            seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
635            unrecognized: &mut Vec<String>,
636        ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
637            let mut result = [None; MAX_BUTTONS_PER_SIDE];
638            let mut i = 0;
639            for name in s.split(',') {
640                let trimmed = name.trim();
641                if trimmed.is_empty() {
642                    continue;
643                }
644                let button = match trimmed {
645                    "minimize" => Some(WindowButton::Minimize),
646                    "maximize" => Some(WindowButton::Maximize),
647                    "close" => Some(WindowButton::Close),
648                    other => {
649                        unrecognized.push(other.to_string());
650                        None
651                    }
652                };
653                if let Some(button) = button {
654                    if seen_buttons[button.index()] {
655                        continue;
656                    }
657                    if let Some(slot) = result.get_mut(i) {
658                        *slot = Some(button);
659                        seen_buttons[button.index()] = true;
660                        i += 1;
661                    }
662                }
663            }
664            result
665        }
666
667        let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
668        let mut unrecognized = Vec::new();
669        let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
670        let layout = Self {
671            left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
672            right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
673        };
674
675        if !unrecognized.is_empty()
676            && layout.left.iter().all(Option::is_none)
677            && layout.right.iter().all(Option::is_none)
678        {
679            bail!(
680                "button layout string {:?} contains no valid buttons (unrecognized: {})",
681                layout_string,
682                unrecognized.join(", ")
683            );
684        }
685
686        Ok(layout)
687    }
688
689    /// Formats the layout back into a GNOME-style `button-layout` string.
690    #[cfg(test)]
691    pub fn format(&self) -> String {
692        fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
693            buttons
694                .iter()
695                .flatten()
696                .map(|button| match button {
697                    WindowButton::Minimize => "minimize",
698                    WindowButton::Maximize => "maximize",
699                    WindowButton::Close => "close",
700                })
701                .collect::<Vec<_>>()
702                .join(",")
703        }
704
705        format!("{}:{}", format_side(&self.left), format_side(&self.right))
706    }
707}
708
709/// A type to describe which sides of the window are currently tiled in some way
710#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
711pub struct Tiling {
712    /// Whether the top edge is tiled
713    pub top: bool,
714    /// Whether the left edge is tiled
715    pub left: bool,
716    /// Whether the right edge is tiled
717    pub right: bool,
718    /// Whether the bottom edge is tiled
719    pub bottom: bool,
720}
721
722impl Tiling {
723    /// Initializes a [`Tiling`] type with all sides tiled
724    pub fn tiled() -> Self {
725        Self {
726            top: true,
727            left: true,
728            right: true,
729            bottom: true,
730        }
731    }
732
733    /// Whether any edge is tiled
734    pub fn is_tiled(&self) -> bool {
735        self.top || self.left || self.right || self.bottom
736    }
737}
738
739/// Callbacks for the accessibility adapter.
740pub struct A11yCallbacks {
741    /// Called when the adapter is activated (a screen reader connects).
742    pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
743    /// Called when an action is requested by the screen reader.
744    pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
745    /// Called when the adapter is deactivated (screen reader disconnects).
746    pub deactivation: Box<dyn Fn() + Send + 'static>,
747}
748
749#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
750#[expect(missing_docs)]
751pub struct RequestFrameOptions {
752    /// Whether a presentation is required.
753    pub require_presentation: bool,
754    /// Force refresh of all rendering states when true.
755    pub force_render: bool,
756}
757
758/// The application's lifecycle phase, as owned and reported by a mobile OS.
759///
760/// `Inactive` means visible but not receiving input (a system dialog on
761/// top), while `Background` means not visible at all, with process death
762/// possible at any time thereafter.
763///
764/// | Phase        | iOS                          | Android      |
765/// |--------------|------------------------------|--------------|
766/// | `Active`     | `didBecomeActive`            | `onResume`   |
767/// | `Inactive`   | `willResignActive`           | `onPause`    |
768/// | `Background` | `didEnterBackground`         | `onStop`     |
769/// | `Foreground` | `willEnterForeground`        | `onStart`    |
770#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
771pub enum AppLifecyclePhase {
772    /// Foreground and receiving input.
773    Active,
774    /// Foreground (visible) but not receiving input.
775    Inactive,
776    /// Not visible. The GPU surface may be destroyed while backgrounded and
777    /// the process may be killed without further notice.
778    Background,
779    /// Becoming visible again, before input is restored.
780    Foreground,
781}
782
783/// Regions of a window that are obscured or reserved by the system.
784///
785/// Mobile applications often share space in their window with system-specific
786/// geometry, from keyboards to camera notches. In GPUI, all this is abstracted
787/// into a single "inset" which should be overlaid on the window's bounds.
788/// It is up to the application develop to determine how to handle these cases.
789#[derive(Debug, Clone, Default, PartialEq)]
790pub struct WindowInsets {
791    /// Regions covered by system UI or hardware: status bar, display
792    /// cutouts/notch, home indicator, navigation bars.
793    /// (iOS: `safeAreaInsets`. Android: `WindowInsets` of types
794    /// `systemBars() | displayCutout()`.)
795    pub safe_area: Edges<Pixels>,
796    /// The region covered by the keyboard, when present.
797    /// (iOS: derived from `keyboardWillShow`/frame-change notifications.
798    /// Android: `WindowInsets.Type.ime()`.)
799    pub ime: Edges<Pixels>,
800}
801
802impl WindowInsets {
803    /// The combined inset content should avoid.
804    pub fn effective(&self) -> Edges<Pixels> {
805        Edges {
806            top: self.safe_area.top.max(self.ime.top),
807            right: self.safe_area.right.max(self.ime.right),
808            bottom: self.safe_area.bottom.max(self.ime.bottom),
809            left: self.safe_area.left.max(self.ime.left),
810        }
811    }
812}
813
814/// A change in the state of the focused text input.
815#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
816pub enum TextInputStateChange {
817    /// An editable element gained focus.
818    FocusGained,
819    /// The focused editable element lost focus.
820    FocusLost,
821    /// The selection or caret moved
822    SelectionChanged,
823    /// The document content changed outside of platform-initiated edits.
824    ContentChanged,
825}
826
827#[expect(missing_docs)]
828pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
829    fn bounds(&self) -> Bounds<Pixels>;
830    fn is_maximized(&self) -> bool;
831    fn window_bounds(&self) -> WindowBounds;
832    fn content_size(&self) -> Size<Pixels>;
833    fn resize(&mut self, size: Size<Pixels>);
834    fn scale_factor(&self) -> f32;
835    fn appearance(&self) -> WindowAppearance;
836    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
837    fn mouse_position(&self) -> Point<Pixels>;
838    fn modifiers(&self) -> Modifiers;
839    fn capslock(&self) -> Capslock;
840    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
841    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
842    fn prompt(
843        &self,
844        level: PromptLevel,
845        msg: &str,
846        detail: Option<&str>,
847        answers: &[PromptButton],
848    ) -> Option<oneshot::Receiver<usize>>;
849    fn activate(&self);
850    /// Requests that the operating system draw attention to this window.
851    fn request_attention(&self) {}
852    fn is_active(&self) -> bool;
853    fn is_hovered(&self) -> bool;
854    fn background_appearance(&self) -> WindowBackgroundAppearance;
855    fn set_title(&mut self, title: &str);
856    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
857    fn minimize(&self);
858    fn zoom(&self);
859    fn toggle_fullscreen(&self);
860    fn is_fullscreen(&self) -> bool;
861    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
862    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
863    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
864    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
865    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
866    fn on_moved(&self, callback: Box<dyn FnMut()>);
867    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
868    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
869    fn on_close(&self, callback: Box<dyn FnOnce()>);
870    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
871    fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
872    fn draw(&self, scene: &Scene);
873    fn completed_frame(&self) {}
874    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
875    fn is_subpixel_rendering_supported(&self) -> bool;
876
877    // macOS specific methods
878    fn get_title(&self) -> String {
879        String::new()
880    }
881    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
882        None
883    }
884    fn tab_bar_visible(&self) -> bool {
885        false
886    }
887    fn set_edited(&mut self, _edited: bool) {}
888    fn set_document_path(&self, _path: Option<&std::path::Path>) {}
889    #[cfg(target_os = "macos")]
890    fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
891    fn show_character_palette(&self) {}
892    fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
893    fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
894    fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
895    fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
896    fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
897    fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
898    fn merge_all_windows(&self) {}
899    fn move_tab_to_new_window(&self) {}
900    fn toggle_window_tab_overview(&self) {}
901    fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
902
903    #[cfg(target_os = "windows")]
904    fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
905
906    // Linux specific methods
907    fn inner_window_bounds(&self) -> WindowBounds {
908        self.window_bounds()
909    }
910    fn request_decorations(&self, _decorations: WindowDecorations) {}
911    fn show_window_menu(&self, _position: Point<Pixels>) {}
912    fn start_window_move(&self) {}
913    fn can_start_external_drag(&self) -> bool {
914        false
915    }
916    fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
917        false
918    }
919    fn start_window_resize(&self, _edge: ResizeEdge) {}
920    fn set_exclusive_zone(&self, _zone: Pixels) {}
921    #[cfg(all(target_os = "linux", feature = "wayland"))]
922    fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
923    fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
924    fn window_decorations(&self) -> Decorations {
925        Decorations::Server
926    }
927    fn set_app_id(&mut self, _app_id: &str) {}
928    fn map_window(&mut self) -> anyhow::Result<()> {
929        Ok(())
930    }
931    fn window_controls(&self) -> WindowControls {
932        WindowControls::default()
933    }
934    fn set_client_inset(&self, _inset: Pixels) {}
935    fn gpu_specs(&self) -> Option<GpuSpecs>;
936
937    fn update_ime_position(&self, _bounds: Bounds<Pixels>);
938
939    // Mobile platform methods.
940
941    /// The regions of this window currently obscured or reserved by the
942    /// system. Zero on platforms without such regions.
943    fn insets(&self) -> WindowInsets {
944        WindowInsets::default()
945    }
946
947    /// Registers a callback invoked whenever [`Self::insets`] change.
948    ///
949    /// Contract: fires continuously during animated transitions (Android
950    /// `WindowInsetsAnimation` progress; on iOS the platform interpolates
951    /// the keyboard animation curve on frame ticks) and is exact at rest.
952    fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
953
954    /// Sets the handler for the system back action (Android back
955    /// button/gesture; no source on iOS or desktop).
956    fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
957
958    /// Declares whether the application would currently handle the system
959    /// back action (e.g. navigation depth > 0).
960    fn set_back_enabled(&self, _enabled: bool) {}
961
962    /// Requests that the soft keyboard be shown.
963    fn show_soft_keyboard(&self) {}
964
965    /// Requests that the soft keyboard be hidden.
966    fn hide_soft_keyboard(&self) {}
967
968    /// Inform the operating system that the text input state has changed
969    fn text_input_state_changed(&self, _change: TextInputStateChange) {}
970
971    fn play_system_bell(&self) {}
972
973    /// Initialize the accessibility adapter with callbacks.
974    fn a11y_init(&self, _callbacks: A11yCallbacks) {}
975
976    /// Provide a TreeUpdate to the accessibility adapter.
977    fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
978
979    /// Inform the adapter of updated window bounds.
980    fn a11y_update_window_bounds(&self) {}
981
982    #[cfg(any(test, feature = "test-support"))]
983    fn as_test(&mut self) -> Option<&mut TestWindow> {
984        None
985    }
986
987    /// Renders the given scene to a texture and returns the pixel data as an RGBA image.
988    /// This does not present the frame to screen - useful for visual testing where we want
989    /// to capture what would be rendered without displaying it or requiring the window to be visible.
990    #[cfg(any(test, feature = "test-support"))]
991    fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
992        anyhow::bail!("render_to_image not implemented for this platform")
993    }
994}
995
996/// A renderer for headless windows that can produce real rendered output.
997#[cfg(any(test, feature = "test-support"))]
998pub trait PlatformHeadlessRenderer {
999    /// Render a scene and return the result as an RGBA image.
1000    fn render_scene_to_image(
1001        &mut self,
1002        scene: &Scene,
1003        size: Size<DevicePixels>,
1004    ) -> Result<RgbaImage>;
1005
1006    /// Render a scene to an offscreen target without reading the result back.
1007    ///
1008    /// This is the headless analogue of presenting a frame: it performs the
1009    /// same CPU-side scene encoding and GPU submission as drawing to a real
1010    /// window, but doesn't block on GPU completion or copy pixels back.
1011    fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1012
1013    /// Returns the sprite atlas used by this renderer.
1014    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1015}
1016
1017/// Type alias for runnables with metadata.
1018/// Previously an enum with a single variant, now simplified to a direct type alias.
1019#[doc(hidden)]
1020pub type RunnableVariant = Runnable<RunnableMeta>;
1021
1022#[doc(hidden)]
1023pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1024
1025#[doc(hidden)]
1026pub enum TasksIncluded {
1027    OnlyCompleted,
1028    CompletedAndRunning,
1029}
1030
1031/// This type is public so that our test macro can generate and use it, but it should not
1032/// be considered part of our public API.
1033#[doc(hidden)]
1034pub trait PlatformDispatcher: Send + Sync {
1035    fn is_main_thread(&self) -> bool;
1036    fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1037    fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1038    fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1039
1040    fn dispatch_on_main_thread_when_idle(
1041        &self,
1042        runnable: RunnableVariant,
1043        timeout: Option<Duration>,
1044    ) {
1045        let _ = timeout;
1046        self.dispatch_on_main_thread(runnable, Priority::Low);
1047    }
1048
1049    fn idle_time_remaining(&self) -> Option<Duration> {
1050        None
1051    }
1052
1053    fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1054
1055    fn now(&self) -> Instant {
1056        Instant::now()
1057    }
1058
1059    fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1060        gpui_util::defer(Box::new(|| {}))
1061    }
1062
1063    #[cfg(any(test, feature = "test-support"))]
1064    fn as_test(&self) -> Option<&TestDispatcher> {
1065        None
1066    }
1067
1068    // This cfg must match the `bench_dispatcher` module's, which implements
1069    // this method whenever it compiles.
1070    #[cfg(any(test, feature = "bench"))]
1071    fn as_bench(&self) -> Option<&BenchDispatcher> {
1072        None
1073    }
1074}
1075
1076#[expect(missing_docs)]
1077pub trait PlatformTextSystem: Send + Sync {
1078    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1079    /// Get all available font names.
1080    fn all_font_names(&self) -> Vec<String>;
1081    /// Get the font ID for a font descriptor.
1082    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1083    /// Get metrics for a font.
1084    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1085    /// Get typographic bounds for a glyph.
1086    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1087    /// Get the advance width for a glyph.
1088    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1089    /// Get the glyph ID for a character.
1090    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1091    /// Get raster bounds for a glyph.
1092    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1093    /// Rasterize a glyph.
1094    fn rasterize_glyph(
1095        &self,
1096        params: &RenderGlyphParams,
1097        raster_bounds: Bounds<DevicePixels>,
1098    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1099    /// Layout a line of text with the given font runs.
1100    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1101    /// Returns the recommended text rendering mode for the given font and size.
1102    fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1103    -> TextRenderingMode;
1104    /// Returns the dilation level to use for a glyph painted in the given color.
1105    fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1106        0
1107    }
1108}
1109
1110#[expect(missing_docs)]
1111pub struct NoopTextSystem;
1112
1113#[expect(missing_docs)]
1114impl NoopTextSystem {
1115    #[allow(dead_code)]
1116    pub fn new() -> Self {
1117        Self
1118    }
1119}
1120
1121impl PlatformTextSystem for NoopTextSystem {
1122    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1123        Ok(())
1124    }
1125
1126    fn all_font_names(&self) -> Vec<String> {
1127        Vec::new()
1128    }
1129
1130    fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1131        Ok(FontId(1))
1132    }
1133
1134    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1135        FontMetrics {
1136            units_per_em: 1000,
1137            ascent: 1025.0,
1138            descent: -275.0,
1139            line_gap: 0.0,
1140            underline_position: -95.0,
1141            underline_thickness: 60.0,
1142            cap_height: 698.0,
1143            x_height: 516.0,
1144            bounding_box: Bounds {
1145                origin: Point {
1146                    x: -260.0,
1147                    y: -245.0,
1148                },
1149                size: Size {
1150                    width: 1501.0,
1151                    height: 1364.0,
1152                },
1153            },
1154        }
1155    }
1156
1157    fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1158        Ok(Bounds {
1159            origin: Point { x: 54.0, y: 0.0 },
1160            size: size(392.0, 528.0),
1161        })
1162    }
1163
1164    fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1165        Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1166    }
1167
1168    fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1169        Some(GlyphId(ch.len_utf16() as u32))
1170    }
1171
1172    fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1173        Ok(Default::default())
1174    }
1175
1176    fn rasterize_glyph(
1177        &self,
1178        _params: &RenderGlyphParams,
1179        raster_bounds: Bounds<DevicePixels>,
1180    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1181        Ok((raster_bounds.size, Vec::new()))
1182    }
1183
1184    fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1185        let mut position = px(0.);
1186        let metrics = self.font_metrics(FontId(0));
1187        let em_width = font_size
1188            * self
1189                .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1190                .unwrap()
1191                .width
1192            / metrics.units_per_em as f32;
1193        let mut glyphs = Vec::new();
1194        for (ix, c) in text.char_indices() {
1195            if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1196                glyphs.push(ShapedGlyph {
1197                    id: glyph,
1198                    position: point(position, px(0.)),
1199                    index: ix,
1200                    is_emoji: glyph.0 == 2,
1201                });
1202                if glyph.0 == 2 {
1203                    position += em_width * 2.0;
1204                } else {
1205                    position += em_width;
1206                }
1207            } else {
1208                position += em_width
1209            }
1210        }
1211        let mut runs = Vec::default();
1212        if !glyphs.is_empty() {
1213            runs.push(ShapedRun {
1214                font_id: FontId(0),
1215                glyphs,
1216            });
1217        } else {
1218            position = px(0.);
1219        }
1220
1221        LineLayout {
1222            font_size,
1223            width: position,
1224            ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1225            descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1226            runs,
1227            len: text.len(),
1228        }
1229    }
1230
1231    fn recommended_rendering_mode(
1232        &self,
1233        _font_id: FontId,
1234        _font_size: Pixels,
1235    ) -> TextRenderingMode {
1236        TextRenderingMode::Grayscale
1237    }
1238}
1239
1240// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.cpp
1241// Copyright (c) Microsoft Corporation.
1242// Licensed under the MIT license.
1243/// Compute gamma correction ratios for subpixel text rendering.
1244#[allow(dead_code)]
1245pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1246    const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1247        [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], // gamma = 1.0
1248        [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], // gamma = 1.1
1249        [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], // gamma = 1.2
1250        [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], // gamma = 1.3
1251        [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], // gamma = 1.4
1252        [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], // gamma = 1.5
1253        [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], // gamma = 1.6
1254        [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], // gamma = 1.7
1255        [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], // gamma = 1.8
1256        [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], // gamma = 1.9
1257        [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], // gamma = 2.0
1258        [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], // gamma = 2.1
1259        [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], // gamma = 2.2
1260    ];
1261
1262    const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1263    const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1264
1265    let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1266    let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1267
1268    [
1269        ratios[0] * NORM13,
1270        ratios[1] * NORM24,
1271        ratios[2] * NORM13,
1272        ratios[3] * NORM24,
1273    ]
1274}
1275
1276#[derive(PartialEq, Eq, Hash, Clone)]
1277#[expect(missing_docs)]
1278pub enum AtlasKey {
1279    Glyph(RenderGlyphParams),
1280    Svg(RenderSvgParams),
1281    Image(RenderImageParams),
1282}
1283
1284impl AtlasKey {
1285    #[cfg_attr(
1286        all(
1287            any(target_os = "linux", target_os = "freebsd"),
1288            not(any(feature = "x11", feature = "wayland"))
1289        ),
1290        allow(dead_code)
1291    )]
1292    /// Returns the texture kind for this atlas key.
1293    pub fn texture_kind(&self) -> AtlasTextureKind {
1294        match self {
1295            AtlasKey::Glyph(params) => {
1296                if params.is_emoji {
1297                    AtlasTextureKind::Polychrome
1298                } else if params.subpixel_rendering {
1299                    AtlasTextureKind::Subpixel
1300                } else {
1301                    AtlasTextureKind::Monochrome
1302                }
1303            }
1304            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1305            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1306        }
1307    }
1308}
1309
1310impl From<RenderGlyphParams> for AtlasKey {
1311    fn from(params: RenderGlyphParams) -> Self {
1312        Self::Glyph(params)
1313    }
1314}
1315
1316impl From<RenderSvgParams> for AtlasKey {
1317    fn from(params: RenderSvgParams) -> Self {
1318        Self::Svg(params)
1319    }
1320}
1321
1322impl From<RenderImageParams> for AtlasKey {
1323    fn from(params: RenderImageParams) -> Self {
1324        Self::Image(params)
1325    }
1326}
1327
1328#[expect(missing_docs)]
1329pub trait PlatformAtlas {
1330    fn get_or_insert_with<'a>(
1331        &self,
1332        key: &AtlasKey,
1333        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1334    ) -> Result<Option<AtlasTile>>;
1335    fn remove(&self, key: &AtlasKey);
1336
1337    #[cfg(any(test, feature = "test-support"))]
1338    fn contains(&self, _key: &AtlasKey) -> bool {
1339        false
1340    }
1341}
1342
1343#[doc(hidden)]
1344pub struct AtlasTextureList<T> {
1345    pub textures: Vec<Option<T>>,
1346    pub free_list: Vec<usize>,
1347}
1348
1349impl<T> Default for AtlasTextureList<T> {
1350    fn default() -> Self {
1351        Self {
1352            textures: Vec::default(),
1353            free_list: Vec::default(),
1354        }
1355    }
1356}
1357
1358impl<T> ops::Index<usize> for AtlasTextureList<T> {
1359    type Output = Option<T>;
1360
1361    fn index(&self, index: usize) -> &Self::Output {
1362        &self.textures[index]
1363    }
1364}
1365
1366impl<T> AtlasTextureList<T> {
1367    #[allow(unused)]
1368    pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1369        self.free_list.clear();
1370        self.textures.drain(..)
1371    }
1372
1373    #[allow(dead_code)]
1374    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1375        self.textures.iter_mut().flatten()
1376    }
1377}
1378
1379#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1380#[repr(C)]
1381#[expect(missing_docs)]
1382pub struct AtlasTile {
1383    /// The texture this tile belongs to.
1384    pub texture_id: AtlasTextureId,
1385    /// The unique ID of this tile within its texture.
1386    pub tile_id: TileId,
1387    /// Padding around the tile content in pixels.
1388    pub padding: u32,
1389    /// The bounds of this tile within the texture.
1390    pub bounds: Bounds<DevicePixels>,
1391}
1392
1393#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1394#[repr(C)]
1395#[expect(missing_docs)]
1396pub struct AtlasTextureId {
1397    // We use u32 instead of usize for Metal Shader Language compatibility
1398    /// The index of this texture in the atlas.
1399    pub index: u32,
1400    /// The kind of content stored in this texture.
1401    pub kind: AtlasTextureKind,
1402}
1403
1404#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1405#[repr(C)]
1406#[cfg_attr(
1407    all(
1408        any(target_os = "linux", target_os = "freebsd"),
1409        not(any(feature = "x11", feature = "wayland"))
1410    ),
1411    allow(dead_code)
1412)]
1413#[expect(missing_docs)]
1414pub enum AtlasTextureKind {
1415    Monochrome = 0,
1416    Polychrome = 1,
1417    Subpixel = 2,
1418}
1419
1420#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1421#[repr(C)]
1422#[expect(missing_docs)]
1423pub struct TileId(pub u32);
1424
1425impl From<etagere::AllocId> for TileId {
1426    fn from(id: etagere::AllocId) -> Self {
1427        Self(id.serialize())
1428    }
1429}
1430
1431impl From<TileId> for etagere::AllocId {
1432    fn from(id: TileId) -> Self {
1433        Self::deserialize(id.0)
1434    }
1435}
1436
1437#[expect(missing_docs)]
1438pub struct PlatformInputHandler {
1439    cx: AsyncWindowContext,
1440    handler: Box<dyn InputHandler>,
1441}
1442
1443#[expect(missing_docs)]
1444#[cfg_attr(
1445    all(
1446        any(target_os = "linux", target_os = "freebsd"),
1447        not(any(feature = "x11", feature = "wayland"))
1448    ),
1449    allow(dead_code)
1450)]
1451impl PlatformInputHandler {
1452    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
1453        Self { cx, handler }
1454    }
1455
1456    pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
1457        self.cx
1458            .update(|window, cx| {
1459                self.handler
1460                    .selected_text_range(ignore_disabled_input, window, cx)
1461            })
1462            .ok()
1463            .flatten()
1464    }
1465
1466    #[cfg_attr(target_os = "windows", allow(dead_code))]
1467    pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
1468        self.cx
1469            .update(|window, cx| self.handler.marked_text_range(window, cx))
1470            .ok()
1471            .flatten()
1472    }
1473
1474    #[cfg_attr(
1475        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1476        allow(dead_code)
1477    )]
1478    pub fn text_for_range(
1479        &mut self,
1480        range_utf16: Range<usize>,
1481        adjusted: &mut Option<Range<usize>>,
1482    ) -> Option<String> {
1483        self.cx
1484            .update(|window, cx| {
1485                self.handler
1486                    .text_for_range(range_utf16, adjusted, window, cx)
1487            })
1488            .ok()
1489            .flatten()
1490    }
1491
1492    pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
1493        self.cx
1494            .update(|window, cx| {
1495                self.handler
1496                    .replace_text_in_range(replacement_range, text, window, cx);
1497            })
1498            .ok();
1499    }
1500
1501    pub fn replace_and_mark_text_in_range(
1502        &mut self,
1503        range_utf16: Option<Range<usize>>,
1504        new_text: &str,
1505        new_selected_range: Option<Range<usize>>,
1506    ) {
1507        self.cx
1508            .update(|window, cx| {
1509                self.handler.replace_and_mark_text_in_range(
1510                    range_utf16,
1511                    new_text,
1512                    new_selected_range,
1513                    window,
1514                    cx,
1515                )
1516            })
1517            .ok();
1518    }
1519
1520    #[cfg_attr(target_os = "windows", allow(dead_code))]
1521    pub fn unmark_text(&mut self) {
1522        self.cx
1523            .update(|window, cx| self.handler.unmark_text(window, cx))
1524            .ok();
1525    }
1526
1527    pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
1528        self.cx
1529            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
1530            .ok()
1531            .flatten()
1532    }
1533
1534    #[allow(dead_code)]
1535    pub fn apple_press_and_hold_enabled(&mut self) -> bool {
1536        self.handler.apple_press_and_hold_enabled()
1537    }
1538
1539    pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1540        self.handler.replace_text_in_range(None, input, window, cx);
1541    }
1542
1543    pub fn compute_ime_candidate_bounds(
1544        marked_range: Option<Range<usize>>,
1545        selection: &UTF16Selection,
1546        mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
1547    ) -> Option<Bounds<Pixels>> {
1548        if let Some(marked_range) = marked_range {
1549            // Default to the start of the marked (composing) range.
1550            let mut line_start = marked_range.start;
1551
1552            // Walk backward from the caret looking for a line break. A change in
1553            // the Y coordinate means we crossed into the previous visual line, so
1554            // the line start is one position after the break point.
1555            let caret = selection.range.end;
1556            if let Some(caret_bounds) = bounds_for_range(caret..caret) {
1557                for i in (marked_range.start..caret).rev() {
1558                    if let Some(b) = bounds_for_range(i..i) {
1559                        if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
1560                            line_start = i + 1;
1561                            break;
1562                        }
1563                    }
1564                }
1565            }
1566            bounds_for_range(line_start..line_start)
1567        } else {
1568            // No active composition \u{2014} use the selection endpoint.
1569            let offset = if selection.reversed {
1570                selection.range.start
1571            } else {
1572                selection.range.end
1573            };
1574            bounds_for_range(offset..offset)
1575        }
1576    }
1577
1578    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
1579        let marked_range = self.handler.marked_text_range(window, cx);
1580        let selection = self.handler.selected_text_range(true, window, cx)?;
1581        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
1582            self.handler.bounds_for_range(range, window, cx)
1583        })
1584    }
1585
1586    pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
1587        let marked_range = self.marked_text_range();
1588        let selection = self.selected_text_range(true)?;
1589        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
1590            self.bounds_for_range(range)
1591        })
1592    }
1593
1594    #[allow(unused)]
1595    pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
1596        self.cx
1597            .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
1598            .ok()
1599            .flatten()
1600    }
1601
1602    /// See [`InputHandler::set_selected_text_range`].
1603    pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
1604        self.cx
1605            .update(|window, cx| {
1606                self.handler
1607                    .set_selected_text_range(range_utf16, window, cx)
1608            })
1609            .ok();
1610    }
1611
1612    /// See [`InputHandler::element_bounds`].
1613    pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
1614        self.cx
1615            .update(|window, cx| self.handler.element_bounds(window, cx))
1616            .ok()
1617            .flatten()
1618    }
1619
1620    /// See [`InputHandler::text_length_utf16`].
1621    pub fn text_length_utf16(&mut self) -> Option<usize> {
1622        self.cx
1623            .update(|window, cx| self.handler.text_length_utf16(window, cx))
1624            .ok()
1625            .flatten()
1626    }
1627
1628    #[allow(dead_code)]
1629    pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
1630        self.handler.accepts_text_input(window, cx)
1631    }
1632
1633    #[allow(dead_code)]
1634    pub fn query_accepts_text_input(&mut self) -> bool {
1635        self.cx
1636            .update(|window, cx| self.handler.accepts_text_input(window, cx))
1637            .unwrap_or(true)
1638    }
1639
1640    /// See [`InputHandler::prefers_ime_for_printable_keys`].
1641    ///
1642    /// This is not a pure delegation to the handler: while a multi-stroke binding is pending this
1643    /// returns `false` regardless of the handler's preference, because the next printable key may
1644    /// complete a binding whose prefix already bypassed the IME.
1645    pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
1646        self.cx
1647            .update(|window, cx| {
1648                // The next printable key may complete a chord whose prefix bypassed the IME.
1649                !window.has_pending_keystrokes()
1650                    && self.handler.prefers_ime_for_printable_keys(window, cx)
1651            })
1652            .unwrap_or(false)
1653    }
1654}
1655
1656/// A struct representing a selection in a text buffer, in UTF-16 code units.
1657/// This is different from a range because the head may be before the tail.
1658#[derive(Debug)]
1659pub struct UTF16Selection {
1660    /// The range of text in the document this selection corresponds to
1661    /// in UTF-16 code units.
1662    pub range: Range<usize>,
1663    /// Whether the head of this selection is at the start (true), or end (false)
1664    /// of the range
1665    pub reversed: bool,
1666}
1667
1668/// Zed's interface for handling text input from the platform's IME system
1669/// This is currently a 1:1 exposure of the NSTextInputClient API:
1670///
1671/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
1672pub trait InputHandler: 'static {
1673    /// Get the range of the user's currently selected text, if any
1674    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
1675    ///
1676    /// Return value is in terms of UTF-16 code units, from 0 to the length of the document
1677    fn selected_text_range(
1678        &mut self,
1679        ignore_disabled_input: bool,
1680        window: &mut Window,
1681        cx: &mut App,
1682    ) -> Option<UTF16Selection>;
1683
1684    /// Get the range of the currently marked text, if any
1685    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
1686    ///
1687    /// Return value is in terms of UTF-16 code units, from 0 to the length of the document
1688    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
1689
1690    /// Get the text for the given document range in UTF-16 code units
1691    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
1692    ///
1693    /// range_utf16 is in terms of UTF-16 code units
1694    fn text_for_range(
1695        &mut self,
1696        range_utf16: Range<usize>,
1697        adjusted_range: &mut Option<Range<usize>>,
1698        window: &mut Window,
1699        cx: &mut App,
1700    ) -> Option<String>;
1701
1702    /// Replace the text in the given document range with the given text
1703    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
1704    ///
1705    /// replacement_range is in terms of UTF-16 code units
1706    fn replace_text_in_range(
1707        &mut self,
1708        replacement_range: Option<Range<usize>>,
1709        text: &str,
1710        window: &mut Window,
1711        cx: &mut App,
1712    );
1713
1714    /// Replace the text in the given document range with the given text,
1715    /// and mark the given text as part of an IME 'composing' state
1716    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
1717    ///
1718    /// range_utf16 is in terms of UTF-16 code units
1719    /// new_selected_range is relative to the beginning of new_text, in UTF-16 code units.
1720    fn replace_and_mark_text_in_range(
1721        &mut self,
1722        range_utf16: Option<Range<usize>>,
1723        new_text: &str,
1724        new_selected_range: Option<Range<usize>>,
1725        window: &mut Window,
1726        cx: &mut App,
1727    );
1728
1729    /// Remove the IME 'composing' state from the document
1730    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
1731    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
1732
1733    /// Get the bounds of the given document range in window-local logical pixels.
1734    /// The origin is the top-left of the window content area; the platform bridge
1735    /// converts to native screen coordinates or device pixels as required.
1736    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
1737    ///
1738    /// This is used for positioning the IME candidate window
1739    fn bounds_for_range(
1740        &mut self,
1741        range_utf16: Range<usize>,
1742        window: &mut Window,
1743        cx: &mut App,
1744    ) -> Option<Bounds<Pixels>>;
1745
1746    /// Get the document offset for the given point in UTF-16 code units.
1747    /// The point is in window-local logical pixels, like [`Self::bounds_for_range`].
1748    ///
1749    /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
1750    fn character_index_for_point(
1751        &mut self,
1752        point: Point<Pixels>,
1753        window: &mut Window,
1754        cx: &mut App,
1755    ) -> Option<usize>;
1756
1757    /// Set the range of the user's currently selected text.
1758    ///
1759    /// This is the reverse data-flow direction from [`Self::selected_text_range`]:
1760    /// platforms call it when the system text machinery moves the selection on the
1761    /// application's behalf \u{2014} e.g. the user drags a system selection handle or
1762    /// invokes Select All from system UI (iOS `UITextInput setSelectedTextRange:`,
1763    /// Android `InputConnection.setSelection`).
1764    ///
1765    /// range_utf16 is in terms of UTF-16 code units, from 0 to the length of the document
1766    fn set_selected_text_range(
1767        &mut self,
1768        _range_utf16: Range<usize>,
1769        _window: &mut Window,
1770        _cx: &mut App,
1771    ) {
1772    }
1773
1774    /// Get the bounds of the focused text element in window coordinates, if known.
1775    ///
1776    /// This is the pull counterpart to the [`PlatformWindow::update_ime_position`]
1777    /// push: mobile platforms ask for the focused element's geometry when they
1778    /// need it (e.g. to frame system text-interaction UI overlaid on the focused
1779    /// element).
1780    fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
1781        None
1782    }
1783
1784    /// Get the length of the document in UTF-16 code units, if known.
1785    fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
1786        None
1787    }
1788
1789    /// Allows a given input context to opt into getting raw key repeats instead of
1790    /// sending these to the platform.
1791    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1792    /// (which is how iTerm does it) but it doesn't seem to work for me.
1793    #[allow(dead_code)]
1794    fn apple_press_and_hold_enabled(&mut self) -> bool {
1795        true
1796    }
1797
1798    /// Returns whether this handler is accepting text input to be inserted.
1799    fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1800        true
1801    }
1802
1803    /// Returns whether printable keys should be routed to the IME before keybinding
1804    /// matching when a non-ASCII input source (e.g. Japanese, Korean, Chinese IME)
1805    /// is active. This prevents multi-stroke keybindings like `jj` from intercepting
1806    /// keys that the IME should compose.
1807    ///
1808    /// Defaults to `false`. The editor overrides this based on whether it expects
1809    /// character input (e.g. Vim insert mode returns `true`, normal mode returns `false`).
1810    /// The terminal keeps the default `false` so that raw keys reach the terminal process.
1811    fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1812        false
1813    }
1814}
1815
1816/// Selects the rendering composition mode for a Windows window.
1817///
1818/// Other platforms ignore this setting. The mode cannot be changed after creation.
1819#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1820pub enum WindowsCompositionMode {
1821    /// Use the platform default, including `GPUI_DISABLE_DIRECT_COMPOSITION`.
1822    #[default]
1823    Auto,
1824    /// Use DirectComposition, overriding the process-wide environment setting.
1825    DirectComposition,
1826    /// Use a redirected window surface for native menus and GDI child controls.
1827    ///
1828    /// This disables DirectComposition for this window. Embedded WebViews still
1829    /// occupy a separate native layer and cannot be covered by GPUI overlays.
1830    RedirectionBitmap,
1831}
1832
1833/// The variables that can be configured when creating a new window
1834#[derive(Debug)]
1835pub struct WindowOptions {
1836    /// Specifies the state and bounds of the window in screen coordinates.
1837    /// - `None`: Inherit the bounds.
1838    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1839    pub window_bounds: Option<WindowBounds>,
1840
1841    /// The titlebar configuration of the window
1842    pub titlebar: Option<TitlebarOptions>,
1843
1844    /// Whether the window should be focused when created
1845    pub focus: bool,
1846
1847    /// Whether the window should be shown when created
1848    pub show: bool,
1849
1850    /// The kind of window to create
1851    pub kind: WindowKind,
1852
1853    /// Whether the window can be moved by the user. When `false`, the user cannot drag
1854    /// the window (on macOS this sets `NSWindow.isMovable`, which also disables the
1855    /// Window-menu tiling items); programmatic moves are still allowed.
1856    pub is_movable: bool,
1857
1858    /// Whether the application owns dragging of the (custom) titlebar, rather than
1859    /// AppKit. Only has an effect on macOS.
1860    ///
1861    /// Set this to `true` for windows that draw their own titlebar and move the window
1862    /// themselves via [`Window::start_window_move`]. It marks the whole content view as
1863    /// app-owned titlebar content, so AppKit neither drags the window from the titlebar
1864    /// nor delays titlebar clicks while disambiguating double-clicks (a delay first
1865    /// observed on macOS 27). It is independent of `is_movable`, so such windows stay
1866    /// user-movable (via their own drag) and keep the Window-menu tiling items enabled.
1867    ///
1868    /// Leave this `false` for windows that rely on AppKit's native titlebar dragging.
1869    pub app_owns_titlebar_drag: bool,
1870
1871    /// Whether the window should be resizable by the user
1872    pub is_resizable: bool,
1873
1874    /// Whether the window should be minimized by the user
1875    pub is_minimizable: bool,
1876
1877    /// The display to create the window on, if this is None,
1878    /// the window will be created on the main display
1879    pub display_id: Option<DisplayId>,
1880
1881    /// The appearance of the window background.
1882    pub window_background: WindowBackgroundAppearance,
1883
1884    /// Windows rendering composition mode. Ignored on other platforms.
1885    /// Use [`WindowsCompositionMode::RedirectionBitmap`] for native menus or GDI child controls.
1886    pub windows_composition: WindowsCompositionMode,
1887
1888    /// Application identifier of the window. Can by used by desktop environments to group applications together.
1889    pub app_id: Option<String>,
1890
1891    /// Window minimum size
1892    pub window_min_size: Option<Size<Pixels>>,
1893
1894    /// Whether to use client or server-side decorations on X11 and Wayland.
1895    /// The platform may ignore requests it cannot satisfy.
1896    pub window_decorations: Option<WindowDecorations>,
1897
1898    /// Icon image (X11 only)
1899    pub icon: Option<Arc<image::RgbaImage>>,
1900
1901    /// 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.
1902    pub tabbing_identifier: Option<String>,
1903}
1904
1905/// The variables that can be configured when creating a new window
1906#[derive(Debug)]
1907#[cfg_attr(
1908    all(
1909        any(target_os = "linux", target_os = "freebsd"),
1910        not(any(feature = "x11", feature = "wayland"))
1911    ),
1912    allow(dead_code)
1913)]
1914#[allow(missing_docs)]
1915pub struct WindowParams {
1916    pub bounds: Bounds<Pixels>,
1917
1918    pub windows_composition: WindowsCompositionMode,
1919
1920    /// The titlebar configuration of the window
1921    #[cfg_attr(feature = "wayland", allow(dead_code))]
1922    pub titlebar: Option<TitlebarOptions>,
1923
1924    /// The kind of window to create
1925    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1926    pub kind: WindowKind,
1927
1928    /// Whether the window should be movable by the user
1929    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1930    pub is_movable: bool,
1931
1932    /// Whether the application owns dragging of the (custom) titlebar (macOS only)
1933    #[cfg_attr(
1934        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1935        allow(dead_code)
1936    )]
1937    pub app_owns_titlebar_drag: bool,
1938
1939    /// Whether the window should be resizable by the user
1940    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1941    pub is_resizable: bool,
1942
1943    /// Whether the window should be minimized by the user
1944    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1945    pub is_minimizable: bool,
1946
1947    #[cfg_attr(
1948        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1949        allow(dead_code)
1950    )]
1951    pub focus: bool,
1952
1953    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1954    pub show: bool,
1955
1956    /// An image to set as the window icon (x11 only)
1957    #[cfg_attr(feature = "wayland", allow(dead_code))]
1958    pub icon: Option<Arc<image::RgbaImage>>,
1959
1960    #[cfg_attr(feature = "wayland", allow(dead_code))]
1961    pub display_id: Option<DisplayId>,
1962
1963    #[cfg_attr(feature = "wayland", allow(dead_code))]
1964    pub app_id: Option<String>,
1965
1966    pub window_min_size: Option<Size<Pixels>>,
1967
1968    #[cfg(target_os = "macos")]
1969    pub tabbing_identifier: Option<String>,
1970}
1971
1972/// Represents the status of how a window should be opened.
1973#[derive(Debug, Copy, Clone, PartialEq)]
1974pub enum WindowBounds {
1975    /// Indicates that the window should open in a windowed state with the given bounds.
1976    Windowed(Bounds<Pixels>),
1977    /// Indicates that the window should open in a maximized state.
1978    /// The bounds provided here represent the restore size of the window.
1979    Maximized(Bounds<Pixels>),
1980    /// Indicates that the window should open in fullscreen mode.
1981    /// The bounds provided here represent the restore size of the window.
1982    Fullscreen(Bounds<Pixels>),
1983}
1984
1985impl Default for WindowBounds {
1986    fn default() -> Self {
1987        WindowBounds::Windowed(Bounds::default())
1988    }
1989}
1990
1991impl WindowBounds {
1992    /// Retrieve the inner bounds
1993    pub fn get_bounds(&self) -> Bounds<Pixels> {
1994        match self {
1995            WindowBounds::Windowed(bounds) => *bounds,
1996            WindowBounds::Maximized(bounds) => *bounds,
1997            WindowBounds::Fullscreen(bounds) => *bounds,
1998        }
1999    }
2000
2001    /// Creates a new window bounds that centers the window on the screen.
2002    pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
2003        WindowBounds::Windowed(Bounds::centered(None, size, cx))
2004    }
2005}
2006
2007impl Default for WindowOptions {
2008    fn default() -> Self {
2009        Self {
2010            window_bounds: None,
2011            titlebar: Some(TitlebarOptions {
2012                title: Default::default(),
2013                appears_transparent: Default::default(),
2014                traffic_light_position: Default::default(),
2015            }),
2016            focus: true,
2017            show: true,
2018            kind: WindowKind::Normal,
2019            is_movable: true,
2020            app_owns_titlebar_drag: false,
2021            is_resizable: true,
2022            is_minimizable: true,
2023            display_id: None,
2024            window_background: WindowBackgroundAppearance::default(),
2025            windows_composition: WindowsCompositionMode::default(),
2026            icon: None,
2027            app_id: None,
2028            window_min_size: None,
2029            window_decorations: None,
2030            tabbing_identifier: None,
2031        }
2032    }
2033}
2034
2035/// The options that can be configured for a window's titlebar
2036#[derive(Debug, Default)]
2037pub struct TitlebarOptions {
2038    /// The initial title of the window
2039    pub title: Option<SharedString>,
2040
2041    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
2042    /// Refer to [`WindowOptions::window_decorations`] on Linux
2043    pub appears_transparent: bool,
2044
2045    /// The position of the macOS traffic light buttons
2046    pub traffic_light_position: Option<Point<Pixels>>,
2047}
2048
2049/// The kind of window to create
2050#[derive(Clone, Debug, PartialEq, Eq)]
2051pub enum WindowKind {
2052    /// A normal application window
2053    Normal,
2054
2055    /// A window that appears above all other windows, usually used for alerts or popups
2056    /// use sparingly!
2057    PopUp,
2058
2059    /// A parent-anchored, platform-native popup window for menus, comboboxes, context menus and
2060    /// tooltips. Unlike [`WindowKind::PopUp`], it is positioned relative to a parent window.
2061    ///
2062    /// The popup's size comes from [`WindowOptions::window_bounds`], whose origin is ignored.
2063    /// See [`popup::PopupOptions`] for the placement options. Platforms without a native
2064    /// implementation reject it with [`popup::PopupNotSupportedError`].
2065    AnchoredPopup(popup::PopupOptions),
2066
2067    /// A floating window that appears on top of its parent window
2068    Floating,
2069
2070    /// A Wayland LayerShell window, used to draw overlays or backgrounds for applications such as
2071    /// docks, notifications or wallpapers.
2072    #[cfg(all(target_os = "linux", feature = "wayland"))]
2073    LayerShell(layer_shell::LayerShellOptions),
2074
2075    /// A window that appears on top of its parent window and blocks interaction with it
2076    /// until the modal window is closed
2077    Dialog,
2078}
2079
2080/// The appearance of the window, as defined by the operating system.
2081///
2082/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
2083/// values.
2084#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2085pub enum WindowAppearance {
2086    /// A light appearance.
2087    ///
2088    /// On macOS, this corresponds to the `aqua` appearance.
2089    #[default]
2090    Light,
2091
2092    /// A light appearance with vibrant colors.
2093    ///
2094    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
2095    VibrantLight,
2096
2097    /// A dark appearance.
2098    ///
2099    /// On macOS, this corresponds to the `darkAqua` appearance.
2100    Dark,
2101
2102    /// A dark appearance with vibrant colors.
2103    ///
2104    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
2105    VibrantDark,
2106}
2107
2108/// The appearance of the background of the window itself, when there is
2109/// no content or the content is transparent.
2110#[derive(Copy, Clone, Debug, Default, PartialEq)]
2111pub enum WindowBackgroundAppearance {
2112    /// Opaque.
2113    ///
2114    /// This lets the window manager know that content behind this
2115    /// window does not need to be drawn.
2116    ///
2117    /// Actual color depends on the system and themes should define a fully
2118    /// opaque background color instead.
2119    #[default]
2120    Opaque,
2121    /// Plain alpha transparency.
2122    Transparent,
2123    /// Transparency, but the contents behind the window are blurred.
2124    ///
2125    /// Not always supported.
2126    Blurred,
2127    /// The Mica backdrop material, supported on Windows 11.
2128    MicaBackdrop,
2129    /// The Mica Alt backdrop material, supported on Windows 11.
2130    MicaAltBackdrop,
2131}
2132
2133/// The text rendering mode to use for drawing glyphs.
2134#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2135pub enum TextRenderingMode {
2136    /// Use the platform's default text rendering mode.
2137    #[default]
2138    PlatformDefault,
2139    /// Use subpixel (ClearType-style) text rendering.
2140    Subpixel,
2141    /// Use grayscale text rendering.
2142    Grayscale,
2143}
2144
2145/// The options that can be configured for a file dialog prompt
2146#[derive(Clone, Debug)]
2147pub struct PathPromptOptions {
2148    /// Should the prompt allow files to be selected?
2149    pub files: bool,
2150    /// Should the prompt allow directories to be selected?
2151    pub directories: bool,
2152    /// Should the prompt allow multiple files to be selected?
2153    pub multiple: bool,
2154    /// The prompt to show to a user when selecting a path
2155    pub prompt: Option<SharedString>,
2156}
2157
2158/// What kind of prompt styling to show
2159#[derive(Copy, Clone, Debug, PartialEq)]
2160pub enum PromptLevel {
2161    /// A prompt that is shown when the user should be notified of something
2162    Info,
2163
2164    /// A prompt that is shown when the user needs to be warned of a potential problem
2165    Warning,
2166
2167    /// A prompt that is shown when a critical problem has occurred
2168    Critical,
2169}
2170
2171/// Prompt Button
2172#[derive(Clone, Debug, PartialEq)]
2173pub enum PromptButton {
2174    /// Ok button
2175    Ok(SharedString),
2176    /// Cancel button
2177    Cancel(SharedString),
2178    /// Other button
2179    Other(SharedString),
2180}
2181
2182impl PromptButton {
2183    /// Create a button with label
2184    pub fn new(label: impl Into<SharedString>) -> Self {
2185        PromptButton::Other(label.into())
2186    }
2187
2188    /// Create an Ok button
2189    pub fn ok(label: impl Into<SharedString>) -> Self {
2190        PromptButton::Ok(label.into())
2191    }
2192
2193    /// Create a Cancel button
2194    pub fn cancel(label: impl Into<SharedString>) -> Self {
2195        PromptButton::Cancel(label.into())
2196    }
2197
2198    /// Returns true if this button is a cancel button.
2199    #[allow(dead_code)]
2200    pub fn is_cancel(&self) -> bool {
2201        matches!(self, PromptButton::Cancel(_))
2202    }
2203
2204    /// Returns the label of the button
2205    pub fn label(&self) -> &SharedString {
2206        match self {
2207            PromptButton::Ok(label) => label,
2208            PromptButton::Cancel(label) => label,
2209            PromptButton::Other(label) => label,
2210        }
2211    }
2212}
2213
2214impl From<&str> for PromptButton {
2215    fn from(value: &str) -> Self {
2216        match value.to_lowercase().as_str() {
2217            "ok" => PromptButton::Ok("OK".into()),
2218            "cancel" => PromptButton::Cancel("Cancel".into()),
2219            _ => PromptButton::Other(SharedString::from(value.to_owned())),
2220        }
2221    }
2222}
2223
2224/// The style of the cursor (pointer)
2225#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2226pub enum CursorStyle {
2227    /// The default cursor
2228    #[default]
2229    Arrow,
2230
2231    /// A text input cursor
2232    /// corresponds to the CSS cursor value `text`
2233    IBeam,
2234
2235    /// A crosshair cursor
2236    /// corresponds to the CSS cursor value `crosshair`
2237    Crosshair,
2238
2239    /// A closed hand cursor
2240    /// corresponds to the CSS cursor value `grabbing`
2241    ClosedHand,
2242
2243    /// An open hand cursor
2244    /// corresponds to the CSS cursor value `grab`
2245    OpenHand,
2246
2247    /// A pointing hand cursor
2248    /// corresponds to the CSS cursor value `pointer`
2249    PointingHand,
2250
2251    /// A resize left cursor
2252    /// corresponds to the CSS cursor value `w-resize`
2253    ResizeLeft,
2254
2255    /// A resize right cursor
2256    /// corresponds to the CSS cursor value `e-resize`
2257    ResizeRight,
2258
2259    /// A resize cursor to the left and right
2260    /// corresponds to the CSS cursor value `ew-resize`
2261    ResizeLeftRight,
2262
2263    /// A resize up cursor
2264    /// corresponds to the CSS cursor value `n-resize`
2265    ResizeUp,
2266
2267    /// A resize down cursor
2268    /// corresponds to the CSS cursor value `s-resize`
2269    ResizeDown,
2270
2271    /// A resize cursor directing up and down
2272    /// corresponds to the CSS cursor value `ns-resize`
2273    ResizeUpDown,
2274
2275    /// A resize cursor directing up-left and down-right
2276    /// corresponds to the CSS cursor value `nesw-resize`
2277    ResizeUpLeftDownRight,
2278
2279    /// A resize cursor directing up-right and down-left
2280    /// corresponds to the CSS cursor value `nwse-resize`
2281    ResizeUpRightDownLeft,
2282
2283    /// A cursor indicating that the item/column can be resized horizontally.
2284    /// corresponds to the CSS cursor value `col-resize`
2285    ResizeColumn,
2286
2287    /// A cursor indicating that the item/row can be resized vertically.
2288    /// corresponds to the CSS cursor value `row-resize`
2289    ResizeRow,
2290
2291    /// A text input cursor for vertical layout
2292    /// corresponds to the CSS cursor value `vertical-text`
2293    IBeamCursorForVerticalLayout,
2294
2295    /// A cursor indicating that the operation is not allowed
2296    /// corresponds to the CSS cursor value `not-allowed`
2297    OperationNotAllowed,
2298
2299    /// A cursor indicating that the operation will result in a link
2300    /// corresponds to the CSS cursor value `alias`
2301    DragLink,
2302
2303    /// A cursor indicating that the operation will result in a copy
2304    /// corresponds to the CSS cursor value `copy`
2305    DragCopy,
2306
2307    /// A cursor indicating that the operation will result in a context menu
2308    /// corresponds to the CSS cursor value `context-menu`
2309    ContextualMenu,
2310}
2311
2312/// The requested operation when a file manager pastes a file list.
2313/// This is a hint to the recipient, not a request for GPUI to delete any files.
2314#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2315pub enum FileClipboardOperation {
2316    /// Copy the files.
2317    Copy,
2318    /// Request a move. The receiving application owns the actual file operation.
2319    Move,
2320}
2321
2322/// A native file clipboard write could not be completed.
2323#[derive(Debug, thiserror::Error)]
2324pub enum FileClipboardError {
2325    /// The backend does not support this operation.
2326    #[error("file clipboard operation is unsupported on this backend")]
2327    Unsupported,
2328    /// A file list must be nonempty and contain absolute paths without NUL bytes.
2329    #[error("file clipboard paths must be nonempty, absolute, and contain no NUL bytes")]
2330    InvalidPaths,
2331    /// Clipboard access or selection ownership is currently unavailable.
2332    #[error("file clipboard unavailable: {0}")]
2333    Unavailable(String),
2334}
2335
2336impl crate::ExternalPaths {
2337    /// Validates paths before a native clipboard write can replace existing contents.
2338    /// No filesystem access is performed and paths need not exist yet.
2339    pub fn validate_for_clipboard(&self) -> std::result::Result<(), FileClipboardError> {
2340        if self.0.is_empty()
2341            || self
2342                .0
2343                .iter()
2344                .any(|path| !path.is_absolute() || path.as_os_str().as_encoded_bytes().contains(&0))
2345        {
2346            return Err(FileClipboardError::InvalidPaths);
2347        }
2348        Ok(())
2349    }
2350
2351    /// Serializes absolute file URLs for the `text/uri-list` clipboard format.
2352    /// Reserved characters, Unicode and line breaks are percent-encoded.
2353    /// Returns [`FileClipboardError::Unsupported`] on targets without native paths.
2354    pub fn clipboard_uri_list(&self) -> std::result::Result<String, FileClipboardError> {
2355        #[cfg(not(any(unix, windows, target_os = "wasi")))]
2356        {
2357            Err(FileClipboardError::Unsupported)
2358        }
2359        #[cfg(any(unix, windows, target_os = "wasi"))]
2360        {
2361            self.validate_for_clipboard()?;
2362            let mut result = String::new();
2363            for path in &self.0 {
2364                let uri =
2365                    url::Url::from_file_path(path).map_err(|_| FileClipboardError::InvalidPaths)?;
2366                result.push_str(uri.as_str());
2367                result.push_str("\r\n");
2368            }
2369            Ok(result)
2370        }
2371    }
2372
2373    /// Serializes the GNOME file clipboard format, including copy or move intent.
2374    pub fn clipboard_gnome_files(
2375        &self,
2376        operation: FileClipboardOperation,
2377    ) -> std::result::Result<String, FileClipboardError> {
2378        let uris = self.clipboard_uri_list()?;
2379        let verb = match operation {
2380            FileClipboardOperation::Copy => "copy",
2381            FileClipboardOperation::Move => "cut",
2382        };
2383        Ok(format!(
2384            "{verb}\n{}",
2385            uris.trim_end_matches("\r\n").replace("\r\n", "\n")
2386        ))
2387    }
2388}
2389
2390/// A clipboard item that should be copied to the clipboard
2391#[derive(Clone, Debug, Eq, PartialEq)]
2392pub struct ClipboardItem {
2393    /// The entries in this clipboard item.
2394    pub entries: Vec<ClipboardEntry>,
2395}
2396
2397/// Either a ClipboardString or a ClipboardImage
2398#[derive(Clone, Debug, Eq, PartialEq)]
2399pub enum ClipboardEntry {
2400    /// A string entry
2401    String(ClipboardString),
2402    /// An image entry
2403    Image(Image),
2404    /// A file list. Legacy clipboard writes interpret this as copy intent.
2405    /// Use [`App::write_files_to_clipboard`] for move intent and error reporting.
2406    ExternalPaths(crate::ExternalPaths),
2407}
2408
2409impl ClipboardItem {
2410    /// Create a new ClipboardItem::String with no associated metadata
2411    pub fn new_string(text: String) -> Self {
2412        Self {
2413            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
2414        }
2415    }
2416
2417    /// Create a new ClipboardItem::String with the given text and associated metadata
2418    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
2419        Self {
2420            entries: vec![ClipboardEntry::String(ClipboardString {
2421                text,
2422                metadata: Some(metadata),
2423            })],
2424        }
2425    }
2426
2427    /// Create a new ClipboardItem::String with the given text and associated metadata
2428    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
2429        Self {
2430            entries: vec![ClipboardEntry::String(
2431                ClipboardString::new(text).with_json_metadata(metadata),
2432            )],
2433        }
2434    }
2435
2436    /// Create a new ClipboardItem::Image with the given image with no associated metadata
2437    pub fn new_image(image: &Image) -> Self {
2438        Self {
2439            entries: vec![ClipboardEntry::Image(image.clone())],
2440        }
2441    }
2442
2443    /// Concatenates plain text entries, excluding file paths, images, and metadata.
2444    /// Returns `None` when there is no nonempty plain text.
2445    pub fn plain_text(&self) -> Option<String> {
2446        let mut text = String::new();
2447        for entry in &self.entries {
2448            if let ClipboardEntry::String(entry) = entry {
2449                text.push_str(&entry.text);
2450            }
2451        }
2452        (!text.is_empty()).then_some(text)
2453    }
2454
2455    /// Concatenates together all the ClipboardString entries in the item.
2456    /// Returns None if there were no ClipboardString entries.
2457    pub fn text(&self) -> Option<String> {
2458        let mut answer = String::new();
2459
2460        for entry in self.entries.iter() {
2461            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
2462                answer.push_str(text);
2463            }
2464        }
2465
2466        if answer.is_empty() {
2467            for entry in self.entries.iter() {
2468                if let ClipboardEntry::ExternalPaths(paths) = entry {
2469                    for path in &paths.0 {
2470                        use std::fmt::Write as _;
2471                        _ = write!(answer, "{}", path.display());
2472                    }
2473                }
2474            }
2475        }
2476
2477        if !answer.is_empty() {
2478            Some(answer)
2479        } else {
2480            None
2481        }
2482    }
2483
2484    /// If this item is one ClipboardEntry::String, returns its metadata.
2485    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
2486    pub fn metadata(&self) -> Option<&String> {
2487        match self.entries().first() {
2488            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
2489                clipboard_string.metadata.as_ref()
2490            }
2491            _ => None,
2492        }
2493    }
2494
2495    /// Get the item's entries
2496    pub fn entries(&self) -> &[ClipboardEntry] {
2497        &self.entries
2498    }
2499
2500    /// Get owned versions of the item's entries
2501    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
2502        self.entries.into_iter()
2503    }
2504}
2505
2506impl From<ClipboardString> for ClipboardEntry {
2507    fn from(value: ClipboardString) -> Self {
2508        Self::String(value)
2509    }
2510}
2511
2512impl From<String> for ClipboardEntry {
2513    fn from(value: String) -> Self {
2514        Self::from(ClipboardString::from(value))
2515    }
2516}
2517
2518impl From<Image> for ClipboardEntry {
2519    fn from(value: Image) -> Self {
2520        Self::Image(value)
2521    }
2522}
2523
2524impl From<ClipboardEntry> for ClipboardItem {
2525    fn from(value: ClipboardEntry) -> Self {
2526        Self {
2527            entries: vec![value],
2528        }
2529    }
2530}
2531
2532impl From<String> for ClipboardItem {
2533    fn from(value: String) -> Self {
2534        Self::from(ClipboardEntry::from(value))
2535    }
2536}
2537
2538impl From<Image> for ClipboardItem {
2539    fn from(value: Image) -> Self {
2540        Self::from(ClipboardEntry::from(value))
2541    }
2542}
2543
2544/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
2545#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
2546pub enum ImageFormat {
2547    // Sorted from most to least likely to be pasted into an editor,
2548    // which matters when we iterate through them trying to see if
2549    // clipboard content matches them.
2550    /// .png
2551    Png,
2552    /// .jpeg or .jpg
2553    Jpeg,
2554    /// .webp
2555    Webp,
2556    /// .gif
2557    Gif,
2558    /// .svg
2559    Svg,
2560    /// .bmp
2561    Bmp,
2562    /// .tif or .tiff
2563    Tiff,
2564    /// .ico
2565    Ico,
2566    /// Netpbm image formats (.pbm, .ppm, .pgm).
2567    Pnm,
2568}
2569
2570impl ImageFormat {
2571    /// Returns the mime type for the ImageFormat
2572    pub const fn mime_type(self) -> &'static str {
2573        match self {
2574            ImageFormat::Png => "image/png",
2575            ImageFormat::Jpeg => "image/jpeg",
2576            ImageFormat::Webp => "image/webp",
2577            ImageFormat::Gif => "image/gif",
2578            ImageFormat::Svg => "image/svg+xml",
2579            ImageFormat::Bmp => "image/bmp",
2580            ImageFormat::Tiff => "image/tiff",
2581            ImageFormat::Ico => "image/ico",
2582            ImageFormat::Pnm => "image/x-portable-anymap",
2583        }
2584    }
2585
2586    /// Returns the file extension for this image format (without leading dot).
2587    pub const fn extension(self) -> &'static str {
2588        match self {
2589            ImageFormat::Png => "png",
2590            ImageFormat::Jpeg => "jpg",
2591            ImageFormat::Webp => "webp",
2592            ImageFormat::Gif => "gif",
2593            ImageFormat::Svg => "svg",
2594            ImageFormat::Bmp => "bmp",
2595            ImageFormat::Tiff => "tiff",
2596            ImageFormat::Ico => "ico",
2597            ImageFormat::Pnm => "pnm",
2598        }
2599    }
2600
2601    /// Returns the ImageFormat for the given mime type, including known aliases.
2602    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
2603        use strum::IntoEnumIterator;
2604        Self::iter()
2605            .find(|format| format.mime_type() == mime_type)
2606            .or_else(|| Self::from_mime_type_alias(mime_type))
2607    }
2608
2609    /// Non-canonical mime types that some producers use in the wild.
2610    /// Unlike `mime_type()` which returns the single canonical form,
2611    /// these are legacy or shortened variants we still need to recognize.
2612    fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
2613        match mime_type {
2614            "image/jpg" => Some(Self::Jpeg),
2615            "image/tif" => Some(Self::Tiff),
2616            _ => None,
2617        }
2618    }
2619}
2620
2621/// An image, with a format and certain bytes
2622#[derive(Clone, Debug, PartialEq, Eq)]
2623pub struct Image {
2624    /// The image format the bytes represent (e.g. PNG)
2625    pub format: ImageFormat,
2626    /// The raw image bytes
2627    pub bytes: Vec<u8>,
2628    /// The unique ID for the image
2629    pub id: u64,
2630}
2631
2632pub(crate) fn decode_static_image(
2633    bytes: &[u8],
2634    format: image::ImageFormat,
2635) -> Result<SmallVec<[Frame; 1]>> {
2636    let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
2637        .into_decoder()
2638        .context("creating image decoder")?;
2639    decode_static_image_from_decoder(decoder)
2640}
2641
2642pub(crate) fn decode_static_image_from_decoder(
2643    mut decoder: impl image::ImageDecoder,
2644) -> Result<SmallVec<[Frame; 1]>> {
2645    let orientation = decoder
2646        .orientation()
2647        .context("reading decoder's orientation")?;
2648    let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
2649    image.apply_orientation(orientation);
2650
2651    let mut data = image.into_rgba8();
2652    for pixel in data.chunks_exact_mut(4) {
2653        pixel.swap(0, 2);
2654    }
2655
2656    Ok(SmallVec::from_elem(Frame::new(data), 1))
2657}
2658
2659impl Hash for Image {
2660    fn hash<H: Hasher>(&self, state: &mut H) {
2661        state.write_u64(self.id);
2662    }
2663}
2664
2665impl Image {
2666    /// An empty image containing no data
2667    pub fn empty() -> Self {
2668        Self::from_bytes(ImageFormat::Png, Vec::new())
2669    }
2670
2671    /// Create an image from a format and bytes
2672    pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
2673        Self {
2674            id: hash(&bytes),
2675            format,
2676            bytes,
2677        }
2678    }
2679
2680    /// Get this image's ID
2681    pub fn id(&self) -> u64 {
2682        self.id
2683    }
2684
2685    /// Use the GPUI `use_asset` API to make this image renderable
2686    pub fn use_render_image(
2687        self: Arc<Self>,
2688        window: &mut Window,
2689        cx: &mut App,
2690    ) -> Option<Arc<RenderImage>> {
2691        ImageSource::Image(self)
2692            .use_data(None, window, cx)
2693            .and_then(|result| result.ok())
2694    }
2695
2696    /// Use the GPUI `get_asset` API to make this image renderable
2697    pub fn get_render_image(
2698        self: Arc<Self>,
2699        window: &mut Window,
2700        cx: &mut App,
2701    ) -> Option<Arc<RenderImage>> {
2702        ImageSource::Image(self)
2703            .get_data(None, window, cx)
2704            .and_then(|result| result.ok())
2705    }
2706
2707    /// Use the GPUI `remove_asset` API to drop this image, if possible.
2708    pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
2709        ImageSource::Image(self).remove_asset(cx);
2710    }
2711
2712    /// Check whether this image is present in GPUI's asset cache (loading or
2713    /// loaded), without fetching it.
2714    #[cfg(any(test, feature = "test-support"))]
2715    pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
2716        ImageSource::Image(self.clone()).is_asset_cached(cx)
2717    }
2718
2719    /// Convert the clipboard image to an `ImageData` object.
2720    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
2721        let frames = match self.format {
2722            ImageFormat::Gif => {
2723                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
2724                let mut frames = SmallVec::new();
2725
2726                for frame in decoder.into_frames() {
2727                    match frame {
2728                        Ok(mut frame) => {
2729                            // Convert from RGBA to BGRA.
2730                            for pixel in frame.buffer_mut().chunks_exact_mut(4) {
2731                                pixel.swap(0, 2);
2732                            }
2733                            frames.push(frame);
2734                        }
2735                        Err(err) => {
2736                            log::debug!("Skipping GIF frame due to decode error: {err}");
2737                        }
2738                    }
2739                }
2740
2741                if frames.is_empty() {
2742                    anyhow::bail!("GIF could not be decoded: all frames failed");
2743                }
2744
2745                frames
2746            }
2747            ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
2748            ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
2749            ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
2750            ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
2751            ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
2752            ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
2753            ImageFormat::Svg => {
2754                return svg_renderer
2755                    .render_single_frame(&self.bytes, 1.0)
2756                    .map_err(Into::into);
2757            }
2758            ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
2759        };
2760
2761        Ok(Arc::new(RenderImage::new(frames)))
2762    }
2763
2764    /// Get the format of the clipboard image
2765    pub fn format(&self) -> ImageFormat {
2766        self.format
2767    }
2768
2769    /// Get the raw bytes of the clipboard image
2770    pub fn bytes(&self) -> &[u8] {
2771        self.bytes.as_slice()
2772    }
2773}
2774
2775/// A clipboard item that should be copied to the clipboard
2776#[derive(Clone, Debug, Eq, PartialEq)]
2777pub struct ClipboardString {
2778    /// The text content.
2779    pub text: String,
2780    /// Optional metadata associated with this clipboard string.
2781    pub metadata: Option<String>,
2782}
2783
2784impl ClipboardString {
2785    /// Create a new clipboard string with the given text
2786    pub fn new(text: String) -> Self {
2787        Self {
2788            text,
2789            metadata: None,
2790        }
2791    }
2792
2793    /// Return a new clipboard item with the metadata replaced by the given metadata,
2794    /// after serializing it as JSON.
2795    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
2796        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
2797        self
2798    }
2799
2800    /// Get the text of the clipboard string
2801    pub fn text(&self) -> &String {
2802        &self.text
2803    }
2804
2805    /// Get the owned text of the clipboard string
2806    pub fn into_text(self) -> String {
2807        self.text
2808    }
2809
2810    /// Get the metadata of the clipboard string, formatted as JSON
2811    pub fn metadata_json<T>(&self) -> Option<T>
2812    where
2813        T: for<'a> Deserialize<'a>,
2814    {
2815        self.metadata
2816            .as_ref()
2817            .and_then(|m| serde_json::from_str(m).ok())
2818    }
2819
2820    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2821    /// Compute a hash of the given text for clipboard change detection.
2822    pub fn text_hash(text: &str) -> u64 {
2823        let mut hasher = SeaHasher::new();
2824        text.hash(&mut hasher);
2825        hasher.finish()
2826    }
2827}
2828
2829impl From<String> for ClipboardString {
2830    fn from(value: String) -> Self {
2831        Self {
2832            text: value,
2833            metadata: None,
2834        }
2835    }
2836}
2837
2838#[cfg(test)]
2839mod image_tests {
2840    use super::*;
2841    use std::sync::Arc;
2842
2843    #[test]
2844    fn test_image_to_image_data_applies_exif_orientation() {
2845        let image = Image::from_bytes(
2846            ImageFormat::Jpeg,
2847            include_bytes!("test_data/exif-orientation-rotate-180.jpg").to_vec(),
2848        );
2849
2850        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
2851
2852        assert_eq!(render_image.size(0), size(16.into(), 32.into()));
2853
2854        let bytes = render_image.as_bytes(0).unwrap();
2855        assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
2856        assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
2857    }
2858
2859    #[test]
2860    fn test_svg_image_to_image_data_converts_to_bgra() {
2861        let image = Image::from_bytes(
2862            ImageFormat::Svg,
2863            br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
2864<rect width="1" height="1" fill="#38BDF8"/>
2865</svg>"##
2866                .to_vec(),
2867        );
2868
2869        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
2870        let bytes = render_image.as_bytes(0).unwrap();
2871
2872        for pixel in bytes.chunks_exact(4) {
2873            assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
2874        }
2875    }
2876}
2877
2878#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
2879mod tests {
2880    use super::*;
2881    use std::collections::HashSet;
2882
2883    #[test]
2884    fn test_window_button_layout_parse_standard() {
2885        let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
2886        assert_eq!(
2887            layout.left,
2888            [
2889                Some(WindowButton::Close),
2890                Some(WindowButton::Minimize),
2891                None
2892            ]
2893        );
2894        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2895    }
2896
2897    #[test]
2898    fn test_window_button_layout_parse_right_only() {
2899        let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
2900        assert_eq!(layout.left, [None, None, None]);
2901        assert_eq!(
2902            layout.right,
2903            [
2904                Some(WindowButton::Minimize),
2905                Some(WindowButton::Maximize),
2906                Some(WindowButton::Close)
2907            ]
2908        );
2909    }
2910
2911    #[test]
2912    fn test_window_button_layout_parse_left_only() {
2913        let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
2914        assert_eq!(
2915            layout.left,
2916            [
2917                Some(WindowButton::Close),
2918                Some(WindowButton::Minimize),
2919                Some(WindowButton::Maximize)
2920            ]
2921        );
2922        assert_eq!(layout.right, [None, None, None]);
2923    }
2924
2925    #[test]
2926    fn test_window_button_layout_parse_with_whitespace() {
2927        let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
2928        assert_eq!(
2929            layout.left,
2930            [
2931                Some(WindowButton::Close),
2932                Some(WindowButton::Minimize),
2933                None
2934            ]
2935        );
2936        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2937    }
2938
2939    #[test]
2940    fn test_window_button_layout_parse_empty() {
2941        let layout = WindowButtonLayout::parse("").unwrap();
2942        assert_eq!(layout.left, [None, None, None]);
2943        assert_eq!(layout.right, [None, None, None]);
2944    }
2945
2946    #[test]
2947    fn test_window_button_layout_parse_intentionally_empty() {
2948        let layout = WindowButtonLayout::parse(":").unwrap();
2949        assert_eq!(layout.left, [None, None, None]);
2950        assert_eq!(layout.right, [None, None, None]);
2951    }
2952
2953    #[test]
2954    fn test_window_button_layout_parse_invalid_buttons() {
2955        let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
2956        assert_eq!(
2957            layout.left,
2958            [
2959                Some(WindowButton::Close),
2960                Some(WindowButton::Minimize),
2961                None
2962            ]
2963        );
2964        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2965    }
2966
2967    #[test]
2968    fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
2969        let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
2970        assert_eq!(
2971            layout.right,
2972            [
2973                Some(WindowButton::Close),
2974                Some(WindowButton::Minimize),
2975                None
2976            ]
2977        );
2978        assert_eq!(layout.format(), ":close,minimize");
2979    }
2980
2981    #[test]
2982    fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
2983        let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
2984        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
2985        assert_eq!(
2986            layout.right,
2987            [
2988                Some(WindowButton::Maximize),
2989                Some(WindowButton::Minimize),
2990                None
2991            ]
2992        );
2993
2994        let button_ids: Vec<_> = layout
2995            .left
2996            .iter()
2997            .chain(layout.right.iter())
2998            .flatten()
2999            .map(WindowButton::id)
3000            .collect();
3001        let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
3002        assert_eq!(unique_button_ids.len(), button_ids.len());
3003        assert_eq!(layout.format(), "close:maximize,minimize");
3004    }
3005
3006    #[test]
3007    fn test_window_button_layout_parse_gnome_style() {
3008        let layout = WindowButtonLayout::parse("close").unwrap();
3009        assert_eq!(layout.left, [None, None, None]);
3010        assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
3011    }
3012
3013    #[test]
3014    fn test_window_button_layout_parse_elementary_style() {
3015        let layout = WindowButtonLayout::parse("close:maximize").unwrap();
3016        assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3017        assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3018    }
3019
3020    #[test]
3021    fn test_window_button_layout_round_trip() {
3022        let cases = [
3023            "close:minimize,maximize",
3024            "minimize,maximize,close:",
3025            ":close",
3026            "close:",
3027            "close:maximize",
3028            ":",
3029        ];
3030
3031        for case in cases {
3032            let layout = WindowButtonLayout::parse(case).unwrap();
3033            assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
3034        }
3035    }
3036
3037    #[test]
3038    fn test_window_button_layout_linux_default() {
3039        let layout = WindowButtonLayout::linux_default();
3040        assert_eq!(layout.left, [None, None, None]);
3041        assert_eq!(
3042            layout.right,
3043            [
3044                Some(WindowButton::Minimize),
3045                Some(WindowButton::Maximize),
3046                Some(WindowButton::Close)
3047            ]
3048        );
3049
3050        let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
3051        assert_eq!(round_tripped, layout);
3052    }
3053
3054    #[test]
3055    fn test_window_button_layout_parse_all_invalid() {
3056        assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
3057    }
3058}
3059
3060#[cfg(test)]
3061mod file_clipboard_tests {
3062    use super::*;
3063
3064    #[test]
3065    fn invalid_file_lists_are_rejected() {
3066        for names in [vec![], vec!["relative"], vec!["/tmp/nul\0file"]] {
3067            let paths = crate::ExternalPaths(names.into_iter().map(PathBuf::from).collect());
3068            assert!(matches!(
3069                paths.validate_for_clipboard(),
3070                Err(FileClipboardError::InvalidPaths)
3071            ));
3072        }
3073    }
3074
3075    #[test]
3076    #[cfg(unix)]
3077    fn file_mime_payloads_escape_unicode_and_record_intent() {
3078        let paths = crate::ExternalPaths(
3079            ["/tmp/\u{65e5}\u{672c}\u{8a9e} #%.txt", "/tmp/line\nbreak"]
3080                .into_iter()
3081                .map(PathBuf::from)
3082                .collect(),
3083        );
3084        let uris = paths.clipboard_uri_list().unwrap();
3085        assert!(uris.contains("%20%23%25.txt\r\n"));
3086        assert!(uris.contains("line%0Abreak\r\n"));
3087        let decoded: Vec<_> = uris
3088            .lines()
3089            .map(|line| url::Url::parse(line).unwrap().to_file_path().unwrap())
3090            .collect();
3091        assert_eq!(decoded, paths.paths());
3092        assert_eq!(
3093            paths
3094                .clipboard_gnome_files(FileClipboardOperation::Copy)
3095                .unwrap(),
3096            format!("copy\n{}", uris.trim_end().replace("\r\n", "\n"))
3097        );
3098        assert!(
3099            paths
3100                .clipboard_gnome_files(FileClipboardOperation::Move)
3101                .unwrap()
3102                .starts_with("cut\n")
3103        );
3104    }
3105
3106    #[crate::test]
3107    fn unsupported_backend_preserves_existing_clipboard(cx: &mut crate::TestAppContext) {
3108        cx.update(|cx| {
3109            let original = ClipboardItem::new_string("keep".into());
3110            cx.write_to_clipboard(original.clone());
3111            assert!(!cx.supports_file_clipboard(FileClipboardOperation::Copy));
3112            let paths = crate::ExternalPaths(Default::default());
3113            assert!(matches!(
3114                cx.write_files_to_clipboard(paths, FileClipboardOperation::Copy),
3115                Err(FileClipboardError::Unsupported)
3116            ));
3117            assert_eq!(cx.read_from_clipboard(), Some(original));
3118        });
3119    }
3120}
3121
3122#[cfg(test)]
3123mod async_clipboard_tests {
3124    use super::*;
3125
3126    #[crate::test]
3127    async fn asynchronous_text_read_captures_test_clipboard_and_preserves_writes(
3128        cx: &mut crate::TestAppContext,
3129    ) {
3130        let text = "日本語🙂e\u{301}\r\n".repeat(20_000);
3131        let read = cx.update(|cx| {
3132            cx.write_to_clipboard(ClipboardItem::new_string(text.clone()));
3133            cx.read_text_from_clipboard_async()
3134        });
3135        cx.write_to_clipboard(ClipboardItem::new_string("later".into()));
3136        assert_eq!(read.await, Some(text));
3137        assert_eq!(
3138            cx.read_from_clipboard()
3139                .and_then(|item| item.text())
3140                .as_deref(),
3141            Some("later")
3142        );
3143        let read = cx.update(|cx| cx.read_text_from_clipboard_async());
3144        drop(read);
3145        cx.run_until_parked();
3146        assert_eq!(
3147            cx.read_from_clipboard()
3148                .and_then(|item| item.text())
3149                .as_deref(),
3150            Some("later")
3151        );
3152    }
3153
3154    #[crate::test]
3155    async fn asynchronous_text_read_ignores_empty_and_nontext_items(
3156        cx: &mut crate::TestAppContext,
3157    ) {
3158        for item in [
3159            ClipboardItem::new_string(String::new()),
3160            ClipboardItem {
3161                entries: vec![ClipboardEntry::ExternalPaths(crate::ExternalPaths(
3162                    smallvec::smallvec!["file.txt".into()],
3163                ))],
3164            },
3165        ] {
3166            let read = cx.update(|cx| {
3167                cx.write_to_clipboard(item);
3168                cx.read_text_from_clipboard_async()
3169            });
3170            assert_eq!(read.await, None);
3171        }
3172    }
3173}