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