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