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