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
166    #[cfg(any(test, feature = "test-support"))]
167    fn as_test(&self) -> Option<&TestDispatcher> {
168        None
169    }
170}
171
172pub trait PlatformTextSystem: Send + Sync {
173    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()>;
174    fn all_font_families(&self) -> Vec<String>;
175    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
176    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
177    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
178    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
179    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
180    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
181    fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)>;
182    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
183    fn wrap_line(
184        &self,
185        text: &str,
186        font_id: FontId,
187        font_size: Pixels,
188        width: Pixels,
189    ) -> Vec<usize>;
190}
191
192#[derive(Clone, Debug)]
193pub struct AppMetadata {
194    pub os_name: &'static str,
195    pub os_version: Option<SemanticVersion>,
196    pub app_version: Option<SemanticVersion>,
197}
198
199#[derive(PartialEq, Eq, Hash, Clone)]
200pub enum AtlasKey {
201    Glyph(RenderGlyphParams),
202    Svg(RenderSvgParams),
203    Image(RenderImageParams),
204}
205
206impl AtlasKey {
207    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
208        match self {
209            AtlasKey::Glyph(params) => {
210                if params.is_emoji {
211                    AtlasTextureKind::Polychrome
212                } else {
213                    AtlasTextureKind::Monochrome
214                }
215            }
216            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
217            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
218        }
219    }
220}
221
222impl From<RenderGlyphParams> for AtlasKey {
223    fn from(params: RenderGlyphParams) -> Self {
224        Self::Glyph(params)
225    }
226}
227
228impl From<RenderSvgParams> for AtlasKey {
229    fn from(params: RenderSvgParams) -> Self {
230        Self::Svg(params)
231    }
232}
233
234impl From<RenderImageParams> for AtlasKey {
235    fn from(params: RenderImageParams) -> Self {
236        Self::Image(params)
237    }
238}
239
240pub trait PlatformAtlas: Send + Sync {
241    fn get_or_insert_with<'a>(
242        &self,
243        key: &AtlasKey,
244        build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Cow<'a, [u8]>)>,
245    ) -> Result<AtlasTile>;
246
247    fn clear(&self);
248}
249
250#[derive(Clone, Debug, PartialEq, Eq)]
251#[repr(C)]
252pub struct AtlasTile {
253    pub(crate) texture_id: AtlasTextureId,
254    pub(crate) tile_id: TileId,
255    pub(crate) bounds: Bounds<DevicePixels>,
256}
257
258#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
259#[repr(C)]
260pub(crate) struct AtlasTextureId {
261    // We use u32 instead of usize for Metal Shader Language compatibility
262    pub(crate) index: u32,
263    pub(crate) kind: AtlasTextureKind,
264}
265
266#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
267#[repr(C)]
268pub(crate) enum AtlasTextureKind {
269    Monochrome = 0,
270    Polychrome = 1,
271    Path = 2,
272}
273
274#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
275#[repr(C)]
276pub(crate) struct TileId(pub(crate) u32);
277
278impl From<etagere::AllocId> for TileId {
279    fn from(id: etagere::AllocId) -> Self {
280        Self(id.serialize())
281    }
282}
283
284impl From<TileId> for etagere::AllocId {
285    fn from(id: TileId) -> Self {
286        Self::deserialize(id.0)
287    }
288}
289
290pub trait PlatformInputHandler {
291    fn selected_text_range(&self) -> Option<Range<usize>>;
292    fn marked_text_range(&self) -> Option<Range<usize>>;
293    fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
294    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
295    fn replace_and_mark_text_in_range(
296        &mut self,
297        range_utf16: Option<Range<usize>>,
298        new_text: &str,
299        new_selected_range: Option<Range<usize>>,
300    );
301    fn unmark_text(&mut self);
302    fn bounds_for_range(&self, range_utf16: Range<usize>) -> Option<Bounds<f32>>;
303}
304
305#[derive(Debug)]
306pub struct WindowOptions {
307    pub bounds: WindowBounds,
308    pub titlebar: Option<TitlebarOptions>,
309    pub center: bool,
310    pub focus: bool,
311    pub show: bool,
312    pub kind: WindowKind,
313    pub is_movable: bool,
314    pub display_id: Option<DisplayId>,
315}
316
317impl Default for WindowOptions {
318    fn default() -> Self {
319        Self {
320            bounds: WindowBounds::default(),
321            titlebar: Some(TitlebarOptions {
322                title: Default::default(),
323                appears_transparent: Default::default(),
324                traffic_light_position: Default::default(),
325            }),
326            center: false,
327            focus: true,
328            show: true,
329            kind: WindowKind::Normal,
330            is_movable: true,
331            display_id: None,
332        }
333    }
334}
335
336#[derive(Debug, Default)]
337pub struct TitlebarOptions {
338    pub title: Option<SharedString>,
339    pub appears_transparent: bool,
340    pub traffic_light_position: Option<Point<Pixels>>,
341}
342
343#[derive(Copy, Clone, Debug)]
344pub enum Appearance {
345    Light,
346    VibrantLight,
347    Dark,
348    VibrantDark,
349}
350
351impl Default for Appearance {
352    fn default() -> Self {
353        Self::Light
354    }
355}
356
357#[derive(Copy, Clone, Debug, PartialEq, Eq)]
358pub enum WindowKind {
359    Normal,
360    PopUp,
361}
362
363#[derive(Copy, Clone, Debug, PartialEq, Default)]
364pub enum WindowBounds {
365    Fullscreen,
366    #[default]
367    Maximized,
368    Fixed(Bounds<GlobalPixels>),
369}
370
371#[derive(Copy, Clone, Debug)]
372pub enum WindowAppearance {
373    Light,
374    VibrantLight,
375    Dark,
376    VibrantDark,
377}
378
379impl Default for WindowAppearance {
380    fn default() -> Self {
381        Self::Light
382    }
383}
384
385#[derive(Copy, Clone, Debug, PartialEq, Default)]
386pub enum WindowPromptLevel {
387    #[default]
388    Info,
389    Warning,
390    Critical,
391}
392
393#[derive(Copy, Clone, Debug)]
394pub struct PathPromptOptions {
395    pub files: bool,
396    pub directories: bool,
397    pub multiple: bool,
398}
399
400#[derive(Copy, Clone, Debug)]
401pub enum PromptLevel {
402    Info,
403    Warning,
404    Critical,
405}
406
407#[derive(Copy, Clone, Debug)]
408pub enum CursorStyle {
409    Arrow,
410    ResizeLeftRight,
411    ResizeUpDown,
412    PointingHand,
413    IBeam,
414}
415
416impl Default for CursorStyle {
417    fn default() -> Self {
418        Self::Arrow
419    }
420}
421
422#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
423pub struct SemanticVersion {
424    major: usize,
425    minor: usize,
426    patch: usize,
427}
428
429impl FromStr for SemanticVersion {
430    type Err = anyhow::Error;
431
432    fn from_str(s: &str) -> Result<Self> {
433        let mut components = s.trim().split('.');
434        let major = components
435            .next()
436            .ok_or_else(|| anyhow!("missing major version number"))?
437            .parse()?;
438        let minor = components
439            .next()
440            .ok_or_else(|| anyhow!("missing minor version number"))?
441            .parse()?;
442        let patch = components
443            .next()
444            .ok_or_else(|| anyhow!("missing patch version number"))?
445            .parse()?;
446        Ok(Self {
447            major,
448            minor,
449            patch,
450        })
451    }
452}
453
454impl Display for SemanticVersion {
455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
457    }
458}
459
460#[derive(Clone, Debug, Eq, PartialEq)]
461pub struct ClipboardItem {
462    pub(crate) text: String,
463    pub(crate) metadata: Option<String>,
464}
465
466impl ClipboardItem {
467    pub fn new(text: String) -> Self {
468        Self {
469            text,
470            metadata: None,
471        }
472    }
473
474    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
475        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
476        self
477    }
478
479    pub fn text(&self) -> &String {
480        &self.text
481    }
482
483    pub fn metadata<T>(&self) -> Option<T>
484    where
485        T: for<'a> Deserialize<'a>,
486    {
487        self.metadata
488            .as_ref()
489            .and_then(|m| serde_json::from_str(m).ok())
490    }
491
492    pub(crate) fn text_hash(text: &str) -> u64 {
493        let mut hasher = SeaHasher::new();
494        text.hash(&mut hasher);
495        hasher.finish()
496    }
497}