Skip to main content

day_piece_webview/
browsing.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! What a page asks of the app around it, and what the engine tells the app about a page: script
5//! dialogs, HTTP sign-in, file choosing, downloads, failed loads and a lost page process
6//! (docs/webview.md "Browser duties").
7//!
8//! A backend reports a question on the node's `Event::Custom` channel (`PAGE_PROMPT`, a JSON
9//! [`PromptReport`]) and holds the engine's callback until the answer returns as
10//! [`crate::WebPatch::PromptAnswer`]. One-way reports (`PAGE_NOTICE`, a JSON [`Notice`]) need no
11//! answer. A download outlives the view that started it, so its progress does not use the node
12//! at all: backends call [`download_event`] and the app's callback is kept here by id.
13
14use std::cell::RefCell;
15use std::collections::HashMap;
16use std::path::{Path, PathBuf};
17use std::rc::Rc;
18
19use serde::{Deserialize, Serialize};
20
21/// The `num` that tags a question a page or the engine asks: a JSON [`PromptReport`].
22pub(crate) const PAGE_PROMPT: f64 = -11.0;
23/// The `num` that tags a one-way report: a JSON [`Notice`].
24pub(crate) const PAGE_NOTICE: f64 = -12.0;
25
26// ---------------------------------------------------------------------------
27// Reports, as backends compose them
28// ---------------------------------------------------------------------------
29
30/// A question from a backend. Every arm carries the `id` its answer is keyed by.
31#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
32#[serde(tag = "kind", rename_all = "kebab-case")]
33pub(crate) enum PromptReport {
34    /// `alert()`, `confirm()` or `prompt()`.
35    Dialog {
36        id: u64,
37        dialog: DialogKind,
38        #[serde(default)]
39        message: String,
40        #[serde(default)]
41        default_text: String,
42        /// The address of the frame that asked.
43        #[serde(default)]
44        url: String,
45    },
46    /// An HTTP Basic, Digest or NTLM challenge.
47    Auth {
48        id: u64,
49        #[serde(default)]
50        host: String,
51        #[serde(default)]
52        realm: String,
53        #[serde(default)]
54        proxy: bool,
55        #[serde(default)]
56        failures: u32,
57    },
58    /// `<input type=file>` on an engine with no chooser of its own (Android).
59    Files {
60        id: u64,
61        #[serde(default)]
62        accept: Vec<String>,
63        #[serde(default)]
64        multiple: bool,
65    },
66    /// A response the engine will not show, or a link marked `download`.
67    Download {
68        id: u64,
69        #[serde(default)]
70        url: String,
71        #[serde(default)]
72        name: String,
73        #[serde(default)]
74        mime: String,
75        /// The length the server announced, or a negative number for none.
76        #[serde(default = "unknown_size")]
77        size: i64,
78    },
79}
80
81fn unknown_size() -> i64 {
82    -1
83}
84
85/// A one-way report from a backend.
86#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
87#[serde(tag = "kind", rename_all = "kebab-case")]
88pub(crate) enum Notice {
89    LoadError {
90        #[serde(default)]
91        url: String,
92        error: LoadErrorKind,
93        #[serde(default)]
94        code: i64,
95        #[serde(default)]
96        text: String,
97    },
98    RendererGone {
99        #[serde(default)]
100        crashed: bool,
101    },
102}
103
104/// A prompt as an event, for the arms that emit from Rust.
105#[allow(
106    dead_code,
107    reason = "only the Apple arms emit prompts from Rust; the others emit from Java, C++ or JS"
108)]
109pub(crate) fn prompt_event(report: &PromptReport) -> day_spec::Event {
110    day_spec::Event::Custom {
111        tag: "webview:prompt",
112        num: PAGE_PROMPT,
113        text: serde_json::to_string(report).unwrap_or_default(),
114    }
115}
116
117/// A notice as an event, for the arms that emit from Rust.
118#[allow(
119    dead_code,
120    reason = "only the Apple arms emit notices from Rust; the others emit from Java, C++ or JS"
121)]
122pub(crate) fn notice_event(notice: &Notice) -> day_spec::Event {
123    day_spec::Event::Custom {
124        tag: "webview:notice",
125        num: PAGE_NOTICE,
126        text: serde_json::to_string(notice).unwrap_or_default(),
127    }
128}
129
130/// The answer to a prompt, as it crosses to a backend in [`crate::WebPatch::PromptAnswer`].
131/// `ok: false` cancels whatever was asked; the other fields are the arm's own.
132#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
133pub(crate) struct Answer {
134    pub ok: bool,
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub text: Option<String>,
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub user: Option<String>,
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub password: Option<String>,
141    #[serde(default, skip_serializing_if = "Vec::is_empty")]
142    pub paths: Vec<String>,
143    /// A download goes to the user's Downloads under this name, where the backend keeps that
144    /// collection itself (Android).
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub name: Option<String>,
147}
148
149impl Answer {
150    /// Read an answer a backend received; anything unreadable cancels.
151    #[allow(
152        dead_code,
153        reason = "only the Apple arms read an answer in Rust; the others read it in Java, C++ or JS"
154    )]
155    pub(crate) fn parse(json: &str) -> Answer {
156        serde_json::from_str(json).unwrap_or_default()
157    }
158}
159
160/// Sends one answer, once. Dropped unanswered, it cancels: an engine waits on every question it
161/// asks, and a page whose `confirm()` is never answered stays frozen.
162struct Reply {
163    id: u64,
164    send: Option<Box<dyn FnOnce(u64, Answer)>>,
165}
166
167impl Reply {
168    fn answer(&mut self, answer: Answer) {
169        if let Some(send) = self.send.take() {
170            send(self.id, answer);
171        }
172    }
173}
174
175impl Drop for Reply {
176    fn drop(&mut self) {
177        self.answer(Answer::default());
178    }
179}
180
181// ---------------------------------------------------------------------------
182// Script dialogs
183// ---------------------------------------------------------------------------
184
185/// Which of the three script dialogs a page opened.
186#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
187#[serde(rename_all = "kebab-case")]
188pub enum DialogKind {
189    /// `alert(message)`: one button.
190    Alert,
191    /// `confirm(message)`: accept or dismiss.
192    Confirm,
193    /// `prompt(message, default)`: a line of text, or dismiss.
194    Prompt,
195}
196
197/// A script dialog a page opened ([`crate::WebView::on_dialog`]). The page's script waits until
198/// the [`DialogResponder`] answers.
199#[derive(Clone, Debug, PartialEq, Eq)]
200pub struct DialogRequest {
201    pub kind: DialogKind,
202    /// The text the page passed.
203    pub message: String,
204    /// `prompt()`'s second argument; empty for the other two.
205    pub default_text: String,
206    /// The address of the frame that asked, so the dialog can say which site is speaking.
207    pub url: String,
208}
209
210impl DialogRequest {
211    /// The host of the frame that asked, or an empty string for a page with none.
212    pub fn host(&self) -> String {
213        url::Url::parse(&self.url)
214            .ok()
215            .and_then(|u| u.host_str().map(str::to_owned))
216            .unwrap_or_default()
217    }
218}
219
220/// Answers a [`DialogRequest`]. Dropping it dismisses the dialog.
221pub struct DialogResponder(Reply);
222
223impl DialogResponder {
224    /// OK: `alert()` returns, `confirm()` is `true`, `prompt()` gives back its default text.
225    pub fn accept(mut self) {
226        self.0.answer(Answer {
227            ok: true,
228            ..Answer::default()
229        });
230    }
231    /// OK with the text typed into a `prompt()`.
232    pub fn accept_with(mut self, text: impl Into<String>) {
233        self.0.answer(Answer {
234            ok: true,
235            text: Some(text.into()),
236            ..Answer::default()
237        });
238    }
239    /// Cancel: `confirm()` is `false`, `prompt()` is `null`.
240    pub fn dismiss(mut self) {
241        self.0.answer(Answer::default());
242    }
243}
244
245pub(crate) type DialogHandler = Rc<dyn Fn(DialogRequest, DialogResponder)>;
246
247/// Present a script dialog as Day's own alert, confirm or prompt, titled with the site that
248/// asked, and answer the page with what the user chose. It is what a view does when the app
249/// set no [`crate::WebView::on_dialog`]; an app's handler calls it after changing the request
250/// (the address a dialog names, say) or deciding not to suppress it.
251pub fn present_dialog(request: DialogRequest, responder: DialogResponder) {
252    let host = request.host();
253    // A dialog's title is the site and its message the page's text. A page with no host (a
254    // bundled page) has only its text to show.
255    let (title, message) = if host.is_empty() {
256        (request.message.clone(), None)
257    } else {
258        (host, Some(request.message.clone()))
259    };
260    day_core::task(async move {
261        match request.kind {
262            DialogKind::Alert => {
263                let mut dialog = day_pieces::alert(title);
264                if let Some(message) = message {
265                    dialog = dialog.message(message);
266                }
267                dialog.present().await;
268                responder.accept();
269            }
270            DialogKind::Confirm => {
271                let mut dialog = day_pieces::confirm(title);
272                if let Some(message) = message {
273                    dialog = dialog.message(message);
274                }
275                if dialog.present().await {
276                    responder.accept();
277                } else {
278                    responder.dismiss();
279                }
280            }
281            DialogKind::Prompt => {
282                let mut dialog = day_pieces::prompt(title).initial(request.default_text.clone());
283                if let Some(message) = message {
284                    dialog = dialog.message(message);
285                }
286                match dialog.await {
287                    Some(text) => responder.accept_with(text),
288                    None => responder.dismiss(),
289                }
290            }
291        }
292    });
293}
294
295// ---------------------------------------------------------------------------
296// HTTP sign-in
297// ---------------------------------------------------------------------------
298
299/// A server or proxy asking for a name and password ([`crate::WebView::on_auth`]).
300#[derive(Clone, Debug, PartialEq, Eq)]
301pub struct AuthRequest {
302    /// The server, or the proxy when [`AuthRequest::proxy`] is set.
303    pub host: String,
304    /// The realm the server named, which may be empty.
305    pub realm: String,
306    pub proxy: bool,
307    /// How many answers to this challenge the server has refused so far.
308    pub failures: u32,
309}
310
311/// Answers an [`AuthRequest`]. Dropping it cancels the sign-in, and the server's own
312/// "unauthorized" page loads.
313pub struct AuthResponder(Reply);
314
315impl AuthResponder {
316    pub fn sign_in(mut self, user: impl Into<String>, password: impl Into<String>) {
317        self.0.answer(Answer {
318            ok: true,
319            user: Some(user.into()),
320            password: Some(password.into()),
321            ..Answer::default()
322        });
323    }
324    pub fn cancel(mut self) {
325        self.0.answer(Answer::default());
326    }
327}
328
329pub(crate) type AuthHandler = Rc<dyn Fn(AuthRequest, AuthResponder)>;
330
331// ---------------------------------------------------------------------------
332// File choosing (Android; the other engines show the system's chooser themselves)
333// ---------------------------------------------------------------------------
334
335/// The extensions an `<input accept>` list names, for the picker's filter: `.pdf` as given, and
336/// the common extensions behind `image/*`, `video/*`, `audio/*` and a few exact types. An empty
337/// answer means "any file".
338pub(crate) fn accept_extensions(accept: &[String]) -> Vec<&'static str> {
339    const TYPES: &[(&str, &[&str])] = &[
340        (
341            "image/*",
342            &["png", "jpg", "jpeg", "gif", "webp", "heic", "bmp", "svg"],
343        ),
344        ("video/*", &["mp4", "mov", "m4v", "webm", "mkv", "3gp"]),
345        (
346            "audio/*",
347            &["mp3", "m4a", "aac", "wav", "ogg", "flac", "opus"],
348        ),
349        ("image/png", &["png"]),
350        ("image/jpeg", &["jpg", "jpeg"]),
351        ("image/gif", &["gif"]),
352        ("image/webp", &["webp"]),
353        ("application/pdf", &["pdf"]),
354        ("text/plain", &["txt"]),
355        ("text/csv", &["csv"]),
356        ("application/json", &["json"]),
357        ("application/zip", &["zip"]),
358    ];
359    const KNOWN: &[&str] = &[
360        "png", "jpg", "jpeg", "gif", "webp", "heic", "bmp", "svg", "mp4", "mov", "m4v", "webm",
361        "mkv", "3gp", "mp3", "m4a", "aac", "wav", "ogg", "flac", "opus", "pdf", "txt", "csv",
362        "json", "zip", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "xml", "md", "rtf",
363        "epub",
364    ];
365    let mut out: Vec<&'static str> = Vec::new();
366    for entry in accept
367        .iter()
368        .flat_map(|a| a.split(','))
369        .map(|a| a.trim().to_ascii_lowercase())
370    {
371        if entry.is_empty() {
372            continue;
373        }
374        let found: &[&'static str] = match entry.strip_prefix('.') {
375            Some(ext) => match KNOWN.iter().find(|k| **k == ext) {
376                Some(known) => std::slice::from_ref(known),
377                // An extension this table does not know cannot be named statically: any file.
378                None => return Vec::new(),
379            },
380            None => match TYPES.iter().find(|(mime, _)| *mime == entry) {
381                Some((_, extensions)) => extensions,
382                None => return Vec::new(),
383            },
384        };
385        for ext in found {
386            if !out.contains(ext) {
387                out.push(ext);
388            }
389        }
390    }
391    out
392}
393
394/// Show Day's file picker for a page's `<input type=file>` and answer with what was picked.
395fn choose_files(accept: Vec<String>, multiple: bool, mut reply: Reply) {
396    let extensions = accept_extensions(&accept);
397    day_core::task(async move {
398        let picked: Vec<day_pieces::FileUrl> = if multiple {
399            let mut picker = day_pieces::open_files();
400            if !extensions.is_empty() {
401                picker = picker.filter(accept.join(", "), &extensions);
402            }
403            picker.await
404        } else {
405            let mut picker = day_pieces::open_file();
406            if !extensions.is_empty() {
407                picker = picker.filter(accept.join(", "), &extensions);
408            }
409            picker.await.into_iter().collect()
410        };
411        let paths: Vec<String> = picked
412            .iter()
413            .filter_map(day_pieces::FileUrl::local_path)
414            .map(|path| path.display().to_string())
415            .collect();
416        reply.answer(Answer {
417            ok: !paths.is_empty(),
418            paths,
419            ..Answer::default()
420        });
421    });
422}
423
424// ---------------------------------------------------------------------------
425// Downloads
426// ---------------------------------------------------------------------------
427
428/// A file the engine will not show and offers to save instead ([`crate::WebView::on_download`]):
429/// a response with a type no page can display, one the server marked as an attachment, or a link
430/// with the `download` attribute.
431#[derive(Clone, Debug, PartialEq, Eq)]
432pub struct DownloadRequest {
433    /// Identifies the download in [`cancel_download`].
434    pub id: u64,
435    pub url: String,
436    /// The file name the server or the link suggests. It is a name only, never a path, and safe
437    /// to join onto a directory.
438    pub suggested_name: String,
439    /// The MIME type the server gave, which may be empty.
440    pub mime: String,
441    /// The length the server announced.
442    pub size: Option<u64>,
443}
444
445/// How a download is going, as its callback hears it ([`DownloadResponder::save_to`]).
446#[derive(Clone, Debug, PartialEq, Eq)]
447pub enum DownloadEvent {
448    /// Bytes written so far, and the total where the server announced one.
449    Progress { received: u64, total: Option<u64> },
450    /// The whole file is saved. `location` is where: the path it was saved to, or on Android
451    /// a `content://` address in the system's Downloads collection. It is what
452    /// [`open_download`] and [`remove_download`] take.
453    Finished { location: String },
454    /// The download stopped, with the engine's description of why. A canceled download ends
455    /// here too. The partial file is removed.
456    Failed(String),
457}
458
459impl DownloadEvent {
460    /// Whether this is the last event of its download.
461    pub fn is_terminal(&self) -> bool {
462        !matches!(self, DownloadEvent::Progress { .. })
463    }
464}
465
466/// Answers a [`DownloadRequest`]. Dropping it declines the download.
467pub struct DownloadResponder(Reply);
468
469impl DownloadResponder {
470    /// Save the file at `path`, whose directory exists and which names no existing file, and
471    /// hear how it goes. `on_event` runs on the main thread until a terminal event, also after
472    /// the view that started the download is gone.
473    pub fn save_to(mut self, path: impl AsRef<Path>, on_event: impl Fn(&DownloadEvent) + 'static) {
474        DOWNLOADS.with(|d| d.borrow_mut().insert(self.0.id, Rc::new(on_event)));
475        self.0.answer(Answer {
476            ok: true,
477            paths: vec![path.as_ref().display().to_string()],
478            ..Answer::default()
479        });
480    }
481    /// Save the file where the user looks for downloads, under `name` or the next free variant
482    /// of it (`report (2).pdf`): the system's Downloads collection on Android, the app's folder
483    /// in the Files app on iOS (which shows it once the app's `Info.plist` sets
484    /// `UIFileSharingEnabled` and `LSSupportsOpeningDocumentsInPlace`), and the user's Downloads
485    /// folder elsewhere. [`DownloadEvent::Finished`] says where it went.
486    pub fn save_to_downloads(mut self, name: &str, on_event: impl Fn(&DownloadEvent) + 'static) {
487        let name = sanitize_file_name(name, "download");
488        if cfg!(target_os = "android") {
489            DOWNLOADS.with(|d| d.borrow_mut().insert(self.0.id, Rc::new(on_event)));
490            self.0.answer(Answer {
491                ok: true,
492                name: Some(name),
493                ..Answer::default()
494            });
495            return;
496        }
497        match downloads_dir() {
498            Some(dir) if std::fs::create_dir_all(&dir).is_ok() => {
499                self.save_to(unused_path(&dir, &name), on_event);
500            }
501            _ => {
502                on_event(&DownloadEvent::Failed("no Downloads folder".into()));
503                self.cancel();
504            }
505        }
506    }
507    pub fn cancel(mut self) {
508        self.0.answer(Answer::default());
509    }
510}
511
512/// The folder [`DownloadResponder::save_to_downloads`] saves into outside Android: `Downloads`
513/// in the app's Documents on iOS, the user's own Downloads folder on a desktop.
514fn downloads_dir() -> Option<PathBuf> {
515    let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })?;
516    let home = PathBuf::from(home);
517    Some(if cfg!(target_os = "ios") {
518        home.join("Documents").join("Downloads")
519    } else {
520        home.join("Downloads")
521    })
522}
523
524/// Show a finished download ([`DownloadEvent::Finished`]'s `location`) in whatever the system
525/// opens it with: the app that handles its type on Android, the share sheet on iOS (which
526/// previews, saves and sends), the default application on a desktop. `false` when nothing
527/// could be asked to open it. The web backend cannot open native downloaded files and returns
528/// `false`.
529pub fn open_download(location: &str) -> bool {
530    #[cfg(all(target_os = "android", feature = "material"))]
531    return crate::android_impl::open_download(location);
532    #[cfg(target_family = "wasm")]
533    {
534        let _ = location;
535        false
536    }
537    #[cfg(all(
538        not(target_family = "wasm"),
539        not(all(target_os = "android", feature = "material"))
540    ))]
541    {
542        let Ok(url) = url::Url::from_file_path(location) else {
543            return false;
544        };
545        if cfg!(target_os = "ios") {
546            day_pieces::Share::url(url.to_string()).present()
547        } else {
548            day_core::open_url(url.as_str());
549            true
550        }
551    }
552}
553
554/// Delete a finished download from where it was saved.
555pub fn remove_download(location: &str) {
556    #[cfg(all(target_os = "android", feature = "material"))]
557    crate::android_impl::remove_download(location);
558    #[cfg(not(all(target_os = "android", feature = "material")))]
559    let _ = std::fs::remove_file(location);
560}
561
562pub(crate) type DownloadHandler = Rc<dyn Fn(DownloadRequest, DownloadResponder)>;
563
564/// What hears a download's events ([`DownloadResponder::save_to`]).
565type DownloadCallback = Rc<dyn Fn(&DownloadEvent)>;
566
567thread_local! {
568    /// The callback of each download in flight, by id.
569    static DOWNLOADS: RefCell<HashMap<u64, DownloadCallback>> = RefCell::new(HashMap::new());
570}
571
572/// A download's progress, from its backend, on the main thread.
573#[allow(
574    dead_code,
575    reason = "only the Apple and Android arms report downloads through Rust"
576)]
577#[expect(
578    clippy::needless_pass_by_value,
579    reason = "each backend hands over the event it has just built"
580)]
581pub(crate) fn download_event(id: u64, event: DownloadEvent) {
582    let callback = DOWNLOADS.with(|d| {
583        if event.is_terminal() {
584            d.borrow_mut().remove(&id)
585        } else {
586            d.borrow().get(&id).cloned()
587        }
588    });
589    if let Some(callback) = callback {
590        callback(&event);
591    }
592}
593
594/// Stop a download in flight. Its callback hears [`DownloadEvent::Failed`]. Nothing happens for
595/// an id that is not downloading.
596pub fn cancel_download(id: u64) {
597    if !DOWNLOADS.with(|d| d.borrow().contains_key(&id)) {
598        return;
599    }
600    #[cfg(any(
601        all(feature = "uikit", target_os = "ios"),
602        all(any(feature = "appkit", feature = "gtk"), target_os = "macos")
603    ))]
604    crate::browsing_apple::cancel_download(id);
605    #[cfg(all(target_os = "android", feature = "material"))]
606    crate::android_impl::cancel_download(id);
607    #[cfg(not(any(
608        all(feature = "uikit", target_os = "ios"),
609        all(any(feature = "appkit", feature = "gtk"), target_os = "macos"),
610        all(target_os = "android", feature = "material")
611    )))]
612    let _ = id;
613}
614
615/// Whether [`crate::WebView::on_download`] is ever asked on this backend.
616pub fn download_support() -> day_spec::Support {
617    if cfg!(any(
618        all(feature = "uikit", target_os = "ios"),
619        all(
620            any(feature = "appkit", feature = "gtk"),
621            target_os = "macos"
622        ),
623        all(target_os = "android", feature = "material")
624    )) {
625        day_spec::Support::Native
626    } else {
627        day_spec::Support::Unsupported
628    }
629}
630
631/// A file name safe to join onto a directory: the last path component of what the server or the
632/// link suggested, without control characters or the characters a file system refuses, and
633/// `fallback` for a name with nothing left.
634pub fn sanitize_file_name(suggested: &str, fallback: &str) -> String {
635    let last = suggested
636        .rsplit(['/', '\\'])
637        .next()
638        .unwrap_or_default()
639        .trim();
640    let clean: String = last
641        .chars()
642        .filter(|c| !c.is_control() && !matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|'))
643        .collect();
644    let clean = clean.trim_matches(['.', ' ']).to_string();
645    if clean.is_empty() {
646        fallback.to_string()
647    } else {
648        clean
649    }
650}
651
652/// `dir/name`, or `dir/stem (2).ext` and so on for the first name not taken: where a browser
653/// saves a second file of the same name.
654#[expect(
655    clippy::maybe_infinite_iter,
656    reason = "the search ends at the first name that is not taken"
657)]
658pub fn unused_path(dir: &Path, name: &str) -> PathBuf {
659    let first = dir.join(name);
660    if !first.exists() {
661        return first;
662    }
663    let (stem, extension) = match name.rfind('.') {
664        Some(dot) if dot > 0 => (&name[..dot], &name[dot..]),
665        _ => (name, ""),
666    };
667    (2u32..)
668        .map(|n| dir.join(format!("{stem} ({n}){extension}")))
669        .find(|candidate| !candidate.exists())
670        .unwrap_or(first)
671}
672
673// ---------------------------------------------------------------------------
674// Failed loads and certificates
675// ---------------------------------------------------------------------------
676
677/// Why a page did not load, in the terms an error page explains.
678#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
679#[serde(rename_all = "kebab-case")]
680pub enum LoadErrorKind {
681    /// The device has no connection.
682    Offline,
683    /// No server has that name.
684    HostNotFound,
685    /// The server did not answer in time.
686    Timeout,
687    /// The server refused or dropped the connection.
688    Connection,
689    /// The server's certificate is not trusted, expired, or made out to another name. The page
690    /// loads after [`trust_host`] and a reload.
691    Certificate,
692    /// The connection could not be made secure for a reason other than the certificate.
693    Secure,
694    /// The address names a scheme the engine cannot load.
695    Unsupported,
696    /// Anything else; [`LoadError::description`] has the engine's words.
697    Other,
698}
699
700/// A main-frame load that failed ([`crate::WebView::on_load_error`]).
701#[derive(Clone, Debug, PartialEq, Eq)]
702pub struct LoadError {
703    /// The address that failed.
704    pub url: String,
705    pub kind: LoadErrorKind,
706    /// The engine's own error number, for logs.
707    pub code: i64,
708    /// The engine's description, in the system's language where the engine localizes it.
709    pub description: String,
710}
711
712impl LoadError {
713    /// The host of the address that failed, which is what [`trust_host`] takes.
714    pub fn host(&self) -> String {
715        url::Url::parse(&self.url)
716            .ok()
717            .and_then(|u| u.host_str().map(str::to_owned))
718            .unwrap_or_default()
719    }
720}
721
722pub(crate) type LoadErrorHandler = Rc<dyn Fn(&LoadError)>;
723
724/// The hosts [`trust_host`] excepted. Engines ask about a certificate on threads of their own.
725static TRUSTED_HOSTS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
726
727/// Load pages from `host` despite a certificate the system does not trust, until the app exits:
728/// what "visit this site anyway" does after a [`LoadErrorKind::Certificate`] error. Reload the
729/// page afterwards. The exception covers every view and is never stored.
730pub fn trust_host(host: &str) {
731    let host = host.to_ascii_lowercase();
732    if host.is_empty() || host_trusted(&host) {
733        return;
734    }
735    if let Ok(mut trusted) = TRUSTED_HOSTS.lock() {
736        trusted.push(host.clone());
737    }
738    #[cfg(all(target_os = "android", feature = "material"))]
739    crate::android_impl::trust_host(&host);
740}
741
742/// Whether [`trust_host`] was called for `host`.
743pub fn host_trusted(host: &str) -> bool {
744    let host = host.to_ascii_lowercase();
745    TRUSTED_HOSTS
746        .lock()
747        .is_ok_and(|trusted| trusted.contains(&host))
748}
749
750// ---------------------------------------------------------------------------
751// The user agent
752// ---------------------------------------------------------------------------
753
754/// What a view tells sites it is ([`crate::WebView::user_agent`]).
755#[derive(Clone, Debug, Default, PartialEq, Eq)]
756pub enum UserAgent {
757    /// The engine's own string, which marks the view as embedded in an app: Android's has
758    /// `; wv` and `Version/4.0`, and WebKit's lacks Safari's `Version/… Safari/…`. Sites act on
759    /// that (some refuse sign-in to embedded views, some push their own app).
760    #[default]
761    Engine,
762    /// The string the platform's own browser sends, built from the engine's: Chrome's on
763    /// Android, Safari's on iOS and macOS. What a browser built on the system engine sends.
764    Browser,
765    /// This exact string.
766    Custom(String),
767}
768
769impl UserAgent {
770    /// The form a backend receives at creation: empty for the engine's own, `\u{1}` for the
771    /// platform browser's, or the custom string.
772    #[allow(
773        dead_code,
774        reason = "only the Android arm hands the user agent over in this form"
775    )]
776    pub(crate) fn wire(&self) -> &str {
777        match self {
778            UserAgent::Engine => "",
779            UserAgent::Browser => "\u{1}",
780            UserAgent::Custom(text) => text.trim(),
781        }
782    }
783}
784
785/// [`UserAgent::Browser`] on WebKit: what follows `(KHTML, like Gecko)` in Safari's string,
786/// for `WKWebViewConfiguration.applicationNameForUserAgent`. WebKit writes everything before
787/// it, so the device and its content mode stay the engine's to describe. `version` is the
788/// system's `major.minor`.
789#[allow(dead_code, reason = "only the Apple arms describe Safari's user agent")]
790pub(crate) fn safari_application_name(version: &str, mobile: bool) -> String {
791    if mobile {
792        format!("Version/{version} Mobile/15E148 Safari/604.1")
793    } else {
794        format!("Version/{version} Safari/605.1.15")
795    }
796}
797
798// ---------------------------------------------------------------------------
799// A lost page process
800// ---------------------------------------------------------------------------
801
802/// The process that ran a view's page is gone ([`crate::WebView::on_renderer_gone`]).
803#[derive(Clone, Copy, Debug, PartialEq, Eq)]
804pub struct RendererGone {
805    /// The process crashed. `false` means the system took it back for memory.
806    pub crashed: bool,
807}
808
809pub(crate) type RendererGoneHandler = Rc<dyn Fn(&RendererGone)>;
810
811// ---------------------------------------------------------------------------
812// The front-end's half: what a view's handlers do with a report
813// ---------------------------------------------------------------------------
814
815/// A view's handlers for this module's reports.
816#[derive(Clone, Default)]
817pub(crate) struct Handlers {
818    pub dialog: Option<DialogHandler>,
819    pub auth: Option<AuthHandler>,
820    pub download: Option<DownloadHandler>,
821    pub load_error: Option<LoadErrorHandler>,
822    pub renderer_gone: Option<RendererGoneHandler>,
823}
824
825/// What a backend needs to know of them before the first load.
826#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
827pub struct BrowseProps {
828    /// The app answers HTTP sign-in ([`crate::WebView::on_auth`]); without it the engine's
829    /// default applies, which cancels.
830    pub auth: bool,
831    /// The app takes downloads ([`crate::WebView::on_download`]); without it the engine does
832    /// what it does with a file it cannot show.
833    pub downloads: bool,
834    /// The app rebuilds a view whose page process is gone ([`crate::WebView::on_renderer_gone`]);
835    /// without it WebKit reloads the page itself.
836    pub renderer_gone: bool,
837    /// Swiping from a screen edge goes back and forward ([`crate::WebView::swipe_navigation`]).
838    pub swipe_navigation: bool,
839}
840
841impl Handlers {
842    pub(crate) fn props(&self, swipe_navigation: bool) -> BrowseProps {
843        BrowseProps {
844            auth: self.auth.is_some(),
845            downloads: self.download.is_some(),
846            renderer_gone: self.renderer_gone.is_some(),
847            swipe_navigation,
848        }
849    }
850
851    /// Run the handler a prompt is for. `send` carries the answer back to the backend.
852    pub(crate) fn prompt(&self, text: &str, send: impl Fn(u64, Answer) + 'static) {
853        let Ok(report) = serde_json::from_str::<PromptReport>(text) else {
854            return;
855        };
856        let reply = |id: u64| Reply {
857            id,
858            send: Some(Box::new(send)),
859        };
860        match report {
861            PromptReport::Dialog {
862                id,
863                dialog,
864                message,
865                default_text,
866                url,
867            } => {
868                let request = DialogRequest {
869                    kind: dialog,
870                    message,
871                    default_text,
872                    url,
873                };
874                let responder = DialogResponder(reply(id));
875                match &self.dialog {
876                    Some(handler) => handler(request, responder),
877                    None => present_dialog(request, responder),
878                }
879            }
880            PromptReport::Auth {
881                id,
882                host,
883                realm,
884                proxy,
885                failures,
886            } => {
887                let responder = AuthResponder(reply(id));
888                match &self.auth {
889                    Some(handler) => handler(
890                        AuthRequest {
891                            host,
892                            realm,
893                            proxy,
894                            failures,
895                        },
896                        responder,
897                    ),
898                    None => responder.cancel(),
899                }
900            }
901            PromptReport::Files {
902                id,
903                accept,
904                multiple,
905            } => choose_files(accept, multiple, reply(id)),
906            PromptReport::Download {
907                id,
908                url,
909                name,
910                mime,
911                size,
912            } => {
913                let responder = DownloadResponder(reply(id));
914                match &self.download {
915                    Some(handler) => handler(
916                        DownloadRequest {
917                            id,
918                            url,
919                            suggested_name: sanitize_file_name(&name, "download"),
920                            mime,
921                            size: u64::try_from(size).ok(),
922                        },
923                        responder,
924                    ),
925                    None => responder.cancel(),
926                }
927            }
928        }
929    }
930
931    /// Run the handler a notice is for.
932    pub(crate) fn notice(&self, text: &str) {
933        match serde_json::from_str::<Notice>(text) {
934            Ok(Notice::LoadError {
935                url,
936                error,
937                code,
938                text,
939            }) => {
940                if let Some(handler) = &self.load_error {
941                    handler(&LoadError {
942                        url,
943                        kind: error,
944                        code,
945                        description: text,
946                    });
947                }
948            }
949            Ok(Notice::RendererGone { crashed }) => {
950                if let Some(handler) = &self.renderer_gone {
951                    handler(&RendererGone { crashed });
952                }
953            }
954            Err(_) => {}
955        }
956    }
957}
958
959/// Whether a navigation to `url` is one a web engine loads itself. Anything else (`mailto:`,
960/// `tel:`, an app's own scheme, Android's `intent:`) is another program's to open, and a view
961/// reports it like a link out of a bundled site ([`crate::WebView::on_external_link`]).
962pub(crate) fn engine_scheme(url: &str) -> bool {
963    let scheme = url
964        .split_once(':')
965        .map_or_default(|(scheme, _)| scheme.to_ascii_lowercase());
966    matches!(
967        scheme.as_str(),
968        "http"
969            | "https"
970            | "about"
971            | "blob"
972            | "data"
973            | "file"
974            | "javascript"
975            | "day-resource"
976            | "day-tab"
977            | "view-source"
978            | "chrome"
979            | ""
980    )
981}
982
983#[cfg(test)]
984mod tests {
985    use super::*;
986    use std::cell::Cell;
987
988    /// The answers a test's handlers sent, in order.
989    type Seen = Rc<RefCell<Vec<(u64, Answer)>>>;
990
991    fn answers() -> (Seen, impl Fn(u64, Answer) + Clone + 'static) {
992        let seen = Rc::new(RefCell::new(Vec::new()));
993        let sink = seen.clone();
994        (seen, move |id, answer| sink.borrow_mut().push((id, answer)))
995    }
996
997    #[test]
998    fn a_dialog_reaches_its_handler_and_answers_once() {
999        let (seen, send) = answers();
1000        let handlers = Handlers {
1001            dialog: Some(Rc::new(|request, responder| {
1002                assert_eq!(request.kind, DialogKind::Prompt);
1003                assert_eq!(request.host(), "example.com");
1004                assert_eq!(request.default_text, "blue");
1005                responder.accept_with("green");
1006            })),
1007            ..Handlers::default()
1008        };
1009        handlers.prompt(
1010            r#"{"kind":"dialog","id":7,"dialog":"prompt","message":"Color?","default_text":"blue","url":"https://example.com/a"}"#,
1011            send,
1012        );
1013        let seen = seen.borrow();
1014        assert_eq!(seen.len(), 1);
1015        assert_eq!(seen[0].0, 7);
1016        assert!(seen[0].1.ok);
1017        assert_eq!(seen[0].1.text.as_deref(), Some("green"));
1018    }
1019
1020    #[test]
1021    fn a_dropped_responder_cancels() {
1022        let (seen, send) = answers();
1023        let handlers = Handlers {
1024            dialog: Some(Rc::new(|_, responder| drop(responder))),
1025            auth: Some(Rc::new(|_, responder| drop(responder))),
1026            ..Handlers::default()
1027        };
1028        handlers.prompt(
1029            r#"{"kind":"dialog","id":1,"dialog":"confirm","message":"Sure?"}"#,
1030            send.clone(),
1031        );
1032        handlers.prompt(r#"{"kind":"auth","id":2,"host":"example.com"}"#, send);
1033        let seen = seen.borrow();
1034        assert_eq!(seen.len(), 2);
1035        assert!(seen.iter().all(|(_, answer)| !answer.ok));
1036    }
1037
1038    #[test]
1039    fn sign_in_without_a_handler_cancels_and_with_one_carries_the_credentials() {
1040        let (seen, send) = answers();
1041        Handlers::default().prompt(
1042            r#"{"kind":"auth","id":3,"host":"example.com","realm":"staff"}"#,
1043            send.clone(),
1044        );
1045        let handlers = Handlers {
1046            auth: Some(Rc::new(|request, responder| {
1047                assert_eq!((request.realm.as_str(), request.failures), ("staff", 1));
1048                responder.sign_in("ada", "s3cret");
1049            })),
1050            ..Handlers::default()
1051        };
1052        handlers.prompt(
1053            r#"{"kind":"auth","id":4,"host":"example.com","realm":"staff","failures":1}"#,
1054            send,
1055        );
1056        let seen = seen.borrow();
1057        assert!(!seen[0].1.ok);
1058        assert_eq!(seen[1].1.user.as_deref(), Some("ada"));
1059        assert_eq!(seen[1].1.password.as_deref(), Some("s3cret"));
1060    }
1061
1062    #[test]
1063    fn a_download_names_a_safe_file_and_hears_its_events_until_the_last() {
1064        let (seen, send) = answers();
1065        let events = Rc::new(RefCell::new(Vec::new()));
1066        let heard = events.clone();
1067        let handlers = Handlers {
1068            download: Some(Rc::new(move |request, responder| {
1069                assert_eq!(request.suggested_name, "report.pdf");
1070                assert_eq!(request.size, None);
1071                let heard = heard.clone();
1072                responder.save_to("/tmp/report.pdf", move |event| {
1073                    heard.borrow_mut().push(event.clone());
1074                });
1075            })),
1076            ..Handlers::default()
1077        };
1078        handlers.prompt(
1079            r#"{"kind":"download","id":900001,"url":"https://example.com/r","name":"../../etc/report.pdf","mime":"application/pdf"}"#,
1080            send,
1081        );
1082        assert_eq!(seen.borrow()[0].1.paths, vec!["/tmp/report.pdf"]);
1083        download_event(
1084            900_001,
1085            DownloadEvent::Progress {
1086                received: 10,
1087                total: Some(20),
1088            },
1089        );
1090        download_event(
1091            900_001,
1092            DownloadEvent::Finished {
1093                location: "/tmp/report.pdf".into(),
1094            },
1095        );
1096        // Nothing is kept for a finished download.
1097        download_event(900_001, DownloadEvent::Failed("late".into()));
1098        assert_eq!(
1099            *events.borrow(),
1100            vec![
1101                DownloadEvent::Progress {
1102                    received: 10,
1103                    total: Some(20)
1104                },
1105                DownloadEvent::Finished {
1106                    location: "/tmp/report.pdf".into()
1107                }
1108            ]
1109        );
1110    }
1111
1112    #[test]
1113    fn file_names_lose_their_directories_and_refused_characters() {
1114        assert_eq!(sanitize_file_name("a/b/c.txt", "x"), "c.txt");
1115        assert_eq!(sanitize_file_name("..\\..\\evil.exe", "x"), "evil.exe");
1116        assert_eq!(sanitize_file_name("what?.txt", "x"), "what.txt");
1117        assert_eq!(sanitize_file_name("..", "download"), "download");
1118        assert_eq!(sanitize_file_name("  ", "download"), "download");
1119    }
1120
1121    #[test]
1122    fn a_taken_name_gets_a_number_before_its_extension() {
1123        let dir = std::env::temp_dir().join(format!("day-webview-unused-{}", std::process::id()));
1124        std::fs::create_dir_all(&dir).unwrap();
1125        assert_eq!(unused_path(&dir, "a.txt"), dir.join("a.txt"));
1126        std::fs::write(dir.join("a.txt"), b"1").unwrap();
1127        assert_eq!(unused_path(&dir, "a.txt"), dir.join("a (2).txt"));
1128        std::fs::write(dir.join("a (2).txt"), b"2").unwrap();
1129        assert_eq!(unused_path(&dir, "a.txt"), dir.join("a (3).txt"));
1130        std::fs::write(dir.join("noext"), b"3").unwrap();
1131        assert_eq!(unused_path(&dir, "noext"), dir.join("noext (2)"));
1132        std::fs::remove_dir_all(&dir).unwrap();
1133    }
1134
1135    #[test]
1136    fn notices_reach_their_handlers() {
1137        let failed = Rc::new(Cell::new(None));
1138        let gone = Rc::new(Cell::new(None));
1139        let (f, g) = (failed.clone(), gone.clone());
1140        let handlers = Handlers {
1141            load_error: Some(Rc::new(move |error| {
1142                f.set(Some((error.kind, error.host())));
1143            })),
1144            renderer_gone: Some(Rc::new(move |report| g.set(Some(report.crashed)))),
1145            ..Handlers::default()
1146        };
1147        handlers.notice(
1148            r#"{"kind":"load-error","url":"https://expired.example/x","error":"certificate","code":-1202,"text":"untrusted"}"#,
1149        );
1150        handlers.notice(r#"{"kind":"renderer-gone","crashed":true}"#);
1151        handlers.notice("not json");
1152        assert_eq!(
1153            failed.take(),
1154            Some((LoadErrorKind::Certificate, "expired.example".to_string()))
1155        );
1156        assert_eq!(gone.take(), Some(true));
1157    }
1158
1159    #[test]
1160    fn accept_lists_become_picker_extensions() {
1161        let list = |s: &str| vec![s.to_string()];
1162        assert_eq!(accept_extensions(&list(".pdf,.txt")), vec!["pdf", "txt"]);
1163        assert!(accept_extensions(&list("image/*")).contains(&"jpg"));
1164        assert_eq!(accept_extensions(&list("application/pdf")), vec!["pdf"]);
1165        // Anything the table cannot name means every file.
1166        assert_eq!(accept_extensions(&list("image/*,.xyz")), [] as [&str; 0]);
1167        assert_eq!(accept_extensions(&[]), [] as [&str; 0]);
1168    }
1169
1170    #[test]
1171    fn only_web_schemes_stay_in_the_engine() {
1172        for url in [
1173            "https://example.com/",
1174            "about:blank",
1175            "blob:https://example.com/1",
1176            "data:text/plain,hi",
1177        ] {
1178            assert!(engine_scheme(url), "{url}");
1179        }
1180        for url in [
1181            "mailto:a@example.com",
1182            "tel:+15551234",
1183            "intent://scan/#Intent;scheme=zxing;end",
1184            "myapp://open",
1185        ] {
1186            assert!(!engine_scheme(url), "{url}");
1187        }
1188    }
1189
1190    #[test]
1191    fn user_agents_cross_as_empty_a_marker_or_the_text() {
1192        assert_eq!(UserAgent::default().wire(), "");
1193        assert_eq!(UserAgent::Browser.wire(), "\u{1}");
1194        assert_eq!(
1195            UserAgent::Custom("  Mozilla/5.0 X  ".into()).wire(),
1196            "Mozilla/5.0 X"
1197        );
1198        assert_eq!(
1199            safari_application_name("18.6", true),
1200            "Version/18.6 Mobile/15E148 Safari/604.1"
1201        );
1202        assert_eq!(
1203            safari_application_name("26.1", false),
1204            "Version/26.1 Safari/605.1.15"
1205        );
1206    }
1207
1208    #[test]
1209    fn trusted_hosts_are_remembered_without_case() {
1210        assert!(!host_trusted("self-signed.example"));
1211        trust_host("Self-Signed.Example");
1212        assert!(host_trusted("self-signed.example"));
1213    }
1214}