platform.rs

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