mod app_menu;
mod keyboard;
mod keystroke;
#[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "wayland"))]
pub mod layer_shell;
pub mod single_instance;
pub mod window_positioner;
#[cfg(all(
feature = "screen-capture",
any(target_os = "linux", target_os = "freebsd")
))]
type PlatformScreenCaptureFrame = scap::frame::Frame;
#[cfg(all(
any(target_os = "linux", target_os = "freebsd"),
not(feature = "screen-capture")
))]
type PlatformScreenCaptureFrame = ();
#[cfg(target_os = "macos")]
type PlatformScreenCaptureFrame = core_video::image_buffer::CVImageBuffer;
#[cfg(all(target_os = "windows", feature = "screen-capture"))]
type PlatformScreenCaptureFrame = scap::frame::Frame;
#[cfg(all(target_os = "windows", not(feature = "screen-capture")))]
type PlatformScreenCaptureFrame = ();
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
#[allow(missing_docs)]
pub mod render_image;
#[cfg(any(test, feature = "test-support"))]
mod test;
#[cfg(any(test, feature = "test-support"))]
mod threaded_dispatcher;
#[cfg(all(
feature = "screen-capture",
any(
target_os = "windows",
all(
any(target_os = "linux", target_os = "freebsd"),
any(feature = "wayland", feature = "x11"),
)
)
))]
#[doc(hidden)]
pub mod scap_screen_capture;
use crate::{
Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun,
ForegroundExecutor, GlyphId, GpuResourceBudget, GpuSpecs, Hsla, ImageSource, Keymap,
LineLayout, MissingGlyphSink, Pixels, PlatformInput, Point, QuitMode, RenderGlyphParams,
RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString,
Size, SvgRenderer, SystemWindowTab, Task, TaskLabel, Window, WindowControlArea, hash, point,
px, size,
};
use anyhow::{Context as _, Result};
use async_task::Runnable;
use futures::channel::oneshot;
#[cfg(feature = "image-format-gif")]
use image::AnimationDecoder as _;
#[cfg(feature = "image-format-gif")]
use image::codecs::gif::GifDecoder;
use image::{DynamicImage, Frame};
use parking::Unparker;
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use schemars::JsonSchema;
use seahash::SeaHasher;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::borrow::Cow;
use std::hash::{Hash, Hasher};
use std::io::Cursor;
use std::ops;
use std::time::{Duration, Instant};
use std::{
ffi::OsString,
fmt::{self, Debug},
ops::Range,
path::{Path, PathBuf},
rc::Rc,
sync::Arc,
};
use strum::EnumIter;
use uuid::Uuid;
pub use app_menu::*;
pub use keyboard::*;
pub use keystroke::*;
pub use semantic_version::SemanticVersion;
#[cfg(any(test, feature = "test-support"))]
pub(crate) use test::*;
pub struct ActivityGuard {
_release: util::Deferred<Box<dyn FnOnce() + Send>>,
}
impl std::fmt::Debug for ActivityGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ActivityGuard").finish_non_exhaustive()
}
}
impl ActivityGuard {
pub fn new(release: impl FnOnce() + Send + 'static) -> Self {
Self {
_release: util::defer(Box::new(release)),
}
}
pub fn noop() -> Self {
Self::new(|| {})
}
}
#[cfg(any(test, feature = "test-support"))]
pub use test::{
TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream, VisualRenderArtifact,
};
#[cfg(any(test, feature = "test-support"))]
pub use threaded_dispatcher::ThreadedDispatcher;
#[cfg(all(
any(test, feature = "test-support"),
any(
target_os = "macos",
target_os = "linux",
target_os = "freebsd",
target_os = "windows"
)
))]
#[doc(hidden)]
pub use test::VisualTestPlatform;
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
#[inline]
pub fn guess_compositor() -> &'static str {
if std::env::var_os("ZED_HEADLESS").is_some() {
return "Headless";
}
#[cfg(feature = "wayland")]
let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
#[cfg(not(feature = "wayland"))]
let wayland_display: Option<std::ffi::OsString> = None;
#[cfg(feature = "x11")]
let x11_display = std::env::var_os("DISPLAY");
#[cfg(not(feature = "x11"))]
let x11_display: Option<std::ffi::OsString> = None;
let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
if use_wayland {
"Wayland"
} else if use_x11 {
"X11"
} else {
"Headless"
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RendererCacheStats {
pub idle_gpu_buffers: usize,
pub gpu_buffer_size_bytes: usize,
}
impl RendererCacheStats {
#[doc(hidden)]
pub fn new(idle_gpu_buffers: usize, gpu_buffer_size_bytes: usize) -> Self {
Self {
idle_gpu_buffers,
gpu_buffer_size_bytes,
}
}
}
#[allow(missing_docs)]
pub trait Platform: 'static {
fn background_executor(&self) -> BackgroundExecutor;
fn foreground_executor(&self) -> ForegroundExecutor;
fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
fn quit(&self);
fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
fn activate(&self, ignoring_other_apps: bool);
fn hide(&self);
fn hide_other_apps(&self);
fn unhide_other_apps(&self);
fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
fn active_window(&self) -> Option<AnyWindowHandle>;
fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
None
}
#[cfg(feature = "screen-capture")]
fn is_screen_capture_supported(&self) -> bool;
#[cfg(not(feature = "screen-capture"))]
fn is_screen_capture_supported(&self) -> bool {
false
}
#[cfg(feature = "screen-capture")]
fn screen_capture_sources(&self)
-> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>>;
#[cfg(not(feature = "screen-capture"))]
fn screen_capture_sources(
&self,
) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
let (sources_tx, sources_rx) = oneshot::channel();
sources_tx
.send(Err(anyhow::anyhow!(
"gpui was compiled without the screen-capture feature"
)))
.ok();
sources_rx
}
fn open_window(
&self,
handle: AnyWindowHandle,
options: WindowParams,
) -> anyhow::Result<Box<dyn PlatformWindow>>;
fn trim_renderer_caches(&self) {}
fn configure_gpu_resources(&self, _gpu: &GpuResourceBudget) {}
fn renderer_cache_stats(&self) -> RendererCacheStats {
RendererCacheStats::default()
}
fn window_appearance(&self) -> WindowAppearance;
fn set_window_appearance(&self, _appearance: Option<WindowAppearance>) {}
fn open_url(&self, url: &str);
fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
fn prompt_for_paths(
&self,
options: PathPromptOptions,
) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
fn prompt_for_new_path(
&self,
directory: &Path,
suggested_name: Option<&str>,
) -> oneshot::Receiver<Result<Option<PathBuf>>>;
fn can_select_mixed_files_and_dirs(&self) -> bool;
fn reveal_path(&self, path: &Path);
fn open_with_system(&self, path: &Path);
fn on_quit(&self, callback: Box<dyn FnMut() -> bool>);
fn on_reopen(&self, callback: Box<dyn FnMut()>);
fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
None
}
fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
fn perform_dock_menu_action(&self, _action: usize) {}
fn add_recent_document(&self, _path: &Path) {}
fn update_jump_list(
&self,
_menus: Vec<MenuItem>,
_entries: Vec<SmallVec<[PathBuf; 2]>>,
) -> Vec<SmallVec<[PathBuf; 2]>> {
Vec::new()
}
fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
fn thermal_state(&self) -> ThermalState {
ThermalState::Nominal
}
fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>>;
fn compositor_name(&self) -> &'static str {
""
}
fn app_path(&self) -> Result<PathBuf>;
fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
fn set_cursor_style(&self, style: CursorStyle);
fn should_auto_hide_scrollbars(&self) -> bool;
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
fn write_to_primary(&self, item: ClipboardItem);
fn write_to_clipboard(&self, item: ClipboardItem);
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
fn read_from_primary(&self) -> Option<ClipboardItem>;
fn read_from_clipboard(&self) -> Option<ClipboardItem>;
fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
fn set_tray_icon(&self, _icon: Option<&[u8]>) {}
fn set_tray_icon_rendering_mode(&self, _rendering_mode: TrayIconRenderingMode) {}
fn set_tray_menu(&self, _menu: Vec<TrayMenuItem>) {}
fn set_tray_tooltip(&self, _tooltip: &str) {}
fn set_tray_panel_mode(&self, _enabled: bool) {}
fn get_tray_icon_anchor(&self) -> Option<TrayAnchor> {
None
}
fn get_tray_icon_bounds(&self) -> Option<Bounds<Pixels>> {
None
}
fn on_tray_icon_event(&self, mut callback: Box<dyn FnMut(TrayIconEvent)>) {
self.on_tray_icon_click_event(Box::new(move |event| callback(event.kind)));
}
fn on_tray_icon_click_event(&self, _callback: Box<dyn FnMut(TrayIconClickEvent)>) {}
fn on_tray_menu_action(&self, _callback: Box<dyn FnMut(SharedString)>) {}
fn register_global_hotkey(&self, _id: u32, _keystroke: &Keystroke) -> Result<()> {
Err(anyhow::anyhow!(
"Global hotkeys not supported on this platform"
))
}
fn unregister_global_hotkey(&self, _id: u32) {}
fn on_global_hotkey(&self, _callback: Box<dyn FnMut(u32)>) {}
fn focused_window_info(&self) -> Option<FocusedWindowInfo> {
None
}
fn accessibility_status(&self) -> PermissionStatus {
PermissionStatus::Unavailable
}
fn request_accessibility_permission(&self) -> PermissionRequestStatus {
PermissionRequestStatus::Unavailable
}
fn microphone_status(&self) -> PermissionStatus {
PermissionStatus::Unavailable
}
fn request_microphone_permission(
&self,
callback: Box<dyn FnOnce(bool)>,
) -> PermissionRequestStatus {
callback(false);
PermissionRequestStatus::Unavailable
}
fn set_auto_launch(&self, _app_id: &str, _enabled: bool) -> Result<()> {
Err(anyhow::anyhow!(
"Auto-launch not supported on this platform"
))
}
fn is_auto_launch_enabled(&self, _app_id: &str) -> bool {
false
}
fn show_notification(&self, _title: &str, _body: &str) -> Result<()> {
Err(anyhow::anyhow!(
"Notifications not supported on this platform"
))
}
fn set_quit_mode(&self, _mode: QuitMode) {}
fn on_system_power_event(&self, _callback: Box<dyn FnMut(SystemPowerEvent)>) {}
fn start_power_save_blocker(&self, _kind: PowerSaveBlockerKind) -> Option<u32> {
None
}
fn stop_power_save_blocker(&self, _id: u32) {}
fn system_idle_time(&self) -> Option<Duration> {
None
}
fn network_status(&self) -> NetworkStatus {
NetworkStatus::Online
}
fn on_network_status_change(&self, _callback: Box<dyn FnMut(NetworkStatus)>) {}
fn on_media_key_event(&self, _callback: Box<dyn FnMut(MediaKeyEvent)>) {}
fn request_user_attention(&self, _attention_type: AttentionType) {}
fn cancel_user_attention(&self) {}
fn set_dock_badge(&self, _label: Option<&str>) {}
fn show_context_menu(
&self,
_position: Point<Pixels>,
_items: Vec<TrayMenuItem>,
_callback: Box<dyn FnMut(SharedString)>,
) {
}
fn show_dialog(&self, _options: DialogOptions) -> oneshot::Receiver<usize> {
let (tx, rx) = oneshot::channel();
tx.send(0).ok();
rx
}
fn os_info(&self) -> OsInfo {
OsInfo {
name: std::env::consts::OS.into(),
arch: std::env::consts::ARCH.into(),
version: String::new().into(),
locale: String::new().into(),
hostname: String::new().into(),
}
}
fn biometric_status(&self) -> BiometricStatus {
BiometricStatus::Unavailable
}
fn authenticate_biometric(&self, _reason: &str, callback: Box<dyn FnOnce(bool) + Send>) {
callback(false);
}
}
pub trait PlatformDisplay: Send + Sync + Debug {
fn id(&self) -> DisplayId;
fn uuid(&self) -> Result<Uuid>;
fn bounds(&self) -> Bounds<Pixels>;
fn visible_bounds(&self) -> Bounds<Pixels> {
self.bounds()
}
fn default_bounds(&self) -> Bounds<Pixels> {
let bounds = self.visible_bounds();
let center = bounds.center();
let window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
let offset = window_size / 2.0;
let origin = point(center.x - offset.width, center.y - offset.height);
Bounds::new(origin, window_size)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThermalState {
Nominal,
Fair,
Serious,
Critical,
}
#[derive(Clone)]
pub struct SourceMetadata {
pub id: u64,
pub label: Option<SharedString>,
pub is_main: Option<bool>,
pub resolution: Size<DevicePixels>,
}
pub trait ScreenCaptureSource {
fn metadata(&self) -> Result<SourceMetadata>;
fn stream(
&self,
foreground_executor: &ForegroundExecutor,
frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
fn stream_with_termination(
&self,
_foreground_executor: &ForegroundExecutor,
_frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
_termination_callback: ScreenCaptureTerminationCallback,
) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>> {
let (mut sender, receiver) = oneshot::channel();
sender
.send(Err(anyhow::anyhow!(
"runtime termination notification is not supported by this screen capture source"
)))
.ok();
receiver
}
}
pub type ScreenCaptureTerminationCallback = Box<dyn FnOnce(ScreenCaptureStreamTermination) + Send>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScreenCaptureStreamTermination {
Ended,
Cancelled,
Failed(SharedString),
}
pub trait ScreenCaptureStream {
fn metadata(&self) -> Result<SourceMetadata>;
}
pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
#[derive(PartialEq, Eq, Hash, Copy, Clone)]
pub struct DisplayId(pub(crate) u64);
impl DisplayId {
#[doc(hidden)]
pub fn new(id: u64) -> Self {
Self(id)
}
#[doc(hidden)]
pub fn index(self) -> usize {
self.0 as usize
}
}
impl From<u32> for DisplayId {
fn from(id: u32) -> Self {
Self(u64::from(id))
}
}
impl From<DisplayId> for u32 {
fn from(id: DisplayId) -> Self {
id.0 as u32
}
}
impl From<DisplayId> for u64 {
fn from(id: DisplayId) -> Self {
id.0
}
}
impl Debug for DisplayId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "DisplayId({})", self.0)
}
}
unsafe impl Send for DisplayId {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResizeEdge {
Top,
TopRight,
Right,
BottomRight,
Bottom,
BottomLeft,
Left,
TopLeft,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
pub enum WindowDecorations {
#[default]
Server,
Client,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
pub enum Decorations {
#[default]
Server,
Client {
tiling: Tiling,
},
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct WindowControls {
pub fullscreen: bool,
pub maximize: bool,
pub minimize: bool,
pub window_menu: bool,
}
impl Default for WindowControls {
fn default() -> Self {
Self {
fullscreen: true,
maximize: true,
minimize: true,
window_menu: true,
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
pub struct Tiling {
pub top: bool,
pub left: bool,
pub right: bool,
pub bottom: bool,
}
impl Tiling {
pub fn tiled() -> Self {
Self {
top: true,
left: true,
right: true,
bottom: true,
}
}
pub fn is_tiled(&self) -> bool {
self.top || self.left || self.right || self.bottom
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
#[allow(missing_docs)]
pub struct RequestFrameOptions {
pub require_presentation: bool,
pub force_render: bool,
}
pub struct A11yCallbacks {
pub activation: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
pub action: Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>,
pub deactivation: Box<dyn Fn() + Send + 'static>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowVisibility {
Visible,
Hidden,
}
impl WindowVisibility {
pub fn is_visible(self) -> bool {
self == Self::Visible
}
}
#[allow(missing_docs)]
pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
fn bounds(&self) -> Bounds<Pixels>;
fn is_maximized(&self) -> bool;
fn window_bounds(&self) -> WindowBounds;
fn content_size(&self) -> Size<Pixels>;
fn resize(&mut self, size: Size<Pixels>);
fn scale_factor(&self) -> f32;
fn appearance(&self) -> WindowAppearance;
fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
fn mouse_position(&self) -> Point<Pixels>;
fn modifiers(&self) -> Modifiers;
fn capslock(&self) -> Capslock;
fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
fn prompt(
&self,
level: PromptLevel,
msg: &str,
detail: Option<&str>,
answers: &[PromptButton],
) -> Option<oneshot::Receiver<usize>>;
fn activate(&self);
fn request_attention(&self) {}
fn is_active(&self) -> bool;
fn visibility(&self) -> WindowVisibility;
fn is_hovered(&self) -> bool;
fn set_title(&mut self, title: &str);
fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
fn minimize(&self);
fn zoom(&self);
fn toggle_fullscreen(&self);
fn is_fullscreen(&self) -> bool;
fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>);
fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
fn on_moved(&self, callback: Box<dyn FnMut()>);
fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
fn on_close(&self, callback: Box<dyn FnOnce()>);
fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
fn draw(&self, scene: &Scene);
#[cfg(any(test, feature = "test-support"))]
fn render_to_image(&self, _scene: &Scene) -> anyhow::Result<image::RgbaImage> {
anyhow::bail!("render_to_image not implemented for this platform")
}
fn schedule_frame(&self) {}
fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
fn get_title(&self) -> String {
String::new()
}
fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
None
}
fn tab_bar_visible(&self) -> bool {
false
}
fn set_edited(&mut self, _edited: bool) {}
fn toggle_simple_fullscreen(&self) {}
fn is_simple_fullscreen(&self) -> bool {
false
}
fn show_character_palette(&self) {}
fn titlebar_double_click(&self) {}
fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
fn merge_all_windows(&self) {}
fn move_tab_to_new_window(&self) {}
fn toggle_window_tab_overview(&self) {}
fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
fn native_window_state(&self) -> Option<Vec<u8>> {
None
}
fn restore_native_window_state(&self, _state: &[u8]) {}
#[cfg(target_os = "windows")]
fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND;
fn inner_window_bounds(&self) -> WindowBounds {
self.window_bounds()
}
fn request_decorations(&self, _decorations: WindowDecorations) {}
fn show_window_menu(&self, _position: Point<Pixels>) {}
fn start_window_move(&self) {}
fn start_window_resize(&self, _edge: ResizeEdge) {}
fn set_exclusive_zone(&self, _zone: Pixels) {}
#[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "wayland"))]
fn set_exclusive_edge(&self, _edge: layer_shell::Anchor) {}
fn set_input_region(&self, _region: Option<&[Bounds<Pixels>]>) {}
fn window_decorations(&self) -> Decorations {
Decorations::Server
}
fn set_app_id(&mut self, _app_id: &str) {}
fn map_window(&mut self) -> anyhow::Result<()> {
Ok(())
}
fn window_controls(&self) -> WindowControls {
WindowControls::default()
}
fn set_client_inset(&self, _inset: Pixels) {}
fn gpu_specs(&self) -> Option<GpuSpecs>;
fn update_ime_position(&self, _bounds: Bounds<Pixels>);
fn play_system_bell(&self) {}
fn a11y_init(&self, _callbacks: A11yCallbacks) {}
fn a11y_tree_update(&self, _tree_update: accesskit::TreeUpdate) {}
fn a11y_update_window_bounds(&self) {}
fn show(&self) {}
fn hide(&self) {}
fn is_visible(&self) -> bool {
true
}
fn set_mouse_passthrough(&self, _passthrough: bool) {}
fn set_progress_bar(&self, _state: ProgressBarState) {}
#[allow(dead_code)]
fn set_window_icon(&self, _icon: Option<image::RgbaImage>) {}
fn set_cursor_style(&self, _style: CursorStyle) {}
#[cfg(any(test, feature = "test-support"))]
fn as_test(&mut self) -> Option<&mut TestWindow> {
None
}
}
#[doc(hidden)]
pub trait PlatformDispatcher: Send + Sync {
fn is_main_thread(&self) -> bool;
fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
fn dispatch_on_main_thread(&self, runnable: Runnable);
fn dispatch_after(&self, duration: Duration, runnable: Runnable);
fn park(&self, timeout: Option<Duration>) -> bool;
fn unparker(&self) -> Unparker;
fn now(&self) -> Instant {
Instant::now()
}
fn prevent_app_nap(&self, _reason: &str) -> ActivityGuard {
ActivityGuard::noop()
}
#[cfg(any(test, feature = "test-support"))]
fn as_test(&self) -> Option<&TestDispatcher> {
None
}
#[cfg(any(test, feature = "test-support"))]
fn as_threaded(&self) -> Option<&ThreadedDispatcher> {
None
}
}
#[allow(missing_docs)]
pub trait PlatformTextSystem: Send + Sync {
fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
fn all_font_names(&self) -> Vec<String>;
fn font_id(&self, descriptor: &Font) -> Result<FontId>;
fn clear_glyph_raster_cache(&self) {}
fn prewarm_fonts(&self, _font_ids: &[FontId]) {}
fn font_metrics(&self, font_id: FontId) -> FontMetrics;
fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
fn rasterize_glyph(
&self,
params: &RenderGlyphParams,
raster_bounds: Bounds<DevicePixels>,
) -> Result<(Size<DevicePixels>, Vec<u8>)>;
fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
fn set_missing_glyph_sink(&self, _sink: Arc<dyn MissingGlyphSink>) {}
fn glyph_dilation_for_color(&self, _color: Hsla) -> u8 {
0
}
}
#[allow(missing_docs)]
pub struct NoopTextSystem;
#[allow(missing_docs)]
impl NoopTextSystem {
#[allow(dead_code)]
pub fn new() -> Self {
Self
}
}
impl PlatformTextSystem for NoopTextSystem {
fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
Ok(())
}
fn all_font_names(&self) -> Vec<String> {
Vec::new()
}
fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
Ok(FontId(1))
}
fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
FontMetrics {
units_per_em: 1000,
ascent: 1025.0,
descent: -275.0,
line_gap: 0.0,
underline_position: -95.0,
underline_thickness: 60.0,
cap_height: 698.0,
x_height: 516.0,
bounding_box: Bounds {
origin: Point {
x: -260.0,
y: -245.0,
},
size: Size {
width: 1501.0,
height: 1364.0,
},
},
}
}
fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
Ok(Bounds {
origin: Point { x: 54.0, y: 0.0 },
size: size(392.0, 528.0),
})
}
fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
Ok(size(600.0 * glyph_id.0 as f32, 0.0))
}
fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
Some(GlyphId(ch.len_utf16() as u32))
}
fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
Ok(Default::default())
}
fn rasterize_glyph(
&self,
_params: &RenderGlyphParams,
raster_bounds: Bounds<DevicePixels>,
) -> Result<(Size<DevicePixels>, Vec<u8>)> {
Ok((raster_bounds.size, Vec::new()))
}
fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
let mut position = px(0.);
let metrics = self.font_metrics(FontId(0));
let em_width = font_size
* self
.advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
.unwrap()
.width
/ metrics.units_per_em as f32;
let mut glyphs = Vec::new();
for (ix, c) in text.char_indices() {
if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
glyphs.push(ShapedGlyph {
id: glyph,
position: point(position, px(0.)),
index: ix,
is_emoji: glyph.0 == 2,
});
if glyph.0 == 2 {
position += em_width * 2.0;
} else {
position += em_width;
}
} else {
position += em_width
}
}
let mut runs = Vec::default();
if !glyphs.is_empty() {
runs.push(ShapedRun {
font_id: FontId(0),
glyphs,
});
} else {
position = px(0.);
}
LineLayout {
font_size,
width: position,
ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
descent: font_size * (metrics.descent / metrics.units_per_em as f32),
runs,
len: text.len(),
}
}
}
#[derive(PartialEq, Eq, Hash, Clone)]
#[allow(missing_docs)]
pub enum AtlasKey {
Glyph(RenderGlyphParams),
Svg(RenderSvgParams),
Image(RenderImageParams),
}
#[allow(missing_docs)]
impl AtlasKey {
#[cfg_attr(
all(
any(target_os = "linux", target_os = "freebsd"),
not(any(feature = "x11", feature = "wayland"))
),
allow(dead_code)
)]
pub fn texture_kind(&self) -> AtlasTextureKind {
match self {
AtlasKey::Glyph(params) => {
if params.is_emoji {
AtlasTextureKind::Polychrome
} else {
AtlasTextureKind::Monochrome
}
}
AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
}
}
}
impl From<RenderGlyphParams> for AtlasKey {
fn from(params: RenderGlyphParams) -> Self {
Self::Glyph(params)
}
}
impl From<RenderSvgParams> for AtlasKey {
fn from(params: RenderSvgParams) -> Self {
Self::Svg(params)
}
}
impl From<RenderImageParams> for AtlasKey {
fn from(params: RenderImageParams) -> Self {
Self::Image(params)
}
}
#[allow(missing_docs)]
pub trait PlatformAtlas: Send + Sync {
fn get_or_insert_with<'a>(
&self,
key: &AtlasKey,
build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
) -> Result<Option<AtlasTile>>;
fn remove(&self, key: &AtlasKey);
}
#[doc(hidden)]
pub struct AtlasTextureList<T> {
pub textures: Vec<Option<T>>,
pub free_list: Vec<usize>,
}
impl<T> Default for AtlasTextureList<T> {
fn default() -> Self {
Self {
textures: Vec::default(),
free_list: Vec::default(),
}
}
}
impl<T> ops::Index<usize> for AtlasTextureList<T> {
type Output = Option<T>;
fn index(&self, index: usize) -> &Self::Output {
&self.textures[index]
}
}
#[allow(missing_docs)]
impl<T> AtlasTextureList<T> {
#[allow(unused)]
pub fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
self.free_list.clear();
self.textures.drain(..)
}
#[allow(dead_code)]
pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
self.textures.iter_mut().flatten()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(C)]
#[allow(missing_docs)]
pub struct AtlasTile {
pub texture_id: AtlasTextureId,
pub tile_id: TileId,
pub padding: u32,
pub bounds: Bounds<DevicePixels>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(C)]
#[allow(missing_docs)]
pub struct AtlasTextureId {
pub index: u32,
pub kind: AtlasTextureKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(C)]
#[cfg_attr(
all(
any(target_os = "linux", target_os = "freebsd"),
not(any(feature = "x11", feature = "wayland"))
),
allow(dead_code)
)]
#[allow(missing_docs)]
pub enum AtlasTextureKind {
Monochrome = 0,
Polychrome = 1,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[repr(C)]
#[allow(missing_docs)]
pub struct TileId(pub u32);
impl From<etagere::AllocId> for TileId {
fn from(id: etagere::AllocId) -> Self {
Self(id.serialize())
}
}
impl From<TileId> for etagere::AllocId {
fn from(id: TileId) -> Self {
Self::deserialize(id.0)
}
}
#[allow(missing_docs)]
pub struct PlatformInputHandler {
cx: AsyncWindowContext,
handler: Box<dyn InputHandler>,
}
#[cfg_attr(
all(
any(target_os = "linux", target_os = "freebsd"),
not(any(feature = "x11", feature = "wayland"))
),
allow(dead_code)
)]
#[allow(missing_docs)]
impl PlatformInputHandler {
pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
Self { cx, handler }
}
fn mark_keyboard_input(window: &Window) {
window.input_rate_tracker.borrow_mut().record_input();
window.last_input_was_keyboard.set(true);
}
pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
self.cx
.update(|window, cx| {
self.handler
.selected_text_range(ignore_disabled_input, window, cx)
})
.ok()
.flatten()
}
#[cfg_attr(target_os = "windows", allow(dead_code))]
pub fn marked_text_range(&mut self) -> Option<Range<usize>> {
self.cx
.update(|window, cx| self.handler.marked_text_range(window, cx))
.ok()
.flatten()
}
#[cfg_attr(
any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
allow(dead_code)
)]
pub fn text_for_range(
&mut self,
range_utf16: Range<usize>,
adjusted: &mut Option<Range<usize>>,
) -> Option<String> {
self.cx
.update(|window, cx| {
self.handler
.text_for_range(range_utf16, adjusted, window, cx)
})
.ok()
.flatten()
}
pub fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
self.cx
.update(|window, cx| {
Self::mark_keyboard_input(window);
self.handler
.replace_text_in_range(replacement_range, text, window, cx);
})
.ok();
}
pub fn replace_and_mark_text_in_range(
&mut self,
range_utf16: Option<Range<usize>>,
new_text: &str,
new_selected_range: Option<Range<usize>>,
) {
self.cx
.update(|window, cx| {
Self::mark_keyboard_input(window);
self.handler.replace_and_mark_text_in_range(
range_utf16,
new_text,
new_selected_range,
window,
cx,
)
})
.ok();
}
#[cfg_attr(target_os = "windows", allow(dead_code))]
pub fn unmark_text(&mut self) {
self.cx
.update(|window, cx| {
Self::mark_keyboard_input(window);
self.handler.unmark_text(window, cx)
})
.ok();
}
pub fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
self.cx
.update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
.ok()
.flatten()
}
#[allow(dead_code)]
pub fn apple_press_and_hold_enabled(&mut self) -> bool {
self.handler.apple_press_and_hold_enabled()
}
pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
window.last_input_was_keyboard.set(true);
self.handler.replace_text_in_range(None, input, window, cx);
}
pub fn compute_ime_candidate_bounds(
marked_range: Option<Range<usize>>,
selection: &UTF16Selection,
mut bounds_for_range: impl FnMut(Range<usize>) -> Option<Bounds<Pixels>>,
) -> Option<Bounds<Pixels>> {
if let Some(marked_range) = marked_range {
let mut line_start = marked_range.start;
let caret = selection.range.end;
if let Some(caret_bounds) = bounds_for_range(caret..caret) {
for i in (marked_range.start..caret).rev() {
if let Some(bounds) = bounds_for_range(i..i)
&& (bounds.origin.y - caret_bounds.origin.y).abs() > px(0.1)
{
line_start = i + 1;
break;
}
}
}
bounds_for_range(line_start..line_start)
} else {
let offset = if selection.reversed {
selection.range.start
} else {
selection.range.end
};
bounds_for_range(offset..offset)
}
}
pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
let marked_range = self.handler.marked_text_range(window, cx);
let selection = self.handler.selected_text_range(true, window, cx)?;
Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
self.handler.bounds_for_range(range, window, cx)
})
}
#[allow(dead_code)]
pub fn ime_candidate_bounds(&mut self) -> Option<Bounds<Pixels>> {
let marked_range = self.marked_text_range();
let selection = self.selected_text_range(true)?;
Self::compute_ime_candidate_bounds(marked_range, &selection, |range| {
self.bounds_for_range(range)
})
}
#[allow(unused)]
pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
self.cx
.update(|window, cx| self.handler.character_index_for_point(point, window, cx))
.ok()
.flatten()
}
#[allow(dead_code)]
pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
self.handler.accepts_text_input(window, cx)
}
#[allow(dead_code)]
pub fn query_accepts_text_input(&mut self) -> bool {
self.cx
.update(|window, cx| self.handler.accepts_text_input(window, cx))
.unwrap_or(true)
}
}
#[derive(Debug)]
pub struct UTF16Selection {
pub range: Range<usize>,
pub reversed: bool,
}
pub trait InputHandler: 'static {
fn selected_text_range(
&mut self,
ignore_disabled_input: bool,
window: &mut Window,
cx: &mut App,
) -> Option<UTF16Selection>;
fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
fn text_for_range(
&mut self,
range_utf16: Range<usize>,
adjusted_range: &mut Option<Range<usize>>,
window: &mut Window,
cx: &mut App,
) -> Option<String>;
fn replace_text_in_range(
&mut self,
replacement_range: Option<Range<usize>>,
text: &str,
window: &mut Window,
cx: &mut App,
);
fn replace_and_mark_text_in_range(
&mut self,
range_utf16: Option<Range<usize>>,
new_text: &str,
new_selected_range: Option<Range<usize>>,
window: &mut Window,
cx: &mut App,
);
fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
fn bounds_for_range(
&mut self,
range_utf16: Range<usize>,
window: &mut Window,
cx: &mut App,
) -> Option<Bounds<Pixels>>;
fn character_index_for_point(
&mut self,
point: Point<Pixels>,
window: &mut Window,
cx: &mut App,
) -> Option<usize>;
#[allow(dead_code)]
fn apple_press_and_hold_enabled(&mut self) -> bool {
true
}
fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
true
}
}
#[derive(Debug)]
pub struct WindowOptions {
pub window_bounds: Option<WindowBounds>,
pub titlebar: Option<TitlebarOptions>,
pub focus: bool,
pub show: bool,
pub kind: WindowKind,
pub is_movable: bool,
pub app_owns_titlebar_drag: bool,
pub inactive_frame_interval: Option<Duration>,
pub is_resizable: bool,
pub is_minimizable: bool,
pub display_id: Option<DisplayId>,
pub window_background: WindowBackgroundAppearance,
pub app_id: Option<String>,
pub window_min_size: Option<Size<Pixels>>,
pub window_decorations: Option<WindowDecorations>,
pub tabbing_identifier: Option<String>,
pub mouse_passthrough: bool,
pub icon: Option<image::RgbaImage>,
}
#[derive(Debug)]
#[cfg_attr(
all(
any(target_os = "linux", target_os = "freebsd"),
not(any(feature = "x11", feature = "wayland"))
),
allow(dead_code)
)]
#[allow(missing_docs)]
pub struct WindowParams {
pub bounds: Bounds<Pixels>,
#[cfg_attr(feature = "wayland", allow(dead_code))]
pub titlebar: Option<TitlebarOptions>,
#[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
pub kind: WindowKind,
#[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
pub is_movable: bool,
#[cfg_attr(
any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
allow(dead_code)
)]
pub app_owns_titlebar_drag: bool,
#[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
pub is_resizable: bool,
#[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
pub is_minimizable: bool,
#[cfg_attr(
any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
allow(dead_code)
)]
pub focus: bool,
#[cfg_attr(
any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
allow(dead_code)
)]
pub app_id: Option<String>,
#[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
pub show: bool,
#[cfg_attr(feature = "wayland", allow(dead_code))]
pub display_id: Option<DisplayId>,
pub window_min_size: Option<Size<Pixels>>,
#[cfg(target_os = "macos")]
pub tabbing_identifier: Option<String>,
#[allow(dead_code)]
pub mouse_passthrough: bool,
#[cfg_attr(not(any(target_os = "linux", target_os = "freebsd")), allow(dead_code))]
pub icon: Option<image::RgbaImage>,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum WindowBounds {
Windowed(Bounds<Pixels>),
Maximized(Bounds<Pixels>),
Fullscreen(Bounds<Pixels>),
}
impl Default for WindowBounds {
fn default() -> Self {
WindowBounds::Windowed(Bounds::default())
}
}
impl WindowBounds {
pub fn get_bounds(&self) -> Bounds<Pixels> {
match self {
WindowBounds::Windowed(bounds) => *bounds,
WindowBounds::Maximized(bounds) => *bounds,
WindowBounds::Fullscreen(bounds) => *bounds,
}
}
pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
WindowBounds::Windowed(Bounds::centered(None, size, cx))
}
}
impl Default for WindowOptions {
fn default() -> Self {
Self {
window_bounds: None,
titlebar: Some(TitlebarOptions {
title: Default::default(),
appears_transparent: Default::default(),
traffic_light_position: Default::default(),
}),
focus: true,
show: true,
kind: WindowKind::Normal,
is_movable: true,
app_owns_titlebar_drag: false,
inactive_frame_interval: Some(Duration::from_micros(33_333)),
is_resizable: true,
is_minimizable: true,
display_id: None,
window_background: WindowBackgroundAppearance::default(),
app_id: None,
window_min_size: None,
window_decorations: None,
tabbing_identifier: None,
mouse_passthrough: false,
icon: None,
}
}
}
#[cfg(test)]
mod platform_input_handler_tests {
use super::*;
use crate::{
AppContext, Context, ElementInputHandler, Empty, EntityInputHandler, TestAppContext,
};
struct RejectingEntityInputHandler;
impl EntityInputHandler for RejectingEntityInputHandler {
fn text_for_range(
&mut self,
_range: Range<usize>,
_adjusted_range: &mut Option<Range<usize>>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<String> {
None
}
fn selected_text_range(
&mut self,
_ignore_disabled_input: bool,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<UTF16Selection> {
None
}
fn marked_text_range(
&self,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<Range<usize>> {
None
}
fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
fn replace_text_in_range(
&mut self,
_range: Option<Range<usize>>,
_text: &str,
_window: &mut Window,
_cx: &mut Context<Self>,
) {
}
fn replace_and_mark_text_in_range(
&mut self,
_range: Option<Range<usize>>,
_new_text: &str,
_new_selected_range: Option<Range<usize>>,
_window: &mut Window,
_cx: &mut Context<Self>,
) {
}
fn bounds_for_range(
&mut self,
_range_utf16: Range<usize>,
_element_bounds: Bounds<Pixels>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<Bounds<Pixels>> {
None
}
fn character_index_for_point(
&mut self,
_point: Point<Pixels>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<usize> {
None
}
fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
false
}
}
#[gpui_macros::test]
fn element_input_handler_forwards_text_input_rejection(cx: &mut TestAppContext) {
let entity = cx.new(|_| RejectingEntityInputHandler);
let window = cx.add_window(|_, _| Empty);
cx.update_window(window.into(), |_, window, cx| {
let mut handler = ElementInputHandler::new(Bounds::default(), entity);
assert!(!handler.accepts_text_input(window, cx));
})
.unwrap();
}
#[gpui_macros::test]
fn platform_input_handler_accepts_text_when_window_update_fails(cx: &mut TestAppContext) {
let entity = cx.new(|_| RejectingEntityInputHandler);
let window = cx.add_window(|_, _| Empty);
let window = AnyWindowHandle::from(window);
let async_cx = cx
.update_window(window, |_, window, cx| window.to_async(cx))
.unwrap();
cx.update_window(window, |_, window, _| window.remove_window())
.unwrap();
assert!(cx.update_window(window, |_, _, _| ()).is_err());
let mut handler = PlatformInputHandler::new(
async_cx,
Box::new(ElementInputHandler::new(Bounds::default(), entity)),
);
assert!(handler.query_accepts_text_input());
}
fn bounds_at(offset: usize, y: f32) -> Bounds<Pixels> {
Bounds::new(
point(px(offset as f32 * 10.0), px(y)),
size(px(1.0), px(20.0)),
)
}
#[test]
fn ime_candidate_bounds_uses_selection_endpoint_without_marked_range() {
let selection = UTF16Selection {
range: 3..5,
reversed: false,
};
let mut requests = Vec::new();
let bounds =
PlatformInputHandler::compute_ime_candidate_bounds(None, &selection, |range| {
requests.push(range.clone());
Some(bounds_at(range.start, 0.0))
})
.unwrap();
assert_eq!(bounds.origin.x, px(50.0));
assert_eq!(requests, vec![5..5]);
let selection = UTF16Selection {
range: 3..5,
reversed: true,
};
let bounds =
PlatformInputHandler::compute_ime_candidate_bounds(None, &selection, |range| {
Some(bounds_at(range.start, 0.0))
})
.unwrap();
assert_eq!(bounds.origin.x, px(30.0));
}
#[test]
fn ime_candidate_bounds_anchors_marked_text_to_visual_line_start() {
let selection = UTF16Selection {
range: 15..15,
reversed: false,
};
let mut requests = Vec::new();
let bounds =
PlatformInputHandler::compute_ime_candidate_bounds(Some(10..15), &selection, |range| {
requests.push(range.clone());
let y = if range.start >= 13 { 20.0 } else { 0.0 };
Some(bounds_at(range.start, y))
})
.unwrap();
assert_eq!(bounds.origin.x, px(130.0));
assert_eq!(requests.last(), Some(&(13..13)));
}
}
#[derive(Debug, Default)]
pub struct TitlebarOptions {
pub title: Option<SharedString>,
pub appears_transparent: bool,
pub traffic_light_position: Option<Point<Pixels>>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum WindowKind {
Normal,
PopUp,
Floating,
Overlay,
#[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "wayland"))]
LayerShell(layer_shell::LayerShellOptions),
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum WindowAppearance {
#[default]
Light,
VibrantLight,
Dark,
VibrantDark,
}
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub enum WindowBackgroundAppearance {
#[default]
Opaque,
Transparent,
Blurred,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TrayIconRenderingMode {
#[default]
Adaptive,
Original,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TrayIconEvent {
LeftClick,
RightClick,
DoubleClick,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TrayIconClickEvent {
pub kind: TrayIconEvent,
pub position: Option<Point<Pixels>>,
}
impl TrayIconClickEvent {
pub fn new(kind: TrayIconEvent) -> Self {
Self {
kind,
position: None,
}
}
pub fn with_position(kind: TrayIconEvent, position: Point<Pixels>) -> Self {
Self {
kind,
position: Some(position),
}
}
}
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq)]
pub struct TrayAnchor {
pub display_id: DisplayId,
pub bounds: Bounds<Pixels>,
}
#[derive(Debug, Clone)]
pub enum TrayMenuItem {
Action {
label: SharedString,
id: SharedString,
},
Separator,
Submenu {
label: SharedString,
items: Vec<TrayMenuItem>,
},
Toggle {
label: SharedString,
checked: bool,
id: SharedString,
},
}
#[derive(Debug, Clone)]
pub struct FocusedWindowInfo {
pub app_name: String,
pub window_title: String,
pub bundle_id: Option<String>,
pub pid: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionStatus {
Granted,
Denied,
NotDetermined,
Unavailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionRequestStatus {
Requested,
Unavailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SystemPowerEvent {
Suspend,
Resume,
LockScreen,
UnlockScreen,
Shutdown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PowerSaveBlockerKind {
PreventAppSuspension,
PreventDisplaySleep,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkStatus {
Online,
Offline,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MediaKeyEvent {
Play,
Pause,
PlayPause,
Stop,
NextTrack,
PreviousTrack,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttentionType {
Informational,
Critical,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ProgressBarState {
None,
Indeterminate,
Normal(f64),
Error(f64),
Paused(f64),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DialogKind {
Info,
Warning,
Error,
}
#[derive(Debug, Clone)]
pub struct DialogOptions {
pub kind: DialogKind,
pub title: SharedString,
pub message: SharedString,
pub detail: Option<SharedString>,
pub buttons: Vec<SharedString>,
}
#[derive(Debug, Clone)]
pub struct OsInfo {
pub name: SharedString,
pub version: SharedString,
pub arch: SharedString,
pub locale: SharedString,
pub hostname: SharedString,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BiometricKind {
TouchId,
WindowsHello,
Fingerprint,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BiometricStatus {
Available(BiometricKind),
Unavailable,
}
#[derive(Debug, Clone, PartialEq)]
pub struct WindowState {
pub bounds: WindowBounds,
pub display_id: Option<DisplayId>,
pub fullscreen: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum WindowPosition {
Center,
CenterOnDisplay(DisplayId),
#[deprecated(
since = "0.5.3",
note = "Use `WindowPosition::TrayAnchored(TrayAnchor)` instead; the new variant carries `display_id` and fixes multi-monitor placement. This variant will be removed in a future release."
)]
TrayCenter(Bounds<Pixels>),
TrayAnchored(TrayAnchor),
TopRight {
margin: Pixels,
},
BottomRight {
margin: Pixels,
},
TopLeft {
margin: Pixels,
},
BottomLeft {
margin: Pixels,
},
}
#[derive(Debug, Clone)]
pub struct CrashReport {
pub message: String,
pub backtrace: String,
pub os_info: OsInfo,
pub app_version: Option<String>,
}
#[derive(Clone, Debug)]
pub struct PathPromptOptions {
pub files: bool,
pub directories: bool,
pub multiple: bool,
pub prompt: Option<SharedString>,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PromptLevel {
Info,
Warning,
Critical,
}
#[derive(Clone, Debug, PartialEq)]
pub enum PromptButton {
Ok(SharedString),
Cancel(SharedString),
Other(SharedString),
}
impl PromptButton {
pub fn new(label: impl Into<SharedString>) -> Self {
PromptButton::Other(label.into())
}
pub fn ok(label: impl Into<SharedString>) -> Self {
PromptButton::Ok(label.into())
}
pub fn cancel(label: impl Into<SharedString>) -> Self {
PromptButton::Cancel(label.into())
}
#[allow(dead_code)]
#[doc(hidden)]
pub fn is_cancel(&self) -> bool {
matches!(self, PromptButton::Cancel(_))
}
pub fn label(&self) -> &SharedString {
match self {
PromptButton::Ok(label) => label,
PromptButton::Cancel(label) => label,
PromptButton::Other(label) => label,
}
}
}
impl From<&str> for PromptButton {
fn from(value: &str) -> Self {
match value.to_lowercase().as_str() {
"ok" => PromptButton::Ok("Ok".into()),
"cancel" => PromptButton::Cancel("Cancel".into()),
_ => PromptButton::Other(SharedString::from(value.to_owned())),
}
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum CursorStyle {
#[default]
Arrow,
IBeam,
Crosshair,
ClosedHand,
OpenHand,
PointingHand,
ResizeLeft,
ResizeRight,
ResizeLeftRight,
ResizeUp,
ResizeDown,
ResizeUpDown,
ResizeUpLeftDownRight,
ResizeUpRightDownLeft,
ResizeColumn,
ResizeRow,
IBeamCursorForVerticalLayout,
OperationNotAllowed,
DragLink,
DragCopy,
ContextualMenu,
None,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClipboardItem {
entries: Vec<ClipboardEntry>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClipboardEntry {
String(ClipboardString),
Image(Image),
}
impl ClipboardItem {
pub fn new_string(text: String) -> Self {
Self {
entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
}
}
pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
Self {
entries: vec![ClipboardEntry::String(ClipboardString {
text,
metadata: Some(metadata),
})],
}
}
pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
Self {
entries: vec![ClipboardEntry::String(
ClipboardString::new(text).with_json_metadata(metadata),
)],
}
}
pub fn new_image(image: &Image) -> Self {
Self {
entries: vec![ClipboardEntry::Image(image.clone())],
}
}
pub fn text(&self) -> Option<String> {
let mut answer = String::new();
let mut any_entries = false;
for entry in self.entries.iter() {
if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
answer.push_str(text);
any_entries = true;
}
}
if any_entries { Some(answer) } else { None }
}
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub fn metadata(&self) -> Option<&String> {
match self.entries().first() {
Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
clipboard_string.metadata.as_ref()
}
_ => None,
}
}
pub fn entries(&self) -> &[ClipboardEntry] {
&self.entries
}
pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
self.entries.into_iter()
}
}
impl From<ClipboardString> for ClipboardEntry {
fn from(value: ClipboardString) -> Self {
Self::String(value)
}
}
impl From<String> for ClipboardEntry {
fn from(value: String) -> Self {
Self::from(ClipboardString::from(value))
}
}
impl From<Image> for ClipboardEntry {
fn from(value: Image) -> Self {
Self::Image(value)
}
}
impl From<ClipboardEntry> for ClipboardItem {
fn from(value: ClipboardEntry) -> Self {
Self {
entries: vec![value],
}
}
}
impl From<String> for ClipboardItem {
fn from(value: String) -> Self {
Self::from(ClipboardEntry::from(value))
}
}
impl From<Image> for ClipboardItem {
fn from(value: Image) -> Self {
Self::from(ClipboardEntry::from(value))
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
pub enum ImageFormat {
Png,
Jpeg,
Webp,
Gif,
Svg,
Bmp,
Tiff,
}
impl ImageFormat {
pub const fn mime_type(self) -> &'static str {
match self {
ImageFormat::Png => "image/png",
ImageFormat::Jpeg => "image/jpeg",
ImageFormat::Webp => "image/webp",
ImageFormat::Gif => "image/gif",
ImageFormat::Svg => "image/svg+xml",
ImageFormat::Bmp => "image/bmp",
ImageFormat::Tiff => "image/tiff",
}
}
pub fn from_mime_type(mime_type: &str) -> Option<Self> {
match mime_type {
"image/png" => Some(Self::Png),
"image/jpeg" | "image/jpg" => Some(Self::Jpeg),
"image/webp" => Some(Self::Webp),
"image/gif" => Some(Self::Gif),
"image/svg+xml" => Some(Self::Svg),
"image/bmp" => Some(Self::Bmp),
"image/tiff" | "image/tif" => Some(Self::Tiff),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Image {
pub format: ImageFormat,
pub bytes: Vec<u8>,
id: u64,
}
impl Image {
pub fn new(format: ImageFormat, bytes: Vec<u8>) -> Self {
let id = crate::hash(&bytes);
Self { format, bytes, id }
}
}
impl Hash for Image {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_u64(self.id);
}
}
pub(crate) fn decode_static_image(
bytes: &[u8],
format: image::ImageFormat,
) -> Result<SmallVec<[Frame; 1]>> {
let decoder = image::ImageReader::with_format(Cursor::new(bytes), format)
.into_decoder()
.context("creating image decoder")?;
decode_static_image_from_decoder(decoder)
}
pub(crate) fn decode_static_image_from_decoder(
mut decoder: impl image::ImageDecoder,
) -> Result<SmallVec<[Frame; 1]>> {
let orientation = decoder.orientation().context("reading image orientation")?;
let mut image = DynamicImage::from_decoder(decoder).context("decoding static image")?;
image.apply_orientation(orientation);
let mut data = image.into_rgba8();
for pixel in data.chunks_exact_mut(4) {
pixel.swap(0, 2);
}
Ok(SmallVec::from_elem(Frame::new(data), 1))
}
impl Image {
pub fn empty() -> Self {
Self::from_bytes(ImageFormat::Png, Vec::new())
}
pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
Self {
id: hash(&bytes),
format,
bytes,
}
}
pub fn id(&self) -> u64 {
self.id
}
pub fn use_render_image(
self: Arc<Self>,
window: &mut Window,
cx: &mut App,
) -> Option<Arc<RenderImage>> {
ImageSource::Image(self)
.use_data(None, window, cx)
.and_then(|result| result.ok())
}
pub fn get_render_image(
self: Arc<Self>,
window: &mut Window,
cx: &mut App,
) -> Option<Arc<RenderImage>> {
ImageSource::Image(self)
.get_data(None, window, cx)
.and_then(|result| result.ok())
}
pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
ImageSource::Image(self).remove_asset(cx);
}
pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
let frames = match self.format {
#[cfg(feature = "image-format-gif")]
ImageFormat::Gif => {
let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
let mut frames = SmallVec::new();
for frame in decoder.into_frames() {
let mut frame = frame?;
for pixel in frame.buffer_mut().chunks_exact_mut(4) {
pixel.swap(0, 2);
}
frames.push(frame);
}
frames
}
#[cfg(not(feature = "image-format-gif"))]
ImageFormat::Gif => decode_static_image(&self.bytes, image::ImageFormat::Gif)?,
ImageFormat::Png => decode_static_image(&self.bytes, image::ImageFormat::Png)?,
ImageFormat::Jpeg => decode_static_image(&self.bytes, image::ImageFormat::Jpeg)?,
ImageFormat::Webp => decode_static_image(&self.bytes, image::ImageFormat::WebP)?,
ImageFormat::Bmp => decode_static_image(&self.bytes, image::ImageFormat::Bmp)?,
ImageFormat::Tiff => decode_static_image(&self.bytes, image::ImageFormat::Tiff)?,
ImageFormat::Svg => {
return svg_renderer
.render_single_frame(&self.bytes, 1.0)
.map_err(Into::into);
}
};
Ok(Arc::new(RenderImage::new(frames)))
}
pub fn format(&self) -> ImageFormat {
self.format
}
pub fn bytes(&self) -> &[u8] {
self.bytes.as_slice()
}
}
#[cfg(test)]
mod image_tests {
use super::*;
#[test]
fn image_to_image_data_applies_exif_orientation() {
let image = Image::from_bytes(
ImageFormat::Jpeg,
include_bytes!("../test_data/exif-orientation-rotate-180.jpg").to_vec(),
);
let render_image = image.to_image_data(SvgRenderer::new(Arc::new(()))).unwrap();
assert_eq!(render_image.size(0), size(16.into(), 32.into()));
let bytes = render_image.as_bytes(0).unwrap();
assert_eq!(&bytes[..4], &[255, 255, 255, 255]);
assert_eq!(&bytes[(16 * 32 - 1) * 4..], &[0, 0, 0, 255]);
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClipboardString {
pub(crate) text: String,
pub(crate) metadata: Option<String>,
}
impl ClipboardString {
pub fn new(text: String) -> Self {
Self {
text,
metadata: None,
}
}
#[doc(hidden)]
pub fn with_metadata(mut self, metadata: String) -> Self {
self.metadata = Some(metadata);
self
}
pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
self.metadata = Some(serde_json::to_string(&metadata).unwrap());
self
}
pub fn text(&self) -> &String {
&self.text
}
pub fn into_text(self) -> String {
self.text
}
pub fn metadata_json<T>(&self) -> Option<T>
where
T: for<'a> Deserialize<'a>,
{
self.metadata
.as_ref()
.and_then(|m| serde_json::from_str(m).ok())
}
#[doc(hidden)]
pub fn metadata(&self) -> Option<&str> {
self.metadata.as_deref()
}
#[doc(hidden)]
pub fn text_hash(text: &str) -> u64 {
let mut hasher = SeaHasher::new();
text.hash(&mut hasher);
hasher.finish()
}
}
impl From<String> for ClipboardString {
fn from(value: String) -> Self {
Self {
text: value,
metadata: None,
}
}
}
#[cfg(test)]
mod clipboard_string_tests {
use super::ClipboardString;
#[test]
fn raw_metadata_preserves_the_clipboard_text() {
let clipboard_string = ClipboardString::new("copied text".to_owned())
.with_metadata("application/x-adabraka".to_owned());
assert_eq!(clipboard_string.text(), "copied text");
assert_eq!(clipboard_string.metadata(), Some("application/x-adabraka"));
}
}