1pub mod clipboard;
6pub mod web_evaluation;
7
8use crate::geometry::{Bounds, Edges, Points, Size};
9
10pub const TAB_BAR_COMPONENT: &str = "nsh/tab-bar";
14
15pub const MENU_BUTTON_COMPONENT: &str = "nsh/menu-button";
20
21pub const CONTEXT_MENU_COMPONENT: &str = "nsh/context-menu";
27
28pub const SPLIT_VIEW_COMPONENT: &str = "nsh/split-view";
32
33pub fn is_reserved_component(name: &str) -> bool {
37 name.starts_with("nsh/")
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum ColorScheme {
43 #[default]
45 Light,
46 Dark,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
53pub enum Appearance {
54 #[default]
56 System,
57 Light,
59 Dark,
61}
62
63impl Appearance {
64 pub fn resolve(self, system: ColorScheme) -> ColorScheme {
66 match self {
67 Appearance::System => system,
68 Appearance::Light => ColorScheme::Light,
69 Appearance::Dark => ColorScheme::Dark,
70 }
71 }
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum InputModality {
79 Keyboard,
82 Pointer,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum Os {
89 Ios,
91 Android,
93 MacOs,
95 Windows,
97 Linux,
99 Web,
102}
103
104impl Os {
105 pub fn name(self) -> &'static str {
107 match self {
108 Os::Ios => "ios",
109 Os::Android => "android",
110 Os::MacOs => "macos",
111 Os::Windows => "windows",
112 Os::Linux => "linux",
113 Os::Web => "web",
114 }
115 }
116
117 pub(crate) fn from_name(name: &str) -> Option<Self> {
120 [
121 Os::Ios,
122 Os::Android,
123 Os::MacOs,
124 Os::Windows,
125 Os::Linux,
126 Os::Web,
127 ]
128 .into_iter()
129 .find(|os| os.name() == name)
130 }
131
132 pub fn is_desktop(self) -> bool {
138 matches!(self, Os::MacOs | Os::Windows | Os::Linux)
139 }
140
141 pub fn is_catalyst(self) -> bool {
146 self == Os::Ios && cfg!(target_abi = "macabi")
147 }
148}
149
150impl Default for Os {
151 fn default() -> Self {
154 if cfg!(target_os = "android") {
155 Os::Android
156 } else {
157 Os::Ios
158 }
159 }
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
164pub enum Idiom {
165 #[default]
167 Phone,
168 Pad,
170 Mac,
173 Tv,
175 Desktop,
179 Terminal,
182}
183
184impl Idiom {
185 pub fn desktop_on(self, os: Os) -> bool {
192 os.is_desktop() || (os == Os::Web && self == Idiom::Desktop) || self == Idiom::Terminal
193 }
194
195 pub fn reported_on(self, os: Os) -> Idiom {
201 if self == Idiom::Terminal {
202 Idiom::Terminal
203 } else if self.desktop_on(os) {
204 Idiom::Desktop
205 } else if self == Idiom::Desktop {
206 Idiom::Phone
207 } else {
208 self
209 }
210 }
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
216pub enum Lifecycle {
217 #[default]
219 Active,
220 Inactive,
224 Background,
227}
228
229impl Lifecycle {
230 pub fn name(self) -> &'static str {
232 match self {
233 Lifecycle::Active => "active",
234 Lifecycle::Inactive => "inactive",
235 Lifecycle::Background => "background",
236 }
237 }
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
248#[non_exhaustive]
249pub struct Network {
250 pub kind: NetworkKind,
253 pub expensive: bool,
257 pub constrained: bool,
260 pub cellular_data: CellularData,
264}
265
266impl Network {
267 pub fn new(kind: NetworkKind) -> Self {
270 Self {
271 kind,
272 ..Self::default()
273 }
274 }
275
276 pub fn expensive(mut self, expensive: bool) -> Self {
278 self.expensive = expensive;
279 self
280 }
281
282 pub fn constrained(mut self, constrained: bool) -> Self {
284 self.constrained = constrained;
285 self
286 }
287
288 pub fn cellular_data(mut self, cellular_data: CellularData) -> Self {
290 self.cellular_data = cellular_data;
291 self
292 }
293
294 pub fn online(&self) -> bool {
298 self.kind != NetworkKind::None
299 }
300}
301
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
304#[non_exhaustive]
305pub enum NetworkKind {
306 #[default]
309 Unknown,
310 None,
312 Wifi,
314 Cellular,
316 Wired,
318 Other,
321}
322
323impl NetworkKind {
324 pub fn name(self) -> &'static str {
326 match self {
327 Self::Unknown => "unknown",
328 Self::None => "none",
329 Self::Wifi => "wifi",
330 Self::Cellular => "cellular",
331 Self::Wired => "wired",
332 Self::Other => "other",
333 }
334 }
335
336 pub fn parse(name: &str) -> Option<Self> {
338 Some(match name {
339 "unknown" => Self::Unknown,
340 "none" => Self::None,
341 "wifi" => Self::Wifi,
342 "cellular" => Self::Cellular,
343 "wired" => Self::Wired,
344 "other" => Self::Other,
345 _ => return None,
346 })
347 }
348}
349
350#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
353#[non_exhaustive]
354pub enum CellularData {
355 #[default]
359 Unknown,
360 Restricted,
364 NotRestricted,
366}
367
368impl CellularData {
369 pub fn name(self) -> &'static str {
371 match self {
372 Self::Unknown => "unknown",
373 Self::Restricted => "restricted",
374 Self::NotRestricted => "notRestricted",
375 }
376 }
377
378 pub fn parse(name: &str) -> Option<Self> {
380 Some(match name {
381 "unknown" => Self::Unknown,
382 "restricted" => Self::Restricted,
383 "notRestricted" => Self::NotRestricted,
384 _ => return None,
385 })
386 }
387}
388
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
391pub enum SizeClass {
392 Compact,
394 Regular,
396}
397
398impl SizeClass {
399 pub(crate) fn from_length(length: Points) -> Self {
402 if length < Points(600.0) {
403 Self::Compact
404 } else {
405 Self::Regular
406 }
407 }
408
409 pub fn name(self) -> &'static str {
411 match self {
412 Self::Compact => "compact",
413 Self::Regular => "regular",
414 }
415 }
416}
417
418#[derive(Debug, Clone, Copy, PartialEq)]
420pub struct Environment {
421 pub window: Size<Points>,
423 pub horizontal_size_class: Option<SizeClass>,
425 pub vertical_size_class: Option<SizeClass>,
427 pub safe_area: Edges<Points>,
429 pub reserved_regions: ReservedRegions,
434 pub title_bar: Edges<Points>,
440 pub window_state: Option<crate::desktop::WindowState>,
445 pub keyboard_height: Points,
447 pub keyboard_duration: f32,
449 pub color_scheme: ColorScheme,
451 pub font_scale: f32,
453 pub rtl: bool,
455 pub reduce_motion: bool,
458 pub pixel_ratio: f32,
460 pub screen_reader: bool,
462 pub reads_active_descendants: bool,
469 pub os: Os,
471 pub platform: Option<&'static str>,
477 pub os_version: (u16, u16),
480 pub idiom: Idiom,
482 pub apple_keyboard: bool,
487 pub ctrl_for_command: bool,
492 pub locale: Locale,
494 pub locale_settings: LocaleSettings,
497 pub host: bool,
500 pub lifecycle: Lifecycle,
504 pub wake_count: u32,
511 pub network: Network,
516 pub screen_color: bool,
520 pub clipboard_write_result: bool,
526 pub canvas_render: bool,
530 pub app_settings: bool,
536 pub scheme_links: Option<bool>,
543 pub file_requests: bool,
548 pub notifications: bool,
552 pub audio: bool,
556 pub tab_bar: bool,
564 pub clipboard_images: Option<bool>,
571 pub cell: Option<Size<Points>>,
578 pub web_input: bool,
582 pub web_evaluate: bool,
585 pub web_views: bool,
592 pub webview_requests: bool,
598 pub shaders: bool,
606}
607
608impl Environment {
609 pub fn horizontal_size_class(&self) -> SizeClass {
611 self.horizontal_size_class
612 .unwrap_or_else(|| SizeClass::from_length(self.window.width))
613 }
614
615 pub fn vertical_size_class(&self) -> SizeClass {
617 self.vertical_size_class
618 .unwrap_or_else(|| SizeClass::from_length(self.window.height))
619 }
620
621 pub fn platform_name(&self) -> &'static str {
625 self.platform.unwrap_or(self.os.name())
626 }
627
628 pub fn desktop(&self) -> bool {
633 self.idiom.desktop_on(self.os)
634 }
635
636 pub fn reported_idiom(&self) -> Idiom {
638 self.idiom.reported_on(self.os)
639 }
640
641 pub fn scheme_links(&self) -> bool {
645 self.scheme_links.unwrap_or(self.os != Os::Web)
646 }
647}
648
649impl Default for Environment {
650 fn default() -> Self {
651 Self {
652 window: Size::default(),
653 horizontal_size_class: None,
654 vertical_size_class: None,
655 safe_area: Edges::default(),
656 reserved_regions: ReservedRegions::NONE,
657 title_bar: Edges::default(),
658 window_state: None,
659 keyboard_height: Points(0.0),
660 keyboard_duration: 250.0,
661 color_scheme: ColorScheme::Light,
662 font_scale: 1.0,
663 rtl: false,
664 reduce_motion: false,
665 pixel_ratio: 1.0,
666 screen_reader: false,
667 reads_active_descendants: false,
668 os: Os::default(),
669 platform: None,
670 os_version: (0, 0),
671 idiom: Idiom::Phone,
672 apple_keyboard: false,
673 ctrl_for_command: false,
674 locale: Locale::EN_US,
675 locale_settings: LocaleSettings::EN_US,
676 host: false,
677 lifecycle: Lifecycle::Active,
678 wake_count: 0,
679 network: Network::default(),
680 screen_color: false,
681 clipboard_write_result: false,
682 canvas_render: false,
683 app_settings: false,
684 scheme_links: None,
685 file_requests: false,
686 notifications: false,
687 audio: false,
688 tab_bar: true,
689 clipboard_images: None,
690 cell: None,
691 web_input: false,
692 web_evaluate: false,
693 web_views: true,
694 webview_requests: false,
695 shaders: true,
696 }
697 }
698}
699
700#[derive(Debug, Clone, Copy, PartialEq, Default)]
707pub struct HostEnvironment {
708 pub locale: Option<Locale>,
710 pub font_scale: Option<f32>,
713}
714
715impl HostEnvironment {
716 pub fn apply(&self, env: &mut Environment) {
718 if let Some(locale) = self.locale {
719 env.locale = locale;
720 env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
721 }
722 if let Some(scale) = self.font_scale.filter(|s| s.is_finite() && *s > 0.0) {
723 env.font_scale = scale;
724 }
725 }
726}
727
728#[derive(Clone, Copy, PartialEq, Eq, Hash)]
732pub struct Locale {
733 bytes: [u8; Locale::CAPACITY],
734 len: u8,
735}
736
737impl Locale {
738 const CAPACITY: usize = 15;
739
740 pub const EN_US: Locale = Locale {
742 bytes: *b"en-US\0\0\0\0\0\0\0\0\0\0",
743 len: 5,
744 };
745
746 pub fn parse(identifier: &str) -> Option<Locale> {
751 let identifier = identifier.split(['@', '.']).next().unwrap_or_default();
752 let mut bytes = [0u8; Self::CAPACITY];
753 let mut len = 0;
754 for (i, part) in identifier.split(['-', '_']).enumerate() {
755 let keep = if i == 0 {
756 (2..=3).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphabetic())
757 } else {
758 (part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()))
760 || (part.len() == 2 && part.bytes().all(|b| b.is_ascii_alphabetic()))
761 || (part.len() == 3 && part.bytes().all(|b| b.is_ascii_digit()))
762 };
763 if !keep {
764 if i == 0 {
765 return None;
766 }
767 break;
769 }
770 if len + part.len() + usize::from(i > 0) > Self::CAPACITY {
771 break;
772 }
773 if i > 0 {
774 bytes[len] = b'-';
775 len += 1;
776 }
777 for (j, b) in part.bytes().enumerate() {
778 bytes[len] = match (i, part.len()) {
779 (0, _) => b.to_ascii_lowercase(),
780 (_, 4) if j == 0 => b.to_ascii_uppercase(),
781 (_, 4) => b.to_ascii_lowercase(),
782 _ => b.to_ascii_uppercase(),
783 };
784 len += 1;
785 }
786 }
787 Some(Locale {
788 bytes,
789 len: len as u8,
790 })
791 }
792
793 pub fn as_str(&self) -> &str {
795 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("en-US")
797 }
798
799 pub fn language(&self) -> &str {
801 self.as_str().split('-').next().unwrap_or_default()
802 }
803
804 pub fn region(&self) -> Option<&str> {
806 self.as_str().split('-').skip(1).find(|s| s.len() != 4)
808 }
809}
810
811impl Default for Locale {
812 fn default() -> Self {
813 Self::EN_US
814 }
815}
816
817impl std::fmt::Debug for Locale {
818 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
819 write!(f, "Locale({})", self.as_str())
820 }
821}
822
823impl std::fmt::Display for Locale {
824 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
825 f.write_str(self.as_str())
826 }
827}
828
829#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
832#[non_exhaustive]
833pub enum ReservedRegionKind {
834 #[default]
837 Occlusion,
838 Division,
841}
842
843impl ReservedRegionKind {
844 pub fn name(self) -> &'static str {
846 match self {
847 Self::Occlusion => "occlusion",
848 Self::Division => "division",
849 }
850 }
851}
852
853#[derive(Debug, Clone, Copy, PartialEq, Default, crate::element::JsObject)]
857#[non_exhaustive]
858pub struct ReservedRegion {
859 pub kind: ReservedRegionKind,
861 pub bounds: Bounds<Points>,
864}
865
866impl ReservedRegion {
867 pub fn new(kind: ReservedRegionKind, bounds: Bounds<Points>) -> ReservedRegion {
869 ReservedRegion { kind, bounds }
870 }
871}
872
873#[derive(Clone, Copy, PartialEq)]
877pub struct ReservedRegions {
878 regions: [ReservedRegion; ReservedRegions::CAPACITY],
879 len: u8,
880}
881
882impl ReservedRegions {
883 pub const CAPACITY: usize = 8;
886
887 pub const NONE: ReservedRegions = ReservedRegions {
889 regions: [ReservedRegion {
890 kind: ReservedRegionKind::Occlusion,
891 bounds: Bounds {
892 origin: crate::geometry::Point {
893 x: Points(0.0),
894 y: Points(0.0),
895 },
896 size: Size {
897 width: Points(0.0),
898 height: Points(0.0),
899 },
900 },
901 }; ReservedRegions::CAPACITY],
902 len: 0,
903 };
904
905 pub fn new(regions: impl IntoIterator<Item = ReservedRegion>) -> ReservedRegions {
907 let mut list = Self::NONE;
908 for region in regions.into_iter().take(Self::CAPACITY) {
909 list.regions[usize::from(list.len)] = region;
910 list.len += 1;
911 }
912 list
913 }
914
915 pub fn as_slice(&self) -> &[ReservedRegion] {
917 &self.regions[..usize::from(self.len)]
918 }
919
920 pub fn iter(&self) -> impl Iterator<Item = ReservedRegion> + '_ {
922 self.as_slice().iter().copied()
923 }
924
925 pub fn is_empty(&self) -> bool {
927 self.len == 0
928 }
929
930 pub fn len(&self) -> usize {
932 usize::from(self.len)
933 }
934}
935
936impl Default for ReservedRegions {
937 fn default() -> Self {
938 Self::NONE
939 }
940}
941
942impl std::fmt::Debug for ReservedRegions {
943 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
944 f.debug_list().entries(self.as_slice()).finish()
945 }
946}
947
948#[derive(Clone, Copy, PartialEq, Eq, Hash)]
952pub struct Languages {
953 tags: [Locale; Languages::CAPACITY],
954 len: u8,
955}
956
957impl Languages {
958 const CAPACITY: usize = 8;
961
962 pub(crate) const EN_US: Languages = Languages {
964 tags: [Locale::EN_US; Languages::CAPACITY],
965 len: 1,
966 };
967
968 #[doc(hidden)]
970 pub const fn one(locale: Locale) -> Languages {
971 Languages {
972 tags: [locale; Languages::CAPACITY],
973 len: 1,
974 }
975 }
976
977 #[doc(hidden)]
982 pub fn parse<'a>(identifiers: impl IntoIterator<Item = &'a str>) -> Option<Languages> {
983 let mut languages = Languages::EN_US;
984 languages.len = 0;
985 for locale in identifiers.into_iter().filter_map(Locale::parse) {
986 if usize::from(languages.len) == Self::CAPACITY {
987 break;
988 }
989 if !languages.as_slice().contains(&locale) {
990 languages.tags[usize::from(languages.len)] = locale;
991 languages.len += 1;
992 }
993 }
994 (languages.len > 0).then_some(languages)
995 }
996
997 pub fn preferring(&self, locale: Locale) -> Languages {
1001 let mut languages = Languages::one(locale);
1002 for &other in self.as_slice() {
1003 if usize::from(languages.len) == Self::CAPACITY {
1004 break;
1005 }
1006 if other != locale {
1007 languages.tags[usize::from(languages.len)] = other;
1008 languages.len += 1;
1009 }
1010 }
1011 languages
1012 }
1013
1014 pub fn first(&self) -> Locale {
1016 self.tags[0]
1017 }
1018
1019 pub fn as_slice(&self) -> &[Locale] {
1021 &self.tags[..usize::from(self.len)]
1022 }
1023
1024 pub fn iter(&self) -> impl Iterator<Item = Locale> + '_ {
1026 self.as_slice().iter().copied()
1027 }
1028}
1029
1030impl Default for Languages {
1031 fn default() -> Self {
1032 Self::EN_US
1033 }
1034}
1035
1036impl std::fmt::Debug for Languages {
1037 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1038 f.debug_list()
1039 .entries(self.iter().map(|l| l.to_string()))
1040 .finish()
1041 }
1042}
1043
1044#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1049#[non_exhaustive]
1050pub struct TimeZone {
1051 bytes: [u8; TimeZone::CAPACITY],
1052 len: u8,
1053}
1054
1055impl TimeZone {
1056 const CAPACITY: usize = 63;
1061
1062 pub const UTC: TimeZone = {
1064 let mut bytes = [0u8; TimeZone::CAPACITY];
1065 bytes[0] = b'U';
1066 bytes[1] = b'T';
1067 bytes[2] = b'C';
1068 TimeZone { bytes, len: 3 }
1069 };
1070
1071 pub fn parse(identifier: &str) -> Option<TimeZone> {
1078 let identifier = identifier.trim();
1079 let name = match identifier.rsplit_once("zoneinfo/") {
1080 Some((_, name)) => name,
1081 None => identifier.strip_prefix(':').unwrap_or(identifier),
1082 };
1083 let valid = !name.is_empty()
1084 && name.len() <= Self::CAPACITY
1085 && name
1086 .bytes()
1087 .all(|b| b.is_ascii_alphanumeric() || b"/_-+:".contains(&b))
1088 && name
1089 .split('/')
1090 .all(|part| !part.is_empty() && part != "." && part != "..");
1091 if !valid {
1092 return None;
1093 }
1094 let mut bytes = [0u8; Self::CAPACITY];
1095 bytes[..name.len()].copy_from_slice(name.as_bytes());
1096 Some(TimeZone {
1097 bytes,
1098 len: name.len() as u8,
1099 })
1100 }
1101
1102 #[doc(hidden)]
1117 pub fn posix(tz: Option<&str>, system: impl FnOnce() -> Option<TimeZone>) -> TimeZone {
1118 let zone = match tz.map(str::trim) {
1119 None => None,
1120 Some("") => Some(Self::UTC),
1122 Some(tz) => {
1123 let name = tz.strip_prefix(':').unwrap_or(tz);
1124 if is_posix_rule(name) && !RULE_NAMED_ZONES.contains(&name) {
1125 None
1126 } else {
1127 Self::parse(name)
1128 }
1129 }
1130 };
1131 zone.or_else(system).unwrap_or_default()
1132 }
1133
1134 pub fn as_str(&self) -> &str {
1136 std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("UTC")
1138 }
1139}
1140
1141const RULE_NAMED_ZONES: [&str; 7] = [
1145 "EST5EDT", "CST6CDT", "MST7MDT", "PST8PDT", "GMT0", "GMT+0", "GMT-0",
1146];
1147
1148fn is_posix_rule(tz: &str) -> bool {
1154 let letters = tz.bytes().take_while(u8::is_ascii_alphabetic).count();
1155 tz.starts_with('<')
1156 || letters >= 3
1157 && tz
1158 .as_bytes()
1159 .get(letters)
1160 .is_some_and(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-'))
1161}
1162
1163impl Default for TimeZone {
1164 fn default() -> Self {
1165 Self::UTC
1166 }
1167}
1168
1169impl std::fmt::Debug for TimeZone {
1170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1171 write!(f, "TimeZone({})", self.as_str())
1172 }
1173}
1174
1175impl std::fmt::Display for TimeZone {
1176 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1177 f.write_str(self.as_str())
1178 }
1179}
1180
1181#[non_exhaustive]
1185#[derive(Debug, Clone, Copy, PartialEq, Default, crate::element::JsObject)]
1186pub struct PerfStats {
1187 pub fps: f32,
1190 pub refresh_rate: Option<f32>,
1193 pub dropped: crate::geometry::Percentage,
1196 pub memory: Option<u64>,
1201}
1202
1203impl PerfStats {
1204 #[doc(hidden)]
1208 pub fn new(fps: f32) -> PerfStats {
1209 PerfStats {
1210 fps,
1211 ..PerfStats::default()
1212 }
1213 }
1214}
1215
1216#[derive(Debug, Clone, PartialEq, Eq, Default)]
1223#[non_exhaustive]
1224pub struct AppInfo {
1225 pub id: Option<String>,
1227 pub name: Option<String>,
1229 pub version: Option<String>,
1232 pub build: Option<u64>,
1235 pub development: bool,
1238}
1239
1240impl AppInfo {
1241 #[doc(hidden)]
1245 pub fn from_json(value: &crate::JsonValue) -> AppInfo {
1246 let text = |key: &str| value.get(key).and_then(|v| v.as_str()).map(str::to_owned);
1247 AppInfo {
1248 id: text("id"),
1249 name: text("name"),
1250 version: text("version"),
1251 build: value.get("build").and_then(|v| v.as_u64()),
1252 development: value
1253 .get("development")
1254 .and_then(|v| v.as_bool())
1255 .unwrap_or(false),
1256 }
1257 }
1258
1259 pub fn to_json(&self) -> crate::JsonValue {
1261 serde_json::json!({
1262 "id": self.id,
1263 "name": self.name,
1264 "version": self.version,
1265 "build": self.build,
1266 "development": self.development,
1267 })
1268 }
1269}
1270
1271#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1280#[non_exhaustive]
1281pub struct LocaleSettings {
1282 pub languages: Languages,
1285 pub time_zone: TimeZone,
1287 pub hour_cycle: HourCycle,
1289 pub first_day_of_week: Weekday,
1291 pub measurement_system: MeasurementSystem,
1293 pub temperature_unit: TemperatureUnit,
1295}
1296
1297impl LocaleSettings {
1298 pub(crate) const EN_US: LocaleSettings = LocaleSettings {
1301 languages: Languages::EN_US,
1302 time_zone: TimeZone::UTC,
1303 hour_cycle: HourCycle::H12,
1304 first_day_of_week: Weekday::Sunday,
1305 measurement_system: MeasurementSystem::Us,
1306 temperature_unit: TemperatureUnit::Fahrenheit,
1307 };
1308
1309 #[doc(hidden)]
1314 pub fn of(locale: Locale) -> LocaleSettings {
1315 LocaleSettings {
1316 languages: Languages::one(locale),
1317 ..Self::of_region(locale.language(), locale.region().unwrap_or("001"))
1318 }
1319 }
1320
1321 #[doc(hidden)]
1331 pub fn parse(identifier: &str) -> LocaleSettings {
1332 let identifier = identifier.trim();
1333 let (tag, icu) = identifier.split_once('@').unwrap_or((identifier, ""));
1334 let mut keywords = Keywords::default();
1335 let mut extension = false;
1338 let mut key = "";
1339 for subtag in tag.split('.').next().unwrap_or_default().split(['-', '_']) {
1340 if subtag.len() == 1 {
1341 extension = subtag.eq_ignore_ascii_case("u");
1342 key = "";
1343 } else if extension && subtag.len() == 2 {
1344 key = subtag;
1345 } else if extension && !key.is_empty() {
1346 keywords.set(key, subtag);
1347 key = "";
1348 }
1349 }
1350 for keyword in icu.split(';') {
1351 if let Some((key, value)) = keyword.split_once('=') {
1352 keywords.set(key.trim(), value.trim());
1353 }
1354 }
1355 let locale = Locale::parse(identifier);
1356 let language = locale.as_ref().map_or("", Locale::language);
1357 let region = match &keywords.region {
1358 Some((bytes, len)) => std::str::from_utf8(&bytes[..*len]).unwrap_or("001"),
1359 None => locale.as_ref().and_then(Locale::region).unwrap_or("001"),
1360 };
1361 let own = Self::of_region(language, region);
1362 LocaleSettings {
1363 languages: Languages::one(locale.unwrap_or(Locale::EN_US)),
1364 hour_cycle: keywords.hour_cycle.unwrap_or(own.hour_cycle),
1365 first_day_of_week: keywords.first_day_of_week.unwrap_or(own.first_day_of_week),
1366 measurement_system: keywords
1367 .measurement_system
1368 .unwrap_or(own.measurement_system),
1369 temperature_unit: keywords.temperature_unit.unwrap_or(own.temperature_unit),
1370 ..own
1371 }
1372 }
1373
1374 fn of_region(language: &str, region: &str) -> LocaleSettings {
1376 let listed = |regions: &[&str]| regions.binary_search(®ion).is_ok();
1377 LocaleSettings {
1378 hour_cycle: match (language, region) {
1379 ("fr", "CA") | ("ku", "SY") => HourCycle::H23,
1381 ("ar" | "en", "001") => HourCycle::H12,
1382 _ if listed(HOUR12_REGIONS) => HourCycle::H12,
1383 _ => HourCycle::H23,
1384 },
1385 first_day_of_week: if listed(SUNDAY_REGIONS) {
1386 Weekday::Sunday
1387 } else if listed(SATURDAY_REGIONS) {
1388 Weekday::Saturday
1389 } else if listed(FRIDAY_REGIONS) {
1390 Weekday::Friday
1391 } else {
1392 Weekday::Monday
1393 },
1394 measurement_system: match region {
1395 "LR" | "US" => MeasurementSystem::Us,
1396 "GB" | "MM" => MeasurementSystem::Uk,
1397 _ => MeasurementSystem::Metric,
1398 },
1399 temperature_unit: match region {
1400 "BS" | "BZ" | "KY" | "PR" | "PW" | "US" => TemperatureUnit::Fahrenheit,
1401 _ => TemperatureUnit::Celsius,
1402 },
1403 ..Self::default()
1404 }
1405 }
1406}
1407
1408impl Default for LocaleSettings {
1409 fn default() -> Self {
1410 Self::EN_US
1411 }
1412}
1413
1414#[derive(Default)]
1416struct Keywords {
1417 hour_cycle: Option<HourCycle>,
1418 first_day_of_week: Option<Weekday>,
1419 measurement_system: Option<MeasurementSystem>,
1420 temperature_unit: Option<TemperatureUnit>,
1421 region: Option<([u8; 3], usize)>,
1423}
1424
1425impl Keywords {
1426 fn set(&mut self, key: &str, value: &str) {
1428 let is = |names: &[&str]| names.iter().any(|n| key.eq_ignore_ascii_case(n));
1429 let value_is = |name: &str| value.eq_ignore_ascii_case(name);
1430 if is(&["hc", "hours"]) {
1431 self.hour_cycle = HourCycle::parse(value).or(self.hour_cycle);
1432 } else if is(&["fw"]) {
1433 self.first_day_of_week = Weekday::ALL
1434 .into_iter()
1435 .find(|d| value_is(d.code()))
1436 .or(self.first_day_of_week);
1437 } else if is(&["ms", "measure"]) {
1438 self.measurement_system = match () {
1439 _ if value_is("metric") => Some(MeasurementSystem::Metric),
1440 _ if value_is("ussystem") => Some(MeasurementSystem::Us),
1441 _ if value_is("uksystem") => Some(MeasurementSystem::Uk),
1442 _ => self.measurement_system,
1443 };
1444 } else if is(&["mu"]) {
1445 let unit = match value_is("fahrenhe") {
1447 true => Some(TemperatureUnit::Fahrenheit),
1448 false => TemperatureUnit::parse(value),
1449 };
1450 self.temperature_unit = unit.or(self.temperature_unit);
1451 } else if is(&["rg"]) {
1452 let bytes = value.as_bytes();
1455 let len = match bytes {
1456 [a, b, c, ..] if [a, b, c].iter().all(|b| b.is_ascii_digit()) => 3,
1457 [a, b, ..] if a.is_ascii_alphabetic() && b.is_ascii_alphabetic() => 2,
1458 _ => return,
1459 };
1460 let mut region = [0u8; 3];
1461 for (to, from) in region.iter_mut().zip(bytes) {
1462 *to = from.to_ascii_uppercase();
1463 }
1464 self.region = Some((region, len));
1465 }
1466 }
1467}
1468
1469const HOUR12_REGIONS: &[&str] = &[
1471 "419", "AE", "AG", "AL", "AR", "AS", "AU", "BB", "BD", "BH", "BM", "BN", "BO", "BS", "BT",
1472 "CA", "CL", "CO", "CR", "CU", "CY", "DJ", "DM", "DO", "DZ", "EC", "EG", "EH", "ER", "ET", "FJ",
1473 "FM", "GD", "GH", "GM", "GR", "GT", "GU", "GY", "HK", "HN", "IN", "IQ", "JM", "JO", "KH", "KI",
1474 "KN", "KP", "KR", "KW", "KY", "LB", "LC", "LR", "LS", "LY", "MH", "MO", "MP", "MR", "MW", "MX",
1475 "MY", "NA", "NI", "NZ", "OM", "PA", "PE", "PG", "PH", "PK", "PR", "PS", "PW", "PY", "QA", "SA",
1476 "SB", "SD", "SG", "SL", "SO", "SS", "SV", "SY", "SZ", "TC", "TD", "TN", "TO", "TT", "TW", "UM",
1477 "US", "UY", "VC", "VE", "VG", "VI", "VU", "WS", "YE", "ZM",
1478];
1479
1480const SUNDAY_REGIONS: &[&str] = &[
1482 "AG", "AS", "BD", "BR", "BS", "BT", "BW", "BZ", "CA", "CO", "DM", "DO", "ET", "GT", "GU", "HK",
1483 "HN", "ID", "IL", "IN", "IS", "JM", "JP", "KE", "KH", "KR", "LA", "MH", "MM", "MO", "MT", "MX",
1484 "MZ", "NI", "NP", "PA", "PE", "PH", "PK", "PR", "PT", "PY", "SA", "SG", "SV", "TH", "TT", "TW",
1485 "UM", "US", "VE", "VI", "WS", "YE", "ZA", "ZW",
1486];
1487
1488const SATURDAY_REGIONS: &[&str] = &[
1490 "AF", "BH", "DJ", "DZ", "EG", "IQ", "IR", "JO", "KW", "LY", "OM", "QA", "SD", "SY",
1491];
1492
1493const FRIDAY_REGIONS: &[&str] = &["MV"];
1495
1496#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1498pub enum HourCycle {
1499 H11,
1501 #[default]
1503 H12,
1504 H23,
1506 H24,
1508}
1509
1510impl HourCycle {
1511 pub fn name(self) -> &'static str {
1513 match self {
1514 HourCycle::H11 => "h11",
1515 HourCycle::H12 => "h12",
1516 HourCycle::H23 => "h23",
1517 HourCycle::H24 => "h24",
1518 }
1519 }
1520
1521 pub fn parse(name: &str) -> Option<HourCycle> {
1523 [
1524 HourCycle::H11,
1525 HourCycle::H12,
1526 HourCycle::H23,
1527 HourCycle::H24,
1528 ]
1529 .into_iter()
1530 .find(|c| name.eq_ignore_ascii_case(c.name()))
1531 }
1532
1533 #[doc(hidden)]
1538 pub fn of_pattern(pattern: &str) -> Option<HourCycle> {
1539 let mut quoted = false;
1540 pattern.chars().find_map(|c| match c {
1541 '\'' => {
1542 quoted = !quoted;
1543 None
1544 }
1545 _ if quoted => None,
1546 'h' => Some(HourCycle::H12),
1547 'H' => Some(HourCycle::H23),
1548 'K' => Some(HourCycle::H11),
1549 'k' => Some(HourCycle::H24),
1550 _ => None,
1551 })
1552 }
1553
1554 pub fn twelve_hour(self) -> bool {
1556 matches!(self, HourCycle::H11 | HourCycle::H12)
1557 }
1558}
1559
1560#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1562pub enum Weekday {
1563 Monday = 1,
1565 Tuesday,
1567 Wednesday,
1569 Thursday,
1571 Friday,
1573 Saturday,
1575 Sunday,
1577}
1578
1579impl Weekday {
1580 const ALL: [Weekday; 7] = [
1582 Weekday::Monday,
1583 Weekday::Tuesday,
1584 Weekday::Wednesday,
1585 Weekday::Thursday,
1586 Weekday::Friday,
1587 Weekday::Saturday,
1588 Weekday::Sunday,
1589 ];
1590
1591 pub fn number(self) -> u8 {
1594 self as u8
1595 }
1596
1597 pub fn from_number(number: u8) -> Option<Weekday> {
1599 Self::ALL.get(usize::from(number).checked_sub(1)?).copied()
1600 }
1601
1602 fn code(self) -> &'static str {
1604 match self {
1605 Weekday::Monday => "mon",
1606 Weekday::Tuesday => "tue",
1607 Weekday::Wednesday => "wed",
1608 Weekday::Thursday => "thu",
1609 Weekday::Friday => "fri",
1610 Weekday::Saturday => "sat",
1611 Weekday::Sunday => "sun",
1612 }
1613 }
1614}
1615
1616#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1618pub enum MeasurementSystem {
1619 #[default]
1621 Metric,
1622 Us,
1624 Uk,
1626}
1627
1628impl MeasurementSystem {
1629 pub fn name(self) -> &'static str {
1631 match self {
1632 MeasurementSystem::Metric => "metric",
1633 MeasurementSystem::Us => "us",
1634 MeasurementSystem::Uk => "uk",
1635 }
1636 }
1637
1638 pub fn parse(name: &str) -> Option<MeasurementSystem> {
1640 [
1641 MeasurementSystem::Metric,
1642 MeasurementSystem::Us,
1643 MeasurementSystem::Uk,
1644 ]
1645 .into_iter()
1646 .find(|s| name.eq_ignore_ascii_case(s.name()))
1647 }
1648}
1649
1650#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, crate::element::PropEnum)]
1652pub enum TemperatureUnit {
1653 #[default]
1655 Celsius,
1656 Fahrenheit,
1658}
1659
1660impl TemperatureUnit {
1661 pub fn name(self) -> &'static str {
1663 match self {
1664 TemperatureUnit::Celsius => "celsius",
1665 TemperatureUnit::Fahrenheit => "fahrenheit",
1666 }
1667 }
1668
1669 pub fn parse(name: &str) -> Option<TemperatureUnit> {
1671 [TemperatureUnit::Celsius, TemperatureUnit::Fahrenheit]
1672 .into_iter()
1673 .find(|u| name.eq_ignore_ascii_case(u.name()))
1674 }
1675}
1676
1677#[derive(Debug, Clone, PartialEq, Eq)]
1680pub struct HttpRequest {
1681 pub method: String,
1683 pub url: String,
1685 pub headers: Vec<(String, String)>,
1687 pub body: HttpBody,
1689 pub follow_redirects: bool,
1691 pub cache: HttpCache,
1694}
1695
1696#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
1704pub enum HttpCache {
1705 #[default]
1708 Default,
1709 NoStore,
1711 Reload,
1713 NoCache,
1715 ForceCache,
1718 OnlyIfCached,
1720}
1721
1722impl HttpCache {
1723 pub fn as_str(self) -> &'static str {
1725 match self {
1726 Self::Default => "default",
1727 Self::NoStore => "no-store",
1728 Self::Reload => "reload",
1729 Self::NoCache => "no-cache",
1730 Self::ForceCache => "force-cache",
1731 Self::OnlyIfCached => "only-if-cached",
1732 }
1733 }
1734
1735 pub fn parse(name: &str) -> Option<Self> {
1737 Some(match name {
1738 "default" => Self::Default,
1739 "no-store" => Self::NoStore,
1740 "reload" => Self::Reload,
1741 "no-cache" => Self::NoCache,
1742 "force-cache" => Self::ForceCache,
1743 "only-if-cached" => Self::OnlyIfCached,
1744 _ => return None,
1745 })
1746 }
1747}
1748
1749impl HttpRequest {
1750 pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
1753 Self {
1754 method: method.into().to_ascii_uppercase(),
1755 url: url.into(),
1756 headers: Vec::new(),
1757 body: HttpBody::Empty,
1758 follow_redirects: true,
1759 cache: HttpCache::Default,
1760 }
1761 }
1762
1763 pub fn get(url: impl Into<String>) -> Self {
1765 Self::new("GET", url)
1766 }
1767
1768 pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
1770 Self::new("POST", url).body(body)
1771 }
1772
1773 #[must_use]
1775 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
1776 self.headers.push((name.into(), value.into()));
1777 self
1778 }
1779
1780 #[must_use]
1782 pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
1783 self.body = HttpBody::Bytes(body.into());
1784 self
1785 }
1786
1787 #[must_use]
1789 pub fn cache(mut self, cache: HttpCache) -> Self {
1790 self.cache = cache;
1791 self
1792 }
1793}
1794
1795impl From<&str> for HttpRequest {
1796 fn from(url: &str) -> Self {
1797 Self::get(url)
1798 }
1799}
1800
1801impl From<String> for HttpRequest {
1802 fn from(url: String) -> Self {
1803 Self::get(url)
1804 }
1805}
1806
1807#[derive(Debug, Clone, PartialEq, Eq, Default)]
1809pub enum HttpBody {
1810 #[default]
1812 Empty,
1813 Bytes(Vec<u8>),
1815 Stream,
1819}
1820
1821impl HttpBody {
1822 pub fn is_empty(&self) -> bool {
1824 match self {
1825 HttpBody::Empty => true,
1826 HttpBody::Bytes(b) => b.is_empty(),
1827 HttpBody::Stream => false,
1828 }
1829 }
1830}
1831
1832#[derive(Debug, Clone, PartialEq, Eq, Default)]
1834pub struct HttpHead {
1835 pub status: u16,
1837 pub status_text: String,
1839 pub url: String,
1841 pub redirected: bool,
1843 pub headers: Vec<(String, String)>,
1845}
1846
1847#[doc(hidden)]
1854pub fn content_type(path: &str) -> &'static str {
1855 match std::path::Path::new(path)
1856 .extension()
1857 .and_then(|e| e.to_str())
1858 .map(str::to_ascii_lowercase)
1859 .as_deref()
1860 {
1861 Some("html") => "text/html; charset=utf-8",
1862 Some("js" | "mjs") => "text/javascript; charset=utf-8",
1863 Some("json" | "map") => "application/json",
1864 Some("webmanifest") => "application/manifest+json",
1865 Some("wasm") => "application/wasm",
1866 Some("css") => "text/css; charset=utf-8",
1867 Some("txt") => "text/plain; charset=utf-8",
1868 Some("png") => "image/png",
1869 Some("jpg" | "jpeg") => "image/jpeg",
1870 Some("gif") => "image/gif",
1871 Some("webp") => "image/webp",
1872 Some("avif") => "image/avif",
1873 Some("svg") => "image/svg+xml",
1874 Some("ico") => "image/x-icon",
1875 Some("heic") => "image/heic",
1876 Some("ttf") => "font/ttf",
1877 Some("otf") => "font/otf",
1878 Some("woff") => "font/woff",
1879 Some("woff2") => "font/woff2",
1880 Some("mp4" | "m4v") => "video/mp4",
1881 Some("webm") => "video/webm",
1882 Some("mov") => "video/quicktime",
1883 Some("mp3") => "audio/mpeg",
1884 Some("m4a") => "audio/mp4",
1885 Some("aac") => "audio/aac",
1886 Some("wav") => "audio/wav",
1887 Some("ogg" | "oga" | "opus") => "audio/ogg",
1888 Some("flac") => "audio/flac",
1889 Some("aif" | "aiff") => "audio/aiff",
1890 Some("caf") => "audio/x-caf",
1891 _ => "application/octet-stream",
1892 }
1893}
1894
1895#[doc(hidden)]
1902pub fn file_mime_type(uri: &str) -> &'static str {
1903 let path = uri.split(['?', '#']).next().unwrap_or_default();
1904 let name = path.rsplit('/').next().unwrap_or_default();
1905 let Some((stem, ext)) = name.rsplit_once('.') else {
1906 return "";
1907 };
1908 if stem.is_empty() {
1909 return "";
1911 }
1912 match ext.to_ascii_lowercase().as_str() {
1913 "png" => "image/png",
1914 "jpg" | "jpeg" | "jpe" => "image/jpeg",
1915 "gif" => "image/gif",
1916 "webp" => "image/webp",
1917 "avif" => "image/avif",
1918 "heic" => "image/heic",
1919 "heif" => "image/heif",
1920 "svg" => "image/svg+xml",
1921 "bmp" => "image/bmp",
1922 "tif" | "tiff" => "image/tiff",
1923 "ico" => "image/x-icon",
1924 "mp4" | "m4v" => "video/mp4",
1925 "mov" => "video/quicktime",
1926 "webm" => "video/webm",
1927 "mkv" => "video/x-matroska",
1928 "avi" => "video/x-msvideo",
1929 "mp3" => "audio/mpeg",
1930 "m4a" => "audio/mp4",
1931 "aac" => "audio/aac",
1932 "wav" => "audio/wav",
1933 "ogg" | "oga" | "opus" => "audio/ogg",
1934 "flac" => "audio/flac",
1935 "aif" | "aiff" => "audio/aiff",
1936 "caf" => "audio/x-caf",
1937 "txt" | "text" | "log" => "text/plain",
1938 "md" | "markdown" => "text/markdown",
1939 "csv" => "text/csv",
1940 "tsv" => "text/tab-separated-values",
1941 "html" | "htm" => "text/html",
1942 "css" => "text/css",
1943 "js" | "mjs" => "text/javascript",
1944 "json" => "application/json",
1945 "xml" => "application/xml",
1946 "yaml" | "yml" => "application/yaml",
1947 "pdf" => "application/pdf",
1948 "rtf" => "application/rtf",
1949 "doc" => "application/msword",
1950 "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1951 "xls" => "application/vnd.ms-excel",
1952 "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1953 "ppt" => "application/vnd.ms-powerpoint",
1954 "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1955 "zip" => "application/zip",
1956 "gz" | "tgz" => "application/gzip",
1957 "tar" => "application/x-tar",
1958 "7z" => "application/x-7z-compressed",
1959 "rar" => "application/vnd.rar",
1960 "wasm" => "application/wasm",
1961 "ttf" => "font/ttf",
1962 "otf" => "font/otf",
1963 "woff" => "font/woff",
1964 "woff2" => "font/woff2",
1965 _ => "",
1966 }
1967}
1968
1969#[derive(Debug, Clone, PartialEq, Eq)]
1973pub enum FetchEvent {
1974 BodyWanted,
1977 Head(HttpHead),
1979 Data(Vec<u8>),
1981 End,
1983 Failed(String),
1985}
1986
1987#[derive(Debug, Clone, PartialEq, Eq)]
1990pub enum FetchOp {
1991 Start(HttpRequest),
1993 Send(Vec<u8>),
1995 Finish,
1997 Pause(bool),
2000 Cancel,
2002}
2003
2004#[cfg(test)]
2005mod tests {
2006 #[test]
2007 fn app_info_reads_and_writes_app_infos_json() {
2008 use super::AppInfo;
2009 let json = serde_json::json!({
2010 "id": "com.example.orders",
2011 "name": "Orders",
2012 "version": "2.1.0",
2013 "build": 7,
2014 "development": true,
2015 "store": "play",
2016 });
2017 let info = AppInfo::from_json(&json);
2018 assert_eq!(info.id.as_deref(), Some("com.example.orders"));
2019 assert_eq!(info.name.as_deref(), Some("Orders"));
2020 assert_eq!(info.version.as_deref(), Some("2.1.0"));
2021 assert_eq!(info.build, Some(7));
2022 assert!(info.development);
2023 assert_eq!(AppInfo::from_json(&info.to_json()), info);
2024 let partial = AppInfo::from_json(&serde_json::json!({
2026 "id": null,
2027 "version": 2,
2028 "build": "7",
2029 }));
2030 assert_eq!(partial, AppInfo::default());
2031 assert_eq!(
2032 AppInfo::default().to_json(),
2033 serde_json::json!({
2034 "id": null, "name": null, "version": null, "build": null, "development": false,
2035 })
2036 );
2037 }
2038
2039 #[test]
2040 fn scheme_links_follow_the_os_unless_the_platform_says() {
2041 use super::{Environment, Os};
2042 let on = |os: Os, scheme_links: Option<bool>| {
2043 Environment {
2044 os,
2045 scheme_links,
2046 ..Environment::default()
2047 }
2048 .scheme_links()
2049 };
2050 for os in [Os::Ios, Os::Android, Os::MacOs, Os::Windows, Os::Linux] {
2051 assert!(on(os, None), "{os:?}");
2052 assert!(on(os, Some(true)), "{os:?}");
2053 assert!(!on(os, Some(false)), "{os:?}");
2054 }
2055 assert!(!on(Os::Web, None));
2056 assert!(on(Os::Web, Some(true)));
2057 assert!(!on(Os::Web, Some(false)));
2058 }
2059
2060 #[test]
2061 fn size_class_fallback_uses_points_and_native_traits_win() {
2062 use super::{Environment, SizeClass};
2063 use crate::geometry::size_pt;
2064 for (dimension, expected) in [
2065 (0.0, SizeClass::Compact),
2066 (599.5, SizeClass::Compact),
2067 (600.0, SizeClass::Regular),
2068 (1200.0, SizeClass::Regular),
2069 ] {
2070 let env = Environment {
2071 window: size_pt(dimension, dimension),
2072 ..Default::default()
2073 };
2074 assert_eq!(env.horizontal_size_class(), expected);
2075 assert_eq!(env.vertical_size_class(), expected);
2076 }
2077 let env = Environment {
2078 window: size_pt(900.0, 300.0),
2079 horizontal_size_class: Some(SizeClass::Compact),
2080 vertical_size_class: Some(SizeClass::Regular),
2081 ..Default::default()
2082 };
2083 assert_eq!(env.horizontal_size_class(), SizeClass::Compact);
2084 assert_eq!(env.vertical_size_class(), SizeClass::Regular);
2085 }
2086
2087 use super::{
2088 Environment, HostEnvironment, HourCycle, Idiom, Languages, Locale, LocaleSettings,
2089 MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday, content_type, file_mime_type,
2090 };
2091
2092 #[test]
2093 fn desktop_is_a_desktop_os_or_a_desktop_browser() {
2094 let desktop = |os: Os, idiom: Idiom| Environment {
2095 os,
2096 idiom,
2097 ..Environment::default()
2098 };
2099 for (os, idiom, expected) in [
2100 (Os::MacOs, Idiom::Desktop, true),
2101 (Os::Windows, Idiom::Desktop, true),
2102 (Os::Linux, Idiom::Desktop, true),
2103 (Os::Linux, Idiom::Phone, true),
2105 (Os::Web, Idiom::Desktop, true),
2106 (Os::Web, Idiom::Pad, false),
2107 (Os::Web, Idiom::Phone, false),
2108 (Os::Ios, Idiom::Phone, false),
2109 (Os::Ios, Idiom::Pad, false),
2110 (Os::Ios, Idiom::Mac, false),
2112 (Os::Ios, Idiom::Desktop, false),
2113 (Os::Android, Idiom::Tv, false),
2114 ] {
2115 let env = desktop(os, idiom);
2116 assert_eq!(env.desktop(), expected, "{os:?} {idiom:?}");
2117 assert_eq!(
2119 env.reported_idiom() == Idiom::Desktop,
2120 expected,
2121 "{os:?} {idiom:?}"
2122 );
2123 }
2124 assert_eq!(desktop(Os::Ios, Idiom::Mac).reported_idiom(), Idiom::Mac);
2125 assert_eq!(
2126 desktop(Os::Ios, Idiom::Desktop).reported_idiom(),
2127 Idiom::Phone
2128 );
2129 assert!(!Os::MacOs.is_catalyst() && !Os::Web.is_catalyst());
2130 assert_eq!(Os::Ios.is_catalyst(), cfg!(target_abi = "macabi"));
2131 }
2132
2133 #[test]
2134 fn desktop_behavior_applies_in_the_terminal_idiom_on_any_os() {
2135 for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Web] {
2136 assert!(Idiom::Terminal.desktop_on(os), "{os:?}");
2137 assert_eq!(Idiom::Terminal.reported_on(os), Idiom::Terminal, "{os:?}");
2138 }
2139 }
2140
2141 #[test]
2142 fn a_host_environment_replaces_what_it_sets() {
2143 let mut env = Environment {
2144 font_scale: 1.25,
2145 ..Environment::default()
2146 };
2147 HostEnvironment::default().apply(&mut env);
2148 assert_eq!((env.locale, env.font_scale), (Locale::EN_US, 1.25));
2149 let zh = Locale::parse("zh-Hans-CN").unwrap();
2150 HostEnvironment {
2151 locale: Some(zh),
2152 font_scale: Some(f32::NAN),
2153 }
2154 .apply(&mut env);
2155 assert_eq!((env.locale, env.font_scale), (zh, 1.25));
2156 HostEnvironment {
2157 locale: None,
2158 font_scale: Some(1.5),
2159 }
2160 .apply(&mut env);
2161 assert_eq!((env.locale, env.font_scale), (zh, 1.5));
2162 }
2163
2164 #[test]
2165 fn languages_parse_platform_identifiers_and_an_embedding_app_goes_first() {
2166 let tags = |l: Languages| l.iter().map(|l| l.to_string()).collect::<Vec<_>>();
2167 let system = Languages::parse(["de_DE", "C", "en-US", "de-DE", "fr"]).unwrap();
2168 assert_eq!(tags(system), ["de-DE", "en-US", "fr"]);
2169 assert_eq!(system.first().as_str(), "de-DE");
2170 assert_eq!(Languages::parse(["C", ""]), None);
2171 let many: Vec<String> = (0..20)
2172 .map(|i| format!("x{}", (b'a' + i) as char))
2173 .collect();
2174 let many = Languages::parse(many.iter().map(String::as_str)).unwrap();
2175 assert_eq!(many.as_slice().len(), Languages::CAPACITY);
2176 let fr = Locale::parse("fr").unwrap();
2177 assert_eq!(tags(system.preferring(fr)), ["fr", "de-DE", "en-US"]);
2178 let ja = Locale::parse("ja-JP").unwrap();
2179 assert_eq!(
2180 tags(system.preferring(ja)),
2181 ["ja-JP", "de-DE", "en-US", "fr"]
2182 );
2183 assert_eq!(tags(Languages::default()), ["en-US"]);
2184 let mut env = Environment::default();
2186 env.locale_settings.languages = system;
2187 HostEnvironment {
2188 locale: Some(ja),
2189 font_scale: None,
2190 }
2191 .apply(&mut env);
2192 assert_eq!(
2193 tags(env.locale_settings.languages),
2194 ["ja-JP", "de-DE", "en-US", "fr"]
2195 );
2196 }
2197
2198 #[test]
2199 fn locales_parse_platform_identifiers() {
2200 let tag = |s: &str| Locale::parse(s).map(|l| l.as_str().to_owned());
2201 assert_eq!(tag("en_US").as_deref(), Some("en-US"));
2202 assert_eq!(tag("zh-hans_cn").as_deref(), Some("zh-Hans-CN"));
2203 assert_eq!(tag("de_DE@calendar=gregorian").as_deref(), Some("de-DE"));
2204 assert_eq!(tag("pt_BR.UTF-8").as_deref(), Some("pt-BR"));
2205 assert_eq!(tag("es-419").as_deref(), Some("es-419"));
2206 assert_eq!(tag("en-US-u-hc-h23").as_deref(), Some("en-US"));
2207 assert_eq!(tag("C"), None);
2208 assert_eq!(Locale::default().as_str(), "en-US");
2209 let zh = Locale::parse("zh-Hans-CN").unwrap();
2210 assert_eq!((zh.language(), zh.region()), ("zh", Some("CN")));
2211 assert_eq!(Locale::parse("zh-Hans").unwrap().region(), None);
2212 assert_eq!(Locale::parse("es-419").unwrap().region(), Some("419"));
2213 }
2214
2215 #[test]
2216 fn regional_preferences_are_the_regions_unless_the_locale_sets_others() {
2217 type Regional = (HourCycle, Weekday, MeasurementSystem, TemperatureUnit);
2219 let regional = |s: LocaleSettings| -> Regional {
2220 (
2221 s.hour_cycle,
2222 s.first_day_of_week,
2223 s.measurement_system,
2224 s.temperature_unit,
2225 )
2226 };
2227 let of = |tag: &str| LocaleSettings::of(Locale::parse(tag).unwrap());
2228 let us = regional(LocaleSettings::default());
2229 let world = (
2230 HourCycle::H23,
2231 Weekday::Monday,
2232 MeasurementSystem::Metric,
2233 TemperatureUnit::Celsius,
2234 );
2235 assert_eq!(regional(of("en-US")), us);
2236 assert_eq!(
2237 LocaleSettings::default().languages.as_slice(),
2238 &[Locale::EN_US]
2239 );
2240 assert_eq!(LocaleSettings::default().time_zone, TimeZone::UTC);
2241 assert_eq!(
2243 of("de-DE").languages.as_slice(),
2244 &[Locale::parse("de-DE").unwrap()]
2245 );
2246 assert_eq!(regional(of("de-DE")), world);
2247 assert_eq!(regional(of("ja")), world);
2249 assert_eq!(of("en-CA").hour_cycle, HourCycle::H12);
2250 assert_eq!(of("fr-CA").hour_cycle, HourCycle::H23);
2252 assert_eq!(of("fr-CA").first_day_of_week, Weekday::Sunday);
2253 assert_eq!(of("en-001").hour_cycle, HourCycle::H12);
2254 assert_eq!(of("es-419").hour_cycle, HourCycle::H12);
2255 assert_eq!(of("ar-EG").first_day_of_week, Weekday::Saturday);
2256 assert_eq!(of("dv-MV").first_day_of_week, Weekday::Friday);
2257 let gb = of("en-GB");
2258 assert_eq!(gb.measurement_system, MeasurementSystem::Uk);
2259 assert_eq!(gb.temperature_unit, TemperatureUnit::Celsius);
2260 assert_eq!(of("en-LR").temperature_unit, TemperatureUnit::Celsius);
2261 assert_eq!(of("es-PR").temperature_unit, TemperatureUnit::Fahrenheit);
2262
2263 let parse = |identifier: &str| regional(LocaleSettings::parse(identifier));
2264 assert_eq!(
2265 parse("en-US-u-fw-mon-mu-celsius"),
2266 (
2267 HourCycle::H12,
2268 Weekday::Monday,
2269 MeasurementSystem::Us,
2270 TemperatureUnit::Celsius
2271 )
2272 );
2273 assert_eq!(
2274 parse("en_US@hours=h23;measure=metric"),
2275 (
2276 HourCycle::H23,
2277 Weekday::Sunday,
2278 MeasurementSystem::Metric,
2279 TemperatureUnit::Fahrenheit
2280 )
2281 );
2282 assert_eq!(parse("en_US@rg=gbzzzz"), regional(gb));
2283 assert_eq!(
2284 parse("ar-u-ca-islamic-umalqura-hc-h11-rg-uszzzz"),
2285 (HourCycle::H11, us.1, us.2, us.3)
2286 );
2287 assert_eq!(
2288 LocaleSettings::parse("en-GB-u-ms-ussystem-mu-fahrenhe").measurement_system,
2289 MeasurementSystem::Us
2290 );
2291 assert_eq!(parse("de_DE.UTF-8@fw=xyz;hours=h99;rg=1"), world);
2293 assert_eq!(parse("en-US-x-hc-h23"), us);
2294 assert_eq!(parse("C"), world);
2295 assert_eq!(
2297 LocaleSettings::parse("de_DE.UTF-8").languages.as_slice(),
2298 &[Locale::parse("de-DE").unwrap()]
2299 );
2300 assert_eq!(
2301 LocaleSettings::parse("C").languages.as_slice(),
2302 &[Locale::EN_US]
2303 );
2304 assert_eq!(Weekday::from_number(7), Some(Weekday::Sunday));
2305 assert_eq!(Weekday::from_number(0), None);
2306 assert_eq!(Weekday::Monday.number(), 1);
2307 assert!(HourCycle::H11.twelve_hour() && !HourCycle::H24.twelve_hour());
2308 assert_eq!(HourCycle::of_pattern("h:mm a"), Some(HourCycle::H12));
2309 assert_eq!(HourCycle::of_pattern("HH 'Uhr'"), Some(HourCycle::H23));
2310 assert_eq!(HourCycle::of_pattern("'h' K:mm"), Some(HourCycle::H11));
2311 assert_eq!(HourCycle::of_pattern("mm:ss"), None);
2312 }
2313
2314 #[test]
2315 fn time_zones_parse_platform_identifiers() {
2316 let zone = |s: &str| TimeZone::parse(s).map(|z| z.as_str().to_owned());
2317 assert_eq!(zone("Europe/Berlin").as_deref(), Some("Europe/Berlin"));
2318 assert_eq!(zone(":Asia/Tokyo").as_deref(), Some("Asia/Tokyo"));
2319 assert_eq!(
2320 zone("/var/db/timezone/zoneinfo/America/Argentina/Buenos_Aires").as_deref(),
2321 Some("America/Argentina/Buenos_Aires")
2322 );
2323 assert_eq!(
2324 zone("/usr/share/zoneinfo/Etc/GMT+5").as_deref(),
2325 Some("Etc/GMT+5")
2326 );
2327 assert_eq!(zone("GMT+01:00").as_deref(), Some("GMT+01:00"));
2328 assert_eq!(
2329 zone("America/Argentina/ComodRivadavia").as_deref(),
2330 Some("America/Argentina/ComodRivadavia")
2331 );
2332 assert_eq!(zone(""), None);
2333 assert_eq!(zone("Europe//Berlin"), None);
2334 assert_eq!(zone("../etc/passwd"), None);
2335 assert_eq!(zone("Central European Standard Time"), None);
2336 let parts = ["Abcdefghijklmn"; 4].join("/");
2337 assert_eq!(zone(&parts).as_deref(), Some(parts.as_str()));
2338 assert_eq!(zone(&"A".repeat(64)), None);
2339 assert_eq!(TimeZone::default().as_str(), "UTC");
2340 assert_eq!(
2341 Environment::default().locale_settings.time_zone,
2342 TimeZone::UTC
2343 );
2344 }
2345
2346 #[test]
2347 fn posix_time_zones_follow_the_zone_tz_names() {
2348 let singapore = || TimeZone::parse("Asia/Singapore");
2350 let zone = |tz: Option<&str>| TimeZone::posix(tz, singapore).as_str().to_owned();
2351 assert_eq!(zone(Some("GMT")), "GMT");
2353 assert_eq!(
2354 TimeZone::posix(Some("GMT"), || unreachable!("TZ names the zone")).as_str(),
2355 "GMT"
2356 );
2357 for name in [
2359 "UTC",
2360 "EST",
2361 "Japan",
2362 "NZ-CHAT",
2363 "Etc/GMT+5",
2364 "Europe/Berlin",
2365 "EST5EDT",
2366 "GMT0",
2367 "GMT-0",
2368 ] {
2369 assert_eq!(zone(Some(name)), name);
2370 assert_eq!(zone(Some(&format!(":{name}"))), name);
2371 }
2372 assert_eq!(zone(Some(":/usr/share/zoneinfo/Asia/Tokyo")), "Asia/Tokyo");
2373 assert_eq!(zone(Some("")), "UTC");
2375 for tz in [
2377 "JST-9",
2378 "EST5",
2379 "CET-1CEST",
2380 "<+08>-8",
2381 "CET-1CEST,M3.5.0,M10.5.0/3",
2382 "GMT+01:00",
2383 ":/etc/localtime",
2384 ":",
2385 ] {
2386 assert_eq!(zone(Some(tz)), "Asia/Singapore", "TZ={tz}");
2387 }
2388 assert_eq!(zone(None), "Asia/Singapore");
2389 assert_eq!(TimeZone::posix(None, || None), TimeZone::UTC);
2390 }
2391
2392 #[test]
2393 fn content_types_follow_the_extension_of_paths_and_asset_urls() {
2394 assert_eq!(
2395 content_type("dist/app.js"),
2396 "text/javascript; charset=utf-8"
2397 );
2398 assert_eq!(content_type("nsh.WASM"), "application/wasm");
2399 assert_eq!(
2400 content_type("asset:/@app/locales/en.json"),
2401 "application/json"
2402 );
2403 assert_eq!(content_type("asset:/images/flag@2x.png"), "image/png");
2404 assert_eq!(content_type("asset:/fonts/Inter.woff2"), "font/woff2");
2405 assert_eq!(content_type("asset:/sounds/chime.OGG"), "audio/ogg");
2406 for unknown in ["asset:/data.bin", "asset:/README", "asset:/.png"] {
2407 assert_eq!(
2408 content_type(unknown),
2409 "application/octet-stream",
2410 "{unknown}"
2411 );
2412 }
2413 }
2414
2415 #[test]
2416 fn file_mime_types_come_from_the_name_alone() {
2417 assert_eq!(file_mime_type("file:///tmp/a%20b.PNG"), "image/png");
2418 assert_eq!(file_mime_type("file:///tmp/%E4%B8%AD.jpeg"), "image/jpeg");
2419 assert_eq!(file_mime_type("/Users/me/Report.pdf"), "application/pdf");
2420 assert_eq!(
2421 file_mime_type("file:///tmp/notes.md?x=1#y"),
2422 "text/markdown"
2423 );
2424 assert_eq!(file_mime_type("C:/Users/me/Clip.mov"), "video/quicktime");
2425 for none in [
2427 "file:///tmp/photos.d/",
2428 "file:///tmp/README",
2429 "file:///tmp/.env",
2430 "file:///tmp/a.unknownext",
2431 "",
2432 ] {
2433 assert_eq!(file_mime_type(none), "", "{none}");
2434 }
2435 }
2436}
2437
2438pub fn warn_unsupported(backend: &str, command: &dyn std::fmt::Debug) {
2446 use std::{
2447 collections::HashSet,
2448 sync::{Mutex, OnceLock},
2449 };
2450
2451 static SEEN: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
2452 let debug = format!("{command:?}");
2453 let key = format!("{backend}:{}", unsupported_kind(&debug));
2454 let seen = SEEN.get_or_init(Default::default);
2455 if seen
2456 .lock()
2457 .map(|mut seen| seen.insert(key))
2458 .unwrap_or(false)
2459 {
2460 log::warn!(
2461 "{backend}: {} is not supported on this platform and is ignored",
2462 unsupported_kind(&debug)
2463 );
2464 }
2465}
2466
2467fn unsupported_kind(debug: &str) -> &str {
2469 let mut end = 0;
2470 let bytes = debug.as_bytes();
2471 let mut i = 0;
2472 for _ in 0..2 {
2474 let start = i;
2475 if !bytes.get(i).is_some_and(u8::is_ascii_uppercase) {
2477 break;
2478 }
2479 while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
2480 i += 1;
2481 }
2482 if i == start {
2483 break;
2484 }
2485 end = i;
2486 if i < bytes.len() && bytes[i] == b'(' {
2487 i += 1;
2488 } else {
2489 break;
2490 }
2491 }
2492 if end == 0 { debug } else { &debug[..end] }
2493}
2494
2495#[cfg(test)]
2496mod unsupported_tests {
2497 use super::unsupported_kind;
2498
2499 #[test]
2500 fn kind_is_the_variant_chain() {
2501 assert_eq!(
2502 unsupported_kind("Desktop(SetAttributes(Foo { a: 1 }))"),
2503 "Desktop(SetAttributes"
2504 );
2505 assert_eq!(unsupported_kind("Share { text: \"x\" }"), "Share");
2506 assert_eq!(unsupported_kind("Vibrate(12)"), "Vibrate");
2507 assert_eq!(unsupported_kind("Quit"), "Quit");
2508 }
2509}