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, bail, Result};
22use async_task::Runnable;
23pub use event::*;
24use postage::oneshot;
25use serde::Deserialize;
26use sqlez::{
27 bindable::{Bind, Column, StaticColumnCount},
28 statement::Statement,
29};
30use std::{
31 any::Any,
32 fmt::{self, Debug, Display},
33 ops::Range,
34 path::{Path, PathBuf},
35 rc::Rc,
36 str::FromStr,
37 sync::Arc,
38};
39use time::UtcOffset;
40use uuid::Uuid;
41
42pub trait Platform: Send + Sync {
43 fn dispatcher(&self) -> Arc<dyn Dispatcher>;
44 fn fonts(&self) -> Arc<dyn FontSystem>;
45
46 fn activate(&self, ignoring_other_apps: bool);
47 fn hide(&self);
48 fn hide_other_apps(&self);
49 fn unhide_other_apps(&self);
50 fn quit(&self);
51
52 fn screen_by_id(&self, id: Uuid) -> Option<Rc<dyn Screen>>;
53 fn screens(&self) -> Vec<Rc<dyn Screen>>;
54
55 fn open_window(
56 &self,
57 id: usize,
58 options: WindowOptions,
59 executor: Rc<executor::Foreground>,
60 ) -> Box<dyn Window>;
61 fn main_window_id(&self) -> Option<usize>;
62
63 fn add_status_item(&self) -> Box<dyn Window>;
64
65 fn write_to_clipboard(&self, item: ClipboardItem);
66 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
67 fn open_url(&self, url: &str);
68
69 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()>;
70 fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>>;
71 fn delete_credentials(&self, url: &str) -> Result<()>;
72
73 fn set_cursor_style(&self, style: CursorStyle);
74 fn should_auto_hide_scrollbars(&self) -> bool;
75
76 fn local_timezone(&self) -> UtcOffset;
77
78 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
79 fn app_path(&self) -> Result<PathBuf>;
80 fn app_version(&self) -> Result<AppVersion>;
81 fn os_name(&self) -> &'static str;
82 fn os_version(&self) -> Result<AppVersion>;
83 fn restart(&self);
84}
85
86pub(crate) trait ForegroundPlatform {
87 fn on_become_active(&self, callback: Box<dyn FnMut()>);
88 fn on_resign_active(&self, callback: Box<dyn FnMut()>);
89 fn on_quit(&self, callback: Box<dyn FnMut()>);
90 fn on_event(&self, callback: Box<dyn FnMut(Event) -> bool>);
91 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
92 fn run(&self, on_finish_launching: Box<dyn FnOnce()>);
93
94 fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>);
95 fn on_validate_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
96 fn on_will_open_menu(&self, callback: Box<dyn FnMut()>);
97 fn set_menus(&self, menus: Vec<Menu>, matcher: &KeymapMatcher);
98 fn prompt_for_paths(
99 &self,
100 options: PathPromptOptions,
101 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
102 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
103 fn reveal_path(&self, path: &Path);
104}
105
106pub trait Dispatcher: Send + Sync {
107 fn is_main_thread(&self) -> bool;
108 fn run_on_main_thread(&self, task: Runnable);
109}
110
111pub trait InputHandler {
112 fn selected_text_range(&self) -> Option<Range<usize>>;
113 fn marked_text_range(&self) -> Option<Range<usize>>;
114 fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
115 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
116 fn replace_and_mark_text_in_range(
117 &mut self,
118 range_utf16: Option<Range<usize>>,
119 new_text: &str,
120 new_selected_range: Option<Range<usize>>,
121 );
122 fn unmark_text(&mut self);
123 fn rect_for_range(&self, range_utf16: Range<usize>) -> Option<RectF>;
124}
125
126pub trait Screen: Debug {
127 fn as_any(&self) -> &dyn Any;
128 fn bounds(&self) -> RectF;
129 fn display_uuid(&self) -> Option<Uuid>;
130}
131
132pub trait Window {
133 fn bounds(&self) -> WindowBounds;
134 fn content_size(&self) -> Vector2F;
135 fn scale_factor(&self) -> f32;
136 fn titlebar_height(&self) -> f32;
137 fn appearance(&self) -> Appearance;
138 fn screen(&self) -> Rc<dyn Screen>;
139
140 fn as_any_mut(&mut self) -> &mut dyn Any;
141 fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>);
142 fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
143 fn activate(&self);
144 fn set_title(&mut self, title: &str);
145 fn set_edited(&mut self, edited: bool);
146 fn show_character_palette(&self);
147 fn minimize(&self);
148 fn zoom(&self);
149 fn present_scene(&mut self, scene: Scene);
150 fn toggle_full_screen(&self);
151
152 fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>);
153 fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
154 fn on_resize(&mut self, callback: Box<dyn FnMut()>);
155 fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>);
156 fn on_moved(&mut self, callback: Box<dyn FnMut()>);
157 fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>);
158 fn on_close(&mut self, callback: Box<dyn FnOnce()>);
159 fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>);
160 fn is_topmost_for_position(&self, position: Vector2F) -> bool;
161}
162
163#[derive(Debug)]
164pub struct WindowOptions<'a> {
165 pub bounds: WindowBounds,
166 pub titlebar: Option<TitlebarOptions<'a>>,
167 pub center: bool,
168 pub focus: bool,
169 pub kind: WindowKind,
170 pub is_movable: bool,
171 pub screen: Option<Rc<dyn Screen>>,
172}
173
174#[derive(Debug)]
175pub struct TitlebarOptions<'a> {
176 pub title: Option<&'a str>,
177 pub appears_transparent: bool,
178 pub traffic_light_position: Option<Vector2F>,
179}
180
181#[derive(Copy, Clone, Debug)]
182pub enum Appearance {
183 Light,
184 VibrantLight,
185 Dark,
186 VibrantDark,
187}
188
189impl Default for Appearance {
190 fn default() -> Self {
191 Self::Light
192 }
193}
194
195#[derive(Copy, Clone, Debug, PartialEq, Eq)]
196pub enum WindowKind {
197 Normal,
198 PopUp,
199}
200
201#[derive(Copy, Clone, Debug, PartialEq)]
202pub enum WindowBounds {
203 Fullscreen,
204 Maximized,
205 Fixed(RectF),
206}
207
208impl StaticColumnCount for WindowBounds {
209 fn column_count() -> usize {
210 5
211 }
212}
213
214impl Bind for WindowBounds {
215 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
216 let (region, next_index) = match self {
217 WindowBounds::Fullscreen => {
218 let next_index = statement.bind("Fullscreen", start_index)?;
219 (None, next_index)
220 }
221 WindowBounds::Maximized => {
222 let next_index = statement.bind("Maximized", start_index)?;
223 (None, next_index)
224 }
225 WindowBounds::Fixed(region) => {
226 let next_index = statement.bind("Fixed", start_index)?;
227 (Some(*region), next_index)
228 }
229 };
230
231 statement.bind(
232 region.map(|region| {
233 (
234 region.min_x(),
235 region.min_y(),
236 region.width(),
237 region.height(),
238 )
239 }),
240 next_index,
241 )
242 }
243}
244
245impl Column for WindowBounds {
246 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
247 let (window_state, next_index) = String::column(statement, start_index)?;
248 let bounds = match window_state.as_str() {
249 "Fullscreen" => WindowBounds::Fullscreen,
250 "Maximized" => WindowBounds::Maximized,
251 "Fixed" => {
252 let ((x, y, width, height), _) = Column::column(statement, next_index)?;
253 WindowBounds::Fixed(RectF::new(
254 Vector2F::new(x, y),
255 Vector2F::new(width, height),
256 ))
257 }
258 _ => bail!("Window State did not have a valid string"),
259 };
260
261 Ok((bounds, next_index + 4))
262 }
263}
264
265pub struct PathPromptOptions {
266 pub files: bool,
267 pub directories: bool,
268 pub multiple: bool,
269}
270
271pub enum PromptLevel {
272 Info,
273 Warning,
274 Critical,
275}
276
277#[derive(Copy, Clone, Debug, Deserialize)]
278pub enum CursorStyle {
279 Arrow,
280 ResizeLeftRight,
281 ResizeUpDown,
282 PointingHand,
283 IBeam,
284}
285
286impl Default for CursorStyle {
287 fn default() -> Self {
288 Self::Arrow
289 }
290}
291
292#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
293pub struct AppVersion {
294 major: usize,
295 minor: usize,
296 patch: usize,
297}
298
299impl FromStr for AppVersion {
300 type Err = anyhow::Error;
301
302 fn from_str(s: &str) -> Result<Self> {
303 let mut components = s.trim().split('.');
304 let major = components
305 .next()
306 .ok_or_else(|| anyhow!("missing major version number"))?
307 .parse()?;
308 let minor = components
309 .next()
310 .ok_or_else(|| anyhow!("missing minor version number"))?
311 .parse()?;
312 let patch = components
313 .next()
314 .ok_or_else(|| anyhow!("missing patch version number"))?
315 .parse()?;
316 Ok(Self {
317 major,
318 minor,
319 patch,
320 })
321 }
322}
323
324impl Display for AppVersion {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
327 }
328}
329
330#[derive(Copy, Clone, Debug)]
331pub enum RasterizationOptions {
332 Alpha,
333 Bgra,
334}
335
336pub trait FontSystem: Send + Sync {
337 fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> anyhow::Result<()>;
338 fn load_family(&self, name: &str) -> anyhow::Result<Vec<FontId>>;
339 fn select_font(
340 &self,
341 font_ids: &[FontId],
342 properties: &FontProperties,
343 ) -> anyhow::Result<FontId>;
344 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
345 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF>;
346 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Vector2F>;
347 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
348 fn rasterize_glyph(
349 &self,
350 font_id: FontId,
351 font_size: f32,
352 glyph_id: GlyphId,
353 subpixel_shift: Vector2F,
354 scale_factor: f32,
355 options: RasterizationOptions,
356 ) -> Option<(RectI, Vec<u8>)>;
357 fn layout_line(&self, text: &str, font_size: f32, runs: &[(usize, RunStyle)]) -> LineLayout;
358 fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize>;
359}
360
361impl<'a> Default for WindowOptions<'a> {
362 fn default() -> Self {
363 Self {
364 bounds: WindowBounds::Maximized,
365 titlebar: Some(TitlebarOptions {
366 title: Default::default(),
367 appears_transparent: Default::default(),
368 traffic_light_position: Default::default(),
369 }),
370 center: false,
371 focus: true,
372 kind: WindowKind::Normal,
373 is_movable: true,
374 screen: None,
375 }
376 }
377}