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