platform.rs

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