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