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