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