S061: site menus win on every right click, menu keys, pop-ups need a click, ad frames can't take the tab

WebKit asks for a menu on cancelled right clicks once it has shown one; the bridge
script's answer decides now. Script navigations that may be a frame's are no longer
rewritten into loads in the tab (an ad frame took the tab over on the user's site).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-18 04:55:53 -06:00
commit 09233cdaf3
20 changed files with 372 additions and 28 deletions

View file

@ -78,6 +78,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
| `tools/engine-test/run.sh chromium\|webkit` + `analyze.py` | engine comparison: one browser visible on DP-1, throwaway profile, sites from `sites.txt`, per-second RAM (PSS), CPU, GPU of the whole process tree into `docs/engine/runs/<engine>/samples.csv`; `webkit_shell.py` is the WebKitGTK 6.0 shell (needs `webkitgtk-6.0`); report `docs/engine/engine-comparison.md`. Never run two at once or alongside cargo | now |
| `python3 tests/smoke/net/server.py &` + `tools/smoke.sh tests/smoke/site-data.txt`; `tools/smoke.sh tests/smoke/media-audio.txt` | site info cookie/data count, Clear data time range (stored data kept, cookies always whole); WebKit `is-playing-audio` → tab audible, tab mute via `set_is_muted` (`pages/sound.html`, `?element` plays `tone.ogg` with Media Session metadata; WebKit's MPRIS player shows on the run's bus: `busctl --address=unix:path=$(cat <out>/session/runtime)/bus list`). Offline, hidden | now (S051) |
| `tools/smoke.sh tests/smoke/pip.txt` (+ `tools/hidden.sh tests/smoke/pip.txt <out> -- tests/smoke/pip-driver.sh`: `<out>/windows.json` PiP floating), `bindings.txt` (side buttons, middle click; hidden only), `ctxmenu.txt` (site menu vs Nacre's; hidden only), `pip-return.txt` (page input after PiP and back; hidden only), `pip-loop.txt` (+ `-- tests/smoke/pip-loop-driver.sh`: PiP three rounds, ended by command, Escape, window close; `windows-<n>.json`; hidden only), selftest `pick x y` (GTK's pick at a page point + view state), `python3 tests/smoke/net/server.py &` + `SMOKE_SIZE=1280x900 tools/smoke.sh tests/smoke/auth.txt`, `tests/smoke/visible-ui.txt` (by hand, header) | PiP moves the live view and back (offline); HTTP sign-in cancel + saved login (offline); visible: portal file chooser, notification, page full screen, Web Inspector (`dialogs.txt` now also checks dialog answers, context menu, leave page, permission bars, notifications count) | now (S048, S056) |
| `python3 tests/smoke/net/server.py &` + `tools/smoke.sh tests/smoke/player-ad.txt`; `tools/smoke.sh tests/smoke/ctxmenu.txt` | video site ad tricks (click catcher over the player, pop-under on click, pop-up without a click, ad frame in a cross-site frame must not take the tab); site context menus (`pages/site-menu.html`: YouTube-like toggle, Discord-like, plain, each 3×) and Nacre's menu keys via selftest `realkey <wtype keys>`. Hidden only, offline | now (S061) |
| `tools/hidden.sh <script> [outdir] [-- driver.sh]` | WebKit build hidden with a driver script: Xvfb → nested niri (`tools/nested-session.sh`), throwaway home, software GL, `NACRE_SCRIPT`; the driver gets `click`/`scroll` (`tools/wl-input`), `grab` (grim), `key`/`type` (wtype). Scripts in `tests/hidden/` (`basic.txt` offline; `web.txt` + `web-driver.sh` needs internet). Read the PNGs | now (S045) |
| appimagetool, wine + Inno Setup, VM "Windows 10" | packaging and Windows checks | see the user's global CLAUDE.md "Building" |

View file

@ -15,12 +15,12 @@
- `tests/smoke/ctxmenu.txt` header
## Steps
- [ ] Find why priority is lost on repeat clicks (e.g. `defaultPrevented` read before the page's listener ran, a stale "site menu" flag per view, YouTube's listener on a different target/phase). Fix so `defaultPrevented` decides each time.
- [ ] Test page `tests/smoke/pages/site-menu.html`: own menu that toggles like YouTube's (first right-click custom, second native), plus a Discord-style always-custom area; extend `ctxmenu.txt` to right-click each 3×.
- [ ] Nacre's menu: arrow keys, Enter, Esc (from S035).
- [ ] Ad on click: local repro page (player under a transparent full-size link + `window.open` on first click, like pop-under scripts); make Nacre block the un-gestured/pop-under window and let the click reach the video. Then load the real site once in a hidden run if it isn't refused; if refused or blocked, hand it to the user (🧑) with the steps.
- [ ] Run `ctxmenu.txt` and the new click test only (D-048).
- [ ] PROGRESS entry, INDEX line (also mark S035 superseded), tracker, commit `S061: …`, push.
- [x] Find why priority is lost on repeat clicks (e.g. `defaultPrevented` read before the page's listener ran, a stale "site menu" flag per view, YouTube's listener on a different target/phase). Fix so `defaultPrevented` decides each time.
- [x] Test page `tests/smoke/pages/site-menu.html`: own menu that toggles like YouTube's (first right-click custom, second native), plus a Discord-style always-custom area; extend `ctxmenu.txt` to right-click each 3×.
- [x] Nacre's menu: arrow keys, Enter, Esc (from S035).
- [x] Ad on click: local repro page (player under a transparent full-size link + `window.open` on first click, like pop-under scripts); make Nacre block the un-gestured/pop-under window and let the click reach the video. Then load the real site once in a hidden run if it isn't refused; if refused or blocked, hand it to the user (🧑) with the steps.
- [x] Run `ctxmenu.txt` and the new click test only (D-048).
- [x] PROGRESS entry, INDEX line (also mark S035 superseded), tracker, commit `S061: …`, push.
## End criteria
- `ctxmenu.txt` exit 0: site menu shown (no Nacre menu) on every right-click where the page prevents default; Nacre's menu elsewhere; keys work.

View file

@ -13,7 +13,7 @@ Dropped with Servo (D-032): S011, S029, S030, S032, S033, S037, S038.
## 09 Fix round (after S054; S059 first, S060/S062/S064/S065 can run beside it; S066 last)
- [x] [S059 — Tab lifecycle: stuck pages, nacre:// pages unloading, script message handler](09%20Fix%20round/S059-tab-lifecycle.md) · Opus high
- [x] [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 · 🧑
- [x] [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
- [ ] [S063 — Lock down nacre:// pages; passwords unlock on every open](09%20Fix%20round/S063-nacre-pages-lockdown.md) · Opus medium
- [ ] [S064 — History flyout, bookmark flyout on tab switch, About lists nacre:// pages](09%20Fix%20round/S064-history-flyout-about.md) · Sonnet high

View file

@ -54,3 +54,4 @@
- D-048 — 2026-11-18 — Testing is targeted: each plan runs the smoke it adds or the one or two its change touches, never whole suites again; problems noticed elsewhere are reported in PROGRESS, not chased. — Earlier rounds spent much on repeated full runs that missed the real bugs. — S059–S066
- D-049 — 2026-11-18 — Internal pages: web content never opens, redirects to, frames or pops up a `nacre://` URL; only the user's own actions open them. `nacre://passwords` asks for the vault unlock on every open, relocks when its tab is hidden, switched, navigated or closed, and is never saved in the session. — Pages could open nacre://passwords with a link. — S063
- D-050 — 2026-11-18 — Amends D-022: a custom download manager is a user-given name + loopback port (several allowed), listed with the built-in managers; the endpoint is `http://127.0.0.1:<port>/` with D-022's body, ping and fallback. S036 superseded by S065. — User's choice. — S065
- D-051 — 2026-11-18 — Pop-ups and frames: a site not asked about gets pop-ups only from a click or key press (Chromium's rule); Allow/Block per site as before. Nacre's menu shows only when the page didn't cancel `contextmenu` (the bridge script's answer decides, not WebKit's signal). A script navigation not proven to be a frame's is never rewritten into a load in the tab; the browser reloads it only once the tab itself starts loading it. — WebKit asks for menus on cancelled right clicks after its first menu; ad frames took tabs over through Nacre's rewrites. — S061 — later pop-up, menu or navigation-policy work

View file

@ -481,6 +481,15 @@ Later: S010 list: user checks the Discord icon with their own client (the Discor
- Also tried (orchestrator's suspects): a visible DP-1 run (real GPU, user's niri, 3 rounds, `cmd pip`; round 2 a real Escape, round 3 niri close-window by id; niri windows sampled 1/3/5 s into each round): the PiP window was floating and focused for the whole 5 s every round, each round a new window id, the old PiP window gone from niri's list after exit. Code read: the only `present()` calls are `open_window` (the new window itself), opening a link in a new tab and a second launch; nothing presents or focuses the parent on PiP enter/exit; the closed PiP window's handlers hold only a weak app ref and its id. The user's niri config has no Nacre rule and no focus-follows-mouse.
- Not done: 🧑 the user trying PiP 3× on YouTube on their screen (deferred overnight, box left unticked); the user's exact steps for "focus goes back" weren't known, so a focus loss specific to the real screen may remain.
## S061 — A site's own context menu wins; video clicks don't open ads (2026-11-18)
- Priority, root cause (reproduced hidden): once WebKit has shown one menu on a page it emits `context-menu` even for right clicks the page cancels (it reuses its last hit test), so after one Nacre menu every site menu got Nacre's on top (the user's YouTube case). Fix: the bridge script reports after dispatch whether the page cancelled (`context_end`); Nacre shows its menu only when not (`tabs::MenuWait`; 300 ms fallback for pages without the script). Stale right-click details are dropped on each new click.
- Nacre's menu: Up/Down/Enter/Escape (S035). WebKit keeps the keyboard after a right click, so the window's key handler sends those keys to the open menu.
- Ad on click: one hidden load of the user's site (no account): the tab's own page ended up on an ad frame's address (`cdn-fc.com/creatives/…`). Cause: Nacre's rewrites of a script navigation (HTTPS-only upgrade, tracking-param strip, user-agent reload) load in the tab, and a frame inside a cross-site frame can't be found by the page check. Fix: such navigations (`maybe_frame`) load where they were going; only if the tab itself starts loading that URL does the browser load it again with its rules (`Tab::redo`). Also pop-ups need a click or key press unless the site is allowed (Chromium's rule, the "pop-up blocked" bar otherwise); listed pop-up addresses were already stopped by WebKit's content filters; a zapped ad no longer catches clicks while it fades.
- Tests: `ctxmenu.txt` extended (`pages/site-menu.html`: YouTube-like toggle, Discord-like always-own, plain, each 3×, keys), new `player-ad.txt` (`pages/player-ad.html` click catcher + pop-unders, `frame-hijack.html` + `frame-ad.html`; server.py serves them and `/popup-list.txt`); selftest `realkey`. The frame case fails without the fix (tab went to the frame's URL).
- Verified: hidden `ctxmenu.txt`, `player-ad.txt`, `basics.txt` exit 0; `cargo test` 88 + webext 1.
- Not done: 🧑 the real site after the fix was not reloaded (plan allows one hidden load; it was used to find the cause): the user should open a video there and click the player once to confirm. No visible run; YouTube/Discord menus not rechecked live.
- Later: a link clicked inside a frame still goes through the tab's policy (S050 note); WebKit treats `evaluate_javascript` window.open as a user gesture.
## 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

@ -1364,6 +1364,16 @@ impl App {
}
let outcome = crate::net::policy::decide(&self.hub.config.borrow(), &url);
let Some(view) = tab.webview().cloned() else { return request.allow() };
// Maybe a frame's: let it load where it was going; if it turns out to be the tab's own load, it is
// loaded again from the browser then (`redo`). An ad frame never takes the tab over this way.
if request.maybe_frame {
let quirk = self.hub.config.borrow().wants_ua_quirk(&url);
let ua_change = self.engine.as_ref().is_some_and(|e| e.own_user_agent(&view) != quirk);
if !matches!(outcome, crate::net::policy::Outcome::Allow) || ua_change && request.reloadable {
tab.redo = Some(url);
}
return request.allow();
}
match outcome {
crate::net::policy::Outcome::Upgrade(secure) => {
request.deny();
@ -1664,7 +1674,19 @@ impl App {
}
},
"context" => {
self.windows.get_mut(&w).expect("found").tabs[i].context = Some(data);
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
// A new right click: what was waiting for the last one is stale.
tab.context = Some(data);
tab.menu_wait = crate::tabs::MenuWait::None;
},
"context_end" => {
let prevented = data.get("prevented").and_then(|v| v.as_bool()).unwrap_or(false);
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
match std::mem::take(&mut tab.menu_wait) {
crate::tabs::MenuWait::Menu(request, _) if !prevented => self.show_page_menu(w, i, *request),
crate::tabs::MenuWait::Menu(..) => tab.context = None,
_ => tab.menu_wait = crate::tabs::MenuWait::Answer(prevented),
}
},
"login_form" | "login_focus" => {
let settings = self.shared.settings.borrow().vault.clone();

View file

@ -792,7 +792,7 @@ impl App {
}
self.redraw(w);
},
Event::CreateNew(parent, view, url) => self.on_create_new(parent, view, url),
Event::CreateNew(parent, view, url, gesture) => self.on_create_new(parent, view, url, gesture),
Event::OpenLink(id, url, front) => {
if let Some((w, i)) = self.find_webview(id) {
let from = Some(self.windows[&w].tabs[i].id);
@ -859,6 +859,12 @@ impl App {
tab.page = None;
}
tab.prompts.retain(|p| matches!(p, crate::tabs::Prompt::SaveLogin { .. }));
if let Some(redo) = tab.redo.take()
&& let Some(view) = tab.webview()
&& view.url().as_ref() == Some(&redo)
{
view.load(&redo);
}
},
LoadState::Committed => {
self.windows.get_mut(&w).expect("found").tabs[i].load_status = Some(status);
@ -972,11 +978,18 @@ impl App {
/// A pop-up opened as a tab next to its opener (WebKit already made its view, related to the opener's).
/// Pop-ups open as tabs next to their opener (a related view keeps `window.opener`).
fn on_create_new(&mut self, parent: ViewId, view: View, url: Option<Url>) {
/// As in Chromium, a site that wasn't asked about gets pop-ups only from a click or key press (S061). Pop-ups to
/// addresses the ad lists block never get here: WebKit's content filters stop them.
fn on_create_new(&mut self, parent: ViewId, view: View, url: Option<Url>, gesture: bool) {
use crate::store::permissions::{Answer, Kind};
let found = self.find_webview(parent);
let blocked = found.is_some_and(|(w, i)| {
let host = self.windows[&w].tabs[i].host();
self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, crate::store::permissions::Kind::Popups) == crate::store::permissions::Answer::Block
match self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, Kind::Popups) {
Answer::Allow => false,
Answer::Block => true,
Answer::Ask => !gesture,
}
});
let Some((w, i)) = found.filter(|_| !blocked) else {
// WebKit already holds the view: the page sees its window close at once.
@ -1075,16 +1088,28 @@ impl App {
}
},
Control::ContextMenu(menu) => {
let win = self.windows.get_mut(&w).expect("found");
let tab = &mut win.tabs[i];
let extra = tab.context.take();
let page_menu = crate::ui::menus::PageMenu::new(menu, extra, &tab.url, tab.media.is_some());
tab.dialog = Some(crate::tabs::Dialog::ContextMenu(Box::new(page_menu)));
// Only when the page didn't cancel the right click (its own menu): WebKit asks either way once it
// has shown one menu on the page. The page's answer comes from the bridge script, before or after.
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
match std::mem::take(&mut tab.menu_wait) {
crate::tabs::MenuWait::Answer(true) => tab.context = None,
crate::tabs::MenuWait::Answer(false) => self.show_page_menu(w, i, menu),
_ => tab.menu_wait = crate::tabs::MenuWait::Menu(Box::new(menu), Instant::now()),
}
},
}
self.redraw(w);
}
/// Nacre's right-click menu for a tab's page.
pub fn show_page_menu(&mut self, w: WindowId, i: usize, menu: crate::engine::PageMenuRequest) {
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
let extra = tab.context.take();
let page_menu = crate::ui::menus::PageMenu::new(menu, extra, &tab.url, tab.media.is_some());
tab.dialog = Some(crate::tabs::Dialog::ContextMenu(Box::new(page_menu)));
self.redraw(w);
}
fn on_notification(&mut self, id: Option<ViewId>, notification: crate::engine::Notification) {
let host = id.and_then(|id| self.tab_mut(id).map(|t| t.host())).unwrap_or_default();
// WebKit shows only what the page was granted (a prompt answer, or the saved ones); a site blocked since stays quiet.
@ -1138,6 +1163,13 @@ impl App {
}
self.close_tab(w, tab, true);
}
// A right click whose page never answered (no bridge script: scripts off): the menu shows after 300 ms.
let unanswered: Vec<(WindowId, usize)> = self.windows.iter().flat_map(|(w, win)| win.tabs.iter().enumerate().filter(|(_, t)| matches!(t.menu_wait, crate::tabs::MenuWait::Menu(_, at) if now - at > Duration::from_millis(300))).map(|(i, _)| (*w, i))).collect();
for (w, i) in unanswered {
if let crate::tabs::MenuWait::Menu(menu, _) = std::mem::take(&mut self.windows.get_mut(&w).expect("found").tabs[i].menu_wait) {
self.show_page_menu(w, i, *menu);
}
}
// Blocked counts for the toolbar.
let counts: Vec<(ViewId, u32)> = self.hub.blocked.borrow().iter().map(|(k, v)| (*k, *v)).collect();
for (id, n) in counts {
@ -1455,6 +1487,24 @@ impl App {
/// A key press anywhere in the window, before the focused widget sees it. True: it was a browser shortcut.
fn window_key(&mut self, window: WindowId, key: gdk::Key, state: gdk::ModifierType) -> bool {
// The page's right-click menu answers arrows, Enter and Escape wherever the keyboard is: the page keeps it
// (WebKit takes it back after the right click), so they go to the menu before the page sees them (S061).
if let Some(win) = self.windows.get_mut(&window)
&& win.tab().is_some_and(|t| matches!(t.dialog, Some(crate::tabs::Dialog::ContextMenu(_))))
&& let Some(k) = match key {
gdk::Key::Escape => Some(egui::Key::Escape),
gdk::Key::Up | gdk::Key::KP_Up => Some(egui::Key::ArrowUp),
gdk::Key::Down | gdk::Key::KP_Down => Some(egui::Key::ArrowDown),
gdk::Key::Return | gdk::Key::KP_Enter => Some(egui::Key::Enter),
_ => None,
}
{
for pressed in [true, false] {
win.area.push(egui::Event::Key { key: k, physical_key: Some(k), pressed, repeat: false, modifiers: egui::Modifiers::NONE });
}
win.redraw();
return true;
}
let Some(shortcut) = crate::keys::Shortcut::from_gdk(key, state) else { return false };
let Some(action) = self.shared.keymap.borrow().action_for(&shortcut) else { return false };
let Some(win) = self.windows.get_mut(&window) else { return false };

View file

@ -78,6 +78,8 @@ fn webext_dir() -> Option<std::path::PathBuf> {
/// A navigation found to be the tab's own, for the browser to decide.
struct Navigation {
web: webkit::WebView,
/// See `NavigationRequest::maybe_frame`.
maybe_frame: bool,
hub: Rc<Hub>,
filters: Rc<RefCell<Vec<webkit::UserContentFilter>>>,
images: Rc<RefCell<Option<webkit::UserContentFilter>>>,
@ -92,7 +94,7 @@ impl Navigation {
fn decide(self) {
// The filter is set for the page's site before it loads (paused sites go without).
attach_filters(&self.web, &self.hub, &self.filters, &self.images, self.url.host_str().unwrap_or(""));
self.hub.push(Event::Navigation(self.id, NavigationRequest::new(self.url, self.redirect, self.reloadable, self.decision)));
self.hub.push(Event::Navigation(self.id, NavigationRequest::new(self.url, self.redirect, self.reloadable, self.maybe_frame, self.decision)));
}
}
@ -428,6 +430,11 @@ impl Engine {
/// A user agent for one view only (`None`: back to the shared settings). Google's sign-in refuses browsers it
/// doesn't know, so its pages get Firefox's (`HubConfig::wants_ua_quirk`). Whether the view's agent changed: a
/// navigation already on its way still carries the old one.
/// The view has a user agent of its own (a site quirk), not the shared one.
pub fn own_user_agent(&self, view: &View) -> bool {
webkit::prelude::WebViewExt::settings(&view.web).as_ref() != Some(&self.settings)
}
pub fn set_view_user_agent(&self, view: &View, ua: Option<&str>) -> bool {
let current = webkit::prelude::WebViewExt::settings(&view.web);
let own = current.as_ref() != Some(&self.settings);
@ -737,7 +744,8 @@ impl Engine {
let get = request.http_method().is_none_or(|m| m.eq_ignore_ascii_case("GET"));
let reloadable = get && action.navigation_type() != webkit::NavigationType::BackForward;
let redirect = action.is_redirect();
let tab = Navigation { web: web.clone(), hub: hub.clone(), filters: filters.clone(), images: images.clone(), id, url, redirect, reloadable, decision: decision.clone() };
let scripted = !matches!(action.navigation_type(), webkit::NavigationType::LinkClicked | webkit::NavigationType::FormSubmitted | webkit::NavigationType::FormResubmitted | webkit::NavigationType::BackForward | webkit::NavigationType::Reload);
let mut tab = Navigation { web: web.clone(), hub: hub.clone(), filters: filters.clone(), images: images.clone(), id, url, redirect, reloadable, maybe_frame: false, decision: decision.clone() };
// WebKit's GTK API doesn't say which frame a navigation is for, and the browser's decisions (HTTPS-only,
// the strip, the user agent reload) load the new URL in the tab: only the tab's own loads go to it.
// The browser's own loads come without headers; a redirect is the tab's while its load is provisional
@ -757,6 +765,7 @@ impl Engine {
tab.decide();
} else {
let script = format!("(() => {{ const u = {}; const has = d => [...d.querySelectorAll('iframe, frame')].some(f => {{ if (f.src === u) return true; try {{ return !!f.contentDocument && has(f.contentDocument); }} catch (e) {{ return false; }} }}); return has(document); }})()", serde_json::to_string(uri.as_str()).unwrap_or_default());
tab.maybe_frame = scripted;
View::new(id, web.clone()).evaluate_javascript(script, move |frame| match frame {
Ok(serde_json::Value::Bool(true)) => tab.decision.use_(),
_ => tab.decide(),
@ -792,9 +801,10 @@ impl Engine {
web.connect_create(move |w, action| {
let engine = engine.upgrade()?;
let url = action.request().and_then(|r| r.uri()).and_then(|u| Url::parse(&u).ok());
let gesture = action.is_user_gesture();
let popup = engine.create_view(ViewId(crate::app::next_id()), Some(&View::new(id, w.clone())));
let widget = popup.widget();
hub.push(Event::CreateNew(id, popup, url));
hub.push(Event::CreateNew(id, popup, url, gesture));
Some(widget)
});
let hub = self.hub.clone();

View file

@ -79,7 +79,8 @@ pub enum Event {
LoadFailed(ViewId, String, String),
/// A pop-up (`window.open`, target=_blank): its view, already made as a related view of the opener, and the
/// address it will load (none for `about:blank`-style opens).
CreateNew(ViewId, View, Option<Url>),
/// A page opened a window: opener, the new view, its address, and whether a click or key press opened it.
CreateNew(ViewId, View, Option<Url>, bool),
/// A link clicked with the middle button or Ctrl: open it in a new tab (true: in front).
OpenLink(ViewId, Url, bool),
Permission(ViewId, crate::store::permissions::Kind, PermissionAsk),
@ -180,12 +181,15 @@ pub struct NavigationRequest {
pub redirect: bool,
/// A plain GET that isn't a back/forward step: denying it and loading the URL again gives the same page.
pub reloadable: bool,
/// Started by a script and not found as a frame of the page: it may still be a frame's (one inside a
/// cross-site frame, an ad's), so Nacre doesn't load another URL in the tab for it (S061).
pub maybe_frame: bool,
decision: webkit::PolicyDecision,
}
impl NavigationRequest {
pub(crate) fn new(url: Url, redirect: bool, reloadable: bool, decision: webkit::PolicyDecision) -> Self {
NavigationRequest { url, redirect, reloadable, decision }
pub(crate) fn new(url: Url, redirect: bool, reloadable: bool, maybe_frame: bool, decision: webkit::PolicyDecision) -> Self {
NavigationRequest { url, redirect, reloadable, maybe_frame, decision }
}
pub fn allow(self) {
self.decision.use_();

View file

@ -140,6 +140,9 @@ const BRIDGE_JS: &str = r#"if (window.__nacre) return;
__send('context', { selection: sel.slice(0, 2000), word, editable: !!field,
media: media ? { src: media.currentSrc || media.src || '', kind: media.tagName.toLowerCase() } : null,
x: e.clientX, y: e.clientY });
// Sent before the page's own listeners run; once they have, whether the page cancelled the event (it shows its
// own menu): WebKit asks for the browser's menu even then, once it has shown one on the page (S061).
setTimeout(() => __send('context_end', { prevented: e.defaultPrevented }), 0);
}, true);
addEventListener('DOMContentLoaded', () => __send('ready', { title: document.title }), { once: true });
"#;
@ -544,6 +547,7 @@ const COSMETIC_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.cosm
document.documentElement.append(ov);
el.style.setProperty('transition', 'opacity .22s ease .12s', 'important');
el.style.setProperty('opacity', '0', 'important'); // the ad fades out under the overlay
el.style.setProperty('pointer-events', 'none', 'important'); // and catches no click meanwhile (S061)
live++;
setTimeout(() => { ov.remove(); live--; collapse(el); }, o.ms); };
const handle = el => {

View file

@ -46,6 +46,8 @@
//! `{enter}` / `{escape}` in the text press Enter / Escape
//! pointer <x> <y> | off move the interface's pointer to x,y in the page area (new tab backgrounds follow it)
//! key <name> press and release a key in the interface: enter, escape, tab, space or a letter
//! realkey <key>… real key presses through the compositor (wtype names: Down, Return, Escape), wherever
//! the window's keyboard is; hidden runs only
//! tap <x> <y> click the interface (not the web page) at x,y in the window (logical px, as in a
//! 1:1 screenshot): press, then release a frame later; for the chrome and Nacre's pages
//! press <x> <y> hold the interface's button down at x,y (as `tap`), for a drag
@ -651,6 +653,15 @@ impl App {
None => self.selftest_log("pagetype: the page doesn't have keyboard focus"),
}
},
"realkey" => {
// Real compositor key presses (wtype key names, e.g. Down Return Escape), wherever the keyboard is.
if WL_INPUT.is_some() {
let args: Vec<String> = rest.split_whitespace().flat_map(|k| ["-k".to_owned(), k.to_owned()]).collect();
self.selftest_spawn("wtype", &args);
} else {
self.selftest_log("realkey: needs real input (a hidden run)");
}
},
"type" => {
// Type into the address bar as if the user did: focus, text, suggestions.
if let Some(win) = self.windows.get_mut(&window) {

View file

@ -119,6 +119,17 @@ pub enum Prompt {
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),
@ -188,6 +199,9 @@ pub struct Tab {
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.
@ -201,6 +215,8 @@ pub struct Tab {
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.
@ -246,6 +262,7 @@ impl Tab {
closing: None,
crashed: None,
upgraded_from: None,
redo: None,
cert_error: None,
theme_color: None,
favicon_colour: None,
@ -254,6 +271,7 @@ impl Tab {
manifest: String::new(),
arrived_ms: crate::util::now_ms(),
context: None,
menu_wait: MenuWait::None,
draft: None,
opener: None,
fullscreen: false,

View file

@ -368,19 +368,45 @@ pub fn page_menu(ctx: &egui::Context, f: &mut Frame, tab_id: u64, menu: &PageMen
Vec::new()
};
let misspelled = menu.editable && !menu.word.is_empty() && f.shared.speller.borrow().as_ref().is_some_and(|s| !s.check(&menu.word));
// Keyboard choice: arrows move over the rows that can be chosen, Enter picks, Escape closes.
let id = Id::new(("page-menu", tab_id));
// Per menu: a new right click starts with no row chosen.
let key_id = id.with(("key", menu.position.x as i32, menu.position.y as i32));
let spell_rows = if misspelled { speller_suggestions.len() + 1 } else { 0 };
let rows = spell_rows + menu.items.iter().filter(|(label, _, enabled)| !label.is_empty() && *enabled).count();
let (down, up, enter) = ctx.input(|i| (i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::Enter)));
let mut key_row: Option<usize> = ctx.data(|d| d.get_temp(key_id));
if rows > 0 && (down || up) {
let r = match key_row {
None if down => 0,
None => rows - 1,
Some(r) if down => (r + 1) % rows,
Some(r) => (r + rows - 1) % rows,
};
key_row = Some(r);
ctx.data_mut(|d| d.insert_temp(key_id, r));
}
let mut row = 0;
let mut next = || {
let on = key_row == Some(row);
row += 1;
(on, on && enter)
};
let mut chosen = None;
let Some(area) = floating(ctx, Id::new(("page-menu", tab_id)), pos, Align2::LEFT_TOP, true, |ui| {
let Some(area) = floating(ctx, id, pos, Align2::LEFT_TOP, true, |ui| {
ui.set_width(260.0);
if misspelled {
for s in &speller_suggestions {
if menu_item(ui, Some(icons::CHECK), s, "", false).clicked() {
let (on, picked) = next();
if menu_item(ui, Some(icons::CHECK), s, "", on).clicked() || picked {
chosen = Some(MenuAction::SpellReplace(menu.word.clone(), s.clone()));
}
}
if speller_suggestions.is_empty() {
empty(ui, "No spelling suggestions");
}
if menu_item(ui, Some(icons::ADD), &format!("Add “{}” to the dictionary", menu.word), "", false).clicked() {
let (on, picked) = next();
if menu_item(ui, Some(icons::ADD), &format!("Add “{}” to the dictionary", menu.word), "", on).clicked() || picked {
chosen = Some(MenuAction::SpellAdd(menu.word.clone()));
}
divider(ui);
@ -395,7 +421,8 @@ pub fn page_menu(ctx: &egui::Context, f: &mut Frame, tab_id: u64, menu: &PageMen
continue;
}
last_sep = false;
if ui.add_enabled_ui(*enabled, |ui| menu_item(ui, Some(page_menu_icon(action)), label, "", false)).inner.clicked() {
let (on, picked) = if *enabled { next() } else { (false, false) };
if ui.add_enabled_ui(*enabled, |ui| menu_item(ui, Some(page_menu_icon(action)), label, "", on)).inner.clicked() || picked {
chosen = Some(action.clone());
}
}
@ -404,6 +431,9 @@ pub fn page_menu(ctx: &egui::Context, f: &mut Frame, tab_id: u64, menu: &PageMen
};
let clicked_outside = ctx.input(|i| i.pointer.any_pressed()) && !ctx.input(|i| i.pointer.interact_pos().is_some_and(|p| area.response.rect.contains(p)));
let escape = ctx.input(|i| i.key_pressed(egui::Key::Escape));
if chosen.is_some() || clicked_outside || escape {
ctx.data_mut(|d| d.remove::<usize>(key_id));
}
if let Some(action) = chosen {
f.send(Command::Menu { tab: tab_id, action });
} else if clicked_outside || escape {

View file

@ -1,5 +1,6 @@
# Context menus (S056): a site that handles `contextmenu` shows only its own menu; elsewhere Nacre's menu. Hidden only
# (rclick needs real input). Offline. Run with tools/smoke.sh.
# Context menus (S056, S061): a site that cancels `contextmenu` shows only its own menu, on every right click;
# elsewhere Nacre's menu, which takes the keyboard (arrows, Enter, Escape) and gives it back to the page. Hidden only
# (rclick and realkey need real input). Offline. Run with tools/smoke.sh.
wait 3
open @PAGES@/ctxmenu.html
waitload
@ -15,5 +16,74 @@ rclick 200 300
wait 1.5
shot ctx-plain
expect /active/dialog true
key escape
wait 0.5
# S061: pages/site-menu.html, each area right-clicked three times (in a new tab: no Back in its menu).
do new_tab
wait 1
open @PAGES@/site-menu.html
waitload
# Like YouTube's player: its menu, then the browser's (a right click while its menu is open), then its menu again.
rclick 200 100
wait 1
expect /active/dialog false
assert window.toggleOwn === 1
rclick 220 110
wait 1
shot toggle-native
expect /active/dialog true
assert window.toggleNative === 1
realkey Escape
wait 1
expect /active/dialog false
expect /page_focused true
rclick 200 100
wait 1
expect /active/dialog false
assert window.toggleOwn === 2
click 600 600
wait 0.5
# Like Discord: its own menu every time, never Nacre's.
rclick 200 260
wait 1
expect /active/dialog false
rclick 210 270
wait 1
expect /active/dialog false
rclick 220 280
wait 1
shot always
expect /active/dialog false
assert window.alwaysOwn === 3
click 600 600
wait 0.5
# No menu of its own: Nacre's every time; Escape closes it, the page has the keyboard again.
rclick 200 440
wait 1
expect /active/dialog true
realkey Escape
wait 1
expect /active/dialog false
expect /page_focused true
rclick 210 450
wait 1
shot plain-menu
expect /active/dialog true
realkey Escape
wait 1
expect /active/dialog false
# Keys: Down picks the first row that can be chosen (Reload: no Back or Forward in this tab), Enter runs it.
assert sessionStorage.loads === "1"
rclick 220 460
wait 1
expect /active/dialog true
realkey Down
wait 0.5
shot plain-key
realkey Return
wait 2
waitload
expect /active/dialog false
assert sessionStorage.loads === "2"
status done
quit

View file

@ -12,6 +12,8 @@ certificate for *.nacre.test. Port 8767 speaks plain HTTP only (an HTTPS upgrade
/ads.html page with a listed script and image and elements the cosmetic rules hide
/ads/* the "ads" (count as hits when they get through)
/list.txt filter list for the ad blocker (a custom list URL)
/popup-list.txt pop-up and click catcher rules for /pages/player-ad.html (S061; that page, clip.webm,
frame-hijack.html and frame-ad.html come from tests/smoke/pages)
/big.bin 4 MiB sent slowly (about 7 s), with Range support for pause/resume
/file.zip small file (a download by its URL)
/attachment small file with Content-Disposition: attachment (a download by its headers); /report the same
@ -108,6 +110,15 @@ nacre.test,127.0.0.1##.nacre-ad
###nacre-generic-ad
"""
# Video site ad tricks (S061): pop-under windows and the click catcher over the player of /pages/player-ad.html.
POPUP_LIST = b"""! Title: Nacre pop-up smoke test list (S061)
/ads/popunder
/ads/overlay
127.0.0.1##.nacre-click-ad
"""
PAGES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "pages")
TP_PAGE = """<!doctype html><meta charset=utf-8><title>TP TAG</title>
<p>Third-party test TAG
<iframe id=frame src="https://cdn.other.test:8766/setcookie?name=tpTAG&tag=TAG"></iframe>
@ -202,6 +213,13 @@ class Handler(BaseHTTPRequestHandler):
return self.reply(GIF, "image/gif")
if path == "/list.txt":
return self.reply(FILTER_LIST, "text/plain")
if path == "/popup-list.txt":
return self.reply(POPUP_LIST, "text/plain")
if path.startswith("/ads/"):
return self.reply(b"<!doctype html><title>Ad</title>an ad", "text/html")
if path in ("/pages/player-ad.html", "/pages/clip.webm", "/pages/frame-hijack.html", "/pages/frame-ad.html"):
with open(os.path.join(PAGES, path[len("/pages/"):]), "rb") as f:
return self.reply(f.read(), "text/html" if path.endswith(".html") else "video/webm")
if path == "/file.zip":
return self.reply(b"PK\x05\x06" + b"\x00" * 18, "application/zip")
if path in ("/attachment", "/report"):

View file

@ -0,0 +1,6 @@
<!doctype html><meta charset="utf-8"><title>Frame ad</title>
<!-- S061: the cross-site ad frame of frame-hijack.html: a nested frame, then a script load with a tracking parameter. -->
<body style="margin:0;background:#fd5">
<iframe id="inner" style="width:300px;height:100px"></iframe>
<script>setTimeout(() => { document.getElementById('inner').contentWindow.location.href = '/echo?creative=1&utm_source=ad'; }, 300);</script>
</body>

View file

@ -0,0 +1,8 @@
<!doctype html><meta charset="utf-8"><title>Frame hijack</title>
<!-- S061: an ad frame on another site (port 8767) whose script loads a nested frame at an address with a tracking
parameter. The page can't see into the cross-site frame, so Nacre must not take the address for the tab's own
load and strip-and-load it in the tab. Served by tests/smoke/net/server.py as /pages/frame-hijack.html. -->
<body style="font:16px sans-serif">
<p>The page stays here.</p>
<iframe id="ad" src="http://127.0.0.1:8767/pages/frame-ad.html" style="width:320px;height:120px"></iframe>
</body>

View file

@ -0,0 +1,18 @@
<!doctype html><meta charset="utf-8"><title>Player ad</title>
<!-- S061: a video site's ad tricks. Served by tests/smoke/net/server.py as /pages/player-ad.html (its /popup-list.txt
names the ads). A transparent full-size click catcher over the player (an ad element the list hides), a pop-under
script that opens an ad window on the first click anywhere, and one that opens a window without any click.
The player is at x 20..660, y 20..380 (CSS px). -->
<body style="margin:0;font:16px sans-serif">
<video id="v" src="/pages/clip.webm" loop muted playsinline style="position:absolute;left:20px;top:20px;width:640px;height:360px;background:#000"></video>
<a class="nacre-click-ad" href="/ads/overlay" target="_blank" style="position:absolute;left:20px;top:20px;width:640px;height:360px;z-index:5;background:rgba(0,0,0,.01)"></a>
<script>
const v = document.getElementById('v');
window.played = 0;
v.addEventListener('click', () => { window.played++; v.play(); });
// Pop-under: the first click anywhere opens an ad window, then lets the click go on.
document.addEventListener('click', () => { if (!window.popped) { window.popped = true; window.open('/ads/popunder?click', '_blank'); } }, true);
// No click at all.
setTimeout(() => window.open('/echo?auto', '_blank'), 300);
</script>
</body>

View file

@ -0,0 +1,27 @@
<!doctype html><meta charset="utf-8"><title>Site menus</title>
<!-- S061: sites with their own context menu. #toggle works like YouTube's player (its menu on the first right click,
the browser's on a right click while its menu is open); #always like Discord (its own menu every time); #plain has
no menu of its own. Layout (CSS px): #toggle y 20..170, #always y 200..350, #plain y 380..530, x 20..420. -->
<body style="font:18px sans-serif;margin:0">
<div id="toggle" style="position:absolute;left:20px;top:20px;width:400px;height:150px;background:#1a5fb4;color:#fff">Player: own menu, then the browser's</div>
<div id="always" style="position:absolute;left:20px;top:200px;width:400px;height:150px;background:#5865f2;color:#fff">Chat: always its own menu</div>
<div id="plain" style="position:absolute;left:20px;top:380px;width:400px;height:150px;background:#e5e5e5">Plain text: the browser's menu</div>
<div id="menu" style="display:none;position:fixed;pointer-events:none;background:#222;color:#fff;padding:8px 16px">Site menu</div>
<script>
sessionStorage.loads = String(Number(sessionStorage.loads || 0) + 1);
window.toggleOwn = 0; window.toggleNative = 0; window.alwaysOwn = 0;
const menu = document.getElementById('menu');
const show = e => { menu.style.left = (e.clientX + 460) + 'px'; menu.style.top = e.clientY + 'px'; menu.style.display = 'block'; };
const hide = () => menu.style.display = 'none';
document.getElementById('toggle').addEventListener('contextmenu', e => {
if (menu.style.display === 'block') { hide(); window.toggleNative++; return; }
e.preventDefault(); window.toggleOwn++; show(e);
});
// Bubble phase on the document, as many apps do.
document.addEventListener('contextmenu', e => {
if (!e.target.closest('#always')) return;
e.preventDefault(); window.alwaysOwn++; show(e);
});
document.addEventListener('mousedown', e => { if (e.button === 0) hide(); });
</script>
</body>

37
tests/smoke/player-ad.txt Normal file
View file

@ -0,0 +1,37 @@
# Video site ad tricks (S061): pages/player-ad.html has a transparent click catcher over the player (an ad the list
# hides), a pop-under that opens a listed ad window on the first click, and a window opened without any click. The
# content filter stops the listed one, Nacre the one without a click (a 'pop-up blocked' bar), and the click reaches
# the player. An ad frame's load never takes the tab over (frame-hijack.html). Hidden only
# (real clicks). Offline. Start the server first:
# python3 tests/smoke/net/server.py & then tools/smoke.sh tests/smoke/player-ad.txt
wait 3
set /adblock/update_days 0
set /adblock/lists []
set /adblock/custom ["http://127.0.0.1:8766/popup-list.txt"]
wait 5
expect /adblock/rules 3
waitstatus 60 /adblock/filters_ready true
open http://127.0.0.1:8766/pages/player-ad.html
waitload
wait 3
shot before
expect /tab_count 1
expect /active/prompts 1
assert getComputedStyle(document.querySelector(".nacre-click-ad")).display === "none" || getComputedStyle(document.querySelector(".nacre-click-ad")).pointerEvents === "none"
click 300 200
wait 2
shot after
status after
expect /tab_count 1
assert window.popped === true && window.played === 1 && document.getElementById("v").paused === false
expect /active/prompts 1
# An ad frame inside a cross-site frame loads an address with a tracking parameter: the tab stays on its page (before
# S061 Nacre stripped it and loaded it in the tab).
open http://127.0.0.1:8766/pages/frame-hijack.html
waitload
wait 3
status frame
expect /active/url "http://127.0.0.1:8766/pages/frame-hijack.html"
expect /tab_count 1
status done
quit