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
16 changed files with 285 additions and 32 deletions

View file

@ -64,7 +64,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
| `nice cargo build --release -j 2` | compile check, produces `target/release/nacre` | now |
| `nice cargo test --release -j 2` | unit tests (44, ~16 s test-profile build then <1 s run; shares the S001 build) (util, settings, history, bookmarks, permissions, vault, dns, bridge loopback, download, adblock, keys, scripts, updates, inject, hub, theme, ui::widgets input, ui::paint, ui::pages::newtab) | first successful build; not alongside a build |
| `src/selftest.rs` | in-app self test: `NACRE_SCRIPT=<file>` runs script commands (listed at its top) | now |
| `tools/smoke.sh <script> [outdir]` | smoke run in a hidden nested Wayland session (`tools/nested-session.sh start\|stop <dir> [WxH]`: Xvfb → nested niri, software GL, own runtime dir and bus; `SMOKE_SIZE` = nested output size, window at 0,0) with a throwaway home; selftest `click`/`rclick`/`pagescroll`/`pagetype` are real compositor input there (`tools/wl-input`, own crate, built on first use; `wtype`), `resize` goes through the nested niri; outdir (default `target/smoke/<name>-<time>`, use a fresh one: `home/` persists) gets `nacre.log`, `selftest.log`, `<shot>.png`, `<status>.json`, `home/`, `session/`; exits non-zero on crash, panic, no `status done` or a failed `assert <js>`. Scripts in `tests/smoke/` (`launch.txt` offline, `https.txt` needs internet, `restore.txt` with `SMOKE_HOME=<launch outdir>/home`, `chrome.txt` chrome and every flyout dark and light, offline; `colours.txt` colours after welcome and site colour vs internal pages, hidden `SMOKE_SIZE=1280x1100`; `input.txt` real clicks, typing, right click, wheel on a web page, offline; `basics.txt` tabs, navigation, find, zoom, full screen, pop-ups, offline; `heavy-web.txt` DuckDuckGo, Wikipedia, YouTube, needs internet, `SMOKE_TIMEOUT=900`; `keys.txt` every shortcut action, offline; `privacy-net.txt` DNT/GPC/Save-Data headers and third-party cookies on a loopback server, offline, start `python3 tests/smoke/net/server.py &` first; `site-doctor.txt` Google sign-in, captchas, Reddit, GitHub, needs internet; `cache.txt` HTTP cache, offline, start `python3 tests/smoke/cache/server.py &` first; selftest `launch <args>` checks single instance; `cookies.txt` → `cookies-restart.txt` → `cookies-cleared.txt` encrypted cookies across restarts with `SMOKE_KEYRING=1` (own throwaway GNOME Keyring + bus) and `SMOKE_HOME`, `cookies-nokeyring.txt` without, server.py first; `zap.txt` ad removal animation (cookie shield mid-animation, slots closed, players kept, Motion off), dark and light, offline, `SMOKE_SIZE=1280x900`; `crash-adblock.txt` R5-01 regression, ~1300 blocked loads with reloads/navigations mid-load plus 3200 timers under GC pressure, offline, server.py first); header documents env vars and commands. `SMOKE_VISIBLE=1` shows the run on the user's screen (real GPU; page input synthesized in the page, no `rclick`/`resize`); it refuses to start unless the user's niri config has the `dev.nacre.Nacre` window rule from the smoke.sh header (DP-1, no focus), so it never moves the user's focus or workspace (D-044). WebKit state (S050): launch, basics, input, keys, chrome, dialogs, pip, auth, stores-*, integ-spell, net-*, privacy-net, privacy-mode, cache*, crash-adblock green hidden (loopback skips the bridge, no `NACRE_NO_BRIDGE` needed); other scripts not yet. Read the PNGs | now (S003, S046) |
| `tools/smoke.sh <script> [outdir]` | smoke run in a hidden nested Wayland session (`tools/nested-session.sh start\|stop <dir> [WxH]`: Xvfb → nested niri, software GL, own runtime dir and bus; `SMOKE_SIZE` = nested output size, window at 0,0) with a throwaway home; selftest `click`/`rclick`/`pagescroll`/`pagetype` are real compositor input there (`tools/wl-input`, own crate, built on first use; `wtype`), `resize` goes through the nested niri; outdir (default `target/smoke/<name>-<time>`, use a fresh one: `home/` persists) gets `nacre.log`, `selftest.log`, `<shot>.png`, `<status>.json`, `home/`, `session/`; exits non-zero on crash, panic, no `status done` or a failed `assert <js>`. Scripts in `tests/smoke/` (`launch.txt` offline, `https.txt` needs internet, `restore.txt` with `SMOKE_HOME=<launch outdir>/home`, `chrome.txt` chrome and every flyout dark and light, offline; `colours.txt` colours after welcome and site colour vs internal pages, hidden `SMOKE_SIZE=1280x1100`; `input.txt` real clicks, typing, right click, wheel on a web page, offline; `basics.txt` tabs, navigation, find, zoom, full screen, pop-ups, offline; `heavy-web.txt` DuckDuckGo, Wikipedia, YouTube, needs internet, `SMOKE_TIMEOUT=900`; `keys.txt` every shortcut action, offline; `privacy-net.txt` DNT/GPC/Save-Data headers and third-party cookies on a loopback server, offline, start `python3 tests/smoke/net/server.py &` first; `site-doctor.txt` Google sign-in, captchas, Reddit, GitHub, needs internet; `cache.txt` HTTP cache, offline, start `python3 tests/smoke/cache/server.py &` first; selftest `launch <args>` checks single instance; `cookies.txt` → `cookies-restart.txt` → `cookies-cleared.txt` encrypted cookies across restarts with `SMOKE_KEYRING=1` (own throwaway GNOME Keyring + bus) and `SMOKE_HOME`, `cookies-nokeyring.txt` without, server.py first; `zap.txt` ad removal animation (cookie shield mid-animation, slots closed, players kept, Motion off), dark and light, offline, `SMOKE_SIZE=1280x900`; `stuck.txt` tab lifecycle (leave-page question, Reload, nacre:// pages free their view, Back with history, chatty page closes without CRITICAL, shortcut recording ends), offline, `SMOKE_SIZE=1280x900`; `crash-adblock.txt` R5-01 regression, ~1300 blocked loads with reloads/navigations mid-load plus 3200 timers under GC pressure, offline, server.py first); header documents env vars and commands. `SMOKE_VISIBLE=1` shows the run on the user's screen (real GPU; page input synthesized in the page, no `rclick`/`resize`); it refuses to start unless the user's niri config has the `dev.nacre.Nacre` window rule from the smoke.sh header (DP-1, no focus), so it never moves the user's focus or workspace (D-044). WebKit state (S050): launch, basics, input, keys, chrome, dialogs, pip, auth, stores-*, integ-spell, net-*, privacy-net, privacy-mode, cache*, crash-adblock green hidden (loopback skips the bridge, no `NACRE_NO_BRIDGE` needed); other scripts not yet. Read the PNGs | now (S003, S046) |
| `nacre://gallery` + `SMOKE_SIZE=1400x2800 tools/smoke.sh tests/smoke/gallery.txt` | every design token and widget, dark and light (+ new tab and settings shots); read the PNGs | now (S015) |
| `SMOKE_SIZE=1400x1200 tools/smoke.sh tests/smoke/newtab.txt` | new tab page dark/light, nothing playing and a video playing, weather failed state, tall/narrow/phone widths (offline); `tests/smoke/newtab-weather.txt` shoots the real weather card (needs internet); read the PNGs | now (S017) |
| `SMOKE_SIZE=1400x900 tools/smoke.sh tests/smoke/backgrounds.txt` | every new tab background with the pointer, Customize panel dark/light, image + blur, GIF frames; `perf-*-a/b.json` `frames` (median/max draw ms, `drawn` count) per background at Lots/Fast, hidden tab, still, Motion off. Selftest `pointer x y`, `customize`; `@PAGESDIR@` = path of tests/smoke/pages | now (S018) |

View file

@ -17,12 +17,12 @@ Three faults in how tabs live and die (user report, D-048 testing rule):
- Last 3 PROGRESS entries (S054's fix of a closing tab)
## Steps
- [ ] Reproduce 1 with the selftest: tab whose page answers `beforeunload`, close cancelled / page kept, then Reload and scroll; also an open flyout or dialog left on a tab you switch away from. Write down which state stays stuck (log it, don't guess).
- [ ] Fix the root cause of 1; add a guard so a stuck `closing`/`dialog` state can't silently eat Reload (log a line if it ever happens).
- [ ] 2: closing a tab (or navigating away from) a nacre:// page drops its web view (`detach` + `engine.forget`) and clears page state; a web page navigating to nacre:// keeps no hidden live view.
- [ ] 3: unregister the `nacre` script message handler and disconnect its handler on view close/forget; CRITICAL line gone.
- [ ] Unit test for the pure part (closing state rules) where feasible.
- [ ] `tests/smoke/stuck.txt` (offline): the repro of 1 + close a nacre:// tab + close a web tab while its page posts messages; asserts Reload works, view count drops, `nacre.log` has no `CRITICAL`. Run it and `basics.txt` only (D-048).
- [x] Reproduce 1 with the selftest: tab whose page answers `beforeunload`, close cancelled / page kept, then Reload and scroll; also an open flyout or dialog left on a tab you switch away from. Write down which state stays stuck (log it, don't guess).
- [x] Fix the root cause of 1; add a guard so a stuck `closing`/`dialog` state can't silently eat Reload (log a line if it ever happens).
- [x] 2: closing a tab (or navigating away from) a nacre:// page drops its web view (`detach` + `engine.forget`) and clears page state; a web page navigating to nacre:// keeps no hidden live view.
- [x] 3: unregister the `nacre` script message handler and disconnect its handler on view close/forget; CRITICAL line gone.
- [x] Unit test for the pure part (closing state rules) where feasible.
- [x] `tests/smoke/stuck.txt` (offline): the repro of 1 + close a nacre:// tab + close a web tab while its page posts messages; asserts Reload works, view count drops, `nacre.log` has no `CRITICAL`. Run it and `basics.txt` only (D-048).
- [ ] PROGRESS entry, INDEX line, tracker, commit `S059: …`, push.
## End criteria

View file

@ -11,7 +11,7 @@ Dropped with Servo (D-032): S011, S029, S030, S032, S033, S037, S038.
- [ ] [S054 — Site pass on WebKit vs Chromium reference](08%20WebKit%20engine/S054-site-pass.md) · Opus high
## 09 Fix round (after S054; S059 first, S060/S062/S064/S065 can run beside it; S066 last)
- [ ] [S059 — Tab lifecycle: stuck pages, nacre:// pages unloading, script message handler](09%20Fix%20round/S059-tab-lifecycle.md) · Opus high
- [x] [S059 — Tab lifecycle: stuck pages, nacre:// pages unloading, script message handler](09%20Fix%20round/S059-tab-lifecycle.md) · Opus high
- [ ] [S060 — Picture in picture keeps working (focus)](09%20Fix%20round/S060-pip-focus.md) · Opus medium · 🧑
- [ ] [S061 — A site's own context menu wins; video clicks don't open ads](09%20Fix%20round/S061-site-menus-clickthrough.md) · Opus medium · 🧑
- [ ] [S062 — Memory saver that actually unloads, sliders, resting tab icons](09%20Fix%20round/S062-memory-saver.md) · Sonnet high

View file

@ -464,6 +464,15 @@ Later: S010 list: user checks the Discord icon with their own client (the Discor
- Not done: no real 10-tab list (tune list has six tabs); no visible/real-GPU run; `tc netem` not used (paced server instead); idle CPU varies a lot between runs.
- Later: a file without validators or cache headers (like `bare.js`) is refetched on every visit, as in any browser.
## S059 — Tab lifecycle: stuck tab, views freed, script message handler (2026-11-18)
- Root cause of the stuck tab (reproduced in `stuck.txt`): a web page's open question ("Leave this page?" from a Reload or close, or an alert) stayed on the tab when it moved to one of Nacre's pages, with the web view kept hidden behind, so the page kept waiting on it and Reload went to that hidden view. A second stuck state: a shortcut being recorded in settings (`capture_key`) stayed on after leaving the section/tab, and every shortcut of the window (Ctrl+R/F5 too) was eaten.
- Fixes: `Tab::take_web` (navigating to nacre://, memory saver, Free memory) detaches + forgets the view, denies/dismisses its open dialog and keeps its back/forward list (`HistoryState`, WebKit session state); Back from the page builds a new view with that list (`View::restore_history`, goes to the current entry). Shortcut recording ends when its button isn't drawn in a frame (`capture_shown`). The tick's 3 s close timeout now only waits for a "Leave this page?" (`Tab::close_overdue`), not any dialog.
- Guard: Reload on a closing tab is ignored with `tab N: Reload ignored, the tab is closing (x s, dialog true)`.
- Views: `Engine::forget` disconnects and unregisters the `nacre` message handler before the content manager can drop; selftest status `lifecycle` {views, views_leaked, capture_key}.
- Verified: `cargo test` 88 + webext 1; hidden `stuck.txt` (new, offline, `pages/chatty.html`) and `basics.txt` exit 0, `grep -c CRITICAL nacre.log` = 0 both; shots read.
- Not done: the CRITICAL line never showed in a hidden run before the fix either (not reproduced; fix by reading the API); settings wheel scroll had no cause of its own found (the dialog left over the page is the likely one); a real key press of Reload while recording not scripted (status check instead); no visible run.
- Later: when the app is busy at a render, `EguiArea` keeps the previous page rect (egui_area.rs `if let Ok(rect)`), which could route input to a stale rect.
## Later
- A link followed inside a frame still goes through the tab's navigation policy (WebKit's GTK API has no frame info; S050).
- file:// media outside the XDG user folders doesn't play (WebKit sandbox, D-043).

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;
}
});
}

View file

@ -0,0 +1,9 @@
<!doctype html><meta charset="utf-8"><title>Chatty</title>
<body style="font:16px sans-serif;padding:24px">
<p>Posts to Nacre's message handler every few milliseconds, also while it closes (S059).</p>
<script>
const post = () => { try { window.webkit.messageHandlers.nacre.postMessage('{"chatty":1}'); } catch (e) {} };
setInterval(post, 2);
window.addEventListener('pagehide', () => { for (let i = 0; i < 200; i++) post(); });
</script>
</body>

110
tests/smoke/stuck.txt Normal file
View file

@ -0,0 +1,110 @@
# Tab lifecycle (S059): a tab that asked "Leave this page?" and stayed takes Reload again; Reload while the question
# is up is ignored with a log line; Nacre's pages hold no web view (navigating there frees it, Back brings the page
# back with its history); closing a tab whose page posts messages frees its view without a GLib CRITICAL; a shortcut
# being recorded in settings stops when its tab is left. Offline.
# Run: SMOKE_SIZE=1280x900 tools/smoke.sh tests/smoke/stuck.txt ; then `grep -c CRITICAL <out>/nacre.log` = 0.
wait 3
resize 1280 900
open @PAGES@/dialogs.html
waitload
# The page's beforeunload only asks after a click in it.
locate #t
wait 0.5
click @
wait 0.5
cmd close_tab
wait 1.2
expect /active/dialog true
expect /active/closing true
shot leave-ask
# Reload while the question is up: ignored (log line), the view isn't loaded into while WebKit closes it.
cmd reload
wait 0.5
expect /tab_count 1
key Escape
wait 0.5
expect /active/dialog false
expect /active/closing false
expect /tab_count 1
# Stayed: Reload works again (the marker set now is gone after it).
js window.__mark = 1
assert window.__mark === 1
# The page was clicked, so the Reload asks too: Leave (the dialog's second button).
cmd reload
wait 1.2
expect /active/dialog true
expect /active/closing false
shot reload-ask
tap 700 542
wait 1.5
waitfor 10 window.__mark === undefined && document.readyState === "complete"
expect /active/dialog false
js window.onbeforeunload = null
open @PAGES@/hello.html
waitload
expect /active/title "Smoke page"
# A web page navigating to one of Nacre's pages lets its view go; Back loads it again, history kept.
open @PAGES@/basics.html
waitload
expect /lifecycle/views 1
cmd navigate nacre://settings
wait 1
expect /active/has_web false
expect /active/history_state true
expect /active/can_back true
wait 2
expect /lifecycle/views 0
expect /lifecycle/views_leaked 0
status on-settings
cmd back
waitload
expect /active/has_web true
expect /active/title "Basics"
wait 1
expect /active/can_back true
cmd back
waitload
expect /active/title "Smoke page"
# A nacre:// tab closes at once and leaves nothing behind.
newtab nacre://history
wait 1
expect /tab_count 2
cmd close_tab
wait 1
expect /tab_count 1
# A tab whose page keeps posting messages closes and frees its view, and WebKit drops the late messages.
newtab @PAGES@/chatty.html
waitload
wait 1
expect /lifecycle/views 2
cmd close_tab
wait 3
expect /tab_count 1
expect /lifecycle/views 1
expect /lifecycle/views_leaked 0
# A shortcut being recorded stops when its tab is left (else every shortcut of the window stays dead).
newtab nacre://settings/keys
wait 1.5
tap 1091 313
wait 0.5
expect /lifecycle/capture_key true
shot keys
cmd select 0
wait 0.5
expect /lifecycle/capture_key false
# And a web page's question left on the tab goes with its view when the tab opens one of Nacre's pages.
open @PAGES@/dialogs.html
waitload
locate #t
wait 0.5
click @
wait 0.5
cmd reload
wait 1.2
expect /active/dialog true
cmd navigate nacre://settings
wait 2
expect /active/dialog false
expect /lifecycle/views_leaked 0
status done
quit