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 park(&self, timeout: Option<Duration>) -> bool;
244 fn unparker(&self) -> Unparker;
245
246 #[cfg(any(test, feature = "test-support"))]
247 fn as_test(&self) -> Option<&TestDispatcher> {
248 None
249 }
250}
251
252pub(crate) trait PlatformTextSystem: Send + Sync {
253 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
254 fn all_font_names(&self) -> Vec<String>;
255 fn all_font_families(&self) -> Vec<String>;
256 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
257 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
258 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
259 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
260 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
261 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
262 fn rasterize_glyph(
263 &self,
264 params: &RenderGlyphParams,
265 raster_bounds: Bounds<DevicePixels>,
266 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
267 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
268}
269
270/// Basic metadata about the current application and operating system.
271#[derive(Clone, Debug)]
272pub struct AppMetadata {
273 /// The name of the current operating system
274 pub os_name: &'static str,
275
276 /// The operating system's version
277 pub os_version: Option<SemanticVersion>,
278
279 /// The current version of the application
280 pub app_version: Option<SemanticVersion>,
281}
282
283#[derive(PartialEq, Eq, Hash, Clone)]
284pub(crate) enum AtlasKey {
285 Glyph(RenderGlyphParams),
286 Svg(RenderSvgParams),
287 Image(RenderImageParams),
288}
289
290impl AtlasKey {
291 pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
292 match self {
293 AtlasKey::Glyph(params) => {
294 if params.is_emoji {
295 AtlasTextureKind::Polychrome
296 } else {
297 AtlasTextureKind::Monochrome
298 }
299 }
300 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
301 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
302 }
303 }
304}
305
306impl From<RenderGlyphParams> for AtlasKey {
307 fn from(params: RenderGlyphParams) -> Self {
308 Self::Glyph(params)
309 }
310}
311
312impl From<RenderSvgParams> for AtlasKey {
313 fn from(params: RenderSvgParams) -> Self {
314 Self::Svg(params)
315 }
316}
317
318impl From<RenderImageParams> for AtlasKey {
319 fn from(params: RenderImageParams) -> Self {
320 Self::Image(params)
321 }
322}
323
324pub(crate) trait PlatformAtlas: Send + Sync {
325 fn get_or_insert_with<'a>(
326 &self,
327 key: &AtlasKey,
328 build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Cow<'a, [u8]>)>,
329 ) -> Result<AtlasTile>;
330}
331
332#[derive(Clone, Debug, PartialEq, Eq)]
333#[repr(C)]
334pub(crate) struct AtlasTile {
335 pub(crate) texture_id: AtlasTextureId,
336 pub(crate) tile_id: TileId,
337 pub(crate) padding: u32,
338 pub(crate) bounds: Bounds<DevicePixels>,
339}
340
341#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
342#[repr(C)]
343pub(crate) struct AtlasTextureId {
344 // We use u32 instead of usize for Metal Shader Language compatibility
345 pub(crate) index: u32,
346 pub(crate) kind: AtlasTextureKind,
347}
348
349#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
350#[repr(C)]
351pub(crate) enum AtlasTextureKind {
352 Monochrome = 0,
353 Polychrome = 1,
354 Path = 2,
355}
356
357#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
358#[repr(C)]
359pub(crate) struct TileId(pub(crate) u32);
360
361impl From<etagere::AllocId> for TileId {
362 fn from(id: etagere::AllocId) -> Self {
363 Self(id.serialize())
364 }
365}
366
367impl From<TileId> for etagere::AllocId {
368 fn from(id: TileId) -> Self {
369 Self::deserialize(id.0)
370 }
371}
372
373pub(crate) struct PlatformInputHandler {
374 cx: AsyncWindowContext,
375 handler: Box<dyn InputHandler>,
376}
377
378impl PlatformInputHandler {
379 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
380 Self { cx, handler }
381 }
382
383 fn selected_text_range(&mut self) -> Option<Range<usize>> {
384 self.cx
385 .update(|cx| self.handler.selected_text_range(cx))
386 .ok()
387 .flatten()
388 }
389
390 fn marked_text_range(&mut self) -> Option<Range<usize>> {
391 self.cx
392 .update(|cx| self.handler.marked_text_range(cx))
393 .ok()
394 .flatten()
395 }
396
397 fn text_for_range(&mut self, range_utf16: Range<usize>) -> Option<String> {
398 self.cx
399 .update(|cx| self.handler.text_for_range(range_utf16, cx))
400 .ok()
401 .flatten()
402 }
403
404 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
405 self.cx
406 .update(|cx| {
407 self.handler
408 .replace_text_in_range(replacement_range, text, cx);
409 })
410 .ok();
411 }
412
413 fn replace_and_mark_text_in_range(
414 &mut self,
415 range_utf16: Option<Range<usize>>,
416 new_text: &str,
417 new_selected_range: Option<Range<usize>>,
418 ) {
419 self.cx
420 .update(|cx| {
421 self.handler.replace_and_mark_text_in_range(
422 range_utf16,
423 new_text,
424 new_selected_range,
425 cx,
426 )
427 })
428 .ok();
429 }
430
431 fn unmark_text(&mut self) {
432 self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
433 }
434
435 fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
436 self.cx
437 .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
438 .ok()
439 .flatten()
440 }
441
442 pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
443 self.handler.replace_text_in_range(None, input, cx);
444 }
445}
446
447/// Zed's interface for handling text input from the platform's IME system
448/// This is currently a 1:1 exposure of the NSTextInputClient API:
449///
450/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
451pub trait InputHandler: 'static {
452 /// Get the range of the user's currently selected text, if any
453 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
454 ///
455 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
456 fn selected_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
457
458 /// Get the range of the currently marked text, if any
459 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
460 ///
461 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
462 fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
463
464 /// Get the text for the given document range in UTF-16 characters
465 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
466 ///
467 /// range_utf16 is in terms of UTF-16 characters
468 fn text_for_range(
469 &mut self,
470 range_utf16: Range<usize>,
471 cx: &mut WindowContext,
472 ) -> Option<String>;
473
474 /// Replace the text in the given document range with the given text
475 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
476 ///
477 /// replacement_range is in terms of UTF-16 characters
478 fn replace_text_in_range(
479 &mut self,
480 replacement_range: Option<Range<usize>>,
481 text: &str,
482 cx: &mut WindowContext,
483 );
484
485 /// Replace the text in the given document range with the given text,
486 /// and mark the given text as part of of an IME 'composing' state
487 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
488 ///
489 /// range_utf16 is in terms of UTF-16 characters
490 /// new_selected_range is in terms of UTF-16 characters
491 fn replace_and_mark_text_in_range(
492 &mut self,
493 range_utf16: Option<Range<usize>>,
494 new_text: &str,
495 new_selected_range: Option<Range<usize>>,
496 cx: &mut WindowContext,
497 );
498
499 /// Remove the IME 'composing' state from the document
500 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
501 fn unmark_text(&mut self, cx: &mut WindowContext);
502
503 /// Get the bounds of the given document range in screen coordinates
504 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
505 ///
506 /// This is used for positioning the IME candidate window
507 fn bounds_for_range(
508 &mut self,
509 range_utf16: Range<usize>,
510 cx: &mut WindowContext,
511 ) -> Option<Bounds<Pixels>>;
512}
513
514/// The variables that can be configured when creating a new window
515#[derive(Debug)]
516pub struct WindowOptions {
517 /// Specifies the state and bounds of the window in screen coordinates.
518 /// - `None`: Inherit the bounds.
519 /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
520 pub window_bounds: Option<WindowBounds>,
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 /// The kind of window to create
532 pub kind: WindowKind,
533
534 /// Whether the window should be movable by the user
535 pub is_movable: bool,
536
537 /// The display to create the window on, if this is None,
538 /// the window will be created on the main display
539 pub display_id: Option<DisplayId>,
540
541 /// The appearance of the window background.
542 pub window_background: WindowBackgroundAppearance,
543
544 /// Application identifier of the window. Can by used by desktop environments to group applications together.
545 pub app_id: Option<String>,
546}
547
548/// The variables that can be configured when creating a new window
549#[derive(Debug)]
550pub(crate) struct WindowParams {
551 pub bounds: Bounds<DevicePixels>,
552
553 /// The titlebar configuration of the window
554 pub titlebar: Option<TitlebarOptions>,
555
556 /// The kind of window to create
557 pub kind: WindowKind,
558
559 /// Whether the window should be movable by the user
560 pub is_movable: bool,
561
562 pub focus: bool,
563
564 pub show: bool,
565
566 pub display_id: Option<DisplayId>,
567
568 pub window_background: WindowBackgroundAppearance,
569}
570
571/// Represents the status of how a window should be opened.
572#[derive(Debug, Copy, Clone, PartialEq)]
573pub enum WindowBounds {
574 /// Indicates that the window should open in a windowed state with the given bounds.
575 Windowed(Bounds<DevicePixels>),
576 /// Indicates that the window should open in a maximized state.
577 /// The bounds provided here represent the restore size of the window.
578 Maximized(Bounds<DevicePixels>),
579 /// Indicates that the window should open in fullscreen mode.
580 /// The bounds provided here represent the restore size of the window.
581 Fullscreen(Bounds<DevicePixels>),
582}
583
584impl Default for WindowBounds {
585 fn default() -> Self {
586 WindowBounds::Windowed(Bounds::default())
587 }
588}
589
590impl WindowBounds {
591 /// Retrieve the inner bounds
592 pub fn get_bounds(&self) -> Bounds<DevicePixels> {
593 match self {
594 WindowBounds::Windowed(bounds) => *bounds,
595 WindowBounds::Maximized(bounds) => *bounds,
596 WindowBounds::Fullscreen(bounds) => *bounds,
597 }
598 }
599}
600
601impl Default for WindowOptions {
602 fn default() -> Self {
603 Self {
604 window_bounds: None,
605 titlebar: Some(TitlebarOptions {
606 title: Default::default(),
607 appears_transparent: Default::default(),
608 traffic_light_position: Default::default(),
609 }),
610 focus: true,
611 show: true,
612 kind: WindowKind::Normal,
613 is_movable: true,
614 display_id: None,
615 window_background: WindowBackgroundAppearance::default(),
616 app_id: None,
617 }
618 }
619}
620
621/// The options that can be configured for a window's titlebar
622#[derive(Debug, Default)]
623pub struct TitlebarOptions {
624 /// The initial title of the window
625 pub title: Option<SharedString>,
626
627 /// Whether the titlebar should appear transparent
628 pub appears_transparent: bool,
629
630 /// The position of the macOS traffic light buttons
631 pub traffic_light_position: Option<Point<Pixels>>,
632}
633
634/// The kind of window to create
635#[derive(Copy, Clone, Debug, PartialEq, Eq)]
636pub enum WindowKind {
637 /// A normal application window
638 Normal,
639
640 /// A window that appears above all other windows, usually used for alerts or popups
641 /// use sparingly!
642 PopUp,
643}
644
645/// The appearance of the window, as defined by the operating system.
646///
647/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
648/// values.
649#[derive(Copy, Clone, Debug)]
650pub enum WindowAppearance {
651 /// A light appearance.
652 ///
653 /// On macOS, this corresponds to the `aqua` appearance.
654 Light,
655
656 /// A light appearance with vibrant colors.
657 ///
658 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
659 VibrantLight,
660
661 /// A dark appearance.
662 ///
663 /// On macOS, this corresponds to the `darkAqua` appearance.
664 Dark,
665
666 /// A dark appearance with vibrant colors.
667 ///
668 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
669 VibrantDark,
670}
671
672impl Default for WindowAppearance {
673 fn default() -> Self {
674 Self::Light
675 }
676}
677
678/// The appearance of the background of the window itself, when there is
679/// no content or the content is transparent.
680#[derive(Copy, Clone, Debug, Default, PartialEq)]
681pub enum WindowBackgroundAppearance {
682 /// Opaque.
683 ///
684 /// This lets the window manager know that content behind this
685 /// window does not need to be drawn.
686 ///
687 /// Actual color depends on the system and themes should define a fully
688 /// opaque background color instead.
689 #[default]
690 Opaque,
691 /// Plain alpha transparency.
692 Transparent,
693 /// Transparency, but the contents behind the window are blurred.
694 ///
695 /// Not always supported.
696 Blurred,
697}
698
699/// The options that can be configured for a file dialog prompt
700#[derive(Copy, Clone, Debug)]
701pub struct PathPromptOptions {
702 /// Should the prompt allow files to be selected?
703 pub files: bool,
704 /// Should the prompt allow directories to be selected?
705 pub directories: bool,
706 /// Should the prompt allow multiple files to be selected?
707 pub multiple: bool,
708}
709
710/// What kind of prompt styling to show
711#[derive(Copy, Clone, Debug, PartialEq)]
712pub enum PromptLevel {
713 /// A prompt that is shown when the user should be notified of something
714 Info,
715
716 /// A prompt that is shown when the user needs to be warned of a potential problem
717 Warning,
718
719 /// A prompt that is shown when a critical problem has occurred
720 Critical,
721}
722
723/// The style of the cursor (pointer)
724#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
725pub enum CursorStyle {
726 /// The default cursor
727 Arrow,
728
729 /// A text input cursor
730 /// corresponds to the CSS cursor value `text`
731 IBeam,
732
733 /// A crosshair cursor
734 /// corresponds to the CSS cursor value `crosshair`
735 Crosshair,
736
737 /// A closed hand cursor
738 /// corresponds to the CSS cursor value `grabbing`
739 ClosedHand,
740
741 /// An open hand cursor
742 /// corresponds to the CSS cursor value `grab`
743 OpenHand,
744
745 /// A pointing hand cursor
746 /// corresponds to the CSS cursor value `pointer`
747 PointingHand,
748
749 /// A resize left cursor
750 /// corresponds to the CSS cursor value `w-resize`
751 ResizeLeft,
752
753 /// A resize right cursor
754 /// corresponds to the CSS cursor value `e-resize`
755 ResizeRight,
756
757 /// A resize cursor to the left and right
758 /// corresponds to the CSS cursor value `ew-resize`
759 ResizeLeftRight,
760
761 /// A resize up cursor
762 /// corresponds to the CSS cursor value `n-resize`
763 ResizeUp,
764
765 /// A resize down cursor
766 /// corresponds to the CSS cursor value `s-resize`
767 ResizeDown,
768
769 /// A resize cursor directing up and down
770 /// corresponds to the CSS cursor value `ns-resize`
771 ResizeUpDown,
772
773 /// A cursor indicating that the item/column can be resized horizontally.
774 /// corresponds to the CSS curosr value `col-resize`
775 ResizeColumn,
776
777 /// A cursor indicating that the item/row can be resized vertically.
778 /// corresponds to the CSS curosr value `row-resize`
779 ResizeRow,
780
781 /// A cursor indicating that something will disappear if moved here
782 /// Does not correspond to a CSS cursor value
783 DisappearingItem,
784
785 /// A text input cursor for vertical layout
786 /// corresponds to the CSS cursor value `vertical-text`
787 IBeamCursorForVerticalLayout,
788
789 /// A cursor indicating that the operation is not allowed
790 /// corresponds to the CSS cursor value `not-allowed`
791 OperationNotAllowed,
792
793 /// A cursor indicating that the operation will result in a link
794 /// corresponds to the CSS cursor value `alias`
795 DragLink,
796
797 /// A cursor indicating that the operation will result in a copy
798 /// corresponds to the CSS cursor value `copy`
799 DragCopy,
800
801 /// A cursor indicating that the operation will result in a context menu
802 /// corresponds to the CSS cursor value `context-menu`
803 ContextualMenu,
804}
805
806impl Default for CursorStyle {
807 fn default() -> Self {
808 Self::Arrow
809 }
810}
811
812/// A clipboard item that should be copied to the clipboard
813#[derive(Clone, Debug, Eq, PartialEq)]
814pub struct ClipboardItem {
815 pub(crate) text: String,
816 pub(crate) metadata: Option<String>,
817}
818
819impl ClipboardItem {
820 /// Create a new clipboard item with the given text
821 pub fn new(text: String) -> Self {
822 Self {
823 text,
824 metadata: None,
825 }
826 }
827
828 /// Create a new clipboard item with the given text and metadata
829 pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
830 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
831 self
832 }
833
834 /// Get the text of the clipboard item
835 pub fn text(&self) -> &String {
836 &self.text
837 }
838
839 /// Get the metadata of the clipboard item
840 pub fn metadata<T>(&self) -> Option<T>
841 where
842 T: for<'a> Deserialize<'a>,
843 {
844 self.metadata
845 .as_ref()
846 .and_then(|m| serde_json::from_str(m).ok())
847 }
848
849 pub(crate) fn text_hash(text: &str) -> u64 {
850 let mut hasher = SeaHasher::new();
851 text.hash(&mut hasher);
852 hasher.finish()
853 }
854}