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, Default, Clone, Copy, PartialEq, Eq)]
130pub enum ActivationPolicy {
131 #[default]
133 Regular,
134 Accessory,
136}
137
138#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
139pub(crate) use test::*;
140
141#[cfg(any(test, feature = "test-support"))]
142pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
143
144#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
145pub use threaded_dispatcher::ThreadedDispatcher;
146
147#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
148pub use visual_test::VisualTestPlatform;
149
150pub struct ActivityGuard {
152 _release: gpui_util::Deferred<Box<dyn FnOnce() + Send>>,
153}
154
155impl ActivityGuard {
156 pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
158 Self {
159 _release: gpui_util::defer(Box::new(release)),
160 }
161 }
162
163 pub fn noop() -> Self {
165 Self::new(|| {})
166 }
167}
168
169#[cfg(any(target_os = "linux", target_os = "freebsd"))]
173#[inline]
174pub fn guess_compositor() -> &'static str {
175 if std::env::var_os("ZED_HEADLESS").is_some() {
176 return "Headless";
177 }
178 GraphicalEnvironment::detect().guess_compositor()
179}
180
181#[cfg(any(target_os = "linux", target_os = "freebsd"))]
190#[derive(Clone, Debug, Default)]
191pub struct GraphicalEnvironment {
192 pub wayland_display: Option<OsString>,
194 pub x11_display: Option<OsString>,
196 pub xdg_runtime_dir: Option<OsString>,
198 pub activation_token: Option<String>,
204}
205
206#[cfg(target_os = "windows")]
212#[derive(Clone, Debug, Default)]
213pub struct GraphicalEnvironment {
214 pub session_id: Option<u32>,
217}
218
219#[cfg(target_os = "windows")]
220impl GraphicalEnvironment {
221 pub fn detect() -> Self {
223 let mut session_id = 0;
224 let result = unsafe {
226 windows::Win32::System::RemoteDesktop::ProcessIdToSessionId(
227 windows::Win32::System::Threading::GetCurrentProcessId(),
228 &mut session_id,
229 )
230 };
231 Self {
232 session_id: result.is_ok().then_some(session_id),
233 }
234 }
235
236 pub fn apply_to(&self, _command: &mut std::process::Command) {}
239}
240
241#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
243#[derive(Clone, Debug, Default)]
244pub struct GraphicalEnvironment;
245
246#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
247impl GraphicalEnvironment {
248 pub fn detect() -> Self {
250 Self
251 }
252
253 pub fn apply_to(&self, _command: &mut std::process::Command) {}
255}
256
257#[derive(Clone, Debug)]
259pub enum WindowingRequest {
260 Headless,
262 Windowed(GraphicalEnvironment),
264}
265
266#[cfg(any(target_os = "linux", target_os = "freebsd"))]
267impl GraphicalEnvironment {
268 pub fn detect() -> Self {
273 Self {
274 wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
275 x11_display: std::env::var_os("DISPLAY"),
276 xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
277 activation_token: None,
278 }
279 }
280
281 pub fn apply_to(&self, command: &mut std::process::Command) {
285 for (name, value) in [
286 ("WAYLAND_DISPLAY", &self.wayland_display),
287 ("DISPLAY", &self.x11_display),
288 ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
289 ] {
290 match value {
291 Some(value) => command.env(name, value),
292 None => command.env_remove(name),
293 };
294 }
295 }
296
297 pub fn guess_compositor(&self) -> &'static str {
301 let is_set =
302 |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
303 if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
304 "Wayland"
305 } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
306 "X11"
307 } else {
308 "Headless"
309 }
310 }
311}
312
313#[cfg(any(target_os = "linux", target_os = "freebsd"))]
314bitflags::bitflags! {
315 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
317 pub struct WindowingModes: u8 {
318 const WAYLAND = 1 << 0;
320 const X11 = 1 << 1;
322 const HEADLESS = 1 << 2;
324 }
325}
326
327#[expect(missing_docs)]
328pub trait Platform: 'static {
329 fn background_executor(&self) -> BackgroundExecutor;
330 fn foreground_executor(&self) -> ForegroundExecutor;
331 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
332
333 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
334 fn quit(&self);
335 fn set_initial_windowing(&self, _request: WindowingRequest) {}
340 fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
341 Task::ready(Err(anyhow::anyhow!(
342 "this platform cannot switch between headless and windowed modes"
343 )))
344 }
345 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
346 fn activate(&self, ignoring_other_apps: bool);
347 fn set_activation_policy(&self, _policy: ActivationPolicy) {}
349 fn hide(&self);
350 fn hide_other_apps(&self);
351 fn unhide_other_apps(&self);
352
353 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
354 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
355 fn active_window(&self) -> Option<AnyWindowHandle>;
356 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
357 None
358 }
359
360 fn is_screen_capture_supported(&self) -> bool {
361 false
362 }
363
364 fn screen_capture_sources(
365 &self,
366 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
367 let (sources_tx, sources_rx) = oneshot::channel();
368 sources_tx
369 .send(Err(anyhow::anyhow!(
370 "gpui was compiled without the screen-capture feature"
371 )))
372 .ok();
373 sources_rx
374 }
375
376 fn open_window(
377 &self,
378 handle: AnyWindowHandle,
379 options: WindowParams,
380 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
381
382 fn window_appearance(&self) -> WindowAppearance;
384
385 fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
394
395 fn button_layout(&self) -> Option<WindowButtonLayout> {
397 None
398 }
399
400 fn open_url(&self, url: &str);
401 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
402 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
403
404 fn prompt_for_paths(
405 &self,
406 options: PathPromptOptions,
407 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
408 fn prompt_for_new_path(
409 &self,
410 directory: &Path,
411 suggested_name: Option<&str>,
412 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
413 fn can_select_mixed_files_and_dirs(&self) -> bool;
414 fn reveal_path(&self, path: &Path);
415 fn open_with_system(&self, path: &Path);
416
417 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
418 fn on_reopen(&self, callback: Box<dyn FnMut()>);
419 fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
421 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
423
424 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
434
435 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
440
441 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
445 None
446 }
447
448 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
449 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
450 None
451 }
452
453 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
454 fn perform_dock_menu_action(&self, _action: usize) {}
455 fn add_recent_document(&self, _path: &Path) {}
456 fn update_jump_list(
457 &self,
458 _menus: Vec<MenuItem>,
459 _entries: Vec<SmallVec<[PathBuf; 2]>>,
460 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
461 Task::ready(Vec::new())
462 }
463 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
464 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
465 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
466
467 fn thermal_state(&self) -> ThermalState;
468 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
469 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
470
471 fn set_app_identity(&self, identifier: &str, name: &str) {
478 _ = (identifier, name);
479 }
480
481 fn show_system_notification(&self, notification: SystemNotification) {
488 _ = notification;
489 }
490
491 fn dismiss_system_notification(&self, tag: &str) {
496 _ = tag;
497 }
498
499 fn on_system_notification_response(
505 &self,
506 callback: Box<dyn FnMut(SystemNotificationResponse)>,
507 ) {
508 _ = callback;
509 }
510
511 fn compositor_name(&self) -> &'static str {
512 ""
513 }
514 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
517 None
518 }
519 fn app_path(&self) -> Result<PathBuf>;
520 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
521
522 fn set_cursor_style(&self, style: CursorStyle);
523
524 fn hide_cursor_until_mouse_moves(&self);
527
528 fn is_cursor_visible(&self) -> bool;
530
531 fn should_auto_hide_scrollbars(&self) -> bool;
532
533 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
534 fn write_to_clipboard(&self, item: ClipboardItem);
535
536 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
544 Task::ready(Ok(self.read_from_clipboard()))
545 }
546
547 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
548 fn read_from_primary(&self) -> Option<ClipboardItem>;
549 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
550 fn write_to_primary(&self, item: ClipboardItem);
551
552 #[cfg(target_os = "macos")]
553 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
554 #[cfg(target_os = "macos")]
555 fn write_to_find_pasteboard(&self, item: ClipboardItem);
556
557 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
558 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
559 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
560
561 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
562 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
563 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
564}
565
566pub trait PlatformDisplay: Debug {
568 fn id(&self) -> DisplayId;
570
571 fn uuid(&self) -> Result<Uuid>;
574
575 fn bounds(&self) -> Bounds<Pixels>;
577
578 fn visible_bounds(&self) -> Bounds<Pixels> {
582 self.bounds()
583 }
584
585 fn default_bounds(&self) -> Bounds<Pixels> {
587 let bounds = self.bounds();
588 let center = bounds.center();
589 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
590
591 let offset = clipped_window_size / 2.0;
592 let origin = point(center.x - offset.width, center.y - offset.height);
593 Bounds::new(origin, clipped_window_size)
594 }
595}
596
597#[derive(Clone, Debug, PartialEq, Eq)]
600pub struct SystemNotification {
601 pub tag: SharedString,
605 pub title: SharedString,
607 pub body: SharedString,
609 pub actions: Vec<SystemNotificationAction>,
612}
613
614#[derive(Clone, Debug, PartialEq, Eq, Hash)]
616pub struct SystemNotificationAction {
617 pub id: SharedString,
620 pub label: SharedString,
622}
623
624#[derive(Clone, Debug, PartialEq, Eq)]
626pub struct SystemNotificationResponse {
627 pub tag: SharedString,
629 pub action_id: Option<SharedString>,
632}
633
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
636pub enum ThermalState {
637 Nominal,
639 Fair,
641 Serious,
643 Critical,
645}
646
647#[derive(Clone)]
649pub struct SourceMetadata {
650 pub id: u64,
652 pub label: Option<SharedString>,
654 pub is_main: Option<bool>,
656 pub resolution: Size<DevicePixels>,
658}
659
660pub trait ScreenCaptureSource {
662 fn metadata(&self) -> Result<SourceMetadata>;
664
665 fn stream(
668 &self,
669 foreground_executor: &ForegroundExecutor,
670 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
671 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
672}
673
674pub trait ScreenCaptureStream {
676 fn metadata(&self) -> Result<SourceMetadata>;
678}
679
680pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
682
683#[derive(PartialEq, Eq, Hash, Copy, Clone)]
685pub struct DisplayId(pub(crate) u64);
686
687impl DisplayId {
688 pub fn new(id: u64) -> Self {
690 Self(id)
691 }
692}
693
694impl From<u64> for DisplayId {
695 fn from(id: u64) -> Self {
696 Self(id)
697 }
698}
699
700impl From<DisplayId> for u64 {
701 fn from(id: DisplayId) -> Self {
702 id.0
703 }
704}
705
706impl Debug for DisplayId {
707 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
708 write!(f, "DisplayId({})", self.0)
709 }
710}
711
712#[derive(Debug, Clone, Copy, PartialEq, Eq)]
714pub enum ResizeEdge {
715 Top,
717 TopRight,
719 Right,
721 BottomRight,
723 Bottom,
725 BottomLeft,
727 Left,
729 TopLeft,
731}
732
733#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
735pub enum WindowDecorations {
736 #[default]
737 Server,
739 Client,
741}
742
743#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
745pub enum Decorations {
746 #[default]
748 Server,
749 Client {
751 tiling: Tiling,
753 },
754}
755
756#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
758pub struct WindowControls {
759 pub fullscreen: bool,
761 pub maximize: bool,
763 pub minimize: bool,
765 pub window_menu: bool,
767}
768
769impl Default for WindowControls {
770 fn default() -> Self {
771 Self {
773 fullscreen: true,
774 maximize: true,
775 minimize: true,
776 window_menu: true,
777 }
778 }
779}
780
781#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
783pub enum WindowButton {
784 Minimize,
786 Maximize,
788 Close,
790}
791
792impl WindowButton {
793 pub fn id(&self) -> &'static str {
795 match self {
796 WindowButton::Minimize => "minimize",
797 WindowButton::Maximize => "maximize",
798 WindowButton::Close => "close",
799 }
800 }
801
802 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
803 fn index(&self) -> usize {
804 match self {
805 WindowButton::Minimize => 0,
806 WindowButton::Maximize => 1,
807 WindowButton::Close => 2,
808 }
809 }
810}
811
812pub const MAX_BUTTONS_PER_SIDE: usize = 3;
814
815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
820pub struct WindowButtonLayout {
821 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
823 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
825}
826
827#[cfg(any(target_os = "linux", target_os = "freebsd"))]
828impl WindowButtonLayout {
829 pub fn linux_default() -> Self {
831 Self {
832 left: [None; MAX_BUTTONS_PER_SIDE],
833 right: [
834 Some(WindowButton::Minimize),
835 Some(WindowButton::Maximize),
836 Some(WindowButton::Close),
837 ],
838 }
839 }
840
841 pub fn parse(layout_string: &str) -> Result<Self> {
843 fn parse_side(
844 s: &str,
845 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
846 unrecognized: &mut Vec<String>,
847 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
848 let mut result = [None; MAX_BUTTONS_PER_SIDE];
849 let mut i = 0;
850 for name in s.split(',') {
851 let trimmed = name.trim();
852 if trimmed.is_empty() {
853 continue;
854 }
855 let button = match trimmed {
856 "minimize" => Some(WindowButton::Minimize),
857 "maximize" => Some(WindowButton::Maximize),
858 "close" => Some(WindowButton::Close),
859 other => {
860 unrecognized.push(other.to_string());
861 None
862 }
863 };
864 if let Some(button) = button {
865 if seen_buttons[button.index()] {
866 continue;
867 }
868 if let Some(slot) = result.get_mut(i) {
869 *slot = Some(button);
870 seen_buttons[button.index()] = true;
871 i += 1;
872 }
873 }
874 }
875 result
876 }
877
878 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
879 let mut unrecognized = Vec::new();
880 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
881 let layout = Self {
882 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
883 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
884 };
885
886 if !unrecognized.is_empty()
887 && layout.left.iter().all(Option::is_none)
888 && layout.right.iter().all(Option::is_none)
889 {
890 bail!(
891 "button layout string {:?} contains no valid buttons (unrecognized: {})",
892 layout_string,
893 unrecognized.join(", ")
894 );
895 }
896
897 Ok(layout)
898 }
899
900 #[cfg(test)]
902 pub fn format(&self) -> String {
903 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
904 buttons
905 .iter()
906 .flatten()
907 .map(|button| match button {
908 WindowButton::Minimize => "minimize",
909 WindowButton::Maximize => "maximize",
910 WindowButton::Close => "close",
911 })
912 .collect::<Vec<_>>()
913 .join(",")
914 }
915
916 format!("{}:{}", format_side(&self.left), format_side(&self.right))
917 }
918}
919
920#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
922pub struct Tiling {
923 pub top: bool,
925 pub left: bool,
927 pub right: bool,
929 pub bottom: bool,
931}
932
933impl Tiling {
934 pub fn tiled() -> Self {
936 Self {
937 top: true,
938 left: true,
939 right: true,
940 bottom: true,
941 }
942 }
943
944 pub fn is_tiled(&self) -> bool {
946 self.top || self.left || self.right || self.bottom
947 }
948}
949
950pub struct A11yCallbacks {
952 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
954 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
956 pub deactivation: Box<dyn Fn() + Send + 'static>,
958}
959
960#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
962pub enum FrameRequestSource {
963 #[default]
965 NativeCallback,
966 LocalSchedule,
968}
969
970#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
971#[expect(missing_docs)]
972pub struct RequestFrameOptions {
973 pub require_presentation: bool,
975 pub force_render: bool,
977 pub signal_at: Option<Instant>,
983 pub signal_source: FrameRequestSource,
985}
986
987pub struct PlatformFrameSignal {
996 #[cfg(feature = "profiler")]
997 origin: Instant,
998 #[cfg(feature = "profiler")]
999 first_signal: std::sync::atomic::AtomicU64,
1000}
1001
1002impl Default for PlatformFrameSignal {
1003 fn default() -> Self {
1004 Self::new()
1005 }
1006}
1007
1008impl PlatformFrameSignal {
1009 pub fn new() -> Self {
1011 Self {
1012 #[cfg(feature = "profiler")]
1013 origin: Instant::now(),
1014 #[cfg(feature = "profiler")]
1015 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1016 }
1017 }
1018
1019 #[inline]
1023 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1024 if cfg!(feature = "profiler") {
1025 Some(capture())
1026 } else {
1027 None
1028 }
1029 }
1030
1031 #[inline]
1033 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1034 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1035 #[cfg(feature = "profiler")]
1036 {
1037 let nanoseconds = at
1038 .saturating_duration_since(self.origin)
1039 .as_nanos()
1040 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1041 let source_bit = match source {
1042 FrameRequestSource::NativeCallback => 0,
1043 FrameRequestSource::LocalSchedule => 1,
1044 };
1045 self.first_signal.fetch_min(
1046 (nanoseconds << 1) | source_bit,
1047 std::sync::atomic::Ordering::Relaxed,
1048 );
1049 }
1050 }
1051
1052 #[inline]
1054 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1055 #[cfg(feature = "profiler")]
1056 {
1057 let signal = self
1058 .first_signal
1059 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1060 (signal != u64::MAX).then(|| {
1061 let source = match signal & 1 {
1062 0 => FrameRequestSource::NativeCallback,
1063 _ => FrameRequestSource::LocalSchedule,
1064 };
1065 (self.origin + Duration::from_nanos(signal >> 1), source)
1066 })
1067 }
1068 #[cfg(not(feature = "profiler"))]
1069 {
1070 None
1071 }
1072 }
1073}
1074
1075#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1088pub enum AppLifecyclePhase {
1089 Active,
1091 Inactive,
1093 Background,
1096 Foreground,
1098}
1099
1100#[derive(Debug, Clone, Default, PartialEq)]
1107pub struct WindowInsets {
1108 pub safe_area: Edges<Pixels>,
1113 pub ime: Edges<Pixels>,
1117}
1118
1119impl WindowInsets {
1120 pub fn effective(&self) -> Edges<Pixels> {
1122 Edges {
1123 top: self.safe_area.top.max(self.ime.top),
1124 right: self.safe_area.right.max(self.ime.right),
1125 bottom: self.safe_area.bottom.max(self.ime.bottom),
1126 left: self.safe_area.left.max(self.ime.left),
1127 }
1128 }
1129}
1130
1131#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1133pub enum TextInputStateChange {
1134 FocusGained,
1136 FocusLost,
1138 SelectionChanged,
1140 ContentChanged,
1142}
1143
1144#[expect(missing_docs)]
1145pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1146 fn bounds(&self) -> Bounds<Pixels>;
1147 fn is_maximized(&self) -> bool;
1148 fn window_bounds(&self) -> WindowBounds;
1149 fn content_size(&self) -> Size<Pixels>;
1150 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1156 Bounds::new(Point::default(), self.content_size())
1157 }
1158 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1163 fn prepare_frame(&self) -> bool {
1168 false
1169 }
1170 fn resize(&mut self, size: Size<Pixels>);
1171 fn scale_factor(&self) -> f32;
1172 fn appearance(&self) -> WindowAppearance;
1173 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1174 fn mouse_position(&self) -> Point<Pixels>;
1175 fn modifiers(&self) -> Modifiers;
1176 fn capslock(&self) -> Capslock;
1177 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1178 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1179 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1184 fn prompt(
1185 &self,
1186 level: PromptLevel,
1187 msg: &str,
1188 detail: Option<&str>,
1189 answers: &[PromptButton],
1190 ) -> Option<oneshot::Receiver<usize>>;
1191 fn activate(&self);
1192 fn request_attention(&self) {}
1194 fn is_active(&self) -> bool;
1195 fn visibility(&self) -> WindowVisibility;
1198 fn is_hovered(&self) -> bool;
1199 fn background_appearance(&self) -> WindowBackgroundAppearance;
1200 fn set_title(&mut self, title: &str);
1201 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1202 fn minimize(&self);
1203 fn zoom(&self);
1204 fn toggle_fullscreen(&self);
1205 fn is_fullscreen(&self) -> bool;
1206 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1207 None
1208 }
1209 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1210 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1211 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1212 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1216 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1217 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1218 fn on_moved(&self, callback: Box<dyn FnMut()>);
1219 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1220 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1221 fn on_close(&self, callback: Box<dyn FnOnce()>);
1222 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1223 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1224 fn draw(&self, scene: &Scene);
1225 fn draw_composed(&self, scene: crate::fast::composition::ComposedScene<'_>) {
1226 crate::fast::composition::draw_uncomposed(self, scene)
1227 }
1228 fn enable_window_composition(&self) -> Result<()> {
1229 crate::fast::composition::unsupported("window composition")
1230 }
1231 fn create_native_surface(
1232 &self,
1233 ) -> Result<Rc<dyn crate::fast::composition::PlatformSurfaceAttachment>> {
1234 crate::fast::composition::unsupported("native surface portals")
1235 }
1236 fn set_composition_order(
1237 &self,
1238 _fast_surfaces: &[crate::fast::composition::PlatformCompositionSurface],
1239 ) -> Result<()> {
1240 crate::fast::composition::unsupported("surface ordering")
1241 }
1242 fn schedule_frame(&self) {}
1243 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1244 fn is_subpixel_rendering_supported(&self) -> bool;
1245
1246 fn get_title(&self) -> String {
1248 String::new()
1249 }
1250 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1251 None
1252 }
1253 fn tab_bar_visible(&self) -> bool {
1254 false
1255 }
1256 fn set_edited(&mut self, _edited: bool) {}
1257 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1258 fn toggle_simple_fullscreen(&self) {}
1259 fn is_simple_fullscreen(&self) -> bool {
1260 false
1261 }
1262 #[cfg(target_os = "macos")]
1263 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1264 fn show_character_palette(&self) {}
1265 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1266 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1267 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1268 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1269 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1270 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1271 fn merge_all_windows(&self) {}
1272 fn move_tab_to_new_window(&self) {}
1273 fn toggle_window_tab_overview(&self) {}
1274 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1275
1276 fn native_window_state(&self) -> Option<Vec<u8>> {
1277 None
1278 }
1279 fn restore_native_window_state(&self, _state: &[u8]) {}
1280
1281 #[cfg(target_os = "windows")]
1282 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1283
1284 fn inner_window_bounds(&self) -> WindowBounds {
1286 self.window_bounds()
1287 }
1288 fn request_decorations(&self, _decorations: WindowDecorations) {}
1289 fn show_window_menu(&self, _position: Point<Pixels>) {}
1290 fn start_window_move(&self) {}
1291 fn can_start_external_drag(&self) -> bool {
1292 false
1293 }
1294 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1295 false
1296 }
1297 fn start_window_resize(&self, _edge: ResizeEdge) {}
1298 fn set_exclusive_zone(&self, _zone: Pixels) {}
1299 #[cfg(all(target_os = "linux", feature = "wayland"))]
1300 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1301 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1302 fn window_decorations(&self) -> Decorations {
1303 Decorations::Server
1304 }
1305 fn set_app_id(&mut self, _app_id: &str) {}
1306 fn map_window(&mut self) -> anyhow::Result<()> {
1307 Ok(())
1308 }
1309 fn window_controls(&self) -> WindowControls {
1310 WindowControls::default()
1311 }
1312 fn set_client_inset(&self, _inset: Pixels) {}
1313 fn gpu_specs(&self) -> Option<GpuSpecs>;
1314
1315 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1316
1317 fn insets(&self) -> WindowInsets {
1322 WindowInsets::default()
1323 }
1324
1325 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1331
1332 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1335
1336 fn set_back_enabled(&self, _enabled: bool) {}
1339
1340 fn show_soft_keyboard(&self) {}
1342
1343 fn hide_soft_keyboard(&self) {}
1345
1346 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1348
1349 fn play_system_bell(&self) {}
1350
1351 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1353
1354 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1356
1357 fn a11y_update_window_bounds(&self) {}
1359
1360 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1361 fn as_test(&mut self) -> Option<&mut TestWindow> {
1362 None
1363 }
1364
1365 #[cfg(any(test, feature = "test-support"))]
1369 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1370 anyhow::bail!("render_to_image not implemented for this platform")
1371 }
1372}
1373
1374#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1376pub trait PlatformHeadlessRenderer {
1377 fn render_scene_to_image(
1379 &mut self,
1380 scene: &Scene,
1381 size: Size<DevicePixels>,
1382 ) -> Result<RgbaImage>;
1383
1384 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1390
1391 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1393}
1394
1395#[doc(hidden)]
1398pub type RunnableVariant = Runnable<RunnableMeta>;
1399
1400#[doc(hidden)]
1401pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1402
1403#[doc(hidden)]
1404pub enum TasksIncluded {
1405 OnlyCompleted,
1406 CompletedAndRunning,
1407}
1408
1409#[doc(hidden)]
1412pub trait PlatformDispatcher: Send + Sync {
1413 fn is_main_thread(&self) -> bool;
1414 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1415 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1416 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1417
1418 fn dispatch_on_main_thread_when_idle(
1419 &self,
1420 runnable: RunnableVariant,
1421 timeout: Option<Duration>,
1422 ) {
1423 let _ = timeout;
1424 self.dispatch_on_main_thread(runnable, Priority::Low);
1425 }
1426
1427 fn idle_time_remaining(&self) -> Option<Duration> {
1428 None
1429 }
1430
1431 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1432
1433 fn now(&self) -> Instant {
1434 Instant::now()
1435 }
1436
1437 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1438 gpui_util::defer(Box::new(|| {}))
1439 }
1440
1441 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1442 ActivityGuard::noop()
1443 }
1444
1445 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1446 fn as_test(&self) -> Option<&TestDispatcher> {
1447 None
1448 }
1449
1450 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1453 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1454 None
1455 }
1456}
1457
1458#[expect(missing_docs)]
1459pub trait PlatformTextSystem: Send + Sync {
1460 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1461 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1463 fn all_font_names(&self) -> Vec<String>;
1465 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1467 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1469 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1471 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1473 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1475 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1477 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1479 fn rasterize_glyph(
1481 &self,
1482 params: &RenderGlyphParams,
1483 raster_bounds: Bounds<DevicePixels>,
1484 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1485 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1487 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1489 -> TextRenderingMode;
1490 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1492 0
1493 }
1494}
1495
1496#[expect(missing_docs)]
1497pub struct NoopTextSystem;
1498
1499#[expect(missing_docs)]
1500impl NoopTextSystem {
1501 #[allow(dead_code)]
1502 pub fn new() -> Self {
1503 Self
1504 }
1505}
1506
1507impl PlatformTextSystem for NoopTextSystem {
1508 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1509 Ok(())
1510 }
1511
1512 fn all_font_names(&self) -> Vec<String> {
1513 Vec::new()
1514 }
1515
1516 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1517 Ok(FontId(1))
1518 }
1519
1520 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1521 FontMetrics {
1522 units_per_em: 1000,
1523 ascent: 1025.0,
1524 descent: -275.0,
1525 line_gap: 0.0,
1526 underline_position: -95.0,
1527 underline_thickness: 60.0,
1528 cap_height: 698.0,
1529 x_height: 516.0,
1530 bounding_box: Bounds {
1531 origin: Point {
1532 x: -260.0,
1533 y: -245.0,
1534 },
1535 size: Size {
1536 width: 1501.0,
1537 height: 1364.0,
1538 },
1539 },
1540 }
1541 }
1542
1543 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1544 Ok(Bounds {
1545 origin: Point { x: 54.0, y: 0.0 },
1546 size: size(392.0, 528.0),
1547 })
1548 }
1549
1550 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1551 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1552 }
1553
1554 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1555 Some(GlyphId(ch.len_utf16() as u32))
1556 }
1557
1558 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1559 Ok(Default::default())
1560 }
1561
1562 fn rasterize_glyph(
1563 &self,
1564 _params: &RenderGlyphParams,
1565 raster_bounds: Bounds<DevicePixels>,
1566 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1567 Ok((raster_bounds.size, Vec::new()))
1568 }
1569
1570 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1571 let mut position = px(0.);
1572 let metrics = self.font_metrics(FontId(0));
1573 let em_width = font_size
1574 * self
1575 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1576 .unwrap()
1577 .width
1578 / metrics.units_per_em as f32;
1579 let mut glyphs = Vec::new();
1580 for (ix, c) in text.char_indices() {
1581 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1582 glyphs.push(ShapedGlyph {
1583 id: glyph,
1584 position: point(position, px(0.)),
1585 index: ix,
1586 is_emoji: glyph.0 == 2,
1587 });
1588 if glyph.0 == 2 {
1589 position += em_width * 2.0;
1590 } else {
1591 position += em_width;
1592 }
1593 } else {
1594 position += em_width
1595 }
1596 }
1597 let mut runs = Vec::default();
1598 if !glyphs.is_empty() {
1599 runs.push(ShapedRun {
1600 font_id: FontId(0),
1601 glyphs,
1602 });
1603 } else {
1604 position = px(0.);
1605 }
1606
1607 LineLayout {
1608 font_size,
1609 width: position,
1610 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1611 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1612 runs,
1613 len: text.len(),
1614 }
1615 }
1616
1617 fn recommended_rendering_mode(
1618 &self,
1619 _font_id: FontId,
1620 _font_size: Pixels,
1621 ) -> TextRenderingMode {
1622 TextRenderingMode::Grayscale
1623 }
1624}
1625
1626#[allow(dead_code)]
1631pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1632 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1633 [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], ];
1647
1648 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1649 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1650
1651 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1652 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1653
1654 [
1655 ratios[0] * NORM13,
1656 ratios[1] * NORM24,
1657 ratios[2] * NORM13,
1658 ratios[3] * NORM24,
1659 ]
1660}
1661
1662#[derive(PartialEq, Eq, Hash, Clone)]
1663#[expect(missing_docs)]
1664pub enum AtlasKey {
1665 Glyph(RenderGlyphParams),
1666 Svg(RenderSvgParams),
1667 Image(RenderImageParams),
1668}
1669
1670impl AtlasKey {
1671 pub fn texture_kind(&self) -> AtlasTextureKind {
1673 match self {
1674 AtlasKey::Glyph(params) => {
1675 if params.is_emoji {
1676 AtlasTextureKind::Polychrome
1677 } else if params.subpixel_rendering {
1678 AtlasTextureKind::Subpixel
1679 } else {
1680 AtlasTextureKind::Monochrome
1681 }
1682 }
1683 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1684 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1685 }
1686 }
1687}
1688
1689impl From<RenderGlyphParams> for AtlasKey {
1690 fn from(params: RenderGlyphParams) -> Self {
1691 Self::Glyph(params)
1692 }
1693}
1694
1695impl From<RenderSvgParams> for AtlasKey {
1696 fn from(params: RenderSvgParams) -> Self {
1697 Self::Svg(params)
1698 }
1699}
1700
1701impl From<RenderImageParams> for AtlasKey {
1702 fn from(params: RenderImageParams) -> Self {
1703 Self::Image(params)
1704 }
1705}
1706
1707#[expect(missing_docs)]
1708pub trait PlatformAtlas {
1709 fn get_or_insert_with<'a>(
1711 &self,
1712 key: AtlasKey,
1713 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1714 ) -> Result<Option<AtlasTile>>;
1715 fn remove(&self, key: &AtlasKey);
1716
1717 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1718 fn contains(&self, _key: &AtlasKey) -> bool {
1719 false
1720 }
1721}
1722
1723#[doc(hidden)]
1724pub trait AtlasBackend {
1725 fn insert(
1726 &mut self,
1727 kind: AtlasTextureKind,
1728 size: Size<DevicePixels>,
1729 bytes: &[u8],
1730 ) -> Result<AtlasTile>;
1731
1732 fn remove(&mut self, tile: AtlasTile);
1733}
1734
1735#[doc(hidden)]
1736pub struct AtlasState<Backend> {
1737 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1738 pub backend: Backend,
1739}
1740
1741impl<Backend> AtlasState<Backend> {
1742 pub fn new(backend: Backend) -> Self {
1743 Self {
1744 tiles_by_key: FxHashMap::default(),
1745 backend,
1746 }
1747 }
1748
1749 pub fn contains(&self, key: &AtlasKey) -> bool {
1750 self.tiles_by_key.contains_key(key)
1751 }
1752
1753 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1754 self.tiles_by_key.clear();
1755 reset_backend(&mut self.backend);
1756 }
1757}
1758
1759impl<Backend: Default> Default for AtlasState<Backend> {
1760 fn default() -> Self {
1761 Self::new(Backend::default())
1762 }
1763}
1764
1765impl<Backend: AtlasBackend> AtlasState<Backend> {
1766 pub fn get_or_insert_with<'a>(
1767 &mut self,
1768 key: AtlasKey,
1769 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1770 ) -> Result<Option<AtlasTile>> {
1771 match self.tiles_by_key.entry(key) {
1772 Entry::Occupied(entry) => Ok(Some(*entry.get())),
1773 Entry::Vacant(entry) => {
1774 profiling::scope!("new tile");
1775 let Some((size, bytes)) = build()? else {
1776 return Ok(None);
1777 };
1778 let tile = self
1779 .backend
1780 .insert(entry.key().texture_kind(), size, &bytes)?;
1781 entry.insert(tile);
1782 Ok(Some(tile))
1783 }
1784 }
1785 }
1786
1787 pub fn remove(&mut self, key: &AtlasKey) {
1788 if let Some(tile) = self.tiles_by_key.remove(key) {
1789 self.backend.remove(tile);
1790 }
1791 }
1792}
1793
1794#[derive(Default)]
1798pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1799
1800#[doc(hidden)]
1801#[derive(Default)]
1802pub struct HeadlessAtlasBackend {
1803 next_id: u32,
1804}
1805
1806impl AtlasBackend for HeadlessAtlasBackend {
1807 fn insert(
1808 &mut self,
1809 kind: AtlasTextureKind,
1810 size: Size<DevicePixels>,
1811 _bytes: &[u8],
1812 ) -> Result<AtlasTile> {
1813 self.next_id += 1;
1814 let texture_id = self.next_id;
1815 self.next_id += 1;
1816 let tile_id = self.next_id;
1817 Ok(AtlasTile {
1818 texture_id: AtlasTextureId {
1819 index: texture_id,
1820 kind,
1821 },
1822 tile_id: TileId(tile_id),
1823 padding: 0,
1824 bounds: Bounds {
1825 origin: Point::default(),
1826 size,
1827 },
1828 })
1829 }
1830
1831 fn remove(&mut self, _tile: AtlasTile) {}
1832}
1833
1834impl PlatformAtlas for HeadlessAtlas {
1835 fn get_or_insert_with<'a>(
1836 &self,
1837 key: AtlasKey,
1838 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1839 ) -> Result<Option<AtlasTile>> {
1840 self.0.lock().get_or_insert_with(key, build)
1841 }
1842
1843 fn remove(&self, key: &AtlasKey) {
1844 self.0.lock().remove(key);
1845 }
1846
1847 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1848 fn contains(&self, key: &AtlasKey) -> bool {
1849 self.0.lock().contains(key)
1850 }
1851}
1852
1853#[doc(hidden)]
1854pub struct AtlasTextureList<T> {
1855 pub textures: Vec<Option<T>>,
1856 pub free_list: Vec<usize>,
1857}
1858
1859impl<T> Default for AtlasTextureList<T> {
1860 fn default() -> Self {
1861 Self {
1862 textures: Vec::default(),
1863 free_list: Vec::default(),
1864 }
1865 }
1866}
1867
1868impl<T> ops::Index<usize> for AtlasTextureList<T> {
1869 type Output = Option<T>;
1870
1871 fn index(&self, index: usize) -> &Self::Output {
1872 &self.textures[index]
1873 }
1874}
1875
1876impl<T> AtlasTextureList<T> {
1877 #[allow(unused)]
1878 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1879 self.free_list.clear();
1880 self.textures.drain(..)
1881 }
1882
1883 #[allow(dead_code)]
1884 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1885 self.textures.iter_mut().flatten()
1886 }
1887}
1888
1889#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1890#[repr(C)]
1891#[expect(missing_docs)]
1892pub struct AtlasTile {
1893 pub texture_id: AtlasTextureId,
1895 pub tile_id: TileId,
1897 pub padding: u32,
1899 pub bounds: Bounds<DevicePixels>,
1901}
1902
1903#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1904#[repr(C)]
1905#[expect(missing_docs)]
1906pub struct AtlasTextureId {
1907 pub index: u32,
1910 pub kind: AtlasTextureKind,
1912}
1913
1914#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1915#[repr(C)]
1916#[cfg_attr(
1917 all(
1918 any(target_os = "linux", target_os = "freebsd"),
1919 not(any(feature = "x11", feature = "wayland"))
1920 ),
1921 allow(dead_code)
1922)]
1923#[expect(missing_docs)]
1924pub enum AtlasTextureKind {
1925 Monochrome = 0,
1926 Polychrome = 1,
1927 Subpixel = 2,
1928}
1929
1930#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1931#[repr(C)]
1932#[expect(missing_docs)]
1933pub struct TileId(pub u32);
1934
1935impl From<etagere::AllocId> for TileId {
1936 fn from(id: etagere::AllocId) -> Self {
1937 Self(id.serialize())
1938 }
1939}
1940
1941impl From<TileId> for etagere::AllocId {
1942 fn from(id: TileId) -> Self {
1943 Self::deserialize(id.0)
1944 }
1945}
1946
1947#[expect(missing_docs)]
1948pub struct PlatformInputHandler {
1949 cx: AsyncWindowContext,
1950 handler: Box<dyn InputHandler>,
1951}
1952
1953#[expect(missing_docs)]
1954#[cfg_attr(
1955 all(
1956 any(target_os = "linux", target_os = "freebsd"),
1957 not(any(feature = "x11", feature = "wayland"))
1958 ),
1959 allow(dead_code)
1960)]
1961impl PlatformInputHandler {
1962 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
1963 Self { cx, handler }
1964 }
1965
1966 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
1967 self.cx
1968 .update(|window, cx| {
1969 self.handler
1970 .selected_text_range(ignore_disabled_input, window, cx)
1971 })
1972 .ok()
1973 .flatten()
1974 }
1975
1976 #[cfg_attr(target_os = "windows", allow(dead_code))]
1977 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
1978 self.cx
1979 .update(|window, cx| self.handler.marked_text_range(window, cx))
1980 .ok()
1981 .flatten()
1982 }
1983
1984 #[cfg_attr(
1985 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1986 allow(dead_code)
1987 )]
1988 pub fn text_for_range(
1989 &mut self,
1990 range_utf16: Range<usize>,
1991 adjusted: &mut Option<Range<usize>>,
1992 ) -> Option<String> {
1993 self.cx
1994 .update(|window, cx| {
1995 self.handler
1996 .text_for_range(range_utf16, adjusted, window, cx)
1997 })
1998 .ok()
1999 .flatten()
2000 }
2001
2002 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2003 self.cx
2004 .update(|window, cx| {
2005 self.handler
2006 .replace_text_in_range(replacement_range, text, window, cx);
2007 })
2008 .ok();
2009 }
2010
2011 pub fn replace_and_mark_text_in_range(
2012 &mut self,
2013 range_utf16: Option<Range<usize>>,
2014 new_text: &str,
2015 new_selected_range: Option<Range<usize>>,
2016 ) {
2017 self.cx
2018 .update(|window, cx| {
2019 self.handler.replace_and_mark_text_in_range(
2020 range_utf16,
2021 new_text,
2022 new_selected_range,
2023 window,
2024 cx,
2025 )
2026 })
2027 .ok();
2028 }
2029
2030 #[cfg_attr(target_os = "windows", allow(dead_code))]
2031 pub fn unmark_text(&mut self) {
2032 self.cx
2033 .update(|window, cx| self.handler.unmark_text(window, cx))
2034 .ok();
2035 }
2036
2037 pub fn paste(&mut self, item: ClipboardItem) {
2038 self.cx
2039 .update(|window, cx| self.handler.paste(item, window, cx))
2040 .ok();
2041 }
2042
2043 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2044 self.cx
2045 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2046 .ok()
2047 .flatten()
2048 }
2049
2050 #[allow(dead_code)]
2051 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2052 self.handler.apple_press_and_hold_enabled()
2053 }
2054
2055 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2056 self.handler.replace_text_in_range(None, input, window, cx);
2057 }
2058
2059 pub fn compute_ime_candidate_bounds(
2060 marked_range: Option<Range<usize>>,
2061 selection: &UTF16Selection,
2062 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2063 ) -> Option<Bounds<Pixels>> {
2064 if let Some(marked_range) = marked_range {
2065 let mut line_start = marked_range.start;
2067
2068 let caret = selection.range.end;
2072 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2073 for i in (marked_range.start..caret).rev() {
2074 if let Some(b) = bounds_for_range(i..i) {
2075 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2076 line_start = i + 1;
2077 break;
2078 }
2079 }
2080 }
2081 }
2082 bounds_for_range(line_start..line_start)
2083 } else {
2084 let offset = if selection.reversed {
2086 selection.range.start
2087 } else {
2088 selection.range.end
2089 };
2090 bounds_for_range(offset..offset)
2091 }
2092 }
2093
2094 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2095 let marked_range = self.handler.marked_text_range(window, cx);
2096 let selection = self.handler.selected_text_range(true, window, cx)?;
2097 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2098 self.handler.bounds_for_range(range, window, cx)
2099 })
2100 }
2101
2102 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2103 let marked_range = self.marked_text_range();
2104 let selection = self.selected_text_range(true)?;
2105 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2106 self.bounds_for_range(range)
2107 })
2108 }
2109
2110 #[allow(unused)]
2111 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2112 self.cx
2113 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2114 .ok()
2115 .flatten()
2116 }
2117
2118 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2120 self.cx
2121 .update(|window, cx| {
2122 self.handler
2123 .set_selected_text_range(range_utf16, window, cx)
2124 })
2125 .ok();
2126 }
2127
2128 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2130 self.cx
2131 .update(|window, cx| self.handler.element_bounds(window, cx))
2132 .ok()
2133 .flatten()
2134 }
2135
2136 pub fn text_length_utf16(&mut self) -> Option<usize> {
2138 self.cx
2139 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2140 .ok()
2141 .flatten()
2142 }
2143
2144 #[allow(dead_code)]
2145 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2146 self.handler.accepts_text_input(window, cx)
2147 }
2148
2149 #[allow(dead_code)]
2150 pub fn query_accepts_text_input(&mut self) -> bool {
2151 self.cx
2152 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2153 .unwrap_or(true)
2154 }
2155
2156 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2162 self.cx
2163 .update(|window, cx| {
2164 !window.has_pending_keystrokes()
2166 && self.handler.prefers_ime_for_printable_keys(window, cx)
2167 })
2168 .unwrap_or(false)
2169 }
2170
2171 pub fn text_input_configuration(
2173 &mut self,
2174 window: &mut Window,
2175 cx: &mut App,
2176 ) -> TextInputConfiguration {
2177 self.handler.text_input_configuration(window, cx)
2178 }
2179
2180 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2182 self.cx
2183 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2184 .ok()
2185 .flatten()
2186 }
2187}
2188
2189#[derive(Debug)]
2192pub struct UTF16Selection {
2193 pub range: Range<usize>,
2196 pub reversed: bool,
2199}
2200
2201pub trait InputHandler: 'static {
2206 fn selected_text_range(
2211 &mut self,
2212 ignore_disabled_input: bool,
2213 window: &mut Window,
2214 cx: &mut App,
2215 ) -> Option<UTF16Selection>;
2216
2217 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2222
2223 fn text_for_range(
2228 &mut self,
2229 range_utf16: Range<usize>,
2230 adjusted_range: &mut Option<Range<usize>>,
2231 window: &mut Window,
2232 cx: &mut App,
2233 ) -> Option<String>;
2234
2235 fn replace_text_in_range(
2240 &mut self,
2241 replacement_range: Option<Range<usize>>,
2242 text: &str,
2243 window: &mut Window,
2244 cx: &mut App,
2245 );
2246
2247 fn replace_and_mark_text_in_range(
2254 &mut self,
2255 range_utf16: Option<Range<usize>>,
2256 new_text: &str,
2257 new_selected_range: Option<Range<usize>>,
2258 window: &mut Window,
2259 cx: &mut App,
2260 );
2261
2262 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2265
2266 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2273 if let Some(text) = item.text() {
2274 self.replace_text_in_range(None, &text, window, cx);
2275 }
2276 }
2277
2278 fn bounds_for_range(
2283 &mut self,
2284 range_utf16: Range<usize>,
2285 window: &mut Window,
2286 cx: &mut App,
2287 ) -> Option<Bounds<Pixels>>;
2288
2289 fn character_index_for_point(
2293 &mut self,
2294 point: Point<Pixels>,
2295 window: &mut Window,
2296 cx: &mut App,
2297 ) -> Option<usize>;
2298
2299 fn set_selected_text_range(
2309 &mut self,
2310 _range_utf16: Range<usize>,
2311 _window: &mut Window,
2312 _cx: &mut App,
2313 ) {
2314 }
2315
2316 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2323 None
2324 }
2325
2326 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2328 None
2329 }
2330
2331 #[allow(dead_code)]
2336 fn apple_press_and_hold_enabled(&mut self) -> bool {
2337 true
2338 }
2339
2340 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2342 true
2343 }
2344
2345 fn text_input_editable_range(
2356 &mut self,
2357 _window: &mut Window,
2358 _cx: &mut App,
2359 ) -> Option<Range<usize>> {
2360 None
2361 }
2362
2363 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2372 false
2373 }
2374
2375 fn text_input_configuration(
2381 &mut self,
2382 _window: &mut Window,
2383 _cx: &mut App,
2384 ) -> TextInputConfiguration {
2385 TextInputConfiguration::default()
2386 }
2387}
2388
2389#[derive(Clone, Debug, Default, PartialEq, Eq)]
2399pub struct TextInputConfiguration {
2400 pub autocorrect: bool,
2402 pub autocapitalize: Autocapitalize,
2404 pub suggestions: bool,
2406 pub input_action: TextInputAction,
2408}
2409
2410#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2412pub enum Autocapitalize {
2413 #[default]
2415 None,
2416 Words,
2418 Sentences,
2420 Characters,
2422}
2423
2424#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2434pub enum TextInputAction {
2435 #[default]
2437 Unspecified,
2438 Enter,
2440 Done,
2442 Go,
2444 Next,
2446 Previous,
2448 Search,
2450 Send,
2452}
2453
2454#[derive(Debug)]
2456pub struct WindowOptions {
2457 pub window_bounds: Option<WindowBounds>,
2461
2462 pub titlebar: Option<TitlebarOptions>,
2464
2465 pub focus: bool,
2467
2468 pub show: bool,
2470
2471 pub kind: WindowKind,
2473
2474 pub is_movable: bool,
2478
2479 pub app_owns_titlebar_drag: bool,
2491
2492 pub inactive_frame_interval: Option<Duration>,
2496
2497 pub is_resizable: bool,
2499
2500 pub is_minimizable: bool,
2502
2503 pub display_id: Option<DisplayId>,
2506
2507 pub window_background: WindowBackgroundAppearance,
2509
2510 pub app_id: Option<String>,
2512
2513 pub window_min_size: Option<Size<Pixels>>,
2515
2516 pub window_decorations: Option<WindowDecorations>,
2519
2520 pub icon: Option<Arc<image::RgbaImage>>,
2522
2523 pub tabbing_identifier: Option<String>,
2525}
2526
2527#[derive(Debug)]
2529#[cfg_attr(
2530 all(
2531 any(target_os = "linux", target_os = "freebsd"),
2532 not(any(feature = "x11", feature = "wayland"))
2533 ),
2534 allow(dead_code)
2535)]
2536#[allow(missing_docs)]
2537pub struct WindowParams {
2538 pub bounds: Bounds<Pixels>,
2539
2540 #[cfg_attr(feature = "wayland", allow(dead_code))]
2542 pub titlebar: Option<TitlebarOptions>,
2543
2544 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2546 pub kind: WindowKind,
2547
2548 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2550 pub is_movable: bool,
2551
2552 #[cfg_attr(
2554 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2555 allow(dead_code)
2556 )]
2557 pub app_owns_titlebar_drag: bool,
2558
2559 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2561 pub is_resizable: bool,
2562
2563 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2565 pub is_minimizable: bool,
2566
2567 #[cfg_attr(
2568 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2569 allow(dead_code)
2570 )]
2571 pub focus: bool,
2572
2573 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2574 pub show: bool,
2575
2576 #[cfg_attr(feature = "wayland", allow(dead_code))]
2578 pub icon: Option<Arc<image::RgbaImage>>,
2579
2580 #[cfg_attr(feature = "wayland", allow(dead_code))]
2581 pub display_id: Option<DisplayId>,
2582
2583 #[cfg_attr(feature = "wayland", allow(dead_code))]
2584 pub app_id: Option<String>,
2585
2586 pub window_min_size: Option<Size<Pixels>>,
2587
2588 #[cfg(target_os = "macos")]
2589 pub tabbing_identifier: Option<String>,
2590}
2591
2592#[derive(Debug, Copy, Clone, PartialEq)]
2594pub enum WindowBounds {
2595 Windowed(Bounds<Pixels>),
2597 Maximized(Bounds<Pixels>),
2600 Fullscreen(Bounds<Pixels>),
2603}
2604
2605impl Default for WindowBounds {
2606 fn default() -> Self {
2607 WindowBounds::Windowed(Bounds::default())
2608 }
2609}
2610
2611impl WindowBounds {
2612 pub fn get_bounds(&self) -> Bounds<Pixels> {
2614 match self {
2615 WindowBounds::Windowed(bounds) => *bounds,
2616 WindowBounds::Maximized(bounds) => *bounds,
2617 WindowBounds::Fullscreen(bounds) => *bounds,
2618 }
2619 }
2620
2621 pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
2623 WindowBounds::Windowed(Bounds::centered(None, size, cx))
2624 }
2625}
2626
2627impl Default for WindowOptions {
2628 fn default() -> Self {
2629 Self {
2630 window_bounds: None,
2631 titlebar: Some(TitlebarOptions {
2632 title: Default::default(),
2633 appears_transparent: Default::default(),
2634 traffic_light_position: Default::default(),
2635 }),
2636 focus: true,
2637 show: true,
2638 kind: WindowKind::Normal,
2639 is_movable: true,
2640 app_owns_titlebar_drag: false,
2641 inactive_frame_interval: Some(Duration::from_micros(33_333)),
2642 is_resizable: true,
2643 is_minimizable: true,
2644 display_id: None,
2645 window_background: WindowBackgroundAppearance::default(),
2646 icon: None,
2647 app_id: None,
2648 window_min_size: None,
2649 window_decorations: None,
2650 tabbing_identifier: None,
2651 }
2652 }
2653}
2654
2655#[derive(Debug, Default)]
2657pub struct TitlebarOptions {
2658 pub title: Option<SharedString>,
2660
2661 pub appears_transparent: bool,
2664
2665 pub traffic_light_position: Option<Point<Pixels>>,
2667}
2668
2669#[derive(Clone, Debug, PartialEq, Eq)]
2671pub enum WindowKind {
2672 Normal,
2674
2675 PopUp,
2678
2679 AnchoredPopup(popup::PopupOptions),
2686
2687 Floating,
2689
2690 #[cfg(all(target_os = "linux", feature = "wayland"))]
2693 LayerShell(layer_shell::LayerShellOptions),
2694
2695 Dialog,
2698}
2699
2700#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2705pub enum WindowAppearance {
2706 #[default]
2710 Light,
2711
2712 VibrantLight,
2716
2717 Dark,
2721
2722 VibrantDark,
2726}
2727
2728#[derive(Copy, Clone, Debug, Default, PartialEq)]
2731pub enum WindowBackgroundAppearance {
2732 #[default]
2740 Opaque,
2741 Transparent,
2743 Blurred,
2747 MicaBackdrop,
2749 MicaAltBackdrop,
2751}
2752
2753#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2755pub enum TextRenderingMode {
2756 #[default]
2758 PlatformDefault,
2759 Subpixel,
2761 Grayscale,
2763}
2764
2765#[derive(Clone, Debug)]
2767pub struct PathPromptOptions {
2768 pub files: bool,
2770 pub directories: bool,
2772 pub multiple: bool,
2774 pub prompt: Option<SharedString>,
2776}
2777
2778#[derive(Copy, Clone, Debug, PartialEq)]
2780pub enum PromptLevel {
2781 Info,
2783
2784 Warning,
2786
2787 Critical,
2789}
2790
2791#[derive(Clone, Debug, PartialEq)]
2793pub enum PromptButton {
2794 Ok(SharedString),
2796 Cancel(SharedString),
2798 Other(SharedString),
2800}
2801
2802impl PromptButton {
2803 pub fn new(label: impl Into<SharedString>) -> Self {
2805 PromptButton::Other(label.into())
2806 }
2807
2808 pub fn ok(label: impl Into<SharedString>) -> Self {
2810 PromptButton::Ok(label.into())
2811 }
2812
2813 pub fn cancel(label: impl Into<SharedString>) -> Self {
2815 PromptButton::Cancel(label.into())
2816 }
2817
2818 #[allow(dead_code)]
2820 pub fn is_cancel(&self) -> bool {
2821 matches!(self, PromptButton::Cancel(_))
2822 }
2823
2824 pub fn label(&self) -> &SharedString {
2826 match self {
2827 PromptButton::Ok(label) => label,
2828 PromptButton::Cancel(label) => label,
2829 PromptButton::Other(label) => label,
2830 }
2831 }
2832}
2833
2834impl From<&str> for PromptButton {
2835 fn from(value: &str) -> Self {
2836 match value.to_lowercase().as_str() {
2837 "ok" => PromptButton::Ok("OK".into()),
2838 "cancel" => PromptButton::Cancel("Cancel".into()),
2839 _ => PromptButton::Other(SharedString::from(value.to_owned())),
2840 }
2841 }
2842}
2843
2844#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2846pub enum CursorStyle {
2847 #[default]
2849 Arrow,
2850
2851 IBeam,
2854
2855 Crosshair,
2858
2859 ClosedHand,
2862
2863 OpenHand,
2866
2867 PointingHand,
2870
2871 ResizeLeft,
2874
2875 ResizeRight,
2878
2879 ResizeLeftRight,
2882
2883 ResizeUp,
2886
2887 ResizeDown,
2890
2891 ResizeUpDown,
2894
2895 ResizeUpLeftDownRight,
2898
2899 ResizeUpRightDownLeft,
2902
2903 ResizeColumn,
2906
2907 ResizeRow,
2910
2911 IBeamCursorForVerticalLayout,
2914
2915 OperationNotAllowed,
2918
2919 DragLink,
2922
2923 DragCopy,
2926
2927 ContextualMenu,
2930}
2931
2932#[derive(Clone, Debug, Eq, PartialEq)]
2934pub struct ClipboardItem {
2935 pub entries: Vec<ClipboardEntry>,
2937}
2938
2939#[derive(Clone, Debug, PartialEq, Eq)]
2944pub enum ClipboardReadError {
2945 Unavailable,
2949 Denied(String),
2952 UnsupportedContent,
2955}
2956
2957impl std::fmt::Display for ClipboardReadError {
2958 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2959 match self {
2960 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
2961 Self::Denied(message) => {
2962 write!(formatter, "clipboard access was denied: {message}")
2963 }
2964 Self::UnsupportedContent => {
2965 formatter.write_str("the clipboard contents are unsupported")
2966 }
2967 }
2968 }
2969}
2970
2971impl std::error::Error for ClipboardReadError {}
2972
2973#[derive(Clone, Debug, Eq, PartialEq)]
2975pub enum ClipboardEntry {
2976 String(ClipboardString),
2978 Image(Image),
2980 ExternalPaths(crate::ExternalPaths),
2982}
2983
2984impl ClipboardItem {
2985 pub fn new_string(text: String) -> Self {
2987 Self {
2988 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
2989 }
2990 }
2991
2992 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
2994 Self {
2995 entries: vec![ClipboardEntry::String(ClipboardString {
2996 text,
2997 metadata: Some(metadata),
2998 })],
2999 }
3000 }
3001
3002 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3004 Self {
3005 entries: vec![ClipboardEntry::String(
3006 ClipboardString::new(text).with_json_metadata(metadata),
3007 )],
3008 }
3009 }
3010
3011 pub fn new_image(image: &Image) -> Self {
3013 Self {
3014 entries: vec![ClipboardEntry::Image(image.clone())],
3015 }
3016 }
3017
3018 pub fn text(&self) -> Option<String> {
3021 let mut answer = String::new();
3022
3023 for entry in self.entries.iter() {
3024 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3025 answer.push_str(text);
3026 }
3027 }
3028
3029 if answer.is_empty() {
3030 for entry in self.entries.iter() {
3031 if let ClipboardEntry::ExternalPaths(paths) = entry {
3032 for path in &paths.0 {
3033 use std::fmt::Write as _;
3034 _ = write!(answer, "{}", path.display());
3035 }
3036 }
3037 }
3038 }
3039
3040 if !answer.is_empty() {
3041 Some(answer)
3042 } else {
3043 None
3044 }
3045 }
3046
3047 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3049 pub fn metadata(&self) -> Option<&String> {
3050 match self.entries().first() {
3051 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3052 clipboard_string.metadata.as_ref()
3053 }
3054 _ => None,
3055 }
3056 }
3057
3058 pub fn entries(&self) -> &[ClipboardEntry] {
3060 &self.entries
3061 }
3062
3063 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3065 self.entries.into_iter()
3066 }
3067}
3068
3069impl From<ClipboardString> for ClipboardEntry {
3070 fn from(value: ClipboardString) -> Self {
3071 Self::String(value)
3072 }
3073}
3074
3075impl From<String> for ClipboardEntry {
3076 fn from(value: String) -> Self {
3077 Self::from(ClipboardString::from(value))
3078 }
3079}
3080
3081impl From<Image> for ClipboardEntry {
3082 fn from(value: Image) -> Self {
3083 Self::Image(value)
3084 }
3085}
3086
3087impl From<ClipboardEntry> for ClipboardItem {
3088 fn from(value: ClipboardEntry) -> Self {
3089 Self {
3090 entries: vec![value],
3091 }
3092 }
3093}
3094
3095impl From<String> for ClipboardItem {
3096 fn from(value: String) -> Self {
3097 Self::from(ClipboardEntry::from(value))
3098 }
3099}
3100
3101impl From<Image> for ClipboardItem {
3102 fn from(value: Image) -> Self {
3103 Self::from(ClipboardEntry::from(value))
3104 }
3105}
3106
3107#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3109pub enum ImageFormat {
3110 Png,
3115 Jpeg,
3117 Webp,
3119 Gif,
3121 Svg,
3123 Bmp,
3125 Tiff,
3127 Ico,
3129 Pnm,
3131}
3132
3133impl ImageFormat {
3134 pub const fn mime_type(self) -> &'static str {
3136 match self {
3137 ImageFormat::Png => "image/png",
3138 ImageFormat::Jpeg => "image/jpeg",
3139 ImageFormat::Webp => "image/webp",
3140 ImageFormat::Gif => "image/gif",
3141 ImageFormat::Svg => "image/svg+xml",
3142 ImageFormat::Bmp => "image/bmp",
3143 ImageFormat::Tiff => "image/tiff",
3144 ImageFormat::Ico => "image/ico",
3145 ImageFormat::Pnm => "image/x-portable-anymap",
3146 }
3147 }
3148
3149 pub const fn extension(self) -> &'static str {
3151 match self {
3152 ImageFormat::Png => "png",
3153 ImageFormat::Jpeg => "jpg",
3154 ImageFormat::Webp => "webp",
3155 ImageFormat::Gif => "gif",
3156 ImageFormat::Svg => "svg",
3157 ImageFormat::Bmp => "bmp",
3158 ImageFormat::Tiff => "tiff",
3159 ImageFormat::Ico => "ico",
3160 ImageFormat::Pnm => "pnm",
3161 }
3162 }
3163
3164 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3166 use strum::IntoEnumIterator;
3167 Self::iter()
3168 .find(|format| format.mime_type() == mime_type)
3169 .or_else(|| Self::from_mime_type_alias(mime_type))
3170 }
3171
3172 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3176 match mime_type {
3177 "image/jpg" => Some(Self::Jpeg),
3178 "image/tif" => Some(Self::Tiff),
3179 _ => None,
3180 }
3181 }
3182}
3183
3184#[derive(Clone, Debug, PartialEq, Eq)]
3186pub struct Image {
3187 pub format: ImageFormat,
3189 pub bytes: Vec<u8>,
3191 pub id: u64,
3193}
3194
3195pub(crate) fn decode_static_image(
3196 bytes: &[u8],
3197 format: image::ImageFormat,
3198) -> Result<SmallVec<[Frame; 1]>> {
3199 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3200 .into_decoder()
3201 .context("creating image decoder")?;
3202 decode_static_image_from_decoder(decoder)
3203}
3204
3205pub(crate) fn decode_static_image_from_decoder(
3206 mut decoder: impl image::ImageDecoder,
3207) -> Result<SmallVec<[Frame; 1]>> {
3208 let orientation = decoder
3209 .orientation()
3210 .context("reading decoder's orientation")?;
3211 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3212 image.apply_orientation(orientation);
3213
3214 let mut data = image.into_rgba8();
3215 for pixel in data.chunks_exact_mut(4) {
3216 pixel.swap(0, 2);
3217 }
3218
3219 Ok(SmallVec::from_elem(Frame::new(data), 1))
3220}
3221
3222impl Hash for Image {
3223 fn hash<H: Hasher>(&self, state: &mut H) {
3224 state.write_u64(self.id);
3225 }
3226}
3227
3228impl Image {
3229 pub fn empty() -> Self {
3231 Self::from_bytes(ImageFormat::Png, Vec::new())
3232 }
3233
3234 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3236 Self {
3237 id: hash(&bytes),
3238 format,
3239 bytes,
3240 }
3241 }
3242
3243 pub fn id(&self) -> u64 {
3245 self.id
3246 }
3247
3248 pub fn use_render_image(
3250 self: Arc<Self>,
3251 window: &mut Window,
3252 cx: &mut App,
3253 ) -> Option<Arc<RenderImage>> {
3254 ImageSource::Image(self)
3255 .use_data(None, window, cx)
3256 .and_then(|result| result.ok())
3257 }
3258
3259 pub fn get_render_image(
3261 self: Arc<Self>,
3262 window: &mut Window,
3263 cx: &mut App,
3264 ) -> Option<Arc<RenderImage>> {
3265 ImageSource::Image(self)
3266 .get_data(None, window, cx)
3267 .and_then(|result| result.ok())
3268 }
3269
3270 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3272 ImageSource::Image(self).remove_asset(cx);
3273 }
3274
3275 #[cfg(any(test, feature = "test-support"))]
3278 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3279 ImageSource::Image(self.clone()).is_asset_cached(cx)
3280 }
3281
3282 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3284 let frames = match self.format {
3285 ImageFormat::Gif => {
3286 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
3287 let mut frames = SmallVec::new();
3288
3289 for frame in decoder.into_frames() {
3290 match frame {
3291 Ok(mut frame) => {
3292 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3294 pixel.swap(0, 2);
3295 }
3296 frames.push(frame);
3297 }
3298 Err(err) => {
3299 log::debug!("Skipping GIF frame due to decode error: {err}");
3300 }
3301 }
3302 }
3303
3304 if frames.is_empty() {
3305 anyhow::bail!("GIF could not be decoded: all frames failed");
3306 }
3307
3308 frames
3309 }
3310 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3311 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3312 ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
3313 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3314 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3315 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3316 ImageFormat::Svg => {
3317 return svg_renderer
3318 .render_single_frame(&self.bytes, 1.0)
3319 .map_err(Into::into);
3320 }
3321 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3322 };
3323
3324 Ok(Arc::new(RenderImage::new(frames)))
3325 }
3326
3327 pub fn format(&self) -> ImageFormat {
3329 self.format
3330 }
3331
3332 pub fn bytes(&self) -> &[u8] {
3334 self.bytes.as_slice()
3335 }
3336}
3337
3338#[derive(Clone, Debug, Eq, PartialEq)]
3340pub struct ClipboardString {
3341 pub text: String,
3343 pub metadata: Option<String>,
3345}
3346
3347impl ClipboardString {
3348 pub fn new(text: String) -> Self {
3350 Self {
3351 text,
3352 metadata: None,
3353 }
3354 }
3355
3356 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3359 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3360 self
3361 }
3362
3363 pub fn text(&self) -> &String {
3365 &self.text
3366 }
3367
3368 pub fn into_text(self) -> String {
3370 self.text
3371 }
3372
3373 pub fn metadata_json<T>(&self) -> Option<T>
3375 where
3376 T: for<'a> Deserialize<'a>,
3377 {
3378 self.metadata
3379 .as_ref()
3380 .and_then(|m| serde_json::from_str(m).ok())
3381 }
3382
3383 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3384 pub fn text_hash(text: &str) -> u64 {
3386 let mut hasher = SeaHasher::new();
3387 text.hash(&mut hasher);
3388 hasher.finish()
3389 }
3390}
3391
3392impl From<String> for ClipboardString {
3393 fn from(value: String) -> Self {
3394 Self {
3395 text: value,
3396 metadata: None,
3397 }
3398 }
3399}
3400
3401#[cfg(test)]
3402mod image_tests {
3403 use super::*;
3404 use std::sync::Arc;
3405
3406 #[test]
3407 fn test_image_to_image_data_applies_exif_orientation() {
3408 let image = Image::from_bytes(
3409 ImageFormat::Jpeg,
3410 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3411 );
3412
3413 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3414
3415 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3416
3417 let bytes = render_image.as_bytes(0).unwrap();
3418 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3419 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3420 }
3421
3422 #[test]
3423 fn test_svg_image_to_image_data_converts_to_bgra() {
3424 let image = Image::from_bytes(
3425 ImageFormat::Svg,
3426 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3427<rect width="1" height="1" fill="#38BDF8"/>
3428</svg>"##
3429 .to_vec(),
3430 );
3431
3432 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3433 let bytes = render_image.as_bytes(0).unwrap();
3434
3435 for pixel in bytes.chunks_exact(4) {
3436 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3437 }
3438 }
3439}
3440
3441#[cfg(test)]
3442mod atlas_tests {
3443 use super::*;
3444
3445 const TILE_SIZE: Size<DevicePixels> = Size {
3446 width: DevicePixels(1),
3447 height: DevicePixels(1),
3448 };
3449
3450 #[derive(Default)]
3451 struct RecordingAtlasBackend {
3452 insert_calls: u32,
3453 fail_next_insert: bool,
3454 removed_tiles: Vec<AtlasTile>,
3455 }
3456
3457 impl AtlasBackend for RecordingAtlasBackend {
3458 fn insert(
3459 &mut self,
3460 kind: AtlasTextureKind,
3461 size: Size<DevicePixels>,
3462 _bytes: &[u8],
3463 ) -> Result<AtlasTile> {
3464 self.insert_calls += 1;
3465 if std::mem::take(&mut self.fail_next_insert) {
3466 anyhow::bail!("backend failed");
3467 }
3468 Ok(AtlasTile {
3469 texture_id: AtlasTextureId { index: 0, kind },
3470 tile_id: TileId(self.insert_calls),
3471 padding: 0,
3472 bounds: Bounds {
3473 origin: Point::default(),
3474 size,
3475 },
3476 })
3477 }
3478
3479 fn remove(&mut self, tile: AtlasTile) {
3480 self.removed_tiles.push(tile);
3481 }
3482 }
3483
3484 fn image_key(image_id: usize) -> AtlasKey {
3485 AtlasKey::Image(RenderImageParams {
3486 image_id: crate::ImageId(image_id),
3487 frame_index: 0,
3488 })
3489 }
3490
3491 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3492 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3493 }
3494
3495 #[test]
3496 fn only_successful_inserts_are_cached() -> Result<()> {
3497 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3498 let key = image_key(1);
3499
3500 assert_eq!(
3501 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3502 None
3503 );
3504 state
3505 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3506 .expect_err("builder error should propagate");
3507 assert!(!state.contains(&key));
3508 assert_eq!(state.backend.insert_calls, 0);
3509
3510 state.backend.fail_next_insert = true;
3511 state
3512 .get_or_insert_with(key.clone(), &mut build_tile)
3513 .expect_err("backend error should propagate");
3514 assert!(!state.contains(&key));
3515 assert_eq!(state.backend.insert_calls, 1);
3516
3517 let tile = state
3518 .get_or_insert_with(key.clone(), &mut build_tile)?
3519 .context("builder should produce a tile")?;
3520 assert_eq!(tile.texture_id.kind, key.texture_kind());
3521 assert_eq!(
3522 state.get_or_insert_with(key.clone(), &mut || {
3523 anyhow::bail!("cache hit must not call the builder")
3524 })?,
3525 Some(tile)
3526 );
3527 assert!(state.contains(&key));
3528 assert_eq!(state.backend.insert_calls, 2);
3529 Ok(())
3530 }
3531
3532 #[test]
3533 fn remove_and_clear_invalidate_keys() -> Result<()> {
3534 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3535 let key = image_key(1);
3536 let other_key = image_key(2);
3537 let tile = state
3538 .get_or_insert_with(key.clone(), &mut build_tile)?
3539 .context("builder should produce a tile")?;
3540 state
3541 .get_or_insert_with(other_key.clone(), &mut build_tile)?
3542 .context("builder should produce another tile")?;
3543
3544 state.remove(&key);
3545 state.remove(&key);
3546 assert!(!state.contains(&key));
3547 assert!(state.contains(&other_key));
3548 assert_eq!(state.backend.removed_tiles, vec![tile]);
3549
3550 let mut reset_calls = 0;
3551 state.clear(|_| reset_calls += 1);
3552 assert_eq!(reset_calls, 1);
3553 assert!(!state.contains(&other_key));
3554 assert_eq!(state.backend.removed_tiles, vec![tile]);
3555 Ok(())
3556 }
3557}
3558
3559#[cfg(test)]
3560mod frame_signal_tests {
3561 use super::*;
3562
3563 #[cfg(feature = "profiler")]
3564 #[test]
3565 fn coalesced_signals_retain_the_earliest_until_drained() {
3566 for (first_source, later_source) in [
3567 (
3568 FrameRequestSource::NativeCallback,
3569 FrameRequestSource::LocalSchedule,
3570 ),
3571 (
3572 FrameRequestSource::LocalSchedule,
3573 FrameRequestSource::NativeCallback,
3574 ),
3575 ] {
3576 let signal = PlatformFrameSignal::new();
3577 let first =
3578 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3579 assert_eq!(signal.take(), None);
3580 signal.record(first + Duration::from_millis(16), later_source);
3581 signal.record(first, first_source);
3582 signal.record(first + Duration::from_millis(32), later_source);
3583 assert_eq!(signal.take(), Some((first, first_source)));
3584 assert_eq!(signal.take(), None);
3585 let next = first + Duration::from_millis(48);
3586 signal.record(next, later_source);
3587 assert_eq!(signal.take(), Some((next, later_source)));
3588 }
3589 }
3590
3591 #[cfg(not(feature = "profiler"))]
3592 #[test]
3593 fn disabled_profiling_does_not_capture_or_store_timestamps() {
3594 let captured = PlatformFrameSignal::capture(|| {
3595 panic!("profiler-disabled builds must not evaluate the capture closure");
3596 });
3597 assert_eq!(captured, None);
3598 let signal = PlatformFrameSignal::new();
3599 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3600 assert_eq!(signal.take(), None);
3601 }
3602}
3603
3604#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3605mod tests {
3606 use super::*;
3607 use std::collections::HashSet;
3608
3609 #[test]
3610 fn test_window_button_layout_parse_standard() {
3611 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3612 assert_eq!(
3613 layout.left,
3614 [
3615 Some(WindowButton::Close),
3616 Some(WindowButton::Minimize),
3617 None
3618 ]
3619 );
3620 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3621 }
3622
3623 #[test]
3624 fn test_window_button_layout_parse_right_only() {
3625 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3626 assert_eq!(layout.left, [None, None, None]);
3627 assert_eq!(
3628 layout.right,
3629 [
3630 Some(WindowButton::Minimize),
3631 Some(WindowButton::Maximize),
3632 Some(WindowButton::Close)
3633 ]
3634 );
3635 }
3636
3637 #[test]
3638 fn test_window_button_layout_parse_left_only() {
3639 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3640 assert_eq!(
3641 layout.left,
3642 [
3643 Some(WindowButton::Close),
3644 Some(WindowButton::Minimize),
3645 Some(WindowButton::Maximize)
3646 ]
3647 );
3648 assert_eq!(layout.right, [None, None, None]);
3649 }
3650
3651 #[test]
3652 fn test_window_button_layout_parse_with_whitespace() {
3653 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3654 assert_eq!(
3655 layout.left,
3656 [
3657 Some(WindowButton::Close),
3658 Some(WindowButton::Minimize),
3659 None
3660 ]
3661 );
3662 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3663 }
3664
3665 #[test]
3666 fn test_window_button_layout_parse_empty() {
3667 let layout = WindowButtonLayout::parse("").unwrap();
3668 assert_eq!(layout.left, [None, None, None]);
3669 assert_eq!(layout.right, [None, None, None]);
3670 }
3671
3672 #[test]
3673 fn test_window_button_layout_parse_intentionally_empty() {
3674 let layout = WindowButtonLayout::parse(":").unwrap();
3675 assert_eq!(layout.left, [None, None, None]);
3676 assert_eq!(layout.right, [None, None, None]);
3677 }
3678
3679 #[test]
3680 fn test_window_button_layout_parse_invalid_buttons() {
3681 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
3682 assert_eq!(
3683 layout.left,
3684 [
3685 Some(WindowButton::Close),
3686 Some(WindowButton::Minimize),
3687 None
3688 ]
3689 );
3690 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3691 }
3692
3693 #[test]
3694 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
3695 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
3696 assert_eq!(
3697 layout.right,
3698 [
3699 Some(WindowButton::Close),
3700 Some(WindowButton::Minimize),
3701 None
3702 ]
3703 );
3704 assert_eq!(layout.format(), ":close,minimize");
3705 }
3706
3707 #[test]
3708 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
3709 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
3710 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3711 assert_eq!(
3712 layout.right,
3713 [
3714 Some(WindowButton::Maximize),
3715 Some(WindowButton::Minimize),
3716 None
3717 ]
3718 );
3719
3720 let button_ids: Vec<_> = layout
3721 .left
3722 .iter()
3723 .chain(layout.right.iter())
3724 .flatten()
3725 .map(WindowButton::id)
3726 .collect();
3727 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
3728 assert_eq!(unique_button_ids.len(), button_ids.len());
3729 assert_eq!(layout.format(), "close:maximize,minimize");
3730 }
3731
3732 #[test]
3733 fn test_window_button_layout_parse_gnome_style() {
3734 let layout = WindowButtonLayout::parse("close").unwrap();
3735 assert_eq!(layout.left, [None, None, None]);
3736 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
3737 }
3738
3739 #[test]
3740 fn test_window_button_layout_parse_elementary_style() {
3741 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
3742 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3743 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3744 }
3745
3746 #[test]
3747 fn test_window_button_layout_round_trip() {
3748 let cases = [
3749 "close:minimize,maximize",
3750 "minimize,maximize,close:",
3751 ":close",
3752 "close:",
3753 "close:maximize",
3754 ":",
3755 ];
3756
3757 for case in cases {
3758 let layout = WindowButtonLayout::parse(case).unwrap();
3759 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
3760 }
3761 }
3762
3763 #[test]
3764 fn test_window_button_layout_linux_default() {
3765 let layout = WindowButtonLayout::linux_default();
3766 assert_eq!(layout.left, [None, None, None]);
3767 assert_eq!(
3768 layout.right,
3769 [
3770 Some(WindowButton::Minimize),
3771 Some(WindowButton::Maximize),
3772 Some(WindowButton::Close)
3773 ]
3774 );
3775
3776 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
3777 assert_eq!(round_tripped, layout);
3778 }
3779
3780 #[test]
3781 fn test_window_button_layout_parse_all_invalid() {
3782 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
3783 }
3784}