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