1mod app_menu;
4mod keyboard;
5mod keystroke;
6
7pub mod popup;
9
10#[cfg(all(
11 any(test, feature = "test-support"),
12 any(
13 target_os = "windows",
14 target_os = "linux",
15 target_os = "macos",
16 target_family = "wasm"
17 )
18))]
19mod threaded_dispatcher;
20
21#[cfg(target_os = "linux")]
24pub mod layer_shell;
25
26#[cfg(any(test, feature = "test-support"))]
27#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
28mod test;
30
31#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
32#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
33mod visual_test;
35
36#[cfg(all(
37 feature = "screen-capture",
38 any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
39))]
40pub mod scap_screen_capture;
41
42#[cfg(all(
43 any(target_os = "windows", target_os = "linux"),
44 feature = "screen-capture"
45))]
46pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
47#[cfg(not(feature = "screen-capture"))]
48pub(crate) type PlatformScreenCaptureFrame = ();
49#[cfg(all(target_os = "macos", feature = "screen-capture"))]
50pub(crate) type PlatformScreenCaptureFrame = core_video::image_buffer::CVImageBuffer;
51
52use crate::menu::NativeMenu;
53use crate::rgpui_util;
54use crate::scheduler::Instant;
55pub use crate::scheduler::RunnableMeta;
56use crate::{
57 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
58 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun,
59 ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap, LineLayout, Pixels,
60 PlatformInput, Point, Priority, RenderGlyphParams, RenderImage, RenderImageParams,
61 RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString, Size, SvgRenderer,
62 SystemWindowTab, Task, Window, WindowControlArea, hash, point, px, size,
63};
64use crate::{Tray, TrayIconEvent, TrayMenuItem};
65use anyhow::Result;
66#[cfg(any(target_os = "linux", target_os = "freebsd"))]
67use anyhow::bail;
68use async_task::Runnable;
69use futures::channel::oneshot;
70#[cfg(any(test, feature = "test-support"))]
71use image::RgbaImage;
72use image::codecs::gif::GifDecoder;
73use image::{AnimationDecoder as _, Frame};
74use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
75use schemars::JsonSchema;
76use seahash::SeaHasher;
77use serde::{Deserialize, Serialize};
78use smallvec::SmallVec;
79use std::borrow::Cow;
80use std::hash::{Hash, Hasher};
81use std::io::Cursor;
82use std::ops;
83use std::time::Duration;
84use std::{
85 fmt::{self, Debug},
86 ops::Range,
87 path::{Path, PathBuf},
88 rc::Rc,
89 sync::Arc,
90};
91use strum::EnumIter;
92use uuid::Uuid;
93
94#[inline]
99#[allow(clippy::panic)] fn invariant<T>(value: Option<T>, message: &str) -> T {
101 match value {
102 Some(value) => value,
103 None => panic!("{message}"),
104 }
105}
106
107#[inline]
109#[allow(clippy::panic)] fn invariant_result<T, E>(result: Result<T, E>, message: &str) -> T {
111 match result {
112 Ok(value) => value,
113 Err(_) => panic!("{message}"),
114 }
115}
116
117pub use app_menu::*;
118pub use keyboard::*;
119pub use keystroke::*;
120
121#[cfg(any(test, feature = "test-support"))]
122pub(crate) use test::*;
123
124#[cfg(any(test, feature = "test-support"))]
125pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
126
127#[cfg(all(
128 any(test, feature = "test-support"),
129 any(
130 target_os = "windows",
131 target_os = "linux",
132 target_os = "macos",
133 target_family = "wasm"
134 )
135))]
136pub use threaded_dispatcher::ThreadedDispatcher;
137
138#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
139pub use visual_test::VisualTestPlatform;
140
141#[cfg(any(target_os = "linux", target_os = "freebsd"))]
145#[inline]
146pub fn guess_compositor() -> &'static str {
147 if std::env::var_os("ZED_HEADLESS").is_some() {
148 return "Headless";
149 }
150
151 #[cfg(feature = "wayland")]
152 let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
153 #[cfg(not(feature = "wayland"))]
154 let wayland_display: Option<std::ffi::OsString> = None;
155
156 #[cfg(feature = "x11")]
157 let x11_display = std::env::var_os("DISPLAY");
158 #[cfg(not(feature = "x11"))]
159 let x11_display: Option<std::ffi::OsString> = None;
160
161 let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
162 let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
163
164 if use_wayland {
165 "Wayland"
166 } else if use_x11 {
167 "X11"
168 } else {
169 "Headless"
170 }
171}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub enum SystemPowerEvent {
180 Sleep,
182 WakeUp,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum PowerSaveBlockerKind {
189 PreventSleep,
191 PreventDisplaySleep,
193}
194
195pub trait PowerSaveBlocker: Send {}
200
201#[derive(Debug, Clone)]
203pub struct OsInfo {
204 pub name: String,
206 pub version: String,
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub enum PermissionStatus {
213 NotDetermined,
215 Granted,
217 Denied,
219 Unavailable,
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum PermissionType {
228 Accessibility,
232
233 ScreenCapture,
237
238 InputMonitoring,
242}
243
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum NetworkStatus {
247 Disconnected,
249 ConnectedBelowRequired,
251 Connected,
253}
254
255#[derive(Debug, Clone)]
257pub struct FocusedWindowInfo {
258 pub app_name: String,
260 pub window_title: String,
262 pub bundle_id: Option<String>,
264 pub pid: Option<u32>,
266}
267
268#[derive(Debug, Clone, Copy, PartialEq)]
270pub enum WindowPosition {
271 Center,
273 CenterOnDisplay(DisplayId),
275 TrayCenter(Bounds<Pixels>),
277 TopRight {
279 margin: Pixels,
281 },
282 BottomRight {
284 margin: Pixels,
286 },
287 TopLeft {
289 margin: Pixels,
291 },
292 BottomLeft {
294 margin: Pixels,
296 },
297}
298
299pub trait Platform: 'static {
304 fn background_executor(&self) -> BackgroundExecutor;
306 fn foreground_executor(&self) -> ForegroundExecutor;
308 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
310
311 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
313 fn quit(&self);
315 fn restart(&self, binary_path: Option<PathBuf>);
317 fn activate(&self, ignoring_other_apps: bool);
319 fn hide(&self);
321 fn hide_other_apps(&self);
323 fn unhide_other_apps(&self);
325
326 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
328 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
330 fn active_window(&self) -> Option<AnyWindowHandle>;
332 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
334 None
335 }
336
337 fn is_screen_capture_supported(&self) -> bool {
339 false
340 }
341
342 fn screen_capture_sources(
344 &self,
345 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
346 let (sources_tx, sources_rx) = oneshot::channel();
347 sources_tx
348 .send(Err(anyhow::anyhow!(
349 "rgpui was compiled without the screen-capture feature"
350 )))
351 .ok();
352 sources_rx
353 }
354
355 fn open_window(
357 &self,
358 handle: AnyWindowHandle,
359 options: WindowParams,
360 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
361
362 fn window_appearance(&self) -> WindowAppearance;
364
365 fn reduce_motion_enabled(&self) -> bool {
370 false
371 }
372
373 fn button_layout(&self) -> Option<WindowButtonLayout> {
375 None
376 }
377
378 fn open_url(&self, url: &str);
383 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
389 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
391
392 fn prompt_for_paths(
394 &self,
395 options: PathPromptOptions,
396 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
397 fn prompt_for_new_path(
399 &self,
400 directory: &Path,
401 suggested_name: Option<&str>,
402 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
403 fn can_select_mixed_files_and_dirs(&self) -> bool;
405 fn reveal_path(&self, path: &Path);
409 fn open_with_system(&self, path: &Path);
411
412 fn on_quit(&self, callback: Box<dyn FnMut()>);
414 fn on_reopen(&self, callback: Box<dyn FnMut()>);
416
417 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
419 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
421 None
422 }
423
424 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
426 fn perform_dock_menu_action(&self, _action: usize) {}
428 fn add_recent_document(&self, _path: &Path) {}
430 fn update_jump_list(
432 &self,
433 _menus: Vec<MenuItem>,
434 _entries: Vec<SmallVec<[PathBuf; 2]>>,
435 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
436 Task::ready(Vec::new())
437 }
438 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
440 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
442 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
444
445 fn thermal_state(&self) -> ThermalState;
447 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
449
450 fn compositor_name(&self) -> &'static str {
452 ""
453 }
454 fn app_path(&self) -> Result<PathBuf>;
456 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
458
459 fn set_cursor_style(&self, style: CursorStyle);
461
462 fn hide_cursor_until_mouse_moves(&self);
464
465 fn is_cursor_visible(&self) -> bool;
467
468 fn should_auto_hide_scrollbars(&self) -> bool;
470
471 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
473 fn write_to_clipboard(&self, item: ClipboardItem);
475
476 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
478 fn read_from_primary(&self) -> Option<ClipboardItem>;
479 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
481 fn write_to_primary(&self, item: ClipboardItem);
482
483 #[cfg(target_os = "macos")]
485 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
486 #[cfg(target_os = "macos")]
488 fn write_to_find_pasteboard(&self, item: ClipboardItem);
489
490 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
492 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
494 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
496
497 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
499 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
501 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
503
504 fn set_tray(&self, _tray: Tray, _menus: Option<Vec<MenuItem>>, _keymap: &Keymap) {}
506 fn set_tray_icon(&self, _icon: Option<&[u8]>) {}
508 fn set_tray_menu(&self, _menu: Vec<TrayMenuItem>) {}
510 fn set_tray_tooltip(&self, _tooltip: &str) {}
512 fn set_tray_panel_mode(&self, _enabled: bool) {}
514 fn get_tray_icon_bounds(&self) -> Option<Bounds<Pixels>> {
516 None
517 }
518 fn on_tray_icon_event(&self, _callback: Box<dyn FnMut(TrayIconEvent)>) {}
520 fn on_tray_menu_action(&self, _callback: Box<dyn FnMut(SharedString)>) {}
522
523 fn register_global_hotkey(&self, _id: u32, _keystroke: &Keystroke) -> Result<()> {
528 Ok(())
529 }
530 fn unregister_global_hotkey(&self, _id: u32) {}
532 fn on_global_hotkey(&self, _callback: Box<dyn FnMut(u32)>) {}
534
535 fn show_notification(&self, _title: &str, _body: &str) -> Result<()> {
540 Ok(())
541 }
542
543 fn set_auto_launch(&self, _app_id: &str, _enabled: bool) -> Result<()> {
548 Ok(())
549 }
550 fn is_auto_launch_enabled(&self, _app_id: &str) -> bool {
552 false
553 }
554
555 fn focused_window_info(&self) -> Option<FocusedWindowInfo> {
561 None
562 }
563
564 fn check_permission(&self, _kind: PermissionType) -> PermissionStatus {
572 PermissionStatus::Unavailable
573 }
574 fn request_permission(&self, _kind: PermissionType) {}
576
577 fn on_system_power_event(&self, _callback: Box<dyn FnMut(SystemPowerEvent)>) {}
579
580 fn on_system_wake(&self, _callback: Box<dyn FnMut()>) {}
582
583 fn start_power_save_blocker(
591 &self,
592 _kind: PowerSaveBlockerKind,
593 ) -> Option<Box<dyn PowerSaveBlocker>> {
594 None
595 }
596
597 fn system_idle_time(&self) -> Option<Duration> {
599 None
600 }
601
602 fn network_status(&self) -> NetworkStatus {
604 NetworkStatus::Connected
605 }
606
607 fn os_info(&self) -> OsInfo {
609 OsInfo {
610 name: String::new(),
611 version: String::new(),
612 }
613 }
614}
615
616pub trait PlatformDisplay: Debug {
618 fn id(&self) -> DisplayId;
620
621 fn uuid(&self) -> Result<Uuid>;
623
624 fn bounds(&self) -> Bounds<Pixels>;
626
627 fn visible_bounds(&self) -> Bounds<Pixels> {
631 self.bounds()
632 }
633
634 fn default_bounds(&self) -> Bounds<Pixels> {
636 let bounds = self.bounds();
637 let center = bounds.center();
638 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
639
640 let offset = clipped_window_size / 2.0;
641 let origin = point(center.x - offset.width, center.y - offset.height);
642 Bounds::new(origin, clipped_window_size)
643 }
644}
645
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648pub enum ThermalState {
649 Nominal,
651 Fair,
653 Serious,
655 Critical,
657}
658
659#[derive(Clone)]
661pub struct SourceMetadata {
662 pub id: u64,
664 pub label: Option<SharedString>,
666 pub is_main: Option<bool>,
668 pub resolution: Size<DevicePixels>,
670}
671
672pub trait ScreenCaptureSource {
674 fn metadata(&self) -> Result<SourceMetadata>;
676
677 fn stream(
679 &self,
680 foreground_executor: &ForegroundExecutor,
681 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
682 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
683}
684
685pub trait ScreenCaptureStream {
687 fn metadata(&self) -> Result<SourceMetadata>;
689}
690
691pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
693
694#[cfg(all(
695 any(target_os = "windows", target_os = "linux"),
696 feature = "screen-capture"
697))]
698impl ScreenCaptureFrame {
699 pub fn width(&self) -> u32 {
701 match &self.0 {
702 scap::frame::Frame::YUVFrame(f) => f.width as u32,
703 scap::frame::Frame::RGB(f) => f.width as u32,
704 scap::frame::Frame::RGBx(f) => f.width as u32,
705 scap::frame::Frame::XBGR(f) => f.width as u32,
706 scap::frame::Frame::BGRx(f) => f.width as u32,
707 scap::frame::Frame::BGR0(f) => f.width as u32,
708 scap::frame::Frame::BGRA(f) => f.width as u32,
709 }
710 }
711
712 pub fn height(&self) -> u32 {
714 match &self.0 {
715 scap::frame::Frame::YUVFrame(f) => f.height as u32,
716 scap::frame::Frame::RGB(f) => f.height as u32,
717 scap::frame::Frame::RGBx(f) => f.height as u32,
718 scap::frame::Frame::XBGR(f) => f.height as u32,
719 scap::frame::Frame::BGRx(f) => f.height as u32,
720 scap::frame::Frame::BGR0(f) => f.height as u32,
721 scap::frame::Frame::BGRA(f) => f.height as u32,
722 }
723 }
724
725 pub fn to_rgba(&self) -> Option<image::RgbaImage> {
730 match &self.0 {
731 scap::frame::Frame::BGRA(f) => {
732 let w = f.width as u32;
733 let h = f.height as u32;
734 let mut rgba = Vec::with_capacity((w * h * 4) as usize);
735 for chunk in f.data.chunks_exact(4) {
736 rgba.push(chunk[2]); rgba.push(chunk[1]); rgba.push(chunk[0]); rgba.push(chunk[3]); }
741 image::RgbaImage::from_raw(w, h, rgba)
742 }
743 scap::frame::Frame::BGR0(f) => {
744 let w = f.width as u32;
745 let h = f.height as u32;
746 let mut rgba = Vec::with_capacity((w * h * 4) as usize);
747 for chunk in f.data.chunks_exact(4) {
748 rgba.push(chunk[2]); rgba.push(chunk[1]); rgba.push(chunk[0]); rgba.push(255); }
753 image::RgbaImage::from_raw(w, h, rgba)
754 }
755 scap::frame::Frame::BGRx(f) => {
756 let w = f.width as u32;
757 let h = f.height as u32;
758 let mut rgba = Vec::with_capacity((w * h * 4) as usize);
759 for chunk in f.data.chunks_exact(4) {
760 rgba.push(chunk[2]); rgba.push(chunk[1]); rgba.push(chunk[0]); rgba.push(255); }
765 image::RgbaImage::from_raw(w, h, rgba)
766 }
767 scap::frame::Frame::XBGR(f) => {
768 let w = f.width as u32;
769 let h = f.height as u32;
770 let mut rgba = Vec::with_capacity((w * h * 4) as usize);
771 for chunk in f.data.chunks_exact(4) {
772 rgba.push(chunk[3]); rgba.push(chunk[2]); rgba.push(chunk[1]); rgba.push(255); }
777 image::RgbaImage::from_raw(w, h, rgba)
778 }
779 scap::frame::Frame::RGB(f) => {
780 let w = f.width as u32;
781 let h = f.height as u32;
782 let mut rgba = Vec::with_capacity((w * h * 4) as usize);
783 for chunk in f.data.chunks_exact(3) {
784 rgba.push(chunk[0]); rgba.push(chunk[1]); rgba.push(chunk[2]); rgba.push(255); }
789 image::RgbaImage::from_raw(w, h, rgba)
790 }
791 scap::frame::Frame::RGBx(f) => {
792 let w = f.width as u32;
793 let h = f.height as u32;
794 let mut rgba = Vec::with_capacity((w * h * 4) as usize);
795 for chunk in f.data.chunks_exact(4) {
796 rgba.push(chunk[0]); rgba.push(chunk[1]); rgba.push(chunk[2]); rgba.push(255); }
801 image::RgbaImage::from_raw(w, h, rgba)
802 }
803 scap::frame::Frame::YUVFrame(f) => {
804 let w = f.width as u32;
805 let h = f.height as u32;
806 let mut rgba = Vec::with_capacity((w * h * 4) as usize);
807
808 let y_plane = &f.luminance_bytes;
810 let uv_plane = &f.chrominance_bytes;
811 let y_stride = f.luminance_stride as usize;
812 let uv_stride = f.chrominance_stride as usize;
813
814 for row in 0..h as usize {
815 for col in 0..w as usize {
816 let y_idx = row * y_stride + col;
818 let y = if y_idx < y_plane.len() {
819 y_plane[y_idx] as i32
820 } else {
821 0
822 };
823
824 let uv_row = row / 2;
826 let uv_col = (col / 2) * 2;
827 let uv_idx = uv_row * uv_stride + uv_col;
828 let u = if uv_idx < uv_plane.len() {
829 uv_plane[uv_idx] as i32
830 } else {
831 128
832 };
833 let v = if uv_idx + 1 < uv_plane.len() {
834 uv_plane[uv_idx + 1] as i32
835 } else {
836 128
837 };
838
839 let c = 298 * (y - 16);
841 let r = ((c + 409 * (v - 128) + 128) >> 8).clamp(0, 255) as u8;
842 let g = ((c - 100 * (u - 128) - 208 * (v - 128) + 128) >> 8).clamp(0, 255)
843 as u8;
844 let b = ((c + 516 * (u - 128) + 128) >> 8).clamp(0, 255) as u8;
845
846 rgba.push(r);
847 rgba.push(g);
848 rgba.push(b);
849 rgba.push(255); }
851 }
852 image::RgbaImage::from_raw(w, h, rgba)
853 }
854 }
855 }
856}
857
858#[cfg(all(target_os = "macos", feature = "screen-capture"))]
859impl ScreenCaptureFrame {
860 pub fn width(&self) -> u32 {
862 0
863 }
864
865 pub fn height(&self) -> u32 {
867 0
868 }
869
870 pub fn to_rgba(&self) -> Option<image::RgbaImage> {
872 None
873 }
874}
875
876#[derive(PartialEq, Eq, Hash, Copy, Clone)]
878pub struct DisplayId(pub(crate) u64);
879
880impl DisplayId {
881 pub fn new(id: u64) -> Self {
883 Self(id)
884 }
885}
886
887impl From<u64> for DisplayId {
888 fn from(id: u64) -> Self {
889 Self(id)
890 }
891}
892
893impl From<DisplayId> for u64 {
894 fn from(id: DisplayId) -> Self {
895 id.0
896 }
897}
898
899impl Debug for DisplayId {
900 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901 write!(f, "DisplayId({})", self.0)
902 }
903}
904
905#[derive(Debug, Clone, Copy, PartialEq, Eq)]
907pub enum ResizeEdge {
908 Top,
910 TopRight,
912 Right,
914 BottomRight,
916 Bottom,
918 BottomLeft,
920 Left,
922 TopLeft,
924}
925
926#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
928pub enum WindowDecorations {
929 #[default]
930 Server,
932 Client,
934}
935
936#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
938pub enum Decorations {
939 #[default]
941 Server,
942 Client {
944 tiling: Tiling,
946 },
947}
948
949#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
951pub struct WindowControls {
952 pub fullscreen: bool,
954 pub maximize: bool,
956 pub minimize: bool,
958 pub window_menu: bool,
960}
961
962impl Default for WindowControls {
963 fn default() -> Self {
964 Self {
966 fullscreen: true,
967 maximize: true,
968 minimize: true,
969 window_menu: true,
970 }
971 }
972}
973
974#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
976pub enum WindowButton {
977 Minimize,
979 Maximize,
981 Close,
983}
984
985impl WindowButton {
986 pub fn id(&self) -> &'static str {
988 match self {
989 WindowButton::Minimize => "minimize",
990 WindowButton::Maximize => "maximize",
991 WindowButton::Close => "close",
992 }
993 }
994
995 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
996 fn index(&self) -> usize {
997 match self {
998 WindowButton::Minimize => 0,
999 WindowButton::Maximize => 1,
1000 WindowButton::Close => 2,
1001 }
1002 }
1003}
1004
1005pub const MAX_BUTTONS_PER_SIDE: usize = 3;
1007
1008#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1013pub struct WindowButtonLayout {
1014 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
1016 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
1018}
1019
1020#[cfg(any(target_os = "linux", target_os = "freebsd"))]
1021impl WindowButtonLayout {
1022 pub fn linux_default() -> Self {
1024 Self {
1025 left: [None; MAX_BUTTONS_PER_SIDE],
1026 right: [
1027 Some(WindowButton::Minimize),
1028 Some(WindowButton::Maximize),
1029 Some(WindowButton::Close),
1030 ],
1031 }
1032 }
1033
1034 pub fn parse(layout_string: &str) -> Result<Self> {
1036 fn parse_side(
1037 s: &str,
1038 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
1039 unrecognized: &mut Vec<String>,
1040 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
1041 let mut result = [None; MAX_BUTTONS_PER_SIDE];
1042 let mut i = 0;
1043 for name in s.split(',') {
1044 let trimmed = name.trim();
1045 if trimmed.is_empty() {
1046 continue;
1047 }
1048 let button = match trimmed {
1049 "minimize" => Some(WindowButton::Minimize),
1050 "maximize" => Some(WindowButton::Maximize),
1051 "close" => Some(WindowButton::Close),
1052 other => {
1053 unrecognized.push(other.to_string());
1054 None
1055 }
1056 };
1057 if let Some(button) = button {
1058 if seen_buttons[button.index()] {
1059 continue;
1060 }
1061 if let Some(slot) = result.get_mut(i) {
1062 *slot = Some(button);
1063 seen_buttons[button.index()] = true;
1064 i += 1;
1065 }
1066 }
1067 }
1068 result
1069 }
1070
1071 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
1072 let mut unrecognized = Vec::new();
1073 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
1074 let layout = Self {
1075 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
1076 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
1077 };
1078
1079 if !unrecognized.is_empty()
1080 && layout.left.iter().all(Option::is_none)
1081 && layout.right.iter().all(Option::is_none)
1082 {
1083 bail!(
1084 "button layout string {:?} contains no valid buttons (unrecognized: {})",
1085 layout_string,
1086 unrecognized.join(", ")
1087 );
1088 }
1089
1090 Ok(layout)
1091 }
1092
1093 #[cfg(test)]
1095 pub fn format(&self) -> String {
1096 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
1097 buttons
1098 .iter()
1099 .flatten()
1100 .map(|button| match button {
1101 WindowButton::Minimize => "minimize",
1102 WindowButton::Maximize => "maximize",
1103 WindowButton::Close => "close",
1104 })
1105 .collect::<Vec<_>>()
1106 .join(",")
1107 }
1108
1109 format!("{}:{}", format_side(&self.left), format_side(&self.right))
1110 }
1111}
1112
1113#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
1115pub struct Tiling {
1116 pub top: bool,
1118 pub left: bool,
1120 pub right: bool,
1122 pub bottom: bool,
1124}
1125
1126impl Tiling {
1127 pub fn tiled() -> Self {
1129 Self {
1130 top: true,
1131 left: true,
1132 right: true,
1133 bottom: true,
1134 }
1135 }
1136
1137 pub fn is_tiled(&self) -> bool {
1139 self.top || self.left || self.right || self.bottom
1140 }
1141}
1142
1143pub struct A11yCallbacks {
1145 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1147 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
1149 pub deactivation: Box<dyn Fn() + Send + 'static>,
1151}
1152
1153#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
1155pub struct RequestFrameOptions {
1156 pub require_presentation: bool,
1158 pub force_render: bool,
1160}
1161
1162pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
1166 fn bounds(&self) -> Bounds<Pixels>;
1168 fn is_maximized(&self) -> bool;
1170 fn window_bounds(&self) -> WindowBounds;
1172 fn content_size(&self) -> Size<Pixels>;
1174 fn resize(&mut self, size: Size<Pixels>);
1176 fn scale_factor(&self) -> f32;
1178 fn appearance(&self) -> WindowAppearance;
1180 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
1182 fn mouse_position(&self) -> Point<Pixels>;
1184 fn modifiers(&self) -> Modifiers;
1186 fn capslock(&self) -> Capslock;
1188 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
1190 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
1192 fn prompt(
1194 &self,
1195 level: PromptLevel,
1196 msg: &str,
1197 detail: Option<&str>,
1198 answers: &[PromptButton],
1199 ) -> Option<oneshot::Receiver<usize>>;
1200 fn show_native_menu(
1208 &self,
1209 _position: Point<Pixels>,
1210 _menu: NativeMenu,
1211 ) -> Option<oneshot::Receiver<SharedString>> {
1212 None
1213 }
1214 fn activate(&self);
1216 fn is_active(&self) -> bool;
1218 fn is_hovered(&self) -> bool;
1220 fn background_appearance(&self) -> WindowBackgroundAppearance;
1222 fn set_title(&mut self, title: &str);
1224 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
1226 fn minimize(&self);
1228 fn zoom(&self);
1230 fn toggle_fullscreen(&self);
1232 fn is_fullscreen(&self) -> bool;
1234 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
1236 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
1238 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
1240 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
1242 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
1244 fn on_moved(&self, callback: Box<dyn FnMut()>);
1246 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
1248 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
1254 fn on_close(&self, callback: Box<dyn FnOnce()>);
1256 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
1258 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
1260 fn draw(&self, scene: &Scene);
1262 fn completed_frame(&self) {}
1264 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1266 fn is_subpixel_rendering_supported(&self) -> bool;
1268
1269 #[cfg(feature = "dom-backend")]
1274 fn supports_dom(&self) -> bool {
1275 false
1276 }
1277
1278 #[cfg(feature = "dom-backend")]
1283 fn dom_tree_update(&self, _tree: &crate::dom::DomTree) {}
1284
1285 #[cfg(feature = "dom-backend")]
1290 fn on_dom_event(
1291 &self,
1292 _callback: Box<dyn FnMut(Vec<crate::DomNodeKey>, PlatformInput) -> DispatchEventResult>,
1293 ) {
1294 }
1295
1296 #[cfg(feature = "dom-backend")]
1300 fn on_dom_scroll(&self, _callback: Box<dyn FnMut(Vec<crate::DomNodeKey>, f64, f64)>) {}
1301
1302 fn get_title(&self) -> String {
1305 String::new()
1306 }
1307 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1309 None
1310 }
1311 fn tab_bar_visible(&self) -> bool {
1313 false
1314 }
1315 fn set_edited(&mut self, _edited: bool) {}
1317 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
1319 #[cfg(target_os = "macos")]
1321 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
1322 fn show_character_palette(&self) {}
1324 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
1326 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
1328 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
1330 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
1332 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
1334 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
1336 fn merge_all_windows(&self) {}
1338 fn move_tab_to_new_window(&self) {}
1340 fn toggle_window_tab_overview(&self) {}
1342 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
1344
1345 #[cfg(target_os = "windows")]
1347 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
1348
1349 fn inner_window_bounds(&self) -> WindowBounds {
1351 self.window_bounds()
1352 }
1353 fn request_decorations(&self, _decorations: WindowDecorations) {}
1355 fn show_window_menu(&self, _position: Point<Pixels>) {}
1357 fn start_window_move(&self) {}
1359 fn start_window_resize(&self, _edge: ResizeEdge) {}
1361 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
1363 fn window_decorations(&self) -> Decorations {
1365 Decorations::Server
1366 }
1367 fn set_app_id(&mut self, _app_id: &str) {}
1369 fn map_window(&mut self) -> anyhow::Result<()> {
1374 Ok(())
1375 }
1376 fn window_controls(&self) -> WindowControls {
1378 WindowControls::default()
1379 }
1380 fn set_client_inset(&self, _inset: Pixels) {}
1382 fn gpu_specs(&self) -> Option<GpuSpecs>;
1384
1385 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
1387
1388 fn play_system_bell(&self) {}
1390
1391 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
1393
1394 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
1396
1397 #[cfg(any(test, feature = "test-support"))]
1399 fn as_test(&mut self) -> Option<&mut TestWindow> {
1400 None
1401 }
1402
1403 #[cfg(any(test, feature = "test-support"))]
1406 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
1407 anyhow::bail!("render_to_image not implemented for this platform")
1408 }
1409
1410 fn set_exclusive_zone(&self, _zone: Pixels) {}
1417 #[cfg(all(target_os = "linux", any(feature = "wayland", feature = "x11")))]
1423 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
1424
1425 fn request_attention(&self) {}
1431
1432 fn request_frame(&self) {}
1444
1445 fn set_position(&mut self, _position: Point<Pixels>) {}
1450
1451 fn hide(&self) {}
1453
1454 fn set_mouse_passthrough(&self, _passthrough: bool) {}
1456
1457 fn set_titlebar_visible(&self, _visible: bool) {}
1462
1463 fn set_text_content_type(&self, _content_type: Option<&'static str>) {}
1466}
1467
1468#[cfg(any(test, feature = "test-support"))]
1470pub trait PlatformHeadlessRenderer {
1471 fn render_scene_to_image(
1473 &mut self,
1474 scene: &Scene,
1475 size: Size<DevicePixels>,
1476 ) -> Result<RgbaImage>;
1477
1478 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1482
1483 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1485}
1486
1487#[doc(hidden)]
1490pub type RunnableVariant = Runnable<RunnableMeta>;
1491
1492#[doc(hidden)]
1493pub type TimerResolutionGuard = rgpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1494
1495#[doc(hidden)]
1496pub enum TasksIncluded {
1497 OnlyCompleted,
1498 CompletedAndRunning,
1499}
1500
1501#[doc(hidden)]
1503pub trait PlatformDispatcher: Send + Sync {
1504 fn is_main_thread(&self) -> bool;
1505 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1506 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1507 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1508
1509 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1510
1511 fn now(&self) -> Instant {
1512 Instant::now()
1513 }
1514
1515 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1516 rgpui_util::defer(Box::new(|| {}))
1517 }
1518
1519 #[cfg(any(test, feature = "test-support"))]
1520 fn as_test(&self) -> Option<&TestDispatcher> {
1521 None
1522 }
1523
1524 #[cfg(all(
1526 any(test, feature = "test-support"),
1527 any(
1528 target_os = "windows",
1529 target_os = "linux",
1530 target_os = "macos",
1531 target_family = "wasm"
1532 )
1533 ))]
1534 fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
1535 None
1536 }
1537}
1538
1539pub trait PlatformTextSystem: Send + Sync {
1541 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1543 fn all_font_names(&self) -> Vec<String>;
1545 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1547 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1549 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1551 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1553 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1555 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1557 fn rasterize_glyph(
1559 &self,
1560 params: &RenderGlyphParams,
1561 raster_bounds: Bounds<DevicePixels>,
1562 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1563 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1565 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1567 -> TextRenderingMode;
1568 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1570 0
1571 }
1572}
1573
1574pub struct NoopTextSystem;
1576
1577impl NoopTextSystem {
1578 pub fn new() -> Self {
1580 Self
1581 }
1582}
1583
1584impl PlatformTextSystem for NoopTextSystem {
1585 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1586 Ok(())
1587 }
1588
1589 fn all_font_names(&self) -> Vec<String> {
1590 Vec::new()
1591 }
1592
1593 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1594 Ok(FontId(1))
1595 }
1596
1597 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1598 FontMetrics {
1599 units_per_em: 1000,
1600 ascent: 1025.0,
1601 descent: -275.0,
1602 line_gap: 0.0,
1603 underline_position: -95.0,
1604 underline_thickness: 60.0,
1605 cap_height: 698.0,
1606 x_height: 516.0,
1607 bounding_box: Bounds {
1608 origin: Point {
1609 x: -260.0,
1610 y: -245.0,
1611 },
1612 size: Size {
1613 width: 1501.0,
1614 height: 1364.0,
1615 },
1616 },
1617 }
1618 }
1619
1620 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1621 Ok(Bounds {
1622 origin: Point { x: 54.0, y: 0.0 },
1623 size: size(392.0, 528.0),
1624 })
1625 }
1626
1627 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1628 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1629 }
1630
1631 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1632 Some(GlyphId(ch.len_utf16() as u32))
1633 }
1634
1635 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1636 Ok(Default::default())
1637 }
1638
1639 fn rasterize_glyph(
1640 &self,
1641 _params: &RenderGlyphParams,
1642 raster_bounds: Bounds<DevicePixels>,
1643 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1644 Ok((raster_bounds.size, Vec::new()))
1645 }
1646
1647 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1648 let mut position = px(0.);
1649 let metrics = self.font_metrics(FontId(0));
1650 let glyph = invariant(
1652 self.glyph_for_char(FontId(0), 'm'),
1653 "NoopTextSystem:字符 'm' 必有字形",
1654 );
1655 let advance = invariant_result(
1656 self.advance(FontId(0), glyph),
1657 "NoopTextSystem:advance 必成功",
1658 );
1659 let em_width = font_size * advance.width / metrics.units_per_em as f32;
1660 let mut glyphs = Vec::new();
1661 for (ix, c) in text.char_indices() {
1662 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1663 glyphs.push(ShapedGlyph {
1664 id: glyph,
1665 position: point(position, px(0.)),
1666 index: ix,
1667 is_emoji: glyph.0 == 2,
1668 });
1669 if glyph.0 == 2 {
1670 position += em_width * 2.0;
1671 } else {
1672 position += em_width;
1673 }
1674 } else {
1675 position += em_width
1676 }
1677 }
1678 let mut runs = Vec::default();
1679 if !glyphs.is_empty() {
1680 runs.push(ShapedRun {
1681 font_id: FontId(0),
1682 glyphs,
1683 });
1684 } else {
1685 position = px(0.);
1686 }
1687
1688 LineLayout {
1689 font_size,
1690 width: position,
1691 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1692 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1693 runs,
1694 len: text.len(),
1695 }
1696 }
1697
1698 fn recommended_rendering_mode(
1699 &self,
1700 _font_id: FontId,
1701 _font_size: Pixels,
1702 ) -> TextRenderingMode {
1703 TextRenderingMode::Grayscale
1704 }
1705}
1706
1707pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1712 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1713 [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], ];
1727
1728 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1729 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1730
1731 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1732 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1733
1734 [
1735 ratios[0] * NORM13,
1736 ratios[1] * NORM24,
1737 ratios[2] * NORM13,
1738 ratios[3] * NORM24,
1739 ]
1740}
1741
1742#[derive(PartialEq, Eq, Hash, Clone)]
1744pub enum AtlasKey {
1745 Glyph(RenderGlyphParams),
1747 Svg(RenderSvgParams),
1749 Image(RenderImageParams),
1751}
1752
1753impl AtlasKey {
1754 pub fn texture_kind(&self) -> AtlasTextureKind {
1756 match self {
1757 AtlasKey::Glyph(params) => {
1758 if params.is_emoji {
1759 AtlasTextureKind::Polychrome
1760 } else if params.subpixel_rendering {
1761 AtlasTextureKind::Subpixel
1762 } else {
1763 AtlasTextureKind::Monochrome
1764 }
1765 }
1766 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1767 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1768 }
1769 }
1770}
1771
1772impl From<RenderGlyphParams> for AtlasKey {
1773 fn from(params: RenderGlyphParams) -> Self {
1774 Self::Glyph(params)
1775 }
1776}
1777
1778impl From<RenderSvgParams> for AtlasKey {
1779 fn from(params: RenderSvgParams) -> Self {
1780 Self::Svg(params)
1781 }
1782}
1783
1784impl From<RenderImageParams> for AtlasKey {
1785 fn from(params: RenderImageParams) -> Self {
1786 Self::Image(params)
1787 }
1788}
1789
1790pub trait PlatformAtlas {
1792 fn get_or_insert_with<'a>(
1794 &self,
1795 key: &AtlasKey,
1796 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1797 ) -> Result<Option<AtlasTile>>;
1798 fn remove(&self, key: &AtlasKey);
1800 #[cfg(any(test, feature = "test-support"))]
1802 fn contains(&self, _key: &AtlasKey) -> bool {
1803 false
1804 }
1805}
1806
1807#[doc(hidden)]
1808pub struct AtlasTextureList<T> {
1809 pub textures: Vec<Option<T>>,
1810 pub free_list: Vec<usize>,
1811}
1812
1813impl<T> Default for AtlasTextureList<T> {
1814 fn default() -> Self {
1815 Self {
1816 textures: Vec::default(),
1817 free_list: Vec::default(),
1818 }
1819 }
1820}
1821
1822impl<T> ops::Index<usize> for AtlasTextureList<T> {
1823 type Output = Option<T>;
1824
1825 fn index(&self, index: usize) -> &Self::Output {
1826 &self.textures[index]
1827 }
1828}
1829
1830impl<T> AtlasTextureList<T> {
1831 #[allow(unused)]
1832 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1833 self.free_list.clear();
1834 self.textures.drain(..)
1835 }
1836
1837 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1838 self.textures.iter_mut().flatten()
1839 }
1840}
1841
1842#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1844#[repr(C)]
1845pub struct AtlasTile {
1846 pub texture_id: AtlasTextureId,
1848 pub tile_id: TileId,
1850 pub padding: u32,
1852 pub bounds: Bounds<DevicePixels>,
1854}
1855
1856#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1858#[repr(C)]
1859pub struct AtlasTextureId {
1860 pub index: u32,
1863 pub kind: AtlasTextureKind,
1865}
1866
1867#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1868#[repr(C)]
1869pub enum AtlasTextureKind {
1871 Monochrome,
1873 Polychrome,
1875 Subpixel,
1877}
1878
1879#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1881#[repr(C)]
1882pub struct TileId(pub u32);
1883
1884impl From<etagere::AllocId> for TileId {
1885 fn from(id: etagere::AllocId) -> Self {
1886 Self(id.serialize())
1887 }
1888}
1889
1890impl From<TileId> for etagere::AllocId {
1891 fn from(id: TileId) -> Self {
1892 Self::deserialize(id.0)
1893 }
1894}
1895
1896pub struct PlatformInputHandler {
1898 cx: AsyncWindowContext,
1899 handler: Box<dyn InputHandler>,
1900}
1901
1902impl PlatformInputHandler {
1903 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
1905 Self { cx, handler }
1906 }
1907
1908 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
1910 self.cx
1911 .update(|window, cx| {
1912 self.handler
1913 .selected_text_range(ignore_disabled_input, window, cx)
1914 })
1915 .ok()
1916 .flatten()
1917 }
1918
1919 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
1921 self.cx
1922 .update(|window, cx| self.handler.marked_text_range(window, cx))
1923 .ok()
1924 .flatten()
1925 }
1926
1927 pub fn text_for_range(
1929 &mut self,
1930 range_utf16: Range<usize>,
1931 adjusted: &mut Option<Range<usize>>,
1932 ) -> Option<String> {
1933 self.cx
1934 .update(|window, cx| {
1935 self.handler
1936 .text_for_range(range_utf16, adjusted, window, cx)
1937 })
1938 .ok()
1939 .flatten()
1940 }
1941
1942 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
1944 self.cx
1945 .update(|window, cx| {
1946 self.handler
1947 .replace_text_in_range(replacement_range, text, window, cx);
1948 })
1949 .ok();
1950 }
1951
1952 pub fn replace_and_mark_text_in_range(
1954 &mut self,
1955 range_utf16: Option<Range<usize>>,
1956 new_text: &str,
1957 new_selected_range: Option<Range<usize>>,
1958 ) {
1959 self.cx
1960 .update(|window, cx| {
1961 self.handler.replace_and_mark_text_in_range(
1962 range_utf16,
1963 new_text,
1964 new_selected_range,
1965 window,
1966 cx,
1967 )
1968 })
1969 .ok();
1970 }
1971
1972 pub fn unmark_text(&mut self) {
1974 self.cx
1975 .update(|window, cx| self.handler.unmark_text(window, cx))
1976 .ok();
1977 }
1978
1979 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
1981 self.cx
1982 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
1983 .ok()
1984 .flatten()
1985 }
1986
1987 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
1989 self.handler.apple_press_and_hold_enabled()
1990 }
1991
1992 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1994 self.handler.replace_text_in_range(None, input, window, cx);
1995 }
1996
1997 pub fn compute_ime_candidate_bounds(
1999 marked_range: Option<Range<usize>>,
2000 selection: &UTF16Selection,
2001 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
2002 ) -> Option<Bounds<Pixels>> {
2003 if let Some(marked_range) = marked_range {
2004 let mut line_start = marked_range.start;
2006
2007 let caret = selection.range.end;
2011 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
2012 for i in (marked_range.start..caret).rev() {
2013 if let Some(b) = bounds_for_range(i..i) {
2014 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
2015 line_start = i + 1;
2016 break;
2017 }
2018 }
2019 }
2020 }
2021 bounds_for_range(line_start..line_start)
2022 } else {
2023 let offset = if selection.reversed {
2025 selection.range.start
2026 } else {
2027 selection.range.end
2028 };
2029 bounds_for_range(offset..offset)
2030 }
2031 }
2032
2033 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
2035 let marked_range = self.handler.marked_text_range(window, cx);
2036 let selection = self.handler.selected_text_range(true, window, cx)?;
2037 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2038 self.handler.bounds_for_range(range, window, cx)
2039 })
2040 }
2041
2042 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
2044 let marked_range = self.marked_text_range();
2045 let selection = self.selected_text_range(true)?;
2046 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
2047 self.bounds_for_range(range)
2048 })
2049 }
2050
2051 #[allow(unused)]
2053 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
2054 self.cx
2055 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
2056 .ok()
2057 .flatten()
2058 }
2059
2060 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
2062 self.handler.accepts_text_input(window, cx)
2063 }
2064
2065 pub fn query_accepts_text_input(&mut self) -> bool {
2067 self.cx
2068 .update(|window, cx| self.handler.accepts_text_input(window, cx))
2069 .unwrap_or(true)
2070 }
2071
2072 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
2077 self.cx
2078 .update(|window, cx| {
2079 !window.has_pending_keystrokes()
2081 && self.handler.prefers_ime_for_printable_keys(window, cx)
2082 })
2083 .unwrap_or(false)
2084 }
2085}
2086
2087#[derive(Debug)]
2090pub struct UTF16Selection {
2091 pub range: Range<usize>,
2093 pub reversed: bool,
2095}
2096
2097pub trait InputHandler: 'static {
2102 fn selected_text_range(
2107 &mut self,
2108 ignore_disabled_input: bool,
2109 window: &mut Window,
2110 cx: &mut App,
2111 ) -> Option<UTF16Selection>;
2112
2113 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
2118
2119 fn text_for_range(
2124 &mut self,
2125 range_utf16: Range<usize>,
2126 adjusted_range: &mut Option<Range<usize>>,
2127 window: &mut Window,
2128 cx: &mut App,
2129 ) -> Option<String>;
2130
2131 fn replace_text_in_range(
2136 &mut self,
2137 replacement_range: Option<Range<usize>>,
2138 text: &str,
2139 window: &mut Window,
2140 cx: &mut App,
2141 );
2142
2143 fn replace_and_mark_text_in_range(
2150 &mut self,
2151 range_utf16: Option<Range<usize>>,
2152 new_text: &str,
2153 new_selected_range: Option<Range<usize>>,
2154 window: &mut Window,
2155 cx: &mut App,
2156 );
2157
2158 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
2161
2162 fn bounds_for_range(
2167 &mut self,
2168 range_utf16: Range<usize>,
2169 window: &mut Window,
2170 cx: &mut App,
2171 ) -> Option<Bounds<Pixels>>;
2172
2173 fn character_index_for_point(
2177 &mut self,
2178 point: Point<Pixels>,
2179 window: &mut Window,
2180 cx: &mut App,
2181 ) -> Option<usize>;
2182
2183 fn apple_press_and_hold_enabled(&mut self) -> bool {
2187 true
2188 }
2189
2190 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2192 true
2193 }
2194
2195 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
2203 false
2204 }
2205
2206 fn set_selected_text_range(
2208 &mut self,
2209 _range_utf16: Range<usize>,
2210 _window: &mut Window,
2211 _cx: &mut App,
2212 ) {
2213 }
2214
2215 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
2217 None
2218 }
2219
2220 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
2222 None
2223 }
2224}
2225
2226#[derive(Debug)]
2228pub struct WindowOptions {
2229 pub window_bounds: Option<WindowBounds>,
2233
2234 pub titlebar: Option<TitlebarOptions>,
2236
2237 pub focus: bool,
2239
2240 pub show: bool,
2242
2243 pub kind: WindowKind,
2245
2246 pub is_movable: bool,
2250
2251 pub is_resizable: bool,
2254
2255 pub is_minimizable: bool,
2259
2260 pub display_id: Option<DisplayId>,
2263
2264 pub window_background: WindowBackgroundAppearance,
2266
2267 pub app_id: Option<String>,
2269
2270 pub window_min_size: Option<Size<Pixels>>,
2272
2273 pub window_decorations: Option<WindowDecorations>,
2284
2285 pub icon: Option<Arc<image::RgbaImage>>,
2287
2288 pub tabbing_identifier: Option<String>,
2290
2291 pub app_owns_titlebar_drag: bool,
2294
2295 pub mouse_passthrough: bool,
2298
2299 pub inactive_frame_interval: Option<Duration>,
2308
2309 pub thermal_frame_interval: Option<Duration>,
2316}
2317
2318#[derive(Debug)]
2320pub struct WindowParams {
2321 pub bounds: Bounds<Pixels>,
2323
2324 pub titlebar: Option<TitlebarOptions>,
2326
2327 pub kind: WindowKind,
2329
2330 pub is_movable: bool,
2332
2333 pub is_resizable: bool,
2335
2336 pub is_minimizable: bool,
2338
2339 pub focus: bool,
2341
2342 pub show: bool,
2344
2345 pub icon: Option<Arc<image::RgbaImage>>,
2347
2348 pub display_id: Option<DisplayId>,
2350
2351 pub app_id: Option<String>,
2353
2354 pub window_min_size: Option<Size<Pixels>>,
2356 #[cfg(target_os = "macos")]
2358 pub tabbing_identifier: Option<String>,
2359
2360 pub app_owns_titlebar_drag: bool,
2363
2364 pub mouse_passthrough: bool,
2367
2368 pub window_background: WindowBackgroundAppearance,
2371}
2372
2373#[derive(Debug, Copy, Clone, PartialEq)]
2375pub enum WindowBounds {
2376 Windowed(Bounds<Pixels>),
2378 Maximized(Bounds<Pixels>),
2381 Fullscreen(Bounds<Pixels>),
2384}
2385
2386impl Default for WindowBounds {
2387 fn default() -> Self {
2388 WindowBounds::Windowed(Bounds::default())
2389 }
2390}
2391
2392impl WindowBounds {
2393 pub fn get_bounds(&self) -> Bounds<Pixels> {
2395 match self {
2396 WindowBounds::Windowed(bounds) => *bounds,
2397 WindowBounds::Maximized(bounds) => *bounds,
2398 WindowBounds::Fullscreen(bounds) => *bounds,
2399 }
2400 }
2401
2402 pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
2404 WindowBounds::Windowed(Bounds::centered(None, size, cx))
2405 }
2406}
2407
2408impl Default for WindowOptions {
2409 fn default() -> Self {
2410 Self {
2411 window_bounds: None,
2412 titlebar: Some(TitlebarOptions {
2413 title: Default::default(),
2414 appears_transparent: Default::default(),
2415 traffic_light_position: Default::default(),
2416 }),
2417 focus: true,
2418 show: true,
2419 kind: WindowKind::Normal,
2420 is_movable: true,
2421 is_resizable: true,
2422 is_minimizable: true,
2423 display_id: None,
2424 window_background: WindowBackgroundAppearance::default(),
2425 icon: None,
2426 app_id: None,
2427 window_min_size: None,
2428 window_decorations: None,
2429 tabbing_identifier: None,
2430 app_owns_titlebar_drag: false,
2431 mouse_passthrough: false,
2432 inactive_frame_interval: Some(crate::frame_throttle::DEFAULT_INACTIVE_FRAME_INTERVAL),
2433 thermal_frame_interval: Some(crate::frame_throttle::DEFAULT_THERMAL_FRAME_INTERVAL),
2434 }
2435 }
2436}
2437
2438#[derive(Debug, Default)]
2440pub struct TitlebarOptions {
2441 pub title: Option<SharedString>,
2443
2444 pub appears_transparent: bool,
2447
2448 pub traffic_light_position: Option<Point<Pixels>>,
2450}
2451
2452#[derive(Clone, Debug, PartialEq, Eq)]
2454pub enum WindowKind {
2455 Normal,
2457
2458 PopUp,
2461
2462 AnchoredPopup(popup::PopupOptions),
2469
2470 Floating,
2472
2473 #[cfg(target_os = "linux")]
2476 LayerShell(layer_shell::LayerShellOptions),
2477
2478 Dialog,
2481
2482 Overlay,
2484}
2485
2486#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2491pub enum WindowAppearance {
2492 #[default]
2496 Light,
2497
2498 VibrantLight,
2502
2503 Dark,
2507
2508 VibrantDark,
2512}
2513
2514#[derive(Copy, Clone, Debug, Default, PartialEq)]
2516pub enum WindowBackgroundAppearance {
2517 #[default]
2523 Opaque,
2524 Transparent,
2526 Blurred,
2530 MicaBackdrop,
2532 MicaAltBackdrop,
2534}
2535
2536#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2538pub enum TextRenderingMode {
2539 #[default]
2541 PlatformDefault,
2542 Subpixel,
2544 Grayscale,
2546}
2547
2548#[derive(Clone, Debug)]
2550pub struct PathPromptOptions {
2551 pub files: bool,
2553 pub directories: bool,
2555 pub multiple: bool,
2557 pub prompt: Option<SharedString>,
2559}
2560
2561#[derive(Copy, Clone, Debug, PartialEq)]
2563pub enum PromptLevel {
2564 Info,
2566
2567 Warning,
2569
2570 Critical,
2572}
2573
2574#[derive(Clone, Debug, PartialEq)]
2576pub enum PromptButton {
2577 Ok(SharedString),
2579 Cancel(SharedString),
2581 Other(SharedString),
2583}
2584
2585impl PromptButton {
2586 pub fn new(label: impl Into<SharedString>) -> Self {
2588 PromptButton::Other(label.into())
2589 }
2590
2591 pub fn ok(label: impl Into<SharedString>) -> Self {
2593 PromptButton::Ok(label.into())
2594 }
2595
2596 pub fn cancel(label: impl Into<SharedString>) -> Self {
2598 PromptButton::Cancel(label.into())
2599 }
2600
2601 pub fn is_cancel(&self) -> bool {
2603 matches!(self, PromptButton::Cancel(_))
2604 }
2605
2606 pub fn label(&self) -> &SharedString {
2608 match self {
2609 PromptButton::Ok(label) => label,
2610 PromptButton::Cancel(label) => label,
2611 PromptButton::Other(label) => label,
2612 }
2613 }
2614}
2615
2616impl From<&str> for PromptButton {
2617 fn from(value: &str) -> Self {
2618 match value.to_lowercase().as_str() {
2619 "ok" => PromptButton::Ok("OK".into()),
2620 "cancel" => PromptButton::Cancel("Cancel".into()),
2621 _ => PromptButton::Other(SharedString::from(value.to_owned())),
2622 }
2623 }
2624}
2625
2626#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2628pub enum CursorStyle {
2629 #[default]
2631 Arrow,
2632
2633 IBeam,
2636
2637 Crosshair,
2640
2641 ClosedHand,
2644
2645 OpenHand,
2648
2649 PointingHand,
2652
2653 ResizeLeft,
2656
2657 ResizeRight,
2660
2661 ResizeLeftRight,
2664
2665 ResizeUp,
2668
2669 ResizeDown,
2672
2673 ResizeUpDown,
2676
2677 ResizeUpLeftDownRight,
2680
2681 ResizeUpRightDownLeft,
2684
2685 ResizeColumn,
2688
2689 ResizeRow,
2692
2693 IBeamCursorForVerticalLayout,
2696
2697 OperationNotAllowed,
2700
2701 DragLink,
2704
2705 DragCopy,
2708
2709 ContextualMenu,
2712}
2713
2714#[derive(Clone, Debug, Eq, PartialEq)]
2720pub struct ClipboardFormat {
2721 pub mime_type: String,
2723 pub bytes: Vec<u8>,
2725}
2726
2727impl ClipboardFormat {
2728 pub const PLAIN_TEXT: &'static str = "text/plain";
2730 pub const HTML: &'static str = "text/html";
2732 pub const RTF: &'static str = "text/rtf";
2734 pub const MARKDOWN: &'static str = "text/markdown";
2736 pub const CSV: &'static str = "text/csv";
2738 pub const TSV: &'static str = "text/tab-separated-values";
2740 pub const URI_LIST: &'static str = "text/uri-list";
2742
2743 pub fn new(mime_type: impl Into<String>, bytes: Vec<u8>) -> Self {
2745 Self {
2746 mime_type: mime_type.into(),
2747 bytes,
2748 }
2749 }
2750
2751 pub fn new_text(mime_type: impl Into<String>, text: impl Into<String>) -> Self {
2753 Self::new(mime_type, text.into().into_bytes())
2754 }
2755
2756 pub fn text(&self) -> Option<&str> {
2758 std::str::from_utf8(&self.bytes).ok()
2759 }
2760}
2761
2762#[derive(Clone, Debug, Eq, PartialEq)]
2764pub struct ClipboardItem {
2765 pub entries: Vec<ClipboardEntry>,
2767}
2768
2769#[derive(Clone, Debug, Eq, PartialEq)]
2771pub enum ClipboardEntry {
2772 String(ClipboardString),
2774 Image(Image),
2776 ExternalPaths(crate::ExternalPaths),
2778 Format(ClipboardFormat),
2780}
2781
2782impl ClipboardItem {
2783 pub fn new_string(text: String) -> Self {
2785 Self {
2786 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
2787 }
2788 }
2789
2790 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
2792 Self {
2793 entries: vec![ClipboardEntry::String(ClipboardString {
2794 text,
2795 metadata: Some(metadata),
2796 })],
2797 }
2798 }
2799
2800 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
2802 Self {
2803 entries: vec![ClipboardEntry::String(
2804 ClipboardString::new(text).with_json_metadata(metadata),
2805 )],
2806 }
2807 }
2808
2809 pub fn new_image(image: &Image) -> Self {
2811 Self {
2812 entries: vec![ClipboardEntry::Image(image.clone())],
2813 }
2814 }
2815
2816 pub fn new_html(html: impl Into<String>, plain_text: Option<String>) -> Self {
2821 let mut entries = Vec::with_capacity(2);
2822 if let Some(text) = plain_text {
2823 entries.push(ClipboardEntry::String(ClipboardString::new(text)));
2824 }
2825 entries.push(ClipboardEntry::Format(ClipboardFormat::new_text(
2826 ClipboardFormat::HTML,
2827 html,
2828 )));
2829 Self { entries }
2830 }
2831
2832 pub fn new_rtf(rtf: impl Into<String>, plain_text: Option<String>) -> Self {
2834 let mut entries = Vec::with_capacity(2);
2835 if let Some(text) = plain_text {
2836 entries.push(ClipboardEntry::String(ClipboardString::new(text)));
2837 }
2838 entries.push(ClipboardEntry::Format(ClipboardFormat::new_text(
2839 ClipboardFormat::RTF,
2840 rtf,
2841 )));
2842 Self { entries }
2843 }
2844
2845 pub fn new_with_format(format: ClipboardFormat) -> Self {
2847 Self {
2848 entries: vec![ClipboardEntry::Format(format)],
2849 }
2850 }
2851
2852 pub fn with_string(mut self, text: impl Into<String>) -> Self {
2854 self.entries
2855 .push(ClipboardEntry::String(ClipboardString::new(text.into())));
2856 self
2857 }
2858
2859 pub fn with_format(mut self, format: ClipboardFormat) -> Self {
2861 self.entries.push(ClipboardEntry::Format(format));
2862 self
2863 }
2864
2865 pub fn text(&self) -> Option<String> {
2868 let mut answer = String::new();
2869
2870 for entry in self.entries.iter() {
2871 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
2872 answer.push_str(text);
2873 }
2874 }
2875
2876 if answer.is_empty() {
2877 for entry in self.entries.iter() {
2878 if let ClipboardEntry::ExternalPaths(paths) = entry {
2879 for path in &paths.0 {
2880 use std::fmt::Write as _;
2881 _ = write!(answer, "{}", path.display());
2882 }
2883 }
2884 }
2885 }
2886
2887 if !answer.is_empty() {
2888 Some(answer)
2889 } else {
2890 None
2891 }
2892 }
2893
2894 pub fn metadata(&self) -> Option<&String> {
2896 match self.entries().first() {
2897 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
2898 clipboard_string.metadata.as_ref()
2899 }
2900 _ => None,
2901 }
2902 }
2903
2904 pub fn entries(&self) -> &[ClipboardEntry] {
2906 &self.entries
2907 }
2908
2909 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
2911 self.entries.into_iter()
2912 }
2913
2914 pub fn format(&self, mime_type: &str) -> Option<&ClipboardFormat> {
2916 self.entries.iter().find_map(|entry| match entry {
2917 ClipboardEntry::Format(format) if format.mime_type == mime_type => Some(format),
2918 _ => None,
2919 })
2920 }
2921
2922 pub fn formats(&self) -> impl Iterator<Item = &ClipboardFormat> {
2924 self.entries.iter().filter_map(|entry| match entry {
2925 ClipboardEntry::Format(format) => Some(format),
2926 _ => None,
2927 })
2928 }
2929
2930 pub fn html(&self) -> Option<&str> {
2932 self.format(ClipboardFormat::HTML)?.text()
2933 }
2934
2935 pub fn rtf(&self) -> Option<&str> {
2937 self.format(ClipboardFormat::RTF)?.text()
2938 }
2939}
2940
2941impl From<ClipboardString> for ClipboardEntry {
2942 fn from(value: ClipboardString) -> Self {
2943 Self::String(value)
2944 }
2945}
2946
2947impl From<String> for ClipboardEntry {
2948 fn from(value: String) -> Self {
2949 Self::from(ClipboardString::from(value))
2950 }
2951}
2952
2953impl From<Image> for ClipboardEntry {
2954 fn from(value: Image) -> Self {
2955 Self::Image(value)
2956 }
2957}
2958
2959impl From<ClipboardFormat> for ClipboardEntry {
2960 fn from(value: ClipboardFormat) -> Self {
2961 Self::Format(value)
2962 }
2963}
2964
2965impl From<ClipboardEntry> for ClipboardItem {
2966 fn from(value: ClipboardEntry) -> Self {
2967 Self {
2968 entries: vec![value],
2969 }
2970 }
2971}
2972
2973impl From<String> for ClipboardItem {
2974 fn from(value: String) -> Self {
2975 Self::from(ClipboardEntry::from(value))
2976 }
2977}
2978
2979impl From<Image> for ClipboardItem {
2980 fn from(value: Image) -> Self {
2981 Self::from(ClipboardEntry::from(value))
2982 }
2983}
2984
2985impl From<ClipboardFormat> for ClipboardItem {
2986 fn from(value: ClipboardFormat) -> Self {
2987 Self::from(ClipboardEntry::from(value))
2988 }
2989}
2990
2991#[cfg(test)]
2992mod clipboard_tests {
2993 use super::*;
2994
2995 #[test]
2997 fn html_item_exposes_text_and_html() {
2998 let item = ClipboardItem::new_html("<b>Hi</b>", Some("Hi".to_string()));
2999 assert_eq!(item.text().as_deref(), Some("Hi"));
3000 assert_eq!(item.html(), Some("<b>Hi</b>"));
3001 assert_eq!(item.rtf(), None);
3002 assert_eq!(item.formats().count(), 1);
3003 }
3004
3005 #[test]
3007 fn rtf_item_exposes_rtf() {
3008 let item = ClipboardItem::new_rtf(r"{\rtf1 hi}", Some("hi".to_string()));
3009 assert_eq!(item.text().as_deref(), Some("hi"));
3010 assert_eq!(item.rtf(), Some(r"{\rtf1 hi}"));
3011 }
3012
3013 #[test]
3015 fn format_only_item_has_no_plain_text() {
3016 let item = ClipboardItem::new_with_format(ClipboardFormat::new_text(
3017 ClipboardFormat::CSV,
3018 "a,b\n1,2",
3019 ));
3020 assert_eq!(item.text(), None);
3021 assert_eq!(
3022 item.format(ClipboardFormat::CSV)
3023 .and_then(ClipboardFormat::text),
3024 Some("a,b\n1,2")
3025 );
3026 }
3027
3028 #[test]
3030 fn non_utf8_format_has_no_text() {
3031 let format = ClipboardFormat::new("application/octet-stream", vec![0xff, 0xfe]);
3032 assert_eq!(format.text(), None);
3033 assert_eq!(format.mime_type, "application/octet-stream");
3034 }
3035
3036 #[test]
3038 fn builder_appends_entries_in_order() {
3039 let item = ClipboardItem::new_string("plain".to_string()).with_format(
3040 ClipboardFormat::new_text(ClipboardFormat::HTML, "<i>plain</i>"),
3041 );
3042 assert_eq!(item.entries.len(), 2);
3043 assert!(matches!(item.entries[0], ClipboardEntry::String(_)));
3044 assert!(matches!(item.entries[1], ClipboardEntry::Format(_)));
3045 }
3046}
3047
3048#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
3050pub enum ImageFormat {
3051 Png,
3055 Jpeg,
3057 Webp,
3059 Gif,
3061 Svg,
3063 Bmp,
3065 Tiff,
3067 Ico,
3069 Pnm,
3071}
3072
3073impl ImageFormat {
3074 pub const fn mime_type(self) -> &'static str {
3076 match self {
3077 ImageFormat::Png => "image/png",
3078 ImageFormat::Jpeg => "image/jpeg",
3079 ImageFormat::Webp => "image/webp",
3080 ImageFormat::Gif => "image/gif",
3081 ImageFormat::Svg => "image/svg+xml",
3082 ImageFormat::Bmp => "image/bmp",
3083 ImageFormat::Tiff => "image/tiff",
3084 ImageFormat::Ico => "image/ico",
3085 ImageFormat::Pnm => "image/x-portable-anymap",
3086 }
3087 }
3088
3089 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
3091 use strum::IntoEnumIterator;
3092 Self::iter()
3093 .find(|format| format.mime_type() == mime_type)
3094 .or_else(|| Self::from_mime_type_alias(mime_type))
3095 }
3096
3097 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
3101 match mime_type {
3102 "image/jpg" => Some(Self::Jpeg),
3103 "image/tif" => Some(Self::Tiff),
3104 _ => None,
3105 }
3106 }
3107}
3108
3109#[derive(Clone, Debug, PartialEq, Eq)]
3111pub struct Image {
3112 pub format: ImageFormat,
3114 pub bytes: Vec<u8>,
3116 pub id: u64,
3118}
3119
3120impl Hash for Image {
3121 fn hash<H: Hasher>(&self, state: &mut H) {
3122 state.write_u64(self.id);
3123 }
3124}
3125
3126impl Image {
3127 pub fn empty() -> Self {
3129 Self::from_bytes(ImageFormat::Png, Vec::new())
3130 }
3131
3132 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
3134 Self {
3135 id: hash(&bytes),
3136 format,
3137 bytes,
3138 }
3139 }
3140
3141 pub fn id(&self) -> u64 {
3143 self.id
3144 }
3145
3146 pub fn use_render_image(
3148 self: Arc<Self>,
3149 window: &mut Window,
3150 cx: &mut App,
3151 ) -> Option<Arc<RenderImage>> {
3152 ImageSource::Image(self)
3153 .use_data(None, window, cx)
3154 .and_then(|result| result.ok())
3155 }
3156
3157 pub fn get_render_image(
3159 self: Arc<Self>,
3160 window: &mut Window,
3161 cx: &mut App,
3162 ) -> Option<Arc<RenderImage>> {
3163 ImageSource::Image(self)
3164 .get_data(None, window, cx)
3165 .and_then(|result| result.ok())
3166 }
3167
3168 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
3170 ImageSource::Image(self).remove_asset(cx);
3171 }
3172
3173 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
3175 fn frames_for_image(
3176 bytes: &[u8],
3177 format: image::ImageFormat,
3178 ) -> Result<SmallVec<[Frame; 1]>> {
3179 let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
3180
3181 for pixel in data.chunks_exact_mut(4) {
3183 pixel.swap(0, 2);
3184 }
3185
3186 Ok(SmallVec::from_elem(Frame::new(data), 1))
3187 }
3188
3189 let frames = match self.format {
3190 ImageFormat::Gif => {
3191 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
3192 let mut frames = SmallVec::new();
3193
3194 for frame in decoder.into_frames() {
3195 match frame {
3196 Ok(mut frame) => {
3197 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
3199 pixel.swap(0, 2);
3200 }
3201 frames.push(frame);
3202 }
3203 Err(err) => {
3204 log::debug!("Skipping GIF frame due to decode error: {err}");
3205 }
3206 }
3207 }
3208
3209 if frames.is_empty() {
3210 anyhow::bail!("GIF could not be decoded: all frames failed");
3211 }
3212
3213 frames
3214 }
3215 ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
3216 ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
3217 ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
3218 ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
3219 ImageFormat::Tiff => {
3220 #[cfg(feature = "image-tiff")]
3221 {
3222 frames_for_image(&self.bytes, image::ImageFormat::Tiff)?
3223 }
3224 #[cfg(not(feature = "image-tiff"))]
3225 {
3226 anyhow::bail!("TIFF format not enabled, enable `image-tiff` feature")
3227 }
3228 }
3229 ImageFormat::Ico => frames_for_image(&self.bytes, image::ImageFormat::Ico)?,
3230 ImageFormat::Svg => {
3231 return svg_renderer
3232 .render_single_frame(&self.bytes, 1.0)
3233 .map_err(Into::into);
3234 }
3235 ImageFormat::Pnm => frames_for_image(&self.bytes, image::ImageFormat::Pnm)?,
3236 };
3237
3238 Ok(Arc::new(RenderImage::new(frames)))
3239 }
3240
3241 pub fn format(&self) -> ImageFormat {
3243 self.format
3244 }
3245
3246 pub fn bytes(&self) -> &[u8] {
3248 self.bytes.as_slice()
3249 }
3250}
3251
3252#[derive(Clone, Debug, Eq, PartialEq)]
3254pub struct ClipboardString {
3255 pub text: String,
3257 pub metadata: Option<String>,
3259}
3260
3261impl ClipboardString {
3262 pub fn new(text: String) -> Self {
3264 Self {
3265 text,
3266 metadata: None,
3267 }
3268 }
3269
3270 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
3275 match serde_json::to_string(&metadata) {
3276 Ok(json) => self.metadata = Some(json),
3277 Err(err) => log::warn!("[rgpui::platform] 剪贴板元数据 JSON 序列化失败,已忽略:{err}"),
3278 }
3279 self
3280 }
3281
3282 pub fn text(&self) -> &String {
3284 &self.text
3285 }
3286
3287 pub fn into_text(self) -> String {
3289 self.text
3290 }
3291
3292 pub fn metadata_json<T>(&self) -> Option<T>
3294 where
3295 T: for<'a> Deserialize<'a>,
3296 {
3297 self.metadata
3298 .as_ref()
3299 .and_then(|m| serde_json::from_str(m).ok())
3300 }
3301
3302 pub fn text_hash(text: &str) -> u64 {
3304 let mut hasher = SeaHasher::new();
3305 text.hash(&mut hasher);
3306 hasher.finish()
3307 }
3308}
3309
3310impl From<String> for ClipboardString {
3311 fn from(value: String) -> Self {
3312 Self {
3313 text: value,
3314 metadata: None,
3315 }
3316 }
3317}
3318
3319#[cfg(test)]
3320mod image_tests {
3321 use super::*;
3322 use std::sync::Arc;
3323
3324 #[test]
3325 fn test_svg_image_to_image_data_converts_to_bgra() {
3326 let image = Image::from_bytes(
3327 ImageFormat::Svg,
3328 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
3329<rect width="1" height="1" fill="#38BDF8"/>
3330</svg>"##
3331 .to_vec(),
3332 );
3333
3334 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
3335 let bytes = render_image.as_bytes(0).unwrap();
3336
3337 for pixel in bytes.chunks_exact(4) {
3338 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
3339 }
3340 }
3341}
3342
3343#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
3344mod tests {
3345 use super::*;
3346 use rgpui::collections::HashSet;
3347
3348 #[test]
3349 fn test_window_button_layout_parse_standard() {
3350 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
3351 assert_eq!(
3352 layout.left,
3353 [
3354 Some(WindowButton::Close),
3355 Some(WindowButton::Minimize),
3356 None
3357 ]
3358 );
3359 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3360 }
3361
3362 #[test]
3363 fn test_window_button_layout_parse_right_only() {
3364 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
3365 assert_eq!(layout.left, [None, None, None]);
3366 assert_eq!(
3367 layout.right,
3368 [
3369 Some(WindowButton::Minimize),
3370 Some(WindowButton::Maximize),
3371 Some(WindowButton::Close)
3372 ]
3373 );
3374 }
3375
3376 #[test]
3377 fn test_window_button_layout_parse_left_only() {
3378 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
3379 assert_eq!(
3380 layout.left,
3381 [
3382 Some(WindowButton::Close),
3383 Some(WindowButton::Minimize),
3384 Some(WindowButton::Maximize)
3385 ]
3386 );
3387 assert_eq!(layout.right, [None, None, None]);
3388 }
3389
3390 #[test]
3391 fn test_window_button_layout_parse_with_whitespace() {
3392 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
3393 assert_eq!(
3394 layout.left,
3395 [
3396 Some(WindowButton::Close),
3397 Some(WindowButton::Minimize),
3398 None
3399 ]
3400 );
3401 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3402 }
3403
3404 #[test]
3405 fn test_window_button_layout_parse_empty() {
3406 let layout = WindowButtonLayout::parse("").unwrap();
3407 assert_eq!(layout.left, [None, None, None]);
3408 assert_eq!(layout.right, [None, None, None]);
3409 }
3410
3411 #[test]
3412 fn test_window_button_layout_parse_intentionally_empty() {
3413 let layout = WindowButtonLayout::parse(":").unwrap();
3414 assert_eq!(layout.left, [None, None, None]);
3415 assert_eq!(layout.right, [None, None, None]);
3416 }
3417
3418 #[test]
3419 fn test_window_button_layout_parse_invalid_buttons() {
3420 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
3421 assert_eq!(
3422 layout.left,
3423 [
3424 Some(WindowButton::Close),
3425 Some(WindowButton::Minimize),
3426 None
3427 ]
3428 );
3429 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3430 }
3431
3432 #[test]
3433 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
3434 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
3435 assert_eq!(
3436 layout.right,
3437 [
3438 Some(WindowButton::Close),
3439 Some(WindowButton::Minimize),
3440 None
3441 ]
3442 );
3443 assert_eq!(layout.format(), ":close,minimize");
3444 }
3445
3446 #[test]
3447 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
3448 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
3449 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3450 assert_eq!(
3451 layout.right,
3452 [
3453 Some(WindowButton::Maximize),
3454 Some(WindowButton::Minimize),
3455 None
3456 ]
3457 );
3458
3459 let button_ids: Vec<_> = layout
3460 .left
3461 .iter()
3462 .chain(layout.right.iter())
3463 .flatten()
3464 .map(WindowButton::id)
3465 .collect();
3466 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
3467 assert_eq!(unique_button_ids.len(), button_ids.len());
3468 assert_eq!(layout.format(), "close:maximize,minimize");
3469 }
3470
3471 #[test]
3472 fn test_window_button_layout_parse_gnome_style() {
3473 let layout = WindowButtonLayout::parse("close").unwrap();
3474 assert_eq!(layout.left, [None, None, None]);
3475 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
3476 }
3477
3478 #[test]
3479 fn test_window_button_layout_parse_elementary_style() {
3480 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
3481 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3482 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3483 }
3484
3485 #[test]
3486 fn test_window_button_layout_round_trip() {
3487 let cases = [
3488 "close:minimize,maximize",
3489 "minimize,maximize,close:",
3490 ":close",
3491 "close:",
3492 "close:maximize",
3493 ":",
3494 ];
3495
3496 for case in cases {
3497 let layout = WindowButtonLayout::parse(case).unwrap();
3498 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
3499 }
3500 }
3501
3502 #[test]
3503 fn test_window_button_layout_linux_default() {
3504 let layout = WindowButtonLayout::linux_default();
3505 assert_eq!(layout.left, [None, None, None]);
3506 assert_eq!(
3507 layout.right,
3508 [
3509 Some(WindowButton::Minimize),
3510 Some(WindowButton::Maximize),
3511 Some(WindowButton::Close)
3512 ]
3513 );
3514
3515 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
3516 assert_eq!(round_tripped, layout);
3517 }
3518
3519 #[test]
3520 fn test_window_button_layout_parse_all_invalid() {
3521 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
3522 }
3523}