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