1mod app_menu;
2mod keyboard;
3mod keystroke;
4mod platform_info;
5
6#[cfg(all(target_os = "linux", feature = "wayland"))]
7#[expect(missing_docs)]
8pub mod layer_shell;
9
10pub mod popup;
12
13#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
14mod threaded_dispatcher;
15
16#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
17mod test;
18
19#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
20mod visual_test;
21
22#[cfg(all(
23 feature = "screen-capture",
24 any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
25))]
26pub mod scap_screen_capture;
27
28#[cfg(all(
29 any(target_os = "windows", target_os = "linux"),
30 feature = "screen-capture"
31))]
32pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
33#[cfg(not(feature = "screen-capture"))]
34pub(crate) type PlatformScreenCaptureFrame = ();
35#[cfg(all(target_os = "macos", feature = "screen-capture"))]
36pub(crate) type PlatformScreenCaptureFrame =
37 objc2_core_foundation::CFRetained<objc2_core_video::CVImageBuffer>;
38
39use crate::{
40 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds, Corners,
41 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
42 FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, 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, webp::WebPDecoder};
57use image::{DynamicImage, Frame, Rgba};
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 current_desktop: Option<OsString>,
239 pub activation_token: Option<String>,
245}
246
247#[cfg(target_os = "windows")]
253#[derive(Clone, Debug, Default)]
254pub struct GraphicalEnvironment {
255 pub session_id: Option<u32>,
258}
259
260#[cfg(target_os = "windows")]
261impl GraphicalEnvironment {
262 pub fn detect() -> Self {
264 let mut session_id = 0;
265 let result = unsafe {
267 windows::Win32::System::RemoteDesktop::ProcessIdToSessionId(
268 windows::Win32::System::Threading::GetCurrentProcessId(),
269 &mut session_id,
270 )
271 };
272 Self {
273 session_id: result.is_ok().then_some(session_id),
274 }
275 }
276
277 pub fn apply_to(&self, _command: &mut std::process::Command) {}
280
281 pub fn desktop_environment(&self) -> Option<String> {
283 None
284 }
285}
286
287#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
289#[derive(Clone, Debug, Default)]
290pub struct GraphicalEnvironment;
291
292#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
293impl GraphicalEnvironment {
294 pub fn detect() -> Self {
296 Self
297 }
298
299 pub fn apply_to(&self, _command: &mut std::process::Command) {}
301
302 pub fn desktop_environment(&self) -> Option<String> {
304 None
305 }
306}
307
308#[derive(Clone, Debug)]
310pub enum WindowingRequest {
311 Headless,
313 Windowed(GraphicalEnvironment),
315}
316
317#[cfg(any(target_os = "linux", target_os = "freebsd"))]
318impl GraphicalEnvironment {
319 pub fn detect() -> Self {
324 Self {
325 wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
326 x11_display: std::env::var_os("DISPLAY"),
327 xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
328 current_desktop: std::env::var_os("XDG_CURRENT_DESKTOP"),
329 activation_token: None,
330 }
331 }
332
333 pub fn apply_to(&self, command: &mut std::process::Command) {
337 for (name, value) in [
338 ("WAYLAND_DISPLAY", &self.wayland_display),
339 ("DISPLAY", &self.x11_display),
340 ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
341 ] {
342 match value {
343 Some(value) => command.env(name, value),
344 None => command.env_remove(name),
345 };
346 }
347 }
348
349 pub fn desktop_environment(&self) -> Option<String> {
354 self.current_desktop
355 .as_ref()
356 .and_then(|desktop| desktop.to_str())
357 .filter(|desktop| !desktop.is_empty())
358 .map(str::to_owned)
359 }
360
361 pub fn guess_compositor(&self) -> &'static str {
365 let is_set =
366 |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
367 if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
368 "Wayland"
369 } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
370 "X11"
371 } else {
372 "headless"
373 }
374 }
375}
376
377#[cfg(any(target_os = "linux", target_os = "freebsd"))]
378bitflags::bitflags! {
379 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
381 pub struct WindowingModes: u8 {
382 const WAYLAND = 1 << 0;
384 const X11 = 1 << 1;
386 const HEADLESS = 1 << 2;
388 }
389}
390
391pub use platform_info::{OperatingSystem, PlatformInfo, PlatformTarget};
392
393#[expect(missing_docs)]
394pub trait Platform: 'static {
395 fn platform_info(&self) -> PlatformInfo;
397
398 fn background_executor(&self) -> BackgroundExecutor;
399 fn foreground_executor(&self) -> ForegroundExecutor;
400 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
401
402 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
403 fn quit(&self);
404 fn set_initial_windowing(&self, _request: WindowingRequest) {}
409 fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
410 Task::ready(Err(anyhow::anyhow!(
411 "this platform cannot switch between headless and windowed modes"
412 )))
413 }
414 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
415 fn activate(&self, ignoring_other_apps: bool);
416 fn set_activation_policy(&self, _policy: ActivationPolicy) {}
418 fn hide(&self);
419 fn hide_other_apps(&self);
420 fn unhide_other_apps(&self);
421
422 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
423 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
424 fn on_displays_changed(&self, callback: Box<dyn FnMut()>);
429 fn active_window(&self) -> Option<AnyWindowHandle>;
430 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
431 None
432 }
433
434 fn is_screen_capture_supported(&self) -> bool {
435 false
436 }
437
438 fn screen_capture_sources(
439 &self,
440 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
441 let (sources_tx, sources_rx) = oneshot::channel();
442 sources_tx
443 .send(Err(anyhow::anyhow!(
444 "gpui was compiled without the screen-capture feature"
445 )))
446 .ok();
447 sources_rx
448 }
449
450 fn open_window(
451 &self,
452 handle: AnyWindowHandle,
453 options: WindowParams,
454 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
455
456 fn window_appearance(&self) -> WindowAppearance;
458
459 fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
468
469 fn button_layout(&self) -> Option<WindowButtonLayout> {
471 None
472 }
473
474 fn text_scale_factor(&self) -> f32 {
476 1.0
477 }
478
479 fn on_text_scale_factor_change(&self, _callback: Box<dyn FnMut()>) {}
480
481 fn open_url(&self, url: &str);
482 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
483 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
484
485 fn prompt_for_paths(
486 &self,
487 options: PathPromptOptions,
488 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
489 fn prompt_for_new_path(
490 &self,
491 directory: &Path,
492 suggested_name: Option<&str>,
493 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
494 fn can_select_mixed_files_and_dirs(&self) -> bool;
495 fn reveal_path(&self, path: &Path);
496 fn open_with_system(&self, path: &Path);
497
498 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
499 fn on_reopen(&self, callback: Box<dyn FnMut()>);
500 fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
502 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
504
505 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
515
516 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
521
522 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
526 None
527 }
528
529 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
530 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
531 None
532 }
533
534 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
535 fn perform_dock_menu_action(&self, _action: usize) {}
536 fn add_recent_document(&self, _path: &Path) {}
537 fn update_jump_list(
538 &self,
539 _menus: Vec<MenuItem>,
540 _entries: Vec<SmallVec<[PathBuf; 2]>>,
541 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
542 Task::ready(Vec::new())
543 }
544 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
545 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
546 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
547
548 fn debug_state(&self) -> serde_json::Value {
550 serde_json::Value::Null
551 }
552
553 fn thermal_state(&self) -> ThermalState;
554 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
555 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
556
557 fn power_mode(&self) -> PowerMode {
560 PowerMode::Unknown
561 }
562 fn on_power_mode_change(&self, _callback: Box<dyn FnMut()>) {}
564
565 fn set_app_identity(&self, identifier: &str, name: &str) {
572 _ = (identifier, name);
573 }
574
575 fn show_system_notification(&self, notification: SystemNotification) {
582 _ = notification;
583 }
584
585 fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
593 _ = tag;
594 Task::ready(())
595 }
596
597 fn on_system_notification_response(
603 &self,
604 callback: Box<dyn FnMut(SystemNotificationResponse)>,
605 ) {
606 _ = callback;
607 }
608
609 fn compositor_name(&self) -> &'static str {
610 ""
611 }
612 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
615 None
616 }
617 fn app_path(&self) -> Result<PathBuf>;
618 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
619
620 fn set_cursor_style(&self, style: CursorStyle);
621
622 fn hide_cursor_until_mouse_moves(&self);
625
626 fn is_cursor_visible(&self) -> bool;
628
629 fn should_auto_hide_scrollbars(&self) -> bool;
630
631 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
632 fn write_to_clipboard(&self, item: ClipboardItem);
633
634 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
642 Task::ready(Ok(self.read_from_clipboard()))
643 }
644
645 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
646 fn read_from_primary(&self) -> Option<ClipboardItem>;
647 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
648 fn write_to_primary(&self, item: ClipboardItem);
649
650 #[cfg(target_os = "macos")]
651 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
652 #[cfg(target_os = "macos")]
653 fn write_to_find_pasteboard(&self, item: ClipboardItem);
654
655 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
656
657 #[cfg(target_os = "macos")]
661 fn write_credentials_if_not_exists(
662 &self,
663 _url: &str,
664 _username: &str,
665 _password: &[u8],
666 ) -> Task<Result<bool>> {
667 Task::ready(Err(anyhow::anyhow!(
668 "this platform does not support atomic credential writes"
669 )))
670 }
671
672 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
673 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
674
675 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
676 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
677 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
678}
679
680pub trait PlatformDisplay: Debug {
682 fn id(&self) -> DisplayId;
684
685 fn uuid(&self) -> Result<Uuid>;
688
689 fn bounds(&self) -> Bounds<Pixels>;
691
692 fn refresh_interval(&self) -> Option<Duration>;
699
700 fn visible_bounds(&self) -> Bounds<Pixels> {
704 self.bounds()
705 }
706
707 fn default_bounds(&self) -> Bounds<Pixels> {
709 let bounds = self.bounds();
710 let center = bounds.center();
711 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
712
713 let offset = clipped_window_size / 2.0;
714 let origin = point(center.x - offset.width, center.y - offset.height);
715 Bounds::new(origin, clipped_window_size)
716 }
717}
718
719#[derive(Clone, Debug, PartialEq, Eq)]
722pub struct SystemNotification {
723 pub tag: SharedString,
727 pub title: SharedString,
729 pub body: SharedString,
731 pub actions: Vec<SystemNotificationAction>,
734}
735
736#[derive(Clone, Debug, PartialEq, Eq, Hash)]
738pub struct SystemNotificationAction {
739 pub id: SharedString,
742 pub label: SharedString,
744}
745
746#[derive(Clone, Debug, PartialEq, Eq)]
748pub struct SystemNotificationResponse {
749 pub tag: SharedString,
751 pub action_id: Option<SharedString>,
754}
755
756#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758pub enum PowerMode {
759 Unknown,
762 LowPower,
764 Balanced,
766 HighPower,
768}
769
770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
772pub enum ThermalState {
773 Nominal,
775 Fair,
777 Serious,
779 Critical,
781}
782
783#[derive(Clone)]
785pub struct SourceMetadata {
786 pub id: u64,
788 pub label: Option<SharedString>,
790 pub is_main: Option<bool>,
792 pub resolution: Size<DevicePixels>,
794}
795
796pub trait ScreenCaptureSource {
798 fn metadata(&self) -> Result<SourceMetadata>;
800
801 fn stream(
804 &self,
805 foreground_executor: &ForegroundExecutor,
806 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
807 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
808}
809
810pub trait ScreenCaptureStream {
812 fn metadata(&self) -> Result<SourceMetadata>;
814}
815
816pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
818
819#[derive(PartialEq, Eq, Hash, Copy, Clone)]
821pub struct DisplayId(pub(crate) u64);
822
823impl DisplayId {
824 pub fn new(id: u64) -> Self {
826 Self(id)
827 }
828}
829
830impl From<u64> for DisplayId {
831 fn from(id: u64) -> Self {
832 Self(id)
833 }
834}
835
836impl From<DisplayId> for u64 {
837 fn from(id: DisplayId) -> Self {
838 id.0
839 }
840}
841
842impl Debug for DisplayId {
843 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
844 write!(f, "DisplayId({})", self.0)
845 }
846}
847
848#[derive(Debug, Clone, Copy, PartialEq, Eq)]
850pub enum ResizeEdge {
851 Top,
853 TopRight,
855 Right,
857 BottomRight,
859 Bottom,
861 BottomLeft,
863 Left,
865 TopLeft,
867}
868
869#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
871pub enum WindowDecorations {
872 #[default]
873 Server,
875 Client,
877}
878
879#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
881pub enum Decorations {
882 #[default]
884 Server,
885 Client {
887 tiling: Tiling,
889 },
890}
891
892#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
894pub struct WindowControls {
895 pub fullscreen: bool,
897 pub maximize: bool,
899 pub minimize: bool,
901 pub window_menu: bool,
903}
904
905impl Default for WindowControls {
906 fn default() -> Self {
907 Self {
909 fullscreen: true,
910 maximize: true,
911 minimize: true,
912 window_menu: true,
913 }
914 }
915}
916
917#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
919pub enum WindowButton {
920 Minimize,
922 Maximize,
924 Close,
926}
927
928impl WindowButton {
929 pub fn id(&self) -> &'static str {
931 match self {
932 WindowButton::Minimize => "minimize",
933 WindowButton::Maximize => "maximize",
934 WindowButton::Close => "close",
935 }
936 }
937
938 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
939 fn index(&self) -> usize {
940 match self {
941 WindowButton::Minimize => 0,
942 WindowButton::Maximize => 1,
943 WindowButton::Close => 2,
944 }
945 }
946}
947
948pub const MAX_BUTTONS_PER_SIDE: usize = 3;
950
951#[derive(Debug, Clone, Copy, PartialEq, Eq)]
956pub struct WindowButtonLayout {
957 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
959 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
961}
962
963#[cfg(any(target_os = "linux", target_os = "freebsd"))]
964impl WindowButtonLayout {
965 pub fn linux_default() -> Self {
967 Self {
968 left: [None; MAX_BUTTONS_PER_SIDE],
969 right: [
970 Some(WindowButton::Minimize),
971 Some(WindowButton::Maximize),
972 Some(WindowButton::Close),
973 ],
974 }
975 }
976
977 pub fn parse(layout_string: &str) -> Result<Self> {
979 fn parse_side(
980 s: &str,
981 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
982 unrecognized: &mut Vec<String>,
983 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
984 let mut result = [None; MAX_BUTTONS_PER_SIDE];
985 let mut i = 0;
986 for name in s.split(',') {
987 let trimmed = name.trim();
988 if trimmed.is_empty() {
989 continue;
990 }
991 let button = match trimmed {
992 "minimize" => Some(WindowButton::Minimize),
993 "maximize" => Some(WindowButton::Maximize),
994 "close" => Some(WindowButton::Close),
995 other => {
996 unrecognized.push(other.to_string());
997 None
998 }
999 };
1000 if let Some(button) = button {
1001 if seen_buttons[button.index()] {
1002 continue;
1003 }
1004 if let Some(slot) = result.get_mut(i) {
1005 *slot = Some(button);
1006 seen_buttons[button.index()] = true;
1007 i += 1;
1008 }
1009 }
1010 }
1011 result
1012 }
1013
1014 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1015 let mut unrecognized = Vec::new();
1016 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1017 let layout = Self {
1018 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1019 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1020 };
1021
1022 if !unrecognized.is_empty()
1023 && layout.left.iter().all(Option::is_none)
1024 && layout.right.iter().all(Option::is_none)
1025 {
1026 bail!(
1027 "button layout string {:?} contains no valid buttons (unrecognized: {})",
1028 layout_string,
1029 unrecognized.join(", ")
1030 );
1031 }
1032
1033 Ok(layout)
1034 }
1035
1036 #[cfg(test)]
1038 pub fn format(&self) -> String {
1039 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1040 buttons
1041 .iter()
1042 .flatten()
1043 .map(|button| match button {
1044 WindowButton::Minimize => "minimize",
1045 WindowButton::Maximize => "maximize",
1046 WindowButton::Close => "close",
1047 })
1048 .collect::<Vec<_>>()
1049 .join(",")
1050 }
1051
1052 format!("{}:{}", format_side(&self.left), format_side(&self.right))
1053 }
1054}
1055
1056#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1058pub struct Tiling {
1059 pub top: bool,
1061 pub left: bool,
1063 pub right: bool,
1065 pub bottom: bool,
1067}
1068
1069impl Tiling {
1070 pub fn tiled() -> Self {
1072 Self {
1073 top: true,
1074 left: true,
1075 right: true,
1076 bottom: true,
1077 }
1078 }
1079
1080 pub fn is_tiled(&self) -> bool {
1082 self.top || self.left || self.right || self.bottom
1083 }
1084}
1085
1086pub struct A11yCallbacks {
1088 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1090 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1092 pub deactivation: Box<dyn Fn() + Send + 'static>,
1094}
1095
1096#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1098pub enum FrameRequestSource {
1099 #[default]
1101 NativeCallback,
1102 LocalSchedule,
1104}
1105
1106#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1107#[expect(missing_docs)]
1108pub struct RequestFrameOptions {
1109 pub require_presentation: bool,
1111 pub force_render: bool,
1113 pub signal_at: Option<Instant>,
1119 pub signal_source: FrameRequestSource,
1121}
1122
1123pub struct PlatformFrameSignal {
1132 #[cfg(feature = "profiler")]
1133 origin: Instant,
1134 #[cfg(feature = "profiler")]
1135 first_signal: std::sync::atomic::AtomicU64,
1136}
1137
1138impl Default for PlatformFrameSignal {
1139 fn default() -> Self {
1140 Self::new()
1141 }
1142}
1143
1144impl PlatformFrameSignal {
1145 pub fn new() -> Self {
1147 Self {
1148 #[cfg(feature = "profiler")]
1149 origin: Instant::now(),
1150 #[cfg(feature = "profiler")]
1151 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1152 }
1153 }
1154
1155 #[inline]
1159 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1160 if cfg!(feature = "profiler") {
1161 Some(capture())
1162 } else {
1163 None
1164 }
1165 }
1166
1167 #[inline]
1169 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1170 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1171 #[cfg(feature = "profiler")]
1172 {
1173 let nanoseconds = at
1174 .saturating_duration_since(self.origin)
1175 .as_nanos()
1176 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1177 let source_bit = match source {
1178 FrameRequestSource::NativeCallback => 0,
1179 FrameRequestSource::LocalSchedule => 1,
1180 };
1181 self.first_signal.fetch_min(
1182 (nanoseconds << 1) | source_bit,
1183 std::sync::atomic::Ordering::Relaxed,
1184 );
1185 }
1186 }
1187
1188 #[inline]
1190 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1191 #[cfg(feature = "profiler")]
1192 {
1193 let signal = self
1194 .first_signal
1195 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1196 (signal != u64::MAX).then(|| {
1197 let source = match signal & 1 {
1198 0 => FrameRequestSource::NativeCallback,
1199 _ => FrameRequestSource::LocalSchedule,
1200 };
1201 (self.origin + Duration::from_nanos(signal >> 1), source)
1202 })
1203 }
1204 #[cfg(not(feature = "profiler"))]
1205 {
1206 None
1207 }
1208 }
1209}
1210
1211#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1224pub enum AppLifecyclePhase {
1225 Active,
1227 Inactive,
1229 Background,
1232 Foreground,
1234 Disconnected,
1238}
1239
1240#[derive(Debug, Clone, Default, PartialEq)]
1247pub struct WindowInsets {
1248 pub safe_area: Edges<Pixels>,
1253 pub ime: Edges<Pixels>,
1257 pub corner_radii: Corners<Pixels>,
1262}
1263
1264impl WindowInsets {
1265 pub fn effective(&self) -> Edges<Pixels> {
1267 Edges {
1268 top: self.safe_area.top.max(self.ime.top),
1269 right: self.safe_area.right.max(self.ime.right),
1270 bottom: self.safe_area.bottom.max(self.ime.bottom),
1271 left: self.safe_area.left.max(self.ime.left),
1272 }
1273 }
1274}
1275
1276#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1278pub enum TextInputStateChange {
1279 FocusGained,
1281 FocusLost,
1283 SelectionChanged,
1285 ContentChanged,
1287}
1288
1289#[expect(missing_docs)]
1290pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1291 fn bounds(&self) -> Bounds<Pixels>;
1292 fn is_maximized(&self) -> bool;
1293 fn window_bounds(&self) -> WindowBounds;
1294 fn content_size(&self) -> Size<Pixels>;
1295 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1301 Bounds::new(Point::default(), self.content_size())
1302 }
1303 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1308 fn prepare_frame(&self) -> bool {
1313 false
1314 }
1315 fn resize(&mut self, size: Size<Pixels>);
1316 fn scale_factor(&self) -> f32;
1317 fn appearance(&self) -> WindowAppearance;
1318 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1319 fn mouse_position(&self) -> Point<Pixels>;
1320 fn modifiers(&self) -> Modifiers;
1321 fn capslock(&self) -> Capslock;
1322 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1323 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1324 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1329 fn prompt(
1330 &self,
1331 level: PromptLevel,
1332 msg: &str,
1333 detail: Option<&str>,
1334 answers: &[PromptButton],
1335 ) -> Option<oneshot::Receiver<usize>>;
1336 fn activate(&self);
1337 fn request_attention(&self) {}
1339 fn is_active(&self) -> bool;
1340 fn visibility(&self) -> WindowVisibility;
1343 fn is_hovered(&self) -> bool;
1344 fn background_appearance(&self) -> WindowBackgroundAppearance;
1345 fn set_title(&mut self, title: &str);
1346 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1347 fn minimize(&self);
1348 fn zoom(&self);
1349 fn toggle_fullscreen(&self);
1350 fn is_fullscreen(&self) -> bool;
1351 fn debug_state(&self) -> serde_json::Value {
1353 serde_json::Value::Null
1354 }
1355 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1356 None
1357 }
1358 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1359 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1360 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1361 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1365 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1366 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1367 fn on_moved(&self, callback: Box<dyn FnMut()>);
1368 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1372 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1373 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1374 fn on_close(&self, callback: Box<dyn FnOnce()>);
1375
1376 unsafe fn attach_native_view(
1386 &self,
1387 _id: crate::NativeViewId,
1388 _view: std::ptr::NonNull<std::ffi::c_void>,
1389 ) -> Option<Box<dyn std::any::Any>> {
1390 None
1391 }
1392 fn set_focused_native_view(&self, _id: Option<crate::NativeViewId>) {}
1395 fn on_hit_test_native_view(
1398 &self,
1399 _callback: Box<dyn FnMut(Point<Pixels>) -> Option<crate::NativeViewId>>,
1400 ) {
1401 }
1402 fn on_native_view_focused(&self, _callback: Box<dyn FnMut(crate::NativeViewId)>) {}
1405 fn on_key_down_before_native_view(
1411 &self,
1412 _callback: Box<dyn FnMut(crate::KeyDownEvent) -> bool>,
1413 ) {
1414 }
1415 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1416 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1417 fn draw(&self, scene: &Scene);
1418 fn schedule_frame(&self) {}
1419 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1420 fn is_subpixel_rendering_supported(&self) -> bool;
1421
1422 fn get_title(&self) -> String {
1424 String::new()
1425 }
1426 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1427 None
1428 }
1429 fn tab_bar_visible(&self) -> bool {
1430 false
1431 }
1432 fn set_edited(&mut self, _edited: bool) {}
1433 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1434 fn toggle_simple_fullscreen(&self) {}
1435 fn is_simple_fullscreen(&self) -> bool {
1436 false
1437 }
1438 #[cfg(target_os = "macos")]
1439 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1440 #[cfg(target_os = "macos")]
1441 fn set_native_titlebar_visibility(&self, _visible: bool) {}
1442 fn show_character_palette(&self) {}
1443 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1444 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1445 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1446 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1447 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1448 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1449 fn merge_all_windows(&self) {}
1450 fn move_tab_to_new_window(&self) {}
1451 fn toggle_window_tab_overview(&self) {}
1452 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1453
1454 fn native_window_state(&self) -> Option<Vec<u8>> {
1455 None
1456 }
1457 fn restore_native_window_state(&self, _state: &[u8]) {}
1458
1459 #[cfg(target_os = "windows")]
1460 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1461
1462 fn inner_window_bounds(&self) -> WindowBounds {
1464 self.window_bounds()
1465 }
1466 fn request_decorations(&self, _decorations: WindowDecorations) {}
1467 fn show_window_menu(&self, _position: Point<Pixels>) {}
1468 fn start_window_move(&self) {}
1469 fn can_start_external_drag(&self) -> bool {
1470 false
1471 }
1472 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1473 false
1474 }
1475 fn start_window_resize(&self, _edge: ResizeEdge) {}
1476 fn set_exclusive_zone(&self, _zone: Pixels) {}
1477 #[cfg(all(target_os = "linux", feature = "wayland"))]
1478 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1479 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1480 fn window_decorations(&self) -> Decorations {
1481 Decorations::Server
1482 }
1483 fn set_app_id(&mut self, _app_id: &str) {}
1484 fn map_window(&mut self) -> anyhow::Result<()> {
1485 Ok(())
1486 }
1487 fn window_controls(&self) -> WindowControls {
1488 WindowControls::default()
1489 }
1490 fn set_client_inset(&self, _inset: Pixels) {}
1491 fn set_client_corner_radii(&self, _radii: Corners<Pixels>) {}
1492 fn gpu_specs(&self) -> Option<GpuSpecs>;
1493
1494 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1495
1496 fn insets(&self) -> WindowInsets {
1501 WindowInsets::default()
1502 }
1503
1504 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1510
1511 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1514
1515 fn set_back_enabled(&self, _enabled: bool) {}
1518
1519 fn show_soft_keyboard(&self) {}
1521
1522 fn hide_soft_keyboard(&self) {}
1524
1525 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1527
1528 fn play_system_bell(&self) {}
1529
1530 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1532
1533 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1535
1536 fn a11y_update_window_bounds(&self) {}
1538
1539 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1540 fn as_test(&mut self) -> Option<&mut TestWindow> {
1541 None
1542 }
1543
1544 #[cfg(any(test, feature = "test-support"))]
1548 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1549 anyhow::bail!("render_to_image not implemented for this platform")
1550 }
1551}
1552
1553#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1555pub trait PlatformHeadlessRenderer {
1556 fn render_scene_to_image(
1558 &mut self,
1559 scene: &Scene,
1560 size: Size<DevicePixels>,
1561 ) -> Result<RgbaImage>;
1562
1563 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1569
1570 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1572}
1573
1574#[doc(hidden)]
1577pub type RunnableVariant = Runnable<RunnableMeta>;
1578
1579#[doc(hidden)]
1580pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1581
1582#[doc(hidden)]
1583pub enum TasksIncluded {
1584 OnlyCompleted,
1585 CompletedAndRunning,
1586}
1587
1588#[doc(hidden)]
1591pub trait PlatformDispatcher: Send + Sync {
1592 fn is_main_thread(&self) -> bool;
1593 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1594 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1595 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1596
1597 fn dispatch_on_main_thread_when_idle(
1598 &self,
1599 runnable: RunnableVariant,
1600 timeout: Option<Duration>,
1601 ) {
1602 let _ = timeout;
1603 self.dispatch_on_main_thread(runnable, Priority::Low);
1604 }
1605
1606 fn idle_time_remaining(&self) -> Option<Duration> {
1607 None
1608 }
1609
1610 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1611
1612 fn now(&self) -> Instant {
1613 Instant::now()
1614 }
1615
1616 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1617 gpui_util::defer(Box::new(|| {}))
1618 }
1619
1620 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1621 ActivityGuard::noop()
1622 }
1623
1624 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1625 fn as_test(&self) -> Option<&TestDispatcher> {
1626 None
1627 }
1628
1629 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1632 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1633 None
1634 }
1635}
1636
1637#[expect(missing_docs)]
1638pub trait PlatformTextSystem: Send + Sync {
1639 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1640 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1642 fn all_font_names(&self) -> Vec<String>;
1644 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1646 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1648 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1650 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1652 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1654 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1656 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1658 fn rasterize_glyph(
1660 &self,
1661 params: &RenderGlyphParams,
1662 raster_bounds: Bounds<DevicePixels>,
1663 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1664 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1666 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1668 -> TextRenderingMode;
1669 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1671 0
1672 }
1673}
1674
1675#[expect(missing_docs)]
1676pub struct NoopTextSystem;
1677
1678#[expect(missing_docs)]
1679impl NoopTextSystem {
1680 #[allow(dead_code)]
1681 pub fn new() -> Self {
1682 Self
1683 }
1684}
1685
1686impl PlatformTextSystem for NoopTextSystem {
1687 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1688 Ok(())
1689 }
1690
1691 fn all_font_names(&self) -> Vec<String> {
1692 Vec::new()
1693 }
1694
1695 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1696 Ok(FontId(1))
1697 }
1698
1699 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1700 FontMetrics {
1701 units_per_em: 1000,
1702 ascent: 1025.0,
1703 descent: -275.0,
1704 line_gap: 0.0,
1705 underline_position: -95.0,
1706 underline_thickness: 60.0,
1707 cap_height: 698.0,
1708 x_height: 516.0,
1709 bounding_box: Bounds {
1710 origin: Point {
1711 x: -260.0,
1712 y: -245.0,
1713 },
1714 size: Size {
1715 width: 1501.0,
1716 height: 1364.0,
1717 },
1718 },
1719 }
1720 }
1721
1722 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1723 Ok(Bounds {
1724 origin: Point { x: 54.0, y: 0.0 },
1725 size: size(392.0, 528.0),
1726 })
1727 }
1728
1729 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1730 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1731 }
1732
1733 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1734 Some(GlyphId(ch.len_utf16() as u32))
1735 }
1736
1737 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1738 Ok(Default::default())
1739 }
1740
1741 fn rasterize_glyph(
1742 &self,
1743 _params: &RenderGlyphParams,
1744 raster_bounds: Bounds<DevicePixels>,
1745 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1746 Ok((raster_bounds.size, Vec::new()))
1747 }
1748
1749 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1750 let mut position = px(0.);
1751 let metrics = self.font_metrics(FontId(0));
1752 let em_width = font_size
1753 * self
1754 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1755 .unwrap()
1756 .width
1757 / metrics.units_per_em as f32;
1758 let mut glyphs = Vec::new();
1759 for (ix, c) in text.char_indices() {
1760 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1761 glyphs.push(ShapedGlyph {
1762 id: glyph,
1763 position: point(position, px(0.)),
1764 index: ix,
1765 is_emoji: glyph.0 == 2,
1766 });
1767 if glyph.0 == 2 {
1768 position += em_width * 2.0;
1769 } else {
1770 position += em_width;
1771 }
1772 } else {
1773 position += em_width
1774 }
1775 }
1776 let mut runs = Vec::default();
1777 if !glyphs.is_empty() {
1778 runs.push(ShapedRun {
1779 font_id: FontId(0),
1780 glyphs,
1781 });
1782 } else {
1783 position = px(0.);
1784 }
1785
1786 LineLayout {
1787 font_size,
1788 width: position,
1789 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1790 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1791 runs,
1792 len: text.len(),
1793 }
1794 }
1795
1796 fn recommended_rendering_mode(
1797 &self,
1798 _font_id: FontId,
1799 _font_size: Pixels,
1800 ) -> TextRenderingMode {
1801 TextRenderingMode::Grayscale
1802 }
1803}
1804
1805#[allow(dead_code)]
1810pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1811 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1812 [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], ];
1826
1827 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1828 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1829
1830 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1831 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1832
1833 [
1834 ratios[0] * NORM13,
1835 ratios[1] * NORM24,
1836 ratios[2] * NORM13,
1837 ratios[3] * NORM24,
1838 ]
1839}
1840
1841#[derive(PartialEq, Eq, Hash, Clone)]
1842#[expect(missing_docs)]
1843pub enum AtlasKey {
1844 Glyph(RenderGlyphParams),
1845 Svg(RenderSvgParams),
1846 Image(RenderImageParams),
1847}
1848
1849impl AtlasKey {
1850 pub fn texture_kind(&self) -> AtlasTextureKind {
1852 match self {
1853 AtlasKey::Glyph(params) => {
1854 if params.is_emoji {
1855 AtlasTextureKind::Polychrome
1856 } else if params.subpixel_rendering {
1857 AtlasTextureKind::Subpixel
1858 } else {
1859 AtlasTextureKind::Monochrome
1860 }
1861 }
1862 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1863 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1864 }
1865 }
1866}
1867
1868impl From<RenderGlyphParams> for AtlasKey {
1869 fn from(params: RenderGlyphParams) -> Self {
1870 Self::Glyph(params)
1871 }
1872}
1873
1874impl From<RenderSvgParams> for AtlasKey {
1875 fn from(params: RenderSvgParams) -> Self {
1876 Self::Svg(params)
1877 }
1878}
1879
1880impl From<RenderImageParams> for AtlasKey {
1881 fn from(params: RenderImageParams) -> Self {
1882 Self::Image(params)
1883 }
1884}
1885
1886#[expect(missing_docs)]
1887pub trait PlatformAtlas {
1888 fn get_or_insert_with<'a>(
1890 &self,
1891 key: AtlasKey,
1892 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1893 ) -> Result<Option<AtlasTile>>;
1894 fn remove(&self, key: &AtlasKey);
1895
1896 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1897 fn contains(&self, _key: &AtlasKey) -> bool {
1898 false
1899 }
1900}
1901
1902#[doc(hidden)]
1903pub trait AtlasBackend {
1904 fn insert(
1905 &mut self,
1906 kind: AtlasTextureKind,
1907 size: Size<DevicePixels>,
1908 bytes: &[u8],
1909 ) -> Result<AtlasTile>;
1910
1911 fn remove(&mut self, tile: AtlasTile);
1912}
1913
1914#[doc(hidden)]
1915pub struct AtlasState<Backend> {
1916 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1917 pub backend: Backend,
1918}
1919
1920impl<Backend> AtlasState<Backend> {
1921 pub fn new(backend: Backend) -> Self {
1922 Self {
1923 tiles_by_key: FxHashMap::default(),
1924 backend,
1925 }
1926 }
1927
1928 pub fn contains(&self, key: &AtlasKey) -> bool {
1929 self.tiles_by_key.contains_key(key)
1930 }
1931
1932 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1933 self.tiles_by_key.clear();
1934 reset_backend(&mut self.backend);
1935 }
1936}
1937
1938impl<Backend: Default> Default for AtlasState<Backend> {
1939 fn default() -> Self {
1940 Self::new(Backend::default())
1941 }
1942}
1943
1944impl<Backend: AtlasBackend> AtlasState<Backend> {
1945 pub fn get_or_insert_with<'a>(
1946 &mut self,
1947 key: AtlasKey,
1948 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1949 ) -> Result<Option<AtlasTile>> {
1950 match self.tiles_by_key.entry(key) {
1951 Entry::Occupied(entry) => Ok(Some(*entry.get())),
1952 Entry::Vacant(entry) => {
1953 profiling::scope!("new tile");
1954 let Some((size, bytes)) = build()? else {
1955 return Ok(None);
1956 };
1957 let tile = self
1958 .backend
1959 .insert(entry.key().texture_kind(), size, &bytes)?;
1960 entry.insert(tile);
1961 Ok(Some(tile))
1962 }
1963 }
1964 }
1965
1966 pub fn remove(&mut self, key: &AtlasKey) {
1967 if let Some(tile) = self.tiles_by_key.remove(key) {
1968 self.backend.remove(tile);
1969 }
1970 }
1971}
1972
1973#[derive(Default)]
1977pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1978
1979#[doc(hidden)]
1980#[derive(Default)]
1981pub struct HeadlessAtlasBackend {
1982 next_id: u32,
1983}
1984
1985impl AtlasBackend for HeadlessAtlasBackend {
1986 fn insert(
1987 &mut self,
1988 kind: AtlasTextureKind,
1989 size: Size<DevicePixels>,
1990 _bytes: &[u8],
1991 ) -> Result<AtlasTile> {
1992 self.next_id += 1;
1993 let texture_id = self.next_id;
1994 self.next_id += 1;
1995 let tile_id = self.next_id;
1996 Ok(AtlasTile {
1997 texture_id: AtlasTextureId {
1998 index: texture_id,
1999 kind,
2000 },
2001 tile_id: TileId(tile_id),
2002 padding: 0,
2003 bounds: Bounds {
2004 origin: Point::default(),
2005 size,
2006 },
2007 })
2008 }
2009
2010 fn remove(&mut self, _tile: AtlasTile) {}
2011}
2012
2013impl PlatformAtlas for HeadlessAtlas {
2014 fn get_or_insert_with<'a>(
2015 &self,
2016 key: AtlasKey,
2017 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2018 ) -> Result<Option<AtlasTile>> {
2019 self.0.lock().get_or_insert_with(key, build)
2020 }
2021
2022 fn remove(&self, key: &AtlasKey) {
2023 self.0.lock().remove(key);
2024 }
2025
2026 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2027 fn contains(&self, key: &AtlasKey) -> bool {
2028 self.0.lock().contains(key)
2029 }
2030}
2031
2032#[doc(hidden)]
2033pub struct AtlasTextureList<T> {
2034 pub textures: Vec<Option<T>>,
2035 pub free_list: Vec<usize>,
2036}
2037
2038impl<T> Default for AtlasTextureList<T> {
2039 fn default() -> Self {
2040 Self {
2041 textures: Vec::default(),
2042 free_list: Vec::default(),
2043 }
2044 }
2045}
2046
2047impl<T> ops::Index<usize> for AtlasTextureList<T> {
2048 type Output = Option<T>;
2049
2050 fn index(&self, index: usize) -> &Self::Output {
2051 &self.textures[index]
2052 }
2053}
2054
2055impl<T> AtlasTextureList<T> {
2056 #[allow(unused)]
2057 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2058 self.free_list.clear();
2059 self.textures.drain(..)
2060 }
2061
2062 #[allow(dead_code)]
2063 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2064 self.textures.iter_mut().flatten()
2065 }
2066}
2067
2068#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2069#[repr(C)]
2070#[expect(missing_docs)]
2071pub struct AtlasTile {
2072 pub texture_id: AtlasTextureId,
2074 pub tile_id: TileId,
2076 pub padding: u32,
2078 pub bounds: Bounds<DevicePixels>,
2080}
2081
2082#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2083#[repr(C)]
2084#[expect(missing_docs)]
2085pub struct AtlasTextureId {
2086 pub index: u32,
2089 pub kind: AtlasTextureKind,
2091}
2092
2093#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2094#[repr(C)]
2095#[cfg_attr(
2096 all(
2097 any(target_os = "linux", target_os = "freebsd"),
2098 not(any(feature = "x11", feature = "wayland"))
2099 ),
2100 allow(dead_code)
2101)]
2102#[expect(missing_docs)]
2103pub enum AtlasTextureKind {
2104 Monochrome = 0,
2105 Polychrome = 1,
2106 Subpixel = 2,
2107}
2108
2109#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2110#[repr(C)]
2111#[expect(missing_docs)]
2112pub struct TileId(pub u32);
2113
2114impl From<etagere::AllocId> for TileId {
2115 fn from(id: etagere::AllocId) -> Self {
2116 Self(id.serialize())
2117 }
2118}
2119
2120impl From<TileId> for etagere::AllocId {
2121 fn from(id: TileId) -> Self {
2122 Self::deserialize(id.0)
2123 }
2124}
2125
2126#[expect(missing_docs)]
2127pub struct PlatformInputHandler {
2128 cx: AsyncWindowContext,
2129 handler: Box<dyn InputHandler>,
2130 focus_id: Option<crate::FocusId>,
2131}
2132
2133#[expect(missing_docs)]
2134#[cfg_attr(
2135 all(
2136 any(target_os = "linux", target_os = "freebsd"),
2137 not(any(feature = "x11", feature = "wayland"))
2138 ),
2139 allow(dead_code)
2140)]
2141impl PlatformInputHandler {
2142 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2143 Self {
2144 cx,
2145 handler,
2146 focus_id: None,
2147 }
2148 }
2149
2150 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2151 self.focus_id = Some(focus_id);
2152 self
2153 }
2154
2155 pub fn focus_id(&self) -> Option<crate::FocusId> {
2160 self.focus_id
2161 }
2162
2163 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2164 self.cx
2165 .update(|window, cx| {
2166 self.handler
2167 .selected_text_range(ignore_disabled_input, window, cx)
2168 })
2169 .ok()
2170 .flatten()
2171 }
2172
2173 #[cfg_attr(target_os = "windows", allow(dead_code))]
2174 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2175 self.cx
2176 .update(|window, cx| self.handler.marked_text_range(window, cx))
2177 .ok()
2178 .flatten()
2179 }
2180
2181 #[cfg_attr(
2182 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2183 allow(dead_code)
2184 )]
2185 pub fn text_for_range(
2186 &mut self,
2187 range_utf16: Range<usize>,
2188 adjusted: &mut Option<Range<usize>>,
2189 ) -> Option<String> {
2190 self.cx
2191 .update(|window, cx| {
2192 self.handler
2193 .text_for_range(range_utf16, adjusted, window, cx)
2194 })
2195 .ok()
2196 .flatten()
2197 }
2198
2199 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2200 self.cx
2201 .update(|window, cx| {
2202 self.handler
2203 .replace_text_in_range(replacement_range, text, window, cx);
2204 })
2205 .ok();
2206 }
2207
2208 pub fn replace_and_mark_text_in_range(
2209 &mut self,
2210 range_utf16: Option<Range<usize>>,
2211 new_text: &str,
2212 new_selected_range: Option<Range<usize>>,
2213 ) {
2214 self.cx
2215 .update(|window, cx| {
2216 self.handler.replace_and_mark_text_in_range(
2217 range_utf16,
2218 new_text,
2219 new_selected_range,
2220 window,
2221 cx,
2222 )
2223 })
2224 .ok();
2225 }
2226
2227 #[cfg_attr(target_os = "windows", allow(dead_code))]
2228 pub fn unmark_text(&mut self) {
2229 self.cx
2230 .update(|window, cx| self.handler.unmark_text(window, cx))
2231 .ok();
2232 }
2233
2234 pub fn paste(&mut self, item: ClipboardItem) {
2235 self.cx
2236 .update(|window, cx| self.handler.paste(item, window, cx))
2237 .ok();
2238 }
2239
2240 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2241 self.cx
2242 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2243 .ok()
2244 .flatten()
2245 }
2246
2247 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2248 self.cx
2249 .update(|window, cx| {
2250 self.handler
2251 .selection_bounds_for_range(range_utf16, window, cx)
2252 })
2253 .unwrap_or_default()
2254 }
2255
2256 #[allow(dead_code)]
2257 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2258 self.handler.apple_press_and_hold_enabled()
2259 }
2260
2261 pub(crate) fn unmark_text_during_update(&mut self, window: &mut Window, cx: &mut App) {
2264 self.handler.unmark_text(window, cx);
2265 }
2266
2267 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2268 self.handler.replace_text_in_range(None, input, window, cx);
2269 }
2270
2271 pub fn compute_ime_candidate_bounds(
2272 marked_range: Option<Range<usize>>,
2273 selection: &UTF16Selection,
2274 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2275 ) -> Option<Bounds<Pixels>> {
2276 if let Some(marked_range) = marked_range {
2277 let mut line_start = marked_range.start;
2279
2280 let caret = selection.range.end;
2284 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2285 for i in (marked_range.start..caret).rev() {
2286 if let Some(b) = bounds_for_range(i..i) {
2287 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2288 line_start = i + 1;
2289 break;
2290 }
2291 }
2292 }
2293 }
2294 bounds_for_range(line_start..line_start)
2295 } else {
2296 let offset = if selection.reversed {
2298 selection.range.start
2299 } else {
2300 selection.range.end
2301 };
2302 bounds_for_range(offset..offset)
2303 }
2304 }
2305
2306 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2307 let marked_range = self.handler.marked_text_range(window, cx);
2308 let selection = self.handler.selected_text_range(true, window, cx)?;
2309 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2310 self.handler.bounds_for_range(range, window, cx)
2311 })
2312 }
2313
2314 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2315 let marked_range = self.marked_text_range();
2316 let selection = self.selected_text_range(true)?;
2317 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2318 self.bounds_for_range(range)
2319 })
2320 }
2321
2322 #[allow(unused)]
2323 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2324 self.cx
2325 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2326 .ok()
2327 .flatten()
2328 }
2329
2330 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2332 self.cx
2333 .update(|window, cx| {
2334 self.handler
2335 .set_selected_text_range(range_utf16, window, cx)
2336 })
2337 .ok();
2338 }
2339
2340 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2342 self.cx
2343 .update(|window, cx| self.handler.element_bounds(window, cx))
2344 .ok()
2345 .flatten()
2346 }
2347
2348 pub fn text_length_utf16(&mut self) -> Option<usize> {
2350 self.cx
2351 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2352 .ok()
2353 .flatten()
2354 }
2355
2356 #[allow(dead_code)]
2357 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2358 self.handler.accepts_text_input(window, cx)
2359 }
2360
2361 #[allow(dead_code)]
2362 pub fn query_accepts_text_input(&mut self) -> bool {
2363 self.cx
2364 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2365 .unwrap_or(true)
2366 }
2367
2368 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2373 let focus_id = self.focus_id;
2374 self.cx
2375 .update(|window, cx| {
2376 focus_id.is_some()
2377 && window.focus == focus_id
2378 && self.handler.accepts_text_input(window, cx)
2379 })
2380 .unwrap_or(false)
2381 }
2382
2383 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2389 self.cx
2390 .update(|window, cx| {
2391 !window.has_pending_keystrokes()
2393 && self.handler.prefers_ime_for_printable_keys(window, cx)
2394 })
2395 .unwrap_or(false)
2396 }
2397
2398 pub fn text_input_configuration(
2400 &mut self,
2401 window: &mut Window,
2402 cx: &mut App,
2403 ) -> TextInputConfiguration {
2404 self.handler.text_input_configuration(window, cx)
2405 }
2406
2407 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2409 self.cx
2410 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2411 .ok()
2412 .flatten()
2413 }
2414}
2415
2416#[derive(Debug)]
2419pub struct UTF16Selection {
2420 pub range: Range<usize>,
2423 pub reversed: bool,
2426}
2427
2428pub trait InputHandler: 'static {
2433 fn selected_text_range(
2438 &mut self,
2439 ignore_disabled_input: bool,
2440 window: &mut Window,
2441 cx: &mut App,
2442 ) -> Option<UTF16Selection>;
2443
2444 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2449
2450 fn text_for_range(
2455 &mut self,
2456 range_utf16: Range<usize>,
2457 adjusted_range: &mut Option<Range<usize>>,
2458 window: &mut Window,
2459 cx: &mut App,
2460 ) -> Option<String>;
2461
2462 fn replace_text_in_range(
2467 &mut self,
2468 replacement_range: Option<Range<usize>>,
2469 text: &str,
2470 window: &mut Window,
2471 cx: &mut App,
2472 );
2473
2474 fn replace_and_mark_text_in_range(
2481 &mut self,
2482 range_utf16: Option<Range<usize>>,
2483 new_text: &str,
2484 new_selected_range: Option<Range<usize>>,
2485 window: &mut Window,
2486 cx: &mut App,
2487 );
2488
2489 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2492
2493 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2500 if let Some(text) = item.text() {
2501 self.replace_text_in_range(None, &text, window, cx);
2502 }
2503 }
2504
2505 fn bounds_for_range(
2510 &mut self,
2511 range_utf16: Range<usize>,
2512 window: &mut Window,
2513 cx: &mut App,
2514 ) -> Option<Bounds<Pixels>>;
2515
2516 fn selection_bounds_for_range(
2523 &mut self,
2524 _range_utf16: Range<usize>,
2525 _window: &mut Window,
2526 _cx: &mut App,
2527 ) -> Vec<Bounds<Pixels>> {
2528 Vec::new()
2529 }
2530
2531 fn character_index_for_point(
2535 &mut self,
2536 point: Point<Pixels>,
2537 window: &mut Window,
2538 cx: &mut App,
2539 ) -> Option<usize>;
2540
2541 fn set_selected_text_range(
2551 &mut self,
2552 _range_utf16: Range<usize>,
2553 _window: &mut Window,
2554 _cx: &mut App,
2555 ) {
2556 }
2557
2558 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2565 None
2566 }
2567
2568 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2570 None
2571 }
2572
2573 #[allow(dead_code)]
2578 fn apple_press_and_hold_enabled(&mut self) -> bool {
2579 true
2580 }
2581
2582 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2584 true
2585 }
2586
2587 fn text_input_editable_range(
2598 &mut self,
2599 _window: &mut Window,
2600 _cx: &mut App,
2601 ) -> Option<Range<usize>> {
2602 None
2603 }
2604
2605 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2614 false
2615 }
2616
2617 fn text_input_configuration(
2623 &mut self,
2624 _window: &mut Window,
2625 _cx: &mut App,
2626 ) -> TextInputConfiguration {
2627 TextInputConfiguration::default()
2628 }
2629}
2630
2631#[derive(Clone, Debug, Default, PartialEq, Eq)]
2641pub struct TextInputConfiguration {
2642 pub autocorrect: bool,
2644 pub autocapitalize: Autocapitalize,
2646 pub suggestions: bool,
2648 pub input_action: TextInputAction,
2650}
2651
2652#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2654pub enum Autocapitalize {
2655 #[default]
2657 None,
2658 Words,
2660 Sentences,
2662 Characters,
2664}
2665
2666#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2676pub enum TextInputAction {
2677 #[default]
2679 Unspecified,
2680 Enter,
2682 Done,
2684 Go,
2686 Next,
2688 Previous,
2690 Search,
2692 Send,
2694}
2695
2696#[derive(Debug)]
2698pub struct WindowOptions {
2699 pub window_bounds: Option<WindowBounds>,
2703
2704 pub titlebar: Option<TitlebarOptions>,
2706
2707 pub focus: bool,
2709
2710 pub show: bool,
2712
2713 pub kind: WindowKind,
2715
2716 pub is_movable: bool,
2720
2721 pub app_owns_titlebar_drag: bool,
2733
2734 pub inactive_frame_interval: Option<Duration>,
2739
2740 pub low_power_frame_interval: Option<Duration>,
2745
2746 pub thermal_frame_interval: Option<Duration>,
2751
2752 pub is_resizable: bool,
2754
2755 pub is_minimizable: bool,
2757
2758 pub display_id: Option<DisplayId>,
2761
2762 pub window_background: WindowBackgroundAppearance,
2764
2765 pub app_id: Option<String>,
2767
2768 pub window_min_size: Option<Size<Pixels>>,
2770
2771 pub window_decorations: Option<WindowDecorations>,
2774
2775 pub icon: Option<Arc<image::RgbaImage>>,
2777
2778 pub tabbing_identifier: Option<String>,
2780
2781 pub use_display_p3: bool,
2783}
2784
2785#[derive(Debug)]
2787#[cfg_attr(
2788 all(
2789 any(target_os = "linux", target_os = "freebsd"),
2790 not(any(feature = "x11", feature = "wayland"))
2791 ),
2792 allow(dead_code)
2793)]
2794#[allow(missing_docs)]
2795pub struct WindowParams {
2796 pub bounds: Bounds<Pixels>,
2797
2798 #[cfg_attr(feature = "wayland", allow(dead_code))]
2800 pub titlebar: Option<TitlebarOptions>,
2801
2802 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2804 pub kind: WindowKind,
2805
2806 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2808 pub is_movable: bool,
2809
2810 #[cfg_attr(
2812 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2813 allow(dead_code)
2814 )]
2815 pub app_owns_titlebar_drag: bool,
2816
2817 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2819 pub is_resizable: bool,
2820
2821 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2823 pub is_minimizable: bool,
2824
2825 #[cfg_attr(
2826 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2827 allow(dead_code)
2828 )]
2829 pub focus: bool,
2830
2831 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2832 pub show: bool,
2833
2834 #[cfg_attr(feature = "wayland", allow(dead_code))]
2836 pub icon: Option<Arc<image::RgbaImage>>,
2837
2838 #[cfg_attr(feature = "wayland", allow(dead_code))]
2839 pub display_id: Option<DisplayId>,
2840
2841 #[cfg_attr(feature = "wayland", allow(dead_code))]
2842 pub app_id: Option<String>,
2843
2844 pub window_min_size: Option<Size<Pixels>>,
2845
2846 #[cfg(target_os = "macos")]
2847 pub tabbing_identifier: Option<String>,
2848
2849 #[cfg(target_os = "macos")]
2850 pub use_display_p3: bool,
2851}
2852
2853#[derive(Debug, Copy, Clone, PartialEq)]
2855pub enum WindowBounds {
2856 Windowed(Bounds<Pixels>),
2858 Maximized(Bounds<Pixels>),
2861 Fullscreen(Bounds<Pixels>),
2864}
2865
2866impl Default for WindowBounds {
2867 fn default() -> Self {
2868 WindowBounds::Windowed(Bounds::default())
2869 }
2870}
2871
2872impl WindowBounds {
2873 pub fn get_bounds(&self) -> Bounds<Pixels> {
2875 match self {
2876 WindowBounds::Windowed(bounds) => *bounds,
2877 WindowBounds::Maximized(bounds) => *bounds,
2878 WindowBounds::Fullscreen(bounds) => *bounds,
2879 }
2880 }
2881
2882 pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
2885 WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
2886 }
2887}
2888
2889impl Default for WindowOptions {
2890 fn default() -> Self {
2891 Self {
2892 window_bounds: None,
2893 titlebar: Some(TitlebarOptions {
2894 title: Default::default(),
2895 appears_transparent: Default::default(),
2896 traffic_light_position: Default::default(),
2897 }),
2898 focus: true,
2899 show: true,
2900 kind: WindowKind::Normal,
2901 is_movable: true,
2902 app_owns_titlebar_drag: false,
2903 inactive_frame_interval: Some(Duration::from_micros(33_333)),
2904 low_power_frame_interval: Some(Duration::from_micros(33_333)),
2905 thermal_frame_interval: Some(Duration::from_micros(16_667)),
2906 is_resizable: true,
2907 is_minimizable: true,
2908 display_id: None,
2909 window_background: WindowBackgroundAppearance::default(),
2910 icon: None,
2911 app_id: None,
2912 window_min_size: None,
2913 window_decorations: None,
2914 tabbing_identifier: None,
2915 use_display_p3: false,
2916 }
2917 }
2918}
2919
2920#[derive(Debug, Default)]
2922pub struct TitlebarOptions {
2923 pub title: Option<SharedString>,
2925
2926 pub appears_transparent: bool,
2929
2930 pub traffic_light_position: Option<Point<Pixels>>,
2932}
2933
2934#[derive(Clone, Debug, PartialEq, Eq)]
2936pub enum WindowKind {
2937 Normal,
2939
2940 PopUp,
2943
2944 AnchoredPopup(popup::PopupOptions),
2951
2952 Floating,
2954
2955 #[cfg(all(target_os = "linux", feature = "wayland"))]
2958 LayerShell(layer_shell::LayerShellOptions),
2959
2960 Dialog,
2963}
2964
2965#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2970pub enum WindowAppearance {
2971 #[default]
2975 Light,
2976
2977 VibrantLight,
2981
2982 Dark,
2986
2987 VibrantDark,
2991}
2992
2993#[derive(Copy, Clone, Debug, Default, PartialEq)]
2996pub enum WindowBackgroundAppearance {
2997 #[default]
3005 Opaque,
3006 Transparent,
3008 Blurred,
3012 MicaBackdrop,
3014 MicaAltBackdrop,
3016}
3017
3018#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3020pub enum TextRenderingMode {
3021 #[default]
3023 PlatformDefault,
3024 Subpixel,
3026 Grayscale,
3028}
3029
3030#[derive(Clone, Debug)]
3032pub struct PathPromptOptions {
3033 pub files: bool,
3035 pub directories: bool,
3037 pub multiple: bool,
3039 pub prompt: Option<SharedString>,
3041}
3042
3043#[derive(Copy, Clone, Debug, PartialEq)]
3045pub enum PromptLevel {
3046 Info,
3048
3049 Warning,
3051
3052 Critical,
3054}
3055
3056#[derive(Clone, Debug, PartialEq)]
3058pub enum PromptButton {
3059 Ok(SharedString),
3061 Cancel(SharedString),
3063 Other(SharedString),
3065}
3066
3067impl PromptButton {
3068 pub fn new(label: impl Into<SharedString>) -> Self {
3070 PromptButton::Other(label.into())
3071 }
3072
3073 pub fn ok(label: impl Into<SharedString>) -> Self {
3075 PromptButton::Ok(label.into())
3076 }
3077
3078 pub fn cancel(label: impl Into<SharedString>) -> Self {
3080 PromptButton::Cancel(label.into())
3081 }
3082
3083 #[allow(dead_code)]
3085 pub fn is_cancel(&self) -> bool {
3086 matches!(self, PromptButton::Cancel(_))
3087 }
3088
3089 pub fn label(&self) -> &SharedString {
3091 match self {
3092 PromptButton::Ok(label) => label,
3093 PromptButton::Cancel(label) => label,
3094 PromptButton::Other(label) => label,
3095 }
3096 }
3097}
3098
3099impl From<&str> for PromptButton {
3100 fn from(value: &str) -> Self {
3101 match value.to_lowercase().as_str() {
3102 "ok" => PromptButton::Ok("OK".into()),
3103 "cancel" => PromptButton::Cancel("Cancel".into()),
3104 _ => PromptButton::Other(SharedString::from(value.to_owned())),
3105 }
3106 }
3107}
3108
3109#[derive(
3111 Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, EnumIter,
3112)]
3113pub enum CursorStyle {
3114 #[default]
3116 Arrow,
3117
3118 IBeam,
3121
3122 Crosshair,
3125
3126 ClosedHand,
3129
3130 OpenHand,
3133
3134 PointingHand,
3137
3138 ResizeLeft,
3141
3142 ResizeRight,
3145
3146 ResizeLeftRight,
3149
3150 ResizeUp,
3153
3154 ResizeDown,
3157
3158 ResizeUpDown,
3161
3162 ResizeUpLeftDownRight,
3165
3166 ResizeUpRightDownLeft,
3169
3170 ResizeColumn,
3173
3174 ResizeRow,
3177
3178 IBeamCursorForVerticalLayout,
3181
3182 OperationNotAllowed,
3185
3186 DragLink,
3189
3190 DragCopy,
3193
3194 ContextualMenu,
3197}
3198
3199#[derive(Clone, Debug, Eq, PartialEq)]
3201pub struct ClipboardItem {
3202 pub entries: Vec<ClipboardEntry>,
3204}
3205
3206#[derive(Clone, Debug, PartialEq, Eq)]
3211pub enum ClipboardReadError {
3212 Unavailable,
3216 Denied(String),
3219 UnsupportedContent,
3222}
3223
3224impl std::fmt::Display for ClipboardReadError {
3225 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3226 match self {
3227 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3228 Self::Denied(message) => {
3229 write!(formatter, "clipboard access was denied: {message}")
3230 }
3231 Self::UnsupportedContent => {
3232 formatter.write_str("the clipboard contents are unsupported")
3233 }
3234 }
3235 }
3236}
3237
3238impl std::error::Error for ClipboardReadError {}
3239
3240#[derive(Clone, Debug, Eq, PartialEq)]
3242pub enum ClipboardEntry {
3243 String(ClipboardString),
3245 Image(Image),
3247 ExternalPaths(crate::ExternalPaths),
3249}
3250
3251impl ClipboardItem {
3252 pub fn new_string(text: String) -> Self {
3254 Self {
3255 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3256 }
3257 }
3258
3259 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3261 Self {
3262 entries: vec![ClipboardEntry::String(ClipboardString {
3263 text,
3264 metadata: Some(metadata),
3265 })],
3266 }
3267 }
3268
3269 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3271 Self {
3272 entries: vec![ClipboardEntry::String(
3273 ClipboardString::new(text).with_json_metadata(metadata),
3274 )],
3275 }
3276 }
3277
3278 pub fn new_image(image: &Image) -> Self {
3280 Self {
3281 entries: vec![ClipboardEntry::Image(image.clone())],
3282 }
3283 }
3284
3285 pub fn text(&self) -> Option<String> {
3288 let mut answer = String::new();
3289
3290 for entry in self.entries.iter() {
3291 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3292 answer.push_str(text);
3293 }
3294 }
3295
3296 if answer.is_empty() {
3297 for entry in self.entries.iter() {
3298 if let ClipboardEntry::ExternalPaths(paths) = entry {
3299 for path in &paths.0 {
3300 use std::fmt::Write as _;
3301 _ = write!(answer, "{}", path.display());
3302 }
3303 }
3304 }
3305 }
3306
3307 if !answer.is_empty() {
3308 Some(answer)
3309 } else {
3310 None
3311 }
3312 }
3313
3314 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3316 pub fn metadata(&self) -> Option<&String> {
3317 match self.entries().first() {
3318 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3319 clipboard_string.metadata.as_ref()
3320 }
3321 _ => None,
3322 }
3323 }
3324
3325 pub fn entries(&self) -> &[ClipboardEntry] {
3327 &self.entries
3328 }
3329
3330 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3332 self.entries.into_iter()
3333 }
3334}
3335
3336impl From<ClipboardString> for ClipboardEntry {
3337 fn from(value: ClipboardString) -> Self {
3338 Self::String(value)
3339 }
3340}
3341
3342impl From<String> for ClipboardEntry {
3343 fn from(value: String) -> Self {
3344 Self::from(ClipboardString::from(value))
3345 }
3346}
3347
3348impl From<Image> for ClipboardEntry {
3349 fn from(value: Image) -> Self {
3350 Self::Image(value)
3351 }
3352}
3353
3354impl From<ClipboardEntry> for ClipboardItem {
3355 fn from(value: ClipboardEntry) -> Self {
3356 Self {
3357 entries: vec![value],
3358 }
3359 }
3360}
3361
3362impl From<String> for ClipboardItem {
3363 fn from(value: String) -> Self {
3364 Self::from(ClipboardEntry::from(value))
3365 }
3366}
3367
3368impl From<Image> for ClipboardItem {
3369 fn from(value: Image) -> Self {
3370 Self::from(ClipboardEntry::from(value))
3371 }
3372}
3373
3374#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3376pub enum ImageFormat {
3377 Png,
3382 Jpeg,
3384 Webp,
3386 Gif,
3388 Svg,
3390 Bmp,
3392 Tiff,
3394 Ico,
3396 Pnm,
3398}
3399
3400impl ImageFormat {
3401 pub const fn mime_type(self) -> &'static str {
3403 match self {
3404 ImageFormat::Png => "image/png",
3405 ImageFormat::Jpeg => "image/jpeg",
3406 ImageFormat::Webp => "image/webp",
3407 ImageFormat::Gif => "image/gif",
3408 ImageFormat::Svg => "image/svg+xml",
3409 ImageFormat::Bmp => "image/bmp",
3410 ImageFormat::Tiff => "image/tiff",
3411 ImageFormat::Ico => "image/ico",
3412 ImageFormat::Pnm => "image/x-portable-anymap",
3413 }
3414 }
3415
3416 pub const fn extension(self) -> &'static str {
3418 match self {
3419 ImageFormat::Png => "png",
3420 ImageFormat::Jpeg => "jpg",
3421 ImageFormat::Webp => "webp",
3422 ImageFormat::Gif => "gif",
3423 ImageFormat::Svg => "svg",
3424 ImageFormat::Bmp => "bmp",
3425 ImageFormat::Tiff => "tiff",
3426 ImageFormat::Ico => "ico",
3427 ImageFormat::Pnm => "pnm",
3428 }
3429 }
3430
3431 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3433 use strum::IntoEnumIterator;
3434 Self::iter()
3435 .find(|format| format.mime_type() == mime_type)
3436 .or_else(|| Self::from_mime_type_alias(mime_type))
3437 }
3438
3439 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3443 match mime_type {
3444 "image/jpg" => Some(Self::Jpeg),
3445 "image/tif" => Some(Self::Tiff),
3446 _ => None,
3447 }
3448 }
3449}
3450
3451#[derive(Clone, Debug, PartialEq, Eq)]
3453pub struct Image {
3454 pub format: ImageFormat,
3456 pub bytes: Vec<u8>,
3458 pub id: u64,
3460}
3461
3462pub(crate) fn decode_static_image(
3463 bytes: &[u8],
3464 format: image::ImageFormat,
3465) -> Result<SmallVec<[Frame; 1]>> {
3466 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3467 .into_decoder()
3468 .context("creating image decoder")?;
3469 decode_static_image_from_decoder(decoder)
3470}
3471
3472pub(crate) fn decode_static_image_from_decoder(
3473 mut decoder: impl image::ImageDecoder,
3474) -> Result<SmallVec<[Frame; 1]>> {
3475 let orientation = decoder
3476 .orientation()
3477 .context("reading decoder's orientation")?;
3478 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3479 image.apply_orientation(orientation);
3480
3481 let mut data = image.into_rgba8();
3482 for pixel in data.chunks_exact_mut(4) {
3483 pixel.swap(0, 2);
3484 }
3485
3486 Ok(SmallVec::from_elem(Frame::new(data), 1))
3487}
3488
3489fn decode_animated_frames<'a>(
3490 decoder: impl image::AnimationDecoder<'a>,
3491 format_name: &str,
3492) -> Result<SmallVec<[Frame; 1]>> {
3493 let mut frames = SmallVec::new();
3494
3495 for frame in decoder.into_frames() {
3496 match frame {
3497 Ok(mut frame) => {
3498 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3500 pixel.swap(0, 2);
3501 }
3502 frames.push(frame);
3503 }
3504 Err(err) => {
3505 log::debug!("Skipping {format_name} frame due to decode error: {err}");
3506 }
3507 }
3508 }
3509
3510 if frames.is_empty() {
3511 anyhow::bail!("{format_name} could not be decoded: all frames failed");
3512 }
3513
3514 Ok(frames)
3515}
3516
3517pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3518 let decoder = GifDecoder::new(Cursor::new(bytes))?;
3519 decode_animated_frames(decoder, "GIF")
3520}
3521
3522pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3523 let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
3524
3525 if decoder.has_animation() {
3526 let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
3527 decode_animated_frames(decoder, "WebP")
3528 } else {
3529 decode_static_image_from_decoder(decoder)
3530 }
3531}
3532
3533impl Hash for Image {
3534 fn hash<H: Hasher>(&self, state: &mut H) {
3535 state.write_u64(self.id);
3536 }
3537}
3538
3539impl Image {
3540 pub fn empty() -> Self {
3542 Self::from_bytes(ImageFormat::Png, Vec::new())
3543 }
3544
3545 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3547 Self {
3548 id: hash(&bytes),
3549 format,
3550 bytes,
3551 }
3552 }
3553
3554 pub fn id(&self) -> u64 {
3556 self.id
3557 }
3558
3559 pub fn use_render_image(
3561 self: Arc<Self>,
3562 window: &mut Window,
3563 cx: &mut App,
3564 ) -> Option<Arc<RenderImage>> {
3565 ImageSource::Image(self)
3566 .use_data(None, window, cx)
3567 .and_then(|result| result.ok())
3568 }
3569
3570 pub fn get_render_image(
3572 self: Arc<Self>,
3573 window: &mut Window,
3574 cx: &mut App,
3575 ) -> Option<Arc<RenderImage>> {
3576 ImageSource::Image(self)
3577 .get_data(None, window, cx)
3578 .and_then(|result| result.ok())
3579 }
3580
3581 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3583 ImageSource::Image(self).remove_asset(cx);
3584 }
3585
3586 #[cfg(any(test, feature = "test-support"))]
3589 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3590 ImageSource::Image(self.clone()).is_asset_cached(cx)
3591 }
3592
3593 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3595 let frames = match self.format {
3596 ImageFormat::Gif => decode_gif_image(&self.bytes)?,
3597 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3598 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3599 ImageFormat::Webp => decode_webp_image(&self.bytes)?,
3600 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3601 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3602 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3603 ImageFormat::Svg => {
3604 return svg_renderer
3605 .render_single_frame(&self.bytes, 1.0)
3606 .map_err(Into::into);
3607 }
3608 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3609 };
3610
3611 Ok(Arc::new(RenderImage::new(frames)))
3612 }
3613
3614 pub fn format(&self) -> ImageFormat {
3616 self.format
3617 }
3618
3619 pub fn bytes(&self) -> &[u8] {
3621 self.bytes.as_slice()
3622 }
3623}
3624
3625#[derive(Clone, Debug, Eq, PartialEq)]
3627pub struct ClipboardString {
3628 pub text: String,
3630 pub metadata: Option<String>,
3632}
3633
3634impl ClipboardString {
3635 pub fn new(text: String) -> Self {
3637 Self {
3638 text,
3639 metadata: None,
3640 }
3641 }
3642
3643 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3646 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3647 self
3648 }
3649
3650 pub fn text(&self) -> &String {
3652 &self.text
3653 }
3654
3655 pub fn into_text(self) -> String {
3657 self.text
3658 }
3659
3660 pub fn metadata_json<T>(&self) -> Option<T>
3662 where
3663 T: for<'a> Deserialize<'a>,
3664 {
3665 self.metadata
3666 .as_ref()
3667 .and_then(|m| serde_json::from_str(m).ok())
3668 }
3669
3670 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3671 pub fn text_hash(text: &str) -> u64 {
3673 let mut hasher = SeaHasher::new();
3674 text.hash(&mut hasher);
3675 hasher.finish()
3676 }
3677}
3678
3679impl From<String> for ClipboardString {
3680 fn from(value: String) -> Self {
3681 Self {
3682 text: value,
3683 metadata: None,
3684 }
3685 }
3686}
3687
3688#[cfg(test)]
3689mod image_tests {
3690 use super::*;
3691 use std::sync::Arc;
3692
3693 #[test]
3694 fn test_image_to_image_data_applies_exif_orientation() {
3695 let image = Image::from_bytes(
3696 ImageFormat::Jpeg,
3697 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3698 );
3699
3700 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3701
3702 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3703
3704 let bytes = render_image.as_bytes(0).unwrap();
3705 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3706 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3707 }
3708
3709 #[test]
3710 fn test_svg_image_to_image_data_converts_to_bgra() {
3711 let image = Image::from_bytes(
3712 ImageFormat::Svg,
3713 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3714<rect width="1" height="1" fill="#38BDF8"/>
3715</svg>"##
3716 .to_vec(),
3717 );
3718
3719 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3720 let bytes = render_image.as_bytes(0).unwrap();
3721
3722 for pixel in bytes.chunks_exact(4) {
3723 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3724 }
3725 }
3726
3727 #[test]
3728 fn test_animated_webp_image_to_image_data_decodes_frames() {
3729 const ANIMATED_WEBP: &[u8] = &[
3731 82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
3732 0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
3733 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 2, 86, 80, 56, 32, 48, 0,
3734 0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
3735 176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
3736 128, 255, 248, 242, 0, 0, 0, 65, 78, 77, 70, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3737 0, 0, 100, 0, 0, 0, 86, 80, 56, 32, 44, 0, 0, 0, 148, 1, 0, 157, 1, 42, 1, 0, 1, 0, 0,
3738 0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
3739 31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
3740 ];
3741
3742 let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
3743 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3744
3745 assert_eq!(render_image.frame_count(), 2);
3746 assert_eq!(render_image.size(0), size(1.into(), 1.into()));
3747 assert_eq!(
3748 Duration::from(render_image.delay(0)),
3749 Duration::from_millis(100)
3750 );
3751 assert_eq!(
3752 Duration::from(render_image.delay(1)),
3753 Duration::from_millis(100)
3754 );
3755 }
3756}
3757
3758#[cfg(test)]
3759mod atlas_tests {
3760 use super::*;
3761
3762 const TILE_SIZE: Size<DevicePixels> = Size {
3763 width: DevicePixels(1),
3764 height: DevicePixels(1),
3765 };
3766
3767 #[derive(Default)]
3768 struct RecordingAtlasBackend {
3769 insert_calls: u32,
3770 fail_next_insert: bool,
3771 removed_tiles: Vec<AtlasTile>,
3772 }
3773
3774 impl AtlasBackend for RecordingAtlasBackend {
3775 fn insert(
3776 &mut self,
3777 kind: AtlasTextureKind,
3778 size: Size<DevicePixels>,
3779 _bytes: &[u8],
3780 ) -> Result<AtlasTile> {
3781 self.insert_calls += 1;
3782 if std::mem::take(&mut self.fail_next_insert) {
3783 anyhow::bail!("backend failed");
3784 }
3785 Ok(AtlasTile {
3786 texture_id: AtlasTextureId { index: 0, kind },
3787 tile_id: TileId(self.insert_calls),
3788 padding: 0,
3789 bounds: Bounds {
3790 origin: Point::default(),
3791 size,
3792 },
3793 })
3794 }
3795
3796 fn remove(&mut self, tile: AtlasTile) {
3797 self.removed_tiles.push(tile);
3798 }
3799 }
3800
3801 fn image_key(image_id: usize) -> AtlasKey {
3802 AtlasKey::Image(RenderImageParams {
3803 image_id: crate::ImageId(image_id),
3804 frame_index: 0,
3805 })
3806 }
3807
3808 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3809 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3810 }
3811
3812 #[test]
3813 fn only_successful_inserts_are_cached() -> Result<()> {
3814 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3815 let key = image_key(1);
3816
3817 assert_eq!(
3818 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3819 None
3820 );
3821 state
3822 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3823 .expect_err("builder error should propagate");
3824 assert!(!state.contains(&key));
3825 assert_eq!(state.backend.insert_calls, 0);
3826
3827 state.backend.fail_next_insert = true;
3828 state
3829 .get_or_insert_with(key.clone(), &mut build_tile)
3830 .expect_err("backend error should propagate");
3831 assert!(!state.contains(&key));
3832 assert_eq!(state.backend.insert_calls, 1);
3833
3834 let tile = state
3835 .get_or_insert_with(key.clone(), &mut build_tile)?
3836 .context("builder should produce a tile")?;
3837 assert_eq!(tile.texture_id.kind, key.texture_kind());
3838 assert_eq!(
3839 state.get_or_insert_with(key.clone(), &mut || {
3840 anyhow::bail!("cache hit must not call the builder")
3841 })?,
3842 Some(tile)
3843 );
3844 assert!(state.contains(&key));
3845 assert_eq!(state.backend.insert_calls, 2);
3846 Ok(())
3847 }
3848
3849 #[test]
3850 fn remove_and_clear_invalidate_keys() -> Result<()> {
3851 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3852 let key = image_key(1);
3853 let other_key = image_key(2);
3854 let tile = state
3855 .get_or_insert_with(key.clone(), &mut build_tile)?
3856 .context("builder should produce a tile")?;
3857 state
3858 .get_or_insert_with(other_key.clone(), &mut build_tile)?
3859 .context("builder should produce another tile")?;
3860
3861 state.remove(&key);
3862 state.remove(&key);
3863 assert!(!state.contains(&key));
3864 assert!(state.contains(&other_key));
3865 assert_eq!(state.backend.removed_tiles, vec![tile]);
3866
3867 let mut reset_calls = 0;
3868 state.clear(|_| reset_calls += 1);
3869 assert_eq!(reset_calls, 1);
3870 assert!(!state.contains(&other_key));
3871 assert_eq!(state.backend.removed_tiles, vec![tile]);
3872 Ok(())
3873 }
3874}
3875
3876#[cfg(test)]
3877mod frame_signal_tests {
3878 use super::*;
3879
3880 #[cfg(feature = "profiler")]
3881 #[test]
3882 fn coalesced_signals_retain_the_earliest_until_drained() {
3883 for (first_source, later_source) in [
3884 (
3885 FrameRequestSource::NativeCallback,
3886 FrameRequestSource::LocalSchedule,
3887 ),
3888 (
3889 FrameRequestSource::LocalSchedule,
3890 FrameRequestSource::NativeCallback,
3891 ),
3892 ] {
3893 let signal = PlatformFrameSignal::new();
3894 let first =
3895 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3896 assert_eq!(signal.take(), None);
3897 signal.record(first + Duration::from_millis(16), later_source);
3898 signal.record(first, first_source);
3899 signal.record(first + Duration::from_millis(32), later_source);
3900 assert_eq!(signal.take(), Some((first, first_source)));
3901 assert_eq!(signal.take(), None);
3902 let next = first + Duration::from_millis(48);
3903 signal.record(next, later_source);
3904 assert_eq!(signal.take(), Some((next, later_source)));
3905 }
3906 }
3907
3908 #[cfg(not(feature = "profiler"))]
3909 #[test]
3910 fn disabled_profiling_does_not_capture_or_store_timestamps() {
3911 let captured = PlatformFrameSignal::capture(|| {
3912 panic!("profiler-disabled builds must not evaluate the capture closure");
3913 });
3914 assert_eq!(captured, None);
3915 let signal = PlatformFrameSignal::new();
3916 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3917 assert_eq!(signal.take(), None);
3918 }
3919}
3920
3921#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3922mod tests {
3923 use super::*;
3924 use std::collections::HashSet;
3925
3926 #[test]
3927 fn test_refresh_interval_from_hz() {
3928 assert_eq!(
3929 refresh_interval_from_hz(50.0),
3930 Some(Duration::from_millis(20))
3931 );
3932 assert_eq!(
3933 refresh_interval_from_hz(120.0),
3934 Some(Duration::from_secs(1) / 120)
3935 );
3936 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
3937 assert_eq!(refresh_interval_from_hz(unknown), None);
3938 }
3939 }
3940
3941 #[test]
3942 fn test_window_button_layout_parse_standard() {
3943 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3944 assert_eq!(
3945 layout.left,
3946 [
3947 Some(WindowButton::Close),
3948 Some(WindowButton::Minimize),
3949 None
3950 ]
3951 );
3952 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3953 }
3954
3955 #[test]
3956 fn test_window_button_layout_parse_right_only() {
3957 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3958 assert_eq!(layout.left, [None, None, None]);
3959 assert_eq!(
3960 layout.right,
3961 [
3962 Some(WindowButton::Minimize),
3963 Some(WindowButton::Maximize),
3964 Some(WindowButton::Close)
3965 ]
3966 );
3967 }
3968
3969 #[test]
3970 fn test_window_button_layout_parse_left_only() {
3971 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3972 assert_eq!(
3973 layout.left,
3974 [
3975 Some(WindowButton::Close),
3976 Some(WindowButton::Minimize),
3977 Some(WindowButton::Maximize)
3978 ]
3979 );
3980 assert_eq!(layout.right, [None, None, None]);
3981 }
3982
3983 #[test]
3984 fn test_window_button_layout_parse_with_whitespace() {
3985 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3986 assert_eq!(
3987 layout.left,
3988 [
3989 Some(WindowButton::Close),
3990 Some(WindowButton::Minimize),
3991 None
3992 ]
3993 );
3994 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3995 }
3996
3997 #[test]
3998 fn test_window_button_layout_parse_empty() {
3999 let layout = WindowButtonLayout::parse("").unwrap();
4000 assert_eq!(layout.left, [None, None, None]);
4001 assert_eq!(layout.right, [None, None, None]);
4002 }
4003
4004 #[test]
4005 fn test_window_button_layout_parse_intentionally_empty() {
4006 let layout = WindowButtonLayout::parse(":").unwrap();
4007 assert_eq!(layout.left, [None, None, None]);
4008 assert_eq!(layout.right, [None, None, None]);
4009 }
4010
4011 #[test]
4012 fn test_window_button_layout_parse_invalid_buttons() {
4013 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
4014 assert_eq!(
4015 layout.left,
4016 [
4017 Some(WindowButton::Close),
4018 Some(WindowButton::Minimize),
4019 None
4020 ]
4021 );
4022 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4023 }
4024
4025 #[test]
4026 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
4027 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
4028 assert_eq!(
4029 layout.right,
4030 [
4031 Some(WindowButton::Close),
4032 Some(WindowButton::Minimize),
4033 None
4034 ]
4035 );
4036 assert_eq!(layout.format(), ":close,minimize");
4037 }
4038
4039 #[test]
4040 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
4041 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
4042 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4043 assert_eq!(
4044 layout.right,
4045 [
4046 Some(WindowButton::Maximize),
4047 Some(WindowButton::Minimize),
4048 None
4049 ]
4050 );
4051
4052 let button_ids: Vec<_> = layout
4053 .left
4054 .iter()
4055 .chain(layout.right.iter())
4056 .flatten()
4057 .map(WindowButton::id)
4058 .collect();
4059 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4060 assert_eq!(unique_button_ids.len(), button_ids.len());
4061 assert_eq!(layout.format(), "close:maximize,minimize");
4062 }
4063
4064 #[test]
4065 fn test_window_button_layout_parse_gnome_style() {
4066 let layout = WindowButtonLayout::parse("close").unwrap();
4067 assert_eq!(layout.left, [None, None, None]);
4068 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4069 }
4070
4071 #[test]
4072 fn test_window_button_layout_parse_elementary_style() {
4073 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4074 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4075 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4076 }
4077
4078 #[test]
4079 fn test_window_button_layout_round_trip() {
4080 let cases = [
4081 "close:minimize,maximize",
4082 "minimize,maximize,close:",
4083 ":close",
4084 "close:",
4085 "close:maximize",
4086 ":",
4087 ];
4088
4089 for case in cases {
4090 let layout = WindowButtonLayout::parse(case).unwrap();
4091 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4092 }
4093 }
4094
4095 #[test]
4096 fn test_window_button_layout_linux_default() {
4097 let layout = WindowButtonLayout::linux_default();
4098 assert_eq!(layout.left, [None, None, None]);
4099 assert_eq!(
4100 layout.right,
4101 [
4102 Some(WindowButton::Minimize),
4103 Some(WindowButton::Maximize),
4104 Some(WindowButton::Close)
4105 ]
4106 );
4107
4108 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4109 assert_eq!(round_tripped, layout);
4110 }
4111
4112 #[test]
4113 fn test_window_button_layout_parse_all_invalid() {
4114 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4115 }
4116}