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