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    text_layout::{LineLayout, RunStyle},
 18    Action, ClipboardItem, Menu, Scene,
 19};
 20use anyhow::{anyhow, Result};
 21use async_task::Runnable;
 22pub use event::{Event, NavigationDirection};
 23use postage::oneshot;
 24use serde::Deserialize;
 25use std::{
 26    any::Any,
 27    fmt::{self, Display},
 28    path::{Path, PathBuf},
 29    rc::Rc,
 30    str::FromStr,
 31    sync::Arc,
 32};
 33use time::UtcOffset;
 34
 35pub trait Platform: Send + Sync {
 36    fn dispatcher(&self) -> Arc<dyn Dispatcher>;
 37    fn fonts(&self) -> Arc<dyn FontSystem>;
 38
 39    fn activate(&self, ignoring_other_apps: bool);
 40    fn open_window(
 41        &self,
 42        id: usize,
 43        options: WindowOptions,
 44        executor: Rc<executor::Foreground>,
 45    ) -> Box<dyn Window>;
 46    fn key_window_id(&self) -> Option<usize>;
 47    fn quit(&self);
 48
 49    fn write_to_clipboard(&self, item: ClipboardItem);
 50    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 51    fn open_url(&self, url: &str);
 52
 53    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()>;
 54    fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>>;
 55    fn delete_credentials(&self, url: &str) -> Result<()>;
 56
 57    fn set_cursor_style(&self, style: CursorStyle);
 58
 59    fn local_timezone(&self) -> UtcOffset;
 60
 61    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
 62    fn app_path(&self) -> Result<PathBuf>;
 63    fn app_version(&self) -> Result<AppVersion>;
 64}
 65
 66pub(crate) trait ForegroundPlatform {
 67    fn on_become_active(&self, callback: Box<dyn FnMut()>);
 68    fn on_resign_active(&self, callback: Box<dyn FnMut()>);
 69    fn on_quit(&self, callback: Box<dyn FnMut()>);
 70    fn on_event(&self, callback: Box<dyn FnMut(Event) -> bool>);
 71    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
 72    fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>);
 73
 74    fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>);
 75    fn set_menus(&self, menus: Vec<Menu>);
 76    fn prompt_for_paths(
 77        &self,
 78        options: PathPromptOptions,
 79    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
 80    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
 81}
 82
 83pub trait Dispatcher: Send + Sync {
 84    fn is_main_thread(&self) -> bool;
 85    fn run_on_main_thread(&self, task: Runnable);
 86}
 87
 88pub trait Window: WindowContext {
 89    fn as_any_mut(&mut self) -> &mut dyn Any;
 90    fn on_event(&mut self, callback: Box<dyn FnMut(Event)>);
 91    fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
 92    fn on_resize(&mut self, callback: Box<dyn FnMut()>);
 93    fn on_close(&mut self, callback: Box<dyn FnOnce()>);
 94    fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
 95    fn activate(&self);
 96}
 97
 98pub trait WindowContext {
 99    fn size(&self) -> Vector2F;
100    fn scale_factor(&self) -> f32;
101    fn titlebar_height(&self) -> f32;
102    fn present_scene(&mut self, scene: Scene);
103}
104
105#[derive(Debug)]
106pub struct WindowOptions<'a> {
107    pub bounds: WindowBounds,
108    pub title: Option<&'a str>,
109    pub titlebar_appears_transparent: bool,
110    pub traffic_light_position: Option<Vector2F>,
111}
112
113#[derive(Debug)]
114pub enum WindowBounds {
115    Maximized,
116    Fixed(RectF),
117}
118
119pub struct PathPromptOptions {
120    pub files: bool,
121    pub directories: bool,
122    pub multiple: bool,
123}
124
125pub enum PromptLevel {
126    Info,
127    Warning,
128    Critical,
129}
130
131#[derive(Copy, Clone, Debug, Deserialize)]
132pub enum CursorStyle {
133    Arrow,
134    ResizeLeftRight,
135    PointingHand,
136    IBeam,
137}
138
139#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
140pub struct AppVersion {
141    major: usize,
142    minor: usize,
143    patch: usize,
144}
145
146impl FromStr for AppVersion {
147    type Err = anyhow::Error;
148
149    fn from_str(s: &str) -> Result<Self> {
150        let mut components = s.trim().split('.');
151        let major = components
152            .next()
153            .ok_or_else(|| anyhow!("missing major version number"))?
154            .parse()?;
155        let minor = components
156            .next()
157            .ok_or_else(|| anyhow!("missing minor version number"))?
158            .parse()?;
159        let patch = components
160            .next()
161            .ok_or_else(|| anyhow!("missing patch version number"))?
162            .parse()?;
163        Ok(Self {
164            major,
165            minor,
166            patch,
167        })
168    }
169}
170
171impl Display for AppVersion {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
174    }
175}
176
177#[derive(Copy, Clone, Debug)]
178pub enum RasterizationOptions {
179    Alpha,
180    Bgra,
181}
182
183pub trait FontSystem: Send + Sync {
184    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> anyhow::Result<()>;
185    fn load_family(&self, name: &str) -> anyhow::Result<Vec<FontId>>;
186    fn select_font(
187        &self,
188        font_ids: &[FontId],
189        properties: &FontProperties,
190    ) -> anyhow::Result<FontId>;
191    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
192    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF>;
193    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Vector2F>;
194    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
195    fn rasterize_glyph(
196        &self,
197        font_id: FontId,
198        font_size: f32,
199        glyph_id: GlyphId,
200        subpixel_shift: Vector2F,
201        scale_factor: f32,
202        options: RasterizationOptions,
203    ) -> Option<(RectI, Vec<u8>)>;
204    fn layout_line(&self, text: &str, font_size: f32, runs: &[(usize, RunStyle)]) -> LineLayout;
205    fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize>;
206}
207
208impl<'a> Default for WindowOptions<'a> {
209    fn default() -> Self {
210        Self {
211            bounds: WindowBounds::Maximized,
212            title: Default::default(),
213            titlebar_appears_transparent: Default::default(),
214            traffic_light_position: Default::default(),
215        }
216    }
217}