platform.rs

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