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 ShapedGlyph, ShapedRun, SharedString, Size, SvgRenderer, SvgSize, Task, TaskLabel, Window,
41 point, px, size,
42};
43use anyhow::Result;
44use async_task::Runnable;
45use futures::channel::oneshot;
46use image::codecs::gif::GifDecoder;
47use image::{AnimationDecoder as _, Frame};
48use parking::Unparker;
49use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
50use seahash::SeaHasher;
51use serde::{Deserialize, Serialize};
52use smallvec::SmallVec;
53use std::borrow::Cow;
54use std::hash::{Hash, Hasher};
55use std::io::Cursor;
56use std::ops;
57use std::time::{Duration, Instant};
58use std::{
59 fmt::{self, Debug},
60 ops::Range,
61 path::{Path, PathBuf},
62 rc::Rc,
63 sync::Arc,
64};
65use strum::EnumIter;
66use uuid::Uuid;
67
68pub use app_menu::*;
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::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 = SmallVec::default();
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 fn marked_text_range(&mut self) -> Option<Range<usize>> {
806 self.cx
807 .update(|window, cx| self.handler.marked_text_range(window, cx))
808 .ok()
809 .flatten()
810 }
811
812 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
813 fn text_for_range(
814 &mut self,
815 range_utf16: Range<usize>,
816 adjusted: &mut Option<Range<usize>>,
817 ) -> Option<String> {
818 self.cx
819 .update(|window, cx| {
820 self.handler
821 .text_for_range(range_utf16, adjusted, window, cx)
822 })
823 .ok()
824 .flatten()
825 }
826
827 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
828 self.cx
829 .update(|window, cx| {
830 self.handler
831 .replace_text_in_range(replacement_range, text, window, cx);
832 })
833 .ok();
834 }
835
836 fn replace_and_mark_text_in_range(
837 &mut self,
838 range_utf16: Option<Range<usize>>,
839 new_text: &str,
840 new_selected_range: Option<Range<usize>>,
841 ) {
842 self.cx
843 .update(|window, cx| {
844 self.handler.replace_and_mark_text_in_range(
845 range_utf16,
846 new_text,
847 new_selected_range,
848 window,
849 cx,
850 )
851 })
852 .ok();
853 }
854
855 fn unmark_text(&mut self) {
856 self.cx
857 .update(|window, cx| self.handler.unmark_text(window, cx))
858 .ok();
859 }
860
861 fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
862 self.cx
863 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
864 .ok()
865 .flatten()
866 }
867
868 #[allow(dead_code)]
869 fn apple_press_and_hold_enabled(&mut self) -> bool {
870 self.handler.apple_press_and_hold_enabled()
871 }
872
873 pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
874 self.handler.replace_text_in_range(None, input, window, cx);
875 }
876
877 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
878 let selection = self.handler.selected_text_range(true, window, cx)?;
879 self.handler.bounds_for_range(
880 if selection.reversed {
881 selection.range.start..selection.range.start
882 } else {
883 selection.range.end..selection.range.end
884 },
885 window,
886 cx,
887 )
888 }
889
890 #[allow(unused)]
891 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
892 self.cx
893 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
894 .ok()
895 .flatten()
896 }
897}
898
899/// A struct representing a selection in a text buffer, in UTF16 characters.
900/// This is different from a range because the head may be before the tail.
901#[derive(Debug)]
902pub struct UTF16Selection {
903 /// The range of text in the document this selection corresponds to
904 /// in UTF16 characters.
905 pub range: Range<usize>,
906 /// Whether the head of this selection is at the start (true), or end (false)
907 /// of the range
908 pub reversed: bool,
909}
910
911/// Zed's interface for handling text input from the platform's IME system
912/// This is currently a 1:1 exposure of the NSTextInputClient API:
913///
914/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
915pub trait InputHandler: 'static {
916 /// Get the range of the user's currently selected text, if any
917 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
918 ///
919 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
920 fn selected_text_range(
921 &mut self,
922 ignore_disabled_input: bool,
923 window: &mut Window,
924 cx: &mut App,
925 ) -> Option<UTF16Selection>;
926
927 /// Get the range of the currently marked text, if any
928 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
929 ///
930 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
931 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
932
933 /// Get the text for the given document range in UTF-16 characters
934 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
935 ///
936 /// range_utf16 is in terms of UTF-16 characters
937 fn text_for_range(
938 &mut self,
939 range_utf16: Range<usize>,
940 adjusted_range: &mut Option<Range<usize>>,
941 window: &mut Window,
942 cx: &mut App,
943 ) -> Option<String>;
944
945 /// Replace the text in the given document range with the given text
946 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
947 ///
948 /// replacement_range is in terms of UTF-16 characters
949 fn replace_text_in_range(
950 &mut self,
951 replacement_range: Option<Range<usize>>,
952 text: &str,
953 window: &mut Window,
954 cx: &mut App,
955 );
956
957 /// Replace the text in the given document range with the given text,
958 /// and mark the given text as part of an IME 'composing' state
959 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
960 ///
961 /// range_utf16 is in terms of UTF-16 characters
962 /// new_selected_range is in terms of UTF-16 characters
963 fn replace_and_mark_text_in_range(
964 &mut self,
965 range_utf16: Option<Range<usize>>,
966 new_text: &str,
967 new_selected_range: Option<Range<usize>>,
968 window: &mut Window,
969 cx: &mut App,
970 );
971
972 /// Remove the IME 'composing' state from the document
973 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
974 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
975
976 /// Get the bounds of the given document range in screen coordinates
977 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
978 ///
979 /// This is used for positioning the IME candidate window
980 fn bounds_for_range(
981 &mut self,
982 range_utf16: Range<usize>,
983 window: &mut Window,
984 cx: &mut App,
985 ) -> Option<Bounds<Pixels>>;
986
987 /// Get the character offset for the given point in terms of UTF16 characters
988 ///
989 /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
990 fn character_index_for_point(
991 &mut self,
992 point: Point<Pixels>,
993 window: &mut Window,
994 cx: &mut App,
995 ) -> Option<usize>;
996
997 /// Allows a given input context to opt into getting raw key repeats instead of
998 /// sending these to the platform.
999 /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1000 /// (which is how iTerm does it) but it doesn't seem to work for me.
1001 #[allow(dead_code)]
1002 fn apple_press_and_hold_enabled(&mut self) -> bool {
1003 true
1004 }
1005}
1006
1007/// The variables that can be configured when creating a new window
1008#[derive(Debug)]
1009pub struct WindowOptions {
1010 /// Specifies the state and bounds of the window in screen coordinates.
1011 /// - `None`: Inherit the bounds.
1012 /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1013 pub window_bounds: Option<WindowBounds>,
1014
1015 /// The titlebar configuration of the window
1016 pub titlebar: Option<TitlebarOptions>,
1017
1018 /// Whether the window should be focused when created
1019 pub focus: bool,
1020
1021 /// Whether the window should be shown when created
1022 pub show: bool,
1023
1024 /// The kind of window to create
1025 pub kind: WindowKind,
1026
1027 /// Whether the window should be movable by the user
1028 pub is_movable: bool,
1029
1030 /// The display to create the window on, if this is None,
1031 /// the window will be created on the main display
1032 pub display_id: Option<DisplayId>,
1033
1034 /// The appearance of the window background.
1035 pub window_background: WindowBackgroundAppearance,
1036
1037 /// Application identifier of the window. Can by used by desktop environments to group applications together.
1038 pub app_id: Option<String>,
1039
1040 /// Window minimum size
1041 pub window_min_size: Option<Size<Pixels>>,
1042
1043 /// Whether to use client or server side decorations. Wayland only
1044 /// Note that this may be ignored.
1045 pub window_decorations: Option<WindowDecorations>,
1046}
1047
1048/// The variables that can be configured when creating a new window
1049#[derive(Debug)]
1050#[cfg_attr(
1051 all(
1052 any(target_os = "linux", target_os = "freebsd"),
1053 not(any(feature = "x11", feature = "wayland"))
1054 ),
1055 allow(dead_code)
1056)]
1057pub(crate) struct WindowParams {
1058 pub bounds: Bounds<Pixels>,
1059
1060 /// The titlebar configuration of the window
1061 #[cfg_attr(feature = "wayland", allow(dead_code))]
1062 pub titlebar: Option<TitlebarOptions>,
1063
1064 /// The kind of window to create
1065 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1066 pub kind: WindowKind,
1067
1068 /// Whether the window should be movable by the user
1069 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1070 pub is_movable: bool,
1071
1072 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1073 pub focus: bool,
1074
1075 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1076 pub show: bool,
1077
1078 #[cfg_attr(feature = "wayland", allow(dead_code))]
1079 pub display_id: Option<DisplayId>,
1080
1081 pub window_min_size: Option<Size<Pixels>>,
1082}
1083
1084/// Represents the status of how a window should be opened.
1085#[derive(Debug, Copy, Clone, PartialEq)]
1086pub enum WindowBounds {
1087 /// Indicates that the window should open in a windowed state with the given bounds.
1088 Windowed(Bounds<Pixels>),
1089 /// Indicates that the window should open in a maximized state.
1090 /// The bounds provided here represent the restore size of the window.
1091 Maximized(Bounds<Pixels>),
1092 /// Indicates that the window should open in fullscreen mode.
1093 /// The bounds provided here represent the restore size of the window.
1094 Fullscreen(Bounds<Pixels>),
1095}
1096
1097impl Default for WindowBounds {
1098 fn default() -> Self {
1099 WindowBounds::Windowed(Bounds::default())
1100 }
1101}
1102
1103impl WindowBounds {
1104 /// Retrieve the inner bounds
1105 pub fn get_bounds(&self) -> Bounds<Pixels> {
1106 match self {
1107 WindowBounds::Windowed(bounds) => *bounds,
1108 WindowBounds::Maximized(bounds) => *bounds,
1109 WindowBounds::Fullscreen(bounds) => *bounds,
1110 }
1111 }
1112}
1113
1114impl Default for WindowOptions {
1115 fn default() -> Self {
1116 Self {
1117 window_bounds: None,
1118 titlebar: Some(TitlebarOptions {
1119 title: Default::default(),
1120 appears_transparent: Default::default(),
1121 traffic_light_position: Default::default(),
1122 }),
1123 focus: true,
1124 show: true,
1125 kind: WindowKind::Normal,
1126 is_movable: true,
1127 display_id: None,
1128 window_background: WindowBackgroundAppearance::default(),
1129 app_id: None,
1130 window_min_size: None,
1131 window_decorations: None,
1132 }
1133 }
1134}
1135
1136/// The options that can be configured for a window's titlebar
1137#[derive(Debug, Default)]
1138pub struct TitlebarOptions {
1139 /// The initial title of the window
1140 pub title: Option<SharedString>,
1141
1142 /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
1143 /// Refer to [`WindowOptions::window_decorations`] on Linux
1144 pub appears_transparent: bool,
1145
1146 /// The position of the macOS traffic light buttons
1147 pub traffic_light_position: Option<Point<Pixels>>,
1148}
1149
1150/// The kind of window to create
1151#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1152pub enum WindowKind {
1153 /// A normal application window
1154 Normal,
1155
1156 /// A window that appears above all other windows, usually used for alerts or popups
1157 /// use sparingly!
1158 PopUp,
1159}
1160
1161/// The appearance of the window, as defined by the operating system.
1162///
1163/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
1164/// values.
1165#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1166pub enum WindowAppearance {
1167 /// A light appearance.
1168 ///
1169 /// On macOS, this corresponds to the `aqua` appearance.
1170 Light,
1171
1172 /// A light appearance with vibrant colors.
1173 ///
1174 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
1175 VibrantLight,
1176
1177 /// A dark appearance.
1178 ///
1179 /// On macOS, this corresponds to the `darkAqua` appearance.
1180 Dark,
1181
1182 /// A dark appearance with vibrant colors.
1183 ///
1184 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
1185 VibrantDark,
1186}
1187
1188impl Default for WindowAppearance {
1189 fn default() -> Self {
1190 Self::Light
1191 }
1192}
1193
1194/// The appearance of the background of the window itself, when there is
1195/// no content or the content is transparent.
1196#[derive(Copy, Clone, Debug, Default, PartialEq)]
1197pub enum WindowBackgroundAppearance {
1198 /// Opaque.
1199 ///
1200 /// This lets the window manager know that content behind this
1201 /// window does not need to be drawn.
1202 ///
1203 /// Actual color depends on the system and themes should define a fully
1204 /// opaque background color instead.
1205 #[default]
1206 Opaque,
1207 /// Plain alpha transparency.
1208 Transparent,
1209 /// Transparency, but the contents behind the window are blurred.
1210 ///
1211 /// Not always supported.
1212 Blurred,
1213}
1214
1215/// The options that can be configured for a file dialog prompt
1216#[derive(Copy, Clone, Debug)]
1217pub struct PathPromptOptions {
1218 /// Should the prompt allow files to be selected?
1219 pub files: bool,
1220 /// Should the prompt allow directories to be selected?
1221 pub directories: bool,
1222 /// Should the prompt allow multiple files to be selected?
1223 pub multiple: bool,
1224}
1225
1226/// What kind of prompt styling to show
1227#[derive(Copy, Clone, Debug, PartialEq)]
1228pub enum PromptLevel {
1229 /// A prompt that is shown when the user should be notified of something
1230 Info,
1231
1232 /// A prompt that is shown when the user needs to be warned of a potential problem
1233 Warning,
1234
1235 /// A prompt that is shown when a critical problem has occurred
1236 Critical,
1237}
1238
1239/// The style of the cursor (pointer)
1240#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1241pub enum CursorStyle {
1242 /// The default cursor
1243 Arrow,
1244
1245 /// A text input cursor
1246 /// corresponds to the CSS cursor value `text`
1247 IBeam,
1248
1249 /// A crosshair cursor
1250 /// corresponds to the CSS cursor value `crosshair`
1251 Crosshair,
1252
1253 /// A closed hand cursor
1254 /// corresponds to the CSS cursor value `grabbing`
1255 ClosedHand,
1256
1257 /// An open hand cursor
1258 /// corresponds to the CSS cursor value `grab`
1259 OpenHand,
1260
1261 /// A pointing hand cursor
1262 /// corresponds to the CSS cursor value `pointer`
1263 PointingHand,
1264
1265 /// A resize left cursor
1266 /// corresponds to the CSS cursor value `w-resize`
1267 ResizeLeft,
1268
1269 /// A resize right cursor
1270 /// corresponds to the CSS cursor value `e-resize`
1271 ResizeRight,
1272
1273 /// A resize cursor to the left and right
1274 /// corresponds to the CSS cursor value `ew-resize`
1275 ResizeLeftRight,
1276
1277 /// A resize up cursor
1278 /// corresponds to the CSS cursor value `n-resize`
1279 ResizeUp,
1280
1281 /// A resize down cursor
1282 /// corresponds to the CSS cursor value `s-resize`
1283 ResizeDown,
1284
1285 /// A resize cursor directing up and down
1286 /// corresponds to the CSS cursor value `ns-resize`
1287 ResizeUpDown,
1288
1289 /// A resize cursor directing up-left and down-right
1290 /// corresponds to the CSS cursor value `nesw-resize`
1291 ResizeUpLeftDownRight,
1292
1293 /// A resize cursor directing up-right and down-left
1294 /// corresponds to the CSS cursor value `nwse-resize`
1295 ResizeUpRightDownLeft,
1296
1297 /// A cursor indicating that the item/column can be resized horizontally.
1298 /// corresponds to the CSS cursor value `col-resize`
1299 ResizeColumn,
1300
1301 /// A cursor indicating that the item/row can be resized vertically.
1302 /// corresponds to the CSS cursor value `row-resize`
1303 ResizeRow,
1304
1305 /// A text input cursor for vertical layout
1306 /// corresponds to the CSS cursor value `vertical-text`
1307 IBeamCursorForVerticalLayout,
1308
1309 /// A cursor indicating that the operation is not allowed
1310 /// corresponds to the CSS cursor value `not-allowed`
1311 OperationNotAllowed,
1312
1313 /// A cursor indicating that the operation will result in a link
1314 /// corresponds to the CSS cursor value `alias`
1315 DragLink,
1316
1317 /// A cursor indicating that the operation will result in a copy
1318 /// corresponds to the CSS cursor value `copy`
1319 DragCopy,
1320
1321 /// A cursor indicating that the operation will result in a context menu
1322 /// corresponds to the CSS cursor value `context-menu`
1323 ContextualMenu,
1324
1325 /// Hide the cursor
1326 None,
1327}
1328
1329impl Default for CursorStyle {
1330 fn default() -> Self {
1331 Self::Arrow
1332 }
1333}
1334
1335/// A clipboard item that should be copied to the clipboard
1336#[derive(Clone, Debug, Eq, PartialEq)]
1337pub struct ClipboardItem {
1338 entries: Vec<ClipboardEntry>,
1339}
1340
1341/// Either a ClipboardString or a ClipboardImage
1342#[derive(Clone, Debug, Eq, PartialEq)]
1343pub enum ClipboardEntry {
1344 /// A string entry
1345 String(ClipboardString),
1346 /// An image entry
1347 Image(Image),
1348}
1349
1350impl ClipboardItem {
1351 /// Create a new ClipboardItem::String with no associated metadata
1352 pub fn new_string(text: String) -> Self {
1353 Self {
1354 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1355 }
1356 }
1357
1358 /// Create a new ClipboardItem::String with the given text and associated metadata
1359 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1360 Self {
1361 entries: vec![ClipboardEntry::String(ClipboardString {
1362 text,
1363 metadata: Some(metadata),
1364 })],
1365 }
1366 }
1367
1368 /// Create a new ClipboardItem::String with the given text and associated metadata
1369 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1370 Self {
1371 entries: vec![ClipboardEntry::String(
1372 ClipboardString::new(text).with_json_metadata(metadata),
1373 )],
1374 }
1375 }
1376
1377 /// Create a new ClipboardItem::Image with the given image with no associated metadata
1378 pub fn new_image(image: &Image) -> Self {
1379 Self {
1380 entries: vec![ClipboardEntry::Image(image.clone())],
1381 }
1382 }
1383
1384 /// Concatenates together all the ClipboardString entries in the item.
1385 /// Returns None if there were no ClipboardString entries.
1386 pub fn text(&self) -> Option<String> {
1387 let mut answer = String::new();
1388 let mut any_entries = false;
1389
1390 for entry in self.entries.iter() {
1391 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1392 answer.push_str(&text);
1393 any_entries = true;
1394 }
1395 }
1396
1397 if any_entries { Some(answer) } else { None }
1398 }
1399
1400 /// If this item is one ClipboardEntry::String, returns its metadata.
1401 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1402 pub fn metadata(&self) -> Option<&String> {
1403 match self.entries().first() {
1404 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1405 clipboard_string.metadata.as_ref()
1406 }
1407 _ => None,
1408 }
1409 }
1410
1411 /// Get the item's entries
1412 pub fn entries(&self) -> &[ClipboardEntry] {
1413 &self.entries
1414 }
1415
1416 /// Get owned versions of the item's entries
1417 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1418 self.entries.into_iter()
1419 }
1420}
1421
1422impl From<ClipboardString> for ClipboardEntry {
1423 fn from(value: ClipboardString) -> Self {
1424 Self::String(value)
1425 }
1426}
1427
1428impl From<String> for ClipboardEntry {
1429 fn from(value: String) -> Self {
1430 Self::from(ClipboardString::from(value))
1431 }
1432}
1433
1434impl From<Image> for ClipboardEntry {
1435 fn from(value: Image) -> Self {
1436 Self::Image(value)
1437 }
1438}
1439
1440impl From<ClipboardEntry> for ClipboardItem {
1441 fn from(value: ClipboardEntry) -> Self {
1442 Self {
1443 entries: vec![value],
1444 }
1445 }
1446}
1447
1448impl From<String> for ClipboardItem {
1449 fn from(value: String) -> Self {
1450 Self::from(ClipboardEntry::from(value))
1451 }
1452}
1453
1454impl From<Image> for ClipboardItem {
1455 fn from(value: Image) -> Self {
1456 Self::from(ClipboardEntry::from(value))
1457 }
1458}
1459
1460/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1461#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1462pub enum ImageFormat {
1463 // Sorted from most to least likely to be pasted into an editor,
1464 // which matters when we iterate through them trying to see if
1465 // clipboard content matches them.
1466 /// .png
1467 Png,
1468 /// .jpeg or .jpg
1469 Jpeg,
1470 /// .webp
1471 Webp,
1472 /// .gif
1473 Gif,
1474 /// .svg
1475 Svg,
1476 /// .bmp
1477 Bmp,
1478 /// .tif or .tiff
1479 Tiff,
1480}
1481
1482/// An image, with a format and certain bytes
1483#[derive(Clone, Debug, PartialEq, Eq)]
1484pub struct Image {
1485 /// The image format the bytes represent (e.g. PNG)
1486 pub format: ImageFormat,
1487 /// The raw image bytes
1488 pub bytes: Vec<u8>,
1489 /// The unique ID for the image
1490 pub id: u64,
1491}
1492
1493impl Hash for Image {
1494 fn hash<H: Hasher>(&self, state: &mut H) {
1495 state.write_u64(self.id);
1496 }
1497}
1498
1499impl Image {
1500 /// An empty image containing no data
1501 pub fn empty() -> Self {
1502 Self {
1503 format: ImageFormat::Png,
1504 bytes: Vec::new(),
1505 id: 0,
1506 }
1507 }
1508
1509 /// Get this image's ID
1510 pub fn id(&self) -> u64 {
1511 self.id
1512 }
1513
1514 /// Use the GPUI `use_asset` API to make this image renderable
1515 pub fn use_render_image(
1516 self: Arc<Self>,
1517 window: &mut Window,
1518 cx: &mut App,
1519 ) -> Option<Arc<RenderImage>> {
1520 ImageSource::Image(self)
1521 .use_data(None, window, cx)
1522 .and_then(|result| result.ok())
1523 }
1524
1525 /// Convert the clipboard image to an `ImageData` object.
1526 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1527 fn frames_for_image(
1528 bytes: &[u8],
1529 format: image::ImageFormat,
1530 ) -> Result<SmallVec<[Frame; 1]>> {
1531 let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1532
1533 // Convert from RGBA to BGRA.
1534 for pixel in data.chunks_exact_mut(4) {
1535 pixel.swap(0, 2);
1536 }
1537
1538 Ok(SmallVec::from_elem(Frame::new(data), 1))
1539 }
1540
1541 let frames = match self.format {
1542 ImageFormat::Gif => {
1543 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1544 let mut frames = SmallVec::new();
1545
1546 for frame in decoder.into_frames() {
1547 let mut frame = frame?;
1548 // Convert from RGBA to BGRA.
1549 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1550 pixel.swap(0, 2);
1551 }
1552 frames.push(frame);
1553 }
1554
1555 frames
1556 }
1557 ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1558 ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1559 ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1560 ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1561 ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1562 ImageFormat::Svg => {
1563 let pixmap = svg_renderer.render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1564
1565 let buffer =
1566 image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1567 .unwrap();
1568
1569 SmallVec::from_elem(Frame::new(buffer), 1)
1570 }
1571 };
1572
1573 Ok(Arc::new(RenderImage::new(frames)))
1574 }
1575
1576 /// Get the format of the clipboard image
1577 pub fn format(&self) -> ImageFormat {
1578 self.format
1579 }
1580
1581 /// Get the raw bytes of the clipboard image
1582 pub fn bytes(&self) -> &[u8] {
1583 self.bytes.as_slice()
1584 }
1585}
1586
1587/// A clipboard item that should be copied to the clipboard
1588#[derive(Clone, Debug, Eq, PartialEq)]
1589pub struct ClipboardString {
1590 pub(crate) text: String,
1591 pub(crate) metadata: Option<String>,
1592}
1593
1594impl ClipboardString {
1595 /// Create a new clipboard string with the given text
1596 pub fn new(text: String) -> Self {
1597 Self {
1598 text,
1599 metadata: None,
1600 }
1601 }
1602
1603 /// Return a new clipboard item with the metadata replaced by the given metadata,
1604 /// after serializing it as JSON.
1605 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1606 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1607 self
1608 }
1609
1610 /// Get the text of the clipboard string
1611 pub fn text(&self) -> &String {
1612 &self.text
1613 }
1614
1615 /// Get the owned text of the clipboard string
1616 pub fn into_text(self) -> String {
1617 self.text
1618 }
1619
1620 /// Get the metadata of the clipboard string, formatted as JSON
1621 pub fn metadata_json<T>(&self) -> Option<T>
1622 where
1623 T: for<'a> Deserialize<'a>,
1624 {
1625 self.metadata
1626 .as_ref()
1627 .and_then(|m| serde_json::from_str(m).ok())
1628 }
1629
1630 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1631 pub(crate) fn text_hash(text: &str) -> u64 {
1632 let mut hasher = SeaHasher::new();
1633 text.hash(&mut hasher);
1634 hasher.finish()
1635 }
1636}
1637
1638impl From<String> for ClipboardString {
1639 fn from(value: String) -> Self {
1640 Self {
1641 text: value,
1642 metadata: None,
1643 }
1644 }
1645}
1646
1647/// A trait for platform-specific keyboard layouts
1648pub trait PlatformKeyboardLayout {
1649 /// Get the keyboard layout ID, which should be unique to the layout
1650 fn id(&self) -> &str;
1651 /// Get the keyboard layout display name
1652 fn name(&self) -> &str;
1653}