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);
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 is_minimized(&self) -> bool;
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    /// The bounds of the window in screen coordinates.
519    /// None -> inherit, Some(bounds) -> set bounds
520    pub bounds: Option<Bounds<DevicePixels>>,
521
522    /// The titlebar configuration of the window
523    pub titlebar: Option<TitlebarOptions>,
524
525    /// Whether the window should be focused when created
526    pub focus: bool,
527
528    /// Whether the window should be shown when created
529    pub show: bool,
530
531    /// Whether the window should be fullscreen when created
532    pub fullscreen: bool,
533
534    /// The kind of window to create
535    pub kind: WindowKind,
536
537    /// Whether the window should be movable by the user
538    pub is_movable: bool,
539
540    /// The display to create the window on, if this is None,
541    /// the window will be created on the main display
542    pub display_id: Option<DisplayId>,
543
544    /// The appearance of the window background.
545    pub window_background: WindowBackgroundAppearance,
546
547    /// Application identifier of the window. Can by used by desktop environments to group applications together.
548    pub app_id: Option<String>,
549}
550
551/// The variables that can be configured when creating a new window
552#[derive(Debug)]
553pub(crate) struct WindowParams {
554    pub bounds: Bounds<DevicePixels>,
555
556    /// The titlebar configuration of the window
557    pub titlebar: Option<TitlebarOptions>,
558
559    /// The kind of window to create
560    pub kind: WindowKind,
561
562    /// Whether the window should be movable by the user
563    pub is_movable: bool,
564
565    pub focus: bool,
566
567    pub show: bool,
568
569    pub display_id: Option<DisplayId>,
570
571    pub window_background: WindowBackgroundAppearance,
572}
573
574impl Default for WindowOptions {
575    fn default() -> Self {
576        Self {
577            bounds: None,
578            titlebar: Some(TitlebarOptions {
579                title: Default::default(),
580                appears_transparent: Default::default(),
581                traffic_light_position: Default::default(),
582            }),
583            focus: true,
584            show: true,
585            kind: WindowKind::Normal,
586            is_movable: true,
587            display_id: None,
588            fullscreen: false,
589            window_background: WindowBackgroundAppearance::default(),
590            app_id: None,
591        }
592    }
593}
594
595/// The options that can be configured for a window's titlebar
596#[derive(Debug, Default)]
597pub struct TitlebarOptions {
598    /// The initial title of the window
599    pub title: Option<SharedString>,
600
601    /// Whether the titlebar should appear transparent
602    pub appears_transparent: bool,
603
604    /// The position of the macOS traffic light buttons
605    pub traffic_light_position: Option<Point<Pixels>>,
606}
607
608/// The kind of window to create
609#[derive(Copy, Clone, Debug, PartialEq, Eq)]
610pub enum WindowKind {
611    /// A normal application window
612    Normal,
613
614    /// A window that appears above all other windows, usually used for alerts or popups
615    /// use sparingly!
616    PopUp,
617}
618
619/// The appearance of the window, as defined by the operating system.
620///
621/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
622/// values.
623#[derive(Copy, Clone, Debug)]
624pub enum WindowAppearance {
625    /// A light appearance.
626    ///
627    /// On macOS, this corresponds to the `aqua` appearance.
628    Light,
629
630    /// A light appearance with vibrant colors.
631    ///
632    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
633    VibrantLight,
634
635    /// A dark appearance.
636    ///
637    /// On macOS, this corresponds to the `darkAqua` appearance.
638    Dark,
639
640    /// A dark appearance with vibrant colors.
641    ///
642    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
643    VibrantDark,
644}
645
646impl Default for WindowAppearance {
647    fn default() -> Self {
648        Self::Light
649    }
650}
651
652/// The appearance of the background of the window itself, when there is
653/// no content or the content is transparent.
654#[derive(Copy, Clone, Debug, Default, PartialEq)]
655pub enum WindowBackgroundAppearance {
656    /// Opaque.
657    ///
658    /// This lets the window manager know that content behind this
659    /// window does not need to be drawn.
660    ///
661    /// Actual color depends on the system and themes should define a fully
662    /// opaque background color instead.
663    #[default]
664    Opaque,
665    /// Plain alpha transparency.
666    Transparent,
667    /// Transparency, but the contents behind the window are blurred.
668    ///
669    /// Not always supported.
670    Blurred,
671}
672
673/// The options that can be configured for a file dialog prompt
674#[derive(Copy, Clone, Debug)]
675pub struct PathPromptOptions {
676    /// Should the prompt allow files to be selected?
677    pub files: bool,
678    /// Should the prompt allow directories to be selected?
679    pub directories: bool,
680    /// Should the prompt allow multiple files to be selected?
681    pub multiple: bool,
682}
683
684/// What kind of prompt styling to show
685#[derive(Copy, Clone, Debug, PartialEq)]
686pub enum PromptLevel {
687    /// A prompt that is shown when the user should be notified of something
688    Info,
689
690    /// A prompt that is shown when the user needs to be warned of a potential problem
691    Warning,
692
693    /// A prompt that is shown when a critical problem has occurred
694    Critical,
695
696    /// A prompt that is shown when asking the user to confirm a potentially destructive action
697    /// (overwriting a file for example)
698    Destructive,
699}
700
701/// The style of the cursor (pointer)
702#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
703pub enum CursorStyle {
704    /// The default cursor
705    Arrow,
706
707    /// A text input cursor
708    /// corresponds to the CSS cursor value `text`
709    IBeam,
710
711    /// A crosshair cursor
712    /// corresponds to the CSS cursor value `crosshair`
713    Crosshair,
714
715    /// A closed hand cursor
716    /// corresponds to the CSS cursor value `grabbing`
717    ClosedHand,
718
719    /// An open hand cursor
720    /// corresponds to the CSS cursor value `grab`
721    OpenHand,
722
723    /// A pointing hand cursor
724    /// corresponds to the CSS cursor value `pointer`
725    PointingHand,
726
727    /// A resize left cursor
728    /// corresponds to the CSS cursor value `w-resize`
729    ResizeLeft,
730
731    /// A resize right cursor
732    /// corresponds to the CSS cursor value `e-resize`
733    ResizeRight,
734
735    /// A resize cursor to the left and right
736    /// corresponds to the CSS cursor value `col-resize`
737    ResizeLeftRight,
738
739    /// A resize up cursor
740    /// corresponds to the CSS cursor value `n-resize`
741    ResizeUp,
742
743    /// A resize down cursor
744    /// corresponds to the CSS cursor value `s-resize`
745    ResizeDown,
746
747    /// A resize cursor directing up and down
748    /// corresponds to the CSS cursor value `row-resize`
749    ResizeUpDown,
750
751    /// A cursor indicating that something will disappear if moved here
752    /// Does not correspond to a CSS cursor value
753    DisappearingItem,
754
755    /// A text input cursor for vertical layout
756    /// corresponds to the CSS cursor value `vertical-text`
757    IBeamCursorForVerticalLayout,
758
759    /// A cursor indicating that the operation is not allowed
760    /// corresponds to the CSS cursor value `not-allowed`
761    OperationNotAllowed,
762
763    /// A cursor indicating that the operation will result in a link
764    /// corresponds to the CSS cursor value `alias`
765    DragLink,
766
767    /// A cursor indicating that the operation will result in a copy
768    /// corresponds to the CSS cursor value `copy`
769    DragCopy,
770
771    /// A cursor indicating that the operation will result in a context menu
772    /// corresponds to the CSS cursor value `context-menu`
773    ContextualMenu,
774}
775
776impl Default for CursorStyle {
777    fn default() -> Self {
778        Self::Arrow
779    }
780}
781
782/// A clipboard item that should be copied to the clipboard
783#[derive(Clone, Debug, Eq, PartialEq)]
784pub struct ClipboardItem {
785    pub(crate) text: String,
786    pub(crate) metadata: Option<String>,
787}
788
789impl ClipboardItem {
790    /// Create a new clipboard item with the given text
791    pub fn new(text: String) -> Self {
792        Self {
793            text,
794            metadata: None,
795        }
796    }
797
798    /// Create a new clipboard item with the given text and metadata
799    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
800        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
801        self
802    }
803
804    /// Get the text of the clipboard item
805    pub fn text(&self) -> &String {
806        &self.text
807    }
808
809    /// Get the metadata of the clipboard item
810    pub fn metadata<T>(&self) -> Option<T>
811    where
812        T: for<'a> Deserialize<'a>,
813    {
814        self.metadata
815            .as_ref()
816            .and_then(|m| serde_json::from_str(m).ok())
817    }
818
819    pub(crate) fn text_hash(text: &str) -> u64 {
820        let mut hasher = SeaHasher::new();
821        text.hash(&mut hasher);
822        hasher.finish()
823    }
824}