S048: WebKit UI callbacks: pop-ups, dialogs, context menu, permissions, full screen, Web Inspector, PiP
- Pop-ups as related-view tabs; a blocked one's URL opens on "Allow" - Closing a tab runs beforeunload (try_close, 3 s fallback); HTTP sign-in checked - egui takes the pointer over the page while a dialog or menu is open; colour picker closes on Escape/outside - Permission reasons recomputed for WebKit; media stream/WebRTC on; saved notification answers given to WebKit - Notifications no longer dropped after a non-remembered allow - F12 opens Web Inspector; nacre://devtools lists tabs and remote inspection (D-046); console/network page removed - PiP moves the tab's own view into the PiP window and back (no reload) - Smokes: dialogs, basics extended; pip.txt, auth.txt (server /auth), visible-ui.txt Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
e2f1fa4fdf
commit
72709e07b9
28 changed files with 435 additions and 296 deletions
|
|
@ -79,6 +79,7 @@ Never modify: `~/Documents/Apps/Nacre` (the original Python Nacre, reference onl
|
|||
| `tools/smoke.sh tests/smoke/privacy-mode.txt` (+ `SMOKE_ARGS=--incognito … privacy-incognito.txt`) | privacy mode: `pages/fingerprint.html` read off/on, `fp-off.json`/`fp-on.json` + shots (offline); `privacy-net.txt` (needs `tests/smoke/net/server.py`) frame cookies, per-site pause, Accept-Language; `SMOKE_TIMEOUT=700 … coveryourtracks.txt` EFF's test off/on (internet, direct). Selftest `save <name> <js>` writes a JS string result to `<name>.json`; `SMOKE_ARGS` passes browser arguments | now (S024) |
|
||||
| `python tools/icons.py` | rebuilds the icon font subset and `src/ui/icons.rs` from `tools/icons.txt` (needs fontTools and Arch's ttf-material-symbols-variable) | now (S015) |
|
||||
| `tools/engine-test/run.sh servo\|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 |
|
||||
| `tools/smoke.sh tests/smoke/pip.txt`, `python3 tests/smoke/net/server.py &` + `NACRE_NO_BRIDGE=1 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) |
|
||||
| `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" |
|
||||
|
||||
|
|
|
|||
|
|
@ -14,16 +14,16 @@ full screen, Web Inspector (replaces the Servo devtools pages), PiP by moving th
|
|||
- `spikes/webkit-egui/src/main.rs` (`connect_create`, `connect_context_menu`), `src/app.rs` `on_create_new`/`on_permission`/`on_control`, `src/ui/menus.rs` `PageMenu`, `src/ui/dialogs.rs` header.
|
||||
|
||||
## Steps
|
||||
- [ ] `create` → `actions::on_navigation` pop-up rules → related view as tab or pop-up window; `close` signal.
|
||||
- [ ] `run-dialog` (alert/confirm/prompt/before-unload) and `authenticate` → `tabs::Dialog` egui dialogs, answered asynchronously.
|
||||
- [ ] `run-file-chooser` (rfd/portal as today), `run-color-chooser`, `show-option-menu` → existing egui pickers positioned at the element rect.
|
||||
- [ ] `context-menu` → `PageMenu` (link/image/selection/editable from `HitTestResult`), actions via `execute_editing_command` + Nacre actions; WebKit's own menu suppressed.
|
||||
- [ ] `permission-request` (geolocation, notifications, user media, device info, pointer lock, clipboard, media key system → "later" for Widevine) → `store::permissions`; recompute `unavailable()` reasons for WebKit (remove the Servo 0.7 texts).
|
||||
- [ ] `show-notification` → system notification; `enter/leave-fullscreen` → window full screen and chrome hidden.
|
||||
- [ ] Web Inspector (`enable-developer-extras`, inspector window attached/detached); `nacre://devtools` console/network either fed from WebKit or replaced by an "Open Web Inspector" page — pick the smaller, record in PROGRESS.
|
||||
- [ ] PiP: move the playing view into the PiP window and back (no reload); check page state stays.
|
||||
- [ ] Smoke: `dialogs.txt`, `basics.txt` (pop-ups, full screen), PiP steps green hidden; shots of each dialog Read.
|
||||
- [ ] PROGRESS entry, INDEX line, tracker, commit `S048: …`, push.
|
||||
- [x] `create` → `actions::on_navigation` pop-up rules → related view as tab or pop-up window; `close` signal.
|
||||
- [x] `run-dialog` (alert/confirm/prompt/before-unload) and `authenticate` → `tabs::Dialog` egui dialogs, answered asynchronously.
|
||||
- [x] `run-file-chooser` (rfd/portal as today), `run-color-chooser`, `show-option-menu` → existing egui pickers positioned at the element rect.
|
||||
- [x] `context-menu` → `PageMenu` (link/image/selection/editable from `HitTestResult`), actions via `execute_editing_command` + Nacre actions; WebKit's own menu suppressed.
|
||||
- [x] `permission-request` (geolocation, notifications, user media, device info, pointer lock, clipboard, media key system → "later" for Widevine) → `store::permissions`; recompute `unavailable()` reasons for WebKit (remove the Servo 0.7 texts).
|
||||
- [x] `show-notification` → system notification; `enter/leave-fullscreen` → window full screen and chrome hidden.
|
||||
- [x] Web Inspector (`enable-developer-extras`, inspector window attached/detached); `nacre://devtools` console/network either fed from WebKit or replaced by an "Open Web Inspector" page — pick the smaller, record in PROGRESS.
|
||||
- [x] PiP: move the playing view into the PiP window and back (no reload); check page state stays.
|
||||
- [x] Smoke: `dialogs.txt`, `basics.txt` (pop-ups, full screen), PiP steps green hidden; shots of each dialog Read.
|
||||
- [x] PROGRESS entry, INDEX line, tracker, commit `S048: …`, push.
|
||||
|
||||
## End criteria
|
||||
- `cargo test` green; `dialogs.txt` and `basics.txt` exit 0 hidden; a shot of the egui context menu over a page and of a file chooser request Read.
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ Engine switch to WebKit (D-032): new category `08 WebKit engine` comes first; Se
|
|||
- [x] [S045 — GTK 4 host with the egui overlay; WebKitGTK views; Servo out of the build](08%20WebKit%20engine/S045-gtk-host.md) · Opus high
|
||||
- [x] [S046 — Smoke harness and selftest on the GTK host (hidden nested niri)](08%20WebKit%20engine/S046-smoke-harness.md) · Opus medium
|
||||
- [x] [S047 — Page scripts, page messages, find and JS on WebKit](08%20WebKit%20engine/S047-page-channel.md) · Opus medium
|
||||
- [ ] [S048 — WebKit UI callbacks: pop-ups, dialogs, menus, permissions, full screen, inspector, PiP](08%20WebKit%20engine/S048-ui-callbacks.md) · Opus high
|
||||
- [x] [S048 — WebKit UI callbacks: pop-ups, dialogs, menus, permissions, full screen, inspector, PiP](08%20WebKit%20engine/S048-ui-callbacks.md) · Opus high
|
||||
- [ ] [S049 — Ad blocker on WebKit: content filters + web process extension](08%20WebKit%20engine/S049-adblock-webext.md) · Opus high
|
||||
- [ ] [S050 — Network bridge, HTTPS-only, certificates, error pages, privacy switches, downloads](08%20WebKit%20engine/S050-net-privacy-downloads.md) · Opus medium
|
||||
- [ ] [S051 — Profile folder, sealed cookies, site data, incognito, media source](08%20WebKit%20engine/S051-profile-cookies-media.md) · Opus medium
|
||||
|
|
|
|||
|
|
@ -49,3 +49,4 @@
|
|||
- D-043 — 2026-11-13 — Local media and WebKit's sandbox: the web process sandbox (bwrap) has no /home, so GStreamer can't read file:// media. Nacre adds the XDG user folders that exist (Downloads, Videos, Music, Pictures, Desktop, Documents; never the home folder itself) read-only with `WebContext::add_path_to_sandbox` before the first web process, plus `tests/smoke/pages` read-only only when `NACRE_SCRIPT` is set (`engine::host::media_dirs`). file:// media elsewhere doesn't play. — Chromium plays local files; all of $HOME would let a web process read ~/.ssh — orchestrator (option A), 2026-11-13 — S050/S051 media and downloads, any sandbox change
|
||||
- D-044 — 2026-11-13 — Supersedes D-034 while the user allows it: visible test runs on the user's niri session (DP-1) are allowed ("you can run real tests on my niri session"), for what hidden runs can't prove (GPU/dmabuf path, 60 fps, video playback); everything else stays hidden. A visible run never switches the user's workspace, maximizes or steals focus; if the window can't open that way it stays hidden. `tools/smoke.sh` no longer focuses a monitor and starts `SMOKE_VISIBLE=1` only when the user's niri config has the window rule `match app-id="^dev\.nacre\.Nacre$"; open-on-output "DP-1"; open-focused false` (added by the user, not by a session). — user via orchestrator, 2026-11-13 — every plan with visible checks
|
||||
- D-045 — 2026-11-13 — Visible test runs on DP-1 may take focus or switch the workspace; amends D-044 (no focus rule needed). Use them where they prove more than hidden runs (real GPU, video, real input); hidden stays fine for quick checks. — user, 2026-11-13 ("just run it, I never cared about running it with focus") — every plan with GUI tests
|
||||
- D-046 — 2026-11-13 — Developer tools are WebKit's Web Inspector: F12 opens it attached for the active web tab, `nacre://devtools` only lists tabs to inspect and switches remote inspection (127.0.0.1:6080); Nacre has no console or network page of its own. Pop-ups open as tabs next to their opener (related views). — S048 (plan let the session pick the smaller option) — later devtools, net-log and pop-up work
|
||||
|
|
|
|||
|
|
@ -381,6 +381,15 @@ Later: S010 list: user checks the Discord icon with their own client (the Discor
|
|||
- Smoke changes: basics SVG check reads the computed colour (WebKit paints currentColor itself); `waitload` after duplicate_tab (1 s was too short under load); `pages/probe-file.user.css`. Note: `*/` in a style's header pattern ends the CSS comment.
|
||||
- Not done: visible run; D-045 (visible runs allowed with focus change) not written — the auto-mode classifier blocked the DECISIONS edit relayed from the orchestrator; the user should confirm/add it.
|
||||
|
||||
## S048 — WebKit UI callbacks: pop-ups, dialogs, menus, permissions, full screen, inspector, PiP (2026-11-13)
|
||||
- Wired and smoke-checked: pop-ups as tabs (related view, `window.opener` kept; blocked → bar, "Allow" opens the blocked URL), alert/confirm/prompt answers, beforeunload (closing a tab now runs WebKit `try_close`; 3 s fallback; browser navigation asks too), HTTP sign-in (saved login filled, signs in), select/colour at the element rect, portal file chooser (visible run), Nacre's context menu with link items from the hit test, notifications/location prompts, system notifications, page full screen hides the chrome, PiP moves the live view (no reload, video keeps playing).
|
||||
- Devtools: the smaller option: F12 opens WebKit's Web Inspector (attached); `nacre://devtools` lists the window's tabs to inspect plus remote inspection (`WEBKIT_INSPECTOR_HTTP_SERVER` 127.0.0.1:6080, restart). Console/network/elements tabs, `DevToolsEval`, `ConsoleLine` removed.
|
||||
- Permissions: media stream + WebRTC on (each use asks); saved notification answers given to WebKit at start; unavailable with WebKit: storage persist, per-site JavaScript (not wired yet), MIDI, Bluetooth, wake lock, background sync, game controllers (no request reaches the browser). Pointer lock allowed, EME/XR denied (Widevine later).
|
||||
- Fixes: colour picker closes on Escape/outside; egui takes the pointer over the page while a dialog/menu is open (page clicks never reached egui); prompt names "This page" for file://; `on_notification` dropped every prompt-granted (not remembered) notification.
|
||||
- Verified: build, `cargo test` 75; hidden smokes exit 0: dialogs, basics, pip (new), auth (new, server.py + NACRE_NO_BRIDGE=1), launch, keys, input; visible run (`tests/smoke/visible-ui.txt`, by hand, user's bus): portal file chooser, full screen, inspector shots read.
|
||||
- Not done: notification popup not seen on screen (user switched workspace; `/notifications` count checked hidden); inspector detach, camera/mic with a real device, HTTP auth for a proxy, settings page rows not re-shot.
|
||||
- Later: egui colour picker shows broken glyph chips (missing emoji in Nacre's fonts); user-visible Servo texts in settings.rs/misc.rs (About, freeze tabs, Widevine, clear data, task manager); closing a window/quit doesn't run beforeunload; smoke.sh still refuses visible runs without the niri rule (D-045 says it's not needed) and keeps a private bus (no portal); pop-ups never open as separate windows (WebKit window properties unused).
|
||||
|
||||
## Later
|
||||
- file:// media outside the XDG user folders doesn't play (WebKit sandbox, D-043).
|
||||
- Visible runs need the user to add the niri window rule for `dev.nacre.Nacre` (tools/smoke.sh header, D-044).
|
||||
|
|
|
|||
135
src/actions.rs
135
src/actions.rs
|
|
@ -9,7 +9,7 @@ use std::time::Duration;
|
|||
use gtk::prelude::*;
|
||||
use url::Url;
|
||||
|
||||
use crate::engine::{ConsoleLevel, PageAction, ViewId};
|
||||
use crate::engine::{PageAction, ViewId};
|
||||
|
||||
use crate::app::{App, Launch, WindowRequest};
|
||||
use crate::inject::{self, PageMessage};
|
||||
|
|
@ -158,7 +158,8 @@ pub enum Command {
|
|||
SavePage,
|
||||
PrintPage,
|
||||
ViewSource,
|
||||
DevToolsEval(String),
|
||||
/// Open WebKit's Web Inspector for this tab.
|
||||
Inspect(u64),
|
||||
SpellReplace { word: String, by: String },
|
||||
Suggest(String),
|
||||
Weather,
|
||||
|
|
@ -226,7 +227,22 @@ impl App {
|
|||
Command::Open { url, how, from } => self.open(window, url, how, from),
|
||||
Command::ShowPage(page) => self.show_page(window, page),
|
||||
Command::NewTab => self.new_tab(window, None, true),
|
||||
Command::CloseTab(id) => self.close_tab(window, id, true),
|
||||
Command::CloseTab(id) => {
|
||||
// A web page may ask first ("Leave this page?"): WebKit runs its beforeunload and then closes it
|
||||
// (`Event::Closed`), or the tick closes it if the page hangs.
|
||||
if let Some((w, i)) = self.find_tab(id)
|
||||
&& let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i]
|
||||
&& tab.closing.is_none()
|
||||
&& tab.crashed.is_none()
|
||||
&& tab.page.is_none()
|
||||
&& let Some(view) = tab.web.as_ref().map(|web| web.webview.clone())
|
||||
{
|
||||
tab.closing = Some(std::time::Instant::now());
|
||||
view.close();
|
||||
return;
|
||||
}
|
||||
self.close_tab(window, id, true)
|
||||
},
|
||||
Command::CloseOtherTabs(id) => {
|
||||
let ids: Vec<u64> = self.windows.get(&window).map(|w| w.tabs.iter().filter(|t| t.id != id && !t.pinned).map(|t| t.id).collect()).unwrap_or_default();
|
||||
for other in ids {
|
||||
|
|
@ -748,29 +764,11 @@ impl App {
|
|||
self.open(window, Page::Source(url).url(), Disposition::NewForegroundTab, None);
|
||||
}
|
||||
},
|
||||
Command::DevToolsEval(script) => {
|
||||
// Developer tools run against the last web tab that was active in this window.
|
||||
let target = self.windows.get(&window).and_then(|w| w.ui.devtools_target);
|
||||
if let Some(tab) = target
|
||||
&& let Some((w, i)) = self.find_tab(tab)
|
||||
Command::Inspect(tab) => {
|
||||
if let Some((w, i)) = self.find_tab(tab)
|
||||
&& let Some(web) = &self.windows[&w].tabs[i].web
|
||||
{
|
||||
let webview = web.webview.clone();
|
||||
let jobs = self.jobs_tx.clone();
|
||||
self.windows.get_mut(&w).expect("found").tabs[i].push_console(ConsoleLevel::Log, format!("> {script}"));
|
||||
webview.evaluate_javascript(script, move |result| {
|
||||
let (level, text) = match result {
|
||||
Ok(value) => (ConsoleLevel::Info, value.to_string()),
|
||||
Err(error) => (ConsoleLevel::Error, format!("Error: {error}")),
|
||||
};
|
||||
let _ = jobs.send(Box::new(move |app: &mut App| {
|
||||
if let Some((w, i)) = app.find_tab(tab) {
|
||||
app.windows.get_mut(&w).expect("found").tabs[i].push_console(level, text);
|
||||
app.redraw(w);
|
||||
}
|
||||
}));
|
||||
crate::app::Waker.wake();
|
||||
});
|
||||
web.webview.show_inspector();
|
||||
}
|
||||
},
|
||||
Command::SpellReplace { word, by } => {
|
||||
|
|
@ -969,11 +967,10 @@ impl App {
|
|||
self.redraw(window);
|
||||
return;
|
||||
},
|
||||
Action::DevTools => {
|
||||
if let Some(win) = self.windows.get_mut(&window) {
|
||||
win.ui.devtools_target = win.tab().filter(|t| t.web.is_some()).map(|t| t.id).or(win.ui.devtools_target);
|
||||
}
|
||||
Command::ShowPage(Page::DevTools)
|
||||
// On a web page the inspector opens at once; elsewhere the page lists the tabs to inspect.
|
||||
Action::DevTools => match self.windows.get(&window).and_then(|w| w.tab()).filter(|t| t.page.is_none() && t.web.is_some()) {
|
||||
Some(tab) => Command::Inspect(tab.id),
|
||||
None => Command::ShowPage(Page::DevTools),
|
||||
},
|
||||
Action::ViewSource => Command::ViewSource,
|
||||
Action::SavePage => Command::SavePage,
|
||||
|
|
@ -1052,9 +1049,6 @@ impl App {
|
|||
win.ui.omnibox_edit = win.tabs[index].draft.clone();
|
||||
win.ui.close_popups();
|
||||
win.tabs[index].last_shown = std::time::Instant::now();
|
||||
if win.tabs[index].page.is_none() {
|
||||
win.ui.devtools_target = Some(win.tabs[index].id);
|
||||
}
|
||||
}
|
||||
self.ensure_loaded(window);
|
||||
// A web page tab takes the keyboard back (the address field doesn't keep another tab's focus).
|
||||
|
|
@ -1405,12 +1399,18 @@ impl App {
|
|||
_ => {},
|
||||
}
|
||||
},
|
||||
Prompt::PopupBlocked { .. } | Prompt::Info { .. } => {
|
||||
Prompt::PopupBlocked { url } => {
|
||||
if let PromptAnswer::Allow { .. } = answer {
|
||||
let host = self.windows[&w].tabs[i].host();
|
||||
self.shared.permissions.borrow_mut().set(&host, Perm::Popups, Some(Decision::Allow));
|
||||
// The blocked one opens now (without its opener, which WebKit already let go).
|
||||
if !url.is_empty() {
|
||||
let from = Some(self.windows[&w].tabs[i].id);
|
||||
self.open(w, url, Disposition::NewForegroundTab, from);
|
||||
}
|
||||
}
|
||||
},
|
||||
Prompt::Info { .. } => {},
|
||||
}
|
||||
self.redraw(w);
|
||||
}
|
||||
|
|
@ -1454,7 +1454,13 @@ impl App {
|
|||
},
|
||||
Dialog::ContextMenu(menu) => drop(menu),
|
||||
Dialog::LeavePage(request) => {
|
||||
if matches!(result, DialogResult::Leave(true)) { request.allow() } else { request.deny() }
|
||||
if matches!(result, DialogResult::Leave(true)) {
|
||||
request.allow();
|
||||
} else {
|
||||
// Stay: a close waiting for this answer is off.
|
||||
self.windows.get_mut(&w).expect("found").tabs[i].closing = None;
|
||||
request.deny();
|
||||
}
|
||||
},
|
||||
Dialog::Logins { .. } | Dialog::Forms { .. } => {},
|
||||
}
|
||||
|
|
@ -2231,33 +2237,64 @@ impl App {
|
|||
|
||||
// ── picture in picture ────────────────────────────────────────────
|
||||
|
||||
/// Picture in picture is not ported to WebKit yet (S047): say so instead of doing nothing.
|
||||
fn enter_pip(&mut self, _window: WindowId) {
|
||||
self.shared.toast("Picture in picture isn't available yet in this version");
|
||||
/// Picture in picture: the tab's own view moves into a small window of its own and shows only its video; the
|
||||
/// page keeps playing as it was (no reload).
|
||||
fn enter_pip(&mut self, window: WindowId) {
|
||||
let Some(tab_id) = self.active_tab_id(window) else { return };
|
||||
let Some((w, i)) = self.find_tab(tab_id) else { return };
|
||||
let tab = &self.windows[&w].tabs[i];
|
||||
if tab.pip_size.is_some() || tab.page.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(view) = tab.web.as_ref().map(|web| web.webview.clone()) else { return };
|
||||
let jobs = self.jobs_tx.clone();
|
||||
view.evaluate_javascript(inject::call("pip.enter", &[]), move |result| {
|
||||
let video = result.ok().and_then(|v| Some((v.get("w")?.as_f64()?, v.get("h")?.as_f64()?)));
|
||||
let _ = jobs.send(Box::new(move |app: &mut App| {
|
||||
let Some((vw, vh)) = video else {
|
||||
app.shared.toast("There's no video on this page to show in picture in picture");
|
||||
return;
|
||||
};
|
||||
let Some((w, i)) = app.find_tab(tab_id) else { return };
|
||||
let Some(view) = app.windows[&w].tabs[i].web.as_ref().map(|web| web.webview.clone()) else { return };
|
||||
let width = 480u32;
|
||||
let height = ((width as f64) * vh.max(9.0) / vw.max(16.0)).round().clamp(120.0, 900.0) as u32;
|
||||
let win = app.windows.get_mut(&w).expect("found");
|
||||
win.tabs[i].pip_size = Some([width, height]);
|
||||
win.detach(&view);
|
||||
win.sync_webviews();
|
||||
if let Some(pip) = app.open_window(Kind::Pip { window: w, tab: tab_id }, Vec::new(), 0, Some((width, height)))
|
||||
&& let Some(win) = app.windows.get_mut(&pip)
|
||||
{
|
||||
win.pip_view = Some(view);
|
||||
win.sync_webviews();
|
||||
}
|
||||
app.redraw(w);
|
||||
}));
|
||||
crate::app::schedule_pump();
|
||||
});
|
||||
}
|
||||
|
||||
/// Back from picture in picture.
|
||||
/// Back from picture in picture: the view goes back into its tab, the page as it was before.
|
||||
pub fn exit_pip(&mut self, source: WindowId, tab_id: u64) {
|
||||
let pip = self.windows.iter_mut().find(|(_, w)| matches!(w.kind, Kind::Pip { tab, .. } if tab == tab_id)).and_then(|(_, w)| w.pip_view.take().map(|v| (v, w)));
|
||||
if let Some((view, pip)) = pip {
|
||||
pip.detach(&view);
|
||||
view.evaluate_javascript(inject::call("pip.leave", &[]), |_| {});
|
||||
}
|
||||
let Some(win) = self.windows.get_mut(&source) else { return };
|
||||
let Some(i) = win.tab_index(tab_id) else { return };
|
||||
let tab = &mut win.tabs[i];
|
||||
tab.pip_size = None;
|
||||
tab.pip_start = None;
|
||||
if let Some(pip) = tab.pip.take()
|
||||
&& let Some(engine) = &self.engine
|
||||
{
|
||||
engine.forget(pip.webview.id());
|
||||
}
|
||||
win.tabs[i].pip_size = None;
|
||||
win.sync_webviews();
|
||||
self.redraw(source);
|
||||
}
|
||||
|
||||
/// Run a script in a tab's picture-in-picture web view.
|
||||
/// Run a script in the page of a tab shown in picture in picture.
|
||||
fn eval_pip(&self, tab_id: u64, script: String) {
|
||||
if let Some((w, i)) = self.find_tab(tab_id)
|
||||
&& let Some(pip) = &self.windows[&w].tabs[i].pip
|
||||
&& let Some(web) = &self.windows[&w].tabs[i].web
|
||||
{
|
||||
pip.webview.evaluate_javascript(script, |_| {});
|
||||
web.webview.evaluate_javascript(script, |_| {});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
65
src/app.rs
65
src/app.rs
|
|
@ -214,6 +214,8 @@ pub struct App {
|
|||
pub pending_launches: Vec<Launch>,
|
||||
pub pending_files: HashMap<u64, crate::engine::FilePicker>,
|
||||
pub next_pending: u64,
|
||||
/// Page notifications shown this run (self-test status).
|
||||
pub notifications_shown: u32,
|
||||
pub download_controls: HashMap<u64, Arc<AtomicU8>>,
|
||||
pub presence: Option<Presence>,
|
||||
pub presence_started: Option<(u64, String, i64)>,
|
||||
|
|
@ -336,6 +338,7 @@ impl App {
|
|||
pending_launches: Vec::new(),
|
||||
pending_files: HashMap::new(),
|
||||
next_pending: 1,
|
||||
notifications_shown: 0,
|
||||
download_controls: HashMap::new(),
|
||||
presence: None,
|
||||
presence_started: None,
|
||||
|
|
@ -389,10 +392,17 @@ impl App {
|
|||
user_agent: settings.web.user_agent.clone(),
|
||||
dark_background: dark,
|
||||
developer_extras: true,
|
||||
remote_inspector: settings.web.remote_debugging.then(|| "127.0.0.1:6080".to_owned()),
|
||||
};
|
||||
// Cookies stay in WebKit's memory for the run until S051 seals them (D-037); never plain on disk.
|
||||
crate::store::cookies::start(&self.shared.paths.data, &self.shared.paths.engine(), self.shared.incognito);
|
||||
let engine = Engine::new(self.hub.clone(), &setup);
|
||||
{
|
||||
use crate::store::permissions::{Decision, Kind};
|
||||
let saved: Vec<(String, Decision)> = self.shared.permissions.borrow().all().into_iter().filter(|(_, k, _)| *k == Kind::Notifications).map(|(h, _, d)| (h, d)).collect();
|
||||
let hosts = |want: Decision| saved.iter().filter(|(_, d)| *d == want).map(|(h, _)| h.clone()).collect();
|
||||
engine.set_notification_answers(hosts(Decision::Allow), hosts(Decision::Block));
|
||||
}
|
||||
let ua = engine.user_agent();
|
||||
*self.shared.user_agent.borrow_mut() = ua.clone();
|
||||
crate::net::fetch::set_user_agent(&ua);
|
||||
|
|
@ -660,8 +670,10 @@ impl App {
|
|||
},
|
||||
Event::Closed(id) => {
|
||||
if let Some((w, i)) = self.find_webview(id) {
|
||||
let tab_id = self.windows[&w].tabs[i].id;
|
||||
self.close_tab(w, tab_id, false);
|
||||
let tab = &self.windows[&w].tabs[i];
|
||||
// Closed by the user (after beforeunload): kept in recently closed; by `window.close()`: not.
|
||||
let (tab_id, remember) = (tab.id, tab.closing.is_some());
|
||||
self.close_tab(w, tab_id, remember);
|
||||
}
|
||||
},
|
||||
Event::Crashed(id, reason) => {
|
||||
|
|
@ -707,7 +719,7 @@ impl App {
|
|||
}
|
||||
self.redraw(w);
|
||||
},
|
||||
Event::CreateNew(parent, view) => self.on_create_new(parent, view),
|
||||
Event::CreateNew(parent, view, url) => self.on_create_new(parent, view, url),
|
||||
Event::Permission(id, kind, request) => self.on_permission(id, kind, request),
|
||||
Event::Auth(id, request) => {
|
||||
let origin = request.origin();
|
||||
|
|
@ -830,21 +842,26 @@ impl App {
|
|||
}
|
||||
|
||||
/// A pop-up opened as a tab next to its opener (WebKit already made its view, related to the opener's).
|
||||
fn on_create_new(&mut self, parent: ViewId, view: View) {
|
||||
let Some((w, i)) = self.find_webview(parent) else {
|
||||
view.close();
|
||||
return;
|
||||
};
|
||||
let host = self.windows[&w].tabs[i].host();
|
||||
let answer = self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, crate::store::permissions::Kind::Popups);
|
||||
if answer == crate::store::permissions::Answer::Block {
|
||||
/// Pop-ups open as tabs next to their opener (as with Servo; a related view keeps `window.opener`).
|
||||
fn on_create_new(&mut self, parent: ViewId, view: View, url: Option<Url>) {
|
||||
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
|
||||
});
|
||||
let Some((w, i)) = found.filter(|_| !blocked) else {
|
||||
// WebKit already holds the view: the page sees its window close at once.
|
||||
if let Some(engine) = &self.engine {
|
||||
engine.forget(view.id());
|
||||
}
|
||||
self.windows.get_mut(&w).expect("found").tabs[i].prompts.push_back(crate::tabs::Prompt::PopupBlocked { url: String::new() });
|
||||
self.redraw(w);
|
||||
view.close();
|
||||
if let Some((w, i)) = found {
|
||||
let url = url.map(|u| u.to_string()).unwrap_or_default();
|
||||
self.windows.get_mut(&w).expect("found").tabs[i].prompts.push_back(crate::tabs::Prompt::PopupBlocked { url });
|
||||
self.redraw(w);
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
let opener = self.windows[&w].tabs[i].id;
|
||||
let mut tab = Tab::new(view.id().0);
|
||||
tab.page = None;
|
||||
|
|
@ -935,10 +952,12 @@ impl App {
|
|||
|
||||
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();
|
||||
let allowed = self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, crate::store::permissions::Kind::Notifications) == crate::store::permissions::Answer::Allow;
|
||||
if !allowed {
|
||||
// WebKit shows only what the page was granted (a prompt answer, or the saved ones); a site blocked since stays quiet.
|
||||
let blocked = self.shared.permissions.borrow().answer(&self.shared.settings.borrow(), &host, crate::store::permissions::Kind::Notifications) == crate::store::permissions::Answer::Block;
|
||||
if blocked {
|
||||
return;
|
||||
}
|
||||
self.notifications_shown += 1;
|
||||
let title = if notification.title.is_empty() { host.clone() } else { notification.title.clone() };
|
||||
let shown = cfg!(unix) && util::which("notify-send").is_some() && std::process::Command::new("notify-send").args(["-a", "Nacre", &title, ¬ification.body]).spawn().is_ok();
|
||||
if !shown {
|
||||
|
|
@ -976,6 +995,11 @@ 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();
|
||||
for (w, tab) in hung {
|
||||
self.close_tab(w, tab, true);
|
||||
}
|
||||
// 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 {
|
||||
|
|
@ -1566,8 +1590,8 @@ impl App {
|
|||
let shared = self.shared.clone();
|
||||
let hub = self.hub.clone();
|
||||
{
|
||||
let BrowserWindow { tabs, active, ui, page_rect, kind, fullscreen, pip_frame, pip_size, .. } = win;
|
||||
let mut frame = crate::ui::Frame { shared: &shared, hub: &hub, tabs, active, ui, page_rect, kind, fullscreen: *fullscreen, pip_frame: pip_frame.as_ref(), pip_size: *pip_size, commands: &mut commands, window_id: window };
|
||||
let BrowserWindow { tabs, active, ui, page_rect, kind, fullscreen, .. } = win;
|
||||
let mut frame = crate::ui::Frame { shared: &shared, hub: &hub, tabs, active, ui, page_rect, kind, fullscreen: *fullscreen, commands: &mut commands, window_id: window };
|
||||
crate::ui::draw(root, &mut frame);
|
||||
}
|
||||
if win.frame_times.len() >= 120 {
|
||||
|
|
@ -1580,6 +1604,11 @@ impl App {
|
|||
schedule_pump();
|
||||
}
|
||||
self.ui_commands.extend(commands.into_iter().map(|c| (window, c)));
|
||||
// While the tab shows a dialog or a page menu, egui takes the pointer over the page too, so a click beside a
|
||||
// menu closes it (and the page under a dialog gets no clicks).
|
||||
if win.tab().is_some_and(|t| t.dialog.is_some()) {
|
||||
return None;
|
||||
}
|
||||
page
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ pub struct Setup {
|
|||
pub user_agent: String,
|
||||
pub dark_background: bool,
|
||||
pub developer_extras: bool,
|
||||
/// Serve the Web Inspector to other browsers on this address (`127.0.0.1:6080`).
|
||||
pub remote_inspector: Option<String>,
|
||||
}
|
||||
|
||||
pub struct Engine {
|
||||
|
|
@ -36,6 +38,9 @@ pub struct Engine {
|
|||
styles: RefCell<Vec<UserStyle>>,
|
||||
views: RefCell<HashMap<ViewId, 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).
|
||||
notifications: Rc<RefCell<(Vec<String>, Vec<String>)>>,
|
||||
}
|
||||
|
||||
fn env(name: &str) -> Option<String> {
|
||||
|
|
@ -44,6 +49,10 @@ fn env(name: &str) -> Option<String> {
|
|||
|
||||
impl Engine {
|
||||
pub fn new(hub: Rc<Hub>, setup: &Setup) -> Rc<Engine> {
|
||||
if let Some(address) = &setup.remote_inspector {
|
||||
// Read once when the first web context starts; nothing else in Nacre reads or writes it.
|
||||
unsafe { std::env::set_var("WEBKIT_INSPECTOR_HTTP_SERVER", address) };
|
||||
}
|
||||
// D-040 tuning defaults, env overrides for tests.
|
||||
let mem_limit: u32 = env("NACRE_WK_MEM_LIMIT").and_then(|v| v.parse().ok()).unwrap_or(500);
|
||||
let mut pressure = None;
|
||||
|
|
@ -86,6 +95,9 @@ impl Engine {
|
|||
settings.set_enable_page_cache(env("NACRE_WK_PAGE_CACHE").as_deref() == Some("1"));
|
||||
settings.set_javascript_can_open_windows_automatically(true);
|
||||
settings.set_enable_back_forward_navigation_gestures(true);
|
||||
// Camera and microphone (getUserMedia) and calls; each use still asks (`permission-request`).
|
||||
settings.set_enable_media_stream(true);
|
||||
settings.set_enable_webrtc(true);
|
||||
match env("NACRE_WK_HW").as_deref() {
|
||||
Some("never") => settings.set_hardware_acceleration_policy(webkit::HardwareAccelerationPolicy::Never),
|
||||
Some("always") => settings.set_hardware_acceleration_policy(webkit::HardwareAccelerationPolicy::Always),
|
||||
|
|
@ -95,6 +107,13 @@ impl Engine {
|
|||
settings.set_user_agent(Some(setup.user_agent.trim()));
|
||||
}
|
||||
let shade = if setup.dark_background { 0.1 } else { 1.0 };
|
||||
let notifications: Rc<RefCell<(Vec<String>, Vec<String>)>> = Rc::default();
|
||||
let answers = notifications.clone();
|
||||
context.connect_initialize_notification_permissions(move |context| {
|
||||
let origins = |hosts: &[String]| -> Vec<webkit::SecurityOrigin> { hosts.iter().flat_map(|h| ["https", "http"].map(|s| webkit::SecurityOrigin::new(s, h, 0))).collect() };
|
||||
let (allowed, blocked) = { let a = answers.borrow(); (origins(&a.0), origins(&a.1)) };
|
||||
context.initialize_notification_permissions(&allowed.iter().collect::<Vec<_>>(), &blocked.iter().collect::<Vec<_>>());
|
||||
});
|
||||
Rc::new(Engine {
|
||||
hub,
|
||||
session,
|
||||
|
|
@ -104,9 +123,15 @@ impl Engine {
|
|||
styles: RefCell::new(Vec::new()),
|
||||
views: RefCell::new(HashMap::new()),
|
||||
background: RefCell::new(gtk::gdk::RGBA::new(shade, shade, shade, 1.0)),
|
||||
notifications,
|
||||
})
|
||||
}
|
||||
|
||||
/// The saved notification answers (hosts allowed, hosts blocked); read when WebKit starts a web process.
|
||||
pub fn set_notification_answers(&self, allowed: Vec<String>, blocked: Vec<String>) {
|
||||
*self.notifications.borrow_mut() = (allowed, blocked);
|
||||
}
|
||||
|
||||
/// The user agent pages see.
|
||||
pub fn user_agent(&self) -> String {
|
||||
self.settings.user_agent().map(|u| u.to_string()).unwrap_or_default()
|
||||
|
|
@ -316,11 +341,12 @@ impl Engine {
|
|||
});
|
||||
let engine = Rc::downgrade(self);
|
||||
let hub = self.hub.clone();
|
||||
web.connect_create(move |w, _action| {
|
||||
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 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));
|
||||
hub.push(Event::CreateNew(id, popup, url));
|
||||
Some(widget)
|
||||
});
|
||||
let hub = self.hub.clone();
|
||||
|
|
|
|||
|
|
@ -48,16 +48,6 @@ pub enum LoadState {
|
|||
Complete,
|
||||
}
|
||||
|
||||
/// Console line level for the developer tools page.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ConsoleLevel {
|
||||
Log,
|
||||
Info,
|
||||
Warn,
|
||||
Error,
|
||||
Debug,
|
||||
}
|
||||
|
||||
pub enum Event {
|
||||
UrlChanged(ViewId, Url),
|
||||
TitleChanged(ViewId, Option<String>),
|
||||
|
|
@ -80,8 +70,9 @@ pub enum Event {
|
|||
Download(ViewId, Url),
|
||||
/// A load failed (not a cancel): url, error text.
|
||||
LoadFailed(ViewId, String, String),
|
||||
/// A pop-up (`window.open`, target=_blank): its view, already made as a related view of the opener.
|
||||
CreateNew(ViewId, View),
|
||||
/// 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>),
|
||||
Permission(ViewId, crate::store::permissions::Kind, PermissionAsk),
|
||||
Auth(ViewId, AuthRequest),
|
||||
Control(ViewId, Control),
|
||||
|
|
|
|||
|
|
@ -234,8 +234,8 @@ const MEDIA_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.media)
|
|||
} };
|
||||
})();"#;
|
||||
|
||||
/// Picture-in-picture. The tab's own page hands over its video (`take`, later `resume`); a second web view
|
||||
/// with its own painter loads the same page and shows only that video (`start`, D-008).
|
||||
/// Picture-in-picture. The tab's own view moves into the PiP window (no reload, page state kept); `enter` makes its
|
||||
/// biggest (playing) video fill the viewport, `leave` puts the page back as it was.
|
||||
const PIP_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.pip) return;
|
||||
const pick = () => {
|
||||
const vs = [...document.querySelectorAll('video')].filter(v => v.readyState > 0);
|
||||
|
|
@ -243,15 +243,6 @@ const PIP_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.pip) retu
|
|||
return vs.filter(v => !v.paused).sort((a, b) => area(b) - area(a))[0] || vs.sort((a, b) => area(b) - area(a))[0] || null;
|
||||
};
|
||||
window.__nacre.pip = {
|
||||
take() { const v = pick(); if (!v) return null; window.__nacrePipV = v;
|
||||
const r = { w: v.videoWidth || 16, h: v.videoHeight || 9, t: v.currentTime, paused: v.paused }; v.pause(); return r; },
|
||||
resume(t, play) { const v = window.__nacrePipV; window.__nacrePipV = null; if (!v || !v.isConnected) return;
|
||||
try { v.currentTime = t; } catch (e) {} if (play) v.play().catch(() => {}); },
|
||||
// The page may build its video late (players): keep looking for up to 30 s.
|
||||
start(t, play, tries) { const pip = window.__nacre.pip;
|
||||
if (!pip.enter()) { if ((tries || 0) < 150) setTimeout(() => pip.start(t, play, (tries || 0) + 1), 200); return; }
|
||||
const v = window.__nacrePipV; try { v.currentTime = t; } catch (e) {}
|
||||
if (play) v.play().catch(() => {}); else v.pause(); },
|
||||
enter() {
|
||||
const v = pick();
|
||||
if (!v) return null;
|
||||
|
|
@ -266,6 +257,9 @@ const PIP_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.pip) retu
|
|||
document.documentElement.classList.add('__nacre_pip');
|
||||
return { w: v.videoWidth || 16, h: v.videoHeight || 9, paused: v.paused };
|
||||
},
|
||||
leave() { const v = window.__nacrePipV; window.__nacrePipV = null;
|
||||
if (v) v.removeAttribute('data-nacre-pip');
|
||||
document.documentElement.classList.remove('__nacre_pip'); },
|
||||
state() { const v = window.__nacrePipV; if (!v || !v.isConnected) return null;
|
||||
return { t: v.currentTime, d: isFinite(v.duration) ? v.duration : 0, paused: v.paused, muted: v.muted, vol: v.volume, w: v.videoWidth, h: v.videoHeight }; },
|
||||
act(what, arg) { const v = window.__nacrePipV; if (!v) return;
|
||||
|
|
|
|||
|
|
@ -807,7 +807,7 @@ impl App {
|
|||
"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})),
|
||||
"theme_color": t.theme_color.map(crate::theme::to_hex), "console_lines": t.console.len(), "pip": t.pip_size.is_some(),
|
||||
"theme_color": t.theme_color.map(crate::theme::to_hex), "pip": t.pip_size.is_some(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
|
|
@ -827,6 +827,7 @@ impl App {
|
|||
};
|
||||
serde_json::json!({
|
||||
"windows": self.windows.len(),
|
||||
"notifications": self.notifications_shown,
|
||||
"tab_count": tabs.len(),
|
||||
"cookies": crate::store::cookies::keeping().map(|k| format!("{k:?}")),
|
||||
"active_index": self.windows.get(&window).map(|w| w.active),
|
||||
|
|
|
|||
|
|
@ -120,14 +120,17 @@ impl Kind {
|
|||
}
|
||||
}
|
||||
|
||||
/// Why Nacre can't enforce this one: Servo 0.7 has no per-site switch for it. Those rows show as unavailable.
|
||||
/// Why Nacre can't enforce this one with WebKit (no request reaches the browser, or no per-site switch). Those
|
||||
/// rows show as unavailable.
|
||||
pub fn engine_limit(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Kind::Location => Some("Servo 0.7 never asks for the location: navigator.geolocation does nothing"),
|
||||
Kind::Camera | Kind::Microphone | Kind::DeviceInfo => Some("Servo 0.7 has no navigator.mediaDevices, so no page can ask"),
|
||||
Kind::Storage => Some("Servo 0.7 has no navigator.storage.persist(), so no page can ask"),
|
||||
Kind::Javascript => Some("Servo 0.7 can't turn JavaScript off for one site"),
|
||||
Kind::Clipboard => Some("Servo 0.7 doesn't ask before a page reads the clipboard"),
|
||||
Kind::Storage => Some("WebKit answers navigator.storage.persist() itself and doesn't ask the browser"),
|
||||
Kind::Javascript => Some("Nacre can't turn JavaScript off for one site yet"),
|
||||
Kind::Midi => Some("WebKit has no Web MIDI, so no page can ask"),
|
||||
Kind::Bluetooth => Some("WebKit has no Web Bluetooth, so no page can ask"),
|
||||
Kind::WakeLock => Some("WebKit doesn't ask the browser before a page keeps the screen on"),
|
||||
Kind::BackgroundSync => Some("WebKit has no background sync, so no page can ask"),
|
||||
Kind::Gamepad => Some("WebKit doesn't ask the browser before a page reads game controllers"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
28
src/tabs.rs
28
src/tabs.rs
|
|
@ -6,7 +6,7 @@ use std::time::Instant;
|
|||
|
||||
use url::Url;
|
||||
|
||||
use crate::engine::{ConsoleLevel, LoadState, View, ViewId};
|
||||
use crate::engine::{LoadState, View, ViewId};
|
||||
|
||||
use crate::media::MediaState;
|
||||
|
||||
|
|
@ -144,12 +144,6 @@ pub struct FindState {
|
|||
pub searched: Option<(String, bool)>,
|
||||
}
|
||||
|
||||
pub struct ConsoleLine {
|
||||
pub level: ConsoleLevel,
|
||||
pub text: String,
|
||||
pub time_ms: u64,
|
||||
}
|
||||
|
||||
pub struct Web {
|
||||
pub webview: View,
|
||||
}
|
||||
|
|
@ -186,9 +180,10 @@ pub struct Tab {
|
|||
pub prompts: VecDeque<Prompt>,
|
||||
pub dialog: Option<Dialog>,
|
||||
pub crashed: Option<String>,
|
||||
/// The user closed the tab and its page runs `beforeunload` first (WebKit `try_close`); since when.
|
||||
pub closing: Option<std::time::Instant>,
|
||||
/// HTTPS-only upgraded this load from this URL.
|
||||
pub upgraded_from: Option<Url>,
|
||||
pub console: VecDeque<ConsoleLine>,
|
||||
/// Page details from META_JS.
|
||||
pub theme_color: Option<egui::Color32>,
|
||||
pub site_name: String,
|
||||
|
|
@ -206,12 +201,8 @@ pub struct Tab {
|
|||
pub animating: bool,
|
||||
/// Ad leftovers hidden on this page.
|
||||
pub hidden_elements: u32,
|
||||
/// Shown in a picture-in-picture window at this size (physical pixels).
|
||||
/// Its view is in a picture-in-picture window, showing a video of this size (logical pixels).
|
||||
pub pip_size: Option<[u32; 2]>,
|
||||
/// The picture-in-picture web view: the same page loaded again with its own painter (D-008).
|
||||
pub pip: Option<Web>,
|
||||
/// Video time and playing state to start the PiP video at once its page has loaded.
|
||||
pub pip_start: Option<(f64, bool)>,
|
||||
}
|
||||
|
||||
impl Tab {
|
||||
|
|
@ -242,9 +233,9 @@ impl Tab {
|
|||
find: FindState::default(),
|
||||
prompts: VecDeque::new(),
|
||||
dialog: None,
|
||||
closing: None,
|
||||
crashed: None,
|
||||
upgraded_from: None,
|
||||
console: VecDeque::new(),
|
||||
theme_color: None,
|
||||
site_name: String::new(),
|
||||
page_image: String::new(),
|
||||
|
|
@ -257,8 +248,6 @@ impl Tab {
|
|||
animating: false,
|
||||
hidden_elements: 0,
|
||||
pip_size: None,
|
||||
pip: None,
|
||||
pip_start: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -317,13 +306,6 @@ impl Tab {
|
|||
if self.url.is_empty() { "New tab".into() } else { self.url.clone() }
|
||||
}
|
||||
|
||||
pub fn push_console(&mut self, level: ConsoleLevel, text: String) {
|
||||
if self.console.len() >= 500 {
|
||||
self.console.pop_front();
|
||||
}
|
||||
self.console.push_back(ConsoleLine { level, text, time_ms: crate::util::now_ms() });
|
||||
}
|
||||
|
||||
/// What the session file keeps for this tab.
|
||||
pub fn saved(&self) -> crate::store::session::SavedTab {
|
||||
crate::store::session::SavedTab {
|
||||
|
|
|
|||
|
|
@ -1071,13 +1071,8 @@ pub fn app_bar(root: &mut Ui, f: &mut Frame) {
|
|||
|
||||
/// Picture in picture: the video frame and a few controls over it.
|
||||
pub fn pip_window(root: &mut Ui, f: &mut Frame) {
|
||||
// The tab's own view fills the window under this overlay; egui takes the pointer everywhere (no page rect).
|
||||
let rect = root.max_rect();
|
||||
root.painter().rect_filled(rect, 0.0, Color32::BLACK);
|
||||
if let Some(texture) = f.pip_frame {
|
||||
root.painter().image(texture.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
} else {
|
||||
root.put(egui::Rect::from_center_size(rect.center(), Vec2::splat(32.0)), egui::Spinner::new());
|
||||
}
|
||||
let hovered = root.ctx().input(|i| i.pointer.hover_pos().is_some());
|
||||
if !hovered {
|
||||
return;
|
||||
|
|
@ -1113,7 +1108,6 @@ pub fn pip_window(root: &mut Ui, f: &mut Frame) {
|
|||
});
|
||||
});
|
||||
});
|
||||
let _ = f.pip_size;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ pub fn prompt_bars(root: &mut Ui, f: &mut Frame) {
|
|||
let tab_id = tab.id;
|
||||
let more = tab.prompts.len() - 1;
|
||||
let text = match prompt {
|
||||
Prompt::Permission { host, kind, .. } => format!("{host} wants to {}", kind.request_text()),
|
||||
Prompt::Permission { host, kind, .. } => format!("{} wants to {}", if host.is_empty() { "This page" } else { host }, kind.request_text()),
|
||||
Prompt::SaveLogin { origin, username, update, .. } => {
|
||||
let who = if username.is_empty() { String::new() } else { format!(" for {username}") };
|
||||
if *update { format!("Update the saved password{who} on {}?", util::host_of_str(origin)) } else { format!("Save the password{who} on {}?", util::host_of_str(origin)) }
|
||||
|
|
@ -345,7 +345,7 @@ pub fn page_dialogs(ctx: &egui::Context, f: &mut Frame) {
|
|||
let rect = page_rect(ctx, f.page_rect.as_ref(), picker.rect);
|
||||
let id = Id::new(("color", tab_id));
|
||||
let mut rgb = ctx.data_mut(|d| d.get_temp::<[u8; 3]>(id)).unwrap_or(*initial);
|
||||
egui::Area::new(id).fixed_pos(rect.left_bottom()).order(egui::Order::Foreground).constrain(true).show(ctx, |ui| {
|
||||
let area = egui::Area::new(id).fixed_pos(rect.left_bottom()).order(egui::Order::Foreground).constrain(true).show(ctx, |ui| {
|
||||
surface(&palette, ctx).inner_margin(egui::Margin::same(theme::GAP_L as i8)).show(ui, |ui| {
|
||||
let mut color = egui::Color32::from_rgb(rgb[0], rgb[1], rgb[2]);
|
||||
egui::color_picker::color_picker_color32(ui, &mut color, egui::color_picker::Alpha::Opaque);
|
||||
|
|
@ -360,6 +360,10 @@ pub fn page_dialogs(ctx: &egui::Context, f: &mut Frame) {
|
|||
});
|
||||
});
|
||||
});
|
||||
let outside = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !area.response.rect.contains(p)));
|
||||
if result.is_none() && (outside || ctx.input(|i| i.key_pressed(egui::Key::Escape))) {
|
||||
result = Some(DialogResult::Color(None));
|
||||
}
|
||||
ctx.data_mut(|d| d.insert_temp(id, rgb));
|
||||
if result.is_some() {
|
||||
ctx.data_mut(|d| d.remove::<[u8; 3]>(id));
|
||||
|
|
|
|||
|
|
@ -78,8 +78,6 @@ pub struct WindowUi {
|
|||
pub flyout: Option<Flyout>,
|
||||
/// Where the last flyout button was, to place the flyout under it.
|
||||
pub flyout_anchor: Option<egui::Rect>,
|
||||
/// The web tab developer tools look at.
|
||||
pub devtools_target: Option<u64>,
|
||||
pub pages: pages::PageState,
|
||||
/// Tab being dragged in the tab strip: (tab id, grab offset x).
|
||||
pub dragging_tab: Option<(u64, f32)>,
|
||||
|
|
@ -135,8 +133,6 @@ pub struct Frame<'a> {
|
|||
pub page_rect: &'a mut Option<egui::Rect>,
|
||||
pub kind: &'a Kind,
|
||||
pub fullscreen: bool,
|
||||
pub pip_frame: Option<&'a egui::TextureHandle>,
|
||||
pub pip_size: [u32; 2],
|
||||
pub commands: &'a mut Vec<Command>,
|
||||
pub window_id: WindowId,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,152 +1,35 @@
|
|||
//! nacre://devtools — a small set of developer tools for a tab: its console (with evaluation),
|
||||
//! the requests it made (and which were blocked), and the page's current HTML. Full tools are
|
||||
//! available through Firefox's remote debugging (Settings → Privacy).
|
||||
//! nacre://devtools — opens WebKit's Web Inspector (console, network, elements, sources) for a tab of this window,
|
||||
//! and turns on remote inspection for other browsers. F12 on a web page opens the inspector directly (S048).
|
||||
|
||||
use egui::{RichText, Ui};
|
||||
|
||||
use super::super::widgets::{ButtonKind, button, choice_chips, empty_state, icon_button, text_field};
|
||||
use super::super::widgets::{ButtonKind, button, card, empty_state, list_item, page_column, page_header, section, switch_row};
|
||||
use super::super::Frame;
|
||||
use crate::actions::Command;
|
||||
use crate::theme::{self, Weight};
|
||||
use crate::ui::icons;
|
||||
use crate::util;
|
||||
|
||||
/// A recessed panel for log text: a step above the page, large corners.
|
||||
fn panel<R>(ui: &mut Ui, height: f32, contents: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
let p = theme::palette(ui.ctx());
|
||||
egui::Frame::NONE.fill(p.surface_container).corner_radius(theme::corner_radius(theme::radius(ui.ctx(), theme::L))).inner_margin(theme::GAP_M as i8).show(ui, |ui| {
|
||||
ui.set_min_height(height.max(80.0));
|
||||
ui.set_min_width(ui.available_width());
|
||||
contents(ui)
|
||||
}).inner
|
||||
}
|
||||
|
||||
pub fn draw(ui: &mut Ui, f: &mut Frame) {
|
||||
let p = f.palette();
|
||||
let target = f.ui.devtools_target.and_then(|id| f.tabs.iter().find(|t| t.id == id)).or_else(|| f.tabs.iter().find(|t| t.page.is_none()));
|
||||
let Some(target) = target else {
|
||||
empty_state(ui, icons::BUG_REPORT, "No page to inspect", "Open a web page in this window, then come back here to see its console and requests.", None);
|
||||
return;
|
||||
};
|
||||
let target_id = target.id;
|
||||
let target_title = target.display_title();
|
||||
let webview = target.view_id();
|
||||
egui::Frame::NONE.inner_margin(egui::Margin::symmetric(theme::GAP_L as i8, theme::GAP_S as i8)).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new("Developer tools").font(theme::font(theme::HEADLINE, Weight::Medium)).color(p.on_surface));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let remote = f.shared.settings.borrow().web.remote_debugging;
|
||||
let kind = if remote { ButtonKind::Tonal } else { ButtonKind::Outlined };
|
||||
if button(ui, kind, Some(icons::BUG_REPORT), if remote { "Remote debugging on" } else { "Remote debugging off" }).on_hover_text("Firefox: about:debugging, then connect to localhost:6080. Restart Nacre to apply.").clicked() {
|
||||
f.send(Command::ToggleRemoteDebugging);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = egui::vec2(theme::GAP_S, theme::GAP_S);
|
||||
ui.label(RichText::new(format!("for {}", util::ellipsize(&target_title, 60))).font(theme::font(theme::BODY, Weight::Regular)).color(p.on_surface_variant));
|
||||
let others: Vec<(u64, String)> = f.tabs.iter().filter(|t| t.page.is_none() && t.id != target_id).map(|t| (t.id, util::ellipsize(&t.display_title(), 40))).collect();
|
||||
if !others.is_empty() {
|
||||
ui.menu_button(format!("{} Other tab", icons::EXPAND_MORE), |ui| {
|
||||
for (id, title) in others {
|
||||
if ui.button(title).clicked() {
|
||||
f.ui.devtools_target = Some(id);
|
||||
ui.close();
|
||||
pub fn draw(ui: &mut egui::Ui, f: &mut Frame) {
|
||||
page_column(ui, "devtools", 860.0, |ui| {
|
||||
page_header(ui, "Developer tools", "WebKit's Web Inspector: console, network, elements, sources, storage and performance for one tab.", |_| {});
|
||||
let tabs: Vec<(u64, String)> = f.tabs.iter().filter(|t| t.page.is_none() && t.web.is_some()).map(|t| (t.id, t.display_title())).collect();
|
||||
if tabs.is_empty() {
|
||||
empty_state(ui, icons::BUG_REPORT, "No page to inspect", "Open a web page in this window, then press F12 on it.", None);
|
||||
} else {
|
||||
section(ui, "Tabs in this window");
|
||||
card(ui, |ui| {
|
||||
for (id, title) in tabs {
|
||||
list_item(ui, id, Some(icons::TAB), &title, "", |ui| {
|
||||
if button(ui, ButtonKind::Tonal, Some(icons::BUG_REPORT), "Inspect").clicked() {
|
||||
f.send(Command::Inspect(id));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.add_space(theme::GAP_S);
|
||||
f.ui.devtools_target = Some(target_id);
|
||||
let mut tab = f.ui.pages.devtools_tab;
|
||||
if choice_chips(ui, &mut tab, &[(0usize, "Console"), (1, "Network"), (2, "Elements")]) {
|
||||
f.ui.pages.devtools_tab = tab;
|
||||
}
|
||||
ui.add_space(theme::GAP_M);
|
||||
match f.ui.pages.devtools_tab {
|
||||
0 => console(ui, f, target_id),
|
||||
1 => network(ui, f, webview),
|
||||
_ => elements(ui, f, target_id),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn console(ui: &mut Ui, f: &mut Frame, target_id: u64) {
|
||||
let palette = f.palette();
|
||||
let lines: Vec<(crate::engine::ConsoleLevel, String, u64)> = f.tabs.iter().find(|t| t.id == target_id).map(|t| t.console.iter().map(|l| (l.level.clone(), l.text.clone(), l.time_ms)).collect()).unwrap_or_default();
|
||||
let height = ui.available_height() - theme::CONTROL - 3.0 * theme::GAP_L;
|
||||
panel(ui, height, |ui| {
|
||||
if lines.is_empty() {
|
||||
ui.label(RichText::new("Nothing logged yet. Messages from the page and results of what you run below show here.").font(theme::font(theme::SMALL, Weight::Regular)).color(palette.on_surface_variant));
|
||||
}
|
||||
egui::ScrollArea::vertical().stick_to_bottom(true).max_height(height).auto_shrink([false, false]).show(ui, |ui| {
|
||||
for (level, text, time) in lines {
|
||||
let color = match level {
|
||||
crate::engine::ConsoleLevel::Error => palette.error,
|
||||
crate::engine::ConsoleLevel::Warn => palette.warning,
|
||||
crate::engine::ConsoleLevel::Debug => palette.on_surface_variant,
|
||||
_ => palette.on_surface,
|
||||
};
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(RichText::new(util::format_clock(time / 1000)).monospace().small().color(palette.on_surface_variant));
|
||||
ui.label(RichText::new(text).color(color).monospace());
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(theme::GAP_S);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = theme::GAP_S;
|
||||
let r = text_field(ui, &mut f.ui.pages.devtools_input, "JavaScript to run in the page", ui.available_width() - 100.0);
|
||||
let run = button(ui, ButtonKind::Filled, Some(icons::PLAY_ARROW), "Run").clicked() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)));
|
||||
if run && !f.ui.pages.devtools_input.trim().is_empty() {
|
||||
let script = std::mem::take(&mut f.ui.pages.devtools_input);
|
||||
f.send(Command::DevToolsEval(script));
|
||||
r.request_focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn network(ui: &mut Ui, f: &mut Frame, webview: Option<crate::engine::ViewId>) {
|
||||
let p = f.palette();
|
||||
let entries: Vec<crate::engine::NetEntry> = webview.and_then(|id| f.hub.net_log.borrow().get(&id).map(|log| log.iter().cloned().collect())).unwrap_or_default();
|
||||
ui.label(RichText::new(format!("{} requests, {} blocked", entries.len(), entries.iter().filter(|e| e.blocked).count())).font(theme::font(theme::SMALL, Weight::Medium)).color(p.on_surface_variant));
|
||||
ui.add_space(theme::GAP_S);
|
||||
let height = ui.available_height() - theme::GAP_L;
|
||||
panel(ui, height, |ui| {
|
||||
if entries.is_empty() {
|
||||
ui.label(RichText::new("No requests yet. Load or reload the page to see what it asks for.").font(theme::font(theme::SMALL, Weight::Regular)).color(p.on_surface_variant));
|
||||
}
|
||||
egui::ScrollArea::vertical().max_height(height).auto_shrink([false, false]).show(ui, |ui| {
|
||||
egui::Grid::new("net").num_columns(4).spacing([theme::GAP_L, theme::GAP_XS]).show(ui, |ui| {
|
||||
for e in entries.iter().rev() {
|
||||
ui.label(RichText::new(&e.method).monospace().color(p.on_surface));
|
||||
ui.label(RichText::new(&e.kind).color(p.on_surface_variant));
|
||||
ui.label(if e.blocked { RichText::new("blocked").color(p.error) } else { RichText::new("") });
|
||||
ui.label(RichText::new(util::ellipsize(&e.url, 120)).monospace().small().color(p.on_surface)).on_hover_text(&e.url);
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
section(ui, "Remote inspection");
|
||||
card(ui, |ui| {
|
||||
let mut on = f.shared.settings.borrow().web.remote_debugging;
|
||||
if switch_row(ui, "Inspect from another browser", "Open http://127.0.0.1:6080 in another browser to inspect Nacre's tabs. Applies after a restart.", &mut on) {
|
||||
f.send(Command::ToggleRemoteDebugging);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn elements(ui: &mut Ui, f: &mut Frame, target_id: u64) {
|
||||
let p = f.palette();
|
||||
ui.label(RichText::new("The page's HTML as it is now, after scripts ran, is printed in the console.").font(theme::font(theme::BODY, Weight::Regular)).color(p.on_surface_variant));
|
||||
ui.add_space(theme::GAP_M);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = theme::GAP_S;
|
||||
if button(ui, ButtonKind::Tonal, Some(icons::CODE), "Print the current HTML").clicked() {
|
||||
f.send(Command::DevToolsEval("document.documentElement.outerHTML".into()));
|
||||
f.ui.pages.devtools_tab = 0;
|
||||
}
|
||||
if button(ui, ButtonKind::Outlined, Some(icons::OPEN_IN_NEW), "View the original source").clicked()
|
||||
&& let Some(url) = f.tabs.iter().find(|t| t.id == target_id).map(|t| t.url.clone())
|
||||
{
|
||||
f.send(Command::Open { url: crate::tabs::Page::Source(url).url(), how: crate::actions::Disposition::NewForegroundTab, from: None });
|
||||
}
|
||||
});
|
||||
let _ = icon_button;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,8 +59,6 @@ pub struct PageState {
|
|||
pub clear_range: usize,
|
||||
pub clear_what: Vec<String>,
|
||||
pub welcome_step: usize,
|
||||
pub devtools_input: String,
|
||||
pub devtools_tab: usize,
|
||||
pub notes_dirty: bool,
|
||||
/// The new tab page's Customize panel is open.
|
||||
pub ntp_customize: bool,
|
||||
|
|
|
|||
|
|
@ -785,7 +785,7 @@ fn privacy(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
|
|||
});
|
||||
section(ui, "Developers");
|
||||
card(ui, |ui| {
|
||||
row(ui, "Remote debugging", "Lets Firefox's developer tools connect to Nacre on localhost:6080 (restart to apply)", |ui| switch(ui, &mut s.web.remote_debugging));
|
||||
row(ui, "Remote debugging", "Lets another browser open the Web Inspector at http://127.0.0.1:6080 (restart to apply)", |ui| switch(ui, &mut s.web.remote_debugging));
|
||||
row(ui, "User agent", "Empty uses the engine's default", |ui| text_field(ui, &mut s.web.user_agent, "Default", 260.0));
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,9 +45,8 @@ pub struct BrowserWindow {
|
|||
pub page_focused: bool,
|
||||
pub fullscreen: bool,
|
||||
pub last_input: Instant,
|
||||
/// Picture-in-picture: the latest frame of the tab being shown.
|
||||
pub pip_frame: Option<egui::TextureHandle>,
|
||||
pub pip_size: [u32; 2],
|
||||
/// Picture-in-picture windows: the tab's own view, moved here while it plays (filling the window).
|
||||
pub pip_view: Option<View>,
|
||||
pub focused: bool,
|
||||
/// Save the window to this file after the next frame (self-test screenshots).
|
||||
pub shot_request: Option<std::path::PathBuf>,
|
||||
|
|
@ -90,8 +89,7 @@ impl BrowserWindow {
|
|||
page_focused: false,
|
||||
fullscreen: false,
|
||||
last_input: Instant::now(),
|
||||
pip_frame: None,
|
||||
pip_size: [0, 0],
|
||||
pip_view: None,
|
||||
focused: true,
|
||||
shot_request: None,
|
||||
shot_frame: None,
|
||||
|
|
@ -131,6 +129,16 @@ impl BrowserWindow {
|
|||
/// Put every tab's web view into the stack, show the active tab's at the page rect, hide the stack when the
|
||||
/// active tab shows no web page.
|
||||
pub fn sync_webviews(&mut self) {
|
||||
if let Some(view) = &self.pip_view {
|
||||
let widget = view.widget();
|
||||
if widget.parent().as_ref() != Some(self.stack.upcast_ref()) {
|
||||
widget.unparent();
|
||||
widget.set_child_visible(true);
|
||||
self.stack.add_overlay(&widget);
|
||||
}
|
||||
self.stack.set_visible(true);
|
||||
return;
|
||||
}
|
||||
for tab in &self.tabs {
|
||||
if let Some(web) = &tab.web {
|
||||
let widget = web.webview.widget();
|
||||
|
|
@ -207,6 +215,9 @@ impl BrowserWindow {
|
|||
self.detach(&web.webview);
|
||||
}
|
||||
}
|
||||
if let Some(view) = self.pip_view.take() {
|
||||
self.detach(&view);
|
||||
}
|
||||
EguiArea::forget(self.id.0);
|
||||
self.window.destroy();
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue