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