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