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