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