1mod keystroke;
2#[cfg(target_os = "macos")]
3mod mac;
4#[cfg(any(test, feature = "test-support"))]
5mod test;
6
7use crate::{
8 AnyWindowHandle, BackgroundExecutor, Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun,
9 ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point,
10 RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size,
11};
12use anyhow::{anyhow, bail};
13use async_task::Runnable;
14use futures::channel::oneshot;
15use parking::Unparker;
16use seahash::SeaHasher;
17use serde::{Deserialize, Serialize};
18use sqlez::bindable::{Bind, Column, StaticColumnCount};
19use sqlez::statement::Statement;
20use std::borrow::Cow;
21use std::hash::{Hash, Hasher};
22use std::time::Duration;
23use std::{
24 any::Any,
25 fmt::{self, Debug, Display},
26 ops::Range,
27 path::{Path, PathBuf},
28 rc::Rc,
29 str::FromStr,
30 sync::Arc,
31};
32use uuid::Uuid;
33
34pub use keystroke::*;
35#[cfg(target_os = "macos")]
36pub use mac::*;
37#[cfg(any(test, feature = "test-support"))]
38pub use test::*;
39pub use time::UtcOffset;
40
41#[cfg(target_os = "macos")]
42pub(crate) fn current_platform() -> Rc<dyn Platform> {
43 Rc::new(MacPlatform::new())
44}
45
46pub(crate) trait Platform: 'static {
47 fn background_executor(&self) -> BackgroundExecutor;
48 fn foreground_executor(&self) -> ForegroundExecutor;
49 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
50
51 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
52 fn quit(&self);
53 fn restart(&self);
54 fn activate(&self, ignoring_other_apps: bool);
55 fn hide(&self);
56 fn hide_other_apps(&self);
57 fn unhide_other_apps(&self);
58
59 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
60 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
61 fn main_window(&self) -> Option<AnyWindowHandle>;
62 fn open_window(
63 &self,
64 handle: AnyWindowHandle,
65 options: WindowOptions,
66 ) -> Box<dyn PlatformWindow>;
67
68 fn set_display_link_output_callback(
69 &self,
70 display_id: DisplayId,
71 callback: Box<dyn FnMut(&VideoTimestamp, &VideoTimestamp)>,
72 );
73 fn start_display_link(&self, display_id: DisplayId);
74 fn stop_display_link(&self, display_id: DisplayId);
75 // fn add_status_item(&self, _handle: AnyWindowHandle) -> Box<dyn PlatformWindow>;
76
77 fn open_url(&self, url: &str);
78 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
79 fn prompt_for_paths(
80 &self,
81 options: PathPromptOptions,
82 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>;
83 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>>;
84 fn reveal_path(&self, path: &Path);
85
86 fn on_become_active(&self, callback: Box<dyn FnMut()>);
87 fn on_resign_active(&self, callback: Box<dyn FnMut()>);
88 fn on_quit(&self, callback: Box<dyn FnMut()>);
89 fn on_reopen(&self, callback: Box<dyn FnMut()>);
90 fn on_event(&self, callback: Box<dyn FnMut(InputEvent) -> bool>);
91
92 fn os_name(&self) -> &'static str;
93 fn os_version(&self) -> Result<SemanticVersion>;
94 fn app_version(&self) -> Result<SemanticVersion>;
95 fn app_path(&self) -> Result<PathBuf>;
96 fn local_timezone(&self) -> UtcOffset;
97 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
98
99 fn set_cursor_style(&self, style: CursorStyle);
100 fn should_auto_hide_scrollbars(&self) -> bool;
101
102 fn write_to_clipboard(&self, item: ClipboardItem);
103 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
104
105 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()>;
106 fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>>;
107 fn delete_credentials(&self, url: &str) -> Result<()>;
108}
109
110pub trait PlatformDisplay: Send + Sync + Debug {
111 fn id(&self) -> DisplayId;
112 /// Returns a stable identifier for this display that can be persisted and used
113 /// across system restarts.
114 fn uuid(&self) -> Result<Uuid>;
115 fn as_any(&self) -> &dyn Any;
116 fn bounds(&self) -> Bounds<GlobalPixels>;
117}
118
119#[derive(PartialEq, Eq, Hash, Copy, Clone)]
120pub struct DisplayId(pub(crate) u32);
121
122impl Debug for DisplayId {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 write!(f, "DisplayId({})", self.0)
125 }
126}
127
128unsafe impl Send for DisplayId {}
129
130pub(crate) trait PlatformWindow {
131 fn bounds(&self) -> WindowBounds;
132 fn content_size(&self) -> Size<Pixels>;
133 fn scale_factor(&self) -> f32;
134 fn titlebar_height(&self) -> Pixels;
135 fn appearance(&self) -> WindowAppearance;
136 fn display(&self) -> Rc<dyn PlatformDisplay>;
137 fn mouse_position(&self) -> Point<Pixels>;
138 fn as_any_mut(&mut self) -> &mut dyn Any;
139 fn set_input_handler(&mut self, input_handler: Box<dyn PlatformInputHandler>);
140 fn prompt(
141 &self,
142 level: WindowPromptLevel,
143 msg: &str,
144 answers: &[&str],
145 ) -> oneshot::Receiver<usize>;
146 fn activate(&self);
147 fn set_title(&mut self, title: &str);
148 fn set_edited(&mut self, edited: bool);
149 fn show_character_palette(&self);
150 fn minimize(&self);
151 fn zoom(&self);
152 fn toggle_full_screen(&self);
153 fn on_input(&self, callback: Box<dyn FnMut(InputEvent) -> bool>);
154 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
155 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
156 fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>);
157 fn on_moved(&self, callback: Box<dyn FnMut()>);
158 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
159 fn on_close(&self, callback: Box<dyn FnOnce()>);
160 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
161 fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool;
162 fn draw(&self, scene: Scene);
163
164 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
165}
166
167pub trait PlatformDispatcher: Send + Sync {
168 fn is_main_thread(&self) -> bool;
169 fn dispatch(&self, runnable: Runnable);
170 fn dispatch_on_main_thread(&self, runnable: Runnable);
171 fn dispatch_after(&self, duration: Duration, runnable: Runnable);
172 fn poll(&self, background_only: bool) -> bool;
173 fn park(&self);
174 fn unparker(&self) -> Unparker;
175
176 #[cfg(any(test, feature = "test-support"))]
177 fn as_test(&self) -> Option<&TestDispatcher> {
178 None
179 }
180}
181
182pub trait PlatformTextSystem: Send + Sync {
183 fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()>;
184 fn all_font_families(&self) -> Vec<String>;
185 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
186 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
187 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
188 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
189 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
190 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
191 fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)>;
192 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
193 fn wrap_line(
194 &self,
195 text: &str,
196 font_id: FontId,
197 font_size: Pixels,
198 width: Pixels,
199 ) -> Vec<usize>;
200}
201
202#[derive(Clone, Debug)]
203pub struct AppMetadata {
204 pub os_name: &'static str,
205 pub os_version: Option<SemanticVersion>,
206 pub app_version: Option<SemanticVersion>,
207}
208
209#[derive(PartialEq, Eq, Hash, Clone)]
210pub enum AtlasKey {
211 Glyph(RenderGlyphParams),
212 Svg(RenderSvgParams),
213 Image(RenderImageParams),
214}
215
216impl AtlasKey {
217 pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
218 match self {
219 AtlasKey::Glyph(params) => {
220 if params.is_emoji {
221 AtlasTextureKind::Polychrome
222 } else {
223 AtlasTextureKind::Monochrome
224 }
225 }
226 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
227 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
228 }
229 }
230}
231
232impl From<RenderGlyphParams> for AtlasKey {
233 fn from(params: RenderGlyphParams) -> Self {
234 Self::Glyph(params)
235 }
236}
237
238impl From<RenderSvgParams> for AtlasKey {
239 fn from(params: RenderSvgParams) -> Self {
240 Self::Svg(params)
241 }
242}
243
244impl From<RenderImageParams> for AtlasKey {
245 fn from(params: RenderImageParams) -> Self {
246 Self::Image(params)
247 }
248}
249
250pub trait PlatformAtlas: Send + Sync {
251 fn get_or_insert_with<'a>(
252 &self,
253 key: &AtlasKey,
254 build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Cow<'a, [u8]>)>,
255 ) -> Result<AtlasTile>;
256
257 fn clear(&self);
258}
259
260#[derive(Clone, Debug, PartialEq, Eq)]
261#[repr(C)]
262pub struct AtlasTile {
263 pub(crate) texture_id: AtlasTextureId,
264 pub(crate) tile_id: TileId,
265 pub(crate) bounds: Bounds<DevicePixels>,
266}
267
268#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
269#[repr(C)]
270pub(crate) struct AtlasTextureId {
271 // We use u32 instead of usize for Metal Shader Language compatibility
272 pub(crate) index: u32,
273 pub(crate) kind: AtlasTextureKind,
274}
275
276#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
277#[repr(C)]
278pub(crate) enum AtlasTextureKind {
279 Monochrome = 0,
280 Polychrome = 1,
281 Path = 2,
282}
283
284#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
285#[repr(C)]
286pub(crate) struct TileId(pub(crate) u32);
287
288impl From<etagere::AllocId> for TileId {
289 fn from(id: etagere::AllocId) -> Self {
290 Self(id.serialize())
291 }
292}
293
294impl From<TileId> for etagere::AllocId {
295 fn from(id: TileId) -> Self {
296 Self::deserialize(id.0)
297 }
298}
299
300pub trait PlatformInputHandler {
301 fn selected_text_range(&self) -> Option<Range<usize>>;
302 fn marked_text_range(&self) -> Option<Range<usize>>;
303 fn text_for_range(&self, range_utf16: Range<usize>) -> Option<String>;
304 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str);
305 fn replace_and_mark_text_in_range(
306 &mut self,
307 range_utf16: Option<Range<usize>>,
308 new_text: &str,
309 new_selected_range: Option<Range<usize>>,
310 );
311 fn unmark_text(&mut self);
312 fn bounds_for_range(&self, range_utf16: Range<usize>) -> Option<Bounds<f32>>;
313}
314
315#[derive(Debug)]
316pub struct WindowOptions {
317 pub bounds: WindowBounds,
318 pub titlebar: Option<TitlebarOptions>,
319 pub center: bool,
320 pub focus: bool,
321 pub show: bool,
322 pub kind: WindowKind,
323 pub is_movable: bool,
324 pub display_id: Option<DisplayId>,
325}
326
327impl Default for WindowOptions {
328 fn default() -> Self {
329 Self {
330 bounds: WindowBounds::default(),
331 titlebar: Some(TitlebarOptions {
332 title: Default::default(),
333 appears_transparent: Default::default(),
334 traffic_light_position: Default::default(),
335 }),
336 center: false,
337 focus: true,
338 show: true,
339 kind: WindowKind::Normal,
340 is_movable: true,
341 display_id: None,
342 }
343 }
344}
345
346#[derive(Debug, Default)]
347pub struct TitlebarOptions {
348 pub title: Option<SharedString>,
349 pub appears_transparent: bool,
350 pub traffic_light_position: Option<Point<Pixels>>,
351}
352
353#[derive(Copy, Clone, Debug)]
354pub enum Appearance {
355 Light,
356 VibrantLight,
357 Dark,
358 VibrantDark,
359}
360
361impl Default for Appearance {
362 fn default() -> Self {
363 Self::Light
364 }
365}
366
367#[derive(Copy, Clone, Debug, PartialEq, Eq)]
368pub enum WindowKind {
369 Normal,
370 PopUp,
371}
372
373#[derive(Copy, Clone, Debug, PartialEq, Default)]
374pub enum WindowBounds {
375 Fullscreen,
376 #[default]
377 Maximized,
378 Fixed(Bounds<GlobalPixels>),
379}
380
381impl StaticColumnCount for WindowBounds {
382 fn column_count() -> usize {
383 5
384 }
385}
386
387impl Bind for WindowBounds {
388 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
389 let (region, next_index) = match self {
390 WindowBounds::Fullscreen => {
391 let next_index = statement.bind(&"Fullscreen", start_index)?;
392 (None, next_index)
393 }
394 WindowBounds::Maximized => {
395 let next_index = statement.bind(&"Maximized", start_index)?;
396 (None, next_index)
397 }
398 WindowBounds::Fixed(region) => {
399 let next_index = statement.bind(&"Fixed", start_index)?;
400 (Some(*region), next_index)
401 }
402 };
403
404 statement.bind(
405 ®ion.map(|region| {
406 (
407 region.origin.x,
408 region.origin.y,
409 region.size.width,
410 region.size.height,
411 )
412 }),
413 next_index,
414 )
415 }
416}
417
418impl Column for WindowBounds {
419 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
420 let (window_state, next_index) = String::column(statement, start_index)?;
421 let bounds = match window_state.as_str() {
422 "Fullscreen" => WindowBounds::Fullscreen,
423 "Maximized" => WindowBounds::Maximized,
424 "Fixed" => {
425 // let ((x, y, width, height), _) = Column::column(statement, next_index)?;
426 // WindowBounds::Fixed(RectF::new(
427 // Vector2F::new(x, y),
428 // Vector2F::new(width, height),
429 // ))
430 todo!()
431 }
432 _ => bail!("Window State did not have a valid string"),
433 };
434
435 Ok((bounds, next_index + 4))
436 }
437}
438
439#[derive(Copy, Clone, Debug)]
440pub enum WindowAppearance {
441 Light,
442 VibrantLight,
443 Dark,
444 VibrantDark,
445}
446
447impl Default for WindowAppearance {
448 fn default() -> Self {
449 Self::Light
450 }
451}
452
453#[derive(Copy, Clone, Debug, PartialEq, Default)]
454pub enum WindowPromptLevel {
455 #[default]
456 Info,
457 Warning,
458 Critical,
459}
460
461#[derive(Copy, Clone, Debug)]
462pub struct PathPromptOptions {
463 pub files: bool,
464 pub directories: bool,
465 pub multiple: bool,
466}
467
468#[derive(Copy, Clone, Debug)]
469pub enum PromptLevel {
470 Info,
471 Warning,
472 Critical,
473}
474
475#[derive(Copy, Clone, Debug)]
476pub enum CursorStyle {
477 Arrow,
478 ResizeLeftRight,
479 ResizeUpDown,
480 PointingHand,
481 IBeam,
482}
483
484impl Default for CursorStyle {
485 fn default() -> Self {
486 Self::Arrow
487 }
488}
489
490#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
491pub struct SemanticVersion {
492 major: usize,
493 minor: usize,
494 patch: usize,
495}
496
497impl FromStr for SemanticVersion {
498 type Err = anyhow::Error;
499
500 fn from_str(s: &str) -> Result<Self> {
501 let mut components = s.trim().split('.');
502 let major = components
503 .next()
504 .ok_or_else(|| anyhow!("missing major version number"))?
505 .parse()?;
506 let minor = components
507 .next()
508 .ok_or_else(|| anyhow!("missing minor version number"))?
509 .parse()?;
510 let patch = components
511 .next()
512 .ok_or_else(|| anyhow!("missing patch version number"))?
513 .parse()?;
514 Ok(Self {
515 major,
516 minor,
517 patch,
518 })
519 }
520}
521
522impl Display for SemanticVersion {
523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
525 }
526}
527
528#[derive(Clone, Debug, Eq, PartialEq)]
529pub struct ClipboardItem {
530 pub(crate) text: String,
531 pub(crate) metadata: Option<String>,
532}
533
534impl ClipboardItem {
535 pub fn new(text: String) -> Self {
536 Self {
537 text,
538 metadata: None,
539 }
540 }
541
542 pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
543 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
544 self
545 }
546
547 pub fn text(&self) -> &String {
548 &self.text
549 }
550
551 pub fn metadata<T>(&self) -> Option<T>
552 where
553 T: for<'a> Deserialize<'a>,
554 {
555 self.metadata
556 .as_ref()
557 .and_then(|m| serde_json::from_str(m).ok())
558 }
559
560 pub(crate) fn text_hash(text: &str) -> u64 {
561 let mut hasher = SeaHasher::new();
562 text.hash(&mut hasher);
563 hasher.finish()
564 }
565}