469 lines
18 KiB
Rust
469 lines
18 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 {
|
|
/// Every page the UI links to, with the name the address bar completes: the one list the About page and the
|
|
/// address suggestions use. Not the gallery, source or error pages, nor `nacre://allowcert`.
|
|
pub const PUBLIC: &'static [(&'static str, fn() -> Page)] = &[
|
|
("newtab", || Page::NewTab),
|
|
("settings", || Page::Settings(String::new())),
|
|
("history", || Page::History),
|
|
("bookmarks", || Page::Bookmarks),
|
|
("downloads", || Page::Downloads),
|
|
("passwords", || Page::Passwords),
|
|
("apps", || Page::Apps),
|
|
("site-settings", || Page::SiteSettings(String::new())),
|
|
("clear-data", || Page::ClearData),
|
|
("task-manager", || Page::TaskManager),
|
|
("devtools", || Page::DevTools),
|
|
("welcome", || Page::Welcome),
|
|
("about", || Page::About),
|
|
];
|
|
|
|
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(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The certificate warning's "Open anyway" (`assets/pages/badcert.html`).
|
|
pub const ALLOW_CERT: &str = "nacre://allowcert";
|
|
|
|
/// D-049: whether web content (a page's links, redirects, scripts, frames, pop-ups, the links of its context menu)
|
|
/// may go to this address. Never to one of Nacre's pages: only the user opens those (address bar, menus, buttons,
|
|
/// shortcuts, bookmarks). The one exception is the certificate warning's "Open anyway", which the browser takes only
|
|
/// from the tab showing that warning.
|
|
pub fn web_may_open(url: &str) -> bool {
|
|
let nacre = |scheme: &str| scheme.eq_ignore_ascii_case("nacre");
|
|
url == ALLOW_CERT || !(Url::parse(url).is_ok_and(|u| nacre(u.scheme())) || nacre(url.trim_start().split(':').next().unwrap_or("")))
|
|
}
|
|
|
|
/// 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 right click on a web page: WebKit's menu request and the page's answer (did it cancel the event?) come apart.
|
|
#[derive(Default)]
|
|
pub enum MenuWait {
|
|
#[default]
|
|
None,
|
|
/// WebKit asked for a menu (at this time); the page hasn't answered yet.
|
|
Menu(Box<crate::engine::PageMenuRequest>, std::time::Instant),
|
|
/// The page answered first: true when it cancelled the event.
|
|
Answer(bool),
|
|
}
|
|
|
|
/// 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>,
|
|
/// The back/forward list of the view the tab let go (`take_web`), for its next one.
|
|
pub history_state: Option<crate::engine::HistoryState>,
|
|
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,
|
|
/// WebKit hears sound from the page (`is-playing-audio`: Web Audio and frames too).
|
|
pub playing_audio: 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>,
|
|
/// A script's navigation Nacre would change (upgrade, strip, user agent) but that may be a frame's: if the tab
|
|
/// itself starts loading this URL, the browser loads it again with its rules (S061).
|
|
pub redo: 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: the `theme-color` meta.
|
|
pub theme_color: Option<egui::Color32>,
|
|
/// The icon's dominant vivid colour (`theme::dominant_vivid`).
|
|
pub favicon_colour: 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>,
|
|
/// The last right click's menu request or the page's answer, whichever came first (S061).
|
|
pub menu_wait: MenuWait,
|
|
/// 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,
|
|
history_state: 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,
|
|
playing_audio: 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,
|
|
redo: None,
|
|
cert_error: None,
|
|
theme_color: None,
|
|
favicon_colour: None,
|
|
site_name: String::new(),
|
|
page_image: String::new(),
|
|
manifest: String::new(),
|
|
arrived_ms: crate::util::now_ms(),
|
|
context: None,
|
|
menu_wait: MenuWait::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: the favicon's, else the page's `theme-color`; 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.favicon_colour.or(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 opened from a web page goes back to that page.
|
|
self.page.is_some() && self.has_web_behind() || self.webview().is_some_and(View::can_go_back)
|
|
}
|
|
|
|
/// A close (`closing`) nobody answers after 3 s goes ahead: the page hung, gave no close signal, or its question
|
|
/// was lost. Only "Leave this page?" on screen counts as an answer pending.
|
|
pub fn close_overdue(&self, now: Instant) -> bool {
|
|
!matches!(self.dialog, Some(Dialog::LeavePage(_))) && self.closing.is_some_and(|c| now.duration_since(c) > std::time::Duration::from_secs(3))
|
|
}
|
|
|
|
/// One of Nacre's pages opened from a web page: the tab's view, or the history it let go, is that page.
|
|
pub fn has_web_behind(&self) -> bool {
|
|
self.web.is_some() || self.history_state.is_some()
|
|
}
|
|
|
|
/// Take the web view out (unloading the tab, or showing one of Nacre's pages in it); its back/forward list stays
|
|
/// for the next view. The caller detaches and forgets the view.
|
|
pub fn take_web(&mut self) -> Option<View> {
|
|
let web = self.web.take()?;
|
|
self.history_state = web.webview.history_state();
|
|
self.load_status = None;
|
|
// The page's open question goes with it: left on the tab it would show over Nacre's page and keep the view
|
|
// alive (a "Leave this page?" from a Reload, S059).
|
|
match self.dialog.take() {
|
|
Some(Dialog::LeavePage(request)) => request.deny(),
|
|
Some(Dialog::Simple(dialog, _)) => dialog.dismiss(),
|
|
_ => {},
|
|
}
|
|
Some(web.webview)
|
|
}
|
|
|
|
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.muted && (self.playing_audio || self.media.as_ref().is_some_and(|(m, _)| !m.paused && !m.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 {
|
|
let url = self.pending_url.clone().unwrap_or_else(|| self.shown_url());
|
|
let kept = crate::store::session::kept_url(&url);
|
|
crate::store::session::SavedTab {
|
|
title: if kept == url { self.display_title() } else { String::new() },
|
|
url: kept.to_owned(),
|
|
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::*;
|
|
|
|
#[test]
|
|
fn listed_pages_round_trip_and_hide_internal_ones() {
|
|
for (name, make) in Page::PUBLIC {
|
|
let page = make();
|
|
assert_eq!(Page::from_url(&page.url()), Some(page.clone()), "{name}");
|
|
assert_eq!(page.url(), format!("nacre://{name}"));
|
|
}
|
|
assert!(Page::PUBLIC.iter().all(|(name, _)| !matches!(*name, "gallery" | "source" | "allowcert")));
|
|
}
|
|
|
|
// S063 (D-049): a page's navigations never reach Nacre's pages, except "Open anyway" of the certificate warning.
|
|
#[test]
|
|
fn web_content_cannot_open_internal_pages() {
|
|
for url in ["nacre://passwords", "NACRE://passwords", "nacre:passwords", " nacre://settings", "Nacre://allowcert/x", "nacre://newtab"] {
|
|
assert!(!web_may_open(url), "{url}");
|
|
}
|
|
for url in [ALLOW_CERT, "https://example.com/nacre://passwords", "about:blank", "data:text/html,x", "http://nacre/"] {
|
|
assert!(web_may_open(url), "{url}");
|
|
}
|
|
}
|
|
|
|
// S059: a close left without an answer must not keep the tab closing (Reload and navigation ignored) for good.
|
|
#[test]
|
|
fn unanswered_close_goes_ahead() {
|
|
let mut tab = Tab::new(1);
|
|
let now = Instant::now();
|
|
assert!(!tab.close_overdue(now));
|
|
tab.closing = Some(now);
|
|
assert!(!tab.close_overdue(now + std::time::Duration::from_secs(2)));
|
|
assert!(tab.close_overdue(now + std::time::Duration::from_secs(4)));
|
|
tab.dialog = Some(Dialog::Forms { kind: "card".into(), x: 0.0, y: 0.0 });
|
|
assert!(tab.close_overdue(now + std::time::Duration::from_secs(4)));
|
|
}
|
|
|
|
// S059: one of Nacre's pages goes back to a web page only when the tab came from one.
|
|
#[test]
|
|
fn internal_page_back_needs_a_web_page() {
|
|
let tab = Tab::new(1);
|
|
assert!(tab.page.is_some() && !tab.has_web_behind() && !tab.can_go_back());
|
|
}
|
|
|
|
// 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.favicon_colour = Some(egui::Color32::from_rgb(0x30, 0x60, 0xE0));
|
|
assert_eq!(tab.site_colour(), tab.favicon_colour);
|
|
tab.page = Some(Page::Settings(String::new()));
|
|
assert_eq!(tab.site_colour(), None);
|
|
}
|
|
}
|