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 text_scale_factor(&self) -> f32 {
477 1.0
478 }
479
480 fn on_text_scale_factor_change(&self, _callback: Box<dyn FnMut()>) {}
481
482 fn open_url(&self, url: &str);
483 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
484 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
485
486 fn prompt_for_paths(
487 &self,
488 options: PathPromptOptions,
489 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
490 fn prompt_for_new_path(
491 &self,
492 directory: &Path,
493 suggested_name: Option<&str>,
494 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
495 fn can_select_mixed_files_and_dirs(&self) -> bool;
496 fn reveal_path(&self, path: &Path);
497 fn open_with_system(&self, path: &Path);
498
499 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
500 fn on_reopen(&self, callback: Box<dyn FnMut()>);
501 fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
503 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
505
506 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
516
517 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
522
523 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
527 None
528 }
529
530 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
531 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
532 None
533 }
534
535 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
536 fn perform_dock_menu_action(&self, _action: usize) {}
537 fn add_recent_document(&self, _path: &Path) {}
538 fn update_jump_list(
539 &self,
540 _menus: Vec<MenuItem>,
541 _entries: Vec<SmallVec<[PathBuf; 2]>>,
542 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
543 Task::ready(Vec::new())
544 }
545 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
546 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
547 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
548
549 fn debug_state(&self) -> serde_json::Value {
551 serde_json::Value::Null
552 }
553
554 fn thermal_state(&self) -> ThermalState;
555 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
556 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
557
558 fn power_mode(&self) -> PowerMode {
561 PowerMode::Unknown
562 }
563 fn on_power_mode_change(&self, _callback: Box<dyn FnMut()>) {}
565
566 fn set_app_identity(&self, identifier: &str, name: &str) {
573 _ = (identifier, name);
574 }
575
576 fn show_system_notification(&self, notification: SystemNotification) {
583 _ = notification;
584 }
585
586 fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
594 _ = tag;
595 Task::ready(())
596 }
597
598 fn on_system_notification_response(
604 &self,
605 callback: Box<dyn FnMut(SystemNotificationResponse)>,
606 ) {
607 _ = callback;
608 }
609
610 fn compositor_name(&self) -> &'static str {
611 ""
612 }
613 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
616 None
617 }
618 fn app_path(&self) -> Result<PathBuf>;
619 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
620
621 fn set_cursor_style(&self, style: CursorStyle);
622
623 fn hide_cursor_until_mouse_moves(&self);
626
627 fn is_cursor_visible(&self) -> bool;
629
630 fn should_auto_hide_scrollbars(&self) -> bool;
631
632 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
633 fn write_to_clipboard(&self, item: ClipboardItem);
634
635 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
643 Task::ready(Ok(self.read_from_clipboard()))
644 }
645
646 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
647 fn read_from_primary(&self) -> Option<ClipboardItem>;
648 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
649 fn write_to_primary(&self, item: ClipboardItem);
650
651 #[cfg(target_os = "macos")]
652 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
653 #[cfg(target_os = "macos")]
654 fn write_to_find_pasteboard(&self, item: ClipboardItem);
655
656 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
657
658 #[cfg(target_os = "macos")]
662 fn write_credentials_if_not_exists(
663 &self,
664 _url: &str,
665 _username: &str,
666 _password: &[u8],
667 ) -> Task<Result<bool>> {
668 Task::ready(Err(anyhow::anyhow!(
669 "this platform does not support atomic credential writes"
670 )))
671 }
672
673 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
674 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
675
676 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
677 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
678 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
679}
680
681pub trait PlatformDisplay: Debug {
683 fn id(&self) -> DisplayId;
685
686 fn uuid(&self) -> Result<Uuid>;
689
690 fn bounds(&self) -> Bounds<Pixels>;
692
693 fn refresh_interval(&self) -> Option<Duration>;
700
701 fn visible_bounds(&self) -> Bounds<Pixels> {
705 self.bounds()
706 }
707
708 fn default_bounds(&self) -> Bounds<Pixels> {
710 let bounds = self.bounds();
711 let center = bounds.center();
712 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
713
714 let offset = clipped_window_size / 2.0;
715 let origin = point(center.x - offset.width, center.y - offset.height);
716 Bounds::new(origin, clipped_window_size)
717 }
718}
719
720#[derive(Clone, Debug, PartialEq, Eq)]
723pub struct SystemNotification {
724 pub tag: SharedString,
728 pub title: SharedString,
730 pub body: SharedString,
732 pub actions: Vec<SystemNotificationAction>,
735}
736
737#[derive(Clone, Debug, PartialEq, Eq, Hash)]
739pub struct SystemNotificationAction {
740 pub id: SharedString,
743 pub label: SharedString,
745}
746
747#[derive(Clone, Debug, PartialEq, Eq)]
749pub struct SystemNotificationResponse {
750 pub tag: SharedString,
752 pub action_id: Option<SharedString>,
755}
756
757#[derive(Debug, Clone, Copy, PartialEq, Eq)]
759pub enum PowerMode {
760 Unknown,
763 LowPower,
765 Balanced,
767 HighPower,
769}
770
771#[derive(Debug, Clone, Copy, PartialEq, Eq)]
773pub enum ThermalState {
774 Nominal,
776 Fair,
778 Serious,
780 Critical,
782}
783
784#[derive(Clone)]
786pub struct SourceMetadata {
787 pub id: u64,
789 pub label: Option<SharedString>,
791 pub is_main: Option<bool>,
793 pub resolution: Size<DevicePixels>,
795}
796
797pub trait ScreenCaptureSource {
799 fn metadata(&self) -> Result<SourceMetadata>;
801
802 fn stream(
805 &self,
806 foreground_executor: &ForegroundExecutor,
807 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
808 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
809}
810
811pub trait ScreenCaptureStream {
813 fn metadata(&self) -> Result<SourceMetadata>;
815}
816
817pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
819
820#[derive(PartialEq, Eq, Hash, Copy, Clone)]
822pub struct DisplayId(pub(crate) u64);
823
824impl DisplayId {
825 pub fn new(id: u64) -> Self {
827 Self(id)
828 }
829}
830
831impl From<u64> for DisplayId {
832 fn from(id: u64) -> Self {
833 Self(id)
834 }
835}
836
837impl From<DisplayId> for u64 {
838 fn from(id: DisplayId) -> Self {
839 id.0
840 }
841}
842
843impl Debug for DisplayId {
844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845 write!(f, "DisplayId({})", self.0)
846 }
847}
848
849#[derive(Debug, Clone, Copy, PartialEq, Eq)]
851pub enum ResizeEdge {
852 Top,
854 TopRight,
856 Right,
858 BottomRight,
860 Bottom,
862 BottomLeft,
864 Left,
866 TopLeft,
868}
869
870#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
872pub enum WindowDecorations {
873 #[default]
874 Server,
876 Client,
878}
879
880#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
882pub enum Decorations {
883 #[default]
885 Server,
886 Client {
888 tiling: Tiling,
890 },
891}
892
893#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
895pub struct WindowControls {
896 pub fullscreen: bool,
898 pub maximize: bool,
900 pub minimize: bool,
902 pub window_menu: bool,
904}
905
906impl Default for WindowControls {
907 fn default() -> Self {
908 Self {
910 fullscreen: true,
911 maximize: true,
912 minimize: true,
913 window_menu: true,
914 }
915 }
916}
917
918#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
920pub enum WindowButton {
921 Minimize,
923 Maximize,
925 Close,
927}
928
929impl WindowButton {
930 pub fn id(&self) -> &'static str {
932 match self {
933 WindowButton::Minimize => "minimize",
934 WindowButton::Maximize => "maximize",
935 WindowButton::Close => "close",
936 }
937 }
938
939 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
940 fn index(&self) -> usize {
941 match self {
942 WindowButton::Minimize => 0,
943 WindowButton::Maximize => 1,
944 WindowButton::Close => 2,
945 }
946 }
947}
948
949pub const MAX_BUTTONS_PER_SIDE: usize = 3;
951
952#[derive(Debug, Clone, Copy, PartialEq, Eq)]
957pub struct WindowButtonLayout {
958 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
960 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
962}
963
964#[cfg(any(target_os = "linux", target_os = "freebsd"))]
965impl WindowButtonLayout {
966 pub fn linux_default() -> Self {
968 Self {
969 left: [None; MAX_BUTTONS_PER_SIDE],
970 right: [
971 Some(WindowButton::Minimize),
972 Some(WindowButton::Maximize),
973 Some(WindowButton::Close),
974 ],
975 }
976 }
977
978 pub fn parse(layout_string: &str) -> Result<Self> {
980 fn parse_side(
981 s: &str,
982 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
983 unrecognized: &mut Vec<String>,
984 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
985 let mut result = [None; MAX_BUTTONS_PER_SIDE];
986 let mut i = 0;
987 for name in s.split(',') {
988 let trimmed = name.trim();
989 if trimmed.is_empty() {
990 continue;
991 }
992 let button = match trimmed {
993 "minimize" => Some(WindowButton::Minimize),
994 "maximize" => Some(WindowButton::Maximize),
995 "close" => Some(WindowButton::Close),
996 other => {
997 unrecognized.push(other.to_string());
998 None
999 }
1000 };
1001 if let Some(button) = button {
1002 if seen_buttons[button.index()] {
1003 continue;
1004 }
1005 if let Some(slot) = result.get_mut(i) {
1006 *slot = Some(button);
1007 seen_buttons[button.index()] = true;
1008 i += 1;
1009 }
1010 }
1011 }
1012 result
1013 }
1014
1015 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1016 let mut unrecognized = Vec::new();
1017 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1018 let layout = Self {
1019 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1020 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1021 };
1022
1023 if !unrecognized.is_empty()
1024 && layout.left.iter().all(Option::is_none)
1025 && layout.right.iter().all(Option::is_none)
1026 {
1027 bail!(
1028 "button layout string {:?} contains no valid buttons (unrecognized: {})",
1029 layout_string,
1030 unrecognized.join(", ")
1031 );
1032 }
1033
1034 Ok(layout)
1035 }
1036
1037 #[cfg(test)]
1039 pub fn format(&self) -> String {
1040 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1041 buttons
1042 .iter()
1043 .flatten()
1044 .map(|button| match button {
1045 WindowButton::Minimize => "minimize",
1046 WindowButton::Maximize => "maximize",
1047 WindowButton::Close => "close",
1048 })
1049 .collect::<Vec<_>>()
1050 .join(",")
1051 }
1052
1053 format!("{}:{}", format_side(&self.left), format_side(&self.right))
1054 }
1055}
1056
1057#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1059pub struct Tiling {
1060 pub top: bool,
1062 pub left: bool,
1064 pub right: bool,
1066 pub bottom: bool,
1068}
1069
1070impl Tiling {
1071 pub fn tiled() -> Self {
1073 Self {
1074 top: true,
1075 left: true,
1076 right: true,
1077 bottom: true,
1078 }
1079 }
1080
1081 pub fn is_tiled(&self) -> bool {
1083 self.top || self.left || self.right || self.bottom
1084 }
1085}
1086
1087pub struct A11yCallbacks {
1089 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1091 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1093 pub deactivation: Box<dyn Fn() + Send + 'static>,
1095}
1096
1097#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1099pub enum FrameRequestSource {
1100 #[default]
1102 NativeCallback,
1103 LocalSchedule,
1105}
1106
1107#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1108#[expect(missing_docs)]
1109pub struct RequestFrameOptions {
1110 pub require_presentation: bool,
1112 pub force_render: bool,
1114 pub signal_at: Option<Instant>,
1120 pub signal_source: FrameRequestSource,
1122}
1123
1124pub struct PlatformFrameSignal {
1133 #[cfg(feature = "profiler")]
1134 origin: Instant,
1135 #[cfg(feature = "profiler")]
1136 first_signal: std::sync::atomic::AtomicU64,
1137}
1138
1139impl Default for PlatformFrameSignal {
1140 fn default() -> Self {
1141 Self::new()
1142 }
1143}
1144
1145impl PlatformFrameSignal {
1146 pub fn new() -> Self {
1148 Self {
1149 #[cfg(feature = "profiler")]
1150 origin: Instant::now(),
1151 #[cfg(feature = "profiler")]
1152 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1153 }
1154 }
1155
1156 #[inline]
1160 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1161 if cfg!(feature = "profiler") {
1162 Some(capture())
1163 } else {
1164 None
1165 }
1166 }
1167
1168 #[inline]
1170 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1171 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1172 #[cfg(feature = "profiler")]
1173 {
1174 let nanoseconds = at
1175 .saturating_duration_since(self.origin)
1176 .as_nanos()
1177 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1178 let source_bit = match source {
1179 FrameRequestSource::NativeCallback => 0,
1180 FrameRequestSource::LocalSchedule => 1,
1181 };
1182 self.first_signal.fetch_min(
1183 (nanoseconds << 1) | source_bit,
1184 std::sync::atomic::Ordering::Relaxed,
1185 );
1186 }
1187 }
1188
1189 #[inline]
1191 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1192 #[cfg(feature = "profiler")]
1193 {
1194 let signal = self
1195 .first_signal
1196 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1197 (signal != u64::MAX).then(|| {
1198 let source = match signal & 1 {
1199 0 => FrameRequestSource::NativeCallback,
1200 _ => FrameRequestSource::LocalSchedule,
1201 };
1202 (self.origin + Duration::from_nanos(signal >> 1), source)
1203 })
1204 }
1205 #[cfg(not(feature = "profiler"))]
1206 {
1207 None
1208 }
1209 }
1210}
1211
1212#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1225pub enum AppLifecyclePhase {
1226 Active,
1228 Inactive,
1230 Background,
1233 Foreground,
1235 Disconnected,
1239}
1240
1241#[derive(Debug, Clone, Default, PartialEq)]
1248pub struct WindowInsets {
1249 pub safe_area: Edges<Pixels>,
1254 pub ime: Edges<Pixels>,
1258 pub corner_radii: Corners<Pixels>,
1263}
1264
1265impl WindowInsets {
1266 pub fn effective(&self) -> Edges<Pixels> {
1268 Edges {
1269 top: self.safe_area.top.max(self.ime.top),
1270 right: self.safe_area.right.max(self.ime.right),
1271 bottom: self.safe_area.bottom.max(self.ime.bottom),
1272 left: self.safe_area.left.max(self.ime.left),
1273 }
1274 }
1275}
1276
1277#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1279pub enum TextInputStateChange {
1280 FocusGained,
1282 FocusLost,
1284 SelectionChanged,
1286 ContentChanged,
1288}
1289
1290#[expect(missing_docs)]
1291pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1292 fn bounds(&self) -> Bounds<Pixels>;
1293 fn is_maximized(&self) -> bool;
1294 fn window_bounds(&self) -> WindowBounds;
1295 fn content_size(&self) -> Size<Pixels>;
1296 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1302 Bounds::new(Point::default(), self.content_size())
1303 }
1304 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1309 fn prepare_frame(&self) -> bool {
1314 false
1315 }
1316 fn resize(&mut self, size: Size<Pixels>);
1317 fn scale_factor(&self) -> f32;
1318 fn appearance(&self) -> WindowAppearance;
1319 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1320 fn mouse_position(&self) -> Point<Pixels>;
1321 fn modifiers(&self) -> Modifiers;
1322 fn capslock(&self) -> Capslock;
1323 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1324 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1325 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1330 fn prompt(
1331 &self,
1332 level: PromptLevel,
1333 msg: &str,
1334 detail: Option<&str>,
1335 answers: &[PromptButton],
1336 ) -> Option<oneshot::Receiver<usize>>;
1337 fn activate(&self);
1338 fn request_attention(&self) {}
1340 fn is_active(&self) -> bool;
1341 fn visibility(&self) -> WindowVisibility;
1344 fn is_hovered(&self) -> bool;
1345 fn background_appearance(&self) -> WindowBackgroundAppearance;
1346 fn set_title(&mut self, title: &str);
1347 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1348 fn minimize(&self);
1349 fn zoom(&self);
1350 fn toggle_fullscreen(&self);
1351 fn is_fullscreen(&self) -> bool;
1352 fn debug_state(&self) -> serde_json::Value {
1354 serde_json::Value::Null
1355 }
1356 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1357 None
1358 }
1359 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1360 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1361 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1362 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1366 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1367 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1368 fn on_moved(&self, callback: Box<dyn FnMut()>);
1369 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1373 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1374 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1375 fn on_close(&self, callback: Box<dyn FnOnce()>);
1376
1377 unsafe fn attach_native_view(
1387 &self,
1388 _id: crate::NativeViewId,
1389 _view: std::ptr::NonNull<std::ffi::c_void>,
1390 ) -> Option<Box<dyn std::any::Any>> {
1391 None
1392 }
1393 fn set_focused_native_view(&self, _id: Option<crate::NativeViewId>) {}
1396 fn on_hit_test_native_view(
1399 &self,
1400 _callback: Box<dyn FnMut(Point<Pixels>) -> Option<crate::NativeViewId>>,
1401 ) {
1402 }
1403 fn on_native_view_focused(&self, _callback: Box<dyn FnMut(crate::NativeViewId)>) {}
1406 fn on_key_down_before_native_view(
1412 &self,
1413 _callback: Box<dyn FnMut(crate::KeyDownEvent) -> bool>,
1414 ) {
1415 }
1416 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1417 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1418 fn draw(&self, scene: &Scene);
1419 fn draw_composed(&self, scene: crate::fast::composition::ComposedScene<'_>) {
1420 crate::fast::composition::draw_uncomposed(self, scene)
1421 }
1422 fn enable_window_composition(&self) -> Result<()> {
1423 crate::fast::composition::unsupported("window composition")
1424 }
1425 fn create_native_surface(
1426 &self,
1427 ) -> Result<Rc<dyn crate::fast::composition::PlatformSurfaceAttachment>> {
1428 crate::fast::composition::unsupported("native surface portals")
1429 }
1430 fn set_composition_order(
1431 &self,
1432 _fast_surfaces: &[crate::fast::composition::PlatformCompositionSurface],
1433 ) -> Result<()> {
1434 crate::fast::composition::unsupported("surface ordering")
1435 }
1436 fn schedule_frame(&self) {}
1437 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1438 fn is_subpixel_rendering_supported(&self) -> bool;
1439
1440 fn get_title(&self) -> String {
1442 String::new()
1443 }
1444 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1445 None
1446 }
1447 fn tab_bar_visible(&self) -> bool {
1448 false
1449 }
1450 fn set_edited(&mut self, _edited: bool) {}
1451 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1452 fn toggle_simple_fullscreen(&self) {}
1453 fn is_simple_fullscreen(&self) -> bool {
1454 false
1455 }
1456 #[cfg(target_os = "macos")]
1457 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1458 #[cfg(target_os = "macos")]
1459 fn set_native_titlebar_visibility(&self, _visible: bool) {}
1460 fn show_character_palette(&self) {}
1461 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1462 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1463 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1464 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1465 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1466 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1467 fn merge_all_windows(&self) {}
1468 fn move_tab_to_new_window(&self) {}
1469 fn toggle_window_tab_overview(&self) {}
1470 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1471
1472 fn native_window_state(&self) -> Option<Vec<u8>> {
1473 None
1474 }
1475 fn restore_native_window_state(&self, _state: &[u8]) {}
1476
1477 #[cfg(target_os = "windows")]
1478 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1479
1480 fn inner_window_bounds(&self) -> WindowBounds {
1482 self.window_bounds()
1483 }
1484 fn request_decorations(&self, _decorations: WindowDecorations) {}
1485 fn show_window_menu(&self, _position: Point<Pixels>) {}
1486 fn start_window_move(&self) {}
1487 fn can_start_external_drag(&self) -> bool {
1488 false
1489 }
1490 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1491 false
1492 }
1493 fn start_window_resize(&self, _edge: ResizeEdge) {}
1494 fn set_exclusive_zone(&self, _zone: Pixels) {}
1495 #[cfg(all(target_os = "linux", feature = "wayland"))]
1496 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1497 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1498 fn window_decorations(&self) -> Decorations {
1499 Decorations::Server
1500 }
1501 fn set_app_id(&mut self, _app_id: &str) {}
1502 fn map_window(&mut self) -> anyhow::Result<()> {
1503 Ok(())
1504 }
1505 fn window_controls(&self) -> WindowControls {
1506 WindowControls::default()
1507 }
1508 fn set_client_inset(&self, _inset: Pixels) {}
1509 fn set_client_corner_radii(&self, _radii: Corners<Pixels>) {}
1510 fn gpu_specs(&self) -> Option<GpuSpecs>;
1511
1512 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1513
1514 fn insets(&self) -> WindowInsets {
1519 WindowInsets::default()
1520 }
1521
1522 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1528
1529 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1532
1533 fn set_back_enabled(&self, _enabled: bool) {}
1536
1537 fn show_soft_keyboard(&self) {}
1539
1540 fn hide_soft_keyboard(&self) {}
1542
1543 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1545
1546 fn play_system_bell(&self) {}
1547
1548 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1550
1551 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1553
1554 fn a11y_update_window_bounds(&self) {}
1556
1557 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1558 fn as_test(&mut self) -> Option<&mut TestWindow> {
1559 None
1560 }
1561
1562 #[cfg(any(test, feature = "test-support"))]
1566 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1567 anyhow::bail!("render_to_image not implemented for this platform")
1568 }
1569}
1570
1571#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1573pub trait PlatformHeadlessRenderer {
1574 fn render_scene_to_image(
1576 &mut self,
1577 scene: &Scene,
1578 size: Size<DevicePixels>,
1579 ) -> Result<RgbaImage>;
1580
1581 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1587
1588 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1590}
1591
1592#[doc(hidden)]
1595pub type RunnableVariant = Runnable<RunnableMeta>;
1596
1597#[doc(hidden)]
1598pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1599
1600#[doc(hidden)]
1601pub enum TasksIncluded {
1602 OnlyCompleted,
1603 CompletedAndRunning,
1604}
1605
1606#[doc(hidden)]
1609pub trait PlatformDispatcher: Send + Sync {
1610 fn is_main_thread(&self) -> bool;
1611 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1612 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1613 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1614
1615 fn dispatch_on_main_thread_when_idle(
1616 &self,
1617 runnable: RunnableVariant,
1618 timeout: Option<Duration>,
1619 ) {
1620 let _ = timeout;
1621 self.dispatch_on_main_thread(runnable, Priority::Low);
1622 }
1623
1624 fn idle_time_remaining(&self) -> Option<Duration> {
1625 None
1626 }
1627
1628 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1629
1630 fn now(&self) -> Instant {
1631 Instant::now()
1632 }
1633
1634 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1635 gpui_util::defer(Box::new(|| {}))
1636 }
1637
1638 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1639 ActivityGuard::noop()
1640 }
1641
1642 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1643 fn as_test(&self) -> Option<&TestDispatcher> {
1644 None
1645 }
1646
1647 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1650 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1651 None
1652 }
1653}
1654
1655#[expect(missing_docs)]
1656pub trait PlatformTextSystem: Send + Sync {
1657 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1658 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1660 fn all_font_names(&self) -> Vec<String>;
1662 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1664 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1666 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1668 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1670 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1672 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1674 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1676 fn rasterize_glyph(
1678 &self,
1679 params: &RenderGlyphParams,
1680 raster_bounds: Bounds<DevicePixels>,
1681 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1682 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1684 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1686 -> TextRenderingMode;
1687 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1689 0
1690 }
1691}
1692
1693#[expect(missing_docs)]
1694pub struct NoopTextSystem;
1695
1696#[expect(missing_docs)]
1697impl NoopTextSystem {
1698 #[allow(dead_code)]
1699 pub fn new() -> Self {
1700 Self
1701 }
1702}
1703
1704impl PlatformTextSystem for NoopTextSystem {
1705 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1706 Ok(())
1707 }
1708
1709 fn all_font_names(&self) -> Vec<String> {
1710 Vec::new()
1711 }
1712
1713 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1714 Ok(FontId(1))
1715 }
1716
1717 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1718 FontMetrics {
1719 units_per_em: 1000,
1720 ascent: 1025.0,
1721 descent: -275.0,
1722 line_gap: 0.0,
1723 underline_position: -95.0,
1724 underline_thickness: 60.0,
1725 cap_height: 698.0,
1726 x_height: 516.0,
1727 bounding_box: Bounds {
1728 origin: Point {
1729 x: -260.0,
1730 y: -245.0,
1731 },
1732 size: Size {
1733 width: 1501.0,
1734 height: 1364.0,
1735 },
1736 },
1737 }
1738 }
1739
1740 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1741 Ok(Bounds {
1742 origin: Point { x: 54.0, y: 0.0 },
1743 size: size(392.0, 528.0),
1744 })
1745 }
1746
1747 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1748 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1749 }
1750
1751 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1752 Some(GlyphId(ch.len_utf16() as u32))
1753 }
1754
1755 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1756 Ok(Default::default())
1757 }
1758
1759 fn rasterize_glyph(
1760 &self,
1761 _params: &RenderGlyphParams,
1762 raster_bounds: Bounds<DevicePixels>,
1763 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1764 Ok((raster_bounds.size, Vec::new()))
1765 }
1766
1767 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1768 let mut position = px(0.);
1769 let metrics = self.font_metrics(FontId(0));
1770 let em_width = font_size
1771 * self
1772 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1773 .unwrap()
1774 .width
1775 / metrics.units_per_em as f32;
1776 let mut glyphs = Vec::new();
1777 for (ix, c) in text.char_indices() {
1778 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1779 glyphs.push(ShapedGlyph {
1780 id: glyph,
1781 position: point(position, px(0.)),
1782 index: ix,
1783 is_emoji: glyph.0 == 2,
1784 });
1785 if glyph.0 == 2 {
1786 position += em_width * 2.0;
1787 } else {
1788 position += em_width;
1789 }
1790 } else {
1791 position += em_width
1792 }
1793 }
1794 let mut runs = Vec::default();
1795 if !glyphs.is_empty() {
1796 runs.push(ShapedRun {
1797 font_id: FontId(0),
1798 glyphs,
1799 });
1800 } else {
1801 position = px(0.);
1802 }
1803
1804 LineLayout {
1805 font_size,
1806 width: position,
1807 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1808 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1809 runs,
1810 len: text.len(),
1811 }
1812 }
1813
1814 fn recommended_rendering_mode(
1815 &self,
1816 _font_id: FontId,
1817 _font_size: Pixels,
1818 ) -> TextRenderingMode {
1819 TextRenderingMode::Grayscale
1820 }
1821}
1822
1823#[allow(dead_code)]
1828pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1829 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1830 [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], ];
1844
1845 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1846 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1847
1848 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1849 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1850
1851 [
1852 ratios[0] * NORM13,
1853 ratios[1] * NORM24,
1854 ratios[2] * NORM13,
1855 ratios[3] * NORM24,
1856 ]
1857}
1858
1859#[derive(PartialEq, Eq, Hash, Clone)]
1860#[expect(missing_docs)]
1861pub enum AtlasKey {
1862 Glyph(RenderGlyphParams),
1863 Svg(RenderSvgParams),
1864 Image(RenderImageParams),
1865}
1866
1867impl AtlasKey {
1868 pub fn texture_kind(&self) -> AtlasTextureKind {
1870 match self {
1871 AtlasKey::Glyph(params) => {
1872 if params.is_emoji {
1873 AtlasTextureKind::Polychrome
1874 } else if params.subpixel_rendering {
1875 AtlasTextureKind::Subpixel
1876 } else {
1877 AtlasTextureKind::Monochrome
1878 }
1879 }
1880 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1881 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1882 }
1883 }
1884}
1885
1886impl From<RenderGlyphParams> for AtlasKey {
1887 fn from(params: RenderGlyphParams) -> Self {
1888 Self::Glyph(params)
1889 }
1890}
1891
1892impl From<RenderSvgParams> for AtlasKey {
1893 fn from(params: RenderSvgParams) -> Self {
1894 Self::Svg(params)
1895 }
1896}
1897
1898impl From<RenderImageParams> for AtlasKey {
1899 fn from(params: RenderImageParams) -> Self {
1900 Self::Image(params)
1901 }
1902}
1903
1904#[expect(missing_docs)]
1905pub trait PlatformAtlas {
1906 fn get_or_insert_with<'a>(
1908 &self,
1909 key: AtlasKey,
1910 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1911 ) -> Result<Option<AtlasTile>>;
1912 fn remove(&self, key: &AtlasKey);
1913
1914 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1915 fn contains(&self, _key: &AtlasKey) -> bool {
1916 false
1917 }
1918}
1919
1920#[doc(hidden)]
1921pub trait AtlasBackend {
1922 fn insert(
1923 &mut self,
1924 kind: AtlasTextureKind,
1925 size: Size<DevicePixels>,
1926 bytes: &[u8],
1927 ) -> Result<AtlasTile>;
1928
1929 fn remove(&mut self, tile: AtlasTile);
1930}
1931
1932#[doc(hidden)]
1933pub struct AtlasState<Backend> {
1934 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
1935 pub backend: Backend,
1936}
1937
1938impl<Backend> AtlasState<Backend> {
1939 pub fn new(backend: Backend) -> Self {
1940 Self {
1941 tiles_by_key: FxHashMap::default(),
1942 backend,
1943 }
1944 }
1945
1946 pub fn contains(&self, key: &AtlasKey) -> bool {
1947 self.tiles_by_key.contains_key(key)
1948 }
1949
1950 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
1951 self.tiles_by_key.clear();
1952 reset_backend(&mut self.backend);
1953 }
1954}
1955
1956impl<Backend: Default> Default for AtlasState<Backend> {
1957 fn default() -> Self {
1958 Self::new(Backend::default())
1959 }
1960}
1961
1962impl<Backend: AtlasBackend> AtlasState<Backend> {
1963 pub fn get_or_insert_with<'a>(
1964 &mut self,
1965 key: AtlasKey,
1966 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1967 ) -> Result<Option<AtlasTile>> {
1968 match self.tiles_by_key.entry(key) {
1969 Entry::Occupied(entry) => Ok(Some(*entry.get())),
1970 Entry::Vacant(entry) => {
1971 profiling::scope!("new tile");
1972 let Some((size, bytes)) = build()? else {
1973 return Ok(None);
1974 };
1975 let tile = self
1976 .backend
1977 .insert(entry.key().texture_kind(), size, &bytes)?;
1978 entry.insert(tile);
1979 Ok(Some(tile))
1980 }
1981 }
1982 }
1983
1984 pub fn remove(&mut self, key: &AtlasKey) {
1985 if let Some(tile) = self.tiles_by_key.remove(key) {
1986 self.backend.remove(tile);
1987 }
1988 }
1989}
1990
1991#[derive(Default)]
1995pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
1996
1997#[doc(hidden)]
1998#[derive(Default)]
1999pub struct HeadlessAtlasBackend {
2000 next_id: u32,
2001}
2002
2003impl AtlasBackend for HeadlessAtlasBackend {
2004 fn insert(
2005 &mut self,
2006 kind: AtlasTextureKind,
2007 size: Size<DevicePixels>,
2008 _bytes: &[u8],
2009 ) -> Result<AtlasTile> {
2010 self.next_id += 1;
2011 let texture_id = self.next_id;
2012 self.next_id += 1;
2013 let tile_id = self.next_id;
2014 Ok(AtlasTile {
2015 texture_id: AtlasTextureId {
2016 index: texture_id,
2017 kind,
2018 },
2019 tile_id: TileId(tile_id),
2020 padding: 0,
2021 bounds: Bounds {
2022 origin: Point::default(),
2023 size,
2024 },
2025 })
2026 }
2027
2028 fn remove(&mut self, _tile: AtlasTile) {}
2029}
2030
2031impl PlatformAtlas for HeadlessAtlas {
2032 fn get_or_insert_with<'a>(
2033 &self,
2034 key: AtlasKey,
2035 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2036 ) -> Result<Option<AtlasTile>> {
2037 self.0.lock().get_or_insert_with(key, build)
2038 }
2039
2040 fn remove(&self, key: &AtlasKey) {
2041 self.0.lock().remove(key);
2042 }
2043
2044 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2045 fn contains(&self, key: &AtlasKey) -> bool {
2046 self.0.lock().contains(key)
2047 }
2048}
2049
2050#[doc(hidden)]
2051pub struct AtlasTextureList<T> {
2052 pub textures: Vec<Option<T>>,
2053 pub free_list: Vec<usize>,
2054}
2055
2056impl<T> Default for AtlasTextureList<T> {
2057 fn default() -> Self {
2058 Self {
2059 textures: Vec::default(),
2060 free_list: Vec::default(),
2061 }
2062 }
2063}
2064
2065impl<T> ops::Index<usize> for AtlasTextureList<T> {
2066 type Output = Option<T>;
2067
2068 fn index(&self, index: usize) -> &Self::Output {
2069 &self.textures[index]
2070 }
2071}
2072
2073impl<T> AtlasTextureList<T> {
2074 #[allow(unused)]
2075 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2076 self.free_list.clear();
2077 self.textures.drain(..)
2078 }
2079
2080 #[allow(dead_code)]
2081 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2082 self.textures.iter_mut().flatten()
2083 }
2084}
2085
2086#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2087#[repr(C)]
2088#[expect(missing_docs)]
2089pub struct AtlasTile {
2090 pub texture_id: AtlasTextureId,
2092 pub tile_id: TileId,
2094 pub padding: u32,
2096 pub bounds: Bounds<DevicePixels>,
2098}
2099
2100#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2101#[repr(C)]
2102#[expect(missing_docs)]
2103pub struct AtlasTextureId {
2104 pub index: u32,
2107 pub kind: AtlasTextureKind,
2109}
2110
2111#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2112#[repr(C)]
2113#[cfg_attr(
2114 all(
2115 any(target_os = "linux", target_os = "freebsd"),
2116 not(any(feature = "x11", feature = "wayland"))
2117 ),
2118 allow(dead_code)
2119)]
2120#[expect(missing_docs)]
2121pub enum AtlasTextureKind {
2122 Monochrome = 0,
2123 Polychrome = 1,
2124 Subpixel = 2,
2125}
2126
2127#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2128#[repr(C)]
2129#[expect(missing_docs)]
2130pub struct TileId(pub u32);
2131
2132impl From<etagere::AllocId> for TileId {
2133 fn from(id: etagere::AllocId) -> Self {
2134 Self(id.serialize())
2135 }
2136}
2137
2138impl From<TileId> for etagere::AllocId {
2139 fn from(id: TileId) -> Self {
2140 Self::deserialize(id.0)
2141 }
2142}
2143
2144#[expect(missing_docs)]
2145pub struct PlatformInputHandler {
2146 cx: AsyncWindowContext,
2147 handler: Box<dyn InputHandler>,
2148 focus_id: Option<crate::FocusId>,
2149}
2150
2151#[expect(missing_docs)]
2152#[cfg_attr(
2153 all(
2154 any(target_os = "linux", target_os = "freebsd"),
2155 not(any(feature = "x11", feature = "wayland"))
2156 ),
2157 allow(dead_code)
2158)]
2159impl PlatformInputHandler {
2160 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2161 Self {
2162 cx,
2163 handler,
2164 focus_id: None,
2165 }
2166 }
2167
2168 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2169 self.focus_id = Some(focus_id);
2170 self
2171 }
2172
2173 pub fn focus_id(&self) -> Option<crate::FocusId> {
2178 self.focus_id
2179 }
2180
2181 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2182 self.cx
2183 .update(|window, cx| {
2184 self.handler
2185 .selected_text_range(ignore_disabled_input, window, cx)
2186 })
2187 .ok()
2188 .flatten()
2189 }
2190
2191 #[cfg_attr(target_os = "windows", allow(dead_code))]
2192 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2193 self.cx
2194 .update(|window, cx| self.handler.marked_text_range(window, cx))
2195 .ok()
2196 .flatten()
2197 }
2198
2199 #[cfg_attr(
2200 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2201 allow(dead_code)
2202 )]
2203 pub fn text_for_range(
2204 &mut self,
2205 range_utf16: Range<usize>,
2206 adjusted: &mut Option<Range<usize>>,
2207 ) -> Option<String> {
2208 self.cx
2209 .update(|window, cx| {
2210 self.handler
2211 .text_for_range(range_utf16, adjusted, window, cx)
2212 })
2213 .ok()
2214 .flatten()
2215 }
2216
2217 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2218 self.cx
2219 .update(|window, cx| {
2220 self.handler
2221 .replace_text_in_range(replacement_range, text, window, cx);
2222 })
2223 .ok();
2224 }
2225
2226 pub fn replace_and_mark_text_in_range(
2227 &mut self,
2228 range_utf16: Option<Range<usize>>,
2229 new_text: &str,
2230 new_selected_range: Option<Range<usize>>,
2231 ) {
2232 self.cx
2233 .update(|window, cx| {
2234 self.handler.replace_and_mark_text_in_range(
2235 range_utf16,
2236 new_text,
2237 new_selected_range,
2238 window,
2239 cx,
2240 )
2241 })
2242 .ok();
2243 }
2244
2245 #[cfg_attr(target_os = "windows", allow(dead_code))]
2246 pub fn unmark_text(&mut self) {
2247 self.cx
2248 .update(|window, cx| self.handler.unmark_text(window, cx))
2249 .ok();
2250 }
2251
2252 pub fn paste(&mut self, item: ClipboardItem) {
2253 self.cx
2254 .update(|window, cx| self.handler.paste(item, window, cx))
2255 .ok();
2256 }
2257
2258 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2259 self.cx
2260 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2261 .ok()
2262 .flatten()
2263 }
2264
2265 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2266 self.cx
2267 .update(|window, cx| {
2268 self.handler
2269 .selection_bounds_for_range(range_utf16, window, cx)
2270 })
2271 .unwrap_or_default()
2272 }
2273
2274 #[allow(dead_code)]
2275 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2276 self.handler.apple_press_and_hold_enabled()
2277 }
2278
2279 pub(crate) fn unmark_text_during_update(&mut self, window: &mut Window, cx: &mut App) {
2282 self.handler.unmark_text(window, cx);
2283 }
2284
2285 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2286 self.handler.replace_text_in_range(None, input, window, cx);
2287 }
2288
2289 pub fn compute_ime_candidate_bounds(
2290 marked_range: Option<Range<usize>>,
2291 selection: &UTF16Selection,
2292 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2293 ) -> Option<Bounds<Pixels>> {
2294 if let Some(marked_range) = marked_range {
2295 let mut line_start = marked_range.start;
2297
2298 let caret = selection.range.end;
2302 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2303 for i in (marked_range.start..caret).rev() {
2304 if let Some(b) = bounds_for_range(i..i) {
2305 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2306 line_start = i + 1;
2307 break;
2308 }
2309 }
2310 }
2311 }
2312 bounds_for_range(line_start..line_start)
2313 } else {
2314 let offset = if selection.reversed {
2316 selection.range.start
2317 } else {
2318 selection.range.end
2319 };
2320 bounds_for_range(offset..offset)
2321 }
2322 }
2323
2324 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2325 let marked_range = self.handler.marked_text_range(window, cx);
2326 let selection = self.handler.selected_text_range(true, window, cx)?;
2327 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2328 self.handler.bounds_for_range(range, window, cx)
2329 })
2330 }
2331
2332 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2333 let marked_range = self.marked_text_range();
2334 let selection = self.selected_text_range(true)?;
2335 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2336 self.bounds_for_range(range)
2337 })
2338 }
2339
2340 #[allow(unused)]
2341 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2342 self.cx
2343 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2344 .ok()
2345 .flatten()
2346 }
2347
2348 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2350 self.cx
2351 .update(|window, cx| {
2352 self.handler
2353 .set_selected_text_range(range_utf16, window, cx)
2354 })
2355 .ok();
2356 }
2357
2358 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2360 self.cx
2361 .update(|window, cx| self.handler.element_bounds(window, cx))
2362 .ok()
2363 .flatten()
2364 }
2365
2366 pub fn text_length_utf16(&mut self) -> Option<usize> {
2368 self.cx
2369 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2370 .ok()
2371 .flatten()
2372 }
2373
2374 #[allow(dead_code)]
2375 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2376 self.handler.accepts_text_input(window, cx)
2377 }
2378
2379 #[allow(dead_code)]
2380 pub fn query_accepts_text_input(&mut self) -> bool {
2381 self.cx
2382 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2383 .unwrap_or(true)
2384 }
2385
2386 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2391 let focus_id = self.focus_id;
2392 self.cx
2393 .update(|window, cx| {
2394 focus_id.is_some()
2395 && window.focus == focus_id
2396 && self.handler.accepts_text_input(window, cx)
2397 })
2398 .unwrap_or(false)
2399 }
2400
2401 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2407 self.cx
2408 .update(|window, cx| {
2409 !window.has_pending_keystrokes()
2411 && self.handler.prefers_ime_for_printable_keys(window, cx)
2412 })
2413 .unwrap_or(false)
2414 }
2415
2416 pub fn text_input_configuration(
2418 &mut self,
2419 window: &mut Window,
2420 cx: &mut App,
2421 ) -> TextInputConfiguration {
2422 self.handler.text_input_configuration(window, cx)
2423 }
2424
2425 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2427 self.cx
2428 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2429 .ok()
2430 .flatten()
2431 }
2432}
2433
2434#[derive(Debug)]
2437pub struct UTF16Selection {
2438 pub range: Range<usize>,
2441 pub reversed: bool,
2444}
2445
2446pub trait InputHandler: 'static {
2451 fn selected_text_range(
2456 &mut self,
2457 ignore_disabled_input: bool,
2458 window: &mut Window,
2459 cx: &mut App,
2460 ) -> Option<UTF16Selection>;
2461
2462 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2467
2468 fn text_for_range(
2473 &mut self,
2474 range_utf16: Range<usize>,
2475 adjusted_range: &mut Option<Range<usize>>,
2476 window: &mut Window,
2477 cx: &mut App,
2478 ) -> Option<String>;
2479
2480 fn replace_text_in_range(
2485 &mut self,
2486 replacement_range: Option<Range<usize>>,
2487 text: &str,
2488 window: &mut Window,
2489 cx: &mut App,
2490 );
2491
2492 fn replace_and_mark_text_in_range(
2499 &mut self,
2500 range_utf16: Option<Range<usize>>,
2501 new_text: &str,
2502 new_selected_range: Option<Range<usize>>,
2503 window: &mut Window,
2504 cx: &mut App,
2505 );
2506
2507 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2510
2511 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2518 if let Some(text) = item.text() {
2519 self.replace_text_in_range(None, &text, window, cx);
2520 }
2521 }
2522
2523 fn bounds_for_range(
2528 &mut self,
2529 range_utf16: Range<usize>,
2530 window: &mut Window,
2531 cx: &mut App,
2532 ) -> Option<Bounds<Pixels>>;
2533
2534 fn selection_bounds_for_range(
2541 &mut self,
2542 _range_utf16: Range<usize>,
2543 _window: &mut Window,
2544 _cx: &mut App,
2545 ) -> Vec<Bounds<Pixels>> {
2546 Vec::new()
2547 }
2548
2549 fn character_index_for_point(
2553 &mut self,
2554 point: Point<Pixels>,
2555 window: &mut Window,
2556 cx: &mut App,
2557 ) -> Option<usize>;
2558
2559 fn set_selected_text_range(
2569 &mut self,
2570 _range_utf16: Range<usize>,
2571 _window: &mut Window,
2572 _cx: &mut App,
2573 ) {
2574 }
2575
2576 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2583 None
2584 }
2585
2586 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2588 None
2589 }
2590
2591 #[allow(dead_code)]
2596 fn apple_press_and_hold_enabled(&mut self) -> bool {
2597 true
2598 }
2599
2600 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2602 true
2603 }
2604
2605 fn text_input_editable_range(
2616 &mut self,
2617 _window: &mut Window,
2618 _cx: &mut App,
2619 ) -> Option<Range<usize>> {
2620 None
2621 }
2622
2623 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2632 false
2633 }
2634
2635 fn text_input_configuration(
2641 &mut self,
2642 _window: &mut Window,
2643 _cx: &mut App,
2644 ) -> TextInputConfiguration {
2645 TextInputConfiguration::default()
2646 }
2647}
2648
2649#[derive(Clone, Debug, Default, PartialEq, Eq)]
2659pub struct TextInputConfiguration {
2660 pub autocorrect: bool,
2662 pub autocapitalize: Autocapitalize,
2664 pub suggestions: bool,
2666 pub input_action: TextInputAction,
2668}
2669
2670#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2672pub enum Autocapitalize {
2673 #[default]
2675 None,
2676 Words,
2678 Sentences,
2680 Characters,
2682}
2683
2684#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2694pub enum TextInputAction {
2695 #[default]
2697 Unspecified,
2698 Enter,
2700 Done,
2702 Go,
2704 Next,
2706 Previous,
2708 Search,
2710 Send,
2712}
2713
2714#[derive(Debug)]
2716pub struct WindowOptions {
2717 pub window_bounds: Option<WindowBounds>,
2721
2722 pub titlebar: Option<TitlebarOptions>,
2724
2725 pub focus: bool,
2727
2728 pub show: bool,
2730
2731 pub kind: WindowKind,
2733
2734 pub is_movable: bool,
2738
2739 pub app_owns_titlebar_drag: bool,
2751
2752 pub inactive_frame_interval: Option<Duration>,
2757
2758 pub low_power_frame_interval: Option<Duration>,
2763
2764 pub thermal_frame_interval: Option<Duration>,
2769
2770 pub is_resizable: bool,
2772
2773 pub is_minimizable: bool,
2775
2776 pub display_id: Option<DisplayId>,
2779
2780 pub window_background: WindowBackgroundAppearance,
2782
2783 pub app_id: Option<String>,
2785
2786 pub window_min_size: Option<Size<Pixels>>,
2788
2789 pub window_decorations: Option<WindowDecorations>,
2792
2793 pub icon: Option<Arc<image::RgbaImage>>,
2795
2796 pub tabbing_identifier: Option<String>,
2798
2799 pub use_display_p3: bool,
2801}
2802
2803#[derive(Debug)]
2805#[cfg_attr(
2806 all(
2807 any(target_os = "linux", target_os = "freebsd"),
2808 not(any(feature = "x11", feature = "wayland"))
2809 ),
2810 allow(dead_code)
2811)]
2812#[allow(missing_docs)]
2813pub struct WindowParams {
2814 pub bounds: Bounds<Pixels>,
2815
2816 #[cfg_attr(feature = "wayland", allow(dead_code))]
2818 pub titlebar: Option<TitlebarOptions>,
2819
2820 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2822 pub kind: WindowKind,
2823
2824 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2826 pub is_movable: bool,
2827
2828 #[cfg_attr(
2830 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2831 allow(dead_code)
2832 )]
2833 pub app_owns_titlebar_drag: bool,
2834
2835 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2837 pub is_resizable: bool,
2838
2839 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2841 pub is_minimizable: bool,
2842
2843 #[cfg_attr(
2844 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2845 allow(dead_code)
2846 )]
2847 pub focus: bool,
2848
2849 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2850 pub show: bool,
2851
2852 #[cfg_attr(feature = "wayland", allow(dead_code))]
2854 pub icon: Option<Arc<image::RgbaImage>>,
2855
2856 #[cfg_attr(feature = "wayland", allow(dead_code))]
2857 pub display_id: Option<DisplayId>,
2858
2859 #[cfg_attr(feature = "wayland", allow(dead_code))]
2860 pub app_id: Option<String>,
2861
2862 pub window_min_size: Option<Size<Pixels>>,
2863
2864 #[cfg(target_os = "macos")]
2865 pub tabbing_identifier: Option<String>,
2866
2867 #[cfg(target_os = "macos")]
2868 pub use_display_p3: bool,
2869}
2870
2871#[derive(Debug, Copy, Clone, PartialEq)]
2873pub enum WindowBounds {
2874 Windowed(Bounds<Pixels>),
2876 Maximized(Bounds<Pixels>),
2879 Fullscreen(Bounds<Pixels>),
2882}
2883
2884impl Default for WindowBounds {
2885 fn default() -> Self {
2886 WindowBounds::Windowed(Bounds::default())
2887 }
2888}
2889
2890impl WindowBounds {
2891 pub fn get_bounds(&self) -> Bounds<Pixels> {
2893 match self {
2894 WindowBounds::Windowed(bounds) => *bounds,
2895 WindowBounds::Maximized(bounds) => *bounds,
2896 WindowBounds::Fullscreen(bounds) => *bounds,
2897 }
2898 }
2899
2900 pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
2903 WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
2904 }
2905}
2906
2907impl Default for WindowOptions {
2908 fn default() -> Self {
2909 Self {
2910 window_bounds: None,
2911 titlebar: Some(TitlebarOptions {
2912 title: Default::default(),
2913 appears_transparent: Default::default(),
2914 traffic_light_position: Default::default(),
2915 }),
2916 focus: true,
2917 show: true,
2918 kind: WindowKind::Normal,
2919 is_movable: true,
2920 app_owns_titlebar_drag: false,
2921 inactive_frame_interval: Some(Duration::from_micros(33_333)),
2922 low_power_frame_interval: Some(Duration::from_micros(33_333)),
2923 thermal_frame_interval: Some(Duration::from_micros(16_667)),
2924 is_resizable: true,
2925 is_minimizable: true,
2926 display_id: None,
2927 window_background: WindowBackgroundAppearance::default(),
2928 icon: None,
2929 app_id: None,
2930 window_min_size: None,
2931 window_decorations: None,
2932 tabbing_identifier: None,
2933 use_display_p3: false,
2934 }
2935 }
2936}
2937
2938#[derive(Debug, Default)]
2940pub struct TitlebarOptions {
2941 pub title: Option<SharedString>,
2943
2944 pub appears_transparent: bool,
2947
2948 pub traffic_light_position: Option<Point<Pixels>>,
2950}
2951
2952#[derive(Clone, Debug, PartialEq, Eq)]
2954pub enum WindowKind {
2955 Normal,
2957
2958 PopUp,
2961
2962 AnchoredPopup(popup::PopupOptions),
2969
2970 Floating,
2972
2973 #[cfg(all(target_os = "linux", feature = "wayland"))]
2976 LayerShell(layer_shell::LayerShellOptions),
2977
2978 Dialog,
2981}
2982
2983#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2988pub enum WindowAppearance {
2989 #[default]
2993 Light,
2994
2995 VibrantLight,
2999
3000 Dark,
3004
3005 VibrantDark,
3009}
3010
3011#[derive(Copy, Clone, Debug, Default, PartialEq)]
3014pub enum WindowBackgroundAppearance {
3015 #[default]
3023 Opaque,
3024 Transparent,
3026 Blurred,
3030 MicaBackdrop,
3032 MicaAltBackdrop,
3034}
3035
3036#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3038pub enum TextRenderingMode {
3039 #[default]
3041 PlatformDefault,
3042 Subpixel,
3044 Grayscale,
3046}
3047
3048#[derive(Clone, Debug)]
3050pub struct PathPromptOptions {
3051 pub files: bool,
3053 pub directories: bool,
3055 pub multiple: bool,
3057 pub prompt: Option<SharedString>,
3059}
3060
3061#[derive(Copy, Clone, Debug, PartialEq)]
3063pub enum PromptLevel {
3064 Info,
3066
3067 Warning,
3069
3070 Critical,
3072}
3073
3074#[derive(Clone, Debug, PartialEq)]
3076pub enum PromptButton {
3077 Ok(SharedString),
3079 Cancel(SharedString),
3081 Other(SharedString),
3083}
3084
3085impl PromptButton {
3086 pub fn new(label: impl Into<SharedString>) -> Self {
3088 PromptButton::Other(label.into())
3089 }
3090
3091 pub fn ok(label: impl Into<SharedString>) -> Self {
3093 PromptButton::Ok(label.into())
3094 }
3095
3096 pub fn cancel(label: impl Into<SharedString>) -> Self {
3098 PromptButton::Cancel(label.into())
3099 }
3100
3101 #[allow(dead_code)]
3103 pub fn is_cancel(&self) -> bool {
3104 matches!(self, PromptButton::Cancel(_))
3105 }
3106
3107 pub fn label(&self) -> &SharedString {
3109 match self {
3110 PromptButton::Ok(label) => label,
3111 PromptButton::Cancel(label) => label,
3112 PromptButton::Other(label) => label,
3113 }
3114 }
3115}
3116
3117impl From<&str> for PromptButton {
3118 fn from(value: &str) -> Self {
3119 match value.to_lowercase().as_str() {
3120 "ok" => PromptButton::Ok("OK".into()),
3121 "cancel" => PromptButton::Cancel("Cancel".into()),
3122 _ => PromptButton::Other(SharedString::from(value.to_owned())),
3123 }
3124 }
3125}
3126
3127#[derive(
3129 Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, EnumIter,
3130)]
3131pub enum CursorStyle {
3132 #[default]
3134 Arrow,
3135
3136 IBeam,
3139
3140 Crosshair,
3143
3144 ClosedHand,
3147
3148 OpenHand,
3151
3152 PointingHand,
3155
3156 ResizeLeft,
3159
3160 ResizeRight,
3163
3164 ResizeLeftRight,
3167
3168 ResizeUp,
3171
3172 ResizeDown,
3175
3176 ResizeUpDown,
3179
3180 ResizeUpLeftDownRight,
3183
3184 ResizeUpRightDownLeft,
3187
3188 ResizeColumn,
3191
3192 ResizeRow,
3195
3196 IBeamCursorForVerticalLayout,
3199
3200 OperationNotAllowed,
3203
3204 DragLink,
3207
3208 DragCopy,
3211
3212 ContextualMenu,
3215}
3216
3217#[derive(Clone, Debug, Eq, PartialEq)]
3219pub struct ClipboardItem {
3220 pub entries: Vec<ClipboardEntry>,
3222}
3223
3224#[derive(Clone, Debug, PartialEq, Eq)]
3229pub enum ClipboardReadError {
3230 Unavailable,
3234 Denied(String),
3237 UnsupportedContent,
3240}
3241
3242impl std::fmt::Display for ClipboardReadError {
3243 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3244 match self {
3245 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3246 Self::Denied(message) => {
3247 write!(formatter, "clipboard access was denied: {message}")
3248 }
3249 Self::UnsupportedContent => {
3250 formatter.write_str("the clipboard contents are unsupported")
3251 }
3252 }
3253 }
3254}
3255
3256impl std::error::Error for ClipboardReadError {}
3257
3258#[derive(Clone, Debug, Eq, PartialEq)]
3260pub enum ClipboardEntry {
3261 String(ClipboardString),
3263 Image(Image),
3265 ExternalPaths(crate::ExternalPaths),
3267}
3268
3269impl ClipboardItem {
3270 pub fn new_string(text: String) -> Self {
3272 Self {
3273 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3274 }
3275 }
3276
3277 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3279 Self {
3280 entries: vec![ClipboardEntry::String(ClipboardString {
3281 text,
3282 metadata: Some(metadata),
3283 })],
3284 }
3285 }
3286
3287 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3289 Self {
3290 entries: vec![ClipboardEntry::String(
3291 ClipboardString::new(text).with_json_metadata(metadata),
3292 )],
3293 }
3294 }
3295
3296 pub fn new_image(image: &Image) -> Self {
3298 Self {
3299 entries: vec![ClipboardEntry::Image(image.clone())],
3300 }
3301 }
3302
3303 pub fn text(&self) -> Option<String> {
3306 let mut answer = String::new();
3307
3308 for entry in self.entries.iter() {
3309 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3310 answer.push_str(text);
3311 }
3312 }
3313
3314 if answer.is_empty() {
3315 for entry in self.entries.iter() {
3316 if let ClipboardEntry::ExternalPaths(paths) = entry {
3317 for path in &paths.0 {
3318 use std::fmt::Write as _;
3319 _ = write!(answer, "{}", path.display());
3320 }
3321 }
3322 }
3323 }
3324
3325 if !answer.is_empty() {
3326 Some(answer)
3327 } else {
3328 None
3329 }
3330 }
3331
3332 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3334 pub fn metadata(&self) -> Option<&String> {
3335 match self.entries().first() {
3336 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3337 clipboard_string.metadata.as_ref()
3338 }
3339 _ => None,
3340 }
3341 }
3342
3343 pub fn entries(&self) -> &[ClipboardEntry] {
3345 &self.entries
3346 }
3347
3348 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3350 self.entries.into_iter()
3351 }
3352}
3353
3354impl From<ClipboardString> for ClipboardEntry {
3355 fn from(value: ClipboardString) -> Self {
3356 Self::String(value)
3357 }
3358}
3359
3360impl From<String> for ClipboardEntry {
3361 fn from(value: String) -> Self {
3362 Self::from(ClipboardString::from(value))
3363 }
3364}
3365
3366impl From<Image> for ClipboardEntry {
3367 fn from(value: Image) -> Self {
3368 Self::Image(value)
3369 }
3370}
3371
3372impl From<ClipboardEntry> for ClipboardItem {
3373 fn from(value: ClipboardEntry) -> Self {
3374 Self {
3375 entries: vec![value],
3376 }
3377 }
3378}
3379
3380impl From<String> for ClipboardItem {
3381 fn from(value: String) -> Self {
3382 Self::from(ClipboardEntry::from(value))
3383 }
3384}
3385
3386impl From<Image> for ClipboardItem {
3387 fn from(value: Image) -> Self {
3388 Self::from(ClipboardEntry::from(value))
3389 }
3390}
3391
3392#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3394pub enum ImageFormat {
3395 Png,
3400 Jpeg,
3402 Webp,
3404 Gif,
3406 Svg,
3408 Bmp,
3410 Tiff,
3412 Ico,
3414 Pnm,
3416}
3417
3418impl ImageFormat {
3419 pub const fn mime_type(self) -> &'static str {
3421 match self {
3422 ImageFormat::Png => "image/png",
3423 ImageFormat::Jpeg => "image/jpeg",
3424 ImageFormat::Webp => "image/webp",
3425 ImageFormat::Gif => "image/gif",
3426 ImageFormat::Svg => "image/svg+xml",
3427 ImageFormat::Bmp => "image/bmp",
3428 ImageFormat::Tiff => "image/tiff",
3429 ImageFormat::Ico => "image/ico",
3430 ImageFormat::Pnm => "image/x-portable-anymap",
3431 }
3432 }
3433
3434 pub const fn extension(self) -> &'static str {
3436 match self {
3437 ImageFormat::Png => "png",
3438 ImageFormat::Jpeg => "jpg",
3439 ImageFormat::Webp => "webp",
3440 ImageFormat::Gif => "gif",
3441 ImageFormat::Svg => "svg",
3442 ImageFormat::Bmp => "bmp",
3443 ImageFormat::Tiff => "tiff",
3444 ImageFormat::Ico => "ico",
3445 ImageFormat::Pnm => "pnm",
3446 }
3447 }
3448
3449 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3451 use strum::IntoEnumIterator;
3452 Self::iter()
3453 .find(|format| format.mime_type() == mime_type)
3454 .or_else(|| Self::from_mime_type_alias(mime_type))
3455 }
3456
3457 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3461 match mime_type {
3462 "image/jpg" => Some(Self::Jpeg),
3463 "image/tif" => Some(Self::Tiff),
3464 _ => None,
3465 }
3466 }
3467}
3468
3469#[derive(Clone, Debug, PartialEq, Eq)]
3471pub struct Image {
3472 pub format: ImageFormat,
3474 pub bytes: Vec<u8>,
3476 pub id: u64,
3478}
3479
3480pub(crate) fn decode_static_image(
3481 bytes: &[u8],
3482 format: image::ImageFormat,
3483) -> Result<SmallVec<[Frame; 1]>> {
3484 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3485 .into_decoder()
3486 .context("creating image decoder")?;
3487 decode_static_image_from_decoder(decoder)
3488}
3489
3490pub(crate) fn decode_static_image_from_decoder(
3491 mut decoder: impl image::ImageDecoder,
3492) -> Result<SmallVec<[Frame; 1]>> {
3493 let orientation = decoder
3494 .orientation()
3495 .context("reading decoder's orientation")?;
3496 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3497 image.apply_orientation(orientation);
3498
3499 let mut data = image.into_rgba8();
3500 for pixel in data.chunks_exact_mut(4) {
3501 pixel.swap(0, 2);
3502 }
3503
3504 Ok(SmallVec::from_elem(Frame::new(data), 1))
3505}
3506
3507fn decode_animated_frames<'a>(
3508 decoder: impl image::AnimationDecoder<'a>,
3509 format_name: &str,
3510) -> Result<SmallVec<[Frame; 1]>> {
3511 let mut frames = SmallVec::new();
3512
3513 for frame in decoder.into_frames() {
3514 match frame {
3515 Ok(mut frame) => {
3516 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3518 pixel.swap(0, 2);
3519 }
3520 frames.push(frame);
3521 }
3522 Err(err) => {
3523 log::debug!("Skipping {format_name} frame due to decode error: {err}");
3524 }
3525 }
3526 }
3527
3528 if frames.is_empty() {
3529 anyhow::bail!("{format_name} could not be decoded: all frames failed");
3530 }
3531
3532 Ok(frames)
3533}
3534
3535pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3536 let decoder = GifDecoder::new(Cursor::new(bytes))?;
3537 decode_animated_frames(decoder, "GIF")
3538}
3539
3540pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
3541 let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
3542
3543 if decoder.has_animation() {
3544 let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
3545 decode_animated_frames(decoder, "WebP")
3546 } else {
3547 decode_static_image_from_decoder(decoder)
3548 }
3549}
3550
3551impl Hash for Image {
3552 fn hash<H: Hasher>(&self, state: &mut H) {
3553 state.write_u64(self.id);
3554 }
3555}
3556
3557impl Image {
3558 pub fn empty() -> Self {
3560 Self::from_bytes(ImageFormat::Png, Vec::new())
3561 }
3562
3563 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3565 Self {
3566 id: hash(&bytes),
3567 format,
3568 bytes,
3569 }
3570 }
3571
3572 pub fn id(&self) -> u64 {
3574 self.id
3575 }
3576
3577 pub fn use_render_image(
3579 self: Arc<Self>,
3580 window: &mut Window,
3581 cx: &mut App,
3582 ) -> Option<Arc<RenderImage>> {
3583 ImageSource::Image(self)
3584 .use_data(None, window, cx)
3585 .and_then(|result| result.ok())
3586 }
3587
3588 pub fn get_render_image(
3590 self: Arc<Self>,
3591 window: &mut Window,
3592 cx: &mut App,
3593 ) -> Option<Arc<RenderImage>> {
3594 ImageSource::Image(self)
3595 .get_data(None, window, cx)
3596 .and_then(|result| result.ok())
3597 }
3598
3599 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3601 ImageSource::Image(self).remove_asset(cx);
3602 }
3603
3604 #[cfg(any(test, feature = "test-support"))]
3607 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
3608 ImageSource::Image(self.clone()).is_asset_cached(cx)
3609 }
3610
3611 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3613 let frames = match self.format {
3614 ImageFormat::Gif => decode_gif_image(&self.bytes)?,
3615 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
3616 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
3617 ImageFormat::Webp => decode_webp_image(&self.bytes)?,
3618 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
3619 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
3620 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
3621 ImageFormat::Svg => {
3622 return svg_renderer
3623 .render_single_frame(&self.bytes, 1.0)
3624 .map_err(Into::into);
3625 }
3626 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
3627 };
3628
3629 Ok(Arc::new(RenderImage::new(frames)))
3630 }
3631
3632 pub fn format(&self) -> ImageFormat {
3634 self.format
3635 }
3636
3637 pub fn bytes(&self) -> &[u8] {
3639 self.bytes.as_slice()
3640 }
3641}
3642
3643#[derive(Clone, Debug, Eq, PartialEq)]
3645pub struct ClipboardString {
3646 pub text: String,
3648 pub metadata: Option<String>,
3650}
3651
3652impl ClipboardString {
3653 pub fn new(text: String) -> Self {
3655 Self {
3656 text,
3657 metadata: None,
3658 }
3659 }
3660
3661 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3664 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
3665 self
3666 }
3667
3668 pub fn text(&self) -> &String {
3670 &self.text
3671 }
3672
3673 pub fn into_text(self) -> String {
3675 self.text
3676 }
3677
3678 pub fn metadata_json<T>(&self) -> Option<T>
3680 where
3681 T: for<'a> Deserialize<'a>,
3682 {
3683 self.metadata
3684 .as_ref()
3685 .and_then(|m| serde_json::from_str(m).ok())
3686 }
3687
3688 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3689 pub fn text_hash(text: &str) -> u64 {
3691 let mut hasher = SeaHasher::new();
3692 text.hash(&mut hasher);
3693 hasher.finish()
3694 }
3695}
3696
3697impl From<String> for ClipboardString {
3698 fn from(value: String) -> Self {
3699 Self {
3700 text: value,
3701 metadata: None,
3702 }
3703 }
3704}
3705
3706#[cfg(test)]
3707mod image_tests {
3708 use super::*;
3709 use std::sync::Arc;
3710
3711 #[test]
3712 fn test_image_to_image_data_applies_exif_orientation() {
3713 let image = Image::from_bytes(
3714 ImageFormat::Jpeg,
3715 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
3716 );
3717
3718 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3719
3720 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
3721
3722 let bytes = render_image.as_bytes(0).unwrap();
3723 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
3724 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
3725 }
3726
3727 #[test]
3728 fn test_svg_image_to_image_data_converts_to_bgra() {
3729 let image = Image::from_bytes(
3730 ImageFormat::Svg,
3731 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3732<rect width="1" height="1" fill="#38BDF8"/>
3733</svg>"##
3734 .to_vec(),
3735 );
3736
3737 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3738 let bytes = render_image.as_bytes(0).unwrap();
3739
3740 for pixel in bytes.chunks_exact(4) {
3741 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3742 }
3743 }
3744
3745 #[test]
3746 fn test_animated_webp_image_to_image_data_decodes_frames() {
3747 const ANIMATED_WEBP: &[u8] = &[
3749 82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
3750 0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
3751 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,
3752 0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
3753 176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
3754 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,
3755 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,
3756 0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
3757 31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
3758 ];
3759
3760 let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
3761 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3762
3763 assert_eq!(render_image.frame_count(), 2);
3764 assert_eq!(render_image.size(0), size(1.into(), 1.into()));
3765 assert_eq!(
3766 Duration::from(render_image.delay(0)),
3767 Duration::from_millis(100)
3768 );
3769 assert_eq!(
3770 Duration::from(render_image.delay(1)),
3771 Duration::from_millis(100)
3772 );
3773 }
3774}
3775
3776#[cfg(test)]
3777mod atlas_tests {
3778 use super::*;
3779
3780 const TILE_SIZE: Size<DevicePixels> = Size {
3781 width: DevicePixels(1),
3782 height: DevicePixels(1),
3783 };
3784
3785 #[derive(Default)]
3786 struct RecordingAtlasBackend {
3787 insert_calls: u32,
3788 fail_next_insert: bool,
3789 removed_tiles: Vec<AtlasTile>,
3790 }
3791
3792 impl AtlasBackend for RecordingAtlasBackend {
3793 fn insert(
3794 &mut self,
3795 kind: AtlasTextureKind,
3796 size: Size<DevicePixels>,
3797 _bytes: &[u8],
3798 ) -> Result<AtlasTile> {
3799 self.insert_calls += 1;
3800 if std::mem::take(&mut self.fail_next_insert) {
3801 anyhow::bail!("backend failed");
3802 }
3803 Ok(AtlasTile {
3804 texture_id: AtlasTextureId { index: 0, kind },
3805 tile_id: TileId(self.insert_calls),
3806 padding: 0,
3807 bounds: Bounds {
3808 origin: Point::default(),
3809 size,
3810 },
3811 })
3812 }
3813
3814 fn remove(&mut self, tile: AtlasTile) {
3815 self.removed_tiles.push(tile);
3816 }
3817 }
3818
3819 fn image_key(image_id: usize) -> AtlasKey {
3820 AtlasKey::Image(RenderImageParams {
3821 image_id: crate::ImageId(image_id),
3822 frame_index: 0,
3823 })
3824 }
3825
3826 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
3827 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
3828 }
3829
3830 #[test]
3831 fn only_successful_inserts_are_cached() -> Result<()> {
3832 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3833 let key = image_key(1);
3834
3835 assert_eq!(
3836 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
3837 None
3838 );
3839 state
3840 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
3841 .expect_err("builder error should propagate");
3842 assert!(!state.contains(&key));
3843 assert_eq!(state.backend.insert_calls, 0);
3844
3845 state.backend.fail_next_insert = true;
3846 state
3847 .get_or_insert_with(key.clone(), &mut build_tile)
3848 .expect_err("backend error should propagate");
3849 assert!(!state.contains(&key));
3850 assert_eq!(state.backend.insert_calls, 1);
3851
3852 let tile = state
3853 .get_or_insert_with(key.clone(), &mut build_tile)?
3854 .context("builder should produce a tile")?;
3855 assert_eq!(tile.texture_id.kind, key.texture_kind());
3856 assert_eq!(
3857 state.get_or_insert_with(key.clone(), &mut || {
3858 anyhow::bail!("cache hit must not call the builder")
3859 })?,
3860 Some(tile)
3861 );
3862 assert!(state.contains(&key));
3863 assert_eq!(state.backend.insert_calls, 2);
3864 Ok(())
3865 }
3866
3867 #[test]
3868 fn remove_and_clear_invalidate_keys() -> Result<()> {
3869 let mut state = AtlasState::new(RecordingAtlasBackend::default());
3870 let key = image_key(1);
3871 let other_key = image_key(2);
3872 let tile = state
3873 .get_or_insert_with(key.clone(), &mut build_tile)?
3874 .context("builder should produce a tile")?;
3875 state
3876 .get_or_insert_with(other_key.clone(), &mut build_tile)?
3877 .context("builder should produce another tile")?;
3878
3879 state.remove(&key);
3880 state.remove(&key);
3881 assert!(!state.contains(&key));
3882 assert!(state.contains(&other_key));
3883 assert_eq!(state.backend.removed_tiles, vec![tile]);
3884
3885 let mut reset_calls = 0;
3886 state.clear(|_| reset_calls += 1);
3887 assert_eq!(reset_calls, 1);
3888 assert!(!state.contains(&other_key));
3889 assert_eq!(state.backend.removed_tiles, vec![tile]);
3890 Ok(())
3891 }
3892}
3893
3894#[cfg(test)]
3895mod frame_signal_tests {
3896 use super::*;
3897
3898 #[cfg(feature = "profiler")]
3899 #[test]
3900 fn coalesced_signals_retain_the_earliest_until_drained() {
3901 for (first_source, later_source) in [
3902 (
3903 FrameRequestSource::NativeCallback,
3904 FrameRequestSource::LocalSchedule,
3905 ),
3906 (
3907 FrameRequestSource::LocalSchedule,
3908 FrameRequestSource::NativeCallback,
3909 ),
3910 ] {
3911 let signal = PlatformFrameSignal::new();
3912 let first =
3913 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
3914 assert_eq!(signal.take(), None);
3915 signal.record(first + Duration::from_millis(16), later_source);
3916 signal.record(first, first_source);
3917 signal.record(first + Duration::from_millis(32), later_source);
3918 assert_eq!(signal.take(), Some((first, first_source)));
3919 assert_eq!(signal.take(), None);
3920 let next = first + Duration::from_millis(48);
3921 signal.record(next, later_source);
3922 assert_eq!(signal.take(), Some((next, later_source)));
3923 }
3924 }
3925
3926 #[cfg(not(feature = "profiler"))]
3927 #[test]
3928 fn disabled_profiling_does_not_capture_or_store_timestamps() {
3929 let captured = PlatformFrameSignal::capture(|| {
3930 panic!("profiler-disabled builds must not evaluate the capture closure");
3931 });
3932 assert_eq!(captured, None);
3933 let signal = PlatformFrameSignal::new();
3934 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
3935 assert_eq!(signal.take(), None);
3936 }
3937}
3938
3939#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3940mod tests {
3941 use super::*;
3942 use std::collections::HashSet;
3943
3944 #[test]
3945 fn test_refresh_interval_from_hz() {
3946 assert_eq!(
3947 refresh_interval_from_hz(50.0),
3948 Some(Duration::from_millis(20))
3949 );
3950 assert_eq!(
3951 refresh_interval_from_hz(120.0),
3952 Some(Duration::from_secs(1) / 120)
3953 );
3954 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
3955 assert_eq!(refresh_interval_from_hz(unknown), None);
3956 }
3957 }
3958
3959 #[test]
3960 fn test_window_button_layout_parse_standard() {
3961 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3962 assert_eq!(
3963 layout.left,
3964 [
3965 Some(WindowButton::Close),
3966 Some(WindowButton::Minimize),
3967 None
3968 ]
3969 );
3970 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3971 }
3972
3973 #[test]
3974 fn test_window_button_layout_parse_right_only() {
3975 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3976 assert_eq!(layout.left, [None, None, None]);
3977 assert_eq!(
3978 layout.right,
3979 [
3980 Some(WindowButton::Minimize),
3981 Some(WindowButton::Maximize),
3982 Some(WindowButton::Close)
3983 ]
3984 );
3985 }
3986
3987 #[test]
3988 fn test_window_button_layout_parse_left_only() {
3989 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3990 assert_eq!(
3991 layout.left,
3992 [
3993 Some(WindowButton::Close),
3994 Some(WindowButton::Minimize),
3995 Some(WindowButton::Maximize)
3996 ]
3997 );
3998 assert_eq!(layout.right, [None, None, None]);
3999 }
4000
4001 #[test]
4002 fn test_window_button_layout_parse_with_whitespace() {
4003 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
4004 assert_eq!(
4005 layout.left,
4006 [
4007 Some(WindowButton::Close),
4008 Some(WindowButton::Minimize),
4009 None
4010 ]
4011 );
4012 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4013 }
4014
4015 #[test]
4016 fn test_window_button_layout_parse_empty() {
4017 let layout = WindowButtonLayout::parse("").unwrap();
4018 assert_eq!(layout.left, [None, None, None]);
4019 assert_eq!(layout.right, [None, None, None]);
4020 }
4021
4022 #[test]
4023 fn test_window_button_layout_parse_intentionally_empty() {
4024 let layout = WindowButtonLayout::parse(":").unwrap();
4025 assert_eq!(layout.left, [None, None, None]);
4026 assert_eq!(layout.right, [None, None, None]);
4027 }
4028
4029 #[test]
4030 fn test_window_button_layout_parse_invalid_buttons() {
4031 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
4032 assert_eq!(
4033 layout.left,
4034 [
4035 Some(WindowButton::Close),
4036 Some(WindowButton::Minimize),
4037 None
4038 ]
4039 );
4040 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4041 }
4042
4043 #[test]
4044 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
4045 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
4046 assert_eq!(
4047 layout.right,
4048 [
4049 Some(WindowButton::Close),
4050 Some(WindowButton::Minimize),
4051 None
4052 ]
4053 );
4054 assert_eq!(layout.format(), ":close,minimize");
4055 }
4056
4057 #[test]
4058 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
4059 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
4060 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4061 assert_eq!(
4062 layout.right,
4063 [
4064 Some(WindowButton::Maximize),
4065 Some(WindowButton::Minimize),
4066 None
4067 ]
4068 );
4069
4070 let button_ids: Vec<_> = layout
4071 .left
4072 .iter()
4073 .chain(layout.right.iter())
4074 .flatten()
4075 .map(WindowButton::id)
4076 .collect();
4077 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4078 assert_eq!(unique_button_ids.len(), button_ids.len());
4079 assert_eq!(layout.format(), "close:maximize,minimize");
4080 }
4081
4082 #[test]
4083 fn test_window_button_layout_parse_gnome_style() {
4084 let layout = WindowButtonLayout::parse("close").unwrap();
4085 assert_eq!(layout.left, [None, None, None]);
4086 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4087 }
4088
4089 #[test]
4090 fn test_window_button_layout_parse_elementary_style() {
4091 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4092 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4093 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4094 }
4095
4096 #[test]
4097 fn test_window_button_layout_round_trip() {
4098 let cases = [
4099 "close:minimize,maximize",
4100 "minimize,maximize,close:",
4101 ":close",
4102 "close:",
4103 "close:maximize",
4104 ":",
4105 ];
4106
4107 for case in cases {
4108 let layout = WindowButtonLayout::parse(case).unwrap();
4109 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4110 }
4111 }
4112
4113 #[test]
4114 fn test_window_button_layout_linux_default() {
4115 let layout = WindowButtonLayout::linux_default();
4116 assert_eq!(layout.left, [None, None, None]);
4117 assert_eq!(
4118 layout.right,
4119 [
4120 Some(WindowButton::Minimize),
4121 Some(WindowButton::Maximize),
4122 Some(WindowButton::Close)
4123 ]
4124 );
4125
4126 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4127 assert_eq!(round_tripped, layout);
4128 }
4129
4130 #[test]
4131 fn test_window_button_layout_parse_all_invalid() {
4132 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4133 }
4134}