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