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