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