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