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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//! 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). A `blob:` URL's bytes are in the VM already: its size is read from
//! their header here, without the platform.
use crate::{
ImageData, 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>,
/// The bytes of a `blob:` URL (`URL.createObjectURL`).
blob: Option<ImageData>,
}
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() {
let blob = match url.starts_with("blob:") {
true => value.host().image_blob(&url).map(|(_, data)| data),
false => None,
};
return Ok(Self {
url,
scales: ImageScales::NONE,
size: None,
blob,
});
}
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,
blob: None,
});
}
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> {
if let Some(data) = &src.blob {
return blob_size(&src.url, data);
}
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> {
if src.blob.is_some() {
return Ok(());
}
let url = src.pick().0;
granted(&sys, &url)?;
crate::prelude::prefetch_image(url)
.await
.map_err(JsError::Error)
}
}
/// The size the header of a `blob:` URL's image gives.
fn blob_size(url: &str, data: &ImageData) -> Result<ImageSize, JsError> {
let size = crate::picker::image_size(data.bytes()).ok_or_else(|| {
JsError::Error(format!(
"Image.getSize: {url} is not an image whose header gives its size \
(PNG, JPEG, GIF, WebP, HEIC, AVIF, TIFF, BMP)"
))
})?;
Ok(ImageSize {
width: size.width,
height: size.height,
})
}
/// The VM's roots its local images are read under, resolved the first time
/// a call names a source ([`crate::access::MediaFiles`]).
#[derive(Default)]
struct Files(std::cell::OnceCell<crate::access::MediaFiles>);
impl crate::element::Local for Files {}
/// Whether the app may load the image at `url`, as the core checks the
/// `Command::ImageInfo` it sends (against the same base): why not when it
/// may not.
fn granted(sys: &System, url: &str) -> Result<(), JsError> {
// An app without capabilities reads local files unchecked: no roots to
// resolve (`media_url` answers it before it looks at them).
let files = (!sys.access.is_unrestricted()).then(|| sys.locals.get::<Files>());
let files = files.as_ref().map(|files| {
files.0.get_or_init(|| {
let available = crate::access::native_files(sys.os);
crate::access::MediaFiles::new(
&sys.access,
sys.data_dir.as_deref(),
&sys.paths,
available,
)
})
});
if sys
.access
.media_url(url, sys.base_url.as_deref(), files)
.is_some()
{
return Ok(());
}
let base = sys.base_url.as_deref();
let advice = crate::access::media_grant_advice(url, base);
Err(JsError::access_denied(
format!("Image.getSize / prefetch of {url} is not granted: {advice}"),
crate::access::media_capability(url, base),
url,
))
}