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    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: &keymap::Matcher);
 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 Window {
119    fn as_any_mut(&mut self) -> &mut dyn Any;
120    fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>);
121    fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
122    fn on_resize(&mut self, callback: Box<dyn FnMut()>);
123    fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>);
124    fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>);
125    fn on_close(&mut self, callback: Box<dyn FnOnce()>);
126    fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>);
127    fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
128    fn activate(&self);
129    fn set_title(&mut self, title: &str);
130    fn set_edited(&mut self, edited: bool);
131    fn show_character_palette(&self);
132    fn minimize(&self);
133    fn zoom(&self);
134    fn toggle_full_screen(&self);
135
136    fn bounds(&self) -> RectF;
137    fn content_size(&self) -> Vector2F;
138    fn scale_factor(&self) -> f32;
139    fn titlebar_height(&self) -> f32;
140    fn present_scene(&mut self, scene: Scene);
141    fn appearance(&self) -> Appearance;
142    fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>);
143}
144
145#[derive(Debug)]
146pub struct WindowOptions<'a> {
147    pub bounds: WindowBounds,
148    pub titlebar: Option<TitlebarOptions<'a>>,
149    pub center: bool,
150    pub kind: WindowKind,
151    pub is_movable: bool,
152}
153
154#[derive(Debug)]
155pub struct TitlebarOptions<'a> {
156    pub title: Option<&'a str>,
157    pub appears_transparent: bool,
158    pub traffic_light_position: Option<Vector2F>,
159}
160
161#[derive(Copy, Clone, Debug)]
162pub enum Appearance {
163    Light,
164    VibrantLight,
165    Dark,
166    VibrantDark,
167}
168
169impl Default for Appearance {
170    fn default() -> Self {
171        Self::Light
172    }
173}
174
175#[derive(Copy, Clone, Debug)]
176pub enum WindowKind {
177    Normal,
178    PopUp,
179}
180
181#[derive(Debug)]
182pub enum WindowBounds {
183    Maximized,
184    Fixed(RectF),
185}
186
187pub struct PathPromptOptions {
188    pub files: bool,
189    pub directories: bool,
190    pub multiple: bool,
191}
192
193pub enum PromptLevel {
194    Info,
195    Warning,
196    Critical,
197}
198
199#[derive(Copy, Clone, Debug, Deserialize)]
200pub enum CursorStyle {
201    Arrow,
202    ResizeLeftRight,
203    ResizeUpDown,
204    PointingHand,
205    IBeam,
206}
207
208impl Default for CursorStyle {
209    fn default() -> Self {
210        Self::Arrow
211    }
212}
213
214#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
215pub struct AppVersion {
216    major: usize,
217    minor: usize,
218    patch: usize,
219}
220
221impl FromStr for AppVersion {
222    type Err = anyhow::Error;
223
224    fn from_str(s: &str) -> Result<Self> {
225        let mut components = s.trim().split('.');
226        let major = components
227            .next()
228            .ok_or_else(|| anyhow!("missing major version number"))?
229            .parse()?;
230        let minor = components
231            .next()
232            .ok_or_else(|| anyhow!("missing minor version number"))?
233            .parse()?;
234        let patch = components
235            .next()
236            .ok_or_else(|| anyhow!("missing patch version number"))?
237            .parse()?;
238        Ok(Self {
239            major,
240            minor,
241            patch,
242        })
243    }
244}
245
246impl Display for AppVersion {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
249    }
250}
251
252#[derive(Copy, Clone, Debug)]
253pub enum RasterizationOptions {
254    Alpha,
255    Bgra,
256}
257
258pub trait FontSystem: Send + Sync {
259    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> anyhow::Result<()>;
260    fn load_family(&self, name: &str) -> anyhow::Result<Vec<FontId>>;
261    fn select_font(
262        &self,
263        font_ids: &[FontId],
264        properties: &FontProperties,
265    ) -> anyhow::Result<FontId>;
266    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
267    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF>;
268    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Vector2F>;
269    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
270    fn rasterize_glyph(
271        &self,
272        font_id: FontId,
273        font_size: f32,
274        glyph_id: GlyphId,
275        subpixel_shift: Vector2F,
276        scale_factor: f32,
277        options: RasterizationOptions,
278    ) -> Option<(RectI, Vec<u8>)>;
279    fn layout_line(&self, text: &str, font_size: f32, runs: &[(usize, RunStyle)]) -> LineLayout;
280    fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize>;
281}
282
283impl<'a> Default for WindowOptions<'a> {
284    fn default() -> Self {
285        Self {
286            bounds: WindowBounds::Maximized,
287            titlebar: Some(TitlebarOptions {
288                title: Default::default(),
289                appears_transparent: Default::default(),
290                traffic_light_position: Default::default(),
291            }),
292            center: false,
293            kind: WindowKind::Normal,
294            is_movable: true,
295        }
296    }
297}