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, GlobalPixels,
 27    GlyphId, Keymap, LineLayout, Pixels, PlatformInput, Point, RenderGlyphParams,
 28    RenderImageParams, 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::*;
 56#[cfg(any(test, feature = "test-support"))]
 57pub(crate) use test::*;
 58use time::UtcOffset;
 59pub use util::SemanticVersion;
 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_documents(&self, _paths: &[PathBuf]) {}
122    fn clear_recent_documents(&self) {}
123    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
124    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
125    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
126
127    fn os_name(&self) -> &'static str;
128    fn os_version(&self) -> Result<SemanticVersion>;
129    fn app_version(&self) -> Result<SemanticVersion>;
130    fn app_path(&self) -> Result<PathBuf>;
131    fn local_timezone(&self) -> UtcOffset;
132    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
133
134    fn set_cursor_style(&self, style: CursorStyle);
135    fn should_auto_hide_scrollbars(&self) -> bool;
136
137    fn write_to_clipboard(&self, item: ClipboardItem);
138    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
139
140    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
141    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
142    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
143}
144
145/// A handle to a platform's display, e.g. a monitor or laptop screen.
146pub trait PlatformDisplay: Send + Sync + Debug {
147    /// Get the ID for this display
148    fn id(&self) -> DisplayId;
149
150    /// Returns a stable identifier for this display that can be persisted and used
151    /// across system restarts.
152    fn uuid(&self) -> Result<Uuid>;
153
154    /// Get the bounds for this display
155    fn bounds(&self) -> Bounds<GlobalPixels>;
156}
157
158/// An opaque identifier for a hardware display
159#[derive(PartialEq, Eq, Hash, Copy, Clone)]
160pub struct DisplayId(pub(crate) u32);
161
162impl Debug for DisplayId {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        write!(f, "DisplayId({})", self.0)
165    }
166}
167
168unsafe impl Send for DisplayId {}
169
170pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
171    fn bounds(&self) -> Bounds<GlobalPixels>;
172    fn is_maximized(&self) -> bool;
173    fn is_minimized(&self) -> bool;
174    fn content_size(&self) -> Size<Pixels>;
175    fn scale_factor(&self) -> f32;
176    fn appearance(&self) -> WindowAppearance;
177    fn display(&self) -> Rc<dyn PlatformDisplay>;
178    fn mouse_position(&self) -> Point<Pixels>;
179    fn modifiers(&self) -> Modifiers;
180    fn as_any_mut(&mut self) -> &mut dyn Any;
181    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
182    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
183    fn prompt(
184        &self,
185        level: PromptLevel,
186        msg: &str,
187        detail: Option<&str>,
188        answers: &[&str],
189    ) -> Option<oneshot::Receiver<usize>>;
190    fn activate(&self);
191    fn is_active(&self) -> bool;
192    fn set_title(&mut self, title: &str);
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    /// None -> inherit, Some(bounds) -> set bounds
512    pub bounds: Option<Bounds<GlobalPixels>>,
513
514    /// The titlebar configuration of the window
515    pub titlebar: Option<TitlebarOptions>,
516
517    /// Whether the window should be focused when created
518    pub focus: bool,
519
520    /// Whether the window should be shown when created
521    pub show: bool,
522
523    /// Whether the window should be fullscreen when created
524    pub fullscreen: bool,
525
526    /// The kind of window to create
527    pub kind: WindowKind,
528
529    /// Whether the window should be movable by the user
530    pub is_movable: bool,
531
532    /// The display to create the window on
533    pub display_id: Option<DisplayId>,
534}
535
536/// The variables that can be configured when creating a new window
537#[derive(Debug)]
538pub(crate) struct WindowParams {
539    ///
540    pub bounds: Bounds<GlobalPixels>,
541
542    /// The titlebar configuration of the window
543    pub titlebar: Option<TitlebarOptions>,
544
545    /// The kind of window to create
546    pub kind: WindowKind,
547
548    /// Whether the window should be movable by the user
549    pub is_movable: bool,
550
551    pub focus: bool,
552
553    pub show: bool,
554
555    /// The display to create the window on
556    pub display_id: Option<DisplayId>,
557}
558
559impl Default for WindowOptions {
560    fn default() -> Self {
561        Self {
562            bounds: None,
563            titlebar: Some(TitlebarOptions {
564                title: Default::default(),
565                appears_transparent: Default::default(),
566                traffic_light_position: Default::default(),
567            }),
568            focus: true,
569            show: true,
570            kind: WindowKind::Normal,
571            is_movable: true,
572            display_id: None,
573            fullscreen: false,
574        }
575    }
576}
577
578/// The options that can be configured for a window's titlebar
579#[derive(Debug, Default)]
580pub struct TitlebarOptions {
581    /// The initial title of the window
582    pub title: Option<SharedString>,
583
584    /// Whether the titlebar should appear transparent
585    pub appears_transparent: bool,
586
587    /// The position of the macOS traffic light buttons
588    pub traffic_light_position: Option<Point<Pixels>>,
589}
590
591/// The kind of window to create
592#[derive(Copy, Clone, Debug, PartialEq, Eq)]
593pub enum WindowKind {
594    /// A normal application window
595    Normal,
596
597    /// A window that appears above all other windows, usually used for alerts or popups
598    /// use sparingly!
599    PopUp,
600}
601
602/// Platform level interface
603/// bounds: Bounds<GlobalPixels>
604/// fullscreen: bool
605
606/// The appearance of the window, as defined by the operating system.
607///
608/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
609/// values.
610#[derive(Copy, Clone, Debug)]
611pub enum WindowAppearance {
612    /// A light appearance.
613    ///
614    /// On macOS, this corresponds to the `aqua` appearance.
615    Light,
616
617    /// A light appearance with vibrant colors.
618    ///
619    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
620    VibrantLight,
621
622    /// A dark appearance.
623    ///
624    /// On macOS, this corresponds to the `darkAqua` appearance.
625    Dark,
626
627    /// A dark appearance with vibrant colors.
628    ///
629    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
630    VibrantDark,
631}
632
633impl Default for WindowAppearance {
634    fn default() -> Self {
635        Self::Light
636    }
637}
638
639/// The options that can be configured for a file dialog prompt
640#[derive(Copy, Clone, Debug)]
641pub struct PathPromptOptions {
642    /// Should the prompt allow files to be selected?
643    pub files: bool,
644    /// Should the prompt allow directories to be selected?
645    pub directories: bool,
646    /// Should the prompt allow multiple files to be selected?
647    pub multiple: bool,
648}
649
650/// What kind of prompt styling to show
651#[derive(Copy, Clone, Debug)]
652pub enum PromptLevel {
653    /// A prompt that is shown when the user should be notified of something
654    Info,
655
656    /// A prompt that is shown when the user needs to be warned of a potential problem
657    Warning,
658
659    /// A prompt that is shown when a critical problem has occurred
660    Critical,
661}
662
663/// The style of the cursor (pointer)
664#[derive(Copy, Clone, Debug)]
665pub enum CursorStyle {
666    /// The default cursor
667    Arrow,
668
669    /// A text input cursor
670    /// corresponds to the CSS cursor value `text`
671    IBeam,
672
673    /// A crosshair cursor
674    /// corresponds to the CSS cursor value `crosshair`
675    Crosshair,
676
677    /// A closed hand cursor
678    /// corresponds to the CSS cursor value `grabbing`
679    ClosedHand,
680
681    /// An open hand cursor
682    /// corresponds to the CSS cursor value `grab`
683    OpenHand,
684
685    /// A pointing hand cursor
686    /// corresponds to the CSS cursor value `pointer`
687    PointingHand,
688
689    /// A resize left cursor
690    /// corresponds to the CSS cursor value `w-resize`
691    ResizeLeft,
692
693    /// A resize right cursor
694    /// corresponds to the CSS cursor value `e-resize`
695    ResizeRight,
696
697    /// A resize cursor to the left and right
698    /// corresponds to the CSS cursor value `col-resize`
699    ResizeLeftRight,
700
701    /// A resize up cursor
702    /// corresponds to the CSS cursor value `n-resize`
703    ResizeUp,
704
705    /// A resize down cursor
706    /// corresponds to the CSS cursor value `s-resize`
707    ResizeDown,
708
709    /// A resize cursor directing up and down
710    /// corresponds to the CSS cursor value `row-resize`
711    ResizeUpDown,
712
713    /// A cursor indicating that something will disappear if moved here
714    /// Does not correspond to a CSS cursor value
715    DisappearingItem,
716
717    /// A text input cursor for vertical layout
718    /// corresponds to the CSS cursor value `vertical-text`
719    IBeamCursorForVerticalLayout,
720
721    /// A cursor indicating that the operation is not allowed
722    /// corresponds to the CSS cursor value `not-allowed`
723    OperationNotAllowed,
724
725    /// A cursor indicating that the operation will result in a link
726    /// corresponds to the CSS cursor value `alias`
727    DragLink,
728
729    /// A cursor indicating that the operation will result in a copy
730    /// corresponds to the CSS cursor value `copy`
731    DragCopy,
732
733    /// A cursor indicating that the operation will result in a context menu
734    /// corresponds to the CSS cursor value `context-menu`
735    ContextualMenu,
736}
737
738impl Default for CursorStyle {
739    fn default() -> Self {
740        Self::Arrow
741    }
742}
743
744/// A clipboard item that should be copied to the clipboard
745#[derive(Clone, Debug, Eq, PartialEq)]
746pub struct ClipboardItem {
747    pub(crate) text: String,
748    pub(crate) metadata: Option<String>,
749}
750
751impl ClipboardItem {
752    /// Create a new clipboard item with the given text
753    pub fn new(text: String) -> Self {
754        Self {
755            text,
756            metadata: None,
757        }
758    }
759
760    /// Create a new clipboard item with the given text and metadata
761    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
762        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
763        self
764    }
765
766    /// Get the text of the clipboard item
767    pub fn text(&self) -> &String {
768        &self.text
769    }
770
771    /// Get the metadata of the clipboard item
772    pub fn metadata<T>(&self) -> Option<T>
773    where
774        T: for<'a> Deserialize<'a>,
775    {
776        self.metadata
777            .as_ref()
778            .and_then(|m| serde_json::from_str(m).ok())
779    }
780
781    pub(crate) fn text_hash(text: &str) -> u64 {
782        let mut hasher = SeaHasher::new();
783        text.hash(&mut hasher);
784        hasher.finish()
785    }
786}