1mod app_menu;
2mod keyboard;
3mod keystroke;
4
5#[cfg(any(target_os = "linux", target_os = "freebsd"))]
6mod linux;
7
8#[cfg(target_os = "macos")]
9mod mac;
10
11#[cfg(any(
12 all(
13 any(target_os = "linux", target_os = "freebsd"),
14 any(feature = "x11", feature = "wayland")
15 ),
16 all(target_os = "macos", feature = "macos-blade")
17))]
18mod blade;
19
20#[cfg(any(test, feature = "test-support"))]
21mod test;
22
23#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
24mod visual_test;
25
26#[cfg(target_os = "windows")]
27mod windows;
28
29#[cfg(all(
30 feature = "screen-capture",
31 any(
32 target_os = "windows",
33 all(
34 any(target_os = "linux", target_os = "freebsd"),
35 any(feature = "wayland", feature = "x11"),
36 )
37 )
38))]
39pub(crate) mod scap_screen_capture;
40
41use crate::{
42 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
43 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun,
44 ForegroundExecutor, GlyphId, GpuSpecs, ImageSource, Keymap, LineLayout, Pixels, PlatformInput,
45 Point, Priority, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene,
46 ShapedGlyph, ShapedRun, SharedString, Size, SvgRenderer, SystemWindowTab, Task, TaskTiming,
47 ThreadTaskTimings, Window, WindowControlArea, hash, point, px, size,
48};
49use anyhow::Result;
50use async_task::Runnable;
51use futures::channel::oneshot;
52#[cfg(any(test, feature = "test-support"))]
53use image::RgbaImage;
54use image::codecs::gif::GifDecoder;
55use image::{AnimationDecoder as _, Frame};
56use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
57pub use scheduler::RunnableMeta;
58use schemars::JsonSchema;
59use seahash::SeaHasher;
60use serde::{Deserialize, Serialize};
61use smallvec::SmallVec;
62use std::borrow::Cow;
63use std::hash::{Hash, Hasher};
64use std::io::Cursor;
65use std::ops;
66use std::time::{Duration, Instant};
67use std::{
68 fmt::{self, Debug},
69 ops::Range,
70 path::{Path, PathBuf},
71 rc::Rc,
72 sync::Arc,
73};
74use strum::EnumIter;
75use uuid::Uuid;
76
77pub use app_menu::*;
78pub use keyboard::*;
79pub use keystroke::*;
80
81#[cfg(any(target_os = "linux", target_os = "freebsd"))]
82pub(crate) use linux::*;
83#[cfg(target_os = "macos")]
84pub(crate) use mac::*;
85#[cfg(any(test, feature = "test-support"))]
86pub(crate) use test::*;
87#[cfg(target_os = "windows")]
88pub(crate) use windows::*;
89
90#[cfg(all(target_os = "linux", feature = "wayland"))]
91pub use linux::layer_shell;
92
93#[cfg(any(test, feature = "test-support"))]
94pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
95
96#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
97pub use visual_test::VisualTestPlatform;
98
99/// Returns a background executor for the current platform.
100pub fn background_executor() -> BackgroundExecutor {
101 current_platform(true).background_executor()
102}
103
104#[cfg(target_os = "macos")]
105pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
106 Rc::new(MacPlatform::new(headless))
107}
108
109#[cfg(any(target_os = "linux", target_os = "freebsd"))]
110pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
111 #[cfg(feature = "x11")]
112 use anyhow::Context as _;
113
114 if headless {
115 return Rc::new(HeadlessClient::new());
116 }
117
118 match guess_compositor() {
119 #[cfg(feature = "wayland")]
120 "Wayland" => Rc::new(WaylandClient::new()),
121
122 #[cfg(feature = "x11")]
123 "X11" => Rc::new(
124 X11Client::new()
125 .context("Failed to initialize X11 client.")
126 .unwrap(),
127 ),
128
129 "Headless" => Rc::new(HeadlessClient::new()),
130 _ => unreachable!(),
131 }
132}
133
134#[cfg(target_os = "windows")]
135pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
136 Rc::new(
137 WindowsPlatform::new(headless)
138 .inspect_err(|err| show_error("Failed to launch", err.to_string()))
139 .unwrap(),
140 )
141}
142
143/// Return which compositor we're guessing we'll use.
144/// Does not attempt to connect to the given compositor
145#[cfg(any(target_os = "linux", target_os = "freebsd"))]
146#[inline]
147pub fn guess_compositor() -> &'static str {
148 if std::env::var_os("ZED_HEADLESS").is_some() {
149 return "Headless";
150 }
151
152 #[cfg(feature = "wayland")]
153 let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
154 #[cfg(not(feature = "wayland"))]
155 let wayland_display: Option<std::ffi::OsString> = None;
156
157 #[cfg(feature = "x11")]
158 let x11_display = std::env::var_os("DISPLAY");
159 #[cfg(not(feature = "x11"))]
160 let x11_display: Option<std::ffi::OsString> = None;
161
162 let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
163 let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
164
165 if use_wayland {
166 "Wayland"
167 } else if use_x11 {
168 "X11"
169 } else {
170 "Headless"
171 }
172}
173
174pub(crate) trait Platform: 'static {
175 fn background_executor(&self) -> BackgroundExecutor;
176 fn foreground_executor(&self) -> ForegroundExecutor;
177 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
178
179 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
180 fn quit(&self);
181 fn restart(&self, binary_path: Option<PathBuf>);
182 fn activate(&self, ignoring_other_apps: bool);
183 fn hide(&self);
184 fn hide_other_apps(&self);
185 fn unhide_other_apps(&self);
186
187 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
188 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
189 fn active_window(&self) -> Option<AnyWindowHandle>;
190 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
191 None
192 }
193
194 #[cfg(feature = "screen-capture")]
195 fn is_screen_capture_supported(&self) -> bool;
196 #[cfg(not(feature = "screen-capture"))]
197 fn is_screen_capture_supported(&self) -> bool {
198 false
199 }
200 #[cfg(feature = "screen-capture")]
201 fn screen_capture_sources(&self)
202 -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>>;
203 #[cfg(not(feature = "screen-capture"))]
204 fn screen_capture_sources(
205 &self,
206 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
207 let (sources_tx, sources_rx) = oneshot::channel();
208 sources_tx
209 .send(Err(anyhow::anyhow!(
210 "gpui was compiled without the screen-capture feature"
211 )))
212 .ok();
213 sources_rx
214 }
215
216 fn open_window(
217 &self,
218 handle: AnyWindowHandle,
219 options: WindowParams,
220 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
221
222 /// Returns the appearance of the application's windows.
223 fn window_appearance(&self) -> WindowAppearance;
224
225 fn open_url(&self, url: &str);
226 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
227 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
228
229 fn prompt_for_paths(
230 &self,
231 options: PathPromptOptions,
232 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
233 fn prompt_for_new_path(
234 &self,
235 directory: &Path,
236 suggested_name: Option<&str>,
237 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
238 fn can_select_mixed_files_and_dirs(&self) -> bool;
239 fn reveal_path(&self, path: &Path);
240 fn open_with_system(&self, path: &Path);
241
242 fn on_quit(&self, callback: Box<dyn FnMut()>);
243 fn on_reopen(&self, callback: Box<dyn FnMut()>);
244
245 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
246 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
247 None
248 }
249
250 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
251 fn perform_dock_menu_action(&self, _action: usize) {}
252 fn add_recent_document(&self, _path: &Path) {}
253 fn update_jump_list(
254 &self,
255 _menus: Vec<MenuItem>,
256 _entries: Vec<SmallVec<[PathBuf; 2]>>,
257 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
258 Task::ready(Vec::new())
259 }
260 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
261 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
262 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
263
264 fn thermal_state(&self) -> ThermalState;
265 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
266
267 fn compositor_name(&self) -> &'static str {
268 ""
269 }
270 fn app_path(&self) -> Result<PathBuf>;
271 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
272
273 fn set_cursor_style(&self, style: CursorStyle);
274 fn should_auto_hide_scrollbars(&self) -> bool;
275
276 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
277 fn write_to_clipboard(&self, item: ClipboardItem);
278
279 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
280 fn read_from_primary(&self) -> Option<ClipboardItem>;
281 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
282 fn write_to_primary(&self, item: ClipboardItem);
283
284 #[cfg(target_os = "macos")]
285 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
286 #[cfg(target_os = "macos")]
287 fn write_to_find_pasteboard(&self, item: ClipboardItem);
288
289 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
290 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
291 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
292
293 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
294 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
295 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
296}
297
298/// A handle to a platform's display, e.g. a monitor or laptop screen.
299pub trait PlatformDisplay: Send + Sync + Debug {
300 /// Get the ID for this display
301 fn id(&self) -> DisplayId;
302
303 /// Returns a stable identifier for this display that can be persisted and used
304 /// across system restarts.
305 fn uuid(&self) -> Result<Uuid>;
306
307 /// Get the bounds for this display
308 fn bounds(&self) -> Bounds<Pixels>;
309
310 /// Get the visible bounds for this display, excluding taskbar/dock areas.
311 /// This is the usable area where windows can be placed without being obscured.
312 /// Defaults to the full display bounds if not overridden.
313 fn visible_bounds(&self) -> Bounds<Pixels> {
314 self.bounds()
315 }
316
317 /// Get the default bounds for this display to place a window
318 fn default_bounds(&self) -> Bounds<Pixels> {
319 let bounds = self.bounds();
320 let center = bounds.center();
321 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
322
323 let offset = clipped_window_size / 2.0;
324 let origin = point(center.x - offset.width, center.y - offset.height);
325 Bounds::new(origin, clipped_window_size)
326 }
327}
328
329/// Thermal state of the system
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331pub enum ThermalState {
332 /// System has no thermal constraints
333 Nominal,
334 /// System is slightly constrained, reduce discretionary work
335 Fair,
336 /// System is moderately constrained, reduce CPU/GPU intensive work
337 Serious,
338 /// System is critically constrained, minimize all resource usage
339 Critical,
340}
341
342/// Metadata for a given [ScreenCaptureSource]
343#[derive(Clone)]
344pub struct SourceMetadata {
345 /// Opaque identifier of this screen.
346 pub id: u64,
347 /// Human-readable label for this source.
348 pub label: Option<SharedString>,
349 /// Whether this source is the main display.
350 pub is_main: Option<bool>,
351 /// Video resolution of this source.
352 pub resolution: Size<DevicePixels>,
353}
354
355/// A source of on-screen video content that can be captured.
356pub trait ScreenCaptureSource {
357 /// Returns metadata for this source.
358 fn metadata(&self) -> Result<SourceMetadata>;
359
360 /// Start capture video from this source, invoking the given callback
361 /// with each frame.
362 fn stream(
363 &self,
364 foreground_executor: &ForegroundExecutor,
365 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
366 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
367}
368
369/// A video stream captured from a screen.
370pub trait ScreenCaptureStream {
371 /// Returns metadata for this source.
372 fn metadata(&self) -> Result<SourceMetadata>;
373}
374
375/// A frame of video captured from a screen.
376pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
377
378/// An opaque identifier for a hardware display
379#[derive(PartialEq, Eq, Hash, Copy, Clone)]
380pub struct DisplayId(pub(crate) u32);
381
382impl From<DisplayId> for u32 {
383 fn from(id: DisplayId) -> Self {
384 id.0
385 }
386}
387
388impl Debug for DisplayId {
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 write!(f, "DisplayId({})", self.0)
391 }
392}
393
394/// Which part of the window to resize
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
396pub enum ResizeEdge {
397 /// The top edge
398 Top,
399 /// The top right corner
400 TopRight,
401 /// The right edge
402 Right,
403 /// The bottom right corner
404 BottomRight,
405 /// The bottom edge
406 Bottom,
407 /// The bottom left corner
408 BottomLeft,
409 /// The left edge
410 Left,
411 /// The top left corner
412 TopLeft,
413}
414
415/// A type to describe the appearance of a window
416#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
417pub enum WindowDecorations {
418 #[default]
419 /// Server side decorations
420 Server,
421 /// Client side decorations
422 Client,
423}
424
425/// A type to describe how this window is currently configured
426#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
427pub enum Decorations {
428 /// The window is configured to use server side decorations
429 #[default]
430 Server,
431 /// The window is configured to use client side decorations
432 Client {
433 /// The edge tiling state
434 tiling: Tiling,
435 },
436}
437
438/// What window controls this platform supports
439#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
440pub struct WindowControls {
441 /// Whether this platform supports fullscreen
442 pub fullscreen: bool,
443 /// Whether this platform supports maximize
444 pub maximize: bool,
445 /// Whether this platform supports minimize
446 pub minimize: bool,
447 /// Whether this platform supports a window menu
448 pub window_menu: bool,
449}
450
451impl Default for WindowControls {
452 fn default() -> Self {
453 // Assume that we can do anything, unless told otherwise
454 Self {
455 fullscreen: true,
456 maximize: true,
457 minimize: true,
458 window_menu: true,
459 }
460 }
461}
462
463/// A type to describe which sides of the window are currently tiled in some way
464#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
465pub struct Tiling {
466 /// Whether the top edge is tiled
467 pub top: bool,
468 /// Whether the left edge is tiled
469 pub left: bool,
470 /// Whether the right edge is tiled
471 pub right: bool,
472 /// Whether the bottom edge is tiled
473 pub bottom: bool,
474}
475
476impl Tiling {
477 /// Initializes a [`Tiling`] type with all sides tiled
478 pub fn tiled() -> Self {
479 Self {
480 top: true,
481 left: true,
482 right: true,
483 bottom: true,
484 }
485 }
486
487 /// Whether any edge is tiled
488 pub fn is_tiled(&self) -> bool {
489 self.top || self.left || self.right || self.bottom
490 }
491}
492
493#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
494pub(crate) struct RequestFrameOptions {
495 pub(crate) require_presentation: bool,
496 /// Force refresh of all rendering states when true
497 pub(crate) force_render: bool,
498}
499
500pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
501 fn bounds(&self) -> Bounds<Pixels>;
502 fn is_maximized(&self) -> bool;
503 fn window_bounds(&self) -> WindowBounds;
504 fn content_size(&self) -> Size<Pixels>;
505 fn resize(&mut self, size: Size<Pixels>);
506 fn scale_factor(&self) -> f32;
507 fn appearance(&self) -> WindowAppearance;
508 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
509 fn mouse_position(&self) -> Point<Pixels>;
510 fn modifiers(&self) -> Modifiers;
511 fn capslock(&self) -> Capslock;
512 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
513 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
514 fn prompt(
515 &self,
516 level: PromptLevel,
517 msg: &str,
518 detail: Option<&str>,
519 answers: &[PromptButton],
520 ) -> Option<oneshot::Receiver<usize>>;
521 fn activate(&self);
522 fn is_active(&self) -> bool;
523 fn is_hovered(&self) -> bool;
524 fn background_appearance(&self) -> WindowBackgroundAppearance;
525 fn set_title(&mut self, title: &str);
526 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
527 fn minimize(&self);
528 fn zoom(&self);
529 fn toggle_fullscreen(&self);
530 fn is_fullscreen(&self) -> bool;
531 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
532 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
533 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
534 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
535 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
536 fn on_moved(&self, callback: Box<dyn FnMut()>);
537 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
538 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
539 fn on_close(&self, callback: Box<dyn FnOnce()>);
540 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
541 fn draw(&self, scene: &Scene);
542 fn completed_frame(&self) {}
543 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
544 fn is_subpixel_rendering_supported(&self) -> bool;
545
546 // macOS specific methods
547 fn get_title(&self) -> String {
548 String::new()
549 }
550 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
551 None
552 }
553 fn tab_bar_visible(&self) -> bool {
554 false
555 }
556 fn set_edited(&mut self, _edited: bool) {}
557 fn show_character_palette(&self) {}
558 fn titlebar_double_click(&self) {}
559 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
560 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
561 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
562 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
563 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
564 fn merge_all_windows(&self) {}
565 fn move_tab_to_new_window(&self) {}
566 fn toggle_window_tab_overview(&self) {}
567 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
568
569 #[cfg(target_os = "windows")]
570 fn get_raw_handle(&self) -> windows::HWND;
571
572 // Linux specific methods
573 fn inner_window_bounds(&self) -> WindowBounds {
574 self.window_bounds()
575 }
576 fn request_decorations(&self, _decorations: WindowDecorations) {}
577 fn show_window_menu(&self, _position: Point<Pixels>) {}
578 fn start_window_move(&self) {}
579 fn start_window_resize(&self, _edge: ResizeEdge) {}
580 fn window_decorations(&self) -> Decorations {
581 Decorations::Server
582 }
583 fn set_app_id(&mut self, _app_id: &str) {}
584 fn map_window(&mut self) -> anyhow::Result<()> {
585 Ok(())
586 }
587 fn window_controls(&self) -> WindowControls {
588 WindowControls::default()
589 }
590 fn set_client_inset(&self, _inset: Pixels) {}
591 fn gpu_specs(&self) -> Option<GpuSpecs>;
592
593 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
594
595 #[cfg(any(test, feature = "test-support"))]
596 fn as_test(&mut self) -> Option<&mut TestWindow> {
597 None
598 }
599
600 /// Renders the given scene to a texture and returns the pixel data as an RGBA image.
601 /// This does not present the frame to screen - useful for visual testing where we want
602 /// to capture what would be rendered without displaying it or requiring the window to be visible.
603 #[cfg(any(test, feature = "test-support"))]
604 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
605 anyhow::bail!("render_to_image not implemented for this platform")
606 }
607}
608
609/// Type alias for runnables with metadata.
610/// Previously an enum with a single variant, now simplified to a direct type alias.
611#[doc(hidden)]
612pub type RunnableVariant = Runnable<RunnableMeta>;
613
614#[doc(hidden)]
615pub struct TimerResolutionGuard {
616 cleanup: Option<Box<dyn FnOnce() + Send>>,
617}
618
619impl Drop for TimerResolutionGuard {
620 fn drop(&mut self) {
621 if let Some(cleanup) = self.cleanup.take() {
622 cleanup();
623 }
624 }
625}
626
627/// This type is public so that our test macro can generate and use it, but it should not
628/// be considered part of our public API.
629#[doc(hidden)]
630pub trait PlatformDispatcher: Send + Sync {
631 fn get_all_timings(&self) -> Vec<ThreadTaskTimings>;
632 fn get_current_thread_timings(&self) -> Vec<TaskTiming>;
633 fn is_main_thread(&self) -> bool;
634 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
635 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
636 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
637 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
638
639 fn now(&self) -> Instant {
640 Instant::now()
641 }
642
643 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
644 TimerResolutionGuard { cleanup: None }
645 }
646
647 #[cfg(any(test, feature = "test-support"))]
648 fn as_test(&self) -> Option<&TestDispatcher> {
649 None
650 }
651}
652
653pub(crate) trait PlatformTextSystem: Send + Sync {
654 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
655 fn all_font_names(&self) -> Vec<String>;
656 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
657 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
658 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
659 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
660 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
661 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
662 fn rasterize_glyph(
663 &self,
664 params: &RenderGlyphParams,
665 raster_bounds: Bounds<DevicePixels>,
666 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
667 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
668 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
669 -> TextRenderingMode;
670}
671
672pub(crate) struct NoopTextSystem;
673
674impl NoopTextSystem {
675 #[allow(dead_code)]
676 pub fn new() -> Self {
677 Self
678 }
679}
680
681impl PlatformTextSystem for NoopTextSystem {
682 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
683 Ok(())
684 }
685
686 fn all_font_names(&self) -> Vec<String> {
687 Vec::new()
688 }
689
690 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
691 Ok(FontId(1))
692 }
693
694 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
695 FontMetrics {
696 units_per_em: 1000,
697 ascent: 1025.0,
698 descent: -275.0,
699 line_gap: 0.0,
700 underline_position: -95.0,
701 underline_thickness: 60.0,
702 cap_height: 698.0,
703 x_height: 516.0,
704 bounding_box: Bounds {
705 origin: Point {
706 x: -260.0,
707 y: -245.0,
708 },
709 size: Size {
710 width: 1501.0,
711 height: 1364.0,
712 },
713 },
714 }
715 }
716
717 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
718 Ok(Bounds {
719 origin: Point { x: 54.0, y: 0.0 },
720 size: size(392.0, 528.0),
721 })
722 }
723
724 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
725 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
726 }
727
728 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
729 Some(GlyphId(ch.len_utf16() as u32))
730 }
731
732 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
733 Ok(Default::default())
734 }
735
736 fn rasterize_glyph(
737 &self,
738 _params: &RenderGlyphParams,
739 raster_bounds: Bounds<DevicePixels>,
740 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
741 Ok((raster_bounds.size, Vec::new()))
742 }
743
744 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
745 let mut position = px(0.);
746 let metrics = self.font_metrics(FontId(0));
747 let em_width = font_size
748 * self
749 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
750 .unwrap()
751 .width
752 / metrics.units_per_em as f32;
753 let mut glyphs = Vec::new();
754 for (ix, c) in text.char_indices() {
755 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
756 glyphs.push(ShapedGlyph {
757 id: glyph,
758 position: point(position, px(0.)),
759 index: ix,
760 is_emoji: glyph.0 == 2,
761 });
762 if glyph.0 == 2 {
763 position += em_width * 2.0;
764 } else {
765 position += em_width;
766 }
767 } else {
768 position += em_width
769 }
770 }
771 let mut runs = Vec::default();
772 if !glyphs.is_empty() {
773 runs.push(ShapedRun {
774 font_id: FontId(0),
775 glyphs,
776 });
777 } else {
778 position = px(0.);
779 }
780
781 LineLayout {
782 font_size,
783 width: position,
784 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
785 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
786 runs,
787 len: text.len(),
788 }
789 }
790
791 fn recommended_rendering_mode(
792 &self,
793 _font_id: FontId,
794 _font_size: Pixels,
795 ) -> TextRenderingMode {
796 TextRenderingMode::Grayscale
797 }
798}
799
800// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.cpp
801// Copyright (c) Microsoft Corporation.
802// Licensed under the MIT license.
803#[allow(dead_code)]
804pub(crate) fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
805 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
806 [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], // gamma = 1.0
807 [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], // gamma = 1.1
808 [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], // gamma = 1.2
809 [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], // gamma = 1.3
810 [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], // gamma = 1.4
811 [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], // gamma = 1.5
812 [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], // gamma = 1.6
813 [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], // gamma = 1.7
814 [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], // gamma = 1.8
815 [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], // gamma = 1.9
816 [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], // gamma = 2.0
817 [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], // gamma = 2.1
818 [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], // gamma = 2.2
819 ];
820
821 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
822 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
823
824 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
825 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
826
827 [
828 ratios[0] * NORM13,
829 ratios[1] * NORM24,
830 ratios[2] * NORM13,
831 ratios[3] * NORM24,
832 ]
833}
834
835#[derive(PartialEq, Eq, Hash, Clone)]
836pub(crate) enum AtlasKey {
837 Glyph(RenderGlyphParams),
838 Svg(RenderSvgParams),
839 Image(RenderImageParams),
840}
841
842impl AtlasKey {
843 #[cfg_attr(
844 all(
845 any(target_os = "linux", target_os = "freebsd"),
846 not(any(feature = "x11", feature = "wayland"))
847 ),
848 allow(dead_code)
849 )]
850 pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
851 match self {
852 AtlasKey::Glyph(params) => {
853 if params.is_emoji {
854 AtlasTextureKind::Polychrome
855 } else if params.subpixel_rendering {
856 AtlasTextureKind::Subpixel
857 } else {
858 AtlasTextureKind::Monochrome
859 }
860 }
861 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
862 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
863 }
864 }
865}
866
867impl From<RenderGlyphParams> for AtlasKey {
868 fn from(params: RenderGlyphParams) -> Self {
869 Self::Glyph(params)
870 }
871}
872
873impl From<RenderSvgParams> for AtlasKey {
874 fn from(params: RenderSvgParams) -> Self {
875 Self::Svg(params)
876 }
877}
878
879impl From<RenderImageParams> for AtlasKey {
880 fn from(params: RenderImageParams) -> Self {
881 Self::Image(params)
882 }
883}
884
885pub(crate) trait PlatformAtlas: Send + Sync {
886 fn get_or_insert_with<'a>(
887 &self,
888 key: &AtlasKey,
889 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
890 ) -> Result<Option<AtlasTile>>;
891 fn remove(&self, key: &AtlasKey);
892}
893
894struct AtlasTextureList<T> {
895 textures: Vec<Option<T>>,
896 free_list: Vec<usize>,
897}
898
899impl<T> Default for AtlasTextureList<T> {
900 fn default() -> Self {
901 Self {
902 textures: Vec::default(),
903 free_list: Vec::default(),
904 }
905 }
906}
907
908impl<T> ops::Index<usize> for AtlasTextureList<T> {
909 type Output = Option<T>;
910
911 fn index(&self, index: usize) -> &Self::Output {
912 &self.textures[index]
913 }
914}
915
916impl<T> AtlasTextureList<T> {
917 #[allow(unused)]
918 fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
919 self.free_list.clear();
920 self.textures.drain(..)
921 }
922
923 #[allow(dead_code)]
924 fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
925 self.textures.iter_mut().flatten()
926 }
927}
928
929#[derive(Clone, Debug, PartialEq, Eq)]
930#[repr(C)]
931pub(crate) struct AtlasTile {
932 pub(crate) texture_id: AtlasTextureId,
933 pub(crate) tile_id: TileId,
934 pub(crate) padding: u32,
935 pub(crate) bounds: Bounds<DevicePixels>,
936}
937
938#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
939#[repr(C)]
940pub(crate) struct AtlasTextureId {
941 // We use u32 instead of usize for Metal Shader Language compatibility
942 pub(crate) index: u32,
943 pub(crate) kind: AtlasTextureKind,
944}
945
946#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
947#[repr(C)]
948#[cfg_attr(
949 all(
950 any(target_os = "linux", target_os = "freebsd"),
951 not(any(feature = "x11", feature = "wayland"))
952 ),
953 allow(dead_code)
954)]
955pub(crate) enum AtlasTextureKind {
956 Monochrome = 0,
957 Polychrome = 1,
958 Subpixel = 2,
959}
960
961#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
962#[repr(C)]
963pub(crate) struct TileId(pub(crate) u32);
964
965impl From<etagere::AllocId> for TileId {
966 fn from(id: etagere::AllocId) -> Self {
967 Self(id.serialize())
968 }
969}
970
971impl From<TileId> for etagere::AllocId {
972 fn from(id: TileId) -> Self {
973 Self::deserialize(id.0)
974 }
975}
976
977pub(crate) struct PlatformInputHandler {
978 cx: AsyncWindowContext,
979 handler: Box<dyn InputHandler>,
980}
981
982#[cfg_attr(
983 all(
984 any(target_os = "linux", target_os = "freebsd"),
985 not(any(feature = "x11", feature = "wayland"))
986 ),
987 allow(dead_code)
988)]
989impl PlatformInputHandler {
990 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
991 Self { cx, handler }
992 }
993
994 fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
995 self.cx
996 .update(|window, cx| {
997 self.handler
998 .selected_text_range(ignore_disabled_input, window, cx)
999 })
1000 .ok()
1001 .flatten()
1002 }
1003
1004 #[cfg_attr(target_os = "windows", allow(dead_code))]
1005 fn marked_text_range(&mut self) -> Option<Range<usize>> {
1006 self.cx
1007 .update(|window, cx| self.handler.marked_text_range(window, cx))
1008 .ok()
1009 .flatten()
1010 }
1011
1012 #[cfg_attr(
1013 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1014 allow(dead_code)
1015 )]
1016 fn text_for_range(
1017 &mut self,
1018 range_utf16: Range<usize>,
1019 adjusted: &mut Option<Range<usize>>,
1020 ) -> Option<String> {
1021 self.cx
1022 .update(|window, cx| {
1023 self.handler
1024 .text_for_range(range_utf16, adjusted, window, cx)
1025 })
1026 .ok()
1027 .flatten()
1028 }
1029
1030 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
1031 self.cx
1032 .update(|window, cx| {
1033 self.handler
1034 .replace_text_in_range(replacement_range, text, window, cx);
1035 })
1036 .ok();
1037 }
1038
1039 pub fn replace_and_mark_text_in_range(
1040 &mut self,
1041 range_utf16: Option<Range<usize>>,
1042 new_text: &str,
1043 new_selected_range: Option<Range<usize>>,
1044 ) {
1045 self.cx
1046 .update(|window, cx| {
1047 self.handler.replace_and_mark_text_in_range(
1048 range_utf16,
1049 new_text,
1050 new_selected_range,
1051 window,
1052 cx,
1053 )
1054 })
1055 .ok();
1056 }
1057
1058 #[cfg_attr(target_os = "windows", allow(dead_code))]
1059 fn unmark_text(&mut self) {
1060 self.cx
1061 .update(|window, cx| self.handler.unmark_text(window, cx))
1062 .ok();
1063 }
1064
1065 fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
1066 self.cx
1067 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
1068 .ok()
1069 .flatten()
1070 }
1071
1072 #[allow(dead_code)]
1073 fn apple_press_and_hold_enabled(&mut self) -> bool {
1074 self.handler.apple_press_and_hold_enabled()
1075 }
1076
1077 pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1078 self.handler.replace_text_in_range(None, input, window, cx);
1079 }
1080
1081 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
1082 let selection = self.handler.selected_text_range(true, window, cx)?;
1083 self.handler.bounds_for_range(
1084 if selection.reversed {
1085 selection.range.start..selection.range.start
1086 } else {
1087 selection.range.end..selection.range.end
1088 },
1089 window,
1090 cx,
1091 )
1092 }
1093
1094 #[allow(unused)]
1095 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
1096 self.cx
1097 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
1098 .ok()
1099 .flatten()
1100 }
1101
1102 #[allow(dead_code)]
1103 pub(crate) fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
1104 self.handler.accepts_text_input(window, cx)
1105 }
1106}
1107
1108/// A struct representing a selection in a text buffer, in UTF16 characters.
1109/// This is different from a range because the head may be before the tail.
1110#[derive(Debug)]
1111pub struct UTF16Selection {
1112 /// The range of text in the document this selection corresponds to
1113 /// in UTF16 characters.
1114 pub range: Range<usize>,
1115 /// Whether the head of this selection is at the start (true), or end (false)
1116 /// of the range
1117 pub reversed: bool,
1118}
1119
1120/// Zed's interface for handling text input from the platform's IME system
1121/// This is currently a 1:1 exposure of the NSTextInputClient API:
1122///
1123/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
1124pub trait InputHandler: 'static {
1125 /// Get the range of the user's currently selected text, if any
1126 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
1127 ///
1128 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1129 fn selected_text_range(
1130 &mut self,
1131 ignore_disabled_input: bool,
1132 window: &mut Window,
1133 cx: &mut App,
1134 ) -> Option<UTF16Selection>;
1135
1136 /// Get the range of the currently marked text, if any
1137 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
1138 ///
1139 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1140 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
1141
1142 /// Get the text for the given document range in UTF-16 characters
1143 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
1144 ///
1145 /// range_utf16 is in terms of UTF-16 characters
1146 fn text_for_range(
1147 &mut self,
1148 range_utf16: Range<usize>,
1149 adjusted_range: &mut Option<Range<usize>>,
1150 window: &mut Window,
1151 cx: &mut App,
1152 ) -> Option<String>;
1153
1154 /// Replace the text in the given document range with the given text
1155 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
1156 ///
1157 /// replacement_range is in terms of UTF-16 characters
1158 fn replace_text_in_range(
1159 &mut self,
1160 replacement_range: Option<Range<usize>>,
1161 text: &str,
1162 window: &mut Window,
1163 cx: &mut App,
1164 );
1165
1166 /// Replace the text in the given document range with the given text,
1167 /// and mark the given text as part of an IME 'composing' state
1168 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
1169 ///
1170 /// range_utf16 is in terms of UTF-16 characters
1171 /// new_selected_range is in terms of UTF-16 characters
1172 fn replace_and_mark_text_in_range(
1173 &mut self,
1174 range_utf16: Option<Range<usize>>,
1175 new_text: &str,
1176 new_selected_range: Option<Range<usize>>,
1177 window: &mut Window,
1178 cx: &mut App,
1179 );
1180
1181 /// Remove the IME 'composing' state from the document
1182 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
1183 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
1184
1185 /// Get the bounds of the given document range in screen coordinates
1186 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
1187 ///
1188 /// This is used for positioning the IME candidate window
1189 fn bounds_for_range(
1190 &mut self,
1191 range_utf16: Range<usize>,
1192 window: &mut Window,
1193 cx: &mut App,
1194 ) -> Option<Bounds<Pixels>>;
1195
1196 /// Get the character offset for the given point in terms of UTF16 characters
1197 ///
1198 /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
1199 fn character_index_for_point(
1200 &mut self,
1201 point: Point<Pixels>,
1202 window: &mut Window,
1203 cx: &mut App,
1204 ) -> Option<usize>;
1205
1206 /// Allows a given input context to opt into getting raw key repeats instead of
1207 /// sending these to the platform.
1208 /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1209 /// (which is how iTerm does it) but it doesn't seem to work for me.
1210 #[allow(dead_code)]
1211 fn apple_press_and_hold_enabled(&mut self) -> bool {
1212 true
1213 }
1214
1215 /// Returns whether this handler is accepting text input to be inserted.
1216 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1217 true
1218 }
1219}
1220
1221/// The variables that can be configured when creating a new window
1222#[derive(Debug)]
1223pub struct WindowOptions {
1224 /// Specifies the state and bounds of the window in screen coordinates.
1225 /// - `None`: Inherit the bounds.
1226 /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1227 pub window_bounds: Option<WindowBounds>,
1228
1229 /// The titlebar configuration of the window
1230 pub titlebar: Option<TitlebarOptions>,
1231
1232 /// Whether the window should be focused when created
1233 pub focus: bool,
1234
1235 /// Whether the window should be shown when created
1236 pub show: bool,
1237
1238 /// The kind of window to create
1239 pub kind: WindowKind,
1240
1241 /// Whether the window should be movable by the user
1242 pub is_movable: bool,
1243
1244 /// Whether the window should be resizable by the user
1245 pub is_resizable: bool,
1246
1247 /// Whether the window should be minimized by the user
1248 pub is_minimizable: bool,
1249
1250 /// The display to create the window on, if this is None,
1251 /// the window will be created on the main display
1252 pub display_id: Option<DisplayId>,
1253
1254 /// The appearance of the window background.
1255 pub window_background: WindowBackgroundAppearance,
1256
1257 /// Application identifier of the window. Can by used by desktop environments to group applications together.
1258 pub app_id: Option<String>,
1259
1260 /// Window minimum size
1261 pub window_min_size: Option<Size<Pixels>>,
1262
1263 /// Whether to use client or server side decorations. Wayland only
1264 /// Note that this may be ignored.
1265 pub window_decorations: Option<WindowDecorations>,
1266
1267 /// Tab group name, allows opening the window as a native tab on macOS 10.12+. Windows with the same tabbing identifier will be grouped together.
1268 pub tabbing_identifier: Option<String>,
1269}
1270
1271/// The variables that can be configured when creating a new window
1272#[derive(Debug)]
1273#[cfg_attr(
1274 all(
1275 any(target_os = "linux", target_os = "freebsd"),
1276 not(any(feature = "x11", feature = "wayland"))
1277 ),
1278 allow(dead_code)
1279)]
1280pub(crate) struct WindowParams {
1281 pub bounds: Bounds<Pixels>,
1282
1283 /// The titlebar configuration of the window
1284 #[cfg_attr(feature = "wayland", allow(dead_code))]
1285 pub titlebar: Option<TitlebarOptions>,
1286
1287 /// The kind of window to create
1288 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1289 pub kind: WindowKind,
1290
1291 /// Whether the window should be movable by the user
1292 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1293 pub is_movable: bool,
1294
1295 /// Whether the window should be resizable by the user
1296 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1297 pub is_resizable: bool,
1298
1299 /// Whether the window should be minimized by the user
1300 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1301 pub is_minimizable: bool,
1302
1303 #[cfg_attr(
1304 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1305 allow(dead_code)
1306 )]
1307 pub focus: bool,
1308
1309 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1310 pub show: bool,
1311
1312 #[cfg_attr(feature = "wayland", allow(dead_code))]
1313 pub display_id: Option<DisplayId>,
1314
1315 pub window_min_size: Option<Size<Pixels>>,
1316 #[cfg(target_os = "macos")]
1317 pub tabbing_identifier: Option<String>,
1318}
1319
1320/// Represents the status of how a window should be opened.
1321#[derive(Debug, Copy, Clone, PartialEq)]
1322pub enum WindowBounds {
1323 /// Indicates that the window should open in a windowed state with the given bounds.
1324 Windowed(Bounds<Pixels>),
1325 /// Indicates that the window should open in a maximized state.
1326 /// The bounds provided here represent the restore size of the window.
1327 Maximized(Bounds<Pixels>),
1328 /// Indicates that the window should open in fullscreen mode.
1329 /// The bounds provided here represent the restore size of the window.
1330 Fullscreen(Bounds<Pixels>),
1331}
1332
1333impl Default for WindowBounds {
1334 fn default() -> Self {
1335 WindowBounds::Windowed(Bounds::default())
1336 }
1337}
1338
1339impl WindowBounds {
1340 /// Retrieve the inner bounds
1341 pub fn get_bounds(&self) -> Bounds<Pixels> {
1342 match self {
1343 WindowBounds::Windowed(bounds) => *bounds,
1344 WindowBounds::Maximized(bounds) => *bounds,
1345 WindowBounds::Fullscreen(bounds) => *bounds,
1346 }
1347 }
1348
1349 /// Creates a new window bounds that centers the window on the screen.
1350 pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
1351 WindowBounds::Windowed(Bounds::centered(None, size, cx))
1352 }
1353}
1354
1355impl Default for WindowOptions {
1356 fn default() -> Self {
1357 Self {
1358 window_bounds: None,
1359 titlebar: Some(TitlebarOptions {
1360 title: Default::default(),
1361 appears_transparent: Default::default(),
1362 traffic_light_position: Default::default(),
1363 }),
1364 focus: true,
1365 show: true,
1366 kind: WindowKind::Normal,
1367 is_movable: true,
1368 is_resizable: true,
1369 is_minimizable: true,
1370 display_id: None,
1371 window_background: WindowBackgroundAppearance::default(),
1372 app_id: None,
1373 window_min_size: None,
1374 window_decorations: None,
1375 tabbing_identifier: None,
1376 }
1377 }
1378}
1379
1380/// The options that can be configured for a window's titlebar
1381#[derive(Debug, Default)]
1382pub struct TitlebarOptions {
1383 /// The initial title of the window
1384 pub title: Option<SharedString>,
1385
1386 /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
1387 /// Refer to [`WindowOptions::window_decorations`] on Linux
1388 pub appears_transparent: bool,
1389
1390 /// The position of the macOS traffic light buttons
1391 pub traffic_light_position: Option<Point<Pixels>>,
1392}
1393
1394/// The kind of window to create
1395#[derive(Clone, Debug, PartialEq, Eq)]
1396pub enum WindowKind {
1397 /// A normal application window
1398 Normal,
1399
1400 /// A window that appears above all other windows, usually used for alerts or popups
1401 /// use sparingly!
1402 PopUp,
1403
1404 /// A floating window that appears on top of its parent window
1405 Floating,
1406
1407 /// A Wayland LayerShell window, used to draw overlays or backgrounds for applications such as
1408 /// docks, notifications or wallpapers.
1409 #[cfg(all(target_os = "linux", feature = "wayland"))]
1410 LayerShell(layer_shell::LayerShellOptions),
1411
1412 /// A window that appears on top of its parent window and blocks interaction with it
1413 /// until the modal window is closed
1414 Dialog,
1415}
1416
1417/// The appearance of the window, as defined by the operating system.
1418///
1419/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
1420/// values.
1421#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1422pub enum WindowAppearance {
1423 /// A light appearance.
1424 ///
1425 /// On macOS, this corresponds to the `aqua` appearance.
1426 #[default]
1427 Light,
1428
1429 /// A light appearance with vibrant colors.
1430 ///
1431 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
1432 VibrantLight,
1433
1434 /// A dark appearance.
1435 ///
1436 /// On macOS, this corresponds to the `darkAqua` appearance.
1437 Dark,
1438
1439 /// A dark appearance with vibrant colors.
1440 ///
1441 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
1442 VibrantDark,
1443}
1444
1445/// The appearance of the background of the window itself, when there is
1446/// no content or the content is transparent.
1447#[derive(Copy, Clone, Debug, Default, PartialEq)]
1448pub enum WindowBackgroundAppearance {
1449 /// Opaque.
1450 ///
1451 /// This lets the window manager know that content behind this
1452 /// window does not need to be drawn.
1453 ///
1454 /// Actual color depends on the system and themes should define a fully
1455 /// opaque background color instead.
1456 #[default]
1457 Opaque,
1458 /// Plain alpha transparency.
1459 Transparent,
1460 /// Transparency, but the contents behind the window are blurred.
1461 ///
1462 /// Not always supported.
1463 Blurred,
1464 /// The Mica backdrop material, supported on Windows 11.
1465 MicaBackdrop,
1466 /// The Mica Alt backdrop material, supported on Windows 11.
1467 MicaAltBackdrop,
1468}
1469
1470/// The text rendering mode to use for drawing glyphs.
1471#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1472pub enum TextRenderingMode {
1473 /// Use the platform's default text rendering mode.
1474 #[default]
1475 PlatformDefault,
1476 /// Use subpixel (ClearType-style) text rendering.
1477 Subpixel,
1478 /// Use grayscale text rendering.
1479 Grayscale,
1480}
1481
1482/// The options that can be configured for a file dialog prompt
1483#[derive(Clone, Debug)]
1484pub struct PathPromptOptions {
1485 /// Should the prompt allow files to be selected?
1486 pub files: bool,
1487 /// Should the prompt allow directories to be selected?
1488 pub directories: bool,
1489 /// Should the prompt allow multiple files to be selected?
1490 pub multiple: bool,
1491 /// The prompt to show to a user when selecting a path
1492 pub prompt: Option<SharedString>,
1493}
1494
1495/// What kind of prompt styling to show
1496#[derive(Copy, Clone, Debug, PartialEq)]
1497pub enum PromptLevel {
1498 /// A prompt that is shown when the user should be notified of something
1499 Info,
1500
1501 /// A prompt that is shown when the user needs to be warned of a potential problem
1502 Warning,
1503
1504 /// A prompt that is shown when a critical problem has occurred
1505 Critical,
1506}
1507
1508/// Prompt Button
1509#[derive(Clone, Debug, PartialEq)]
1510pub enum PromptButton {
1511 /// Ok button
1512 Ok(SharedString),
1513 /// Cancel button
1514 Cancel(SharedString),
1515 /// Other button
1516 Other(SharedString),
1517}
1518
1519impl PromptButton {
1520 /// Create a button with label
1521 pub fn new(label: impl Into<SharedString>) -> Self {
1522 PromptButton::Other(label.into())
1523 }
1524
1525 /// Create an Ok button
1526 pub fn ok(label: impl Into<SharedString>) -> Self {
1527 PromptButton::Ok(label.into())
1528 }
1529
1530 /// Create a Cancel button
1531 pub fn cancel(label: impl Into<SharedString>) -> Self {
1532 PromptButton::Cancel(label.into())
1533 }
1534
1535 #[allow(dead_code)]
1536 pub(crate) fn is_cancel(&self) -> bool {
1537 matches!(self, PromptButton::Cancel(_))
1538 }
1539
1540 /// Returns the label of the button
1541 pub fn label(&self) -> &SharedString {
1542 match self {
1543 PromptButton::Ok(label) => label,
1544 PromptButton::Cancel(label) => label,
1545 PromptButton::Other(label) => label,
1546 }
1547 }
1548}
1549
1550impl From<&str> for PromptButton {
1551 fn from(value: &str) -> Self {
1552 match value.to_lowercase().as_str() {
1553 "ok" => PromptButton::Ok("Ok".into()),
1554 "cancel" => PromptButton::Cancel("Cancel".into()),
1555 _ => PromptButton::Other(SharedString::from(value.to_owned())),
1556 }
1557 }
1558}
1559
1560/// The style of the cursor (pointer)
1561#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1562pub enum CursorStyle {
1563 /// The default cursor
1564 #[default]
1565 Arrow,
1566
1567 /// A text input cursor
1568 /// corresponds to the CSS cursor value `text`
1569 IBeam,
1570
1571 /// A crosshair cursor
1572 /// corresponds to the CSS cursor value `crosshair`
1573 Crosshair,
1574
1575 /// A closed hand cursor
1576 /// corresponds to the CSS cursor value `grabbing`
1577 ClosedHand,
1578
1579 /// An open hand cursor
1580 /// corresponds to the CSS cursor value `grab`
1581 OpenHand,
1582
1583 /// A pointing hand cursor
1584 /// corresponds to the CSS cursor value `pointer`
1585 PointingHand,
1586
1587 /// A resize left cursor
1588 /// corresponds to the CSS cursor value `w-resize`
1589 ResizeLeft,
1590
1591 /// A resize right cursor
1592 /// corresponds to the CSS cursor value `e-resize`
1593 ResizeRight,
1594
1595 /// A resize cursor to the left and right
1596 /// corresponds to the CSS cursor value `ew-resize`
1597 ResizeLeftRight,
1598
1599 /// A resize up cursor
1600 /// corresponds to the CSS cursor value `n-resize`
1601 ResizeUp,
1602
1603 /// A resize down cursor
1604 /// corresponds to the CSS cursor value `s-resize`
1605 ResizeDown,
1606
1607 /// A resize cursor directing up and down
1608 /// corresponds to the CSS cursor value `ns-resize`
1609 ResizeUpDown,
1610
1611 /// A resize cursor directing up-left and down-right
1612 /// corresponds to the CSS cursor value `nesw-resize`
1613 ResizeUpLeftDownRight,
1614
1615 /// A resize cursor directing up-right and down-left
1616 /// corresponds to the CSS cursor value `nwse-resize`
1617 ResizeUpRightDownLeft,
1618
1619 /// A cursor indicating that the item/column can be resized horizontally.
1620 /// corresponds to the CSS cursor value `col-resize`
1621 ResizeColumn,
1622
1623 /// A cursor indicating that the item/row can be resized vertically.
1624 /// corresponds to the CSS cursor value `row-resize`
1625 ResizeRow,
1626
1627 /// A text input cursor for vertical layout
1628 /// corresponds to the CSS cursor value `vertical-text`
1629 IBeamCursorForVerticalLayout,
1630
1631 /// A cursor indicating that the operation is not allowed
1632 /// corresponds to the CSS cursor value `not-allowed`
1633 OperationNotAllowed,
1634
1635 /// A cursor indicating that the operation will result in a link
1636 /// corresponds to the CSS cursor value `alias`
1637 DragLink,
1638
1639 /// A cursor indicating that the operation will result in a copy
1640 /// corresponds to the CSS cursor value `copy`
1641 DragCopy,
1642
1643 /// A cursor indicating that the operation will result in a context menu
1644 /// corresponds to the CSS cursor value `context-menu`
1645 ContextualMenu,
1646
1647 /// Hide the cursor
1648 None,
1649}
1650
1651/// A clipboard item that should be copied to the clipboard
1652#[derive(Clone, Debug, Eq, PartialEq)]
1653pub struct ClipboardItem {
1654 entries: Vec<ClipboardEntry>,
1655}
1656
1657/// Either a ClipboardString or a ClipboardImage
1658#[derive(Clone, Debug, Eq, PartialEq)]
1659pub enum ClipboardEntry {
1660 /// A string entry
1661 String(ClipboardString),
1662 /// An image entry
1663 Image(Image),
1664 /// A file entry
1665 ExternalPaths(crate::ExternalPaths),
1666}
1667
1668impl ClipboardItem {
1669 /// Create a new ClipboardItem::String with no associated metadata
1670 pub fn new_string(text: String) -> Self {
1671 Self {
1672 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1673 }
1674 }
1675
1676 /// Create a new ClipboardItem::String with the given text and associated metadata
1677 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1678 Self {
1679 entries: vec![ClipboardEntry::String(ClipboardString {
1680 text,
1681 metadata: Some(metadata),
1682 })],
1683 }
1684 }
1685
1686 /// Create a new ClipboardItem::String with the given text and associated metadata
1687 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1688 Self {
1689 entries: vec![ClipboardEntry::String(
1690 ClipboardString::new(text).with_json_metadata(metadata),
1691 )],
1692 }
1693 }
1694
1695 /// Create a new ClipboardItem::Image with the given image with no associated metadata
1696 pub fn new_image(image: &Image) -> Self {
1697 Self {
1698 entries: vec![ClipboardEntry::Image(image.clone())],
1699 }
1700 }
1701
1702 /// Concatenates together all the ClipboardString entries in the item.
1703 /// Returns None if there were no ClipboardString entries.
1704 pub fn text(&self) -> Option<String> {
1705 let mut answer = String::new();
1706
1707 for entry in self.entries.iter() {
1708 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1709 answer.push_str(text);
1710 }
1711 }
1712
1713 if answer.is_empty() {
1714 for entry in self.entries.iter() {
1715 if let ClipboardEntry::ExternalPaths(paths) = entry {
1716 for path in &paths.0 {
1717 use std::fmt::Write as _;
1718 _ = write!(answer, "{}", path.display());
1719 }
1720 }
1721 }
1722 }
1723
1724 if !answer.is_empty() {
1725 Some(answer)
1726 } else {
1727 None
1728 }
1729 }
1730
1731 /// If this item is one ClipboardEntry::String, returns its metadata.
1732 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1733 pub fn metadata(&self) -> Option<&String> {
1734 match self.entries().first() {
1735 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1736 clipboard_string.metadata.as_ref()
1737 }
1738 _ => None,
1739 }
1740 }
1741
1742 /// Get the item's entries
1743 pub fn entries(&self) -> &[ClipboardEntry] {
1744 &self.entries
1745 }
1746
1747 /// Get owned versions of the item's entries
1748 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1749 self.entries.into_iter()
1750 }
1751}
1752
1753impl From<ClipboardString> for ClipboardEntry {
1754 fn from(value: ClipboardString) -> Self {
1755 Self::String(value)
1756 }
1757}
1758
1759impl From<String> for ClipboardEntry {
1760 fn from(value: String) -> Self {
1761 Self::from(ClipboardString::from(value))
1762 }
1763}
1764
1765impl From<Image> for ClipboardEntry {
1766 fn from(value: Image) -> Self {
1767 Self::Image(value)
1768 }
1769}
1770
1771impl From<ClipboardEntry> for ClipboardItem {
1772 fn from(value: ClipboardEntry) -> Self {
1773 Self {
1774 entries: vec![value],
1775 }
1776 }
1777}
1778
1779impl From<String> for ClipboardItem {
1780 fn from(value: String) -> Self {
1781 Self::from(ClipboardEntry::from(value))
1782 }
1783}
1784
1785impl From<Image> for ClipboardItem {
1786 fn from(value: Image) -> Self {
1787 Self::from(ClipboardEntry::from(value))
1788 }
1789}
1790
1791/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1792#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1793pub enum ImageFormat {
1794 // Sorted from most to least likely to be pasted into an editor,
1795 // which matters when we iterate through them trying to see if
1796 // clipboard content matches them.
1797 /// .png
1798 Png,
1799 /// .jpeg or .jpg
1800 Jpeg,
1801 /// .webp
1802 Webp,
1803 /// .gif
1804 Gif,
1805 /// .svg
1806 Svg,
1807 /// .bmp
1808 Bmp,
1809 /// .tif or .tiff
1810 Tiff,
1811 /// .ico
1812 Ico,
1813}
1814
1815impl ImageFormat {
1816 /// Returns the mime type for the ImageFormat
1817 pub const fn mime_type(self) -> &'static str {
1818 match self {
1819 ImageFormat::Png => "image/png",
1820 ImageFormat::Jpeg => "image/jpeg",
1821 ImageFormat::Webp => "image/webp",
1822 ImageFormat::Gif => "image/gif",
1823 ImageFormat::Svg => "image/svg+xml",
1824 ImageFormat::Bmp => "image/bmp",
1825 ImageFormat::Tiff => "image/tiff",
1826 ImageFormat::Ico => "image/ico",
1827 }
1828 }
1829
1830 /// Returns the ImageFormat for the given mime type
1831 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
1832 match mime_type {
1833 "image/png" => Some(Self::Png),
1834 "image/jpeg" | "image/jpg" => Some(Self::Jpeg),
1835 "image/webp" => Some(Self::Webp),
1836 "image/gif" => Some(Self::Gif),
1837 "image/svg+xml" => Some(Self::Svg),
1838 "image/bmp" => Some(Self::Bmp),
1839 "image/tiff" | "image/tif" => Some(Self::Tiff),
1840 "image/ico" => Some(Self::Ico),
1841 _ => None,
1842 }
1843 }
1844}
1845
1846/// An image, with a format and certain bytes
1847#[derive(Clone, Debug, PartialEq, Eq)]
1848pub struct Image {
1849 /// The image format the bytes represent (e.g. PNG)
1850 pub format: ImageFormat,
1851 /// The raw image bytes
1852 pub bytes: Vec<u8>,
1853 /// The unique ID for the image
1854 id: u64,
1855}
1856
1857impl Hash for Image {
1858 fn hash<H: Hasher>(&self, state: &mut H) {
1859 state.write_u64(self.id);
1860 }
1861}
1862
1863impl Image {
1864 /// An empty image containing no data
1865 pub fn empty() -> Self {
1866 Self::from_bytes(ImageFormat::Png, Vec::new())
1867 }
1868
1869 /// Create an image from a format and bytes
1870 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
1871 Self {
1872 id: hash(&bytes),
1873 format,
1874 bytes,
1875 }
1876 }
1877
1878 /// Get this image's ID
1879 pub fn id(&self) -> u64 {
1880 self.id
1881 }
1882
1883 /// Use the GPUI `use_asset` API to make this image renderable
1884 pub fn use_render_image(
1885 self: Arc<Self>,
1886 window: &mut Window,
1887 cx: &mut App,
1888 ) -> Option<Arc<RenderImage>> {
1889 ImageSource::Image(self)
1890 .use_data(None, window, cx)
1891 .and_then(|result| result.ok())
1892 }
1893
1894 /// Use the GPUI `get_asset` API to make this image renderable
1895 pub fn get_render_image(
1896 self: Arc<Self>,
1897 window: &mut Window,
1898 cx: &mut App,
1899 ) -> Option<Arc<RenderImage>> {
1900 ImageSource::Image(self)
1901 .get_data(None, window, cx)
1902 .and_then(|result| result.ok())
1903 }
1904
1905 /// Use the GPUI `remove_asset` API to drop this image, if possible.
1906 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
1907 ImageSource::Image(self).remove_asset(cx);
1908 }
1909
1910 /// Convert the clipboard image to an `ImageData` object.
1911 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1912 fn frames_for_image(
1913 bytes: &[u8],
1914 format: image::ImageFormat,
1915 ) -> Result<SmallVec<[Frame; 1]>> {
1916 let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1917
1918 // Convert from RGBA to BGRA.
1919 for pixel in data.chunks_exact_mut(4) {
1920 pixel.swap(0, 2);
1921 }
1922
1923 Ok(SmallVec::from_elem(Frame::new(data), 1))
1924 }
1925
1926 let frames = match self.format {
1927 ImageFormat::Gif => {
1928 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1929 let mut frames = SmallVec::new();
1930
1931 for frame in decoder.into_frames() {
1932 let mut frame = frame?;
1933 // Convert from RGBA to BGRA.
1934 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1935 pixel.swap(0, 2);
1936 }
1937 frames.push(frame);
1938 }
1939
1940 frames
1941 }
1942 ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1943 ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1944 ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1945 ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1946 ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1947 ImageFormat::Ico => frames_for_image(&self.bytes, image::ImageFormat::Ico)?,
1948 ImageFormat::Svg => {
1949 return svg_renderer
1950 .render_single_frame(&self.bytes, 1.0, false)
1951 .map_err(Into::into);
1952 }
1953 };
1954
1955 Ok(Arc::new(RenderImage::new(frames)))
1956 }
1957
1958 /// Get the format of the clipboard image
1959 pub fn format(&self) -> ImageFormat {
1960 self.format
1961 }
1962
1963 /// Get the raw bytes of the clipboard image
1964 pub fn bytes(&self) -> &[u8] {
1965 self.bytes.as_slice()
1966 }
1967}
1968
1969/// A clipboard item that should be copied to the clipboard
1970#[derive(Clone, Debug, Eq, PartialEq)]
1971pub struct ClipboardString {
1972 pub(crate) text: String,
1973 pub(crate) metadata: Option<String>,
1974}
1975
1976impl ClipboardString {
1977 /// Create a new clipboard string with the given text
1978 pub fn new(text: String) -> Self {
1979 Self {
1980 text,
1981 metadata: None,
1982 }
1983 }
1984
1985 /// Return a new clipboard item with the metadata replaced by the given metadata,
1986 /// after serializing it as JSON.
1987 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1988 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1989 self
1990 }
1991
1992 /// Get the text of the clipboard string
1993 pub fn text(&self) -> &String {
1994 &self.text
1995 }
1996
1997 /// Get the owned text of the clipboard string
1998 pub fn into_text(self) -> String {
1999 self.text
2000 }
2001
2002 /// Get the metadata of the clipboard string, formatted as JSON
2003 pub fn metadata_json<T>(&self) -> Option<T>
2004 where
2005 T: for<'a> Deserialize<'a>,
2006 {
2007 self.metadata
2008 .as_ref()
2009 .and_then(|m| serde_json::from_str(m).ok())
2010 }
2011
2012 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2013 pub(crate) fn text_hash(text: &str) -> u64 {
2014 let mut hasher = SeaHasher::new();
2015 text.hash(&mut hasher);
2016 hasher.finish()
2017 }
2018}
2019
2020impl From<String> for ClipboardString {
2021 fn from(value: String) -> Self {
2022 Self {
2023 text: value,
2024 metadata: None,
2025 }
2026 }
2027}