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