platform.rs

  1// todo(windows): remove
  2#![cfg_attr(windows, allow(dead_code))]
  3
  4mod app_menu;
  5mod keystroke;
  6
  7#[cfg(not(target_os = "macos"))]
  8mod cosmic_text;
  9
 10#[cfg(target_os = "linux")]
 11mod linux;
 12
 13#[cfg(target_os = "macos")]
 14mod mac;
 15
 16#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-blade"))]
 17mod blade;
 18
 19#[cfg(any(test, feature = "test-support"))]
 20mod test;
 21
 22#[cfg(target_os = "windows")]
 23mod windows;
 24
 25use crate::{
 26    point, Action, AnyWindowHandle, AsyncWindowContext, BackgroundExecutor, Bounds, DevicePixels,
 27    DispatchEventResult, Font, FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, Keymap,
 28    LineLayout, Pixels, PlatformInput, Point, RenderGlyphParams, RenderImageParams,
 29    RenderSvgParams, Scene, SharedString, Size, Task, TaskLabel, WindowContext,
 30    DEFAULT_WINDOW_SIZE,
 31};
 32use anyhow::Result;
 33use async_task::Runnable;
 34use futures::channel::oneshot;
 35use parking::Unparker;
 36use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
 37use seahash::SeaHasher;
 38use serde::{Deserialize, Serialize};
 39use std::borrow::Cow;
 40use std::hash::{Hash, Hasher};
 41use std::time::Duration;
 42use std::{
 43    fmt::{self, Debug},
 44    ops::Range,
 45    path::{Path, PathBuf},
 46    rc::Rc,
 47    sync::Arc,
 48};
 49use uuid::Uuid;
 50
 51pub use app_menu::*;
 52pub use keystroke::*;
 53
 54#[cfg(not(target_os = "macos"))]
 55pub(crate) use cosmic_text::*;
 56#[cfg(target_os = "linux")]
 57pub(crate) use linux::*;
 58#[cfg(target_os = "macos")]
 59pub(crate) use mac::*;
 60pub use semantic_version::SemanticVersion;
 61#[cfg(any(test, feature = "test-support"))]
 62pub(crate) use test::*;
 63use time::UtcOffset;
 64#[cfg(target_os = "windows")]
 65pub(crate) use windows::*;
 66
 67#[cfg(target_os = "macos")]
 68pub(crate) fn current_platform() -> Rc<dyn Platform> {
 69    Rc::new(MacPlatform::new())
 70}
 71#[cfg(target_os = "linux")]
 72pub(crate) fn current_platform() -> Rc<dyn Platform> {
 73    let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
 74    let x11_display = std::env::var_os("DISPLAY");
 75
 76    let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
 77    let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
 78
 79    if use_wayland {
 80        Rc::new(WaylandClient::new())
 81    } else if use_x11 {
 82        Rc::new(X11Client::new())
 83    } else {
 84        Rc::new(HeadlessClient::new())
 85    }
 86}
 87// todo("windows")
 88#[cfg(target_os = "windows")]
 89pub(crate) fn current_platform() -> Rc<dyn Platform> {
 90    Rc::new(WindowsPlatform::new())
 91}
 92
 93pub(crate) trait Platform: 'static {
 94    fn background_executor(&self) -> BackgroundExecutor;
 95    fn foreground_executor(&self) -> ForegroundExecutor;
 96    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
 97
 98    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
 99    fn quit(&self);
100    fn restart(&self, binary_path: Option<PathBuf>);
101    fn activate(&self, ignoring_other_apps: bool);
102    fn hide(&self);
103    fn hide_other_apps(&self);
104    fn unhide_other_apps(&self);
105
106    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
107    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
108    fn active_window(&self) -> Option<AnyWindowHandle>;
109    fn can_open_windows(&self) -> anyhow::Result<()> {
110        Ok(())
111    }
112    fn open_window(
113        &self,
114        handle: AnyWindowHandle,
115        options: WindowParams,
116    ) -> Box<dyn PlatformWindow>;
117
118    /// Returns the appearance of the application's windows.
119    fn window_appearance(&self) -> WindowAppearance;
120
121    fn open_url(&self, url: &str);
122    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
123    fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
124
125    fn prompt_for_paths(
126        &self,
127        options: PathPromptOptions,
128    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
129    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
130    fn reveal_path(&self, path: &Path);
131
132    fn on_quit(&self, callback: Box<dyn FnMut()>);
133    fn on_reopen(&self, callback: Box<dyn FnMut()>);
134
135    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
136    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
137        None
138    }
139
140    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
141    fn add_recent_document(&self, _path: &Path) {}
142    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
143    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
144    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
145
146    fn os_name(&self) -> &'static str;
147    fn os_version(&self) -> Result<SemanticVersion>;
148    fn app_version(&self) -> Result<SemanticVersion>;
149    fn app_path(&self) -> Result<PathBuf>;
150    fn local_timezone(&self) -> UtcOffset;
151    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
152
153    fn set_cursor_style(&self, style: CursorStyle);
154    fn should_auto_hide_scrollbars(&self) -> bool;
155
156    #[cfg(target_os = "linux")]
157    fn write_to_primary(&self, item: ClipboardItem);
158    fn write_to_clipboard(&self, item: ClipboardItem);
159    #[cfg(target_os = "linux")]
160    fn read_from_primary(&self) -> Option<ClipboardItem>;
161    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
162
163    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
164    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
165    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
166}
167
168/// A handle to a platform's display, e.g. a monitor or laptop screen.
169pub trait PlatformDisplay: Send + Sync + Debug {
170    /// Get the ID for this display
171    fn id(&self) -> DisplayId;
172
173    /// Returns a stable identifier for this display that can be persisted and used
174    /// across system restarts.
175    fn uuid(&self) -> Result<Uuid>;
176
177    /// Get the bounds for this display
178    fn bounds(&self) -> Bounds<DevicePixels>;
179
180    /// Get the default bounds for this display to place a window
181    fn default_bounds(&self) -> Bounds<DevicePixels> {
182        let center = self.bounds().center();
183        let offset = DEFAULT_WINDOW_SIZE / 2;
184        let origin = point(center.x - offset.width, center.y - offset.height);
185        Bounds::new(origin, DEFAULT_WINDOW_SIZE)
186    }
187}
188
189/// An opaque identifier for a hardware display
190#[derive(PartialEq, Eq, Hash, Copy, Clone)]
191pub struct DisplayId(pub(crate) u32);
192
193impl Debug for DisplayId {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        write!(f, "DisplayId({})", self.0)
196    }
197}
198
199unsafe impl Send for DisplayId {}
200
201pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
202    fn bounds(&self) -> Bounds<DevicePixels>;
203    fn is_maximized(&self) -> bool;
204    fn window_bounds(&self) -> WindowBounds;
205    fn content_size(&self) -> Size<Pixels>;
206    fn scale_factor(&self) -> f32;
207    fn appearance(&self) -> WindowAppearance;
208    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
209    fn mouse_position(&self) -> Point<Pixels>;
210    fn modifiers(&self) -> Modifiers;
211    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
212    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
213    fn prompt(
214        &self,
215        level: PromptLevel,
216        msg: &str,
217        detail: Option<&str>,
218        answers: &[&str],
219    ) -> Option<oneshot::Receiver<usize>>;
220    fn activate(&self);
221    fn is_active(&self) -> bool;
222    fn set_title(&mut self, title: &str);
223    fn set_app_id(&mut self, app_id: &str);
224    fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance);
225    fn set_edited(&mut self, edited: bool);
226    fn show_character_palette(&self);
227    fn minimize(&self);
228    fn zoom(&self);
229    fn toggle_fullscreen(&self);
230    fn is_fullscreen(&self) -> bool;
231    fn on_request_frame(&self, callback: Box<dyn FnMut()>);
232    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
233    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
234    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
235    fn on_moved(&self, callback: Box<dyn FnMut()>);
236    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
237    fn on_close(&self, callback: Box<dyn FnOnce()>);
238    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
239    fn draw(&self, scene: &Scene);
240    fn completed_frame(&self) {}
241    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
242
243    #[cfg(target_os = "windows")]
244    fn get_raw_handle(&self) -> windows::HWND;
245
246    fn show_window_menu(&self, position: Point<Pixels>);
247    fn start_system_move(&self);
248    fn should_render_window_controls(&self) -> bool;
249
250    #[cfg(any(test, feature = "test-support"))]
251    fn as_test(&mut self) -> Option<&mut TestWindow> {
252        None
253    }
254}
255
256/// This type is public so that our test macro can generate and use it, but it should not
257/// be considered part of our public API.
258#[doc(hidden)]
259pub trait PlatformDispatcher: Send + Sync {
260    fn is_main_thread(&self) -> bool;
261    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
262    fn dispatch_on_main_thread(&self, runnable: Runnable);
263    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
264    fn park(&self, timeout: Option<Duration>) -> bool;
265    fn unparker(&self) -> Unparker;
266
267    #[cfg(any(test, feature = "test-support"))]
268    fn as_test(&self) -> Option<&TestDispatcher> {
269        None
270    }
271}
272
273pub(crate) trait PlatformTextSystem: Send + Sync {
274    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
275    fn all_font_names(&self) -> Vec<String>;
276    fn all_font_families(&self) -> Vec<String>;
277    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
278    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
279    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
280    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
281    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
282    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
283    fn rasterize_glyph(
284        &self,
285        params: &RenderGlyphParams,
286        raster_bounds: Bounds<DevicePixels>,
287    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
288    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
289}
290
291/// Basic metadata about the current application and operating system.
292#[derive(Clone, Debug)]
293pub struct AppMetadata {
294    /// The name of the current operating system
295    pub os_name: &'static str,
296
297    /// The operating system's version
298    pub os_version: Option<SemanticVersion>,
299
300    /// The current version of the application
301    pub app_version: Option<SemanticVersion>,
302}
303
304#[derive(PartialEq, Eq, Hash, Clone)]
305pub(crate) enum AtlasKey {
306    Glyph(RenderGlyphParams),
307    Svg(RenderSvgParams),
308    Image(RenderImageParams),
309}
310
311impl AtlasKey {
312    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
313        match self {
314            AtlasKey::Glyph(params) => {
315                if params.is_emoji {
316                    AtlasTextureKind::Polychrome
317                } else {
318                    AtlasTextureKind::Monochrome
319                }
320            }
321            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
322            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
323        }
324    }
325}
326
327impl From<RenderGlyphParams> for AtlasKey {
328    fn from(params: RenderGlyphParams) -> Self {
329        Self::Glyph(params)
330    }
331}
332
333impl From<RenderSvgParams> for AtlasKey {
334    fn from(params: RenderSvgParams) -> Self {
335        Self::Svg(params)
336    }
337}
338
339impl From<RenderImageParams> for AtlasKey {
340    fn from(params: RenderImageParams) -> Self {
341        Self::Image(params)
342    }
343}
344
345pub(crate) trait PlatformAtlas: Send + Sync {
346    fn get_or_insert_with<'a>(
347        &self,
348        key: &AtlasKey,
349        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
350    ) -> Result<Option<AtlasTile>>;
351}
352
353#[derive(Clone, Debug, PartialEq, Eq)]
354#[repr(C)]
355pub(crate) struct AtlasTile {
356    pub(crate) texture_id: AtlasTextureId,
357    pub(crate) tile_id: TileId,
358    pub(crate) padding: u32,
359    pub(crate) bounds: Bounds<DevicePixels>,
360}
361
362#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
363#[repr(C)]
364pub(crate) struct AtlasTextureId {
365    // We use u32 instead of usize for Metal Shader Language compatibility
366    pub(crate) index: u32,
367    pub(crate) kind: AtlasTextureKind,
368}
369
370#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
371#[repr(C)]
372pub(crate) enum AtlasTextureKind {
373    Monochrome = 0,
374    Polychrome = 1,
375    Path = 2,
376}
377
378#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
379#[repr(C)]
380pub(crate) struct TileId(pub(crate) u32);
381
382impl From<etagere::AllocId> for TileId {
383    fn from(id: etagere::AllocId) -> Self {
384        Self(id.serialize())
385    }
386}
387
388impl From<TileId> for etagere::AllocId {
389    fn from(id: TileId) -> Self {
390        Self::deserialize(id.0)
391    }
392}
393
394pub(crate) struct PlatformInputHandler {
395    cx: AsyncWindowContext,
396    handler: Box<dyn InputHandler>,
397}
398
399impl PlatformInputHandler {
400    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
401        Self { cx, handler }
402    }
403
404    fn selected_text_range(&mut self) -> Option<Range<usize>> {
405        self.cx
406            .update(|cx| self.handler.selected_text_range(cx))
407            .ok()
408            .flatten()
409    }
410
411    fn marked_text_range(&mut self) -> Option<Range<usize>> {
412        self.cx
413            .update(|cx| self.handler.marked_text_range(cx))
414            .ok()
415            .flatten()
416    }
417
418    #[cfg_attr(target_os = "linux", allow(dead_code))]
419    fn text_for_range(&mut self, range_utf16: Range<usize>) -> Option<String> {
420        self.cx
421            .update(|cx| self.handler.text_for_range(range_utf16, cx))
422            .ok()
423            .flatten()
424    }
425
426    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
427        self.cx
428            .update(|cx| {
429                self.handler
430                    .replace_text_in_range(replacement_range, text, cx);
431            })
432            .ok();
433    }
434
435    fn replace_and_mark_text_in_range(
436        &mut self,
437        range_utf16: Option<Range<usize>>,
438        new_text: &str,
439        new_selected_range: Option<Range<usize>>,
440    ) {
441        self.cx
442            .update(|cx| {
443                self.handler.replace_and_mark_text_in_range(
444                    range_utf16,
445                    new_text,
446                    new_selected_range,
447                    cx,
448                )
449            })
450            .ok();
451    }
452
453    fn unmark_text(&mut self) {
454        self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
455    }
456
457    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
458        self.cx
459            .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
460            .ok()
461            .flatten()
462    }
463
464    pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
465        self.handler.replace_text_in_range(None, input, cx);
466    }
467}
468
469/// Zed's interface for handling text input from the platform's IME system
470/// This is currently a 1:1 exposure of the NSTextInputClient API:
471///
472/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
473pub trait InputHandler: 'static {
474    /// Get the range of the user's currently selected text, if any
475    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
476    ///
477    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
478    fn selected_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
479
480    /// Get the range of the currently marked text, if any
481    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
482    ///
483    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
484    fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
485
486    /// Get the text for the given document range in UTF-16 characters
487    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
488    ///
489    /// range_utf16 is in terms of UTF-16 characters
490    fn text_for_range(
491        &mut self,
492        range_utf16: Range<usize>,
493        cx: &mut WindowContext,
494    ) -> Option<String>;
495
496    /// Replace the text in the given document range with the given text
497    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
498    ///
499    /// replacement_range is in terms of UTF-16 characters
500    fn replace_text_in_range(
501        &mut self,
502        replacement_range: Option<Range<usize>>,
503        text: &str,
504        cx: &mut WindowContext,
505    );
506
507    /// Replace the text in the given document range with the given text,
508    /// and mark the given text as part of of an IME 'composing' state
509    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
510    ///
511    /// range_utf16 is in terms of UTF-16 characters
512    /// new_selected_range is in terms of UTF-16 characters
513    fn replace_and_mark_text_in_range(
514        &mut self,
515        range_utf16: Option<Range<usize>>,
516        new_text: &str,
517        new_selected_range: Option<Range<usize>>,
518        cx: &mut WindowContext,
519    );
520
521    /// Remove the IME 'composing' state from the document
522    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
523    fn unmark_text(&mut self, cx: &mut WindowContext);
524
525    /// Get the bounds of the given document range in screen coordinates
526    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
527    ///
528    /// This is used for positioning the IME candidate window
529    fn bounds_for_range(
530        &mut self,
531        range_utf16: Range<usize>,
532        cx: &mut WindowContext,
533    ) -> Option<Bounds<Pixels>>;
534}
535
536/// The variables that can be configured when creating a new window
537#[derive(Debug)]
538pub struct WindowOptions {
539    /// Specifies the state and bounds of the window in screen coordinates.
540    /// - `None`: Inherit the bounds.
541    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
542    pub window_bounds: Option<WindowBounds>,
543
544    /// The titlebar configuration of the window
545    pub titlebar: Option<TitlebarOptions>,
546
547    /// Whether the window should be focused when created
548    pub focus: bool,
549
550    /// Whether the window should be shown when created
551    pub show: bool,
552
553    /// The kind of window to create
554    pub kind: WindowKind,
555
556    /// Whether the window should be movable by the user
557    pub is_movable: bool,
558
559    /// The display to create the window on, if this is None,
560    /// the window will be created on the main display
561    pub display_id: Option<DisplayId>,
562
563    /// The appearance of the window background.
564    pub window_background: WindowBackgroundAppearance,
565
566    /// Application identifier of the window. Can by used by desktop environments to group applications together.
567    pub app_id: Option<String>,
568}
569
570/// The variables that can be configured when creating a new window
571#[derive(Debug)]
572pub(crate) struct WindowParams {
573    pub bounds: Bounds<DevicePixels>,
574
575    /// The titlebar configuration of the window
576    pub titlebar: Option<TitlebarOptions>,
577
578    /// The kind of window to create
579    #[cfg_attr(target_os = "linux", allow(dead_code))]
580    pub kind: WindowKind,
581
582    /// Whether the window should be movable by the user
583    #[cfg_attr(target_os = "linux", allow(dead_code))]
584    pub is_movable: bool,
585
586    #[cfg_attr(target_os = "linux", allow(dead_code))]
587    pub focus: bool,
588
589    #[cfg_attr(target_os = "linux", allow(dead_code))]
590    pub show: bool,
591
592    pub display_id: Option<DisplayId>,
593
594    pub window_background: WindowBackgroundAppearance,
595}
596
597/// Represents the status of how a window should be opened.
598#[derive(Debug, Copy, Clone, PartialEq)]
599pub enum WindowBounds {
600    /// Indicates that the window should open in a windowed state with the given bounds.
601    Windowed(Bounds<DevicePixels>),
602    /// Indicates that the window should open in a maximized state.
603    /// The bounds provided here represent the restore size of the window.
604    Maximized(Bounds<DevicePixels>),
605    /// Indicates that the window should open in fullscreen mode.
606    /// The bounds provided here represent the restore size of the window.
607    Fullscreen(Bounds<DevicePixels>),
608}
609
610impl Default for WindowBounds {
611    fn default() -> Self {
612        WindowBounds::Windowed(Bounds::default())
613    }
614}
615
616impl WindowBounds {
617    /// Retrieve the inner bounds
618    pub fn get_bounds(&self) -> Bounds<DevicePixels> {
619        match self {
620            WindowBounds::Windowed(bounds) => *bounds,
621            WindowBounds::Maximized(bounds) => *bounds,
622            WindowBounds::Fullscreen(bounds) => *bounds,
623        }
624    }
625}
626
627impl Default for WindowOptions {
628    fn default() -> Self {
629        Self {
630            window_bounds: None,
631            titlebar: Some(TitlebarOptions {
632                title: Default::default(),
633                appears_transparent: Default::default(),
634                traffic_light_position: Default::default(),
635            }),
636            focus: true,
637            show: true,
638            kind: WindowKind::Normal,
639            is_movable: true,
640            display_id: None,
641            window_background: WindowBackgroundAppearance::default(),
642            app_id: None,
643        }
644    }
645}
646
647/// The options that can be configured for a window's titlebar
648#[derive(Debug, Default)]
649pub struct TitlebarOptions {
650    /// The initial title of the window
651    pub title: Option<SharedString>,
652
653    /// Whether the titlebar should appear transparent
654    pub appears_transparent: bool,
655
656    /// The position of the macOS traffic light buttons
657    pub traffic_light_position: Option<Point<Pixels>>,
658}
659
660/// The kind of window to create
661#[derive(Copy, Clone, Debug, PartialEq, Eq)]
662pub enum WindowKind {
663    /// A normal application window
664    Normal,
665
666    /// A window that appears above all other windows, usually used for alerts or popups
667    /// use sparingly!
668    PopUp,
669}
670
671/// The appearance of the window, as defined by the operating system.
672///
673/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
674/// values.
675#[derive(Copy, Clone, Debug)]
676pub enum WindowAppearance {
677    /// A light appearance.
678    ///
679    /// On macOS, this corresponds to the `aqua` appearance.
680    Light,
681
682    /// A light appearance with vibrant colors.
683    ///
684    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
685    VibrantLight,
686
687    /// A dark appearance.
688    ///
689    /// On macOS, this corresponds to the `darkAqua` appearance.
690    Dark,
691
692    /// A dark appearance with vibrant colors.
693    ///
694    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
695    VibrantDark,
696}
697
698impl Default for WindowAppearance {
699    fn default() -> Self {
700        Self::Light
701    }
702}
703
704/// The appearance of the background of the window itself, when there is
705/// no content or the content is transparent.
706#[derive(Copy, Clone, Debug, Default, PartialEq)]
707pub enum WindowBackgroundAppearance {
708    /// Opaque.
709    ///
710    /// This lets the window manager know that content behind this
711    /// window does not need to be drawn.
712    ///
713    /// Actual color depends on the system and themes should define a fully
714    /// opaque background color instead.
715    #[default]
716    Opaque,
717    /// Plain alpha transparency.
718    Transparent,
719    /// Transparency, but the contents behind the window are blurred.
720    ///
721    /// Not always supported.
722    Blurred,
723}
724
725/// The options that can be configured for a file dialog prompt
726#[derive(Copy, Clone, Debug)]
727pub struct PathPromptOptions {
728    /// Should the prompt allow files to be selected?
729    pub files: bool,
730    /// Should the prompt allow directories to be selected?
731    pub directories: bool,
732    /// Should the prompt allow multiple files to be selected?
733    pub multiple: bool,
734}
735
736/// What kind of prompt styling to show
737#[derive(Copy, Clone, Debug, PartialEq)]
738pub enum PromptLevel {
739    /// A prompt that is shown when the user should be notified of something
740    Info,
741
742    /// A prompt that is shown when the user needs to be warned of a potential problem
743    Warning,
744
745    /// A prompt that is shown when a critical problem has occurred
746    Critical,
747}
748
749/// The style of the cursor (pointer)
750#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
751pub enum CursorStyle {
752    /// The default cursor
753    Arrow,
754
755    /// A text input cursor
756    /// corresponds to the CSS cursor value `text`
757    IBeam,
758
759    /// A crosshair cursor
760    /// corresponds to the CSS cursor value `crosshair`
761    Crosshair,
762
763    /// A closed hand cursor
764    /// corresponds to the CSS cursor value `grabbing`
765    ClosedHand,
766
767    /// An open hand cursor
768    /// corresponds to the CSS cursor value `grab`
769    OpenHand,
770
771    /// A pointing hand cursor
772    /// corresponds to the CSS cursor value `pointer`
773    PointingHand,
774
775    /// A resize left cursor
776    /// corresponds to the CSS cursor value `w-resize`
777    ResizeLeft,
778
779    /// A resize right cursor
780    /// corresponds to the CSS cursor value `e-resize`
781    ResizeRight,
782
783    /// A resize cursor to the left and right
784    /// corresponds to the CSS cursor value `ew-resize`
785    ResizeLeftRight,
786
787    /// A resize up cursor
788    /// corresponds to the CSS cursor value `n-resize`
789    ResizeUp,
790
791    /// A resize down cursor
792    /// corresponds to the CSS cursor value `s-resize`
793    ResizeDown,
794
795    /// A resize cursor directing up and down
796    /// corresponds to the CSS cursor value `ns-resize`
797    ResizeUpDown,
798
799    /// A cursor indicating that the item/column can be resized horizontally.
800    /// corresponds to the CSS curosr value `col-resize`
801    ResizeColumn,
802
803    /// A cursor indicating that the item/row can be resized vertically.
804    /// corresponds to the CSS curosr value `row-resize`
805    ResizeRow,
806
807    /// A text input cursor for vertical layout
808    /// corresponds to the CSS cursor value `vertical-text`
809    IBeamCursorForVerticalLayout,
810
811    /// A cursor indicating that the operation is not allowed
812    /// corresponds to the CSS cursor value `not-allowed`
813    OperationNotAllowed,
814
815    /// A cursor indicating that the operation will result in a link
816    /// corresponds to the CSS cursor value `alias`
817    DragLink,
818
819    /// A cursor indicating that the operation will result in a copy
820    /// corresponds to the CSS cursor value `copy`
821    DragCopy,
822
823    /// A cursor indicating that the operation will result in a context menu
824    /// corresponds to the CSS cursor value `context-menu`
825    ContextualMenu,
826}
827
828impl Default for CursorStyle {
829    fn default() -> Self {
830        Self::Arrow
831    }
832}
833
834/// A clipboard item that should be copied to the clipboard
835#[derive(Clone, Debug, Eq, PartialEq)]
836pub struct ClipboardItem {
837    pub(crate) text: String,
838    pub(crate) metadata: Option<String>,
839}
840
841impl ClipboardItem {
842    /// Create a new clipboard item with the given text
843    pub fn new(text: String) -> Self {
844        Self {
845            text,
846            metadata: None,
847        }
848    }
849
850    /// Create a new clipboard item with the given text and metadata
851    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
852        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
853        self
854    }
855
856    /// Get the text of the clipboard item
857    pub fn text(&self) -> &String {
858        &self.text
859    }
860
861    /// Get the metadata of the clipboard item
862    pub fn metadata<T>(&self) -> Option<T>
863    where
864        T: for<'a> Deserialize<'a>,
865    {
866        self.metadata
867            .as_ref()
868            .and_then(|m| serde_json::from_str(m).ok())
869    }
870
871    #[cfg_attr(target_os = "linux", allow(dead_code))]
872    pub(crate) fn text_hash(text: &str) -> u64 {
873        let mut hasher = SeaHasher::new();
874        text.hash(&mut hasher);
875        hasher.finish()
876    }
877}