platform.rs

  1mod keystroke;
  2#[cfg(target_os = "macos")]
  3mod mac;
  4#[cfg(any(test, feature = "test-support"))]
  5mod test;
  6
  7use crate::{
  8    AnyWindowHandle, Bounds, DevicePixels, Executor, Font, FontId, FontMetrics, FontRun,
  9    GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point, RenderGlyphParams,
 10    RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size,
 11};
 12use anyhow::anyhow;
 13use async_task::Runnable;
 14use futures::channel::oneshot;
 15use seahash::SeaHasher;
 16use serde::{Deserialize, Serialize};
 17use std::borrow::Cow;
 18use std::hash::{Hash, Hasher};
 19use std::time::Duration;
 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};
 29
 30pub use keystroke::*;
 31#[cfg(target_os = "macos")]
 32pub use mac::*;
 33#[cfg(any(test, feature = "test-support"))]
 34pub use test::*;
 35pub use time::UtcOffset;
 36
 37#[cfg(target_os = "macos")]
 38pub(crate) fn current_platform() -> Arc<dyn Platform> {
 39    Arc::new(MacPlatform::new())
 40}
 41
 42pub(crate) trait Platform: 'static {
 43    fn executor(&self) -> Executor;
 44    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
 45
 46    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
 47    fn quit(&self);
 48    fn restart(&self);
 49    fn activate(&self, ignoring_other_apps: bool);
 50    fn hide(&self);
 51    fn hide_other_apps(&self);
 52    fn unhide_other_apps(&self);
 53
 54    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
 55    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
 56    fn main_window(&self) -> Option<AnyWindowHandle>;
 57    fn open_window(
 58        &self,
 59        handle: AnyWindowHandle,
 60        options: WindowOptions,
 61    ) -> Box<dyn PlatformWindow>;
 62
 63    fn set_display_link_output_callback(
 64        &self,
 65        display_id: DisplayId,
 66        callback: Box<dyn FnMut(&VideoTimestamp, &VideoTimestamp)>,
 67    );
 68    fn start_display_link(&self, display_id: DisplayId);
 69    fn stop_display_link(&self, display_id: DisplayId);
 70    // fn add_status_item(&self, _handle: AnyWindowHandle) -> Box<dyn PlatformWindow>;
 71
 72    fn open_url(&self, url: &str);
 73    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
 74    fn prompt_for_paths(
 75        &self,
 76        options: PathPromptOptions,
 77    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
 78    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
 79    fn reveal_path(&self, path: &Path);
 80
 81    fn on_become_active(&self, callback: Box<dyn FnMut()>);
 82    fn on_resign_active(&self, callback: Box<dyn FnMut()>);
 83    fn on_quit(&self, callback: Box<dyn FnMut()>);
 84    fn on_reopen(&self, callback: Box<dyn FnMut()>);
 85    fn on_event(&self, callback: Box<dyn FnMut(InputEvent) -> bool>);
 86
 87    fn os_name(&self) -> &'static str;
 88    fn os_version(&self) -> Result<SemanticVersion>;
 89    fn app_version(&self) -> Result<SemanticVersion>;
 90    fn app_path(&self) -> Result<PathBuf>;
 91    fn local_timezone(&self) -> UtcOffset;
 92    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
 93
 94    fn set_cursor_style(&self, style: CursorStyle);
 95    fn should_auto_hide_scrollbars(&self) -> bool;
 96
 97    fn write_to_clipboard(&self, item: ClipboardItem);
 98    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 99
100    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()>;
101    fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>>;
102    fn delete_credentials(&self, url: &str) -> Result<()>;
103}
104
105pub trait PlatformDisplay: Send + Sync + Debug {
106    fn id(&self) -> DisplayId;
107    fn as_any(&self) -> &dyn Any;
108    fn bounds(&self) -> Bounds<GlobalPixels>;
109}
110
111#[derive(PartialEq, Eq, Hash, Copy, Clone)]
112pub struct DisplayId(pub(crate) u32);
113
114impl Debug for DisplayId {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        write!(f, "DisplayId({})", self.0)
117    }
118}
119
120unsafe impl Send for DisplayId {}
121
122pub(crate) trait PlatformWindow {
123    fn bounds(&self) -> WindowBounds;
124    fn content_size(&self) -> Size<Pixels>;
125    fn scale_factor(&self) -> f32;
126    fn titlebar_height(&self) -> Pixels;
127    fn appearance(&self) -> WindowAppearance;
128    fn display(&self) -> Rc<dyn PlatformDisplay>;
129    fn mouse_position(&self) -> Point<Pixels>;
130    fn as_any_mut(&mut self) -> &mut dyn Any;
131    fn set_input_handler(&mut self, input_handler: Box<dyn PlatformInputHandler>);
132    fn prompt(
133        &self,
134        level: WindowPromptLevel,
135        msg: &str,
136        answers: &[&str],
137    ) -> oneshot::Receiver<usize>;
138    fn activate(&self);
139    fn set_title(&mut self, title: &str);
140    fn set_edited(&mut self, edited: bool);
141    fn show_character_palette(&self);
142    fn minimize(&self);
143    fn zoom(&self);
144    fn toggle_full_screen(&self);
145    fn on_input(&self, callback: Box<dyn FnMut(InputEvent) -> bool>);
146    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
147    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
148    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>);
149    fn on_moved(&self, callback: Box<dyn FnMut()>);
150    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
151    fn on_close(&self, callback: Box<dyn FnOnce()>);
152    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
153    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool;
154    fn draw(&self, scene: Scene);
155
156    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
157}
158
159pub trait PlatformDispatcher: Send + Sync {
160    fn is_main_thread(&self) -> bool;
161    fn dispatch(&self, runnable: Runnable);
162    fn dispatch_on_main_thread(&self, runnable: Runnable);
163    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
164    fn poll(&self) -> bool;
165    #[cfg(any(test, feature = "test-support"))]
166    fn advance_clock(&self, duration: Duration);
167}
168
169pub trait PlatformTextSystem: Send + Sync {
170    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()>;
171    fn all_font_families(&self) -> Vec<String>;
172    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
173    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
174    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
175    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
176    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
177    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
178    fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)>;
179    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> 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
189#[derive(Clone, Debug)]
190pub struct AppMetadata {
191    pub os_name: &'static str,
192    pub os_version: Option<SemanticVersion>,
193    pub app_version: Option<SemanticVersion>,
194}
195
196#[derive(PartialEq, Eq, Hash, Clone)]
197pub enum AtlasKey {
198    Glyph(RenderGlyphParams),
199    Svg(RenderSvgParams),
200    Image(RenderImageParams),
201}
202
203impl AtlasKey {
204    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
205        match self {
206            AtlasKey::Glyph(params) => {
207                if params.is_emoji {
208                    AtlasTextureKind::Polychrome
209                } else {
210                    AtlasTextureKind::Monochrome
211                }
212            }
213            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
214            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
215        }
216    }
217}
218
219impl From<RenderGlyphParams> for AtlasKey {
220    fn from(params: RenderGlyphParams) -> Self {
221        Self::Glyph(params)
222    }
223}
224
225impl From<RenderSvgParams> for AtlasKey {
226    fn from(params: RenderSvgParams) -> Self {
227        Self::Svg(params)
228    }
229}
230
231impl From<RenderImageParams> for AtlasKey {
232    fn from(params: RenderImageParams) -> Self {
233        Self::Image(params)
234    }
235}
236
237pub trait PlatformAtlas: Send + Sync {
238    fn get_or_insert_with<'a>(
239        &self,
240        key: &AtlasKey,
241        build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Cow<'a, [u8]>)>,
242    ) -> Result<AtlasTile>;
243
244    fn clear(&self);
245}
246
247#[derive(Clone, Debug, PartialEq, Eq)]
248#[repr(C)]
249pub struct AtlasTile {
250    pub(crate) texture_id: AtlasTextureId,
251    pub(crate) tile_id: TileId,
252    pub(crate) bounds: Bounds<DevicePixels>,
253}
254
255#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
256#[repr(C)]
257pub(crate) struct AtlasTextureId {
258    // We use u32 instead of usize for Metal Shader Language compatibility
259    pub(crate) index: u32,
260    pub(crate) kind: AtlasTextureKind,
261}
262
263#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
264#[repr(C)]
265pub(crate) enum AtlasTextureKind {
266    Monochrome = 0,
267    Polychrome = 1,
268    Path = 2,
269}
270
271#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
272#[repr(C)]
273pub(crate) struct TileId(pub(crate) u32);
274
275impl From<etagere::AllocId> for TileId {
276    fn from(id: etagere::AllocId) -> Self {
277        Self(id.serialize())
278    }
279}
280
281impl From<TileId> for etagere::AllocId {
282    fn from(id: TileId) -> Self {
283        Self::deserialize(id.0)
284    }
285}
286
287pub trait PlatformInputHandler {
288    fn selected_text_range(&self) -> Option<Range<usize>>;
289    fn marked_text_range(&self) -> Option<Range<usize>>;
290    fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
291    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
292    fn replace_and_mark_text_in_range(
293        &mut self,
294        range_utf16: Option<Range<usize>>,
295        new_text: &str,
296        new_selected_range: Option<Range<usize>>,
297    );
298    fn unmark_text(&mut self);
299    fn bounds_for_range(&self, range_utf16: Range<usize>) -> Option<Bounds<f32>>;
300}
301
302#[derive(Debug)]
303pub struct WindowOptions {
304    pub bounds: WindowBounds,
305    pub titlebar: Option<TitlebarOptions>,
306    pub center: bool,
307    pub focus: bool,
308    pub show: bool,
309    pub kind: WindowKind,
310    pub is_movable: bool,
311    pub display_id: Option<DisplayId>,
312}
313
314impl Default for WindowOptions {
315    fn default() -> Self {
316        Self {
317            bounds: WindowBounds::default(),
318            titlebar: Some(TitlebarOptions {
319                title: Default::default(),
320                appears_transparent: Default::default(),
321                traffic_light_position: Default::default(),
322            }),
323            center: false,
324            focus: true,
325            show: true,
326            kind: WindowKind::Normal,
327            is_movable: true,
328            display_id: None,
329        }
330    }
331}
332
333#[derive(Debug, Default)]
334pub struct TitlebarOptions {
335    pub title: Option<SharedString>,
336    pub appears_transparent: bool,
337    pub traffic_light_position: Option<Point<Pixels>>,
338}
339
340#[derive(Copy, Clone, Debug)]
341pub enum Appearance {
342    Light,
343    VibrantLight,
344    Dark,
345    VibrantDark,
346}
347
348impl Default for Appearance {
349    fn default() -> Self {
350        Self::Light
351    }
352}
353
354#[derive(Copy, Clone, Debug, PartialEq, Eq)]
355pub enum WindowKind {
356    Normal,
357    PopUp,
358}
359
360#[derive(Copy, Clone, Debug, PartialEq, Default)]
361pub enum WindowBounds {
362    Fullscreen,
363    #[default]
364    Maximized,
365    Fixed(Bounds<GlobalPixels>),
366}
367
368#[derive(Copy, Clone, Debug)]
369pub enum WindowAppearance {
370    Light,
371    VibrantLight,
372    Dark,
373    VibrantDark,
374}
375
376impl Default for WindowAppearance {
377    fn default() -> Self {
378        Self::Light
379    }
380}
381
382#[derive(Copy, Clone, Debug, PartialEq, Default)]
383pub enum WindowPromptLevel {
384    #[default]
385    Info,
386    Warning,
387    Critical,
388}
389
390#[derive(Copy, Clone, Debug)]
391pub struct PathPromptOptions {
392    pub files: bool,
393    pub directories: bool,
394    pub multiple: bool,
395}
396
397#[derive(Copy, Clone, Debug)]
398pub enum PromptLevel {
399    Info,
400    Warning,
401    Critical,
402}
403
404#[derive(Copy, Clone, Debug)]
405pub enum CursorStyle {
406    Arrow,
407    ResizeLeftRight,
408    ResizeUpDown,
409    PointingHand,
410    IBeam,
411}
412
413impl Default for CursorStyle {
414    fn default() -> Self {
415        Self::Arrow
416    }
417}
418
419#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
420pub struct SemanticVersion {
421    major: usize,
422    minor: usize,
423    patch: usize,
424}
425
426impl FromStr for SemanticVersion {
427    type Err = anyhow::Error;
428
429    fn from_str(s: &str) -> Result<Self> {
430        let mut components = s.trim().split('.');
431        let major = components
432            .next()
433            .ok_or_else(|| anyhow!("missing major version number"))?
434            .parse()?;
435        let minor = components
436            .next()
437            .ok_or_else(|| anyhow!("missing minor version number"))?
438            .parse()?;
439        let patch = components
440            .next()
441            .ok_or_else(|| anyhow!("missing patch version number"))?
442            .parse()?;
443        Ok(Self {
444            major,
445            minor,
446            patch,
447        })
448    }
449}
450
451impl Display for SemanticVersion {
452    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
454    }
455}
456
457#[derive(Clone, Debug, Eq, PartialEq)]
458pub struct ClipboardItem {
459    pub(crate) text: String,
460    pub(crate) metadata: Option<String>,
461}
462
463impl ClipboardItem {
464    pub fn new(text: String) -> Self {
465        Self {
466            text,
467            metadata: None,
468        }
469    }
470
471    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
472        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
473        self
474    }
475
476    pub fn text(&self) -> &String {
477        &self.text
478    }
479
480    pub fn metadata<T>(&self) -> Option<T>
481    where
482        T: for<'a> Deserialize<'a>,
483    {
484        self.metadata
485            .as_ref()
486            .and_then(|m| serde_json::from_str(m).ok())
487    }
488
489    pub(crate) fn text_hash(text: &str) -> u64 {
490        let mut hasher = SeaHasher::new();
491        text.hash(&mut hasher);
492        hasher.finish()
493    }
494}