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