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