platform.rs

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