Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: keep the lists' page exceptions and reach subdomains with site hiding rules
Tw93d612863f435f
diff --git a/src-tauri/src/app/content_blocking.rs b/src-tauri/src/app/content_blocking.rsindex caf26dd1..58fc8b90 100644--- a/src-tauri/src/app/content_blocking.rs+++ b/src-tauri/src/app/content_blocking.rs@@ -82,7 +82,7 @@ fn filter_set(groups: &[&str], rule_types: RuleTypes, debug: bool) -> FilterSet/// its identifier, so a change to the conversion has to change this, or apps/// go on using the list the old conversion made.#[cfg(any(target_os = "macos", target_os = "linux", test))]-const CONVERSION: &str = "unhide-2";+const CONVERSION: &str = "exceptions-3";/// FNV-1a, enough to tell one selection of embedded lists from another.#[cfg(any(target_os = "macos", target_os = "linux", test))]@@ -127,16 +127,18 @@ fn webkit_identifier(groups: &[&str], unit: &str) -> String {format!("{IDENTIFIER_PREFIX}{unit}-{:016x}", fingerprint(groups))}-/// The rules of one WebKit unit, ready to serialize.-#[cfg(any(target_os = "macos", target_os = "linux", test))]+/// The rules of one WebKit unit, ready to serialize. Windows builds its+/// generic hiding from the same rules, so the three platforms agree.fn webkit_rules(groups: &[&str], rule_types: RuleTypes) -> Vec<adblock::content_blocking::CbRule> {let mut set = FilterSet::new(true);let mut unhide = Unhide::default();+ let mut allowed = Allowed::default();for bytes in list_bytes(groups) {let Some(text) = gunzip(bytes) else {eprintln!("[Pake] A built-in filter list could not be read");continue;};+ allowed.take_from(&text);set.add_filter_list(unhide.take_from(&text),ParseOptions {@@ -149,7 +151,104 @@ fn webkit_rules(groups: &[&str], rule_types: RuleTypes) -> Vec<adblock::content_.into_content_blocking().map(|(rules, _)| rules).unwrap_or_default();- unhide.apply(rules)+ if matches!(rule_types, RuleTypes::CosmeticOnly) {+ allowed.order(unhide.apply(rules))+ } else {+ allowed.after_requests(rules)+ }+}++/// The lists' page exceptions: `@@||site^$generichide` keeps the rules for+/// every site off a site, `$elemhide` every hiding rule, `$document` blocking+/// too. adblock's conversion drops the first two and reads the third as an+/// exception for requests to the site, so none of them held; EasyList keeps+/// generic hiding off about 350 sites this way. WebKit can only be told a+/// site, not a page: an exception for a path (`||bing.com/search?`) covers+/// its whole site, and one with no plain host is left out.+#[derive(Default)]+struct Allowed {+ generic_hiding: Vec<String>,+ hiding: Vec<String>,+ requests: Vec<String>,+}++impl Allowed {+ fn take_from(&mut self, text: &str) {+ for line in text.lines() {+ let Some(rest) = line.trim().strip_prefix("@@||") else {+ continue;+ };+ let Some((pattern, options)) = rest.rsplit_once('$') else {+ continue;+ };+ let host = pattern+ .split(['/', '^', '|', ':', '?'])+ .next()+ .unwrap_or_default()+ .to_ascii_lowercase();+ let plain = host.contains('.')+ && host+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-');+ if !plain {+ continue;+ }+ let entry = format!("*{host}");+ for option in options.split(',') {+ let lists: &mut [&mut Vec<String>] = match option.trim() {+ "generichide" | "ghide" => &mut [&mut self.generic_hiding],+ "elemhide" | "ehide" => &mut [&mut self.hiding],+ "document" | "doc" => &mut [&mut self.hiding, &mut self.requests],+ _ => continue,+ };+ for list in lists.iter_mut() {+ if !list.contains(&entry) {+ list.push(entry.clone());+ }+ }+ }+ }+ }++ fn ignore(sites: &[String]) -> Option<adblock::content_blocking::CbRule> {+ use adblock::content_blocking::{CbAction, CbRule, CbTrigger, CbType};+ (!sites.is_empty()).then(|| CbRule {+ action: CbAction {+ typ: CbType::IgnorePreviousRules,+ selector: None,+ },+ trigger: CbTrigger {+ url_filter: ".*".to_owned(),+ if_domain: Some(sites.to_vec()),+ ..CbTrigger::default()+ },+ })+ }++ /// Hiding rules for every site, the sites that take none of those, the+ /// rules for named sites, then the sites that take no hiding at all.+ fn order(+ &self,+ rules: Vec<adblock::content_blocking::CbRule>,+ ) -> Vec<adblock::content_blocking::CbRule> {+ let (specific, generic): (Vec<_>, Vec<_>) = rules+ .into_iter()+ .partition(|rule| rule.trigger.if_domain.is_some());+ generic+ .into_iter()+ .chain(Self::ignore(&self.generic_hiding))+ .chain(specific)+ .chain(Self::ignore(&self.hiding))+ .collect()+ }++ fn after_requests(+ &self,+ mut rules: Vec<adblock::content_blocking::CbRule>,+ ) -> Vec<adblock::content_blocking::CbRule> {+ rules.extend(Self::ignore(&self.requests));+ rules+ }}/// The lists' hiding exceptions (`example.com#@#.ad`: do not hide `.ad` on@@ -157,7 +256,6 @@ fn webkit_rules(groups: &[&str], rule_types: RuleTypes) -> Vec<adblock::content_/// conversion writes each one as "hide the selector on every site but that/// one", which hid every `svg`, Google's logo and icons among them, on all/// sites for the sake of one site's exception.-#[cfg(any(target_os = "macos", target_os = "linux", test))]#[derive(Default)]struct Unhide {/// Selector to the sites that keep it; an empty list is every site.@@ -165,13 +263,11 @@ struct Unhide {}/// Where a hiding exception holds.-#[cfg(any(target_os = "macos", target_os = "linux", test))]enum Sites {Every,Named(Vec<String>),}-#[cfg(any(target_os = "macos", target_os = "linux", test))]impl Unhide {/// `text` without its hiding exceptions, which are remembered.fn take_from(&mut self, text: &str) -> String {@@ -241,6 +337,16 @@ impl Unhide {rules.into_iter().filter_map(|mut rule| {+ // WebKit reads a bare name as that host alone; the lists mean+ // its subdomains too, and adblock leaves the `*` out for+ // hiding rules, so `example.com##.ad` never reached www.+ for hosts in [&mut rule.trigger.if_domain, &mut rule.trigger.unless_domain] {+ for host in hosts.iter_mut().flatten() {+ if !host.starts_with('*') {+ host.insert(0, '*');+ }+ }+ }let Some(sites) = rule.action.selector@@ -286,6 +392,58 @@ impl Unhide {}}+/// A script for every document on Windows: the hiding rules for every site,+/// each without the sites its exceptions name, and none at all on a site the+/// lists keep generic or all hiding off. One rule per selector, so a selector+/// the browser rejects only drops its own rule.+#[cfg(any(target_os = "windows", test))]+fn generic_script(groups: &[&str]) -> String {+ use adblock::content_blocking::CbType;+ let bare = |hosts: &[String]| -> Vec<String> {+ hosts+ .iter()+ .map(|host| host.trim_start_matches('*').to_owned())+ .collect()+ };+ let mut off: Vec<String> = Vec::new();+ let mut plain = String::new();+ let mut excepted: Vec<(String, Vec<String>)> = Vec::new();+ for rule in webkit_rules(groups, RuleTypes::CosmeticOnly) {+ let hosts = rule.trigger.if_domain.as_deref();+ match (rule.action.typ, rule.action.selector, hosts) {+ (CbType::IgnorePreviousRules, _, Some(hosts)) => off.extend(bare(hosts)),+ (CbType::CssDisplayNone, Some(selector), None) => {+ if selector.contains(['{', '}', '<']) {+ continue;+ }+ match rule.trigger.unless_domain.as_deref() {+ Some(hosts) => excepted.push((selector, bare(hosts))),+ None => {+ plain.push_str(&selector);+ plain.push_str("{display:none!important}\n");+ }+ }+ }+ _ => {}+ }+ }+ if plain.is_empty() && excepted.is_empty() {+ return String::new();+ }+ fn json<T: serde::Serialize>(value: &T) -> String {+ serde_json::to_string(value).unwrap_or_else(|_| "[]".into())+ }+ format!(+ "(()=>{{const h=location.hostname,on=d=>h===d||h.endsWith('.'+d);if({off}.some(on))return;\+ let c={plain};for(const [s,d] of {excepted})if(!d.some(on))c+=s+'{{display:none!important}}\\n';\+ const s=document.createElement('style');s.setAttribute('data-pake-blocking','');s.textContent=c;\+ (document.head||document.documentElement).appendChild(s);}})();",+ off = json(&off),+ plain = json(&plain),+ excepted = json(&excepted),+ )+}+/// The JSON of one WebKit unit, or `None` when it has no rules or is too large.#[cfg(any(target_os = "macos", target_os = "linux"))]fn webkit_json(groups: &[&str], unit: &str) -> Option<String> {@@ -789,7 +947,7 @@ pub use platform::set_store_dir;#[cfg(target_os = "windows")]mod windows {- use super::{filter_set, selected_groups};+ use super::{filter_set, generic_script, selected_groups};use adblock::lists::RuleTypes;use adblock::request::Request;use adblock::Engine;@@ -805,8 +963,8 @@ mod windows {struct Blocker {engine: Engine,- /// Element hiding that applies on every site.- generic_css: String,+ /// Hides what the lists hide on every site, exceptions observed.+ generic_script: String,}// The engine is built once per selection; a process has one selection.@@ -818,33 +976,13 @@ mod windows {let mut map = map.lock().unwrap_or_else(|poisoned| poisoned.into_inner());map.entry(groups.clone()).or_insert_with(|| {let engine = Engine::new_with_filter_set(filter_set(&groups, RuleTypes::All, false));- let generic = generic_selectors(&groups);Box::leak(Box::new(Blocker {engine,- generic_css: css(generic.iter().map(String::as_str)),+ generic_script: generic_script(&groups),}))})}- /// Selectors of the hiding rules with no site condition, taken from the- /// WebKit conversion so both platforms hide the same generic elements.- fn generic_selectors(groups: &[&str]) -> Vec<String> {- let Ok((rules, _)) =- filter_set(groups, RuleTypes::CosmeticOnly, true).into_content_blocking()- else {- return Vec::new();- };- rules- .into_iter()- .filter(|rule| {- rule.trigger.if_domain.is_none()- && rule.trigger.unless_domain.is_none()- && rule.trigger.url_filter == ".*"- })- .filter_map(|rule| rule.action.selector)- .collect()- }-/// One rule per selector: a selector the browser rejects only drops its own rule.fn css<'a>(selectors: impl Iterator<Item = &'a str>) -> String {selectors@@ -948,9 +1086,9 @@ mod windows {&mut token,)?;- if !blocker.generic_css.is_empty() {+ if !blocker.generic_script.is_empty() {core.AddScriptToExecuteOnDocumentCreated(- &HSTRING::from(style_script(&blocker.generic_css)),+ &HSTRING::from(blocker.generic_script.as_str()),&AddScriptToExecuteOnDocumentCreatedCompletedHandler::create(Box::new(|_, _| Ok(()),)),@@ -1099,10 +1237,69 @@ mod tests {let ad = of(".ad").expect("the generic rule stays");assert_eq!(ad.trigger.unless_domain, Some(vec!["*keep.com".to_owned()]));let boxed = of(".box").expect("the rule keeps its other site");- assert_eq!(boxed.trigger.if_domain, Some(vec!["bar.com".to_owned()]));+ assert_eq!(boxed.trigger.if_domain, Some(vec!["*bar.com".to_owned()]));assert!(of(".only").is_none() && of(".gone").is_none() && of("svg").is_none());}+ #[test]+ fn page_exceptions_become_rules_webkit_can_follow() {+ let mut allowed = Allowed::default();+ allowed.take_from(+ "@@||a.com^$generichide\n@@||b.com/search?$ghide\n@@||c.com^$elemhide\n\+ @@||d.com^$document\n@@||www.google.*/search?$generichide\n\+ @@://localhost/$generichide\n@@||e.com^$script\n||f.com^$document\n",+ );+ assert_eq!(allowed.generic_hiding, ["*a.com", "*b.com"]);+ assert_eq!(allowed.hiding, ["*c.com", "*d.com"]);+ assert_eq!(allowed.requests, ["*d.com"]);++ use adblock::content_blocking::CbType;+ let all: Vec<&str> = GROUPS.iter().map(|(group, _)| *group).collect();+ let rules = webkit_rules(&all, RuleTypes::CosmeticOnly);+ let ignores: Vec<usize> = (0..rules.len())+ .filter(|index| rules[*index].action.typ == CbType::IgnorePreviousRules)+ .collect();+ assert_eq!(ignores.len(), 2, "generic hiding and all hiding");+ let sites = |index: usize| rules[index].trigger.if_domain.clone().unwrap_or_default();+ assert!(sites(ignores[0]).contains(&"*bing.com".to_owned()));+ assert!(sites(ignores[0]).len() > 300);+ assert!(rules[..ignores[0]]+ .iter()+ .all(|rule| rule.trigger.if_domain.is_none()));+ assert!(rules[ignores[0] + 1..ignores[1]]+ .iter()+ .all(|rule| rule.trigger.if_domain.is_some()));+ assert_eq!(ignores[1], rules.len() - 1);+ // A bare name is that host alone to WebKit.+ assert!(rules+ .iter()+ .flat_map(|rule| rule+ .trigger+ .if_domain+ .iter()+ .chain(&rule.trigger.unless_domain))+ .flatten()+ .all(|host| host.starts_with('*')));+ }++ #[test]+ fn the_windows_script_carries_the_exceptions() {+ let script = generic_script(&["ads"]);+ if let Ok(path) = std::env::var("PAKE_DUMP_SCRIPT") {+ std::fs::write(path, &script).expect("script written");+ }+ assert!(+ script.contains("\"bing.com\""),+ "a site with generic hiding off"+ );+ assert!(+ script.contains("\",[\""),+ "a selector with the sites that keep it"+ );+ assert!(!script.contains("\"*"), "hosts are compared bare");+ assert!(!script.contains("svg{display"));+ }+#[test]fn rules_serialize_to_webkit_json() {let rules = webkit_rules(&["ads"], RuleTypes::NetworkOnly);