Nacre/src/tabs.rs
astar76 f63ddf8da1 S050 (WIP): WebKit through the bridge over SOCKS5, navigation policy, certificate warning, downloads, cookie policy
- Bridge speaks SOCKS5 on its port; WebKit uses it (plain http through the HTTP proxy lost the login and looped);
  loopback skips the proxy.
- decide-policy: HTTPS-only upgrade with redirect guard, tracking strip, Content-Disposition downloads; Images
  permission as a WebKit content filter (net::policy::images_filter).
- load-failed-with-tls-errors -> Nacre's certificate page (assets/pages/badcert.html), "Open anyway" via
  nacre://allowcert for that tab only.
- download-started: web links to Nacre's downloader, blob:/data: saved by WebKit and tracked in the downloads list.
- Third-party cookies: NoThirdParty + ITP; privacy mode Accept-Language through the extension.
- selftest js/assert/save wait for the page's answer (unanswered asserts used to pass).
- Smokes: net-privacy (+localhost, TLS, images), net-downloads (+<a download>, blob:), privacy-net on https.
Open: main-frame detection for navigations, Google UA quirk, privacy-mode/cache smokes (see plan "Resume").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 15:27:36 -06:00

339 lines
12 KiB
Rust

//! Tabs. A tab shows either a web page (a WebKit view, `engine::View`) or one of Nacre's own pages (drawn with
//! egui).
use std::collections::VecDeque;
use std::time::Instant;
use url::Url;
use crate::engine::{LoadState, View, ViewId};
use crate::media::MediaState;
/// Nacre's own pages, addressed as nacre://<name>.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Page {
NewTab,
Settings(String),
History,
Bookmarks,
Downloads,
Passwords,
Apps,
SiteSettings(String),
ClearData,
About,
Welcome,
TaskManager,
DevTools,
/// Every widget and design token (not linked from the UI; for checking the design system).
Gallery,
/// Page source of the URL.
Source(String),
/// Network error page for a URL the browser itself couldn't open.
Error(String, String),
}
impl Page {
pub fn from_url(url: &str) -> Option<Page> {
let rest = url.strip_prefix("nacre://").or_else(|| url.strip_prefix("nacre:"))?;
let (name, arg) = rest.split_once('/').map(|(n, a)| (n, a.to_owned())).unwrap_or((rest, String::new()));
let name = name.split(['?', '#']).next().unwrap_or("").to_ascii_lowercase();
Some(match name.as_str() {
"" | "newtab" | "home" => Page::NewTab,
"settings" => Page::Settings(arg),
"history" => Page::History,
"bookmarks" => Page::Bookmarks,
"downloads" => Page::Downloads,
"passwords" => Page::Passwords,
"apps" | "scripts" | "extensions" => Page::Apps,
"site-settings" | "content" => Page::SiteSettings(arg),
"clear-data" | "clear" => Page::ClearData,
"about" | "version" => Page::About,
"welcome" | "setup" => Page::Welcome,
"task-manager" | "tasks" => Page::TaskManager,
"devtools" => Page::DevTools,
"gallery" => Page::Gallery,
"source" => Page::Source(crate::util::percent_decode(&arg)),
_ => return None,
})
}
pub fn url(&self) -> String {
match self {
Page::NewTab => "nacre://newtab".into(),
Page::Settings(section) if section.is_empty() => "nacre://settings".into(),
Page::Settings(section) => format!("nacre://settings/{section}"),
Page::History => "nacre://history".into(),
Page::Bookmarks => "nacre://bookmarks".into(),
Page::Downloads => "nacre://downloads".into(),
Page::Passwords => "nacre://passwords".into(),
Page::Apps => "nacre://apps".into(),
Page::SiteSettings(host) if host.is_empty() => "nacre://site-settings".into(),
Page::SiteSettings(host) => format!("nacre://site-settings/{host}"),
Page::ClearData => "nacre://clear-data".into(),
Page::About => "nacre://about".into(),
Page::Welcome => "nacre://welcome".into(),
Page::TaskManager => "nacre://task-manager".into(),
Page::DevTools => "nacre://devtools".into(),
Page::Gallery => "nacre://gallery".into(),
Page::Source(url) => format!("nacre://source/{}", crate::util::encode_query(url)),
Page::Error(url, _) => url.clone(),
}
}
pub fn title(&self) -> String {
match self {
Page::NewTab => "New tab".into(),
Page::Settings(_) => "Settings".into(),
Page::History => "History".into(),
Page::Bookmarks => "Bookmarks".into(),
Page::Downloads => "Downloads".into(),
Page::Passwords => "Passwords".into(),
Page::Apps => "Apps and scripts".into(),
Page::SiteSettings(_) => "Site settings".into(),
Page::ClearData => "Delete browsing data".into(),
Page::About => "About Nacre".into(),
Page::Welcome => "Welcome to Nacre".into(),
Page::TaskManager => "Task manager".into(),
Page::DevTools => "Developer tools".into(),
Page::Gallery => "Gallery".into(),
Page::Source(url) => format!("Source of {url}"),
Page::Error(_, _) => crate::resources::ERROR_TITLE.into(),
}
}
}
/// A question the tab is asking the user (shown as a bar above the page).
pub enum Prompt {
Permission { host: String, kind: crate::store::permissions::Kind, request: crate::engine::PermissionAsk },
/// Save the password just used?
SaveLogin { origin: String, username: String, password: String, update: bool },
/// HTTPS-only: the secure version didn't load.
HttpFallback { url: Url },
/// Open a link in another app (mailto:, magnet:, ...)?
External { url: String },
/// The page tried to open a pop-up that was blocked.
PopupBlocked { url: String },
/// A download the user should confirm (dangerous type), or where to send it.
Info { text: String },
}
/// A dialog in front of the page (modal for that tab only).
pub enum Dialog {
Simple(crate::engine::SimpleDialog, String),
Auth { request: crate::engine::AuthRequest, username: String, password: String },
Select(crate::engine::SelectElement),
Color(crate::engine::ColorPicker, [u8; 3]),
ContextMenu(Box<crate::ui::menus::PageMenu>),
LeavePage(crate::engine::LeavePage),
/// Saved logins for a field (autofill dropdown) at a point in the page (CSS px).
Logins { x: f32, y: f32, items: Vec<(u64, String)> },
Forms { kind: String, x: f32, y: f32 },
}
#[derive(Default, Clone)]
pub struct FindState {
pub open: bool,
pub text: String,
pub case_sensitive: bool,
pub count: u32,
pub index: u32,
pub focus: bool,
/// The words and match case WebKit last searched for (the bar's `text` changes before its command runs).
pub searched: Option<(String, bool)>,
}
pub struct Web {
pub webview: View,
}
pub struct Tab {
pub id: u64,
/// The internal page being shown (the web view, if any, stays behind it for "back").
pub page: Option<Page>,
pub web: Option<Web>,
/// For tabs restored lazily or unloaded: what to load when the tab is next shown.
pub pending_url: Option<String>,
pub url: String,
pub title: String,
pub favicon: Option<egui::TextureHandle>,
/// Favicon as PNG, for installing the site as an app.
pub favicon_png: Option<Vec<u8>>,
pub favicon_url: String,
pub load_status: Option<LoadState>,
pub load_started: Option<Instant>,
/// WebKit's estimated load progress, 0..1.
pub progress: f64,
pub status_text: Option<String>,
pub pinned: bool,
pub muted: bool,
pub media: Option<(MediaState, u64)>,
pub back_forward: Vec<Url>,
pub history_index: usize,
pub last_shown: Instant,
/// Hidden and not drawing (memory saver: freeze).
pub frozen: bool,
pub zoom: f32,
pub blocked: u32,
pub find: FindState,
pub prompts: VecDeque<Prompt>,
pub dialog: Option<Dialog>,
pub crashed: Option<String>,
/// The user closed the tab and its page runs `beforeunload` first (WebKit `try_close`); since when.
pub closing: Option<std::time::Instant>,
/// HTTPS-only upgraded this load from this URL.
pub upgraded_from: Option<Url>,
/// The certificate warning on show; its "Open anyway" (`nacre://allowcert`) trusts this one.
pub cert_error: Option<crate::engine::CertError>,
/// Page details from META_JS.
pub theme_color: Option<egui::Color32>,
pub site_name: String,
pub page_image: String,
pub manifest: String,
/// When the user arrived on this page (Discord "browsing" timer), ms.
pub arrived_ms: u64,
/// Last right-click details from the page.
pub context: Option<serde_json::Value>,
/// Text typed in the address bar for this tab but not yet submitted.
pub draft: Option<String>,
/// Opened by another tab (pop-up / target=_blank); closing returns to it.
pub opener: Option<u64>,
pub fullscreen: bool,
pub animating: bool,
/// Ad leftovers hidden on this page.
pub hidden_elements: u32,
/// Its view is in a picture-in-picture window, showing a video of this size (logical pixels).
pub pip_size: Option<[u32; 2]>,
}
impl Tab {
pub fn new(id: u64) -> Tab {
Tab {
id,
page: Some(Page::NewTab),
web: None,
pending_url: None,
url: "nacre://newtab".into(),
title: "New tab".into(),
favicon: None,
favicon_png: None,
favicon_url: String::new(),
load_status: None,
load_started: None,
progress: 0.0,
status_text: None,
pinned: false,
muted: false,
media: None,
back_forward: Vec::new(),
history_index: 0,
last_shown: Instant::now(),
frozen: false,
zoom: 1.0,
blocked: 0,
find: FindState::default(),
prompts: VecDeque::new(),
dialog: None,
closing: None,
crashed: None,
upgraded_from: None,
cert_error: None,
theme_color: None,
site_name: String::new(),
page_image: String::new(),
manifest: String::new(),
arrived_ms: crate::util::now_ms(),
context: None,
draft: None,
opener: None,
fullscreen: false,
animating: false,
hidden_elements: 0,
pip_size: None,
}
}
pub fn webview(&self) -> Option<&View> {
self.web.as_ref().map(|w| &w.webview)
}
pub fn view_id(&self) -> Option<ViewId> {
self.webview().map(View::id)
}
pub fn is_internal(&self) -> bool {
self.page.is_some()
}
/// The colour the "Website" colour source follows: none on an internal page, even one shown over a web page.
pub fn site_colour(&self) -> Option<egui::Color32> {
if self.is_internal() { None } else { self.theme_color }
}
pub fn loading(&self) -> bool {
self.page.is_none() && matches!(self.load_status, Some(LoadState::Started | LoadState::Committed))
}
pub fn shown_url(&self) -> String {
match &self.page {
Some(page) => page.url(),
None => self.url.clone(),
}
}
pub fn host(&self) -> String {
if self.page.is_some() { String::new() } else { crate::util::host_of_str(&self.url) }
}
pub fn can_go_back(&self) -> bool {
// An internal page shown over a web view goes back to the web view.
(self.page.is_some() && self.web.is_some()) || self.webview().is_some_and(View::can_go_back)
}
pub fn can_go_forward(&self) -> bool {
self.page.is_none() && self.webview().is_some_and(View::can_go_forward)
}
pub fn audible(&self) -> bool {
self.media.as_ref().is_some_and(|(m, _)| !m.paused && !m.muted) && !self.muted
}
pub fn display_title(&self) -> String {
if let Some(page) = &self.page {
return page.title();
}
if !self.title.trim().is_empty() {
return self.title.clone();
}
if self.url.is_empty() { "New tab".into() } else { self.url.clone() }
}
/// What the session file keeps for this tab.
pub fn saved(&self) -> crate::store::session::SavedTab {
crate::store::session::SavedTab {
url: self.pending_url.clone().unwrap_or_else(|| self.shown_url()),
title: self.display_title(),
pinned: self.pinned,
muted: self.muted,
history: self.back_forward.iter().map(Url::to_string).collect(),
history_index: self.history_index,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// R1-11: a nacre:// page opened in a web tab kept the site's colour, so palette picks didn't show.
#[test]
fn internal_page_has_no_site_colour() {
let mut tab = Tab::new(1);
tab.page = None;
tab.theme_color = Some(egui::Color32::from_rgb(0xDE, 0x58, 0x33));
assert_eq!(tab.site_colour(), tab.theme_color);
tab.page = Some(Page::Settings(String::new()));
assert_eq!(tab.site_colour(), None);
}
}