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