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