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";
34
35pub const CONTEXT_MENU_COMPONENT: &str = "nsh/context-menu";
41
42pub const SPLIT_VIEW_COMPONENT: &str = "nsh/split-view";
46
47pub fn is_reserved_component(name: &str) -> bool {
51 name.starts_with("nsh/")
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub enum ColorScheme {
57 #[default]
59 Light,
60 Dark,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
67pub enum Appearance {
68 #[default]
70 System,
71 Light,
73 Dark,
75}
76
77impl Appearance {
78 pub fn resolve(self, system: ColorScheme) -> ColorScheme {
80 match self {
81 Appearance::System => system,
82 Appearance::Light => ColorScheme::Light,
83 Appearance::Dark => ColorScheme::Dark,
84 }
85 }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum InputModality {
93 Keyboard,
96 Pointer,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum Os {
103 Ios,
105 Android,
107 MacOs,
109 Windows,
111 Linux,
113 Web,
116}
117
118impl Os {
119 pub fn name(self) -> &'static str {
121 match self {
122 Os::Ios => "ios",
123 Os::Android => "android",
124 Os::MacOs => "macos",
125 Os::Windows => "windows",
126 Os::Linux => "linux",
127 Os::Web => "web",
128 }
129 }
130
131 pub(crate) fn from_name(name: &str) -> Option<Self> {
134 [
135 Os::Ios,
136 Os::Android,
137 Os::MacOs,
138 Os::Windows,
139 Os::Linux,
140 Os::Web,
141 ]
142 .into_iter()
143 .find(|os| os.name() == name)
144 }
145
146 pub fn is_desktop(self) -> bool {
152 matches!(self, Os::MacOs | Os::Windows | Os::Linux)
153 }
154
155 pub fn is_catalyst(self) -> bool {
160 self == Os::Ios && cfg!(target_abi = "macabi")
161 }
162}
163
164impl Default for Os {
165 fn default() -> Self {
168 if cfg!(target_os = "android") {
169 Os::Android
170 } else {
171 Os::Ios
172 }
173 }
174}
175
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
178pub enum Idiom {
179 #[default]
181 Phone,
182 Pad,
184 Mac,
187 Tv,
189 Desktop,
193 Terminal,
196}
197
198impl Idiom {
199 pub fn desktop_on(self, os: Os) -> bool {
206 os.is_desktop() || (os == Os::Web && self == Idiom::Desktop) || self == Idiom::Terminal
207 }
208
209 pub fn reported_on(self, os: Os) -> Idiom {
215 if self == Idiom::Terminal {
216 Idiom::Terminal
217 } else if self.desktop_on(os) {
218 Idiom::Desktop
219 } else if self == Idiom::Desktop {
220 Idiom::Phone
221 } else {
222 self
223 }
224 }
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
230pub enum Lifecycle {
231 #[default]
233 Active,
234 Inactive,
238 Background,
241}
242
243impl Lifecycle {
244 pub fn name(self) -> &'static str {
246 match self {
247 Lifecycle::Active => "active",
248 Lifecycle::Inactive => "inactive",
249 Lifecycle::Background => "background",
250 }
251 }
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
262#[non_exhaustive]
263pub struct Network {
264 pub kind: NetworkKind,
267 pub expensive: bool,
271 pub constrained: bool,
274 pub cellular_data: CellularData,
278}
279
280impl Network {
281 pub fn new(kind: NetworkKind) -> Self {
284 Self {
285 kind,
286 ..Self::default()
287 }
288 }
289
290 pub fn expensive(mut self, expensive: bool) -> Self {
292 self.expensive = expensive;
293 self
294 }
295
296 pub fn constrained(mut self, constrained: bool) -> Self {
298 self.constrained = constrained;
299 self
300 }
301
302 pub fn cellular_data(mut self, cellular_data: CellularData) -> Self {
304 self.cellular_data = cellular_data;
305 self
306 }
307
308 pub fn online(&self) -> bool {
312 self.kind != NetworkKind::None
313 }
314}
315
316#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
318#[non_exhaustive]
319pub enum NetworkKind {
320 #[default]
323 Unknown,
324 None,
326 Wifi,
328 Cellular,
330 Wired,
332 Other,
335}
336
337impl NetworkKind {
338 pub fn name(self) -> &'static str {
340 match self {
341 Self::Unknown => "unknown",
342 Self::None => "none",
343 Self::Wifi => "wifi",
344 Self::Cellular => "cellular",
345 Self::Wired => "wired",
346 Self::Other => "other",
347 }
348 }
349
350 pub fn parse(name: &str) -> Option<Self> {
352 Some(match name {
353 "unknown" => Self::Unknown,
354 "none" => Self::None,
355 "wifi" => Self::Wifi,
356 "cellular" => Self::Cellular,
357 "wired" => Self::Wired,
358 "other" => Self::Other,
359 _ => return None,
360 })
361 }
362}
363
364#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
367#[non_exhaustive]
368pub enum CellularData {
369 #[default]
373 Unknown,
374 Restricted,
378 NotRestricted,
380}
381
382impl CellularData {
383 pub fn name(self) -> &'static str {
385 match self {
386 Self::Unknown => "unknown",
387 Self::Restricted => "restricted",
388 Self::NotRestricted => "notRestricted",
389 }
390 }
391
392 pub fn parse(name: &str) -> Option<Self> {
394 Some(match name {
395 "unknown" => Self::Unknown,
396 "restricted" => Self::Restricted,
397 "notRestricted" => Self::NotRestricted,
398 _ => return None,
399 })
400 }
401}
402
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
405pub enum SizeClass {
406 Compact,
408 Regular,
410}
411
412impl SizeClass {
413 pub(crate) fn from_length(length: Points) -> Self {
416 if length < Points(600.0) {
417 Self::Compact
418 } else {
419 Self::Regular
420 }
421 }
422
423 pub fn name(self) -> &'static str {
425 match self {
426 Self::Compact => "compact",
427 Self::Regular => "regular",
428 }
429 }
430}
431
432#[derive(Debug, Clone, Copy, PartialEq)]
434pub struct Environment {
435 pub window: Size<Points>,
437 pub horizontal_size_class: Option<SizeClass>,
439 pub vertical_size_class: Option<SizeClass>,
441 pub safe_area: Edges<Points>,
443 pub title_bar: Edges<Points>,
449 pub window_state: Option<crate::desktop::WindowState>,
454 pub keyboard_height: Points,
456 pub keyboard_duration: f32,
458 pub color_scheme: ColorScheme,
460 pub font_scale: f32,
462 pub rtl: bool,
464 pub reduce_motion: bool,
467 pub pixel_ratio: f32,
469 pub screen_reader: bool,
471 pub reads_active_descendants: bool,
478 pub os: Os,
480 pub platform: Option<&'static str>,
486 pub os_version: (u16, u16),
489 pub idiom: Idiom,
491 pub apple_keyboard: bool,
496 pub ctrl_for_command: bool,
501 pub locale: Locale,
503 pub locale_settings: LocaleSettings,
506 pub host: bool,
509 pub lifecycle: Lifecycle,
513 pub wake_count: u32,
520 pub network: Network,
525 pub screen_color: bool,
529 pub clipboard_write_result: bool,
535 pub canvas_render: bool,
539 pub share: bool,
543 pub app_settings: bool,
549 pub auth_session: bool,
557 pub scheme_links: Option<bool>,
567 pub file_requests: bool,
572 pub notifications: bool,
576 pub audio: bool,
580 pub tab_bar: bool,
588 pub clipboard_images: Option<bool>,
596 pub cell: Option<Size<Points>>,
603 pub web_input: bool,
607 pub web_evaluate: bool,
610 pub web_views: bool,
617 pub webview_requests: bool,
623 pub shaders: bool,
631}
632
633impl Environment {
634 pub fn horizontal_size_class(&self) -> SizeClass {
636 self.horizontal_size_class
637 .unwrap_or_else(|| SizeClass::from_length(self.window.width))
638 }
639
640 pub fn vertical_size_class(&self) -> SizeClass {
642 self.vertical_size_class
643 .unwrap_or_else(|| SizeClass::from_length(self.window.height))
644 }
645
646 pub fn platform_name(&self) -> &'static str {
650 self.platform.unwrap_or(self.os.name())
651 }
652
653 pub fn desktop(&self) -> bool {
658 self.idiom.desktop_on(self.os)
659 }
660
661 pub fn reported_idiom(&self) -> Idiom {
663 self.idiom.reported_on(self.os)
664 }
665
666 pub fn scheme_links(&self) -> bool {
670 self.scheme_links.unwrap_or(self.os != Os::Web)
671 }
672}
673
674impl Default for Environment {
675 fn default() -> Self {
676 Self {
677 window: Size::default(),
678 horizontal_size_class: None,
679 vertical_size_class: None,
680 safe_area: Edges::default(),
681 title_bar: Edges::default(),
682 window_state: None,
683 keyboard_height: Points(0.0),
684 keyboard_duration: 250.0,
685 color_scheme: ColorScheme::Light,
686 font_scale: 1.0,
687 rtl: false,
688 reduce_motion: false,
689 pixel_ratio: 1.0,
690 screen_reader: false,
691 reads_active_descendants: false,
692 os: Os::default(),
693 platform: None,
694 os_version: (0, 0),
695 idiom: Idiom::Phone,
696 apple_keyboard: false,
697 ctrl_for_command: false,
698 locale: Locale::EN_US,
699 locale_settings: LocaleSettings::EN_US,
700 host: false,
701 lifecycle: Lifecycle::Active,
702 wake_count: 0,
703 network: Network::default(),
704 screen_color: false,
705 clipboard_write_result: false,
706 canvas_render: false,
707 share: false,
708 app_settings: false,
709 auth_session: false,
710 scheme_links: None,
711 file_requests: false,
712 notifications: false,
713 audio: false,
714 tab_bar: true,
715 clipboard_images: None,
716 cell: None,
717 web_input: false,
718 web_evaluate: false,
719 web_views: true,
720 webview_requests: false,
721 shaders: true,
722 }
723 }
724}
725
726#[derive(Debug, Clone, Copy, PartialEq, Default)]
733pub struct HostEnvironment {
734 pub locale: Option<Locale>,
736 pub font_scale: Option<f32>,
739}
740
741impl HostEnvironment {
742 pub fn apply(&self, env: &mut Environment) {
744 if let Some(locale) = self.locale {
745 env.locale = locale;
746 env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
747 }
748 if let Some(scale) = self.font_scale.filter(|s| s.is_finite() && *s > 0.0) {
749 env.font_scale = scale;
750 }
751 }
752}
753
754#[derive(Clone, Copy, PartialEq, Eq, Hash)]
758pub struct Locale {
759 bytes: [u8; Locale::CAPACITY],
760 len: u8,
761}
762
763impl Locale {
764 const CAPACITY: usize = 15;
765
766 pub const EN_US: Locale = Locale {
768 bytes: *b"en-US\0\0\0\0\0\0\0\0\0\0",
769 len: 5,
770 };
771
772 pub fn parse(identifier: &str) -> Option<Locale> {
777 let identifier = identifier.split(['@', '.']).next().unwrap_or_default();
778 let mut bytes = [0u8; Self::CAPACITY];
779 let mut len = 0;
780 for (i, part) in identifier.split(['-', '_']).enumerate() {
781 let keep = if i == 0 {
782 (2..=3).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphabetic())
783 } else {
784 (part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()))
786 || (part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()))
787 || (part.len() == 3 && part.bytes().all(|b| b.is_ascii_digit()))
788 };
789 if !keep {
790 if i == 0 {
791 return None;
792 }
793 break;
795 }
796 if len + part.len() + usize::from(i > 0) > Self::CAPACITY {
797 break;
798 }
799 if i > 0 {
800 bytes[len] = b'-';
801 len += 1;
802 }
803 for (j, b) in part.bytes().enumerate() {
804 bytes[len] = match (i, part.len()) {
805 (0, _) => b.to_ascii_lowercase(),
806 (_, 4) if j == 0 => b.to_ascii_uppercase(),
807 (_, 4) => b.to_ascii_lowercase(),
808 _ => b.to_ascii_uppercase(),
809 };
810 len += 1;
811 }
812 }
813 Some(Locale {
814 bytes,
815 len: len as u8,
816 })
817 }
818
819 pub fn as_str(&self) -> &str {
821 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
823 }
824
825 pub fn language(&self) -> &str {
827 self.as_str().split('-').next().unwrap_or_default()
828 }
829
830 pub fn region(&self) -> Option<&str> {
832 self.as_str().split('-').skip(1).find(|s| s.len() != 4)
834 }
835}
836
837impl Default for Locale {
838 fn default() -> Self {
839 Self::EN_US
840 }
841}
842
843impl std::fmt::Debug for Locale {
844 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
845 write!(f, "Locale({})", self.as_str())
846 }
847}
848
849impl std::fmt::Display for Locale {
850 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
851 f.write_str(self.as_str())
852 }
853}
854
855#[derive(Clone, Copy, PartialEq, Eq, Hash)]
859pub struct Languages {
860 tags: [Locale; Languages::CAPACITY],
861 len: u8,
862}
863
864impl Languages {
865 const CAPACITY: usize = 8;
868
869 pub(crate) const EN_US: Languages = Languages {
871 tags: [Locale::EN_US; Languages::CAPACITY],
872 len: 1,
873 };
874
875 #[doc(hidden)]
877 pub const fn one(locale: Locale) -> Languages {
878 Languages {
879 tags: [locale; Languages::CAPACITY],
880 len: 1,
881 }
882 }
883
884 #[doc(hidden)]
889 pub fn parse<'a>(identifiers: impl IntoIterator<Item = &'a str>) -> Option<Languages> {
890 let mut languages = Languages::EN_US;
891 languages.len = 0;
892 for locale in identifiers.into_iter().filter_map(Locale::parse) {
893 if usize::from(languages.len) == Self::CAPACITY {
894 break;
895 }
896 if !languages.as_slice().contains(&locale) {
897 languages.tags[usize::from(languages.len)] = locale;
898 languages.len += 1;
899 }
900 }
901 (languages.len > 0).then_some(languages)
902 }
903
904 pub fn preferring(&self, locale: Locale) -> Languages {
908 let mut languages = Languages::one(locale);
909 for &other in self.as_slice() {
910 if usize::from(languages.len) == Self::CAPACITY {
911 break;
912 }
913 if other != locale {
914 languages.tags[usize::from(languages.len)] = other;
915 languages.len += 1;
916 }
917 }
918 languages
919 }
920
921 pub fn first(&self) -> Locale {
923 self.tags[0]
924 }
925
926 pub fn as_slice(&self) -> &[Locale] {
928 &self.tags[..usize::from(self.len)]
929 }
930
931 pub fn iter(&self) -> impl Iterator<Item = Locale> + '_ {
933 self.as_slice().iter().copied()
934 }
935}
936
937impl Default for Languages {
938 fn default() -> Self {
939 Self::EN_US
940 }
941}
942
943impl std::fmt::Debug for Languages {
944 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
945 f.debug_list()
946 .entries(self.iter().map(|l| l.to_string()))
947 .finish()
948 }
949}
950
951#[derive(Clone, Copy, PartialEq, Eq, Hash)]
956#[non_exhaustive]
957pub struct TimeZone {
958 bytes: [u8; TimeZone::CAPACITY],
959 len: u8,
960}
961
962impl TimeZone {
963 const CAPACITY: usize = 63;
968
969 pub const UTC: TimeZone = {
971 let mut bytes = [0u8; TimeZone::CAPACITY];
972 bytes[0] = b'U';
973 bytes[1] = b'T';
974 bytes[2] = b'C';
975 TimeZone { bytes, len: 3 }
976 };
977
978 pub fn parse(identifier: &str) -> Option<TimeZone> {
985 let identifier = identifier.trim();
986 let name = match identifier.rsplit_once("zoneinfo/") {
987 Some((_, name)) => name,
988 None => identifier.strip_prefix(':').unwrap_or(identifier),
989 };
990 let valid = !name.is_empty()
991 && name.len() <= Self::CAPACITY
992 && name
993 .bytes()
994 .all(|b| b.is_ascii_alphanumeric() || b"/_-+:".contains(&b))
995 && name
996 .split('/')
997 .all(|part| !part.is_empty() && part != "." && part != "..");
998 if !valid {
999 return None;
1000 }
1001 let mut bytes = [0u8; Self::CAPACITY];
1002 bytes[..name.len()].copy_from_slice(name.as_bytes());
1003 Some(TimeZone {
1004 bytes,
1005 len: name.len() as u8,
1006 })
1007 }
1008
1009 #[doc(hidden)]
1024 pub fn posix(tz: Option<&str>, system: impl FnOnce() -> Option<TimeZone>) -> TimeZone {
1025 let zone = match tz.map(str::trim) {
1026 None => None,
1027 Some("") => Some(Self::UTC),
1029 Some(tz) => {
1030 let name = tz.strip_prefix(':').unwrap_or(tz);
1031 if is_posix_rule(name) && !RULE_NAMED_ZONES.contains(&name) {
1032 None
1033 } else {
1034 Self::parse(name)
1035 }
1036 }
1037 };
1038 zone.or_else(system).unwrap_or_default()
1039 }
1040
1041 pub fn as_str(&self) -> &str {
1043 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("UTC")
1045 }
1046}
1047
1048const RULE_NAMED_ZONES: [&str; 7] = [
1052 "EST5EDT", "CST6CDT", "MST7MDT", "PST8PDT", "GMT0", "GMT+0", "GMT-0",
1053];
1054
1055fn is_posix_rule(tz: &str) -> bool {
1061 let letters = tz.bytes().take_while(u8::is_ascii_alphabetic).count();
1062 tz.starts_with('<')
1063 || letters >= 3
1064 && tz
1065 .as_bytes()
1066 .get(letters)
1067 .is_some_and(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-'))
1068}
1069
1070impl Default for TimeZone {
1071 fn default() -> Self {
1072 Self::UTC
1073 }
1074}
1075
1076impl std::fmt::Debug for TimeZone {
1077 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1078 write!(f, "TimeZone({})", self.as_str())
1079 }
1080}
1081
1082impl std::fmt::Display for TimeZone {
1083 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1084 f.write_str(self.as_str())
1085 }
1086}
1087
1088#[non_exhaustive]
1092#[derive(Debug, Clone, Copy, PartialEq, Default, crate::element::JsObject)]
1093pub struct PerfStats {
1094 pub fps: f32,
1097 pub refresh_rate: Option<f32>,
1100 pub dropped: crate::geometry::Percentage,
1103}
1104
1105impl PerfStats {
1106 #[doc(hidden)]
1110 pub fn new(fps: f32) -> PerfStats {
1111 PerfStats {
1112 fps,
1113 ..PerfStats::default()
1114 }
1115 }
1116}
1117
1118#[derive(Debug, Clone, PartialEq, Eq, Default)]
1125#[non_exhaustive]
1126pub struct AppInfo {
1127 pub id: Option<String>,
1129 pub name: Option<String>,
1131 pub version: Option<String>,
1134 pub build: Option<u64>,
1137 pub development: bool,
1140}
1141
1142impl AppInfo {
1143 #[doc(hidden)]
1147 pub fn from_json(value: &crate::JsonValue) -> AppInfo {
1148 let text = |key: &str| value.get(key).and_then(|v| v.as_str()).map(str::to_owned);
1149 AppInfo {
1150 id: text("id"),
1151 name: text("name"),
1152 version: text("version"),
1153 build: value.get("build").and_then(|v| v.as_u64()),
1154 development: value
1155 .get("development")
1156 .and_then(|v| v.as_bool())
1157 .unwrap_or(false),
1158 }
1159 }
1160
1161 pub fn to_json(&self) -> crate::JsonValue {
1163 serde_json::json!({
1164 "id": self.id,
1165 "name": self.name,
1166 "version": self.version,
1167 "build": self.build,
1168 "development": self.development,
1169 })
1170 }
1171}
1172
1173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1182#[non_exhaustive]
1183pub struct LocaleSettings {
1184 pub languages: Languages,
1187 pub time_zone: TimeZone,
1189 pub hour_cycle: HourCycle,
1191 pub first_day_of_week: Weekday,
1193 pub measurement_system: MeasurementSystem,
1195 pub temperature_unit: TemperatureUnit,
1197}
1198
1199impl LocaleSettings {
1200 pub(crate) const EN_US: LocaleSettings = LocaleSettings {
1203 languages: Languages::EN_US,
1204 time_zone: TimeZone::UTC,
1205 hour_cycle: HourCycle::H12,
1206 first_day_of_week: Weekday::Sunday,
1207 measurement_system: MeasurementSystem::Us,
1208 temperature_unit: TemperatureUnit::Fahrenheit,
1209 };
1210
1211 #[doc(hidden)]
1216 pub fn of(locale: Locale) -> LocaleSettings {
1217 LocaleSettings {
1218 languages: Languages::one(locale),
1219 ..Self::of_region(locale.language(), locale.region().unwrap_or("001"))
1220 }
1221 }
1222
1223 #[doc(hidden)]
1233 pub fn parse(identifier: &str) -> LocaleSettings {
1234 let identifier = identifier.trim();
1235 let (tag, icu) = identifier.split_once('@').unwrap_or((identifier, ""));
1236 let mut keywords = Keywords::default();
1237 let mut extension = false;
1240 let mut key = "";
1241 for subtag in tag.split('.').next().unwrap_or_default().split(['-', '_']) {
1242 if subtag.len() == 1 {
1243 extension = subtag.eq_ignore_ascii_case("u");
1244 key = "";
1245 } else if extension && subtag.len() == 2 {
1246 key = subtag;
1247 } else if extension && !key.is_empty() {
1248 keywords.set(key, subtag);
1249 key = "";
1250 }
1251 }
1252 for keyword in icu.split(';') {
1253 if let Some((key, value)) = keyword.split_once('=') {
1254 keywords.set(key.trim(), value.trim());
1255 }
1256 }
1257 let locale = Locale::parse(identifier);
1258 let language = locale.as_ref().map_or("", Locale::language);
1259 let region = match &keywords.region {
1260 Some((bytes, len)) => std::str::from_utf8(&bytes[..*len]).unwrap_or("001"),
1261 None => locale.as_ref().and_then(Locale::region).unwrap_or("001"),
1262 };
1263 let own = Self::of_region(language, region);
1264 LocaleSettings {
1265 languages: Languages::one(locale.unwrap_or(Locale::EN_US)),
1266 hour_cycle: keywords.hour_cycle.unwrap_or(own.hour_cycle),
1267 first_day_of_week: keywords.first_day_of_week.unwrap_or(own.first_day_of_week),
1268 measurement_system: keywords
1269 .measurement_system
1270 .unwrap_or(own.measurement_system),
1271 temperature_unit: keywords.temperature_unit.unwrap_or(own.temperature_unit),
1272 ..own
1273 }
1274 }
1275
1276 fn of_region(language: &str, region: &str) -> LocaleSettings {
1278 let listed = |regions: &[&str]| regions.binary_search(®ion).is_ok();
1279 LocaleSettings {
1280 hour_cycle: match (language, region) {
1281 ("fr", "CA") | ("ku", "SY") => HourCycle::H23,
1283 ("ar" | "en", "001") => HourCycle::H12,
1284 _ if listed(HOUR12_REGIONS) => HourCycle::H12,
1285 _ => HourCycle::H23,
1286 },
1287 first_day_of_week: if listed(SUNDAY_REGIONS) {
1288 Weekday::Sunday
1289 } else if listed(SATURDAY_REGIONS) {
1290 Weekday::Saturday
1291 } else if listed(FRIDAY_REGIONS) {
1292 Weekday::Friday
1293 } else {
1294 Weekday::Monday
1295 },
1296 measurement_system: match region {
1297 "LR" | "US" => MeasurementSystem::Us,
1298 "GB" | "MM" => MeasurementSystem::Uk,
1299 _ => MeasurementSystem::Metric,
1300 },
1301 temperature_unit: match region {
1302 "BS" | "BZ" | "KY" | "PR" | "PW" | "US" => TemperatureUnit::Fahrenheit,
1303 _ => TemperatureUnit::Celsius,
1304 },
1305 ..Self::default()
1306 }
1307 }
1308}
1309
1310impl Default for LocaleSettings {
1311 fn default() -> Self {
1312 Self::EN_US
1313 }
1314}
1315
1316#[derive(Default)]
1318struct Keywords {
1319 hour_cycle: Option<HourCycle>,
1320 first_day_of_week: Option<Weekday>,
1321 measurement_system: Option<MeasurementSystem>,
1322 temperature_unit: Option<TemperatureUnit>,
1323 region: Option<([u8; 3], usize)>,
1325}
1326
1327impl Keywords {
1328 fn set(&mut self, key: &str, value: &str) {
1330 let is = |names: &[&str]| names.iter().any(|n| key.eq_ignore_ascii_case(n));
1331 let value_is = |name: &str| value.eq_ignore_ascii_case(name);
1332 if is(&["hc", "hours"]) {
1333 self.hour_cycle = HourCycle::parse(value).or(self.hour_cycle);
1334 } else if is(&["fw"]) {
1335 self.first_day_of_week = Weekday::ALL
1336 .into_iter()
1337 .find(|d| value_is(d.code()))
1338 .or(self.first_day_of_week);
1339 } else if is(&["ms", "measure"]) {
1340 self.measurement_system = match () {
1341 _ if value_is("metric") => Some(MeasurementSystem::Metric),
1342 _ if value_is("ussystem") => Some(MeasurementSystem::Us),
1343 _ if value_is("uksystem") => Some(MeasurementSystem::Uk),
1344 _ => self.measurement_system,
1345 };
1346 } else if is(&["mu"]) {
1347 let unit = match value_is("fahrenhe") {
1349 true => Some(TemperatureUnit::Fahrenheit),
1350 false => TemperatureUnit::parse(value),
1351 };
1352 self.temperature_unit = unit.or(self.temperature_unit);
1353 } else if is(&["rg"]) {
1354 let bytes = value.as_bytes();
1357 let len = match bytes {
1358 [a, b, c, ..] if [a, b, c].iter().all(|b| b.is_ascii_digit()) => 3,
1359 [a, b, ..] if a.is_ascii_alphabetic() && b.is_ascii_alphabetic() => 2,
1360 _ => return,
1361 };
1362 let mut region = [0u8; 3];
1363 for (to, from) in region.iter_mut().zip(bytes) {
1364 *to = from.to_ascii_uppercase();
1365 }
1366 self.region = Some((region, len));
1367 }
1368 }
1369}
1370
1371const HOUR12_REGIONS: &[&str] = &[
1373 "419", "AE", "AG", "AL", "AR", "AS", "AU", "BB", "BD", "BH", "BM", "BN", "BO", "BS", "BT",
1374 "CA", "CL", "CO", "CR", "CU", "CY", "DJ", "DM", "DO", "DZ", "EC", "EG", "EH", "ER", "ET", "FJ",
1375 "FM", "GD", "GH", "GM", "GR", "GT", "GU", "GY", "HK", "HN", "IN", "IQ", "JM", "JO", "KH", "KI",
1376 "KN", "KP", "KR", "KW", "KY", "LB", "LC", "LR", "LS", "LY", "MH", "MO", "MP", "MR", "MW", "MX",
1377 "MY", "NA", "NI", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PR", "PS", "PW", "PY", "QA", "SA",
1378 "SB", "SD", "SG", "SL", "SO", "SS", "SV", "SY", "SZ", "TC", "TD", "TN", "TO", "TT", "TW", "UM",
1379 "US", "UY", "VC", "VE", "VG", "VI", "VU", "WS", "YE", "ZM",
1380];
1381
1382const SUNDAY_REGIONS: &[&str] = &[
1384 "AG", "AS", "BD", "BR", "BS", "BT", "BW", "BZ", "CA", "CO", "DM", "DO", "ET", "GT", "GU", "HK",
1385 "HN", "ID", "IL", "IN", "IS", "JM", "JP", "KE", "KH", "KR", "LA", "MH", "MM", "MO", "MT", "MX",
1386 "MZ", "NI", "NP", "PA", "PE", "PH", "PK", "PR", "PT", "PY", "SA", "SG", "SV", "TH", "TT", "TW",
1387 "UM", "US", "VE", "VI", "WS", "YE", "ZA", "ZW",
1388];
1389
1390const SATURDAY_REGIONS: &[&str] = &[
1392 "AF", "BH", "DJ", "DZ", "EG", "IQ", "IR", "JO", "KW", "LY", "OM", "QA", "SD", "SY",
1393];
1394
1395const FRIDAY_REGIONS: &[&str] = &["MV"];
1397
1398#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1400pub enum HourCycle {
1401 H11,
1403 #[default]
1405 H12,
1406 H23,
1408 H24,
1410}
1411
1412impl HourCycle {
1413 pub fn name(self) -> &'static str {
1415 match self {
1416 HourCycle::H11 => "h11",
1417 HourCycle::H12 => "h12",
1418 HourCycle::H23 => "h23",
1419 HourCycle::H24 => "h24",
1420 }
1421 }
1422
1423 pub fn parse(name: &str) -> Option<HourCycle> {
1425 [
1426 HourCycle::H11,
1427 HourCycle::H12,
1428 HourCycle::H23,
1429 HourCycle::H24,
1430 ]
1431 .into_iter()
1432 .find(|c| name.eq_ignore_ascii_case(c.name()))
1433 }
1434
1435 #[doc(hidden)]
1440 pub fn of_pattern(pattern: &str) -> Option<HourCycle> {
1441 let mut quoted = false;
1442 pattern.chars().find_map(|c| match c {
1443 '\'' => {
1444 quoted = !quoted;
1445 None
1446 }
1447 _ if quoted => None,
1448 'h' => Some(HourCycle::H12),
1449 'H' => Some(HourCycle::H23),
1450 'K' => Some(HourCycle::H11),
1451 'k' => Some(HourCycle::H24),
1452 _ => None,
1453 })
1454 }
1455
1456 pub fn twelve_hour(self) -> bool {
1458 matches!(self, HourCycle::H11 | HourCycle::H12)
1459 }
1460}
1461
1462#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1464pub enum Weekday {
1465 Monday = 1,
1467 Tuesday,
1469 Wednesday,
1471 Thursday,
1473 Friday,
1475 Saturday,
1477 Sunday,
1479}
1480
1481impl Weekday {
1482 const ALL: [Weekday; 7] = [
1484 Weekday::Monday,
1485 Weekday::Tuesday,
1486 Weekday::Wednesday,
1487 Weekday::Thursday,
1488 Weekday::Friday,
1489 Weekday::Saturday,
1490 Weekday::Sunday,
1491 ];
1492
1493 pub fn number(self) -> u8 {
1496 self as u8
1497 }
1498
1499 pub fn from_number(number: u8) -> Option<Weekday> {
1501 Self::ALL.get(usize::from(number).checked_sub(1)?).copied()
1502 }
1503
1504 fn code(self) -> &'static str {
1506 match self {
1507 Weekday::Monday => "mon",
1508 Weekday::Tuesday => "tue",
1509 Weekday::Wednesday => "wed",
1510 Weekday::Thursday => "thu",
1511 Weekday::Friday => "fri",
1512 Weekday::Saturday => "sat",
1513 Weekday::Sunday => "sun",
1514 }
1515 }
1516}
1517
1518#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1520pub enum MeasurementSystem {
1521 #[default]
1523 Metric,
1524 Us,
1526 Uk,
1528}
1529
1530impl MeasurementSystem {
1531 pub fn name(self) -> &'static str {
1533 match self {
1534 MeasurementSystem::Metric => "metric",
1535 MeasurementSystem::Us => "us",
1536 MeasurementSystem::Uk => "uk",
1537 }
1538 }
1539
1540 pub fn parse(name: &str) -> Option<MeasurementSystem> {
1542 [
1543 MeasurementSystem::Metric,
1544 MeasurementSystem::Us,
1545 MeasurementSystem::Uk,
1546 ]
1547 .into_iter()
1548 .find(|s| name.eq_ignore_ascii_case(s.name()))
1549 }
1550}
1551
1552#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1554pub enum TemperatureUnit {
1555 #[default]
1557 Celsius,
1558 Fahrenheit,
1560}
1561
1562impl TemperatureUnit {
1563 pub fn name(self) -> &'static str {
1565 match self {
1566 TemperatureUnit::Celsius => "celsius",
1567 TemperatureUnit::Fahrenheit => "fahrenheit",
1568 }
1569 }
1570
1571 pub fn parse(name: &str) -> Option<TemperatureUnit> {
1573 [TemperatureUnit::Celsius, TemperatureUnit::Fahrenheit]
1574 .into_iter()
1575 .find(|u| name.eq_ignore_ascii_case(u.name()))
1576 }
1577}
1578
1579#[derive(Debug, Clone, PartialEq, Eq)]
1582pub struct HttpRequest {
1583 pub method: String,
1585 pub url: String,
1587 pub headers: Vec<(String, String)>,
1589 pub body: HttpBody,
1591 pub follow_redirects: bool,
1593 pub cache: HttpCache,
1596}
1597
1598#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
1606pub enum HttpCache {
1607 #[default]
1610 Default,
1611 NoStore,
1613 Reload,
1615 NoCache,
1617 ForceCache,
1620 OnlyIfCached,
1622}
1623
1624impl HttpCache {
1625 pub fn as_str(self) -> &'static str {
1627 match self {
1628 Self::Default => "default",
1629 Self::NoStore => "no-store",
1630 Self::Reload => "reload",
1631 Self::NoCache => "no-cache",
1632 Self::ForceCache => "force-cache",
1633 Self::OnlyIfCached => "only-if-cached",
1634 }
1635 }
1636
1637 pub fn parse(name: &str) -> Option<Self> {
1639 Some(match name {
1640 "default" => Self::Default,
1641 "no-store" => Self::NoStore,
1642 "reload" => Self::Reload,
1643 "no-cache" => Self::NoCache,
1644 "force-cache" => Self::ForceCache,
1645 "only-if-cached" => Self::OnlyIfCached,
1646 _ => return None,
1647 })
1648 }
1649}
1650
1651impl HttpRequest {
1652 pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
1655 Self {
1656 method: method.into().to_ascii_uppercase(),
1657 url: url.into(),
1658 headers: Vec::new(),
1659 body: HttpBody::Empty,
1660 follow_redirects: true,
1661 cache: HttpCache::Default,
1662 }
1663 }
1664
1665 pub fn get(url: impl Into<String>) -> Self {
1667 Self::new("GET", url)
1668 }
1669
1670 pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
1672 Self::new("POST", url).body(body)
1673 }
1674
1675 #[must_use]
1677 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1678 self.headers.push((name.into(), value.into()));
1679 self
1680 }
1681
1682 #[must_use]
1684 pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
1685 self.body = HttpBody::Bytes(body.into());
1686 self
1687 }
1688
1689 #[must_use]
1691 pub fn cache(mut self, cache: HttpCache) -> Self {
1692 self.cache = cache;
1693 self
1694 }
1695}
1696
1697impl From<&str> for HttpRequest {
1698 fn from(url: &str) -> Self {
1699 Self::get(url)
1700 }
1701}
1702
1703impl From<String> for HttpRequest {
1704 fn from(url: String) -> Self {
1705 Self::get(url)
1706 }
1707}
1708
1709#[derive(Debug, Clone, PartialEq, Eq, Default)]
1711pub enum HttpBody {
1712 #[default]
1714 Empty,
1715 Bytes(Vec<u8>),
1717 Stream,
1721}
1722
1723impl HttpBody {
1724 pub fn is_empty(&self) -> bool {
1726 match self {
1727 HttpBody::Empty => true,
1728 HttpBody::Bytes(b) => b.is_empty(),
1729 HttpBody::Stream => false,
1730 }
1731 }
1732}
1733
1734#[derive(Debug, Clone, PartialEq, Eq, Default)]
1736pub struct HttpHead {
1737 pub status: u16,
1739 pub status_text: String,
1741 pub url: String,
1743 pub redirected: bool,
1745 pub headers: Vec<(String, String)>,
1747}
1748
1749#[doc(hidden)]
1756pub fn content_type(path: &str) -> &'static str {
1757 match std::path::Path::new(path)
1758 .extension()
1759 .and_then(|e| e.to_str())
1760 .map(str::to_ascii_lowercase)
1761 .as_deref()
1762 {
1763 Some("html") => "text/html; charset=utf-8",
1764 Some("js" | "mjs") => "text/javascript; charset=utf-8",
1765 Some("json" | "map") => "application/json",
1766 Some("webmanifest") => "application/manifest+json",
1767 Some("wasm") => "application/wasm",
1768 Some("css") => "text/css; charset=utf-8",
1769 Some("txt") => "text/plain; charset=utf-8",
1770 Some("png") => "image/png",
1771 Some("jpg" | "jpeg") => "image/jpeg",
1772 Some("gif") => "image/gif",
1773 Some("webp") => "image/webp",
1774 Some("avif") => "image/avif",
1775 Some("svg") => "image/svg+xml",
1776 Some("ico") => "image/x-icon",
1777 Some("heic") => "image/heic",
1778 Some("ttf") => "font/ttf",
1779 Some("otf") => "font/otf",
1780 Some("woff") => "font/woff",
1781 Some("woff2") => "font/woff2",
1782 Some("mp4" | "m4v") => "video/mp4",
1783 Some("webm") => "video/webm",
1784 Some("mov") => "video/quicktime",
1785 Some("mp3") => "audio/mpeg",
1786 Some("m4a") => "audio/mp4",
1787 Some("aac") => "audio/aac",
1788 Some("wav") => "audio/wav",
1789 Some("ogg" | "oga" | "opus") => "audio/ogg",
1790 Some("flac") => "audio/flac",
1791 Some("aif" | "aiff") => "audio/aiff",
1792 Some("caf") => "audio/x-caf",
1793 _ => "application/octet-stream",
1794 }
1795}
1796
1797#[doc(hidden)]
1804pub fn file_mime_type(uri: &str) -> &'static str {
1805 let path = uri.split(['?', '#']).next().unwrap_or_default();
1806 let name = path.rsplit('/').next().unwrap_or_default();
1807 let Some((stem, ext)) = name.rsplit_once('.') else {
1808 return "";
1809 };
1810 if stem.is_empty() {
1811 return "";
1813 }
1814 match ext.to_ascii_lowercase().as_str() {
1815 "png" => "image/png",
1816 "jpg" | "jpeg" | "jpe" => "image/jpeg",
1817 "gif" => "image/gif",
1818 "webp" => "image/webp",
1819 "avif" => "image/avif",
1820 "heic" => "image/heic",
1821 "heif" => "image/heif",
1822 "svg" => "image/svg+xml",
1823 "bmp" => "image/bmp",
1824 "tif" | "tiff" => "image/tiff",
1825 "ico" => "image/x-icon",
1826 "mp4" | "m4v" => "video/mp4",
1827 "mov" => "video/quicktime",
1828 "webm" => "video/webm",
1829 "mkv" => "video/x-matroska",
1830 "avi" => "video/x-msvideo",
1831 "mp3" => "audio/mpeg",
1832 "m4a" => "audio/mp4",
1833 "aac" => "audio/aac",
1834 "wav" => "audio/wav",
1835 "ogg" | "oga" | "opus" => "audio/ogg",
1836 "flac" => "audio/flac",
1837 "aif" | "aiff" => "audio/aiff",
1838 "caf" => "audio/x-caf",
1839 "txt" | "text" | "log" => "text/plain",
1840 "md" | "markdown" => "text/markdown",
1841 "csv" => "text/csv",
1842 "tsv" => "text/tab-separated-values",
1843 "html" | "htm" => "text/html",
1844 "css" => "text/css",
1845 "js" | "mjs" => "text/javascript",
1846 "json" => "application/json",
1847 "xml" => "application/xml",
1848 "yaml" | "yml" => "application/yaml",
1849 "pdf" => "application/pdf",
1850 "rtf" => "application/rtf",
1851 "doc" => "application/msword",
1852 "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1853 "xls" => "application/vnd.ms-excel",
1854 "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1855 "ppt" => "application/vnd.ms-powerpoint",
1856 "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1857 "zip" => "application/zip",
1858 "gz" | "tgz" => "application/gzip",
1859 "tar" => "application/x-tar",
1860 "7z" => "application/x-7z-compressed",
1861 "rar" => "application/vnd.rar",
1862 "wasm" => "application/wasm",
1863 "ttf" => "font/ttf",
1864 "otf" => "font/otf",
1865 "woff" => "font/woff",
1866 "woff2" => "font/woff2",
1867 _ => "",
1868 }
1869}
1870
1871#[derive(Debug, Clone, PartialEq, Eq)]
1875pub enum FetchEvent {
1876 BodyWanted,
1879 Head(HttpHead),
1881 Data(Vec<u8>),
1883 End,
1885 Failed(String),
1887}
1888
1889#[derive(Debug, Clone, PartialEq, Eq)]
1892pub enum FetchOp {
1893 Start(HttpRequest),
1895 Send(Vec<u8>),
1897 Finish,
1899 Pause(bool),
1902 Cancel,
1904}
1905
1906#[cfg(test)]
1907mod tests {
1908 #[test]
1909 fn app_info_reads_and_writes_app_infos_json() {
1910 use super::AppInfo;
1911 let json = serde_json::json!({
1912 "id": "com.example.orders",
1913 "name": "Orders",
1914 "version": "2.1.0",
1915 "build": 7,
1916 "development": true,
1917 "store": "play",
1918 });
1919 let info = AppInfo::from_json(&json);
1920 assert_eq!(info.id.as_deref(), Some("com.example.orders"));
1921 assert_eq!(info.name.as_deref(), Some("Orders"));
1922 assert_eq!(info.version.as_deref(), Some("2.1.0"));
1923 assert_eq!(info.build, Some(7));
1924 assert!(info.development);
1925 assert_eq!(AppInfo::from_json(&info.to_json()), info);
1926 let partial = AppInfo::from_json(&serde_json::json!({
1928 "id": null,
1929 "version": 2,
1930 "build": "7",
1931 }));
1932 assert_eq!(partial, AppInfo::default());
1933 assert_eq!(
1934 AppInfo::default().to_json(),
1935 serde_json::json!({
1936 "id": null, "name": null, "version": null, "build": null, "development": false,
1937 })
1938 );
1939 }
1940
1941 #[test]
1942 fn scheme_links_follow_the_os_unless_the_platform_says() {
1943 use super::{Environment, Os};
1944 let on = |os: Os, scheme_links: Option<bool>| {
1945 Environment {
1946 os,
1947 scheme_links,
1948 ..Environment::default()
1949 }
1950 .scheme_links()
1951 };
1952 for os in [Os::Ios, Os::Android, Os::MacOs, Os::Windows, Os::Linux] {
1953 assert!(on(os, None), "{os:?}");
1954 assert!(on(os, Some(true)), "{os:?}");
1955 assert!(!on(os, Some(false)), "{os:?}");
1956 }
1957 assert!(!on(Os::Web, None));
1958 assert!(on(Os::Web, Some(true)));
1959 assert!(!on(Os::Web, Some(false)));
1960 }
1961
1962 #[test]
1963 fn size_class_fallback_uses_points_and_native_traits_win() {
1964 use super::{Environment, SizeClass};
1965 use crate::geometry::size_pt;
1966 for (dimension, expected) in [
1967 (0.0, SizeClass::Compact),
1968 (599.5, SizeClass::Compact),
1969 (600.0, SizeClass::Regular),
1970 (1200.0, SizeClass::Regular),
1971 ] {
1972 let env = Environment {
1973 window: size_pt(dimension, dimension),
1974 ..Default::default()
1975 };
1976 assert_eq!(env.horizontal_size_class(), expected);
1977 assert_eq!(env.vertical_size_class(), expected);
1978 }
1979 let env = Environment {
1980 window: size_pt(900.0, 300.0),
1981 horizontal_size_class: Some(SizeClass::Compact),
1982 vertical_size_class: Some(SizeClass::Regular),
1983 ..Default::default()
1984 };
1985 assert_eq!(env.horizontal_size_class(), SizeClass::Compact);
1986 assert_eq!(env.vertical_size_class(), SizeClass::Regular);
1987 }
1988
1989 use super::{
1990 Environment, HostEnvironment, HourCycle, Idiom, Languages, Locale, LocaleSettings,
1991 MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday, content_type, file_mime_type,
1992 };
1993
1994 #[test]
1995 fn desktop_is_a_desktop_os_or_a_desktop_browser() {
1996 let desktop = |os: Os, idiom: Idiom| Environment {
1997 os,
1998 idiom,
1999 ..Environment::default()
2000 };
2001 for (os, idiom, expected) in [
2002 (Os::MacOs, Idiom::Desktop, true),
2003 (Os::Windows, Idiom::Desktop, true),
2004 (Os::Linux, Idiom::Desktop, true),
2005 (Os::Linux, Idiom::Phone, true),
2007 (Os::Web, Idiom::Desktop, true),
2008 (Os::Web, Idiom::Pad, false),
2009 (Os::Web, Idiom::Phone, false),
2010 (Os::Ios, Idiom::Phone, false),
2011 (Os::Ios, Idiom::Pad, false),
2012 (Os::Ios, Idiom::Mac, false),
2014 (Os::Ios, Idiom::Desktop, false),
2015 (Os::Android, Idiom::Tv, false),
2016 ] {
2017 let env = desktop(os, idiom);
2018 assert_eq!(env.desktop(), expected, "{os:?} {idiom:?}");
2019 assert_eq!(
2021 env.reported_idiom() == Idiom::Desktop,
2022 expected,
2023 "{os:?} {idiom:?}"
2024 );
2025 }
2026 assert_eq!(desktop(Os::Ios, Idiom::Mac).reported_idiom(), Idiom::Mac);
2027 assert_eq!(
2028 desktop(Os::Ios, Idiom::Desktop).reported_idiom(),
2029 Idiom::Phone
2030 );
2031 assert!(!Os::MacOs.is_catalyst() && !Os::Web.is_catalyst());
2032 assert_eq!(Os::Ios.is_catalyst(), cfg!(target_abi = "macabi"));
2033 }
2034
2035 #[test]
2036 fn desktop_behavior_applies_in_the_terminal_idiom_on_any_os() {
2037 for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Web] {
2038 assert!(Idiom::Terminal.desktop_on(os), "{os:?}");
2039 assert_eq!(Idiom::Terminal.reported_on(os), Idiom::Terminal, "{os:?}");
2040 }
2041 }
2042
2043 #[test]
2044 fn a_host_environment_replaces_what_it_sets() {
2045 let mut env = Environment {
2046 font_scale: 1.25,
2047 ..Environment::default()
2048 };
2049 HostEnvironment::default().apply(&mut env);
2050 assert_eq!((env.locale, env.font_scale), (Locale::EN_US, 1.25));
2051 let zh = Locale::parse("zh-Hans-CN").unwrap();
2052 HostEnvironment {
2053 locale: Some(zh),
2054 font_scale: Some(f32::NAN),
2055 }
2056 .apply(&mut env);
2057 assert_eq!((env.locale, env.font_scale), (zh, 1.25));
2058 HostEnvironment {
2059 locale: None,
2060 font_scale: Some(1.5),
2061 }
2062 .apply(&mut env);
2063 assert_eq!((env.locale, env.font_scale), (zh, 1.5));
2064 }
2065
2066 #[test]
2067 fn languages_parse_platform_identifiers_and_an_embedding_app_goes_first() {
2068 let tags = |l: Languages| l.iter().map(|l| l.to_string()).collect::<Vec<_>>();
2069 let system = Languages::parse(["de_DE", "C", "en-US", "de-DE", "fr"]).unwrap();
2070 assert_eq!(tags(system), ["de-DE", "en-US", "fr"]);
2071 assert_eq!(system.first().as_str(), "de-DE");
2072 assert_eq!(Languages::parse(["C", ""]), None);
2073 let many: Vec<String> = (0..20)
2074 .map(|i| format!("x{}", (b'a' + i) as char))
2075 .collect();
2076 let many = Languages::parse(many.iter().map(String::as_str)).unwrap();
2077 assert_eq!(many.as_slice().len(), Languages::CAPACITY);
2078 let fr = Locale::parse("fr").unwrap();
2079 assert_eq!(tags(system.preferring(fr)), ["fr", "de-DE", "en-US"]);
2080 let ja = Locale::parse("ja-JP").unwrap();
2081 assert_eq!(
2082 tags(system.preferring(ja)),
2083 ["ja-JP", "de-DE", "en-US", "fr"]
2084 );
2085 assert_eq!(tags(Languages::default()), ["en-US"]);
2086 let mut env = Environment::default();
2088 env.locale_settings.languages = system;
2089 HostEnvironment {
2090 locale: Some(ja),
2091 font_scale: None,
2092 }
2093 .apply(&mut env);
2094 assert_eq!(
2095 tags(env.locale_settings.languages),
2096 ["ja-JP", "de-DE", "en-US", "fr"]
2097 );
2098 }
2099
2100 #[test]
2101 fn locales_parse_platform_identifiers() {
2102 let tag = |s: &str| Locale::parse(s).map(|l| l.as_str().to_owned());
2103 assert_eq!(tag("en_US").as_deref(), Some("en-US"));
2104 assert_eq!(tag("zh-hans_cn").as_deref(), Some("zh-Hans-CN"));
2105 assert_eq!(tag("de_DE@calendar=gregorian").as_deref(), Some("de-DE"));
2106 assert_eq!(tag("pt_BR.UTF-8").as_deref(), Some("pt-BR"));
2107 assert_eq!(tag("es-419").as_deref(), Some("es-419"));
2108 assert_eq!(tag("en-US-u-hc-h23").as_deref(), Some("en-US"));
2109 assert_eq!(tag("C"), None);
2110 assert_eq!(Locale::default().as_str(), "en-US");
2111 let zh = Locale::parse("zh-Hans-CN").unwrap();
2112 assert_eq!((zh.language(), zh.region()), ("zh", Some("CN")));
2113 assert_eq!(Locale::parse("zh-Hans").unwrap().region(), None);
2114 assert_eq!(Locale::parse("es-419").unwrap().region(), Some("419"));
2115 }
2116
2117 #[test]
2118 fn regional_preferences_are_the_regions_unless_the_locale_sets_others() {
2119 type Regional = (HourCycle, Weekday, MeasurementSystem, TemperatureUnit);
2121 let regional = |s: LocaleSettings| -> Regional {
2122 (
2123 s.hour_cycle,
2124 s.first_day_of_week,
2125 s.measurement_system,
2126 s.temperature_unit,
2127 )
2128 };
2129 let of = |tag: &str| LocaleSettings::of(Locale::parse(tag).unwrap());
2130 let us = regional(LocaleSettings::default());
2131 let world = (
2132 HourCycle::H23,
2133 Weekday::Monday,
2134 MeasurementSystem::Metric,
2135 TemperatureUnit::Celsius,
2136 );
2137 assert_eq!(regional(of("en-US")), us);
2138 assert_eq!(
2139 LocaleSettings::default().languages.as_slice(),
2140 &[Locale::EN_US]
2141 );
2142 assert_eq!(LocaleSettings::default().time_zone, TimeZone::UTC);
2143 assert_eq!(
2145 of("de-DE").languages.as_slice(),
2146 &[Locale::parse("de-DE").unwrap()]
2147 );
2148 assert_eq!(regional(of("de-DE")), world);
2149 assert_eq!(regional(of("ja")), world);
2151 assert_eq!(of("en-CA").hour_cycle, HourCycle::H12);
2152 assert_eq!(of("fr-CA").hour_cycle, HourCycle::H23);
2154 assert_eq!(of("fr-CA").first_day_of_week, Weekday::Sunday);
2155 assert_eq!(of("en-001").hour_cycle, HourCycle::H12);
2156 assert_eq!(of("es-419").hour_cycle, HourCycle::H12);
2157 assert_eq!(of("ar-EG").first_day_of_week, Weekday::Saturday);
2158 assert_eq!(of("dv-MV").first_day_of_week, Weekday::Friday);
2159 let gb = of("en-GB");
2160 assert_eq!(gb.measurement_system, MeasurementSystem::Uk);
2161 assert_eq!(gb.temperature_unit, TemperatureUnit::Celsius);
2162 assert_eq!(of("en-LR").temperature_unit, TemperatureUnit::Celsius);
2163 assert_eq!(of("es-PR").temperature_unit, TemperatureUnit::Fahrenheit);
2164
2165 let parse = |identifier: &str| regional(LocaleSettings::parse(identifier));
2166 assert_eq!(
2167 parse("en-US-u-fw-mon-mu-celsius"),
2168 (
2169 HourCycle::H12,
2170 Weekday::Monday,
2171 MeasurementSystem::Us,
2172 TemperatureUnit::Celsius
2173 )
2174 );
2175 assert_eq!(
2176 parse("en_US@hours=h23;measure=metric"),
2177 (
2178 HourCycle::H23,
2179 Weekday::Sunday,
2180 MeasurementSystem::Metric,
2181 TemperatureUnit::Fahrenheit
2182 )
2183 );
2184 assert_eq!(parse("en_US@rg=gbzzzz"), regional(gb));
2185 assert_eq!(
2186 parse("ar-u-ca-islamic-umalqura-hc-h11-rg-uszzzz"),
2187 (HourCycle::H11, us.1, us.2, us.3)
2188 );
2189 assert_eq!(
2190 LocaleSettings::parse("en-GB-u-ms-ussystem-mu-fahrenhe").measurement_system,
2191 MeasurementSystem::Us
2192 );
2193 assert_eq!(parse("de_DE.UTF-8@fw=xyz;hours=h99;rg=1"), world);
2195 assert_eq!(parse("en-US-x-hc-h23"), us);
2196 assert_eq!(parse("C"), world);
2197 assert_eq!(
2199 LocaleSettings::parse("de_DE.UTF-8").languages.as_slice(),
2200 &[Locale::parse("de-DE").unwrap()]
2201 );
2202 assert_eq!(
2203 LocaleSettings::parse("C").languages.as_slice(),
2204 &[Locale::EN_US]
2205 );
2206 assert_eq!(Weekday::from_number(7), Some(Weekday::Sunday));
2207 assert_eq!(Weekday::from_number(0), None);
2208 assert_eq!(Weekday::Monday.number(), 1);
2209 assert!(HourCycle::H11.twelve_hour() && !HourCycle::H24.twelve_hour());
2210 assert_eq!(HourCycle::of_pattern("h:mm a"), Some(HourCycle::H12));
2211 assert_eq!(HourCycle::of_pattern("HH 'Uhr'"), Some(HourCycle::H23));
2212 assert_eq!(HourCycle::of_pattern("'h' K:mm"), Some(HourCycle::H11));
2213 assert_eq!(HourCycle::of_pattern("mm:ss"), None);
2214 }
2215
2216 #[test]
2217 fn time_zones_parse_platform_identifiers() {
2218 let zone = |s: &str| TimeZone::parse(s).map(|z| z.as_str().to_owned());
2219 assert_eq!(zone("Europe/Berlin").as_deref(), Some("Europe/Berlin"));
2220 assert_eq!(zone(":Asia/Tokyo").as_deref(), Some("Asia/Tokyo"));
2221 assert_eq!(
2222 zone("/var/db/timezone/zoneinfo/America/Argentina/Buenos_Aires").as_deref(),
2223 Some("America/Argentina/Buenos_Aires")
2224 );
2225 assert_eq!(
2226 zone("/usr/share/zoneinfo/Etc/GMT+5").as_deref(),
2227 Some("Etc/GMT+5")
2228 );
2229 assert_eq!(zone("GMT+01:00").as_deref(), Some("GMT+01:00"));
2230 assert_eq!(
2231 zone("America/Argentina/ComodRivadavia").as_deref(),
2232 Some("America/Argentina/ComodRivadavia")
2233 );
2234 assert_eq!(zone(""), None);
2235 assert_eq!(zone("Europe//Berlin"), None);
2236 assert_eq!(zone("../etc/passwd"), None);
2237 assert_eq!(zone("Central European Standard Time"), None);
2238 let parts = ["Abcdefghijklmn"; 4].join("/");
2239 assert_eq!(zone(&parts).as_deref(), Some(parts.as_str()));
2240 assert_eq!(zone(&"A".repeat(64)), None);
2241 assert_eq!(TimeZone::default().as_str(), "UTC");
2242 assert_eq!(
2243 Environment::default().locale_settings.time_zone,
2244 TimeZone::UTC
2245 );
2246 }
2247
2248 #[test]
2249 fn posix_time_zones_follow_the_zone_tz_names() {
2250 let singapore = || TimeZone::parse("Asia/Singapore");
2252 let zone = |tz: Option<&str>| TimeZone::posix(tz, singapore).as_str().to_owned();
2253 assert_eq!(zone(Some("GMT")), "GMT");
2255 assert_eq!(
2256 TimeZone::posix(Some("GMT"), || unreachable!("TZ names the zone")).as_str(),
2257 "GMT"
2258 );
2259 for name in [
2261 "UTC",
2262 "EST",
2263 "Japan",
2264 "NZ-CHAT",
2265 "Etc/GMT+5",
2266 "Europe/Berlin",
2267 "EST5EDT",
2268 "GMT0",
2269 "GMT-0",
2270 ] {
2271 assert_eq!(zone(Some(name)), name);
2272 assert_eq!(zone(Some(&format!(":{name}"))), name);
2273 }
2274 assert_eq!(zone(Some(":/usr/share/zoneinfo/Asia/Tokyo")), "Asia/Tokyo");
2275 assert_eq!(zone(Some("")), "UTC");
2277 for tz in [
2279 "JST-9",
2280 "EST5",
2281 "CET-1CEST",
2282 "<+08>-8",
2283 "CET-1CEST,M3.5.0,M10.5.0/3",
2284 "GMT+01:00",
2285 ":/etc/localtime",
2286 ":",
2287 ] {
2288 assert_eq!(zone(Some(tz)), "Asia/Singapore", "TZ={tz}");
2289 }
2290 assert_eq!(zone(None), "Asia/Singapore");
2291 assert_eq!(TimeZone::posix(None, || None), TimeZone::UTC);
2292 }
2293
2294 #[test]
2295 fn content_types_follow_the_extension_of_paths_and_asset_urls() {
2296 assert_eq!(
2297 content_type("dist/app.js"),
2298 "text/javascript; charset=utf-8"
2299 );
2300 assert_eq!(content_type("nsh.WASM"), "application/wasm");
2301 assert_eq!(
2302 content_type("asset:/@app/locales/en.json"),
2303 "application/json"
2304 );
2305 assert_eq!(content_type("asset:/images/flag@2x.png"), "image/png");
2306 assert_eq!(content_type("asset:/fonts/Inter.woff2"), "font/woff2");
2307 assert_eq!(content_type("asset:/sounds/chime.OGG"), "audio/ogg");
2308 for unknown in ["asset:/data.bin", "asset:/README", "asset:/.png"] {
2309 assert_eq!(
2310 content_type(unknown),
2311 "application/octet-stream",
2312 "{unknown}"
2313 );
2314 }
2315 }
2316
2317 #[test]
2318 fn file_mime_types_come_from_the_name_alone() {
2319 assert_eq!(file_mime_type("file:///tmp/a%20b.PNG"), "image/png");
2320 assert_eq!(file_mime_type("file:///tmp/%E4%B8%AD.jpeg"), "image/jpeg");
2321 assert_eq!(file_mime_type("/Users/me/Report.pdf"), "application/pdf");
2322 assert_eq!(
2323 file_mime_type("file:///tmp/notes.md?x=1#y"),
2324 "text/markdown"
2325 );
2326 assert_eq!(file_mime_type("C:/Users/me/Clip.mov"), "video/quicktime");
2327 for none in [
2329 "file:///tmp/photos.d/",
2330 "file:///tmp/README",
2331 "file:///tmp/.env",
2332 "file:///tmp/a.unknownext",
2333 "",
2334 ] {
2335 assert_eq!(file_mime_type(none), "", "{none}");
2336 }
2337 }
2338}