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