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