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