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