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