1mod event;
2#[cfg(target_os = "macos")]
3pub mod mac;
4pub mod test;
5pub mod current {
6 #[cfg(target_os = "macos")]
7 pub use super::mac::*;
8}
9
10use crate::{
11 executor,
12 fonts::{FontId, GlyphId, Metrics as FontMetrics, Properties as FontProperties},
13 geometry::{
14 rect::{RectF, RectI},
15 vector::Vector2F,
16 },
17 keymap,
18 text_layout::{LineLayout, RunStyle},
19 Action, ClipboardItem, Menu, Scene,
20};
21use anyhow::{anyhow, Result};
22use async_task::Runnable;
23pub use event::{Event, NavigationDirection};
24use postage::oneshot;
25use serde::Deserialize;
26use std::{
27 any::Any,
28 fmt::{self, Display},
29 path::{Path, PathBuf},
30 rc::Rc,
31 str::FromStr,
32 sync::Arc,
33};
34use time::UtcOffset;
35
36pub trait Platform: Send + Sync {
37 fn dispatcher(&self) -> Arc<dyn Dispatcher>;
38 fn fonts(&self) -> Arc<dyn FontSystem>;
39
40 fn activate(&self, ignoring_other_apps: bool);
41 fn open_window(
42 &self,
43 id: usize,
44 options: WindowOptions,
45 executor: Rc<executor::Foreground>,
46 ) -> Box<dyn Window>;
47 fn key_window_id(&self) -> Option<usize>;
48 fn quit(&self);
49
50 fn write_to_clipboard(&self, item: ClipboardItem);
51 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
52 fn open_url(&self, url: &str);
53
54 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()>;
55 fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>>;
56 fn delete_credentials(&self, url: &str) -> Result<()>;
57
58 fn set_cursor_style(&self, style: CursorStyle);
59
60 fn local_timezone(&self) -> UtcOffset;
61
62 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
63 fn app_path(&self) -> Result<PathBuf>;
64 fn app_version(&self) -> Result<AppVersion>;
65}
66
67pub(crate) trait ForegroundPlatform {
68 fn on_become_active(&self, callback: Box<dyn FnMut()>);
69 fn on_resign_active(&self, callback: Box<dyn FnMut()>);
70 fn on_quit(&self, callback: Box<dyn FnMut()>);
71 fn on_event(&self, callback: Box<dyn FnMut(Event) -> bool>);
72 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
73 fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>);
74
75 fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>);
76 fn set_menus(&self, menus: Vec<Menu>, matcher: &keymap::Matcher);
77 fn prompt_for_paths(
78 &self,
79 options: PathPromptOptions,
80 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
81 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
82}
83
84pub trait Dispatcher: Send + Sync {
85 fn is_main_thread(&self) -> bool;
86 fn run_on_main_thread(&self, task: Runnable);
87}
88
89pub trait Window: WindowContext {
90 fn as_any_mut(&mut self) -> &mut dyn Any;
91 fn on_event(&mut self, callback: Box<dyn FnMut(Event)>);
92 fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
93 fn on_resize(&mut self, callback: Box<dyn FnMut()>);
94 fn on_close(&mut self, callback: Box<dyn FnOnce()>);
95 fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
96 fn activate(&self);
97}
98
99pub trait WindowContext {
100 fn size(&self) -> Vector2F;
101 fn scale_factor(&self) -> f32;
102 fn titlebar_height(&self) -> f32;
103 fn present_scene(&mut self, scene: Scene);
104}
105
106#[derive(Debug)]
107pub struct WindowOptions<'a> {
108 pub bounds: WindowBounds,
109 pub title: Option<&'a str>,
110 pub titlebar_appears_transparent: bool,
111 pub traffic_light_position: Option<Vector2F>,
112}
113
114#[derive(Debug)]
115pub enum WindowBounds {
116 Maximized,
117 Fixed(RectF),
118}
119
120pub struct PathPromptOptions {
121 pub files: bool,
122 pub directories: bool,
123 pub multiple: bool,
124}
125
126pub enum PromptLevel {
127 Info,
128 Warning,
129 Critical,
130}
131
132#[derive(Copy, Clone, Debug, Deserialize)]
133pub enum CursorStyle {
134 Arrow,
135 ResizeLeftRight,
136 PointingHand,
137 IBeam,
138}
139
140#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
141pub struct AppVersion {
142 major: usize,
143 minor: usize,
144 patch: usize,
145}
146
147impl FromStr for AppVersion {
148 type Err = anyhow::Error;
149
150 fn from_str(s: &str) -> Result<Self> {
151 let mut components = s.trim().split('.');
152 let major = components
153 .next()
154 .ok_or_else(|| anyhow!("missing major version number"))?
155 .parse()?;
156 let minor = components
157 .next()
158 .ok_or_else(|| anyhow!("missing minor version number"))?
159 .parse()?;
160 let patch = components
161 .next()
162 .ok_or_else(|| anyhow!("missing patch version number"))?
163 .parse()?;
164 Ok(Self {
165 major,
166 minor,
167 patch,
168 })
169 }
170}
171
172impl Display for AppVersion {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
175 }
176}
177
178#[derive(Copy, Clone, Debug)]
179pub enum RasterizationOptions {
180 Alpha,
181 Bgra,
182}
183
184pub trait FontSystem: Send + Sync {
185 fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> anyhow::Result<()>;
186 fn load_family(&self, name: &str) -> anyhow::Result<Vec<FontId>>;
187 fn select_font(
188 &self,
189 font_ids: &[FontId],
190 properties: &FontProperties,
191 ) -> anyhow::Result<FontId>;
192 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
193 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF>;
194 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Vector2F>;
195 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
196 fn rasterize_glyph(
197 &self,
198 font_id: FontId,
199 font_size: f32,
200 glyph_id: GlyphId,
201 subpixel_shift: Vector2F,
202 scale_factor: f32,
203 options: RasterizationOptions,
204 ) -> Option<(RectI, Vec<u8>)>;
205 fn layout_line(&self, text: &str, font_size: f32, runs: &[(usize, RunStyle)]) -> LineLayout;
206 fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize>;
207}
208
209impl<'a> Default for WindowOptions<'a> {
210 fn default() -> Self {
211 Self {
212 bounds: WindowBounds::Maximized,
213 title: Default::default(),
214 titlebar_appears_transparent: Default::default(),
215 traffic_light_position: Default::default(),
216 }
217 }
218}