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