pub mod clipboard;
pub mod web_evaluation;
use crate::geometry::{Edges, Points, Size};
pub const TAB_BAR_COMPONENT: &str = "nsh/tab-bar";
pub const SEGMENTED_CONTROL_COMPONENT: &str = "nsh/segmented-control";
pub const SWITCH_COMPONENT: &str = "nsh/switch";
pub const DATE_TIME_PICKER_COMPONENT: &str = "nsh/date-time-picker";
pub const MENU_BUTTON_COMPONENT: &str = "nsh/menu-button";
pub const CONTEXT_MENU_COMPONENT: &str = "nsh/context-menu";
pub const SPLIT_VIEW_COMPONENT: &str = "nsh/split-view";
pub fn is_reserved_component(name: &str) -> bool {
name.starts_with("nsh/")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ColorScheme {
#[default]
Light,
Dark,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
pub enum Appearance {
#[default]
System,
Light,
Dark,
}
impl Appearance {
pub fn resolve(self, system: ColorScheme) -> ColorScheme {
match self {
Appearance::System => system,
Appearance::Light => ColorScheme::Light,
Appearance::Dark => ColorScheme::Dark,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputModality {
Keyboard,
Pointer,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
Ios,
Android,
MacOs,
Windows,
Linux,
Web,
}
impl Os {
pub fn name(self) -> &'static str {
match self {
Os::Ios => "ios",
Os::Android => "android",
Os::MacOs => "macos",
Os::Windows => "windows",
Os::Linux => "linux",
Os::Web => "web",
}
}
pub fn is_desktop(self) -> bool {
matches!(self, Os::MacOs | Os::Windows | Os::Linux)
}
pub fn is_catalyst(self) -> bool {
self == Os::Ios && cfg!(target_abi = "macabi")
}
}
impl Default for Os {
fn default() -> Self {
if cfg!(target_os = "android") {
Os::Android
} else {
Os::Ios
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Idiom {
#[default]
Phone,
Pad,
Mac,
Tv,
Desktop,
Terminal,
}
impl Idiom {
pub fn desktop_on(self, os: Os) -> bool {
os.is_desktop() || (os == Os::Web && self == Idiom::Desktop) || self == Idiom::Terminal
}
pub fn reported_on(self, os: Os) -> Idiom {
if self == Idiom::Terminal {
Idiom::Terminal
} else if self.desktop_on(os) {
Idiom::Desktop
} else if self == Idiom::Desktop {
Idiom::Phone
} else {
self
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Lifecycle {
#[default]
Active,
Inactive,
Background,
}
impl Lifecycle {
pub fn name(self) -> &'static str {
match self {
Lifecycle::Active => "active",
Lifecycle::Inactive => "inactive",
Lifecycle::Background => "background",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeClass {
Compact,
Regular,
}
impl SizeClass {
pub(crate) fn from_length(length: Points) -> Self {
if length < Points(600.0) {
Self::Compact
} else {
Self::Regular
}
}
pub fn name(self) -> &'static str {
match self {
Self::Compact => "compact",
Self::Regular => "regular",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Environment {
pub window: Size<Points>,
pub horizontal_size_class: Option<SizeClass>,
pub vertical_size_class: Option<SizeClass>,
pub safe_area: Edges<Points>,
pub title_bar: Edges<Points>,
pub window_state: Option<crate::desktop::WindowState>,
pub keyboard_height: Points,
pub keyboard_duration: f32,
pub color_scheme: ColorScheme,
pub font_scale: f32,
pub rtl: bool,
pub reduce_motion: bool,
pub pixel_ratio: f32,
pub screen_reader: bool,
pub reads_active_descendants: bool,
pub os: Os,
pub platform: Option<&'static str>,
pub os_version: (u16, u16),
pub idiom: Idiom,
pub apple_keyboard: bool,
pub ctrl_for_command: bool,
pub locale: Locale,
pub locale_settings: LocaleSettings,
pub host: bool,
pub lifecycle: Lifecycle,
pub wake_count: u32,
pub screen_color: bool,
pub canvas_render: bool,
pub share: bool,
pub auth_session: bool,
pub file_requests: bool,
pub speech: bool,
pub notifications: bool,
pub audio: bool,
pub tab_bar: bool,
pub clipboard_images: Option<bool>,
pub cell: Option<Size<Points>>,
pub web_input: bool,
pub web_evaluate: bool,
pub web_views: bool,
pub webview_requests: bool,
pub shaders: bool,
}
impl Environment {
pub fn horizontal_size_class(&self) -> SizeClass {
self.horizontal_size_class
.unwrap_or_else(|| SizeClass::from_length(self.window.width))
}
pub fn vertical_size_class(&self) -> SizeClass {
self.vertical_size_class
.unwrap_or_else(|| SizeClass::from_length(self.window.height))
}
pub fn platform_name(&self) -> &'static str {
self.platform.unwrap_or(self.os.name())
}
pub fn desktop(&self) -> bool {
self.idiom.desktop_on(self.os)
}
pub fn reported_idiom(&self) -> Idiom {
self.idiom.reported_on(self.os)
}
}
impl Default for Environment {
fn default() -> Self {
Self {
window: Size::default(),
horizontal_size_class: None,
vertical_size_class: None,
safe_area: Edges::default(),
title_bar: Edges::default(),
window_state: None,
keyboard_height: Points(0.0),
keyboard_duration: 250.0,
color_scheme: ColorScheme::Light,
font_scale: 1.0,
rtl: false,
reduce_motion: false,
pixel_ratio: 1.0,
screen_reader: false,
reads_active_descendants: false,
os: Os::default(),
platform: None,
os_version: (0, 0),
idiom: Idiom::Phone,
apple_keyboard: false,
ctrl_for_command: false,
locale: Locale::EN_US,
locale_settings: LocaleSettings::EN_US,
host: false,
lifecycle: Lifecycle::Active,
wake_count: 0,
screen_color: false,
canvas_render: false,
share: false,
auth_session: false,
file_requests: false,
speech: false,
notifications: false,
audio: false,
tab_bar: true,
clipboard_images: None,
cell: None,
web_input: false,
web_evaluate: false,
web_views: true,
webview_requests: false,
shaders: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct HostEnvironment {
pub locale: Option<Locale>,
pub font_scale: Option<f32>,
}
impl HostEnvironment {
pub fn apply(&self, env: &mut Environment) {
if let Some(locale) = self.locale {
env.locale = locale;
env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
}
if let Some(scale) = self.font_scale.filter(|s| s.is_finite() && *s > 0.0) {
env.font_scale = scale;
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Locale {
bytes: [u8; Locale::CAPACITY],
len: u8,
}
impl Locale {
const CAPACITY: usize = 15;
pub const EN_US: Locale = Locale {
bytes: *b"en-US\0\0\0\0\0\0\0\0\0\0",
len: 5,
};
pub fn parse(identifier: &str) -> Option<Locale> {
let identifier = identifier.split(['@', '.']).next().unwrap_or_default();
let mut bytes = [0u8; Self::CAPACITY];
let mut len = 0;
for (i, part) in identifier.split(['-', '_']).enumerate() {
let keep = if i == 0 {
(2..=3).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphabetic())
} else {
(part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()))
|| (part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()))
|| (part.len() == 3 && part.bytes().all(|b| b.is_ascii_digit()))
};
if !keep {
if i == 0 {
return None;
}
break;
}
if len + part.len() + usize::from(i > 0) > Self::CAPACITY {
break;
}
if i > 0 {
bytes[len] = b'-';
len += 1;
}
for (j, b) in part.bytes().enumerate() {
bytes[len] = match (i, part.len()) {
(0, _) => b.to_ascii_lowercase(),
(_, 4) if j == 0 => b.to_ascii_uppercase(),
(_, 4) => b.to_ascii_lowercase(),
_ => b.to_ascii_uppercase(),
};
len += 1;
}
}
Some(Locale {
bytes,
len: len as u8,
})
}
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
}
pub fn language(&self) -> &str {
self.as_str().split('-').next().unwrap_or_default()
}
pub fn region(&self) -> Option<&str> {
self.as_str().split('-').skip(1).find(|s| s.len() != 4)
}
}
impl Default for Locale {
fn default() -> Self {
Self::EN_US
}
}
impl std::fmt::Debug for Locale {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Locale({})", self.as_str())
}
}
impl std::fmt::Display for Locale {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Languages {
tags: [Locale; Languages::CAPACITY],
len: u8,
}
impl Languages {
const CAPACITY: usize = 8;
pub(crate) const EN_US: Languages = Languages {
tags: [Locale::EN_US; Languages::CAPACITY],
len: 1,
};
#[doc(hidden)]
pub const fn one(locale: Locale) -> Languages {
Languages {
tags: [locale; Languages::CAPACITY],
len: 1,
}
}
#[doc(hidden)]
pub fn parse<'a>(identifiers: impl IntoIterator<Item = &'a str>) -> Option<Languages> {
let mut languages = Languages::EN_US;
languages.len = 0;
for locale in identifiers.into_iter().filter_map(Locale::parse) {
if usize::from(languages.len) == Self::CAPACITY {
break;
}
if !languages.as_slice().contains(&locale) {
languages.tags[usize::from(languages.len)] = locale;
languages.len += 1;
}
}
(languages.len > 0).then_some(languages)
}
pub fn preferring(&self, locale: Locale) -> Languages {
let mut languages = Languages::one(locale);
for &other in self.as_slice() {
if usize::from(languages.len) == Self::CAPACITY {
break;
}
if other != locale {
languages.tags[usize::from(languages.len)] = other;
languages.len += 1;
}
}
languages
}
pub fn first(&self) -> Locale {
self.tags[0]
}
pub fn as_slice(&self) -> &[Locale] {
&self.tags[..usize::from(self.len)]
}
pub fn iter(&self) -> impl Iterator<Item = Locale> + '_ {
self.as_slice().iter().copied()
}
}
impl Default for Languages {
fn default() -> Self {
Self::EN_US
}
}
impl std::fmt::Debug for Languages {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list()
.entries(self.iter().map(|l| l.to_string()))
.finish()
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TimeZone {
bytes: [u8; TimeZone::CAPACITY],
len: u8,
}
impl TimeZone {
const CAPACITY: usize = 63;
pub const UTC: TimeZone = {
let mut bytes = [0u8; TimeZone::CAPACITY];
bytes[0] = b'U';
bytes[1] = b'T';
bytes[2] = b'C';
TimeZone { bytes, len: 3 }
};
pub fn parse(identifier: &str) -> Option<TimeZone> {
let identifier = identifier.trim();
let name = match identifier.rsplit_once("zoneinfo/") {
Some((_, name)) => name,
None => identifier.strip_prefix(':').unwrap_or(identifier),
};
let valid = !name.is_empty()
&& name.len() <= Self::CAPACITY
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"/_-+:".contains(&b))
&& name
.split('/')
.all(|part| !part.is_empty() && part != "." && part != "..");
if !valid {
return None;
}
let mut bytes = [0u8; Self::CAPACITY];
bytes[..name.len()].copy_from_slice(name.as_bytes());
Some(TimeZone {
bytes,
len: name.len() as u8,
})
}
#[doc(hidden)]
pub fn posix(tz: Option<&str>, system: impl FnOnce() -> Option<TimeZone>) -> TimeZone {
let zone = match tz.map(str::trim) {
None => None,
Some("") => Some(Self::UTC),
Some(tz) => {
let name = tz.strip_prefix(':').unwrap_or(tz);
if is_posix_rule(name) && !RULE_NAMED_ZONES.contains(&name) {
None
} else {
Self::parse(name)
}
}
};
zone.or_else(system).unwrap_or_default()
}
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("UTC")
}
}
const RULE_NAMED_ZONES: [&str; 7] = [
"EST5EDT", "CST6CDT", "MST7MDT", "PST8PDT", "GMT0", "GMT+0", "GMT-0",
];
fn is_posix_rule(tz: &str) -> bool {
let letters = tz.bytes().take_while(u8::is_ascii_alphabetic).count();
tz.starts_with('<')
|| letters >= 3
&& tz
.as_bytes()
.get(letters)
.is_some_and(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-'))
}
impl Default for TimeZone {
fn default() -> Self {
Self::UTC
}
}
impl std::fmt::Debug for TimeZone {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TimeZone({})", self.as_str())
}
}
impl std::fmt::Display for TimeZone {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Default, crate::element::JsObject)]
pub struct PerfStats {
pub fps: f32,
pub refresh_rate: Option<f32>,
pub dropped: crate::geometry::Percentage,
}
impl PerfStats {
#[doc(hidden)]
pub fn new(fps: f32) -> PerfStats {
PerfStats {
fps,
..PerfStats::default()
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct LocaleSettings {
pub languages: Languages,
pub time_zone: TimeZone,
pub hour_cycle: HourCycle,
pub first_day_of_week: Weekday,
pub measurement_system: MeasurementSystem,
pub temperature_unit: TemperatureUnit,
}
impl LocaleSettings {
pub(crate) const EN_US: LocaleSettings = LocaleSettings {
languages: Languages::EN_US,
time_zone: TimeZone::UTC,
hour_cycle: HourCycle::H12,
first_day_of_week: Weekday::Sunday,
measurement_system: MeasurementSystem::Us,
temperature_unit: TemperatureUnit::Fahrenheit,
};
#[doc(hidden)]
pub fn of(locale: Locale) -> LocaleSettings {
LocaleSettings {
languages: Languages::one(locale),
..Self::of_region(locale.language(), locale.region().unwrap_or("001"))
}
}
#[doc(hidden)]
pub fn parse(identifier: &str) -> LocaleSettings {
let identifier = identifier.trim();
let (tag, icu) = identifier.split_once('@').unwrap_or((identifier, ""));
let mut keywords = Keywords::default();
let mut extension = false;
let mut key = "";
for subtag in tag.split('.').next().unwrap_or_default().split(['-', '_']) {
if subtag.len() == 1 {
extension = subtag.eq_ignore_ascii_case("u");
key = "";
} else if extension && subtag.len() == 2 {
key = subtag;
} else if extension && !key.is_empty() {
keywords.set(key, subtag);
key = "";
}
}
for keyword in icu.split(';') {
if let Some((key, value)) = keyword.split_once('=') {
keywords.set(key.trim(), value.trim());
}
}
let locale = Locale::parse(identifier);
let language = locale.as_ref().map_or("", Locale::language);
let region = match &keywords.region {
Some((bytes, len)) => std::str::from_utf8(&bytes[..*len]).unwrap_or("001"),
None => locale.as_ref().and_then(Locale::region).unwrap_or("001"),
};
let own = Self::of_region(language, region);
LocaleSettings {
languages: Languages::one(locale.unwrap_or(Locale::EN_US)),
hour_cycle: keywords.hour_cycle.unwrap_or(own.hour_cycle),
first_day_of_week: keywords.first_day_of_week.unwrap_or(own.first_day_of_week),
measurement_system: keywords
.measurement_system
.unwrap_or(own.measurement_system),
temperature_unit: keywords.temperature_unit.unwrap_or(own.temperature_unit),
..own
}
}
fn of_region(language: &str, region: &str) -> LocaleSettings {
let listed = |regions: &[&str]| regions.binary_search(®ion).is_ok();
LocaleSettings {
hour_cycle: match (language, region) {
("fr", "CA") | ("ku", "SY") => HourCycle::H23,
("ar" | "en", "001") => HourCycle::H12,
_ if listed(HOUR12_REGIONS) => HourCycle::H12,
_ => HourCycle::H23,
},
first_day_of_week: if listed(SUNDAY_REGIONS) {
Weekday::Sunday
} else if listed(SATURDAY_REGIONS) {
Weekday::Saturday
} else if listed(FRIDAY_REGIONS) {
Weekday::Friday
} else {
Weekday::Monday
},
measurement_system: match region {
"LR" | "US" => MeasurementSystem::Us,
"GB" | "MM" => MeasurementSystem::Uk,
_ => MeasurementSystem::Metric,
},
temperature_unit: match region {
"BS" | "BZ" | "KY" | "PR" | "PW" | "US" => TemperatureUnit::Fahrenheit,
_ => TemperatureUnit::Celsius,
},
..Self::default()
}
}
}
impl Default for LocaleSettings {
fn default() -> Self {
Self::EN_US
}
}
#[derive(Default)]
struct Keywords {
hour_cycle: Option<HourCycle>,
first_day_of_week: Option<Weekday>,
measurement_system: Option<MeasurementSystem>,
temperature_unit: Option<TemperatureUnit>,
region: Option<([u8; 3], usize)>,
}
impl Keywords {
fn set(&mut self, key: &str, value: &str) {
let is = |names: &[&str]| names.iter().any(|n| key.eq_ignore_ascii_case(n));
let value_is = |name: &str| value.eq_ignore_ascii_case(name);
if is(&["hc", "hours"]) {
self.hour_cycle = HourCycle::parse(value).or(self.hour_cycle);
} else if is(&["fw"]) {
self.first_day_of_week = Weekday::ALL
.into_iter()
.find(|d| value_is(d.code()))
.or(self.first_day_of_week);
} else if is(&["ms", "measure"]) {
self.measurement_system = match () {
_ if value_is("metric") => Some(MeasurementSystem::Metric),
_ if value_is("ussystem") => Some(MeasurementSystem::Us),
_ if value_is("uksystem") => Some(MeasurementSystem::Uk),
_ => self.measurement_system,
};
} else if is(&["mu"]) {
let unit = match value_is("fahrenhe") {
true => Some(TemperatureUnit::Fahrenheit),
false => TemperatureUnit::parse(value),
};
self.temperature_unit = unit.or(self.temperature_unit);
} else if is(&["rg"]) {
let bytes = value.as_bytes();
let len = match bytes {
[a, b, c, ..] if [a, b, c].iter().all(|b| b.is_ascii_digit()) => 3,
[a, b, ..] if a.is_ascii_alphabetic() && b.is_ascii_alphabetic() => 2,
_ => return,
};
let mut region = [0u8; 3];
for (to, from) in region.iter_mut().zip(bytes) {
*to = from.to_ascii_uppercase();
}
self.region = Some((region, len));
}
}
}
const HOUR12_REGIONS: &[&str] = &[
"419", "AE", "AG", "AL", "AR", "AS", "AU", "BB", "BD", "BH", "BM", "BN", "BO", "BS", "BT",
"CA", "CL", "CO", "CR", "CU", "CY", "DJ", "DM", "DO", "DZ", "EC", "EG", "EH", "ER", "ET", "FJ",
"FM", "GD", "GH", "GM", "GR", "GT", "GU", "GY", "HK", "HN", "IN", "IQ", "JM", "JO", "KH", "KI",
"KN", "KP", "KR", "KW", "KY", "LB", "LC", "LR", "LS", "LY", "MH", "MO", "MP", "MR", "MW", "MX",
"MY", "NA", "NI", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PR", "PS", "PW", "PY", "QA", "SA",
"SB", "SD", "SG", "SL", "SO", "SS", "SV", "SY", "SZ", "TC", "TD", "TN", "TO", "TT", "TW", "UM",
"US", "UY", "VC", "VE", "VG", "VI", "VU", "WS", "YE", "ZM",
];
const SUNDAY_REGIONS: &[&str] = &[
"AG", "AS", "BD", "BR", "BS", "BT", "BW", "BZ", "CA", "CO", "DM", "DO", "ET", "GT", "GU", "HK",
"HN", "ID", "IL", "IN", "IS", "JM", "JP", "KE", "KH", "KR", "LA", "MH", "MM", "MO", "MT", "MX",
"MZ", "NI", "NP", "PA", "PE", "PH", "PK", "PR", "PT", "PY", "SA", "SG", "SV", "TH", "TT", "TW",
"UM", "US", "VE", "VI", "WS", "YE", "ZA", "ZW",
];
const SATURDAY_REGIONS: &[&str] = &[
"AF", "BH", "DJ", "DZ", "EG", "IQ", "IR", "JO", "KW", "LY", "OM", "QA", "SD", "SY",
];
const FRIDAY_REGIONS: &[&str] = &["MV"];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
pub enum HourCycle {
H11,
#[default]
H12,
H23,
H24,
}
impl HourCycle {
pub fn name(self) -> &'static str {
match self {
HourCycle::H11 => "h11",
HourCycle::H12 => "h12",
HourCycle::H23 => "h23",
HourCycle::H24 => "h24",
}
}
pub fn parse(name: &str) -> Option<HourCycle> {
[
HourCycle::H11,
HourCycle::H12,
HourCycle::H23,
HourCycle::H24,
]
.into_iter()
.find(|c| name.eq_ignore_ascii_case(c.name()))
}
#[doc(hidden)]
pub fn of_pattern(pattern: &str) -> Option<HourCycle> {
let mut quoted = false;
pattern.chars().find_map(|c| match c {
'\'' => {
quoted = !quoted;
None
}
_ if quoted => None,
'h' => Some(HourCycle::H12),
'H' => Some(HourCycle::H23),
'K' => Some(HourCycle::H11),
'k' => Some(HourCycle::H24),
_ => None,
})
}
pub fn twelve_hour(self) -> bool {
matches!(self, HourCycle::H11 | HourCycle::H12)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Weekday {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}
impl Weekday {
const ALL: [Weekday; 7] = [
Weekday::Monday,
Weekday::Tuesday,
Weekday::Wednesday,
Weekday::Thursday,
Weekday::Friday,
Weekday::Saturday,
Weekday::Sunday,
];
pub fn number(self) -> u8 {
self as u8
}
pub fn from_number(number: u8) -> Option<Weekday> {
Self::ALL.get(usize::from(number).checked_sub(1)?).copied()
}
fn code(self) -> &'static str {
match self {
Weekday::Monday => "mon",
Weekday::Tuesday => "tue",
Weekday::Wednesday => "wed",
Weekday::Thursday => "thu",
Weekday::Friday => "fri",
Weekday::Saturday => "sat",
Weekday::Sunday => "sun",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
pub enum MeasurementSystem {
#[default]
Metric,
Us,
Uk,
}
impl MeasurementSystem {
pub fn name(self) -> &'static str {
match self {
MeasurementSystem::Metric => "metric",
MeasurementSystem::Us => "us",
MeasurementSystem::Uk => "uk",
}
}
pub fn parse(name: &str) -> Option<MeasurementSystem> {
[
MeasurementSystem::Metric,
MeasurementSystem::Us,
MeasurementSystem::Uk,
]
.into_iter()
.find(|s| name.eq_ignore_ascii_case(s.name()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
pub enum TemperatureUnit {
#[default]
Celsius,
Fahrenheit,
}
impl TemperatureUnit {
pub fn name(self) -> &'static str {
match self {
TemperatureUnit::Celsius => "celsius",
TemperatureUnit::Fahrenheit => "fahrenheit",
}
}
pub fn parse(name: &str) -> Option<TemperatureUnit> {
[TemperatureUnit::Celsius, TemperatureUnit::Fahrenheit]
.into_iter()
.find(|u| name.eq_ignore_ascii_case(u.name()))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpRequest {
pub method: String,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: HttpBody,
pub follow_redirects: bool,
}
impl HttpRequest {
pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
Self {
method: method.into().to_ascii_uppercase(),
url: url.into(),
headers: Vec::new(),
body: HttpBody::Empty,
follow_redirects: true,
}
}
pub fn get(url: impl Into<String>) -> Self {
Self::new("GET", url)
}
pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
Self::new("POST", url).body(body)
}
#[must_use]
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
#[must_use]
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
self.body = HttpBody::Bytes(body.into());
self
}
}
impl From<&str> for HttpRequest {
fn from(url: &str) -> Self {
Self::get(url)
}
}
impl From<String> for HttpRequest {
fn from(url: String) -> Self {
Self::get(url)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum HttpBody {
#[default]
Empty,
Bytes(Vec<u8>),
Stream,
}
impl HttpBody {
pub fn is_empty(&self) -> bool {
match self {
HttpBody::Empty => true,
HttpBody::Bytes(b) => b.is_empty(),
HttpBody::Stream => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HttpHead {
pub status: u16,
pub status_text: String,
pub url: String,
pub redirected: bool,
pub headers: Vec<(String, String)>,
}
#[doc(hidden)]
pub fn content_type(path: &str) -> &'static str {
match std::path::Path::new(path)
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase)
.as_deref()
{
Some("html") => "text/html; charset=utf-8",
Some("js" | "mjs") => "text/javascript; charset=utf-8",
Some("json" | "map") => "application/json",
Some("webmanifest") => "application/manifest+json",
Some("wasm") => "application/wasm",
Some("css") => "text/css; charset=utf-8",
Some("txt") => "text/plain; charset=utf-8",
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
Some("avif") => "image/avif",
Some("svg") => "image/svg+xml",
Some("ico") => "image/x-icon",
Some("heic") => "image/heic",
Some("ttf") => "font/ttf",
Some("otf") => "font/otf",
Some("woff") => "font/woff",
Some("woff2") => "font/woff2",
Some("mp4" | "m4v") => "video/mp4",
Some("webm") => "video/webm",
Some("mov") => "video/quicktime",
Some("mp3") => "audio/mpeg",
Some("m4a") => "audio/mp4",
Some("aac") => "audio/aac",
Some("wav") => "audio/wav",
Some("ogg" | "oga" | "opus") => "audio/ogg",
Some("flac") => "audio/flac",
Some("aif" | "aiff") => "audio/aiff",
Some("caf") => "audio/x-caf",
_ => "application/octet-stream",
}
}
#[doc(hidden)]
pub fn file_mime_type(uri: &str) -> &'static str {
let path = uri.split(['?', '#']).next().unwrap_or_default();
let name = path.rsplit('/').next().unwrap_or_default();
let Some((stem, ext)) = name.rsplit_once('.') else {
return "";
};
if stem.is_empty() {
return "";
}
match ext.to_ascii_lowercase().as_str() {
"png" => "image/png",
"jpg" | "jpeg" | "jpe" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"avif" => "image/avif",
"heic" => "image/heic",
"heif" => "image/heif",
"svg" => "image/svg+xml",
"bmp" => "image/bmp",
"tif" | "tiff" => "image/tiff",
"ico" => "image/x-icon",
"mp4" | "m4v" => "video/mp4",
"mov" => "video/quicktime",
"webm" => "video/webm",
"mkv" => "video/x-matroska",
"avi" => "video/x-msvideo",
"mp3" => "audio/mpeg",
"m4a" => "audio/mp4",
"aac" => "audio/aac",
"wav" => "audio/wav",
"ogg" | "oga" | "opus" => "audio/ogg",
"flac" => "audio/flac",
"aif" | "aiff" => "audio/aiff",
"caf" => "audio/x-caf",
"txt" | "text" | "log" => "text/plain",
"md" | "markdown" => "text/markdown",
"csv" => "text/csv",
"tsv" => "text/tab-separated-values",
"html" | "htm" => "text/html",
"css" => "text/css",
"js" | "mjs" => "text/javascript",
"json" => "application/json",
"xml" => "application/xml",
"yaml" | "yml" => "application/yaml",
"pdf" => "application/pdf",
"rtf" => "application/rtf",
"doc" => "application/msword",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xls" => "application/vnd.ms-excel",
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"ppt" => "application/vnd.ms-powerpoint",
"pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"zip" => "application/zip",
"gz" | "tgz" => "application/gzip",
"tar" => "application/x-tar",
"7z" => "application/x-7z-compressed",
"rar" => "application/vnd.rar",
"wasm" => "application/wasm",
"ttf" => "font/ttf",
"otf" => "font/otf",
"woff" => "font/woff",
"woff2" => "font/woff2",
_ => "",
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchEvent {
BodyWanted,
Head(HttpHead),
Data(Vec<u8>),
End,
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FetchOp {
Start(HttpRequest),
Send(Vec<u8>),
Finish,
Pause(bool),
Cancel,
}
#[cfg(test)]
mod tests {
#[test]
fn size_class_fallback_uses_points_and_native_traits_win() {
use super::{Environment, SizeClass};
use crate::geometry::size_pt;
for (dimension, expected) in [
(0.0, SizeClass::Compact),
(599.5, SizeClass::Compact),
(600.0, SizeClass::Regular),
(1200.0, SizeClass::Regular),
] {
let env = Environment {
window: size_pt(dimension, dimension),
..Default::default()
};
assert_eq!(env.horizontal_size_class(), expected);
assert_eq!(env.vertical_size_class(), expected);
}
let env = Environment {
window: size_pt(900.0, 300.0),
horizontal_size_class: Some(SizeClass::Compact),
vertical_size_class: Some(SizeClass::Regular),
..Default::default()
};
assert_eq!(env.horizontal_size_class(), SizeClass::Compact);
assert_eq!(env.vertical_size_class(), SizeClass::Regular);
}
use super::{
Environment, HostEnvironment, HourCycle, Idiom, Languages, Locale, LocaleSettings,
MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday, content_type, file_mime_type,
};
#[test]
fn desktop_is_a_desktop_os_or_a_desktop_browser() {
let desktop = |os: Os, idiom: Idiom| Environment {
os,
idiom,
..Environment::default()
};
for (os, idiom, expected) in [
(Os::MacOs, Idiom::Desktop, true),
(Os::Windows, Idiom::Desktop, true),
(Os::Linux, Idiom::Desktop, true),
(Os::Linux, Idiom::Phone, true),
(Os::Web, Idiom::Desktop, true),
(Os::Web, Idiom::Pad, false),
(Os::Web, Idiom::Phone, false),
(Os::Ios, Idiom::Phone, false),
(Os::Ios, Idiom::Pad, false),
(Os::Ios, Idiom::Mac, false),
(Os::Ios, Idiom::Desktop, false),
(Os::Android, Idiom::Tv, false),
] {
let env = desktop(os, idiom);
assert_eq!(env.desktop(), expected, "{os:?} {idiom:?}");
assert_eq!(
env.reported_idiom() == Idiom::Desktop,
expected,
"{os:?} {idiom:?}"
);
}
assert_eq!(desktop(Os::Ios, Idiom::Mac).reported_idiom(), Idiom::Mac);
assert_eq!(
desktop(Os::Ios, Idiom::Desktop).reported_idiom(),
Idiom::Phone
);
assert!(!Os::MacOs.is_catalyst() && !Os::Web.is_catalyst());
assert_eq!(Os::Ios.is_catalyst(), cfg!(target_abi = "macabi"));
}
#[test]
fn desktop_behavior_applies_in_the_terminal_idiom_on_any_os() {
for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Web] {
assert!(Idiom::Terminal.desktop_on(os), "{os:?}");
assert_eq!(Idiom::Terminal.reported_on(os), Idiom::Terminal, "{os:?}");
}
}
#[test]
fn a_host_environment_replaces_what_it_sets() {
let mut env = Environment {
font_scale: 1.25,
..Environment::default()
};
HostEnvironment::default().apply(&mut env);
assert_eq!((env.locale, env.font_scale), (Locale::EN_US, 1.25));
let zh = Locale::parse("zh-Hans-CN").unwrap();
HostEnvironment {
locale: Some(zh),
font_scale: Some(f32::NAN),
}
.apply(&mut env);
assert_eq!((env.locale, env.font_scale), (zh, 1.25));
HostEnvironment {
locale: None,
font_scale: Some(1.5),
}
.apply(&mut env);
assert_eq!((env.locale, env.font_scale), (zh, 1.5));
}
#[test]
fn languages_parse_platform_identifiers_and_an_embedding_app_goes_first() {
let tags = |l: Languages| l.iter().map(|l| l.to_string()).collect::<Vec<_>>();
let system = Languages::parse(["de_DE", "C", "en-US", "de-DE", "fr"]).unwrap();
assert_eq!(tags(system), ["de-DE", "en-US", "fr"]);
assert_eq!(system.first().as_str(), "de-DE");
assert_eq!(Languages::parse(["C", ""]), None);
let many: Vec<String> = (0..20)
.map(|i| format!("x{}", (b'a' + i) as char))
.collect();
let many = Languages::parse(many.iter().map(String::as_str)).unwrap();
assert_eq!(many.as_slice().len(), Languages::CAPACITY);
let fr = Locale::parse("fr").unwrap();
assert_eq!(tags(system.preferring(fr)), ["fr", "de-DE", "en-US"]);
let ja = Locale::parse("ja-JP").unwrap();
assert_eq!(
tags(system.preferring(ja)),
["ja-JP", "de-DE", "en-US", "fr"]
);
assert_eq!(tags(Languages::default()), ["en-US"]);
let mut env = Environment::default();
env.locale_settings.languages = system;
HostEnvironment {
locale: Some(ja),
font_scale: None,
}
.apply(&mut env);
assert_eq!(
tags(env.locale_settings.languages),
["ja-JP", "de-DE", "en-US", "fr"]
);
}
#[test]
fn locales_parse_platform_identifiers() {
let tag = |s: &str| Locale::parse(s).map(|l| l.as_str().to_owned());
assert_eq!(tag("en_US").as_deref(), Some("en-US"));
assert_eq!(tag("zh-hans_cn").as_deref(), Some("zh-Hans-CN"));
assert_eq!(tag("de_DE@calendar=gregorian").as_deref(), Some("de-DE"));
assert_eq!(tag("pt_BR.UTF-8").as_deref(), Some("pt-BR"));
assert_eq!(tag("es-419").as_deref(), Some("es-419"));
assert_eq!(tag("en-US-u-hc-h23").as_deref(), Some("en-US"));
assert_eq!(tag("C"), None);
assert_eq!(Locale::default().as_str(), "en-US");
let zh = Locale::parse("zh-Hans-CN").unwrap();
assert_eq!((zh.language(), zh.region()), ("zh", Some("CN")));
assert_eq!(Locale::parse("zh-Hans").unwrap().region(), None);
assert_eq!(Locale::parse("es-419").unwrap().region(), Some("419"));
}
#[test]
fn regional_preferences_are_the_regions_unless_the_locale_sets_others() {
type Regional = (HourCycle, Weekday, MeasurementSystem, TemperatureUnit);
let regional = |s: LocaleSettings| -> Regional {
(
s.hour_cycle,
s.first_day_of_week,
s.measurement_system,
s.temperature_unit,
)
};
let of = |tag: &str| LocaleSettings::of(Locale::parse(tag).unwrap());
let us = regional(LocaleSettings::default());
let world = (
HourCycle::H23,
Weekday::Monday,
MeasurementSystem::Metric,
TemperatureUnit::Celsius,
);
assert_eq!(regional(of("en-US")), us);
assert_eq!(
LocaleSettings::default().languages.as_slice(),
&[Locale::EN_US]
);
assert_eq!(LocaleSettings::default().time_zone, TimeZone::UTC);
assert_eq!(
of("de-DE").languages.as_slice(),
&[Locale::parse("de-DE").unwrap()]
);
assert_eq!(regional(of("de-DE")), world);
assert_eq!(regional(of("ja")), world);
assert_eq!(of("en-CA").hour_cycle, HourCycle::H12);
assert_eq!(of("fr-CA").hour_cycle, HourCycle::H23);
assert_eq!(of("fr-CA").first_day_of_week, Weekday::Sunday);
assert_eq!(of("en-001").hour_cycle, HourCycle::H12);
assert_eq!(of("es-419").hour_cycle, HourCycle::H12);
assert_eq!(of("ar-EG").first_day_of_week, Weekday::Saturday);
assert_eq!(of("dv-MV").first_day_of_week, Weekday::Friday);
let gb = of("en-GB");
assert_eq!(gb.measurement_system, MeasurementSystem::Uk);
assert_eq!(gb.temperature_unit, TemperatureUnit::Celsius);
assert_eq!(of("en-LR").temperature_unit, TemperatureUnit::Celsius);
assert_eq!(of("es-PR").temperature_unit, TemperatureUnit::Fahrenheit);
let parse = |identifier: &str| regional(LocaleSettings::parse(identifier));
assert_eq!(
parse("en-US-u-fw-mon-mu-celsius"),
(
HourCycle::H12,
Weekday::Monday,
MeasurementSystem::Us,
TemperatureUnit::Celsius
)
);
assert_eq!(
parse("en_US@hours=h23;measure=metric"),
(
HourCycle::H23,
Weekday::Sunday,
MeasurementSystem::Metric,
TemperatureUnit::Fahrenheit
)
);
assert_eq!(parse("en_US@rg=gbzzzz"), regional(gb));
assert_eq!(
parse("ar-u-ca-islamic-umalqura-hc-h11-rg-uszzzz"),
(HourCycle::H11, us.1, us.2, us.3)
);
assert_eq!(
LocaleSettings::parse("en-GB-u-ms-ussystem-mu-fahrenhe").measurement_system,
MeasurementSystem::Us
);
assert_eq!(parse("de_DE.UTF-8@fw=xyz;hours=h99;rg=1"), world);
assert_eq!(parse("en-US-x-hc-h23"), us);
assert_eq!(parse("C"), world);
assert_eq!(
LocaleSettings::parse("de_DE.UTF-8").languages.as_slice(),
&[Locale::parse("de-DE").unwrap()]
);
assert_eq!(
LocaleSettings::parse("C").languages.as_slice(),
&[Locale::EN_US]
);
assert_eq!(Weekday::from_number(7), Some(Weekday::Sunday));
assert_eq!(Weekday::from_number(0), None);
assert_eq!(Weekday::Monday.number(), 1);
assert!(HourCycle::H11.twelve_hour() && !HourCycle::H24.twelve_hour());
assert_eq!(HourCycle::of_pattern("h:mm a"), Some(HourCycle::H12));
assert_eq!(HourCycle::of_pattern("HH 'Uhr'"), Some(HourCycle::H23));
assert_eq!(HourCycle::of_pattern("'h' K:mm"), Some(HourCycle::H11));
assert_eq!(HourCycle::of_pattern("mm:ss"), None);
}
#[test]
fn time_zones_parse_platform_identifiers() {
let zone = |s: &str| TimeZone::parse(s).map(|z| z.as_str().to_owned());
assert_eq!(zone("Europe/Berlin").as_deref(), Some("Europe/Berlin"));
assert_eq!(zone(":Asia/Tokyo").as_deref(), Some("Asia/Tokyo"));
assert_eq!(
zone("/var/db/timezone/zoneinfo/America/Argentina/Buenos_Aires").as_deref(),
Some("America/Argentina/Buenos_Aires")
);
assert_eq!(
zone("/usr/share/zoneinfo/Etc/GMT+5").as_deref(),
Some("Etc/GMT+5")
);
assert_eq!(zone("GMT+01:00").as_deref(), Some("GMT+01:00"));
assert_eq!(
zone("America/Argentina/ComodRivadavia").as_deref(),
Some("America/Argentina/ComodRivadavia")
);
assert_eq!(zone(""), None);
assert_eq!(zone("Europe//Berlin"), None);
assert_eq!(zone("../etc/passwd"), None);
assert_eq!(zone("Central European Standard Time"), None);
let parts = ["Abcdefghijklmn"; 4].join("/");
assert_eq!(zone(&parts).as_deref(), Some(parts.as_str()));
assert_eq!(zone(&"A".repeat(64)), None);
assert_eq!(TimeZone::default().as_str(), "UTC");
assert_eq!(
Environment::default().locale_settings.time_zone,
TimeZone::UTC
);
}
#[test]
fn posix_time_zones_follow_the_zone_tz_names() {
let singapore = || TimeZone::parse("Asia/Singapore");
let zone = |tz: Option<&str>| TimeZone::posix(tz, singapore).as_str().to_owned();
assert_eq!(zone(Some("GMT")), "GMT");
assert_eq!(
TimeZone::posix(Some("GMT"), || unreachable!("TZ names the zone")).as_str(),
"GMT"
);
for name in [
"UTC",
"EST",
"Japan",
"NZ-CHAT",
"Etc/GMT+5",
"Europe/Berlin",
"EST5EDT",
"GMT0",
"GMT-0",
] {
assert_eq!(zone(Some(name)), name);
assert_eq!(zone(Some(&format!(":{name}"))), name);
}
assert_eq!(zone(Some(":/usr/share/zoneinfo/Asia/Tokyo")), "Asia/Tokyo");
assert_eq!(zone(Some("")), "UTC");
for tz in [
"JST-9",
"EST5",
"CET-1CEST",
"<+08>-8",
"CET-1CEST,M3.5.0,M10.5.0/3",
"GMT+01:00",
":/etc/localtime",
":",
] {
assert_eq!(zone(Some(tz)), "Asia/Singapore", "TZ={tz}");
}
assert_eq!(zone(None), "Asia/Singapore");
assert_eq!(TimeZone::posix(None, || None), TimeZone::UTC);
}
#[test]
fn content_types_follow_the_extension_of_paths_and_asset_urls() {
assert_eq!(
content_type("dist/app.js"),
"text/javascript; charset=utf-8"
);
assert_eq!(content_type("nsh.WASM"), "application/wasm");
assert_eq!(
content_type("asset:/@app/locales/en.json"),
"application/json"
);
assert_eq!(content_type("asset:/images/flag@2x.png"), "image/png");
assert_eq!(content_type("asset:/fonts/Inter.woff2"), "font/woff2");
assert_eq!(content_type("asset:/sounds/chime.OGG"), "audio/ogg");
for unknown in ["asset:/data.bin", "asset:/README", "asset:/.png"] {
assert_eq!(
content_type(unknown),
"application/octet-stream",
"{unknown}"
);
}
}
#[test]
fn file_mime_types_come_from_the_name_alone() {
assert_eq!(file_mime_type("file:///tmp/a%20b.PNG"), "image/png");
assert_eq!(file_mime_type("file:///tmp/%E4%B8%AD.jpeg"), "image/jpeg");
assert_eq!(file_mime_type("/Users/me/Report.pdf"), "application/pdf");
assert_eq!(
file_mime_type("file:///tmp/notes.md?x=1#y"),
"text/markdown"
);
assert_eq!(file_mime_type("C:/Users/me/Clip.mov"), "video/quicktime");
for none in [
"file:///tmp/photos.d/",
"file:///tmp/README",
"file:///tmp/.env",
"file:///tmp/a.unknownext",
"",
] {
assert_eq!(file_mime_type(none), "", "{none}");
}
}
}