1// todo(windows): remove
2#![cfg_attr(windows, allow(dead_code))]
3
4mod app_menu;
5mod keystroke;
6
7#[cfg(any(target_os = "linux", target_os = "freebsd"))]
8mod linux;
9
10#[cfg(target_os = "macos")]
11mod mac;
12
13#[cfg(any(
14 all(
15 any(target_os = "linux", target_os = "freebsd"),
16 any(feature = "x11", feature = "wayland")
17 ),
18 target_os = "windows",
19 feature = "macos-blade"
20))]
21mod blade;
22
23#[cfg(any(test, feature = "test-support"))]
24mod test;
25
26#[cfg(target_os = "windows")]
27mod windows;
28
29use crate::{
30 point, Action, AnyWindowHandle, AsyncWindowContext, BackgroundExecutor, Bounds, DevicePixels,
31 DispatchEventResult, Font, FontId, FontMetrics, FontRun, ForegroundExecutor, GPUSpecs, GlyphId,
32 ImageSource, Keymap, LineLayout, Pixels, PlatformInput, Point, RenderGlyphParams, RenderImage,
33 RenderImageParams, RenderSvgParams, ScaledPixels, Scene, SharedString, Size, SvgRenderer,
34 SvgSize, Task, TaskLabel, WindowContext, DEFAULT_WINDOW_SIZE,
35};
36use anyhow::{anyhow, Result};
37use async_task::Runnable;
38use futures::channel::oneshot;
39use image::codecs::gif::GifDecoder;
40use image::{AnimationDecoder as _, Frame};
41use parking::Unparker;
42use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
43use seahash::SeaHasher;
44use serde::{Deserialize, Serialize};
45use smallvec::SmallVec;
46use std::borrow::Cow;
47use std::hash::{Hash, Hasher};
48use std::io::Cursor;
49use std::time::{Duration, Instant};
50use std::{
51 fmt::{self, Debug},
52 ops::Range,
53 path::{Path, PathBuf},
54 rc::Rc,
55 sync::Arc,
56};
57use strum::EnumIter;
58use uuid::Uuid;
59
60pub use app_menu::*;
61pub use keystroke::*;
62
63#[cfg(any(target_os = "linux", target_os = "freebsd"))]
64pub(crate) use linux::*;
65#[cfg(target_os = "macos")]
66pub(crate) use mac::*;
67pub use semantic_version::SemanticVersion;
68#[cfg(any(test, feature = "test-support"))]
69pub(crate) use test::*;
70#[cfg(target_os = "windows")]
71pub(crate) use windows::*;
72
73#[cfg(target_os = "macos")]
74pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
75 Rc::new(MacPlatform::new(headless))
76}
77
78#[cfg(any(target_os = "linux", target_os = "freebsd"))]
79pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
80 if headless {
81 return Rc::new(HeadlessClient::new());
82 }
83
84 match guess_compositor() {
85 #[cfg(feature = "wayland")]
86 "Wayland" => Rc::new(WaylandClient::new()),
87
88 #[cfg(feature = "x11")]
89 "X11" => Rc::new(X11Client::new()),
90
91 "Headless" => Rc::new(HeadlessClient::new()),
92 _ => unreachable!(),
93 }
94}
95
96/// Return which compositor we're guessing we'll use.
97/// Does not attempt to connect to the given compositor
98#[cfg(any(target_os = "linux", target_os = "freebsd"))]
99#[inline]
100pub fn guess_compositor() -> &'static str {
101 if std::env::var_os("ZED_HEADLESS").is_some() {
102 return "Headless";
103 }
104
105 #[cfg(feature = "wayland")]
106 let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
107 #[cfg(not(feature = "wayland"))]
108 let wayland_display: Option<std::ffi::OsString> = None;
109
110 #[cfg(feature = "x11")]
111 let x11_display = std::env::var_os("DISPLAY");
112 #[cfg(not(feature = "x11"))]
113 let x11_display: Option<std::ffi::OsString> = None;
114
115 let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
116 let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
117
118 if use_wayland {
119 "Wayland"
120 } else if use_x11 {
121 "X11"
122 } else {
123 "Headless"
124 }
125}
126
127#[cfg(target_os = "windows")]
128pub(crate) fn current_platform(_headless: bool) -> Rc<dyn Platform> {
129 Rc::new(WindowsPlatform::new())
130}
131
132pub(crate) trait Platform: 'static {
133 fn background_executor(&self) -> BackgroundExecutor;
134 fn foreground_executor(&self) -> ForegroundExecutor;
135 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
136
137 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
138 fn quit(&self);
139 fn restart(&self, binary_path: Option<PathBuf>);
140 fn activate(&self, ignoring_other_apps: bool);
141 fn hide(&self);
142 fn hide_other_apps(&self);
143 fn unhide_other_apps(&self);
144
145 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
146 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
147 fn active_window(&self) -> Option<AnyWindowHandle>;
148 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
149 None
150 }
151
152 fn open_window(
153 &self,
154 handle: AnyWindowHandle,
155 options: WindowParams,
156 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
157
158 /// Returns the appearance of the application's windows.
159 fn window_appearance(&self) -> WindowAppearance;
160
161 fn open_url(&self, url: &str);
162 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
163 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
164
165 fn prompt_for_paths(
166 &self,
167 options: PathPromptOptions,
168 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
169 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>>;
170 fn reveal_path(&self, path: &Path);
171 fn open_with_system(&self, path: &Path);
172
173 fn on_quit(&self, callback: Box<dyn FnMut()>);
174 fn on_reopen(&self, callback: Box<dyn FnMut()>);
175 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
176
177 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
178 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
179 None
180 }
181
182 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
183 fn add_recent_document(&self, _path: &Path) {}
184 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
185 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
186 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
187 fn keyboard_layout(&self) -> String;
188
189 fn compositor_name(&self) -> &'static str {
190 ""
191 }
192 fn app_path(&self) -> Result<PathBuf>;
193 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
194
195 fn set_cursor_style(&self, style: CursorStyle);
196 fn should_auto_hide_scrollbars(&self) -> bool;
197
198 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
199 fn write_to_primary(&self, item: ClipboardItem);
200 fn write_to_clipboard(&self, item: ClipboardItem);
201 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
202 fn read_from_primary(&self) -> Option<ClipboardItem>;
203 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
204
205 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
206 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
207 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
208}
209
210/// A handle to a platform's display, e.g. a monitor or laptop screen.
211pub trait PlatformDisplay: Send + Sync + Debug {
212 /// Get the ID for this display
213 fn id(&self) -> DisplayId;
214
215 /// Returns a stable identifier for this display that can be persisted and used
216 /// across system restarts.
217 fn uuid(&self) -> Result<Uuid>;
218
219 /// Get the bounds for this display
220 fn bounds(&self) -> Bounds<Pixels>;
221
222 /// Get the default bounds for this display to place a window
223 fn default_bounds(&self) -> Bounds<Pixels> {
224 let center = self.bounds().center();
225 let offset = DEFAULT_WINDOW_SIZE / 2.0;
226 let origin = point(center.x - offset.width, center.y - offset.height);
227 Bounds::new(origin, DEFAULT_WINDOW_SIZE)
228 }
229}
230
231/// An opaque identifier for a hardware display
232#[derive(PartialEq, Eq, Hash, Copy, Clone)]
233pub struct DisplayId(pub(crate) u32);
234
235impl Debug for DisplayId {
236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237 write!(f, "DisplayId({})", self.0)
238 }
239}
240
241unsafe impl Send for DisplayId {}
242
243/// Which part of the window to resize
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub enum ResizeEdge {
246 /// The top edge
247 Top,
248 /// The top right corner
249 TopRight,
250 /// The right edge
251 Right,
252 /// The bottom right corner
253 BottomRight,
254 /// The bottom edge
255 Bottom,
256 /// The bottom left corner
257 BottomLeft,
258 /// The left edge
259 Left,
260 /// The top left corner
261 TopLeft,
262}
263
264/// A type to describe the appearance of a window
265#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
266pub enum WindowDecorations {
267 #[default]
268 /// Server side decorations
269 Server,
270 /// Client side decorations
271 Client,
272}
273
274/// A type to describe how this window is currently configured
275#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
276pub enum Decorations {
277 /// The window is configured to use server side decorations
278 #[default]
279 Server,
280 /// The window is configured to use client side decorations
281 Client {
282 /// The edge tiling state
283 tiling: Tiling,
284 },
285}
286
287/// What window controls this platform supports
288#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
289pub struct WindowControls {
290 /// Whether this platform supports fullscreen
291 pub fullscreen: bool,
292 /// Whether this platform supports maximize
293 pub maximize: bool,
294 /// Whether this platform supports minimize
295 pub minimize: bool,
296 /// Whether this platform supports a window menu
297 pub window_menu: bool,
298}
299
300impl Default for WindowControls {
301 fn default() -> Self {
302 // Assume that we can do anything, unless told otherwise
303 Self {
304 fullscreen: true,
305 maximize: true,
306 minimize: true,
307 window_menu: true,
308 }
309 }
310}
311
312/// A type to describe which sides of the window are currently tiled in some way
313#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
314pub struct Tiling {
315 /// Whether the top edge is tiled
316 pub top: bool,
317 /// Whether the left edge is tiled
318 pub left: bool,
319 /// Whether the right edge is tiled
320 pub right: bool,
321 /// Whether the bottom edge is tiled
322 pub bottom: bool,
323}
324
325impl Tiling {
326 /// Initializes a [`Tiling`] type with all sides tiled
327 pub fn tiled() -> Self {
328 Self {
329 top: true,
330 left: true,
331 right: true,
332 bottom: true,
333 }
334 }
335
336 /// Whether any edge is tiled
337 pub fn is_tiled(&self) -> bool {
338 self.top || self.left || self.right || self.bottom
339 }
340}
341
342#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
343pub(crate) struct RequestFrameOptions {
344 pub(crate) require_presentation: bool,
345}
346
347pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
348 fn bounds(&self) -> Bounds<Pixels>;
349 fn is_maximized(&self) -> bool;
350 fn window_bounds(&self) -> WindowBounds;
351 fn content_size(&self) -> Size<Pixels>;
352 fn scale_factor(&self) -> f32;
353 fn appearance(&self) -> WindowAppearance;
354 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
355 fn mouse_position(&self) -> Point<Pixels>;
356 fn modifiers(&self) -> Modifiers;
357 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
358 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
359 fn prompt(
360 &self,
361 level: PromptLevel,
362 msg: &str,
363 detail: Option<&str>,
364 answers: &[&str],
365 ) -> Option<oneshot::Receiver<usize>>;
366 fn activate(&self);
367 fn is_active(&self) -> bool;
368 fn is_hovered(&self) -> bool;
369 fn set_title(&mut self, title: &str);
370 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
371 fn minimize(&self);
372 fn zoom(&self);
373 fn toggle_fullscreen(&self);
374 fn is_fullscreen(&self) -> bool;
375 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
376 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
377 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
378 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
379 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
380 fn on_moved(&self, callback: Box<dyn FnMut()>);
381 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
382 fn on_close(&self, callback: Box<dyn FnOnce()>);
383 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
384 fn draw(&self, scene: &Scene);
385 fn completed_frame(&self) {}
386 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
387
388 // macOS specific methods
389 fn set_edited(&mut self, _edited: bool) {}
390 fn show_character_palette(&self) {}
391
392 #[cfg(target_os = "windows")]
393 fn get_raw_handle(&self) -> windows::HWND;
394
395 // Linux specific methods
396 fn request_decorations(&self, _decorations: WindowDecorations) {}
397 fn show_window_menu(&self, _position: Point<Pixels>) {}
398 fn start_window_move(&self) {}
399 fn start_window_resize(&self, _edge: ResizeEdge) {}
400 fn window_decorations(&self) -> Decorations {
401 Decorations::Server
402 }
403 fn set_app_id(&mut self, _app_id: &str) {}
404 fn window_controls(&self) -> WindowControls {
405 WindowControls::default()
406 }
407 fn set_client_inset(&self, _inset: Pixels) {}
408 fn gpu_specs(&self) -> Option<GPUSpecs>;
409
410 fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>);
411
412 #[cfg(any(test, feature = "test-support"))]
413 fn as_test(&mut self) -> Option<&mut TestWindow> {
414 None
415 }
416}
417
418/// This type is public so that our test macro can generate and use it, but it should not
419/// be considered part of our public API.
420#[doc(hidden)]
421pub trait PlatformDispatcher: Send + Sync {
422 fn is_main_thread(&self) -> bool;
423 fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
424 fn dispatch_on_main_thread(&self, runnable: Runnable);
425 fn dispatch_after(&self, duration: Duration, runnable: Runnable);
426 fn park(&self, timeout: Option<Duration>) -> bool;
427 fn unparker(&self) -> Unparker;
428 fn now(&self) -> Instant {
429 Instant::now()
430 }
431
432 #[cfg(any(test, feature = "test-support"))]
433 fn as_test(&self) -> Option<&TestDispatcher> {
434 None
435 }
436}
437
438pub(crate) trait PlatformTextSystem: Send + Sync {
439 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
440 fn all_font_names(&self) -> Vec<String>;
441 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
442 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
443 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
444 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
445 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
446 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
447 fn rasterize_glyph(
448 &self,
449 params: &RenderGlyphParams,
450 raster_bounds: Bounds<DevicePixels>,
451 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
452 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
453}
454
455pub(crate) struct NoopTextSystem;
456
457impl NoopTextSystem {
458 #[allow(dead_code)]
459 pub fn new() -> Self {
460 Self
461 }
462}
463
464impl PlatformTextSystem for NoopTextSystem {
465 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
466 Ok(())
467 }
468
469 fn all_font_names(&self) -> Vec<String> {
470 Vec::new()
471 }
472
473 fn font_id(&self, descriptor: &Font) -> Result<FontId> {
474 Err(anyhow!("No font found for {:?}", descriptor))
475 }
476
477 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
478 unimplemented!()
479 }
480
481 fn typographic_bounds(&self, font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
482 Err(anyhow!("No font found for {:?}", font_id))
483 }
484
485 fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> Result<Size<f32>> {
486 Err(anyhow!("No font found for {:?}", font_id))
487 }
488
489 fn glyph_for_char(&self, _font_id: FontId, _ch: char) -> Option<GlyphId> {
490 None
491 }
492
493 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
494 Err(anyhow!("No font found for {:?}", params))
495 }
496
497 fn rasterize_glyph(
498 &self,
499 params: &RenderGlyphParams,
500 _raster_bounds: Bounds<DevicePixels>,
501 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
502 Err(anyhow!("No font found for {:?}", params))
503 }
504
505 fn layout_line(&self, _text: &str, _font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
506 unimplemented!()
507 }
508}
509
510#[derive(PartialEq, Eq, Hash, Clone)]
511pub(crate) enum AtlasKey {
512 Glyph(RenderGlyphParams),
513 Svg(RenderSvgParams),
514 Image(RenderImageParams),
515}
516
517impl AtlasKey {
518 #[cfg_attr(
519 all(
520 any(target_os = "linux", target_os = "freebsd"),
521 not(any(feature = "x11", feature = "wayland"))
522 ),
523 allow(dead_code)
524 )]
525 pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
526 match self {
527 AtlasKey::Glyph(params) => {
528 if params.is_emoji {
529 AtlasTextureKind::Polychrome
530 } else {
531 AtlasTextureKind::Monochrome
532 }
533 }
534 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
535 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
536 }
537 }
538}
539
540impl From<RenderGlyphParams> for AtlasKey {
541 fn from(params: RenderGlyphParams) -> Self {
542 Self::Glyph(params)
543 }
544}
545
546impl From<RenderSvgParams> for AtlasKey {
547 fn from(params: RenderSvgParams) -> Self {
548 Self::Svg(params)
549 }
550}
551
552impl From<RenderImageParams> for AtlasKey {
553 fn from(params: RenderImageParams) -> Self {
554 Self::Image(params)
555 }
556}
557
558pub(crate) trait PlatformAtlas: Send + Sync {
559 fn get_or_insert_with<'a>(
560 &self,
561 key: &AtlasKey,
562 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
563 ) -> Result<Option<AtlasTile>>;
564}
565
566#[derive(Clone, Debug, PartialEq, Eq)]
567#[repr(C)]
568pub(crate) struct AtlasTile {
569 pub(crate) texture_id: AtlasTextureId,
570 pub(crate) tile_id: TileId,
571 pub(crate) padding: u32,
572 pub(crate) bounds: Bounds<DevicePixels>,
573}
574
575#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
576#[repr(C)]
577pub(crate) struct AtlasTextureId {
578 // We use u32 instead of usize for Metal Shader Language compatibility
579 pub(crate) index: u32,
580 pub(crate) kind: AtlasTextureKind,
581}
582
583#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
584#[repr(C)]
585#[cfg_attr(
586 all(
587 any(target_os = "linux", target_os = "freebsd"),
588 not(any(feature = "x11", feature = "wayland"))
589 ),
590 allow(dead_code)
591)]
592pub(crate) enum AtlasTextureKind {
593 Monochrome = 0,
594 Polychrome = 1,
595 Path = 2,
596}
597
598#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
599#[repr(C)]
600pub(crate) struct TileId(pub(crate) u32);
601
602impl From<etagere::AllocId> for TileId {
603 fn from(id: etagere::AllocId) -> Self {
604 Self(id.serialize())
605 }
606}
607
608impl From<TileId> for etagere::AllocId {
609 fn from(id: TileId) -> Self {
610 Self::deserialize(id.0)
611 }
612}
613
614pub(crate) struct PlatformInputHandler {
615 cx: AsyncWindowContext,
616 handler: Box<dyn InputHandler>,
617}
618
619#[cfg_attr(
620 all(
621 any(target_os = "linux", target_os = "freebsd"),
622 not(any(feature = "x11", feature = "wayland"))
623 ),
624 allow(dead_code)
625)]
626impl PlatformInputHandler {
627 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
628 Self { cx, handler }
629 }
630
631 fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
632 self.cx
633 .update(|cx| self.handler.selected_text_range(ignore_disabled_input, cx))
634 .ok()
635 .flatten()
636 }
637
638 fn marked_text_range(&mut self) -> Option<Range<usize>> {
639 self.cx
640 .update(|cx| self.handler.marked_text_range(cx))
641 .ok()
642 .flatten()
643 }
644
645 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
646 fn text_for_range(
647 &mut self,
648 range_utf16: Range<usize>,
649 adjusted: &mut Option<Range<usize>>,
650 ) -> Option<String> {
651 self.cx
652 .update(|cx| self.handler.text_for_range(range_utf16, adjusted, cx))
653 .ok()
654 .flatten()
655 }
656
657 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
658 self.cx
659 .update(|cx| {
660 self.handler
661 .replace_text_in_range(replacement_range, text, cx);
662 })
663 .ok();
664 }
665
666 fn replace_and_mark_text_in_range(
667 &mut self,
668 range_utf16: Option<Range<usize>>,
669 new_text: &str,
670 new_selected_range: Option<Range<usize>>,
671 ) {
672 self.cx
673 .update(|cx| {
674 self.handler.replace_and_mark_text_in_range(
675 range_utf16,
676 new_text,
677 new_selected_range,
678 cx,
679 )
680 })
681 .ok();
682 }
683
684 fn unmark_text(&mut self) {
685 self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
686 }
687
688 fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
689 self.cx
690 .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
691 .ok()
692 .flatten()
693 }
694
695 #[allow(dead_code)]
696 fn apple_press_and_hold_enabled(&mut self) -> bool {
697 self.handler.apple_press_and_hold_enabled()
698 }
699
700 pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
701 self.handler.replace_text_in_range(None, input, cx);
702 }
703
704 pub fn selected_bounds(&mut self, cx: &mut WindowContext) -> Option<Bounds<Pixels>> {
705 let selection = self.handler.selected_text_range(true, cx)?;
706 self.handler.bounds_for_range(
707 if selection.reversed {
708 selection.range.start..selection.range.start
709 } else {
710 selection.range.end..selection.range.end
711 },
712 cx,
713 )
714 }
715}
716
717/// A struct representing a selection in a text buffer, in UTF16 characters.
718/// This is different from a range because the head may be before the tail.
719#[derive(Debug)]
720pub struct UTF16Selection {
721 /// The range of text in the document this selection corresponds to
722 /// in UTF16 characters.
723 pub range: Range<usize>,
724 /// Whether the head of this selection is at the start (true), or end (false)
725 /// of the range
726 pub reversed: bool,
727}
728
729/// Zed's interface for handling text input from the platform's IME system
730/// This is currently a 1:1 exposure of the NSTextInputClient API:
731///
732/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
733pub trait InputHandler: 'static {
734 /// Get the range of the user's currently selected text, if any
735 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
736 ///
737 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
738 fn selected_text_range(
739 &mut self,
740 ignore_disabled_input: bool,
741 cx: &mut WindowContext,
742 ) -> Option<UTF16Selection>;
743
744 /// Get the range of the currently marked text, if any
745 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
746 ///
747 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
748 fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
749
750 /// Get the text for the given document range in UTF-16 characters
751 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
752 ///
753 /// range_utf16 is in terms of UTF-16 characters
754 fn text_for_range(
755 &mut self,
756 range_utf16: Range<usize>,
757 adjusted_range: &mut Option<Range<usize>>,
758 cx: &mut WindowContext,
759 ) -> Option<String>;
760
761 /// Replace the text in the given document range with the given text
762 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
763 ///
764 /// replacement_range is in terms of UTF-16 characters
765 fn replace_text_in_range(
766 &mut self,
767 replacement_range: Option<Range<usize>>,
768 text: &str,
769 cx: &mut WindowContext,
770 );
771
772 /// Replace the text in the given document range with the given text,
773 /// and mark the given text as part of an IME 'composing' state
774 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
775 ///
776 /// range_utf16 is in terms of UTF-16 characters
777 /// new_selected_range is in terms of UTF-16 characters
778 fn replace_and_mark_text_in_range(
779 &mut self,
780 range_utf16: Option<Range<usize>>,
781 new_text: &str,
782 new_selected_range: Option<Range<usize>>,
783 cx: &mut WindowContext,
784 );
785
786 /// Remove the IME 'composing' state from the document
787 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
788 fn unmark_text(&mut self, cx: &mut WindowContext);
789
790 /// Get the bounds of the given document range in screen coordinates
791 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
792 ///
793 /// This is used for positioning the IME candidate window
794 fn bounds_for_range(
795 &mut self,
796 range_utf16: Range<usize>,
797 cx: &mut WindowContext,
798 ) -> Option<Bounds<Pixels>>;
799
800 /// Allows a given input context to opt into getting raw key repeats instead of
801 /// sending these to the platform.
802 /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
803 /// (which is how iTerm does it) but it doesn't seem to work for me.
804 #[allow(dead_code)]
805 fn apple_press_and_hold_enabled(&mut self) -> bool {
806 true
807 }
808}
809
810/// The variables that can be configured when creating a new window
811#[derive(Debug)]
812pub struct WindowOptions {
813 /// Specifies the state and bounds of the window in screen coordinates.
814 /// - `None`: Inherit the bounds.
815 /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
816 pub window_bounds: Option<WindowBounds>,
817
818 /// The titlebar configuration of the window
819 pub titlebar: Option<TitlebarOptions>,
820
821 /// Whether the window should be focused when created
822 pub focus: bool,
823
824 /// Whether the window should be shown when created
825 pub show: bool,
826
827 /// The kind of window to create
828 pub kind: WindowKind,
829
830 /// Whether the window should be movable by the user
831 pub is_movable: bool,
832
833 /// The display to create the window on, if this is None,
834 /// the window will be created on the main display
835 pub display_id: Option<DisplayId>,
836
837 /// The appearance of the window background.
838 pub window_background: WindowBackgroundAppearance,
839
840 /// Application identifier of the window. Can by used by desktop environments to group applications together.
841 pub app_id: Option<String>,
842
843 /// Window minimum size
844 pub window_min_size: Option<Size<Pixels>>,
845
846 /// Whether to use client or server side decorations. Wayland only
847 /// Note that this may be ignored.
848 pub window_decorations: Option<WindowDecorations>,
849}
850
851/// The variables that can be configured when creating a new window
852#[derive(Debug)]
853#[cfg_attr(
854 all(
855 any(target_os = "linux", target_os = "freebsd"),
856 not(any(feature = "x11", feature = "wayland"))
857 ),
858 allow(dead_code)
859)]
860pub(crate) struct WindowParams {
861 pub bounds: Bounds<Pixels>,
862
863 /// The titlebar configuration of the window
864 #[cfg_attr(feature = "wayland", allow(dead_code))]
865 pub titlebar: Option<TitlebarOptions>,
866
867 /// The kind of window to create
868 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
869 pub kind: WindowKind,
870
871 /// Whether the window should be movable by the user
872 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
873 pub is_movable: bool,
874
875 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
876 pub focus: bool,
877
878 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
879 pub show: bool,
880
881 #[cfg_attr(feature = "wayland", allow(dead_code))]
882 pub display_id: Option<DisplayId>,
883
884 pub window_min_size: Option<Size<Pixels>>,
885}
886
887/// Represents the status of how a window should be opened.
888#[derive(Debug, Copy, Clone, PartialEq)]
889pub enum WindowBounds {
890 /// Indicates that the window should open in a windowed state with the given bounds.
891 Windowed(Bounds<Pixels>),
892 /// Indicates that the window should open in a maximized state.
893 /// The bounds provided here represent the restore size of the window.
894 Maximized(Bounds<Pixels>),
895 /// Indicates that the window should open in fullscreen mode.
896 /// The bounds provided here represent the restore size of the window.
897 Fullscreen(Bounds<Pixels>),
898}
899
900impl Default for WindowBounds {
901 fn default() -> Self {
902 WindowBounds::Windowed(Bounds::default())
903 }
904}
905
906impl WindowBounds {
907 /// Retrieve the inner bounds
908 pub fn get_bounds(&self) -> Bounds<Pixels> {
909 match self {
910 WindowBounds::Windowed(bounds) => *bounds,
911 WindowBounds::Maximized(bounds) => *bounds,
912 WindowBounds::Fullscreen(bounds) => *bounds,
913 }
914 }
915}
916
917impl Default for WindowOptions {
918 fn default() -> Self {
919 Self {
920 window_bounds: None,
921 titlebar: Some(TitlebarOptions {
922 title: Default::default(),
923 appears_transparent: Default::default(),
924 traffic_light_position: Default::default(),
925 }),
926 focus: true,
927 show: true,
928 kind: WindowKind::Normal,
929 is_movable: true,
930 display_id: None,
931 window_background: WindowBackgroundAppearance::default(),
932 app_id: None,
933 window_min_size: None,
934 window_decorations: None,
935 }
936 }
937}
938
939/// The options that can be configured for a window's titlebar
940#[derive(Debug, Default)]
941pub struct TitlebarOptions {
942 /// The initial title of the window
943 pub title: Option<SharedString>,
944
945 /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
946 /// Refer to [`WindowOptions::window_decorations`] on Linux
947 pub appears_transparent: bool,
948
949 /// The position of the macOS traffic light buttons
950 pub traffic_light_position: Option<Point<Pixels>>,
951}
952
953/// The kind of window to create
954#[derive(Copy, Clone, Debug, PartialEq, Eq)]
955pub enum WindowKind {
956 /// A normal application window
957 Normal,
958
959 /// A window that appears above all other windows, usually used for alerts or popups
960 /// use sparingly!
961 PopUp,
962}
963
964/// The appearance of the window, as defined by the operating system.
965///
966/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
967/// values.
968#[derive(Copy, Clone, Debug)]
969pub enum WindowAppearance {
970 /// A light appearance.
971 ///
972 /// On macOS, this corresponds to the `aqua` appearance.
973 Light,
974
975 /// A light appearance with vibrant colors.
976 ///
977 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
978 VibrantLight,
979
980 /// A dark appearance.
981 ///
982 /// On macOS, this corresponds to the `darkAqua` appearance.
983 Dark,
984
985 /// A dark appearance with vibrant colors.
986 ///
987 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
988 VibrantDark,
989}
990
991impl Default for WindowAppearance {
992 fn default() -> Self {
993 Self::Light
994 }
995}
996
997/// The appearance of the background of the window itself, when there is
998/// no content or the content is transparent.
999#[derive(Copy, Clone, Debug, Default, PartialEq)]
1000pub enum WindowBackgroundAppearance {
1001 /// Opaque.
1002 ///
1003 /// This lets the window manager know that content behind this
1004 /// window does not need to be drawn.
1005 ///
1006 /// Actual color depends on the system and themes should define a fully
1007 /// opaque background color instead.
1008 #[default]
1009 Opaque,
1010 /// Plain alpha transparency.
1011 Transparent,
1012 /// Transparency, but the contents behind the window are blurred.
1013 ///
1014 /// Not always supported.
1015 Blurred,
1016}
1017
1018/// The options that can be configured for a file dialog prompt
1019#[derive(Copy, Clone, Debug)]
1020pub struct PathPromptOptions {
1021 /// Should the prompt allow files to be selected?
1022 pub files: bool,
1023 /// Should the prompt allow directories to be selected?
1024 pub directories: bool,
1025 /// Should the prompt allow multiple files to be selected?
1026 pub multiple: bool,
1027}
1028
1029/// What kind of prompt styling to show
1030#[derive(Copy, Clone, Debug, PartialEq)]
1031pub enum PromptLevel {
1032 /// A prompt that is shown when the user should be notified of something
1033 Info,
1034
1035 /// A prompt that is shown when the user needs to be warned of a potential problem
1036 Warning,
1037
1038 /// A prompt that is shown when a critical problem has occurred
1039 Critical,
1040}
1041
1042/// The style of the cursor (pointer)
1043#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1044pub enum CursorStyle {
1045 /// The default cursor
1046 Arrow,
1047
1048 /// A text input cursor
1049 /// corresponds to the CSS cursor value `text`
1050 IBeam,
1051
1052 /// A crosshair cursor
1053 /// corresponds to the CSS cursor value `crosshair`
1054 Crosshair,
1055
1056 /// A closed hand cursor
1057 /// corresponds to the CSS cursor value `grabbing`
1058 ClosedHand,
1059
1060 /// An open hand cursor
1061 /// corresponds to the CSS cursor value `grab`
1062 OpenHand,
1063
1064 /// A pointing hand cursor
1065 /// corresponds to the CSS cursor value `pointer`
1066 PointingHand,
1067
1068 /// A resize left cursor
1069 /// corresponds to the CSS cursor value `w-resize`
1070 ResizeLeft,
1071
1072 /// A resize right cursor
1073 /// corresponds to the CSS cursor value `e-resize`
1074 ResizeRight,
1075
1076 /// A resize cursor to the left and right
1077 /// corresponds to the CSS cursor value `ew-resize`
1078 ResizeLeftRight,
1079
1080 /// A resize up cursor
1081 /// corresponds to the CSS cursor value `n-resize`
1082 ResizeUp,
1083
1084 /// A resize down cursor
1085 /// corresponds to the CSS cursor value `s-resize`
1086 ResizeDown,
1087
1088 /// A resize cursor directing up and down
1089 /// corresponds to the CSS cursor value `ns-resize`
1090 ResizeUpDown,
1091
1092 /// A resize cursor directing up-left and down-right
1093 /// corresponds to the CSS cursor value `nesw-resize`
1094 ResizeUpLeftDownRight,
1095
1096 /// A resize cursor directing up-right and down-left
1097 /// corresponds to the CSS cursor value `nwse-resize`
1098 ResizeUpRightDownLeft,
1099
1100 /// A cursor indicating that the item/column can be resized horizontally.
1101 /// corresponds to the CSS cursor value `col-resize`
1102 ResizeColumn,
1103
1104 /// A cursor indicating that the item/row can be resized vertically.
1105 /// corresponds to the CSS cursor value `row-resize`
1106 ResizeRow,
1107
1108 /// A text input cursor for vertical layout
1109 /// corresponds to the CSS cursor value `vertical-text`
1110 IBeamCursorForVerticalLayout,
1111
1112 /// A cursor indicating that the operation is not allowed
1113 /// corresponds to the CSS cursor value `not-allowed`
1114 OperationNotAllowed,
1115
1116 /// A cursor indicating that the operation will result in a link
1117 /// corresponds to the CSS cursor value `alias`
1118 DragLink,
1119
1120 /// A cursor indicating that the operation will result in a copy
1121 /// corresponds to the CSS cursor value `copy`
1122 DragCopy,
1123
1124 /// A cursor indicating that the operation will result in a context menu
1125 /// corresponds to the CSS cursor value `context-menu`
1126 ContextualMenu,
1127}
1128
1129impl Default for CursorStyle {
1130 fn default() -> Self {
1131 Self::Arrow
1132 }
1133}
1134
1135/// A clipboard item that should be copied to the clipboard
1136#[derive(Clone, Debug, Eq, PartialEq)]
1137pub struct ClipboardItem {
1138 entries: Vec<ClipboardEntry>,
1139}
1140
1141/// Either a ClipboardString or a ClipboardImage
1142#[derive(Clone, Debug, Eq, PartialEq)]
1143pub enum ClipboardEntry {
1144 /// A string entry
1145 String(ClipboardString),
1146 /// An image entry
1147 Image(Image),
1148}
1149
1150impl ClipboardItem {
1151 /// Create a new ClipboardItem::String with no associated metadata
1152 pub fn new_string(text: String) -> Self {
1153 Self {
1154 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1155 }
1156 }
1157
1158 /// Create a new ClipboardItem::String with the given text and associated metadata
1159 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1160 Self {
1161 entries: vec![ClipboardEntry::String(ClipboardString {
1162 text,
1163 metadata: Some(metadata),
1164 })],
1165 }
1166 }
1167
1168 /// Create a new ClipboardItem::String with the given text and associated metadata
1169 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1170 Self {
1171 entries: vec![ClipboardEntry::String(
1172 ClipboardString::new(text).with_json_metadata(metadata),
1173 )],
1174 }
1175 }
1176
1177 /// Create a new ClipboardItem::Image with the given image with no associated metadata
1178 pub fn new_image(image: &Image) -> Self {
1179 Self {
1180 entries: vec![ClipboardEntry::Image(image.clone())],
1181 }
1182 }
1183
1184 /// Concatenates together all the ClipboardString entries in the item.
1185 /// Returns None if there were no ClipboardString entries.
1186 pub fn text(&self) -> Option<String> {
1187 let mut answer = String::new();
1188 let mut any_entries = false;
1189
1190 for entry in self.entries.iter() {
1191 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1192 answer.push_str(text);
1193 any_entries = true;
1194 }
1195 }
1196
1197 if any_entries {
1198 Some(answer)
1199 } else {
1200 None
1201 }
1202 }
1203
1204 /// If this item is one ClipboardEntry::String, returns its metadata.
1205 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1206 pub fn metadata(&self) -> Option<&String> {
1207 match self.entries().first() {
1208 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1209 clipboard_string.metadata.as_ref()
1210 }
1211 _ => None,
1212 }
1213 }
1214
1215 /// Get the item's entries
1216 pub fn entries(&self) -> &[ClipboardEntry] {
1217 &self.entries
1218 }
1219
1220 /// Get owned versions of the item's entries
1221 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1222 self.entries.into_iter()
1223 }
1224}
1225
1226/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1227#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1228pub enum ImageFormat {
1229 // Sorted from most to least likely to be pasted into an editor,
1230 // which matters when we iterate through them trying to see if
1231 // clipboard content matches them.
1232 /// .png
1233 Png,
1234 /// .jpeg or .jpg
1235 Jpeg,
1236 /// .webp
1237 Webp,
1238 /// .gif
1239 Gif,
1240 /// .svg
1241 Svg,
1242 /// .bmp
1243 Bmp,
1244 /// .tif or .tiff
1245 Tiff,
1246}
1247
1248/// An image, with a format and certain bytes
1249#[derive(Clone, Debug, PartialEq, Eq)]
1250pub struct Image {
1251 /// The image format the bytes represent (e.g. PNG)
1252 pub format: ImageFormat,
1253 /// The raw image bytes
1254 pub bytes: Vec<u8>,
1255 /// The unique ID for the image
1256 pub id: u64,
1257}
1258
1259impl Hash for Image {
1260 fn hash<H: Hasher>(&self, state: &mut H) {
1261 state.write_u64(self.id);
1262 }
1263}
1264
1265impl Image {
1266 /// Get this image's ID
1267 pub fn id(&self) -> u64 {
1268 self.id
1269 }
1270
1271 /// Use the GPUI `use_asset` API to make this image renderable
1272 pub fn use_render_image(self: Arc<Self>, cx: &mut WindowContext) -> Option<Arc<RenderImage>> {
1273 ImageSource::Image(self)
1274 .use_data(cx)
1275 .and_then(|result| result.ok())
1276 }
1277
1278 /// Convert the clipboard image to an `ImageData` object.
1279 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1280 fn frames_for_image(
1281 bytes: &[u8],
1282 format: image::ImageFormat,
1283 ) -> Result<SmallVec<[Frame; 1]>> {
1284 let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1285
1286 // Convert from RGBA to BGRA.
1287 for pixel in data.chunks_exact_mut(4) {
1288 pixel.swap(0, 2);
1289 }
1290
1291 Ok(SmallVec::from_elem(Frame::new(data), 1))
1292 }
1293
1294 let frames = match self.format {
1295 ImageFormat::Gif => {
1296 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1297 let mut frames = SmallVec::new();
1298
1299 for frame in decoder.into_frames() {
1300 let mut frame = frame?;
1301 // Convert from RGBA to BGRA.
1302 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1303 pixel.swap(0, 2);
1304 }
1305 frames.push(frame);
1306 }
1307
1308 frames
1309 }
1310 ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1311 ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1312 ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1313 ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1314 ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1315 ImageFormat::Svg => {
1316 let pixmap = svg_renderer.render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1317
1318 let buffer =
1319 image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1320 .unwrap();
1321
1322 SmallVec::from_elem(Frame::new(buffer), 1)
1323 }
1324 };
1325
1326 Ok(Arc::new(RenderImage::new(frames)))
1327 }
1328
1329 /// Get the format of the clipboard image
1330 pub fn format(&self) -> ImageFormat {
1331 self.format
1332 }
1333
1334 /// Get the raw bytes of the clipboard image
1335 pub fn bytes(&self) -> &[u8] {
1336 self.bytes.as_slice()
1337 }
1338}
1339
1340/// A clipboard item that should be copied to the clipboard
1341#[derive(Clone, Debug, Eq, PartialEq)]
1342pub struct ClipboardString {
1343 pub(crate) text: String,
1344 pub(crate) metadata: Option<String>,
1345}
1346
1347impl ClipboardString {
1348 /// Create a new clipboard string with the given text
1349 pub fn new(text: String) -> Self {
1350 Self {
1351 text,
1352 metadata: None,
1353 }
1354 }
1355
1356 /// Return a new clipboard item with the metadata replaced by the given metadata,
1357 /// after serializing it as JSON.
1358 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1359 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1360 self
1361 }
1362
1363 /// Get the text of the clipboard string
1364 pub fn text(&self) -> &String {
1365 &self.text
1366 }
1367
1368 /// Get the owned text of the clipboard string
1369 pub fn into_text(self) -> String {
1370 self.text
1371 }
1372
1373 /// Get the metadata of the clipboard string, formatted as JSON
1374 pub fn metadata_json<T>(&self) -> Option<T>
1375 where
1376 T: for<'a> Deserialize<'a>,
1377 {
1378 self.metadata
1379 .as_ref()
1380 .and_then(|m| serde_json::from_str(m).ok())
1381 }
1382
1383 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1384 pub(crate) fn text_hash(text: &str) -> u64 {
1385 let mut hasher = SeaHasher::new();
1386 text.hash(&mut hasher);
1387 hasher.finish()
1388 }
1389}