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