S047: page scripts, user style sheets, find and JS on WebKit
User styles become WebKit user style sheets (script fallback for patterns WebKit can't express), the nacre message handler is registered before the view exists, find runs on FindController, and the Servo-only shims are gone from inject.rs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
b7d1dbcc2f
commit
ffc22e911f
14 changed files with 264 additions and 186 deletions
|
|
@ -13,13 +13,13 @@ cosmetic filters, autofill, media actions; Servo-only shims in `inject.rs` dropp
|
|||
- `src/inject.rs` (whole), `src/app.rs` `install_page_scripts` / `on_page_message` / `apply_cosmetic`.
|
||||
|
||||
## Steps
|
||||
- [ ] `UserContentManager` per profile: `WebKitUserScript` (document start, all frames) for Nacre's scripts, `WebKitUserStyleSheet` for user styles; reinstall on settings change.
|
||||
- [ ] Script message handler `nacre` → `inject::PageMessage` → `Event::PageMessage`; replace the Servo transport in `inject.rs`.
|
||||
- [ ] `evaluate_javascript` wrapper returning `serde_json::Value` (JSCValue → JSON string); callers in actions/selftest.
|
||||
- [ ] Find bar on `FindController` (count, next/prev, highlight, close).
|
||||
- [ ] Drop/re-check the Servo shims listed in servo-removal §3.7 (UA cleanup, SVG colour, WebGL vendor, fonts check, compressor, caret workaround, seek-then-play, navigator fixes) — each removed or kept with a one-line reason.
|
||||
- [ ] Smoke: `basics.txt` find steps, `dialogs.txt`, `stores-*`/`integ-*` that use page scripts (autofill, scripts store) green hidden.
|
||||
- [ ] PROGRESS entry, INDEX line, tracker, commit `S047: …`, push.
|
||||
- [x] `UserContentManager` per profile: `WebKitUserScript` (document start, all frames) for Nacre's scripts, `WebKitUserStyleSheet` for user styles; reinstall on settings change.
|
||||
- [x] Script message handler `nacre` → `inject::PageMessage` → `Event::PageMessage`; replace the Servo transport in `inject.rs`.
|
||||
- [x] `evaluate_javascript` wrapper returning `serde_json::Value` (JSCValue → JSON string); callers in actions/selftest.
|
||||
- [x] Find bar on `FindController` (count, next/prev, highlight, close).
|
||||
- [x] Drop/re-check the Servo shims listed in servo-removal §3.7 (UA cleanup, SVG colour, WebGL vendor, fonts check, compressor, caret workaround, seek-then-play, navigator fixes) — each removed or kept with a one-line reason.
|
||||
- [x] Smoke: `basics.txt` find steps, `dialogs.txt`, `stores-*`/`integ-*` that use page scripts (autofill, scripts store) green hidden.
|
||||
- [x] PROGRESS entry, INDEX line, tracker, commit `S047: …`, push.
|
||||
|
||||
## End criteria
|
||||
- `cargo test` green; the listed smokes exit 0 hidden; `grep -n "Servo" src/inject.rs` returns nothing.
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ Engine switch to WebKit (D-032): new category `08 WebKit engine` comes first; Se
|
|||
- [x] [S044 — Engine seam: pure logic out of the Servo files](08%20WebKit%20engine/S044-engine-seam.md) · Opus medium
|
||||
- [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
|
||||
- [ ] [S047 — Page scripts, page messages, find and JS on WebKit](08%20WebKit%20engine/S047-page-channel.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
|
||||
- [ ] [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
|
||||
|
|
|
|||
|
|
@ -373,6 +373,14 @@ Later: S010 list: user checks the Discord icon with their own client (the Discor
|
|||
- Not done: no visible run. The user's niri config has no window rule for `dev.nacre.Nacre`, so a window would take focus; smoke.sh now refuses visible runs without the rule (D-044). Other smoke scripts not ported (each moves with its feature's plan).
|
||||
- Found: loopback http goes through the bridge and fails ("restarted too many times") → S050 box; use `NACRE_NO_BRIDGE=1` for loopback smokes until then.
|
||||
|
||||
## S047 — Page scripts, page messages, find and JS on WebKit (2026-11-13)
|
||||
- Done: user styles are WebKit user style sheets (author level, all frames) via `Engine::set_page_content`; patterns WebKit can't say (`*` inside a host, a port) keep the `<style>` script (`store::scripts::user_style`); `nacre` message handler registered before the view is built; find bar on `FindController` (`View::find`/`find_finish`, `Event::Find` count, "n of m" kept by Nacre: `step_match`, `FindState.searched`).
|
||||
- JSON result shape unchanged: `View::evaluate_javascript` gives `serde_json::Value` (undefined/null → `Null`).
|
||||
- inject.rs: dropped FIND_JS, SVG_COLOR_JS, FONTS_CHECK_JS, COMPRESSOR_JS, `mainstream_ua`, PiP pause-before-seek; caret workaround kept for text fields (comment says why); privacy mode's WebGL unmasked vendor/renderer now read as the masked ones ("WebKit", "WebKit WebGL"), no fake debug extension; FRAME_COOKIE_JS kept until WebKit's third-party cookie policy is on.
|
||||
- Verified: release build, `cargo test` 75 green; hidden smokes exit 0: basics (find [1,3]→[2,3], all matches highlighted in find.png), dialogs, stores-apps (new file:// style-sheet probe), stores-vault + check, integ-spell. `grep -n Servo src/inject.rs` empty.
|
||||
- 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.
|
||||
|
||||
## 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).
|
||||
|
|
|
|||
|
|
@ -416,29 +416,35 @@ impl App {
|
|||
self.redraw(window);
|
||||
},
|
||||
Command::Find { text, forward, case } => {
|
||||
let Some(id) = self.active_tab_id(window) else { return };
|
||||
if let Some(win) = self.windows.get_mut(&window)
|
||||
&& let Some(tab) = win.tab_mut()
|
||||
{
|
||||
tab.find.open = true;
|
||||
tab.find.text = text.clone();
|
||||
tab.find.case_sensitive = case;
|
||||
}
|
||||
if text.is_empty() {
|
||||
self.eval(id, inject::call("find.stop", &[]));
|
||||
if let Some(tab) = self.windows.get_mut(&window).and_then(|w| w.tab_mut()) {
|
||||
tab.find.count = 0;
|
||||
tab.find.index = 0;
|
||||
}
|
||||
let Some(win) = self.windows.get_mut(&window) else { return };
|
||||
let Some(tab) = win.tab_mut() else { return };
|
||||
let find = &mut tab.find;
|
||||
// The same words again step through the matches; new words (or match case) search afresh.
|
||||
let fresh = find.searched.as_ref() != Some(&(text.clone(), case)) || find.count == 0;
|
||||
find.open = true;
|
||||
find.text = text.clone();
|
||||
find.case_sensitive = case;
|
||||
find.searched = (!text.is_empty()).then(|| (text.clone(), case));
|
||||
if fresh {
|
||||
// `on_find` puts a fresh search on the first match, or the last one searching backwards.
|
||||
find.count = 0;
|
||||
find.index = if forward { 0 } else { u32::MAX };
|
||||
} else {
|
||||
self.eval(id, inject::call("find.run", &[text.into(), case.into(), (if forward { 1 } else { -1 }).into()]));
|
||||
find.index = step_match(find.index, find.count, forward);
|
||||
}
|
||||
let Some(web) = &tab.web else { return };
|
||||
if text.is_empty() {
|
||||
web.webview.find_finish();
|
||||
} else {
|
||||
web.webview.find(&text, case, forward, fresh);
|
||||
}
|
||||
self.redraw(window);
|
||||
},
|
||||
Command::FindClose => {
|
||||
if let Some(id) = self.active_tab_id(window) {
|
||||
self.eval(id, inject::call("find.stop", &[]));
|
||||
}
|
||||
if let Some(tab) = self.windows.get_mut(&window).and_then(|w| w.tab_mut()) {
|
||||
if let Some(web) = &tab.web {
|
||||
web.webview.find_finish();
|
||||
}
|
||||
tab.find = Default::default();
|
||||
}
|
||||
self.redraw(window);
|
||||
|
|
@ -1511,6 +1517,22 @@ impl App {
|
|||
self.redraw(w);
|
||||
}
|
||||
|
||||
/// WebKit counted the matches of the find bar's search (or of a step through them).
|
||||
pub fn on_find(&mut self, id: ViewId, count: u32) {
|
||||
let Some((w, i)) = self.find_webview(id) else { return };
|
||||
let find = &mut self.windows.get_mut(&w).expect("found").tabs[i].find;
|
||||
if find.text.is_empty() {
|
||||
return;
|
||||
}
|
||||
find.count = count;
|
||||
find.index = match (count, find.index) {
|
||||
(0, _) => 0,
|
||||
(_, 0) => 1,
|
||||
(n, i) => i.min(n),
|
||||
};
|
||||
self.redraw(w);
|
||||
}
|
||||
|
||||
// ── page messages ─────────────────────────────────────────────────
|
||||
|
||||
pub fn on_page_message(&mut self, id: ViewId, message: PageMessage) {
|
||||
|
|
@ -1550,12 +1572,6 @@ impl App {
|
|||
tab.media = state.map(|s| (s, util::now_ms()));
|
||||
self.redraw_all();
|
||||
},
|
||||
"find" => {
|
||||
let tab = &mut self.windows.get_mut(&w).expect("found").tabs[i];
|
||||
tab.find.count = data.get("count").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
|
||||
tab.find.index = data.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
|
||||
self.redraw(w);
|
||||
},
|
||||
"download" => {
|
||||
if let Ok(url) = Url::parse(&s(&data, "url")) {
|
||||
let name = s(&data, "name");
|
||||
|
|
@ -2381,6 +2397,17 @@ impl App {
|
|||
}
|
||||
}
|
||||
|
||||
/// The find bar's "n of m" after a step forward or back (WebKit wraps around; it doesn't say where it is).
|
||||
fn step_match(index: u32, count: u32, forward: bool) -> u32 {
|
||||
match (forward, index) {
|
||||
(_, _) if count == 0 => 0,
|
||||
(true, i) if i >= count => 1,
|
||||
(true, i) => i + 1,
|
||||
(false, i) if i <= 1 => count,
|
||||
(false, i) => i - 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt_count(n: usize) -> String {
|
||||
let s = n.to_string();
|
||||
let mut out = String::new();
|
||||
|
|
@ -2392,3 +2419,17 @@ fn fmt_count(n: usize) -> String {
|
|||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::step_match;
|
||||
|
||||
#[test]
|
||||
fn find_steps_wrap_around() {
|
||||
assert_eq!(step_match(1, 3, true), 2);
|
||||
assert_eq!(step_match(3, 3, true), 1);
|
||||
assert_eq!(step_match(1, 3, false), 3);
|
||||
assert_eq!(step_match(2, 3, false), 1);
|
||||
assert_eq!(step_match(0, 0, true), 0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -443,8 +443,9 @@ impl App {
|
|||
google_signin: s.privacy.google_signin,
|
||||
};
|
||||
let mut sources = inject::page_scripts(&options);
|
||||
sources.extend(self.shared.scripts.borrow().page_scripts());
|
||||
engine.set_scripts(sources);
|
||||
let scripts = self.shared.scripts.borrow();
|
||||
sources.extend(scripts.page_scripts());
|
||||
engine.set_page_content(sources, scripts.page_styles());
|
||||
}
|
||||
|
||||
/// A web view for a tab, loading `url`.
|
||||
|
|
@ -725,6 +726,7 @@ impl App {
|
|||
Event::Control(id, control) => self.on_control(id, control),
|
||||
Event::Notification(id, notification) => self.on_notification(id, notification),
|
||||
Event::Page(id, message) => self.on_page_message(id, message),
|
||||
Event::Find(id, count) => self.on_find(id, count),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use gtk::prelude::*;
|
|||
use url::Url;
|
||||
use webkit::prelude::*;
|
||||
|
||||
use super::{AuthRequest, ColorPicker, Control, Event, FilePicker, Hub, LoadState, NavigationRequest, Notification, PageAction, PageMenuRequest, PermissionAsk, SelectElement, SimpleDialog, View, ViewId};
|
||||
use super::{AuthRequest, ColorPicker, Control, Event, FilePicker, Hub, LoadState, NavigationRequest, Notification, PageAction, PageMenuRequest, PermissionAsk, SelectElement, SimpleDialog, UserStyle, View, ViewId};
|
||||
use crate::store::permissions::Kind as Perm;
|
||||
|
||||
/// Settings the engine starts with.
|
||||
|
|
@ -33,6 +33,7 @@ pub struct Engine {
|
|||
/// The page scripts every new document gets (each view has its own content manager so page messages know
|
||||
/// their view).
|
||||
scripts: RefCell<Vec<String>>,
|
||||
styles: RefCell<Vec<UserStyle>>,
|
||||
views: RefCell<HashMap<ViewId, glib::WeakRef<webkit::WebView>>>,
|
||||
background: RefCell<gtk::gdk::RGBA>,
|
||||
}
|
||||
|
|
@ -100,6 +101,7 @@ impl Engine {
|
|||
context,
|
||||
settings,
|
||||
scripts: RefCell::new(Vec::new()),
|
||||
styles: RefCell::new(Vec::new()),
|
||||
views: RefCell::new(HashMap::new()),
|
||||
background: RefCell::new(gtk::gdk::RGBA::new(shade, shade, shade, 1.0)),
|
||||
})
|
||||
|
|
@ -129,22 +131,30 @@ impl Engine {
|
|||
}
|
||||
}
|
||||
|
||||
/// Replace the page scripts; they apply to each page's next document.
|
||||
pub fn set_scripts(&self, sources: Vec<String>) {
|
||||
*self.scripts.borrow_mut() = sources;
|
||||
/// Replace the page scripts and user style sheets; scripts apply to each page's next document, style sheets at once.
|
||||
pub fn set_page_content(&self, scripts: Vec<String>, styles: Vec<UserStyle>) {
|
||||
*self.scripts.borrow_mut() = scripts;
|
||||
*self.styles.borrow_mut() = styles;
|
||||
for web in self.live_views() {
|
||||
if let Some(ucm) = web.user_content_manager() {
|
||||
ucm.remove_all_scripts();
|
||||
self.add_scripts(&ucm);
|
||||
ucm.remove_all_style_sheets();
|
||||
self.add_content(&ucm);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn add_scripts(&self, ucm: &webkit::UserContentManager) {
|
||||
fn add_content(&self, ucm: &webkit::UserContentManager) {
|
||||
for source in self.scripts.borrow().iter() {
|
||||
let script = webkit::UserScript::new(source, webkit::UserContentInjectedFrames::AllFrames, webkit::UserScriptInjectionTime::Start, &[], &[]);
|
||||
ucm.add_script(&script);
|
||||
}
|
||||
for style in self.styles.borrow().iter() {
|
||||
let allow: Vec<&str> = style.allow.iter().map(String::as_str).collect();
|
||||
let block: Vec<&str> = style.block.iter().map(String::as_str).collect();
|
||||
let sheet = webkit::UserStyleSheet::new(&style.css, webkit::UserContentInjectedFrames::AllFrames, webkit::UserStyleLevel::Author, &allow, &block);
|
||||
ucm.add_style_sheet(&sheet);
|
||||
}
|
||||
}
|
||||
|
||||
fn live_views(&self) -> Vec<webkit::WebView> {
|
||||
|
|
@ -182,15 +192,9 @@ impl Engine {
|
|||
|
||||
/// A new web view for a tab (`related`: a pop-up sharing its opener's web process).
|
||||
pub fn create_view(self: &Rc<Self>, id: ViewId, related: Option<&View>) -> View {
|
||||
// The message handler is registered before the view exists, so the first document can already post.
|
||||
let ucm = webkit::UserContentManager::new();
|
||||
let mut builder = webkit::WebView::builder().settings(&self.settings).user_content_manager(&ucm);
|
||||
builder = match related.map(|r| &r.web) {
|
||||
Some(r) => builder.related_view(r),
|
||||
None => builder.network_session(&self.session).web_context(&self.context),
|
||||
};
|
||||
let web = builder.build();
|
||||
web.set_background_color(&self.background.borrow());
|
||||
self.add_scripts(&ucm);
|
||||
self.add_content(&ucm);
|
||||
ucm.register_script_message_handler("nacre", None);
|
||||
let hub = self.hub.clone();
|
||||
ucm.connect_script_message_received(Some("nacre"), move |_, value| {
|
||||
|
|
@ -198,6 +202,13 @@ impl Engine {
|
|||
hub.push(Event::Page(id, msg));
|
||||
}
|
||||
});
|
||||
let mut builder = webkit::WebView::builder().settings(&self.settings).user_content_manager(&ucm);
|
||||
builder = match related.map(|r| &r.web) {
|
||||
Some(r) => builder.related_view(r),
|
||||
None => builder.network_session(&self.session).web_context(&self.context),
|
||||
};
|
||||
let web = builder.build();
|
||||
web.set_background_color(&self.background.borrow());
|
||||
self.views.borrow_mut().insert(id, web.downgrade());
|
||||
let view = View::new(id, web);
|
||||
self.wire(&view);
|
||||
|
|
@ -252,6 +263,12 @@ impl Engine {
|
|||
});
|
||||
let hub = self.hub.clone();
|
||||
web.connect_close(move |_| hub.push(Event::Closed(id)));
|
||||
if let Some(find) = web.find_controller() {
|
||||
let hub = self.hub.clone();
|
||||
find.connect_found_text(move |_, count| hub.push(Event::Find(id, count)));
|
||||
let hub = self.hub.clone();
|
||||
find.connect_failed_to_find_text(move |_| hub.push(Event::Find(id, 0)));
|
||||
}
|
||||
let hub = self.hub.clone();
|
||||
web.connect_web_process_terminated(move |_, reason| {
|
||||
let why = match reason {
|
||||
|
|
|
|||
|
|
@ -87,6 +87,17 @@ pub enum Event {
|
|||
Control(ViewId, Control),
|
||||
Notification(Option<ViewId>, Notification),
|
||||
Page(ViewId, PageMessage),
|
||||
/// Find in page: how many matches the last search or step found (0: none).
|
||||
Find(ViewId, u32),
|
||||
}
|
||||
|
||||
/// A user style sheet (`store::scripts`), added at author level so it acts like the page's own last `<style>`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct UserStyle {
|
||||
pub css: String,
|
||||
/// WebKit URL patterns (`https://*.example.com/*`); empty = every page.
|
||||
pub allow: Vec<String>,
|
||||
pub block: Vec<String>,
|
||||
}
|
||||
|
||||
/// One request seen by the network log (developer tools).
|
||||
|
|
|
|||
|
|
@ -7,6 +7,9 @@ use webkit::prelude::*;
|
|||
|
||||
use super::{JsValue, PageAction, ViewId};
|
||||
|
||||
/// Matches counted at most (as many as the old script-based find marked).
|
||||
const FIND_MAX: u32 = 5000;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct View {
|
||||
id: ViewId,
|
||||
|
|
@ -159,13 +162,38 @@ impl View {
|
|||
}
|
||||
}
|
||||
|
||||
/// Run `script` in the page's main frame; `done` gets the completion value as JSON, or the error text.
|
||||
/// Find in page: a new search (`fresh`) highlights every match and selects the first (or last, backwards);
|
||||
/// otherwise steps to the next or previous one. Both wrap around; the count comes back as `Event::Find`.
|
||||
pub fn find(&self, text: &str, case_sensitive: bool, forward: bool, fresh: bool) {
|
||||
let Some(find) = self.web.find_controller() else { return };
|
||||
if !fresh {
|
||||
if forward { find.search_next() } else { find.search_previous() }
|
||||
return;
|
||||
}
|
||||
let mut options = webkit::FindOptions::WRAP_AROUND;
|
||||
if !case_sensitive {
|
||||
options |= webkit::FindOptions::CASE_INSENSITIVE;
|
||||
}
|
||||
if !forward {
|
||||
options |= webkit::FindOptions::BACKWARDS;
|
||||
}
|
||||
find.search(text, options.bits(), FIND_MAX);
|
||||
}
|
||||
|
||||
/// Close find: highlights go.
|
||||
pub fn find_finish(&self) {
|
||||
if let Some(find) = self.web.find_controller() {
|
||||
find.search_finish();
|
||||
}
|
||||
}
|
||||
|
||||
/// Open WebKit's print dialog for the page.
|
||||
pub fn print(&self, parent: >k::Window) {
|
||||
let op = webkit::PrintOperation::new(&self.web);
|
||||
op.run_dialog(Some(parent));
|
||||
}
|
||||
|
||||
/// Run `script` in the page's main frame; `done` gets the completion value as JSON, or the error text.
|
||||
pub fn evaluate_javascript(&self, script: impl AsRef<str>, done: impl FnOnce(Result<JsValue, String>) + 'static) {
|
||||
self.web.evaluate_javascript(script.as_ref(), None, None, None::<>k::gio::Cancellable>, move |result| {
|
||||
done(match result {
|
||||
|
|
|
|||
153
src/inject.rs
153
src/inject.rs
|
|
@ -58,9 +58,9 @@ pub struct Options<'a> {
|
|||
/// All scripts, in the order they are added to the user content manager.
|
||||
///
|
||||
/// Nacre's own scripts run inside one closure with the private `__send`, so pages can call the
|
||||
/// functions on `window.__nacre` (find, media controls, ...) but can never send a message as Nacre.
|
||||
/// functions on `window.__nacre` (media controls, autofill, ...) but can never send a message as Nacre.
|
||||
pub fn page_scripts(o: &Options) -> Vec<String> {
|
||||
let mut modules: Vec<String> = vec![MEDIA_JS.to_owned(), FIND_JS.to_owned(), PIP_JS.to_owned(), META_JS.to_owned(), SVG_COLOR_JS.to_owned(), FONTS_CHECK_JS.to_owned(), COMPRESSOR_JS.to_owned()];
|
||||
let mut modules: Vec<String> = vec![MEDIA_JS.to_owned(), PIP_JS.to_owned(), META_JS.to_owned()];
|
||||
if o.dnt {
|
||||
modules.push(DNT_JS.to_owned());
|
||||
}
|
||||
|
|
@ -117,7 +117,7 @@ const BRIDGE_JS: &str = r#"if (window.__nacre) return;
|
|||
// Private to Nacre's scripts: pages run later and can't reach it, or swap what it uses.
|
||||
const __send = (t, d) => { try { log(TOKEN + stringify({ t, d: d === undefined ? null : d })); } catch (e) {} };
|
||||
Object.defineProperty(window, '__nacre', { value: {}, writable: false, configurable: false, enumerable: false });
|
||||
// <a download> and links the user asked to save: Servo can't download, Nacre does.
|
||||
// <a download> and links the user asked to save go to Nacre's own download manager.
|
||||
document.addEventListener('click', e => {
|
||||
const a = e.target && e.target.closest && e.target.closest('a[download]');
|
||||
if (!a || !a.href || e.defaultPrevented) return;
|
||||
|
|
@ -133,8 +133,8 @@ const BRIDGE_JS: &str = r#"if (window.__nacre) return;
|
|||
if (r && r.startContainer.nodeType === 3) { const s = r.startContainer.data, i = r.startOffset;
|
||||
const m = /[\p{L}'’-]*$/u.exec(s.slice(0, i))[0] + /^[\p{L}'’-]*/u.exec(s.slice(i))[0]; word = m; } } catch (e) {}
|
||||
const field = t && t.closest && t.closest('input,textarea,[contenteditable=""],[contenteditable=true]');
|
||||
// Servo has no caretRangeFromPoint, and text fields have no text node anyway: the spell check's mirror
|
||||
// underlines the misspelled words, so the one under the pointer is the one clicked.
|
||||
// Text fields have no text node for caretRangeFromPoint: the spell check's mirror underlines the
|
||||
// misspelled words, so the one under the pointer is the one clicked.
|
||||
if (!word && field) for (const u of document.querySelectorAll('.__nacre_spell_mirror u'))
|
||||
for (const r of u.getClientRects()) if (e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) word = u.textContent;
|
||||
__send('context', { selection: sel.slice(0, 2000), word, editable: !!field,
|
||||
|
|
@ -234,52 +234,6 @@ const MEDIA_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.media)
|
|||
} };
|
||||
})();"#;
|
||||
|
||||
/// Find in page: highlights every match, steps through them, reports "n of m".
|
||||
const FIND_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.find) return;
|
||||
let marks = [], cur = -1, lastQ = '', lastCase = false;
|
||||
const clear = () => { for (const m of marks) { const p = m.parentNode; if (!p) continue;
|
||||
p.replaceChild(document.createTextNode(m.textContent), m); p.normalize(); }
|
||||
marks = []; cur = -1; };
|
||||
const css = () => { if (document.getElementById('__nacre_find_css')) return;
|
||||
const s = document.createElement('style'); s.id = '__nacre_find_css';
|
||||
s.textContent = 'mark[data-nacre-find]{background:#ffd54f!important;color:#000!important;border-radius:2px}' +
|
||||
'mark[data-nacre-find].cur{background:#ff9800!important}';
|
||||
(document.head || document.documentElement).appendChild(s); };
|
||||
const search = (q, cs) => {
|
||||
clear(); if (!q) return;
|
||||
css();
|
||||
const needle = cs ? q : q.toLowerCase();
|
||||
const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT, { acceptNode: n => {
|
||||
const p = n.parentElement; if (!p || /^(SCRIPT|STYLE|NOSCRIPT|TEXTAREA|INPUT)$/.test(p.tagName)) return NodeFilter.FILTER_REJECT;
|
||||
const st = getComputedStyle(p); if (st.display === 'none' || st.visibility === 'hidden') return NodeFilter.FILTER_REJECT;
|
||||
return NodeFilter.FILTER_ACCEPT; } });
|
||||
const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode);
|
||||
for (const node of nodes) {
|
||||
const text = cs ? node.data : node.data.toLowerCase();
|
||||
let i = text.indexOf(needle); if (i < 0) continue;
|
||||
let n = node;
|
||||
while (i >= 0 && marks.length < 5000) {
|
||||
const hit = n.splitText(i); const after = hit.splitText(q.length);
|
||||
const m = document.createElement('mark'); m.setAttribute('data-nacre-find', '');
|
||||
hit.parentNode.replaceChild(m, hit); m.appendChild(hit); marks.push(m);
|
||||
n = after; const t = cs ? n.data : n.data.toLowerCase(); i = t.indexOf(needle);
|
||||
}
|
||||
}
|
||||
};
|
||||
const go = i => { if (!marks.length) return; if (cur >= 0 && marks[cur]) marks[cur].classList.remove('cur');
|
||||
cur = (i + marks.length) % marks.length; marks[cur].classList.add('cur');
|
||||
marks[cur].scrollIntoView({ block: 'center', inline: 'nearest' }); };
|
||||
window.__nacre.find = {
|
||||
run(q, cs, dir) {
|
||||
if (q !== lastQ || cs !== lastCase || !marks.length || !marks[0].isConnected) { search(q, cs); lastQ = q; lastCase = cs; go(0); }
|
||||
else go(cur + (dir < 0 ? -1 : 1));
|
||||
const r = { count: marks.length, index: marks.length ? cur + 1 : 0 };
|
||||
__send('find', r); return r;
|
||||
},
|
||||
stop() { clear(); lastQ = ''; }
|
||||
};
|
||||
})();"#;
|
||||
|
||||
/// 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).
|
||||
const PIP_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.pip) return;
|
||||
|
|
@ -296,8 +250,7 @@ const PIP_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.pip) retu
|
|||
// 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; }
|
||||
// Servo 0.7 freezes a playing video that is seeked and then play()ed: pause before the seek.
|
||||
const v = window.__nacrePipV; v.pause(); try { v.currentTime = t; } catch (e) {}
|
||||
const v = window.__nacrePipV; try { v.currentTime = t; } catch (e) {}
|
||||
if (play) v.play().catch(() => {}); else v.pause(); },
|
||||
enter() {
|
||||
const v = pick();
|
||||
|
|
@ -353,8 +306,8 @@ const DNT_JS: &str = r#"(() => { try {
|
|||
} catch (e) {} })();"#;
|
||||
|
||||
/// Privacy mode: fingerprint noise seeded per site and per run, common values for the rest.
|
||||
/// What `navigator` reports about the system in Firefox with this user agent. Servo answers "Linux" and "4.0",
|
||||
/// which no Firefox does, so privacy mode makes them agree with the user agent.
|
||||
/// What `navigator` reports about the system in Firefox with this user agent. With a Firefox user agent (the
|
||||
/// user's choice) the engine's own values would give it away, so privacy mode makes them agree.
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
pub struct FirefoxNavigator {
|
||||
pub platform: String,
|
||||
|
|
@ -363,7 +316,7 @@ pub struct FirefoxNavigator {
|
|||
pub app_version: String,
|
||||
}
|
||||
|
||||
/// `None` for a user agent that isn't Firefox on Windows, macOS or Linux (then Servo's own values stay).
|
||||
/// `None` for a user agent that isn't Firefox on Windows, macOS or Linux (then the engine's own values stay).
|
||||
pub fn firefox_navigator(ua: &str) -> Option<FirefoxNavigator> {
|
||||
if !ua.contains("Firefox/") {
|
||||
return None;
|
||||
|
|
@ -399,16 +352,15 @@ pub fn privacy_script(seed: &str, user_agent: &str, languages: &[String], paused
|
|||
/// - canvas, WebGL pixels, audio and canvas text widths get tiny noise seeded per top-level site and per run,
|
||||
/// so values differ on every site and after every restart but stay stable inside one site;
|
||||
/// - text-width noise makes every font in a probe list measure as "installed", the same for every user;
|
||||
/// - WebGL vendor/renderer say "Mozilla" (as Firefox does) instead of "Mozilla/Servo";
|
||||
/// - WebGL's unmasked vendor/renderer (the real GPU) read the same as the masked ones ("WebKit", "WebKit WebGL");
|
||||
/// - screen size is the smallest common size that holds the window, colour depth 24, position 0,0;
|
||||
/// - CPU cores read 8; platform, oscpu and appVersion match the user agent (`firefox_navigator`);
|
||||
/// - WEBGL_debug_renderer_info exists (answering "Mozilla"); no touch points and `createEvent('TouchEvent')`
|
||||
/// fails, as in desktop Firefox;
|
||||
/// - `navigator.languages` is Firefox's list for the locale, the same as Accept-Language (`net::nacre`).
|
||||
/// Not changed: time zone and locale (real, and consistent with each other: Servo reads both from the system),
|
||||
/// - no touch points and `createEvent('TouchEvent')` fails, as in desktop browsers;
|
||||
/// - `navigator.languages` is Firefox's list for the locale, the same as Accept-Language (`net::privacy`).
|
||||
/// Not changed: time zone and locale (real, and consistent with each other: both come from the system),
|
||||
/// the user agent itself, DOM-measured fonts, web workers. Paused sites (and every frame on their pages) keep
|
||||
/// the engine's values except the language list. Same-origin frames made by script get the same treatment through
|
||||
/// `contentWindow`, as Servo only injects scripts into documents it parses.
|
||||
/// `contentWindow`, as user scripts don't reach every document a script makes (`about:blank` frames).
|
||||
const PRIVACY_JS: &str = r#"(() => {
|
||||
if (location.protocol === 'nacre:' || window.__nacrePriv) return;
|
||||
const SEED = __SEED__, NAV = __NAV__, LANGS = __LANGS__, PAUSED = __PAUSED__;
|
||||
|
|
@ -465,14 +417,9 @@ function install(W) {
|
|||
let c = null; try { c = noisyCopy(this); } catch (e) {} return orig.apply(c || this, arguments); });
|
||||
for (const P of [W.WebGLRenderingContext, W.WebGL2RenderingContext]) { if (!P) continue;
|
||||
wrap(P.prototype, 'getParameter', orig => function (p) {
|
||||
if (p === 0x1F00 || p === 0x1F01 || p === 0x9245 || p === 0x9246) return 'Mozilla'; return orig.apply(this, arguments); });
|
||||
return orig.call(this, p === 0x9245 ? 0x1F00 : p === 0x9246 ? 0x1F01 : p); });
|
||||
wrap(P.prototype, 'readPixels', orig => function () { const r = orig.apply(this, arguments);
|
||||
const a = arguments[6]; if (a && a.length) noisePixels(a); return r; });
|
||||
// Servo has no WEBGL_debug_renderer_info; Firefox has it and answers "Mozilla" (getParameter above).
|
||||
const DEBUG = 'WEBGL_debug_renderer_info', info = Object.freeze({ UNMASKED_VENDOR_WEBGL: 0x9245, UNMASKED_RENDERER_WEBGL: 0x9246 });
|
||||
wrap(P.prototype, 'getExtension', orig => function (name) { const r = orig.apply(this, arguments); return r || name !== DEBUG ? r : info; });
|
||||
wrap(P.prototype, 'getSupportedExtensions', orig => function () { const r = orig.apply(this, arguments);
|
||||
return r && !r.includes(DEBUG) ? r.concat([DEBUG]) : r; }); }
|
||||
const a = arguments[6]; if (a && a.length) noisePixels(a); return r; }); }
|
||||
// Audio: tiny deterministic noise once per buffer.
|
||||
const seen = new WeakSet();
|
||||
wrap(W.AudioBuffer && W.AudioBuffer.prototype, 'getChannelData', orig => function () { const d = orig.apply(this, arguments);
|
||||
|
|
@ -489,13 +436,12 @@ function install(W) {
|
|||
getter(SP, 'availWidth', () => size()[0]); getter(SP, 'availHeight', () => size()[1]);
|
||||
getter(SP, 'availLeft', () => 0); getter(SP, 'availTop', () => 0);
|
||||
getter(SP, 'colorDepth', () => 24); getter(SP, 'pixelDepth', () => 24);
|
||||
// Window position: Servo keeps Window's attributes on the window itself or its prototype.
|
||||
// Window position: engines keep Window's attributes on the window itself or on its prototype.
|
||||
for (const k of ['screenX', 'screenY', 'screenLeft', 'screenTop'])
|
||||
getter(Object.getOwnPropertyDescriptor(W, k) ? W : W.Window && W.Window.prototype, k, () => 0);
|
||||
const NP = W.Navigator && W.Navigator.prototype;
|
||||
getter(NP, 'hardwareConcurrency', () => 8);
|
||||
// Desktop Firefox: no touch points, and touch events can't be created (Servo has touch events but no
|
||||
// maxTouchPoints, a rare combination). The TouchEvent globals stay: removing them breaks pages (Wikipedia's
|
||||
// Desktop browsers: no touch points, and touch events can't be created. The TouchEvent globals stay: removing them breaks pages (Wikipedia's
|
||||
// search field, media documents).
|
||||
getter(NP, 'maxTouchPoints', () => 0);
|
||||
wrap(W.Document && W.Document.prototype, 'createEvent', orig => function (type) {
|
||||
|
|
@ -510,33 +456,8 @@ function install(W) {
|
|||
install(window);
|
||||
})();"#;
|
||||
|
||||
/// Servo 0.7's `document.fonts` has no `check()`, and scripts that call it stop there (Cover Your Tracks never
|
||||
/// sends its fingerprint). Per the spec: false only when a face of a named family is in the set and not loaded yet.
|
||||
const FONTS_CHECK_JS: &str = r#"(() => { const P = window.FontFaceSet && FontFaceSet.prototype; if (!P || P.check) return;
|
||||
Object.defineProperty(P, 'check', { configurable: true, writable: true, value: function check(font) {
|
||||
const m = /(?:^|\s)[\d.]+(?:px|pt|em|rem|%)(?:\s*\/\s*\S+)?\s+(.+)$/.exec(String(font));
|
||||
if (!m) throw new DOMException('Invalid font', 'SyntaxError');
|
||||
const names = m[1].split(',').map(f => f.trim().replace(/^["']|["']$/g, '').toLowerCase());
|
||||
let ok = true;
|
||||
try { this.forEach(face => { if (names.includes(face.family.replace(/^["']|["']$/g, '').toLowerCase()) && face.status !== 'loaded') ok = false; }); } catch (e) {}
|
||||
return ok; } });
|
||||
})();"#;
|
||||
|
||||
/// Servo 0.7 has no DynamicsCompressorNode; audio fingerprint scripts (Fingerprint2, Cover Your Tracks) and some
|
||||
/// players throw at `createDynamicsCompressor`. This stand-in passes the sound through unchanged: a GainNode with
|
||||
/// the compressor's parameters (real AudioParams, so automation calls work) and `reduction` 0.
|
||||
const COMPRESSOR_JS: &str = r#"(() => { const B = window.BaseAudioContext || window.AudioContext; const P = B && B.prototype;
|
||||
if (!P || P.createDynamicsCompressor || !P.createGain) return;
|
||||
const PARAMS = { threshold: -24, knee: 30, ratio: 12, attack: 0.003, release: 0.25 };
|
||||
Object.defineProperty(P, 'createDynamicsCompressor', { configurable: true, writable: true, value: function createDynamicsCompressor() {
|
||||
const node = this.createGain();
|
||||
for (const [k, v] of Object.entries(PARAMS)) { const param = this.createGain().gain; param.value = v; Object.defineProperty(node, k, { value: param, enumerable: true }); }
|
||||
Object.defineProperty(node, 'reduction', { value: 0, enumerable: true });
|
||||
return node; } });
|
||||
})();"#;
|
||||
|
||||
/// Third-party cookie blocking for scripts: servo-net blocks the cookies of cross-site requests (S023), but a
|
||||
/// cross-site frame's `document.cookie` goes through the script thread, which doesn't say which page it is on.
|
||||
/// Third-party cookie blocking for scripts, until the engine's own third-party cookie policy is on (it covers
|
||||
/// frames' `document.cookie` itself, and this module goes).
|
||||
/// A frame whose top page is another site gets an empty, write-only-to-nowhere `document.cookie`. The top page
|
||||
/// is known when same-origin, else from the referrer; with neither, the frame counts as cross-site.
|
||||
const FRAME_COOKIE_JS: &str = r#"(() => { if (window.top === window || !location.hostname) return;
|
||||
|
|
@ -550,18 +471,6 @@ const FRAME_COOKIE_JS: &str = r#"(() => { if (window.top === window || !location
|
|||
})();"#;
|
||||
|
||||
/// Dark pages for sites that have no dark style of their own.
|
||||
/// Servo 0.7 paints an inline <svg> as a separate image from its own markup, so `currentColor` doesn't see the
|
||||
/// colour CSS gives the element and falls back to black (dark icons on dark sites, R1-13). Each new <svg> gets its
|
||||
/// computed colour as its `color` attribute; a colour scheme change redoes them all. Hover colours aren't followed.
|
||||
const SVG_COLOR_JS: &str = r#"(() => { if (window.__nacreSvg) return; window.__nacreSvg = 1;
|
||||
let queued = false, all = false;
|
||||
const run = () => { queued = false; const list = document.querySelectorAll(all ? 'svg' : 'svg:not([data-nacre-color])'); all = false;
|
||||
for (const svg of list) { const c = getComputedStyle(svg).color; if (svg.getAttribute('data-nacre-color') !== c) { svg.setAttribute('data-nacre-color', c); svg.setAttribute('color', c); } } };
|
||||
const queue = (everything) => { all = all || everything === true; if (!queued) { queued = true; requestAnimationFrame(run); } };
|
||||
const start = () => { queue(true); new MutationObserver(() => queue()).observe(document.documentElement, { childList: true, subtree: true }); };
|
||||
try { matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => queue(true)); } catch (e) {}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true }); else start(); })();"#;
|
||||
|
||||
const FORCE_DARK_JS: &str = r#"(() => { const add = () => { if (document.getElementById('__nacre_dark')) return;
|
||||
const dark = matchMedia && matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
let bg = 'rgb(255, 255, 255)'; try { bg = getComputedStyle(document.body || document.documentElement).backgroundColor; } catch (e) {}
|
||||
|
|
@ -720,14 +629,6 @@ const GOOGLE_SIGNIN_JS: &str = r#"(() => { if (!/(^|\.)accounts\.google\.com$/.t
|
|||
/// The Firefox user agent used on Google's sign-in pages.
|
||||
pub const FIREFOX_UA: &str = "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0";
|
||||
|
||||
/// The default user agent: Servo's own, in Firefox's exact form ("... rv:N) Gecko/20100101 Firefox/N"), so sites
|
||||
/// that sniff for a known browser serve their Firefox pages; the Firefox version follows Servo's default.
|
||||
pub fn mainstream_ua(servo_default: &str) -> String {
|
||||
let without_servo: Vec<&str> = servo_default.split(' ').filter(|part| !part.starts_with("Servo/")).collect();
|
||||
let ua = without_servo.join(" ");
|
||||
if ua.contains("Gecko/") { ua } else { ua.replacen(" Firefox/", " Gecko/20100101 Firefox/", 1) }
|
||||
}
|
||||
|
||||
/// Small helpers for browser -> page calls.
|
||||
pub fn call(path: &str, args: &[Value]) -> String {
|
||||
let args: Vec<String> = args.iter().map(Value::to_string).collect();
|
||||
|
|
@ -750,13 +651,6 @@ pub fn redirect_page(to: &str, note: &str) -> Vec<u8> {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mainstream_user_agent() {
|
||||
let ua = mainstream_ua("Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Servo/0.7.0 Firefox/153.0");
|
||||
assert_eq!(ua, "Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0");
|
||||
assert_eq!(mainstream_ua(&ua), ua);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigator_values_match_the_user_agent() {
|
||||
let linux = firefox_navigator("Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0").unwrap();
|
||||
|
|
@ -767,12 +661,9 @@ mod tests {
|
|||
assert_eq!(windows, FirefoxNavigator { platform: "Win32".into(), oscpu: "Windows NT 10.0; Win64; x64".into(), app_version: "5.0 (Windows)".into() });
|
||||
let mac = firefox_navigator("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:153.0) Gecko/20100101 Firefox/153.0").unwrap();
|
||||
assert_eq!(mac, FirefoxNavigator { platform: "MacIntel".into(), oscpu: "Intel Mac OS X 10.15".into(), app_version: "5.0 (Macintosh)".into() });
|
||||
// Not Firefox, or an OS Firefox's form isn't known for: Servo's values stay.
|
||||
// Not Firefox, or an OS Firefox's form isn't known for: the engine's values stay.
|
||||
assert!(firefox_navigator("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36").is_none());
|
||||
assert!(firefox_navigator("Mozilla/5.0 (Android 14; Mobile; rv:140.0) Gecko/140.0 Firefox/140.0").is_none());
|
||||
// The script gets the default user agent's values (consistency with what Nacre sends).
|
||||
let ua = mainstream_ua("Mozilla/5.0 (X11; Linux x86_64; rv:153.0) Servo/0.7.0 Firefox/153.0");
|
||||
assert_eq!(firefox_navigator(&ua).unwrap().app_version, "5.0 (X11)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -796,6 +687,6 @@ mod tests {
|
|||
let m = parse_message("abc", r#"abc{"t":"media","d":{"title":"x"}}"#).unwrap();
|
||||
assert_eq!(m.kind, "media");
|
||||
assert!(parse_message("abc", "hello").is_none());
|
||||
assert_eq!(call("find.run", &[Value::from("a"), Value::from(false), Value::from(1)]).contains(r#"f("a",false,1)"#), true);
|
||||
assert!(call("media.act", &[Value::from("seek"), Value::from(1)]).contains(r#"f("seek",1)"#));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,12 +11,15 @@
|
|||
//! ```
|
||||
//!
|
||||
//! Styles use the same header inside a CSS comment (`/* ==UserStyle== ... */`) with `@match` too.
|
||||
//! Servo injects user content into every page, so each one is wrapped in a URL check.
|
||||
//! Scripts go into every page and are wrapped in a URL check. Styles become WebKit user style sheets with
|
||||
//! the patterns as their allow and block lists; a style whose patterns WebKit can't express (a `*` inside a
|
||||
//! host name, a port) falls back to a script that adds a `<style>`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::engine::UserStyle;
|
||||
use crate::util;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -151,8 +154,8 @@ fn escape_regex(text: &str) -> String {
|
|||
out
|
||||
}
|
||||
|
||||
/// JavaScript that runs `body` only on matching pages and at the right time. Servo user scripts
|
||||
/// run before the page's own scripts, which is "document-start".
|
||||
/// JavaScript that runs `body` only on matching pages and at the right time. User scripts run before
|
||||
/// the page's own scripts, which is "document-start".
|
||||
pub fn wrap_for_page(item: &UserContent) -> String {
|
||||
let header = item.header();
|
||||
let matches: Vec<String> = header.matches.iter().map(|p| util::js_string(&pattern_to_regex(p))).collect();
|
||||
|
|
@ -186,6 +189,36 @@ pub fn wrap_for_page(item: &UserContent) -> String {
|
|||
}
|
||||
}
|
||||
|
||||
/// A style as a WebKit user style sheet, or `None` when it's a script or a pattern WebKit's URL patterns can't say.
|
||||
pub fn user_style(item: &UserContent) -> Option<UserStyle> {
|
||||
if item.kind != Kind::Style {
|
||||
return None;
|
||||
}
|
||||
let header = item.header();
|
||||
let list = |patterns: &[String]| patterns.iter().map(|p| webkit_patterns(p)).collect::<Option<Vec<_>>>().map(|v| v.concat());
|
||||
Some(UserStyle { css: item.source.clone(), allow: list(&header.matches)?, block: list(&header.excludes)? })
|
||||
}
|
||||
|
||||
/// A match pattern in WebKit's form (scheme `*` = http and https, host `*` or `*.domain` or plain, path glob),
|
||||
/// with the same meaning `pattern_to_regex` gives it. WebKit's patterns have no port, so a host with one can't.
|
||||
fn webkit_patterns(pattern: &str) -> Option<Vec<String>> {
|
||||
if pattern == "<all_urls>" || pattern == "*" {
|
||||
return Some(vec!["http://*/*".to_owned(), "https://*/*".to_owned(), "file:///*".to_owned()]);
|
||||
}
|
||||
let (scheme, rest) = pattern.split_once("://")?;
|
||||
let (host, path) = match rest.find('/') {
|
||||
Some(i) => (&rest[..i], &rest[i..]),
|
||||
None => (rest, "/*"),
|
||||
};
|
||||
let host_ok = host == "*" || !host.strip_prefix("*.").unwrap_or(host).contains(['*', ':']);
|
||||
let ok = match scheme {
|
||||
"*" | "http" | "https" => host_ok && !host.is_empty(),
|
||||
"file" => host.is_empty(),
|
||||
_ => false,
|
||||
};
|
||||
ok.then(|| vec![format!("{scheme}://{host}{path}")])
|
||||
}
|
||||
|
||||
pub struct Scripts {
|
||||
path: PathBuf,
|
||||
pub items: Vec<UserContent>,
|
||||
|
|
@ -227,9 +260,14 @@ impl Scripts {
|
|||
self.save();
|
||||
}
|
||||
|
||||
/// JavaScript for every enabled item.
|
||||
/// JavaScript for every enabled script, and for styles `user_style` can't turn into a style sheet.
|
||||
pub fn page_scripts(&self) -> Vec<String> {
|
||||
self.items.iter().filter(|i| i.enabled).map(wrap_for_page).collect()
|
||||
self.items.iter().filter(|i| i.enabled && (i.kind == Kind::Script || user_style(i).is_none())).map(wrap_for_page).collect()
|
||||
}
|
||||
|
||||
/// Style sheets for every enabled style WebKit can match itself.
|
||||
pub fn page_styles(&self) -> Vec<UserStyle> {
|
||||
self.items.iter().filter(|i| i.enabled).filter_map(user_style).collect()
|
||||
}
|
||||
|
||||
fn save(&self) {
|
||||
|
|
@ -252,4 +290,27 @@ mod tests {
|
|||
assert_eq!(pattern_to_regex("https://*.example.com/*"), "^https:\\/\\/([^/]*\\.)?example\\.com\\/.*$");
|
||||
assert_eq!(pattern_to_regex("*://*/*"), "^https?:\\/\\/[^/]*\\/.*$");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_become_style_sheets_when_webkit_can_match() {
|
||||
let style = |src: &str| UserContent { id: 1, kind: Kind::Style, enabled: true, source: src.to_owned(), origin_url: String::new(), installed: 0 };
|
||||
let plain = style("/* ==UserStyle==\n@match https://*.example.com/*\n@exclude https://example.com/private/*\n==/UserStyle== */\nbody{color:red}");
|
||||
let sheet = user_style(&plain).unwrap();
|
||||
assert_eq!(sheet.allow, ["https://*.example.com/*"]);
|
||||
assert_eq!(sheet.block, ["https://example.com/private/*"]);
|
||||
assert!(sheet.css.ends_with("body{color:red}"));
|
||||
// No @match = every web page; <all_urls> the same plus files.
|
||||
assert_eq!(user_style(&style("a{}")).unwrap().allow, ["*://*/*"]);
|
||||
assert_eq!(webkit_patterns("<all_urls>").unwrap().len(), 3);
|
||||
assert_eq!(webkit_patterns("https://example.com").unwrap(), ["https://example.com/*"]);
|
||||
// A * inside a host name: WebKit can't, the script wrapper does.
|
||||
let glob = style("/* ==UserStyle==\n@match https://example.*/*\n==/UserStyle== */");
|
||||
assert!(user_style(&glob).is_none());
|
||||
assert!(webkit_patterns("http://127.0.0.1:8768/*").is_none());
|
||||
let mut store = Scripts { path: PathBuf::new(), items: vec![plain, glob], read_only: true };
|
||||
store.items[1].id = 2;
|
||||
assert_eq!((store.page_styles().len(), store.page_scripts().len()), (1, 1));
|
||||
let script = UserContent { id: 3, kind: Kind::Script, enabled: true, source: "1".to_owned(), origin_url: String::new(), installed: 0 };
|
||||
assert!(user_style(&script).is_none());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -140,6 +140,8 @@ pub struct FindState {
|
|||
pub count: u32,
|
||||
pub index: u32,
|
||||
pub focus: bool,
|
||||
/// The words and match case WebKit last searched for (the bar's `text` changes before its command runs).
|
||||
pub searched: Option<(String, bool)>,
|
||||
}
|
||||
|
||||
pub struct ConsoleLine {
|
||||
|
|
|
|||
|
|
@ -12,11 +12,11 @@ expect /tab_count 2
|
|||
open @PAGES@/basics.html
|
||||
waitload
|
||||
expect /active/title "Basics"
|
||||
# Inline SVG takes its colour from CSS (inject.rs SVG_COLOR_JS, R1-13): the icon is green, not black.
|
||||
waitfor 5 document.getElementById("icon").getAttribute("color") === "rgb(0, 160, 0)"
|
||||
# Inline SVG takes its colour from CSS (R1-13; WebKit paints currentColor itself): the icon is green, not black.
|
||||
waitfor 5 getComputedStyle(document.getElementById("icon")).color === "rgb(0, 160, 0)"
|
||||
shot svg-colour
|
||||
do duplicate_tab
|
||||
wait 1
|
||||
waitload
|
||||
expect /tab_count 3
|
||||
expect /active/title "Basics"
|
||||
do pin_tab
|
||||
|
|
|
|||
5
tests/smoke/pages/probe-file.user.css
Normal file
5
tests/smoke/pages/probe-file.user.css
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
/* ==UserStyle==
|
||||
@name Smoke probe file style
|
||||
@match file:///*smoke/pages/basics.html
|
||||
==/UserStyle== */
|
||||
body { background-color: rgb(86, 52, 18) !important; }
|
||||
|
|
@ -21,6 +21,18 @@ waitload
|
|||
wait 2
|
||||
assert window.userScriptRan === undefined
|
||||
assert getComputedStyle(document.body).backgroundColor !== 'rgb(18, 52, 86)'
|
||||
# A style WebKit matches itself (no port in the pattern): a user style sheet, not the script fallback.
|
||||
cmd install_script http://127.0.0.1:8768/probe-file.user.css
|
||||
wait 2
|
||||
open @PAGES@/basics.html
|
||||
waitload
|
||||
wait 1
|
||||
assert getComputedStyle(document.body).backgroundColor === 'rgb(86, 52, 18)'
|
||||
assert document.querySelector('style[data-nacre-user-style]') === null
|
||||
open @PAGES@/input.html
|
||||
waitload
|
||||
wait 1
|
||||
assert getComputedStyle(document.body).backgroundColor !== 'rgb(86, 52, 18)'
|
||||
# Install the page as an app, open its window.
|
||||
open http://127.0.0.1:8768/hello.html
|
||||
waitload
|
||||
|
|
|
|||
Loading…
Reference in a new issue