Skip to main content

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`'s `isAvailable`). Desktop behavior
88    /// (`desktop={{…}}` props, `platform.select({ desktop })`,
89    /// `platform.desktop`) also covers browsers in the desktop idiom:
90    /// [`Environment::desktop`].
91    pub fn is_desktop(self) -> bool {
92        matches!(self, Os::MacOs | Os::Windows | Os::Linux)
93    }
94
95    /// iOS running under Mac Catalyst, in every idiom (`platform.catalyst`):
96    /// this build is Catalyst's (`target_abi = "macabi"`). Catalyst runs the
97    /// iOS backend, so it is mobile, not desktop: `ios={{…}}` props apply and
98    /// `nsh/desktop`'s window and menu APIs are not there.
99    pub fn is_catalyst(self) -> bool {
100        self == Os::Ios && cfg!(target_abi = "macabi")
101    }
102}
103
104impl Default for Os {
105    /// The mobile OS of this build (headless runs, `nsh test`, behave as iOS); desktop
106    /// backends set theirs.
107    fn default() -> Self {
108        if cfg!(target_os = "android") {
109            Os::Android
110        } else {
111            Os::Ios
112        }
113    }
114}
115
116/// The kind of device (`platform.idiom`).
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
118pub enum Idiom {
119    /// A phone.
120    #[default]
121    Phone,
122    /// A tablet.
123    Pad,
124    /// UIKit's Mac idiom (Mac Catalyst optimized for Mac). Catalyst runs
125    /// the iOS backend, so this idiom is mobile, not [`Idiom::Desktop`].
126    Mac,
127    /// A TV.
128    Tv,
129    /// Desktop: a desktop backend (macOS, Windows, Linux), or a browser with
130    /// a mouse and a wide viewport ([`Idiom::desktop_on`]). Mac Catalyst is
131    /// [`Idiom::Pad`] or [`Idiom::Mac`], as UIKit reports.
132    Desktop,
133}
134
135impl Idiom {
136    /// Whether desktop behavior applies on `os` in this idiom, NSH's one
137    /// definition of desktop: a desktop OS (macOS, Windows, Linux), or a
138    /// browser in the desktop idiom. `desktop={{…}}` props,
139    /// `platform.select({ desktop })`, `platform.desktop` and
140    /// `platform.idiom === "desktop"` all follow it ([`Idiom::reported_on`]).
141    pub fn desktop_on(self, os: Os) -> bool {
142        os.is_desktop() || (os == Os::Web && self == Idiom::Desktop)
143    }
144
145    /// The idiom apps see on `os` (TS: `platform.idiom`): [`Idiom::Desktop`]
146    /// exactly where [`Idiom::desktop_on`] holds, so that `"desktop"` agrees
147    /// with desktop behavior whatever a platform (or a test) set. Elsewhere
148    /// this idiom, and [`Idiom::Phone`] for [`Idiom::Desktop`] on a mobile OS.
149    pub fn reported_on(self, os: Os) -> Idiom {
150        if self.desktop_on(os) {
151            Idiom::Desktop
152        } else if self == Idiom::Desktop {
153            Idiom::Phone
154        } else {
155            self
156        }
157    }
158}
159
160/// Whether the app is in use (`lifecycle()`), in React Native's `AppState`
161/// terms.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
163pub enum Lifecycle {
164    /// In the foreground and taking input.
165    #[default]
166    Active,
167    /// Still visible, but not taking input: another app or window has the
168    /// focus, or the system shows something over it (the app switcher, an
169    /// incoming call, Control Center).
170    Inactive,
171    /// Not visible: in the background, minimized or hidden. The system may
172    /// suspend it there.
173    Background,
174}
175
176impl Lifecycle {
177    /// Its `lifecycle()` name: `"active"`, `"inactive"` or `"background"`.
178    pub fn name(self) -> &'static str {
179        match self {
180            Lifecycle::Active => "active",
181            Lifecycle::Inactive => "inactive",
182            Lifecycle::Background => "background",
183        }
184    }
185}
186
187/// What the platform knows about the surface.
188#[derive(Debug, Clone, Copy, PartialEq)]
189pub struct Environment {
190    /// Size of the surface in points.
191    pub window: Size<Points>,
192    /// Insets not covered by system UI (notch, home indicator, title bar).
193    pub safe_area: Edges<Points>,
194    /// The title bar's area while the app hides it (desktops,
195    /// [`crate::desktop::TitleBarStyle::Hidden`]): `top` is its height,
196    /// `left` and `right` the widths the system's window controls take at
197    /// its ends (`bottom` is 0); all 0 while the system shows its title
198    /// bar.
199    pub title_bar: Edges<Points>,
200    /// Height of the software keyboard over the surface; 0 when hidden.
201    pub keyboard_height: Points,
202    /// Duration of the keyboard's show / hide animation in milliseconds.
203    pub keyboard_duration: f32,
204    /// Light or dark appearance.
205    pub color_scheme: ColorScheme,
206    /// Preferred text size relative to the default (1.0).
207    pub font_scale: f32,
208    /// The user's language is written right to left.
209    pub rtl: bool,
210    /// The user asked for less motion (iOS Reduce Motion, Android's
211    /// animator duration scale at 0).
212    pub reduce_motion: bool,
213    /// Device pixels per point.
214    pub pixel_ratio: f32,
215    /// A screen reader runs (VoiceOver, TalkBack).
216    pub screen_reader: bool,
217    /// The operating system.
218    pub os: Os,
219    /// The OS version: major and minor (iOS, desktops), Android's API level
220    /// and 0.
221    pub os_version: (u16, u16),
222    /// The kind of device.
223    pub idiom: Idiom,
224    /// A browser on an Apple platform (macOS, iOS): its keyboard shortcuts
225    /// follow Apple's conventions ([`crate::keymap::apple_keys`]: `mod` is
226    /// Command, labels use ⌘). Only read for [`Os::Web`]; the other OSes
227    /// imply theirs.
228    pub apple_keyboard: bool,
229    /// The user's locale (number and date formats: `Intl`'s default).
230    pub locale: Locale,
231    /// The app embedding NSH answers `nsh/host`'s calls
232    /// ([`crate::Command::HostCall`]); without it, they reject at once.
233    pub host: bool,
234    /// Whether the app is in use: in the foreground, visible without the
235    /// focus, or in the background. For an embedded surface, the embedding
236    /// app's.
237    pub lifecycle: Lifecycle,
238    /// The platform picks a color from the screen
239    /// ([`crate::Command::PickScreenColor`]); without it, a pick answers
240    /// no color at once.
241    pub screen_color: bool,
242    /// The platform shows the system's open and save dialogs and opens,
243    /// reveals and trashes local paths ([`crate::Command::FileRequest`],
244    /// the desktops); without it, those requests answer at once with an
245    /// error.
246    pub file_requests: bool,
247    /// The platform recognizes speech ([`crate::Command::Speech`],
248    /// [`crate::speech`]); without it, a session ends at once
249    /// (`unavailable`) unless the core has a [`crate::speech::SpeechBackend`].
250    pub speech: bool,
251    /// The platform gives web views trusted input
252    /// ([`crate::Command::SendInput`], macOS); without it, the command
253    /// does nothing.
254    pub web_input: bool,
255}
256
257impl Environment {
258    /// Desktop behavior applies: a desktop OS, or a browser in the desktop
259    /// idiom ([`Idiom::desktop_on`]: `desktop={{…}}` props,
260    /// `platform.select({ desktop })`, `platform.desktop`, `platform.idiom`
261    /// `"desktop"`).
262    pub fn desktop(&self) -> bool {
263        self.idiom.desktop_on(self.os)
264    }
265
266    /// The idiom apps see (TS: `platform.idiom`, [`Idiom::reported_on`]).
267    pub fn reported_idiom(&self) -> Idiom {
268        self.idiom.reported_on(self.os)
269    }
270}
271
272impl Default for Environment {
273    fn default() -> Self {
274        Self {
275            window: Size::default(),
276            safe_area: Edges::default(),
277            title_bar: Edges::default(),
278            keyboard_height: Points(0.0),
279            keyboard_duration: 250.0,
280            color_scheme: ColorScheme::Light,
281            font_scale: 1.0,
282            rtl: false,
283            reduce_motion: false,
284            pixel_ratio: 1.0,
285            screen_reader: false,
286            os: Os::default(),
287            os_version: (0, 0),
288            idiom: Idiom::Phone,
289            apple_keyboard: false,
290            locale: Locale::EN_US,
291            host: false,
292            lifecycle: Lifecycle::Active,
293            screen_color: false,
294            file_requests: false,
295            speech: false,
296            web_input: false,
297        }
298    }
299}
300
301/// The settings an embedding app gives its surfaces in place of the
302/// system's (`None`: the system's): its own language and text size, for an
303/// app inside a native app that lets its users switch them. The platforms
304/// write them over what they read from the system ([`Self::apply`]), so the
305/// app's `Intl`, `locale()`, `fontScale()` and text follow them like a system
306/// change.
307#[derive(Debug, Clone, Copy, PartialEq, Default)]
308pub struct HostEnvironment {
309    /// The locale in place of the user's ([`Environment::locale`]).
310    pub locale: Option<Locale>,
311    /// The text size in place of the user's ([`Environment::font_scale`]);
312    /// values that are not finite and positive count as `None`.
313    pub font_scale: Option<f32>,
314}
315
316impl HostEnvironment {
317    /// Writes the settings `self` has over `env`'s.
318    pub fn apply(&self, env: &mut Environment) {
319        if let Some(locale) = self.locale {
320            env.locale = locale;
321        }
322        if let Some(scale) = self.font_scale.filter(|s| s.is_finite() && *s > 0.0) {
323            env.font_scale = scale;
324        }
325    }
326}
327
328/// A BCP 47 language tag (`en-US`, `zh-Hans-CN`), held inline so that the
329/// environment stays `Copy`: the language, script and region subtags fit;
330/// variants and extensions are dropped.
331#[derive(Clone, Copy, PartialEq, Eq, Hash)]
332pub struct Locale {
333    bytes: [u8; Locale::CAPACITY],
334    len: u8,
335}
336
337impl Locale {
338    const CAPACITY: usize = 15;
339
340    /// `en-US`, the default when a platform reports none.
341    pub const EN_US: Locale = Locale {
342        bytes: *b"en-US\0\0\0\0\0\0\0\0\0\0",
343        len: 5,
344    };
345
346    /// The tag of a platform locale identifier: `en_US`, `en-US`,
347    /// `de_DE@calendar=gregorian`, `pt_BR.UTF-8` (POSIX) and `zh-Hans_CN`
348    /// all work. Subtags are cased as BCP 47 writes them (`zh-Hans-CN`);
349    /// `None` without a language.
350    pub fn parse(identifier: &str) -> Option<Locale> {
351        let identifier = identifier.split(['@', '.']).next().unwrap_or_default();
352        let mut bytes = [0u8; Self::CAPACITY];
353        let mut len = 0;
354        for (i, part) in identifier.split(['-', '_']).enumerate() {
355            let keep = if i == 0 {
356                (2..=3).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphabetic())
357            } else {
358                // A script (4 letters) or a region (2 letters, 3 digits).
359                (part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()))
360                    || (part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()))
361                    || (part.len() == 3 && part.bytes().all(|b| b.is_ascii_digit()))
362            };
363            if !keep {
364                if i == 0 {
365                    return None;
366                }
367                // A variant or an extension: dropped with what follows.
368                break;
369            }
370            if len + part.len() + usize::from(i > 0) > Self::CAPACITY {
371                break;
372            }
373            if i > 0 {
374                bytes[len] = b'-';
375                len += 1;
376            }
377            for (j, b) in part.bytes().enumerate() {
378                bytes[len] = match (i, part.len()) {
379                    (0, _) => b.to_ascii_lowercase(),
380                    (_, 4) if j == 0 => b.to_ascii_uppercase(),
381                    (_, 4) => b.to_ascii_lowercase(),
382                    _ => b.to_ascii_uppercase(),
383                };
384                len += 1;
385            }
386        }
387        Some(Locale {
388            bytes,
389            len: len as u8,
390        })
391    }
392
393    /// The tag (`en-US`).
394    pub fn as_str(&self) -> &str {
395        // ASCII, as parsed.
396        std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
397    }
398}
399
400impl Default for Locale {
401    fn default() -> Self {
402        Self::EN_US
403    }
404}
405
406impl std::fmt::Debug for Locale {
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        write!(f, "Locale({})", self.as_str())
409    }
410}
411
412impl std::fmt::Display for Locale {
413    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
414        f.write_str(self.as_str())
415    }
416}
417
418/// An HTTP request for the platform's network stack (made by JS `fetch`
419/// and by Rust components' [`crate::element::fetch`]).
420#[derive(Debug, Clone, PartialEq, Eq)]
421pub struct HttpRequest {
422    /// Upper-case method (`GET`, `POST`, ...).
423    pub method: String,
424    /// Absolute URL.
425    pub url: String,
426    /// Header names and values, in order; names may repeat.
427    pub headers: Vec<(String, String)>,
428    /// Request body.
429    pub body: HttpBody,
430    /// Follow redirects (`redirect: "follow"`, the default).
431    pub follow_redirects: bool,
432}
433
434impl HttpRequest {
435    /// A request of `method` (`GET`, `POST`, ...; upper-cased) to `url`,
436    /// with no headers or body, following redirects.
437    pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
438        Self {
439            method: method.into().to_ascii_uppercase(),
440            url: url.into(),
441            headers: Vec::new(),
442            body: HttpBody::Empty,
443            follow_redirects: true,
444        }
445    }
446
447    /// A `GET` of `url`.
448    pub fn get(url: impl Into<String>) -> Self {
449        Self::new("GET", url)
450    }
451
452    /// A `POST` of `body` to `url`.
453    pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
454        Self::new("POST", url).body(body)
455    }
456
457    /// Adds the header `name: value`.
458    #[must_use]
459    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
460        self.headers.push((name.into(), value.into()));
461        self
462    }
463
464    /// Sends `body`.
465    #[must_use]
466    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
467        self.body = HttpBody::Bytes(body.into());
468        self
469    }
470}
471
472impl From<&str> for HttpRequest {
473    fn from(url: &str) -> Self {
474        Self::get(url)
475    }
476}
477
478impl From<String> for HttpRequest {
479    fn from(url: String) -> Self {
480        Self::get(url)
481    }
482}
483
484/// The body of an [`HttpRequest`].
485#[derive(Debug, Clone, PartialEq, Eq, Default)]
486pub enum HttpBody {
487    /// No body.
488    #[default]
489    Empty,
490    /// All of it, known up front.
491    Bytes(Vec<u8>),
492    /// Produced while the request is sent (a `ReadableStream`), in chunks
493    /// the stack asks for one at a time ([`FetchEvent::BodyWanted`]); sent
494    /// with chunked transfer encoding.
495    Stream,
496}
497
498impl HttpBody {
499    /// No body at all.
500    pub fn is_empty(&self) -> bool {
501        match self {
502            HttpBody::Empty => true,
503            HttpBody::Bytes(b) => b.is_empty(),
504            HttpBody::Stream => false,
505        }
506    }
507}
508
509/// The status line and headers of a response, before its body.
510#[derive(Debug, Clone, PartialEq, Eq, Default)]
511pub struct HttpHead {
512    /// Status code.
513    pub status: u16,
514    /// Reason phrase, if the stack reports one.
515    pub status_text: String,
516    /// Final URL, after redirects.
517    pub url: String,
518    /// True if a redirect was followed.
519    pub redirected: bool,
520    /// Header names and values.
521    pub headers: Vec<(String, String)>,
522}
523
524/// What happens to a request, in order: (for a streamed body) any number
525/// of `BodyWanted`; then `Head`, `Data`… and `End` — or `Failed` at any
526/// point.
527#[derive(Debug, Clone, PartialEq, Eq)]
528pub enum FetchEvent {
529    /// A streamed body's next chunk is wanted: first when the stack is
530    /// ready to send, then each time the last chunk was handed on.
531    BodyWanted,
532    /// The response's status and headers arrived.
533    Head(HttpHead),
534    /// Bytes of the response body, in order.
535    Data(Vec<u8>),
536    /// The body is complete.
537    End,
538    /// The request failed (no response, or the body broke off).
539    Failed(String),
540}
541
542/// What JS asks of a request it made (the JS host queues these for the
543/// engine, which hands them to the stack).
544#[derive(Debug, Clone, PartialEq, Eq)]
545pub enum FetchOp {
546    /// Make the request.
547    Start(HttpRequest),
548    /// The next chunk of a streamed body (after [`FetchEvent::BodyWanted`]).
549    Send(Vec<u8>),
550    /// A streamed body is complete.
551    Finish,
552    /// Stop (`true`) or go on (`false`) reading the response body: nobody
553    /// reads what arrived.
554    Pause(bool),
555    /// Abort the request (`AbortController`, or the body was cancelled).
556    Cancel,
557}
558
559#[cfg(test)]
560mod tests {
561    use super::{Environment, HostEnvironment, Idiom, Locale, Os};
562
563    #[test]
564    fn desktop_is_a_desktop_os_or_a_desktop_browser() {
565        let desktop = |os: Os, idiom: Idiom| Environment {
566            os,
567            idiom,
568            ..Environment::default()
569        };
570        for (os, idiom, expected) in [
571            (Os::MacOs, Idiom::Desktop, true),
572            (Os::Windows, Idiom::Desktop, true),
573            (Os::Linux, Idiom::Desktop, true),
574            // A desktop OS is desktop whatever idiom it was given.
575            (Os::Linux, Idiom::Phone, true),
576            (Os::Web, Idiom::Desktop, true),
577            (Os::Web, Idiom::Pad, false),
578            (Os::Web, Idiom::Phone, false),
579            (Os::Ios, Idiom::Phone, false),
580            (Os::Ios, Idiom::Pad, false),
581            // Mac Catalyst: the iOS backend, mobile in either idiom.
582            (Os::Ios, Idiom::Mac, false),
583            (Os::Ios, Idiom::Desktop, false),
584            (Os::Android, Idiom::Tv, false),
585        ] {
586            let env = desktop(os, idiom);
587            assert_eq!(env.desktop(), expected, "{os:?} {idiom:?}");
588            // `platform.idiom` is "desktop" exactly where desktop applies.
589            assert_eq!(
590                env.reported_idiom() == Idiom::Desktop,
591                expected,
592                "{os:?} {idiom:?}"
593            );
594        }
595        assert_eq!(desktop(Os::Ios, Idiom::Mac).reported_idiom(), Idiom::Mac);
596        assert_eq!(
597            desktop(Os::Ios, Idiom::Desktop).reported_idiom(),
598            Idiom::Phone
599        );
600        assert!(!Os::MacOs.is_catalyst() && !Os::Web.is_catalyst());
601        assert_eq!(Os::Ios.is_catalyst(), cfg!(target_abi = "macabi"));
602    }
603
604    #[test]
605    fn a_host_environment_replaces_what_it_sets() {
606        let mut env = Environment {
607            font_scale: 1.25,
608            ..Environment::default()
609        };
610        HostEnvironment::default().apply(&mut env);
611        assert_eq!((env.locale, env.font_scale), (Locale::EN_US, 1.25));
612        let zh = Locale::parse("zh-Hans-CN").unwrap();
613        HostEnvironment {
614            locale: Some(zh),
615            font_scale: Some(f32::NAN),
616        }
617        .apply(&mut env);
618        assert_eq!((env.locale, env.font_scale), (zh, 1.25));
619        HostEnvironment {
620            locale: None,
621            font_scale: Some(1.5),
622        }
623        .apply(&mut env);
624        assert_eq!((env.locale, env.font_scale), (zh, 1.5));
625    }
626
627    #[test]
628    fn locales_parse_platform_identifiers() {
629        let tag = |s: &str| Locale::parse(s).map(|l| l.as_str().to_owned());
630        assert_eq!(tag("en_US").as_deref(), Some("en-US"));
631        assert_eq!(tag("zh-hans_cn").as_deref(), Some("zh-Hans-CN"));
632        assert_eq!(tag("de_DE@calendar=gregorian").as_deref(), Some("de-DE"));
633        assert_eq!(tag("pt_BR.UTF-8").as_deref(), Some("pt-BR"));
634        assert_eq!(tag("es-419").as_deref(), Some("es-419"));
635        assert_eq!(tag("en-US-u-hc-h23").as_deref(), Some("en-US"));
636        assert_eq!(tag("C"), None);
637        assert_eq!(Locale::default().as_str(), "en-US");
638    }
639}