platform.rs

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