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