Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Leave extensions turned off in chrome://extensions out of Cra's toolbar (#41) (#52)

Victor Kildahlcc0c85cdacd5
diff --git a/Sources/Cra/Services/ExtensionActions.swift b/Sources/Cra/Services/ExtensionActions.swift
index 4eafc9b..0de6177 100644
--- a/Sources/Cra/Services/ExtensionActions.swift
+++ b/Sources/Cra/Services/ExtensionActions.swift
@@ -43,12 +43,17 @@ final class ExtensionActions {
/// Triggers the action; `anchor` is the top-right point (screen coordinates) the popup hangs from.
/// Returns false when the pipe or the page is unavailable (the caller falls back).
+ /// `inDefaultProfile`: the page is in the "Default" profile folder, whose extensions the
+ /// pipe can list.
@discardableResult
- func run(_ extensionID: String, on browser: CraBrowser, anchor: NSPoint) async -> Bool {
+ func run(_ extensionID: String, on browser: CraBrowser, anchor: NSPoint, inDefaultProfile: Bool) async -> Bool {
guard isAvailable else { return false }
var triggered = false
HitchMonitor.mark("extension request \(extensionID)")
do {
+ // Turned off in chrome://extensions moments ago: Chromium writes that to the
+ // profile's prefs ~10 s later, and triggerAction on it crashes Chromium (#41).
+ if inDefaultProfile, await isTurnedOff(extensionID) { throw Failure.turnedOff }
let tab = try await tabTarget(for: browser)
let before = WindowSnapshot()
placingOwnPopup = true
@@ -61,6 +66,12 @@ final class ExtensionActions {
} catch {
placingOwnPopup = false
NSLog("Cra: extension action %@ failed: %@", extensionID, String(describing: error))
+ // Off (CEF's TriggerAction patch says so too): nothing to fall back to.
+ if case Failure.turnedOff = error { ExtensionStore.shared.reload(); return true }
+ if case let Failure.protocolError(message) = error, message.contains("No enabled extension") {
+ ExtensionStore.shared.reload()
+ return true
+ }
tabTargets[ObjectIdentifier(browser)] = nil
// The action may still run after its reply timed out; a fallback page would be a
// second popup.
@@ -141,7 +152,14 @@ final class ExtensionActions {
// MARK: Targets
- private enum Failure: Error { case protocolError(String), noTabTarget }
+ private enum Failure: Error { case protocolError(String), noTabTarget, turnedOff }
+
+ /// Extensions.getExtensions lists the default profile's unpacked extensions (also the
+ /// --load-extension ones) with their live state; Web Store ones are not in it.
+ private func isTurnedOff(_ extensionID: String) async -> Bool {
+ let list = (try? await call("Extensions.getExtensions"))?["extensions"] as? [[String: Any]] ?? []
+ return list.first { $0["id"] as? String == extensionID }?["enabled"] as? Bool == false
+ }
/// The tab target that holds this browser's page: attach to each tab target and let it
/// auto-attach its page (the protocol has no direct page → tab link). Cached per browser.
diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swift
index bd1ca8b..e96d0bd 100644
--- a/Sources/Cra/Services/ExtensionStore.swift
+++ b/Sources/Cra/Services/ExtensionStore.swift
@@ -28,12 +28,20 @@ final class ExtensionStore {
/// Chromium profile folders ("Default", "Profile <id>") it is installed in; nil for the
/// --load-extension ones, which Chromium loads into every profile.
var profiles: Set<String>?
+ /// Profile folders where it is turned off in chrome://extensions. Chromium keeps it off
+ /// there across launches, also when --load-extension loads the folder again.
+ var disabledProfiles: Set<String> = []
func isInstalled(inProfile name: String) -> Bool { profiles?.contains(name) ?? true }
+ func isEnabled(inProfile name: String) -> Bool { isInstalled(inProfile: name) && !disabledProfiles.contains(name) }
}
/// The menu bar's Extensions menu and the toolbar read this one.
- static let shared = ExtensionStore()
+ static let shared: ExtensionStore = {
+ let store = ExtensionStore()
+ store.watchProfiles()
+ return store
+ }()
/// CraCEF loads the same folder (it also honours CRA_DATA_DIR).
nonisolated static var directory: URL { AppPaths.supportDir.appendingPathComponent("Extensions", isDirectory: true) }
@@ -71,22 +79,33 @@ final class ExtensionStore {
let fm = FileManager.default
try? fm.createDirectory(at: ExtensionStore.directory, withIntermediateDirectories: true)
let names = (try? fm.contentsOfDirectory(atPath: ExtensionStore.directory.path)) ?? []
- let list = names.sorted().compactMap { name in
- Self.entry(id: name, folder: ExtensionStore.directory.appendingPathComponent(name, isDirectory: true), extensionID: nil)
+ let root = AppPaths.chromiumCache
+ let profiles = Self.profileNames()
+ let disabled = Self.disabledIDs(profiles)
+ disabledByProfile = disabled
+ let list = names.sorted().compactMap { name -> Entry? in
+ guard var entry = Self.entry(id: name, folder: ExtensionStore.directory.appendingPathComponent(name, isDirectory: true),
+ extensionID: nil) else { return nil }
+ entry.disabledProfiles = Set(profiles.filter { disabled[$0]?.contains(entry.extensionID) == true })
+ return entry
}
let loaded = Set(list.map(\.extensionID))
// Each profile has its own Web Store extensions: note which profiles hold each one.
- let root = AppPaths.chromiumCache
- let profiles = ((try? fm.contentsOfDirectory(atPath: root.path)) ?? []).filter { $0 == "Default" || $0.hasPrefix("Profile ") }.sorted()
var managed: [Entry] = []
for profile in profiles {
+ // Turned-off ones stay listed (as off) so their pins come back with them.
for e in ExtensionImporter.extensions(inProfile: root.appendingPathComponent(profile, isDirectory: true))
- where e.isEnabled && !loaded.contains(e.id) {
- if let i = managed.firstIndex(where: { $0.extensionID == e.id }) { managed[i].profiles?.insert(profile); continue }
- guard var entry = Self.entry(id: e.id, folder: e.folder, extensionID: e.id) else { continue }
- entry.managedByChrome = true
- entry.profiles = [profile]
- managed.append(entry)
+ where !loaded.contains(e.id) {
+ var i = managed.firstIndex(where: { $0.extensionID == e.id })
+ if i == nil, var entry = Self.entry(id: e.id, folder: e.folder, extensionID: e.id) {
+ entry.managedByChrome = true
+ entry.profiles = []
+ managed.append(entry)
+ i = managed.count - 1
+ }
+ guard let i else { continue }
+ managed[i].profiles?.insert(profile)
+ if !e.isEnabled { managed[i].disabledProfiles.insert(profile) }
}
}
entries = list + managed.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
@@ -94,8 +113,75 @@ final class ExtensionStore {
}
/// The extensions a page in this Chromium profile folder can run; running another
- /// profile's extension there crashes Chromium.
- func entries(inProfile name: String) -> [Entry] { entries.filter { $0.isInstalled(inProfile: name) } }
+ /// profile's extension there, or one turned off there, crashes Chromium. Arc's toolbar and
+ /// Site Control Center leave turned-off extensions out (Chrome's toolbar model).
+ func entries(inProfile name: String) -> [Entry] { entries.filter { $0.isEnabled(inProfile: name) } }
+
+ // MARK: Turned on and off in chrome://extensions (GitHub #41)
+
+ /// Profile folder → extension IDs turned off there, as `reload` last read them.
+ @ObservationIgnored private var disabledByProfile: [String: Set<String>] = [:]
+ @ObservationIgnored private var profileWatchers: [String: DispatchSourceFileSystemObject] = [:]
+ @ObservationIgnored private var prefsCheckPending = false
+
+ nonisolated private static func profileNames() -> [String] {
+ ((try? FileManager.default.contentsOfDirectory(atPath: AppPaths.chromiumCache.path)) ?? [])
+ .filter { $0 == "Default" || $0.hasPrefix("Profile ") }.sorted()
+ }
+
+ nonisolated private static func disabledIDs(_ profiles: [String]) -> [String: Set<String>] {
+ Dictionary(uniqueKeysWithValues: profiles.map {
+ ($0, ExtensionImporter.disabledIDs(inProfile: AppPaths.chromiumCache.appendingPathComponent($0, isDirectory: true)))
+ })
+ }
+
+ nonisolated private static func prefsDates(_ profiles: [String]) -> [Date?] {
+ profiles.flatMap { name in ["Preferences", "Secure Preferences"].map { file in
+ let path = AppPaths.chromiumCache.appendingPathComponent(name).appendingPathComponent(file).path
+ return (try? FileManager.default.attributesOfItem(atPath: path))?[.modificationDate] as? Date
+ } }
+ }
+
+ /// Pinned buttons follow a switch in chrome://extensions once Chromium writes the profile's
+ /// prefs (about 10 s later), by renaming a new file into the profile folder. The folders
+ /// change all the time (database journals), so only new prefs files are read.
+ private func watchProfiles() {
+ let root = AppPaths.chromiumCache
+ try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ // The root too, for a space's new profile.
+ for name in [""] + Self.profileNames() where profileWatchers[name] == nil {
+ let fd = open(root.appendingPathComponent(name).path, O_EVTONLY)
+ guard fd >= 0 else { continue }
+ let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: .write, queue: .main)
+ source.setEventHandler { [weak self] in MainActor.assumeIsolated { self?.profileFolderChanged() } }
+ source.setCancelHandler { close(fd) }
+ source.resume()
+ profileWatchers[name] = source
+ }
+ }
+
+ @ObservationIgnored private var prefsDatesSeen: [Date?] = []
+
+ private func profileFolderChanged() {
+ guard !prefsCheckPending else { return }
+ prefsCheckPending = true
+ let seen = prefsDatesSeen
+ let known = disabledByProfile
+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 1) { [weak self] in
+ let profiles = Self.profileNames()
+ let dates = Self.prefsDates(profiles)
+ let changed = dates != seen && Self.disabledIDs(profiles) != known
+ DispatchQueue.main.async {
+ MainActor.assumeIsolated {
+ guard let self else { return }
+ self.prefsCheckPending = false
+ self.prefsDatesSeen = dates
+ if changed { self.reload() }
+ self.watchProfiles()
+ }
+ }
+ }
+ }
private static func entry(id: String, folder dir: URL, extensionID: String?) -> Entry? {
guard let data = try? Data(contentsOf: dir.appendingPathComponent("manifest.json")),
diff --git a/Sources/Cra/Services/Import/ExtensionImporter.swift b/Sources/Cra/Services/Import/ExtensionImporter.swift
index 08f9192..3ff50a2 100644
--- a/Sources/Cra/Services/Import/ExtensionImporter.swift
+++ b/Sources/Cra/Services/Import/ExtensionImporter.swift
@@ -35,9 +35,10 @@ enum ExtensionImporter {
return out.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
}
- static func extensions(inProfile dir: URL) -> [ImportableExtension] {
+ /// extensions.settings by extension ID. Newer Chromium keeps extension state in
+ /// Secure Preferences; older in Preferences.
+ private static func settings(inProfile dir: URL) -> [String: Any] {
var settings: [String: Any] = [:]
- // Newer Chromium keeps extension state in Secure Preferences; older in Preferences.
for file in ["Preferences", "Secure Preferences"] {
guard let data = try? Data(contentsOf: dir.appendingPathComponent(file)),
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
@@ -45,7 +46,21 @@ enum ExtensionImporter {
let s = ext["settings"] as? [String: Any] else { continue }
settings.merge(s) { _, new in new }
}
- return settings.compactMap { id, value -> ImportableExtension? in
+ return settings
+ }
+
+ private static func isDisabled(_ s: [String: Any]) -> Bool {
+ !((s["disable_reasons"] as? [Any])?.isEmpty ?? true) || (s["state"] as? Int) == 0
+ }
+
+ /// Extensions turned off in this profile (chrome://extensions), of any install location:
+ /// also the --load-extension ones (location 8), which Chromium loads disabled again.
+ static func disabledIDs(inProfile dir: URL) -> Set<String> {
+ Set(settings(inProfile: dir).compactMap { id, value in (value as? [String: Any]).flatMap { isDisabled($0) ? id : nil } })
+ }
+
+ static func extensions(inProfile dir: URL) -> [ImportableExtension] {
+ settings(inProfile: dir).compactMap { id, value -> ImportableExtension? in
guard let s = value as? [String: Any], let location = s["location"] as? Int,
importableLocations.contains(location), let path = s["path"] as? String else { return nil }
let folder = path.hasPrefix("/") ? URL(fileURLWithPath: path, isDirectory: true)
@@ -54,10 +69,9 @@ enum ExtensionImporter {
let manifest = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
// Themes and hosted apps are not extensions people pick in a toolbar.
if manifest["theme"] != nil || manifest["app"] != nil { return nil }
- let disabled = !((s["disable_reasons"] as? [Any])?.isEmpty ?? true) || (s["state"] as? Int) == 0
return ImportableExtension(id: id, name: localized(manifest["name"] as? String ?? id, manifest: manifest, folder: folder),
version: manifest["version"] as? String ?? "", folder: folder,
- isEnabled: !disabled, icon: icon(manifest: manifest, folder: folder))
+ isEnabled: !isDisabled(s), icon: icon(manifest: manifest, folder: folder))
}
}
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 1ad25f8..e704962 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -1652,8 +1652,11 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let anchor = buttonRightX.map { NSPoint(x: $0, y: urlBarBottomOnScreen() ?? bar.y) }
?? extensionPopupAnchor(id) ?? NSPoint(x: bar.cardMaxX - 8, y: bar.y)
guard let browser = currentBrowser else { openExtensionPopupPage(id, anchor: anchor); return }
+ let inDefaultProfile = profileDirectoryName == "Default"
Task {
- if await !ExtensionActions.shared.run(id, on: browser, anchor: anchor) { self.openExtensionPopupPage(id, anchor: anchor) }
+ if await !ExtensionActions.shared.run(id, on: browser, anchor: anchor, inDefaultProfile: inDefaultProfile) {
+ self.openExtensionPopupPage(id, anchor: anchor)
+ }
}
}
diff --git a/Tests/ExtensionStateTests.swift b/Tests/ExtensionStateTests.swift
new file mode 100644
index 0000000..2861ecc
--- /dev/null
+++ b/Tests/ExtensionStateTests.swift
@@ -0,0 +1,41 @@
+import Foundation
+
+/// GitHub #41: which extensions a Chromium profile has turned off (chrome://extensions).
+@main
+enum ExtensionStateTests {
+ static func main() throws {
+ let fm = FileManager.default
+ let profile = fm.temporaryDirectory.appendingPathComponent("cra-extension-state-\(UUID().uuidString)", isDirectory: true)
+ defer { try? fm.removeItem(at: profile) }
+ try fm.createDirectory(at: profile, withIntermediateDirectories: true)
+ func write(_ name: String, _ settings: [String: Any]) throws {
+ let json = try JSONSerialization.data(withJSONObject: ["extensions": ["settings": settings]])
+ try json.write(to: profile.appendingPathComponent(name))
+ }
+ // A Web Store install with a folder, so extensions(inProfile:) lists it too.
+ let store = profile.appendingPathComponent("Extensions/store/1.0", isDirectory: true)
+ try fm.createDirectory(at: store, withIntermediateDirectories: true)
+ try Data(#"{"name":"Store","version":"1.0"}"#.utf8).write(to: store.appendingPathComponent("manifest.json"))
+ try write("Preferences", [
+ "old": ["location": 1, "state": 0, "path": "/nowhere"], // older Chromium: state 0
+ ])
+ try write("Secure Preferences", [
+ "cmdoff": ["location": 8, "disable_reasons": [1], "path": "/x"], // --load-extension, turned off
+ "cmdon": ["location": 8, "disable_reasons": [], "path": "/y"],
+ "plain": ["location": 8, "path": "/z"], // no reasons at all
+ "store": ["location": 1, "disable_reasons": [1], "path": "store/1.0"],
+ ])
+ var checks = 0
+ func check(_ value: Bool, _ message: String) {
+ precondition(value, message)
+ checks += 1
+ }
+ let off = ExtensionImporter.disabledIDs(inProfile: profile)
+ check(off == ["cmdoff", "old", "store"], "disabled IDs: \(off.sorted())")
+ let listed = ExtensionImporter.extensions(inProfile: profile)
+ check(listed.map(\.id) == ["store"], "importable: \(listed.map(\.id))")
+ check(listed.first?.isEnabled == false, "the turned-off Web Store install reads as off")
+ check(ExtensionImporter.disabledIDs(inProfile: profile.appendingPathComponent("missing")).isEmpty, "no prefs, nothing off")
+ print("ExtensionStateTests: \(checks) checks passed")
+ }
+}
diff --git a/scripts/cef-patches/extension-trigger-action-null-checks.patch b/scripts/cef-patches/extension-trigger-action-null-checks.patch
new file mode 100644
index 0000000..86e7cb2
--- /dev/null
+++ b/scripts/cef-patches/extension-trigger-action-null-checks.patch
@@ -0,0 +1,30 @@
+diff --git a/chrome/browser/devtools/protocol/extensions_handler.cc b/chrome/browser/devtools/protocol/extensions_handler.cc
+index 08de746ed0..8bdbf16224 100644
+--- a/chrome/browser/devtools/protocol/extensions_handler.cc
++++ b/chrome/browser/devtools/protocol/extensions_handler.cc
+@@ -187,12 +187,25 @@ protocol::DispatchResponse ExtensionsHandler::TriggerAction(
+
+ BrowserWindowInterface* browser =
+ extensions::browser_window_util::GetBrowserForTabContents(*web_contents);
++ // Cra: answer with an error instead of crashing. A disabled or uninstalled
++ // extension has no toolbar action, and a tab need not be in a browser with
++ // an extensions container.
++ if (browser == nullptr) {
++ return protocol::Response::ServerError("Tab target has no browser.");
++ }
+
+ ExtensionsContainer* extension_container =
+ ExtensionsContainer::From(*browser);
++ if (extension_container == nullptr) {
++ return protocol::Response::ServerError("Browser has no extensions toolbar.");
++ }
+
+ ToolbarActionViewModel* extension_model =
+ extension_container->GetActionForId(extension_id);
++ if (extension_model == nullptr) {
++ return protocol::Response::ServerError(
++ "No enabled extension with the provided id.");
++ }
+
+ extension_model->ExecuteUserAction(
+ ExtensionActionViewModel::InvocationSource::kCdp);
diff --git a/scripts/test-extension-state.sh b/scripts/test-extension-state.sh
new file mode 100755
index 0000000..aa2059f
--- /dev/null
+++ b/scripts/test-extension-state.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+TEST_DIR="$(mktemp -d /tmp/cra-extension-state.XXXXXX)"
+trap 'rm -rf "$TEST_DIR"' EXIT
+xcrun swiftc -parse-as-library Sources/Cra/Services/Import/ExtensionImporter.swift \
+ Tests/ExtensionStateTests.swift -o "$TEST_DIR/extension-state-tests"
+"$TEST_DIR/extension-state-tests"