1mod app_menu;
2mod keyboard;
3mod keystroke;
4mod platform_info;
5
6#[cfg(all(target_os = "linux", feature = "wayland"))]
7#[expect(missing_docs)]
8pub mod layer_shell;
9
10pub mod popup;
12
13#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
14mod threaded_dispatcher;
15
16#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
17mod test;
18
19#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
20mod visual_test;
21
22#[cfg(all(
23 feature = "screen-capture",
24 any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
25))]
26pub mod scap_screen_capture;
27
28#[cfg(all(
29 any(target_os = "windows", target_os = "linux"),
30 feature = "screen-capture"
31))]
32pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
33#[cfg(not(feature = "screen-capture"))]
34pub(crate) type PlatformScreenCaptureFrame = ();
35#[cfg(all(target_os = "macos", feature = "screen-capture"))]
36pub(crate) type PlatformScreenCaptureFrame =
37 objc2_core_foundation::CFRetained<objc2_core_video::CVImageBuffer>;
38
39use crate::{
40 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds, Corners,
41 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
42 FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GlyphShadowParams, GpuSpecs, Hsla,
43 ImageSource, Keymap,
44 LineLayout, MissingGlyphSink, Pixels, PlatformGestures, PlatformInput, Point, Priority,
45 RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph,
46 ShapedRun, SharedString, Size, SvgRenderer, SystemWindowTab, Task, Window, WindowControlArea,
47 hash, point, px, size,
48};
49#[cfg(any(target_os = "linux", target_os = "freebsd"))]
50use anyhow::bail;
51use anyhow::{Context as _, Result};
52use async_task::Runnable;
53use collections::FxHashMap;
54use futures::channel::oneshot;
55use image::RgbaImage;
57use image::codecs::{gif::GifDecoder, webp::WebPDecoder};
58use image::{DynamicImage, Frame, Rgba};
59use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
60use scheduler::Instant;
61pub use scheduler::RunnableMeta;
62#[cfg(feature = "schemars")]
63use schemars::JsonSchema;
64use seahash::SeaHasher;
65use serde::{Deserialize, Serialize};
66use smallvec::SmallVec;
67use std::borrow::Cow;
68use std::collections::hash_map::Entry;
69use std::hash::{Hash, Hasher};
70use std::io::Cursor;
71use std::ops;
72use std::time::Duration;
73use std::{
74 ffi::OsString,
75 fmt::{self, Debug},
76 ops::Range,
77 path::{Path, PathBuf},
78 rc::Rc,
79 sync::Arc,
80};
81use uuid::Uuid;
82
83pub use app_menu::*;
84pub use keyboard::*;
85pub use keystroke::*;
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum WindowVisibility {
109 Visible,
112 Hidden,
115}
116
117impl WindowVisibility {
118 pub fn is_visible(self) -> bool {
120 self == Self::Visible
121 }
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
127#[non_exhaustive]
128pub enum DisplayEvent {
129 Added(DisplayId),
131 Removed(DisplayId),
134 Changed {
136 id: DisplayId,
138 changes: DisplayChanges,
140 },
141}
142
143bitflags::bitflags! {
144 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
146 pub struct DisplayChanges: u8 {
147 const BOUNDS = 1 << 0;
149 const REFRESH_INTERVAL = 1 << 1;
151 }
152}
153
154pub fn refresh_interval_from_hz(hertz: f64) -> Option<Duration> {
157 (hertz.is_finite() && hertz > 0.0).then(|| Duration::from_secs_f64(1.0 / hertz))
158}
159
160#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
167pub enum ActivationPolicy {
168 #[default]
170 Regular,
171 Accessory,
173}
174
175#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
176pub(crate) use test::*;
177
178#[cfg(any(test, feature = "test-support"))]
179pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
180
181#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
182pub use threaded_dispatcher::ThreadedDispatcher;
183
184#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
185pub use visual_test::VisualTestPlatform;
186
187pub struct ActivityGuard {
189 _release: gpui_util::Deferred<Box<dyn FnOnce() + Send>>,
190}
191
192impl ActivityGuard {
193 pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
195 Self {
196 _release: gpui_util::defer(Box::new(release)),
197 }
198 }
199
200 pub fn noop() -> Self {
202 Self::new(|| {})
203 }
204}
205
206#[cfg(any(target_os = "linux", target_os = "freebsd"))]
210#[inline]
211pub fn guess_compositor() -> &'static str {
212 if std::env::var_os("ZED_HEADLESS").is_some() {
213 return "headless";
214 }
215 GraphicalEnvironment::detect().guess_compositor()
216}
217
218#[cfg(any(target_os = "linux", target_os = "freebsd"))]
227#[derive(Clone, Debug, Default)]
228pub struct GraphicalEnvironment {
229 pub wayland_display: Option<OsString>,
231 pub x11_display: Option<OsString>,
233 pub xdg_runtime_dir: Option<OsString>,
235 pub current_desktop: Option<OsString>,
240 pub activation_token: Option<String>,
246}
247
248#[cfg(target_os = "windows")]
254#[derive(Clone, Debug, Default)]
255pub struct GraphicalEnvironment {
256 pub session_id: Option<u32>,
259}
260
261#[cfg(target_os = "windows")]
262impl GraphicalEnvironment {
263 pub fn detect() -> Self {
265 let mut session_id = 0;
266 let result = unsafe {
268 windows_sys::Win32::System::RemoteDesktop::ProcessIdToSessionId(
269 windows_sys::Win32::System::Threading::GetCurrentProcessId(),
270 &mut session_id,
271 )
272 };
273 Self {
274 session_id: (result != 0).then_some(session_id),
275 }
276 }
277
278 pub fn apply_to(&self, _command: &mut std::process::Command) {}
281
282 pub fn desktop_environment(&self) -> Option<String> {
284 None
285 }
286}
287
288#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
290#[derive(Clone, Debug, Default)]
291pub struct GraphicalEnvironment;
292
293#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
294impl GraphicalEnvironment {
295 pub fn detect() -> Self {
297 Self
298 }
299
300 pub fn apply_to(&self, _command: &mut std::process::Command) {}
302
303 pub fn desktop_environment(&self) -> Option<String> {
305 None
306 }
307}
308
309#[derive(Clone, Debug)]
311pub enum WindowingRequest {
312 Headless,
314 Windowed(GraphicalEnvironment),
316}
317
318#[cfg(any(target_os = "linux", target_os = "freebsd"))]
319impl GraphicalEnvironment {
320 pub fn detect() -> Self {
325 Self {
326 wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
327 x11_display: std::env::var_os("DISPLAY"),
328 xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
329 current_desktop: std::env::var_os("XDG_CURRENT_DESKTOP"),
330 activation_token: None,
331 }
332 }
333
334 pub fn apply_to(&self, command: &mut std::process::Command) {
338 for (name, value) in [
339 ("WAYLAND_DISPLAY", &self.wayland_display),
340 ("DISPLAY", &self.x11_display),
341 ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
342 ] {
343 match value {
344 Some(value) => command.env(name, value),
345 None => command.env_remove(name),
346 };
347 }
348 }
349
350 pub fn desktop_environment(&self) -> Option<String> {
355 self.current_desktop
356 .as_ref()
357 .and_then(|desktop| desktop.to_str())
358 .filter(|desktop| !desktop.is_empty())
359 .map(str::to_owned)
360 }
361
362 pub fn guess_compositor(&self) -> &'static str {
366 let is_set =
367 |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
368 if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
369 "Wayland"
370 } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
371 "X11"
372 } else {
373 "headless"
374 }
375 }
376}
377
378#[cfg(any(target_os = "linux", target_os = "freebsd"))]
379bitflags::bitflags! {
380 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
382 pub struct WindowingModes: u8 {
383 const WAYLAND = 1 << 0;
385 const X11 = 1 << 1;
387 const HEADLESS = 1 << 2;
389 }
390}
391
392pub use platform_info::{OperatingSystem, PlatformInfo, PlatformTarget};
393
394#[expect(missing_docs)]
395pub trait Platform: 'static {
396 fn platform_info(&self) -> PlatformInfo;
398
399 fn background_executor(&self) -> BackgroundExecutor;
400 fn foreground_executor(&self) -> ForegroundExecutor;
401 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
402
403 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
404 fn quit(&self);
405 fn set_initial_windowing(&self, _request: WindowingRequest) {}
410 fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
411 Task::ready(Err(anyhow::anyhow!(
412 "this platform cannot switch between headless and windowed modes"
413 )))
414 }
415 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
416 fn activate(&self, ignoring_other_apps: bool);
417 fn set_activation_policy(&self, _policy: ActivationPolicy) {}
419 fn hide(&self);
420 fn hide_other_apps(&self);
421 fn unhide_other_apps(&self);
422
423 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
424 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
425 fn on_displays_changed(&self, callback: Box<dyn FnMut()>);
430 fn active_window(&self) -> Option<AnyWindowHandle>;
431 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
432 None
433 }
434
435 fn is_screen_capture_supported(&self) -> bool {
436 false
437 }
438
439 fn screen_capture_sources(
440 &self,
441 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
442 let (sources_tx, sources_rx) = oneshot::channel();
443 sources_tx
444 .send(Err(anyhow::anyhow!(
445 "gpui was compiled without the screen-capture feature"
446 )))
447 .ok();
448 sources_rx
449 }
450
451 fn open_window(
452 &self,
453 handle: AnyWindowHandle,
454 options: WindowParams,
455 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
456
457 fn window_appearance(&self) -> WindowAppearance;
459
460 fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
469
470 fn button_layout(&self) -> Option<WindowButtonLayout> {
472 None
473 }
474
475 fn open_url(&self, url: &str);
476 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
477 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
478
479 fn prompt_for_paths(
480 &self,
481 options: PathPromptOptions,
482 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
483 fn prompt_for_new_path(
484 &self,
485 directory: &Path,
486 suggested_name: Option<&str>,
487 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
488 fn can_select_mixed_files_and_dirs(&self) -> bool;
489 fn reveal_path(&self, path: &Path);
490 fn open_with_system(&self, path: &Path);
491
492 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
493 fn on_reopen(&self, callback: Box<dyn FnMut()>);
494 fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
496 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
498
499 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
509
510 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
515
516 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
520 None
521 }
522
523 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
524 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
525 None
526 }
527
528 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
529 fn perform_dock_menu_action(&self, _action: usize) {}
530 fn add_recent_document(&self, _path: &Path) {}
531 fn update_jump_list(
532 &self,
533 _menus: Vec<MenuItem>,
534 _entries: Vec<SmallVec<[PathBuf; 2]>>,
535 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
536 Task::ready(Vec::new())
537 }
538 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
539 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
540 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
541
542 fn debug_state(&self) -> serde_json::Value {
544 serde_json::Value::Null
545 }
546
547 fn thermal_state(&self) -> ThermalState;
548 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
549 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
550
551 fn power_mode(&self) -> PowerMode {
554 PowerMode::Unknown
555 }
556 fn on_power_mode_change(&self, _callback: Box<dyn FnMut()>) {}
558
559 fn set_app_identity(&self, identifier: &str, name: &str) {
566 _ = (identifier, name);
567 }
568
569 fn show_system_notification(&self, notification: SystemNotification) {
576 _ = notification;
577 }
578
579 fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
587 _ = tag;
588 Task::ready(())
589 }
590
591 fn on_system_notification_response(
597 &self,
598 callback: Box<dyn FnMut(SystemNotificationResponse)>,
599 ) {
600 _ = callback;
601 }
602
603 fn compositor_name(&self) -> &'static str {
604 ""
605 }
606 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
609 None
610 }
611 fn app_path(&self) -> Result<PathBuf>;
612 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
613
614 fn set_cursor_style(&self, style: CursorStyle);
615
616 fn hide_cursor_until_mouse_moves(&self);
619
620 fn is_cursor_visible(&self) -> bool;
622
623 fn should_auto_hide_scrollbars(&self) -> bool;
624
625 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
626 fn write_to_clipboard(&self, item: ClipboardItem);
627
628 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
636 Task::ready(Ok(self.read_from_clipboard()))
637 }
638
639 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
640 fn read_from_primary(&self) -> Option<ClipboardItem>;
641 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
642 fn write_to_primary(&self, item: ClipboardItem);
643
644 #[cfg(target_os = "macos")]
645 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
646 #[cfg(target_os = "macos")]
647 fn write_to_find_pasteboard(&self, item: ClipboardItem);
648
649 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
650
651 #[cfg(target_os = "macos")]
655 fn write_credentials_if_not_exists(
656 &self,
657 _url: &str,
658 _username: &str,
659 _password: &[u8],
660 ) -> Task<Result<bool>> {
661 Task::ready(Err(anyhow::anyhow!(
662 "this platform does not support atomic credential writes"
663 )))
664 }
665
666 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
667 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
668
669 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
670 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
671 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
672}
673
674pub trait PlatformDisplay: Debug {
676 fn id(&self) -> DisplayId;
678
679 fn uuid(&self) -> Result<Uuid>;
682
683 fn bounds(&self) -> Bounds<Pixels>;
685
686 fn refresh_interval(&self) -> Option<Duration>;
693
694 fn visible_bounds(&self) -> Bounds<Pixels> {
698 self.bounds()
699 }
700
701 fn default_bounds(&self) -> Bounds<Pixels> {
703 let bounds = self.bounds();
704 let center = bounds.center();
705 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
706
707 let offset = clipped_window_size / 2.0;
708 let origin = point(center.x - offset.width, center.y - offset.height);
709 Bounds::new(origin, clipped_window_size)
710 }
711}
712
713#[derive(Clone, Debug, PartialEq, Eq)]
716pub struct SystemNotification {
717 pub tag: SharedString,
721 pub title: SharedString,
723 pub body: SharedString,
725 pub actions: Vec<SystemNotificationAction>,
728}
729
730#[derive(Clone, Debug, PartialEq, Eq, Hash)]
732pub struct SystemNotificationAction {
733 pub id: SharedString,
736 pub label: SharedString,
738}
739
740#[derive(Clone, Debug, PartialEq, Eq)]
742pub struct SystemNotificationResponse {
743 pub tag: SharedString,
745 pub action_id: Option<SharedString>,
748}
749
750#[derive(Debug, Clone, Copy, PartialEq, Eq)]
752pub enum PowerMode {
753 Unknown,
756 LowPower,
758 Balanced,
760 HighPower,
762}
763
764#[derive(Debug, Clone, Copy, PartialEq, Eq)]
766pub enum ThermalState {
767 Nominal,
769 Fair,
771 Serious,
773 Critical,
775}
776
777#[derive(Clone)]
779pub struct SourceMetadata {
780 pub id: u64,
782 pub label: Option<SharedString>,
784 pub is_main: Option<bool>,
786 pub resolution: Size<DevicePixels>,
788}
789
790pub trait ScreenCaptureSource {
792 fn metadata(&self) -> Result<SourceMetadata>;
794
795 fn stream(
798 &self,
799 foreground_executor: &ForegroundExecutor,
800 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
801 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
802}
803
804pub trait ScreenCaptureStream {
806 fn metadata(&self) -> Result<SourceMetadata>;
808}
809
810pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
812
813#[derive(PartialEq, Eq, Hash, Copy, Clone)]
815pub struct DisplayId(pub(crate) u64);
816
817impl DisplayId {
818 pub fn new(id: u64) -> Self {
820 Self(id)
821 }
822}
823
824impl From<u64> for DisplayId {
825 fn from(id: u64) -> Self {
826 Self(id)
827 }
828}
829
830impl From<DisplayId> for u64 {
831 fn from(id: DisplayId) -> Self {
832 id.0
833 }
834}
835
836impl Debug for DisplayId {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 write!(f, "DisplayId({})", self.0)
839 }
840}
841
842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
844pub enum ResizeEdge {
845 Top,
847 TopRight,
849 Right,
851 BottomRight,
853 Bottom,
855 BottomLeft,
857 Left,
859 TopLeft,
861}
862
863#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
865pub enum WindowDecorations {
866 #[default]
867 Server,
869 Client,
871}
872
873#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
875pub enum Decorations {
876 #[default]
878 Server,
879 Client {
881 tiling: Tiling,
883 },
884}
885
886#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
888pub struct WindowControls {
889 pub fullscreen: bool,
891 pub maximize: bool,
893 pub minimize: bool,
895 pub window_menu: bool,
897}
898
899impl Default for WindowControls {
900 fn default() -> Self {
901 Self {
903 fullscreen: true,
904 maximize: true,
905 minimize: true,
906 window_menu: true,
907 }
908 }
909}
910
911#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
913pub enum WindowButton {
914 Minimize,
916 Maximize,
918 Close,
920}
921
922impl WindowButton {
923 pub fn id(&self) -> &'static str {
925 match self {
926 WindowButton::Minimize => "minimize",
927 WindowButton::Maximize => "maximize",
928 WindowButton::Close => "close",
929 }
930 }
931
932 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
933 fn index(&self) -> usize {
934 match self {
935 WindowButton::Minimize => 0,
936 WindowButton::Maximize => 1,
937 WindowButton::Close => 2,
938 }
939 }
940}
941
942pub const MAX_BUTTONS_PER_SIDE: usize = 3;
944
945#[derive(Debug, Clone, Copy, PartialEq, Eq)]
950pub struct WindowButtonLayout {
951 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
953 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
955}
956
957#[cfg(any(target_os = "linux", target_os = "freebsd"))]
958impl WindowButtonLayout {
959 pub fn linux_default() -> Self {
961 Self {
962 left: [None; MAX_BUTTONS_PER_SIDE],
963 right: [
964 Some(WindowButton::Minimize),
965 Some(WindowButton::Maximize),
966 Some(WindowButton::Close),
967 ],
968 }
969 }
970
971 pub fn parse(layout_string: &str) -> Result<Self> {
973 fn parse_side(
974 s: &str,
975 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
976 unrecognized: &mut Vec<String>,
977 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
978 let mut result = [None; MAX_BUTTONS_PER_SIDE];
979 let mut i = 0;
980 for name in s.split(',') {
981 let trimmed = name.trim();
982 if trimmed.is_empty() {
983 continue;
984 }
985 let button = match trimmed {
986 "minimize" => Some(WindowButton::Minimize),
987 "maximize" => Some(WindowButton::Maximize),
988 "close" => Some(WindowButton::Close),
989 other => {
990 unrecognized.push(other.to_string());
991 None
992 }
993 };
994 if let Some(button) = button {
995 if seen_buttons[button.index()] {
996 continue;
997 }
998 if let Some(slot) = result.get_mut(i) {
999 *slot = Some(button);
1000 seen_buttons[button.index()] = true;
1001 i += 1;
1002 }
1003 }
1004 }
1005 result
1006 }
1007
1008 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1009 let mut unrecognized = Vec::new();
1010 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1011 let layout = Self {
1012 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1013 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1014 };
1015
1016 if !unrecognized.is_empty()
1017 && layout.left.iter().all(Option::is_none)
1018 && layout.right.iter().all(Option::is_none)
1019 {
1020 bail!(
1021 "button layout string {:?} contains no valid buttons (unrecognized: {})",
1022 layout_string,
1023 unrecognized.join(", ")
1024 );
1025 }
1026
1027 Ok(layout)
1028 }
1029
1030 #[cfg(test)]
1032 pub fn format(&self) -> String {
1033 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1034 buttons
1035 .iter()
1036 .flatten()
1037 .map(|button| match button {
1038 WindowButton::Minimize => "minimize",
1039 WindowButton::Maximize => "maximize",
1040 WindowButton::Close => "close",
1041 })
1042 .collect::<Vec<_>>()
1043 .join(",")
1044 }
1045
1046 format!("{}:{}", format_side(&self.left), format_side(&self.right))
1047 }
1048}
1049
1050#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1052pub struct Tiling {
1053 pub top: bool,
1055 pub left: bool,
1057 pub right: bool,
1059 pub bottom: bool,
1061}
1062
1063impl Tiling {
1064 pub fn tiled() -> Self {
1066 Self {
1067 top: true,
1068 left: true,
1069 right: true,
1070 bottom: true,
1071 }
1072 }
1073
1074 pub fn is_tiled(&self) -> bool {
1076 self.top || self.left || self.right || self.bottom
1077 }
1078}
1079
1080pub struct A11yCallbacks {
1082 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1084 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1086 pub deactivation: Box<dyn Fn() + Send + 'static>,
1088}
1089
1090#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1092pub enum FrameRequestSource {
1093 #[default]
1095 NativeCallback,
1096 LocalSchedule,
1098}
1099
1100#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1101#[expect(missing_docs)]
1102pub struct RequestFrameOptions {
1103 pub require_presentation: bool,
1105 pub force_render: bool,
1107 pub signal_at: Option<Instant>,
1113 pub signal_source: FrameRequestSource,
1115}
1116
1117pub struct PlatformFrameSignal {
1126 #[cfg(feature = "profiler")]
1127 origin: Instant,
1128 #[cfg(feature = "profiler")]
1129 first_signal: std::sync::atomic::AtomicU64,
1130}
1131
1132impl Default for PlatformFrameSignal {
1133 fn default() -> Self {
1134 Self::new()
1135 }
1136}
1137
1138impl PlatformFrameSignal {
1139 pub fn new() -> Self {
1141 Self {
1142 #[cfg(feature = "profiler")]
1143 origin: Instant::now(),
1144 #[cfg(feature = "profiler")]
1145 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1146 }
1147 }
1148
1149 #[inline]
1153 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1154 if cfg!(feature = "profiler") {
1155 Some(capture())
1156 } else {
1157 None
1158 }
1159 }
1160
1161 #[inline]
1163 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1164 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1165 #[cfg(feature = "profiler")]
1166 {
1167 let nanoseconds = at
1168 .saturating_duration_since(self.origin)
1169 .as_nanos()
1170 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1171 let source_bit = match source {
1172 FrameRequestSource::NativeCallback => 0,
1173 FrameRequestSource::LocalSchedule => 1,
1174 };
1175 self.first_signal.fetch_min(
1176 (nanoseconds << 1) | source_bit,
1177 std::sync::atomic::Ordering::Relaxed,
1178 );
1179 }
1180 }
1181
1182 #[inline]
1184 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1185 #[cfg(feature = "profiler")]
1186 {
1187 let signal = self
1188 .first_signal
1189 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1190 (signal != u64::MAX).then(|| {
1191 let source = match signal & 1 {
1192 0 => FrameRequestSource::NativeCallback,
1193 _ => FrameRequestSource::LocalSchedule,
1194 };
1195 (self.origin + Duration::from_nanos(signal >> 1), source)
1196 })
1197 }
1198 #[cfg(not(feature = "profiler"))]
1199 {
1200 None
1201 }
1202 }
1203}
1204
1205#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1218pub enum AppLifecyclePhase {
1219 Active,
1221 Inactive,
1223 Background,
1226 Foreground,
1228 Disconnected,
1232}
1233
1234#[derive(Debug, Clone, Default, PartialEq)]
1241pub struct WindowInsets {
1242 pub safe_area: Edges<Pixels>,
1247 pub ime: Edges<Pixels>,
1251 pub corner_radii: Corners<Pixels>,
1256}
1257
1258impl WindowInsets {
1259 pub fn effective(&self) -> Edges<Pixels> {
1261 Edges {
1262 top: self.safe_area.top.max(self.ime.top),
1263 right: self.safe_area.right.max(self.ime.right),
1264 bottom: self.safe_area.bottom.max(self.ime.bottom),
1265 left: self.safe_area.left.max(self.ime.left),
1266 }
1267 }
1268}
1269
1270#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1272pub enum TextInputStateChange {
1273 FocusGained,
1275 FocusLost,
1277 SelectionChanged,
1279 ContentChanged,
1281}
1282
1283#[expect(missing_docs)]
1284pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1285 fn bounds(&self) -> Bounds<Pixels>;
1286 fn is_maximized(&self) -> bool;
1287 fn window_bounds(&self) -> WindowBounds;
1288 fn content_size(&self) -> Size<Pixels>;
1289 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1295 Bounds::new(Point::default(), self.content_size())
1296 }
1297 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1302 fn prepare_frame(&self) -> bool {
1307 false
1308 }
1309 fn resize(&mut self, size: Size<Pixels>);
1310 fn scale_factor(&self) -> f32;
1311 fn appearance(&self) -> WindowAppearance;
1312 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1313 fn mouse_position(&self) -> Point<Pixels>;
1314 fn modifiers(&self) -> Modifiers;
1315 fn capslock(&self) -> Capslock;
1316 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1317 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1318 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1323 fn prompt(
1324 &self,
1325 level: PromptLevel,
1326 msg: &str,
1327 detail: Option<&str>,
1328 answers: &[PromptButton],
1329 ) -> Option<oneshot::Receiver<usize>>;
1330 fn activate(&self);
1331 fn show_window(
1337 &self,
1338 _activate: bool,
1339 _should_show: Box<dyn FnOnce() -> bool>,
1340 _completed: Box<dyn FnOnce(bool)>,
1341 ) -> bool {
1342 false
1343 }
1344 fn request_attention(&self) {}
1346 fn is_active(&self) -> bool;
1347 fn visibility(&self) -> WindowVisibility;
1350 fn is_hovered(&self) -> bool;
1351 fn background_appearance(&self) -> WindowBackgroundAppearance;
1352 fn set_title(&mut self, title: &str);
1353 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1354 fn is_background_appearance_drawn(&self) -> bool {
1359 true
1360 }
1361 fn minimize(&self);
1362 fn zoom(&self);
1363 fn toggle_fullscreen(&self);
1364 fn is_fullscreen(&self) -> bool;
1365 fn debug_state(&self) -> serde_json::Value {
1367 serde_json::Value::Null
1368 }
1369 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1370 None
1371 }
1372 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1373 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1374 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1375 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1379 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1380 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1381 fn on_moved(&self, callback: Box<dyn FnMut()>);
1382 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1386 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1387 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1388 fn on_hit_test_window_control_at(
1391 &self,
1392 mut callback: Box<dyn FnMut(Option<Point<Pixels>>) -> Option<WindowControlArea>>,
1393 ) {
1394 self.on_hit_test_window_control(Box::new(move || callback(None)));
1395 }
1396 fn on_close(&self, callback: Box<dyn FnOnce()>);
1397 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1398 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1399 fn draw(&self, scene: &Scene);
1400 fn schedule_frame(&self) {}
1401 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1402 fn is_subpixel_rendering_supported(&self) -> bool;
1403
1404 fn get_title(&self) -> String {
1406 String::new()
1407 }
1408 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1409 None
1410 }
1411 fn tab_bar_visible(&self) -> bool {
1412 false
1413 }
1414 fn set_edited(&mut self, _edited: bool) {}
1415 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1416 fn toggle_simple_fullscreen(&self) {}
1417 fn is_simple_fullscreen(&self) -> bool {
1418 false
1419 }
1420 #[cfg(target_os = "macos")]
1421 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1422 #[cfg(target_os = "macos")]
1423 fn set_native_titlebar_visibility(&self, _visible: bool) {}
1424 fn show_character_palette(&self) {}
1425 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1426 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1427 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1428 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1429 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1430 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1431 fn merge_all_windows(&self) {}
1432 fn move_tab_to_new_window(&self) {}
1433 fn toggle_window_tab_overview(&self) {}
1434 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1435
1436 fn native_window_state(&self) -> Option<Vec<u8>> {
1437 None
1438 }
1439 fn restore_native_window_state(&self, _state: &[u8]) {}
1440
1441 fn vn_composition_underlay(&self) -> Option<(usize, usize)> {
1446 None
1447 }
1448
1449 fn vn_set_maximized(&self, maximized: bool) {
1451 if self.is_maximized() != maximized {
1452 self.zoom();
1453 }
1454 }
1455 fn vn_is_zoomed(&self) -> bool {
1457 self.is_maximized()
1458 }
1459 fn vn_is_minimized(&self) -> bool {
1461 false
1462 }
1463 fn vn_unminimize(&self) {}
1465 fn vn_hide(&self) -> bool {
1467 false
1468 }
1469 fn vn_is_shown(&self) -> bool {
1471 true
1472 }
1473 fn vn_set_frame(&self, _origin: Option<Point<Pixels>>, _size: Option<Size<Pixels>>) -> bool {
1476 false
1477 }
1478 fn vn_set_always_on_top(&self, _on: bool) -> bool {
1480 false
1481 }
1482 fn vn_set_maximizable(&self, _maximizable: bool) {}
1484 fn vn_set_ignore_mouse(&self, _ignore: bool) -> bool {
1486 false
1487 }
1488 fn vn_set_content_protection(&self, _on: bool) -> bool {
1490 false
1491 }
1492 fn vn_request_close(&self) {}
1495
1496 fn lock_pointer(&self, _unadjusted: bool) -> Result<(), PointerLockError> {
1501 Err(PointerLockError::Unsupported)
1502 }
1503 fn unlock_pointer(&self) {}
1505 fn is_pointer_locked(&self) -> bool {
1507 false
1508 }
1509 fn take_pointer_motion(&self) -> Option<Point<Pixels>> {
1512 None
1513 }
1514
1515 fn inner_window_bounds(&self) -> WindowBounds {
1517 self.window_bounds()
1518 }
1519 fn request_decorations(&self, _decorations: WindowDecorations) {}
1520 fn show_window_menu(&self, _position: Point<Pixels>) {}
1521 fn start_window_move(&self) {}
1522 fn can_start_external_drag(&self) -> bool {
1523 false
1524 }
1525 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1526 false
1527 }
1528 fn start_window_resize(&self, _edge: ResizeEdge) {}
1529 fn set_exclusive_zone(&self, _zone: Pixels) {}
1530 #[cfg(all(target_os = "linux", feature = "wayland"))]
1531 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1532 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1533 fn window_decorations(&self) -> Decorations {
1534 Decorations::Server
1535 }
1536 fn set_app_id(&mut self, _app_id: &str) {}
1537 fn map_window(&mut self) -> anyhow::Result<()> {
1538 Ok(())
1539 }
1540 fn window_controls(&self) -> WindowControls {
1541 WindowControls::default()
1542 }
1543 fn set_client_inset(&self, _inset: Pixels) {}
1544 fn set_client_corner_radii(&self, _radii: Corners<Pixels>) {}
1545 fn gpu_specs(&self) -> Option<GpuSpecs>;
1546
1547 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1548
1549 fn insets(&self) -> WindowInsets {
1554 WindowInsets::default()
1555 }
1556
1557 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1563
1564 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1567
1568 fn set_back_enabled(&self, _enabled: bool) {}
1571
1572 fn show_soft_keyboard(&self) {}
1574
1575 fn hide_soft_keyboard(&self) {}
1577
1578 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1580
1581 fn play_system_bell(&self) {}
1582
1583 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1585
1586 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1588
1589 fn a11y_update_window_bounds(&self) {}
1591
1592 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1593 fn as_test(&mut self) -> Option<&mut TestWindow> {
1594 None
1595 }
1596
1597 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1602 anyhow::bail!("render_to_image not implemented for this platform")
1603 }
1604
1605 fn vn_supports_snapshots(&self) -> bool {
1608 false
1609 }
1610}
1611
1612#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1614pub enum PointerLockError {
1615 Unsupported,
1617 Refused,
1619}
1620
1621#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1623pub trait PlatformHeadlessRenderer {
1624 fn render_scene_to_image(
1626 &mut self,
1627 scene: &Scene,
1628 size: Size<DevicePixels>,
1629 ) -> Result<RgbaImage>;
1630
1631 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1637
1638 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1640}
1641
1642#[doc(hidden)]
1645pub type RunnableVariant = Runnable<RunnableMeta>;
1646
1647#[doc(hidden)]
1648pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1649
1650#[doc(hidden)]
1651pub enum TasksIncluded {
1652 OnlyCompleted,
1653 CompletedAndRunning,
1654}
1655
1656#[doc(hidden)]
1659pub trait PlatformDispatcher: Send + Sync {
1660 fn is_main_thread(&self) -> bool;
1661 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1662 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1663 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1664
1665 fn dispatch_on_main_thread_when_idle(
1666 &self,
1667 runnable: RunnableVariant,
1668 timeout: Option<Duration>,
1669 ) {
1670 let _ = timeout;
1671 self.dispatch_on_main_thread(runnable, Priority::Low);
1672 }
1673
1674 fn idle_time_remaining(&self) -> Option<Duration> {
1675 None
1676 }
1677
1678 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1679
1680 fn now(&self) -> Instant {
1681 Instant::now()
1682 }
1683
1684 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1685 gpui_util::defer(Box::new(|| {}))
1686 }
1687
1688 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1689 ActivityGuard::noop()
1690 }
1691
1692 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1693 fn as_test(&self) -> Option<&TestDispatcher> {
1694 None
1695 }
1696
1697 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1700 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1701 None
1702 }
1703}
1704
1705#[expect(missing_docs)]
1706pub trait PlatformTextSystem: Send + Sync {
1707 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1708 fn set_composed_families(&self, _families: Vec<(SharedString, crate::FamilyComposer)>) {}
1712 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1714 fn all_font_names(&self) -> Vec<String>;
1716 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1718 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1720 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1722 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1724 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1726 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1728 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1730 fn rasterize_glyph(
1732 &self,
1733 params: &RenderGlyphParams,
1734 raster_bounds: Bounds<DevicePixels>,
1735 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1736 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1738 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1740 -> TextRenderingMode;
1741 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1743 0
1744 }
1745}
1746
1747#[expect(missing_docs)]
1748pub struct NoopTextSystem;
1749
1750#[expect(missing_docs)]
1751impl NoopTextSystem {
1752 #[allow(dead_code)]
1753 pub fn new() -> Self {
1754 Self
1755 }
1756}
1757
1758impl PlatformTextSystem for NoopTextSystem {
1759 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1760 Ok(())
1761 }
1762
1763 fn all_font_names(&self) -> Vec<String> {
1764 Vec::new()
1765 }
1766
1767 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1768 Ok(FontId(1))
1769 }
1770
1771 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1772 FontMetrics {
1773 units_per_em: 1000,
1774 ascent: 1025.0,
1775 descent: -275.0,
1776 line_gap: 0.0,
1777 underline_position: -95.0,
1778 underline_thickness: 60.0,
1779 cap_height: 698.0,
1780 x_height: 516.0,
1781 bounding_box: Bounds {
1782 origin: Point {
1783 x: -260.0,
1784 y: -245.0,
1785 },
1786 size: Size {
1787 width: 1501.0,
1788 height: 1364.0,
1789 },
1790 },
1791 }
1792 }
1793
1794 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1795 Ok(Bounds {
1796 origin: Point { x: 54.0, y: 0.0 },
1797 size: size(392.0, 528.0),
1798 })
1799 }
1800
1801 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1802 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1803 }
1804
1805 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1806 Some(GlyphId(ch.len_utf16() as u32))
1807 }
1808
1809 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1810 Ok(Default::default())
1811 }
1812
1813 fn rasterize_glyph(
1814 &self,
1815 _params: &RenderGlyphParams,
1816 raster_bounds: Bounds<DevicePixels>,
1817 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1818 Ok((raster_bounds.size, Vec::new()))
1819 }
1820
1821 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1822 let mut position = px(0.);
1823 let metrics = self.font_metrics(FontId(0));
1824 let em_width = font_size
1825 * self
1826 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1827 .unwrap()
1828 .width
1829 / metrics.units_per_em as f32;
1830 let mut glyphs = Vec::new();
1831 for (ix, c) in text.char_indices() {
1832 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1833 glyphs.push(ShapedGlyph {
1834 id: glyph,
1835 position: point(position, px(0.)),
1836 index: ix,
1837 is_emoji: glyph.0 == 2,
1838 });
1839 if glyph.0 == 2 {
1840 position += em_width * 2.0;
1841 } else {
1842 position += em_width;
1843 }
1844 } else {
1845 position += em_width
1846 }
1847 }
1848 let mut runs = Vec::default();
1849 if !glyphs.is_empty() {
1850 runs.push(ShapedRun {
1851 font_id: FontId(0),
1852 glyphs,
1853 });
1854 } else {
1855 position = px(0.);
1856 }
1857
1858 LineLayout {
1859 font_size,
1860 width: position,
1861 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1862 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1863 runs,
1864 len: text.len(),
1865 }
1866 }
1867
1868 fn recommended_rendering_mode(
1869 &self,
1870 _font_id: FontId,
1871 _font_size: Pixels,
1872 ) -> TextRenderingMode {
1873 TextRenderingMode::Grayscale
1874 }
1875}
1876
1877#[allow(dead_code)]
1882pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1883 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1884 [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], ];
1898
1899 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1900 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1901
1902 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1903 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1904
1905 [
1906 ratios[0] * NORM13,
1907 ratios[1] * NORM24,
1908 ratios[2] * NORM13,
1909 ratios[3] * NORM24,
1910 ]
1911}
1912
1913#[derive(PartialEq, Eq, Hash, Clone)]
1914#[expect(missing_docs)]
1915pub enum AtlasKey {
1916 Glyph(RenderGlyphParams),
1917 GlyphShadow(GlyphShadowParams),
1918 Svg(RenderSvgParams),
1919 Image(RenderImageParams),
1920}
1921
1922impl AtlasKey {
1923 pub fn texture_kind(&self) -> AtlasTextureKind {
1925 match self {
1926 AtlasKey::Glyph(params) => {
1927 if params.is_emoji {
1928 AtlasTextureKind::Polychrome
1929 } else if params.subpixel_rendering {
1930 AtlasTextureKind::Subpixel
1931 } else {
1932 AtlasTextureKind::Monochrome
1933 }
1934 }
1935 AtlasKey::GlyphShadow(_) | AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1936 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1937 }
1938 }
1939}
1940
1941impl From<RenderGlyphParams> for AtlasKey {
1942 fn from(params: RenderGlyphParams) -> Self {
1943 Self::Glyph(params)
1944 }
1945}
1946
1947impl From<RenderSvgParams> for AtlasKey {
1948 fn from(params: RenderSvgParams) -> Self {
1949 Self::Svg(params)
1950 }
1951}
1952
1953impl From<RenderImageParams> for AtlasKey {
1954 fn from(params: RenderImageParams) -> Self {
1955 Self::Image(params)
1956 }
1957}
1958
1959#[expect(missing_docs)]
1960pub trait PlatformAtlas {
1961 fn get_or_insert_with<'a>(
1963 &self,
1964 key: AtlasKey,
1965 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1966 ) -> Result<Option<AtlasTile>>;
1967 fn remove(&self, key: &AtlasKey);
1968
1969 fn upload_from_gpu(
1996 &self,
1997 _key: &AtlasKey,
1998 _size: Size<DevicePixels>,
1999 _texture: GpuTextureHandle,
2000 ) -> Result<Option<AtlasTile>> {
2001 Ok(None)
2002 }
2003
2004 fn upload_from_d3d12(
2010 &self,
2011 _key: &AtlasKey,
2012 _size: Size<DevicePixels>,
2013 _texture: D3D12TextureHandle,
2014 _owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2015 ) -> Result<Option<AtlasTile>> {
2016 Ok(None)
2017 }
2018
2019 fn tile(&self, _key: &AtlasKey) -> Option<AtlasTile> {
2024 None
2025 }
2026
2027 fn write_bytes(
2035 &self,
2036 _key: &AtlasKey,
2037 _size: Size<DevicePixels>,
2038 _bytes: &[u8],
2039 ) -> Result<Option<AtlasTile>> {
2040 Ok(None)
2041 }
2042
2043 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2044 fn contains(&self, _key: &AtlasKey) -> bool {
2045 false
2046 }
2047
2048 fn stats(&self) -> Option<AtlasStats> {
2052 None
2053 }
2054}
2055
2056#[derive(Clone, Copy, Debug, Default)]
2058pub struct AtlasKindStats {
2059 pub pages: u32,
2061 pub bytes: u64,
2063 pub tiles: u32,
2065 pub tile_pixels: u64,
2068}
2069
2070#[derive(Clone, Copy, Debug, Default)]
2073pub struct AtlasStats {
2074 pub kinds: [AtlasKindStats; 3],
2076 pub keys: u32,
2078 pub image_keys: u32,
2080 pub image_pixels: u64,
2082}
2083
2084#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2093pub struct GpuTextureHandle(pub *mut std::ffi::c_void);
2094
2095#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2098pub struct D3D12TextureHandle {
2099 pub resource: *mut std::ffi::c_void,
2101 pub ready_fence: *mut std::ffi::c_void,
2103 pub ready_value: u64,
2105}
2106
2107#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2110pub enum TileSource {
2111 Bytes,
2115 Gpu(GpuTextureHandle),
2118}
2119
2120#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2122pub enum TileWrite {
2123 InPlace,
2127 Placed,
2131 Refused,
2134}
2135
2136impl GpuTextureHandle {
2137 pub const NULL: Self = Self(std::ptr::null_mut());
2139
2140 pub fn is_null(&self) -> bool {
2142 self.0.is_null()
2143 }
2144}
2145
2146#[doc(hidden)]
2147pub trait AtlasBackend {
2148 fn insert(
2149 &mut self,
2150 kind: AtlasTextureKind,
2151 size: Size<DevicePixels>,
2152 bytes: &[u8],
2153 ) -> Result<AtlasTile>;
2154
2155 fn remove(&mut self, tile: AtlasTile);
2156}
2157
2158#[doc(hidden)]
2159pub struct AtlasState<Backend> {
2160 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
2161 pub backend: Backend,
2162}
2163
2164impl<Backend> AtlasState<Backend> {
2165 pub fn new(backend: Backend) -> Self {
2166 Self {
2167 tiles_by_key: FxHashMap::default(),
2168 backend,
2169 }
2170 }
2171
2172 pub fn contains(&self, key: &AtlasKey) -> bool {
2173 self.tiles_by_key.contains_key(key)
2174 }
2175
2176 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
2177 self.tiles_by_key.clear();
2178 reset_backend(&mut self.backend);
2179 }
2180
2181 pub fn tile(&self, key: &AtlasKey) -> Option<AtlasTile> {
2185 self.tiles_by_key.get(key).copied()
2186 }
2187
2188 pub fn insert_tile(&mut self, key: AtlasKey, tile: AtlasTile) {
2192 self.tiles_by_key.insert(key, tile);
2193 }
2194
2195 pub fn count_keys(&self, stats: &mut AtlasStats) {
2199 stats.keys = self.tiles_by_key.len() as u32;
2200 for (key, tile) in &self.tiles_by_key {
2201 let pixels =
2202 (tile.bounds.size.width.0.max(0) as u64) * (tile.bounds.size.height.0.max(0) as u64);
2203 stats.kinds[tile.texture_id.kind as usize].tile_pixels += pixels;
2204 if let AtlasKey::Image(_) = key {
2205 stats.image_keys += 1;
2206 stats.image_pixels += pixels;
2207 }
2208 }
2209 }
2210}
2211
2212impl<Backend: Default> Default for AtlasState<Backend> {
2213 fn default() -> Self {
2214 Self::new(Backend::default())
2215 }
2216}
2217
2218impl<Backend: AtlasBackend> AtlasState<Backend> {
2219 pub fn get_or_insert_with<'a>(
2220 &mut self,
2221 key: AtlasKey,
2222 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2223 ) -> Result<Option<AtlasTile>> {
2224 match self.tiles_by_key.entry(key) {
2225 Entry::Occupied(entry) => Ok(Some(*entry.get())),
2226 Entry::Vacant(entry) => {
2227 profiling::scope!("new tile");
2228 let Some((size, bytes)) = build()? else {
2229 return Ok(None);
2230 };
2231 let tile = self
2232 .backend
2233 .insert(entry.key().texture_kind(), size, &bytes)?;
2234 entry.insert(tile);
2235 Ok(Some(tile))
2236 }
2237 }
2238 }
2239
2240 pub fn remove(&mut self, key: &AtlasKey) {
2241 if let Some(tile) = self.tiles_by_key.remove(key) {
2242 self.backend.remove(tile);
2243 }
2244 }
2245}
2246
2247#[derive(Default)]
2251pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
2252
2253#[doc(hidden)]
2254#[derive(Default)]
2255pub struct HeadlessAtlasBackend {
2256 next_id: u32,
2257}
2258
2259impl AtlasBackend for HeadlessAtlasBackend {
2260 fn insert(
2261 &mut self,
2262 kind: AtlasTextureKind,
2263 size: Size<DevicePixels>,
2264 _bytes: &[u8],
2265 ) -> Result<AtlasTile> {
2266 self.next_id += 1;
2267 let texture_id = self.next_id;
2268 self.next_id += 1;
2269 let tile_id = self.next_id;
2270 Ok(AtlasTile {
2271 texture_id: AtlasTextureId {
2272 index: texture_id,
2273 kind,
2274 },
2275 tile_id: TileId(tile_id),
2276 padding: 0,
2277 bounds: Bounds {
2278 origin: Point::default(),
2279 size,
2280 },
2281 })
2282 }
2283
2284 fn remove(&mut self, _tile: AtlasTile) {}
2285}
2286
2287impl PlatformAtlas for HeadlessAtlas {
2288 fn get_or_insert_with<'a>(
2289 &self,
2290 key: AtlasKey,
2291 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2292 ) -> Result<Option<AtlasTile>> {
2293 self.0.lock().get_or_insert_with(key, build)
2294 }
2295
2296 fn remove(&self, key: &AtlasKey) {
2297 self.0.lock().remove(key);
2298 }
2299
2300 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2301 fn contains(&self, key: &AtlasKey) -> bool {
2302 self.0.lock().contains(key)
2303 }
2304}
2305
2306#[doc(hidden)]
2307pub struct AtlasTextureList<T> {
2308 pub textures: Vec<Option<T>>,
2309 pub free_list: Vec<usize>,
2310}
2311
2312impl<T> Default for AtlasTextureList<T> {
2313 fn default() -> Self {
2314 Self {
2315 textures: Vec::default(),
2316 free_list: Vec::default(),
2317 }
2318 }
2319}
2320
2321impl<T> ops::Index<usize> for AtlasTextureList<T> {
2322 type Output = Option<T>;
2323
2324 fn index(&self, index: usize) -> &Self::Output {
2325 &self.textures[index]
2326 }
2327}
2328
2329impl<T> AtlasTextureList<T> {
2330 #[allow(unused)]
2331 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2332 self.free_list.clear();
2333 self.textures.drain(..)
2334 }
2335
2336 #[allow(dead_code)]
2337 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2338 self.textures.iter_mut().flatten()
2339 }
2340}
2341
2342#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2343#[repr(C)]
2344#[expect(missing_docs)]
2345pub struct AtlasTile {
2346 pub texture_id: AtlasTextureId,
2348 pub tile_id: TileId,
2350 pub padding: u32,
2352 pub bounds: Bounds<DevicePixels>,
2354}
2355
2356#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2357#[repr(C)]
2358#[expect(missing_docs)]
2359pub struct AtlasTextureId {
2360 pub index: u32,
2363 pub kind: AtlasTextureKind,
2365}
2366
2367#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2368#[repr(C)]
2369#[cfg_attr(
2370 all(
2371 any(target_os = "linux", target_os = "freebsd"),
2372 not(any(feature = "x11", feature = "wayland"))
2373 ),
2374 allow(dead_code)
2375)]
2376#[expect(missing_docs)]
2377pub enum AtlasTextureKind {
2378 Monochrome = 0,
2379 Polychrome = 1,
2380 Subpixel = 2,
2381}
2382
2383#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2384#[repr(C)]
2385#[expect(missing_docs)]
2386pub struct TileId(pub u32);
2387
2388impl From<etagere::AllocId> for TileId {
2389 fn from(id: etagere::AllocId) -> Self {
2390 Self(id.serialize())
2391 }
2392}
2393
2394impl From<TileId> for etagere::AllocId {
2395 fn from(id: TileId) -> Self {
2396 Self::deserialize(id.0)
2397 }
2398}
2399
2400#[expect(missing_docs)]
2401pub struct PlatformInputHandler {
2402 cx: AsyncWindowContext,
2403 handler: Box<dyn InputHandler>,
2404 focus_id: Option<crate::FocusId>,
2405}
2406
2407#[expect(missing_docs)]
2408#[cfg_attr(
2409 all(
2410 any(target_os = "linux", target_os = "freebsd"),
2411 not(any(feature = "x11", feature = "wayland"))
2412 ),
2413 allow(dead_code)
2414)]
2415impl PlatformInputHandler {
2416 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2417 Self {
2418 cx,
2419 handler,
2420 focus_id: None,
2421 }
2422 }
2423
2424 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2425 self.focus_id = Some(focus_id);
2426 self
2427 }
2428
2429 pub fn focus_id(&self) -> Option<crate::FocusId> {
2434 self.focus_id
2435 }
2436
2437 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2438 self.cx
2439 .update(|window, cx| {
2440 self.handler
2441 .selected_text_range(ignore_disabled_input, window, cx)
2442 })
2443 .ok()
2444 .flatten()
2445 }
2446
2447 #[cfg_attr(target_os = "windows", allow(dead_code))]
2448 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2449 self.cx
2450 .update(|window, cx| self.handler.marked_text_range(window, cx))
2451 .ok()
2452 .flatten()
2453 }
2454
2455 #[cfg_attr(
2456 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2457 allow(dead_code)
2458 )]
2459 pub fn text_for_range(
2460 &mut self,
2461 range_utf16: Range<usize>,
2462 adjusted: &mut Option<Range<usize>>,
2463 ) -> Option<String> {
2464 self.cx
2465 .update(|window, cx| {
2466 self.handler
2467 .text_for_range(range_utf16, adjusted, window, cx)
2468 })
2469 .ok()
2470 .flatten()
2471 }
2472
2473 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2474 self.cx
2475 .update(|window, cx| {
2476 self.handler
2477 .replace_text_in_range(replacement_range, text, window, cx);
2478 })
2479 .ok();
2480 }
2481
2482 pub fn replace_and_mark_text_in_range(
2483 &mut self,
2484 range_utf16: Option<Range<usize>>,
2485 new_text: &str,
2486 new_selected_range: Option<Range<usize>>,
2487 ) {
2488 self.cx
2489 .update(|window, cx| {
2490 self.handler.replace_and_mark_text_in_range(
2491 range_utf16,
2492 new_text,
2493 new_selected_range,
2494 window,
2495 cx,
2496 )
2497 })
2498 .ok();
2499 }
2500
2501 #[cfg_attr(target_os = "windows", allow(dead_code))]
2502 pub fn unmark_text(&mut self) {
2503 self.cx
2504 .update(|window, cx| self.handler.unmark_text(window, cx))
2505 .ok();
2506 }
2507
2508 pub fn paste(&mut self, item: ClipboardItem) {
2509 self.cx
2510 .update(|window, cx| self.handler.paste(item, window, cx))
2511 .ok();
2512 }
2513
2514 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2515 self.cx
2516 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2517 .ok()
2518 .flatten()
2519 }
2520
2521 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2522 self.cx
2523 .update(|window, cx| {
2524 self.handler
2525 .selection_bounds_for_range(range_utf16, window, cx)
2526 })
2527 .unwrap_or_default()
2528 }
2529
2530 #[allow(dead_code)]
2531 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2532 self.handler.apple_press_and_hold_enabled()
2533 }
2534
2535 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2536 self.handler.replace_text_in_range(None, input, window, cx);
2537 }
2538
2539 pub fn compute_ime_candidate_bounds(
2540 marked_range: Option<Range<usize>>,
2541 selection: &UTF16Selection,
2542 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2543 ) -> Option<Bounds<Pixels>> {
2544 if let Some(marked_range) = marked_range {
2545 let mut line_start = marked_range.start;
2547
2548 let caret = selection.range.end;
2552 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2553 for i in (marked_range.start..caret).rev() {
2554 if let Some(b) = bounds_for_range(i..i) {
2555 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2556 line_start = i + 1;
2557 break;
2558 }
2559 }
2560 }
2561 }
2562 bounds_for_range(line_start..line_start)
2563 } else {
2564 let offset = if selection.reversed {
2566 selection.range.start
2567 } else {
2568 selection.range.end
2569 };
2570 bounds_for_range(offset..offset)
2571 }
2572 }
2573
2574 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2575 let marked_range = self.handler.marked_text_range(window, cx);
2576 let selection = self.handler.selected_text_range(true, window, cx)?;
2577 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2578 self.handler.bounds_for_range(range, window, cx)
2579 })
2580 }
2581
2582 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2583 let marked_range = self.marked_text_range();
2584 let selection = self.selected_text_range(true)?;
2585 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2586 self.bounds_for_range(range)
2587 })
2588 }
2589
2590 #[allow(unused)]
2591 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2592 self.cx
2593 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2594 .ok()
2595 .flatten()
2596 }
2597
2598 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2600 self.cx
2601 .update(|window, cx| {
2602 self.handler
2603 .set_selected_text_range(range_utf16, window, cx)
2604 })
2605 .ok();
2606 }
2607
2608 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2610 self.cx
2611 .update(|window, cx| self.handler.element_bounds(window, cx))
2612 .ok()
2613 .flatten()
2614 }
2615
2616 pub fn text_length_utf16(&mut self) -> Option<usize> {
2618 self.cx
2619 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2620 .ok()
2621 .flatten()
2622 }
2623
2624 #[allow(dead_code)]
2625 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2626 self.handler.accepts_text_input(window, cx)
2627 }
2628
2629 #[allow(dead_code)]
2630 pub fn query_accepts_text_input(&mut self) -> bool {
2631 self.cx
2632 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2633 .unwrap_or(true)
2634 }
2635
2636 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2641 let focus_id = self.focus_id;
2642 self.cx
2643 .update(|window, cx| {
2644 focus_id.is_some()
2645 && window.focus == focus_id
2646 && self.handler.accepts_text_input(window, cx)
2647 })
2648 .unwrap_or(false)
2649 }
2650
2651 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2657 self.cx
2658 .update(|window, cx| {
2659 !window.has_pending_keystrokes()
2661 && self.handler.prefers_ime_for_printable_keys(window, cx)
2662 })
2663 .unwrap_or(false)
2664 }
2665
2666 pub fn text_input_configuration(
2668 &mut self,
2669 window: &mut Window,
2670 cx: &mut App,
2671 ) -> TextInputConfiguration {
2672 self.handler.text_input_configuration(window, cx)
2673 }
2674
2675 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2677 self.cx
2678 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2679 .ok()
2680 .flatten()
2681 }
2682}
2683
2684#[derive(Debug)]
2687pub struct UTF16Selection {
2688 pub range: Range<usize>,
2691 pub reversed: bool,
2694}
2695
2696pub trait InputHandler: 'static {
2701 fn selected_text_range(
2706 &mut self,
2707 ignore_disabled_input: bool,
2708 window: &mut Window,
2709 cx: &mut App,
2710 ) -> Option<UTF16Selection>;
2711
2712 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2717
2718 fn text_for_range(
2723 &mut self,
2724 range_utf16: Range<usize>,
2725 adjusted_range: &mut Option<Range<usize>>,
2726 window: &mut Window,
2727 cx: &mut App,
2728 ) -> Option<String>;
2729
2730 fn replace_text_in_range(
2735 &mut self,
2736 replacement_range: Option<Range<usize>>,
2737 text: &str,
2738 window: &mut Window,
2739 cx: &mut App,
2740 );
2741
2742 fn replace_and_mark_text_in_range(
2749 &mut self,
2750 range_utf16: Option<Range<usize>>,
2751 new_text: &str,
2752 new_selected_range: Option<Range<usize>>,
2753 window: &mut Window,
2754 cx: &mut App,
2755 );
2756
2757 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2760
2761 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2768 if let Some(text) = item.text() {
2769 self.replace_text_in_range(None, &text, window, cx);
2770 }
2771 }
2772
2773 fn bounds_for_range(
2778 &mut self,
2779 range_utf16: Range<usize>,
2780 window: &mut Window,
2781 cx: &mut App,
2782 ) -> Option<Bounds<Pixels>>;
2783
2784 fn selection_bounds_for_range(
2791 &mut self,
2792 _range_utf16: Range<usize>,
2793 _window: &mut Window,
2794 _cx: &mut App,
2795 ) -> Vec<Bounds<Pixels>> {
2796 Vec::new()
2797 }
2798
2799 fn character_index_for_point(
2803 &mut self,
2804 point: Point<Pixels>,
2805 window: &mut Window,
2806 cx: &mut App,
2807 ) -> Option<usize>;
2808
2809 fn set_selected_text_range(
2819 &mut self,
2820 _range_utf16: Range<usize>,
2821 _window: &mut Window,
2822 _cx: &mut App,
2823 ) {
2824 }
2825
2826 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2833 None
2834 }
2835
2836 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2838 None
2839 }
2840
2841 #[allow(dead_code)]
2846 fn apple_press_and_hold_enabled(&mut self) -> bool {
2847 true
2848 }
2849
2850 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2852 true
2853 }
2854
2855 fn text_input_editable_range(
2866 &mut self,
2867 _window: &mut Window,
2868 _cx: &mut App,
2869 ) -> Option<Range<usize>> {
2870 None
2871 }
2872
2873 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2882 false
2883 }
2884
2885 fn text_input_configuration(
2891 &mut self,
2892 _window: &mut Window,
2893 _cx: &mut App,
2894 ) -> TextInputConfiguration {
2895 TextInputConfiguration::default()
2896 }
2897}
2898
2899#[derive(Clone, Debug, Default, PartialEq, Eq)]
2909pub struct TextInputConfiguration {
2910 pub autocorrect: bool,
2912 pub autocapitalize: Autocapitalize,
2914 pub suggestions: bool,
2916 pub input_action: TextInputAction,
2918}
2919
2920#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2922pub enum Autocapitalize {
2923 #[default]
2925 None,
2926 Words,
2928 Sentences,
2930 Characters,
2932}
2933
2934#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2944pub enum TextInputAction {
2945 #[default]
2947 Unspecified,
2948 Enter,
2950 Done,
2952 Go,
2954 Next,
2956 Previous,
2958 Search,
2960 Send,
2962}
2963
2964#[derive(Debug)]
2966pub struct WindowOptions {
2967 pub window_bounds: Option<WindowBounds>,
2971
2972 pub titlebar: Option<TitlebarOptions>,
2974
2975 pub focus: bool,
2977
2978 pub show: bool,
2980
2981 pub kind: WindowKind,
2983
2984 pub is_movable: bool,
2988
2989 pub app_owns_titlebar_drag: bool,
3001
3002 pub inactive_frame_interval: Option<Duration>,
3007
3008 pub low_power_frame_interval: Option<Duration>,
3013
3014 pub thermal_frame_interval: Option<Duration>,
3019
3020 pub is_resizable: bool,
3022
3023 pub is_minimizable: bool,
3025
3026 pub display_id: Option<DisplayId>,
3029
3030 pub window_background: WindowBackgroundAppearance,
3032
3033 pub app_id: Option<String>,
3035
3036 pub window_min_size: Option<Size<Pixels>>,
3038
3039 pub window_decorations: Option<WindowDecorations>,
3042
3043 pub icon: Option<Arc<image::RgbaImage>>,
3045
3046 pub tabbing_identifier: Option<String>,
3048
3049 pub use_display_p3: bool,
3051}
3052
3053#[derive(Debug)]
3055#[cfg_attr(
3056 all(
3057 any(target_os = "linux", target_os = "freebsd"),
3058 not(any(feature = "x11", feature = "wayland"))
3059 ),
3060 allow(dead_code)
3061)]
3062#[allow(missing_docs)]
3063pub struct WindowParams {
3064 pub bounds: Bounds<Pixels>,
3065
3066 #[cfg_attr(feature = "wayland", allow(dead_code))]
3068 pub titlebar: Option<TitlebarOptions>,
3069
3070 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3072 pub kind: WindowKind,
3073
3074 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3076 pub is_movable: bool,
3077
3078 #[cfg_attr(
3080 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3081 allow(dead_code)
3082 )]
3083 pub app_owns_titlebar_drag: bool,
3084
3085 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3087 pub is_resizable: bool,
3088
3089 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3091 pub is_minimizable: bool,
3092
3093 #[cfg_attr(
3094 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3095 allow(dead_code)
3096 )]
3097 pub focus: bool,
3098
3099 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3100 pub show: bool,
3101
3102 #[cfg_attr(feature = "wayland", allow(dead_code))]
3104 pub icon: Option<Arc<image::RgbaImage>>,
3105
3106 #[cfg_attr(feature = "wayland", allow(dead_code))]
3107 pub display_id: Option<DisplayId>,
3108
3109 #[cfg_attr(feature = "wayland", allow(dead_code))]
3110 pub app_id: Option<String>,
3111
3112 pub window_min_size: Option<Size<Pixels>>,
3113
3114 #[cfg(target_os = "macos")]
3115 pub tabbing_identifier: Option<String>,
3116
3117 #[cfg(target_os = "macos")]
3118 pub use_display_p3: bool,
3119}
3120
3121#[derive(Debug, Copy, Clone, PartialEq)]
3123pub enum WindowBounds {
3124 Windowed(Bounds<Pixels>),
3126 Maximized(Bounds<Pixels>),
3129 Fullscreen(Bounds<Pixels>),
3132}
3133
3134impl Default for WindowBounds {
3135 fn default() -> Self {
3136 WindowBounds::Windowed(Bounds::default())
3137 }
3138}
3139
3140impl WindowBounds {
3141 pub fn get_bounds(&self) -> Bounds<Pixels> {
3143 match self {
3144 WindowBounds::Windowed(bounds) => *bounds,
3145 WindowBounds::Maximized(bounds) => *bounds,
3146 WindowBounds::Fullscreen(bounds) => *bounds,
3147 }
3148 }
3149
3150 pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
3153 WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
3154 }
3155}
3156
3157impl Default for WindowOptions {
3158 fn default() -> Self {
3159 Self {
3160 window_bounds: None,
3161 titlebar: Some(TitlebarOptions {
3162 title: Default::default(),
3163 appears_transparent: Default::default(),
3164 traffic_light_position: Default::default(),
3165 }),
3166 focus: true,
3167 show: true,
3168 kind: WindowKind::Normal,
3169 is_movable: true,
3170 app_owns_titlebar_drag: false,
3171 inactive_frame_interval: Some(Duration::from_micros(33_333)),
3172 low_power_frame_interval: Some(Duration::from_micros(33_333)),
3173 thermal_frame_interval: Some(Duration::from_micros(16_667)),
3174 is_resizable: true,
3175 is_minimizable: true,
3176 display_id: None,
3177 window_background: WindowBackgroundAppearance::default(),
3178 icon: None,
3179 app_id: None,
3180 window_min_size: None,
3181 window_decorations: None,
3182 tabbing_identifier: None,
3183 use_display_p3: false,
3184 }
3185 }
3186}
3187
3188#[derive(Debug, Default)]
3190pub struct TitlebarOptions {
3191 pub title: Option<SharedString>,
3193
3194 pub appears_transparent: bool,
3197
3198 pub traffic_light_position: Option<Point<Pixels>>,
3200}
3201
3202#[derive(Clone, Debug, PartialEq, Eq)]
3204pub enum WindowKind {
3205 Normal,
3207
3208 PopUp,
3211
3212 AnchoredPopup(popup::PopupOptions),
3219
3220 Floating,
3222
3223 #[cfg(all(target_os = "linux", feature = "wayland"))]
3226 LayerShell(layer_shell::LayerShellOptions),
3227
3228 Dialog,
3231}
3232
3233#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3238pub enum WindowAppearance {
3239 #[default]
3243 Light,
3244
3245 VibrantLight,
3249
3250 Dark,
3254
3255 VibrantDark,
3259}
3260
3261#[derive(Copy, Clone, Debug, Default, PartialEq)]
3264pub enum WindowBackgroundAppearance {
3265 #[default]
3273 Opaque,
3274 Transparent,
3276 Blurred,
3280 MicaBackdrop,
3282 MicaAltBackdrop,
3284 AcrylicBackdrop,
3287}
3288
3289#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3291pub enum TextRenderingMode {
3292 #[default]
3294 PlatformDefault,
3295 Subpixel,
3297 Grayscale,
3299}
3300
3301#[derive(Clone, Debug)]
3303pub struct PathPromptOptions {
3304 pub files: bool,
3306 pub directories: bool,
3308 pub multiple: bool,
3310 pub prompt: Option<SharedString>,
3312}
3313
3314#[derive(Copy, Clone, Debug, PartialEq)]
3316pub enum PromptLevel {
3317 Info,
3319
3320 Warning,
3322
3323 Critical,
3325}
3326
3327#[derive(Clone, Debug, PartialEq)]
3329pub enum PromptButton {
3330 Ok(SharedString),
3332 Cancel(SharedString),
3334 Other(SharedString),
3336}
3337
3338impl PromptButton {
3339 pub fn new(label: impl Into<SharedString>) -> Self {
3341 PromptButton::Other(label.into())
3342 }
3343
3344 pub fn ok(label: impl Into<SharedString>) -> Self {
3346 PromptButton::Ok(label.into())
3347 }
3348
3349 pub fn cancel(label: impl Into<SharedString>) -> Self {
3351 PromptButton::Cancel(label.into())
3352 }
3353
3354 #[allow(dead_code)]
3356 pub fn is_cancel(&self) -> bool {
3357 matches!(self, PromptButton::Cancel(_))
3358 }
3359
3360 pub fn label(&self) -> &SharedString {
3362 match self {
3363 PromptButton::Ok(label) => label,
3364 PromptButton::Cancel(label) => label,
3365 PromptButton::Other(label) => label,
3366 }
3367 }
3368}
3369
3370impl From<&str> for PromptButton {
3371 fn from(value: &str) -> Self {
3372 match value.to_lowercase().as_str() {
3373 "ok" => PromptButton::Ok("OK".into()),
3374 "cancel" => PromptButton::Cancel("Cancel".into()),
3375 _ => PromptButton::Other(SharedString::from(value.to_owned())),
3376 }
3377 }
3378}
3379
3380#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
3382#[cfg_attr(feature = "schemars", derive(JsonSchema))]
3383pub enum CursorStyle {
3384 #[default]
3386 Arrow,
3387
3388 IBeam,
3391
3392 Crosshair,
3395
3396 ClosedHand,
3399
3400 OpenHand,
3403
3404 PointingHand,
3407
3408 ResizeLeft,
3411
3412 ResizeRight,
3415
3416 ResizeLeftRight,
3419
3420 ResizeUp,
3423
3424 ResizeDown,
3427
3428 ResizeUpDown,
3431
3432 ResizeUpLeftDownRight,
3435
3436 ResizeUpRightDownLeft,
3439
3440 ResizeColumn,
3443
3444 ResizeRow,
3447
3448 IBeamCursorForVerticalLayout,
3451
3452 OperationNotAllowed,
3455
3456 DragLink,
3459
3460 DragCopy,
3463
3464 ContextualMenu,
3467}
3468
3469impl CursorStyle {
3470 pub const ALL: [Self; 21] = [
3472 Self::Arrow,
3473 Self::IBeam,
3474 Self::Crosshair,
3475 Self::ClosedHand,
3476 Self::OpenHand,
3477 Self::PointingHand,
3478 Self::ResizeLeft,
3479 Self::ResizeRight,
3480 Self::ResizeLeftRight,
3481 Self::ResizeUp,
3482 Self::ResizeDown,
3483 Self::ResizeUpDown,
3484 Self::ResizeUpLeftDownRight,
3485 Self::ResizeUpRightDownLeft,
3486 Self::ResizeColumn,
3487 Self::ResizeRow,
3488 Self::IBeamCursorForVerticalLayout,
3489 Self::OperationNotAllowed,
3490 Self::DragLink,
3491 Self::DragCopy,
3492 Self::ContextualMenu,
3493 ];
3494
3495 pub fn iter() -> impl Iterator<Item = Self> {
3497 Self::ALL.into_iter()
3498 }
3499}
3500
3501#[derive(Clone, Debug, Eq, PartialEq)]
3503pub struct ClipboardItem {
3504 pub entries: Vec<ClipboardEntry>,
3506}
3507
3508#[derive(Clone, Debug, PartialEq, Eq)]
3513pub enum ClipboardReadError {
3514 Unavailable,
3518 Denied(String),
3521 UnsupportedContent,
3524}
3525
3526impl std::fmt::Display for ClipboardReadError {
3527 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3528 match self {
3529 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3530 Self::Denied(message) => {
3531 write!(formatter, "clipboard access was denied: {message}")
3532 }
3533 Self::UnsupportedContent => {
3534 formatter.write_str("the clipboard contents are unsupported")
3535 }
3536 }
3537 }
3538}
3539
3540impl std::error::Error for ClipboardReadError {}
3541
3542#[derive(Clone, Debug, Eq, PartialEq)]
3544pub enum ClipboardEntry {
3545 String(ClipboardString),
3547 Image(Image),
3549 ExternalPaths(crate::ExternalPaths),
3551}
3552
3553impl ClipboardItem {
3554 pub fn new_string(text: String) -> Self {
3556 Self {
3557 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3558 }
3559 }
3560
3561 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3563 Self {
3564 entries: vec![ClipboardEntry::String(ClipboardString {
3565 text,
3566 metadata: Some(metadata),
3567 })],
3568 }
3569 }
3570
3571 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3573 Self {
3574 entries: vec![ClipboardEntry::String(
3575 ClipboardString::new(text).with_json_metadata(metadata),
3576 )],
3577 }
3578 }
3579
3580 pub fn new_image(image: &Image) -> Self {
3582 Self {
3583 entries: vec![ClipboardEntry::Image(image.clone())],
3584 }
3585 }
3586
3587 pub fn text(&self) -> Option<String> {
3590 let mut answer = String::new();
3591
3592 for entry in self.entries.iter() {
3593 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3594 answer.push_str(text);
3595 }
3596 }
3597
3598 if answer.is_empty() {
3599 for entry in self.entries.iter() {
3600 if let ClipboardEntry::ExternalPaths(paths) = entry {
3601 for path in &paths.0 {
3602 use std::fmt::Write as _;
3603 _ = write!(answer, "{}", path.display());
3604 }
3605 }
3606 }
3607 }
3608
3609 if !answer.is_empty() {
3610 Some(answer)
3611 } else {
3612 None
3613 }
3614 }
3615
3616 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3618 pub fn metadata(&self) -> Option<&String> {
3619 match self.entries().first() {
3620 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3621 clipboard_string.metadata.as_ref()
3622 }
3623 _ => None,
3624 }
3625 }
3626
3627 pub fn entries(&self) -> &[ClipboardEntry] {
3629 &self.entries
3630 }
3631
3632 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3634 self.entries.into_iter()
3635 }
3636}
3637
3638impl From<ClipboardString> for ClipboardEntry {
3639 fn from(value: ClipboardString) -> Self {
3640 Self::String(value)
3641 }
3642}
3643
3644impl From<String> for ClipboardEntry {
3645 fn from(value: String) -> Self {
3646 Self::from(ClipboardString::from(value))
3647 }
3648}
3649
3650impl From<Image> for ClipboardEntry {
3651 fn from(value: Image) -> Self {
3652 Self::Image(value)
3653 }
3654}
3655
3656impl From<ClipboardEntry> for ClipboardItem {
3657 fn from(value: ClipboardEntry) -> Self {
3658 Self {
3659 entries: vec![value],
3660 }
3661 }
3662}
3663
3664impl From<String> for ClipboardItem {
3665 fn from(value: String) -> Self {
3666 Self::from(ClipboardEntry::from(value))
3667 }
3668}
3669
3670impl From<Image> for ClipboardItem {
3671 fn from(value: Image) -> Self {
3672 Self::from(ClipboardEntry::from(value))
3673 }
3674}
3675
3676#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3678pub enum ImageFormat {
3679 Png,
3684 Jpeg,
3686 Webp,
3688 Gif,
3690 Svg,
3692 Bmp,
3694 Tiff,
3696 Ico,
3698 Pnm,
3700}
3701
3702impl ImageFormat {
3703 pub const ALL: [Self; 9] = [
3705 Self::Png,
3706 Self::Jpeg,
3707 Self::Webp,
3708 Self::Gif,
3709 Self::Svg,
3710 Self::Bmp,
3711 Self::Tiff,
3712 Self::Ico,
3713 Self::Pnm,
3714 ];
3715
3716 pub fn iter() -> impl Iterator<Item = Self> {
3718 Self::ALL.into_iter()
3719 }
3720
3721 pub const fn mime_type(self) -> &'static str {
3723 match self {
3724 ImageFormat::Png => "image/png",
3725 ImageFormat::Jpeg => "image/jpeg",
3726 ImageFormat::Webp => "image/webp",
3727 ImageFormat::Gif => "image/gif",
3728 ImageFormat::Svg => "image/svg+xml",
3729 ImageFormat::Bmp => "image/bmp",
3730 ImageFormat::Tiff => "image/tiff",
3731 ImageFormat::Ico => "image/ico",
3732 ImageFormat::Pnm => "image/x-portable-anymap",
3733 }
3734 }
3735
3736 pub const fn extension(self) -> &'static str {
3738 match self {
3739 ImageFormat::Png => "png",
3740 ImageFormat::Jpeg => "jpg",
3741 ImageFormat::Webp => "webp",
3742 ImageFormat::Gif => "gif",
3743 ImageFormat::Svg => "svg",
3744 ImageFormat::Bmp => "bmp",
3745 ImageFormat::Tiff => "tiff",
3746 ImageFormat::Ico => "ico",
3747 ImageFormat::Pnm => "pnm",
3748 }
3749 }
3750
3751 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3753 Self::iter()
3754 .find(|format| format.mime_type() == mime_type)
3755 .or_else(|| Self::from_mime_type_alias(mime_type))
3756 }
3757
3758 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3762 match mime_type {
3763 "image/jpg" => Some(Self::Jpeg),
3764 "image/tif" => Some(Self::Tiff),
3765 _ => None,
3766 }
3767 }
3768}
3769
3770#[derive(Clone, Debug, PartialEq, Eq)]
3772pub struct Image {
3773 pub format: ImageFormat,
3775 pub bytes: Vec<u8>,
3777 pub id: u64,
3779}
3780
3781pub(crate) fn decode_static_image(
3782 bytes: &[u8],
3783 format: image::ImageFormat,
3784) -> Result<SmallVec<[Frame; 1]>> {
3785 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3786 .into_decoder()
3787 .context("creating image decoder")?;
3788 decode_static_image_from_decoder(decoder)
3789}
3790
3791pub(crate) fn decode_static_image_from_decoder(
3792 mut decoder: impl image::ImageDecoder,
3793) -> Result<SmallVec<[Frame; 1]>> {
3794 let orientation = decoder
3795 .orientation()
3796 .context("reading decoder's orientation")?;
3797 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3798 image.apply_orientation(orientation);
3799
3800 let mut data = image.into_rgba8();
3801 for pixel in data.chunks_exact_mut(4) {
3802 pixel.swap(0, 2);
3803 }
3804
3805 Ok(SmallVec::from_elem(Frame::new(data), 1))
3806}
3807
3808fn decode_animated_frames<'a>(
3809 decoder: impl image::AnimationDecoder<'a>,
3810 format_name: &str,
3811) -> Result<SmallVec<[Frame; 1]>> {
3812 let mut frames = SmallVec::new();
3813
3814 for frame in decoder.into_frames() {
3815 match frame {
3816 Ok(mut frame) => {
3817 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3819 pixel.swap(0, 2);
3820 }
3821 frames.push(frame);
3822 }
3823 Err(err) => {
3824 log::debug!("Skipping {format_name} frame due to decode error: {err}");
3825 }
3826 }
3827 }
3828
3829 if frames.is_empty() {
3830 anyhow::bail!("{format_name} could not be decoded: all frames failed");
3831 }
3832
3833 Ok(frames)
3834}
3835
3836pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3837 let decoder = GifDecoder::new(Cursor::new(bytes))?;
3838 decode_animated_frames(decoder, "GIF")
3839}
3840
3841pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3842 let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
3843
3844 if decoder.has_animation() {
3845 let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
3846 decode_animated_frames(decoder, "WebP")
3847 } else {
3848 decode_static_image_from_decoder(decoder)
3849 }
3850}
3851
3852impl Hash for Image {
3853 fn hash<H: Hasher>(&self, state: &mut H) {
3854 state.write_u64(self.id);
3855 }
3856}
3857
3858impl Image {
3859 pub fn empty() -> Self {
3861 Self::from_bytes(ImageFormat::Png, Vec::new())
3862 }
3863
3864 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3866 Self {
3867 id: hash(&bytes),
3868 format,
3869 bytes,
3870 }
3871 }
3872
3873 pub fn id(&self) -> u64 {
3875 self.id
3876 }
3877
3878 pub fn use_render_image(
3880 self: Arc<Self>,
3881 window: &mut Window,
3882 cx: &mut App,
3883 ) -> Option<Arc<RenderImage>> {
3884 ImageSource::Image(self)
3885 .use_data(None, window, cx)
3886 .and_then(|result| result.ok())
3887 }
3888
3889 pub fn get_render_image(
3891 self: Arc<Self>,
3892 window: &mut Window,
3893 cx: &mut App,
3894 ) -> Option<Arc<RenderImage>> {
3895 ImageSource::Image(self)
3896 .get_data(None, window, cx)
3897 .and_then(|result| result.ok())
3898 }
3899
3900 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3902 ImageSource::Image(self).remove_asset(cx);
3903 }
3904
3905 #[cfg(any(test, feature = "test-support"))]
3908 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3909 ImageSource::Image(self.clone()).is_asset_cached(cx)
3910 }
3911
3912 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3914 let frames = match self.format {
3915 ImageFormat::Gif => decode_gif_image(&self.bytes)?,
3916 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3917 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3918 ImageFormat::Webp => decode_webp_image(&self.bytes)?,
3919 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3920 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3921 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3922 ImageFormat::Svg => {
3923 return svg_renderer
3924 .render_single_frame(&self.bytes, 1.0)
3925 .map_err(Into::into);
3926 }
3927 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3928 };
3929
3930 Ok(Arc::new(RenderImage::new(frames)))
3931 }
3932
3933 pub fn format(&self) -> ImageFormat {
3935 self.format
3936 }
3937
3938 pub fn bytes(&self) -> &[u8] {
3940 self.bytes.as_slice()
3941 }
3942}
3943
3944#[derive(Clone, Debug, Eq, PartialEq)]
3946pub struct ClipboardString {
3947 pub text: String,
3949 pub metadata: Option<String>,
3951}
3952
3953impl ClipboardString {
3954 pub fn new(text: String) -> Self {
3956 Self {
3957 text,
3958 metadata: None,
3959 }
3960 }
3961
3962 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3965 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3966 self
3967 }
3968
3969 pub fn text(&self) -> &String {
3971 &self.text
3972 }
3973
3974 pub fn into_text(self) -> String {
3976 self.text
3977 }
3978
3979 pub fn metadata_json<T>(&self) -> Option<T>
3981 where
3982 T: for<'a> Deserialize<'a>,
3983 {
3984 self.metadata
3985 .as_ref()
3986 .and_then(|m| serde_json::from_str(m).ok())
3987 }
3988
3989 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3990 pub fn text_hash(text: &str) -> u64 {
3992 let mut hasher = SeaHasher::new();
3993 text.hash(&mut hasher);
3994 hasher.finish()
3995 }
3996}
3997
3998impl From<String> for ClipboardString {
3999 fn from(value: String) -> Self {
4000 Self {
4001 text: value,
4002 metadata: None,
4003 }
4004 }
4005}
4006
4007#[cfg(test)]
4008mod image_tests {
4009 use super::*;
4010 use std::sync::Arc;
4011
4012 #[test]
4013 fn test_image_to_image_data_applies_exif_orientation() {
4014 let image = Image::from_bytes(
4015 ImageFormat::Jpeg,
4016 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
4017 );
4018
4019 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4020
4021 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
4022
4023 let bytes = render_image.as_bytes(0).unwrap();
4024 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
4025 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
4026 }
4027
4028 #[test]
4029 fn test_svg_image_to_image_data_converts_to_bgra() {
4030 let image = Image::from_bytes(
4031 ImageFormat::Svg,
4032 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
4033<rect width="1" height="1" fill="#38BDF8"/>
4034</svg>"##
4035 .to_vec(),
4036 );
4037
4038 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4039 let bytes = render_image.as_bytes(0).unwrap();
4040
4041 for pixel in bytes.chunks_exact(4) {
4042 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
4043 }
4044 }
4045
4046 #[test]
4047 fn test_animated_webp_image_to_image_data_decodes_frames() {
4048 const ANIMATED_WEBP: &[u8] = &[
4050 82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
4051 0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
4052 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 2, 86, 80, 56, 32, 48, 0,
4053 0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
4054 176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
4055 128, 255, 248, 242, 0, 0, 0, 65, 78, 77, 70, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4056 0, 0, 100, 0, 0, 0, 86, 80, 56, 32, 44, 0, 0, 0, 148, 1, 0, 157, 1, 42, 1, 0, 1, 0, 0,
4057 0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
4058 31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
4059 ];
4060
4061 let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
4062 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4063
4064 assert_eq!(render_image.frame_count(), 2);
4065 assert_eq!(render_image.size(0), size(1.into(), 1.into()));
4066 assert_eq!(
4067 Duration::from(render_image.delay(0)),
4068 Duration::from_millis(100)
4069 );
4070 assert_eq!(
4071 Duration::from(render_image.delay(1)),
4072 Duration::from_millis(100)
4073 );
4074 }
4075}
4076
4077#[cfg(test)]
4078mod atlas_tests {
4079 use super::*;
4080
4081 const TILE_SIZE: Size<DevicePixels> = Size {
4082 width: DevicePixels(1),
4083 height: DevicePixels(1),
4084 };
4085
4086 #[derive(Default)]
4087 struct RecordingAtlasBackend {
4088 insert_calls: u32,
4089 fail_next_insert: bool,
4090 removed_tiles: Vec<AtlasTile>,
4091 }
4092
4093 impl AtlasBackend for RecordingAtlasBackend {
4094 fn insert(
4095 &mut self,
4096 kind: AtlasTextureKind,
4097 size: Size<DevicePixels>,
4098 _bytes: &[u8],
4099 ) -> Result<AtlasTile> {
4100 self.insert_calls += 1;
4101 if std::mem::take(&mut self.fail_next_insert) {
4102 anyhow::bail!("backend failed");
4103 }
4104 Ok(AtlasTile {
4105 texture_id: AtlasTextureId { index: 0, kind },
4106 tile_id: TileId(self.insert_calls),
4107 padding: 0,
4108 bounds: Bounds {
4109 origin: Point::default(),
4110 size,
4111 },
4112 })
4113 }
4114
4115 fn remove(&mut self, tile: AtlasTile) {
4116 self.removed_tiles.push(tile);
4117 }
4118 }
4119
4120 fn image_key(image_id: usize) -> AtlasKey {
4121 AtlasKey::Image(RenderImageParams {
4122 image_id: crate::ImageId(image_id),
4123 frame_index: 0,
4124 })
4125 }
4126
4127 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
4128 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
4129 }
4130
4131 #[test]
4132 fn only_successful_inserts_are_cached() -> Result<()> {
4133 let mut state = AtlasState::new(RecordingAtlasBackend::default());
4134 let key = image_key(1);
4135
4136 assert_eq!(
4137 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
4138 None
4139 );
4140 state
4141 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
4142 .expect_err("builder error should propagate");
4143 assert!(!state.contains(&key));
4144 assert_eq!(state.backend.insert_calls, 0);
4145
4146 state.backend.fail_next_insert = true;
4147 state
4148 .get_or_insert_with(key.clone(), &mut build_tile)
4149 .expect_err("backend error should propagate");
4150 assert!(!state.contains(&key));
4151 assert_eq!(state.backend.insert_calls, 1);
4152
4153 let tile = state
4154 .get_or_insert_with(key.clone(), &mut build_tile)?
4155 .context("builder should produce a tile")?;
4156 assert_eq!(tile.texture_id.kind, key.texture_kind());
4157 assert_eq!(
4158 state.get_or_insert_with(key.clone(), &mut || {
4159 anyhow::bail!("cache hit must not call the builder")
4160 })?,
4161 Some(tile)
4162 );
4163 assert!(state.contains(&key));
4164 assert_eq!(state.backend.insert_calls, 2);
4165 Ok(())
4166 }
4167
4168 #[test]
4169 fn remove_and_clear_invalidate_keys() -> Result<()> {
4170 let mut state = AtlasState::new(RecordingAtlasBackend::default());
4171 let key = image_key(1);
4172 let other_key = image_key(2);
4173 let tile = state
4174 .get_or_insert_with(key.clone(), &mut build_tile)?
4175 .context("builder should produce a tile")?;
4176 state
4177 .get_or_insert_with(other_key.clone(), &mut build_tile)?
4178 .context("builder should produce another tile")?;
4179
4180 state.remove(&key);
4181 state.remove(&key);
4182 assert!(!state.contains(&key));
4183 assert!(state.contains(&other_key));
4184 assert_eq!(state.backend.removed_tiles, vec![tile]);
4185
4186 let mut reset_calls = 0;
4187 state.clear(|_| reset_calls += 1);
4188 assert_eq!(reset_calls, 1);
4189 assert!(!state.contains(&other_key));
4190 assert_eq!(state.backend.removed_tiles, vec![tile]);
4191 Ok(())
4192 }
4193}
4194
4195#[cfg(test)]
4196mod frame_signal_tests {
4197 use super::*;
4198
4199 #[cfg(feature = "profiler")]
4200 #[test]
4201 fn coalesced_signals_retain_the_earliest_until_drained() {
4202 for (first_source, later_source) in [
4203 (
4204 FrameRequestSource::NativeCallback,
4205 FrameRequestSource::LocalSchedule,
4206 ),
4207 (
4208 FrameRequestSource::LocalSchedule,
4209 FrameRequestSource::NativeCallback,
4210 ),
4211 ] {
4212 let signal = PlatformFrameSignal::new();
4213 let first =
4214 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
4215 assert_eq!(signal.take(), None);
4216 signal.record(first + Duration::from_millis(16), later_source);
4217 signal.record(first, first_source);
4218 signal.record(first + Duration::from_millis(32), later_source);
4219 assert_eq!(signal.take(), Some((first, first_source)));
4220 assert_eq!(signal.take(), None);
4221 let next = first + Duration::from_millis(48);
4222 signal.record(next, later_source);
4223 assert_eq!(signal.take(), Some((next, later_source)));
4224 }
4225 }
4226
4227 #[cfg(not(feature = "profiler"))]
4228 #[test]
4229 fn disabled_profiling_does_not_capture_or_store_timestamps() {
4230 let captured = PlatformFrameSignal::capture(|| {
4231 panic!("profiler-disabled builds must not evaluate the capture closure");
4232 });
4233 assert_eq!(captured, None);
4234 let signal = PlatformFrameSignal::new();
4235 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
4236 assert_eq!(signal.take(), None);
4237 }
4238}
4239
4240#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
4241mod tests {
4242 use super::*;
4243 use std::collections::HashSet;
4244
4245 #[test]
4246 fn test_refresh_interval_from_hz() {
4247 assert_eq!(
4248 refresh_interval_from_hz(50.0),
4249 Some(Duration::from_millis(20))
4250 );
4251 assert_eq!(
4252 refresh_interval_from_hz(120.0),
4253 Some(Duration::from_secs(1) / 120)
4254 );
4255 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
4256 assert_eq!(refresh_interval_from_hz(unknown), None);
4257 }
4258 }
4259
4260 #[test]
4261 fn test_window_button_layout_parse_standard() {
4262 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
4263 assert_eq!(
4264 layout.left,
4265 [
4266 Some(WindowButton::Close),
4267 Some(WindowButton::Minimize),
4268 None
4269 ]
4270 );
4271 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4272 }
4273
4274 #[test]
4275 fn test_window_button_layout_parse_right_only() {
4276 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
4277 assert_eq!(layout.left, [None, None, None]);
4278 assert_eq!(
4279 layout.right,
4280 [
4281 Some(WindowButton::Minimize),
4282 Some(WindowButton::Maximize),
4283 Some(WindowButton::Close)
4284 ]
4285 );
4286 }
4287
4288 #[test]
4289 fn test_window_button_layout_parse_left_only() {
4290 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
4291 assert_eq!(
4292 layout.left,
4293 [
4294 Some(WindowButton::Close),
4295 Some(WindowButton::Minimize),
4296 Some(WindowButton::Maximize)
4297 ]
4298 );
4299 assert_eq!(layout.right, [None, None, None]);
4300 }
4301
4302 #[test]
4303 fn test_window_button_layout_parse_with_whitespace() {
4304 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
4305 assert_eq!(
4306 layout.left,
4307 [
4308 Some(WindowButton::Close),
4309 Some(WindowButton::Minimize),
4310 None
4311 ]
4312 );
4313 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4314 }
4315
4316 #[test]
4317 fn test_window_button_layout_parse_empty() {
4318 let layout = WindowButtonLayout::parse("").unwrap();
4319 assert_eq!(layout.left, [None, None, None]);
4320 assert_eq!(layout.right, [None, None, None]);
4321 }
4322
4323 #[test]
4324 fn test_window_button_layout_parse_intentionally_empty() {
4325 let layout = WindowButtonLayout::parse(":").unwrap();
4326 assert_eq!(layout.left, [None, None, None]);
4327 assert_eq!(layout.right, [None, None, None]);
4328 }
4329
4330 #[test]
4331 fn test_window_button_layout_parse_invalid_buttons() {
4332 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
4333 assert_eq!(
4334 layout.left,
4335 [
4336 Some(WindowButton::Close),
4337 Some(WindowButton::Minimize),
4338 None
4339 ]
4340 );
4341 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4342 }
4343
4344 #[test]
4345 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
4346 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
4347 assert_eq!(
4348 layout.right,
4349 [
4350 Some(WindowButton::Close),
4351 Some(WindowButton::Minimize),
4352 None
4353 ]
4354 );
4355 assert_eq!(layout.format(), ":close,minimize");
4356 }
4357
4358 #[test]
4359 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
4360 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
4361 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4362 assert_eq!(
4363 layout.right,
4364 [
4365 Some(WindowButton::Maximize),
4366 Some(WindowButton::Minimize),
4367 None
4368 ]
4369 );
4370
4371 let button_ids: Vec<_> = layout
4372 .left
4373 .iter()
4374 .chain(layout.right.iter())
4375 .flatten()
4376 .map(WindowButton::id)
4377 .collect();
4378 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4379 assert_eq!(unique_button_ids.len(), button_ids.len());
4380 assert_eq!(layout.format(), "close:maximize,minimize");
4381 }
4382
4383 #[test]
4384 fn test_window_button_layout_parse_gnome_style() {
4385 let layout = WindowButtonLayout::parse("close").unwrap();
4386 assert_eq!(layout.left, [None, None, None]);
4387 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4388 }
4389
4390 #[test]
4391 fn test_window_button_layout_parse_elementary_style() {
4392 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4393 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4394 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4395 }
4396
4397 #[test]
4398 fn test_window_button_layout_round_trip() {
4399 let cases = [
4400 "close:minimize,maximize",
4401 "minimize,maximize,close:",
4402 ":close",
4403 "close:",
4404 "close:maximize",
4405 ":",
4406 ];
4407
4408 for case in cases {
4409 let layout = WindowButtonLayout::parse(case).unwrap();
4410 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4411 }
4412 }
4413
4414 #[test]
4415 fn test_window_button_layout_linux_default() {
4416 let layout = WindowButtonLayout::linux_default();
4417 assert_eq!(layout.left, [None, None, None]);
4418 assert_eq!(
4419 layout.right,
4420 [
4421 Some(WindowButton::Minimize),
4422 Some(WindowButton::Maximize),
4423 Some(WindowButton::Close)
4424 ]
4425 );
4426
4427 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4428 assert_eq!(round_tripped, layout);
4429 }
4430
4431 #[test]
4432 fn test_window_button_layout_parse_all_invalid() {
4433 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4434 }
4435}