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