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