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