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