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