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