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