platform.rs

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