Skip to repository content2868 lines · 97.3 KB · rust
tenant.openagents/omega
No repository description is available.
OpenAgents Git authority 2026-07-28T02:34:17.963Z Public web read
NIP-34 coordinate
30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omegaMaintainersHidden in public view
References2 branches · 1 tag
Read-only clone
git clone https://openagents.com/git/tenant.openagents/omega.gitBrowse files
platform.rs
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
9/// Types for configuring parent-anchored popup windows such as menus, dropdowns and tooltips.
10pub 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, Font, FontId, FontMetrics,
40 FontRun, ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap, LineLayout, Pixels,
41 PlatformGestures, PlatformInput, Point, Priority, RenderGlyphParams, RenderImage,
42 RenderImageParams, RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString, Size,
43 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// TODO(jk): return an enum instead of a string
93/// Return which compositor we're guessing we'll use.
94/// Does not attempt to connect to the given compositor.
95#[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 /// Returns the appearance of the application's windows.
168 fn window_appearance(&self) -> WindowAppearance;
169
170 /// Returns the window button layout configuration when supported.
171 fn button_layout(&self) -> Option<WindowButtonLayout> {
172 None
173 }
174
175 fn open_url(&self, url: &str);
176 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
177 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
178
179 fn prompt_for_paths(
180 &self,
181 options: PathPromptOptions,
182 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
183 fn prompt_for_new_path(
184 &self,
185 directory: &Path,
186 suggested_name: Option<&str>,
187 ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
188 fn can_select_mixed_files_and_dirs(&self) -> bool;
189 fn reveal_path(&self, path: &Path);
190 fn open_with_system(&self, path: &Path);
191
192 fn on_quit(&self, callback: Box<dyn FnMut()>);
193 fn on_reopen(&self, callback: Box<dyn FnMut()>);
194 fn on_system_wake(&self, callback: Box<dyn FnMut()>);
195
196 // Mobile platform methods. On mobile the OS owns the application
197 // lifecycle: apps are backgrounded, foregrounded, and killed at the
198 // system's discretion, and must react rather than decide.
199
200 /// Registers a callback invoked whenever the application's lifecycle
201 /// phase changes. See [`AppLifecyclePhase`] for the phase vocabulary and
202 /// its mapping onto iOS and Android.
203 ///
204 /// Desktop platforms never invoke this.
205 fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
206
207 /// Registers a callback invoked when the OS signals memory pressure
208 /// (iOS `didReceiveMemoryWarning`, Android `onTrimMemory`).
209 ///
210 /// Desktop platforms never invoke this.
211 fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
212
213 /// The platform's gesture recognition services, if it provides any
214 /// beyond gpui's portable recognizers. See
215 /// [`PlatformGestures`](crate::PlatformGestures).
216 fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
217 None
218 }
219
220 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
221 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
222 None
223 }
224
225 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
226 fn perform_dock_menu_action(&self, _action: usize) {}
227 fn add_recent_document(&self, _path: &Path) {}
228 fn update_jump_list(
229 &self,
230 _menus: Vec<MenuItem>,
231 _entries: Vec<SmallVec<[PathBuf; 2]>>,
232 ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
233 Task::ready(Vec::new())
234 }
235 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
236 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
237 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
238
239 fn thermal_state(&self) -> ThermalState;
240 fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>);
241
242 /// Sets the application's process-wide identity and user-visible name.
243 ///
244 /// The identifier is used for platform identity mechanisms such as the
245 /// Windows AppUserModelID. The name is used wherever the operating system
246 /// presents the application to the user. Call this once, early in startup,
247 /// before opening windows or posting notifications.
248 fn set_app_identity(&self, identifier: &str, name: &str) {
249 _ = (identifier, name);
250 }
251
252 /// Posts a notification to the operating system's notification center.
253 ///
254 /// Posting a notification whose [`SystemNotification::tag`] matches an
255 /// earlier one replaces that notification where the platform supports it.
256 /// No-op on platforms without notification support, or when delivery is
257 /// unavailable (e.g. authorization was denied).
258 fn show_system_notification(&self, notification: SystemNotification) {
259 _ = notification;
260 }
261
262 /// Removes the delivered or pending notification with this tag.
263 ///
264 /// Best-effort: some platforms cannot retract a notification once shown,
265 /// in which case it ages out of the notification center on its own.
266 fn dismiss_system_notification(&self, tag: &str) {
267 _ = tag;
268 }
269
270 /// Registers the callback invoked when the user activates a system
271 /// notification, either by clicking its body or one of its action
272 /// buttons.
273 ///
274 /// Implementations must invoke the callback on the main thread.
275 fn on_system_notification_response(
276 &self,
277 callback: Box<dyn FnMut(SystemNotificationResponse)>,
278 ) {
279 _ = callback;
280 }
281
282 fn compositor_name(&self) -> &'static str {
283 ""
284 }
285 fn app_path(&self) -> Result<PathBuf>;
286 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
287
288 fn set_cursor_style(&self, style: CursorStyle);
289
290 /// Hides the mouse cursor until the user moves the mouse over one of
291 /// this application's windows.
292 fn hide_cursor_until_mouse_moves(&self);
293
294 /// Returns whether the mouse cursor is currently visible.
295 fn is_cursor_visible(&self) -> bool;
296
297 fn should_auto_hide_scrollbars(&self) -> bool;
298
299 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
300 fn write_to_clipboard(&self, item: ClipboardItem);
301
302 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
303 fn read_from_primary(&self) -> Option<ClipboardItem>;
304 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
305 fn write_to_primary(&self, item: ClipboardItem);
306
307 #[cfg(target_os = "macos")]
308 fn read_from_find_pasteboard(&self) -> Option<ClipboardItem>;
309 #[cfg(target_os = "macos")]
310 fn write_to_find_pasteboard(&self, item: ClipboardItem);
311
312 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
313 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
314 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
315
316 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
317 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
318 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
319}
320
321/// A handle to a platform's display, e.g. a monitor or laptop screen.
322pub trait PlatformDisplay: Debug {
323 /// Get the ID for this display
324 fn id(&self) -> DisplayId;
325
326 /// Returns a stable identifier for this display that can be persisted and used
327 /// across system restarts.
328 fn uuid(&self) -> Result<Uuid>;
329
330 /// Get the bounds for this display
331 fn bounds(&self) -> Bounds<Pixels>;
332
333 /// Get the visible bounds for this display, excluding taskbar/dock areas.
334 /// This is the usable area where windows can be placed without being obscured.
335 /// Defaults to the full display bounds if not overridden.
336 fn visible_bounds(&self) -> Bounds<Pixels> {
337 self.bounds()
338 }
339
340 /// Get the default bounds for this display to place a window
341 fn default_bounds(&self) -> Bounds<Pixels> {
342 let bounds = self.bounds();
343 let center = bounds.center();
344 let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
345
346 let offset = clipped_window_size / 2.0;
347 let origin = point(center.x - offset.width, center.y - offset.height);
348 Bounds::new(origin, clipped_window_size)
349 }
350}
351
352/// A notification posted to the operating system's notification center,
353/// rather than rendered as in-app UI.
354#[derive(Clone, Debug, PartialEq, Eq)]
355pub struct SystemNotification {
356 /// Stable identity for the notification. Posting a new notification with
357 /// the same tag replaces the previous one where the platform supports it,
358 /// and responses carry the tag back to the application.
359 pub tag: SharedString,
360 /// The notification's headline.
361 pub title: SharedString,
362 /// Additional text displayed below the title.
363 pub body: SharedString,
364 /// Buttons offered on the notification. Platforms that cannot display
365 /// action buttons show the notification without them.
366 pub actions: Vec<SystemNotificationAction>,
367}
368
369/// A button offered on a [`SystemNotification`].
370#[derive(Clone, Debug, PartialEq, Eq, Hash)]
371pub struct SystemNotificationAction {
372 /// Identifies the action in [`SystemNotificationResponse::action_id`]
373 /// when the user presses this button.
374 pub id: SharedString,
375 /// The button's user-visible label.
376 pub label: SharedString,
377}
378
379/// The user's activation of a [`SystemNotification`].
380#[derive(Clone, Debug, PartialEq, Eq)]
381pub struct SystemNotificationResponse {
382 /// The [`SystemNotification::tag`] of the activated notification.
383 pub tag: SharedString,
384 /// The pressed action button's [`SystemNotificationAction::id`], or
385 /// `None` when the user activated the notification body itself.
386 pub action_id: Option<SharedString>,
387}
388
389/// Thermal state of the system
390#[derive(Debug, Clone, Copy, PartialEq, Eq)]
391pub enum ThermalState {
392 /// System has no thermal constraints
393 Nominal,
394 /// System is slightly constrained, reduce discretionary work
395 Fair,
396 /// System is moderately constrained, reduce CPU/GPU intensive work
397 Serious,
398 /// System is critically constrained, minimize all resource usage
399 Critical,
400}
401
402/// Metadata for a given [ScreenCaptureSource]
403#[derive(Clone)]
404pub struct SourceMetadata {
405 /// Opaque identifier of this screen.
406 pub id: u64,
407 /// Human-readable label for this source.
408 pub label: Option<SharedString>,
409 /// Whether this source is the main display.
410 pub is_main: Option<bool>,
411 /// Video resolution of this source.
412 pub resolution: Size<DevicePixels>,
413}
414
415/// A source of on-screen video content that can be captured.
416pub trait ScreenCaptureSource {
417 /// Returns metadata for this source.
418 fn metadata(&self) -> Result<SourceMetadata>;
419
420 /// Start capture video from this source, invoking the given callback
421 /// with each frame.
422 fn stream(
423 &self,
424 foreground_executor: &ForegroundExecutor,
425 frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
426 ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
427}
428
429/// A video stream captured from a screen.
430pub trait ScreenCaptureStream {
431 /// Returns metadata for this source.
432 fn metadata(&self) -> Result<SourceMetadata>;
433}
434
435/// A frame of video captured from a screen.
436pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
437
438/// An opaque identifier for a hardware display
439#[derive(PartialEq, Eq, Hash, Copy, Clone)]
440pub struct DisplayId(pub(crate) u64);
441
442impl DisplayId {
443 /// Create a new `DisplayId` from a raw platform display identifier.
444 pub fn new(id: u64) -> Self {
445 Self(id)
446 }
447}
448
449impl From<u64> for DisplayId {
450 fn from(id: u64) -> Self {
451 Self(id)
452 }
453}
454
455impl From<DisplayId> for u64 {
456 fn from(id: DisplayId) -> Self {
457 id.0
458 }
459}
460
461impl Debug for DisplayId {
462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463 write!(f, "DisplayId({})", self.0)
464 }
465}
466
467/// Which part of the window to resize
468#[derive(Debug, Clone, Copy, PartialEq, Eq)]
469pub enum ResizeEdge {
470 /// The top edge
471 Top,
472 /// The top right corner
473 TopRight,
474 /// The right edge
475 Right,
476 /// The bottom right corner
477 BottomRight,
478 /// The bottom edge
479 Bottom,
480 /// The bottom left corner
481 BottomLeft,
482 /// The left edge
483 Left,
484 /// The top left corner
485 TopLeft,
486}
487
488/// A type to describe the appearance of a window
489#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
490pub enum WindowDecorations {
491 #[default]
492 /// Server side decorations
493 Server,
494 /// Client side decorations
495 Client,
496}
497
498/// A type to describe how this window is currently configured
499#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
500pub enum Decorations {
501 /// The window is configured to use server side decorations
502 #[default]
503 Server,
504 /// The window is configured to use client side decorations
505 Client {
506 /// The edge tiling state
507 tiling: Tiling,
508 },
509}
510
511/// What window controls this platform supports
512#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
513pub struct WindowControls {
514 /// Whether this platform supports fullscreen
515 pub fullscreen: bool,
516 /// Whether this platform supports maximize
517 pub maximize: bool,
518 /// Whether this platform supports minimize
519 pub minimize: bool,
520 /// Whether this platform supports a window menu
521 pub window_menu: bool,
522}
523
524impl Default for WindowControls {
525 fn default() -> Self {
526 // Assume that we can do anything, unless told otherwise
527 Self {
528 fullscreen: true,
529 maximize: true,
530 minimize: true,
531 window_menu: true,
532 }
533 }
534}
535
536/// A window control button type used in [`WindowButtonLayout`].
537#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
538pub enum WindowButton {
539 /// The minimize button
540 Minimize,
541 /// The maximize button
542 Maximize,
543 /// The close button
544 Close,
545}
546
547impl WindowButton {
548 /// Returns a stable element ID for rendering this button.
549 pub fn id(&self) -> &'static str {
550 match self {
551 WindowButton::Minimize => "minimize",
552 WindowButton::Maximize => "maximize",
553 WindowButton::Close => "close",
554 }
555 }
556
557 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
558 fn index(&self) -> usize {
559 match self {
560 WindowButton::Minimize => 0,
561 WindowButton::Maximize => 1,
562 WindowButton::Close => 2,
563 }
564 }
565}
566
567/// Maximum number of [`WindowButton`]s per side in the titlebar.
568pub const MAX_BUTTONS_PER_SIDE: usize = 3;
569
570/// Describes which [`WindowButton`]s appear on each side of the titlebar.
571///
572/// On Linux, this is read from the desktop environment's configuration
573/// (e.g. GNOME's `gtk-decoration-layout` gsetting) via [`WindowButtonLayout::parse`].
574#[derive(Debug, Clone, Copy, PartialEq, Eq)]
575pub struct WindowButtonLayout {
576 /// Buttons on the left side of the titlebar.
577 pub left: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
578 /// Buttons on the right side of the titlebar.
579 pub right: [Option<WindowButton>; MAX_BUTTONS_PER_SIDE],
580}
581
582#[cfg(any(target_os = "linux", target_os = "freebsd"))]
583impl WindowButtonLayout {
584 /// Returns Omega's built-in fallback button layout for Linux titlebars.
585 pub fn linux_default() -> Self {
586 Self {
587 left: [None; MAX_BUTTONS_PER_SIDE],
588 right: [
589 Some(WindowButton::Minimize),
590 Some(WindowButton::Maximize),
591 Some(WindowButton::Close),
592 ],
593 }
594 }
595
596 /// Parses a GNOME-style `button-layout` string (e.g. `"close,minimize:maximize"`).
597 pub fn parse(layout_string: &str) -> Result<Self> {
598 fn parse_side(
599 s: &str,
600 seen_buttons: &mut [bool; MAX_BUTTONS_PER_SIDE],
601 unrecognized: &mut Vec<String>,
602 ) -> [Option<WindowButton>; MAX_BUTTONS_PER_SIDE] {
603 let mut result = [None; MAX_BUTTONS_PER_SIDE];
604 let mut i = 0;
605 for name in s.split(',') {
606 let trimmed = name.trim();
607 if trimmed.is_empty() {
608 continue;
609 }
610 let button = match trimmed {
611 "minimize" => Some(WindowButton::Minimize),
612 "maximize" => Some(WindowButton::Maximize),
613 "close" => Some(WindowButton::Close),
614 other => {
615 unrecognized.push(other.to_string());
616 None
617 }
618 };
619 if let Some(button) = button {
620 if seen_buttons[button.index()] {
621 continue;
622 }
623 if let Some(slot) = result.get_mut(i) {
624 *slot = Some(button);
625 seen_buttons[button.index()] = true;
626 i += 1;
627 }
628 }
629 }
630 result
631 }
632
633 let (left_str, right_str) = layout_string.split_once(':').unwrap_or(("", layout_string));
634 let mut unrecognized = Vec::new();
635 let mut seen_buttons = [false; MAX_BUTTONS_PER_SIDE];
636 let layout = Self {
637 left: parse_side(left_str, &mut seen_buttons, &mut unrecognized),
638 right: parse_side(right_str, &mut seen_buttons, &mut unrecognized),
639 };
640
641 if !unrecognized.is_empty()
642 && layout.left.iter().all(Option::is_none)
643 && layout.right.iter().all(Option::is_none)
644 {
645 bail!(
646 "button layout string {:?} contains no valid buttons (unrecognized: {})",
647 layout_string,
648 unrecognized.join(", ")
649 );
650 }
651
652 Ok(layout)
653 }
654
655 /// Formats the layout back into a GNOME-style `button-layout` string.
656 #[cfg(test)]
657 pub fn format(&self) -> String {
658 fn format_side(buttons: &[Option<WindowButton>; MAX_BUTTONS_PER_SIDE]) -> String {
659 buttons
660 .iter()
661 .flatten()
662 .map(|button| match button {
663 WindowButton::Minimize => "minimize",
664 WindowButton::Maximize => "maximize",
665 WindowButton::Close => "close",
666 })
667 .collect::<Vec<_>>()
668 .join(",")
669 }
670
671 format!("{}:{}", format_side(&self.left), format_side(&self.right))
672 }
673}
674
675/// A type to describe which sides of the window are currently tiled in some way
676#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
677pub struct Tiling {
678 /// Whether the top edge is tiled
679 pub top: bool,
680 /// Whether the left edge is tiled
681 pub left: bool,
682 /// Whether the right edge is tiled
683 pub right: bool,
684 /// Whether the bottom edge is tiled
685 pub bottom: bool,
686}
687
688impl Tiling {
689 /// Initializes a [`Tiling`] type with all sides tiled
690 pub fn tiled() -> Self {
691 Self {
692 top: true,
693 left: true,
694 right: true,
695 bottom: true,
696 }
697 }
698
699 /// Whether any edge is tiled
700 pub fn is_tiled(&self) -> bool {
701 self.top || self.left || self.right || self.bottom
702 }
703}
704
705/// Callbacks for the accessibility adapter.
706pub struct A11yCallbacks {
707 /// Called when the adapter is activated (a screen reader connects).
708 pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
709 /// Called when an action is requested by the screen reader.
710 pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
711 /// Called when the adapter is deactivated (screen reader disconnects).
712 pub deactivation: Box<dyn Fn() + Send + 'static>,
713}
714
715#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
716#[expect(missing_docs)]
717pub struct RequestFrameOptions {
718 /// Whether a presentation is required.
719 pub require_presentation: bool,
720 /// Force refresh of all rendering states when true.
721 pub force_render: bool,
722}
723
724/// The application's lifecycle phase, as owned and reported by a mobile OS.
725///
726/// `Inactive` means visible but not receiving input (a system dialog on
727/// top), while `Background` means not visible at all, with process death
728/// possible at any time thereafter.
729///
730/// | Phase | iOS | Android |
731/// |--------------|------------------------------|--------------|
732/// | `Active` | `didBecomeActive` | `onResume` |
733/// | `Inactive` | `willResignActive` | `onPause` |
734/// | `Background` | `didEnterBackground` | `onStop` |
735/// | `Foreground` | `willEnterForeground` | `onStart` |
736#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
737pub enum AppLifecyclePhase {
738 /// Foreground and receiving input.
739 Active,
740 /// Foreground (visible) but not receiving input.
741 Inactive,
742 /// Not visible. The GPU surface may be destroyed while backgrounded and
743 /// the process may be killed without further notice.
744 Background,
745 /// Becoming visible again, before input is restored.
746 Foreground,
747}
748
749/// Regions of a window that are obscured or reserved by the system.
750///
751/// Mobile applications often share space in their window with system-specific
752/// geometry, from keyboards to camera notches. In GPUI, all this is abstracted
753/// into a single "inset" which should be overlaid on the window's bounds.
754/// It is up to the application develop to determine how to handle these cases.
755#[derive(Debug, Clone, Default, PartialEq)]
756pub struct WindowInsets {
757 /// Regions covered by system UI or hardware: status bar, display
758 /// cutouts/notch, home indicator, navigation bars.
759 /// (iOS: `safeAreaInsets`. Android: `WindowInsets` of types
760 /// `systemBars() | displayCutout()`.)
761 pub safe_area: Edges<Pixels>,
762 /// The region covered by the keyboard, when present.
763 /// (iOS: derived from `keyboardWillShow`/frame-change notifications.
764 /// Android: `WindowInsets.Type.ime()`.)
765 pub ime: Edges<Pixels>,
766}
767
768impl WindowInsets {
769 /// The combined inset content should avoid.
770 pub fn effective(&self) -> Edges<Pixels> {
771 Edges {
772 top: self.safe_area.top.max(self.ime.top),
773 right: self.safe_area.right.max(self.ime.right),
774 bottom: self.safe_area.bottom.max(self.ime.bottom),
775 left: self.safe_area.left.max(self.ime.left),
776 }
777 }
778}
779
780/// A change in the state of the focused text input.
781#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
782pub enum TextInputStateChange {
783 /// An editable element gained focus.
784 FocusGained,
785 /// The focused editable element lost focus.
786 FocusLost,
787 /// The selection or caret moved
788 SelectionChanged,
789 /// The document content changed outside of platform-initiated edits.
790 ContentChanged,
791}
792
793#[expect(missing_docs)]
794pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
795 fn bounds(&self) -> Bounds<Pixels>;
796 fn is_maximized(&self) -> bool;
797 fn window_bounds(&self) -> WindowBounds;
798 fn content_size(&self) -> Size<Pixels>;
799 fn resize(&mut self, size: Size<Pixels>);
800 fn scale_factor(&self) -> f32;
801 fn appearance(&self) -> WindowAppearance;
802 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
803 fn mouse_position(&self) -> Point<Pixels>;
804 fn modifiers(&self) -> Modifiers;
805 fn capslock(&self) -> Capslock;
806 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
807 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
808 fn prompt(
809 &self,
810 level: PromptLevel,
811 msg: &str,
812 detail: Option<&str>,
813 answers: &[PromptButton],
814 ) -> Option<oneshot::Receiver<usize>>;
815 fn activate(&self);
816 /// Requests that the operating system draw attention to this window.
817 fn request_attention(&self) {}
818 fn is_active(&self) -> bool;
819 fn is_hovered(&self) -> bool;
820 fn background_appearance(&self) -> WindowBackgroundAppearance;
821 fn set_title(&mut self, title: &str);
822 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
823 fn minimize(&self);
824 fn zoom(&self);
825 fn toggle_fullscreen(&self);
826 fn is_fullscreen(&self) -> bool;
827 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
828 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
829 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
830 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
831 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
832 fn on_moved(&self, callback: Box<dyn FnMut()>);
833 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
834 fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
835 fn on_close(&self, callback: Box<dyn FnOnce()>);
836 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
837 fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
838 fn draw(&self, scene: &Scene);
839 fn completed_frame(&self) {}
840 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
841 fn is_subpixel_rendering_supported(&self) -> bool;
842
843 // macOS specific methods
844 fn get_title(&self) -> String {
845 String::new()
846 }
847 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
848 None
849 }
850 fn tab_bar_visible(&self) -> bool {
851 false
852 }
853 fn set_edited(&mut self, _edited: bool) {}
854 fn set_document_path(&self, _path: Option<&std::path::Path>) {}
855 #[cfg(target_os = "macos")]
856 fn set_traffic_light_position(&self, _position: Point<Pixels>) {}
857 fn show_character_palette(&self) {}
858 fn titlebar_double_click(&self) {}
859 fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
860 fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
861 fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
862 fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
863 fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
864 fn merge_all_windows(&self) {}
865 fn move_tab_to_new_window(&self) {}
866 fn toggle_window_tab_overview(&self) {}
867 fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
868
869 #[cfg(target_os = "windows")]
870 fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
871
872 // Linux specific methods
873 fn inner_window_bounds(&self) -> WindowBounds {
874 self.window_bounds()
875 }
876 fn request_decorations(&self, _decorations: WindowDecorations) {}
877 fn show_window_menu(&self, _position: Point<Pixels>) {}
878 fn start_window_move(&self) {}
879 fn start_window_resize(&self, _edge: ResizeEdge) {}
880 fn set_exclusive_zone(&self, _zone: Pixels) {}
881 #[cfg(all(target_os = "linux", feature = "wayland"))]
882 fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
883 fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
884 fn window_decorations(&self) -> Decorations {
885 Decorations::Server
886 }
887 fn set_app_id(&mut self, _app_id: &str) {}
888 fn map_window(&mut self) -> anyhow::Result<()> {
889 Ok(())
890 }
891 fn window_controls(&self) -> WindowControls {
892 WindowControls::default()
893 }
894 fn set_client_inset(&self, _inset: Pixels) {}
895 fn gpu_specs(&self) -> Option<GpuSpecs>;
896
897 fn update_ime_position(&self, _bounds: Bounds<Pixels>);
898
899 // Mobile platform methods.
900
901 /// The regions of this window currently obscured or reserved by the
902 /// system. Zero on platforms without such regions.
903 fn insets(&self) -> WindowInsets {
904 WindowInsets::default()
905 }
906
907 /// Registers a callback invoked whenever [`Self::insets`] change.
908 ///
909 /// Contract: fires continuously during animated transitions (Android
910 /// `WindowInsetsAnimation` progress; on iOS the platform interpolates
911 /// the keyboard animation curve on frame ticks) and is exact at rest.
912 fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
913
914 /// Sets the handler for the system back action (Android back
915 /// button/gesture; no source on iOS or desktop).
916 fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
917
918 /// Declares whether the application would currently handle the system
919 /// back action (e.g. navigation depth > 0).
920 fn set_back_enabled(&self, _enabled: bool) {}
921
922 /// Requests that the soft keyboard be shown.
923 fn show_soft_keyboard(&self) {}
924
925 /// Requests that the soft keyboard be hidden.
926 fn hide_soft_keyboard(&self) {}
927
928 /// Inform the operating system that the text input state has changed
929 fn text_input_state_changed(&self, _change: TextInputStateChange) {}
930
931 fn play_system_bell(&self) {}
932
933 /// Initialize the accessibility adapter with callbacks.
934 fn a11y_init(&self, _callbacks: A11yCallbacks) {}
935
936 /// Provide a TreeUpdate to the accessibility adapter.
937 fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
938
939 /// Inform the adapter of updated window bounds.
940 fn a11y_update_window_bounds(&self) {}
941
942 #[cfg(any(test, feature = "test-support"))]
943 fn as_test(&mut self) -> Option<&mut TestWindow> {
944 None
945 }
946
947 /// Renders the given scene to a texture and returns the pixel data as an RGBA image.
948 /// This does not present the frame to screen - useful for visual testing where we want
949 /// to capture what would be rendered without displaying it or requiring the window to be visible.
950 #[cfg(any(test, feature = "test-support"))]
951 fn render_to_image(&self, _scene: &Scene) -> Result<RgbaImage> {
952 anyhow::bail!("render_to_image not implemented for this platform")
953 }
954}
955
956/// A renderer for headless windows that can produce real rendered output.
957#[cfg(any(test, feature = "test-support"))]
958pub trait PlatformHeadlessRenderer {
959 /// Render a scene and return the result as an RGBA image.
960 fn render_scene_to_image(
961 &mut self,
962 scene: &Scene,
963 size: Size<DevicePixels>,
964 ) -> Result<RgbaImage>;
965
966 /// Render a scene to an offscreen target without reading the result back.
967 ///
968 /// This is the headless analogue of presenting a frame: it performs the
969 /// same CPU-side scene encoding and GPU submission as drawing to a real
970 /// window, but doesn't block on GPU completion or copy pixels back.
971 fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> Result<()>;
972
973 /// Returns the sprite atlas used by this renderer.
974 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
975}
976
977/// Type alias for runnables with metadata.
978/// Previously an enum with a single variant, now simplified to a direct type alias.
979#[doc(hidden)]
980pub type RunnableVariant = Runnable<RunnableMeta>;
981
982#[doc(hidden)]
983pub type TimerResolutionGuard = gpui_util::Deferred<Box<dyn FnOnce() + Send>>;
984
985#[doc(hidden)]
986pub enum TasksIncluded {
987 OnlyCompleted,
988 CompletedAndRunning,
989}
990
991/// This type is public so that our test macro can generate and use it, but it should not
992/// be considered part of our public API.
993#[doc(hidden)]
994pub trait PlatformDispatcher: Send + Sync {
995 fn is_main_thread(&self) -> bool;
996 fn dispatch(&self, runnable: RunnableVariant, priority: Priority);
997 fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority);
998 fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
999
1000 fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>);
1001
1002 fn now(&self) -> Instant {
1003 Instant::now()
1004 }
1005
1006 fn increase_timer_resolution(&self) -> TimerResolutionGuard {
1007 gpui_util::defer(Box::new(|| {}))
1008 }
1009
1010 #[cfg(any(test, feature = "test-support"))]
1011 fn as_test(&self) -> Option<&TestDispatcher> {
1012 None
1013 }
1014
1015 // This cfg must match the `bench_dispatcher` module's, which implements
1016 // this method whenever it compiles.
1017 #[cfg(any(test, feature = "bench"))]
1018 fn as_bench(&self) -> Option<&BenchDispatcher> {
1019 None
1020 }
1021}
1022
1023#[expect(missing_docs)]
1024pub trait PlatformTextSystem: Send + Sync {
1025 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
1026 /// Get all available font names.
1027 fn all_font_names(&self) -> Vec<String>;
1028 /// Get the font ID for a font descriptor.
1029 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
1030 /// Get metrics for a font.
1031 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
1032 /// Get typographic bounds for a glyph.
1033 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
1034 /// Get the advance width for a glyph.
1035 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
1036 /// Get the glyph ID for a character.
1037 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
1038 /// Get raster bounds for a glyph.
1039 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
1040 /// Rasterize a glyph.
1041 fn rasterize_glyph(
1042 &self,
1043 params: &RenderGlyphParams,
1044 raster_bounds: Bounds<DevicePixels>,
1045 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
1046 /// Layout a line of text with the given font runs.
1047 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
1048 /// Returns the recommended text rendering mode for the given font and size.
1049 fn recommended_rendering_mode(&self, _font_id: FontId, _font_size: Pixels)
1050 -> TextRenderingMode;
1051 /// Returns the dilation level to use for a glyph painted in the given color.
1052 fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
1053 0
1054 }
1055}
1056
1057#[expect(missing_docs)]
1058pub struct NoopTextSystem;
1059
1060#[expect(missing_docs)]
1061impl NoopTextSystem {
1062 #[allow(dead_code)]
1063 pub fn new() -> Self {
1064 Self
1065 }
1066}
1067
1068impl PlatformTextSystem for NoopTextSystem {
1069 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
1070 Ok(())
1071 }
1072
1073 fn all_font_names(&self) -> Vec<String> {
1074 Vec::new()
1075 }
1076
1077 fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
1078 Ok(FontId(1))
1079 }
1080
1081 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1082 FontMetrics {
1083 units_per_em: 1000,
1084 ascent: 1025.0,
1085 descent: -275.0,
1086 line_gap: 0.0,
1087 underline_position: -95.0,
1088 underline_thickness: 60.0,
1089 cap_height: 698.0,
1090 x_height: 516.0,
1091 bounding_box: Bounds {
1092 origin: Point {
1093 x: -260.0,
1094 y: -245.0,
1095 },
1096 size: Size {
1097 width: 1501.0,
1098 height: 1364.0,
1099 },
1100 },
1101 }
1102 }
1103
1104 fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
1105 Ok(Bounds {
1106 origin: Point { x: 54.0, y: 0.0 },
1107 size: size(392.0, 528.0),
1108 })
1109 }
1110
1111 fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
1112 Ok(size(600.0 * glyph_id.0 as f32, 0.0))
1113 }
1114
1115 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1116 Some(GlyphId(ch.len_utf16() as u32))
1117 }
1118
1119 fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
1120 Ok(Default::default())
1121 }
1122
1123 fn rasterize_glyph(
1124 &self,
1125 _params: &RenderGlyphParams,
1126 raster_bounds: Bounds<DevicePixels>,
1127 ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
1128 Ok((raster_bounds.size, Vec::new()))
1129 }
1130
1131 fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
1132 let mut position = px(0.);
1133 let metrics = self.font_metrics(FontId(0));
1134 let em_width = font_size
1135 * self
1136 .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
1137 .unwrap()
1138 .width
1139 / metrics.units_per_em as f32;
1140 let mut glyphs = Vec::new();
1141 for (ix, c) in text.char_indices() {
1142 if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
1143 glyphs.push(ShapedGlyph {
1144 id: glyph,
1145 position: point(position, px(0.)),
1146 index: ix,
1147 is_emoji: glyph.0 == 2,
1148 });
1149 if glyph.0 == 2 {
1150 position += em_width * 2.0;
1151 } else {
1152 position += em_width;
1153 }
1154 } else {
1155 position += em_width
1156 }
1157 }
1158 let mut runs = Vec::default();
1159 if !glyphs.is_empty() {
1160 runs.push(ShapedRun {
1161 font_id: FontId(0),
1162 glyphs,
1163 });
1164 } else {
1165 position = px(0.);
1166 }
1167
1168 LineLayout {
1169 font_size,
1170 width: position,
1171 ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
1172 descent: font_size * (metrics.descent / metrics.units_per_em as f32),
1173 runs,
1174 len: text.len(),
1175 }
1176 }
1177
1178 fn recommended_rendering_mode(
1179 &self,
1180 _font_id: FontId,
1181 _font_size: Pixels,
1182 ) -> TextRenderingMode {
1183 TextRenderingMode::Grayscale
1184 }
1185}
1186
1187// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.cpp
1188// Copyright (c) Microsoft Corporation.
1189// Licensed under the MIT license.
1190/// Compute gamma correction ratios for subpixel text rendering.
1191#[allow(dead_code)]
1192pub fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
1193 const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
1194 [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], // gamma = 1.0
1195 [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], // gamma = 1.1
1196 [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], // gamma = 1.2
1197 [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], // gamma = 1.3
1198 [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], // gamma = 1.4
1199 [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], // gamma = 1.5
1200 [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], // gamma = 1.6
1201 [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], // gamma = 1.7
1202 [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], // gamma = 1.8
1203 [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], // gamma = 1.9
1204 [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], // gamma = 2.0
1205 [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], // gamma = 2.1
1206 [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], // gamma = 2.2
1207 ];
1208
1209 const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
1210 const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
1211
1212 let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
1213 let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
1214
1215 [
1216 ratios[0] * NORM13,
1217 ratios[1] * NORM24,
1218 ratios[2] * NORM13,
1219 ratios[3] * NORM24,
1220 ]
1221}
1222
1223#[derive(PartialEq, Eq, Hash, Clone)]
1224#[expect(missing_docs)]
1225pub enum AtlasKey {
1226 Glyph(RenderGlyphParams),
1227 Svg(RenderSvgParams),
1228 Image(RenderImageParams),
1229}
1230
1231impl AtlasKey {
1232 #[cfg_attr(
1233 all(
1234 any(target_os = "linux", target_os = "freebsd"),
1235 not(any(feature = "x11", feature = "wayland"))
1236 ),
1237 allow(dead_code)
1238 )]
1239 /// Returns the texture kind for this atlas key.
1240 pub fn texture_kind(&self) -> AtlasTextureKind {
1241 match self {
1242 AtlasKey::Glyph(params) => {
1243 if params.is_emoji {
1244 AtlasTextureKind::Polychrome
1245 } else if params.subpixel_rendering {
1246 AtlasTextureKind::Subpixel
1247 } else {
1248 AtlasTextureKind::Monochrome
1249 }
1250 }
1251 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
1252 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
1253 }
1254 }
1255}
1256
1257impl From<RenderGlyphParams> for AtlasKey {
1258 fn from(params: RenderGlyphParams) -> Self {
1259 Self::Glyph(params)
1260 }
1261}
1262
1263impl From<RenderSvgParams> for AtlasKey {
1264 fn from(params: RenderSvgParams) -> Self {
1265 Self::Svg(params)
1266 }
1267}
1268
1269impl From<RenderImageParams> for AtlasKey {
1270 fn from(params: RenderImageParams) -> Self {
1271 Self::Image(params)
1272 }
1273}
1274
1275#[expect(missing_docs)]
1276pub trait PlatformAtlas {
1277 fn get_or_insert_with<'a>(
1278 &self,
1279 key: &AtlasKey,
1280 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
1281 ) -> Result<Option<AtlasTile>>;
1282 fn remove(&self, key: &AtlasKey);
1283}
1284
1285#[doc(hidden)]
1286pub struct AtlasTextureList<T> {
1287 pub textures: Vec<Option<T>>,
1288 pub free_list: Vec<usize>,
1289}
1290
1291impl<T> Default for AtlasTextureList<T> {
1292 fn default() -> Self {
1293 Self {
1294 textures: Vec::default(),
1295 free_list: Vec::default(),
1296 }
1297 }
1298}
1299
1300impl<T> ops::Index<usize> for AtlasTextureList<T> {
1301 type Output = Option<T>;
1302
1303 fn index(&self, index: usize) -> &Self::Output {
1304 &self.textures[index]
1305 }
1306}
1307
1308impl<T> AtlasTextureList<T> {
1309 #[allow(unused)]
1310 pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
1311 self.free_list.clear();
1312 self.textures.drain(..)
1313 }
1314
1315 #[allow(dead_code)]
1316 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
1317 self.textures.iter_mut().flatten()
1318 }
1319}
1320
1321#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1322#[repr(C)]
1323#[expect(missing_docs)]
1324pub struct AtlasTile {
1325 /// The texture this tile belongs to.
1326 pub texture_id: AtlasTextureId,
1327 /// The unique ID of this tile within its texture.
1328 pub tile_id: TileId,
1329 /// Padding around the tile content in pixels.
1330 pub padding: u32,
1331 /// The bounds of this tile within the texture.
1332 pub bounds: Bounds<DevicePixels>,
1333}
1334
1335#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1336#[repr(C)]
1337#[expect(missing_docs)]
1338pub struct AtlasTextureId {
1339 // We use u32 instead of usize for Metal Shader Language compatibility
1340 /// The index of this texture in the atlas.
1341 pub index: u32,
1342 /// The kind of content stored in this texture.
1343 pub kind: AtlasTextureKind,
1344}
1345
1346#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1347#[repr(C)]
1348#[cfg_attr(
1349 all(
1350 any(target_os = "linux", target_os = "freebsd"),
1351 not(any(feature = "x11", feature = "wayland"))
1352 ),
1353 allow(dead_code)
1354)]
1355#[expect(missing_docs)]
1356pub enum AtlasTextureKind {
1357 Monochrome = 0,
1358 Polychrome = 1,
1359 Subpixel = 2,
1360}
1361
1362#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1363#[repr(C)]
1364#[expect(missing_docs)]
1365pub struct TileId(pub u32);
1366
1367impl From<etagere::AllocId> for TileId {
1368 fn from(id: etagere::AllocId) -> Self {
1369 Self(id.serialize())
1370 }
1371}
1372
1373impl From<TileId> for etagere::AllocId {
1374 fn from(id: TileId) -> Self {
1375 Self::deserialize(id.0)
1376 }
1377}
1378
1379#[expect(missing_docs)]
1380pub struct PlatformInputHandler {
1381 cx: AsyncWindowContext,
1382 handler: Box<dyn InputHandler>,
1383}
1384
1385#[expect(missing_docs)]
1386#[cfg_attr(
1387 all(
1388 any(target_os = "linux", target_os = "freebsd"),
1389 not(any(feature = "x11", feature = "wayland"))
1390 ),
1391 allow(dead_code)
1392)]
1393impl PlatformInputHandler {
1394 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
1395 Self { cx, handler }
1396 }
1397
1398 pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
1399 self.cx
1400 .update(|window, cx| {
1401 self.handler
1402 .selected_text_range(ignore_disabled_input, window, cx)
1403 })
1404 .ok()
1405 .flatten()
1406 }
1407
1408 #[cfg_attr(target_os = "windows", allow(dead_code))]
1409 pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
1410 self.cx
1411 .update(|window, cx| self.handler.marked_text_range(window, cx))
1412 .ok()
1413 .flatten()
1414 }
1415
1416 #[cfg_attr(
1417 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1418 allow(dead_code)
1419 )]
1420 pub fn text_for_range(
1421 &mut self,
1422 range_utf16: Range<usize>,
1423 adjusted: &mut Option<Range<usize>>,
1424 ) -> Option<String> {
1425 self.cx
1426 .update(|window, cx| {
1427 self.handler
1428 .text_for_range(range_utf16, adjusted, window, cx)
1429 })
1430 .ok()
1431 .flatten()
1432 }
1433
1434 pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
1435 self.cx
1436 .update(|window, cx| {
1437 self.handler
1438 .replace_text_in_range(replacement_range, text, window, cx);
1439 })
1440 .ok();
1441 }
1442
1443 pub fn replace_and_mark_text_in_range(
1444 &mut self,
1445 range_utf16: Option<Range<usize>>,
1446 new_text: &str,
1447 new_selected_range: Option<Range<usize>>,
1448 ) {
1449 self.cx
1450 .update(|window, cx| {
1451 self.handler.replace_and_mark_text_in_range(
1452 range_utf16,
1453 new_text,
1454 new_selected_range,
1455 window,
1456 cx,
1457 )
1458 })
1459 .ok();
1460 }
1461
1462 #[cfg_attr(target_os = "windows", allow(dead_code))]
1463 pub fn unmark_text(&mut self) {
1464 self.cx
1465 .update(|window, cx| self.handler.unmark_text(window, cx))
1466 .ok();
1467 }
1468
1469 pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
1470 self.cx
1471 .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
1472 .ok()
1473 .flatten()
1474 }
1475
1476 #[allow(dead_code)]
1477 pub fn apple_press_and_hold_enabled(&mut self) -> bool {
1478 self.handler.apple_press_and_hold_enabled()
1479 }
1480
1481 pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1482 self.handler.replace_text_in_range(None, input, window, cx);
1483 }
1484
1485 pub fn compute_ime_candidate_bounds(
1486 marked_range: Option<Range<usize>>,
1487 selection: &UTF16Selection,
1488 mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
1489 ) -> Option<Bounds<Pixels>> {
1490 if let Some(marked_range) = marked_range {
1491 // Default to the start of the marked (composing) range.
1492 let mut line_start = marked_range.start;
1493
1494 // Walk backward from the caret looking for a line break. A change in
1495 // the Y coordinate means we crossed into the previous visual line, so
1496 // the line start is one position after the break point.
1497 let caret = selection.range.end;
1498 if let Some(caret_bounds) = bounds_for_range(caret..caret) {
1499 for i in (marked_range.start..caret).rev() {
1500 if let Some(b) = bounds_for_range(i..i) {
1501 if (b.origin.y - caret_bounds.origin.y).abs() > px(0.1) {
1502 line_start = i + 1;
1503 break;
1504 }
1505 }
1506 }
1507 }
1508 bounds_for_range(line_start..line_start)
1509 } else {
1510 // No active composition — use the selection endpoint.
1511 let offset = if selection.reversed {
1512 selection.range.start
1513 } else {
1514 selection.range.end
1515 };
1516 bounds_for_range(offset..offset)
1517 }
1518 }
1519
1520 pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
1521 let marked_range = self.handler.marked_text_range(window, cx);
1522 let selection = self.handler.selected_text_range(true, window, cx)?;
1523 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
1524 self.handler.bounds_for_range(range, window, cx)
1525 })
1526 }
1527
1528 pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
1529 let marked_range = self.marked_text_range();
1530 let selection = self.selected_text_range(true)?;
1531 Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
1532 self.bounds_for_range(range)
1533 })
1534 }
1535
1536 #[allow(unused)]
1537 pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
1538 self.cx
1539 .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
1540 .ok()
1541 .flatten()
1542 }
1543
1544 /// See [`InputHandler::set_selected_text_range`].
1545 pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
1546 self.cx
1547 .update(|window, cx| {
1548 self.handler
1549 .set_selected_text_range(range_utf16, window, cx)
1550 })
1551 .ok();
1552 }
1553
1554 /// See [`InputHandler::element_bounds`].
1555 pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
1556 self.cx
1557 .update(|window, cx| self.handler.element_bounds(window, cx))
1558 .ok()
1559 .flatten()
1560 }
1561
1562 /// See [`InputHandler::text_length_utf16`].
1563 pub fn text_length_utf16(&mut self) -> Option<usize> {
1564 self.cx
1565 .update(|window, cx| self.handler.text_length_utf16(window, cx))
1566 .ok()
1567 .flatten()
1568 }
1569
1570 #[allow(dead_code)]
1571 pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
1572 self.handler.accepts_text_input(window, cx)
1573 }
1574
1575 #[allow(dead_code)]
1576 pub fn query_accepts_text_input(&mut self) -> bool {
1577 self.cx
1578 .update(|window, cx| self.handler.accepts_text_input(window, cx))
1579 .unwrap_or(true)
1580 }
1581
1582 #[allow(dead_code)]
1583 pub fn query_prefers_ime_for_printable_keys(&mut self) -> bool {
1584 self.cx
1585 .update(|window, cx| self.handler.prefers_ime_for_printable_keys(window, cx))
1586 .unwrap_or(false)
1587 }
1588}
1589
1590/// A struct representing a selection in a text buffer, in UTF16 characters.
1591/// This is different from a range because the head may be before the tail.
1592#[derive(Debug)]
1593pub struct UTF16Selection {
1594 /// The range of text in the document this selection corresponds to
1595 /// in UTF16 characters.
1596 pub range: Range<usize>,
1597 /// Whether the head of this selection is at the start (true), or end (false)
1598 /// of the range
1599 pub reversed: bool,
1600}
1601
1602/// Omega's interface for handling text input from the platform's IME system
1603/// This is currently a 1:1 exposure of the NSTextInputClient API:
1604///
1605/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
1606pub trait InputHandler: 'static {
1607 /// Get the range of the user's currently selected text, if any
1608 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
1609 ///
1610 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1611 fn selected_text_range(
1612 &mut self,
1613 ignore_disabled_input: bool,
1614 window: &mut Window,
1615 cx: &mut App,
1616 ) -> Option<UTF16Selection>;
1617
1618 /// Get the range of the currently marked text, if any
1619 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
1620 ///
1621 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1622 fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
1623
1624 /// Get the text for the given document range in UTF-16 characters
1625 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
1626 ///
1627 /// range_utf16 is in terms of UTF-16 characters
1628 fn text_for_range(
1629 &mut self,
1630 range_utf16: Range<usize>,
1631 adjusted_range: &mut Option<Range<usize>>,
1632 window: &mut Window,
1633 cx: &mut App,
1634 ) -> Option<String>;
1635
1636 /// Replace the text in the given document range with the given text
1637 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
1638 ///
1639 /// replacement_range is in terms of UTF-16 characters
1640 fn replace_text_in_range(
1641 &mut self,
1642 replacement_range: Option<Range<usize>>,
1643 text: &str,
1644 window: &mut Window,
1645 cx: &mut App,
1646 );
1647
1648 /// Replace the text in the given document range with the given text,
1649 /// and mark the given text as part of an IME 'composing' state
1650 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
1651 ///
1652 /// range_utf16 is in terms of UTF-16 characters
1653 /// new_selected_range is in terms of UTF-16 characters
1654 fn replace_and_mark_text_in_range(
1655 &mut self,
1656 range_utf16: Option<Range<usize>>,
1657 new_text: &str,
1658 new_selected_range: Option<Range<usize>>,
1659 window: &mut Window,
1660 cx: &mut App,
1661 );
1662
1663 /// Remove the IME 'composing' state from the document
1664 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
1665 fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
1666
1667 /// Get the bounds of the given document range in screen coordinates
1668 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
1669 ///
1670 /// This is used for positioning the IME candidate window
1671 fn bounds_for_range(
1672 &mut self,
1673 range_utf16: Range<usize>,
1674 window: &mut Window,
1675 cx: &mut App,
1676 ) -> Option<Bounds<Pixels>>;
1677
1678 /// Get the character offset for the given point in terms of UTF16 characters
1679 ///
1680 /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
1681 fn character_index_for_point(
1682 &mut self,
1683 point: Point<Pixels>,
1684 window: &mut Window,
1685 cx: &mut App,
1686 ) -> Option<usize>;
1687
1688 /// Set the range of the user's currently selected text.
1689 ///
1690 /// This is the reverse data-flow direction from [`Self::selected_text_range`]:
1691 /// platforms call it when the system text machinery moves the selection on the
1692 /// application's behalf — e.g. the user drags a system selection handle or
1693 /// invokes Select All from system UI (iOS `UITextInput setSelectedTextRange:`,
1694 /// Android `InputConnection.setSelection`).
1695 ///
1696 /// range_utf16 is in terms of UTF-16 characters, from 0 to the length of the document
1697 fn set_selected_text_range(
1698 &mut self,
1699 _range_utf16: Range<usize>,
1700 _window: &mut Window,
1701 _cx: &mut App,
1702 ) {
1703 }
1704
1705 /// Get the bounds of the focused text element in window coordinates, if known.
1706 ///
1707 /// This is the pull counterpart to the [`PlatformWindow::update_ime_position`]
1708 /// push: mobile platforms ask for the focused element's geometry when they
1709 /// need it (e.g. to frame system text-interaction UI overlaid on the focused
1710 /// element).
1711 fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
1712 None
1713 }
1714
1715 /// Get the length of the document in UTF-16 characters, if known.
1716 fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
1717 None
1718 }
1719
1720 /// Allows a given input context to opt into getting raw key repeats instead of
1721 /// sending these to the platform.
1722 /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1723 /// (which is how iTerm does it) but it doesn't seem to work for me.
1724 #[allow(dead_code)]
1725 fn apple_press_and_hold_enabled(&mut self) -> bool {
1726 true
1727 }
1728
1729 /// Returns whether this handler is accepting text input to be inserted.
1730 fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1731 true
1732 }
1733
1734 /// Returns whether printable keys should be routed to the IME before keybinding
1735 /// matching when a non-ASCII input source (e.g. Japanese, Korean, Chinese IME)
1736 /// is active. This prevents multi-stroke keybindings like `jj` from intercepting
1737 /// keys that the IME should compose.
1738 ///
1739 /// Defaults to `false`. The editor overrides this based on whether it expects
1740 /// character input (e.g. Vim insert mode returns `true`, normal mode returns `false`).
1741 /// The terminal keeps the default `false` so that raw keys reach the terminal process.
1742 fn prefers_ime_for_printable_keys(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1743 false
1744 }
1745}
1746
1747/// The variables that can be configured when creating a new window
1748#[derive(Debug)]
1749pub struct WindowOptions {
1750 /// Specifies the state and bounds of the window in screen coordinates.
1751 /// - `None`: Inherit the bounds.
1752 /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1753 pub window_bounds: Option<WindowBounds>,
1754
1755 /// The titlebar configuration of the window
1756 pub titlebar: Option<TitlebarOptions>,
1757
1758 /// Whether the window should be focused when created
1759 pub focus: bool,
1760
1761 /// Whether the window should be shown when created
1762 pub show: bool,
1763
1764 /// The kind of window to create
1765 pub kind: WindowKind,
1766
1767 /// Whether the window can be moved by the user. When `false`, the user cannot drag
1768 /// the window (on macOS this sets `NSWindow.isMovable`, which also disables the
1769 /// Window-menu tiling items); programmatic moves are still allowed.
1770 pub is_movable: bool,
1771
1772 /// Whether the application owns dragging of the (custom) titlebar, rather than
1773 /// AppKit. Only has an effect on macOS.
1774 ///
1775 /// Set this to `true` for windows that draw their own titlebar and move the window
1776 /// themselves via [`Window::start_window_move`]. It marks the whole content view as
1777 /// app-owned titlebar content, so AppKit neither drags the window from the titlebar
1778 /// nor delays titlebar clicks while disambiguating double-clicks (a delay first
1779 /// observed on macOS 27). It is independent of `is_movable`, so such windows stay
1780 /// user-movable (via their own drag) and keep the Window-menu tiling items enabled.
1781 ///
1782 /// Leave this `false` for windows that rely on AppKit's native titlebar dragging.
1783 pub app_owns_titlebar_drag: bool,
1784
1785 /// Whether the window should be resizable by the user
1786 pub is_resizable: bool,
1787
1788 /// Whether the window should be minimized by the user
1789 pub is_minimizable: bool,
1790
1791 /// The display to create the window on, if this is None,
1792 /// the window will be created on the main display
1793 pub display_id: Option<DisplayId>,
1794
1795 /// The appearance of the window background.
1796 pub window_background: WindowBackgroundAppearance,
1797
1798 /// Application identifier of the window. Can by used by desktop environments to group applications together.
1799 pub app_id: Option<String>,
1800
1801 /// Window minimum size
1802 pub window_min_size: Option<Size<Pixels>>,
1803
1804 /// Whether to use client or server side decorations. Wayland only
1805 /// Note that this may be ignored.
1806 pub window_decorations: Option<WindowDecorations>,
1807
1808 /// Icon image (X11 only)
1809 pub icon: Option<Arc<image::RgbaImage>>,
1810
1811 /// Tab group name, allows opening the window as a native tab on macOS 10.12+. Windows with the same tabbing identifier will be grouped together.
1812 pub tabbing_identifier: Option<String>,
1813}
1814
1815/// The variables that can be configured when creating a new window
1816#[derive(Debug)]
1817#[cfg_attr(
1818 all(
1819 any(target_os = "linux", target_os = "freebsd"),
1820 not(any(feature = "x11", feature = "wayland"))
1821 ),
1822 allow(dead_code)
1823)]
1824#[allow(missing_docs)]
1825pub struct WindowParams {
1826 pub bounds: Bounds<Pixels>,
1827
1828 /// The titlebar configuration of the window
1829 #[cfg_attr(feature = "wayland", allow(dead_code))]
1830 pub titlebar: Option<TitlebarOptions>,
1831
1832 /// The kind of window to create
1833 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1834 pub kind: WindowKind,
1835
1836 /// Whether the window should be movable by the user
1837 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1838 pub is_movable: bool,
1839
1840 /// Whether the application owns dragging of the (custom) titlebar (macOS only)
1841 #[cfg_attr(
1842 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1843 allow(dead_code)
1844 )]
1845 pub app_owns_titlebar_drag: bool,
1846
1847 /// Whether the window should be resizable by the user
1848 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1849 pub is_resizable: bool,
1850
1851 /// Whether the window should be minimized by the user
1852 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1853 pub is_minimizable: bool,
1854
1855 #[cfg_attr(
1856 any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1857 allow(dead_code)
1858 )]
1859 pub focus: bool,
1860
1861 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1862 pub show: bool,
1863
1864 /// An image to set as the window icon (x11 only)
1865 #[cfg_attr(feature = "wayland", allow(dead_code))]
1866 pub icon: Option<Arc<image::RgbaImage>>,
1867
1868 #[cfg_attr(feature = "wayland", allow(dead_code))]
1869 pub display_id: Option<DisplayId>,
1870
1871 #[cfg_attr(feature = "wayland", allow(dead_code))]
1872 pub app_id: Option<String>,
1873
1874 pub window_min_size: Option<Size<Pixels>>,
1875
1876 #[cfg(target_os = "macos")]
1877 pub tabbing_identifier: Option<String>,
1878}
1879
1880/// Represents the status of how a window should be opened.
1881#[derive(Debug, Copy, Clone, PartialEq)]
1882pub enum WindowBounds {
1883 /// Indicates that the window should open in a windowed state with the given bounds.
1884 Windowed(Bounds<Pixels>),
1885 /// Indicates that the window should open in a maximized state.
1886 /// The bounds provided here represent the restore size of the window.
1887 Maximized(Bounds<Pixels>),
1888 /// Indicates that the window should open in fullscreen mode.
1889 /// The bounds provided here represent the restore size of the window.
1890 Fullscreen(Bounds<Pixels>),
1891}
1892
1893impl Default for WindowBounds {
1894 fn default() -> Self {
1895 WindowBounds::Windowed(Bounds::default())
1896 }
1897}
1898
1899impl WindowBounds {
1900 /// Retrieve the inner bounds
1901 pub fn get_bounds(&self) -> Bounds<Pixels> {
1902 match self {
1903 WindowBounds::Windowed(bounds) => *bounds,
1904 WindowBounds::Maximized(bounds) => *bounds,
1905 WindowBounds::Fullscreen(bounds) => *bounds,
1906 }
1907 }
1908
1909 /// Creates a new window bounds that centers the window on the screen.
1910 pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
1911 WindowBounds::Windowed(Bounds::centered(None, size, cx))
1912 }
1913}
1914
1915impl Default for WindowOptions {
1916 fn default() -> Self {
1917 Self {
1918 window_bounds: None,
1919 titlebar: Some(TitlebarOptions {
1920 title: Default::default(),
1921 appears_transparent: Default::default(),
1922 traffic_light_position: Default::default(),
1923 }),
1924 focus: true,
1925 show: true,
1926 kind: WindowKind::Normal,
1927 is_movable: true,
1928 app_owns_titlebar_drag: false,
1929 is_resizable: true,
1930 is_minimizable: true,
1931 display_id: None,
1932 window_background: WindowBackgroundAppearance::default(),
1933 icon: None,
1934 app_id: None,
1935 window_min_size: None,
1936 window_decorations: None,
1937 tabbing_identifier: None,
1938 }
1939 }
1940}
1941
1942/// The options that can be configured for a window's titlebar
1943#[derive(Debug, Default)]
1944pub struct TitlebarOptions {
1945 /// The initial title of the window
1946 pub title: Option<SharedString>,
1947
1948 /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
1949 /// Refer to [`WindowOptions::window_decorations`] on Linux
1950 pub appears_transparent: bool,
1951
1952 /// The position of the macOS traffic light buttons
1953 pub traffic_light_position: Option<Point<Pixels>>,
1954}
1955
1956/// The kind of window to create
1957#[derive(Clone, Debug, PartialEq, Eq)]
1958pub enum WindowKind {
1959 /// A normal application window
1960 Normal,
1961
1962 /// A window that appears above all other windows, usually used for alerts or popups
1963 /// use sparingly!
1964 PopUp,
1965
1966 /// A parent-anchored, platform-native popup window for menus, comboboxes, context menus and
1967 /// tooltips. Unlike [`WindowKind::PopUp`], it is positioned relative to a parent window.
1968 ///
1969 /// The popup's size comes from [`WindowOptions::window_bounds`], whose origin is ignored.
1970 /// See [`popup::PopupOptions`] for the placement options. Platforms without a native
1971 /// implementation reject it with [`popup::PopupNotSupportedError`].
1972 AnchoredPopup(popup::PopupOptions),
1973
1974 /// A floating window that appears on top of its parent window
1975 Floating,
1976
1977 /// A Wayland LayerShell window, used to draw overlays or backgrounds for applications such as
1978 /// docks, notifications or wallpapers.
1979 #[cfg(all(target_os = "linux", feature = "wayland"))]
1980 LayerShell(layer_shell::LayerShellOptions),
1981
1982 /// A window that appears on top of its parent window and blocks interaction with it
1983 /// until the modal window is closed
1984 Dialog,
1985}
1986
1987/// The appearance of the window, as defined by the operating system.
1988///
1989/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
1990/// values.
1991#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1992pub enum WindowAppearance {
1993 /// A light appearance.
1994 ///
1995 /// On macOS, this corresponds to the `aqua` appearance.
1996 #[default]
1997 Light,
1998
1999 /// A light appearance with vibrant colors.
2000 ///
2001 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
2002 VibrantLight,
2003
2004 /// A dark appearance.
2005 ///
2006 /// On macOS, this corresponds to the `darkAqua` appearance.
2007 Dark,
2008
2009 /// A dark appearance with vibrant colors.
2010 ///
2011 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
2012 VibrantDark,
2013}
2014
2015/// The appearance of the background of the window itself, when there is
2016/// no content or the content is transparent.
2017#[derive(Copy, Clone, Debug, Default, PartialEq)]
2018pub enum WindowBackgroundAppearance {
2019 /// Opaque.
2020 ///
2021 /// This lets the window manager know that content behind this
2022 /// window does not need to be drawn.
2023 ///
2024 /// Actual color depends on the system and themes should define a fully
2025 /// opaque background color instead.
2026 #[default]
2027 Opaque,
2028 /// Plain alpha transparency.
2029 Transparent,
2030 /// Transparency, but the contents behind the window are blurred.
2031 ///
2032 /// Not always supported.
2033 Blurred,
2034 /// The Mica backdrop material, supported on Windows 11.
2035 MicaBackdrop,
2036 /// The Mica Alt backdrop material, supported on Windows 11.
2037 MicaAltBackdrop,
2038}
2039
2040/// The text rendering mode to use for drawing glyphs.
2041#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2042pub enum TextRenderingMode {
2043 /// Use the platform's default text rendering mode.
2044 #[default]
2045 PlatformDefault,
2046 /// Use subpixel (ClearType-style) text rendering.
2047 Subpixel,
2048 /// Use grayscale text rendering.
2049 Grayscale,
2050}
2051
2052/// The options that can be configured for a file dialog prompt
2053#[derive(Clone, Debug)]
2054pub struct PathPromptOptions {
2055 /// Should the prompt allow files to be selected?
2056 pub files: bool,
2057 /// Should the prompt allow directories to be selected?
2058 pub directories: bool,
2059 /// Should the prompt allow multiple files to be selected?
2060 pub multiple: bool,
2061 /// The prompt to show to a user when selecting a path
2062 pub prompt: Option<SharedString>,
2063}
2064
2065/// What kind of prompt styling to show
2066#[derive(Copy, Clone, Debug, PartialEq)]
2067pub enum PromptLevel {
2068 /// A prompt that is shown when the user should be notified of something
2069 Info,
2070
2071 /// A prompt that is shown when the user needs to be warned of a potential problem
2072 Warning,
2073
2074 /// A prompt that is shown when a critical problem has occurred
2075 Critical,
2076}
2077
2078/// Prompt Button
2079#[derive(Clone, Debug, PartialEq)]
2080pub enum PromptButton {
2081 /// Ok button
2082 Ok(SharedString),
2083 /// Cancel button
2084 Cancel(SharedString),
2085 /// Other button
2086 Other(SharedString),
2087}
2088
2089impl PromptButton {
2090 /// Create a button with label
2091 pub fn new(label: impl Into<SharedString>) -> Self {
2092 PromptButton::Other(label.into())
2093 }
2094
2095 /// Create an Ok button
2096 pub fn ok(label: impl Into<SharedString>) -> Self {
2097 PromptButton::Ok(label.into())
2098 }
2099
2100 /// Create a Cancel button
2101 pub fn cancel(label: impl Into<SharedString>) -> Self {
2102 PromptButton::Cancel(label.into())
2103 }
2104
2105 /// Returns true if this button is a cancel button.
2106 #[allow(dead_code)]
2107 pub fn is_cancel(&self) -> bool {
2108 matches!(self, PromptButton::Cancel(_))
2109 }
2110
2111 /// Returns the label of the button
2112 pub fn label(&self) -> &SharedString {
2113 match self {
2114 PromptButton::Ok(label) => label,
2115 PromptButton::Cancel(label) => label,
2116 PromptButton::Other(label) => label,
2117 }
2118 }
2119}
2120
2121impl From<&str> for PromptButton {
2122 fn from(value: &str) -> Self {
2123 match value.to_lowercase().as_str() {
2124 "ok" => PromptButton::Ok("OK".into()),
2125 "cancel" => PromptButton::Cancel("Cancel".into()),
2126 _ => PromptButton::Other(SharedString::from(value.to_owned())),
2127 }
2128 }
2129}
2130
2131/// The style of the cursor (pointer)
2132#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
2133pub enum CursorStyle {
2134 /// The default cursor
2135 #[default]
2136 Arrow,
2137
2138 /// A text input cursor
2139 /// corresponds to the CSS cursor value `text`
2140 IBeam,
2141
2142 /// A crosshair cursor
2143 /// corresponds to the CSS cursor value `crosshair`
2144 Crosshair,
2145
2146 /// A closed hand cursor
2147 /// corresponds to the CSS cursor value `grabbing`
2148 ClosedHand,
2149
2150 /// An open hand cursor
2151 /// corresponds to the CSS cursor value `grab`
2152 OpenHand,
2153
2154 /// A pointing hand cursor
2155 /// corresponds to the CSS cursor value `pointer`
2156 PointingHand,
2157
2158 /// A resize left cursor
2159 /// corresponds to the CSS cursor value `w-resize`
2160 ResizeLeft,
2161
2162 /// A resize right cursor
2163 /// corresponds to the CSS cursor value `e-resize`
2164 ResizeRight,
2165
2166 /// A resize cursor to the left and right
2167 /// corresponds to the CSS cursor value `ew-resize`
2168 ResizeLeftRight,
2169
2170 /// A resize up cursor
2171 /// corresponds to the CSS cursor value `n-resize`
2172 ResizeUp,
2173
2174 /// A resize down cursor
2175 /// corresponds to the CSS cursor value `s-resize`
2176 ResizeDown,
2177
2178 /// A resize cursor directing up and down
2179 /// corresponds to the CSS cursor value `ns-resize`
2180 ResizeUpDown,
2181
2182 /// A resize cursor directing up-left and down-right
2183 /// corresponds to the CSS cursor value `nesw-resize`
2184 ResizeUpLeftDownRight,
2185
2186 /// A resize cursor directing up-right and down-left
2187 /// corresponds to the CSS cursor value `nwse-resize`
2188 ResizeUpRightDownLeft,
2189
2190 /// A cursor indicating that the item/column can be resized horizontally.
2191 /// corresponds to the CSS cursor value `col-resize`
2192 ResizeColumn,
2193
2194 /// A cursor indicating that the item/row can be resized vertically.
2195 /// corresponds to the CSS cursor value `row-resize`
2196 ResizeRow,
2197
2198 /// A text input cursor for vertical layout
2199 /// corresponds to the CSS cursor value `vertical-text`
2200 IBeamCursorForVerticalLayout,
2201
2202 /// A cursor indicating that the operation is not allowed
2203 /// corresponds to the CSS cursor value `not-allowed`
2204 OperationNotAllowed,
2205
2206 /// A cursor indicating that the operation will result in a link
2207 /// corresponds to the CSS cursor value `alias`
2208 DragLink,
2209
2210 /// A cursor indicating that the operation will result in a copy
2211 /// corresponds to the CSS cursor value `copy`
2212 DragCopy,
2213
2214 /// A cursor indicating that the operation will result in a context menu
2215 /// corresponds to the CSS cursor value `context-menu`
2216 ContextualMenu,
2217}
2218
2219/// A clipboard item that should be copied to the clipboard
2220#[derive(Clone, Debug, Eq, PartialEq)]
2221pub struct ClipboardItem {
2222 /// The entries in this clipboard item.
2223 pub entries: Vec<ClipboardEntry>,
2224}
2225
2226/// Either a ClipboardString or a ClipboardImage
2227#[derive(Clone, Debug, Eq, PartialEq)]
2228pub enum ClipboardEntry {
2229 /// A string entry
2230 String(ClipboardString),
2231 /// An image entry
2232 Image(Image),
2233 /// A file entry
2234 ExternalPaths(crate::ExternalPaths),
2235}
2236
2237impl ClipboardItem {
2238 /// Create a new ClipboardItem::String with no associated metadata
2239 pub fn new_string(text: String) -> Self {
2240 Self {
2241 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
2242 }
2243 }
2244
2245 /// Create a new ClipboardItem::String with the given text and associated metadata
2246 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
2247 Self {
2248 entries: vec![ClipboardEntry::String(ClipboardString {
2249 text,
2250 metadata: Some(metadata),
2251 })],
2252 }
2253 }
2254
2255 /// Create a new ClipboardItem::String with the given text and associated metadata
2256 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
2257 Self {
2258 entries: vec![ClipboardEntry::String(
2259 ClipboardString::new(text).with_json_metadata(metadata),
2260 )],
2261 }
2262 }
2263
2264 /// Create a new ClipboardItem::Image with the given image with no associated metadata
2265 pub fn new_image(image: &Image) -> Self {
2266 Self {
2267 entries: vec![ClipboardEntry::Image(image.clone())],
2268 }
2269 }
2270
2271 /// Concatenates together all the ClipboardString entries in the item.
2272 /// Returns None if there were no ClipboardString entries.
2273 pub fn text(&self) -> Option<String> {
2274 let mut answer = String::new();
2275
2276 for entry in self.entries.iter() {
2277 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
2278 answer.push_str(text);
2279 }
2280 }
2281
2282 if answer.is_empty() {
2283 for entry in self.entries.iter() {
2284 if let ClipboardEntry::ExternalPaths(paths) = entry {
2285 for path in &paths.0 {
2286 use std::fmt::Write as _;
2287 _ = write!(answer, "{}", path.display());
2288 }
2289 }
2290 }
2291 }
2292
2293 if !answer.is_empty() {
2294 Some(answer)
2295 } else {
2296 None
2297 }
2298 }
2299
2300 /// If this item is one ClipboardEntry::String, returns its metadata.
2301 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
2302 pub fn metadata(&self) -> Option<&String> {
2303 match self.entries().first() {
2304 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
2305 clipboard_string.metadata.as_ref()
2306 }
2307 _ => None,
2308 }
2309 }
2310
2311 /// Get the item's entries
2312 pub fn entries(&self) -> &[ClipboardEntry] {
2313 &self.entries
2314 }
2315
2316 /// Get owned versions of the item's entries
2317 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
2318 self.entries.into_iter()
2319 }
2320}
2321
2322impl From<ClipboardString> for ClipboardEntry {
2323 fn from(value: ClipboardString) -> Self {
2324 Self::String(value)
2325 }
2326}
2327
2328impl From<String> for ClipboardEntry {
2329 fn from(value: String) -> Self {
2330 Self::from(ClipboardString::from(value))
2331 }
2332}
2333
2334impl From<Image> for ClipboardEntry {
2335 fn from(value: Image) -> Self {
2336 Self::Image(value)
2337 }
2338}
2339
2340impl From<ClipboardEntry> for ClipboardItem {
2341 fn from(value: ClipboardEntry) -> Self {
2342 Self {
2343 entries: vec![value],
2344 }
2345 }
2346}
2347
2348impl From<String> for ClipboardItem {
2349 fn from(value: String) -> Self {
2350 Self::from(ClipboardEntry::from(value))
2351 }
2352}
2353
2354impl From<Image> for ClipboardItem {
2355 fn from(value: Image) -> Self {
2356 Self::from(ClipboardEntry::from(value))
2357 }
2358}
2359
2360/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
2361#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
2362pub enum ImageFormat {
2363 // Sorted from most to least likely to be pasted into an editor,
2364 // which matters when we iterate through them trying to see if
2365 // clipboard content matches them.
2366 /// .png
2367 Png,
2368 /// .jpeg or .jpg
2369 Jpeg,
2370 /// .webp
2371 Webp,
2372 /// .gif
2373 Gif,
2374 /// .svg
2375 Svg,
2376 /// .bmp
2377 Bmp,
2378 /// .tif or .tiff
2379 Tiff,
2380 /// .ico
2381 Ico,
2382 /// Netpbm image formats (.pbm, .ppm, .pgm).
2383 Pnm,
2384}
2385
2386impl ImageFormat {
2387 /// Returns the mime type for the ImageFormat
2388 pub const fn mime_type(self) -> &'static str {
2389 match self {
2390 ImageFormat::Png => "image/png",
2391 ImageFormat::Jpeg => "image/jpeg",
2392 ImageFormat::Webp => "image/webp",
2393 ImageFormat::Gif => "image/gif",
2394 ImageFormat::Svg => "image/svg+xml",
2395 ImageFormat::Bmp => "image/bmp",
2396 ImageFormat::Tiff => "image/tiff",
2397 ImageFormat::Ico => "image/ico",
2398 ImageFormat::Pnm => "image/x-portable-anymap",
2399 }
2400 }
2401
2402 /// Returns the file extension for this image format (without leading dot).
2403 pub const fn extension(self) -> &'static str {
2404 match self {
2405 ImageFormat::Png => "png",
2406 ImageFormat::Jpeg => "jpg",
2407 ImageFormat::Webp => "webp",
2408 ImageFormat::Gif => "gif",
2409 ImageFormat::Svg => "svg",
2410 ImageFormat::Bmp => "bmp",
2411 ImageFormat::Tiff => "tiff",
2412 ImageFormat::Ico => "ico",
2413 ImageFormat::Pnm => "pnm",
2414 }
2415 }
2416
2417 /// Returns the ImageFormat for the given mime type, including known aliases.
2418 pub fn from_mime_type(mime_type: &str) -> Option<Self> {
2419 use strum::IntoEnumIterator;
2420 Self::iter()
2421 .find(|format| format.mime_type() == mime_type)
2422 .or_else(|| Self::from_mime_type_alias(mime_type))
2423 }
2424
2425 /// Non-canonical mime types that some producers use in the wild.
2426 /// Unlike `mime_type()` which returns the single canonical form,
2427 /// these are legacy or shortened variants we still need to recognize.
2428 fn from_mime_type_alias(mime_type: &str) -> Option<Self> {
2429 match mime_type {
2430 "image/jpg" => Some(Self::Jpeg),
2431 "image/tif" => Some(Self::Tiff),
2432 _ => None,
2433 }
2434 }
2435}
2436
2437/// An image, with a format and certain bytes
2438#[derive(Clone, Debug, PartialEq, Eq)]
2439pub struct Image {
2440 /// The image format the bytes represent (e.g. PNG)
2441 pub format: ImageFormat,
2442 /// The raw image bytes
2443 pub bytes: Vec<u8>,
2444 /// The unique ID for the image
2445 pub id: u64,
2446}
2447
2448pub(crate) fn decode_static_image(
2449 bytes: &[u8],
2450 format: image::ImageFormat,
2451) -> Result<SmallVec<[Frame; 1]>> {
2452 let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
2453 .into_decoder()
2454 .context("creating image decoder")?;
2455 decode_static_image_from_decoder(decoder)
2456}
2457
2458pub(crate) fn decode_static_image_from_decoder(
2459 mut decoder: impl image::ImageDecoder,
2460) -> Result<SmallVec<[Frame; 1]>> {
2461 let orientation = decoder
2462 .orientation()
2463 .context("reading decoder's orientation")?;
2464 let mut image = DynamicImage::from_decoder(decoder).context("decoding image")?;
2465 image.apply_orientation(orientation);
2466
2467 let mut data = image.into_rgba8();
2468 for pixel in data.chunks_exact_mut(4) {
2469 pixel.swap(0, 2);
2470 }
2471
2472 Ok(SmallVec::from_elem(Frame::new(data), 1))
2473}
2474
2475impl Hash for Image {
2476 fn hash<H: Hasher>(&self, state: &mut H) {
2477 state.write_u64(self.id);
2478 }
2479}
2480
2481impl Image {
2482 /// An empty image containing no data
2483 pub fn empty() -> Self {
2484 Self::from_bytes(ImageFormat::Png, Vec::new())
2485 }
2486
2487 /// Create an image from a format and bytes
2488 pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
2489 Self {
2490 id: hash(&bytes),
2491 format,
2492 bytes,
2493 }
2494 }
2495
2496 /// Get this image's ID
2497 pub fn id(&self) -> u64 {
2498 self.id
2499 }
2500
2501 /// Use the GPUI `use_asset` API to make this image renderable
2502 pub fn use_render_image(
2503 self: Arc<Self>,
2504 window: &mut Window,
2505 cx: &mut App,
2506 ) -> Option<Arc<RenderImage>> {
2507 ImageSource::Image(self)
2508 .use_data(None, window, cx)
2509 .and_then(|result| result.ok())
2510 }
2511
2512 /// Use the GPUI `get_asset` API to make this image renderable
2513 pub fn get_render_image(
2514 self: Arc<Self>,
2515 window: &mut Window,
2516 cx: &mut App,
2517 ) -> Option<Arc<RenderImage>> {
2518 ImageSource::Image(self)
2519 .get_data(None, window, cx)
2520 .and_then(|result| result.ok())
2521 }
2522
2523 /// Use the GPUI `remove_asset` API to drop this image, if possible.
2524 pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
2525 ImageSource::Image(self).remove_asset(cx);
2526 }
2527
2528 /// Convert the clipboard image to an `ImageData` object.
2529 pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
2530 let frames = match self.format {
2531 ImageFormat::Gif => {
2532 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
2533 let mut frames = SmallVec::new();
2534
2535 for frame in decoder.into_frames() {
2536 match frame {
2537 Ok(mut frame) => {
2538 // Convert from RGBA to BGRA.
2539 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
2540 pixel.swap(0, 2);
2541 }
2542 frames.push(frame);
2543 }
2544 Err(err) => {
2545 log::debug!("Skipping GIF frame due to decode error: {err}");
2546 }
2547 }
2548 }
2549
2550 if frames.is_empty() {
2551 anyhow::bail!("GIF could not be decoded: all frames failed");
2552 }
2553
2554 frames
2555 }
2556 ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
2557 ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
2558 ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
2559 ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
2560 ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
2561 ImageFormat::Ico => decode_static_image(&self.bytes, image::ImageFormat::Ico)?,
2562 ImageFormat::Svg => {
2563 return svg_renderer
2564 .render_single_frame(&self.bytes, 1.0)
2565 .map_err(Into::into);
2566 }
2567 ImageFormat::Pnm => decode_static_image(&self.bytes, image::ImageFormat::Pnm)?,
2568 };
2569
2570 Ok(Arc::new(RenderImage::new(frames)))
2571 }
2572
2573 /// Get the format of the clipboard image
2574 pub fn format(&self) -> ImageFormat {
2575 self.format
2576 }
2577
2578 /// Get the raw bytes of the clipboard image
2579 pub fn bytes(&self) -> &[u8] {
2580 self.bytes.as_slice()
2581 }
2582}
2583
2584/// A clipboard item that should be copied to the clipboard
2585#[derive(Clone, Debug, Eq, PartialEq)]
2586pub struct ClipboardString {
2587 /// The text content.
2588 pub text: String,
2589 /// Optional metadata associated with this clipboard string.
2590 pub metadata: Option<String>,
2591}
2592
2593impl ClipboardString {
2594 /// Create a new clipboard string with the given text
2595 pub fn new(text: String) -> Self {
2596 Self {
2597 text,
2598 metadata: None,
2599 }
2600 }
2601
2602 /// Return a new clipboard item with the metadata replaced by the given metadata,
2603 /// after serializing it as JSON.
2604 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
2605 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
2606 self
2607 }
2608
2609 /// Get the text of the clipboard string
2610 pub fn text(&self) -> &String {
2611 &self.text
2612 }
2613
2614 /// Get the owned text of the clipboard string
2615 pub fn into_text(self) -> String {
2616 self.text
2617 }
2618
2619 /// Get the metadata of the clipboard string, formatted as JSON
2620 pub fn metadata_json<T>(&self) -> Option<T>
2621 where
2622 T: for<'a> Deserialize<'a>,
2623 {
2624 self.metadata
2625 .as_ref()
2626 .and_then(|m| serde_json::from_str(m).ok())
2627 }
2628
2629 #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
2630 /// Compute a hash of the given text for clipboard change detection.
2631 pub fn text_hash(text: &str) -> u64 {
2632 let mut hasher = SeaHasher::new();
2633 text.hash(&mut hasher);
2634 hasher.finish()
2635 }
2636}
2637
2638impl From<String> for ClipboardString {
2639 fn from(value: String) -> Self {
2640 Self {
2641 text: value,
2642 metadata: None,
2643 }
2644 }
2645}
2646
2647#[cfg(test)]
2648mod image_tests {
2649 use super::*;
2650 use std::sync::Arc;
2651
2652 #[test]
2653 fn test_image_to_image_data_applies_exif_orientation() {
2654 let image = Image::from_bytes(
2655 ImageFormat::Jpeg,
2656 include_bytes!("../examples/image/exif-orientation-rotate-180.jpg").to_vec(),
2657 );
2658
2659 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
2660
2661 assert_eq!(render_image.size(0), size(16.into(), 32.into()));
2662
2663 let bytes = render_image.as_bytes(0).unwrap();
2664 assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
2665 assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
2666 }
2667
2668 #[test]
2669 fn test_svg_image_to_image_data_converts_to_bgra() {
2670 let image = Image::from_bytes(
2671 ImageFormat::Svg,
2672 br##"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">
2673<rect width="1" height="1" fill="#38BDF8"/>
2674</svg>"##
2675 .to_vec(),
2676 );
2677
2678 let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
2679 let bytes = render_image.as_bytes(0).unwrap();
2680
2681 for pixel in bytes.chunks_exact(4) {
2682 assert_eq!(pixel, &[0xF8, 0xBD, 0x38, 0xFF]);
2683 }
2684 }
2685}
2686
2687#[cfg(all(test, any(target_os = "linux", target_os = "freebsd")))]
2688mod tests {
2689 use super::*;
2690 use std::collections::HashSet;
2691
2692 #[test]
2693 fn test_window_button_layout_parse_standard() {
2694 let layout = WindowButtonLayout::parse("close,minimize:maximize").unwrap();
2695 assert_eq!(
2696 layout.left,
2697 [
2698 Some(WindowButton::Close),
2699 Some(WindowButton::Minimize),
2700 None
2701 ]
2702 );
2703 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2704 }
2705
2706 #[test]
2707 fn test_window_button_layout_parse_right_only() {
2708 let layout = WindowButtonLayout::parse("minimize,maximize,close").unwrap();
2709 assert_eq!(layout.left, [None, None, None]);
2710 assert_eq!(
2711 layout.right,
2712 [
2713 Some(WindowButton::Minimize),
2714 Some(WindowButton::Maximize),
2715 Some(WindowButton::Close)
2716 ]
2717 );
2718 }
2719
2720 #[test]
2721 fn test_window_button_layout_parse_left_only() {
2722 let layout = WindowButtonLayout::parse("close,minimize,maximize:").unwrap();
2723 assert_eq!(
2724 layout.left,
2725 [
2726 Some(WindowButton::Close),
2727 Some(WindowButton::Minimize),
2728 Some(WindowButton::Maximize)
2729 ]
2730 );
2731 assert_eq!(layout.right, [None, None, None]);
2732 }
2733
2734 #[test]
2735 fn test_window_button_layout_parse_with_whitespace() {
2736 let layout = WindowButtonLayout::parse(" close , minimize : maximize ").unwrap();
2737 assert_eq!(
2738 layout.left,
2739 [
2740 Some(WindowButton::Close),
2741 Some(WindowButton::Minimize),
2742 None
2743 ]
2744 );
2745 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2746 }
2747
2748 #[test]
2749 fn test_window_button_layout_parse_empty() {
2750 let layout = WindowButtonLayout::parse("").unwrap();
2751 assert_eq!(layout.left, [None, None, None]);
2752 assert_eq!(layout.right, [None, None, None]);
2753 }
2754
2755 #[test]
2756 fn test_window_button_layout_parse_intentionally_empty() {
2757 let layout = WindowButtonLayout::parse(":").unwrap();
2758 assert_eq!(layout.left, [None, None, None]);
2759 assert_eq!(layout.right, [None, None, None]);
2760 }
2761
2762 #[test]
2763 fn test_window_button_layout_parse_invalid_buttons() {
2764 let layout = WindowButtonLayout::parse("close,invalid,minimize:maximize,foo").unwrap();
2765 assert_eq!(
2766 layout.left,
2767 [
2768 Some(WindowButton::Close),
2769 Some(WindowButton::Minimize),
2770 None
2771 ]
2772 );
2773 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2774 }
2775
2776 #[test]
2777 fn test_window_button_layout_parse_deduplicates_same_side_buttons() {
2778 let layout = WindowButtonLayout::parse("close,close,minimize").unwrap();
2779 assert_eq!(
2780 layout.right,
2781 [
2782 Some(WindowButton::Close),
2783 Some(WindowButton::Minimize),
2784 None
2785 ]
2786 );
2787 assert_eq!(layout.format(), ":close,minimize");
2788 }
2789
2790 #[test]
2791 fn test_window_button_layout_parse_deduplicates_buttons_across_sides() {
2792 let layout = WindowButtonLayout::parse("close:maximize,close,minimize").unwrap();
2793 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
2794 assert_eq!(
2795 layout.right,
2796 [
2797 Some(WindowButton::Maximize),
2798 Some(WindowButton::Minimize),
2799 None
2800 ]
2801 );
2802
2803 let button_ids: Vec<_> = layout
2804 .left
2805 .iter()
2806 .chain(layout.right.iter())
2807 .flatten()
2808 .map(WindowButton::id)
2809 .collect();
2810 let unique_button_ids = button_ids.iter().copied().collect::<HashSet<_>>();
2811 assert_eq!(unique_button_ids.len(), button_ids.len());
2812 assert_eq!(layout.format(), "close:maximize,minimize");
2813 }
2814
2815 #[test]
2816 fn test_window_button_layout_parse_gnome_style() {
2817 let layout = WindowButtonLayout::parse("close").unwrap();
2818 assert_eq!(layout.left, [None, None, None]);
2819 assert_eq!(layout.right, [Some(WindowButton::Close), None, None]);
2820 }
2821
2822 #[test]
2823 fn test_window_button_layout_parse_elementary_style() {
2824 let layout = WindowButtonLayout::parse("close:maximize").unwrap();
2825 assert_eq!(layout.left, [Some(WindowButton::Close), None, None]);
2826 assert_eq!(layout.right, [Some(WindowButton::Maximize), None, None]);
2827 }
2828
2829 #[test]
2830 fn test_window_button_layout_round_trip() {
2831 let cases = [
2832 "close:minimize,maximize",
2833 "minimize,maximize,close:",
2834 ":close",
2835 "close:",
2836 "close:maximize",
2837 ":",
2838 ];
2839
2840 for case in cases {
2841 let layout = WindowButtonLayout::parse(case).unwrap();
2842 assert_eq!(layout.format(), case, "Round-trip failed for: {}", case);
2843 }
2844 }
2845
2846 #[test]
2847 fn test_window_button_layout_linux_default() {
2848 let layout = WindowButtonLayout::linux_default();
2849 assert_eq!(layout.left, [None, None, None]);
2850 assert_eq!(
2851 layout.right,
2852 [
2853 Some(WindowButton::Minimize),
2854 Some(WindowButton::Maximize),
2855 Some(WindowButton::Close)
2856 ]
2857 );
2858
2859 let round_tripped = WindowButtonLayout::parse(&layout.format()).unwrap();
2860 assert_eq!(round_tripped, layout);
2861 }
2862
2863 #[test]
2864 fn test_window_button_layout_parse_all_invalid() {
2865 assert!(WindowButtonLayout::parse("asdfghjkl").is_err());
2866 }
2867}
2868