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(any(test, feature = "test-support"))]
23#[doc(hidden)]
24pub mod hdr_test_scene;
25
26#[cfg(all(
27 feature = "screen-capture",
28 any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
29))]
30pub mod scap_screen_capture;
31
32#[cfg(all(
33 any(target_os = "windows", target_os = "linux"),
34 feature = "screen-capture"
35))]
36pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
37#[cfg(not(feature = "screen-capture"))]
38pub(crate) type PlatformScreenCaptureFrame = ();
39#[cfg(all(target_os = "macos", feature = "screen-capture"))]
40pub(crate) type PlatformScreenCaptureFrame =
41 objc2_core_foundation::CFRetained<objc2_core_video::CVImageBuffer>;
42
43use crate::{
44 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds, Corners,
45 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
46 FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GlyphShadowParams, GpuSpecs, Hsla,
47 ImageSource, Keymap,
48 LineLayout, MissingGlyphSink, Pixels, PlatformGestures, PlatformInput, Point, Priority,
49 RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph,
50 ShapedRun, SharedString, Size, SvgRenderer, SystemWindowTab, Task, Window, WindowControlArea,
51 hash, point, px, size,
52};
53#[cfg(any(target_os = "linux", target_os = "freebsd"))]
54use anyhow::bail;
55use anyhow::{Context as _, Result};
56use async_task::Runnable;
57use collections::FxHashMap;
58use futures::channel::oneshot;
59use image::RgbaImage;
61use image::codecs::{gif::GifDecoder, webp::WebPDecoder};
62use image::{DynamicImage, Frame, Rgba};
63use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
64use scheduler::Instant;
65pub use scheduler::RunnableMeta;
66#[cfg(feature = "schemars")]
67use schemars::JsonSchema;
68use seahash::SeaHasher;
69use serde::{Deserialize, Serialize};
70use smallvec::SmallVec;
71use std::borrow::Cow;
72use std::collections::hash_map::Entry;
73use std::hash::{Hash, Hasher};
74use std::io::Cursor;
75use std::ops;
76use std::time::Duration;
77use std::{
78 ffi::OsString,
79 fmt::{self, Debug},
80 ops::Range,
81 path::{Path, PathBuf},
82 rc::Rc,
83 sync::Arc,
84};
85use uuid::Uuid;
86
87pub use app_menu::*;
88pub use keyboard::*;
89pub use keystroke::*;
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum WindowVisibility {
113 Visible,
116 Hidden,
119}
120
121impl WindowVisibility {
122 pub fn is_visible(self) -> bool {
124 self == Self::Visible
125 }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
131#[non_exhaustive]
132pub enum DisplayEvent {
133 Added(DisplayId),
135 Removed(DisplayId),
138 Changed {
140 id: DisplayId,
142 changes: DisplayChanges,
144 },
145}
146
147bitflags::bitflags! {
148 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150 pub struct DisplayChanges: u8 {
151 const BOUNDS = 1 << 0;
153 const REFRESH_INTERVAL = 1 << 1;
155 }
156}
157
158pub fn refresh_interval_from_hz(hertz: f64) -> Option<Duration> {
161 (hertz.is_finite() && hertz > 0.0).then(|| Duration::from_secs_f64(1.0 / hertz))
162}
163
164#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
171pub enum ActivationPolicy {
172 #[default]
174 Regular,
175 Accessory,
177}
178
179#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
180pub(crate) use test::*;
181
182#[cfg(any(test, feature = "test-support"))]
183pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
184
185#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
186pub use threaded_dispatcher::ThreadedDispatcher;
187
188#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
189pub use visual_test::VisualTestPlatform;
190
191pub struct ActivityGuard {
193 _release: gpui_util::Deferred<Box<dyn FnOnce() + Send>>,
194}
195
196impl ActivityGuard {
197 pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
199 Self {
200 _release: gpui_util::defer(Box::new(release)),
201 }
202 }
203
204 pub fn noop() -> Self {
206 Self::new(|| {})
207 }
208}
209
210#[cfg(any(target_os = "linux", target_os = "freebsd"))]
214#[inline]
215pub fn guess_compositor() -> &'static str {
216 if std::env::var_os("ZED_HEADLESS").is_some() {
217 return "headless";
218 }
219 GraphicalEnvironment::detect().guess_compositor()
220}
221
222#[cfg(any(target_os = "linux", target_os = "freebsd"))]
231#[derive(Clone, Debug, Default)]
232pub struct GraphicalEnvironment {
233 pub wayland_display: Option<OsString>,
235 pub x11_display: Option<OsString>,
237 pub xdg_runtime_dir: Option<OsString>,
239 pub current_desktop: Option<OsString>,
244 pub activation_token: Option<String>,
250}
251
252#[cfg(target_os = "windows")]
258#[derive(Clone, Debug, Default)]
259pub struct GraphicalEnvironment {
260 pub session_id: Option<u32>,
263}
264
265#[cfg(target_os = "windows")]
266impl GraphicalEnvironment {
267 pub fn detect() -> Self {
269 let mut session_id = 0;
270 let result = unsafe {
272 windows_sys::Win32::System::RemoteDesktop::ProcessIdToSessionId(
273 windows_sys::Win32::System::Threading::GetCurrentProcessId(),
274 &mut session_id,
275 )
276 };
277 Self {
278 session_id: (result != 0).then_some(session_id),
279 }
280 }
281
282 pub fn apply_to(&self, _command: &mut std::process::Command) {}
285
286 pub fn desktop_environment(&self) -> Option<String> {
288 None
289 }
290}
291
292#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
294#[derive(Clone, Debug, Default)]
295pub struct GraphicalEnvironment;
296
297#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
298impl GraphicalEnvironment {
299 pub fn detect() -> Self {
301 Self
302 }
303
304 pub fn apply_to(&self, _command: &mut std::process::Command) {}
306
307 pub fn desktop_environment(&self) -> Option<String> {
309 None
310 }
311}
312
313#[derive(Clone, Debug)]
315pub enum WindowingRequest {
316 Headless,
318 Windowed(GraphicalEnvironment),
320}
321
322#[cfg(any(target_os = "linux", target_os = "freebsd"))]
323impl GraphicalEnvironment {
324 pub fn detect() -> Self {
329 Self {
330 wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
331 x11_display: std::env::var_os("DISPLAY"),
332 xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
333 current_desktop: std::env::var_os("XDG_CURRENT_DESKTOP"),
334 activation_token: None,
335 }
336 }
337
338 pub fn apply_to(&self, command: &mut std::process::Command) {
342 for (name, value) in [
343 ("WAYLAND_DISPLAY", &self.wayland_display),
344 ("DISPLAY", &self.x11_display),
345 ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
346 ] {
347 match value {
348 Some(value) => command.env(name, value),
349 None => command.env_remove(name),
350 };
351 }
352 }
353
354 pub fn desktop_environment(&self) -> Option<String> {
359 self.current_desktop
360 .as_ref()
361 .and_then(|desktop| desktop.to_str())
362 .filter(|desktop| !desktop.is_empty())
363 .map(str::to_owned)
364 }
365
366 pub fn guess_compositor(&self) -> &'static str {
370 let is_set =
371 |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
372 if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
373 "Wayland"
374 } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
375 "X11"
376 } else {
377 "headless"
378 }
379 }
380}
381
382#[cfg(any(target_os = "linux", target_os = "freebsd"))]
383bitflags::bitflags! {
384 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
386 pub struct WindowingModes: u8 {
387 const WAYLAND = 1 << 0;
389 const X11 = 1 << 1;
391 const HEADLESS = 1 << 2;
393 }
394}
395
396pub use platform_info::{OperatingSystem, PlatformInfo, PlatformTarget};
397
398#[expect(missing_docs)]
399pub trait Platform: 'static {
400 fn platform_info(&self) -> PlatformInfo;
402
403 fn background_executor(&self) -> BackgroundExecutor;
404 fn foreground_executor(&self) -> ForegroundExecutor;
405 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
406
407 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
408 fn quit(&self);
409 fn set_initial_windowing(&self, _request: WindowingRequest) {}
414 fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
415 Task::ready(Err(anyhow::anyhow!(
416 "this platform cannot switch between headless and windowed modes"
417 )))
418 }
419 fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
420 fn activate(&self, ignoring_other_apps: bool);
421 fn set_activation_policy(&self, _policy: ActivationPolicy) {}
423 fn hide(&self);
424 fn hide_other_apps(&self);
425 fn unhide_other_apps(&self);
426
427 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
428 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
429 fn on_displays_changed(&self, callback: Box<dyn FnMut()>);
434 fn active_window(&self) -> Option<AnyWindowHandle>;
435 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
436 None
437 }
438
439 fn is_screen_capture_supported(&self) -> bool {
440 false
441 }
442
443 fn screen_capture_sources(
444 &self,
445 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
446 let (sources_tx, sources_rx) = oneshot::channel();
447 sources_tx
448 .send(Err(anyhow::anyhow!(
449 "gpui was compiled without the screen-capture feature"
450 )))
451 .ok();
452 sources_rx
453 }
454
455 fn open_window(
456 &self,
457 handle: AnyWindowHandle,
458 options: WindowParams,
459 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
460
461 fn window_appearance(&self) -> WindowAppearance;
463
464 fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
473
474 fn button_layout(&self) -> Option<WindowButtonLayout> {
476 None
477 }
478
479 fn open_url(&self, url: &str);
480 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
481 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
482
483 fn prompt_for_paths(
484 &self,
485 options: PathPromptOptions,
486 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
487 fn prompt_for_new_path(
488 &self,
489 directory: &Path,
490 suggested_name: Option<&str>,
491 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
492 fn can_select_mixed_files_and_dirs(&self) -> bool;
493 fn reveal_path(&self, path: &Path);
494 fn open_with_system(&self, path: &Path);
495
496 fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
497 fn on_reopen(&self, callback: Box<dyn FnMut()>);
498 fn on_system_sleep(&self, callback: Box<dyn FnMut()>);
500 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
502
503 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
513
514 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
519
520 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
524 None
525 }
526
527 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
528 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
529 None
530 }
531
532 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
533 fn perform_dock_menu_action(&self, _action: usize) {}
534 fn add_recent_document(&self, _path: &Path) {}
535 fn update_jump_list(
536 &self,
537 _menus: Vec<MenuItem>,
538 _entries: Vec<SmallVec<[PathBuf; 2]>>,
539 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
540 Task::ready(Vec::new())
541 }
542 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
543 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
544 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
545
546 fn debug_state(&self) -> serde_json::Value {
548 serde_json::Value::Null
549 }
550
551 fn thermal_state(&self) -> ThermalState;
552 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
553 fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
554
555 fn power_mode(&self) -> PowerMode {
558 PowerMode::Unknown
559 }
560 fn on_power_mode_change(&self, _callback: Box<dyn FnMut()>) {}
562
563 fn set_app_identity(&self, identifier: &str, name: &str) {
570 _ = (identifier, name);
571 }
572
573 fn show_system_notification(&self, notification: SystemNotification) {
580 _ = notification;
581 }
582
583 fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
591 _ = tag;
592 Task::ready(())
593 }
594
595 fn on_system_notification_response(
601 &self,
602 callback: Box<dyn FnMut(SystemNotificationResponse)>,
603 ) {
604 _ = callback;
605 }
606
607 fn compositor_name(&self) -> &'static str {
608 ""
609 }
610 fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
613 None
614 }
615 fn app_path(&self) -> Result<PathBuf>;
616 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
617
618 fn set_cursor_style(&self, style: CursorStyle);
619
620 fn hide_cursor_until_mouse_moves(&self);
623
624 fn is_cursor_visible(&self) -> bool;
626
627 fn should_auto_hide_scrollbars(&self) -> bool;
628
629 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
630 fn write_to_clipboard(&self, item: ClipboardItem);
631
632 fn read_from_clipboard_async(&self) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
640 Task::ready(Ok(self.read_from_clipboard()))
641 }
642
643 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
644 fn read_from_primary(&self) -> Option<ClipboardItem>;
645 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
646 fn write_to_primary(&self, item: ClipboardItem);
647
648 #[cfg(target_os = "macos")]
649 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
650 #[cfg(target_os = "macos")]
651 fn write_to_find_pasteboard(&self, item: ClipboardItem);
652
653 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
654
655 #[cfg(target_os = "macos")]
659 fn write_credentials_if_not_exists(
660 &self,
661 _url: &str,
662 _username: &str,
663 _password: &[u8],
664 ) -> Task<Result<bool>> {
665 Task::ready(Err(anyhow::anyhow!(
666 "this platform does not support atomic credential writes"
667 )))
668 }
669
670 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
671 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
672
673 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
674 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
675 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
676}
677
678pub trait PlatformDisplay: Debug {
680 fn id(&self) -> DisplayId;
682
683 fn uuid(&self) -> Result<Uuid>;
686
687 fn bounds(&self) -> Bounds<Pixels>;
689
690 fn refresh_interval(&self) -> Option<Duration>;
697
698 fn visible_bounds(&self) -> Bounds<Pixels> {
702 self.bounds()
703 }
704
705 fn default_bounds(&self) -> Bounds<Pixels> {
707 let bounds = self.bounds();
708 let center = bounds.center();
709 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
710
711 let offset = clipped_window_size / 2.0;
712 let origin = point(center.x - offset.width, center.y - offset.height);
713 Bounds::new(origin, clipped_window_size)
714 }
715}
716
717#[derive(Clone, Debug, PartialEq, Eq)]
720pub struct SystemNotification {
721 pub tag: SharedString,
725 pub title: SharedString,
727 pub body: SharedString,
729 pub actions: Vec<SystemNotificationAction>,
732}
733
734#[derive(Clone, Debug, PartialEq, Eq, Hash)]
736pub struct SystemNotificationAction {
737 pub id: SharedString,
740 pub label: SharedString,
742}
743
744#[derive(Clone, Debug, PartialEq, Eq)]
746pub struct SystemNotificationResponse {
747 pub tag: SharedString,
749 pub action_id: Option<SharedString>,
752}
753
754#[derive(Debug, Clone, Copy, PartialEq, Eq)]
756pub enum PowerMode {
757 Unknown,
760 LowPower,
762 Balanced,
764 HighPower,
766}
767
768#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770pub enum ThermalState {
771 Nominal,
773 Fair,
775 Serious,
777 Critical,
779}
780
781#[derive(Clone)]
783pub struct SourceMetadata {
784 pub id: u64,
786 pub label: Option<SharedString>,
788 pub is_main: Option<bool>,
790 pub resolution: Size<DevicePixels>,
792}
793
794pub trait ScreenCaptureSource {
796 fn metadata(&self) -> Result<SourceMetadata>;
798
799 fn stream(
802 &self,
803 foreground_executor: &ForegroundExecutor,
804 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
805 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
806}
807
808pub trait ScreenCaptureStream {
810 fn metadata(&self) -> Result<SourceMetadata>;
812}
813
814pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
816
817#[derive(PartialEq, Eq, Hash, Copy, Clone)]
819pub struct DisplayId(pub(crate) u64);
820
821impl DisplayId {
822 pub fn new(id: u64) -> Self {
824 Self(id)
825 }
826}
827
828impl From<u64> for DisplayId {
829 fn from(id: u64) -> Self {
830 Self(id)
831 }
832}
833
834impl From<DisplayId> for u64 {
835 fn from(id: DisplayId) -> Self {
836 id.0
837 }
838}
839
840impl Debug for DisplayId {
841 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
842 write!(f, "DisplayId({})", self.0)
843 }
844}
845
846#[derive(Debug, Clone, Copy, PartialEq, Eq)]
848pub enum ResizeEdge {
849 Top,
851 TopRight,
853 Right,
855 BottomRight,
857 Bottom,
859 BottomLeft,
861 Left,
863 TopLeft,
865}
866
867#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
869pub enum WindowDecorations {
870 #[default]
871 Server,
873 Client,
875}
876
877#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
879pub enum Decorations {
880 #[default]
882 Server,
883 Client {
885 tiling: Tiling,
887 },
888}
889
890#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
892pub struct WindowControls {
893 pub fullscreen: bool,
895 pub maximize: bool,
897 pub minimize: bool,
899 pub window_menu: bool,
901}
902
903impl Default for WindowControls {
904 fn default() -> Self {
905 Self {
907 fullscreen: true,
908 maximize: true,
909 minimize: true,
910 window_menu: true,
911 }
912 }
913}
914
915#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
917pub enum WindowButton {
918 Minimize,
920 Maximize,
922 Close,
924}
925
926impl WindowButton {
927 pub fn id(&self) -> &'static str {
929 match self {
930 WindowButton::Minimize => "minimize",
931 WindowButton::Maximize => "maximize",
932 WindowButton::Close => "close",
933 }
934 }
935
936 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
937 fn index(&self) -> usize {
938 match self {
939 WindowButton::Minimize => 0,
940 WindowButton::Maximize => 1,
941 WindowButton::Close => 2,
942 }
943 }
944}
945
946pub const MAX_BUTTONS_PER_SIDE: usize = 3;
948
949#[derive(Debug, Clone, Copy, PartialEq, Eq)]
954pub struct WindowButtonLayout {
955 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
957 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
959}
960
961#[cfg(any(target_os = "linux", target_os = "freebsd"))]
962impl WindowButtonLayout {
963 pub fn linux_default() -> Self {
965 Self {
966 left: [None; MAX_BUTTONS_PER_SIDE],
967 right: [
968 Some(WindowButton::Minimize),
969 Some(WindowButton::Maximize),
970 Some(WindowButton::Close),
971 ],
972 }
973 }
974
975 pub fn parse(layout_string: &str) -> Result<Self> {
977 fn parse_side(
978 s: &str,
979 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
980 unrecognized: &mut Vec<String>,
981 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
982 let mut result = [None; MAX_BUTTONS_PER_SIDE];
983 let mut i = 0;
984 for name in s.split(',') {
985 let trimmed = name.trim();
986 if trimmed.is_empty() {
987 continue;
988 }
989 let button = match trimmed {
990 "minimize" => Some(WindowButton::Minimize),
991 "maximize" => Some(WindowButton::Maximize),
992 "close" => Some(WindowButton::Close),
993 other => {
994 unrecognized.push(other.to_string());
995 None
996 }
997 };
998 if let Some(button) = button {
999 if seen_buttons[button.index()] {
1000 continue;
1001 }
1002 if let Some(slot) = result.get_mut(i) {
1003 *slot = Some(button);
1004 seen_buttons[button.index()] = true;
1005 i += 1;
1006 }
1007 }
1008 }
1009 result
1010 }
1011
1012 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1013 let mut unrecognized = Vec::new();
1014 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1015 let layout = Self {
1016 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1017 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1018 };
1019
1020 if !unrecognized.is_empty()
1021 && layout.left.iter().all(Option::is_none)
1022 && layout.right.iter().all(Option::is_none)
1023 {
1024 bail!(
1025 "button layout string {:?} contains no valid buttons (unrecognized: {})",
1026 layout_string,
1027 unrecognized.join(", ")
1028 );
1029 }
1030
1031 Ok(layout)
1032 }
1033
1034 #[cfg(test)]
1036 pub fn format(&self) -> String {
1037 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1038 buttons
1039 .iter()
1040 .flatten()
1041 .map(|button| match button {
1042 WindowButton::Minimize => "minimize",
1043 WindowButton::Maximize => "maximize",
1044 WindowButton::Close => "close",
1045 })
1046 .collect::<Vec<_>>()
1047 .join(",")
1048 }
1049
1050 format!("{}:{}", format_side(&self.left), format_side(&self.right))
1051 }
1052}
1053
1054#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1056pub struct Tiling {
1057 pub top: bool,
1059 pub left: bool,
1061 pub right: bool,
1063 pub bottom: bool,
1065}
1066
1067impl Tiling {
1068 pub fn tiled() -> Self {
1070 Self {
1071 top: true,
1072 left: true,
1073 right: true,
1074 bottom: true,
1075 }
1076 }
1077
1078 pub fn is_tiled(&self) -> bool {
1080 self.top || self.left || self.right || self.bottom
1081 }
1082}
1083
1084pub struct A11yCallbacks {
1086 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1088 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1090 pub deactivation: Box<dyn Fn() + Send + 'static>,
1092}
1093
1094#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1096pub enum FrameRequestSource {
1097 #[default]
1099 NativeCallback,
1100 LocalSchedule,
1102}
1103
1104#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1105#[expect(missing_docs)]
1106pub struct RequestFrameOptions {
1107 pub require_presentation: bool,
1109 pub force_render: bool,
1111 pub signal_at: Option<Instant>,
1117 pub signal_source: FrameRequestSource,
1119}
1120
1121pub struct PlatformFrameSignal {
1130 #[cfg(feature = "profiler")]
1131 origin: Instant,
1132 #[cfg(feature = "profiler")]
1133 first_signal: std::sync::atomic::AtomicU64,
1134}
1135
1136impl Default for PlatformFrameSignal {
1137 fn default() -> Self {
1138 Self::new()
1139 }
1140}
1141
1142impl PlatformFrameSignal {
1143 pub fn new() -> Self {
1145 Self {
1146 #[cfg(feature = "profiler")]
1147 origin: Instant::now(),
1148 #[cfg(feature = "profiler")]
1149 first_signal: std::sync::atomic::AtomicU64::new(u64::MAX),
1150 }
1151 }
1152
1153 #[inline]
1157 pub fn capture(capture: impl FnOnce() -> Instant) -> Option<Instant> {
1158 if cfg!(feature = "profiler") {
1159 Some(capture())
1160 } else {
1161 None
1162 }
1163 }
1164
1165 #[inline]
1167 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1168 pub fn record(&self, at: Instant, source: FrameRequestSource) {
1169 #[cfg(feature = "profiler")]
1170 {
1171 let nanoseconds = at
1172 .saturating_duration_since(self.origin)
1173 .as_nanos()
1174 .min(u128::from((u64::MAX >> 1) - 1)) as u64;
1175 let source_bit = match source {
1176 FrameRequestSource::NativeCallback => 0,
1177 FrameRequestSource::LocalSchedule => 1,
1178 };
1179 self.first_signal.fetch_min(
1180 (nanoseconds << 1) | source_bit,
1181 std::sync::atomic::Ordering::Relaxed,
1182 );
1183 }
1184 }
1185
1186 #[inline]
1188 pub fn take(&self) -> Option<(Instant, FrameRequestSource)> {
1189 #[cfg(feature = "profiler")]
1190 {
1191 let signal = self
1192 .first_signal
1193 .swap(u64::MAX, std::sync::atomic::Ordering::Relaxed);
1194 (signal != u64::MAX).then(|| {
1195 let source = match signal & 1 {
1196 0 => FrameRequestSource::NativeCallback,
1197 _ => FrameRequestSource::LocalSchedule,
1198 };
1199 (self.origin + Duration::from_nanos(signal >> 1), source)
1200 })
1201 }
1202 #[cfg(not(feature = "profiler"))]
1203 {
1204 None
1205 }
1206 }
1207}
1208
1209#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1222pub enum AppLifecyclePhase {
1223 Active,
1225 Inactive,
1227 Background,
1230 Foreground,
1232 Disconnected,
1236}
1237
1238#[derive(Debug, Clone, Default, PartialEq)]
1245pub struct WindowInsets {
1246 pub safe_area: Edges<Pixels>,
1251 pub ime: Edges<Pixels>,
1255 pub corner_radii: Corners<Pixels>,
1260}
1261
1262impl WindowInsets {
1263 pub fn effective(&self) -> Edges<Pixels> {
1265 Edges {
1266 top: self.safe_area.top.max(self.ime.top),
1267 right: self.safe_area.right.max(self.ime.right),
1268 bottom: self.safe_area.bottom.max(self.ime.bottom),
1269 left: self.safe_area.left.max(self.ime.left),
1270 }
1271 }
1272}
1273
1274#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
1276pub enum TextInputStateChange {
1277 FocusGained,
1279 FocusLost,
1281 SelectionChanged,
1283 ContentChanged,
1285}
1286
1287#[expect(missing_docs)]
1288pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1289 fn bounds(&self) -> Bounds<Pixels>;
1290 fn is_maximized(&self) -> bool;
1291 fn window_bounds(&self) -> WindowBounds;
1292 fn content_size(&self) -> Size<Pixels>;
1293 fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
1299 Bounds::new(Point::default(), self.content_size())
1300 }
1301 fn on_visual_viewport_changed(&self, _callback: Box<dyn FnMut()>) {}
1306 fn prepare_frame(&self) -> bool {
1311 false
1312 }
1313 fn resize(&mut self, size: Size<Pixels>);
1314 fn scale_factor(&self) -> f32;
1315 fn appearance(&self) -> WindowAppearance;
1316 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1317 fn mouse_position(&self) -> Point<Pixels>;
1318 fn modifiers(&self) -> Modifiers;
1319 fn capslock(&self) -> Capslock;
1320 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1321 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1322 fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
1327 fn prompt(
1328 &self,
1329 level: PromptLevel,
1330 msg: &str,
1331 detail: Option<&str>,
1332 answers: &[PromptButton],
1333 ) -> Option<oneshot::Receiver<usize>>;
1334 fn activate(&self);
1335 fn show_window(
1341 &self,
1342 _activate: bool,
1343 _should_show: Box<dyn FnOnce() -> bool>,
1344 _completed: Box<dyn FnOnce(bool)>,
1345 ) -> bool {
1346 false
1347 }
1348 fn request_attention(&self) {}
1350 fn is_active(&self) -> bool;
1351 fn visibility(&self) -> WindowVisibility;
1354 fn is_hovered(&self) -> bool;
1355 fn background_appearance(&self) -> WindowBackgroundAppearance;
1356 fn set_title(&mut self, title: &str);
1357 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1358 fn is_background_appearance_drawn(&self) -> bool {
1363 true
1364 }
1365 fn minimize(&self);
1366 fn zoom(&self);
1367 fn toggle_fullscreen(&self);
1368 fn is_fullscreen(&self) -> bool;
1369 fn debug_state(&self) -> serde_json::Value {
1371 serde_json::Value::Null
1372 }
1373 fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
1374 None
1375 }
1376 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1377 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1378 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1379 fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
1383 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1384 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1385 fn on_moved(&self, callback: Box<dyn FnMut()>);
1386 fn on_display_changed(&self, callback: Box<dyn FnMut()>);
1390 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1391 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1392 fn on_hit_test_window_control_at(
1395 &self,
1396 mut callback: Box<dyn FnMut(Option<Point<Pixels>>) -> Option<WindowControlArea>>,
1397 ) {
1398 self.on_hit_test_window_control(Box::new(move || callback(None)));
1399 }
1400 fn on_close(&self, callback: Box<dyn FnOnce()>);
1401 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1402 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1403 fn draw(&self, scene: &Scene);
1404 fn schedule_frame(&self) {}
1405 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1406 fn is_subpixel_rendering_supported(&self) -> bool;
1407
1408 fn get_title(&self) -> String {
1410 String::new()
1411 }
1412 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1413 None
1414 }
1415 fn tab_bar_visible(&self) -> bool {
1416 false
1417 }
1418 fn set_edited(&mut self, _edited: bool) {}
1419 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1420 fn toggle_simple_fullscreen(&self) {}
1421 fn is_simple_fullscreen(&self) -> bool {
1422 false
1423 }
1424 #[cfg(target_os = "macos")]
1425 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1426 #[cfg(target_os = "macos")]
1427 fn set_native_titlebar_visibility(&self, _visible: bool) {}
1428 fn show_character_palette(&self) {}
1429 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1430 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1431 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1432 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1433 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1434 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1435 fn merge_all_windows(&self) {}
1436 fn move_tab_to_new_window(&self) {}
1437 fn toggle_window_tab_overview(&self) {}
1438 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1439
1440 fn native_window_state(&self) -> Option<Vec<u8>> {
1441 None
1442 }
1443 fn restore_native_window_state(&self, _state: &[u8]) {}
1444
1445 fn vn_composition_underlay(&self) -> Option<(usize, usize)> {
1450 None
1451 }
1452
1453 fn vn_set_maximized(&self, maximized: bool) {
1455 if self.is_maximized() != maximized {
1456 self.zoom();
1457 }
1458 }
1459 fn vn_is_zoomed(&self) -> bool {
1461 self.is_maximized()
1462 }
1463 fn vn_is_minimized(&self) -> bool {
1465 false
1466 }
1467 fn vn_unminimize(&self) {}
1469 fn vn_hide(&self) -> bool {
1471 false
1472 }
1473 fn vn_is_shown(&self) -> bool {
1475 true
1476 }
1477 fn vn_set_frame(&self, _origin: Option<Point<Pixels>>, _size: Option<Size<Pixels>>) -> bool {
1480 false
1481 }
1482 fn vn_set_always_on_top(&self, _on: bool) -> bool {
1484 false
1485 }
1486 fn vn_set_maximizable(&self, _maximizable: bool) {}
1488 fn vn_set_ignore_mouse(&self, _ignore: bool) -> bool {
1490 false
1491 }
1492 fn vn_set_content_protection(&self, _on: bool) -> bool {
1494 false
1495 }
1496 fn vn_request_close(&self) {}
1499
1500 fn lock_pointer(&self, _unadjusted: bool) -> Result<(), PointerLockError> {
1505 Err(PointerLockError::Unsupported)
1506 }
1507 fn unlock_pointer(&self) {}
1509 fn is_pointer_locked(&self) -> bool {
1511 false
1512 }
1513 fn take_pointer_motion(&self) -> Option<Point<Pixels>> {
1516 None
1517 }
1518 fn set_draws_while_occluded(&self, _on: bool) {}
1520 fn set_hdr_output(&self, _output: Option<HdrOutput>) -> bool {
1523 false
1524 }
1525
1526 fn inner_window_bounds(&self) -> WindowBounds {
1528 self.window_bounds()
1529 }
1530 fn request_decorations(&self, _decorations: WindowDecorations) {}
1531 fn show_window_menu(&self, _position: Point<Pixels>) {}
1532 fn start_window_move(&self) {}
1533 fn can_start_external_drag(&self) -> bool {
1534 false
1535 }
1536 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
1537 false
1538 }
1539 fn start_window_resize(&self, _edge: ResizeEdge) {}
1540 fn set_exclusive_zone(&self, _zone: Pixels) {}
1541 #[cfg(all(target_os = "linux", feature = "wayland"))]
1542 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1543 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1544 fn window_decorations(&self) -> Decorations {
1545 Decorations::Server
1546 }
1547 fn set_app_id(&mut self, _app_id: &str) {}
1548 fn map_window(&mut self) -> anyhow::Result<()> {
1549 Ok(())
1550 }
1551 fn window_controls(&self) -> WindowControls {
1552 WindowControls::default()
1553 }
1554 fn set_client_inset(&self, _inset: Pixels) {}
1555 fn set_client_corner_radii(&self, _radii: Corners<Pixels>) {}
1556 fn gpu_specs(&self) -> Option<GpuSpecs>;
1557
1558 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1559
1560 fn insets(&self) -> WindowInsets {
1565 WindowInsets::default()
1566 }
1567
1568 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
1574
1575 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
1578
1579 fn set_back_enabled(&self, _enabled: bool) {}
1582
1583 fn show_soft_keyboard(&self) {}
1585
1586 fn hide_soft_keyboard(&self) {}
1588
1589 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
1591
1592 fn play_system_bell(&self) {}
1593
1594 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1596
1597 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1599
1600 fn a11y_update_window_bounds(&self) {}
1602
1603 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1604 fn as_test(&mut self) -> Option<&mut TestWindow> {
1605 None
1606 }
1607
1608 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1613 anyhow::bail!("render_to_image not implemented for this platform")
1614 }
1615
1616 fn vn_supports_snapshots(&self) -> bool {
1619 false
1620 }
1621}
1622
1623#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1625pub enum PointerLockError {
1626 Unsupported,
1628 Refused,
1630}
1631
1632#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1634pub trait PlatformHeadlessRenderer {
1635 fn render_scene_to_image(
1637 &mut self,
1638 scene: &Scene,
1639 size: Size<DevicePixels>,
1640 ) -> Result<RgbaImage>;
1641
1642 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1648
1649 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1651}
1652
1653#[doc(hidden)]
1656pub type RunnableVariant = Runnable<RunnableMeta>;
1657
1658#[doc(hidden)]
1659pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1660
1661#[doc(hidden)]
1662pub enum TasksIncluded {
1663 OnlyCompleted,
1664 CompletedAndRunning,
1665}
1666
1667#[doc(hidden)]
1670pub trait PlatformDispatcher: Send + Sync {
1671 fn is_main_thread(&self) -> bool;
1672 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1673 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1674 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1675
1676 fn dispatch_on_main_thread_when_idle(
1677 &self,
1678 runnable: RunnableVariant,
1679 timeout: Option<Duration>,
1680 ) {
1681 let _ = timeout;
1682 self.dispatch_on_main_thread(runnable, Priority::Low);
1683 }
1684
1685 fn idle_time_remaining(&self) -> Option<Duration> {
1686 None
1687 }
1688
1689 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1690
1691 fn now(&self) -> Instant {
1692 Instant::now()
1693 }
1694
1695 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1696 gpui_util::defer(Box::new(|| {}))
1697 }
1698
1699 fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
1700 ActivityGuard::noop()
1701 }
1702
1703 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1704 fn as_test(&self) -> Option<&TestDispatcher> {
1705 None
1706 }
1707
1708 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
1711 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1712 None
1713 }
1714}
1715
1716#[expect(missing_docs)]
1717pub trait PlatformTextSystem: Send + Sync {
1718 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1719 fn set_composed_families(&self, _families: Vec<(SharedString, crate::FamilyComposer)>) {}
1723 fn set_missing_glyph_sink(&self, _sink: Option<Arc<dyn MissingGlyphSink>>) {}
1725 fn all_font_names(&self) -> Vec<String>;
1727 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1729 fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
1731 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1733 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1735 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1737 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1739 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1741 fn rasterize_glyph(
1743 &self,
1744 params: &RenderGlyphParams,
1745 raster_bounds: Bounds<DevicePixels>,
1746 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1747 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1749 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1751 -> TextRenderingMode;
1752 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1754 0
1755 }
1756}
1757
1758#[expect(missing_docs)]
1759pub struct NoopTextSystem;
1760
1761#[expect(missing_docs)]
1762impl NoopTextSystem {
1763 #[allow(dead_code)]
1764 pub fn new() -> Self {
1765 Self
1766 }
1767}
1768
1769impl PlatformTextSystem for NoopTextSystem {
1770 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1771 Ok(())
1772 }
1773
1774 fn all_font_names(&self) -> Vec<String> {
1775 Vec::new()
1776 }
1777
1778 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1779 Ok(FontId(1))
1780 }
1781
1782 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1783 FontMetrics {
1784 units_per_em: 1000,
1785 ascent: 1025.0,
1786 descent: -275.0,
1787 line_gap: 0.0,
1788 underline_position: -95.0,
1789 underline_thickness: 60.0,
1790 cap_height: 698.0,
1791 x_height: 516.0,
1792 bounding_box: Bounds {
1793 origin: Point {
1794 x: -260.0,
1795 y: -245.0,
1796 },
1797 size: Size {
1798 width: 1501.0,
1799 height: 1364.0,
1800 },
1801 },
1802 }
1803 }
1804
1805 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1806 Ok(Bounds {
1807 origin: Point { x: 54.0, y: 0.0 },
1808 size: size(392.0, 528.0),
1809 })
1810 }
1811
1812 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1813 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1814 }
1815
1816 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1817 Some(GlyphId(ch.len_utf16() as u32))
1818 }
1819
1820 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1821 Ok(Default::default())
1822 }
1823
1824 fn rasterize_glyph(
1825 &self,
1826 _params: &RenderGlyphParams,
1827 raster_bounds: Bounds<DevicePixels>,
1828 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1829 Ok((raster_bounds.size, Vec::new()))
1830 }
1831
1832 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1833 let mut position = px(0.);
1834 let metrics = self.font_metrics(FontId(0));
1835 let em_width = font_size
1836 * self
1837 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1838 .unwrap()
1839 .width
1840 / metrics.units_per_em as f32;
1841 let mut glyphs = Vec::new();
1842 for (ix, c) in text.char_indices() {
1843 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1844 glyphs.push(ShapedGlyph {
1845 id: glyph,
1846 position: point(position, px(0.)),
1847 index: ix,
1848 is_emoji: glyph.0 == 2,
1849 });
1850 if glyph.0 == 2 {
1851 position += em_width * 2.0;
1852 } else {
1853 position += em_width;
1854 }
1855 } else {
1856 position += em_width
1857 }
1858 }
1859 let mut runs = Vec::default();
1860 if !glyphs.is_empty() {
1861 runs.push(ShapedRun {
1862 font_id: FontId(0),
1863 glyphs,
1864 });
1865 } else {
1866 position = px(0.);
1867 }
1868
1869 LineLayout {
1870 font_size,
1871 width: position,
1872 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1873 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1874 runs,
1875 len: text.len(),
1876 }
1877 }
1878
1879 fn recommended_rendering_mode(
1880 &self,
1881 _font_id: FontId,
1882 _font_size: Pixels,
1883 ) -> TextRenderingMode {
1884 TextRenderingMode::Grayscale
1885 }
1886}
1887
1888#[allow(dead_code)]
1893pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1894 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1895 [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], ];
1909
1910 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1911 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1912
1913 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1914 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1915
1916 [
1917 ratios[0] * NORM13,
1918 ratios[1] * NORM24,
1919 ratios[2] * NORM13,
1920 ratios[3] * NORM24,
1921 ]
1922}
1923
1924#[derive(PartialEq, Eq, Hash, Clone)]
1925#[expect(missing_docs)]
1926pub enum AtlasKey {
1927 Glyph(RenderGlyphParams),
1928 GlyphShadow(GlyphShadowParams),
1929 Svg(RenderSvgParams),
1930 Image(RenderImageParams),
1931}
1932
1933impl AtlasKey {
1934 pub fn texture_kind(&self) -> AtlasTextureKind {
1936 match self {
1937 AtlasKey::Glyph(params) => {
1938 if params.is_emoji {
1939 AtlasTextureKind::Polychrome
1940 } else if params.subpixel_rendering {
1941 AtlasTextureKind::Subpixel
1942 } else {
1943 AtlasTextureKind::Monochrome
1944 }
1945 }
1946 AtlasKey::GlyphShadow(_) | AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1947 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1948 }
1949 }
1950}
1951
1952impl From<RenderGlyphParams> for AtlasKey {
1953 fn from(params: RenderGlyphParams) -> Self {
1954 Self::Glyph(params)
1955 }
1956}
1957
1958impl From<RenderSvgParams> for AtlasKey {
1959 fn from(params: RenderSvgParams) -> Self {
1960 Self::Svg(params)
1961 }
1962}
1963
1964impl From<RenderImageParams> for AtlasKey {
1965 fn from(params: RenderImageParams) -> Self {
1966 Self::Image(params)
1967 }
1968}
1969
1970#[expect(missing_docs)]
1971pub trait PlatformAtlas {
1972 fn get_or_insert_with<'a>(
1974 &self,
1975 key: AtlasKey,
1976 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1977 ) -> Result<Option<AtlasTile>>;
1978 fn remove(&self, key: &AtlasKey);
1979
1980 fn upload_from_gpu(
2007 &self,
2008 _key: &AtlasKey,
2009 _size: Size<DevicePixels>,
2010 _texture: GpuTextureHandle,
2011 ) -> Result<Option<AtlasTile>> {
2012 Ok(None)
2013 }
2014
2015 fn upload_from_d3d12(
2021 &self,
2022 _key: &AtlasKey,
2023 _size: Size<DevicePixels>,
2024 _texture: D3D12TextureHandle,
2025 _owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2026 ) -> Result<Option<AtlasTile>> {
2027 Ok(None)
2028 }
2029
2030 fn upload_from_metal(
2037 &self,
2038 _key: &AtlasKey,
2039 _size: Size<DevicePixels>,
2040 _texture: GpuTextureHandle,
2041 _ready: Option<(*mut std::ffi::c_void, u64)>,
2042 _owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2043 ) -> Result<Option<AtlasTile>> {
2044 Ok(None)
2045 }
2046
2047 fn tile(&self, _key: &AtlasKey) -> Option<AtlasTile> {
2052 None
2053 }
2054
2055 fn write_bytes(
2063 &self,
2064 _key: &AtlasKey,
2065 _size: Size<DevicePixels>,
2066 _bytes: &[u8],
2067 ) -> Result<Option<AtlasTile>> {
2068 Ok(None)
2069 }
2070
2071 fn write_hdr_bytes(
2075 &self,
2076 _key: &AtlasKey,
2077 _size: Size<DevicePixels>,
2078 _bytes: &[u8],
2079 ) -> Result<Option<AtlasTile>> {
2080 Ok(None)
2081 }
2082
2083 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2084 fn contains(&self, _key: &AtlasKey) -> bool {
2085 false
2086 }
2087
2088 fn stats(&self) -> Option<AtlasStats> {
2092 None
2093 }
2094}
2095
2096#[derive(Clone, Copy, Debug, Default)]
2098pub struct AtlasKindStats {
2099 pub pages: u32,
2101 pub bytes: u64,
2103 pub tiles: u32,
2105 pub tile_pixels: u64,
2108}
2109
2110#[derive(Clone, Copy, Debug, Default)]
2113pub struct AtlasStats {
2114 pub kinds: [AtlasKindStats; 4],
2116 pub keys: u32,
2118 pub image_keys: u32,
2120 pub image_pixels: u64,
2122}
2123
2124#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2133pub struct GpuTextureHandle(pub *mut std::ffi::c_void);
2134
2135#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2138pub struct D3D12TextureHandle {
2139 pub resource: *mut std::ffi::c_void,
2141 pub ready_fence: *mut std::ffi::c_void,
2143 pub ready_value: u64,
2145}
2146
2147#[derive(Clone)]
2151pub struct MetalDeviceLease {
2152 pub device: *mut std::ffi::c_void,
2154 pub queue: *mut std::ffi::c_void,
2156 pub generation: u64,
2158 pub keep_alive: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2160}
2161
2162unsafe impl Send for MetalDeviceLease {}
2164unsafe impl Sync for MetalDeviceLease {}
2165
2166static RENDERER_METAL_DEVICE: std::sync::Mutex<Option<MetalDeviceLease>> =
2167 std::sync::Mutex::new(None);
2168
2169pub fn renderer_metal_device() -> Option<MetalDeviceLease> {
2172 RENDERER_METAL_DEVICE
2173 .lock()
2174 .unwrap_or_else(|p| p.into_inner())
2175 .clone()
2176}
2177
2178#[doc(hidden)]
2181pub fn publish_renderer_metal_device(
2182 device: *mut std::ffi::c_void,
2183 queue: *mut std::ffi::c_void,
2184 keep_alive: std::sync::Arc<dyn std::any::Any + Send + Sync>,
2185) {
2186 let mut published = RENDERER_METAL_DEVICE
2187 .lock()
2188 .unwrap_or_else(|p| p.into_inner());
2189 let generation = match published.as_ref() {
2190 Some(lease) if lease.device == device => return,
2191 Some(lease) => lease.generation + 1,
2192 None => 1,
2193 };
2194 *published = Some(MetalDeviceLease {
2195 device,
2196 queue,
2197 generation,
2198 keep_alive,
2199 });
2200}
2201
2202#[derive(Copy, Clone, Debug, PartialEq)]
2206pub struct HdrOutput {
2207 pub sdr_white: f32,
2210}
2211
2212#[doc(hidden)]
2214pub fn half_to_f32(bits: u16) -> f32 {
2215 let exponent = (bits >> 10) & 0x1f;
2216 let mantissa = u32::from(bits & 0x3ff);
2217 let magnitude = match exponent {
2218 0 => mantissa as f32 / 16_777_216.0,
2219 31 if mantissa == 0 => f32::INFINITY,
2220 31 => f32::NAN,
2221 _ => f32::from_bits(((u32::from(exponent) + 112) << 23) | (mantissa << 13)),
2222 };
2223 if bits & 0x8000 != 0 {
2224 -magnitude
2225 } else {
2226 magnitude
2227 }
2228}
2229
2230#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2233pub enum TileSource {
2234 Bytes,
2238 Gpu(GpuTextureHandle),
2241}
2242
2243#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2245pub enum TileWrite {
2246 InPlace,
2250 Placed,
2254 Refused,
2257}
2258
2259impl GpuTextureHandle {
2260 pub const NULL: Self = Self(std::ptr::null_mut());
2262
2263 pub fn is_null(&self) -> bool {
2265 self.0.is_null()
2266 }
2267}
2268
2269#[doc(hidden)]
2270pub trait AtlasBackend {
2271 fn insert(
2272 &mut self,
2273 kind: AtlasTextureKind,
2274 size: Size<DevicePixels>,
2275 bytes: &[u8],
2276 ) -> Result<AtlasTile>;
2277
2278 fn remove(&mut self, tile: AtlasTile);
2279}
2280
2281#[doc(hidden)]
2282pub struct AtlasState<Backend> {
2283 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
2284 pub backend: Backend,
2285}
2286
2287impl<Backend> AtlasState<Backend> {
2288 pub fn new(backend: Backend) -> Self {
2289 Self {
2290 tiles_by_key: FxHashMap::default(),
2291 backend,
2292 }
2293 }
2294
2295 pub fn contains(&self, key: &AtlasKey) -> bool {
2296 self.tiles_by_key.contains_key(key)
2297 }
2298
2299 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
2300 self.tiles_by_key.clear();
2301 reset_backend(&mut self.backend);
2302 }
2303
2304 pub fn tile(&self, key: &AtlasKey) -> Option<AtlasTile> {
2308 self.tiles_by_key.get(key).copied()
2309 }
2310
2311 pub fn insert_tile(&mut self, key: AtlasKey, tile: AtlasTile) {
2315 self.tiles_by_key.insert(key, tile);
2316 }
2317
2318 pub fn count_keys(&self, stats: &mut AtlasStats) {
2322 stats.keys = self.tiles_by_key.len() as u32;
2323 for (key, tile) in &self.tiles_by_key {
2324 let pixels =
2325 (tile.bounds.size.width.0.max(0) as u64) * (tile.bounds.size.height.0.max(0) as u64);
2326 stats.kinds[tile.texture_id.kind as usize].tile_pixels += pixels;
2327 if let AtlasKey::Image(_) = key {
2328 stats.image_keys += 1;
2329 stats.image_pixels += pixels;
2330 }
2331 }
2332 }
2333}
2334
2335impl<Backend: Default> Default for AtlasState<Backend> {
2336 fn default() -> Self {
2337 Self::new(Backend::default())
2338 }
2339}
2340
2341impl<Backend: AtlasBackend> AtlasState<Backend> {
2342 pub fn get_or_insert_with<'a>(
2343 &mut self,
2344 key: AtlasKey,
2345 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2346 ) -> Result<Option<AtlasTile>> {
2347 match self.tiles_by_key.entry(key) {
2348 Entry::Occupied(entry) => Ok(Some(*entry.get())),
2349 Entry::Vacant(entry) => {
2350 profiling::scope!("new tile");
2351 let Some((size, bytes)) = build()? else {
2352 return Ok(None);
2353 };
2354 let tile = self
2355 .backend
2356 .insert(entry.key().texture_kind(), size, &bytes)?;
2357 entry.insert(tile);
2358 Ok(Some(tile))
2359 }
2360 }
2361 }
2362
2363 pub fn remove(&mut self, key: &AtlasKey) {
2364 if let Some(tile) = self.tiles_by_key.remove(key) {
2365 self.backend.remove(tile);
2366 }
2367 }
2368}
2369
2370#[derive(Default)]
2374pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
2375
2376#[doc(hidden)]
2377#[derive(Default)]
2378pub struct HeadlessAtlasBackend {
2379 next_id: u32,
2380}
2381
2382impl AtlasBackend for HeadlessAtlasBackend {
2383 fn insert(
2384 &mut self,
2385 kind: AtlasTextureKind,
2386 size: Size<DevicePixels>,
2387 _bytes: &[u8],
2388 ) -> Result<AtlasTile> {
2389 self.next_id += 1;
2390 let texture_id = self.next_id;
2391 self.next_id += 1;
2392 let tile_id = self.next_id;
2393 Ok(AtlasTile {
2394 texture_id: AtlasTextureId {
2395 index: texture_id,
2396 kind,
2397 },
2398 tile_id: TileId(tile_id),
2399 padding: 0,
2400 bounds: Bounds {
2401 origin: Point::default(),
2402 size,
2403 },
2404 })
2405 }
2406
2407 fn remove(&mut self, _tile: AtlasTile) {}
2408}
2409
2410impl PlatformAtlas for HeadlessAtlas {
2411 fn get_or_insert_with<'a>(
2412 &self,
2413 key: AtlasKey,
2414 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2415 ) -> Result<Option<AtlasTile>> {
2416 self.0.lock().get_or_insert_with(key, build)
2417 }
2418
2419 fn remove(&self, key: &AtlasKey) {
2420 self.0.lock().remove(key);
2421 }
2422
2423 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2424 fn contains(&self, key: &AtlasKey) -> bool {
2425 self.0.lock().contains(key)
2426 }
2427}
2428
2429#[doc(hidden)]
2430pub struct AtlasTextureList<T> {
2431 pub textures: Vec<Option<T>>,
2432 pub free_list: Vec<usize>,
2433}
2434
2435impl<T> Default for AtlasTextureList<T> {
2436 fn default() -> Self {
2437 Self {
2438 textures: Vec::default(),
2439 free_list: Vec::default(),
2440 }
2441 }
2442}
2443
2444impl<T> ops::Index<usize> for AtlasTextureList<T> {
2445 type Output = Option<T>;
2446
2447 fn index(&self, index: usize) -> &Self::Output {
2448 &self.textures[index]
2449 }
2450}
2451
2452impl<T> AtlasTextureList<T> {
2453 #[allow(unused)]
2454 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2455 self.free_list.clear();
2456 self.textures.drain(..)
2457 }
2458
2459 #[allow(dead_code)]
2460 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2461 self.textures.iter_mut().flatten()
2462 }
2463}
2464
2465#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2466#[repr(C)]
2467#[expect(missing_docs)]
2468pub struct AtlasTile {
2469 pub texture_id: AtlasTextureId,
2471 pub tile_id: TileId,
2473 pub padding: u32,
2475 pub bounds: Bounds<DevicePixels>,
2477}
2478
2479#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2480#[repr(C)]
2481#[expect(missing_docs)]
2482pub struct AtlasTextureId {
2483 pub index: u32,
2486 pub kind: AtlasTextureKind,
2488}
2489
2490#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2491#[repr(C)]
2492#[cfg_attr(
2493 all(
2494 any(target_os = "linux", target_os = "freebsd"),
2495 not(any(feature = "x11", feature = "wayland"))
2496 ),
2497 allow(dead_code)
2498)]
2499#[expect(missing_docs)]
2500pub enum AtlasTextureKind {
2501 Monochrome = 0,
2502 Polychrome = 1,
2503 Subpixel = 2,
2504 PolychromeHdr = 3,
2510}
2511
2512#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2513#[repr(C)]
2514#[expect(missing_docs)]
2515pub struct TileId(pub u32);
2516
2517impl From<etagere::AllocId> for TileId {
2518 fn from(id: etagere::AllocId) -> Self {
2519 Self(id.serialize())
2520 }
2521}
2522
2523impl From<TileId> for etagere::AllocId {
2524 fn from(id: TileId) -> Self {
2525 Self::deserialize(id.0)
2526 }
2527}
2528
2529#[expect(missing_docs)]
2530pub struct PlatformInputHandler {
2531 cx: AsyncWindowContext,
2532 handler: Box<dyn InputHandler>,
2533 focus_id: Option<crate::FocusId>,
2534}
2535
2536#[expect(missing_docs)]
2537#[cfg_attr(
2538 all(
2539 any(target_os = "linux", target_os = "freebsd"),
2540 not(any(feature = "x11", feature = "wayland"))
2541 ),
2542 allow(dead_code)
2543)]
2544impl PlatformInputHandler {
2545 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2546 Self {
2547 cx,
2548 handler,
2549 focus_id: None,
2550 }
2551 }
2552
2553 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2554 self.focus_id = Some(focus_id);
2555 self
2556 }
2557
2558 pub fn focus_id(&self) -> Option<crate::FocusId> {
2563 self.focus_id
2564 }
2565
2566 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2567 self.cx
2568 .update(|window, cx| {
2569 self.handler
2570 .selected_text_range(ignore_disabled_input, window, cx)
2571 })
2572 .ok()
2573 .flatten()
2574 }
2575
2576 #[cfg_attr(target_os = "windows", allow(dead_code))]
2577 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2578 self.cx
2579 .update(|window, cx| self.handler.marked_text_range(window, cx))
2580 .ok()
2581 .flatten()
2582 }
2583
2584 #[cfg_attr(
2585 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2586 allow(dead_code)
2587 )]
2588 pub fn text_for_range(
2589 &mut self,
2590 range_utf16: Range<usize>,
2591 adjusted: &mut Option<Range<usize>>,
2592 ) -> Option<String> {
2593 self.cx
2594 .update(|window, cx| {
2595 self.handler
2596 .text_for_range(range_utf16, adjusted, window, cx)
2597 })
2598 .ok()
2599 .flatten()
2600 }
2601
2602 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2603 self.cx
2604 .update(|window, cx| {
2605 self.handler
2606 .replace_text_in_range(replacement_range, text, window, cx);
2607 })
2608 .ok();
2609 }
2610
2611 pub fn replace_and_mark_text_in_range(
2612 &mut self,
2613 range_utf16: Option<Range<usize>>,
2614 new_text: &str,
2615 new_selected_range: Option<Range<usize>>,
2616 ) {
2617 self.cx
2618 .update(|window, cx| {
2619 self.handler.replace_and_mark_text_in_range(
2620 range_utf16,
2621 new_text,
2622 new_selected_range,
2623 window,
2624 cx,
2625 )
2626 })
2627 .ok();
2628 }
2629
2630 #[cfg_attr(target_os = "windows", allow(dead_code))]
2631 pub fn unmark_text(&mut self) {
2632 self.cx
2633 .update(|window, cx| self.handler.unmark_text(window, cx))
2634 .ok();
2635 }
2636
2637 pub fn paste(&mut self, item: ClipboardItem) {
2638 self.cx
2639 .update(|window, cx| self.handler.paste(item, window, cx))
2640 .ok();
2641 }
2642
2643 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2644 self.cx
2645 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2646 .ok()
2647 .flatten()
2648 }
2649
2650 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2651 self.cx
2652 .update(|window, cx| {
2653 self.handler
2654 .selection_bounds_for_range(range_utf16, window, cx)
2655 })
2656 .unwrap_or_default()
2657 }
2658
2659 #[allow(dead_code)]
2660 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2661 self.handler.apple_press_and_hold_enabled()
2662 }
2663
2664 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2665 self.handler.replace_text_in_range(None, input, window, cx);
2666 }
2667
2668 pub fn compute_ime_candidate_bounds(
2669 marked_range: Option<Range<usize>>,
2670 selection: &UTF16Selection,
2671 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2672 ) -> Option<Bounds<Pixels>> {
2673 if let Some(marked_range) = marked_range {
2674 let mut line_start = marked_range.start;
2676
2677 let caret = selection.range.end;
2681 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2682 for i in (marked_range.start..caret).rev() {
2683 if let Some(b) = bounds_for_range(i..i) {
2684 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2685 line_start = i + 1;
2686 break;
2687 }
2688 }
2689 }
2690 }
2691 bounds_for_range(line_start..line_start)
2692 } else {
2693 let offset = if selection.reversed {
2695 selection.range.start
2696 } else {
2697 selection.range.end
2698 };
2699 bounds_for_range(offset..offset)
2700 }
2701 }
2702
2703 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2704 let marked_range = self.handler.marked_text_range(window, cx);
2705 let selection = self.handler.selected_text_range(true, window, cx)?;
2706 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2707 self.handler.bounds_for_range(range, window, cx)
2708 })
2709 }
2710
2711 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2712 let marked_range = self.marked_text_range();
2713 let selection = self.selected_text_range(true)?;
2714 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2715 self.bounds_for_range(range)
2716 })
2717 }
2718
2719 #[allow(unused)]
2720 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2721 self.cx
2722 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2723 .ok()
2724 .flatten()
2725 }
2726
2727 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2729 self.cx
2730 .update(|window, cx| {
2731 self.handler
2732 .set_selected_text_range(range_utf16, window, cx)
2733 })
2734 .ok();
2735 }
2736
2737 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2739 self.cx
2740 .update(|window, cx| self.handler.element_bounds(window, cx))
2741 .ok()
2742 .flatten()
2743 }
2744
2745 pub fn text_length_utf16(&mut self) -> Option<usize> {
2747 self.cx
2748 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2749 .ok()
2750 .flatten()
2751 }
2752
2753 #[allow(dead_code)]
2754 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2755 self.handler.accepts_text_input(window, cx)
2756 }
2757
2758 #[allow(dead_code)]
2759 pub fn query_accepts_text_input(&mut self) -> bool {
2760 self.cx
2761 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2762 .unwrap_or(true)
2763 }
2764
2765 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2770 let focus_id = self.focus_id;
2771 self.cx
2772 .update(|window, cx| {
2773 focus_id.is_some()
2774 && window.focus == focus_id
2775 && self.handler.accepts_text_input(window, cx)
2776 })
2777 .unwrap_or(false)
2778 }
2779
2780 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2786 self.cx
2787 .update(|window, cx| {
2788 !window.has_pending_keystrokes()
2790 && self.handler.prefers_ime_for_printable_keys(window, cx)
2791 })
2792 .unwrap_or(false)
2793 }
2794
2795 pub fn text_input_configuration(
2797 &mut self,
2798 window: &mut Window,
2799 cx: &mut App,
2800 ) -> TextInputConfiguration {
2801 self.handler.text_input_configuration(window, cx)
2802 }
2803
2804 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2806 self.cx
2807 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2808 .ok()
2809 .flatten()
2810 }
2811}
2812
2813#[derive(Debug)]
2816pub struct UTF16Selection {
2817 pub range: Range<usize>,
2820 pub reversed: bool,
2823}
2824
2825pub trait InputHandler: 'static {
2830 fn selected_text_range(
2835 &mut self,
2836 ignore_disabled_input: bool,
2837 window: &mut Window,
2838 cx: &mut App,
2839 ) -> Option<UTF16Selection>;
2840
2841 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2846
2847 fn text_for_range(
2852 &mut self,
2853 range_utf16: Range<usize>,
2854 adjusted_range: &mut Option<Range<usize>>,
2855 window: &mut Window,
2856 cx: &mut App,
2857 ) -> Option<String>;
2858
2859 fn replace_text_in_range(
2864 &mut self,
2865 replacement_range: Option<Range<usize>>,
2866 text: &str,
2867 window: &mut Window,
2868 cx: &mut App,
2869 );
2870
2871 fn replace_and_mark_text_in_range(
2878 &mut self,
2879 range_utf16: Option<Range<usize>>,
2880 new_text: &str,
2881 new_selected_range: Option<Range<usize>>,
2882 window: &mut Window,
2883 cx: &mut App,
2884 );
2885
2886 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2889
2890 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2897 if let Some(text) = item.text() {
2898 self.replace_text_in_range(None, &text, window, cx);
2899 }
2900 }
2901
2902 fn bounds_for_range(
2907 &mut self,
2908 range_utf16: Range<usize>,
2909 window: &mut Window,
2910 cx: &mut App,
2911 ) -> Option<Bounds<Pixels>>;
2912
2913 fn selection_bounds_for_range(
2920 &mut self,
2921 _range_utf16: Range<usize>,
2922 _window: &mut Window,
2923 _cx: &mut App,
2924 ) -> Vec<Bounds<Pixels>> {
2925 Vec::new()
2926 }
2927
2928 fn character_index_for_point(
2932 &mut self,
2933 point: Point<Pixels>,
2934 window: &mut Window,
2935 cx: &mut App,
2936 ) -> Option<usize>;
2937
2938 fn set_selected_text_range(
2948 &mut self,
2949 _range_utf16: Range<usize>,
2950 _window: &mut Window,
2951 _cx: &mut App,
2952 ) {
2953 }
2954
2955 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2962 None
2963 }
2964
2965 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2967 None
2968 }
2969
2970 #[allow(dead_code)]
2975 fn apple_press_and_hold_enabled(&mut self) -> bool {
2976 true
2977 }
2978
2979 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2981 true
2982 }
2983
2984 fn text_input_editable_range(
2995 &mut self,
2996 _window: &mut Window,
2997 _cx: &mut App,
2998 ) -> Option<Range<usize>> {
2999 None
3000 }
3001
3002 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
3011 false
3012 }
3013
3014 fn text_input_configuration(
3020 &mut self,
3021 _window: &mut Window,
3022 _cx: &mut App,
3023 ) -> TextInputConfiguration {
3024 TextInputConfiguration::default()
3025 }
3026}
3027
3028#[derive(Clone, Debug, Default, PartialEq, Eq)]
3038pub struct TextInputConfiguration {
3039 pub autocorrect: bool,
3041 pub autocapitalize: Autocapitalize,
3043 pub suggestions: bool,
3045 pub input_action: TextInputAction,
3047}
3048
3049#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3051pub enum Autocapitalize {
3052 #[default]
3054 None,
3055 Words,
3057 Sentences,
3059 Characters,
3061}
3062
3063#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3073pub enum TextInputAction {
3074 #[default]
3076 Unspecified,
3077 Enter,
3079 Done,
3081 Go,
3083 Next,
3085 Previous,
3087 Search,
3089 Send,
3091}
3092
3093#[derive(Debug)]
3095pub struct WindowOptions {
3096 pub window_bounds: Option<WindowBounds>,
3100
3101 pub titlebar: Option<TitlebarOptions>,
3103
3104 pub focus: bool,
3106
3107 pub show: bool,
3109
3110 pub kind: WindowKind,
3112
3113 pub is_movable: bool,
3117
3118 pub app_owns_titlebar_drag: bool,
3130
3131 pub inactive_frame_interval: Option<Duration>,
3136
3137 pub low_power_frame_interval: Option<Duration>,
3142
3143 pub thermal_frame_interval: Option<Duration>,
3148
3149 pub is_resizable: bool,
3151
3152 pub is_minimizable: bool,
3154
3155 pub display_id: Option<DisplayId>,
3158
3159 pub window_background: WindowBackgroundAppearance,
3161
3162 pub app_id: Option<String>,
3164
3165 pub window_min_size: Option<Size<Pixels>>,
3167
3168 pub window_decorations: Option<WindowDecorations>,
3171
3172 pub icon: Option<Arc<image::RgbaImage>>,
3174
3175 pub tabbing_identifier: Option<String>,
3177
3178 pub use_display_p3: bool,
3180}
3181
3182#[derive(Debug)]
3184#[cfg_attr(
3185 all(
3186 any(target_os = "linux", target_os = "freebsd"),
3187 not(any(feature = "x11", feature = "wayland"))
3188 ),
3189 allow(dead_code)
3190)]
3191#[allow(missing_docs)]
3192pub struct WindowParams {
3193 pub bounds: Bounds<Pixels>,
3194
3195 #[cfg_attr(feature = "wayland", allow(dead_code))]
3197 pub titlebar: Option<TitlebarOptions>,
3198
3199 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3201 pub kind: WindowKind,
3202
3203 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3205 pub is_movable: bool,
3206
3207 #[cfg_attr(
3209 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3210 allow(dead_code)
3211 )]
3212 pub app_owns_titlebar_drag: bool,
3213
3214 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3216 pub is_resizable: bool,
3217
3218 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3220 pub is_minimizable: bool,
3221
3222 #[cfg_attr(
3223 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3224 allow(dead_code)
3225 )]
3226 pub focus: bool,
3227
3228 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3229 pub show: bool,
3230
3231 #[cfg_attr(feature = "wayland", allow(dead_code))]
3233 pub icon: Option<Arc<image::RgbaImage>>,
3234
3235 #[cfg_attr(feature = "wayland", allow(dead_code))]
3236 pub display_id: Option<DisplayId>,
3237
3238 #[cfg_attr(feature = "wayland", allow(dead_code))]
3239 pub app_id: Option<String>,
3240
3241 pub window_min_size: Option<Size<Pixels>>,
3242
3243 #[cfg(target_os = "macos")]
3244 pub tabbing_identifier: Option<String>,
3245
3246 #[cfg(target_os = "macos")]
3247 pub use_display_p3: bool,
3248}
3249
3250#[derive(Debug, Copy, Clone, PartialEq)]
3252pub enum WindowBounds {
3253 Windowed(Bounds<Pixels>),
3255 Maximized(Bounds<Pixels>),
3258 Fullscreen(Bounds<Pixels>),
3261}
3262
3263impl Default for WindowBounds {
3264 fn default() -> Self {
3265 WindowBounds::Windowed(Bounds::default())
3266 }
3267}
3268
3269impl WindowBounds {
3270 pub fn get_bounds(&self) -> Bounds<Pixels> {
3272 match self {
3273 WindowBounds::Windowed(bounds) => *bounds,
3274 WindowBounds::Maximized(bounds) => *bounds,
3275 WindowBounds::Fullscreen(bounds) => *bounds,
3276 }
3277 }
3278
3279 pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
3282 WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
3283 }
3284}
3285
3286impl Default for WindowOptions {
3287 fn default() -> Self {
3288 Self {
3289 window_bounds: None,
3290 titlebar: Some(TitlebarOptions {
3291 title: Default::default(),
3292 appears_transparent: Default::default(),
3293 traffic_light_position: Default::default(),
3294 }),
3295 focus: true,
3296 show: true,
3297 kind: WindowKind::Normal,
3298 is_movable: true,
3299 app_owns_titlebar_drag: false,
3300 inactive_frame_interval: Some(Duration::from_micros(33_333)),
3301 low_power_frame_interval: Some(Duration::from_micros(33_333)),
3302 thermal_frame_interval: Some(Duration::from_micros(16_667)),
3303 is_resizable: true,
3304 is_minimizable: true,
3305 display_id: None,
3306 window_background: WindowBackgroundAppearance::default(),
3307 icon: None,
3308 app_id: None,
3309 window_min_size: None,
3310 window_decorations: None,
3311 tabbing_identifier: None,
3312 use_display_p3: false,
3313 }
3314 }
3315}
3316
3317#[derive(Debug, Default)]
3319pub struct TitlebarOptions {
3320 pub title: Option<SharedString>,
3322
3323 pub appears_transparent: bool,
3326
3327 pub traffic_light_position: Option<Point<Pixels>>,
3329}
3330
3331#[derive(Clone, Debug, PartialEq, Eq)]
3333pub enum WindowKind {
3334 Normal,
3336
3337 PopUp,
3340
3341 AnchoredPopup(popup::PopupOptions),
3348
3349 Floating,
3351
3352 #[cfg(all(target_os = "linux", feature = "wayland"))]
3355 LayerShell(layer_shell::LayerShellOptions),
3356
3357 Dialog,
3360}
3361
3362#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3367pub enum WindowAppearance {
3368 #[default]
3372 Light,
3373
3374 VibrantLight,
3378
3379 Dark,
3383
3384 VibrantDark,
3388}
3389
3390#[derive(Copy, Clone, Debug, Default, PartialEq)]
3393pub enum WindowBackgroundAppearance {
3394 #[default]
3402 Opaque,
3403 Transparent,
3405 Blurred,
3409 MicaBackdrop,
3411 MicaAltBackdrop,
3413 AcrylicBackdrop,
3416}
3417
3418#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3420pub enum TextRenderingMode {
3421 #[default]
3423 PlatformDefault,
3424 Subpixel,
3426 Grayscale,
3428}
3429
3430#[derive(Clone, Debug)]
3432pub struct PathPromptOptions {
3433 pub files: bool,
3435 pub directories: bool,
3437 pub multiple: bool,
3439 pub prompt: Option<SharedString>,
3441}
3442
3443#[derive(Copy, Clone, Debug, PartialEq)]
3445pub enum PromptLevel {
3446 Info,
3448
3449 Warning,
3451
3452 Critical,
3454}
3455
3456#[derive(Clone, Debug, PartialEq)]
3458pub enum PromptButton {
3459 Ok(SharedString),
3461 Cancel(SharedString),
3463 Other(SharedString),
3465}
3466
3467impl PromptButton {
3468 pub fn new(label: impl Into<SharedString>) -> Self {
3470 PromptButton::Other(label.into())
3471 }
3472
3473 pub fn ok(label: impl Into<SharedString>) -> Self {
3475 PromptButton::Ok(label.into())
3476 }
3477
3478 pub fn cancel(label: impl Into<SharedString>) -> Self {
3480 PromptButton::Cancel(label.into())
3481 }
3482
3483 #[allow(dead_code)]
3485 pub fn is_cancel(&self) -> bool {
3486 matches!(self, PromptButton::Cancel(_))
3487 }
3488
3489 pub fn label(&self) -> &SharedString {
3491 match self {
3492 PromptButton::Ok(label) => label,
3493 PromptButton::Cancel(label) => label,
3494 PromptButton::Other(label) => label,
3495 }
3496 }
3497}
3498
3499impl From<&str> for PromptButton {
3500 fn from(value: &str) -> Self {
3501 match value.to_lowercase().as_str() {
3502 "ok" => PromptButton::Ok("OK".into()),
3503 "cancel" => PromptButton::Cancel("Cancel".into()),
3504 _ => PromptButton::Other(SharedString::from(value.to_owned())),
3505 }
3506 }
3507}
3508
3509#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
3511#[cfg_attr(feature = "schemars", derive(JsonSchema))]
3512pub enum CursorStyle {
3513 #[default]
3515 Arrow,
3516
3517 IBeam,
3520
3521 Crosshair,
3524
3525 ClosedHand,
3528
3529 OpenHand,
3532
3533 PointingHand,
3536
3537 ResizeLeft,
3540
3541 ResizeRight,
3544
3545 ResizeLeftRight,
3548
3549 ResizeUp,
3552
3553 ResizeDown,
3556
3557 ResizeUpDown,
3560
3561 ResizeUpLeftDownRight,
3564
3565 ResizeUpRightDownLeft,
3568
3569 ResizeColumn,
3572
3573 ResizeRow,
3576
3577 IBeamCursorForVerticalLayout,
3580
3581 OperationNotAllowed,
3584
3585 DragLink,
3588
3589 DragCopy,
3592
3593 ContextualMenu,
3596
3597 Help,
3599
3600 Progress,
3603
3604 Wait,
3606
3607 Move,
3609
3610 AllScroll,
3612
3613 Cell,
3615
3616 ZoomIn,
3618
3619 ZoomOut,
3621
3622 NoDrop,
3624
3625 Hidden,
3628}
3629
3630impl CursorStyle {
3631 pub const ALL: [Self; 31] = [
3633 Self::Arrow,
3634 Self::IBeam,
3635 Self::Crosshair,
3636 Self::ClosedHand,
3637 Self::OpenHand,
3638 Self::PointingHand,
3639 Self::ResizeLeft,
3640 Self::ResizeRight,
3641 Self::ResizeLeftRight,
3642 Self::ResizeUp,
3643 Self::ResizeDown,
3644 Self::ResizeUpDown,
3645 Self::ResizeUpLeftDownRight,
3646 Self::ResizeUpRightDownLeft,
3647 Self::ResizeColumn,
3648 Self::ResizeRow,
3649 Self::IBeamCursorForVerticalLayout,
3650 Self::OperationNotAllowed,
3651 Self::DragLink,
3652 Self::DragCopy,
3653 Self::ContextualMenu,
3654 Self::Help,
3655 Self::Progress,
3656 Self::Wait,
3657 Self::Move,
3658 Self::AllScroll,
3659 Self::Cell,
3660 Self::ZoomIn,
3661 Self::ZoomOut,
3662 Self::NoDrop,
3663 Self::Hidden,
3664 ];
3665
3666 pub fn iter() -> impl Iterator<Item = Self> {
3668 Self::ALL.into_iter()
3669 }
3670}
3671
3672#[derive(Clone, Debug, Eq, PartialEq)]
3674pub struct ClipboardItem {
3675 pub entries: Vec<ClipboardEntry>,
3677}
3678
3679#[derive(Clone, Debug, PartialEq, Eq)]
3684pub enum ClipboardReadError {
3685 Unavailable,
3689 Denied(String),
3692 UnsupportedContent,
3695}
3696
3697impl std::fmt::Display for ClipboardReadError {
3698 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3699 match self {
3700 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3701 Self::Denied(message) => {
3702 write!(formatter, "clipboard access was denied: {message}")
3703 }
3704 Self::UnsupportedContent => {
3705 formatter.write_str("the clipboard contents are unsupported")
3706 }
3707 }
3708 }
3709}
3710
3711impl std::error::Error for ClipboardReadError {}
3712
3713#[derive(Clone, Debug, Eq, PartialEq)]
3715pub enum ClipboardEntry {
3716 String(ClipboardString),
3718 Image(Image),
3720 ExternalPaths(crate::ExternalPaths),
3722}
3723
3724impl ClipboardItem {
3725 pub fn new_string(text: String) -> Self {
3727 Self {
3728 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3729 }
3730 }
3731
3732 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3734 Self {
3735 entries: vec![ClipboardEntry::String(ClipboardString {
3736 text,
3737 metadata: Some(metadata),
3738 })],
3739 }
3740 }
3741
3742 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3744 Self {
3745 entries: vec![ClipboardEntry::String(
3746 ClipboardString::new(text).with_json_metadata(metadata),
3747 )],
3748 }
3749 }
3750
3751 pub fn new_image(image: &Image) -> Self {
3753 Self {
3754 entries: vec![ClipboardEntry::Image(image.clone())],
3755 }
3756 }
3757
3758 pub fn text(&self) -> Option<String> {
3761 let mut answer = String::new();
3762
3763 for entry in self.entries.iter() {
3764 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3765 answer.push_str(text);
3766 }
3767 }
3768
3769 if answer.is_empty() {
3770 for entry in self.entries.iter() {
3771 if let ClipboardEntry::ExternalPaths(paths) = entry {
3772 for path in &paths.0 {
3773 use std::fmt::Write as _;
3774 _ = write!(answer, "{}", path.display());
3775 }
3776 }
3777 }
3778 }
3779
3780 if !answer.is_empty() {
3781 Some(answer)
3782 } else {
3783 None
3784 }
3785 }
3786
3787 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3789 pub fn metadata(&self) -> Option<&String> {
3790 match self.entries().first() {
3791 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3792 clipboard_string.metadata.as_ref()
3793 }
3794 _ => None,
3795 }
3796 }
3797
3798 pub fn entries(&self) -> &[ClipboardEntry] {
3800 &self.entries
3801 }
3802
3803 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3805 self.entries.into_iter()
3806 }
3807}
3808
3809impl From<ClipboardString> for ClipboardEntry {
3810 fn from(value: ClipboardString) -> Self {
3811 Self::String(value)
3812 }
3813}
3814
3815impl From<String> for ClipboardEntry {
3816 fn from(value: String) -> Self {
3817 Self::from(ClipboardString::from(value))
3818 }
3819}
3820
3821impl From<Image> for ClipboardEntry {
3822 fn from(value: Image) -> Self {
3823 Self::Image(value)
3824 }
3825}
3826
3827impl From<ClipboardEntry> for ClipboardItem {
3828 fn from(value: ClipboardEntry) -> Self {
3829 Self {
3830 entries: vec![value],
3831 }
3832 }
3833}
3834
3835impl From<String> for ClipboardItem {
3836 fn from(value: String) -> Self {
3837 Self::from(ClipboardEntry::from(value))
3838 }
3839}
3840
3841impl From<Image> for ClipboardItem {
3842 fn from(value: Image) -> Self {
3843 Self::from(ClipboardEntry::from(value))
3844 }
3845}
3846
3847#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3849pub enum ImageFormat {
3850 Png,
3855 Jpeg,
3857 Webp,
3859 Gif,
3861 Svg,
3863 Bmp,
3865 Tiff,
3867 Ico,
3869 Pnm,
3871}
3872
3873impl ImageFormat {
3874 pub const ALL: [Self; 9] = [
3876 Self::Png,
3877 Self::Jpeg,
3878 Self::Webp,
3879 Self::Gif,
3880 Self::Svg,
3881 Self::Bmp,
3882 Self::Tiff,
3883 Self::Ico,
3884 Self::Pnm,
3885 ];
3886
3887 pub fn iter() -> impl Iterator<Item = Self> {
3889 Self::ALL.into_iter()
3890 }
3891
3892 pub const fn mime_type(self) -> &'static str {
3894 match self {
3895 ImageFormat::Png => "image/png",
3896 ImageFormat::Jpeg => "image/jpeg",
3897 ImageFormat::Webp => "image/webp",
3898 ImageFormat::Gif => "image/gif",
3899 ImageFormat::Svg => "image/svg+xml",
3900 ImageFormat::Bmp => "image/bmp",
3901 ImageFormat::Tiff => "image/tiff",
3902 ImageFormat::Ico => "image/ico",
3903 ImageFormat::Pnm => "image/x-portable-anymap",
3904 }
3905 }
3906
3907 pub const fn extension(self) -> &'static str {
3909 match self {
3910 ImageFormat::Png => "png",
3911 ImageFormat::Jpeg => "jpg",
3912 ImageFormat::Webp => "webp",
3913 ImageFormat::Gif => "gif",
3914 ImageFormat::Svg => "svg",
3915 ImageFormat::Bmp => "bmp",
3916 ImageFormat::Tiff => "tiff",
3917 ImageFormat::Ico => "ico",
3918 ImageFormat::Pnm => "pnm",
3919 }
3920 }
3921
3922 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3924 Self::iter()
3925 .find(|format| format.mime_type() == mime_type)
3926 .or_else(|| Self::from_mime_type_alias(mime_type))
3927 }
3928
3929 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3933 match mime_type {
3934 "image/jpg" => Some(Self::Jpeg),
3935 "image/tif" => Some(Self::Tiff),
3936 _ => None,
3937 }
3938 }
3939}
3940
3941#[derive(Clone, Debug, PartialEq, Eq)]
3943pub struct Image {
3944 pub format: ImageFormat,
3946 pub bytes: Vec<u8>,
3948 pub id: u64,
3950}
3951
3952pub(crate) fn decode_static_image(
3953 bytes: &[u8],
3954 format: image::ImageFormat,
3955) -> Result<SmallVec<[Frame; 1]>> {
3956 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3957 .into_decoder()
3958 .context("creating image decoder")?;
3959 decode_static_image_from_decoder(decoder)
3960}
3961
3962pub(crate) fn decode_static_image_from_decoder(
3963 mut decoder: impl image::ImageDecoder,
3964) -> Result<SmallVec<[Frame; 1]>> {
3965 let orientation = decoder
3966 .orientation()
3967 .context("reading decoder's orientation")?;
3968 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3969 image.apply_orientation(orientation);
3970
3971 let mut data = image.into_rgba8();
3972 for pixel in data.chunks_exact_mut(4) {
3973 pixel.swap(0, 2);
3974 }
3975
3976 Ok(SmallVec::from_elem(Frame::new(data), 1))
3977}
3978
3979fn decode_animated_frames<'a>(
3980 decoder: impl image::AnimationDecoder<'a>,
3981 format_name: &str,
3982) -> Result<SmallVec<[Frame; 1]>> {
3983 let mut frames = SmallVec::new();
3984
3985 for frame in decoder.into_frames() {
3986 match frame {
3987 Ok(mut frame) => {
3988 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3990 pixel.swap(0, 2);
3991 }
3992 frames.push(frame);
3993 }
3994 Err(err) => {
3995 log::debug!("Skipping {format_name} frame due to decode error: {err}");
3996 }
3997 }
3998 }
3999
4000 if frames.is_empty() {
4001 anyhow::bail!("{format_name} could not be decoded: all frames failed");
4002 }
4003
4004 Ok(frames)
4005}
4006
4007pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
4008 let decoder = GifDecoder::new(Cursor::new(bytes))?;
4009 decode_animated_frames(decoder, "GIF")
4010}
4011
4012pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
4013 let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
4014
4015 if decoder.has_animation() {
4016 let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
4017 decode_animated_frames(decoder, "WebP")
4018 } else {
4019 decode_static_image_from_decoder(decoder)
4020 }
4021}
4022
4023impl Hash for Image {
4024 fn hash<H: Hasher>(&self, state: &mut H) {
4025 state.write_u64(self.id);
4026 }
4027}
4028
4029impl Image {
4030 pub fn empty() -> Self {
4032 Self::from_bytes(ImageFormat::Png, Vec::new())
4033 }
4034
4035 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
4037 Self {
4038 id: hash(&bytes),
4039 format,
4040 bytes,
4041 }
4042 }
4043
4044 pub fn id(&self) -> u64 {
4046 self.id
4047 }
4048
4049 pub fn use_render_image(
4051 self: Arc<Self>,
4052 window: &mut Window,
4053 cx: &mut App,
4054 ) -> Option<Arc<RenderImage>> {
4055 ImageSource::Image(self)
4056 .use_data(None, window, cx)
4057 .and_then(|result| result.ok())
4058 }
4059
4060 pub fn get_render_image(
4062 self: Arc<Self>,
4063 window: &mut Window,
4064 cx: &mut App,
4065 ) -> Option<Arc<RenderImage>> {
4066 ImageSource::Image(self)
4067 .get_data(None, window, cx)
4068 .and_then(|result| result.ok())
4069 }
4070
4071 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
4073 ImageSource::Image(self).remove_asset(cx);
4074 }
4075
4076 #[cfg(any(test, feature = "test-support"))]
4079 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
4080 ImageSource::Image(self.clone()).is_asset_cached(cx)
4081 }
4082
4083 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
4085 let frames = match self.format {
4086 ImageFormat::Gif => decode_gif_image(&self.bytes)?,
4087 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
4088 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
4089 ImageFormat::Webp => decode_webp_image(&self.bytes)?,
4090 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
4091 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
4092 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
4093 ImageFormat::Svg => {
4094 return svg_renderer
4095 .render_single_frame(&self.bytes, 1.0)
4096 .map_err(Into::into);
4097 }
4098 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
4099 };
4100
4101 Ok(Arc::new(RenderImage::new(frames)))
4102 }
4103
4104 pub fn format(&self) -> ImageFormat {
4106 self.format
4107 }
4108
4109 pub fn bytes(&self) -> &[u8] {
4111 self.bytes.as_slice()
4112 }
4113}
4114
4115#[derive(Clone, Debug, Eq, PartialEq)]
4117pub struct ClipboardString {
4118 pub text: String,
4120 pub metadata: Option<String>,
4122}
4123
4124impl ClipboardString {
4125 pub fn new(text: String) -> Self {
4127 Self {
4128 text,
4129 metadata: None,
4130 }
4131 }
4132
4133 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
4136 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
4137 self
4138 }
4139
4140 pub fn text(&self) -> &String {
4142 &self.text
4143 }
4144
4145 pub fn into_text(self) -> String {
4147 self.text
4148 }
4149
4150 pub fn metadata_json<T>(&self) -> Option<T>
4152 where
4153 T: for<'a> Deserialize<'a>,
4154 {
4155 self.metadata
4156 .as_ref()
4157 .and_then(|m| serde_json::from_str(m).ok())
4158 }
4159
4160 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
4161 pub fn text_hash(text: &str) -> u64 {
4163 let mut hasher = SeaHasher::new();
4164 text.hash(&mut hasher);
4165 hasher.finish()
4166 }
4167}
4168
4169impl From<String> for ClipboardString {
4170 fn from(value: String) -> Self {
4171 Self {
4172 text: value,
4173 metadata: None,
4174 }
4175 }
4176}
4177
4178#[cfg(test)]
4179mod image_tests {
4180 use super::*;
4181 use std::sync::Arc;
4182
4183 #[test]
4184 fn test_image_to_image_data_applies_exif_orientation() {
4185 let image = Image::from_bytes(
4186 ImageFormat::Jpeg,
4187 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
4188 );
4189
4190 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4191
4192 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
4193
4194 let bytes = render_image.as_bytes(0).unwrap();
4195 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
4196 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
4197 }
4198
4199 #[test]
4200 fn test_svg_image_to_image_data_converts_to_bgra() {
4201 let image = Image::from_bytes(
4202 ImageFormat::Svg,
4203 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
4204<rect width="1" height="1" fill="#38BDF8"/>
4205</svg>"##
4206 .to_vec(),
4207 );
4208
4209 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4210 let bytes = render_image.as_bytes(0).unwrap();
4211
4212 for pixel in bytes.chunks_exact(4) {
4213 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
4214 }
4215 }
4216
4217 #[test]
4218 fn test_animated_webp_image_to_image_data_decodes_frames() {
4219 const ANIMATED_WEBP: &[u8] = &[
4221 82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
4222 0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
4223 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,
4224 0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
4225 176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
4226 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,
4227 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,
4228 0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
4229 31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
4230 ];
4231
4232 let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
4233 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4234
4235 assert_eq!(render_image.frame_count(), 2);
4236 assert_eq!(render_image.size(0), size(1.into(), 1.into()));
4237 assert_eq!(
4238 Duration::from(render_image.delay(0)),
4239 Duration::from_millis(100)
4240 );
4241 assert_eq!(
4242 Duration::from(render_image.delay(1)),
4243 Duration::from_millis(100)
4244 );
4245 }
4246}
4247
4248#[cfg(test)]
4249mod atlas_tests {
4250 use super::*;
4251
4252 const TILE_SIZE: Size<DevicePixels> = Size {
4253 width: DevicePixels(1),
4254 height: DevicePixels(1),
4255 };
4256
4257 #[derive(Default)]
4258 struct RecordingAtlasBackend {
4259 insert_calls: u32,
4260 fail_next_insert: bool,
4261 removed_tiles: Vec<AtlasTile>,
4262 }
4263
4264 impl AtlasBackend for RecordingAtlasBackend {
4265 fn insert(
4266 &mut self,
4267 kind: AtlasTextureKind,
4268 size: Size<DevicePixels>,
4269 _bytes: &[u8],
4270 ) -> Result<AtlasTile> {
4271 self.insert_calls += 1;
4272 if std::mem::take(&mut self.fail_next_insert) {
4273 anyhow::bail!("backend failed");
4274 }
4275 Ok(AtlasTile {
4276 texture_id: AtlasTextureId { index: 0, kind },
4277 tile_id: TileId(self.insert_calls),
4278 padding: 0,
4279 bounds: Bounds {
4280 origin: Point::default(),
4281 size,
4282 },
4283 })
4284 }
4285
4286 fn remove(&mut self, tile: AtlasTile) {
4287 self.removed_tiles.push(tile);
4288 }
4289 }
4290
4291 fn image_key(image_id: usize) -> AtlasKey {
4292 AtlasKey::Image(RenderImageParams {
4293 image_id: crate::ImageId(image_id),
4294 frame_index: 0,
4295 })
4296 }
4297
4298 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
4299 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
4300 }
4301
4302 #[test]
4303 fn only_successful_inserts_are_cached() -> Result<()> {
4304 let mut state = AtlasState::new(RecordingAtlasBackend::default());
4305 let key = image_key(1);
4306
4307 assert_eq!(
4308 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
4309 None
4310 );
4311 state
4312 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
4313 .expect_err("builder error should propagate");
4314 assert!(!state.contains(&key));
4315 assert_eq!(state.backend.insert_calls, 0);
4316
4317 state.backend.fail_next_insert = true;
4318 state
4319 .get_or_insert_with(key.clone(), &mut build_tile)
4320 .expect_err("backend error should propagate");
4321 assert!(!state.contains(&key));
4322 assert_eq!(state.backend.insert_calls, 1);
4323
4324 let tile = state
4325 .get_or_insert_with(key.clone(), &mut build_tile)?
4326 .context("builder should produce a tile")?;
4327 assert_eq!(tile.texture_id.kind, key.texture_kind());
4328 assert_eq!(
4329 state.get_or_insert_with(key.clone(), &mut || {
4330 anyhow::bail!("cache hit must not call the builder")
4331 })?,
4332 Some(tile)
4333 );
4334 assert!(state.contains(&key));
4335 assert_eq!(state.backend.insert_calls, 2);
4336 Ok(())
4337 }
4338
4339 #[test]
4340 fn remove_and_clear_invalidate_keys() -> Result<()> {
4341 let mut state = AtlasState::new(RecordingAtlasBackend::default());
4342 let key = image_key(1);
4343 let other_key = image_key(2);
4344 let tile = state
4345 .get_or_insert_with(key.clone(), &mut build_tile)?
4346 .context("builder should produce a tile")?;
4347 state
4348 .get_or_insert_with(other_key.clone(), &mut build_tile)?
4349 .context("builder should produce another tile")?;
4350
4351 state.remove(&key);
4352 state.remove(&key);
4353 assert!(!state.contains(&key));
4354 assert!(state.contains(&other_key));
4355 assert_eq!(state.backend.removed_tiles, vec![tile]);
4356
4357 let mut reset_calls = 0;
4358 state.clear(|_| reset_calls += 1);
4359 assert_eq!(reset_calls, 1);
4360 assert!(!state.contains(&other_key));
4361 assert_eq!(state.backend.removed_tiles, vec![tile]);
4362 Ok(())
4363 }
4364}
4365
4366#[cfg(test)]
4367mod frame_signal_tests {
4368 use super::*;
4369
4370 #[cfg(feature = "profiler")]
4371 #[test]
4372 fn coalesced_signals_retain_the_earliest_until_drained() {
4373 for (first_source, later_source) in [
4374 (
4375 FrameRequestSource::NativeCallback,
4376 FrameRequestSource::LocalSchedule,
4377 ),
4378 (
4379 FrameRequestSource::LocalSchedule,
4380 FrameRequestSource::NativeCallback,
4381 ),
4382 ] {
4383 let signal = PlatformFrameSignal::new();
4384 let first =
4385 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
4386 assert_eq!(signal.take(), None);
4387 signal.record(first + Duration::from_millis(16), later_source);
4388 signal.record(first, first_source);
4389 signal.record(first + Duration::from_millis(32), later_source);
4390 assert_eq!(signal.take(), Some((first, first_source)));
4391 assert_eq!(signal.take(), None);
4392 let next = first + Duration::from_millis(48);
4393 signal.record(next, later_source);
4394 assert_eq!(signal.take(), Some((next, later_source)));
4395 }
4396 }
4397
4398 #[cfg(not(feature = "profiler"))]
4399 #[test]
4400 fn disabled_profiling_does_not_capture_or_store_timestamps() {
4401 let captured = PlatformFrameSignal::capture(|| {
4402 panic!("profiler-disabled builds must not evaluate the capture closure");
4403 });
4404 assert_eq!(captured, None);
4405 let signal = PlatformFrameSignal::new();
4406 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
4407 assert_eq!(signal.take(), None);
4408 }
4409}
4410
4411#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
4412mod tests {
4413 use super::*;
4414 use std::collections::HashSet;
4415
4416 #[test]
4417 fn test_refresh_interval_from_hz() {
4418 assert_eq!(
4419 refresh_interval_from_hz(50.0),
4420 Some(Duration::from_millis(20))
4421 );
4422 assert_eq!(
4423 refresh_interval_from_hz(120.0),
4424 Some(Duration::from_secs(1) / 120)
4425 );
4426 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
4427 assert_eq!(refresh_interval_from_hz(unknown), None);
4428 }
4429 }
4430
4431 #[test]
4432 fn test_window_button_layout_parse_standard() {
4433 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
4434 assert_eq!(
4435 layout.left,
4436 [
4437 Some(WindowButton::Close),
4438 Some(WindowButton::Minimize),
4439 None
4440 ]
4441 );
4442 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4443 }
4444
4445 #[test]
4446 fn test_window_button_layout_parse_right_only() {
4447 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
4448 assert_eq!(layout.left, [None, None, None]);
4449 assert_eq!(
4450 layout.right,
4451 [
4452 Some(WindowButton::Minimize),
4453 Some(WindowButton::Maximize),
4454 Some(WindowButton::Close)
4455 ]
4456 );
4457 }
4458
4459 #[test]
4460 fn test_window_button_layout_parse_left_only() {
4461 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
4462 assert_eq!(
4463 layout.left,
4464 [
4465 Some(WindowButton::Close),
4466 Some(WindowButton::Minimize),
4467 Some(WindowButton::Maximize)
4468 ]
4469 );
4470 assert_eq!(layout.right, [None, None, None]);
4471 }
4472
4473 #[test]
4474 fn test_window_button_layout_parse_with_whitespace() {
4475 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
4476 assert_eq!(
4477 layout.left,
4478 [
4479 Some(WindowButton::Close),
4480 Some(WindowButton::Minimize),
4481 None
4482 ]
4483 );
4484 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4485 }
4486
4487 #[test]
4488 fn test_window_button_layout_parse_empty() {
4489 let layout = WindowButtonLayout::parse("").unwrap();
4490 assert_eq!(layout.left, [None, None, None]);
4491 assert_eq!(layout.right, [None, None, None]);
4492 }
4493
4494 #[test]
4495 fn test_window_button_layout_parse_intentionally_empty() {
4496 let layout = WindowButtonLayout::parse(":").unwrap();
4497 assert_eq!(layout.left, [None, None, None]);
4498 assert_eq!(layout.right, [None, None, None]);
4499 }
4500
4501 #[test]
4502 fn test_window_button_layout_parse_invalid_buttons() {
4503 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
4504 assert_eq!(
4505 layout.left,
4506 [
4507 Some(WindowButton::Close),
4508 Some(WindowButton::Minimize),
4509 None
4510 ]
4511 );
4512 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4513 }
4514
4515 #[test]
4516 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
4517 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
4518 assert_eq!(
4519 layout.right,
4520 [
4521 Some(WindowButton::Close),
4522 Some(WindowButton::Minimize),
4523 None
4524 ]
4525 );
4526 assert_eq!(layout.format(), ":close,minimize");
4527 }
4528
4529 #[test]
4530 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
4531 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
4532 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4533 assert_eq!(
4534 layout.right,
4535 [
4536 Some(WindowButton::Maximize),
4537 Some(WindowButton::Minimize),
4538 None
4539 ]
4540 );
4541
4542 let button_ids: Vec<_> = layout
4543 .left
4544 .iter()
4545 .chain(layout.right.iter())
4546 .flatten()
4547 .map(WindowButton::id)
4548 .collect();
4549 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4550 assert_eq!(unique_button_ids.len(), button_ids.len());
4551 assert_eq!(layout.format(), "close:maximize,minimize");
4552 }
4553
4554 #[test]
4555 fn test_window_button_layout_parse_gnome_style() {
4556 let layout = WindowButtonLayout::parse("close").unwrap();
4557 assert_eq!(layout.left, [None, None, None]);
4558 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4559 }
4560
4561 #[test]
4562 fn test_window_button_layout_parse_elementary_style() {
4563 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4564 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4565 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4566 }
4567
4568 #[test]
4569 fn test_window_button_layout_round_trip() {
4570 let cases = [
4571 "close:minimize,maximize",
4572 "minimize,maximize,close:",
4573 ":close",
4574 "close:",
4575 "close:maximize",
4576 ":",
4577 ];
4578
4579 for case in cases {
4580 let layout = WindowButtonLayout::parse(case).unwrap();
4581 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4582 }
4583 }
4584
4585 #[test]
4586 fn test_window_button_layout_linux_default() {
4587 let layout = WindowButtonLayout::linux_default();
4588 assert_eq!(layout.left, [None, None, None]);
4589 assert_eq!(
4590 layout.right,
4591 [
4592 Some(WindowButton::Minimize),
4593 Some(WindowButton::Maximize),
4594 Some(WindowButton::Close)
4595 ]
4596 );
4597
4598 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4599 assert_eq!(round_tripped, layout);
4600 }
4601
4602 #[test]
4603 fn test_window_button_layout_parse_all_invalid() {
4604 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4605 }
4606}