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.

Extension side panels: MetaMask's toolbar button opens its wallet beside the page

Victor4ce0e40891a2
diff --git a/Packages/CraCore/Sources/CraCore/ExtensionSidePanel.swift b/Packages/CraCore/Sources/CraCore/ExtensionSidePanel.swift
new file mode 100644
index 0000000..2c780df
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/ExtensionSidePanel.swift
@@ -0,0 +1,107 @@
+import Foundation
+
+/// One Extensions.sidePanelRequested event: an extension asked to show, hide or toggle its side
+/// panel for a page (its toolbar action with `openPanelOnActionClick`, `chrome.sidePanel.open()`
+/// or `close()`). Chromium sends it to Cra instead of opening its own side panel, which CEF never
+/// shows (scripts/cef-patches/extension-side-panels.patch). MetaMask opens in its side panel by
+/// default, so before this its toolbar button did nothing, in Cra as in Arc.
+public struct ExtensionSidePanelRequest: Equatable, Sendable {
+ public enum Kind: String, Sendable { case toggle, open, close }
+
+ public let extensionID: String
+ /// Chromium profile folder ("Default", "Profile 1").
+ public let profile: String
+ public let kind: Kind
+ /// The panel's page for that tab; empty for `close`.
+ public let url: String
+ /// The page target of the tab the request is for.
+ public let targetID: String
+
+ public init(extensionID: String, profile: String, kind: Kind, url: String, targetID: String) {
+ self.extensionID = extensionID
+ self.profile = profile
+ self.kind = kind
+ self.url = url
+ self.targetID = targetID
+ }
+
+ /// The event's params; nil when they are not one, or when a show/toggle names a page that is
+ /// not one of the extension's own.
+ 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,
+ let kind = (p["request"] as? String).flatMap(Kind.init(rawValue:)),
+ let target = p["targetId"] as? String else { return nil }
+ let url = p["url"] as? String ?? ""
+ if kind != .close, !Self.isOwnPage(url, of: id) { return nil }
+ self.init(extensionID: id, profile: profile, kind: kind, url: url, targetID: target)
+ }
+
+ /// `url` is a page of the extension `id` (chrome-extension://<id>/…).
+ static func isOwnPage(_ url: String, of id: String) -> Bool {
+ guard let u = URL(string: url), u.scheme == "chrome-extension", u.host == id else { return false }
+ return true
+ }
+
+ /// What the window's panel does about this request, given what it shows. Chrome shows one
+ /// panel per window: opening another extension's replaces it; toggling or closing only ever
+ /// hides the asking extension's own.
+ public func change(from current: ExtensionSidePanelState?) -> ExtensionSidePanelChange {
+ let wanted = ExtensionSidePanelState(extensionID: extensionID, profile: profile, url: url)
+ let showsThis = current.map { $0.extensionID == extensionID && $0.profile == profile } ?? false
+ switch kind {
+ case .toggle: return showsThis ? .hide : .show(wanted)
+ case .open: return current == wanted ? .none : .show(wanted)
+ case .close: return showsThis ? .hide : .none
+ }
+ }
+}
+
+/// What a window's extension side panel shows.
+public struct ExtensionSidePanelState: Equatable, Sendable {
+ public var extensionID: String
+ public var profile: String
+ public var url: String
+
+ public init(extensionID: String, profile: String, url: String) {
+ self.extensionID = extensionID
+ self.profile = profile
+ self.url = url
+ }
+}
+
+public enum ExtensionSidePanelChange: Equatable, Sendable {
+ case none
+ case show(ExtensionSidePanelState)
+ case hide
+}
+
+/// The panel's width: Chrome's side panel starts at 320 pt and drags wider; Cra starts a little
+/// wider (MetaMask's panel layout wants ~360) and always leaves the pages room.
+public enum ExtensionSidePanelWidth {
+ public static let initial: Double = 360
+ public static let minimum: Double = 320
+ public static let maximum: Double = 640
+ /// A single page keeps at least this much beside the panel; a window narrower than panel +
+ /// page does not show the panel (it comes back when the window is wide enough).
+ public static let minimumPageWidth: Double = 400
+
+ /// What the pages need beside the panel: one page its minimum, a split every pane its own
+ /// minimum and the gaps between them (side by side), so the panel never squeezes a pane.
+ public static func pageMinimum(panes: Int, paneMinimum: Double, gap: Double, sideBySide: Bool = true) -> Double {
+ guard sideBySide, panes > 1 else { return minimumPageWidth }
+ return max(minimumPageWidth, Double(panes) * paneMinimum + Double(panes - 1) * gap)
+ }
+
+ /// `width` within the limits, and narrow enough that `container` (the content area, gap
+ /// included) keeps `pages` for the pages.
+ public static func clamp(_ width: Double, container: Double, gap: Double, pages: Double = minimumPageWidth) -> Double {
+ let room = container - gap - pages
+ return max(minimum, min(width, maximum, room))
+ }
+
+ /// Whether the panel fits beside the pages at all.
+ public static func fits(container: Double, gap: Double, pages: Double = minimumPageWidth) -> Bool {
+ container - gap - pages >= minimum
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/ExtensionSidePanelTests.swift b/Packages/CraCore/Tests/CraCoreTests/ExtensionSidePanelTests.swift
new file mode 100644
index 0000000..7eaec3a
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/ExtensionSidePanelTests.swift
@@ -0,0 +1,117 @@
+import CraCore
+import Foundation
+import Testing
+
+struct ExtensionSidePanelTests {
+ static let metaMask = "nkbihfbeogaeaoehlefnkodbefgpgknn"
+ static let panelURL = "chrome-extension://\(metaMask)/sidepanel.html"
+
+ static func params(_ p: [String: Any]) -> Data { try! JSONSerialization.data(withJSONObject: p) }
+
+ static func request(_ kind: ExtensionSidePanelRequest.Kind, id: String = metaMask, profile: String = "Default",
+ url: String? = nil) -> ExtensionSidePanelRequest {
+ ExtensionSidePanelRequest(extensionID: id, profile: profile, kind: kind,
+ url: url ?? (kind == .close ? "" : "chrome-extension://\(id)/sidepanel.html"), targetID: "T")
+ }
+
+ static func shown(_ id: String = metaMask, profile: String = "Default", url: String? = nil) -> ExtensionSidePanelState {
+ ExtensionSidePanelState(extensionID: id, profile: profile, url: url ?? "chrome-extension://\(id)/sidepanel.html")
+ }
+
+ @Test func decodesTheEvent() throws {
+ let r = try #require(ExtensionSidePanelRequest(params: Self.params([
+ "id": Self.metaMask, "profile": "Profile 1", "request": "toggle", "url": Self.panelURL, "targetId": "T1",
+ ])))
+ #expect(r == ExtensionSidePanelRequest(extensionID: Self.metaMask, profile: "Profile 1", kind: .toggle,
+ url: Self.panelURL, targetID: "T1"))
+ }
+
+ @Test func closeNeedsNoPage() throws {
+ let r = try #require(ExtensionSidePanelRequest(params: Self.params([
+ "id": Self.metaMask, "profile": "Default", "request": "close", "url": "", "targetId": "T1",
+ ])))
+ #expect(r.kind == .close)
+ }
+
+ /// A panel only ever shows the asking extension's own pages.
+ @Test(arguments: [
+ "https://evil.example/sidepanel.html",
+ "chrome-extension://otherextensionid/sidepanel.html",
+ "chrome://settings",
+ "",
+ ])
+ func refusesPagesThatAreNotTheExtensions(_ url: String) {
+ #expect(ExtensionSidePanelRequest(params: Self.params([
+ "id": Self.metaMask, "profile": "Default", "request": "open", "url": url, "targetId": "T1",
+ ])) == nil)
+ }
+
+ @Test func refusesUnknownRequestsAndMissingFields() {
+ #expect(ExtensionSidePanelRequest(params: Self.params([
+ "id": Self.metaMask, "profile": "Default", "request": "pin", "url": Self.panelURL, "targetId": "T1",
+ ])) == nil)
+ #expect(ExtensionSidePanelRequest(params: Self.params([
+ "id": Self.metaMask, "profile": "Default", "request": "open", "url": Self.panelURL,
+ ])) == nil)
+ #expect(ExtensionSidePanelRequest(params: Data("nope".utf8)) == nil)
+ }
+
+ // MetaMask's toolbar button (openPanelOnActionClick): a click opens the panel, the next closes it.
+ @Test func toggleOpensThenCloses() {
+ let toggle = Self.request(.toggle)
+ #expect(toggle.change(from: nil) == .show(Self.shown()))
+ #expect(toggle.change(from: Self.shown()) == .hide)
+ }
+
+ @Test func toggleReplacesAnotherExtensionsPanel() {
+ #expect(Self.request(.toggle).change(from: Self.shown("other")) == .show(Self.shown()))
+ }
+
+ /// Same extension, another profile's copy: a different panel (its own storage and accounts).
+ @Test func anotherProfileIsAnotherPanel() {
+ #expect(Self.request(.toggle).change(from: Self.shown(profile: "Profile 1")) == .show(Self.shown()))
+ #expect(Self.request(.close).change(from: Self.shown(profile: "Profile 1")) == .none)
+ }
+
+ @Test func openShowsOrKeepsOrNavigates() {
+ let open = Self.request(.open)
+ #expect(open.change(from: nil) == .show(Self.shown()))
+ #expect(open.change(from: Self.shown()) == .none)
+ let other = "chrome-extension://\(Self.metaMask)/other.html"
+ #expect(Self.request(.open, url: other).change(from: Self.shown()) == .show(Self.shown(url: other)))
+ }
+
+ @Test func closeOnlyHidesItsOwnPanel() {
+ let close = Self.request(.close)
+ #expect(close.change(from: Self.shown()) == .hide)
+ #expect(close.change(from: Self.shown("other")) == .none)
+ #expect(close.change(from: nil) == .none)
+ }
+
+ @Test func widthStaysWithinLimitsAndLeavesThePageRoom() {
+ typealias W = ExtensionSidePanelWidth
+ #expect(W.clamp(360, container: 1400, gap: 10) == 360)
+ #expect(W.clamp(100, container: 1400, gap: 10) == W.minimum)
+ #expect(W.clamp(2000, container: 1400, gap: 10) == W.maximum)
+ // 900 pt of content: the page keeps 400 beside a 10 pt gap.
+ #expect(W.clamp(600, container: 900, gap: 10) == 490)
+ #expect(W.fits(container: 730, gap: 10))
+ #expect(!W.fits(container: 729, gap: 10))
+ }
+
+ /// A split keeps every pane at its minimum: three side-by-side panes of 200 pt and two 10 pt
+ /// gaps need 620 pt, so the panel only shows from 950 pt of content.
+ @Test func splitPanesKeepTheirMinimum() {
+ typealias W = ExtensionSidePanelWidth
+ #expect(W.pageMinimum(panes: 1, paneMinimum: 200, gap: 10) == 400)
+ #expect(W.pageMinimum(panes: 2, paneMinimum: 200, gap: 10) == 410)
+ let three = W.pageMinimum(panes: 3, paneMinimum: 200, gap: 10)
+ #expect(three == 620)
+ #expect(!W.fits(container: 762, gap: 10, pages: three))
+ #expect(W.fits(container: 950, gap: 10, pages: three))
+ #expect(W.clamp(360, container: 1000, gap: 10, pages: three) == 360)
+ #expect(W.clamp(500, container: 1000, gap: 10, pages: three) == 370)
+ // Stacked panes share the width, so they need only a page's minimum.
+ #expect(W.pageMinimum(panes: 3, paneMinimum: 200, gap: 10, sideBySide: false) == 400)
+ }
+}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 462ac06..bd8aa2c 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -707,6 +707,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
return
}
if let id = dict["extensionAction"] { main.runExtensionAction(id); return }
+ // What the side panel's close button does (scripts/scenario.sh).
+ if dict["sidePanel"] == "close" { main.sidePanel.hide(); return }
if let path = dict["exportDiagnostics"] {
Diagnostics.export(windows: mainWindows, store: store, to: URL(fileURLWithPath: path))
return
diff --git a/Sources/Cra/Services/ExtensionActions.swift b/Sources/Cra/Services/ExtensionActions.swift
index a1ce0cd..558cae6 100644
--- a/Sources/Cra/Services/ExtensionActions.swift
+++ b/Sources/Cra/Services/ExtensionActions.swift
@@ -201,6 +201,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 }
+ if method == "Extensions.sidePanelRequested" { sidePanelRequested(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 }
@@ -234,6 +235,7 @@ final class ExtensionActions {
/// 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 sidePanelRequestsAwaitingTabs: [ExtensionSidePanelRequest] = []
private var resolvingPageTargets = false
/// Turns on Chromium's Extensions.actionUpdated (Cra's CEF patch): extensions' own icons
@@ -255,6 +257,21 @@ final class ExtensionActions {
resolvePageTargets()
}
+ // MARK: Side panels
+
+ /// Gets each side panel request with the Cra tab it is for (nil: no Cra tab, e.g. the panel
+ /// page itself or a Little Window). Chromium sends them while action updates are on
+ /// (scripts/cef-patches/extension-side-panels.patch).
+ var sidePanelHandler: ((ExtensionSidePanelRequest, UUID?) -> Void)?
+
+ private func sidePanelRequested(_ params: String) {
+ guard let request = ExtensionSidePanelRequest(params: Data(params.utf8)) else { return }
+ if let tab = tabsByPageTarget[request.targetID] { sidePanelHandler?(request, tab); return }
+ if foreignPageTargets.contains(request.targetID) { sidePanelHandler?(request, nil); return }
+ sidePanelRequestsAwaitingTabs.append(request)
+ 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 }
@@ -271,6 +288,9 @@ final class ExtensionActions {
let waiting = updatesAwaitingTabs
updatesAwaitingTabs = []
foreignPageTargets = []
+ let panelRequests = sidePanelRequestsAwaitingTabs
+ sidePanelRequestsAwaitingTabs = []
+ for request in panelRequests { sidePanelHandler?(request, map[request.targetID]) }
for update in waiting {
guard let target = update.targetID else { continue }
if let tab = map[target] {
diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swift
index af92123..715472e 100644
--- a/Sources/Cra/UI/ShellView.swift
+++ b/Sources/Cra/UI/ShellView.swift
@@ -54,6 +54,13 @@ final class ShellView: NSView {
var devToolsFrontendDocked = false { didSet { needsLayout = true } }
/// The page rect (window coordinates) the frontend-docked layout produced; overlays follow it.
var frontendPageRect: NSRect? { didSet { if oldValue != frontendPageRect { needsLayout = true } } }
+ /// An extension's side panel (chrome.sidePanel) right of the panes, Chrome's place for it.
+ let sidePanel = ExtensionSidePanelCard()
+ let sidePanelHandle = DevToolsResizeHandle()
+ /// The panel's width; 0 = no panel.
+ var sidePanelWidth: CGFloat = 0 { didSet { if sidePanelWidth != oldValue { needsLayout = true } } }
+ /// The panel page's area (window coordinates), nil while no panel shows.
+ var onSidePanelFrame: ((NSRect?) -> Void)?
/// Reports the dock area (window coordinates) so the DevTools child window follows it.
var onDevToolsFrame: ((NSRect) -> Void)?
/// Reports each pane's page area (window coordinates) so Chrome-style page windows follow it.
@@ -295,6 +302,10 @@ final class ShellView: NSView {
self.layoutSubtreeIfNeeded()
}
contentContainer.addSubview(placeholderHost)
+ sidePanel.isHidden = true
+ sidePanelHandle.isHidden = true
+ contentContainer.addSubview(sidePanel)
+ contentContainer.addSubview(sidePanelHandle)
for h in [statusHost, findHost] as [NSView] {
h.isHidden = true
contentContainer.addSubview(h)
@@ -464,10 +475,33 @@ final class ShellView: NSView {
}
}
+ /// The side panel's width in `bounds` (the content area), 0 when none shows: none open, a
+ /// page in full screen, or no room beside the page.
+ private func sidePanelShownWidth(in bounds: NSRect) -> CGFloat {
+ let gap = Double(SplitPaneLayout.Constants.gap)
+ let pages = sidePanelPageMinimum
+ guard sidePanelWidth > 0, hasTab, !contentFullscreen,
+ ExtensionSidePanelWidth.fits(container: Double(bounds.width), gap: gap, pages: pages) else { return 0 }
+ return CGFloat(ExtensionSidePanelWidth.clamp(Double(sidePanelWidth), container: Double(bounds.width), gap: gap, pages: pages)).rounded()
+ }
+
+ /// What the panes need beside the side panel: each split pane keeps its minimum.
+ var sidePanelPageMinimum: Double {
+ ExtensionSidePanelWidth.pageMinimum(panes: paneCards.count, paneMinimum: Double(SplitPaneLayout.Constants.minimumPaneLength),
+ gap: Double(SplitPaneLayout.Constants.gap), sideBySide: splitOrientation == .horizontal)
+ }
+
+ /// The panes' share of `bounds`: all of it, less the side panel and its gap on the right.
+ private func paneArea(in bounds: NSRect) -> NSRect {
+ let w = sidePanelShownWidth(in: bounds)
+ guard w > 0 else { return bounds }
+ return NSRect(x: bounds.minX, y: bounds.minY, width: bounds.width - w - SplitPaneLayout.Constants.gap, height: bounds.height)
+ }
+
private func paneLayout(in bounds: NSRect) -> SplitPaneLayout.Result {
let ids = paneCards.map(\.tabID)
let panes = ids.map { SplitPaneLayout.Pane(id: $0, factor: paneFactors[$0] ?? (1 / CGFloat(max(1, ids.count)))) }
- var layout = SplitPaneLayout(panes: panes, orientation: splitOrientation, containerSize: bounds.size)
+ var layout = SplitPaneLayout(panes: panes, orientation: splitOrientation, containerSize: paneArea(in: bounds).size)
layout.backingScaleFactor = window?.backingScaleFactor ?? 2
return layout.compute()
}
@@ -500,7 +534,7 @@ final class ShellView: NSView {
private func dragPane(_ index: Int, delta: CGFloat) {
let ids = paneCards.map(\.tabID)
let panes = ids.map { SplitPaneLayout.Pane(id: $0, factor: dragStartFactors[$0] ?? (1 / CGFloat(max(1, ids.count)))) }
- let layout = SplitPaneLayout(panes: panes, orientation: splitOrientation, containerSize: contentContainer.bounds.size)
+ let layout = SplitPaneLayout(panes: panes, orientation: splitOrientation, containerSize: paneArea(in: contentContainer.bounds).size)
paneFactors = layout.dragging(dividerAfter: index, by: delta).factors
layoutContentChildren()
}
@@ -677,6 +711,7 @@ final class ShellView: NSView {
}
placeholderHost.frame = cb
placeholderHost.isHidden = hasTab
+ layoutSidePanel(in: cb)
// The no-tab card is rounded like a page's (GitHub #6: a new window showed a square one).
placeholderHost.layer?.cornerRadius = cardCornerRadius
placeholderHost.layer?.cornerCurve = .continuous
@@ -726,6 +761,22 @@ final class ShellView: NSView {
if !animatingPanes, paneCards.allSatisfy({ $0.frozenWebBounds == nil }) { onPaneFrames?(paneWebFrames(layout)) }
}
+ private func layoutSidePanel(in cb: NSRect) {
+ let w = sidePanelShownWidth(in: cb)
+ sidePanel.isHidden = w == 0
+ sidePanelHandle.isHidden = w == 0
+ guard w > 0 else { onSidePanelFrame?(nil); return }
+ let gap = SplitPaneLayout.Constants.gap
+ let f = NSRect(x: cb.maxX - w, y: cb.minY, width: w, height: cb.height)
+ if sidePanel.frame != f { sidePanel.frame = f }
+ sidePanel.cornerRadius = edgeToEdge ? 0 : CraMetrics.contentCornerRadius
+ sidePanel.castsShadow = !edgeToEdge
+ sidePanel.layoutSubtreeIfNeeded()
+ // The handle covers the gap and reaches a little into the cards on both sides.
+ sidePanelHandle.frame = NSRect(x: f.minX - gap - 3, y: cb.minY, width: gap + 6, height: cb.height)
+ onSidePanelFrame?(contentContainer.convert(sidePanel.convert(sidePanel.pageArea.frame, to: contentContainer), to: nil))
+ }
+
/// Chrome-style hosting: the status bubble moves into a click-through panel above the
/// page windows; the find bar, which takes clicks, into its own panel just its size, which
/// the window controller places.
diff --git a/Sources/Cra/UI/Windows/ExtensionSidePanel.swift b/Sources/Cra/UI/Windows/ExtensionSidePanel.swift
new file mode 100644
index 0000000..3979a75
--- /dev/null
+++ b/Sources/Cra/UI/Windows/ExtensionSidePanel.swift
@@ -0,0 +1,352 @@
+import AppKit
+import CraCEF
+
+/// An extension's side panel (Chrome's chrome.sidePanel) as a card on the right of the window's
+/// panes: a header with the extension's icon, name and a close button, and the panel page under
+/// it. Arc has no side panel, so extensions that open in one (MetaMask by default) did nothing
+/// there; Chrome shows it beside the page, and so does Cra.
+final class ExtensionSidePanelCard: NSView {
+ static let headerHeight: CGFloat = 36
+
+ /// Where the panel page's views go (EmbeddedPages), or where its window is laid over.
+ let pageArea = NSView()
+ private let header = NSView()
+ private let icon = NSImageView()
+ private let title = NSTextField(labelWithString: "")
+ let closeButton = ToolbarGlyphButton()
+ private let hairline = NSView()
+ private let shadowView = CardShadowView()
+ var cornerRadius: CGFloat = CraMetrics.contentCornerRadius {
+ didSet { layer?.cornerRadius = cornerRadius; syncShadow() }
+ }
+ var castsShadow = true { didSet { syncShadow() } }
+ private var appearanceObservation: NSKeyValueObservation?
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.cornerRadius = cornerRadius
+ layer?.cornerCurve = .continuous
+ layer?.masksToBounds = true
+ pageArea.wantsLayer = true
+ pageArea.autoresizesSubviews = false
+ hairline.wantsLayer = true
+ icon.imageScaling = .scaleProportionallyUpOrDown
+ title.font = .systemFont(ofSize: 13, weight: .medium)
+ title.lineBreakMode = .byTruncatingTail
+ title.cell?.usesSingleLineMode = true
+ header.addSubview(icon)
+ header.addSubview(title)
+ header.addSubview(closeButton)
+ addSubview(pageArea)
+ addSubview(header)
+ addSubview(hairline)
+ refreshColors()
+ appearanceObservation = NSApp.observe(\.effectiveAppearance) { [weak self] _, _ in
+ MainActor.assumeIsolated { self?.refreshColors() }
+ }
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ func show(name: String, icon image: NSImage?) {
+ title.stringValue = name
+ icon.image = image ?? SidebarSymbols.image("puzzlepiece.extension", size: 14)
+ refreshColors()
+ }
+
+ /// The panel page follows the app's appearance, as pages do; the header matches it.
+ private func refreshColors() {
+ let dark = NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ layer?.backgroundColor = CraBrowser.pageCanvasColor.cgColor
+ header.wantsLayer = true
+ header.layer?.backgroundColor = CraBrowser.pageCanvasColor.cgColor
+ let ink = dark ? NSColor(white: 1, alpha: 0.85) : NSColor(white: 0, alpha: 0.8)
+ title.textColor = ink
+ hairline.layer?.backgroundColor = NSColor(white: dark ? 1 : 0, alpha: 0.08).cgColor
+ closeButton.configure(symbol: "xmark", image: nil, help: "Close Side Panel", enabled: true, width: 26, iconSize: 11,
+ tint: ink.withAlphaComponent(0.7), hover: NSColor(white: dark ? 1 : 0, alpha: 0.08))
+ }
+
+ override func layout() {
+ super.layout()
+ let b = bounds, h = Self.headerHeight
+ header.frame = NSRect(x: 0, y: b.height - h, width: b.width, height: h)
+ icon.frame = NSRect(x: 12, y: (h - 16) / 2, width: 16, height: 16)
+ closeButton.frame = NSRect(x: b.width - 8 - 26, y: (h - 26) / 2, width: 26, height: 26)
+ let titleH = ceil(title.intrinsicContentSize.height)
+ title.frame = NSRect(x: icon.frame.maxX + 8, y: (h - titleH) / 2, width: max(0, closeButton.frame.minX - icon.frame.maxX - 16), height: titleH)
+ hairline.frame = NSRect(x: 0, y: b.height - h - 1, width: b.width, height: 1)
+ pageArea.frame = NSRect(x: 0, y: 0, width: b.width, height: max(0, b.height - h - 1))
+ for sub in pageArea.subviews where sub.frame != pageArea.bounds { sub.frame = pageArea.bounds }
+ }
+
+ // The same shadow as a page card (PaneCardView): a sibling behind it.
+ override func viewDidMoveToSuperview() {
+ super.viewDidMoveToSuperview()
+ if let superview {
+ if shadowView.superview !== superview { superview.addSubview(shadowView, positioned: .below, relativeTo: self) }
+ } else {
+ shadowView.removeFromSuperview()
+ }
+ syncShadow()
+ }
+
+ override func setFrameOrigin(_ newOrigin: NSPoint) { super.setFrameOrigin(newOrigin); syncShadow() }
+ override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize); syncShadow() }
+ override var isHidden: Bool { didSet { syncShadow() } }
+
+ private func syncShadow() {
+ let on = castsShadow && cornerRadius > 0 && !isHidden && superview != nil
+ shadowView.isHidden = !on
+ guard on else { return }
+ shadowView.cornerRadius = cornerRadius
+ let f = frame.insetBy(dx: -CardShadowView.pad, dy: -CardShadowView.pad)
+ if shadowView.frame != f { shadowView.frame = f }
+ }
+}
+
+/// One main window's extension side panel: shows, swaps and hides the panel page as extensions
+/// ask (ExtensionSidePanelRequest decides), in its own Cra browser on the asking page's profile.
+@MainActor
+final class ExtensionSidePanelController: NSObject, @preconcurrency CraBrowserDelegate {
+ private unowned let app: AppDelegate
+ private unowned let shell: ShellView
+ private weak var owner: MainWindowController?
+ private var mainWindow: NSWindow? { owner?.window }
+ private(set) var state: ExtensionSidePanelState?
+ private var browser: CraBrowser?
+ /// The panel page's own page target, so a request from the panel itself
+ /// (chrome.sidePanel.close() in it) finds this window.
+ private(set) var pageTarget: String?
+ /// The page's area in window coordinates, nil while the shell shows no panel.
+ private var bodyRect: NSRect?
+ /// Page windows already made borderless and adopted (weakly keyed by identity; one per browser).
+ private var attachedOnce: Set<ObjectIdentifier> = []
+
+ private static let widthKey = "extensionSidePanelWidth"
+ static var savedWidth: CGFloat {
+ get { CGFloat(UserDefaults.standard.object(forKey: widthKey) as? Double ?? ExtensionSidePanelWidth.initial) }
+ set { UserDefaults.standard.set(Double(newValue), forKey: widthKey) }
+ }
+
+ init(app: AppDelegate, shell: ShellView, owner: MainWindowController) {
+ self.app = app
+ self.shell = shell
+ self.owner = owner
+ super.init()
+ shell.sidePanel.closeButton.action = { [weak self] in self?.hide() }
+ shell.onSidePanelFrame = { [weak self] rect in self?.place(rect) }
+ shell.sidePanelHandle.onDrag = { [weak self] dx in self?.resize(by: dx) }
+ }
+
+ var isShowing: Bool { state != nil }
+
+ /// Owns the browser `b` (the panel page).
+ func owns(_ b: CraBrowser) -> Bool { browser === b }
+
+ /// `profilePath`: the asking page's profile folder (nil = Default), where the panel loads.
+ func handle(_ request: ExtensionSidePanelRequest, profilePath: String?) {
+ switch request.change(from: state) {
+ case .none: return
+ case .hide: hide()
+ case .show(let wanted): show(wanted, profilePath: profilePath)
+ }
+ }
+
+ private func show(_ wanted: ExtensionSidePanelState, profilePath: String?) {
+ let sameExtension = state.map { $0.extensionID == wanted.extensionID && $0.profile == wanted.profile } ?? false
+ state = wanted
+ CraLog.note("side panel shows \(wanted.extensionID) in \(wanted.profile)")
+ let entry = ExtensionStore.shared.entries.first { $0.extensionID == wanted.extensionID }
+ shell.sidePanel.show(name: entry?.name ?? "Extension", icon: entry?.icon)
+ if sameExtension, let browser {
+ // Another page of the same panel (chrome.sidePanel.setOptions with a new path).
+ browser.loadURL(wanted.url)
+ } else {
+ closeBrowser()
+ let b = CraBrowser(frame: NSRect(x: 0, y: 0, width: ExtensionSidePanelWidth.initial, height: 600), url: wanted.url,
+ delegate: self, incognito: false, profilePath: profilePath)
+ browser = b
+ if let host = b.hostWindow { attach(host) }
+ Task { [weak self] in await self?.resolvePageTarget(of: b) }
+ }
+ shell.sidePanelWidth = Self.savedWidth
+ }
+
+ func hide() {
+ guard let shown = state else { return }
+ CraLog.note("side panel hides \(shown.extensionID)")
+ state = nil
+ closeBrowser()
+ shell.sidePanelWidth = 0
+ }
+
+ private func closeBrowser() {
+ pageTarget = nil
+ attachedOnce.removeAll()
+ guard let b = browser else { return }
+ browser = nil
+ if let host = b.hostWindow {
+ if let views = EmbeddedPages.pageViews(of: host) { for v in views { v.removeFromSuperview() } }
+ host.parent?.removeChildWindow(host)
+ host.orderOut(nil)
+ }
+ b.close()
+ }
+
+ private func resolvePageTarget(of b: CraBrowser) async {
+ let info: [String: Any]? = await withCheckedContinuation { cont in
+ b.sendDevToolsMethod("Target.getTargetInfo", params: "{}") { result, _ in
+ cont.resume(returning: result.flatMap { try? JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any] })
+ }
+ }
+ guard browser === b else { return }
+ pageTarget = (info?["targetInfo"] as? [String: Any])?["targetId"] as? String
+ }
+
+ private func resize(by dx: CGFloat) {
+ let container = Double(shell.contentContainer.bounds.width)
+ let w = ExtensionSidePanelWidth.clamp(Double(shell.sidePanelWidth - dx), container: container, gap: Double(SplitPaneLayout.Constants.gap),
+ pages: shell.sidePanelPageMinimum)
+ Self.savedWidth = CGFloat(w)
+ shell.sidePanelWidth = CGFloat(w)
+ }
+
+ // MARK: Page placement
+
+ /// Like a tab's page (MainWindowController.browserManagerPageWindowsChanged): Chrome's window
+ /// stays, borderless and empty, over the panel; its page views move into the card.
+ private func attach(_ host: NSWindow) {
+ guard let mainWindow, attachedOnce.insert(ObjectIdentifier(host)).inserted else { return }
+ host.styleMask.remove([.titled, .resizable])
+ host.styleMask.insert(.fullSizeContentView)
+ ChromiumWindowCorners.setSquare(true, for: host)
+ ChromiumChildHover.setDocked(true, for: host)
+ host.titlebarAppearsTransparent = true
+ host.titleVisibility = .hidden
+ host.isMovable = false
+ host.hasShadow = false
+ host.isOpaque = false
+ host.backgroundColor = .clear
+ if let cv = host.contentView {
+ cv.wantsLayer = true
+ cv.layer?.cornerRadius = CraMetrics.contentCornerRadius
+ cv.layer?.cornerCurve = .continuous
+ cv.layer?.maskedCorners = cv.isFlipped ? [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] : [.layerMinXMinYCorner, .layerMaxXMinYCorner]
+ cv.layer?.masksToBounds = true
+ }
+ mainWindow.addChildWindow(host, ordered: .above)
+ // Shown and raised under the overlay panels there, or ordered out while the panel has no room.
+ place(bodyRect)
+ if host.isVisible { owner?.sidePanelPageAttached() }
+ }
+
+ private func place(_ rect: NSRect?) {
+ bodyRect = rect
+ guard let mainWindow, let host = browser?.hostWindow, attachedOnce.contains(ObjectIdentifier(host)) else { return }
+ guard let rect else {
+ // The panel does not fit (a narrow window, a page in full screen): out of sight, as
+ // a hidden tab's window is. Left on screen it stayed where the panel was, outside
+ // a window that had just shrunk.
+ host.contentView?.isHidden = true
+ if let views = EmbeddedPages.pageViews(of: host) { for v in views { v.removeFromSuperview() } }
+ if host.isVisible { host.orderOut(nil) }
+ return
+ }
+ // Back from hidden: ordering out can take a child window off its parent.
+ if host.parent !== mainWindow { mainWindow.addChildWindow(host, ordered: .above) }
+ let target = mainWindow.convertToScreen(rect)
+ if host.frame != target { host.setFrame(target, display: false) }
+ if let cv = host.contentView, cv.frame.size != target.size { cv.frame = NSRect(origin: .zero, size: target.size) }
+ host.contentView?.isHidden = false
+ if !host.isVisible {
+ host.orderFront(nil)
+ owner?.sidePanelPageAttached()
+ }
+ guard EmbeddedPages.isEnabled, let views = EmbeddedPages.pageViews(of: host) else { return }
+ EmbeddedPages.markHost(host)
+ let area = shell.sidePanel.pageArea
+ if views.contains(where: { $0.superview !== area }) { for v in views { area.addSubview(v) } }
+ for v in views where v.frame != area.bounds { v.frame = area.bounds }
+ }
+
+ /// The panel page's views (embedded in the card), so the window keeps its focus there.
+ var embeddedViews: [NSView] {
+ guard let host = browser?.hostWindow else { return [] }
+ return EmbeddedPages.pageViews(of: host) ?? []
+ }
+
+ // MARK: CraBrowserDelegate
+
+ func browser(_ browser: CraBrowser, didChangeTitle title: String) {}
+ func browser(_ browser: CraBrowser, didChangeURL url: String) {}
+ func browser(_ browser: CraBrowser, didChangeLoading loading: Bool, canGoBack: Bool, canGoForward: Bool) {}
+ func browser(_ browser: CraBrowser, didChangeProgress progress: Double) {}
+ func browser(_ browser: CraBrowser, didFinishLoadingURL url: String, title: String, statusCode: Int) {}
+ func browser(_ browser: CraBrowser, didLoadFavicon image: NSImage, forURL iconURL: String) {}
+ func browser(_ browser: CraBrowser, didChangeStatusMessage message: String) {}
+ func browser(_ browser: CraBrowser, didReportThemeColor hex: String) {}
+ func browser(_ browser: CraBrowser, didChangeFullscreen fullscreen: Bool) {}
+ /// Links the panel opens go to tabs in this window, as Chrome opens them in its window.
+ func browser(_ browser: CraBrowser, requestsNewTabWithURL url: String, inBackground background: Bool) {
+ openTab(url, select: !background)
+ }
+ func browser(_ browser: CraBrowser, popupHostForURL url: String, inBackground background: Bool) -> CraBrowser? {
+ openTab(url, select: !background)
+ return nil
+ }
+ private func openTab(_ url: String, select: Bool) {
+ guard let owner else { return }
+ app.store.createTab(url: url, select: select, window: owner.windowID)
+ }
+ func devToolsHostView(for browser: CraBrowser) -> NSView? { nil }
+ func browser(_ browser: CraBrowser, didCreateDevToolsView view: NSView) {}
+ func browserDidCloseDevTools(_ browser: CraBrowser) {}
+ func browser(_ browser: CraBrowser, didCreateHostWindow window: NSWindow) {
+ guard self.browser === browser else { return }
+ attach(window)
+ }
+ func browser(_ browser: CraBrowser, devToolsPageBounds bounds: NSRect) {}
+ func browser(_ browser: CraBrowser, devToolsDocked docked: Bool) {}
+ func browser(_ browser: CraBrowser, handleKeyEvent event: NSEvent) -> Bool { app.handleReservedKey(event) }
+ func browser(_ browser: CraBrowser, handleUnhandledKeyEvent event: NSEvent) -> Bool { app.handleUnhandledKey(event) }
+ func browser(_ browser: CraBrowser, didUpdateDownload download: CraDownloadInfo) { app.main.browserManager(download: download) }
+ func browser(_ browser: CraBrowser, requestsPermissionForOrigin origin: String, kinds: UInt, completion: @escaping (Bool) -> Void) {
+ completion(false)
+ }
+ func browserDidReceiveFocus(_ browser: CraBrowser) {}
+ /// window.close() in the panel page (MetaMask's "switch to popup view" does it): the panel goes.
+ func browserDidClose(_ browser: CraBrowser) {
+ guard self.browser === browser else { return }
+ CraLog.note("side panel page closed itself")
+ self.browser = nil
+ state = nil
+ pageTarget = nil
+ attachedOnce.removeAll()
+ if let host = browser.hostWindow {
+ if let views = EmbeddedPages.pageViews(of: host) { for v in views { v.removeFromSuperview() } }
+ host.parent?.removeChildWindow(host)
+ }
+ shell.sidePanelWidth = 0
+ }
+}
+
+extension ExtensionSidePanelController {
+ /// The window a request is for: the one whose panel page asked, else the one showing the
+ /// asking tab, else the window in use (a Little Window's page). The panel loads in the
+ /// asking page's profile.
+ static func route(_ request: ExtensionSidePanelRequest, tab: UUID?, app: AppDelegate) {
+ let windows = app.mainWindows
+ let owner = windows.first { $0.sidePanel.pageTarget == request.targetID }
+ ?? tab.flatMap { id in windows.first { $0.browsers.runtime(for: id) != nil } }
+ ?? app.main
+ owner?.sidePanel.handle(request, profilePath: profilePath(request.profile))
+ }
+
+ /// Chromium's profile folder name as CraBrowser takes it: nil for Default.
+ static func profilePath(_ directoryName: String) -> String? {
+ directoryName == "Default" || directoryName.isEmpty ? nil
+ : AppPaths.chromiumCache.appendingPathComponent(directoryName, isDirectory: true).path
+ }
+}
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 45d99f6..73b5581 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -56,6 +56,12 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
var currentBrowser: CraBrowser? { browsers.visibleRuntime?.browser }
+ /// The window's extension side panel (chrome.sidePanel; Chrome's, which Arc lacks).
+ private(set) lazy var sidePanel = ExtensionSidePanelController(app: app, shell: shell, owner: self)
+
+ /// The side panel's page window joined this window's children: the overlay panels stay above it.
+ func sidePanelPageAttached() { raiseOverlayPanels() }
+
/// This window's entry in the store (WindowSession): its space, open tabs, frame.
let windowID: UUID
/// Pages load in the off-the-record profile; nothing is saved (WindowSession.isIncognito).
@@ -329,6 +335,10 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
ExtensionActions.shared.watchActions { [weak app] in
app?.mainWindows.flatMap { $0.browsers.runtimes.values.map { (tab: $0.tabID, browser: $0.browser) } } ?? []
}
+ ExtensionActions.shared.sidePanelHandler = { [weak app] request, tab in
+ guard let app else { return }
+ ExtensionSidePanelController.route(request, tab: tab, app: app)
+ }
browsers.nowPlaying = sidebarUI.nowPlaying
sidebarUI.nowPlaying.perform = { [weak self] id, action in
guard let self else { return }
@@ -934,7 +944,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
guard EmbeddedPages.isEnabled, let window, let responder = window.firstResponder as? NSView,
NSStringFromClass(type(of: responder)) == "RenderWidgetHostViewCocoa" else { return }
let focused = browsers.visibleTabID.flatMap { browsers.runtime(for: $0)?.hostWindow }.flatMap(EmbeddedPages.pageViews(of:)) ?? []
- if !focused.contains(where: { responder.isDescendant(of: $0) }) { window.makeFirstResponder(nil) }
+ // The extension side panel's page keeps the keys it has.
+ let panel = sidePanel.isShowing ? sidePanel.embeddedViews : []
+ if !(focused + panel).contains(where: { responder.isDescendant(of: $0) }) { window.makeFirstResponder(nil) }
}
/// The tab whose embedded page should take keyboard focus once it is in its card.
@@ -2860,6 +2872,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func tearDown() {
isTornDown = true
dismissTransientUI()
+ sidePanel.hide()
for p in peeks { p.closeWindow() }
// A page another window shows behind its blurred stand-in moves there with its history
// and state; closed with this window, that window loaded it again from scratch.
diff --git a/Tests/Fixtures/SidePanelExtension/ID b/Tests/Fixtures/SidePanelExtension/ID
new file mode 100644
index 0000000..de1bd20
--- /dev/null
+++ b/Tests/Fixtures/SidePanelExtension/ID
@@ -0,0 +1 @@
+mdmoahljgbbmpomiaogbjkgijinlckad
diff --git a/Tests/Fixtures/SidePanelExtension/manifest.json b/Tests/Fixtures/SidePanelExtension/manifest.json
new file mode 100644
index 0000000..27d850d
--- /dev/null
+++ b/Tests/Fixtures/SidePanelExtension/manifest.json
@@ -0,0 +1,11 @@
+{
+ "manifest_version": 3,
+ "name": "Cra Side Panel Fixture",
+ "version": "1.0",
+ "description": "Made up for scripts/scenario.sh: like MetaMask, a popup in the manifest but the toolbar button opens the side panel.",
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApW4QzzYh7p/Zl9rDQ7QsEI6hg9GDXQwlQ6Qj5Gphj9vje+JODZduUy5zsLcSdpkeprcEjvflwKnCGknSsMSgzN8Gtk+R7pCOvsR77iAK3zCS3PBLQldI+65XlFjTf/SzjsioaimAs9m/lMRQV98gnkc6EmWxmglJSD3AyiuHcfCTcd8ylpl002ukh3s+45rdzoB64DpsvGY6oqNDe4+wPSJQTDTjd43CBARk1BTQmqsRMhj2NB0X/SRDc4fMRtAg0ZoFfSW91/buIIqlI3wuqy7P6Jfr73xQWWfhmFUSPQyzxjQmC/njtqY2ACfwyVbEZmlz+xogdWB7hZeJ4nuttwIDAQAB",
+ "permissions": ["sidePanel"],
+ "background": { "service_worker": "worker.js" },
+ "action": { "default_popup": "popup.html", "default_title": "Cra Side Panel Fixture" },
+ "side_panel": { "default_path": "panel.html" }
+}
diff --git a/Tests/Fixtures/SidePanelExtension/panel.html b/Tests/Fixtures/SidePanelExtension/panel.html
new file mode 100644
index 0000000..03776a8
--- /dev/null
+++ b/Tests/Fixtures/SidePanelExtension/panel.html
@@ -0,0 +1,9 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Side Panel Fixture</title>
+<body style="font: 14px system-ui; margin: 16px">
+<h1 style="font-size: 16px">Side panel</h1>
+<p>Opened by the toolbar button.</p>
+<button id="close">window.close()</button>
+<script src="panel.js"></script>
+</body>
diff --git a/Tests/Fixtures/SidePanelExtension/panel.js b/Tests/Fixtures/SidePanelExtension/panel.js
new file mode 100644
index 0000000..af1dec5
--- /dev/null
+++ b/Tests/Fixtures/SidePanelExtension/panel.js
@@ -0,0 +1 @@
+document.getElementById('close').addEventListener('click', () => window.close());
diff --git a/Tests/Fixtures/SidePanelExtension/popup.html b/Tests/Fixtures/SidePanelExtension/popup.html
new file mode 100644
index 0000000..397be18
--- /dev/null
+++ b/Tests/Fixtures/SidePanelExtension/popup.html
@@ -0,0 +1,3 @@
+<!doctype html>
+<meta charset="utf-8">
+<body style="width: 200px; font: 14px system-ui">Popup (the side panel should open instead)</body>
diff --git a/Tests/Fixtures/SidePanelExtension/worker.js b/Tests/Fixtures/SidePanelExtension/worker.js
new file mode 100644
index 0000000..0819d0d
--- /dev/null
+++ b/Tests/Fixtures/SidePanelExtension/worker.js
@@ -0,0 +1,2 @@
+// MetaMask does this on start-up: the toolbar button opens the side panel, not the popup.
+chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
diff --git a/Tests/Scenarios/extension-side-panel.scenario b/Tests/Scenarios/extension-side-panel.scenario
new file mode 100644
index 0000000..10cbad7
--- /dev/null
+++ b/Tests/Scenarios/extension-side-panel.scenario
@@ -0,0 +1,28 @@
+# An extension whose toolbar button opens Chrome's side panel (openPanelOnActionClick), as
+# MetaMask's does by default. Chrome's own panel never shows in CEF, so the click did nothing,
+# in Cra as in Arc; Cra now shows the panel beside the page. A second click closes it, and so
+# does the panel's close button (sidePanel=close), after which a click opens it again.
+budget rss=700 stalls50=5
+cra://debug?installExtension=${FIXTURES}/SidePanelExtension
+relaunch
+cra://open?url=${PAGE}?n=panel
+wait 3
+cra://debug?extensionAction=${SIDE_PANEL_EXTENSION_ID}
+expect-log side panel shows ${SIDE_PANEL_EXTENSION_ID} in Default
+wait 2
+cra://debug?extensionAction=${SIDE_PANEL_EXTENSION_ID}
+expect-log side panel hides ${SIDE_PANEL_EXTENSION_ID}
+wait 1
+cra://debug?extensionAction=${SIDE_PANEL_EXTENSION_ID}
+wait 2
+cra://debug?windowSize=900x700
+wait 1
+cra://debug?windowSize=1400x880
+wait 1
+cra://debug?sidePanel=close
+wait 1
+cra://debug?extensionAction=${SIDE_PANEL_EXTENSION_ID}
+wait 2
+cra://debug?removeExtension=${SIDE_PANEL_EXTENSION_ID}
+wait 1
+reject-log fault:
diff --git a/scripts/cef-patches/extension-side-panels.patch b/scripts/cef-patches/extension-side-panels.patch
new file mode 100644
index 0000000..2c6f703
--- /dev/null
+++ b/scripts/cef-patches/extension-side-panels.patch
@@ -0,0 +1,133 @@
+diff --git a/chrome/browser/ui/extensions/extension_side_panel_utils.cc b/chrome/browser/ui/extensions/extension_side_panel_utils.cc
+--- a/chrome/browser/ui/extensions/extension_side_panel_utils.cc
++++ b/chrome/browser/ui/extensions/extension_side_panel_utils.cc
+@@ -20,6 +20,10 @@
+ #include "chrome/browser/ui/views/tabs/organizer/organizer_panel_utils.h"
+ #endif
+
++#if BUILDFLAG(ENABLE_CEF)
++#include "cef/libcef/browser/chrome/browser_delegate.h"
++#endif
++
+ namespace extensions::side_panel_util {
+
+ namespace {
+@@ -43,6 +47,32 @@ SidePanelRegistry* GetTabRegistry(content::WebContents* web_contents) {
+ return GetTabRegistry(tabs::TabInterface::MaybeGetFromContents(web_contents));
+ }
+
++// Cra: see SetCraSidePanelHandler.
++CraSidePanelHandler g_cra_side_panel_handler = nullptr;
++
++// Cra: hands the request to Cra when `browser_window` is a page CEF hosts.
++// `web_contents` defaults to the window's active page. True when Cra took it.
++bool ForwardToCra(BrowserWindowInterface* browser_window,
++ content::WebContents* web_contents,
++ const ExtensionId& extension_id,
++ CraSidePanelRequest request) {
++#if BUILDFLAG(ENABLE_CEF)
++ if (!g_cra_side_panel_handler || !browser_window ||
++ !browser_window->cef_delegate() ||
++ !browser_window->cef_delegate()->IsViewsHosted()) {
++ return false;
++ }
++ if (!web_contents) {
++ tabs::TabInterface* tab = GetActiveTab(browser_window);
++ web_contents = tab ? tab->GetContents() : nullptr;
++ }
++ return web_contents &&
++ g_cra_side_panel_handler(web_contents, extension_id, request);
++#else
++ return false;
++#endif
++}
++
+ // Returns true if `registry` exists and has an active entry whose key matches
+ // the provided `key`.
+ bool IsKeyActiveInRegistry(SidePanelRegistry* registry,
+@@ -56,12 +86,20 @@ bool IsKeyActiveInRegistry(SidePanelRegistry* registry,
+
+ } // namespace
+
++void SetCraSidePanelHandler(CraSidePanelHandler handler) {
++ g_cra_side_panel_handler = handler;
++}
++
+ // Defined in extension_side_panel_utils.h
+ void ToggleExtensionSidePanel(BrowserWindowInterface* browser_window,
+ const ExtensionId& extension_id) {
+ if (!browser_window) {
+ return;
+ }
++ if (ForwardToCra(browser_window, nullptr, extension_id,
++ CraSidePanelRequest::kToggle)) {
++ return;
++ }
+
+ #if BUILDFLAG(ENABLE_EXTENSIONS)
+ auto* organizer_controller =
+@@ -88,6 +126,10 @@ void ToggleExtensionSidePanel(BrowserWindowInterface* browser_window,
+ void OpenGlobalExtensionSidePanel(BrowserWindowInterface& browser_window,
+ content::WebContents* web_contents,
+ const ExtensionId& extension_id) {
++ if (ForwardToCra(&browser_window, web_contents, extension_id,
++ CraSidePanelRequest::kOpen)) {
++ return;
++ }
+ #if BUILDFLAG(ENABLE_EXTENSIONS)
+ auto* organizer_controller =
+ organizer_panel::IsShowExtensionsSidePanelUiInOrganizerPanelEnabled()
+@@ -172,6 +214,10 @@ void OpenGlobalExtensionSidePanel(BrowserWindowInterface& browser_window,
+ void OpenContextualExtensionSidePanel(BrowserWindowInterface& browser_window,
+ content::WebContents& web_contents,
+ const ExtensionId& extension_id) {
++ if (ForwardToCra(&browser_window, &web_contents, extension_id,
++ CraSidePanelRequest::kOpen)) {
++ return;
++ }
+ #if BUILDFLAG(ENABLE_EXTENSIONS)
+ auto* organizer_controller =
+ organizer_panel::IsShowExtensionsSidePanelUiInOrganizerPanelEnabled()
+@@ -213,6 +259,10 @@ void CloseGlobalExtensionSidePanel(BrowserWindowInterface* browser_window,
+ if (!browser_window) {
+ return;
+ }
++ if (ForwardToCra(browser_window, nullptr, extension_id,
++ CraSidePanelRequest::kClose)) {
++ return;
++ }
+
+ #if BUILDFLAG(ENABLE_EXTENSIONS)
+ auto* organizer_controller =
+@@ -261,6 +311,10 @@ void CloseContextualExtensionSidePanel(BrowserWindowInterface* browser_window,
+ if (!browser_window || !web_contents) {
+ return;
+ }
++ if (ForwardToCra(browser_window, web_contents, extension_id,
++ CraSidePanelRequest::kClose)) {
++ return;
++ }
+
+ #if BUILDFLAG(ENABLE_EXTENSIONS)
+ auto* organizer_controller =
+diff --git a/chrome/browser/ui/extensions/extension_side_panel_utils.h b/chrome/browser/ui/extensions/extension_side_panel_utils.h
+--- a/chrome/browser/ui/extensions/extension_side_panel_utils.h
++++ b/chrome/browser/ui/extensions/extension_side_panel_utils.h
+@@ -17,6 +17,17 @@ class WebContents;
+
+ namespace extensions::side_panel_util {
+
++// Cra: Cra shows extension side panels in its own windows. While a handler is
++// set, a request for a browser that CEF hosts in a views window goes to it
++// (with that browser's active page) instead of to Chrome's side panel, which
++// CEF's hidden browser view never shows. The handler returns false to leave
++// the request to Chrome.
++enum class CraSidePanelRequest { kToggle, kOpen, kClose };
++using CraSidePanelHandler = bool (*)(content::WebContents* web_contents,
++ const ExtensionId& extension_id,
++ CraSidePanelRequest request);
++void SetCraSidePanelHandler(CraSidePanelHandler handler);
++
+ // Toggles the side panel for the given `extension_id` in `browser_window`,
+ // opening the panel if it is closed and closing it if it is open.
+ void ToggleExtensionSidePanel(BrowserWindowInterface* browser_window,
diff --git a/scripts/cef-patches/extensions-action-updates.patch b/scripts/cef-patches/extensions-action-updates.patch
index a695772..5af9c14 100644
--- a/scripts/cef-patches/extensions-action-updates.patch
+++ b/scripts/cef-patches/extensions-action-updates.patch
@@ -13,13 +13,17 @@ diff --git a/chrome/browser/devtools/inspector_protocol_config.json b/chrome/bro
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 @@
+@@ -5,17 +5,26 @@
+ #include "chrome/browser/devtools/protocol/extensions_handler.h"
+
#include <memory>
++#include <set>
#include <string>
+#include "base/base64.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
++#include "base/no_destructor.h"
+#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
+#include "chrome/browser/browser_process.h"
@@ -28,6 +32,7 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.cc b/chrome/bro
#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/api/side_panel/side_panel_service.h"
+#include "chrome/browser/extensions/extension_action_dispatcher.h"
+#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_util.h"
@@ -35,7 +40,7 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.cc b/chrome/bro
#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 @@
+@@ -23,9 +32,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"
@@ -51,7 +56,7 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.cc b/chrome/bro
namespace {
-@@ -160,7 +172,194 @@
+@@ -160,8 +175,269 @@ GetExtensionAndStorageFrontendResult GetExtensionAndStorageFrontend(
return result;
}
@@ -79,6 +84,13 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.cc b/chrome/bro
+}
+
} // namespace
+
++// Cra: the handlers with action updates on, which also take side panel
++// requests.
++std::set<ExtensionsHandler*>& SidePanelHandlers() {
++ static base::NoDestructor<std::set<ExtensionsHandler*>> handlers;
++ return *handlers;
++}
+
+// Cra: forwards one profile's action changes to the handler.
+class ExtensionsHandler::ActionWatch
@@ -119,8 +131,12 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.cc b/chrome/bro
+ action_watches_.clear();
+ profile_manager_observation_.Reset();
+ reported_actions_.clear();
++ SidePanelHandlers().erase(this);
+ return protocol::Response::Success();
+ }
++ SidePanelHandlers().insert(this);
++ extensions::side_panel_util::SetCraSidePanelHandler(
++ &ExtensionsHandler::ForwardSidePanelRequest);
+ ProfileManager* profile_manager = g_browser_process->profile_manager();
+ if (!profile_manager) {
+ return protocol::Response::ServerError("No profile manager.");
@@ -243,10 +259,74 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.cc b/chrome/bro
+ badge_text, badge_color, badge_text_color,
+ std::move(target_id));
+}
-
++
++// static
++bool ExtensionsHandler::ForwardSidePanelRequest(
++ content::WebContents* web_contents,
++ const extensions::ExtensionId& extension_id,
++ extensions::side_panel_util::CraSidePanelRequest request) {
++ bool taken = false;
++ // A copy: a handler can't go away while it reports, but stay safe.
++ const std::set<ExtensionsHandler*> handlers = SidePanelHandlers();
++ for (ExtensionsHandler* handler : handlers) {
++ taken = handler->ReportSidePanelRequest(web_contents, extension_id,
++ request) ||
++ taken;
++ }
++ return taken;
++}
++
++// Reports the request with the panel page for `web_contents`'s tab; false
++// (Chrome keeps it) when the extension has no panel enabled there.
++bool ExtensionsHandler::ReportSidePanelRequest(
++ content::WebContents* web_contents,
++ const extensions::ExtensionId& extension_id,
++ extensions::side_panel_util::CraSidePanelRequest request) {
++ using Request = extensions::side_panel_util::CraSidePanelRequest;
++ if (!frontend_ || !web_contents) {
++ return false;
++ }
++ content::BrowserContext* context = web_contents->GetBrowserContext();
++ extensions::ExtensionRegistry* registry =
++ extensions::ExtensionRegistry::Get(context);
++ const extensions::Extension* extension =
++ registry ? registry->enabled_extensions().GetByID(extension_id)
++ : nullptr;
++ if (!extension) {
++ return false;
++ }
++ std::string url;
++ if (request != Request::kClose) {
++ extensions::SidePanelService* service =
++ extensions::SidePanelService::Get(context);
++ if (!service) {
++ return false;
++ }
++ extensions::api::side_panel::PanelOptions options = service->GetOptions(
++ *extension, extensions::ExtensionTabUtil::GetTabId(web_contents));
++ if (!options.path || options.path->empty() ||
++ (options.enabled.has_value() && !*options.enabled)) {
++ return false;
++ }
++ url = extension->ResolveExtensionURL(*options.path).spec();
++ }
++ const std::string profile = Profile::FromBrowserContext(context)
++ ->GetOriginalProfile()
++ ->GetBaseName()
++ .AsUTF8Unsafe();
++ const std::string kind = request == Request::kToggle ? "toggle"
++ : request == Request::kOpen ? "open"
++ : "close";
++ frontend_->SidePanelRequested(
++ extension_id, profile, kind, url,
++ content::DevToolsAgentHost::GetOrCreateFor(web_contents)->GetId());
++ return true;
++}
++
protocol::DispatchResponse ExtensionsHandler::TriggerAction(
const std::string& extension_id,
-@@ -219,6 +418,9 @@
+ const std::string& target_id) {
+@@ -219,9 +495,14 @@ ExtensionsHandler::ExtensionsHandler(protocol::UberDispatcher* dispatcher,
: target_id_(target_id),
allow_loading_extensions_(allow_loading_extensions) {
protocol::Extensions::Dispatcher::wire(dispatcher, this);
@@ -255,11 +335,17 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.cc b/chrome/bro
+ std::make_unique<protocol::Extensions::Frontend>(dispatcher->channel());
}
- ExtensionsHandler::~ExtensionsHandler() = default;
+-ExtensionsHandler::~ExtensionsHandler() = default;
++ExtensionsHandler::~ExtensionsHandler() {
++ SidePanelHandlers().erase(this);
++}
+
+ void ExtensionsHandler::LoadUnpacked(
+ const protocol::String& path,
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 @@
+@@ -5,13 +5,32 @@
#ifndef CHROME_BROWSER_DEVTOOLS_PROTOCOL_EXTENSIONS_HANDLER_H_
#define CHROME_BROWSER_DEVTOOLS_PROTOCOL_EXTENSIONS_HANDLER_H_
@@ -271,6 +357,7 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.h b/chrome/brow
#include "chrome/browser/devtools/protocol/protocol.h"
+#include "chrome/browser/profiles/profile_manager.h"
+#include "chrome/browser/profiles/profile_manager_observer.h"
++#include "chrome/browser/ui/extensions/extension_side_panel_utils.h"
#include "extensions/browser/api/storage/storage_frontend.h"
#include "extensions/common/extension.h"
@@ -292,7 +379,7 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.h b/chrome/brow
public:
explicit ExtensionsHandler(protocol::UberDispatcher* dispatcher,
const std::string& target_id,
-@@ -26,6 +44,15 @@
+@@ -26,6 +45,24 @@ class ExtensionsHandler : public protocol::Extensions::Backend {
protocol::DispatchResponse TriggerAction(
const protocol::String& extendsion_id,
const protocol::String& target_id) override;
@@ -305,10 +392,19 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.h b/chrome/brow
+ void ReportAction(const extensions::ExtensionAction& action,
+ content::WebContents* web_contents,
+ content::BrowserContext* context);
++ // Cra: sidePanelRequested, for every handler with action updates on.
++ static bool ForwardSidePanelRequest(
++ content::WebContents* web_contents,
++ const extensions::ExtensionId& extension_id,
++ extensions::side_panel_util::CraSidePanelRequest request);
++ bool ReportSidePanelRequest(
++ content::WebContents* web_contents,
++ const extensions::ExtensionId& extension_id,
++ extensions::side_panel_util::CraSidePanelRequest request);
void LoadUnpacked(const protocol::String& path,
std::optional<bool> enable_in_incognito,
std::unique_ptr<LoadUnpackedCallback> callback) override;
-@@ -83,6 +110,15 @@
+@@ -83,6 +120,15 @@ class ExtensionsHandler : public protocol::Extensions::Backend {
bool allow_loading_extensions_;
std::unique_ptr<protocol::Extensions::Frontend> frontend_;
@@ -327,7 +423,7 @@ diff --git a/chrome/browser/devtools/protocol/extensions_handler.h b/chrome/brow
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,34 @@
+@@ -22,6 +22,51 @@ experimental domain Extensions
# A tab target ID to trigger the default extension action on.
string targetId
@@ -358,6 +454,23 @@ diff --git a/third_party/blink/public/devtools_protocol/domains/Extensions.pdl b
+ # Page target of the tab the change is for; absent for the
+ # tab-independent state.
+ optional string targetId
++
++ # Cra: with action updates on, an extension's request to show, hide or toggle
++ # its side panel for a page CEF hosts (its toolbar action with
++ # openPanelOnActionClick, chrome.sidePanel.open or close) comes here instead
++ # of to Chrome's side panel, which CEF never shows.
++ event sidePanelRequested
++ parameters
++ # Extension id.
++ string id
++ # Profile directory name ("Default", "Profile 1").
++ string profile
++ # "toggle", "open" or "close".
++ string request
++ # The panel's page for that tab (chrome-extension://…); empty for "close".
++ string url
++ # Page target of the tab the request is for.
++ string targetId
+
# Installs an unpacked extension from the filesystem similar to
# --load-extension CLI flags. Returns extension ID once the extension
diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.sh
index b0f5620..c1f9660 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%%+*}-codecs11}"
+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs12}"
URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"
mkdir -p vendor
diff --git a/scripts/scenario.sh b/scripts/scenario.sh
index 57a0862..fb57c4e 100755
--- a/scripts/scenario.sh
+++ b/scripts/scenario.sh
@@ -30,13 +30,15 @@
# requires screen
# port <n> serve ${PAGE} on a fixed port (snapshots show the address)
# ${FIXTURES}, ${PAGE} (Tests/Fixtures/Pages/page.html from a local server, so it has a host
-# for developer mode and tab sleep) and ${EXTENSION_ID} (Tests/Fixtures/Extension) expand.
+# for developer mode and tab sleep), ${EXTENSION_ID} (Tests/Fixtures/Extension) and
+# ${SIDE_PANEL_EXTENSION_ID} (Tests/Fixtures/SidePanelExtension) expand.
set -uo pipefail
cd "$(dirname "$0")/.."
ROOT="$PWD"
APP="${CRA_APP:-$ROOT/build/Cra.app}"
FIXTURES="$ROOT/Tests/Fixtures"
EXTENSION_ID="$(cat "$FIXTURES/Extension/ID")"
+SIDE_PANEL_EXTENSION_ID="$(cat "$FIXTURES/SidePanelExtension/ID")"
if [ "${1:-}" = "all" ]; then
failed=()
@@ -120,7 +122,7 @@ sleep 2
PACE=0.2
RSS_BUDGET=1500 MAXSTALL=1500 STALLS50=10 LAUNCHSTALL=1000 PERFCPU=0.1
BASELINE=""
-expand() { local s="$1"; s="${s//\$\{FIXTURES\}/$FIXTURES}"; s="${s//\$\{PAGE\}/$PAGE}"; s="${s//\$\{EXTENSION_ID\}/$EXTENSION_ID}"; printf '%s' "$s"; }
+expand() { local s="$1"; s="${s//\$\{FIXTURES\}/$FIXTURES}"; s="${s//\$\{PAGE\}/$PAGE}"; s="${s//\$\{EXTENSION_ID\}/$EXTENSION_ID}"; s="${s//\$\{SIDE_PANEL_EXTENSION_ID\}/$SIDE_PANEL_EXTENSION_ID}"; printf '%s' "$s"; }
echo "$NAME (pid $PID, logs in ${OUT#$ROOT/})"
while IFS= read -r raw || [ -n "$raw" ]; do