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