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    RenderGlyphParams, RenderSvgParams, 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::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};
 28use uuid::Uuid;
 29
 30pub use events::*;
 31pub use keystroke::*;
 32#[cfg(target_os = "macos")]
 33pub use mac::*;
 34#[cfg(any(test, feature = "test"))]
 35pub use test::*;
 36pub use time::UtcOffset;
 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 PlatformInputHandler>);
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(&self, callback: Box<dyn FnMut(Event) -> bool>);
140    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
141    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
142    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>);
143    fn on_moved(&self, callback: Box<dyn FnMut()>);
144    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
145    fn on_close(&self, callback: Box<dyn FnOnce()>);
146    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
147    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool;
148    fn draw(&self, scene: Scene);
149
150    fn monochrome_sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
151    fn polychrome_sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
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 glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
168    fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)>;
169    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[(usize, FontId)]) -> ShapedLine;
170    fn wrap_line(
171        &self,
172        text: &str,
173        font_id: FontId,
174        font_size: Pixels,
175        width: Pixels,
176    ) -> Vec<usize>;
177}
178
179#[derive(PartialEq, Eq, Hash, Clone)]
180pub enum AtlasKey {
181    Glyph(RenderGlyphParams),
182    Svg(RenderSvgParams),
183}
184
185impl From<RenderGlyphParams> for AtlasKey {
186    fn from(params: RenderGlyphParams) -> Self {
187        Self::Glyph(params)
188    }
189}
190
191impl From<RenderSvgParams> for AtlasKey {
192    fn from(params: RenderSvgParams) -> Self {
193        Self::Svg(params)
194    }
195}
196
197pub trait PlatformAtlas: Send + Sync {
198    fn get_or_insert_with(
199        &self,
200        key: &AtlasKey,
201        build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Vec<u8>)>,
202    ) -> Result<AtlasTile>;
203
204    fn clear(&self);
205}
206
207#[derive(Clone, Debug, PartialEq, Eq)]
208#[repr(C)]
209pub struct AtlasTile {
210    pub(crate) texture_id: AtlasTextureId,
211    pub(crate) tile_id: TileId,
212    pub(crate) bounds: Bounds<DevicePixels>,
213}
214
215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
216#[repr(C)]
217pub(crate) struct AtlasTextureId(pub(crate) u32); // We use u32 instead of usize for Metal Shader Language compatibility
218
219#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
220#[repr(C)]
221pub(crate) struct TileId(pub(crate) u32);
222
223impl From<etagere::AllocId> for TileId {
224    fn from(id: etagere::AllocId) -> Self {
225        Self(id.serialize())
226    }
227}
228
229impl From<TileId> for etagere::AllocId {
230    fn from(id: TileId) -> Self {
231        Self::deserialize(id.0)
232    }
233}
234
235pub trait PlatformInputHandler {
236    fn selected_text_range(&self) -> Option<Range<usize>>;
237    fn marked_text_range(&self) -> Option<Range<usize>>;
238    fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
239    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
240    fn replace_and_mark_text_in_range(
241        &mut self,
242        range_utf16: Option<Range<usize>>,
243        new_text: &str,
244        new_selected_range: Option<Range<usize>>,
245    );
246    fn unmark_text(&mut self);
247    fn bounds_for_range(&self, range_utf16: Range<usize>) -> Option<Bounds<f32>>;
248}
249
250#[derive(Copy, Clone, Debug, PartialEq)]
251pub struct ScreenId(pub(crate) Uuid);
252
253#[derive(Copy, Clone, Debug)]
254pub enum RasterizationOptions {
255    Alpha,
256    Bgra,
257}
258
259#[derive(Debug)]
260pub struct WindowOptions {
261    pub bounds: WindowBounds,
262    pub titlebar: Option<TitlebarOptions>,
263    pub center: bool,
264    pub focus: bool,
265    pub show: bool,
266    pub kind: WindowKind,
267    pub is_movable: bool,
268    pub screen: Option<PlatformScreenHandle>,
269}
270
271impl Default for WindowOptions {
272    fn default() -> Self {
273        Self {
274            bounds: WindowBounds::default(),
275            titlebar: Some(TitlebarOptions {
276                title: Default::default(),
277                appears_transparent: Default::default(),
278                traffic_light_position: Default::default(),
279            }),
280            center: false,
281            focus: true,
282            show: true,
283            kind: WindowKind::Normal,
284            is_movable: true,
285            screen: None,
286        }
287    }
288}
289
290#[derive(Debug, Default)]
291pub struct TitlebarOptions {
292    pub title: Option<SharedString>,
293    pub appears_transparent: bool,
294    pub traffic_light_position: Option<Point<Pixels>>,
295}
296
297#[derive(Copy, Clone, Debug)]
298pub enum Appearance {
299    Light,
300    VibrantLight,
301    Dark,
302    VibrantDark,
303}
304
305impl Default for Appearance {
306    fn default() -> Self {
307        Self::Light
308    }
309}
310
311#[derive(Copy, Clone, Debug, PartialEq, Eq)]
312pub enum WindowKind {
313    Normal,
314    PopUp,
315}
316
317#[derive(Copy, Clone, Debug, PartialEq, Default)]
318pub enum WindowBounds {
319    Fullscreen,
320    #[default]
321    Maximized,
322    Fixed(Bounds<Pixels>),
323}
324
325#[derive(Copy, Clone, Debug)]
326pub enum WindowAppearance {
327    Light,
328    VibrantLight,
329    Dark,
330    VibrantDark,
331}
332
333impl Default for WindowAppearance {
334    fn default() -> Self {
335        Self::Light
336    }
337}
338
339#[derive(Copy, Clone, Debug, PartialEq, Default)]
340pub enum WindowPromptLevel {
341    #[default]
342    Info,
343    Warning,
344    Critical,
345}
346
347#[derive(Copy, Clone, Debug)]
348pub struct PathPromptOptions {
349    pub files: bool,
350    pub directories: bool,
351    pub multiple: bool,
352}
353
354#[derive(Copy, Clone, Debug)]
355pub enum PromptLevel {
356    Info,
357    Warning,
358    Critical,
359}
360
361#[derive(Copy, Clone, Debug)]
362pub enum CursorStyle {
363    Arrow,
364    ResizeLeftRight,
365    ResizeUpDown,
366    PointingHand,
367    IBeam,
368}
369
370impl Default for CursorStyle {
371    fn default() -> Self {
372        Self::Arrow
373    }
374}
375
376#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
377pub struct SemanticVersion {
378    major: usize,
379    minor: usize,
380    patch: usize,
381}
382
383impl FromStr for SemanticVersion {
384    type Err = anyhow::Error;
385
386    fn from_str(s: &str) -> Result<Self> {
387        let mut components = s.trim().split('.');
388        let major = components
389            .next()
390            .ok_or_else(|| anyhow!("missing major version number"))?
391            .parse()?;
392        let minor = components
393            .next()
394            .ok_or_else(|| anyhow!("missing minor version number"))?
395            .parse()?;
396        let patch = components
397            .next()
398            .ok_or_else(|| anyhow!("missing patch version number"))?
399            .parse()?;
400        Ok(Self {
401            major,
402            minor,
403            patch,
404        })
405    }
406}
407
408impl Display for SemanticVersion {
409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
411    }
412}
413
414#[derive(Clone, Debug, Eq, PartialEq)]
415pub struct ClipboardItem {
416    pub(crate) text: String,
417    pub(crate) metadata: Option<String>,
418}
419
420impl ClipboardItem {
421    pub fn new(text: String) -> Self {
422        Self {
423            text,
424            metadata: None,
425        }
426    }
427
428    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
429        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
430        self
431    }
432
433    pub fn text(&self) -> &String {
434        &self.text
435    }
436
437    pub fn metadata<T>(&self) -> Option<T>
438    where
439        T: for<'a> Deserialize<'a>,
440    {
441        self.metadata
442            .as_ref()
443            .and_then(|m| serde_json::from_str(m).ok())
444    }
445
446    pub(crate) fn text_hash(text: &str) -> u64 {
447        let mut hasher = SeaHasher::new();
448        text.hash(&mut hasher);
449        hasher.finish()
450    }
451}