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