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