1pub mod clipboard;
6pub mod web_evaluation;
7
8use crate::geometry::{Edges, Points, Size};
9
10pub const TAB_BAR_COMPONENT: &str = "nsh/tab-bar";
14
15pub const SEGMENTED_CONTROL_COMPONENT: &str = "nsh/segmented-control";
18
19pub const SWITCH_COMPONENT: &str = "nsh/switch";
23
24pub const DATE_TIME_PICKER_COMPONENT: &str = "nsh/date-time-picker";
28
29pub const MENU_BUTTON_COMPONENT: &str = "nsh/menu-button";
33
34pub const CONTEXT_MENU_COMPONENT: &str = "nsh/context-menu";
38
39pub const SPLIT_VIEW_COMPONENT: &str = "nsh/split-view";
43
44pub fn is_reserved_component(name: &str) -> bool {
48 name.starts_with("nsh/")
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53pub enum ColorScheme {
54 #[default]
56 Light,
57 Dark,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
64pub enum Appearance {
65 #[default]
67 System,
68 Light,
70 Dark,
72}
73
74impl Appearance {
75 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum InputModality {
90 Keyboard,
93 Pointer,
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum Os {
100 Ios,
102 Android,
104 MacOs,
106 Windows,
108 Linux,
110 Web,
113}
114
115impl Os {
116 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 pub fn is_desktop(self) -> bool {
134 matches!(self, Os::MacOs | Os::Windows | Os::Linux)
135 }
136
137 pub fn is_catalyst(self) -> bool {
142 self == Os::Ios && cfg!(target_abi = "macabi")
143 }
144}
145
146impl Default for Os {
147 fn default() -> Self {
150 if cfg!(target_os = "android") {
151 Os::Android
152 } else {
153 Os::Ios
154 }
155 }
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
160pub enum Idiom {
161 #[default]
163 Phone,
164 Pad,
166 Mac,
169 Tv,
171 Desktop,
175 Terminal,
178}
179
180impl Idiom {
181 pub fn desktop_on(self, os: Os) -> bool {
188 os.is_desktop() || (os == Os::Web && self == Idiom::Desktop) || self == Idiom::Terminal
189 }
190
191 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
212pub enum Lifecycle {
213 #[default]
215 Active,
216 Inactive,
220 Background,
223}
224
225impl Lifecycle {
226 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum SizeClass {
239 Compact,
241 Regular,
243}
244
245impl SizeClass {
246 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 pub fn name(self) -> &'static str {
258 match self {
259 Self::Compact => "compact",
260 Self::Regular => "regular",
261 }
262 }
263}
264
265#[derive(Debug, Clone, Copy, PartialEq)]
267pub struct Environment {
268 pub window: Size<Points>,
270 pub horizontal_size_class: Option<SizeClass>,
272 pub vertical_size_class: Option<SizeClass>,
274 pub safe_area: Edges<Points>,
276 pub title_bar: Edges<Points>,
282 pub window_state: Option<crate::desktop::WindowState>,
287 pub keyboard_height: Points,
289 pub keyboard_duration: f32,
291 pub color_scheme: ColorScheme,
293 pub font_scale: f32,
295 pub rtl: bool,
297 pub reduce_motion: bool,
300 pub pixel_ratio: f32,
302 pub screen_reader: bool,
304 pub reads_active_descendants: bool,
311 pub os: Os,
313 pub platform: Option<&'static str>,
319 pub os_version: (u16, u16),
322 pub idiom: Idiom,
324 pub apple_keyboard: bool,
329 pub ctrl_for_command: bool,
334 pub locale: Locale,
336 pub locale_settings: LocaleSettings,
339 pub host: bool,
342 pub lifecycle: Lifecycle,
346 pub wake_count: u32,
353 pub screen_color: bool,
357 pub canvas_render: bool,
361 pub share: bool,
365 pub auth_session: bool,
371 pub file_requests: bool,
376 pub speech: bool,
380 pub notifications: bool,
384 pub audio: bool,
388 pub tab_bar: bool,
396 pub clipboard_images: Option<bool>,
404 pub cell: Option<Size<Points>>,
411 pub web_input: bool,
415 pub web_evaluate: bool,
418 pub web_views: bool,
425 pub webview_requests: bool,
431 pub shaders: bool,
439}
440
441impl Environment {
442 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 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 pub fn platform_name(&self) -> &'static str {
458 self.platform.unwrap_or(self.os.name())
459 }
460
461 pub fn desktop(&self) -> bool {
466 self.idiom.desktop_on(self.os)
467 }
468
469 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#[derive(Debug, Clone, Copy, PartialEq, Default)]
531pub struct HostEnvironment {
532 pub locale: Option<Locale>,
534 pub font_scale: Option<f32>,
537}
538
539impl HostEnvironment {
540 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#[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 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 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 (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 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 pub fn as_str(&self) -> &str {
619 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
621 }
622
623 pub fn language(&self) -> &str {
625 self.as_str().split('-').next().unwrap_or_default()
626 }
627
628 pub fn region(&self) -> Option<&str> {
630 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#[derive(Clone, Copy, PartialEq, Eq, Hash)]
657pub struct Languages {
658 tags: [Locale; Languages::CAPACITY],
659 len: u8,
660}
661
662impl Languages {
663 const CAPACITY: usize = 8;
666
667 pub(crate) const EN_US: Languages = Languages {
669 tags: [Locale::EN_US; Languages::CAPACITY],
670 len: 1,
671 };
672
673 #[doc(hidden)]
675 pub const fn one(locale: Locale) -> Languages {
676 Languages {
677 tags: [locale; Languages::CAPACITY],
678 len: 1,
679 }
680 }
681
682 #[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 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 pub fn first(&self) -> Locale {
721 self.tags[0]
722 }
723
724 pub fn as_slice(&self) -> &[Locale] {
726 &self.tags[..usize::from(self.len)]
727 }
728
729 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#[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 const CAPACITY: usize = 63;
766
767 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 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 #[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 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 pub fn as_str(&self) -> &str {
841 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("UTC")
843 }
844}
845
846const RULE_NAMED_ZONES: [&str; 7] = [
850 "EST5EDT", "CST6CDT", "MST7MDT", "PST8PDT", "GMT0", "GMT+0", "GMT-0",
851];
852
853fn 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#[non_exhaustive]
890#[derive(Debug, Clone, Copy, PartialEq, Default, crate::element::JsObject)]
891pub struct PerfStats {
892 pub fps: f32,
895 pub refresh_rate: Option<f32>,
898 pub dropped: crate::geometry::Percentage,
901}
902
903impl PerfStats {
904 #[doc(hidden)]
908 pub fn new(fps: f32) -> PerfStats {
909 PerfStats {
910 fps,
911 ..PerfStats::default()
912 }
913 }
914}
915
916#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
925#[non_exhaustive]
926pub struct LocaleSettings {
927 pub languages: Languages,
930 pub time_zone: TimeZone,
932 pub hour_cycle: HourCycle,
934 pub first_day_of_week: Weekday,
936 pub measurement_system: MeasurementSystem,
938 pub temperature_unit: TemperatureUnit,
940}
941
942impl LocaleSettings {
943 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 #[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 #[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 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 fn of_region(language: &str, region: &str) -> LocaleSettings {
1021 let listed = |regions: &[&str]| regions.binary_search(®ion).is_ok();
1022 LocaleSettings {
1023 hour_cycle: match (language, region) {
1024 ("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#[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 region: Option<([u8; 3], usize)>,
1068}
1069
1070impl Keywords {
1071 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 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 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
1114const 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
1125const 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
1133const SATURDAY_REGIONS: &[&str] = &[
1135 "AF", "BH", "DJ", "DZ", "EG", "IQ", "IR", "JO", "KW", "LY", "OM", "QA", "SD", "SY",
1136];
1137
1138const FRIDAY_REGIONS: &[&str] = &["MV"];
1140
1141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1143pub enum HourCycle {
1144 H11,
1146 #[default]
1148 H12,
1149 H23,
1151 H24,
1153}
1154
1155impl HourCycle {
1156 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 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 #[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 pub fn twelve_hour(self) -> bool {
1201 matches!(self, HourCycle::H11 | HourCycle::H12)
1202 }
1203}
1204
1205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1207pub enum Weekday {
1208 Monday = 1,
1210 Tuesday,
1212 Wednesday,
1214 Thursday,
1216 Friday,
1218 Saturday,
1220 Sunday,
1222}
1223
1224impl Weekday {
1225 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 pub fn number(self) -> u8 {
1239 self as u8
1240 }
1241
1242 pub fn from_number(number: u8) -> Option<Weekday> {
1244 Self::ALL.get(usize::from(number).checked_sub(1)?).copied()
1245 }
1246
1247 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1263pub enum MeasurementSystem {
1264 #[default]
1266 Metric,
1267 Us,
1269 Uk,
1271}
1272
1273impl MeasurementSystem {
1274 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1297pub enum TemperatureUnit {
1298 #[default]
1300 Celsius,
1301 Fahrenheit,
1303}
1304
1305impl TemperatureUnit {
1306 pub fn name(self) -> &'static str {
1308 match self {
1309 TemperatureUnit::Celsius => "celsius",
1310 TemperatureUnit::Fahrenheit => "fahrenheit",
1311 }
1312 }
1313
1314 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#[derive(Debug, Clone, PartialEq, Eq)]
1325pub struct HttpRequest {
1326 pub method: String,
1328 pub url: String,
1330 pub headers: Vec<(String, String)>,
1332 pub body: HttpBody,
1334 pub follow_redirects: bool,
1336}
1337
1338impl HttpRequest {
1339 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 pub fn get(url: impl Into<String>) -> Self {
1353 Self::new("GET", url)
1354 }
1355
1356 pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
1358 Self::new("POST", url).body(body)
1359 }
1360
1361 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Default)]
1390pub enum HttpBody {
1391 #[default]
1393 Empty,
1394 Bytes(Vec<u8>),
1396 Stream,
1400}
1401
1402impl HttpBody {
1403 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
1415pub struct HttpHead {
1416 pub status: u16,
1418 pub status_text: String,
1420 pub url: String,
1422 pub redirected: bool,
1424 pub headers: Vec<(String, String)>,
1426}
1427
1428#[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#[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 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#[derive(Debug, Clone, PartialEq, Eq)]
1554pub enum FetchEvent {
1555 BodyWanted,
1558 Head(HttpHead),
1560 Data(Vec<u8>),
1562 End,
1564 Failed(String),
1566}
1567
1568#[derive(Debug, Clone, PartialEq, Eq)]
1571pub enum FetchOp {
1572 Start(HttpRequest),
1574 Send(Vec<u8>),
1576 Finish,
1578 Pause(bool),
1581 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 (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 (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 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 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 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 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 assert_eq!(regional(of("ja")), world);
1776 assert_eq!(of("en-CA").hour_cycle, HourCycle::H12);
1777 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 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 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 let singapore = || TimeZone::parse("Asia/Singapore");
1877 let zone = |tz: Option<&str>| TimeZone::posix(tz, singapore).as_str().to_owned();
1878 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 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 assert_eq!(zone(Some("")), "UTC");
1902 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 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}