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