S059: tab lifecycle: page dialogs and views go with a tab's web page, shortcut recording ends, message handler unregistered

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-18 04:00:18 -06:00
commit 9b7ea2b255
10 changed files with 285 additions and 32 deletions

View file

@ -377,6 +377,12 @@ impl App {
&& let Some(tab) = win.tab_mut()
{
tab.crashed = None;
// WebKit is running the page's beforeunload for a close: loading into that view crashed (S054). The
// tick ends a close nobody answers, so this only shows while "Leave this page?" is up.
if let Some(since) = tab.closing {
eprintln!("tab {}: Reload ignored, the tab is closing ({:.1} s, dialog {})", tab.id, since.elapsed().as_secs_f32(), tab.dialog.is_some());
return;
}
if let Some(web) = &tab.web {
if hard { web.webview.reload_bypass_cache() } else { web.webview.reload() }
}
@ -740,9 +746,7 @@ impl App {
for (i, tab) in win.tabs.iter_mut().enumerate() {
if i != active && tab.web.is_some() && !tab.audible() && tab.pip_size.is_none() {
tab.pending_url = Some(tab.url.clone());
if let Some(web) = tab.web.take() {
unloaded.push(web.webview);
}
unloaded.extend(tab.take_web());
freed += 1;
}
}
@ -1043,7 +1047,7 @@ impl App {
// Background tabs start loading at once (lazy loading is only for restored tabs).
let url = tab.pending_url.take().unwrap_or_default();
if let Ok(parsed) = Url::parse(&url) {
tab.web = Some(self.build_webview(tab.id, parsed));
tab.web = Some(self.build_webview(tab.id, parsed, None));
tab.load_status = Some(crate::engine::LoadState::Started);
}
}
@ -1145,6 +1149,13 @@ impl App {
win.tabs[i].page = Some(page);
win.tabs[i].draft = None;
win.ui.omnibox_edit = None;
// The web page doesn't run on hidden behind Nacre's page; Back loads it again with its history.
if let Some(view) = win.tabs[i].take_web() {
win.detach(&view);
if let Some(engine) = &self.engine {
engine.forget(view.id());
}
}
self.redraw(window);
return;
}
@ -1183,7 +1194,8 @@ impl App {
win.focus_page();
} else {
let tab_id = win.tabs[i].id;
let web = self.build_webview(tab_id, parsed);
let history = self.windows.get_mut(&window).expect("found").tabs[i].history_state.take();
let web = self.build_webview(tab_id, parsed, history);
let win = self.windows.get_mut(&window).expect("found");
let tab = &mut win.tabs[i];
tab.web = Some(web);
@ -1265,9 +1277,13 @@ impl App {
fn go_back(&mut self, window: WindowId) {
let Some(win) = self.windows.get_mut(&window) else { return };
let Some(tab) = win.tab_mut() else { return };
if tab.page.is_some() && tab.web.is_some() {
// From an internal page back to the web page behind it.
if tab.page.is_some() && tab.has_web_behind() {
// From an internal page back to the web page it was opened from.
tab.page = None;
if tab.web.is_none() {
tab.pending_url = Some(tab.url.clone());
self.ensure_loaded(window);
}
self.redraw(window);
return;
}

View file

@ -500,8 +500,8 @@ impl App {
engine.set_page_content(sources, scripts.page_styles());
}
/// A web view for a tab, loading `url`.
pub fn build_webview(&mut self, tab_id: u64, url: Url) -> Web {
/// A web view for a tab, loading `url` (after the back/forward list of the tab's previous view, if any).
pub fn build_webview(&mut self, tab_id: u64, url: Url, history: Option<crate::engine::HistoryState>) -> Web {
if self.engine.is_none() {
self.start_engine();
}
@ -509,7 +509,10 @@ impl App {
let webview = engine.create_view(ViewId(tab_id), None);
let zoom = self.shared.settings.borrow().zoom_for(&util::host_of(&url));
webview.set_page_zoom(zoom);
webview.load(&url);
match &history {
Some(history) => webview.restore_history(history, &url),
None => webview.load(&url),
}
Web { webview }
}
@ -1127,8 +1130,8 @@ impl App {
while let Ok(msg) = self.downloads_rx.try_recv() {
self.on_download_msg(msg);
}
// A closing tab whose page doesn't answer (hung, or no close signal) goes after 3 s, unless it is asking.
let hung: Vec<(WindowId, u64)> = self.windows.iter().flat_map(|(w, win)| win.tabs.iter().filter(|t| t.dialog.is_none() && t.closing.is_some_and(|c| now.duration_since(c) > Duration::from_secs(3))).map(|t| (*w, t.id))).collect();
// A closing tab whose page doesn't answer goes after 3 s, unless it is asking.
let hung: Vec<(WindowId, u64)> = self.windows.iter().flat_map(|(w, win)| win.tabs.iter().filter(|t| t.close_overdue(now)).map(|t| (*w, t.id))).collect();
for (w, tab) in hung {
if self.shutdown_answered(tab) {
continue;
@ -1250,10 +1253,7 @@ impl App {
if discard > 0 && idle >= discard as u64 && !tab.pinned {
// Unload: forget the web view, keep the address to load it again when shown.
tab.pending_url = Some(tab.url.clone());
if let Some(web) = tab.web.take() {
win_detach.push(web.webview);
}
tab.load_status = None;
win_detach.extend(tab.take_web());
} else if freeze > 0 && idle >= freeze as u64 && !tab.frozen {
// WebKit throttles hidden views by itself (bg-tabs.txt) and has no suspend call; the flag only drives the tab strip.
tab.frozen = true;
@ -1507,7 +1507,8 @@ impl App {
win.tabs[i].pending_url = None;
return;
};
let web = self.build_webview(tab_id, parsed);
let history = self.windows.get_mut(&window).expect("found").tabs[i].history_state.take();
let web = self.build_webview(tab_id, parsed, history);
let win = self.windows.get_mut(&window).expect("found");
let tab = &mut win.tabs[i];
tab.web = Some(web);
@ -1526,7 +1527,8 @@ impl App {
if Page::from_url(&url).is_some() {
continue;
}
let web = self.build_webview(tab_id, parsed);
let history = self.windows.get_mut(&window).expect("found").tabs[i].history_state.take();
let web = self.build_webview(tab_id, parsed, history);
let win = self.windows.get_mut(&window).expect("found");
let tab = &mut win.tabs[i];
tab.web = Some(web);

View file

@ -41,6 +41,10 @@ pub struct Engine {
scripts: RefCell<Vec<String>>,
styles: RefCell<Vec<UserStyle>>,
views: RefCell<HashMap<ViewId, glib::WeakRef<webkit::WebView>>>,
/// Each view's content manager and its `nacre` message handler, unregistered when the view is forgotten.
messages: RefCell<HashMap<ViewId, (webkit::UserContentManager, glib::SignalHandlerId)>>,
/// Forgotten views, to count the ones something still keeps alive (selftest status).
forgotten: RefCell<Vec<glib::WeakRef<webkit::WebView>>>,
background: RefCell<gtk::gdk::RGBA>,
/// Hosts whose notifications the user allowed / blocked, told to WebKit when it starts a web process (so
/// `Notification.permission` reads "granted"/"denied" without asking again).
@ -244,6 +248,8 @@ impl Engine {
scripts: RefCell::new(Vec::new()),
styles: RefCell::new(Vec::new()),
views: RefCell::new(HashMap::new()),
messages: RefCell::new(HashMap::new()),
forgotten: RefCell::new(Vec::new()),
background: RefCell::new(gtk::gdk::RGBA::new(shade, shade, shade, 1.0)),
notifications,
filter_store,
@ -564,11 +570,14 @@ impl Engine {
self.add_content(&ucm);
ucm.register_script_message_handler("nacre", None);
let hub = self.hub.clone();
ucm.connect_script_message_received(Some("nacre"), move |_, value| {
let handler = ucm.connect_script_message_received(Some("nacre"), move |_, value| {
if let Some(msg) = crate::inject::parse_message(&hub.token, &value.to_str()) {
hub.push(Event::Page(id, msg));
}
});
if let Some((old, handler)) = self.messages.borrow_mut().insert(id, (ucm.clone(), handler)) {
release_messages(&old, handler);
}
// Media may start with sound by itself, as in Chromium and the original Nacre (WebKit's default lets it
// start only muted, so YouTube's watch page stayed paused).
let policies = webkit::WebsitePolicies::builder().autoplay(webkit::AutoplayPolicy::Allow).build();
@ -586,12 +595,25 @@ impl Engine {
view
}
/// Forget a closed view.
/// Forget a closed view. Its `nacre` handler goes first, while the content manager still lives: a message the page
/// posts after that is dropped by WebKit instead of reaching a destroyed manager (GLib CRITICAL).
pub fn forget(&self, id: ViewId) {
self.views.borrow_mut().remove(&id);
if let Some((ucm, handler)) = self.messages.borrow_mut().remove(&id) {
release_messages(&ucm, handler);
}
if let Some(web) = self.views.borrow_mut().remove(&id) {
let mut forgotten = self.forgotten.borrow_mut();
forgotten.retain(|w| w.upgrade().is_some());
forgotten.push(web);
}
self.hub.forget(id);
}
/// Web views alive: (in use, forgotten but still kept by something).
pub fn view_counts(&self) -> (usize, usize) {
(self.live_views().len(), self.forgotten.borrow().iter().filter(|w| w.upgrade().is_some()).count())
}
fn wire(self: &Rc<Self>, view: &View) {
let id = view.id();
let web = &view.web;
@ -910,3 +932,8 @@ mod tests {
assert!(!media_dirs(false).iter().any(|d| d.ends_with("tests/smoke/pages")));
}
}
fn release_messages(ucm: &webkit::UserContentManager, handler: glib::SignalHandlerId) {
ucm.disconnect(handler);
ucm.unregister_script_message_handler("nacre", None);
}

View file

@ -22,6 +22,8 @@ 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;

View file

@ -127,6 +127,21 @@ impl View {
self.web.try_close();
}
/// The back/forward list, for a later view of the same tab (`restore_history`).
pub fn history_state(&self) -> Option<super::HistoryState> {
self.web.session_state()
}
/// Give a new view an old view's back/forward list, then open `url`: the list's current entry when it is that
/// address (a load of the same address would add a second entry), else a new entry after it.
pub fn restore_history(&self, state: &super::HistoryState, url: &Url) {
self.web.restore_session_state(state);
match self.web.back_forward_list().and_then(|l| l.current_item()).filter(|item| item.uri().as_deref() == Some(url.as_str())) {
Some(item) => self.web.go_to_back_forward_list_item(&item),
None => self.load(url),
}
}
/// Back/forward list as URLs and the current index.
pub fn back_forward(&self) -> (Vec<Url>, usize) {
let Some(list) = self.web.back_forward_list() else { return (Vec::new(), 0) };

View file

@ -887,7 +887,7 @@ impl App {
"hidden_elements": t.hidden_elements, "pinned": t.pinned, "muted": t.muted, "playing_audio": t.playing_audio, "audible": t.audible(), "zoom": t.zoom,
"favicon": t.favicon.is_some(), "crashed": t.crashed, "can_back": t.can_go_back(), "can_forward": t.can_go_forward(),
"history_len": t.back_forward.len(), "find": [t.find.index, t.find.count], "prompts": t.prompts.len(),
"dialog": t.dialog.is_some(), "media": t.media.as_ref().map(|(m, _)| serde_json::json!({"title": m.title, "paused": m.paused, "duration": m.duration, "position": m.position})),
"dialog": t.dialog.is_some(), "closing": t.closing.is_some(), "page": t.page.as_ref().map(|p| p.url()), "history_state": t.history_state.is_some(), "media": t.media.as_ref().map(|(m, _)| serde_json::json!({"title": m.title, "paused": m.paused, "duration": m.duration, "position": m.position})),
"theme_color": t.theme_color.map(crate::theme::to_hex), "favicon_colour": t.favicon_colour.map(crate::theme::to_hex), "site_colour": t.site_colour().map(crate::theme::to_hex), "pip": t.pip_size.is_some(),
})
})
@ -906,6 +906,9 @@ impl App {
let b = self.shared.bookmarks.borrow();
[crate::store::bookmarks::BAR, crate::store::bookmarks::OTHER].iter().filter_map(|id| b.get(*id)).map(|n| n.children.iter().filter(|c| c.is_folder()).count()).sum::<usize>()
};
// Web views alive (in use, forgotten but kept) and a shortcut being recorded (S059).
let views = self.engine.as_ref().map(|e| e.view_counts()).unwrap_or_default();
let lifecycle = serde_json::json!({"views": views.0, "views_leaked": views.1, "capture_key": self.windows.get(&window).map(|w| w.ui.pages.capture_key.is_some())});
serde_json::json!({
"windows": self.windows.len(),
"notifications": self.notifications_shown,
@ -918,6 +921,7 @@ impl App {
"page_focused": self.windows.get(&window).map(|w| w.page_focused && w.active_webview().is_some_and(|v| v.focused())),
"frames": frames,
"painters": self.windows.values().flat_map(|w| &w.tabs).filter(|t| t.web.is_some()).count(),
"lifecycle": lifecycle,
"window_kinds": self.windows.values().map(|w| format!("{:?}", w.kind)).collect::<Vec<_>>(),
"tabs": tabs,
"downloads": downloads,

View file

@ -155,6 +155,8 @@ pub struct Tab {
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>,
@ -218,6 +220,7 @@ impl Tab {
page: Some(Page::NewTab),
web: None,
pending_url: None,
history_state: None,
url: "nacre://newtab".into(),
title: "New tab".into(),
favicon: None,
@ -294,8 +297,35 @@ impl Tab {
}
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)
// 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 {
@ -333,6 +363,26 @@ impl Tab {
mod tests {
use super::*;
// 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() {

View file

@ -216,6 +216,11 @@ pub fn draw(root: &mut egui::Ui, f: &mut Frame) {
dialogs::page_dialogs(&ctx, f);
menus::flyouts(&ctx, f);
toasts(&ctx, f);
// Recording a shortcut lasts while its button is on screen: left behind (another section or tab, the settings
// tab closed) it would keep every shortcut of the window from working (S059).
if !std::mem::take(&mut f.ui.pages.capture_shown) {
f.ui.pages.capture_key = None;
}
}
/// The page itself: a web page's framebuffer, or one of Nacre's pages.

View file

@ -28,6 +28,8 @@ pub struct PageState {
pub settings_search: String,
/// Action whose shortcut is being recorded.
pub capture_key: Option<crate::keys::Action>,
/// The shortcut being recorded was drawn this frame.
pub capture_shown: bool,
pub new_engine: (String, String),
pub new_list_url: String,
pub keep_active_input: String,

View file

@ -1223,6 +1223,7 @@ fn keys(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
for (action, key, label, _) in Action::ALL {
let shortcuts: Vec<String> = map.shortcuts(*action).iter().map(Shortcut::label).collect();
let capturing = f.ui.pages.capture_key == Some(*action);
f.ui.pages.capture_shown |= capturing && ui.is_visible();
let changed = s.keys.contains_key(*key);
row(ui, label, if changed { "Changed" } else { "" }, |ui| {
if changed && icon_button(ui, icons::UNDO, "Reset to the default").clicked() {
@ -1232,6 +1233,7 @@ fn keys(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
let kind = if capturing { ButtonKind::Tonal } else { ButtonKind::Outlined };
if button(ui, kind, None, &text).clicked() {
f.ui.pages.capture_key = Some(*action);
f.ui.pages.capture_shown = true;
}
});
}