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