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