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