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 content_bounds(&self) -> RectF;
139    fn display_uuid(&self) -> Option<Uuid>;
140}
141
142pub trait Window {
143    fn bounds(&self) -> WindowBounds;
144    fn content_size(&self) -> Vector2F;
145    fn scale_factor(&self) -> f32;
146    fn titlebar_height(&self) -> f32;
147    fn appearance(&self) -> Appearance;
148    fn screen(&self) -> Rc<dyn Screen>;
149    fn mouse_position(&self) -> Vector2F;
150
151    fn as_any_mut(&mut self) -> &mut dyn Any;
152    fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>);
153    fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
154    fn activate(&self);
155    fn set_title(&mut self, title: &str);
156    fn set_edited(&mut self, edited: bool);
157    fn show_character_palette(&self);
158    fn minimize(&self);
159    fn zoom(&self);
160    fn present_scene(&mut self, scene: Scene);
161    fn toggle_full_screen(&self);
162
163    fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>);
164    fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
165    fn on_resize(&mut self, callback: Box<dyn FnMut()>);
166    fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>);
167    fn on_moved(&mut self, callback: Box<dyn FnMut()>);
168    fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>);
169    fn on_close(&mut self, callback: Box<dyn FnOnce()>);
170    fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>);
171    fn is_topmost_for_position(&self, position: Vector2F) -> bool;
172}
173
174#[derive(Debug)]
175pub struct WindowOptions<'a> {
176    pub bounds: WindowBounds,
177    pub titlebar: Option<TitlebarOptions<'a>>,
178    pub center: bool,
179    pub focus: bool,
180    pub show: bool,
181    pub kind: WindowKind,
182    pub is_movable: bool,
183    pub screen: Option<Rc<dyn Screen>>,
184}
185
186impl<'a> WindowOptions<'a> {
187    pub fn with_bounds(bounds: Vector2F) -> Self {
188        Self {
189            bounds: WindowBounds::Fixed(RectF::new(vec2f(0., 0.), bounds)),
190            center: true,
191            ..Default::default()
192        }
193    }
194}
195
196#[derive(Debug, Default)]
197pub struct TitlebarOptions<'a> {
198    pub title: Option<&'a str>,
199    pub appears_transparent: bool,
200    pub traffic_light_position: Option<Vector2F>,
201}
202
203#[derive(Copy, Clone, Debug)]
204pub enum Appearance {
205    Light,
206    VibrantLight,
207    Dark,
208    VibrantDark,
209}
210
211impl Default for Appearance {
212    fn default() -> Self {
213        Self::Light
214    }
215}
216
217#[derive(Copy, Clone, Debug, PartialEq, Eq)]
218pub enum WindowKind {
219    Normal,
220    PopUp,
221}
222
223#[derive(Copy, Clone, Debug, PartialEq)]
224pub enum WindowBounds {
225    Fullscreen,
226    Maximized,
227    Fixed(RectF),
228}
229
230impl StaticColumnCount for WindowBounds {
231    fn column_count() -> usize {
232        5
233    }
234}
235
236impl Bind for WindowBounds {
237    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
238        let (region, next_index) = match self {
239            WindowBounds::Fullscreen => {
240                let next_index = statement.bind(&"Fullscreen", start_index)?;
241                (None, next_index)
242            }
243            WindowBounds::Maximized => {
244                let next_index = statement.bind(&"Maximized", start_index)?;
245                (None, next_index)
246            }
247            WindowBounds::Fixed(region) => {
248                let next_index = statement.bind(&"Fixed", start_index)?;
249                (Some(*region), next_index)
250            }
251        };
252
253        statement.bind(
254            &region.map(|region| {
255                (
256                    region.min_x(),
257                    region.min_y(),
258                    region.width(),
259                    region.height(),
260                )
261            }),
262            next_index,
263        )
264    }
265}
266
267impl Column for WindowBounds {
268    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
269        let (window_state, next_index) = String::column(statement, start_index)?;
270        let bounds = match window_state.as_str() {
271            "Fullscreen" => WindowBounds::Fullscreen,
272            "Maximized" => WindowBounds::Maximized,
273            "Fixed" => {
274                let ((x, y, width, height), _) = Column::column(statement, next_index)?;
275                WindowBounds::Fixed(RectF::new(
276                    Vector2F::new(x, y),
277                    Vector2F::new(width, height),
278                ))
279            }
280            _ => bail!("Window State did not have a valid string"),
281        };
282
283        Ok((bounds, next_index + 4))
284    }
285}
286
287pub struct PathPromptOptions {
288    pub files: bool,
289    pub directories: bool,
290    pub multiple: bool,
291}
292
293pub enum PromptLevel {
294    Info,
295    Warning,
296    Critical,
297}
298
299#[derive(Copy, Clone, Debug, Deserialize, JsonSchema)]
300pub enum CursorStyle {
301    Arrow,
302    ResizeLeftRight,
303    ResizeUpDown,
304    PointingHand,
305    IBeam,
306}
307
308impl Default for CursorStyle {
309    fn default() -> Self {
310        Self::Arrow
311    }
312}
313
314#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
315pub struct AppVersion {
316    major: usize,
317    minor: usize,
318    patch: usize,
319}
320
321impl FromStr for AppVersion {
322    type Err = anyhow::Error;
323
324    fn from_str(s: &str) -> Result<Self> {
325        let mut components = s.trim().split('.');
326        let major = components
327            .next()
328            .ok_or_else(|| anyhow!("missing major version number"))?
329            .parse()?;
330        let minor = components
331            .next()
332            .ok_or_else(|| anyhow!("missing minor version number"))?
333            .parse()?;
334        let patch = components
335            .next()
336            .ok_or_else(|| anyhow!("missing patch version number"))?
337            .parse()?;
338        Ok(Self {
339            major,
340            minor,
341            patch,
342        })
343    }
344}
345
346impl Display for AppVersion {
347    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
349    }
350}
351
352#[derive(Copy, Clone, Debug)]
353pub enum RasterizationOptions {
354    Alpha,
355    Bgra,
356}
357
358pub trait FontSystem: Send + Sync {
359    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> anyhow::Result<()>;
360    fn all_families(&self) -> Vec<String>;
361    fn load_family(&self, name: &str, features: &FontFeatures) -> anyhow::Result<Vec<FontId>>;
362    fn select_font(
363        &self,
364        font_ids: &[FontId],
365        properties: &FontProperties,
366    ) -> anyhow::Result<FontId>;
367    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
368    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<RectF>;
369    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Vector2F>;
370    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
371    fn rasterize_glyph(
372        &self,
373        font_id: FontId,
374        font_size: f32,
375        glyph_id: GlyphId,
376        subpixel_shift: Vector2F,
377        scale_factor: f32,
378        options: RasterizationOptions,
379    ) -> Option<(RectI, Vec<u8>)>;
380    fn layout_line(&self, text: &str, font_size: f32, runs: &[(usize, RunStyle)]) -> LineLayout;
381    fn wrap_line(&self, text: &str, font_id: FontId, font_size: f32, width: f32) -> Vec<usize>;
382}
383
384impl<'a> Default for WindowOptions<'a> {
385    fn default() -> Self {
386        Self {
387            bounds: WindowBounds::Maximized,
388            titlebar: Some(TitlebarOptions {
389                title: Default::default(),
390                appears_transparent: Default::default(),
391                traffic_light_position: Default::default(),
392            }),
393            center: false,
394            focus: true,
395            show: true,
396            kind: WindowKind::Normal,
397            is_movable: true,
398            screen: None,
399        }
400    }
401}