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.

Pinned extension buttons, the Site Control Center and the Extensions menu follow chrome.action.setIcon (#106) (#124)

Victor Kildahl3fb36c986522
diff --git a/Packages/CraCore/Sources/CraCore/ExtensionActionState.swift b/Packages/CraCore/Sources/CraCore/ExtensionActionState.swift
new file mode 100644
index 0000000..ab741e2
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/ExtensionActionState.swift
@@ -0,0 +1,102 @@
+import Foundation
+
+/// What an extension set on its toolbar action while running (chrome.action.setIcon, setTitle,
+/// setBadgeText), from Chromium's Extensions.actionUpdated (scripts/cef-patches/
+/// extensions-action-updates.patch, GitHub #106). Empty values are ones it did not set.
+public struct ExtensionActionState: Equatable, Sendable {
+ /// PNG bytes of the icon it set.
+ public var icon: Data?
+ public var title = ""
+ public var badgeText = ""
+ /// "#RRGGBBAA".
+ public var badgeColor = ""
+
+ public init(icon: Data? = nil, title: String = "", badgeText: String = "", badgeColor: String = "") {
+ self.icon = icon
+ self.title = title
+ self.badgeText = badgeText
+ self.badgeColor = badgeColor
+ }
+
+ public var isEmpty: Bool { icon == nil && title.isEmpty && badgeText.isEmpty && badgeColor.isEmpty }
+
+ /// Chrome's rule, value by value: what the extension set for the tab, else what it set for
+ /// every tab.
+ public func over(_ fallback: ExtensionActionState) -> ExtensionActionState {
+ ExtensionActionState(icon: icon ?? fallback.icon, title: title.isEmpty ? fallback.title : title,
+ badgeText: badgeText.isEmpty ? fallback.badgeText : badgeText,
+ badgeColor: badgeColor.isEmpty ? fallback.badgeColor : badgeColor)
+ }
+}
+
+/// One Extensions.actionUpdated event.
+public struct ExtensionActionUpdate: Equatable, Sendable {
+ public let extensionID: String
+ /// Chromium profile folder ("Default", "Profile 1").
+ public let profile: String
+ /// The page target of the tab the values are for; nil for every tab.
+ public let targetID: String?
+ public let state: ExtensionActionState
+
+ /// Icons are 16 pt (32 px at 2x); anything near this size is not one.
+ static let maxIconBytes = 256 * 1024
+ static let pngDataURLPrefix = "data:image/png;base64,"
+
+ public init(extensionID: String, profile: String, targetID: String?, state: ExtensionActionState) {
+ self.extensionID = extensionID
+ self.profile = profile
+ self.targetID = targetID
+ self.state = state
+ }
+
+ /// The event's params; nil when they are not one. An icon that is not a PNG data URL, or
+ /// too large to be an icon, counts as none.
+ public init?(params: Data) {
+ guard let p = try? JSONSerialization.jsonObject(with: params) as? [String: Any],
+ let id = p["id"] as? String, !id.isEmpty, let profile = p["profile"] as? String else { return nil }
+ let target = (p["targetId"] as? String).flatMap { $0.isEmpty ? nil : $0 }
+ var icon: Data?
+ if let url = p["icon"] as? String, url.hasPrefix(Self.pngDataURLPrefix),
+ url.utf8.count <= Self.maxIconBytes * 4 / 3 + Self.pngDataURLPrefix.utf8.count {
+ icon = Data(base64Encoded: String(url.dropFirst(Self.pngDataURLPrefix.count)))
+ }
+ self.init(extensionID: id, profile: profile, targetID: target,
+ state: ExtensionActionState(icon: icon, title: p["title"] as? String ?? "",
+ badgeText: p["badgeText"] as? String ?? "",
+ badgeColor: p["badgeColor"] as? String ?? ""))
+ }
+}
+
+/// Every reported action: each extension's values for every tab, per profile, and each Cra
+/// tab's own values.
+public struct ExtensionActionStates: Equatable, Sendable {
+ struct Key: Hashable, Sendable { let profile: String; let extensionID: String }
+ private var everyTab: [Key: ExtensionActionState] = [:]
+ /// Tab → extension ID → what was set for that tab only.
+ private var tabs: [UUID: [String: ExtensionActionState]] = [:]
+
+ public init() {}
+
+ /// `tab` is the Cra tab the update's page target belongs to (nil for an update for every tab).
+ public mutating func apply(_ update: ExtensionActionUpdate, tab: UUID?) {
+ if let tab {
+ tabs[tab, default: [:]][update.extensionID] = update.state.isEmpty ? nil : update.state
+ if tabs[tab]?.isEmpty == true { tabs[tab] = nil }
+ } else {
+ let key = Key(profile: update.profile, extensionID: update.extensionID)
+ everyTab[key] = update.state.isEmpty ? nil : update.state
+ }
+ }
+
+ /// Chromium forgets a tab's values with its page (closed or put to sleep).
+ public mutating func removeTab(_ tab: UUID) {
+ tabs[tab] = nil
+ }
+
+ /// What the extension shows on `tab` (in `profile`), or on a tab it set nothing for.
+ public func state(extensionID: String, profile: String, tab: UUID?) -> ExtensionActionState {
+ let shared = everyTab[Key(profile: profile, extensionID: extensionID)] ?? ExtensionActionState()
+ guard let own = tab.flatMap({ tabs[$0]?[extensionID] }) else { return shared }
+ return own.over(shared)
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/ExtensionActionStateTests.swift b/Packages/CraCore/Tests/CraCoreTests/ExtensionActionStateTests.swift
new file mode 100644
index 0000000..3d3beb3
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/ExtensionActionStateTests.swift
@@ -0,0 +1,118 @@
+import CraCore
+import Foundation
+import Testing
+
+struct ExtensionActionStateTests {
+ static let png = Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])
+ static let other = Data([0x89, 0x50, 0x4E, 0x47, 0, 0, 0, 1])
+
+ static func params(_ p: [String: Any]) -> Data { try! JSONSerialization.data(withJSONObject: p) }
+
+ static func update(_ id: String = "ext", profile: String = "Default", target: String? = nil,
+ icon: Data? = nil, title: String = "") -> ExtensionActionUpdate {
+ ExtensionActionUpdate(extensionID: id, profile: profile, targetID: target,
+ state: ExtensionActionState(icon: icon, title: title))
+ }
+
+ @Test func decodesTheEvent() throws {
+ let u = try #require(ExtensionActionUpdate(params: Self.params([
+ "id": "abc", "profile": "Profile 1", "targetId": "T1",
+ "icon": "data:image/png;base64," + Self.png.base64EncodedString(),
+ "title": "Omega: auto", "badgeText": "3", "badgeColor": "#FF0000FF",
+ ])))
+ #expect(u.extensionID == "abc")
+ #expect(u.profile == "Profile 1")
+ #expect(u.targetID == "T1")
+ #expect(u.state == ExtensionActionState(icon: Self.png, title: "Omega: auto", badgeText: "3", badgeColor: "#FF0000FF"))
+ }
+
+ @Test func everyTabEventHasNoTarget() throws {
+ let u = try #require(ExtensionActionUpdate(params: Self.params(["id": "abc", "profile": "Default", "icon": ""])))
+ #expect(u.targetID == nil)
+ #expect(u.state.isEmpty)
+ }
+
+ @Test(arguments: [
+ // Not PNG, or not a data URL: Chromium only sends PNG data URLs.
+ "data:image/svg+xml;base64,PHN2Zy8+",
+ "https://example.com/icon.png",
+ "data:image/png;base64,not base64!",
+ ])
+ func ignoresIconsThatAreNotPNGs(icon: String) throws {
+ let u = try #require(ExtensionActionUpdate(params: Self.params(["id": "abc", "profile": "Default", "icon": icon])))
+ #expect(u.state.icon == nil)
+ }
+
+ @Test func ignoresIconsFarLargerThanAToolbarIcon() throws {
+ let icon = "data:image/png;base64," + Data(count: 300 * 1024).base64EncodedString()
+ let u = try #require(ExtensionActionUpdate(params: Self.params(["id": "abc", "profile": "Default", "icon": icon])))
+ #expect(u.state.icon == nil)
+ }
+
+ @Test(arguments: [
+ ["profile": "Default"],
+ ["id": "", "profile": "Default"],
+ ["id": "abc"],
+ ] as [[String: String]])
+ func rejectsOtherParams(p: [String: String]) {
+ #expect(ExtensionActionUpdate(params: Self.params(p)) == nil)
+ }
+
+ @Test func nothingReportedIsEmpty() {
+ #expect(ExtensionActionStates().state(extensionID: "ext", profile: "Default", tab: UUID()).isEmpty)
+ }
+
+ @Test func everyTabValueAppliesToEachTabInItsProfile() {
+ var s = ExtensionActionStates()
+ s.apply(Self.update(icon: Self.png), tab: nil)
+ #expect(s.state(extensionID: "ext", profile: "Default", tab: UUID()).icon == Self.png)
+ #expect(s.state(extensionID: "ext", profile: "Default", tab: nil).icon == Self.png)
+ // The same extension in another profile has its own action.
+ #expect(s.state(extensionID: "ext", profile: "Profile 1", tab: nil).icon == nil)
+ #expect(s.state(extensionID: "other", profile: "Default", tab: nil).icon == nil)
+ }
+
+ @Test func aTabsOwnValueWinsValueByValue() {
+ var s = ExtensionActionStates()
+ let tab = UUID(), elsewhere = UUID()
+ s.apply(Self.update(icon: Self.png, title: "On"), tab: nil)
+ // AdGuard: setIcon({path: off}, tabId) on an allowlisted site, title untouched.
+ s.apply(Self.update(target: "T", icon: Self.other), tab: tab)
+ #expect(s.state(extensionID: "ext", profile: "Default", tab: tab) == ExtensionActionState(icon: Self.other, title: "On"))
+ #expect(s.state(extensionID: "ext", profile: "Default", tab: elsewhere).icon == Self.png)
+ // A later change for every tab shows through where the tab set nothing of its own.
+ s.apply(Self.update(icon: Self.png, title: "Paused"), tab: nil)
+ #expect(s.state(extensionID: "ext", profile: "Default", tab: tab) == ExtensionActionState(icon: Self.other, title: "Paused"))
+ }
+
+ @Test func aNavigationThatClearsTheTabFallsBack() {
+ var s = ExtensionActionStates()
+ let tab = UUID()
+ s.apply(Self.update(icon: Self.png), tab: nil)
+ s.apply(Self.update(target: "T", icon: Self.other), tab: tab)
+ s.apply(Self.update(target: "T"), tab: tab)
+ #expect(s.state(extensionID: "ext", profile: "Default", tab: tab).icon == Self.png)
+ #expect(s == {
+ var only = ExtensionActionStates()
+ only.apply(Self.update(icon: Self.png), tab: nil)
+ return only
+ }())
+ }
+
+ @Test func anEmptyEveryTabStateGoesBackToTheManifest() {
+ var s = ExtensionActionStates()
+ s.apply(Self.update(icon: Self.png), tab: nil)
+ s.apply(Self.update(), tab: nil)
+ #expect(s == ExtensionActionStates())
+ }
+
+ @Test func closedTabsAreForgotten() {
+ var s = ExtensionActionStates()
+ let open = UUID(), closed = UUID()
+ s.apply(Self.update(target: "A", icon: Self.png), tab: open)
+ s.apply(Self.update(target: "B", icon: Self.png), tab: closed)
+ s.removeTab(closed)
+ #expect(s.state(extensionID: "ext", profile: "Default", tab: open).icon == Self.png)
+ #expect(s.state(extensionID: "ext", profile: "Default", tab: closed).icon == nil)
+ }
+}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index dd9d879..418a3f8 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -85,6 +85,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
var takeRuntimeFromOtherWindow: ((UUID) -> TabRuntime?)?
/// The window's sidebar player (Arc's "now playing"), fed with this manager's pages.
var nowPlaying: NowPlaying?
+ /// A tab's page closed (the tab closed or went to sleep), with what Chromium kept for it.
+ var pageClosed: (UUID) -> Void = { _ in }
private var byBrowser: [ObjectIdentifier: UUID] = [:]
/// CEF's client holds its owner weakly; keep retired browsers alive until teardown finishes.
private var closingBrowsers: [ObjectIdentifier: CraBrowser] = [:]
@@ -351,6 +353,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
log(tabID, "closes its page")
Perf.cancel(.pageLoad, tabID.uuidString)
Perf.cancel(.tabWake, tabID.uuidString)
+ pageClosed(tabID)
rt.browser.containerView.isHidden = true
closingBrowsers[ObjectIdentifier(rt.browser)] = rt.browser
rt.browser.close()
diff --git a/Sources/Cra/Services/ExtensionActions.swift b/Sources/Cra/Services/ExtensionActions.swift
index 0de6177..cff20a4 100644
--- a/Sources/Cra/Services/ExtensionActions.swift
+++ b/Sources/Cra/Services/ExtensionActions.swift
@@ -200,6 +200,7 @@ final class ExtensionActions {
private func handleEvent(_ method: String, params: String, sessionID: String?) {
if method == "Target.targetCreated" || method == "Target.targetInfoChanged" { popupPageCreated(params); return }
+ if method == "Extensions.actionUpdated" { actionUpdated(params); return }
guard method == "Target.attachedToTarget", let sessionID, childWaiters[sessionID] != nil,
let p = try? JSONSerialization.jsonObject(with: Data(params.utf8)) as? [String: Any],
let info = p["targetInfo"] as? [String: Any], info["type"] as? String == "page" else { return }
@@ -223,6 +224,64 @@ final class ExtensionActions {
placePopup(appearingAfter: WindowSnapshot(), anchor: anchor)
}
+ // MARK: Live actions (GitHub #106)
+
+ /// Cra's live pages by tab, set by the app.
+ private var liveTabs: () -> [(tab: UUID, browser: CraBrowser)] = { [] }
+ private var watchingActions = false
+ /// Page target → Cra tab: Chromium names the tab an action change is for by its page.
+ private var tabsByPageTarget: [String: UUID] = [:]
+ /// Page targets that were no Cra page when last looked up (Chrome's own pages).
+ private var foreignPageTargets: Set<String> = []
+ private var updatesAwaitingTabs: [ExtensionActionUpdate] = []
+ private var resolvingPageTargets = false
+
+ /// Turns on Chromium's Extensions.actionUpdated (Cra's CEF patch): extensions' own icons
+ /// (chrome.action.setIcon), titles and badges, for every tab or for one, reach ExtensionStore.
+ /// Chromium first reports what each extension has set so far.
+ func watchActions(liveTabs: @escaping () -> [(tab: UUID, browser: CraBrowser)]) {
+ self.liveTabs = liveTabs
+ guard isAvailable, !watchingActions else { return }
+ watchingActions = true
+ Task { _ = try? await call("Extensions.setActionUpdatesEnabled", ["enabled": true]) }
+ }
+
+ private func actionUpdated(_ params: String) {
+ guard let update = ExtensionActionUpdate(params: Data(params.utf8)) else { return }
+ guard let target = update.targetID else { return ExtensionStore.shared.applyActionUpdate(update, tab: nil) }
+ if let tab = tabsByPageTarget[target] { return ExtensionStore.shared.applyActionUpdate(update, tab: tab) }
+ guard !foreignPageTargets.contains(target) else { return }
+ updatesAwaitingTabs.append(update)
+ resolvePageTargets()
+ }
+
+ /// Asks each live page for its target, then applies the updates that waited for one, in order.
+ private func resolvePageTargets() {
+ guard !resolvingPageTargets else { return }
+ resolvingPageTargets = true
+ Task {
+ var map: [String: UUID] = [:]
+ for (tab, browser) in liveTabs() {
+ guard let info = try? await pageCall(browser, "Target.getTargetInfo"),
+ let target = (info["targetInfo"] as? [String: Any])?["targetId"] as? String else { continue }
+ map[target] = tab
+ }
+ tabsByPageTarget = map
+ resolvingPageTargets = false
+ let waiting = updatesAwaitingTabs
+ updatesAwaitingTabs = []
+ foreignPageTargets = []
+ for update in waiting {
+ guard let target = update.targetID else { continue }
+ if let tab = map[target] {
+ ExtensionStore.shared.applyActionUpdate(update, tab: tab)
+ } else {
+ foreignPageTargets.insert(target)
+ }
+ }
+ }
+ }
+
// MARK: Protocol calls
// Chromium can leave a request unanswered (its target went away meanwhile). Without a
diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swift
index ae6e17a..dd6a89b 100644
--- a/Sources/Cra/Services/ExtensionStore.swift
+++ b/Sources/Cra/Services/ExtensionStore.swift
@@ -17,7 +17,8 @@ final class ExtensionStore {
let url: URL
/// Chromium's extension ID (from the manifest key, else the folder path).
var extensionID: String = ""
- /// Manifest icon for menus (16 px preferred).
+ /// The action's manifest icon (16 px preferred): its default_icon, else the extension's
+ /// icons, as Chrome's toolbar picks it.
var icon: NSImage?
/// action / browser_action / page_action default_popup, relative to the folder.
var popupPath: String?
@@ -164,9 +165,12 @@ final class ExtensionStore {
if title.hasPrefix("__MSG_") { title = id }
let action = (m["action"] ?? m["browser_action"] ?? m["page_action"]) as? [String: Any]
let options = (m["options_ui"] as? [String: Any])?["page"] as? String ?? m["options_page"] as? String
+ // A path or {size: path} (React DevTools' grey "disabled" icon until a page uses React).
+ let actionIcons = action?["default_icon"] as? [String: String] ?? (action?["default_icon"] as? String).map { ["16": $0] }
return Entry(id: id, name: title.isEmpty ? id : title, version: str("version"), description: str("description"), url: dir,
extensionID: extensionID ?? chromiumID(key: m["key"] as? String, folder: dir),
- icon: ExtensionImporter.icon(manifest: m, folder: dir, minPixels: 16),
+ icon: actionIcons.flatMap { ExtensionImporter.icon(manifest: ["icons": $0], folder: dir, minPixels: 16) }
+ ?? ExtensionImporter.icon(manifest: m, folder: dir, minPixels: 16),
popupPath: (action?["default_popup"] as? String).flatMap { $0.isEmpty ? nil : $0 }, optionsPath: options)
}
@@ -245,8 +249,9 @@ final class ExtensionStore {
guard let data = try? Data(contentsOf: ExtensionStore.iconStylesFile) else { return [:] }
return (try? JSONDecoder().decode([String: IconStyle].self, from: data)) ?? [:]
}()
- /// One image per extension, so the toolbar sees the same object until the style changes.
- @ObservationIgnored private var toolbarIcons: [String: NSImage] = [:]
+ /// One image per extension, so the toolbar sees the same object until the style or the
+ /// image it was made from changes.
+ @ObservationIgnored private var toolbarIcons: [String: (base: NSImage?, image: NSImage?)] = [:]
func iconStyle(_ id: String) -> IconStyle { iconStyles[id] ?? IconStyle() }
@@ -277,12 +282,16 @@ final class ExtensionStore {
setIconStyle(id, style)
}
- /// The pinned button's image: the extension's icon, the user's replacement, or either as a
- /// template image (the button tints templates with the toolbar's ink).
- func toolbarIcon(for e: Entry) -> NSImage? {
+ /// The pinned button's image: the extension's icon as it is now on `tab`, the user's
+ /// replacement, or either as a template image (the button tints templates with the toolbar's
+ /// ink). A monochrome icon follows the extension's own changes.
+ func toolbarIcon(for e: Entry, profile: String, tab: UUID?) -> NSImage? {
+ // Read before the early return, so every caller's observation sees the extension's changes.
+ let live = liveIcon(for: e, profile: profile, tab: tab)
let style = iconStyle(e.extensionID)
- if style == IconStyle() { return e.icon }
- if let cached = toolbarIcons[e.extensionID] { return cached }
+ if style == IconStyle() { return live }
+ let set = live === e.icon ? nil : live
+ if let cached = toolbarIcons[e.extensionID], cached.base === set { return cached.image }
var image: NSImage?
if let symbol = style.symbol {
image = NSImage(systemSymbolName: symbol, accessibilityDescription: e.name)?
@@ -290,18 +299,54 @@ final class ExtensionStore {
image?.isTemplate = true
} else {
if let file = style.imageFile {
- image = NSImage(contentsOf: Self.customIconsDir.appendingPathComponent(file)) ?? e.icon
- } else if style.monochrome {
+ image = NSImage(contentsOf: Self.customIconsDir.appendingPathComponent(file)) ?? live
+ } else if style.monochrome, set == nil {
// From the largest icon: in the 16 px one a plate's edge and the mark blur together.
let manifest = (try? Data(contentsOf: e.url.appendingPathComponent("manifest.json")))
.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }
image = manifest.flatMap { ExtensionImporter.icon(manifest: $0, folder: e.url, minPixels: 128) } ?? e.icon
} else {
- image = e.icon
+ image = live
}
if style.monochrome { image = image.flatMap(Self.monochrome) }
}
- toolbarIcons[e.extensionID] = image
+ toolbarIcons[e.extensionID] = (set, image)
+ return image
+ }
+
+ // MARK: Live actions (GitHub #106: chrome.action.setIcon, setTitle)
+
+ /// What extensions set on their toolbar actions while running, from Chromium
+ /// (ExtensionActions forwards Extensions.actionUpdated).
+ private(set) var actions = ExtensionActionStates()
+ /// Decoded icons by their PNG bytes, so a redraw sees the same image until the icon changes.
+ @ObservationIgnored private var actionIcons: [Data: NSImage] = [:]
+
+ func applyActionUpdate(_ update: ExtensionActionUpdate, tab: UUID?) {
+ var next = actions
+ next.apply(update, tab: tab)
+ guard next != actions else { return }
+ actions = next
+ }
+
+ /// Drops the values extensions set for a tab whose page is gone (closed or asleep).
+ func forgetActionTab(_ tab: UUID) {
+ var next = actions
+ next.removeTab(tab)
+ guard next != actions else { return }
+ actions = next
+ }
+
+ /// The icon the extension shows on `tab` (any tab when nil): the one it set there, else
+ /// the one it set for every tab, else its manifest's.
+ func liveIcon(for e: Entry, profile: String, tab: UUID?) -> NSImage? {
+ guard let png = actions.state(extensionID: e.extensionID, profile: profile, tab: tab).icon else { return e.icon }
+ if let image = actionIcons[png] { return image }
+ guard let image = NSImage(data: png), image.size.width > 0 else { return e.icon }
+ // Action icons are 16 pt; Chromium sends the largest scale it has (32 px on Retina).
+ image.size = NSSize(width: 16, height: 16 * image.size.height / image.size.width)
+ if actionIcons.count > 64 { actionIcons.removeAll() }
+ actionIcons[png] = image
return image
}
diff --git a/Sources/Cra/UI/ExtensionsMenu.swift b/Sources/Cra/UI/ExtensionsMenu.swift
index 2fa7e96..e5c5b67 100644
--- a/Sources/Cra/UI/ExtensionsMenu.swift
+++ b/Sources/Cra/UI/ExtensionsMenu.swift
@@ -22,11 +22,13 @@ final class ExtensionsMenu: NSObject, NSMenuDelegate, NSMenuItemValidation {
let store = ExtensionStore.shared
store.reload()
let entries = app.main.extensionEntries.sorted { $0.name < $1.name }
+ // Each extension's icon as it is now on the focused page (chrome.action.setIcon).
+ let profile = app.main.profileDirectoryName, tab = app.main.selectedTabID
for e in entries {
let item = NSMenuItem(title: e.name, action: #selector(runExtension(_:)), keyEquivalent: "")
item.target = self
item.representedObject = e.extensionID
- item.image = Self.menuIcon(e.icon)
+ item.image = Self.menuIcon(store.liveIcon(for: e, profile: profile, tab: tab))
menu.addItem(item)
}
if !entries.isEmpty { menu.addItem(.separator()) }
@@ -46,7 +48,7 @@ final class ExtensionsMenu: NSObject, NSMenuDelegate, NSMenuItemValidation {
let item = NSMenuItem(title: e.name, action: #selector(togglePin(_:)), keyEquivalent: "")
item.target = self
item.representedObject = e.extensionID
- item.image = Self.menuIcon(e.icon)
+ item.image = Self.menuIcon(store.liveIcon(for: e, profile: profile, tab: tab))
item.state = store.isPinned(e.extensionID) ? .on : .off
pinMenu.addItem(item)
}
@@ -58,7 +60,7 @@ final class ExtensionsMenu: NSObject, NSMenuDelegate, NSMenuItemValidation {
let iconsMenu = NSMenu(title: "Toolbar Icons")
for e in entries {
let item = NSMenuItem(title: e.name, action: nil, keyEquivalent: "")
- item.image = Self.menuIcon(store.toolbarIcon(for: e))
+ item.image = Self.menuIcon(store.toolbarIcon(for: e, profile: profile, tab: tab))
item.submenu = Self.iconMenu(for: e)
iconsMenu.addItem(item)
}
diff --git a/Sources/Cra/UI/PaneToolbarView.swift b/Sources/Cra/UI/PaneToolbarView.swift
index 2a68e7b..fc09f6c 100644
--- a/Sources/Cra/UI/PaneToolbarView.swift
+++ b/Sources/Cra/UI/PaneToolbarView.swift
@@ -144,11 +144,14 @@ final class PaneToolbarView: NSView {
m.path = store.settings.toolbarShowsFullURL && human.hasPrefix(m.host) ? String(human.dropFirst(m.host.count)) : ""
}
let extensions = ExtensionStore.shared
- let entries = extensions.entries(inProfile: item.map { store.profileDirectoryName(item: $0.id) }
- ?? store.profileDirectoryName(space: store.focusedSpaceID(window: ui.windowID)))
+ let profile = item.map { store.profileDirectoryName(item: $0.id) }
+ ?? store.profileDirectoryName(space: store.focusedSpaceID(window: ui.windowID))
+ let entries = extensions.entries(inProfile: profile)
m.hasExtensions = !entries.isEmpty
m.pinned = extensions.pinnedIDs.compactMap { id in
- entries.first { $0.extensionID == id }.map { Model.Ext(id: id, name: $0.name, icon: extensions.toolbarIcon(for: $0)) }
+ entries.first { $0.extensionID == id }.map {
+ Model.Ext(id: id, name: $0.name, icon: extensions.toolbarIcon(for: $0, profile: profile, tab: m.tabID))
+ }
}
// Arc's toolbar colour (ToolbarColor): the page's report, else the tab's last colour, else
// white (MainWindowController.toolbarColors uses the same rule for the card behind the bar).
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarView.swift b/Sources/Cra/UI/Sidebar/List/SidebarView.swift
index 39b83ae..bbecf91 100644
--- a/Sources/Cra/UI/Sidebar/List/SidebarView.swift
+++ b/Sources/Cra/UI/Sidebar/List/SidebarView.swift
@@ -338,9 +338,12 @@ final class SidebarTopBarView: NSView {
let host = URL(string: url)?.host ?? ""
let text = tab == nil ? "Search or Enter URL…" : (host.isEmpty ? SuggestionEngine.humanURL(url) : host.replacingOccurrences(of: "www.", with: ""))
let ext = ExtensionStore.shared
- let entries = ext.entries(inProfile: tab.map { store.profileDirectoryName(item: $0.id) }
- ?? store.profileDirectoryName(space: store.focusedSpaceID(window: ui.windowID)))
- let pinned = ext.pinnedIDs.compactMap { id in entries.first { $0.extensionID == id }.map { (id, $0.name, ext.toolbarIcon(for: $0)) } }
+ let profile = tab.map { store.profileDirectoryName(item: $0.id) }
+ ?? store.profileDirectoryName(space: store.focusedSpaceID(window: ui.windowID))
+ let entries = ext.entries(inProfile: profile)
+ let pinned = ext.pinnedIDs.compactMap { id in
+ entries.first { $0.extensionID == id }.map { (id, $0.name, ext.toolbarIcon(for: $0, profile: profile, tab: tab?.id)) }
+ }
pill.show(text: text, url: url, hasTab: tab != nil, colors: colors, active: active,
pinned: pinned, hasExtensions: !entries.isEmpty)
}
diff --git a/Sources/Cra/UI/SiteControlCenter.swift b/Sources/Cra/UI/SiteControlCenter.swift
index efcb58b..88f91a0 100644
--- a/Sources/Cra/UI/SiteControlCenter.swift
+++ b/Sources/Cra/UI/SiteControlCenter.swift
@@ -43,12 +43,17 @@ final class SiteControlCenterView: NSView {
private let store: SidebarStore
/// The page's Chromium profile folder: only its extensions are offered.
private let profile: String
+ /// The page's tab, whose extension icons the tiles show.
+ private let tab: UUID?
private var extensions: ExtensionStore { .shared }
+ /// The tiles by extension ID, whose icons follow the extensions' own changes in place.
+ private var extensionTiles: [String: SiteExtensionTile] = [:]
- init(url: String, secure: Bool, dark: Bool, profile: String, actions: SiteControlCenterActions, store: SidebarStore) {
+ init(url: String, secure: Bool, dark: Bool, profile: String, tab: UUID?, actions: SiteControlCenterActions, store: SidebarStore) {
self.url = url
self.secure = secure
self.profile = profile
+ self.tab = tab
colors = SiteControlCenterColors(dark: dark)
self.actions = actions
self.store = store
@@ -56,6 +61,11 @@ final class SiteControlCenterView: NSView {
wantsLayer = true
layer?.backgroundColor = colors.background.cgColor
observe()
+ // An extension changing its icon redraws only its tile, so the one under the pointer
+ // keeps its hover. Ends with the view: then nothing observable is read.
+ observeChanges(of: { [weak self] in self?.liveIcons() ?? [:] }) { [weak self] icons in
+ for (id, icon) in icons { self?.extensionTiles[id]?.show(icon: icon) }
+ }
}
required init?(coder: NSCoder) { fatalError() }
@@ -84,6 +94,11 @@ final class SiteControlCenterView: NSView {
build()
}
+ /// The tiles' icons as the extensions set them now (chrome.action.setIcon).
+ private func liveIcons() -> [String: NSImage?] {
+ Dictionary(uniqueKeysWithValues: orderedExtensions.map { ($0.extensionID, extensions.liveIcon(for: $0, profile: profile, tab: tab)) })
+ }
+
private func build() {
subviews.forEach { $0.removeFromSuperview() }
let x = M.inset, w = M.width - 2 * M.inset
@@ -101,10 +116,14 @@ final class SiteControlCenterView: NSView {
y += M.tile.height + 11
// Extensions: a 4-column grid of tiles, then "+".
let ext = SiteSectionView(title: "Extensions", hoverText: "Manage", colors: colors, onHeaderClick: actions.manageExtensions)
+ extensionTiles = [:]
var tiles: [NSView] = orderedExtensions.map { e in
- SiteExtensionTile(entry: e, pinned: extensions.isPinned(e.extensionID), colors: colors,
- run: { [actions] in actions.runExtension(e.extensionID) },
- togglePin: { ExtensionStore.shared.setPinned(e.extensionID, !ExtensionStore.shared.isPinned(e.extensionID)) })
+ let tile = SiteExtensionTile(entry: e, pinned: extensions.isPinned(e.extensionID), colors: colors,
+ run: { [actions] in actions.runExtension(e.extensionID) },
+ togglePin: { ExtensionStore.shared.setPinned(e.extensionID, !ExtensionStore.shared.isPinned(e.extensionID)) })
+ tile.show(icon: extensions.liveIcon(for: e, profile: profile, tab: tab))
+ extensionTiles[e.extensionID] = tile
+ return tile
}
let add = SiteTile(colors: colors, help: "Add Extension", action: actions.addExtension)
add.setGlyph(SidebarSymbols.image("plus", size: 14, weight: .medium), tint: colors.text)
@@ -306,6 +325,7 @@ private class SiteTile: SiteHoverView {
/// SiteControlCenterExtensionPinButton, "Pin" / "Unpin").
private final class SiteExtensionTile: SiteTile {
private let pinned: Bool
+ private var shownIcon: NSImage??
/// The 14 pt pin badge hangs off the tile's bottom-right corner, 37 × 21 pt in. It sits
/// next to the tile in the grid, above it, so nothing clips it (SwiftUI's .offset).
let badge = SiteHoverView()
@@ -314,11 +334,7 @@ private final class SiteExtensionTile: SiteTile {
init(entry: ExtensionStore.Entry, pinned: Bool, colors: SiteControlCenterColors, run: @escaping () -> Void, togglePin: @escaping () -> Void) {
self.pinned = pinned
super.init(colors: colors, help: entry.name, action: run)
- if let icon = entry.icon {
- setGlyph(icon, tint: nil, size: 16)
- } else {
- setGlyph(SidebarSymbols.image("puzzlepiece.extension.fill", size: 13), tint: colors.secondary)
- }
+ show(icon: entry.icon)
setAccessibilityLabel(entry.name)
badge.onClick = togglePin
badge.onHover = { [weak self] in self?.refresh() }
@@ -333,6 +349,17 @@ private final class SiteExtensionTile: SiteTile {
required init?(coder: NSCoder) { fatalError() }
+ /// The extension's icon as it is now, else the puzzle piece.
+ func show(icon: NSImage?) {
+ guard shownIcon.map({ $0 !== icon }) ?? true else { return }
+ shownIcon = .some(icon)
+ if let icon {
+ setGlyph(icon, tint: nil, size: 16)
+ } else {
+ setGlyph(SidebarSymbols.image("puzzlepiece.extension.fill", size: 13), tint: colors.secondary)
+ }
+ }
+
/// The badge as one image: the circle, a 1 pt ring in the panel colour inside its edge, and
/// the pin turned 45° clockwise.
private static func badgeImage(fill: NSColor, ring: NSColor, glyph: NSColor) -> NSImage {
@@ -573,8 +600,8 @@ final class SiteControlCenterPopover: NSObject, NSPopoverDelegate {
var isShown: Bool { popover?.isShown == true }
- func show(relativeTo rect: NSRect, of view: NSView, url: String, secure: Bool, dark: Bool, profile: String, store: SidebarStore,
- actions: SiteControlCenterActions) {
+ func show(relativeTo rect: NSRect, of view: NSView, url: String, secure: Bool, dark: Bool, profile: String, tab: UUID?,
+ store: SidebarStore, actions: SiteControlCenterActions) {
// A transient popover closes on the mouse-down outside it; the button fires on that
// click's mouse-up. The same click on the sliders button closes it, as in Arc,
// however long the press took (GitHub #42): the latest mouse-down is the closing one.
@@ -604,7 +631,7 @@ final class SiteControlCenterPopover: NSObject, NSPopoverDelegate {
acts.clearCache = closing(actions.clearCache)
acts.clearCookies = closing(actions.clearCookies)
acts.showCertificate = actions.showCertificate.map(closing)
- let content = SiteControlCenterView(url: url, secure: secure, dark: dark, profile: profile, actions: acts, store: store)
+ let content = SiteControlCenterView(url: url, secure: secure, dark: dark, profile: profile, tab: tab, actions: acts, store: store)
let host = NSViewController()
host.view = content
host.preferredContentSize = content.frame.size
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 1663da5..7124392 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -108,6 +108,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
window.backgroundColor = NSColor(palette.gradientColors.first ?? .gray)
browsers = BrowserManager(store: store, favicons: app.favicons, container: shell.parkingView, clock: app.composition.clock)
+ // What extensions set for a tab (chrome.action.setIcon with tabId) went with its page.
+ browsers.pageClosed = { ExtensionStore.shared.forgetActionTab($0) }
browsers.delegate = self
browsers.windowID = session.id
browsers.takeRuntimeFromOtherWindow = { [weak self] id in
@@ -270,6 +272,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
guard let main = app?.main, let window = main.window, let key = NSApp.keyWindow, key === window || key.parent === window else { return nil }
return main.extensionPopupAnchor(id)
}
+ ExtensionActions.shared.watchActions { [weak app] in
+ app?.mainWindows.flatMap { $0.browsers.runtimes.values.map { (tab: $0.tabID, browser: $0.browser) } } ?? []
+ }
browsers.nowPlaying = sidebarUI.nowPlaying
sidebarUI.nowPlaying.perform = { [weak self] id, action in
guard let self else { return }
@@ -1973,7 +1978,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
siteControlCenterSpaceID = focusedSpaceID
siteControlCenter.show(relativeTo: rect, of: content, url: url, secure: secure, dark: focusedSpace.theme.palette.isDark,
- profile: profileDirectoryName, store: store, actions: actions)
+ profile: profileDirectoryName, tab: selectedTabID, store: store, actions: actions)
}
private func openTab(_ url: String) {
diff --git a/scripts/cef-patches/extensions-action-updates.patch b/scripts/cef-patches/extensions-action-updates.patch
new file mode 100644
index 0000000..f08ebe1
--- /dev/null
+++ b/scripts/cef-patches/extensions-action-updates.patch
@@ -0,0 +1,353 @@
+diff --git a/chrome/browser/devtools/inspector_protocol_config.json b/chrome/browser/devtools/inspector_protocol_config.json
+--- a/chrome/browser/devtools/inspector_protocol_config.json
++++ b/chrome/browser/devtools/inspector_protocol_config.json
+@@ -39,7 +39,7 @@
+ },
+ {
+ "domain": "Extensions",
+- "include": [ "triggerAction", "loadUnpacked", "getStorageItems", "setStorageItems", "removeStorageItems", "clearStorageItems", "uninstall", "getExtensions" ],
++ "include": [ "triggerAction", "setActionUpdatesEnabled", "loadUnpacked", "getStorageItems", "setStorageItems", "removeStorageItems", "clearStorageItems", "uninstall", "getExtensions" ],
+ "async": [ "loadUnpacked", "getStorageItems", "setStorageItems", "removeStorageItems", "clearStorageItems", "uninstall" ]
+ },
+ {
+diff --git a/chrome/browser/devtools/protocol/extensions_handler.cc b/chrome/browser/devtools/protocol/extensions_handler.cc
+--- a/chrome/browser/devtools/protocol/extensions_handler.cc
++++ b/chrome/browser/devtools/protocol/extensions_handler.cc
+@@ -7,15 +7,21 @@
+ #include <memory>
+ #include <string>
+
++#include "base/base64.h"
+ #include "base/files/file_path.h"
+ #include "base/functional/bind.h"
++#include "base/strings/stringprintf.h"
+ #include "base/strings/utf_string_conversions.h"
++#include "chrome/browser/browser_process.h"
+ #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
+ #include "chrome/browser/devtools/devtools_browser_context_manager.h"
+ #include "chrome/browser/devtools/protocol/extensions.h"
+ #include "chrome/browser/devtools/protocol/protocol.h"
+ #include "chrome/browser/extensions/browser_window_util.h"
++#include "chrome/browser/extensions/extension_action_dispatcher.h"
++#include "chrome/browser/extensions/extension_tab_util.h"
+ #include "chrome/browser/extensions/extension_util.h"
++#include "chrome/browser/profiles/profile.h"
+ #include "chrome/browser/ui/extensions/extension_action_view_model.h"
+ #include "chrome/browser/ui/extensions/extensions_container.h"
+ #include "chrome/browser/ui/toolbar/toolbar_action_view_model.h"
+@@ -23,9 +29,15 @@
+ #include "content/public/browser/web_contents.h"
+ #include "extensions/browser/api/storage/storage_area_namespace.h"
+ #include "extensions/browser/api/storage/storage_utils.h"
++#include "extensions/browser/extension_action.h"
++#include "extensions/browser/extension_action_manager.h"
+ #include "extensions/browser/extension_registrar.h"
+ #include "extensions/browser/unpacked_installer.h"
+ #include "extensions/common/manifest.h"
++#include "ui/gfx/codec/png_codec.h"
++#include "ui/gfx/image/image.h"
++#include "ui/gfx/image/image_skia.h"
++#include "ui/gfx/image/image_skia_rep.h"
+
+ namespace {
+
+@@ -160,8 +172,185 @@
+ return result;
+ }
+
++// Cra: `image` as a PNG data: URL from its largest scale, empty when it has
++// none.
++std::string PngDataUrl(const gfx::Image& image) {
++ if (image.IsEmpty()) {
++ return std::string();
++ }
++ // image_reps() returns a copy: keep it alive while `best` points into it.
++ const std::vector<gfx::ImageSkiaRep> reps = image.AsImageSkia().image_reps();
++ const gfx::ImageSkiaRep* best = nullptr;
++ for (const gfx::ImageSkiaRep& rep : reps) {
++ if (!best || rep.scale() > best->scale()) {
++ best = &rep;
++ }
++ }
++ if (!best || best->GetBitmap().drawsNothing()) {
++ return std::string();
++ }
++ std::optional<std::vector<uint8_t>> png = gfx::PNGCodec::EncodeBGRASkBitmap(
++ best->GetBitmap(), /*discard_transparency=*/false);
++ return png ? "data:image/png;base64," + base::Base64Encode(*png)
++ : std::string();
++}
++
+ } // namespace
++
++// Cra: forwards one profile's action changes to the handler.
++class ExtensionsHandler::ActionWatch
++ : public extensions::ExtensionActionDispatcher::Observer {
++ public:
++ ActionWatch(ExtensionsHandler* handler,
++ extensions::ExtensionActionDispatcher* dispatcher)
++ : handler_(handler) {
++ observation_.Observe(dispatcher);
++ }
++
++ bool IsWatching(extensions::ExtensionActionDispatcher* dispatcher) const {
++ return observation_.IsObservingSource(dispatcher);
++ }
++
++ void OnExtensionActionUpdated(
++ extensions::ExtensionAction* extension_action,
++ content::WebContents* web_contents,
++ content::BrowserContext* browser_context) override {
++ handler_->ReportAction(*extension_action, web_contents, browser_context);
++ }
++
++ void OnShuttingDown() override { observation_.Reset(); }
++
++ private:
++ raw_ptr<ExtensionsHandler> handler_;
++ base::ScopedObservation<extensions::ExtensionActionDispatcher,
++ extensions::ExtensionActionDispatcher::Observer>
++ observation_{this};
++};
++
++protocol::DispatchResponse ExtensionsHandler::SetActionUpdatesEnabled(
++ bool enabled) {
++ if (!allow_loading_extensions_) {
++ return protocol::Response::ServerError("Method not available.");
++ }
++ if (!enabled) {
++ action_watches_.clear();
++ profile_manager_observation_.Reset();
++ reported_actions_.clear();
++ return protocol::Response::Success();
++ }
++ ProfileManager* profile_manager = g_browser_process->profile_manager();
++ if (!profile_manager) {
++ return protocol::Response::ServerError("No profile manager.");
++ }
++ if (!profile_manager_observation_.IsObserving()) {
++ profile_manager_observation_.Observe(profile_manager);
++ }
++ for (Profile* profile : profile_manager->GetLoadedProfiles()) {
++ WatchActions(profile);
++ }
++ return protocol::Response::Success();
++}
++
++void ExtensionsHandler::OnProfileAdded(Profile* profile) {
++ WatchActions(profile);
++}
++
++void ExtensionsHandler::OnProfileManagerDestroying() {
++ action_watches_.clear();
++ profile_manager_observation_.Reset();
++}
+
++// Observes `profile`'s actions and reports their tab-independent state.
++void ExtensionsHandler::WatchActions(Profile* profile) {
++ extensions::ExtensionActionDispatcher* dispatcher =
++ extensions::ExtensionActionDispatcher::Get(profile);
++ if (!dispatcher) {
++ return;
++ }
++ for (const auto& watch : action_watches_) {
++ if (watch->IsWatching(dispatcher)) {
++ return;
++ }
++ }
++ action_watches_.push_back(std::make_unique<ActionWatch>(this, dispatcher));
++ extensions::ExtensionActionManager* manager =
++ extensions::ExtensionActionManager::Get(profile);
++ extensions::ExtensionRegistry* registry =
++ extensions::ExtensionRegistry::Get(profile);
++ if (!manager || !registry) {
++ return;
++ }
++ for (const auto& extension : registry->enabled_extensions()) {
++ if (extensions::ExtensionAction* action =
++ manager->GetExtensionAction(*extension)) {
++ ReportAction(*action, nullptr, profile);
++ }
++ }
++}
++
++// Reports what the extension set for a tab (only that tab's own values), or
++// with no `web_contents` its tab-independent values.
++void ExtensionsHandler::ReportAction(const extensions::ExtensionAction& action,
++ content::WebContents* web_contents,
++ content::BrowserContext* context) {
++ if (!frontend_ || !context) {
++ return;
++ }
++ const std::string profile = Profile::FromBrowserContext(context)
++ ->GetOriginalProfile()
++ ->GetBaseName()
++ .AsUTF8Unsafe();
++ int tab_id = extensions::ExtensionAction::kDefaultTabId;
++ std::optional<std::string> target_id;
++ if (web_contents) {
++ // Cra knows a tab by its page target; one DevTools never listed has none.
++ if (!content::DevToolsAgentHost::HasFor(web_contents)) {
++ return;
++ }
++ target_id =
++ content::DevToolsAgentHost::GetOrCreateFor(web_contents)->GetId();
++ tab_id = extensions::ExtensionTabUtil::GetTabId(web_contents);
++ }
++ const std::string key = profile + "/" + action.extension_id() + "/" +
++ target_id.value_or(std::string());
++ if (web_contents && web_contents->IsBeingDestroyed()) {
++ reported_actions_.erase(key);
++ return;
++ }
++ const bool for_tab = target_id.has_value();
++ const std::string icon = PngDataUrl(
++ !for_tab || action.HasIcon(tab_id) ? action.GetExplicitlySetIcon(tab_id)
++ : action.GetDeclarativeIcon(tab_id));
++ const std::string title =
++ !for_tab || action.HasTitle(tab_id) ? action.GetTitle(tab_id) : "";
++ const std::string badge_text =
++ !for_tab || action.HasBadgeText(tab_id)
++ ? action.GetExplicitlySetBadgeText(tab_id)
++ : "";
++ std::string badge_color;
++ if (!for_tab || action.HasBadgeBackgroundColor(tab_id)) {
++ const SkColor color = action.GetBadgeBackgroundColor(tab_id);
++ badge_color = base::StringPrintf(
++ "#%02X%02X%02X%02X", SkColorGetR(color), SkColorGetG(color),
++ SkColorGetB(color), SkColorGetA(color));
++ }
++ const std::string state =
++ icon + "\n" + title + "\n" + badge_text + "\n" + badge_color;
++ const bool empty =
++ icon.empty() && title.empty() && badge_text.empty() && badge_color.empty();
++ auto it = reported_actions_.find(key);
++ if (it == reported_actions_.end() ? (empty && for_tab) : it->second == state) {
++ return;
++ }
++ if (empty) {
++ reported_actions_.erase(key);
++ } else {
++ reported_actions_[key] = state;
++ }
++ frontend_->ActionUpdated(action.extension_id(), profile, icon, title,
++ badge_text, badge_color, std::move(target_id));
++}
++
+ protocol::DispatchResponse ExtensionsHandler::TriggerAction(
+ const std::string& extension_id,
+ const std::string& target_id) {
+@@ -219,6 +408,9 @@
+ : target_id_(target_id),
+ allow_loading_extensions_(allow_loading_extensions) {
+ protocol::Extensions::Dispatcher::wire(dispatcher, this);
++ // Cra: actionUpdated needs a frontend.
++ frontend_ =
++ std::make_unique<protocol::Extensions::Frontend>(dispatcher->channel());
+ }
+
+ ExtensionsHandler::~ExtensionsHandler() = default;
+diff --git a/chrome/browser/devtools/protocol/extensions_handler.h b/chrome/browser/devtools/protocol/extensions_handler.h
+--- a/chrome/browser/devtools/protocol/extensions_handler.h
++++ b/chrome/browser/devtools/protocol/extensions_handler.h
+@@ -5,13 +5,31 @@
+ #ifndef CHROME_BROWSER_DEVTOOLS_PROTOCOL_EXTENSIONS_HANDLER_H_
+ #define CHROME_BROWSER_DEVTOOLS_PROTOCOL_EXTENSIONS_HANDLER_H_
+
++#include <map>
++#include <vector>
++
++#include "base/scoped_observation.h"
+ #include "chrome/browser/devtools/protocol/extensions.h"
+ #include "chrome/browser/devtools/protocol/protocol.h"
++#include "chrome/browser/profiles/profile_manager.h"
++#include "chrome/browser/profiles/profile_manager_observer.h"
+ #include "extensions/browser/api/storage/storage_frontend.h"
+ #include "extensions/common/extension.h"
+
++class Profile;
++
++namespace content {
++class BrowserContext;
++class WebContents;
++} // namespace content
++
++namespace extensions {
++class ExtensionAction;
++} // namespace extensions
++
+ // Implements the Extensions domain for Chrome DevTools Protocol.
+-class ExtensionsHandler : public protocol::Extensions::Backend {
++class ExtensionsHandler : public protocol::Extensions::Backend,
++ public ProfileManagerObserver {
+ public:
+ explicit ExtensionsHandler(protocol::UberDispatcher* dispatcher,
+ const std::string& target_id,
+@@ -26,6 +44,15 @@
+ protocol::DispatchResponse TriggerAction(
+ const protocol::String& extendsion_id,
+ const protocol::String& target_id) override;
++ // Cra: actionUpdated for chrome.action.setIcon and friends.
++ protocol::DispatchResponse SetActionUpdatesEnabled(bool enabled) override;
++ // ProfileManagerObserver:
++ void OnProfileAdded(Profile* profile) override;
++ void OnProfileManagerDestroying() override;
++ void WatchActions(Profile* profile);
++ void ReportAction(const extensions::ExtensionAction& action,
++ content::WebContents* web_contents,
++ content::BrowserContext* context);
+ void LoadUnpacked(const protocol::String& path,
+ std::optional<bool> enable_in_incognito,
+ std::unique_ptr<LoadUnpackedCallback> callback) override;
+@@ -83,6 +110,15 @@
+ bool allow_loading_extensions_;
+
+ std::unique_ptr<protocol::Extensions::Frontend> frontend_;
++
++ // Cra: one observer per profile's ExtensionActionDispatcher.
++ class ActionWatch;
++ std::vector<std::unique_ptr<ActionWatch>> action_watches_;
++ base::ScopedObservation<ProfileManager, ProfileManagerObserver>
++ profile_manager_observation_{this};
++ // The last reported state of each action that has one, by profile, extension
++ // and page target, so a navigation that clears nothing reports nothing.
++ std::map<std::string, std::string> reported_actions_;
+ base::WeakPtrFactory<ExtensionsHandler> weak_factory_{this};
+ };
+
+diff --git a/third_party/blink/public/devtools_protocol/domains/Extensions.pdl b/third_party/blink/public/devtools_protocol/domains/Extensions.pdl
+--- a/third_party/blink/public/devtools_protocol/domains/Extensions.pdl
++++ b/third_party/blink/public/devtools_protocol/domains/Extensions.pdl
+@@ -22,6 +22,32 @@
+ # A tab target ID to trigger the default extension action on.
+ string targetId
+
++ # Cra: reports changes to extensions' toolbar actions (chrome.action.setIcon,
++ # setTitle, setBadgeText) in every profile as `actionUpdated`. Turning it on
++ # first reports each enabled extension's tab-independent state.
++ command setActionUpdatesEnabled
++ parameters
++ boolean enabled
++
++ # Cra: an extension changed its toolbar action. Empty values are ones the
++ # extension did not set: the manifest's default applies, or for a tab, the
++ # tab-independent value.
++ event actionUpdated
++ parameters
++ # Extension id.
++ string id
++ # Profile directory name ("Default", "Profile 1").
++ string profile
++ # The icon the extension set, as a PNG data: URL at its largest scale.
++ string icon
++ string title
++ string badgeText
++ # Badge background as #RRGGBBAA.
++ string badgeColor
++ # Page target of the tab the change is for; absent for the
++ # tab-independent state.
++ optional string targetId
++
+ # Installs an unpacked extension from the filesystem similar to
+ # --load-extension CLI flags. Returns extension ID once the extension
+ # has been installed.
diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.sh
index 36d0884..79f3fd0 100755
--- a/scripts/fetch-cef.sh
+++ b/scripts/fetch-cef.sh
@@ -13,7 +13,7 @@ CEF_VERSION="${CEF_VERSION:-156.0.15+gcf671c0+chromium-156.0.8078.80}"
ARCH="${CEF_ARCH:-macosarm64}"
NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"
# Bump the suffix (codecs2, …) when the build changes but CEF_VERSION does not.
-CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs5}"
+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs6}"
URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"
mkdir -p vendor