platform.rs

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