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