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