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