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