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