1mod app_menu;
3mod keyboard;
4mod keystroke;
5
6#[cfg(all(target_os = "linux", feature = "wayland"))]
7#[expect(missing_docs)]
8pub mod layer_shell;
9
10pub mod popup;
12
13#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
14mod threaded_dispatcher;
15
16#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
17mod test;
18
19#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
20mod visual_test;
21
22#[cfg(all(
23 feature = "screen-capture",
24 any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
25))]
26pub mod scap_screen_capture;
27
28#[cfg(all(
29 any(target_os = "windows", target_os = "linux"),
30 feature = "screen-capture"
31))]
32pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
33#[cfg(not(feature = "screen-capture"))]
34pub(crate) type PlatformScreenCaptureFrame = ();
35#[cfg(all(target_os = "macos", feature = "screen-capture"))]
36pub(crate) type PlatformScreenCaptureFrame =
37 objc2_core_foundation::CFRetained<objc2_core_video::CVImageBuffer>;
38
39use crate::{
40 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
41 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
42 FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap,
43 LineLayout, MissingGlyphSink, Pixels, PlatformGestures, PlatformInput, Point, Priority,
44 RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph,
45 ShapedRun, SharedString, Size, SvgRenderer, SystemWindowTab, Task, Window, WindowControlArea,
46 hash, point, px, size,
47};
48#[cfg(any(target_os = "linux", target_os = "freebsd"))]
49use anyhow::bail;
50use anyhow::{Context as _, Result};
51use async_task::Runnable;
52use collections::FxHashMap;
53use futures::channel::oneshot;
54#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
55use image::RgbaImage;
56use image::codecs::gif::GifDecoder;
57use image::{AnimationDecoder as _, DynamicImage, Frame};
58use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
59use scheduler::Instant;
60pub use scheduler::RunnableMeta;
61use schemars::JsonSchema;
62use seahash::SeaHasher;
63use serde::{Deserialize, Serialize};
64use smallvec::SmallVec;
65use std::borrow::Cow;
66use std::collections::hash_map::Entry;
67use std::hash::{Hash, Hasher};
68use std::io::Cursor;
69use std::ops;
70use std::time::Duration;
71use std::{
72 ffi::OsString,
73 fmt::{self, Debug},
74 ops::Range,
75 path::{Path, PathBuf},
76 rc::Rc,
77 sync::Arc,
78};
79use strum::EnumIter;
80use uuid::Uuid;
81
82pub use app_menu::*;
83pub use keyboard::*;
84pub use keystroke::*;
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum WindowVisibility {
108 Visible,
111 Hidden,
114}
115
116impl WindowVisibility {
117 pub fn is_visible(self) -> bool {
119 self == Self::Visible
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126#[non_exhaustive]
127pub enum DisplayEvent {
128 Added(DisplayId),
130 Removed(DisplayId),
133 Changed {
135 id: DisplayId,
137 changes: DisplayChanges,
139 },
140}
141
142bitflags::bitflags! {
143 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
145 pub struct DisplayChanges: u8 {
146 const BOUNDS = 1 << 0;
148 const REFRESH_INTERVAL = 1 << 1;
150 }
151}
152
153pub fn refresh_interval_from_hz(hertz: f64) -> Option<Duration> {
156 (hertz.is_finite() && hertz > 0.0).then(|| Duration::from_secs_f64(1.0 / hertz))
157}
158
159#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
166pub enum ActivationPolicy {
167 #[default]
169 Regular,
170 Accessory,
172}
173
174#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
175pub(crate) use test::*;
176
177#[cfg(any(test, feature = "test-support"))]
178pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
179
180#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
181pub use threaded_dispatcher::ThreadedDispatcher;
182
183#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
184pub use visual_test::VisualTestPlatform;
185
186pub struct ActivityGuard {
188 _release: gpui_util::Deferred<Box<dyn FnOnce() + Send>>,
189}
190
191impl ActivityGuard {
192 pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
194 Self {
195 _release: gpui_util::defer(Box::new(release)),
196 }
197 }
198
199 pub fn noop() -> Self {
201 Self::new(|| {})
202 }
203}
204
205#[cfg(any(target_os = "linux", target_os = "freebsd"))]
209#[inline]
210pub fn guess_compositor() -> &'static str {
211 if std::env::var_os("ZED_HEADLESS").is_some() {
212 return "Headless";
213 }
214 GraphicalEnvironment::detect().guess_compositor()
215}
216
217#[cfg(any(target_os = "linux", target_os = "freebsd"))]
226#[derive(Clone, Debug, Default)]
227pub struct GraphicalEnvironment {
228 pub wayland_display: Option<OsString>,
230 pub x11_display: Option<OsString>,
232 pub xdg_runtime_dir: Option<OsString>,
234 pub activation_token: Option<String>,
240}
241
242#[cfg(target_os = "windows")]
248#[derive(Clone, Debug, Default)]
249pub struct GraphicalEnvironment {
250 pub session_id: Option<u32>,
253}
254
255#[cfg(target_os = "windows")]
256impl GraphicalEnvironment {
257 pub fn detect() -> Self {
259 let mut session_id = 0;
260 let result = unsafe {
262 windows::Win32::System::RemoteDesktop::ProcessIdToSessionId(
263 windows::Win32::System::Threading::GetCurrentProcessId(),
264 &mut session_id,
265 )
266 };
267 Self {
268 session_id: result.is_ok().then_some(session_id),
269 }
270 }
271
272 pub fn apply_to(&self, _command: &mut std::process::Command) {}
275}
276
277#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
279#[derive(Clone, Debug, Default)]
280pub struct GraphicalEnvironment;
281
282#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
283impl GraphicalEnvironment {
284 pub fn detect() -> Self {
286 Self
287 }
288
289 pub fn apply_to(&self, _command: &mut std::process::Command) {}
291}
292
293#[derive(Clone, Debug)]
295pub enum WindowingRequest {
296 Headless,
298 Windowed(GraphicalEnvironment),
300}
301
302#[cfg(any(target_os = "linux", target_os = "freebsd"))]
303impl GraphicalEnvironment {
304 pub fn detect() -> Self {
309 Self {
310 wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
311 x11_display: std::env::var_os("DISPLAY"),
312 xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
313 activation_token: None,
314 }
315 }
316
317 pub fn apply_to(&self, command: &mut std::process::Command) {
321 for (name, value) in [
322 ("WAYLAND_DISPLAY", &self.wayland_display),
323 ("DISPLAY", &self.x11_display),
324 ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
325 ] {
326 match value {
327 Some(value) => command.env(name, value),
328 None => command.env_remove(name),
329 };
330 }
331 }
332
333 pub fn guess_compositor(&self) -> &'static str {
337 let is_set =
338 |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
339 if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
340 "Wayland"
341 } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
342 "X11"
343 } else {
344 "Headless"
345 }
346 }
347}
348
349#[cfg(any(target_os = "linux", target_os = "freebsd"))]
350bitflags::bitflags! {
351 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
353 pub struct WindowingModes: u8 {
354 const WAYLAND = 1 << 0;
356 const X11 = 1 << 1;
358 const HEADLESS = 1 << 2;
360 }
361}
362
363#[expect(missing_docs)]
364pub trait Platform: 'static {
365 fn background_executor(&self) -> BackgroundExecutor;
366 fn foreground_executor(&self) -> ForegroundExecutor;
367 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
368
369 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
370 fn quit(&self);
371 fn set_initial_windowing(&self, _request: WindowingRequest) {}
376 fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
377 Task::ready(Err(anyhow::anyhow!(
378 "this platform cannot switch between headless and windowed modes"
379 )))
380 }
381 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
382 fn activate(&self, ignoring_other_apps: bool);
383 fn set_activation_policy(&self, _policy: ActivationPolicy) {}
385 fn hide(&self);
386 fn hide_other_apps(&self);
387 fn unhide_other_apps(&self);
388
389 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
390 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
391 fn on_displays_changed(&self, callback: Box<dyn FnMut()>);
396 fn active_window(&self) -> Option<AnyWindowHandle>;
397 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
398 None
399 }
400
401 fn is_screen_capture_supported(&self) -> bool {
402 false
403 }
404
405 fn screen_capture_sources(
406 &self,
407 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
408 let (sources_tx, sources_rx) = oneshot::channel();
409 sources_tx
410 .send(Err(anyhow::anyhow!(
411 "gpui was compiled without the screen-capture feature"
412 )))
413 .ok();
414 sources_rx
415 }
416
417 fn open_window(
418 &self,
419 handle: AnyWindowHandle,
420 options: WindowParams,
421 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
422
423 fn window_appearance(&self) -> WindowAppearance;
425
426 fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
435
436 fn button_layout(&self) -> Option<WindowButtonLayout> {
438 None
439 }
440
441 fn open_url(&self, url: &str);
442 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
443 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
444
445 fn prompt_for_paths(
446 &self,
447 options: PathPromptOptions,
448 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
449 fn prompt_for_new_path(
450 &self,
451 directory: &Path,
452 suggested_name: Option<&str>,
453 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
454 fn can_select_mixed_files_and_dirs(&self) -> bool;
455 fn reveal_path(&self, path: &Path);
456 fn open_with_system(&self, path: &Path);
457
458 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
459 fn on_reopen(&self, callback: Box<dyn FnMut()>);
460 fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
462 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
464
465 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
475
476 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
481
482 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
486 None
487 }
488
489 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
490 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
491 None
492 }
493
494 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
495 fn perform_dock_menu_action(&self, _action: usize) {}
496 fn add_recent_document(&self, _path: &Path) {}
497 fn update_jump_list(
498 &self,
499 _menus: Vec<MenuItem>,
500 _entries: Vec<SmallVec<[PathBuf; 2]>>,
501 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
502 Task::ready(Vec::new())
503 }
504 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
505 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
506 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
507
508 fn thermal_state(&self) -> ThermalState;
509 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
510 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
511
512 fn set_app_identity(&self, identifier: &str, name: &str) {
519 _ = (identifier, name);
520 }
521
522 fn show_system_notification(&self, notification: SystemNotification) {
529 _ = notification;
530 }
531
532 fn dismiss_system_notification(&self, tag: &str) {
537 _ = tag;
538 }
539
540 fn on_system_notification_response(
546 &self,
547 callback: Box<dyn FnMut(SystemNotificationResponse)>,
548 ) {
549 _ = callback;
550 }
551
552 fn compositor_name(&self) -> &'static str {
553 ""
554 }
555 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
558 None
559 }
560 fn app_path(&self) -> Result<PathBuf>;
561 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
562
563 fn set_cursor_style(&self, style: CursorStyle);
564
565 fn hide_cursor_until_mouse_moves(&self);
568
569 fn is_cursor_visible(&self) -> bool;
571
572 fn should_auto_hide_scrollbars(&self) -> bool;
573
574 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
575 fn write_to_clipboard(&self, item: ClipboardItem);
576
577 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
585 Task::ready(Ok(self.read_from_clipboard()))
586 }
587
588 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
589 fn read_from_primary(&self) -> Option<ClipboardItem>;
590 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
591 fn write_to_primary(&self, item: ClipboardItem);
592
593 #[cfg(target_os = "macos")]
594 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
595 #[cfg(target_os = "macos")]
596 fn write_to_find_pasteboard(&self, item: ClipboardItem);
597
598 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
599 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
600 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
601
602 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
603 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
604 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
605}
606
607pub trait PlatformDisplay: Debug {
609 fn id(&self) -> DisplayId;
611
612 fn uuid(&self) -> Result<Uuid>;
615
616 fn bounds(&self) -> Bounds<Pixels>;
618
619 fn refresh_interval(&self) -> Option<Duration>;
626
627 fn visible_bounds(&self) -> Bounds<Pixels> {
631 self.bounds()
632 }
633
634 fn default_bounds(&self) -> Bounds<Pixels> {
636 let bounds = self.bounds();
637 let center = bounds.center();
638 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
639
640 let offset = clipped_window_size / 2.0;
641 let origin = point(center.x - offset.width, center.y - offset.height);
642 Bounds::new(origin, clipped_window_size)
643 }
644}
645
646#[derive(Clone, Debug, PartialEq, Eq)]
649pub struct SystemNotification {
650 pub tag: SharedString,
654 pub title: SharedString,
656 pub body: SharedString,
658 pub actions: Vec<SystemNotificationAction>,
661}
662
663#[derive(Clone, Debug, PartialEq, Eq, Hash)]
665pub struct SystemNotificationAction {
666 pub id: SharedString,
669 pub label: SharedString,
671}
672
673#[derive(Clone, Debug, PartialEq, Eq)]
675pub struct SystemNotificationResponse {
676 pub tag: SharedString,
678 pub action_id: Option<SharedString>,
681}
682
683#[derive(Debug, Clone, Copy, PartialEq, Eq)]
685pub enum ThermalState {
686 Nominal,
688 Fair,
690 Serious,
692 Critical,
694}
695
696#[derive(Clone)]
698pub struct SourceMetadata {
699 pub id: u64,
701 pub label: Option<SharedString>,
703 pub is_main: Option<bool>,
705 pub resolution: Size<DevicePixels>,
707}
708
709pub trait ScreenCaptureSource {
711 fn metadata(&self) -> Result<SourceMetadata>;
713
714 fn stream(
717 &self,
718 foreground_executor: &ForegroundExecutor,
719 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
720 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
721}
722
723pub trait ScreenCaptureStream {
725 fn metadata(&self) -> Result<SourceMetadata>;
727}
728
729pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
731
732#[derive(PartialEq, Eq, Hash, Copy, Clone)]
734pub struct DisplayId(pub(crate) u64);
735
736impl DisplayId {
737 pub fn new(id: u64) -> Self {
739 Self(id)
740 }
741}
742
743impl From<u64> for DisplayId {
744 fn from(id: u64) -> Self {
745 Self(id)
746 }
747}
748
749impl From<DisplayId> for u64 {
750 fn from(id: DisplayId) -> Self {
751 id.0
752 }
753}
754
755impl Debug for DisplayId {
756 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757 write!(f, "DisplayId({})", self.0)
758 }
759}
760
761#[derive(Debug, Clone, Copy, PartialEq, Eq)]
763pub enum ResizeEdge {
764 Top,
766 TopRight,
768 Right,
770 BottomRight,
772 Bottom,
774 BottomLeft,
776 Left,
778 TopLeft,
780}
781
782#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
784pub enum WindowDecorations {
785 #[default]
786 Server,
788 Client,
790}
791
792#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
794pub enum Decorations {
795 #[default]
797 Server,
798 Client {
800 tiling: Tiling,
802 },
803}
804
805#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
807pub struct WindowControls {
808 pub fullscreen: bool,
810 pub maximize: bool,
812 pub minimize: bool,
814 pub window_menu: bool,
816}
817
818impl Default for WindowControls {
819 fn default() -> Self {
820 Self {
822 fullscreen: true,
823 maximize: true,
824 minimize: true,
825 window_menu: true,
826 }
827 }
828}
829
830#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
832pub enum WindowButton {
833 Minimize,
835 Maximize,
837 Close,
839}
840
841impl WindowButton {
842 pub fn id(&self) -> &'static str {
844 match self {
845 WindowButton::Minimize => "minimize",
846 WindowButton::Maximize => "maximize",
847 WindowButton::Close => "close",
848 }
849 }
850
851 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
852 fn index(&self) -> usize {
853 match self {
854 WindowButton::Minimize => 0,
855 WindowButton::Maximize => 1,
856 WindowButton::Close => 2,
857 }
858 }
859}
860
861pub const MAX_BUTTONS_PER_SIDE: usize = 3;
863
864#[derive(Debug, Clone, Copy, PartialEq, Eq)]
869pub struct WindowButtonLayout {
870 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
872 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
874}
875
876#[cfg(any(target_os = "linux", target_os = "freebsd"))]
877impl WindowButtonLayout {
878 pub fn linux_default() -> Self {
880 Self {
881 left: [None; MAX_BUTTONS_PER_SIDE],
882 right: [
883 Some(WindowButton::Minimize),
884 Some(WindowButton::Maximize),
885 Some(WindowButton::Close),
886 ],
887 }
888 }
889
890 pub fn parse(layout_string: &str) -> Result<Self> {
892 fn parse_side(
893 s: &str,
894 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
895 unrecognized: &mut Vec<String>,
896 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
897 let mut result = [None; MAX_BUTTONS_PER_SIDE];
898 let mut i = 0;
899 for name in s.split(',') {
900 let trimmed = name.trim();
901 if trimmed.is_empty() {
902 continue;
903 }
904 let button = match trimmed {
905 "minimize" => Some(WindowButton::Minimize),
906 "maximize" => Some(WindowButton::Maximize),
907 "close" => Some(WindowButton::Close),
908 other => {
909 unrecognized.push(other.to_string());
910 None
911 }
912 };
913 if let Some(button) = button {
914 if seen_buttons[button.index()] {
915 continue;
916 }
917 if let Some(slot) = result.get_mut(i) {
918 *slot = Some(button);
919 seen_buttons[button.index()] = true;
920 i += 1;
921 }
922 }
923 }
924 result
925 }
926
927 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
928 let mut unrecognized = Vec::new();
929 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
930 let layout = Self {
931 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
932 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
933 };
934
935 if !unrecognized.is_empty()
936 && layout.left.iter().all(Option::is_none)
937 && layout.right.iter().all(Option::is_none)
938 {
939 bail!(
940 "button layout string {:?} contains no valid buttons (unrecognized: {})",
941 layout_string,
942 unrecognized.join(", ")
943 );
944 }
945
946 Ok(layout)
947 }
948
949 #[cfg(test)]
951 pub fn format(&self) -> String {
952 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
953 buttons
954 .iter()
955 .flatten()
956 .map(|button| match button {
957 WindowButton::Minimize => "minimize",
958 WindowButton::Maximize => "maximize",
959 WindowButton::Close => "close",
960 })
961 .collect::<Vec<_>>()
962 .join(",")
963 }
964
965 format!("{}:{}", format_side(&self.left), format_side(&self.right))
966 }
967}
968
969#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
971pub struct Tiling {
972 pub top: bool,
974 pub left: bool,
976 pub right: bool,
978 pub bottom: bool,
980}
981
982impl Tiling {
983 pub fn tiled() -> Self {
985 Self {
986 top: true,
987 left: true,
988 right: true,
989 bottom: true,
990 }
991 }
992
993 pub fn is_tiled(&self) -> bool {
995 self.top || self.left || self.right || self.bottom
996 }
997}
998
999pub struct A11yCallbacks {
1001 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1003 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1005 pub deactivation: Box<dyn Fn() + Send + 'static>,
1007}
1008
1009#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1011pub enum FrameRequestSource {
1012 #[default]
1014 NativeCallback,
1015 LocalSchedule,
1017}
1018
1019#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1020#[expect(missing_docs)]
1021pub struct RequestFrameOptions {
1022 pub require_presentation: bool,
1024 pub force_render: bool,
1026 pub signal_at: Option<Instant>,
1032 pub signal_source: FrameRequestSource,
1034}
1035
1036pub struct PlatformFrameSignal {
1045 #[cfg(feature = "profiler")]
1046 origin: Instant,
1047 #[cfg(feature = "profiler")]
1048 first_signal: std::sync::atomic::AtomicU64,
1049}
1050
1051impl Default for PlatformFrameSignal {
1052 fn default() -> Self {
1053 Self::new()
1054 }
1055}
1056
1057impl PlatformFrameSignal {
1058 pub fn new() -> Self {
1060 Self {
1061 #[cfg(feature = "profiler")]
1062 origin: Instant::now(),
1063 #[cfg(feature = "profiler")]
1064 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1065 }
1066 }
1067
1068 #[inline]
1072 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1073 if cfg!(feature = "profiler") {
1074 Some(capture())
1075 } else {
1076 None
1077 }
1078 }
1079
1080 #[inline]
1082 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1083 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1084 #[cfg(feature = "profiler")]
1085 {
1086 let nanoseconds = at
1087 .saturating_duration_since(self.origin)
1088 .as_nanos()
1089 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1090 let source_bit = match source {
1091 FrameRequestSource::NativeCallback => 0,
1092 FrameRequestSource::LocalSchedule => 1,
1093 };
1094 self.first_signal.fetch_min(
1095 (nanoseconds << 1) | source_bit,
1096 std::sync::atomic::Ordering::Relaxed,
1097 );
1098 }
1099 }
1100
1101 #[inline]
1103 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1104 #[cfg(feature = "profiler")]
1105 {
1106 let signal = self
1107 .first_signal
1108 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1109 (signal != u64::MAX).then(|| {
1110 let source = match signal & 1 {
1111 0 => FrameRequestSource::NativeCallback,
1112 _ => FrameRequestSource::LocalSchedule,
1113 };
1114 (self.origin + Duration::from_nanos(signal >> 1), source)
1115 })
1116 }
1117 #[cfg(not(feature = "profiler"))]
1118 {
1119 None
1120 }
1121 }
1122}
1123
1124#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1137pub enum AppLifecyclePhase {
1138 Active,
1140 Inactive,
1142 Background,
1145 Foreground,
1147}
1148
1149#[derive(Debug, Clone, Default, PartialEq)]
1156pub struct WindowInsets {
1157 pub safe_area: Edges<Pixels>,
1162 pub ime: Edges<Pixels>,
1166}
1167
1168impl WindowInsets {
1169 pub fn effective(&self) -> Edges<Pixels> {
1171 Edges {
1172 top: self.safe_area.top.max(self.ime.top),
1173 right: self.safe_area.right.max(self.ime.right),
1174 bottom: self.safe_area.bottom.max(self.ime.bottom),
1175 left: self.safe_area.left.max(self.ime.left),
1176 }
1177 }
1178}
1179
1180#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1182pub enum TextInputStateChange {
1183 FocusGained,
1185 FocusLost,
1187 SelectionChanged,
1189 ContentChanged,
1191}
1192
1193#[expect(missing_docs)]
1194pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1195 fn bounds(&self) -> Bounds<Pixels>;
1196 fn is_maximized(&self) -> bool;
1197 fn window_bounds(&self) -> WindowBounds;
1198 fn content_size(&self) -> Size<Pixels>;
1199 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1205 Bounds::new(Point::default(), self.content_size())
1206 }
1207 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1212 fn prepare_frame(&self) -> bool {
1217 false
1218 }
1219 fn resize(&mut self, size: Size<Pixels>);
1220 fn scale_factor(&self) -> f32;
1221 fn appearance(&self) -> WindowAppearance;
1222 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1223 fn mouse_position(&self) -> Point<Pixels>;
1224 fn modifiers(&self) -> Modifiers;
1225 fn capslock(&self) -> Capslock;
1226 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1227 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1228 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1233 fn prompt(
1234 &self,
1235 level: PromptLevel,
1236 msg: &str,
1237 detail: Option<&str>,
1238 answers: &[PromptButton],
1239 ) -> Option<oneshot::Receiver<usize>>;
1240 fn activate(&self);
1241 fn request_attention(&self) {}
1243 fn is_active(&self) -> bool;
1244 fn visibility(&self) -> WindowVisibility;
1247 fn is_hovered(&self) -> bool;
1248 fn background_appearance(&self) -> WindowBackgroundAppearance;
1249 fn set_title(&mut self, title: &str);
1250 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1251 fn minimize(&self);
1252 fn zoom(&self);
1253 fn toggle_fullscreen(&self);
1254 fn is_fullscreen(&self) -> bool;
1255 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1256 None
1257 }
1258 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1259 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1260 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1261 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1265 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1266 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1267 fn on_moved(&self, callback: Box<dyn FnMut()>);
1268 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1272 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1273 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1274 fn on_close(&self, callback: Box<dyn FnOnce()>);
1275 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1276 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1277 fn draw(&self, scene: &Scene);
1278 fn draw_composed(&self, scene: crate::fast::composition::ComposedScene<'_>) {
1279 crate::fast::composition::draw_uncomposed(self, scene)
1280 }
1281 fn enable_window_composition(&self) -> Result<()> {
1282 crate::fast::composition::unsupported("window composition")
1283 }
1284 fn create_native_surface(
1285 &self,
1286 ) -> Result<Rc<dyn crate::fast::composition::PlatformSurfaceAttachment>> {
1287 crate::fast::composition::unsupported("native surface portals")
1288 }
1289 fn set_composition_order(
1290 &self,
1291 _fast_surfaces: &[crate::fast::composition::PlatformCompositionSurface],
1292 ) -> Result<()> {
1293 crate::fast::composition::unsupported("surface ordering")
1294 }
1295 fn schedule_frame(&self) {}
1296 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1297 fn is_subpixel_rendering_supported(&self) -> bool;
1298
1299 fn get_title(&self) -> String {
1301 String::new()
1302 }
1303 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1304 None
1305 }
1306 fn tab_bar_visible(&self) -> bool {
1307 false
1308 }
1309 fn set_edited(&mut self, _edited: bool) {}
1310 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1311 fn toggle_simple_fullscreen(&self) {}
1312 fn is_simple_fullscreen(&self) -> bool {
1313 false
1314 }
1315 #[cfg(target_os = "macos")]
1316 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1317 fn show_character_palette(&self) {}
1318 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1319 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1320 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1321 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1322 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1323 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1324 fn merge_all_windows(&self) {}
1325 fn move_tab_to_new_window(&self) {}
1326 fn toggle_window_tab_overview(&self) {}
1327 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1328
1329 fn native_window_state(&self) -> Option<Vec<u8>> {
1330 None
1331 }
1332 fn restore_native_window_state(&self, _state: &[u8]) {}
1333
1334 #[cfg(target_os = "windows")]
1335 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1336
1337 fn inner_window_bounds(&self) -> WindowBounds {
1339 self.window_bounds()
1340 }
1341 fn request_decorations(&self, _decorations: WindowDecorations) {}
1342 fn show_window_menu(&self, _position: Point<Pixels>) {}
1343 fn start_window_move(&self) {}
1344 fn can_start_external_drag(&self) -> bool {
1345 false
1346 }
1347 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1348 false
1349 }
1350 fn start_window_resize(&self, _edge: ResizeEdge) {}
1351 fn set_exclusive_zone(&self, _zone: Pixels) {}
1352 #[cfg(all(target_os = "linux", feature = "wayland"))]
1353 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1354 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1355 fn window_decorations(&self) -> Decorations {
1356 Decorations::Server
1357 }
1358 fn set_app_id(&mut self, _app_id: &str) {}
1359 fn map_window(&mut self) -> anyhow::Result<()> {
1360 Ok(())
1361 }
1362 fn window_controls(&self) -> WindowControls {
1363 WindowControls::default()
1364 }
1365 fn set_client_inset(&self, _inset: Pixels) {}
1366 fn gpu_specs(&self) -> Option<GpuSpecs>;
1367
1368 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1369
1370 fn insets(&self) -> WindowInsets {
1375 WindowInsets::default()
1376 }
1377
1378 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1384
1385 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1388
1389 fn set_back_enabled(&self, _enabled: bool) {}
1392
1393 fn show_soft_keyboard(&self) {}
1395
1396 fn hide_soft_keyboard(&self) {}
1398
1399 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1401
1402 fn play_system_bell(&self) {}
1403
1404 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1406
1407 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1409
1410 fn a11y_update_window_bounds(&self) {}
1412
1413 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1414 fn as_test(&mut self) -> Option<&mut TestWindow> {
1415 None
1416 }
1417
1418 #[cfg(any(test, feature = "test-support"))]
1422 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1423 anyhow::bail!("render_to_image not implemented for this platform")
1424 }
1425}
1426
1427#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1429pub trait PlatformHeadlessRenderer {
1430 fn render_scene_to_image(
1432 &mut self,
1433 scene: &Scene,
1434 size: Size<DevicePixels>,
1435 ) -> Result<RgbaImage>;
1436
1437 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1443
1444 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1446}
1447
1448#[doc(hidden)]
1451pub type RunnableVariant = Runnable<RunnableMeta>;
1452
1453#[doc(hidden)]
1454pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1455
1456#[doc(hidden)]
1457pub enum TasksIncluded {
1458 OnlyCompleted,
1459 CompletedAndRunning,
1460}
1461
1462#[doc(hidden)]
1465pub trait PlatformDispatcher: Send + Sync {
1466 fn is_main_thread(&self) -> bool;
1467 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1468 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1469 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1470
1471 fn dispatch_on_main_thread_when_idle(
1472 &self,
1473 runnable: RunnableVariant,
1474 timeout: Option<Duration>,
1475 ) {
1476 let _ = timeout;
1477 self.dispatch_on_main_thread(runnable, Priority::Low);
1478 }
1479
1480 fn idle_time_remaining(&self) -> Option<Duration> {
1481 None
1482 }
1483
1484 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1485
1486 fn now(&self) -> Instant {
1487 Instant::now()
1488 }
1489
1490 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1491 gpui_util::defer(Box::new(|| {}))
1492 }
1493
1494 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1495 ActivityGuard::noop()
1496 }
1497
1498 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1499 fn as_test(&self) -> Option<&TestDispatcher> {
1500 None
1501 }
1502
1503 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1506 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1507 None
1508 }
1509}
1510
1511#[expect(missing_docs)]
1512pub trait PlatformTextSystem: Send + Sync {
1513 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1514 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1516 fn all_font_names(&self) -> Vec<String>;
1518 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1520 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1522 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1524 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1526 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1528 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1530 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1532 fn rasterize_glyph(
1534 &self,
1535 params: &RenderGlyphParams,
1536 raster_bounds: Bounds<DevicePixels>,
1537 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1538 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1540 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1542 -> TextRenderingMode;
1543 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1545 0
1546 }
1547}
1548
1549#[expect(missing_docs)]
1550pub struct NoopTextSystem;
1551
1552#[expect(missing_docs)]
1553impl NoopTextSystem {
1554 #[allow(dead_code)]
1555 pub fn new() -> Self {
1556 Self
1557 }
1558}
1559
1560impl PlatformTextSystem for NoopTextSystem {
1561 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1562 Ok(())
1563 }
1564
1565 fn all_font_names(&self) -> Vec<String> {
1566 Vec::new()
1567 }
1568
1569 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1570 Ok(FontId(1))
1571 }
1572
1573 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1574 FontMetrics {
1575 units_per_em: 1000,
1576 ascent: 1025.0,
1577 descent: -275.0,
1578 line_gap: 0.0,
1579 underline_position: -95.0,
1580 underline_thickness: 60.0,
1581 cap_height: 698.0,
1582 x_height: 516.0,
1583 bounding_box: Bounds {
1584 origin: Point {
1585 x: -260.0,
1586 y: -245.0,
1587 },
1588 size: Size {
1589 width: 1501.0,
1590 height: 1364.0,
1591 },
1592 },
1593 }
1594 }
1595
1596 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1597 Ok(Bounds {
1598 origin: Point { x: 54.0, y: 0.0 },
1599 size: size(392.0, 528.0),
1600 })
1601 }
1602
1603 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1604 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1605 }
1606
1607 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1608 Some(GlyphId(ch.len_utf16() as u32))
1609 }
1610
1611 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1612 Ok(Default::default())
1613 }
1614
1615 fn rasterize_glyph(
1616 &self,
1617 _params: &RenderGlyphParams,
1618 raster_bounds: Bounds<DevicePixels>,
1619 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1620 Ok((raster_bounds.size, Vec::new()))
1621 }
1622
1623 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1624 let mut position = px(0.);
1625 let metrics = self.font_metrics(FontId(0));
1626 let em_width = font_size
1627 * self
1628 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1629 .unwrap()
1630 .width
1631 / metrics.units_per_em as f32;
1632 let mut glyphs = Vec::new();
1633 for (ix, c) in text.char_indices() {
1634 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1635 glyphs.push(ShapedGlyph {
1636 id: glyph,
1637 position: point(position, px(0.)),
1638 index: ix,
1639 is_emoji: glyph.0 == 2,
1640 });
1641 if glyph.0 == 2 {
1642 position += em_width * 2.0;
1643 } else {
1644 position += em_width;
1645 }
1646 } else {
1647 position += em_width
1648 }
1649 }
1650 let mut runs = Vec::default();
1651 if !glyphs.is_empty() {
1652 runs.push(ShapedRun {
1653 font_id: FontId(0),
1654 glyphs,
1655 });
1656 } else {
1657 position = px(0.);
1658 }
1659
1660 LineLayout {
1661 font_size,
1662 width: position,
1663 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1664 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1665 runs,
1666 len: text.len(),
1667 }
1668 }
1669
1670 fn recommended_rendering_mode(
1671 &self,
1672 _font_id: FontId,
1673 _font_size: Pixels,
1674 ) -> TextRenderingMode {
1675 TextRenderingMode::Grayscale
1676 }
1677}
1678
1679#[allow(dead_code)]
1684pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1685 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1686 [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], ];
1700
1701 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1702 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1703
1704 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1705 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1706
1707 [
1708 ratios[0] * NORM13,
1709 ratios[1] * NORM24,
1710 ratios[2] * NORM13,
1711 ratios[3] * NORM24,
1712 ]
1713}
1714
1715#[derive(PartialEq, Eq, Hash, Clone)]
1716#[expect(missing_docs)]
1717pub enum AtlasKey {
1718 Glyph(RenderGlyphParams),
1719 Svg(RenderSvgParams),
1720 Image(RenderImageParams),
1721}
1722
1723impl AtlasKey {
1724 pub fn texture_kind(&self) -> AtlasTextureKind {
1726 match self {
1727 AtlasKey::Glyph(params) => {
1728 if params.is_emoji {
1729 AtlasTextureKind::Polychrome
1730 } else if params.subpixel_rendering {
1731 AtlasTextureKind::Subpixel
1732 } else {
1733 AtlasTextureKind::Monochrome
1734 }
1735 }
1736 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1737 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1738 }
1739 }
1740}
1741
1742impl From<RenderGlyphParams> for AtlasKey {
1743 fn from(params: RenderGlyphParams) -> Self {
1744 Self::Glyph(params)
1745 }
1746}
1747
1748impl From<RenderSvgParams> for AtlasKey {
1749 fn from(params: RenderSvgParams) -> Self {
1750 Self::Svg(params)
1751 }
1752}
1753
1754impl From<RenderImageParams> for AtlasKey {
1755 fn from(params: RenderImageParams) -> Self {
1756 Self::Image(params)
1757 }
1758}
1759
1760#[expect(missing_docs)]
1761pub trait PlatformAtlas {
1762 fn get_or_insert_with<'a>(
1764 &self,
1765 key: AtlasKey,
1766 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1767 ) -> Result<Option<AtlasTile>>;
1768 fn remove(&self, key: &AtlasKey);
1769
1770 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1771 fn contains(&self, _key: &AtlasKey) -> bool {
1772 false
1773 }
1774}
1775
1776#[doc(hidden)]
1777pub trait AtlasBackend {
1778 fn insert(
1779 &mut self,
1780 kind: AtlasTextureKind,
1781 size: Size<DevicePixels>,
1782 bytes: &[u8],
1783 ) -> Result<AtlasTile>;
1784
1785 fn remove(&mut self, tile: AtlasTile);
1786}
1787
1788#[doc(hidden)]
1789pub struct AtlasState<Backend> {
1790 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1791 pub backend: Backend,
1792}
1793
1794impl<Backend> AtlasState<Backend> {
1795 pub fn new(backend: Backend) -> Self {
1796 Self {
1797 tiles_by_key: FxHashMap::default(),
1798 backend,
1799 }
1800 }
1801
1802 pub fn contains(&self, key: &AtlasKey) -> bool {
1803 self.tiles_by_key.contains_key(key)
1804 }
1805
1806 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1807 self.tiles_by_key.clear();
1808 reset_backend(&mut self.backend);
1809 }
1810}
1811
1812impl<Backend: Default> Default for AtlasState<Backend> {
1813 fn default() -> Self {
1814 Self::new(Backend::default())
1815 }
1816}
1817
1818impl<Backend: AtlasBackend> AtlasState<Backend> {
1819 pub fn get_or_insert_with<'a>(
1820 &mut self,
1821 key: AtlasKey,
1822 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1823 ) -> Result<Option<AtlasTile>> {
1824 match self.tiles_by_key.entry(key) {
1825 Entry::Occupied(entry) => Ok(Some(*entry.get())),
1826 Entry::Vacant(entry) => {
1827 profiling::scope!("new tile");
1828 let Some((size, bytes)) = build()? else {
1829 return Ok(None);
1830 };
1831 let tile = self
1832 .backend
1833 .insert(entry.key().texture_kind(), size, &bytes)?;
1834 entry.insert(tile);
1835 Ok(Some(tile))
1836 }
1837 }
1838 }
1839
1840 pub fn remove(&mut self, key: &AtlasKey) {
1841 if let Some(tile) = self.tiles_by_key.remove(key) {
1842 self.backend.remove(tile);
1843 }
1844 }
1845}
1846
1847#[derive(Default)]
1851pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1852
1853#[doc(hidden)]
1854#[derive(Default)]
1855pub struct HeadlessAtlasBackend {
1856 next_id: u32,
1857}
1858
1859impl AtlasBackend for HeadlessAtlasBackend {
1860 fn insert(
1861 &mut self,
1862 kind: AtlasTextureKind,
1863 size: Size<DevicePixels>,
1864 _bytes: &[u8],
1865 ) -> Result<AtlasTile> {
1866 self.next_id += 1;
1867 let texture_id = self.next_id;
1868 self.next_id += 1;
1869 let tile_id = self.next_id;
1870 Ok(AtlasTile {
1871 texture_id: AtlasTextureId {
1872 index: texture_id,
1873 kind,
1874 },
1875 tile_id: TileId(tile_id),
1876 padding: 0,
1877 bounds: Bounds {
1878 origin: Point::default(),
1879 size,
1880 },
1881 })
1882 }
1883
1884 fn remove(&mut self, _tile: AtlasTile) {}
1885}
1886
1887impl PlatformAtlas for HeadlessAtlas {
1888 fn get_or_insert_with<'a>(
1889 &self,
1890 key: AtlasKey,
1891 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1892 ) -> Result<Option<AtlasTile>> {
1893 self.0.lock().get_or_insert_with(key, build)
1894 }
1895
1896 fn remove(&self, key: &AtlasKey) {
1897 self.0.lock().remove(key);
1898 }
1899
1900 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1901 fn contains(&self, key: &AtlasKey) -> bool {
1902 self.0.lock().contains(key)
1903 }
1904}
1905
1906#[doc(hidden)]
1907pub struct AtlasTextureList<T> {
1908 pub textures: Vec<Option<T>>,
1909 pub free_list: Vec<usize>,
1910}
1911
1912impl<T> Default for AtlasTextureList<T> {
1913 fn default() -> Self {
1914 Self {
1915 textures: Vec::default(),
1916 free_list: Vec::default(),
1917 }
1918 }
1919}
1920
1921impl<T> ops::Index<usize> for AtlasTextureList<T> {
1922 type Output = Option<T>;
1923
1924 fn index(&self, index: usize) -> &Self::Output {
1925 &self.textures[index]
1926 }
1927}
1928
1929impl<T> AtlasTextureList<T> {
1930 #[allow(unused)]
1931 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1932 self.free_list.clear();
1933 self.textures.drain(..)
1934 }
1935
1936 #[allow(dead_code)]
1937 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1938 self.textures.iter_mut().flatten()
1939 }
1940}
1941
1942#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1943#[repr(C)]
1944#[expect(missing_docs)]
1945pub struct AtlasTile {
1946 pub texture_id: AtlasTextureId,
1948 pub tile_id: TileId,
1950 pub padding: u32,
1952 pub bounds: Bounds<DevicePixels>,
1954}
1955
1956#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1957#[repr(C)]
1958#[expect(missing_docs)]
1959pub struct AtlasTextureId {
1960 pub index: u32,
1963 pub kind: AtlasTextureKind,
1965}
1966
1967#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1968#[repr(C)]
1969#[cfg_attr(
1970 all(
1971 any(target_os = "linux", target_os = "freebsd"),
1972 not(any(feature = "x11", feature = "wayland"))
1973 ),
1974 allow(dead_code)
1975)]
1976#[expect(missing_docs)]
1977pub enum AtlasTextureKind {
1978 Monochrome = 0,
1979 Polychrome = 1,
1980 Subpixel = 2,
1981}
1982
1983#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1984#[repr(C)]
1985#[expect(missing_docs)]
1986pub struct TileId(pub u32);
1987
1988impl From<etagere::AllocId> for TileId {
1989 fn from(id: etagere::AllocId) -> Self {
1990 Self(id.serialize())
1991 }
1992}
1993
1994impl From<TileId> for etagere::AllocId {
1995 fn from(id: TileId) -> Self {
1996 Self::deserialize(id.0)
1997 }
1998}
1999
2000#[expect(missing_docs)]
2001pub struct PlatformInputHandler {
2002 cx: AsyncWindowContext,
2003 handler: Box<dyn InputHandler>,
2004}
2005
2006#[expect(missing_docs)]
2007#[cfg_attr(
2008 all(
2009 any(target_os = "linux", target_os = "freebsd"),
2010 not(any(feature = "x11", feature = "wayland"))
2011 ),
2012 allow(dead_code)
2013)]
2014impl PlatformInputHandler {
2015 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2016 Self { cx, handler }
2017 }
2018
2019 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2020 self.cx
2021 .update(|window, cx| {
2022 self.handler
2023 .selected_text_range(ignore_disabled_input, window, cx)
2024 })
2025 .ok()
2026 .flatten()
2027 }
2028
2029 #[cfg_attr(target_os = "windows", allow(dead_code))]
2030 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2031 self.cx
2032 .update(|window, cx| self.handler.marked_text_range(window, cx))
2033 .ok()
2034 .flatten()
2035 }
2036
2037 #[cfg_attr(
2038 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2039 allow(dead_code)
2040 )]
2041 pub fn text_for_range(
2042 &mut self,
2043 range_utf16: Range<usize>,
2044 adjusted: &mut Option<Range<usize>>,
2045 ) -> Option<String> {
2046 self.cx
2047 .update(|window, cx| {
2048 self.handler
2049 .text_for_range(range_utf16, adjusted, window, cx)
2050 })
2051 .ok()
2052 .flatten()
2053 }
2054
2055 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2056 self.cx
2057 .update(|window, cx| {
2058 self.handler
2059 .replace_text_in_range(replacement_range, text, window, cx);
2060 })
2061 .ok();
2062 }
2063
2064 pub fn replace_and_mark_text_in_range(
2065 &mut self,
2066 range_utf16: Option<Range<usize>>,
2067 new_text: &str,
2068 new_selected_range: Option<Range<usize>>,
2069 ) {
2070 self.cx
2071 .update(|window, cx| {
2072 self.handler.replace_and_mark_text_in_range(
2073 range_utf16,
2074 new_text,
2075 new_selected_range,
2076 window,
2077 cx,
2078 )
2079 })
2080 .ok();
2081 }
2082
2083 #[cfg_attr(target_os = "windows", allow(dead_code))]
2084 pub fn unmark_text(&mut self) {
2085 self.cx
2086 .update(|window, cx| self.handler.unmark_text(window, cx))
2087 .ok();
2088 }
2089
2090 pub fn paste(&mut self, item: ClipboardItem) {
2091 self.cx
2092 .update(|window, cx| self.handler.paste(item, window, cx))
2093 .ok();
2094 }
2095
2096 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2097 self.cx
2098 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2099 .ok()
2100 .flatten()
2101 }
2102
2103 #[allow(dead_code)]
2104 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2105 self.handler.apple_press_and_hold_enabled()
2106 }
2107
2108 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2109 self.handler.replace_text_in_range(None, input, window, cx);
2110 }
2111
2112 pub fn compute_ime_candidate_bounds(
2113 marked_range: Option<Range<usize>>,
2114 selection: &UTF16Selection,
2115 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2116 ) -> Option<Bounds<Pixels>> {
2117 if let Some(marked_range) = marked_range {
2118 let mut line_start = marked_range.start;
2120
2121 let caret = selection.range.end;
2125 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2126 for i in (marked_range.start..caret).rev() {
2127 if let Some(b) = bounds_for_range(i..i) {
2128 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2129 line_start = i + 1;
2130 break;
2131 }
2132 }
2133 }
2134 }
2135 bounds_for_range(line_start..line_start)
2136 } else {
2137 let offset = if selection.reversed {
2139 selection.range.start
2140 } else {
2141 selection.range.end
2142 };
2143 bounds_for_range(offset..offset)
2144 }
2145 }
2146
2147 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2148 let marked_range = self.handler.marked_text_range(window, cx);
2149 let selection = self.handler.selected_text_range(true, window, cx)?;
2150 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2151 self.handler.bounds_for_range(range, window, cx)
2152 })
2153 }
2154
2155 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2156 let marked_range = self.marked_text_range();
2157 let selection = self.selected_text_range(true)?;
2158 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2159 self.bounds_for_range(range)
2160 })
2161 }
2162
2163 #[allow(unused)]
2164 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2165 self.cx
2166 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2167 .ok()
2168 .flatten()
2169 }
2170
2171 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2173 self.cx
2174 .update(|window, cx| {
2175 self.handler
2176 .set_selected_text_range(range_utf16, window, cx)
2177 })
2178 .ok();
2179 }
2180
2181 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2183 self.cx
2184 .update(|window, cx| self.handler.element_bounds(window, cx))
2185 .ok()
2186 .flatten()
2187 }
2188
2189 pub fn text_length_utf16(&mut self) -> Option<usize> {
2191 self.cx
2192 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2193 .ok()
2194 .flatten()
2195 }
2196
2197 #[allow(dead_code)]
2198 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2199 self.handler.accepts_text_input(window, cx)
2200 }
2201
2202 #[allow(dead_code)]
2203 pub fn query_accepts_text_input(&mut self) -> bool {
2204 self.cx
2205 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2206 .unwrap_or(true)
2207 }
2208
2209 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2215 self.cx
2216 .update(|window, cx| {
2217 !window.has_pending_keystrokes()
2219 && self.handler.prefers_ime_for_printable_keys(window, cx)
2220 })
2221 .unwrap_or(false)
2222 }
2223
2224 pub fn text_input_configuration(
2226 &mut self,
2227 window: &mut Window,
2228 cx: &mut App,
2229 ) -> TextInputConfiguration {
2230 self.handler.text_input_configuration(window, cx)
2231 }
2232
2233 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2235 self.cx
2236 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2237 .ok()
2238 .flatten()
2239 }
2240}
2241
2242#[derive(Debug)]
2245pub struct UTF16Selection {
2246 pub range: Range<usize>,
2249 pub reversed: bool,
2252}
2253
2254pub trait InputHandler: 'static {
2259 fn selected_text_range(
2264 &mut self,
2265 ignore_disabled_input: bool,
2266 window: &mut Window,
2267 cx: &mut App,
2268 ) -> Option<UTF16Selection>;
2269
2270 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2275
2276 fn text_for_range(
2281 &mut self,
2282 range_utf16: Range<usize>,
2283 adjusted_range: &mut Option<Range<usize>>,
2284 window: &mut Window,
2285 cx: &mut App,
2286 ) -> Option<String>;
2287
2288 fn replace_text_in_range(
2293 &mut self,
2294 replacement_range: Option<Range<usize>>,
2295 text: &str,
2296 window: &mut Window,
2297 cx: &mut App,
2298 );
2299
2300 fn replace_and_mark_text_in_range(
2307 &mut self,
2308 range_utf16: Option<Range<usize>>,
2309 new_text: &str,
2310 new_selected_range: Option<Range<usize>>,
2311 window: &mut Window,
2312 cx: &mut App,
2313 );
2314
2315 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2318
2319 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2326 if let Some(text) = item.text() {
2327 self.replace_text_in_range(None, &text, window, cx);
2328 }
2329 }
2330
2331 fn bounds_for_range(
2336 &mut self,
2337 range_utf16: Range<usize>,
2338 window: &mut Window,
2339 cx: &mut App,
2340 ) -> Option<Bounds<Pixels>>;
2341
2342 fn character_index_for_point(
2346 &mut self,
2347 point: Point<Pixels>,
2348 window: &mut Window,
2349 cx: &mut App,
2350 ) -> Option<usize>;
2351
2352 fn set_selected_text_range(
2362 &mut self,
2363 _range_utf16: Range<usize>,
2364 _window: &mut Window,
2365 _cx: &mut App,
2366 ) {
2367 }
2368
2369 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2376 None
2377 }
2378
2379 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2381 None
2382 }
2383
2384 #[allow(dead_code)]
2389 fn apple_press_and_hold_enabled(&mut self) -> bool {
2390 true
2391 }
2392
2393 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2395 true
2396 }
2397
2398 fn text_input_editable_range(
2409 &mut self,
2410 _window: &mut Window,
2411 _cx: &mut App,
2412 ) -> Option<Range<usize>> {
2413 None
2414 }
2415
2416 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2425 false
2426 }
2427
2428 fn text_input_configuration(
2434 &mut self,
2435 _window: &mut Window,
2436 _cx: &mut App,
2437 ) -> TextInputConfiguration {
2438 TextInputConfiguration::default()
2439 }
2440}
2441
2442#[derive(Clone, Debug, Default, PartialEq, Eq)]
2452pub struct TextInputConfiguration {
2453 pub autocorrect: bool,
2455 pub autocapitalize: Autocapitalize,
2457 pub suggestions: bool,
2459 pub input_action: TextInputAction,
2461}
2462
2463#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2465pub enum Autocapitalize {
2466 #[default]
2468 None,
2469 Words,
2471 Sentences,
2473 Characters,
2475}
2476
2477#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2487pub enum TextInputAction {
2488 #[default]
2490 Unspecified,
2491 Enter,
2493 Done,
2495 Go,
2497 Next,
2499 Previous,
2501 Search,
2503 Send,
2505}
2506
2507#[derive(Debug)]
2509pub struct WindowOptions {
2510 pub window_bounds: Option<WindowBounds>,
2514
2515 pub titlebar: Option<TitlebarOptions>,
2517
2518 pub focus: bool,
2520
2521 pub show: bool,
2523
2524 pub kind: WindowKind,
2526
2527 pub is_movable: bool,
2531
2532 pub app_owns_titlebar_drag: bool,
2544
2545 pub inactive_frame_interval: Option<Duration>,
2549
2550 pub is_resizable: bool,
2552
2553 pub is_minimizable: bool,
2555
2556 pub display_id: Option<DisplayId>,
2559
2560 pub window_background: WindowBackgroundAppearance,
2562
2563 pub app_id: Option<String>,
2565
2566 pub window_min_size: Option<Size<Pixels>>,
2568
2569 pub window_decorations: Option<WindowDecorations>,
2572
2573 pub icon: Option<Arc<image::RgbaImage>>,
2575
2576 pub tabbing_identifier: Option<String>,
2578}
2579
2580#[derive(Debug)]
2582#[cfg_attr(
2583 all(
2584 any(target_os = "linux", target_os = "freebsd"),
2585 not(any(feature = "x11", feature = "wayland"))
2586 ),
2587 allow(dead_code)
2588)]
2589#[allow(missing_docs)]
2590pub struct WindowParams {
2591 pub bounds: Bounds<Pixels>,
2592
2593 #[cfg_attr(feature = "wayland", allow(dead_code))]
2595 pub titlebar: Option<TitlebarOptions>,
2596
2597 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2599 pub kind: WindowKind,
2600
2601 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2603 pub is_movable: bool,
2604
2605 #[cfg_attr(
2607 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2608 allow(dead_code)
2609 )]
2610 pub app_owns_titlebar_drag: bool,
2611
2612 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2614 pub is_resizable: bool,
2615
2616 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2618 pub is_minimizable: bool,
2619
2620 #[cfg_attr(
2621 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2622 allow(dead_code)
2623 )]
2624 pub focus: bool,
2625
2626 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2627 pub show: bool,
2628
2629 #[cfg_attr(feature = "wayland", allow(dead_code))]
2631 pub icon: Option<Arc<image::RgbaImage>>,
2632
2633 #[cfg_attr(feature = "wayland", allow(dead_code))]
2634 pub display_id: Option<DisplayId>,
2635
2636 #[cfg_attr(feature = "wayland", allow(dead_code))]
2637 pub app_id: Option<String>,
2638
2639 pub window_min_size: Option<Size<Pixels>>,
2640
2641 #[cfg(target_os = "macos")]
2642 pub tabbing_identifier: Option<String>,
2643}
2644
2645#[derive(Debug, Copy, Clone, PartialEq)]
2647pub enum WindowBounds {
2648 Windowed(Bounds<Pixels>),
2650 Maximized(Bounds<Pixels>),
2653 Fullscreen(Bounds<Pixels>),
2656}
2657
2658impl Default for WindowBounds {
2659 fn default() -> Self {
2660 WindowBounds::Windowed(Bounds::default())
2661 }
2662}
2663
2664impl WindowBounds {
2665 pub fn get_bounds(&self) -> Bounds<Pixels> {
2667 match self {
2668 WindowBounds::Windowed(bounds) => *bounds,
2669 WindowBounds::Maximized(bounds) => *bounds,
2670 WindowBounds::Fullscreen(bounds) => *bounds,
2671 }
2672 }
2673
2674 pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
2676 WindowBounds::Windowed(Bounds::centered(None, size, cx))
2677 }
2678}
2679
2680impl Default for WindowOptions {
2681 fn default() -> Self {
2682 Self {
2683 window_bounds: None,
2684 titlebar: Some(TitlebarOptions {
2685 title: Default::default(),
2686 appears_transparent: Default::default(),
2687 traffic_light_position: Default::default(),
2688 }),
2689 focus: true,
2690 show: true,
2691 kind: WindowKind::Normal,
2692 is_movable: true,
2693 app_owns_titlebar_drag: false,
2694 inactive_frame_interval: Some(Duration::from_micros(33_333)),
2695 is_resizable: true,
2696 is_minimizable: true,
2697 display_id: None,
2698 window_background: WindowBackgroundAppearance::default(),
2699 icon: None,
2700 app_id: None,
2701 window_min_size: None,
2702 window_decorations: None,
2703 tabbing_identifier: None,
2704 }
2705 }
2706}
2707
2708#[derive(Debug, Default)]
2710pub struct TitlebarOptions {
2711 pub title: Option<SharedString>,
2713
2714 pub appears_transparent: bool,
2717
2718 pub traffic_light_position: Option<Point<Pixels>>,
2720}
2721
2722#[derive(Clone, Debug, PartialEq, Eq)]
2724pub enum WindowKind {
2725 Normal,
2727
2728 PopUp,
2731
2732 AnchoredPopup(popup::PopupOptions),
2739
2740 Floating,
2742
2743 #[cfg(all(target_os = "linux", feature = "wayland"))]
2746 LayerShell(layer_shell::LayerShellOptions),
2747
2748 Dialog,
2751}
2752
2753#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2758pub enum WindowAppearance {
2759 #[default]
2763 Light,
2764
2765 VibrantLight,
2769
2770 Dark,
2774
2775 VibrantDark,
2779}
2780
2781#[derive(Copy, Clone, Debug, Default, PartialEq)]
2784pub enum WindowBackgroundAppearance {
2785 #[default]
2793 Opaque,
2794 Transparent,
2796 Blurred,
2800 MicaBackdrop,
2802 MicaAltBackdrop,
2804}
2805
2806#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2808pub enum TextRenderingMode {
2809 #[default]
2811 PlatformDefault,
2812 Subpixel,
2814 Grayscale,
2816}
2817
2818#[derive(Clone, Debug)]
2820pub struct PathPromptOptions {
2821 pub files: bool,
2823 pub directories: bool,
2825 pub multiple: bool,
2827 pub prompt: Option<SharedString>,
2829}
2830
2831#[derive(Copy, Clone, Debug, PartialEq)]
2833pub enum PromptLevel {
2834 Info,
2836
2837 Warning,
2839
2840 Critical,
2842}
2843
2844#[derive(Clone, Debug, PartialEq)]
2846pub enum PromptButton {
2847 Ok(SharedString),
2849 Cancel(SharedString),
2851 Other(SharedString),
2853}
2854
2855impl PromptButton {
2856 pub fn new(label: impl Into<SharedString>) -> Self {
2858 PromptButton::Other(label.into())
2859 }
2860
2861 pub fn ok(label: impl Into<SharedString>) -> Self {
2863 PromptButton::Ok(label.into())
2864 }
2865
2866 pub fn cancel(label: impl Into<SharedString>) -> Self {
2868 PromptButton::Cancel(label.into())
2869 }
2870
2871 #[allow(dead_code)]
2873 pub fn is_cancel(&self) -> bool {
2874 matches!(self, PromptButton::Cancel(_))
2875 }
2876
2877 pub fn label(&self) -> &SharedString {
2879 match self {
2880 PromptButton::Ok(label) => label,
2881 PromptButton::Cancel(label) => label,
2882 PromptButton::Other(label) => label,
2883 }
2884 }
2885}
2886
2887impl From<&str> for PromptButton {
2888 fn from(value: &str) -> Self {
2889 match value.to_lowercase().as_str() {
2890 "ok" => PromptButton::Ok("OK".into()),
2891 "cancel" => PromptButton::Cancel("Cancel".into()),
2892 _ => PromptButton::Other(SharedString::from(value.to_owned())),
2893 }
2894 }
2895}
2896
2897#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2899pub enum CursorStyle {
2900 #[default]
2902 Arrow,
2903
2904 IBeam,
2907
2908 Crosshair,
2911
2912 ClosedHand,
2915
2916 OpenHand,
2919
2920 PointingHand,
2923
2924 ResizeLeft,
2927
2928 ResizeRight,
2931
2932 ResizeLeftRight,
2935
2936 ResizeUp,
2939
2940 ResizeDown,
2943
2944 ResizeUpDown,
2947
2948 ResizeUpLeftDownRight,
2951
2952 ResizeUpRightDownLeft,
2955
2956 ResizeColumn,
2959
2960 ResizeRow,
2963
2964 IBeamCursorForVerticalLayout,
2967
2968 OperationNotAllowed,
2971
2972 DragLink,
2975
2976 DragCopy,
2979
2980 ContextualMenu,
2983}
2984
2985#[derive(Clone, Debug, Eq, PartialEq)]
2987pub struct ClipboardItem {
2988 pub entries: Vec<ClipboardEntry>,
2990}
2991
2992#[derive(Clone, Debug, PartialEq, Eq)]
2997pub enum ClipboardReadError {
2998 Unavailable,
3002 Denied(String),
3005 UnsupportedContent,
3008}
3009
3010impl std::fmt::Display for ClipboardReadError {
3011 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3012 match self {
3013 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3014 Self::Denied(message) => {
3015 write!(formatter, "clipboard access was denied: {message}")
3016 }
3017 Self::UnsupportedContent => {
3018 formatter.write_str("the clipboard contents are unsupported")
3019 }
3020 }
3021 }
3022}
3023
3024impl std::error::Error for ClipboardReadError {}
3025
3026#[derive(Clone, Debug, Eq, PartialEq)]
3028pub enum ClipboardEntry {
3029 String(ClipboardString),
3031 Image(Image),
3033 ExternalPaths(crate::ExternalPaths),
3035}
3036
3037impl ClipboardItem {
3038 pub fn new_string(text: String) -> Self {
3040 Self {
3041 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3042 }
3043 }
3044
3045 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3047 Self {
3048 entries: vec![ClipboardEntry::String(ClipboardString {
3049 text,
3050 metadata: Some(metadata),
3051 })],
3052 }
3053 }
3054
3055 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3057 Self {
3058 entries: vec![ClipboardEntry::String(
3059 ClipboardString::new(text).with_json_metadata(metadata),
3060 )],
3061 }
3062 }
3063
3064 pub fn new_image(image: &Image) -> Self {
3066 Self {
3067 entries: vec![ClipboardEntry::Image(image.clone())],
3068 }
3069 }
3070
3071 pub fn text(&self) -> Option<String> {
3074 let mut answer = String::new();
3075
3076 for entry in self.entries.iter() {
3077 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3078 answer.push_str(text);
3079 }
3080 }
3081
3082 if answer.is_empty() {
3083 for entry in self.entries.iter() {
3084 if let ClipboardEntry::ExternalPaths(paths) = entry {
3085 for path in &paths.0 {
3086 use std::fmt::Write as _;
3087 _ = write!(answer, "{}", path.display());
3088 }
3089 }
3090 }
3091 }
3092
3093 if !answer.is_empty() {
3094 Some(answer)
3095 } else {
3096 None
3097 }
3098 }
3099
3100 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3102 pub fn metadata(&self) -> Option<&String> {
3103 match self.entries().first() {
3104 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3105 clipboard_string.metadata.as_ref()
3106 }
3107 _ => None,
3108 }
3109 }
3110
3111 pub fn entries(&self) -> &[ClipboardEntry] {
3113 &self.entries
3114 }
3115
3116 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3118 self.entries.into_iter()
3119 }
3120}
3121
3122impl From<ClipboardString> for ClipboardEntry {
3123 fn from(value: ClipboardString) -> Self {
3124 Self::String(value)
3125 }
3126}
3127
3128impl From<String> for ClipboardEntry {
3129 fn from(value: String) -> Self {
3130 Self::from(ClipboardString::from(value))
3131 }
3132}
3133
3134impl From<Image> for ClipboardEntry {
3135 fn from(value: Image) -> Self {
3136 Self::Image(value)
3137 }
3138}
3139
3140impl From<ClipboardEntry> for ClipboardItem {
3141 fn from(value: ClipboardEntry) -> Self {
3142 Self {
3143 entries: vec![value],
3144 }
3145 }
3146}
3147
3148impl From<String> for ClipboardItem {
3149 fn from(value: String) -> Self {
3150 Self::from(ClipboardEntry::from(value))
3151 }
3152}
3153
3154impl From<Image> for ClipboardItem {
3155 fn from(value: Image) -> Self {
3156 Self::from(ClipboardEntry::from(value))
3157 }
3158}
3159
3160#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3162pub enum ImageFormat {
3163 Png,
3168 Jpeg,
3170 Webp,
3172 Gif,
3174 Svg,
3176 Bmp,
3178 Tiff,
3180 Ico,
3182 Pnm,
3184}
3185
3186impl ImageFormat {
3187 pub const fn mime_type(self) -> &'static str {
3189 match self {
3190 ImageFormat::Png => "image/png",
3191 ImageFormat::Jpeg => "image/jpeg",
3192 ImageFormat::Webp => "image/webp",
3193 ImageFormat::Gif => "image/gif",
3194 ImageFormat::Svg => "image/svg+xml",
3195 ImageFormat::Bmp => "image/bmp",
3196 ImageFormat::Tiff => "image/tiff",
3197 ImageFormat::Ico => "image/ico",
3198 ImageFormat::Pnm => "image/x-portable-anymap",
3199 }
3200 }
3201
3202 pub const fn extension(self) -> &'static str {
3204 match self {
3205 ImageFormat::Png => "png",
3206 ImageFormat::Jpeg => "jpg",
3207 ImageFormat::Webp => "webp",
3208 ImageFormat::Gif => "gif",
3209 ImageFormat::Svg => "svg",
3210 ImageFormat::Bmp => "bmp",
3211 ImageFormat::Tiff => "tiff",
3212 ImageFormat::Ico => "ico",
3213 ImageFormat::Pnm => "pnm",
3214 }
3215 }
3216
3217 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3219 use strum::IntoEnumIterator;
3220 Self::iter()
3221 .find(|format| format.mime_type() == mime_type)
3222 .or_else(|| Self::from_mime_type_alias(mime_type))
3223 }
3224
3225 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3229 match mime_type {
3230 "image/jpg" => Some(Self::Jpeg),
3231 "image/tif" => Some(Self::Tiff),
3232 _ => None,
3233 }
3234 }
3235}
3236
3237#[derive(Clone, Debug, PartialEq, Eq)]
3239pub struct Image {
3240 pub format: ImageFormat,
3242 pub bytes: Vec<u8>,
3244 pub id: u64,
3246}
3247
3248pub(crate) fn decode_static_image(
3249 bytes: &[u8],
3250 format: image::ImageFormat,
3251) -> Result<SmallVec<[Frame; 1]>> {
3252 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3253 .into_decoder()
3254 .context("creating image decoder")?;
3255 decode_static_image_from_decoder(decoder)
3256}
3257
3258pub(crate) fn decode_static_image_from_decoder(
3259 mut decoder: impl image::ImageDecoder,
3260) -> Result<SmallVec<[Frame; 1]>> {
3261 let orientation = decoder
3262 .orientation()
3263 .context("reading decoder's orientation")?;
3264 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3265 image.apply_orientation(orientation);
3266
3267 let mut data = image.into_rgba8();
3268 for pixel in data.chunks_exact_mut(4) {
3269 pixel.swap(0, 2);
3270 }
3271
3272 Ok(SmallVec::from_elem(Frame::new(data), 1))
3273}
3274
3275impl Hash for Image {
3276 fn hash<H: Hasher>(&self, state: &mut H) {
3277 state.write_u64(self.id);
3278 }
3279}
3280
3281impl Image {
3282 pub fn empty() -> Self {
3284 Self::from_bytes(ImageFormat::Png, Vec::new())
3285 }
3286
3287 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3289 Self {
3290 id: hash(&bytes),
3291 format,
3292 bytes,
3293 }
3294 }
3295
3296 pub fn id(&self) -> u64 {
3298 self.id
3299 }
3300
3301 pub fn use_render_image(
3303 self: Arc<Self>,
3304 window: &mut Window,
3305 cx: &mut App,
3306 ) -> Option<Arc<RenderImage>> {
3307 ImageSource::Image(self)
3308 .use_data(None, window, cx)
3309 .and_then(|result| result.ok())
3310 }
3311
3312 pub fn get_render_image(
3314 self: Arc<Self>,
3315 window: &mut Window,
3316 cx: &mut App,
3317 ) -> Option<Arc<RenderImage>> {
3318 ImageSource::Image(self)
3319 .get_data(None, window, cx)
3320 .and_then(|result| result.ok())
3321 }
3322
3323 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3325 ImageSource::Image(self).remove_asset(cx);
3326 }
3327
3328 #[cfg(any(test, feature = "test-support"))]
3331 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3332 ImageSource::Image(self.clone()).is_asset_cached(cx)
3333 }
3334
3335 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3337 let frames = match self.format {
3338 ImageFormat::Gif => {
3339 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
3340 let mut frames = SmallVec::new();
3341
3342 for frame in decoder.into_frames() {
3343 match frame {
3344 Ok(mut frame) => {
3345 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3347 pixel.swap(0, 2);
3348 }
3349 frames.push(frame);
3350 }
3351 Err(err) => {
3352 log::debug!("Skipping GIF frame due to decode error: {err}");
3353 }
3354 }
3355 }
3356
3357 if frames.is_empty() {
3358 anyhow::bail!("GIF could not be decoded: all frames failed");
3359 }
3360
3361 frames
3362 }
3363 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3364 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3365 ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
3366 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3367 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3368 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3369 ImageFormat::Svg => {
3370 return svg_renderer
3371 .render_single_frame(&self.bytes, 1.0)
3372 .map_err(Into::into);
3373 }
3374 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3375 };
3376
3377 Ok(Arc::new(RenderImage::new(frames)))
3378 }
3379
3380 pub fn format(&self) -> ImageFormat {
3382 self.format
3383 }
3384
3385 pub fn bytes(&self) -> &[u8] {
3387 self.bytes.as_slice()
3388 }
3389}
3390
3391#[derive(Clone, Debug, Eq, PartialEq)]
3393pub struct ClipboardString {
3394 pub text: String,
3396 pub metadata: Option<String>,
3398}
3399
3400impl ClipboardString {
3401 pub fn new(text: String) -> Self {
3403 Self {
3404 text,
3405 metadata: None,
3406 }
3407 }
3408
3409 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3412 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3413 self
3414 }
3415
3416 pub fn text(&self) -> &String {
3418 &self.text
3419 }
3420
3421 pub fn into_text(self) -> String {
3423 self.text
3424 }
3425
3426 pub fn metadata_json<T>(&self) -> Option<T>
3428 where
3429 T: for<'a> Deserialize<'a>,
3430 {
3431 self.metadata
3432 .as_ref()
3433 .and_then(|m| serde_json::from_str(m).ok())
3434 }
3435
3436 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3437 pub fn text_hash(text: &str) -> u64 {
3439 let mut hasher = SeaHasher::new();
3440 text.hash(&mut hasher);
3441 hasher.finish()
3442 }
3443}
3444
3445impl From<String> for ClipboardString {
3446 fn from(value: String) -> Self {
3447 Self {
3448 text: value,
3449 metadata: None,
3450 }
3451 }
3452}
3453
3454#[cfg(test)]
3455mod image_tests {
3456 use super::*;
3457 use std::sync::Arc;
3458
3459 #[test]
3460 fn test_image_to_image_data_applies_exif_orientation() {
3461 let image = Image::from_bytes(
3462 ImageFormat::Jpeg,
3463 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3464 );
3465
3466 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3467
3468 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3469
3470 let bytes = render_image.as_bytes(0).unwrap();
3471 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3472 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3473 }
3474
3475 #[test]
3476 fn test_svg_image_to_image_data_converts_to_bgra() {
3477 let image = Image::from_bytes(
3478 ImageFormat::Svg,
3479 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3480<rect width="1" height="1" fill="#38BDF8"/>
3481</svg>"##
3482 .to_vec(),
3483 );
3484
3485 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3486 let bytes = render_image.as_bytes(0).unwrap();
3487
3488 for pixel in bytes.chunks_exact(4) {
3489 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3490 }
3491 }
3492}
3493
3494#[cfg(test)]
3495mod atlas_tests {
3496 use super::*;
3497
3498 const TILE_SIZE: Size<DevicePixels> = Size {
3499 width: DevicePixels(1),
3500 height: DevicePixels(1),
3501 };
3502
3503 #[derive(Default)]
3504 struct RecordingAtlasBackend {
3505 insert_calls: u32,
3506 fail_next_insert: bool,
3507 removed_tiles: Vec<AtlasTile>,
3508 }
3509
3510 impl AtlasBackend for RecordingAtlasBackend {
3511 fn insert(
3512 &mut self,
3513 kind: AtlasTextureKind,
3514 size: Size<DevicePixels>,
3515 _bytes: &[u8],
3516 ) -> Result<AtlasTile> {
3517 self.insert_calls += 1;
3518 if std::mem::take(&mut self.fail_next_insert) {
3519 anyhow::bail!("backend failed");
3520 }
3521 Ok(AtlasTile {
3522 texture_id: AtlasTextureId { index: 0, kind },
3523 tile_id: TileId(self.insert_calls),
3524 padding: 0,
3525 bounds: Bounds {
3526 origin: Point::default(),
3527 size,
3528 },
3529 })
3530 }
3531
3532 fn remove(&mut self, tile: AtlasTile) {
3533 self.removed_tiles.push(tile);
3534 }
3535 }
3536
3537 fn image_key(image_id: usize) -> AtlasKey {
3538 AtlasKey::Image(RenderImageParams {
3539 image_id: crate::ImageId(image_id),
3540 frame_index: 0,
3541 })
3542 }
3543
3544 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3545 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3546 }
3547
3548 #[test]
3549 fn only_successful_inserts_are_cached() -> Result<()> {
3550 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3551 let key = image_key(1);
3552
3553 assert_eq!(
3554 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3555 None
3556 );
3557 state
3558 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3559 .expect_err("builder error should propagate");
3560 assert!(!state.contains(&key));
3561 assert_eq!(state.backend.insert_calls, 0);
3562
3563 state.backend.fail_next_insert = true;
3564 state
3565 .get_or_insert_with(key.clone(), &mut build_tile)
3566 .expect_err("backend error should propagate");
3567 assert!(!state.contains(&key));
3568 assert_eq!(state.backend.insert_calls, 1);
3569
3570 let tile = state
3571 .get_or_insert_with(key.clone(), &mut build_tile)?
3572 .context("builder should produce a tile")?;
3573 assert_eq!(tile.texture_id.kind, key.texture_kind());
3574 assert_eq!(
3575 state.get_or_insert_with(key.clone(), &mut || {
3576 anyhow::bail!("cache hit must not call the builder")
3577 })?,
3578 Some(tile)
3579 );
3580 assert!(state.contains(&key));
3581 assert_eq!(state.backend.insert_calls, 2);
3582 Ok(())
3583 }
3584
3585 #[test]
3586 fn remove_and_clear_invalidate_keys() -> Result<()> {
3587 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3588 let key = image_key(1);
3589 let other_key = image_key(2);
3590 let tile = state
3591 .get_or_insert_with(key.clone(), &mut build_tile)?
3592 .context("builder should produce a tile")?;
3593 state
3594 .get_or_insert_with(other_key.clone(), &mut build_tile)?
3595 .context("builder should produce another tile")?;
3596
3597 state.remove(&key);
3598 state.remove(&key);
3599 assert!(!state.contains(&key));
3600 assert!(state.contains(&other_key));
3601 assert_eq!(state.backend.removed_tiles, vec![tile]);
3602
3603 let mut reset_calls = 0;
3604 state.clear(|_| reset_calls += 1);
3605 assert_eq!(reset_calls, 1);
3606 assert!(!state.contains(&other_key));
3607 assert_eq!(state.backend.removed_tiles, vec![tile]);
3608 Ok(())
3609 }
3610}
3611
3612#[cfg(test)]
3613mod frame_signal_tests {
3614 use super::*;
3615
3616 #[cfg(feature = "profiler")]
3617 #[test]
3618 fn coalesced_signals_retain_the_earliest_until_drained() {
3619 for (first_source, later_source) in [
3620 (
3621 FrameRequestSource::NativeCallback,
3622 FrameRequestSource::LocalSchedule,
3623 ),
3624 (
3625 FrameRequestSource::LocalSchedule,
3626 FrameRequestSource::NativeCallback,
3627 ),
3628 ] {
3629 let signal = PlatformFrameSignal::new();
3630 let first =
3631 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3632 assert_eq!(signal.take(), None);
3633 signal.record(first + Duration::from_millis(16), later_source);
3634 signal.record(first, first_source);
3635 signal.record(first + Duration::from_millis(32), later_source);
3636 assert_eq!(signal.take(), Some((first, first_source)));
3637 assert_eq!(signal.take(), None);
3638 let next = first + Duration::from_millis(48);
3639 signal.record(next, later_source);
3640 assert_eq!(signal.take(), Some((next, later_source)));
3641 }
3642 }
3643
3644 #[cfg(not(feature = "profiler"))]
3645 #[test]
3646 fn disabled_profiling_does_not_capture_or_store_timestamps() {
3647 let captured = PlatformFrameSignal::capture(|| {
3648 panic!("profiler-disabled builds must not evaluate the capture closure");
3649 });
3650 assert_eq!(captured, None);
3651 let signal = PlatformFrameSignal::new();
3652 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3653 assert_eq!(signal.take(), None);
3654 }
3655}
3656
3657#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3658mod tests {
3659 use super::*;
3660 use std::collections::HashSet;
3661
3662 #[test]
3663 fn test_refresh_interval_from_hz() {
3664 assert_eq!(
3665 refresh_interval_from_hz(50.0),
3666 Some(Duration::from_millis(20))
3667 );
3668 assert_eq!(
3669 refresh_interval_from_hz(120.0),
3670 Some(Duration::from_secs(1) / 120)
3671 );
3672 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
3673 assert_eq!(refresh_interval_from_hz(unknown), None);
3674 }
3675 }
3676
3677 #[test]
3678 fn test_window_button_layout_parse_standard() {
3679 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3680 assert_eq!(
3681 layout.left,
3682 [
3683 Some(WindowButton::Close),
3684 Some(WindowButton::Minimize),
3685 None
3686 ]
3687 );
3688 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3689 }
3690
3691 #[test]
3692 fn test_window_button_layout_parse_right_only() {
3693 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3694 assert_eq!(layout.left, [None, None, None]);
3695 assert_eq!(
3696 layout.right,
3697 [
3698 Some(WindowButton::Minimize),
3699 Some(WindowButton::Maximize),
3700 Some(WindowButton::Close)
3701 ]
3702 );
3703 }
3704
3705 #[test]
3706 fn test_window_button_layout_parse_left_only() {
3707 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3708 assert_eq!(
3709 layout.left,
3710 [
3711 Some(WindowButton::Close),
3712 Some(WindowButton::Minimize),
3713 Some(WindowButton::Maximize)
3714 ]
3715 );
3716 assert_eq!(layout.right, [None, None, None]);
3717 }
3718
3719 #[test]
3720 fn test_window_button_layout_parse_with_whitespace() {
3721 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3722 assert_eq!(
3723 layout.left,
3724 [
3725 Some(WindowButton::Close),
3726 Some(WindowButton::Minimize),
3727 None
3728 ]
3729 );
3730 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3731 }
3732
3733 #[test]
3734 fn test_window_button_layout_parse_empty() {
3735 let layout = WindowButtonLayout::parse("").unwrap();
3736 assert_eq!(layout.left, [None, None, None]);
3737 assert_eq!(layout.right, [None, None, None]);
3738 }
3739
3740 #[test]
3741 fn test_window_button_layout_parse_intentionally_empty() {
3742 let layout = WindowButtonLayout::parse(":").unwrap();
3743 assert_eq!(layout.left, [None, None, None]);
3744 assert_eq!(layout.right, [None, None, None]);
3745 }
3746
3747 #[test]
3748 fn test_window_button_layout_parse_invalid_buttons() {
3749 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
3750 assert_eq!(
3751 layout.left,
3752 [
3753 Some(WindowButton::Close),
3754 Some(WindowButton::Minimize),
3755 None
3756 ]
3757 );
3758 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3759 }
3760
3761 #[test]
3762 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
3763 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
3764 assert_eq!(
3765 layout.right,
3766 [
3767 Some(WindowButton::Close),
3768 Some(WindowButton::Minimize),
3769 None
3770 ]
3771 );
3772 assert_eq!(layout.format(), ":close,minimize");
3773 }
3774
3775 #[test]
3776 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
3777 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
3778 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3779 assert_eq!(
3780 layout.right,
3781 [
3782 Some(WindowButton::Maximize),
3783 Some(WindowButton::Minimize),
3784 None
3785 ]
3786 );
3787
3788 let button_ids: Vec<_> = layout
3789 .left
3790 .iter()
3791 .chain(layout.right.iter())
3792 .flatten()
3793 .map(WindowButton::id)
3794 .collect();
3795 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
3796 assert_eq!(unique_button_ids.len(), button_ids.len());
3797 assert_eq!(layout.format(), "close:maximize,minimize");
3798 }
3799
3800 #[test]
3801 fn test_window_button_layout_parse_gnome_style() {
3802 let layout = WindowButtonLayout::parse("close").unwrap();
3803 assert_eq!(layout.left, [None, None, None]);
3804 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
3805 }
3806
3807 #[test]
3808 fn test_window_button_layout_parse_elementary_style() {
3809 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
3810 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3811 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3812 }
3813
3814 #[test]
3815 fn test_window_button_layout_round_trip() {
3816 let cases = [
3817 "close:minimize,maximize",
3818 "minimize,maximize,close:",
3819 ":close",
3820 "close:",
3821 "close:maximize",
3822 ":",
3823 ];
3824
3825 for case in cases {
3826 let layout = WindowButtonLayout::parse(case).unwrap();
3827 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
3828 }
3829 }
3830
3831 #[test]
3832 fn test_window_button_layout_linux_default() {
3833 let layout = WindowButtonLayout::linux_default();
3834 assert_eq!(layout.left, [None, None, None]);
3835 assert_eq!(
3836 layout.right,
3837 [
3838 Some(WindowButton::Minimize),
3839 Some(WindowButton::Maximize),
3840 Some(WindowButton::Close)
3841 ]
3842 );
3843
3844 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
3845 assert_eq!(round_tripped, layout);
3846 }
3847
3848 #[test]
3849 fn test_window_button_layout_parse_all_invalid() {
3850 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
3851 }
3852}