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