Skip to main content

nsh_core/
web_resource.rs

1//! Resources a web view's page loads from the app: the URLs of a scheme the
2//! app serves ([`WebView::url_scheme`](crate::element::WebView::url_scheme)),
3//! answered by the app's handler with bytes and a MIME type.
4//!
5//! The page refers to them as to any subresource
6//! (`<img src="app-image://img/1">`, `fetch("app-image://img/1")`), and the
7//! platform's web engine loads them through
8//! its own scheme handler (WebKit's `WKURLSchemeHandler` on iOS and macOS,
9//! `webkit_web_context_register_uri_scheme` on Linux, WebView2's custom
10//! scheme registrations and `WebResourceRequested` on Windows, which
11//! registers an app's schemes once, with its first web views): the bytes
12//! reach the page's process as they are, without being encoded into a
13//! script or a `data:` URL and without waiting behind the page's scripts.
14//!
15//! The platform calls the handler on its main thread, with a
16//! [`WebResourceRequest`] the app answers then or later, from any thread
17//! ([`WebResourceRequest::respond`], [`WebResourceRequest::fail`]): the
18//! handler returns at once and hands slow work (a file read, a decode) to
19//! a thread of its own. A request dropped unanswered fails, so the page
20//! never waits for an answer that cannot come. When the page no longer
21//! needs a resource (it navigated away, the web view went), the platform
22//! cancels the request ([`WebResourceRequest::is_cancelled`]), and an
23//! answer given after that is dropped.
24//!
25//! The schemes are read when the platform makes the web view, as
26//! `incognito` is: a web view serves the schemes of its first props.
27//!
28//! URLs of the form `scheme://host/path` reach the handler as the page
29//! wrote them on every platform. Windows reads a scheme's URLs as it reads
30//! `https` ones, so that pages may `fetch` them: there `scheme:name/rest`
31//! arrives as `scheme://name/rest`, its first segment a host in lower case.
32
33use std::{
34    fmt,
35    sync::{
36        Arc,
37        atomic::{AtomicBool, Ordering},
38    },
39};
40
41/// The function that answers a scheme's requests.
42type Handler = dyn Fn(WebResourceRequest) + Send + Sync;
43
44/// What a request's platform does with its answer: the resource, or
45/// `None` when it failed.
46type Respond = Box<dyn FnOnce(Option<WebResource>) + Send>;
47
48/// A URL scheme a web view serves from the app: its name and the handler
49/// that answers its requests. Platform plumbing: apps use
50/// [`WebView::url_scheme`](crate::element::WebView::url_scheme).
51#[doc(hidden)]
52#[derive(Clone)]
53pub struct WebUrlScheme {
54    scheme: Arc<str>,
55    handler: Arc<Handler>,
56}
57
58impl WebUrlScheme {
59    /// The scheme `scheme` (`"app-image"`, without the colon), answered by
60    /// `handler`. A scheme is a letter followed by letters, digits, `+`,
61    /// `-` or `.`, and none of those the web engine or the system own
62    /// (`http`, `https`, `file`, `data`, `blob`, `about`, ...); it is kept
63    /// in lower case. The error says what is wrong.
64    pub fn new(
65        scheme: &str,
66        handler: impl Fn(WebResourceRequest) + Send + Sync + 'static,
67    ) -> Result<Self, String> {
68        crate::url_scheme::check_scheme(scheme)?;
69        Ok(Self {
70            scheme: scheme.to_ascii_lowercase().into(),
71            handler: Arc::new(handler),
72        })
73    }
74
75    /// The scheme, in lower case, without the colon.
76    pub fn scheme(&self) -> &str {
77        &self.scheme
78    }
79
80    /// Answers `request` with the app's handler (for the platforms, on
81    /// their main thread).
82    pub fn handle(&self, request: WebResourceRequest) {
83        (self.handler)(request);
84    }
85}
86
87impl PartialEq for WebUrlScheme {
88    fn eq(&self, other: &Self) -> bool {
89        self.scheme == other.scheme && Arc::ptr_eq(&self.handler, &other.handler)
90    }
91}
92
93impl fmt::Debug for WebUrlScheme {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        f.debug_tuple("WebUrlScheme").field(&self.scheme).finish()
96    }
97}
98
99/// What a scheme's URL serves: its bytes and their MIME type.
100#[derive(Debug, Clone, Default, PartialEq, Eq)]
101#[non_exhaustive]
102pub struct WebResource {
103    /// The MIME type (`"image/png"`); an empty one is
104    /// `application/octet-stream`.
105    pub mime_type: Arc<str>,
106    /// The bytes.
107    pub bytes: Arc<[u8]>,
108}
109
110impl WebResource {
111    /// `bytes` of the MIME type `mime_type`.
112    pub fn new(mime_type: impl Into<Arc<str>>, bytes: impl Into<Arc<[u8]>>) -> Self {
113        Self {
114            mime_type: mime_type.into(),
115            bytes: bytes.into(),
116        }
117    }
118
119    /// The MIME type the platform answers with:
120    /// `application/octet-stream` when none is set, or when it has control
121    /// characters, which no MIME type has and which would end the response's
122    /// header line.
123    #[doc(hidden)]
124    pub fn mime_type_or_default(&self) -> &str {
125        if self.mime_type.is_empty() {
126            "application/octet-stream"
127        } else if self.mime_type.chars().any(char::is_control) {
128            log::warn!(
129                "web view: the MIME type {:?} has control characters; answering application/octet-stream",
130                self.mime_type
131            );
132            "application/octet-stream"
133        } else {
134            &self.mime_type
135        }
136    }
137}
138
139/// A request of the page for a URL of a scheme the app serves. It is
140/// answered once, by [`respond`](Self::respond) or [`fail`](Self::fail),
141/// from any thread; dropped unanswered, it fails.
142pub struct WebResourceRequest {
143    url: String,
144    method: String,
145    cancelled: Arc<AtomicBool>,
146    respond: Option<Respond>,
147}
148
149impl WebResourceRequest {
150    /// A request for `url` with the HTTP method `method` (`"GET"`), for the
151    /// platforms: `respond` takes its answer (from whichever thread the app
152    /// answers on; `None` when it failed), and the [`WebResourceCancel`]
153    /// cancels it when the page no longer needs it.
154    #[doc(hidden)]
155    pub fn new(
156        url: impl Into<String>,
157        method: impl Into<String>,
158        respond: impl FnOnce(Option<WebResource>) + Send + 'static,
159    ) -> (Self, WebResourceCancel) {
160        let cancelled = Arc::new(AtomicBool::new(false));
161        let request = Self {
162            url: url.into(),
163            method: method.into(),
164            cancelled: cancelled.clone(),
165            respond: Some(Box::new(respond)),
166        };
167        (request, WebResourceCancel(cancelled))
168    }
169
170    /// The URL requested (`app-image://img/1`), as the page's engine
171    /// resolved it.
172    pub fn url(&self) -> &str {
173        &self.url
174    }
175
176    /// The HTTP method (`"GET"` for images and most loads).
177    pub fn method(&self) -> &str {
178        &self.method
179    }
180
181    /// Whether the page no longer needs it (it navigated away, the web view
182    /// went): work for it can stop, and an answer is dropped.
183    pub fn is_cancelled(&self) -> bool {
184        self.cancelled.load(Ordering::Acquire)
185    }
186
187    /// Answers with `resource`.
188    pub fn respond(mut self, resource: WebResource) {
189        self.finish(Some(resource));
190    }
191
192    /// Answers that there is nothing there: the page's load fails (an
193    /// image's `error` event, a rejected `fetch`).
194    pub fn fail(mut self) {
195        self.finish(None);
196    }
197
198    fn finish(&mut self, resource: Option<WebResource>) {
199        if let Some(respond) = self.respond.take()
200            && !self.is_cancelled()
201        {
202            respond(resource);
203        }
204    }
205}
206
207impl Drop for WebResourceRequest {
208    fn drop(&mut self) {
209        self.finish(None);
210    }
211}
212
213impl fmt::Debug for WebResourceRequest {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        f.debug_struct("WebResourceRequest")
216            .field("url", &self.url)
217            .field("method", &self.method)
218            .field("cancelled", &self.is_cancelled())
219            .finish()
220    }
221}
222
223/// Cancels a [`WebResourceRequest`] (the platform's side of it). Platform
224/// plumbing, not for apps.
225#[doc(hidden)]
226#[derive(Debug, Clone)]
227pub struct WebResourceCancel(Arc<AtomicBool>);
228
229impl WebResourceCancel {
230    /// The page no longer needs the resource: the request reports it, and
231    /// its answer is dropped.
232    pub fn cancel(&self) {
233        self.0.store(true, Ordering::Release);
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use std::sync::Mutex;
240
241    use super::*;
242
243    fn new_request() -> (
244        WebResourceRequest,
245        WebResourceCancel,
246        Arc<Mutex<Vec<Option<WebResource>>>>,
247    ) {
248        let answers = Arc::new(Mutex::new(Vec::new()));
249        let (request, cancel) = WebResourceRequest::new("app-image://img/1", "GET", {
250            let answers = answers.clone();
251            move |answer| answers.lock().unwrap().push(answer)
252        });
253        (request, cancel, answers)
254    }
255
256    #[test]
257    fn checks_schemes() {
258        let scheme = WebUrlScheme::new("App-Image", |_| {}).unwrap();
259        assert_eq!(scheme.scheme(), "app-image");
260        assert!(WebUrlScheme::new("https", |_| {}).is_err());
261        assert!(WebUrlScheme::new("data", |_| {}).is_err());
262        assert!(WebUrlScheme::new("1app", |_| {}).is_err());
263        assert!(WebUrlScheme::new("app image", |_| {}).is_err());
264        assert_eq!(scheme, scheme.clone());
265        assert_ne!(scheme, WebUrlScheme::new("app-image", |_| {}).unwrap());
266    }
267
268    #[test]
269    fn answers_once() {
270        let (request, _cancel, answers) = new_request();
271        assert_eq!(request.url(), "app-image://img/1");
272        assert_eq!(request.method(), "GET");
273        let resource = WebResource::new("image/png", vec![1, 2, 3]);
274        std::thread::spawn(move || request.respond(resource))
275            .join()
276            .unwrap();
277        let answers = answers.lock().unwrap();
278        assert_eq!(answers.len(), 1);
279        let resource = answers[0].as_ref().unwrap();
280        assert_eq!(resource.mime_type_or_default(), "image/png");
281        assert_eq!(&*resource.bytes, &[1, 2, 3]);
282    }
283
284    #[test]
285    fn fails_when_dropped_or_failed() {
286        let (request, _cancel, answers) = new_request();
287        drop(request);
288        let (request, _cancel, failed) = new_request();
289        request.fail();
290        assert_eq!(*answers.lock().unwrap(), vec![None]);
291        assert_eq!(*failed.lock().unwrap(), vec![None]);
292    }
293
294    #[test]
295    fn drops_answers_once_cancelled() {
296        let (request, cancel, answers) = new_request();
297        cancel.cancel();
298        assert!(request.is_cancelled());
299        request.respond(WebResource::default());
300        assert!(answers.lock().unwrap().is_empty());
301        assert_eq!(
302            WebResource::default().mime_type_or_default(),
303            "application/octet-stream"
304        );
305        assert_eq!(
306            WebResource::new("text/html\r\nSet-Cookie: a=b", vec![]).mime_type_or_default(),
307            "application/octet-stream"
308        );
309    }
310}