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.

Chromium 156, Air Traffic Control, Site Control Center, extension popups

Victorc5b7f46a852b
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index e7fecd0..7f75382 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -217,12 +217,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
handleInternalURL(u)
return
}
- // Arc: "Links from other apps open in Little Arc".
- if store.settings.openExternalLinksInLittleWindow {
+ // Arc's Air Traffic Control: the first matching route, else the default
+ // ("Links from other apps open in Little Arc").
+ switch store.settings.destination(forExternalURL: url) {
+ case .littleWindow:
openLittleWindow(url: url)
return
+ case .space(let id) where store.space(id) != nil:
+ store.createTab(url: url, in: id, select: true)
+ case .space, .mostRecentSpace:
+ store.createTab(url: url, select: true)
}
- store.createTab(url: url, select: true)
main.showWindow(nil)
NSApp.activate(ignoringOtherApps: true)
}
@@ -476,6 +481,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
func perform(_ id: String) {
store.recordCommandUse(id)
+ // An extension's own window (Arc: BrowserExtensionWindowController.closeCurrentItem:)
+ // closes on ⌘W instead of the tab behind it.
+ if ["closeTab", "closeWindow"].contains(id), let key = NSApp.keyWindow, CraCEFRuntime.isExtensionWindow(key) {
+ key.performClose(nil)
+ return
+ }
// A key Little Window takes the page/window actions first (⌘W, ⌘L, ⌘R…).
if let little = keyLittleWindow, little.handle(action: id) { return }
let current = store.selectedTabID
diff --git a/Sources/Cra/Model/LinkRouting.swift b/Sources/Cra/Model/LinkRouting.swift
new file mode 100644
index 0000000..9db112b
--- /dev/null
+++ b/Sources/Cra/Model/LinkRouting.swift
@@ -0,0 +1,72 @@
+import Foundation
+
+// Arc's Air Traffic Control (Settings ▸ Links ▸ Air Traffic Control…, stored in
+// StorableLinkRouting.json, see docs/arc-reverse-engineering.md): a link from another
+// app is checked against the routes in order, the first match decides where it opens
+// and anything else goes to the default destination.
+
+/// Arc's LinkSourceTextMatchingStyle (`matches` / `contains`).
+enum LinkMatchStyle: String, Codable, CaseIterable, Identifiable {
+ case equals, contains
+ var id: String { rawValue }
+ var label: String { self == .equals ? "Is equal to" : "Contains" }
+}
+
+/// Arc's LinkDestination is `space(ProfileDestination)` or `littleArc(ProfileDestination)`
+/// with ProfileDestination `mostRecent | space(id) | profile(…)`. Its editor only offers
+/// space(mostRecent), space(id) and littleArc(mostRecent); a Little Arc given a space still
+/// opened with "Open in <most recent space>", so Cra has no profiles and no space here.
+/// A space destination opens a new foreground tab in that space's Today list (also when
+/// the URL is already open) and switches the window to the space.
+enum LinkDestination: Codable, Hashable {
+ case mostRecentSpace
+ case space(UUID)
+ case littleWindow
+}
+
+struct LinkRoute: Codable, Identifiable, Equatable {
+ var id = UUID()
+ var match: LinkMatchStyle = .contains
+ var text = ""
+ var destination: LinkDestination = .mostRecentSpace
+
+ /// Matches like Arc 1.170 (observed by handing it links, see docs/arc-reverse-engineering.md):
+ /// both sides lose case, the scheme and a leading `www.`; "Contains" then searches the
+ /// rest including query and fragment, while "Is equal to" also drops the query, the
+ /// fragment and trailing slashes, so `example.com/a` equals `http://www.example.com/a/?x#y`
+ /// but not `example.com/a/b`. An empty route matches nothing.
+ func matches(_ url: String) -> Bool {
+ let want = Self.normalized(text.trimmingCharacters(in: .whitespacesAndNewlines))
+ guard !want.isEmpty else { return false }
+ let have = Self.normalized(url)
+ switch match {
+ case .contains: return have.contains(want)
+ case .equals: return Self.page(have) == Self.page(want)
+ }
+ }
+
+ private static func normalized(_ url: String) -> String {
+ var s = Substring(url.lowercased())
+ if let r = s.range(of: "://") { s = s[r.upperBound...] }
+ if s.hasPrefix("www.") { s = s.dropFirst(4) }
+ return String(s)
+ }
+
+ /// Host and path only.
+ private static func page(_ s: String) -> Substring {
+ var p = s[..<(s.firstIndex { $0 == "?" || $0 == "#" } ?? s.endIndex)]
+ while p.hasSuffix("/") { p = p.dropLast() }
+ return p
+ }
+
+ /// Arc seeds this route once (AppState+DefaultLinkRoutes, `didSetDefaultGoogleMeetRoute`)
+ /// so calls open in a full window rather than in Little Arc.
+ static let googleMeet = LinkRoute(match: .contains, text: "meet.google.com", destination: .mostRecentSpace)
+}
+
+extension AppSettings {
+ /// Where a link from another app opens: the first matching route, else the default.
+ func destination(forExternalURL url: String) -> LinkDestination {
+ linkRoutes.first { $0.matches(url) }?.destination ?? defaultLinkDestination
+ }
+}
diff --git a/Sources/Cra/Model/SidebarModel.swift b/Sources/Cra/Model/SidebarModel.swift
index 0b5a90f..9df97d0 100644
--- a/Sources/Cra/Model/SidebarModel.swift
+++ b/Sources/Cra/Model/SidebarModel.swift
@@ -64,6 +64,12 @@ struct TabData: Codable, Equatable {
var activeTabBeforeCreationID: UUID?
/// Host used as favicon cache key.
var faviconKey: String?
+ /// FaviconCache key of an image the user picked; wins over the site's favicon.
+ var customIconKey: String?
+ /// Favorite tile background as "#RRGGBB". nil is the theme's tile fill.
+ var tileColor: String?
+
+ var iconKey: String? { customIconKey ?? faviconKey }
init(url: String, title: String = "") {
self.url = url
@@ -99,6 +105,11 @@ enum SplitOrientation: String, Codable {
case vertical
}
+/// A fixed folder glyph colour, for when the theme's own doesn't read well.
+enum FolderIconStyle: String, Codable, CaseIterable {
+ case white, black
+}
+
enum ItemData: Codable, Equatable {
case tab(TabData)
case folder
@@ -115,6 +126,8 @@ struct SidebarItem: Identifiable, Codable, Equatable {
var isUnread: Bool
var createdAt: Date
var data: ItemData
+ /// A folder's glyph colour; nil is Auto (it follows the theme).
+ var folderIcon: FolderIconStyle? = nil
var tab: TabData? {
if case .tab(let t) = data { return t }
@@ -349,9 +362,13 @@ struct AppSettings: Codable, Equatable {
/// Host pages in Chrome-style windows: Chrome extensions and Chrome's own
/// DevTools docking. Needs a restart to change.
var chromeEngine: Bool = true
- /// Arc's "Links from other apps open in Little Arc": URLs handed to Cra by
- /// other apps open in a small disposable window instead of a sidebar tab.
- var openExternalLinksInLittleWindow: Bool = true
+ /// Air Traffic Control's "Default": where links from other apps open when no route
+ /// matches. Arc's "Links from other apps open in Little Arc" switch is this set to
+ /// Little Arc (on) or the most recent space (off).
+ var defaultLinkDestination: LinkDestination = .littleWindow
+ /// Air Traffic Control routes, checked in order (LinkRouting.swift). Starts with Arc's
+ /// Google Meet route.
+ var linkRoutes: [LinkRoute] = [.googleMeet]
/// Arc: "Enable Picture in Picture when you leave a video tab".
var autoPictureInPicture: Bool = true
/// Dia's onboarding privacy choice "Block third-party ads and trackers": requests
@@ -370,6 +387,12 @@ struct AppSettings: Codable, Equatable {
static func siteKey(for url: String) -> String? {
URL(string: url)?.host?.lowercased().replacingOccurrences(of: "www.", with: "")
}
+ /// Arc's "Links from other apps open in Little Arc" (URLs handed over by other apps
+ /// open in a small disposable window instead of a sidebar tab).
+ var openExternalLinksInLittleWindow: Bool {
+ get { defaultLinkDestination == .littleWindow }
+ set { defaultLinkDestination = newValue ? .littleWindow : .mostRecentSpace }
+ }
func isDeveloperMode(url: String) -> Bool { AppSettings.siteKey(for: url).map(developerHosts.contains) ?? false }
mutating func toggleDeveloperMode(url: String) {
guard let k = AppSettings.siteKey(for: url) else { return }
@@ -408,6 +431,9 @@ struct RankingData: Codable, Equatable {
// Tolerant decoding so new preference keys never reset the file.
extension AppSettings {
+ /// Keys earlier versions wrote; read once and replaced.
+ private enum LegacyKeys: String, CodingKey { case openExternalLinksInLittleWindow }
+
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
autoArchive = try c.decodeIfPresent(AutoArchiveThreshold.self, forKey: .autoArchive) ?? .twelveHours
@@ -424,7 +450,14 @@ extension AppSettings {
chromeEngine = try c.decodeIfPresent(Bool.self, forKey: .chromeEngine) ?? true
autoPictureInPicture = try c.decodeIfPresent(Bool.self, forKey: .autoPictureInPicture) ?? true
blockAdsAndTrackers = try c.decodeIfPresent(Bool.self, forKey: .blockAdsAndTrackers) ?? true
- openExternalLinksInLittleWindow = try c.decodeIfPresent(Bool.self, forKey: .openExternalLinksInLittleWindow) ?? true
+ if let d = try? c.decodeIfPresent(LinkDestination.self, forKey: .defaultLinkDestination) {
+ defaultLinkDestination = d
+ } else {
+ let legacy = try decoder.container(keyedBy: LegacyKeys.self)
+ openExternalLinksInLittleWindow = try legacy.decodeIfPresent(Bool.self, forKey: .openExternalLinksInLittleWindow) ?? true
+ }
+ // Settings from before Air Traffic Control get Arc's Google Meet route once.
+ linkRoutes = c.contains(.linkRoutes) ? (try? c.decode([LinkRoute].self, forKey: .linkRoutes)) ?? [] : [.googleMeet]
hapticFeedbackOnReorder = try c.decodeIfPresent(Bool.self, forKey: .hapticFeedbackOnReorder) ?? true
warnBeforeQuitting = try c.decodeIfPresent(Bool.self, forKey: .warnBeforeQuitting) ?? false
autoArchiveEnabled = try c.decodeIfPresent(Bool.self, forKey: .autoArchiveEnabled) ?? true
@@ -470,5 +503,7 @@ extension TabData {
timeLastActiveAt = try c.decodeIfPresent(Date.self, forKey: .timeLastActiveAt)
activeTabBeforeCreationID = try c.decodeIfPresent(UUID.self, forKey: .activeTabBeforeCreationID)
faviconKey = try c.decodeIfPresent(String.self, forKey: .faviconKey) ?? URL(string: url)?.host
+ customIconKey = try c.decodeIfPresent(String.self, forKey: .customIconKey)
+ tileColor = try c.decodeIfPresent(String.self, forKey: .tileColor)
}
}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index 2cd8f6d..6f4f0b7 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -42,6 +42,8 @@ protocol BrowserManagerDelegate: AnyObject {
func browserManagerHandleUnhandledKey(_ event: NSEvent) -> Bool
func browserManagerFocusedBrowser(_ tabID: UUID)
func browserManagerOpenInternalURL(_ url: String)
+ /// The page closed itself (window.close()).
+ func browserManagerPageClosedTab(_ tabID: UUID)
}
/// Creates, shows, hides and tears down CEF browsers inside a container view.
@@ -109,6 +111,9 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
runtimes[tabID] = rt
byBrowser[ObjectIdentifier(browser)] = tabID
if let t = store.item(tabID)?.tab, t.muted { browser.setAudioMuted(true) }
+ // CEF creates the page window inside CraBrowser's init, before the tab is known here,
+ // so didCreateHostWindow could not place it: a background tab's window stayed shown.
+ if browser.hostWindow != nil { delegate?.browserManagerPageWindowsChanged(focus: false) }
return rt
}
@@ -408,9 +413,9 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
if kinds & 2 != 0 { what.append("microphone") }
if kinds & 4 != 0 { what.append("location") }
if kinds & 8 != 0 { what.append("notifications") }
- if what.isEmpty { what.append("a browser permission") }
let alert = NSAlert()
- alert.messageText = "\(origin) wants to use your \(what.joined(separator: " and "))"
+ alert.messageText = what.isEmpty ? "\(origin) is asking for a browser permission"
+ : "\(origin) wants to use your \(what.joined(separator: " and "))"
alert.addButton(withTitle: "Allow")
alert.addButton(withTitle: "Block")
guard let window = container.window else { completion(false); return }
@@ -430,5 +435,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
if visibleTabID == id { visibleTabID = nil }
visibleTabIDs.removeAll { $0 == id }
delegate?.browserManagerDidUpdate(id)
+ // window.close() (a sign-in or payment popup finishing): the tab goes, like Chrome.
+ if browser.closedByPage { delegate?.browserManagerPageClosedTab(id) }
}
}
diff --git a/Sources/Cra/Services/ExtensionActions.swift b/Sources/Cra/Services/ExtensionActions.swift
index d20c7a4..ba1d69a 100644
--- a/Sources/Cra/Services/ExtensionActions.swift
+++ b/Sources/Cra/Services/ExtensionActions.swift
@@ -5,7 +5,7 @@ import CraCEF
/// toolbar button does: `Extensions.triggerAction` over the browser-level DevTools
/// pipe. Chrome then opens the real popup (with activeTab granted) or fires
/// chrome.action.onClicked. The popup anchors to the page's hidden Chrome toolbar,
-/// so Cra moves it under its own button (Arc: right edges aligned, just below the bar).
+/// so Cra frames it in a window under its own button (Arc: right edges aligned, just below the bar).
@MainActor
final class ExtensionActions {
static let shared = ExtensionActions()
@@ -15,7 +15,6 @@ final class ExtensionActions {
private var tabTargets: [ObjectIdentifier: CachedTab] = [:]
/// Tab session → callback with the page target that auto-attaches under it.
private var childWaiters: [String: (String?) -> Void] = [:]
- private var popupObservers: [NSObjectProtocol] = []
var isAvailable: Bool { CraCEFRuntime.hasBrowserDevTools() }
@@ -26,6 +25,22 @@ final class ExtensionActions {
}
}
+ /// Where a popup Cra did not ask for hangs (screen top-right point), nil to leave it where
+ /// Chrome put it.
+ private var defaultAnchor: () -> NSPoint? = { nil }
+ /// True while `run` waits for its own popup.
+ private var placingOwnPopup = false
+
+ /// Popups can open without Cra's buttons: the extension's keyboard shortcut (1Password's
+ /// ⌘⇧X) or chrome.action.openPopup() (1Password's inline menu). Arc hosts every popup
+ /// under its toolbar (ArcCore hands it over in browser:didOpenExtensionPopup:webContents:);
+ /// Cra watches for popup pages being created and moves those under `anchor` too.
+ func watchPopups(anchor: @escaping () -> NSPoint?) {
+ defaultAnchor = anchor
+ guard isAvailable else { return }
+ Task { _ = try? await call("Target.setDiscoverTargets", ["discover": true]) }
+ }
+
/// Triggers the action; `anchor` is the top-right point (screen coordinates) the popup hangs from.
/// Returns false when the pipe or the page is unavailable (the caller falls back).
@discardableResult
@@ -33,11 +48,13 @@ final class ExtensionActions {
guard isAvailable else { return false }
do {
let tab = try await tabTarget(for: browser)
- let before = Set(NSApp.windows.map(ObjectIdentifier.init))
+ let before = visibleWindows()
+ placingOwnPopup = true
_ = try await call("Extensions.triggerAction", ["id": extensionID, "targetId": tab])
placePopup(appearingAfter: before, anchor: anchor)
return true
} catch {
+ placingOwnPopup = false
NSLog("Cra: extension action %@ failed: %@", extensionID, String(describing: error))
tabTargets[ObjectIdentifier(browser)] = nil
return false
@@ -46,36 +63,25 @@ final class ExtensionActions {
// MARK: Popup placement
- /// Chrome shows the popup once its page has loaded; watch for the new window and keep it
- /// under the anchor (Chrome re-anchors it to the hidden toolbar whenever it resizes).
+ /// Chrome creates the popup's window hidden, sometimes before the popup page exists, so
+ /// "new" means newly visible.
+ private func visibleWindows() -> Set<ObjectIdentifier> {
+ Set(NSApp.windows.filter(\.isVisible).map(ObjectIdentifier.init))
+ }
+
+ /// Chrome shows the popup once its page has loaded; watch for the new window and frame it
+ /// under the anchor (ExtensionPopupWindow, Arc's BrowserExtensionWindow).
private func placePopup(appearingAfter before: Set<ObjectIdentifier>, anchor: NSPoint, attempt: Int = 0) {
- if let popup = NSApp.windows.first(where: { !before.contains(ObjectIdentifier($0)) && $0.isVisible && $0.frame.width > 1 }) {
- for o in popupObservers { NotificationCenter.default.removeObserver(o) }
- popupObservers = []
- let pin = { [weak popup] in
- guard let popup else { return }
- let screen = (popup.screen ?? NSScreen.main)?.visibleFrame ?? .infinite
- var origin = NSPoint(x: anchor.x - popup.frame.width, y: anchor.y - popup.frame.height)
- origin.x = min(max(origin.x, screen.minX + 4), screen.maxX - popup.frame.width - 4)
- if popup.frame.origin != origin { popup.setFrameOrigin(origin) }
- }
- pin()
- for name in [NSWindow.didResizeNotification, NSWindow.didMoveNotification] {
- popupObservers.append(NotificationCenter.default.addObserver(forName: name, object: popup, queue: .main) { _ in
- MainActor.assumeIsolated { pin() }
- })
- }
- popupObservers.append(NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification, object: popup, queue: .main) { [weak self] _ in
- MainActor.assumeIsolated {
- guard let self else { return }
- for o in self.popupObservers { NotificationCenter.default.removeObserver(o) }
- self.popupObservers = []
- }
- })
+ // Chrome's popup bubble is borderless; an extension's own (titled) window is not one.
+ if let popup = NSApp.windows.first(where: { !before.contains(ObjectIdentifier($0)) && $0.isVisible && $0.frame.width > 1
+ && !$0.styleMask.contains(.titled) && !($0 is NSPanel)
+ && !CraCEFRuntime.isPageWindow($0) }) {
+ placingOwnPopup = false
+ ExtensionPopupWindow.present(popup, anchor: anchor)
return
}
// No popup yet (still loading), or an action without one (onClicked): keep looking for 3 s.
- guard attempt < 60 else { return }
+ guard attempt < 60 else { placingOwnPopup = false; return }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
MainActor.assumeIsolated { self?.placePopup(appearingAfter: before, anchor: anchor, attempt: attempt + 1) }
}
@@ -123,12 +129,30 @@ final class ExtensionActions {
}
private func handleEvent(_ method: String, params: String, sessionID: String?) {
+ if method == "Target.targetCreated" || method == "Target.targetInfoChanged" { popupPageCreated(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 }
childWaiters.removeValue(forKey: sessionID)?(info["targetId"] as? String)
}
+ /// Popup targets already seen (each is placed once).
+ private var seenPopupTargets: Set<String> = []
+
+ /// A target for an extension's popup URL that Cra's own `run` is not waiting for. Chrome
+ /// creates it blank ("other", no URL) and reports the URL in a later targetInfoChanged.
+ private func popupPageCreated(_ params: String) {
+ guard let p = try? JSONSerialization.jsonObject(with: Data(params.utf8)) as? [String: Any],
+ let info = p["targetInfo"] as? [String: Any], let target = info["targetId"] as? String,
+ let url = (info["url"] as? String).flatMap(URL.init(string:)), url.scheme == "chrome-extension",
+ let id = url.host, url.fragment == nil,
+ let popup = ExtensionStore.shared.entries.first(where: { $0.extensionID == id })?.popupPath,
+ url.path == "/" + popup.trimmingCharacters(in: CharacterSet(charactersIn: "/")),
+ seenPopupTargets.insert(target).inserted, !placingOwnPopup,
+ let anchor = defaultAnchor() else { return }
+ placePopup(appearingAfter: visibleWindows(), anchor: anchor)
+ }
+
// MARK: Protocol calls
private func call(_ method: String, _ params: [String: Any] = [:], session: String? = nil) async throws -> [String: Any] {
diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swift
index 038e111..39a876d 100644
--- a/Sources/Cra/Services/ExtensionStore.swift
+++ b/Sources/Cra/Services/ExtensionStore.swift
@@ -56,7 +56,11 @@ final class ExtensionStore {
/// Set once the folder changed in this session; a restart loads the change.
private(set) var needsRestart = false
- init() { reload() }
+ init() {
+ reload()
+ // Keep what was taken over from another browser, so it is only read once.
+ if !FileManager.default.fileExists(atPath: Self.pinnedFile.path), !pinnedIDs.isEmpty { savePinned() }
+ }
func reload() {
let fm = FileManager.default
@@ -103,7 +107,21 @@ final class ExtensionStore {
private static var pinnedFile: URL { AppPaths.file("pinned-extensions.json") }
/// Chromium extension IDs in toolbar order.
- private(set) var pinnedIDs: [String] = (try? JSONDecoder().decode([String].self, from: Data(contentsOf: ExtensionStore.pinnedFile))) ?? []
+ private(set) var pinnedIDs: [String] = ExtensionStore.loadPinned()
+
+ /// Before Cra has a list of its own, the browser it replaces supplies one: Arc keeps its
+ /// pinned extensions in Chromium's `extensions.pinned_extensions` pref, as do Dia and Chrome.
+ private static func loadPinned() -> [String] {
+ if let data = try? Data(contentsOf: pinnedFile) { return (try? JSONDecoder().decode([String].self, from: data)) ?? [] }
+ for source in [ImportSource.arc, .dia] + ImportSource.allCases.filter({ $0.id == "chrome" }) {
+ let prefs = source.dataDir.appendingPathComponent("Default/Preferences")
+ guard let data = try? Data(contentsOf: prefs),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let ids = (json["extensions"] as? [String: Any])?["pinned_extensions"] as? [String], !ids.isEmpty else { continue }
+ return ids
+ }
+ return []
+ }
func isPinned(_ id: String) -> Bool { pinnedIDs.contains(id) }
diff --git a/Sources/Cra/Services/FaviconCache.swift b/Sources/Cra/Services/FaviconCache.swift
index 9c93f01..ab72c45 100644
--- a/Sources/Cra/Services/FaviconCache.swift
+++ b/Sources/Cra/Services/FaviconCache.swift
@@ -56,11 +56,77 @@ final class FaviconCache {
return hex
}
+ private var glyphTone: [String: Bool?] = [:]
+
+ /// For a one-color gray glyph on a transparent background (GitHub's
+ /// octocat, black or white depending on the page's color scheme): true when
+ /// it is dark, false when light, nil for any other icon. Such glyphs vanish
+ /// on a tile of their own tone. Custom icons are left as picked.
+ func glyphIsDark(forKey key: String?) -> Bool? {
+ guard let key, !Self.isCustom(key) else { return nil }
+ if let v = glyphTone[key] { return v }
+ guard let img = image(forKey: key), let cg = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return nil }
+ let w = 32, h = 32
+ var buf = [UInt8](repeating: 0, count: w * h * 4)
+ guard let ctx = CGContext(data: &buf, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,
+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
+ ctx.draw(cg, in: CGRect(x: 0, y: 0, width: w, height: h))
+ var opaque = 0, dark = 0, light = 0
+ for i in stride(from: 0, to: buf.count, by: 4) where buf[i + 3] > 128 {
+ let a = Double(buf[i + 3])
+ let r = Double(buf[i]) / a, g = Double(buf[i + 1]) / a, b = Double(buf[i + 2]) / a
+ opaque += 1
+ guard max(r, g, b) - min(r, g, b) < 0.15 else { continue }
+ let l = 0.2126 * r + 0.7152 * g + 0.0722 * b
+ if l < 0.3 { dark += 1 } else if l > 0.75 { light += 1 }
+ }
+ // Mostly see-through and almost every visible pixel the same gray.
+ var v: Bool?
+ if opaque > 20, opaque < w * h * 85 / 100 {
+ if Double(dark) / Double(opaque) > 0.92 { v = true } else if Double(light) / Double(opaque) > 0.92 { v = false }
+ }
+ glyphTone[key] = .some(v)
+ return v
+ }
+
/// Forget in-memory state so files added on disk (imports) are picked up.
func reset() {
images = [:]
attemptedDiskLoad = []
dominant = [:]
+ glyphTone = [:]
+ }
+
+ static func isCustom(_ key: String) -> Bool { key.hasPrefix("custom-") }
+
+ /// Fits an image the user picked into a 256px square and caches it under a
+ /// fresh key, so a replaced icon never shows a stale copy.
+ func importCustomIcon(from url: URL) -> String? {
+ guard let src = NSImage(contentsOf: url), src.size.width > 0, src.size.height > 0,
+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 256, pixelsHigh: 256, bitsPerSample: 8,
+ samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,
+ bytesPerRow: 0, bitsPerPixel: 0),
+ let ctx = NSGraphicsContext(bitmapImageRep: rep) else { return nil }
+ let side: CGFloat = 256
+ let scale = min(side / src.size.width, side / src.size.height)
+ let size = NSSize(width: src.size.width * scale, height: src.size.height * scale)
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = ctx
+ ctx.imageInterpolation = .high
+ src.draw(in: NSRect(x: (side - size.width) / 2, y: (side - size.height) / 2, width: size.width, height: size.height))
+ NSGraphicsContext.restoreGraphicsState()
+ rep.size = NSSize(width: 128, height: 128)
+ let img = NSImage(size: rep.size)
+ img.addRepresentation(rep)
+ let key = "custom-" + UUID().uuidString.lowercased()
+ store(img, forKey: key)
+ return key
+ }
+
+ func removeCustomIcon(_ key: String) {
+ guard Self.isCustom(key) else { return }
+ images[key] = nil
+ try? FileManager.default.removeItem(at: AppPaths.favicons.appendingPathComponent(Self.fileName(key)))
}
func store(_ image: NSImage, forKey key: String) {
diff --git a/Sources/Cra/Services/Import/BrowserSources.swift b/Sources/Cra/Services/Import/BrowserSources.swift
index 55c33ed..b6f1ad6 100644
--- a/Sources/Cra/Services/Import/BrowserSources.swift
+++ b/Sources/Cra/Services/Import/BrowserSources.swift
@@ -7,6 +7,8 @@ struct ImportSource: Identifiable, Hashable {
/// Arc and Dia: their own sidebar stores, and a Chromium profile for passwords and cookies.
case arc, dia
case chromium, firefox
+ /// Zen: Firefox underneath, with Arc-style spaces, Essentials and pinned tabs.
+ case zen
/// Safari: only what Safari exports itself.
case safari
}
@@ -50,13 +52,13 @@ struct ImportSource: Identifiable, Hashable {
chromium("chromium", "Chromium", "org.chromium.Chromium", "Chromium", account: "Chromium"),
ImportSource(id: "firefox", name: "Firefox", bundleID: "org.mozilla.firefox", kind: .firefox,
dataDir: support.appendingPathComponent("Firefox", isDirectory: true)),
- ImportSource(id: "zen", name: "Zen", bundleID: "app.zen-browser.zen", kind: .firefox,
+ ImportSource(id: "zen", name: "Zen", bundleID: "app.zen-browser.zen", kind: .zen,
dataDir: support.appendingPathComponent("zen", isDirectory: true)),
ImportSource(id: "safari", name: "Safari", bundleID: "com.apple.Safari", kind: .safari,
dataDir: FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Safari", isDirectory: true)),
]
- /// Installed with data to bring over. Arc and Dia only need their data
+ /// Installed with data to bring over. Arc, Dia and Zen only need their data
/// (the import also runs after they are deleted); Safari is always there.
var isAvailable: Bool {
switch kind {
@@ -67,6 +69,8 @@ struct ImportSource: Identifiable, Hashable {
return isInstalled && !ChromiumImporter.profiles(userData: dataDir).isEmpty
case .firefox:
return isInstalled && FirefoxImporter.defaultProfile(root: dataDir) != nil
+ case .zen:
+ return FirefoxImporter.defaultProfile(root: dataDir) != nil
}
}
@@ -81,6 +85,7 @@ struct ImportSource: Identifiable, Hashable {
case .dia: return try DiaImporter.plan()
case .chromium: return try ChromiumImporter.plan(browser: name, userData: dataDir)
case .firefox: return try FirefoxImporter.plan(browser: name, root: dataDir)
+ case .zen: return try ZenImporter.plan(root: dataDir)
case .safari: return ImportPlan(source: name)
}
}
@@ -93,7 +98,7 @@ struct ImportSource: Identifiable, Hashable {
func topSites(limit: Int) -> [TopSite] {
switch kind {
case .arc, .dia, .chromium: return ChromiumImporter.topSites(userData: dataDir, limit: limit)
- case .firefox: return FirefoxImporter.topSites(root: dataDir, limit: limit)
+ case .firefox, .zen: return FirefoxImporter.topSites(root: dataDir, limit: limit)
case .safari: return []
}
}
@@ -101,7 +106,7 @@ struct ImportSource: Identifiable, Hashable {
func favicons(hosts: [String]) -> [String: NSImage] {
switch kind {
case .arc, .dia, .chromium: return ChromiumImporter.favicons(userData: dataDir, hosts: hosts)
- case .firefox: return FirefoxImporter.favicons(root: dataDir, hosts: hosts)
+ case .firefox, .zen: return FirefoxImporter.favicons(root: dataDir, hosts: hosts)
case .safari: return [:]
}
}
@@ -109,15 +114,18 @@ struct ImportSource: Identifiable, Hashable {
func extensions() -> [ImportableExtension] {
switch kind {
case .arc, .dia, .chromium: return ExtensionImporter.extensions(inUserData: dataDir)
- case .firefox, .safari: return []
+ case .firefox, .zen, .safari: return []
}
}
- /// The installed app's own icon (Dia shows its bundled browser logos here).
+ /// The installed app's own icon, else a logo bundled in resources/browsers for a
+ /// browser that may already be deleted (Dia bundles its browser logos).
var icon: NSImage {
if let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID) {
return NSWorkspace.shared.icon(forFile: url.path)
}
+ if let url = Bundle.main.url(forResource: id, withExtension: "png", subdirectory: "browsers"),
+ let image = NSImage(contentsOf: url) { return image }
return NSImage(systemSymbolName: "globe", accessibilityDescription: name) ?? NSImage()
}
}
diff --git a/Sources/Cra/Services/Import/FirefoxImporter.swift b/Sources/Cra/Services/Import/FirefoxImporter.swift
index 2e528d1..306137d 100644
--- a/Sources/Cra/Services/Import/FirefoxImporter.swift
+++ b/Sources/Cra/Services/Import/FirefoxImporter.swift
@@ -1,7 +1,7 @@
import AppKit
import Compression
-// Firefox and Firefox-based browsers (Zen): bookmarks from places.sqlite and
+// Firefox (and Zen's bookmarks and favicons, see ZenImporter): bookmarks from places.sqlite and
// open tabs from the session store (mozLz4). Saved logins come in only through
// Firefox's own export (about:logins ▸ Export Passwords…), read with
// PasswordCSV like Safari's exported Passwords.csv.
@@ -45,6 +45,10 @@ enum FirefoxImporter {
return plan
}
+ static func bookmarks(profile: URL) -> [ImportedItem] {
+ SQLiteSnapshot(copying: profile.appendingPathComponent("places.sqlite")).map(bookmarks) ?? []
+ }
+
/// The toolbar's bookmarks, then the menu and unsorted bookmarks as folders.
private static func bookmarks(_ db: SQLiteSnapshot) -> [ImportedItem] {
let rows = db.rows("""
diff --git a/Sources/Cra/Services/Import/Importers.swift b/Sources/Cra/Services/Import/Importers.swift
index 2bb7fc4..4772a97 100644
--- a/Sources/Cra/Services/Import/Importers.swift
+++ b/Sources/Cra/Services/Import/Importers.swift
@@ -35,12 +35,29 @@ struct ImportedArchiveEntry {
var spaceTitle: String?
}
+/// Air Traffic Control destinations name spaces by title; ids differ between browsers.
+enum ImportedLinkDestination {
+ case mostRecentSpace
+ case space(title: String)
+ case littleWindow
+}
+
+struct ImportedLinkRoute {
+ var match: LinkMatchStyle
+ var text: String
+ var destination: ImportedLinkDestination
+}
+
struct ImportedSettings {
var autoArchive: AutoArchiveThreshold?
var sidebarWidth: Double?
var showToolbar: Bool?
+ var linkRoutes: [ImportedLinkRoute] = []
+ var defaultLinkDestination: ImportedLinkDestination?
- var isEmpty: Bool { autoArchive == nil && sidebarWidth == nil && showToolbar == nil }
+ var isEmpty: Bool {
+ autoArchive == nil && sidebarWidth == nil && showToolbar == nil && linkRoutes.isEmpty && defaultLinkDestination == nil
+ }
}
struct ImportPlan {
@@ -199,9 +216,41 @@ enum ArcImporter {
plan.settings.autoArchive = AutoArchiveThreshold(rawValue: threshold)
}
plan.settings.showToolbar = showsToolbar
+ if let ldata = try? Data(contentsOf: supportDir.appendingPathComponent("StorableLinkRouting.json")),
+ let lroot = try? JSONSerialization.jsonObject(with: ldata) as? [String: Any] {
+ plan.settings.defaultLinkDestination = linkDestination(lroot["defaultDestination"], spaceTitles: spaceTitleByID)
+ plan.settings.linkRoutes = (lroot["rules"] as? [[String: Any]] ?? []).compactMap { linkRoute($0, spaceTitles: spaceTitleByID) }
+ }
return plan
}
+ /// One Air Traffic Control rule: `sourceComponents[0].componentType.urlMatch` is
+ /// `{_0: {contains: {}} | {matches: {}}, _1: text}`.
+ private static func linkRoute(_ rule: [String: Any], spaceTitles: [String: String]) -> ImportedLinkRoute? {
+ guard let dest = linkDestination(rule["destination"], spaceTitles: spaceTitles),
+ let component = (rule["sourceComponents"] as? [[String: Any]])?.first,
+ let type = component["componentType"] as? [String: Any],
+ let urlMatch = type["urlMatch"] as? [String: Any],
+ let text = urlMatch["_1"] as? String else { return nil }
+ let style: LinkMatchStyle = (urlMatch["_0"] as? [String: Any])?["matches"] != nil ? .equals : .contains
+ return ImportedLinkRoute(match: style, text: text, destination: dest)
+ }
+
+ /// `{littleArc: {_0: <profile>}}` or `{space: {_0: {mostRecent: {}}}}`; a specific
+ /// space is recognised by its id anywhere inside `space`.
+ private static func linkDestination(_ value: Any?, spaceTitles: [String: String]) -> ImportedLinkDestination? {
+ guard let d = value as? [String: Any] else { return nil }
+ if d["littleArc"] != nil { return .littleWindow }
+ guard let space = d["space"] else { return nil }
+ func title(_ v: Any) -> String? {
+ if let s = v as? String { return spaceTitles[s] }
+ if let o = v as? [String: Any] { return o.values.lazy.compactMap(title).first }
+ if let a = v as? [Any] { return a.lazy.compactMap(title).first }
+ return nil
+ }
+ return title(space).map { .space(title: $0) } ?? .mostRecentSpace
+ }
+
/// Arc caches sidebar favicons as 32x32 PNGs named md5(item id).
static func faviconFile(forItemID id: String) -> String? {
let digest = Insecure.MD5.hash(data: Data(id.utf8)).map { String(format: "%02x", $0) }.joined()
@@ -468,6 +517,19 @@ extension SidebarStore {
if let a = plan.settings.autoArchive { settings.autoArchive = a }
if let w = plan.settings.sidebarWidth { prefs.sidebarWidth = min(max(w, 220), 520) }
if let t = plan.settings.showToolbar { settings.showToolbar = t }
+ // Air Traffic Control, pointed at the spaces of the same name.
+ func destination(_ d: ImportedLinkDestination) -> LinkDestination {
+ switch d {
+ case .mostRecentSpace: return .mostRecentSpace
+ case .littleWindow: return .littleWindow
+ case .space(let title):
+ return orderedSpaces.first { $0.title.caseInsensitiveCompare(title) == .orderedSame }.map { .space($0.id) } ?? .mostRecentSpace
+ }
+ }
+ if let d = plan.settings.defaultLinkDestination { settings.defaultLinkDestination = destination(d) }
+ for r in plan.settings.linkRoutes where !settings.linkRoutes.contains(where: { $0.match == r.match && $0.text == r.text }) {
+ settings.linkRoutes.append(LinkRoute(match: r.match, text: r.text, destination: destination(r.destination)))
+ }
}
touchAfterImport()
return result
diff --git a/Sources/Cra/Services/Import/ZenImporter.swift b/Sources/Cra/Services/Import/ZenImporter.swift
new file mode 100644
index 0000000..e287228
--- /dev/null
+++ b/Sources/Cra/Services/Import/ZenImporter.swift
@@ -0,0 +1,197 @@
+import AppKit
+
+// Zen is Firefox with Arc's sidebar: spaces, Essentials, pinned tabs and folders.
+// Since Zen 1.15 one file holds that sidebar for every window,
+// <profile>/zen-sessions.jsonlz4 = {spaces, tabs, folders, groups, splitViewData}
+// (src/zen/sessionstore/ZenSessionManager.sys.mjs, read against 1.23.4b). Older
+// profiles keep spaces in places.sqlite (zen_workspaces) and the tabs, with the
+// same zen* fields, in Firefox's session store.
+
+enum ZenImporter {
+ static func plan(root: URL) throws -> ImportPlan {
+ guard let profile = FirefoxImporter.defaultProfile(root: root) else { throw ImportError.notFound("Zen") }
+ let sidebar = sidebar(profile: profile)
+ var plan = ImportPlan(source: "Zen")
+
+ let spaceData = sidebar.spaces.sorted { ($0["position"] as? Double ?? 0) < ($1["position"] as? Double ?? 0) }
+ var spaces = spaceData.map { s -> ImportedSpace in
+ let icon = s["icon"] as? String ?? ""
+ // Zen's icon is an emoji or a chrome://…svg path.
+ let emoji = icon.isEmpty || icon.contains("/") ? "🗂️" : icon
+ return ImportedSpace(title: (s["name"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? "Space", emoji: emoji,
+ theme: theme(s["theme"] as? [String: Any]))
+ }
+ if spaces.isEmpty { spaces = [ImportedSpace(title: "Zen", emoji: "🗂️", theme: nil)] }
+ let spaceIndex = Dictionary(spaceData.enumerated().compactMap { i, s in (s["uuid"] as? String).map { ($0, i) } },
+ uniquingKeysWith: { a, _ in a })
+
+ // Folders nest through parentId; split views are groups inside a folder and flatten into it.
+ var folders: [String: (name: String, parent: String?, split: Bool)] = [:]
+ for f in sidebar.folders {
+ guard let id = f["id"] as? String else { continue }
+ folders[id] = (f["name"] as? String ?? "Folder", f["parentId"] as? String, f["splitViewGroup"] as? Bool ?? false)
+ }
+ func folderChain(_ groupID: String?) -> [String] {
+ var chain: [String] = [], id = groupID
+ while let g = id, let f = folders[g], !chain.contains(g) {
+ if !f.split { chain.insert(g, at: 0) }
+ id = f.parent
+ }
+ return chain
+ }
+
+ var essentials: [ImportedItem] = []
+ // Per space: pinned and Today trees, built in the session's tab order.
+ let trees = spaces.map { _ in (pinned: Tree(), today: Tree()) }
+ for t in sidebar.tabs {
+ guard let item = tabItem(t) else { continue }
+ if flag(t["zenEssential"]) {
+ if !essentials.contains(where: { $0.url == item.url }) { essentials.append(item) }
+ continue
+ }
+ let i = (t["zenWorkspace"] as? String).flatMap { spaceIndex[$0] } ?? 0
+ let chain = folderChain(t["groupId"] as? String)
+ if flag(t["pinned"]) || !chain.isEmpty {
+ trees[i].pinned.insert(item, path: chain.map { ($0, folders[$0]!.name) })
+ } else {
+ trees[i].today.insert(item, path: [])
+ }
+ }
+
+ // Essentials sit above every space in Zen; Cra's favorites belong to a space.
+ for i in spaces.indices {
+ spaces[i].favorites = essentials
+ spaces[i].pinned = trees[i].pinned.items
+ spaces[i].today = trees[i].today.items
+ }
+ let bookmarks = FirefoxImporter.bookmarks(profile: profile)
+ if !bookmarks.isEmpty {
+ spaces[0].pinned.append(ImportedItem(customTitle: "Bookmarks", pageTitle: "Bookmarks", url: nil, isFolder: true, children: bookmarks))
+ }
+
+ // Favicons from favicons.sqlite, written where the plan's copy step can pick them up.
+ func hosts(_ items: [ImportedItem]) -> [String] { items.flatMap { $0.isFolder ? hosts($0.children) : [$0.url.flatMap(host)].compactMap { $0 } } }
+ let allHosts = Set(spaces.flatMap { hosts($0.favorites) + hosts($0.pinned) + hosts($0.today) })
+ let icons = FirefoxImporter.favicons(root: root, hosts: Array(allHosts))
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cra-zen-favicons", isDirectory: true)
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ var files: [String: String] = [:]
+ for (host, img) in icons {
+ guard let tiff = img.tiffRepresentation, let png = NSBitmapImageRep(data: tiff)?.representation(using: .png, properties: [:]) else { continue }
+ let file = dir.appendingPathComponent("\(files.count).png")
+ if (try? png.write(to: file, options: .atomic)) != nil { files[host] = file.path }
+ }
+ func withIcons(_ items: [ImportedItem]) -> [ImportedItem] {
+ items.map { var it = $0; it.children = withIcons(it.children); it.faviconPath = it.url.flatMap(host).flatMap { files[$0] }; return it }
+ }
+ for i in spaces.indices {
+ spaces[i].favorites = withIcons(spaces[i].favorites)
+ spaces[i].pinned = withIcons(spaces[i].pinned)
+ spaces[i].today = withIcons(spaces[i].today)
+ }
+
+ plan.spaces = spaces.filter { !$0.favorites.isEmpty || !$0.pinned.isEmpty || !$0.today.isEmpty }
+ return plan
+ }
+
+ /// Zen's own session file, else its backup, else Firefox's session store plus
+ /// the spaces table of older Zen versions.
+ private static func sidebar(profile: URL) -> (spaces: [[String: Any]], tabs: [[String: Any]], folders: [[String: Any]]) {
+ for name in ["zen-sessions.jsonlz4", "zen-sessions-backup/clean.jsonlz4"] {
+ guard let root = json(profile.appendingPathComponent(name)),
+ let spaces = root["spaces"] as? [[String: Any]], !spaces.isEmpty else { continue }
+ return (spaces, root["tabs"] as? [[String: Any]] ?? [], root["folders"] as? [[String: Any]] ?? [])
+ }
+ let store = ["sessionstore-backups/recovery.jsonlz4", "sessionstore.jsonlz4", "sessionstore-backups/previous.jsonlz4"]
+ .lazy.compactMap { json(profile.appendingPathComponent($0)) }.first
+ let windows = store?["windows"] as? [[String: Any]] ?? []
+ // Every window holds the pinned tabs; keep one copy of each.
+ var seen = Set<String>()
+ let tabs = windows.flatMap { $0["tabs"] as? [[String: Any]] ?? [] }.filter { t in
+ guard let id = (t["zenSyncId"] ?? t["zenPinnedId"]) as? String else { return true }
+ return seen.insert(id).inserted
+ }
+ var spaces = windows.first?["spaces"] as? [[String: Any]] ?? []
+ if spaces.isEmpty, let db = SQLiteSnapshot(copying: profile.appendingPathComponent("places.sqlite")) {
+ spaces = db.rows("SELECT * FROM zen_workspaces ORDER BY position").map { r in
+ var s: [String: Any] = ["uuid": r["uuid"] as? String ?? "", "name": r["name"] as? String ?? "",
+ "icon": r["icon"] as? String ?? "", "position": Double(r["position"] as? Int64 ?? 0)]
+ if let colors = (r["theme_colors"] as? String).flatMap({ try? JSONSerialization.jsonObject(with: Data($0.utf8)) }) {
+ s["theme"] = ["gradientColors": colors, "opacity": r["theme_opacity"] as? Double ?? 0.5,
+ "texture": r["theme_texture"] as? Double ?? 0]
+ }
+ return s
+ }
+ }
+ return (spaces, tabs, windows.first?["folders"] as? [[String: Any]] ?? [])
+ }
+
+ /// FaviconCache's key: the lowercased host.
+ private static func host(_ url: String) -> String? {
+ URL(string: url)?.host.flatMap { $0.isEmpty ? nil : $0.lowercased() }
+ }
+
+ private static func json(_ url: URL) -> [String: Any]? {
+ guard let data = try? Data(contentsOf: url), let raw = FirefoxImporter.mozLz4(data) else { return nil }
+ return try? JSONSerialization.jsonObject(with: raw) as? [String: Any]
+ }
+
+ /// Older Zen wrote some flags as the strings "true"/"false".
+ private static func flag(_ v: Any?) -> Bool { (v as? Bool) ?? ((v as? String) == "true") }
+
+ /// A pinned tab keeps the URL it was pinned with (Arc's savedURL), not where it navigated.
+ private static func tabItem(_ t: [String: Any]) -> ImportedItem? {
+ if flag(t["zenIsEmpty"]) || flag(t["zenIsGlance"]) { return nil }
+ let entries = t["entries"] as? [[String: Any]] ?? []
+ let current = entries.isEmpty ? nil : entries[min(max((t["index"] as? Int ?? entries.count) - 1, 0), entries.count - 1)]
+ let home = (t["_zenPinnedInitialState"] as? [String: Any])?["entry"] as? [String: Any]
+ let entry = (flag(t["pinned"]) || flag(t["zenEssential"]) ? home : nil) ?? current
+ guard let url = entry?["url"] as? String, url.hasPrefix("http") else { return nil }
+ let label = (t["zenStaticLabel"] as? String).flatMap { $0.isEmpty ? nil : $0 }
+ let title = (entry?["title"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? current?["title"] as? String ?? ""
+ return ImportedItem(customTitle: label, pageTitle: title, url: url)
+ }
+
+ /// Zen's gradient: up to three dots ({c: [r, g, b]} or a CSS colour when custom),
+ /// laid over the window at `opacity`, with `texture` grain.
+ private static func theme(_ t: [String: Any]?) -> SpaceTheme? {
+ guard let t, let dots = t["gradientColors"] as? [[String: Any]] else { return nil }
+ let colors: [String] = dots.compactMap { d in
+ if let c = d["c"] as? [Double], c.count >= 3 {
+ return String(format: "#%02X%02X%02X", Int(c[0].rounded()), Int(c[1].rounded()), Int(c[2].rounded()))
+ }
+ if let s = d["c"] as? String, HexColor.components(s) != nil { return s.uppercased() }
+ return nil
+ }
+ guard let first = colors.first else { return nil }
+ let opacity = t["opacity"] as? Double ?? 0.5
+ return SpaceTheme(colors: Array((colors + [first]).prefix(2)), intensity: max(0.3, min(1, opacity)),
+ noise: max(0, min(1, t["texture"] as? Double ?? 0)), appearance: "auto", accent: first)
+ }
+
+ /// Sidebar items in arrival order, with folders created where their first tab appears.
+ private final class Tree {
+ private final class Node {
+ var item: ImportedItem
+ var kids: [Node] = []
+ var folders: [String: Node] = [:]
+ init(_ item: ImportedItem) { self.item = item }
+ var built: ImportedItem { var it = item; if it.isFolder { it.children = kids.map(\.built) }; return it }
+ }
+ private let root = Node(ImportedItem(url: nil, isFolder: true))
+
+ func insert(_ item: ImportedItem, path: [(id: String, name: String)]) {
+ var n = root
+ for (id, name) in path {
+ if let f = n.folders[id] { n = f; continue }
+ let f = Node(ImportedItem(customTitle: name, pageTitle: name, url: nil, isFolder: true))
+ n.kids.append(f)
+ n.folders[id] = f
+ n = f
+ }
+ if !n.kids.contains(where: { !$0.item.isFolder && $0.item.url == item.url }) { n.kids.append(Node(item)) }
+ }
+
+ var items: [ImportedItem] { root.kids.map(\.built) }
+ }
+}
diff --git a/Sources/Cra/Services/NativeMessagingHosts.swift b/Sources/Cra/Services/NativeMessagingHosts.swift
index 92dcc91..33d95e9 100644
--- a/Sources/Cra/Services/NativeMessagingHosts.swift
+++ b/Sources/Cra/Services/NativeMessagingHosts.swift
@@ -24,7 +24,7 @@ enum NativeMessagingHosts {
// First source wins: Chrome is where every app installs, the rest fill gaps.
for dir in sources {
- for name in (try? fm.contentsOfDirectory(atPath: dir.path)) ?? [] where name.hasSuffix(".json") {
+ for name in (try? fm.contentsOfDirectory(atPath: dir.path)) ?? [] where name.hasSuffix(".json") && !excluded.contains(name) {
let link = dest.appendingPathComponent(name)
if (try? link.checkResourceIsReachable()) == true { continue }
try? fm.createSymbolicLink(at: link, withDestinationURL: dir.appendingPathComponent(name))
@@ -32,6 +32,13 @@ enum NativeMessagingHosts {
}
}
+ /// Hosts that let a desktop app drive "Chrome" through its extension. The app
+ /// cannot tell Cra from Chrome, so ChatGPT's computer use switched to Cra (and
+ /// its agent tabs took over Cra's window) instead of using the user's Chrome.
+ private static let excluded: Set<String> = [
+ "com.openai.codexextension.json", // ChatGPT desktop app → ChatGPT extension
+ ]
+
private static var sources: [URL] {
let browsers = ImportSource.allCases.filter { [.chromium, .arc, .dia].contains($0.kind) }
let user = (browsers.filter { $0.id == "chrome" } + browsers.filter { $0.id != "chrome" }).map { $0.dataDir.appendingPathComponent("NativeMessagingHosts", isDirectory: true) }
diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swift
index 6606672..aa2e477 100644
--- a/Sources/Cra/Services/SidebarStore.swift
+++ b/Sources/Cra/Services/SidebarStore.swift
@@ -458,6 +458,16 @@ final class SidebarStore {
touch()
}
+ /// Moves several items so they end up next to each other, in the given
+ /// order, starting at `index` (appended when nil).
+ func moveItems(_ ids: [UUID], to newParent: UUID, index: Int?) {
+ var at = index
+ for id in ids {
+ moveItem(id, to: newParent, index: at)
+ if at != nil, let i = items[newParent]?.children.firstIndex(of: id) { at = i + 1 }
+ }
+ }
+
private func rootContainerKind(_ id: UUID) -> ContainerKind? { rootContainer(of: id) }
// MARK: Split view (Arc: SidebarSplitViewData + WindowAction.SplitViewAction)
@@ -681,7 +691,28 @@ final class SidebarStore {
/// Favorites belong to one space: the tab's own unless another is given.
func addToFavorites(_ id: UUID, in spaceID: UUID? = nil) {
guard let space = spaces[spaceID ?? self.spaceID(ofItem: id) ?? focusedSpaceID] else { return }
+ // A new favorite takes the tile color when every existing one shares it.
+ let colors = Set(tabs(under: space.favoritesContainerID).map { $0.tab?.tileColor })
moveItem(id, to: space.favoritesContainerID, index: nil)
+ if colors.count == 1, let color = colors.first!, items[id]?.tab?.tileColor == nil { setTileColor(color, for: [id]) }
+ }
+
+ func setTileColor(_ hex: String?, for ids: [UUID]) {
+ for id in ids {
+ guard var it = items[id], var t = it.tab else { continue }
+ t.tileColor = hex
+ it.data = .tab(t)
+ items[id] = it
+ }
+ touch()
+ }
+
+ func setCustomIcon(_ key: String?, for id: UUID) {
+ guard var it = items[id], var t = it.tab else { return }
+ t.customIconKey = key
+ it.data = .tab(t)
+ items[id] = it
+ touch()
}
func removeFromFavorites(_ id: UUID) {
@@ -707,6 +738,8 @@ final class SidebarStore {
p.children.insert(folder.id, at: min(index ?? p.children.count, p.children.count))
items[parent] = p
prefs.expandedFolders.insert(folder.id)
+ // A collapsed pinned list would hide the new folder (and its rename field).
+ if case .pinned(let sid)? = rootContainer(of: parent) { prefs.collapsedPinnedSpaces.remove(sid) }
touch()
return folder
}
@@ -716,16 +749,36 @@ final class SidebarStore {
/// the folder at the end of its space's pinned list.
@discardableResult
func createFolder(combining targetID: UUID, with tabID: UUID, named name: String = "New Folder") -> SidebarItem? {
- guard targetID != tabID, items[targetID]?.isTab == true, items[tabID]?.isTab == true,
+ createFolder(combining: targetID, with: [tabID], named: name)
+ }
+
+ @discardableResult
+ func createFolder(combining targetID: UUID, with tabIDs: [UUID], named name: String = "New Folder") -> SidebarItem? {
+ let tabIDs = tabIDs.filter { $0 != targetID && items[$0]?.isTab == true }
+ guard !tabIDs.isEmpty, items[targetID]?.isTab == true,
let parent = items[targetID]?.parentID, let sid = spaceID(ofItem: targetID), let space = spaces[sid] else { return nil }
let inPinned = rootContainer(of: targetID) == .pinned(spaceID: sid)
let folder = createFolder(named: name, in: inPinned ? parent : space.pinnedContainerID,
index: inPinned ? items[parent]?.children.firstIndex(of: targetID) : nil)
- moveItem(targetID, to: folder.id, index: nil)
- moveItem(tabID, to: folder.id, index: nil)
+ moveItems([targetID] + tabIDs, to: folder.id, index: nil)
return items[folder.id]
}
+ func setFolderIcon(_ style: FolderIconStyle?, for id: UUID) {
+ guard var it = items[id], it.isFolder else { return }
+ it.folderIcon = style
+ items[id] = it
+ touch()
+ }
+
+ /// A new folder at the top of the space's pinned list holding these tabs.
+ @discardableResult
+ func createFolder(with tabIDs: [UUID], named name: String = "New Folder") -> SidebarItem {
+ let folder = createFolder(named: name, in: focusedSpace.pinnedContainerID, index: 0)
+ moveItems(tabIDs, to: folder.id, index: nil)
+ return items[folder.id] ?? folder
+ }
+
func deleteFolder(_ id: UUID) {
guard let f = items[id], f.isFolder else { return }
for t in tabs(under: id) { archiveTab(t.id, reason: .manual) }
diff --git a/Sources/Cra/UI/ExtensionsMenu.swift b/Sources/Cra/UI/ExtensionsMenu.swift
index f1bc2a6..ecb891c 100644
--- a/Sources/Cra/UI/ExtensionsMenu.swift
+++ b/Sources/Cra/UI/ExtensionsMenu.swift
@@ -38,7 +38,7 @@ final class ExtensionsMenu: NSObject, NSMenuDelegate, NSMenuItemValidation {
manage.target = self
menu.addItem(manage)
- // Until the toolbar's Extensions popover exists, pinning is a checklist here.
+ // Dia's checklist; the Site Control Center's tiles pin the same list (Arc).
let pin = NSMenuItem(title: "Pin Extensions…", action: nil, keyEquivalent: "")
let pinMenu = NSMenu(title: "Pin Extensions")
for e in entries {
diff --git a/Sources/Cra/UI/Onboarding/ImportFlow.swift b/Sources/Cra/UI/Onboarding/ImportFlow.swift
index 706085f..518cbff 100644
--- a/Sources/Cra/UI/Onboarding/ImportFlow.swift
+++ b/Sources/Cra/UI/Onboarding/ImportFlow.swift
@@ -251,7 +251,7 @@ final class ImportFlowModel {
guard canContinueFromSource, let source else { return }
switch source.kind {
case .safari: go(.safariExport)
- case .firefox: go(.passwordsFile)
+ case .firefox, .zen: go(.passwordsFile)
case .arc, .dia, .chromium: credentialProfiles.isEmpty ? goToSpaces() : go(.unlock)
}
}
@@ -312,7 +312,7 @@ final class ImportFlowModel {
}
/// Safari's exported .zip or folder (bookmarks, history, passwords) or
- /// Firefox's exported passwords CSV.
+ /// Firefox's (or Zen's) exported passwords CSV.
func readExport(_ url: URL) {
guard let source, !readingExport else { return }
readingExport = true
@@ -366,7 +366,7 @@ final class ImportFlowModel {
credentialsStaged = false
switch source.kind {
case .safari: go(.safariExport)
- case .firefox: go(.passwordsFile)
+ case .firefox, .zen: go(.passwordsFile)
default: go(.unlock)
}
}
diff --git a/Sources/Cra/UI/Onboarding/ImportFlowViews.swift b/Sources/Cra/UI/Onboarding/ImportFlowViews.swift
index a1db20f..55a43c0 100644
--- a/Sources/Cra/UI/Onboarding/ImportFlowViews.swift
+++ b/Sources/Cra/UI/Onboarding/ImportFlowViews.swift
@@ -258,7 +258,7 @@ private struct SpacesStep: View {
if !plan.settings.isEmpty {
SelectableRow(c: c, checked: model.includeSettings, toggle: { model.includeSettings.toggle() }) {
RowSymbol(name: "gearshape.fill", c: c)
- RowTitle(title: "Settings", caption: "Auto-archive, sidebar width and toolbar", c: c)
+ RowTitle(title: "Settings", caption: plan.settings.linkRoutes.isEmpty ? "Auto-archive, sidebar width and toolbar" : "Auto-archive, toolbar and Air Traffic Control", c: c)
}
}
}
diff --git a/Sources/Cra/UI/Onboarding/OnboardingSteps.swift b/Sources/Cra/UI/Onboarding/OnboardingSteps.swift
index efd416c..b3ed419 100644
--- a/Sources/Cra/UI/Onboarding/OnboardingSteps.swift
+++ b/Sources/Cra/UI/Onboarding/OnboardingSteps.swift
@@ -134,7 +134,7 @@ struct UnlockStep: View {
}
}
-// MARK: - Exported file (Dia's SafariExportedDataView; also Firefox passwords)
+// MARK: - Exported file (Dia's SafariExportedDataView; also Firefox and Zen passwords)
struct ExportedFileStep: View {
let model: ImportFlowModel
@@ -142,13 +142,14 @@ struct ExportedFileStep: View {
@State private var dropTargeted = false
private var isSafari: Bool { model.source?.kind == .safari }
+ private var browser: String { model.source?.name ?? "Firefox" }
var body: some View {
ZStack(alignment: .topLeading) {
BackLink(c: c) { model.go(.source) }
- StepHeader(title: isSafari ? "Import from Safari" : "Import Firefox passwords",
+ StepHeader(title: isSafari ? "Import from Safari" : "Import \(browser) passwords",
subtitle: isSafari ? "Open Safari and follow these steps to import your passwords, history, and bookmarks."
- : "In Firefox, open Settings ▸ Passwords ▸ ⋯ ▸ Export Passwords, then drop the file here.", c: c)
+ : "In \(browser), open Settings ▸ Passwords ▸ ⋯ ▸ Export Passwords, then drop the file here.", c: c)
VStack(alignment: .leading, spacing: 10) {
if isSafari {
InstructionRow(n: 1, text: "Open the Safari app.", c: c)
diff --git a/Sources/Cra/UI/Settings/AirTrafficControlView.swift b/Sources/Cra/UI/Settings/AirTrafficControlView.swift
new file mode 100644
index 0000000..2988c6a
--- /dev/null
+++ b/Sources/Cra/UI/Settings/AirTrafficControlView.swift
@@ -0,0 +1,168 @@
+import SwiftUI
+
+/// Arc's Air Traffic Control sheet (Settings ▸ Links, Arc 1.170), measured from window
+/// captures and the accessibility tree: title and "New Route" over a hairline, one
+/// two-line route per entry ("🔗 URL [Contains ⌃⌄] [text] ⊖" / "↳ Open in [Space ⌃⌄]",
+/// 52 pt tall on a 76 pt pitch), then "Default" below a second hairline.
+struct AirTrafficControlView: View {
+ @Environment(SidebarStore.self) private var store
+ @Environment(\.dismiss) private var dismiss
+ @FocusState private var focusedRoute: UUID?
+
+ var body: some View {
+ @Bindable var store = store
+ VStack(spacing: 0) {
+ HStack(spacing: 0) {
+ Text("Air Traffic Control").font(.system(size: 13, weight: .bold))
+ Spacer(minLength: 8)
+ Button { addRoute() } label: { Text("New Route").frame(width: 94) }
+ .controlSize(.large)
+ .buttonBorderShape(.roundedRectangle(radius: 6))
+ Button { dismiss() } label: {
+ Image(systemName: "xmark").font(.system(size: 15, weight: .light)).frame(width: 32, height: 32).contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.secondary)
+ .help("Close")
+ .keyboardShortcut(.cancelAction)
+ .padding(.leading, 24)
+ }
+ .frame(height: 76)
+ .padding(.top, 8)
+ Divider()
+ routes
+ Divider()
+ HStack(spacing: 0) {
+ Text("Default").font(.system(size: 13))
+ .frame(width: 104, alignment: .leading)
+ destinationPicker($store.settings.defaultLinkDestination)
+ Spacer(minLength: 0)
+ }
+ .padding(.leading, 36)
+ .frame(height: 90)
+ }
+ .padding(.horizontal, 24)
+ .frame(width: 508, height: 440)
+ // Arc opens the sheet with nothing focused; AppKit would select the first route's text.
+ .onAppear { DispatchQueue.main.async { NSApp.keyWindow?.makeFirstResponder(nil) } }
+ }
+
+ private var routes: some View {
+ ScrollViewReader { proxy in
+ ScrollView(.vertical) {
+ VStack(spacing: 24) {
+ ForEach(store.settings.linkRoutes) { route in
+ routeRow(route.id).id(route.id)
+ }
+ }
+ .padding(.top, 24)
+ .padding(.bottom, 16)
+ .padding(.leading, 31)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .overlay {
+ if store.settings.linkRoutes.isEmpty {
+ Text("Add a route to open matching links from other apps in a chosen space.")
+ .font(.system(size: 12)).foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: 300)
+ }
+ }
+ .onChange(of: store.settings.linkRoutes.last?.id) { _, id in
+ guard let id, focusedRoute == id else { return }
+ withAnimation { proxy.scrollTo(id, anchor: .bottom) }
+ }
+ }
+ .frame(maxHeight: .infinity)
+ }
+
+ private func routeRow(_ id: UUID) -> some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 8) {
+ Label("URL", systemImage: "link")
+ .labelStyle(RouteLabelStyle())
+ .frame(width: 49, alignment: .leading)
+ .accessibilityLabel("Link URL")
+ Picker("Match", selection: binding(id, \.match)) {
+ ForEach(LinkMatchStyle.allCases) { Text($0.label).tag($0) }
+ }
+ .labelsHidden()
+ .frame(width: 110)
+ TextField("URL", text: binding(id, \.text), prompt: Text("crabrowser.app"))
+ .textFieldStyle(.roundedBorder)
+ .focused($focusedRoute, equals: id)
+ .frame(width: 210)
+ Button { removeRoute(id) } label: {
+ Image(systemName: "minus.circle.fill").font(.system(size: 13))
+ .symbolRenderingMode(.palette)
+ .foregroundStyle(.background, .secondary)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Remove")
+ }
+ HStack(spacing: 8) {
+ Label("Open in", systemImage: "arrow.turn.down.right")
+ .labelStyle(RouteLabelStyle())
+ .frame(width: 70, alignment: .leading)
+ destinationPicker(binding(id, \.destination))
+ }
+ .padding(.leading, 74)
+ }
+ }
+
+ /// Arc's destination menu: an "Open in Space" header over Most Recent Space and
+ /// every space, then Little Arc after a separator.
+ private func destinationPicker(_ selection: Binding<LinkDestination>) -> some View {
+ let spaces = store.orderedSpaces
+ // A route to a deleted space opens in the most recent one; show it that way.
+ let shown = Binding<LinkDestination>(
+ get: {
+ if case .space(let sid) = selection.wrappedValue, !spaces.contains(where: { $0.id == sid }) { return .mostRecentSpace }
+ return selection.wrappedValue
+ },
+ set: { selection.wrappedValue = $0 })
+ return Picker("Open in", selection: shown) {
+ Section("Open in Space") {
+ Text("Most Recent Space").tag(LinkDestination.mostRecentSpace)
+ ForEach(spaces) { space in
+ Text("\(space.emoji) \(space.title)").tag(LinkDestination.space(space.id))
+ }
+ }
+ Divider()
+ Text("Little Window").tag(LinkDestination.littleWindow)
+ }
+ .labelsHidden()
+ .frame(width: 165)
+ }
+
+ private func binding<T>(_ id: UUID, _ key: WritableKeyPath<LinkRoute, T>) -> Binding<T> {
+ Binding(
+ get: { store.settings.linkRoutes.first { $0.id == id }.map { $0[keyPath: key] } ?? LinkRoute()[keyPath: key] },
+ set: { value in
+ guard let i = store.settings.linkRoutes.firstIndex(where: { $0.id == id }) else { return }
+ store.settings.linkRoutes[i][keyPath: key] = value
+ })
+ }
+
+ private func addRoute() {
+ let route = LinkRoute()
+ store.settings.linkRoutes.append(route)
+ focusedRoute = route.id
+ }
+
+ private func removeRoute(_ id: UUID) {
+ if focusedRoute == id { focusedRoute = nil }
+ store.settings.linkRoutes.removeAll { $0.id == id }
+ }
+}
+
+/// Secondary 13 pt label with its symbol in front ("🔗 URL", "↳ Open in").
+private struct RouteLabelStyle: LabelStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ HStack(spacing: 6) {
+ configuration.icon.font(.system(size: 12))
+ configuration.title.font(.system(size: 13))
+ }
+ .foregroundStyle(.secondary)
+ }
+}
diff --git a/Sources/Cra/UI/Settings/TabsPane.swift b/Sources/Cra/UI/Settings/TabsPane.swift
index 790c833..1d91521 100644
--- a/Sources/Cra/UI/Settings/TabsPane.swift
+++ b/Sources/Cra/UI/Settings/TabsPane.swift
@@ -14,7 +14,17 @@ struct TabsPane: View {
SettingsCheckbox(title: "Haptic feedback when reordering tabs", isOn: $store.settings.hapticFeedbackOnReorder)
SettingsCheckbox(title: "Show toolbar above the page", isOn: $store.settings.showToolbar)
SettingsCheckbox(title: "Enable Picture in Picture when you leave a video tab", isOn: $store.settings.autoPictureInPicture)
+ }
+ // Arc's Links pane: the Little Arc switch and "Choose where links open inside
+ // Arc." with an "Air Traffic Control…" button.
+ SettingsFormRow(label: "Links:") {
SettingsCheckbox(title: "Links from other apps open in a Little Window", isOn: $store.settings.openExternalLinksInLittleWindow)
+ HStack(spacing: 8) {
+ Button("Air Traffic Control…") { showsAirTrafficControl = true }
+ Text(routesSummary).font(.system(size: 11)).foregroundStyle(.secondary)
+ }
+ Text("Choose which space links from other apps open in.")
+ .font(.system(size: 11)).foregroundStyle(.secondary)
}
SettingsFormRow(label: "Tab Cleanup:") {
HStack(spacing: 6) {
@@ -28,5 +38,18 @@ struct TabsPane: View {
}
}
}
+ .sheet(isPresented: $showsAirTrafficControl) {
+ AirTrafficControlView().environment(store)
+ }
+ }
+
+ @State private var showsAirTrafficControl = false
+
+ private var routesSummary: String {
+ switch store.settings.linkRoutes.count {
+ case 0: return ""
+ case 1: return "1 route"
+ case let n: return "\(n) routes"
+ }
}
}
diff --git a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
index 80a707f..5fb4b04 100644
--- a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
+++ b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
@@ -1,4 +1,5 @@
import SwiftUI
+import UniformTypeIdentifiers
/// Arc's "top apps": a 4-wide grid of favorite tiles. Arc shares them between
/// spaces; in Cra every space has its own.
@@ -58,29 +59,40 @@ struct FavoriteCell: View {
let palette: SpacePalette
@Environment(SidebarStore.self) private var store
@Environment(SidebarUIState.self) private var ui
+ @Environment(FaviconCache.self) private var favicons
@Environment(\.sidebarActions) private var actions
@State private var hover = false
@State private var targeted = false
private var selected: Bool { store.selectedTabID(in: space.id) == item.id }
+ private var tileColor: String? { item.tab?.tileColor }
+ private var tileIsDark: Bool { tileColor.flatMap(HexColor.luminance).map { $0 < 0.5 } ?? palette.isDark }
var body: some View {
let session = ui
ZStack {
- // Arc 1.170: 13pt circular corners; the active tile is the hover fill
- // with a 2pt darker rim, inactive tiles sit ~4.5% darker than the sidebar.
- RoundedRectangle(cornerRadius: 13)
- // Arc 1.170 over white: tile 207/194/166, hovered tile 197/184/158 (another ~4.5% black on top of the tile fill).
- .fill(selected ? (palette.isDark ? Color.white.opacity(0.13) : Color.white.opacity(0.38))
- : (hover || targeted ? (palette.isDark ? Color.white.opacity(0.15) : Color.black.opacity(0.09)) : palette.pillFill))
+ if let tileColor {
+ // A picked color keeps its hue in every state; hover and selection shade it.
+ RoundedRectangle(cornerRadius: 13).fill(Color(hex: tileColor))
+ if selected || hover || targeted {
+ RoundedRectangle(cornerRadius: 13).fill(tileIsDark ? Color.white.opacity(0.12) : Color.black.opacity(0.07))
+ }
+ } else {
+ // Arc 1.170: 13pt circular corners; the active tile is the hover fill
+ // with a 2pt darker rim, inactive tiles sit ~4.5% darker than the sidebar.
+ RoundedRectangle(cornerRadius: 13)
+ // Arc 1.170 over white: tile 207/194/166, hovered tile 197/184/158 (another ~4.5% black on top of the tile fill).
+ .fill(selected ? (palette.isDark ? Color.white.opacity(0.13) : Color.white.opacity(0.38))
+ : (hover || targeted ? (palette.isDark ? Color.white.opacity(0.15) : Color.black.opacity(0.09)) : palette.pillFill))
+ }
if selected {
RoundedRectangle(cornerRadius: 13)
- .strokeBorder(palette.isDark ? Color.white.opacity(0.14) : Color.black.opacity(0.17), lineWidth: 2)
+ .strokeBorder(tileIsDark ? Color.white.opacity(0.14) : Color.black.opacity(0.17), lineWidth: 2)
}
if ui.keyboardFocusID == item.id { FocusRing(radius: 13) }
- FaviconView(key: item.tab?.faviconKey, palette: palette, size: 20)
+ FaviconView(key: item.tab?.iconKey, palette: palette, size: 20, onDark: tileIsDark)
if item.isUnread && !selected {
- Circle().fill(palette.textPrimary.opacity(0.6)).frame(width: 6, height: 6)
+ Circle().fill((tileColor == nil ? palette.textPrimary : (tileIsDark ? .white : .black)).opacity(0.6)).frame(width: 6, height: 6)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)
.padding(5)
}
@@ -107,8 +119,102 @@ struct FavoriteCell: View {
if let t = item.tab, t.url != t.savedURL { Button("Back to Pinned Page") { actions.resetPinnedTab(item.id) } }
Button("Make This the Pinned Page") { store.setPinnedHomeToCurrent(item.id) }
Divider()
+ Button("Change Icon…") { pickIcon() }
+ if let key = item.tab?.customIconKey {
+ Button("Use Site Icon") {
+ store.setCustomIcon(nil, for: item.id)
+ favicons.removeCustomIcon(key)
+ }
+ }
+ tileColorMenu
+ Divider()
Button("Close") { actions.closeTab(item.id) }
Button("Archive") { store.archiveTab(item.id, reason: .manual) }
}
}
+
+ private var tileColorMenu: some View {
+ Menu("Tile Color") {
+ colorToggle("Default", hex: nil)
+ ForEach(TileColor.presets, id: \.hex) { colorToggle($0.name, hex: $0.hex) }
+ if let tileColor, !TileColor.presets.contains(where: { $0.hex == tileColor }) {
+ colorToggle("Custom", hex: tileColor)
+ }
+ Button("Other Color…") {
+ let id = item.id
+ TileColorPanel.shared.show(tileColor) { [store] hex in store.setTileColor(hex, for: [id]) }
+ }
+ Divider()
+ Button("Use This Color for All Favorites") {
+ store.setTileColor(tileColor, for: store.tabs(under: space.favoritesContainerID).map(\.id))
+ }
+ }
+ }
+
+ private func colorToggle(_ name: String, hex: String?) -> some View {
+ Toggle(isOn: Binding(get: { tileColor == hex }, set: { _ in store.setTileColor(hex, for: [item.id]) })) {
+ Label { Text(name) } icon: { Image(nsImage: TileColor.swatch(hex)) }
+ }
+ }
+
+ private func pickIcon() {
+ let panel = NSOpenPanel()
+ panel.allowedContentTypes = [.image]
+ panel.allowsMultipleSelection = false
+ panel.prompt = "Use Icon"
+ panel.message = "Choose an image for \(item.displayTitle)."
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+ guard let key = favicons.importCustomIcon(from: url) else { NSSound.beep(); return }
+ let old = item.tab?.customIconKey
+ store.setCustomIcon(key, for: item.id)
+ if let old { favicons.removeCustomIcon(old) }
+ }
+}
+
+/// Tile backgrounds offered in a favorite's "Tile Color" menu.
+enum TileColor {
+ static let presets: [(name: String, hex: String)] = [
+ ("White", "#FFFFFF"), ("Light Gray", "#D9D9DE"), ("Graphite", "#48484A"), ("Black", "#000000"),
+ ("Red", "#FF453A"), ("Orange", "#FF9F0A"), ("Yellow", "#FFD60A"), ("Green", "#30D158"),
+ ("Teal", "#40C8E0"), ("Blue", "#0A84FF"), ("Purple", "#BF5AF2"), ("Pink", "#FF375F"),
+ ]
+
+ /// A 12pt dot for the menu; Default is drawn hollow.
+ static func swatch(_ hex: String?) -> NSImage {
+ NSImage(size: NSSize(width: 12, height: 12), flipped: false) { rect in
+ let path = NSBezierPath(ovalIn: rect.insetBy(dx: 0.5, dy: 0.5))
+ if let hex { NSColor(hex: hex).setFill(); path.fill() }
+ NSColor.secondaryLabelColor.setStroke()
+ path.lineWidth = 1
+ path.stroke()
+ return true
+ }
+ }
+}
+
+/// Routes the shared color panel to whichever favorite asked for it last.
+@MainActor
+final class TileColorPanel: NSObject {
+ static let shared = TileColorPanel()
+ private var onChange: ((String) -> Void)?
+
+ func show(_ hex: String?, onChange: @escaping (String) -> Void) {
+ let panel = NSColorPanel.shared
+ // Detach first so seeding the color doesn't recolor the previous tile.
+ panel.setTarget(nil)
+ panel.setAction(nil)
+ panel.showsAlpha = false
+ panel.isContinuous = true
+ if let hex { panel.color = NSColor(hex: hex) }
+ self.onChange = onChange
+ panel.setTarget(self)
+ panel.setAction(#selector(changed(_:)))
+ panel.orderFront(nil)
+ }
+
+ @objc private func changed(_ panel: NSColorPanel) {
+ guard let c = panel.color.usingColorSpace(.sRGB) else { return }
+ onChange?(String(format: "#%02X%02X%02X", Int((c.redComponent * 255).rounded()),
+ Int((c.greenComponent * 255).rounded()), Int((c.blueComponent * 255).rounded())))
+ }
}
diff --git a/Sources/Cra/UI/Sidebar/SidebarItemView.swift b/Sources/Cra/UI/Sidebar/SidebarItemView.swift
index 410f773..979b1e3 100644
--- a/Sources/Cra/UI/Sidebar/SidebarItemView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarItemView.swift
@@ -31,14 +31,21 @@ struct FaviconView: View {
let key: String?
let palette: SpacePalette
var size: CGFloat = CraMetrics.favicon
+ /// Whether the icon sits on a dark fill; defaults to the sidebar's.
+ var onDark: Bool?
@Environment(FaviconCache.self) private var favicons
var body: some View {
if let img = favicons.image(forKey: key) {
+ // One-color glyphs (GitHub) flip to white on dark fills and black on light ones.
+ let dark = onDark ?? palette.isDark
+ let flip = favicons.glyphIsDark(forKey: key) == dark
Image(nsImage: img)
.resizable()
+ .renderingMode(flip ? .template : .original)
.interpolation(.high)
.aspectRatio(contentMode: .fit)
+ .foregroundStyle(dark ? Color.white.opacity(0.92) : Color.black.opacity(0.85))
.frame(width: size, height: size)
.clipShape(RoundedRectangle(cornerRadius: size * 0.22, style: .continuous))
} else {
@@ -83,7 +90,7 @@ struct TabRow: View {
var body: some View {
let session = ui
HStack(spacing: 11) {
- FaviconView(key: tab.faviconKey, palette: palette)
+ FaviconView(key: tab.iconKey, palette: palette)
.frame(width: CraMetrics.favicon)
if editing {
TextField("", text: $draft)
@@ -152,9 +159,18 @@ struct TabRow: View {
}
}
.draggable(SidebarDragItem.begin(item.id, session)) {
+ // Dragging one of several picked tabs moves them all.
HStack(spacing: 8) {
- FaviconView(key: tab.faviconKey, palette: palette)
+ FaviconView(key: tab.iconKey, palette: palette)
Text(item.displayTitle).font(.system(size: 14)).lineLimit(1)
+ if closeGroup.count > 1 {
+ Text("\(closeGroup.count)")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(.white)
+ .padding(.horizontal, 6)
+ .frame(minWidth: 18, minHeight: 18)
+ .background(Capsule().fill(Color.accentColor))
+ }
}
.padding(8)
.background(RoundedRectangle(cornerRadius: 8).fill(.regularMaterial))
@@ -182,6 +198,8 @@ struct TabRow: View {
@ViewBuilder
private var contextMenu: some View {
if closeGroup.count > 1 {
+ folderMenu(ui.group(for: item.id, in: store))
+ Divider()
Button("Close \(closeGroup.count) Tabs") { closeTabs(closeGroup) }
Button("Deselect All") { ui.clearPicks() }
} else {
@@ -189,6 +207,25 @@ struct TabRow: View {
}
}
+ /// Move to Folder / New Folder for this tab, or for every picked tab.
+ @ViewBuilder
+ private func folderMenu(_ ids: [UUID]) -> some View {
+ let folders = store.children(of: store.focusedSpace.pinnedContainerID).filter { $0.isFolder }
+ if !folders.isEmpty {
+ Menu(ids.count > 1 ? "Move \(ids.count) Tabs to Folder" : "Move to Folder") {
+ ForEach(folders) { f in
+ Button(f.title ?? "Folder") {
+ withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { store.moveItems(ids, to: f.id, index: nil) }
+ }
+ .disabled(ids.allSatisfy { store.item($0)?.parentID == f.id })
+ }
+ }
+ }
+ Button(ids.count > 1 ? "New Folder with \(ids.count) Tabs" : "New Folder with Tab") {
+ withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { ui.renamingID = store.createFolder(with: ids).id }
+ }
+ }
+
@ViewBuilder
private var singleTabMenu: some View {
if pinned {
@@ -222,20 +259,7 @@ struct TabRow: View {
.disabled(s.id == store.spaceID(ofItem: item.id))
}
}
- let folders = store.children(of: store.focusedSpace.pinnedContainerID).filter { $0.isFolder }
- if !folders.isEmpty {
- Menu("Move to Folder") {
- ForEach(folders) { f in
- Button(f.title ?? "Folder") { store.moveItem(item.id, to: f.id, index: nil) }
- .disabled(f.id == item.parentID)
- }
- }
- }
- Button("New Folder with Tab") {
- let f = store.createFolder(named: "New Folder", in: store.focusedSpace.pinnedContainerID, index: 0)
- store.moveItem(item.id, to: f.id, index: nil)
- ui.renamingID = f.id
- }
+ folderMenu([item.id])
Divider()
Button(pinned ? "Close" : "Archive") { actions.closeTab(item.id) }
if pinned { Button("Unpin and Archive") { store.archiveTab(item.id, reason: .manual) } }
@@ -257,12 +281,13 @@ struct FolderRow: View {
var body: some View {
let session = ui
+ let glyph = palette.folderColors(item.folderIcon)
HStack(spacing: 11) {
ZStack {
if !expanded {
- Image(systemName: "folder.fill").foregroundStyle(palette.folderFill)
+ Image(systemName: "folder.fill").foregroundStyle(glyph.fill)
}
- Image(systemName: "folder").foregroundStyle(palette.folderTint)
+ Image(systemName: "folder").foregroundStyle(glyph.tint)
}
.font(.system(size: 15, weight: .regular))
.frame(width: CraMetrics.favicon)
@@ -309,6 +334,11 @@ struct FolderRow: View {
store.setExpanded(item.id, true)
ui.renamingID = f.id
}
+ Picker("Icon Color", selection: Binding(get: { item.folderIcon }, set: { store.setFolderIcon($0, for: item.id) })) {
+ Text("Auto").tag(FolderIconStyle?.none)
+ Text("White").tag(FolderIconStyle?.some(.white))
+ Text("Black").tag(FolderIconStyle?.some(.black))
+ }
Divider()
Button("Delete Folder (archives tabs)") { store.deleteFolder(item.id) }
}
diff --git a/Sources/Cra/UI/Sidebar/SidebarListDrop.swift b/Sources/Cra/UI/Sidebar/SidebarListDrop.swift
index e7f1e56..0ef0b0e 100644
--- a/Sources/Cra/UI/Sidebar/SidebarListDrop.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarListDrop.swift
@@ -180,16 +180,22 @@ struct SidebarListDropDelegate: DropDelegate {
private func apply(_ drop: SidebarListDrop) {
let id = drop.draggedID
+ // A picked tab carries the other picks along (a split still takes one pane).
+ let group = ui.group(for: id, in: store)
switch drop.target {
case .insert(let parent, let index)?:
- store.moveItem(id, to: parent, index: index)
+ store.moveItems(group, to: parent, index: index)
case .newFolder(let tab)?:
- if let folder = store.createFolder(combining: tab, with: id) { ui.renamingID = folder.id }
+ if let folder = store.createFolder(combining: tab, with: group) { ui.renamingID = folder.id }
case .split(let tab, let leading)?:
store.createSplit(with: leading ? [id, tab] : [tab, id], at: tab)
case .into(let target)?:
- store.moveItem(id, to: target, index: nil)
- if store.item(target)?.isFolder == true { store.setExpanded(target, true) }
+ if store.item(target)?.isFolder == true {
+ store.moveItems(group, to: target, index: nil)
+ store.setExpanded(target, true)
+ } else {
+ store.moveItem(id, to: target, index: nil)
+ }
case nil:
break
}
@@ -240,6 +246,7 @@ struct SidebarListDropDelegate: DropDelegate {
/// a new folder, a split row takes a pane.
func resolve(dragged id: UUID, at p: CGPoint) -> SidebarListDrop {
let rows = visibleRows()
+ let group = ui.group(for: id, in: store)
let isTab = store.item(id)?.isTab == true
let half = CraMetrics.rowSpacing / 2
var target: SidebarListDrop.Target?
@@ -249,7 +256,7 @@ struct SidebarListDropDelegate: DropDelegate {
let middle = (0.25..<0.75).contains(f)
let before = SidebarListDrop.Target.insert(parent: r.parent, index: r.index)
let after = SidebarListDrop.Target.insert(parent: r.parent, index: r.index + 1)
- if r.item.id == id || isInside(r.item.id, id) {
+ if group.contains(r.item.id) || isInside(r.item.id, id) {
target = nil
} else if r.item.isFolder {
if f < 0.25 { target = before }
@@ -279,7 +286,7 @@ struct SidebarListDropDelegate: DropDelegate {
if case .insert(let parent, let index)? = target {
if parent == id || isInside(parent, id) {
target = nil
- } else if store.item(id)?.parentID == parent, let old = store.item(parent)?.children.firstIndex(of: id), index == old || index == old + 1 {
+ } else if group.count == 1, store.item(id)?.parentID == parent, let old = store.item(parent)?.children.firstIndex(of: id), index == old || index == old + 1 {
target = nil
}
}
@@ -350,7 +357,7 @@ struct SidebarDropPreview: ViewModifier {
.allowsHitTesting(false)
}
}
- .opacity(combine != nil ? 0 : (drop?.draggedID == id ? 0.4 : 1))
+ .opacity(combine != nil ? 0 : (drop.map { isDragged($0.draggedID) } ?? false ? 0.4 : 1))
.overlay {
if let combine, let target = store.item(id), let dragged = store.item(combine.dragged) {
CombineDropPreview(kind: combine.kind, target: target, dragged: dragged, depth: depth, palette: palette)
@@ -362,6 +369,11 @@ struct SidebarDropPreview: ViewModifier {
.visualEffect { content, _ in content.offset(y: nudge) }
}
+ /// This row is being dragged, itself or as one of the picked tabs.
+ private func isDragged(_ draggedID: UUID) -> Bool {
+ draggedID == id || (ui.multiSelection.count > 1 && ui.multiSelection.contains(draggedID) && ui.multiSelection.contains(id))
+ }
+
private func combine(for drop: SidebarListDrop?) -> (kind: CombineDropPreview.Kind, dragged: UUID)? {
switch drop?.target {
case .split(let t, let leading)? where t == id: return (.split(leading: leading), drop!.draggedID)
@@ -453,7 +465,7 @@ struct CombineDropPreview: View {
private func cell(_ item: SidebarItem) -> some View {
HStack(spacing: 8) {
- FaviconView(key: item.tab?.faviconKey, palette: palette)
+ FaviconView(key: item.tab?.iconKey, palette: palette)
.frame(width: CraMetrics.favicon)
Text(item.displayTitle)
.font(.system(size: 14))
@@ -498,7 +510,7 @@ struct CombineDropPreview: View {
}
private func stackedIcon(_ item: SidebarItem) -> some View {
- FaviconView(key: item.tab?.faviconKey, palette: palette, size: 14)
+ FaviconView(key: item.tab?.iconKey, palette: palette, size: 14)
.padding(3)
.background(
RoundedRectangle(cornerRadius: 5, style: .continuous)
diff --git a/Sources/Cra/UI/Sidebar/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
index 6cc3593..82072e3 100644
--- a/Sources/Cra/UI/Sidebar/SidebarRootView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
@@ -289,19 +289,28 @@ struct SpaceSectionView: View {
SpaceHeader(space: space, palette: palette)
.padding(.horizontal, 10)
.padding(.bottom, 3)
- ScrollView(.vertical, showsIndicators: false) {
- rows
- .padding(.top, 3)
- .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(Self.scrollSpace)) } action: { rowsFrame = $0 }
- // Arc leaves ~121pt of empty list after the last row at full scroll.
- .padding(.bottom, 121)
- .overlay(alignment: .topLeading) { dropLine }
- .background(DragAutoscroller.Anchor(scroller: autoscroller))
- .contentShape(Rectangle())
- .onDrop(of: [.craSidebarItem], delegate: SidebarListDropDelegate(space: space, store: store, ui: ui, autoscroller: autoscroller))
- // Safety net: a drag that ended without an exit callback leaves no preview behind.
- .onContinuousHover { _ in if ui.listDrop != nil, NSEvent.pressedMouseButtons == 0 { ui.listDrop = nil } }
- .coordinateSpace(name: SidebarListDropDelegate.coordinateSpace)
+ ScrollViewReader { proxy in
+ ScrollView(.vertical, showsIndicators: false) {
+ rows
+ .padding(.top, 3)
+ .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(Self.scrollSpace)) } action: { rowsFrame = $0 }
+ // Arc leaves ~121pt of empty list after the last row at full scroll.
+ .padding(.bottom, 121)
+ .overlay(alignment: .topLeading) { dropLine }
+ .background(DragAutoscroller.Anchor(scroller: autoscroller))
+ .contentShape(Rectangle())
+ // Right-click on empty list space; rows have their own menus.
+ .contextMenu { listMenu }
+ .onDrop(of: [.craSidebarItem], delegate: SidebarListDropDelegate(space: space, store: store, ui: ui, autoscroller: autoscroller))
+ // Safety net: a drag that ended without an exit callback leaves no preview behind.
+ .onContinuousHover { _ in if ui.listDrop != nil, NSEvent.pressedMouseButtons == 0 { ui.listDrop = nil } }
+ .coordinateSpace(name: SidebarListDropDelegate.coordinateSpace)
+ }
+ // A new folder starts renaming at the top of pinned, maybe scrolled away.
+ .onChange(of: ui.renamingID) { _, id in
+ guard let id else { return }
+ withAnimation(.snappy(duration: 0.25, extraBounce: 0)) { proxy.scrollTo(id) }
+ }
}
.coordinateSpace(name: Self.scrollSpace)
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: { viewportHeight = $0 }
@@ -314,6 +323,17 @@ struct SpaceSectionView: View {
private static let scrollSpace = "spaceSectionScroll"
+ @ViewBuilder
+ private var listMenu: some View {
+ Button("New Tab") { actions.openCommandBar(.newTab) }
+ Button("New Folder") { actions.performAction("newFolder") }
+ Divider()
+ if !store.children(of: space.todayContainerID).isEmpty {
+ Button("Clear Today") { store.clearToday(space.id) }
+ }
+ Button("Edit Space…") { actions.editSpace(space) }
+ }
+
@ViewBuilder
private var dropLine: some View {
if let line = ui.listDrop?.line {
@@ -376,6 +396,7 @@ struct SpaceSectionView: View {
VStack(spacing: CraMetrics.rowSpacing) {
ForEach(pinnedItems) { item in
SidebarItemView(item: item, depth: 0, palette: palette, section: .pinned)
+ .id(item.id)
}
// With nothing pinned the list is 8pt tall; a drag opens a real target.
// Not when collapsed: the placeholder would claim an empty list and
@@ -408,6 +429,7 @@ struct SpaceSectionView: View {
VStack(spacing: CraMetrics.rowSpacing) {
ForEach(todayItems) { item in
SidebarItemView(item: item, depth: 0, palette: palette, section: .today)
+ .id(item.id)
}
NewTabRow(palette: palette)
}
diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swift
index 5bae083..7fd38ec 100644
--- a/Sources/Cra/UI/SidebarUIState.swift
+++ b/Sources/Cra/UI/SidebarUIState.swift
@@ -93,6 +93,13 @@ final class SidebarUIState {
}
}
+ /// The tabs an action on this row moves: every picked tab, in sidebar
+ /// order, when the row is one of several picks; otherwise just the row.
+ func group(for id: UUID, in store: SidebarStore) -> [UUID] {
+ guard multiSelection.count > 1, multiSelection.contains(id) else { return [id] }
+ return store.listedTabIDs(in: store.focusedSpaceID).filter { multiSelection.contains($0) }
+ }
+
func clearPicks(anchor: UUID? = nil) {
if !multiSelection.isEmpty { multiSelection = [] }
selectionAnchor = anchor
diff --git a/Sources/Cra/UI/SiteControlCenter.swift b/Sources/Cra/UI/SiteControlCenter.swift
new file mode 100644
index 0000000..44bf4e6
--- /dev/null
+++ b/Sources/Cra/UI/SiteControlCenter.swift
@@ -0,0 +1,395 @@
+import AppKit
+import SwiftUI
+
+/// Arc 1.170's Site Control Center: the sliders button at the end of the toolbar and of the
+/// sidebar's URL pill (SiteControlCenterView in ARC_SiteControlCenter). Geometry and colours
+/// were read from Arc's accessibility tree and captures of the open popover (26 Oct 2026):
+/// a 236 pt column, a row of four 48×32 action buttons, "Extensions" with a 4-column grid of
+/// 48×32 tiles (pinned first, then by name, then "+"), "Settings" rows of 208×33 and a footer
+/// with the connection state and a More menu. A tile's 14 pt badge pins it to the toolbar:
+/// filled for pinned extensions, grey on hover for the others.
+struct SiteControlCenterActions {
+ var share: () -> Void = {}
+ var copyURL: () -> Void = {}
+ var capture: () -> Void = {}
+ var captureFullPage: () -> Void = {}
+ var runExtension: (String) -> Void = { _ in }
+ var addExtension: () -> Void = {}
+ var manageExtensions: () -> Void = {}
+ var clearCache: () -> Void = {}
+ var clearCookies: () -> Void = {}
+ var siteSettings: () -> Void = {}
+}
+
+enum SiteControlCenterMetrics {
+ static let width: CGFloat = 236
+ static let inset: CGFloat = 10
+ static let tile = CGSize(width: 48, height: 32)
+ static let gap: CGFloat = 8
+}
+
+struct SiteControlCenterView: View {
+ let url: String
+ let dark: Bool
+ let actions: SiteControlCenterActions
+ @Environment(SidebarStore.self) private var store
+ private var extensions: ExtensionStore { .shared }
+
+ private var colors: SiteControlCenterColors { SiteControlCenterColors(dark: dark) }
+
+ /// Arc: pinned extensions in toolbar order, then the rest by name.
+ private var orderedExtensions: [ExtensionStore.Entry] {
+ let entries = extensions.entries
+ let pinned = extensions.pinnedIDs.compactMap { id in entries.first { $0.extensionID == id } }
+ let rest = entries.filter { !extensions.isPinned($0.extensionID) }
+ .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
+ return pinned + rest
+ }
+
+ private var isSecure: Bool { url.hasPrefix("https://") || url.hasPrefix("chrome://") || url.hasPrefix("chrome-extension://") }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ actionRow
+ .padding(.bottom, 11)
+ SiteControlCenterSection(title: "Extensions", hoverText: "Manage", colors: colors, onHeaderClick: actions.manageExtensions) {
+ extensionGrid
+ }
+ .padding(.bottom, 15)
+ SiteControlCenterSection(title: "Settings", hoverText: nil, colors: colors, onHeaderClick: {}) {
+ settings
+ }
+ Rectangle().fill(colors.divider).frame(height: 1)
+ .padding(.top, 13).padding(.bottom, 12)
+ footer
+ }
+ .padding(.top, 9)
+ .padding([.horizontal, .bottom], SiteControlCenterMetrics.inset)
+ .frame(width: SiteControlCenterMetrics.width)
+ }
+
+ private var actionRow: some View {
+ HStack(spacing: SiteControlCenterMetrics.gap) {
+ SiteControlCenterActionButton(symbol: "square.and.arrow.up", help: "Share", colors: colors, action: actions.share)
+ SiteControlCenterActionButton(symbol: "link", help: "Copy URL", colors: colors, action: actions.copyURL)
+ SiteControlCenterActionButton(symbol: "camera", help: "Capture this page", colors: colors, action: actions.capture)
+ SiteControlCenterActionButton(symbol: "text.viewfinder", help: "Capture the full page", colors: colors, action: actions.captureFullPage)
+ }
+ }
+
+ private var extensionGrid: some View {
+ let columns = Array(repeating: GridItem(.fixed(SiteControlCenterMetrics.tile.width), spacing: SiteControlCenterMetrics.gap), count: 4)
+ return LazyVGrid(columns: columns, alignment: .leading, spacing: SiteControlCenterMetrics.gap) {
+ ForEach(orderedExtensions) { e in
+ SiteControlCenterExtensionButton(entry: e, pinned: extensions.isPinned(e.extensionID), colors: colors,
+ run: { actions.runExtension(e.extensionID) },
+ togglePin: { extensions.setPinned(e.extensionID, !extensions.isPinned(e.extensionID)) })
+ }
+ SiteControlCenterTile(colors: colors, help: "Add Extension", action: actions.addExtension) {
+ Image(systemName: "plus").font(.system(size: 14, weight: .medium)).foregroundStyle(colors.text)
+ }
+ }
+ }
+
+ private var settings: some View {
+ let developer = store.settings.isDeveloperMode(url: url)
+ return VStack(alignment: .leading, spacing: 10) {
+ SiteControlCenterSettingRow(symbol: "hammer.fill", title: "Developer Mode", subtitle: developer ? "On" : "Off",
+ active: developer, colors: colors) { store.settings.toggleDeveloperMode(url: url) }
+ SiteControlCenterSettingRow(symbol: "shield.fill", title: "Block Ads & Trackers",
+ subtitle: store.settings.blockAdsAndTrackers ? "On" : "Off",
+ active: store.settings.blockAdsAndTrackers, colors: colors) { store.settings.blockAdsAndTrackers.toggle() }
+ SiteControlCenterSettingRow(symbol: "gearshape.fill", title: "Automatic Picture-In-Picture",
+ subtitle: store.settings.autoPictureInPicture ? "Allowed" : "Disabled",
+ active: store.settings.autoPictureInPicture, colors: colors) { store.settings.autoPictureInPicture.toggle() }
+ }
+ }
+
+ private var footer: some View {
+ HStack(spacing: 0) {
+ HStack(spacing: 6) {
+ Image(systemName: isSecure ? "lock.fill" : "lock.open.fill").font(.system(size: 12, weight: .semibold))
+ Text(isSecure ? "Secure" : "Not Secure").font(.system(size: 14, weight: .semibold))
+ }
+ .foregroundStyle(colors.text)
+ .padding(.horizontal, 10)
+ .frame(height: 32)
+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(colors.footerFill))
+ .help(isSecure ? "Your connection to this site is secure" : "Your connection to this site is not secure")
+ Spacer(minLength: 0)
+ SiteControlCenterMoreButton(colors: colors, actions: actions)
+ }
+ }
+}
+
+/// Arc's site control center palette (dark values sampled from Arc 1.170; light ones mirror them).
+struct SiteControlCenterColors {
+ let dark: Bool
+ var background: Color { dark ? Color(hex: "#272728") : Color(hex: "#F4F4F5") }
+ var tile: Color { dark ? .white.opacity(0.07) : .black.opacity(0.05) }
+ var tileHover: Color { dark ? .white.opacity(0.09) : .black.opacity(0.08) }
+ var text: Color { dark ? Color(hex: "#DCDCDC") : Color(hex: "#232325") }
+ var header: Color { dark ? Color(hex: "#D4D4D5") : Color(hex: "#2A2A2C") }
+ var secondary: Color { dark ? Color(hex: "#979798") : Color(hex: "#6E6E73") }
+ var divider: Color { dark ? .white.opacity(0.1) : .black.opacity(0.1) }
+ var footerFill: Color { dark ? Color(hex: "#363536") : .black.opacity(0.05) }
+ var moreFill: Color { dark ? Color(hex: "#403F40") : .black.opacity(0.08) }
+ /// Pinned badge and active setting circles.
+ /// Light themes invert Arc's dark-theme pair: a near-white badge vanishes on light tiles.
+ var accent: Color { dark ? Color(hex: "#F0F1FE") : Color(hex: "#232325") }
+ var inactive: Color { dark ? Color(hex: "#6A6A6F") : Color(hex: "#C7C7CC") }
+ var pinHover: Color { dark ? Color(hex: "#7F7E85") : Color(hex: "#8E8E93") }
+ var glyphOnAccent: Color { dark ? Color(hex: "#232325") : .white }
+ var glyphOnInactive: Color { dark ? Color(hex: "#232325") : Color(hex: "#3A3A3C") }
+ /// The pin glyph: cut out of the badge in the panel colour (dark), white on light themes.
+ var pinGlyph: Color { dark ? background : .white }
+ func actionFill(hovered: Bool) -> [Color] {
+ dark ? [Color(hex: hovered ? "#3C3C3C" : "#363636"), Color(hex: hovered ? "#272727" : "#212121")]
+ : [Color(hex: hovered ? "#FFFFFF" : "#FDFDFD"), Color(hex: hovered ? "#F2F2F2" : "#EDEDED")]
+ }
+ var actionHighlight: Color { dark ? Color(hex: "#69696A") : .white }
+ var actionOutline: Color { dark ? Color(hex: "#141115") : .black.opacity(0.14) }
+}
+
+/// A titled section; hovering it shows `hoverText` at the header's right end (Arc: "Manage").
+private struct SiteControlCenterSection<Content: View>: View {
+ let title: String
+ let hoverText: String?
+ let colors: SiteControlCenterColors
+ let onHeaderClick: () -> Void
+ @ViewBuilder let content: Content
+ @State private var hovered = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 0) {
+ Text(title).font(.system(size: 14, weight: .bold)).foregroundStyle(colors.header)
+ Spacer(minLength: 0)
+ if let hoverText, hovered {
+ Button(action: onHeaderClick) {
+ Text(hoverText).font(.system(size: 12, weight: .semibold)).foregroundStyle(colors.secondary)
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ .frame(height: 17)
+ content
+ }
+ .contentShape(Rectangle())
+ .onHover { hovered = $0 }
+ }
+}
+
+private struct SiteControlCenterTile<Label: View>: View {
+ let colors: SiteControlCenterColors
+ var help: String = ""
+ let action: () -> Void
+ @ViewBuilder let label: Label
+ @State private var hovered = false
+
+ var body: some View {
+ Button(action: action) {
+ label
+ .frame(width: SiteControlCenterMetrics.tile.width, height: SiteControlCenterMetrics.tile.height)
+ .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(hovered ? colors.tileHover : colors.tile))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .onHover { hovered = $0 }
+ .help(help)
+ }
+}
+
+private struct SiteControlCenterActionButton: View {
+ let symbol: String
+ let help: String
+ let colors: SiteControlCenterColors
+ let action: () -> Void
+
+ @State private var hovered = false
+
+ /// Arc draws these raised: a top-lit gradient, a light top edge and a dark outline.
+ var body: some View {
+ let shape = RoundedRectangle(cornerRadius: 7, style: .continuous)
+ Button(action: action) {
+ Image(systemName: symbol).font(.system(size: 15, weight: .regular)).foregroundStyle(colors.text)
+ .frame(width: SiteControlCenterMetrics.tile.width, height: SiteControlCenterMetrics.tile.height)
+ .background(shape.fill(LinearGradient(colors: colors.actionFill(hovered: hovered), startPoint: .top, endPoint: .bottom)))
+ .overlay(shape.inset(by: 0.5).stroke(LinearGradient(colors: [colors.actionHighlight, .clear], startPoint: .top, endPoint: .center), lineWidth: 1))
+ .overlay(shape.stroke(colors.actionOutline, lineWidth: 0.5))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .onHover { hovered = $0 }
+ .help(help)
+ }
+}
+
+/// An extension tile: click runs it, the badge pins or unpins it (Arc's
+/// SiteControlCenterExtensionPinButton, "Pin" / "Unpin").
+private struct SiteControlCenterExtensionButton: View {
+ let entry: ExtensionStore.Entry
+ let pinned: Bool
+ let colors: SiteControlCenterColors
+ let run: () -> Void
+ let togglePin: () -> Void
+ @State private var hovered = false
+
+ var body: some View {
+ ZStack(alignment: .topLeading) {
+ Button(action: run) {
+ Group {
+ if let icon = entry.icon {
+ Image(nsImage: icon).resizable().interpolation(.high).frame(width: 16, height: 16)
+ } else {
+ Image(systemName: "puzzlepiece.extension.fill").font(.system(size: 13)).foregroundStyle(colors.secondary)
+ }
+ }
+ .frame(width: SiteControlCenterMetrics.tile.width, height: SiteControlCenterMetrics.tile.height)
+ .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(hovered ? colors.tileHover : colors.tile))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .help(entry.name)
+ .accessibilityLabel(entry.name)
+ if pinned || hovered {
+ Button(action: togglePin) {
+ Image(systemName: "pin.fill")
+ .font(.system(size: 8, weight: .bold))
+ .rotationEffect(.degrees(45))
+ .foregroundStyle(colors.pinGlyph)
+ .frame(width: 14, height: 14)
+ .background(Circle().fill(pinned ? colors.accent : colors.pinHover))
+ .overlay(Circle().strokeBorder(colors.background, lineWidth: 1))
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .help(pinned ? "Unpin" : "Pin")
+ .accessibilityLabel(pinned ? "Unpin" : "Pin")
+ .offset(x: 37, y: 21)
+ }
+ }
+ .frame(width: SiteControlCenterMetrics.tile.width, height: SiteControlCenterMetrics.tile.height, alignment: .topLeading)
+ .onHover { hovered = $0 }
+ }
+}
+
+private struct SiteControlCenterSettingRow: View {
+ let symbol: String
+ let title: String
+ let subtitle: String
+ let active: Bool
+ let colors: SiteControlCenterColors
+ let action: () -> Void
+ @State private var hovered = false
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 8) {
+ Image(systemName: symbol)
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(active ? colors.glyphOnAccent : colors.glyphOnInactive)
+ .frame(width: 32, height: 32)
+ .background(Circle().fill(active ? colors.accent : colors.inactive))
+ VStack(alignment: .leading, spacing: 0) {
+ Text(title).font(.system(size: 14, weight: .semibold)).foregroundStyle(colors.text)
+ .lineLimit(1).truncationMode(.tail)
+ Text(subtitle).font(.system(size: 13)).foregroundStyle(colors.secondary)
+ }
+ Spacer(minLength: 0)
+ }
+ .frame(width: 208, height: 33, alignment: .leading)
+ .contentShape(Rectangle())
+ .opacity(hovered ? 0.85 : 1)
+ }
+ .buttonStyle(.plain)
+ .onHover { hovered = $0 }
+ .accessibilityLabel("\(title), \(subtitle)")
+ }
+}
+
+/// Arc's footer "…": Clear Cache, Clear Cookies, Manage Extensions, Add Extension, All Site Settings.
+private struct SiteControlCenterMoreButton: View {
+ let colors: SiteControlCenterColors
+ let actions: SiteControlCenterActions
+ @State private var hovered = false
+
+ var body: some View {
+ Button(action: showMenu) {
+ Image(systemName: "ellipsis").font(.system(size: 13, weight: .bold)).foregroundStyle(colors.text)
+ .frame(width: 32, height: 32)
+ .background(Circle().fill(colors.moreFill).brightness(hovered ? 0.04 : 0))
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .onHover { hovered = $0 }
+ .help("More")
+ .accessibilityLabel("More")
+ }
+
+ private func showMenu() {
+ let menu = NSMenu()
+ func add(_ title: String, _ action: @escaping () -> Void) { menu.addItem(BlockMenuItem(title: title, action: action)) }
+ add("Clear Cache", actions.clearCache)
+ add("Clear Cookies", actions.clearCookies)
+ menu.addItem(.separator())
+ add("Manage Extensions", actions.manageExtensions)
+ add("Add Extension", actions.addExtension)
+ menu.addItem(.separator())
+ add("All Site Settings", actions.siteSettings)
+ menu.popUp(positioning: nil, at: NSEvent.mouseLocation, in: nil)
+ }
+}
+
+private final class BlockMenuItem: NSMenuItem {
+ private let block: () -> Void
+ init(title: String, action: @escaping () -> Void) {
+ block = action
+ super.init(title: title, action: #selector(run), keyEquivalent: "")
+ target = self
+ }
+ required init(coder: NSCoder) { fatalError() }
+ @objc private func run() { block() }
+}
+
+/// Shows the Site Control Center in an NSPopover under a toolbar or pill button.
+@MainActor
+final class SiteControlCenterPopover: NSObject, NSPopoverDelegate {
+ private var popover: NSPopover?
+
+ var isShown: Bool { popover?.isShown == true }
+
+ func show(relativeTo rect: NSRect, of view: NSView, url: String, dark: Bool, store: SidebarStore, actions: SiteControlCenterActions) {
+ if let popover, popover.isShown { popover.performClose(nil); return }
+ let p = NSPopover()
+ p.behavior = .transient
+ p.animates = true
+ p.delegate = self
+ p.appearance = NSAppearance(named: dark ? .darkAqua : .aqua)
+ var acts = actions
+ // Every action ends the popover, as in Arc (pinning keeps it open).
+ func closing(_ f: @escaping () -> Void) -> () -> Void { { [weak p] in p?.performClose(nil); f() } }
+ acts.share = closing(actions.share)
+ acts.copyURL = closing(actions.copyURL)
+ acts.capture = closing(actions.capture)
+ acts.captureFullPage = closing(actions.captureFullPage)
+ acts.runExtension = { [weak p] id in p?.performClose(nil); actions.runExtension(id) }
+ acts.addExtension = closing(actions.addExtension)
+ acts.manageExtensions = closing(actions.manageExtensions)
+ acts.siteSettings = closing(actions.siteSettings)
+ acts.clearCache = closing(actions.clearCache)
+ acts.clearCookies = closing(actions.clearCookies)
+ let root = SiteControlCenterView(url: url, dark: dark, actions: acts)
+ .environment(store)
+ .background(SiteControlCenterColors(dark: dark).background)
+ let host = NSHostingController(rootView: AnyView(root))
+ host.sizingOptions = [.preferredContentSize]
+ p.contentViewController = host
+ popover = p
+ p.show(relativeTo: rect, of: view, preferredEdge: .minY)
+ }
+
+ func close() { popover?.performClose(nil) }
+
+ func popoverDidClose(_ notification: Notification) { popover = nil }
+}
diff --git a/Sources/Cra/UI/SplitView/SplitRow.swift b/Sources/Cra/UI/SplitView/SplitRow.swift
index 95f4e6e..ec4bead 100644
--- a/Sources/Cra/UI/SplitView/SplitRow.swift
+++ b/Sources/Cra/UI/SplitView/SplitRow.swift
@@ -67,7 +67,7 @@ struct SplitChildCell: View {
var body: some View {
let session = ui
HStack(spacing: 8) {
- FaviconView(key: item.tab?.faviconKey, palette: palette)
+ FaviconView(key: item.tab?.iconKey, palette: palette)
.frame(width: CraMetrics.favicon)
Text(item.displayTitle)
.font(.system(size: 14))
@@ -91,7 +91,7 @@ struct SplitChildCell: View {
.onTapGesture { store.selectTab(item.id) }
.draggable(SidebarDragItem.begin(item.id, session)) {
HStack(spacing: 8) {
- FaviconView(key: item.tab?.faviconKey, palette: palette)
+ FaviconView(key: item.tab?.iconKey, palette: palette)
Text(item.displayTitle).font(.system(size: 14)).lineLimit(1)
}
.padding(8)
diff --git a/Sources/Cra/UI/Theme.swift b/Sources/Cra/UI/Theme.swift
index 7d86856..3ac84c6 100644
--- a/Sources/Cra/UI/Theme.swift
+++ b/Sources/Cra/UI/Theme.swift
@@ -30,7 +30,8 @@ struct SpacePalette {
let pillFill: Color
let toolbarFill: Color
let folderTint: Color
- /// Arc 1.170: folder glyphs are a cream fill (theme colour pulled 80% to white) with an outline in the toolbar colour.
+ /// Arc 1.170: folder glyphs are a cream fill (theme colour pulled 80% to white) with an outline in the
+ /// toolbar colour. Dark themes use a light outline over a faint white fill instead.
let folderFill: Color
/// Selected row in the command bar (Arc tints it with the space color).
let commandHighlight: Color
@@ -44,6 +45,15 @@ struct SpacePalette {
var gradient: LinearGradient {
LinearGradient(colors: gradientColors, startPoint: .top, endPoint: .bottom)
}
+
+ /// Outline and fill for a folder glyph; nil (Auto) is the theme's pair.
+ func folderColors(_ style: FolderIconStyle?) -> (tint: Color, fill: Color) {
+ switch style {
+ case nil: return (folderTint, folderFill)
+ case .white?: return (.white.opacity(0.92), .white.opacity(0.22))
+ case .black?: return (.black.opacity(0.8), .black.opacity(0.12))
+ }
+ }
}
extension SpaceTheme {
@@ -132,8 +142,9 @@ extension SpaceTheme {
pillFill: dark ? .white.opacity(0.08) : .black.opacity(0.045),
// Arc: the toolbar is the first theme color at ~46% (dark) / lightened a touch (dark themes).
toolbarFill: SpaceTheme.toolbarColor(self.accent ?? base[0], dark: dark),
- folderTint: SpaceTheme.toolbarColor(self.accent ?? base[0], dark: dark),
- folderFill: SpaceTheme.mix(base[0], towardWhite: !dark, amount: dark ? 0.25 : 0.8),
+ // Dark themes: the toolbar shade vanished on the dark sidebar, so the outline is light ink there.
+ folderTint: dark ? .white.opacity(0.85) : SpaceTheme.toolbarColor(self.accent ?? base[0], dark: dark),
+ folderFill: dark ? .white.opacity(0.14) : SpaceTheme.mix(base[0], towardWhite: true, amount: 0.8),
commandHighlight: dark ? accent.opacity(0.55) : SpaceTheme.mix(base[0], towardWhite: false, amount: 0.45).opacity(0.75),
noise: noise,
// Calibrated against Arc's rendering of a 0.25-intensity vibrant theme.
diff --git a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
new file mode 100644
index 0000000..5ceb21d
--- /dev/null
+++ b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
@@ -0,0 +1,415 @@
+import AppKit
+import CraCEF
+
+/// Arc's BrowserExtensionWindow: an extension's popup in a small titled window under the
+/// toolbar (close button only, transparent title bar) that can be dragged away, after
+/// which Arc keeps its place (`userHasMovedWindow`, `.browserExtensionWindowAutosaveFrame`).
+///
+/// Cra keeps Chrome's own popup (its page stays a real extension popup: activeTab, the
+/// tab it fills into) and puts a frame window around it. Chrome's bubble becomes the
+/// frame's child, so it moves with it. The frame never becomes key: Chrome closes a popup
+/// as soon as it loses focus, and a click on the title bar would otherwise take it.
+@MainActor
+final class ExtensionPopupWindow: NSWindow {
+ /// Chrome's bubble draws a transparent margin around the page.
+ static let bubbleInset: CGFloat = 7
+ static let titleBarHeight: CGFloat = 28
+ private static let savedOriginKey = "extensionPopupWindowTopLeft"
+
+ private static var current: ExtensionPopupWindow?
+
+ private weak var bubble: NSWindow?
+ /// The frame's top-left (screen): under the anchor, or where the user left it.
+ private var topLeft = NSPoint.zero
+ private var observers: [NSObjectProtocol] = []
+ private var placing = false
+ /// A title-bar drag is under way (willMove is only posted for those, not when the main
+ /// window carries this child along).
+ private var dragging = false
+
+ override var canBecomeKey: Bool { false }
+ override var canBecomeMain: Bool { false }
+
+ private init() {
+ super.init(contentRect: NSRect(x: 0, y: 0, width: 300, height: 200),
+ styleMask: [.titled, .closable, .fullSizeContentView], backing: .buffered, defer: false)
+ titlebarAppearsTransparent = true
+ titleVisibility = .hidden
+ titlebarSeparatorStyle = .none
+ isReleasedWhenClosed = false
+ animationBehavior = .none
+ collectionBehavior = [.fullScreenAuxiliary, .moveToActiveSpace]
+ // The frame is never key, so AppKit would draw all three buttons inactive (grey).
+ // Arc shows a live red close button next to two disabled ones: draw those in place.
+ for kind: NSWindow.ButtonType in [.closeButton, .miniaturizeButton, .zoomButton] {
+ guard let button = standardWindowButton(kind), let superview = button.superview else { continue }
+ let light = TrafficLight(close: kind == .closeButton) { [weak self] in self?.performClose(nil) }
+ light.frame = button.frame
+ light.autoresizingMask = button.autoresizingMask
+ superview.addSubview(light)
+ button.isHidden = true
+ }
+ }
+
+ /// Wraps Chrome's popup `bubble`; `anchor` is the top-right point (screen) it hangs from
+ /// until the user moves the window.
+ static func present(_ bubble: NSWindow, anchor: NSPoint) {
+ current?.dismiss(closingBubble: false)
+ let w = ExtensionPopupWindow()
+ w.bubble = bubble
+ w.topLeft = placement(anchor: anchor, width: bubble.frame.width - 2 * bubbleInset)
+ w.appearance = bubble.parent?.effectiveAppearance ?? NSApp.effectiveAppearance
+ w.backgroundColor = .windowBackgroundColor
+ current = w
+
+ // Above the page (and the main window), below the popup.
+ let host = bubble.parent?.parent ?? bubble.parent
+ bubble.parent?.removeChildWindow(bubble)
+ bubble.hasShadow = false
+ w.layout()
+ host?.addChildWindow(w, ordered: .above)
+ w.orderFront(nil)
+ w.addChildWindow(bubble, ordered: .above)
+
+ for name in [NSWindow.didResizeNotification, NSWindow.didMoveNotification] {
+ w.observers.append(NotificationCenter.default.addObserver(forName: name, object: bubble, queue: .main) { [weak w] _ in
+ MainActor.assumeIsolated { w?.layout() }
+ })
+ }
+ w.observers.append(NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification, object: bubble, queue: .main) { [weak w] _ in
+ MainActor.assumeIsolated { w?.dismiss(closingBubble: false) }
+ })
+ w.observers.append(NotificationCenter.default.addObserver(forName: NSWindow.willMoveNotification, object: w, queue: .main) { [weak w] _ in
+ MainActor.assumeIsolated { w?.dragging = true }
+ })
+ w.observers.append(NotificationCenter.default.addObserver(forName: NSWindow.didMoveNotification, object: w, queue: .main) { [weak w] _ in
+ MainActor.assumeIsolated { w?.userMoved() }
+ })
+ }
+
+ /// Sizes the frame to the popup page and puts the bubble in it (Chrome re-anchors the
+ /// bubble to its hidden toolbar whenever the page resizes).
+ private func layout() {
+ guard let bubble, !placing else { return }
+ // While the title bar is dragged AppKit carries the bubble along; afterwards the
+ // frame stays where it was dropped.
+ if dragging {
+ if NSEvent.pressedMouseButtons != 0 { return }
+ dragging = false
+ }
+ placing = true
+ defer { placing = false }
+ let inset = Self.bubbleInset
+ let size = NSSize(width: bubble.frame.width - 2 * inset, height: bubble.frame.height - 2 * inset + Self.titleBarHeight)
+ var topLeft = self.topLeft
+ if let screen = (bubble.screen ?? NSScreen.main)?.visibleFrame {
+ topLeft.x = min(max(topLeft.x, screen.minX + 4), screen.maxX - size.width - 4)
+ topLeft.y = min(max(topLeft.y, screen.minY + size.height + 4), screen.maxY)
+ }
+ let frame = NSRect(x: topLeft.x, y: topLeft.y - size.height, width: size.width, height: size.height)
+ if self.frame != frame { setFrame(frame, display: true) }
+ let origin = NSPoint(x: frame.minX - inset, y: frame.minY - inset)
+ if bubble.frame.origin != origin { bubble.setFrameOrigin(origin) }
+ }
+
+ private func userMoved() {
+ guard dragging, !placing, bubble != nil else { return }
+ topLeft = NSPoint(x: frame.minX, y: frame.maxY)
+ Self.savedTopLeft = topLeft
+ }
+
+ /// Top-left of a popup window `width` wide: where the user last left one, else hanging
+ /// from `anchor` (top-right).
+ static func placement(anchor: NSPoint, width: CGFloat) -> NSPoint {
+ savedTopLeft ?? NSPoint(x: anchor.x - width, y: anchor.y)
+ }
+
+ private static var savedTopLeft: NSPoint? {
+ get {
+ guard let s = UserDefaults.standard.string(forKey: savedOriginKey) else { return nil }
+ let p = NSPointFromString(s)
+ return p == .zero ? nil : p
+ }
+ set { UserDefaults.standard.set(newValue.map(NSStringFromPoint), forKey: savedOriginKey) }
+ }
+
+ override func performClose(_ sender: Any?) { dismiss(closingBubble: true) }
+ override func close() { dismiss(closingBubble: true) }
+
+ private func dismiss(closingBubble: Bool) {
+ for o in observers { NotificationCenter.default.removeObserver(o) }
+ observers = []
+ if let bubble {
+ removeChildWindow(bubble)
+ if closingBubble { bubble.close() }
+ }
+ bubble = nil
+ parent?.removeChildWindow(self)
+ orderOut(nil)
+ if Self.current === self { Self.current = nil }
+ }
+}
+
+/// A title-bar button as AppKit draws it in an active window: red close (× on hover) or a
+/// disabled grey circle.
+private final class TrafficLight: NSView {
+ private let isClose: Bool
+ private let action: () -> Void
+ private var hovered = false { didSet { needsDisplay = true } }
+
+ init(close: Bool, action: @escaping () -> Void) {
+ isClose = close
+ self.action = action
+ super.init(frame: .zero)
+ if close { addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self)) }
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func draw(_ dirtyRect: NSRect) {
+ let d = min(bounds.width, bounds.height) - 2
+ let circle = NSRect(x: bounds.midX - d / 2, y: bounds.midY - d / 2, width: d, height: d)
+ let path = NSBezierPath(ovalIn: circle)
+ if isClose {
+ NSColor(srgbRed: 1, green: 0.373, blue: 0.341, alpha: 1).setFill()
+ path.fill()
+ NSColor(srgbRed: 0.886, green: 0.267, blue: 0.239, alpha: 1).setStroke()
+ path.lineWidth = 0.5
+ path.stroke()
+ if hovered {
+ let x = NSBezierPath()
+ let r = d * 0.2
+ x.move(to: NSPoint(x: circle.midX - r, y: circle.midY - r)); x.line(to: NSPoint(x: circle.midX + r, y: circle.midY + r))
+ x.move(to: NSPoint(x: circle.midX - r, y: circle.midY + r)); x.line(to: NSPoint(x: circle.midX + r, y: circle.midY - r))
+ x.lineWidth = 1.2
+ x.lineCapStyle = .round
+ NSColor(srgbRed: 0.3, green: 0, blue: 0, alpha: 0.8).setStroke()
+ x.stroke()
+ }
+ } else {
+ (effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ ? NSColor.white.withAlphaComponent(0.22) : NSColor.black.withAlphaComponent(0.13)).setFill()
+ path.fill()
+ }
+ }
+
+ override func mouseEntered(with event: NSEvent) { hovered = true }
+ override func mouseExited(with event: NSEvent) { hovered = false }
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ guard isClose, bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
+ action()
+ }
+}
+
+/// An extension's popup page when there is no page for Chrome's real popup to attach to
+/// (no tab open, or no DevTools pipe): the same frame as ExtensionPopupWindow around a
+/// Cra browser on the popup URL, sized the way Chrome sizes popups (the page's own size,
+/// 25×25 to 800×600, following it as it changes) and closed when it loses focus.
+@MainActor
+final class ExtensionPageWindow: NSWindow, NSWindowDelegate, @preconcurrency CraBrowserDelegate {
+ private static var current: ExtensionPageWindow?
+ nonisolated static let minSize = NSSize(width: 25, height: 25)
+ nonisolated static let maxSize = NSSize(width: 800, height: 600)
+
+ private unowned let app: AppDelegate
+ private var browser: CraBrowser?
+ private var topLeft: NSPoint
+ private var pageSize: NSSize?
+ private var measureTimer: Timer?
+ private var closing = false
+
+ /// The page's natural size: its max-content width, then its height at that width.
+ private static let measureScript = """
+ (() => { const d = document.documentElement, b = document.body; if (!b) return null;
+ const old = d.style.width; d.style.width = 'max-content';
+ const w = Math.ceil(d.getBoundingClientRect().width); d.style.width = old;
+ const h = Math.ceil(Math.max(b.getBoundingClientRect().bottom + parseFloat(getComputedStyle(b).marginBottom || '0'),
+ b.scrollHeight));
+ return [w, h]; })()
+ """
+
+ static func open(url: String, anchor: NSPoint, app: AppDelegate) {
+ current?.close()
+ let w = ExtensionPageWindow(url: url, anchor: anchor, app: app)
+ current = w
+ }
+
+ private init(url: String, anchor: NSPoint, app: AppDelegate) {
+ self.app = app
+ let start = NSSize(width: 360, height: 240)
+ topLeft = ExtensionPopupWindow.placement(anchor: anchor, width: start.width)
+ super.init(contentRect: NSRect(origin: .zero, size: start), styleMask: [.titled, .closable, .fullSizeContentView],
+ backing: .buffered, defer: false)
+ titlebarAppearsTransparent = true
+ titleVisibility = .hidden
+ titlebarSeparatorStyle = .none
+ isReleasedWhenClosed = false
+ animationBehavior = .none
+ collectionBehavior = [.fullScreenAuxiliary, .moveToActiveSpace]
+ standardWindowButton(.miniaturizeButton)?.isEnabled = false
+ standardWindowButton(.zoomButton)?.isEnabled = false
+ delegate = self
+ alphaValue = 0 // shown once the page has a size
+ setFrame(frame(for: start), display: false)
+
+ let b = CraBrowser(frame: pageRect, url: url, delegate: self)
+ browser = b
+ let v = b.containerView
+ v.frame = pageRect
+ v.autoresizingMask = [.width, .height]
+ contentView?.addSubview(v)
+ if let host = b.hostWindow { attach(host) }
+ makeKeyAndOrderFront(nil)
+ // Show it even if the page never reports a size.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in self?.alphaValue = 1 }
+ measureTimer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in
+ MainActor.assumeIsolated { self?.measure() }
+ }
+ }
+
+ /// The area under the title bar, in window coordinates.
+ private var pageRect: NSRect {
+ NSRect(x: 0, y: 0, width: frame.width, height: max(0, frame.height - ExtensionPopupWindow.titleBarHeight))
+ }
+
+ private func frame(for page: NSSize) -> NSRect {
+ let h = page.height + ExtensionPopupWindow.titleBarHeight
+ var tl = topLeft
+ if let screen = (screen ?? NSScreen.main)?.visibleFrame {
+ tl.x = min(max(tl.x, screen.minX + 4), screen.maxX - page.width - 4)
+ tl.y = min(max(tl.y, screen.minY + h + 4), screen.maxY)
+ }
+ return NSRect(x: tl.x, y: tl.y - h, width: page.width, height: h)
+ }
+
+ private func measure() {
+ guard let b = browser, !closing else { return }
+ let params = String(decoding: (try? JSONSerialization.data(withJSONObject: ["expression": Self.measureScript, "returnByValue": true])) ?? Data(), as: UTF8.self)
+ b.sendDevToolsMethod("Runtime.evaluate", params: params) { [weak self] result, _ in
+ guard let result, let o = try? JSONSerialization.jsonObject(with: Data(result.utf8)) as? [String: Any],
+ let value = (o["result"] as? [String: Any])?["value"] as? [Double], value.count == 2 else { return }
+ let size = NSSize(width: min(max(value[0], Self.minSize.width), Self.maxSize.width),
+ height: min(max(value[1], Self.minSize.height), Self.maxSize.height))
+ DispatchQueue.main.async { self?.apply(size) }
+ }
+ }
+
+ private func apply(_ size: NSSize) {
+ guard !closing else { return }
+ if let old = pageSize, abs(old.width - size.width) < 1, abs(old.height - size.height) < 1 { return }
+ pageSize = size
+ setFrame(frame(for: size), display: true)
+ positionHost()
+ alphaValue = 1
+ }
+
+ private func attach(_ host: NSWindow) {
+ guard host.parent !== self else { return }
+ // As MainWindowController does for tabs: borderless (a titled window keeps a title
+ // bar strip above the page), the bottom corners following the frame's.
+ 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.isHidden = false
+ cv.wantsLayer = true
+ cv.layer?.cornerRadius = 12
+ cv.layer?.cornerCurve = .continuous
+ cv.layer?.maskedCorners = cv.isFlipped ? [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] : [.layerMinXMinYCorner, .layerMaxXMinYCorner]
+ cv.layer?.masksToBounds = true
+ }
+ addChildWindow(host, ordered: .above)
+ positionHost()
+ host.orderFront(nil)
+ host.makeKey()
+ browser?.setFocused(true)
+ }
+
+ private func positionHost() {
+ guard let host = browser?.hostWindow, host.parent === self else { return }
+ let onScreen = convertToScreen(pageRect)
+ if host.frame != onScreen { host.setFrame(onScreen, display: true) }
+ // Chrome leaves its content view where the title bar used to end (22 pt down).
+ let full = NSRect(origin: .zero, size: onScreen.size)
+ if let cv = host.contentView, cv.frame != full { cv.frame = full }
+ }
+
+ // MARK: Window
+
+ func windowDidMove(_ notification: Notification) {
+ topLeft = NSPoint(x: frame.minX, y: frame.maxY)
+ }
+
+ /// Like a popup: clicking anywhere else closes it (the page's own window is a child,
+ /// so focus moving into it is not "elsewhere").
+ func windowDidResignKey(_ notification: Notification) { closeIfFocusLeft() }
+
+ private func closeIfFocusLeft() {
+ DispatchQueue.main.async { [weak self] in
+ guard let self, !self.closing else { return }
+ let key = NSApp.keyWindow
+ if key === self || (key != nil && key === self.browser?.hostWindow) { return }
+ self.close()
+ }
+ }
+
+ override func close() {
+ guard !closing else { return }
+ closing = true
+ measureTimer?.invalidate()
+ if let host = browser?.hostWindow { removeChildWindow(host); host.orderOut(nil) }
+ browser?.close()
+ browser = nil
+ super.close()
+ if Self.current === self { Self.current = nil }
+ }
+
+ // 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) { measure() }
+ 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) {}
+ func browser(_ browser: CraBrowser, requestsNewTabWithURL url: String, inBackground background: Bool) {
+ app.store.createTab(url: url, select: !background)
+ }
+ /// Links the popup opens (Chrome opens them as tabs): a Cra tab.
+ func browser(_ browser: CraBrowser, popupHostForURL url: String, inBackground background: Bool) -> CraBrowser? {
+ app.store.createTab(url: url, select: !background)
+ app.main.showWindow(nil)
+ return nil
+ }
+ 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) { attach(window) }
+ func browser(_ browser: CraBrowser, devToolsPageBounds bounds: NSRect) {}
+ func browser(_ browser: CraBrowser, devToolsDocked docked: Bool) {}
+ func browser(_ browser: CraBrowser, handleKeyEvent event: NSEvent) -> Bool {
+ if event.modifierFlags.contains(.command), event.charactersIgnoringModifiers == "w" { close(); return true }
+ return 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) {}
+ func browserDidClose(_ browser: CraBrowser) {
+ // window.close() from the popup page.
+ browser.containerView.removeFromSuperview()
+ if !closing { close() }
+ }
+}
diff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swift
index 3c896b3..3a6afb9 100644
--- a/Sources/Cra/UI/Windows/LittleWindowController.swift
+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift
@@ -59,7 +59,10 @@ enum LittleMetrics {
static let popupRowHeight: CGFloat = 54
static let popupHeaderHeight: CGFloat = 46
static let commandBarWidth: CGFloat = 500
- static let defaultSize = NSSize(width: 1000, height: 700)
+ static let defaultSize = NSSize(width: 1400, height: 900)
+ /// The old default, which every resize used to save (placement and the open
+ /// animation included), so a stored copy of it was never the user's choice.
+ static let legacyDefaultSize = NSSize(width: 1000, height: 700)
static let minSize = NSSize(width: 480, height: 360)
static let openDuration: TimeInterval = 0.12
}
@@ -126,6 +129,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
state = LittleWindowState(targetSpaceID: app.store.focusedSpaceID)
commandBar = CommandBarController(engine: app.engine, store: app.store)
let size = app.store.prefs.littleWindowSize.map { NSSizeFromString($0) }
+ .flatMap { $0 == LittleMetrics.legacyDefaultSize ? nil : $0 }
.map { NSSize(width: max(LittleMetrics.minSize.width, $0.width), height: max(LittleMetrics.minSize.height, $0.height)) }
?? LittleMetrics.defaultSize
let window = LittleWindow(contentRect: NSRect(origin: .zero, size: size),
@@ -198,6 +202,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
w.isOpaque = false
w.backgroundColor = .clear
if let cv = w.contentView {
+ cv.isHidden = false // a background tab's page (MainWindowController hides it)
cv.wantsLayer = true
cv.layer?.cornerRadius = LittleMetrics.cornerRadius
cv.layer?.cornerCurve = .continuous
@@ -215,6 +220,10 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
guard let window, let w = browser?.hostWindow, w.parent === window, !rectInWindow.isEmpty else { return }
let onScreen = window.convertToScreen(rectInWindow)
if w.frame != onScreen { w.setFrame(onScreen, display: true) }
+ // Chrome leaves its content view where the title bar ended (22 pt down), which
+ // showed as a strip above the page and cut off its bottom.
+ let full = NSRect(origin: .zero, size: onScreen.size)
+ if let cv = w.contentView, cv.frame != full { cv.frame = full }
if let cv = w.contentView { cv.layer?.cornerRadius = window.styleMask.contains(.fullScreen) ? 0 : LittleMetrics.cornerRadius }
}
@@ -544,6 +553,12 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
guard let window, (notification.object as? NSWindow) === window, !window.styleMask.contains(.fullScreen) else { return }
if commandBar.isOpen { positionCommandPanel() }
if popup != nil { closePopup() }
+ }
+
+ /// Only a drag by the user sets the remembered size, not placement clamping
+ /// or the open animation.
+ func windowDidEndLiveResize(_ notification: Notification) {
+ guard let window, (notification.object as? NSWindow) === window, !window.styleMask.contains(.fullScreen) else { return }
store.prefs.littleWindowSize = NSStringFromSize(window.frame.size)
}
@@ -656,9 +671,9 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
if kinds & 1 != 0 { what.append("camera") }
if kinds & 2 != 0 { what.append("microphone") }
if kinds & 4 != 0 { what.append("location") }
- if what.isEmpty { what.append("a browser permission") }
let alert = NSAlert()
- alert.messageText = "\(origin) wants to use your \(what.joined(separator: " and "))"
+ alert.messageText = what.isEmpty ? "\(origin) is asking for a browser permission"
+ : "\(origin) wants to use your \(what.joined(separator: " and "))"
alert.addButton(withTitle: "Allow")
alert.addButton(withTitle: "Block")
guard let window else { completion(false); return }
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index aa99ca0..be10c6e 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -176,6 +176,13 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// right edge lines up with the button's (Chrome anchors popups that way).
sidebarActions.runExtension = { [weak self] id in self?.runExtensionAction(id, buttonRightX: NSEvent.mouseLocation.x + 17) }
sidebarActions.showExtensionsMenu = { [weak self] in self?.showToolbarExtensionsMenu() }
+ // Popups from an extension's shortcut or chrome.action.openPopup() hang where the
+ // menu bar's do: under the toolbar at the card's right end.
+ ExtensionActions.shared.watchPopups { [weak self] in
+ guard let self, let window = self.window, let key = NSApp.keyWindow, key === window || key.parent === window,
+ let bar = self.toolbarBottomOnScreen() else { return nil }
+ return NSPoint(x: bar.cardMaxX - 8, y: bar.y)
+ }
sidebarActions.performAction = { [weak self] id in
if id.hasPrefix("muteTab:"), let uuid = UUID(uuidString: String(id.dropFirst(8))) {
let muted = self?.store.item(uuid)?.tab?.muted ?? false
@@ -429,6 +436,11 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let focused = browsers.visibleRuntime?.hostWindow
for (id, rt) in browsers.runtimes {
guard let w = rt.hostWindow else { continue }
+ // Chromium never learns that an ordered-out window is hidden (it checks for a hidden
+ // NSView ancestor), so hidden tabs stayed "visible": background tabs autoplayed video
+ // and ran at full speed. A hidden content view makes the tab hidden like Chrome's
+ // background tabs: media waits until the tab is first shown.
+ w.contentView?.isHidden = !visibleIDs.contains(id)
if !visibleIDs.contains(id) { if w.isVisible { w.orderOut(nil) }; continue }
if w.parent !== window {
// Borderless: a titled window gets macOS's rounded corners on all four sides,
@@ -751,6 +763,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
if let u = URL(string: url) { app.handleInternalURL(u) }
}
+ func browserManagerPageClosedTab(_ tabID: UUID) { closeTab(tabID) }
+
// MARK: Tabs
/// cra://debug?devtoolsjs=…: run script in the current tab's DevTools frontend.
@@ -974,7 +988,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// MARK: Extensions
- private lazy var toolbarExtensionsMenu = ExtensionsMenu(app: app)
+ private let siteControlCenter = SiteControlCenterPopover()
/// Screen y of the focused card's toolbar bottom (its top edge when the toolbar is hidden),
/// and the card's right edge.
@@ -1001,33 +1015,108 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// Dia's Extensions menu. The popup hangs under the toolbar, its right edge at `buttonRightX`
/// (screen x; nil = the card's right end, for the menu bar).
func runExtensionAction(_ id: String, buttonRightX: CGFloat? = nil) {
- guard let bar = toolbarBottomOnScreen(), let browser = currentBrowser else { openExtensionPopupPage(id); return }
+ guard let bar = toolbarBottomOnScreen() else { openExtensionPopupPage(id, anchor: nil); return }
let y = buttonRightX != nil ? (urlBarBottomOnScreen() ?? bar.y) : bar.y
let anchor = NSPoint(x: buttonRightX ?? bar.cardMaxX - 8, y: y)
+ guard let browser = currentBrowser else { openExtensionPopupPage(id, anchor: anchor); return }
Task {
- if await !ExtensionActions.shared.run(id, on: browser, anchor: anchor) { self.openExtensionPopupPage(id) }
+ if await !ExtensionActions.shared.run(id, on: browser, anchor: anchor) { self.openExtensionPopupPage(id, anchor: anchor) }
}
}
- /// Without the DevTools pipe (or for a page it cannot reach): the popup page in a Little
- /// Window, else the options page, else Chrome's details page for the extension.
- private func openExtensionPopupPage(_ id: String) {
+ /// No page for Chrome's popup to attach to (no tab open, no DevTools pipe, a page it
+ /// cannot reach): the popup page in a popup-sized window under the button, else the
+ /// options page, else Chrome's details page for the extension.
+ private func openExtensionPopupPage(_ id: String, anchor: NSPoint?) {
guard let e = ExtensionStore.shared.entries.first(where: { $0.extensionID == id }) else { return }
let base = "chrome-extension://\(id)/"
if let popup = e.popupPath {
- _ = app.openLittleWindow(url: base + popup)
+ let fallback = window.map { NSPoint(x: $0.frame.maxX - 16, y: $0.frame.maxY - CraMetrics.toolbarHeight) } ?? .zero
+ ExtensionPageWindow.open(url: base + popup, anchor: anchor ?? fallback, app: app)
} else {
store.createTab(url: e.optionsPath.map { base + $0 } ?? "chrome://extensions/?id=\(id)", select: true)
}
}
- /// Arc's toolbar Extensions button: the same menu as the menu bar's Extensions menu,
- /// dropped just under the button.
+ /// Arc's sliders button (toolbar and URL pill): the Site Control Center, hung under the
+ /// button the pointer is on (buttons are 32 × 28).
private func showToolbarExtensionsMenu() {
guard let window, let content = window.contentView, let y = urlBarBottomOnScreen() else { return }
- let menu = toolbarExtensionsMenu.makeMenu()
- let point = window.convertPoint(fromScreen: NSPoint(x: NSEvent.mouseLocation.x - 14, y: y - 2))
- menu.popUp(positioning: nil, at: content.convert(point, from: nil), in: content)
+ ExtensionStore.shared.reload()
+ let mouse = NSEvent.mouseLocation
+ // Arc's popover overlaps the bar by 4 pt (popover top 71 under a bar ending at 75).
+ let onScreen = NSRect(x: mouse.x - 16, y: y + 4, width: 32, height: 28)
+ let rect = content.convert(window.convertFromScreen(onScreen), from: nil)
+ let url = store.selectedTabID.flatMap { store.item($0)?.tab?.url } ?? ""
+ var actions = SiteControlCenterActions()
+ actions.share = { [weak self] in self?.shareCurrentPage(from: rect, in: content) }
+ actions.copyURL = { [weak self] in self?.app.perform("copyURL") }
+ actions.capture = { [weak self] in self?.capturePage() }
+ actions.captureFullPage = { [weak self] in self?.captureFullPage() }
+ actions.runExtension = { [weak self] id in self?.runExtensionAction(id) }
+ actions.addExtension = { [weak self] in self?.openTab("https://chromewebstore.google.com/category/extensions") }
+ actions.manageExtensions = { [weak self] in self?.openTab("chrome://extensions") }
+ actions.clearCache = { [weak self] in self?.clearSiteData(cookies: false) }
+ actions.clearCookies = { [weak self] in self?.clearSiteData(cookies: true) }
+ actions.siteSettings = { [weak self] in
+ guard let origin = URL(string: url).flatMap({ u in u.host.map { "\(u.scheme ?? "https")://\($0)" } }) else { return }
+ self?.openTab("chrome://settings/content/siteDetails?site=" + (origin.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? origin))
+ }
+ siteControlCenter.show(relativeTo: rect, of: content, url: url, dark: store.focusedSpace.theme.palette.isDark,
+ store: store, actions: actions)
+ }
+
+ private func openTab(_ url: String) {
+ store.createTab(url: url, select: true)
+ showWindow(nil)
+ }
+
+ private func shareCurrentPage(from rect: NSRect, in view: NSView) {
+ guard let url = store.selectedTabID.flatMap({ store.item($0)?.tab?.url }).flatMap(URL.init(string:)) else { return }
+ NSSharingServicePicker(items: [url]).show(relativeTo: rect, of: view, preferredEdge: .minY)
+ }
+
+ /// Arc's "Clear cookies and refresh the current page" (and the cache variant): this site's
+ /// cookies, or the HTTP cache, then a reload.
+ private func clearSiteData(cookies: Bool) {
+ guard let b = currentBrowser, let u = URL(string: b.currentURL), let host = u.host, let scheme = u.scheme else { return }
+ let done: (String?, String?) -> Void = { _, error in
+ if let error { NSLog("Cra: clearing site data failed: %@", error) }
+ DispatchQueue.main.async { b.reload() }
+ }
+ if cookies {
+ let params = ["origin": "\(scheme)://\(host)\(u.port.map { ":\($0)" } ?? "")", "storageTypes": "cookies"]
+ let json = String(decoding: (try? JSONSerialization.data(withJSONObject: params)) ?? Data("{}".utf8), as: UTF8.self)
+ b.sendDevToolsMethod("Storage.clearDataForOrigin", params: json, completion: done)
+ } else {
+ b.sendDevToolsMethod("Network.clearBrowserCache", params: "{}", completion: done)
+ }
+ }
+
+ /// Arc's "Capture the full page": the whole document (beyond the viewport) as a PNG in Downloads.
+ func captureFullPage() {
+ guard let b = currentBrowser else { return }
+ b.sendDevToolsMethod("Page.getLayoutMetrics", params: "{}") { result, _ in
+ guard let result, let m = try? JSONSerialization.jsonObject(with: Data(result.utf8)) as? [String: Any],
+ let size = (m["cssContentSize"] ?? m["contentSize"]) as? [String: Any],
+ let w = size["width"] as? Double, let h = size["height"] as? Double else { return }
+ let params = #"{"format":"png","captureBeyondViewport":true,"clip":{"x":0,"y":0,"width":\#(w),"height":\#(min(h, 16384)),"scale":1}}"#
+ b.sendDevToolsMethod("Page.captureScreenshot", params: params) { shot, error in
+ guard let shot, let o = try? JSONSerialization.jsonObject(with: Data(shot.utf8)) as? [String: Any],
+ let b64 = o["data"] as? String, let png = Data(base64Encoded: b64) else {
+ NSLog("Cra: full-page capture failed: %@", error ?? "no data")
+ return
+ }
+ DispatchQueue.main.async {
+ let f = DateFormatter()
+ f.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss"
+ let url = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("Cra Capture \(f.string(from: Date())).png")
+ try? png.write(to: url)
+ NSWorkspace.shared.activateFileViewerSelecting([url])
+ }
+ }
+ }
}
// MARK: Command bar
@@ -1351,18 +1440,20 @@ final class CraWindow: NSWindow {
guard hide != appliedTrafficLightsHidden else { return }
appliedTrafficLightsHidden = hide
let buttons = [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton].compactMap { standardWindowButton($0) }
+ // Hidden buttons rest at alpha 1: AppKit refuses to miniaturize a window whose
+ // minimize button has alpha 0 (⌘M and the floating sidebar's yellow button did nothing).
guard animated else {
- for b in buttons { b.alphaValue = hide ? 0 : 1; b.isHidden = hide }
+ for b in buttons { b.alphaValue = 1; b.isHidden = hide }
return
}
- if !hide { for b in buttons { b.isHidden = false } }
+ if !hide { for b in buttons where b.isHidden { b.alphaValue = 0; b.isHidden = false } }
// Same timing as the sidebar's slide (ShellView.animateSidebar).
NSAnimationContext.runAnimationGroup { ctx in
ctx.duration = 0.085
for b in buttons { b.animator().alphaValue = hide ? 0 : 1 }
} completionHandler: { [weak self] in
guard let self, self.appliedTrafficLightsHidden == hide else { return }
- for b in buttons { b.isHidden = hide }
+ for b in buttons { b.isHidden = hide; b.alphaValue = 1 }
}
}
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index 64ae193..2e13b77 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -7,6 +7,7 @@
#include "include/views/cef_window_delegate.h"
#include <crt_externs.h>
#include <atomic>
+#include <map>
#include <string>
#include <vector>
@@ -26,6 +27,7 @@
#include "include/cef_load_handler.h"
#include "include/cef_parser.h"
#include "include/cef_permission_handler.h"
+#include "include/cef_request_context.h"
#include "include/cef_request_handler.h"
#include "include/cef_resource_request_handler.h"
#include "include/cef_version.h"
@@ -93,6 +95,8 @@ static CraClient* AsCraClient(CefClient* c) {
@property (nonatomic) BOOL canGoForward;
@property (nonatomic) BOOL isCreated;
@property (nonatomic) BOOL isClosed;
+@property (nonatomic) BOOL closeRequested;
+@property (nonatomic) BOOL closedByPage;
@property (nonatomic) BOOL isInPictureInPicture;
@property (nonatomic) BOOL isPictureInPicturePlaying;
- (void)requestPictureInPictureInFrame:(CefRefPtr<CefFrame>)frame automatic:(BOOL)automatic x:(int)x y:(int)y;
@@ -115,20 +119,38 @@ static CraClient* AsCraClient(CefClient* c) {
// extension opens once it is installed. CEF gives them GetDefaultClient(); without
// one they appear in a stock Chrome window with a tab strip. Cra takes the URL as
// one of its own tabs and closes Chrome's browser before it is shown.
+//
+// Popup-type windows (windows.create({type: "popup"}): 1Password's detached window,
+// sign-in and approval windows) stay what the extension asked for, like Arc's
+// BrowserType.popup: the extension keeps its window id, can resize or close it and
+// checks windows.getCurrent().type. Chrome gives tabbed windows a full-size content
+// view under a transparent title bar (BrowserNativeWidgetMac::PopulateCreateWindowParams)
+// and popups a plain titled window, which is how they are told apart here.
+static NSHashTable<NSWindow*>* g_extensionWindows = nil;
+
class StrayBrowserClient : public CefClient, public CefLifeSpanHandler, public CefRequestHandler {
public:
CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() override { return this; }
CefRefPtr<CefRequestHandler> GetRequestHandler() override { return this; }
- void OnAfterCreated(CefRefPtr<CefBrowser> browser) override {
- if (!g_strayPageHandler) return;
- NSView* view = (__bridge NSView*)browser->GetHost()->GetWindowHandle();
- [view.window orderOut:nil];
+ void OnBeforeClose(CefRefPtr<CefBrowser> browser) override { windows_.erase(browser->GetIdentifier()); }
+
+ void CloseWindows() {
+ for (auto& entry : windows_) entry.second->GetHost()->CloseBrowser(true);
}
bool OnBeforeBrowse(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request,
bool user_gesture, bool is_redirect) override {
- if (!g_strayPageHandler || !frame->IsMain()) return false;
+ if (!g_strayPageHandler || !frame->IsMain() || windows_.count(browser->GetIdentifier())) return false;
+ // Chrome's window exists by the first navigation (not yet in OnAfterCreated).
+ NSWindow* window = ((__bridge NSView*)browser->GetHost()->GetWindowHandle()).window;
+ if (window && !(window.styleMask & NSWindowStyleMaskFullSizeContentView)) {
+ windows_[browser->GetIdentifier()] = browser;
+ if (!g_extensionWindows) g_extensionWindows = [NSHashTable weakObjectsHashTable];
+ [g_extensionWindows addObject:window];
+ return false;
+ }
+ [window orderOut:nil];
NSString* url = NSStringFromCef(request->GetURL());
if (url.length == 0 || [url isEqualToString:@"about:blank"]) return false;
// Chrome's own empty tab (the window it opens to show "extension added" after a
@@ -144,8 +166,10 @@ public:
}
private:
+ std::map<int, CefRefPtr<CefBrowser>> windows_;
IMPLEMENT_REFCOUNTING(StrayBrowserClient);
};
+static CefRefPtr<StrayBrowserClient> g_strayClient;
// MARK: - Browser-level DevTools pipe
@@ -246,8 +270,8 @@ public:
CefRefPtr<CefBrowserProcessHandler> GetBrowserProcessHandler() override { return this; }
CefRefPtr<CefClient> GetDefaultClient() override {
- if (!stray_) stray_ = new StrayBrowserClient();
- return stray_;
+ if (!g_strayClient) g_strayClient = new StrayBrowserClient();
+ return g_strayClient;
}
void OnBeforeCommandLineProcessing(const CefString& process_type,
@@ -276,6 +300,14 @@ public:
if (paths.count) command_line->AppendSwitchWithValue("load-extension", CefStringFromNS([paths componentsJoinedByString:@","]));
}
command_line->AppendSwitchWithValue("autoplay-policy", "document-user-activation-required");
+ // WebRTC hides this Mac's local IP behind a random .local name announced over
+ // mDNS, and macOS asks for Local Network access the first time any page (an
+ // ad script will do) opens a peer connection. Cra offers no local address at
+ // all instead (webrtc.ip_handling_policy, set in OnContextInitialized), so
+ // there is nothing to announce and the mDNS responder can stay off.
+ std::string disabled = command_line->GetSwitchValue("disable-features");
+ command_line->AppendSwitchWithValue("disable-features",
+ (disabled.empty() ? "" : disabled + ",") + "WebRtcHideLocalIpsWithMdns");
// Kerberos/NTLM single sign-on (ADFS /adfs/ls/wia and the like). Chromium only sends
// the OS ticket to allowlisted hosts, and IT sets that list as a Chrome or Edge policy,
// which CEF never reads. Without it those logins fail with ERR_INVALID_AUTH_CREDENTIALS.
@@ -321,6 +353,14 @@ public:
void OnContextInitialized() override {
CEF_REQUIRE_UI_THREAD();
+ // Before any page loads: with mDNS off, the default policy would hand pages
+ // the real local IP. Pages get the public address STUN reports and nothing else.
+ CefRefPtr<CefValue> policy = CefValue::Create();
+ policy->SetString("default_public_interface_only");
+ CefString error;
+ if (!CefRequestContext::GetGlobalContext()->SetPreference("webrtc.ip_handling_policy", policy, error)) {
+ NSLog(@"CraCEF: webrtc.ip_handling_policy: %s", error.ToString().c_str());
+ }
g_contextInitialized = true;
NSArray<CraBrowser*>* pending = [g_pendingCreation copy];
[g_pendingCreation removeAllObjects];
@@ -330,7 +370,6 @@ public:
}
private:
- CefRefPtr<StrayBrowserClient> stray_;
IMPLEMENT_REFCOUNTING(CraApp);
};
@@ -568,14 +607,21 @@ static const char kBackgroundProbe[] =
"setTimeout(window.__craBg,1500);}"
"window.__craBg();})();";
-// MARK: - Content blocking
+// MARK: - Content blocking and app links
// Cancels third-party requests to listed ad and tracker domains (CraContentBlocker.h).
// Runs on the IO thread; stateless, the list and the switch are global atomics.
+//
+// Also lets links with a scheme Chromium can't load (macappstore:, mailto:, zoommtg:,
+// slack:, …) reach the app registered for it. CEF only asks a resource request handler,
+// so without this every such link failed with ERR_UNKNOWN_URL_SCHEME. Allowing it hands
+// the link to Chrome's ExternalProtocolHandler, which blocks dangerous schemes and asks
+// "Open <app>?" with "Always allow" like Chrome and Arc.
class CraContentBlockingHandler : public CefResourceRequestHandler {
public:
ReturnValue OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request, CefRefPtr<CefCallback> callback) override {
+ if (!cra_blocker::Enabled().load(std::memory_order_relaxed)) return RV_CONTINUE;
if (!browser || request->GetResourceType() == RT_MAIN_FRAME) return RV_CONTINUE;
CefRefPtr<CefFrame> top = browser->GetMainFrame(); // the tab's top-level page
if (!top) return RV_CONTINUE;
@@ -584,6 +630,13 @@ public:
return cra_blocker::ShouldBlock(requestHost, pageHost) ? RV_CANCEL : RV_CONTINUE;
}
+ void OnProtocolExecution(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request,
+ bool& allow_os_execution) override {
+ // cra:// is Cra's own scripting scheme; a page must not drive it.
+ std::string url = request->GetURL().ToString();
+ allow_os_execution = url.compare(0, 4, "cra:") != 0;
+ }
+
private:
IMPLEMENT_REFCOUNTING(CraContentBlockingHandler);
};
@@ -752,6 +805,10 @@ public:
void OnLoadError(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, ErrorCode errorCode,
const CefString& errorText, const CefString& failedUrl) override {
if ((int)errorCode == -3 /* ERR_ABORTED */ || !frame->IsMain()) return;
+ // Chrome-style pages get Chrome's own error page: Reload retries the site and it
+ // reloads by itself when the network returns. Ours, a data: URL loaded on top,
+ // made Reload reload the error and added a history entry.
+ if (browser->GetHost()->GetRuntimeStyle() == CEF_RUNTIME_STYLE_CHROME) return;
// Chrome fails a navigation that hits an auth challenge with this error, commits a
// blank page and asks for the password over it. Our page would replace both.
if ((int)errorCode == -338 /* ERR_INVALID_AUTH_CREDENTIALS */) return;
@@ -825,13 +882,13 @@ public:
// Request -------------------------------------------------------------
- // Content blocking (IO thread). Top-level navigations and downloads always load;
- // with blocking off no handler is attached at all.
+ // Content blocking and app links (IO thread). Top-level navigations and downloads always
+ // load; navigations always get the handler so app links work with blocking off.
CefRefPtr<CefResourceRequestHandler> GetResourceRequestHandler(
CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, bool is_navigation,
bool is_download, const CefString& request_initiator, bool& disable_default_handling) override {
- if (!cra_blocker::Enabled().load(std::memory_order_relaxed) || is_download) return nullptr;
- if (is_navigation && frame && frame->IsMain()) return nullptr;
+ if (is_download) return nullptr;
+ if (!is_navigation && !cra_blocker::Enabled().load(std::memory_order_relaxed)) return nullptr;
return blocker_;
}
@@ -981,11 +1038,11 @@ public:
CefRefPtr<CefMediaAccessCallback> callback) override {
CraBrowser* o = owner_;
if (!o || !o.delegate) return false;
- // Screen sharing (getDisplayMedia) in a Chrome-style page goes to Chrome's own
- // picker: tabs, windows or a screen, with "Also share tab audio". Granting it
- // here would make CEF share the whole screen with system loopback audio instead.
- if ((requested_permissions & (CEF_MEDIA_PERMISSION_DESKTOP_VIDEO_CAPTURE | CEF_MEDIA_PERMISSION_DESKTOP_AUDIO_CAPTURE)) &&
- browser->GetHost()->GetRuntimeStyle() == CEF_RUNTIME_STYLE_CHROME) return false;
+ // Chrome-style pages use Chrome's permission flow: camera and microphone come back
+ // through OnShowPermissionPrompt and Chrome remembers the answer per site (answered
+ // here, every getUserMedia asked again). Screen sharing goes to Chrome's own picker:
+ // tabs, windows or a screen, with "Also share tab audio".
+ if (browser->GetHost()->GetRuntimeStyle() == CEF_RUNTIME_STYLE_CHROME) return false;
NSUInteger kinds = 0;
if (requested_permissions & (CEF_MEDIA_PERMISSION_DEVICE_VIDEO_CAPTURE | CEF_MEDIA_PERMISSION_DESKTOP_VIDEO_CAPTURE)) kinds |= 1;
if (requested_permissions & (CEF_MEDIA_PERMISSION_DEVICE_AUDIO_CAPTURE | CEF_MEDIA_PERMISSION_DESKTOP_AUDIO_CAPTURE)) kinds |= 2;
@@ -1214,6 +1271,7 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
- (void)browserClosed {
_browser = nullptr;
self.isClosed = YES;
+ self.closedByPage = !self.closeRequested && !g_quitting;
[g_allBrowsers removeObject:self];
id<CraBrowserDelegate> d = self.delegate;
[d browserDidClose:self];
@@ -1305,14 +1363,15 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
// request once `navigator.userActivation` reports active. `x`/`y` (view DIPs,
// -1 for none) pick the video under a context-menu click; otherwise the
// playing, largest video wins. Automatic requests (leaving the tab) take only
-// a playing video of some size and skip GIF-like muted loops.
+// an audible, playing video of some size: muted ones are hover previews
+// (YouTube's thumbnails play muted on hover) or GIF-like loops.
static NSString* PictureInPictureScript(BOOL automatic, int x, int y) {
return [NSString stringWithFormat:
@"(function(auto,x,y){try{"
"if(document.pictureInPictureElement){if(!auto){document.exitPictureInPicture().catch(function(){});}return;}"
"var area=function(v){var r=v.getBoundingClientRect();return r.width*r.height;};"
"var c=Array.prototype.slice.call(document.querySelectorAll('video')).filter(function(v){return !v.disablePictureInPicture&&v.readyState>=1&&v.videoWidth>0;});"
- "if(auto){c=c.filter(function(v){return !v.paused&&!v.ended&&!(v.muted&&v.loop)&&area(v)>=20000;});}"
+ "if(auto){c=c.filter(function(v){return !v.paused&&!v.ended&&!v.muted&&v.volume>0&&area(v)>=20000;});}"
"if(!c.length){console.log('__cra_pip:none');return;}"
"var v=null;"
"if(x>=0){v=c.filter(function(e){var r=e.getBoundingClientRect();return x>=r.left&&x<=r.right&&y>=r.top&&y<=r.bottom;}).sort(function(a,b){return area(a)-area(b);})[0]||null;}"
@@ -1459,6 +1518,7 @@ static NSView* FindRenderWidgetHostView(NSView* root) {
- (void)close {
if (_isClosed) return;
+ self.closeRequested = YES;
if (_browser) {
_browser->GetHost()->CloseBrowser(true);
} else {
@@ -1605,6 +1665,11 @@ static void MarkProfileExitedCleanly(NSString* cachePath) {
+ (BOOL)anotherInstanceWasNotified { return g_alreadyRunning; }
+ (void)setRelaunchHandler:(void (^)(NSArray<NSString*>*))handler { g_relaunchHandler = [handler copy]; }
+ (void)setStrayPageHandler:(void (^)(NSString*))handler { g_strayPageHandler = [handler copy]; }
++ (BOOL)isExtensionWindow:(NSWindow*)window { return window && [g_extensionWindows containsObject:window]; }
++ (BOOL)isPageWindow:(NSWindow*)window {
+ for (CraBrowser* b in g_allBrowsers) if (window && b.hostWindow == window) return YES;
+ return NO;
+}
+ (void)runMessageLoop { CefRunMessageLoop(); }
+ (void)quitMessageLoop { CraQuitMessageLoop(); }
@@ -1612,6 +1677,7 @@ static void MarkProfileExitedCleanly(NSString* cachePath) {
+ (void)closeAllBrowsersAndQuit {
g_quitting = true;
+ if (g_strayClient) g_strayClient->CloseWindows();
NSArray<CraBrowser*>* all = [g_allBrowsers allObjects];
if (all.count == 0 || g_liveBrowsers <= 0) {
CraQuitMessageLoop();
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index 901f39f..561a92f 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -97,6 +97,8 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
@property (nonatomic, readonly) BOOL canGoForward;
@property (nonatomic, readonly) BOOL isCreated;
@property (nonatomic, readonly) BOOL isClosed;
+/// YES once the page closed itself (window.close()) rather than through -close.
+@property (nonatomic, readonly) BOOL closedByPage;
@property (nonatomic, readonly) BOOL hasDevTools;
/// Anything you want to hang on the browser (Swift stores the tab id).
@property (nonatomic, strong, nullable) id userInfo;
@@ -193,7 +195,12 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
/// Pages Chromium opens on its own (an extension's chrome.tabs.create or
/// windows.create, welcome pages after an extension loads). The handler gets
/// the URL to open as a Cra tab; Chrome's own window for it is closed.
+/// Popup-type windows (windows.create({type: "popup"})) stay Chrome's windows.
+ (void)setStrayPageHandler:(void (^)(NSString *url))handler;
+/// YES for a popup window an extension opened (kept by the stray page handling).
++ (BOOL)isExtensionWindow:(NSWindow *)window;
+/// YES for the Chrome-style window hosting one of Cra's own browsers.
++ (BOOL)isPageWindow:(NSWindow *)window;
+ (NSString *)chromiumVersion;
+ (NSString *)cefVersion;
/// YES when the browser-level DevTools pipe is up (it needs fds 3/4 free at start-up).
diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.md
index cc56e0e..6f41bbe 100644
--- a/docs/arc-reverse-engineering.md
+++ b/docs/arc-reverse-engineering.md
@@ -732,6 +732,11 @@ of the sidebar strip, pixel runs at x=500 px (2x), y = 160/700/1200/1700/2100.
y 135 shown only while the list is scrolled away from the top, bottom one at y 1033 shown only while
rows are hidden below the viewport (the trailing empty space does not count). Both fade over roughly
0.2–0.3s (window captures 0.2s apart showed partial strength in the first frame).
+- [O] Pinned rows scroll with Today (26 Oct, AX row frames): one outline holds pinned, divider and Today
+ rows; at scroll value 1 the first pinned rows (Kildash, Phantom, Umami) sat above the viewport top while
+ the header stayed. No sticky pinned section: no class implements `tableView:isGroupRow:` /
+ `floatsGroupRows` (only a selector reference exists). Arc's way to keep a long pinned list out of the way
+ is collapsing it from the space name. Cra keeps the single list (a pinned/Today split was tried and dropped).
- [?] Dark-theme hairline colour (no dark Arc sidebar on screen; Cra uses 7% white) and whether Arc keeps
each space's scroll offset across space switches (Cra currently resets to the top).
- Cra: favorites and `SpaceHeader` are outside the `ScrollView`; its viewport measures 0,168 284×899 in
@@ -1192,3 +1197,131 @@ the arm64 slice. [O] = observed, [I] = inferred.
Verified with local appcasts (renamed CraUpd test bundle, LSEnvironment for the relaunch): background download →
banner → idle restart, auto-download off → "New Cra Version Available" → Download → Install and Relaunch, and the
"Cra Updated!" banner after each, all ad-hoc signed.
+
+## Air Traffic Control (Arc 1.170, 26 Oct 2026, live via AX + window captures)
+
+- [O] Settings ▸ Links ends with a card "Choose where links open inside Arc. ⓘ" and an "Air Traffic Control…" button,
+ which opens a 508 × 500 sheet: "Air Traffic Control" 13 pt bold at (24, 37), "New Route" 122 × 28 at (306, 32), a
+ 32 × 32 close ✕ at (452, 30), a hairline, the route list (scroll area at (24, 92), 460 wide), a hairline at y 410,
+ "Default" at (60, 438) with a 165 × 24 popup at (164, 434). Each route is two lines on a 76 pt pitch, 52 pt tall:
+ "🔗 URL" (secondary, x 55) · match popup 110 × 24 at x 112 ("Is equal to" / "Contains") · text field 210 × 24 at
+ x 230 (placeholder "arc.net") · 13 pt ⊖ remove at x 449; then "↳ Open in" at x 129 with a 165 × 24 popup at x 207,
+ 28 pt below. Destination menu: disabled header "Open in Space", "Most Recent Space", every space (emoji + title),
+ separator, "Little Arc". New Route appends `Contains`, empty, Most Recent Space at the bottom.
+- [O] Storage `StorableLinkRouting.json`: `{rules: [{id, sourceComponents: [{id, componentType: {urlMatch: {_0:
+ {contains: {}} | {matches: {}}, _1: "meet.google.com"}}}], destination}], defaultDestination, version: 1}` with
+ destinations `{space: {_0: {mostRecent: {}}}}` and `{littleArc: {_0: {mostRecent: {}}}}` (the inner value is the
+ profile). Swift types: LinkMatchingRule, LinkSourceComponent.ComponentType (only `urlMatch`),
+ LinkSourceTextMatchingStyle, LinkDestination, ProfileDestination. Arc seeds a meet.google.com route
+ (`didSetDefaultGoogleMeetRoute`).
+- [O] "Links from other apps open in Little Arc" *is* the default destination: switching it off rewrote
+ defaultDestination to `space(mostRecent)`, on to `littleArc`.
+- [O] Swift metadata (`__swift5_fieldmd`, arm64 slice): `LinkDestination = space(ProfileDestination) |
+ littleArc(ProfileDestination)`, `ProfileDestination = mostRecent | space(UUID) | profile(…)`, so a specific space is
+ stored as `{space: {_0: {space: {_0: "<space id>"}}}}`. `LinkMatchingRule {id, sourceComponents, destination}`,
+ `LinkSourceComponent.ComponentType = urlMatch(LinkSourceTextMatchingStyle, String)`, style `matches | contains`.
+ Only `Arc.AppReducer` and `Arc.WindowsReducer` hold the LinkRoutingClient (routing happens where URLs are opened).
+ The editor (`LinkRoutingEditor`) has a `focusedRuleID` and ComponentAction `add/delete/submit`; Return in a route
+ field did not add a second condition. Analytics: LinkRoutingWindowType `littleArc | mainWindow | customSpace`,
+ LinkRoutingURLMatchType `equals | contains`, property `autoRouted`. `AppState+DefaultLinkRoutes.swift` seeds the
+ meet.google.com → Most Recent Space route once.
+- [O] Runtime (26 Oct 2026, temporary routes written to StorableLinkRouting.json while Arc was quit, links handed over
+ with `open -g -a Arc <url>`, landing read from the AX tree and StorableSidebar.json, file restored afterwards):
+ - Both the URL and the route text lose case, the scheme and a leading `www.` before comparing: "Contains
+ https://example.com/atc-scheme" matched `http://example.com/…` and `https://www.example.com/…`; "Contains
+ ATC-CASE" matched `/atc-case`.
+ - "Contains" also sees the query and fragment (`?x=atc-order`, `#atc-recent` matched).
+ - "Is equal to" compares host and path only: `example.com/atc-eq` matched `…/atc-eq?x=1`, `…/atc-eq#frag`,
+ `http://`, `www.`, upper case and a trailing slash, but not `…/atc-eq/more`.
+ - Routes are checked in order; the first match wins. No match → the default (Little Arc).
+ - A space destination opens a new foreground tab at the top of that space's Today list (a second copy when the URL
+ is already open) and switches the main window to the space. Most Recent Space = the space the main window last
+ showed.
+ - `littleArc(space(JYSK))` opened a Little Arc whose button read "Open in Victor" (the most recent space); the
+ editor shows that destination blank. The payload only picks a profile.
+- [U] what several conditions in one rule mean (any vs all; the UI never creates them), the ⓘ help article URL
+ (built at run time, `featuresForLinkRouting`), the empty-list state.
+- Cra: `Model/LinkRouting.swift` (Arc's matching above, checked against every observed case; first match wins; the
+ Google Meet route is seeded once), `AppSettings.linkRoutes` / `defaultLinkDestination` (the Little Window checkbox is a view of the
+ default; old `openExternalLinksInLittleWindow` values migrate), `AppDelegate.openExternalURL`, Settings ▸ Tabs ▸
+ Links ▸ "Air Traffic Control…" (`UI/Settings/AirTrafficControlView.swift`, Arc's geometry within 1 pt, 440 tall to
+ fit Cra's Settings window, the window's own background instead of Arc's navy). The Arc import brings the routes
+ and default along, matching spaces by title. Compare: docs/screenshots/compare-air-traffic-control.png.
+
+## Extension popups and extension windows (Arc 1.170, 26 Oct 2026, static)
+
+Method: `strings`, `otool -oV` with relative-method-list selectors resolved by hand, and Swift field metadata
+(`__swift5_types` → field descriptors) of the arm64 slices of `Arc` and `ArcCore.framework`. No runtime capture of
+Arc's popup this time, so geometry is not measured.
+
+- [O] ArcCore's browser delegate hands the toolbar popup to the Swift shell as web contents:
+ `browser:didOpenExtensionPopup:webContents:`, `browser:didResizeExtensionPopup:size:`,
+ `browser:didCloseExtensionPopup:` (`ADKClientLive.BrowserExtensionsPopUpManager`). The window state keeps
+ `WindowState.browserExtensionPopup: BrowserExtensionPopup? {extensionID, size, browserID}` and
+ `WindowViewController` / `LittleWindowViewController` own a `browserExtensionWindowController`.
+- [O] `Arc.BrowserExtensionWindow: NSWindow` (fields store, viewStore, defaultSize; "Expected an extension
+ popupView, but there wasn't one.") and `BrowserExtensionWindowController: NSWindowController` (delegate,
+ `savedDefaultWindowFrameKey`, `userHasMovedWindow`, `closeCurrentItem:`, `windowDidBecomeKey:`,
+ `onWindowWillMove:`; autosave name `.browserExtensionWindowAutosaveFrame`).
+ [I] The popup is a separate window under the toolbar that the user can drag; once moved, its frame is remembered.
+ Every popup takes this path, whatever opened it (toolbar click, keyboard command, `chrome.action.openPopup()`).
+- [O] Windows an extension creates: ArcCore `createPopupBrowser:withDelegate:` / `didCreateNewBrowser:`,
+ `ChromiumBrowser.browserType: BrowserType {normal, popup, pictureInPicture}` and `OpenDisposition.popup`. Popup-type
+ browsers stay popups; Arc's tabs live in normal Chrome windows.
+- [O] Arc ships a list of password-manager extension IDs (`PasswordManagerExtensionID`: 1Password, its beta and
+ nightly builds, Bitwarden, Dashlane, LastPass, iCloud Passwords, Keeper, RoboForm, NordPass), plus a hard-coded
+ `chrome-extension://pejdijmoenmkgeppbflobdenhhabjlaj/page_popup.html?popupWindow=1` ([I] iCloud Passwords).
+- Cra (Chromium side, observed with a probe extension and the DevTools port):
+ - CEF creates every `CefBrowserView` browser as `TYPE_POPUP` (trusted). To extensions every Cra tab therefore
+ sits in a `"popup"` window (`windows.getAll()` returns only popups), and `chrome.action.openPopup()` fails with
+ "Browser window has no toolbar." (`PopupBrowserSupportsWindowFeature(kFeatureToolbar)` is false). 1Password
+ calls `openPopup()` from its inline menu and checks `windows.getCurrent().type === "popup"`; its
+ `windows.onCreated` handler treats every new Cra tab as a sign-in popup from the previous tab.
+ `scripts/cef-patches/extensions-normal-windows.patch` reports `IsViewsHosted()` browsers as `"normal"` and lets
+ them open popups (needs a CEF build; not in the CEF 154 codecs1 build).
+ - `windows.create({type: "popup"})` used to become a Cra tab (StrayBrowserClient). Chrome gives tabbed windows
+ `NSWindowStyleMaskFullSizeContentView` (BrowserNativeWidgetMac::PopulateCreateWindowParams) and popups a plain
+ titled window, so Cra now keeps the latter as Chrome's own window (`+[CraCEFRuntime isExtensionWindow:]`, ⌘W
+ closes it). The window does not exist yet in OnAfterCreated (GetWindowHandle is nil); it does by OnBeforeBrowse.
+ - Popups Cra did not open itself (shortcut, `openPopup()`) are found through `Target.setDiscoverTargets`: the
+ target is created as `"other"` with no URL and gets the popup URL in `targetInfoChanged`; Chrome creates the
+ bubble window hidden before that, so placement looks for a newly *visible* borderless window. Without this the
+ popup hangs off Chrome's hidden toolbar (x ≈ 174 pt from the left).
+ - [U] Not reproduced from Arc: the popup window's chrome (shadow, corner radius, drag handle) and where it reopens
+ after being dragged; Cra still uses Chrome's bubble.
+
+## Site Control Center and pinned extensions (Arc 1.170, 26 Oct 2026, live via AX + captures)
+
+- [O] The toolbar's sliders button is "Site Control Center" (32×28 at the bar's right end, after the pinned extension
+ icons at a 36 pt pitch; `SiteControlCenterView` in ARC_SiteControlCenter). It opens an `AXPopover` 262 wide whose
+ content column is 236 wide, inset 13; the popover's top sits 4 pt above the bar's bottom edge.
+- [O] Column, top to bottom: four 48×32 action buttons on a 56 pt pitch (Share, New Boost, "Capture a portion of this
+ page", "Capture the full page"; raised: gradient #363636→#212121, top edge #69696A, outline #141115), 11 pt;
+ "Extensions" 14 pt bold #D4D4D5 (hovering the section shows "Manage" 12 pt #959496 at the right; it opens
+ extension management), 10 pt; a 4-column grid of 48×32 tiles (#353436, hover #39383B) on 56/40 pt pitches:
+ pinned extensions in pin order, then the rest by name, then a "+" tile (Add Extension); 15 pt; "Settings", 10 pt;
+ 208×33 rows on a 43 pt pitch (32 pt circle #F0F1FE when on, #6A6A6F when off; title 14 pt semibold #DBDBDB,
+ subtitle 13 pt #979798): Developer Mode On/Off, Block Ads & Trackers On/Off, Automatic Picture-In-Picture Allowed;
+ a divider; footer: "Secure" pill 82×32 (#363536) and a 32 pt "More" circle (#403F40). Background #272728 (dark theme).
+- [O] Pinning: each tile carries a 14 pt `pin.fill` badge at (+37, +21) from its top-left. Pinned tiles always show
+ it (#F0F1FE, AX "Unpin"); an unpinned tile shows it on hover only (#7F7E85, AX "Pin"). The badge glyph is the
+ popover's background colour.
+- [O] More menu items (strings): Clear Cache, Clear Cookies, Manage Extensions, Add Extension, All Site Settings
+ (plus Boost items).
+- [O] Extension popup window (user screenshot): ≈472×380 pt titled window, ≈25 pt title bar with a red close button and
+ disabled minimize/zoom, the popup page filling the rest.
+- Cra: `UI/SiteControlCenter.swift` (same geometry; Cra's popover lands at Arc's exact screen coordinates), the
+ second action is Copy URL (no Boosts), Capture = visible page, Capture full page = DevTools
+ `Page.captureScreenshot` with `captureBeyondViewport`; Clear Cookies = `Storage.clearDataForOrigin`, Clear Cache =
+ `Network.clearBrowserCache`, both reload. Pins live in `pinned-extensions.json`; when that file does not exist yet
+ Cra takes Arc's (then Dia's, then Chrome's) `extensions.pinned_extensions`. The popup frame is
+ `UI/Windows/ExtensionPopupWindow.swift` (Chrome's bubble as a child; the frame never becomes key, since Chrome
+ closes popups that lose focus, so its traffic lights are drawn by Cra).
+- [U] Arc's "disabled" subtitle wording for Picture-in-Picture (Cra says "Disabled"); the Secure pill's click action.
+- Popup size (Arc inherits Chrome's rule): the popup page's own size, at least 25×25 and at most 800×600, following
+ the page as it changes. When Cra has no page to hang Chrome's real popup on (no tab open, no DevTools pipe) it used
+ to load the popup page into a 1000×700 Little Window; it now uses `ExtensionPageWindow` (same frame, the page's
+ max-content width and its height at that width, re-measured every 250 ms, closes when it loses focus).
+- Chrome-style page windows that Cra re-parents keep Chrome's `BridgedContentView` at y −22 (where the title bar ended):
+ the page is drawn 22 pt low and its bottom cut off unless the content view is reset to the full window frame
+ (MainWindowController.fillContentView did this for tabs; Little Windows and the popup window now do too).
diff --git a/docs/screenshots/compare-air-traffic-control.png b/docs/screenshots/compare-air-traffic-control.png
new file mode 100644
index 0000000..02b1eb1
Binary files /dev/null and b/docs/screenshots/compare-air-traffic-control.png differ
diff --git a/resources/Info.plist b/resources/Info.plist
index 0ae1e3d..d91cdfc 100644
--- a/resources/Info.plist
+++ b/resources/Info.plist
@@ -50,6 +50,8 @@
<string>Web sites you visit can ask to use the microphone.</string>
<key>NSLocationUsageDescription</key>
<string>Web sites you visit can ask for your location.</string>
+ <key>NSBluetoothAlwaysUsageDescription</key>
+ <string>Web sites you visit can ask to connect to Bluetooth devices, and passkey sign-ins can use your phone nearby.</string>
<!-- macOS asks the first time a page uses WebRTC: Chromium announces a random .local
name over mDNS instead of handing the page this Mac's local IP address. -->
<key>NSLocalNetworkUsageDescription</key>
diff --git a/resources/browsers/arc.png b/resources/browsers/arc.png
new file mode 100644
index 0000000..02c1fc9
Binary files /dev/null and b/resources/browsers/arc.png differ
diff --git a/resources/browsers/dia.png b/resources/browsers/dia.png
new file mode 100644
index 0000000..a313e4c
Binary files /dev/null and b/resources/browsers/dia.png differ
diff --git a/resources/browsers/zen.png b/resources/browsers/zen.png
new file mode 100644
index 0000000..14b3136
Binary files /dev/null and b/resources/browsers/zen.png differ
diff --git a/scripts/build.sh b/scripts/build.sh
index d5bfb20..1e438e5 100755
--- a/scripts/build.sh
+++ b/scripts/build.sh
@@ -38,6 +38,7 @@ echo -n "APPL????" > "$APP/Contents/PkgInfo"
[ -d resources/web ] && cp -R resources/web "$APP/Contents/Resources/web"
[ -d resources/brand ] && cp -R resources/brand "$APP/Contents/Resources/brand"
[ -d resources/blocklist ] && cp -R resources/blocklist "$APP/Contents/Resources/blocklist"
+[ -d resources/browsers ] && cp -R resources/browsers "$APP/Contents/Resources/browsers"
FRAMEWORK_SRC="$ROOT/vendor/cef/Release/Chromium Embedded Framework.framework"
cp -R "$FRAMEWORK_SRC" "$APP/Contents/Frameworks/"
diff --git a/scripts/cef-patches/extensions-normal-windows.patch b/scripts/cef-patches/extensions-normal-windows.patch
new file mode 100644
index 0000000..f697efc
--- /dev/null
+++ b/scripts/cef-patches/extensions-normal-windows.patch
@@ -0,0 +1,69 @@
+diff --git a/chrome/browser/extensions/api/extension_action/extension_action_api.cc b/chrome/browser/extensions/api/extension_action/extension_action_api.cc
+index 35e0c91..c702702 100644
+--- a/chrome/browser/extensions/api/extension_action/extension_action_api.cc
++++ b/chrome/browser/extensions/api/extension_action/extension_action_api.cc
+@@ -57,6 +57,10 @@
+ #include "chrome/browser/ui/window_feature_controller/window_feature_controller.h"
+ #endif // !BUILDFLAG(IS_ANDROID)
+
++#if BUILDFLAG(ENABLE_CEF)
++#include "cef/libcef/browser/chrome/browser_delegate.h"
++#endif
++
+ using content::WebContents;
+ using extensions::browser_window_util::GetLastActiveBrowserWithProfile;
+
+@@ -145,9 +149,18 @@ bool OpenPopupInBrowser(BrowserWindowInterface& browser,
+ // exists, so the check below is sufficient.
+ // On other platforms, ExtensionsContainer is always constructed except for
+ // guest sessions, so we need more detailed checks.
+- if (!WindowFeatureController::From(&browser)->SupportsWindowFeature(
+- WindowFeatureController::WindowFeature::kFeatureToolbar) ||
+- !BrowserWindow::FromBrowser(&browser)->IsToolbarVisible()) {
++ bool has_toolbar =
++ WindowFeatureController::From(&browser)->SupportsWindowFeature(
++ WindowFeatureController::WindowFeature::kFeatureToolbar) &&
++ BrowserWindow::FromBrowser(&browser)->IsToolbarVisible();
++#if BUILDFLAG(ENABLE_CEF)
++ // Cra: CEF hosts pages in popup-type Browsers, which never "have" a toolbar,
++ // and Cra draws its own toolbar over Chrome's hidden one. The extensions
++ // container still shows the popup, as it does for Cra's toolbar buttons.
++ has_toolbar = has_toolbar ||
++ (browser.cef_delegate() && browser.cef_delegate()->IsViewsHosted());
++#endif
++ if (!has_toolbar) {
+ *error = "Browser window has no toolbar.";
+ return false;
+ }
+diff --git a/chrome/browser/extensions/browser_extension_window_controller.cc b/chrome/browser/extensions/browser_extension_window_controller.cc
+index b48c045..bacb778 100644
+--- a/chrome/browser/extensions/browser_extension_window_controller.cc
++++ b/chrome/browser/extensions/browser_extension_window_controller.cc
+@@ -32,6 +32,10 @@
+ #include "ui/base/page_transition_types.h"
+ #include "ui/base/window_open_disposition.h"
+
++#if BUILDFLAG(ENABLE_CEF)
++#include "cef/libcef/browser/chrome/browser_delegate.h"
++#endif
++
+ // TODO(http://crbug.com/453008083): Stop including
+ // "android/chrome_feature_list.h".
+ #if BUILDFLAG(IS_ANDROID)
+@@ -137,6 +141,16 @@ int BrowserExtensionWindowController::GetWindowId() const {
+ }
+
+ std::string BrowserExtensionWindowController::GetWindowTypeText() const {
++#if BUILDFLAG(ENABLE_CEF)
++ // Cra: a page in a CefBrowserView is a popup-type Browser (CEF's way of
++ // dropping the tab strip), but to extensions it is the user's normal browser
++ // window, as in Chrome and Arc. Reporting "popup" made password managers
++ // treat every tab as a sign-in popup opened from the previous one.
++ if (window_type_ == api::tabs::WindowType::kPopup &&
++ browser_->cef_delegate() && browser_->cef_delegate()->IsViewsHosted()) {
++ return api::tabs::ToString(api::tabs::WindowType::kNormal);
++ }
++#endif
+ return api::tabs::ToString(window_type_);
+ }
+
diff --git a/scripts/dev.sh b/scripts/dev.sh
index ceae669..a82e578 100755
--- a/scripts/dev.sh
+++ b/scripts/dev.sh
@@ -65,7 +65,7 @@ build() {
fi
done
cp "$bin/Cra" "$APP/Contents/MacOS/$NAME"
- for d in web brand blocklist; do
+ for d in web brand blocklist browsers; do
[ -d "resources/$d" ] && rsync -a --delete "resources/$d/" "$APP/Contents/Resources/$d/"
done
codesign --force --sign - --entitlements resources/Cra.entitlements "$APP"
diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.sh
index 6395675..434fa9c 100755
--- a/scripts/fetch-cef.sh
+++ b/scripts/fetch-cef.sh
@@ -9,7 +9,7 @@
set -euo pipefail
cd "$(dirname "$0")/.."
-CEF_VERSION="${CEF_VERSION:-154.0.34+g14c5a08+chromium-154.0.8037.98}"
+CEF_VERSION="${CEF_VERSION:-156.0.14+g4fa4ab5+chromium-156.0.8078.48}"
ARCH="${CEF_ARCH:-macosarm64}"
NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"
# Bump the suffix (codecs2, …) when the build changes but CEF_VERSION does not.