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