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.
Show a newly installed extension in the Extensions popover at once (#43) (#61)
Victor Kildahl29ae3156db28
diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swiftindex e96d0bd..b01338e 100644--- a/Sources/Cra/Services/ExtensionStore.swift+++ b/Sources/Cra/Services/ExtensionStore.swift@@ -1,4 +1,5 @@import AppKit+import CraCEFimport CryptoKitimport Observation@@ -39,7 +40,10 @@ final class ExtensionStore {/// The menu bar's Extensions menu and the toolbar read this one.static let shared: ExtensionStore = {let store = ExtensionStore()- store.watchProfiles()+ // An install, switch or removal in chrome://extensions or the Web Store (main queue).+ CraCEFRuntime.setExtensionSettingsChangeHandler { [weak store] in+ MainActor.assumeIsolated { store?.reload() }+ }return store}()@@ -80,9 +84,9 @@ final class ExtensionStore {try? fm.createDirectory(at: ExtensionStore.directory, withIntermediateDirectories: true)let names = (try? fm.contentsOfDirectory(atPath: ExtensionStore.directory.path)) ?? []let root = AppPaths.chromiumCache- let profiles = Self.profileNames()- let disabled = Self.disabledIDs(profiles)- disabledByProfile = disabled+ let profiles = ((try? fm.contentsOfDirectory(atPath: root.path)) ?? []).filter { $0 == "Default" || $0.hasPrefix("Profile ") }.sorted()+ let settings = Dictionary(uniqueKeysWithValues: profiles.map { ($0, Self.extensionSettings(inProfile: $0)) })+ let disabled = settings.mapValues(ExtensionImporter.disabledIDs(settings:))let list = names.sorted().compactMap { name -> Entry? inguard var entry = Self.entry(id: name, folder: ExtensionStore.directory.appendingPathComponent(name, isDirectory: true),extensionID: nil) else { return nil }@@ -94,7 +98,7 @@ final class ExtensionStore {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))+ for e in ExtensionImporter.extensions(settings: settings[profile] ?? [:], inProfile: root.appendingPathComponent(profile, isDirectory: true))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) {@@ -117,70 +121,18 @@ final class ExtensionStore {/// 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- } }- }+ // MARK: Installed, turned on and off in chrome://extensions (GitHub #41, #43)- /// 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()- }- }+ /// A profile's extensions.settings. Chromium writes its prefs to disk ~10 s after an install+ /// or a switch, so a profile that has loaded answers from memory (and says when it changes);+ /// the files only for one no space has opened yet, where nothing can have changed.+ private static func extensionSettings(inProfile name: String) -> [String: Any] {+ let dir = AppPaths.chromiumCache.appendingPathComponent(name, isDirectory: true)+ if let json = CraCEFRuntime.extensionSettings(forProfile: name == "Default" ? nil : dir.path),+ let live = try? JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any] {+ return live}+ return ExtensionImporter.settings(inProfile: dir)}private static func entry(id: String, folder dir: URL, extensionID: String?) -> Entry? {diff --git a/Sources/Cra/Services/Import/ExtensionImporter.swift b/Sources/Cra/Services/Import/ExtensionImporter.swiftindex 3ff50a2..dbe454c 100644--- a/Sources/Cra/Services/Import/ExtensionImporter.swift+++ b/Sources/Cra/Services/Import/ExtensionImporter.swift@@ -35,9 +35,9 @@ enum ExtensionImporter {return out.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }}- /// 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] {+ /// extensions.settings by extension ID, from the profile's files. Newer Chromium keeps+ /// extension state in Secure Preferences; older in Preferences.+ static func settings(inProfile dir: URL) -> [String: Any] {var settings: [String: Any] = [:]for file in ["Preferences", "Secure Preferences"] {guard let data = try? Data(contentsOf: dir.appendingPathComponent(file)),@@ -55,12 +55,17 @@ enum ExtensionImporter {/// 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 disabledIDs(inProfile dir: URL) -> Set<String> { disabledIDs(settings: settings(inProfile: dir)) }++ static func disabledIDs(settings: [String: Any]) -> Set<String> {+ Set(settings.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+ static func extensions(inProfile dir: URL) -> [ImportableExtension] { extensions(settings: settings(inProfile: dir), inProfile: dir) }++ /// The profile's extensions.settings, from its files or (Cra's own profiles) live from Chromium.+ static func extensions(settings: [String: Any], inProfile dir: URL) -> [ImportableExtension] {+ settings.compactMap { id, value -> ImportableExtension? inguard 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)diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex 3ea60c5..e971ff4 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -393,6 +393,35 @@ static void ApplyProfilePreferences(CefRefPtr<CefRequestContext> context) {ApplyHttpsOnly(context);}+// Cra's extension list (ExtensionStore) reads extensions.settings. On disk it lags ~10 s+// behind an install (Chromium's pref writer batches), so a "Load unpacked" extension was+// missing from the Site Control Center (GitHub #43); the live pref and its changes are not.+static void (^g_extensionSettingsHandler)(void) = nil;+static bool g_extensionSettingsChangePending = false;++class ExtensionSettingsObserver : public CefPreferenceObserver {+public:+ void OnPreferenceChanged(const CefString& name) override {+ // An install changes the pref several times in a row: one reload for all of them.+ if (!g_extensionSettingsHandler || g_extensionSettingsChangePending || g_quitting) return;+ g_extensionSettingsChangePending = true;+ dispatch_async(dispatch_get_main_queue(), ^{+ g_extensionSettingsChangePending = false;+ if (g_extensionSettingsHandler) g_extensionSettingsHandler();+ });+ }+private:+ IMPLEMENT_REFCOUNTING(ExtensionSettingsObserver);+};+static std::vector<CefRefPtr<CefRegistration>> g_extensionSettingsObservers;++static void ObserveExtensionSettings(CefRefPtr<CefRequestContext> context) {+ static CefRefPtr<ExtensionSettingsObserver> observer = new ExtensionSettingsObserver();+ if (CefRefPtr<CefRegistration> r = context->AddPreferenceObserver("extensions.settings", observer)) {+ g_extensionSettingsObservers.push_back(r);+ }+}+/// Profiles other than the global Default one get the same preferences once they load,/// then create the browsers that waited for them.class ProfileContextHandler : public CefRequestContextHandler {@@ -401,6 +430,7 @@ public:void OnRequestContextInitialized(CefRefPtr<CefRequestContext> context) override {ApplyProfilePreferences(context);if (!path_) { g_incognitoReady = true; return; }+ ObserveExtensionSettings(context);if (!g_readyProfiles) g_readyProfiles = [NSMutableSet set];[g_readyProfiles addObject:path_];NSArray<CraBrowser*>* waiting = [g_waitingForProfile[path_] copy];@@ -542,6 +572,7 @@ public:void OnContextInitialized() override {CEF_REQUIRE_UI_THREAD();ApplyProfilePreferences(CefRequestContext::GetGlobalContext());+ ObserveExtensionSettings(CefRequestContext::GetGlobalContext());g_contextInitialized = true;NSArray<CraBrowser*>* pending = [g_pendingCreation copy];[g_pendingCreation removeAllObjects];@@ -2191,6 +2222,7 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {g_quitting = true;g_incognitoContext = nullptr;g_profileContexts.clear();+ g_extensionSettingsObservers.clear();g_waitingForProfile = nil;CefShutdown();}@@ -2218,6 +2250,18 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {+ (void)setBrowserDevToolsEventHandler:(void (^)(NSString*, NSString*, NSString* _Nullable))handler {g_cdpEventHandler = [handler copy];}++ (NSString*)extensionSettingsForProfile:(NSString*)profilePath {+ // Quitting: the contexts are going away, and ProfileContext would make a new one.+ if (!g_contextInitialized || g_quitting) return nil;+ if (profilePath.length && ![g_readyProfiles containsObject:profilePath]) return nil;+ CefRefPtr<CefRequestContext> context = profilePath.length ? ProfileContext(profilePath) : CefRequestContext::GetGlobalContext();+ CefRefPtr<CefValue> value = context ? context->GetPreference("extensions.settings") : nullptr;+ if (!value || value->GetType() != VTYPE_DICTIONARY) return nil;+ return NSStringFromCef(CefWriteJSON(value, JSON_WRITER_DEFAULT));+}++ (void)setExtensionSettingsChangeHandler:(void (^)(void))handler {+ g_extensionSettingsHandler = [handler copy];+}+ (void)sendBrowserDevToolsMethod:(NSString*)method params:(NSString*)paramscompletion:(void (^)(NSString* _Nullable, NSString* _Nullable))completion {[self sendBrowserDevToolsMethod:method params:params sessionID:nil completion:completion];diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.hindex a21f03b..8178385 100644--- a/Sources/CraCEF/include/CraCEF.h+++ b/Sources/CraCEF/include/CraCEF.h@@ -262,6 +262,13 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {completion:(void (^)(NSString * _Nullable result, NSString * _Nullable error))completion;/// Protocol events from the pipe: method, params JSON, and the session they belong to.+ (void)setBrowserDevToolsEventHandler:(nullable void (^)(NSString *method, NSString *params, NSString * _Nullable sessionID))handler;+/// A profile's `extensions.settings` pref as Chromium holds it now (nil profilePath is+/// Default), as JSON. Chromium writes it to Preferences ~10 s after a change. nil until+/// that profile has loaded.++ (nullable NSString *)extensionSettingsForProfile:(nullable NSString *)profilePath;+/// Called on the main queue after a loaded profile's `extensions.settings` changed: an+/// extension installed, enabled, disabled or removed.++ (void)setExtensionSettingsChangeHandler:(nullable void (^)(void))handler;@end/// NSApplication subclass CEF requires (CefAppProtocol). Set asdiff --git a/Tests/ExtensionStateTests.swift b/Tests/ExtensionStateTests.swiftindex 2861ecc..0ad9d9c 100644--- a/Tests/ExtensionStateTests.swift+++ b/Tests/ExtensionStateTests.swift@@ -36,6 +36,26 @@ enum ExtensionStateTests {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")++ // GitHub #43: Cra's own profiles pass Chromium's live extensions.settings instead of the+ // files, which lag ~10 s behind an install. The same dictionary reads the same.+ let unpacked = profile.appendingPathComponent("unpacked", isDirectory: true)+ try fm.createDirectory(at: unpacked.appendingPathComponent("_locales/en"), withIntermediateDirectories: true)+ try Data(#"{"name":"__MSG_appName__","version":"1.0","default_locale":"en"}"#.utf8).write(to: unpacked.appendingPathComponent("manifest.json"))+ try Data(#"{"appName":{"message":"Unpacked"}}"#.utf8).write(to: unpacked.appendingPathComponent("_locales/en/messages.json"))+ let live = ExtensionImporter.settings(inProfile: profile).merging([+ "fresh": ["location": 4, "disable_reasons": [], "path": unpacked.path], // just loaded unpacked+ "component": ["location": 5, "path": unpacked.path],+ "gone": ["location": 4, "path": profile.appendingPathComponent("removed").path],+ "noise": "not a dictionary",+ ]) { _, new in new }+ let fromLive = ExtensionImporter.extensions(settings: live, inProfile: profile)+ check(Set(fromLive.map(\.id)) == ["store", "fresh"], "live importable: \(fromLive.map(\.id).sorted())")+ let fresh = fromLive.first { $0.id == "fresh" }+ check(fresh?.isEnabled == true && fresh?.name == "Unpacked" && fresh?.folder.path == unpacked.path,+ "a just-loaded unpacked extension: on, localized name, its own folder")+ check(fromLive.first { $0.id == "store" }?.folder.path == store.path, "a relative path sits in the profile's Extensions")+ check(ExtensionImporter.disabledIDs(settings: live) == off, "live disabled IDs match the files'")print("ExtensionStateTests: \(checks) checks passed")}}