platform.rs

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