Skip to main content

gpui_core/
platform.rs

1mod app_menu;
2mod keyboard;
3mod keystroke;
4/// Wayland layer-shell window configuration.
5#[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "wayland"))]
6pub mod layer_shell;
7/// Cross-platform single instance enforcement using Unix domain sockets and Windows named mutexes.
8pub mod single_instance;
9/// Pure Rust utility for computing window bounds from a semantic [`WindowPosition`].
10pub mod window_positioner;
11
12#[cfg(all(
13    feature = "screen-capture",
14    any(target_os = "linux", target_os = "freebsd")
15))]
16type PlatformScreenCaptureFrame = scap::frame::Frame;
17#[cfg(all(
18    any(target_os = "linux", target_os = "freebsd"),
19    not(feature = "screen-capture")
20))]
21type PlatformScreenCaptureFrame = ();
22
23#[cfg(target_os = "macos")]
24type PlatformScreenCaptureFrame = core_video::image_buffer::CVImageBuffer;
25
26#[cfg(all(target_os = "windows", feature = "screen-capture"))]
27type PlatformScreenCaptureFrame = scap::frame::Frame;
28#[cfg(all(target_os = "windows", not(feature = "screen-capture")))]
29type PlatformScreenCaptureFrame = ();
30
31#[cfg(any(test, feature = "test-support"))]
32#[doc(hidden)]
33#[allow(missing_docs)]
34pub mod render_image;
35
36#[cfg(any(test, feature = "test-support"))]
37mod test;
38#[cfg(any(test, feature = "test-support"))]
39mod threaded_dispatcher;
40
41#[cfg(all(
42    feature = "screen-capture",
43    any(
44        target_os = "windows",
45        all(
46            any(target_os = "linux", target_os = "freebsd"),
47            any(feature = "wayland", feature = "x11"),
48        )
49    )
50))]
51/// Shared screen-capture implementation used by desktop backends.
52#[doc(hidden)]
53pub mod scap_screen_capture;
54
55use crate::{
56    Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
57    DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun,
58    ForegroundExecutor, GlyphId, GpuResourceBudget, GpuSpecs, Hsla, ImageSource, Keymap,
59    LineLayout, MissingGlyphSink, Pixels, PlatformInput, Point, QuitMode, RenderGlyphParams,
60    RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString,
61    Size, SvgRenderer, SystemWindowTab, Task, TaskLabel, Window, WindowControlArea, hash, point,
62    px, size,
63};
64use anyhow::{Context as _, Result};
65use async_task::Runnable;
66use futures::channel::oneshot;
67#[cfg(feature = "image-format-gif")]
68use image::AnimationDecoder as _;
69#[cfg(feature = "image-format-gif")]
70use image::codecs::gif::GifDecoder;
71use image::{DynamicImage, Frame};
72use parking::Unparker;
73use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
74use schemars::JsonSchema;
75use seahash::SeaHasher;
76use serde::{Deserialize, Serialize};
77use smallvec::SmallVec;
78use std::borrow::Cow;
79use std::hash::{Hash, Hasher};
80use std::io::Cursor;
81use std::ops;
82use std::time::{Duration, Instant};
83use std::{
84    ffi::OsString,
85    fmt::{self, Debug},
86    ops::Range,
87    path::{Path, PathBuf},
88    rc::Rc,
89    sync::Arc,
90};
91use strum::EnumIter;
92use uuid::Uuid;
93
94pub use app_menu::*;
95pub use keyboard::*;
96pub use keystroke::*;
97
98pub use semantic_version::SemanticVersion;
99#[cfg(any(test, feature = "test-support"))]
100pub(crate) use test::*;
101
102/// Keeps an operating system activity, such as an idle sleep inhibitor, alive until dropped.
103pub struct ActivityGuard {
104    _release: util::Deferred<Box<dyn FnOnce() + Send>>,
105}
106
107impl std::fmt::Debug for ActivityGuard {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.debug_struct("ActivityGuard").finish_non_exhaustive()
110    }
111}
112
113impl ActivityGuard {
114    /// Runs `release` when the guard is dropped.
115    pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
116        Self {
117            _release: util::defer(Box::new(release)),
118        }
119    }
120
121    /// A guard for platforms without a corresponding activity.
122    pub fn noop() -> Self {
123        Self::new(|| {})
124    }
125}
126
127#[cfg(any(test, feature = "test-support"))]
128pub use test::{
129    TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream, VisualRenderArtifact,
130};
131#[cfg(any(test, feature = "test-support"))]
132pub use threaded_dispatcher::ThreadedDispatcher;
133
134#[cfg(all(
135    any(test, feature = "test-support"),
136    any(
137        target_os = "macos",
138        target_os = "linux",
139        target_os = "freebsd",
140        target_os = "windows"
141    )
142))]
143#[doc(hidden)]
144pub use test::VisualTestPlatform;
145
146/// Returns which Linux compositor the environment indicates without connecting to it.
147#[cfg(any(target_os = "linux", target_os = "freebsd"))]
148#[inline]
149pub fn guess_compositor() -> &'static str {
150    if std::env::var_os("ZED_HEADLESS").is_some() {
151        return "Headless";
152    }
153
154    #[cfg(feature = "wayland")]
155    let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
156    #[cfg(not(feature = "wayland"))]
157    let wayland_display: Option<std::ffi::OsString> = None;
158
159    #[cfg(feature = "x11")]
160    let x11_display = std::env::var_os("DISPLAY");
161    #[cfg(not(feature = "x11"))]
162    let x11_display: Option<std::ffi::OsString> = None;
163
164    let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
165    let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
166
167    if use_wayland {
168        "Wayland"
169    } else if use_x11 {
170        "X11"
171    } else {
172        "Headless"
173    }
174}
175
176/// Snapshot of the renderer's pooled GPU resource usage.
177///
178/// Returned by [`App::renderer_cache_stats`]. Use together with
179/// [`App::trim_gpu_caches`] to decide whether reclaiming idle GPU memory is
180/// worthwhile. This is a best-effort diagnostic snapshot; platforms that do
181/// not maintain trimmable GPU pools report zero.
182#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
183#[non_exhaustive]
184pub struct RendererCacheStats {
185    /// Number of idle GPU instance buffers held by the renderer pool.
186    pub idle_gpu_buffers: usize,
187    /// Configured size in bytes of each pooled GPU instance buffer.
188    pub gpu_buffer_size_bytes: usize,
189}
190
191impl RendererCacheStats {
192    /// Creates a renderer cache snapshot from backend pool counters.
193    #[doc(hidden)]
194    pub fn new(idle_gpu_buffers: usize, gpu_buffer_size_bytes: usize) -> Self {
195        Self {
196            idle_gpu_buffers,
197            gpu_buffer_size_bytes,
198        }
199    }
200}
201
202/// Low-level operating-system integration contract implemented by GPUI backends.
203#[allow(missing_docs)]
204pub trait Platform: 'static {
205    fn background_executor(&self) -> BackgroundExecutor;
206    fn foreground_executor(&self) -> ForegroundExecutor;
207    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
208
209    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
210    fn quit(&self);
211    fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
212    fn activate(&self, ignoring_other_apps: bool);
213    fn hide(&self);
214    fn hide_other_apps(&self);
215    fn unhide_other_apps(&self);
216
217    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
218    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
219    fn active_window(&self) -> Option<AnyWindowHandle>;
220    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
221        None
222    }
223
224    #[cfg(feature = "screen-capture")]
225    fn is_screen_capture_supported(&self) -> bool;
226    #[cfg(not(feature = "screen-capture"))]
227    fn is_screen_capture_supported(&self) -> bool {
228        false
229    }
230    #[cfg(feature = "screen-capture")]
231    fn screen_capture_sources(&self)
232    -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>>;
233    #[cfg(not(feature = "screen-capture"))]
234    fn screen_capture_sources(
235        &self,
236    ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
237        let (sources_tx, sources_rx) = oneshot::channel();
238        sources_tx
239            .send(Err(anyhow::anyhow!(
240                "gpui was compiled without the screen-capture feature"
241            )))
242            .ok();
243        sources_rx
244    }
245
246    fn open_window(
247        &self,
248        handle: AnyWindowHandle,
249        options: WindowParams,
250    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
251
252    /// Drop any idle GPU buffers held by the renderer's pools, retaining
253    /// configuration. Default implementation is a no-op for platforms that do
254    /// not maintain such pools.
255    fn trim_renderer_caches(&self) {}
256
257    /// Apply renderer GPU resource budgets. Default implementation is a no-op
258    /// for platforms that do not expose configurable renderer pools.
259    fn configure_gpu_resources(&self, _gpu: &GpuResourceBudget) {}
260
261    /// Snapshot of the renderer's pooled GPU resource usage. Default
262    /// implementation reports an empty snapshot for platforms that do not
263    /// maintain such pools.
264    fn renderer_cache_stats(&self) -> RendererCacheStats {
265        RendererCacheStats::default()
266    }
267
268    /// Returns the appearance of the application's windows.
269    fn window_appearance(&self) -> WindowAppearance;
270
271    /// Overrides the appearance (light/dark) applied to the app's windows, independent
272    /// of the OS-wide setting. Pass `None` to clear the override and follow the system
273    /// again. The override is reflected by [`Platform::window_appearance`].
274    ///
275    /// On macOS this sets `NSApplication.appearance` so the native window chrome (the
276    /// window border and titlebar) of every window matches a dark app theme even when
277    /// the system is in light mode (or vice versa). Other backends store the override
278    /// for [`Platform::window_appearance`] without changing native chrome.
279    fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
280
281    fn open_url(&self, url: &str);
282    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
283    fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
284
285    fn prompt_for_paths(
286        &self,
287        options: PathPromptOptions,
288    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
289    fn prompt_for_new_path(
290        &self,
291        directory: &Path,
292        suggested_name: Option<&str>,
293    ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
294    fn can_select_mixed_files_and_dirs(&self) -> bool;
295    fn reveal_path(&self, path: &Path);
296    fn open_with_system(&self, path: &Path);
297
298    fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
299    fn on_reopen(&self, callback: Box<dyn FnMut()>);
300
301    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
302    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
303        None
304    }
305
306    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
307    fn perform_dock_menu_action(&self, _action: usize) {}
308    fn add_recent_document(&self, _path: &Path) {}
309    fn update_jump_list(
310        &self,
311        _menus: Vec<MenuItem>,
312        _entries: Vec<SmallVec<[PathBuf; 2]>>,
313    ) -> Vec<SmallVec<[PathBuf; 2]>> {
314        Vec::new()
315    }
316    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
317    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
318    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
319
320    fn thermal_state(&self) -> ThermalState {
321        ThermalState::Nominal
322    }
323    fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
324
325    /// Prevents idle sleep while the returned guard is held.
326    ///
327    /// Dropping the guard restores the previous sleep policy.
328    fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
329
330    fn compositor_name(&self) -> &'static str {
331        ""
332    }
333    fn app_path(&self) -> Result<PathBuf>;
334    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
335
336    fn set_cursor_style(&self, style: CursorStyle);
337    fn should_auto_hide_scrollbars(&self) -> bool;
338
339    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
340    fn write_to_primary(&self, item: ClipboardItem);
341    fn write_to_clipboard(&self, item: ClipboardItem);
342    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
343    fn read_from_primary(&self) -> Option<ClipboardItem>;
344    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
345
346    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
347    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
348    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
349
350    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
351    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
352    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
353
354    fn set_tray_icon(&self, _icon: Option<&[u8]>) {}
355    fn set_tray_icon_rendering_mode(&self, _rendering_mode: TrayIconRenderingMode) {}
356    fn set_tray_menu(&self, _menu: Vec<TrayMenuItem>) {}
357    fn set_tray_tooltip(&self, _tooltip: &str) {}
358    fn set_tray_panel_mode(&self, _enabled: bool) {}
359    fn get_tray_icon_anchor(&self) -> Option<TrayAnchor> {
360        None
361    }
362    fn get_tray_icon_bounds(&self) -> Option<Bounds<Pixels>> {
363        None
364    }
365    fn on_tray_icon_event(&self, mut callback: Box<dyn FnMut(TrayIconEvent)>) {
366        self.on_tray_icon_click_event(Box::new(move |event| callback(event.kind)));
367    }
368    fn on_tray_icon_click_event(&self, _callback: Box<dyn FnMut(TrayIconClickEvent)>) {}
369    fn on_tray_menu_action(&self, _callback: Box<dyn FnMut(SharedString)>) {}
370
371    fn register_global_hotkey(&self, _id: u32, _keystroke: &Keystroke) -> Result<()> {
372        Err(anyhow::anyhow!(
373            "Global hotkeys not supported on this platform"
374        ))
375    }
376    fn unregister_global_hotkey(&self, _id: u32) {}
377    fn on_global_hotkey(&self, _callback: Box<dyn FnMut(u32)>) {}
378
379    fn focused_window_info(&self) -> Option<FocusedWindowInfo> {
380        None
381    }
382
383    fn accessibility_status(&self) -> PermissionStatus {
384        PermissionStatus::Unavailable
385    }
386    fn request_accessibility_permission(&self) -> PermissionRequestStatus {
387        PermissionRequestStatus::Unavailable
388    }
389
390    fn microphone_status(&self) -> PermissionStatus {
391        PermissionStatus::Unavailable
392    }
393    fn request_microphone_permission(
394        &self,
395        callback: Box<dyn FnOnce(bool)>,
396    ) -> PermissionRequestStatus {
397        callback(false);
398        PermissionRequestStatus::Unavailable
399    }
400
401    fn set_auto_launch(&self, _app_id: &str, _enabled: bool) -> Result<()> {
402        Err(anyhow::anyhow!(
403            "Auto-launch not supported on this platform"
404        ))
405    }
406    fn is_auto_launch_enabled(&self, _app_id: &str) -> bool {
407        false
408    }
409
410    fn show_notification(&self, _title: &str, _body: &str) -> Result<()> {
411        Err(anyhow::anyhow!(
412            "Notifications not supported on this platform"
413        ))
414    }
415
416    /// Receive the application's configured [`QuitMode`].
417    ///
418    /// The core application state owns the actual lifecycle decision; platforms
419    /// only need this hook when quit mode carries a platform-visible side
420    /// effect (for example macOS `ActivationPolicy`). The default
421    /// implementation is a no-op.
422    fn set_quit_mode(&self, _mode: QuitMode) {}
423
424    fn on_system_power_event(&self, _callback: Box<dyn FnMut(SystemPowerEvent)>) {}
425    fn start_power_save_blocker(&self, _kind: PowerSaveBlockerKind) -> Option<u32> {
426        None
427    }
428    fn stop_power_save_blocker(&self, _id: u32) {}
429    fn system_idle_time(&self) -> Option<Duration> {
430        None
431    }
432    fn network_status(&self) -> NetworkStatus {
433        NetworkStatus::Online
434    }
435    fn on_network_status_change(&self, _callback: Box<dyn FnMut(NetworkStatus)>) {}
436    fn on_media_key_event(&self, _callback: Box<dyn FnMut(MediaKeyEvent)>) {}
437    fn request_user_attention(&self, _attention_type: AttentionType) {}
438    fn cancel_user_attention(&self) {}
439    fn set_dock_badge(&self, _label: Option<&str>) {}
440    fn show_context_menu(
441        &self,
442        _position: Point<Pixels>,
443        _items: Vec<TrayMenuItem>,
444        _callback: Box<dyn FnMut(SharedString)>,
445    ) {
446    }
447    fn show_dialog(&self, _options: DialogOptions) -> oneshot::Receiver<usize> {
448        let (tx, rx) = oneshot::channel();
449        tx.send(0).ok();
450        rx
451    }
452    fn os_info(&self) -> OsInfo {
453        OsInfo {
454            name: std::env::consts::OS.into(),
455            arch: std::env::consts::ARCH.into(),
456            version: String::new().into(),
457            locale: String::new().into(),
458            hostname: String::new().into(),
459        }
460    }
461    fn biometric_status(&self) -> BiometricStatus {
462        BiometricStatus::Unavailable
463    }
464    fn authenticate_biometric(&self, _reason: &str, callback: Box<dyn FnOnce(bool) + Send>) {
465        callback(false);
466    }
467}
468
469/// A handle to a platform's display, e.g. a monitor or laptop screen.
470pub trait PlatformDisplay: Send + Sync + Debug {
471    /// Get the ID for this display
472    fn id(&self) -> DisplayId;
473
474    /// Returns a stable identifier for this display that can be persisted and used
475    /// across system restarts.
476    fn uuid(&self) -> Result<Uuid>;
477
478    /// Get the bounds for this display
479    fn bounds(&self) -> Bounds<Pixels>;
480
481    /// Get the visible bounds for this display, excluding taskbar/dock areas.
482    /// Defaults to the full display bounds if the platform does not expose a
483    /// separate work area.
484    fn visible_bounds(&self) -> Bounds<Pixels> {
485        self.bounds()
486    }
487
488    /// Get the default bounds for this display to place a window
489    fn default_bounds(&self) -> Bounds<Pixels> {
490        let bounds = self.visible_bounds();
491        let center = bounds.center();
492        let window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
493        let offset = window_size / 2.0;
494        let origin = point(center.x - offset.width, center.y - offset.height);
495        Bounds::new(origin, window_size)
496    }
497}
498
499/// Thermal state of the system.
500#[derive(Debug, Clone, Copy, PartialEq, Eq)]
501pub enum ThermalState {
502    /// System has no thermal constraints.
503    Nominal,
504    /// System is slightly constrained, reduce discretionary work.
505    Fair,
506    /// System is moderately constrained, reduce CPU/GPU intensive work.
507    Serious,
508    /// System is critically constrained, minimize all resource usage.
509    Critical,
510}
511
512/// Metadata for a given [ScreenCaptureSource]
513#[derive(Clone)]
514pub struct SourceMetadata {
515    /// Opaque identifier of this screen.
516    pub id: u64,
517    /// Human-readable label for this source.
518    pub label: Option<SharedString>,
519    /// Whether this source is the main display.
520    pub is_main: Option<bool>,
521    /// Video resolution of this source.
522    pub resolution: Size<DevicePixels>,
523}
524
525/// A source of on-screen video content that can be captured.
526pub trait ScreenCaptureSource {
527    /// Returns metadata for this source.
528    fn metadata(&self) -> Result<SourceMetadata>;
529
530    /// Start capture video from this source, invoking the given callback
531    /// with each frame.
532    fn stream(
533        &self,
534        foreground_executor: &ForegroundExecutor,
535        frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
536    ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
537
538    /// Starts capture and reports its terminal state.
539    ///
540    /// Startup failures are returned through the receiver. Implementations
541    /// invoke `termination_callback` exactly once after a started stream ends,
542    /// is cancelled, or fails.
543    fn stream_with_termination(
544        &self,
545        _foreground_executor: &ForegroundExecutor,
546        _frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
547        _termination_callback: ScreenCaptureTerminationCallback,
548    ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>> {
549        let (mut sender, receiver) = oneshot::channel();
550        sender
551            .send(Err(anyhow::anyhow!(
552                "runtime termination notification is not supported by this screen capture source"
553            )))
554            .ok();
555        receiver
556    }
557}
558
559/// Receives a single terminal state from a started screen-capture stream.
560pub type ScreenCaptureTerminationCallback = Box<dyn FnOnce(ScreenCaptureStreamTermination) + Send>;
561
562/// The terminal state of a started screen-capture stream.
563#[derive(Debug, Clone, PartialEq, Eq)]
564pub enum ScreenCaptureStreamTermination {
565    /// The stream completed without an error.
566    Ended,
567    /// The stream was cancelled before completion.
568    Cancelled,
569    /// The stream ended because capture failed at runtime.
570    Failed(SharedString),
571}
572
573/// A video stream captured from a screen.
574pub trait ScreenCaptureStream {
575    /// Returns metadata for this source.
576    fn metadata(&self) -> Result<SourceMetadata>;
577}
578
579/// A frame of video captured from a screen.
580pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
581
582/// An opaque identifier for a hardware display
583#[derive(PartialEq, Eq, Hash, Copy, Clone)]
584pub struct DisplayId(pub(crate) u64);
585
586impl DisplayId {
587    /// Creates a display identifier from a raw platform display value.
588    #[doc(hidden)]
589    pub fn new(id: u64) -> Self {
590        Self(id)
591    }
592
593    /// Returns this identifier as a zero-based platform display index.
594    #[doc(hidden)]
595    pub fn index(self) -> usize {
596        self.0 as usize
597    }
598}
599
600impl From<u32> for DisplayId {
601    fn from(id: u32) -> Self {
602        Self(u64::from(id))
603    }
604}
605
606impl From<DisplayId> for u32 {
607    fn from(id: DisplayId) -> Self {
608        id.0 as u32
609    }
610}
611
612impl From<DisplayId> for u64 {
613    fn from(id: DisplayId) -> Self {
614        id.0
615    }
616}
617
618impl Debug for DisplayId {
619    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620        write!(f, "DisplayId({})", self.0)
621    }
622}
623
624unsafe impl Send for DisplayId {}
625
626/// Which part of the window to resize
627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
628pub enum ResizeEdge {
629    /// The top edge
630    Top,
631    /// The top right corner
632    TopRight,
633    /// The right edge
634    Right,
635    /// The bottom right corner
636    BottomRight,
637    /// The bottom edge
638    Bottom,
639    /// The bottom left corner
640    BottomLeft,
641    /// The left edge
642    Left,
643    /// The top left corner
644    TopLeft,
645}
646
647/// A type to describe the appearance of a window
648#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
649pub enum WindowDecorations {
650    #[default]
651    /// Server side decorations
652    Server,
653    /// Client side decorations
654    Client,
655}
656
657/// A type to describe how this window is currently configured
658#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
659pub enum Decorations {
660    /// The window is configured to use server side decorations
661    #[default]
662    Server,
663    /// The window is configured to use client side decorations
664    Client {
665        /// The edge tiling state
666        tiling: Tiling,
667    },
668}
669
670/// What window controls this platform supports
671#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
672pub struct WindowControls {
673    /// Whether this platform supports fullscreen
674    pub fullscreen: bool,
675    /// Whether this platform supports maximize
676    pub maximize: bool,
677    /// Whether this platform supports minimize
678    pub minimize: bool,
679    /// Whether this platform supports a window menu
680    pub window_menu: bool,
681}
682
683impl Default for WindowControls {
684    fn default() -> Self {
685        // Assume that we can do anything, unless told otherwise
686        Self {
687            fullscreen: true,
688            maximize: true,
689            minimize: true,
690            window_menu: true,
691        }
692    }
693}
694
695/// A type to describe which sides of the window are currently tiled in some way
696#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
697pub struct Tiling {
698    /// Whether the top edge is tiled
699    pub top: bool,
700    /// Whether the left edge is tiled
701    pub left: bool,
702    /// Whether the right edge is tiled
703    pub right: bool,
704    /// Whether the bottom edge is tiled
705    pub bottom: bool,
706}
707
708impl Tiling {
709    /// Initializes a [`Tiling`] type with all sides tiled
710    pub fn tiled() -> Self {
711        Self {
712            top: true,
713            left: true,
714            right: true,
715            bottom: true,
716        }
717    }
718
719    /// Whether any edge is tiled
720    pub fn is_tiled(&self) -> bool {
721        self.top || self.left || self.right || self.bottom
722    }
723}
724
725#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
726#[allow(missing_docs)]
727pub struct RequestFrameOptions {
728    pub require_presentation: bool,
729    /// Force refresh of all rendering states when true
730    pub force_render: bool,
731}
732
733/// Callbacks for the accessibility adapter.
734pub struct A11yCallbacks {
735    /// Called when the adapter is activated.
736    pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
737    /// Called when an action is requested by the screen reader.
738    pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
739    /// Called when the adapter is deactivated.
740    pub deactivation: Box<dyn Fn() + Send + 'static>,
741}
742
743/// Whether the platform is presenting a window's frames.
744///
745/// This is about presentation, not the window's shown/hidden state: a shown
746/// window that is fully covered by other windows, minimized, on another
747/// Space or virtual desktop, or on a display that is asleep is `Hidden`. A
748/// window only partly covered by other windows is `Visible`.
749///
750/// Each platform reports from a single source, and what that source can see
751/// differs:
752///
753/// * macOS: `NSWindow.occlusionState`. Covers all of the cases above.
754/// * Windows: `WS_VISIBLE` and the minimized state. Windows keeps compositing
755///   covered windows for thumbnails and Alt-Tab and offers no occlusion
756///   notification, so a fully covered window stays `Visible`. Display sleep is
757///   not reported either.
758/// * Wayland: the `xdg_toplevel` `suspended` state (xdg-shell v6). Compositors
759///   that don't support it never report `Hidden`.
760/// * X11: mapped state plus `VisibilityNotify`. Compositing window managers
761///   generally never report a window as fully obscured, so covering is only
762///   detected without compositing.
763#[derive(Debug, Clone, Copy, PartialEq, Eq)]
764pub enum WindowVisibility {
765    /// At least part of the window is being presented; frames drawn for it
766    /// will be shown.
767    Visible,
768    /// No part of the window is being presented. The platform will not
769    /// request frames for it until it becomes visible again.
770    Hidden,
771}
772
773impl WindowVisibility {
774    /// Whether frames drawn for the window will be shown.
775    pub fn is_visible(self) -> bool {
776        self == Self::Visible
777    }
778}
779
780#[allow(missing_docs)]
781pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
782    fn bounds(&self) -> Bounds<Pixels>;
783    fn is_maximized(&self) -> bool;
784    fn window_bounds(&self) -> WindowBounds;
785    fn content_size(&self) -> Size<Pixels>;
786    fn resize(&mut self, size: Size<Pixels>);
787    /// Resizes the window to the given content size while keeping `anchor`
788    /// fixed on screen.
789    ///
790    /// Unlike [`Self::resize`], which keeps the window origin fixed (growing
791    /// right and down) and may animate the change, implementations must not
792    /// animate and must keep the anchored corner or edge at its on-screen
793    /// position. Useful for popup panels that grow away from the edge they
794    /// are attached to (e.g. a tray popup anchored under the menu bar).
795    ///
796    /// The default falls back to [`Self::resize`], ignoring the anchor.
797    fn resize_anchored(&mut self, size: Size<Pixels>, _anchor: ResizeAnchor) {
798        self.resize(size);
799    }
800    fn scale_factor(&self) -> f32;
801    fn appearance(&self) -> WindowAppearance;
802    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
803    fn mouse_position(&self) -> Point<Pixels>;
804    fn modifiers(&self) -> Modifiers;
805    fn capslock(&self) -> Capslock;
806    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
807    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
808    fn prompt(
809        &self,
810        level: PromptLevel,
811        msg: &str,
812        detail: Option<&str>,
813        answers: &[PromptButton],
814    ) -> Option<oneshot::Receiver<usize>>;
815    fn activate(&self);
816    /// Requests that the operating system draw attention to this window.
817    fn request_attention(&self) {}
818    fn is_active(&self) -> bool;
819    /// The current [`WindowVisibility`]. Read once when the window is created;
820    /// afterwards changes arrive through [`Self::on_visibility_change`].
821    fn visibility(&self) -> WindowVisibility;
822    fn is_hovered(&self) -> bool;
823    fn set_title(&mut self, title: &str);
824    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
825    fn minimize(&self);
826    fn zoom(&self);
827    fn toggle_fullscreen(&self);
828    fn is_fullscreen(&self) -> bool;
829    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
830    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
831    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
832    /// Registers the callback invoked when [`Self::visibility`] changes. Only
833    /// transitions are reported; the callback runs on the main thread outside
834    /// of any window update.
835    fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
836    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
837    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
838    fn on_moved(&self, callback: Box<dyn FnMut()>);
839    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
840    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
841    fn on_close(&self, callback: Box<dyn FnOnce()>);
842    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
843    fn draw(&self, scene: &Scene);
844    #[cfg(any(test, feature = "test-support"))]
845    fn render_to_image(&self, _scene: &Scene) -> anyhow::Result<image::RgbaImage> {
846        anyhow::bail!("render_to_image not implemented for this platform")
847    }
848    fn schedule_frame(&self) {}
849    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
850
851    // macOS specific methods
852    fn get_title(&self) -> String {
853        String::new()
854    }
855    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
856        None
857    }
858    fn tab_bar_visible(&self) -> bool {
859        false
860    }
861    fn set_edited(&mut self, _edited: bool) {}
862    fn toggle_simple_fullscreen(&self) {}
863    fn is_simple_fullscreen(&self) -> bool {
864        false
865    }
866    fn show_character_palette(&self) {}
867    fn titlebar_double_click(&self) {}
868    fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
869    fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
870    fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
871    fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
872    fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
873    fn merge_all_windows(&self) {}
874    fn move_tab_to_new_window(&self) {}
875    fn toggle_window_tab_overview(&self) {}
876    fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
877
878    fn native_window_state(&self) -> Option<Vec<u8>> {
879        None
880    }
881    fn restore_native_window_state(&self, _state: &[u8]) {}
882
883    #[cfg(target_os = "windows")]
884    fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
885
886    // Linux specific methods
887    fn inner_window_bounds(&self) -> WindowBounds {
888        self.window_bounds()
889    }
890    fn request_decorations(&self, _decorations: WindowDecorations) {}
891    fn show_window_menu(&self, _position: Point<Pixels>) {}
892    fn start_window_move(&self) {}
893    fn start_window_resize(&self, _edge: ResizeEdge) {}
894    fn set_exclusive_zone(&self, _zone: Pixels) {}
895    #[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "wayland"))]
896    fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
897    fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
898    fn window_decorations(&self) -> Decorations {
899        Decorations::Server
900    }
901    fn set_app_id(&mut self, _app_id: &str) {}
902    fn map_window(&mut self) -> anyhow::Result<()> {
903        Ok(())
904    }
905    fn window_controls(&self) -> WindowControls {
906        WindowControls::default()
907    }
908    fn set_client_inset(&self, _inset: Pixels) {}
909    fn gpu_specs(&self) -> Option<GpuSpecs>;
910
911    /// Drops idle pooled GPU resources owned by this window's renderer,
912    /// where supported. Called by [`crate::App::trim_gpu_caches`] in
913    /// addition to [`Platform::trim_renderer_caches`], which covers
914    /// renderers whose caches are shared across windows.
915    fn trim_renderer_caches(&self) {}
916
917    fn update_ime_position(&self, _bounds: Bounds<Pixels>);
918
919    fn play_system_bell(&self) {}
920
921    /// Initialize the accessibility adapter with callbacks.
922    fn a11y_init(&self, _callbacks: A11yCallbacks) {}
923
924    /// Provide a tree update to the accessibility adapter.
925    fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
926
927    /// Inform the adapter of updated window bounds.
928    fn a11y_update_window_bounds(&self) {}
929
930    fn show(&self) {}
931    fn hide(&self) {}
932    fn is_visible(&self) -> bool {
933        true
934    }
935    fn set_mouse_passthrough(&self, _passthrough: bool) {}
936    fn set_progress_bar(&self, _state: ProgressBarState) {}
937    #[allow(dead_code)]
938    fn set_window_icon(&self, _icon: Option<image::RgbaImage>) {}
939
940    fn set_cursor_style(&self, _style: CursorStyle) {}
941
942    #[cfg(any(test, feature = "test-support"))]
943    fn as_test(&mut self) -> Option<&mut TestWindow> {
944        None
945    }
946}
947
948/// This type is public so that our test macro can generate and use it, but it should not
949/// be considered part of our public API.
950#[doc(hidden)]
951pub trait PlatformDispatcher: Send + Sync {
952    fn is_main_thread(&self) -> bool;
953    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
954    fn dispatch_on_main_thread(&self, runnable: Runnable);
955    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
956    fn park(&self, timeout: Option<Duration>) -> bool;
957    fn unparker(&self) -> Unparker;
958    fn now(&self) -> Instant {
959        Instant::now()
960    }
961
962    /// Prevents App Nap-style throttling while the returned guard is held.
963    ///
964    /// This does not prevent the system from entering idle sleep.
965    fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
966        ActivityGuard::noop()
967    }
968
969    #[cfg(any(test, feature = "test-support"))]
970    fn as_test(&self) -> Option<&TestDispatcher> {
971        None
972    }
973
974    #[cfg(any(test, feature = "test-support"))]
975    fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
976        None
977    }
978}
979
980#[allow(missing_docs)]
981pub trait PlatformTextSystem: Send + Sync {
982    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
983    fn all_font_names(&self) -> Vec<String>;
984    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
985    /// Drop platform-side glyph rasterization data associated with the core raster-bounds cache.
986    fn clear_glyph_raster_cache(&self) {}
987    /// Prewarm any system font caches needed to shape text.
988    fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
989    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
990    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
991    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
992    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
993    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
994    fn rasterize_glyph(
995        &self,
996        params: &RenderGlyphParams,
997        raster_bounds: Bounds<DevicePixels>,
998    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
999    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1000
1001    /// Installs the sink for grapheme clusters that exhaust font fallback during
1002    /// [`Self::layout_line`]. The core text system installs its reporter when it is
1003    /// created. Platforms that do not detect missing glyphs keep the default no-op.
1004    fn set_missing_glyph_sink(&self, _sink: Arc<dyn MissingGlyphSink>) {}
1005
1006    fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1007        0
1008    }
1009}
1010
1011#[allow(missing_docs)]
1012pub struct NoopTextSystem;
1013
1014#[allow(missing_docs)]
1015impl NoopTextSystem {
1016    #[allow(dead_code)]
1017    pub fn new() -> Self {
1018        Self
1019    }
1020}
1021
1022impl PlatformTextSystem for NoopTextSystem {
1023    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1024        Ok(())
1025    }
1026
1027    fn all_font_names(&self) -> Vec<String> {
1028        Vec::new()
1029    }
1030
1031    fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1032        Ok(FontId(1))
1033    }
1034
1035    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1036        FontMetrics {
1037            units_per_em: 1000,
1038            ascent: 1025.0,
1039            descent: -275.0,
1040            line_gap: 0.0,
1041            underline_position: -95.0,
1042            underline_thickness: 60.0,
1043            cap_height: 698.0,
1044            x_height: 516.0,
1045            bounding_box: Bounds {
1046                origin: Point {
1047                    x: -260.0,
1048                    y: -245.0,
1049                },
1050                size: Size {
1051                    width: 1501.0,
1052                    height: 1364.0,
1053                },
1054            },
1055        }
1056    }
1057
1058    fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1059        Ok(Bounds {
1060            origin: Point { x: 54.0, y: 0.0 },
1061            size: size(392.0, 528.0),
1062        })
1063    }
1064
1065    fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1066        Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1067    }
1068
1069    fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1070        Some(GlyphId(ch.len_utf16() as u32))
1071    }
1072
1073    fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1074        Ok(Default::default())
1075    }
1076
1077    fn rasterize_glyph(
1078        &self,
1079        _params: &RenderGlyphParams,
1080        raster_bounds: Bounds<DevicePixels>,
1081    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1082        Ok((raster_bounds.size, Vec::new()))
1083    }
1084
1085    fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1086        let mut position = px(0.);
1087        let metrics = self.font_metrics(FontId(0));
1088        let em_width = font_size
1089            * self
1090                .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1091                .unwrap()
1092                .width
1093            / metrics.units_per_em as f32;
1094        let mut glyphs = Vec::new();
1095        for (ix, c) in text.char_indices() {
1096            if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1097                glyphs.push(ShapedGlyph {
1098                    id: glyph,
1099                    position: point(position, px(0.)),
1100                    index: ix,
1101                    is_emoji: glyph.0 == 2,
1102                });
1103                if glyph.0 == 2 {
1104                    position += em_width * 2.0;
1105                } else {
1106                    position += em_width;
1107                }
1108            } else {
1109                position += em_width
1110            }
1111        }
1112        let mut runs = Vec::default();
1113        if !glyphs.is_empty() {
1114            runs.push(ShapedRun {
1115                font_id: FontId(0),
1116                glyphs,
1117            });
1118        } else {
1119            position = px(0.);
1120        }
1121
1122        LineLayout {
1123            font_size,
1124            width: position,
1125            ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1126            descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1127            runs,
1128            len: text.len(),
1129        }
1130    }
1131}
1132
1133#[derive(PartialEq, Eq, Hash, Clone)]
1134#[allow(missing_docs)]
1135pub enum AtlasKey {
1136    Glyph(RenderGlyphParams),
1137    Svg(RenderSvgParams),
1138    Image(RenderImageParams),
1139}
1140
1141#[allow(missing_docs)]
1142impl AtlasKey {
1143    #[cfg_attr(
1144        all(
1145            any(target_os = "linux", target_os = "freebsd"),
1146            not(any(feature = "x11", feature = "wayland"))
1147        ),
1148        allow(dead_code)
1149    )]
1150    pub fn texture_kind(&self) -> AtlasTextureKind {
1151        match self {
1152            AtlasKey::Glyph(params) => {
1153                if params.is_emoji {
1154                    AtlasTextureKind::Polychrome
1155                } else {
1156                    AtlasTextureKind::Monochrome
1157                }
1158            }
1159            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1160            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1161        }
1162    }
1163}
1164
1165impl From<RenderGlyphParams> for AtlasKey {
1166    fn from(params: RenderGlyphParams) -> Self {
1167        Self::Glyph(params)
1168    }
1169}
1170
1171impl From<RenderSvgParams> for AtlasKey {
1172    fn from(params: RenderSvgParams) -> Self {
1173        Self::Svg(params)
1174    }
1175}
1176
1177impl From<RenderImageParams> for AtlasKey {
1178    fn from(params: RenderImageParams) -> Self {
1179        Self::Image(params)
1180    }
1181}
1182
1183#[allow(missing_docs)]
1184pub trait PlatformAtlas: Send + Sync {
1185    fn get_or_insert_with<'a>(
1186        &self,
1187        key: &AtlasKey,
1188        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1189    ) -> Result<Option<AtlasTile>>;
1190    fn remove(&self, key: &AtlasKey);
1191}
1192
1193#[doc(hidden)]
1194pub struct AtlasTextureList<T> {
1195    pub textures: Vec<Option<T>>,
1196    pub free_list: Vec<usize>,
1197}
1198
1199impl<T> Default for AtlasTextureList<T> {
1200    fn default() -> Self {
1201        Self {
1202            textures: Vec::default(),
1203            free_list: Vec::default(),
1204        }
1205    }
1206}
1207
1208impl<T> ops::Index<usize> for AtlasTextureList<T> {
1209    type Output = Option<T>;
1210
1211    fn index(&self, index: usize) -> &Self::Output {
1212        &self.textures[index]
1213    }
1214}
1215
1216#[allow(missing_docs)]
1217impl<T> AtlasTextureList<T> {
1218    #[allow(unused)]
1219    pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1220        self.free_list.clear();
1221        self.textures.drain(..)
1222    }
1223
1224    #[allow(dead_code)]
1225    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1226        self.textures.iter_mut().flatten()
1227    }
1228}
1229
1230#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1231#[repr(C)]
1232#[allow(missing_docs)]
1233pub struct AtlasTile {
1234    pub texture_id: AtlasTextureId,
1235    pub tile_id: TileId,
1236    pub padding: u32,
1237    pub bounds: Bounds<DevicePixels>,
1238}
1239
1240#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1241#[repr(C)]
1242#[allow(missing_docs)]
1243pub struct AtlasTextureId {
1244    // We use u32 instead of usize for Metal Shader Language compatibility
1245    pub index: u32,
1246    pub kind: AtlasTextureKind,
1247}
1248
1249#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1250#[repr(C)]
1251#[cfg_attr(
1252    all(
1253        any(target_os = "linux", target_os = "freebsd"),
1254        not(any(feature = "x11", feature = "wayland"))
1255    ),
1256    allow(dead_code)
1257)]
1258#[allow(missing_docs)]
1259pub enum AtlasTextureKind {
1260    Monochrome = 0,
1261    Polychrome = 1,
1262}
1263
1264#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1265#[repr(C)]
1266#[allow(missing_docs)]
1267pub struct TileId(pub u32);
1268
1269impl From<etagere::AllocId> for TileId {
1270    fn from(id: etagere::AllocId) -> Self {
1271        Self(id.serialize())
1272    }
1273}
1274
1275impl From<TileId> for etagere::AllocId {
1276    fn from(id: TileId) -> Self {
1277        Self::deserialize(id.0)
1278    }
1279}
1280
1281#[allow(missing_docs)]
1282pub struct PlatformInputHandler {
1283    cx: AsyncWindowContext,
1284    handler: Box<dyn InputHandler>,
1285}
1286
1287#[cfg_attr(
1288    all(
1289        any(target_os = "linux", target_os = "freebsd"),
1290        not(any(feature = "x11", feature = "wayland"))
1291    ),
1292    allow(dead_code)
1293)]
1294#[allow(missing_docs)]
1295impl PlatformInputHandler {
1296    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
1297        Self { cx, handler }
1298    }
1299
1300    fn mark_keyboard_input(window: &Window) {
1301        window.input_rate_tracker.borrow_mut().record_input();
1302        window.last_input_was_keyboard.set(true);
1303    }
1304
1305    pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
1306        self.cx
1307            .update(|window, cx| {
1308                self.handler
1309                    .selected_text_range(ignore_disabled_input, window, cx)
1310            })
1311            .ok()
1312            .flatten()
1313    }
1314
1315    #[cfg_attr(target_os = "windows", allow(dead_code))]
1316    pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
1317        self.cx
1318            .update(|window, cx| self.handler.marked_text_range(window, cx))
1319            .ok()
1320            .flatten()
1321    }
1322
1323    #[cfg_attr(
1324        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1325        allow(dead_code)
1326    )]
1327    pub fn text_for_range(
1328        &mut self,
1329        range_utf16: Range<usize>,
1330        adjusted: &mut Option<Range<usize>>,
1331    ) -> Option<String> {
1332        self.cx
1333            .update(|window, cx| {
1334                self.handler
1335                    .text_for_range(range_utf16, adjusted, window, cx)
1336            })
1337            .ok()
1338            .flatten()
1339    }
1340
1341    pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
1342        self.cx
1343            .update(|window, cx| {
1344                Self::mark_keyboard_input(window);
1345                self.handler
1346                    .replace_text_in_range(replacement_range, text, window, cx);
1347            })
1348            .ok();
1349    }
1350
1351    pub fn replace_and_mark_text_in_range(
1352        &mut self,
1353        range_utf16: Option<Range<usize>>,
1354        new_text: &str,
1355        new_selected_range: Option<Range<usize>>,
1356    ) {
1357        self.cx
1358            .update(|window, cx| {
1359                Self::mark_keyboard_input(window);
1360                self.handler.replace_and_mark_text_in_range(
1361                    range_utf16,
1362                    new_text,
1363                    new_selected_range,
1364                    window,
1365                    cx,
1366                )
1367            })
1368            .ok();
1369    }
1370
1371    #[cfg_attr(target_os = "windows", allow(dead_code))]
1372    pub fn unmark_text(&mut self) {
1373        self.cx
1374            .update(|window, cx| {
1375                Self::mark_keyboard_input(window);
1376                self.handler.unmark_text(window, cx)
1377            })
1378            .ok();
1379    }
1380
1381    pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
1382        self.cx
1383            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
1384            .ok()
1385            .flatten()
1386    }
1387
1388    #[allow(dead_code)]
1389    pub fn apple_press_and_hold_enabled(&mut self) -> bool {
1390        self.handler.apple_press_and_hold_enabled()
1391    }
1392
1393    pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1394        // Note: record_input() is already called by dispatch_event for the key event
1395        // that triggered this text insertion, so we only update last_input_was_keyboard here.
1396        window.last_input_was_keyboard.set(true);
1397        self.handler.replace_text_in_range(None, input, window, cx);
1398    }
1399
1400    pub fn compute_ime_candidate_bounds(
1401        marked_range: Option<Range<usize>>,
1402        selection: &UTF16Selection,
1403        mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
1404    ) -> Option<Bounds<Pixels>> {
1405        if let Some(marked_range) = marked_range {
1406            let mut line_start = marked_range.start;
1407            let caret = selection.range.end;
1408            if let Some(caret_bounds) = bounds_for_range(caret..caret) {
1409                for i in (marked_range.start..caret).rev() {
1410                    if let Some(bounds) = bounds_for_range(i..i)
1411                        && (bounds.origin.y - caret_bounds.origin.y).abs() > px(0.1)
1412                    {
1413                        line_start = i + 1;
1414                        break;
1415                    }
1416                }
1417            }
1418            bounds_for_range(line_start..line_start)
1419        } else {
1420            let offset = if selection.reversed {
1421                selection.range.start
1422            } else {
1423                selection.range.end
1424            };
1425            bounds_for_range(offset..offset)
1426        }
1427    }
1428
1429    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
1430        let marked_range = self.handler.marked_text_range(window, cx);
1431        let selection = self.handler.selected_text_range(true, window, cx)?;
1432        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
1433            self.handler.bounds_for_range(range, window, cx)
1434        })
1435    }
1436
1437    #[allow(dead_code)]
1438    pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
1439        let marked_range = self.marked_text_range();
1440        let selection = self.selected_text_range(true)?;
1441        Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
1442            self.bounds_for_range(range)
1443        })
1444    }
1445
1446    #[allow(unused)]
1447    pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
1448        self.cx
1449            .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
1450            .ok()
1451            .flatten()
1452    }
1453
1454    #[allow(dead_code)]
1455    pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
1456        self.handler.accepts_text_input(window, cx)
1457    }
1458
1459    #[allow(dead_code)]
1460    pub fn query_accepts_text_input(&mut self) -> bool {
1461        self.cx
1462            .update(|window, cx| self.handler.accepts_text_input(window, cx))
1463            .unwrap_or(true)
1464    }
1465}
1466
1467/// A struct representing a selection in a text buffer, in UTF16 characters.
1468/// This is different from a range because the head may be before the tail.
1469#[derive(Debug)]
1470pub struct UTF16Selection {
1471    /// The range of text in the document this selection corresponds to
1472    /// in UTF16 characters.
1473    pub range: Range<usize>,
1474    /// Whether the head of this selection is at the start (true), or end (false)
1475    /// of the range
1476    pub reversed: bool,
1477}
1478
1479/// Zed's interface for handling text input from the platform's IME system
1480/// This is currently a 1:1 exposure of the NSTextInputClient API:
1481///
1482/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
1483pub trait InputHandler: 'static {
1484    /// Get the range of the user's currently selected text, if any
1485    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
1486    ///
1487    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1488    fn selected_text_range(
1489        &mut self,
1490        ignore_disabled_input: bool,
1491        window: &mut Window,
1492        cx: &mut App,
1493    ) -> Option<UTF16Selection>;
1494
1495    /// Get the range of the currently marked text, if any
1496    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
1497    ///
1498    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1499    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
1500
1501    /// Get the text for the given document range in UTF-16 characters
1502    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
1503    ///
1504    /// range_utf16 is in terms of UTF-16 characters
1505    fn text_for_range(
1506        &mut self,
1507        range_utf16: Range<usize>,
1508        adjusted_range: &mut Option<Range<usize>>,
1509        window: &mut Window,
1510        cx: &mut App,
1511    ) -> Option<String>;
1512
1513    /// Replace the text in the given document range with the given text
1514    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
1515    ///
1516    /// replacement_range is in terms of UTF-16 characters
1517    fn replace_text_in_range(
1518        &mut self,
1519        replacement_range: Option<Range<usize>>,
1520        text: &str,
1521        window: &mut Window,
1522        cx: &mut App,
1523    );
1524
1525    /// Replace the text in the given document range with the given text,
1526    /// and mark the given text as part of an IME 'composing' state
1527    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
1528    ///
1529    /// range_utf16 is in terms of UTF-16 characters
1530    /// new_selected_range is in terms of UTF-16 characters
1531    fn replace_and_mark_text_in_range(
1532        &mut self,
1533        range_utf16: Option<Range<usize>>,
1534        new_text: &str,
1535        new_selected_range: Option<Range<usize>>,
1536        window: &mut Window,
1537        cx: &mut App,
1538    );
1539
1540    /// Remove the IME 'composing' state from the document
1541    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
1542    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
1543
1544    /// Get the bounds of the given document range in screen coordinates
1545    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
1546    ///
1547    /// This is used for positioning the IME candidate window
1548    fn bounds_for_range(
1549        &mut self,
1550        range_utf16: Range<usize>,
1551        window: &mut Window,
1552        cx: &mut App,
1553    ) -> Option<Bounds<Pixels>>;
1554
1555    /// Get the character offset for the given point in terms of UTF16 characters
1556    ///
1557    /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
1558    fn character_index_for_point(
1559        &mut self,
1560        point: Point<Pixels>,
1561        window: &mut Window,
1562        cx: &mut App,
1563    ) -> Option<usize>;
1564
1565    /// Allows a given input context to opt into getting raw key repeats instead of
1566    /// sending these to the platform.
1567    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1568    /// (which is how iTerm does it) but it doesn't seem to work for me.
1569    #[allow(dead_code)]
1570    fn apple_press_and_hold_enabled(&mut self) -> bool {
1571        true
1572    }
1573
1574    /// Returns whether this handler is accepting text input to be inserted.
1575    fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1576        true
1577    }
1578}
1579
1580/// The variables that can be configured when creating a new window
1581#[derive(Debug)]
1582pub struct WindowOptions {
1583    /// Specifies the state and bounds of the window in screen coordinates.
1584    /// - `None`: Inherit the bounds.
1585    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1586    pub window_bounds: Option<WindowBounds>,
1587
1588    /// The titlebar configuration of the window
1589    pub titlebar: Option<TitlebarOptions>,
1590
1591    /// Whether the window should be focused when created
1592    pub focus: bool,
1593
1594    /// Whether the window should be shown when created
1595    pub show: bool,
1596
1597    /// The kind of window to create
1598    pub kind: WindowKind,
1599
1600    /// Whether the window should be movable by the user.
1601    pub is_movable: bool,
1602
1603    /// Whether the application owns dragging of its custom titlebar on macOS.
1604    ///
1605    /// This prevents AppKit from claiming the titlebar region or delaying clicks,
1606    /// while leaving `is_movable` enabled for application-driven window moves.
1607    pub app_owns_titlebar_drag: bool,
1608
1609    /// The minimum interval between animation frames while the window is inactive.
1610    ///
1611    /// Set to `None` to disable inactive-window animation frame throttling.
1612    /// Overlay, HUD, and daemon windows that keep animating while unfocused
1613    /// can set a shorter interval (or `None`) here.
1614    pub inactive_frame_interval: Option<Duration>,
1615
1616    /// Whether the window should be resizable by the user
1617    pub is_resizable: bool,
1618
1619    /// Whether the window should be minimized by the user
1620    pub is_minimizable: bool,
1621
1622    /// The display to create the window on, if this is None,
1623    /// the window will be created on the main display
1624    pub display_id: Option<DisplayId>,
1625
1626    /// The appearance of the window background.
1627    pub window_background: WindowBackgroundAppearance,
1628
1629    /// Application identifier of the window. Can by used by desktop environments to group applications together.
1630    pub app_id: Option<String>,
1631
1632    /// Window minimum size
1633    pub window_min_size: Option<Size<Pixels>>,
1634
1635    /// Whether to use client or server side decorations. Wayland only
1636    /// Note that this may be ignored.
1637    pub window_decorations: Option<WindowDecorations>,
1638
1639    /// 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.
1640    pub tabbing_identifier: Option<String>,
1641
1642    /// Whether the window should allow mouse events to pass through to windows behind it
1643    pub mouse_passthrough: bool,
1644
1645    /// Optional window icon (currently consumed only on X11; ignored elsewhere)
1646    pub icon: Option<image::RgbaImage>,
1647}
1648
1649/// The variables that can be configured when creating a new window
1650#[derive(Debug)]
1651#[cfg_attr(
1652    all(
1653        any(target_os = "linux", target_os = "freebsd"),
1654        not(any(feature = "x11", feature = "wayland"))
1655    ),
1656    allow(dead_code)
1657)]
1658#[allow(missing_docs)]
1659pub struct WindowParams {
1660    pub bounds: Bounds<Pixels>,
1661
1662    /// The titlebar configuration of the window
1663    #[cfg_attr(feature = "wayland", allow(dead_code))]
1664    pub titlebar: Option<TitlebarOptions>,
1665
1666    /// The kind of window to create
1667    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1668    pub kind: WindowKind,
1669
1670    /// Whether the window should be movable by the user
1671    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1672    pub is_movable: bool,
1673
1674    /// Whether the application owns custom-titlebar dragging on macOS.
1675    #[cfg_attr(
1676        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1677        allow(dead_code)
1678    )]
1679    pub app_owns_titlebar_drag: bool,
1680
1681    /// Whether the window should be resizable by the user
1682    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1683    pub is_resizable: bool,
1684
1685    /// Whether the window should be minimized by the user
1686    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1687    pub is_minimizable: bool,
1688
1689    #[cfg_attr(
1690        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1691        allow(dead_code)
1692    )]
1693    pub focus: bool,
1694
1695    #[cfg_attr(
1696        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1697        allow(dead_code)
1698    )]
1699    pub app_id: Option<String>,
1700
1701    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1702    pub show: bool,
1703
1704    #[cfg_attr(feature = "wayland", allow(dead_code))]
1705    pub display_id: Option<DisplayId>,
1706
1707    pub window_min_size: Option<Size<Pixels>>,
1708    #[cfg(target_os = "macos")]
1709    pub tabbing_identifier: Option<String>,
1710
1711    #[allow(dead_code)]
1712    pub mouse_passthrough: bool,
1713
1714    /// Optional window icon (primarily for X11)
1715    #[cfg_attr(not(any(target_os = "linux", target_os = "freebsd")), allow(dead_code))]
1716    pub icon: Option<image::RgbaImage>,
1717}
1718
1719/// The window corner or edge that stays fixed on screen when the window is
1720/// resized via [`PlatformWindow::resize_anchored`] / [`crate::Window::resize_anchored`].
1721///
1722/// Named from the viewer's perspective: `TopLeft` pins the visually top-left
1723/// corner, so a tray popup below the menu bar grows down and to the right.
1724#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1725pub enum ResizeAnchor {
1726    /// Keep the visually top-left corner fixed; the window grows down-right.
1727    TopLeft,
1728    /// Keep the top edge's midpoint fixed; the window grows downward.
1729    Top,
1730    /// Keep the visually top-right corner fixed; the window grows down-left.
1731    TopRight,
1732    /// Keep the left edge's midpoint fixed; the window grows rightward.
1733    Left,
1734    /// Keep the center fixed; the window grows outward.
1735    Center,
1736    /// Keep the right edge's midpoint fixed; the window grows leftward.
1737    Right,
1738    /// Keep the visually bottom-left corner fixed; the window grows up-right.
1739    BottomLeft,
1740    /// Keep the bottom edge's midpoint fixed; the window grows upward.
1741    Bottom,
1742    /// Keep the visually bottom-right corner fixed; the window grows up-left.
1743    BottomRight,
1744}
1745
1746/// Represents the status of how a window should be opened.
1747#[derive(Debug, Copy, Clone, PartialEq)]
1748pub enum WindowBounds {
1749    /// Indicates that the window should open in a windowed state with the given bounds.
1750    Windowed(Bounds<Pixels>),
1751    /// Indicates that the window should open in a maximized state.
1752    /// The bounds provided here represent the restore size of the window.
1753    Maximized(Bounds<Pixels>),
1754    /// Indicates that the window should open in fullscreen mode.
1755    /// The bounds provided here represent the restore size of the window.
1756    Fullscreen(Bounds<Pixels>),
1757}
1758
1759impl Default for WindowBounds {
1760    fn default() -> Self {
1761        WindowBounds::Windowed(Bounds::default())
1762    }
1763}
1764
1765impl WindowBounds {
1766    /// Retrieve the inner bounds
1767    pub fn get_bounds(&self) -> Bounds<Pixels> {
1768        match self {
1769            WindowBounds::Windowed(bounds) => *bounds,
1770            WindowBounds::Maximized(bounds) => *bounds,
1771            WindowBounds::Fullscreen(bounds) => *bounds,
1772        }
1773    }
1774
1775    /// Creates windowed bounds centered in the primary display's work area.
1776    ///
1777    /// Delegates to [`Bounds::centered`], so the size is clamped with [`Size::min`]
1778    /// and the origin uses `visible_bounds` rather than the full display.
1779    pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
1780        WindowBounds::Windowed(Bounds::centered(None, size, cx))
1781    }
1782}
1783
1784impl Default for WindowOptions {
1785    fn default() -> Self {
1786        Self {
1787            window_bounds: None,
1788            titlebar: Some(TitlebarOptions {
1789                title: Default::default(),
1790                appears_transparent: Default::default(),
1791                traffic_light_position: Default::default(),
1792            }),
1793            focus: true,
1794            show: true,
1795            kind: WindowKind::Normal,
1796            is_movable: true,
1797            app_owns_titlebar_drag: false,
1798            inactive_frame_interval: Some(Duration::from_micros(33_333)),
1799            is_resizable: true,
1800            is_minimizable: true,
1801            display_id: None,
1802            window_background: WindowBackgroundAppearance::default(),
1803            app_id: None,
1804            window_min_size: None,
1805            window_decorations: None,
1806            tabbing_identifier: None,
1807            mouse_passthrough: false,
1808            icon: None,
1809        }
1810    }
1811}
1812
1813#[cfg(test)]
1814mod platform_input_handler_tests {
1815    use super::*;
1816    use crate::{
1817        AppContext, Context, ElementInputHandler, Empty, EntityInputHandler, TestAppContext,
1818    };
1819
1820    struct RejectingEntityInputHandler;
1821
1822    impl EntityInputHandler for RejectingEntityInputHandler {
1823        fn text_for_range(
1824            &mut self,
1825            _range: Range<usize>,
1826            _adjusted_range: &mut Option<Range<usize>>,
1827            _window: &mut Window,
1828            _cx: &mut Context<Self>,
1829        ) -> Option<String> {
1830            None
1831        }
1832
1833        fn selected_text_range(
1834            &mut self,
1835            _ignore_disabled_input: bool,
1836            _window: &mut Window,
1837            _cx: &mut Context<Self>,
1838        ) -> Option<UTF16Selection> {
1839            None
1840        }
1841
1842        fn marked_text_range(
1843            &self,
1844            _window: &mut Window,
1845            _cx: &mut Context<Self>,
1846        ) -> Option<Range<usize>> {
1847            None
1848        }
1849
1850        fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
1851
1852        fn replace_text_in_range(
1853            &mut self,
1854            _range: Option<Range<usize>>,
1855            _text: &str,
1856            _window: &mut Window,
1857            _cx: &mut Context<Self>,
1858        ) {
1859        }
1860
1861        fn replace_and_mark_text_in_range(
1862            &mut self,
1863            _range: Option<Range<usize>>,
1864            _new_text: &str,
1865            _new_selected_range: Option<Range<usize>>,
1866            _window: &mut Window,
1867            _cx: &mut Context<Self>,
1868        ) {
1869        }
1870
1871        fn bounds_for_range(
1872            &mut self,
1873            _range_utf16: Range<usize>,
1874            _element_bounds: Bounds<Pixels>,
1875            _window: &mut Window,
1876            _cx: &mut Context<Self>,
1877        ) -> Option<Bounds<Pixels>> {
1878            None
1879        }
1880
1881        fn character_index_for_point(
1882            &mut self,
1883            _point: Point<Pixels>,
1884            _window: &mut Window,
1885            _cx: &mut Context<Self>,
1886        ) -> Option<usize> {
1887            None
1888        }
1889
1890        fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
1891            false
1892        }
1893    }
1894
1895    #[gpui_macros::test]
1896    fn element_input_handler_forwards_text_input_rejection(cx: &mut TestAppContext) {
1897        let entity = cx.new(|_| RejectingEntityInputHandler);
1898        let window = cx.add_window(|_, _| Empty);
1899
1900        cx.update_window(window.into(), |_, window, cx| {
1901            let mut handler = ElementInputHandler::new(Bounds::default(), entity);
1902            assert!(!handler.accepts_text_input(window, cx));
1903        })
1904        .unwrap();
1905    }
1906
1907    #[gpui_macros::test]
1908    fn platform_input_handler_accepts_text_when_window_update_fails(cx: &mut TestAppContext) {
1909        let entity = cx.new(|_| RejectingEntityInputHandler);
1910        let window = cx.add_window(|_, _| Empty);
1911        let window = AnyWindowHandle::from(window);
1912        let async_cx = cx
1913            .update_window(window, |_, window, cx| window.to_async(cx))
1914            .unwrap();
1915
1916        cx.update_window(window, |_, window, _| window.remove_window())
1917            .unwrap();
1918        assert!(cx.update_window(window, |_, _, _| ()).is_err());
1919
1920        let mut handler = PlatformInputHandler::new(
1921            async_cx,
1922            Box::new(ElementInputHandler::new(Bounds::default(), entity)),
1923        );
1924        assert!(handler.query_accepts_text_input());
1925    }
1926
1927    fn bounds_at(offset: usize, y: f32) -> Bounds<Pixels> {
1928        Bounds::new(
1929            point(px(offset as f32 * 10.0), px(y)),
1930            size(px(1.0), px(20.0)),
1931        )
1932    }
1933
1934    #[test]
1935    fn ime_candidate_bounds_uses_selection_endpoint_without_marked_range() {
1936        let selection = UTF16Selection {
1937            range: 3..5,
1938            reversed: false,
1939        };
1940        let mut requests = Vec::new();
1941        let bounds =
1942            PlatformInputHandler::compute_ime_candidate_bounds(None, &selection, |range| {
1943                requests.push(range.clone());
1944                Some(bounds_at(range.start, 0.0))
1945            })
1946            .unwrap();
1947
1948        assert_eq!(bounds.origin.x, px(50.0));
1949        assert_eq!(requests, vec![5..5]);
1950
1951        let selection = UTF16Selection {
1952            range: 3..5,
1953            reversed: true,
1954        };
1955        let bounds =
1956            PlatformInputHandler::compute_ime_candidate_bounds(None, &selection, |range| {
1957                Some(bounds_at(range.start, 0.0))
1958            })
1959            .unwrap();
1960
1961        assert_eq!(bounds.origin.x, px(30.0));
1962    }
1963
1964    #[test]
1965    fn ime_candidate_bounds_anchors_marked_text_to_visual_line_start() {
1966        let selection = UTF16Selection {
1967            range: 15..15,
1968            reversed: false,
1969        };
1970        let mut requests = Vec::new();
1971        let bounds =
1972            PlatformInputHandler::compute_ime_candidate_bounds(Some(10..15), &selection, |range| {
1973                requests.push(range.clone());
1974                let y = if range.start >= 13 { 20.0 } else { 0.0 };
1975                Some(bounds_at(range.start, y))
1976            })
1977            .unwrap();
1978
1979        assert_eq!(bounds.origin.x, px(130.0));
1980        assert_eq!(requests.last(), Some(&(13..13)));
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)]
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 floating window that appears on top of its parent window
2009    Floating,
2010
2011    /// An overlay window that appears above all other windows, including fullscreen apps
2012    Overlay,
2013
2014    /// A Wayland layer-shell window, used for overlays or backgrounds such as docks,
2015    /// notifications, and wallpapers.
2016    #[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "wayland"))]
2017    LayerShell(layer_shell::LayerShellOptions),
2018}
2019
2020/// The appearance of the window, as defined by the operating system.
2021///
2022/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
2023/// values.
2024#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2025pub enum WindowAppearance {
2026    /// A light appearance.
2027    ///
2028    /// On macOS, this corresponds to the `aqua` appearance.
2029    #[default]
2030    Light,
2031
2032    /// A light appearance with vibrant colors.
2033    ///
2034    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
2035    VibrantLight,
2036
2037    /// A dark appearance.
2038    ///
2039    /// On macOS, this corresponds to the `darkAqua` appearance.
2040    Dark,
2041
2042    /// A dark appearance with vibrant colors.
2043    ///
2044    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
2045    VibrantDark,
2046}
2047
2048/// The appearance of the background of the window itself, when there is
2049/// no content or the content is transparent.
2050#[derive(Copy, Clone, Debug, Default, PartialEq)]
2051pub enum WindowBackgroundAppearance {
2052    /// Opaque.
2053    ///
2054    /// This lets the window manager know that content behind this
2055    /// window does not need to be drawn.
2056    ///
2057    /// Actual color depends on the system and themes should define a fully
2058    /// opaque background color instead.
2059    #[default]
2060    Opaque,
2061    /// Plain alpha transparency.
2062    Transparent,
2063    /// Transparency, but the contents behind the window are blurred.
2064    ///
2065    /// Not always supported.
2066    Blurred,
2067}
2068
2069/// Controls how a system tray icon should be rendered.
2070#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2071#[non_exhaustive]
2072pub enum TrayIconRenderingMode {
2073    /// Render using the platform's default status icon appearance.
2074    ///
2075    /// On macOS, this uses template rendering so the icon adapts to the menu bar appearance.
2076    #[default]
2077    Adaptive,
2078    /// Render the icon with its original colors when supported by the platform.
2079    ///
2080    /// On macOS, this disables template rendering.
2081    Original,
2082}
2083
2084/// Events that can occur on a system tray icon.
2085#[derive(Debug, Clone, PartialEq, Eq)]
2086pub enum TrayIconEvent {
2087    /// The user left-clicked the tray icon.
2088    LeftClick,
2089    /// The user right-clicked the tray icon.
2090    RightClick,
2091    /// The user double-clicked the tray icon.
2092    DoubleClick,
2093}
2094
2095/// A tray icon click event with optional screen position information.
2096#[derive(Debug, Clone, PartialEq)]
2097pub struct TrayIconClickEvent {
2098    /// The kind of click that occurred.
2099    pub kind: TrayIconEvent,
2100    /// The click position in GPUI logical screen coordinates, if the platform provides it.
2101    ///
2102    /// Linux StatusNotifierItem provides a raw screen-coordinate hint; GPUI
2103    /// converts that hint through the active display scale before exposing it.
2104    /// On Wayland fractional scaling, the hint has no surface association, so
2105    /// conversion uses the integer output scale and may remain approximate.
2106    pub position: Option<Point<Pixels>>,
2107}
2108
2109impl TrayIconClickEvent {
2110    /// Create a tray click event without position information.
2111    pub fn new(kind: TrayIconEvent) -> Self {
2112        Self {
2113            kind,
2114            position: None,
2115        }
2116    }
2117
2118    /// Create a tray click event with a logical screen-coordinate hint.
2119    pub fn with_position(kind: TrayIconEvent, position: Point<Pixels>) -> Self {
2120        Self {
2121            kind,
2122            position: Some(position),
2123        }
2124    }
2125}
2126
2127#[allow(missing_docs)]
2128#[derive(Debug, Clone, PartialEq)]
2129pub struct TrayAnchor {
2130    pub display_id: DisplayId,
2131    pub bounds: Bounds<Pixels>,
2132}
2133
2134/// A menu item for a system tray context menu.
2135#[derive(Debug, Clone)]
2136pub enum TrayMenuItem {
2137    /// A clickable action item.
2138    Action {
2139        /// The display label.
2140        label: SharedString,
2141        /// A unique identifier for this action.
2142        id: SharedString,
2143    },
2144    /// A visual separator between menu items.
2145    Separator,
2146    /// A submenu containing nested items.
2147    Submenu {
2148        /// The display label.
2149        label: SharedString,
2150        /// The nested menu items.
2151        items: Vec<TrayMenuItem>,
2152    },
2153    /// A toggleable menu item with a checkmark.
2154    Toggle {
2155        /// The display label.
2156        label: SharedString,
2157        /// Whether the item is currently checked.
2158        checked: bool,
2159        /// A unique identifier for this toggle.
2160        id: SharedString,
2161    },
2162}
2163
2164/// Information about the currently focused window from any application.
2165#[derive(Debug, Clone)]
2166pub struct FocusedWindowInfo {
2167    /// The name of the application that owns the focused window.
2168    pub app_name: String,
2169    /// The title of the focused window.
2170    pub window_title: String,
2171    /// The bundle identifier of the application (macOS only).
2172    pub bundle_id: Option<String>,
2173    /// The process ID of the application.
2174    pub pid: Option<u32>,
2175}
2176
2177/// The status of a system permission.
2178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2179pub enum PermissionStatus {
2180    /// Permission has been granted.
2181    Granted,
2182    /// Permission has been denied.
2183    Denied,
2184    /// Permission has not yet been requested.
2185    NotDetermined,
2186    /// The platform does not expose this permission capability.
2187    Unavailable,
2188}
2189
2190/// Whether the platform accepted a permission request.
2191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2192pub enum PermissionRequestStatus {
2193    /// The platform accepted the request and will resolve it through its normal flow.
2194    Requested,
2195    /// The platform does not expose this permission request.
2196    Unavailable,
2197}
2198
2199/// System power state change events.
2200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2201pub enum SystemPowerEvent {
2202    /// The system is about to suspend/sleep.
2203    Suspend,
2204    /// The system has resumed from suspend/sleep.
2205    Resume,
2206    /// The screen has been locked.
2207    LockScreen,
2208    /// The screen has been unlocked.
2209    UnlockScreen,
2210    /// The system is shutting down.
2211    Shutdown,
2212}
2213
2214/// The kind of power save blocker to create.
2215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2216pub enum PowerSaveBlockerKind {
2217    /// Prevent the application from being suspended.
2218    PreventAppSuspension,
2219    /// Prevent the display from sleeping.
2220    PreventDisplaySleep,
2221}
2222
2223/// The current network connectivity status.
2224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2225pub enum NetworkStatus {
2226    /// The system has network connectivity.
2227    Online,
2228    /// The system has no network connectivity.
2229    Offline,
2230}
2231
2232/// Media key events from hardware media keys or OS media controls.
2233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2234pub enum MediaKeyEvent {
2235    /// Play media.
2236    Play,
2237    /// Pause media.
2238    Pause,
2239    /// Toggle play/pause.
2240    PlayPause,
2241    /// Stop media playback.
2242    Stop,
2243    /// Skip to the next track.
2244    NextTrack,
2245    /// Skip to the previous track.
2246    PreviousTrack,
2247}
2248
2249/// The type of user attention to request from the OS.
2250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2251pub enum AttentionType {
2252    /// An informational attention request (e.g. bounce dock icon once).
2253    Informational,
2254    /// A critical attention request (e.g. bounce dock icon continuously).
2255    Critical,
2256}
2257
2258/// The state of a taskbar/dock progress bar for a window.
2259#[derive(Debug, Clone, Copy, PartialEq)]
2260pub enum ProgressBarState {
2261    /// No progress bar is shown.
2262    None,
2263    /// An indeterminate progress bar is shown.
2264    Indeterminate,
2265    /// A normal progress bar with the given fraction (0.0 to 1.0).
2266    Normal(f64),
2267    /// An error progress bar with the given fraction (0.0 to 1.0).
2268    Error(f64),
2269    /// A paused progress bar with the given fraction (0.0 to 1.0).
2270    Paused(f64),
2271}
2272
2273/// The kind of a native dialog.
2274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2275pub enum DialogKind {
2276    /// An informational dialog.
2277    Info,
2278    /// A warning dialog.
2279    Warning,
2280    /// An error dialog.
2281    Error,
2282}
2283
2284/// Options for displaying a native dialog.
2285#[derive(Debug, Clone)]
2286pub struct DialogOptions {
2287    /// The kind of dialog to display.
2288    pub kind: DialogKind,
2289    /// The title of the dialog.
2290    pub title: SharedString,
2291    /// The primary message of the dialog.
2292    pub message: SharedString,
2293    /// Optional detail text shown below the message.
2294    pub detail: Option<SharedString>,
2295    /// The button labels for the dialog.
2296    pub buttons: Vec<SharedString>,
2297}
2298
2299/// Information about the operating system.
2300#[derive(Debug, Clone)]
2301pub struct OsInfo {
2302    /// The name of the operating system (e.g. "macos", "linux", "windows").
2303    pub name: SharedString,
2304    /// The version of the operating system.
2305    pub version: SharedString,
2306    /// The CPU architecture (e.g. "x86_64", "aarch64").
2307    pub arch: SharedString,
2308    /// The system locale (e.g. "en-US").
2309    pub locale: SharedString,
2310    /// The hostname of the system.
2311    pub hostname: SharedString,
2312}
2313
2314/// The kind of biometric authentication available.
2315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2316pub enum BiometricKind {
2317    /// macOS Touch ID.
2318    TouchId,
2319    /// Windows Hello.
2320    WindowsHello,
2321    /// Generic fingerprint reader.
2322    Fingerprint,
2323}
2324
2325/// The availability status of biometric authentication.
2326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2327pub enum BiometricStatus {
2328    /// Biometric authentication is available with the given kind.
2329    Available(BiometricKind),
2330    /// Biometric authentication is not available.
2331    Unavailable,
2332}
2333
2334/// A snapshot of a window's state for save/restore.
2335#[derive(Debug, Clone, PartialEq)]
2336pub struct WindowState {
2337    /// The window bounds.
2338    pub bounds: WindowBounds,
2339    /// The display the window is on.
2340    pub display_id: Option<DisplayId>,
2341    /// Whether the window is fullscreen.
2342    pub fullscreen: bool,
2343}
2344
2345/// A semantic window position for positioning windows relative to the screen.
2346#[derive(Debug, Clone, PartialEq)]
2347pub enum WindowPosition {
2348    /// Center the window on the primary display.
2349    Center,
2350    /// Center the window on the given display.
2351    CenterOnDisplay(DisplayId),
2352    /// Center the window above the tray icon area.
2353    ///
2354    /// Deprecated: this variant only carries the tray icon bounds and does
2355    /// not know which display the tray is on, which causes window placement
2356    /// to be off on multi-monitor setups. Prefer [`WindowPosition::TrayAnchored`],
2357    /// which carries a full [`TrayAnchor`] (including `display_id`).
2358    #[deprecated(
2359        since = "0.5.3",
2360        note = "Use `WindowPosition::TrayAnchored(TrayAnchor)` instead; the new variant carries `display_id` and fixes multi-monitor placement. This variant will be removed in a future release."
2361    )]
2362    TrayCenter(Bounds<Pixels>),
2363    /// Center the window above the tray icon area, using a full [`TrayAnchor`].
2364    ///
2365    /// The `TrayAnchor` carries both the tray icon `bounds` (display-local,
2366    /// top-left origin) and the `display_id` it resides on. Callers should
2367    /// also propagate `display_id` to `WindowOptions.display_id` so the
2368    /// window is opened on the correct screen in multi-monitor setups.
2369    TrayAnchored(TrayAnchor),
2370    /// Position the window in the top-right corner.
2371    TopRight {
2372        /// The margin from the screen edge.
2373        margin: Pixels,
2374    },
2375    /// Position the window in the bottom-right corner.
2376    BottomRight {
2377        /// The margin from the screen edge.
2378        margin: Pixels,
2379    },
2380    /// Position the window in the top-left corner.
2381    TopLeft {
2382        /// The margin from the screen edge.
2383        margin: Pixels,
2384    },
2385    /// Position the window in the bottom-left corner.
2386    BottomLeft {
2387        /// The margin from the screen edge.
2388        margin: Pixels,
2389    },
2390}
2391
2392/// Information collected for a crash report.
2393#[derive(Debug, Clone)]
2394pub struct CrashReport {
2395    /// The error message.
2396    pub message: String,
2397    /// The backtrace at the time of the crash.
2398    pub backtrace: String,
2399    /// Information about the operating system.
2400    pub os_info: OsInfo,
2401    /// The application version, if available.
2402    pub app_version: Option<String>,
2403}
2404
2405/// The options that can be configured for a file dialog prompt
2406#[derive(Clone, Debug)]
2407pub struct PathPromptOptions {
2408    /// Should the prompt allow files to be selected?
2409    pub files: bool,
2410    /// Should the prompt allow directories to be selected?
2411    pub directories: bool,
2412    /// Should the prompt allow multiple files to be selected?
2413    pub multiple: bool,
2414    /// The prompt to show to a user when selecting a path
2415    pub prompt: Option<SharedString>,
2416}
2417
2418/// What kind of prompt styling to show
2419#[derive(Copy, Clone, Debug, PartialEq)]
2420pub enum PromptLevel {
2421    /// A prompt that is shown when the user should be notified of something
2422    Info,
2423
2424    /// A prompt that is shown when the user needs to be warned of a potential problem
2425    Warning,
2426
2427    /// A prompt that is shown when a critical problem has occurred
2428    Critical,
2429}
2430
2431/// Prompt Button
2432#[derive(Clone, Debug, PartialEq)]
2433pub enum PromptButton {
2434    /// Ok button
2435    Ok(SharedString),
2436    /// Cancel button
2437    Cancel(SharedString),
2438    /// Other button
2439    Other(SharedString),
2440}
2441
2442impl PromptButton {
2443    /// Create a button with label
2444    pub fn new(label: impl Into<SharedString>) -> Self {
2445        PromptButton::Other(label.into())
2446    }
2447
2448    /// Create an Ok button
2449    pub fn ok(label: impl Into<SharedString>) -> Self {
2450        PromptButton::Ok(label.into())
2451    }
2452
2453    /// Create a Cancel button
2454    pub fn cancel(label: impl Into<SharedString>) -> Self {
2455        PromptButton::Cancel(label.into())
2456    }
2457
2458    #[allow(dead_code)]
2459    #[doc(hidden)]
2460    pub fn is_cancel(&self) -> bool {
2461        matches!(self, PromptButton::Cancel(_))
2462    }
2463
2464    /// Returns the label of the button
2465    pub fn label(&self) -> &SharedString {
2466        match self {
2467            PromptButton::Ok(label) => label,
2468            PromptButton::Cancel(label) => label,
2469            PromptButton::Other(label) => label,
2470        }
2471    }
2472}
2473
2474impl From<&str> for PromptButton {
2475    fn from(value: &str) -> Self {
2476        match value.to_lowercase().as_str() {
2477            "ok" => PromptButton::Ok("Ok".into()),
2478            "cancel" => PromptButton::Cancel("Cancel".into()),
2479            _ => PromptButton::Other(SharedString::from(value.to_owned())),
2480        }
2481    }
2482}
2483
2484/// The style of the cursor (pointer)
2485#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2486pub enum CursorStyle {
2487    /// The default cursor
2488    #[default]
2489    Arrow,
2490
2491    /// A text input cursor
2492    /// corresponds to the CSS cursor value `text`
2493    IBeam,
2494
2495    /// A crosshair cursor
2496    /// corresponds to the CSS cursor value `crosshair`
2497    Crosshair,
2498
2499    /// A closed hand cursor
2500    /// corresponds to the CSS cursor value `grabbing`
2501    ClosedHand,
2502
2503    /// An open hand cursor
2504    /// corresponds to the CSS cursor value `grab`
2505    OpenHand,
2506
2507    /// A pointing hand cursor
2508    /// corresponds to the CSS cursor value `pointer`
2509    PointingHand,
2510
2511    /// A resize left cursor
2512    /// corresponds to the CSS cursor value `w-resize`
2513    ResizeLeft,
2514
2515    /// A resize right cursor
2516    /// corresponds to the CSS cursor value `e-resize`
2517    ResizeRight,
2518
2519    /// A resize cursor to the left and right
2520    /// corresponds to the CSS cursor value `ew-resize`
2521    ResizeLeftRight,
2522
2523    /// A resize up cursor
2524    /// corresponds to the CSS cursor value `n-resize`
2525    ResizeUp,
2526
2527    /// A resize down cursor
2528    /// corresponds to the CSS cursor value `s-resize`
2529    ResizeDown,
2530
2531    /// A resize cursor directing up and down
2532    /// corresponds to the CSS cursor value `ns-resize`
2533    ResizeUpDown,
2534
2535    /// A resize cursor directing up-left and down-right
2536    /// corresponds to the CSS cursor value `nesw-resize`
2537    ResizeUpLeftDownRight,
2538
2539    /// A resize cursor directing up-right and down-left
2540    /// corresponds to the CSS cursor value `nwse-resize`
2541    ResizeUpRightDownLeft,
2542
2543    /// A cursor indicating that the item/column can be resized horizontally.
2544    /// corresponds to the CSS cursor value `col-resize`
2545    ResizeColumn,
2546
2547    /// A cursor indicating that the item/row can be resized vertically.
2548    /// corresponds to the CSS cursor value `row-resize`
2549    ResizeRow,
2550
2551    /// A text input cursor for vertical layout
2552    /// corresponds to the CSS cursor value `vertical-text`
2553    IBeamCursorForVerticalLayout,
2554
2555    /// A cursor indicating that the operation is not allowed
2556    /// corresponds to the CSS cursor value `not-allowed`
2557    OperationNotAllowed,
2558
2559    /// A cursor indicating that the operation will result in a link
2560    /// corresponds to the CSS cursor value `alias`
2561    DragLink,
2562
2563    /// A cursor indicating that the operation will result in a copy
2564    /// corresponds to the CSS cursor value `copy`
2565    DragCopy,
2566
2567    /// A cursor indicating that the operation will result in a context menu
2568    /// corresponds to the CSS cursor value `context-menu`
2569    ContextualMenu,
2570
2571    /// Hide the cursor
2572    None,
2573}
2574
2575/// A clipboard item that should be copied to the clipboard
2576#[derive(Clone, Debug, Eq, PartialEq)]
2577pub struct ClipboardItem {
2578    entries: Vec<ClipboardEntry>,
2579}
2580
2581/// Either a ClipboardString or a ClipboardImage
2582#[derive(Clone, Debug, Eq, PartialEq)]
2583pub enum ClipboardEntry {
2584    /// A string entry
2585    String(ClipboardString),
2586    /// An image entry
2587    Image(Image),
2588}
2589
2590impl ClipboardItem {
2591    /// Create a new ClipboardItem::String with no associated metadata
2592    pub fn new_string(text: String) -> Self {
2593        Self {
2594            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
2595        }
2596    }
2597
2598    /// Create a new ClipboardItem::String with the given text and associated metadata
2599    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
2600        Self {
2601            entries: vec![ClipboardEntry::String(ClipboardString {
2602                text,
2603                metadata: Some(metadata),
2604            })],
2605        }
2606    }
2607
2608    /// Create a new ClipboardItem::String with the given text and associated metadata
2609    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
2610        Self {
2611            entries: vec![ClipboardEntry::String(
2612                ClipboardString::new(text).with_json_metadata(metadata),
2613            )],
2614        }
2615    }
2616
2617    /// Create a new ClipboardItem::Image with the given image with no associated metadata
2618    pub fn new_image(image: &Image) -> Self {
2619        Self {
2620            entries: vec![ClipboardEntry::Image(image.clone())],
2621        }
2622    }
2623
2624    /// Concatenates together all the ClipboardString entries in the item.
2625    /// Returns None if there were no ClipboardString entries.
2626    pub fn text(&self) -> Option<String> {
2627        let mut answer = String::new();
2628        let mut any_entries = false;
2629
2630        for entry in self.entries.iter() {
2631            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
2632                answer.push_str(text);
2633                any_entries = true;
2634            }
2635        }
2636
2637        if any_entries { Some(answer) } else { None }
2638    }
2639
2640    /// If this item is one ClipboardEntry::String, returns its metadata.
2641    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
2642    pub fn metadata(&self) -> Option<&String> {
2643        match self.entries().first() {
2644            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
2645                clipboard_string.metadata.as_ref()
2646            }
2647            _ => None,
2648        }
2649    }
2650
2651    /// Get the item's entries
2652    pub fn entries(&self) -> &[ClipboardEntry] {
2653        &self.entries
2654    }
2655
2656    /// Get owned versions of the item's entries
2657    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
2658        self.entries.into_iter()
2659    }
2660}
2661
2662impl From<ClipboardString> for ClipboardEntry {
2663    fn from(value: ClipboardString) -> Self {
2664        Self::String(value)
2665    }
2666}
2667
2668impl From<String> for ClipboardEntry {
2669    fn from(value: String) -> Self {
2670        Self::from(ClipboardString::from(value))
2671    }
2672}
2673
2674impl From<Image> for ClipboardEntry {
2675    fn from(value: Image) -> Self {
2676        Self::Image(value)
2677    }
2678}
2679
2680impl From<ClipboardEntry> for ClipboardItem {
2681    fn from(value: ClipboardEntry) -> Self {
2682        Self {
2683            entries: vec![value],
2684        }
2685    }
2686}
2687
2688impl From<String> for ClipboardItem {
2689    fn from(value: String) -> Self {
2690        Self::from(ClipboardEntry::from(value))
2691    }
2692}
2693
2694impl From<Image> for ClipboardItem {
2695    fn from(value: Image) -> Self {
2696        Self::from(ClipboardEntry::from(value))
2697    }
2698}
2699
2700/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
2701#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
2702pub enum ImageFormat {
2703    // Sorted from most to least likely to be pasted into an editor,
2704    // which matters when we iterate through them trying to see if
2705    // clipboard content matches them.
2706    /// .png
2707    Png,
2708    /// .jpeg or .jpg
2709    Jpeg,
2710    /// .webp
2711    Webp,
2712    /// .gif
2713    Gif,
2714    /// .svg
2715    Svg,
2716    /// .bmp
2717    Bmp,
2718    /// .tif or .tiff
2719    Tiff,
2720}
2721
2722impl ImageFormat {
2723    /// Returns the mime type for the ImageFormat
2724    pub const fn mime_type(self) -> &'static str {
2725        match self {
2726            ImageFormat::Png => "image/png",
2727            ImageFormat::Jpeg => "image/jpeg",
2728            ImageFormat::Webp => "image/webp",
2729            ImageFormat::Gif => "image/gif",
2730            ImageFormat::Svg => "image/svg+xml",
2731            ImageFormat::Bmp => "image/bmp",
2732            ImageFormat::Tiff => "image/tiff",
2733        }
2734    }
2735
2736    /// Returns the ImageFormat for the given mime type
2737    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
2738        match mime_type {
2739            "image/png" => Some(Self::Png),
2740            "image/jpeg" | "image/jpg" => Some(Self::Jpeg),
2741            "image/webp" => Some(Self::Webp),
2742            "image/gif" => Some(Self::Gif),
2743            "image/svg+xml" => Some(Self::Svg),
2744            "image/bmp" => Some(Self::Bmp),
2745            "image/tiff" | "image/tif" => Some(Self::Tiff),
2746            _ => None,
2747        }
2748    }
2749}
2750
2751/// An image, with a format and certain bytes
2752#[derive(Clone, Debug, PartialEq, Eq)]
2753pub struct Image {
2754    /// The image format the bytes represent (e.g. PNG)
2755    pub format: ImageFormat,
2756    /// The raw image bytes
2757    pub bytes: Vec<u8>,
2758    /// The unique ID for the image
2759    id: u64,
2760}
2761
2762impl Image {
2763    /// Creates an image from encoded bytes and derives its stable clipboard identifier.
2764    pub fn new(format: ImageFormat, bytes: Vec<u8>) -> Self {
2765        let id = crate::hash(&bytes);
2766        Self { format, bytes, id }
2767    }
2768}
2769
2770impl Hash for Image {
2771    fn hash<H: Hasher>(&self, state: &mut H) {
2772        state.write_u64(self.id);
2773    }
2774}
2775
2776pub(crate) fn decode_static_image(
2777    bytes: &[u8],
2778    format: image::ImageFormat,
2779) -> Result<SmallVec<[Frame; 1]>> {
2780    let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
2781        .into_decoder()
2782        .context("creating image decoder")?;
2783    decode_static_image_from_decoder(decoder)
2784}
2785
2786pub(crate) fn decode_static_image_from_decoder(
2787    mut decoder: impl image::ImageDecoder,
2788) -> Result<SmallVec<[Frame; 1]>> {
2789    let orientation = decoder.orientation().context("reading image orientation")?;
2790    let mut image = DynamicImage::from_decoder(decoder).context("decoding static image")?;
2791    image.apply_orientation(orientation);
2792
2793    let mut data = image.into_rgba8();
2794    for pixel in data.chunks_exact_mut(4) {
2795        pixel.swap(0, 2);
2796    }
2797
2798    Ok(SmallVec::from_elem(Frame::new(data), 1))
2799}
2800
2801impl Image {
2802    /// An empty image containing no data
2803    pub fn empty() -> Self {
2804        Self::from_bytes(ImageFormat::Png, Vec::new())
2805    }
2806
2807    /// Create an image from a format and bytes
2808    pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
2809        Self {
2810            id: hash(&bytes),
2811            format,
2812            bytes,
2813        }
2814    }
2815
2816    /// Get this image's ID
2817    pub fn id(&self) -> u64 {
2818        self.id
2819    }
2820
2821    /// Use the GPUI `use_asset` API to make this image renderable
2822    pub fn use_render_image(
2823        self: Arc<Self>,
2824        window: &mut Window,
2825        cx: &mut App,
2826    ) -> Option<Arc<RenderImage>> {
2827        ImageSource::Image(self)
2828            .use_data(None, window, cx)
2829            .and_then(|result| result.ok())
2830    }
2831
2832    /// Use the GPUI `get_asset` API to make this image renderable
2833    pub fn get_render_image(
2834        self: Arc<Self>,
2835        window: &mut Window,
2836        cx: &mut App,
2837    ) -> Option<Arc<RenderImage>> {
2838        ImageSource::Image(self)
2839            .get_data(None, window, cx)
2840            .and_then(|result| result.ok())
2841    }
2842
2843    /// Use the GPUI `remove_asset` API to drop this image, if possible.
2844    pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
2845        ImageSource::Image(self).remove_asset(cx);
2846    }
2847
2848    /// Convert the clipboard image to an `ImageData` object.
2849    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
2850        let frames = match self.format {
2851            #[cfg(feature = "image-format-gif")]
2852            ImageFormat::Gif => {
2853                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
2854                let mut frames = SmallVec::new();
2855
2856                for frame in decoder.into_frames() {
2857                    let mut frame = frame?;
2858                    // Convert from RGBA to BGRA.
2859                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
2860                        pixel.swap(0, 2);
2861                    }
2862                    frames.push(frame);
2863                }
2864
2865                frames
2866            }
2867            #[cfg(not(feature = "image-format-gif"))]
2868            ImageFormat::Gif => decode_static_image(&self.bytes, image::ImageFormat::Gif)?,
2869            ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
2870            ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
2871            ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
2872            ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
2873            ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
2874            ImageFormat::Svg => {
2875                return svg_renderer
2876                    .render_single_frame(&self.bytes, 1.0)
2877                    .map_err(Into::into);
2878            }
2879        };
2880
2881        Ok(Arc::new(RenderImage::new(frames)))
2882    }
2883
2884    /// Get the format of the clipboard image
2885    pub fn format(&self) -> ImageFormat {
2886        self.format
2887    }
2888
2889    /// Get the raw bytes of the clipboard image
2890    pub fn bytes(&self) -> &[u8] {
2891        self.bytes.as_slice()
2892    }
2893}
2894
2895#[cfg(test)]
2896mod image_tests {
2897    use super::*;
2898
2899    #[test]
2900    fn image_to_image_data_applies_exif_orientation() {
2901        let image = Image::from_bytes(
2902            ImageFormat::Jpeg,
2903            include_bytes!("../test_data/exif-orientation-rotate-180.jpg").to_vec(),
2904        );
2905
2906        let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
2907
2908        assert_eq!(render_image.size(0), size(16.into(), 32.into()));
2909        let bytes = render_image.as_bytes(0).unwrap();
2910        assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
2911        assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
2912    }
2913}
2914
2915/// A clipboard item that should be copied to the clipboard
2916#[derive(Clone, Debug, Eq, PartialEq)]
2917pub struct ClipboardString {
2918    pub(crate) text: String,
2919    pub(crate) metadata: Option<String>,
2920}
2921
2922impl ClipboardString {
2923    /// Create a new clipboard string with the given text
2924    pub fn new(text: String) -> Self {
2925        Self {
2926            text,
2927            metadata: None,
2928        }
2929    }
2930
2931    /// Replace the associated metadata with an opaque string.
2932    #[doc(hidden)]
2933    pub fn with_metadata(mut self, metadata: String) -> Self {
2934        self.metadata = Some(metadata);
2935        self
2936    }
2937
2938    /// Return a new clipboard item with the metadata replaced by the given metadata,
2939    /// after serializing it as JSON.
2940    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
2941        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
2942        self
2943    }
2944
2945    /// Get the text of the clipboard string
2946    pub fn text(&self) -> &String {
2947        &self.text
2948    }
2949
2950    /// Get the owned text of the clipboard string
2951    pub fn into_text(self) -> String {
2952        self.text
2953    }
2954
2955    /// Get the metadata of the clipboard string, formatted as JSON
2956    pub fn metadata_json<T>(&self) -> Option<T>
2957    where
2958        T: for<'a> Deserialize<'a>,
2959    {
2960        self.metadata
2961            .as_ref()
2962            .and_then(|m| serde_json::from_str(m).ok())
2963    }
2964
2965    /// Returns the raw metadata string associated with this clipboard entry.
2966    #[doc(hidden)]
2967    pub fn metadata(&self) -> Option<&str> {
2968        self.metadata.as_deref()
2969    }
2970
2971    #[doc(hidden)]
2972    pub fn text_hash(text: &str) -> u64 {
2973        let mut hasher = SeaHasher::new();
2974        text.hash(&mut hasher);
2975        hasher.finish()
2976    }
2977}
2978
2979impl From<String> for ClipboardString {
2980    fn from(value: String) -> Self {
2981        Self {
2982            text: value,
2983            metadata: None,
2984        }
2985    }
2986}
2987
2988#[cfg(test)]
2989mod clipboard_string_tests {
2990    use super::ClipboardString;
2991
2992    #[test]
2993    fn raw_metadata_preserves_the_clipboard_text() {
2994        let clipboard_string = ClipboardString::new("copied text".to_owned())
2995            .with_metadata("application/x-fc-gpui".to_owned());
2996
2997        assert_eq!(clipboard_string.text(), "copied text");
2998        assert_eq!(clipboard_string.metadata(), Some("application/x-fc-gpui"));
2999    }
3000}