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;
6pub mod web_evaluation;
7
8use crate::geometry::{Bounds, Edges, Points, Size};
9
10/// The native component of `nsh/mobile`'s `TabBar`, which the iOS and
11/// Android backends register themselves (`TabBarComponent.java`'s `NAME` keeps
12/// the same name).
13pub const TAB_BAR_COMPONENT: &str = "nsh/tab-bar";
14
15/// The native component of `nsh/base`'s `MenuButton`, which the iOS backend
16/// registers itself (a `UIButton` showing its `UIMenu` as its primary
17/// action), and the Android backend (a button showing the system's popup
18/// menu; `MenuButtonComponent.java`'s `NAME` keeps the same name).
19pub const MENU_BUTTON_COMPONENT: &str = "nsh/menu-button";
20
21/// The native component of `nsh/base`'s `ContextMenu` given `items`, which
22/// the iOS backend registers itself (a `UIContextMenuInteraction` on the
23/// view around the trigger, the trigger lifted as its preview), and the
24/// Android backend (the system's popup menu by the trigger, shown when
25/// `open`; `ContextMenuComponent.java`'s `NAME` keeps the same name).
26pub const CONTEXT_MENU_COMPONENT: &str = "nsh/context-menu";
27
28/// The native component of `nsh/base`'s `SplitView`, which the iOS backend
29/// makes itself (a `UISplitViewController` whose columns are the
30/// navigation controllers of the stacks the view places before it).
31pub const SPLIT_VIEW_COMPONENT: &str = "nsh/split-view";
32
33/// Whether native component `name` is NSH's own: names under `nsh/` are, and
34/// an embedding app's registration of one is refused, so it can never
35/// replace what NSH's exports render.
36pub fn is_reserved_component(name: &str) -> bool {
37    name.starts_with("nsh/")
38}
39
40/// The system appearance.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum ColorScheme {
43    /// Light mode.
44    #[default]
45    Light,
46    /// Dark mode.
47    Dark,
48}
49
50/// The appearance an app asks for (`nsh.json` `"appearance"`, TS
51/// `setColorScheme`): one of its own, or the system's.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
53pub enum Appearance {
54    /// The system appearance (default).
55    #[default]
56    System,
57    /// Always light.
58    Light,
59    /// Always dark.
60    Dark,
61}
62
63impl Appearance {
64    /// The color scheme shown when the system's is `system`.
65    pub fn resolve(self, system: ColorScheme) -> ColorScheme {
66        match self {
67            Appearance::System => system,
68            Appearance::Light => ColorScheme::Light,
69            Appearance::Dark => ColorScheme::Dark,
70        }
71    }
72}
73
74/// What the user last gave a surface input with
75/// (`EngineControl::set_input_modality`): the core shows the keyboard focus
76/// (`focus-visible:`) by it, as browsers decide CSS's `:focus-visible`.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum InputModality {
79    /// A key press (not a modifier alone): Tab, an arrow, a shortcut,
80    /// typing, from a hardware keyboard.
81    Keyboard,
82    /// A mouse button, a pen or a finger going down.
83    Pointer,
84}
85
86/// The operating system (`platform.os`).
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum Os {
89    /// iOS, iPadOS, Mac Catalyst.
90    Ios,
91    /// Android.
92    Android,
93    /// macOS (a desktop backend).
94    MacOs,
95    /// Windows.
96    Windows,
97    /// Linux.
98    Linux,
99    /// A web browser (the WebAssembly runtime): phone, tablet or desktop
100    /// by [`Idiom`].
101    Web,
102}
103
104impl Os {
105    /// Its `platform.os` name.
106    pub fn name(self) -> &'static str {
107        match self {
108            Os::Ios => "ios",
109            Os::Android => "android",
110            Os::MacOs => "macos",
111            Os::Windows => "windows",
112            Os::Linux => "linux",
113            Os::Web => "web",
114        }
115    }
116
117    /// The OS named `name` ([`Os::name`]): a scoped asset's target in a
118    /// UI set's description.
119    pub(crate) fn from_name(name: &str) -> Option<Self> {
120        [
121            Os::Ios,
122            Os::Android,
123            Os::MacOs,
124            Os::Windows,
125            Os::Linux,
126            Os::Web,
127        ]
128        .into_iter()
129        .find(|os| os.name() == name)
130    }
131
132    /// The OS of a desktop backend (macOS, Windows, Linux): it has windows
133    /// and menus (`nsh/desktop`'s `isAvailable`). Desktop behavior
134    /// (`desktop={{…}}` props, `platform.select({ desktop })`,
135    /// `platform.desktop`) also covers browsers in the desktop idiom:
136    /// [`Environment::desktop`].
137    pub fn is_desktop(self) -> bool {
138        matches!(self, Os::MacOs | Os::Windows | Os::Linux)
139    }
140
141    /// iOS running under Mac Catalyst, in every idiom (`platform.catalyst`):
142    /// this build is Catalyst's (`target_abi = "macabi"`). Catalyst runs the
143    /// iOS backend, so it is mobile, not desktop: `ios={{…}}` props apply and
144    /// `nsh/desktop`'s window and menu APIs are not there.
145    pub fn is_catalyst(self) -> bool {
146        self == Os::Ios && cfg!(target_abi = "macabi")
147    }
148}
149
150impl Default for Os {
151    /// The mobile OS of this build (headless runs, `nsh test`, behave as iOS); desktop
152    /// backends set theirs.
153    fn default() -> Self {
154        if cfg!(target_os = "android") {
155            Os::Android
156        } else {
157            Os::Ios
158        }
159    }
160}
161
162/// The kind of device (`platform.idiom`).
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
164pub enum Idiom {
165    /// A phone.
166    #[default]
167    Phone,
168    /// A tablet.
169    Pad,
170    /// UIKit's Mac idiom (Mac Catalyst optimized for Mac). Catalyst runs
171    /// the iOS backend, so this idiom is mobile, not [`Idiom::Desktop`].
172    Mac,
173    /// A TV.
174    Tv,
175    /// Desktop: a desktop backend (macOS, Windows, Linux), or a browser with
176    /// a mouse and a wide viewport ([`Idiom::desktop_on`]). Mac Catalyst is
177    /// [`Idiom::Pad`] or [`Idiom::Mac`], as UIKit reports.
178    Desktop,
179    /// A terminal: drawn on a grid of Cells, keyboard first (the terminal
180    /// backend). The OS stays the machine's; desktop behavior applies.
181    Terminal,
182}
183
184impl Idiom {
185    /// Whether desktop behavior applies on `os` in this idiom, NSH's one
186    /// definition of desktop: a desktop OS (macOS, Windows, Linux), a
187    /// browser in the desktop idiom, or a terminal. `desktop={{…}}` props,
188    /// `platform.select({ desktop })` and `platform.desktop` all follow it,
189    /// and so does `platform.idiom === "desktop"` outside a terminal
190    /// ([`Idiom::reported_on`]).
191    pub fn desktop_on(self, os: Os) -> bool {
192        os.is_desktop() || (os == Os::Web && self == Idiom::Desktop) || self == Idiom::Terminal
193    }
194
195    /// The idiom apps see on `os` (TS: `platform.idiom`): [`Idiom::Terminal`]
196    /// in a terminal, else [`Idiom::Desktop`] exactly where
197    /// [`Idiom::desktop_on`] holds, so that `"desktop"` agrees with desktop
198    /// behavior whatever a platform (or a test) set. Elsewhere this idiom,
199    /// and [`Idiom::Phone`] for [`Idiom::Desktop`] on a mobile OS.
200    pub fn reported_on(self, os: Os) -> Idiom {
201        if self == Idiom::Terminal {
202            Idiom::Terminal
203        } else if self.desktop_on(os) {
204            Idiom::Desktop
205        } else if self == Idiom::Desktop {
206            Idiom::Phone
207        } else {
208            self
209        }
210    }
211}
212
213/// Whether the app is in use (`lifecycle()`), in React Native's `AppState`
214/// terms.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
216pub enum Lifecycle {
217    /// In the foreground and taking input.
218    #[default]
219    Active,
220    /// Still visible, but not taking input: another app or window has the
221    /// focus, or the system shows something over it (the app switcher, an
222    /// incoming call, Control Center).
223    Inactive,
224    /// Not visible: in the background, minimized or hidden. The system may
225    /// suspend it there.
226    Background,
227}
228
229impl Lifecycle {
230    /// Its `lifecycle()` name: `"active"`, `"inactive"` or `"background"`.
231    pub fn name(self) -> &'static str {
232        match self {
233            Lifecycle::Active => "active",
234            Lifecycle::Inactive => "inactive",
235            Lifecycle::Background => "background",
236        }
237    }
238}
239
240/// How the device reaches the network now (`network()`), as the system's
241/// path monitor reports it: the kind of link its default route takes,
242/// whether that link costs the user (`expensive`) or the user asked to save
243/// data on it (`constrained`), and on iOS whether the user lets the app use
244/// cellular data. Platforms that cannot tell report
245/// [`NetworkKind::Unknown`], which counts as online: the app tries and
246/// learns from its requests.
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
248#[non_exhaustive]
249pub struct Network {
250    /// The kind of link the default route takes, [`NetworkKind::None`]
251    /// without one.
252    pub kind: NetworkKind,
253    /// The link costs the user: cellular data, a phone's hotspot, a
254    /// metered connection (Apple's `isExpensive`, Android's metered
255    /// networks, the browser's `cellular` connection).
256    pub expensive: bool,
257    /// The user asked to use less data on this link: Low Data Mode (iOS,
258    /// macOS), Data Saver (Android), the browser's `saveData`.
259    pub constrained: bool,
260    /// Whether the user lets the app use cellular data (iOS:
261    /// `CTCellularData`; on devices sold in mainland China, the system's
262    /// prompt for wireless data). [`CellularData::Unknown`] elsewhere.
263    pub cellular_data: CellularData,
264}
265
266impl Network {
267    /// A network of `kind`, neither expensive nor constrained, with the
268    /// cellular data permission unknown.
269    pub fn new(kind: NetworkKind) -> Self {
270        Self {
271            kind,
272            ..Self::default()
273        }
274    }
275
276    /// The link costs the user.
277    pub fn expensive(mut self, expensive: bool) -> Self {
278        self.expensive = expensive;
279        self
280    }
281
282    /// The user asked to use less data on this link.
283    pub fn constrained(mut self, constrained: bool) -> Self {
284        self.constrained = constrained;
285        self
286    }
287
288    /// Whether the user lets the app use cellular data.
289    pub fn cellular_data(mut self, cellular_data: CellularData) -> Self {
290        self.cellular_data = cellular_data;
291        self
292    }
293
294    /// Whether a route to the network exists (TS: `network().online`):
295    /// false only when the platform knows there is none, true while it
296    /// does not know ([`NetworkKind::Unknown`]).
297    pub fn online(&self) -> bool {
298        self.kind != NetworkKind::None
299    }
300}
301
302/// The kind of link the device's default route takes (`network().kind`).
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
304#[non_exhaustive]
305pub enum NetworkKind {
306    /// The platform does not say (it has no monitor, or has not answered
307    /// yet).
308    #[default]
309    Unknown,
310    /// No route to the network: offline.
311    None,
312    /// Wi-Fi.
313    Wifi,
314    /// Cellular data.
315    Cellular,
316    /// A wired link: Ethernet.
317    Wired,
318    /// Another link: a VPN without a known link beneath, Bluetooth, a
319    /// USB tether, loopback only.
320    Other,
321}
322
323impl NetworkKind {
324    /// Its `network().kind` name.
325    pub fn name(self) -> &'static str {
326        match self {
327            Self::Unknown => "unknown",
328            Self::None => "none",
329            Self::Wifi => "wifi",
330            Self::Cellular => "cellular",
331            Self::Wired => "wired",
332            Self::Other => "other",
333        }
334    }
335
336    /// The kind named `name` ([`Self::name`]).
337    pub fn parse(name: &str) -> Option<Self> {
338        Some(match name {
339            "unknown" => Self::Unknown,
340            "none" => Self::None,
341            "wifi" => Self::Wifi,
342            "cellular" => Self::Cellular,
343            "wired" => Self::Wired,
344            "other" => Self::Other,
345            _ => return None,
346        })
347    }
348}
349
350/// Whether the user lets the app use cellular data
351/// (`network().cellularData`): iOS's `CTCellularData.restrictedState`.
352#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
353#[non_exhaustive]
354pub enum CellularData {
355    /// Not known: the user has not decided yet (the first launch on a
356    /// device that asks), or the platform does not report it (every
357    /// platform but iOS).
358    #[default]
359    Unknown,
360    /// The user turned cellular data off for the app (on devices that ask
361    /// for wireless data, also "Off" or "WLAN" only): its requests over
362    /// cellular fail, and only the system's settings change it.
363    Restricted,
364    /// The app may use cellular data.
365    NotRestricted,
366}
367
368impl CellularData {
369    /// Its `network().cellularData` name.
370    pub fn name(self) -> &'static str {
371        match self {
372            Self::Unknown => "unknown",
373            Self::Restricted => "restricted",
374            Self::NotRestricted => "notRestricted",
375        }
376    }
377
378    /// The state named `name` ([`Self::name`]).
379    pub fn parse(name: &str) -> Option<Self> {
380        Some(match name {
381            "unknown" => Self::Unknown,
382            "restricted" => Self::Restricted,
383            "notRestricted" => Self::NotRestricted,
384            _ => return None,
385        })
386    }
387}
388
389/// The space available along one axis of a surface.
390#[derive(Debug, Clone, Copy, PartialEq, Eq)]
391pub enum SizeClass {
392    /// Less room for content.
393    Compact,
394    /// Room for an expanded layout.
395    Regular,
396}
397
398impl SizeClass {
399    /// Classify a length in points: below 600 is compact, 600 and above regular.
400    /// This is the fallback where the platform supplies no native size class.
401    pub(crate) fn from_length(length: Points) -> Self {
402        if length < Points(600.0) {
403            Self::Compact
404        } else {
405            Self::Regular
406        }
407    }
408
409    /// The TypeScript value of this class.
410    pub fn name(self) -> &'static str {
411        match self {
412            Self::Compact => "compact",
413            Self::Regular => "regular",
414        }
415    }
416}
417
418/// What the platform knows about the surface.
419#[derive(Debug, Clone, Copy, PartialEq)]
420pub struct Environment {
421    /// Size of the surface in points.
422    pub window: Size<Points>,
423    /// Native horizontal size class (UIKit); `None` derives it from window width.
424    pub horizontal_size_class: Option<SizeClass>,
425    /// Native vertical size class (UIKit); `None` derives it from window height.
426    pub vertical_size_class: Option<SizeClass>,
427    /// Insets not covered by system UI (notch, home indicator, title bar).
428    pub safe_area: Edges<Points>,
429    /// The parts of the surface the device reserves inside the safe area
430    /// (TS: `reservedRegions()`): the fold of a partly folded display,
431    /// a camera that shows through it. Empty where the platform reports
432    /// none.
433    pub reserved_regions: ReservedRegions,
434    /// The title bar's area while the app hides it (desktops,
435    /// [`crate::desktop::TitleBarStyle::Hidden`]): `top` is its height,
436    /// `left` and `right` the widths the system's window controls take at
437    /// its ends (`bottom` is 0); all 0 while the system shows its title
438    /// bar.
439    pub title_bar: Edges<Points>,
440    /// The app's window: its bounds on the screen, its mode and display
441    /// (desktops; `None` elsewhere and where the surface has no window).
442    /// The engine holds back a move or resize until the window stops for
443    /// a moment, so platforms report every change.
444    pub window_state: Option<crate::desktop::WindowState>,
445    /// Height of the software keyboard over the surface; 0 when hidden.
446    pub keyboard_height: Points,
447    /// Duration of the keyboard's show / hide animation in milliseconds.
448    pub keyboard_duration: f32,
449    /// Light or dark appearance.
450    pub color_scheme: ColorScheme,
451    /// Preferred text size relative to the default (1.0).
452    pub font_scale: f32,
453    /// The user's language is written right to left.
454    pub rtl: bool,
455    /// The user asked for less motion (iOS Reduce Motion, Android's
456    /// animator duration scale at 0).
457    pub reduce_motion: bool,
458    /// Device pixels per point.
459    pub pixel_ratio: f32,
460    /// A screen reader runs (VoiceOver, TalkBack).
461    pub screen_reader: bool,
462    /// The platform's screen readers follow the active descendant a
463    /// focused view names (`accessibilityActiveDescendant`): they read the
464    /// element named as it changes while the focus stays. `nsh-base`'s
465    /// lists then name their highlighted row and tell screen readers
466    /// nothing more; without it, they announce the row or move the screen
467    /// reader's focus to it.
468    pub reads_active_descendants: bool,
469    /// The operating system.
470    pub os: Os,
471    /// The platform's name where it is not the OS's: a platform built
472    /// outside NSH, on NSH's engine (`docs/dev/platforms.md`), names itself
473    /// here (`Some("miniprogram")`) and reports the OS it runs on in
474    /// [`Environment::os`]. Lower case, none of [`Os`]'s names. `None` on
475    /// NSH's own platforms ([`Environment::platform_name`]).
476    pub platform: Option<&'static str>,
477    /// The OS version: major and minor (iOS, desktops), Android's API level
478    /// and 0.
479    pub os_version: (u16, u16),
480    /// The kind of device.
481    pub idiom: Idiom,
482    /// A browser on an Apple platform (macOS, iOS): its keyboard shortcuts
483    /// follow Apple's conventions ([`crate::keymap::apple_keys`]: `mod` is
484    /// Command, labels use ⌘). Only read for [`Os::Web`]; the other OSes
485    /// imply theirs.
486    pub apple_keyboard: bool,
487    /// Ctrl stands in for Command: the keyboard cannot report Command (a
488    /// terminal on macOS without the kitty keyboard protocol), so a
489    /// `mod+` / `cmd+` shortcut takes Ctrl and labels show it as Ctrl
490    /// ([`crate::keymap::Keystroke::pressed`]).
491    pub ctrl_for_command: bool,
492    /// The user's locale (number and date formats: `Intl`'s default).
493    pub locale: Locale,
494    /// The user's locale settings: the preferred languages, the time zone
495    /// and the regional preferences.
496    pub locale_settings: LocaleSettings,
497    /// The app embedding NSH answers `nsh/host`'s calls
498    /// ([`crate::Command::HostCall`]); without it, they reject at once.
499    pub host: bool,
500    /// Whether the app is in use: in the foreground, visible without the
501    /// focus, or in the background. For an embedded surface, the embedding
502    /// app's.
503    pub lifecycle: Lifecycle,
504    /// How many times the system woke from sleep while the surface ran
505    /// (TS: `wakeCount()`): the platform adds one on each wake (macOS,
506    /// Windows, Linux), so what read it runs again then. A sleep may leave
507    /// the app's state as it was (a laptop's lid closed and opened with the
508    /// app in front), while its network connections and timers did not
509    /// live through it.
510    pub wake_count: u32,
511    /// How the device reaches the network (TS: `network()`): the platform
512    /// reports each change of the system's default route and, on iOS, of
513    /// the cellular data permission. [`NetworkKind::Unknown`] where it has
514    /// no monitor.
515    pub network: Network,
516    /// The platform picks a color from the screen
517    /// ([`crate::Command::PickScreenColor`]); without it, a pick answers
518    /// no color at once.
519    pub screen_color: bool,
520    /// The platform reports whether each clipboard write
521    /// ([`crate::Command::SetClipboard`], [`crate::Command::SetClipboardItem`])
522    /// reached the system clipboard, as [`crate::EventKind::ClipboardWrite`]
523    /// in the order of the writes; without it, a write answers
524    /// [`crate::element::ClipboardWrite::Requested`] at once.
525    pub clipboard_write_result: bool,
526    /// The platform renders canvas drawings offscreen into images
527    /// ([`crate::Command::RenderCanvas`], `OffscreenCanvas`); without it,
528    /// a render fails at once with `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`.
529    pub canvas_render: bool,
530    /// The platform opens the app's own page in the system's settings
531    /// ([`crate::Command::OpenAppSettings`], `nsh/mobile`'s
532    /// `AppSettings.open`: iOS and Android); without it, opening it fails at
533    /// once with `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`
534    /// ([`crate::mobile::open_app_settings`]).
535    pub app_settings: bool,
536    /// Whether the platform hands the app links of the schemes it claims
537    /// (`nsh.json` `schemes`, [`crate::element::next_url_scheme_open`]).
538    /// `None` (the default): as NSH's native backends on [`Self::os`],
539    /// every OS but the web, where a page hears only its own address. The
540    /// GPUI and terminal backends, which hear no links, say `Some(false)`,
541    /// as does a platform built outside NSH that hears none.
542    pub scheme_links: Option<bool>,
543    /// The platform handles file requests ([`crate::Command::FileRequest`]).
544    /// Desktops implement the full set; mobile platforms answer the open
545    /// dialog and reject operations they do not support. Without it, all
546    /// file requests answer at once with an error.
547    pub file_requests: bool,
548    /// The platform shows notifications ([`crate::Command::Notification`],
549    /// [`crate::notifications`]); without it, the permission is
550    /// `unavailable` and nothing shows.
551    pub notifications: bool,
552    /// The platform plays sound ([`crate::Command::Audio`],
553    /// [`crate::audio`]); without it, sounds and players fail at once
554    /// (`unavailable`) unless the core has a [`crate::audio::AudioBackend`].
555    pub audio: bool,
556    /// The platform shows the system's tab bar on iOS and Android
557    /// (`nsh/mobile`'s `TabBar`: it registers [`TAB_BAR_COMPONENT`]). On by
558    /// default, as NSH's own iOS and Android backends do; a platform built
559    /// outside NSH that runs on those OSes without one turns it off, and
560    /// `TabBar` then takes no room and `nsh/mobile`'s `isAvailable` is false,
561    /// so the app shows its tabs with `nsh/base`'s `Tabs`. Read only on iOS
562    /// and Android.
563    pub tab_bar: bool,
564    /// Whether the platform puts images on the system clipboard and reads
565    /// them back (`Clipboard.readImage`, `writeImage`, `hasImage`). `None`
566    /// (the default): yes, as every NSH backend does. A platform built outside
567    /// NSH says what it does with `Some`: without images its image calls
568    /// reject with `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` and `hasImage` is
569    /// false.
570    pub clipboard_images: Option<bool>,
571    /// The size of one Cell of a grid surface (a terminal, whose content is
572    /// whole character Cells), in points; `None` on every other surface.
573    /// With it the core lays out with its terminal algorithm, ratatui's
574    /// splits in whole Cells (x the Cell's width, y its height): a border
575    /// is one Cell and every frame is whole Cells (`docs/dev/styles.md`
576    /// "Layout in a terminal").
577    pub cell: Option<Size<Points>>,
578    /// The platform gives web views trusted input
579    /// ([`crate::Command::SendInput`], macOS and Windows); without it, the
580    /// command does nothing.
581    pub web_input: bool,
582    /// The platform answers awaitable WebView evaluations
583    /// ([`crate::Command::Evaluate`]); false rejects as unavailable.
584    pub web_evaluate: bool,
585    /// The platform shows web views (TS: `WebView.available()`). `true` by
586    /// default; a platform that knows from the start that it shows none
587    /// (built without a web engine, the system's failed to load) sets
588    /// `false`, and every web view then reports `onError` with `code`
589    /// `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`. A web engine that fails only
590    /// when a web view starts reports that error itself.
591    pub web_views: bool,
592    /// The platform carries out a web view's requests
593    /// ([`crate::Command::WebViewRequest`]: a pending download's
594    /// destination or cancellation; the desktops); without it, they answer
595    /// at once with an error and no web view downloads behind the app's
596    /// back.
597    pub webview_requests: bool,
598    /// The platform draws shader views (`Shader`, `ShaderEffect`,
599    /// `ShaderTransition`, the screen's; TS: `shadersAvailable()`). `true`
600    /// by default. A platform built without a renderer sets `false` from
601    /// the start; one that finds no GPU when the first shader mounts
602    /// reports it then (`nsh_engine::EngineControl::shaders_unavailable`),
603    /// so it can turn `false` while the app runs, never back. A grid
604    /// surface ([`Environment::cell`]) draws none.
605    pub shaders: bool,
606}
607
608impl Environment {
609    /// Native horizontal size class, or the window width at the 600pt breakpoint.
610    pub fn horizontal_size_class(&self) -> SizeClass {
611        self.horizontal_size_class
612            .unwrap_or_else(|| SizeClass::from_length(self.window.width))
613    }
614
615    /// Native vertical size class, or the window height at the 600pt breakpoint.
616    pub fn vertical_size_class(&self) -> SizeClass {
617        self.vertical_size_class
618            .unwrap_or_else(|| SizeClass::from_length(self.window.height))
619    }
620
621    /// The platform's name (TS: `platform.name`): [`Environment::platform`]
622    /// on a platform built outside NSH (`"miniprogram"`), else the OS's
623    /// (`"ios"`, `"web"`, ...).
624    pub fn platform_name(&self) -> &'static str {
625        self.platform.unwrap_or(self.os.name())
626    }
627
628    /// Desktop behavior applies: a desktop OS, a browser in the desktop
629    /// idiom or a terminal ([`Idiom::desktop_on`]: `desktop={{…}}` props,
630    /// `platform.select({ desktop })`, `platform.desktop`, `platform.idiom`
631    /// `"desktop"` outside a terminal).
632    pub fn desktop(&self) -> bool {
633        self.idiom.desktop_on(self.os)
634    }
635
636    /// The idiom apps see (TS: `platform.idiom`, [`Idiom::reported_on`]).
637    pub fn reported_idiom(&self) -> Idiom {
638        self.idiom.reported_on(self.os)
639    }
640
641    /// Whether links of the schemes the app claims reach it
642    /// ([`field@Environment::scheme_links`], or by the OS: all but the
643    /// web).
644    pub fn scheme_links(&self) -> bool {
645        self.scheme_links.unwrap_or(self.os != Os::Web)
646    }
647}
648
649impl Default for Environment {
650    fn default() -> Self {
651        Self {
652            window: Size::default(),
653            horizontal_size_class: None,
654            vertical_size_class: None,
655            safe_area: Edges::default(),
656            reserved_regions: ReservedRegions::NONE,
657            title_bar: Edges::default(),
658            window_state: None,
659            keyboard_height: Points(0.0),
660            keyboard_duration: 250.0,
661            color_scheme: ColorScheme::Light,
662            font_scale: 1.0,
663            rtl: false,
664            reduce_motion: false,
665            pixel_ratio: 1.0,
666            screen_reader: false,
667            reads_active_descendants: false,
668            os: Os::default(),
669            platform: None,
670            os_version: (0, 0),
671            idiom: Idiom::Phone,
672            apple_keyboard: false,
673            ctrl_for_command: false,
674            locale: Locale::EN_US,
675            locale_settings: LocaleSettings::EN_US,
676            host: false,
677            lifecycle: Lifecycle::Active,
678            wake_count: 0,
679            network: Network::default(),
680            screen_color: false,
681            clipboard_write_result: false,
682            canvas_render: false,
683            app_settings: false,
684            scheme_links: None,
685            file_requests: false,
686            notifications: false,
687            audio: false,
688            tab_bar: true,
689            clipboard_images: None,
690            cell: None,
691            web_input: false,
692            web_evaluate: false,
693            web_views: true,
694            webview_requests: false,
695            shaders: true,
696        }
697    }
698}
699
700/// The settings an embedding app gives its surfaces in place of the
701/// system's (`None`: the system's): its own language and text size, for an
702/// app inside a native app that lets its users switch them. The platforms
703/// write them over what they read from the system ([`Self::apply`]), so the
704/// app's `Intl`, `locale()`, `localeSettings()`'s languages (its language first),
705/// `fontScale()` and text follow them like a system change.
706#[derive(Debug, Clone, Copy, PartialEq, Default)]
707pub struct HostEnvironment {
708    /// The locale in place of the user's ([`Environment::locale`]).
709    pub locale: Option<Locale>,
710    /// The text size in place of the user's ([`Environment::font_scale`]);
711    /// values that are not finite and positive count as `None`.
712    pub font_scale: Option<f32>,
713}
714
715impl HostEnvironment {
716    /// Writes the settings `self` has over `env`'s.
717    pub fn apply(&self, env: &mut Environment) {
718        if let Some(locale) = self.locale {
719            env.locale = locale;
720            env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
721        }
722        if let Some(scale) = self.font_scale.filter(|s| s.is_finite() && *s > 0.0) {
723            env.font_scale = scale;
724        }
725    }
726}
727
728/// A BCP 47 language tag (`en-US`, `zh-Hans-CN`), held inline so that the
729/// environment stays `Copy`: the language, script and region subtags fit;
730/// variants and extensions are dropped.
731#[derive(Clone, Copy, PartialEq, Eq, Hash)]
732pub struct Locale {
733    bytes: [u8; Locale::CAPACITY],
734    len: u8,
735}
736
737impl Locale {
738    const CAPACITY: usize = 15;
739
740    /// `en-US`, the default when a platform reports none.
741    pub const EN_US: Locale = Locale {
742        bytes: *b"en-US\0\0\0\0\0\0\0\0\0\0",
743        len: 5,
744    };
745
746    /// The tag of a platform locale identifier: `en_US`, `en-US`,
747    /// `de_DE@calendar=gregorian`, `pt_BR.UTF-8` (POSIX) and `zh-Hans_CN`
748    /// all work. Subtags are cased as BCP 47 writes them (`zh-Hans-CN`);
749    /// `None` without a language.
750    pub fn parse(identifier: &str) -> Option<Locale> {
751        let identifier = identifier.split(['@', '.']).next().unwrap_or_default();
752        let mut bytes = [0u8; Self::CAPACITY];
753        let mut len = 0;
754        for (i, part) in identifier.split(['-', '_']).enumerate() {
755            let keep = if i == 0 {
756                (2..=3).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphabetic())
757            } else {
758                // A script (4 letters) or a region (2 letters, 3 digits).
759                (part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()))
760                    || (part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()))
761                    || (part.len() == 3 && part.bytes().all(|b| b.is_ascii_digit()))
762            };
763            if !keep {
764                if i == 0 {
765                    return None;
766                }
767                // A variant or an extension: dropped with what follows.
768                break;
769            }
770            if len + part.len() + usize::from(i > 0) > Self::CAPACITY {
771                break;
772            }
773            if i > 0 {
774                bytes[len] = b'-';
775                len += 1;
776            }
777            for (j, b) in part.bytes().enumerate() {
778                bytes[len] = match (i, part.len()) {
779                    (0, _) => b.to_ascii_lowercase(),
780                    (_, 4) if j == 0 => b.to_ascii_uppercase(),
781                    (_, 4) => b.to_ascii_lowercase(),
782                    _ => b.to_ascii_uppercase(),
783                };
784                len += 1;
785            }
786        }
787        Some(Locale {
788            bytes,
789            len: len as u8,
790        })
791    }
792
793    /// The tag (`en-US`).
794    pub fn as_str(&self) -> &str {
795        // ASCII, as parsed.
796        std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
797    }
798
799    /// The language subtag (`en`).
800    pub fn language(&self) -> &str {
801        self.as_str().split('-').next().unwrap_or_default()
802    }
803
804    /// The region subtag (`US`, `419`), if the tag has one.
805    pub fn region(&self) -> Option<&str> {
806        // What follows the language is a script (4 letters) or a region.
807        self.as_str().split('-').skip(1).find(|s| s.len() != 4)
808    }
809}
810
811impl Default for Locale {
812    fn default() -> Self {
813        Self::EN_US
814    }
815}
816
817impl std::fmt::Debug for Locale {
818    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
819        write!(f, "Locale({})", self.as_str())
820    }
821}
822
823impl std::fmt::Display for Locale {
824    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
825        f.write_str(self.as_str())
826    }
827}
828
829/// What a reserved region asks of the content in it (TS:
830/// `ReservedRegion["kind"]`).
831#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
832#[non_exhaustive]
833pub enum ReservedRegionKind {
834    /// Something covers it (a camera that shows through the display):
835    /// keep what matters out of it.
836    #[default]
837    Occlusion,
838    /// The display divides there (the fold of a partly folded display):
839    /// keep content clear of it, on either side.
840    Division,
841}
842
843impl ReservedRegionKind {
844    /// The kind's name in TS (`"occlusion"`, `"division"`).
845    pub fn name(self) -> &'static str {
846        match self {
847            Self::Occlusion => "occlusion",
848            Self::Division => "division",
849        }
850    }
851}
852
853/// A part of the surface the device reserves (TS: `ReservedRegion`): what
854/// UIKit calls a reserved region (`UIView.ReservedRegion`), Jetpack
855/// WindowManager a display feature.
856#[derive(Debug, Clone, Copy, PartialEq, Default, crate::element::JsObject)]
857#[non_exhaustive]
858pub struct ReservedRegion {
859    /// What it asks of the content in it.
860    pub kind: ReservedRegionKind,
861    /// Where it is, in the surface's points (as layout places views),
862    /// with the margin interactive content keeps from it.
863    pub bounds: Bounds<Points>,
864}
865
866impl ReservedRegion {
867    /// A region of `kind` at `bounds`.
868    pub fn new(kind: ReservedRegionKind, bounds: Bounds<Points>) -> ReservedRegion {
869        ReservedRegion { kind, bounds }
870    }
871}
872
873/// The regions the device reserves in a surface ([`ReservedRegion`]), at
874/// most [`ReservedRegions::CAPACITY`]. Held inline so that the environment
875/// stays `Copy`.
876#[derive(Clone, Copy, PartialEq)]
877pub struct ReservedRegions {
878    regions: [ReservedRegion; ReservedRegions::CAPACITY],
879    len: u8,
880}
881
882impl ReservedRegions {
883    /// How many it keeps: a device reserves a few (iPhone Duo: its fold
884    /// and its cameras); the rest are left out.
885    pub const CAPACITY: usize = 8;
886
887    /// None, the default.
888    pub const NONE: ReservedRegions = ReservedRegions {
889        regions: [ReservedRegion {
890            kind: ReservedRegionKind::Occlusion,
891            bounds: Bounds {
892                origin: crate::geometry::Point {
893                    x: Points(0.0),
894                    y: Points(0.0),
895                },
896                size: Size {
897                    width: Points(0.0),
898                    height: Points(0.0),
899                },
900            },
901        }; ReservedRegions::CAPACITY],
902        len: 0,
903    };
904
905    /// These regions, the first [`ReservedRegions::CAPACITY`] kept.
906    pub fn new(regions: impl IntoIterator<Item = ReservedRegion>) -> ReservedRegions {
907        let mut list = Self::NONE;
908        for region in regions.into_iter().take(Self::CAPACITY) {
909            list.regions[usize::from(list.len)] = region;
910            list.len += 1;
911        }
912        list
913    }
914
915    /// All of them.
916    pub fn as_slice(&self) -> &[ReservedRegion] {
917        &self.regions[..usize::from(self.len)]
918    }
919
920    /// All of them.
921    pub fn iter(&self) -> impl Iterator<Item = ReservedRegion> + '_ {
922        self.as_slice().iter().copied()
923    }
924
925    /// There are none.
926    pub fn is_empty(&self) -> bool {
927        self.len == 0
928    }
929
930    /// How many there are.
931    pub fn len(&self) -> usize {
932        usize::from(self.len)
933    }
934}
935
936impl Default for ReservedRegions {
937    fn default() -> Self {
938        Self::NONE
939    }
940}
941
942impl std::fmt::Debug for ReservedRegions {
943    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
944        f.debug_list().entries(self.as_slice()).finish()
945    }
946}
947
948/// The user's preferred languages, most preferred first, as BCP 47 tags
949/// (`localeSettings()`'s `languages`): never empty, at most eight, each once. Held inline so
950/// that the environment stays `Copy`.
951#[derive(Clone, Copy, PartialEq, Eq, Hash)]
952pub struct Languages {
953    tags: [Locale; Languages::CAPACITY],
954    len: u8,
955}
956
957impl Languages {
958    /// How many it keeps: systems list a few (iOS and Android up to the
959    /// ones the user added, desktops their UI languages).
960    const CAPACITY: usize = 8;
961
962    /// `en-US` alone, the default when a platform reports none.
963    pub(crate) const EN_US: Languages = Languages {
964        tags: [Locale::EN_US; Languages::CAPACITY],
965        len: 1,
966    };
967
968    /// `locale` alone.
969    #[doc(hidden)]
970    pub const fn one(locale: Locale) -> Languages {
971        Languages {
972            tags: [locale; Languages::CAPACITY],
973            len: 1,
974        }
975    }
976
977    /// The languages of platform identifiers, most preferred first
978    /// ([`Locale::parse`]'s forms: `en_US`, `zh-Hans-CN`): ones that name
979    /// no language and repeats are left out, the first eight kept. `None`
980    /// when none is a language.
981    #[doc(hidden)]
982    pub fn parse<'a>(identifiers: impl IntoIterator<Item = &'a str>) -> Option<Languages> {
983        let mut languages = Languages::EN_US;
984        languages.len = 0;
985        for locale in identifiers.into_iter().filter_map(Locale::parse) {
986            if usize::from(languages.len) == Self::CAPACITY {
987                break;
988            }
989            if !languages.as_slice().contains(&locale) {
990                languages.tags[usize::from(languages.len)] = locale;
991                languages.len += 1;
992            }
993        }
994        (languages.len > 0).then_some(languages)
995    }
996
997    /// These with `locale` first (an embedding app's own language, the
998    /// app's `set_locale`): it moves there if it is listed, else comes
999    /// before them (the last one then left out when they are eight).
1000    pub fn preferring(&self, locale: Locale) -> Languages {
1001        let mut languages = Languages::one(locale);
1002        for &other in self.as_slice() {
1003            if usize::from(languages.len) == Self::CAPACITY {
1004                break;
1005            }
1006            if other != locale {
1007                languages.tags[usize::from(languages.len)] = other;
1008                languages.len += 1;
1009            }
1010        }
1011        languages
1012    }
1013
1014    /// The most preferred.
1015    pub fn first(&self) -> Locale {
1016        self.tags[0]
1017    }
1018
1019    /// All of them, most preferred first.
1020    pub fn as_slice(&self) -> &[Locale] {
1021        &self.tags[..usize::from(self.len)]
1022    }
1023
1024    /// All of them, most preferred first.
1025    pub fn iter(&self) -> impl Iterator<Item = Locale> + '_ {
1026        self.as_slice().iter().copied()
1027    }
1028}
1029
1030impl Default for Languages {
1031    fn default() -> Self {
1032        Self::EN_US
1033    }
1034}
1035
1036impl std::fmt::Debug for Languages {
1037    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1038        f.debug_list()
1039            .entries(self.iter().map(|l| l.to_string()))
1040            .finish()
1041    }
1042}
1043
1044/// A time zone's name as the system gives it: an IANA name
1045/// (`Europe/Berlin`, `America/Argentina/Buenos_Aires`, `UTC`), or an offset
1046/// zone where the system has one (Android's `GMT+01:00`). Held inline so
1047/// that the environment stays `Copy`.
1048#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1049#[non_exhaustive]
1050pub struct TimeZone {
1051    bytes: [u8; TimeZone::CAPACITY],
1052    len: u8,
1053}
1054
1055impl TimeZone {
1056    /// Room for any name the tz database's rules allow: parts of at most 14
1057    /// characters, four of them with their slashes in 59 bytes (its longest
1058    /// name, `America/Argentina/ComodRivadavia`, has three in 32), and for
1059    /// the systems' offset zones (`GMT+05:30`). 64 bytes with the length.
1060    const CAPACITY: usize = 63;
1061
1062    /// `UTC`, the default when a platform reports none (and headless).
1063    pub const UTC: TimeZone = {
1064        let mut bytes = [0u8; TimeZone::CAPACITY];
1065        bytes[0] = b'U';
1066        bytes[1] = b'T';
1067        bytes[2] = b'C';
1068        TimeZone { bytes, len: 3 }
1069    };
1070
1071    /// The zone of a platform identifier: an IANA name (`Europe/Berlin`),
1072    /// with POSIX `TZ`'s leading `:` (`:Europe/Berlin`), or as a path into
1073    /// a zone database (`/usr/share/zoneinfo/Europe/Berlin`,
1074    /// `/var/db/timezone/zoneinfo/Europe/Berlin`). `None` for what names no
1075    /// zone: empty, longer than any zone's name, or with characters zone
1076    /// names do not have.
1077    pub fn parse(identifier: &str) -> Option<TimeZone> {
1078        let identifier = identifier.trim();
1079        let name = match identifier.rsplit_once("zoneinfo/") {
1080            Some((_, name)) => name,
1081            None => identifier.strip_prefix(':').unwrap_or(identifier),
1082        };
1083        let valid = !name.is_empty()
1084            && name.len() <= Self::CAPACITY
1085            && name
1086                .bytes()
1087                .all(|b| b.is_ascii_alphanumeric() || b"/_-+:".contains(&b))
1088            && name
1089                .split('/')
1090                .all(|part| !part.is_empty() && part != "." && part != "..");
1091        if !valid {
1092            return None;
1093        }
1094        let mut bytes = [0u8; Self::CAPACITY];
1095        bytes[..name.len()].copy_from_slice(name.as_bytes());
1096        Some(TimeZone {
1097            bytes,
1098            len: name.len() as u8,
1099        })
1100    }
1101
1102    /// The zone a process's local times follow on a POSIX system (Linux,
1103    /// macOS, the BSDs): the one its `TZ` variable (`tz`, `None` when
1104    /// unset) names, as the C library reads it, else the system's
1105    /// (`system`, asked only then), else UTC.
1106    ///
1107    /// `TZ` names a zone of the tz database by its name, with a slash or
1108    /// without (`Europe/Berlin`, `Etc/GMT+5`, `GMT`, `EST`) and with or
1109    /// without its leading `:`, or by a path into the database
1110    /// (`/usr/share/zoneinfo/Asia/Tokyo`); empty, it is UTC. A POSIX rule
1111    /// (`JST-9`, `<+08>-8`, `CET-1CEST,M3.5.0,M10.5.0/3`) names no zone,
1112    /// nor does a path elsewhere (`:/etc/localtime`, the system's): the
1113    /// system's zone is reported for them. The database's few names that
1114    /// read as rules too (`EST5EDT`, `GMT0`) are its zones, which mean the
1115    /// same.
1116    #[doc(hidden)]
1117    pub fn posix(tz: Option<&str>, system: impl FnOnce() -> Option<TimeZone>) -> TimeZone {
1118        let zone = match tz.map(str::trim) {
1119            None => None,
1120            // glibc and tzcode alike take an empty `TZ` for UTC.
1121            Some("") => Some(Self::UTC),
1122            Some(tz) => {
1123                let name = tz.strip_prefix(':').unwrap_or(tz);
1124                if is_posix_rule(name) && !RULE_NAMED_ZONES.contains(&name) {
1125                    None
1126                } else {
1127                    Self::parse(name)
1128                }
1129            }
1130        };
1131        zone.or_else(system).unwrap_or_default()
1132    }
1133
1134    /// The name (`Europe/Berlin`).
1135    pub fn as_str(&self) -> &str {
1136        // ASCII, as parsed.
1137        std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("UTC")
1138    }
1139}
1140
1141/// The tz database's names that read as POSIX rules too (`EST5EDT` is
1142/// Eastern time with US rules, `GMT0` UTC under either reading): the C
1143/// library loads their zones' files.
1144const RULE_NAMED_ZONES: [&str; 7] = [
1145    "EST5EDT", "CST6CDT", "MST7MDT", "PST8PDT", "GMT0", "GMT+0", "GMT-0",
1146];
1147
1148/// Whether `TZ`'s value `tz` is a POSIX rule: a zone abbreviation, quoted
1149/// (`<+08>`) or of three letters or more (`JST`), then its offset from UTC
1150/// (`-9`, `5`, `+5:30`). No zone's name but [`RULE_NAMED_ZONES`] has that
1151/// shape: the database's other names without a slash have no offset
1152/// (`GMT`, `Japan`) or a shorter word before it (`NZ-CHAT`).
1153fn is_posix_rule(tz: &str) -> bool {
1154    let letters = tz.bytes().take_while(u8::is_ascii_alphabetic).count();
1155    tz.starts_with('<')
1156        || letters >= 3
1157            && tz
1158                .as_bytes()
1159                .get(letters)
1160                .is_some_and(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-'))
1161}
1162
1163impl Default for TimeZone {
1164    fn default() -> Self {
1165        Self::UTC
1166    }
1167}
1168
1169impl std::fmt::Debug for TimeZone {
1170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1171        write!(f, "TimeZone({})", self.as_str())
1172    }
1173}
1174
1175impl std::fmt::Display for TimeZone {
1176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1177        f.write_str(self.as_str())
1178    }
1179}
1180
1181/// What the performance monitor measured over the last second
1182/// ([`crate::element::perf_stats`]; TS `perfStats()`), read once a second
1183/// while it measures. More of what the monitor measures can join it.
1184#[non_exhaustive]
1185#[derive(Debug, Clone, Copy, PartialEq, Default, crate::element::JsObject)]
1186pub struct PerfStats {
1187    /// Frames shown per second: display refreshes in which the app changed
1188    /// something. An idle app reads low, which is not slowness.
1189    pub fps: f32,
1190    /// The rate the display refreshes at (Hz), once the monitor saw it
1191    /// refresh.
1192    pub refresh_rate: Option<f32>,
1193    /// The share of recent frames that took longer than one refresh, from 0
1194    /// to 1 (`0.05` is 5%), as TS's `dropped` reads it.
1195    pub dropped: crate::geometry::Percentage,
1196    /// Memory the process owns, in bytes, as the monitor's panel shows it:
1197    /// the physical footprint on Apple platforms (Activity Monitor's Memory
1198    /// column), the resident set elsewhere. `None` where the platform does
1199    /// not say, and on the web.
1200    pub memory: Option<u64>,
1201}
1202
1203impl PerfStats {
1204    /// Stats of `fps` frames a second, the rest unknown: the engine's way
1205    /// to make them (the type is non-exhaustive). Apps read them
1206    /// ([`crate::element::perf_stats`]) and never make one.
1207    #[doc(hidden)]
1208    pub fn new(fps: f32) -> PerfStats {
1209        PerfStats {
1210            fps,
1211            ..PerfStats::default()
1212        }
1213    }
1214}
1215
1216/// The app as it was built (TS: `appInfo()`; Rust:
1217/// [`crate::element::app_info`]): its id, name, version and build number,
1218/// and whether it is a development build. A Rust app's root carries it
1219/// ([`crate::element::Root::app_info`], which nsh's generated code sets
1220/// from `nsh.json`, or from the package: `nsh package --id`, `--name`,
1221/// `--version` and `--build` included); a TSX app's is JS's `appInfo()`.
1222#[derive(Debug, Clone, PartialEq, Eq, Default)]
1223#[non_exhaustive]
1224pub struct AppInfo {
1225    /// The app's id (`nsh.json` `"id"`; a package's as it names it).
1226    pub id: Option<String>,
1227    /// The app's name (`nsh.json` `"name"`; a package's as it names it).
1228    pub name: Option<String>,
1229    /// The app's version (`nsh.json` `"version"`; a package's, `1.0.0`
1230    /// where nothing gives one).
1231    pub version: Option<String>,
1232    /// The build number (`nsh.json` `"build"`; a package's, `1` where
1233    /// nothing gives one).
1234    pub build: Option<u64>,
1235    /// A development build (`nsh run`, `nsh dev`, `nsh test`, a build
1236    /// without `--release`), not a package's.
1237    pub development: bool,
1238}
1239
1240impl AppInfo {
1241    /// From the JSON `appInfo()` reports (`{"id", "name", "version",
1242    /// "build", "development"}`): a key that is missing, `null` or of
1243    /// another type is left unknown, and other keys are ignored.
1244    #[doc(hidden)]
1245    pub fn from_json(value: &crate::JsonValue) -> AppInfo {
1246        let text = |key: &str| value.get(key).and_then(|v| v.as_str()).map(str::to_owned);
1247        AppInfo {
1248            id: text("id"),
1249            name: text("name"),
1250            version: text("version"),
1251            build: value.get("build").and_then(|v| v.as_u64()),
1252            development: value
1253                .get("development")
1254                .and_then(|v| v.as_bool())
1255                .unwrap_or(false),
1256        }
1257    }
1258
1259    /// As `appInfo()` reports it: unknown fields are `null`.
1260    pub fn to_json(&self) -> crate::JsonValue {
1261        serde_json::json!({
1262            "id": self.id,
1263            "name": self.name,
1264            "version": self.version,
1265            "build": self.build,
1266            "development": self.development,
1267        })
1268    }
1269}
1270
1271/// The user's locale settings beside the locale (`locale_settings()`; TS
1272/// `localeSettings()`): the preferred languages, the time zone and the
1273/// regional preferences the systems keep beside the language (Language &
1274/// Region on Apple platforms, Android's regional preferences, Windows'
1275/// region settings). They change together, as the user changes the
1276/// system's settings or travels. Where the user set no regional preference,
1277/// it is the region's. The names are `Intl`'s and Foundation's, so they
1278/// pass into `Intl`'s options as they are.
1279#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1280#[non_exhaustive]
1281pub struct LocaleSettings {
1282    /// The preferred languages, most preferred first (the system's list:
1283    /// the language apps show their text in, then its fallbacks).
1284    pub languages: Languages,
1285    /// The device's time zone, as the system names it (`Europe/Berlin`).
1286    pub time_zone: TimeZone,
1287    /// 12- or 24-hour time.
1288    pub hour_cycle: HourCycle,
1289    /// The day weeks start on: a calendar's first column.
1290    pub first_day_of_week: Weekday,
1291    /// The units of lengths, weights and volumes.
1292    pub measurement_system: MeasurementSystem,
1293    /// The unit of temperatures.
1294    pub temperature_unit: TemperatureUnit,
1295}
1296
1297impl LocaleSettings {
1298    /// `en-US`'s (`en-US` alone, 12-hour time, weeks from Sunday, US units,
1299    /// Fahrenheit) in UTC, the default when a platform reports none.
1300    pub(crate) const EN_US: LocaleSettings = LocaleSettings {
1301        languages: Languages::EN_US,
1302        time_zone: TimeZone::UTC,
1303        hour_cycle: HourCycle::H12,
1304        first_day_of_week: Weekday::Sunday,
1305        measurement_system: MeasurementSystem::Us,
1306        temperature_unit: TemperatureUnit::Fahrenheit,
1307    };
1308
1309    /// `locale`'s: it alone as the languages, UTC, and its region's
1310    /// preferences as CLDR (48) gives them. A locale without a region has
1311    /// the world's: 24-hour time, weeks from Monday, metric units and
1312    /// Celsius.
1313    #[doc(hidden)]
1314    pub fn of(locale: Locale) -> LocaleSettings {
1315        LocaleSettings {
1316            languages: Languages::one(locale),
1317            ..Self::of_region(locale.language(), locale.region().unwrap_or("001"))
1318        }
1319    }
1320
1321    /// The settings a platform locale identifier names: its locale alone
1322    /// as the languages (`en-US` where it names none), UTC, and its
1323    /// region's preferences ([`Self::of`]; the `rg` keyword's region in
1324    /// place of its own), with what its Unicode extension keywords set:
1325    /// `hc` (the hour cycle), `fw` (the first day of the week), `ms` (the
1326    /// measurement system) and `mu` (the temperature unit), written as BCP
1327    /// 47 does (`en-US-u-fw-mon-mu-celsius`, Android's regional
1328    /// preferences) or as ICU does (`en_US@hours=h23;fw=mon;rg=gbzzzz`).
1329    /// Values it does not know are left out.
1330    #[doc(hidden)]
1331    pub fn parse(identifier: &str) -> LocaleSettings {
1332        let identifier = identifier.trim();
1333        let (tag, icu) = identifier.split_once('@').unwrap_or((identifier, ""));
1334        let mut keywords = Keywords::default();
1335        // BCP 47's `-u-` extension: keys of two characters, each followed
1336        // by its value.
1337        let mut extension = false;
1338        let mut key = "";
1339        for subtag in tag.split('.').next().unwrap_or_default().split(['-', '_']) {
1340            if subtag.len() == 1 {
1341                extension = subtag.eq_ignore_ascii_case("u");
1342                key = "";
1343            } else if extension && subtag.len() == 2 {
1344                key = subtag;
1345            } else if extension && !key.is_empty() {
1346                keywords.set(key, subtag);
1347                key = "";
1348            }
1349        }
1350        for keyword in icu.split(';') {
1351            if let Some((key, value)) = keyword.split_once('=') {
1352                keywords.set(key.trim(), value.trim());
1353            }
1354        }
1355        let locale = Locale::parse(identifier);
1356        let language = locale.as_ref().map_or("", Locale::language);
1357        let region = match &keywords.region {
1358            Some((bytes, len)) => std::str::from_utf8(&bytes[..*len]).unwrap_or("001"),
1359            None => locale.as_ref().and_then(Locale::region).unwrap_or("001"),
1360        };
1361        let own = Self::of_region(language, region);
1362        LocaleSettings {
1363            languages: Languages::one(locale.unwrap_or(Locale::EN_US)),
1364            hour_cycle: keywords.hour_cycle.unwrap_or(own.hour_cycle),
1365            first_day_of_week: keywords.first_day_of_week.unwrap_or(own.first_day_of_week),
1366            measurement_system: keywords
1367                .measurement_system
1368                .unwrap_or(own.measurement_system),
1369            temperature_unit: keywords.temperature_unit.unwrap_or(own.temperature_unit),
1370            ..own
1371        }
1372    }
1373
1374    /// CLDR's preferences of `region` (`001`: the world's), for `language`.
1375    fn of_region(language: &str, region: &str) -> LocaleSettings {
1376        let listed = |regions: &[&str]| regions.binary_search(&region).is_ok();
1377        LocaleSettings {
1378            hour_cycle: match (language, region) {
1379                // Where a language's differs from its region's.
1380                ("fr", "CA") | ("ku", "SY") => HourCycle::H23,
1381                ("ar" | "en", "001") => HourCycle::H12,
1382                _ if listed(HOUR12_REGIONS) => HourCycle::H12,
1383                _ => HourCycle::H23,
1384            },
1385            first_day_of_week: if listed(SUNDAY_REGIONS) {
1386                Weekday::Sunday
1387            } else if listed(SATURDAY_REGIONS) {
1388                Weekday::Saturday
1389            } else if listed(FRIDAY_REGIONS) {
1390                Weekday::Friday
1391            } else {
1392                Weekday::Monday
1393            },
1394            measurement_system: match region {
1395                "LR" | "US" => MeasurementSystem::Us,
1396                "GB" | "MM" => MeasurementSystem::Uk,
1397                _ => MeasurementSystem::Metric,
1398            },
1399            temperature_unit: match region {
1400                "BS" | "BZ" | "KY" | "PR" | "PW" | "US" => TemperatureUnit::Fahrenheit,
1401                _ => TemperatureUnit::Celsius,
1402            },
1403            ..Self::default()
1404        }
1405    }
1406}
1407
1408impl Default for LocaleSettings {
1409    fn default() -> Self {
1410        Self::EN_US
1411    }
1412}
1413
1414/// What a locale identifier's extension keywords set.
1415#[derive(Default)]
1416struct Keywords {
1417    hour_cycle: Option<HourCycle>,
1418    first_day_of_week: Option<Weekday>,
1419    measurement_system: Option<MeasurementSystem>,
1420    temperature_unit: Option<TemperatureUnit>,
1421    /// `rg`'s region, upper-cased, and its length.
1422    region: Option<([u8; 3], usize)>,
1423}
1424
1425impl Keywords {
1426    /// Reads `key`'s `value` (BCP 47's key or ICU's name for it).
1427    fn set(&mut self, key: &str, value: &str) {
1428        let is = |names: &[&str]| names.iter().any(|n| key.eq_ignore_ascii_case(n));
1429        let value_is = |name: &str| value.eq_ignore_ascii_case(name);
1430        if is(&["hc", "hours"]) {
1431            self.hour_cycle = HourCycle::parse(value).or(self.hour_cycle);
1432        } else if is(&["fw"]) {
1433            self.first_day_of_week = Weekday::ALL
1434                .into_iter()
1435                .find(|d| value_is(d.code()))
1436                .or(self.first_day_of_week);
1437        } else if is(&["ms", "measure"]) {
1438            self.measurement_system = match () {
1439                _ if value_is("metric") => Some(MeasurementSystem::Metric),
1440                _ if value_is("ussystem") => Some(MeasurementSystem::Us),
1441                _ if value_is("uksystem") => Some(MeasurementSystem::Uk),
1442                _ => self.measurement_system,
1443            };
1444        } else if is(&["mu"]) {
1445            // BCP 47 values have at most 8 characters: `fahrenhe`.
1446            let unit = match value_is("fahrenhe") {
1447                true => Some(TemperatureUnit::Fahrenheit),
1448                false => TemperatureUnit::parse(value),
1449            };
1450            self.temperature_unit = unit.or(self.temperature_unit);
1451        } else if is(&["rg"]) {
1452            // A subdivision: the region (`gb`, `419`), then `zzzz` for all
1453            // of it.
1454            let bytes = value.as_bytes();
1455            let len = match bytes {
1456                [a, b, c, ..] if [a, b, c].iter().all(|b| b.is_ascii_digit()) => 3,
1457                [a, b, ..] if a.is_ascii_alphabetic() && b.is_ascii_alphabetic() => 2,
1458                _ => return,
1459            };
1460            let mut region = [0u8; 3];
1461            for (to, from) in region.iter_mut().zip(bytes) {
1462                *to = from.to_ascii_uppercase();
1463            }
1464            self.region = Some((region, len));
1465        }
1466    }
1467}
1468
1469/// The regions whose times are 12-hour (`timeData`'s preferred `h`).
1470const HOUR12_REGIONS: &[&str] = &[
1471    "419", "AE", "AG", "AL", "AR", "AS", "AU", "BB", "BD", "BH", "BM", "BN", "BO", "BS", "BT",
1472    "CA", "CL", "CO", "CR", "CU", "CY", "DJ", "DM", "DO", "DZ", "EC", "EG", "EH", "ER", "ET", "FJ",
1473    "FM", "GD", "GH", "GM", "GR", "GT", "GU", "GY", "HK", "HN", "IN", "IQ", "JM", "JO", "KH", "KI",
1474    "KN", "KP", "KR", "KW", "KY", "LB", "LC", "LR", "LS", "LY", "MH", "MO", "MP", "MR", "MW", "MX",
1475    "MY", "NA", "NI", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PR", "PS", "PW", "PY", "QA", "SA",
1476    "SB", "SD", "SG", "SL", "SO", "SS", "SV", "SY", "SZ", "TC", "TD", "TN", "TO", "TT", "TW", "UM",
1477    "US", "UY", "VC", "VE", "VG", "VI", "VU", "WS", "YE", "ZM",
1478];
1479
1480/// The regions whose weeks start on Sunday (`weekData`'s `firstDay`).
1481const SUNDAY_REGIONS: &[&str] = &[
1482    "AG", "AS", "BD", "BR", "BS", "BT", "BW", "BZ", "CA", "CO", "DM", "DO", "ET", "GT", "GU", "HK",
1483    "HN", "ID", "IL", "IN", "IS", "JM", "JP", "KE", "KH", "KR", "LA", "MH", "MM", "MO", "MT", "MX",
1484    "MZ", "NI", "NP", "PA", "PE", "PH", "PK", "PR", "PT", "PY", "SA", "SG", "SV", "TH", "TT", "TW",
1485    "UM", "US", "VE", "VI", "WS", "YE", "ZA", "ZW",
1486];
1487
1488/// The regions whose weeks start on Saturday.
1489const SATURDAY_REGIONS: &[&str] = &[
1490    "AF", "BH", "DJ", "DZ", "EG", "IQ", "IR", "JO", "KW", "LY", "OM", "QA", "SD", "SY",
1491];
1492
1493/// The regions whose weeks start on Friday.
1494const FRIDAY_REGIONS: &[&str] = &["MV"];
1495
1496/// How hours are counted, as `Intl`'s `hourCycle` names it.
1497#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1498pub enum HourCycle {
1499    /// 12-hour time from 0 to 11 (`h11`: `0:30 PM`).
1500    H11,
1501    /// 12-hour time from 1 to 12 (`h12`: `12:30 PM`).
1502    #[default]
1503    H12,
1504    /// 24-hour time from 0 to 23 (`h23`: `00:30`).
1505    H23,
1506    /// 24-hour time from 1 to 24 (`h24`: `24:30`).
1507    H24,
1508}
1509
1510impl HourCycle {
1511    /// Its `Intl` name: `"h11"`, `"h12"`, `"h23"` or `"h24"`.
1512    pub fn name(self) -> &'static str {
1513        match self {
1514            HourCycle::H11 => "h11",
1515            HourCycle::H12 => "h12",
1516            HourCycle::H23 => "h23",
1517            HourCycle::H24 => "h24",
1518        }
1519    }
1520
1521    /// The cycle `Intl` names `name` (`"h23"`, in any case).
1522    pub fn parse(name: &str) -> Option<HourCycle> {
1523        [
1524            HourCycle::H11,
1525            HourCycle::H12,
1526            HourCycle::H23,
1527            HourCycle::H24,
1528        ]
1529        .into_iter()
1530        .find(|c| name.eq_ignore_ascii_case(c.name()))
1531    }
1532
1533    /// The cycle of a date pattern's hour field, in the letters of
1534    /// Unicode's patterns (Apple's and ICU's date formats, Windows' time
1535    /// formats): `h` (`h:mm a` is `h12`), `H` (`HH:mm` is `h23`), `K` and
1536    /// `k`. Quoted text (`HH 'Uhr'`) is not read; `None` without an hour.
1537    #[doc(hidden)]
1538    pub fn of_pattern(pattern: &str) -> Option<HourCycle> {
1539        let mut quoted = false;
1540        pattern.chars().find_map(|c| match c {
1541            '\'' => {
1542                quoted = !quoted;
1543                None
1544            }
1545            _ if quoted => None,
1546            'h' => Some(HourCycle::H12),
1547            'H' => Some(HourCycle::H23),
1548            'K' => Some(HourCycle::H11),
1549            'k' => Some(HourCycle::H24),
1550            _ => None,
1551        })
1552    }
1553
1554    /// 12-hour time: times have AM and PM.
1555    pub fn twelve_hour(self) -> bool {
1556        matches!(self, HourCycle::H11 | HourCycle::H12)
1557    }
1558}
1559
1560/// A day of the week.
1561#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1562pub enum Weekday {
1563    /// Monday (1).
1564    Monday = 1,
1565    /// Tuesday (2).
1566    Tuesday,
1567    /// Wednesday (3).
1568    Wednesday,
1569    /// Thursday (4).
1570    Thursday,
1571    /// Friday (5).
1572    Friday,
1573    /// Saturday (6).
1574    Saturday,
1575    /// Sunday (7).
1576    Sunday,
1577}
1578
1579impl Weekday {
1580    /// The days, from Monday.
1581    const ALL: [Weekday; 7] = [
1582        Weekday::Monday,
1583        Weekday::Tuesday,
1584        Weekday::Wednesday,
1585        Weekday::Thursday,
1586        Weekday::Friday,
1587        Weekday::Saturday,
1588        Weekday::Sunday,
1589    ];
1590
1591    /// Its ISO 8601 number, TS's: 1 for Monday to 7 for Sunday (as
1592    /// `Intl.Locale`'s `firstDay` and Temporal's `dayOfWeek` count).
1593    pub fn number(self) -> u8 {
1594        self as u8
1595    }
1596
1597    /// The day of an ISO 8601 number (1 for Monday to 7 for Sunday).
1598    pub fn from_number(number: u8) -> Option<Weekday> {
1599        Self::ALL.get(usize::from(number).checked_sub(1)?).copied()
1600    }
1601
1602    /// Unicode's code for it (`mon`), as the `fw` keyword writes it.
1603    fn code(self) -> &'static str {
1604        match self {
1605            Weekday::Monday => "mon",
1606            Weekday::Tuesday => "tue",
1607            Weekday::Wednesday => "wed",
1608            Weekday::Thursday => "thu",
1609            Weekday::Friday => "fri",
1610            Weekday::Saturday => "sat",
1611            Weekday::Sunday => "sun",
1612        }
1613    }
1614}
1615
1616/// The units of lengths, weights and volumes.
1617#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1618pub enum MeasurementSystem {
1619    /// Metres, kilograms and litres (`metric`).
1620    #[default]
1621    Metric,
1622    /// The US customary units: feet, miles, pounds and gallons (`us`).
1623    Us,
1624    /// The UK's: metric, with miles for distances and pints (`uk`).
1625    Uk,
1626}
1627
1628impl MeasurementSystem {
1629    /// Its TS name: `"metric"`, `"us"` or `"uk"`.
1630    pub fn name(self) -> &'static str {
1631        match self {
1632            MeasurementSystem::Metric => "metric",
1633            MeasurementSystem::Us => "us",
1634            MeasurementSystem::Uk => "uk",
1635        }
1636    }
1637
1638    /// The system TS names `name` (`"metric"`, in any case).
1639    pub fn parse(name: &str) -> Option<MeasurementSystem> {
1640        [
1641            MeasurementSystem::Metric,
1642            MeasurementSystem::Us,
1643            MeasurementSystem::Uk,
1644        ]
1645        .into_iter()
1646        .find(|s| name.eq_ignore_ascii_case(s.name()))
1647    }
1648}
1649
1650/// The unit of temperatures.
1651#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1652pub enum TemperatureUnit {
1653    /// Degrees Celsius (`celsius`).
1654    #[default]
1655    Celsius,
1656    /// Degrees Fahrenheit (`fahrenheit`).
1657    Fahrenheit,
1658}
1659
1660impl TemperatureUnit {
1661    /// Its TS name: `"celsius"` or `"fahrenheit"`.
1662    pub fn name(self) -> &'static str {
1663        match self {
1664            TemperatureUnit::Celsius => "celsius",
1665            TemperatureUnit::Fahrenheit => "fahrenheit",
1666        }
1667    }
1668
1669    /// The unit TS names `name` (`"celsius"`, in any case).
1670    pub fn parse(name: &str) -> Option<TemperatureUnit> {
1671        [TemperatureUnit::Celsius, TemperatureUnit::Fahrenheit]
1672            .into_iter()
1673            .find(|u| name.eq_ignore_ascii_case(u.name()))
1674    }
1675}
1676
1677/// An HTTP request for the platform's network stack (made by JS `fetch`
1678/// and by Rust components' [`crate::element::fetch`]).
1679#[derive(Debug, Clone, PartialEq, Eq)]
1680pub struct HttpRequest {
1681    /// Upper-case method (`GET`, `POST`, ...).
1682    pub method: String,
1683    /// Absolute URL.
1684    pub url: String,
1685    /// Header names and values, in order; names may repeat.
1686    pub headers: Vec<(String, String)>,
1687    /// Request body.
1688    pub body: HttpBody,
1689    /// Follow redirects (`redirect: "follow"`, the default).
1690    pub follow_redirects: bool,
1691    /// How the request uses the platform's HTTP cache (`cache` of
1692    /// `fetch`).
1693    pub cache: HttpCache,
1694}
1695
1696/// How a request uses the HTTP cache: the Fetch standard's
1697/// [cache modes](https://fetch.spec.whatwg.org/#concept-request-cache-mode).
1698///
1699/// Honoured where the platform's network stack has a cache (Web: the
1700/// browser's; macOS / iOS: `NSURLSession`'s). Elsewhere requests always go
1701/// to the network, which every mode but [`HttpCache::OnlyIfCached`]
1702/// allows; that one fails there, as nothing is cached.
1703#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
1704pub enum HttpCache {
1705    /// Use a fresh cached response, revalidate a stale one, store the
1706    /// response (`"default"`).
1707    #[default]
1708    Default,
1709    /// Neither read nor update the cache (`"no-store"`).
1710    NoStore,
1711    /// Skip the cache, then store the response (`"reload"`).
1712    Reload,
1713    /// Revalidate any cached response with the server (`"no-cache"`).
1714    NoCache,
1715    /// Use any cached response, stale or not; else the network
1716    /// (`"force-cache"`).
1717    ForceCache,
1718    /// Use only a cached response; fail without one (`"only-if-cached"`).
1719    OnlyIfCached,
1720}
1721
1722impl HttpCache {
1723    /// The mode's Fetch name (`"no-store"`, ...).
1724    pub fn as_str(self) -> &'static str {
1725        match self {
1726            Self::Default => "default",
1727            Self::NoStore => "no-store",
1728            Self::Reload => "reload",
1729            Self::NoCache => "no-cache",
1730            Self::ForceCache => "force-cache",
1731            Self::OnlyIfCached => "only-if-cached",
1732        }
1733    }
1734
1735    /// The mode named `name` (Fetch's names; `None` for others).
1736    pub fn parse(name: &str) -> Option<Self> {
1737        Some(match name {
1738            "default" => Self::Default,
1739            "no-store" => Self::NoStore,
1740            "reload" => Self::Reload,
1741            "no-cache" => Self::NoCache,
1742            "force-cache" => Self::ForceCache,
1743            "only-if-cached" => Self::OnlyIfCached,
1744            _ => return None,
1745        })
1746    }
1747}
1748
1749impl HttpRequest {
1750    /// A request of `method` (`GET`, `POST`, ...; upper-cased) to `url`,
1751    /// with no headers or body, following redirects.
1752    pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
1753        Self {
1754            method: method.into().to_ascii_uppercase(),
1755            url: url.into(),
1756            headers: Vec::new(),
1757            body: HttpBody::Empty,
1758            follow_redirects: true,
1759            cache: HttpCache::Default,
1760        }
1761    }
1762
1763    /// A `GET` of `url`.
1764    pub fn get(url: impl Into<String>) -> Self {
1765        Self::new("GET", url)
1766    }
1767
1768    /// A `POST` of `body` to `url`.
1769    pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
1770        Self::new("POST", url).body(body)
1771    }
1772
1773    /// Adds the header `name: value`.
1774    #[must_use]
1775    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1776        self.headers.push((name.into(), value.into()));
1777        self
1778    }
1779
1780    /// Sends `body`.
1781    #[must_use]
1782    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
1783        self.body = HttpBody::Bytes(body.into());
1784        self
1785    }
1786
1787    /// Uses the HTTP cache as `cache` says.
1788    #[must_use]
1789    pub fn cache(mut self, cache: HttpCache) -> Self {
1790        self.cache = cache;
1791        self
1792    }
1793}
1794
1795impl From<&str> for HttpRequest {
1796    fn from(url: &str) -> Self {
1797        Self::get(url)
1798    }
1799}
1800
1801impl From<String> for HttpRequest {
1802    fn from(url: String) -> Self {
1803        Self::get(url)
1804    }
1805}
1806
1807/// The body of an [`HttpRequest`].
1808#[derive(Debug, Clone, PartialEq, Eq, Default)]
1809pub enum HttpBody {
1810    /// No body.
1811    #[default]
1812    Empty,
1813    /// All of it, known up front.
1814    Bytes(Vec<u8>),
1815    /// Produced while the request is sent (a `ReadableStream`), in chunks
1816    /// the stack asks for one at a time ([`FetchEvent::BodyWanted`]); sent
1817    /// with chunked transfer encoding.
1818    Stream,
1819}
1820
1821impl HttpBody {
1822    /// No body at all.
1823    pub fn is_empty(&self) -> bool {
1824        match self {
1825            HttpBody::Empty => true,
1826            HttpBody::Bytes(b) => b.is_empty(),
1827            HttpBody::Stream => false,
1828        }
1829    }
1830}
1831
1832/// The status line and headers of a response, before its body.
1833#[derive(Debug, Clone, PartialEq, Eq, Default)]
1834pub struct HttpHead {
1835    /// Status code.
1836    pub status: u16,
1837    /// Reason phrase, if the stack reports one.
1838    pub status_text: String,
1839    /// Final URL, after redirects.
1840    pub url: String,
1841    /// True if a redirect was followed.
1842    pub redirected: bool,
1843    /// Header names and values.
1844    pub headers: Vec<(String, String)>,
1845}
1846
1847/// The media type of the file at `path` (a path or an `asset:/` URL), by
1848/// its extension: what the dev server serves files with and what the
1849/// engine answers requests of the app's files with, so a file has one type
1850/// however it arrives. Browsers need it to load scripts, WebAssembly
1851/// (compiled while it streams only as `application/wasm`), images, fonts
1852/// and media.
1853#[doc(hidden)]
1854pub fn content_type(path: &str) -> &'static str {
1855    match std::path::Path::new(path)
1856        .extension()
1857        .and_then(|e| e.to_str())
1858        .map(str::to_ascii_lowercase)
1859        .as_deref()
1860    {
1861        Some("html") => "text/html; charset=utf-8",
1862        Some("js" | "mjs") => "text/javascript; charset=utf-8",
1863        Some("json" | "map") => "application/json",
1864        Some("webmanifest") => "application/manifest+json",
1865        Some("wasm") => "application/wasm",
1866        Some("css") => "text/css; charset=utf-8",
1867        Some("txt") => "text/plain; charset=utf-8",
1868        Some("png") => "image/png",
1869        Some("jpg" | "jpeg") => "image/jpeg",
1870        Some("gif") => "image/gif",
1871        Some("webp") => "image/webp",
1872        Some("avif") => "image/avif",
1873        Some("svg") => "image/svg+xml",
1874        Some("ico") => "image/x-icon",
1875        Some("heic") => "image/heic",
1876        Some("ttf") => "font/ttf",
1877        Some("otf") => "font/otf",
1878        Some("woff") => "font/woff",
1879        Some("woff2") => "font/woff2",
1880        Some("mp4" | "m4v") => "video/mp4",
1881        Some("webm") => "video/webm",
1882        Some("mov") => "video/quicktime",
1883        Some("mp3") => "audio/mpeg",
1884        Some("m4a") => "audio/mp4",
1885        Some("aac") => "audio/aac",
1886        Some("wav") => "audio/wav",
1887        Some("ogg" | "oga" | "opus") => "audio/ogg",
1888        Some("flac") => "audio/flac",
1889        Some("aif" | "aiff") => "audio/aiff",
1890        Some("caf") => "audio/x-caf",
1891        _ => "application/octet-stream",
1892    }
1893}
1894
1895/// The MIME type of a local file by its name's extension, `""` when the
1896/// name says none (a directory, no extension, one this table lacks), as the
1897/// DOM's `File.type`. File drags and drops report it beside each URL
1898/// (`FileDragEvent::mime_types`): it reads the name only, never the file,
1899/// so it costs nothing while a drag hovers and is the same on every
1900/// platform. `uri` is a `file:` URL or a path.
1901#[doc(hidden)]
1902pub fn file_mime_type(uri: &str) -> &'static str {
1903    let path = uri.split(['?', '#']).next().unwrap_or_default();
1904    let name = path.rsplit('/').next().unwrap_or_default();
1905    let Some((stem, ext)) = name.rsplit_once('.') else {
1906        return "";
1907    };
1908    if stem.is_empty() {
1909        // A dotfile (`.env`): a name, not an extension.
1910        return "";
1911    }
1912    match ext.to_ascii_lowercase().as_str() {
1913        "png" => "image/png",
1914        "jpg" | "jpeg" | "jpe" => "image/jpeg",
1915        "gif" => "image/gif",
1916        "webp" => "image/webp",
1917        "avif" => "image/avif",
1918        "heic" => "image/heic",
1919        "heif" => "image/heif",
1920        "svg" => "image/svg+xml",
1921        "bmp" => "image/bmp",
1922        "tif" | "tiff" => "image/tiff",
1923        "ico" => "image/x-icon",
1924        "mp4" | "m4v" => "video/mp4",
1925        "mov" => "video/quicktime",
1926        "webm" => "video/webm",
1927        "mkv" => "video/x-matroska",
1928        "avi" => "video/x-msvideo",
1929        "mp3" => "audio/mpeg",
1930        "m4a" => "audio/mp4",
1931        "aac" => "audio/aac",
1932        "wav" => "audio/wav",
1933        "ogg" | "oga" | "opus" => "audio/ogg",
1934        "flac" => "audio/flac",
1935        "aif" | "aiff" => "audio/aiff",
1936        "caf" => "audio/x-caf",
1937        "txt" | "text" | "log" => "text/plain",
1938        "md" | "markdown" => "text/markdown",
1939        "csv" => "text/csv",
1940        "tsv" => "text/tab-separated-values",
1941        "html" | "htm" => "text/html",
1942        "css" => "text/css",
1943        "js" | "mjs" => "text/javascript",
1944        "json" => "application/json",
1945        "xml" => "application/xml",
1946        "yaml" | "yml" => "application/yaml",
1947        "pdf" => "application/pdf",
1948        "rtf" => "application/rtf",
1949        "doc" => "application/msword",
1950        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1951        "xls" => "application/vnd.ms-excel",
1952        "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1953        "ppt" => "application/vnd.ms-powerpoint",
1954        "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1955        "zip" => "application/zip",
1956        "gz" | "tgz" => "application/gzip",
1957        "tar" => "application/x-tar",
1958        "7z" => "application/x-7z-compressed",
1959        "rar" => "application/vnd.rar",
1960        "wasm" => "application/wasm",
1961        "ttf" => "font/ttf",
1962        "otf" => "font/otf",
1963        "woff" => "font/woff",
1964        "woff2" => "font/woff2",
1965        _ => "",
1966    }
1967}
1968
1969/// What happens to a request, in order: (for a streamed body) any number
1970/// of `BodyWanted`; then `Head`, `Data`… and `End` — or `Failed` at any
1971/// point.
1972#[derive(Debug, Clone, PartialEq, Eq)]
1973pub enum FetchEvent {
1974    /// A streamed body's next chunk is wanted: first when the stack is
1975    /// ready to send, then each time the last chunk was handed on.
1976    BodyWanted,
1977    /// The response's status and headers arrived.
1978    Head(HttpHead),
1979    /// Bytes of the response body, in order.
1980    Data(Vec<u8>),
1981    /// The body is complete.
1982    End,
1983    /// The request failed (no response, or the body broke off).
1984    Failed(String),
1985}
1986
1987/// What JS asks of a request it made (the JS host queues these for the
1988/// engine, which hands them to the stack).
1989#[derive(Debug, Clone, PartialEq, Eq)]
1990pub enum FetchOp {
1991    /// Make the request.
1992    Start(HttpRequest),
1993    /// The next chunk of a streamed body (after [`FetchEvent::BodyWanted`]).
1994    Send(Vec<u8>),
1995    /// A streamed body is complete.
1996    Finish,
1997    /// Stop (`true`) or go on (`false`) reading the response body: nobody
1998    /// reads what arrived.
1999    Pause(bool),
2000    /// Abort the request (`AbortController`, or the body was cancelled).
2001    Cancel,
2002}
2003
2004#[cfg(test)]
2005mod tests {
2006    #[test]
2007    fn app_info_reads_and_writes_app_infos_json() {
2008        use super::AppInfo;
2009        let json = serde_json::json!({
2010            "id": "com.example.orders",
2011            "name": "Orders",
2012            "version": "2.1.0",
2013            "build": 7,
2014            "development": true,
2015            "store": "play",
2016        });
2017        let info = AppInfo::from_json(&json);
2018        assert_eq!(info.id.as_deref(), Some("com.example.orders"));
2019        assert_eq!(info.name.as_deref(), Some("Orders"));
2020        assert_eq!(info.version.as_deref(), Some("2.1.0"));
2021        assert_eq!(info.build, Some(7));
2022        assert!(info.development);
2023        assert_eq!(AppInfo::from_json(&info.to_json()), info);
2024        // Missing, null or mistyped: unknown.
2025        let partial = AppInfo::from_json(&serde_json::json!({
2026            "id": null,
2027            "version": 2,
2028            "build": "7",
2029        }));
2030        assert_eq!(partial, AppInfo::default());
2031        assert_eq!(
2032            AppInfo::default().to_json(),
2033            serde_json::json!({
2034                "id": null, "name": null, "version": null, "build": null, "development": false,
2035            })
2036        );
2037    }
2038
2039    #[test]
2040    fn scheme_links_follow_the_os_unless_the_platform_says() {
2041        use super::{Environment, Os};
2042        let on = |os: Os, scheme_links: Option<bool>| {
2043            Environment {
2044                os,
2045                scheme_links,
2046                ..Environment::default()
2047            }
2048            .scheme_links()
2049        };
2050        for os in [Os::Ios, Os::Android, Os::MacOs, Os::Windows, Os::Linux] {
2051            assert!(on(os, None), "{os:?}");
2052            assert!(on(os, Some(true)), "{os:?}");
2053            assert!(!on(os, Some(false)), "{os:?}");
2054        }
2055        assert!(!on(Os::Web, None));
2056        assert!(on(Os::Web, Some(true)));
2057        assert!(!on(Os::Web, Some(false)));
2058    }
2059
2060    #[test]
2061    fn size_class_fallback_uses_points_and_native_traits_win() {
2062        use super::{Environment, SizeClass};
2063        use crate::geometry::size_pt;
2064        for (dimension, expected) in [
2065            (0.0, SizeClass::Compact),
2066            (599.5, SizeClass::Compact),
2067            (600.0, SizeClass::Regular),
2068            (1200.0, SizeClass::Regular),
2069        ] {
2070            let env = Environment {
2071                window: size_pt(dimension, dimension),
2072                ..Default::default()
2073            };
2074            assert_eq!(env.horizontal_size_class(), expected);
2075            assert_eq!(env.vertical_size_class(), expected);
2076        }
2077        let env = Environment {
2078            window: size_pt(900.0, 300.0),
2079            horizontal_size_class: Some(SizeClass::Compact),
2080            vertical_size_class: Some(SizeClass::Regular),
2081            ..Default::default()
2082        };
2083        assert_eq!(env.horizontal_size_class(), SizeClass::Compact);
2084        assert_eq!(env.vertical_size_class(), SizeClass::Regular);
2085    }
2086
2087    use super::{
2088        Environment, HostEnvironment, HourCycle, Idiom, Languages, Locale, LocaleSettings,
2089        MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday, content_type, file_mime_type,
2090    };
2091
2092    #[test]
2093    fn desktop_is_a_desktop_os_or_a_desktop_browser() {
2094        let desktop = |os: Os, idiom: Idiom| Environment {
2095            os,
2096            idiom,
2097            ..Environment::default()
2098        };
2099        for (os, idiom, expected) in [
2100            (Os::MacOs, Idiom::Desktop, true),
2101            (Os::Windows, Idiom::Desktop, true),
2102            (Os::Linux, Idiom::Desktop, true),
2103            // A desktop OS is desktop whatever idiom it was given.
2104            (Os::Linux, Idiom::Phone, true),
2105            (Os::Web, Idiom::Desktop, true),
2106            (Os::Web, Idiom::Pad, false),
2107            (Os::Web, Idiom::Phone, false),
2108            (Os::Ios, Idiom::Phone, false),
2109            (Os::Ios, Idiom::Pad, false),
2110            // Mac Catalyst: the iOS backend, mobile in either idiom.
2111            (Os::Ios, Idiom::Mac, false),
2112            (Os::Ios, Idiom::Desktop, false),
2113            (Os::Android, Idiom::Tv, false),
2114        ] {
2115            let env = desktop(os, idiom);
2116            assert_eq!(env.desktop(), expected, "{os:?} {idiom:?}");
2117            // `platform.idiom` is "desktop" exactly where desktop applies.
2118            assert_eq!(
2119                env.reported_idiom() == Idiom::Desktop,
2120                expected,
2121                "{os:?} {idiom:?}"
2122            );
2123        }
2124        assert_eq!(desktop(Os::Ios, Idiom::Mac).reported_idiom(), Idiom::Mac);
2125        assert_eq!(
2126            desktop(Os::Ios, Idiom::Desktop).reported_idiom(),
2127            Idiom::Phone
2128        );
2129        assert!(!Os::MacOs.is_catalyst() && !Os::Web.is_catalyst());
2130        assert_eq!(Os::Ios.is_catalyst(), cfg!(target_abi = "macabi"));
2131    }
2132
2133    #[test]
2134    fn desktop_behavior_applies_in_the_terminal_idiom_on_any_os() {
2135        for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Web] {
2136            assert!(Idiom::Terminal.desktop_on(os), "{os:?}");
2137            assert_eq!(Idiom::Terminal.reported_on(os), Idiom::Terminal, "{os:?}");
2138        }
2139    }
2140
2141    #[test]
2142    fn a_host_environment_replaces_what_it_sets() {
2143        let mut env = Environment {
2144            font_scale: 1.25,
2145            ..Environment::default()
2146        };
2147        HostEnvironment::default().apply(&mut env);
2148        assert_eq!((env.locale, env.font_scale), (Locale::EN_US, 1.25));
2149        let zh = Locale::parse("zh-Hans-CN").unwrap();
2150        HostEnvironment {
2151            locale: Some(zh),
2152            font_scale: Some(f32::NAN),
2153        }
2154        .apply(&mut env);
2155        assert_eq!((env.locale, env.font_scale), (zh, 1.25));
2156        HostEnvironment {
2157            locale: None,
2158            font_scale: Some(1.5),
2159        }
2160        .apply(&mut env);
2161        assert_eq!((env.locale, env.font_scale), (zh, 1.5));
2162    }
2163
2164    #[test]
2165    fn languages_parse_platform_identifiers_and_an_embedding_app_goes_first() {
2166        let tags = |l: Languages| l.iter().map(|l| l.to_string()).collect::<Vec<_>>();
2167        let system = Languages::parse(["de_DE", "C", "en-US", "de-DE", "fr"]).unwrap();
2168        assert_eq!(tags(system), ["de-DE", "en-US", "fr"]);
2169        assert_eq!(system.first().as_str(), "de-DE");
2170        assert_eq!(Languages::parse(["C", ""]), None);
2171        let many: Vec<String> = (0..20)
2172            .map(|i| format!("x{}", (b'a' + i) as char))
2173            .collect();
2174        let many = Languages::parse(many.iter().map(String::as_str)).unwrap();
2175        assert_eq!(many.as_slice().len(), Languages::CAPACITY);
2176        let fr = Locale::parse("fr").unwrap();
2177        assert_eq!(tags(system.preferring(fr)), ["fr", "de-DE", "en-US"]);
2178        let ja = Locale::parse("ja-JP").unwrap();
2179        assert_eq!(
2180            tags(system.preferring(ja)),
2181            ["ja-JP", "de-DE", "en-US", "fr"]
2182        );
2183        assert_eq!(tags(Languages::default()), ["en-US"]);
2184        // An embedding app's language comes first.
2185        let mut env = Environment::default();
2186        env.locale_settings.languages = system;
2187        HostEnvironment {
2188            locale: Some(ja),
2189            font_scale: None,
2190        }
2191        .apply(&mut env);
2192        assert_eq!(
2193            tags(env.locale_settings.languages),
2194            ["ja-JP", "de-DE", "en-US", "fr"]
2195        );
2196    }
2197
2198    #[test]
2199    fn locales_parse_platform_identifiers() {
2200        let tag = |s: &str| Locale::parse(s).map(|l| l.as_str().to_owned());
2201        assert_eq!(tag("en_US").as_deref(), Some("en-US"));
2202        assert_eq!(tag("zh-hans_cn").as_deref(), Some("zh-Hans-CN"));
2203        assert_eq!(tag("de_DE@calendar=gregorian").as_deref(), Some("de-DE"));
2204        assert_eq!(tag("pt_BR.UTF-8").as_deref(), Some("pt-BR"));
2205        assert_eq!(tag("es-419").as_deref(), Some("es-419"));
2206        assert_eq!(tag("en-US-u-hc-h23").as_deref(), Some("en-US"));
2207        assert_eq!(tag("C"), None);
2208        assert_eq!(Locale::default().as_str(), "en-US");
2209        let zh = Locale::parse("zh-Hans-CN").unwrap();
2210        assert_eq!((zh.language(), zh.region()), ("zh", Some("CN")));
2211        assert_eq!(Locale::parse("zh-Hans").unwrap().region(), None);
2212        assert_eq!(Locale::parse("es-419").unwrap().region(), Some("419"));
2213    }
2214
2215    #[test]
2216    fn regional_preferences_are_the_regions_unless_the_locale_sets_others() {
2217        // The regional part of the settings: what the locale decides.
2218        type Regional = (HourCycle, Weekday, MeasurementSystem, TemperatureUnit);
2219        let regional = |s: LocaleSettings| -> Regional {
2220            (
2221                s.hour_cycle,
2222                s.first_day_of_week,
2223                s.measurement_system,
2224                s.temperature_unit,
2225            )
2226        };
2227        let of = |tag: &str| LocaleSettings::of(Locale::parse(tag).unwrap());
2228        let us = regional(LocaleSettings::default());
2229        let world = (
2230            HourCycle::H23,
2231            Weekday::Monday,
2232            MeasurementSystem::Metric,
2233            TemperatureUnit::Celsius,
2234        );
2235        assert_eq!(regional(of("en-US")), us);
2236        assert_eq!(
2237            LocaleSettings::default().languages.as_slice(),
2238            &[Locale::EN_US]
2239        );
2240        assert_eq!(LocaleSettings::default().time_zone, TimeZone::UTC);
2241        // The locale alone is the languages.
2242        assert_eq!(
2243            of("de-DE").languages.as_slice(),
2244            &[Locale::parse("de-DE").unwrap()]
2245        );
2246        assert_eq!(regional(of("de-DE")), world);
2247        // Without a region: the world's.
2248        assert_eq!(regional(of("ja")), world);
2249        assert_eq!(of("en-CA").hour_cycle, HourCycle::H12);
2250        // Where the language's differs from the region's.
2251        assert_eq!(of("fr-CA").hour_cycle, HourCycle::H23);
2252        assert_eq!(of("fr-CA").first_day_of_week, Weekday::Sunday);
2253        assert_eq!(of("en-001").hour_cycle, HourCycle::H12);
2254        assert_eq!(of("es-419").hour_cycle, HourCycle::H12);
2255        assert_eq!(of("ar-EG").first_day_of_week, Weekday::Saturday);
2256        assert_eq!(of("dv-MV").first_day_of_week, Weekday::Friday);
2257        let gb = of("en-GB");
2258        assert_eq!(gb.measurement_system, MeasurementSystem::Uk);
2259        assert_eq!(gb.temperature_unit, TemperatureUnit::Celsius);
2260        assert_eq!(of("en-LR").temperature_unit, TemperatureUnit::Celsius);
2261        assert_eq!(of("es-PR").temperature_unit, TemperatureUnit::Fahrenheit);
2262
2263        let parse = |identifier: &str| regional(LocaleSettings::parse(identifier));
2264        assert_eq!(
2265            parse("en-US-u-fw-mon-mu-celsius"),
2266            (
2267                HourCycle::H12,
2268                Weekday::Monday,
2269                MeasurementSystem::Us,
2270                TemperatureUnit::Celsius
2271            )
2272        );
2273        assert_eq!(
2274            parse("en_US@hours=h23;measure=metric"),
2275            (
2276                HourCycle::H23,
2277                Weekday::Sunday,
2278                MeasurementSystem::Metric,
2279                TemperatureUnit::Fahrenheit
2280            )
2281        );
2282        assert_eq!(parse("en_US@rg=gbzzzz"), regional(gb));
2283        assert_eq!(
2284            parse("ar-u-ca-islamic-umalqura-hc-h11-rg-uszzzz"),
2285            (HourCycle::H11, us.1, us.2, us.3)
2286        );
2287        assert_eq!(
2288            LocaleSettings::parse("en-GB-u-ms-ussystem-mu-fahrenhe").measurement_system,
2289            MeasurementSystem::Us
2290        );
2291        // What it does not know is left out.
2292        assert_eq!(parse("de_DE.UTF-8@fw=xyz;hours=h99;rg=1"), world);
2293        assert_eq!(parse("en-US-x-hc-h23"), us);
2294        assert_eq!(parse("C"), world);
2295        // Its locale is the languages, `en-US` where it names none.
2296        assert_eq!(
2297            LocaleSettings::parse("de_DE.UTF-8").languages.as_slice(),
2298            &[Locale::parse("de-DE").unwrap()]
2299        );
2300        assert_eq!(
2301            LocaleSettings::parse("C").languages.as_slice(),
2302            &[Locale::EN_US]
2303        );
2304        assert_eq!(Weekday::from_number(7), Some(Weekday::Sunday));
2305        assert_eq!(Weekday::from_number(0), None);
2306        assert_eq!(Weekday::Monday.number(), 1);
2307        assert!(HourCycle::H11.twelve_hour() && !HourCycle::H24.twelve_hour());
2308        assert_eq!(HourCycle::of_pattern("h:mm a"), Some(HourCycle::H12));
2309        assert_eq!(HourCycle::of_pattern("HH 'Uhr'"), Some(HourCycle::H23));
2310        assert_eq!(HourCycle::of_pattern("'h' K:mm"), Some(HourCycle::H11));
2311        assert_eq!(HourCycle::of_pattern("mm:ss"), None);
2312    }
2313
2314    #[test]
2315    fn time_zones_parse_platform_identifiers() {
2316        let zone = |s: &str| TimeZone::parse(s).map(|z| z.as_str().to_owned());
2317        assert_eq!(zone("Europe/Berlin").as_deref(), Some("Europe/Berlin"));
2318        assert_eq!(zone(":Asia/Tokyo").as_deref(), Some("Asia/Tokyo"));
2319        assert_eq!(
2320            zone("/var/db/timezone/zoneinfo/America/Argentina/Buenos_Aires").as_deref(),
2321            Some("America/Argentina/Buenos_Aires")
2322        );
2323        assert_eq!(
2324            zone("/usr/share/zoneinfo/Etc/GMT+5").as_deref(),
2325            Some("Etc/GMT+5")
2326        );
2327        assert_eq!(zone("GMT+01:00").as_deref(), Some("GMT+01:00"));
2328        assert_eq!(
2329            zone("America/Argentina/ComodRivadavia").as_deref(),
2330            Some("America/Argentina/ComodRivadavia")
2331        );
2332        assert_eq!(zone(""), None);
2333        assert_eq!(zone("Europe//Berlin"), None);
2334        assert_eq!(zone("../etc/passwd"), None);
2335        assert_eq!(zone("Central European Standard Time"), None);
2336        let parts = ["Abcdefghijklmn"; 4].join("/");
2337        assert_eq!(zone(&parts).as_deref(), Some(parts.as_str()));
2338        assert_eq!(zone(&"A".repeat(64)), None);
2339        assert_eq!(TimeZone::default().as_str(), "UTC");
2340        assert_eq!(
2341            Environment::default().locale_settings.time_zone,
2342            TimeZone::UTC
2343        );
2344    }
2345
2346    #[test]
2347    fn posix_time_zones_follow_the_zone_tz_names() {
2348        // A system zone other than UTC, so that falling back on it shows.
2349        let singapore = || TimeZone::parse("Asia/Singapore");
2350        let zone = |tz: Option<&str>| TimeZone::posix(tz, singapore).as_str().to_owned();
2351        // `TZ=GMT` is the process's zone, eight hours from the system's.
2352        assert_eq!(zone(Some("GMT")), "GMT");
2353        assert_eq!(
2354            TimeZone::posix(Some("GMT"), || unreachable!("TZ names the zone")).as_str(),
2355            "GMT"
2356        );
2357        // The tz database's names, with a slash or without, and with `:`.
2358        for name in [
2359            "UTC",
2360            "EST",
2361            "Japan",
2362            "NZ-CHAT",
2363            "Etc/GMT+5",
2364            "Europe/Berlin",
2365            "EST5EDT",
2366            "GMT0",
2367            "GMT-0",
2368        ] {
2369            assert_eq!(zone(Some(name)), name);
2370            assert_eq!(zone(Some(&format!(":{name}"))), name);
2371        }
2372        assert_eq!(zone(Some(":/usr/share/zoneinfo/Asia/Tokyo")), "Asia/Tokyo");
2373        // An empty `TZ` is UTC.
2374        assert_eq!(zone(Some("")), "UTC");
2375        // POSIX rules and other files name no zone: the system's stands.
2376        for tz in [
2377            "JST-9",
2378            "EST5",
2379            "CET-1CEST",
2380            "<+08>-8",
2381            "CET-1CEST,M3.5.0,M10.5.0/3",
2382            "GMT+01:00",
2383            ":/etc/localtime",
2384            ":",
2385        ] {
2386            assert_eq!(zone(Some(tz)), "Asia/Singapore", "TZ={tz}");
2387        }
2388        assert_eq!(zone(None), "Asia/Singapore");
2389        assert_eq!(TimeZone::posix(None, || None), TimeZone::UTC);
2390    }
2391
2392    #[test]
2393    fn content_types_follow_the_extension_of_paths_and_asset_urls() {
2394        assert_eq!(
2395            content_type("dist/app.js"),
2396            "text/javascript; charset=utf-8"
2397        );
2398        assert_eq!(content_type("nsh.WASM"), "application/wasm");
2399        assert_eq!(
2400            content_type("asset:/@app/locales/en.json"),
2401            "application/json"
2402        );
2403        assert_eq!(content_type("asset:/images/flag@2x.png"), "image/png");
2404        assert_eq!(content_type("asset:/fonts/Inter.woff2"), "font/woff2");
2405        assert_eq!(content_type("asset:/sounds/chime.OGG"), "audio/ogg");
2406        for unknown in ["asset:/data.bin", "asset:/README", "asset:/.png"] {
2407            assert_eq!(
2408                content_type(unknown),
2409                "application/octet-stream",
2410                "{unknown}"
2411            );
2412        }
2413    }
2414
2415    #[test]
2416    fn file_mime_types_come_from_the_name_alone() {
2417        assert_eq!(file_mime_type("file:///tmp/a%20b.PNG"), "image/png");
2418        assert_eq!(file_mime_type("file:///tmp/%E4%B8%AD.jpeg"), "image/jpeg");
2419        assert_eq!(file_mime_type("/Users/me/Report.pdf"), "application/pdf");
2420        assert_eq!(
2421            file_mime_type("file:///tmp/notes.md?x=1#y"),
2422            "text/markdown"
2423        );
2424        assert_eq!(file_mime_type("C:/Users/me/Clip.mov"), "video/quicktime");
2425        // A directory, no extension, a dotfile, an extension the table lacks.
2426        for none in [
2427            "file:///tmp/photos.d/",
2428            "file:///tmp/README",
2429            "file:///tmp/.env",
2430            "file:///tmp/a.unknownext",
2431            "",
2432        ] {
2433            assert_eq!(file_mime_type(none), "", "{none}");
2434        }
2435    }
2436}
2437
2438/// Logs, once per backend and command kind, that a backend ignores a command.
2439///
2440/// Backends call this from their catch-all arm so an app learns that a call
2441/// does nothing on this platform, without one log line per frame or call. The
2442/// kind is the leading variant chain of the command's `Debug` output (for
2443/// `Desktop(SetAttributes(..))`, `Desktop(SetAttributes`), so commands with
2444/// different payloads share one warning.
2445pub fn warn_unsupported(backend: &str, command: &dyn std::fmt::Debug) {
2446    use std::{
2447        collections::HashSet,
2448        sync::{Mutex, OnceLock},
2449    };
2450
2451    static SEEN: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
2452    let debug = format!("{command:?}");
2453    let key = format!("{backend}:{}", unsupported_kind(&debug));
2454    let seen = SEEN.get_or_init(Default::default);
2455    if seen
2456        .lock()
2457        .map(|mut seen| seen.insert(key))
2458        .unwrap_or(false)
2459    {
2460        log::warn!(
2461            "{backend}: {} is not supported on this platform and is ignored",
2462            unsupported_kind(&debug)
2463        );
2464    }
2465}
2466
2467/// The leading `Variant(Variant` (at most two levels) of a `Debug` string.
2468fn unsupported_kind(debug: &str) -> &str {
2469    let mut end = 0;
2470    let bytes = debug.as_bytes();
2471    let mut i = 0;
2472    // A command and, for grouped commands such as `Desktop`, its subcommand.
2473    for _ in 0..2 {
2474        let start = i;
2475        // Variants start with an uppercase letter; a number or a string is a payload.
2476        if !bytes.get(i).is_some_and(u8::is_ascii_uppercase) {
2477            break;
2478        }
2479        while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
2480            i += 1;
2481        }
2482        if i == start {
2483            break;
2484        }
2485        end = i;
2486        if i < bytes.len() && bytes[i] == b'(' {
2487            i += 1;
2488        } else {
2489            break;
2490        }
2491    }
2492    if end == 0 { debug } else { &debug[..end] }
2493}
2494
2495#[cfg(test)]
2496mod unsupported_tests {
2497    use super::unsupported_kind;
2498
2499    #[test]
2500    fn kind_is_the_variant_chain() {
2501        assert_eq!(
2502            unsupported_kind("Desktop(SetAttributes(Foo { a: 1 }))"),
2503            "Desktop(SetAttributes"
2504        );
2505        assert_eq!(unsupported_kind("Share { text: \"x\" }"), "Share");
2506        assert_eq!(unsupported_kind("Vibrate(12)"), "Vibrate");
2507        assert_eq!(unsupported_kind("Quit"), "Quit");
2508    }
2509}