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 pub(crate) fn flush_pending_input(&mut self, input: &str, cx: &mut WindowContext) {
397 let Some(range) = self.handler.selected_text_range(cx) else {
398 return;
399 };
400 self.handler.replace_text_in_range(Some(range), &input, cx);
401 }
402}
403
404/// Zed's interface for handling text input from the platform's IME system
405/// This is currently a 1:1 exposure of the NSTextInputClient API:
406///
407/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
408pub trait InputHandler: 'static {
409 /// Get the range of the user's currently selected text, if any
410 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
411 ///
412 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
413 fn selected_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
414
415 /// Get the range of the currently marked text, if any
416 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
417 ///
418 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
419 fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
420
421 /// Get the text for the given document range in UTF-16 characters
422 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
423 ///
424 /// range_utf16 is in terms of UTF-16 characters
425 fn text_for_range(
426 &mut self,
427 range_utf16: Range<usize>,
428 cx: &mut WindowContext,
429 ) -> Option<String>;
430
431 /// Replace the text in the given document range with the given text
432 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
433 ///
434 /// replacement_range is in terms of UTF-16 characters
435 fn replace_text_in_range(
436 &mut self,
437 replacement_range: Option<Range<usize>>,
438 text: &str,
439 cx: &mut WindowContext,
440 );
441
442 /// Replace the text in the given document range with the given text,
443 /// and mark the given text as part of of an IME 'composing' state
444 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
445 ///
446 /// range_utf16 is in terms of UTF-16 characters
447 /// new_selected_range is in terms of UTF-16 characters
448 fn replace_and_mark_text_in_range(
449 &mut self,
450 range_utf16: Option<Range<usize>>,
451 new_text: &str,
452 new_selected_range: Option<Range<usize>>,
453 cx: &mut WindowContext,
454 );
455
456 /// Remove the IME 'composing' state from the document
457 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
458 fn unmark_text(&mut self, cx: &mut WindowContext);
459
460 /// Get the bounds of the given document range in screen coordinates
461 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
462 ///
463 /// This is used for positioning the IME candidate window
464 fn bounds_for_range(
465 &mut self,
466 range_utf16: Range<usize>,
467 cx: &mut WindowContext,
468 ) -> Option<Bounds<Pixels>>;
469}
470
471/// The variables that can be configured when creating a new window
472#[derive(Debug)]
473pub struct WindowOptions {
474 /// The initial bounds of the window
475 pub bounds: WindowBounds,
476
477 /// The titlebar configuration of the window
478 pub titlebar: Option<TitlebarOptions>,
479
480 /// Whether the window should be centered on the screen
481 pub center: bool,
482
483 /// Whether the window should be focused when created
484 pub focus: bool,
485
486 /// Whether the window should be shown when created
487 pub show: bool,
488
489 /// The kind of window to create
490 pub kind: WindowKind,
491
492 /// Whether the window should be movable by the user
493 pub is_movable: bool,
494
495 /// The display to create the window on
496 pub display_id: Option<DisplayId>,
497}
498
499impl Default for WindowOptions {
500 fn default() -> Self {
501 Self {
502 bounds: WindowBounds::default(),
503 titlebar: Some(TitlebarOptions {
504 title: Default::default(),
505 appears_transparent: Default::default(),
506 traffic_light_position: Default::default(),
507 }),
508 center: false,
509 focus: true,
510 show: true,
511 kind: WindowKind::Normal,
512 is_movable: true,
513 display_id: None,
514 }
515 }
516}
517
518/// The options that can be configured for a window's titlebar
519#[derive(Debug, Default)]
520pub struct TitlebarOptions {
521 /// The initial title of the window
522 pub title: Option<SharedString>,
523
524 /// Whether the titlebar should appear transparent
525 pub appears_transparent: bool,
526
527 /// The position of the macOS traffic light buttons
528 pub traffic_light_position: Option<Point<Pixels>>,
529}
530
531/// The kind of window to create
532#[derive(Copy, Clone, Debug, PartialEq, Eq)]
533pub enum WindowKind {
534 /// A normal application window
535 Normal,
536
537 /// A window that appears above all other windows, usually used for alerts or popups
538 /// use sparingly!
539 PopUp,
540}
541
542/// Which bounds algorithm to use for the initial size a window
543#[derive(Copy, Clone, Debug, PartialEq, Default)]
544pub enum WindowBounds {
545 /// The window should be full screen, on macOS this corresponds to the full screen feature
546 Fullscreen,
547
548 /// Make the window as large as the current display's size.
549 #[default]
550 Maximized,
551
552 /// Set the window to the given size in pixels
553 Fixed(Bounds<GlobalPixels>),
554}
555
556/// The appearance of the window, as defined by the operating system
557/// On macOS, this corresponds to named [NSAppearance](https://developer.apple.com/documentation/appkit/nsappearance)
558/// values
559#[derive(Copy, Clone, Debug)]
560pub enum WindowAppearance {
561 /// A light appearance
562 ///
563 /// on macOS, this corresponds to the `aqua` appearance
564 Light,
565
566 /// A light appearance with vibrant colors
567 ///
568 /// on macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance
569 VibrantLight,
570
571 /// A dark appearance
572 ///
573 /// on macOS, this corresponds to the `darkAqua` appearance
574 Dark,
575
576 /// A dark appearance with vibrant colors
577 ///
578 /// on macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance
579 VibrantDark,
580}
581
582impl Default for WindowAppearance {
583 fn default() -> Self {
584 Self::Light
585 }
586}
587
588/// The options that can be configured for a file dialog prompt
589#[derive(Copy, Clone, Debug)]
590pub struct PathPromptOptions {
591 /// Should the prompt allow files to be selected?
592 pub files: bool,
593 /// Should the prompt allow directories to be selected?
594 pub directories: bool,
595 /// Should the prompt allow multiple files to be selected?
596 pub multiple: bool,
597}
598
599/// What kind of prompt styling to show
600#[derive(Copy, Clone, Debug)]
601pub enum PromptLevel {
602 /// A prompt that is shown when the user should be notified of something
603 Info,
604
605 /// A prompt that is shown when the user needs to be warned of a potential problem
606 Warning,
607
608 /// A prompt that is shown when a critical problem has occurred
609 Critical,
610}
611
612/// The style of the cursor (pointer)
613#[derive(Copy, Clone, Debug)]
614pub enum CursorStyle {
615 /// The default cursor
616 Arrow,
617
618 /// A text input cursor
619 /// corresponds to the CSS cursor value `text`
620 IBeam,
621
622 /// A crosshair cursor
623 /// corresponds to the CSS cursor value `crosshair`
624 Crosshair,
625
626 /// A closed hand cursor
627 /// corresponds to the CSS cursor value `grabbing`
628 ClosedHand,
629
630 /// An open hand cursor
631 /// corresponds to the CSS cursor value `grab`
632 OpenHand,
633
634 /// A pointing hand cursor
635 /// corresponds to the CSS cursor value `pointer`
636 PointingHand,
637
638 /// A resize left cursor
639 /// corresponds to the CSS cursor value `w-resize`
640 ResizeLeft,
641
642 /// A resize right cursor
643 /// corresponds to the CSS cursor value `e-resize`
644 ResizeRight,
645
646 /// A resize cursor to the left and right
647 /// corresponds to the CSS cursor value `col-resize`
648 ResizeLeftRight,
649
650 /// A resize up cursor
651 /// corresponds to the CSS cursor value `n-resize`
652 ResizeUp,
653
654 /// A resize down cursor
655 /// corresponds to the CSS cursor value `s-resize`
656 ResizeDown,
657
658 /// A resize cursor directing up and down
659 /// corresponds to the CSS cursor value `row-resize`
660 ResizeUpDown,
661
662 /// A cursor indicating that something will disappear if moved here
663 /// Does not correspond to a CSS cursor value
664 DisappearingItem,
665
666 /// A text input cursor for vertical layout
667 /// corresponds to the CSS cursor value `vertical-text`
668 IBeamCursorForVerticalLayout,
669
670 /// A cursor indicating that the operation is not allowed
671 /// corresponds to the CSS cursor value `not-allowed`
672 OperationNotAllowed,
673
674 /// A cursor indicating that the operation will result in a link
675 /// corresponds to the CSS cursor value `alias`
676 DragLink,
677
678 /// A cursor indicating that the operation will result in a copy
679 /// corresponds to the CSS cursor value `copy`
680 DragCopy,
681
682 /// A cursor indicating that the operation will result in a context menu
683 /// corresponds to the CSS cursor value `context-menu`
684 ContextualMenu,
685}
686
687impl Default for CursorStyle {
688 fn default() -> Self {
689 Self::Arrow
690 }
691}
692
693/// A datastructure representing a semantic version number
694#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize)]
695pub struct SemanticVersion {
696 major: usize,
697 minor: usize,
698 patch: usize,
699}
700
701impl FromStr for SemanticVersion {
702 type Err = anyhow::Error;
703
704 fn from_str(s: &str) -> Result<Self> {
705 let mut components = s.trim().split('.');
706 let major = components
707 .next()
708 .ok_or_else(|| anyhow!("missing major version number"))?
709 .parse()?;
710 let minor = components
711 .next()
712 .ok_or_else(|| anyhow!("missing minor version number"))?
713 .parse()?;
714 let patch = components
715 .next()
716 .ok_or_else(|| anyhow!("missing patch version number"))?
717 .parse()?;
718 Ok(Self {
719 major,
720 minor,
721 patch,
722 })
723 }
724}
725
726impl Display for SemanticVersion {
727 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
728 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
729 }
730}
731
732/// A clipboard item that should be copied to the clipboard
733#[derive(Clone, Debug, Eq, PartialEq)]
734pub struct ClipboardItem {
735 pub(crate) text: String,
736 pub(crate) metadata: Option<String>,
737}
738
739impl ClipboardItem {
740 /// Create a new clipboard item with the given text
741 pub fn new(text: String) -> Self {
742 Self {
743 text,
744 metadata: None,
745 }
746 }
747
748 /// Create a new clipboard item with the given text and metadata
749 pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
750 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
751 self
752 }
753
754 /// Get the text of the clipboard item
755 pub fn text(&self) -> &String {
756 &self.text
757 }
758
759 /// Get the metadata of the clipboard item
760 pub fn metadata<T>(&self) -> Option<T>
761 where
762 T: for<'a> Deserialize<'a>,
763 {
764 self.metadata
765 .as_ref()
766 .and_then(|m| serde_json::from_str(m).ok())
767 }
768
769 pub(crate) fn text_hash(text: &str) -> u64 {
770 let mut hasher = SeaHasher::new();
771 text.hash(&mut hasher);
772 hasher.finish()
773 }
774}