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        self.handler.replace_text_in_range(None, 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///
574/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
575/// values.
576#[derive(Copy, Clone, Debug)]
577pub enum WindowAppearance {
578    /// A light appearance.
579    ///
580    /// On macOS, this corresponds to the `aqua` appearance.
581    Light,
582
583    /// A light appearance with vibrant colors.
584    ///
585    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
586    VibrantLight,
587
588    /// A dark appearance.
589    ///
590    /// On macOS, this corresponds to the `darkAqua` appearance.
591    Dark,
592
593    /// A dark appearance with vibrant colors.
594    ///
595    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
596    VibrantDark,
597}
598
599impl Default for WindowAppearance {
600    fn default() -> Self {
601        Self::Light
602    }
603}
604
605/// The options that can be configured for a file dialog prompt
606#[derive(Copy, Clone, Debug)]
607pub struct PathPromptOptions {
608    /// Should the prompt allow files to be selected?
609    pub files: bool,
610    /// Should the prompt allow directories to be selected?
611    pub directories: bool,
612    /// Should the prompt allow multiple files to be selected?
613    pub multiple: bool,
614}
615
616/// What kind of prompt styling to show
617#[derive(Copy, Clone, Debug)]
618pub enum PromptLevel {
619    /// A prompt that is shown when the user should be notified of something
620    Info,
621
622    /// A prompt that is shown when the user needs to be warned of a potential problem
623    Warning,
624
625    /// A prompt that is shown when a critical problem has occurred
626    Critical,
627}
628
629/// The style of the cursor (pointer)
630#[derive(Copy, Clone, Debug)]
631pub enum CursorStyle {
632    /// The default cursor
633    Arrow,
634
635    /// A text input cursor
636    /// corresponds to the CSS cursor value `text`
637    IBeam,
638
639    /// A crosshair cursor
640    /// corresponds to the CSS cursor value `crosshair`
641    Crosshair,
642
643    /// A closed hand cursor
644    /// corresponds to the CSS cursor value `grabbing`
645    ClosedHand,
646
647    /// An open hand cursor
648    /// corresponds to the CSS cursor value `grab`
649    OpenHand,
650
651    /// A pointing hand cursor
652    /// corresponds to the CSS cursor value `pointer`
653    PointingHand,
654
655    /// A resize left cursor
656    /// corresponds to the CSS cursor value `w-resize`
657    ResizeLeft,
658
659    /// A resize right cursor
660    /// corresponds to the CSS cursor value `e-resize`
661    ResizeRight,
662
663    /// A resize cursor to the left and right
664    /// corresponds to the CSS cursor value `col-resize`
665    ResizeLeftRight,
666
667    /// A resize up cursor
668    /// corresponds to the CSS cursor value `n-resize`
669    ResizeUp,
670
671    /// A resize down cursor
672    /// corresponds to the CSS cursor value `s-resize`
673    ResizeDown,
674
675    /// A resize cursor directing up and down
676    /// corresponds to the CSS cursor value `row-resize`
677    ResizeUpDown,
678
679    /// A cursor indicating that something will disappear if moved here
680    /// Does not correspond to a CSS cursor value
681    DisappearingItem,
682
683    /// A text input cursor for vertical layout
684    /// corresponds to the CSS cursor value `vertical-text`
685    IBeamCursorForVerticalLayout,
686
687    /// A cursor indicating that the operation is not allowed
688    /// corresponds to the CSS cursor value `not-allowed`
689    OperationNotAllowed,
690
691    /// A cursor indicating that the operation will result in a link
692    /// corresponds to the CSS cursor value `alias`
693    DragLink,
694
695    /// A cursor indicating that the operation will result in a copy
696    /// corresponds to the CSS cursor value `copy`
697    DragCopy,
698
699    /// A cursor indicating that the operation will result in a context menu
700    /// corresponds to the CSS cursor value `context-menu`
701    ContextualMenu,
702}
703
704impl Default for CursorStyle {
705    fn default() -> Self {
706        Self::Arrow
707    }
708}
709
710/// A clipboard item that should be copied to the clipboard
711#[derive(Clone, Debug, Eq, PartialEq)]
712pub struct ClipboardItem {
713    pub(crate) text: String,
714    pub(crate) metadata: Option<String>,
715}
716
717impl ClipboardItem {
718    /// Create a new clipboard item with the given text
719    pub fn new(text: String) -> Self {
720        Self {
721            text,
722            metadata: None,
723        }
724    }
725
726    /// Create a new clipboard item with the given text and metadata
727    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
728        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
729        self
730    }
731
732    /// Get the text of the clipboard item
733    pub fn text(&self) -> &String {
734        &self.text
735    }
736
737    /// Get the metadata of the clipboard item
738    pub fn metadata<T>(&self) -> Option<T>
739    where
740        T: for<'a> Deserialize<'a>,
741    {
742        self.metadata
743            .as_ref()
744            .and_then(|m| serde_json::from_str(m).ok())
745    }
746
747    pub(crate) fn text_hash(text: &str) -> u64 {
748        let mut hasher = SeaHasher::new();
749        text.hash(&mut hasher);
750        hasher.finish()
751    }
752}