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