1mod app_menu;
2mod keyboard;
3mod keystroke;
4mod platform_info;
5
6#[cfg(all(target_os = "linux", feature = "wayland"))]
7#[expect(missing_docs)]
8pub mod layer_shell;
9
10pub mod popup;
12
13#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
14mod threaded_dispatcher;
15
16#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
17mod test;
18
19#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
20mod visual_test;
21
22#[cfg(all(
23 feature = "screen-capture",
24 any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
25))]
26pub mod scap_screen_capture;
27
28#[cfg(all(
29 any(target_os = "windows", target_os = "linux"),
30 feature = "screen-capture"
31))]
32pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
33#[cfg(not(feature = "screen-capture"))]
34pub(crate) type PlatformScreenCaptureFrame = ();
35#[cfg(all(target_os = "macos", feature = "screen-capture"))]
36pub(crate) type PlatformScreenCaptureFrame =
37 objc2_core_foundation::CFRetained<objc2_core_video::CVImageBuffer>;
38
39use crate::{
40 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds, Corners,
41 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
42 FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap,
43 LineLayout, MissingGlyphSink, Pixels, PlatformGestures, PlatformInput, Point, Priority,
44 RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph,
45 ShapedRun, SharedString, Size, SvgRenderer, SystemWindowTab, Task, Window, WindowControlArea,
46 hash, point, px, size,
47};
48#[cfg(any(target_os = "linux", target_os = "freebsd"))]
49use anyhow::bail;
50use anyhow::{Context as _, Result};
51use async_task::Runnable;
52use collections::FxHashMap;
53use futures::channel::oneshot;
54#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
55use image::RgbaImage;
56use image::codecs::{gif::GifDecoder, webp::WebPDecoder};
57use image::{DynamicImage, Frame, Rgba};
58use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
59use scheduler::Instant;
60pub use scheduler::RunnableMeta;
61use schemars::JsonSchema;
62use seahash::SeaHasher;
63use serde::{Deserialize, Serialize};
64use smallvec::SmallVec;
65use std::borrow::Cow;
66use std::collections::hash_map::Entry;
67use std::hash::{Hash, Hasher};
68use std::io::Cursor;
69use std::ops;
70use std::time::Duration;
71use std::{
72 ffi::OsString,
73 fmt::{self, Debug},
74 ops::Range,
75 path::{Path, PathBuf},
76 rc::Rc,
77 sync::Arc,
78};
79use strum::EnumIter;
80use uuid::Uuid;
81
82pub use app_menu::*;
83pub use keyboard::*;
84pub use keystroke::*;
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum WindowVisibility {
108 Visible,
111 Hidden,
114}
115
116impl WindowVisibility {
117 pub fn is_visible(self) -> bool {
119 self == Self::Visible
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126#[non_exhaustive]
127pub enum DisplayEvent {
128 Added(DisplayId),
130 Removed(DisplayId),
133 Changed {
135 id: DisplayId,
137 changes: DisplayChanges,
139 },
140}
141
142bitflags::bitflags! {
143 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
145 pub struct DisplayChanges: u8 {
146 const BOUNDS = 1 << 0;
148 const REFRESH_INTERVAL = 1 << 1;
150 }
151}
152
153pub fn refresh_interval_from_hz(hertz: f64) -> Option<Duration> {
156 (hertz.is_finite() && hertz > 0.0).then(|| Duration::from_secs_f64(1.0 / hertz))
157}
158
159#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
166pub enum ActivationPolicy {
167 #[default]
169 Regular,
170 Accessory,
172}
173
174#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
175pub(crate) use test::*;
176
177#[cfg(any(test, feature = "test-support"))]
178pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
179
180#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
181pub use threaded_dispatcher::ThreadedDispatcher;
182
183#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
184pub use visual_test::VisualTestPlatform;
185
186pub struct ActivityGuard {
188 _release: gpui_util::Deferred<Box<dyn FnOnce() + Send>>,
189}
190
191impl ActivityGuard {
192 pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
194 Self {
195 _release: gpui_util::defer(Box::new(release)),
196 }
197 }
198
199 pub fn noop() -> Self {
201 Self::new(|| {})
202 }
203}
204
205#[cfg(any(target_os = "linux", target_os = "freebsd"))]
209#[inline]
210pub fn guess_compositor() -> &'static str {
211 if std::env::var_os("ZED_HEADLESS").is_some() {
212 return "headless";
213 }
214 GraphicalEnvironment::detect().guess_compositor()
215}
216
217#[cfg(any(target_os = "linux", target_os = "freebsd"))]
226#[derive(Clone, Debug, Default)]
227pub struct GraphicalEnvironment {
228 pub wayland_display: Option<OsString>,
230 pub x11_display: Option<OsString>,
232 pub xdg_runtime_dir: Option<OsString>,
234 pub current_desktop: Option<OsString>,
239 pub activation_token: Option<String>,
245}
246
247#[cfg(target_os = "windows")]
253#[derive(Clone, Debug, Default)]
254pub struct GraphicalEnvironment {
255 pub session_id: Option<u32>,
258}
259
260#[cfg(target_os = "windows")]
261impl GraphicalEnvironment {
262 pub fn detect() -> Self {
264 let mut session_id = 0;
265 let result = unsafe {
267 windows::Win32::System::RemoteDesktop::ProcessIdToSessionId(
268 windows::Win32::System::Threading::GetCurrentProcessId(),
269 &mut session_id,
270 )
271 };
272 Self {
273 session_id: result.is_ok().then_some(session_id),
274 }
275 }
276
277 pub fn apply_to(&self, _command: &mut std::process::Command) {}
280
281 pub fn desktop_environment(&self) -> Option<String> {
283 None
284 }
285}
286
287#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
289#[derive(Clone, Debug, Default)]
290pub struct GraphicalEnvironment;
291
292#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
293impl GraphicalEnvironment {
294 pub fn detect() -> Self {
296 Self
297 }
298
299 pub fn apply_to(&self, _command: &mut std::process::Command) {}
301
302 pub fn desktop_environment(&self) -> Option<String> {
304 None
305 }
306}
307
308#[derive(Clone, Debug)]
310pub enum WindowingRequest {
311 Headless,
313 Windowed(GraphicalEnvironment),
315}
316
317#[cfg(any(target_os = "linux", target_os = "freebsd"))]
318impl GraphicalEnvironment {
319 pub fn detect() -> Self {
324 Self {
325 wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
326 x11_display: std::env::var_os("DISPLAY"),
327 xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
328 current_desktop: std::env::var_os("XDG_CURRENT_DESKTOP"),
329 activation_token: None,
330 }
331 }
332
333 pub fn apply_to(&self, command: &mut std::process::Command) {
337 for (name, value) in [
338 ("WAYLAND_DISPLAY", &self.wayland_display),
339 ("DISPLAY", &self.x11_display),
340 ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
341 ] {
342 match value {
343 Some(value) => command.env(name, value),
344 None => command.env_remove(name),
345 };
346 }
347 }
348
349 pub fn desktop_environment(&self) -> Option<String> {
354 self.current_desktop
355 .as_ref()
356 .and_then(|desktop| desktop.to_str())
357 .filter(|desktop| !desktop.is_empty())
358 .map(str::to_owned)
359 }
360
361 pub fn guess_compositor(&self) -> &'static str {
365 let is_set =
366 |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
367 if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
368 "Wayland"
369 } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
370 "X11"
371 } else {
372 "headless"
373 }
374 }
375}
376
377#[cfg(any(target_os = "linux", target_os = "freebsd"))]
378bitflags::bitflags! {
379 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
381 pub struct WindowingModes: u8 {
382 const WAYLAND = 1 << 0;
384 const X11 = 1 << 1;
386 const HEADLESS = 1 << 2;
388 }
389}
390
391pub use platform_info::{OperatingSystem, PlatformInfo, PlatformTarget};
392
393#[expect(missing_docs)]
394pub trait Platform: 'static {
395 fn platform_info(&self) -> PlatformInfo;
397
398 fn background_executor(&self) -> BackgroundExecutor;
399 fn foreground_executor(&self) -> ForegroundExecutor;
400 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
401
402 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
403 fn quit(&self);
404 fn set_initial_windowing(&self, _request: WindowingRequest) {}
409 fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
410 Task::ready(Err(anyhow::anyhow!(
411 "this platform cannot switch between headless and windowed modes"
412 )))
413 }
414 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
415 fn activate(&self, ignoring_other_apps: bool);
416 fn set_activation_policy(&self, _policy: ActivationPolicy) {}
418 fn hide(&self);
419 fn hide_other_apps(&self);
420 fn unhide_other_apps(&self);
421
422 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
423 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
424 fn on_displays_changed(&self, callback: Box<dyn FnMut()>);
429 fn active_window(&self) -> Option<AnyWindowHandle>;
430 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
431 None
432 }
433
434 fn is_screen_capture_supported(&self) -> bool {
435 false
436 }
437
438 fn screen_capture_sources(
439 &self,
440 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
441 let (sources_tx, sources_rx) = oneshot::channel();
442 sources_tx
443 .send(Err(anyhow::anyhow!(
444 "gpui was compiled without the screen-capture feature"
445 )))
446 .ok();
447 sources_rx
448 }
449
450 fn open_window(
451 &self,
452 handle: AnyWindowHandle,
453 options: WindowParams,
454 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
455
456 fn window_appearance(&self) -> WindowAppearance;
458
459 fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
468
469 fn button_layout(&self) -> Option<WindowButtonLayout> {
471 None
472 }
473
474 fn open_url(&self, url: &str);
475 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
476 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
477
478 fn prompt_for_paths(
479 &self,
480 options: PathPromptOptions,
481 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
482 fn prompt_for_new_path(
483 &self,
484 directory: &Path,
485 suggested_name: Option<&str>,
486 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
487 fn can_select_mixed_files_and_dirs(&self) -> bool;
488 fn reveal_path(&self, path: &Path);
489 fn open_with_system(&self, path: &Path);
490
491 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
492 fn on_reopen(&self, callback: Box<dyn FnMut()>);
493 fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
495 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
497
498 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
508
509 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
514
515 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
519 None
520 }
521
522 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
523 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
524 None
525 }
526
527 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
528 fn perform_dock_menu_action(&self, _action: usize) {}
529 fn add_recent_document(&self, _path: &Path) {}
530 fn update_jump_list(
531 &self,
532 _menus: Vec<MenuItem>,
533 _entries: Vec<SmallVec<[PathBuf; 2]>>,
534 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
535 Task::ready(Vec::new())
536 }
537 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
538 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
539 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
540
541 fn debug_state(&self) -> serde_json::Value {
543 serde_json::Value::Null
544 }
545
546 fn thermal_state(&self) -> ThermalState;
547 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
548 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
549
550 fn power_mode(&self) -> PowerMode {
553 PowerMode::Unknown
554 }
555 fn on_power_mode_change(&self, _callback: Box<dyn FnMut()>) {}
557
558 fn set_app_identity(&self, identifier: &str, name: &str) {
565 _ = (identifier, name);
566 }
567
568 fn show_system_notification(&self, notification: SystemNotification) {
575 _ = notification;
576 }
577
578 fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
586 _ = tag;
587 Task::ready(())
588 }
589
590 fn on_system_notification_response(
596 &self,
597 callback: Box<dyn FnMut(SystemNotificationResponse)>,
598 ) {
599 _ = callback;
600 }
601
602 fn compositor_name(&self) -> &'static str {
603 ""
604 }
605 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
608 None
609 }
610 fn app_path(&self) -> Result<PathBuf>;
611 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
612
613 fn set_cursor_style(&self, style: CursorStyle);
614
615 fn hide_cursor_until_mouse_moves(&self);
618
619 fn is_cursor_visible(&self) -> bool;
621
622 fn should_auto_hide_scrollbars(&self) -> bool;
623
624 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
625 fn write_to_clipboard(&self, item: ClipboardItem);
626
627 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
635 Task::ready(Ok(self.read_from_clipboard()))
636 }
637
638 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
639 fn read_from_primary(&self) -> Option<ClipboardItem>;
640 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
641 fn write_to_primary(&self, item: ClipboardItem);
642
643 #[cfg(target_os = "macos")]
644 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
645 #[cfg(target_os = "macos")]
646 fn write_to_find_pasteboard(&self, item: ClipboardItem);
647
648 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
649
650 #[cfg(target_os = "macos")]
654 fn write_credentials_if_not_exists(
655 &self,
656 _url: &str,
657 _username: &str,
658 _password: &[u8],
659 ) -> Task<Result<bool>> {
660 Task::ready(Err(anyhow::anyhow!(
661 "this platform does not support atomic credential writes"
662 )))
663 }
664
665 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
666 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
667
668 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
669 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
670 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
671}
672
673pub trait PlatformDisplay: Debug {
675 fn id(&self) -> DisplayId;
677
678 fn uuid(&self) -> Result<Uuid>;
681
682 fn bounds(&self) -> Bounds<Pixels>;
684
685 fn refresh_interval(&self) -> Option<Duration>;
692
693 fn visible_bounds(&self) -> Bounds<Pixels> {
697 self.bounds()
698 }
699
700 fn default_bounds(&self) -> Bounds<Pixels> {
702 let bounds = self.bounds();
703 let center = bounds.center();
704 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
705
706 let offset = clipped_window_size / 2.0;
707 let origin = point(center.x - offset.width, center.y - offset.height);
708 Bounds::new(origin, clipped_window_size)
709 }
710}
711
712#[derive(Clone, Debug, PartialEq, Eq)]
715pub struct SystemNotification {
716 pub tag: SharedString,
720 pub title: SharedString,
722 pub body: SharedString,
724 pub actions: Vec<SystemNotificationAction>,
727}
728
729#[derive(Clone, Debug, PartialEq, Eq, Hash)]
731pub struct SystemNotificationAction {
732 pub id: SharedString,
735 pub label: SharedString,
737}
738
739#[derive(Clone, Debug, PartialEq, Eq)]
741pub struct SystemNotificationResponse {
742 pub tag: SharedString,
744 pub action_id: Option<SharedString>,
747}
748
749#[derive(Debug, Clone, Copy, PartialEq, Eq)]
751pub enum PowerMode {
752 Unknown,
755 LowPower,
757 Balanced,
759 HighPower,
761}
762
763#[derive(Debug, Clone, Copy, PartialEq, Eq)]
765pub enum ThermalState {
766 Nominal,
768 Fair,
770 Serious,
772 Critical,
774}
775
776#[derive(Clone)]
778pub struct SourceMetadata {
779 pub id: u64,
781 pub label: Option<SharedString>,
783 pub is_main: Option<bool>,
785 pub resolution: Size<DevicePixels>,
787}
788
789pub trait ScreenCaptureSource {
791 fn metadata(&self) -> Result<SourceMetadata>;
793
794 fn stream(
797 &self,
798 foreground_executor: &ForegroundExecutor,
799 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
800 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
801}
802
803pub trait ScreenCaptureStream {
805 fn metadata(&self) -> Result<SourceMetadata>;
807}
808
809pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
811
812#[derive(PartialEq, Eq, Hash, Copy, Clone)]
814pub struct DisplayId(pub(crate) u64);
815
816impl DisplayId {
817 pub fn new(id: u64) -> Self {
819 Self(id)
820 }
821}
822
823impl From<u64> for DisplayId {
824 fn from(id: u64) -> Self {
825 Self(id)
826 }
827}
828
829impl From<DisplayId> for u64 {
830 fn from(id: DisplayId) -> Self {
831 id.0
832 }
833}
834
835impl Debug for DisplayId {
836 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837 write!(f, "DisplayId({})", self.0)
838 }
839}
840
841#[derive(Debug, Clone, Copy, PartialEq, Eq)]
843pub enum ResizeEdge {
844 Top,
846 TopRight,
848 Right,
850 BottomRight,
852 Bottom,
854 BottomLeft,
856 Left,
858 TopLeft,
860}
861
862#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
864pub enum WindowDecorations {
865 #[default]
866 Server,
868 Client,
870}
871
872#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
874pub enum Decorations {
875 #[default]
877 Server,
878 Client {
880 tiling: Tiling,
882 },
883}
884
885#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
887pub struct WindowControls {
888 pub fullscreen: bool,
890 pub maximize: bool,
892 pub minimize: bool,
894 pub window_menu: bool,
896}
897
898impl Default for WindowControls {
899 fn default() -> Self {
900 Self {
902 fullscreen: true,
903 maximize: true,
904 minimize: true,
905 window_menu: true,
906 }
907 }
908}
909
910#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
912pub enum WindowButton {
913 Minimize,
915 Maximize,
917 Close,
919}
920
921impl WindowButton {
922 pub fn id(&self) -> &'static str {
924 match self {
925 WindowButton::Minimize => "minimize",
926 WindowButton::Maximize => "maximize",
927 WindowButton::Close => "close",
928 }
929 }
930
931 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
932 fn index(&self) -> usize {
933 match self {
934 WindowButton::Minimize => 0,
935 WindowButton::Maximize => 1,
936 WindowButton::Close => 2,
937 }
938 }
939}
940
941pub const MAX_BUTTONS_PER_SIDE: usize = 3;
943
944#[derive(Debug, Clone, Copy, PartialEq, Eq)]
949pub struct WindowButtonLayout {
950 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
952 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
954}
955
956#[cfg(any(target_os = "linux", target_os = "freebsd"))]
957impl WindowButtonLayout {
958 pub fn linux_default() -> Self {
960 Self {
961 left: [None; MAX_BUTTONS_PER_SIDE],
962 right: [
963 Some(WindowButton::Minimize),
964 Some(WindowButton::Maximize),
965 Some(WindowButton::Close),
966 ],
967 }
968 }
969
970 pub fn parse(layout_string: &str) -> Result<Self> {
972 fn parse_side(
973 s: &str,
974 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
975 unrecognized: &mut Vec<String>,
976 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
977 let mut result = [None; MAX_BUTTONS_PER_SIDE];
978 let mut i = 0;
979 for name in s.split(',') {
980 let trimmed = name.trim();
981 if trimmed.is_empty() {
982 continue;
983 }
984 let button = match trimmed {
985 "minimize" => Some(WindowButton::Minimize),
986 "maximize" => Some(WindowButton::Maximize),
987 "close" => Some(WindowButton::Close),
988 other => {
989 unrecognized.push(other.to_string());
990 None
991 }
992 };
993 if let Some(button) = button {
994 if seen_buttons[button.index()] {
995 continue;
996 }
997 if let Some(slot) = result.get_mut(i) {
998 *slot = Some(button);
999 seen_buttons[button.index()] = true;
1000 i += 1;
1001 }
1002 }
1003 }
1004 result
1005 }
1006
1007 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1008 let mut unrecognized = Vec::new();
1009 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1010 let layout = Self {
1011 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1012 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1013 };
1014
1015 if !unrecognized.is_empty()
1016 && layout.left.iter().all(Option::is_none)
1017 && layout.right.iter().all(Option::is_none)
1018 {
1019 bail!(
1020 "button layout string {:?} contains no valid buttons (unrecognized: {})",
1021 layout_string,
1022 unrecognized.join(", ")
1023 );
1024 }
1025
1026 Ok(layout)
1027 }
1028
1029 #[cfg(test)]
1031 pub fn format(&self) -> String {
1032 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1033 buttons
1034 .iter()
1035 .flatten()
1036 .map(|button| match button {
1037 WindowButton::Minimize => "minimize",
1038 WindowButton::Maximize => "maximize",
1039 WindowButton::Close => "close",
1040 })
1041 .collect::<Vec<_>>()
1042 .join(",")
1043 }
1044
1045 format!("{}:{}", format_side(&self.left), format_side(&self.right))
1046 }
1047}
1048
1049#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1051pub struct Tiling {
1052 pub top: bool,
1054 pub left: bool,
1056 pub right: bool,
1058 pub bottom: bool,
1060}
1061
1062impl Tiling {
1063 pub fn tiled() -> Self {
1065 Self {
1066 top: true,
1067 left: true,
1068 right: true,
1069 bottom: true,
1070 }
1071 }
1072
1073 pub fn is_tiled(&self) -> bool {
1075 self.top || self.left || self.right || self.bottom
1076 }
1077}
1078
1079pub struct A11yCallbacks {
1081 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1083 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1085 pub deactivation: Box<dyn Fn() + Send + 'static>,
1087}
1088
1089#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1091pub enum FrameRequestSource {
1092 #[default]
1094 NativeCallback,
1095 LocalSchedule,
1097}
1098
1099#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1100#[expect(missing_docs)]
1101pub struct RequestFrameOptions {
1102 pub require_presentation: bool,
1104 pub force_render: bool,
1106 pub signal_at: Option<Instant>,
1112 pub signal_source: FrameRequestSource,
1114}
1115
1116pub struct PlatformFrameSignal {
1125 #[cfg(feature = "profiler")]
1126 origin: Instant,
1127 #[cfg(feature = "profiler")]
1128 first_signal: std::sync::atomic::AtomicU64,
1129}
1130
1131impl Default for PlatformFrameSignal {
1132 fn default() -> Self {
1133 Self::new()
1134 }
1135}
1136
1137impl PlatformFrameSignal {
1138 pub fn new() -> Self {
1140 Self {
1141 #[cfg(feature = "profiler")]
1142 origin: Instant::now(),
1143 #[cfg(feature = "profiler")]
1144 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1145 }
1146 }
1147
1148 #[inline]
1152 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1153 if cfg!(feature = "profiler") {
1154 Some(capture())
1155 } else {
1156 None
1157 }
1158 }
1159
1160 #[inline]
1162 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1163 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1164 #[cfg(feature = "profiler")]
1165 {
1166 let nanoseconds = at
1167 .saturating_duration_since(self.origin)
1168 .as_nanos()
1169 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1170 let source_bit = match source {
1171 FrameRequestSource::NativeCallback => 0,
1172 FrameRequestSource::LocalSchedule => 1,
1173 };
1174 self.first_signal.fetch_min(
1175 (nanoseconds << 1) | source_bit,
1176 std::sync::atomic::Ordering::Relaxed,
1177 );
1178 }
1179 }
1180
1181 #[inline]
1183 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1184 #[cfg(feature = "profiler")]
1185 {
1186 let signal = self
1187 .first_signal
1188 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1189 (signal != u64::MAX).then(|| {
1190 let source = match signal & 1 {
1191 0 => FrameRequestSource::NativeCallback,
1192 _ => FrameRequestSource::LocalSchedule,
1193 };
1194 (self.origin + Duration::from_nanos(signal >> 1), source)
1195 })
1196 }
1197 #[cfg(not(feature = "profiler"))]
1198 {
1199 None
1200 }
1201 }
1202}
1203
1204#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1217pub enum AppLifecyclePhase {
1218 Active,
1220 Inactive,
1222 Background,
1225 Foreground,
1227 Disconnected,
1231}
1232
1233#[derive(Debug, Clone, Default, PartialEq)]
1240pub struct WindowInsets {
1241 pub safe_area: Edges<Pixels>,
1246 pub ime: Edges<Pixels>,
1250 pub corner_radii: Corners<Pixels>,
1255}
1256
1257impl WindowInsets {
1258 pub fn effective(&self) -> Edges<Pixels> {
1260 Edges {
1261 top: self.safe_area.top.max(self.ime.top),
1262 right: self.safe_area.right.max(self.ime.right),
1263 bottom: self.safe_area.bottom.max(self.ime.bottom),
1264 left: self.safe_area.left.max(self.ime.left),
1265 }
1266 }
1267}
1268
1269#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1271pub enum TextInputStateChange {
1272 FocusGained,
1274 FocusLost,
1276 SelectionChanged,
1278 ContentChanged,
1280}
1281
1282#[expect(missing_docs)]
1283pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1284 fn bounds(&self) -> Bounds<Pixels>;
1285 fn is_maximized(&self) -> bool;
1286 fn window_bounds(&self) -> WindowBounds;
1287 fn content_size(&self) -> Size<Pixels>;
1288 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1294 Bounds::new(Point::default(), self.content_size())
1295 }
1296 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1301 fn prepare_frame(&self) -> bool {
1306 false
1307 }
1308 fn resize(&mut self, size: Size<Pixels>);
1309 fn scale_factor(&self) -> f32;
1310 fn appearance(&self) -> WindowAppearance;
1311 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1312 fn mouse_position(&self) -> Point<Pixels>;
1313 fn modifiers(&self) -> Modifiers;
1314 fn capslock(&self) -> Capslock;
1315 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1316 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1317 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1322 fn prompt(
1323 &self,
1324 level: PromptLevel,
1325 msg: &str,
1326 detail: Option<&str>,
1327 answers: &[PromptButton],
1328 ) -> Option<oneshot::Receiver<usize>>;
1329 fn activate(&self);
1330 fn request_attention(&self) {}
1332 fn is_active(&self) -> bool;
1333 fn visibility(&self) -> WindowVisibility;
1336 fn is_hovered(&self) -> bool;
1337 fn background_appearance(&self) -> WindowBackgroundAppearance;
1338 fn set_title(&mut self, title: &str);
1339 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1340 fn minimize(&self);
1341 fn zoom(&self);
1342 fn toggle_fullscreen(&self);
1343 fn is_fullscreen(&self) -> bool;
1344 fn debug_state(&self) -> serde_json::Value {
1346 serde_json::Value::Null
1347 }
1348 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1349 None
1350 }
1351 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1352 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1353 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1354 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1358 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1359 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1360 fn on_moved(&self, callback: Box<dyn FnMut()>);
1361 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1365 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1366 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1367 fn on_close(&self, callback: Box<dyn FnOnce()>);
1368 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1369 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1370 fn draw(&self, scene: &Scene);
1371 fn schedule_frame(&self) {}
1372 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1373 fn is_subpixel_rendering_supported(&self) -> bool;
1374
1375 fn get_title(&self) -> String {
1377 String::new()
1378 }
1379 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1380 None
1381 }
1382 fn tab_bar_visible(&self) -> bool {
1383 false
1384 }
1385 fn set_edited(&mut self, _edited: bool) {}
1386 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1387 fn toggle_simple_fullscreen(&self) {}
1388 fn is_simple_fullscreen(&self) -> bool {
1389 false
1390 }
1391 #[cfg(target_os = "macos")]
1392 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1393 #[cfg(target_os = "macos")]
1394 fn set_native_titlebar_visibility(&self, _visible: bool) {}
1395 fn show_character_palette(&self) {}
1396 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1397 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1398 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1399 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1400 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1401 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1402 fn merge_all_windows(&self) {}
1403 fn move_tab_to_new_window(&self) {}
1404 fn toggle_window_tab_overview(&self) {}
1405 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1406
1407 fn native_window_state(&self) -> Option<Vec<u8>> {
1408 None
1409 }
1410 fn restore_native_window_state(&self, _state: &[u8]) {}
1411
1412 #[cfg(target_os = "windows")]
1413 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1414
1415 fn inner_window_bounds(&self) -> WindowBounds {
1417 self.window_bounds()
1418 }
1419 fn request_decorations(&self, _decorations: WindowDecorations) {}
1420 fn show_window_menu(&self, _position: Point<Pixels>) {}
1421 fn start_window_move(&self) {}
1422 fn can_start_external_drag(&self) -> bool {
1423 false
1424 }
1425 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1426 false
1427 }
1428 fn start_window_resize(&self, _edge: ResizeEdge) {}
1429 fn set_exclusive_zone(&self, _zone: Pixels) {}
1430 #[cfg(all(target_os = "linux", feature = "wayland"))]
1431 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1432 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1433 fn window_decorations(&self) -> Decorations {
1434 Decorations::Server
1435 }
1436 fn set_app_id(&mut self, _app_id: &str) {}
1437 fn map_window(&mut self) -> anyhow::Result<()> {
1438 Ok(())
1439 }
1440 fn window_controls(&self) -> WindowControls {
1441 WindowControls::default()
1442 }
1443 fn set_client_inset(&self, _inset: Pixels) {}
1444 fn set_client_corner_radii(&self, _radii: Corners<Pixels>) {}
1445 fn gpu_specs(&self) -> Option<GpuSpecs>;
1446
1447 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1448
1449 fn insets(&self) -> WindowInsets {
1454 WindowInsets::default()
1455 }
1456
1457 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1463
1464 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1467
1468 fn set_back_enabled(&self, _enabled: bool) {}
1471
1472 fn show_soft_keyboard(&self) {}
1474
1475 fn hide_soft_keyboard(&self) {}
1477
1478 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1480
1481 fn play_system_bell(&self) {}
1482
1483 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1485
1486 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1488
1489 fn a11y_update_window_bounds(&self) {}
1491
1492 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1493 fn as_test(&mut self) -> Option<&mut TestWindow> {
1494 None
1495 }
1496
1497 #[cfg(any(test, feature = "test-support"))]
1501 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1502 anyhow::bail!("render_to_image not implemented for this platform")
1503 }
1504}
1505
1506#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1508pub trait PlatformHeadlessRenderer {
1509 fn render_scene_to_image(
1511 &mut self,
1512 scene: &Scene,
1513 size: Size<DevicePixels>,
1514 ) -> Result<RgbaImage>;
1515
1516 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1522
1523 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1525}
1526
1527#[doc(hidden)]
1530pub type RunnableVariant = Runnable<RunnableMeta>;
1531
1532#[doc(hidden)]
1533pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1534
1535#[doc(hidden)]
1536pub enum TasksIncluded {
1537 OnlyCompleted,
1538 CompletedAndRunning,
1539}
1540
1541#[doc(hidden)]
1544pub trait PlatformDispatcher: Send + Sync {
1545 fn is_main_thread(&self) -> bool;
1546 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1547 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1548 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1549
1550 fn dispatch_on_main_thread_when_idle(
1551 &self,
1552 runnable: RunnableVariant,
1553 timeout: Option<Duration>,
1554 ) {
1555 let _ = timeout;
1556 self.dispatch_on_main_thread(runnable, Priority::Low);
1557 }
1558
1559 fn idle_time_remaining(&self) -> Option<Duration> {
1560 None
1561 }
1562
1563 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1564
1565 fn now(&self) -> Instant {
1566 Instant::now()
1567 }
1568
1569 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1570 gpui_util::defer(Box::new(|| {}))
1571 }
1572
1573 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1574 ActivityGuard::noop()
1575 }
1576
1577 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1578 fn as_test(&self) -> Option<&TestDispatcher> {
1579 None
1580 }
1581
1582 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1585 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1586 None
1587 }
1588}
1589
1590#[expect(missing_docs)]
1591pub trait PlatformTextSystem: Send + Sync {
1592 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1593 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1595 fn all_font_names(&self) -> Vec<String>;
1597 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1599 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1601 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1603 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1605 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1607 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1609 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1611 fn rasterize_glyph(
1613 &self,
1614 params: &RenderGlyphParams,
1615 raster_bounds: Bounds<DevicePixels>,
1616 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1617 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1619 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1621 -> TextRenderingMode;
1622 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1624 0
1625 }
1626}
1627
1628#[expect(missing_docs)]
1629pub struct NoopTextSystem;
1630
1631#[expect(missing_docs)]
1632impl NoopTextSystem {
1633 #[allow(dead_code)]
1634 pub fn new() -> Self {
1635 Self
1636 }
1637}
1638
1639impl PlatformTextSystem for NoopTextSystem {
1640 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1641 Ok(())
1642 }
1643
1644 fn all_font_names(&self) -> Vec<String> {
1645 Vec::new()
1646 }
1647
1648 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1649 Ok(FontId(1))
1650 }
1651
1652 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1653 FontMetrics {
1654 units_per_em: 1000,
1655 ascent: 1025.0,
1656 descent: -275.0,
1657 line_gap: 0.0,
1658 underline_position: -95.0,
1659 underline_thickness: 60.0,
1660 cap_height: 698.0,
1661 x_height: 516.0,
1662 bounding_box: Bounds {
1663 origin: Point {
1664 x: -260.0,
1665 y: -245.0,
1666 },
1667 size: Size {
1668 width: 1501.0,
1669 height: 1364.0,
1670 },
1671 },
1672 }
1673 }
1674
1675 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1676 Ok(Bounds {
1677 origin: Point { x: 54.0, y: 0.0 },
1678 size: size(392.0, 528.0),
1679 })
1680 }
1681
1682 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1683 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1684 }
1685
1686 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1687 Some(GlyphId(ch.len_utf16() as u32))
1688 }
1689
1690 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1691 Ok(Default::default())
1692 }
1693
1694 fn rasterize_glyph(
1695 &self,
1696 _params: &RenderGlyphParams,
1697 raster_bounds: Bounds<DevicePixels>,
1698 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1699 Ok((raster_bounds.size, Vec::new()))
1700 }
1701
1702 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1703 let mut position = px(0.);
1704 let metrics = self.font_metrics(FontId(0));
1705 let em_width = font_size
1706 * self
1707 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1708 .unwrap()
1709 .width
1710 / metrics.units_per_em as f32;
1711 let mut glyphs = Vec::new();
1712 for (ix, c) in text.char_indices() {
1713 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1714 glyphs.push(ShapedGlyph {
1715 id: glyph,
1716 position: point(position, px(0.)),
1717 index: ix,
1718 is_emoji: glyph.0 == 2,
1719 });
1720 if glyph.0 == 2 {
1721 position += em_width * 2.0;
1722 } else {
1723 position += em_width;
1724 }
1725 } else {
1726 position += em_width
1727 }
1728 }
1729 let mut runs = Vec::default();
1730 if !glyphs.is_empty() {
1731 runs.push(ShapedRun {
1732 font_id: FontId(0),
1733 glyphs,
1734 });
1735 } else {
1736 position = px(0.);
1737 }
1738
1739 LineLayout {
1740 font_size,
1741 width: position,
1742 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1743 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1744 runs,
1745 len: text.len(),
1746 }
1747 }
1748
1749 fn recommended_rendering_mode(
1750 &self,
1751 _font_id: FontId,
1752 _font_size: Pixels,
1753 ) -> TextRenderingMode {
1754 TextRenderingMode::Grayscale
1755 }
1756}
1757
1758#[allow(dead_code)]
1763pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1764 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1765 [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], ];
1779
1780 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1781 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1782
1783 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1784 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1785
1786 [
1787 ratios[0] * NORM13,
1788 ratios[1] * NORM24,
1789 ratios[2] * NORM13,
1790 ratios[3] * NORM24,
1791 ]
1792}
1793
1794#[derive(PartialEq, Eq, Hash, Clone)]
1795#[expect(missing_docs)]
1796pub enum AtlasKey {
1797 Glyph(RenderGlyphParams),
1798 Svg(RenderSvgParams),
1799 Image(RenderImageParams),
1800}
1801
1802impl AtlasKey {
1803 pub fn texture_kind(&self) -> AtlasTextureKind {
1805 match self {
1806 AtlasKey::Glyph(params) => {
1807 if params.is_emoji {
1808 AtlasTextureKind::Polychrome
1809 } else if params.subpixel_rendering {
1810 AtlasTextureKind::Subpixel
1811 } else {
1812 AtlasTextureKind::Monochrome
1813 }
1814 }
1815 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1816 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1817 }
1818 }
1819}
1820
1821impl From<RenderGlyphParams> for AtlasKey {
1822 fn from(params: RenderGlyphParams) -> Self {
1823 Self::Glyph(params)
1824 }
1825}
1826
1827impl From<RenderSvgParams> for AtlasKey {
1828 fn from(params: RenderSvgParams) -> Self {
1829 Self::Svg(params)
1830 }
1831}
1832
1833impl From<RenderImageParams> for AtlasKey {
1834 fn from(params: RenderImageParams) -> Self {
1835 Self::Image(params)
1836 }
1837}
1838
1839#[expect(missing_docs)]
1840pub trait PlatformAtlas {
1841 fn get_or_insert_with<'a>(
1843 &self,
1844 key: AtlasKey,
1845 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1846 ) -> Result<Option<AtlasTile>>;
1847 fn remove(&self, key: &AtlasKey);
1848
1849 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1850 fn contains(&self, _key: &AtlasKey) -> bool {
1851 false
1852 }
1853}
1854
1855#[doc(hidden)]
1856pub trait AtlasBackend {
1857 fn insert(
1858 &mut self,
1859 kind: AtlasTextureKind,
1860 size: Size<DevicePixels>,
1861 bytes: &[u8],
1862 ) -> Result<AtlasTile>;
1863
1864 fn remove(&mut self, tile: AtlasTile);
1865}
1866
1867#[doc(hidden)]
1868pub struct AtlasState<Backend> {
1869 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1870 pub backend: Backend,
1871}
1872
1873impl<Backend> AtlasState<Backend> {
1874 pub fn new(backend: Backend) -> Self {
1875 Self {
1876 tiles_by_key: FxHashMap::default(),
1877 backend,
1878 }
1879 }
1880
1881 pub fn contains(&self, key: &AtlasKey) -> bool {
1882 self.tiles_by_key.contains_key(key)
1883 }
1884
1885 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1886 self.tiles_by_key.clear();
1887 reset_backend(&mut self.backend);
1888 }
1889}
1890
1891impl<Backend: Default> Default for AtlasState<Backend> {
1892 fn default() -> Self {
1893 Self::new(Backend::default())
1894 }
1895}
1896
1897impl<Backend: AtlasBackend> AtlasState<Backend> {
1898 pub fn get_or_insert_with<'a>(
1899 &mut self,
1900 key: AtlasKey,
1901 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1902 ) -> Result<Option<AtlasTile>> {
1903 match self.tiles_by_key.entry(key) {
1904 Entry::Occupied(entry) => Ok(Some(*entry.get())),
1905 Entry::Vacant(entry) => {
1906 profiling::scope!("new tile");
1907 let Some((size, bytes)) = build()? else {
1908 return Ok(None);
1909 };
1910 let tile = self
1911 .backend
1912 .insert(entry.key().texture_kind(), size, &bytes)?;
1913 entry.insert(tile);
1914 Ok(Some(tile))
1915 }
1916 }
1917 }
1918
1919 pub fn remove(&mut self, key: &AtlasKey) {
1920 if let Some(tile) = self.tiles_by_key.remove(key) {
1921 self.backend.remove(tile);
1922 }
1923 }
1924}
1925
1926#[derive(Default)]
1930pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1931
1932#[doc(hidden)]
1933#[derive(Default)]
1934pub struct HeadlessAtlasBackend {
1935 next_id: u32,
1936}
1937
1938impl AtlasBackend for HeadlessAtlasBackend {
1939 fn insert(
1940 &mut self,
1941 kind: AtlasTextureKind,
1942 size: Size<DevicePixels>,
1943 _bytes: &[u8],
1944 ) -> Result<AtlasTile> {
1945 self.next_id += 1;
1946 let texture_id = self.next_id;
1947 self.next_id += 1;
1948 let tile_id = self.next_id;
1949 Ok(AtlasTile {
1950 texture_id: AtlasTextureId {
1951 index: texture_id,
1952 kind,
1953 },
1954 tile_id: TileId(tile_id),
1955 padding: 0,
1956 bounds: Bounds {
1957 origin: Point::default(),
1958 size,
1959 },
1960 })
1961 }
1962
1963 fn remove(&mut self, _tile: AtlasTile) {}
1964}
1965
1966impl PlatformAtlas for HeadlessAtlas {
1967 fn get_or_insert_with<'a>(
1968 &self,
1969 key: AtlasKey,
1970 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1971 ) -> Result<Option<AtlasTile>> {
1972 self.0.lock().get_or_insert_with(key, build)
1973 }
1974
1975 fn remove(&self, key: &AtlasKey) {
1976 self.0.lock().remove(key);
1977 }
1978
1979 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1980 fn contains(&self, key: &AtlasKey) -> bool {
1981 self.0.lock().contains(key)
1982 }
1983}
1984
1985#[doc(hidden)]
1986pub struct AtlasTextureList<T> {
1987 pub textures: Vec<Option<T>>,
1988 pub free_list: Vec<usize>,
1989}
1990
1991impl<T> Default for AtlasTextureList<T> {
1992 fn default() -> Self {
1993 Self {
1994 textures: Vec::default(),
1995 free_list: Vec::default(),
1996 }
1997 }
1998}
1999
2000impl<T> ops::Index<usize> for AtlasTextureList<T> {
2001 type Output = Option<T>;
2002
2003 fn index(&self, index: usize) -> &Self::Output {
2004 &self.textures[index]
2005 }
2006}
2007
2008impl<T> AtlasTextureList<T> {
2009 #[allow(unused)]
2010 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2011 self.free_list.clear();
2012 self.textures.drain(..)
2013 }
2014
2015 #[allow(dead_code)]
2016 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2017 self.textures.iter_mut().flatten()
2018 }
2019}
2020
2021#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2022#[repr(C)]
2023#[expect(missing_docs)]
2024pub struct AtlasTile {
2025 pub texture_id: AtlasTextureId,
2027 pub tile_id: TileId,
2029 pub padding: u32,
2031 pub bounds: Bounds<DevicePixels>,
2033}
2034
2035#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2036#[repr(C)]
2037#[expect(missing_docs)]
2038pub struct AtlasTextureId {
2039 pub index: u32,
2042 pub kind: AtlasTextureKind,
2044}
2045
2046#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2047#[repr(C)]
2048#[cfg_attr(
2049 all(
2050 any(target_os = "linux", target_os = "freebsd"),
2051 not(any(feature = "x11", feature = "wayland"))
2052 ),
2053 allow(dead_code)
2054)]
2055#[expect(missing_docs)]
2056pub enum AtlasTextureKind {
2057 Monochrome = 0,
2058 Polychrome = 1,
2059 Subpixel = 2,
2060}
2061
2062#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2063#[repr(C)]
2064#[expect(missing_docs)]
2065pub struct TileId(pub u32);
2066
2067impl From<etagere::AllocId> for TileId {
2068 fn from(id: etagere::AllocId) -> Self {
2069 Self(id.serialize())
2070 }
2071}
2072
2073impl From<TileId> for etagere::AllocId {
2074 fn from(id: TileId) -> Self {
2075 Self::deserialize(id.0)
2076 }
2077}
2078
2079#[expect(missing_docs)]
2080pub struct PlatformInputHandler {
2081 cx: AsyncWindowContext,
2082 handler: Box<dyn InputHandler>,
2083 focus_id: Option<crate::FocusId>,
2084}
2085
2086#[expect(missing_docs)]
2087#[cfg_attr(
2088 all(
2089 any(target_os = "linux", target_os = "freebsd"),
2090 not(any(feature = "x11", feature = "wayland"))
2091 ),
2092 allow(dead_code)
2093)]
2094impl PlatformInputHandler {
2095 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2096 Self {
2097 cx,
2098 handler,
2099 focus_id: None,
2100 }
2101 }
2102
2103 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2104 self.focus_id = Some(focus_id);
2105 self
2106 }
2107
2108 pub fn focus_id(&self) -> Option<crate::FocusId> {
2113 self.focus_id
2114 }
2115
2116 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2117 self.cx
2118 .update(|window, cx| {
2119 self.handler
2120 .selected_text_range(ignore_disabled_input, window, cx)
2121 })
2122 .ok()
2123 .flatten()
2124 }
2125
2126 #[cfg_attr(target_os = "windows", allow(dead_code))]
2127 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2128 self.cx
2129 .update(|window, cx| self.handler.marked_text_range(window, cx))
2130 .ok()
2131 .flatten()
2132 }
2133
2134 #[cfg_attr(
2135 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2136 allow(dead_code)
2137 )]
2138 pub fn text_for_range(
2139 &mut self,
2140 range_utf16: Range<usize>,
2141 adjusted: &mut Option<Range<usize>>,
2142 ) -> Option<String> {
2143 self.cx
2144 .update(|window, cx| {
2145 self.handler
2146 .text_for_range(range_utf16, adjusted, window, cx)
2147 })
2148 .ok()
2149 .flatten()
2150 }
2151
2152 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2153 self.cx
2154 .update(|window, cx| {
2155 self.handler
2156 .replace_text_in_range(replacement_range, text, window, cx);
2157 })
2158 .ok();
2159 }
2160
2161 pub fn replace_and_mark_text_in_range(
2162 &mut self,
2163 range_utf16: Option<Range<usize>>,
2164 new_text: &str,
2165 new_selected_range: Option<Range<usize>>,
2166 ) {
2167 self.cx
2168 .update(|window, cx| {
2169 self.handler.replace_and_mark_text_in_range(
2170 range_utf16,
2171 new_text,
2172 new_selected_range,
2173 window,
2174 cx,
2175 )
2176 })
2177 .ok();
2178 }
2179
2180 #[cfg_attr(target_os = "windows", allow(dead_code))]
2181 pub fn unmark_text(&mut self) {
2182 self.cx
2183 .update(|window, cx| self.handler.unmark_text(window, cx))
2184 .ok();
2185 }
2186
2187 pub fn paste(&mut self, item: ClipboardItem) {
2188 self.cx
2189 .update(|window, cx| self.handler.paste(item, window, cx))
2190 .ok();
2191 }
2192
2193 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2194 self.cx
2195 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2196 .ok()
2197 .flatten()
2198 }
2199
2200 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2201 self.cx
2202 .update(|window, cx| {
2203 self.handler
2204 .selection_bounds_for_range(range_utf16, window, cx)
2205 })
2206 .unwrap_or_default()
2207 }
2208
2209 #[allow(dead_code)]
2210 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2211 self.handler.apple_press_and_hold_enabled()
2212 }
2213
2214 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2215 self.handler.replace_text_in_range(None, input, window, cx);
2216 }
2217
2218 pub fn compute_ime_candidate_bounds(
2219 marked_range: Option<Range<usize>>,
2220 selection: &UTF16Selection,
2221 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2222 ) -> Option<Bounds<Pixels>> {
2223 if let Some(marked_range) = marked_range {
2224 let mut line_start = marked_range.start;
2226
2227 let caret = selection.range.end;
2231 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2232 for i in (marked_range.start..caret).rev() {
2233 if let Some(b) = bounds_for_range(i..i) {
2234 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2235 line_start = i + 1;
2236 break;
2237 }
2238 }
2239 }
2240 }
2241 bounds_for_range(line_start..line_start)
2242 } else {
2243 let offset = if selection.reversed {
2245 selection.range.start
2246 } else {
2247 selection.range.end
2248 };
2249 bounds_for_range(offset..offset)
2250 }
2251 }
2252
2253 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2254 let marked_range = self.handler.marked_text_range(window, cx);
2255 let selection = self.handler.selected_text_range(true, window, cx)?;
2256 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2257 self.handler.bounds_for_range(range, window, cx)
2258 })
2259 }
2260
2261 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2262 let marked_range = self.marked_text_range();
2263 let selection = self.selected_text_range(true)?;
2264 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2265 self.bounds_for_range(range)
2266 })
2267 }
2268
2269 #[allow(unused)]
2270 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2271 self.cx
2272 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2273 .ok()
2274 .flatten()
2275 }
2276
2277 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2279 self.cx
2280 .update(|window, cx| {
2281 self.handler
2282 .set_selected_text_range(range_utf16, window, cx)
2283 })
2284 .ok();
2285 }
2286
2287 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2289 self.cx
2290 .update(|window, cx| self.handler.element_bounds(window, cx))
2291 .ok()
2292 .flatten()
2293 }
2294
2295 pub fn text_length_utf16(&mut self) -> Option<usize> {
2297 self.cx
2298 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2299 .ok()
2300 .flatten()
2301 }
2302
2303 #[allow(dead_code)]
2304 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2305 self.handler.accepts_text_input(window, cx)
2306 }
2307
2308 #[allow(dead_code)]
2309 pub fn query_accepts_text_input(&mut self) -> bool {
2310 self.cx
2311 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2312 .unwrap_or(true)
2313 }
2314
2315 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2320 let focus_id = self.focus_id;
2321 self.cx
2322 .update(|window, cx| {
2323 focus_id.is_some()
2324 && window.focus == focus_id
2325 && self.handler.accepts_text_input(window, cx)
2326 })
2327 .unwrap_or(false)
2328 }
2329
2330 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2336 self.cx
2337 .update(|window, cx| {
2338 !window.has_pending_keystrokes()
2340 && self.handler.prefers_ime_for_printable_keys(window, cx)
2341 })
2342 .unwrap_or(false)
2343 }
2344
2345 pub fn text_input_configuration(
2347 &mut self,
2348 window: &mut Window,
2349 cx: &mut App,
2350 ) -> TextInputConfiguration {
2351 self.handler.text_input_configuration(window, cx)
2352 }
2353
2354 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2356 self.cx
2357 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2358 .ok()
2359 .flatten()
2360 }
2361}
2362
2363#[derive(Debug)]
2366pub struct UTF16Selection {
2367 pub range: Range<usize>,
2370 pub reversed: bool,
2373}
2374
2375pub trait InputHandler: 'static {
2380 fn selected_text_range(
2385 &mut self,
2386 ignore_disabled_input: bool,
2387 window: &mut Window,
2388 cx: &mut App,
2389 ) -> Option<UTF16Selection>;
2390
2391 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2396
2397 fn text_for_range(
2402 &mut self,
2403 range_utf16: Range<usize>,
2404 adjusted_range: &mut Option<Range<usize>>,
2405 window: &mut Window,
2406 cx: &mut App,
2407 ) -> Option<String>;
2408
2409 fn replace_text_in_range(
2414 &mut self,
2415 replacement_range: Option<Range<usize>>,
2416 text: &str,
2417 window: &mut Window,
2418 cx: &mut App,
2419 );
2420
2421 fn replace_and_mark_text_in_range(
2428 &mut self,
2429 range_utf16: Option<Range<usize>>,
2430 new_text: &str,
2431 new_selected_range: Option<Range<usize>>,
2432 window: &mut Window,
2433 cx: &mut App,
2434 );
2435
2436 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2439
2440 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2447 if let Some(text) = item.text() {
2448 self.replace_text_in_range(None, &text, window, cx);
2449 }
2450 }
2451
2452 fn bounds_for_range(
2457 &mut self,
2458 range_utf16: Range<usize>,
2459 window: &mut Window,
2460 cx: &mut App,
2461 ) -> Option<Bounds<Pixels>>;
2462
2463 fn selection_bounds_for_range(
2470 &mut self,
2471 _range_utf16: Range<usize>,
2472 _window: &mut Window,
2473 _cx: &mut App,
2474 ) -> Vec<Bounds<Pixels>> {
2475 Vec::new()
2476 }
2477
2478 fn character_index_for_point(
2482 &mut self,
2483 point: Point<Pixels>,
2484 window: &mut Window,
2485 cx: &mut App,
2486 ) -> Option<usize>;
2487
2488 fn set_selected_text_range(
2498 &mut self,
2499 _range_utf16: Range<usize>,
2500 _window: &mut Window,
2501 _cx: &mut App,
2502 ) {
2503 }
2504
2505 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2512 None
2513 }
2514
2515 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2517 None
2518 }
2519
2520 #[allow(dead_code)]
2525 fn apple_press_and_hold_enabled(&mut self) -> bool {
2526 true
2527 }
2528
2529 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2531 true
2532 }
2533
2534 fn text_input_editable_range(
2545 &mut self,
2546 _window: &mut Window,
2547 _cx: &mut App,
2548 ) -> Option<Range<usize>> {
2549 None
2550 }
2551
2552 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2561 false
2562 }
2563
2564 fn text_input_configuration(
2570 &mut self,
2571 _window: &mut Window,
2572 _cx: &mut App,
2573 ) -> TextInputConfiguration {
2574 TextInputConfiguration::default()
2575 }
2576}
2577
2578#[derive(Clone, Debug, Default, PartialEq, Eq)]
2588pub struct TextInputConfiguration {
2589 pub autocorrect: bool,
2591 pub autocapitalize: Autocapitalize,
2593 pub suggestions: bool,
2595 pub input_action: TextInputAction,
2597}
2598
2599#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2601pub enum Autocapitalize {
2602 #[default]
2604 None,
2605 Words,
2607 Sentences,
2609 Characters,
2611}
2612
2613#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2623pub enum TextInputAction {
2624 #[default]
2626 Unspecified,
2627 Enter,
2629 Done,
2631 Go,
2633 Next,
2635 Previous,
2637 Search,
2639 Send,
2641}
2642
2643#[derive(Debug)]
2645pub struct WindowOptions {
2646 pub window_bounds: Option<WindowBounds>,
2650
2651 pub titlebar: Option<TitlebarOptions>,
2653
2654 pub focus: bool,
2656
2657 pub show: bool,
2659
2660 pub kind: WindowKind,
2662
2663 pub is_movable: bool,
2667
2668 pub app_owns_titlebar_drag: bool,
2680
2681 pub inactive_frame_interval: Option<Duration>,
2686
2687 pub low_power_frame_interval: Option<Duration>,
2692
2693 pub thermal_frame_interval: Option<Duration>,
2698
2699 pub is_resizable: bool,
2701
2702 pub is_minimizable: bool,
2704
2705 pub display_id: Option<DisplayId>,
2708
2709 pub window_background: WindowBackgroundAppearance,
2711
2712 pub app_id: Option<String>,
2714
2715 pub window_min_size: Option<Size<Pixels>>,
2717
2718 pub window_decorations: Option<WindowDecorations>,
2721
2722 pub icon: Option<Arc<image::RgbaImage>>,
2724
2725 pub tabbing_identifier: Option<String>,
2727
2728 pub use_display_p3: bool,
2730}
2731
2732#[derive(Debug)]
2734#[cfg_attr(
2735 all(
2736 any(target_os = "linux", target_os = "freebsd"),
2737 not(any(feature = "x11", feature = "wayland"))
2738 ),
2739 allow(dead_code)
2740)]
2741#[allow(missing_docs)]
2742pub struct WindowParams {
2743 pub bounds: Bounds<Pixels>,
2744
2745 #[cfg_attr(feature = "wayland", allow(dead_code))]
2747 pub titlebar: Option<TitlebarOptions>,
2748
2749 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2751 pub kind: WindowKind,
2752
2753 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2755 pub is_movable: bool,
2756
2757 #[cfg_attr(
2759 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2760 allow(dead_code)
2761 )]
2762 pub app_owns_titlebar_drag: bool,
2763
2764 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2766 pub is_resizable: bool,
2767
2768 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2770 pub is_minimizable: bool,
2771
2772 #[cfg_attr(
2773 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2774 allow(dead_code)
2775 )]
2776 pub focus: bool,
2777
2778 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2779 pub show: bool,
2780
2781 #[cfg_attr(feature = "wayland", allow(dead_code))]
2783 pub icon: Option<Arc<image::RgbaImage>>,
2784
2785 #[cfg_attr(feature = "wayland", allow(dead_code))]
2786 pub display_id: Option<DisplayId>,
2787
2788 #[cfg_attr(feature = "wayland", allow(dead_code))]
2789 pub app_id: Option<String>,
2790
2791 pub window_min_size: Option<Size<Pixels>>,
2792
2793 #[cfg(target_os = "macos")]
2794 pub tabbing_identifier: Option<String>,
2795
2796 #[cfg(target_os = "macos")]
2797 pub use_display_p3: bool,
2798}
2799
2800#[derive(Debug, Copy, Clone, PartialEq)]
2802pub enum WindowBounds {
2803 Windowed(Bounds<Pixels>),
2805 Maximized(Bounds<Pixels>),
2808 Fullscreen(Bounds<Pixels>),
2811}
2812
2813impl Default for WindowBounds {
2814 fn default() -> Self {
2815 WindowBounds::Windowed(Bounds::default())
2816 }
2817}
2818
2819impl WindowBounds {
2820 pub fn get_bounds(&self) -> Bounds<Pixels> {
2822 match self {
2823 WindowBounds::Windowed(bounds) => *bounds,
2824 WindowBounds::Maximized(bounds) => *bounds,
2825 WindowBounds::Fullscreen(bounds) => *bounds,
2826 }
2827 }
2828
2829 pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
2832 WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
2833 }
2834}
2835
2836impl Default for WindowOptions {
2837 fn default() -> Self {
2838 Self {
2839 window_bounds: None,
2840 titlebar: Some(TitlebarOptions {
2841 title: Default::default(),
2842 appears_transparent: Default::default(),
2843 traffic_light_position: Default::default(),
2844 }),
2845 focus: true,
2846 show: true,
2847 kind: WindowKind::Normal,
2848 is_movable: true,
2849 app_owns_titlebar_drag: false,
2850 inactive_frame_interval: Some(Duration::from_micros(33_333)),
2851 low_power_frame_interval: Some(Duration::from_micros(33_333)),
2852 thermal_frame_interval: Some(Duration::from_micros(16_667)),
2853 is_resizable: true,
2854 is_minimizable: true,
2855 display_id: None,
2856 window_background: WindowBackgroundAppearance::default(),
2857 icon: None,
2858 app_id: None,
2859 window_min_size: None,
2860 window_decorations: None,
2861 tabbing_identifier: None,
2862 use_display_p3: false,
2863 }
2864 }
2865}
2866
2867#[derive(Debug, Default)]
2869pub struct TitlebarOptions {
2870 pub title: Option<SharedString>,
2872
2873 pub appears_transparent: bool,
2876
2877 pub traffic_light_position: Option<Point<Pixels>>,
2879}
2880
2881#[derive(Clone, Debug, PartialEq, Eq)]
2883pub enum WindowKind {
2884 Normal,
2886
2887 PopUp,
2890
2891 AnchoredPopup(popup::PopupOptions),
2898
2899 Floating,
2901
2902 #[cfg(all(target_os = "linux", feature = "wayland"))]
2905 LayerShell(layer_shell::LayerShellOptions),
2906
2907 Dialog,
2910}
2911
2912#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2917pub enum WindowAppearance {
2918 #[default]
2922 Light,
2923
2924 VibrantLight,
2928
2929 Dark,
2933
2934 VibrantDark,
2938}
2939
2940#[derive(Copy, Clone, Debug, Default, PartialEq)]
2943pub enum WindowBackgroundAppearance {
2944 #[default]
2952 Opaque,
2953 Transparent,
2955 Blurred,
2959 MicaBackdrop,
2961 MicaAltBackdrop,
2963}
2964
2965#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2967pub enum TextRenderingMode {
2968 #[default]
2970 PlatformDefault,
2971 Subpixel,
2973 Grayscale,
2975}
2976
2977#[derive(Clone, Debug)]
2979pub struct PathPromptOptions {
2980 pub files: bool,
2982 pub directories: bool,
2984 pub multiple: bool,
2986 pub prompt: Option<SharedString>,
2988}
2989
2990#[derive(Copy, Clone, Debug, PartialEq)]
2992pub enum PromptLevel {
2993 Info,
2995
2996 Warning,
2998
2999 Critical,
3001}
3002
3003#[derive(Clone, Debug, PartialEq)]
3005pub enum PromptButton {
3006 Ok(SharedString),
3008 Cancel(SharedString),
3010 Other(SharedString),
3012}
3013
3014impl PromptButton {
3015 pub fn new(label: impl Into<SharedString>) -> Self {
3017 PromptButton::Other(label.into())
3018 }
3019
3020 pub fn ok(label: impl Into<SharedString>) -> Self {
3022 PromptButton::Ok(label.into())
3023 }
3024
3025 pub fn cancel(label: impl Into<SharedString>) -> Self {
3027 PromptButton::Cancel(label.into())
3028 }
3029
3030 #[allow(dead_code)]
3032 pub fn is_cancel(&self) -> bool {
3033 matches!(self, PromptButton::Cancel(_))
3034 }
3035
3036 pub fn label(&self) -> &SharedString {
3038 match self {
3039 PromptButton::Ok(label) => label,
3040 PromptButton::Cancel(label) => label,
3041 PromptButton::Other(label) => label,
3042 }
3043 }
3044}
3045
3046impl From<&str> for PromptButton {
3047 fn from(value: &str) -> Self {
3048 match value.to_lowercase().as_str() {
3049 "ok" => PromptButton::Ok("OK".into()),
3050 "cancel" => PromptButton::Cancel("Cancel".into()),
3051 _ => PromptButton::Other(SharedString::from(value.to_owned())),
3052 }
3053 }
3054}
3055
3056#[derive(
3058 Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, EnumIter,
3059)]
3060pub enum CursorStyle {
3061 #[default]
3063 Arrow,
3064
3065 IBeam,
3068
3069 Crosshair,
3072
3073 ClosedHand,
3076
3077 OpenHand,
3080
3081 PointingHand,
3084
3085 ResizeLeft,
3088
3089 ResizeRight,
3092
3093 ResizeLeftRight,
3096
3097 ResizeUp,
3100
3101 ResizeDown,
3104
3105 ResizeUpDown,
3108
3109 ResizeUpLeftDownRight,
3112
3113 ResizeUpRightDownLeft,
3116
3117 ResizeColumn,
3120
3121 ResizeRow,
3124
3125 IBeamCursorForVerticalLayout,
3128
3129 OperationNotAllowed,
3132
3133 DragLink,
3136
3137 DragCopy,
3140
3141 ContextualMenu,
3144}
3145
3146#[derive(Clone, Debug, Eq, PartialEq)]
3148pub struct ClipboardItem {
3149 pub entries: Vec<ClipboardEntry>,
3151}
3152
3153#[derive(Clone, Debug, PartialEq, Eq)]
3158pub enum ClipboardReadError {
3159 Unavailable,
3163 Denied(String),
3166 UnsupportedContent,
3169}
3170
3171impl std::fmt::Display for ClipboardReadError {
3172 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3173 match self {
3174 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3175 Self::Denied(message) => {
3176 write!(formatter, "clipboard access was denied: {message}")
3177 }
3178 Self::UnsupportedContent => {
3179 formatter.write_str("the clipboard contents are unsupported")
3180 }
3181 }
3182 }
3183}
3184
3185impl std::error::Error for ClipboardReadError {}
3186
3187#[derive(Clone, Debug, Eq, PartialEq)]
3189pub enum ClipboardEntry {
3190 String(ClipboardString),
3192 Image(Image),
3194 ExternalPaths(crate::ExternalPaths),
3196}
3197
3198impl ClipboardItem {
3199 pub fn new_string(text: String) -> Self {
3201 Self {
3202 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3203 }
3204 }
3205
3206 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3208 Self {
3209 entries: vec![ClipboardEntry::String(ClipboardString {
3210 text,
3211 metadata: Some(metadata),
3212 })],
3213 }
3214 }
3215
3216 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3218 Self {
3219 entries: vec![ClipboardEntry::String(
3220 ClipboardString::new(text).with_json_metadata(metadata),
3221 )],
3222 }
3223 }
3224
3225 pub fn new_image(image: &Image) -> Self {
3227 Self {
3228 entries: vec![ClipboardEntry::Image(image.clone())],
3229 }
3230 }
3231
3232 pub fn text(&self) -> Option<String> {
3235 let mut answer = String::new();
3236
3237 for entry in self.entries.iter() {
3238 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3239 answer.push_str(text);
3240 }
3241 }
3242
3243 if answer.is_empty() {
3244 for entry in self.entries.iter() {
3245 if let ClipboardEntry::ExternalPaths(paths) = entry {
3246 for path in &paths.0 {
3247 use std::fmt::Write as _;
3248 _ = write!(answer, "{}", path.display());
3249 }
3250 }
3251 }
3252 }
3253
3254 if !answer.is_empty() {
3255 Some(answer)
3256 } else {
3257 None
3258 }
3259 }
3260
3261 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3263 pub fn metadata(&self) -> Option<&String> {
3264 match self.entries().first() {
3265 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3266 clipboard_string.metadata.as_ref()
3267 }
3268 _ => None,
3269 }
3270 }
3271
3272 pub fn entries(&self) -> &[ClipboardEntry] {
3274 &self.entries
3275 }
3276
3277 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3279 self.entries.into_iter()
3280 }
3281}
3282
3283impl From<ClipboardString> for ClipboardEntry {
3284 fn from(value: ClipboardString) -> Self {
3285 Self::String(value)
3286 }
3287}
3288
3289impl From<String> for ClipboardEntry {
3290 fn from(value: String) -> Self {
3291 Self::from(ClipboardString::from(value))
3292 }
3293}
3294
3295impl From<Image> for ClipboardEntry {
3296 fn from(value: Image) -> Self {
3297 Self::Image(value)
3298 }
3299}
3300
3301impl From<ClipboardEntry> for ClipboardItem {
3302 fn from(value: ClipboardEntry) -> Self {
3303 Self {
3304 entries: vec![value],
3305 }
3306 }
3307}
3308
3309impl From<String> for ClipboardItem {
3310 fn from(value: String) -> Self {
3311 Self::from(ClipboardEntry::from(value))
3312 }
3313}
3314
3315impl From<Image> for ClipboardItem {
3316 fn from(value: Image) -> Self {
3317 Self::from(ClipboardEntry::from(value))
3318 }
3319}
3320
3321#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3323pub enum ImageFormat {
3324 Png,
3329 Jpeg,
3331 Webp,
3333 Gif,
3335 Svg,
3337 Bmp,
3339 Tiff,
3341 Ico,
3343 Pnm,
3345}
3346
3347impl ImageFormat {
3348 pub const fn mime_type(self) -> &'static str {
3350 match self {
3351 ImageFormat::Png => "image/png",
3352 ImageFormat::Jpeg => "image/jpeg",
3353 ImageFormat::Webp => "image/webp",
3354 ImageFormat::Gif => "image/gif",
3355 ImageFormat::Svg => "image/svg+xml",
3356 ImageFormat::Bmp => "image/bmp",
3357 ImageFormat::Tiff => "image/tiff",
3358 ImageFormat::Ico => "image/ico",
3359 ImageFormat::Pnm => "image/x-portable-anymap",
3360 }
3361 }
3362
3363 pub const fn extension(self) -> &'static str {
3365 match self {
3366 ImageFormat::Png => "png",
3367 ImageFormat::Jpeg => "jpg",
3368 ImageFormat::Webp => "webp",
3369 ImageFormat::Gif => "gif",
3370 ImageFormat::Svg => "svg",
3371 ImageFormat::Bmp => "bmp",
3372 ImageFormat::Tiff => "tiff",
3373 ImageFormat::Ico => "ico",
3374 ImageFormat::Pnm => "pnm",
3375 }
3376 }
3377
3378 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3380 use strum::IntoEnumIterator;
3381 Self::iter()
3382 .find(|format| format.mime_type() == mime_type)
3383 .or_else(|| Self::from_mime_type_alias(mime_type))
3384 }
3385
3386 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3390 match mime_type {
3391 "image/jpg" => Some(Self::Jpeg),
3392 "image/tif" => Some(Self::Tiff),
3393 _ => None,
3394 }
3395 }
3396}
3397
3398#[derive(Clone, Debug, PartialEq, Eq)]
3400pub struct Image {
3401 pub format: ImageFormat,
3403 pub bytes: Vec<u8>,
3405 pub id: u64,
3407}
3408
3409pub(crate) fn decode_static_image(
3410 bytes: &[u8],
3411 format: image::ImageFormat,
3412) -> Result<SmallVec<[Frame; 1]>> {
3413 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3414 .into_decoder()
3415 .context("creating image decoder")?;
3416 decode_static_image_from_decoder(decoder)
3417}
3418
3419pub(crate) fn decode_static_image_from_decoder(
3420 mut decoder: impl image::ImageDecoder,
3421) -> Result<SmallVec<[Frame; 1]>> {
3422 let orientation = decoder
3423 .orientation()
3424 .context("reading decoder's orientation")?;
3425 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3426 image.apply_orientation(orientation);
3427
3428 let mut data = image.into_rgba8();
3429 for pixel in data.chunks_exact_mut(4) {
3430 pixel.swap(0, 2);
3431 }
3432
3433 Ok(SmallVec::from_elem(Frame::new(data), 1))
3434}
3435
3436fn decode_animated_frames<'a>(
3437 decoder: impl image::AnimationDecoder<'a>,
3438 format_name: &str,
3439) -> Result<SmallVec<[Frame; 1]>> {
3440 let mut frames = SmallVec::new();
3441
3442 for frame in decoder.into_frames() {
3443 match frame {
3444 Ok(mut frame) => {
3445 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3447 pixel.swap(0, 2);
3448 }
3449 frames.push(frame);
3450 }
3451 Err(err) => {
3452 log::debug!("Skipping {format_name} frame due to decode error: {err}");
3453 }
3454 }
3455 }
3456
3457 if frames.is_empty() {
3458 anyhow::bail!("{format_name} could not be decoded: all frames failed");
3459 }
3460
3461 Ok(frames)
3462}
3463
3464pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3465 let decoder = GifDecoder::new(Cursor::new(bytes))?;
3466 decode_animated_frames(decoder, "GIF")
3467}
3468
3469pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3470 let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
3471
3472 if decoder.has_animation() {
3473 let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
3474 decode_animated_frames(decoder, "WebP")
3475 } else {
3476 decode_static_image_from_decoder(decoder)
3477 }
3478}
3479
3480impl Hash for Image {
3481 fn hash<H: Hasher>(&self, state: &mut H) {
3482 state.write_u64(self.id);
3483 }
3484}
3485
3486impl Image {
3487 pub fn empty() -> Self {
3489 Self::from_bytes(ImageFormat::Png, Vec::new())
3490 }
3491
3492 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3494 Self {
3495 id: hash(&bytes),
3496 format,
3497 bytes,
3498 }
3499 }
3500
3501 pub fn id(&self) -> u64 {
3503 self.id
3504 }
3505
3506 pub fn use_render_image(
3508 self: Arc<Self>,
3509 window: &mut Window,
3510 cx: &mut App,
3511 ) -> Option<Arc<RenderImage>> {
3512 ImageSource::Image(self)
3513 .use_data(None, window, cx)
3514 .and_then(|result| result.ok())
3515 }
3516
3517 pub fn get_render_image(
3519 self: Arc<Self>,
3520 window: &mut Window,
3521 cx: &mut App,
3522 ) -> Option<Arc<RenderImage>> {
3523 ImageSource::Image(self)
3524 .get_data(None, window, cx)
3525 .and_then(|result| result.ok())
3526 }
3527
3528 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3530 ImageSource::Image(self).remove_asset(cx);
3531 }
3532
3533 #[cfg(any(test, feature = "test-support"))]
3536 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3537 ImageSource::Image(self.clone()).is_asset_cached(cx)
3538 }
3539
3540 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3542 let frames = match self.format {
3543 ImageFormat::Gif => decode_gif_image(&self.bytes)?,
3544 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3545 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3546 ImageFormat::Webp => decode_webp_image(&self.bytes)?,
3547 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3548 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3549 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3550 ImageFormat::Svg => {
3551 return svg_renderer
3552 .render_single_frame(&self.bytes, 1.0)
3553 .map_err(Into::into);
3554 }
3555 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3556 };
3557
3558 Ok(Arc::new(RenderImage::new(frames)))
3559 }
3560
3561 pub fn format(&self) -> ImageFormat {
3563 self.format
3564 }
3565
3566 pub fn bytes(&self) -> &[u8] {
3568 self.bytes.as_slice()
3569 }
3570}
3571
3572#[derive(Clone, Debug, Eq, PartialEq)]
3574pub struct ClipboardString {
3575 pub text: String,
3577 pub metadata: Option<String>,
3579}
3580
3581impl ClipboardString {
3582 pub fn new(text: String) -> Self {
3584 Self {
3585 text,
3586 metadata: None,
3587 }
3588 }
3589
3590 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3593 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3594 self
3595 }
3596
3597 pub fn text(&self) -> &String {
3599 &self.text
3600 }
3601
3602 pub fn into_text(self) -> String {
3604 self.text
3605 }
3606
3607 pub fn metadata_json<T>(&self) -> Option<T>
3609 where
3610 T: for<'a> Deserialize<'a>,
3611 {
3612 self.metadata
3613 .as_ref()
3614 .and_then(|m| serde_json::from_str(m).ok())
3615 }
3616
3617 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3618 pub fn text_hash(text: &str) -> u64 {
3620 let mut hasher = SeaHasher::new();
3621 text.hash(&mut hasher);
3622 hasher.finish()
3623 }
3624}
3625
3626impl From<String> for ClipboardString {
3627 fn from(value: String) -> Self {
3628 Self {
3629 text: value,
3630 metadata: None,
3631 }
3632 }
3633}
3634
3635#[cfg(test)]
3636mod image_tests {
3637 use super::*;
3638 use std::sync::Arc;
3639
3640 #[test]
3641 fn test_image_to_image_data_applies_exif_orientation() {
3642 let image = Image::from_bytes(
3643 ImageFormat::Jpeg,
3644 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3645 );
3646
3647 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3648
3649 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3650
3651 let bytes = render_image.as_bytes(0).unwrap();
3652 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3653 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3654 }
3655
3656 #[test]
3657 fn test_svg_image_to_image_data_converts_to_bgra() {
3658 let image = Image::from_bytes(
3659 ImageFormat::Svg,
3660 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3661<rect width="1" height="1" fill="#38BDF8"/>
3662</svg>"##
3663 .to_vec(),
3664 );
3665
3666 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3667 let bytes = render_image.as_bytes(0).unwrap();
3668
3669 for pixel in bytes.chunks_exact(4) {
3670 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3671 }
3672 }
3673
3674 #[test]
3675 fn test_animated_webp_image_to_image_data_decodes_frames() {
3676 const ANIMATED_WEBP: &[u8] = &[
3678 82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
3679 0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
3680 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,
3681 0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
3682 176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
3683 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,
3684 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,
3685 0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
3686 31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
3687 ];
3688
3689 let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
3690 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3691
3692 assert_eq!(render_image.frame_count(), 2);
3693 assert_eq!(render_image.size(0), size(1.into(), 1.into()));
3694 assert_eq!(
3695 Duration::from(render_image.delay(0)),
3696 Duration::from_millis(100)
3697 );
3698 assert_eq!(
3699 Duration::from(render_image.delay(1)),
3700 Duration::from_millis(100)
3701 );
3702 }
3703}
3704
3705#[cfg(test)]
3706mod atlas_tests {
3707 use super::*;
3708
3709 const TILE_SIZE: Size<DevicePixels> = Size {
3710 width: DevicePixels(1),
3711 height: DevicePixels(1),
3712 };
3713
3714 #[derive(Default)]
3715 struct RecordingAtlasBackend {
3716 insert_calls: u32,
3717 fail_next_insert: bool,
3718 removed_tiles: Vec<AtlasTile>,
3719 }
3720
3721 impl AtlasBackend for RecordingAtlasBackend {
3722 fn insert(
3723 &mut self,
3724 kind: AtlasTextureKind,
3725 size: Size<DevicePixels>,
3726 _bytes: &[u8],
3727 ) -> Result<AtlasTile> {
3728 self.insert_calls += 1;
3729 if std::mem::take(&mut self.fail_next_insert) {
3730 anyhow::bail!("backend failed");
3731 }
3732 Ok(AtlasTile {
3733 texture_id: AtlasTextureId { index: 0, kind },
3734 tile_id: TileId(self.insert_calls),
3735 padding: 0,
3736 bounds: Bounds {
3737 origin: Point::default(),
3738 size,
3739 },
3740 })
3741 }
3742
3743 fn remove(&mut self, tile: AtlasTile) {
3744 self.removed_tiles.push(tile);
3745 }
3746 }
3747
3748 fn image_key(image_id: usize) -> AtlasKey {
3749 AtlasKey::Image(RenderImageParams {
3750 image_id: crate::ImageId(image_id),
3751 frame_index: 0,
3752 })
3753 }
3754
3755 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3756 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3757 }
3758
3759 #[test]
3760 fn only_successful_inserts_are_cached() -> Result<()> {
3761 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3762 let key = image_key(1);
3763
3764 assert_eq!(
3765 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3766 None
3767 );
3768 state
3769 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3770 .expect_err("builder error should propagate");
3771 assert!(!state.contains(&key));
3772 assert_eq!(state.backend.insert_calls, 0);
3773
3774 state.backend.fail_next_insert = true;
3775 state
3776 .get_or_insert_with(key.clone(), &mut build_tile)
3777 .expect_err("backend error should propagate");
3778 assert!(!state.contains(&key));
3779 assert_eq!(state.backend.insert_calls, 1);
3780
3781 let tile = state
3782 .get_or_insert_with(key.clone(), &mut build_tile)?
3783 .context("builder should produce a tile")?;
3784 assert_eq!(tile.texture_id.kind, key.texture_kind());
3785 assert_eq!(
3786 state.get_or_insert_with(key.clone(), &mut || {
3787 anyhow::bail!("cache hit must not call the builder")
3788 })?,
3789 Some(tile)
3790 );
3791 assert!(state.contains(&key));
3792 assert_eq!(state.backend.insert_calls, 2);
3793 Ok(())
3794 }
3795
3796 #[test]
3797 fn remove_and_clear_invalidate_keys() -> Result<()> {
3798 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3799 let key = image_key(1);
3800 let other_key = image_key(2);
3801 let tile = state
3802 .get_or_insert_with(key.clone(), &mut build_tile)?
3803 .context("builder should produce a tile")?;
3804 state
3805 .get_or_insert_with(other_key.clone(), &mut build_tile)?
3806 .context("builder should produce another tile")?;
3807
3808 state.remove(&key);
3809 state.remove(&key);
3810 assert!(!state.contains(&key));
3811 assert!(state.contains(&other_key));
3812 assert_eq!(state.backend.removed_tiles, vec![tile]);
3813
3814 let mut reset_calls = 0;
3815 state.clear(|_| reset_calls += 1);
3816 assert_eq!(reset_calls, 1);
3817 assert!(!state.contains(&other_key));
3818 assert_eq!(state.backend.removed_tiles, vec![tile]);
3819 Ok(())
3820 }
3821}
3822
3823#[cfg(test)]
3824mod frame_signal_tests {
3825 use super::*;
3826
3827 #[cfg(feature = "profiler")]
3828 #[test]
3829 fn coalesced_signals_retain_the_earliest_until_drained() {
3830 for (first_source, later_source) in [
3831 (
3832 FrameRequestSource::NativeCallback,
3833 FrameRequestSource::LocalSchedule,
3834 ),
3835 (
3836 FrameRequestSource::LocalSchedule,
3837 FrameRequestSource::NativeCallback,
3838 ),
3839 ] {
3840 let signal = PlatformFrameSignal::new();
3841 let first =
3842 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3843 assert_eq!(signal.take(), None);
3844 signal.record(first + Duration::from_millis(16), later_source);
3845 signal.record(first, first_source);
3846 signal.record(first + Duration::from_millis(32), later_source);
3847 assert_eq!(signal.take(), Some((first, first_source)));
3848 assert_eq!(signal.take(), None);
3849 let next = first + Duration::from_millis(48);
3850 signal.record(next, later_source);
3851 assert_eq!(signal.take(), Some((next, later_source)));
3852 }
3853 }
3854
3855 #[cfg(not(feature = "profiler"))]
3856 #[test]
3857 fn disabled_profiling_does_not_capture_or_store_timestamps() {
3858 let captured = PlatformFrameSignal::capture(|| {
3859 panic!("profiler-disabled builds must not evaluate the capture closure");
3860 });
3861 assert_eq!(captured, None);
3862 let signal = PlatformFrameSignal::new();
3863 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3864 assert_eq!(signal.take(), None);
3865 }
3866}
3867
3868#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3869mod tests {
3870 use super::*;
3871 use std::collections::HashSet;
3872
3873 #[test]
3874 fn test_refresh_interval_from_hz() {
3875 assert_eq!(
3876 refresh_interval_from_hz(50.0),
3877 Some(Duration::from_millis(20))
3878 );
3879 assert_eq!(
3880 refresh_interval_from_hz(120.0),
3881 Some(Duration::from_secs(1) / 120)
3882 );
3883 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
3884 assert_eq!(refresh_interval_from_hz(unknown), None);
3885 }
3886 }
3887
3888 #[test]
3889 fn test_window_button_layout_parse_standard() {
3890 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3891 assert_eq!(
3892 layout.left,
3893 [
3894 Some(WindowButton::Close),
3895 Some(WindowButton::Minimize),
3896 None
3897 ]
3898 );
3899 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3900 }
3901
3902 #[test]
3903 fn test_window_button_layout_parse_right_only() {
3904 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3905 assert_eq!(layout.left, [None, None, None]);
3906 assert_eq!(
3907 layout.right,
3908 [
3909 Some(WindowButton::Minimize),
3910 Some(WindowButton::Maximize),
3911 Some(WindowButton::Close)
3912 ]
3913 );
3914 }
3915
3916 #[test]
3917 fn test_window_button_layout_parse_left_only() {
3918 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3919 assert_eq!(
3920 layout.left,
3921 [
3922 Some(WindowButton::Close),
3923 Some(WindowButton::Minimize),
3924 Some(WindowButton::Maximize)
3925 ]
3926 );
3927 assert_eq!(layout.right, [None, None, None]);
3928 }
3929
3930 #[test]
3931 fn test_window_button_layout_parse_with_whitespace() {
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 None
3939 ]
3940 );
3941 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3942 }
3943
3944 #[test]
3945 fn test_window_button_layout_parse_empty() {
3946 let layout = WindowButtonLayout::parse("").unwrap();
3947 assert_eq!(layout.left, [None, None, None]);
3948 assert_eq!(layout.right, [None, None, None]);
3949 }
3950
3951 #[test]
3952 fn test_window_button_layout_parse_intentionally_empty() {
3953 let layout = WindowButtonLayout::parse(":").unwrap();
3954 assert_eq!(layout.left, [None, None, None]);
3955 assert_eq!(layout.right, [None, None, None]);
3956 }
3957
3958 #[test]
3959 fn test_window_button_layout_parse_invalid_buttons() {
3960 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
3961 assert_eq!(
3962 layout.left,
3963 [
3964 Some(WindowButton::Close),
3965 Some(WindowButton::Minimize),
3966 None
3967 ]
3968 );
3969 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3970 }
3971
3972 #[test]
3973 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
3974 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
3975 assert_eq!(
3976 layout.right,
3977 [
3978 Some(WindowButton::Close),
3979 Some(WindowButton::Minimize),
3980 None
3981 ]
3982 );
3983 assert_eq!(layout.format(), ":close,minimize");
3984 }
3985
3986 #[test]
3987 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
3988 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
3989 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3990 assert_eq!(
3991 layout.right,
3992 [
3993 Some(WindowButton::Maximize),
3994 Some(WindowButton::Minimize),
3995 None
3996 ]
3997 );
3998
3999 let button_ids: Vec<_> = layout
4000 .left
4001 .iter()
4002 .chain(layout.right.iter())
4003 .flatten()
4004 .map(WindowButton::id)
4005 .collect();
4006 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4007 assert_eq!(unique_button_ids.len(), button_ids.len());
4008 assert_eq!(layout.format(), "close:maximize,minimize");
4009 }
4010
4011 #[test]
4012 fn test_window_button_layout_parse_gnome_style() {
4013 let layout = WindowButtonLayout::parse("close").unwrap();
4014 assert_eq!(layout.left, [None, None, None]);
4015 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4016 }
4017
4018 #[test]
4019 fn test_window_button_layout_parse_elementary_style() {
4020 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4021 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4022 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4023 }
4024
4025 #[test]
4026 fn test_window_button_layout_round_trip() {
4027 let cases = [
4028 "close:minimize,maximize",
4029 "minimize,maximize,close:",
4030 ":close",
4031 "close:",
4032 "close:maximize",
4033 ":",
4034 ];
4035
4036 for case in cases {
4037 let layout = WindowButtonLayout::parse(case).unwrap();
4038 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4039 }
4040 }
4041
4042 #[test]
4043 fn test_window_button_layout_linux_default() {
4044 let layout = WindowButtonLayout::linux_default();
4045 assert_eq!(layout.left, [None, None, None]);
4046 assert_eq!(
4047 layout.right,
4048 [
4049 Some(WindowButton::Minimize),
4050 Some(WindowButton::Maximize),
4051 Some(WindowButton::Close)
4052 ]
4053 );
4054
4055 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4056 assert_eq!(round_tripped, layout);
4057 }
4058
4059 #[test]
4060 fn test_window_button_layout_parse_all_invalid() {
4061 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4062 }
4063}