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/// This type is public so that our test macro can generate and use it, but it should not
615/// be considered part of our public API.
616#[doc(hidden)]
617pub trait PlatformDispatcher: Send + Sync {
618 fn get_all_timings(&self) -> Vec<ThreadTaskTimings>;
619 fn get_current_thread_timings(&self) -> Vec<TaskTiming>;
620 fn is_main_thread(&self) -> bool;
621 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
622 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
623 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
624 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
625
626 fn now(&self) -> Instant {
627 Instant::now()
628 }
629
630 #[cfg(any(test, feature = "test-support"))]
631 fn as_test(&self) -> Option<&TestDispatcher> {
632 None
633 }
634}
635
636pub(crate) trait PlatformTextSystem: Send + Sync {
637 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
638 fn all_font_names(&self) -> Vec<String>;
639 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
640 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
641 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
642 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
643 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
644 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
645 fn rasterize_glyph(
646 &self,
647 params: &RenderGlyphParams,
648 raster_bounds: Bounds<DevicePixels>,
649 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
650 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
651 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
652 -> TextRenderingMode;
653}
654
655pub(crate) struct NoopTextSystem;
656
657impl NoopTextSystem {
658 #[allow(dead_code)]
659 pub fn new() -> Self {
660 Self
661 }
662}
663
664impl PlatformTextSystem for NoopTextSystem {
665 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
666 Ok(())
667 }
668
669 fn all_font_names(&self) -> Vec<String> {
670 Vec::new()
671 }
672
673 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
674 Ok(FontId(1))
675 }
676
677 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
678 FontMetrics {
679 units_per_em: 1000,
680 ascent: 1025.0,
681 descent: -275.0,
682 line_gap: 0.0,
683 underline_position: -95.0,
684 underline_thickness: 60.0,
685 cap_height: 698.0,
686 x_height: 516.0,
687 bounding_box: Bounds {
688 origin: Point {
689 x: -260.0,
690 y: -245.0,
691 },
692 size: Size {
693 width: 1501.0,
694 height: 1364.0,
695 },
696 },
697 }
698 }
699
700 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
701 Ok(Bounds {
702 origin: Point { x: 54.0, y: 0.0 },
703 size: size(392.0, 528.0),
704 })
705 }
706
707 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
708 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
709 }
710
711 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
712 Some(GlyphId(ch.len_utf16() as u32))
713 }
714
715 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
716 Ok(Default::default())
717 }
718
719 fn rasterize_glyph(
720 &self,
721 _params: &RenderGlyphParams,
722 raster_bounds: Bounds<DevicePixels>,
723 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
724 Ok((raster_bounds.size, Vec::new()))
725 }
726
727 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
728 let mut position = px(0.);
729 let metrics = self.font_metrics(FontId(0));
730 let em_width = font_size
731 * self
732 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
733 .unwrap()
734 .width
735 / metrics.units_per_em as f32;
736 let mut glyphs = Vec::new();
737 for (ix, c) in text.char_indices() {
738 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
739 glyphs.push(ShapedGlyph {
740 id: glyph,
741 position: point(position, px(0.)),
742 index: ix,
743 is_emoji: glyph.0 == 2,
744 });
745 if glyph.0 == 2 {
746 position += em_width * 2.0;
747 } else {
748 position += em_width;
749 }
750 } else {
751 position += em_width
752 }
753 }
754 let mut runs = Vec::default();
755 if !glyphs.is_empty() {
756 runs.push(ShapedRun {
757 font_id: FontId(0),
758 glyphs,
759 });
760 } else {
761 position = px(0.);
762 }
763
764 LineLayout {
765 font_size,
766 width: position,
767 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
768 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
769 runs,
770 len: text.len(),
771 }
772 }
773
774 fn recommended_rendering_mode(
775 &self,
776 _font_id: FontId,
777 _font_size: Pixels,
778 ) -> TextRenderingMode {
779 TextRenderingMode::Grayscale
780 }
781}
782
783// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.cpp
784// Copyright (c) Microsoft Corporation.
785// Licensed under the MIT license.
786#[allow(dead_code)]
787pub(crate) fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
788 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
789 [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], // gamma = 1.0
790 [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], // gamma = 1.1
791 [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], // gamma = 1.2
792 [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], // gamma = 1.3
793 [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], // gamma = 1.4
794 [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], // gamma = 1.5
795 [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], // gamma = 1.6
796 [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], // gamma = 1.7
797 [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], // gamma = 1.8
798 [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], // gamma = 1.9
799 [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], // gamma = 2.0
800 [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], // gamma = 2.1
801 [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], // gamma = 2.2
802 ];
803
804 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
805 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
806
807 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
808 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
809
810 [
811 ratios[0] * NORM13,
812 ratios[1] * NORM24,
813 ratios[2] * NORM13,
814 ratios[3] * NORM24,
815 ]
816}
817
818#[derive(PartialEq, Eq, Hash, Clone)]
819pub(crate) enum AtlasKey {
820 Glyph(RenderGlyphParams),
821 Svg(RenderSvgParams),
822 Image(RenderImageParams),
823}
824
825impl AtlasKey {
826 #[cfg_attr(
827 all(
828 any(target_os = "linux", target_os = "freebsd"),
829 not(any(feature = "x11", feature = "wayland"))
830 ),
831 allow(dead_code)
832 )]
833 pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
834 match self {
835 AtlasKey::Glyph(params) => {
836 if params.is_emoji {
837 AtlasTextureKind::Polychrome
838 } else if params.subpixel_rendering {
839 AtlasTextureKind::Subpixel
840 } else {
841 AtlasTextureKind::Monochrome
842 }
843 }
844 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
845 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
846 }
847 }
848}
849
850impl From<RenderGlyphParams> for AtlasKey {
851 fn from(params: RenderGlyphParams) -> Self {
852 Self::Glyph(params)
853 }
854}
855
856impl From<RenderSvgParams> for AtlasKey {
857 fn from(params: RenderSvgParams) -> Self {
858 Self::Svg(params)
859 }
860}
861
862impl From<RenderImageParams> for AtlasKey {
863 fn from(params: RenderImageParams) -> Self {
864 Self::Image(params)
865 }
866}
867
868pub(crate) trait PlatformAtlas: Send + Sync {
869 fn get_or_insert_with<'a>(
870 &self,
871 key: &AtlasKey,
872 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
873 ) -> Result<Option<AtlasTile>>;
874 fn remove(&self, key: &AtlasKey);
875}
876
877struct AtlasTextureList<T> {
878 textures: Vec<Option<T>>,
879 free_list: Vec<usize>,
880}
881
882impl<T> Default for AtlasTextureList<T> {
883 fn default() -> Self {
884 Self {
885 textures: Vec::default(),
886 free_list: Vec::default(),
887 }
888 }
889}
890
891impl<T> ops::Index<usize> for AtlasTextureList<T> {
892 type Output = Option<T>;
893
894 fn index(&self, index: usize) -> &Self::Output {
895 &self.textures[index]
896 }
897}
898
899impl<T> AtlasTextureList<T> {
900 #[allow(unused)]
901 fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
902 self.free_list.clear();
903 self.textures.drain(..)
904 }
905
906 #[allow(dead_code)]
907 fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
908 self.textures.iter_mut().flatten()
909 }
910}
911
912#[derive(Clone, Debug, PartialEq, Eq)]
913#[repr(C)]
914pub(crate) struct AtlasTile {
915 pub(crate) texture_id: AtlasTextureId,
916 pub(crate) tile_id: TileId,
917 pub(crate) padding: u32,
918 pub(crate) bounds: Bounds<DevicePixels>,
919}
920
921#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
922#[repr(C)]
923pub(crate) struct AtlasTextureId {
924 // We use u32 instead of usize for Metal Shader Language compatibility
925 pub(crate) index: u32,
926 pub(crate) kind: AtlasTextureKind,
927}
928
929#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
930#[repr(C)]
931#[cfg_attr(
932 all(
933 any(target_os = "linux", target_os = "freebsd"),
934 not(any(feature = "x11", feature = "wayland"))
935 ),
936 allow(dead_code)
937)]
938pub(crate) enum AtlasTextureKind {
939 Monochrome = 0,
940 Polychrome = 1,
941 Subpixel = 2,
942}
943
944#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
945#[repr(C)]
946pub(crate) struct TileId(pub(crate) u32);
947
948impl From<etagere::AllocId> for TileId {
949 fn from(id: etagere::AllocId) -> Self {
950 Self(id.serialize())
951 }
952}
953
954impl From<TileId> for etagere::AllocId {
955 fn from(id: TileId) -> Self {
956 Self::deserialize(id.0)
957 }
958}
959
960pub(crate) struct PlatformInputHandler {
961 cx: AsyncWindowContext,
962 handler: Box<dyn InputHandler>,
963}
964
965#[cfg_attr(
966 all(
967 any(target_os = "linux", target_os = "freebsd"),
968 not(any(feature = "x11", feature = "wayland"))
969 ),
970 allow(dead_code)
971)]
972impl PlatformInputHandler {
973 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
974 Self { cx, handler }
975 }
976
977 fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
978 self.cx
979 .update(|window, cx| {
980 self.handler
981 .selected_text_range(ignore_disabled_input, window, cx)
982 })
983 .ok()
984 .flatten()
985 }
986
987 #[cfg_attr(target_os = "windows", allow(dead_code))]
988 fn marked_text_range(&mut self) -> Option<Range<usize>> {
989 self.cx
990 .update(|window, cx| self.handler.marked_text_range(window, cx))
991 .ok()
992 .flatten()
993 }
994
995 #[cfg_attr(
996 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
997 allow(dead_code)
998 )]
999 fn text_for_range(
1000 &mut self,
1001 range_utf16: Range<usize>,
1002 adjusted: &mut Option<Range<usize>>,
1003 ) -> Option<String> {
1004 self.cx
1005 .update(|window, cx| {
1006 self.handler
1007 .text_for_range(range_utf16, adjusted, window, cx)
1008 })
1009 .ok()
1010 .flatten()
1011 }
1012
1013 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
1014 self.cx
1015 .update(|window, cx| {
1016 self.handler
1017 .replace_text_in_range(replacement_range, text, window, cx);
1018 })
1019 .ok();
1020 }
1021
1022 pub fn replace_and_mark_text_in_range(
1023 &mut self,
1024 range_utf16: Option<Range<usize>>,
1025 new_text: &str,
1026 new_selected_range: Option<Range<usize>>,
1027 ) {
1028 self.cx
1029 .update(|window, cx| {
1030 self.handler.replace_and_mark_text_in_range(
1031 range_utf16,
1032 new_text,
1033 new_selected_range,
1034 window,
1035 cx,
1036 )
1037 })
1038 .ok();
1039 }
1040
1041 #[cfg_attr(target_os = "windows", allow(dead_code))]
1042 fn unmark_text(&mut self) {
1043 self.cx
1044 .update(|window, cx| self.handler.unmark_text(window, cx))
1045 .ok();
1046 }
1047
1048 fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
1049 self.cx
1050 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
1051 .ok()
1052 .flatten()
1053 }
1054
1055 #[allow(dead_code)]
1056 fn apple_press_and_hold_enabled(&mut self) -> bool {
1057 self.handler.apple_press_and_hold_enabled()
1058 }
1059
1060 pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1061 self.handler.replace_text_in_range(None, input, window, cx);
1062 }
1063
1064 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
1065 let selection = self.handler.selected_text_range(true, window, cx)?;
1066 self.handler.bounds_for_range(
1067 if selection.reversed {
1068 selection.range.start..selection.range.start
1069 } else {
1070 selection.range.end..selection.range.end
1071 },
1072 window,
1073 cx,
1074 )
1075 }
1076
1077 #[allow(unused)]
1078 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
1079 self.cx
1080 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
1081 .ok()
1082 .flatten()
1083 }
1084
1085 #[allow(dead_code)]
1086 pub(crate) fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
1087 self.handler.accepts_text_input(window, cx)
1088 }
1089}
1090
1091/// A struct representing a selection in a text buffer, in UTF16 characters.
1092/// This is different from a range because the head may be before the tail.
1093#[derive(Debug)]
1094pub struct UTF16Selection {
1095 /// The range of text in the document this selection corresponds to
1096 /// in UTF16 characters.
1097 pub range: Range<usize>,
1098 /// Whether the head of this selection is at the start (true), or end (false)
1099 /// of the range
1100 pub reversed: bool,
1101}
1102
1103/// Zed's interface for handling text input from the platform's IME system
1104/// This is currently a 1:1 exposure of the NSTextInputClient API:
1105///
1106/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
1107pub trait InputHandler: 'static {
1108 /// Get the range of the user's currently selected text, if any
1109 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
1110 ///
1111 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1112 fn selected_text_range(
1113 &mut self,
1114 ignore_disabled_input: bool,
1115 window: &mut Window,
1116 cx: &mut App,
1117 ) -> Option<UTF16Selection>;
1118
1119 /// Get the range of the currently marked text, if any
1120 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
1121 ///
1122 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1123 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
1124
1125 /// Get the text for the given document range in UTF-16 characters
1126 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
1127 ///
1128 /// range_utf16 is in terms of UTF-16 characters
1129 fn text_for_range(
1130 &mut self,
1131 range_utf16: Range<usize>,
1132 adjusted_range: &mut Option<Range<usize>>,
1133 window: &mut Window,
1134 cx: &mut App,
1135 ) -> Option<String>;
1136
1137 /// Replace the text in the given document range with the given text
1138 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
1139 ///
1140 /// replacement_range is in terms of UTF-16 characters
1141 fn replace_text_in_range(
1142 &mut self,
1143 replacement_range: Option<Range<usize>>,
1144 text: &str,
1145 window: &mut Window,
1146 cx: &mut App,
1147 );
1148
1149 /// Replace the text in the given document range with the given text,
1150 /// and mark the given text as part of an IME 'composing' state
1151 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
1152 ///
1153 /// range_utf16 is in terms of UTF-16 characters
1154 /// new_selected_range is in terms of UTF-16 characters
1155 fn replace_and_mark_text_in_range(
1156 &mut self,
1157 range_utf16: Option<Range<usize>>,
1158 new_text: &str,
1159 new_selected_range: Option<Range<usize>>,
1160 window: &mut Window,
1161 cx: &mut App,
1162 );
1163
1164 /// Remove the IME 'composing' state from the document
1165 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
1166 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
1167
1168 /// Get the bounds of the given document range in screen coordinates
1169 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
1170 ///
1171 /// This is used for positioning the IME candidate window
1172 fn bounds_for_range(
1173 &mut self,
1174 range_utf16: Range<usize>,
1175 window: &mut Window,
1176 cx: &mut App,
1177 ) -> Option<Bounds<Pixels>>;
1178
1179 /// Get the character offset for the given point in terms of UTF16 characters
1180 ///
1181 /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
1182 fn character_index_for_point(
1183 &mut self,
1184 point: Point<Pixels>,
1185 window: &mut Window,
1186 cx: &mut App,
1187 ) -> Option<usize>;
1188
1189 /// Allows a given input context to opt into getting raw key repeats instead of
1190 /// sending these to the platform.
1191 /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1192 /// (which is how iTerm does it) but it doesn't seem to work for me.
1193 #[allow(dead_code)]
1194 fn apple_press_and_hold_enabled(&mut self) -> bool {
1195 true
1196 }
1197
1198 /// Returns whether this handler is accepting text input to be inserted.
1199 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1200 true
1201 }
1202}
1203
1204/// The variables that can be configured when creating a new window
1205#[derive(Debug)]
1206pub struct WindowOptions {
1207 /// Specifies the state and bounds of the window in screen coordinates.
1208 /// - `None`: Inherit the bounds.
1209 /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1210 pub window_bounds: Option<WindowBounds>,
1211
1212 /// The titlebar configuration of the window
1213 pub titlebar: Option<TitlebarOptions>,
1214
1215 /// Whether the window should be focused when created
1216 pub focus: bool,
1217
1218 /// Whether the window should be shown when created
1219 pub show: bool,
1220
1221 /// The kind of window to create
1222 pub kind: WindowKind,
1223
1224 /// Whether the window should be movable by the user
1225 pub is_movable: bool,
1226
1227 /// Whether the window should be resizable by the user
1228 pub is_resizable: bool,
1229
1230 /// Whether the window should be minimized by the user
1231 pub is_minimizable: bool,
1232
1233 /// The display to create the window on, if this is None,
1234 /// the window will be created on the main display
1235 pub display_id: Option<DisplayId>,
1236
1237 /// The appearance of the window background.
1238 pub window_background: WindowBackgroundAppearance,
1239
1240 /// Application identifier of the window. Can by used by desktop environments to group applications together.
1241 pub app_id: Option<String>,
1242
1243 /// Window minimum size
1244 pub window_min_size: Option<Size<Pixels>>,
1245
1246 /// Whether to use client or server side decorations. Wayland only
1247 /// Note that this may be ignored.
1248 pub window_decorations: Option<WindowDecorations>,
1249
1250 /// 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.
1251 pub tabbing_identifier: Option<String>,
1252}
1253
1254/// The variables that can be configured when creating a new window
1255#[derive(Debug)]
1256#[cfg_attr(
1257 all(
1258 any(target_os = "linux", target_os = "freebsd"),
1259 not(any(feature = "x11", feature = "wayland"))
1260 ),
1261 allow(dead_code)
1262)]
1263pub(crate) struct WindowParams {
1264 pub bounds: Bounds<Pixels>,
1265
1266 /// The titlebar configuration of the window
1267 #[cfg_attr(feature = "wayland", allow(dead_code))]
1268 pub titlebar: Option<TitlebarOptions>,
1269
1270 /// The kind of window to create
1271 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1272 pub kind: WindowKind,
1273
1274 /// Whether the window should be movable by the user
1275 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1276 pub is_movable: bool,
1277
1278 /// Whether the window should be resizable by the user
1279 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1280 pub is_resizable: bool,
1281
1282 /// Whether the window should be minimized by the user
1283 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1284 pub is_minimizable: bool,
1285
1286 #[cfg_attr(
1287 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1288 allow(dead_code)
1289 )]
1290 pub focus: bool,
1291
1292 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1293 pub show: bool,
1294
1295 #[cfg_attr(feature = "wayland", allow(dead_code))]
1296 pub display_id: Option<DisplayId>,
1297
1298 pub window_min_size: Option<Size<Pixels>>,
1299 #[cfg(target_os = "macos")]
1300 pub tabbing_identifier: Option<String>,
1301}
1302
1303/// Represents the status of how a window should be opened.
1304#[derive(Debug, Copy, Clone, PartialEq)]
1305pub enum WindowBounds {
1306 /// Indicates that the window should open in a windowed state with the given bounds.
1307 Windowed(Bounds<Pixels>),
1308 /// Indicates that the window should open in a maximized state.
1309 /// The bounds provided here represent the restore size of the window.
1310 Maximized(Bounds<Pixels>),
1311 /// Indicates that the window should open in fullscreen mode.
1312 /// The bounds provided here represent the restore size of the window.
1313 Fullscreen(Bounds<Pixels>),
1314}
1315
1316impl Default for WindowBounds {
1317 fn default() -> Self {
1318 WindowBounds::Windowed(Bounds::default())
1319 }
1320}
1321
1322impl WindowBounds {
1323 /// Retrieve the inner bounds
1324 pub fn get_bounds(&self) -> Bounds<Pixels> {
1325 match self {
1326 WindowBounds::Windowed(bounds) => *bounds,
1327 WindowBounds::Maximized(bounds) => *bounds,
1328 WindowBounds::Fullscreen(bounds) => *bounds,
1329 }
1330 }
1331
1332 /// Creates a new window bounds that centers the window on the screen.
1333 pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
1334 WindowBounds::Windowed(Bounds::centered(None, size, cx))
1335 }
1336}
1337
1338impl Default for WindowOptions {
1339 fn default() -> Self {
1340 Self {
1341 window_bounds: None,
1342 titlebar: Some(TitlebarOptions {
1343 title: Default::default(),
1344 appears_transparent: Default::default(),
1345 traffic_light_position: Default::default(),
1346 }),
1347 focus: true,
1348 show: true,
1349 kind: WindowKind::Normal,
1350 is_movable: true,
1351 is_resizable: true,
1352 is_minimizable: true,
1353 display_id: None,
1354 window_background: WindowBackgroundAppearance::default(),
1355 app_id: None,
1356 window_min_size: None,
1357 window_decorations: None,
1358 tabbing_identifier: None,
1359 }
1360 }
1361}
1362
1363/// The options that can be configured for a window's titlebar
1364#[derive(Debug, Default)]
1365pub struct TitlebarOptions {
1366 /// The initial title of the window
1367 pub title: Option<SharedString>,
1368
1369 /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
1370 /// Refer to [`WindowOptions::window_decorations`] on Linux
1371 pub appears_transparent: bool,
1372
1373 /// The position of the macOS traffic light buttons
1374 pub traffic_light_position: Option<Point<Pixels>>,
1375}
1376
1377/// The kind of window to create
1378#[derive(Clone, Debug, PartialEq, Eq)]
1379pub enum WindowKind {
1380 /// A normal application window
1381 Normal,
1382
1383 /// A window that appears above all other windows, usually used for alerts or popups
1384 /// use sparingly!
1385 PopUp,
1386
1387 /// A floating window that appears on top of its parent window
1388 Floating,
1389
1390 /// A Wayland LayerShell window, used to draw overlays or backgrounds for applications such as
1391 /// docks, notifications or wallpapers.
1392 #[cfg(all(target_os = "linux", feature = "wayland"))]
1393 LayerShell(layer_shell::LayerShellOptions),
1394
1395 /// A window that appears on top of its parent window and blocks interaction with it
1396 /// until the modal window is closed
1397 Dialog,
1398}
1399
1400/// The appearance of the window, as defined by the operating system.
1401///
1402/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
1403/// values.
1404#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1405pub enum WindowAppearance {
1406 /// A light appearance.
1407 ///
1408 /// On macOS, this corresponds to the `aqua` appearance.
1409 #[default]
1410 Light,
1411
1412 /// A light appearance with vibrant colors.
1413 ///
1414 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
1415 VibrantLight,
1416
1417 /// A dark appearance.
1418 ///
1419 /// On macOS, this corresponds to the `darkAqua` appearance.
1420 Dark,
1421
1422 /// A dark appearance with vibrant colors.
1423 ///
1424 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
1425 VibrantDark,
1426}
1427
1428/// The appearance of the background of the window itself, when there is
1429/// no content or the content is transparent.
1430#[derive(Copy, Clone, Debug, Default, PartialEq)]
1431pub enum WindowBackgroundAppearance {
1432 /// Opaque.
1433 ///
1434 /// This lets the window manager know that content behind this
1435 /// window does not need to be drawn.
1436 ///
1437 /// Actual color depends on the system and themes should define a fully
1438 /// opaque background color instead.
1439 #[default]
1440 Opaque,
1441 /// Plain alpha transparency.
1442 Transparent,
1443 /// Transparency, but the contents behind the window are blurred.
1444 ///
1445 /// Not always supported.
1446 Blurred,
1447 /// The Mica backdrop material, supported on Windows 11.
1448 MicaBackdrop,
1449 /// The Mica Alt backdrop material, supported on Windows 11.
1450 MicaAltBackdrop,
1451}
1452
1453/// The text rendering mode to use for drawing glyphs.
1454#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1455pub enum TextRenderingMode {
1456 /// Use the platform's default text rendering mode.
1457 #[default]
1458 PlatformDefault,
1459 /// Use subpixel (ClearType-style) text rendering.
1460 Subpixel,
1461 /// Use grayscale text rendering.
1462 Grayscale,
1463}
1464
1465/// The options that can be configured for a file dialog prompt
1466#[derive(Clone, Debug)]
1467pub struct PathPromptOptions {
1468 /// Should the prompt allow files to be selected?
1469 pub files: bool,
1470 /// Should the prompt allow directories to be selected?
1471 pub directories: bool,
1472 /// Should the prompt allow multiple files to be selected?
1473 pub multiple: bool,
1474 /// The prompt to show to a user when selecting a path
1475 pub prompt: Option<SharedString>,
1476}
1477
1478/// What kind of prompt styling to show
1479#[derive(Copy, Clone, Debug, PartialEq)]
1480pub enum PromptLevel {
1481 /// A prompt that is shown when the user should be notified of something
1482 Info,
1483
1484 /// A prompt that is shown when the user needs to be warned of a potential problem
1485 Warning,
1486
1487 /// A prompt that is shown when a critical problem has occurred
1488 Critical,
1489}
1490
1491/// Prompt Button
1492#[derive(Clone, Debug, PartialEq)]
1493pub enum PromptButton {
1494 /// Ok button
1495 Ok(SharedString),
1496 /// Cancel button
1497 Cancel(SharedString),
1498 /// Other button
1499 Other(SharedString),
1500}
1501
1502impl PromptButton {
1503 /// Create a button with label
1504 pub fn new(label: impl Into<SharedString>) -> Self {
1505 PromptButton::Other(label.into())
1506 }
1507
1508 /// Create an Ok button
1509 pub fn ok(label: impl Into<SharedString>) -> Self {
1510 PromptButton::Ok(label.into())
1511 }
1512
1513 /// Create a Cancel button
1514 pub fn cancel(label: impl Into<SharedString>) -> Self {
1515 PromptButton::Cancel(label.into())
1516 }
1517
1518 #[allow(dead_code)]
1519 pub(crate) fn is_cancel(&self) -> bool {
1520 matches!(self, PromptButton::Cancel(_))
1521 }
1522
1523 /// Returns the label of the button
1524 pub fn label(&self) -> &SharedString {
1525 match self {
1526 PromptButton::Ok(label) => label,
1527 PromptButton::Cancel(label) => label,
1528 PromptButton::Other(label) => label,
1529 }
1530 }
1531}
1532
1533impl From<&str> for PromptButton {
1534 fn from(value: &str) -> Self {
1535 match value.to_lowercase().as_str() {
1536 "ok" => PromptButton::Ok("Ok".into()),
1537 "cancel" => PromptButton::Cancel("Cancel".into()),
1538 _ => PromptButton::Other(SharedString::from(value.to_owned())),
1539 }
1540 }
1541}
1542
1543/// The style of the cursor (pointer)
1544#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1545pub enum CursorStyle {
1546 /// The default cursor
1547 #[default]
1548 Arrow,
1549
1550 /// A text input cursor
1551 /// corresponds to the CSS cursor value `text`
1552 IBeam,
1553
1554 /// A crosshair cursor
1555 /// corresponds to the CSS cursor value `crosshair`
1556 Crosshair,
1557
1558 /// A closed hand cursor
1559 /// corresponds to the CSS cursor value `grabbing`
1560 ClosedHand,
1561
1562 /// An open hand cursor
1563 /// corresponds to the CSS cursor value `grab`
1564 OpenHand,
1565
1566 /// A pointing hand cursor
1567 /// corresponds to the CSS cursor value `pointer`
1568 PointingHand,
1569
1570 /// A resize left cursor
1571 /// corresponds to the CSS cursor value `w-resize`
1572 ResizeLeft,
1573
1574 /// A resize right cursor
1575 /// corresponds to the CSS cursor value `e-resize`
1576 ResizeRight,
1577
1578 /// A resize cursor to the left and right
1579 /// corresponds to the CSS cursor value `ew-resize`
1580 ResizeLeftRight,
1581
1582 /// A resize up cursor
1583 /// corresponds to the CSS cursor value `n-resize`
1584 ResizeUp,
1585
1586 /// A resize down cursor
1587 /// corresponds to the CSS cursor value `s-resize`
1588 ResizeDown,
1589
1590 /// A resize cursor directing up and down
1591 /// corresponds to the CSS cursor value `ns-resize`
1592 ResizeUpDown,
1593
1594 /// A resize cursor directing up-left and down-right
1595 /// corresponds to the CSS cursor value `nesw-resize`
1596 ResizeUpLeftDownRight,
1597
1598 /// A resize cursor directing up-right and down-left
1599 /// corresponds to the CSS cursor value `nwse-resize`
1600 ResizeUpRightDownLeft,
1601
1602 /// A cursor indicating that the item/column can be resized horizontally.
1603 /// corresponds to the CSS cursor value `col-resize`
1604 ResizeColumn,
1605
1606 /// A cursor indicating that the item/row can be resized vertically.
1607 /// corresponds to the CSS cursor value `row-resize`
1608 ResizeRow,
1609
1610 /// A text input cursor for vertical layout
1611 /// corresponds to the CSS cursor value `vertical-text`
1612 IBeamCursorForVerticalLayout,
1613
1614 /// A cursor indicating that the operation is not allowed
1615 /// corresponds to the CSS cursor value `not-allowed`
1616 OperationNotAllowed,
1617
1618 /// A cursor indicating that the operation will result in a link
1619 /// corresponds to the CSS cursor value `alias`
1620 DragLink,
1621
1622 /// A cursor indicating that the operation will result in a copy
1623 /// corresponds to the CSS cursor value `copy`
1624 DragCopy,
1625
1626 /// A cursor indicating that the operation will result in a context menu
1627 /// corresponds to the CSS cursor value `context-menu`
1628 ContextualMenu,
1629
1630 /// Hide the cursor
1631 None,
1632}
1633
1634/// A clipboard item that should be copied to the clipboard
1635#[derive(Clone, Debug, Eq, PartialEq)]
1636pub struct ClipboardItem {
1637 entries: Vec<ClipboardEntry>,
1638}
1639
1640/// Either a ClipboardString or a ClipboardImage
1641#[derive(Clone, Debug, Eq, PartialEq)]
1642pub enum ClipboardEntry {
1643 /// A string entry
1644 String(ClipboardString),
1645 /// An image entry
1646 Image(Image),
1647 /// A file entry
1648 ExternalPaths(crate::ExternalPaths),
1649}
1650
1651impl ClipboardItem {
1652 /// Create a new ClipboardItem::String with no associated metadata
1653 pub fn new_string(text: String) -> Self {
1654 Self {
1655 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1656 }
1657 }
1658
1659 /// Create a new ClipboardItem::String with the given text and associated metadata
1660 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1661 Self {
1662 entries: vec![ClipboardEntry::String(ClipboardString {
1663 text,
1664 metadata: Some(metadata),
1665 })],
1666 }
1667 }
1668
1669 /// Create a new ClipboardItem::String with the given text and associated metadata
1670 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1671 Self {
1672 entries: vec![ClipboardEntry::String(
1673 ClipboardString::new(text).with_json_metadata(metadata),
1674 )],
1675 }
1676 }
1677
1678 /// Create a new ClipboardItem::Image with the given image with no associated metadata
1679 pub fn new_image(image: &Image) -> Self {
1680 Self {
1681 entries: vec![ClipboardEntry::Image(image.clone())],
1682 }
1683 }
1684
1685 /// Concatenates together all the ClipboardString entries in the item.
1686 /// Returns None if there were no ClipboardString entries.
1687 pub fn text(&self) -> Option<String> {
1688 let mut answer = String::new();
1689
1690 for entry in self.entries.iter() {
1691 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1692 answer.push_str(text);
1693 }
1694 }
1695
1696 if answer.is_empty() {
1697 for entry in self.entries.iter() {
1698 if let ClipboardEntry::ExternalPaths(paths) = entry {
1699 for path in &paths.0 {
1700 use std::fmt::Write as _;
1701 _ = write!(answer, "{}", path.display());
1702 }
1703 }
1704 }
1705 }
1706
1707 if !answer.is_empty() {
1708 Some(answer)
1709 } else {
1710 None
1711 }
1712 }
1713
1714 /// If this item is one ClipboardEntry::String, returns its metadata.
1715 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1716 pub fn metadata(&self) -> Option<&String> {
1717 match self.entries().first() {
1718 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1719 clipboard_string.metadata.as_ref()
1720 }
1721 _ => None,
1722 }
1723 }
1724
1725 /// Get the item's entries
1726 pub fn entries(&self) -> &[ClipboardEntry] {
1727 &self.entries
1728 }
1729
1730 /// Get owned versions of the item's entries
1731 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1732 self.entries.into_iter()
1733 }
1734}
1735
1736impl From<ClipboardString> for ClipboardEntry {
1737 fn from(value: ClipboardString) -> Self {
1738 Self::String(value)
1739 }
1740}
1741
1742impl From<String> for ClipboardEntry {
1743 fn from(value: String) -> Self {
1744 Self::from(ClipboardString::from(value))
1745 }
1746}
1747
1748impl From<Image> for ClipboardEntry {
1749 fn from(value: Image) -> Self {
1750 Self::Image(value)
1751 }
1752}
1753
1754impl From<ClipboardEntry> for ClipboardItem {
1755 fn from(value: ClipboardEntry) -> Self {
1756 Self {
1757 entries: vec![value],
1758 }
1759 }
1760}
1761
1762impl From<String> for ClipboardItem {
1763 fn from(value: String) -> Self {
1764 Self::from(ClipboardEntry::from(value))
1765 }
1766}
1767
1768impl From<Image> for ClipboardItem {
1769 fn from(value: Image) -> Self {
1770 Self::from(ClipboardEntry::from(value))
1771 }
1772}
1773
1774/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1775#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1776pub enum ImageFormat {
1777 // Sorted from most to least likely to be pasted into an editor,
1778 // which matters when we iterate through them trying to see if
1779 // clipboard content matches them.
1780 /// .png
1781 Png,
1782 /// .jpeg or .jpg
1783 Jpeg,
1784 /// .webp
1785 Webp,
1786 /// .gif
1787 Gif,
1788 /// .svg
1789 Svg,
1790 /// .bmp
1791 Bmp,
1792 /// .tif or .tiff
1793 Tiff,
1794 /// .ico
1795 Ico,
1796}
1797
1798impl ImageFormat {
1799 /// Returns the mime type for the ImageFormat
1800 pub const fn mime_type(self) -> &'static str {
1801 match self {
1802 ImageFormat::Png => "image/png",
1803 ImageFormat::Jpeg => "image/jpeg",
1804 ImageFormat::Webp => "image/webp",
1805 ImageFormat::Gif => "image/gif",
1806 ImageFormat::Svg => "image/svg+xml",
1807 ImageFormat::Bmp => "image/bmp",
1808 ImageFormat::Tiff => "image/tiff",
1809 ImageFormat::Ico => "image/ico",
1810 }
1811 }
1812
1813 /// Returns the ImageFormat for the given mime type
1814 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
1815 match mime_type {
1816 "image/png" => Some(Self::Png),
1817 "image/jpeg" | "image/jpg" => Some(Self::Jpeg),
1818 "image/webp" => Some(Self::Webp),
1819 "image/gif" => Some(Self::Gif),
1820 "image/svg+xml" => Some(Self::Svg),
1821 "image/bmp" => Some(Self::Bmp),
1822 "image/tiff" | "image/tif" => Some(Self::Tiff),
1823 "image/ico" => Some(Self::Ico),
1824 _ => None,
1825 }
1826 }
1827}
1828
1829/// An image, with a format and certain bytes
1830#[derive(Clone, Debug, PartialEq, Eq)]
1831pub struct Image {
1832 /// The image format the bytes represent (e.g. PNG)
1833 pub format: ImageFormat,
1834 /// The raw image bytes
1835 pub bytes: Vec<u8>,
1836 /// The unique ID for the image
1837 id: u64,
1838}
1839
1840impl Hash for Image {
1841 fn hash<H: Hasher>(&self, state: &mut H) {
1842 state.write_u64(self.id);
1843 }
1844}
1845
1846impl Image {
1847 /// An empty image containing no data
1848 pub fn empty() -> Self {
1849 Self::from_bytes(ImageFormat::Png, Vec::new())
1850 }
1851
1852 /// Create an image from a format and bytes
1853 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
1854 Self {
1855 id: hash(&bytes),
1856 format,
1857 bytes,
1858 }
1859 }
1860
1861 /// Get this image's ID
1862 pub fn id(&self) -> u64 {
1863 self.id
1864 }
1865
1866 /// Use the GPUI `use_asset` API to make this image renderable
1867 pub fn use_render_image(
1868 self: Arc<Self>,
1869 window: &mut Window,
1870 cx: &mut App,
1871 ) -> Option<Arc<RenderImage>> {
1872 ImageSource::Image(self)
1873 .use_data(None, window, cx)
1874 .and_then(|result| result.ok())
1875 }
1876
1877 /// Use the GPUI `get_asset` API to make this image renderable
1878 pub fn get_render_image(
1879 self: Arc<Self>,
1880 window: &mut Window,
1881 cx: &mut App,
1882 ) -> Option<Arc<RenderImage>> {
1883 ImageSource::Image(self)
1884 .get_data(None, window, cx)
1885 .and_then(|result| result.ok())
1886 }
1887
1888 /// Use the GPUI `remove_asset` API to drop this image, if possible.
1889 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
1890 ImageSource::Image(self).remove_asset(cx);
1891 }
1892
1893 /// Convert the clipboard image to an `ImageData` object.
1894 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1895 fn frames_for_image(
1896 bytes: &[u8],
1897 format: image::ImageFormat,
1898 ) -> Result<SmallVec<[Frame; 1]>> {
1899 let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1900
1901 // Convert from RGBA to BGRA.
1902 for pixel in data.chunks_exact_mut(4) {
1903 pixel.swap(0, 2);
1904 }
1905
1906 Ok(SmallVec::from_elem(Frame::new(data), 1))
1907 }
1908
1909 let frames = match self.format {
1910 ImageFormat::Gif => {
1911 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1912 let mut frames = SmallVec::new();
1913
1914 for frame in decoder.into_frames() {
1915 let mut frame = frame?;
1916 // Convert from RGBA to BGRA.
1917 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1918 pixel.swap(0, 2);
1919 }
1920 frames.push(frame);
1921 }
1922
1923 frames
1924 }
1925 ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1926 ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1927 ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1928 ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1929 ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1930 ImageFormat::Ico => frames_for_image(&self.bytes, image::ImageFormat::Ico)?,
1931 ImageFormat::Svg => {
1932 return svg_renderer
1933 .render_single_frame(&self.bytes, 1.0, false)
1934 .map_err(Into::into);
1935 }
1936 };
1937
1938 Ok(Arc::new(RenderImage::new(frames)))
1939 }
1940
1941 /// Get the format of the clipboard image
1942 pub fn format(&self) -> ImageFormat {
1943 self.format
1944 }
1945
1946 /// Get the raw bytes of the clipboard image
1947 pub fn bytes(&self) -> &[u8] {
1948 self.bytes.as_slice()
1949 }
1950}
1951
1952/// A clipboard item that should be copied to the clipboard
1953#[derive(Clone, Debug, Eq, PartialEq)]
1954pub struct ClipboardString {
1955 pub(crate) text: String,
1956 pub(crate) metadata: Option<String>,
1957}
1958
1959impl ClipboardString {
1960 /// Create a new clipboard string with the given text
1961 pub fn new(text: String) -> Self {
1962 Self {
1963 text,
1964 metadata: None,
1965 }
1966 }
1967
1968 /// Return a new clipboard item with the metadata replaced by the given metadata,
1969 /// after serializing it as JSON.
1970 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1971 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1972 self
1973 }
1974
1975 /// Get the text of the clipboard string
1976 pub fn text(&self) -> &String {
1977 &self.text
1978 }
1979
1980 /// Get the owned text of the clipboard string
1981 pub fn into_text(self) -> String {
1982 self.text
1983 }
1984
1985 /// Get the metadata of the clipboard string, formatted as JSON
1986 pub fn metadata_json<T>(&self) -> Option<T>
1987 where
1988 T: for<'a> Deserialize<'a>,
1989 {
1990 self.metadata
1991 .as_ref()
1992 .and_then(|m| serde_json::from_str(m).ok())
1993 }
1994
1995 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1996 pub(crate) fn text_hash(text: &str) -> u64 {
1997 let mut hasher = SeaHasher::new();
1998 text.hash(&mut hasher);
1999 hasher.finish()
2000 }
2001}
2002
2003impl From<String> for ClipboardString {
2004 fn from(value: String) -> Self {
2005 Self {
2006 text: value,
2007 metadata: None,
2008 }
2009 }
2010}