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