Nacre/src/tabs.rs
astar76 2d8323a3e0 Nacre on Servo: first complete, reviewed, not yet built version
Everything in Rust on Servo 0.7 (trimmed: no WebXR, WebGPU, multiprocess):
tabs and windows, address bar with suggestions, history, bookmarks and
reading list, downloads with resume and external download managers,
encrypted password vault with autofill, ad blocker (adblock-rust, 22 lists),
VPN through Tor or a proxy and secure DNS via a local bridge proxy,
picture in picture, Discord Rich Presence, media player and visualizer,
spell check, site apps, user scripts and styles, import from other
browsers, gamepads, Web Bluetooth, and every setting of the original Nacre
in a plain egui interface.

Not compiled yet; docs/HANDOFF.md has the first build checklist.

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

325 lines
11 KiB
Rust

//! Tabs. A tab shows either a web page (a Servo WebView with its own offscreen rendering
//! context, see DESIGN.md) or one of Nacre's own pages (drawn with egui).
use std::collections::VecDeque;
use std::rc::Rc;
use std::time::Instant;
use servo::{LoadStatus, OffscreenRenderingContext, WebView};
use url::Url;
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,
/// 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,
"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::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::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: servo::PermissionRequest },
/// A site asks to handle a link type (mailto: and so on).
ProtocolHandler { host: String, scheme: String, request: servo::AllowOrDenyRequest },
/// 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(servo::SimpleDialog, String),
Auth { request: servo::AuthenticationRequest, username: String, password: String },
Select(servo::SelectElement),
Color(servo::ColorPicker, [u8; 3]),
ContextMenu(Box<crate::ui::menus::PageMenu>),
Bluetooth(servo::BluetoothDeviceSelectionRequest),
LeavePage(servo::AllowOrDenyRequest),
/// 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,
}
pub struct ConsoleLine {
pub level: servo::ConsoleLogLevel,
pub text: String,
pub time_ms: u64,
}
pub struct Web {
pub webview: WebView,
pub context: Rc<OffscreenRenderingContext>,
/// A new frame is waiting to be painted.
pub dirty: bool,
}
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<LoadStatus>,
pub load_started: Option<Instant>,
pub status_text: Option<String>,
pub cursor: servo::Cursor,
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>,
/// HTTPS-only upgraded this load from this URL.
pub upgraded_from: Option<Url>,
pub console: VecDeque<ConsoleLine>,
/// 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,
/// Shown in a picture-in-picture window at this size (physical pixels).
pub pip_size: Option<dpi::PhysicalSize<u32>>,
}
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,
status_text: None,
cursor: servo::Cursor::Default,
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,
crashed: None,
upgraded_from: None,
console: VecDeque::new(),
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<&WebView> {
self.web.as_ref().map(|w| &w.webview)
}
pub fn webview_id(&self) -> Option<servo::WebViewId> {
self.webview().map(WebView::id)
}
pub fn is_internal(&self) -> bool {
self.page.is_some()
}
pub fn loading(&self) -> bool {
self.page.is_none() && matches!(self.load_status, Some(LoadStatus::Started | LoadStatus::HeadParsed))
}
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(WebView::can_go_back)
}
pub fn can_go_forward(&self) -> bool {
self.page.is_none() && self.webview().is_some_and(WebView::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() }
}
pub fn push_console(&mut self, level: servo::ConsoleLogLevel, text: String) {
if self.console.len() >= 500 {
self.console.pop_front();
}
self.console.push_back(ConsoleLine { level, text, time_ms: crate::util::now_ms() });
}
/// 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,
}
}
}