platform.rs

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