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 power_mode(&self) -> PowerMode {
521 PowerMode::Unknown
522 }
523 fn on_power_mode_change(&self, _callback: Box<dyn FnMut()>) {}
525
526 fn set_app_identity(&self, identifier: &str, name: &str) {
533 _ = (identifier, name);
534 }
535
536 fn show_system_notification(&self, notification: SystemNotification) {
543 _ = notification;
544 }
545
546 fn dismiss_system_notification(&self, tag: &str) {
551 _ = tag;
552 }
553
554 fn on_system_notification_response(
560 &self,
561 callback: Box<dyn FnMut(SystemNotificationResponse)>,
562 ) {
563 _ = callback;
564 }
565
566 fn compositor_name(&self) -> &'static str {
567 ""
568 }
569 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
572 None
573 }
574 fn app_path(&self) -> Result<PathBuf>;
575 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
576
577 fn set_cursor_style(&self, style: CursorStyle);
578
579 fn hide_cursor_until_mouse_moves(&self);
582
583 fn is_cursor_visible(&self) -> bool;
585
586 fn should_auto_hide_scrollbars(&self) -> bool;
587
588 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
589 fn write_to_clipboard(&self, item: ClipboardItem);
590
591 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
599 Task::ready(Ok(self.read_from_clipboard()))
600 }
601
602 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
603 fn read_from_primary(&self) -> Option<ClipboardItem>;
604 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
605 fn write_to_primary(&self, item: ClipboardItem);
606
607 #[cfg(target_os = "macos")]
608 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
609 #[cfg(target_os = "macos")]
610 fn write_to_find_pasteboard(&self, item: ClipboardItem);
611
612 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
613
614 #[cfg(target_os = "macos")]
618 fn write_credentials_if_not_exists(
619 &self,
620 _url: &str,
621 _username: &str,
622 _password: &[u8],
623 ) -> Task<Result<bool>> {
624 Task::ready(Err(anyhow::anyhow!(
625 "this platform does not support atomic credential writes"
626 )))
627 }
628
629 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
630 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
631
632 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
633 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
634 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
635}
636
637pub trait PlatformDisplay: Debug {
639 fn id(&self) -> DisplayId;
641
642 fn uuid(&self) -> Result<Uuid>;
645
646 fn bounds(&self) -> Bounds<Pixels>;
648
649 fn refresh_interval(&self) -> Option<Duration>;
656
657 fn visible_bounds(&self) -> Bounds<Pixels> {
661 self.bounds()
662 }
663
664 fn default_bounds(&self) -> Bounds<Pixels> {
666 let bounds = self.bounds();
667 let center = bounds.center();
668 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
669
670 let offset = clipped_window_size / 2.0;
671 let origin = point(center.x - offset.width, center.y - offset.height);
672 Bounds::new(origin, clipped_window_size)
673 }
674}
675
676#[derive(Clone, Debug, PartialEq, Eq)]
679pub struct SystemNotification {
680 pub tag: SharedString,
684 pub title: SharedString,
686 pub body: SharedString,
688 pub actions: Vec<SystemNotificationAction>,
691}
692
693#[derive(Clone, Debug, PartialEq, Eq, Hash)]
695pub struct SystemNotificationAction {
696 pub id: SharedString,
699 pub label: SharedString,
701}
702
703#[derive(Clone, Debug, PartialEq, Eq)]
705pub struct SystemNotificationResponse {
706 pub tag: SharedString,
708 pub action_id: Option<SharedString>,
711}
712
713#[derive(Debug, Clone, Copy, PartialEq, Eq)]
715pub enum PowerMode {
716 Unknown,
719 LowPower,
721 Balanced,
723 HighPower,
725}
726
727#[derive(Debug, Clone, Copy, PartialEq, Eq)]
729pub enum ThermalState {
730 Nominal,
732 Fair,
734 Serious,
736 Critical,
738}
739
740#[derive(Clone)]
742pub struct SourceMetadata {
743 pub id: u64,
745 pub label: Option<SharedString>,
747 pub is_main: Option<bool>,
749 pub resolution: Size<DevicePixels>,
751}
752
753pub trait ScreenCaptureSource {
755 fn metadata(&self) -> Result<SourceMetadata>;
757
758 fn stream(
761 &self,
762 foreground_executor: &ForegroundExecutor,
763 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
764 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
765}
766
767pub trait ScreenCaptureStream {
769 fn metadata(&self) -> Result<SourceMetadata>;
771}
772
773pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
775
776#[derive(PartialEq, Eq, Hash, Copy, Clone)]
778pub struct DisplayId(pub(crate) u64);
779
780impl DisplayId {
781 pub fn new(id: u64) -> Self {
783 Self(id)
784 }
785}
786
787impl From<u64> for DisplayId {
788 fn from(id: u64) -> Self {
789 Self(id)
790 }
791}
792
793impl From<DisplayId> for u64 {
794 fn from(id: DisplayId) -> Self {
795 id.0
796 }
797}
798
799impl Debug for DisplayId {
800 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801 write!(f, "DisplayId({})", self.0)
802 }
803}
804
805#[derive(Debug, Clone, Copy, PartialEq, Eq)]
807pub enum ResizeEdge {
808 Top,
810 TopRight,
812 Right,
814 BottomRight,
816 Bottom,
818 BottomLeft,
820 Left,
822 TopLeft,
824}
825
826#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
828pub enum WindowDecorations {
829 #[default]
830 Server,
832 Client,
834}
835
836#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
838pub enum Decorations {
839 #[default]
841 Server,
842 Client {
844 tiling: Tiling,
846 },
847}
848
849#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
851pub struct WindowControls {
852 pub fullscreen: bool,
854 pub maximize: bool,
856 pub minimize: bool,
858 pub window_menu: bool,
860}
861
862impl Default for WindowControls {
863 fn default() -> Self {
864 Self {
866 fullscreen: true,
867 maximize: true,
868 minimize: true,
869 window_menu: true,
870 }
871 }
872}
873
874#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
876pub enum WindowButton {
877 Minimize,
879 Maximize,
881 Close,
883}
884
885impl WindowButton {
886 pub fn id(&self) -> &'static str {
888 match self {
889 WindowButton::Minimize => "minimize",
890 WindowButton::Maximize => "maximize",
891 WindowButton::Close => "close",
892 }
893 }
894
895 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
896 fn index(&self) -> usize {
897 match self {
898 WindowButton::Minimize => 0,
899 WindowButton::Maximize => 1,
900 WindowButton::Close => 2,
901 }
902 }
903}
904
905pub const MAX_BUTTONS_PER_SIDE: usize = 3;
907
908#[derive(Debug, Clone, Copy, PartialEq, Eq)]
913pub struct WindowButtonLayout {
914 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
916 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
918}
919
920#[cfg(any(target_os = "linux", target_os = "freebsd"))]
921impl WindowButtonLayout {
922 pub fn linux_default() -> Self {
924 Self {
925 left: [None; MAX_BUTTONS_PER_SIDE],
926 right: [
927 Some(WindowButton::Minimize),
928 Some(WindowButton::Maximize),
929 Some(WindowButton::Close),
930 ],
931 }
932 }
933
934 pub fn parse(layout_string: &str) -> Result<Self> {
936 fn parse_side(
937 s: &str,
938 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
939 unrecognized: &mut Vec<String>,
940 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
941 let mut result = [None; MAX_BUTTONS_PER_SIDE];
942 let mut i = 0;
943 for name in s.split(',') {
944 let trimmed = name.trim();
945 if trimmed.is_empty() {
946 continue;
947 }
948 let button = match trimmed {
949 "minimize" => Some(WindowButton::Minimize),
950 "maximize" => Some(WindowButton::Maximize),
951 "close" => Some(WindowButton::Close),
952 other => {
953 unrecognized.push(other.to_string());
954 None
955 }
956 };
957 if let Some(button) = button {
958 if seen_buttons[button.index()] {
959 continue;
960 }
961 if let Some(slot) = result.get_mut(i) {
962 *slot = Some(button);
963 seen_buttons[button.index()] = true;
964 i += 1;
965 }
966 }
967 }
968 result
969 }
970
971 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
972 let mut unrecognized = Vec::new();
973 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
974 let layout = Self {
975 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
976 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
977 };
978
979 if !unrecognized.is_empty()
980 && layout.left.iter().all(Option::is_none)
981 && layout.right.iter().all(Option::is_none)
982 {
983 bail!(
984 "button layout string {:?} contains no valid buttons (unrecognized: {})",
985 layout_string,
986 unrecognized.join(", ")
987 );
988 }
989
990 Ok(layout)
991 }
992
993 #[cfg(test)]
995 pub fn format(&self) -> String {
996 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
997 buttons
998 .iter()
999 .flatten()
1000 .map(|button| match button {
1001 WindowButton::Minimize => "minimize",
1002 WindowButton::Maximize => "maximize",
1003 WindowButton::Close => "close",
1004 })
1005 .collect::<Vec<_>>()
1006 .join(",")
1007 }
1008
1009 format!("{}:{}", format_side(&self.left), format_side(&self.right))
1010 }
1011}
1012
1013#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1015pub struct Tiling {
1016 pub top: bool,
1018 pub left: bool,
1020 pub right: bool,
1022 pub bottom: bool,
1024}
1025
1026impl Tiling {
1027 pub fn tiled() -> Self {
1029 Self {
1030 top: true,
1031 left: true,
1032 right: true,
1033 bottom: true,
1034 }
1035 }
1036
1037 pub fn is_tiled(&self) -> bool {
1039 self.top || self.left || self.right || self.bottom
1040 }
1041}
1042
1043pub struct A11yCallbacks {
1045 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1047 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1049 pub deactivation: Box<dyn Fn() + Send + 'static>,
1051}
1052
1053#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1055pub enum FrameRequestSource {
1056 #[default]
1058 NativeCallback,
1059 LocalSchedule,
1061}
1062
1063#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1064#[expect(missing_docs)]
1065pub struct RequestFrameOptions {
1066 pub require_presentation: bool,
1068 pub force_render: bool,
1070 pub signal_at: Option<Instant>,
1076 pub signal_source: FrameRequestSource,
1078}
1079
1080pub struct PlatformFrameSignal {
1089 #[cfg(feature = "profiler")]
1090 origin: Instant,
1091 #[cfg(feature = "profiler")]
1092 first_signal: std::sync::atomic::AtomicU64,
1093}
1094
1095impl Default for PlatformFrameSignal {
1096 fn default() -> Self {
1097 Self::new()
1098 }
1099}
1100
1101impl PlatformFrameSignal {
1102 pub fn new() -> Self {
1104 Self {
1105 #[cfg(feature = "profiler")]
1106 origin: Instant::now(),
1107 #[cfg(feature = "profiler")]
1108 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1109 }
1110 }
1111
1112 #[inline]
1116 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1117 if cfg!(feature = "profiler") {
1118 Some(capture())
1119 } else {
1120 None
1121 }
1122 }
1123
1124 #[inline]
1126 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1127 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1128 #[cfg(feature = "profiler")]
1129 {
1130 let nanoseconds = at
1131 .saturating_duration_since(self.origin)
1132 .as_nanos()
1133 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1134 let source_bit = match source {
1135 FrameRequestSource::NativeCallback => 0,
1136 FrameRequestSource::LocalSchedule => 1,
1137 };
1138 self.first_signal.fetch_min(
1139 (nanoseconds << 1) | source_bit,
1140 std::sync::atomic::Ordering::Relaxed,
1141 );
1142 }
1143 }
1144
1145 #[inline]
1147 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1148 #[cfg(feature = "profiler")]
1149 {
1150 let signal = self
1151 .first_signal
1152 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1153 (signal != u64::MAX).then(|| {
1154 let source = match signal & 1 {
1155 0 => FrameRequestSource::NativeCallback,
1156 _ => FrameRequestSource::LocalSchedule,
1157 };
1158 (self.origin + Duration::from_nanos(signal >> 1), source)
1159 })
1160 }
1161 #[cfg(not(feature = "profiler"))]
1162 {
1163 None
1164 }
1165 }
1166}
1167
1168#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1181pub enum AppLifecyclePhase {
1182 Active,
1184 Inactive,
1186 Background,
1189 Foreground,
1191 Disconnected,
1195}
1196
1197#[derive(Debug, Clone, Default, PartialEq)]
1204pub struct WindowInsets {
1205 pub safe_area: Edges<Pixels>,
1210 pub ime: Edges<Pixels>,
1214 pub corner_radii: Corners<Pixels>,
1219}
1220
1221impl WindowInsets {
1222 pub fn effective(&self) -> Edges<Pixels> {
1224 Edges {
1225 top: self.safe_area.top.max(self.ime.top),
1226 right: self.safe_area.right.max(self.ime.right),
1227 bottom: self.safe_area.bottom.max(self.ime.bottom),
1228 left: self.safe_area.left.max(self.ime.left),
1229 }
1230 }
1231}
1232
1233#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1235pub enum TextInputStateChange {
1236 FocusGained,
1238 FocusLost,
1240 SelectionChanged,
1242 ContentChanged,
1244}
1245
1246#[expect(missing_docs)]
1247pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1248 fn bounds(&self) -> Bounds<Pixels>;
1249 fn is_maximized(&self) -> bool;
1250 fn window_bounds(&self) -> WindowBounds;
1251 fn content_size(&self) -> Size<Pixels>;
1252 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1258 Bounds::new(Point::default(), self.content_size())
1259 }
1260 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1265 fn prepare_frame(&self) -> bool {
1270 false
1271 }
1272 fn resize(&mut self, size: Size<Pixels>);
1273 fn scale_factor(&self) -> f32;
1274 fn appearance(&self) -> WindowAppearance;
1275 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1276 fn mouse_position(&self) -> Point<Pixels>;
1277 fn modifiers(&self) -> Modifiers;
1278 fn capslock(&self) -> Capslock;
1279 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1280 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1281 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1286 fn prompt(
1287 &self,
1288 level: PromptLevel,
1289 msg: &str,
1290 detail: Option<&str>,
1291 answers: &[PromptButton],
1292 ) -> Option<oneshot::Receiver<usize>>;
1293 fn activate(&self);
1294 fn request_attention(&self) {}
1296 fn is_active(&self) -> bool;
1297 fn visibility(&self) -> WindowVisibility;
1300 fn is_hovered(&self) -> bool;
1301 fn background_appearance(&self) -> WindowBackgroundAppearance;
1302 fn set_title(&mut self, title: &str);
1303 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1304 fn minimize(&self);
1305 fn zoom(&self);
1306 fn toggle_fullscreen(&self);
1307 fn is_fullscreen(&self) -> bool;
1308 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1309 None
1310 }
1311 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1312 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1313 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1314 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1318 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1319 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1320 fn on_moved(&self, callback: Box<dyn FnMut()>);
1321 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1325 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1326 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1327 fn on_close(&self, callback: Box<dyn FnOnce()>);
1328 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1329 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1330 fn draw(&self, scene: &Scene);
1331 fn draw_composed(&self, scene: crate::fast::composition::ComposedScene<'_>) {
1332 crate::fast::composition::draw_uncomposed(self, scene)
1333 }
1334 fn enable_window_composition(&self) -> Result<()> {
1335 crate::fast::composition::unsupported("window composition")
1336 }
1337 fn create_native_surface(
1338 &self,
1339 ) -> Result<Rc<dyn crate::fast::composition::PlatformSurfaceAttachment>> {
1340 crate::fast::composition::unsupported("native surface portals")
1341 }
1342 fn set_composition_order(
1343 &self,
1344 _fast_surfaces: &[crate::fast::composition::PlatformCompositionSurface],
1345 ) -> Result<()> {
1346 crate::fast::composition::unsupported("surface ordering")
1347 }
1348 fn schedule_frame(&self) {}
1349 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1350 fn is_subpixel_rendering_supported(&self) -> bool;
1351
1352 fn get_title(&self) -> String {
1354 String::new()
1355 }
1356 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1357 None
1358 }
1359 fn tab_bar_visible(&self) -> bool {
1360 false
1361 }
1362 fn set_edited(&mut self, _edited: bool) {}
1363 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1364 fn toggle_simple_fullscreen(&self) {}
1365 fn is_simple_fullscreen(&self) -> bool {
1366 false
1367 }
1368 #[cfg(target_os = "macos")]
1369 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1370 fn show_character_palette(&self) {}
1371 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1372 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1373 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1374 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1375 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1376 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1377 fn merge_all_windows(&self) {}
1378 fn move_tab_to_new_window(&self) {}
1379 fn toggle_window_tab_overview(&self) {}
1380 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1381
1382 fn native_window_state(&self) -> Option<Vec<u8>> {
1383 None
1384 }
1385 fn restore_native_window_state(&self, _state: &[u8]) {}
1386
1387 #[cfg(target_os = "windows")]
1388 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1389
1390 fn inner_window_bounds(&self) -> WindowBounds {
1392 self.window_bounds()
1393 }
1394 fn request_decorations(&self, _decorations: WindowDecorations) {}
1395 fn show_window_menu(&self, _position: Point<Pixels>) {}
1396 fn start_window_move(&self) {}
1397 fn can_start_external_drag(&self) -> bool {
1398 false
1399 }
1400 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1401 false
1402 }
1403 fn start_window_resize(&self, _edge: ResizeEdge) {}
1404 fn set_exclusive_zone(&self, _zone: Pixels) {}
1405 #[cfg(all(target_os = "linux", feature = "wayland"))]
1406 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1407 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1408 fn window_decorations(&self) -> Decorations {
1409 Decorations::Server
1410 }
1411 fn set_app_id(&mut self, _app_id: &str) {}
1412 fn map_window(&mut self) -> anyhow::Result<()> {
1413 Ok(())
1414 }
1415 fn window_controls(&self) -> WindowControls {
1416 WindowControls::default()
1417 }
1418 fn set_client_inset(&self, _inset: Pixels) {}
1419 fn set_client_corner_radii(&self, _radii: Corners<Pixels>) {}
1420 fn gpu_specs(&self) -> Option<GpuSpecs>;
1421
1422 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1423
1424 fn insets(&self) -> WindowInsets {
1429 WindowInsets::default()
1430 }
1431
1432 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1438
1439 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1442
1443 fn set_back_enabled(&self, _enabled: bool) {}
1446
1447 fn show_soft_keyboard(&self) {}
1449
1450 fn hide_soft_keyboard(&self) {}
1452
1453 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1455
1456 fn play_system_bell(&self) {}
1457
1458 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1460
1461 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1463
1464 fn a11y_update_window_bounds(&self) {}
1466
1467 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1468 fn as_test(&mut self) -> Option<&mut TestWindow> {
1469 None
1470 }
1471
1472 #[cfg(any(test, feature = "test-support"))]
1476 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1477 anyhow::bail!("render_to_image not implemented for this platform")
1478 }
1479}
1480
1481#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1483pub trait PlatformHeadlessRenderer {
1484 fn render_scene_to_image(
1486 &mut self,
1487 scene: &Scene,
1488 size: Size<DevicePixels>,
1489 ) -> Result<RgbaImage>;
1490
1491 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1497
1498 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1500}
1501
1502#[doc(hidden)]
1505pub type RunnableVariant = Runnable<RunnableMeta>;
1506
1507#[doc(hidden)]
1508pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1509
1510#[doc(hidden)]
1511pub enum TasksIncluded {
1512 OnlyCompleted,
1513 CompletedAndRunning,
1514}
1515
1516#[doc(hidden)]
1519pub trait PlatformDispatcher: Send + Sync {
1520 fn is_main_thread(&self) -> bool;
1521 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1522 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1523 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1524
1525 fn dispatch_on_main_thread_when_idle(
1526 &self,
1527 runnable: RunnableVariant,
1528 timeout: Option<Duration>,
1529 ) {
1530 let _ = timeout;
1531 self.dispatch_on_main_thread(runnable, Priority::Low);
1532 }
1533
1534 fn idle_time_remaining(&self) -> Option<Duration> {
1535 None
1536 }
1537
1538 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1539
1540 fn now(&self) -> Instant {
1541 Instant::now()
1542 }
1543
1544 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1545 gpui_util::defer(Box::new(|| {}))
1546 }
1547
1548 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1549 ActivityGuard::noop()
1550 }
1551
1552 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1553 fn as_test(&self) -> Option<&TestDispatcher> {
1554 None
1555 }
1556
1557 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1560 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1561 None
1562 }
1563}
1564
1565#[expect(missing_docs)]
1566pub trait PlatformTextSystem: Send + Sync {
1567 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1568 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1570 fn all_font_names(&self) -> Vec<String>;
1572 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1574 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1576 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1578 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1580 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1582 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1584 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1586 fn rasterize_glyph(
1588 &self,
1589 params: &RenderGlyphParams,
1590 raster_bounds: Bounds<DevicePixels>,
1591 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1592 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1594 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1596 -> TextRenderingMode;
1597 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1599 0
1600 }
1601}
1602
1603#[expect(missing_docs)]
1604pub struct NoopTextSystem;
1605
1606#[expect(missing_docs)]
1607impl NoopTextSystem {
1608 #[allow(dead_code)]
1609 pub fn new() -> Self {
1610 Self
1611 }
1612}
1613
1614impl PlatformTextSystem for NoopTextSystem {
1615 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1616 Ok(())
1617 }
1618
1619 fn all_font_names(&self) -> Vec<String> {
1620 Vec::new()
1621 }
1622
1623 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1624 Ok(FontId(1))
1625 }
1626
1627 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1628 FontMetrics {
1629 units_per_em: 1000,
1630 ascent: 1025.0,
1631 descent: -275.0,
1632 line_gap: 0.0,
1633 underline_position: -95.0,
1634 underline_thickness: 60.0,
1635 cap_height: 698.0,
1636 x_height: 516.0,
1637 bounding_box: Bounds {
1638 origin: Point {
1639 x: -260.0,
1640 y: -245.0,
1641 },
1642 size: Size {
1643 width: 1501.0,
1644 height: 1364.0,
1645 },
1646 },
1647 }
1648 }
1649
1650 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1651 Ok(Bounds {
1652 origin: Point { x: 54.0, y: 0.0 },
1653 size: size(392.0, 528.0),
1654 })
1655 }
1656
1657 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1658 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1659 }
1660
1661 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1662 Some(GlyphId(ch.len_utf16() as u32))
1663 }
1664
1665 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1666 Ok(Default::default())
1667 }
1668
1669 fn rasterize_glyph(
1670 &self,
1671 _params: &RenderGlyphParams,
1672 raster_bounds: Bounds<DevicePixels>,
1673 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1674 Ok((raster_bounds.size, Vec::new()))
1675 }
1676
1677 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1678 let mut position = px(0.);
1679 let metrics = self.font_metrics(FontId(0));
1680 let em_width = font_size
1681 * self
1682 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1683 .unwrap()
1684 .width
1685 / metrics.units_per_em as f32;
1686 let mut glyphs = Vec::new();
1687 for (ix, c) in text.char_indices() {
1688 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1689 glyphs.push(ShapedGlyph {
1690 id: glyph,
1691 position: point(position, px(0.)),
1692 index: ix,
1693 is_emoji: glyph.0 == 2,
1694 });
1695 if glyph.0 == 2 {
1696 position += em_width * 2.0;
1697 } else {
1698 position += em_width;
1699 }
1700 } else {
1701 position += em_width
1702 }
1703 }
1704 let mut runs = Vec::default();
1705 if !glyphs.is_empty() {
1706 runs.push(ShapedRun {
1707 font_id: FontId(0),
1708 glyphs,
1709 });
1710 } else {
1711 position = px(0.);
1712 }
1713
1714 LineLayout {
1715 font_size,
1716 width: position,
1717 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1718 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1719 runs,
1720 len: text.len(),
1721 }
1722 }
1723
1724 fn recommended_rendering_mode(
1725 &self,
1726 _font_id: FontId,
1727 _font_size: Pixels,
1728 ) -> TextRenderingMode {
1729 TextRenderingMode::Grayscale
1730 }
1731}
1732
1733#[allow(dead_code)]
1738pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1739 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1740 [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], ];
1754
1755 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1756 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1757
1758 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1759 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1760
1761 [
1762 ratios[0] * NORM13,
1763 ratios[1] * NORM24,
1764 ratios[2] * NORM13,
1765 ratios[3] * NORM24,
1766 ]
1767}
1768
1769#[derive(PartialEq, Eq, Hash, Clone)]
1770#[expect(missing_docs)]
1771pub enum AtlasKey {
1772 Glyph(RenderGlyphParams),
1773 Svg(RenderSvgParams),
1774 Image(RenderImageParams),
1775}
1776
1777impl AtlasKey {
1778 pub fn texture_kind(&self) -> AtlasTextureKind {
1780 match self {
1781 AtlasKey::Glyph(params) => {
1782 if params.is_emoji {
1783 AtlasTextureKind::Polychrome
1784 } else if params.subpixel_rendering {
1785 AtlasTextureKind::Subpixel
1786 } else {
1787 AtlasTextureKind::Monochrome
1788 }
1789 }
1790 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1791 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1792 }
1793 }
1794}
1795
1796impl From<RenderGlyphParams> for AtlasKey {
1797 fn from(params: RenderGlyphParams) -> Self {
1798 Self::Glyph(params)
1799 }
1800}
1801
1802impl From<RenderSvgParams> for AtlasKey {
1803 fn from(params: RenderSvgParams) -> Self {
1804 Self::Svg(params)
1805 }
1806}
1807
1808impl From<RenderImageParams> for AtlasKey {
1809 fn from(params: RenderImageParams) -> Self {
1810 Self::Image(params)
1811 }
1812}
1813
1814#[expect(missing_docs)]
1815pub trait PlatformAtlas {
1816 fn get_or_insert_with<'a>(
1818 &self,
1819 key: AtlasKey,
1820 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1821 ) -> Result<Option<AtlasTile>>;
1822 fn remove(&self, key: &AtlasKey);
1823
1824 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1825 fn contains(&self, _key: &AtlasKey) -> bool {
1826 false
1827 }
1828}
1829
1830#[doc(hidden)]
1831pub trait AtlasBackend {
1832 fn insert(
1833 &mut self,
1834 kind: AtlasTextureKind,
1835 size: Size<DevicePixels>,
1836 bytes: &[u8],
1837 ) -> Result<AtlasTile>;
1838
1839 fn remove(&mut self, tile: AtlasTile);
1840}
1841
1842#[doc(hidden)]
1843pub struct AtlasState<Backend> {
1844 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1845 pub backend: Backend,
1846}
1847
1848impl<Backend> AtlasState<Backend> {
1849 pub fn new(backend: Backend) -> Self {
1850 Self {
1851 tiles_by_key: FxHashMap::default(),
1852 backend,
1853 }
1854 }
1855
1856 pub fn contains(&self, key: &AtlasKey) -> bool {
1857 self.tiles_by_key.contains_key(key)
1858 }
1859
1860 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1861 self.tiles_by_key.clear();
1862 reset_backend(&mut self.backend);
1863 }
1864}
1865
1866impl<Backend: Default> Default for AtlasState<Backend> {
1867 fn default() -> Self {
1868 Self::new(Backend::default())
1869 }
1870}
1871
1872impl<Backend: AtlasBackend> AtlasState<Backend> {
1873 pub fn get_or_insert_with<'a>(
1874 &mut self,
1875 key: AtlasKey,
1876 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1877 ) -> Result<Option<AtlasTile>> {
1878 match self.tiles_by_key.entry(key) {
1879 Entry::Occupied(entry) => Ok(Some(*entry.get())),
1880 Entry::Vacant(entry) => {
1881 profiling::scope!("new tile");
1882 let Some((size, bytes)) = build()? else {
1883 return Ok(None);
1884 };
1885 let tile = self
1886 .backend
1887 .insert(entry.key().texture_kind(), size, &bytes)?;
1888 entry.insert(tile);
1889 Ok(Some(tile))
1890 }
1891 }
1892 }
1893
1894 pub fn remove(&mut self, key: &AtlasKey) {
1895 if let Some(tile) = self.tiles_by_key.remove(key) {
1896 self.backend.remove(tile);
1897 }
1898 }
1899}
1900
1901#[derive(Default)]
1905pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1906
1907#[doc(hidden)]
1908#[derive(Default)]
1909pub struct HeadlessAtlasBackend {
1910 next_id: u32,
1911}
1912
1913impl AtlasBackend for HeadlessAtlasBackend {
1914 fn insert(
1915 &mut self,
1916 kind: AtlasTextureKind,
1917 size: Size<DevicePixels>,
1918 _bytes: &[u8],
1919 ) -> Result<AtlasTile> {
1920 self.next_id += 1;
1921 let texture_id = self.next_id;
1922 self.next_id += 1;
1923 let tile_id = self.next_id;
1924 Ok(AtlasTile {
1925 texture_id: AtlasTextureId {
1926 index: texture_id,
1927 kind,
1928 },
1929 tile_id: TileId(tile_id),
1930 padding: 0,
1931 bounds: Bounds {
1932 origin: Point::default(),
1933 size,
1934 },
1935 })
1936 }
1937
1938 fn remove(&mut self, _tile: AtlasTile) {}
1939}
1940
1941impl PlatformAtlas for HeadlessAtlas {
1942 fn get_or_insert_with<'a>(
1943 &self,
1944 key: AtlasKey,
1945 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1946 ) -> Result<Option<AtlasTile>> {
1947 self.0.lock().get_or_insert_with(key, build)
1948 }
1949
1950 fn remove(&self, key: &AtlasKey) {
1951 self.0.lock().remove(key);
1952 }
1953
1954 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1955 fn contains(&self, key: &AtlasKey) -> bool {
1956 self.0.lock().contains(key)
1957 }
1958}
1959
1960#[doc(hidden)]
1961pub struct AtlasTextureList<T> {
1962 pub textures: Vec<Option<T>>,
1963 pub free_list: Vec<usize>,
1964}
1965
1966impl<T> Default for AtlasTextureList<T> {
1967 fn default() -> Self {
1968 Self {
1969 textures: Vec::default(),
1970 free_list: Vec::default(),
1971 }
1972 }
1973}
1974
1975impl<T> ops::Index<usize> for AtlasTextureList<T> {
1976 type Output = Option<T>;
1977
1978 fn index(&self, index: usize) -> &Self::Output {
1979 &self.textures[index]
1980 }
1981}
1982
1983impl<T> AtlasTextureList<T> {
1984 #[allow(unused)]
1985 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1986 self.free_list.clear();
1987 self.textures.drain(..)
1988 }
1989
1990 #[allow(dead_code)]
1991 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1992 self.textures.iter_mut().flatten()
1993 }
1994}
1995
1996#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1997#[repr(C)]
1998#[expect(missing_docs)]
1999pub struct AtlasTile {
2000 pub texture_id: AtlasTextureId,
2002 pub tile_id: TileId,
2004 pub padding: u32,
2006 pub bounds: Bounds<DevicePixels>,
2008}
2009
2010#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2011#[repr(C)]
2012#[expect(missing_docs)]
2013pub struct AtlasTextureId {
2014 pub index: u32,
2017 pub kind: AtlasTextureKind,
2019}
2020
2021#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2022#[repr(C)]
2023#[cfg_attr(
2024 all(
2025 any(target_os = "linux", target_os = "freebsd"),
2026 not(any(feature = "x11", feature = "wayland"))
2027 ),
2028 allow(dead_code)
2029)]
2030#[expect(missing_docs)]
2031pub enum AtlasTextureKind {
2032 Monochrome = 0,
2033 Polychrome = 1,
2034 Subpixel = 2,
2035}
2036
2037#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2038#[repr(C)]
2039#[expect(missing_docs)]
2040pub struct TileId(pub u32);
2041
2042impl From<etagere::AllocId> for TileId {
2043 fn from(id: etagere::AllocId) -> Self {
2044 Self(id.serialize())
2045 }
2046}
2047
2048impl From<TileId> for etagere::AllocId {
2049 fn from(id: TileId) -> Self {
2050 Self::deserialize(id.0)
2051 }
2052}
2053
2054#[expect(missing_docs)]
2055pub struct PlatformInputHandler {
2056 cx: AsyncWindowContext,
2057 handler: Box<dyn InputHandler>,
2058 focus_id: Option<crate::FocusId>,
2059}
2060
2061#[expect(missing_docs)]
2062#[cfg_attr(
2063 all(
2064 any(target_os = "linux", target_os = "freebsd"),
2065 not(any(feature = "x11", feature = "wayland"))
2066 ),
2067 allow(dead_code)
2068)]
2069impl PlatformInputHandler {
2070 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2071 Self {
2072 cx,
2073 handler,
2074 focus_id: None,
2075 }
2076 }
2077
2078 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2079 self.focus_id = Some(focus_id);
2080 self
2081 }
2082
2083 pub fn focus_id(&self) -> Option<crate::FocusId> {
2088 self.focus_id
2089 }
2090
2091 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2092 self.cx
2093 .update(|window, cx| {
2094 self.handler
2095 .selected_text_range(ignore_disabled_input, window, cx)
2096 })
2097 .ok()
2098 .flatten()
2099 }
2100
2101 #[cfg_attr(target_os = "windows", allow(dead_code))]
2102 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2103 self.cx
2104 .update(|window, cx| self.handler.marked_text_range(window, cx))
2105 .ok()
2106 .flatten()
2107 }
2108
2109 #[cfg_attr(
2110 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2111 allow(dead_code)
2112 )]
2113 pub fn text_for_range(
2114 &mut self,
2115 range_utf16: Range<usize>,
2116 adjusted: &mut Option<Range<usize>>,
2117 ) -> Option<String> {
2118 self.cx
2119 .update(|window, cx| {
2120 self.handler
2121 .text_for_range(range_utf16, adjusted, window, cx)
2122 })
2123 .ok()
2124 .flatten()
2125 }
2126
2127 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2128 self.cx
2129 .update(|window, cx| {
2130 self.handler
2131 .replace_text_in_range(replacement_range, text, window, cx);
2132 })
2133 .ok();
2134 }
2135
2136 pub fn replace_and_mark_text_in_range(
2137 &mut self,
2138 range_utf16: Option<Range<usize>>,
2139 new_text: &str,
2140 new_selected_range: Option<Range<usize>>,
2141 ) {
2142 self.cx
2143 .update(|window, cx| {
2144 self.handler.replace_and_mark_text_in_range(
2145 range_utf16,
2146 new_text,
2147 new_selected_range,
2148 window,
2149 cx,
2150 )
2151 })
2152 .ok();
2153 }
2154
2155 #[cfg_attr(target_os = "windows", allow(dead_code))]
2156 pub fn unmark_text(&mut self) {
2157 self.cx
2158 .update(|window, cx| self.handler.unmark_text(window, cx))
2159 .ok();
2160 }
2161
2162 pub fn paste(&mut self, item: ClipboardItem) {
2163 self.cx
2164 .update(|window, cx| self.handler.paste(item, window, cx))
2165 .ok();
2166 }
2167
2168 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2169 self.cx
2170 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2171 .ok()
2172 .flatten()
2173 }
2174
2175 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2176 self.cx
2177 .update(|window, cx| {
2178 self.handler
2179 .selection_bounds_for_range(range_utf16, window, cx)
2180 })
2181 .unwrap_or_default()
2182 }
2183
2184 #[allow(dead_code)]
2185 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2186 self.handler.apple_press_and_hold_enabled()
2187 }
2188
2189 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2190 self.handler.replace_text_in_range(None, input, window, cx);
2191 }
2192
2193 pub fn compute_ime_candidate_bounds(
2194 marked_range: Option<Range<usize>>,
2195 selection: &UTF16Selection,
2196 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2197 ) -> Option<Bounds<Pixels>> {
2198 if let Some(marked_range) = marked_range {
2199 let mut line_start = marked_range.start;
2201
2202 let caret = selection.range.end;
2206 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2207 for i in (marked_range.start..caret).rev() {
2208 if let Some(b) = bounds_for_range(i..i) {
2209 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2210 line_start = i + 1;
2211 break;
2212 }
2213 }
2214 }
2215 }
2216 bounds_for_range(line_start..line_start)
2217 } else {
2218 let offset = if selection.reversed {
2220 selection.range.start
2221 } else {
2222 selection.range.end
2223 };
2224 bounds_for_range(offset..offset)
2225 }
2226 }
2227
2228 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2229 let marked_range = self.handler.marked_text_range(window, cx);
2230 let selection = self.handler.selected_text_range(true, window, cx)?;
2231 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2232 self.handler.bounds_for_range(range, window, cx)
2233 })
2234 }
2235
2236 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2237 let marked_range = self.marked_text_range();
2238 let selection = self.selected_text_range(true)?;
2239 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2240 self.bounds_for_range(range)
2241 })
2242 }
2243
2244 #[allow(unused)]
2245 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2246 self.cx
2247 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2248 .ok()
2249 .flatten()
2250 }
2251
2252 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2254 self.cx
2255 .update(|window, cx| {
2256 self.handler
2257 .set_selected_text_range(range_utf16, window, cx)
2258 })
2259 .ok();
2260 }
2261
2262 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2264 self.cx
2265 .update(|window, cx| self.handler.element_bounds(window, cx))
2266 .ok()
2267 .flatten()
2268 }
2269
2270 pub fn text_length_utf16(&mut self) -> Option<usize> {
2272 self.cx
2273 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2274 .ok()
2275 .flatten()
2276 }
2277
2278 #[allow(dead_code)]
2279 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2280 self.handler.accepts_text_input(window, cx)
2281 }
2282
2283 #[allow(dead_code)]
2284 pub fn query_accepts_text_input(&mut self) -> bool {
2285 self.cx
2286 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2287 .unwrap_or(true)
2288 }
2289
2290 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2295 let focus_id = self.focus_id;
2296 self.cx
2297 .update(|window, cx| {
2298 focus_id.is_some()
2299 && window.focus == focus_id
2300 && self.handler.accepts_text_input(window, cx)
2301 })
2302 .unwrap_or(false)
2303 }
2304
2305 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2311 self.cx
2312 .update(|window, cx| {
2313 !window.has_pending_keystrokes()
2315 && self.handler.prefers_ime_for_printable_keys(window, cx)
2316 })
2317 .unwrap_or(false)
2318 }
2319
2320 pub fn text_input_configuration(
2322 &mut self,
2323 window: &mut Window,
2324 cx: &mut App,
2325 ) -> TextInputConfiguration {
2326 self.handler.text_input_configuration(window, cx)
2327 }
2328
2329 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2331 self.cx
2332 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2333 .ok()
2334 .flatten()
2335 }
2336}
2337
2338#[derive(Debug)]
2341pub struct UTF16Selection {
2342 pub range: Range<usize>,
2345 pub reversed: bool,
2348}
2349
2350pub trait InputHandler: 'static {
2355 fn selected_text_range(
2360 &mut self,
2361 ignore_disabled_input: bool,
2362 window: &mut Window,
2363 cx: &mut App,
2364 ) -> Option<UTF16Selection>;
2365
2366 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2371
2372 fn text_for_range(
2377 &mut self,
2378 range_utf16: Range<usize>,
2379 adjusted_range: &mut Option<Range<usize>>,
2380 window: &mut Window,
2381 cx: &mut App,
2382 ) -> Option<String>;
2383
2384 fn replace_text_in_range(
2389 &mut self,
2390 replacement_range: Option<Range<usize>>,
2391 text: &str,
2392 window: &mut Window,
2393 cx: &mut App,
2394 );
2395
2396 fn replace_and_mark_text_in_range(
2403 &mut self,
2404 range_utf16: Option<Range<usize>>,
2405 new_text: &str,
2406 new_selected_range: Option<Range<usize>>,
2407 window: &mut Window,
2408 cx: &mut App,
2409 );
2410
2411 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2414
2415 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2422 if let Some(text) = item.text() {
2423 self.replace_text_in_range(None, &text, window, cx);
2424 }
2425 }
2426
2427 fn bounds_for_range(
2432 &mut self,
2433 range_utf16: Range<usize>,
2434 window: &mut Window,
2435 cx: &mut App,
2436 ) -> Option<Bounds<Pixels>>;
2437
2438 fn selection_bounds_for_range(
2445 &mut self,
2446 _range_utf16: Range<usize>,
2447 _window: &mut Window,
2448 _cx: &mut App,
2449 ) -> Vec<Bounds<Pixels>> {
2450 Vec::new()
2451 }
2452
2453 fn character_index_for_point(
2457 &mut self,
2458 point: Point<Pixels>,
2459 window: &mut Window,
2460 cx: &mut App,
2461 ) -> Option<usize>;
2462
2463 fn set_selected_text_range(
2473 &mut self,
2474 _range_utf16: Range<usize>,
2475 _window: &mut Window,
2476 _cx: &mut App,
2477 ) {
2478 }
2479
2480 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2487 None
2488 }
2489
2490 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2492 None
2493 }
2494
2495 #[allow(dead_code)]
2500 fn apple_press_and_hold_enabled(&mut self) -> bool {
2501 true
2502 }
2503
2504 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2506 true
2507 }
2508
2509 fn text_input_editable_range(
2520 &mut self,
2521 _window: &mut Window,
2522 _cx: &mut App,
2523 ) -> Option<Range<usize>> {
2524 None
2525 }
2526
2527 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2536 false
2537 }
2538
2539 fn text_input_configuration(
2545 &mut self,
2546 _window: &mut Window,
2547 _cx: &mut App,
2548 ) -> TextInputConfiguration {
2549 TextInputConfiguration::default()
2550 }
2551}
2552
2553#[derive(Clone, Debug, Default, PartialEq, Eq)]
2563pub struct TextInputConfiguration {
2564 pub autocorrect: bool,
2566 pub autocapitalize: Autocapitalize,
2568 pub suggestions: bool,
2570 pub input_action: TextInputAction,
2572}
2573
2574#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2576pub enum Autocapitalize {
2577 #[default]
2579 None,
2580 Words,
2582 Sentences,
2584 Characters,
2586}
2587
2588#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2598pub enum TextInputAction {
2599 #[default]
2601 Unspecified,
2602 Enter,
2604 Done,
2606 Go,
2608 Next,
2610 Previous,
2612 Search,
2614 Send,
2616}
2617
2618#[derive(Debug)]
2620pub struct WindowOptions {
2621 pub window_bounds: Option<WindowBounds>,
2625
2626 pub titlebar: Option<TitlebarOptions>,
2628
2629 pub focus: bool,
2631
2632 pub show: bool,
2634
2635 pub kind: WindowKind,
2637
2638 pub is_movable: bool,
2642
2643 pub app_owns_titlebar_drag: bool,
2655
2656 pub inactive_frame_interval: Option<Duration>,
2661
2662 pub low_power_frame_interval: Option<Duration>,
2667
2668 pub thermal_frame_interval: Option<Duration>,
2673
2674 pub is_resizable: bool,
2676
2677 pub is_minimizable: bool,
2679
2680 pub display_id: Option<DisplayId>,
2683
2684 pub window_background: WindowBackgroundAppearance,
2686
2687 pub app_id: Option<String>,
2689
2690 pub window_min_size: Option<Size<Pixels>>,
2692
2693 pub window_decorations: Option<WindowDecorations>,
2696
2697 pub icon: Option<Arc<image::RgbaImage>>,
2699
2700 pub tabbing_identifier: Option<String>,
2702
2703 pub use_display_p3: bool,
2705}
2706
2707#[derive(Debug)]
2709#[cfg_attr(
2710 all(
2711 any(target_os = "linux", target_os = "freebsd"),
2712 not(any(feature = "x11", feature = "wayland"))
2713 ),
2714 allow(dead_code)
2715)]
2716#[allow(missing_docs)]
2717pub struct WindowParams {
2718 pub bounds: Bounds<Pixels>,
2719
2720 #[cfg_attr(feature = "wayland", allow(dead_code))]
2722 pub titlebar: Option<TitlebarOptions>,
2723
2724 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2726 pub kind: WindowKind,
2727
2728 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2730 pub is_movable: bool,
2731
2732 #[cfg_attr(
2734 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2735 allow(dead_code)
2736 )]
2737 pub app_owns_titlebar_drag: bool,
2738
2739 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2741 pub is_resizable: bool,
2742
2743 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2745 pub is_minimizable: bool,
2746
2747 #[cfg_attr(
2748 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2749 allow(dead_code)
2750 )]
2751 pub focus: bool,
2752
2753 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2754 pub show: bool,
2755
2756 #[cfg_attr(feature = "wayland", allow(dead_code))]
2758 pub icon: Option<Arc<image::RgbaImage>>,
2759
2760 #[cfg_attr(feature = "wayland", allow(dead_code))]
2761 pub display_id: Option<DisplayId>,
2762
2763 #[cfg_attr(feature = "wayland", allow(dead_code))]
2764 pub app_id: Option<String>,
2765
2766 pub window_min_size: Option<Size<Pixels>>,
2767
2768 #[cfg(target_os = "macos")]
2769 pub tabbing_identifier: Option<String>,
2770
2771 #[cfg(target_os = "macos")]
2772 pub use_display_p3: bool,
2773}
2774
2775#[derive(Debug, Copy, Clone, PartialEq)]
2777pub enum WindowBounds {
2778 Windowed(Bounds<Pixels>),
2780 Maximized(Bounds<Pixels>),
2783 Fullscreen(Bounds<Pixels>),
2786}
2787
2788impl Default for WindowBounds {
2789 fn default() -> Self {
2790 WindowBounds::Windowed(Bounds::default())
2791 }
2792}
2793
2794impl WindowBounds {
2795 pub fn get_bounds(&self) -> Bounds<Pixels> {
2797 match self {
2798 WindowBounds::Windowed(bounds) => *bounds,
2799 WindowBounds::Maximized(bounds) => *bounds,
2800 WindowBounds::Fullscreen(bounds) => *bounds,
2801 }
2802 }
2803
2804 pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
2806 WindowBounds::Windowed(Bounds::centered(None, size, cx))
2807 }
2808}
2809
2810impl Default for WindowOptions {
2811 fn default() -> Self {
2812 Self {
2813 window_bounds: None,
2814 titlebar: Some(TitlebarOptions {
2815 title: Default::default(),
2816 appears_transparent: Default::default(),
2817 traffic_light_position: Default::default(),
2818 }),
2819 focus: true,
2820 show: true,
2821 kind: WindowKind::Normal,
2822 is_movable: true,
2823 app_owns_titlebar_drag: false,
2824 inactive_frame_interval: Some(Duration::from_micros(33_333)),
2825 low_power_frame_interval: Some(Duration::from_micros(33_333)),
2826 thermal_frame_interval: Some(Duration::from_micros(16_667)),
2827 is_resizable: true,
2828 is_minimizable: true,
2829 display_id: None,
2830 window_background: WindowBackgroundAppearance::default(),
2831 icon: None,
2832 app_id: None,
2833 window_min_size: None,
2834 window_decorations: None,
2835 tabbing_identifier: None,
2836 use_display_p3: false,
2837 }
2838 }
2839}
2840
2841#[derive(Debug, Default)]
2843pub struct TitlebarOptions {
2844 pub title: Option<SharedString>,
2846
2847 pub appears_transparent: bool,
2850
2851 pub traffic_light_position: Option<Point<Pixels>>,
2853}
2854
2855#[derive(Clone, Debug, PartialEq, Eq)]
2857pub enum WindowKind {
2858 Normal,
2860
2861 PopUp,
2864
2865 AnchoredPopup(popup::PopupOptions),
2872
2873 Floating,
2875
2876 #[cfg(all(target_os = "linux", feature = "wayland"))]
2879 LayerShell(layer_shell::LayerShellOptions),
2880
2881 Dialog,
2884}
2885
2886#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2891pub enum WindowAppearance {
2892 #[default]
2896 Light,
2897
2898 VibrantLight,
2902
2903 Dark,
2907
2908 VibrantDark,
2912}
2913
2914#[derive(Copy, Clone, Debug, Default, PartialEq)]
2917pub enum WindowBackgroundAppearance {
2918 #[default]
2926 Opaque,
2927 Transparent,
2929 Blurred,
2933 MicaBackdrop,
2935 MicaAltBackdrop,
2937}
2938
2939#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2941pub enum TextRenderingMode {
2942 #[default]
2944 PlatformDefault,
2945 Subpixel,
2947 Grayscale,
2949}
2950
2951#[derive(Clone, Debug)]
2953pub struct PathPromptOptions {
2954 pub files: bool,
2956 pub directories: bool,
2958 pub multiple: bool,
2960 pub prompt: Option<SharedString>,
2962}
2963
2964#[derive(Copy, Clone, Debug, PartialEq)]
2966pub enum PromptLevel {
2967 Info,
2969
2970 Warning,
2972
2973 Critical,
2975}
2976
2977#[derive(Clone, Debug, PartialEq)]
2979pub enum PromptButton {
2980 Ok(SharedString),
2982 Cancel(SharedString),
2984 Other(SharedString),
2986}
2987
2988impl PromptButton {
2989 pub fn new(label: impl Into<SharedString>) -> Self {
2991 PromptButton::Other(label.into())
2992 }
2993
2994 pub fn ok(label: impl Into<SharedString>) -> Self {
2996 PromptButton::Ok(label.into())
2997 }
2998
2999 pub fn cancel(label: impl Into<SharedString>) -> Self {
3001 PromptButton::Cancel(label.into())
3002 }
3003
3004 #[allow(dead_code)]
3006 pub fn is_cancel(&self) -> bool {
3007 matches!(self, PromptButton::Cancel(_))
3008 }
3009
3010 pub fn label(&self) -> &SharedString {
3012 match self {
3013 PromptButton::Ok(label) => label,
3014 PromptButton::Cancel(label) => label,
3015 PromptButton::Other(label) => label,
3016 }
3017 }
3018}
3019
3020impl From<&str> for PromptButton {
3021 fn from(value: &str) -> Self {
3022 match value.to_lowercase().as_str() {
3023 "ok" => PromptButton::Ok("OK".into()),
3024 "cancel" => PromptButton::Cancel("Cancel".into()),
3025 _ => PromptButton::Other(SharedString::from(value.to_owned())),
3026 }
3027 }
3028}
3029
3030#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
3032pub enum CursorStyle {
3033 #[default]
3035 Arrow,
3036
3037 IBeam,
3040
3041 Crosshair,
3044
3045 ClosedHand,
3048
3049 OpenHand,
3052
3053 PointingHand,
3056
3057 ResizeLeft,
3060
3061 ResizeRight,
3064
3065 ResizeLeftRight,
3068
3069 ResizeUp,
3072
3073 ResizeDown,
3076
3077 ResizeUpDown,
3080
3081 ResizeUpLeftDownRight,
3084
3085 ResizeUpRightDownLeft,
3088
3089 ResizeColumn,
3092
3093 ResizeRow,
3096
3097 IBeamCursorForVerticalLayout,
3100
3101 OperationNotAllowed,
3104
3105 DragLink,
3108
3109 DragCopy,
3112
3113 ContextualMenu,
3116}
3117
3118#[derive(Clone, Debug, Eq, PartialEq)]
3120pub struct ClipboardItem {
3121 pub entries: Vec<ClipboardEntry>,
3123}
3124
3125#[derive(Clone, Debug, PartialEq, Eq)]
3130pub enum ClipboardReadError {
3131 Unavailable,
3135 Denied(String),
3138 UnsupportedContent,
3141}
3142
3143impl std::fmt::Display for ClipboardReadError {
3144 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3145 match self {
3146 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3147 Self::Denied(message) => {
3148 write!(formatter, "clipboard access was denied: {message}")
3149 }
3150 Self::UnsupportedContent => {
3151 formatter.write_str("the clipboard contents are unsupported")
3152 }
3153 }
3154 }
3155}
3156
3157impl std::error::Error for ClipboardReadError {}
3158
3159#[derive(Clone, Debug, Eq, PartialEq)]
3161pub enum ClipboardEntry {
3162 String(ClipboardString),
3164 Image(Image),
3166 ExternalPaths(crate::ExternalPaths),
3168}
3169
3170impl ClipboardItem {
3171 pub fn new_string(text: String) -> Self {
3173 Self {
3174 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3175 }
3176 }
3177
3178 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3180 Self {
3181 entries: vec![ClipboardEntry::String(ClipboardString {
3182 text,
3183 metadata: Some(metadata),
3184 })],
3185 }
3186 }
3187
3188 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3190 Self {
3191 entries: vec![ClipboardEntry::String(
3192 ClipboardString::new(text).with_json_metadata(metadata),
3193 )],
3194 }
3195 }
3196
3197 pub fn new_image(image: &Image) -> Self {
3199 Self {
3200 entries: vec![ClipboardEntry::Image(image.clone())],
3201 }
3202 }
3203
3204 pub fn text(&self) -> Option<String> {
3207 let mut answer = String::new();
3208
3209 for entry in self.entries.iter() {
3210 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3211 answer.push_str(text);
3212 }
3213 }
3214
3215 if answer.is_empty() {
3216 for entry in self.entries.iter() {
3217 if let ClipboardEntry::ExternalPaths(paths) = entry {
3218 for path in &paths.0 {
3219 use std::fmt::Write as _;
3220 _ = write!(answer, "{}", path.display());
3221 }
3222 }
3223 }
3224 }
3225
3226 if !answer.is_empty() {
3227 Some(answer)
3228 } else {
3229 None
3230 }
3231 }
3232
3233 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3235 pub fn metadata(&self) -> Option<&String> {
3236 match self.entries().first() {
3237 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3238 clipboard_string.metadata.as_ref()
3239 }
3240 _ => None,
3241 }
3242 }
3243
3244 pub fn entries(&self) -> &[ClipboardEntry] {
3246 &self.entries
3247 }
3248
3249 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3251 self.entries.into_iter()
3252 }
3253}
3254
3255impl From<ClipboardString> for ClipboardEntry {
3256 fn from(value: ClipboardString) -> Self {
3257 Self::String(value)
3258 }
3259}
3260
3261impl From<String> for ClipboardEntry {
3262 fn from(value: String) -> Self {
3263 Self::from(ClipboardString::from(value))
3264 }
3265}
3266
3267impl From<Image> for ClipboardEntry {
3268 fn from(value: Image) -> Self {
3269 Self::Image(value)
3270 }
3271}
3272
3273impl From<ClipboardEntry> for ClipboardItem {
3274 fn from(value: ClipboardEntry) -> Self {
3275 Self {
3276 entries: vec![value],
3277 }
3278 }
3279}
3280
3281impl From<String> for ClipboardItem {
3282 fn from(value: String) -> Self {
3283 Self::from(ClipboardEntry::from(value))
3284 }
3285}
3286
3287impl From<Image> for ClipboardItem {
3288 fn from(value: Image) -> Self {
3289 Self::from(ClipboardEntry::from(value))
3290 }
3291}
3292
3293#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3295pub enum ImageFormat {
3296 Png,
3301 Jpeg,
3303 Webp,
3305 Gif,
3307 Svg,
3309 Bmp,
3311 Tiff,
3313 Ico,
3315 Pnm,
3317}
3318
3319impl ImageFormat {
3320 pub const fn mime_type(self) -> &'static str {
3322 match self {
3323 ImageFormat::Png => "image/png",
3324 ImageFormat::Jpeg => "image/jpeg",
3325 ImageFormat::Webp => "image/webp",
3326 ImageFormat::Gif => "image/gif",
3327 ImageFormat::Svg => "image/svg+xml",
3328 ImageFormat::Bmp => "image/bmp",
3329 ImageFormat::Tiff => "image/tiff",
3330 ImageFormat::Ico => "image/ico",
3331 ImageFormat::Pnm => "image/x-portable-anymap",
3332 }
3333 }
3334
3335 pub const fn extension(self) -> &'static str {
3337 match self {
3338 ImageFormat::Png => "png",
3339 ImageFormat::Jpeg => "jpg",
3340 ImageFormat::Webp => "webp",
3341 ImageFormat::Gif => "gif",
3342 ImageFormat::Svg => "svg",
3343 ImageFormat::Bmp => "bmp",
3344 ImageFormat::Tiff => "tiff",
3345 ImageFormat::Ico => "ico",
3346 ImageFormat::Pnm => "pnm",
3347 }
3348 }
3349
3350 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3352 use strum::IntoEnumIterator;
3353 Self::iter()
3354 .find(|format| format.mime_type() == mime_type)
3355 .or_else(|| Self::from_mime_type_alias(mime_type))
3356 }
3357
3358 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3362 match mime_type {
3363 "image/jpg" => Some(Self::Jpeg),
3364 "image/tif" => Some(Self::Tiff),
3365 _ => None,
3366 }
3367 }
3368}
3369
3370#[derive(Clone, Debug, PartialEq, Eq)]
3372pub struct Image {
3373 pub format: ImageFormat,
3375 pub bytes: Vec<u8>,
3377 pub id: u64,
3379}
3380
3381pub(crate) fn decode_static_image(
3382 bytes: &[u8],
3383 format: image::ImageFormat,
3384) -> Result<SmallVec<[Frame; 1]>> {
3385 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3386 .into_decoder()
3387 .context("creating image decoder")?;
3388 decode_static_image_from_decoder(decoder)
3389}
3390
3391pub(crate) fn decode_static_image_from_decoder(
3392 mut decoder: impl image::ImageDecoder,
3393) -> Result<SmallVec<[Frame; 1]>> {
3394 let orientation = decoder
3395 .orientation()
3396 .context("reading decoder's orientation")?;
3397 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3398 image.apply_orientation(orientation);
3399
3400 let mut data = image.into_rgba8();
3401 for pixel in data.chunks_exact_mut(4) {
3402 pixel.swap(0, 2);
3403 }
3404
3405 Ok(SmallVec::from_elem(Frame::new(data), 1))
3406}
3407
3408impl Hash for Image {
3409 fn hash<H: Hasher>(&self, state: &mut H) {
3410 state.write_u64(self.id);
3411 }
3412}
3413
3414impl Image {
3415 pub fn empty() -> Self {
3417 Self::from_bytes(ImageFormat::Png, Vec::new())
3418 }
3419
3420 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3422 Self {
3423 id: hash(&bytes),
3424 format,
3425 bytes,
3426 }
3427 }
3428
3429 pub fn id(&self) -> u64 {
3431 self.id
3432 }
3433
3434 pub fn use_render_image(
3436 self: Arc<Self>,
3437 window: &mut Window,
3438 cx: &mut App,
3439 ) -> Option<Arc<RenderImage>> {
3440 ImageSource::Image(self)
3441 .use_data(None, window, cx)
3442 .and_then(|result| result.ok())
3443 }
3444
3445 pub fn get_render_image(
3447 self: Arc<Self>,
3448 window: &mut Window,
3449 cx: &mut App,
3450 ) -> Option<Arc<RenderImage>> {
3451 ImageSource::Image(self)
3452 .get_data(None, window, cx)
3453 .and_then(|result| result.ok())
3454 }
3455
3456 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3458 ImageSource::Image(self).remove_asset(cx);
3459 }
3460
3461 #[cfg(any(test, feature = "test-support"))]
3464 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3465 ImageSource::Image(self.clone()).is_asset_cached(cx)
3466 }
3467
3468 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3470 let frames = match self.format {
3471 ImageFormat::Gif => {
3472 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
3473 let mut frames = SmallVec::new();
3474
3475 for frame in decoder.into_frames() {
3476 match frame {
3477 Ok(mut frame) => {
3478 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3480 pixel.swap(0, 2);
3481 }
3482 frames.push(frame);
3483 }
3484 Err(err) => {
3485 log::debug!("Skipping GIF frame due to decode error: {err}");
3486 }
3487 }
3488 }
3489
3490 if frames.is_empty() {
3491 anyhow::bail!("GIF could not be decoded: all frames failed");
3492 }
3493
3494 frames
3495 }
3496 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3497 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3498 ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
3499 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3500 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3501 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3502 ImageFormat::Svg => {
3503 return svg_renderer
3504 .render_single_frame(&self.bytes, 1.0)
3505 .map_err(Into::into);
3506 }
3507 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3508 };
3509
3510 Ok(Arc::new(RenderImage::new(frames)))
3511 }
3512
3513 pub fn format(&self) -> ImageFormat {
3515 self.format
3516 }
3517
3518 pub fn bytes(&self) -> &[u8] {
3520 self.bytes.as_slice()
3521 }
3522}
3523
3524#[derive(Clone, Debug, Eq, PartialEq)]
3526pub struct ClipboardString {
3527 pub text: String,
3529 pub metadata: Option<String>,
3531}
3532
3533impl ClipboardString {
3534 pub fn new(text: String) -> Self {
3536 Self {
3537 text,
3538 metadata: None,
3539 }
3540 }
3541
3542 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3545 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3546 self
3547 }
3548
3549 pub fn text(&self) -> &String {
3551 &self.text
3552 }
3553
3554 pub fn into_text(self) -> String {
3556 self.text
3557 }
3558
3559 pub fn metadata_json<T>(&self) -> Option<T>
3561 where
3562 T: for<'a> Deserialize<'a>,
3563 {
3564 self.metadata
3565 .as_ref()
3566 .and_then(|m| serde_json::from_str(m).ok())
3567 }
3568
3569 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3570 pub fn text_hash(text: &str) -> u64 {
3572 let mut hasher = SeaHasher::new();
3573 text.hash(&mut hasher);
3574 hasher.finish()
3575 }
3576}
3577
3578impl From<String> for ClipboardString {
3579 fn from(value: String) -> Self {
3580 Self {
3581 text: value,
3582 metadata: None,
3583 }
3584 }
3585}
3586
3587#[cfg(test)]
3588mod image_tests {
3589 use super::*;
3590 use std::sync::Arc;
3591
3592 #[test]
3593 fn test_image_to_image_data_applies_exif_orientation() {
3594 let image = Image::from_bytes(
3595 ImageFormat::Jpeg,
3596 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3597 );
3598
3599 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3600
3601 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3602
3603 let bytes = render_image.as_bytes(0).unwrap();
3604 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3605 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3606 }
3607
3608 #[test]
3609 fn test_svg_image_to_image_data_converts_to_bgra() {
3610 let image = Image::from_bytes(
3611 ImageFormat::Svg,
3612 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3613<rect width="1" height="1" fill="#38BDF8"/>
3614</svg>"##
3615 .to_vec(),
3616 );
3617
3618 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3619 let bytes = render_image.as_bytes(0).unwrap();
3620
3621 for pixel in bytes.chunks_exact(4) {
3622 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3623 }
3624 }
3625}
3626
3627#[cfg(test)]
3628mod atlas_tests {
3629 use super::*;
3630
3631 const TILE_SIZE: Size<DevicePixels> = Size {
3632 width: DevicePixels(1),
3633 height: DevicePixels(1),
3634 };
3635
3636 #[derive(Default)]
3637 struct RecordingAtlasBackend {
3638 insert_calls: u32,
3639 fail_next_insert: bool,
3640 removed_tiles: Vec<AtlasTile>,
3641 }
3642
3643 impl AtlasBackend for RecordingAtlasBackend {
3644 fn insert(
3645 &mut self,
3646 kind: AtlasTextureKind,
3647 size: Size<DevicePixels>,
3648 _bytes: &[u8],
3649 ) -> Result<AtlasTile> {
3650 self.insert_calls += 1;
3651 if std::mem::take(&mut self.fail_next_insert) {
3652 anyhow::bail!("backend failed");
3653 }
3654 Ok(AtlasTile {
3655 texture_id: AtlasTextureId { index: 0, kind },
3656 tile_id: TileId(self.insert_calls),
3657 padding: 0,
3658 bounds: Bounds {
3659 origin: Point::default(),
3660 size,
3661 },
3662 })
3663 }
3664
3665 fn remove(&mut self, tile: AtlasTile) {
3666 self.removed_tiles.push(tile);
3667 }
3668 }
3669
3670 fn image_key(image_id: usize) -> AtlasKey {
3671 AtlasKey::Image(RenderImageParams {
3672 image_id: crate::ImageId(image_id),
3673 frame_index: 0,
3674 })
3675 }
3676
3677 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3678 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3679 }
3680
3681 #[test]
3682 fn only_successful_inserts_are_cached() -> Result<()> {
3683 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3684 let key = image_key(1);
3685
3686 assert_eq!(
3687 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3688 None
3689 );
3690 state
3691 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3692 .expect_err("builder error should propagate");
3693 assert!(!state.contains(&key));
3694 assert_eq!(state.backend.insert_calls, 0);
3695
3696 state.backend.fail_next_insert = true;
3697 state
3698 .get_or_insert_with(key.clone(), &mut build_tile)
3699 .expect_err("backend error should propagate");
3700 assert!(!state.contains(&key));
3701 assert_eq!(state.backend.insert_calls, 1);
3702
3703 let tile = state
3704 .get_or_insert_with(key.clone(), &mut build_tile)?
3705 .context("builder should produce a tile")?;
3706 assert_eq!(tile.texture_id.kind, key.texture_kind());
3707 assert_eq!(
3708 state.get_or_insert_with(key.clone(), &mut || {
3709 anyhow::bail!("cache hit must not call the builder")
3710 })?,
3711 Some(tile)
3712 );
3713 assert!(state.contains(&key));
3714 assert_eq!(state.backend.insert_calls, 2);
3715 Ok(())
3716 }
3717
3718 #[test]
3719 fn remove_and_clear_invalidate_keys() -> Result<()> {
3720 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3721 let key = image_key(1);
3722 let other_key = image_key(2);
3723 let tile = state
3724 .get_or_insert_with(key.clone(), &mut build_tile)?
3725 .context("builder should produce a tile")?;
3726 state
3727 .get_or_insert_with(other_key.clone(), &mut build_tile)?
3728 .context("builder should produce another tile")?;
3729
3730 state.remove(&key);
3731 state.remove(&key);
3732 assert!(!state.contains(&key));
3733 assert!(state.contains(&other_key));
3734 assert_eq!(state.backend.removed_tiles, vec![tile]);
3735
3736 let mut reset_calls = 0;
3737 state.clear(|_| reset_calls += 1);
3738 assert_eq!(reset_calls, 1);
3739 assert!(!state.contains(&other_key));
3740 assert_eq!(state.backend.removed_tiles, vec![tile]);
3741 Ok(())
3742 }
3743}
3744
3745#[cfg(test)]
3746mod frame_signal_tests {
3747 use super::*;
3748
3749 #[cfg(feature = "profiler")]
3750 #[test]
3751 fn coalesced_signals_retain_the_earliest_until_drained() {
3752 for (first_source, later_source) in [
3753 (
3754 FrameRequestSource::NativeCallback,
3755 FrameRequestSource::LocalSchedule,
3756 ),
3757 (
3758 FrameRequestSource::LocalSchedule,
3759 FrameRequestSource::NativeCallback,
3760 ),
3761 ] {
3762 let signal = PlatformFrameSignal::new();
3763 let first =
3764 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3765 assert_eq!(signal.take(), None);
3766 signal.record(first + Duration::from_millis(16), later_source);
3767 signal.record(first, first_source);
3768 signal.record(first + Duration::from_millis(32), later_source);
3769 assert_eq!(signal.take(), Some((first, first_source)));
3770 assert_eq!(signal.take(), None);
3771 let next = first + Duration::from_millis(48);
3772 signal.record(next, later_source);
3773 assert_eq!(signal.take(), Some((next, later_source)));
3774 }
3775 }
3776
3777 #[cfg(not(feature = "profiler"))]
3778 #[test]
3779 fn disabled_profiling_does_not_capture_or_store_timestamps() {
3780 let captured = PlatformFrameSignal::capture(|| {
3781 panic!("profiler-disabled builds must not evaluate the capture closure");
3782 });
3783 assert_eq!(captured, None);
3784 let signal = PlatformFrameSignal::new();
3785 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3786 assert_eq!(signal.take(), None);
3787 }
3788}
3789
3790#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3791mod tests {
3792 use super::*;
3793 use std::collections::HashSet;
3794
3795 #[test]
3796 fn test_refresh_interval_from_hz() {
3797 assert_eq!(
3798 refresh_interval_from_hz(50.0),
3799 Some(Duration::from_millis(20))
3800 );
3801 assert_eq!(
3802 refresh_interval_from_hz(120.0),
3803 Some(Duration::from_secs(1) / 120)
3804 );
3805 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
3806 assert_eq!(refresh_interval_from_hz(unknown), None);
3807 }
3808 }
3809
3810 #[test]
3811 fn test_window_button_layout_parse_standard() {
3812 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3813 assert_eq!(
3814 layout.left,
3815 [
3816 Some(WindowButton::Close),
3817 Some(WindowButton::Minimize),
3818 None
3819 ]
3820 );
3821 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3822 }
3823
3824 #[test]
3825 fn test_window_button_layout_parse_right_only() {
3826 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3827 assert_eq!(layout.left, [None, None, None]);
3828 assert_eq!(
3829 layout.right,
3830 [
3831 Some(WindowButton::Minimize),
3832 Some(WindowButton::Maximize),
3833 Some(WindowButton::Close)
3834 ]
3835 );
3836 }
3837
3838 #[test]
3839 fn test_window_button_layout_parse_left_only() {
3840 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3841 assert_eq!(
3842 layout.left,
3843 [
3844 Some(WindowButton::Close),
3845 Some(WindowButton::Minimize),
3846 Some(WindowButton::Maximize)
3847 ]
3848 );
3849 assert_eq!(layout.right, [None, None, None]);
3850 }
3851
3852 #[test]
3853 fn test_window_button_layout_parse_with_whitespace() {
3854 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3855 assert_eq!(
3856 layout.left,
3857 [
3858 Some(WindowButton::Close),
3859 Some(WindowButton::Minimize),
3860 None
3861 ]
3862 );
3863 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3864 }
3865
3866 #[test]
3867 fn test_window_button_layout_parse_empty() {
3868 let layout = WindowButtonLayout::parse("").unwrap();
3869 assert_eq!(layout.left, [None, None, None]);
3870 assert_eq!(layout.right, [None, None, None]);
3871 }
3872
3873 #[test]
3874 fn test_window_button_layout_parse_intentionally_empty() {
3875 let layout = WindowButtonLayout::parse(":").unwrap();
3876 assert_eq!(layout.left, [None, None, None]);
3877 assert_eq!(layout.right, [None, None, None]);
3878 }
3879
3880 #[test]
3881 fn test_window_button_layout_parse_invalid_buttons() {
3882 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
3883 assert_eq!(
3884 layout.left,
3885 [
3886 Some(WindowButton::Close),
3887 Some(WindowButton::Minimize),
3888 None
3889 ]
3890 );
3891 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3892 }
3893
3894 #[test]
3895 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
3896 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
3897 assert_eq!(
3898 layout.right,
3899 [
3900 Some(WindowButton::Close),
3901 Some(WindowButton::Minimize),
3902 None
3903 ]
3904 );
3905 assert_eq!(layout.format(), ":close,minimize");
3906 }
3907
3908 #[test]
3909 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
3910 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
3911 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3912 assert_eq!(
3913 layout.right,
3914 [
3915 Some(WindowButton::Maximize),
3916 Some(WindowButton::Minimize),
3917 None
3918 ]
3919 );
3920
3921 let button_ids: Vec<_> = layout
3922 .left
3923 .iter()
3924 .chain(layout.right.iter())
3925 .flatten()
3926 .map(WindowButton::id)
3927 .collect();
3928 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
3929 assert_eq!(unique_button_ids.len(), button_ids.len());
3930 assert_eq!(layout.format(), "close:maximize,minimize");
3931 }
3932
3933 #[test]
3934 fn test_window_button_layout_parse_gnome_style() {
3935 let layout = WindowButtonLayout::parse("close").unwrap();
3936 assert_eq!(layout.left, [None, None, None]);
3937 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
3938 }
3939
3940 #[test]
3941 fn test_window_button_layout_parse_elementary_style() {
3942 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
3943 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3944 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3945 }
3946
3947 #[test]
3948 fn test_window_button_layout_round_trip() {
3949 let cases = [
3950 "close:minimize,maximize",
3951 "minimize,maximize,close:",
3952 ":close",
3953 "close:",
3954 "close:maximize",
3955 ":",
3956 ];
3957
3958 for case in cases {
3959 let layout = WindowButtonLayout::parse(case).unwrap();
3960 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
3961 }
3962 }
3963
3964 #[test]
3965 fn test_window_button_layout_linux_default() {
3966 let layout = WindowButtonLayout::linux_default();
3967 assert_eq!(layout.left, [None, None, None]);
3968 assert_eq!(
3969 layout.right,
3970 [
3971 Some(WindowButton::Minimize),
3972 Some(WindowButton::Maximize),
3973 Some(WindowButton::Close)
3974 ]
3975 );
3976
3977 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
3978 assert_eq!(round_tripped, layout);
3979 }
3980
3981 #[test]
3982 fn test_window_button_layout_parse_all_invalid() {
3983 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
3984 }
3985}