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 marked_text_range(&self) -> Option<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 unmark_text(&mut self);
104 fn rect_for_range(&self, range_utf16: Range<usize>) -> Option<RectF>;
105}
106
107pub trait Window: WindowContext {
108 fn as_any_mut(&mut self) -> &mut dyn Any;
109 fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>);
110 fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
111 fn on_resize(&mut self, callback: Box<dyn FnMut()>);
112 fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>);
113 fn on_close(&mut self, callback: Box<dyn FnOnce()>);
114 fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>);
115 fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
116 fn activate(&self);
117 fn set_title(&mut self, title: &str);
118 fn set_edited(&mut self, edited: bool);
119 fn show_character_palette(&self);
120}
121
122pub trait WindowContext {
123 fn size(&self) -> Vector2F;
124 fn scale_factor(&self) -> f32;
125 fn titlebar_height(&self) -> f32;
126 fn present_scene(&mut self, scene: Scene);
127}
128
129#[derive(Debug)]
130pub struct WindowOptions<'a> {
131 pub bounds: WindowBounds,
132 pub title: Option<&'a str>,
133 pub titlebar_appears_transparent: bool,
134 pub traffic_light_position: Option<Vector2F>,
135}
136
137#[derive(Debug)]
138pub enum WindowBounds {
139 Maximized,
140 Fixed(RectF),
141}
142
143pub struct PathPromptOptions {
144 pub files: bool,
145 pub directories: bool,
146 pub multiple: bool,
147}
148
149pub enum PromptLevel {
150 Info,
151 Warning,
152 Critical,
153}
154
155#[derive(Copy, Clone, Debug, Deserialize)]
156pub enum CursorStyle {
157 Arrow,
158 ResizeLeftRight,
159 PointingHand,
160 IBeam,
161}
162
163#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
164pub struct AppVersion {
165 major: usize,
166 minor: usize,
167 patch: usize,
168}
169
170impl Default for CursorStyle {
171 fn default() -> Self {
172 Self::Arrow
173 }
174}
175
176impl FromStr for AppVersion {
177 type Err = anyhow::Error;
178
179 fn from_str(s: &str) -> Result<Self> {
180 let mut components = s.trim().split('.');
181 let major = components
182 .next()
183 .ok_or_else(|| anyhow!("missing major version number"))?
184 .parse()?;
185 let minor = components
186 .next()
187 .ok_or_else(|| anyhow!("missing minor version number"))?
188 .parse()?;
189 let patch = components
190 .next()
191 .ok_or_else(|| anyhow!("missing patch version number"))?
192 .parse()?;
193 Ok(Self {
194 major,
195 minor,
196 patch,
197 })
198 }
199}
200
201impl Display for AppVersion {
202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
204 }
205}
206
207#[derive(Copy, Clone, Debug)]
208pub enum RasterizationOptions {
209 Alpha,
210 Bgra,
211}
212
213pub trait FontSystem: Send + Sync {
214 fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> anyhow::Result<()>;
215 fn load_family(&self, name: &str) -> anyhow::Result<Vec<FontId>>;
216 fn select_font(
217 &self,
218 font_ids: &[FontId],
219 properties: &FontProperties,
220 ) -> anyhow::Result<FontId>;
221 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
222 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF>;
223 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Vector2F>;
224 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
225 fn rasterize_glyph(
226 &self,
227 font_id: FontId,
228 font_size: f32,
229 glyph_id: GlyphId,
230 subpixel_shift: Vector2F,
231 scale_factor: f32,
232 options: RasterizationOptions,
233 ) -> Option<(RectI, Vec<u8>)>;
234 fn layout_line(&self, text: &str, font_size: f32, runs: &[(usize, RunStyle)]) -> LineLayout;
235 fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize>;
236}
237
238impl<'a> Default for WindowOptions<'a> {
239 fn default() -> Self {
240 Self {
241 bounds: WindowBounds::Maximized,
242 title: Default::default(),
243 titlebar_appears_transparent: Default::default(),
244 traffic_light_position: Default::default(),
245 }
246 }
247}