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