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