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, FontFeatures, FontId, FontMetrics, FontStyle, FontWeight,
 10    ForegroundExecutor, GlyphId, LineLayout, Pixels, Point, Result, RunStyle, SharedString, Size,
 11};
 12use anyhow::anyhow;
 13use async_task::Runnable;
 14use futures::channel::oneshot;
 15use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle};
 16use seahash::SeaHasher;
 17use serde::{Deserialize, Serialize};
 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};
 28pub use time::UtcOffset;
 29use uuid::Uuid;
 30
 31pub use events::*;
 32pub use keystroke::*;
 33#[cfg(target_os = "macos")]
 34pub use mac::*;
 35#[cfg(any(test, feature = "test"))]
 36pub use test::*;
 37
 38#[cfg(target_os = "macos")]
 39pub(crate) fn current_platform() -> Rc<dyn Platform> {
 40    Rc::new(MacPlatform::new())
 41}
 42
 43pub trait Platform {
 44    fn executor(&self) -> Rc<ForegroundExecutor>;
 45    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
 46
 47    fn run(&self, on_finish_launching: Box<dyn 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: uuid::Uuid) -> 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 as_any(&self) -> &dyn Any;
100    fn bounds(&self) -> Bounds<Pixels>;
101    fn content_bounds(&self) -> Bounds<Pixels>;
102    fn display_uuid(&self) -> Option<Uuid>;
103}
104
105pub trait PlatformWindow: HasRawWindowHandle + HasRawDisplayHandle {
106    fn bounds(&self) -> WindowBounds;
107    fn content_size(&self) -> Size<Pixels>;
108    fn scale_factor(&self) -> f32;
109    fn titlebar_height(&self) -> Pixels;
110    fn appearance(&self) -> WindowAppearance;
111    fn screen(&self) -> Rc<dyn PlatformScreen>;
112    fn mouse_position(&self) -> Point<Pixels>;
113    fn as_any_mut(&mut self) -> &mut dyn Any;
114    fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>);
115    fn prompt(
116        &self,
117        level: WindowPromptLevel,
118        msg: &str,
119        answers: &[&str],
120    ) -> oneshot::Receiver<usize>;
121    fn activate(&self);
122    fn set_title(&mut self, title: &str);
123    fn set_edited(&mut self, edited: bool);
124    fn show_character_palette(&self);
125    fn minimize(&self);
126    fn zoom(&self);
127    fn toggle_full_screen(&self);
128    fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>);
129    fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>);
130    fn on_resize(&mut self, callback: Box<dyn FnMut()>);
131    fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>);
132    fn on_moved(&mut self, callback: Box<dyn FnMut()>);
133    fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>);
134    fn on_close(&mut self, callback: Box<dyn FnOnce()>);
135    fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>);
136    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool;
137}
138
139pub trait PlatformDispatcher: Send + Sync {
140    fn is_main_thread(&self) -> bool;
141    fn run_on_main_thread(&self, task: Runnable);
142}
143
144pub trait PlatformTextSystem: Send + Sync {
145    fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> anyhow::Result<()>;
146    fn all_families(&self) -> Vec<String>;
147    fn load_family(&self, name: &str, features: &FontFeatures) -> anyhow::Result<Vec<FontId>>;
148    fn select_font(
149        &self,
150        font_ids: &[FontId],
151        weight: FontWeight,
152        style: FontStyle,
153    ) -> anyhow::Result<FontId>;
154    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
155    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId)
156        -> anyhow::Result<Bounds<f32>>;
157    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>>;
158    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
159    fn rasterize_glyph(
160        &self,
161        font_id: FontId,
162        font_size: f32,
163        glyph_id: GlyphId,
164        subpixel_shift: Point<Pixels>,
165        scale_factor: f32,
166        options: RasterizationOptions,
167    ) -> Option<(Bounds<u32>, Vec<u8>)>;
168    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[(usize, RunStyle)]) -> LineLayout;
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
178pub trait InputHandler {
179    fn selected_text_range(&self) -> Option<Range<usize>>;
180    fn marked_text_range(&self) -> Option<Range<usize>>;
181    fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
182    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
183    fn replace_and_mark_text_in_range(
184        &mut self,
185        range_utf16: Option<Range<usize>>,
186        new_text: &str,
187        new_selected_range: Option<Range<usize>>,
188    );
189    fn unmark_text(&mut self);
190    fn bounds_for_range(&self, range_utf16: Range<usize>) -> Option<Bounds<f32>>;
191}
192
193#[derive(Copy, Clone, Debug)]
194pub enum RasterizationOptions {
195    Alpha,
196    Bgra,
197}
198
199#[derive(Debug)]
200pub struct WindowOptions {
201    pub bounds: WindowBounds,
202    pub titlebar: Option<TitlebarOptions>,
203    pub center: bool,
204    pub focus: bool,
205    pub show: bool,
206    pub kind: WindowKind,
207    pub is_movable: bool,
208    pub screen: Option<Rc<dyn PlatformScreen>>,
209}
210
211impl Default for WindowOptions {
212    fn default() -> Self {
213        Self {
214            bounds: WindowBounds::default(),
215            titlebar: Some(TitlebarOptions {
216                title: Default::default(),
217                appears_transparent: Default::default(),
218                traffic_light_position: Default::default(),
219            }),
220            center: false,
221            focus: true,
222            show: true,
223            kind: WindowKind::Normal,
224            is_movable: true,
225            screen: None,
226        }
227    }
228}
229
230#[derive(Debug, Default)]
231pub struct TitlebarOptions {
232    pub title: Option<SharedString>,
233    pub appears_transparent: bool,
234    pub traffic_light_position: Option<Point<Pixels>>,
235}
236
237#[derive(Copy, Clone, Debug)]
238pub enum Appearance {
239    Light,
240    VibrantLight,
241    Dark,
242    VibrantDark,
243}
244
245impl Default for Appearance {
246    fn default() -> Self {
247        Self::Light
248    }
249}
250
251#[derive(Copy, Clone, Debug, PartialEq, Eq)]
252pub enum WindowKind {
253    Normal,
254    PopUp,
255}
256
257#[derive(Copy, Clone, Debug, PartialEq, Default)]
258pub enum WindowBounds {
259    Fullscreen,
260    #[default]
261    Maximized,
262    Fixed(Bounds<Pixels>),
263}
264
265#[derive(Copy, Clone, Debug)]
266pub enum WindowAppearance {
267    Light,
268    VibrantLight,
269    Dark,
270    VibrantDark,
271}
272
273impl Default for WindowAppearance {
274    fn default() -> Self {
275        Self::Light
276    }
277}
278
279#[derive(Copy, Clone, Debug, PartialEq, Default)]
280pub enum WindowPromptLevel {
281    #[default]
282    Info,
283    Warning,
284    Critical,
285}
286
287#[derive(Copy, Clone, Debug)]
288pub struct PathPromptOptions {
289    pub files: bool,
290    pub directories: bool,
291    pub multiple: bool,
292}
293
294#[derive(Copy, Clone, Debug)]
295pub enum PromptLevel {
296    Info,
297    Warning,
298    Critical,
299}
300
301#[derive(Copy, Clone, Debug)]
302pub enum CursorStyle {
303    Arrow,
304    ResizeLeftRight,
305    ResizeUpDown,
306    PointingHand,
307    IBeam,
308}
309
310impl Default for CursorStyle {
311    fn default() -> Self {
312        Self::Arrow
313    }
314}
315
316#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
317pub struct SemanticVersion {
318    major: usize,
319    minor: usize,
320    patch: usize,
321}
322
323impl FromStr for SemanticVersion {
324    type Err = anyhow::Error;
325
326    fn from_str(s: &str) -> Result<Self> {
327        let mut components = s.trim().split('.');
328        let major = components
329            .next()
330            .ok_or_else(|| anyhow!("missing major version number"))?
331            .parse()?;
332        let minor = components
333            .next()
334            .ok_or_else(|| anyhow!("missing minor version number"))?
335            .parse()?;
336        let patch = components
337            .next()
338            .ok_or_else(|| anyhow!("missing patch version number"))?
339            .parse()?;
340        Ok(Self {
341            major,
342            minor,
343            patch,
344        })
345    }
346}
347
348impl Display for SemanticVersion {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
351    }
352}
353
354#[derive(Clone, Debug, Eq, PartialEq)]
355pub struct ClipboardItem {
356    pub(crate) text: String,
357    pub(crate) metadata: Option<String>,
358}
359
360impl ClipboardItem {
361    pub fn new(text: String) -> Self {
362        Self {
363            text,
364            metadata: None,
365        }
366    }
367
368    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
369        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
370        self
371    }
372
373    pub fn text(&self) -> &String {
374        &self.text
375    }
376
377    pub fn metadata<T>(&self) -> Option<T>
378    where
379        T: for<'a> Deserialize<'a>,
380    {
381        self.metadata
382            .as_ref()
383            .and_then(|m| serde_json::from_str(m).ok())
384    }
385
386    pub(crate) fn text_hash(text: &str) -> u64 {
387        let mut hasher = SeaHasher::new();
388        text.hash(&mut hasher);
389        hasher.finish()
390    }
391}