platform.rs

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