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