1mod app_menu;
3mod keyboard;
4mod keystroke;
5mod platform_info;
6
7#[cfg(all(target_os = "linux", feature = "wayland"))]
8#[expect(missing_docs)]
9pub mod layer_shell;
10
11pub mod popup;
13
14#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
15mod threaded_dispatcher;
16
17#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
18mod test;
19
20#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
21mod visual_test;
22
23#[cfg(all(
24 feature = "screen-capture",
25 any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
26))]
27pub mod scap_screen_capture;
28
29#[cfg(all(
30 any(target_os = "windows", target_os = "linux"),
31 feature = "screen-capture"
32))]
33pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
34#[cfg(not(feature = "screen-capture"))]
35pub(crate) type PlatformScreenCaptureFrame = ();
36#[cfg(all(target_os = "macos", feature = "screen-capture"))]
37pub(crate) type PlatformScreenCaptureFrame =
38 objc2_core_foundation::CFRetained<objc2_core_video::CVImageBuffer>;
39
40use crate::{
41 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds, Corners,
42 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
43 FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap,
44 LineLayout, MissingGlyphSink, Pixels, PlatformGestures, PlatformInput, Point, Priority,
45 RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph,
46 ShapedRun, SharedString, Size, SvgRenderer, SystemWindowTab, Task, Window, WindowControlArea,
47 hash, point, px, size,
48};
49#[cfg(any(target_os = "linux", target_os = "freebsd"))]
50use anyhow::bail;
51use anyhow::{Context as _, Result};
52use async_task::Runnable;
53use collections::FxHashMap;
54use futures::channel::oneshot;
55#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
56use image::RgbaImage;
57use image::codecs::{gif::GifDecoder, webp::WebPDecoder};
58use image::{DynamicImage, Frame, Rgba};
59use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
60use scheduler::Instant;
61pub use scheduler::RunnableMeta;
62use schemars::JsonSchema;
63use seahash::SeaHasher;
64use serde::{Deserialize, Serialize};
65use smallvec::SmallVec;
66use std::borrow::Cow;
67use std::collections::hash_map::Entry;
68use std::hash::{Hash, Hasher};
69use std::io::Cursor;
70use std::ops;
71use std::time::Duration;
72use std::{
73 ffi::OsString,
74 fmt::{self, Debug},
75 ops::Range,
76 path::{Path, PathBuf},
77 rc::Rc,
78 sync::Arc,
79};
80use strum::EnumIter;
81use uuid::Uuid;
82
83pub use app_menu::*;
84pub use keyboard::*;
85pub use keystroke::*;
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum WindowVisibility {
109 Visible,
112 Hidden,
115}
116
117impl WindowVisibility {
118 pub fn is_visible(self) -> bool {
120 self == Self::Visible
121 }
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
127#[non_exhaustive]
128pub enum DisplayEvent {
129 Added(DisplayId),
131 Removed(DisplayId),
134 Changed {
136 id: DisplayId,
138 changes: DisplayChanges,
140 },
141}
142
143bitflags::bitflags! {
144 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
146 pub struct DisplayChanges: u8 {
147 const BOUNDS = 1 << 0;
149 const REFRESH_INTERVAL = 1 << 1;
151 }
152}
153
154pub fn refresh_interval_from_hz(hertz: f64) -> Option<Duration> {
157 (hertz.is_finite() && hertz > 0.0).then(|| Duration::from_secs_f64(1.0 / hertz))
158}
159
160#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
167pub enum ActivationPolicy {
168 #[default]
170 Regular,
171 Accessory,
173}
174
175#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
176pub(crate) use test::*;
177
178#[cfg(any(test, feature = "test-support"))]
179pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
180
181#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
182pub use threaded_dispatcher::ThreadedDispatcher;
183
184#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
185pub use visual_test::VisualTestPlatform;
186
187pub struct ActivityGuard {
189 _release: gpui_util::Deferred<Box<dyn FnOnce() + Send>>,
190}
191
192impl ActivityGuard {
193 pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
195 Self {
196 _release: gpui_util::defer(Box::new(release)),
197 }
198 }
199
200 pub fn noop() -> Self {
202 Self::new(|| {})
203 }
204}
205
206#[cfg(any(target_os = "linux", target_os = "freebsd"))]
210#[inline]
211pub fn guess_compositor() -> &'static str {
212 if std::env::var_os("ZED_HEADLESS").is_some() {
213 return "headless";
214 }
215 GraphicalEnvironment::detect().guess_compositor()
216}
217
218#[cfg(any(target_os = "linux", target_os = "freebsd"))]
227#[derive(Clone, Debug, Default)]
228pub struct GraphicalEnvironment {
229 pub wayland_display: Option<OsString>,
231 pub x11_display: Option<OsString>,
233 pub xdg_runtime_dir: Option<OsString>,
235 pub current_desktop: Option<OsString>,
240 pub activation_token: Option<String>,
246}
247
248#[cfg(target_os = "windows")]
254#[derive(Clone, Debug, Default)]
255pub struct GraphicalEnvironment {
256 pub session_id: Option<u32>,
259}
260
261#[cfg(target_os = "windows")]
262impl GraphicalEnvironment {
263 pub fn detect() -> Self {
265 let mut session_id = 0;
266 let result = unsafe {
268 windows::Win32::System::RemoteDesktop::ProcessIdToSessionId(
269 windows::Win32::System::Threading::GetCurrentProcessId(),
270 &mut session_id,
271 )
272 };
273 Self {
274 session_id: result.is_ok().then_some(session_id),
275 }
276 }
277
278 pub fn apply_to(&self, _command: &mut std::process::Command) {}
281
282 pub fn desktop_environment(&self) -> Option<String> {
284 None
285 }
286}
287
288#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
290#[derive(Clone, Debug, Default)]
291pub struct GraphicalEnvironment;
292
293#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
294impl GraphicalEnvironment {
295 pub fn detect() -> Self {
297 Self
298 }
299
300 pub fn apply_to(&self, _command: &mut std::process::Command) {}
302
303 pub fn desktop_environment(&self) -> Option<String> {
305 None
306 }
307}
308
309#[derive(Clone, Debug)]
311pub enum WindowingRequest {
312 Headless,
314 Windowed(GraphicalEnvironment),
316}
317
318#[cfg(any(target_os = "linux", target_os = "freebsd"))]
319impl GraphicalEnvironment {
320 pub fn detect() -> Self {
325 Self {
326 wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
327 x11_display: std::env::var_os("DISPLAY"),
328 xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
329 current_desktop: std::env::var_os("XDG_CURRENT_DESKTOP"),
330 activation_token: None,
331 }
332 }
333
334 pub fn apply_to(&self, command: &mut std::process::Command) {
338 for (name, value) in [
339 ("WAYLAND_DISPLAY", &self.wayland_display),
340 ("DISPLAY", &self.x11_display),
341 ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
342 ] {
343 match value {
344 Some(value) => command.env(name, value),
345 None => command.env_remove(name),
346 };
347 }
348 }
349
350 pub fn desktop_environment(&self) -> Option<String> {
355 self.current_desktop
356 .as_ref()
357 .and_then(|desktop| desktop.to_str())
358 .filter(|desktop| !desktop.is_empty())
359 .map(str::to_owned)
360 }
361
362 pub fn guess_compositor(&self) -> &'static str {
366 let is_set =
367 |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
368 if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
369 "Wayland"
370 } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
371 "X11"
372 } else {
373 "headless"
374 }
375 }
376}
377
378#[cfg(any(target_os = "linux", target_os = "freebsd"))]
379bitflags::bitflags! {
380 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
382 pub struct WindowingModes: u8 {
383 const WAYLAND = 1 << 0;
385 const X11 = 1 << 1;
387 const HEADLESS = 1 << 2;
389 }
390}
391
392pub use platform_info::{OperatingSystem, PlatformInfo, PlatformTarget};
393
394#[expect(missing_docs)]
395pub trait Platform: 'static {
396 fn platform_info(&self) -> PlatformInfo;
398
399 fn background_executor(&self) -> BackgroundExecutor;
400 fn foreground_executor(&self) -> ForegroundExecutor;
401 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
402
403 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
404 fn quit(&self);
405 fn set_initial_windowing(&self, _request: WindowingRequest) {}
410 fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
411 Task::ready(Err(anyhow::anyhow!(
412 "this platform cannot switch between headless and windowed modes"
413 )))
414 }
415 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
416 fn activate(&self, ignoring_other_apps: bool);
417 fn set_activation_policy(&self, _policy: ActivationPolicy) {}
419 fn hide(&self);
420 fn hide_other_apps(&self);
421 fn unhide_other_apps(&self);
422
423 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
424 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
425 fn on_displays_changed(&self, callback: Box<dyn FnMut()>);
430 fn active_window(&self) -> Option<AnyWindowHandle>;
431 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
432 None
433 }
434
435 fn is_screen_capture_supported(&self) -> bool {
436 false
437 }
438
439 fn screen_capture_sources(
440 &self,
441 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
442 let (sources_tx, sources_rx) = oneshot::channel();
443 sources_tx
444 .send(Err(anyhow::anyhow!(
445 "gpui was compiled without the screen-capture feature"
446 )))
447 .ok();
448 sources_rx
449 }
450
451 fn open_window(
452 &self,
453 handle: AnyWindowHandle,
454 options: WindowParams,
455 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
456
457 fn window_appearance(&self) -> WindowAppearance;
459
460 fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
469
470 fn button_layout(&self) -> Option<WindowButtonLayout> {
472 None
473 }
474
475 fn open_url(&self, url: &str);
476 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
477 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
478
479 fn prompt_for_paths(
480 &self,
481 options: PathPromptOptions,
482 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
483 fn prompt_for_new_path(
484 &self,
485 directory: &Path,
486 suggested_name: Option<&str>,
487 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
488 fn can_select_mixed_files_and_dirs(&self) -> bool;
489 fn reveal_path(&self, path: &Path);
490 fn open_with_system(&self, path: &Path);
491
492 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
493 fn on_reopen(&self, callback: Box<dyn FnMut()>);
494 fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
496 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
498
499 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
509
510 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
515
516 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
520 None
521 }
522
523 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
524 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
525 None
526 }
527
528 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
529 fn perform_dock_menu_action(&self, _action: usize) {}
530 fn add_recent_document(&self, _path: &Path) {}
531 fn update_jump_list(
532 &self,
533 _menus: Vec<MenuItem>,
534 _entries: Vec<SmallVec<[PathBuf; 2]>>,
535 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
536 Task::ready(Vec::new())
537 }
538 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
539 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
540 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
541
542 fn debug_state(&self) -> serde_json::Value {
544 serde_json::Value::Null
545 }
546
547 fn thermal_state(&self) -> ThermalState;
548 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
549 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
550
551 fn power_mode(&self) -> PowerMode {
554 PowerMode::Unknown
555 }
556 fn on_power_mode_change(&self, _callback: Box<dyn FnMut()>) {}
558
559 fn set_app_identity(&self, identifier: &str, name: &str) {
566 _ = (identifier, name);
567 }
568
569 fn show_system_notification(&self, notification: SystemNotification) {
576 _ = notification;
577 }
578
579 fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
587 _ = tag;
588 Task::ready(())
589 }
590
591 fn on_system_notification_response(
597 &self,
598 callback: Box<dyn FnMut(SystemNotificationResponse)>,
599 ) {
600 _ = callback;
601 }
602
603 fn compositor_name(&self) -> &'static str {
604 ""
605 }
606 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
609 None
610 }
611 fn app_path(&self) -> Result<PathBuf>;
612 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
613
614 fn set_cursor_style(&self, style: CursorStyle);
615
616 fn hide_cursor_until_mouse_moves(&self);
619
620 fn is_cursor_visible(&self) -> bool;
622
623 fn should_auto_hide_scrollbars(&self) -> bool;
624
625 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
626 fn write_to_clipboard(&self, item: ClipboardItem);
627
628 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
636 Task::ready(Ok(self.read_from_clipboard()))
637 }
638
639 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
640 fn read_from_primary(&self) -> Option<ClipboardItem>;
641 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
642 fn write_to_primary(&self, item: ClipboardItem);
643
644 #[cfg(target_os = "macos")]
645 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
646 #[cfg(target_os = "macos")]
647 fn write_to_find_pasteboard(&self, item: ClipboardItem);
648
649 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
650
651 #[cfg(target_os = "macos")]
655 fn write_credentials_if_not_exists(
656 &self,
657 _url: &str,
658 _username: &str,
659 _password: &[u8],
660 ) -> Task<Result<bool>> {
661 Task::ready(Err(anyhow::anyhow!(
662 "this platform does not support atomic credential writes"
663 )))
664 }
665
666 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
667 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
668
669 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
670 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
671 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
672}
673
674pub trait PlatformDisplay: Debug {
676 fn id(&self) -> DisplayId;
678
679 fn uuid(&self) -> Result<Uuid>;
682
683 fn bounds(&self) -> Bounds<Pixels>;
685
686 fn refresh_interval(&self) -> Option<Duration>;
693
694 fn visible_bounds(&self) -> Bounds<Pixels> {
698 self.bounds()
699 }
700
701 fn default_bounds(&self) -> Bounds<Pixels> {
703 let bounds = self.bounds();
704 let center = bounds.center();
705 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
706
707 let offset = clipped_window_size / 2.0;
708 let origin = point(center.x - offset.width, center.y - offset.height);
709 Bounds::new(origin, clipped_window_size)
710 }
711}
712
713#[derive(Clone, Debug, PartialEq, Eq)]
716pub struct SystemNotification {
717 pub tag: SharedString,
721 pub title: SharedString,
723 pub body: SharedString,
725 pub actions: Vec<SystemNotificationAction>,
728}
729
730#[derive(Clone, Debug, PartialEq, Eq, Hash)]
732pub struct SystemNotificationAction {
733 pub id: SharedString,
736 pub label: SharedString,
738}
739
740#[derive(Clone, Debug, PartialEq, Eq)]
742pub struct SystemNotificationResponse {
743 pub tag: SharedString,
745 pub action_id: Option<SharedString>,
748}
749
750#[derive(Debug, Clone, Copy, PartialEq, Eq)]
752pub enum PowerMode {
753 Unknown,
756 LowPower,
758 Balanced,
760 HighPower,
762}
763
764#[derive(Debug, Clone, Copy, PartialEq, Eq)]
766pub enum ThermalState {
767 Nominal,
769 Fair,
771 Serious,
773 Critical,
775}
776
777#[derive(Clone)]
779pub struct SourceMetadata {
780 pub id: u64,
782 pub label: Option<SharedString>,
784 pub is_main: Option<bool>,
786 pub resolution: Size<DevicePixels>,
788}
789
790pub trait ScreenCaptureSource {
792 fn metadata(&self) -> Result<SourceMetadata>;
794
795 fn stream(
798 &self,
799 foreground_executor: &ForegroundExecutor,
800 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
801 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
802}
803
804pub trait ScreenCaptureStream {
806 fn metadata(&self) -> Result<SourceMetadata>;
808}
809
810pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
812
813#[derive(PartialEq, Eq, Hash, Copy, Clone)]
815pub struct DisplayId(pub(crate) u64);
816
817impl DisplayId {
818 pub fn new(id: u64) -> Self {
820 Self(id)
821 }
822}
823
824impl From<u64> for DisplayId {
825 fn from(id: u64) -> Self {
826 Self(id)
827 }
828}
829
830impl From<DisplayId> for u64 {
831 fn from(id: DisplayId) -> Self {
832 id.0
833 }
834}
835
836impl Debug for DisplayId {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 write!(f, "DisplayId({})", self.0)
839 }
840}
841
842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
844pub enum ResizeEdge {
845 Top,
847 TopRight,
849 Right,
851 BottomRight,
853 Bottom,
855 BottomLeft,
857 Left,
859 TopLeft,
861}
862
863#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
865pub enum WindowDecorations {
866 #[default]
867 Server,
869 Client,
871}
872
873#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
875pub enum Decorations {
876 #[default]
878 Server,
879 Client {
881 tiling: Tiling,
883 },
884}
885
886#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
888pub struct WindowControls {
889 pub fullscreen: bool,
891 pub maximize: bool,
893 pub minimize: bool,
895 pub window_menu: bool,
897}
898
899impl Default for WindowControls {
900 fn default() -> Self {
901 Self {
903 fullscreen: true,
904 maximize: true,
905 minimize: true,
906 window_menu: true,
907 }
908 }
909}
910
911#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
913pub enum WindowButton {
914 Minimize,
916 Maximize,
918 Close,
920}
921
922impl WindowButton {
923 pub fn id(&self) -> &'static str {
925 match self {
926 WindowButton::Minimize => "minimize",
927 WindowButton::Maximize => "maximize",
928 WindowButton::Close => "close",
929 }
930 }
931
932 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
933 fn index(&self) -> usize {
934 match self {
935 WindowButton::Minimize => 0,
936 WindowButton::Maximize => 1,
937 WindowButton::Close => 2,
938 }
939 }
940}
941
942pub const MAX_BUTTONS_PER_SIDE: usize = 3;
944
945#[derive(Debug, Clone, Copy, PartialEq, Eq)]
950pub struct WindowButtonLayout {
951 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
953 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
955}
956
957#[cfg(any(target_os = "linux", target_os = "freebsd"))]
958impl WindowButtonLayout {
959 pub fn linux_default() -> Self {
961 Self {
962 left: [None; MAX_BUTTONS_PER_SIDE],
963 right: [
964 Some(WindowButton::Minimize),
965 Some(WindowButton::Maximize),
966 Some(WindowButton::Close),
967 ],
968 }
969 }
970
971 pub fn parse(layout_string: &str) -> Result<Self> {
973 fn parse_side(
974 s: &str,
975 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
976 unrecognized: &mut Vec<String>,
977 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
978 let mut result = [None; MAX_BUTTONS_PER_SIDE];
979 let mut i = 0;
980 for name in s.split(',') {
981 let trimmed = name.trim();
982 if trimmed.is_empty() {
983 continue;
984 }
985 let button = match trimmed {
986 "minimize" => Some(WindowButton::Minimize),
987 "maximize" => Some(WindowButton::Maximize),
988 "close" => Some(WindowButton::Close),
989 other => {
990 unrecognized.push(other.to_string());
991 None
992 }
993 };
994 if let Some(button) = button {
995 if seen_buttons[button.index()] {
996 continue;
997 }
998 if let Some(slot) = result.get_mut(i) {
999 *slot = Some(button);
1000 seen_buttons[button.index()] = true;
1001 i += 1;
1002 }
1003 }
1004 }
1005 result
1006 }
1007
1008 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1009 let mut unrecognized = Vec::new();
1010 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1011 let layout = Self {
1012 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1013 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1014 };
1015
1016 if !unrecognized.is_empty()
1017 && layout.left.iter().all(Option::is_none)
1018 && layout.right.iter().all(Option::is_none)
1019 {
1020 bail!(
1021 "button layout string {:?} contains no valid buttons (unrecognized: {})",
1022 layout_string,
1023 unrecognized.join(", ")
1024 );
1025 }
1026
1027 Ok(layout)
1028 }
1029
1030 #[cfg(test)]
1032 pub fn format(&self) -> String {
1033 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1034 buttons
1035 .iter()
1036 .flatten()
1037 .map(|button| match button {
1038 WindowButton::Minimize => "minimize",
1039 WindowButton::Maximize => "maximize",
1040 WindowButton::Close => "close",
1041 })
1042 .collect::<Vec<_>>()
1043 .join(",")
1044 }
1045
1046 format!("{}:{}", format_side(&self.left), format_side(&self.right))
1047 }
1048}
1049
1050#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1052pub struct Tiling {
1053 pub top: bool,
1055 pub left: bool,
1057 pub right: bool,
1059 pub bottom: bool,
1061}
1062
1063impl Tiling {
1064 pub fn tiled() -> Self {
1066 Self {
1067 top: true,
1068 left: true,
1069 right: true,
1070 bottom: true,
1071 }
1072 }
1073
1074 pub fn is_tiled(&self) -> bool {
1076 self.top || self.left || self.right || self.bottom
1077 }
1078}
1079
1080pub struct A11yCallbacks {
1082 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1084 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1086 pub deactivation: Box<dyn Fn() + Send + 'static>,
1088}
1089
1090#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1092pub enum FrameRequestSource {
1093 #[default]
1095 NativeCallback,
1096 LocalSchedule,
1098}
1099
1100#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1101#[expect(missing_docs)]
1102pub struct RequestFrameOptions {
1103 pub require_presentation: bool,
1105 pub force_render: bool,
1107 pub signal_at: Option<Instant>,
1113 pub signal_source: FrameRequestSource,
1115}
1116
1117pub struct PlatformFrameSignal {
1126 #[cfg(feature = "profiler")]
1127 origin: Instant,
1128 #[cfg(feature = "profiler")]
1129 first_signal: std::sync::atomic::AtomicU64,
1130}
1131
1132impl Default for PlatformFrameSignal {
1133 fn default() -> Self {
1134 Self::new()
1135 }
1136}
1137
1138impl PlatformFrameSignal {
1139 pub fn new() -> Self {
1141 Self {
1142 #[cfg(feature = "profiler")]
1143 origin: Instant::now(),
1144 #[cfg(feature = "profiler")]
1145 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1146 }
1147 }
1148
1149 #[inline]
1153 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1154 if cfg!(feature = "profiler") {
1155 Some(capture())
1156 } else {
1157 None
1158 }
1159 }
1160
1161 #[inline]
1163 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1164 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1165 #[cfg(feature = "profiler")]
1166 {
1167 let nanoseconds = at
1168 .saturating_duration_since(self.origin)
1169 .as_nanos()
1170 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1171 let source_bit = match source {
1172 FrameRequestSource::NativeCallback => 0,
1173 FrameRequestSource::LocalSchedule => 1,
1174 };
1175 self.first_signal.fetch_min(
1176 (nanoseconds << 1) | source_bit,
1177 std::sync::atomic::Ordering::Relaxed,
1178 );
1179 }
1180 }
1181
1182 #[inline]
1184 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1185 #[cfg(feature = "profiler")]
1186 {
1187 let signal = self
1188 .first_signal
1189 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1190 (signal != u64::MAX).then(|| {
1191 let source = match signal & 1 {
1192 0 => FrameRequestSource::NativeCallback,
1193 _ => FrameRequestSource::LocalSchedule,
1194 };
1195 (self.origin + Duration::from_nanos(signal >> 1), source)
1196 })
1197 }
1198 #[cfg(not(feature = "profiler"))]
1199 {
1200 None
1201 }
1202 }
1203}
1204
1205#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1218pub enum AppLifecyclePhase {
1219 Active,
1221 Inactive,
1223 Background,
1226 Foreground,
1228 Disconnected,
1232}
1233
1234#[derive(Debug, Clone, Default, PartialEq)]
1241pub struct WindowInsets {
1242 pub safe_area: Edges<Pixels>,
1247 pub ime: Edges<Pixels>,
1251 pub corner_radii: Corners<Pixels>,
1256}
1257
1258impl WindowInsets {
1259 pub fn effective(&self) -> Edges<Pixels> {
1261 Edges {
1262 top: self.safe_area.top.max(self.ime.top),
1263 right: self.safe_area.right.max(self.ime.right),
1264 bottom: self.safe_area.bottom.max(self.ime.bottom),
1265 left: self.safe_area.left.max(self.ime.left),
1266 }
1267 }
1268}
1269
1270#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1272pub enum TextInputStateChange {
1273 FocusGained,
1275 FocusLost,
1277 SelectionChanged,
1279 ContentChanged,
1281}
1282
1283#[expect(missing_docs)]
1284pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1285 fn bounds(&self) -> Bounds<Pixels>;
1286 fn is_maximized(&self) -> bool;
1287 fn window_bounds(&self) -> WindowBounds;
1288 fn content_size(&self) -> Size<Pixels>;
1289 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1295 Bounds::new(Point::default(), self.content_size())
1296 }
1297 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1302 fn prepare_frame(&self) -> bool {
1307 false
1308 }
1309 fn resize(&mut self, size: Size<Pixels>);
1310 fn scale_factor(&self) -> f32;
1311 fn appearance(&self) -> WindowAppearance;
1312 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1313 fn mouse_position(&self) -> Point<Pixels>;
1314 fn modifiers(&self) -> Modifiers;
1315 fn capslock(&self) -> Capslock;
1316 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1317 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1318 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1323 fn prompt(
1324 &self,
1325 level: PromptLevel,
1326 msg: &str,
1327 detail: Option<&str>,
1328 answers: &[PromptButton],
1329 ) -> Option<oneshot::Receiver<usize>>;
1330 fn activate(&self);
1331 fn request_attention(&self) {}
1333 fn is_active(&self) -> bool;
1334 fn visibility(&self) -> WindowVisibility;
1337 fn is_hovered(&self) -> bool;
1338 fn background_appearance(&self) -> WindowBackgroundAppearance;
1339 fn set_title(&mut self, title: &str);
1340 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1341 fn minimize(&self);
1342 fn zoom(&self);
1343 fn toggle_fullscreen(&self);
1344 fn is_fullscreen(&self) -> bool;
1345 fn debug_state(&self) -> serde_json::Value {
1347 serde_json::Value::Null
1348 }
1349 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1350 None
1351 }
1352 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1353 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1354 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1355 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1359 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1360 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1361 fn on_moved(&self, callback: Box<dyn FnMut()>);
1362 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1366 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1367 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1368 fn on_close(&self, callback: Box<dyn FnOnce()>);
1369
1370 unsafe fn attach_native_view(
1380 &self,
1381 _id: crate::NativeViewId,
1382 _view: std::ptr::NonNull<std::ffi::c_void>,
1383 ) -> Option<Box<dyn std::any::Any>> {
1384 None
1385 }
1386 fn set_focused_native_view(&self, _id: Option<crate::NativeViewId>) {}
1389 fn on_hit_test_native_view(
1392 &self,
1393 _callback: Box<dyn FnMut(Point<Pixels>) -> Option<crate::NativeViewId>>,
1394 ) {
1395 }
1396 fn on_native_view_focused(&self, _callback: Box<dyn FnMut(crate::NativeViewId)>) {}
1399 fn on_key_down_before_native_view(
1405 &self,
1406 _callback: Box<dyn FnMut(crate::KeyDownEvent) -> bool>,
1407 ) {
1408 }
1409 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1410 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1411 fn draw(&self, scene: &Scene);
1412 fn draw_composed(&self, scene: crate::fast::composition::ComposedScene<'_>) {
1413 crate::fast::composition::draw_uncomposed(self, scene)
1414 }
1415 fn enable_window_composition(&self) -> Result<()> {
1416 crate::fast::composition::unsupported("window composition")
1417 }
1418 fn create_native_surface(
1419 &self,
1420 ) -> Result<Rc<dyn crate::fast::composition::PlatformSurfaceAttachment>> {
1421 crate::fast::composition::unsupported("native surface portals")
1422 }
1423 fn set_composition_order(
1424 &self,
1425 _fast_surfaces: &[crate::fast::composition::PlatformCompositionSurface],
1426 ) -> Result<()> {
1427 crate::fast::composition::unsupported("surface ordering")
1428 }
1429 fn schedule_frame(&self) {}
1430 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1431 fn is_subpixel_rendering_supported(&self) -> bool;
1432
1433 fn get_title(&self) -> String {
1435 String::new()
1436 }
1437 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1438 None
1439 }
1440 fn tab_bar_visible(&self) -> bool {
1441 false
1442 }
1443 fn set_edited(&mut self, _edited: bool) {}
1444 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1445 fn toggle_simple_fullscreen(&self) {}
1446 fn is_simple_fullscreen(&self) -> bool {
1447 false
1448 }
1449 #[cfg(target_os = "macos")]
1450 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1451 #[cfg(target_os = "macos")]
1452 fn set_native_titlebar_visibility(&self, _visible: bool) {}
1453 fn show_character_palette(&self) {}
1454 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1455 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1456 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1457 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1458 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1459 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1460 fn merge_all_windows(&self) {}
1461 fn move_tab_to_new_window(&self) {}
1462 fn toggle_window_tab_overview(&self) {}
1463 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1464
1465 fn native_window_state(&self) -> Option<Vec<u8>> {
1466 None
1467 }
1468 fn restore_native_window_state(&self, _state: &[u8]) {}
1469
1470 #[cfg(target_os = "windows")]
1471 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1472
1473 fn inner_window_bounds(&self) -> WindowBounds {
1475 self.window_bounds()
1476 }
1477 fn request_decorations(&self, _decorations: WindowDecorations) {}
1478 fn show_window_menu(&self, _position: Point<Pixels>) {}
1479 fn start_window_move(&self) {}
1480 fn can_start_external_drag(&self) -> bool {
1481 false
1482 }
1483 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1484 false
1485 }
1486 fn start_window_resize(&self, _edge: ResizeEdge) {}
1487 fn set_exclusive_zone(&self, _zone: Pixels) {}
1488 #[cfg(all(target_os = "linux", feature = "wayland"))]
1489 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1490 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1491 fn window_decorations(&self) -> Decorations {
1492 Decorations::Server
1493 }
1494 fn set_app_id(&mut self, _app_id: &str) {}
1495 fn map_window(&mut self) -> anyhow::Result<()> {
1496 Ok(())
1497 }
1498 fn window_controls(&self) -> WindowControls {
1499 WindowControls::default()
1500 }
1501 fn set_client_inset(&self, _inset: Pixels) {}
1502 fn set_client_corner_radii(&self, _radii: Corners<Pixels>) {}
1503 fn gpu_specs(&self) -> Option<GpuSpecs>;
1504
1505 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1506
1507 fn insets(&self) -> WindowInsets {
1512 WindowInsets::default()
1513 }
1514
1515 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1521
1522 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1525
1526 fn set_back_enabled(&self, _enabled: bool) {}
1529
1530 fn show_soft_keyboard(&self) {}
1532
1533 fn hide_soft_keyboard(&self) {}
1535
1536 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1538
1539 fn play_system_bell(&self) {}
1540
1541 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1543
1544 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1546
1547 fn a11y_update_window_bounds(&self) {}
1549
1550 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1551 fn as_test(&mut self) -> Option<&mut TestWindow> {
1552 None
1553 }
1554
1555 #[cfg(any(test, feature = "test-support"))]
1559 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1560 anyhow::bail!("render_to_image not implemented for this platform")
1561 }
1562}
1563
1564#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1566pub trait PlatformHeadlessRenderer {
1567 fn render_scene_to_image(
1569 &mut self,
1570 scene: &Scene,
1571 size: Size<DevicePixels>,
1572 ) -> Result<RgbaImage>;
1573
1574 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1580
1581 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1583}
1584
1585#[doc(hidden)]
1588pub type RunnableVariant = Runnable<RunnableMeta>;
1589
1590#[doc(hidden)]
1591pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1592
1593#[doc(hidden)]
1594pub enum TasksIncluded {
1595 OnlyCompleted,
1596 CompletedAndRunning,
1597}
1598
1599#[doc(hidden)]
1602pub trait PlatformDispatcher: Send + Sync {
1603 fn is_main_thread(&self) -> bool;
1604 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1605 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1606 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1607
1608 fn dispatch_on_main_thread_when_idle(
1609 &self,
1610 runnable: RunnableVariant,
1611 timeout: Option<Duration>,
1612 ) {
1613 let _ = timeout;
1614 self.dispatch_on_main_thread(runnable, Priority::Low);
1615 }
1616
1617 fn idle_time_remaining(&self) -> Option<Duration> {
1618 None
1619 }
1620
1621 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1622
1623 fn now(&self) -> Instant {
1624 Instant::now()
1625 }
1626
1627 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1628 gpui_util::defer(Box::new(|| {}))
1629 }
1630
1631 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1632 ActivityGuard::noop()
1633 }
1634
1635 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1636 fn as_test(&self) -> Option<&TestDispatcher> {
1637 None
1638 }
1639
1640 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1643 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1644 None
1645 }
1646}
1647
1648#[expect(missing_docs)]
1649pub trait PlatformTextSystem: Send + Sync {
1650 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1651 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1653 fn all_font_names(&self) -> Vec<String>;
1655 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1657 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1659 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1661 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1663 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1665 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1667 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1669 fn rasterize_glyph(
1671 &self,
1672 params: &RenderGlyphParams,
1673 raster_bounds: Bounds<DevicePixels>,
1674 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1675 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1677 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1679 -> TextRenderingMode;
1680 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1682 0
1683 }
1684}
1685
1686#[expect(missing_docs)]
1687pub struct NoopTextSystem;
1688
1689#[expect(missing_docs)]
1690impl NoopTextSystem {
1691 #[allow(dead_code)]
1692 pub fn new() -> Self {
1693 Self
1694 }
1695}
1696
1697impl PlatformTextSystem for NoopTextSystem {
1698 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1699 Ok(())
1700 }
1701
1702 fn all_font_names(&self) -> Vec<String> {
1703 Vec::new()
1704 }
1705
1706 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1707 Ok(FontId(1))
1708 }
1709
1710 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1711 FontMetrics {
1712 units_per_em: 1000,
1713 ascent: 1025.0,
1714 descent: -275.0,
1715 line_gap: 0.0,
1716 underline_position: -95.0,
1717 underline_thickness: 60.0,
1718 cap_height: 698.0,
1719 x_height: 516.0,
1720 bounding_box: Bounds {
1721 origin: Point {
1722 x: -260.0,
1723 y: -245.0,
1724 },
1725 size: Size {
1726 width: 1501.0,
1727 height: 1364.0,
1728 },
1729 },
1730 }
1731 }
1732
1733 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1734 Ok(Bounds {
1735 origin: Point { x: 54.0, y: 0.0 },
1736 size: size(392.0, 528.0),
1737 })
1738 }
1739
1740 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1741 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1742 }
1743
1744 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1745 Some(GlyphId(ch.len_utf16() as u32))
1746 }
1747
1748 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1749 Ok(Default::default())
1750 }
1751
1752 fn rasterize_glyph(
1753 &self,
1754 _params: &RenderGlyphParams,
1755 raster_bounds: Bounds<DevicePixels>,
1756 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1757 Ok((raster_bounds.size, Vec::new()))
1758 }
1759
1760 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1761 let mut position = px(0.);
1762 let metrics = self.font_metrics(FontId(0));
1763 let em_width = font_size
1764 * self
1765 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1766 .unwrap()
1767 .width
1768 / metrics.units_per_em as f32;
1769 let mut glyphs = Vec::new();
1770 for (ix, c) in text.char_indices() {
1771 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1772 glyphs.push(ShapedGlyph {
1773 id: glyph,
1774 position: point(position, px(0.)),
1775 index: ix,
1776 is_emoji: glyph.0 == 2,
1777 });
1778 if glyph.0 == 2 {
1779 position += em_width * 2.0;
1780 } else {
1781 position += em_width;
1782 }
1783 } else {
1784 position += em_width
1785 }
1786 }
1787 let mut runs = Vec::default();
1788 if !glyphs.is_empty() {
1789 runs.push(ShapedRun {
1790 font_id: FontId(0),
1791 glyphs,
1792 });
1793 } else {
1794 position = px(0.);
1795 }
1796
1797 LineLayout {
1798 font_size,
1799 width: position,
1800 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1801 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1802 runs,
1803 len: text.len(),
1804 }
1805 }
1806
1807 fn recommended_rendering_mode(
1808 &self,
1809 _font_id: FontId,
1810 _font_size: Pixels,
1811 ) -> TextRenderingMode {
1812 TextRenderingMode::Grayscale
1813 }
1814}
1815
1816#[allow(dead_code)]
1821pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1822 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1823 [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], ];
1837
1838 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1839 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1840
1841 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1842 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1843
1844 [
1845 ratios[0] * NORM13,
1846 ratios[1] * NORM24,
1847 ratios[2] * NORM13,
1848 ratios[3] * NORM24,
1849 ]
1850}
1851
1852#[derive(PartialEq, Eq, Hash, Clone)]
1853#[expect(missing_docs)]
1854pub enum AtlasKey {
1855 Glyph(RenderGlyphParams),
1856 Svg(RenderSvgParams),
1857 Image(RenderImageParams),
1858}
1859
1860impl AtlasKey {
1861 pub fn texture_kind(&self) -> AtlasTextureKind {
1863 match self {
1864 AtlasKey::Glyph(params) => {
1865 if params.is_emoji {
1866 AtlasTextureKind::Polychrome
1867 } else if params.subpixel_rendering {
1868 AtlasTextureKind::Subpixel
1869 } else {
1870 AtlasTextureKind::Monochrome
1871 }
1872 }
1873 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1874 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1875 }
1876 }
1877}
1878
1879impl From<RenderGlyphParams> for AtlasKey {
1880 fn from(params: RenderGlyphParams) -> Self {
1881 Self::Glyph(params)
1882 }
1883}
1884
1885impl From<RenderSvgParams> for AtlasKey {
1886 fn from(params: RenderSvgParams) -> Self {
1887 Self::Svg(params)
1888 }
1889}
1890
1891impl From<RenderImageParams> for AtlasKey {
1892 fn from(params: RenderImageParams) -> Self {
1893 Self::Image(params)
1894 }
1895}
1896
1897#[expect(missing_docs)]
1898pub trait PlatformAtlas {
1899 fn get_or_insert_with<'a>(
1901 &self,
1902 key: AtlasKey,
1903 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1904 ) -> Result<Option<AtlasTile>>;
1905 fn remove(&self, key: &AtlasKey);
1906
1907 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1908 fn contains(&self, _key: &AtlasKey) -> bool {
1909 false
1910 }
1911}
1912
1913#[doc(hidden)]
1914pub trait AtlasBackend {
1915 fn insert(
1916 &mut self,
1917 kind: AtlasTextureKind,
1918 size: Size<DevicePixels>,
1919 bytes: &[u8],
1920 ) -> Result<AtlasTile>;
1921
1922 fn remove(&mut self, tile: AtlasTile);
1923}
1924
1925#[doc(hidden)]
1926pub struct AtlasState<Backend> {
1927 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1928 pub backend: Backend,
1929}
1930
1931impl<Backend> AtlasState<Backend> {
1932 pub fn new(backend: Backend) -> Self {
1933 Self {
1934 tiles_by_key: FxHashMap::default(),
1935 backend,
1936 }
1937 }
1938
1939 pub fn contains(&self, key: &AtlasKey) -> bool {
1940 self.tiles_by_key.contains_key(key)
1941 }
1942
1943 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1944 self.tiles_by_key.clear();
1945 reset_backend(&mut self.backend);
1946 }
1947}
1948
1949impl<Backend: Default> Default for AtlasState<Backend> {
1950 fn default() -> Self {
1951 Self::new(Backend::default())
1952 }
1953}
1954
1955impl<Backend: AtlasBackend> AtlasState<Backend> {
1956 pub fn get_or_insert_with<'a>(
1957 &mut self,
1958 key: AtlasKey,
1959 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1960 ) -> Result<Option<AtlasTile>> {
1961 match self.tiles_by_key.entry(key) {
1962 Entry::Occupied(entry) => Ok(Some(*entry.get())),
1963 Entry::Vacant(entry) => {
1964 profiling::scope!("new tile");
1965 let Some((size, bytes)) = build()? else {
1966 return Ok(None);
1967 };
1968 let tile = self
1969 .backend
1970 .insert(entry.key().texture_kind(), size, &bytes)?;
1971 entry.insert(tile);
1972 Ok(Some(tile))
1973 }
1974 }
1975 }
1976
1977 pub fn remove(&mut self, key: &AtlasKey) {
1978 if let Some(tile) = self.tiles_by_key.remove(key) {
1979 self.backend.remove(tile);
1980 }
1981 }
1982}
1983
1984#[derive(Default)]
1988pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1989
1990#[doc(hidden)]
1991#[derive(Default)]
1992pub struct HeadlessAtlasBackend {
1993 next_id: u32,
1994}
1995
1996impl AtlasBackend for HeadlessAtlasBackend {
1997 fn insert(
1998 &mut self,
1999 kind: AtlasTextureKind,
2000 size: Size<DevicePixels>,
2001 _bytes: &[u8],
2002 ) -> Result<AtlasTile> {
2003 self.next_id += 1;
2004 let texture_id = self.next_id;
2005 self.next_id += 1;
2006 let tile_id = self.next_id;
2007 Ok(AtlasTile {
2008 texture_id: AtlasTextureId {
2009 index: texture_id,
2010 kind,
2011 },
2012 tile_id: TileId(tile_id),
2013 padding: 0,
2014 bounds: Bounds {
2015 origin: Point::default(),
2016 size,
2017 },
2018 })
2019 }
2020
2021 fn remove(&mut self, _tile: AtlasTile) {}
2022}
2023
2024impl PlatformAtlas for HeadlessAtlas {
2025 fn get_or_insert_with<'a>(
2026 &self,
2027 key: AtlasKey,
2028 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2029 ) -> Result<Option<AtlasTile>> {
2030 self.0.lock().get_or_insert_with(key, build)
2031 }
2032
2033 fn remove(&self, key: &AtlasKey) {
2034 self.0.lock().remove(key);
2035 }
2036
2037 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2038 fn contains(&self, key: &AtlasKey) -> bool {
2039 self.0.lock().contains(key)
2040 }
2041}
2042
2043#[doc(hidden)]
2044pub struct AtlasTextureList<T> {
2045 pub textures: Vec<Option<T>>,
2046 pub free_list: Vec<usize>,
2047}
2048
2049impl<T> Default for AtlasTextureList<T> {
2050 fn default() -> Self {
2051 Self {
2052 textures: Vec::default(),
2053 free_list: Vec::default(),
2054 }
2055 }
2056}
2057
2058impl<T> ops::Index<usize> for AtlasTextureList<T> {
2059 type Output = Option<T>;
2060
2061 fn index(&self, index: usize) -> &Self::Output {
2062 &self.textures[index]
2063 }
2064}
2065
2066impl<T> AtlasTextureList<T> {
2067 #[allow(unused)]
2068 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2069 self.free_list.clear();
2070 self.textures.drain(..)
2071 }
2072
2073 #[allow(dead_code)]
2074 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2075 self.textures.iter_mut().flatten()
2076 }
2077}
2078
2079#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2080#[repr(C)]
2081#[expect(missing_docs)]
2082pub struct AtlasTile {
2083 pub texture_id: AtlasTextureId,
2085 pub tile_id: TileId,
2087 pub padding: u32,
2089 pub bounds: Bounds<DevicePixels>,
2091}
2092
2093#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2094#[repr(C)]
2095#[expect(missing_docs)]
2096pub struct AtlasTextureId {
2097 pub index: u32,
2100 pub kind: AtlasTextureKind,
2102}
2103
2104#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2105#[repr(C)]
2106#[cfg_attr(
2107 all(
2108 any(target_os = "linux", target_os = "freebsd"),
2109 not(any(feature = "x11", feature = "wayland"))
2110 ),
2111 allow(dead_code)
2112)]
2113#[expect(missing_docs)]
2114pub enum AtlasTextureKind {
2115 Monochrome = 0,
2116 Polychrome = 1,
2117 Subpixel = 2,
2118}
2119
2120#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2121#[repr(C)]
2122#[expect(missing_docs)]
2123pub struct TileId(pub u32);
2124
2125impl From<etagere::AllocId> for TileId {
2126 fn from(id: etagere::AllocId) -> Self {
2127 Self(id.serialize())
2128 }
2129}
2130
2131impl From<TileId> for etagere::AllocId {
2132 fn from(id: TileId) -> Self {
2133 Self::deserialize(id.0)
2134 }
2135}
2136
2137#[expect(missing_docs)]
2138pub struct PlatformInputHandler {
2139 cx: AsyncWindowContext,
2140 handler: Box<dyn InputHandler>,
2141 focus_id: Option<crate::FocusId>,
2142}
2143
2144#[expect(missing_docs)]
2145#[cfg_attr(
2146 all(
2147 any(target_os = "linux", target_os = "freebsd"),
2148 not(any(feature = "x11", feature = "wayland"))
2149 ),
2150 allow(dead_code)
2151)]
2152impl PlatformInputHandler {
2153 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2154 Self {
2155 cx,
2156 handler,
2157 focus_id: None,
2158 }
2159 }
2160
2161 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2162 self.focus_id = Some(focus_id);
2163 self
2164 }
2165
2166 pub fn focus_id(&self) -> Option<crate::FocusId> {
2171 self.focus_id
2172 }
2173
2174 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2175 self.cx
2176 .update(|window, cx| {
2177 self.handler
2178 .selected_text_range(ignore_disabled_input, window, cx)
2179 })
2180 .ok()
2181 .flatten()
2182 }
2183
2184 #[cfg_attr(target_os = "windows", allow(dead_code))]
2185 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2186 self.cx
2187 .update(|window, cx| self.handler.marked_text_range(window, cx))
2188 .ok()
2189 .flatten()
2190 }
2191
2192 #[cfg_attr(
2193 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2194 allow(dead_code)
2195 )]
2196 pub fn text_for_range(
2197 &mut self,
2198 range_utf16: Range<usize>,
2199 adjusted: &mut Option<Range<usize>>,
2200 ) -> Option<String> {
2201 self.cx
2202 .update(|window, cx| {
2203 self.handler
2204 .text_for_range(range_utf16, adjusted, window, cx)
2205 })
2206 .ok()
2207 .flatten()
2208 }
2209
2210 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2211 self.cx
2212 .update(|window, cx| {
2213 self.handler
2214 .replace_text_in_range(replacement_range, text, window, cx);
2215 })
2216 .ok();
2217 }
2218
2219 pub fn replace_and_mark_text_in_range(
2220 &mut self,
2221 range_utf16: Option<Range<usize>>,
2222 new_text: &str,
2223 new_selected_range: Option<Range<usize>>,
2224 ) {
2225 self.cx
2226 .update(|window, cx| {
2227 self.handler.replace_and_mark_text_in_range(
2228 range_utf16,
2229 new_text,
2230 new_selected_range,
2231 window,
2232 cx,
2233 )
2234 })
2235 .ok();
2236 }
2237
2238 #[cfg_attr(target_os = "windows", allow(dead_code))]
2239 pub fn unmark_text(&mut self) {
2240 self.cx
2241 .update(|window, cx| self.handler.unmark_text(window, cx))
2242 .ok();
2243 }
2244
2245 pub fn paste(&mut self, item: ClipboardItem) {
2246 self.cx
2247 .update(|window, cx| self.handler.paste(item, window, cx))
2248 .ok();
2249 }
2250
2251 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2252 self.cx
2253 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2254 .ok()
2255 .flatten()
2256 }
2257
2258 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2259 self.cx
2260 .update(|window, cx| {
2261 self.handler
2262 .selection_bounds_for_range(range_utf16, window, cx)
2263 })
2264 .unwrap_or_default()
2265 }
2266
2267 #[allow(dead_code)]
2268 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2269 self.handler.apple_press_and_hold_enabled()
2270 }
2271
2272 pub(crate) fn unmark_text_during_update(&mut self, window: &mut Window, cx: &mut App) {
2275 self.handler.unmark_text(window, cx);
2276 }
2277
2278 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2279 self.handler.replace_text_in_range(None, input, window, cx);
2280 }
2281
2282 pub fn compute_ime_candidate_bounds(
2283 marked_range: Option<Range<usize>>,
2284 selection: &UTF16Selection,
2285 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2286 ) -> Option<Bounds<Pixels>> {
2287 if let Some(marked_range) = marked_range {
2288 let mut line_start = marked_range.start;
2290
2291 let caret = selection.range.end;
2295 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2296 for i in (marked_range.start..caret).rev() {
2297 if let Some(b) = bounds_for_range(i..i) {
2298 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2299 line_start = i + 1;
2300 break;
2301 }
2302 }
2303 }
2304 }
2305 bounds_for_range(line_start..line_start)
2306 } else {
2307 let offset = if selection.reversed {
2309 selection.range.start
2310 } else {
2311 selection.range.end
2312 };
2313 bounds_for_range(offset..offset)
2314 }
2315 }
2316
2317 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2318 let marked_range = self.handler.marked_text_range(window, cx);
2319 let selection = self.handler.selected_text_range(true, window, cx)?;
2320 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2321 self.handler.bounds_for_range(range, window, cx)
2322 })
2323 }
2324
2325 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2326 let marked_range = self.marked_text_range();
2327 let selection = self.selected_text_range(true)?;
2328 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2329 self.bounds_for_range(range)
2330 })
2331 }
2332
2333 #[allow(unused)]
2334 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2335 self.cx
2336 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2337 .ok()
2338 .flatten()
2339 }
2340
2341 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2343 self.cx
2344 .update(|window, cx| {
2345 self.handler
2346 .set_selected_text_range(range_utf16, window, cx)
2347 })
2348 .ok();
2349 }
2350
2351 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2353 self.cx
2354 .update(|window, cx| self.handler.element_bounds(window, cx))
2355 .ok()
2356 .flatten()
2357 }
2358
2359 pub fn text_length_utf16(&mut self) -> Option<usize> {
2361 self.cx
2362 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2363 .ok()
2364 .flatten()
2365 }
2366
2367 #[allow(dead_code)]
2368 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2369 self.handler.accepts_text_input(window, cx)
2370 }
2371
2372 #[allow(dead_code)]
2373 pub fn query_accepts_text_input(&mut self) -> bool {
2374 self.cx
2375 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2376 .unwrap_or(true)
2377 }
2378
2379 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2384 let focus_id = self.focus_id;
2385 self.cx
2386 .update(|window, cx| {
2387 focus_id.is_some()
2388 && window.focus == focus_id
2389 && self.handler.accepts_text_input(window, cx)
2390 })
2391 .unwrap_or(false)
2392 }
2393
2394 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2400 self.cx
2401 .update(|window, cx| {
2402 !window.has_pending_keystrokes()
2404 && self.handler.prefers_ime_for_printable_keys(window, cx)
2405 })
2406 .unwrap_or(false)
2407 }
2408
2409 pub fn text_input_configuration(
2411 &mut self,
2412 window: &mut Window,
2413 cx: &mut App,
2414 ) -> TextInputConfiguration {
2415 self.handler.text_input_configuration(window, cx)
2416 }
2417
2418 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2420 self.cx
2421 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2422 .ok()
2423 .flatten()
2424 }
2425}
2426
2427#[derive(Debug)]
2430pub struct UTF16Selection {
2431 pub range: Range<usize>,
2434 pub reversed: bool,
2437}
2438
2439pub trait InputHandler: 'static {
2444 fn selected_text_range(
2449 &mut self,
2450 ignore_disabled_input: bool,
2451 window: &mut Window,
2452 cx: &mut App,
2453 ) -> Option<UTF16Selection>;
2454
2455 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2460
2461 fn text_for_range(
2466 &mut self,
2467 range_utf16: Range<usize>,
2468 adjusted_range: &mut Option<Range<usize>>,
2469 window: &mut Window,
2470 cx: &mut App,
2471 ) -> Option<String>;
2472
2473 fn replace_text_in_range(
2478 &mut self,
2479 replacement_range: Option<Range<usize>>,
2480 text: &str,
2481 window: &mut Window,
2482 cx: &mut App,
2483 );
2484
2485 fn replace_and_mark_text_in_range(
2492 &mut self,
2493 range_utf16: Option<Range<usize>>,
2494 new_text: &str,
2495 new_selected_range: Option<Range<usize>>,
2496 window: &mut Window,
2497 cx: &mut App,
2498 );
2499
2500 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2503
2504 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2511 if let Some(text) = item.text() {
2512 self.replace_text_in_range(None, &text, window, cx);
2513 }
2514 }
2515
2516 fn bounds_for_range(
2521 &mut self,
2522 range_utf16: Range<usize>,
2523 window: &mut Window,
2524 cx: &mut App,
2525 ) -> Option<Bounds<Pixels>>;
2526
2527 fn selection_bounds_for_range(
2534 &mut self,
2535 _range_utf16: Range<usize>,
2536 _window: &mut Window,
2537 _cx: &mut App,
2538 ) -> Vec<Bounds<Pixels>> {
2539 Vec::new()
2540 }
2541
2542 fn character_index_for_point(
2546 &mut self,
2547 point: Point<Pixels>,
2548 window: &mut Window,
2549 cx: &mut App,
2550 ) -> Option<usize>;
2551
2552 fn set_selected_text_range(
2562 &mut self,
2563 _range_utf16: Range<usize>,
2564 _window: &mut Window,
2565 _cx: &mut App,
2566 ) {
2567 }
2568
2569 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2576 None
2577 }
2578
2579 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2581 None
2582 }
2583
2584 #[allow(dead_code)]
2589 fn apple_press_and_hold_enabled(&mut self) -> bool {
2590 true
2591 }
2592
2593 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2595 true
2596 }
2597
2598 fn text_input_editable_range(
2609 &mut self,
2610 _window: &mut Window,
2611 _cx: &mut App,
2612 ) -> Option<Range<usize>> {
2613 None
2614 }
2615
2616 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2625 false
2626 }
2627
2628 fn text_input_configuration(
2634 &mut self,
2635 _window: &mut Window,
2636 _cx: &mut App,
2637 ) -> TextInputConfiguration {
2638 TextInputConfiguration::default()
2639 }
2640}
2641
2642#[derive(Clone, Debug, Default, PartialEq, Eq)]
2652pub struct TextInputConfiguration {
2653 pub autocorrect: bool,
2655 pub autocapitalize: Autocapitalize,
2657 pub suggestions: bool,
2659 pub input_action: TextInputAction,
2661}
2662
2663#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2665pub enum Autocapitalize {
2666 #[default]
2668 None,
2669 Words,
2671 Sentences,
2673 Characters,
2675}
2676
2677#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2687pub enum TextInputAction {
2688 #[default]
2690 Unspecified,
2691 Enter,
2693 Done,
2695 Go,
2697 Next,
2699 Previous,
2701 Search,
2703 Send,
2705}
2706
2707#[derive(Debug)]
2709pub struct WindowOptions {
2710 pub window_bounds: Option<WindowBounds>,
2714
2715 pub titlebar: Option<TitlebarOptions>,
2717
2718 pub focus: bool,
2720
2721 pub show: bool,
2723
2724 pub kind: WindowKind,
2726
2727 pub is_movable: bool,
2731
2732 pub app_owns_titlebar_drag: bool,
2744
2745 pub inactive_frame_interval: Option<Duration>,
2750
2751 pub low_power_frame_interval: Option<Duration>,
2756
2757 pub thermal_frame_interval: Option<Duration>,
2762
2763 pub is_resizable: bool,
2765
2766 pub is_minimizable: bool,
2768
2769 pub display_id: Option<DisplayId>,
2772
2773 pub window_background: WindowBackgroundAppearance,
2775
2776 pub app_id: Option<String>,
2778
2779 pub window_min_size: Option<Size<Pixels>>,
2781
2782 pub window_decorations: Option<WindowDecorations>,
2785
2786 pub icon: Option<Arc<image::RgbaImage>>,
2788
2789 pub tabbing_identifier: Option<String>,
2791
2792 pub use_display_p3: bool,
2794}
2795
2796#[derive(Debug)]
2798#[cfg_attr(
2799 all(
2800 any(target_os = "linux", target_os = "freebsd"),
2801 not(any(feature = "x11", feature = "wayland"))
2802 ),
2803 allow(dead_code)
2804)]
2805#[allow(missing_docs)]
2806pub struct WindowParams {
2807 pub bounds: Bounds<Pixels>,
2808
2809 #[cfg_attr(feature = "wayland", allow(dead_code))]
2811 pub titlebar: Option<TitlebarOptions>,
2812
2813 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2815 pub kind: WindowKind,
2816
2817 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2819 pub is_movable: bool,
2820
2821 #[cfg_attr(
2823 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2824 allow(dead_code)
2825 )]
2826 pub app_owns_titlebar_drag: bool,
2827
2828 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2830 pub is_resizable: bool,
2831
2832 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2834 pub is_minimizable: bool,
2835
2836 #[cfg_attr(
2837 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2838 allow(dead_code)
2839 )]
2840 pub focus: bool,
2841
2842 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2843 pub show: bool,
2844
2845 #[cfg_attr(feature = "wayland", allow(dead_code))]
2847 pub icon: Option<Arc<image::RgbaImage>>,
2848
2849 #[cfg_attr(feature = "wayland", allow(dead_code))]
2850 pub display_id: Option<DisplayId>,
2851
2852 #[cfg_attr(feature = "wayland", allow(dead_code))]
2853 pub app_id: Option<String>,
2854
2855 pub window_min_size: Option<Size<Pixels>>,
2856
2857 #[cfg(target_os = "macos")]
2858 pub tabbing_identifier: Option<String>,
2859
2860 #[cfg(target_os = "macos")]
2861 pub use_display_p3: bool,
2862}
2863
2864#[derive(Debug, Copy, Clone, PartialEq)]
2866pub enum WindowBounds {
2867 Windowed(Bounds<Pixels>),
2869 Maximized(Bounds<Pixels>),
2872 Fullscreen(Bounds<Pixels>),
2875}
2876
2877impl Default for WindowBounds {
2878 fn default() -> Self {
2879 WindowBounds::Windowed(Bounds::default())
2880 }
2881}
2882
2883impl WindowBounds {
2884 pub fn get_bounds(&self) -> Bounds<Pixels> {
2886 match self {
2887 WindowBounds::Windowed(bounds) => *bounds,
2888 WindowBounds::Maximized(bounds) => *bounds,
2889 WindowBounds::Fullscreen(bounds) => *bounds,
2890 }
2891 }
2892
2893 pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
2896 WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
2897 }
2898}
2899
2900impl Default for WindowOptions {
2901 fn default() -> Self {
2902 Self {
2903 window_bounds: None,
2904 titlebar: Some(TitlebarOptions {
2905 title: Default::default(),
2906 appears_transparent: Default::default(),
2907 traffic_light_position: Default::default(),
2908 }),
2909 focus: true,
2910 show: true,
2911 kind: WindowKind::Normal,
2912 is_movable: true,
2913 app_owns_titlebar_drag: false,
2914 inactive_frame_interval: Some(Duration::from_micros(33_333)),
2915 low_power_frame_interval: Some(Duration::from_micros(33_333)),
2916 thermal_frame_interval: Some(Duration::from_micros(16_667)),
2917 is_resizable: true,
2918 is_minimizable: true,
2919 display_id: None,
2920 window_background: WindowBackgroundAppearance::default(),
2921 icon: None,
2922 app_id: None,
2923 window_min_size: None,
2924 window_decorations: None,
2925 tabbing_identifier: None,
2926 use_display_p3: false,
2927 }
2928 }
2929}
2930
2931#[derive(Debug, Default)]
2933pub struct TitlebarOptions {
2934 pub title: Option<SharedString>,
2936
2937 pub appears_transparent: bool,
2940
2941 pub traffic_light_position: Option<Point<Pixels>>,
2943}
2944
2945#[derive(Clone, Debug, PartialEq, Eq)]
2947pub enum WindowKind {
2948 Normal,
2950
2951 PopUp,
2954
2955 AnchoredPopup(popup::PopupOptions),
2962
2963 Floating,
2965
2966 #[cfg(all(target_os = "linux", feature = "wayland"))]
2969 LayerShell(layer_shell::LayerShellOptions),
2970
2971 Dialog,
2974}
2975
2976#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2981pub enum WindowAppearance {
2982 #[default]
2986 Light,
2987
2988 VibrantLight,
2992
2993 Dark,
2997
2998 VibrantDark,
3002}
3003
3004#[derive(Copy, Clone, Debug, Default, PartialEq)]
3007pub enum WindowBackgroundAppearance {
3008 #[default]
3016 Opaque,
3017 Transparent,
3019 Blurred,
3023 MicaBackdrop,
3025 MicaAltBackdrop,
3027}
3028
3029#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3031pub enum TextRenderingMode {
3032 #[default]
3034 PlatformDefault,
3035 Subpixel,
3037 Grayscale,
3039}
3040
3041#[derive(Clone, Debug)]
3043pub struct PathPromptOptions {
3044 pub files: bool,
3046 pub directories: bool,
3048 pub multiple: bool,
3050 pub prompt: Option<SharedString>,
3052}
3053
3054#[derive(Copy, Clone, Debug, PartialEq)]
3056pub enum PromptLevel {
3057 Info,
3059
3060 Warning,
3062
3063 Critical,
3065}
3066
3067#[derive(Clone, Debug, PartialEq)]
3069pub enum PromptButton {
3070 Ok(SharedString),
3072 Cancel(SharedString),
3074 Other(SharedString),
3076}
3077
3078impl PromptButton {
3079 pub fn new(label: impl Into<SharedString>) -> Self {
3081 PromptButton::Other(label.into())
3082 }
3083
3084 pub fn ok(label: impl Into<SharedString>) -> Self {
3086 PromptButton::Ok(label.into())
3087 }
3088
3089 pub fn cancel(label: impl Into<SharedString>) -> Self {
3091 PromptButton::Cancel(label.into())
3092 }
3093
3094 #[allow(dead_code)]
3096 pub fn is_cancel(&self) -> bool {
3097 matches!(self, PromptButton::Cancel(_))
3098 }
3099
3100 pub fn label(&self) -> &SharedString {
3102 match self {
3103 PromptButton::Ok(label) => label,
3104 PromptButton::Cancel(label) => label,
3105 PromptButton::Other(label) => label,
3106 }
3107 }
3108}
3109
3110impl From<&str> for PromptButton {
3111 fn from(value: &str) -> Self {
3112 match value.to_lowercase().as_str() {
3113 "ok" => PromptButton::Ok("OK".into()),
3114 "cancel" => PromptButton::Cancel("Cancel".into()),
3115 _ => PromptButton::Other(SharedString::from(value.to_owned())),
3116 }
3117 }
3118}
3119
3120#[derive(
3122 Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, EnumIter,
3123)]
3124pub enum CursorStyle {
3125 #[default]
3127 Arrow,
3128
3129 IBeam,
3132
3133 Crosshair,
3136
3137 ClosedHand,
3140
3141 OpenHand,
3144
3145 PointingHand,
3148
3149 ResizeLeft,
3152
3153 ResizeRight,
3156
3157 ResizeLeftRight,
3160
3161 ResizeUp,
3164
3165 ResizeDown,
3168
3169 ResizeUpDown,
3172
3173 ResizeUpLeftDownRight,
3176
3177 ResizeUpRightDownLeft,
3180
3181 ResizeColumn,
3184
3185 ResizeRow,
3188
3189 IBeamCursorForVerticalLayout,
3192
3193 OperationNotAllowed,
3196
3197 DragLink,
3200
3201 DragCopy,
3204
3205 ContextualMenu,
3208}
3209
3210#[derive(Clone, Debug, Eq, PartialEq)]
3212pub struct ClipboardItem {
3213 pub entries: Vec<ClipboardEntry>,
3215}
3216
3217#[derive(Clone, Debug, PartialEq, Eq)]
3222pub enum ClipboardReadError {
3223 Unavailable,
3227 Denied(String),
3230 UnsupportedContent,
3233}
3234
3235impl std::fmt::Display for ClipboardReadError {
3236 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3237 match self {
3238 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3239 Self::Denied(message) => {
3240 write!(formatter, "clipboard access was denied: {message}")
3241 }
3242 Self::UnsupportedContent => {
3243 formatter.write_str("the clipboard contents are unsupported")
3244 }
3245 }
3246 }
3247}
3248
3249impl std::error::Error for ClipboardReadError {}
3250
3251#[derive(Clone, Debug, Eq, PartialEq)]
3253pub enum ClipboardEntry {
3254 String(ClipboardString),
3256 Image(Image),
3258 ExternalPaths(crate::ExternalPaths),
3260}
3261
3262impl ClipboardItem {
3263 pub fn new_string(text: String) -> Self {
3265 Self {
3266 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3267 }
3268 }
3269
3270 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3272 Self {
3273 entries: vec![ClipboardEntry::String(ClipboardString {
3274 text,
3275 metadata: Some(metadata),
3276 })],
3277 }
3278 }
3279
3280 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3282 Self {
3283 entries: vec![ClipboardEntry::String(
3284 ClipboardString::new(text).with_json_metadata(metadata),
3285 )],
3286 }
3287 }
3288
3289 pub fn new_image(image: &Image) -> Self {
3291 Self {
3292 entries: vec![ClipboardEntry::Image(image.clone())],
3293 }
3294 }
3295
3296 pub fn text(&self) -> Option<String> {
3299 let mut answer = String::new();
3300
3301 for entry in self.entries.iter() {
3302 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3303 answer.push_str(text);
3304 }
3305 }
3306
3307 if answer.is_empty() {
3308 for entry in self.entries.iter() {
3309 if let ClipboardEntry::ExternalPaths(paths) = entry {
3310 for path in &paths.0 {
3311 use std::fmt::Write as _;
3312 _ = write!(answer, "{}", path.display());
3313 }
3314 }
3315 }
3316 }
3317
3318 if !answer.is_empty() {
3319 Some(answer)
3320 } else {
3321 None
3322 }
3323 }
3324
3325 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3327 pub fn metadata(&self) -> Option<&String> {
3328 match self.entries().first() {
3329 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3330 clipboard_string.metadata.as_ref()
3331 }
3332 _ => None,
3333 }
3334 }
3335
3336 pub fn entries(&self) -> &[ClipboardEntry] {
3338 &self.entries
3339 }
3340
3341 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3343 self.entries.into_iter()
3344 }
3345}
3346
3347impl From<ClipboardString> for ClipboardEntry {
3348 fn from(value: ClipboardString) -> Self {
3349 Self::String(value)
3350 }
3351}
3352
3353impl From<String> for ClipboardEntry {
3354 fn from(value: String) -> Self {
3355 Self::from(ClipboardString::from(value))
3356 }
3357}
3358
3359impl From<Image> for ClipboardEntry {
3360 fn from(value: Image) -> Self {
3361 Self::Image(value)
3362 }
3363}
3364
3365impl From<ClipboardEntry> for ClipboardItem {
3366 fn from(value: ClipboardEntry) -> Self {
3367 Self {
3368 entries: vec![value],
3369 }
3370 }
3371}
3372
3373impl From<String> for ClipboardItem {
3374 fn from(value: String) -> Self {
3375 Self::from(ClipboardEntry::from(value))
3376 }
3377}
3378
3379impl From<Image> for ClipboardItem {
3380 fn from(value: Image) -> Self {
3381 Self::from(ClipboardEntry::from(value))
3382 }
3383}
3384
3385#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3387pub enum ImageFormat {
3388 Png,
3393 Jpeg,
3395 Webp,
3397 Gif,
3399 Svg,
3401 Bmp,
3403 Tiff,
3405 Ico,
3407 Pnm,
3409}
3410
3411impl ImageFormat {
3412 pub const fn mime_type(self) -> &'static str {
3414 match self {
3415 ImageFormat::Png => "image/png",
3416 ImageFormat::Jpeg => "image/jpeg",
3417 ImageFormat::Webp => "image/webp",
3418 ImageFormat::Gif => "image/gif",
3419 ImageFormat::Svg => "image/svg+xml",
3420 ImageFormat::Bmp => "image/bmp",
3421 ImageFormat::Tiff => "image/tiff",
3422 ImageFormat::Ico => "image/ico",
3423 ImageFormat::Pnm => "image/x-portable-anymap",
3424 }
3425 }
3426
3427 pub const fn extension(self) -> &'static str {
3429 match self {
3430 ImageFormat::Png => "png",
3431 ImageFormat::Jpeg => "jpg",
3432 ImageFormat::Webp => "webp",
3433 ImageFormat::Gif => "gif",
3434 ImageFormat::Svg => "svg",
3435 ImageFormat::Bmp => "bmp",
3436 ImageFormat::Tiff => "tiff",
3437 ImageFormat::Ico => "ico",
3438 ImageFormat::Pnm => "pnm",
3439 }
3440 }
3441
3442 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3444 use strum::IntoEnumIterator;
3445 Self::iter()
3446 .find(|format| format.mime_type() == mime_type)
3447 .or_else(|| Self::from_mime_type_alias(mime_type))
3448 }
3449
3450 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3454 match mime_type {
3455 "image/jpg" => Some(Self::Jpeg),
3456 "image/tif" => Some(Self::Tiff),
3457 _ => None,
3458 }
3459 }
3460}
3461
3462#[derive(Clone, Debug, PartialEq, Eq)]
3464pub struct Image {
3465 pub format: ImageFormat,
3467 pub bytes: Vec<u8>,
3469 pub id: u64,
3471}
3472
3473pub(crate) fn decode_static_image(
3474 bytes: &[u8],
3475 format: image::ImageFormat,
3476) -> Result<SmallVec<[Frame; 1]>> {
3477 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3478 .into_decoder()
3479 .context("creating image decoder")?;
3480 decode_static_image_from_decoder(decoder)
3481}
3482
3483pub(crate) fn decode_static_image_from_decoder(
3484 mut decoder: impl image::ImageDecoder,
3485) -> Result<SmallVec<[Frame; 1]>> {
3486 let orientation = decoder
3487 .orientation()
3488 .context("reading decoder's orientation")?;
3489 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3490 image.apply_orientation(orientation);
3491
3492 let mut data = image.into_rgba8();
3493 for pixel in data.chunks_exact_mut(4) {
3494 pixel.swap(0, 2);
3495 }
3496
3497 Ok(SmallVec::from_elem(Frame::new(data), 1))
3498}
3499
3500fn decode_animated_frames<'a>(
3501 decoder: impl image::AnimationDecoder<'a>,
3502 format_name: &str,
3503) -> Result<SmallVec<[Frame; 1]>> {
3504 let mut frames = SmallVec::new();
3505
3506 for frame in decoder.into_frames() {
3507 match frame {
3508 Ok(mut frame) => {
3509 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3511 pixel.swap(0, 2);
3512 }
3513 frames.push(frame);
3514 }
3515 Err(err) => {
3516 log::debug!("Skipping {format_name} frame due to decode error: {err}");
3517 }
3518 }
3519 }
3520
3521 if frames.is_empty() {
3522 anyhow::bail!("{format_name} could not be decoded: all frames failed");
3523 }
3524
3525 Ok(frames)
3526}
3527
3528pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3529 let decoder = GifDecoder::new(Cursor::new(bytes))?;
3530 decode_animated_frames(decoder, "GIF")
3531}
3532
3533pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3534 let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
3535
3536 if decoder.has_animation() {
3537 let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
3538 decode_animated_frames(decoder, "WebP")
3539 } else {
3540 decode_static_image_from_decoder(decoder)
3541 }
3542}
3543
3544impl Hash for Image {
3545 fn hash<H: Hasher>(&self, state: &mut H) {
3546 state.write_u64(self.id);
3547 }
3548}
3549
3550impl Image {
3551 pub fn empty() -> Self {
3553 Self::from_bytes(ImageFormat::Png, Vec::new())
3554 }
3555
3556 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3558 Self {
3559 id: hash(&bytes),
3560 format,
3561 bytes,
3562 }
3563 }
3564
3565 pub fn id(&self) -> u64 {
3567 self.id
3568 }
3569
3570 pub fn use_render_image(
3572 self: Arc<Self>,
3573 window: &mut Window,
3574 cx: &mut App,
3575 ) -> Option<Arc<RenderImage>> {
3576 ImageSource::Image(self)
3577 .use_data(None, window, cx)
3578 .and_then(|result| result.ok())
3579 }
3580
3581 pub fn get_render_image(
3583 self: Arc<Self>,
3584 window: &mut Window,
3585 cx: &mut App,
3586 ) -> Option<Arc<RenderImage>> {
3587 ImageSource::Image(self)
3588 .get_data(None, window, cx)
3589 .and_then(|result| result.ok())
3590 }
3591
3592 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3594 ImageSource::Image(self).remove_asset(cx);
3595 }
3596
3597 #[cfg(any(test, feature = "test-support"))]
3600 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3601 ImageSource::Image(self.clone()).is_asset_cached(cx)
3602 }
3603
3604 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3606 let frames = match self.format {
3607 ImageFormat::Gif => decode_gif_image(&self.bytes)?,
3608 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3609 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3610 ImageFormat::Webp => decode_webp_image(&self.bytes)?,
3611 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3612 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3613 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3614 ImageFormat::Svg => {
3615 return svg_renderer
3616 .render_single_frame(&self.bytes, 1.0)
3617 .map_err(Into::into);
3618 }
3619 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3620 };
3621
3622 Ok(Arc::new(RenderImage::new(frames)))
3623 }
3624
3625 pub fn format(&self) -> ImageFormat {
3627 self.format
3628 }
3629
3630 pub fn bytes(&self) -> &[u8] {
3632 self.bytes.as_slice()
3633 }
3634}
3635
3636#[derive(Clone, Debug, Eq, PartialEq)]
3638pub struct ClipboardString {
3639 pub text: String,
3641 pub metadata: Option<String>,
3643}
3644
3645impl ClipboardString {
3646 pub fn new(text: String) -> Self {
3648 Self {
3649 text,
3650 metadata: None,
3651 }
3652 }
3653
3654 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3657 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3658 self
3659 }
3660
3661 pub fn text(&self) -> &String {
3663 &self.text
3664 }
3665
3666 pub fn into_text(self) -> String {
3668 self.text
3669 }
3670
3671 pub fn metadata_json<T>(&self) -> Option<T>
3673 where
3674 T: for<'a> Deserialize<'a>,
3675 {
3676 self.metadata
3677 .as_ref()
3678 .and_then(|m| serde_json::from_str(m).ok())
3679 }
3680
3681 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3682 pub fn text_hash(text: &str) -> u64 {
3684 let mut hasher = SeaHasher::new();
3685 text.hash(&mut hasher);
3686 hasher.finish()
3687 }
3688}
3689
3690impl From<String> for ClipboardString {
3691 fn from(value: String) -> Self {
3692 Self {
3693 text: value,
3694 metadata: None,
3695 }
3696 }
3697}
3698
3699#[cfg(test)]
3700mod image_tests {
3701 use super::*;
3702 use std::sync::Arc;
3703
3704 #[test]
3705 fn test_image_to_image_data_applies_exif_orientation() {
3706 let image = Image::from_bytes(
3707 ImageFormat::Jpeg,
3708 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3709 );
3710
3711 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3712
3713 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3714
3715 let bytes = render_image.as_bytes(0).unwrap();
3716 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3717 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3718 }
3719
3720 #[test]
3721 fn test_svg_image_to_image_data_converts_to_bgra() {
3722 let image = Image::from_bytes(
3723 ImageFormat::Svg,
3724 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3725<rect width="1" height="1" fill="#38BDF8"/>
3726</svg>"##
3727 .to_vec(),
3728 );
3729
3730 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3731 let bytes = render_image.as_bytes(0).unwrap();
3732
3733 for pixel in bytes.chunks_exact(4) {
3734 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3735 }
3736 }
3737
3738 #[test]
3739 fn test_animated_webp_image_to_image_data_decodes_frames() {
3740 const ANIMATED_WEBP: &[u8] = &[
3742 82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
3743 0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
3744 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,
3745 0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
3746 176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
3747 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,
3748 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,
3749 0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
3750 31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
3751 ];
3752
3753 let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
3754 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3755
3756 assert_eq!(render_image.frame_count(), 2);
3757 assert_eq!(render_image.size(0), size(1.into(), 1.into()));
3758 assert_eq!(
3759 Duration::from(render_image.delay(0)),
3760 Duration::from_millis(100)
3761 );
3762 assert_eq!(
3763 Duration::from(render_image.delay(1)),
3764 Duration::from_millis(100)
3765 );
3766 }
3767}
3768
3769#[cfg(test)]
3770mod atlas_tests {
3771 use super::*;
3772
3773 const TILE_SIZE: Size<DevicePixels> = Size {
3774 width: DevicePixels(1),
3775 height: DevicePixels(1),
3776 };
3777
3778 #[derive(Default)]
3779 struct RecordingAtlasBackend {
3780 insert_calls: u32,
3781 fail_next_insert: bool,
3782 removed_tiles: Vec<AtlasTile>,
3783 }
3784
3785 impl AtlasBackend for RecordingAtlasBackend {
3786 fn insert(
3787 &mut self,
3788 kind: AtlasTextureKind,
3789 size: Size<DevicePixels>,
3790 _bytes: &[u8],
3791 ) -> Result<AtlasTile> {
3792 self.insert_calls += 1;
3793 if std::mem::take(&mut self.fail_next_insert) {
3794 anyhow::bail!("backend failed");
3795 }
3796 Ok(AtlasTile {
3797 texture_id: AtlasTextureId { index: 0, kind },
3798 tile_id: TileId(self.insert_calls),
3799 padding: 0,
3800 bounds: Bounds {
3801 origin: Point::default(),
3802 size,
3803 },
3804 })
3805 }
3806
3807 fn remove(&mut self, tile: AtlasTile) {
3808 self.removed_tiles.push(tile);
3809 }
3810 }
3811
3812 fn image_key(image_id: usize) -> AtlasKey {
3813 AtlasKey::Image(RenderImageParams {
3814 image_id: crate::ImageId(image_id),
3815 frame_index: 0,
3816 })
3817 }
3818
3819 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3820 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3821 }
3822
3823 #[test]
3824 fn only_successful_inserts_are_cached() -> Result<()> {
3825 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3826 let key = image_key(1);
3827
3828 assert_eq!(
3829 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3830 None
3831 );
3832 state
3833 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3834 .expect_err("builder error should propagate");
3835 assert!(!state.contains(&key));
3836 assert_eq!(state.backend.insert_calls, 0);
3837
3838 state.backend.fail_next_insert = true;
3839 state
3840 .get_or_insert_with(key.clone(), &mut build_tile)
3841 .expect_err("backend error should propagate");
3842 assert!(!state.contains(&key));
3843 assert_eq!(state.backend.insert_calls, 1);
3844
3845 let tile = state
3846 .get_or_insert_with(key.clone(), &mut build_tile)?
3847 .context("builder should produce a tile")?;
3848 assert_eq!(tile.texture_id.kind, key.texture_kind());
3849 assert_eq!(
3850 state.get_or_insert_with(key.clone(), &mut || {
3851 anyhow::bail!("cache hit must not call the builder")
3852 })?,
3853 Some(tile)
3854 );
3855 assert!(state.contains(&key));
3856 assert_eq!(state.backend.insert_calls, 2);
3857 Ok(())
3858 }
3859
3860 #[test]
3861 fn remove_and_clear_invalidate_keys() -> Result<()> {
3862 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3863 let key = image_key(1);
3864 let other_key = image_key(2);
3865 let tile = state
3866 .get_or_insert_with(key.clone(), &mut build_tile)?
3867 .context("builder should produce a tile")?;
3868 state
3869 .get_or_insert_with(other_key.clone(), &mut build_tile)?
3870 .context("builder should produce another tile")?;
3871
3872 state.remove(&key);
3873 state.remove(&key);
3874 assert!(!state.contains(&key));
3875 assert!(state.contains(&other_key));
3876 assert_eq!(state.backend.removed_tiles, vec![tile]);
3877
3878 let mut reset_calls = 0;
3879 state.clear(|_| reset_calls += 1);
3880 assert_eq!(reset_calls, 1);
3881 assert!(!state.contains(&other_key));
3882 assert_eq!(state.backend.removed_tiles, vec![tile]);
3883 Ok(())
3884 }
3885}
3886
3887#[cfg(test)]
3888mod frame_signal_tests {
3889 use super::*;
3890
3891 #[cfg(feature = "profiler")]
3892 #[test]
3893 fn coalesced_signals_retain_the_earliest_until_drained() {
3894 for (first_source, later_source) in [
3895 (
3896 FrameRequestSource::NativeCallback,
3897 FrameRequestSource::LocalSchedule,
3898 ),
3899 (
3900 FrameRequestSource::LocalSchedule,
3901 FrameRequestSource::NativeCallback,
3902 ),
3903 ] {
3904 let signal = PlatformFrameSignal::new();
3905 let first =
3906 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3907 assert_eq!(signal.take(), None);
3908 signal.record(first + Duration::from_millis(16), later_source);
3909 signal.record(first, first_source);
3910 signal.record(first + Duration::from_millis(32), later_source);
3911 assert_eq!(signal.take(), Some((first, first_source)));
3912 assert_eq!(signal.take(), None);
3913 let next = first + Duration::from_millis(48);
3914 signal.record(next, later_source);
3915 assert_eq!(signal.take(), Some((next, later_source)));
3916 }
3917 }
3918
3919 #[cfg(not(feature = "profiler"))]
3920 #[test]
3921 fn disabled_profiling_does_not_capture_or_store_timestamps() {
3922 let captured = PlatformFrameSignal::capture(|| {
3923 panic!("profiler-disabled builds must not evaluate the capture closure");
3924 });
3925 assert_eq!(captured, None);
3926 let signal = PlatformFrameSignal::new();
3927 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3928 assert_eq!(signal.take(), None);
3929 }
3930}
3931
3932#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3933mod tests {
3934 use super::*;
3935 use std::collections::HashSet;
3936
3937 #[test]
3938 fn test_refresh_interval_from_hz() {
3939 assert_eq!(
3940 refresh_interval_from_hz(50.0),
3941 Some(Duration::from_millis(20))
3942 );
3943 assert_eq!(
3944 refresh_interval_from_hz(120.0),
3945 Some(Duration::from_secs(1) / 120)
3946 );
3947 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
3948 assert_eq!(refresh_interval_from_hz(unknown), None);
3949 }
3950 }
3951
3952 #[test]
3953 fn test_window_button_layout_parse_standard() {
3954 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3955 assert_eq!(
3956 layout.left,
3957 [
3958 Some(WindowButton::Close),
3959 Some(WindowButton::Minimize),
3960 None
3961 ]
3962 );
3963 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3964 }
3965
3966 #[test]
3967 fn test_window_button_layout_parse_right_only() {
3968 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3969 assert_eq!(layout.left, [None, None, None]);
3970 assert_eq!(
3971 layout.right,
3972 [
3973 Some(WindowButton::Minimize),
3974 Some(WindowButton::Maximize),
3975 Some(WindowButton::Close)
3976 ]
3977 );
3978 }
3979
3980 #[test]
3981 fn test_window_button_layout_parse_left_only() {
3982 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3983 assert_eq!(
3984 layout.left,
3985 [
3986 Some(WindowButton::Close),
3987 Some(WindowButton::Minimize),
3988 Some(WindowButton::Maximize)
3989 ]
3990 );
3991 assert_eq!(layout.right, [None, None, None]);
3992 }
3993
3994 #[test]
3995 fn test_window_button_layout_parse_with_whitespace() {
3996 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3997 assert_eq!(
3998 layout.left,
3999 [
4000 Some(WindowButton::Close),
4001 Some(WindowButton::Minimize),
4002 None
4003 ]
4004 );
4005 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4006 }
4007
4008 #[test]
4009 fn test_window_button_layout_parse_empty() {
4010 let layout = WindowButtonLayout::parse("").unwrap();
4011 assert_eq!(layout.left, [None, None, None]);
4012 assert_eq!(layout.right, [None, None, None]);
4013 }
4014
4015 #[test]
4016 fn test_window_button_layout_parse_intentionally_empty() {
4017 let layout = WindowButtonLayout::parse(":").unwrap();
4018 assert_eq!(layout.left, [None, None, None]);
4019 assert_eq!(layout.right, [None, None, None]);
4020 }
4021
4022 #[test]
4023 fn test_window_button_layout_parse_invalid_buttons() {
4024 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
4025 assert_eq!(
4026 layout.left,
4027 [
4028 Some(WindowButton::Close),
4029 Some(WindowButton::Minimize),
4030 None
4031 ]
4032 );
4033 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4034 }
4035
4036 #[test]
4037 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
4038 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
4039 assert_eq!(
4040 layout.right,
4041 [
4042 Some(WindowButton::Close),
4043 Some(WindowButton::Minimize),
4044 None
4045 ]
4046 );
4047 assert_eq!(layout.format(), ":close,minimize");
4048 }
4049
4050 #[test]
4051 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
4052 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
4053 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4054 assert_eq!(
4055 layout.right,
4056 [
4057 Some(WindowButton::Maximize),
4058 Some(WindowButton::Minimize),
4059 None
4060 ]
4061 );
4062
4063 let button_ids: Vec<_> = layout
4064 .left
4065 .iter()
4066 .chain(layout.right.iter())
4067 .flatten()
4068 .map(WindowButton::id)
4069 .collect();
4070 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4071 assert_eq!(unique_button_ids.len(), button_ids.len());
4072 assert_eq!(layout.format(), "close:maximize,minimize");
4073 }
4074
4075 #[test]
4076 fn test_window_button_layout_parse_gnome_style() {
4077 let layout = WindowButtonLayout::parse("close").unwrap();
4078 assert_eq!(layout.left, [None, None, None]);
4079 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4080 }
4081
4082 #[test]
4083 fn test_window_button_layout_parse_elementary_style() {
4084 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4085 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4086 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4087 }
4088
4089 #[test]
4090 fn test_window_button_layout_round_trip() {
4091 let cases = [
4092 "close:minimize,maximize",
4093 "minimize,maximize,close:",
4094 ":close",
4095 "close:",
4096 "close:maximize",
4097 ":",
4098 ];
4099
4100 for case in cases {
4101 let layout = WindowButtonLayout::parse(case).unwrap();
4102 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4103 }
4104 }
4105
4106 #[test]
4107 fn test_window_button_layout_linux_default() {
4108 let layout = WindowButtonLayout::linux_default();
4109 assert_eq!(layout.left, [None, None, None]);
4110 assert_eq!(
4111 layout.right,
4112 [
4113 Some(WindowButton::Minimize),
4114 Some(WindowButton::Maximize),
4115 Some(WindowButton::Close)
4116 ]
4117 );
4118
4119 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4120 assert_eq!(round_tripped, layout);
4121 }
4122
4123 #[test]
4124 fn test_window_button_layout_parse_all_invalid() {
4125 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4126 }
4127}