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