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