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: load browser extensions a runtime app carries, on macOS 15.4+ and Windows
Tw9389bbdf32f967
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 4a6dd4a7..c2a78a0d 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -53,7 +53,11 @@ objc2-foundation = { version = "0.3", features = ["NSEnumerator","NSError","NSLocale",+ "NSDate",+ "NSSet","NSString",+ "NSURL",+ "NSUUID","NSUserNotification",] }objc2-web-kit = { version = "0.3", default-features = false, features = [@@ -62,7 +66,18 @@ objc2-web-kit = { version = "0.3", default-features = false, features = ["WKContentRuleList","WKContentRuleListStore","WKUserContentController",+ "WKWebExtension",+ "WKWebExtensionContext",+ "WKWebExtensionController",+ "WKWebExtensionControllerConfiguration",+ "WKWebExtensionControllerDelegate",+ "WKWebExtensionMatchPattern",+ "WKWebExtensionPermission",+ "WKWebExtensionTab",+ "WKWebExtensionTabConfiguration",+ "WKWebExtensionWindow","WKWebViewConfiguration",+ "WKWebsiteDataStore",] }[target.'cfg(target_os = "linux")'.dependencies]diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rsindex 11013f68..a1a9f3c8 100644--- a/src-tauri/src/app/config.rs+++ b/src-tauri/src/app/config.rs@@ -144,6 +144,10 @@ pub struct PakeConfig {/// Replaces the compiled custom.js when a runtime override supplies one.#[serde(skip)]pub runtime_custom_js: Option<String>,+ /// The `extensions` folder of a runtime override when it holds an unpacked+ /// browser extension. macOS 15.4 and later and Windows load what is in it.+ #[serde(skip)]+ pub runtime_extensions: Option<std::path::PathBuf>,/// Set when a runtime override supplied the app identity, so per-app/// directories follow the identifier rather than the product name.#[serde(skip)]diff --git a/src-tauri/src/app/extensions/macos.rs b/src-tauri/src/app/extensions/macos.rsnew file mode 100644index 00000000..02b8ebd8--- /dev/null+++ b/src-tauri/src/app/extensions/macos.rs@@ -0,0 +1,698 @@+//! macOS 15.4 and later. WebKit runs unpacked WebExtensions through `WKWebExtensionController`, but+//! only for a host that looks like a browser: it asks for a window and its+//! tabs, and a content script that messages its background page fails with+//! "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::{installed, unpacked, Installed};+use block2::RcBlock;+use objc2::rc::{Allocated, Retained, Weak};+use objc2::runtime::{AnyClass, AnyObject, NSObject, NSObjectProtocol, ProtocolObject};+use objc2::{class, define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};+use objc2_foundation::{+ NSArray, NSDate, NSError, NSPoint, NSRect, NSSet, NSSize, NSString, NSURL, NSUUID,+};+use objc2_web_kit::{+ WKWebExtension, WKWebExtensionContext, WKWebExtensionContextPermissionStatus,+ WKWebExtensionController, WKWebExtensionControllerConfiguration,+ WKWebExtensionControllerDelegate, WKWebExtensionMatchPattern, WKWebExtensionPermission,+ WKWebExtensionTab, WKWebExtensionTabConfiguration, WKWebExtensionWindow,+ WKWebViewConfiguration, WKWebsiteDataStore,+};+use std::cell::RefCell;+use std::collections::HashMap;+use std::path::Path;+use std::ptr::NonNull;+use std::time::Duration;++/// Names the controller's storage inside the app's own WebKit folder, so an+/// extension's settings survive a restart. One value serves every app: the+/// folder above it already carries the app's bundle identifier.+const STORAGE_IDENTIFIER: &str = "6B1F0C52-7A0E-4C55-9E57-50414B450001";++/// A first page never waits longer than this for the extensions to load.+const READY_TIMEOUT: Duration = Duration::from_secs(3);++type Callback = Box<dyn FnOnce()>;++struct Host {+ controller: Retained<WKWebExtensionController>,+ window: Retained<HostWindow>,+ store: Retained<WKWebsiteDataStore>,+ // The controller holds its delegate weakly.+ _delegate: Retained<HostDelegate>,+ pending: usize,+ opened: bool,+ callbacks: Vec<Callback>,+ /// What is installed, and each one's context once it has loaded.+ listed: Vec<Installed>,+ contexts: HashMap<String, Retained<WKWebExtensionContext>>,+ /// The windows showing an extension's pages, kept so a second ask raises one.+ pages: HashMap<String, Retained<AnyObject>>,+}++thread_local! {+ static HOST: RefCell<Option<Host>> = const { RefCell::new(None) };+}++struct TabIvars {+ webview: Weak<AnyObject>,+ window: Weak<HostWindow>,+}++define_class!(+ // SAFETY: NSObject has no subclassing requirements and HostTab has no Drop.+ #[unsafe(super(NSObject))]+ #[thread_kind = MainThreadOnly]+ #[name = "PakeExtensionTab"]+ #[ivars = TabIvars]+ struct HostTab;++ unsafe impl NSObjectProtocol for HostTab {}++ unsafe impl WKWebExtensionTab for HostTab {+ #[unsafe(method_id(windowForWebExtensionContext:))]+ fn window(+ &self,+ _context: &WKWebExtensionContext,+ ) -> Option<Retained<ProtocolObject<dyn WKWebExtensionWindow>>> {+ self.ivars()+ .window+ .load()+ .map(ProtocolObject::from_retained)+ }++ #[unsafe(method_id(webViewForWebExtensionContext:))]+ fn web_view(&self, _context: &WKWebExtensionContext) -> Option<Retained<AnyObject>> {+ self.ivars().webview.load()+ }++ #[unsafe(method_id(urlForWebExtensionContext:))]+ fn url(&self, _context: &WKWebExtensionContext) -> Option<Retained<NSURL>> {+ self.ivars()+ .webview+ .load()+ .and_then(|webview| unsafe { msg_send![&*webview, URL] })+ }++ #[unsafe(method_id(titleForWebExtensionContext:))]+ fn title(&self, _context: &WKWebExtensionContext) -> Option<Retained<NSString>> {+ self.ivars()+ .webview+ .load()+ .and_then(|webview| unsafe { msg_send![&*webview, title] })+ }++ #[unsafe(method(isSelectedForWebExtensionContext:))]+ fn is_selected(&self, _context: &WKWebExtensionContext) -> bool {+ self.ivars()+ .window+ .load()+ .and_then(|window| window.active())+ .is_some_and(|active| std::ptr::eq(&*active, self))+ }++ #[unsafe(method(isLoadingCompleteForWebExtensionContext:))]+ fn is_loading_complete(&self, _context: &WKWebExtensionContext) -> bool {+ self.ivars().webview.load().is_some_and(|webview| {+ let loading: bool = unsafe { msg_send![&*webview, isLoading] };+ !loading+ })+ }++ #[unsafe(method(sizeForWebExtensionContext:))]+ fn size(&self, _context: &WKWebExtensionContext) -> NSSize {+ self.ivars()+ .webview+ .load()+ .map(|webview| {+ let bounds: NSRect = unsafe { msg_send![&*webview, bounds] };+ bounds.size+ })+ .unwrap_or(NSSize::new(0.0, 0.0))+ }+ }+);++impl HostTab {+ fn new(mtm: MainThreadMarker, webview: &AnyObject, window: &HostWindow) -> Retained<Self> {+ let this = Self::alloc(mtm).set_ivars(TabIvars {+ webview: Weak::new(webview),+ window: Weak::new(window),+ });+ unsafe { msg_send![super(this), init] }+ }++ fn is_alive(&self) -> bool {+ self.ivars().webview.load().is_some()+ }++ /// Whether this tab's webview sits in the key window.+ fn is_key(&self) -> bool {+ self.ivars().webview.load().is_some_and(|webview| unsafe {+ let window: *mut AnyObject = msg_send![&*webview, window];+ !window.is_null() && msg_send![window, isKeyWindow]+ })+ }+}++struct WindowIvars {+ tabs: RefCell<Vec<Retained<HostTab>>>,+}++define_class!(+ // SAFETY: NSObject has no subclassing requirements and HostWindow has no Drop.+ #[unsafe(super(NSObject))]+ #[thread_kind = MainThreadOnly]+ #[name = "PakeExtensionWindow"]+ #[ivars = WindowIvars]+ struct HostWindow;++ unsafe impl NSObjectProtocol for HostWindow {}++ unsafe impl WKWebExtensionWindow for HostWindow {+ #[unsafe(method_id(tabsForWebExtensionContext:))]+ fn tabs(+ &self,+ _context: &WKWebExtensionContext,+ ) -> Retained<NSArray<ProtocolObject<dyn WKWebExtensionTab>>> {+ let tabs: Vec<Retained<ProtocolObject<dyn WKWebExtensionTab>>> = self+ .live()+ .into_iter()+ .map(ProtocolObject::from_retained)+ .collect();+ NSArray::from_retained_slice(&tabs)+ }++ #[unsafe(method_id(activeTabForWebExtensionContext:))]+ fn active_tab(+ &self,+ _context: &WKWebExtensionContext,+ ) -> Option<Retained<ProtocolObject<dyn WKWebExtensionTab>>> {+ self.active().map(ProtocolObject::from_retained)+ }+ }+);++impl HostWindow {+ fn new(mtm: MainThreadMarker) -> Retained<Self> {+ let this = Self::alloc(mtm).set_ivars(WindowIvars {+ tabs: RefCell::new(Vec::new()),+ });+ unsafe { msg_send![super(this), init] }+ }++ fn live(&self) -> Vec<Retained<HostTab>> {+ self.ivars()+ .tabs+ .borrow()+ .iter()+ .filter(|tab| tab.is_alive())+ .cloned()+ .collect()+ }++ /// The tab in the key window, or the first one while the app is in the background.+ fn active(&self) -> Option<Retained<HostTab>> {+ let live = self.live();+ live.iter()+ .find(|tab| tab.is_key())+ .or(live.first())+ .cloned()+ }+}++struct DelegateIvars {+ window: Retained<HostWindow>,+}++define_class!(+ // SAFETY: NSObject has no subclassing requirements and HostDelegate has no Drop.+ #[unsafe(super(NSObject))]+ #[thread_kind = MainThreadOnly]+ #[name = "PakeExtensionDelegate"]+ #[ivars = DelegateIvars]+ struct HostDelegate;++ unsafe impl NSObjectProtocol for HostDelegate {}++ unsafe impl WKWebExtensionControllerDelegate for HostDelegate {+ #[unsafe(method_id(webExtensionController:openWindowsForExtensionContext:))]+ fn open_windows(+ &self,+ _controller: &WKWebExtensionController,+ _context: &WKWebExtensionContext,+ ) -> Retained<NSArray<ProtocolObject<dyn WKWebExtensionWindow>>> {+ let window = ProtocolObject::from_retained(self.ivars().window.clone());+ NSArray::from_retained_slice(&[window])+ }++ #[unsafe(method_id(webExtensionController:focusedWindowForExtensionContext:))]+ fn focused_window(+ &self,+ _controller: &WKWebExtensionController,+ _context: &WKWebExtensionContext,+ ) -> Option<Retained<ProtocolObject<dyn WKWebExtensionWindow>>> {+ Some(ProtocolObject::from_retained(self.ivars().window.clone()))+ }++ // The person chose this extension when they added it to the app, so+ // what its manifest asks for is granted without a second question.+ #[unsafe(method(webExtensionController:promptForPermissions:inTab:forExtensionContext:completionHandler:))]+ fn prompt_permissions(+ &self,+ _controller: &WKWebExtensionController,+ permissions: &NSSet<WKWebExtensionPermission>,+ _tab: Option<&ProtocolObject<dyn WKWebExtensionTab>>,+ _context: &WKWebExtensionContext,+ handler: &block2::DynBlock<+ dyn Fn(NonNull<NSSet<WKWebExtensionPermission>>, *mut NSDate),+ >,+ ) {+ handler.call((NonNull::from(permissions), std::ptr::null_mut()));+ }++ #[unsafe(method(webExtensionController:promptForPermissionToAccessURLs:inTab:forExtensionContext:completionHandler:))]+ fn prompt_urls(+ &self,+ _controller: &WKWebExtensionController,+ urls: &NSSet<NSURL>,+ _tab: Option<&ProtocolObject<dyn WKWebExtensionTab>>,+ _context: &WKWebExtensionContext,+ handler: &block2::DynBlock<dyn Fn(NonNull<NSSet<NSURL>>, *mut NSDate)>,+ ) {+ handler.call((NonNull::from(urls), std::ptr::null_mut()));+ }++ #[unsafe(method(webExtensionController:promptForPermissionMatchPatterns:inTab:forExtensionContext:completionHandler:))]+ fn prompt_patterns(+ &self,+ _controller: &WKWebExtensionController,+ patterns: &NSSet<WKWebExtensionMatchPattern>,+ _tab: Option<&ProtocolObject<dyn WKWebExtensionTab>>,+ _context: &WKWebExtensionContext,+ handler: &block2::DynBlock<+ dyn Fn(NonNull<NSSet<WKWebExtensionMatchPattern>>, *mut NSDate),+ >,+ ) {+ handler.call((NonNull::from(patterns), std::ptr::null_mut()));+ }++ // A popup's "more settings" link asks for the options page.+ #[unsafe(method(webExtensionController:openOptionsPageForExtensionContext:completionHandler:))]+ fn open_options(+ &self,+ _controller: &WKWebExtensionController,+ context: &WKWebExtensionContext,+ handler: &block2::DynBlock<dyn Fn(*mut NSError)>,+ ) {+ let id = unsafe { context.uniqueIdentifier() }.to_string();+ // Once this call has returned: WebKit may be inside a borrow of the host.+ dispatch::Queue::main().exec_async(move || show_page(&id, None));+ handler.call((std::ptr::null_mut(),));+ }++ // Several extensions open a welcome page the first time they run. The+ // app has one page, its site, so an extension gets no tab of its own.+ #[unsafe(method(webExtensionController:openNewTabUsingConfiguration:forExtensionContext:completionHandler:))]+ fn open_new_tab(+ &self,+ _controller: &WKWebExtensionController,+ _configuration: &WKWebExtensionTabConfiguration,+ _context: &WKWebExtensionContext,+ handler: &block2::DynBlock<+ dyn Fn(*mut ProtocolObject<dyn WKWebExtensionTab>, *mut NSError),+ >,+ ) {+ handler.call((std::ptr::null_mut(), std::ptr::null_mut()));+ }+ }+);++impl HostDelegate {+ fn new(mtm: MainThreadMarker, window: Retained<HostWindow>) -> Retained<Self> {+ let this = Self::alloc(mtm).set_ivars(DelegateIvars { window });+ unsafe { msg_send![super(this), init] }+ }+}++/// A webview configuration that carries the extension controller, or `None`+/// where WebKit has none (before macOS 15.4) or nothing is installed.+///+/// Wry takes the data store from a configuration it is handed and ignores its+/// own incognito switch, so the store is chosen here. It must also be the one+/// the controller was made for, or no content script is injected.+pub fn configuration(+ directory: &Path,+ incognito: bool,+) -> Option<Retained<WKWebViewConfiguration>> {+ let mtm = MainThreadMarker::new()?;+ AnyClass::get(c"WKWebExtensionController")?;+ HOST.with_borrow_mut(|host| {+ if host.is_none() {+ *host = start(mtm, directory, incognito);+ }+ let host = host.as_ref()?;+ let configuration = unsafe { WKWebViewConfiguration::new(mtm) };+ unsafe {+ configuration.setWebExtensionController(Some(&host.controller));+ configuration.setWebsiteDataStore(&host.store);+ }+ Some(configuration)+ })+}++fn start(mtm: MainThreadMarker, directory: &Path, incognito: bool) -> Option<Host> {+ let folders = unpacked(directory);+ if folders.is_empty() {+ return None;+ }+ let (settings, store) = unsafe {+ if incognito {+ (+ WKWebExtensionControllerConfiguration::nonPersistentConfiguration(mtm),+ WKWebsiteDataStore::nonPersistentDataStore(mtm),+ )+ } else {+ let identifier = NSUUID::from_string(&NSString::from_str(STORAGE_IDENTIFIER))?;+ (+ WKWebExtensionControllerConfiguration::configurationWithIdentifier(+ &identifier,+ mtm,+ ),+ WKWebsiteDataStore::defaultDataStore(mtm),+ )+ }+ };+ unsafe { settings.setDefaultWebsiteDataStore(Some(&store)) };+ let controller = unsafe {+ WKWebExtensionController::initWithConfiguration(+ WKWebExtensionController::alloc(mtm),+ &settings,+ )+ };+ let window = HostWindow::new(mtm);+ let delegate = HostDelegate::new(mtm, window.clone());+ unsafe { controller.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) };++ for folder in &folders {+ let name = folder+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_default();+ let url = NSURL::fileURLWithPath_isDirectory(+ &NSString::from_str(&folder.to_string_lossy()),+ true,+ );+ let block = RcBlock::new(move |extension: *mut WKWebExtension, error: *mut NSError| {+ let extension = unsafe { Retained::retain(extension) };+ let reason = unsafe { error.as_ref() }+ .map(|error| error.localizedDescription().to_string())+ .unwrap_or_default();+ loaded(&name, extension, &reason);+ });+ unsafe {+ WKWebExtension::extensionWithResourceBaseURL_completionHandler(&url, &block, mtm)+ };+ }++ Some(Host {+ controller,+ window,+ store,+ _delegate: delegate,+ pending: folders.len(),+ opened: false,+ callbacks: Vec::new(),+ listed: installed(directory),+ contexts: HashMap::new(),+ pages: HashMap::new(),+ })+}++fn loaded(name: &str, extension: Option<Retained<WKWebExtension>>, reason: &str) {+ let callbacks = HOST.with_borrow_mut(|host| {+ let host = host.as_mut()?;+ match extension {+ Some(extension) => match load(&host.controller, name, &extension) {+ Ok(context) => {+ host.contexts.insert(name.to_owned(), context);+ }+ Err(error) => eprintln!("[Pake] Could not load the extension {name}: {error}"),+ },+ None => eprintln!("[Pake] Could not read the extension {name}: {reason}"),+ }+ host.pending = host.pending.saturating_sub(1);+ (host.pending == 0).then(|| std::mem::take(&mut host.callbacks))+ });+ callbacks+ .into_iter()+ .flatten()+ .for_each(|callback| callback());+}++fn load(+ controller: &WKWebExtensionController,+ name: &str,+ extension: &WKWebExtension,+) -> Result<Retained<WKWebExtensionContext>, String> {+ unsafe {+ let context = WKWebExtensionContext::contextForExtension(extension);+ // Named after the folder, so the extension keeps its storage and the+ // address of its pages from one launch to the next. WebKit otherwise+ // gives the pages a new random host every time, and what a page kept+ // in localStorage or IndexedDB would be gone.+ context.setUniqueIdentifier(&NSString::from_str(name));+ if let Some(base) = NSURL::URLWithString(&NSString::from_str(&format!(+ "webkit-extension://{}/",+ page_host(name)+ ))) {+ context.setBaseURL(&base);+ }+ let granted = WKWebExtensionContextPermissionStatus::GrantedExplicitly;+ for permission in extension+ .requestedPermissions()+ .iter()+ .chain(extension.optionalPermissions().iter())+ {+ context.setPermissionStatus_forPermission(granted, &permission);+ }+ for pattern in extension+ .allRequestedMatchPatterns()+ .iter()+ .chain(extension.optionalPermissionMatchPatterns().iter())+ {+ context.setPermissionStatus_forMatchPattern(granted, &pattern);+ }+ controller+ .loadExtensionContext_error(&context)+ .map_err(|error| error.localizedDescription().to_string())?;+ Ok(context)+ }+}++/// A host name for an extension's pages: the folder name where it already is+/// one, else its bytes in hex.+fn page_host(name: &str) -> String {+ let plain = !name.is_empty()+ && name.len() <= 63+ && !name.starts_with('-')+ && !name.ends_with('-')+ && name+ .bytes()+ .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-');+ if plain {+ return name.to_owned();+ }+ let hex: String = name+ .bytes()+ .take(28)+ .map(|byte| format!("{byte:02x}"))+ .collect();+ format!("x{hex}")+}++/// Whether this macOS can run extensions at all (15.4 and later).+pub fn supported() -> bool {+ AnyClass::get(c"WKWebExtensionController").is_some()+}++/// Shows the settings page of the extension in folder `id` in a window of its+/// own: the popup a browser would hang from its toolbar, or its options page.+pub fn open_page(id: &str) {+ let page = HOST.with_borrow(|host| {+ host.as_ref()?+ .listed+ .iter()+ .find(|extension| extension.id == id)+ .and_then(|extension| extension.page.clone())+ });+ if let Some(page) = page {+ show_page(id, Some(&page));+ }+}++/// `page` is relative to the extension, or `None` for its options page.+fn show_page(id: &str, page: Option<&str>) {+ HOST.with_borrow_mut(|host| {+ let Some(host) = host.as_mut() else {+ return;+ };+ let key = format!("{id}/{}", page.unwrap_or_default());+ if let Some(window) = host.pages.get(&key) {+ // A minimized window is not visible, but it is still there.+ let (visible, minimized): (bool, bool) = unsafe {+ (+ msg_send![&**window, isVisible],+ msg_send![&**window, isMiniaturized],+ )+ };+ if visible || minimized {+ unsafe { front(window) };+ return;+ }+ }+ let Some(context) = host.contexts.get(id) else {+ eprintln!("[Pake] The extension {id} is not loaded");+ return;+ };+ let title = host+ .listed+ .iter()+ .find(|extension| extension.id == id)+ .map(|extension| extension.name.clone())+ .unwrap_or_default();+ let window = unsafe {+ let url = match page {+ Some(page) => NSURL::URLWithString_relativeToURL(+ &NSString::from_str(page),+ Some(&context.baseURL()),+ ),+ None => context.optionsPageURL(),+ };+ let (Some(url), Some(configuration)) = (url, context.webViewConfiguration()) else {+ eprintln!("[Pake] The extension {id} has no page to show");+ return;+ };+ let frame = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(420.0, 620.0));+ let webview: Allocated<AnyObject> = msg_send![class!(WKWebView), alloc];+ let webview: Retained<AnyObject> =+ msg_send![webview, initWithFrame: frame, configuration: &*configuration];+ // Titled, closable, miniaturizable, resizable; buffered backing.+ let window: Allocated<AnyObject> = msg_send![class!(NSWindow), alloc];+ let window: Retained<AnyObject> = msg_send![+ window,+ initWithContentRect: frame,+ styleMask: 15usize,+ backing: 2usize,+ defer: false+ ];+ // The map below owns it; AppKit must not free it a second time.+ let _: () = msg_send![&*window, setReleasedWhenClosed: false];+ let _: () = msg_send![&*window, setTitle: &*NSString::from_str(&title)];+ let _: () = msg_send![&*window, setContentView: &*webview];+ let _: () = msg_send![&*window, center];+ let request: Retained<AnyObject> =+ msg_send![class!(NSURLRequest), requestWithURL: &*url];+ let _: *mut AnyObject = msg_send![&*webview, loadRequest: &*request];+ front(&window);+ window+ };+ host.pages.insert(key, window);+ });+}++unsafe fn front(window: &AnyObject) {+ let _: () = msg_send![window, deminiaturize: std::ptr::null::<AnyObject>()];+ let _: () = msg_send![window, makeKeyAndOrderFront: std::ptr::null::<AnyObject>()];+}++/// Reports a webview Pake built as a tab, so extensions can find its page.+pub fn register(webview: &AnyObject) {+ let Some(mtm) = MainThreadMarker::new() else {+ return;+ };+ HOST.with_borrow_mut(|host| {+ let Some(host) = host.as_mut() else {+ return;+ };+ let ours: Option<Retained<WKWebExtensionController>> = unsafe {+ let configuration: Retained<WKWebViewConfiguration> = msg_send![webview, configuration];+ configuration.webExtensionController()+ };+ if !ours.is_some_and(|ours| std::ptr::eq(&*ours, &*host.controller)) {+ return;+ }++ let tab = HostTab::new(mtm, webview, &host.window);+ let closed: Vec<Retained<HostTab>> = {+ let mut tabs = host.window.ivars().tabs.borrow_mut();+ let (live, closed) = tabs.drain(..).partition(|tab| tab.is_alive());+ *tabs = live;+ tabs.push(tab.clone());+ closed+ };+ let window: &ProtocolObject<dyn WKWebExtensionWindow> =+ ProtocolObject::from_ref(&*host.window);+ let opened: &ProtocolObject<dyn WKWebExtensionTab> = ProtocolObject::from_ref(&*tab);+ unsafe {+ for tab in &closed {+ host.controller+ .didCloseTab_windowIsClosing(ProtocolObject::from_ref(&**tab), false);+ }+ if !host.opened {+ host.opened = true;+ host.controller.didOpenWindow(window);+ }+ host.controller.didOpenTab(opened);+ host.controller+ .didActivateTab_previousActiveTab(opened, None);+ host.controller.didFocusWindow(Some(window));+ }+ });+}++/// Runs `callback` once every extension is loaded, so the first page gets its+/// content scripts. Runs at once when there are none or they are already in.+pub fn when_ready(callback: Callback) {+ let ready = HOST.with_borrow_mut(|host| match host.as_mut() {+ Some(host) if host.pending > 0 => {+ host.callbacks.push(callback);+ None+ }+ _ => Some(callback),+ });+ if let Some(callback) = ready {+ callback();+ return;+ }+ std::thread::spawn(|| {+ std::thread::sleep(READY_TIMEOUT);+ dispatch::Queue::main().exec_async(|| {+ let late = HOST.with_borrow_mut(|host| {+ host.as_mut()+ .map(|host| std::mem::take(&mut host.callbacks))+ .unwrap_or_default()+ });+ if !late.is_empty() {+ eprintln!("[Pake] Extensions are still loading; opening the page without them");+ }+ late.into_iter().for_each(|callback| callback());+ });+ });+}++#[cfg(test)]+mod tests {+ use super::page_host;++ #[test]+ fn page_host_is_always_a_host_name() {+ assert_eq!(page_host("ublock-origin-lite"), "ublock-origin-lite");+ // Anything a URL host cannot hold is spelled in hex instead.+ assert_eq!(page_host("Dark Reader"), "x4461726b20526561646572");+ assert_eq!(page_host("-edge-"), "x2d656467652d");+ assert_eq!(page_host(""), "x");+ assert!(page_host(&"a".repeat(80)).len() <= 63);+ }+}diff --git a/src-tauri/src/app/extensions/mod.rs b/src-tauri/src/app/extensions/mod.rsnew file mode 100644index 00000000..007688cd--- /dev/null+++ b/src-tauri/src/app/extensions/mod.rs@@ -0,0 +1,195 @@+//! Browser extensions for a runtime app, on macOS 15.4 and later and on+//! Windows. Linux has none: WebKitGTK does not run WebExtensions.+//!+//! Nothing here runs unless `pake-runtime/extensions` holds an unpacked+//! extension; an app without that folder builds its webviews as before.++use std::path::{Path, PathBuf};++#[cfg(target_os = "macos")]+mod macos;+#[cfg(target_os = "macos")]+pub use macos::{configuration, open_page, register, supported, when_ready};++#[cfg(target_os = "windows")]+mod windows;+#[cfg(target_os = "windows")]+pub use windows::{install, open_page};++/// The unpacked extensions under `directory`: every folder with a manifest,+/// in name order so they load the same way each time.+pub fn unpacked(directory: &Path) -> Vec<PathBuf> {+ let Ok(entries) = std::fs::read_dir(directory) else {+ return Vec::new();+ };+ let mut folders: Vec<PathBuf> = entries+ .filter_map(|entry| entry.ok().map(|entry| entry.path()))+ .filter(|path| path.join("manifest.json").is_file())+ .collect();+ folders.sort();+ folders+}++/// What the app shows for one extension: its folder name, the name its+/// manifest gives it, and the page where its settings are.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Installed {+ pub id: String,+ pub name: String,+ pub page: Option<String>,+}++/// The argument a second launch passes to open one extension's page, as in+/// `--extension-settings=dark-reader`. Windows has no menu bar to offer them.+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]+pub const SETTINGS_ARGUMENT: &str = "--extension-settings=";++#[cfg_attr(not(target_os = "windows"), allow(dead_code))]+pub fn requested_settings(arguments: &[String]) -> Option<String> {+ arguments+ .iter()+ .find_map(|argument| argument.strip_prefix(SETTINGS_ARGUMENT))+ .filter(|id| !id.is_empty())+ .map(str::to_owned)+}++pub fn installed(directory: &Path) -> Vec<Installed> {+ unpacked(directory)+ .into_iter()+ .filter_map(|folder| {+ let id = folder.file_name()?.to_string_lossy().into_owned();+ let manifest: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(folder.join("manifest.json")).ok()?)+ .ok()?;+ let name = display_name(&folder, &manifest).unwrap_or_else(|| id.clone());+ Some(Installed {+ id,+ name,+ page: settings_page(&manifest),+ })+ })+ .collect()+}++/// The popup a browser shows from the toolbar when there is one, since that+/// is where an extension puts what people change most, else its options page.+fn settings_page(manifest: &serde_json::Value) -> Option<String> {+ [+ "/action/default_popup",+ "/browser_action/default_popup",+ "/options_ui/page",+ "/options_page",+ ]+ .iter()+ .find_map(|pointer| manifest.pointer(pointer)?.as_str())+ .map(|page| page.trim_start_matches('/').to_owned())+ .filter(|page| !page.is_empty())+}++/// A manifest names itself outright or as `__MSG_key__`, a key into the+/// messages of its default locale.+fn display_name(folder: &Path, manifest: &serde_json::Value) -> Option<String> {+ let name = manifest.get("name")?.as_str()?;+ let Some(key) = name+ .strip_prefix("__MSG_")+ .and_then(|rest| rest.strip_suffix("__"))+ else {+ return Some(name.to_owned());+ };+ let locale = manifest.get("default_locale")?.as_str()?;+ let messages: serde_json::Value = serde_json::from_str(+ &std::fs::read_to_string(folder.join("_locales").join(locale).join("messages.json"))+ .ok()?,+ )+ .ok()?;+ messages+ .as_object()?+ .iter()+ .find(|(candidate, _)| candidate.eq_ignore_ascii_case(key))+ .and_then(|(_, entry)| entry.get("message")?.as_str())+ .map(str::to_owned)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::fs;++ fn folder(name: &str) -> PathBuf {+ let directory =+ std::env::temp_dir().join(format!("pake-extensions-{name}-{}", std::process::id()));+ let _ = fs::remove_dir_all(&directory);+ fs::create_dir_all(&directory).unwrap();+ directory+ }++ #[test]+ fn lists_extensions_with_their_name_and_settings_page() {+ let directory = folder("list");+ let plain = directory.join("b-plain");+ fs::create_dir_all(&plain).unwrap();+ fs::write(+ plain.join("manifest.json"),+ r#"{"name":"Plain","options_ui":{"page":"/options.html"}}"#,+ )+ .unwrap();+ let localized = directory.join("a-localized");+ fs::create_dir_all(localized.join("_locales/en")).unwrap();+ fs::write(+ localized.join("manifest.json"),+ r#"{"name":"__MSG_extName__","default_locale":"en",+ "action":{"default_popup":"popup.html"},"options_page":"options.html"}"#,+ )+ .unwrap();+ fs::write(+ localized.join("_locales/en/messages.json"),+ r#"{"extname":{"message":"Localized"}}"#,+ )+ .unwrap();+ // No manifest: not an extension.+ fs::create_dir_all(directory.join("c-empty")).unwrap();+ // No page and a name it cannot resolve: listed under its folder name.+ let bare = directory.join("d-bare");+ fs::create_dir_all(&bare).unwrap();+ fs::write(bare.join("manifest.json"), r#"{"name":"__MSG_missing__"}"#).unwrap();++ assert_eq!(+ installed(&directory),+ vec![+ Installed {+ id: "a-localized".into(),+ name: "Localized".into(),+ page: Some("popup.html".into()),+ },+ Installed {+ id: "b-plain".into(),+ name: "Plain".into(),+ page: Some("options.html".into()),+ },+ Installed {+ id: "d-bare".into(),+ name: "d-bare".into(),+ page: None,+ },+ ]+ );+ fs::remove_dir_all(directory).unwrap();+ }++ #[test]+ fn reads_the_settings_argument() {+ let arguments = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();+ assert_eq!(+ requested_settings(&arguments(&[+ "pake.exe",+ "--extension-settings=dark-reader"+ ])),+ Some("dark-reader".into())+ );+ assert_eq!(requested_settings(&arguments(&["pake.exe"])), None);+ assert_eq!(+ requested_settings(&arguments(&["pake.exe", "--extension-settings="])),+ None+ );+ }+}diff --git a/src-tauri/src/app/extensions/windows.rs b/src-tauri/src/app/extensions/windows.rsnew file mode 100644index 00000000..3f01a46b--- /dev/null+++ b/src-tauri/src/app/extensions/windows.rs@@ -0,0 +1,285 @@+//! Windows. WebView2 keeps an unpacked extension in the app's own profile once+//! it is added, and runs its content scripts only in pages opened after that.+//! So the first window waits blank until every folder has been added, then+//! opens its page.++use super::{installed, requested_settings, unpacked};+use crate::app::window::MultiWindowState;+use std::cell::Cell;+use std::collections::HashMap;+use std::path::PathBuf;+use std::rc::Rc;+use std::sync::atomic::{AtomicBool, Ordering};+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,+};+use webview2_com::{+ take_pwstr, BrowserExtensionRemoveCompletedHandler, ProfileAddBrowserExtensionCompletedHandler,+ ProfileGetBrowserExtensionsCompletedHandler,+};+use windows_core::{Interface, HSTRING, PWSTR};++/// Folder name to the id WebView2 gave the extension, which its pages live under.+static ADDED: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);+/// Set once every extension is settled; a page asked for earlier waits in `ASKED`.+static READY: AtomicBool = AtomicBool::new(false);+static ASKED: Mutex<Option<String>> = Mutex::new(None);++/// A first page never waits longer than this for the extensions to be added.+const READY_TIMEOUT: Duration = Duration::from_secs(5);++/// Adds every extension under `directory` to the window's profile, then sends+/// the window to `target`.+pub fn install(+ window: &WebviewWindow,+ directory: PathBuf,+ target: Option<Url>,+) -> tauri::Result<()> {+ let opened = Arc::new(AtomicBool::new(target.is_none()));+ if let Some(target) = target.clone() {+ let late = window.clone();+ let opened = opened.clone();+ std::thread::spawn(move || {+ std::thread::sleep(READY_TIMEOUT);+ if !opened.swap(true, Ordering::SeqCst) {+ eprintln!("[Pake] Extensions are still loading; opening the page without them");+ if let Err(error) = late.navigate(target) {+ eprintln!("[Pake] Failed to open the page: {error}");+ }+ }+ });+ }+ // A launch that asked for an extension's page gets it once they are in.+ // A second launch may already have left its own request here.+ if let Some(id) = requested_settings(&std::env::args().collect::<Vec<_>>()) {+ if let Ok(mut asked) = ASKED.lock() {+ asked.get_or_insert(id);+ }+ }+ let app = window.app_handle().clone();+ window.with_webview(move |webview| {+ let core = match unsafe { webview.controller().CoreWebView2() } {+ Ok(core) => core,+ Err(error) => {+ eprintln!("[Pake] Failed to reach WebView2 for the extensions: {error}");+ return;+ }+ };+ let done = Rc::new(Done {+ core: core.clone(),+ target,+ opened,+ app,+ });+ let profile = unsafe {+ core.cast::<ICoreWebView2_13>()+ .and_then(|core| core.Profile())+ .and_then(|profile| profile.cast::<ICoreWebView2Profile7>())+ };+ let profile = match profile {+ Ok(profile) => profile,+ Err(error) => {+ // A WebView2 too old for extensions: the page opens without them.+ eprintln!("[Pake] This WebView2 cannot add extensions: {error}");+ done.finish(None);+ return;+ }+ };+ let folders = unpacked(&directory);+ let pending = Rc::new(Cell::new(folders.len()));+ let failed = Rc::new(Cell::new(false));+ if folders.is_empty() {+ done.finish(Some(&profile));+ return;+ }+ for folder in folders {+ let name = folder+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_default();+ // One more is settled, added or not; the last one opens the page.+ let settle = {+ let (pending, failed, done, profile) = (+ pending.clone(),+ failed.clone(),+ done.clone(),+ profile.clone(),+ );+ move |added: bool| {+ if !added {+ failed.set(true);+ }+ pending.set(pending.get().saturating_sub(1));+ if pending.get() == 0 {+ // Removing what was not added is only safe when all were.+ done.finish((!failed.get()).then_some(&profile));+ }+ }+ };+ let report = settle.clone();+ let handler_name = name.clone();+ let started = unsafe {+ profile.AddBrowserExtension(+ &HSTRING::from(folder.as_os_str()),+ &ProfileAddBrowserExtensionCompletedHandler::create(Box::new(+ move |result, extension| {+ let id = match (&result, &extension) {+ (Ok(()), Some(extension)) => identifier(extension),+ _ => None,+ };+ match (&id, ADDED.lock()) {+ (Some(id), Ok(mut added)) => {+ added+ .get_or_insert_with(HashMap::new)+ .insert(handler_name.clone(), id.clone());+ }+ _ => eprintln!(+ "[Pake] Could not add the extension {handler_name}: {result:?}"+ ),+ }+ report(id.is_some());+ Ok(())+ },+ )),+ )+ };+ if let Err(error) = started {+ eprintln!("[Pake] Could not add the extension {name}: {error}");+ settle(false);+ }+ }+ })+}++/// What happens once every extension is settled.+struct Done {+ core: ICoreWebView2,+ target: Option<Url>,+ opened: Arc<AtomicBool>,+ app: AppHandle,+}++impl Done {+ /// `cleanup` is the profile to drop removed extensions from, when that is safe.+ fn finish(&self, cleanup: Option<&ICoreWebView2Profile7>) {+ open(&self.core, self.target.as_ref(), &self.opened);+ if let Some(profile) = cleanup {+ remove_others(profile);+ }+ READY.store(true, Ordering::SeqCst);+ let asked = ASKED.lock().ok().and_then(|mut asked| asked.take());+ if let Some(id) = asked {+ open_page(&self.app, &id);+ }+ }+}++fn open(core: &ICoreWebView2, target: Option<&Url>, opened: &AtomicBool) {+ let Some(target) = target else {+ return;+ };+ if opened.swap(true, Ordering::SeqCst) {+ return;+ }+ if let Err(error) = unsafe { core.Navigate(&HSTRING::from(target.as_str())) } {+ eprintln!("[Pake] Failed to open the page: {error}");+ }+}++fn identifier(extension: &ICoreWebView2BrowserExtension) -> Option<String> {+ let mut id = PWSTR::null();+ unsafe { extension.Id(&mut id) }.ok()?;+ Some(take_pwstr(id))+}++/// The profile keeps an extension until it is removed, so one whose folder is+/// gone from the app would run on. Whatever was not just added goes.+fn remove_others(profile: &ICoreWebView2Profile7) {+ let result = unsafe {+ profile.GetBrowserExtensions(&ProfileGetBrowserExtensionsCompletedHandler::create(+ Box::new(|result, list| {+ result?;+ let Some(list) = list else {+ return Ok(());+ };+ let kept: Vec<String> = ADDED+ .lock()+ .ok()+ .and_then(|added| added.as_ref().map(|map| map.values().cloned().collect()))+ .unwrap_or_default();+ let mut count = 0;+ list.Count(&mut count)?;+ for index in 0..count {+ let extension = list.GetValueAtIndex(index)?;+ let Some(id) = identifier(&extension) else {+ continue;+ };+ if !kept.contains(&id) {+ extension.Remove(&BrowserExtensionRemoveCompletedHandler::create(+ Box::new(move |result| {+ if let Err(error) = result {+ eprintln!(+ "[Pake] Could not remove the extension {id}: {error}"+ );+ }+ Ok(())+ }),+ ))?;+ }+ }+ Ok(())+ }),+ ))+ };+ if let Err(error) = result {+ eprintln!("[Pake] Failed to list the profile's extensions: {error}");+ }+}++/// Shows the settings page of the extension in folder `id` in a window of its+/// own: the popup a browser would hang from its toolbar, or its options page.+pub fn open_page(app: &AppHandle, id: &str) {+ if !READY.load(Ordering::SeqCst) {+ if let Ok(mut asked) = ASKED.lock() {+ *asked = Some(id.to_owned());+ }+ return;+ }+ let Some(state) = app.try_state::<MultiWindowState>() else {+ return;+ };+ let Some(directory) = state.pake_config.runtime_extensions.clone() else {+ return;+ };+ let Some(extension) = installed(&directory)+ .into_iter()+ .find(|extension| extension.id == id)+ else {+ return;+ };+ let added = ADDED+ .lock()+ .ok()+ .and_then(|added| added.as_ref()?.get(id).cloned());+ let (Some(page), Some(added)) = (extension.page, added) else {+ eprintln!("[Pake] The extension {id} has no page to show");+ return;+ };+ let Ok(url) = Url::parse(&format!("chrome-extension://{added}/{page}")) else {+ return;+ };+ // Off the event loop: building a window from inside a WebView2 callback+ // or the single-instance handler would wait on the loop it is running on.+ let app = app.clone();+ std::thread::spawn(move || {+ if let Err(error) = crate::app::window::open_extension_window(&app, url, &extension.name) {+ eprintln!(+ "[Pake] Failed to open the page of {}: {error}",+ extension.name+ );+ }+ });+}diff --git a/src-tauri/src/app/menu.rs b/src-tauri/src/app/menu.rsindex 9f5eb602..8086f922 100644--- a/src-tauri/src/app/menu.rs+++ b/src-tauri/src/app/menu.rs@@ -7,10 +7,14 @@ use tauri::menu::{AboutMetadata, Menu, MenuItem, PredefinedMenuItem, Submenu};use tauri::{AppHandle, Manager, WebviewWindow, Wry};use tauri_plugin_opener::OpenerExt;+/// Menu ids of the Extensions menu start with this; the rest is the folder name.+const EXTENSION_ITEM_PREFIX: &str = "extension_settings:";+pub fn set_app_menu(app: &AppHandle<Wry>,allow_multi_window: bool,enable_find: bool,+ extensions: &[crate::app::extensions::Installed],) -> tauri::Result<()> {let pake_version = env!("CARGO_PKG_VERSION");let pake_menu_item_title = format!("Built with Pake V{}", pake_version);@@ -25,10 +29,14 @@ pub fn set_app_menu(&edit_menu(app, enable_find)?,&view_menu(app)?,&navigation_menu(app)?,- &window_submenu,- &help_menu(app, &pake_menu_item_title)?,],)?;+ // Only an app with an extension that has settings to show gets the menu.+ if extensions.iter().any(|extension| extension.page.is_some()) {+ menu.append(&extensions_menu(app, extensions)?)?;+ }+ menu.append(&window_submenu)?;+ menu.append(&help_menu(app, &pake_menu_item_title)?)?;app.set_menu(menu)?;@@ -203,6 +211,27 @@ fn navigation_menu(app: &AppHandle<Wry>) -> tauri::Result<Submenu<Wry>> {Ok(navigation_menu)}+/// One item per extension, opening the page where its settings are.+fn extensions_menu(+ app: &AppHandle<Wry>,+ extensions: &[crate::app::extensions::Installed],+) -> tauri::Result<Submenu<Wry>> {+ let menu = Submenu::new(app, "Extensions", true)?;+ for extension in extensions+ .iter()+ .filter(|extension| extension.page.is_some())+ {+ menu.append(&MenuItem::with_id(+ app,+ format!("{EXTENSION_ITEM_PREFIX}{}", extension.id),+ &extension.name,+ true,+ None::<&str>,+ )?)?;+ }+ Ok(menu)+}+fn window_menu(app: &AppHandle<Wry>) -> tauri::Result<Submenu<Wry>> {let window_menu = Submenu::new(app, "Window", true)?;window_menu.append(&PredefinedMenuItem::minimize(app, None)?)?;@@ -270,6 +299,10 @@ fn copy_text_to_pasteboard(text: &str) {}pub fn handle_menu_click(app_handle: &AppHandle, id: &str) {+ if let Some(extension) = id.strip_prefix(EXTENSION_ITEM_PREFIX) {+ crate::app::extensions::open_page(extension);+ return;+ }match id {"new_window" => {open_additional_window_safe(app_handle);diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rsindex 81a5cf20..32910506 100644--- a/src-tauri/src/app/mod.rs+++ b/src-tauri/src/app/mod.rs@@ -8,6 +8,8 @@ pub mod config;pub mod content_blocking;#[cfg(target_os = "windows")]pub mod download;+#[cfg(any(target_os = "macos", target_os = "windows"))]+pub mod extensions;pub mod invoke;#[cfg(target_os = "linux")]pub mod media_permission;diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rsindex 39f6dffd..4bd921fb 100644--- a/src-tauri/src/app/window.rs+++ b/src-tauri/src/app/window.rs@@ -575,6 +575,45 @@ pub fn toggle_all_app_windows(app: &AppHandle, init_fullscreen: bool) {}}+/// The one window that shows an extension's own page. It is built like every+/// other window of the app, since WebView2 wants the same settings for all+/// webviews that share a data folder.+#[cfg(target_os = "windows")]+pub fn open_extension_window(app: &AppHandle, url: Url, title: &str) -> tauri::Result<()> {+ const LABEL: &str = "extension-settings";+ let window = match app.get_webview_window(LABEL) {+ Some(window) => {+ window.navigate(url)?;+ window+ }+ None => {+ let state = app.state::<MultiWindowState>();+ build_window(+ app,+ &state.pake_config,+ &state.tauri_config,+ WindowBuildOptions {+ label: LABEL,+ url: WebviewUrl::External(url),+ visible: true,+ new_window_features: None,+ },+ )?+ }+ };+ // A small plain window whatever the app's own window is set to be.+ window.set_fullscreen(false)?;+ window.unmaximize()?;+ window.set_decorations(true)?;+ window.set_always_on_top(false)?;+ window.set_min_size(None::<tauri::LogicalSize<f64>>)?;+ window.set_title(title)?;+ window.set_size(tauri::LogicalSize::new(440.0, 640.0))?;+ window.unminimize()?;+ window.show()?;+ window.set_focus()+}+fn build_window_with_label(app: &AppHandle,config: &PakeConfig,@@ -741,6 +780,29 @@ fn build_window(_ => (url, None),};+ // Extensions ride on the webview's configuration, which has to exist+ // before the webview does. A page's popup takes the configuration WebKit+ // made from its opener's, controller included.+ #[cfg(target_os = "macos")]+ let extension_configuration = match (&config.runtime_extensions, &new_window_features) {+ (Some(directory), None) => {+ crate::app::extensions::configuration(directory, window_config.incognito)+ }+ _ => None,+ };+ // The main window waits blank for them too, so its first page gets their+ // content scripts. Already blank for content blocking, it leaves there.+ #[cfg(target_os = "macos")]+ let (url, extension_target) = match web_target(&url) {+ Some(target) if label == "pake" && extension_configuration.is_some() => (+ WebviewUrl::CustomProtocol(+ Url::parse("about:blank").expect("about:blank must be a valid URL"),+ ),+ Some(target),+ ),+ _ => (url, None),+ };+let user_agent = config.user_agent.get();let config_script = format!(@@ -1054,6 +1116,18 @@ fn build_window(println!("Proxy configured: {}", config.proxy_url);}+ #[cfg(target_os = "macos")]+ if let Some(configuration) = extension_configuration {+ window_builder = window_builder.with_webview_configuration(configuration);+ }++ // WebView2 keeps one setting per data folder, so every window of the app+ // turns extensions on, a page's popup included.+ #[cfg(target_os = "windows")]+ if config.runtime_extensions.is_some() {+ window_builder = window_builder.browser_extensions_enabled(true);+ }+if let Some(features) = new_window_features {#[cfg(target_os = "macos")]prepare_macos_new_window_configuration(&features)?;@@ -1186,9 +1260,24 @@ fn build_window(}}+ // The first window adds the extensions to the profile and opens its page+ // once they are in; a later window finds them there already.+ #[cfg(target_os = "windows")]+ let (download_target, extension_target) = match &config.runtime_extensions {+ Some(_) if label == "pake" => (None, download_target),+ _ => (download_target, None),+ };+#[cfg(target_os = "windows")]crate::app::download::install(&window, download_target)?;+ #[cfg(target_os = "windows")]+ if let Some(directory) = &config.runtime_extensions {+ if label == "pake" {+ crate::app::extensions::install(&window, directory.clone(), extension_target)?;+ }+ }+// Every webview is built here, so every one can be asked for the camera and microphone.#[cfg(target_os = "linux")]if let Err(error) = window.with_webview(|webview| {@@ -1215,13 +1304,39 @@ fn build_window(crate::app::content_blocking::install(&webview, groups);if let Some(target) = blocked_target {crate::app::content_blocking::when_ready(Box::new(move || {+ let open = move || {+ if let Err(error) = opener.navigate(target) {+ eprintln!("[Pake] Failed to open the page: {error}");+ }+ };+ #[cfg(target_os = "macos")]+ crate::app::extensions::when_ready(Box::new(open));+ #[cfg(not(target_os = "macos"))]+ open();+ }));+ }+ }) {+ eprintln!("[Pake] Failed to access the webview for content blocking: {error}");+ }+ }++ #[cfg(target_os = "macos")]+ if config.runtime_extensions.is_some() {+ let opener = window.clone();+ if let Err(error) = window.with_webview(move |webview| {+ // SAFETY: with_webview runs on the main thread with a live WKWebView.+ crate::app::extensions::register(unsafe {+ &*(webview.inner() as *const objc2::runtime::AnyObject)+ });+ if let Some(target) = extension_target {+ crate::app::extensions::when_ready(Box::new(move || {if let Err(error) = opener.navigate(target) {eprintln!("[Pake] Failed to open the page: {error}");}}));}}) {- eprintln!("[Pake] Failed to access the webview for content blocking: {error}");+ eprintln!("[Pake] Failed to access the webview for extensions: {error}");}}@@ -1364,6 +1479,8 @@ fn build_window(}};Queue::main().exec_async(move || {+ // Runs at once when the app has no extensions.+ let navigate = move || crate::app::extensions::when_ready(Box::new(navigate));#[cfg(feature = "content-blocking")]if wait_for_lists {crate::app::content_blocking::when_ready(Box::new(navigate));@@ -1378,9 +1495,9 @@ fn build_window(}/// The http or https page a window opens, whichever way its URL is held.-#[cfg(all(- any(target_os = "macos", target_os = "linux"),- feature = "content-blocking"+#[cfg(any(+ target_os = "macos",+ all(target_os = "linux", feature = "content-blocking")))]fn web_target(url: &WebviewUrl) -> Option<Url> {let target = match url {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex cbe5001f..acc39337 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -363,6 +363,12 @@ pub fn run_app() {let instance_revealed = startup_window_revealed.clone();app_builder = app_builder.plugin(tauri_plugin_single_instance::init(move |app, _args, _cwd| {+ // A second launch that only asks for an extension's page.+ #[cfg(target_os = "windows")]+ if let Some(id) = app::extensions::requested_settings(&_args) {+ app::extensions::open_page(app, &id);+ return;+ }if multi_window {open_additional_window_safe(app);} else if let Some(window) = app.get_webview_window("pake") {@@ -456,7 +462,14 @@ pub fn run_app() {// --- Menu Construction Start ---#[cfg(target_os = "macos")]{- app::menu::set_app_menu(app.app_handle(), multi_window, _enable_find)?;+ // No menu where WebKit cannot run them (before macOS 15.4).+ let extensions = pake_config+ .runtime_extensions+ .as_deref()+ .filter(|_| app::extensions::supported())+ .map(app::extensions::installed)+ .unwrap_or_default();+ app::menu::set_app_menu(app.app_handle(), multi_window, _enable_find, &extensions)?;// Event Handling for Custom Menu Itemapp.on_menu_event(move |app_handle, event| {diff --git a/src-tauri/src/util.rs b/src-tauri/src/util.rsindex 52a81220..22c50ace 100644--- a/src-tauri/src/util.rs+++ b/src-tauri/src/util.rs@@ -117,12 +117,27 @@ fn apply_runtime_override(.to_string_lossy().into_owned();}+ pake_config.runtime_extensions = runtime_extensions(dir);pake_config.runtime_app = true;tauri_config.identifier = app.identifier;tauri_config.product_name = Some(app.product_name);Ok((pake_config, tauri_config))}+/// `pake-runtime/extensions` when at least one folder in it has a manifest.+/// Linux has no browser extensions in WebKitGTK, so it never reports one.+fn runtime_extensions(dir: &Path) -> Option<PathBuf> {+ if cfg!(target_os = "linux") {+ return None;+ }+ let directory = dir.join("extensions");+ std::fs::read_dir(&directory)+ .ok()?+ .filter_map(Result::ok)+ .any(|entry| entry.path().join("manifest.json").is_file())+ .then_some(directory)+}+/// Same rule as the CLI's --identifier check, capped at the 128 characters an/// AppUserModelID allows.fn is_valid_identifier(id: &str) -> bool {@@ -967,6 +982,20 @@ mod tests {let (pake, _) = apply_runtime_override(pake, tauri, Some(&dir)).unwrap();assert_eq!(PathBuf::from(&pake.system_tray_path), absolute);assert!(pake.runtime_custom_js.is_none());+ // No extensions folder, or one without a manifest in it, changes nothing.+ assert!(pake.runtime_extensions.is_none());+ fs::create_dir_all(dir.join("extensions/empty")).unwrap();+ assert!(runtime_extensions(&dir).is_none());++ fs::create_dir_all(dir.join("extensions/dark-reader")).unwrap();+ fs::write(dir.join("extensions/dark-reader/manifest.json"), "{}").unwrap();+ let (pake, tauri) = compiled_configs();+ let (pake, _) = apply_runtime_override(pake, tauri, Some(&dir)).unwrap();+ if cfg!(target_os = "linux") {+ assert!(pake.runtime_extensions.is_none());+ } else {+ assert_eq!(pake.runtime_extensions, Some(dir.join("extensions")));+ }fs::remove_dir_all(dir.parent().unwrap()).unwrap();}