1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
//! Image information and loading ahead, the functions of `nsh`'s `Image`
//! (`nsh-js` makes it the image element's component). A URL the
//! app's `network` capability does not grant rejects with
//! `ERR_ACCESS_DENIED` (checked here, in the call, as the core checks the
//! loads of Rust components' calls).
use crate::{
ImageScales, ImageSource,
element::{
ImageSize, JsError, JsHost, JsIn, JsKind, JsOwned, JsValue, PropError, System, TsTypes,
module,
},
geometry::DevicePixels,
};
/// Image information and loading ahead.
#[module]
pub(crate) struct Image;
/// An image's address: a string or an imported image (`ImageAsset`, with
/// the `scales` of its variants).
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ImageUrl {
url: String,
scales: ImageScales,
size: Option<ImageSize>,
}
impl ImageUrl {
/// The URL the views load at the surface's pixel ratio, and the scale
/// of that variant (1 for the URL itself).
fn pick(self) -> (String, f32) {
let source = ImageSource {
uri: self.url.into(),
size: None,
scales: self.scales,
data: None,
};
let ratio = crate::prelude::pixel_ratio();
let scale = source.variant(ratio).unwrap_or(1.0);
(source.uri_for(ratio).to_string(), scale)
}
}
impl JsValue for ImageUrl {
fn ts_type(_types: &mut TsTypes) -> String {
"string | ImageAsset".into()
}
fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
if let Some(url) = value.as_string() {
return Ok(Self {
url,
scales: ImageScales::NONE,
size: None,
});
}
if value.kind() == JsKind::Object
&& let Some(url) = value.field("url")?.get().as_string()
{
let list = value.field("scales")?;
let list = list.get();
let mut scales = ImageScales::NONE;
let len = list.array_len()?.unwrap_or(0);
for i in 0..len.min(crate::ops::SCALES_READ) {
if let Some(n) = list.index(i)?.get().as_number() {
scales = scales.with(n as f32);
}
}
// Only variant assets use the imported file's dimensions.
// Plain sources keep reporting the loaded file's pixels.
let size =
if !scales.is_empty() && url.starts_with("asset:/") && !url.contains(['?', '#']) {
let extent = value.field("size")?;
let extent = extent.get();
let dimension = |key| -> Result<Option<DevicePixels>, PropError> {
if extent.kind() != JsKind::Object {
return Ok(None);
}
Ok(extent
.field(key)?
.get()
.as_number()
.filter(|n| n.is_finite() && *n > 0.0 && *n <= f64::from(i32::MAX))
.map(|n| DevicePixels(n.round() as i32)))
};
dimension("width")?
.zip(dimension("height")?)
.map(|(width, height)| ImageSize { width, height })
} else {
None
};
return Ok(Self { url, scales, size });
}
Err(value.expected("a URL or an imported image"))
}
fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
Ok(JsOwned::new(host, host.new_string(&self.url)?))
}
}
#[module]
impl Image {
/// The image's size in pixels; its bytes stay loaded for the views that
/// show it next. An imported image with variants loads the variant the
/// views load and resolves with the imported file's size. Without
/// dimensions, it falls back to the variant's pixels over its scale.
/// Rejects when the image cannot load, with `ERR_ACCESS_DENIED` when
/// the `network` capability does not grant its URL.
pub(crate) async fn get_size(src: ImageUrl, sys: System) -> Result<ImageSize, JsError> {
let imported_size = src.size;
let (url, scale) = src.pick();
granted(&sys, &url)?;
let size = crate::prelude::image_size(url)
.await
.map_err(JsError::Error)?;
if let Some(size) = imported_size {
return Ok(size);
}
let unscaled = |px: DevicePixels| DevicePixels((px.0 as f32 / scale).round() as i32);
Ok(ImageSize {
width: unscaled(size.width),
height: unscaled(size.height),
})
}
/// Loads the image ahead of showing it: resolves once its bytes are in
/// memory, rejects with the error when it cannot load
/// (`ERR_ACCESS_DENIED` when the `network` capability does not grant
/// its URL). An imported image with variants loads the variant the
/// views load at the screen's pixel ratio.
pub(crate) async fn prefetch(src: ImageUrl, sys: System) -> Result<(), JsError> {
let url = src.pick().0;
granted(&sys, &url)?;
crate::prelude::prefetch_image(url)
.await
.map_err(JsError::Error)
}
}
/// Whether the app may load the image at `url`: why not when it may not.
fn granted(sys: &System, url: &str) -> Result<(), JsError> {
if sys.access.allows_media(url) {
return Ok(());
}
let host = crate::access::parse_url(url).map_or_else(|| url.to_owned(), |u| u.host);
Err(JsError::access_denied(
format!(
"Image.getSize / prefetch of {url} is not granted: add `{host}` to capabilities.network in nsh.json"
),
"network",
url,
))
}