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