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