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