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