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, Font, FontId, FontMetrics, GlyphId, Pixels, Point,
 10    RenderGlyphParams, Result, Scene, ShapedLine, SharedString, Size,
 11};
 12use anyhow::anyhow;
 13use async_task::Runnable;
 14use futures::channel::oneshot;
 15use seahash::SeaHasher;
 16use serde::{Deserialize, Serialize};
 17use std::ffi::c_void;
 18use std::hash::{Hash, Hasher};
 19use std::{
 20    any::Any,
 21    fmt::{self, Debug, Display},
 22    ops::Range,
 23    path::{Path, PathBuf},
 24    rc::Rc,
 25    str::FromStr,
 26    sync::Arc,
 27};
 28use uuid::Uuid;
 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 dispatcher(&self) -> Arc<dyn PlatformDispatcher>;
 45    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
 46
 47    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
 48    fn quit(&self);
 49    fn restart(&self);
 50    fn activate(&self, ignoring_other_apps: bool);
 51    fn hide(&self);
 52    fn hide_other_apps(&self);
 53    fn unhide_other_apps(&self);
 54
 55    fn screens(&self) -> Vec<Rc<dyn PlatformScreen>>;
 56    fn screen_by_id(&self, id: ScreenId) -> Option<Rc<dyn PlatformScreen>>;
 57    fn main_window(&self) -> Option<AnyWindowHandle>;
 58    fn open_window(
 59        &self,
 60        handle: AnyWindowHandle,
 61        options: WindowOptions,
 62    ) -> Box<dyn PlatformWindow>;
 63    // fn add_status_item(&self, _handle: AnyWindowHandle) -> Box<dyn PlatformWindow>;
 64
 65    fn open_url(&self, url: &str);
 66    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
 67    fn prompt_for_paths(
 68        &self,
 69        options: PathPromptOptions,
 70    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
 71    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
 72    fn reveal_path(&self, path: &Path);
 73
 74    fn on_become_active(&self, callback: Box<dyn FnMut()>);
 75    fn on_resign_active(&self, callback: Box<dyn FnMut()>);
 76    fn on_quit(&self, callback: Box<dyn FnMut()>);
 77    fn on_reopen(&self, callback: Box<dyn FnMut()>);
 78    fn on_event(&self, callback: Box<dyn FnMut(Event) -> bool>);
 79
 80    fn os_name(&self) -> &'static str;
 81    fn os_version(&self) -> Result<SemanticVersion>;
 82    fn app_version(&self) -> Result<SemanticVersion>;
 83    fn app_path(&self) -> Result<PathBuf>;
 84    fn local_timezone(&self) -> UtcOffset;
 85    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
 86
 87    fn set_cursor_style(&self, style: CursorStyle);
 88    fn should_auto_hide_scrollbars(&self) -> bool;
 89
 90    fn write_to_clipboard(&self, item: ClipboardItem);
 91    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 92
 93    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()>;
 94    fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>>;
 95    fn delete_credentials(&self, url: &str) -> Result<()>;
 96}
 97
 98pub trait PlatformScreen: Debug {
 99    fn id(&self) -> Option<ScreenId>;
100    fn handle(&self) -> PlatformScreenHandle;
101    fn as_any(&self) -> &dyn Any;
102    fn bounds(&self) -> Bounds<Pixels>;
103    fn content_bounds(&self) -> Bounds<Pixels>;
104}
105
106pub struct PlatformScreenHandle(pub *mut c_void);
107
108impl Debug for PlatformScreenHandle {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        write!(f, "PlatformScreenHandle({:p})", self.0)
111    }
112}
113
114unsafe impl Send for PlatformScreenHandle {}
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 screen(&self) -> Rc<dyn PlatformScreen>;
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 glyph_atlas(&self) -> Arc<dyn PlatformAtlas>;
151}
152
153pub trait PlatformDispatcher: Send + Sync {
154    fn is_main_thread(&self) -> bool;
155    fn run_on_main_thread(&self, task: Runnable);
156}
157
158pub trait PlatformTextSystem: Send + Sync {
159    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()>;
160    fn all_font_families(&self) -> Vec<String>;
161    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
162    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
163    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
164    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
165    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
166    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
167    fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)>;
168    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[(usize, FontId)]) -> ShapedLine;
169    fn wrap_line(
170        &self,
171        text: &str,
172        font_id: FontId,
173        font_size: Pixels,
174        width: Pixels,
175    ) -> Vec<usize>;
176}
177
178#[derive(PartialEq, Eq, Hash, Clone)]
179pub enum AtlasKey {
180    Glyph(RenderGlyphParams),
181    // Svg(RenderSvgParams),
182}
183
184impl From<RenderGlyphParams> for AtlasKey {
185    fn from(params: RenderGlyphParams) -> Self {
186        Self::Glyph(params)
187    }
188}
189
190pub trait PlatformAtlas: Send + Sync {
191    fn get_or_insert_with(
192        &self,
193        key: &AtlasKey,
194        build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Vec<u8>)>,
195    ) -> Result<AtlasTile>;
196
197    fn clear(&self);
198}
199
200#[derive(Clone, Debug, PartialEq, Eq)]
201#[repr(C)]
202pub struct AtlasTile {
203    pub(crate) texture_id: AtlasTextureId,
204    pub(crate) tile_id: TileId,
205    pub(crate) bounds: Bounds<DevicePixels>,
206}
207
208#[derive(Clone, Copy, Debug, PartialEq, Eq)]
209#[repr(C)]
210pub(crate) struct AtlasTextureId(pub(crate) u32); // We use u32 instead of usize for Metal Shader Language compatibility
211
212#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
213#[repr(C)]
214pub(crate) struct TileId(pub(crate) u32);
215
216impl From<etagere::AllocId> for TileId {
217    fn from(id: etagere::AllocId) -> Self {
218        Self(id.serialize())
219    }
220}
221
222impl From<TileId> for etagere::AllocId {
223    fn from(id: TileId) -> Self {
224        Self::deserialize(id.0)
225    }
226}
227
228pub trait PlatformInputHandler {
229    fn selected_text_range(&self) -> Option<Range<usize>>;
230    fn marked_text_range(&self) -> Option<Range<usize>>;
231    fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
232    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
233    fn replace_and_mark_text_in_range(
234        &mut self,
235        range_utf16: Option<Range<usize>>,
236        new_text: &str,
237        new_selected_range: Option<Range<usize>>,
238    );
239    fn unmark_text(&mut self);
240    fn bounds_for_range(&self, range_utf16: Range<usize>) -> Option<Bounds<f32>>;
241}
242
243#[derive(Copy, Clone, Debug, PartialEq)]
244pub struct ScreenId(pub(crate) Uuid);
245
246#[derive(Copy, Clone, Debug)]
247pub enum RasterizationOptions {
248    Alpha,
249    Bgra,
250}
251
252#[derive(Debug)]
253pub struct WindowOptions {
254    pub bounds: WindowBounds,
255    pub titlebar: Option<TitlebarOptions>,
256    pub center: bool,
257    pub focus: bool,
258    pub show: bool,
259    pub kind: WindowKind,
260    pub is_movable: bool,
261    pub screen: Option<PlatformScreenHandle>,
262}
263
264impl Default for WindowOptions {
265    fn default() -> Self {
266        Self {
267            bounds: WindowBounds::default(),
268            titlebar: Some(TitlebarOptions {
269                title: Default::default(),
270                appears_transparent: Default::default(),
271                traffic_light_position: Default::default(),
272            }),
273            center: false,
274            focus: true,
275            show: true,
276            kind: WindowKind::Normal,
277            is_movable: true,
278            screen: None,
279        }
280    }
281}
282
283#[derive(Debug, Default)]
284pub struct TitlebarOptions {
285    pub title: Option<SharedString>,
286    pub appears_transparent: bool,
287    pub traffic_light_position: Option<Point<Pixels>>,
288}
289
290#[derive(Copy, Clone, Debug)]
291pub enum Appearance {
292    Light,
293    VibrantLight,
294    Dark,
295    VibrantDark,
296}
297
298impl Default for Appearance {
299    fn default() -> Self {
300        Self::Light
301    }
302}
303
304#[derive(Copy, Clone, Debug, PartialEq, Eq)]
305pub enum WindowKind {
306    Normal,
307    PopUp,
308}
309
310#[derive(Copy, Clone, Debug, PartialEq, Default)]
311pub enum WindowBounds {
312    Fullscreen,
313    #[default]
314    Maximized,
315    Fixed(Bounds<Pixels>),
316}
317
318#[derive(Copy, Clone, Debug)]
319pub enum WindowAppearance {
320    Light,
321    VibrantLight,
322    Dark,
323    VibrantDark,
324}
325
326impl Default for WindowAppearance {
327    fn default() -> Self {
328        Self::Light
329    }
330}
331
332#[derive(Copy, Clone, Debug, PartialEq, Default)]
333pub enum WindowPromptLevel {
334    #[default]
335    Info,
336    Warning,
337    Critical,
338}
339
340#[derive(Copy, Clone, Debug)]
341pub struct PathPromptOptions {
342    pub files: bool,
343    pub directories: bool,
344    pub multiple: bool,
345}
346
347#[derive(Copy, Clone, Debug)]
348pub enum PromptLevel {
349    Info,
350    Warning,
351    Critical,
352}
353
354#[derive(Copy, Clone, Debug)]
355pub enum CursorStyle {
356    Arrow,
357    ResizeLeftRight,
358    ResizeUpDown,
359    PointingHand,
360    IBeam,
361}
362
363impl Default for CursorStyle {
364    fn default() -> Self {
365        Self::Arrow
366    }
367}
368
369#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
370pub struct SemanticVersion {
371    major: usize,
372    minor: usize,
373    patch: usize,
374}
375
376impl FromStr for SemanticVersion {
377    type Err = anyhow::Error;
378
379    fn from_str(s: &str) -> Result<Self> {
380        let mut components = s.trim().split('.');
381        let major = components
382            .next()
383            .ok_or_else(|| anyhow!("missing major version number"))?
384            .parse()?;
385        let minor = components
386            .next()
387            .ok_or_else(|| anyhow!("missing minor version number"))?
388            .parse()?;
389        let patch = components
390            .next()
391            .ok_or_else(|| anyhow!("missing patch version number"))?
392            .parse()?;
393        Ok(Self {
394            major,
395            minor,
396            patch,
397        })
398    }
399}
400
401impl Display for SemanticVersion {
402    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
404    }
405}
406
407#[derive(Clone, Debug, Eq, PartialEq)]
408pub struct ClipboardItem {
409    pub(crate) text: String,
410    pub(crate) metadata: Option<String>,
411}
412
413impl ClipboardItem {
414    pub fn new(text: String) -> Self {
415        Self {
416            text,
417            metadata: None,
418        }
419    }
420
421    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
422        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
423        self
424    }
425
426    pub fn text(&self) -> &String {
427        &self.text
428    }
429
430    pub fn metadata<T>(&self) -> Option<T>
431    where
432        T: for<'a> Deserialize<'a>,
433    {
434        self.metadata
435            .as_ref()
436            .and_then(|m| serde_json::from_str(m).ok())
437    }
438
439    pub(crate) fn text_hash(text: &str) -> u64 {
440        let mut hasher = SeaHasher::new();
441        text.hash(&mut hasher);
442        hasher.finish()
443    }
444}