1mod keystroke;
2#[cfg(target_os = "macos")]
3mod mac;
4#[cfg(any(test, feature = "test-support"))]
5mod test;
6
7use crate::{
8 AnyWindowHandle, BackgroundExecutor, Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun,
9 ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point,
10 RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size,
11};
12use anyhow::anyhow;
13use async_task::Runnable;
14use futures::channel::oneshot;
15use parking::Unparker;
16use seahash::SeaHasher;
17use serde::{Deserialize, Serialize};
18use std::borrow::Cow;
19use std::hash::{Hash, Hasher};
20use std::time::Duration;
21use std::{
22 any::Any,
23 fmt::{self, Debug, Display},
24 ops::Range,
25 path::{Path, PathBuf},
26 rc::Rc,
27 str::FromStr,
28 sync::Arc,
29};
30
31pub use keystroke::*;
32#[cfg(target_os = "macos")]
33pub use mac::*;
34#[cfg(any(test, feature = "test-support"))]
35pub use test::*;
36pub use time::UtcOffset;
37
38#[cfg(target_os = "macos")]
39pub(crate) fn current_platform() -> Rc<dyn Platform> {
40 Rc::new(MacPlatform::new())
41}
42
43pub(crate) trait Platform: 'static {
44 fn background_executor(&self) -> BackgroundExecutor;
45 fn foreground_executor(&self) -> ForegroundExecutor;
46 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
47
48 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
49 fn quit(&self);
50 fn restart(&self);
51 fn activate(&self, ignoring_other_apps: bool);
52 fn hide(&self);
53 fn hide_other_apps(&self);
54 fn unhide_other_apps(&self);
55
56 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
57 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
58 fn main_window(&self) -> Option<AnyWindowHandle>;
59 fn open_window(
60 &self,
61 handle: AnyWindowHandle,
62 options: WindowOptions,
63 ) -> Box<dyn PlatformWindow>;
64
65 fn set_display_link_output_callback(
66 &self,
67 display_id: DisplayId,
68 callback: Box<dyn FnMut(&VideoTimestamp, &VideoTimestamp)>,
69 );
70 fn start_display_link(&self, display_id: DisplayId);
71 fn stop_display_link(&self, display_id: DisplayId);
72 // fn add_status_item(&self, _handle: AnyWindowHandle) -> Box<dyn PlatformWindow>;
73
74 fn open_url(&self, url: &str);
75 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
76 fn prompt_for_paths(
77 &self,
78 options: PathPromptOptions,
79 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
80 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
81 fn reveal_path(&self, path: &Path);
82
83 fn on_become_active(&self, callback: Box<dyn FnMut()>);
84 fn on_resign_active(&self, callback: Box<dyn FnMut()>);
85 fn on_quit(&self, callback: Box<dyn FnMut()>);
86 fn on_reopen(&self, callback: Box<dyn FnMut()>);
87 fn on_event(&self, callback: Box<dyn FnMut(InputEvent) -> bool>);
88
89 fn os_name(&self) -> &'static str;
90 fn os_version(&self) -> Result<SemanticVersion>;
91 fn app_version(&self) -> Result<SemanticVersion>;
92 fn app_path(&self) -> Result<PathBuf>;
93 fn local_timezone(&self) -> UtcOffset;
94 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
95
96 fn set_cursor_style(&self, style: CursorStyle);
97 fn should_auto_hide_scrollbars(&self) -> bool;
98
99 fn write_to_clipboard(&self, item: ClipboardItem);
100 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
101
102 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()>;
103 fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>>;
104 fn delete_credentials(&self, url: &str) -> Result<()>;
105}
106
107pub trait PlatformDisplay: Send + Sync + Debug {
108 fn id(&self) -> DisplayId;
109 fn as_any(&self) -> &dyn Any;
110 fn bounds(&self) -> Bounds<GlobalPixels>;
111}
112
113#[derive(PartialEq, Eq, Hash, Copy, Clone)]
114pub struct DisplayId(pub(crate) u32);
115
116impl Debug for DisplayId {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 write!(f, "DisplayId({})", self.0)
119 }
120}
121
122unsafe impl Send for DisplayId {}
123
124pub(crate) trait PlatformWindow {
125 fn bounds(&self) -> WindowBounds;
126 fn content_size(&self) -> Size<Pixels>;
127 fn scale_factor(&self) -> f32;
128 fn titlebar_height(&self) -> Pixels;
129 fn appearance(&self) -> WindowAppearance;
130 fn display(&self) -> Rc<dyn PlatformDisplay>;
131 fn mouse_position(&self) -> Point<Pixels>;
132 fn as_any_mut(&mut self) -> &mut dyn Any;
133 fn set_input_handler(&mut self, input_handler: Box<dyn PlatformInputHandler>);
134 fn prompt(
135 &self,
136 level: WindowPromptLevel,
137 msg: &str,
138 answers: &[&str],
139 ) -> oneshot::Receiver<usize>;
140 fn activate(&self);
141 fn set_title(&mut self, title: &str);
142 fn set_edited(&mut self, edited: bool);
143 fn show_character_palette(&self);
144 fn minimize(&self);
145 fn zoom(&self);
146 fn toggle_full_screen(&self);
147 fn on_input(&self, callback: Box<dyn FnMut(InputEvent) -> bool>);
148 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
149 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
150 fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>);
151 fn on_moved(&self, callback: Box<dyn FnMut()>);
152 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
153 fn on_close(&self, callback: Box<dyn FnOnce()>);
154 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
155 fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool;
156 fn draw(&self, scene: Scene);
157
158 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
159}
160
161pub trait PlatformDispatcher: Send + Sync {
162 fn is_main_thread(&self) -> bool;
163 fn dispatch(&self, runnable: Runnable);
164 fn dispatch_on_main_thread(&self, runnable: Runnable);
165 fn dispatch_after(&self, duration: Duration, runnable: Runnable);
166 fn poll(&self, background_only: bool) -> bool;
167 fn park(&self);
168 fn unparker(&self) -> Unparker;
169
170 #[cfg(any(test, feature = "test-support"))]
171 fn as_test(&self) -> Option<&TestDispatcher> {
172 None
173 }
174}
175
176pub trait PlatformTextSystem: Send + Sync {
177 fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()>;
178 fn all_font_families(&self) -> Vec<String>;
179 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
180 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
181 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
182 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
183 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
184 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
185 fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)>;
186 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
187 fn wrap_line(
188 &self,
189 text: &str,
190 font_id: FontId,
191 font_size: Pixels,
192 width: Pixels,
193 ) -> Vec<usize>;
194}
195
196#[derive(Clone, Debug)]
197pub struct AppMetadata {
198 pub os_name: &'static str,
199 pub os_version: Option<SemanticVersion>,
200 pub app_version: Option<SemanticVersion>,
201}
202
203#[derive(PartialEq, Eq, Hash, Clone)]
204pub enum AtlasKey {
205 Glyph(RenderGlyphParams),
206 Svg(RenderSvgParams),
207 Image(RenderImageParams),
208}
209
210impl AtlasKey {
211 pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
212 match self {
213 AtlasKey::Glyph(params) => {
214 if params.is_emoji {
215 AtlasTextureKind::Polychrome
216 } else {
217 AtlasTextureKind::Monochrome
218 }
219 }
220 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
221 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
222 }
223 }
224}
225
226impl From<RenderGlyphParams> for AtlasKey {
227 fn from(params: RenderGlyphParams) -> Self {
228 Self::Glyph(params)
229 }
230}
231
232impl From<RenderSvgParams> for AtlasKey {
233 fn from(params: RenderSvgParams) -> Self {
234 Self::Svg(params)
235 }
236}
237
238impl From<RenderImageParams> for AtlasKey {
239 fn from(params: RenderImageParams) -> Self {
240 Self::Image(params)
241 }
242}
243
244pub trait PlatformAtlas: Send + Sync {
245 fn get_or_insert_with<'a>(
246 &self,
247 key: &AtlasKey,
248 build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Cow<'a, [u8]>)>,
249 ) -> Result<AtlasTile>;
250
251 fn clear(&self);
252}
253
254#[derive(Clone, Debug, PartialEq, Eq)]
255#[repr(C)]
256pub struct AtlasTile {
257 pub(crate) texture_id: AtlasTextureId,
258 pub(crate) tile_id: TileId,
259 pub(crate) bounds: Bounds<DevicePixels>,
260}
261
262#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
263#[repr(C)]
264pub(crate) struct AtlasTextureId {
265 // We use u32 instead of usize for Metal Shader Language compatibility
266 pub(crate) index: u32,
267 pub(crate) kind: AtlasTextureKind,
268}
269
270#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
271#[repr(C)]
272pub(crate) enum AtlasTextureKind {
273 Monochrome = 0,
274 Polychrome = 1,
275 Path = 2,
276}
277
278#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
279#[repr(C)]
280pub(crate) struct TileId(pub(crate) u32);
281
282impl From<etagere::AllocId> for TileId {
283 fn from(id: etagere::AllocId) -> Self {
284 Self(id.serialize())
285 }
286}
287
288impl From<TileId> for etagere::AllocId {
289 fn from(id: TileId) -> Self {
290 Self::deserialize(id.0)
291 }
292}
293
294pub trait PlatformInputHandler {
295 fn selected_text_range(&self) -> Option<Range<usize>>;
296 fn marked_text_range(&self) -> Option<Range<usize>>;
297 fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
298 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
299 fn replace_and_mark_text_in_range(
300 &mut self,
301 range_utf16: Option<Range<usize>>,
302 new_text: &str,
303 new_selected_range: Option<Range<usize>>,
304 );
305 fn unmark_text(&mut self);
306 fn bounds_for_range(&self, range_utf16: Range<usize>) -> Option<Bounds<f32>>;
307}
308
309#[derive(Debug)]
310pub struct WindowOptions {
311 pub bounds: WindowBounds,
312 pub titlebar: Option<TitlebarOptions>,
313 pub center: bool,
314 pub focus: bool,
315 pub show: bool,
316 pub kind: WindowKind,
317 pub is_movable: bool,
318 pub display_id: Option<DisplayId>,
319}
320
321impl Default for WindowOptions {
322 fn default() -> Self {
323 Self {
324 bounds: WindowBounds::default(),
325 titlebar: Some(TitlebarOptions {
326 title: Default::default(),
327 appears_transparent: Default::default(),
328 traffic_light_position: Default::default(),
329 }),
330 center: false,
331 focus: true,
332 show: true,
333 kind: WindowKind::Normal,
334 is_movable: true,
335 display_id: None,
336 }
337 }
338}
339
340#[derive(Debug, Default)]
341pub struct TitlebarOptions {
342 pub title: Option<SharedString>,
343 pub appears_transparent: bool,
344 pub traffic_light_position: Option<Point<Pixels>>,
345}
346
347#[derive(Copy, Clone, Debug)]
348pub enum Appearance {
349 Light,
350 VibrantLight,
351 Dark,
352 VibrantDark,
353}
354
355impl Default for Appearance {
356 fn default() -> Self {
357 Self::Light
358 }
359}
360
361#[derive(Copy, Clone, Debug, PartialEq, Eq)]
362pub enum WindowKind {
363 Normal,
364 PopUp,
365}
366
367#[derive(Copy, Clone, Debug, PartialEq, Default)]
368pub enum WindowBounds {
369 Fullscreen,
370 #[default]
371 Maximized,
372 Fixed(Bounds<GlobalPixels>),
373}
374
375#[derive(Copy, Clone, Debug)]
376pub enum WindowAppearance {
377 Light,
378 VibrantLight,
379 Dark,
380 VibrantDark,
381}
382
383impl Default for WindowAppearance {
384 fn default() -> Self {
385 Self::Light
386 }
387}
388
389#[derive(Copy, Clone, Debug, PartialEq, Default)]
390pub enum WindowPromptLevel {
391 #[default]
392 Info,
393 Warning,
394 Critical,
395}
396
397#[derive(Copy, Clone, Debug)]
398pub struct PathPromptOptions {
399 pub files: bool,
400 pub directories: bool,
401 pub multiple: bool,
402}
403
404#[derive(Copy, Clone, Debug)]
405pub enum PromptLevel {
406 Info,
407 Warning,
408 Critical,
409}
410
411#[derive(Copy, Clone, Debug)]
412pub enum CursorStyle {
413 Arrow,
414 ResizeLeftRight,
415 ResizeUpDown,
416 PointingHand,
417 IBeam,
418}
419
420impl Default for CursorStyle {
421 fn default() -> Self {
422 Self::Arrow
423 }
424}
425
426#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
427pub struct SemanticVersion {
428 major: usize,
429 minor: usize,
430 patch: usize,
431}
432
433impl FromStr for SemanticVersion {
434 type Err = anyhow::Error;
435
436 fn from_str(s: &str) -> Result<Self> {
437 let mut components = s.trim().split('.');
438 let major = components
439 .next()
440 .ok_or_else(|| anyhow!("missing major version number"))?
441 .parse()?;
442 let minor = components
443 .next()
444 .ok_or_else(|| anyhow!("missing minor version number"))?
445 .parse()?;
446 let patch = components
447 .next()
448 .ok_or_else(|| anyhow!("missing patch version number"))?
449 .parse()?;
450 Ok(Self {
451 major,
452 minor,
453 patch,
454 })
455 }
456}
457
458impl Display for SemanticVersion {
459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
461 }
462}
463
464#[derive(Clone, Debug, Eq, PartialEq)]
465pub struct ClipboardItem {
466 pub(crate) text: String,
467 pub(crate) metadata: Option<String>,
468}
469
470impl ClipboardItem {
471 pub fn new(text: String) -> Self {
472 Self {
473 text,
474 metadata: None,
475 }
476 }
477
478 pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
479 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
480 self
481 }
482
483 pub fn text(&self) -> &String {
484 &self.text
485 }
486
487 pub fn metadata<T>(&self) -> Option<T>
488 where
489 T: for<'a> Deserialize<'a>,
490 {
491 self.metadata
492 .as_ref()
493 .and_then(|m| serde_json::from_str(m).ok())
494 }
495
496 pub(crate) fn text_hash(text: &str) -> u64 {
497 let mut hasher = SeaHasher::new();
498 text.hash(&mut hasher);
499 hasher.finish()
500 }
501}