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