platform.rs

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