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