1mod app_menu;
3mod keyboard;
4mod keystroke;
5mod platform_info;
6
7#[cfg(all(target_os = "linux", feature = "wayland"))]
8#[expect(missing_docs)]
9pub mod layer_shell;
10
11pub mod popup;
13
14#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
15mod threaded_dispatcher;
16
17#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
18mod test;
19
20#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
21mod visual_test;
22
23#[cfg(all(
24 feature = "screen-capture",
25 any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
26))]
27pub mod scap_screen_capture;
28
29#[cfg(all(
30 any(target_os = "windows", target_os = "linux"),
31 feature = "screen-capture"
32))]
33pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
34#[cfg(not(feature = "screen-capture"))]
35pub(crate) type PlatformScreenCaptureFrame = ();
36#[cfg(all(target_os = "macos", feature = "screen-capture"))]
37pub(crate) type PlatformScreenCaptureFrame =
38 objc2_core_foundation::CFRetained<objc2_core_video::CVImageBuffer>;
39
40use crate::{
41 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds, Corners,
42 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
43 FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GpuSpecs, Hsla, 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;
55#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
56use image::RgbaImage;
57use image::codecs::gif::GifDecoder;
58use image::{AnimationDecoder as _, DynamicImage, Frame};
59use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
60use scheduler::Instant;
61pub use scheduler::RunnableMeta;
62use schemars::JsonSchema;
63use seahash::SeaHasher;
64use serde::{Deserialize, Serialize};
65use smallvec::SmallVec;
66use std::borrow::Cow;
67use std::collections::hash_map::Entry;
68use std::hash::{Hash, Hasher};
69use std::io::Cursor;
70use std::ops;
71use std::time::Duration;
72use std::{
73 ffi::OsString,
74 fmt::{self, Debug},
75 ops::Range,
76 path::{Path, PathBuf},
77 rc::Rc,
78 sync::Arc,
79};
80use strum::EnumIter;
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 activation_token: Option<String>,
241}
242
243#[cfg(target_os = "windows")]
249#[derive(Clone, Debug, Default)]
250pub struct GraphicalEnvironment {
251 pub session_id: Option<u32>,
254}
255
256#[cfg(target_os = "windows")]
257impl GraphicalEnvironment {
258 pub fn detect() -> Self {
260 let mut session_id = 0;
261 let result = unsafe {
263 windows::Win32::System::RemoteDesktop::ProcessIdToSessionId(
264 windows::Win32::System::Threading::GetCurrentProcessId(),
265 &mut session_id,
266 )
267 };
268 Self {
269 session_id: result.is_ok().then_some(session_id),
270 }
271 }
272
273 pub fn apply_to(&self, _command: &mut std::process::Command) {}
276}
277
278#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
280#[derive(Clone, Debug, Default)]
281pub struct GraphicalEnvironment;
282
283#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
284impl GraphicalEnvironment {
285 pub fn detect() -> Self {
287 Self
288 }
289
290 pub fn apply_to(&self, _command: &mut std::process::Command) {}
292}
293
294#[derive(Clone, Debug)]
296pub enum WindowingRequest {
297 Headless,
299 Windowed(GraphicalEnvironment),
301}
302
303#[cfg(any(target_os = "linux", target_os = "freebsd"))]
304impl GraphicalEnvironment {
305 pub fn detect() -> Self {
310 Self {
311 wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
312 x11_display: std::env::var_os("DISPLAY"),
313 xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
314 activation_token: None,
315 }
316 }
317
318 pub fn apply_to(&self, command: &mut std::process::Command) {
322 for (name, value) in [
323 ("WAYLAND_DISPLAY", &self.wayland_display),
324 ("DISPLAY", &self.x11_display),
325 ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
326 ] {
327 match value {
328 Some(value) => command.env(name, value),
329 None => command.env_remove(name),
330 };
331 }
332 }
333
334 pub fn guess_compositor(&self) -> &'static str {
338 let is_set =
339 |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
340 if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
341 "Wayland"
342 } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
343 "X11"
344 } else {
345 "Headless"
346 }
347 }
348}
349
350#[cfg(any(target_os = "linux", target_os = "freebsd"))]
351bitflags::bitflags! {
352 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
354 pub struct WindowingModes: u8 {
355 const WAYLAND = 1 << 0;
357 const X11 = 1 << 1;
359 const HEADLESS = 1 << 2;
361 }
362}
363
364pub use platform_info::{OperatingSystem, PlatformInfo, PlatformTarget};
365
366#[expect(missing_docs)]
367pub trait Platform: 'static {
368 fn platform_info(&self) -> PlatformInfo;
370
371 fn background_executor(&self) -> BackgroundExecutor;
372 fn foreground_executor(&self) -> ForegroundExecutor;
373 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
374
375 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
376 fn quit(&self);
377 fn set_initial_windowing(&self, _request: WindowingRequest) {}
382 fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
383 Task::ready(Err(anyhow::anyhow!(
384 "this platform cannot switch between headless and windowed modes"
385 )))
386 }
387 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
388 fn activate(&self, ignoring_other_apps: bool);
389 fn set_activation_policy(&self, _policy: ActivationPolicy) {}
391 fn hide(&self);
392 fn hide_other_apps(&self);
393 fn unhide_other_apps(&self);
394
395 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
396 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
397 fn on_displays_changed(&self, callback: Box<dyn FnMut()>);
402 fn active_window(&self) -> Option<AnyWindowHandle>;
403 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
404 None
405 }
406
407 fn is_screen_capture_supported(&self) -> bool {
408 false
409 }
410
411 fn screen_capture_sources(
412 &self,
413 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
414 let (sources_tx, sources_rx) = oneshot::channel();
415 sources_tx
416 .send(Err(anyhow::anyhow!(
417 "gpui was compiled without the screen-capture feature"
418 )))
419 .ok();
420 sources_rx
421 }
422
423 fn open_window(
424 &self,
425 handle: AnyWindowHandle,
426 options: WindowParams,
427 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
428
429 fn window_appearance(&self) -> WindowAppearance;
431
432 fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
441
442 fn button_layout(&self) -> Option<WindowButtonLayout> {
444 None
445 }
446
447 fn open_url(&self, url: &str);
448 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
449 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
450
451 fn prompt_for_paths(
452 &self,
453 options: PathPromptOptions,
454 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
455 fn prompt_for_new_path(
456 &self,
457 directory: &Path,
458 suggested_name: Option<&str>,
459 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
460 fn can_select_mixed_files_and_dirs(&self) -> bool;
461 fn reveal_path(&self, path: &Path);
462 fn open_with_system(&self, path: &Path);
463
464 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
465 fn on_reopen(&self, callback: Box<dyn FnMut()>);
466 fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
468 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
470
471 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
481
482 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
487
488 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
492 None
493 }
494
495 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
496 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
497 None
498 }
499
500 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
501 fn perform_dock_menu_action(&self, _action: usize) {}
502 fn add_recent_document(&self, _path: &Path) {}
503 fn update_jump_list(
504 &self,
505 _menus: Vec<MenuItem>,
506 _entries: Vec<SmallVec<[PathBuf; 2]>>,
507 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
508 Task::ready(Vec::new())
509 }
510 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
511 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
512 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
513
514 fn thermal_state(&self) -> ThermalState;
515 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
516 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
517
518 fn set_app_identity(&self, identifier: &str, name: &str) {
525 _ = (identifier, name);
526 }
527
528 fn show_system_notification(&self, notification: SystemNotification) {
535 _ = notification;
536 }
537
538 fn dismiss_system_notification(&self, tag: &str) {
543 _ = tag;
544 }
545
546 fn on_system_notification_response(
552 &self,
553 callback: Box<dyn FnMut(SystemNotificationResponse)>,
554 ) {
555 _ = callback;
556 }
557
558 fn compositor_name(&self) -> &'static str {
559 ""
560 }
561 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
564 None
565 }
566 fn app_path(&self) -> Result<PathBuf>;
567 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
568
569 fn set_cursor_style(&self, style: CursorStyle);
570
571 fn hide_cursor_until_mouse_moves(&self);
574
575 fn is_cursor_visible(&self) -> bool;
577
578 fn should_auto_hide_scrollbars(&self) -> bool;
579
580 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
581 fn write_to_clipboard(&self, item: ClipboardItem);
582
583 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
591 Task::ready(Ok(self.read_from_clipboard()))
592 }
593
594 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
595 fn read_from_primary(&self) -> Option<ClipboardItem>;
596 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
597 fn write_to_primary(&self, item: ClipboardItem);
598
599 #[cfg(target_os = "macos")]
600 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
601 #[cfg(target_os = "macos")]
602 fn write_to_find_pasteboard(&self, item: ClipboardItem);
603
604 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
605
606 #[cfg(target_os = "macos")]
610 fn write_credentials_if_not_exists(
611 &self,
612 _url: &str,
613 _username: &str,
614 _password: &[u8],
615 ) -> Task<Result<bool>> {
616 Task::ready(Err(anyhow::anyhow!(
617 "this platform does not support atomic credential writes"
618 )))
619 }
620
621 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
622 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
623
624 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
625 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
626 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
627}
628
629pub trait PlatformDisplay: Debug {
631 fn id(&self) -> DisplayId;
633
634 fn uuid(&self) -> Result<Uuid>;
637
638 fn bounds(&self) -> Bounds<Pixels>;
640
641 fn refresh_interval(&self) -> Option<Duration>;
648
649 fn visible_bounds(&self) -> Bounds<Pixels> {
653 self.bounds()
654 }
655
656 fn default_bounds(&self) -> Bounds<Pixels> {
658 let bounds = self.bounds();
659 let center = bounds.center();
660 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
661
662 let offset = clipped_window_size / 2.0;
663 let origin = point(center.x - offset.width, center.y - offset.height);
664 Bounds::new(origin, clipped_window_size)
665 }
666}
667
668#[derive(Clone, Debug, PartialEq, Eq)]
671pub struct SystemNotification {
672 pub tag: SharedString,
676 pub title: SharedString,
678 pub body: SharedString,
680 pub actions: Vec<SystemNotificationAction>,
683}
684
685#[derive(Clone, Debug, PartialEq, Eq, Hash)]
687pub struct SystemNotificationAction {
688 pub id: SharedString,
691 pub label: SharedString,
693}
694
695#[derive(Clone, Debug, PartialEq, Eq)]
697pub struct SystemNotificationResponse {
698 pub tag: SharedString,
700 pub action_id: Option<SharedString>,
703}
704
705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
707pub enum ThermalState {
708 Nominal,
710 Fair,
712 Serious,
714 Critical,
716}
717
718#[derive(Clone)]
720pub struct SourceMetadata {
721 pub id: u64,
723 pub label: Option<SharedString>,
725 pub is_main: Option<bool>,
727 pub resolution: Size<DevicePixels>,
729}
730
731pub trait ScreenCaptureSource {
733 fn metadata(&self) -> Result<SourceMetadata>;
735
736 fn stream(
739 &self,
740 foreground_executor: &ForegroundExecutor,
741 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
742 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
743}
744
745pub trait ScreenCaptureStream {
747 fn metadata(&self) -> Result<SourceMetadata>;
749}
750
751pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
753
754#[derive(PartialEq, Eq, Hash, Copy, Clone)]
756pub struct DisplayId(pub(crate) u64);
757
758impl DisplayId {
759 pub fn new(id: u64) -> Self {
761 Self(id)
762 }
763}
764
765impl From<u64> for DisplayId {
766 fn from(id: u64) -> Self {
767 Self(id)
768 }
769}
770
771impl From<DisplayId> for u64 {
772 fn from(id: DisplayId) -> Self {
773 id.0
774 }
775}
776
777impl Debug for DisplayId {
778 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
779 write!(f, "DisplayId({})", self.0)
780 }
781}
782
783#[derive(Debug, Clone, Copy, PartialEq, Eq)]
785pub enum ResizeEdge {
786 Top,
788 TopRight,
790 Right,
792 BottomRight,
794 Bottom,
796 BottomLeft,
798 Left,
800 TopLeft,
802}
803
804#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
806pub enum WindowDecorations {
807 #[default]
808 Server,
810 Client,
812}
813
814#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
816pub enum Decorations {
817 #[default]
819 Server,
820 Client {
822 tiling: Tiling,
824 },
825}
826
827#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
829pub struct WindowControls {
830 pub fullscreen: bool,
832 pub maximize: bool,
834 pub minimize: bool,
836 pub window_menu: bool,
838}
839
840impl Default for WindowControls {
841 fn default() -> Self {
842 Self {
844 fullscreen: true,
845 maximize: true,
846 minimize: true,
847 window_menu: true,
848 }
849 }
850}
851
852#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
854pub enum WindowButton {
855 Minimize,
857 Maximize,
859 Close,
861}
862
863impl WindowButton {
864 pub fn id(&self) -> &'static str {
866 match self {
867 WindowButton::Minimize => "minimize",
868 WindowButton::Maximize => "maximize",
869 WindowButton::Close => "close",
870 }
871 }
872
873 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
874 fn index(&self) -> usize {
875 match self {
876 WindowButton::Minimize => 0,
877 WindowButton::Maximize => 1,
878 WindowButton::Close => 2,
879 }
880 }
881}
882
883pub const MAX_BUTTONS_PER_SIDE: usize = 3;
885
886#[derive(Debug, Clone, Copy, PartialEq, Eq)]
891pub struct WindowButtonLayout {
892 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
894 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
896}
897
898#[cfg(any(target_os = "linux", target_os = "freebsd"))]
899impl WindowButtonLayout {
900 pub fn linux_default() -> Self {
902 Self {
903 left: [None; MAX_BUTTONS_PER_SIDE],
904 right: [
905 Some(WindowButton::Minimize),
906 Some(WindowButton::Maximize),
907 Some(WindowButton::Close),
908 ],
909 }
910 }
911
912 pub fn parse(layout_string: &str) -> Result<Self> {
914 fn parse_side(
915 s: &str,
916 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
917 unrecognized: &mut Vec<String>,
918 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
919 let mut result = [None; MAX_BUTTONS_PER_SIDE];
920 let mut i = 0;
921 for name in s.split(',') {
922 let trimmed = name.trim();
923 if trimmed.is_empty() {
924 continue;
925 }
926 let button = match trimmed {
927 "minimize" => Some(WindowButton::Minimize),
928 "maximize" => Some(WindowButton::Maximize),
929 "close" => Some(WindowButton::Close),
930 other => {
931 unrecognized.push(other.to_string());
932 None
933 }
934 };
935 if let Some(button) = button {
936 if seen_buttons[button.index()] {
937 continue;
938 }
939 if let Some(slot) = result.get_mut(i) {
940 *slot = Some(button);
941 seen_buttons[button.index()] = true;
942 i += 1;
943 }
944 }
945 }
946 result
947 }
948
949 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
950 let mut unrecognized = Vec::new();
951 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
952 let layout = Self {
953 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
954 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
955 };
956
957 if !unrecognized.is_empty()
958 && layout.left.iter().all(Option::is_none)
959 && layout.right.iter().all(Option::is_none)
960 {
961 bail!(
962 "button layout string {:?} contains no valid buttons (unrecognized: {})",
963 layout_string,
964 unrecognized.join(", ")
965 );
966 }
967
968 Ok(layout)
969 }
970
971 #[cfg(test)]
973 pub fn format(&self) -> String {
974 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
975 buttons
976 .iter()
977 .flatten()
978 .map(|button| match button {
979 WindowButton::Minimize => "minimize",
980 WindowButton::Maximize => "maximize",
981 WindowButton::Close => "close",
982 })
983 .collect::<Vec<_>>()
984 .join(",")
985 }
986
987 format!("{}:{}", format_side(&self.left), format_side(&self.right))
988 }
989}
990
991#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
993pub struct Tiling {
994 pub top: bool,
996 pub left: bool,
998 pub right: bool,
1000 pub bottom: bool,
1002}
1003
1004impl Tiling {
1005 pub fn tiled() -> Self {
1007 Self {
1008 top: true,
1009 left: true,
1010 right: true,
1011 bottom: true,
1012 }
1013 }
1014
1015 pub fn is_tiled(&self) -> bool {
1017 self.top || self.left || self.right || self.bottom
1018 }
1019}
1020
1021pub struct A11yCallbacks {
1023 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1025 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1027 pub deactivation: Box<dyn Fn() + Send + 'static>,
1029}
1030
1031#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1033pub enum FrameRequestSource {
1034 #[default]
1036 NativeCallback,
1037 LocalSchedule,
1039}
1040
1041#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1042#[expect(missing_docs)]
1043pub struct RequestFrameOptions {
1044 pub require_presentation: bool,
1046 pub force_render: bool,
1048 pub signal_at: Option<Instant>,
1054 pub signal_source: FrameRequestSource,
1056}
1057
1058pub struct PlatformFrameSignal {
1067 #[cfg(feature = "profiler")]
1068 origin: Instant,
1069 #[cfg(feature = "profiler")]
1070 first_signal: std::sync::atomic::AtomicU64,
1071}
1072
1073impl Default for PlatformFrameSignal {
1074 fn default() -> Self {
1075 Self::new()
1076 }
1077}
1078
1079impl PlatformFrameSignal {
1080 pub fn new() -> Self {
1082 Self {
1083 #[cfg(feature = "profiler")]
1084 origin: Instant::now(),
1085 #[cfg(feature = "profiler")]
1086 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1087 }
1088 }
1089
1090 #[inline]
1094 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1095 if cfg!(feature = "profiler") {
1096 Some(capture())
1097 } else {
1098 None
1099 }
1100 }
1101
1102 #[inline]
1104 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1105 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1106 #[cfg(feature = "profiler")]
1107 {
1108 let nanoseconds = at
1109 .saturating_duration_since(self.origin)
1110 .as_nanos()
1111 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1112 let source_bit = match source {
1113 FrameRequestSource::NativeCallback => 0,
1114 FrameRequestSource::LocalSchedule => 1,
1115 };
1116 self.first_signal.fetch_min(
1117 (nanoseconds << 1) | source_bit,
1118 std::sync::atomic::Ordering::Relaxed,
1119 );
1120 }
1121 }
1122
1123 #[inline]
1125 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1126 #[cfg(feature = "profiler")]
1127 {
1128 let signal = self
1129 .first_signal
1130 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1131 (signal != u64::MAX).then(|| {
1132 let source = match signal & 1 {
1133 0 => FrameRequestSource::NativeCallback,
1134 _ => FrameRequestSource::LocalSchedule,
1135 };
1136 (self.origin + Duration::from_nanos(signal >> 1), source)
1137 })
1138 }
1139 #[cfg(not(feature = "profiler"))]
1140 {
1141 None
1142 }
1143 }
1144}
1145
1146#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1159pub enum AppLifecyclePhase {
1160 Active,
1162 Inactive,
1164 Background,
1167 Foreground,
1169 Disconnected,
1173}
1174
1175#[derive(Debug, Clone, Default, PartialEq)]
1182pub struct WindowInsets {
1183 pub safe_area: Edges<Pixels>,
1188 pub ime: Edges<Pixels>,
1192 pub corner_radii: Corners<Pixels>,
1197}
1198
1199impl WindowInsets {
1200 pub fn effective(&self) -> Edges<Pixels> {
1202 Edges {
1203 top: self.safe_area.top.max(self.ime.top),
1204 right: self.safe_area.right.max(self.ime.right),
1205 bottom: self.safe_area.bottom.max(self.ime.bottom),
1206 left: self.safe_area.left.max(self.ime.left),
1207 }
1208 }
1209}
1210
1211#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1213pub enum TextInputStateChange {
1214 FocusGained,
1216 FocusLost,
1218 SelectionChanged,
1220 ContentChanged,
1222}
1223
1224#[expect(missing_docs)]
1225pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1226 fn bounds(&self) -> Bounds<Pixels>;
1227 fn is_maximized(&self) -> bool;
1228 fn window_bounds(&self) -> WindowBounds;
1229 fn content_size(&self) -> Size<Pixels>;
1230 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1236 Bounds::new(Point::default(), self.content_size())
1237 }
1238 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1243 fn prepare_frame(&self) -> bool {
1248 false
1249 }
1250 fn resize(&mut self, size: Size<Pixels>);
1251 fn scale_factor(&self) -> f32;
1252 fn appearance(&self) -> WindowAppearance;
1253 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1254 fn mouse_position(&self) -> Point<Pixels>;
1255 fn modifiers(&self) -> Modifiers;
1256 fn capslock(&self) -> Capslock;
1257 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1258 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1259 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1264 fn prompt(
1265 &self,
1266 level: PromptLevel,
1267 msg: &str,
1268 detail: Option<&str>,
1269 answers: &[PromptButton],
1270 ) -> Option<oneshot::Receiver<usize>>;
1271 fn activate(&self);
1272 fn request_attention(&self) {}
1274 fn is_active(&self) -> bool;
1275 fn visibility(&self) -> WindowVisibility;
1278 fn is_hovered(&self) -> bool;
1279 fn background_appearance(&self) -> WindowBackgroundAppearance;
1280 fn set_title(&mut self, title: &str);
1281 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1282 fn minimize(&self);
1283 fn zoom(&self);
1284 fn toggle_fullscreen(&self);
1285 fn is_fullscreen(&self) -> bool;
1286 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1287 None
1288 }
1289 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1290 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1291 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1292 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1296 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1297 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1298 fn on_moved(&self, callback: Box<dyn FnMut()>);
1299 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1303 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1304 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1305 fn on_close(&self, callback: Box<dyn FnOnce()>);
1306 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1307 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1308 fn draw(&self, scene: &Scene);
1309 fn draw_composed(&self, scene: crate::fast::composition::ComposedScene<'_>) {
1310 crate::fast::composition::draw_uncomposed(self, scene)
1311 }
1312 fn enable_window_composition(&self) -> Result<()> {
1313 crate::fast::composition::unsupported("window composition")
1314 }
1315 fn create_native_surface(
1316 &self,
1317 ) -> Result<Rc<dyn crate::fast::composition::PlatformSurfaceAttachment>> {
1318 crate::fast::composition::unsupported("native surface portals")
1319 }
1320 fn set_composition_order(
1321 &self,
1322 _fast_surfaces: &[crate::fast::composition::PlatformCompositionSurface],
1323 ) -> Result<()> {
1324 crate::fast::composition::unsupported("surface ordering")
1325 }
1326 fn schedule_frame(&self) {}
1327 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1328 fn is_subpixel_rendering_supported(&self) -> bool;
1329
1330 fn get_title(&self) -> String {
1332 String::new()
1333 }
1334 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1335 None
1336 }
1337 fn tab_bar_visible(&self) -> bool {
1338 false
1339 }
1340 fn set_edited(&mut self, _edited: bool) {}
1341 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1342 fn toggle_simple_fullscreen(&self) {}
1343 fn is_simple_fullscreen(&self) -> bool {
1344 false
1345 }
1346 #[cfg(target_os = "macos")]
1347 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1348 fn show_character_palette(&self) {}
1349 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1350 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1351 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1352 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1353 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1354 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1355 fn merge_all_windows(&self) {}
1356 fn move_tab_to_new_window(&self) {}
1357 fn toggle_window_tab_overview(&self) {}
1358 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1359
1360 fn native_window_state(&self) -> Option<Vec<u8>> {
1361 None
1362 }
1363 fn restore_native_window_state(&self, _state: &[u8]) {}
1364
1365 #[cfg(target_os = "windows")]
1366 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1367
1368 fn inner_window_bounds(&self) -> WindowBounds {
1370 self.window_bounds()
1371 }
1372 fn request_decorations(&self, _decorations: WindowDecorations) {}
1373 fn show_window_menu(&self, _position: Point<Pixels>) {}
1374 fn start_window_move(&self) {}
1375 fn can_start_external_drag(&self) -> bool {
1376 false
1377 }
1378 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1379 false
1380 }
1381 fn start_window_resize(&self, _edge: ResizeEdge) {}
1382 fn set_exclusive_zone(&self, _zone: Pixels) {}
1383 #[cfg(all(target_os = "linux", feature = "wayland"))]
1384 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1385 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1386 fn window_decorations(&self) -> Decorations {
1387 Decorations::Server
1388 }
1389 fn set_app_id(&mut self, _app_id: &str) {}
1390 fn map_window(&mut self) -> anyhow::Result<()> {
1391 Ok(())
1392 }
1393 fn window_controls(&self) -> WindowControls {
1394 WindowControls::default()
1395 }
1396 fn set_client_inset(&self, _inset: Pixels) {}
1397 fn gpu_specs(&self) -> Option<GpuSpecs>;
1398
1399 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1400
1401 fn insets(&self) -> WindowInsets {
1406 WindowInsets::default()
1407 }
1408
1409 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1415
1416 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1419
1420 fn set_back_enabled(&self, _enabled: bool) {}
1423
1424 fn show_soft_keyboard(&self) {}
1426
1427 fn hide_soft_keyboard(&self) {}
1429
1430 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1432
1433 fn play_system_bell(&self) {}
1434
1435 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1437
1438 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1440
1441 fn a11y_update_window_bounds(&self) {}
1443
1444 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1445 fn as_test(&mut self) -> Option<&mut TestWindow> {
1446 None
1447 }
1448
1449 #[cfg(any(test, feature = "test-support"))]
1453 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1454 anyhow::bail!("render_to_image not implemented for this platform")
1455 }
1456}
1457
1458#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1460pub trait PlatformHeadlessRenderer {
1461 fn render_scene_to_image(
1463 &mut self,
1464 scene: &Scene,
1465 size: Size<DevicePixels>,
1466 ) -> Result<RgbaImage>;
1467
1468 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1474
1475 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1477}
1478
1479#[doc(hidden)]
1482pub type RunnableVariant = Runnable<RunnableMeta>;
1483
1484#[doc(hidden)]
1485pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1486
1487#[doc(hidden)]
1488pub enum TasksIncluded {
1489 OnlyCompleted,
1490 CompletedAndRunning,
1491}
1492
1493#[doc(hidden)]
1496pub trait PlatformDispatcher: Send + Sync {
1497 fn is_main_thread(&self) -> bool;
1498 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1499 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1500 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1501
1502 fn dispatch_on_main_thread_when_idle(
1503 &self,
1504 runnable: RunnableVariant,
1505 timeout: Option<Duration>,
1506 ) {
1507 let _ = timeout;
1508 self.dispatch_on_main_thread(runnable, Priority::Low);
1509 }
1510
1511 fn idle_time_remaining(&self) -> Option<Duration> {
1512 None
1513 }
1514
1515 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1516
1517 fn now(&self) -> Instant {
1518 Instant::now()
1519 }
1520
1521 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1522 gpui_util::defer(Box::new(|| {}))
1523 }
1524
1525 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1526 ActivityGuard::noop()
1527 }
1528
1529 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1530 fn as_test(&self) -> Option<&TestDispatcher> {
1531 None
1532 }
1533
1534 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1537 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1538 None
1539 }
1540}
1541
1542#[expect(missing_docs)]
1543pub trait PlatformTextSystem: Send + Sync {
1544 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1545 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1547 fn all_font_names(&self) -> Vec<String>;
1549 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1551 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1553 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1555 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1557 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1559 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1561 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1563 fn rasterize_glyph(
1565 &self,
1566 params: &RenderGlyphParams,
1567 raster_bounds: Bounds<DevicePixels>,
1568 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1569 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1571 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1573 -> TextRenderingMode;
1574 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1576 0
1577 }
1578}
1579
1580#[expect(missing_docs)]
1581pub struct NoopTextSystem;
1582
1583#[expect(missing_docs)]
1584impl NoopTextSystem {
1585 #[allow(dead_code)]
1586 pub fn new() -> Self {
1587 Self
1588 }
1589}
1590
1591impl PlatformTextSystem for NoopTextSystem {
1592 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1593 Ok(())
1594 }
1595
1596 fn all_font_names(&self) -> Vec<String> {
1597 Vec::new()
1598 }
1599
1600 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1601 Ok(FontId(1))
1602 }
1603
1604 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1605 FontMetrics {
1606 units_per_em: 1000,
1607 ascent: 1025.0,
1608 descent: -275.0,
1609 line_gap: 0.0,
1610 underline_position: -95.0,
1611 underline_thickness: 60.0,
1612 cap_height: 698.0,
1613 x_height: 516.0,
1614 bounding_box: Bounds {
1615 origin: Point {
1616 x: -260.0,
1617 y: -245.0,
1618 },
1619 size: Size {
1620 width: 1501.0,
1621 height: 1364.0,
1622 },
1623 },
1624 }
1625 }
1626
1627 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1628 Ok(Bounds {
1629 origin: Point { x: 54.0, y: 0.0 },
1630 size: size(392.0, 528.0),
1631 })
1632 }
1633
1634 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1635 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1636 }
1637
1638 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1639 Some(GlyphId(ch.len_utf16() as u32))
1640 }
1641
1642 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1643 Ok(Default::default())
1644 }
1645
1646 fn rasterize_glyph(
1647 &self,
1648 _params: &RenderGlyphParams,
1649 raster_bounds: Bounds<DevicePixels>,
1650 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1651 Ok((raster_bounds.size, Vec::new()))
1652 }
1653
1654 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1655 let mut position = px(0.);
1656 let metrics = self.font_metrics(FontId(0));
1657 let em_width = font_size
1658 * self
1659 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1660 .unwrap()
1661 .width
1662 / metrics.units_per_em as f32;
1663 let mut glyphs = Vec::new();
1664 for (ix, c) in text.char_indices() {
1665 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1666 glyphs.push(ShapedGlyph {
1667 id: glyph,
1668 position: point(position, px(0.)),
1669 index: ix,
1670 is_emoji: glyph.0 == 2,
1671 });
1672 if glyph.0 == 2 {
1673 position += em_width * 2.0;
1674 } else {
1675 position += em_width;
1676 }
1677 } else {
1678 position += em_width
1679 }
1680 }
1681 let mut runs = Vec::default();
1682 if !glyphs.is_empty() {
1683 runs.push(ShapedRun {
1684 font_id: FontId(0),
1685 glyphs,
1686 });
1687 } else {
1688 position = px(0.);
1689 }
1690
1691 LineLayout {
1692 font_size,
1693 width: position,
1694 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1695 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1696 runs,
1697 len: text.len(),
1698 }
1699 }
1700
1701 fn recommended_rendering_mode(
1702 &self,
1703 _font_id: FontId,
1704 _font_size: Pixels,
1705 ) -> TextRenderingMode {
1706 TextRenderingMode::Grayscale
1707 }
1708}
1709
1710#[allow(dead_code)]
1715pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1716 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1717 [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], ];
1731
1732 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1733 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1734
1735 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1736 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1737
1738 [
1739 ratios[0] * NORM13,
1740 ratios[1] * NORM24,
1741 ratios[2] * NORM13,
1742 ratios[3] * NORM24,
1743 ]
1744}
1745
1746#[derive(PartialEq, Eq, Hash, Clone)]
1747#[expect(missing_docs)]
1748pub enum AtlasKey {
1749 Glyph(RenderGlyphParams),
1750 Svg(RenderSvgParams),
1751 Image(RenderImageParams),
1752}
1753
1754impl AtlasKey {
1755 pub fn texture_kind(&self) -> AtlasTextureKind {
1757 match self {
1758 AtlasKey::Glyph(params) => {
1759 if params.is_emoji {
1760 AtlasTextureKind::Polychrome
1761 } else if params.subpixel_rendering {
1762 AtlasTextureKind::Subpixel
1763 } else {
1764 AtlasTextureKind::Monochrome
1765 }
1766 }
1767 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1768 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1769 }
1770 }
1771}
1772
1773impl From<RenderGlyphParams> for AtlasKey {
1774 fn from(params: RenderGlyphParams) -> Self {
1775 Self::Glyph(params)
1776 }
1777}
1778
1779impl From<RenderSvgParams> for AtlasKey {
1780 fn from(params: RenderSvgParams) -> Self {
1781 Self::Svg(params)
1782 }
1783}
1784
1785impl From<RenderImageParams> for AtlasKey {
1786 fn from(params: RenderImageParams) -> Self {
1787 Self::Image(params)
1788 }
1789}
1790
1791#[expect(missing_docs)]
1792pub trait PlatformAtlas {
1793 fn get_or_insert_with<'a>(
1795 &self,
1796 key: AtlasKey,
1797 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1798 ) -> Result<Option<AtlasTile>>;
1799 fn remove(&self, key: &AtlasKey);
1800
1801 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1802 fn contains(&self, _key: &AtlasKey) -> bool {
1803 false
1804 }
1805}
1806
1807#[doc(hidden)]
1808pub trait AtlasBackend {
1809 fn insert(
1810 &mut self,
1811 kind: AtlasTextureKind,
1812 size: Size<DevicePixels>,
1813 bytes: &[u8],
1814 ) -> Result<AtlasTile>;
1815
1816 fn remove(&mut self, tile: AtlasTile);
1817}
1818
1819#[doc(hidden)]
1820pub struct AtlasState<Backend> {
1821 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1822 pub backend: Backend,
1823}
1824
1825impl<Backend> AtlasState<Backend> {
1826 pub fn new(backend: Backend) -> Self {
1827 Self {
1828 tiles_by_key: FxHashMap::default(),
1829 backend,
1830 }
1831 }
1832
1833 pub fn contains(&self, key: &AtlasKey) -> bool {
1834 self.tiles_by_key.contains_key(key)
1835 }
1836
1837 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1838 self.tiles_by_key.clear();
1839 reset_backend(&mut self.backend);
1840 }
1841}
1842
1843impl<Backend: Default> Default for AtlasState<Backend> {
1844 fn default() -> Self {
1845 Self::new(Backend::default())
1846 }
1847}
1848
1849impl<Backend: AtlasBackend> AtlasState<Backend> {
1850 pub fn get_or_insert_with<'a>(
1851 &mut self,
1852 key: AtlasKey,
1853 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1854 ) -> Result<Option<AtlasTile>> {
1855 match self.tiles_by_key.entry(key) {
1856 Entry::Occupied(entry) => Ok(Some(*entry.get())),
1857 Entry::Vacant(entry) => {
1858 profiling::scope!("new tile");
1859 let Some((size, bytes)) = build()? else {
1860 return Ok(None);
1861 };
1862 let tile = self
1863 .backend
1864 .insert(entry.key().texture_kind(), size, &bytes)?;
1865 entry.insert(tile);
1866 Ok(Some(tile))
1867 }
1868 }
1869 }
1870
1871 pub fn remove(&mut self, key: &AtlasKey) {
1872 if let Some(tile) = self.tiles_by_key.remove(key) {
1873 self.backend.remove(tile);
1874 }
1875 }
1876}
1877
1878#[derive(Default)]
1882pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1883
1884#[doc(hidden)]
1885#[derive(Default)]
1886pub struct HeadlessAtlasBackend {
1887 next_id: u32,
1888}
1889
1890impl AtlasBackend for HeadlessAtlasBackend {
1891 fn insert(
1892 &mut self,
1893 kind: AtlasTextureKind,
1894 size: Size<DevicePixels>,
1895 _bytes: &[u8],
1896 ) -> Result<AtlasTile> {
1897 self.next_id += 1;
1898 let texture_id = self.next_id;
1899 self.next_id += 1;
1900 let tile_id = self.next_id;
1901 Ok(AtlasTile {
1902 texture_id: AtlasTextureId {
1903 index: texture_id,
1904 kind,
1905 },
1906 tile_id: TileId(tile_id),
1907 padding: 0,
1908 bounds: Bounds {
1909 origin: Point::default(),
1910 size,
1911 },
1912 })
1913 }
1914
1915 fn remove(&mut self, _tile: AtlasTile) {}
1916}
1917
1918impl PlatformAtlas for HeadlessAtlas {
1919 fn get_or_insert_with<'a>(
1920 &self,
1921 key: AtlasKey,
1922 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1923 ) -> Result<Option<AtlasTile>> {
1924 self.0.lock().get_or_insert_with(key, build)
1925 }
1926
1927 fn remove(&self, key: &AtlasKey) {
1928 self.0.lock().remove(key);
1929 }
1930
1931 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1932 fn contains(&self, key: &AtlasKey) -> bool {
1933 self.0.lock().contains(key)
1934 }
1935}
1936
1937#[doc(hidden)]
1938pub struct AtlasTextureList<T> {
1939 pub textures: Vec<Option<T>>,
1940 pub free_list: Vec<usize>,
1941}
1942
1943impl<T> Default for AtlasTextureList<T> {
1944 fn default() -> Self {
1945 Self {
1946 textures: Vec::default(),
1947 free_list: Vec::default(),
1948 }
1949 }
1950}
1951
1952impl<T> ops::Index<usize> for AtlasTextureList<T> {
1953 type Output = Option<T>;
1954
1955 fn index(&self, index: usize) -> &Self::Output {
1956 &self.textures[index]
1957 }
1958}
1959
1960impl<T> AtlasTextureList<T> {
1961 #[allow(unused)]
1962 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1963 self.free_list.clear();
1964 self.textures.drain(..)
1965 }
1966
1967 #[allow(dead_code)]
1968 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1969 self.textures.iter_mut().flatten()
1970 }
1971}
1972
1973#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1974#[repr(C)]
1975#[expect(missing_docs)]
1976pub struct AtlasTile {
1977 pub texture_id: AtlasTextureId,
1979 pub tile_id: TileId,
1981 pub padding: u32,
1983 pub bounds: Bounds<DevicePixels>,
1985}
1986
1987#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1988#[repr(C)]
1989#[expect(missing_docs)]
1990pub struct AtlasTextureId {
1991 pub index: u32,
1994 pub kind: AtlasTextureKind,
1996}
1997
1998#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1999#[repr(C)]
2000#[cfg_attr(
2001 all(
2002 any(target_os = "linux", target_os = "freebsd"),
2003 not(any(feature = "x11", feature = "wayland"))
2004 ),
2005 allow(dead_code)
2006)]
2007#[expect(missing_docs)]
2008pub enum AtlasTextureKind {
2009 Monochrome = 0,
2010 Polychrome = 1,
2011 Subpixel = 2,
2012}
2013
2014#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2015#[repr(C)]
2016#[expect(missing_docs)]
2017pub struct TileId(pub u32);
2018
2019impl From<etagere::AllocId> for TileId {
2020 fn from(id: etagere::AllocId) -> Self {
2021 Self(id.serialize())
2022 }
2023}
2024
2025impl From<TileId> for etagere::AllocId {
2026 fn from(id: TileId) -> Self {
2027 Self::deserialize(id.0)
2028 }
2029}
2030
2031#[expect(missing_docs)]
2032pub struct PlatformInputHandler {
2033 cx: AsyncWindowContext,
2034 handler: Box<dyn InputHandler>,
2035 focus_id: Option<crate::FocusId>,
2036}
2037
2038#[expect(missing_docs)]
2039#[cfg_attr(
2040 all(
2041 any(target_os = "linux", target_os = "freebsd"),
2042 not(any(feature = "x11", feature = "wayland"))
2043 ),
2044 allow(dead_code)
2045)]
2046impl PlatformInputHandler {
2047 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2048 Self {
2049 cx,
2050 handler,
2051 focus_id: None,
2052 }
2053 }
2054
2055 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2056 self.focus_id = Some(focus_id);
2057 self
2058 }
2059
2060 pub fn focus_id(&self) -> Option<crate::FocusId> {
2065 self.focus_id
2066 }
2067
2068 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2069 self.cx
2070 .update(|window, cx| {
2071 self.handler
2072 .selected_text_range(ignore_disabled_input, window, cx)
2073 })
2074 .ok()
2075 .flatten()
2076 }
2077
2078 #[cfg_attr(target_os = "windows", allow(dead_code))]
2079 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2080 self.cx
2081 .update(|window, cx| self.handler.marked_text_range(window, cx))
2082 .ok()
2083 .flatten()
2084 }
2085
2086 #[cfg_attr(
2087 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2088 allow(dead_code)
2089 )]
2090 pub fn text_for_range(
2091 &mut self,
2092 range_utf16: Range<usize>,
2093 adjusted: &mut Option<Range<usize>>,
2094 ) -> Option<String> {
2095 self.cx
2096 .update(|window, cx| {
2097 self.handler
2098 .text_for_range(range_utf16, adjusted, window, cx)
2099 })
2100 .ok()
2101 .flatten()
2102 }
2103
2104 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2105 self.cx
2106 .update(|window, cx| {
2107 self.handler
2108 .replace_text_in_range(replacement_range, text, window, cx);
2109 })
2110 .ok();
2111 }
2112
2113 pub fn replace_and_mark_text_in_range(
2114 &mut self,
2115 range_utf16: Option<Range<usize>>,
2116 new_text: &str,
2117 new_selected_range: Option<Range<usize>>,
2118 ) {
2119 self.cx
2120 .update(|window, cx| {
2121 self.handler.replace_and_mark_text_in_range(
2122 range_utf16,
2123 new_text,
2124 new_selected_range,
2125 window,
2126 cx,
2127 )
2128 })
2129 .ok();
2130 }
2131
2132 #[cfg_attr(target_os = "windows", allow(dead_code))]
2133 pub fn unmark_text(&mut self) {
2134 self.cx
2135 .update(|window, cx| self.handler.unmark_text(window, cx))
2136 .ok();
2137 }
2138
2139 pub fn paste(&mut self, item: ClipboardItem) {
2140 self.cx
2141 .update(|window, cx| self.handler.paste(item, window, cx))
2142 .ok();
2143 }
2144
2145 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2146 self.cx
2147 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2148 .ok()
2149 .flatten()
2150 }
2151
2152 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2153 self.cx
2154 .update(|window, cx| {
2155 self.handler
2156 .selection_bounds_for_range(range_utf16, window, cx)
2157 })
2158 .unwrap_or_default()
2159 }
2160
2161 #[allow(dead_code)]
2162 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2163 self.handler.apple_press_and_hold_enabled()
2164 }
2165
2166 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2167 self.handler.replace_text_in_range(None, input, window, cx);
2168 }
2169
2170 pub fn compute_ime_candidate_bounds(
2171 marked_range: Option<Range<usize>>,
2172 selection: &UTF16Selection,
2173 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2174 ) -> Option<Bounds<Pixels>> {
2175 if let Some(marked_range) = marked_range {
2176 let mut line_start = marked_range.start;
2178
2179 let caret = selection.range.end;
2183 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2184 for i in (marked_range.start..caret).rev() {
2185 if let Some(b) = bounds_for_range(i..i) {
2186 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2187 line_start = i + 1;
2188 break;
2189 }
2190 }
2191 }
2192 }
2193 bounds_for_range(line_start..line_start)
2194 } else {
2195 let offset = if selection.reversed {
2197 selection.range.start
2198 } else {
2199 selection.range.end
2200 };
2201 bounds_for_range(offset..offset)
2202 }
2203 }
2204
2205 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2206 let marked_range = self.handler.marked_text_range(window, cx);
2207 let selection = self.handler.selected_text_range(true, window, cx)?;
2208 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2209 self.handler.bounds_for_range(range, window, cx)
2210 })
2211 }
2212
2213 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2214 let marked_range = self.marked_text_range();
2215 let selection = self.selected_text_range(true)?;
2216 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2217 self.bounds_for_range(range)
2218 })
2219 }
2220
2221 #[allow(unused)]
2222 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2223 self.cx
2224 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2225 .ok()
2226 .flatten()
2227 }
2228
2229 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2231 self.cx
2232 .update(|window, cx| {
2233 self.handler
2234 .set_selected_text_range(range_utf16, window, cx)
2235 })
2236 .ok();
2237 }
2238
2239 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2241 self.cx
2242 .update(|window, cx| self.handler.element_bounds(window, cx))
2243 .ok()
2244 .flatten()
2245 }
2246
2247 pub fn text_length_utf16(&mut self) -> Option<usize> {
2249 self.cx
2250 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2251 .ok()
2252 .flatten()
2253 }
2254
2255 #[allow(dead_code)]
2256 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2257 self.handler.accepts_text_input(window, cx)
2258 }
2259
2260 #[allow(dead_code)]
2261 pub fn query_accepts_text_input(&mut self) -> bool {
2262 self.cx
2263 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2264 .unwrap_or(true)
2265 }
2266
2267 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2272 let focus_id = self.focus_id;
2273 self.cx
2274 .update(|window, cx| {
2275 focus_id.is_some()
2276 && window.focus == focus_id
2277 && self.handler.accepts_text_input(window, cx)
2278 })
2279 .unwrap_or(false)
2280 }
2281
2282 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2288 self.cx
2289 .update(|window, cx| {
2290 !window.has_pending_keystrokes()
2292 && self.handler.prefers_ime_for_printable_keys(window, cx)
2293 })
2294 .unwrap_or(false)
2295 }
2296
2297 pub fn text_input_configuration(
2299 &mut self,
2300 window: &mut Window,
2301 cx: &mut App,
2302 ) -> TextInputConfiguration {
2303 self.handler.text_input_configuration(window, cx)
2304 }
2305
2306 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2308 self.cx
2309 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2310 .ok()
2311 .flatten()
2312 }
2313}
2314
2315#[derive(Debug)]
2318pub struct UTF16Selection {
2319 pub range: Range<usize>,
2322 pub reversed: bool,
2325}
2326
2327pub trait InputHandler: 'static {
2332 fn selected_text_range(
2337 &mut self,
2338 ignore_disabled_input: bool,
2339 window: &mut Window,
2340 cx: &mut App,
2341 ) -> Option<UTF16Selection>;
2342
2343 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2348
2349 fn text_for_range(
2354 &mut self,
2355 range_utf16: Range<usize>,
2356 adjusted_range: &mut Option<Range<usize>>,
2357 window: &mut Window,
2358 cx: &mut App,
2359 ) -> Option<String>;
2360
2361 fn replace_text_in_range(
2366 &mut self,
2367 replacement_range: Option<Range<usize>>,
2368 text: &str,
2369 window: &mut Window,
2370 cx: &mut App,
2371 );
2372
2373 fn replace_and_mark_text_in_range(
2380 &mut self,
2381 range_utf16: Option<Range<usize>>,
2382 new_text: &str,
2383 new_selected_range: Option<Range<usize>>,
2384 window: &mut Window,
2385 cx: &mut App,
2386 );
2387
2388 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2391
2392 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2399 if let Some(text) = item.text() {
2400 self.replace_text_in_range(None, &text, window, cx);
2401 }
2402 }
2403
2404 fn bounds_for_range(
2409 &mut self,
2410 range_utf16: Range<usize>,
2411 window: &mut Window,
2412 cx: &mut App,
2413 ) -> Option<Bounds<Pixels>>;
2414
2415 fn selection_bounds_for_range(
2422 &mut self,
2423 _range_utf16: Range<usize>,
2424 _window: &mut Window,
2425 _cx: &mut App,
2426 ) -> Vec<Bounds<Pixels>> {
2427 Vec::new()
2428 }
2429
2430 fn character_index_for_point(
2434 &mut self,
2435 point: Point<Pixels>,
2436 window: &mut Window,
2437 cx: &mut App,
2438 ) -> Option<usize>;
2439
2440 fn set_selected_text_range(
2450 &mut self,
2451 _range_utf16: Range<usize>,
2452 _window: &mut Window,
2453 _cx: &mut App,
2454 ) {
2455 }
2456
2457 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2464 None
2465 }
2466
2467 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2469 None
2470 }
2471
2472 #[allow(dead_code)]
2477 fn apple_press_and_hold_enabled(&mut self) -> bool {
2478 true
2479 }
2480
2481 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2483 true
2484 }
2485
2486 fn text_input_editable_range(
2497 &mut self,
2498 _window: &mut Window,
2499 _cx: &mut App,
2500 ) -> Option<Range<usize>> {
2501 None
2502 }
2503
2504 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2513 false
2514 }
2515
2516 fn text_input_configuration(
2522 &mut self,
2523 _window: &mut Window,
2524 _cx: &mut App,
2525 ) -> TextInputConfiguration {
2526 TextInputConfiguration::default()
2527 }
2528}
2529
2530#[derive(Clone, Debug, Default, PartialEq, Eq)]
2540pub struct TextInputConfiguration {
2541 pub autocorrect: bool,
2543 pub autocapitalize: Autocapitalize,
2545 pub suggestions: bool,
2547 pub input_action: TextInputAction,
2549}
2550
2551#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2553pub enum Autocapitalize {
2554 #[default]
2556 None,
2557 Words,
2559 Sentences,
2561 Characters,
2563}
2564
2565#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2575pub enum TextInputAction {
2576 #[default]
2578 Unspecified,
2579 Enter,
2581 Done,
2583 Go,
2585 Next,
2587 Previous,
2589 Search,
2591 Send,
2593}
2594
2595#[derive(Debug)]
2597pub struct WindowOptions {
2598 pub window_bounds: Option<WindowBounds>,
2602
2603 pub titlebar: Option<TitlebarOptions>,
2605
2606 pub focus: bool,
2608
2609 pub show: bool,
2611
2612 pub kind: WindowKind,
2614
2615 pub is_movable: bool,
2619
2620 pub app_owns_titlebar_drag: bool,
2632
2633 pub inactive_frame_interval: Option<Duration>,
2637
2638 pub is_resizable: bool,
2640
2641 pub is_minimizable: bool,
2643
2644 pub display_id: Option<DisplayId>,
2647
2648 pub window_background: WindowBackgroundAppearance,
2650
2651 pub app_id: Option<String>,
2653
2654 pub window_min_size: Option<Size<Pixels>>,
2656
2657 pub window_decorations: Option<WindowDecorations>,
2660
2661 pub icon: Option<Arc<image::RgbaImage>>,
2663
2664 pub tabbing_identifier: Option<String>,
2666
2667 pub use_display_p3: bool,
2669}
2670
2671#[derive(Debug)]
2673#[cfg_attr(
2674 all(
2675 any(target_os = "linux", target_os = "freebsd"),
2676 not(any(feature = "x11", feature = "wayland"))
2677 ),
2678 allow(dead_code)
2679)]
2680#[allow(missing_docs)]
2681pub struct WindowParams {
2682 pub bounds: Bounds<Pixels>,
2683
2684 #[cfg_attr(feature = "wayland", allow(dead_code))]
2686 pub titlebar: Option<TitlebarOptions>,
2687
2688 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2690 pub kind: WindowKind,
2691
2692 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2694 pub is_movable: bool,
2695
2696 #[cfg_attr(
2698 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2699 allow(dead_code)
2700 )]
2701 pub app_owns_titlebar_drag: bool,
2702
2703 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2705 pub is_resizable: bool,
2706
2707 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2709 pub is_minimizable: bool,
2710
2711 #[cfg_attr(
2712 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2713 allow(dead_code)
2714 )]
2715 pub focus: bool,
2716
2717 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2718 pub show: bool,
2719
2720 #[cfg_attr(feature = "wayland", allow(dead_code))]
2722 pub icon: Option<Arc<image::RgbaImage>>,
2723
2724 #[cfg_attr(feature = "wayland", allow(dead_code))]
2725 pub display_id: Option<DisplayId>,
2726
2727 #[cfg_attr(feature = "wayland", allow(dead_code))]
2728 pub app_id: Option<String>,
2729
2730 pub window_min_size: Option<Size<Pixels>>,
2731
2732 #[cfg(target_os = "macos")]
2733 pub tabbing_identifier: Option<String>,
2734
2735 #[cfg(target_os = "macos")]
2736 pub use_display_p3: bool,
2737}
2738
2739#[derive(Debug, Copy, Clone, PartialEq)]
2741pub enum WindowBounds {
2742 Windowed(Bounds<Pixels>),
2744 Maximized(Bounds<Pixels>),
2747 Fullscreen(Bounds<Pixels>),
2750}
2751
2752impl Default for WindowBounds {
2753 fn default() -> Self {
2754 WindowBounds::Windowed(Bounds::default())
2755 }
2756}
2757
2758impl WindowBounds {
2759 pub fn get_bounds(&self) -> Bounds<Pixels> {
2761 match self {
2762 WindowBounds::Windowed(bounds) => *bounds,
2763 WindowBounds::Maximized(bounds) => *bounds,
2764 WindowBounds::Fullscreen(bounds) => *bounds,
2765 }
2766 }
2767
2768 pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
2770 WindowBounds::Windowed(Bounds::centered(None, size, cx))
2771 }
2772}
2773
2774impl Default for WindowOptions {
2775 fn default() -> Self {
2776 Self {
2777 window_bounds: None,
2778 titlebar: Some(TitlebarOptions {
2779 title: Default::default(),
2780 appears_transparent: Default::default(),
2781 traffic_light_position: Default::default(),
2782 }),
2783 focus: true,
2784 show: true,
2785 kind: WindowKind::Normal,
2786 is_movable: true,
2787 app_owns_titlebar_drag: false,
2788 inactive_frame_interval: Some(Duration::from_micros(33_333)),
2789 is_resizable: true,
2790 is_minimizable: true,
2791 display_id: None,
2792 window_background: WindowBackgroundAppearance::default(),
2793 icon: None,
2794 app_id: None,
2795 window_min_size: None,
2796 window_decorations: None,
2797 tabbing_identifier: None,
2798 use_display_p3: false,
2799 }
2800 }
2801}
2802
2803#[derive(Debug, Default)]
2805pub struct TitlebarOptions {
2806 pub title: Option<SharedString>,
2808
2809 pub appears_transparent: bool,
2812
2813 pub traffic_light_position: Option<Point<Pixels>>,
2815}
2816
2817#[derive(Clone, Debug, PartialEq, Eq)]
2819pub enum WindowKind {
2820 Normal,
2822
2823 PopUp,
2826
2827 AnchoredPopup(popup::PopupOptions),
2834
2835 Floating,
2837
2838 #[cfg(all(target_os = "linux", feature = "wayland"))]
2841 LayerShell(layer_shell::LayerShellOptions),
2842
2843 Dialog,
2846}
2847
2848#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2853pub enum WindowAppearance {
2854 #[default]
2858 Light,
2859
2860 VibrantLight,
2864
2865 Dark,
2869
2870 VibrantDark,
2874}
2875
2876#[derive(Copy, Clone, Debug, Default, PartialEq)]
2879pub enum WindowBackgroundAppearance {
2880 #[default]
2888 Opaque,
2889 Transparent,
2891 Blurred,
2895 MicaBackdrop,
2897 MicaAltBackdrop,
2899}
2900
2901#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2903pub enum TextRenderingMode {
2904 #[default]
2906 PlatformDefault,
2907 Subpixel,
2909 Grayscale,
2911}
2912
2913#[derive(Clone, Debug)]
2915pub struct PathPromptOptions {
2916 pub files: bool,
2918 pub directories: bool,
2920 pub multiple: bool,
2922 pub prompt: Option<SharedString>,
2924}
2925
2926#[derive(Copy, Clone, Debug, PartialEq)]
2928pub enum PromptLevel {
2929 Info,
2931
2932 Warning,
2934
2935 Critical,
2937}
2938
2939#[derive(Clone, Debug, PartialEq)]
2941pub enum PromptButton {
2942 Ok(SharedString),
2944 Cancel(SharedString),
2946 Other(SharedString),
2948}
2949
2950impl PromptButton {
2951 pub fn new(label: impl Into<SharedString>) -> Self {
2953 PromptButton::Other(label.into())
2954 }
2955
2956 pub fn ok(label: impl Into<SharedString>) -> Self {
2958 PromptButton::Ok(label.into())
2959 }
2960
2961 pub fn cancel(label: impl Into<SharedString>) -> Self {
2963 PromptButton::Cancel(label.into())
2964 }
2965
2966 #[allow(dead_code)]
2968 pub fn is_cancel(&self) -> bool {
2969 matches!(self, PromptButton::Cancel(_))
2970 }
2971
2972 pub fn label(&self) -> &SharedString {
2974 match self {
2975 PromptButton::Ok(label) => label,
2976 PromptButton::Cancel(label) => label,
2977 PromptButton::Other(label) => label,
2978 }
2979 }
2980}
2981
2982impl From<&str> for PromptButton {
2983 fn from(value: &str) -> Self {
2984 match value.to_lowercase().as_str() {
2985 "ok" => PromptButton::Ok("OK".into()),
2986 "cancel" => PromptButton::Cancel("Cancel".into()),
2987 _ => PromptButton::Other(SharedString::from(value.to_owned())),
2988 }
2989 }
2990}
2991
2992#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2994pub enum CursorStyle {
2995 #[default]
2997 Arrow,
2998
2999 IBeam,
3002
3003 Crosshair,
3006
3007 ClosedHand,
3010
3011 OpenHand,
3014
3015 PointingHand,
3018
3019 ResizeLeft,
3022
3023 ResizeRight,
3026
3027 ResizeLeftRight,
3030
3031 ResizeUp,
3034
3035 ResizeDown,
3038
3039 ResizeUpDown,
3042
3043 ResizeUpLeftDownRight,
3046
3047 ResizeUpRightDownLeft,
3050
3051 ResizeColumn,
3054
3055 ResizeRow,
3058
3059 IBeamCursorForVerticalLayout,
3062
3063 OperationNotAllowed,
3066
3067 DragLink,
3070
3071 DragCopy,
3074
3075 ContextualMenu,
3078}
3079
3080#[derive(Clone, Debug, Eq, PartialEq)]
3082pub struct ClipboardItem {
3083 pub entries: Vec<ClipboardEntry>,
3085}
3086
3087#[derive(Clone, Debug, PartialEq, Eq)]
3092pub enum ClipboardReadError {
3093 Unavailable,
3097 Denied(String),
3100 UnsupportedContent,
3103}
3104
3105impl std::fmt::Display for ClipboardReadError {
3106 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3107 match self {
3108 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3109 Self::Denied(message) => {
3110 write!(formatter, "clipboard access was denied: {message}")
3111 }
3112 Self::UnsupportedContent => {
3113 formatter.write_str("the clipboard contents are unsupported")
3114 }
3115 }
3116 }
3117}
3118
3119impl std::error::Error for ClipboardReadError {}
3120
3121#[derive(Clone, Debug, Eq, PartialEq)]
3123pub enum ClipboardEntry {
3124 String(ClipboardString),
3126 Image(Image),
3128 ExternalPaths(crate::ExternalPaths),
3130}
3131
3132impl ClipboardItem {
3133 pub fn new_string(text: String) -> Self {
3135 Self {
3136 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3137 }
3138 }
3139
3140 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3142 Self {
3143 entries: vec![ClipboardEntry::String(ClipboardString {
3144 text,
3145 metadata: Some(metadata),
3146 })],
3147 }
3148 }
3149
3150 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3152 Self {
3153 entries: vec![ClipboardEntry::String(
3154 ClipboardString::new(text).with_json_metadata(metadata),
3155 )],
3156 }
3157 }
3158
3159 pub fn new_image(image: &Image) -> Self {
3161 Self {
3162 entries: vec![ClipboardEntry::Image(image.clone())],
3163 }
3164 }
3165
3166 pub fn text(&self) -> Option<String> {
3169 let mut answer = String::new();
3170
3171 for entry in self.entries.iter() {
3172 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3173 answer.push_str(text);
3174 }
3175 }
3176
3177 if answer.is_empty() {
3178 for entry in self.entries.iter() {
3179 if let ClipboardEntry::ExternalPaths(paths) = entry {
3180 for path in &paths.0 {
3181 use std::fmt::Write as _;
3182 _ = write!(answer, "{}", path.display());
3183 }
3184 }
3185 }
3186 }
3187
3188 if !answer.is_empty() {
3189 Some(answer)
3190 } else {
3191 None
3192 }
3193 }
3194
3195 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3197 pub fn metadata(&self) -> Option<&String> {
3198 match self.entries().first() {
3199 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3200 clipboard_string.metadata.as_ref()
3201 }
3202 _ => None,
3203 }
3204 }
3205
3206 pub fn entries(&self) -> &[ClipboardEntry] {
3208 &self.entries
3209 }
3210
3211 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3213 self.entries.into_iter()
3214 }
3215}
3216
3217impl From<ClipboardString> for ClipboardEntry {
3218 fn from(value: ClipboardString) -> Self {
3219 Self::String(value)
3220 }
3221}
3222
3223impl From<String> for ClipboardEntry {
3224 fn from(value: String) -> Self {
3225 Self::from(ClipboardString::from(value))
3226 }
3227}
3228
3229impl From<Image> for ClipboardEntry {
3230 fn from(value: Image) -> Self {
3231 Self::Image(value)
3232 }
3233}
3234
3235impl From<ClipboardEntry> for ClipboardItem {
3236 fn from(value: ClipboardEntry) -> Self {
3237 Self {
3238 entries: vec![value],
3239 }
3240 }
3241}
3242
3243impl From<String> for ClipboardItem {
3244 fn from(value: String) -> Self {
3245 Self::from(ClipboardEntry::from(value))
3246 }
3247}
3248
3249impl From<Image> for ClipboardItem {
3250 fn from(value: Image) -> Self {
3251 Self::from(ClipboardEntry::from(value))
3252 }
3253}
3254
3255#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3257pub enum ImageFormat {
3258 Png,
3263 Jpeg,
3265 Webp,
3267 Gif,
3269 Svg,
3271 Bmp,
3273 Tiff,
3275 Ico,
3277 Pnm,
3279}
3280
3281impl ImageFormat {
3282 pub const fn mime_type(self) -> &'static str {
3284 match self {
3285 ImageFormat::Png => "image/png",
3286 ImageFormat::Jpeg => "image/jpeg",
3287 ImageFormat::Webp => "image/webp",
3288 ImageFormat::Gif => "image/gif",
3289 ImageFormat::Svg => "image/svg+xml",
3290 ImageFormat::Bmp => "image/bmp",
3291 ImageFormat::Tiff => "image/tiff",
3292 ImageFormat::Ico => "image/ico",
3293 ImageFormat::Pnm => "image/x-portable-anymap",
3294 }
3295 }
3296
3297 pub const fn extension(self) -> &'static str {
3299 match self {
3300 ImageFormat::Png => "png",
3301 ImageFormat::Jpeg => "jpg",
3302 ImageFormat::Webp => "webp",
3303 ImageFormat::Gif => "gif",
3304 ImageFormat::Svg => "svg",
3305 ImageFormat::Bmp => "bmp",
3306 ImageFormat::Tiff => "tiff",
3307 ImageFormat::Ico => "ico",
3308 ImageFormat::Pnm => "pnm",
3309 }
3310 }
3311
3312 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3314 use strum::IntoEnumIterator;
3315 Self::iter()
3316 .find(|format| format.mime_type() == mime_type)
3317 .or_else(|| Self::from_mime_type_alias(mime_type))
3318 }
3319
3320 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3324 match mime_type {
3325 "image/jpg" => Some(Self::Jpeg),
3326 "image/tif" => Some(Self::Tiff),
3327 _ => None,
3328 }
3329 }
3330}
3331
3332#[derive(Clone, Debug, PartialEq, Eq)]
3334pub struct Image {
3335 pub format: ImageFormat,
3337 pub bytes: Vec<u8>,
3339 pub id: u64,
3341}
3342
3343pub(crate) fn decode_static_image(
3344 bytes: &[u8],
3345 format: image::ImageFormat,
3346) -> Result<SmallVec<[Frame; 1]>> {
3347 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3348 .into_decoder()
3349 .context("creating image decoder")?;
3350 decode_static_image_from_decoder(decoder)
3351}
3352
3353pub(crate) fn decode_static_image_from_decoder(
3354 mut decoder: impl image::ImageDecoder,
3355) -> Result<SmallVec<[Frame; 1]>> {
3356 let orientation = decoder
3357 .orientation()
3358 .context("reading decoder's orientation")?;
3359 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3360 image.apply_orientation(orientation);
3361
3362 let mut data = image.into_rgba8();
3363 for pixel in data.chunks_exact_mut(4) {
3364 pixel.swap(0, 2);
3365 }
3366
3367 Ok(SmallVec::from_elem(Frame::new(data), 1))
3368}
3369
3370impl Hash for Image {
3371 fn hash<H: Hasher>(&self, state: &mut H) {
3372 state.write_u64(self.id);
3373 }
3374}
3375
3376impl Image {
3377 pub fn empty() -> Self {
3379 Self::from_bytes(ImageFormat::Png, Vec::new())
3380 }
3381
3382 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3384 Self {
3385 id: hash(&bytes),
3386 format,
3387 bytes,
3388 }
3389 }
3390
3391 pub fn id(&self) -> u64 {
3393 self.id
3394 }
3395
3396 pub fn use_render_image(
3398 self: Arc<Self>,
3399 window: &mut Window,
3400 cx: &mut App,
3401 ) -> Option<Arc<RenderImage>> {
3402 ImageSource::Image(self)
3403 .use_data(None, window, cx)
3404 .and_then(|result| result.ok())
3405 }
3406
3407 pub fn get_render_image(
3409 self: Arc<Self>,
3410 window: &mut Window,
3411 cx: &mut App,
3412 ) -> Option<Arc<RenderImage>> {
3413 ImageSource::Image(self)
3414 .get_data(None, window, cx)
3415 .and_then(|result| result.ok())
3416 }
3417
3418 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3420 ImageSource::Image(self).remove_asset(cx);
3421 }
3422
3423 #[cfg(any(test, feature = "test-support"))]
3426 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3427 ImageSource::Image(self.clone()).is_asset_cached(cx)
3428 }
3429
3430 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3432 let frames = match self.format {
3433 ImageFormat::Gif => {
3434 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
3435 let mut frames = SmallVec::new();
3436
3437 for frame in decoder.into_frames() {
3438 match frame {
3439 Ok(mut frame) => {
3440 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3442 pixel.swap(0, 2);
3443 }
3444 frames.push(frame);
3445 }
3446 Err(err) => {
3447 log::debug!("Skipping GIF frame due to decode error: {err}");
3448 }
3449 }
3450 }
3451
3452 if frames.is_empty() {
3453 anyhow::bail!("GIF could not be decoded: all frames failed");
3454 }
3455
3456 frames
3457 }
3458 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3459 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3460 ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
3461 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3462 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3463 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3464 ImageFormat::Svg => {
3465 return svg_renderer
3466 .render_single_frame(&self.bytes, 1.0)
3467 .map_err(Into::into);
3468 }
3469 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3470 };
3471
3472 Ok(Arc::new(RenderImage::new(frames)))
3473 }
3474
3475 pub fn format(&self) -> ImageFormat {
3477 self.format
3478 }
3479
3480 pub fn bytes(&self) -> &[u8] {
3482 self.bytes.as_slice()
3483 }
3484}
3485
3486#[derive(Clone, Debug, Eq, PartialEq)]
3488pub struct ClipboardString {
3489 pub text: String,
3491 pub metadata: Option<String>,
3493}
3494
3495impl ClipboardString {
3496 pub fn new(text: String) -> Self {
3498 Self {
3499 text,
3500 metadata: None,
3501 }
3502 }
3503
3504 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3507 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3508 self
3509 }
3510
3511 pub fn text(&self) -> &String {
3513 &self.text
3514 }
3515
3516 pub fn into_text(self) -> String {
3518 self.text
3519 }
3520
3521 pub fn metadata_json<T>(&self) -> Option<T>
3523 where
3524 T: for<'a> Deserialize<'a>,
3525 {
3526 self.metadata
3527 .as_ref()
3528 .and_then(|m| serde_json::from_str(m).ok())
3529 }
3530
3531 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3532 pub fn text_hash(text: &str) -> u64 {
3534 let mut hasher = SeaHasher::new();
3535 text.hash(&mut hasher);
3536 hasher.finish()
3537 }
3538}
3539
3540impl From<String> for ClipboardString {
3541 fn from(value: String) -> Self {
3542 Self {
3543 text: value,
3544 metadata: None,
3545 }
3546 }
3547}
3548
3549#[cfg(test)]
3550mod image_tests {
3551 use super::*;
3552 use std::sync::Arc;
3553
3554 #[test]
3555 fn test_image_to_image_data_applies_exif_orientation() {
3556 let image = Image::from_bytes(
3557 ImageFormat::Jpeg,
3558 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3559 );
3560
3561 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3562
3563 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3564
3565 let bytes = render_image.as_bytes(0).unwrap();
3566 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3567 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3568 }
3569
3570 #[test]
3571 fn test_svg_image_to_image_data_converts_to_bgra() {
3572 let image = Image::from_bytes(
3573 ImageFormat::Svg,
3574 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3575<rect width="1" height="1" fill="#38BDF8"/>
3576</svg>"##
3577 .to_vec(),
3578 );
3579
3580 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3581 let bytes = render_image.as_bytes(0).unwrap();
3582
3583 for pixel in bytes.chunks_exact(4) {
3584 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3585 }
3586 }
3587}
3588
3589#[cfg(test)]
3590mod atlas_tests {
3591 use super::*;
3592
3593 const TILE_SIZE: Size<DevicePixels> = Size {
3594 width: DevicePixels(1),
3595 height: DevicePixels(1),
3596 };
3597
3598 #[derive(Default)]
3599 struct RecordingAtlasBackend {
3600 insert_calls: u32,
3601 fail_next_insert: bool,
3602 removed_tiles: Vec<AtlasTile>,
3603 }
3604
3605 impl AtlasBackend for RecordingAtlasBackend {
3606 fn insert(
3607 &mut self,
3608 kind: AtlasTextureKind,
3609 size: Size<DevicePixels>,
3610 _bytes: &[u8],
3611 ) -> Result<AtlasTile> {
3612 self.insert_calls += 1;
3613 if std::mem::take(&mut self.fail_next_insert) {
3614 anyhow::bail!("backend failed");
3615 }
3616 Ok(AtlasTile {
3617 texture_id: AtlasTextureId { index: 0, kind },
3618 tile_id: TileId(self.insert_calls),
3619 padding: 0,
3620 bounds: Bounds {
3621 origin: Point::default(),
3622 size,
3623 },
3624 })
3625 }
3626
3627 fn remove(&mut self, tile: AtlasTile) {
3628 self.removed_tiles.push(tile);
3629 }
3630 }
3631
3632 fn image_key(image_id: usize) -> AtlasKey {
3633 AtlasKey::Image(RenderImageParams {
3634 image_id: crate::ImageId(image_id),
3635 frame_index: 0,
3636 })
3637 }
3638
3639 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3640 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3641 }
3642
3643 #[test]
3644 fn only_successful_inserts_are_cached() -> Result<()> {
3645 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3646 let key = image_key(1);
3647
3648 assert_eq!(
3649 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3650 None
3651 );
3652 state
3653 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3654 .expect_err("builder error should propagate");
3655 assert!(!state.contains(&key));
3656 assert_eq!(state.backend.insert_calls, 0);
3657
3658 state.backend.fail_next_insert = true;
3659 state
3660 .get_or_insert_with(key.clone(), &mut build_tile)
3661 .expect_err("backend error should propagate");
3662 assert!(!state.contains(&key));
3663 assert_eq!(state.backend.insert_calls, 1);
3664
3665 let tile = state
3666 .get_or_insert_with(key.clone(), &mut build_tile)?
3667 .context("builder should produce a tile")?;
3668 assert_eq!(tile.texture_id.kind, key.texture_kind());
3669 assert_eq!(
3670 state.get_or_insert_with(key.clone(), &mut || {
3671 anyhow::bail!("cache hit must not call the builder")
3672 })?,
3673 Some(tile)
3674 );
3675 assert!(state.contains(&key));
3676 assert_eq!(state.backend.insert_calls, 2);
3677 Ok(())
3678 }
3679
3680 #[test]
3681 fn remove_and_clear_invalidate_keys() -> Result<()> {
3682 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3683 let key = image_key(1);
3684 let other_key = image_key(2);
3685 let tile = state
3686 .get_or_insert_with(key.clone(), &mut build_tile)?
3687 .context("builder should produce a tile")?;
3688 state
3689 .get_or_insert_with(other_key.clone(), &mut build_tile)?
3690 .context("builder should produce another tile")?;
3691
3692 state.remove(&key);
3693 state.remove(&key);
3694 assert!(!state.contains(&key));
3695 assert!(state.contains(&other_key));
3696 assert_eq!(state.backend.removed_tiles, vec![tile]);
3697
3698 let mut reset_calls = 0;
3699 state.clear(|_| reset_calls += 1);
3700 assert_eq!(reset_calls, 1);
3701 assert!(!state.contains(&other_key));
3702 assert_eq!(state.backend.removed_tiles, vec![tile]);
3703 Ok(())
3704 }
3705}
3706
3707#[cfg(test)]
3708mod frame_signal_tests {
3709 use super::*;
3710
3711 #[cfg(feature = "profiler")]
3712 #[test]
3713 fn coalesced_signals_retain_the_earliest_until_drained() {
3714 for (first_source, later_source) in [
3715 (
3716 FrameRequestSource::NativeCallback,
3717 FrameRequestSource::LocalSchedule,
3718 ),
3719 (
3720 FrameRequestSource::LocalSchedule,
3721 FrameRequestSource::NativeCallback,
3722 ),
3723 ] {
3724 let signal = PlatformFrameSignal::new();
3725 let first =
3726 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3727 assert_eq!(signal.take(), None);
3728 signal.record(first + Duration::from_millis(16), later_source);
3729 signal.record(first, first_source);
3730 signal.record(first + Duration::from_millis(32), later_source);
3731 assert_eq!(signal.take(), Some((first, first_source)));
3732 assert_eq!(signal.take(), None);
3733 let next = first + Duration::from_millis(48);
3734 signal.record(next, later_source);
3735 assert_eq!(signal.take(), Some((next, later_source)));
3736 }
3737 }
3738
3739 #[cfg(not(feature = "profiler"))]
3740 #[test]
3741 fn disabled_profiling_does_not_capture_or_store_timestamps() {
3742 let captured = PlatformFrameSignal::capture(|| {
3743 panic!("profiler-disabled builds must not evaluate the capture closure");
3744 });
3745 assert_eq!(captured, None);
3746 let signal = PlatformFrameSignal::new();
3747 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3748 assert_eq!(signal.take(), None);
3749 }
3750}
3751
3752#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3753mod tests {
3754 use super::*;
3755 use std::collections::HashSet;
3756
3757 #[test]
3758 fn test_refresh_interval_from_hz() {
3759 assert_eq!(
3760 refresh_interval_from_hz(50.0),
3761 Some(Duration::from_millis(20))
3762 );
3763 assert_eq!(
3764 refresh_interval_from_hz(120.0),
3765 Some(Duration::from_secs(1) / 120)
3766 );
3767 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
3768 assert_eq!(refresh_interval_from_hz(unknown), None);
3769 }
3770 }
3771
3772 #[test]
3773 fn test_window_button_layout_parse_standard() {
3774 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3775 assert_eq!(
3776 layout.left,
3777 [
3778 Some(WindowButton::Close),
3779 Some(WindowButton::Minimize),
3780 None
3781 ]
3782 );
3783 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3784 }
3785
3786 #[test]
3787 fn test_window_button_layout_parse_right_only() {
3788 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3789 assert_eq!(layout.left, [None, None, None]);
3790 assert_eq!(
3791 layout.right,
3792 [
3793 Some(WindowButton::Minimize),
3794 Some(WindowButton::Maximize),
3795 Some(WindowButton::Close)
3796 ]
3797 );
3798 }
3799
3800 #[test]
3801 fn test_window_button_layout_parse_left_only() {
3802 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3803 assert_eq!(
3804 layout.left,
3805 [
3806 Some(WindowButton::Close),
3807 Some(WindowButton::Minimize),
3808 Some(WindowButton::Maximize)
3809 ]
3810 );
3811 assert_eq!(layout.right, [None, None, None]);
3812 }
3813
3814 #[test]
3815 fn test_window_button_layout_parse_with_whitespace() {
3816 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3817 assert_eq!(
3818 layout.left,
3819 [
3820 Some(WindowButton::Close),
3821 Some(WindowButton::Minimize),
3822 None
3823 ]
3824 );
3825 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3826 }
3827
3828 #[test]
3829 fn test_window_button_layout_parse_empty() {
3830 let layout = WindowButtonLayout::parse("").unwrap();
3831 assert_eq!(layout.left, [None, None, None]);
3832 assert_eq!(layout.right, [None, None, None]);
3833 }
3834
3835 #[test]
3836 fn test_window_button_layout_parse_intentionally_empty() {
3837 let layout = WindowButtonLayout::parse(":").unwrap();
3838 assert_eq!(layout.left, [None, None, None]);
3839 assert_eq!(layout.right, [None, None, None]);
3840 }
3841
3842 #[test]
3843 fn test_window_button_layout_parse_invalid_buttons() {
3844 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
3845 assert_eq!(
3846 layout.left,
3847 [
3848 Some(WindowButton::Close),
3849 Some(WindowButton::Minimize),
3850 None
3851 ]
3852 );
3853 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3854 }
3855
3856 #[test]
3857 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
3858 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
3859 assert_eq!(
3860 layout.right,
3861 [
3862 Some(WindowButton::Close),
3863 Some(WindowButton::Minimize),
3864 None
3865 ]
3866 );
3867 assert_eq!(layout.format(), ":close,minimize");
3868 }
3869
3870 #[test]
3871 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
3872 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
3873 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3874 assert_eq!(
3875 layout.right,
3876 [
3877 Some(WindowButton::Maximize),
3878 Some(WindowButton::Minimize),
3879 None
3880 ]
3881 );
3882
3883 let button_ids: Vec<_> = layout
3884 .left
3885 .iter()
3886 .chain(layout.right.iter())
3887 .flatten()
3888 .map(WindowButton::id)
3889 .collect();
3890 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
3891 assert_eq!(unique_button_ids.len(), button_ids.len());
3892 assert_eq!(layout.format(), "close:maximize,minimize");
3893 }
3894
3895 #[test]
3896 fn test_window_button_layout_parse_gnome_style() {
3897 let layout = WindowButtonLayout::parse("close").unwrap();
3898 assert_eq!(layout.left, [None, None, None]);
3899 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
3900 }
3901
3902 #[test]
3903 fn test_window_button_layout_parse_elementary_style() {
3904 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
3905 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3906 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3907 }
3908
3909 #[test]
3910 fn test_window_button_layout_round_trip() {
3911 let cases = [
3912 "close:minimize,maximize",
3913 "minimize,maximize,close:",
3914 ":close",
3915 "close:",
3916 "close:maximize",
3917 ":",
3918 ];
3919
3920 for case in cases {
3921 let layout = WindowButtonLayout::parse(case).unwrap();
3922 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
3923 }
3924 }
3925
3926 #[test]
3927 fn test_window_button_layout_linux_default() {
3928 let layout = WindowButtonLayout::linux_default();
3929 assert_eq!(layout.left, [None, None, None]);
3930 assert_eq!(
3931 layout.right,
3932 [
3933 Some(WindowButton::Minimize),
3934 Some(WindowButton::Maximize),
3935 Some(WindowButton::Close)
3936 ]
3937 );
3938
3939 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
3940 assert_eq!(round_tripped, layout);
3941 }
3942
3943 #[test]
3944 fn test_window_button_layout_parse_all_invalid() {
3945 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
3946 }
3947}