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, Executor, Font, FontId, FontMetrics, GlobalPixels,
 10    GlyphId, Pixels, Point, RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene,
 11    ShapedLine, SharedString, Size,
 12};
 13use anyhow::anyhow;
 14use async_task::Runnable;
 15use futures::channel::oneshot;
 16use seahash::SeaHasher;
 17use serde::{Deserialize, Serialize};
 18use std::borrow::Cow;
 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};
 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 executor(&self) -> Executor;
 45    fn display_linker(&self) -> Arc<dyn PlatformDisplayLinker>;
 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 displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
 57    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
 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 PlatformDisplay: Debug {
100    fn id(&self) -> DisplayId;
101    fn as_any(&self) -> &dyn Any;
102    fn bounds(&self) -> Bounds<GlobalPixels>;
103}
104
105#[derive(PartialEq, Eq, Hash, Copy, Clone)]
106pub struct DisplayId(pub(crate) u32);
107
108impl Debug for DisplayId {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        write!(f, "DisplayId({})", self.0)
111    }
112}
113
114unsafe impl Send for DisplayId {}
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 display(&self) -> Rc<dyn PlatformDisplay>;
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 sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
151}
152
153pub trait PlatformDispatcher: Send + Sync {
154    fn is_main_thread(&self) -> bool;
155    fn dispatch(&self, task: Runnable);
156    fn dispatch_on_main_thread(&self, task: Runnable);
157}
158
159pub trait PlatformDisplayLinker: Send + Sync {
160    fn set_output_callback(
161        &self,
162        display_id: DisplayId,
163        callback: Box<dyn FnMut(&VideoTimestamp, &VideoTimestamp)>,
164    );
165    fn start(&self, display_id: DisplayId);
166    fn stop(&self, display_id: DisplayId);
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: &[(usize, FontId)]) -> ShapedLine;
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(PartialEq, Eq, Hash, Clone)]
190pub enum AtlasKey {
191    Glyph(RenderGlyphParams),
192    Svg(RenderSvgParams),
193    Image(RenderImageParams),
194}
195
196impl AtlasKey {
197    pub fn is_monochrome(&self) -> bool {
198        match self {
199            AtlasKey::Glyph(params) => !params.is_emoji,
200            AtlasKey::Svg(_) => true,
201            AtlasKey::Image(_) => false,
202        }
203    }
204}
205
206impl From<RenderGlyphParams> for AtlasKey {
207    fn from(params: RenderGlyphParams) -> Self {
208        Self::Glyph(params)
209    }
210}
211
212impl From<RenderSvgParams> for AtlasKey {
213    fn from(params: RenderSvgParams) -> Self {
214        Self::Svg(params)
215    }
216}
217
218impl From<RenderImageParams> for AtlasKey {
219    fn from(params: RenderImageParams) -> Self {
220        Self::Image(params)
221    }
222}
223
224pub trait PlatformAtlas: Send + Sync {
225    fn get_or_insert_with<'a>(
226        &self,
227        key: &AtlasKey,
228        build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Cow<'a, [u8]>)>,
229    ) -> Result<AtlasTile>;
230
231    fn clear(&self);
232}
233
234#[derive(Clone, Debug, PartialEq, Eq)]
235#[repr(C)]
236pub struct AtlasTile {
237    pub(crate) texture_id: AtlasTextureId,
238    pub(crate) tile_id: TileId,
239    pub(crate) bounds: Bounds<DevicePixels>,
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq)]
243#[repr(C)]
244pub(crate) struct AtlasTextureId(pub(crate) u32); // We use u32 instead of usize for Metal Shader Language compatibility
245
246#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
247#[repr(C)]
248pub(crate) struct TileId(pub(crate) u32);
249
250impl From<etagere::AllocId> for TileId {
251    fn from(id: etagere::AllocId) -> Self {
252        Self(id.serialize())
253    }
254}
255
256impl From<TileId> for etagere::AllocId {
257    fn from(id: TileId) -> Self {
258        Self::deserialize(id.0)
259    }
260}
261
262pub trait PlatformInputHandler {
263    fn selected_text_range(&self) -> Option<Range<usize>>;
264    fn marked_text_range(&self) -> Option<Range<usize>>;
265    fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
266    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
267    fn replace_and_mark_text_in_range(
268        &mut self,
269        range_utf16: Option<Range<usize>>,
270        new_text: &str,
271        new_selected_range: Option<Range<usize>>,
272    );
273    fn unmark_text(&mut self);
274    fn bounds_for_range(&self, range_utf16: Range<usize>) -> Option<Bounds<f32>>;
275}
276
277#[derive(Debug)]
278pub struct WindowOptions {
279    pub bounds: WindowBounds,
280    pub titlebar: Option<TitlebarOptions>,
281    pub center: bool,
282    pub focus: bool,
283    pub show: bool,
284    pub kind: WindowKind,
285    pub is_movable: bool,
286    pub display_id: Option<DisplayId>,
287}
288
289impl Default for WindowOptions {
290    fn default() -> Self {
291        Self {
292            bounds: WindowBounds::default(),
293            titlebar: Some(TitlebarOptions {
294                title: Default::default(),
295                appears_transparent: Default::default(),
296                traffic_light_position: Default::default(),
297            }),
298            center: false,
299            focus: true,
300            show: true,
301            kind: WindowKind::Normal,
302            is_movable: true,
303            display_id: None,
304        }
305    }
306}
307
308#[derive(Debug, Default)]
309pub struct TitlebarOptions {
310    pub title: Option<SharedString>,
311    pub appears_transparent: bool,
312    pub traffic_light_position: Option<Point<Pixels>>,
313}
314
315#[derive(Copy, Clone, Debug)]
316pub enum Appearance {
317    Light,
318    VibrantLight,
319    Dark,
320    VibrantDark,
321}
322
323impl Default for Appearance {
324    fn default() -> Self {
325        Self::Light
326    }
327}
328
329#[derive(Copy, Clone, Debug, PartialEq, Eq)]
330pub enum WindowKind {
331    Normal,
332    PopUp,
333}
334
335#[derive(Copy, Clone, Debug, PartialEq, Default)]
336pub enum WindowBounds {
337    Fullscreen,
338    #[default]
339    Maximized,
340    Fixed(Bounds<GlobalPixels>),
341}
342
343#[derive(Copy, Clone, Debug)]
344pub enum WindowAppearance {
345    Light,
346    VibrantLight,
347    Dark,
348    VibrantDark,
349}
350
351impl Default for WindowAppearance {
352    fn default() -> Self {
353        Self::Light
354    }
355}
356
357#[derive(Copy, Clone, Debug, PartialEq, Default)]
358pub enum WindowPromptLevel {
359    #[default]
360    Info,
361    Warning,
362    Critical,
363}
364
365#[derive(Copy, Clone, Debug)]
366pub struct PathPromptOptions {
367    pub files: bool,
368    pub directories: bool,
369    pub multiple: bool,
370}
371
372#[derive(Copy, Clone, Debug)]
373pub enum PromptLevel {
374    Info,
375    Warning,
376    Critical,
377}
378
379#[derive(Copy, Clone, Debug)]
380pub enum CursorStyle {
381    Arrow,
382    ResizeLeftRight,
383    ResizeUpDown,
384    PointingHand,
385    IBeam,
386}
387
388impl Default for CursorStyle {
389    fn default() -> Self {
390        Self::Arrow
391    }
392}
393
394#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
395pub struct SemanticVersion {
396    major: usize,
397    minor: usize,
398    patch: usize,
399}
400
401impl FromStr for SemanticVersion {
402    type Err = anyhow::Error;
403
404    fn from_str(s: &str) -> Result<Self> {
405        let mut components = s.trim().split('.');
406        let major = components
407            .next()
408            .ok_or_else(|| anyhow!("missing major version number"))?
409            .parse()?;
410        let minor = components
411            .next()
412            .ok_or_else(|| anyhow!("missing minor version number"))?
413            .parse()?;
414        let patch = components
415            .next()
416            .ok_or_else(|| anyhow!("missing patch version number"))?
417            .parse()?;
418        Ok(Self {
419            major,
420            minor,
421            patch,
422        })
423    }
424}
425
426impl Display for SemanticVersion {
427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
429    }
430}
431
432#[derive(Clone, Debug, Eq, PartialEq)]
433pub struct ClipboardItem {
434    pub(crate) text: String,
435    pub(crate) metadata: Option<String>,
436}
437
438impl ClipboardItem {
439    pub fn new(text: String) -> Self {
440        Self {
441            text,
442            metadata: None,
443        }
444    }
445
446    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
447        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
448        self
449    }
450
451    pub fn text(&self) -> &String {
452        &self.text
453    }
454
455    pub fn metadata<T>(&self) -> Option<T>
456    where
457        T: for<'a> Deserialize<'a>,
458    {
459        self.metadata
460            .as_ref()
461            .and_then(|m| serde_json::from_str(m).ok())
462    }
463
464    pub(crate) fn text_hash(text: &str) -> u64 {
465        let mut hasher = SeaHasher::new();
466        text.hash(&mut hasher);
467        hasher.finish()
468    }
469}