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::*;
24use postage::oneshot;
25use serde::Deserialize;
26use std::{
27 any::Any,
28 fmt::{self, Display},
29 ops::Range,
30 path::{Path, PathBuf},
31 rc::Rc,
32 str::FromStr,
33 sync::Arc,
34};
35use time::UtcOffset;
36
37pub trait Platform: Send + Sync {
38 fn dispatcher(&self) -> Arc<dyn Dispatcher>;
39 fn fonts(&self) -> Arc<dyn FontSystem>;
40
41 fn activate(&self, ignoring_other_apps: bool);
42 fn hide(&self);
43 fn hide_other_apps(&self);
44 fn unhide_other_apps(&self);
45 fn quit(&self);
46
47 fn screen_size(&self) -> Vector2F;
48
49 fn open_window(
50 &self,
51 id: usize,
52 options: WindowOptions,
53 executor: Rc<executor::Foreground>,
54 ) -> Box<dyn Window>;
55 fn key_window_id(&self) -> Option<usize>;
56
57 fn add_status_item(&self) -> Box<dyn Window>;
58
59 fn write_to_clipboard(&self, item: ClipboardItem);
60 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
61 fn open_url(&self, url: &str);
62
63 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()>;
64 fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>>;
65 fn delete_credentials(&self, url: &str) -> Result<()>;
66
67 fn set_cursor_style(&self, style: CursorStyle);
68
69 fn local_timezone(&self) -> UtcOffset;
70
71 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
72 fn app_path(&self) -> Result<PathBuf>;
73 fn app_version(&self) -> Result<AppVersion>;
74}
75
76pub(crate) trait ForegroundPlatform {
77 fn on_become_active(&self, callback: Box<dyn FnMut()>);
78 fn on_resign_active(&self, callback: Box<dyn FnMut()>);
79 fn on_quit(&self, callback: Box<dyn FnMut()>);
80 fn on_event(&self, callback: Box<dyn FnMut(Event) -> bool>);
81 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
82 fn run(&self, on_finish_launching: Box<dyn FnOnce()>);
83
84 fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>);
85 fn on_validate_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
86 fn on_will_open_menu(&self, callback: Box<dyn FnMut()>);
87 fn set_menus(&self, menus: Vec<Menu>, matcher: &keymap::Matcher);
88 fn prompt_for_paths(
89 &self,
90 options: PathPromptOptions,
91 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
92 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
93}
94
95pub trait Dispatcher: Send + Sync {
96 fn is_main_thread(&self) -> bool;
97 fn run_on_main_thread(&self, task: Runnable);
98}
99
100pub trait InputHandler {
101 fn selected_text_range(&self) -> Option<Range<usize>>;
102 fn marked_text_range(&self) -> Option<Range<usize>>;
103 fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
104 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
105 fn replace_and_mark_text_in_range(
106 &mut self,
107 range_utf16: Option<Range<usize>>,
108 new_text: &str,
109 new_selected_range: Option<Range<usize>>,
110 );
111 fn unmark_text(&mut self);
112 fn rect_for_range(&self, range_utf16: Range<usize>) -> Option<RectF>;
113}
114
115pub trait Window {
116 fn as_any_mut(&mut self) -> &mut dyn Any;
117 fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>);
118 fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
119 fn on_resize(&mut self, callback: Box<dyn FnMut()>);
120 fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>);
121 fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>);
122 fn on_close(&mut self, callback: Box<dyn FnOnce()>);
123 fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>);
124 fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
125 fn activate(&self);
126 fn set_title(&mut self, title: &str);
127 fn set_edited(&mut self, edited: bool);
128 fn show_character_palette(&self);
129 fn minimize(&self);
130 fn zoom(&self);
131 fn toggle_full_screen(&self);
132
133 fn bounds(&self) -> RectF;
134 fn content_size(&self) -> Vector2F;
135 fn scale_factor(&self) -> f32;
136 fn titlebar_height(&self) -> f32;
137 fn present_scene(&mut self, scene: Scene);
138 fn appearance(&self) -> Appearance;
139 fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>);
140}
141
142#[derive(Debug)]
143pub struct WindowOptions<'a> {
144 pub bounds: WindowBounds,
145 pub titlebar: Option<TitlebarOptions<'a>>,
146 pub center: bool,
147 pub kind: WindowKind,
148 pub is_movable: bool,
149}
150
151#[derive(Debug)]
152pub struct TitlebarOptions<'a> {
153 pub title: Option<&'a str>,
154 pub appears_transparent: bool,
155 pub traffic_light_position: Option<Vector2F>,
156}
157
158#[derive(Copy, Clone, Debug)]
159pub enum Appearance {
160 Light,
161 VibrantLight,
162 Dark,
163 VibrantDark,
164}
165
166impl Default for Appearance {
167 fn default() -> Self {
168 Self::Light
169 }
170}
171
172#[derive(Copy, Clone, Debug)]
173pub enum WindowKind {
174 Normal,
175 PopUp,
176}
177
178#[derive(Debug)]
179pub enum WindowBounds {
180 Maximized,
181 Fixed(RectF),
182}
183
184pub struct PathPromptOptions {
185 pub files: bool,
186 pub directories: bool,
187 pub multiple: bool,
188}
189
190pub enum PromptLevel {
191 Info,
192 Warning,
193 Critical,
194}
195
196#[derive(Copy, Clone, Debug, Deserialize)]
197pub enum CursorStyle {
198 Arrow,
199 ResizeLeftRight,
200 ResizeUpDown,
201 PointingHand,
202 IBeam,
203}
204
205impl Default for CursorStyle {
206 fn default() -> Self {
207 Self::Arrow
208 }
209}
210
211#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
212pub struct AppVersion {
213 major: usize,
214 minor: usize,
215 patch: usize,
216}
217
218impl FromStr for AppVersion {
219 type Err = anyhow::Error;
220
221 fn from_str(s: &str) -> Result<Self> {
222 let mut components = s.trim().split('.');
223 let major = components
224 .next()
225 .ok_or_else(|| anyhow!("missing major version number"))?
226 .parse()?;
227 let minor = components
228 .next()
229 .ok_or_else(|| anyhow!("missing minor version number"))?
230 .parse()?;
231 let patch = components
232 .next()
233 .ok_or_else(|| anyhow!("missing patch version number"))?
234 .parse()?;
235 Ok(Self {
236 major,
237 minor,
238 patch,
239 })
240 }
241}
242
243impl Display for AppVersion {
244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
246 }
247}
248
249#[derive(Copy, Clone, Debug)]
250pub enum RasterizationOptions {
251 Alpha,
252 Bgra,
253}
254
255pub trait FontSystem: Send + Sync {
256 fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> anyhow::Result<()>;
257 fn load_family(&self, name: &str) -> anyhow::Result<Vec<FontId>>;
258 fn select_font(
259 &self,
260 font_ids: &[FontId],
261 properties: &FontProperties,
262 ) -> anyhow::Result<FontId>;
263 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
264 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF>;
265 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Vector2F>;
266 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
267 fn rasterize_glyph(
268 &self,
269 font_id: FontId,
270 font_size: f32,
271 glyph_id: GlyphId,
272 subpixel_shift: Vector2F,
273 scale_factor: f32,
274 options: RasterizationOptions,
275 ) -> Option<(RectI, Vec<u8>)>;
276 fn layout_line(&self, text: &str, font_size: f32, runs: &[(usize, RunStyle)]) -> LineLayout;
277 fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize>;
278}
279
280impl<'a> Default for WindowOptions<'a> {
281 fn default() -> Self {
282 Self {
283 bounds: WindowBounds::Maximized,
284 titlebar: Some(TitlebarOptions {
285 title: Default::default(),
286 appears_transparent: Default::default(),
287 traffic_light_position: Default::default(),
288 }),
289 center: false,
290 kind: WindowKind::Normal,
291 is_movable: true,
292 }
293 }
294}