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 pub content_headroom: f32,
2213}
2214
2215#[doc(hidden)]
2217pub fn half_to_f32(bits: u16) -> f32 {
2218 let exponent = (bits >> 10) & 0x1f;
2219 let mantissa = u32::from(bits & 0x3ff);
2220 let magnitude = match exponent {
2221 0 => mantissa as f32 / 16_777_216.0,
2222 31 if mantissa == 0 => f32::INFINITY,
2223 31 => f32::NAN,
2224 _ => f32::from_bits(((u32::from(exponent) + 112) << 23) | (mantissa << 13)),
2225 };
2226 if bits & 0x8000 != 0 {
2227 -magnitude
2228 } else {
2229 magnitude
2230 }
2231}
2232
2233#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2236pub enum TileSource {
2237 Bytes,
2241 Gpu(GpuTextureHandle),
2244}
2245
2246#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2248pub enum TileWrite {
2249 InPlace,
2253 Placed,
2257 Refused,
2260}
2261
2262impl GpuTextureHandle {
2263 pub const NULL: Self = Self(std::ptr::null_mut());
2265
2266 pub fn is_null(&self) -> bool {
2268 self.0.is_null()
2269 }
2270}
2271
2272#[doc(hidden)]
2273pub trait AtlasBackend {
2274 fn insert(
2275 &mut self,
2276 kind: AtlasTextureKind,
2277 size: Size<DevicePixels>,
2278 bytes: &[u8],
2279 ) -> Result<AtlasTile>;
2280
2281 fn remove(&mut self, tile: AtlasTile);
2282}
2283
2284#[doc(hidden)]
2285pub struct AtlasState<Backend> {
2286 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
2287 pub backend: Backend,
2288}
2289
2290impl<Backend> AtlasState<Backend> {
2291 pub fn new(backend: Backend) -> Self {
2292 Self {
2293 tiles_by_key: FxHashMap::default(),
2294 backend,
2295 }
2296 }
2297
2298 pub fn contains(&self, key: &AtlasKey) -> bool {
2299 self.tiles_by_key.contains_key(key)
2300 }
2301
2302 pub fn clear(&mut self, reset_backend: impl FnOnce(&mut Backend)) {
2303 self.tiles_by_key.clear();
2304 reset_backend(&mut self.backend);
2305 }
2306
2307 pub fn tile(&self, key: &AtlasKey) -> Option<AtlasTile> {
2311 self.tiles_by_key.get(key).copied()
2312 }
2313
2314 pub fn insert_tile(&mut self, key: AtlasKey, tile: AtlasTile) {
2318 self.tiles_by_key.insert(key, tile);
2319 }
2320
2321 pub fn count_keys(&self, stats: &mut AtlasStats) {
2325 stats.keys = self.tiles_by_key.len() as u32;
2326 for (key, tile) in &self.tiles_by_key {
2327 let pixels =
2328 (tile.bounds.size.width.0.max(0) as u64) * (tile.bounds.size.height.0.max(0) as u64);
2329 stats.kinds[tile.texture_id.kind as usize].tile_pixels += pixels;
2330 if let AtlasKey::Image(_) = key {
2331 stats.image_keys += 1;
2332 stats.image_pixels += pixels;
2333 }
2334 }
2335 }
2336}
2337
2338impl<Backend: Default> Default for AtlasState<Backend> {
2339 fn default() -> Self {
2340 Self::new(Backend::default())
2341 }
2342}
2343
2344impl<Backend: AtlasBackend> AtlasState<Backend> {
2345 pub fn get_or_insert_with<'a>(
2346 &mut self,
2347 key: AtlasKey,
2348 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2349 ) -> Result<Option<AtlasTile>> {
2350 match self.tiles_by_key.entry(key) {
2351 Entry::Occupied(entry) => Ok(Some(*entry.get())),
2352 Entry::Vacant(entry) => {
2353 profiling::scope!("new tile");
2354 let Some((size, bytes)) = build()? else {
2355 return Ok(None);
2356 };
2357 let tile = self
2358 .backend
2359 .insert(entry.key().texture_kind(), size, &bytes)?;
2360 entry.insert(tile);
2361 Ok(Some(tile))
2362 }
2363 }
2364 }
2365
2366 pub fn remove(&mut self, key: &AtlasKey) {
2367 if let Some(tile) = self.tiles_by_key.remove(key) {
2368 self.backend.remove(tile);
2369 }
2370 }
2371}
2372
2373#[derive(Default)]
2377pub struct HeadlessAtlas(parking_lot::Mutex<AtlasState<HeadlessAtlasBackend>>);
2378
2379#[doc(hidden)]
2380#[derive(Default)]
2381pub struct HeadlessAtlasBackend {
2382 next_id: u32,
2383}
2384
2385impl AtlasBackend for HeadlessAtlasBackend {
2386 fn insert(
2387 &mut self,
2388 kind: AtlasTextureKind,
2389 size: Size<DevicePixels>,
2390 _bytes: &[u8],
2391 ) -> Result<AtlasTile> {
2392 self.next_id += 1;
2393 let texture_id = self.next_id;
2394 self.next_id += 1;
2395 let tile_id = self.next_id;
2396 Ok(AtlasTile {
2397 texture_id: AtlasTextureId {
2398 index: texture_id,
2399 kind,
2400 },
2401 tile_id: TileId(tile_id),
2402 padding: 0,
2403 bounds: Bounds {
2404 origin: Point::default(),
2405 size,
2406 },
2407 })
2408 }
2409
2410 fn remove(&mut self, _tile: AtlasTile) {}
2411}
2412
2413impl PlatformAtlas for HeadlessAtlas {
2414 fn get_or_insert_with<'a>(
2415 &self,
2416 key: AtlasKey,
2417 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
2418 ) -> Result<Option<AtlasTile>> {
2419 self.0.lock().get_or_insert_with(key, build)
2420 }
2421
2422 fn remove(&self, key: &AtlasKey) {
2423 self.0.lock().remove(key);
2424 }
2425
2426 #[cfg(any(test, feature = "test-support", feature = "bench-support"))]
2427 fn contains(&self, key: &AtlasKey) -> bool {
2428 self.0.lock().contains(key)
2429 }
2430}
2431
2432#[doc(hidden)]
2433pub struct AtlasTextureList<T> {
2434 pub textures: Vec<Option<T>>,
2435 pub free_list: Vec<usize>,
2436}
2437
2438impl<T> Default for AtlasTextureList<T> {
2439 fn default() -> Self {
2440 Self {
2441 textures: Vec::default(),
2442 free_list: Vec::default(),
2443 }
2444 }
2445}
2446
2447impl<T> ops::Index<usize> for AtlasTextureList<T> {
2448 type Output = Option<T>;
2449
2450 fn index(&self, index: usize) -> &Self::Output {
2451 &self.textures[index]
2452 }
2453}
2454
2455impl<T> AtlasTextureList<T> {
2456 #[allow(unused)]
2457 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
2458 self.free_list.clear();
2459 self.textures.drain(..)
2460 }
2461
2462 #[allow(dead_code)]
2463 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
2464 self.textures.iter_mut().flatten()
2465 }
2466}
2467
2468#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2469#[repr(C)]
2470#[expect(missing_docs)]
2471pub struct AtlasTile {
2472 pub texture_id: AtlasTextureId,
2474 pub tile_id: TileId,
2476 pub padding: u32,
2478 pub bounds: Bounds<DevicePixels>,
2480}
2481
2482#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2483#[repr(C)]
2484#[expect(missing_docs)]
2485pub struct AtlasTextureId {
2486 pub index: u32,
2489 pub kind: AtlasTextureKind,
2491}
2492
2493#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2494#[repr(C)]
2495#[cfg_attr(
2496 all(
2497 any(target_os = "linux", target_os = "freebsd"),
2498 not(any(feature = "x11", feature = "wayland"))
2499 ),
2500 allow(dead_code)
2501)]
2502#[expect(missing_docs)]
2503pub enum AtlasTextureKind {
2504 Monochrome = 0,
2505 Polychrome = 1,
2506 Subpixel = 2,
2507 PolychromeHdr = 3,
2513}
2514
2515#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
2516#[repr(C)]
2517#[expect(missing_docs)]
2518pub struct TileId(pub u32);
2519
2520impl From<etagere::AllocId> for TileId {
2521 fn from(id: etagere::AllocId) -> Self {
2522 Self(id.serialize())
2523 }
2524}
2525
2526impl From<TileId> for etagere::AllocId {
2527 fn from(id: TileId) -> Self {
2528 Self::deserialize(id.0)
2529 }
2530}
2531
2532#[expect(missing_docs)]
2533pub struct PlatformInputHandler {
2534 cx: AsyncWindowContext,
2535 handler: Box<dyn InputHandler>,
2536 focus_id: Option<crate::FocusId>,
2537}
2538
2539#[expect(missing_docs)]
2540#[cfg_attr(
2541 all(
2542 any(target_os = "linux", target_os = "freebsd"),
2543 not(any(feature = "x11", feature = "wayland"))
2544 ),
2545 allow(dead_code)
2546)]
2547impl PlatformInputHandler {
2548 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
2549 Self {
2550 cx,
2551 handler,
2552 focus_id: None,
2553 }
2554 }
2555
2556 pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
2557 self.focus_id = Some(focus_id);
2558 self
2559 }
2560
2561 pub fn focus_id(&self) -> Option<crate::FocusId> {
2566 self.focus_id
2567 }
2568
2569 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
2570 self.cx
2571 .update(|window, cx| {
2572 self.handler
2573 .selected_text_range(ignore_disabled_input, window, cx)
2574 })
2575 .ok()
2576 .flatten()
2577 }
2578
2579 #[cfg_attr(target_os = "windows", allow(dead_code))]
2580 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
2581 self.cx
2582 .update(|window, cx| self.handler.marked_text_range(window, cx))
2583 .ok()
2584 .flatten()
2585 }
2586
2587 #[cfg_attr(
2588 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
2589 allow(dead_code)
2590 )]
2591 pub fn text_for_range(
2592 &mut self,
2593 range_utf16: Range<usize>,
2594 adjusted: &mut Option<Range<usize>>,
2595 ) -> Option<String> {
2596 self.cx
2597 .update(|window, cx| {
2598 self.handler
2599 .text_for_range(range_utf16, adjusted, window, cx)
2600 })
2601 .ok()
2602 .flatten()
2603 }
2604
2605 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
2606 self.cx
2607 .update(|window, cx| {
2608 self.handler
2609 .replace_text_in_range(replacement_range, text, window, cx);
2610 })
2611 .ok();
2612 }
2613
2614 pub fn replace_and_mark_text_in_range(
2615 &mut self,
2616 range_utf16: Option<Range<usize>>,
2617 new_text: &str,
2618 new_selected_range: Option<Range<usize>>,
2619 ) {
2620 self.cx
2621 .update(|window, cx| {
2622 self.handler.replace_and_mark_text_in_range(
2623 range_utf16,
2624 new_text,
2625 new_selected_range,
2626 window,
2627 cx,
2628 )
2629 })
2630 .ok();
2631 }
2632
2633 #[cfg_attr(target_os = "windows", allow(dead_code))]
2634 pub fn unmark_text(&mut self) {
2635 self.cx
2636 .update(|window, cx| self.handler.unmark_text(window, cx))
2637 .ok();
2638 }
2639
2640 pub fn paste(&mut self, item: ClipboardItem) {
2641 self.cx
2642 .update(|window, cx| self.handler.paste(item, window, cx))
2643 .ok();
2644 }
2645
2646 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
2647 self.cx
2648 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
2649 .ok()
2650 .flatten()
2651 }
2652
2653 pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
2654 self.cx
2655 .update(|window, cx| {
2656 self.handler
2657 .selection_bounds_for_range(range_utf16, window, cx)
2658 })
2659 .unwrap_or_default()
2660 }
2661
2662 #[allow(dead_code)]
2663 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
2664 self.handler.apple_press_and_hold_enabled()
2665 }
2666
2667 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
2668 self.handler.replace_text_in_range(None, input, window, cx);
2669 }
2670
2671 pub fn compute_ime_candidate_bounds(
2672 marked_range: Option<Range<usize>>,
2673 selection: &UTF16Selection,
2674 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2675 ) -> Option<Bounds<Pixels>> {
2676 if let Some(marked_range) = marked_range {
2677 let mut line_start = marked_range.start;
2679
2680 let caret = selection.range.end;
2684 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2685 for i in (marked_range.start..caret).rev() {
2686 if let Some(b) = bounds_for_range(i..i) {
2687 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2688 line_start = i + 1;
2689 break;
2690 }
2691 }
2692 }
2693 }
2694 bounds_for_range(line_start..line_start)
2695 } else {
2696 let offset = if selection.reversed {
2698 selection.range.start
2699 } else {
2700 selection.range.end
2701 };
2702 bounds_for_range(offset..offset)
2703 }
2704 }
2705
2706 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2707 let marked_range = self.handler.marked_text_range(window, cx);
2708 let selection = self.handler.selected_text_range(true, window, cx)?;
2709 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2710 self.handler.bounds_for_range(range, window, cx)
2711 })
2712 }
2713
2714 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2715 let marked_range = self.marked_text_range();
2716 let selection = self.selected_text_range(true)?;
2717 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2718 self.bounds_for_range(range)
2719 })
2720 }
2721
2722 #[allow(unused)]
2723 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2724 self.cx
2725 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2726 .ok()
2727 .flatten()
2728 }
2729
2730 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
2732 self.cx
2733 .update(|window, cx| {
2734 self.handler
2735 .set_selected_text_range(range_utf16, window, cx)
2736 })
2737 .ok();
2738 }
2739
2740 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
2742 self.cx
2743 .update(|window, cx| self.handler.element_bounds(window, cx))
2744 .ok()
2745 .flatten()
2746 }
2747
2748 pub fn text_length_utf16(&mut self) -> Option<usize> {
2750 self.cx
2751 .update(|window, cx| self.handler.text_length_utf16(window, cx))
2752 .ok()
2753 .flatten()
2754 }
2755
2756 #[allow(dead_code)]
2757 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2758 self.handler.accepts_text_input(window, cx)
2759 }
2760
2761 #[allow(dead_code)]
2762 pub fn query_accepts_text_input(&mut self) -> bool {
2763 self.cx
2764 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2765 .unwrap_or(true)
2766 }
2767
2768 pub fn query_accepts_focused_text_input(&mut self) -> bool {
2773 let focus_id = self.focus_id;
2774 self.cx
2775 .update(|window, cx| {
2776 focus_id.is_some()
2777 && window.focus == focus_id
2778 && self.handler.accepts_text_input(window, cx)
2779 })
2780 .unwrap_or(false)
2781 }
2782
2783 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2789 self.cx
2790 .update(|window, cx| {
2791 !window.has_pending_keystrokes()
2793 && self.handler.prefers_ime_for_printable_keys(window, cx)
2794 })
2795 .unwrap_or(false)
2796 }
2797
2798 pub fn text_input_configuration(
2800 &mut self,
2801 window: &mut Window,
2802 cx: &mut App,
2803 ) -> TextInputConfiguration {
2804 self.handler.text_input_configuration(window, cx)
2805 }
2806
2807 pub fn text_input_editable_range(&mut self) -> Option<Range<usize>> {
2809 self.cx
2810 .update(|window, cx| self.handler.text_input_editable_range(window, cx))
2811 .ok()
2812 .flatten()
2813 }
2814}
2815
2816#[derive(Debug)]
2819pub struct UTF16Selection {
2820 pub range: Range<usize>,
2823 pub reversed: bool,
2826}
2827
2828pub trait InputHandler: 'static {
2833 fn selected_text_range(
2838 &mut self,
2839 ignore_disabled_input: bool,
2840 window: &mut Window,
2841 cx: &mut App,
2842 ) -> Option<UTF16Selection>;
2843
2844 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2849
2850 fn text_for_range(
2855 &mut self,
2856 range_utf16: Range<usize>,
2857 adjusted_range: &mut Option<Range<usize>>,
2858 window: &mut Window,
2859 cx: &mut App,
2860 ) -> Option<String>;
2861
2862 fn replace_text_in_range(
2867 &mut self,
2868 replacement_range: Option<Range<usize>>,
2869 text: &str,
2870 window: &mut Window,
2871 cx: &mut App,
2872 );
2873
2874 fn replace_and_mark_text_in_range(
2881 &mut self,
2882 range_utf16: Option<Range<usize>>,
2883 new_text: &str,
2884 new_selected_range: Option<Range<usize>>,
2885 window: &mut Window,
2886 cx: &mut App,
2887 );
2888
2889 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2892
2893 fn paste(&mut self, item: ClipboardItem, window: &mut Window, cx: &mut App) {
2900 if let Some(text) = item.text() {
2901 self.replace_text_in_range(None, &text, window, cx);
2902 }
2903 }
2904
2905 fn bounds_for_range(
2910 &mut self,
2911 range_utf16: Range<usize>,
2912 window: &mut Window,
2913 cx: &mut App,
2914 ) -> Option<Bounds<Pixels>>;
2915
2916 fn selection_bounds_for_range(
2923 &mut self,
2924 _range_utf16: Range<usize>,
2925 _window: &mut Window,
2926 _cx: &mut App,
2927 ) -> Vec<Bounds<Pixels>> {
2928 Vec::new()
2929 }
2930
2931 fn character_index_for_point(
2935 &mut self,
2936 point: Point<Pixels>,
2937 window: &mut Window,
2938 cx: &mut App,
2939 ) -> Option<usize>;
2940
2941 fn set_selected_text_range(
2951 &mut self,
2952 _range_utf16: Range<usize>,
2953 _window: &mut Window,
2954 _cx: &mut App,
2955 ) {
2956 }
2957
2958 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2965 None
2966 }
2967
2968 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2970 None
2971 }
2972
2973 #[allow(dead_code)]
2978 fn apple_press_and_hold_enabled(&mut self) -> bool {
2979 true
2980 }
2981
2982 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2984 true
2985 }
2986
2987 fn text_input_editable_range(
2998 &mut self,
2999 _window: &mut Window,
3000 _cx: &mut App,
3001 ) -> Option<Range<usize>> {
3002 None
3003 }
3004
3005 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
3014 false
3015 }
3016
3017 fn text_input_configuration(
3023 &mut self,
3024 _window: &mut Window,
3025 _cx: &mut App,
3026 ) -> TextInputConfiguration {
3027 TextInputConfiguration::default()
3028 }
3029}
3030
3031#[derive(Clone, Debug, Default, PartialEq, Eq)]
3041pub struct TextInputConfiguration {
3042 pub autocorrect: bool,
3044 pub autocapitalize: Autocapitalize,
3046 pub suggestions: bool,
3048 pub input_action: TextInputAction,
3050}
3051
3052#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3054pub enum Autocapitalize {
3055 #[default]
3057 None,
3058 Words,
3060 Sentences,
3062 Characters,
3064}
3065
3066#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3076pub enum TextInputAction {
3077 #[default]
3079 Unspecified,
3080 Enter,
3082 Done,
3084 Go,
3086 Next,
3088 Previous,
3090 Search,
3092 Send,
3094}
3095
3096#[derive(Debug)]
3098pub struct WindowOptions {
3099 pub window_bounds: Option<WindowBounds>,
3103
3104 pub titlebar: Option<TitlebarOptions>,
3106
3107 pub focus: bool,
3109
3110 pub show: bool,
3112
3113 pub kind: WindowKind,
3115
3116 pub is_movable: bool,
3120
3121 pub app_owns_titlebar_drag: bool,
3133
3134 pub inactive_frame_interval: Option<Duration>,
3139
3140 pub low_power_frame_interval: Option<Duration>,
3145
3146 pub thermal_frame_interval: Option<Duration>,
3151
3152 pub is_resizable: bool,
3154
3155 pub is_minimizable: bool,
3157
3158 pub display_id: Option<DisplayId>,
3161
3162 pub window_background: WindowBackgroundAppearance,
3164
3165 pub app_id: Option<String>,
3167
3168 pub window_min_size: Option<Size<Pixels>>,
3170
3171 pub window_decorations: Option<WindowDecorations>,
3174
3175 pub icon: Option<Arc<image::RgbaImage>>,
3177
3178 pub tabbing_identifier: Option<String>,
3180
3181 pub use_display_p3: bool,
3183}
3184
3185#[derive(Debug)]
3187#[cfg_attr(
3188 all(
3189 any(target_os = "linux", target_os = "freebsd"),
3190 not(any(feature = "x11", feature = "wayland"))
3191 ),
3192 allow(dead_code)
3193)]
3194#[allow(missing_docs)]
3195pub struct WindowParams {
3196 pub bounds: Bounds<Pixels>,
3197
3198 #[cfg_attr(feature = "wayland", allow(dead_code))]
3200 pub titlebar: Option<TitlebarOptions>,
3201
3202 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3204 pub kind: WindowKind,
3205
3206 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3208 pub is_movable: bool,
3209
3210 #[cfg_attr(
3212 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3213 allow(dead_code)
3214 )]
3215 pub app_owns_titlebar_drag: bool,
3216
3217 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3219 pub is_resizable: bool,
3220
3221 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3223 pub is_minimizable: bool,
3224
3225 #[cfg_attr(
3226 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
3227 allow(dead_code)
3228 )]
3229 pub focus: bool,
3230
3231 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
3232 pub show: bool,
3233
3234 #[cfg_attr(feature = "wayland", allow(dead_code))]
3236 pub icon: Option<Arc<image::RgbaImage>>,
3237
3238 #[cfg_attr(feature = "wayland", allow(dead_code))]
3239 pub display_id: Option<DisplayId>,
3240
3241 #[cfg_attr(feature = "wayland", allow(dead_code))]
3242 pub app_id: Option<String>,
3243
3244 pub window_min_size: Option<Size<Pixels>>,
3245
3246 #[cfg(target_os = "macos")]
3247 pub tabbing_identifier: Option<String>,
3248
3249 #[cfg(target_os = "macos")]
3250 pub use_display_p3: bool,
3251}
3252
3253#[derive(Debug, Copy, Clone, PartialEq)]
3255pub enum WindowBounds {
3256 Windowed(Bounds<Pixels>),
3258 Maximized(Bounds<Pixels>),
3261 Fullscreen(Bounds<Pixels>),
3264}
3265
3266impl Default for WindowBounds {
3267 fn default() -> Self {
3268 WindowBounds::Windowed(Bounds::default())
3269 }
3270}
3271
3272impl WindowBounds {
3273 pub fn get_bounds(&self) -> Bounds<Pixels> {
3275 match self {
3276 WindowBounds::Windowed(bounds) => *bounds,
3277 WindowBounds::Maximized(bounds) => *bounds,
3278 WindowBounds::Fullscreen(bounds) => *bounds,
3279 }
3280 }
3281
3282 pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &App) -> Self {
3285 WindowBounds::Windowed(Bounds::centered(display_id, size, cx))
3286 }
3287}
3288
3289impl Default for WindowOptions {
3290 fn default() -> Self {
3291 Self {
3292 window_bounds: None,
3293 titlebar: Some(TitlebarOptions {
3294 title: Default::default(),
3295 appears_transparent: Default::default(),
3296 traffic_light_position: Default::default(),
3297 }),
3298 focus: true,
3299 show: true,
3300 kind: WindowKind::Normal,
3301 is_movable: true,
3302 app_owns_titlebar_drag: false,
3303 inactive_frame_interval: Some(Duration::from_micros(33_333)),
3304 low_power_frame_interval: Some(Duration::from_micros(33_333)),
3305 thermal_frame_interval: Some(Duration::from_micros(16_667)),
3306 is_resizable: true,
3307 is_minimizable: true,
3308 display_id: None,
3309 window_background: WindowBackgroundAppearance::default(),
3310 icon: None,
3311 app_id: None,
3312 window_min_size: None,
3313 window_decorations: None,
3314 tabbing_identifier: None,
3315 use_display_p3: false,
3316 }
3317 }
3318}
3319
3320#[derive(Debug, Default)]
3322pub struct TitlebarOptions {
3323 pub title: Option<SharedString>,
3325
3326 pub appears_transparent: bool,
3329
3330 pub traffic_light_position: Option<Point<Pixels>>,
3332}
3333
3334#[derive(Clone, Debug, PartialEq, Eq)]
3336pub enum WindowKind {
3337 Normal,
3339
3340 PopUp,
3343
3344 AnchoredPopup(popup::PopupOptions),
3351
3352 Floating,
3354
3355 #[cfg(all(target_os = "linux", feature = "wayland"))]
3358 LayerShell(layer_shell::LayerShellOptions),
3359
3360 Dialog,
3363}
3364
3365#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3370pub enum WindowAppearance {
3371 #[default]
3375 Light,
3376
3377 VibrantLight,
3381
3382 Dark,
3386
3387 VibrantDark,
3391}
3392
3393#[derive(Copy, Clone, Debug, Default, PartialEq)]
3396pub enum WindowBackgroundAppearance {
3397 #[default]
3405 Opaque,
3406 Transparent,
3408 Blurred,
3412 MicaBackdrop,
3414 MicaAltBackdrop,
3416 AcrylicBackdrop,
3419}
3420
3421#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3423pub enum TextRenderingMode {
3424 #[default]
3426 PlatformDefault,
3427 Subpixel,
3429 Grayscale,
3431}
3432
3433#[derive(Clone, Debug)]
3435pub struct PathPromptOptions {
3436 pub files: bool,
3438 pub directories: bool,
3440 pub multiple: bool,
3442 pub prompt: Option<SharedString>,
3444}
3445
3446#[derive(Copy, Clone, Debug, PartialEq)]
3448pub enum PromptLevel {
3449 Info,
3451
3452 Warning,
3454
3455 Critical,
3457}
3458
3459#[derive(Clone, Debug, PartialEq)]
3461pub enum PromptButton {
3462 Ok(SharedString),
3464 Cancel(SharedString),
3466 Other(SharedString),
3468}
3469
3470impl PromptButton {
3471 pub fn new(label: impl Into<SharedString>) -> Self {
3473 PromptButton::Other(label.into())
3474 }
3475
3476 pub fn ok(label: impl Into<SharedString>) -> Self {
3478 PromptButton::Ok(label.into())
3479 }
3480
3481 pub fn cancel(label: impl Into<SharedString>) -> Self {
3483 PromptButton::Cancel(label.into())
3484 }
3485
3486 #[allow(dead_code)]
3488 pub fn is_cancel(&self) -> bool {
3489 matches!(self, PromptButton::Cancel(_))
3490 }
3491
3492 pub fn label(&self) -> &SharedString {
3494 match self {
3495 PromptButton::Ok(label) => label,
3496 PromptButton::Cancel(label) => label,
3497 PromptButton::Other(label) => label,
3498 }
3499 }
3500}
3501
3502impl From<&str> for PromptButton {
3503 fn from(value: &str) -> Self {
3504 match value.to_lowercase().as_str() {
3505 "ok" => PromptButton::Ok("OK".into()),
3506 "cancel" => PromptButton::Cancel("Cancel".into()),
3507 _ => PromptButton::Other(SharedString::from(value.to_owned())),
3508 }
3509 }
3510}
3511
3512#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
3514#[cfg_attr(feature = "schemars", derive(JsonSchema))]
3515pub enum CursorStyle {
3516 #[default]
3518 Arrow,
3519
3520 IBeam,
3523
3524 Crosshair,
3527
3528 ClosedHand,
3531
3532 OpenHand,
3535
3536 PointingHand,
3539
3540 ResizeLeft,
3543
3544 ResizeRight,
3547
3548 ResizeLeftRight,
3551
3552 ResizeUp,
3555
3556 ResizeDown,
3559
3560 ResizeUpDown,
3563
3564 ResizeUpLeftDownRight,
3567
3568 ResizeUpRightDownLeft,
3571
3572 ResizeColumn,
3575
3576 ResizeRow,
3579
3580 IBeamCursorForVerticalLayout,
3583
3584 OperationNotAllowed,
3587
3588 DragLink,
3591
3592 DragCopy,
3595
3596 ContextualMenu,
3599
3600 Help,
3602
3603 Progress,
3606
3607 Wait,
3609
3610 Move,
3612
3613 AllScroll,
3615
3616 Cell,
3618
3619 ZoomIn,
3621
3622 ZoomOut,
3624
3625 NoDrop,
3627
3628 Hidden,
3631}
3632
3633impl CursorStyle {
3634 pub const ALL: [Self; 31] = [
3636 Self::Arrow,
3637 Self::IBeam,
3638 Self::Crosshair,
3639 Self::ClosedHand,
3640 Self::OpenHand,
3641 Self::PointingHand,
3642 Self::ResizeLeft,
3643 Self::ResizeRight,
3644 Self::ResizeLeftRight,
3645 Self::ResizeUp,
3646 Self::ResizeDown,
3647 Self::ResizeUpDown,
3648 Self::ResizeUpLeftDownRight,
3649 Self::ResizeUpRightDownLeft,
3650 Self::ResizeColumn,
3651 Self::ResizeRow,
3652 Self::IBeamCursorForVerticalLayout,
3653 Self::OperationNotAllowed,
3654 Self::DragLink,
3655 Self::DragCopy,
3656 Self::ContextualMenu,
3657 Self::Help,
3658 Self::Progress,
3659 Self::Wait,
3660 Self::Move,
3661 Self::AllScroll,
3662 Self::Cell,
3663 Self::ZoomIn,
3664 Self::ZoomOut,
3665 Self::NoDrop,
3666 Self::Hidden,
3667 ];
3668
3669 pub fn iter() -> impl Iterator<Item = Self> {
3671 Self::ALL.into_iter()
3672 }
3673}
3674
3675#[derive(Clone, Debug, Eq, PartialEq)]
3677pub struct ClipboardItem {
3678 pub entries: Vec<ClipboardEntry>,
3680}
3681
3682#[derive(Clone, Debug, PartialEq, Eq)]
3687pub enum ClipboardReadError {
3688 Unavailable,
3692 Denied(String),
3695 UnsupportedContent,
3698}
3699
3700impl std::fmt::Display for ClipboardReadError {
3701 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3702 match self {
3703 Self::Unavailable => formatter.write_str("the clipboard is unavailable"),
3704 Self::Denied(message) => {
3705 write!(formatter, "clipboard access was denied: {message}")
3706 }
3707 Self::UnsupportedContent => {
3708 formatter.write_str("the clipboard contents are unsupported")
3709 }
3710 }
3711 }
3712}
3713
3714impl std::error::Error for ClipboardReadError {}
3715
3716#[derive(Clone, Debug, Eq, PartialEq)]
3718pub enum ClipboardEntry {
3719 String(ClipboardString),
3721 Image(Image),
3723 ExternalPaths(crate::ExternalPaths),
3725}
3726
3727impl ClipboardItem {
3728 pub fn new_string(text: String) -> Self {
3730 Self {
3731 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
3732 }
3733 }
3734
3735 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
3737 Self {
3738 entries: vec![ClipboardEntry::String(ClipboardString {
3739 text,
3740 metadata: Some(metadata),
3741 })],
3742 }
3743 }
3744
3745 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
3747 Self {
3748 entries: vec![ClipboardEntry::String(
3749 ClipboardString::new(text).with_json_metadata(metadata),
3750 )],
3751 }
3752 }
3753
3754 pub fn new_image(image: &Image) -> Self {
3756 Self {
3757 entries: vec![ClipboardEntry::Image(image.clone())],
3758 }
3759 }
3760
3761 pub fn text(&self) -> Option<String> {
3764 let mut answer = String::new();
3765
3766 for entry in self.entries.iter() {
3767 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
3768 answer.push_str(text);
3769 }
3770 }
3771
3772 if answer.is_empty() {
3773 for entry in self.entries.iter() {
3774 if let ClipboardEntry::ExternalPaths(paths) = entry {
3775 for path in &paths.0 {
3776 use std::fmt::Write as _;
3777 _ = write!(answer, "{}", path.display());
3778 }
3779 }
3780 }
3781 }
3782
3783 if !answer.is_empty() {
3784 Some(answer)
3785 } else {
3786 None
3787 }
3788 }
3789
3790 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
3792 pub fn metadata(&self) -> Option<&String> {
3793 match self.entries().first() {
3794 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
3795 clipboard_string.metadata.as_ref()
3796 }
3797 _ => None,
3798 }
3799 }
3800
3801 pub fn entries(&self) -> &[ClipboardEntry] {
3803 &self.entries
3804 }
3805
3806 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
3808 self.entries.into_iter()
3809 }
3810}
3811
3812impl From<ClipboardString> for ClipboardEntry {
3813 fn from(value: ClipboardString) -> Self {
3814 Self::String(value)
3815 }
3816}
3817
3818impl From<String> for ClipboardEntry {
3819 fn from(value: String) -> Self {
3820 Self::from(ClipboardString::from(value))
3821 }
3822}
3823
3824impl From<Image> for ClipboardEntry {
3825 fn from(value: Image) -> Self {
3826 Self::Image(value)
3827 }
3828}
3829
3830impl From<ClipboardEntry> for ClipboardItem {
3831 fn from(value: ClipboardEntry) -> Self {
3832 Self {
3833 entries: vec![value],
3834 }
3835 }
3836}
3837
3838impl From<String> for ClipboardItem {
3839 fn from(value: String) -> Self {
3840 Self::from(ClipboardEntry::from(value))
3841 }
3842}
3843
3844impl From<Image> for ClipboardItem {
3845 fn from(value: Image) -> Self {
3846 Self::from(ClipboardEntry::from(value))
3847 }
3848}
3849
3850#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3852pub enum ImageFormat {
3853 Png,
3858 Jpeg,
3860 Webp,
3862 Gif,
3864 Svg,
3866 Bmp,
3868 Tiff,
3870 Ico,
3872 Pnm,
3874}
3875
3876impl ImageFormat {
3877 pub const ALL: [Self; 9] = [
3879 Self::Png,
3880 Self::Jpeg,
3881 Self::Webp,
3882 Self::Gif,
3883 Self::Svg,
3884 Self::Bmp,
3885 Self::Tiff,
3886 Self::Ico,
3887 Self::Pnm,
3888 ];
3889
3890 pub fn iter() -> impl Iterator<Item = Self> {
3892 Self::ALL.into_iter()
3893 }
3894
3895 pub const fn mime_type(self) -> &'static str {
3897 match self {
3898 ImageFormat::Png => "image/png",
3899 ImageFormat::Jpeg => "image/jpeg",
3900 ImageFormat::Webp => "image/webp",
3901 ImageFormat::Gif => "image/gif",
3902 ImageFormat::Svg => "image/svg+xml",
3903 ImageFormat::Bmp => "image/bmp",
3904 ImageFormat::Tiff => "image/tiff",
3905 ImageFormat::Ico => "image/ico",
3906 ImageFormat::Pnm => "image/x-portable-anymap",
3907 }
3908 }
3909
3910 pub const fn extension(self) -> &'static str {
3912 match self {
3913 ImageFormat::Png => "png",
3914 ImageFormat::Jpeg => "jpg",
3915 ImageFormat::Webp => "webp",
3916 ImageFormat::Gif => "gif",
3917 ImageFormat::Svg => "svg",
3918 ImageFormat::Bmp => "bmp",
3919 ImageFormat::Tiff => "tiff",
3920 ImageFormat::Ico => "ico",
3921 ImageFormat::Pnm => "pnm",
3922 }
3923 }
3924
3925 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3927 Self::iter()
3928 .find(|format| format.mime_type() == mime_type)
3929 .or_else(|| Self::from_mime_type_alias(mime_type))
3930 }
3931
3932 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3936 match mime_type {
3937 "image/jpg" => Some(Self::Jpeg),
3938 "image/tif" => Some(Self::Tiff),
3939 _ => None,
3940 }
3941 }
3942}
3943
3944#[derive(Clone, Debug, PartialEq, Eq)]
3946pub struct Image {
3947 pub format: ImageFormat,
3949 pub bytes: Vec<u8>,
3951 pub id: u64,
3953}
3954
3955pub(crate) fn decode_static_image(
3956 bytes: &[u8],
3957 format: image::ImageFormat,
3958) -> Result<SmallVec<[Frame; 1]>> {
3959 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
3960 .into_decoder()
3961 .context("creating image decoder")?;
3962 decode_static_image_from_decoder(decoder)
3963}
3964
3965pub(crate) fn decode_static_image_from_decoder(
3966 mut decoder: impl image::ImageDecoder,
3967) -> Result<SmallVec<[Frame; 1]>> {
3968 let orientation = decoder
3969 .orientation()
3970 .context("reading decoder's orientation")?;
3971 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
3972 image.apply_orientation(orientation);
3973
3974 let mut data = image.into_rgba8();
3975 for pixel in data.chunks_exact_mut(4) {
3976 pixel.swap(0, 2);
3977 }
3978
3979 Ok(SmallVec::from_elem(Frame::new(data), 1))
3980}
3981
3982fn decode_animated_frames<'a>(
3983 decoder: impl image::AnimationDecoder<'a>,
3984 format_name: &str,
3985) -> Result<SmallVec<[Frame; 1]>> {
3986 let mut frames = SmallVec::new();
3987
3988 for frame in decoder.into_frames() {
3989 match frame {
3990 Ok(mut frame) => {
3991 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3993 pixel.swap(0, 2);
3994 }
3995 frames.push(frame);
3996 }
3997 Err(err) => {
3998 log::debug!("Skipping {format_name} frame due to decode error: {err}");
3999 }
4000 }
4001 }
4002
4003 if frames.is_empty() {
4004 anyhow::bail!("{format_name} could not be decoded: all frames failed");
4005 }
4006
4007 Ok(frames)
4008}
4009
4010pub(crate) fn decode_gif_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
4011 let decoder = GifDecoder::new(Cursor::new(bytes))?;
4012 decode_animated_frames(decoder, "GIF")
4013}
4014
4015pub(crate) fn decode_webp_image(bytes: &[u8]) -> Result<SmallVec<[Frame; 1]>> {
4016 let mut decoder = WebPDecoder::new(Cursor::new(bytes))?;
4017
4018 if decoder.has_animation() {
4019 let _ = decoder.set_background_color(Rgba([0, 0, 0, 0]));
4020 decode_animated_frames(decoder, "WebP")
4021 } else {
4022 decode_static_image_from_decoder(decoder)
4023 }
4024}
4025
4026impl Hash for Image {
4027 fn hash<H: Hasher>(&self, state: &mut H) {
4028 state.write_u64(self.id);
4029 }
4030}
4031
4032impl Image {
4033 pub fn empty() -> Self {
4035 Self::from_bytes(ImageFormat::Png, Vec::new())
4036 }
4037
4038 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
4040 Self {
4041 id: hash(&bytes),
4042 format,
4043 bytes,
4044 }
4045 }
4046
4047 pub fn id(&self) -> u64 {
4049 self.id
4050 }
4051
4052 pub fn use_render_image(
4054 self: Arc<Self>,
4055 window: &mut Window,
4056 cx: &mut App,
4057 ) -> Option<Arc<RenderImage>> {
4058 ImageSource::Image(self)
4059 .use_data(None, window, cx)
4060 .and_then(|result| result.ok())
4061 }
4062
4063 pub fn get_render_image(
4065 self: Arc<Self>,
4066 window: &mut Window,
4067 cx: &mut App,
4068 ) -> Option<Arc<RenderImage>> {
4069 ImageSource::Image(self)
4070 .get_data(None, window, cx)
4071 .and_then(|result| result.ok())
4072 }
4073
4074 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
4076 ImageSource::Image(self).remove_asset(cx);
4077 }
4078
4079 #[cfg(any(test, feature = "test-support"))]
4082 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
4083 ImageSource::Image(self.clone()).is_asset_cached(cx)
4084 }
4085
4086 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
4088 let frames = match self.format {
4089 ImageFormat::Gif => decode_gif_image(&self.bytes)?,
4090 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
4091 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
4092 ImageFormat::Webp => decode_webp_image(&self.bytes)?,
4093 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
4094 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
4095 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
4096 ImageFormat::Svg => {
4097 return svg_renderer
4098 .render_single_frame(&self.bytes, 1.0)
4099 .map_err(Into::into);
4100 }
4101 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
4102 };
4103
4104 Ok(Arc::new(RenderImage::new(frames)))
4105 }
4106
4107 pub fn format(&self) -> ImageFormat {
4109 self.format
4110 }
4111
4112 pub fn bytes(&self) -> &[u8] {
4114 self.bytes.as_slice()
4115 }
4116}
4117
4118#[derive(Clone, Debug, Eq, PartialEq)]
4120pub struct ClipboardString {
4121 pub text: String,
4123 pub metadata: Option<String>,
4125}
4126
4127impl ClipboardString {
4128 pub fn new(text: String) -> Self {
4130 Self {
4131 text,
4132 metadata: None,
4133 }
4134 }
4135
4136 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
4139 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
4140 self
4141 }
4142
4143 pub fn text(&self) -> &String {
4145 &self.text
4146 }
4147
4148 pub fn into_text(self) -> String {
4150 self.text
4151 }
4152
4153 pub fn metadata_json<T>(&self) -> Option<T>
4155 where
4156 T: for<'a> Deserialize<'a>,
4157 {
4158 self.metadata
4159 .as_ref()
4160 .and_then(|m| serde_json::from_str(m).ok())
4161 }
4162
4163 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
4164 pub fn text_hash(text: &str) -> u64 {
4166 let mut hasher = SeaHasher::new();
4167 text.hash(&mut hasher);
4168 hasher.finish()
4169 }
4170}
4171
4172impl From<String> for ClipboardString {
4173 fn from(value: String) -> Self {
4174 Self {
4175 text: value,
4176 metadata: None,
4177 }
4178 }
4179}
4180
4181#[cfg(test)]
4182mod image_tests {
4183 use super::*;
4184 use std::sync::Arc;
4185
4186 #[test]
4187 fn test_image_to_image_data_applies_exif_orientation() {
4188 let image = Image::from_bytes(
4189 ImageFormat::Jpeg,
4190 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
4191 );
4192
4193 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4194
4195 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
4196
4197 let bytes = render_image.as_bytes(0).unwrap();
4198 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
4199 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
4200 }
4201
4202 #[test]
4203 fn test_svg_image_to_image_data_converts_to_bgra() {
4204 let image = Image::from_bytes(
4205 ImageFormat::Svg,
4206 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
4207<rect width="1" height="1" fill="#38BDF8"/>
4208</svg>"##
4209 .to_vec(),
4210 );
4211
4212 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4213 let bytes = render_image.as_bytes(0).unwrap();
4214
4215 for pixel in bytes.chunks_exact(4) {
4216 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
4217 }
4218 }
4219
4220 #[test]
4221 fn test_animated_webp_image_to_image_data_decodes_frames() {
4222 const ANIMATED_WEBP: &[u8] = &[
4224 82, 73, 70, 70, 192, 0, 0, 0, 87, 69, 66, 80, 86, 80, 56, 88, 10, 0, 0, 0, 2, 0, 0, 0,
4225 0, 0, 0, 0, 0, 0, 65, 78, 73, 77, 6, 0, 0, 0, 255, 255, 255, 255, 0, 0, 65, 78, 77, 70,
4226 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,
4227 0, 0, 208, 1, 0, 157, 1, 42, 1, 0, 1, 0, 2, 0, 52, 37, 160, 2, 116, 186, 1, 248, 0, 3,
4228 176, 0, 254, 240, 196, 11, 255, 32, 185, 97, 117, 200, 215, 255, 32, 63, 228, 7, 252,
4229 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,
4230 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,
4231 0, 52, 37, 160, 2, 116, 186, 0, 3, 152, 0, 254, 249, 147, 111, 255, 144, 31, 255, 144,
4232 31, 255, 144, 31, 255, 32, 63, 226, 23, 123, 32, 48, 0,
4233 ];
4234
4235 let image = Image::from_bytes(ImageFormat::Webp, ANIMATED_WEBP.to_vec());
4236 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
4237
4238 assert_eq!(render_image.frame_count(), 2);
4239 assert_eq!(render_image.size(0), size(1.into(), 1.into()));
4240 assert_eq!(
4241 Duration::from(render_image.delay(0)),
4242 Duration::from_millis(100)
4243 );
4244 assert_eq!(
4245 Duration::from(render_image.delay(1)),
4246 Duration::from_millis(100)
4247 );
4248 }
4249}
4250
4251#[cfg(test)]
4252mod atlas_tests {
4253 use super::*;
4254
4255 const TILE_SIZE: Size<DevicePixels> = Size {
4256 width: DevicePixels(1),
4257 height: DevicePixels(1),
4258 };
4259
4260 #[derive(Default)]
4261 struct RecordingAtlasBackend {
4262 insert_calls: u32,
4263 fail_next_insert: bool,
4264 removed_tiles: Vec<AtlasTile>,
4265 }
4266
4267 impl AtlasBackend for RecordingAtlasBackend {
4268 fn insert(
4269 &mut self,
4270 kind: AtlasTextureKind,
4271 size: Size<DevicePixels>,
4272 _bytes: &[u8],
4273 ) -> Result<AtlasTile> {
4274 self.insert_calls += 1;
4275 if std::mem::take(&mut self.fail_next_insert) {
4276 anyhow::bail!("backend failed");
4277 }
4278 Ok(AtlasTile {
4279 texture_id: AtlasTextureId { index: 0, kind },
4280 tile_id: TileId(self.insert_calls),
4281 padding: 0,
4282 bounds: Bounds {
4283 origin: Point::default(),
4284 size,
4285 },
4286 })
4287 }
4288
4289 fn remove(&mut self, tile: AtlasTile) {
4290 self.removed_tiles.push(tile);
4291 }
4292 }
4293
4294 fn image_key(image_id: usize) -> AtlasKey {
4295 AtlasKey::Image(RenderImageParams {
4296 image_id: crate::ImageId(image_id),
4297 frame_index: 0,
4298 })
4299 }
4300
4301 fn build_tile() -> Result<Option<(Size<DevicePixels>, Cow<'static, [u8]>)>> {
4302 Ok(Some((TILE_SIZE, Cow::Borrowed(&[0, 0, 0, 255]))))
4303 }
4304
4305 #[test]
4306 fn only_successful_inserts_are_cached() -> Result<()> {
4307 let mut state = AtlasState::new(RecordingAtlasBackend::default());
4308 let key = image_key(1);
4309
4310 assert_eq!(
4311 state.get_or_insert_with(key.clone(), &mut || Ok(None))?,
4312 None
4313 );
4314 state
4315 .get_or_insert_with(key.clone(), &mut || anyhow::bail!("builder failed"))
4316 .expect_err("builder error should propagate");
4317 assert!(!state.contains(&key));
4318 assert_eq!(state.backend.insert_calls, 0);
4319
4320 state.backend.fail_next_insert = true;
4321 state
4322 .get_or_insert_with(key.clone(), &mut build_tile)
4323 .expect_err("backend error should propagate");
4324 assert!(!state.contains(&key));
4325 assert_eq!(state.backend.insert_calls, 1);
4326
4327 let tile = state
4328 .get_or_insert_with(key.clone(), &mut build_tile)?
4329 .context("builder should produce a tile")?;
4330 assert_eq!(tile.texture_id.kind, key.texture_kind());
4331 assert_eq!(
4332 state.get_or_insert_with(key.clone(), &mut || {
4333 anyhow::bail!("cache hit must not call the builder")
4334 })?,
4335 Some(tile)
4336 );
4337 assert!(state.contains(&key));
4338 assert_eq!(state.backend.insert_calls, 2);
4339 Ok(())
4340 }
4341
4342 #[test]
4343 fn remove_and_clear_invalidate_keys() -> Result<()> {
4344 let mut state = AtlasState::new(RecordingAtlasBackend::default());
4345 let key = image_key(1);
4346 let other_key = image_key(2);
4347 let tile = state
4348 .get_or_insert_with(key.clone(), &mut build_tile)?
4349 .context("builder should produce a tile")?;
4350 state
4351 .get_or_insert_with(other_key.clone(), &mut build_tile)?
4352 .context("builder should produce another tile")?;
4353
4354 state.remove(&key);
4355 state.remove(&key);
4356 assert!(!state.contains(&key));
4357 assert!(state.contains(&other_key));
4358 assert_eq!(state.backend.removed_tiles, vec![tile]);
4359
4360 let mut reset_calls = 0;
4361 state.clear(|_| reset_calls += 1);
4362 assert_eq!(reset_calls, 1);
4363 assert!(!state.contains(&other_key));
4364 assert_eq!(state.backend.removed_tiles, vec![tile]);
4365 Ok(())
4366 }
4367}
4368
4369#[cfg(test)]
4370mod frame_signal_tests {
4371 use super::*;
4372
4373 #[cfg(feature = "profiler")]
4374 #[test]
4375 fn coalesced_signals_retain_the_earliest_until_drained() {
4376 for (first_source, later_source) in [
4377 (
4378 FrameRequestSource::NativeCallback,
4379 FrameRequestSource::LocalSchedule,
4380 ),
4381 (
4382 FrameRequestSource::LocalSchedule,
4383 FrameRequestSource::NativeCallback,
4384 ),
4385 ] {
4386 let signal = PlatformFrameSignal::new();
4387 let first =
4388 PlatformFrameSignal::capture(Instant::now).expect("profiling captures requests");
4389 assert_eq!(signal.take(), None);
4390 signal.record(first + Duration::from_millis(16), later_source);
4391 signal.record(first, first_source);
4392 signal.record(first + Duration::from_millis(32), later_source);
4393 assert_eq!(signal.take(), Some((first, first_source)));
4394 assert_eq!(signal.take(), None);
4395 let next = first + Duration::from_millis(48);
4396 signal.record(next, later_source);
4397 assert_eq!(signal.take(), Some((next, later_source)));
4398 }
4399 }
4400
4401 #[cfg(not(feature = "profiler"))]
4402 #[test]
4403 fn disabled_profiling_does_not_capture_or_store_timestamps() {
4404 let captured = PlatformFrameSignal::capture(|| {
4405 panic!("profiler-disabled builds must not evaluate the capture closure");
4406 });
4407 assert_eq!(captured, None);
4408 let signal = PlatformFrameSignal::new();
4409 signal.record(Instant::now(), FrameRequestSource::LocalSchedule);
4410 assert_eq!(signal.take(), None);
4411 }
4412}
4413
4414#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
4415mod tests {
4416 use super::*;
4417 use std::collections::HashSet;
4418
4419 #[test]
4420 fn test_refresh_interval_from_hz() {
4421 assert_eq!(
4422 refresh_interval_from_hz(50.0),
4423 Some(Duration::from_millis(20))
4424 );
4425 assert_eq!(
4426 refresh_interval_from_hz(120.0),
4427 Some(Duration::from_secs(1) / 120)
4428 );
4429 for unknown in [0.0, -60.0, f64::NAN, f64::INFINITY] {
4430 assert_eq!(refresh_interval_from_hz(unknown), None);
4431 }
4432 }
4433
4434 #[test]
4435 fn test_window_button_layout_parse_standard() {
4436 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
4437 assert_eq!(
4438 layout.left,
4439 [
4440 Some(WindowButton::Close),
4441 Some(WindowButton::Minimize),
4442 None
4443 ]
4444 );
4445 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4446 }
4447
4448 #[test]
4449 fn test_window_button_layout_parse_right_only() {
4450 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
4451 assert_eq!(layout.left, [None, None, None]);
4452 assert_eq!(
4453 layout.right,
4454 [
4455 Some(WindowButton::Minimize),
4456 Some(WindowButton::Maximize),
4457 Some(WindowButton::Close)
4458 ]
4459 );
4460 }
4461
4462 #[test]
4463 fn test_window_button_layout_parse_left_only() {
4464 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
4465 assert_eq!(
4466 layout.left,
4467 [
4468 Some(WindowButton::Close),
4469 Some(WindowButton::Minimize),
4470 Some(WindowButton::Maximize)
4471 ]
4472 );
4473 assert_eq!(layout.right, [None, None, None]);
4474 }
4475
4476 #[test]
4477 fn test_window_button_layout_parse_with_whitespace() {
4478 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
4479 assert_eq!(
4480 layout.left,
4481 [
4482 Some(WindowButton::Close),
4483 Some(WindowButton::Minimize),
4484 None
4485 ]
4486 );
4487 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4488 }
4489
4490 #[test]
4491 fn test_window_button_layout_parse_empty() {
4492 let layout = WindowButtonLayout::parse("").unwrap();
4493 assert_eq!(layout.left, [None, None, None]);
4494 assert_eq!(layout.right, [None, None, None]);
4495 }
4496
4497 #[test]
4498 fn test_window_button_layout_parse_intentionally_empty() {
4499 let layout = WindowButtonLayout::parse(":").unwrap();
4500 assert_eq!(layout.left, [None, None, None]);
4501 assert_eq!(layout.right, [None, None, None]);
4502 }
4503
4504 #[test]
4505 fn test_window_button_layout_parse_invalid_buttons() {
4506 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
4507 assert_eq!(
4508 layout.left,
4509 [
4510 Some(WindowButton::Close),
4511 Some(WindowButton::Minimize),
4512 None
4513 ]
4514 );
4515 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4516 }
4517
4518 #[test]
4519 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
4520 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
4521 assert_eq!(
4522 layout.right,
4523 [
4524 Some(WindowButton::Close),
4525 Some(WindowButton::Minimize),
4526 None
4527 ]
4528 );
4529 assert_eq!(layout.format(), ":close,minimize");
4530 }
4531
4532 #[test]
4533 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
4534 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
4535 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4536 assert_eq!(
4537 layout.right,
4538 [
4539 Some(WindowButton::Maximize),
4540 Some(WindowButton::Minimize),
4541 None
4542 ]
4543 );
4544
4545 let button_ids: Vec<_> = layout
4546 .left
4547 .iter()
4548 .chain(layout.right.iter())
4549 .flatten()
4550 .map(WindowButton::id)
4551 .collect();
4552 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
4553 assert_eq!(unique_button_ids.len(), button_ids.len());
4554 assert_eq!(layout.format(), "close:maximize,minimize");
4555 }
4556
4557 #[test]
4558 fn test_window_button_layout_parse_gnome_style() {
4559 let layout = WindowButtonLayout::parse("close").unwrap();
4560 assert_eq!(layout.left, [None, None, None]);
4561 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
4562 }
4563
4564 #[test]
4565 fn test_window_button_layout_parse_elementary_style() {
4566 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
4567 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
4568 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
4569 }
4570
4571 #[test]
4572 fn test_window_button_layout_round_trip() {
4573 let cases = [
4574 "close:minimize,maximize",
4575 "minimize,maximize,close:",
4576 ":close",
4577 "close:",
4578 "close:maximize",
4579 ":",
4580 ];
4581
4582 for case in cases {
4583 let layout = WindowButtonLayout::parse(case).unwrap();
4584 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
4585 }
4586 }
4587
4588 #[test]
4589 fn test_window_button_layout_linux_default() {
4590 let layout = WindowButtonLayout::linux_default();
4591 assert_eq!(layout.left, [None, None, None]);
4592 assert_eq!(
4593 layout.right,
4594 [
4595 Some(WindowButton::Minimize),
4596 Some(WindowButton::Maximize),
4597 Some(WindowButton::Close)
4598 ]
4599 );
4600
4601 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
4602 assert_eq!(round_tripped, layout);
4603 }
4604
4605 #[test]
4606 fn test_window_button_layout_parse_all_invalid() {
4607 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
4608 }
4609}