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 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: &[PromptButton],
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_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
440 fn on_close(&self, callback: Box<dyn FnOnce()>);
441 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
442 fn draw(&self, scene: &Scene);
443 fn completed_frame(&self) {}
444 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
445
446 // macOS specific methods
447 fn set_edited(&mut self, _edited: bool) {}
448 fn show_character_palette(&self) {}
449 fn titlebar_double_click(&self) {}
450
451 #[cfg(target_os = "windows")]
452 fn get_raw_handle(&self) -> windows::HWND;
453
454 // Linux specific methods
455 fn inner_window_bounds(&self) -> WindowBounds {
456 self.window_bounds()
457 }
458 fn request_decorations(&self, _decorations: WindowDecorations) {}
459 fn show_window_menu(&self, _position: Point<Pixels>) {}
460 fn start_window_move(&self) {}
461 fn start_window_resize(&self, _edge: ResizeEdge) {}
462 fn window_decorations(&self) -> Decorations {
463 Decorations::Server
464 }
465 fn set_app_id(&mut self, _app_id: &str) {}
466 fn map_window(&mut self) -> anyhow::Result<()> {
467 Ok(())
468 }
469 fn window_controls(&self) -> WindowControls {
470 WindowControls::default()
471 }
472 fn set_client_inset(&self, _inset: Pixels) {}
473 fn gpu_specs(&self) -> Option<GpuSpecs>;
474
475 fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>);
476
477 #[cfg(any(test, feature = "test-support"))]
478 fn as_test(&mut self) -> Option<&mut TestWindow> {
479 None
480 }
481}
482
483/// This type is public so that our test macro can generate and use it, but it should not
484/// be considered part of our public API.
485#[doc(hidden)]
486pub trait PlatformDispatcher: Send + Sync {
487 fn is_main_thread(&self) -> bool;
488 fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
489 fn dispatch_on_main_thread(&self, runnable: Runnable);
490 fn dispatch_after(&self, duration: Duration, runnable: Runnable);
491 fn park(&self, timeout: Option<Duration>) -> bool;
492 fn unparker(&self) -> Unparker;
493 fn now(&self) -> Instant {
494 Instant::now()
495 }
496
497 #[cfg(any(test, feature = "test-support"))]
498 fn as_test(&self) -> Option<&TestDispatcher> {
499 None
500 }
501}
502
503pub(crate) trait PlatformTextSystem: Send + Sync {
504 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
505 fn all_font_names(&self) -> Vec<String>;
506 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
507 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
508 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
509 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
510 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
511 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
512 fn rasterize_glyph(
513 &self,
514 params: &RenderGlyphParams,
515 raster_bounds: Bounds<DevicePixels>,
516 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
517 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
518}
519
520pub(crate) struct NoopTextSystem;
521
522impl NoopTextSystem {
523 #[allow(dead_code)]
524 pub fn new() -> Self {
525 Self
526 }
527}
528
529impl PlatformTextSystem for NoopTextSystem {
530 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
531 Ok(())
532 }
533
534 fn all_font_names(&self) -> Vec<String> {
535 Vec::new()
536 }
537
538 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
539 return Ok(FontId(1));
540 }
541
542 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
543 FontMetrics {
544 units_per_em: 1000,
545 ascent: 1025.0,
546 descent: -275.0,
547 line_gap: 0.0,
548 underline_position: -95.0,
549 underline_thickness: 60.0,
550 cap_height: 698.0,
551 x_height: 516.0,
552 bounding_box: Bounds {
553 origin: Point {
554 x: -260.0,
555 y: -245.0,
556 },
557 size: Size {
558 width: 1501.0,
559 height: 1364.0,
560 },
561 },
562 }
563 }
564
565 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
566 Ok(Bounds {
567 origin: Point { x: 54.0, y: 0.0 },
568 size: size(392.0, 528.0),
569 })
570 }
571
572 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
573 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
574 }
575
576 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
577 Some(GlyphId(ch.len_utf16() as u32))
578 }
579
580 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
581 Ok(Default::default())
582 }
583
584 fn rasterize_glyph(
585 &self,
586 _params: &RenderGlyphParams,
587 raster_bounds: Bounds<DevicePixels>,
588 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
589 Ok((raster_bounds.size, Vec::new()))
590 }
591
592 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
593 let mut position = px(0.);
594 let metrics = self.font_metrics(FontId(0));
595 let em_width = font_size
596 * self
597 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
598 .unwrap()
599 .width
600 / metrics.units_per_em as f32;
601 let mut glyphs = Vec::new();
602 for (ix, c) in text.char_indices() {
603 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
604 glyphs.push(ShapedGlyph {
605 id: glyph,
606 position: point(position, px(0.)),
607 index: ix,
608 is_emoji: glyph.0 == 2,
609 });
610 if glyph.0 == 2 {
611 position += em_width * 2.0;
612 } else {
613 position += em_width;
614 }
615 } else {
616 position += em_width
617 }
618 }
619 let mut runs = Vec::default();
620 if glyphs.len() > 0 {
621 runs.push(ShapedRun {
622 font_id: FontId(0),
623 glyphs,
624 });
625 } else {
626 position = px(0.);
627 }
628
629 LineLayout {
630 font_size,
631 width: position,
632 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
633 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
634 runs,
635 len: text.len(),
636 }
637 }
638}
639
640#[derive(PartialEq, Eq, Hash, Clone)]
641pub(crate) enum AtlasKey {
642 Glyph(RenderGlyphParams),
643 Svg(RenderSvgParams),
644 Image(RenderImageParams),
645}
646
647impl AtlasKey {
648 #[cfg_attr(
649 all(
650 any(target_os = "linux", target_os = "freebsd"),
651 not(any(feature = "x11", feature = "wayland"))
652 ),
653 allow(dead_code)
654 )]
655 pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
656 match self {
657 AtlasKey::Glyph(params) => {
658 if params.is_emoji {
659 AtlasTextureKind::Polychrome
660 } else {
661 AtlasTextureKind::Monochrome
662 }
663 }
664 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
665 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
666 }
667 }
668}
669
670impl From<RenderGlyphParams> for AtlasKey {
671 fn from(params: RenderGlyphParams) -> Self {
672 Self::Glyph(params)
673 }
674}
675
676impl From<RenderSvgParams> for AtlasKey {
677 fn from(params: RenderSvgParams) -> Self {
678 Self::Svg(params)
679 }
680}
681
682impl From<RenderImageParams> for AtlasKey {
683 fn from(params: RenderImageParams) -> Self {
684 Self::Image(params)
685 }
686}
687
688pub(crate) trait PlatformAtlas: Send + Sync {
689 fn get_or_insert_with<'a>(
690 &self,
691 key: &AtlasKey,
692 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
693 ) -> Result<Option<AtlasTile>>;
694 fn remove(&self, key: &AtlasKey);
695}
696
697struct AtlasTextureList<T> {
698 textures: Vec<Option<T>>,
699 free_list: Vec<usize>,
700}
701
702impl<T> Default for AtlasTextureList<T> {
703 fn default() -> Self {
704 Self {
705 textures: Vec::default(),
706 free_list: Vec::default(),
707 }
708 }
709}
710
711impl<T> ops::Index<usize> for AtlasTextureList<T> {
712 type Output = Option<T>;
713
714 fn index(&self, index: usize) -> &Self::Output {
715 &self.textures[index]
716 }
717}
718
719impl<T> AtlasTextureList<T> {
720 #[allow(unused)]
721 fn drain(&mut self) -> std::vec::Drain<Option<T>> {
722 self.free_list.clear();
723 self.textures.drain(..)
724 }
725
726 #[allow(dead_code)]
727 fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
728 self.textures.iter_mut().flatten()
729 }
730}
731
732#[derive(Clone, Debug, PartialEq, Eq)]
733#[repr(C)]
734pub(crate) struct AtlasTile {
735 pub(crate) texture_id: AtlasTextureId,
736 pub(crate) tile_id: TileId,
737 pub(crate) padding: u32,
738 pub(crate) bounds: Bounds<DevicePixels>,
739}
740
741#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
742#[repr(C)]
743pub(crate) struct AtlasTextureId {
744 // We use u32 instead of usize for Metal Shader Language compatibility
745 pub(crate) index: u32,
746 pub(crate) kind: AtlasTextureKind,
747}
748
749#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
750#[repr(C)]
751#[cfg_attr(
752 all(
753 any(target_os = "linux", target_os = "freebsd"),
754 not(any(feature = "x11", feature = "wayland"))
755 ),
756 allow(dead_code)
757)]
758pub(crate) enum AtlasTextureKind {
759 Monochrome = 0,
760 Polychrome = 1,
761 Path = 2,
762}
763
764#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
765#[repr(C)]
766pub(crate) struct TileId(pub(crate) u32);
767
768impl From<etagere::AllocId> for TileId {
769 fn from(id: etagere::AllocId) -> Self {
770 Self(id.serialize())
771 }
772}
773
774impl From<TileId> for etagere::AllocId {
775 fn from(id: TileId) -> Self {
776 Self::deserialize(id.0)
777 }
778}
779
780pub(crate) struct PlatformInputHandler {
781 cx: AsyncWindowContext,
782 handler: Box<dyn InputHandler>,
783}
784
785#[cfg_attr(
786 all(
787 any(target_os = "linux", target_os = "freebsd"),
788 not(any(feature = "x11", feature = "wayland"))
789 ),
790 allow(dead_code)
791)]
792impl PlatformInputHandler {
793 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
794 Self { cx, handler }
795 }
796
797 fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
798 self.cx
799 .update(|window, cx| {
800 self.handler
801 .selected_text_range(ignore_disabled_input, window, cx)
802 })
803 .ok()
804 .flatten()
805 }
806
807 #[cfg_attr(target_os = "windows", allow(dead_code))]
808 fn marked_text_range(&mut self) -> Option<Range<usize>> {
809 self.cx
810 .update(|window, cx| self.handler.marked_text_range(window, cx))
811 .ok()
812 .flatten()
813 }
814
815 #[cfg_attr(
816 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
817 allow(dead_code)
818 )]
819 fn text_for_range(
820 &mut self,
821 range_utf16: Range<usize>,
822 adjusted: &mut Option<Range<usize>>,
823 ) -> Option<String> {
824 self.cx
825 .update(|window, cx| {
826 self.handler
827 .text_for_range(range_utf16, adjusted, window, cx)
828 })
829 .ok()
830 .flatten()
831 }
832
833 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
834 self.cx
835 .update(|window, cx| {
836 self.handler
837 .replace_text_in_range(replacement_range, text, window, cx);
838 })
839 .ok();
840 }
841
842 fn replace_and_mark_text_in_range(
843 &mut self,
844 range_utf16: Option<Range<usize>>,
845 new_text: &str,
846 new_selected_range: Option<Range<usize>>,
847 ) {
848 self.cx
849 .update(|window, cx| {
850 self.handler.replace_and_mark_text_in_range(
851 range_utf16,
852 new_text,
853 new_selected_range,
854 window,
855 cx,
856 )
857 })
858 .ok();
859 }
860
861 #[cfg_attr(target_os = "windows", allow(dead_code))]
862 fn unmark_text(&mut self) {
863 self.cx
864 .update(|window, cx| self.handler.unmark_text(window, cx))
865 .ok();
866 }
867
868 fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
869 self.cx
870 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
871 .ok()
872 .flatten()
873 }
874
875 #[allow(dead_code)]
876 fn apple_press_and_hold_enabled(&mut self) -> bool {
877 self.handler.apple_press_and_hold_enabled()
878 }
879
880 pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
881 self.handler.replace_text_in_range(None, input, window, cx);
882 }
883
884 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
885 let selection = self.handler.selected_text_range(true, window, cx)?;
886 self.handler.bounds_for_range(
887 if selection.reversed {
888 selection.range.start..selection.range.start
889 } else {
890 selection.range.end..selection.range.end
891 },
892 window,
893 cx,
894 )
895 }
896
897 #[allow(unused)]
898 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
899 self.cx
900 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
901 .ok()
902 .flatten()
903 }
904}
905
906/// A struct representing a selection in a text buffer, in UTF16 characters.
907/// This is different from a range because the head may be before the tail.
908#[derive(Debug)]
909pub struct UTF16Selection {
910 /// The range of text in the document this selection corresponds to
911 /// in UTF16 characters.
912 pub range: Range<usize>,
913 /// Whether the head of this selection is at the start (true), or end (false)
914 /// of the range
915 pub reversed: bool,
916}
917
918/// Zed's interface for handling text input from the platform's IME system
919/// This is currently a 1:1 exposure of the NSTextInputClient API:
920///
921/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
922pub trait InputHandler: 'static {
923 /// Get the range of the user's currently selected text, if any
924 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
925 ///
926 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
927 fn selected_text_range(
928 &mut self,
929 ignore_disabled_input: bool,
930 window: &mut Window,
931 cx: &mut App,
932 ) -> Option<UTF16Selection>;
933
934 /// Get the range of the currently marked text, if any
935 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
936 ///
937 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
938 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
939
940 /// Get the text for the given document range in UTF-16 characters
941 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
942 ///
943 /// range_utf16 is in terms of UTF-16 characters
944 fn text_for_range(
945 &mut self,
946 range_utf16: Range<usize>,
947 adjusted_range: &mut Option<Range<usize>>,
948 window: &mut Window,
949 cx: &mut App,
950 ) -> Option<String>;
951
952 /// Replace the text in the given document range with the given text
953 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
954 ///
955 /// replacement_range is in terms of UTF-16 characters
956 fn replace_text_in_range(
957 &mut self,
958 replacement_range: Option<Range<usize>>,
959 text: &str,
960 window: &mut Window,
961 cx: &mut App,
962 );
963
964 /// Replace the text in the given document range with the given text,
965 /// and mark the given text as part of an IME 'composing' state
966 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
967 ///
968 /// range_utf16 is in terms of UTF-16 characters
969 /// new_selected_range is in terms of UTF-16 characters
970 fn replace_and_mark_text_in_range(
971 &mut self,
972 range_utf16: Option<Range<usize>>,
973 new_text: &str,
974 new_selected_range: Option<Range<usize>>,
975 window: &mut Window,
976 cx: &mut App,
977 );
978
979 /// Remove the IME 'composing' state from the document
980 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
981 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
982
983 /// Get the bounds of the given document range in screen coordinates
984 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
985 ///
986 /// This is used for positioning the IME candidate window
987 fn bounds_for_range(
988 &mut self,
989 range_utf16: Range<usize>,
990 window: &mut Window,
991 cx: &mut App,
992 ) -> Option<Bounds<Pixels>>;
993
994 /// Get the character offset for the given point in terms of UTF16 characters
995 ///
996 /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
997 fn character_index_for_point(
998 &mut self,
999 point: Point<Pixels>,
1000 window: &mut Window,
1001 cx: &mut App,
1002 ) -> Option<usize>;
1003
1004 /// Allows a given input context to opt into getting raw key repeats instead of
1005 /// sending these to the platform.
1006 /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1007 /// (which is how iTerm does it) but it doesn't seem to work for me.
1008 #[allow(dead_code)]
1009 fn apple_press_and_hold_enabled(&mut self) -> bool {
1010 true
1011 }
1012}
1013
1014/// The variables that can be configured when creating a new window
1015#[derive(Debug)]
1016pub struct WindowOptions {
1017 /// Specifies the state and bounds of the window in screen coordinates.
1018 /// - `None`: Inherit the bounds.
1019 /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1020 pub window_bounds: Option<WindowBounds>,
1021
1022 /// The titlebar configuration of the window
1023 pub titlebar: Option<TitlebarOptions>,
1024
1025 /// Whether the window should be focused when created
1026 pub focus: bool,
1027
1028 /// Whether the window should be shown when created
1029 pub show: bool,
1030
1031 /// The kind of window to create
1032 pub kind: WindowKind,
1033
1034 /// Whether the window should be movable by the user
1035 pub is_movable: bool,
1036
1037 /// The display to create the window on, if this is None,
1038 /// the window will be created on the main display
1039 pub display_id: Option<DisplayId>,
1040
1041 /// The appearance of the window background.
1042 pub window_background: WindowBackgroundAppearance,
1043
1044 /// Application identifier of the window. Can by used by desktop environments to group applications together.
1045 pub app_id: Option<String>,
1046
1047 /// Window minimum size
1048 pub window_min_size: Option<Size<Pixels>>,
1049
1050 /// Whether to use client or server side decorations. Wayland only
1051 /// Note that this may be ignored.
1052 pub window_decorations: Option<WindowDecorations>,
1053}
1054
1055/// The variables that can be configured when creating a new window
1056#[derive(Debug)]
1057#[cfg_attr(
1058 all(
1059 any(target_os = "linux", target_os = "freebsd"),
1060 not(any(feature = "x11", feature = "wayland"))
1061 ),
1062 allow(dead_code)
1063)]
1064pub(crate) struct WindowParams {
1065 pub bounds: Bounds<Pixels>,
1066
1067 /// The titlebar configuration of the window
1068 #[cfg_attr(feature = "wayland", allow(dead_code))]
1069 pub titlebar: Option<TitlebarOptions>,
1070
1071 /// The kind of window to create
1072 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1073 pub kind: WindowKind,
1074
1075 /// Whether the window should be movable by the user
1076 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1077 pub is_movable: bool,
1078
1079 #[cfg_attr(
1080 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1081 allow(dead_code)
1082 )]
1083 pub focus: bool,
1084
1085 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1086 pub show: bool,
1087
1088 #[cfg_attr(feature = "wayland", allow(dead_code))]
1089 pub display_id: Option<DisplayId>,
1090
1091 pub window_min_size: Option<Size<Pixels>>,
1092}
1093
1094/// Represents the status of how a window should be opened.
1095#[derive(Debug, Copy, Clone, PartialEq)]
1096pub enum WindowBounds {
1097 /// Indicates that the window should open in a windowed state with the given bounds.
1098 Windowed(Bounds<Pixels>),
1099 /// Indicates that the window should open in a maximized state.
1100 /// The bounds provided here represent the restore size of the window.
1101 Maximized(Bounds<Pixels>),
1102 /// Indicates that the window should open in fullscreen mode.
1103 /// The bounds provided here represent the restore size of the window.
1104 Fullscreen(Bounds<Pixels>),
1105}
1106
1107impl Default for WindowBounds {
1108 fn default() -> Self {
1109 WindowBounds::Windowed(Bounds::default())
1110 }
1111}
1112
1113impl WindowBounds {
1114 /// Retrieve the inner bounds
1115 pub fn get_bounds(&self) -> Bounds<Pixels> {
1116 match self {
1117 WindowBounds::Windowed(bounds) => *bounds,
1118 WindowBounds::Maximized(bounds) => *bounds,
1119 WindowBounds::Fullscreen(bounds) => *bounds,
1120 }
1121 }
1122}
1123
1124impl Default for WindowOptions {
1125 fn default() -> Self {
1126 Self {
1127 window_bounds: None,
1128 titlebar: Some(TitlebarOptions {
1129 title: Default::default(),
1130 appears_transparent: Default::default(),
1131 traffic_light_position: Default::default(),
1132 }),
1133 focus: true,
1134 show: true,
1135 kind: WindowKind::Normal,
1136 is_movable: true,
1137 display_id: None,
1138 window_background: WindowBackgroundAppearance::default(),
1139 app_id: None,
1140 window_min_size: None,
1141 window_decorations: None,
1142 }
1143 }
1144}
1145
1146/// The options that can be configured for a window's titlebar
1147#[derive(Debug, Default)]
1148pub struct TitlebarOptions {
1149 /// The initial title of the window
1150 pub title: Option<SharedString>,
1151
1152 /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
1153 /// Refer to [`WindowOptions::window_decorations`] on Linux
1154 pub appears_transparent: bool,
1155
1156 /// The position of the macOS traffic light buttons
1157 pub traffic_light_position: Option<Point<Pixels>>,
1158}
1159
1160/// The kind of window to create
1161#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1162pub enum WindowKind {
1163 /// A normal application window
1164 Normal,
1165
1166 /// A window that appears above all other windows, usually used for alerts or popups
1167 /// use sparingly!
1168 PopUp,
1169}
1170
1171/// The appearance of the window, as defined by the operating system.
1172///
1173/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
1174/// values.
1175#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1176pub enum WindowAppearance {
1177 /// A light appearance.
1178 ///
1179 /// On macOS, this corresponds to the `aqua` appearance.
1180 Light,
1181
1182 /// A light appearance with vibrant colors.
1183 ///
1184 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
1185 VibrantLight,
1186
1187 /// A dark appearance.
1188 ///
1189 /// On macOS, this corresponds to the `darkAqua` appearance.
1190 Dark,
1191
1192 /// A dark appearance with vibrant colors.
1193 ///
1194 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
1195 VibrantDark,
1196}
1197
1198impl Default for WindowAppearance {
1199 fn default() -> Self {
1200 Self::Light
1201 }
1202}
1203
1204/// The appearance of the background of the window itself, when there is
1205/// no content or the content is transparent.
1206#[derive(Copy, Clone, Debug, Default, PartialEq)]
1207pub enum WindowBackgroundAppearance {
1208 /// Opaque.
1209 ///
1210 /// This lets the window manager know that content behind this
1211 /// window does not need to be drawn.
1212 ///
1213 /// Actual color depends on the system and themes should define a fully
1214 /// opaque background color instead.
1215 #[default]
1216 Opaque,
1217 /// Plain alpha transparency.
1218 Transparent,
1219 /// Transparency, but the contents behind the window are blurred.
1220 ///
1221 /// Not always supported.
1222 Blurred,
1223}
1224
1225/// The options that can be configured for a file dialog prompt
1226#[derive(Copy, Clone, Debug)]
1227pub struct PathPromptOptions {
1228 /// Should the prompt allow files to be selected?
1229 pub files: bool,
1230 /// Should the prompt allow directories to be selected?
1231 pub directories: bool,
1232 /// Should the prompt allow multiple files to be selected?
1233 pub multiple: bool,
1234}
1235
1236/// What kind of prompt styling to show
1237#[derive(Copy, Clone, Debug, PartialEq)]
1238pub enum PromptLevel {
1239 /// A prompt that is shown when the user should be notified of something
1240 Info,
1241
1242 /// A prompt that is shown when the user needs to be warned of a potential problem
1243 Warning,
1244
1245 /// A prompt that is shown when a critical problem has occurred
1246 Critical,
1247}
1248
1249/// Prompt Button
1250#[derive(Clone, Debug, PartialEq)]
1251pub enum PromptButton {
1252 /// Ok button
1253 Ok(SharedString),
1254 /// Cancel button
1255 Cancel(SharedString),
1256 /// Other button
1257 Other(SharedString),
1258}
1259
1260impl PromptButton {
1261 /// Create a button with label
1262 pub fn new(label: impl Into<SharedString>) -> Self {
1263 PromptButton::Other(label.into())
1264 }
1265
1266 /// Create an Ok button
1267 pub fn ok(label: impl Into<SharedString>) -> Self {
1268 PromptButton::Ok(label.into())
1269 }
1270
1271 /// Create a Cancel button
1272 pub fn cancel(label: impl Into<SharedString>) -> Self {
1273 PromptButton::Cancel(label.into())
1274 }
1275
1276 #[allow(dead_code)]
1277 pub(crate) fn is_cancel(&self) -> bool {
1278 matches!(self, PromptButton::Cancel(_))
1279 }
1280
1281 /// Returns the label of the button
1282 pub fn label(&self) -> &SharedString {
1283 match self {
1284 PromptButton::Ok(label) => label,
1285 PromptButton::Cancel(label) => label,
1286 PromptButton::Other(label) => label,
1287 }
1288 }
1289}
1290
1291impl From<&str> for PromptButton {
1292 fn from(value: &str) -> Self {
1293 match value.to_lowercase().as_str() {
1294 "ok" => PromptButton::Ok("Ok".into()),
1295 "cancel" => PromptButton::Cancel("Cancel".into()),
1296 _ => PromptButton::Other(SharedString::from(value.to_owned())),
1297 }
1298 }
1299}
1300
1301/// The style of the cursor (pointer)
1302#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1303pub enum CursorStyle {
1304 /// The default cursor
1305 Arrow,
1306
1307 /// A text input cursor
1308 /// corresponds to the CSS cursor value `text`
1309 IBeam,
1310
1311 /// A crosshair cursor
1312 /// corresponds to the CSS cursor value `crosshair`
1313 Crosshair,
1314
1315 /// A closed hand cursor
1316 /// corresponds to the CSS cursor value `grabbing`
1317 ClosedHand,
1318
1319 /// An open hand cursor
1320 /// corresponds to the CSS cursor value `grab`
1321 OpenHand,
1322
1323 /// A pointing hand cursor
1324 /// corresponds to the CSS cursor value `pointer`
1325 PointingHand,
1326
1327 /// A resize left cursor
1328 /// corresponds to the CSS cursor value `w-resize`
1329 ResizeLeft,
1330
1331 /// A resize right cursor
1332 /// corresponds to the CSS cursor value `e-resize`
1333 ResizeRight,
1334
1335 /// A resize cursor to the left and right
1336 /// corresponds to the CSS cursor value `ew-resize`
1337 ResizeLeftRight,
1338
1339 /// A resize up cursor
1340 /// corresponds to the CSS cursor value `n-resize`
1341 ResizeUp,
1342
1343 /// A resize down cursor
1344 /// corresponds to the CSS cursor value `s-resize`
1345 ResizeDown,
1346
1347 /// A resize cursor directing up and down
1348 /// corresponds to the CSS cursor value `ns-resize`
1349 ResizeUpDown,
1350
1351 /// A resize cursor directing up-left and down-right
1352 /// corresponds to the CSS cursor value `nesw-resize`
1353 ResizeUpLeftDownRight,
1354
1355 /// A resize cursor directing up-right and down-left
1356 /// corresponds to the CSS cursor value `nwse-resize`
1357 ResizeUpRightDownLeft,
1358
1359 /// A cursor indicating that the item/column can be resized horizontally.
1360 /// corresponds to the CSS cursor value `col-resize`
1361 ResizeColumn,
1362
1363 /// A cursor indicating that the item/row can be resized vertically.
1364 /// corresponds to the CSS cursor value `row-resize`
1365 ResizeRow,
1366
1367 /// A text input cursor for vertical layout
1368 /// corresponds to the CSS cursor value `vertical-text`
1369 IBeamCursorForVerticalLayout,
1370
1371 /// A cursor indicating that the operation is not allowed
1372 /// corresponds to the CSS cursor value `not-allowed`
1373 OperationNotAllowed,
1374
1375 /// A cursor indicating that the operation will result in a link
1376 /// corresponds to the CSS cursor value `alias`
1377 DragLink,
1378
1379 /// A cursor indicating that the operation will result in a copy
1380 /// corresponds to the CSS cursor value `copy`
1381 DragCopy,
1382
1383 /// A cursor indicating that the operation will result in a context menu
1384 /// corresponds to the CSS cursor value `context-menu`
1385 ContextualMenu,
1386
1387 /// Hide the cursor
1388 None,
1389}
1390
1391impl Default for CursorStyle {
1392 fn default() -> Self {
1393 Self::Arrow
1394 }
1395}
1396
1397/// A clipboard item that should be copied to the clipboard
1398#[derive(Clone, Debug, Eq, PartialEq)]
1399pub struct ClipboardItem {
1400 entries: Vec<ClipboardEntry>,
1401}
1402
1403/// Either a ClipboardString or a ClipboardImage
1404#[derive(Clone, Debug, Eq, PartialEq)]
1405pub enum ClipboardEntry {
1406 /// A string entry
1407 String(ClipboardString),
1408 /// An image entry
1409 Image(Image),
1410}
1411
1412impl ClipboardItem {
1413 /// Create a new ClipboardItem::String with no associated metadata
1414 pub fn new_string(text: String) -> Self {
1415 Self {
1416 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1417 }
1418 }
1419
1420 /// Create a new ClipboardItem::String with the given text and associated metadata
1421 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1422 Self {
1423 entries: vec![ClipboardEntry::String(ClipboardString {
1424 text,
1425 metadata: Some(metadata),
1426 })],
1427 }
1428 }
1429
1430 /// Create a new ClipboardItem::String with the given text and associated metadata
1431 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1432 Self {
1433 entries: vec![ClipboardEntry::String(
1434 ClipboardString::new(text).with_json_metadata(metadata),
1435 )],
1436 }
1437 }
1438
1439 /// Create a new ClipboardItem::Image with the given image with no associated metadata
1440 pub fn new_image(image: &Image) -> Self {
1441 Self {
1442 entries: vec![ClipboardEntry::Image(image.clone())],
1443 }
1444 }
1445
1446 /// Concatenates together all the ClipboardString entries in the item.
1447 /// Returns None if there were no ClipboardString entries.
1448 pub fn text(&self) -> Option<String> {
1449 let mut answer = String::new();
1450 let mut any_entries = false;
1451
1452 for entry in self.entries.iter() {
1453 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1454 answer.push_str(&text);
1455 any_entries = true;
1456 }
1457 }
1458
1459 if any_entries { Some(answer) } else { None }
1460 }
1461
1462 /// If this item is one ClipboardEntry::String, returns its metadata.
1463 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1464 pub fn metadata(&self) -> Option<&String> {
1465 match self.entries().first() {
1466 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1467 clipboard_string.metadata.as_ref()
1468 }
1469 _ => None,
1470 }
1471 }
1472
1473 /// Get the item's entries
1474 pub fn entries(&self) -> &[ClipboardEntry] {
1475 &self.entries
1476 }
1477
1478 /// Get owned versions of the item's entries
1479 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1480 self.entries.into_iter()
1481 }
1482}
1483
1484impl From<ClipboardString> for ClipboardEntry {
1485 fn from(value: ClipboardString) -> Self {
1486 Self::String(value)
1487 }
1488}
1489
1490impl From<String> for ClipboardEntry {
1491 fn from(value: String) -> Self {
1492 Self::from(ClipboardString::from(value))
1493 }
1494}
1495
1496impl From<Image> for ClipboardEntry {
1497 fn from(value: Image) -> Self {
1498 Self::Image(value)
1499 }
1500}
1501
1502impl From<ClipboardEntry> for ClipboardItem {
1503 fn from(value: ClipboardEntry) -> Self {
1504 Self {
1505 entries: vec![value],
1506 }
1507 }
1508}
1509
1510impl From<String> for ClipboardItem {
1511 fn from(value: String) -> Self {
1512 Self::from(ClipboardEntry::from(value))
1513 }
1514}
1515
1516impl From<Image> for ClipboardItem {
1517 fn from(value: Image) -> Self {
1518 Self::from(ClipboardEntry::from(value))
1519 }
1520}
1521
1522/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1523#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1524pub enum ImageFormat {
1525 // Sorted from most to least likely to be pasted into an editor,
1526 // which matters when we iterate through them trying to see if
1527 // clipboard content matches them.
1528 /// .png
1529 Png,
1530 /// .jpeg or .jpg
1531 Jpeg,
1532 /// .webp
1533 Webp,
1534 /// .gif
1535 Gif,
1536 /// .svg
1537 Svg,
1538 /// .bmp
1539 Bmp,
1540 /// .tif or .tiff
1541 Tiff,
1542}
1543
1544impl ImageFormat {
1545 /// Returns the mime type for the ImageFormat
1546 pub const fn mime_type(self) -> &'static str {
1547 match self {
1548 ImageFormat::Png => "image/png",
1549 ImageFormat::Jpeg => "image/jpeg",
1550 ImageFormat::Webp => "image/webp",
1551 ImageFormat::Gif => "image/gif",
1552 ImageFormat::Svg => "image/svg+xml",
1553 ImageFormat::Bmp => "image/bmp",
1554 ImageFormat::Tiff => "image/tiff",
1555 }
1556 }
1557
1558 /// Returns the ImageFormat for the given mime type
1559 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
1560 match mime_type {
1561 "image/png" => Some(Self::Png),
1562 "image/jpeg" | "image/jpg" => Some(Self::Jpeg),
1563 "image/webp" => Some(Self::Webp),
1564 "image/gif" => Some(Self::Gif),
1565 "image/svg+xml" => Some(Self::Svg),
1566 "image/bmp" => Some(Self::Bmp),
1567 "image/tiff" | "image/tif" => Some(Self::Tiff),
1568 _ => None,
1569 }
1570 }
1571}
1572
1573/// An image, with a format and certain bytes
1574#[derive(Clone, Debug, PartialEq, Eq)]
1575pub struct Image {
1576 /// The image format the bytes represent (e.g. PNG)
1577 pub format: ImageFormat,
1578 /// The raw image bytes
1579 pub bytes: Vec<u8>,
1580 /// The unique ID for the image
1581 id: u64,
1582}
1583
1584impl Hash for Image {
1585 fn hash<H: Hasher>(&self, state: &mut H) {
1586 state.write_u64(self.id);
1587 }
1588}
1589
1590impl Image {
1591 /// An empty image containing no data
1592 pub fn empty() -> Self {
1593 Self::from_bytes(ImageFormat::Png, Vec::new())
1594 }
1595
1596 /// Create an image from a format and bytes
1597 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
1598 Self {
1599 id: hash(&bytes),
1600 format,
1601 bytes,
1602 }
1603 }
1604
1605 /// Get this image's ID
1606 pub fn id(&self) -> u64 {
1607 self.id
1608 }
1609
1610 /// Use the GPUI `use_asset` API to make this image renderable
1611 pub fn use_render_image(
1612 self: Arc<Self>,
1613 window: &mut Window,
1614 cx: &mut App,
1615 ) -> Option<Arc<RenderImage>> {
1616 ImageSource::Image(self)
1617 .use_data(None, window, cx)
1618 .and_then(|result| result.ok())
1619 }
1620
1621 /// Use the GPUI `get_asset` API to make this image renderable
1622 pub fn get_render_image(
1623 self: Arc<Self>,
1624 window: &mut Window,
1625 cx: &mut App,
1626 ) -> Option<Arc<RenderImage>> {
1627 ImageSource::Image(self)
1628 .get_data(None, window, cx)
1629 .and_then(|result| result.ok())
1630 }
1631
1632 /// Use the GPUI `remove_asset` API to drop this image, if possible.
1633 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
1634 ImageSource::Image(self).remove_asset(cx);
1635 }
1636
1637 /// Convert the clipboard image to an `ImageData` object.
1638 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1639 fn frames_for_image(
1640 bytes: &[u8],
1641 format: image::ImageFormat,
1642 ) -> Result<SmallVec<[Frame; 1]>> {
1643 let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1644
1645 // Convert from RGBA to BGRA.
1646 for pixel in data.chunks_exact_mut(4) {
1647 pixel.swap(0, 2);
1648 }
1649
1650 Ok(SmallVec::from_elem(Frame::new(data), 1))
1651 }
1652
1653 let frames = match self.format {
1654 ImageFormat::Gif => {
1655 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1656 let mut frames = SmallVec::new();
1657
1658 for frame in decoder.into_frames() {
1659 let mut frame = frame?;
1660 // Convert from RGBA to BGRA.
1661 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1662 pixel.swap(0, 2);
1663 }
1664 frames.push(frame);
1665 }
1666
1667 frames
1668 }
1669 ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1670 ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1671 ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1672 ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1673 ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1674 ImageFormat::Svg => {
1675 let pixmap = svg_renderer.render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1676
1677 let buffer =
1678 image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1679 .unwrap();
1680
1681 SmallVec::from_elem(Frame::new(buffer), 1)
1682 }
1683 };
1684
1685 Ok(Arc::new(RenderImage::new(frames)))
1686 }
1687
1688 /// Get the format of the clipboard image
1689 pub fn format(&self) -> ImageFormat {
1690 self.format
1691 }
1692
1693 /// Get the raw bytes of the clipboard image
1694 pub fn bytes(&self) -> &[u8] {
1695 self.bytes.as_slice()
1696 }
1697}
1698
1699/// A clipboard item that should be copied to the clipboard
1700#[derive(Clone, Debug, Eq, PartialEq)]
1701pub struct ClipboardString {
1702 pub(crate) text: String,
1703 pub(crate) metadata: Option<String>,
1704}
1705
1706impl ClipboardString {
1707 /// Create a new clipboard string with the given text
1708 pub fn new(text: String) -> Self {
1709 Self {
1710 text,
1711 metadata: None,
1712 }
1713 }
1714
1715 /// Return a new clipboard item with the metadata replaced by the given metadata,
1716 /// after serializing it as JSON.
1717 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1718 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1719 self
1720 }
1721
1722 /// Get the text of the clipboard string
1723 pub fn text(&self) -> &String {
1724 &self.text
1725 }
1726
1727 /// Get the owned text of the clipboard string
1728 pub fn into_text(self) -> String {
1729 self.text
1730 }
1731
1732 /// Get the metadata of the clipboard string, formatted as JSON
1733 pub fn metadata_json<T>(&self) -> Option<T>
1734 where
1735 T: for<'a> Deserialize<'a>,
1736 {
1737 self.metadata
1738 .as_ref()
1739 .and_then(|m| serde_json::from_str(m).ok())
1740 }
1741
1742 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1743 pub(crate) fn text_hash(text: &str) -> u64 {
1744 let mut hasher = SeaHasher::new();
1745 text.hash(&mut hasher);
1746 hasher.finish()
1747 }
1748}
1749
1750impl From<String> for ClipboardString {
1751 fn from(value: String) -> Self {
1752 Self {
1753 text: value,
1754 metadata: None,
1755 }
1756 }
1757}