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