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