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