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) {
584 _ = tag;
585 }
586
587 fn on_system_notification_response(
593 &self,
594 callback: Box<dyn FnMut(SystemNotificationResponse)>,
595 ) {
596 _ = callback;
597 }
598
599 fn compositor_name(&self) -> &'static str {
600 ""
601 }
602 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
605 None
606 }
607 fn app_path(&self) -> Result<PathBuf>;
608 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
609
610 fn set_cursor_style(&self, style: CursorStyle);
611
612 fn hide_cursor_until_mouse_moves(&self);
615
616 fn is_cursor_visible(&self) -> bool;
618
619 fn should_auto_hide_scrollbars(&self) -> bool;
620
621 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
622 fn write_to_clipboard(&self, item: ClipboardItem);
623
624 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
632 Task::ready(Ok(self.read_from_clipboard()))
633 }
634
635 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
636 fn read_from_primary(&self) -> Option<ClipboardItem>;
637 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
638 fn write_to_primary(&self, item: ClipboardItem);
639
640 #[cfg(target_os = "macos")]
641 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
642 #[cfg(target_os = "macos")]
643 fn write_to_find_pasteboard(&self, item: ClipboardItem);
644
645 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
646
647 #[cfg(target_os = "macos")]
651 fn write_credentials_if_not_exists(
652 &self,
653 _url: &str,
654 _username: &str,
655 _password: &[u8],
656 ) -> Task<Result<bool>> {
657 Task::ready(Err(anyhow::anyhow!(
658 "this platform does not support atomic credential writes"
659 )))
660 }
661
662 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
663 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
664
665 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
666 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
667 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
668}
669
670pub trait PlatformDisplay: Debug {
672 fn id(&self) -> DisplayId;
674
675 fn uuid(&self) -> Result<Uuid>;
678
679 fn bounds(&self) -> Bounds<Pixels>;
681
682 fn refresh_interval(&self) -> Option<Duration>;
689
690 fn visible_bounds(&self) -> Bounds<Pixels> {
694 self.bounds()
695 }
696
697 fn default_bounds(&self) -> Bounds<Pixels> {
699 let bounds = self.bounds();
700 let center = bounds.center();
701 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
702
703 let offset = clipped_window_size / 2.0;
704 let origin = point(center.x - offset.width, center.y - offset.height);
705 Bounds::new(origin, clipped_window_size)
706 }
707}
708
709#[derive(Clone, Debug, PartialEq, Eq)]
712pub struct SystemNotification {
713 pub tag: SharedString,
717 pub title: SharedString,
719 pub body: SharedString,
721 pub actions: Vec<SystemNotificationAction>,
724}
725
726#[derive(Clone, Debug, PartialEq, Eq, Hash)]
728pub struct SystemNotificationAction {
729 pub id: SharedString,
732 pub label: SharedString,
734}
735
736#[derive(Clone, Debug, PartialEq, Eq)]
738pub struct SystemNotificationResponse {
739 pub tag: SharedString,
741 pub action_id: Option<SharedString>,
744}
745
746#[derive(Debug, Clone, Copy, PartialEq, Eq)]
748pub enum PowerMode {
749 Unknown,
752 LowPower,
754 Balanced,
756 HighPower,
758}
759
760#[derive(Debug, Clone, Copy, PartialEq, Eq)]
762pub enum ThermalState {
763 Nominal,
765 Fair,
767 Serious,
769 Critical,
771}
772
773#[derive(Clone)]
775pub struct SourceMetadata {
776 pub id: u64,
778 pub label: Option<SharedString>,
780 pub is_main: Option<bool>,
782 pub resolution: Size<DevicePixels>,
784}
785
786pub trait ScreenCaptureSource {
788 fn metadata(&self) -> Result<SourceMetadata>;
790
791 fn stream(
794 &self,
795 foreground_executor: &ForegroundExecutor,
796 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
797 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
798}
799
800pub trait ScreenCaptureStream {
802 fn metadata(&self) -> Result<SourceMetadata>;
804}
805
806pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
808
809#[derive(PartialEq, Eq, Hash, Copy, Clone)]
811pub struct DisplayId(pub(crate) u64);
812
813impl DisplayId {
814 pub fn new(id: u64) -> Self {
816 Self(id)
817 }
818}
819
820impl From<u64> for DisplayId {
821 fn from(id: u64) -> Self {
822 Self(id)
823 }
824}
825
826impl From<DisplayId> for u64 {
827 fn from(id: DisplayId) -> Self {
828 id.0
829 }
830}
831
832impl Debug for DisplayId {
833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834 write!(f, "DisplayId({})", self.0)
835 }
836}
837
838#[derive(Debug, Clone, Copy, PartialEq, Eq)]
840pub enum ResizeEdge {
841 Top,
843 TopRight,
845 Right,
847 BottomRight,
849 Bottom,
851 BottomLeft,
853 Left,
855 TopLeft,
857}
858
859#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
861pub enum WindowDecorations {
862 #[default]
863 Server,
865 Client,
867}
868
869#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
871pub enum Decorations {
872 #[default]
874 Server,
875 Client {
877 tiling: Tiling,
879 },
880}
881
882#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
884pub struct WindowControls {
885 pub fullscreen: bool,
887 pub maximize: bool,
889 pub minimize: bool,
891 pub window_menu: bool,
893}
894
895impl Default for WindowControls {
896 fn default() -> Self {
897 Self {
899 fullscreen: true,
900 maximize: true,
901 minimize: true,
902 window_menu: true,
903 }
904 }
905}
906
907#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
909pub enum WindowButton {
910 Minimize,
912 Maximize,
914 Close,
916}
917
918impl WindowButton {
919 pub fn id(&self) -> &'static str {
921 match self {
922 WindowButton::Minimize => "minimize",
923 WindowButton::Maximize => "maximize",
924 WindowButton::Close => "close",
925 }
926 }
927
928 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
929 fn index(&self) -> usize {
930 match self {
931 WindowButton::Minimize => 0,
932 WindowButton::Maximize => 1,
933 WindowButton::Close => 2,
934 }
935 }
936}
937
938pub const MAX_BUTTONS_PER_SIDE: usize = 3;
940
941#[derive(Debug, Clone, Copy, PartialEq, Eq)]
946pub struct WindowButtonLayout {
947 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
949 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
951}
952
953#[cfg(any(target_os = "linux", target_os = "freebsd"))]
954impl WindowButtonLayout {
955 pub fn linux_default() -> Self {
957 Self {
958 left: [None; MAX_BUTTONS_PER_SIDE],
959 right: [
960 Some(WindowButton::Minimize),
961 Some(WindowButton::Maximize),
962 Some(WindowButton::Close),
963 ],
964 }
965 }
966
967 pub fn parse(layout_string: &str) -> Result<Self> {
969 fn parse_side(
970 s: &str,
971 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
972 unrecognized: &mut Vec<String>,
973 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
974 let mut result = [None; MAX_BUTTONS_PER_SIDE];
975 let mut i = 0;
976 for name in s.split(',') {
977 let trimmed = name.trim();
978 if trimmed.is_empty() {
979 continue;
980 }
981 let button = match trimmed {
982 "minimize" => Some(WindowButton::Minimize),
983 "maximize" => Some(WindowButton::Maximize),
984 "close" => Some(WindowButton::Close),
985 other => {
986 unrecognized.push(other.to_string());
987 None
988 }
989 };
990 if let Some(button) = button {
991 if seen_buttons[button.index()] {
992 continue;
993 }
994 if let Some(slot) = result.get_mut(i) {
995 *slot = Some(button);
996 seen_buttons[button.index()] = true;
997 i += 1;
998 }
999 }
1000 }
1001 result
1002 }
1003
1004 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1005 let mut unrecognized = Vec::new();
1006 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1007 let layout = Self {
1008 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1009 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1010 };
1011
1012 if !unrecognized.is_empty()
1013 && layout.left.iter().all(Option::is_none)
1014 && layout.right.iter().all(Option::is_none)
1015 {
1016 bail!(
1017 "button layout string {:?} contains no valid buttons (unrecognized: {})",
1018 layout_string,
1019 unrecognized.join(", ")
1020 );
1021 }
1022
1023 Ok(layout)
1024 }
1025
1026 #[cfg(test)]
1028 pub fn format(&self) -> String {
1029 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1030 buttons
1031 .iter()
1032 .flatten()
1033 .map(|button| match button {
1034 WindowButton::Minimize => "minimize",
1035 WindowButton::Maximize => "maximize",
1036 WindowButton::Close => "close",
1037 })
1038 .collect::<Vec<_>>()
1039 .join(",")
1040 }
1041
1042 format!("{}:{}", format_side(&self.left), format_side(&self.right))
1043 }
1044}
1045
1046#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1048pub struct Tiling {
1049 pub top: bool,
1051 pub left: bool,
1053 pub right: bool,
1055 pub bottom: bool,
1057}
1058
1059impl Tiling {
1060 pub fn tiled() -> Self {
1062 Self {
1063 top: true,
1064 left: true,
1065 right: true,
1066 bottom: true,
1067 }
1068 }
1069
1070 pub fn is_tiled(&self) -> bool {
1072 self.top || self.left || self.right || self.bottom
1073 }
1074}
1075
1076pub struct A11yCallbacks {
1078 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1080 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1082 pub deactivation: Box<dyn Fn() + Send + 'static>,
1084}
1085
1086#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1088pub enum FrameRequestSource {
1089 #[default]
1091 NativeCallback,
1092 LocalSchedule,
1094}
1095
1096#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1097#[expect(missing_docs)]
1098pub struct RequestFrameOptions {
1099 pub require_presentation: bool,
1101 pub force_render: bool,
1103 pub signal_at: Option<Instant>,
1109 pub signal_source: FrameRequestSource,
1111}
1112
1113pub struct PlatformFrameSignal {
1122 #[cfg(feature = "profiler")]
1123 origin: Instant,
1124 #[cfg(feature = "profiler")]
1125 first_signal: std::sync::atomic::AtomicU64,
1126}
1127
1128impl Default for PlatformFrameSignal {
1129 fn default() -> Self {
1130 Self::new()
1131 }
1132}
1133
1134impl PlatformFrameSignal {
1135 pub fn new() -> Self {
1137 Self {
1138 #[cfg(feature = "profiler")]
1139 origin: Instant::now(),
1140 #[cfg(feature = "profiler")]
1141 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1142 }
1143 }
1144
1145 #[inline]
1149 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1150 if cfg!(feature = "profiler") {
1151 Some(capture())
1152 } else {
1153 None
1154 }
1155 }
1156
1157 #[inline]
1159 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1160 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1161 #[cfg(feature = "profiler")]
1162 {
1163 let nanoseconds = at
1164 .saturating_duration_since(self.origin)
1165 .as_nanos()
1166 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1167 let source_bit = match source {
1168 FrameRequestSource::NativeCallback => 0,
1169 FrameRequestSource::LocalSchedule => 1,
1170 };
1171 self.first_signal.fetch_min(
1172 (nanoseconds << 1) | source_bit,
1173 std::sync::atomic::Ordering::Relaxed,
1174 );
1175 }
1176 }
1177
1178 #[inline]
1180 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1181 #[cfg(feature = "profiler")]
1182 {
1183 let signal = self
1184 .first_signal
1185 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1186 (signal != u64::MAX).then(|| {
1187 let source = match signal & 1 {
1188 0 => FrameRequestSource::NativeCallback,
1189 _ => FrameRequestSource::LocalSchedule,
1190 };
1191 (self.origin + Duration::from_nanos(signal >> 1), source)
1192 })
1193 }
1194 #[cfg(not(feature = "profiler"))]
1195 {
1196 None
1197 }
1198 }
1199}
1200
1201#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1214pub enum AppLifecyclePhase {
1215 Active,
1217 Inactive,
1219 Background,
1222 Foreground,
1224 Disconnected,
1228}
1229
1230#[derive(Debug, Clone, Default, PartialEq)]
1237pub struct WindowInsets {
1238 pub safe_area: Edges<Pixels>,
1243 pub ime: Edges<Pixels>,
1247 pub corner_radii: Corners<Pixels>,
1252}
1253
1254impl WindowInsets {
1255 pub fn effective(&self) -> Edges<Pixels> {
1257 Edges {
1258 top: self.safe_area.top.max(self.ime.top),
1259 right: self.safe_area.right.max(self.ime.right),
1260 bottom: self.safe_area.bottom.max(self.ime.bottom),
1261 left: self.safe_area.left.max(self.ime.left),
1262 }
1263 }
1264}
1265
1266#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1268pub enum TextInputStateChange {
1269 FocusGained,
1271 FocusLost,
1273 SelectionChanged,
1275 ContentChanged,
1277}
1278
1279#[expect(missing_docs)]
1280pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1281 fn bounds(&self) -> Bounds<Pixels>;
1282 fn is_maximized(&self) -> bool;
1283 fn window_bounds(&self) -> WindowBounds;
1284 fn content_size(&self) -> Size<Pixels>;
1285 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1291 Bounds::new(Point::default(), self.content_size())
1292 }
1293 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1298 fn prepare_frame(&self) -> bool {
1303 false
1304 }
1305 fn resize(&mut self, size: Size<Pixels>);
1306 fn scale_factor(&self) -> f32;
1307 fn appearance(&self) -> WindowAppearance;
1308 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1309 fn mouse_position(&self) -> Point<Pixels>;
1310 fn modifiers(&self) -> Modifiers;
1311 fn capslock(&self) -> Capslock;
1312 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1313 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1314 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1319 fn prompt(
1320 &self,
1321 level: PromptLevel,
1322 msg: &str,
1323 detail: Option<&str>,
1324 answers: &[PromptButton],
1325 ) -> Option<oneshot::Receiver<usize>>;
1326 fn activate(&self);
1327 fn request_attention(&self) {}
1329 fn is_active(&self) -> bool;
1330 fn visibility(&self) -> WindowVisibility;
1333 fn is_hovered(&self) -> bool;
1334 fn background_appearance(&self) -> WindowBackgroundAppearance;
1335 fn set_title(&mut self, title: &str);
1336 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1337 fn minimize(&self);
1338 fn zoom(&self);
1339 fn toggle_fullscreen(&self);
1340 fn is_fullscreen(&self) -> bool;
1341 fn debug_state(&self) -> serde_json::Value {
1343 serde_json::Value::Null
1344 }
1345 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1346 None
1347 }
1348 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1349 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1350 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1351 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1355 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1356 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1357 fn on_moved(&self, callback: Box<dyn FnMut()>);
1358 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1362 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1363 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1364 fn on_close(&self, callback: Box<dyn FnOnce()>);
1365 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1366 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1367 fn draw(&self, scene: &Scene);
1368 fn draw_composed(&self, scene: crate::fast::composition::ComposedScene<'_>) {
1369 crate::fast::composition::draw_uncomposed(self, scene)
1370 }
1371 fn enable_window_composition(&self) -> Result<()> {
1372 crate::fast::composition::unsupported("window composition")
1373 }
1374 fn create_native_surface(
1375 &self,
1376 ) -> Result<Rc<dyn crate::fast::composition::PlatformSurfaceAttachment>> {
1377 crate::fast::composition::unsupported("native surface portals")
1378 }
1379 fn set_composition_order(
1380 &self,
1381 _fast_surfaces: &[crate::fast::composition::PlatformCompositionSurface],
1382 ) -> Result<()> {
1383 crate::fast::composition::unsupported("surface ordering")
1384 }
1385 fn schedule_frame(&self) {}
1386 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1387 fn is_subpixel_rendering_supported(&self) -> bool;
1388
1389 fn get_title(&self) -> String {
1391 String::new()
1392 }
1393 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1394 None
1395 }
1396 fn tab_bar_visible(&self) -> bool {
1397 false
1398 }
1399 fn set_edited(&mut self, _edited: bool) {}
1400 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1401 fn toggle_simple_fullscreen(&self) {}
1402 fn is_simple_fullscreen(&self) -> bool {
1403 false
1404 }
1405 #[cfg(target_os = "macos")]
1406 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1407 #[cfg(target_os = "macos")]
1408 fn set_native_titlebar_visibility(&self, _visible: bool) {}
1409 fn show_character_palette(&self) {}
1410 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1411 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1412 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1413 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1414 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1415 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1416 fn merge_all_windows(&self) {}
1417 fn move_tab_to_new_window(&self) {}
1418 fn toggle_window_tab_overview(&self) {}
1419 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1420
1421 fn native_window_state(&self) -> Option<Vec<u8>> {
1422 None
1423 }
1424 fn restore_native_window_state(&self, _state: &[u8]) {}
1425
1426 #[cfg(target_os = "windows")]
1427 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1428
1429 fn inner_window_bounds(&self) -> WindowBounds {
1431 self.window_bounds()
1432 }
1433 fn request_decorations(&self, _decorations: WindowDecorations) {}
1434 fn show_window_menu(&self, _position: Point<Pixels>) {}
1435 fn start_window_move(&self) {}
1436 fn can_start_external_drag(&self) -> bool {
1437 false
1438 }
1439 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1440 false
1441 }
1442 fn start_window_resize(&self, _edge: ResizeEdge) {}
1443 fn set_exclusive_zone(&self, _zone: Pixels) {}
1444 #[cfg(all(target_os = "linux", feature = "wayland"))]
1445 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1446 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1447 fn window_decorations(&self) -> Decorations {
1448 Decorations::Server
1449 }
1450 fn set_app_id(&mut self, _app_id: &str) {}
1451 fn map_window(&mut self) -> anyhow::Result<()> {
1452 Ok(())
1453 }
1454 fn window_controls(&self) -> WindowControls {
1455 WindowControls::default()
1456 }
1457 fn set_client_inset(&self, _inset: Pixels) {}
1458 fn set_client_corner_radii(&self, _radii: Corners<Pixels>) {}
1459 fn gpu_specs(&self) -> Option<GpuSpecs>;
1460
1461 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1462
1463 fn insets(&self) -> WindowInsets {
1468 WindowInsets::default()
1469 }
1470
1471 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1477
1478 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1481
1482 fn set_back_enabled(&self, _enabled: bool) {}
1485
1486 fn show_soft_keyboard(&self) {}
1488
1489 fn hide_soft_keyboard(&self) {}
1491
1492 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1494
1495 fn play_system_bell(&self) {}
1496
1497 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1499
1500 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1502
1503 fn a11y_update_window_bounds(&self) {}
1505
1506 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1507 fn as_test(&mut self) -> Option<&mut TestWindow> {
1508 None
1509 }
1510
1511 #[cfg(any(test, feature = "test-support"))]
1515 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1516 anyhow::bail!("render_to_image not implemented for this platform")
1517 }
1518}
1519
1520#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1522pub trait PlatformHeadlessRenderer {
1523 fn render_scene_to_image(
1525 &mut self,
1526 scene: &Scene,
1527 size: Size<DevicePixels>,
1528 ) -> Result<RgbaImage>;
1529
1530 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1536
1537 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1539}
1540
1541#[doc(hidden)]
1544pub type RunnableVariant = Runnable<RunnableMeta>;
1545
1546#[doc(hidden)]
1547pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1548
1549#[doc(hidden)]
1550pub enum TasksIncluded {
1551 OnlyCompleted,
1552 CompletedAndRunning,
1553}
1554
1555#[doc(hidden)]
1558pub trait PlatformDispatcher: Send + Sync {
1559 fn is_main_thread(&self) -> bool;
1560 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1561 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1562 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1563
1564 fn dispatch_on_main_thread_when_idle(
1565 &self,
1566 runnable: RunnableVariant,
1567 timeout: Option<Duration>,
1568 ) {
1569 let _ = timeout;
1570 self.dispatch_on_main_thread(runnable, Priority::Low);
1571 }
1572
1573 fn idle_time_remaining(&self) -> Option<Duration> {
1574 None
1575 }
1576
1577 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1578
1579 fn now(&self) -> Instant {
1580 Instant::now()
1581 }
1582
1583 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1584 gpui_util::defer(Box::new(|| {}))
1585 }
1586
1587 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1588 ActivityGuard::noop()
1589 }
1590
1591 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1592 fn as_test(&self) -> Option<&TestDispatcher> {
1593 None
1594 }
1595
1596 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1599 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1600 None
1601 }
1602}
1603
1604#[expect(missing_docs)]
1605pub trait PlatformTextSystem: Send + Sync {
1606 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1607 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1609 fn all_font_names(&self) -> Vec<String>;
1611 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1613 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1615 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1617 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1619 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1621 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1623 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1625 fn rasterize_glyph(
1627 &self,
1628 params: &RenderGlyphParams,
1629 raster_bounds: Bounds<DevicePixels>,
1630 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1631 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1633 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1635 -> TextRenderingMode;
1636 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1638 0
1639 }
1640}
1641
1642#[expect(missing_docs)]
1643pub struct NoopTextSystem;
1644
1645#[expect(missing_docs)]
1646impl NoopTextSystem {
1647 #[allow(dead_code)]
1648 pub fn new() -> Self {
1649 Self
1650 }
1651}
1652
1653impl PlatformTextSystem for NoopTextSystem {
1654 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1655 Ok(())
1656 }
1657
1658 fn all_font_names(&self) -> Vec<String> {
1659 Vec::new()
1660 }
1661
1662 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1663 Ok(FontId(1))
1664 }
1665
1666 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1667 FontMetrics {
1668 units_per_em: 1000,
1669 ascent: 1025.0,
1670 descent: -275.0,
1671 line_gap: 0.0,
1672 underline_position: -95.0,
1673 underline_thickness: 60.0,
1674 cap_height: 698.0,
1675 x_height: 516.0,
1676 bounding_box: Bounds {
1677 origin: Point {
1678 x: -260.0,
1679 y: -245.0,
1680 },
1681 size: Size {
1682 width: 1501.0,
1683 height: 1364.0,
1684 },
1685 },
1686 }
1687 }
1688
1689 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1690 Ok(Bounds {
1691 origin: Point { x: 54.0, y: 0.0 },
1692 size: size(392.0, 528.0),
1693 })
1694 }
1695
1696 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1697 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1698 }
1699
1700 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1701 Some(GlyphId(ch.len_utf16() as u32))
1702 }
1703
1704 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1705 Ok(Default::default())
1706 }
1707
1708 fn rasterize_glyph(
1709 &self,
1710 _params: &RenderGlyphParams,
1711 raster_bounds: Bounds<DevicePixels>,
1712 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1713 Ok((raster_bounds.size, Vec::new()))
1714 }
1715
1716 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1717 let mut position = px(0.);
1718 let metrics = self.font_metrics(FontId(0));
1719 let em_width = font_size
1720 * self
1721 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1722 .unwrap()
1723 .width
1724 / metrics.units_per_em as f32;
1725 let mut glyphs = Vec::new();
1726 for (ix, c) in text.char_indices() {
1727 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1728 glyphs.push(ShapedGlyph {
1729 id: glyph,
1730 position: point(position, px(0.)),
1731 index: ix,
1732 is_emoji: glyph.0 == 2,
1733 });
1734 if glyph.0 == 2 {
1735 position += em_width * 2.0;
1736 } else {
1737 position += em_width;
1738 }
1739 } else {
1740 position += em_width
1741 }
1742 }
1743 let mut runs = Vec::default();
1744 if !glyphs.is_empty() {
1745 runs.push(ShapedRun {
1746 font_id: FontId(0),
1747 glyphs,
1748 });
1749 } else {
1750 position = px(0.);
1751 }
1752
1753 LineLayout {
1754 font_size,
1755 width: position,
1756 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1757 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1758 runs,
1759 len: text.len(),
1760 }
1761 }
1762
1763 fn recommended_rendering_mode(
1764 &self,
1765 _font_id: FontId,
1766 _font_size: Pixels,
1767 ) -> TextRenderingMode {
1768 TextRenderingMode::Grayscale
1769 }
1770}
1771
1772#[allow(dead_code)]
1777pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1778 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1779 [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], ];
1793
1794 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1795 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1796
1797 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1798 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1799
1800 [
1801 ratios[0] * NORM13,
1802 ratios[1] * NORM24,
1803 ratios[2] * NORM13,
1804 ratios[3] * NORM24,
1805 ]
1806}
1807
1808#[derive(PartialEq, Eq, Hash, Clone)]
1809#[expect(missing_docs)]
1810pub enum AtlasKey {
1811 Glyph(RenderGlyphParams),
1812 Svg(RenderSvgParams),
1813 Image(RenderImageParams),
1814}
1815
1816impl AtlasKey {
1817 pub fn texture_kind(&self) -> AtlasTextureKind {
1819 match self {
1820 AtlasKey::Glyph(params) => {
1821 if params.is_emoji {
1822 AtlasTextureKind::Polychrome
1823 } else if params.subpixel_rendering {
1824 AtlasTextureKind::Subpixel
1825 } else {
1826 AtlasTextureKind::Monochrome
1827 }
1828 }
1829 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1830 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1831 }
1832 }
1833}
1834
1835impl From<RenderGlyphParams> for AtlasKey {
1836 fn from(params: RenderGlyphParams) -> Self {
1837 Self::Glyph(params)
1838 }
1839}
1840
1841impl From<RenderSvgParams> for AtlasKey {
1842 fn from(params: RenderSvgParams) -> Self {
1843 Self::Svg(params)
1844 }
1845}
1846
1847impl From<RenderImageParams> for AtlasKey {
1848 fn from(params: RenderImageParams) -> Self {
1849 Self::Image(params)
1850 }
1851}
1852
1853#[expect(missing_docs)]
1854pub trait PlatformAtlas {
1855 fn get_or_insert_with<'a>(
1857 &self,
1858 key: AtlasKey,
1859 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1860 ) -> Result<Option<AtlasTile>>;
1861 fn remove(&self, key: &AtlasKey);
1862
1863 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1864 fn contains(&self, _key: &AtlasKey) -> bool {
1865 false
1866 }
1867}
1868
1869#[doc(hidden)]
1870pub trait AtlasBackend {
1871 fn insert(
1872 &mut self,
1873 kind: AtlasTextureKind,
1874 size: Size<DevicePixels>,
1875 bytes: &[u8],
1876 ) -> Result<AtlasTile>;
1877
1878 fn remove(&mut self, tile: AtlasTile);
1879}
1880
1881#[doc(hidden)]
1882pub struct AtlasState<Backend> {
1883 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1884 pub backend: Backend,
1885}
1886
1887impl<Backend> AtlasState<Backend> {
1888 pub fn new(backend: Backend) -> Self {
1889 Self {
1890 tiles_by_key: FxHashMap::default(),
1891 backend,
1892 }
1893 }
1894
1895 pub fn contains(&self, key: &AtlasKey) -> bool {
1896 self.tiles_by_key.contains_key(key)
1897 }
1898
1899 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1900 self.tiles_by_key.clear();
1901 reset_backend(&mut self.backend);
1902 }
1903}
1904
1905impl<Backend: Default> Default for AtlasState<Backend> {
1906 fn default() -> Self {
1907 Self::new(Backend::default())
1908 }
1909}
1910
1911impl<Backend: AtlasBackend> AtlasState<Backend> {
1912 pub fn get_or_insert_with<'a>(
1913 &mut self,
1914 key: AtlasKey,
1915 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1916 ) -> Result<Option<AtlasTile>> {
1917 match self.tiles_by_key.entry(key) {
1918 Entry::Occupied(entry) => Ok(Some(*entry.get())),
1919 Entry::Vacant(entry) => {
1920 profiling::scope!("new tile");
1921 let Some((size, bytes)) = build()? else {
1922 return Ok(None);
1923 };
1924 let tile = self
1925 .backend
1926 .insert(entry.key().texture_kind(), size, &bytes)?;
1927 entry.insert(tile);
1928 Ok(Some(tile))
1929 }
1930 }
1931 }
1932
1933 pub fn remove(&mut self, key: &AtlasKey) {
1934 if let Some(tile) = self.tiles_by_key.remove(key) {
1935 self.backend.remove(tile);
1936 }
1937 }
1938}
1939
1940#[derive(Default)]
1944pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1945
1946#[doc(hidden)]
1947#[derive(Default)]
1948pub struct HeadlessAtlasBackend {
1949 next_id: u32,
1950}
1951
1952impl AtlasBackend for HeadlessAtlasBackend {
1953 fn insert(
1954 &mut self,
1955 kind: AtlasTextureKind,
1956 size: Size<DevicePixels>,
1957 _bytes: &[u8],
1958 ) -> Result<AtlasTile> {
1959 self.next_id += 1;
1960 let texture_id = self.next_id;
1961 self.next_id += 1;
1962 let tile_id = self.next_id;
1963 Ok(AtlasTile {
1964 texture_id: AtlasTextureId {
1965 index: texture_id,
1966 kind,
1967 },
1968 tile_id: TileId(tile_id),
1969 padding: 0,
1970 bounds: Bounds {
1971 origin: Point::default(),
1972 size,
1973 },
1974 })
1975 }
1976
1977 fn remove(&mut self, _tile: AtlasTile) {}
1978}
1979
1980impl PlatformAtlas for HeadlessAtlas {
1981 fn get_or_insert_with<'a>(
1982 &self,
1983 key: AtlasKey,
1984 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1985 ) -> Result<Option<AtlasTile>> {
1986 self.0.lock().get_or_insert_with(key, build)
1987 }
1988
1989 fn remove(&self, key: &AtlasKey) {
1990 self.0.lock().remove(key);
1991 }
1992
1993 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1994 fn contains(&self, key: &AtlasKey) -> bool {
1995 self.0.lock().contains(key)
1996 }
1997}
1998
1999#[doc(hidden)]
2000pub struct AtlasTextureList<T> {
2001 pub textures: Vec<Option<T>>,
2002 pub free_list: Vec<usize>,
2003}
2004
2005impl<T> Default for AtlasTextureList<T> {
2006 fn default() -> Self {
2007 Self {
2008 textures: Vec::default(),
2009 free_list: Vec::default(),
2010 }
2011 }
2012}
2013
2014impl<T> ops::Index<usize> for AtlasTextureList<T> {
2015 type Output = Option<T>;
2016
2017 fn index(&self, index: usize) -> &Self::Output {
2018 &self.textures[index]
2019 }
2020}
2021
2022impl<T> AtlasTextureList<T> {
2023 #[allow(unused)]
2024 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2025 self.free_list.clear();
2026 self.textures.drain(..)
2027 }
2028
2029 #[allow(dead_code)]
2030 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2031 self.textures.iter_mut().flatten()
2032 }
2033}
2034
2035#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2036#[repr(C)]
2037#[expect(missing_docs)]
2038pub struct AtlasTile {
2039 pub texture_id: AtlasTextureId,
2041 pub tile_id: TileId,
2043 pub padding: u32,
2045 pub bounds: Bounds<DevicePixels>,
2047}
2048
2049#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2050#[repr(C)]
2051#[expect(missing_docs)]
2052pub struct AtlasTextureId {
2053 pub index: u32,
2056 pub kind: AtlasTextureKind,
2058}
2059
2060#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2061#[repr(C)]
2062#[cfg_attr(
2063 all(
2064 any(target_os = "linux", target_os = "freebsd"),
2065 not(any(feature = "x11", feature = "wayland"))
2066 ),
2067 allow(dead_code)
2068)]
2069#[expect(missing_docs)]
2070pub enum AtlasTextureKind {
2071 Monochrome = 0,
2072 Polychrome = 1,
2073 Subpixel = 2,
2074}
2075
2076#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2077#[repr(C)]
2078#[expect(missing_docs)]
2079pub struct TileId(pub u32);
2080
2081impl From<etagere::AllocId> for TileId {
2082 fn from(id: etagere::AllocId) -> Self {
2083 Self(id.serialize())
2084 }
2085}
2086
2087impl From<TileId> for etagere::AllocId {
2088 fn from(id: TileId) -> Self {
2089 Self::deserialize(id.0)
2090 }
2091}
2092
2093#[expect(missing_docs)]
2094pub struct PlatformInputHandler {
2095 cx: AsyncWindowContext,
2096 handler: Box<dyn InputHandler>,
2097 focus_id: Option<crate::FocusId>,
2098}
2099
2100#[expect(missing_docs)]
2101#[cfg_attr(
2102 all(
2103 any(target_os = "linux", target_os = "freebsd"),
2104 not(any(feature = "x11", feature = "wayland"))
2105 ),
2106 allow(dead_code)
2107)]
2108impl PlatformInputHandler {
2109 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2110 Self {
2111 cx,
2112 handler,
2113 focus_id: None,
2114 }
2115 }
2116
2117 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2118 self.focus_id = Some(focus_id);
2119 self
2120 }
2121
2122 pub fn focus_id(&self) -> Option<crate::FocusId> {
2127 self.focus_id
2128 }
2129
2130 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2131 self.cx
2132 .update(|window, cx| {
2133 self.handler
2134 .selected_text_range(ignore_disabled_input, window, cx)
2135 })
2136 .ok()
2137 .flatten()
2138 }
2139
2140 #[cfg_attr(target_os = "windows", allow(dead_code))]
2141 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2142 self.cx
2143 .update(|window, cx| self.handler.marked_text_range(window, cx))
2144 .ok()
2145 .flatten()
2146 }
2147
2148 #[cfg_attr(
2149 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2150 allow(dead_code)
2151 )]
2152 pub fn text_for_range(
2153 &mut self,
2154 range_utf16: Range<usize>,
2155 adjusted: &mut Option<Range<usize>>,
2156 ) -> Option<String> {
2157 self.cx
2158 .update(|window, cx| {
2159 self.handler
2160 .text_for_range(range_utf16, adjusted, window, cx)
2161 })
2162 .ok()
2163 .flatten()
2164 }
2165
2166 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2167 self.cx
2168 .update(|window, cx| {
2169 self.handler
2170 .replace_text_in_range(replacement_range, text, window, cx);
2171 })
2172 .ok();
2173 }
2174
2175 pub fn replace_and_mark_text_in_range(
2176 &mut self,
2177 range_utf16: Option<Range<usize>>,
2178 new_text: &str,
2179 new_selected_range: Option<Range<usize>>,
2180 ) {
2181 self.cx
2182 .update(|window, cx| {
2183 self.handler.replace_and_mark_text_in_range(
2184 range_utf16,
2185 new_text,
2186 new_selected_range,
2187 window,
2188 cx,
2189 )
2190 })
2191 .ok();
2192 }
2193
2194 #[cfg_attr(target_os = "windows", allow(dead_code))]
2195 pub fn unmark_text(&mut self) {
2196 self.cx
2197 .update(|window, cx| self.handler.unmark_text(window, cx))
2198 .ok();
2199 }
2200
2201 pub fn paste(&mut self, item: ClipboardItem) {
2202 self.cx
2203 .update(|window, cx| self.handler.paste(item, window, cx))
2204 .ok();
2205 }
2206
2207 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2208 self.cx
2209 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2210 .ok()
2211 .flatten()
2212 }
2213
2214 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2215 self.cx
2216 .update(|window, cx| {
2217 self.handler
2218 .selection_bounds_for_range(range_utf16, window, cx)
2219 })
2220 .unwrap_or_default()
2221 }
2222
2223 #[allow(dead_code)]
2224 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2225 self.handler.apple_press_and_hold_enabled()
2226 }
2227
2228 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2229 self.handler.replace_text_in_range(None, input, window, cx);
2230 }
2231
2232 pub fn compute_ime_candidate_bounds(
2233 marked_range: Option<Range<usize>>,
2234 selection: &UTF16Selection,
2235 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2236 ) -> Option<Bounds<Pixels>> {
2237 if let Some(marked_range) = marked_range {
2238 let mut line_start = marked_range.start;
2240
2241 let caret = selection.range.end;
2245 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2246 for i in (marked_range.start..caret).rev() {
2247 if let Some(b) = bounds_for_range(i..i) {
2248 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2249 line_start = i + 1;
2250 break;
2251 }
2252 }
2253 }
2254 }
2255 bounds_for_range(line_start..line_start)
2256 } else {
2257 let offset = if selection.reversed {
2259 selection.range.start
2260 } else {
2261 selection.range.end
2262 };
2263 bounds_for_range(offset..offset)
2264 }
2265 }
2266
2267 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2268 let marked_range = self.handler.marked_text_range(window, cx);
2269 let selection = self.handler.selected_text_range(true, window, cx)?;
2270 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2271 self.handler.bounds_for_range(range, window, cx)
2272 })
2273 }
2274
2275 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2276 let marked_range = self.marked_text_range();
2277 let selection = self.selected_text_range(true)?;
2278 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2279 self.bounds_for_range(range)
2280 })
2281 }
2282
2283 #[allow(unused)]
2284 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2285 self.cx
2286 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2287 .ok()
2288 .flatten()
2289 }
2290
2291 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2293 self.cx
2294 .update(|window, cx| {
2295 self.handler
2296 .set_selected_text_range(range_utf16, window, cx)
2297 })
2298 .ok();
2299 }
2300
2301 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2303 self.cx
2304 .update(|window, cx| self.handler.element_bounds(window, cx))
2305 .ok()
2306 .flatten()
2307 }
2308
2309 pub fn text_length_utf16(&mut self) -> Option<usize> {
2311 self.cx
2312 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2313 .ok()
2314 .flatten()
2315 }
2316
2317 #[allow(dead_code)]
2318 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2319 self.handler.accepts_text_input(window, cx)
2320 }
2321
2322 #[allow(dead_code)]
2323 pub fn query_accepts_text_input(&mut self) -> bool {
2324 self.cx
2325 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2326 .unwrap_or(true)
2327 }
2328
2329 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2334 let focus_id = self.focus_id;
2335 self.cx
2336 .update(|window, cx| {
2337 focus_id.is_some()
2338 && window.focus == focus_id
2339 && self.handler.accepts_text_input(window, cx)
2340 })
2341 .unwrap_or(false)
2342 }
2343
2344 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2350 self.cx
2351 .update(|window, cx| {
2352 !window.has_pending_keystrokes()
2354 && self.handler.prefers_ime_for_printable_keys(window, cx)
2355 })
2356 .unwrap_or(false)
2357 }
2358
2359 pub fn text_input_configuration(
2361 &mut self,
2362 window: &mut Window,
2363 cx: &mut App,
2364 ) -> TextInputConfiguration {
2365 self.handler.text_input_configuration(window, cx)
2366 }
2367
2368 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2370 self.cx
2371 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2372 .ok()
2373 .flatten()
2374 }
2375}
2376
2377#[derive(Debug)]
2380pub struct UTF16Selection {
2381 pub range: Range<usize>,
2384 pub reversed: bool,
2387}
2388
2389pub trait InputHandler: 'static {
2394 fn selected_text_range(
2399 &mut self,
2400 ignore_disabled_input: bool,
2401 window: &mut Window,
2402 cx: &mut App,
2403 ) -> Option<UTF16Selection>;
2404
2405 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2410
2411 fn text_for_range(
2416 &mut self,
2417 range_utf16: Range<usize>,
2418 adjusted_range: &mut Option<Range<usize>>,
2419 window: &mut Window,
2420 cx: &mut App,
2421 ) -> Option<String>;
2422
2423 fn replace_text_in_range(
2428 &mut self,
2429 replacement_range: Option<Range<usize>>,
2430 text: &str,
2431 window: &mut Window,
2432 cx: &mut App,
2433 );
2434
2435 fn replace_and_mark_text_in_range(
2442 &mut self,
2443 range_utf16: Option<Range<usize>>,
2444 new_text: &str,
2445 new_selected_range: Option<Range<usize>>,
2446 window: &mut Window,
2447 cx: &mut App,
2448 );
2449
2450 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2453
2454 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2461 if let Some(text) = item.text() {
2462 self.replace_text_in_range(None, &text, window, cx);
2463 }
2464 }
2465
2466 fn bounds_for_range(
2471 &mut self,
2472 range_utf16: Range<usize>,
2473 window: &mut Window,
2474 cx: &mut App,
2475 ) -> Option<Bounds<Pixels>>;
2476
2477 fn selection_bounds_for_range(
2484 &mut self,
2485 _range_utf16: Range<usize>,
2486 _window: &mut Window,
2487 _cx: &mut App,
2488 ) -> Vec<Bounds<Pixels>> {
2489 Vec::new()
2490 }
2491
2492 fn character_index_for_point(
2496 &mut self,
2497 point: Point<Pixels>,
2498 window: &mut Window,
2499 cx: &mut App,
2500 ) -> Option<usize>;
2501
2502 fn set_selected_text_range(
2512 &mut self,
2513 _range_utf16: Range<usize>,
2514 _window: &mut Window,
2515 _cx: &mut App,
2516 ) {
2517 }
2518
2519 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2526 None
2527 }
2528
2529 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2531 None
2532 }
2533
2534 #[allow(dead_code)]
2539 fn apple_press_and_hold_enabled(&mut self) -> bool {
2540 true
2541 }
2542
2543 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2545 true
2546 }
2547
2548 fn text_input_editable_range(
2559 &mut self,
2560 _window: &mut Window,
2561 _cx: &mut App,
2562 ) -> Option<Range<usize>> {
2563 None
2564 }
2565
2566 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2575 false
2576 }
2577
2578 fn text_input_configuration(
2584 &mut self,
2585 _window: &mut Window,
2586 _cx: &mut App,
2587 ) -> TextInputConfiguration {
2588 TextInputConfiguration::default()
2589 }
2590}
2591
2592#[derive(Clone, Debug, Default, PartialEq, Eq)]
2602pub struct TextInputConfiguration {
2603 pub autocorrect: bool,
2605 pub autocapitalize: Autocapitalize,
2607 pub suggestions: bool,
2609 pub input_action: TextInputAction,
2611}
2612
2613#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2615pub enum Autocapitalize {
2616 #[default]
2618 None,
2619 Words,
2621 Sentences,
2623 Characters,
2625}
2626
2627#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2637pub enum TextInputAction {
2638 #[default]
2640 Unspecified,
2641 Enter,
2643 Done,
2645 Go,
2647 Next,
2649 Previous,
2651 Search,
2653 Send,
2655}
2656
2657#[derive(Debug)]
2659pub struct WindowOptions {
2660 pub window_bounds: Option<WindowBounds>,
2664
2665 pub titlebar: Option<TitlebarOptions>,
2667
2668 pub focus: bool,
2670
2671 pub show: bool,
2673
2674 pub kind: WindowKind,
2676
2677 pub is_movable: bool,
2681
2682 pub app_owns_titlebar_drag: bool,
2694
2695 pub inactive_frame_interval: Option<Duration>,
2700
2701 pub low_power_frame_interval: Option<Duration>,
2706
2707 pub thermal_frame_interval: Option<Duration>,
2712
2713 pub is_resizable: bool,
2715
2716 pub is_minimizable: bool,
2718
2719 pub display_id: Option<DisplayId>,
2722
2723 pub window_background: WindowBackgroundAppearance,
2725
2726 pub app_id: Option<String>,
2728
2729 pub window_min_size: Option<Size<Pixels>>,
2731
2732 pub window_decorations: Option<WindowDecorations>,
2735
2736 pub icon: Option<Arc<image::RgbaImage>>,
2738
2739 pub tabbing_identifier: Option<String>,
2741
2742 pub use_display_p3: bool,
2744}
2745
2746#[derive(Debug)]
2748#[cfg_attr(
2749 all(
2750 any(target_os = "linux", target_os = "freebsd"),
2751 not(any(feature = "x11", feature = "wayland"))
2752 ),
2753 allow(dead_code)
2754)]
2755#[allow(missing_docs)]
2756pub struct WindowParams {
2757 pub bounds: Bounds<Pixels>,
2758
2759 #[cfg_attr(feature = "wayland", allow(dead_code))]
2761 pub titlebar: Option<TitlebarOptions>,
2762
2763 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2765 pub kind: WindowKind,
2766
2767 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2769 pub is_movable: bool,
2770
2771 #[cfg_attr(
2773 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2774 allow(dead_code)
2775 )]
2776 pub app_owns_titlebar_drag: bool,
2777
2778 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2780 pub is_resizable: bool,
2781
2782 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2784 pub is_minimizable: bool,
2785
2786 #[cfg_attr(
2787 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2788 allow(dead_code)
2789 )]
2790 pub focus: bool,
2791
2792 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2793 pub show: bool,
2794
2795 #[cfg_attr(feature = "wayland", allow(dead_code))]
2797 pub icon: Option<Arc<image::RgbaImage>>,
2798
2799 #[cfg_attr(feature = "wayland", allow(dead_code))]
2800 pub display_id: Option<DisplayId>,
2801
2802 #[cfg_attr(feature = "wayland", allow(dead_code))]
2803 pub app_id: Option<String>,
2804
2805 pub window_min_size: Option<Size<Pixels>>,
2806
2807 #[cfg(target_os = "macos")]
2808 pub tabbing_identifier: Option<String>,
2809
2810 #[cfg(target_os = "macos")]
2811 pub use_display_p3: bool,
2812}
2813
2814#[derive(Debug, Copy, Clone, PartialEq)]
2816pub enum WindowBounds {
2817 Windowed(Bounds<Pixels>),
2819 Maximized(Bounds<Pixels>),
2822 Fullscreen(Bounds<Pixels>),
2825}
2826
2827impl Default for WindowBounds {
2828 fn default() -> Self {
2829 WindowBounds::Windowed(Bounds::default())
2830 }
2831}
2832
2833impl WindowBounds {
2834 pub fn get_bounds(&self) -> Bounds<Pixels> {
2836 match self {
2837 WindowBounds::Windowed(bounds) => *bounds,
2838 WindowBounds::Maximized(bounds) => *bounds,
2839 WindowBounds::Fullscreen(bounds) => *bounds,
2840 }
2841 }
2842
2843 pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
2846 WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
2847 }
2848}
2849
2850impl Default for WindowOptions {
2851 fn default() -> Self {
2852 Self {
2853 window_bounds: None,
2854 titlebar: Some(TitlebarOptions {
2855 title: Default::default(),
2856 appears_transparent: Default::default(),
2857 traffic_light_position: Default::default(),
2858 }),
2859 focus: true,
2860 show: true,
2861 kind: WindowKind::Normal,
2862 is_movable: true,
2863 app_owns_titlebar_drag: false,
2864 inactive_frame_interval: Some(Duration::from_micros(33_333)),
2865 low_power_frame_interval: Some(Duration::from_micros(33_333)),
2866 thermal_frame_interval: Some(Duration::from_micros(16_667)),
2867 is_resizable: true,
2868 is_minimizable: true,
2869 display_id: None,
2870 window_background: WindowBackgroundAppearance::default(),
2871 icon: None,
2872 app_id: None,
2873 window_min_size: None,
2874 window_decorations: None,
2875 tabbing_identifier: None,
2876 use_display_p3: false,
2877 }
2878 }
2879}
2880
2881#[derive(Debug, Default)]
2883pub struct TitlebarOptions {
2884 pub title: Option<SharedString>,
2886
2887 pub appears_transparent: bool,
2890
2891 pub traffic_light_position: Option<Point<Pixels>>,
2893}
2894
2895#[derive(Clone, Debug, PartialEq, Eq)]
2897pub enum WindowKind {
2898 Normal,
2900
2901 PopUp,
2904
2905 AnchoredPopup(popup::PopupOptions),
2912
2913 Floating,
2915
2916 #[cfg(all(target_os = "linux", feature = "wayland"))]
2919 LayerShell(layer_shell::LayerShellOptions),
2920
2921 Dialog,
2924}
2925
2926#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2931pub enum WindowAppearance {
2932 #[default]
2936 Light,
2937
2938 VibrantLight,
2942
2943 Dark,
2947
2948 VibrantDark,
2952}
2953
2954#[derive(Copy, Clone, Debug, Default, PartialEq)]
2957pub enum WindowBackgroundAppearance {
2958 #[default]
2966 Opaque,
2967 Transparent,
2969 Blurred,
2973 MicaBackdrop,
2975 MicaAltBackdrop,
2977}
2978
2979#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2981pub enum TextRenderingMode {
2982 #[default]
2984 PlatformDefault,
2985 Subpixel,
2987 Grayscale,
2989}
2990
2991#[derive(Clone, Debug)]
2993pub struct PathPromptOptions {
2994 pub files: bool,
2996 pub directories: bool,
2998 pub multiple: bool,
3000 pub prompt: Option<SharedString>,
3002}
3003
3004#[derive(Copy, Clone, Debug, PartialEq)]
3006pub enum PromptLevel {
3007 Info,
3009
3010 Warning,
3012
3013 Critical,
3015}
3016
3017#[derive(Clone, Debug, PartialEq)]
3019pub enum PromptButton {
3020 Ok(SharedString),
3022 Cancel(SharedString),
3024 Other(SharedString),
3026}
3027
3028impl PromptButton {
3029 pub fn new(label: impl Into<SharedString>) -> Self {
3031 PromptButton::Other(label.into())
3032 }
3033
3034 pub fn ok(label: impl Into<SharedString>) -> Self {
3036 PromptButton::Ok(label.into())
3037 }
3038
3039 pub fn cancel(label: impl Into<SharedString>) -> Self {
3041 PromptButton::Cancel(label.into())
3042 }
3043
3044 #[allow(dead_code)]
3046 pub fn is_cancel(&self) -> bool {
3047 matches!(self, PromptButton::Cancel(_))
3048 }
3049
3050 pub fn label(&self) -> &SharedString {
3052 match self {
3053 PromptButton::Ok(label) => label,
3054 PromptButton::Cancel(label) => label,
3055 PromptButton::Other(label) => label,
3056 }
3057 }
3058}
3059
3060impl From<&str> for PromptButton {
3061 fn from(value: &str) -> Self {
3062 match value.to_lowercase().as_str() {
3063 "ok" => PromptButton::Ok("OK".into()),
3064 "cancel" => PromptButton::Cancel("Cancel".into()),
3065 _ => PromptButton::Other(SharedString::from(value.to_owned())),
3066 }
3067 }
3068}
3069
3070#[derive(
3072 Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, EnumIter,
3073)]
3074pub enum CursorStyle {
3075 #[default]
3077 Arrow,
3078
3079 IBeam,
3082
3083 Crosshair,
3086
3087 ClosedHand,
3090
3091 OpenHand,
3094
3095 PointingHand,
3098
3099 ResizeLeft,
3102
3103 ResizeRight,
3106
3107 ResizeLeftRight,
3110
3111 ResizeUp,
3114
3115 ResizeDown,
3118
3119 ResizeUpDown,
3122
3123 ResizeUpLeftDownRight,
3126
3127 ResizeUpRightDownLeft,
3130
3131 ResizeColumn,
3134
3135 ResizeRow,
3138
3139 IBeamCursorForVerticalLayout,
3142
3143 OperationNotAllowed,
3146
3147 DragLink,
3150
3151 DragCopy,
3154
3155 ContextualMenu,
3158}
3159
3160#[derive(Clone, Debug, Eq, PartialEq)]
3162pub struct ClipboardItem {
3163 pub entries: Vec<ClipboardEntry>,
3165}
3166
3167#[derive(Clone, Debug, PartialEq, Eq)]
3172pub enum ClipboardReadError {
3173 Unavailable,
3177 Denied(String),
3180 UnsupportedContent,
3183}
3184
3185impl std::fmt::Display for ClipboardReadError {
3186 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3187 match self {
3188 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3189 Self::Denied(message) => {
3190 write!(formatter, "clipboard access was denied: {message}")
3191 }
3192 Self::UnsupportedContent => {
3193 formatter.write_str("the clipboard contents are unsupported")
3194 }
3195 }
3196 }
3197}
3198
3199impl std::error::Error for ClipboardReadError {}
3200
3201#[derive(Clone, Debug, Eq, PartialEq)]
3203pub enum ClipboardEntry {
3204 String(ClipboardString),
3206 Image(Image),
3208 ExternalPaths(crate::ExternalPaths),
3210}
3211
3212impl ClipboardItem {
3213 pub fn new_string(text: String) -> Self {
3215 Self {
3216 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3217 }
3218 }
3219
3220 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3222 Self {
3223 entries: vec![ClipboardEntry::String(ClipboardString {
3224 text,
3225 metadata: Some(metadata),
3226 })],
3227 }
3228 }
3229
3230 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3232 Self {
3233 entries: vec![ClipboardEntry::String(
3234 ClipboardString::new(text).with_json_metadata(metadata),
3235 )],
3236 }
3237 }
3238
3239 pub fn new_image(image: &Image) -> Self {
3241 Self {
3242 entries: vec![ClipboardEntry::Image(image.clone())],
3243 }
3244 }
3245
3246 pub fn text(&self) -> Option<String> {
3249 let mut answer = String::new();
3250
3251 for entry in self.entries.iter() {
3252 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3253 answer.push_str(text);
3254 }
3255 }
3256
3257 if answer.is_empty() {
3258 for entry in self.entries.iter() {
3259 if let ClipboardEntry::ExternalPaths(paths) = entry {
3260 for path in &paths.0 {
3261 use std::fmt::Write as _;
3262 _ = write!(answer, "{}", path.display());
3263 }
3264 }
3265 }
3266 }
3267
3268 if !answer.is_empty() {
3269 Some(answer)
3270 } else {
3271 None
3272 }
3273 }
3274
3275 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3277 pub fn metadata(&self) -> Option<&String> {
3278 match self.entries().first() {
3279 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3280 clipboard_string.metadata.as_ref()
3281 }
3282 _ => None,
3283 }
3284 }
3285
3286 pub fn entries(&self) -> &[ClipboardEntry] {
3288 &self.entries
3289 }
3290
3291 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3293 self.entries.into_iter()
3294 }
3295}
3296
3297impl From<ClipboardString> for ClipboardEntry {
3298 fn from(value: ClipboardString) -> Self {
3299 Self::String(value)
3300 }
3301}
3302
3303impl From<String> for ClipboardEntry {
3304 fn from(value: String) -> Self {
3305 Self::from(ClipboardString::from(value))
3306 }
3307}
3308
3309impl From<Image> for ClipboardEntry {
3310 fn from(value: Image) -> Self {
3311 Self::Image(value)
3312 }
3313}
3314
3315impl From<ClipboardEntry> for ClipboardItem {
3316 fn from(value: ClipboardEntry) -> Self {
3317 Self {
3318 entries: vec![value],
3319 }
3320 }
3321}
3322
3323impl From<String> for ClipboardItem {
3324 fn from(value: String) -> Self {
3325 Self::from(ClipboardEntry::from(value))
3326 }
3327}
3328
3329impl From<Image> for ClipboardItem {
3330 fn from(value: Image) -> Self {
3331 Self::from(ClipboardEntry::from(value))
3332 }
3333}
3334
3335#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3337pub enum ImageFormat {
3338 Png,
3343 Jpeg,
3345 Webp,
3347 Gif,
3349 Svg,
3351 Bmp,
3353 Tiff,
3355 Ico,
3357 Pnm,
3359}
3360
3361impl ImageFormat {
3362 pub const fn mime_type(self) -> &'static str {
3364 match self {
3365 ImageFormat::Png => "image/png",
3366 ImageFormat::Jpeg => "image/jpeg",
3367 ImageFormat::Webp => "image/webp",
3368 ImageFormat::Gif => "image/gif",
3369 ImageFormat::Svg => "image/svg+xml",
3370 ImageFormat::Bmp => "image/bmp",
3371 ImageFormat::Tiff => "image/tiff",
3372 ImageFormat::Ico => "image/ico",
3373 ImageFormat::Pnm => "image/x-portable-anymap",
3374 }
3375 }
3376
3377 pub const fn extension(self) -> &'static str {
3379 match self {
3380 ImageFormat::Png => "png",
3381 ImageFormat::Jpeg => "jpg",
3382 ImageFormat::Webp => "webp",
3383 ImageFormat::Gif => "gif",
3384 ImageFormat::Svg => "svg",
3385 ImageFormat::Bmp => "bmp",
3386 ImageFormat::Tiff => "tiff",
3387 ImageFormat::Ico => "ico",
3388 ImageFormat::Pnm => "pnm",
3389 }
3390 }
3391
3392 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3394 use strum::IntoEnumIterator;
3395 Self::iter()
3396 .find(|format| format.mime_type() == mime_type)
3397 .or_else(|| Self::from_mime_type_alias(mime_type))
3398 }
3399
3400 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3404 match mime_type {
3405 "image/jpg" => Some(Self::Jpeg),
3406 "image/tif" => Some(Self::Tiff),
3407 _ => None,
3408 }
3409 }
3410}
3411
3412#[derive(Clone, Debug, PartialEq, Eq)]
3414pub struct Image {
3415 pub format: ImageFormat,
3417 pub bytes: Vec<u8>,
3419 pub id: u64,
3421}
3422
3423pub(crate) fn decode_static_image(
3424 bytes: &[u8],
3425 format: image::ImageFormat,
3426) -> Result<SmallVec<[Frame; 1]>> {
3427 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3428 .into_decoder()
3429 .context("creating image decoder")?;
3430 decode_static_image_from_decoder(decoder)
3431}
3432
3433pub(crate) fn decode_static_image_from_decoder(
3434 mut decoder: impl image::ImageDecoder,
3435) -> Result<SmallVec<[Frame; 1]>> {
3436 let orientation = decoder
3437 .orientation()
3438 .context("reading decoder's orientation")?;
3439 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3440 image.apply_orientation(orientation);
3441
3442 let mut data = image.into_rgba8();
3443 for pixel in data.chunks_exact_mut(4) {
3444 pixel.swap(0, 2);
3445 }
3446
3447 Ok(SmallVec::from_elem(Frame::new(data), 1))
3448}
3449
3450fn decode_animated_frames<'a>(
3451 decoder: impl image::AnimationDecoder<'a>,
3452 format_name: &str,
3453) -> Result<SmallVec<[Frame; 1]>> {
3454 let mut frames = SmallVec::new();
3455
3456 for frame in decoder.into_frames() {
3457 match frame {
3458 Ok(mut frame) => {
3459 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3461 pixel.swap(0, 2);
3462 }
3463 frames.push(frame);
3464 }
3465 Err(err) => {
3466 log::debug!("Skipping {format_name} frame due to decode error: {err}");
3467 }
3468 }
3469 }
3470
3471 if frames.is_empty() {
3472 anyhow::bail!("{format_name} could not be decoded: all frames failed");
3473 }
3474
3475 Ok(frames)
3476}
3477
3478pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3479 let decoder = GifDecoder::new(Cursor::new(bytes))?;
3480 decode_animated_frames(decoder, "GIF")
3481}
3482
3483pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3484 let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
3485
3486 if decoder.has_animation() {
3487 let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
3488 decode_animated_frames(decoder, "WebP")
3489 } else {
3490 decode_static_image_from_decoder(decoder)
3491 }
3492}
3493
3494impl Hash for Image {
3495 fn hash<H: Hasher>(&self, state: &mut H) {
3496 state.write_u64(self.id);
3497 }
3498}
3499
3500impl Image {
3501 pub fn empty() -> Self {
3503 Self::from_bytes(ImageFormat::Png, Vec::new())
3504 }
3505
3506 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3508 Self {
3509 id: hash(&bytes),
3510 format,
3511 bytes,
3512 }
3513 }
3514
3515 pub fn id(&self) -> u64 {
3517 self.id
3518 }
3519
3520 pub fn use_render_image(
3522 self: Arc<Self>,
3523 window: &mut Window,
3524 cx: &mut App,
3525 ) -> Option<Arc<RenderImage>> {
3526 ImageSource::Image(self)
3527 .use_data(None, window, cx)
3528 .and_then(|result| result.ok())
3529 }
3530
3531 pub fn get_render_image(
3533 self: Arc<Self>,
3534 window: &mut Window,
3535 cx: &mut App,
3536 ) -> Option<Arc<RenderImage>> {
3537 ImageSource::Image(self)
3538 .get_data(None, window, cx)
3539 .and_then(|result| result.ok())
3540 }
3541
3542 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3544 ImageSource::Image(self).remove_asset(cx);
3545 }
3546
3547 #[cfg(any(test, feature = "test-support"))]
3550 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3551 ImageSource::Image(self.clone()).is_asset_cached(cx)
3552 }
3553
3554 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3556 let frames = match self.format {
3557 ImageFormat::Gif => decode_gif_image(&self.bytes)?,
3558 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3559 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3560 ImageFormat::Webp => decode_webp_image(&self.bytes)?,
3561 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3562 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3563 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3564 ImageFormat::Svg => {
3565 return svg_renderer
3566 .render_single_frame(&self.bytes, 1.0)
3567 .map_err(Into::into);
3568 }
3569 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3570 };
3571
3572 Ok(Arc::new(RenderImage::new(frames)))
3573 }
3574
3575 pub fn format(&self) -> ImageFormat {
3577 self.format
3578 }
3579
3580 pub fn bytes(&self) -> &[u8] {
3582 self.bytes.as_slice()
3583 }
3584}
3585
3586#[derive(Clone, Debug, Eq, PartialEq)]
3588pub struct ClipboardString {
3589 pub text: String,
3591 pub metadata: Option<String>,
3593}
3594
3595impl ClipboardString {
3596 pub fn new(text: String) -> Self {
3598 Self {
3599 text,
3600 metadata: None,
3601 }
3602 }
3603
3604 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3607 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3608 self
3609 }
3610
3611 pub fn text(&self) -> &String {
3613 &self.text
3614 }
3615
3616 pub fn into_text(self) -> String {
3618 self.text
3619 }
3620
3621 pub fn metadata_json<T>(&self) -> Option<T>
3623 where
3624 T: for<'a> Deserialize<'a>,
3625 {
3626 self.metadata
3627 .as_ref()
3628 .and_then(|m| serde_json::from_str(m).ok())
3629 }
3630
3631 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3632 pub fn text_hash(text: &str) -> u64 {
3634 let mut hasher = SeaHasher::new();
3635 text.hash(&mut hasher);
3636 hasher.finish()
3637 }
3638}
3639
3640impl From<String> for ClipboardString {
3641 fn from(value: String) -> Self {
3642 Self {
3643 text: value,
3644 metadata: None,
3645 }
3646 }
3647}
3648
3649#[cfg(test)]
3650mod image_tests {
3651 use super::*;
3652 use std::sync::Arc;
3653
3654 #[test]
3655 fn test_image_to_image_data_applies_exif_orientation() {
3656 let image = Image::from_bytes(
3657 ImageFormat::Jpeg,
3658 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3659 );
3660
3661 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3662
3663 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3664
3665 let bytes = render_image.as_bytes(0).unwrap();
3666 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3667 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3668 }
3669
3670 #[test]
3671 fn test_svg_image_to_image_data_converts_to_bgra() {
3672 let image = Image::from_bytes(
3673 ImageFormat::Svg,
3674 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3675<rect width="1" height="1" fill="#38BDF8"/>
3676</svg>"##
3677 .to_vec(),
3678 );
3679
3680 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3681 let bytes = render_image.as_bytes(0).unwrap();
3682
3683 for pixel in bytes.chunks_exact(4) {
3684 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3685 }
3686 }
3687
3688 #[test]
3689 fn test_animated_webp_image_to_image_data_decodes_frames() {
3690 const ANIMATED_WEBP: &[u8] = &[
3692 82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
3693 0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
3694 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,
3695 0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
3696 176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
3697 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,
3698 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,
3699 0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
3700 31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
3701 ];
3702
3703 let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
3704 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3705
3706 assert_eq!(render_image.frame_count(), 2);
3707 assert_eq!(render_image.size(0), size(1.into(), 1.into()));
3708 assert_eq!(
3709 Duration::from(render_image.delay(0)),
3710 Duration::from_millis(100)
3711 );
3712 assert_eq!(
3713 Duration::from(render_image.delay(1)),
3714 Duration::from_millis(100)
3715 );
3716 }
3717}
3718
3719#[cfg(test)]
3720mod atlas_tests {
3721 use super::*;
3722
3723 const TILE_SIZE: Size<DevicePixels> = Size {
3724 width: DevicePixels(1),
3725 height: DevicePixels(1),
3726 };
3727
3728 #[derive(Default)]
3729 struct RecordingAtlasBackend {
3730 insert_calls: u32,
3731 fail_next_insert: bool,
3732 removed_tiles: Vec<AtlasTile>,
3733 }
3734
3735 impl AtlasBackend for RecordingAtlasBackend {
3736 fn insert(
3737 &mut self,
3738 kind: AtlasTextureKind,
3739 size: Size<DevicePixels>,
3740 _bytes: &[u8],
3741 ) -> Result<AtlasTile> {
3742 self.insert_calls += 1;
3743 if std::mem::take(&mut self.fail_next_insert) {
3744 anyhow::bail!("backend failed");
3745 }
3746 Ok(AtlasTile {
3747 texture_id: AtlasTextureId { index: 0, kind },
3748 tile_id: TileId(self.insert_calls),
3749 padding: 0,
3750 bounds: Bounds {
3751 origin: Point::default(),
3752 size,
3753 },
3754 })
3755 }
3756
3757 fn remove(&mut self, tile: AtlasTile) {
3758 self.removed_tiles.push(tile);
3759 }
3760 }
3761
3762 fn image_key(image_id: usize) -> AtlasKey {
3763 AtlasKey::Image(RenderImageParams {
3764 image_id: crate::ImageId(image_id),
3765 frame_index: 0,
3766 })
3767 }
3768
3769 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3770 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3771 }
3772
3773 #[test]
3774 fn only_successful_inserts_are_cached() -> Result<()> {
3775 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3776 let key = image_key(1);
3777
3778 assert_eq!(
3779 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3780 None
3781 );
3782 state
3783 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3784 .expect_err("builder error should propagate");
3785 assert!(!state.contains(&key));
3786 assert_eq!(state.backend.insert_calls, 0);
3787
3788 state.backend.fail_next_insert = true;
3789 state
3790 .get_or_insert_with(key.clone(), &mut build_tile)
3791 .expect_err("backend error should propagate");
3792 assert!(!state.contains(&key));
3793 assert_eq!(state.backend.insert_calls, 1);
3794
3795 let tile = state
3796 .get_or_insert_with(key.clone(), &mut build_tile)?
3797 .context("builder should produce a tile")?;
3798 assert_eq!(tile.texture_id.kind, key.texture_kind());
3799 assert_eq!(
3800 state.get_or_insert_with(key.clone(), &mut || {
3801 anyhow::bail!("cache hit must not call the builder")
3802 })?,
3803 Some(tile)
3804 );
3805 assert!(state.contains(&key));
3806 assert_eq!(state.backend.insert_calls, 2);
3807 Ok(())
3808 }
3809
3810 #[test]
3811 fn remove_and_clear_invalidate_keys() -> Result<()> {
3812 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3813 let key = image_key(1);
3814 let other_key = image_key(2);
3815 let tile = state
3816 .get_or_insert_with(key.clone(), &mut build_tile)?
3817 .context("builder should produce a tile")?;
3818 state
3819 .get_or_insert_with(other_key.clone(), &mut build_tile)?
3820 .context("builder should produce another tile")?;
3821
3822 state.remove(&key);
3823 state.remove(&key);
3824 assert!(!state.contains(&key));
3825 assert!(state.contains(&other_key));
3826 assert_eq!(state.backend.removed_tiles, vec![tile]);
3827
3828 let mut reset_calls = 0;
3829 state.clear(|_| reset_calls += 1);
3830 assert_eq!(reset_calls, 1);
3831 assert!(!state.contains(&other_key));
3832 assert_eq!(state.backend.removed_tiles, vec![tile]);
3833 Ok(())
3834 }
3835}
3836
3837#[cfg(test)]
3838mod frame_signal_tests {
3839 use super::*;
3840
3841 #[cfg(feature = "profiler")]
3842 #[test]
3843 fn coalesced_signals_retain_the_earliest_until_drained() {
3844 for (first_source, later_source) in [
3845 (
3846 FrameRequestSource::NativeCallback,
3847 FrameRequestSource::LocalSchedule,
3848 ),
3849 (
3850 FrameRequestSource::LocalSchedule,
3851 FrameRequestSource::NativeCallback,
3852 ),
3853 ] {
3854 let signal = PlatformFrameSignal::new();
3855 let first =
3856 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3857 assert_eq!(signal.take(), None);
3858 signal.record(first + Duration::from_millis(16), later_source);
3859 signal.record(first, first_source);
3860 signal.record(first + Duration::from_millis(32), later_source);
3861 assert_eq!(signal.take(), Some((first, first_source)));
3862 assert_eq!(signal.take(), None);
3863 let next = first + Duration::from_millis(48);
3864 signal.record(next, later_source);
3865 assert_eq!(signal.take(), Some((next, later_source)));
3866 }
3867 }
3868
3869 #[cfg(not(feature = "profiler"))]
3870 #[test]
3871 fn disabled_profiling_does_not_capture_or_store_timestamps() {
3872 let captured = PlatformFrameSignal::capture(|| {
3873 panic!("profiler-disabled builds must not evaluate the capture closure");
3874 });
3875 assert_eq!(captured, None);
3876 let signal = PlatformFrameSignal::new();
3877 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3878 assert_eq!(signal.take(), None);
3879 }
3880}
3881
3882#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3883mod tests {
3884 use super::*;
3885 use std::collections::HashSet;
3886
3887 #[test]
3888 fn test_refresh_interval_from_hz() {
3889 assert_eq!(
3890 refresh_interval_from_hz(50.0),
3891 Some(Duration::from_millis(20))
3892 );
3893 assert_eq!(
3894 refresh_interval_from_hz(120.0),
3895 Some(Duration::from_secs(1) / 120)
3896 );
3897 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
3898 assert_eq!(refresh_interval_from_hz(unknown), None);
3899 }
3900 }
3901
3902 #[test]
3903 fn test_window_button_layout_parse_standard() {
3904 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3905 assert_eq!(
3906 layout.left,
3907 [
3908 Some(WindowButton::Close),
3909 Some(WindowButton::Minimize),
3910 None
3911 ]
3912 );
3913 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3914 }
3915
3916 #[test]
3917 fn test_window_button_layout_parse_right_only() {
3918 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3919 assert_eq!(layout.left, [None, None, None]);
3920 assert_eq!(
3921 layout.right,
3922 [
3923 Some(WindowButton::Minimize),
3924 Some(WindowButton::Maximize),
3925 Some(WindowButton::Close)
3926 ]
3927 );
3928 }
3929
3930 #[test]
3931 fn test_window_button_layout_parse_left_only() {
3932 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3933 assert_eq!(
3934 layout.left,
3935 [
3936 Some(WindowButton::Close),
3937 Some(WindowButton::Minimize),
3938 Some(WindowButton::Maximize)
3939 ]
3940 );
3941 assert_eq!(layout.right, [None, None, None]);
3942 }
3943
3944 #[test]
3945 fn test_window_button_layout_parse_with_whitespace() {
3946 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3947 assert_eq!(
3948 layout.left,
3949 [
3950 Some(WindowButton::Close),
3951 Some(WindowButton::Minimize),
3952 None
3953 ]
3954 );
3955 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3956 }
3957
3958 #[test]
3959 fn test_window_button_layout_parse_empty() {
3960 let layout = WindowButtonLayout::parse("").unwrap();
3961 assert_eq!(layout.left, [None, None, None]);
3962 assert_eq!(layout.right, [None, None, None]);
3963 }
3964
3965 #[test]
3966 fn test_window_button_layout_parse_intentionally_empty() {
3967 let layout = WindowButtonLayout::parse(":").unwrap();
3968 assert_eq!(layout.left, [None, None, None]);
3969 assert_eq!(layout.right, [None, None, None]);
3970 }
3971
3972 #[test]
3973 fn test_window_button_layout_parse_invalid_buttons() {
3974 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
3975 assert_eq!(
3976 layout.left,
3977 [
3978 Some(WindowButton::Close),
3979 Some(WindowButton::Minimize),
3980 None
3981 ]
3982 );
3983 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3984 }
3985
3986 #[test]
3987 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
3988 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
3989 assert_eq!(
3990 layout.right,
3991 [
3992 Some(WindowButton::Close),
3993 Some(WindowButton::Minimize),
3994 None
3995 ]
3996 );
3997 assert_eq!(layout.format(), ":close,minimize");
3998 }
3999
4000 #[test]
4001 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
4002 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
4003 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4004 assert_eq!(
4005 layout.right,
4006 [
4007 Some(WindowButton::Maximize),
4008 Some(WindowButton::Minimize),
4009 None
4010 ]
4011 );
4012
4013 let button_ids: Vec<_> = layout
4014 .left
4015 .iter()
4016 .chain(layout.right.iter())
4017 .flatten()
4018 .map(WindowButton::id)
4019 .collect();
4020 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4021 assert_eq!(unique_button_ids.len(), button_ids.len());
4022 assert_eq!(layout.format(), "close:maximize,minimize");
4023 }
4024
4025 #[test]
4026 fn test_window_button_layout_parse_gnome_style() {
4027 let layout = WindowButtonLayout::parse("close").unwrap();
4028 assert_eq!(layout.left, [None, None, None]);
4029 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4030 }
4031
4032 #[test]
4033 fn test_window_button_layout_parse_elementary_style() {
4034 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4035 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4036 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4037 }
4038
4039 #[test]
4040 fn test_window_button_layout_round_trip() {
4041 let cases = [
4042 "close:minimize,maximize",
4043 "minimize,maximize,close:",
4044 ":close",
4045 "close:",
4046 "close:maximize",
4047 ":",
4048 ];
4049
4050 for case in cases {
4051 let layout = WindowButtonLayout::parse(case).unwrap();
4052 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4053 }
4054 }
4055
4056 #[test]
4057 fn test_window_button_layout_linux_default() {
4058 let layout = WindowButtonLayout::linux_default();
4059 assert_eq!(layout.left, [None, None, None]);
4060 assert_eq!(
4061 layout.right,
4062 [
4063 Some(WindowButton::Minimize),
4064 Some(WindowButton::Maximize),
4065 Some(WindowButton::Close)
4066 ]
4067 );
4068
4069 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4070 assert_eq!(round_tripped, layout);
4071 }
4072
4073 #[test]
4074 fn test_window_button_layout_parse_all_invalid() {
4075 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4076 }
4077}