1mod app_menu;
2mod keyboard;
3mod keystroke;
4
5#[cfg(all(target_os = "linux", feature = "wayland"))]
6#[expect(missing_docs)]
7pub mod layer_shell;
8
9pub mod popup;
11
12#[cfg(any(test, feature = "bench"))]
13mod bench_dispatcher;
14
15#[cfg(any(test, feature = "test-support"))]
16mod test;
17
18#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
19mod visual_test;
20
21#[cfg(all(
22 feature = "screen-capture",
23 any(target_os = "windows", target_os = "linux", target_os = "freebsd",)
24))]
25pub mod scap_screen_capture;
26
27#[cfg(all(
28 any(target_os = "windows", target_os = "linux"),
29 feature = "screen-capture"
30))]
31pub(crate) type PlatformScreenCaptureFrame = scap::frame::Frame;
32#[cfg(not(feature = "screen-capture"))]
33pub(crate) type PlatformScreenCaptureFrame = ();
34#[cfg(all(target_os = "macos", feature = "screen-capture"))]
35pub(crate) type PlatformScreenCaptureFrame = core_video::image_buffer::CVImageBuffer;
36
37use crate::{
38 Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
39 DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, ExternalDragPayload, Font,
40 FontId, FontMetrics, FontRun, ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap,
41 LineLayout, Pixels, PlatformGestures, PlatformInput, Point, Priority, RenderGlyphParams,
42 RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString,
43 Size, SvgRenderer, SystemWindowTab, Task, Window, WindowControlArea, hash, point, px, size,
44};
45#[cfg(any(target_os = "linux", target_os = "freebsd"))]
46use anyhow::bail;
47use anyhow::{Context as _, Result};
48use async_task::Runnable;
49use futures::channel::oneshot;
50#[cfg(any(test, feature = "test-support"))]
51use image::RgbaImage;
52use image::codecs::gif::GifDecoder;
53use image::{AnimationDecoder as _, DynamicImage, Frame};
54use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
55use scheduler::Instant;
56pub use scheduler::RunnableMeta;
57use schemars::JsonSchema;
58use seahash::SeaHasher;
59use serde::{Deserialize, Serialize};
60use smallvec::SmallVec;
61use std::borrow::Cow;
62use std::hash::{Hash, Hasher};
63use std::io::Cursor;
64use std::ops;
65use std::time::Duration;
66use std::{
67 fmt::{self, Debug},
68 ops::Range,
69 path::{Path, PathBuf},
70 rc::Rc,
71 sync::Arc,
72};
73use strum::EnumIter;
74use uuid::Uuid;
75
76pub use app_menu::*;
77pub use keyboard::*;
78pub use keystroke::*;
79
80#[cfg(any(test, feature = "test-support"))]
81pub(crate) use test::*;
82
83#[cfg(any(test, feature = "test-support"))]
84pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
85
86#[cfg(any(test, feature = "bench"))]
87pub use bench_dispatcher::BenchDispatcher;
88
89#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
90pub use visual_test::VisualTestPlatform;
91
92#[cfg(any(target_os = "linux", target_os = "freebsd"))]
96#[inline]
97pub fn guess_compositor() -> &'static str {
98 if std::env::var_os("ZED_HEADLESS").is_some() {
99 return "Headless";
100 }
101
102 #[cfg(feature = "wayland")]
103 let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
104 #[cfg(not(feature = "wayland"))]
105 let wayland_display: Option<std::ffi::OsString> = None;
106
107 #[cfg(feature = "x11")]
108 let x11_display = std::env::var_os("DISPLAY");
109 #[cfg(not(feature = "x11"))]
110 let x11_display: Option<std::ffi::OsString> = None;
111
112 let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
113 let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
114
115 if use_wayland {
116 "Wayland"
117 } else if use_x11 {
118 "X11"
119 } else {
120 "Headless"
121 }
122}
123
124#[expect(missing_docs)]
125pub trait Platform: 'static {
126 fn background_executor(&self) -> BackgroundExecutor;
127 fn foreground_executor(&self) -> ForegroundExecutor;
128 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
129
130 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
131 fn quit(&self);
132 fn restart(&self, binary_path: Option<PathBuf>);
133 fn activate(&self, ignoring_other_apps: bool);
134 fn hide(&self);
135 fn hide_other_apps(&self);
136 fn unhide_other_apps(&self);
137
138 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
139 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
140 fn active_window(&self) -> Option<AnyWindowHandle>;
141 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
142 None
143 }
144
145 fn is_screen_capture_supported(&self) -> bool {
146 false
147 }
148
149 fn screen_capture_sources(
150 &self,
151 ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
152 let (sources_tx, sources_rx) = oneshot::channel();
153 sources_tx
154 .send(Err(anyhow::anyhow!(
155 "gpui was compiled without the screen-capture feature"
156 )))
157 .ok();
158 sources_rx
159 }
160
161 fn open_window(
162 &self,
163 handle: AnyWindowHandle,
164 options: WindowParams,
165 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
166
167 fn window_appearance(&self) -> WindowAppearance;
169
170 fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
179
180 fn button_layout(&self) -> Option<WindowButtonLayout> {
182 None
183 }
184
185 fn open_url(&self, url: &str);
186 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
187 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
188
189 fn prompt_for_paths(
190 &self,
191 options: PathPromptOptions,
192 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
193 fn prompt_for_new_path(
194 &self,
195 directory: &Path,
196 suggested_name: Option<&str>,
197 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
198 fn can_select_mixed_files_and_dirs(&self) -> bool;
199 fn reveal_path(&self, path: &Path);
200 fn open_with_system(&self, path: &Path);
201
202 fn on_quit(&self, callback: Box<dyn FnMut()>);
203 fn on_reopen(&self, callback: Box<dyn FnMut()>);
204 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
205
206 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
216
217 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
222
223 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
227 None
228 }
229
230 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
231 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
232 None
233 }
234
235 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
236 fn perform_dock_menu_action(&self, _action: usize) {}
237 fn add_recent_document(&self, _path: &Path) {}
238 fn update_jump_list(
239 &self,
240 _menus: Vec<MenuItem>,
241 _entries: Vec<SmallVec<[PathBuf; 2]>>,
242 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
243 Task::ready(Vec::new())
244 }
245 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
246 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
247 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
248
249 fn thermal_state(&self) -> ThermalState;
250 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
251
252 fn set_app_identity(&self, identifier: &str, name: &str) {
259 _ = (identifier, name);
260 }
261
262 fn show_system_notification(&self, notification: SystemNotification) {
269 _ = notification;
270 }
271
272 fn dismiss_system_notification(&self, tag: &str) {
277 _ = tag;
278 }
279
280 fn on_system_notification_response(
286 &self,
287 callback: Box<dyn FnMut(SystemNotificationResponse)>,
288 ) {
289 _ = callback;
290 }
291
292 fn compositor_name(&self) -> &'static str {
293 ""
294 }
295 fn app_path(&self) -> Result<PathBuf>;
296 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
297
298 fn set_cursor_style(&self, style: CursorStyle);
299
300 fn hide_cursor_until_mouse_moves(&self);
303
304 fn is_cursor_visible(&self) -> bool;
306
307 fn should_auto_hide_scrollbars(&self) -> bool;
308
309 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
310 fn read_text_from_clipboard_async(&self) -> Task<Option<String>> {
313 Task::ready(
314 self.read_from_clipboard()
315 .and_then(|item| item.plain_text()),
316 )
317 }
318
319 fn write_to_clipboard(&self, item: ClipboardItem);
320
321 fn supports_file_clipboard(&self, _operation: FileClipboardOperation) -> bool {
324 false
325 }
326
327 fn write_files_to_clipboard(
329 &self,
330 _paths: crate::ExternalPaths,
331 _operation: FileClipboardOperation,
332 ) -> std::result::Result<(), FileClipboardError> {
333 Err(FileClipboardError::Unsupported)
334 }
335
336 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
337 fn read_from_primary(&self) -> Option<ClipboardItem>;
338 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
339 fn write_to_primary(&self, item: ClipboardItem);
340
341 #[cfg(target_os = "macos")]
342 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
343 #[cfg(target_os = "macos")]
344 fn write_to_find_pasteboard(&self, item: ClipboardItem);
345
346 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
347 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
348 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
349
350 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
351 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
352 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
353}
354
355pub trait PlatformDisplay: Debug {
357 fn id(&self) -> DisplayId;
359
360 fn uuid(&self) -> Result<Uuid>;
363
364 fn bounds(&self) -> Bounds<Pixels>;
366
367 fn visible_bounds(&self) -> Bounds<Pixels> {
371 self.bounds()
372 }
373
374 fn default_bounds(&self) -> Bounds<Pixels> {
376 let bounds = self.bounds();
377 let center = bounds.center();
378 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
379
380 let offset = clipped_window_size / 2.0;
381 let origin = point(center.x - offset.width, center.y - offset.height);
382 Bounds::new(origin, clipped_window_size)
383 }
384}
385
386#[derive(Clone, Debug, PartialEq, Eq)]
389pub struct SystemNotification {
390 pub tag: SharedString,
394 pub title: SharedString,
396 pub body: SharedString,
398 pub actions: Vec<SystemNotificationAction>,
401}
402
403#[derive(Clone, Debug, PartialEq, Eq, Hash)]
405pub struct SystemNotificationAction {
406 pub id: SharedString,
409 pub label: SharedString,
411}
412
413#[derive(Clone, Debug, PartialEq, Eq)]
415pub struct SystemNotificationResponse {
416 pub tag: SharedString,
418 pub action_id: Option<SharedString>,
421}
422
423#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425pub enum ThermalState {
426 Nominal,
428 Fair,
430 Serious,
432 Critical,
434}
435
436#[derive(Clone)]
438pub struct SourceMetadata {
439 pub id: u64,
441 pub label: Option<SharedString>,
443 pub is_main: Option<bool>,
445 pub resolution: Size<DevicePixels>,
447}
448
449pub trait ScreenCaptureSource {
451 fn metadata(&self) -> Result<SourceMetadata>;
453
454 fn stream(
457 &self,
458 foreground_executor: &ForegroundExecutor,
459 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
460 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
461}
462
463pub trait ScreenCaptureStream {
465 fn metadata(&self) -> Result<SourceMetadata>;
467}
468
469pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
471
472#[derive(PartialEq, Eq, Hash, Copy, Clone)]
474pub struct DisplayId(pub(crate) u64);
475
476impl DisplayId {
477 pub fn new(id: u64) -> Self {
479 Self(id)
480 }
481}
482
483impl From<u64> for DisplayId {
484 fn from(id: u64) -> Self {
485 Self(id)
486 }
487}
488
489impl From<DisplayId> for u64 {
490 fn from(id: DisplayId) -> Self {
491 id.0
492 }
493}
494
495impl Debug for DisplayId {
496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497 write!(f, "DisplayId({})", self.0)
498 }
499}
500
501#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub enum ResizeEdge {
504 Top,
506 TopRight,
508 Right,
510 BottomRight,
512 Bottom,
514 BottomLeft,
516 Left,
518 TopLeft,
520}
521
522#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
524pub enum WindowDecorations {
525 #[default]
526 Server,
528 Client,
530}
531
532#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
534pub enum Decorations {
535 #[default]
537 Server,
538 Client {
540 tiling: Tiling,
542 },
543}
544
545#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
547pub struct WindowControls {
548 pub fullscreen: bool,
550 pub maximize: bool,
552 pub minimize: bool,
554 pub window_menu: bool,
556}
557
558impl Default for WindowControls {
559 fn default() -> Self {
560 Self {
562 fullscreen: true,
563 maximize: true,
564 minimize: true,
565 window_menu: true,
566 }
567 }
568}
569
570#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
572pub enum WindowButton {
573 Minimize,
575 Maximize,
577 Close,
579}
580
581impl WindowButton {
582 pub fn id(&self) -> &'static str {
584 match self {
585 WindowButton::Minimize => "minimize",
586 WindowButton::Maximize => "maximize",
587 WindowButton::Close => "close",
588 }
589 }
590
591 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
592 fn index(&self) -> usize {
593 match self {
594 WindowButton::Minimize => 0,
595 WindowButton::Maximize => 1,
596 WindowButton::Close => 2,
597 }
598 }
599}
600
601pub const MAX_BUTTONS_PER_SIDE: usize = 3;
603
604#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub struct WindowButtonLayout {
610 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
612 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
614}
615
616#[cfg(any(target_os = "linux", target_os = "freebsd"))]
617impl WindowButtonLayout {
618 pub fn linux_default() -> Self {
620 Self {
621 left: [None; MAX_BUTTONS_PER_SIDE],
622 right: [
623 Some(WindowButton::Minimize),
624 Some(WindowButton::Maximize),
625 Some(WindowButton::Close),
626 ],
627 }
628 }
629
630 pub fn parse(layout_string: &str) -> Result<Self> {
632 fn parse_side(
633 s: &str,
634 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
635 unrecognized: &mut Vec<String>,
636 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
637 let mut result = [None; MAX_BUTTONS_PER_SIDE];
638 let mut i = 0;
639 for name in s.split(',') {
640 let trimmed = name.trim();
641 if trimmed.is_empty() {
642 continue;
643 }
644 let button = match trimmed {
645 "minimize" => Some(WindowButton::Minimize),
646 "maximize" => Some(WindowButton::Maximize),
647 "close" => Some(WindowButton::Close),
648 other => {
649 unrecognized.push(other.to_string());
650 None
651 }
652 };
653 if let Some(button) = button {
654 if seen_buttons[button.index()] {
655 continue;
656 }
657 if let Some(slot) = result.get_mut(i) {
658 *slot = Some(button);
659 seen_buttons[button.index()] = true;
660 i += 1;
661 }
662 }
663 }
664 result
665 }
666
667 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
668 let mut unrecognized = Vec::new();
669 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
670 let layout = Self {
671 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
672 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
673 };
674
675 if !unrecognized.is_empty()
676 && layout.left.iter().all(Option::is_none)
677 && layout.right.iter().all(Option::is_none)
678 {
679 bail!(
680 "button layout string {:?} contains no valid buttons (unrecognized: {})",
681 layout_string,
682 unrecognized.join(", ")
683 );
684 }
685
686 Ok(layout)
687 }
688
689 #[cfg(test)]
691 pub fn format(&self) -> String {
692 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
693 buttons
694 .iter()
695 .flatten()
696 .map(|button| match button {
697 WindowButton::Minimize => "minimize",
698 WindowButton::Maximize => "maximize",
699 WindowButton::Close => "close",
700 })
701 .collect::<Vec<_>>()
702 .join(",")
703 }
704
705 format!("{}:{}", format_side(&self.left), format_side(&self.right))
706 }
707}
708
709#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
711pub struct Tiling {
712 pub top: bool,
714 pub left: bool,
716 pub right: bool,
718 pub bottom: bool,
720}
721
722impl Tiling {
723 pub fn tiled() -> Self {
725 Self {
726 top: true,
727 left: true,
728 right: true,
729 bottom: true,
730 }
731 }
732
733 pub fn is_tiled(&self) -> bool {
735 self.top || self.left || self.right || self.bottom
736 }
737}
738
739pub struct A11yCallbacks {
741 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
743 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
745 pub deactivation: Box<dyn Fn() + Send + 'static>,
747}
748
749#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
750#[expect(missing_docs)]
751pub struct RequestFrameOptions {
752 pub require_presentation: bool,
754 pub force_render: bool,
756}
757
758#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
771pub enum AppLifecyclePhase {
772 Active,
774 Inactive,
776 Background,
779 Foreground,
781}
782
783#[derive(Debug, Clone, Default, PartialEq)]
790pub struct WindowInsets {
791 pub safe_area: Edges<Pixels>,
796 pub ime: Edges<Pixels>,
800}
801
802impl WindowInsets {
803 pub fn effective(&self) -> Edges<Pixels> {
805 Edges {
806 top: self.safe_area.top.max(self.ime.top),
807 right: self.safe_area.right.max(self.ime.right),
808 bottom: self.safe_area.bottom.max(self.ime.bottom),
809 left: self.safe_area.left.max(self.ime.left),
810 }
811 }
812}
813
814#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
816pub enum TextInputStateChange {
817 FocusGained,
819 FocusLost,
821 SelectionChanged,
823 ContentChanged,
825}
826
827#[expect(missing_docs)]
828pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
829 fn bounds(&self) -> Bounds<Pixels>;
830 fn is_maximized(&self) -> bool;
831 fn window_bounds(&self) -> WindowBounds;
832 fn content_size(&self) -> Size<Pixels>;
833 fn resize(&mut self, size: Size<Pixels>);
834 fn scale_factor(&self) -> f32;
835 fn appearance(&self) -> WindowAppearance;
836 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
837 fn mouse_position(&self) -> Point<Pixels>;
838 fn modifiers(&self) -> Modifiers;
839 fn capslock(&self) -> Capslock;
840 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
841 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
842 fn prompt(
843 &self,
844 level: PromptLevel,
845 msg: &str,
846 detail: Option<&str>,
847 answers: &[PromptButton],
848 ) -> Option<oneshot::Receiver<usize>>;
849 fn activate(&self);
850 fn request_attention(&self) {}
852 fn is_active(&self) -> bool;
853 fn is_hovered(&self) -> bool;
854 fn background_appearance(&self) -> WindowBackgroundAppearance;
855 fn set_title(&mut self, title: &str);
856 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
857 fn minimize(&self);
858 fn zoom(&self);
859 fn toggle_fullscreen(&self);
860 fn is_fullscreen(&self) -> bool;
861 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
862 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
863 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
864 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
865 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
866 fn on_moved(&self, callback: Box<dyn FnMut()>);
867 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
868 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
869 fn on_close(&self, callback: Box<dyn FnOnce()>);
870 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
871 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
872 fn draw(&self, scene: &Scene);
873 fn completed_frame(&self) {}
874 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
875 fn is_subpixel_rendering_supported(&self) -> bool;
876
877 fn get_title(&self) -> String {
879 String::new()
880 }
881 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
882 None
883 }
884 fn tab_bar_visible(&self) -> bool {
885 false
886 }
887 fn set_edited(&mut self, _edited: bool) {}
888 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
889 #[cfg(target_os = "macos")]
890 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
891 fn show_character_palette(&self) {}
892 fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {}
893 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
894 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
895 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
896 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
897 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
898 fn merge_all_windows(&self) {}
899 fn move_tab_to_new_window(&self) {}
900 fn toggle_window_tab_overview(&self) {}
901 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
902
903 #[cfg(target_os = "windows")]
904 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
905
906 fn inner_window_bounds(&self) -> WindowBounds {
908 self.window_bounds()
909 }
910 fn request_decorations(&self, _decorations: WindowDecorations) {}
911 fn show_window_menu(&self, _position: Point<Pixels>) {}
912 fn start_window_move(&self) {}
913 fn can_start_external_drag(&self) -> bool {
914 false
915 }
916 fn start_external_drag(&self, _payload: &ExternalDragPayload) -> bool {
917 false
918 }
919 fn start_window_resize(&self, _edge: ResizeEdge) {}
920 fn set_exclusive_zone(&self, _zone: Pixels) {}
921 #[cfg(all(target_os = "linux", feature = "wayland"))]
922 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
923 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
924 fn window_decorations(&self) -> Decorations {
925 Decorations::Server
926 }
927 fn set_app_id(&mut self, _app_id: &str) {}
928 fn map_window(&mut self) -> anyhow::Result<()> {
929 Ok(())
930 }
931 fn window_controls(&self) -> WindowControls {
932 WindowControls::default()
933 }
934 fn set_client_inset(&self, _inset: Pixels) {}
935 fn gpu_specs(&self) -> Option<GpuSpecs>;
936
937 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
938
939 fn insets(&self) -> WindowInsets {
944 WindowInsets::default()
945 }
946
947 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
953
954 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
957
958 fn set_back_enabled(&self, _enabled: bool) {}
961
962 fn show_soft_keyboard(&self) {}
964
965 fn hide_soft_keyboard(&self) {}
967
968 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
970
971 fn play_system_bell(&self) {}
972
973 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
975
976 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
978
979 fn a11y_update_window_bounds(&self) {}
981
982 #[cfg(any(test, feature = "test-support"))]
983 fn as_test(&mut self) -> Option<&mut TestWindow> {
984 None
985 }
986
987 #[cfg(any(test, feature = "test-support"))]
991 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
992 anyhow::bail!("render_to_image not implemented for this platform")
993 }
994}
995
996#[cfg(any(test, feature = "test-support"))]
998pub trait PlatformHeadlessRenderer {
999 fn render_scene_to_image(
1001 &mut self,
1002 scene: &Scene,
1003 size: Size<DevicePixels>,
1004 ) -> Result<RgbaImage>;
1005
1006 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
1012
1013 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
1015}
1016
1017#[doc(hidden)]
1020pub type RunnableVariant = Runnable<RunnableMeta>;
1021
1022#[doc(hidden)]
1023pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
1024
1025#[doc(hidden)]
1026pub enum TasksIncluded {
1027 OnlyCompleted,
1028 CompletedAndRunning,
1029}
1030
1031#[doc(hidden)]
1034pub trait PlatformDispatcher: Send + Sync {
1035 fn is_main_thread(&self) -> bool;
1036 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
1037 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
1038 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
1039
1040 fn dispatch_on_main_thread_when_idle(
1041 &self,
1042 runnable: RunnableVariant,
1043 timeout: Option<Duration>,
1044 ) {
1045 let _ = timeout;
1046 self.dispatch_on_main_thread(runnable, Priority::Low);
1047 }
1048
1049 fn idle_time_remaining(&self) -> Option<Duration> {
1050 None
1051 }
1052
1053 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1054
1055 fn now(&self) -> Instant {
1056 Instant::now()
1057 }
1058
1059 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1060 gpui_util::defer(Box::new(|| {}))
1061 }
1062
1063 #[cfg(any(test, feature = "test-support"))]
1064 fn as_test(&self) -> Option<&TestDispatcher> {
1065 None
1066 }
1067
1068 #[cfg(any(test, feature = "bench"))]
1071 fn as_bench(&self) -> Option<&BenchDispatcher> {
1072 None
1073 }
1074}
1075
1076#[expect(missing_docs)]
1077pub trait PlatformTextSystem: Send + Sync {
1078 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1079 fn all_font_names(&self) -> Vec<String>;
1081 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1083 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1085 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1087 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1089 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1091 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1093 fn rasterize_glyph(
1095 &self,
1096 params: &RenderGlyphParams,
1097 raster_bounds: Bounds<DevicePixels>,
1098 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1099 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1101 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1103 -> TextRenderingMode;
1104 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1106 0
1107 }
1108}
1109
1110#[expect(missing_docs)]
1111pub struct NoopTextSystem;
1112
1113#[expect(missing_docs)]
1114impl NoopTextSystem {
1115 #[allow(dead_code)]
1116 pub fn new() -> Self {
1117 Self
1118 }
1119}
1120
1121impl PlatformTextSystem for NoopTextSystem {
1122 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1123 Ok(())
1124 }
1125
1126 fn all_font_names(&self) -> Vec<String> {
1127 Vec::new()
1128 }
1129
1130 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1131 Ok(FontId(1))
1132 }
1133
1134 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1135 FontMetrics {
1136 units_per_em: 1000,
1137 ascent: 1025.0,
1138 descent: -275.0,
1139 line_gap: 0.0,
1140 underline_position: -95.0,
1141 underline_thickness: 60.0,
1142 cap_height: 698.0,
1143 x_height: 516.0,
1144 bounding_box: Bounds {
1145 origin: Point {
1146 x: -260.0,
1147 y: -245.0,
1148 },
1149 size: Size {
1150 width: 1501.0,
1151 height: 1364.0,
1152 },
1153 },
1154 }
1155 }
1156
1157 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1158 Ok(Bounds {
1159 origin: Point { x: 54.0, y: 0.0 },
1160 size: size(392.0, 528.0),
1161 })
1162 }
1163
1164 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1165 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1166 }
1167
1168 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1169 Some(GlyphId(ch.len_utf16() as u32))
1170 }
1171
1172 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1173 Ok(Default::default())
1174 }
1175
1176 fn rasterize_glyph(
1177 &self,
1178 _params: &RenderGlyphParams,
1179 raster_bounds: Bounds<DevicePixels>,
1180 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1181 Ok((raster_bounds.size, Vec::new()))
1182 }
1183
1184 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1185 let mut position = px(0.);
1186 let metrics = self.font_metrics(FontId(0));
1187 let em_width = font_size
1188 * self
1189 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1190 .unwrap()
1191 .width
1192 / metrics.units_per_em as f32;
1193 let mut glyphs = Vec::new();
1194 for (ix, c) in text.char_indices() {
1195 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1196 glyphs.push(ShapedGlyph {
1197 id: glyph,
1198 position: point(position, px(0.)),
1199 index: ix,
1200 is_emoji: glyph.0 == 2,
1201 });
1202 if glyph.0 == 2 {
1203 position += em_width * 2.0;
1204 } else {
1205 position += em_width;
1206 }
1207 } else {
1208 position += em_width
1209 }
1210 }
1211 let mut runs = Vec::default();
1212 if !glyphs.is_empty() {
1213 runs.push(ShapedRun {
1214 font_id: FontId(0),
1215 glyphs,
1216 });
1217 } else {
1218 position = px(0.);
1219 }
1220
1221 LineLayout {
1222 font_size,
1223 width: position,
1224 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1225 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1226 runs,
1227 len: text.len(),
1228 }
1229 }
1230
1231 fn recommended_rendering_mode(
1232 &self,
1233 _font_id: FontId,
1234 _font_size: Pixels,
1235 ) -> TextRenderingMode {
1236 TextRenderingMode::Grayscale
1237 }
1238}
1239
1240#[allow(dead_code)]
1245pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1246 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1247 [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], ];
1261
1262 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1263 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1264
1265 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1266 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1267
1268 [
1269 ratios[0] * NORM13,
1270 ratios[1] * NORM24,
1271 ratios[2] * NORM13,
1272 ratios[3] * NORM24,
1273 ]
1274}
1275
1276#[derive(PartialEq, Eq, Hash, Clone)]
1277#[expect(missing_docs)]
1278pub enum AtlasKey {
1279 Glyph(RenderGlyphParams),
1280 Svg(RenderSvgParams),
1281 Image(RenderImageParams),
1282}
1283
1284impl AtlasKey {
1285 #[cfg_attr(
1286 all(
1287 any(target_os = "linux", target_os = "freebsd"),
1288 not(any(feature = "x11", feature = "wayland"))
1289 ),
1290 allow(dead_code)
1291 )]
1292 pub fn texture_kind(&self) -> AtlasTextureKind {
1294 match self {
1295 AtlasKey::Glyph(params) => {
1296 if params.is_emoji {
1297 AtlasTextureKind::Polychrome
1298 } else if params.subpixel_rendering {
1299 AtlasTextureKind::Subpixel
1300 } else {
1301 AtlasTextureKind::Monochrome
1302 }
1303 }
1304 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1305 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1306 }
1307 }
1308}
1309
1310impl From<RenderGlyphParams> for AtlasKey {
1311 fn from(params: RenderGlyphParams) -> Self {
1312 Self::Glyph(params)
1313 }
1314}
1315
1316impl From<RenderSvgParams> for AtlasKey {
1317 fn from(params: RenderSvgParams) -> Self {
1318 Self::Svg(params)
1319 }
1320}
1321
1322impl From<RenderImageParams> for AtlasKey {
1323 fn from(params: RenderImageParams) -> Self {
1324 Self::Image(params)
1325 }
1326}
1327
1328#[expect(missing_docs)]
1329pub trait PlatformAtlas {
1330 fn get_or_insert_with<'a>(
1331 &self,
1332 key: &AtlasKey,
1333 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1334 ) -> Result<Option<AtlasTile>>;
1335 fn remove(&self, key: &AtlasKey);
1336
1337 #[cfg(any(test, feature = "test-support"))]
1338 fn contains(&self, _key: &AtlasKey) -> bool {
1339 false
1340 }
1341}
1342
1343#[doc(hidden)]
1344pub struct AtlasTextureList<T> {
1345 pub textures: Vec<Option<T>>,
1346 pub free_list: Vec<usize>,
1347}
1348
1349impl<T> Default for AtlasTextureList<T> {
1350 fn default() -> Self {
1351 Self {
1352 textures: Vec::default(),
1353 free_list: Vec::default(),
1354 }
1355 }
1356}
1357
1358impl<T> ops::Index<usize> for AtlasTextureList<T> {
1359 type Output = Option<T>;
1360
1361 fn index(&self, index: usize) -> &Self::Output {
1362 &self.textures[index]
1363 }
1364}
1365
1366impl<T> AtlasTextureList<T> {
1367 #[allow(unused)]
1368 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1369 self.free_list.clear();
1370 self.textures.drain(..)
1371 }
1372
1373 #[allow(dead_code)]
1374 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1375 self.textures.iter_mut().flatten()
1376 }
1377}
1378
1379#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1380#[repr(C)]
1381#[expect(missing_docs)]
1382pub struct AtlasTile {
1383 pub texture_id: AtlasTextureId,
1385 pub tile_id: TileId,
1387 pub padding: u32,
1389 pub bounds: Bounds<DevicePixels>,
1391}
1392
1393#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1394#[repr(C)]
1395#[expect(missing_docs)]
1396pub struct AtlasTextureId {
1397 pub index: u32,
1400 pub kind: AtlasTextureKind,
1402}
1403
1404#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1405#[repr(C)]
1406#[cfg_attr(
1407 all(
1408 any(target_os = "linux", target_os = "freebsd"),
1409 not(any(feature = "x11", feature = "wayland"))
1410 ),
1411 allow(dead_code)
1412)]
1413#[expect(missing_docs)]
1414pub enum AtlasTextureKind {
1415 Monochrome = 0,
1416 Polychrome = 1,
1417 Subpixel = 2,
1418}
1419
1420#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1421#[repr(C)]
1422#[expect(missing_docs)]
1423pub struct TileId(pub u32);
1424
1425impl From<etagere::AllocId> for TileId {
1426 fn from(id: etagere::AllocId) -> Self {
1427 Self(id.serialize())
1428 }
1429}
1430
1431impl From<TileId> for etagere::AllocId {
1432 fn from(id: TileId) -> Self {
1433 Self::deserialize(id.0)
1434 }
1435}
1436
1437#[expect(missing_docs)]
1438pub struct PlatformInputHandler {
1439 cx: AsyncWindowContext,
1440 handler: Box<dyn InputHandler>,
1441}
1442
1443#[expect(missing_docs)]
1444#[cfg_attr(
1445 all(
1446 any(target_os = "linux", target_os = "freebsd"),
1447 not(any(feature = "x11", feature = "wayland"))
1448 ),
1449 allow(dead_code)
1450)]
1451impl PlatformInputHandler {
1452 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
1453 Self { cx, handler }
1454 }
1455
1456 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
1457 self.cx
1458 .update(|window, cx| {
1459 self.handler
1460 .selected_text_range(ignore_disabled_input, window, cx)
1461 })
1462 .ok()
1463 .flatten()
1464 }
1465
1466 #[cfg_attr(target_os = "windows", allow(dead_code))]
1467 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
1468 self.cx
1469 .update(|window, cx| self.handler.marked_text_range(window, cx))
1470 .ok()
1471 .flatten()
1472 }
1473
1474 #[cfg_attr(
1475 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1476 allow(dead_code)
1477 )]
1478 pub fn text_for_range(
1479 &mut self,
1480 range_utf16: Range<usize>,
1481 adjusted: &mut Option<Range<usize>>,
1482 ) -> Option<String> {
1483 self.cx
1484 .update(|window, cx| {
1485 self.handler
1486 .text_for_range(range_utf16, adjusted, window, cx)
1487 })
1488 .ok()
1489 .flatten()
1490 }
1491
1492 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
1493 self.cx
1494 .update(|window, cx| {
1495 self.handler
1496 .replace_text_in_range(replacement_range, text, window, cx);
1497 })
1498 .ok();
1499 }
1500
1501 pub fn replace_and_mark_text_in_range(
1502 &mut self,
1503 range_utf16: Option<Range<usize>>,
1504 new_text: &str,
1505 new_selected_range: Option<Range<usize>>,
1506 ) {
1507 self.cx
1508 .update(|window, cx| {
1509 self.handler.replace_and_mark_text_in_range(
1510 range_utf16,
1511 new_text,
1512 new_selected_range,
1513 window,
1514 cx,
1515 )
1516 })
1517 .ok();
1518 }
1519
1520 #[cfg_attr(target_os = "windows", allow(dead_code))]
1521 pub fn unmark_text(&mut self) {
1522 self.cx
1523 .update(|window, cx| self.handler.unmark_text(window, cx))
1524 .ok();
1525 }
1526
1527 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
1528 self.cx
1529 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
1530 .ok()
1531 .flatten()
1532 }
1533
1534 #[allow(dead_code)]
1535 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
1536 self.handler.apple_press_and_hold_enabled()
1537 }
1538
1539 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1540 self.handler.replace_text_in_range(None, input, window, cx);
1541 }
1542
1543 pub fn compute_ime_candidate_bounds(
1544 marked_range: Option<Range<usize>>,
1545 selection: &UTF16Selection,
1546 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
1547 ) -> Option<Bounds<Pixels>> {
1548 if let Some(marked_range) = marked_range {
1549 let mut line_start = marked_range.start;
1551
1552 let caret = selection.range.end;
1556 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
1557 for i in (marked_range.start..caret).rev() {
1558 if let Some(b) = bounds_for_range(i..i) {
1559 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
1560 line_start = i + 1;
1561 break;
1562 }
1563 }
1564 }
1565 }
1566 bounds_for_range(line_start..line_start)
1567 } else {
1568 let offset = if selection.reversed {
1570 selection.range.start
1571 } else {
1572 selection.range.end
1573 };
1574 bounds_for_range(offset..offset)
1575 }
1576 }
1577
1578 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
1579 let marked_range = self.handler.marked_text_range(window, cx);
1580 let selection = self.handler.selected_text_range(true, window, cx)?;
1581 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
1582 self.handler.bounds_for_range(range, window, cx)
1583 })
1584 }
1585
1586 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
1587 let marked_range = self.marked_text_range();
1588 let selection = self.selected_text_range(true)?;
1589 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
1590 self.bounds_for_range(range)
1591 })
1592 }
1593
1594 #[allow(unused)]
1595 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
1596 self.cx
1597 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
1598 .ok()
1599 .flatten()
1600 }
1601
1602 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
1604 self.cx
1605 .update(|window, cx| {
1606 self.handler
1607 .set_selected_text_range(range_utf16, window, cx)
1608 })
1609 .ok();
1610 }
1611
1612 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
1614 self.cx
1615 .update(|window, cx| self.handler.element_bounds(window, cx))
1616 .ok()
1617 .flatten()
1618 }
1619
1620 pub fn text_length_utf16(&mut self) -> Option<usize> {
1622 self.cx
1623 .update(|window, cx| self.handler.text_length_utf16(window, cx))
1624 .ok()
1625 .flatten()
1626 }
1627
1628 #[allow(dead_code)]
1629 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
1630 self.handler.accepts_text_input(window, cx)
1631 }
1632
1633 #[allow(dead_code)]
1634 pub fn query_accepts_text_input(&mut self) -> bool {
1635 self.cx
1636 .update(|window, cx| self.handler.accepts_text_input(window, cx))
1637 .unwrap_or(true)
1638 }
1639
1640 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
1646 self.cx
1647 .update(|window, cx| {
1648 !window.has_pending_keystrokes()
1650 && self.handler.prefers_ime_for_printable_keys(window, cx)
1651 })
1652 .unwrap_or(false)
1653 }
1654}
1655
1656#[derive(Debug)]
1659pub struct UTF16Selection {
1660 pub range: Range<usize>,
1663 pub reversed: bool,
1666}
1667
1668pub trait InputHandler: 'static {
1673 fn selected_text_range(
1678 &mut self,
1679 ignore_disabled_input: bool,
1680 window: &mut Window,
1681 cx: &mut App,
1682 ) -> Option<UTF16Selection>;
1683
1684 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
1689
1690 fn text_for_range(
1695 &mut self,
1696 range_utf16: Range<usize>,
1697 adjusted_range: &mut Option<Range<usize>>,
1698 window: &mut Window,
1699 cx: &mut App,
1700 ) -> Option<String>;
1701
1702 fn replace_text_in_range(
1707 &mut self,
1708 replacement_range: Option<Range<usize>>,
1709 text: &str,
1710 window: &mut Window,
1711 cx: &mut App,
1712 );
1713
1714 fn replace_and_mark_text_in_range(
1721 &mut self,
1722 range_utf16: Option<Range<usize>>,
1723 new_text: &str,
1724 new_selected_range: Option<Range<usize>>,
1725 window: &mut Window,
1726 cx: &mut App,
1727 );
1728
1729 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
1732
1733 fn bounds_for_range(
1740 &mut self,
1741 range_utf16: Range<usize>,
1742 window: &mut Window,
1743 cx: &mut App,
1744 ) -> Option<Bounds<Pixels>>;
1745
1746 fn character_index_for_point(
1751 &mut self,
1752 point: Point<Pixels>,
1753 window: &mut Window,
1754 cx: &mut App,
1755 ) -> Option<usize>;
1756
1757 fn set_selected_text_range(
1767 &mut self,
1768 _range_utf16: Range<usize>,
1769 _window: &mut Window,
1770 _cx: &mut App,
1771 ) {
1772 }
1773
1774 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
1781 None
1782 }
1783
1784 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
1786 None
1787 }
1788
1789 #[allow(dead_code)]
1794 fn apple_press_and_hold_enabled(&mut self) -> bool {
1795 true
1796 }
1797
1798 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1800 true
1801 }
1802
1803 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1812 false
1813 }
1814}
1815
1816#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1820pub enum WindowsCompositionMode {
1821 #[default]
1823 Auto,
1824 DirectComposition,
1826 RedirectionBitmap,
1831}
1832
1833#[derive(Debug)]
1835pub struct WindowOptions {
1836 pub window_bounds: Option<WindowBounds>,
1840
1841 pub titlebar: Option<TitlebarOptions>,
1843
1844 pub focus: bool,
1846
1847 pub show: bool,
1849
1850 pub kind: WindowKind,
1852
1853 pub is_movable: bool,
1857
1858 pub app_owns_titlebar_drag: bool,
1870
1871 pub is_resizable: bool,
1873
1874 pub is_minimizable: bool,
1876
1877 pub display_id: Option<DisplayId>,
1880
1881 pub window_background: WindowBackgroundAppearance,
1883
1884 pub windows_composition: WindowsCompositionMode,
1887
1888 pub app_id: Option<String>,
1890
1891 pub window_min_size: Option<Size<Pixels>>,
1893
1894 pub window_decorations: Option<WindowDecorations>,
1897
1898 pub icon: Option<Arc<image::RgbaImage>>,
1900
1901 pub tabbing_identifier: Option<String>,
1903}
1904
1905#[derive(Debug)]
1907#[cfg_attr(
1908 all(
1909 any(target_os = "linux", target_os = "freebsd"),
1910 not(any(feature = "x11", feature = "wayland"))
1911 ),
1912 allow(dead_code)
1913)]
1914#[allow(missing_docs)]
1915pub struct WindowParams {
1916 pub bounds: Bounds<Pixels>,
1917
1918 pub windows_composition: WindowsCompositionMode,
1919
1920 #[cfg_attr(feature = "wayland", allow(dead_code))]
1922 pub titlebar: Option<TitlebarOptions>,
1923
1924 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1926 pub kind: WindowKind,
1927
1928 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1930 pub is_movable: bool,
1931
1932 #[cfg_attr(
1934 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1935 allow(dead_code)
1936 )]
1937 pub app_owns_titlebar_drag: bool,
1938
1939 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1941 pub is_resizable: bool,
1942
1943 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1945 pub is_minimizable: bool,
1946
1947 #[cfg_attr(
1948 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1949 allow(dead_code)
1950 )]
1951 pub focus: bool,
1952
1953 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1954 pub show: bool,
1955
1956 #[cfg_attr(feature = "wayland", allow(dead_code))]
1958 pub icon: Option<Arc<image::RgbaImage>>,
1959
1960 #[cfg_attr(feature = "wayland", allow(dead_code))]
1961 pub display_id: Option<DisplayId>,
1962
1963 #[cfg_attr(feature = "wayland", allow(dead_code))]
1964 pub app_id: Option<String>,
1965
1966 pub window_min_size: Option<Size<Pixels>>,
1967
1968 #[cfg(target_os = "macos")]
1969 pub tabbing_identifier: Option<String>,
1970}
1971
1972#[derive(Debug, Copy, Clone, PartialEq)]
1974pub enum WindowBounds {
1975 Windowed(Bounds<Pixels>),
1977 Maximized(Bounds<Pixels>),
1980 Fullscreen(Bounds<Pixels>),
1983}
1984
1985impl Default for WindowBounds {
1986 fn default() -> Self {
1987 WindowBounds::Windowed(Bounds::default())
1988 }
1989}
1990
1991impl WindowBounds {
1992 pub fn get_bounds(&self) -> Bounds<Pixels> {
1994 match self {
1995 WindowBounds::Windowed(bounds) => *bounds,
1996 WindowBounds::Maximized(bounds) => *bounds,
1997 WindowBounds::Fullscreen(bounds) => *bounds,
1998 }
1999 }
2000
2001 pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
2003 WindowBounds::Windowed(Bounds::centered(None, size, cx))
2004 }
2005}
2006
2007impl Default for WindowOptions {
2008 fn default() -> Self {
2009 Self {
2010 window_bounds: None,
2011 titlebar: Some(TitlebarOptions {
2012 title: Default::default(),
2013 appears_transparent: Default::default(),
2014 traffic_light_position: Default::default(),
2015 }),
2016 focus: true,
2017 show: true,
2018 kind: WindowKind::Normal,
2019 is_movable: true,
2020 app_owns_titlebar_drag: false,
2021 is_resizable: true,
2022 is_minimizable: true,
2023 display_id: None,
2024 window_background: WindowBackgroundAppearance::default(),
2025 windows_composition: WindowsCompositionMode::default(),
2026 icon: None,
2027 app_id: None,
2028 window_min_size: None,
2029 window_decorations: None,
2030 tabbing_identifier: None,
2031 }
2032 }
2033}
2034
2035#[derive(Debug, Default)]
2037pub struct TitlebarOptions {
2038 pub title: Option<SharedString>,
2040
2041 pub appears_transparent: bool,
2044
2045 pub traffic_light_position: Option<Point<Pixels>>,
2047}
2048
2049#[derive(Clone, Debug, PartialEq, Eq)]
2051pub enum WindowKind {
2052 Normal,
2054
2055 PopUp,
2058
2059 AnchoredPopup(popup::PopupOptions),
2066
2067 Floating,
2069
2070 #[cfg(all(target_os = "linux", feature = "wayland"))]
2073 LayerShell(layer_shell::LayerShellOptions),
2074
2075 Dialog,
2078}
2079
2080#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2085pub enum WindowAppearance {
2086 #[default]
2090 Light,
2091
2092 VibrantLight,
2096
2097 Dark,
2101
2102 VibrantDark,
2106}
2107
2108#[derive(Copy, Clone, Debug, Default, PartialEq)]
2111pub enum WindowBackgroundAppearance {
2112 #[default]
2120 Opaque,
2121 Transparent,
2123 Blurred,
2127 MicaBackdrop,
2129 MicaAltBackdrop,
2131}
2132
2133#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2135pub enum TextRenderingMode {
2136 #[default]
2138 PlatformDefault,
2139 Subpixel,
2141 Grayscale,
2143}
2144
2145#[derive(Clone, Debug)]
2147pub struct PathPromptOptions {
2148 pub files: bool,
2150 pub directories: bool,
2152 pub multiple: bool,
2154 pub prompt: Option<SharedString>,
2156}
2157
2158#[derive(Copy, Clone, Debug, PartialEq)]
2160pub enum PromptLevel {
2161 Info,
2163
2164 Warning,
2166
2167 Critical,
2169}
2170
2171#[derive(Clone, Debug, PartialEq)]
2173pub enum PromptButton {
2174 Ok(SharedString),
2176 Cancel(SharedString),
2178 Other(SharedString),
2180}
2181
2182impl PromptButton {
2183 pub fn new(label: impl Into<SharedString>) -> Self {
2185 PromptButton::Other(label.into())
2186 }
2187
2188 pub fn ok(label: impl Into<SharedString>) -> Self {
2190 PromptButton::Ok(label.into())
2191 }
2192
2193 pub fn cancel(label: impl Into<SharedString>) -> Self {
2195 PromptButton::Cancel(label.into())
2196 }
2197
2198 #[allow(dead_code)]
2200 pub fn is_cancel(&self) -> bool {
2201 matches!(self, PromptButton::Cancel(_))
2202 }
2203
2204 pub fn label(&self) -> &SharedString {
2206 match self {
2207 PromptButton::Ok(label) => label,
2208 PromptButton::Cancel(label) => label,
2209 PromptButton::Other(label) => label,
2210 }
2211 }
2212}
2213
2214impl From<&str> for PromptButton {
2215 fn from(value: &str) -> Self {
2216 match value.to_lowercase().as_str() {
2217 "ok" => PromptButton::Ok("OK".into()),
2218 "cancel" => PromptButton::Cancel("Cancel".into()),
2219 _ => PromptButton::Other(SharedString::from(value.to_owned())),
2220 }
2221 }
2222}
2223
2224#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2226pub enum CursorStyle {
2227 #[default]
2229 Arrow,
2230
2231 IBeam,
2234
2235 Crosshair,
2238
2239 ClosedHand,
2242
2243 OpenHand,
2246
2247 PointingHand,
2250
2251 ResizeLeft,
2254
2255 ResizeRight,
2258
2259 ResizeLeftRight,
2262
2263 ResizeUp,
2266
2267 ResizeDown,
2270
2271 ResizeUpDown,
2274
2275 ResizeUpLeftDownRight,
2278
2279 ResizeUpRightDownLeft,
2282
2283 ResizeColumn,
2286
2287 ResizeRow,
2290
2291 IBeamCursorForVerticalLayout,
2294
2295 OperationNotAllowed,
2298
2299 DragLink,
2302
2303 DragCopy,
2306
2307 ContextualMenu,
2310}
2311
2312#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2315pub enum FileClipboardOperation {
2316 Copy,
2318 Move,
2320}
2321
2322#[derive(Debug, thiserror::Error)]
2324pub enum FileClipboardError {
2325 #[error("file clipboard operation is unsupported on this backend")]
2327 Unsupported,
2328 #[error("file clipboard paths must be nonempty, absolute, and contain no NUL bytes")]
2330 InvalidPaths,
2331 #[error("file clipboard unavailable: {0}")]
2333 Unavailable(String),
2334}
2335
2336impl crate::ExternalPaths {
2337 pub fn validate_for_clipboard(&self) -> std::result::Result<(), FileClipboardError> {
2340 if self.0.is_empty()
2341 || self
2342 .0
2343 .iter()
2344 .any(|path| !path.is_absolute() || path.as_os_str().as_encoded_bytes().contains(&0))
2345 {
2346 return Err(FileClipboardError::InvalidPaths);
2347 }
2348 Ok(())
2349 }
2350
2351 pub fn clipboard_uri_list(&self) -> std::result::Result<String, FileClipboardError> {
2355 #[cfg(not(any(unix, windows, target_os = "wasi")))]
2356 {
2357 Err(FileClipboardError::Unsupported)
2358 }
2359 #[cfg(any(unix, windows, target_os = "wasi"))]
2360 {
2361 self.validate_for_clipboard()?;
2362 let mut result = String::new();
2363 for path in &self.0 {
2364 let uri =
2365 url::Url::from_file_path(path).map_err(|_| FileClipboardError::InvalidPaths)?;
2366 result.push_str(uri.as_str());
2367 result.push_str("\r\n");
2368 }
2369 Ok(result)
2370 }
2371 }
2372
2373 pub fn clipboard_gnome_files(
2375 &self,
2376 operation: FileClipboardOperation,
2377 ) -> std::result::Result<String, FileClipboardError> {
2378 let uris = self.clipboard_uri_list()?;
2379 let verb = match operation {
2380 FileClipboardOperation::Copy => "copy",
2381 FileClipboardOperation::Move => "cut",
2382 };
2383 Ok(format!(
2384 "{verb}\n{}",
2385 uris.trim_end_matches("\r\n").replace("\r\n", "\n")
2386 ))
2387 }
2388}
2389
2390#[derive(Clone, Debug, Eq, PartialEq)]
2392pub struct ClipboardItem {
2393 pub entries: Vec<ClipboardEntry>,
2395}
2396
2397#[derive(Clone, Debug, Eq, PartialEq)]
2399pub enum ClipboardEntry {
2400 String(ClipboardString),
2402 Image(Image),
2404 ExternalPaths(crate::ExternalPaths),
2407}
2408
2409impl ClipboardItem {
2410 pub fn new_string(text: String) -> Self {
2412 Self {
2413 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
2414 }
2415 }
2416
2417 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
2419 Self {
2420 entries: vec![ClipboardEntry::String(ClipboardString {
2421 text,
2422 metadata: Some(metadata),
2423 })],
2424 }
2425 }
2426
2427 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
2429 Self {
2430 entries: vec![ClipboardEntry::String(
2431 ClipboardString::new(text).with_json_metadata(metadata),
2432 )],
2433 }
2434 }
2435
2436 pub fn new_image(image: &Image) -> Self {
2438 Self {
2439 entries: vec![ClipboardEntry::Image(image.clone())],
2440 }
2441 }
2442
2443 pub fn plain_text(&self) -> Option<String> {
2446 let mut text = String::new();
2447 for entry in &self.entries {
2448 if let ClipboardEntry::String(entry) = entry {
2449 text.push_str(&entry.text);
2450 }
2451 }
2452 (!text.is_empty()).then_some(text)
2453 }
2454
2455 pub fn text(&self) -> Option<String> {
2458 let mut answer = String::new();
2459
2460 for entry in self.entries.iter() {
2461 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
2462 answer.push_str(text);
2463 }
2464 }
2465
2466 if answer.is_empty() {
2467 for entry in self.entries.iter() {
2468 if let ClipboardEntry::ExternalPaths(paths) = entry {
2469 for path in &paths.0 {
2470 use std::fmt::Write as _;
2471 _ = write!(answer, "{}", path.display());
2472 }
2473 }
2474 }
2475 }
2476
2477 if !answer.is_empty() {
2478 Some(answer)
2479 } else {
2480 None
2481 }
2482 }
2483
2484 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
2486 pub fn metadata(&self) -> Option<&String> {
2487 match self.entries().first() {
2488 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
2489 clipboard_string.metadata.as_ref()
2490 }
2491 _ => None,
2492 }
2493 }
2494
2495 pub fn entries(&self) -> &[ClipboardEntry] {
2497 &self.entries
2498 }
2499
2500 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
2502 self.entries.into_iter()
2503 }
2504}
2505
2506impl From<ClipboardString> for ClipboardEntry {
2507 fn from(value: ClipboardString) -> Self {
2508 Self::String(value)
2509 }
2510}
2511
2512impl From<String> for ClipboardEntry {
2513 fn from(value: String) -> Self {
2514 Self::from(ClipboardString::from(value))
2515 }
2516}
2517
2518impl From<Image> for ClipboardEntry {
2519 fn from(value: Image) -> Self {
2520 Self::Image(value)
2521 }
2522}
2523
2524impl From<ClipboardEntry> for ClipboardItem {
2525 fn from(value: ClipboardEntry) -> Self {
2526 Self {
2527 entries: vec![value],
2528 }
2529 }
2530}
2531
2532impl From<String> for ClipboardItem {
2533 fn from(value: String) -> Self {
2534 Self::from(ClipboardEntry::from(value))
2535 }
2536}
2537
2538impl From<Image> for ClipboardItem {
2539 fn from(value: Image) -> Self {
2540 Self::from(ClipboardEntry::from(value))
2541 }
2542}
2543
2544#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
2546pub enum ImageFormat {
2547 Png,
2552 Jpeg,
2554 Webp,
2556 Gif,
2558 Svg,
2560 Bmp,
2562 Tiff,
2564 Ico,
2566 Pnm,
2568}
2569
2570impl ImageFormat {
2571 pub const fn mime_type(self) -> &'static str {
2573 match self {
2574 ImageFormat::Png => "image/png",
2575 ImageFormat::Jpeg => "image/jpeg",
2576 ImageFormat::Webp => "image/webp",
2577 ImageFormat::Gif => "image/gif",
2578 ImageFormat::Svg => "image/svg+xml",
2579 ImageFormat::Bmp => "image/bmp",
2580 ImageFormat::Tiff => "image/tiff",
2581 ImageFormat::Ico => "image/ico",
2582 ImageFormat::Pnm => "image/x-portable-anymap",
2583 }
2584 }
2585
2586 pub const fn extension(self) -> &'static str {
2588 match self {
2589 ImageFormat::Png => "png",
2590 ImageFormat::Jpeg => "jpg",
2591 ImageFormat::Webp => "webp",
2592 ImageFormat::Gif => "gif",
2593 ImageFormat::Svg => "svg",
2594 ImageFormat::Bmp => "bmp",
2595 ImageFormat::Tiff => "tiff",
2596 ImageFormat::Ico => "ico",
2597 ImageFormat::Pnm => "pnm",
2598 }
2599 }
2600
2601 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
2603 use strum::IntoEnumIterator;
2604 Self::iter()
2605 .find(|format| format.mime_type() == mime_type)
2606 .or_else(|| Self::from_mime_type_alias(mime_type))
2607 }
2608
2609 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
2613 match mime_type {
2614 "image/jpg" => Some(Self::Jpeg),
2615 "image/tif" => Some(Self::Tiff),
2616 _ => None,
2617 }
2618 }
2619}
2620
2621#[derive(Clone, Debug, PartialEq, Eq)]
2623pub struct Image {
2624 pub format: ImageFormat,
2626 pub bytes: Vec<u8>,
2628 pub id: u64,
2630}
2631
2632pub(crate) fn decode_static_image(
2633 bytes: &[u8],
2634 format: image::ImageFormat,
2635) -> Result<SmallVec<[Frame; 1]>> {
2636 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
2637 .into_decoder()
2638 .context("creating image decoder")?;
2639 decode_static_image_from_decoder(decoder)
2640}
2641
2642pub(crate) fn decode_static_image_from_decoder(
2643 mut decoder: impl image::ImageDecoder,
2644) -> Result<SmallVec<[Frame; 1]>> {
2645 let orientation = decoder
2646 .orientation()
2647 .context("reading decoder's orientation")?;
2648 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
2649 image.apply_orientation(orientation);
2650
2651 let mut data = image.into_rgba8();
2652 for pixel in data.chunks_exact_mut(4) {
2653 pixel.swap(0, 2);
2654 }
2655
2656 Ok(SmallVec::from_elem(Frame::new(data), 1))
2657}
2658
2659impl Hash for Image {
2660 fn hash<H: Hasher>(&self, state: &mut H) {
2661 state.write_u64(self.id);
2662 }
2663}
2664
2665impl Image {
2666 pub fn empty() -> Self {
2668 Self::from_bytes(ImageFormat::Png, Vec::new())
2669 }
2670
2671 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
2673 Self {
2674 id: hash(&bytes),
2675 format,
2676 bytes,
2677 }
2678 }
2679
2680 pub fn id(&self) -> u64 {
2682 self.id
2683 }
2684
2685 pub fn use_render_image(
2687 self: Arc<Self>,
2688 window: &mut Window,
2689 cx: &mut App,
2690 ) -> Option<Arc<RenderImage>> {
2691 ImageSource::Image(self)
2692 .use_data(None, window, cx)
2693 .and_then(|result| result.ok())
2694 }
2695
2696 pub fn get_render_image(
2698 self: Arc<Self>,
2699 window: &mut Window,
2700 cx: &mut App,
2701 ) -> Option<Arc<RenderImage>> {
2702 ImageSource::Image(self)
2703 .get_data(None, window, cx)
2704 .and_then(|result| result.ok())
2705 }
2706
2707 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
2709 ImageSource::Image(self).remove_asset(cx);
2710 }
2711
2712 #[cfg(any(test, feature = "test-support"))]
2715 pub fn is_asset_cached(self: &Arc<Self>, cx: &App) -> bool {
2716 ImageSource::Image(self.clone()).is_asset_cached(cx)
2717 }
2718
2719 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
2721 let frames = match self.format {
2722 ImageFormat::Gif => {
2723 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
2724 let mut frames = SmallVec::new();
2725
2726 for frame in decoder.into_frames() {
2727 match frame {
2728 Ok(mut frame) => {
2729 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
2731 pixel.swap(0, 2);
2732 }
2733 frames.push(frame);
2734 }
2735 Err(err) => {
2736 log::debug!("Skipping GIF frame due to decode error: {err}");
2737 }
2738 }
2739 }
2740
2741 if frames.is_empty() {
2742 anyhow::bail!("GIF could not be decoded: all frames failed");
2743 }
2744
2745 frames
2746 }
2747 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
2748 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
2749 ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
2750 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
2751 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
2752 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
2753 ImageFormat::Svg => {
2754 return svg_renderer
2755 .render_single_frame(&self.bytes, 1.0)
2756 .map_err(Into::into);
2757 }
2758 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
2759 };
2760
2761 Ok(Arc::new(RenderImage::new(frames)))
2762 }
2763
2764 pub fn format(&self) -> ImageFormat {
2766 self.format
2767 }
2768
2769 pub fn bytes(&self) -> &[u8] {
2771 self.bytes.as_slice()
2772 }
2773}
2774
2775#[derive(Clone, Debug, Eq, PartialEq)]
2777pub struct ClipboardString {
2778 pub text: String,
2780 pub metadata: Option<String>,
2782}
2783
2784impl ClipboardString {
2785 pub fn new(text: String) -> Self {
2787 Self {
2788 text,
2789 metadata: None,
2790 }
2791 }
2792
2793 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
2796 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
2797 self
2798 }
2799
2800 pub fn text(&self) -> &String {
2802 &self.text
2803 }
2804
2805 pub fn into_text(self) -> String {
2807 self.text
2808 }
2809
2810 pub fn metadata_json<T>(&self) -> Option<T>
2812 where
2813 T: for<'a> Deserialize<'a>,
2814 {
2815 self.metadata
2816 .as_ref()
2817 .and_then(|m| serde_json::from_str(m).ok())
2818 }
2819
2820 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2821 pub fn text_hash(text: &str) -> u64 {
2823 let mut hasher = SeaHasher::new();
2824 text.hash(&mut hasher);
2825 hasher.finish()
2826 }
2827}
2828
2829impl From<String> for ClipboardString {
2830 fn from(value: String) -> Self {
2831 Self {
2832 text: value,
2833 metadata: None,
2834 }
2835 }
2836}
2837
2838#[cfg(test)]
2839mod image_tests {
2840 use super::*;
2841 use std::sync::Arc;
2842
2843 #[test]
2844 fn test_image_to_image_data_applies_exif_orientation() {
2845 let image = Image::from_bytes(
2846 ImageFormat::Jpeg,
2847 include_bytes!("test_data/exif-orientation-rotate-180.jpg").to_vec(),
2848 );
2849
2850 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
2851
2852 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
2853
2854 let bytes = render_image.as_bytes(0).unwrap();
2855 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
2856 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
2857 }
2858
2859 #[test]
2860 fn test_svg_image_to_image_data_converts_to_bgra() {
2861 let image = Image::from_bytes(
2862 ImageFormat::Svg,
2863 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
2864<rect width="1" height="1" fill="#38BDF8"/>
2865</svg>"##
2866 .to_vec(),
2867 );
2868
2869 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
2870 let bytes = render_image.as_bytes(0).unwrap();
2871
2872 for pixel in bytes.chunks_exact(4) {
2873 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
2874 }
2875 }
2876}
2877
2878#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
2879mod tests {
2880 use super::*;
2881 use std::collections::HashSet;
2882
2883 #[test]
2884 fn test_window_button_layout_parse_standard() {
2885 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
2886 assert_eq!(
2887 layout.left,
2888 [
2889 Some(WindowButton::Close),
2890 Some(WindowButton::Minimize),
2891 None
2892 ]
2893 );
2894 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2895 }
2896
2897 #[test]
2898 fn test_window_button_layout_parse_right_only() {
2899 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
2900 assert_eq!(layout.left, [None, None, None]);
2901 assert_eq!(
2902 layout.right,
2903 [
2904 Some(WindowButton::Minimize),
2905 Some(WindowButton::Maximize),
2906 Some(WindowButton::Close)
2907 ]
2908 );
2909 }
2910
2911 #[test]
2912 fn test_window_button_layout_parse_left_only() {
2913 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
2914 assert_eq!(
2915 layout.left,
2916 [
2917 Some(WindowButton::Close),
2918 Some(WindowButton::Minimize),
2919 Some(WindowButton::Maximize)
2920 ]
2921 );
2922 assert_eq!(layout.right, [None, None, None]);
2923 }
2924
2925 #[test]
2926 fn test_window_button_layout_parse_with_whitespace() {
2927 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
2928 assert_eq!(
2929 layout.left,
2930 [
2931 Some(WindowButton::Close),
2932 Some(WindowButton::Minimize),
2933 None
2934 ]
2935 );
2936 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2937 }
2938
2939 #[test]
2940 fn test_window_button_layout_parse_empty() {
2941 let layout = WindowButtonLayout::parse("").unwrap();
2942 assert_eq!(layout.left, [None, None, None]);
2943 assert_eq!(layout.right, [None, None, None]);
2944 }
2945
2946 #[test]
2947 fn test_window_button_layout_parse_intentionally_empty() {
2948 let layout = WindowButtonLayout::parse(":").unwrap();
2949 assert_eq!(layout.left, [None, None, None]);
2950 assert_eq!(layout.right, [None, None, None]);
2951 }
2952
2953 #[test]
2954 fn test_window_button_layout_parse_invalid_buttons() {
2955 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
2956 assert_eq!(
2957 layout.left,
2958 [
2959 Some(WindowButton::Close),
2960 Some(WindowButton::Minimize),
2961 None
2962 ]
2963 );
2964 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2965 }
2966
2967 #[test]
2968 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
2969 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
2970 assert_eq!(
2971 layout.right,
2972 [
2973 Some(WindowButton::Close),
2974 Some(WindowButton::Minimize),
2975 None
2976 ]
2977 );
2978 assert_eq!(layout.format(), ":close,minimize");
2979 }
2980
2981 #[test]
2982 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
2983 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
2984 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
2985 assert_eq!(
2986 layout.right,
2987 [
2988 Some(WindowButton::Maximize),
2989 Some(WindowButton::Minimize),
2990 None
2991 ]
2992 );
2993
2994 let button_ids: Vec<_> = layout
2995 .left
2996 .iter()
2997 .chain(layout.right.iter())
2998 .flatten()
2999 .map(WindowButton::id)
3000 .collect();
3001 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
3002 assert_eq!(unique_button_ids.len(), button_ids.len());
3003 assert_eq!(layout.format(), "close:maximize,minimize");
3004 }
3005
3006 #[test]
3007 fn test_window_button_layout_parse_gnome_style() {
3008 let layout = WindowButtonLayout::parse("close").unwrap();
3009 assert_eq!(layout.left, [None, None, None]);
3010 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
3011 }
3012
3013 #[test]
3014 fn test_window_button_layout_parse_elementary_style() {
3015 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
3016 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
3017 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
3018 }
3019
3020 #[test]
3021 fn test_window_button_layout_round_trip() {
3022 let cases = [
3023 "close:minimize,maximize",
3024 "minimize,maximize,close:",
3025 ":close",
3026 "close:",
3027 "close:maximize",
3028 ":",
3029 ];
3030
3031 for case in cases {
3032 let layout = WindowButtonLayout::parse(case).unwrap();
3033 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
3034 }
3035 }
3036
3037 #[test]
3038 fn test_window_button_layout_linux_default() {
3039 let layout = WindowButtonLayout::linux_default();
3040 assert_eq!(layout.left, [None, None, None]);
3041 assert_eq!(
3042 layout.right,
3043 [
3044 Some(WindowButton::Minimize),
3045 Some(WindowButton::Maximize),
3046 Some(WindowButton::Close)
3047 ]
3048 );
3049
3050 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
3051 assert_eq!(round_tripped, layout);
3052 }
3053
3054 #[test]
3055 fn test_window_button_layout_parse_all_invalid() {
3056 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
3057 }
3058}
3059
3060#[cfg(test)]
3061mod file_clipboard_tests {
3062 use super::*;
3063
3064 #[test]
3065 fn invalid_file_lists_are_rejected() {
3066 for names in [vec![], vec!["relative"], vec!["/tmp/nul\0file"]] {
3067 let paths = crate::ExternalPaths(names.into_iter().map(PathBuf::from).collect());
3068 assert!(matches!(
3069 paths.validate_for_clipboard(),
3070 Err(FileClipboardError::InvalidPaths)
3071 ));
3072 }
3073 }
3074
3075 #[test]
3076 #[cfg(unix)]
3077 fn file_mime_payloads_escape_unicode_and_record_intent() {
3078 let paths = crate::ExternalPaths(
3079 ["/tmp/\u{65e5}\u{672c}\u{8a9e} #%.txt", "/tmp/line\nbreak"]
3080 .into_iter()
3081 .map(PathBuf::from)
3082 .collect(),
3083 );
3084 let uris = paths.clipboard_uri_list().unwrap();
3085 assert!(uris.contains("%20%23%25.txt\r\n"));
3086 assert!(uris.contains("line%0Abreak\r\n"));
3087 let decoded: Vec<_> = uris
3088 .lines()
3089 .map(|line| url::Url::parse(line).unwrap().to_file_path().unwrap())
3090 .collect();
3091 assert_eq!(decoded, paths.paths());
3092 assert_eq!(
3093 paths
3094 .clipboard_gnome_files(FileClipboardOperation::Copy)
3095 .unwrap(),
3096 format!("copy\n{}", uris.trim_end().replace("\r\n", "\n"))
3097 );
3098 assert!(
3099 paths
3100 .clipboard_gnome_files(FileClipboardOperation::Move)
3101 .unwrap()
3102 .starts_with("cut\n")
3103 );
3104 }
3105
3106 #[crate::test]
3107 fn unsupported_backend_preserves_existing_clipboard(cx: &mut crate::TestAppContext) {
3108 cx.update(|cx| {
3109 let original = ClipboardItem::new_string("keep".into());
3110 cx.write_to_clipboard(original.clone());
3111 assert!(!cx.supports_file_clipboard(FileClipboardOperation::Copy));
3112 let paths = crate::ExternalPaths(Default::default());
3113 assert!(matches!(
3114 cx.write_files_to_clipboard(paths, FileClipboardOperation::Copy),
3115 Err(FileClipboardError::Unsupported)
3116 ));
3117 assert_eq!(cx.read_from_clipboard(), Some(original));
3118 });
3119 }
3120}
3121
3122#[cfg(test)]
3123mod async_clipboard_tests {
3124 use super::*;
3125
3126 #[crate::test]
3127 async fn asynchronous_text_read_captures_test_clipboard_and_preserves_writes(
3128 cx: &mut crate::TestAppContext,
3129 ) {
3130 let text = "日本語🙂e\u{301}\r\n".repeat(20_000);
3131 let read = cx.update(|cx| {
3132 cx.write_to_clipboard(ClipboardItem::new_string(text.clone()));
3133 cx.read_text_from_clipboard_async()
3134 });
3135 cx.write_to_clipboard(ClipboardItem::new_string("later".into()));
3136 assert_eq!(read.await, Some(text));
3137 assert_eq!(
3138 cx.read_from_clipboard()
3139 .and_then(|item| item.text())
3140 .as_deref(),
3141 Some("later")
3142 );
3143 let read = cx.update(|cx| cx.read_text_from_clipboard_async());
3144 drop(read);
3145 cx.run_until_parked();
3146 assert_eq!(
3147 cx.read_from_clipboard()
3148 .and_then(|item| item.text())
3149 .as_deref(),
3150 Some("later")
3151 );
3152 }
3153
3154 #[crate::test]
3155 async fn asynchronous_text_read_ignores_empty_and_nontext_items(
3156 cx: &mut crate::TestAppContext,
3157 ) {
3158 for item in [
3159 ClipboardItem::new_string(String::new()),
3160 ClipboardItem {
3161 entries: vec![ClipboardEntry::ExternalPaths(crate::ExternalPaths(
3162 smallvec::smallvec!["file.txt".into()],
3163 ))],
3164 },
3165 ] {
3166 let read = cx.update(|cx| {
3167 cx.write_to_clipboard(item);
3168 cx.read_text_from_clipboard_async()
3169 });
3170 assert_eq!(read.await, None);
3171 }
3172 }
3173}