Nacre/src/engine/mod.rs

567 lines
20 KiB
Rust

//! The web engine: WebKitGTK 6.0 views in the GTK 4 window (D-032, D-033, D-035).
//!
//! Everything WebKit tells the browser arrives as signals on the main thread. The signal handlers in `host.rs` only
//! turn them into `Event`s on the `Hub` queue (they never touch the `App`, which may be borrowed while WebKit emits
//! a signal synchronously); `App::handle_event` handles them from a GLib idle right after (`app::pump`).
//!
//! The rest of Nacre sees only the types here: a Nacre-owned `ViewId` per web view (D-041), `View` (a handle with
//! the page actions), and engine-neutral payloads that hold the WebKit request object the answer needs. The
//! `ViewId ↔ WebView` map lives in `host.rs` and nowhere else.
pub mod host;
pub mod view;
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use url::Url;
use webkit::prelude::*;
pub use host::Engine;
pub use view::View;
/// A view's back/forward list, kept while a tab has no view (unloaded, or showing one of Nacre's pages).
pub use webkit::WebViewSessionState as HistoryState;
use crate::adblock::AdBlocker;
use crate::inject::PageMessage;
pub use crate::net::policy::HubConfig;
use crate::util;
/// A web view's id. The same number as the tab id it was made for (`App::new_tab_id`), so tabs and views never
/// share a number by accident; pop-ups take a fresh one from the same counter.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ViewId(pub u64);
/// What `evaluate_javascript` gives back: the completion value as JSON (`undefined` and unserializable values are
/// `Null`).
pub type JsValue = serde_json::Value;
/// Where a page load is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LoadState {
/// The request went out (WebKit `Started`).
Started,
/// The first bytes arrived and the new document replaced the old one (WebKit `Committed`).
Committed,
/// Done (WebKit `Finished`, also after a failure).
Complete,
}
pub enum Event {
UrlChanged(ViewId, Url),
TitleChanged(ViewId, Option<String>),
/// The link under the pointer (shown at the bottom left), or none.
StatusText(ViewId, Option<String>),
Load(ViewId, LoadState),
/// WebKit's estimated load progress, 0..1.
Progress(ViewId, f64),
Favicon(ViewId),
/// Back/forward list: entries and the index of the current one.
History(ViewId, Vec<Url>, usize),
/// The page asked to close (`window.close()`).
Closed(ViewId),
/// The web process died (crash, memory limit).
Crashed(ViewId, String),
/// WebKit's `is-web-process-responsive` changed (false: the page's process didn't answer in time).
Responsive(ViewId, bool),
Fullscreen(ViewId, bool),
/// A main-frame navigation waits for `NavigationRequest::allow`/`deny`.
Navigation(ViewId, NavigationRequest),
/// A response WebKit can't show, or one the server marked as an attachment: Nacre downloads it itself. The
/// file name the server suggested, if any.
Download(ViewId, Url, Option<String>),
/// A download only WebKit can make (`blob:`, `data:`): it waits for `WebDownload::save_to`.
WebDownload(Option<ViewId>, WebDownload),
/// The page's certificate can't be trusted: Nacre shows its warning.
CertError(ViewId, CertError),
/// A load failed (not a cancel): url, error text.
LoadFailed(ViewId, String, String),
/// A pop-up (`window.open`, target=_blank): its view, already made as a related view of the opener, and the
/// address it will load (none for `about:blank`-style opens).
/// A page opened a window: opener, the new view, its address, and whether a click or key press opened it.
CreateNew(ViewId, View, Option<Url>, bool),
/// A link clicked with the middle button or Ctrl: open it in a new tab (true: in front).
OpenLink(ViewId, Url, bool),
Permission(ViewId, crate::store::permissions::Kind, PermissionAsk),
Auth(ViewId, AuthRequest),
Control(ViewId, Control),
Notification(Option<ViewId>, Notification),
Page(ViewId, PageMessage),
/// Find in page: how many matches the last search or step found (0: none).
Find(ViewId, u32),
/// WebKit's `is-playing-audio` changed.
Audio(ViewId, bool),
/// A cookie was added, changed or deleted.
CookiesChanged,
/// What a host keeps (`Engine::site_data`).
SiteData(String, SiteData),
}
/// Cookies and stored data of one site, for the site info flyout.
#[derive(Clone, Debug, Default)]
pub struct SiteData {
/// Cookies the page's address gets.
pub cookies: usize,
/// Kinds of stored data under the host's name ("local storage", …).
pub stored: Vec<&'static str>,
}
/// A user style sheet (`store::scripts`), added at author level so it acts like the page's own last `<style>`.
#[derive(Clone, Debug, PartialEq)]
pub struct UserStyle {
pub css: String,
/// WebKit URL patterns (`https://*.example.com/*`); empty = every page.
pub allow: Vec<String>,
pub block: Vec<String>,
}
/// One request seen by the network log (developer tools).
#[derive(Clone, Debug)]
pub struct NetEntry {
pub time_ms: u64,
pub method: String,
pub url: String,
pub kind: String,
pub blocked: bool,
}
/// The event queue and the per-view counters the UI reads.
pub struct Hub {
events: RefCell<VecDeque<Event>>,
/// Marks Nacre's own page messages (`inject.rs` bridge); random per run.
pub token: String,
pub config: RefCell<HubConfig>,
pub adblock: Arc<AdBlocker>,
/// Requests blocked per view since its page started loading.
pub blocked: RefCell<HashMap<ViewId, u32>>,
/// Total blocked this run (added to the saved total by the app).
pub blocked_total: RefCell<u64>,
pub net_log: RefCell<HashMap<ViewId, VecDeque<NetEntry>>>,
}
impl Hub {
pub fn new(adblock: Arc<AdBlocker>) -> Rc<Hub> {
Rc::new(Hub {
events: RefCell::new(VecDeque::new()),
token: format!("\u{1}nacre-{}\u{1}", util::random_hex(12)),
config: RefCell::new(HubConfig::default()),
adblock,
blocked: RefCell::new(HashMap::new()),
blocked_total: RefCell::new(0),
net_log: RefCell::new(HashMap::new()),
})
}
pub fn push(&self, event: Event) {
self.events.borrow_mut().push_back(event);
crate::app::schedule_pump();
}
pub fn take_events(&self) -> Vec<Event> {
self.events.borrow_mut().drain(..).collect()
}
pub fn clear(&self) {
self.events.borrow_mut().clear();
}
pub fn forget(&self, view: ViewId) {
self.blocked.borrow_mut().remove(&view);
self.net_log.borrow_mut().remove(&view);
}
}
// ── payloads ─────────────────────────────────────────────────────────────────────────────────────────────────────
/// A navigation waiting for the browser's answer (WebKit keeps the load on hold until then).
pub struct NavigationRequest {
pub url: Url,
/// The server sent the page here (an HTTP redirect), rather than a link or the address bar.
pub redirect: bool,
/// Started by a script and not found as a frame of the page: it may still be a frame's (one inside a
/// cross-site frame, an ad's), so Nacre doesn't load another URL in the tab for it (S061).
pub maybe_frame: bool,
decision: webkit::PolicyDecision,
}
impl NavigationRequest {
pub(crate) fn new(url: Url, redirect: bool, maybe_frame: bool, decision: webkit::PolicyDecision) -> Self {
NavigationRequest { url, redirect, maybe_frame, decision }
}
pub fn allow(self) {
self.decision.use_();
}
pub fn deny(self) {
self.decision.ignore();
}
}
/// A page whose certificate failed the checks (self-signed, expired, wrong name, …).
pub struct CertError {
pub url: Url,
pub host: String,
/// What is wrong, in words.
pub why: String,
certificate: gtk::gio::TlsCertificate,
}
impl CertError {
pub(crate) fn new(url: Url, certificate: gtk::gio::TlsCertificate, errors: gtk::gio::TlsCertificateFlags) -> Self {
use gtk::gio::TlsCertificateFlags as F;
let reasons = [
(F::UNKNOWN_CA, "it isn't signed by an authority this computer trusts"),
(F::BAD_IDENTITY, "it belongs to another site"),
(F::NOT_ACTIVATED, "it isn't valid yet"),
(F::EXPIRED, "it has expired"),
(F::REVOKED, "it was revoked"),
(F::INSECURE, "it uses weak encryption"),
];
let found: Vec<&str> = reasons.iter().filter(|(flag, _)| errors.contains(*flag)).map(|(_, why)| *why).collect();
let why = if found.is_empty() { "The certificate couldn't be checked.".to_owned() } else { format!("The certificate can't be trusted: {}.", found.join(", ")) };
CertError { host: url.host_str().unwrap_or("").to_owned(), url, why, certificate }
}
}
/// A download WebKit makes itself, reported back as `net::download::Msg`s with the downloads list's id.
pub struct WebDownload(webkit::Download, String);
impl WebDownload {
pub(crate) fn new(download: webkit::Download, suggested: String) -> Self {
WebDownload(download, suggested)
}
pub fn url(&self) -> String {
self.0.request().and_then(|r| r.uri()).map(|u| u.to_string()).unwrap_or_default()
}
/// The name the page or server gave the file.
pub fn suggested_name(&self) -> &str {
&self.1
}
/// Save it at `path` and report progress, the end or a failure to `tx`.
pub fn save_to(&self, path: &std::path::Path, id: u64, tx: std::sync::mpsc::Sender<crate::net::download::Msg>, wake: impl Fn() + Clone + 'static) {
use crate::net::download::Msg;
let d = &self.0;
let (t, w) = (tx.clone(), wake.clone());
d.connect_received_data(move |d, _| {
let total = d.response().map(|r| r.content_length()).unwrap_or(0);
let _ = t.send(Msg::Progress { id, received: d.received_data_length(), total, speed: 0 });
w();
});
let (t, w) = (tx.clone(), wake.clone());
let done = path.to_owned();
d.connect_finished(move |_| {
// `failed` comes first for a failed or cancelled download; then this one, which must not undo it.
if done.exists() {
let _ = t.send(Msg::Done { id, path: done.clone() });
w();
}
});
d.connect_failed(move |_, error| {
let msg = if error.matches(webkit::DownloadError::CancelledByUser) { Msg::Cancelled { id } } else { Msg::Failed { id, error: error.message().to_owned() } };
let _ = tx.send(msg);
wake();
});
d.set_allow_overwrite(false);
d.set_destination(&path.to_string_lossy());
}
pub fn cancel(&self) {
self.0.cancel();
}
}
/// A permission a page asked for.
pub struct PermissionAsk(webkit::PermissionRequest);
impl PermissionAsk {
pub(crate) fn new(request: webkit::PermissionRequest) -> Self {
PermissionAsk(request)
}
pub fn allow(self) {
self.0.allow();
}
pub fn deny(self) {
self.0.deny();
}
}
/// HTTP authentication (a site or proxy asks for a user name and password).
pub struct AuthRequest(webkit::AuthenticationRequest);
impl AuthRequest {
pub(crate) fn new(request: webkit::AuthenticationRequest) -> Self {
AuthRequest(request)
}
pub fn host(&self) -> String {
self.0.host().map(|h| h.to_string()).unwrap_or_default()
}
/// `scheme://host[:port]`, as the vault keys logins.
pub fn origin(&self) -> String {
match self.0.security_origin() {
Some(o) => {
let (scheme, host, port) = (o.protocol().map(|s| s.to_string()).unwrap_or_default(), o.host().map(|s| s.to_string()).unwrap_or_default(), o.port());
if port == 0 { format!("{scheme}://{host}") } else { format!("{scheme}://{host}:{port}") }
},
None => format!("https://{}", self.host()),
}
}
pub fn for_proxy(&self) -> bool {
self.0.is_for_proxy()
}
pub fn authenticate(self, username: String, password: String) {
let credential = webkit::Credential::new(&username, &password, webkit::CredentialPersistence::ForSession);
self.0.authenticate(Some(&credential));
}
pub fn cancel(self) {
self.0.cancel();
}
}
/// A desktop notification from a page.
pub struct Notification {
pub title: String,
pub body: String,
}
/// Page controls the browser draws itself (in egui) and answers.
pub enum Control {
Dialog(SimpleDialog),
LeavePage(LeavePage),
Select(SelectElement),
Color(ColorPicker),
File(FilePicker),
ContextMenu(PageMenuRequest),
}
/// `alert` / `confirm` / `prompt`.
pub struct ScriptDialog {
dialog: webkit::ScriptDialog,
value: Option<String>,
}
impl ScriptDialog {
pub fn message(&self) -> String {
self.dialog.message().map(|m| m.to_string()).unwrap_or_default()
}
pub fn current_value(&self) -> String {
self.value.clone().unwrap_or_else(|| self.dialog.prompt_get_default_text().map(|t| t.to_string()).unwrap_or_default())
}
pub fn set_current_value(&mut self, value: &str) {
self.value = Some(value.to_owned());
}
}
pub enum SimpleDialog {
Alert(ScriptDialog),
Confirm(ScriptDialog),
Prompt(ScriptDialog),
}
impl SimpleDialog {
pub(crate) fn new(dialog: webkit::ScriptDialog) -> Option<Control> {
let d = ScriptDialog { dialog: dialog.clone(), value: None };
Some(match dialog.dialog_type() {
webkit::ScriptDialogType::Alert => Control::Dialog(SimpleDialog::Alert(d)),
webkit::ScriptDialogType::Confirm => Control::Dialog(SimpleDialog::Confirm(d)),
webkit::ScriptDialogType::Prompt => Control::Dialog(SimpleDialog::Prompt(d)),
webkit::ScriptDialogType::BeforeUnloadConfirm => Control::LeavePage(LeavePage(dialog)),
_ => return None,
})
}
pub fn message(&self) -> String {
match self {
SimpleDialog::Alert(d) | SimpleDialog::Confirm(d) | SimpleDialog::Prompt(d) => d.message(),
}
}
/// OK.
pub fn confirm(self) {
match self {
SimpleDialog::Alert(d) => d.dialog.close(),
SimpleDialog::Confirm(d) => {
d.dialog.confirm_set_confirmed(true);
d.dialog.close();
},
SimpleDialog::Prompt(d) => {
let value = d.current_value();
d.dialog.prompt_set_text(&value);
d.dialog.close();
},
}
}
/// Cancel (a prompt then gives null).
pub fn dismiss(self) {
match self {
SimpleDialog::Alert(d) | SimpleDialog::Prompt(d) => d.dialog.close(),
SimpleDialog::Confirm(d) => {
d.dialog.confirm_set_confirmed(false);
d.dialog.close();
},
}
}
}
/// "Leave this page?" (`beforeunload`).
pub struct LeavePage(webkit::ScriptDialog);
impl LeavePage {
pub fn allow(self) {
self.0.confirm_set_confirmed(true);
self.0.close();
}
pub fn deny(self) {
self.0.confirm_set_confirmed(false);
self.0.close();
}
}
#[derive(Clone, Debug)]
pub struct SelectOption {
pub id: usize,
pub label: String,
pub is_disabled: bool,
}
#[derive(Clone, Debug)]
pub enum SelectEntry {
Option(SelectOption),
Optgroup { label: String, options: Vec<SelectOption> },
}
/// A `<select>`'s drop-down list.
pub struct SelectElement {
menu: webkit::OptionMenu,
/// The element, in logical pixels relative to the page.
pub rect: egui::Rect,
entries: Vec<SelectEntry>,
selected: Vec<usize>,
}
impl SelectElement {
pub(crate) fn new(menu: webkit::OptionMenu, rect: egui::Rect) -> Self {
let mut entries: Vec<SelectEntry> = Vec::new();
let mut selected = Vec::new();
for i in 0..menu.n_items() {
let Some(mut item) = menu.item(i) else { continue };
let label = item.label().map(|l| l.to_string()).unwrap_or_default();
if item.is_group_label() {
entries.push(SelectEntry::Optgroup { label, options: Vec::new() });
continue;
}
if item.is_selected() {
selected.push(i as usize);
}
let option = SelectOption { id: i as usize, label, is_disabled: !item.is_enabled() };
match entries.last_mut() {
Some(SelectEntry::Optgroup { options, .. }) if item.is_group_child() => options.push(option),
_ => entries.push(SelectEntry::Option(option)),
}
}
SelectElement { menu, rect, entries, selected }
}
pub fn options(&self) -> &[SelectEntry] {
&self.entries
}
pub fn selected_options(&self) -> Vec<usize> {
self.selected.clone()
}
/// WebKit opens the list only for single selects (multiple ones are drawn in the page).
pub fn allow_select_multiple(&self) -> bool {
false
}
pub fn select(&mut self, chosen: Vec<usize>) {
if let Some(i) = chosen.first() {
self.menu.activate_item(*i as u32);
}
}
pub fn submit(self) {
self.menu.close();
}
}
/// `<input type=color>`.
pub struct ColorPicker {
request: webkit::ColorChooserRequest,
/// The element, in logical pixels relative to the page.
pub rect: egui::Rect,
}
impl ColorPicker {
pub(crate) fn new(request: webkit::ColorChooserRequest) -> Self {
let r = request.element_rectangle();
let rect = egui::Rect::from_min_size(egui::pos2(r.x() as f32, r.y() as f32), egui::vec2(r.width() as f32, r.height() as f32));
ColorPicker { request, rect }
}
pub fn current_color(&self) -> Option<[u8; 3]> {
let c = self.request.rgba();
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
Some([b(c.red()), b(c.green()), b(c.blue())])
}
pub fn select(&mut self, color: Option<[u8; 3]>) {
if let Some([r, g, b]) = color {
self.request.set_rgba(&gtk::gdk::RGBA::new(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0));
}
}
pub fn submit(self) {
self.request.finish();
}
pub fn cancel(self) {
self.request.cancel();
}
}
/// `<input type=file>`.
pub struct FilePicker(webkit::FileChooserRequest);
impl FilePicker {
pub(crate) fn new(request: webkit::FileChooserRequest) -> Self {
FilePicker(request)
}
/// File name extensions the page accepts, from its MIME types where they are plain (`image/png` → `png`).
pub fn filter_patterns(&self) -> Vec<String> {
self.0.mime_types().iter().filter_map(|m| m.split_once('/').map(|(_, sub)| sub.to_owned())).filter(|s| s != "*" && !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric())).collect()
}
pub fn allow_select_multiple(&self) -> bool {
self.0.selects_multiple()
}
pub fn select(&mut self, paths: &[PathBuf]) {
let files: Vec<String> = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
let refs: Vec<&str> = files.iter().map(String::as_str).collect();
self.0.select_files(&refs);
}
pub fn submit(self) {}
pub fn dismiss(self) {
self.0.cancel();
}
}
/// The engine's own page-menu actions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PageAction {
GoBack,
GoForward,
Reload,
Cut,
Copy,
Paste,
SelectAll,
}
/// A right click on a page (WebKit's own menu is suppressed; Nacre draws its menu at `position`).
pub struct PageMenuRequest {
/// The pointer, in logical pixels of the window.
pub position: egui::Pos2,
pub link: Option<String>,
pub image: Option<String>,
pub media: Option<String>,
pub editable: bool,
pub selection: bool,
pub items: Vec<(String, PageAction, bool)>,
pub(crate) view: View,
}
impl PageMenuRequest {
pub fn select(self, action: PageAction) {
self.view.execute(action);
}
}