platform.rs

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