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, MonochromeSprite,
10 Pixels, Point, RasterizedGlyphId, 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<RasterizedGlyphId>>;
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 rasterize_glyph(
167 &self,
168 font_id: FontId,
169 font_size: f32,
170 glyph_id: GlyphId,
171 subpixel_shift: Point<Pixels>,
172 scale_factor: f32,
173 options: RasterizationOptions,
174 ) -> Option<(Bounds<u32>, Vec<u8>)>;
175 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[(usize, FontId)]) -> ShapedLine;
176 fn wrap_line(
177 &self,
178 text: &str,
179 font_id: FontId,
180 font_size: Pixels,
181 width: Pixels,
182 ) -> Vec<usize>;
183}
184
185pub trait PlatformAtlas<Key>: Send + Sync {
186 fn get_or_insert_with(
187 &self,
188 key: Key,
189 build: &dyn Fn() -> (Size<DevicePixels>, Vec<u8>),
190 ) -> AtlasTile;
191
192 fn clear(&self);
193}
194
195#[derive(Clone, Debug)]
196#[repr(C)]
197pub struct AtlasTile {
198 pub(crate) texture_id: AtlasTextureId,
199 pub(crate) tile_id: TileId,
200 pub(crate) bounds_in_atlas: Bounds<DevicePixels>,
201}
202
203#[derive(Clone, Copy, Debug)]
204#[repr(C)]
205pub(crate) struct AtlasTextureId(pub(crate) usize);
206
207pub(crate) type TileId = etagere::AllocId;
208
209pub trait PlatformInputHandler {
210 fn selected_text_range(&self) -> Option<Range<usize>>;
211 fn marked_text_range(&self) -> Option<Range<usize>>;
212 fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
213 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
214 fn replace_and_mark_text_in_range(
215 &mut self,
216 range_utf16: Option<Range<usize>>,
217 new_text: &str,
218 new_selected_range: Option<Range<usize>>,
219 );
220 fn unmark_text(&mut self);
221 fn bounds_for_range(&self, range_utf16: Range<usize>) -> Option<Bounds<f32>>;
222}
223
224#[derive(Copy, Clone, Debug, PartialEq)]
225pub struct ScreenId(pub(crate) Uuid);
226
227#[derive(Copy, Clone, Debug)]
228pub enum RasterizationOptions {
229 Alpha,
230 Bgra,
231}
232
233#[derive(Debug)]
234pub struct WindowOptions {
235 pub bounds: WindowBounds,
236 pub titlebar: Option<TitlebarOptions>,
237 pub center: bool,
238 pub focus: bool,
239 pub show: bool,
240 pub kind: WindowKind,
241 pub is_movable: bool,
242 pub screen: Option<PlatformScreenHandle>,
243}
244
245impl Default for WindowOptions {
246 fn default() -> Self {
247 Self {
248 bounds: WindowBounds::default(),
249 titlebar: Some(TitlebarOptions {
250 title: Default::default(),
251 appears_transparent: Default::default(),
252 traffic_light_position: Default::default(),
253 }),
254 center: false,
255 focus: true,
256 show: true,
257 kind: WindowKind::Normal,
258 is_movable: true,
259 screen: None,
260 }
261 }
262}
263
264#[derive(Debug, Default)]
265pub struct TitlebarOptions {
266 pub title: Option<SharedString>,
267 pub appears_transparent: bool,
268 pub traffic_light_position: Option<Point<Pixels>>,
269}
270
271#[derive(Copy, Clone, Debug)]
272pub enum Appearance {
273 Light,
274 VibrantLight,
275 Dark,
276 VibrantDark,
277}
278
279impl Default for Appearance {
280 fn default() -> Self {
281 Self::Light
282 }
283}
284
285#[derive(Copy, Clone, Debug, PartialEq, Eq)]
286pub enum WindowKind {
287 Normal,
288 PopUp,
289}
290
291#[derive(Copy, Clone, Debug, PartialEq, Default)]
292pub enum WindowBounds {
293 Fullscreen,
294 #[default]
295 Maximized,
296 Fixed(Bounds<Pixels>),
297}
298
299#[derive(Copy, Clone, Debug)]
300pub enum WindowAppearance {
301 Light,
302 VibrantLight,
303 Dark,
304 VibrantDark,
305}
306
307impl Default for WindowAppearance {
308 fn default() -> Self {
309 Self::Light
310 }
311}
312
313#[derive(Copy, Clone, Debug, PartialEq, Default)]
314pub enum WindowPromptLevel {
315 #[default]
316 Info,
317 Warning,
318 Critical,
319}
320
321#[derive(Copy, Clone, Debug)]
322pub struct PathPromptOptions {
323 pub files: bool,
324 pub directories: bool,
325 pub multiple: bool,
326}
327
328#[derive(Copy, Clone, Debug)]
329pub enum PromptLevel {
330 Info,
331 Warning,
332 Critical,
333}
334
335#[derive(Copy, Clone, Debug)]
336pub enum CursorStyle {
337 Arrow,
338 ResizeLeftRight,
339 ResizeUpDown,
340 PointingHand,
341 IBeam,
342}
343
344impl Default for CursorStyle {
345 fn default() -> Self {
346 Self::Arrow
347 }
348}
349
350#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
351pub struct SemanticVersion {
352 major: usize,
353 minor: usize,
354 patch: usize,
355}
356
357impl FromStr for SemanticVersion {
358 type Err = anyhow::Error;
359
360 fn from_str(s: &str) -> Result<Self> {
361 let mut components = s.trim().split('.');
362 let major = components
363 .next()
364 .ok_or_else(|| anyhow!("missing major version number"))?
365 .parse()?;
366 let minor = components
367 .next()
368 .ok_or_else(|| anyhow!("missing minor version number"))?
369 .parse()?;
370 let patch = components
371 .next()
372 .ok_or_else(|| anyhow!("missing patch version number"))?
373 .parse()?;
374 Ok(Self {
375 major,
376 minor,
377 patch,
378 })
379 }
380}
381
382impl Display for SemanticVersion {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
385 }
386}
387
388#[derive(Clone, Debug, Eq, PartialEq)]
389pub struct ClipboardItem {
390 pub(crate) text: String,
391 pub(crate) metadata: Option<String>,
392}
393
394impl ClipboardItem {
395 pub fn new(text: String) -> Self {
396 Self {
397 text,
398 metadata: None,
399 }
400 }
401
402 pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
403 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
404 self
405 }
406
407 pub fn text(&self) -> &String {
408 &self.text
409 }
410
411 pub fn metadata<T>(&self) -> Option<T>
412 where
413 T: for<'a> Deserialize<'a>,
414 {
415 self.metadata
416 .as_ref()
417 .and_then(|m| serde_json::from_str(m).ok())
418 }
419
420 pub(crate) fn text_hash(text: &str) -> u64 {
421 let mut hasher = SeaHasher::new();
422 text.hash(&mut hasher);
423 hasher.finish()
424 }
425}