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, bail, Result};
 22use async_task::Runnable;
 23pub use event::*;
 24use postage::oneshot;
 25use serde::Deserialize;
 26use sqlez::{
 27    bindable::{Bind, Column, StaticColumnCount},
 28    statement::Statement,
 29};
 30use std::{
 31    any::Any,
 32    fmt::{self, Debug, Display},
 33    ops::Range,
 34    path::{Path, PathBuf},
 35    rc::Rc,
 36    str::FromStr,
 37    sync::Arc,
 38};
 39use time::UtcOffset;
 40use uuid::Uuid;
 41
 42pub trait Platform: Send + Sync {
 43    fn dispatcher(&self) -> Arc<dyn Dispatcher>;
 44    fn fonts(&self) -> Arc<dyn FontSystem>;
 45
 46    fn activate(&self, ignoring_other_apps: bool);
 47    fn hide(&self);
 48    fn hide_other_apps(&self);
 49    fn unhide_other_apps(&self);
 50    fn quit(&self);
 51
 52    fn screen_by_id(&self, id: Uuid) -> Option<Rc<dyn Screen>>;
 53    fn screens(&self) -> Vec<Rc<dyn Screen>>;
 54
 55    fn open_window(
 56        &self,
 57        id: usize,
 58        options: WindowOptions,
 59        executor: Rc<executor::Foreground>,
 60    ) -> Box<dyn Window>;
 61    fn key_window_id(&self) -> Option<usize>;
 62
 63    fn add_status_item(&self) -> Box<dyn Window>;
 64
 65    fn write_to_clipboard(&self, item: ClipboardItem);
 66    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 67    fn open_url(&self, url: &str);
 68
 69    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()>;
 70    fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>>;
 71    fn delete_credentials(&self, url: &str) -> Result<()>;
 72
 73    fn set_cursor_style(&self, style: CursorStyle);
 74    fn should_auto_hide_scrollbars(&self) -> bool;
 75
 76    fn local_timezone(&self) -> UtcOffset;
 77
 78    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
 79    fn app_path(&self) -> Result<PathBuf>;
 80    fn app_version(&self) -> Result<AppVersion>;
 81    fn os_name(&self) -> &'static str;
 82    fn os_version(&self) -> Result<AppVersion>;
 83}
 84
 85pub(crate) trait ForegroundPlatform {
 86    fn on_become_active(&self, callback: Box<dyn FnMut()>);
 87    fn on_resign_active(&self, callback: Box<dyn FnMut()>);
 88    fn on_quit(&self, callback: Box<dyn FnMut()>);
 89    fn on_event(&self, callback: Box<dyn FnMut(Event) -> bool>);
 90    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
 91    fn run(&self, on_finish_launching: Box<dyn FnOnce()>);
 92
 93    fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>);
 94    fn on_validate_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
 95    fn on_will_open_menu(&self, callback: Box<dyn FnMut()>);
 96    fn set_menus(&self, menus: Vec<Menu>, matcher: &KeymapMatcher);
 97    fn prompt_for_paths(
 98        &self,
 99        options: PathPromptOptions,
100    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
101    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
102}
103
104pub trait Dispatcher: Send + Sync {
105    fn is_main_thread(&self) -> bool;
106    fn run_on_main_thread(&self, task: Runnable);
107}
108
109pub trait InputHandler {
110    fn selected_text_range(&self) -> Option<Range<usize>>;
111    fn marked_text_range(&self) -> Option<Range<usize>>;
112    fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
113    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
114    fn replace_and_mark_text_in_range(
115        &mut self,
116        range_utf16: Option<Range<usize>>,
117        new_text: &str,
118        new_selected_range: Option<Range<usize>>,
119    );
120    fn unmark_text(&mut self);
121    fn rect_for_range(&self, range_utf16: Range<usize>) -> Option<RectF>;
122}
123
124pub trait Screen: Debug {
125    fn as_any(&self) -> &dyn Any;
126    fn bounds(&self) -> RectF;
127    fn display_uuid(&self) -> Option<Uuid>;
128}
129
130pub trait Window {
131    fn bounds(&self) -> WindowBounds;
132    fn content_size(&self) -> Vector2F;
133    fn scale_factor(&self) -> f32;
134    fn titlebar_height(&self) -> f32;
135    fn appearance(&self) -> Appearance;
136    fn screen(&self) -> Rc<dyn Screen>;
137
138    fn as_any_mut(&mut self) -> &mut dyn Any;
139    fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>);
140    fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
141    fn activate(&self);
142    fn set_title(&mut self, title: &str);
143    fn set_edited(&mut self, edited: bool);
144    fn show_character_palette(&self);
145    fn minimize(&self);
146    fn zoom(&self);
147    fn present_scene(&mut self, scene: Scene);
148    fn toggle_full_screen(&self);
149
150    fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>);
151    fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
152    fn on_resize(&mut self, callback: Box<dyn FnMut()>);
153    fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>);
154    fn on_moved(&mut self, callback: Box<dyn FnMut()>);
155    fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>);
156    fn on_close(&mut self, callback: Box<dyn FnOnce()>);
157    fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>);
158    fn is_topmost_for_position(&self, position: Vector2F) -> bool;
159}
160
161#[derive(Debug)]
162pub struct WindowOptions<'a> {
163    pub bounds: WindowBounds,
164    pub titlebar: Option<TitlebarOptions<'a>>,
165    pub center: bool,
166    pub focus: bool,
167    pub kind: WindowKind,
168    pub is_movable: bool,
169    pub screen: Option<Rc<dyn Screen>>,
170}
171
172#[derive(Debug)]
173pub struct TitlebarOptions<'a> {
174    pub title: Option<&'a str>,
175    pub appears_transparent: bool,
176    pub traffic_light_position: Option<Vector2F>,
177}
178
179#[derive(Copy, Clone, Debug)]
180pub enum Appearance {
181    Light,
182    VibrantLight,
183    Dark,
184    VibrantDark,
185}
186
187impl Default for Appearance {
188    fn default() -> Self {
189        Self::Light
190    }
191}
192
193#[derive(Copy, Clone, Debug, PartialEq, Eq)]
194pub enum WindowKind {
195    Normal,
196    PopUp,
197}
198
199#[derive(Copy, Clone, Debug, PartialEq)]
200pub enum WindowBounds {
201    Fullscreen,
202    Maximized,
203    Fixed(RectF),
204}
205
206impl StaticColumnCount for WindowBounds {
207    fn column_count() -> usize {
208        5
209    }
210}
211
212impl Bind for WindowBounds {
213    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
214        let (region, next_index) = match self {
215            WindowBounds::Fullscreen => {
216                let next_index = statement.bind("Fullscreen", start_index)?;
217                (None, next_index)
218            }
219            WindowBounds::Maximized => {
220                let next_index = statement.bind("Maximized", start_index)?;
221                (None, next_index)
222            }
223            WindowBounds::Fixed(region) => {
224                let next_index = statement.bind("Fixed", start_index)?;
225                (Some(*region), next_index)
226            }
227        };
228
229        statement.bind(
230            region.map(|region| {
231                (
232                    region.min_x(),
233                    region.min_y(),
234                    region.width(),
235                    region.height(),
236                )
237            }),
238            next_index,
239        )
240    }
241}
242
243impl Column for WindowBounds {
244    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
245        let (window_state, next_index) = String::column(statement, start_index)?;
246        let bounds = match window_state.as_str() {
247            "Fullscreen" => WindowBounds::Fullscreen,
248            "Maximized" => WindowBounds::Maximized,
249            "Fixed" => {
250                let ((x, y, width, height), _) = Column::column(statement, next_index)?;
251                WindowBounds::Fixed(RectF::new(
252                    Vector2F::new(x, y),
253                    Vector2F::new(width, height),
254                ))
255            }
256            _ => bail!("Window State did not have a valid string"),
257        };
258
259        Ok((bounds, next_index + 4))
260    }
261}
262
263pub struct PathPromptOptions {
264    pub files: bool,
265    pub directories: bool,
266    pub multiple: bool,
267}
268
269pub enum PromptLevel {
270    Info,
271    Warning,
272    Critical,
273}
274
275#[derive(Copy, Clone, Debug, Deserialize)]
276pub enum CursorStyle {
277    Arrow,
278    ResizeLeftRight,
279    ResizeUpDown,
280    PointingHand,
281    IBeam,
282}
283
284impl Default for CursorStyle {
285    fn default() -> Self {
286        Self::Arrow
287    }
288}
289
290#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
291pub struct AppVersion {
292    major: usize,
293    minor: usize,
294    patch: usize,
295}
296
297impl FromStr for AppVersion {
298    type Err = anyhow::Error;
299
300    fn from_str(s: &str) -> Result<Self> {
301        let mut components = s.trim().split('.');
302        let major = components
303            .next()
304            .ok_or_else(|| anyhow!("missing major version number"))?
305            .parse()?;
306        let minor = components
307            .next()
308            .ok_or_else(|| anyhow!("missing minor version number"))?
309            .parse()?;
310        let patch = components
311            .next()
312            .ok_or_else(|| anyhow!("missing patch version number"))?
313            .parse()?;
314        Ok(Self {
315            major,
316            minor,
317            patch,
318        })
319    }
320}
321
322impl Display for AppVersion {
323    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
325    }
326}
327
328#[derive(Copy, Clone, Debug)]
329pub enum RasterizationOptions {
330    Alpha,
331    Bgra,
332}
333
334pub trait FontSystem: Send + Sync {
335    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> anyhow::Result<()>;
336    fn load_family(&self, name: &str) -> anyhow::Result<Vec<FontId>>;
337    fn select_font(
338        &self,
339        font_ids: &[FontId],
340        properties: &FontProperties,
341    ) -> anyhow::Result<FontId>;
342    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
343    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF>;
344    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Vector2F>;
345    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
346    fn rasterize_glyph(
347        &self,
348        font_id: FontId,
349        font_size: f32,
350        glyph_id: GlyphId,
351        subpixel_shift: Vector2F,
352        scale_factor: f32,
353        options: RasterizationOptions,
354    ) -> Option<(RectI, Vec<u8>)>;
355    fn layout_line(&self, text: &str, font_size: f32, runs: &[(usize, RunStyle)]) -> LineLayout;
356    fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize>;
357}
358
359impl<'a> Default for WindowOptions<'a> {
360    fn default() -> Self {
361        Self {
362            bounds: WindowBounds::Maximized,
363            titlebar: Some(TitlebarOptions {
364                title: Default::default(),
365                appears_transparent: Default::default(),
366                traffic_light_position: Default::default(),
367            }),
368            center: false,
369            focus: true,
370            kind: WindowKind::Normal,
371            is_movable: true,
372            screen: None,
373        }
374    }
375}