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