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        self.handler.replace_text_in_range(None, input, cx);
411    }
412}
413
414/// Zed's interface for handling text input from the platform's IME system
415/// This is currently a 1:1 exposure of the NSTextInputClient API:
416///
417/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
418pub trait InputHandler: 'static {
419    /// Get the range of the user's currently selected text, if any
420    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
421    ///
422    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
423    fn selected_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
424
425    /// Get the range of the currently marked text, if any
426    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
427    ///
428    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
429    fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
430
431    /// Get the text for the given document range in UTF-16 characters
432    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
433    ///
434    /// range_utf16 is in terms of UTF-16 characters
435    fn text_for_range(
436        &mut self,
437        range_utf16: Range<usize>,
438        cx: &mut WindowContext,
439    ) -> Option<String>;
440
441    /// Replace the text in the given document range with the given text
442    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
443    ///
444    /// replacement_range is in terms of UTF-16 characters
445    fn replace_text_in_range(
446        &mut self,
447        replacement_range: Option<Range<usize>>,
448        text: &str,
449        cx: &mut WindowContext,
450    );
451
452    /// Replace the text in the given document range with the given text,
453    /// and mark the given text as part of of an IME 'composing' state
454    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
455    ///
456    /// range_utf16 is in terms of UTF-16 characters
457    /// new_selected_range is in terms of UTF-16 characters
458    fn replace_and_mark_text_in_range(
459        &mut self,
460        range_utf16: Option<Range<usize>>,
461        new_text: &str,
462        new_selected_range: Option<Range<usize>>,
463        cx: &mut WindowContext,
464    );
465
466    /// Remove the IME 'composing' state from the document
467    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
468    fn unmark_text(&mut self, cx: &mut WindowContext);
469
470    /// Get the bounds of the given document range in screen coordinates
471    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
472    ///
473    /// This is used for positioning the IME candidate window
474    fn bounds_for_range(
475        &mut self,
476        range_utf16: Range<usize>,
477        cx: &mut WindowContext,
478    ) -> Option<Bounds<Pixels>>;
479}
480
481/// The variables that can be configured when creating a new window
482#[derive(Debug)]
483pub struct WindowOptions {
484    /// The initial bounds of the window
485    pub bounds: WindowBounds,
486
487    /// The titlebar configuration of the window
488    pub titlebar: Option<TitlebarOptions>,
489
490    /// Whether the window should be centered on the screen
491    pub center: bool,
492
493    /// Whether the window should be focused when created
494    pub focus: bool,
495
496    /// Whether the window should be shown when created
497    pub show: bool,
498
499    /// The kind of window to create
500    pub kind: WindowKind,
501
502    /// Whether the window should be movable by the user
503    pub is_movable: bool,
504
505    /// The display to create the window on
506    pub display_id: Option<DisplayId>,
507}
508
509impl Default for WindowOptions {
510    fn default() -> Self {
511        Self {
512            bounds: WindowBounds::default(),
513            titlebar: Some(TitlebarOptions {
514                title: Default::default(),
515                appears_transparent: Default::default(),
516                traffic_light_position: Default::default(),
517            }),
518            center: false,
519            focus: true,
520            show: true,
521            kind: WindowKind::Normal,
522            is_movable: true,
523            display_id: None,
524        }
525    }
526}
527
528/// The options that can be configured for a window's titlebar
529#[derive(Debug, Default)]
530pub struct TitlebarOptions {
531    /// The initial title of the window
532    pub title: Option<SharedString>,
533
534    /// Whether the titlebar should appear transparent
535    pub appears_transparent: bool,
536
537    /// The position of the macOS traffic light buttons
538    pub traffic_light_position: Option<Point<Pixels>>,
539}
540
541/// The kind of window to create
542#[derive(Copy, Clone, Debug, PartialEq, Eq)]
543pub enum WindowKind {
544    /// A normal application window
545    Normal,
546
547    /// A window that appears above all other windows, usually used for alerts or popups
548    /// use sparingly!
549    PopUp,
550}
551
552/// Which bounds algorithm to use for the initial size a window
553#[derive(Copy, Clone, Debug, PartialEq, Default)]
554pub enum WindowBounds {
555    /// The window should be full screen, on macOS this corresponds to the full screen feature
556    Fullscreen,
557
558    /// Make the window as large as the current display's size.
559    #[default]
560    Maximized,
561
562    /// Set the window to the given size in pixels
563    Fixed(Bounds<GlobalPixels>),
564}
565
566/// The appearance of the window, as defined by the operating system.
567///
568/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
569/// values.
570#[derive(Copy, Clone, Debug)]
571pub enum WindowAppearance {
572    /// A light appearance.
573    ///
574    /// On macOS, this corresponds to the `aqua` appearance.
575    Light,
576
577    /// A light appearance with vibrant colors.
578    ///
579    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
580    VibrantLight,
581
582    /// A dark appearance.
583    ///
584    /// On macOS, this corresponds to the `darkAqua` appearance.
585    Dark,
586
587    /// A dark appearance with vibrant colors.
588    ///
589    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
590    VibrantDark,
591}
592
593impl Default for WindowAppearance {
594    fn default() -> Self {
595        Self::Light
596    }
597}
598
599/// The options that can be configured for a file dialog prompt
600#[derive(Copy, Clone, Debug)]
601pub struct PathPromptOptions {
602    /// Should the prompt allow files to be selected?
603    pub files: bool,
604    /// Should the prompt allow directories to be selected?
605    pub directories: bool,
606    /// Should the prompt allow multiple files to be selected?
607    pub multiple: bool,
608}
609
610/// What kind of prompt styling to show
611#[derive(Copy, Clone, Debug)]
612pub enum PromptLevel {
613    /// A prompt that is shown when the user should be notified of something
614    Info,
615
616    /// A prompt that is shown when the user needs to be warned of a potential problem
617    Warning,
618
619    /// A prompt that is shown when a critical problem has occurred
620    Critical,
621}
622
623/// The style of the cursor (pointer)
624#[derive(Copy, Clone, Debug)]
625pub enum CursorStyle {
626    /// The default cursor
627    Arrow,
628
629    /// A text input cursor
630    /// corresponds to the CSS cursor value `text`
631    IBeam,
632
633    /// A crosshair cursor
634    /// corresponds to the CSS cursor value `crosshair`
635    Crosshair,
636
637    /// A closed hand cursor
638    /// corresponds to the CSS cursor value `grabbing`
639    ClosedHand,
640
641    /// An open hand cursor
642    /// corresponds to the CSS cursor value `grab`
643    OpenHand,
644
645    /// A pointing hand cursor
646    /// corresponds to the CSS cursor value `pointer`
647    PointingHand,
648
649    /// A resize left cursor
650    /// corresponds to the CSS cursor value `w-resize`
651    ResizeLeft,
652
653    /// A resize right cursor
654    /// corresponds to the CSS cursor value `e-resize`
655    ResizeRight,
656
657    /// A resize cursor to the left and right
658    /// corresponds to the CSS cursor value `col-resize`
659    ResizeLeftRight,
660
661    /// A resize up cursor
662    /// corresponds to the CSS cursor value `n-resize`
663    ResizeUp,
664
665    /// A resize down cursor
666    /// corresponds to the CSS cursor value `s-resize`
667    ResizeDown,
668
669    /// A resize cursor directing up and down
670    /// corresponds to the CSS cursor value `row-resize`
671    ResizeUpDown,
672
673    /// A cursor indicating that something will disappear if moved here
674    /// Does not correspond to a CSS cursor value
675    DisappearingItem,
676
677    /// A text input cursor for vertical layout
678    /// corresponds to the CSS cursor value `vertical-text`
679    IBeamCursorForVerticalLayout,
680
681    /// A cursor indicating that the operation is not allowed
682    /// corresponds to the CSS cursor value `not-allowed`
683    OperationNotAllowed,
684
685    /// A cursor indicating that the operation will result in a link
686    /// corresponds to the CSS cursor value `alias`
687    DragLink,
688
689    /// A cursor indicating that the operation will result in a copy
690    /// corresponds to the CSS cursor value `copy`
691    DragCopy,
692
693    /// A cursor indicating that the operation will result in a context menu
694    /// corresponds to the CSS cursor value `context-menu`
695    ContextualMenu,
696}
697
698impl Default for CursorStyle {
699    fn default() -> Self {
700        Self::Arrow
701    }
702}
703
704/// A clipboard item that should be copied to the clipboard
705#[derive(Clone, Debug, Eq, PartialEq)]
706pub struct ClipboardItem {
707    pub(crate) text: String,
708    pub(crate) metadata: Option<String>,
709}
710
711impl ClipboardItem {
712    /// Create a new clipboard item with the given text
713    pub fn new(text: String) -> Self {
714        Self {
715            text,
716            metadata: None,
717        }
718    }
719
720    /// Create a new clipboard item with the given text and metadata
721    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
722        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
723        self
724    }
725
726    /// Get the text of the clipboard item
727    pub fn text(&self) -> &String {
728        &self.text
729    }
730
731    /// Get the metadata of the clipboard item
732    pub fn metadata<T>(&self) -> Option<T>
733    where
734        T: for<'a> Deserialize<'a>,
735    {
736        self.metadata
737            .as_ref()
738            .and_then(|m| serde_json::from_str(m).ok())
739    }
740
741    pub(crate) fn text_hash(text: &str) -> u64 {
742        let mut hasher = SeaHasher::new();
743        text.hash(&mut hasher);
744        hasher.finish()
745    }
746}