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