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