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/// Whether native component `name` is NSH's own: names under `nsh/` are, and
16/// an embedding app's registration of one is refused, so it can never
17/// replace what NSH's exports render.
18pub fn is_reserved_component(name: &str) -> bool {
19    name.starts_with("nsh/")
20}
21
22/// The system appearance.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum ColorScheme {
25    /// Light mode.
26    #[default]
27    Light,
28    /// Dark mode.
29    Dark,
30}
31
32/// The appearance an app asks for (`nsh.json` `"appearance"`, TS
33/// `setColorScheme`): one of its own, or the system's.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
35pub enum Appearance {
36    /// The system appearance (default).
37    #[default]
38    System,
39    /// Always light.
40    Light,
41    /// Always dark.
42    Dark,
43}
44
45impl Appearance {
46    /// The color scheme shown when the system's is `system`.
47    pub fn resolve(self, system: ColorScheme) -> ColorScheme {
48        match self {
49            Appearance::System => system,
50            Appearance::Light => ColorScheme::Light,
51            Appearance::Dark => ColorScheme::Dark,
52        }
53    }
54}
55
56/// What the user last gave a surface input with
57/// (`EngineControl::set_input_modality`): the core shows the keyboard focus
58/// (`focus-visible:`) by it, as browsers decide CSS's `:focus-visible`.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum InputModality {
61    /// A key press (not a modifier alone): Tab, an arrow, a shortcut,
62    /// typing, from a hardware keyboard.
63    Keyboard,
64    /// A mouse button, a pen or a finger going down.
65    Pointer,
66}
67
68/// The operating system (`platform.os`).
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Os {
71    /// iOS, iPadOS, Mac Catalyst.
72    Ios,
73    /// Android.
74    Android,
75    /// macOS (a desktop backend).
76    MacOs,
77    /// Windows.
78    Windows,
79    /// Linux.
80    Linux,
81    /// A web browser (the WebAssembly runtime): phone, tablet or desktop
82    /// by [`Idiom`].
83    Web,
84}
85
86impl Os {
87    /// Its `platform.os` name.
88    pub fn name(self) -> &'static str {
89        match self {
90            Os::Ios => "ios",
91            Os::Android => "android",
92            Os::MacOs => "macos",
93            Os::Windows => "windows",
94            Os::Linux => "linux",
95            Os::Web => "web",
96        }
97    }
98
99    /// The OS of a desktop backend (macOS, Windows, Linux): it has windows
100    /// and menus (`nsh/desktop`'s `isAvailable`). Desktop behavior
101    /// (`desktop={{…}}` props, `platform.select({ desktop })`,
102    /// `platform.desktop`) also covers browsers in the desktop idiom:
103    /// [`Environment::desktop`].
104    pub fn is_desktop(self) -> bool {
105        matches!(self, Os::MacOs | Os::Windows | Os::Linux)
106    }
107
108    /// iOS running under Mac Catalyst, in every idiom (`platform.catalyst`):
109    /// this build is Catalyst's (`target_abi = "macabi"`). Catalyst runs the
110    /// iOS backend, so it is mobile, not desktop: `ios={{…}}` props apply and
111    /// `nsh/desktop`'s window and menu APIs are not there.
112    pub fn is_catalyst(self) -> bool {
113        self == Os::Ios && cfg!(target_abi = "macabi")
114    }
115}
116
117impl Default for Os {
118    /// The mobile OS of this build (headless runs, `nsh test`, behave as iOS); desktop
119    /// backends set theirs.
120    fn default() -> Self {
121        if cfg!(target_os = "android") {
122            Os::Android
123        } else {
124            Os::Ios
125        }
126    }
127}
128
129/// The kind of device (`platform.idiom`).
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
131pub enum Idiom {
132    /// A phone.
133    #[default]
134    Phone,
135    /// A tablet.
136    Pad,
137    /// UIKit's Mac idiom (Mac Catalyst optimized for Mac). Catalyst runs
138    /// the iOS backend, so this idiom is mobile, not [`Idiom::Desktop`].
139    Mac,
140    /// A TV.
141    Tv,
142    /// Desktop: a desktop backend (macOS, Windows, Linux), or a browser with
143    /// a mouse and a wide viewport ([`Idiom::desktop_on`]). Mac Catalyst is
144    /// [`Idiom::Pad`] or [`Idiom::Mac`], as UIKit reports.
145    Desktop,
146    /// A terminal: drawn on a grid of Cells, keyboard first (the terminal
147    /// backend). The OS stays the machine's; desktop behavior applies.
148    Terminal,
149}
150
151impl Idiom {
152    /// Whether desktop behavior applies on `os` in this idiom, NSH's one
153    /// definition of desktop: a desktop OS (macOS, Windows, Linux), a
154    /// browser in the desktop idiom, or a terminal. `desktop={{…}}` props,
155    /// `platform.select({ desktop })` and `platform.desktop` all follow it,
156    /// and so does `platform.idiom === "desktop"` outside a terminal
157    /// ([`Idiom::reported_on`]).
158    pub fn desktop_on(self, os: Os) -> bool {
159        os.is_desktop() || (os == Os::Web && self == Idiom::Desktop) || self == Idiom::Terminal
160    }
161
162    /// The idiom apps see on `os` (TS: `platform.idiom`): [`Idiom::Terminal`]
163    /// in a terminal, else [`Idiom::Desktop`] exactly where
164    /// [`Idiom::desktop_on`] holds, so that `"desktop"` agrees with desktop
165    /// behavior whatever a platform (or a test) set. Elsewhere this idiom,
166    /// and [`Idiom::Phone`] for [`Idiom::Desktop`] on a mobile OS.
167    pub fn reported_on(self, os: Os) -> Idiom {
168        if self == Idiom::Terminal {
169            Idiom::Terminal
170        } else if self.desktop_on(os) {
171            Idiom::Desktop
172        } else if self == Idiom::Desktop {
173            Idiom::Phone
174        } else {
175            self
176        }
177    }
178}
179
180/// Whether the app is in use (`lifecycle()`), in React Native's `AppState`
181/// terms.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
183pub enum Lifecycle {
184    /// In the foreground and taking input.
185    #[default]
186    Active,
187    /// Still visible, but not taking input: another app or window has the
188    /// focus, or the system shows something over it (the app switcher, an
189    /// incoming call, Control Center).
190    Inactive,
191    /// Not visible: in the background, minimized or hidden. The system may
192    /// suspend it there.
193    Background,
194}
195
196impl Lifecycle {
197    /// Its `lifecycle()` name: `"active"`, `"inactive"` or `"background"`.
198    pub fn name(self) -> &'static str {
199        match self {
200            Lifecycle::Active => "active",
201            Lifecycle::Inactive => "inactive",
202            Lifecycle::Background => "background",
203        }
204    }
205}
206
207/// What the platform knows about the surface.
208#[derive(Debug, Clone, Copy, PartialEq)]
209pub struct Environment {
210    /// Size of the surface in points.
211    pub window: Size<Points>,
212    /// Insets not covered by system UI (notch, home indicator, title bar).
213    pub safe_area: Edges<Points>,
214    /// The title bar's area while the app hides it (desktops,
215    /// [`crate::desktop::TitleBarStyle::Hidden`]): `top` is its height,
216    /// `left` and `right` the widths the system's window controls take at
217    /// its ends (`bottom` is 0); all 0 while the system shows its title
218    /// bar.
219    pub title_bar: Edges<Points>,
220    /// The app's window: its bounds on the screen, its mode and display
221    /// (desktops; `None` elsewhere and where the surface has no window).
222    /// The engine holds back a move or resize until the window stops for
223    /// a moment, so platforms report every change.
224    pub window_state: Option<crate::desktop::WindowState>,
225    /// Height of the software keyboard over the surface; 0 when hidden.
226    pub keyboard_height: Points,
227    /// Duration of the keyboard's show / hide animation in milliseconds.
228    pub keyboard_duration: f32,
229    /// Light or dark appearance.
230    pub color_scheme: ColorScheme,
231    /// Preferred text size relative to the default (1.0).
232    pub font_scale: f32,
233    /// The user's language is written right to left.
234    pub rtl: bool,
235    /// The user asked for less motion (iOS Reduce Motion, Android's
236    /// animator duration scale at 0).
237    pub reduce_motion: bool,
238    /// Device pixels per point.
239    pub pixel_ratio: f32,
240    /// A screen reader runs (VoiceOver, TalkBack).
241    pub screen_reader: bool,
242    /// The operating system.
243    pub os: Os,
244    /// The platform's name where it is not the OS's: a platform built
245    /// outside NSH, on NSH's engine (`docs/dev/platforms.md`), names itself
246    /// here (`Some("miniprogram")`) and reports the OS it runs on in
247    /// [`Environment::os`]. Lower case, none of [`Os`]'s names. `None` on
248    /// NSH's own platforms ([`Environment::platform_name`]).
249    pub platform: Option<&'static str>,
250    /// The OS version: major and minor (iOS, desktops), Android's API level
251    /// and 0.
252    pub os_version: (u16, u16),
253    /// The kind of device.
254    pub idiom: Idiom,
255    /// A browser on an Apple platform (macOS, iOS): its keyboard shortcuts
256    /// follow Apple's conventions ([`crate::keymap::apple_keys`]: `mod` is
257    /// Command, labels use ⌘). Only read for [`Os::Web`]; the other OSes
258    /// imply theirs.
259    pub apple_keyboard: bool,
260    /// Ctrl stands in for Command: the keyboard cannot report Command (a
261    /// terminal on macOS without the kitty keyboard protocol), so a
262    /// `mod+` / `cmd+` shortcut takes Ctrl and labels show it as Ctrl
263    /// ([`crate::keymap::Keystroke::pressed`]).
264    pub ctrl_for_command: bool,
265    /// The user's locale (number and date formats: `Intl`'s default).
266    pub locale: Locale,
267    /// The user's locale settings: the preferred languages, the time zone
268    /// and the regional preferences.
269    pub locale_settings: LocaleSettings,
270    /// The app embedding NSH answers `nsh/host`'s calls
271    /// ([`crate::Command::HostCall`]); without it, they reject at once.
272    pub host: bool,
273    /// Whether the app is in use: in the foreground, visible without the
274    /// focus, or in the background. For an embedded surface, the embedding
275    /// app's.
276    pub lifecycle: Lifecycle,
277    /// The platform picks a color from the screen
278    /// ([`crate::Command::PickScreenColor`]); without it, a pick answers
279    /// no color at once.
280    pub screen_color: bool,
281    /// The platform shows the system's open and save dialogs and opens,
282    /// reveals and trashes local paths ([`crate::Command::FileRequest`],
283    /// the desktops); without it, those requests answer at once with an
284    /// error.
285    pub file_requests: bool,
286    /// The platform recognizes speech ([`crate::Command::Speech`],
287    /// [`crate::speech`]); without it, a session ends at once
288    /// (`unavailable`) unless the core has a [`crate::speech::SpeechBackend`].
289    pub speech: bool,
290    /// The platform shows notifications ([`crate::Command::Notification`],
291    /// [`crate::notifications`]); without it, the permission is
292    /// `unavailable` and nothing shows.
293    pub notifications: bool,
294    /// The platform plays sound ([`crate::Command::Audio`],
295    /// [`crate::audio`]); without it, sounds and players fail at once
296    /// (`unavailable`) unless the core has a [`crate::audio::AudioBackend`].
297    pub audio: bool,
298    /// The size of one Cell of a grid surface (a terminal, whose content is
299    /// whole character Cells), in points; `None` on every other surface.
300    /// With it the core lays out with its terminal algorithm, ratatui's
301    /// splits in whole Cells (x the Cell's width, y its height): a border
302    /// is one Cell and every frame is whole Cells (`docs/dev/styles.md`
303    /// "Layout in a terminal").
304    pub cell: Option<Size<Points>>,
305    /// The platform gives web views trusted input
306    /// ([`crate::Command::SendInput`], macOS); without it, the command
307    /// does nothing.
308    pub web_input: bool,
309    /// The platform answers awaitable WebView evaluations
310    /// ([`crate::Command::Evaluate`]); false rejects as unavailable.
311    pub web_evaluate: bool,
312    /// The platform shows web views (TS: `WebView.available()`). `true` by
313    /// default; a platform that knows from the start that it shows none
314    /// (built without a web engine, the system's failed to load) sets
315    /// `false`, and every web view then reports `onError` with `code`
316    /// `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`. A web engine that fails only
317    /// when a web view starts reports that error itself.
318    pub web_views: bool,
319    /// The platform draws shader views (`Shader`, `ShaderEffect`,
320    /// `ShaderTransition`, the screen's; TS: `shadersAvailable()`). `true`
321    /// by default. A platform built without a renderer sets `false` from
322    /// the start; one that finds no GPU when the first shader mounts
323    /// reports it then (`nsh_engine::EngineControl::shaders_unavailable`),
324    /// so it can turn `false` while the app runs, never back. A grid
325    /// surface ([`Environment::cell`]) draws none.
326    pub shaders: bool,
327}
328
329impl Environment {
330    /// The platform's name (TS: `platform.name`): [`Environment::platform`]
331    /// on a platform built outside NSH (`"miniprogram"`), else the OS's
332    /// (`"ios"`, `"web"`, ...).
333    pub fn platform_name(&self) -> &'static str {
334        self.platform.unwrap_or(self.os.name())
335    }
336
337    /// Desktop behavior applies: a desktop OS, a browser in the desktop
338    /// idiom or a terminal ([`Idiom::desktop_on`]: `desktop={{…}}` props,
339    /// `platform.select({ desktop })`, `platform.desktop`, `platform.idiom`
340    /// `"desktop"` outside a terminal).
341    pub fn desktop(&self) -> bool {
342        self.idiom.desktop_on(self.os)
343    }
344
345    /// The idiom apps see (TS: `platform.idiom`, [`Idiom::reported_on`]).
346    pub fn reported_idiom(&self) -> Idiom {
347        self.idiom.reported_on(self.os)
348    }
349}
350
351impl Default for Environment {
352    fn default() -> Self {
353        Self {
354            window: Size::default(),
355            safe_area: Edges::default(),
356            title_bar: Edges::default(),
357            window_state: None,
358            keyboard_height: Points(0.0),
359            keyboard_duration: 250.0,
360            color_scheme: ColorScheme::Light,
361            font_scale: 1.0,
362            rtl: false,
363            reduce_motion: false,
364            pixel_ratio: 1.0,
365            screen_reader: false,
366            os: Os::default(),
367            platform: None,
368            os_version: (0, 0),
369            idiom: Idiom::Phone,
370            apple_keyboard: false,
371            ctrl_for_command: false,
372            locale: Locale::EN_US,
373            locale_settings: LocaleSettings::EN_US,
374            host: false,
375            lifecycle: Lifecycle::Active,
376            screen_color: false,
377            file_requests: false,
378            speech: false,
379            notifications: false,
380            audio: false,
381            cell: None,
382            web_input: false,
383            web_evaluate: false,
384            web_views: true,
385            shaders: true,
386        }
387    }
388}
389
390/// The settings an embedding app gives its surfaces in place of the
391/// system's (`None`: the system's): its own language and text size, for an
392/// app inside a native app that lets its users switch them. The platforms
393/// write them over what they read from the system ([`Self::apply`]), so the
394/// app's `Intl`, `locale()`, `localeSettings()`'s languages (its language first),
395/// `fontScale()` and text follow them like a system change.
396#[derive(Debug, Clone, Copy, PartialEq, Default)]
397pub struct HostEnvironment {
398    /// The locale in place of the user's ([`Environment::locale`]).
399    pub locale: Option<Locale>,
400    /// The text size in place of the user's ([`Environment::font_scale`]);
401    /// values that are not finite and positive count as `None`.
402    pub font_scale: Option<f32>,
403}
404
405impl HostEnvironment {
406    /// Writes the settings `self` has over `env`'s.
407    pub fn apply(&self, env: &mut Environment) {
408        if let Some(locale) = self.locale {
409            env.locale = locale;
410            env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
411        }
412        if let Some(scale) = self.font_scale.filter(|s| s.is_finite() && *s > 0.0) {
413            env.font_scale = scale;
414        }
415    }
416}
417
418/// A BCP 47 language tag (`en-US`, `zh-Hans-CN`), held inline so that the
419/// environment stays `Copy`: the language, script and region subtags fit;
420/// variants and extensions are dropped.
421#[derive(Clone, Copy, PartialEq, Eq, Hash)]
422pub struct Locale {
423    bytes: [u8; Locale::CAPACITY],
424    len: u8,
425}
426
427impl Locale {
428    const CAPACITY: usize = 15;
429
430    /// `en-US`, the default when a platform reports none.
431    pub const EN_US: Locale = Locale {
432        bytes: *b"en-US\0\0\0\0\0\0\0\0\0\0",
433        len: 5,
434    };
435
436    /// The tag of a platform locale identifier: `en_US`, `en-US`,
437    /// `de_DE@calendar=gregorian`, `pt_BR.UTF-8` (POSIX) and `zh-Hans_CN`
438    /// all work. Subtags are cased as BCP 47 writes them (`zh-Hans-CN`);
439    /// `None` without a language.
440    pub fn parse(identifier: &str) -> Option<Locale> {
441        let identifier = identifier.split(['@', '.']).next().unwrap_or_default();
442        let mut bytes = [0u8; Self::CAPACITY];
443        let mut len = 0;
444        for (i, part) in identifier.split(['-', '_']).enumerate() {
445            let keep = if i == 0 {
446                (2..=3).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphabetic())
447            } else {
448                // A script (4 letters) or a region (2 letters, 3 digits).
449                (part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()))
450                    || (part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()))
451                    || (part.len() == 3 && part.bytes().all(|b| b.is_ascii_digit()))
452            };
453            if !keep {
454                if i == 0 {
455                    return None;
456                }
457                // A variant or an extension: dropped with what follows.
458                break;
459            }
460            if len + part.len() + usize::from(i > 0) > Self::CAPACITY {
461                break;
462            }
463            if i > 0 {
464                bytes[len] = b'-';
465                len += 1;
466            }
467            for (j, b) in part.bytes().enumerate() {
468                bytes[len] = match (i, part.len()) {
469                    (0, _) => b.to_ascii_lowercase(),
470                    (_, 4) if j == 0 => b.to_ascii_uppercase(),
471                    (_, 4) => b.to_ascii_lowercase(),
472                    _ => b.to_ascii_uppercase(),
473                };
474                len += 1;
475            }
476        }
477        Some(Locale {
478            bytes,
479            len: len as u8,
480        })
481    }
482
483    /// The tag (`en-US`).
484    pub fn as_str(&self) -> &str {
485        // ASCII, as parsed.
486        std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
487    }
488
489    /// The language subtag (`en`).
490    pub fn language(&self) -> &str {
491        self.as_str().split('-').next().unwrap_or_default()
492    }
493
494    /// The region subtag (`US`, `419`), if the tag has one.
495    pub fn region(&self) -> Option<&str> {
496        // What follows the language is a script (4 letters) or a region.
497        self.as_str().split('-').skip(1).find(|s| s.len() != 4)
498    }
499}
500
501impl Default for Locale {
502    fn default() -> Self {
503        Self::EN_US
504    }
505}
506
507impl std::fmt::Debug for Locale {
508    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
509        write!(f, "Locale({})", self.as_str())
510    }
511}
512
513impl std::fmt::Display for Locale {
514    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515        f.write_str(self.as_str())
516    }
517}
518
519/// The user's preferred languages, most preferred first, as BCP 47 tags
520/// (`localeSettings()`'s `languages`): never empty, at most eight, each once. Held inline so
521/// that the environment stays `Copy`.
522#[derive(Clone, Copy, PartialEq, Eq, Hash)]
523pub struct Languages {
524    tags: [Locale; Languages::CAPACITY],
525    len: u8,
526}
527
528impl Languages {
529    /// How many it keeps: systems list a few (iOS and Android up to the
530    /// ones the user added, desktops their UI languages).
531    const CAPACITY: usize = 8;
532
533    /// `en-US` alone, the default when a platform reports none.
534    pub(crate) const EN_US: Languages = Languages {
535        tags: [Locale::EN_US; Languages::CAPACITY],
536        len: 1,
537    };
538
539    /// `locale` alone.
540    #[doc(hidden)]
541    pub const fn one(locale: Locale) -> Languages {
542        Languages {
543            tags: [locale; Languages::CAPACITY],
544            len: 1,
545        }
546    }
547
548    /// The languages of platform identifiers, most preferred first
549    /// ([`Locale::parse`]'s forms: `en_US`, `zh-Hans-CN`): ones that name
550    /// no language and repeats are left out, the first eight kept. `None`
551    /// when none is a language.
552    #[doc(hidden)]
553    pub fn parse<'a>(identifiers: impl IntoIterator<Item = &'a str>) -> Option<Languages> {
554        let mut languages = Languages::EN_US;
555        languages.len = 0;
556        for locale in identifiers.into_iter().filter_map(Locale::parse) {
557            if usize::from(languages.len) == Self::CAPACITY {
558                break;
559            }
560            if !languages.as_slice().contains(&locale) {
561                languages.tags[usize::from(languages.len)] = locale;
562                languages.len += 1;
563            }
564        }
565        (languages.len > 0).then_some(languages)
566    }
567
568    /// These with `locale` first (an embedding app's own language, the
569    /// app's `set_locale`): it moves there if it is listed, else comes
570    /// before them (the last one then left out when they are eight).
571    pub fn preferring(&self, locale: Locale) -> Languages {
572        let mut languages = Languages::one(locale);
573        for &other in self.as_slice() {
574            if usize::from(languages.len) == Self::CAPACITY {
575                break;
576            }
577            if other != locale {
578                languages.tags[usize::from(languages.len)] = other;
579                languages.len += 1;
580            }
581        }
582        languages
583    }
584
585    /// The most preferred.
586    pub fn first(&self) -> Locale {
587        self.tags[0]
588    }
589
590    /// All of them, most preferred first.
591    pub fn as_slice(&self) -> &[Locale] {
592        &self.tags[..usize::from(self.len)]
593    }
594
595    /// All of them, most preferred first.
596    pub fn iter(&self) -> impl Iterator<Item = Locale> + '_ {
597        self.as_slice().iter().copied()
598    }
599}
600
601impl Default for Languages {
602    fn default() -> Self {
603        Self::EN_US
604    }
605}
606
607impl std::fmt::Debug for Languages {
608    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
609        f.debug_list()
610            .entries(self.iter().map(|l| l.to_string()))
611            .finish()
612    }
613}
614
615/// A time zone's name as the system gives it: an IANA name
616/// (`Europe/Berlin`, `America/Argentina/Buenos_Aires`, `UTC`), or an offset
617/// zone where the system has one (Android's `GMT+01:00`). Held inline so
618/// that the environment stays `Copy`.
619#[derive(Clone, Copy, PartialEq, Eq, Hash)]
620#[non_exhaustive]
621pub struct TimeZone {
622    bytes: [u8; TimeZone::CAPACITY],
623    len: u8,
624}
625
626impl TimeZone {
627    /// Room for any name the tz database's rules allow: parts of at most 14
628    /// characters, four of them with their slashes in 59 bytes (its longest
629    /// name, `America/Argentina/ComodRivadavia`, has three in 32), and for
630    /// the systems' offset zones (`GMT+05:30`). 64 bytes with the length.
631    const CAPACITY: usize = 63;
632
633    /// `UTC`, the default when a platform reports none (and headless).
634    pub const UTC: TimeZone = {
635        let mut bytes = [0u8; TimeZone::CAPACITY];
636        bytes[0] = b'U';
637        bytes[1] = b'T';
638        bytes[2] = b'C';
639        TimeZone { bytes, len: 3 }
640    };
641
642    /// The zone of a platform identifier: an IANA name (`Europe/Berlin`),
643    /// with POSIX `TZ`'s leading `:` (`:Europe/Berlin`), or as a path into
644    /// a zone database (`/usr/share/zoneinfo/Europe/Berlin`,
645    /// `/var/db/timezone/zoneinfo/Europe/Berlin`). `None` for what names no
646    /// zone: empty, longer than any zone's name, or with characters zone
647    /// names do not have.
648    pub fn parse(identifier: &str) -> Option<TimeZone> {
649        let identifier = identifier.trim();
650        let name = match identifier.rsplit_once("zoneinfo/") {
651            Some((_, name)) => name,
652            None => identifier.strip_prefix(':').unwrap_or(identifier),
653        };
654        let valid = !name.is_empty()
655            && name.len() <= Self::CAPACITY
656            && name
657                .bytes()
658                .all(|b| b.is_ascii_alphanumeric() || b"/_-+:".contains(&b))
659            && name
660                .split('/')
661                .all(|part| !part.is_empty() && part != "." && part != "..");
662        if !valid {
663            return None;
664        }
665        let mut bytes = [0u8; Self::CAPACITY];
666        bytes[..name.len()].copy_from_slice(name.as_bytes());
667        Some(TimeZone {
668            bytes,
669            len: name.len() as u8,
670        })
671    }
672
673    /// The zone a process's local times follow on a POSIX system (Linux,
674    /// macOS, the BSDs): the one its `TZ` variable (`tz`, `None` when
675    /// unset) names, as the C library reads it, else the system's
676    /// (`system`, asked only then), else UTC.
677    ///
678    /// `TZ` names a zone of the tz database by its name, with a slash or
679    /// without (`Europe/Berlin`, `Etc/GMT+5`, `GMT`, `EST`) and with or
680    /// without its leading `:`, or by a path into the database
681    /// (`/usr/share/zoneinfo/Asia/Tokyo`); empty, it is UTC. A POSIX rule
682    /// (`JST-9`, `<+08>-8`, `CET-1CEST,M3.5.0,M10.5.0/3`) names no zone,
683    /// nor does a path elsewhere (`:/etc/localtime`, the system's): the
684    /// system's zone is reported for them. The database's few names that
685    /// read as rules too (`EST5EDT`, `GMT0`) are its zones, which mean the
686    /// same.
687    #[doc(hidden)]
688    pub fn posix(tz: Option<&str>, system: impl FnOnce() -> Option<TimeZone>) -> TimeZone {
689        let zone = match tz.map(str::trim) {
690            None => None,
691            // glibc and tzcode alike take an empty `TZ` for UTC.
692            Some("") => Some(Self::UTC),
693            Some(tz) => {
694                let name = tz.strip_prefix(':').unwrap_or(tz);
695                if is_posix_rule(name) && !RULE_NAMED_ZONES.contains(&name) {
696                    None
697                } else {
698                    Self::parse(name)
699                }
700            }
701        };
702        zone.or_else(system).unwrap_or_default()
703    }
704
705    /// The name (`Europe/Berlin`).
706    pub fn as_str(&self) -> &str {
707        // ASCII, as parsed.
708        std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("UTC")
709    }
710}
711
712/// The tz database's names that read as POSIX rules too (`EST5EDT` is
713/// Eastern time with US rules, `GMT0` UTC under either reading): the C
714/// library loads their zones' files.
715const RULE_NAMED_ZONES: [&str; 7] = [
716    "EST5EDT", "CST6CDT", "MST7MDT", "PST8PDT", "GMT0", "GMT+0", "GMT-0",
717];
718
719/// Whether `TZ`'s value `tz` is a POSIX rule: a zone abbreviation, quoted
720/// (`<+08>`) or of three letters or more (`JST`), then its offset from UTC
721/// (`-9`, `5`, `+5:30`). No zone's name but [`RULE_NAMED_ZONES`] has that
722/// shape: the database's other names without a slash have no offset
723/// (`GMT`, `Japan`) or a shorter word before it (`NZ-CHAT`).
724fn is_posix_rule(tz: &str) -> bool {
725    let letters = tz.bytes().take_while(u8::is_ascii_alphabetic).count();
726    tz.starts_with('<')
727        || letters >= 3
728            && tz
729                .as_bytes()
730                .get(letters)
731                .is_some_and(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-'))
732}
733
734impl Default for TimeZone {
735    fn default() -> Self {
736        Self::UTC
737    }
738}
739
740impl std::fmt::Debug for TimeZone {
741    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
742        write!(f, "TimeZone({})", self.as_str())
743    }
744}
745
746impl std::fmt::Display for TimeZone {
747    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
748        f.write_str(self.as_str())
749    }
750}
751
752/// The user's locale settings beside the locale (`locale_settings()`; TS
753/// `localeSettings()`): the preferred languages, the time zone and the
754/// regional preferences the systems keep beside the language (Language &
755/// Region on Apple platforms, Android's regional preferences, Windows'
756/// region settings). They change together, as the user changes the
757/// system's settings or travels. Where the user set no regional preference,
758/// it is the region's. The names are `Intl`'s and Foundation's, so they
759/// pass into `Intl`'s options as they are.
760#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
761#[non_exhaustive]
762pub struct LocaleSettings {
763    /// The preferred languages, most preferred first (the system's list:
764    /// the language apps show their text in, then its fallbacks).
765    pub languages: Languages,
766    /// The device's time zone, as the system names it (`Europe/Berlin`).
767    pub time_zone: TimeZone,
768    /// 12- or 24-hour time.
769    pub hour_cycle: HourCycle,
770    /// The day weeks start on: a calendar's first column.
771    pub first_day_of_week: Weekday,
772    /// The units of lengths, weights and volumes.
773    pub measurement_system: MeasurementSystem,
774    /// The unit of temperatures.
775    pub temperature_unit: TemperatureUnit,
776}
777
778impl LocaleSettings {
779    /// `en-US`'s (`en-US` alone, 12-hour time, weeks from Sunday, US units,
780    /// Fahrenheit) in UTC, the default when a platform reports none.
781    pub(crate) const EN_US: LocaleSettings = LocaleSettings {
782        languages: Languages::EN_US,
783        time_zone: TimeZone::UTC,
784        hour_cycle: HourCycle::H12,
785        first_day_of_week: Weekday::Sunday,
786        measurement_system: MeasurementSystem::Us,
787        temperature_unit: TemperatureUnit::Fahrenheit,
788    };
789
790    /// `locale`'s: it alone as the languages, UTC, and its region's
791    /// preferences as CLDR (48) gives them. A locale without a region has
792    /// the world's: 24-hour time, weeks from Monday, metric units and
793    /// Celsius.
794    #[doc(hidden)]
795    pub fn of(locale: Locale) -> LocaleSettings {
796        LocaleSettings {
797            languages: Languages::one(locale),
798            ..Self::of_region(locale.language(), locale.region().unwrap_or("001"))
799        }
800    }
801
802    /// The settings a platform locale identifier names: its locale alone
803    /// as the languages (`en-US` where it names none), UTC, and its
804    /// region's preferences ([`Self::of`]; the `rg` keyword's region in
805    /// place of its own), with what its Unicode extension keywords set:
806    /// `hc` (the hour cycle), `fw` (the first day of the week), `ms` (the
807    /// measurement system) and `mu` (the temperature unit), written as BCP
808    /// 47 does (`en-US-u-fw-mon-mu-celsius`, Android's regional
809    /// preferences) or as ICU does (`en_US@hours=h23;fw=mon;rg=gbzzzz`).
810    /// Values it does not know are left out.
811    #[doc(hidden)]
812    pub fn parse(identifier: &str) -> LocaleSettings {
813        let identifier = identifier.trim();
814        let (tag, icu) = identifier.split_once('@').unwrap_or((identifier, ""));
815        let mut keywords = Keywords::default();
816        // BCP 47's `-u-` extension: keys of two characters, each followed
817        // by its value.
818        let mut extension = false;
819        let mut key = "";
820        for subtag in tag.split('.').next().unwrap_or_default().split(['-', '_']) {
821            if subtag.len() == 1 {
822                extension = subtag.eq_ignore_ascii_case("u");
823                key = "";
824            } else if extension && subtag.len() == 2 {
825                key = subtag;
826            } else if extension && !key.is_empty() {
827                keywords.set(key, subtag);
828                key = "";
829            }
830        }
831        for keyword in icu.split(';') {
832            if let Some((key, value)) = keyword.split_once('=') {
833                keywords.set(key.trim(), value.trim());
834            }
835        }
836        let locale = Locale::parse(identifier);
837        let language = locale.as_ref().map_or("", Locale::language);
838        let region = match &keywords.region {
839            Some((bytes, len)) => std::str::from_utf8(&bytes[..*len]).unwrap_or("001"),
840            None => locale.as_ref().and_then(Locale::region).unwrap_or("001"),
841        };
842        let own = Self::of_region(language, region);
843        LocaleSettings {
844            languages: Languages::one(locale.unwrap_or(Locale::EN_US)),
845            hour_cycle: keywords.hour_cycle.unwrap_or(own.hour_cycle),
846            first_day_of_week: keywords.first_day_of_week.unwrap_or(own.first_day_of_week),
847            measurement_system: keywords
848                .measurement_system
849                .unwrap_or(own.measurement_system),
850            temperature_unit: keywords.temperature_unit.unwrap_or(own.temperature_unit),
851            ..own
852        }
853    }
854
855    /// CLDR's preferences of `region` (`001`: the world's), for `language`.
856    fn of_region(language: &str, region: &str) -> LocaleSettings {
857        let listed = |regions: &[&str]| regions.binary_search(&region).is_ok();
858        LocaleSettings {
859            hour_cycle: match (language, region) {
860                // Where a language's differs from its region's.
861                ("fr", "CA") | ("ku", "SY") => HourCycle::H23,
862                ("ar" | "en", "001") => HourCycle::H12,
863                _ if listed(HOUR12_REGIONS) => HourCycle::H12,
864                _ => HourCycle::H23,
865            },
866            first_day_of_week: if listed(SUNDAY_REGIONS) {
867                Weekday::Sunday
868            } else if listed(SATURDAY_REGIONS) {
869                Weekday::Saturday
870            } else if listed(FRIDAY_REGIONS) {
871                Weekday::Friday
872            } else {
873                Weekday::Monday
874            },
875            measurement_system: match region {
876                "LR" | "US" => MeasurementSystem::Us,
877                "GB" | "MM" => MeasurementSystem::Uk,
878                _ => MeasurementSystem::Metric,
879            },
880            temperature_unit: match region {
881                "BS" | "BZ" | "KY" | "PR" | "PW" | "US" => TemperatureUnit::Fahrenheit,
882                _ => TemperatureUnit::Celsius,
883            },
884            ..Self::default()
885        }
886    }
887}
888
889impl Default for LocaleSettings {
890    fn default() -> Self {
891        Self::EN_US
892    }
893}
894
895/// What a locale identifier's extension keywords set.
896#[derive(Default)]
897struct Keywords {
898    hour_cycle: Option<HourCycle>,
899    first_day_of_week: Option<Weekday>,
900    measurement_system: Option<MeasurementSystem>,
901    temperature_unit: Option<TemperatureUnit>,
902    /// `rg`'s region, upper-cased, and its length.
903    region: Option<([u8; 3], usize)>,
904}
905
906impl Keywords {
907    /// Reads `key`'s `value` (BCP 47's key or ICU's name for it).
908    fn set(&mut self, key: &str, value: &str) {
909        let is = |names: &[&str]| names.iter().any(|n| key.eq_ignore_ascii_case(n));
910        let value_is = |name: &str| value.eq_ignore_ascii_case(name);
911        if is(&["hc", "hours"]) {
912            self.hour_cycle = HourCycle::parse(value).or(self.hour_cycle);
913        } else if is(&["fw"]) {
914            self.first_day_of_week = Weekday::ALL
915                .into_iter()
916                .find(|d| value_is(d.code()))
917                .or(self.first_day_of_week);
918        } else if is(&["ms", "measure"]) {
919            self.measurement_system = match () {
920                _ if value_is("metric") => Some(MeasurementSystem::Metric),
921                _ if value_is("ussystem") => Some(MeasurementSystem::Us),
922                _ if value_is("uksystem") => Some(MeasurementSystem::Uk),
923                _ => self.measurement_system,
924            };
925        } else if is(&["mu"]) {
926            // BCP 47 values have at most 8 characters: `fahrenhe`.
927            let unit = match value_is("fahrenhe") {
928                true => Some(TemperatureUnit::Fahrenheit),
929                false => TemperatureUnit::parse(value),
930            };
931            self.temperature_unit = unit.or(self.temperature_unit);
932        } else if is(&["rg"]) {
933            // A subdivision: the region (`gb`, `419`), then `zzzz` for all
934            // of it.
935            let bytes = value.as_bytes();
936            let len = match bytes {
937                [a, b, c, ..] if [a, b, c].iter().all(|b| b.is_ascii_digit()) => 3,
938                [a, b, ..] if a.is_ascii_alphabetic() && b.is_ascii_alphabetic() => 2,
939                _ => return,
940            };
941            let mut region = [0u8; 3];
942            for (to, from) in region.iter_mut().zip(bytes) {
943                *to = from.to_ascii_uppercase();
944            }
945            self.region = Some((region, len));
946        }
947    }
948}
949
950/// The regions whose times are 12-hour (`timeData`'s preferred `h`).
951const HOUR12_REGIONS: &[&str] = &[
952    "419", "AE", "AG", "AL", "AR", "AS", "AU", "BB", "BD", "BH", "BM", "BN", "BO", "BS", "BT",
953    "CA", "CL", "CO", "CR", "CU", "CY", "DJ", "DM", "DO", "DZ", "EC", "EG", "EH", "ER", "ET", "FJ",
954    "FM", "GD", "GH", "GM", "GR", "GT", "GU", "GY", "HK", "HN", "IN", "IQ", "JM", "JO", "KH", "KI",
955    "KN", "KP", "KR", "KW", "KY", "LB", "LC", "LR", "LS", "LY", "MH", "MO", "MP", "MR", "MW", "MX",
956    "MY", "NA", "NI", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PR", "PS", "PW", "PY", "QA", "SA",
957    "SB", "SD", "SG", "SL", "SO", "SS", "SV", "SY", "SZ", "TC", "TD", "TN", "TO", "TT", "TW", "UM",
958    "US", "UY", "VC", "VE", "VG", "VI", "VU", "WS", "YE", "ZM",
959];
960
961/// The regions whose weeks start on Sunday (`weekData`'s `firstDay`).
962const SUNDAY_REGIONS: &[&str] = &[
963    "AG", "AS", "BD", "BR", "BS", "BT", "BW", "BZ", "CA", "CO", "DM", "DO", "ET", "GT", "GU", "HK",
964    "HN", "ID", "IL", "IN", "IS", "JM", "JP", "KE", "KH", "KR", "LA", "MH", "MM", "MO", "MT", "MX",
965    "MZ", "NI", "NP", "PA", "PE", "PH", "PK", "PR", "PT", "PY", "SA", "SG", "SV", "TH", "TT", "TW",
966    "UM", "US", "VE", "VI", "WS", "YE", "ZA", "ZW",
967];
968
969/// The regions whose weeks start on Saturday.
970const SATURDAY_REGIONS: &[&str] = &[
971    "AF", "BH", "DJ", "DZ", "EG", "IQ", "IR", "JO", "KW", "LY", "OM", "QA", "SD", "SY",
972];
973
974/// The regions whose weeks start on Friday.
975const FRIDAY_REGIONS: &[&str] = &["MV"];
976
977/// How hours are counted, as `Intl`'s `hourCycle` names it.
978#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
979pub enum HourCycle {
980    /// 12-hour time from 0 to 11 (`h11`: `0:30 PM`).
981    H11,
982    /// 12-hour time from 1 to 12 (`h12`: `12:30 PM`).
983    #[default]
984    H12,
985    /// 24-hour time from 0 to 23 (`h23`: `00:30`).
986    H23,
987    /// 24-hour time from 1 to 24 (`h24`: `24:30`).
988    H24,
989}
990
991impl HourCycle {
992    /// Its `Intl` name: `"h11"`, `"h12"`, `"h23"` or `"h24"`.
993    pub fn name(self) -> &'static str {
994        match self {
995            HourCycle::H11 => "h11",
996            HourCycle::H12 => "h12",
997            HourCycle::H23 => "h23",
998            HourCycle::H24 => "h24",
999        }
1000    }
1001
1002    /// The cycle `Intl` names `name` (`"h23"`, in any case).
1003    pub fn parse(name: &str) -> Option<HourCycle> {
1004        [
1005            HourCycle::H11,
1006            HourCycle::H12,
1007            HourCycle::H23,
1008            HourCycle::H24,
1009        ]
1010        .into_iter()
1011        .find(|c| name.eq_ignore_ascii_case(c.name()))
1012    }
1013
1014    /// The cycle of a date pattern's hour field, in the letters of
1015    /// Unicode's patterns (Apple's and ICU's date formats, Windows' time
1016    /// formats): `h` (`h:mm a` is `h12`), `H` (`HH:mm` is `h23`), `K` and
1017    /// `k`. Quoted text (`HH 'Uhr'`) is not read; `None` without an hour.
1018    #[doc(hidden)]
1019    pub fn of_pattern(pattern: &str) -> Option<HourCycle> {
1020        let mut quoted = false;
1021        pattern.chars().find_map(|c| match c {
1022            '\'' => {
1023                quoted = !quoted;
1024                None
1025            }
1026            _ if quoted => None,
1027            'h' => Some(HourCycle::H12),
1028            'H' => Some(HourCycle::H23),
1029            'K' => Some(HourCycle::H11),
1030            'k' => Some(HourCycle::H24),
1031            _ => None,
1032        })
1033    }
1034
1035    /// 12-hour time: times have AM and PM.
1036    pub fn twelve_hour(self) -> bool {
1037        matches!(self, HourCycle::H11 | HourCycle::H12)
1038    }
1039}
1040
1041/// A day of the week.
1042#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1043pub enum Weekday {
1044    /// Monday (1).
1045    Monday = 1,
1046    /// Tuesday (2).
1047    Tuesday,
1048    /// Wednesday (3).
1049    Wednesday,
1050    /// Thursday (4).
1051    Thursday,
1052    /// Friday (5).
1053    Friday,
1054    /// Saturday (6).
1055    Saturday,
1056    /// Sunday (7).
1057    Sunday,
1058}
1059
1060impl Weekday {
1061    /// The days, from Monday.
1062    const ALL: [Weekday; 7] = [
1063        Weekday::Monday,
1064        Weekday::Tuesday,
1065        Weekday::Wednesday,
1066        Weekday::Thursday,
1067        Weekday::Friday,
1068        Weekday::Saturday,
1069        Weekday::Sunday,
1070    ];
1071
1072    /// Its ISO 8601 number, TS's: 1 for Monday to 7 for Sunday (as
1073    /// `Intl.Locale`'s `firstDay` and Temporal's `dayOfWeek` count).
1074    pub fn number(self) -> u8 {
1075        self as u8
1076    }
1077
1078    /// The day of an ISO 8601 number (1 for Monday to 7 for Sunday).
1079    pub fn from_number(number: u8) -> Option<Weekday> {
1080        Self::ALL.get(usize::from(number).checked_sub(1)?).copied()
1081    }
1082
1083    /// Unicode's code for it (`mon`), as the `fw` keyword writes it.
1084    fn code(self) -> &'static str {
1085        match self {
1086            Weekday::Monday => "mon",
1087            Weekday::Tuesday => "tue",
1088            Weekday::Wednesday => "wed",
1089            Weekday::Thursday => "thu",
1090            Weekday::Friday => "fri",
1091            Weekday::Saturday => "sat",
1092            Weekday::Sunday => "sun",
1093        }
1094    }
1095}
1096
1097/// The units of lengths, weights and volumes.
1098#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1099pub enum MeasurementSystem {
1100    /// Metres, kilograms and litres (`metric`).
1101    #[default]
1102    Metric,
1103    /// The US customary units: feet, miles, pounds and gallons (`us`).
1104    Us,
1105    /// The UK's: metric, with miles for distances and pints (`uk`).
1106    Uk,
1107}
1108
1109impl MeasurementSystem {
1110    /// Its TS name: `"metric"`, `"us"` or `"uk"`.
1111    pub fn name(self) -> &'static str {
1112        match self {
1113            MeasurementSystem::Metric => "metric",
1114            MeasurementSystem::Us => "us",
1115            MeasurementSystem::Uk => "uk",
1116        }
1117    }
1118
1119    /// The system TS names `name` (`"metric"`, in any case).
1120    pub fn parse(name: &str) -> Option<MeasurementSystem> {
1121        [
1122            MeasurementSystem::Metric,
1123            MeasurementSystem::Us,
1124            MeasurementSystem::Uk,
1125        ]
1126        .into_iter()
1127        .find(|s| name.eq_ignore_ascii_case(s.name()))
1128    }
1129}
1130
1131/// The unit of temperatures.
1132#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1133pub enum TemperatureUnit {
1134    /// Degrees Celsius (`celsius`).
1135    #[default]
1136    Celsius,
1137    /// Degrees Fahrenheit (`fahrenheit`).
1138    Fahrenheit,
1139}
1140
1141impl TemperatureUnit {
1142    /// Its TS name: `"celsius"` or `"fahrenheit"`.
1143    pub fn name(self) -> &'static str {
1144        match self {
1145            TemperatureUnit::Celsius => "celsius",
1146            TemperatureUnit::Fahrenheit => "fahrenheit",
1147        }
1148    }
1149
1150    /// The unit TS names `name` (`"celsius"`, in any case).
1151    pub fn parse(name: &str) -> Option<TemperatureUnit> {
1152        [TemperatureUnit::Celsius, TemperatureUnit::Fahrenheit]
1153            .into_iter()
1154            .find(|u| name.eq_ignore_ascii_case(u.name()))
1155    }
1156}
1157
1158/// An HTTP request for the platform's network stack (made by JS `fetch`
1159/// and by Rust components' [`crate::element::fetch`]).
1160#[derive(Debug, Clone, PartialEq, Eq)]
1161pub struct HttpRequest {
1162    /// Upper-case method (`GET`, `POST`, ...).
1163    pub method: String,
1164    /// Absolute URL.
1165    pub url: String,
1166    /// Header names and values, in order; names may repeat.
1167    pub headers: Vec<(String, String)>,
1168    /// Request body.
1169    pub body: HttpBody,
1170    /// Follow redirects (`redirect: "follow"`, the default).
1171    pub follow_redirects: bool,
1172}
1173
1174impl HttpRequest {
1175    /// A request of `method` (`GET`, `POST`, ...; upper-cased) to `url`,
1176    /// with no headers or body, following redirects.
1177    pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
1178        Self {
1179            method: method.into().to_ascii_uppercase(),
1180            url: url.into(),
1181            headers: Vec::new(),
1182            body: HttpBody::Empty,
1183            follow_redirects: true,
1184        }
1185    }
1186
1187    /// A `GET` of `url`.
1188    pub fn get(url: impl Into<String>) -> Self {
1189        Self::new("GET", url)
1190    }
1191
1192    /// A `POST` of `body` to `url`.
1193    pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
1194        Self::new("POST", url).body(body)
1195    }
1196
1197    /// Adds the header `name: value`.
1198    #[must_use]
1199    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1200        self.headers.push((name.into(), value.into()));
1201        self
1202    }
1203
1204    /// Sends `body`.
1205    #[must_use]
1206    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
1207        self.body = HttpBody::Bytes(body.into());
1208        self
1209    }
1210}
1211
1212impl From<&str> for HttpRequest {
1213    fn from(url: &str) -> Self {
1214        Self::get(url)
1215    }
1216}
1217
1218impl From<String> for HttpRequest {
1219    fn from(url: String) -> Self {
1220        Self::get(url)
1221    }
1222}
1223
1224/// The body of an [`HttpRequest`].
1225#[derive(Debug, Clone, PartialEq, Eq, Default)]
1226pub enum HttpBody {
1227    /// No body.
1228    #[default]
1229    Empty,
1230    /// All of it, known up front.
1231    Bytes(Vec<u8>),
1232    /// Produced while the request is sent (a `ReadableStream`), in chunks
1233    /// the stack asks for one at a time ([`FetchEvent::BodyWanted`]); sent
1234    /// with chunked transfer encoding.
1235    Stream,
1236}
1237
1238impl HttpBody {
1239    /// No body at all.
1240    pub fn is_empty(&self) -> bool {
1241        match self {
1242            HttpBody::Empty => true,
1243            HttpBody::Bytes(b) => b.is_empty(),
1244            HttpBody::Stream => false,
1245        }
1246    }
1247}
1248
1249/// The status line and headers of a response, before its body.
1250#[derive(Debug, Clone, PartialEq, Eq, Default)]
1251pub struct HttpHead {
1252    /// Status code.
1253    pub status: u16,
1254    /// Reason phrase, if the stack reports one.
1255    pub status_text: String,
1256    /// Final URL, after redirects.
1257    pub url: String,
1258    /// True if a redirect was followed.
1259    pub redirected: bool,
1260    /// Header names and values.
1261    pub headers: Vec<(String, String)>,
1262}
1263
1264/// The media type of the file at `path` (a path or an `asset:/` URL), by
1265/// its extension: what the dev server serves files with and what the
1266/// engine answers requests of the app's files with, so a file has one type
1267/// however it arrives. Browsers need it to load scripts, WebAssembly
1268/// (compiled while it streams only as `application/wasm`), images, fonts
1269/// and media.
1270#[doc(hidden)]
1271pub fn content_type(path: &str) -> &'static str {
1272    match std::path::Path::new(path)
1273        .extension()
1274        .and_then(|e| e.to_str())
1275        .map(str::to_ascii_lowercase)
1276        .as_deref()
1277    {
1278        Some("html") => "text/html; charset=utf-8",
1279        Some("js" | "mjs") => "text/javascript; charset=utf-8",
1280        Some("json" | "map") => "application/json",
1281        Some("webmanifest") => "application/manifest+json",
1282        Some("wasm") => "application/wasm",
1283        Some("css") => "text/css; charset=utf-8",
1284        Some("txt") => "text/plain; charset=utf-8",
1285        Some("png") => "image/png",
1286        Some("jpg" | "jpeg") => "image/jpeg",
1287        Some("gif") => "image/gif",
1288        Some("webp") => "image/webp",
1289        Some("avif") => "image/avif",
1290        Some("svg") => "image/svg+xml",
1291        Some("ico") => "image/x-icon",
1292        Some("heic") => "image/heic",
1293        Some("ttf") => "font/ttf",
1294        Some("otf") => "font/otf",
1295        Some("woff") => "font/woff",
1296        Some("woff2") => "font/woff2",
1297        Some("mp4" | "m4v") => "video/mp4",
1298        Some("webm") => "video/webm",
1299        Some("mov") => "video/quicktime",
1300        Some("mp3") => "audio/mpeg",
1301        Some("m4a") => "audio/mp4",
1302        Some("aac") => "audio/aac",
1303        Some("wav") => "audio/wav",
1304        Some("ogg" | "oga" | "opus") => "audio/ogg",
1305        Some("flac") => "audio/flac",
1306        Some("aif" | "aiff") => "audio/aiff",
1307        Some("caf") => "audio/x-caf",
1308        _ => "application/octet-stream",
1309    }
1310}
1311
1312/// The MIME type of a local file by its name's extension, `""` when the
1313/// name says none (a directory, no extension, one this table lacks), as the
1314/// DOM's `File.type`. File drags and drops report it beside each URL
1315/// (`FileDragEvent::mime_types`): it reads the name only, never the file,
1316/// so it costs nothing while a drag hovers and is the same on every
1317/// platform. `uri` is a `file:` URL or a path.
1318#[doc(hidden)]
1319pub fn file_mime_type(uri: &str) -> &'static str {
1320    let path = uri.split(['?', '#']).next().unwrap_or_default();
1321    let name = path.rsplit('/').next().unwrap_or_default();
1322    let Some((stem, ext)) = name.rsplit_once('.') else {
1323        return "";
1324    };
1325    if stem.is_empty() {
1326        // A dotfile (`.env`): a name, not an extension.
1327        return "";
1328    }
1329    match ext.to_ascii_lowercase().as_str() {
1330        "png" => "image/png",
1331        "jpg" | "jpeg" | "jpe" => "image/jpeg",
1332        "gif" => "image/gif",
1333        "webp" => "image/webp",
1334        "avif" => "image/avif",
1335        "heic" => "image/heic",
1336        "heif" => "image/heif",
1337        "svg" => "image/svg+xml",
1338        "bmp" => "image/bmp",
1339        "tif" | "tiff" => "image/tiff",
1340        "ico" => "image/x-icon",
1341        "mp4" | "m4v" => "video/mp4",
1342        "mov" => "video/quicktime",
1343        "webm" => "video/webm",
1344        "mkv" => "video/x-matroska",
1345        "avi" => "video/x-msvideo",
1346        "mp3" => "audio/mpeg",
1347        "m4a" => "audio/mp4",
1348        "aac" => "audio/aac",
1349        "wav" => "audio/wav",
1350        "ogg" | "oga" | "opus" => "audio/ogg",
1351        "flac" => "audio/flac",
1352        "aif" | "aiff" => "audio/aiff",
1353        "caf" => "audio/x-caf",
1354        "txt" | "text" | "log" => "text/plain",
1355        "md" | "markdown" => "text/markdown",
1356        "csv" => "text/csv",
1357        "tsv" => "text/tab-separated-values",
1358        "html" | "htm" => "text/html",
1359        "css" => "text/css",
1360        "js" | "mjs" => "text/javascript",
1361        "json" => "application/json",
1362        "xml" => "application/xml",
1363        "yaml" | "yml" => "application/yaml",
1364        "pdf" => "application/pdf",
1365        "rtf" => "application/rtf",
1366        "doc" => "application/msword",
1367        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1368        "xls" => "application/vnd.ms-excel",
1369        "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1370        "ppt" => "application/vnd.ms-powerpoint",
1371        "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1372        "zip" => "application/zip",
1373        "gz" | "tgz" => "application/gzip",
1374        "tar" => "application/x-tar",
1375        "7z" => "application/x-7z-compressed",
1376        "rar" => "application/vnd.rar",
1377        "wasm" => "application/wasm",
1378        "ttf" => "font/ttf",
1379        "otf" => "font/otf",
1380        "woff" => "font/woff",
1381        "woff2" => "font/woff2",
1382        _ => "",
1383    }
1384}
1385
1386/// What happens to a request, in order: (for a streamed body) any number
1387/// of `BodyWanted`; then `Head`, `Data`… and `End` — or `Failed` at any
1388/// point.
1389#[derive(Debug, Clone, PartialEq, Eq)]
1390pub enum FetchEvent {
1391    /// A streamed body's next chunk is wanted: first when the stack is
1392    /// ready to send, then each time the last chunk was handed on.
1393    BodyWanted,
1394    /// The response's status and headers arrived.
1395    Head(HttpHead),
1396    /// Bytes of the response body, in order.
1397    Data(Vec<u8>),
1398    /// The body is complete.
1399    End,
1400    /// The request failed (no response, or the body broke off).
1401    Failed(String),
1402}
1403
1404/// What JS asks of a request it made (the JS host queues these for the
1405/// engine, which hands them to the stack).
1406#[derive(Debug, Clone, PartialEq, Eq)]
1407pub enum FetchOp {
1408    /// Make the request.
1409    Start(HttpRequest),
1410    /// The next chunk of a streamed body (after [`FetchEvent::BodyWanted`]).
1411    Send(Vec<u8>),
1412    /// A streamed body is complete.
1413    Finish,
1414    /// Stop (`true`) or go on (`false`) reading the response body: nobody
1415    /// reads what arrived.
1416    Pause(bool),
1417    /// Abort the request (`AbortController`, or the body was cancelled).
1418    Cancel,
1419}
1420
1421#[cfg(test)]
1422mod tests {
1423    use super::{
1424        Environment, HostEnvironment, HourCycle, Idiom, Languages, Locale, LocaleSettings,
1425        MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday, content_type, file_mime_type,
1426    };
1427
1428    #[test]
1429    fn desktop_is_a_desktop_os_or_a_desktop_browser() {
1430        let desktop = |os: Os, idiom: Idiom| Environment {
1431            os,
1432            idiom,
1433            ..Environment::default()
1434        };
1435        for (os, idiom, expected) in [
1436            (Os::MacOs, Idiom::Desktop, true),
1437            (Os::Windows, Idiom::Desktop, true),
1438            (Os::Linux, Idiom::Desktop, true),
1439            // A desktop OS is desktop whatever idiom it was given.
1440            (Os::Linux, Idiom::Phone, true),
1441            (Os::Web, Idiom::Desktop, true),
1442            (Os::Web, Idiom::Pad, false),
1443            (Os::Web, Idiom::Phone, false),
1444            (Os::Ios, Idiom::Phone, false),
1445            (Os::Ios, Idiom::Pad, false),
1446            // Mac Catalyst: the iOS backend, mobile in either idiom.
1447            (Os::Ios, Idiom::Mac, false),
1448            (Os::Ios, Idiom::Desktop, false),
1449            (Os::Android, Idiom::Tv, false),
1450        ] {
1451            let env = desktop(os, idiom);
1452            assert_eq!(env.desktop(), expected, "{os:?} {idiom:?}");
1453            // `platform.idiom` is "desktop" exactly where desktop applies.
1454            assert_eq!(
1455                env.reported_idiom() == Idiom::Desktop,
1456                expected,
1457                "{os:?} {idiom:?}"
1458            );
1459        }
1460        assert_eq!(desktop(Os::Ios, Idiom::Mac).reported_idiom(), Idiom::Mac);
1461        assert_eq!(
1462            desktop(Os::Ios, Idiom::Desktop).reported_idiom(),
1463            Idiom::Phone
1464        );
1465        assert!(!Os::MacOs.is_catalyst() && !Os::Web.is_catalyst());
1466        assert_eq!(Os::Ios.is_catalyst(), cfg!(target_abi = "macabi"));
1467    }
1468
1469    #[test]
1470    fn desktop_behavior_applies_in_the_terminal_idiom_on_any_os() {
1471        for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Web] {
1472            assert!(Idiom::Terminal.desktop_on(os), "{os:?}");
1473            assert_eq!(Idiom::Terminal.reported_on(os), Idiom::Terminal, "{os:?}");
1474        }
1475    }
1476
1477    #[test]
1478    fn a_host_environment_replaces_what_it_sets() {
1479        let mut env = Environment {
1480            font_scale: 1.25,
1481            ..Environment::default()
1482        };
1483        HostEnvironment::default().apply(&mut env);
1484        assert_eq!((env.locale, env.font_scale), (Locale::EN_US, 1.25));
1485        let zh = Locale::parse("zh-Hans-CN").unwrap();
1486        HostEnvironment {
1487            locale: Some(zh),
1488            font_scale: Some(f32::NAN),
1489        }
1490        .apply(&mut env);
1491        assert_eq!((env.locale, env.font_scale), (zh, 1.25));
1492        HostEnvironment {
1493            locale: None,
1494            font_scale: Some(1.5),
1495        }
1496        .apply(&mut env);
1497        assert_eq!((env.locale, env.font_scale), (zh, 1.5));
1498    }
1499
1500    #[test]
1501    fn languages_parse_platform_identifiers_and_an_embedding_app_goes_first() {
1502        let tags = |l: Languages| l.iter().map(|l| l.to_string()).collect::<Vec<_>>();
1503        let system = Languages::parse(["de_DE", "C", "en-US", "de-DE", "fr"]).unwrap();
1504        assert_eq!(tags(system), ["de-DE", "en-US", "fr"]);
1505        assert_eq!(system.first().as_str(), "de-DE");
1506        assert_eq!(Languages::parse(["C", ""]), None);
1507        let many: Vec<String> = (0..20)
1508            .map(|i| format!("x{}", (b'a' + i) as char))
1509            .collect();
1510        let many = Languages::parse(many.iter().map(String::as_str)).unwrap();
1511        assert_eq!(many.as_slice().len(), Languages::CAPACITY);
1512        let fr = Locale::parse("fr").unwrap();
1513        assert_eq!(tags(system.preferring(fr)), ["fr", "de-DE", "en-US"]);
1514        let ja = Locale::parse("ja-JP").unwrap();
1515        assert_eq!(
1516            tags(system.preferring(ja)),
1517            ["ja-JP", "de-DE", "en-US", "fr"]
1518        );
1519        assert_eq!(tags(Languages::default()), ["en-US"]);
1520        // An embedding app's language comes first.
1521        let mut env = Environment::default();
1522        env.locale_settings.languages = system;
1523        HostEnvironment {
1524            locale: Some(ja),
1525            font_scale: None,
1526        }
1527        .apply(&mut env);
1528        assert_eq!(
1529            tags(env.locale_settings.languages),
1530            ["ja-JP", "de-DE", "en-US", "fr"]
1531        );
1532    }
1533
1534    #[test]
1535    fn locales_parse_platform_identifiers() {
1536        let tag = |s: &str| Locale::parse(s).map(|l| l.as_str().to_owned());
1537        assert_eq!(tag("en_US").as_deref(), Some("en-US"));
1538        assert_eq!(tag("zh-hans_cn").as_deref(), Some("zh-Hans-CN"));
1539        assert_eq!(tag("de_DE@calendar=gregorian").as_deref(), Some("de-DE"));
1540        assert_eq!(tag("pt_BR.UTF-8").as_deref(), Some("pt-BR"));
1541        assert_eq!(tag("es-419").as_deref(), Some("es-419"));
1542        assert_eq!(tag("en-US-u-hc-h23").as_deref(), Some("en-US"));
1543        assert_eq!(tag("C"), None);
1544        assert_eq!(Locale::default().as_str(), "en-US");
1545        let zh = Locale::parse("zh-Hans-CN").unwrap();
1546        assert_eq!((zh.language(), zh.region()), ("zh", Some("CN")));
1547        assert_eq!(Locale::parse("zh-Hans").unwrap().region(), None);
1548        assert_eq!(Locale::parse("es-419").unwrap().region(), Some("419"));
1549    }
1550
1551    #[test]
1552    fn regional_preferences_are_the_regions_unless_the_locale_sets_others() {
1553        // The regional part of the settings: what the locale decides.
1554        type Regional = (HourCycle, Weekday, MeasurementSystem, TemperatureUnit);
1555        let regional = |s: LocaleSettings| -> Regional {
1556            (
1557                s.hour_cycle,
1558                s.first_day_of_week,
1559                s.measurement_system,
1560                s.temperature_unit,
1561            )
1562        };
1563        let of = |tag: &str| LocaleSettings::of(Locale::parse(tag).unwrap());
1564        let us = regional(LocaleSettings::default());
1565        let world = (
1566            HourCycle::H23,
1567            Weekday::Monday,
1568            MeasurementSystem::Metric,
1569            TemperatureUnit::Celsius,
1570        );
1571        assert_eq!(regional(of("en-US")), us);
1572        assert_eq!(
1573            LocaleSettings::default().languages.as_slice(),
1574            &[Locale::EN_US]
1575        );
1576        assert_eq!(LocaleSettings::default().time_zone, TimeZone::UTC);
1577        // The locale alone is the languages.
1578        assert_eq!(
1579            of("de-DE").languages.as_slice(),
1580            &[Locale::parse("de-DE").unwrap()]
1581        );
1582        assert_eq!(regional(of("de-DE")), world);
1583        // Without a region: the world's.
1584        assert_eq!(regional(of("ja")), world);
1585        assert_eq!(of("en-CA").hour_cycle, HourCycle::H12);
1586        // Where the language's differs from the region's.
1587        assert_eq!(of("fr-CA").hour_cycle, HourCycle::H23);
1588        assert_eq!(of("fr-CA").first_day_of_week, Weekday::Sunday);
1589        assert_eq!(of("en-001").hour_cycle, HourCycle::H12);
1590        assert_eq!(of("es-419").hour_cycle, HourCycle::H12);
1591        assert_eq!(of("ar-EG").first_day_of_week, Weekday::Saturday);
1592        assert_eq!(of("dv-MV").first_day_of_week, Weekday::Friday);
1593        let gb = of("en-GB");
1594        assert_eq!(gb.measurement_system, MeasurementSystem::Uk);
1595        assert_eq!(gb.temperature_unit, TemperatureUnit::Celsius);
1596        assert_eq!(of("en-LR").temperature_unit, TemperatureUnit::Celsius);
1597        assert_eq!(of("es-PR").temperature_unit, TemperatureUnit::Fahrenheit);
1598
1599        let parse = |identifier: &str| regional(LocaleSettings::parse(identifier));
1600        assert_eq!(
1601            parse("en-US-u-fw-mon-mu-celsius"),
1602            (
1603                HourCycle::H12,
1604                Weekday::Monday,
1605                MeasurementSystem::Us,
1606                TemperatureUnit::Celsius
1607            )
1608        );
1609        assert_eq!(
1610            parse("en_US@hours=h23;measure=metric"),
1611            (
1612                HourCycle::H23,
1613                Weekday::Sunday,
1614                MeasurementSystem::Metric,
1615                TemperatureUnit::Fahrenheit
1616            )
1617        );
1618        assert_eq!(parse("en_US@rg=gbzzzz"), regional(gb));
1619        assert_eq!(
1620            parse("ar-u-ca-islamic-umalqura-hc-h11-rg-uszzzz"),
1621            (HourCycle::H11, us.1, us.2, us.3)
1622        );
1623        assert_eq!(
1624            LocaleSettings::parse("en-GB-u-ms-ussystem-mu-fahrenhe").measurement_system,
1625            MeasurementSystem::Us
1626        );
1627        // What it does not know is left out.
1628        assert_eq!(parse("de_DE.UTF-8@fw=xyz;hours=h99;rg=1"), world);
1629        assert_eq!(parse("en-US-x-hc-h23"), us);
1630        assert_eq!(parse("C"), world);
1631        // Its locale is the languages, `en-US` where it names none.
1632        assert_eq!(
1633            LocaleSettings::parse("de_DE.UTF-8").languages.as_slice(),
1634            &[Locale::parse("de-DE").unwrap()]
1635        );
1636        assert_eq!(
1637            LocaleSettings::parse("C").languages.as_slice(),
1638            &[Locale::EN_US]
1639        );
1640        assert_eq!(Weekday::from_number(7), Some(Weekday::Sunday));
1641        assert_eq!(Weekday::from_number(0), None);
1642        assert_eq!(Weekday::Monday.number(), 1);
1643        assert!(HourCycle::H11.twelve_hour() && !HourCycle::H24.twelve_hour());
1644        assert_eq!(HourCycle::of_pattern("h:mm a"), Some(HourCycle::H12));
1645        assert_eq!(HourCycle::of_pattern("HH 'Uhr'"), Some(HourCycle::H23));
1646        assert_eq!(HourCycle::of_pattern("'h' K:mm"), Some(HourCycle::H11));
1647        assert_eq!(HourCycle::of_pattern("mm:ss"), None);
1648    }
1649
1650    #[test]
1651    fn time_zones_parse_platform_identifiers() {
1652        let zone = |s: &str| TimeZone::parse(s).map(|z| z.as_str().to_owned());
1653        assert_eq!(zone("Europe/Berlin").as_deref(), Some("Europe/Berlin"));
1654        assert_eq!(zone(":Asia/Tokyo").as_deref(), Some("Asia/Tokyo"));
1655        assert_eq!(
1656            zone("/var/db/timezone/zoneinfo/America/Argentina/Buenos_Aires").as_deref(),
1657            Some("America/Argentina/Buenos_Aires")
1658        );
1659        assert_eq!(
1660            zone("/usr/share/zoneinfo/Etc/GMT+5").as_deref(),
1661            Some("Etc/GMT+5")
1662        );
1663        assert_eq!(zone("GMT+01:00").as_deref(), Some("GMT+01:00"));
1664        assert_eq!(
1665            zone("America/Argentina/ComodRivadavia").as_deref(),
1666            Some("America/Argentina/ComodRivadavia")
1667        );
1668        assert_eq!(zone(""), None);
1669        assert_eq!(zone("Europe//Berlin"), None);
1670        assert_eq!(zone("../etc/passwd"), None);
1671        assert_eq!(zone("Central European Standard Time"), None);
1672        let parts = ["Abcdefghijklmn"; 4].join("/");
1673        assert_eq!(zone(&parts).as_deref(), Some(parts.as_str()));
1674        assert_eq!(zone(&"A".repeat(64)), None);
1675        assert_eq!(TimeZone::default().as_str(), "UTC");
1676        assert_eq!(
1677            Environment::default().locale_settings.time_zone,
1678            TimeZone::UTC
1679        );
1680    }
1681
1682    #[test]
1683    fn posix_time_zones_follow_the_zone_tz_names() {
1684        // A system zone other than UTC, so that falling back on it shows.
1685        let singapore = || TimeZone::parse("Asia/Singapore");
1686        let zone = |tz: Option<&str>| TimeZone::posix(tz, singapore).as_str().to_owned();
1687        // `TZ=GMT` is the process's zone, eight hours from the system's.
1688        assert_eq!(zone(Some("GMT")), "GMT");
1689        assert_eq!(
1690            TimeZone::posix(Some("GMT"), || unreachable!("TZ names the zone")).as_str(),
1691            "GMT"
1692        );
1693        // The tz database's names, with a slash or without, and with `:`.
1694        for name in [
1695            "UTC",
1696            "EST",
1697            "Japan",
1698            "NZ-CHAT",
1699            "Etc/GMT+5",
1700            "Europe/Berlin",
1701            "EST5EDT",
1702            "GMT0",
1703            "GMT-0",
1704        ] {
1705            assert_eq!(zone(Some(name)), name);
1706            assert_eq!(zone(Some(&format!(":{name}"))), name);
1707        }
1708        assert_eq!(zone(Some(":/usr/share/zoneinfo/Asia/Tokyo")), "Asia/Tokyo");
1709        // An empty `TZ` is UTC.
1710        assert_eq!(zone(Some("")), "UTC");
1711        // POSIX rules and other files name no zone: the system's stands.
1712        for tz in [
1713            "JST-9",
1714            "EST5",
1715            "CET-1CEST",
1716            "<+08>-8",
1717            "CET-1CEST,M3.5.0,M10.5.0/3",
1718            "GMT+01:00",
1719            ":/etc/localtime",
1720            ":",
1721        ] {
1722            assert_eq!(zone(Some(tz)), "Asia/Singapore", "TZ={tz}");
1723        }
1724        assert_eq!(zone(None), "Asia/Singapore");
1725        assert_eq!(TimeZone::posix(None, || None), TimeZone::UTC);
1726    }
1727
1728    #[test]
1729    fn content_types_follow_the_extension_of_paths_and_asset_urls() {
1730        assert_eq!(
1731            content_type("dist/app.js"),
1732            "text/javascript; charset=utf-8"
1733        );
1734        assert_eq!(content_type("nsh.WASM"), "application/wasm");
1735        assert_eq!(
1736            content_type("asset:/@app/locales/en.json"),
1737            "application/json"
1738        );
1739        assert_eq!(content_type("asset:/images/flag@2x.png"), "image/png");
1740        assert_eq!(content_type("asset:/fonts/Inter.woff2"), "font/woff2");
1741        assert_eq!(content_type("asset:/sounds/chime.OGG"), "audio/ogg");
1742        for unknown in ["asset:/data.bin", "asset:/README", "asset:/.png"] {
1743            assert_eq!(
1744                content_type(unknown),
1745                "application/octet-stream",
1746                "{unknown}"
1747            );
1748        }
1749    }
1750
1751    #[test]
1752    fn file_mime_types_come_from_the_name_alone() {
1753        assert_eq!(file_mime_type("file:///tmp/a%20b.PNG"), "image/png");
1754        assert_eq!(file_mime_type("file:///tmp/%E4%B8%AD.jpeg"), "image/jpeg");
1755        assert_eq!(file_mime_type("/Users/me/Report.pdf"), "application/pdf");
1756        assert_eq!(
1757            file_mime_type("file:///tmp/notes.md?x=1#y"),
1758            "text/markdown"
1759        );
1760        assert_eq!(file_mime_type("C:/Users/me/Clip.mov"), "video/quicktime");
1761        // A directory, no extension, a dotfile, an extension the table lacks.
1762        for none in [
1763            "file:///tmp/photos.d/",
1764            "file:///tmp/README",
1765            "file:///tmp/.env",
1766            "file:///tmp/a.unknownext",
1767            "",
1768        ] {
1769            assert_eq!(file_mime_type(none), "", "{none}");
1770        }
1771    }
1772}