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