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