nsh_core/platform.rs
1//! What the platform reports about a surface (its size, safe area,
2//! keyboard, appearance, device) and the HTTP requests it carries out: the
3//! data both Rust components and JS read, with or without a JS runtime.
4
5pub mod clipboard;
6
7use crate::geometry::{Edges, Points, Size};
8
9/// The native component of `nsh/mobile`'s `TabBar`, which the iOS and
10/// Android backends register themselves (`TabBarComponent.java`'s `NAME` keeps
11/// the same name).
12pub const TAB_BAR_COMPONENT: &str = "nsh/tab-bar";
13
14/// Whether native component `name` is NSH's own: names under `nsh/` are, and
15/// an embedding app's registration of one is refused, so it can never
16/// replace what NSH's exports render.
17pub fn is_reserved_component(name: &str) -> bool {
18 name.starts_with("nsh/")
19}
20
21/// The system appearance.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum ColorScheme {
24 /// Light mode.
25 #[default]
26 Light,
27 /// Dark mode.
28 Dark,
29}
30
31/// The appearance an app asks for (`nsh.json` `"appearance"`, TS
32/// `setColorScheme`): one of its own, or the system's.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
34pub enum Appearance {
35 /// The system appearance (default).
36 #[default]
37 System,
38 /// Always light.
39 Light,
40 /// Always dark.
41 Dark,
42}
43
44impl Appearance {
45 /// The color scheme shown when the system's is `system`.
46 pub fn resolve(self, system: ColorScheme) -> ColorScheme {
47 match self {
48 Appearance::System => system,
49 Appearance::Light => ColorScheme::Light,
50 Appearance::Dark => ColorScheme::Dark,
51 }
52 }
53}
54
55/// The operating system (`platform.os`).
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum Os {
58 /// iOS, iPadOS, Mac Catalyst.
59 Ios,
60 /// Android.
61 Android,
62 /// macOS (a desktop backend).
63 MacOs,
64 /// Windows.
65 Windows,
66 /// Linux.
67 Linux,
68 /// A web browser (the WebAssembly runtime): phone, tablet or desktop
69 /// by [`Idiom`].
70 Web,
71}
72
73impl Os {
74 /// Its `platform.os` name.
75 pub fn name(self) -> &'static str {
76 match self {
77 Os::Ios => "ios",
78 Os::Android => "android",
79 Os::MacOs => "macos",
80 Os::Windows => "windows",
81 Os::Linux => "linux",
82 Os::Web => "web",
83 }
84 }
85
86 /// The OS of a desktop backend (macOS, Windows, Linux): it has windows
87 /// and menus (`nsh/desktop`). Desktop behavior (`desktop={{…}}` props,
88 /// `platform.select({ desktop })`) also covers desktop-class browsers:
89 /// [`Environment::desktop`].
90 pub fn is_desktop(self) -> bool {
91 matches!(self, Os::MacOs | Os::Windows | Os::Linux)
92 }
93}
94
95impl Default for Os {
96 /// The mobile OS of this build (headless runs, `nsh test`, behave as iOS); desktop
97 /// backends set theirs.
98 fn default() -> Self {
99 if cfg!(target_os = "android") {
100 Os::Android
101 } else {
102 Os::Ios
103 }
104 }
105}
106
107/// The kind of device (`platform.idiom`).
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
109pub enum Idiom {
110 /// A phone.
111 #[default]
112 Phone,
113 /// A tablet.
114 Pad,
115 /// A Mac (Mac Catalyst).
116 Mac,
117 /// A TV.
118 Tv,
119 /// A desktop computer (a desktop backend, or a browser with a mouse and
120 /// a wide viewport; Mac Catalyst is [`Idiom::Mac`]).
121 Desktop,
122}
123
124impl Idiom {
125 /// Whether desktop behavior applies on `os` in this idiom: a desktop
126 /// OS, or a browser in the desktop idiom (TS: `platform.idiom` `"desktop"`).
127 pub fn desktop_on(self, os: Os) -> bool {
128 os.is_desktop() || (os == Os::Web && self == Idiom::Desktop)
129 }
130}
131
132/// What the platform knows about the surface.
133#[derive(Debug, Clone, Copy, PartialEq)]
134pub struct Environment {
135 /// Size of the surface in points.
136 pub window: Size<Points>,
137 /// Insets not covered by system UI (notch, home indicator, title bar).
138 pub safe_area: Edges<Points>,
139 /// The title bar's area while the app hides it (desktops,
140 /// [`crate::desktop::TitleBarStyle::Hidden`]): `top` is its height,
141 /// `left` and `right` the widths the system's window controls take at
142 /// its ends (`bottom` is 0); all 0 while the system shows its title
143 /// bar.
144 pub title_bar: Edges<Points>,
145 /// Height of the software keyboard over the surface; 0 when hidden.
146 pub keyboard_height: Points,
147 /// Duration of the keyboard's show / hide animation in seconds.
148 pub keyboard_duration: f32,
149 /// Light or dark appearance.
150 pub color_scheme: ColorScheme,
151 /// Preferred text size relative to the default (1.0).
152 pub font_scale: f32,
153 /// The user's language is written right to left.
154 pub rtl: bool,
155 /// The user asked for less motion (iOS Reduce Motion, Android's
156 /// animator duration scale at 0).
157 pub reduce_motion: bool,
158 /// Device pixels per point.
159 pub pixel_ratio: f32,
160 /// A screen reader runs (VoiceOver, TalkBack).
161 pub screen_reader: bool,
162 /// The operating system.
163 pub os: Os,
164 /// The OS version: major and minor (iOS, desktops), Android's API level
165 /// and 0.
166 pub os_version: (u16, u16),
167 /// The kind of device.
168 pub idiom: Idiom,
169 /// A browser on an Apple platform (macOS, iOS): its keyboard shortcuts
170 /// follow Apple's conventions ([`crate::keymap::apple_keys`]: `mod` is
171 /// Command, labels use ⌘). Only read for [`Os::Web`]; the other OSes
172 /// imply theirs.
173 pub apple_keyboard: bool,
174 /// The user's locale (number and date formats: `Intl`'s default).
175 pub locale: Locale,
176 /// The app embedding NSH answers `nsh/host`'s calls
177 /// ([`crate::Command::HostCall`]); without it, they reject at once.
178 pub host: bool,
179}
180
181impl Environment {
182 /// Desktop behavior applies: a desktop OS, or a browser in the desktop
183 /// idiom (`desktop={{…}}` props, `platform.select({ desktop })`,
184 /// `platform.idiom` `"desktop"`).
185 pub fn desktop(&self) -> bool {
186 self.idiom.desktop_on(self.os)
187 }
188}
189
190impl Default for Environment {
191 fn default() -> Self {
192 Self {
193 window: Size::default(),
194 safe_area: Edges::default(),
195 title_bar: Edges::default(),
196 keyboard_height: Points(0.0),
197 keyboard_duration: 0.25,
198 color_scheme: ColorScheme::Light,
199 font_scale: 1.0,
200 rtl: false,
201 reduce_motion: false,
202 pixel_ratio: 1.0,
203 screen_reader: false,
204 os: Os::default(),
205 os_version: (0, 0),
206 idiom: Idiom::Phone,
207 apple_keyboard: false,
208 locale: Locale::EN_US,
209 host: false,
210 }
211 }
212}
213
214/// The settings an embedding app gives its surfaces in place of the
215/// system's (`None`: the system's): its own language and text size, for an
216/// app inside a native app that lets its users switch them. The platforms
217/// write them over what they read from the system ([`Self::apply`]), so the
218/// app's `Intl`, `locale()`, `fontScale()` and text follow them like a system
219/// change.
220#[derive(Debug, Clone, Copy, PartialEq, Default)]
221pub struct HostEnvironment {
222 /// The locale in place of the user's ([`Environment::locale`]).
223 pub locale: Option<Locale>,
224 /// The text size in place of the user's ([`Environment::font_scale`]);
225 /// values that are not finite and positive count as `None`.
226 pub font_scale: Option<f32>,
227}
228
229impl HostEnvironment {
230 /// Writes the settings `self` has over `env`'s.
231 pub fn apply(&self, env: &mut Environment) {
232 if let Some(locale) = self.locale {
233 env.locale = locale;
234 }
235 if let Some(scale) = self.font_scale.filter(|s| s.is_finite() && *s > 0.0) {
236 env.font_scale = scale;
237 }
238 }
239}
240
241/// A BCP 47 language tag (`en-US`, `zh-Hans-CN`), held inline so that the
242/// environment stays `Copy`: the language, script and region subtags fit;
243/// variants and extensions are dropped.
244#[derive(Clone, Copy, PartialEq, Eq, Hash)]
245pub struct Locale {
246 bytes: [u8; Locale::CAPACITY],
247 len: u8,
248}
249
250impl Locale {
251 const CAPACITY: usize = 15;
252
253 /// `en-US`, the default when a platform reports none.
254 pub const EN_US: Locale = Locale {
255 bytes: *b"en-US\0\0\0\0\0\0\0\0\0\0",
256 len: 5,
257 };
258
259 /// The tag of a platform locale identifier: `en_US`, `en-US`,
260 /// `de_DE@calendar=gregorian`, `pt_BR.UTF-8` (POSIX) and `zh-Hans_CN`
261 /// all work. Subtags are cased as BCP 47 writes them (`zh-Hans-CN`);
262 /// `None` without a language.
263 pub fn parse(identifier: &str) -> Option<Locale> {
264 let identifier = identifier.split(['@', '.']).next().unwrap_or_default();
265 let mut bytes = [0u8; Self::CAPACITY];
266 let mut len = 0;
267 for (i, part) in identifier.split(['-', '_']).enumerate() {
268 let keep = if i == 0 {
269 (2..=3).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphabetic())
270 } else {
271 // A script (4 letters) or a region (2 letters, 3 digits).
272 (part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()))
273 || (part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()))
274 || (part.len() == 3 && part.bytes().all(|b| b.is_ascii_digit()))
275 };
276 if !keep {
277 if i == 0 {
278 return None;
279 }
280 // A variant or an extension: dropped with what follows.
281 break;
282 }
283 if len + part.len() + usize::from(i > 0) > Self::CAPACITY {
284 break;
285 }
286 if i > 0 {
287 bytes[len] = b'-';
288 len += 1;
289 }
290 for (j, b) in part.bytes().enumerate() {
291 bytes[len] = match (i, part.len()) {
292 (0, _) => b.to_ascii_lowercase(),
293 (_, 4) if j == 0 => b.to_ascii_uppercase(),
294 (_, 4) => b.to_ascii_lowercase(),
295 _ => b.to_ascii_uppercase(),
296 };
297 len += 1;
298 }
299 }
300 Some(Locale {
301 bytes,
302 len: len as u8,
303 })
304 }
305
306 /// The tag (`en-US`).
307 pub fn as_str(&self) -> &str {
308 // ASCII, as parsed.
309 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
310 }
311}
312
313impl Default for Locale {
314 fn default() -> Self {
315 Self::EN_US
316 }
317}
318
319impl std::fmt::Debug for Locale {
320 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
321 write!(f, "Locale({})", self.as_str())
322 }
323}
324
325impl std::fmt::Display for Locale {
326 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327 f.write_str(self.as_str())
328 }
329}
330
331/// An HTTP request for the platform's network stack (made by JS `fetch`
332/// and by Rust components' [`crate::element::ambient::fetch`]).
333#[derive(Debug, Clone, PartialEq, Eq)]
334pub struct HttpRequest {
335 /// Upper-case method (`GET`, `POST`, ...).
336 pub method: String,
337 /// Absolute URL.
338 pub url: String,
339 /// Header names and values, in order; names may repeat.
340 pub headers: Vec<(String, String)>,
341 /// Request body.
342 pub body: HttpBody,
343 /// Follow redirects (`redirect: "follow"`, the default).
344 pub follow_redirects: bool,
345}
346
347impl HttpRequest {
348 /// A request of `method` (`GET`, `POST`, ...; upper-cased) to `url`,
349 /// with no headers or body, following redirects.
350 pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
351 Self {
352 method: method.into().to_ascii_uppercase(),
353 url: url.into(),
354 headers: Vec::new(),
355 body: HttpBody::Empty,
356 follow_redirects: true,
357 }
358 }
359
360 /// A `GET` of `url`.
361 pub fn get(url: impl Into<String>) -> Self {
362 Self::new("GET", url)
363 }
364
365 /// A `POST` of `body` to `url`.
366 pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
367 Self::new("POST", url).body(body)
368 }
369
370 /// Adds the header `name: value`.
371 #[must_use]
372 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
373 self.headers.push((name.into(), value.into()));
374 self
375 }
376
377 /// Sends `body`.
378 #[must_use]
379 pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
380 self.body = HttpBody::Bytes(body.into());
381 self
382 }
383}
384
385impl From<&str> for HttpRequest {
386 fn from(url: &str) -> Self {
387 Self::get(url)
388 }
389}
390
391impl From<String> for HttpRequest {
392 fn from(url: String) -> Self {
393 Self::get(url)
394 }
395}
396
397/// The body of an [`HttpRequest`].
398#[derive(Debug, Clone, PartialEq, Eq, Default)]
399pub enum HttpBody {
400 /// No body.
401 #[default]
402 Empty,
403 /// All of it, known up front.
404 Bytes(Vec<u8>),
405 /// Produced while the request is sent (a `ReadableStream`), in chunks
406 /// the stack asks for one at a time ([`FetchEvent::BodyWanted`]); sent
407 /// with chunked transfer encoding.
408 Stream,
409}
410
411impl HttpBody {
412 /// No body at all.
413 pub fn is_empty(&self) -> bool {
414 match self {
415 HttpBody::Empty => true,
416 HttpBody::Bytes(b) => b.is_empty(),
417 HttpBody::Stream => false,
418 }
419 }
420}
421
422/// The status line and headers of a response, before its body.
423#[derive(Debug, Clone, PartialEq, Eq, Default)]
424pub struct HttpHead {
425 /// Status code.
426 pub status: u16,
427 /// Reason phrase, if the stack reports one.
428 pub status_text: String,
429 /// Final URL, after redirects.
430 pub url: String,
431 /// True if a redirect was followed.
432 pub redirected: bool,
433 /// Header names and values.
434 pub headers: Vec<(String, String)>,
435}
436
437/// What happens to a request, in order: (for a streamed body) any number
438/// of `BodyWanted`; then `Head`, `Data`… and `End` — or `Failed` at any
439/// point.
440#[derive(Debug, Clone, PartialEq, Eq)]
441pub enum FetchEvent {
442 /// A streamed body's next chunk is wanted: first when the stack is
443 /// ready to send, then each time the last chunk was handed on.
444 BodyWanted,
445 /// The response's status and headers arrived.
446 Head(HttpHead),
447 /// Bytes of the response body, in order.
448 Data(Vec<u8>),
449 /// The body is complete.
450 End,
451 /// The request failed (no response, or the body broke off).
452 Failed(String),
453}
454
455/// What JS asks of a request it made (the JS host queues these for the
456/// engine, which hands them to the stack).
457#[derive(Debug, Clone, PartialEq, Eq)]
458pub enum FetchOp {
459 /// Make the request.
460 Start(HttpRequest),
461 /// The next chunk of a streamed body (after [`FetchEvent::BodyWanted`]).
462 Send(Vec<u8>),
463 /// A streamed body is complete.
464 Finish,
465 /// Stop (`true`) or go on (`false`) reading the response body: nobody
466 /// reads what arrived.
467 Pause(bool),
468 /// Abort the request (`AbortController`, or the body was cancelled).
469 Cancel,
470}
471
472#[cfg(test)]
473mod tests {
474 use super::{Environment, HostEnvironment, Locale};
475
476 #[test]
477 fn a_host_environment_replaces_what_it_sets() {
478 let mut env = Environment {
479 font_scale: 1.25,
480 ..Environment::default()
481 };
482 HostEnvironment::default().apply(&mut env);
483 assert_eq!((env.locale, env.font_scale), (Locale::EN_US, 1.25));
484 let zh = Locale::parse("zh-Hans-CN").unwrap();
485 HostEnvironment {
486 locale: Some(zh),
487 font_scale: Some(f32::NAN),
488 }
489 .apply(&mut env);
490 assert_eq!((env.locale, env.font_scale), (zh, 1.25));
491 HostEnvironment {
492 locale: None,
493 font_scale: Some(1.5),
494 }
495 .apply(&mut env);
496 assert_eq!((env.locale, env.font_scale), (zh, 1.5));
497 }
498
499 #[test]
500 fn locales_parse_platform_identifiers() {
501 let tag = |s: &str| Locale::parse(s).map(|l| l.as_str().to_owned());
502 assert_eq!(tag("en_US").as_deref(), Some("en-US"));
503 assert_eq!(tag("zh-hans_cn").as_deref(), Some("zh-Hans-CN"));
504 assert_eq!(tag("de_DE@calendar=gregorian").as_deref(), Some("de-DE"));
505 assert_eq!(tag("pt_BR.UTF-8").as_deref(), Some("pt-BR"));
506 assert_eq!(tag("es-419").as_deref(), Some("es-419"));
507 assert_eq!(tag("en-US-u-hc-h23").as_deref(), Some("en-US"));
508 assert_eq!(tag("C"), None);
509 assert_eq!(Locale::default().as_str(), "en-US");
510 }
511}