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
feat(extensions): carry an extension's own settings into a built app
Tw9352242388e096
diff --git a/src-tauri/src/app/extensions/macos.rs b/src-tauri/src/app/extensions/macos.rsindex 02b8ebd8..87d46aa3 100644--- a/src-tauri/src/app/extensions/macos.rs+++ b/src-tauri/src/app/extensions/macos.rs@@ -4,6 +4,7 @@//! "Tab not found" when there are none. Pake has no tabs, so every webview it//! builds is reported as one tab of a single window.+use super::settings::{self, Action, Mode};use super::{installed, unpacked, Installed};use block2::RcBlock;use objc2::rc::{Allocated, Retained, Weak};@@ -21,7 +22,7 @@ use objc2_web_kit::{};use std::cell::RefCell;use std::collections::HashMap;-use std::path::Path;+use std::path::{Path, PathBuf};use std::ptr::NonNull;use std::time::Duration;@@ -49,6 +50,12 @@ struct Host {contexts: HashMap<String, Retained<WKWebExtensionContext>>,/// The windows showing an extension's pages, kept so a second ask raises one.pages: HashMap<String, Retained<AnyObject>>,+ directory: PathBuf,+ incognito: bool,+ /// Pake's own page of each extension whose settings an app may carry,+ /// open out of sight (settings.rs).+ settings: HashMap<String, (Retained<AnyObject>, settings::Page)>,+ settings_started: bool,}thread_local! {@@ -427,6 +434,10 @@ fn start(mtm: MainThreadMarker, directory: &Path, incognito: bool) -> Option<Hoslisted: installed(directory),contexts: HashMap::new(),pages: HashMap::new(),+ directory: directory.to_path_buf(),+ incognito,+ settings: HashMap::new(),+ settings_started: false,})}@@ -445,10 +456,207 @@ fn loaded(name: &str, extension: Option<Retained<WKWebExtension>>, reason: &str)host.pending = host.pending.saturating_sub(1);(host.pending == 0).then(|| std::mem::take(&mut host.callbacks))});+ let ready = callbacks.is_some();callbacks.into_iter().flatten().for_each(|callback| callback());+ if ready {+ start_settings();+ }+}++/// Opens Pake's page of every loaded extension that has one, out of sight,+/// and asks each one every `settings::INTERVAL` whether there is news.+fn start_settings() {+ let Some(mtm) = MainThreadMarker::new() else {+ return;+ };+ let started = HOST.with_borrow_mut(|host| {+ let host = host.as_mut()?;+ if std::mem::replace(&mut host.settings_started, true) {+ return None;+ }+ for (name, context) in &host.contexts {+ let Some(mode) = settings::mode(&host.directory.join(name), host.incognito) else {+ continue;+ };+ let Some(webview) = (unsafe { settings_webview(mtm, context, mode) }) else {+ continue;+ };+ let page = settings::Page::new(name.clone(), mode, host.incognito);+ host.settings.insert(name.clone(), (webview, page));+ }+ (!host.settings.is_empty()).then_some(())+ });+ if started.is_none() {+ return;+ }+ std::thread::spawn(|| {+ while settings::polling() {+ std::thread::sleep(settings::INTERVAL);+ dispatch::Queue::main().exec_async(poll_settings);+ }+ });+}++/// A webview of the extension's own, in no window, showing Pake's page.+unsafe fn settings_webview(+ mtm: MainThreadMarker,+ context: &WKWebExtensionContext,+ mode: Mode,+) -> Option<Retained<AnyObject>> {+ let _ = mtm;+ let configuration = context.webViewConfiguration()?;+ let frame = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(1.0, 1.0));+ let webview: Allocated<AnyObject> = msg_send![class!(WKWebView), alloc];+ let webview: Retained<AnyObject> =+ msg_send![webview, initWithFrame: frame, configuration: &*configuration];+ load_settings_page(&webview, context, mode);+ Some(webview)+}++unsafe fn load_settings_page(webview: &AnyObject, context: &WKWebExtensionContext, mode: Mode) {+ let Some(url) = NSURL::URLWithString_relativeToURL(+ &NSString::from_str(&settings::page_path(mode)),+ Some(&context.baseURL()),+ ) else {+ return;+ };+ let request: Retained<AnyObject> = msg_send![class!(NSURLRequest), requestWithURL: &*url];+ let _: *mut AnyObject = msg_send![webview, loadRequest: &*request];+}++/// Runs `script` in `webview` and hands its result, as text, to `done`.+fn evaluate(webview: &AnyObject, script: &str, done: impl Fn(String) + 'static) {+ let block = RcBlock::new(move |result: *mut AnyObject, _error: *mut NSError| {+ let text = unsafe { result.as_ref() }+ .and_then(|result| result.downcast_ref::<NSString>())+ .map(|text| text.to_string())+ .unwrap_or_default();+ done(text);+ });+ unsafe {+ let _: () = msg_send![+ webview,+ evaluateJavaScript: &*NSString::from_str(script),+ completionHandler: &*block+ ];+ }+}++fn settings_webview_of(name: &str) -> Option<Retained<AnyObject>> {+ HOST.with_borrow(|host| Some(host.as_ref()?.settings.get(name)?.0.clone()))+}++fn poll_settings() {+ let names: Vec<String> = HOST.with_borrow(|host| {+ host.as_ref()+ .map(|host| host.settings.keys().cloned().collect())+ .unwrap_or_default()+ });+ for name in names {+ let Some(webview) = settings_webview_of(&name) else {+ continue;+ };+ evaluate(&webview, settings::PROBE_SCRIPT, move |answer| {+ settings_answered(&name, &answer)+ });+ }+}++fn settings_answered(name: &str, answer: &str) {+ let action = HOST.with_borrow_mut(|host| {+ let (_, page) = host.as_mut()?.settings.get_mut(name)?;+ Some(page.next(answer))+ });+ let Some(webview) = settings_webview_of(name) else {+ return;+ };+ match action {+ Some(Action::ReadSnapshot) => {+ let name = name.to_owned();+ evaluate(&webview, settings::SNAPSHOT_SCRIPT, move |snapshot| {+ HOST.with_borrow_mut(|host| {+ if let Some((_, page)) =+ host.as_mut().and_then(|host| host.settings.get_mut(&name))+ {+ page.save(&snapshot);+ }+ });+ });+ }+ Some(Action::Watch) => {+ HOST.with_borrow(|host| {+ if let Some(context) = host.as_ref().and_then(|host| host.contexts.get(name)) {+ unsafe { load_settings_page(&webview, context, Mode::Watch) };+ }+ });+ }+ Some(Action::Close) => HOST.with_borrow_mut(|host| {+ if let Some(host) = host.as_mut() {+ host.settings.remove(name);+ if host.settings.is_empty() {+ settings::stop_polling();+ }+ }+ }),+ Some(Action::Restart) => {+ evaluate(&webview, settings::RESTART_SCRIPT, |_| {});+ let name = name.to_owned();+ std::thread::spawn(move || {+ std::thread::sleep(settings::RESTART_DELAY);+ dispatch::Queue::main().exec_async(move || settings_restarted(&name));+ });+ }+ _ => {}+ }+}++/// The extension has its carried settings and has restarted: Pake's page+/// loads again to follow it, and every page of the app loads again to get it.+fn settings_restarted(name: &str) {+ HOST.with_borrow_mut(|host| {+ let Some(host) = host.as_mut() else {+ return;+ };+ let watch = match host.settings.get_mut(name) {+ Some((_, page)) => {+ page.restarted();+ page.mode == Mode::Watch+ }+ None => return,+ };+ match (watch, host.contexts.get(name), host.settings.get(name)) {+ (true, Some(context), Some((webview, _))) => unsafe {+ load_settings_page(webview, context, Mode::Watch)+ },+ _ => {+ host.settings.remove(name);+ }+ }+ if host.settings.is_empty() {+ settings::stop_polling();+ }+ });+ // WebKit says when a click's navigation is under way before its page shows, which the+ // page itself cannot see: such a window gets the script that leaves it to arrive.+ for (_, window) in settings::own_windows() {+ let _ = window.with_webview(|webview| unsafe {+ let view = webview.inner() as *const AnyObject;+ if view.is_null() {+ return;+ }+ let view = &*view;+ let loading: bool = msg_send![view, isLoading];+ let script = if loading {+ settings::NAVIGATING_RELOAD_SCRIPT+ } else {+ settings::RELOAD_SCRIPT+ };+ evaluate(view, script, |_| {});+ });+ }}fn load(diff --git a/src-tauri/src/app/extensions/mod.rs b/src-tauri/src/app/extensions/mod.rsindex 007688cd..7a2650cf 100644--- a/src-tauri/src/app/extensions/mod.rs+++ b/src-tauri/src/app/extensions/mod.rs@@ -6,6 +6,9 @@use std::path::{Path, PathBuf};+#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]+pub mod settings;+#[cfg(target_os = "macos")]mod macos;#[cfg(target_os = "macos")]diff --git a/src-tauri/src/app/extensions/settings.rs b/src-tauri/src/app/extensions/settings.rsnew file mode 100644index 00000000..c3afdce9--- /dev/null+++ b/src-tauri/src/app/extensions/settings.rs@@ -0,0 +1,475 @@+//! Carrying an extension's settings into a built app.+//!+//! The app builder puts a page of its own, `pake-settings.html`, into each+//! extension whose settings it may carry. The runtime keeps that page open out+//! of sight. The page holds a copy of the extension's storage, which the+//! runtime writes to `<app data>/extension-settings/<folder>.json` whenever it+//! changes, for the builder to read when it builds the app again. A built app+//! carries such a copy as `pake-settings.json` in the extension's folder. On a+//! machine whose storage never held that copy, the first launch writes it into+//! the extension's storage, restarts the extension and reloads the app's pages.+//!+//! The page speaks through `window.pakeSettings`: `state` (`ready` once its+//! copy is current, `written` once a carried copy is in storage, `failed`),+//! `version`, which grows with every new copy, `id`, the copy's digest, and+//! `snapshot`, the copy as JSON. `restart()` restarts the extension.++use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::OnceLock;+use std::time::Duration;++use tauri::{AppHandle, Manager};++pub const PAGE: &str = "pake-settings.html";+pub const PRESET: &str = "pake-settings.json";+/// How often the runtime asks the page whether there is something new.+pub const INTERVAL: Duration = Duration::from_secs(2);+/// How long a restarting extension gets before the page and the app's pages load again.+pub const RESTART_DELAY: Duration = Duration::from_secs(2);++pub const PROBE_SCRIPT: &str =+ "window.pakeSettings ? [pakeSettings.state, pakeSettings.version, pakeSettings.id].join(' ') : ''";+pub const SNAPSHOT_SCRIPT: &str = "window.pakeSettings ? pakeSettings.snapshot : ''";+pub const RESTART_SCRIPT: &str = "window.pakeSettings && pakeSettings.restart(); 0";++/// The digests a store held, newest last; older ones fall off past this many.+/// A carried copy is decided by `<name>.applied`, which never drops one.+const REMEMBERED: usize = 64;++static STORE: OnceLock<PathBuf> = OnceLock::new();+static APP: OnceLock<AppHandle> = OnceLock::new();+/// The hosts' pollers run while this holds; a host clears it once it has no page left to ask.+static POLLING: AtomicBool = AtomicBool::new(true);++/// Where the copies and the digests go: the app's own data folder.+pub fn set_store(app: &AppHandle, directory: PathBuf) {+ let _ = STORE.set(directory.join("extension-settings"));+ let _ = APP.set(app.clone());+}++pub fn polling() -> bool {+ POLLING.load(Ordering::Relaxed)+}++pub fn stop_polling() {+ POLLING.store(false, Ordering::Relaxed);+}++/// The app's own windows, which load again once an extension has its carried settings:+/// the first and any later one, never a sign-in popup, whose half-done sign-in a reload loses.+pub fn reloadable(label: &str) -> bool {+ label == "pake"+ || (label.starts_with("pake-")+ && !label.starts_with(crate::app::window::POPUP_WINDOW_LABEL_PREFIX))+}++/// Loads a page again once it has finished loading, so a page still on its way in is not cut off+/// and still ends up with what the extension now holds. A window on its first blank page is on+/// its way to the site, which it reaches with the restarted extension, so it is left alone.+pub const RELOAD_SCRIPT: &str = "(() => { if (location.protocol === 'about:') return; \+const again = () => location.reload(); \+if (document.readyState === 'complete') again(); \+else addEventListener('load', again, { once: true }); })();";++/// For a web view the host knows is navigating: a document still loading is loaded again once+/// it has finished, and a finished one is left, since the navigation under way is to a new page+/// that comes up with the restarted extension, and reloading would drop it.+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+pub const NAVIGATING_RELOAD_SCRIPT: &str = "(() => { if (location.protocol === 'about:') return; \+if (document.readyState === 'complete') return; \+addEventListener('load', () => location.reload(), { once: true }); })();";++/// The app's own windows, those a carried copy loads again.+pub fn own_windows() -> Vec<(String, tauri::WebviewWindow)> {+ let Some(app) = APP.get() else {+ return Vec::new();+ };+ app.webview_windows()+ .into_iter()+ .filter(|(label, _)| reloadable(label))+ .collect()+}++/// Loads each of the app's own windows again, after an extension took its carried settings.+#[cfg_attr(target_os = "macos", allow(dead_code))]+pub fn reload_windows() {+ for (label, window) in own_windows() {+ if let Err(error) = window.eval(RELOAD_SCRIPT) {+ eprintln!("[Pake] Could not reload {label} for the extension settings: {error}");+ }+ }+}++fn store() -> Option<&'static PathBuf> {+ STORE.get()+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Mode {+ /// Write the carried copy into storage, then restart the extension.+ Apply,+ /// The extension is restarting after that.+ Restarting,+ /// Keep the copy on disk current.+ Watch,+}++/// What to do with the extension in `folder`, or `None` when it has no page of+/// Pake's. In a private window nothing is kept, and a carried copy is written+/// on every launch, since the storage starts empty each time.+pub fn mode(folder: &Path, incognito: bool) -> Option<Mode> {+ if !folder.join(PAGE).is_file() {+ return None;+ }+ let name = folder_name(folder);+ if let Some(id) = preset_id(folder) {+ if incognito {+ return Some(Mode::Apply);+ }+ if !applied(&name).contains(&id) {+ // Built from a copy this store saved: the store already holds it.+ if !remembered(&name).contains(&id) {+ return Some(Mode::Apply);+ }+ mark_applied(&name, &id);+ }+ }+ (!incognito).then_some(Mode::Watch)+}++/// The page's address inside the extension for `mode`.+pub fn page_path(mode: Mode) -> String {+ match mode {+ Mode::Apply => format!("{PAGE}#apply"),+ _ => PAGE.to_owned(),+ }+}++pub fn folder_name(folder: &Path) -> String {+ folder+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_default()+}++fn preset_id(folder: &Path) -> Option<String> {+ let text = std::fs::read_to_string(folder.join(PRESET)).ok()?;+ let value: serde_json::Value = serde_json::from_str(&text).ok()?;+ value+ .get("id")?+ .as_str()+ .filter(|id| !id.is_empty())+ .map(str::to_owned)+}++#[derive(Debug, PartialEq, Eq)]+struct Probe {+ state: String,+ id: String,+}++fn parse(probe: &str) -> Option<Probe> {+ let mut parts = probe.split_whitespace();+ let state = parts.next()?.to_owned();+ let _version = parts.next()?;+ let id = parts.next().unwrap_or_default().to_owned();+ Some(Probe { state, id })+}++#[derive(Debug, PartialEq, Eq)]+pub enum Action {+ Nothing,+ /// Read `SNAPSHOT_SCRIPT` and pass it to `Page::save`.+ ReadSnapshot,+ /// Writing the carried copy failed: load the page again without `#apply`, so this+ /// launch still keeps a copy; the next launch tries the carried one again.+ Watch,+ /// Writing the carried copy failed in a private window, which keeps nothing: close the page.+ Close,+ /// Run `RESTART_SCRIPT`, then after `RESTART_DELAY` load the page again+ /// without `#apply`, reload the app's pages and call `Page::restarted`.+ Restart,+}++/// One extension's page as the runtime follows it.+pub struct Page {+ pub name: String,+ pub mode: Mode,+ incognito: bool,+ written: String,+}++impl Page {+ pub fn new(name: String, mode: Mode, incognito: bool) -> Self {+ Self {+ name,+ mode,+ incognito,+ written: String::new(),+ }+ }++ /// What the page's answer to `PROBE_SCRIPT` asks for.+ pub fn next(&mut self, probe: &str) -> Action {+ let Some(probe) = parse(probe) else {+ return Action::Nothing;+ };+ match self.mode {+ Mode::Apply if probe.state == "written" => {+ if !self.incognito {+ remember(&self.name, &probe.id);+ mark_applied(&self.name, &probe.id);+ }+ self.mode = Mode::Restarting;+ Action::Restart+ }+ Mode::Apply if probe.state == "failed" => {+ if self.incognito {+ self.mode = Mode::Restarting;+ Action::Close+ } else {+ self.mode = Mode::Watch;+ Action::Watch+ }+ }+ Mode::Watch+ if probe.state == "ready"+ && !self.incognito+ && !probe.id.is_empty()+ && probe.id != self.written =>+ {+ Action::ReadSnapshot+ }+ _ => Action::Nothing,+ }+ }++ pub fn restarted(&mut self) {+ self.mode = if self.incognito {+ Mode::Restarting+ } else {+ Mode::Watch+ };+ }++ /// Writes the page's copy, a JSON object with its `id`, for the builder.+ pub fn save(&mut self, snapshot: &str) {+ let Some(id) = serde_json::from_str::<serde_json::Value>(snapshot)+ .ok()+ .and_then(|value| value.get("id")?.as_str().map(str::to_owned))+ else {+ return;+ };+ let Some(store) = store() else {+ return;+ };+ match write(store, &self.name, snapshot) {+ Ok(()) => {+ remember(&self.name, &id);+ self.written = id;+ }+ Err(error) => eprintln!(+ "[Pake] Could not keep the settings of the extension {}: {error}",+ self.name+ ),+ }+ }+}++fn write(store: &Path, name: &str, snapshot: &str) -> std::io::Result<()> {+ write_whole(&store.join(format!("{name}.json")), snapshot)+}++/// Writes beside the file and moves it into place, so a cut-off write never leaves half a file.+fn write_whole(target: &Path, text: &str) -> std::io::Result<()> {+ if let Some(parent) = target.parent() {+ std::fs::create_dir_all(parent)?;+ }+ let mut partial = target.as_os_str().to_owned();+ partial.push(".partial");+ std::fs::write(&partial, text)?;+ std::fs::rename(&partial, target)+}++fn list_file(name: &str, kind: &str) -> Option<PathBuf> {+ store().map(|store| store.join(format!("{name}.{kind}")))+}++fn read_list(name: &str, kind: &str) -> Vec<String> {+ list_file(name, kind)+ .and_then(|file| std::fs::read_to_string(file).ok())+ .map(|text| text.lines().map(str::to_owned).collect())+ .unwrap_or_default()+}++fn add_to_list(name: &str, kind: &str, id: &str, keep: usize) {+ let Some(file) = list_file(name, kind) else {+ return;+ };+ let mut ids = read_list(name, kind);+ if id.is_empty() || ids.iter().any(|known| known == id) {+ return;+ }+ ids.push(id.to_owned());+ let start = ids.len().saturating_sub(keep);+ if let Err(error) = write_whole(&file, &(ids[start..].join("\n") + "\n")) {+ eprintln!("[Pake] Could not note the settings of the extension {name}: {error}");+ }+}++/// The digests of the latest copies this app's storage has held for the extension.+fn remembered(name: &str) -> Vec<String> {+ read_list(name, "ids")+}++fn remember(name: &str, id: &str) {+ add_to_list(name, "ids", id, REMEMBERED);+}++/// The carried copies this store has taken in, each once and for good: one written+/// back after the person changed things would undo what they changed.+fn applied(name: &str) -> Vec<String> {+ read_list(name, "applied")+}++fn mark_applied(name: &str, id: &str) {+ add_to_list(name, "applied", id, usize::MAX);+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::fs;++ fn setup(name: &str) -> (PathBuf, PathBuf) {+ let root = std::env::temp_dir().join(format!(+ "pake-extension-settings-{name}-{}",+ std::process::id()+ ));+ let _ = fs::remove_dir_all(&root);+ let folder = root.join("extensions").join(name);+ fs::create_dir_all(&folder).unwrap();+ // One store for the whole test binary; each test uses its own folder name. It starts+ // empty, since a later run can get the same process id.+ static FRESH: std::sync::Once = std::sync::Once::new();+ let store = std::env::temp_dir().join(format!(+ "pake-extension-settings-store-{}",+ std::process::id()+ ));+ FRESH.call_once(|| {+ let _ = fs::remove_dir_all(&store);+ });+ let _ = STORE.set(store);+ (root, folder)+ }++ #[test]+ fn an_extension_without_the_page_is_left_alone() {+ let (_root, folder) = setup("no-page");+ assert_eq!(mode(&folder, false), None);+ fs::write(folder.join(PRESET), r#"{"id":"a1","local":{}}"#).unwrap();+ assert_eq!(mode(&folder, false), None);+ }++ #[test]+ fn a_carried_copy_is_written_once_per_store() {+ let (_root, folder) = setup("carried-once");+ fs::write(folder.join(PAGE), "").unwrap();+ assert_eq!(mode(&folder, false), Some(Mode::Watch));+ fs::write(folder.join(PRESET), r#"{"id":"carried-once-1","local":{}}"#).unwrap();+ assert_eq!(mode(&folder, false), Some(Mode::Apply));++ let mut page = Page::new("carried-once".into(), Mode::Apply, false);+ assert_eq!(page.next("loading 0 "), Action::Nothing);+ assert_eq!(page.next("written 1 carried-once-1"), Action::Restart);+ page.restarted();+ assert_eq!(page.mode, Mode::Watch);+ // The next launch finds the copy already held.+ assert_eq!(mode(&folder, false), Some(Mode::Watch));+ }++ #[test]+ fn a_private_window_writes_the_copy_every_time_and_keeps_nothing() {+ let (_root, folder) = setup("private");+ fs::write(folder.join(PAGE), "").unwrap();+ assert_eq!(mode(&folder, true), None);+ fs::write(folder.join(PRESET), r#"{"id":"private-1","local":{}}"#).unwrap();+ let mut page = Page::new("private".into(), Mode::Apply, true);+ assert_eq!(page.next("written 1 private-1"), Action::Restart);+ assert_eq!(mode(&folder, true), Some(Mode::Apply));+ page.restarted();+ assert_eq!(page.next("ready 2 private-2"), Action::Nothing);+ }++ #[test]+ fn a_new_copy_is_saved_and_a_build_from_it_is_not_written_back() {+ let (_root, folder) = setup("watched");+ fs::write(folder.join(PAGE), "").unwrap();+ let mut page = Page::new("watched".into(), Mode::Watch, false);+ assert_eq!(page.next("ready 1 watched-1"), Action::ReadSnapshot);+ page.save(r#"{"id":"watched-1","local":{"site.example.com":["p"]}}"#);+ assert_eq!(page.next("ready 1 watched-1"), Action::Nothing);+ assert_eq!(page.next("ready 2 watched-2"), Action::ReadSnapshot);+ let saved = fs::read_to_string(store().unwrap().join("watched.json")).unwrap();+ assert!(saved.contains("site.example.com"));++ // An app built from the first copy, after the second, keeps the second.+ fs::write(folder.join(PRESET), r#"{"id":"watched-1","local":{}}"#).unwrap();+ assert_eq!(mode(&folder, false), Some(Mode::Watch));+ }++ #[test]+ fn a_carried_copy_is_never_written_again_however_much_changes_after() {+ let (_root, folder) = setup("many-changes");+ fs::write(folder.join(PAGE), "").unwrap();+ fs::write(folder.join(PRESET), r#"{"id":"many-1","local":{}}"#).unwrap();+ let mut page = Page::new("many-changes".into(), Mode::Apply, false);+ assert_eq!(page.next("written 1 many-1"), Action::Restart);+ page.restarted();+ for n in 0..REMEMBERED + 10 {+ let id = format!("many-change-{n}");+ assert_eq!(page.next(&format!("ready {n} {id}")), Action::ReadSnapshot);+ page.save(&format!(r#"{{"id":"{id}","local":{{}}}}"#));+ }+ assert!(!remembered("many-changes").contains(&"many-1".to_owned()));+ assert_eq!(mode(&folder, false), Some(Mode::Watch));+ }++ #[test]+ fn a_build_from_this_stores_own_copy_is_taken_as_held() {+ let (_root, folder) = setup("own-copy");+ fs::write(folder.join(PAGE), "").unwrap();+ let mut page = Page::new("own-copy".into(), Mode::Watch, false);+ assert_eq!(page.next("ready 1 own-1"), Action::ReadSnapshot);+ page.save(r#"{"id":"own-1","local":{}}"#);+ fs::write(folder.join(PRESET), r#"{"id":"own-1","local":{}}"#).unwrap();+ assert_eq!(mode(&folder, false), Some(Mode::Watch));+ // Noted for good on that launch, so later changes cannot bring it back.+ assert!(applied("own-copy").contains(&"own-1".to_owned()));+ }++ #[test]+ fn a_copy_that_cannot_be_written_still_lets_the_launch_keep_one() {+ let mut page = Page::new("refused".into(), Mode::Apply, false);+ assert_eq!(page.next("failed 0 "), Action::Watch);+ assert_eq!(page.mode, Mode::Watch);+ let mut private = Page::new("refused-private".into(), Mode::Apply, true);+ assert_eq!(private.next("failed 0 "), Action::Close);+ }++ #[test]+ fn only_the_apps_own_windows_load_again() {+ assert!(reloadable("pake"));+ assert!(reloadable("pake-2"));+ assert!(!reloadable("pake-popup-1"));+ assert!(!reloadable("extension-settings"));+ }++ #[test]+ fn a_page_that_answers_nothing_asks_for_nothing() {+ let mut page = Page::new("silent".into(), Mode::Watch, false);+ assert_eq!(page.next(""), Action::Nothing);+ assert_eq!(page.next("failed 0 "), Action::Nothing);+ }+}diff --git a/src-tauri/src/app/extensions/windows.rs b/src-tauri/src/app/extensions/windows.rsindex 3f01a46b..bfcfd5de 100644--- a/src-tauri/src/app/extensions/windows.rs+++ b/src-tauri/src/app/extensions/windows.rs@@ -3,9 +3,10 @@//! So the first window waits blank until every folder has been added, then//! opens its page.+use super::settings::{self, Action, Mode};use super::{installed, requested_settings, unpacked};use crate::app::window::MultiWindowState;-use std::cell::Cell;+use std::cell::{Cell, RefCell};use std::collections::HashMap;use std::path::PathBuf;use std::rc::Rc;@@ -14,11 +15,14 @@ use std::sync::{Arc, Mutex};use std::time::Duration;use tauri::{AppHandle, Manager, Url, WebviewWindow};use webview2_com::Microsoft::Web::WebView2::Win32::{- ICoreWebView2, ICoreWebView2BrowserExtension, ICoreWebView2Profile7, ICoreWebView2_13,+ ICoreWebView2, ICoreWebView2BrowserExtension, ICoreWebView2Controller,+ ICoreWebView2Environment10, ICoreWebView2Profile, ICoreWebView2Profile7, ICoreWebView2_13,+ ICoreWebView2_2,};use webview2_com::{- take_pwstr, BrowserExtensionRemoveCompletedHandler, ProfileAddBrowserExtensionCompletedHandler,- ProfileGetBrowserExtensionsCompletedHandler,+ take_pwstr, BrowserExtensionRemoveCompletedHandler,+ CreateCoreWebView2ControllerCompletedHandler, ExecuteScriptCompletedHandler,+ ProfileAddBrowserExtensionCompletedHandler, ProfileGetBrowserExtensionsCompletedHandler,};use windows_core::{Interface, HSTRING, PWSTR};@@ -28,6 +32,25 @@ static ADDED: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);static READY: AtomicBool = AtomicBool::new(false);static ASKED: Mutex<Option<String>> = Mutex::new(None);+/// Pake's own page of each extension whose settings an app may carry, in a+/// webview of no window of its own (settings.rs). WebView2 objects stay on the+/// thread that made them, the event loop's.+struct StorePage {+ controller: ICoreWebView2Controller,+ core: ICoreWebView2,+ /// Where the extension's pages live, `chrome-extension://<id>/`.+ base: String,+ page: settings::Page,+}++thread_local! {+ /// A slot goes empty once its page is closed; the others keep their place, which the callbacks name.+ static STORE_PAGES: RefCell<Vec<Option<StorePage>>> = const { RefCell::new(Vec::new()) };+ /// Pages asked for whose creation has not answered yet, so polling does not stop before+ /// they exist.+ static PENDING_PAGES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+}+/// A first page never waits longer than this for the extensions to be added.const READY_TIMEOUT: Duration = Duration::from_secs(5);@@ -37,6 +60,7 @@ pub fn install(window: &WebviewWindow,directory: PathBuf,target: Option<Url>,+ incognito: bool,) -> tauri::Result<()> {let opened = Arc::new(AtomicBool::new(target.is_none()));if let Some(target) = target.clone() {@@ -73,6 +97,8 @@ pub fn install(target,opened,app,+ directory: directory.clone(),+ incognito,});let profile = unsafe {core.cast::<ICoreWebView2_13>()@@ -160,6 +186,8 @@ struct Done {target: Option<Url>,opened: Arc<AtomicBool>,app: AppHandle,+ directory: PathBuf,+ incognito: bool,}impl Done {@@ -174,7 +202,258 @@ impl Done {if let Some(id) = asked {open_page(&self.app, &id);}+ start_settings(&self.app, &self.core, &self.directory, self.incognito);+ }+}++/// Opens Pake's page of every added extension that has one, out of sight, and+/// asks each one every `settings::INTERVAL` whether there is news.+fn start_settings(+ app: &AppHandle,+ core: &ICoreWebView2,+ directory: &std::path::Path,+ incognito: bool,+) {+ // The pages need a parent window, never shown in it: the app's own.+ let Some(Ok(hwnd)) = app.get_webview_window("pake").map(|window| window.hwnd()) else {+ return;+ };+ let added: HashMap<String, String> = ADDED+ .lock()+ .ok()+ .and_then(|added| added.clone())+ .unwrap_or_default();+ let wanted: Vec<(String, String, Mode)> = unpacked(directory)+ .iter()+ .filter_map(|folder| {+ let name = settings::folder_name(folder);+ let mode = settings::mode(folder, incognito)?;+ let id = added.get(&name)?.clone();+ Some((name, format!("chrome-extension://{id}/"), mode))+ })+ .collect();+ if wanted.is_empty() {+ return;+ }+ let made = (|| unsafe {+ let environment = core+ .cast::<ICoreWebView2_2>()?+ .Environment()?+ .cast::<ICoreWebView2Environment10>()?;+ let profile: ICoreWebView2Profile = core.cast::<ICoreWebView2_13>()?.Profile()?;+ let mut profile_name = PWSTR::null();+ profile.ProfileName(&mut profile_name)?;+ let mut private = windows_core::BOOL::default();+ profile.IsInPrivateModeEnabled(&mut private)?;+ let options = environment.CreateCoreWebView2ControllerOptions()?;+ options.SetProfileName(&HSTRING::from(take_pwstr(profile_name)))?;+ options.SetIsInPrivateModeEnabled(private.as_bool())?;+ PENDING_PAGES.set(wanted.len());+ for (name, base, mode) in wanted {+ let incognito_page = incognito;+ let label = name.clone();+ let asked = environment.CreateCoreWebView2ControllerWithOptions(+ hwnd,+ &options,+ &CreateCoreWebView2ControllerCompletedHandler::create(Box::new(+ move |result, controller| {+ PENDING_PAGES.set(PENDING_PAGES.get().saturating_sub(1));+ let Some(controller) = controller.filter(|_| result.is_ok()) else {+ eprintln!("[Pake] Could not open the settings page of {name}");+ stop_when_done();+ return Ok(());+ };+ let opened = (|| {+ controller.SetIsVisible(false)?;+ controller.SetBounds(Default::default())?;+ let core = controller.CoreWebView2()?;+ core.Navigate(&HSTRING::from(format!(+ "{base}{}",+ settings::page_path(mode)+ )))?;+ windows_core::Result::Ok(core)+ })();+ match opened {+ Ok(core) => {+ let page = settings::Page::new(name.clone(), mode, incognito_page);+ STORE_PAGES.with_borrow_mut(|pages| {+ pages.push(Some(StorePage {+ controller,+ core,+ base: base.clone(),+ page,+ }))+ });+ }+ Err(error) => {+ eprintln!(+ "[Pake] Could not open the settings page of {name}: {error}"+ );+ let _ = controller.Close();+ stop_when_done();+ }+ }+ Ok(())+ },+ )),+ );+ if let Err(error) = asked {+ eprintln!("[Pake] Could not open the settings page of {label}: {error}");+ PENDING_PAGES.set(PENDING_PAGES.get().saturating_sub(1));+ }+ }+ windows_core::Result::Ok(())+ })();+ if let Err(error) = made {+ eprintln!("[Pake] Could not open the extensions' settings pages: {error}");+ PENDING_PAGES.set(0);+ settings::stop_polling();+ return;+ }+ stop_when_done();+ if !settings::polling() {+ return;+ }+ let app = app.clone();+ std::thread::spawn(move || {+ while settings::polling() {+ std::thread::sleep(settings::INTERVAL);+ let poller = app.clone();+ if app+ .run_on_main_thread(move || poll_settings(&poller))+ .is_err()+ {+ return;+ }+ }+ });+}++/// Runs `script` in `core` and hands its result, as text, to `done`.+fn evaluate(core: &ICoreWebView2, script: &str, done: impl FnOnce(String) + 'static) {+ let result = unsafe {+ core.ExecuteScript(+ &HSTRING::from(script),+ &ExecuteScriptCompletedHandler::create(Box::new(move |result, json| {+ let text = match (result, serde_json::from_str::<serde_json::Value>(&json)) {+ (Ok(()), Ok(serde_json::Value::String(text))) => text,+ _ => String::new(),+ };+ done(text);+ Ok(())+ })),+ )+ };+ if let Err(error) = result {+ eprintln!("[Pake] Could not ask a settings page: {error}");+ }+}++fn poll_settings(app: &AppHandle) {+ let cores: Vec<(usize, ICoreWebView2)> = STORE_PAGES.with_borrow(|pages| {+ pages+ .iter()+ .enumerate()+ .filter_map(|(index, page)| Some((index, page.as_ref()?.core.clone())))+ .collect()+ });+ for (index, core) in cores {+ let app = app.clone();+ evaluate(&core, settings::PROBE_SCRIPT, move |answer| {+ settings_answered(&app, index, &answer)+ });+ }+}++fn settings_answered(app: &AppHandle, index: usize, answer: &str) {+ let Some((action, core)) = STORE_PAGES.with_borrow_mut(|pages| {+ let page = pages.get_mut(index)?.as_mut()?;+ Some((page.page.next(answer), page.core.clone()))+ }) else {+ return;+ };+ match action {+ Action::ReadSnapshot => evaluate(&core, settings::SNAPSHOT_SCRIPT, move |snapshot| {+ STORE_PAGES.with_borrow_mut(|pages| {+ if let Some(Some(page)) = pages.get_mut(index) {+ page.page.save(&snapshot);+ }+ });+ }),+ Action::Restart => {+ evaluate(&core, settings::RESTART_SCRIPT, |_| {});+ let app = app.clone();+ std::thread::spawn(move || {+ std::thread::sleep(settings::RESTART_DELAY);+ let _ = app.run_on_main_thread(move || settings_restarted(index));+ });+ }+ Action::Close => {+ // Taken out first: Close runs after the list is no longer borrowed.+ let closed =+ STORE_PAGES.with_borrow_mut(|pages| pages.get_mut(index).and_then(Option::take));+ if let Some(page) = closed {+ let _ = unsafe { page.controller.Close() };+ }+ stop_when_done();+ }+ Action::Watch => STORE_PAGES.with_borrow(|pages| {+ if let Some(Some(page)) = pages.get(index) {+ navigate(+ &page.core,+ &format!("{}{}", page.base, settings::page_path(Mode::Watch)),+ );+ }+ }),+ Action::Nothing => {}+ }+}++/// Stops polling once no page is left and none is still being made.+fn stop_when_done() {+ let empty = STORE_PAGES.with_borrow(|pages| pages.iter().all(Option::is_none));+ if empty && PENDING_PAGES.get() == 0 {+ settings::stop_polling();+ }+}++fn navigate(core: &ICoreWebView2, address: &str) {+ if let Err(error) = unsafe { core.Navigate(&HSTRING::from(address)) } {+ eprintln!("[Pake] Could not load a settings page: {error}");+ }+}++/// The extension has its carried settings and has restarted: Pake's page+/// loads again to follow it, and every page of the app loads again to get it.+fn settings_restarted(index: usize) {+ let closed = STORE_PAGES.with_borrow_mut(|pages| {+ let slot = pages.get_mut(index)?;+ let watching = match slot.as_mut() {+ Some(page) => {+ page.page.restarted();+ page.page.mode == Mode::Watch+ }+ None => return None,+ };+ if watching {+ if let Some(page) = slot.as_ref() {+ navigate(+ &page.core,+ &format!("{}{}", page.base, settings::page_path(Mode::Watch)),+ );+ }+ None+ } else {+ // A private window keeps nothing, so its page has nothing left to do.+ slot.take()+ }+ });+ // Closed after the list is no longer borrowed.+ if let Some(page) = closed {+ let _ = unsafe { page.controller.Close() };}+ stop_when_done();+ settings::reload_windows();}fn open(core: &ICoreWebView2, target: Option<&Url>, opened: &AtomicBool) {diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 2e764555..9ea227cb 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -1297,7 +1297,12 @@ fn build_window(#[cfg(target_os = "windows")]if let Some(directory) = &config.runtime_extensions {if label == "pake" {- crate::app::extensions::install(&window, directory.clone(), extension_target)?;+ crate::app::extensions::install(+ &window,+ directory.clone(),+ extension_target,+ window_config.incognito,+ )?;}}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 4dd9e1ca..63191177 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -487,6 +487,14 @@ pub fn run_app() {#[cfg(target_os = "linux")]app::color_scheme::keep_missing_dark_theme_dark();+ // Where the settings of the app's extensions are kept for the builder.+ #[cfg(any(target_os = "macos", target_os = "windows"))]+ if pake_config.runtime_extensions.is_some() {+ if let Ok(directory) = app.path().app_local_data_dir() {+ app::extensions::settings::set_store(app.app_handle(), directory);+ }+ }+let window = set_window(app.app_handle(), &pake_config, &tauri_config)?;// An explicit --dark-mode wins over the desktop preference.