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.

Own Keychain secret for cookies and passwords; lock down cra://

Victor24d502103c57
diff --git a/README.md b/README.md
index 25fffc7..69c7dad 100644
--- a/README.md
+++ b/README.md
@@ -57,6 +57,12 @@ testing without touching the keyboard):
open "cra://open?url=https://example.com&background=1"
open "cra://dismiss" # close sheets, command bar, find bar
+Links from other apps and browsers only reach `commandbar`, `dismiss` and `open` with an
+http(s) URL; pages inside Cra reach none of them. The rest (`action`, `navigate`, `key`,
+`import`, `debug`) run scripts and DevTools Protocol commands, so they need either
+`defaults write dk.kildahl.cra scriptingURLs -bool YES` or a test instance's
+`CRA_COMMAND_FILE`.
+
## Little Windows (Arc's Little Arc)
Links from other apps open in a Little Window: a small, sidebar-less window with one
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 7f75382..d71378e 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -9,7 +9,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
let favicons = FaviconCache()
lazy var engine = SuggestionEngine(store: store, bindings: bindings)
- private(set) var main: MainWindowController!
+ /// Browser windows, one per WindowSession. Closing the last one only hides it.
+ private(set) var mainWindows: [MainWindowController] = []
+ /// The browser window in use: the key one, or the one last key.
+ var main: MainWindowController! {
+ mainWindows.first { $0.windowID == store.activeWindowID } ?? mainWindows.first
+ }
private var bootstrapped = false
private var pendingURLs: [String] = []
private var autoArchiveTimer: Timer?
@@ -24,8 +29,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
/// Shortcuts the app takes before the web page sees them (Chrome calls
/// these reserved). Everything else goes to the page first.
static let reservedActions: Set<String> = Set([
- "newTab", "newWindow", "closeTab", "closeWindow", "reopenClosedTab", "editURL", "toggleSidebar", "toggleToolbar",
- "nextTab", "previousTab", "recentTab", "nextSpace", "previousSpace", "devTools", "jsConsole", "inspectElement",
+ "newTab", "newWindow", "newIncognitoWindow", "closeTab", "closeWindow", "reopenClosedTab", "editURL", "toggleSidebar", "toggleToolbar",
+ "nextTab", "previousTab", "recentTab", "recentTabBackward", "nextSpace", "previousSpace", "devTools", "jsConsole", "inspectElement",
"viewArchive", "openLibrary", "settings", "clearToday", "newLittleWindow", "promoteLittleWindow",
"addSplitView", "closeSplitPane",
] + (1...9).flatMap { ["item\($0)", "space\($0)"] })
@@ -46,10 +51,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
NotificationCenter.default.addObserver(forName: .craKeyBindingsChanged, object: nil, queue: .main) { [weak self] _ in
Task { @MainActor in self?.buildMenus() }
}
- main = MainWindowController(app: self)
+ mainWindows = store.prefs.windows.map { MainWindowController(app: self, session: $0) }
+ followKeyWindow()
// First launch: the default browser step and the import are the onboarding and
// the browser window appears once they are done (Dia does the same).
- if needsOnboarding { main.showImport(firstRun: true) } else { main.showWindow(nil) }
+ if needsOnboarding {
+ main.showImport(firstRun: true)
+ } else {
+ // The window in use last comes up in front.
+ for w in mainWindows.reversed() { w.showWindow(nil) }
+ }
installKeyFallbackMonitor()
installCommandFileWatcher()
store.runAutoArchive()
@@ -77,6 +88,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
NSLog("Cra: dropped start-up page from an extension: %@", url)
return
}
+ self.useNormalWindow()
self.store.createTab(url: url, select: true)
self.main.showWindow(nil)
}
@@ -195,7 +207,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
/// window_dialog_sheet_visible, active tabs). Little Windows go to the Library on quit,
/// so an open one waits too.
func autoUpdateBlocker() -> String? {
- if main.overlay.toasts.contains(where: { $0.state == CraDownloadState.inProgress.rawValue }) { return "a download is in progress" }
+ if mainWindows.contains(where: { $0.overlay.toasts.contains { $0.state == CraDownloadState.inProgress.rawValue } }) { return "a download is in progress" }
if NSApp.modalWindow != nil || NSApp.windows.contains(where: { $0.isVisible && $0.attachedSheet != nil }) { return "a dialog is open" }
if !littleWindows.isEmpty { return "a Little Window is open" }
if PictureInPictureChrome.shared.isPlaying { return "Picture in Picture is playing" }
@@ -213,10 +225,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
}
func openExternalURL(_ url: String) {
- if let u = URL(string: url), u.scheme == "cra" {
- handleInternalURL(u)
+ if let u = URL(string: url), u.scheme?.lowercased() == "cra" {
+ if Self.isUserFacing(u) || UserDefaults.standard.bool(forKey: "scriptingURLs") {
+ handleInternalURL(u)
+ } else {
+ NSLog("Cra: ignored %@ from another app (defaults write dk.kildahl.cra scriptingURLs -bool YES allows it)", url)
+ }
return
}
+ // Links from other apps never land in an incognito window (Chrome does the same).
+ useNormalWindow()
// 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) {
@@ -232,6 +250,95 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
NSApp.activate(ignoringOtherApps: true)
}
+ // MARK: Browser windows
+
+ /// Menu commands and new tabs follow the browser window the user is in. Its key
+ /// window is often a child (a page, the command bar, the find bar).
+ private func followKeyWindow() {
+ // Synchronous: a shortcut right after a click must already go to the new window.
+ // Main covers windows raised while Cra is in the background (Mission Control, the Window menu).
+ for name in [NSWindow.didBecomeKeyNotification, NSWindow.didBecomeMainNotification] {
+ NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [weak self] note in
+ MainActor.assumeIsolated {
+ guard let self, var w = note.object as? NSWindow else { return }
+ while let parent = w.parent { w = parent }
+ if let c = self.mainWindows.first(where: { $0.window === w }) { self.store.activeWindowID = c.windowID }
+ }
+ }
+ }
+ }
+
+ /// The window links from other apps, the Library and Little Windows go to: the
+ /// normal window in use last, never an incognito one.
+ @discardableResult
+ func useNormalWindow() -> MainWindowController {
+ if main.isIncognito, let normal = mainWindows.first(where: { $0.windowID == store.lastNormalWindowID })
+ ?? mainWindows.first(where: { !$0.isIncognito }) {
+ store.activeWindowID = normal.windowID
+ }
+ return main
+ }
+
+ /// Arc's New Window (⌘N): another window on the space in use, cascaded from the
+ /// current one, with the command bar up. With every window closed it brings the
+ /// hidden one back instead. New Incognito Window (⇧⌘N) always opens a new one.
+ func openNewWindow(incognito: Bool = false) {
+ if !incognito, let hidden = mainWindows.first(where: { !$0.isIncognito }),
+ !mainWindows.contains(where: { $0.window?.isVisible == true || $0.window?.isMiniaturized == true }) {
+ hidden.showWindow(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ return
+ }
+ var frame: String?
+ if let current = main?.window, current.isVisible, !current.styleMask.contains(.fullScreen) {
+ var f = current.frame.offsetBy(dx: 22, dy: -22)
+ if let screen = (current.screen ?? NSScreen.main)?.visibleFrame, !screen.contains(f) {
+ f.origin = NSPoint(x: screen.minX + 22, y: screen.maxY - f.height - 22)
+ }
+ frame = NSStringFromRect(f)
+ }
+ let session = incognito ? store.addIncognitoWindow(frame: frame)
+ : store.addWindow(spaceID: store.focusedSpaceID(window: store.lastNormalWindowID), frame: frame)
+ let c = MainWindowController(app: self, session: session)
+ mainWindows.append(c)
+ store.activeWindowID = c.windowID
+ c.showWindow(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ c.openCommandBar(.newTab)
+ }
+
+ /// Closing one of several windows ends it; the last normal one stays around hidden,
+ /// so a Dock click brings the browser back as it was. Incognito windows always end,
+ /// and with the last of them the off-the-record profile goes too.
+ func mainWindowWillClose(_ c: MainWindowController) {
+ guard !isRelaunching, c.isIncognito || mainWindows.contains(where: { $0 !== c && !$0.isIncognito }) else { return }
+ mainWindows.removeAll { $0 === c }
+ c.tearDown()
+ store.removeWindow(c.windowID)
+ if c.isIncognito, !mainWindows.contains(where: \.isIncognito) { CraCEFRuntime.endIncognitoSession() }
+ // AppKit makes the next window key on its own; until then actions go to the frontmost.
+ if let front = NSApp.orderedWindows.compactMap({ w in mainWindows.first { $0.window === w } }).first {
+ store.activeWindowID = front.windowID
+ }
+ }
+
+ /// A tab's live page, whichever window holds it.
+ func runtime(for tabID: UUID) -> TabRuntime? {
+ for w in mainWindows { if let rt = w.browsers.runtime(for: tabID) { return rt } }
+ return nil
+ }
+
+ func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
+ let menu = NSMenu()
+ for (title, id) in [("New Window", "newWindow"), ("New Incognito Window", "newIncognitoWindow")] {
+ let item = NSMenuItem(title: title, action: #selector(menuAction(_:)), keyEquivalent: "")
+ item.representedObject = id
+ item.target = self
+ menu.addItem(item)
+ }
+ return menu
+ }
+
// MARK: Little Windows
/// The little window that owns the key window (the window itself, or its
@@ -268,6 +375,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
for w in littleWindows { w.closeWindow() }
}
+ /// cra:// URLs any app may send: they do what the user could do from the Dock.
+ /// The rest (action, navigate, key, import, debug, open with a file: or javascript:
+ /// URL) run scripts, DevTools Protocol and key presses, so a link in a mail or another
+ /// browser must not reach them. CRA_COMMAND_FILE and the scriptingURLs default do.
+ static func isUserFacing(_ u: URL) -> Bool {
+ switch u.host {
+ case "commandbar", "dismiss":
+ return true
+ case "open":
+ let target = URLComponents(url: u, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "url" }?.value
+ let scheme = target.flatMap { URL(string: $0)?.scheme?.lowercased() }
+ return scheme == "http" || scheme == "https"
+ default:
+ return false
+ }
+ }
+
/// cra://commandbar?query=…&mode=edit, cra://action/<id>, cra://open?url=…,
/// cra://dismiss.
/// Arc marks a tab chosen from the keyboard with its yellow/black focus ring.
@@ -294,6 +418,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
if let url = q("url"), q("little") == "1" {
openLittleWindow(url: url)
} else if let url = q("url") {
+ useNormalWindow()
let tab = store.createTab(url: url, select: q("background") != "1")
if q("background") == "1" { store.markUnread(tab.id, true); main.browsers.ensureRuntime(for: tab.id) }
}
@@ -395,7 +520,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
func validateMenuItem(_ item: NSMenuItem) -> Bool {
switch item.representedObject as? String {
- case "toggleSidebar": item.title = store.prefs.sidebarVisible ? "Hide Sidebar" : "Show Sidebar"
+ case "toggleSidebar": item.title = main.sidebarVisible ? "Hide Sidebar" : "Show Sidebar"
case "toggleToolbar": item.title = store.settings.showToolbar ? "Hide Toolbar" : "Show Toolbar"
case "toggleDeveloperMode":
let on = store.selectedTab?.tab.map { store.settings.isDeveloperMode(url: $0.url) } ?? false
@@ -410,6 +535,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "closeSplitPane", "separateFromSplit", "flipSplitOrientation":
return store.selectedTabID.flatMap { store.splitContaining($0) } != nil
case "addSplitView": return store.selectedTabID != nil
+ case "editSpace", "deleteSpace", "nextSpace", "previousSpace": return !main.isIncognito
case "closeLittleWindows": return !littleWindows.isEmpty
default: break
}
@@ -494,19 +620,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "newLittleWindow": openLittleWindow(url: "")
case "closeLittleWindows": closeLittleWindows()
case "promoteLittleWindow": break // only meaningful while a little window is key
- case "newTab", "newWindow": main.openCommandBar(.newTab)
+ case "newTab": main.openCommandBar(.newTab)
+ case "newWindow": openNewWindow()
+ case "newIncognitoWindow": openNewWindow(incognito: true)
case "editURL": main.openCommandBar(.editURL)
case "newFolder":
let f = store.createFolder(named: "New Folder", in: store.focusedSpace.pinnedContainerID, index: 0)
main.sidebarUI.renamingID = f.id
case "newSpace": main.showSpaceEditor(space: nil)
- case "editSpace": main.showSpaceEditor(space: store.focusedSpace)
- case "deleteSpace": confirmDeleteSpace(store.focusedSpace)
+ case "editSpace": if !main.isIncognito { main.showSpaceEditor(space: store.focusedSpace) }
+ case "deleteSpace": if !main.isIncognito { confirmDeleteSpace(store.focusedSpace) }
case "closeTab":
// Arc: "Close current tab or window".
if current != nil { main.closeCurrentTab() } else { main.window?.performClose(nil) }
case "closeWindow": main.window?.performClose(nil)
- case "reopenClosedTab": store.reopenLastArchived()
+ case "reopenClosedTab": if !main.isIncognito { store.reopenLastArchived() } // incognito tabs leave nothing to restore
case "copyURL":
if let url = current.flatMap({ store.item($0)?.tab?.url }) {
copy(url)
@@ -550,13 +678,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "muteTab":
if let c = current, let t = store.item(c)?.tab {
store.setMuted(c, !t.muted)
- main.browsers.runtime(for: c)?.browser.setAudioMuted(!t.muted)
+ runtime(for: c)?.browser.setAudioMuted(!t.muted)
}
case "clearToday": store.clearToday()
case "pictureInPicture": main.currentBrowser?.requestPictureInPicture(automatic: false)
case "nextTab": main.cycleTab(1); markKeyboardFocus()
case "previousTab": main.cycleTab(-1); markKeyboardFocus()
- case "recentTab": if let id = store.mostRecentOtherTab() { store.selectTab(id); markKeyboardFocus() }
+ case "recentTab": main.cycleRecentTabs(1, event: NSApp.currentEvent)
+ case "recentTabBackward": main.cycleRecentTabs(-1, event: NSApp.currentEvent)
case "nextSpace": store.focusSpace(offset: 1)
case "previousSpace": store.focusSpace(offset: -1)
case "addSplitView": main.addSplitPane()
@@ -605,7 +734,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
if settingsController == nil {
let actions = SettingsActions(
importData: { [weak self] in self?.main.showImport() },
- openURL: { [weak self] url in guard let self else { return }; _ = self.store.createTab(url: url, select: true); self.settingsWindow?.close() })
+ openURL: { [weak self] url in
+ guard let self else { return }
+ self.useNormalWindow()
+ _ = self.store.createTab(url: url, select: true)
+ self.settingsWindow?.close()
+ self.main.showWindow(nil)
+ })
let c = SettingsWindowController(store: store, bindings: bindings, actions: actions)
settingsController = c
settingsWindow = c.window
@@ -618,6 +753,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 720, height: 560), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
w.title = "Library"
w.contentView = NSHostingView(rootView: ArchiveView(onRestore: { [weak self] id in
+ self?.useNormalWindow()
self?.store.restoreArchived(id)
self?.archiveWindow?.close()
self?.main.showWindow(nil)
@@ -673,7 +809,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
menubar.addItem(submenu: appMenu, title: "Cra")
let file = NSMenu(title: "File")
- for id in ["newTab", "newWindow", "newLittleWindow", "reopenClosedTab", "editURL", "newFolder", "newSpace"] { file.addItem(item(id)) }
+ for id in ["newTab", "newWindow", "newIncognitoWindow", "newLittleWindow", "reopenClosedTab", "editURL", "newFolder", "newSpace"] { file.addItem(item(id)) }
file.addItem(.separator())
file.addItem(item("closeWindow")); file.addItem(item("closeTab"))
file.addItem(.separator())
diff --git a/Sources/Cra/App/KeyBindings.swift b/Sources/Cra/App/KeyBindings.swift
index 9be03c3..4d50a24 100644
--- a/Sources/Cra/App/KeyBindings.swift
+++ b/Sources/Cra/App/KeyBindings.swift
@@ -21,7 +21,8 @@ struct Shortcut: Codable, Hashable {
var flags: NSEvent.ModifierFlags { NSEvent.ModifierFlags(rawValue: modifiers) }
/// Shift turns "[" into "{" in charactersIgnoringModifiers; undo that.
- private static let unshift: [String: String] = ["{": "[", "}": "]", "<": ",", ">": ".", "?": "/", "+": "=", "_": "-", "~": "`", ":": ";", "\"": "'", "|": "\\"]
+ /// ⇧Tab arrives as backtab (U+0019).
+ private static let unshift: [String: String] = ["\u{19}": Shortcut.tab, "{": "[", "}": "]", "<": ",", ">": ".", "?": "/", "+": "=", "_": "-", "~": "`", ":": ";", "\"": "'", "|": "\\"]
/// Physical-key fallbacks so ⌘[ / ⌘] work on layouts (Danish, German...)
/// where those characters live on other keys. Key codes are ANSI positions.
@@ -154,6 +155,8 @@ final class KeyBindingRegistry {
// File
KeyAction(id: "newTab", name: "New Tab…", section: .file, shortcuts: [Shortcut("t", cmd)], triggers: ["new tab"]),
KeyAction(id: "newWindow", name: "New Window", section: .file, shortcuts: [Shortcut("n", cmd)], inCommandBar: false),
+ KeyAction(id: "newIncognitoWindow", name: "New Incognito Window", section: .file, shortcuts: [Shortcut("n", cmdShift)],
+ triggers: ["incognito", "private"]),
// Arc: File ▸ New Little Arc Window ⌥⌘N.
KeyAction(id: "newLittleWindow", name: "New Little Window", section: .file, shortcuts: [Shortcut("n", cmdOpt)], triggers: ["little window", "little arc"]),
KeyAction(id: "reopenClosedTab", name: "Restore Last Closed Tab", section: .file, shortcuts: [Shortcut("t", cmdShift)], triggers: ["reopen", "undo close", "restore"]),
@@ -203,7 +206,8 @@ final class KeyBindingRegistry {
KeyAction(id: "pinTab", name: "Pin/Unpin Tab", section: .tabs, shortcuts: [Shortcut("d", cmd)], triggers: ["pin", "unpin"]),
KeyAction(id: "nextTab", name: "Next Tab", section: .tabs, shortcuts: [Shortcut(Shortcut.down, cmdOpt)], inCommandBar: false),
KeyAction(id: "previousTab", name: "Previous Tab", section: .tabs, shortcuts: [Shortcut(Shortcut.up, cmdOpt)], inCommandBar: false),
- KeyAction(id: "recentTab", name: "Toggle Recent Tabs", section: .tabs, shortcuts: [Shortcut(Shortcut.tab, .control)], inCommandBar: false),
+ KeyAction(id: "recentTab", name: "Next Recent Tab", section: .tabs, shortcuts: [Shortcut(Shortcut.tab, .control)], inCommandBar: false),
+ KeyAction(id: "recentTabBackward", name: "Previous Recent Tab", section: .tabs, shortcuts: [Shortcut(Shortcut.tab, [.control, .shift])], inCommandBar: false),
KeyAction(id: "clearToday", name: "Clear Today", section: .tabs, shortcuts: [Shortcut("k", cmdShift)], triggers: ["clear", "tidy"]),
KeyAction(id: "favoriteTab", name: "Add to Favorites", section: .tabs, shortcuts: [], triggers: ["favorite", "top app"]),
KeyAction(id: "renameTab", name: "Rename Tab…", section: .tabs, shortcuts: [], triggers: ["rename"]),
diff --git a/Sources/Cra/App/NewestCopy.swift b/Sources/Cra/App/NewestCopy.swift
new file mode 100644
index 0000000..9c3602a
--- /dev/null
+++ b/Sources/Cra/App/NewestCopy.swift
@@ -0,0 +1,136 @@
+import AppKit
+import Security
+
+/// Keeps an old copy of Cra from standing in for a new one. Chromium lets one process
+/// own the profile and hands every later launch to it, so a new download opened while
+/// an old Cra is still running (closed windows, launch at login) used to show the old
+/// version. Finder cannot replace a running app either, which leaves "Cra 2.app" next
+/// to the old Cra.app that the Dock and login items keep opening. Both run from
+/// main.swift before Chromium starts.
+enum NewestCopy {
+ static let version = shortVersion(at: Bundle.main.bundleURL) ?? ""
+
+ /// Numeric, so 0.1.10 is newer than 0.1.9 and 0.0.0-dev is older than any release.
+ static func isOlder(_ a: String, than b: String) -> Bool {
+ a.compare(b, options: .numeric) == .orderedAscending
+ }
+
+ /// Read from disk rather than through Bundle, which caches Info.plist per path.
+ static func shortVersion(at bundle: URL) -> String? {
+ NSDictionary(contentsOf: bundle.appendingPathComponent("Contents/Info.plist"))?["CFBundleShortVersionString"] as? String
+ }
+
+ /// An installed release opened while a newer one sits elsewhere on the Mac opens that
+ /// one and exits. Only signed releases on the default data dir take part: dev builds
+ /// (0.0.0-dev, no SUFeedURL) and CRA_DATA_DIR copies must run as themselves.
+ static func openNewerInstalledCopy() {
+ guard ProcessInfo.processInfo.environment["CRA_DATA_DIR"] == nil,
+ Bundle.main.object(forInfoDictionaryKey: "SUFeedURL") != nil,
+ let id = Bundle.main.bundleIdentifier, let team = teamID(of: Bundle.main.bundleURL) else { return }
+ let me = Bundle.main.bundleURL.resolvingSymlinksInPath().path
+ let newer = NSWorkspace.shared.urlsForApplications(withBundleIdentifier: id)
+ .map { $0.resolvingSymlinksInPath() }
+ .filter { $0.path != me && isInstalled($0) }
+ .compactMap { url in shortVersion(at: url).map { (url: url, version: $0) } }
+ .filter { isOlder(version, than: $0.version) && teamID(of: $0.url) == team }
+ .max { isOlder($0.version, than: $1.version) }
+ guard let newer else { return }
+ NSLog("Cra: \(version) at \(me) opens the newer \(newer.version) at \(newer.url.path)")
+ let open = Process()
+ open.executableURL = URL(fileURLWithPath: "/usr/bin/open")
+ open.arguments = [newer.url.path]
+ guard (try? open.run()) != nil else { return }
+ open.waitUntilExit()
+ if open.terminationStatus == 0 { exit(0) }
+ }
+
+ /// A running Cra older than this one that owns our profile is asked to quit, so this
+ /// launch takes over instead of being handed to it. Its SingletonLock names it
+ /// ("host-pid"), which also leaves CRA_DATA_DIR copies on other profiles alone.
+ static func replaceOlderRunningCopy() {
+ guard let other = profileOwner(), let url = other.bundleURL,
+ let theirs = shortVersion(at: url), isOlder(theirs, than: version) else { return }
+ let pid = other.processIdentifier
+ NSLog("Cra: \(version) replaces the running \(theirs) (pid \(pid))")
+ other.terminate()
+ while !waitForExit(pid, seconds: 10) {
+ switch stillOpenAlert(theirs, pid: pid) {
+ case .OK: break
+ case .alertFirstButtonReturn: other.terminate()
+ case .alertSecondButtonReturn: other.forceTerminate()
+ default: other.activate(); exit(0)
+ }
+ }
+ // As in relaunch(): give Chromium a moment to let go of the profile.
+ usleep(300_000)
+ }
+
+ /// Shown when the old copy has not quit, usually because its "Warn before quitting"
+ /// prompt is up. That prompt is centred and its app is in front, so this one floats
+ /// above the centre and stays visible while Cra is not active (the launch may not
+ /// have activated it yet), and it closes by itself (.OK) once the old copy is gone.
+ private static func stillOpenAlert(_ theirs: String, pid: pid_t) -> NSApplication.ModalResponse {
+ let alert = NSAlert()
+ alert.messageText = "Cra \(theirs) is still open"
+ alert.informativeText = "Quit it to open Cra \(version). If it asked whether to quit, choose Quit."
+ alert.addButton(withTitle: "Try Again")
+ alert.addButton(withTitle: "Force Quit")
+ alert.addButton(withTitle: "Cancel")
+ alert.layout()
+ alert.window.hidesOnDeactivate = false
+ if let screen = NSScreen.main?.visibleFrame {
+ let size = alert.window.frame.size
+ alert.window.setFrameOrigin(NSPoint(x: screen.midX - size.width / 2, y: screen.midY + 170))
+ }
+ // runModal resets the level, so raise it once the modal session runs.
+ RunLoop.current.perform(inModes: [.modalPanel]) {
+ MainActor.assumeIsolated {
+ alert.window.level = .floating
+ alert.window.orderFrontRegardless()
+ }
+ }
+ let gone = Timer(timeInterval: 0.2, repeats: true) { _ in
+ if kill(pid, 0) != 0 && errno == ESRCH { MainActor.assumeIsolated { NSApp.stopModal(withCode: .OK) } }
+ }
+ RunLoop.current.add(gone, forMode: .modalPanel)
+ defer { gone.invalidate() }
+ return alert.runModal()
+ }
+
+ private static func profileOwner() -> NSRunningApplication? {
+ let lock = AppPaths.chromiumCache.appendingPathComponent("SingletonLock").path
+ guard let target = try? FileManager.default.destinationOfSymbolicLink(atPath: lock),
+ let pid = target.split(separator: "-").last.flatMap({ pid_t($0) }), pid != getpid(),
+ let app = NSRunningApplication(processIdentifier: pid),
+ app.bundleIdentifier == Bundle.main.bundleIdentifier else { return nil }
+ return app
+ }
+
+ private static func waitForExit(_ pid: pid_t, seconds: Double) -> Bool {
+ let deadline = Date().addingTimeInterval(seconds)
+ while kill(pid, 0) == 0 || errno != ESRCH {
+ if Date() > deadline { return false }
+ usleep(100_000)
+ }
+ return true
+ }
+
+ /// Not a disk image, the Trash or a translocated copy, which are not installs.
+ private static func isInstalled(_ url: URL) -> Bool {
+ let p = url.path
+ return FileManager.default.fileExists(atPath: p) && !p.hasPrefix("/Volumes/")
+ && !p.contains("/.Trash/") && !p.contains("/AppTranslocation/")
+ }
+
+ /// The signing team, checked without hashing every resource (CEF is large);
+ /// Gatekeeper checks the whole bundle when it opens. nil for ad-hoc builds.
+ private static func teamID(of bundle: URL) -> String? {
+ var code: SecStaticCode?
+ var info: CFDictionary?
+ guard SecStaticCodeCreateWithPath(bundle as CFURL, [], &code) == errSecSuccess, let code,
+ SecStaticCodeCheckValidity(code, SecCSFlags(rawValue: kSecCSDoNotValidateResources), nil) == errSecSuccess,
+ SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess
+ else { return nil }
+ return (info as? [String: Any])?[kSecCodeInfoTeamIdentifier as String] as? String
+ }
+}
diff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swift
index 20a4a15..530fce7 100644
--- a/Sources/Cra/App/main.swift
+++ b/Sources/Cra/App/main.swift
@@ -8,13 +8,24 @@ MainActor.assumeIsolated {
let delegate = AppDelegate()
app.delegate = delegate
+ // The newest copy of Cra runs: an older install opens a newer one, and an older
+ // Cra holding the profile quits rather than receiving this launch (NewestCopy).
+ NewestCopy.openNewerInstalledCopy()
+ NewestCopy.replaceOlderRunningCopy()
+
// Passwords and cookies staged by the import go into the profile while no
// Chromium has it open: before initializing, and only when no other Cra runs.
+ // The run loop has not started, so the list can still hold a Cra that just quit.
let me = ProcessInfo.processInfo.processIdentifier
- if !NSRunningApplication.runningApplications(withBundleIdentifier: Bundle.main.bundleIdentifier ?? "").contains(where: { $0.processIdentifier != me }) {
+ let profileIsFree = !NSRunningApplication.runningApplications(withBundleIdentifier: Bundle.main.bundleIdentifier ?? "").contains(where: { $0.processIdentifier != me && kill($0.processIdentifier, 0) == 0 })
+ // Cookies and passwords move from the mock keychain to Cra's Keychain item first,
+ // staged imports included, so everything below writes with the key Chromium reads.
+ SafeStorage.prepare(profileIsFree: profileIsFree)
+ if profileIsFree {
let profile = AppPaths.chromiumCache.appendingPathComponent("Default", isDirectory: true)
if CredentialImport.hasPending { CredentialImport.applyPending(profileDir: profile) }
CredentialImport.repairImportedCookies(profileDir: profile)
+ ProfileCleanup.run()
}
NativeMessagingHosts.link(into: AppPaths.chromiumCache)
@@ -23,7 +34,8 @@ MainActor.assumeIsolated {
let started = CraCEFRuntime.initialize(withCachePath: AppPaths.chromiumCache.path,
userAgentProduct: "",
logPath: AppPaths.log.path,
- useChromeStyle: useChromeStyle)
+ useChromeStyle: useChromeStyle,
+ useMockKeychain: !SafeStorage.usesKeychain)
if !started && CraCEFRuntime.anotherInstanceWasNotified() {
// The running Cra got our command line; just activate it.
NSRunningApplication.runningApplications(withBundleIdentifier: Bundle.main.bundleIdentifier ?? "dk.kildahl.cra")
diff --git a/Sources/Cra/Model/SidebarModel.swift b/Sources/Cra/Model/SidebarModel.swift
index 9df97d0..61b1ab6 100644
--- a/Sources/Cra/Model/SidebarModel.swift
+++ b/Sources/Cra/Model/SidebarModel.swift
@@ -232,6 +232,9 @@ struct SpaceTheme: Codable, Equatable {
SpaceTheme(colors: ["#F4F1EA", "#E6DCC8"], intensity: 0.6, noise: 0.15, appearance: "light"), // Parchment
]
+ /// Incognito windows: near-black with a cool violet cast, so they never pass for a space.
+ static let incognito = SpaceTheme(colors: ["#141318", "#2B2638"], intensity: 0.9, noise: 0.14, appearance: "dark")
+
var isDark: Bool {
if appearance == "dark" { return true }
if appearance == "light" { return false }
@@ -262,6 +265,18 @@ struct Space: Identifiable, Codable, Equatable {
var pinnedContainerID: UUID
var todayContainerID: UUID
var createdAt: Date
+ /// The profile its pages load in (Arc: SpaceModel.profile); nil is the Default profile.
+ var profileID: UUID?
+}
+
+/// Arc's Profiles: logins, cookies, site storage and Chromium's own data kept apart
+/// from the Default profile. Any number of spaces can use one.
+struct BrowserProfile: Identifiable, Codable, Equatable {
+ var id: UUID
+ var name: String
+
+ /// Chromium's folder for it, next to Default under AppPaths.chromiumCache.
+ var directoryName: String { "Profile \(id.uuidString)" }
}
struct SidebarDocument: Codable {
@@ -272,6 +287,8 @@ struct SidebarDocument: Codable {
/// split it up between the spaces; new files leave it out.
var favoritesContainerID: UUID?
var items: [SidebarItem]
+ /// Profiles besides Default (missing in files from before profiles).
+ var profiles: [BrowserProfile]?
static func fresh() -> SidebarDocument {
let spaceID = UUID()
@@ -400,14 +417,31 @@ struct AppSettings: Codable, Equatable {
}
}
+/// One browser window. Each window shows its own space and remembers its own
+/// open tab per space; spaces and tabs themselves are shared (Arc).
+struct WindowSession: Codable, Equatable, Identifiable {
+ var id = UUID()
+ var focusedSpaceID: UUID?
+ var selectedTabPerSpace: [UUID: UUID] = [:]
+ var frame: String?
+ var sidebarVisible = true
+ /// Incognito windows show a space of their own, never saved (SidebarStore.addIncognitoWindow).
+ var isIncognito = false
+}
+
struct WindowPrefs: Codable, Equatable {
var sidebarWidth: Double = 328
- var sidebarVisible: Bool = true
- var focusedSpaceID: UUID?
var expandedFolders: Set<UUID> = []
var collapsedPinnedSpaces: Set<UUID> = []
- var selectedTabPerSpace: [UUID: UUID] = [:]
- var windowFrame: String?
+ /// Open browser windows, restored at launch. Never empty.
+ var windows: [WindowSession] = [WindowSession()]
+
+ /// What is written to windows.json: incognito windows are never restored.
+ var withoutIncognito: WindowPrefs {
+ var p = self
+ p.windows.removeAll { $0.isIncognito }
+ return p
+ }
/// Last Little Window size (Arc: LittleBrowserWindow_size).
var littleWindowSize: String?
}
@@ -465,19 +499,38 @@ extension AppSettings {
}
extension WindowPrefs {
+ /// Single-window builds kept the window's state at the top level.
+ private enum LegacyKeys: String, CodingKey { case sidebarVisible, focusedSpaceID, selectedTabPerSpace, windowFrame }
+
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
sidebarWidth = try c.decodeIfPresent(Double.self, forKey: .sidebarWidth) ?? 328
- sidebarVisible = try c.decodeIfPresent(Bool.self, forKey: .sidebarVisible) ?? true
- focusedSpaceID = try c.decodeIfPresent(UUID.self, forKey: .focusedSpaceID)
expandedFolders = try c.decodeIfPresent(Set<UUID>.self, forKey: .expandedFolders) ?? []
collapsedPinnedSpaces = try c.decodeIfPresent(Set<UUID>.self, forKey: .collapsedPinnedSpaces) ?? []
- selectedTabPerSpace = try c.decodeIfPresent([UUID: UUID].self, forKey: .selectedTabPerSpace) ?? [:]
- windowFrame = try c.decodeIfPresent(String.self, forKey: .windowFrame)
+ if let saved = try? c.decodeIfPresent([WindowSession].self, forKey: .windows), !saved.isEmpty {
+ windows = saved
+ } else {
+ let legacy = try decoder.container(keyedBy: LegacyKeys.self)
+ windows = [WindowSession(focusedSpaceID: try legacy.decodeIfPresent(UUID.self, forKey: .focusedSpaceID),
+ selectedTabPerSpace: try legacy.decodeIfPresent([UUID: UUID].self, forKey: .selectedTabPerSpace) ?? [:],
+ frame: try legacy.decodeIfPresent(String.self, forKey: .windowFrame),
+ sidebarVisible: try legacy.decodeIfPresent(Bool.self, forKey: .sidebarVisible) ?? true)]
+ }
littleWindowSize = try c.decodeIfPresent(String.self, forKey: .littleWindowSize)
}
}
+extension WindowSession {
+ init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ id = try c.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
+ focusedSpaceID = try c.decodeIfPresent(UUID.self, forKey: .focusedSpaceID)
+ selectedTabPerSpace = try c.decodeIfPresent([UUID: UUID].self, forKey: .selectedTabPerSpace) ?? [:]
+ frame = try c.decodeIfPresent(String.self, forKey: .frame)
+ sidebarVisible = try c.decodeIfPresent(Bool.self, forKey: .sidebarVisible) ?? true
+ }
+}
+
extension Space {
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
@@ -490,6 +543,7 @@ extension Space {
pinnedContainerID = try c.decode(UUID.self, forKey: .pinnedContainerID)
todayContainerID = try c.decode(UUID.self, forKey: .todayContainerID)
createdAt = try c.decode(Date.self, forKey: .createdAt)
+ profileID = try c.decodeIfPresent(UUID.self, forKey: .profileID)
}
}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index 6f4f0b7..16e4277 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -15,6 +15,9 @@ final class TabRuntime {
/// auto Picture in Picture); coming back brings the video home.
var autoPictureInPicture = false
var pendingAutoPictureInPicture = false
+ /// The tab switcher's thumbnail, taken while the page was last on screen.
+ var snapshot: NSImage?
+ var snapshotWork: DispatchWorkItem?
/// Chrome-style hosting: the page's own window (nil until created, or for Alloy).
var hostWindow: NSWindow? { browser.hostWindow }
init(tabID: UUID, browser: CraBrowser) {
@@ -41,7 +44,6 @@ protocol BrowserManagerDelegate: AnyObject {
func browserManagerHandleKey(_ event: NSEvent) -> Bool
func browserManagerHandleUnhandledKey(_ event: NSEvent) -> Bool
func browserManagerFocusedBrowser(_ tabID: UUID)
- func browserManagerOpenInternalURL(_ url: String)
/// The page closed itself (window.close()).
func browserManagerPageClosedTab(_ tabID: UUID)
}
@@ -60,6 +62,10 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
private(set) var visibleTabIDs: [UUID] = []
/// Split view: the view a tab's Alloy-hosted Chromium view should live in.
var paneHost: ((UUID) -> NSView?)?
+ /// The browser window this manager shows pages in (tabs it opens are selected there).
+ var windowID: UUID?
+ /// A tab's live page held by another window's manager, handed over (see `release`).
+ var takeRuntimeFromOtherWindow: ((UUID) -> TabRuntime?)?
private var byBrowser: [ObjectIdentifier: UUID] = [:]
init(store: SidebarStore, favicons: FaviconCache, container: NSView) {
@@ -76,7 +82,15 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
if let r = runtimes[tabID] { return r }
// An empty split pane has no page yet (Arc shows the tinted card and the command bar).
guard let item = store.item(tabID), let tab = item.tab, !item.isEmptyTab else { return nil }
- let browser = CraBrowser(frame: container.bounds, url: tab.url, delegate: self)
+ // The page moves between windows with its history and state, never loads twice.
+ if let rt = takeRuntimeFromOtherWindow?(tabID) {
+ rt.browser.delegate = self
+ add(rt)
+ if inRightProfile(rt) { return rt }
+ release(tabID)?.browser.close()
+ }
+ let browser = CraBrowser(frame: container.bounds, url: tab.url, delegate: self, incognito: store.isIncognito(item: tabID),
+ profilePath: store.profilePath(item: tabID))
return register(browser: browser, tabID: tabID)
}
@@ -94,7 +108,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
/// Popup host: a browser shell CEF will fill with window.open content.
func makePopupHost(for tabID: UUID) -> CraBrowser {
- let browser = CraBrowser(frame: container.bounds, url: nil, delegate: self)
+ let browser = CraBrowser(frame: container.bounds, url: nil, delegate: self, incognito: store.isIncognito(item: tabID),
+ profilePath: store.profilePath(item: tabID))
register(browser: browser, tabID: tabID)
return browser
}
@@ -102,18 +117,42 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
@discardableResult
private func register(browser: CraBrowser, tabID: UUID) -> TabRuntime {
browser.userInfo = tabID.uuidString
- let v = browser.containerView
+ let rt = TabRuntime(tabID: tabID, browser: browser)
+ if let t = store.item(tabID)?.tab, t.muted { browser.setAudioMuted(true) }
+ add(rt)
+ return rt
+ }
+
+ private func add(_ rt: TabRuntime) {
+ let v = rt.browser.containerView
v.frame = container.bounds
v.autoresizingMask = [.width, .height]
v.isHidden = true
container.addSubview(v)
- let rt = TabRuntime(tabID: tabID, browser: browser)
- runtimes[tabID] = rt
- byBrowser[ObjectIdentifier(browser)] = tabID
- if let t = store.item(tabID)?.tab, t.muted { browser.setAudioMuted(true) }
+ runtimes[rt.tabID] = rt
+ byBrowser[ObjectIdentifier(rt.browser)] = rt.tabID
// 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) }
+ if rt.browser.hostWindow != nil { delegate?.browserManagerPageWindowsChanged(focus: false) }
+ }
+
+ /// Gives up a tab's live page so another window can show it. Its DevTools close:
+ /// their window belongs to this one.
+ func release(_ tabID: UUID) -> TabRuntime? {
+ guard let rt = runtimes.removeValue(forKey: tabID) else { return nil }
+ byBrowser[ObjectIdentifier(rt.browser)] = nil
+ if rt.browser.hasDevTools { rt.browser.closeDevTools() }
+ devToolsViews[tabID] = nil
+ devToolsPlaceholders[tabID] = nil
+ devToolsDockedState[tabID] = nil
+ if visibleTabID == tabID { visibleTabID = nil }
+ visibleTabIDs.removeAll { $0 == tabID }
+ if let host = rt.hostWindow {
+ host.parent?.removeChildWindow(host)
+ host.orderOut(nil)
+ }
+ rt.browser.containerView.removeFromSuperview()
+ delegate?.browserManagerDevToolsChanged()
return rt
}
@@ -152,10 +191,51 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
visibleTabIDs = shown
visibleTabID = focused.flatMap { newSet.contains($0) ? $0 : nil } ?? shown.first
if focus, let f = visibleTabID, let rt = runtimes[f] { rt.browser.setFocused(true) }
+ for id in shown where !wasVisible.contains(id) { scheduleSnapshot(id) }
syncDevToolsVisibility()
delegate?.browserManagerPageWindowsChanged(focus: focus)
}
+ // MARK: Tab switcher thumbnails
+
+ /// Chromium renders nothing for a hidden page, so thumbnails are taken while a tab is
+ /// on screen: a moment after it appears or finishes loading, and when the switcher opens.
+ private func scheduleSnapshot(_ id: UUID, after delay: TimeInterval = 1) {
+ guard let rt = runtimes[id] else { return }
+ rt.snapshotWork?.cancel()
+ let work = DispatchWorkItem { [weak self] in self?.captureSnapshot(id) }
+ rt.snapshotWork = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work)
+ }
+
+ /// The visible viewport, cropped to the switcher's thumbnail shape from the top.
+ func captureSnapshot(_ id: UUID, completion: (() -> Void)? = nil) {
+ guard let rt = runtimes[id], visibleTabIDs.contains(id) else { completion?(); return }
+ let b = rt.browser
+ b.sendDevToolsMethod("Page.getLayoutMetrics", params: "{}") { result, _ in
+ guard let result, let m = try? JSONSerialization.jsonObject(with: Data(result.utf8)) as? [String: Any],
+ let vp = m["cssVisualViewport"] as? [String: Any],
+ let x = vp["pageX"] as? Double, let y = vp["pageY"] as? Double,
+ let w = vp["clientWidth"] as? Double, let h = vp["clientHeight"] as? Double, w > 0, h > 0 else {
+ DispatchQueue.main.async { completion?() }
+ return
+ }
+ let thumb = TabSwitcherMetrics.thumbnail
+ let aspect = Double(thumb.width / thumb.height)
+ let cw = min(w, h * aspect), ch = cw / aspect
+ let scale = min(1, Double(thumb.width) * 2 / cw)
+ let params = #"{"format":"jpeg","quality":80,"clip":{"x":\#(x + (w - cw) / 2),"y":\#(y),"width":\#(cw),"height":\#(ch),"scale":\#(scale)}}"#
+ b.sendDevToolsMethod("Page.captureScreenshot", params: params) { [weak self] shot, _ in
+ let image = shot.flatMap { try? JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any] }
+ .flatMap { $0["data"] as? String }.flatMap { Data(base64Encoded: $0) }.flatMap(NSImage.init(data:))
+ DispatchQueue.main.async {
+ if let image { self?.runtimes[id]?.snapshot = image }
+ completion?()
+ }
+ }
+ }
+ }
+
func browser(_ browser: CraBrowser, didCreateHostWindow window: NSWindow) {
delegate?.browserManagerPageWindowsChanged(focus: tabID(of: browser) == visibleTabID)
}
@@ -168,9 +248,18 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
rt.browser.close()
}
- /// Drop runtimes whose tabs no longer exist (archived, deleted).
+ /// Drop runtimes whose tabs no longer exist (archived, deleted). A page can't change
+ /// its Chromium profile: one whose tab moved to a space with another profile, or whose
+ /// space switched profiles, closes and loads its URL again there when shown.
func pruneMissingTabs() {
for id in runtimes.keys where store.item(id)?.isTab != true { unload(id) }
+ for (id, rt) in runtimes where store.item(id)?.isTab == true && !inRightProfile(rt) {
+ release(id)?.browser.close()
+ }
+ }
+
+ private func inRightProfile(_ rt: TabRuntime) -> Bool {
+ rt.browser.isIncognito || rt.browser.profilePath == store.profilePath(item: rt.tabID)
}
func closeAll() { for id in Array(runtimes.keys) { unload(id) } }
@@ -202,7 +291,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
/// Picture in Picture's "back to tab": select the tab, bring its window up
/// and put the video back in the page (also when the tab was already selected).
private func bringToFront(_ tabID: UUID) {
- store.selectTab(tabID)
+ store.selectTab(tabID, window: windowID)
container.window?.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
runtimes[tabID]?.browser.exitPictureInPicture()
@@ -250,6 +339,11 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
delegate?.browserManagerDidUpdate(id)
}
+ func browser(_ browser: CraBrowser, didChangeMediaCapture capturing: Bool) {
+ guard let id = tabID(of: browser) else { return }
+ delegate?.browserManagerDidUpdate(id)
+ }
+
func browser(_ browser: CraBrowser, didChangeURL url: String) {
guard let id = tabID(of: browser) else { return }
// Our own error page is a data: URL; keep the real address in the model.
@@ -261,6 +355,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
func browser(_ browser: CraBrowser, didChangeLoading loading: Bool, canGoBack: Bool, canGoForward: Bool) {
guard let id = tabID(of: browser) else { return }
if !loading { runtimes[id]?.progress = 0 }
+ if !loading { scheduleSnapshot(id) }
delegate?.browserManagerDidUpdate(id)
}
@@ -271,7 +366,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
func browser(_ browser: CraBrowser, didFinishLoadingURL url: String, title: String, statusCode: Int) {
- guard let id = tabID(of: browser) else { return }
+ guard let id = tabID(of: browser), !browser.isIncognito else { return }
store.recordVisit(url: url, title: title.isEmpty ? (store.item(id)?.tab?.savedTitle ?? "") : title)
}
@@ -279,7 +374,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
guard let id = tabID(of: browser), let tab = store.item(id)?.tab else { return }
let key = FaviconCache.key(for: tab.url) ?? tab.faviconKey
guard let key else { return }
- favicons.store(image, forKey: key)
+ favicons.store(image, forKey: key, persist: !browser.isIncognito)
if tab.faviconKey != key { store.updateTab(id, url: tab.url) }
}
@@ -310,7 +405,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
func browser(_ browser: CraBrowser, requestsNewTabWithURL url: String, inBackground background: Bool) {
- if url.hasPrefix("cra://") { delegate?.browserManagerOpenInternalURL(url); return }
+ // cra:// is Cra's scripting scheme (DevTools Protocol, key presses); a page must not drive it.
+ if url.lowercased().hasPrefix("cra:") { return }
let sourceSpace = tabID(of: browser).flatMap { store.spaceID(ofItem: $0) }
let parentIndex = tabID(of: browser).flatMap { id -> Int? in
guard let it = store.item(id), let p = it.parentID, store.rootContainer(of: id) != nil,
@@ -320,7 +416,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
// Links from a today tab open right below it (Arc); otherwise at the top.
let tab = store.createTab(url: url, in: sourceSpace, select: !background,
parent: parentIndex != nil ? store.item(tabID(of: browser)!)?.parentID : nil,
- index: parentIndex)
+ index: parentIndex, window: windowID)
if background {
store.markUnread(tab.id, true)
ensureRuntime(for: tab.id) // load it so the title and favicon fill in
@@ -328,9 +424,9 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
func browser(_ browser: CraBrowser, popupHostForURL url: String, inBackground background: Bool) -> CraBrowser? {
- if url.hasPrefix("cra://") { delegate?.browserManagerOpenInternalURL(url); return nil }
+ if url.lowercased().hasPrefix("cra:") { return nil }
let sourceSpace = tabID(of: browser).flatMap { store.spaceID(ofItem: $0) }
- let tab = store.createTab(url: url, in: sourceSpace, select: !background)
+ let tab = store.createTab(url: url, in: sourceSpace, select: !background, window: windowID)
if background { store.markUnread(tab.id, true) }
let host = makePopupHost(for: tab.id)
if !background { show(tab.id, focus: true) }
diff --git a/Sources/Cra/Services/DownloadHistory.swift b/Sources/Cra/Services/DownloadHistory.swift
new file mode 100644
index 0000000..e3aa47b
--- /dev/null
+++ b/Sources/Cra/Services/DownloadHistory.swift
@@ -0,0 +1,74 @@
+import AppKit
+import Observation
+import QuickLookThumbnailing
+
+/// Finished downloads, newest last, for the list Arc shows when you hover the Library
+/// button (its downloads tray). Kept in downloads.json; files deleted since drop out.
+@MainActor
+@Observable
+final class DownloadHistory {
+ static let shared = DownloadHistory()
+
+ struct Entry: Codable, Identifiable, Equatable {
+ let id: UUID
+ var path: String
+ var date: Date
+ }
+
+ /// Arc 1.170 listed every recent download it still had on disk (four, oldest at the
+ /// top); how many it shows at most was not observed.
+ static let listLimit = 5
+
+ private(set) var entries: [Entry]
+ /// Quick Look thumbnails by path, made on demand.
+ private(set) var thumbnails: [String: NSImage] = [:]
+ @ObservationIgnored private let file = JSONStore<[Entry]>("downloads.json")
+ @ObservationIgnored private var loading: Set<String> = []
+
+ private init() {
+ entries = file.load(or: { [] })
+ }
+
+ /// The hover list: newest downloads still on disk, oldest first.
+ var recent: [Entry] {
+ Array(entries.filter { FileManager.default.fileExists(atPath: $0.path) }.suffix(Self.listLimit))
+ }
+
+ @discardableResult
+ func add(path: String) -> Entry {
+ let entry = Entry(id: UUID(), path: path, date: Date())
+ entries.append(entry)
+ if entries.count > 200 { entries.removeFirst(entries.count - 200) }
+ file.save(entries)
+ return entry
+ }
+
+ /// A renamed (or reverted) file keeps its place in the list.
+ func move(from old: String, to new: String) {
+ guard let i = entries.lastIndex(where: { $0.path == old }) else { return }
+ entries[i].path = new
+ thumbnails[new] = thumbnails.removeValue(forKey: old)
+ file.save(entries)
+ }
+
+ func thumbnail(for path: String) -> NSImage? {
+ if let image = thumbnails[path] { return image }
+ loadThumbnail(path)
+ return nil
+ }
+
+ private func loadThumbnail(_ path: String) {
+ guard !loading.contains(path) else { return }
+ loading.insert(path)
+ let request = QLThumbnailGenerator.Request(fileAt: URL(fileURLWithPath: path), size: CGSize(width: 40, height: 40),
+ scale: NSScreen.main?.backingScaleFactor ?? 2, representationTypes: .thumbnail)
+ QLThumbnailGenerator.shared.generateBestRepresentation(for: request) { [weak self] thumbnail, _ in
+ let image = thumbnail?.nsImage
+ DispatchQueue.main.async {
+ guard let self else { return }
+ self.loading.remove(path)
+ self.thumbnails[path] = image ?? NSWorkspace.shared.icon(forFile: path)
+ }
+ }
+ }
+}
diff --git a/Sources/Cra/Services/FaviconCache.swift b/Sources/Cra/Services/FaviconCache.swift
index ab72c45..b745e16 100644
--- a/Sources/Cra/Services/FaviconCache.swift
+++ b/Sources/Cra/Services/FaviconCache.swift
@@ -129,8 +129,10 @@ final class FaviconCache {
try? FileManager.default.removeItem(at: AppPaths.favicons.appendingPathComponent(Self.fileName(key)))
}
- func store(_ image: NSImage, forKey key: String) {
+ /// `persist` false keeps the icon in memory only (incognito pages).
+ func store(_ image: NSImage, forKey key: String, persist: Bool = true) {
images[key] = image
+ guard persist else { return }
let file = AppPaths.favicons.appendingPathComponent(Self.fileName(key))
DispatchQueue.global(qos: .utility).async {
guard let tiff = image.tiffRepresentation,
diff --git a/Sources/Cra/Services/Import/CredentialImport.swift b/Sources/Cra/Services/Import/CredentialImport.swift
index c84732f..9cc07f3 100644
--- a/Sources/Cra/Services/Import/CredentialImport.swift
+++ b/Sources/Cra/Services/Import/CredentialImport.swift
@@ -95,25 +95,27 @@ enum ChromiumCrypto {
return key
}
- /// Cra runs Chromium with --use-mock-keychain, whose Keychain secret is fixed.
- static let craKey = key(fromSecret: "mock_password")
-
private static let iv = [UInt8](repeating: 0x20, count: kCCBlockSizeAES128)
+ /// nil for a wrong key too: CommonCrypto strips PKCS#7 padding without checking it,
+ /// so the padding is checked here (a wrong key passes about once in 256).
static func decrypt(_ blob: Data, key: Data) -> Data? {
- guard blob.count > 3, blob.prefix(3) == Data("v10".utf8) else { return nil }
- return crypt(CCOperation(kCCDecrypt), Data(blob.dropFirst(3)), key: key)
+ guard blob.count > 3, blob.prefix(3) == Data("v10".utf8), (blob.count - 3) % kCCBlockSizeAES128 == 0,
+ let padded = crypt(CCOperation(kCCDecrypt), Data(blob.dropFirst(3)), key: key, options: 0),
+ let n = padded.last.map(Int.init), (1...kCCBlockSizeAES128).contains(n), padded.count >= n,
+ padded.suffix(n).allSatisfy({ Int($0) == n }) else { return nil }
+ return Data(padded.dropLast(n))
}
- static func encrypt(_ plain: Data, key: Data = craKey) -> Data {
- Data("v10".utf8) + (crypt(CCOperation(kCCEncrypt), plain, key: key) ?? Data())
+ static func encrypt(_ plain: Data, key: Data) -> Data {
+ Data("v10".utf8) + (crypt(CCOperation(kCCEncrypt), plain, key: key, options: CCOptions(kCCOptionPKCS7Padding)) ?? Data())
}
- private static func crypt(_ op: CCOperation, _ input: Data, key: Data) -> Data? {
+ private static func crypt(_ op: CCOperation, _ input: Data, key: Data, options: CCOptions) -> Data? {
var out = Data(count: input.count + kCCBlockSizeAES128)
var moved = 0
let status = out.withUnsafeMutableBytes { o in input.withUnsafeBytes { i in key.withUnsafeBytes { k in
- CCCrypt(op, CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), k.baseAddress, key.count, iv,
+ CCCrypt(op, CCAlgorithm(kCCAlgorithmAES), options, k.baseAddress, key.count, iv,
i.baseAddress, input.count, o.baseAddress, o.count, &moved)
} } }
return status == kCCSuccess ? out.prefix(moved) : nil
@@ -224,8 +226,8 @@ enum SQLite {
// MARK: - Staging and applying
enum CredentialImport {
- /// Staged rows, already encrypted for Cra's profile, so the file is no
- /// easier to read than the databases it feeds.
+ /// Staged rows, already encrypted for Cra's profile (SafeStorage.key), so the
+ /// file is no easier to read than the databases it feeds.
private struct Pending: Codable {
struct Cookie: Codable { var c: ImportedCookie; var encrypted: Data }
struct Login: Codable { var l: ImportedLogin; var encrypted: Data }
@@ -240,17 +242,22 @@ enum CredentialImport {
@discardableResult
static func stage(_ creds: ImportedCredentials) -> Bool {
guard !creds.isEmpty else { return true }
+ guard let key = SafeStorage.key else { return false }
var pending = (try? Data(contentsOf: pendingFile)).flatMap { try? JSONDecoder().decode(Pending.self, from: $0) } ?? Pending()
for var c in creds.cookies {
- let encrypted = ChromiumCrypto.encrypt(Data(c.value.utf8))
+ let encrypted = ChromiumCrypto.encrypt(Data(c.value.utf8), key: key)
c.value = ""
pending.cookies.append(.init(c: c, encrypted: encrypted))
}
for var l in creds.logins {
- let encrypted = ChromiumCrypto.encrypt(Data(l.password.utf8))
+ let encrypted = ChromiumCrypto.encrypt(Data(l.password.utf8), key: key)
l.password = ""
pending.logins.append(.init(l: l, encrypted: encrypted))
}
+ return write(pending)
+ }
+
+ private static func write(_ pending: Pending) -> Bool {
guard let data = try? JSONEncoder().encode(pending) else { return false }
do {
try data.write(to: pendingFile, options: [.atomic, .completeFileProtection])
@@ -261,12 +268,31 @@ enum CredentialImport {
}
}
+ /// Rows staged before the profile moved to the Keychain secret (SafeStorage). Rows
+ /// that don't decrypt with `old` (already moved by a run that failed later) stay.
+ static func reencryptPending(from old: Data, to new: Data) -> Bool {
+ guard let data = try? Data(contentsOf: pendingFile) else { return true }
+ guard var pending = try? JSONDecoder().decode(Pending.self, from: data) else { return false }
+ for i in pending.cookies.indices {
+ if let plain = ChromiumCrypto.decrypt(pending.cookies[i].encrypted, key: old) {
+ pending.cookies[i].encrypted = ChromiumCrypto.encrypt(plain, key: new)
+ }
+ }
+ for i in pending.logins.indices {
+ if let plain = ChromiumCrypto.decrypt(pending.logins[i].encrypted, key: old) {
+ pending.logins[i].encrypted = ChromiumCrypto.encrypt(plain, key: new)
+ }
+ }
+ return write(pending)
+ }
+
/// Called from main.swift before Chromium starts. Leaves the file in place
/// when the profile's databases are missing (no first run yet) or busy.
static func applyPending(profileDir: URL) {
guard let data = try? Data(contentsOf: pendingFile),
- let pending = try? JSONDecoder().decode(Pending.self, from: data) else { return }
- let cookiesOK = pending.cookies.isEmpty || insertCookies(pending.cookies, into: profileDir.appendingPathComponent("Cookies"))
+ let pending = try? JSONDecoder().decode(Pending.self, from: data),
+ let key = SafeStorage.key else { return }
+ let cookiesOK = pending.cookies.isEmpty || insertCookies(pending.cookies, into: profileDir.appendingPathComponent("Cookies"), key: key)
let loginsOK = pending.logins.isEmpty || insertLogins(pending.logins, into: profileDir.appendingPathComponent("Login Data"))
if cookiesOK && loginsOK {
try? FileManager.default.removeItem(at: pendingFile)
@@ -309,7 +335,7 @@ enum CredentialImport {
return false
}
- private static func insertCookies(_ cookies: [Pending.Cookie], into url: URL) -> Bool {
+ private static func insertCookies(_ cookies: [Pending.Cookie], into url: URL, key: Data) -> Bool {
guard let db = open(url) else { return false }
defer { sqlite3_close(db) }
let version = Int(SQLite.rows(db, "SELECT value FROM meta WHERE key = 'version'").first?["value"] as? String ?? "") ?? 0
@@ -317,8 +343,8 @@ enum CredentialImport {
for p in cookies {
let c = p.c
var encrypted = p.encrypted
- if version >= 24, let plain = ChromiumCrypto.decrypt(encrypted, key: ChromiumCrypto.craKey) {
- encrypted = ChromiumCrypto.encrypt(ChromiumCrypto.hostDigest(c.host) + plain)
+ if version >= 24, let plain = ChromiumCrypto.decrypt(encrypted, key: key) {
+ encrypted = ChromiumCrypto.encrypt(ChromiumCrypto.hostDigest(c.host) + plain, key: key)
}
let ok = insert(db, table: "cookies", values: [
"creation_utc": c.created, "host_key": c.host, "top_frame_site_key": "", "name": c.name, "value": "",
diff --git a/Sources/Cra/Services/Persistence.swift b/Sources/Cra/Services/Persistence.swift
index f265224..4b43ec0 100644
--- a/Sources/Cra/Services/Persistence.swift
+++ b/Sources/Cra/Services/Persistence.swift
@@ -1,5 +1,25 @@
import Foundation
+/// Folders of deleted profiles, removed before Chromium starts (it keeps a loaded
+/// profile's files open for the rest of the session).
+enum ProfileCleanup {
+ private static var file: JSONStore<[String]> { JSONStore("deleted-profiles.json") }
+
+ static func schedule(_ directoryName: String) {
+ file.saveNow(Array(Set(file.load(or: { [] }) + [directoryName])))
+ }
+
+ /// Call before Chromium initializes.
+ static func run() {
+ let names = file.load(or: { [] })
+ guard !names.isEmpty else { return }
+ for name in names where name.hasPrefix("Profile ") {
+ try? FileManager.default.removeItem(at: AppPaths.chromiumCache.appendingPathComponent(name, isDirectory: true))
+ }
+ file.saveNow([])
+ }
+}
+
enum AppPaths {
static let supportDir: URL = {
// CRA_DATA_DIR runs a second, independent Cra (testing next to the installed one).
diff --git a/Sources/Cra/Services/SafeStorage.swift b/Sources/Cra/Services/SafeStorage.swift
new file mode 100644
index 0000000..85588eb
--- /dev/null
+++ b/Sources/Cra/Services/SafeStorage.swift
@@ -0,0 +1,182 @@
+import Foundation
+import Security
+import SQLite3
+
+/// Chromium encrypts cookies, saved passwords, card numbers and search engine hashes
+/// ("v10" values, see ChromiumCrypto) with a key derived from the secret in the login
+/// Keychain item "Cra Safe Storage" (account "Chromium"). Stock Chromium calls it
+/// "Chromium Safe Storage", like every Chromium-based app without its own name; CEF is
+/// built with scripts/cef-patches/keychain-service-name.patch (or patched by
+/// scripts/fetch-cef.sh) so Cra's secret is its own.
+///
+/// Cra used to start Chromium with --use-mock-keychain, whose secret is the public
+/// constant "mock_password": anyone who could read the profile could decrypt it. The
+/// first launch of a signed Cra re-encrypts such a profile with the Keychain secret
+/// before Chromium opens it. Unsigned dev builds keep the mock keychain on profiles that
+/// never used the Keychain: macOS ties the item to the app's signature, which changes
+/// with every ad-hoc rebuild, and would ask for the login password each time.
+enum SafeStorage {
+ static let service = "Cra Safe Storage"
+ /// Chromium's default, left alone: the 156 framework builds it from instruction
+ /// immediates rather than a string the patch could change.
+ static let account = "Chromium"
+
+ /// Whether Chromium reads the Keychain item (false: --use-mock-keychain).
+ private(set) static var usesKeychain = false
+ /// The key Cra's profile is encrypted with, for the importer. nil when the Keychain
+ /// did not hand out the secret.
+ private(set) static var key: Data?
+
+ private static let mockKey = ChromiumCrypto.key(fromSecret: "mock_password")
+ /// Present once the profile is encrypted with the Keychain secret.
+ private static var marker: URL { AppPaths.chromiumCache.appendingPathComponent("Cra Safe Storage") }
+ private static let metaKey = "cra_safe_storage"
+ private static let databases = ["Cookies", "Extension Cookies", "Safe Browsing Cookies", "Login Data",
+ "Login Data For Account", "Web Data", "Account Web Data"]
+
+ /// Called from main.swift before Chromium starts. Only migrates when `profileIsFree`
+ /// (no other Cra has the databases open).
+ static func prepare(profileIsFree: Bool) {
+ if FileManager.default.fileExists(atPath: marker.path) {
+ usesKeychain = true
+ key = keychainSecret().map(ChromiumCrypto.key(fromSecret:))
+ if key == nil { NSLog("Cra: no secret from the \(service) Keychain item") }
+ return
+ }
+ key = mockKey
+ guard profileIsFree, isSignedByTeam, frameworkUsesCraItem, let secret = keychainSecret() else { return }
+ let newKey = ChromiumCrypto.key(fromSecret: secret)
+ guard migrate(to: newKey) else { return }
+ try? FileManager.default.createDirectory(at: AppPaths.chromiumCache, withIntermediateDirectories: true)
+ guard FileManager.default.createFile(atPath: marker.path, contents: Data()) else { return }
+ usesKeychain = true
+ key = newKey
+ }
+
+ /// The item's secret, made the way Chromium makes one (16 random bytes, base64) when
+ /// there is none yet. Cra creates it, so macOS lets Cra read it without asking.
+ private static func keychainSecret() -> String? {
+ let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,
+ kSecAttrAccount as String: account, kSecReturnData as String: true,
+ kSecMatchLimit as String: kSecMatchLimitOne]
+ var result: AnyObject?
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
+ if status == errSecSuccess, let data = result as? Data { return String(data: data, encoding: .utf8) }
+ guard status == errSecItemNotFound else {
+ NSLog("Cra: reading the \(service) Keychain item failed (\(status))")
+ return nil
+ }
+ var bytes = [UInt8](repeating: 0, count: 16)
+ guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { return nil }
+ let secret = Data(bytes).base64EncodedString()
+ let item: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,
+ kSecAttrAccount as String: account, kSecAttrLabel as String: service,
+ kSecValueData as String: Data(secret.utf8)]
+ let added = SecItemAdd(item as CFDictionary, nil)
+ guard added == errSecSuccess else {
+ NSLog("Cra: creating the \(service) Keychain item failed (\(added))")
+ return nil
+ }
+ return secret
+ }
+
+ /// Signed with a Developer ID (a team), so the Keychain keeps trusting Cra across updates.
+ private static var isSignedByTeam: Bool {
+ var code: SecCode?
+ var staticCode: SecStaticCode?
+ var info: CFDictionary?
+ guard SecCodeCopySelf([], &code) == errSecSuccess, let code,
+ SecCodeCopyStaticCode(code, [], &staticCode) == errSecSuccess, let staticCode,
+ SecCodeCopySigningInformation(staticCode, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess
+ else { return false }
+ return (info as? [String: Any])?[kSecCodeInfoTeamIdentifier as String] is String
+ }
+
+ /// A framework that still looks for "Chromium Safe Storage" would make its own secret
+ /// and lose everything this migration re-encrypts.
+ private static var frameworkUsesCraItem: Bool {
+ guard let url = Bundle.main.privateFrameworksURL?
+ .appendingPathComponent("Chromium Embedded Framework.framework/Chromium Embedded Framework"),
+ let data = try? Data(contentsOf: url, options: .alwaysMapped) else { return false }
+ let name = Array("\(service)\0".utf8)
+ let found = data.withUnsafeBytes { memmem($0.baseAddress, $0.count, name, name.count) != nil }
+ if !found { NSLog("Cra: Chromium Embedded Framework does not use \(service); run scripts/fetch-cef.sh") }
+ return found
+ }
+
+ /// Re-encrypts every mock-keychain value in every profile and the import's staged
+ /// rows. All databases commit together or none does. Each one notes it in its meta
+ /// table in the same transaction, so a later run never encrypts a value twice (a
+ /// wrong key "decrypts" about once in 256, which tells nothing).
+ private static func migrate(to newKey: Data) -> Bool {
+ let fm = FileManager.default
+ let root = AppPaths.chromiumCache
+ let profiles = ((try? fm.contentsOfDirectory(atPath: root.path)) ?? []).filter { $0 == "Default" || $0.hasPrefix("Profile ") }
+ var open: [OpaquePointer] = []
+ defer { open.forEach { sqlite3_close($0) } }
+ var count = 0
+ for profile in profiles {
+ for name in databases {
+ let path = root.appendingPathComponent(profile).appendingPathComponent(name).path
+ guard fm.fileExists(atPath: path) else { continue }
+ var db: OpaquePointer?
+ guard sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE, nil) == SQLITE_OK, let db else {
+ sqlite3_close(db)
+ NSLog("Cra: could not open \(profile)/\(name) to re-encrypt it")
+ return false
+ }
+ sqlite3_busy_timeout(db, 500)
+ let hasMeta = !SQLite.rows(db, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").isEmpty
+ if hasMeta, !SQLite.rows(db, "SELECT 1 FROM meta WHERE key = '\(metaKey)'").isEmpty {
+ sqlite3_close(db)
+ continue
+ }
+ open.append(db)
+ guard sqlite3_exec(db, "BEGIN IMMEDIATE", nil, nil, nil) == SQLITE_OK,
+ let n = reencrypt(db, from: mockKey, to: newKey),
+ !hasMeta || sqlite3_exec(db, "INSERT INTO meta (key, value) VALUES ('\(metaKey)', 'keychain')", nil, nil, nil) == SQLITE_OK else {
+ NSLog("Cra: could not re-encrypt \(profile)/\(name)")
+ open.forEach { sqlite3_exec($0, "ROLLBACK", nil, nil, nil) }
+ return false
+ }
+ count += n
+ }
+ }
+ guard CredentialImport.reencryptPending(from: mockKey, to: newKey) else {
+ open.forEach { sqlite3_exec($0, "ROLLBACK", nil, nil, nil) }
+ return false
+ }
+ for db in open where sqlite3_exec(db, "COMMIT", nil, nil, nil) != SQLITE_OK {
+ NSLog("Cra: committing re-encrypted values failed: \(String(cString: sqlite3_errmsg(db)))")
+ return false
+ }
+ NSLog("Cra: moved \(count) encrypted values to the \(service) Keychain item")
+ return true
+ }
+
+ /// Every BLOB that decrypts with `old`, in every table. Returns the number changed.
+ private static func reencrypt(_ db: OpaquePointer, from old: Data, to new: Data) -> Int? {
+ var changed = 0
+ let tables = SQLite.rows(db, "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
+ .compactMap { $0["name"] as? String }
+ for table in tables {
+ let columns = SQLite.rows(db, "SELECT name FROM pragma_table_info('\(table)')").compactMap { $0["name"] as? String }
+ for column in columns {
+ // WITHOUT ROWID tables have no rowid; Chromium keeps no encrypted values in those.
+ let rows = SQLite.rows(db, "SELECT rowid AS r, \"\(column)\" AS v FROM \"\(table)\" WHERE typeof(\"\(column)\") = 'blob' AND substr(\"\(column)\", 1, 3) = X'763130'")
+ for row in rows {
+ guard let rowid = row["r"] as? Int64, let blob = row["v"] as? Data,
+ let plain = ChromiumCrypto.decrypt(blob, key: old) else { continue }
+ var stmt: OpaquePointer?
+ guard sqlite3_prepare_v2(db, "UPDATE \"\(table)\" SET \"\(column)\" = ? WHERE rowid = ?", -1, &stmt, nil) == SQLITE_OK else { return nil }
+ SQLite.bind(stmt, [ChromiumCrypto.encrypt(plain, key: new), rowid])
+ let done = sqlite3_step(stmt) == SQLITE_DONE
+ sqlite3_finalize(stmt)
+ guard done else { return nil }
+ changed += 1
+ }
+ }
+ }
+ return changed
+ }
+}
diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swift
index aa2e477..03707e3 100644
--- a/Sources/Cra/Services/SidebarStore.swift
+++ b/Sources/Cra/Services/SidebarStore.swift
@@ -11,14 +11,26 @@ final class SidebarStore {
private(set) var spaces: [UUID: Space] = [:]
private(set) var spaceOrder: [UUID] = []
+ /// Profiles besides Default, in the order they were made.
+ private(set) var profiles: [BrowserProfile] = []
private(set) var items: [UUID: SidebarItem] = [:]
private(set) var archive: [ArchivedItem] = []
- var prefs = WindowPrefs() { didSet { prefsStore.save(prefs) } }
+ var prefs = WindowPrefs() { didSet { prefsStore.save(prefs.withoutIncognito) } }
var settings = AppSettings() { didSet { settingsStore.save(settings) } }
private(set) var history: [String: HistoryEntry] = [:]
private(set) var ranking = RankingData()
/// Bumped on every structural change; cheap way for AppKit code to observe.
private(set) var revision = 0
+ /// The browser window that menu commands, new tabs and the command bar act on:
+ /// the one the user is in (AppDelegate follows the key window).
+ @ObservationIgnored var activeWindowID = UUID() {
+ didSet { if !window(activeWindowID).isIncognito { lastNormalWindowID = activeWindowID } }
+ }
+ /// The normal window in use last: where links from other apps and the Library go
+ /// while an incognito window is in front.
+ @ObservationIgnored private(set) var lastNormalWindowID = UUID()
+ /// Spaces of incognito windows. Not in `spaceOrder`, never saved.
+ private(set) var incognitoSpaceIDs: Set<UUID> = []
// MARK: Persistence
@@ -32,6 +44,7 @@ final class SidebarStore {
init() {
let doc = sidebarFile.load(or: SidebarDocument.fresh)
for s in doc.spaces { spaces[s.id] = s }
+ profiles = doc.profiles ?? []
spaceOrder = doc.spaceOrder.filter { spaces[$0] != nil }
for s in doc.spaces where !spaceOrder.contains(s.id) { spaceOrder.append(s.id) }
for it in doc.items { items[it.id] = it }
@@ -41,10 +54,14 @@ final class SidebarStore {
for h in historyFile.load(or: { [] }) { history[h.url] = h }
ranking = rankingFile.load(or: { RankingData() })
repair()
- if prefs.focusedSpaceID == nil || spaces[prefs.focusedSpaceID!] == nil {
- prefs.focusedSpaceID = spaceOrder.first
+ if prefs.windows.isEmpty { prefs.windows = [WindowSession()] }
+ for i in prefs.windows.indices where prefs.windows[i].focusedSpaceID.flatMap({ spaces[$0] }) == nil {
+ prefs.windows[i].focusedSpaceID = spaceOrder.first
}
+ activeWindowID = prefs.windows[0].id
+ lastNormalWindowID = activeWindowID
splitSharedFavorites(doc.favoritesContainerID)
+ resolveWindowConflicts(winner: activeWindowID)
}
/// Make sure every space has its containers and no item points at a
@@ -63,8 +80,9 @@ final class SidebarStore {
let c = SidebarItem.container(.today(spaceID: id), id: space.todayContainerID)
items[c.id] = c
}
+ // A profile that is gone: the space falls back to Default (Arc does the same).
+ if let p = space.profileID, !profiles.contains(where: { $0.id == p }) { space.profileID = nil }
spaces[id] = space
- _ = space
}
if spaces.isEmpty {
let doc = SidebarDocument.fresh()
@@ -106,7 +124,9 @@ final class SidebarStore {
}
}
// A favorite open in this space stays open: it is now this space's copy.
- if let sel = prefs.selectedTabPerSpace[sid], let copy = copies[sel] { prefs.selectedTabPerSpace[sid] = copy }
+ for i in prefs.windows.indices {
+ if let sel = prefs.windows[i].selectedTabPerSpace[sid], let copy = copies[sel] { prefs.windows[i].selectedTabPerSpace[sid] = copy }
+ }
for (old, new) in copies where prefs.expandedFolders.contains(old) { prefs.expandedFolders.insert(new) }
}
items[sharedID] = nil
@@ -126,33 +146,136 @@ final class SidebarStore {
}
func save() {
- let doc = SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: spaceOrder.compactMap { spaces[$0] },
- items: Array(items.values))
- sidebarFile.save(doc)
+ sidebarFile.save(document)
archiveFile.save(archive)
}
func saveAll() {
- let doc = SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: spaceOrder.compactMap { spaces[$0] },
- items: Array(items.values))
- sidebarFile.saveNow(doc)
+ sidebarFile.saveNow(document)
archiveFile.saveNow(archive)
- prefsStore.saveNow(prefs)
+ prefsStore.saveNow(prefs.withoutIncognito)
settingsStore.saveNow(settings)
historyFile.saveNow(Array(history.values))
rankingFile.saveNow(ranking)
}
private func touch() {
+ resolveWindowConflicts(winner: activeWindowID)
revision &+= 1
save()
}
+ // MARK: Windows
+
+ private func windowIndex(_ id: UUID?) -> Int {
+ prefs.windows.firstIndex { $0.id == (id ?? activeWindowID) } ?? prefs.windows.firstIndex { $0.id == activeWindowID } ?? 0
+ }
+
+ /// A window's state; an unknown id (a window that is gone) reads as the active window.
+ func window(_ id: UUID? = nil) -> WindowSession { prefs.windows[windowIndex(id)] }
+
+ /// No-op for a window that is gone.
+ func updateWindow(_ id: UUID?, _ change: (inout WindowSession) -> Void) {
+ guard let i = prefs.windows.firstIndex(where: { $0.id == (id ?? activeWindowID) }) else { return }
+ var w = prefs.windows[i]
+ change(&w)
+ if w != prefs.windows[i] { prefs.windows[i] = w }
+ }
+
+ /// A new window on `spaceID` with nothing open yet.
+ func addWindow(spaceID: UUID, frame: String?) -> WindowSession {
+ let w = WindowSession(focusedSpaceID: spaceID, frame: frame)
+ prefs.windows.append(w)
+ return w
+ }
+
+ /// The last window is never removed: closing it only hides it. An incognito
+ /// window's tabs go with it (not to the Library).
+ func removeWindow(_ id: UUID) {
+ guard prefs.windows.count > 1, let gone = prefs.windows.first(where: { $0.id == id }) else { return }
+ prefs.windows.removeAll { $0.id == id }
+ if activeWindowID == id { activeWindowID = prefs.windows.first { !$0.isIncognito }?.id ?? prefs.windows[0].id }
+ if gone.isIncognito, let sid = gone.focusedSpaceID, let space = spaces[sid] {
+ var ids = Set<UUID>()
+ collectSubtree(of: space, into: &ids)
+ for i in ids { items[i] = nil }
+ spaces[sid] = nil
+ incognitoSpaceIDs.remove(sid)
+ revision &+= 1
+ }
+ }
+
+ /// Arc's New Incognito Window: a window with a space of its own whose tabs load
+ /// in an off-the-record profile and are never written anywhere.
+ func addIncognitoWindow(frame: String?) -> WindowSession {
+ let id = UUID()
+ let favorites = SidebarItem.container(.favorites(spaceID: id))
+ let pinned = SidebarItem.container(.pinned(spaceID: id))
+ let today = SidebarItem.container(.today(spaceID: id))
+ for c in [favorites, pinned, today] { items[c.id] = c }
+ spaces[id] = Space(id: id, title: "Incognito", emoji: "🕶️", theme: .incognito, favoritesContainerID: favorites.id,
+ pinnedContainerID: pinned.id, todayContainerID: today.id, createdAt: Date())
+ incognitoSpaceIDs.insert(id)
+ let w = WindowSession(focusedSpaceID: id, frame: frame, isIncognito: true)
+ prefs.windows.append(w)
+ return w
+ }
+
+ func isIncognito(space id: UUID?) -> Bool { id.map(incognitoSpaceIDs.contains) ?? false }
+ func isIncognito(item id: UUID) -> Bool { isIncognito(space: spaceID(ofItem: id)) }
+
+ /// The spaces a window pages between: an incognito window has only its own.
+ func pagedSpaces(window id: UUID?) -> [Space] {
+ let w = window(id)
+ if w.isIncognito, let s = w.focusedSpaceID.flatMap({ spaces[$0] }) { return [s] }
+ return orderedSpaces
+ }
+
+ /// The tabs a window may show and the command bar may offer there: its own
+ /// incognito tabs, or every normal tab.
+ func profileTabs(window id: UUID?) -> [SidebarItem] {
+ let sid = focusedSpaceID(window: id)
+ if isIncognito(space: sid), let s = spaces[sid] {
+ return tabs(under: s.favoritesContainerID) + tabs(under: s.pinnedContainerID) + tabs(under: s.todayContainerID)
+ }
+ return allTabs().filter { !isIncognito(item: $0.id) }
+ }
+
+ private func collectSubtree(of space: Space, into ids: inout Set<UUID>) {
+ func walk(_ id: UUID) {
+ ids.insert(id)
+ for c in items[id]?.children ?? [] { walk(c) }
+ }
+ for c in [space.favoritesContainerID, space.pinnedContainerID, space.todayContainerID] { walk(c) }
+ }
+
+ /// A page is one Chromium browser, so it is on screen in one window at a time:
+ /// when two windows would show the same tab, the winner keeps it and the other
+ /// window drops its open tab in that space (it shows the empty space instead).
+ private func resolveWindowConflicts(winner: UUID, wins: Bool = true) {
+ guard prefs.windows.count > 1 else { return }
+ let me = prefs.windows.filter { $0.id == winner }, others = prefs.windows.filter { $0.id != winner }
+ var claimed = Set<UUID>()
+ for w in wins ? me + others : others + me {
+ let sid = focusedSpaceID(window: w.id)
+ let panes = visiblePaneTabIDs(in: sid, window: w.id)
+ if claimed.isDisjoint(with: panes) {
+ claimed.formUnion(panes)
+ } else {
+ updateWindow(w.id) { $0.selectedTabPerSpace[sid] = nil }
+ }
+ }
+ }
+
// MARK: Lookup
var orderedSpaces: [Space] { spaceOrder.compactMap { spaces[$0] } }
- var focusedSpaceID: UUID { prefs.focusedSpaceID ?? spaceOrder.first! }
- var focusedSpace: Space { spaces[focusedSpaceID] ?? orderedSpaces.first! }
+ func focusedSpaceID(window id: UUID?) -> UUID {
+ window(id).focusedSpaceID.flatMap { spaces[$0] != nil ? $0 : nil } ?? spaceOrder.first!
+ }
+ func focusedSpace(window id: UUID?) -> Space { spaces[focusedSpaceID(window: id)] ?? orderedSpaces.first! }
+ var focusedSpaceID: UUID { focusedSpaceID(window: nil) }
+ var focusedSpace: Space { focusedSpace(window: nil) }
func item(_ id: UUID) -> SidebarItem? { items[id] }
func space(_ id: UUID) -> Space? { spaces[id] }
@@ -192,9 +315,9 @@ final class SidebarStore {
/// The top-level pinned rows a space's list draws. Collapsed, only the
/// pinned item holding the open tab stays.
- func listedPinnedItems(in space: Space) -> [SidebarItem] {
+ func listedPinnedItems(in space: Space, window: UUID? = nil) -> [SidebarItem] {
guard isPinnedCollapsed(space.id) else { return children(of: space.pinnedContainerID) }
- let selected = selectedTabID(in: space.id).flatMap { splitContaining($0) ?? item($0) }
+ let selected = selectedTabID(in: space.id, window: window).flatMap { splitContaining($0) ?? item($0) }
return selected.flatMap { rootContainer(of: $0.id) == .pinned(spaceID: space.id) ? [$0] : nil } ?? []
}
@@ -232,42 +355,53 @@ final class SidebarStore {
return false
}
- func selectedTabID(in spaceID: UUID) -> UUID? {
- guard let id = prefs.selectedTabPerSpace[spaceID], items[id]?.isTab == true else { return nil }
+ func selectedTabID(in spaceID: UUID, window: UUID? = nil) -> UUID? {
+ guard let id = self.window(window).selectedTabPerSpace[spaceID], items[id]?.isTab == true else { return nil }
return id
}
- var selectedTabID: UUID? { selectedTabID(in: focusedSpaceID) }
- var selectedTab: SidebarItem? { selectedTabID.flatMap { items[$0] } }
+ func selectedTabID(window: UUID?) -> UUID? { selectedTabID(in: focusedSpaceID(window: window), window: window) }
+ func selectedTab(window: UUID?) -> SidebarItem? { selectedTabID(window: window).flatMap { items[$0] } }
+ var selectedTabID: UUID? { selectedTabID(window: nil) }
+ var selectedTab: SidebarItem? { selectedTab(window: nil) }
// MARK: Tabs
@discardableResult
func createTab(url: String, title: String = "", in spaceID: UUID? = nil, pinned: Bool = false,
- select: Bool = true, parent: UUID? = nil, index: Int? = nil) -> SidebarItem {
- let sid = spaceID ?? focusedSpaceID
- let space = spaces[sid] ?? focusedSpace
+ select: Bool = true, parent: UUID? = nil, index: Int? = nil, window: UUID? = nil) -> SidebarItem {
+ let sid = spaceID ?? focusedSpaceID(window: window)
+ let space = spaces[sid] ?? focusedSpace(window: window)
let parentID = parent ?? (pinned ? space.pinnedContainerID : space.todayContainerID)
var tab = SidebarItem.tab(url, title: title, parent: parentID)
- tab.data = .tab({ var t = TabData(url: url, title: title); t.activeTabBeforeCreationID = selectedTabID(in: sid); return t }())
+ tab.data = .tab({ var t = TabData(url: url, title: title); t.activeTabBeforeCreationID = selectedTabID(in: sid, window: window); return t }())
tab.isUnread = !select
items[tab.id] = tab
var p = items[parentID]!
let at = index ?? (settings.newTabsAtTop && !pinned ? 0 : p.children.count)
p.children.insert(tab.id, at: min(max(0, at), p.children.count))
items[parentID] = p
- if select { selectTab(tab.id) } else { touch() }
+ if select { selectTab(tab.id, window: window) } else { touch() }
return tab
}
- func selectTab(_ id: UUID?) {
+ func selectTab(_ id: UUID?, window: UUID? = nil) {
+ var w = self.window(window).id
+ // A normal tab picked while an incognito window is in front (a link from another
+ // app, the Library) opens in the last normal window.
+ if window == nil, let id, self.window(w).isIncognito, !isIncognito(item: id) { w = lastNormalWindowID }
+ let focused = focusedSpaceID(window: w)
guard let id, let it = items[id], it.isTab else {
- prefs.selectedTabPerSpace[focusedSpaceID] = nil
+ updateWindow(w) { $0.selectedTabPerSpace[focused] = nil }
touch()
return
}
- let sid = spaceID(ofItem: id) ?? focusedSpaceID
- if sid != focusedSpaceID { prefs.focusedSpaceID = sid }
- prefs.selectedTabPerSpace[sid] = id
+ let sid = spaceID(ofItem: id) ?? focused
+ // Incognito pages stay in their own window; normal tabs never open in one.
+ guard self.window(w).isIncognito ? sid == focused : !isIncognito(space: sid) else { return }
+ updateWindow(w) {
+ $0.focusedSpaceID = sid
+ $0.selectedTabPerSpace[sid] = id
+ }
var updated = it
updated.isUnread = false
if var t = updated.tab { t.timeLastActiveAt = Date(); updated.data = .tab(t) }
@@ -279,11 +413,14 @@ final class SidebarStore {
split.data = .split(s)
items[p] = split
}
- var dates = ranking.recentlySwitchedToTabs[id] ?? []
- dates.append(Date())
- if dates.count > 10 { dates.removeFirst(dates.count - 10) }
- ranking.recentlySwitchedToTabs[id] = dates
- rankingFile.save(ranking)
+ if !isIncognito(space: sid) {
+ var dates = ranking.recentlySwitchedToTabs[id] ?? []
+ dates.append(Date())
+ if dates.count > 10 { dates.removeFirst(dates.count - 10) }
+ ranking.recentlySwitchedToTabs[id] = dates
+ rankingFile.save(ranking)
+ }
+ resolveWindowConflicts(winner: w)
touch()
}
@@ -299,7 +436,7 @@ final class SidebarStore {
items[id] = it
revision &+= 1
sidebarFile.save(SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: orderedSpaces,
- items: Array(items.values)), delay: 2)
+ items: Array(items.values), profiles: profiles), delay: 2)
}
func markUnread(_ id: UUID, _ unread: Bool = true) {
@@ -379,16 +516,29 @@ final class SidebarStore {
func touchAfterImport() { touch() }
+ /// What goes to disk: everything but incognito windows' spaces and tabs.
var document: SidebarDocument {
- SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: orderedSpaces, items: Array(items.values))
+ var hidden = Set<UUID>()
+ for sid in incognitoSpaceIDs { if let s = spaces[sid] { collectSubtree(of: s, into: &hidden) } }
+ return SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: orderedSpaces,
+ items: hidden.isEmpty ? Array(items.values) : items.values.filter { !hidden.contains($0.id) },
+ profiles: profiles)
}
- /// Most recently used tab other than the current one (⌃Tab).
- func mostRecentOtherTab() -> UUID? {
- let current = selectedTabID
- return ranking.recentlySwitchedToTabs
- .filter { $0.key != current && items[$0.key]?.isTab == true }
- .max { ($0.value.last ?? .distantPast) < ($1.value.last ?? .distantPast) }?.key
+ /// The tab switcher's list (⌃Tab): a space's most recently used tabs, newest first
+ /// (Arc shows five, the current tab first).
+ func recentTabs(in sid: UUID, limit: Int) -> [UUID] {
+ visibleTabs(in: sid)
+ .filter { $0.tab?.timeLastActiveAt != nil }
+ .sorted { $0.tab!.timeLastActiveAt! > $1.tab!.timeLastActiveAt! }
+ .prefix(limit).map(\.id)
+ }
+
+ /// The tab last used in a space before `id` (where Arc goes after "Close and Keep Pinned").
+ func mostRecentTab(in sid: UUID, excluding id: UUID) -> UUID? {
+ visibleTabs(in: sid)
+ .filter { $0.id != id && $0.tab?.timeLastActiveAt != nil }
+ .max { $0.tab!.timeLastActiveAt! < $1.tab!.timeLastActiveAt! }?.id
}
// MARK: Tree moves
@@ -416,6 +566,8 @@ final class SidebarStore {
/// today list unpacks it.
func moveItem(_ id: UUID, to newParent: UUID, index: Int?) {
guard var it = items[id], items[newParent] != nil, id != newParent, !isDescendant(newParent, of: id) else { return }
+ // A page can't change profile: nothing moves into or out of an incognito window.
+ guard isIncognito(item: id) == isIncognito(item: newParent) else { return }
// Only tabs live inside a split; dropping onto a split adds a pane.
if items[newParent]?.isSplit == true {
if it.isTab { addToSplit(newParent, tabID: id, at: index) }
@@ -486,8 +638,8 @@ final class SidebarStore {
}
/// Panes shown in a space right now (the selected tab's split).
- func visiblePaneTabIDs(in spaceID: UUID) -> [UUID] {
- guard let sel = selectedTabID(in: spaceID) else { return [] }
+ func visiblePaneTabIDs(in spaceID: UUID, window: UUID? = nil) -> [UUID] {
+ guard let sel = selectedTabID(in: spaceID, window: window) else { return [] }
return paneTabIDs(for: sel)
}
@@ -665,8 +817,12 @@ final class SidebarStore {
items[gp] = grand
}
items[splitID] = nil
- if let sid, let sel = prefs.selectedTabPerSpace[sid], items[sel] == nil {
- prefs.selectedTabPerSpace[sid] = split.children.first
+ if let sid {
+ for w in prefs.windows {
+ if let sel = w.selectedTabPerSpace[sid], items[sel] == nil {
+ updateWindow(w.id) { $0.selectedTabPerSpace[sid] = split.children.first }
+ }
+ }
}
}
@@ -806,23 +962,20 @@ final class SidebarStore {
func archiveTab(_ id: UUID, reason: ArchiveReason) {
guard let it = items[id], it.isTab else { return }
let sid = spaceID(ofItem: id)
- let wasSelected = sid.flatMap { selectedTabID(in: $0) } == id
+ let selectedIn = sid.map { s in prefs.windows.filter { $0.selectedTabPerSpace[s] == id }.map(\.id) } ?? []
let pinned = isPinned(id)
let split = splitContaining(id)
detach(id)
items[id] = nil
- // Empty panes never had a page; nothing to keep in the Library.
- if !it.isEmptyTab {
+ // Empty panes never had a page and incognito pages leave no trace: nothing for the Library.
+ if !it.isEmptyTab, !isIncognito(space: sid) {
archive.insert(ArchivedItem(archivedAt: Date(), reason: reason, sourceSpaceID: sid, wasPinned: pinned, item: it), at: 0)
if archive.count > 2000 { archive.removeLast(archive.count - 2000) }
}
- if wasSelected, let sid {
+ if !selectedIn.isEmpty, let sid {
// Closing a pane keeps the split on screen: focus a neighbour pane.
- if let split, let remaining = items[split.id]?.children.first(where: { items[$0]?.isTab == true }) {
- prefs.selectedTabPerSpace[sid] = remaining
- } else {
- prefs.selectedTabPerSpace[sid] = nextSelection(after: it, in: sid)
- }
+ let next = split.flatMap { s in items[s.id]?.children.first { items[$0]?.isTab == true } } ?? nextSelection(after: it, in: sid)
+ for w in selectedIn { updateWindow(w) { $0.selectedTabPerSpace[sid] = next } }
}
if let split { collapseSplitIfNeeded(split.id) }
touch()
@@ -893,8 +1046,8 @@ final class SidebarStore {
guard settings.autoArchiveEnabled else { return }
let cutoff = Date().addingTimeInterval(-settings.autoArchive.seconds)
for space in orderedSpaces {
- let selected = selectedTabID(in: space.id)
- for t in tabs(under: space.todayContainerID) where t.id != selected {
+ let selected = Set(prefs.windows.compactMap { $0.selectedTabPerSpace[space.id] })
+ for t in tabs(under: space.todayContainerID) where !selected.contains(t.id) {
let last = t.tab?.timeLastActiveAt ?? t.createdAt
if last < cutoff { archiveTab(t.id, reason: .auto) }
}
@@ -917,7 +1070,7 @@ final class SidebarStore {
pinnedContainerID: pinned.id, todayContainerID: today.id, createdAt: Date())
spaces[id] = space
spaceOrder.append(id)
- if focus { prefs.focusedSpaceID = id }
+ if focus, !window().isIncognito { updateWindow(nil) { $0.focusedSpaceID = id } }
touch()
return space
}
@@ -929,7 +1082,7 @@ final class SidebarStore {
}
func deleteSpace(_ id: UUID) {
- guard spaces.count > 1, let space = spaces[id] else { return }
+ guard spaceOrder.count > 1, spaceOrder.contains(id), let space = spaces[id] else { return }
for t in tabs(under: space.favoritesContainerID) + tabs(under: space.pinnedContainerID) + tabs(under: space.todayContainerID) {
archiveTab(t.id, reason: .spaceDeleted)
}
@@ -939,8 +1092,55 @@ final class SidebarStore {
items[space.todayContainerID] = nil
spaces[id] = nil
spaceOrder.removeAll { $0 == id }
- prefs.selectedTabPerSpace[id] = nil
- if prefs.focusedSpaceID == id { prefs.focusedSpaceID = spaceOrder.first }
+ var windows = prefs.windows
+ for i in windows.indices {
+ windows[i].selectedTabPerSpace[id] = nil
+ if windows[i].focusedSpaceID == id { windows[i].focusedSpaceID = spaceOrder.first }
+ }
+ prefs.windows = windows
+ touch()
+ }
+
+ // MARK: Profiles
+
+ func profile(_ id: UUID?) -> BrowserProfile? { id.flatMap { p in profiles.first { $0.id == p } } }
+ func spaces(usingProfile id: UUID?) -> [Space] { orderedSpaces.filter { $0.profileID == id } }
+
+ /// The Chromium folder a tab's pages load in: its space's profile, or nil for the
+ /// Default profile (and for incognito, which has its own off-the-record one).
+ func profilePath(item id: UUID) -> String? {
+ guard let sid = spaceID(ofItem: id), !isIncognito(space: sid), let p = profile(spaces[sid]?.profileID) else { return nil }
+ return AppPaths.chromiumCache.appendingPathComponent(p.directoryName, isDirectory: true).path
+ }
+
+ @discardableResult
+ func createProfile(name: String) -> BrowserProfile {
+ let p = BrowserProfile(id: UUID(), name: name)
+ profiles.append(p)
+ touch()
+ return p
+ }
+
+ func renameProfile(_ id: UUID, to name: String) {
+ guard let i = profiles.firstIndex(where: { $0.id == id }), !name.isEmpty else { return }
+ profiles[i].name = name
+ touch()
+ }
+
+ /// Pages already open in the space load again in the new profile (BrowserManager).
+ func setProfile(_ profileID: UUID?, forSpace id: UUID) {
+ guard var s = spaces[id], s.profileID != profileID, profileID == nil || profile(profileID) != nil else { return }
+ s.profileID = profileID
+ spaces[id] = s
+ touch()
+ }
+
+ /// Arc: only profiles no space uses can be deleted. Chromium may still hold the
+ /// folder open, so it goes at the next launch (ProfileCleanup).
+ func deleteProfile(_ id: UUID) {
+ guard let p = profile(id), spaces.values.allSatisfy({ $0.profileID != id }) else { return }
+ profiles.removeAll { $0.id == id }
+ ProfileCleanup.schedule(p.directoryName)
touch()
}
@@ -951,16 +1151,19 @@ final class SidebarStore {
touch()
}
- func focusSpace(_ id: UUID) {
- guard spaces[id] != nil, id != focusedSpaceID else { return }
- prefs.focusedSpaceID = id
+ /// A window switching to a space whose open tab another window shows leaves it there.
+ func focusSpace(_ id: UUID, window: UUID? = nil) {
+ let w = self.window(window).id
+ guard spaces[id] != nil, id != focusedSpaceID(window: w), !self.window(w).isIncognito, !isIncognito(space: id) else { return }
+ updateWindow(w) { $0.focusedSpaceID = id }
+ resolveWindowConflicts(winner: w, wins: false)
revision &+= 1
}
- func focusSpace(offset: Int) {
- guard let idx = spaceOrder.firstIndex(of: focusedSpaceID), spaceOrder.count > 1 else { return }
+ func focusSpace(offset: Int, window: UUID? = nil) {
+ guard let idx = spaceOrder.firstIndex(of: focusedSpaceID(window: window)), spaceOrder.count > 1 else { return }
let n = spaceOrder.count
- focusSpace(spaceOrder[((idx + offset) % n + n) % n])
+ focusSpace(spaceOrder[((idx + offset) % n + n) % n], window: window)
}
// MARK: History and ranking signals
@@ -981,7 +1184,7 @@ final class SidebarStore {
func recordQuerySelection(query: String, url: String) {
let q = query.lowercased().trimmingCharacters(in: .whitespaces)
- guard !q.isEmpty else { return }
+ guard !q.isEmpty, !window().isIncognito else { return }
ranking.queriesToSelected[q] = url
if ranking.queriesToSelected.count > 500 {
if let k = ranking.queriesToSelected.keys.first { ranking.queriesToSelected[k] = nil }
diff --git a/Sources/Cra/Services/SuggestionEngine.swift b/Sources/Cra/Services/SuggestionEngine.swift
index a57a6d5..1508685 100644
--- a/Sources/Cra/Services/SuggestionEngine.swift
+++ b/Sources/Cra/Services/SuggestionEngine.swift
@@ -71,9 +71,12 @@ final class SuggestionEngine {
var items: [Suggestion] = []
let typed = typedRow(query: query)
items.append(contentsOf: tabSuggestions(q, excluding: currentTabID))
- items.append(contentsOf: archiveSuggestions(q))
- items.append(contentsOf: historySuggestions(q, openURLs: Set(store.allTabs().compactMap { $0.tab?.url })))
- items.append(contentsOf: topDomainSuggestions(q))
+ // Incognito: the window's own tabs, search and commands; nothing from the normal profile.
+ if !incognito {
+ items.append(contentsOf: archiveSuggestions(q))
+ items.append(contentsOf: historySuggestions(q, openURLs: Set(store.profileTabs(window: nil).compactMap { $0.tab?.url })))
+ items.append(contentsOf: topDomainSuggestions(q))
+ }
items.append(contentsOf: commandSuggestions(q, currentTabID: currentTabID))
// Learned: the user picked this URL for this query before.
@@ -133,9 +136,12 @@ final class SuggestionEngine {
// MARK: Sources
+ /// The command bar is open in an incognito window (it acts on the window in use).
+ private var incognito: Bool { store.window().isIncognito }
+
private func tabSuggestions(_ q: String, excluding current: UUID?) -> [Suggestion] {
var out: [Suggestion] = []
- for tab in store.allTabs() where tab.id != current {
+ for tab in store.profileTabs(window: nil) where tab.id != current {
guard let t = tab.tab else { continue }
var score = textScore(q, title: tab.displayTitle, url: t.url)
if let custom = tab.title?.lowercased(), custom.hasPrefix(q) { score += 40 }
@@ -213,7 +219,7 @@ final class SuggestionEngine {
out.append(Suggestion(id: "cmd:\(a.id)", kind: .command(a.id), title: a.name, subtitle: "Command",
url: nil, faviconKey: nil, symbol: "command", trailing: a.primary?.display, score: s))
}
- for space in store.orderedSpaces {
+ for space in incognito ? [] : store.orderedSpaces {
let s = nameScore("Switch to \(space.title)", triggers: [space.title.lowercased()])
if s > 0 && space.id != store.focusedSpaceID {
out.append(Suggestion(id: "space:\(space.id)", kind: .switchSpace(space.id), title: "Switch to \(space.title)",
@@ -241,7 +247,7 @@ final class SuggestionEngine {
}
private func recentSuggestions(excluding current: UUID?) -> [Suggestion] {
- let tabs = store.allTabs().filter { $0.id != current }
+ let tabs = store.profileTabs(window: nil).filter { $0.id != current }
.sorted { ($0.tab?.timeLastActiveAt ?? .distantPast) > ($1.tab?.timeLastActiveAt ?? .distantPast) }
.prefix(7)
var out: [Suggestion] = tabs.map { tab in
@@ -250,7 +256,7 @@ final class SuggestionEngine {
subtitle: [sid.flatMap { store.space($0)?.title } ?? "", Self.humanURL(tab.tab?.url ?? "")].filter { !$0.isEmpty }.joined(separator: " · "),
url: tab.tab?.url, faviconKey: tab.tab?.faviconKey, symbol: nil, trailing: "Switch to Tab", score: 0, spaceID: sid)
}
- for entry in store.archive.prefix(2) {
+ for entry in store.archive.prefix(incognito ? 0 : 2) {
guard let t = entry.item.tab else { continue }
out.append(Suggestion(id: "arch:\(entry.id)", kind: .archived(entry.id), title: entry.item.displayTitle,
subtitle: "Archived \(Self.relative(entry.archivedAt))", url: t.url, faviconKey: t.faviconKey,
diff --git a/Sources/Cra/UI/ArcTooltip.swift b/Sources/Cra/UI/ArcTooltip.swift
new file mode 100644
index 0000000..e8ad0bb
--- /dev/null
+++ b/Sources/Cra/UI/ArcTooltip.swift
@@ -0,0 +1,291 @@
+import AppKit
+import SwiftUI
+
+/// Arc's hover tips for small controls (ArcTooltip, PresentationBehavior.onMouseIdle).
+/// Measured on Arc 1.170's sidebar row buttons (27 Oct 2026, 1x screen recordings): the tip
+/// shows once the pointer has rested ~1.6 s, at once when moving from another tip, pops in
+/// without a fade, fades out in ~60 ms, and hangs off the bottom-trailing corner of a 16 pt
+/// box around the glyph. Clicking the control dismisses it.
+@MainActor
+final class ArcTooltipController {
+ static let shared = ArcTooltipController()
+
+ static let idleDelay: TimeInterval = 1.6
+ /// Moving onto another control this soon after a tip closed shows its tip right away.
+ static let warmWindow: TimeInterval = 0.5
+
+ private var panel: LittleTooltipPanel?
+ private weak var shownFor: ArcTooltipAnchorView?
+ private weak var pendingFor: ArcTooltipAnchorView?
+ private var timer: Timer?
+ private var lastHiddenAt = Date.distantPast
+ private var clickMonitor: Any?
+ private var flagsMonitor: Any?
+ /// Anchors under the pointer; a row and its close button both track it, and the
+ /// innermost (smallest) one owns the tip (Arc: TooltipController.enteredViewStack).
+ private var hovered: [WeakAnchor] = []
+
+ private struct WeakAnchor { weak var view: ArcTooltipAnchorView? }
+
+ private init() {
+ clickMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .keyDown]) { [weak self] e in
+ self?.dismiss()
+ return e
+ }
+ // Modifier keys keep the tip up (Arc: allowedModifierKeys); ⌥ swaps in the option text.
+ flagsMonitor = NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { [weak self] e in
+ if let self, let v = self.shownFor, v.optionText != nil { self.show(for: v) }
+ return e
+ }
+ }
+
+ func mouseMoved(in view: ArcTooltipAnchorView) {
+ if !hovered.contains(where: { $0.view === view }) { hovered.append(WeakAnchor(view: view)) }
+ let mouse = NSEvent.mouseLocation
+ hovered.removeAll { a in
+ guard let v = a.view, v.window != nil else { return true }
+ return !v.screenFrame.contains(mouse)
+ }
+ guard let target = hovered.compactMap(\.view).min(by: { $0.screenFrame.width * $0.screenFrame.height < $1.screenFrame.width * $1.screenFrame.height }),
+ !target.text.isEmpty else {
+ if shownFor != nil { hide() }
+ cancelPending()
+ return
+ }
+ if shownFor === target { return }
+ startTip(for: target)
+ }
+
+ private func startTip(for view: ArcTooltipAnchorView) {
+ if panel != nil || Date().timeIntervalSince(lastHiddenAt) < Self.warmWindow {
+ show(for: view)
+ return
+ }
+ // On mouse idle: every move restarts the wait.
+ pendingFor = view
+ timer?.invalidate()
+ timer = Timer.scheduledTimer(withTimeInterval: Self.idleDelay, repeats: false) { [weak self, weak view] _ in
+ Task { @MainActor in
+ guard let self, let view, self.pendingFor === view else { return }
+ self.show(for: view)
+ }
+ }
+ }
+
+ func mouseExited(_ view: ArcTooltipAnchorView) {
+ hovered.removeAll { $0.view === view || $0.view == nil }
+ if pendingFor === view { cancelPending() }
+ if shownFor === view { hide() }
+ // Leaving a close button for the rest of its row hands the tip back to the row.
+ if let outer = hovered.last?.view, outer.window != nil { mouseMoved(in: outer) }
+ }
+
+ /// A click or key press: the next tip waits for the pointer to rest again, so a row that
+ /// slides under the pointer after the click doesn't pop its tip.
+ func dismiss() {
+ cancelPending()
+ hide()
+ lastHiddenAt = .distantPast
+ }
+
+ private func cancelPending() {
+ timer?.invalidate()
+ timer = nil
+ pendingFor = nil
+ }
+
+ private func show(for view: ArcTooltipAnchorView) {
+ cancelPending()
+ guard let window = view.window, !view.text.isEmpty else { return }
+ removePanel()
+ let p = LittleTooltipPanel()
+ let option = NSEvent.modifierFlags.contains(.option) ? view.optionText : nil
+ let host = NSHostingView(rootView: ArcTooltipLabel(text: option ?? view.text, keys: option == nil ? view.keys : [],
+ subtitle: option == nil ? view.subtitle : nil))
+ let size = host.fittingSize
+ host.setFrameSize(size)
+ p.contentView = host
+ // Buttons: off the bottom-trailing corner of a 16 pt box around the glyph.
+ // Rows: Arc's .cursor anchor, 13 pt right of and 14 pt below the pointer.
+ let r = view.screenFrame
+ let mouse = NSEvent.mouseLocation
+ let anchor = view.followsCursor ? NSPoint(x: mouse.x + 13, y: mouse.y - 14) : NSPoint(x: r.midX + 8, y: r.midY - 7)
+ var origin = NSPoint(x: anchor.x, y: anchor.y - size.height)
+ if let screen = window.screen?.visibleFrame {
+ origin.x = min(max(origin.x, screen.minX + 4), screen.maxX - size.width - 4)
+ if origin.y < screen.minY + 4 { origin.y = (view.followsCursor ? mouse.y : r.midY) + 7 }
+ }
+ p.setFrame(NSRect(origin: origin, size: size), display: true)
+ window.addChildWindow(p, ordered: .above)
+ p.orderFront(nil)
+ panel = p
+ shownFor = view
+ view.onShow?()
+ }
+
+ private func hide() {
+ guard let p = panel else { return }
+ panel = nil
+ shownFor = nil
+ lastHiddenAt = Date()
+ NSAnimationContext.runAnimationGroup({ ctx in
+ ctx.duration = 0.06
+ p.animator().alphaValue = 0
+ }, completionHandler: {
+ p.parent?.removeChildWindow(p)
+ p.orderOut(nil)
+ })
+ }
+
+ private func removePanel() {
+ guard let p = panel else { return }
+ panel = nil
+ shownFor = nil
+ p.parent?.removeChildWindow(p)
+ p.orderOut(nil)
+ }
+}
+
+/// Tracks the pointer over a control without taking its clicks.
+final class ArcTooltipAnchorView: NSView {
+ var text = ""
+ var keys: [String] = []
+ var followsCursor = false
+ /// A second, dimmer line (Arc's SidebarCellTooltipView subtitle, e.g. "Double-click to rename").
+ var subtitle: String?
+ /// Shown instead while ⌥ is held (the split close button un-splits on ⌥-click).
+ var optionText: String?
+ var onShow: (() -> Void)?
+
+ var screenFrame: NSRect { window?.convertToScreen(convert(bounds, to: nil)) ?? .zero }
+
+ /// For AppKit controls: an anchor filling `control`.
+ static func attach(to control: NSView, help: String) -> ArcTooltipAnchorView {
+ let a = ArcTooltipAnchorView(frame: control.bounds)
+ a.autoresizingMask = [.width, .height]
+ (a.text, a.keys) = ArcTooltipLabel.split(help)
+ control.addSubview(a)
+ return a
+ }
+
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas { removeTrackingArea(t) }
+ // activeAlways: the key window is usually a Chromium page window, not the sidebar's.
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect],
+ owner: self, userInfo: nil))
+ }
+
+ override func mouseEntered(with event: NSEvent) { MainActor.assumeIsolated { ArcTooltipController.shared.mouseMoved(in: self) } }
+ override func mouseMoved(with event: NSEvent) { MainActor.assumeIsolated { ArcTooltipController.shared.mouseMoved(in: self) } }
+ override func mouseExited(with event: NSEvent) { MainActor.assumeIsolated { ArcTooltipController.shared.mouseExited(self) } }
+
+ override func viewWillMove(toWindow newWindow: NSWindow?) {
+ // Row buttons vanish when the row loses hover; their tip goes with them.
+ if newWindow == nil { MainActor.assumeIsolated { ArcTooltipController.shared.mouseExited(self) } }
+ super.viewWillMove(toWindow: newWindow)
+ }
+}
+
+private struct ArcTooltipAnchor: NSViewRepresentable {
+ let text: String
+ let keys: [String]
+ let followsCursor: Bool
+ let subtitle: String?
+ let optionText: String?
+ let onShow: (() -> Void)?
+ func makeNSView(context: Context) -> ArcTooltipAnchorView { ArcTooltipAnchorView() }
+ func updateNSView(_ v: ArcTooltipAnchorView, context: Context) {
+ v.text = text
+ v.keys = keys
+ v.followsCursor = followsCursor
+ v.subtitle = subtitle
+ v.optionText = optionText
+ v.onShow = onShow
+ }
+}
+
+extension View {
+ /// Arc-style tooltip. A trailing shortcut in parentheses, "Close Tab (⌘W)", becomes key caps.
+ /// `followsCursor` places it by the pointer (Arc's sidebar rows and tiles) instead of the control.
+ func arcTooltip(_ help: String, followsCursor: Bool = false, subtitle: String? = nil,
+ optionHelp: String? = nil, onShow: (() -> Void)? = nil) -> some View {
+ let (text, keys) = ArcTooltipLabel.split(help)
+ return background(ArcTooltipAnchor(text: text, keys: keys, followsCursor: followsCursor, subtitle: subtitle,
+ optionText: optionHelp, onShow: onShow))
+ }
+}
+
+/// The tip itself: 28 pt navy capsule, 12 pt medium text, 18 pt key caps with a darker
+/// bottom edge (Arc sidebar, 1x captures; Little Arc's larger tip is LittleTooltip).
+struct ArcTooltipLabel: View {
+ let text: String
+ let keys: [String]
+ var subtitle: String? = nil
+
+ static let capEdge = Color(red: 119 / 255, green: 122 / 255, blue: 211 / 255)
+ static let maxTextWidth: CGFloat = 280
+
+ static func width(of text: String) -> CGFloat {
+ (text as NSString).size(withAttributes: [.font: NSFont.systemFont(ofSize: 12, weight: .medium)]).width
+ }
+
+ private var wraps: Bool { Self.width(of: text) > Self.maxTextWidth }
+
+ var body: some View {
+ let multiline = wraps || subtitle != nil
+ HStack(spacing: 7) {
+ VStack(alignment: .leading, spacing: 1) {
+ // Long titles wrap at a fixed width (ArcTooltipConfiguration.maxWidth; Arc's value is unknown).
+ if wraps {
+ Text(text).font(.system(size: 12, weight: .medium)).foregroundStyle(LittlePalette.tooltipText)
+ .lineLimit(3)
+ .frame(width: Self.maxTextWidth, alignment: .leading)
+ .fixedSize(horizontal: false, vertical: true)
+ } else {
+ Text(text).font(.system(size: 12, weight: .medium)).foregroundStyle(LittlePalette.tooltipText)
+ }
+ if let subtitle {
+ Text(subtitle).font(.system(size: 11)).foregroundStyle(LittlePalette.tooltipText.opacity(0.6))
+ }
+ }
+ if !keys.isEmpty {
+ HStack(spacing: 3) {
+ ForEach(Array(keys.enumerated()), id: \.offset) { _, k in
+ ZStack(alignment: .top) {
+ RoundedRectangle(cornerRadius: 4, style: .continuous).fill(Self.capEdge)
+ Text(k)
+ .font(.system(size: 10, weight: .bold))
+ .foregroundStyle(LittlePalette.tooltipCapGlyph)
+ .frame(width: 18, height: 16)
+ .background(RoundedRectangle(cornerRadius: 4, style: .continuous).fill(LittlePalette.tooltipCap))
+ }
+ .frame(width: 18, height: 18)
+ }
+ }
+ }
+ }
+ .padding(.leading, 10)
+ .padding(.trailing, keys.isEmpty ? 10 : 8)
+ .padding(.vertical, multiline ? 6 : 0)
+ .frame(minHeight: 28)
+ // No border: unlike Little Arc's tip, the sidebar one goes straight from fill to backdrop.
+ // Two or more lines get a rounded rectangle (Cra's choice; Arc's multi-line tip wasn't observed).
+ .background(RoundedRectangle(cornerRadius: multiline ? 10 : 14, style: .circular).fill(LittlePalette.tooltip))
+ .fixedSize()
+ }
+
+ /// "Copy URL (⇧⌘C)" → ("Copy URL", ["⇧", "⌘", "C"]).
+ static func split(_ help: String) -> (String, [String]) {
+ guard help.hasSuffix(")"), let open = help.range(of: " (", options: .backwards) else { return (help, []) }
+ let shortcut = String(help[open.upperBound..<help.index(before: help.endIndex)])
+ let modifiers: Set<Character> = ["⌃", "⌥", "⇧", "⌘"]
+ guard let first = shortcut.first, modifiers.contains(first), shortcut.count <= 6 else { return (help, []) }
+ var caps = shortcut.prefix { modifiers.contains($0) }.map(String.init)
+ let key = shortcut.drop { modifiers.contains($0) }
+ if !key.isEmpty { caps.append(String(key)) }
+ return (String(help[..<open.lowerBound]), caps)
+ }
+}
diff --git a/Sources/Cra/UI/ContentToolbarView.swift b/Sources/Cra/UI/ContentToolbarView.swift
index 4eb3aba..9db24ee 100644
--- a/Sources/Cra/UI/ContentToolbarView.swift
+++ b/Sources/Cra/UI/ContentToolbarView.swift
@@ -14,13 +14,13 @@ struct ContentToolbarView: View {
private var tab: SidebarItem? {
if let id = paneTabID { return store.item(id) }
- return store.selectedTab
+ return store.selectedTab(window: ui.windowID)
}
private var onCard: Bool { tab != nil && !isEmptyPane }
/// Arc's empty pane ("Search or Enter URL…" on the tinted card).
private var isEmptyPane: Bool { tab?.isEmptyTab ?? false }
private var inSplit: Bool { paneTabID != nil && ui.splitPaneIDs.count > 1 }
- private var isFocusedPane: Bool { paneTabID == nil || store.selectedTabID == paneTabID }
+ private var isFocusedPane: Bool { paneTabID == nil || store.selectedTabID(window: ui.windowID) == paneTabID }
private var nav: TabNavState {
if let id = paneTabID { return ui.navState(for: id) }
return TabNavState(canGoBack: ui.canGoBack, canGoForward: ui.canGoForward, isLoading: ui.isLoading, themeColor: ui.pageThemeColor)
@@ -97,7 +97,7 @@ struct ContentToolbarView: View {
}
.buttonStyle(.plain)
.onHover { hoverURL = $0 }
- .help(t.url)
+ .arcTooltip(t.url, followsCursor: true)
Spacer(minLength: 8)
}
@@ -196,7 +196,7 @@ struct ContentToolbarView: View {
}
.menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden)
.frame(width: 26)
- .help("Split View Options")
+ .arcTooltip("Split View Options")
}
ToolbarIcon(symbol: "xmark", fg: isEmptyPane ? palette.textSecondary : fgDim, help: "Close this Split Pane (⌃⇧-)", width: 30, iconSize: 14) { actions.closePane(id) }
.padding(.trailing, 4)
@@ -241,7 +241,7 @@ private extension ContentToolbarView {
}
var sidebarToggle: some View {
- ToolbarIcon(symbol: "sidebar.left", fg: fgDim, help: store.prefs.sidebarVisible ? "Hide Sidebar (⌘S)" : "Show Sidebar (⌘S)",
+ ToolbarIcon(symbol: "sidebar.left", fg: fgDim, help: store.window(ui.windowID).sidebarVisible ? "Hide Sidebar (⌘S)" : "Show Sidebar (⌘S)",
width: 37, iconSize: 15.5) { actions.toggleSidebar() }
}
@@ -270,7 +270,7 @@ struct ToolbarIcon: View {
.buttonStyle(.plain)
.disabled(!enabled)
.onHover { hover = $0 }
- .help(help)
+ .arcTooltip(help)
}
}
@@ -295,6 +295,6 @@ struct ToolbarImageButton: View {
}
.buttonStyle(.plain)
.onHover { hover = $0 }
- .help(help)
+ .arcTooltip(help)
}
}
diff --git a/Sources/Cra/UI/PictureInPicture/PictureInPictureControls.swift b/Sources/Cra/UI/PictureInPicture/PictureInPictureControls.swift
index 470a067..e1a3dd0 100644
--- a/Sources/Cra/UI/PictureInPicture/PictureInPictureControls.swift
+++ b/Sources/Cra/UI/PictureInPicture/PictureInPictureControls.swift
@@ -9,7 +9,7 @@ import AppKit
/// through to the overlay, which drags and resizes the window.
@MainActor
final class PictureInPictureControlsView: NSView {
- var isPlaying = false { didSet { playButton.symbol = isPlaying ? "pause.fill" : "play.fill"; playButton.toolTip = isPlaying ? "Pause" : "Play" } }
+ var isPlaying = false { didSet { playButton.symbol = isPlaying ? "pause.fill" : "play.fill"; playButton.tip = isPlaying ? "Pause" : "Play" } }
private let scrim = CAGradientLayer()
private let closeButton = PictureInPictureButton(symbol: "xmark", pointSize: 12, diameter: 26, tip: "Close")
@@ -125,20 +125,24 @@ final class PictureInPictureButton: NSView {
private var isPressed = false { didSet { updateBackground() } }
private let pointSize: CGFloat
private let image = NSImageView()
+ private var tipAnchor: ArcTooltipAnchorView?
+ /// Arc-style hover tip (ArcTooltip), not AppKit's yellow one.
+ var tip: String { didSet { tipAnchor?.text = tip; setAccessibilityLabel(tip) } }
init(symbol: String, pointSize: CGFloat, diameter: CGFloat, tip: String) {
self.symbol = symbol
self.pointSize = pointSize
+ self.tip = tip
super.init(frame: NSRect(x: 0, y: 0, width: diameter, height: diameter))
wantsLayer = true
layer?.cornerRadius = diameter / 2
- toolTip = tip
image.image = Self.image(symbol, pointSize)
image.contentTintColor = .white
image.imageScaling = .scaleNone
image.frame = bounds
image.autoresizingMask = [.width, .height]
addSubview(image)
+ tipAnchor = ArcTooltipAnchorView.attach(to: self, help: tip)
setAccessibilityRole(.button)
setAccessibilityLabel(tip)
updateBackground()
diff --git a/Sources/Cra/UI/Settings/ProfilesPane.swift b/Sources/Cra/UI/Settings/ProfilesPane.swift
new file mode 100644
index 0000000..681853e
--- /dev/null
+++ b/Sources/Cra/UI/Settings/ProfilesPane.swift
@@ -0,0 +1,68 @@
+import SwiftUI
+
+/// Dia's Profiles pane (and Arc's Profiles preferences): the profiles and how many spaces
+/// use each, "Create Profile…" under the card. A space picks its profile in Edit Space.
+/// Arc only deletes profiles no space uses, and never Default.
+struct ProfilesPane: View {
+ @Environment(SidebarStore.self) private var store
+ @State private var naming: BrowserProfile?
+ @State private var creating = false
+ @State private var name = ""
+ @State private var deleting: BrowserProfile?
+
+ var body: some View {
+ SettingsCardPane {
+ SettingsHeader("Profiles")
+ SettingsCard {
+ row(name: "Default", profileID: nil) { EmptyView() }
+ ForEach(store.profiles) { p in
+ SettingsCardDivider()
+ row(name: p.name, profileID: p.id) {
+ Button("Rename…") { name = p.name; naming = p }
+ Button("Delete…") { deleting = p }
+ .disabled(!store.spaces(usingProfile: p.id).isEmpty)
+ }
+ }
+ }
+ HStack {
+ Button("Create Profile…") { name = ""; creating = true }
+ Spacer()
+ }
+ .padding(.top, 7.5)
+ SettingsFootnote("Profiles help keep your data separate across Spaces, like logins, cookies and site data. You can use any Profile across one or more Spaces: right-click a Space and choose Edit Space to pick one. Only Profiles not assigned to any Spaces can be deleted.")
+ }
+ .alert("Create a new Profile", isPresented: $creating) {
+ TextField("Profile name", text: $name)
+ Button("Create") { if !trimmed.isEmpty { store.createProfile(name: trimmed) } }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("What do you want to call this Profile?")
+ }
+ .alert("Rename Profile", isPresented: Binding(get: { naming != nil }, set: { if !$0 { naming = nil } })) {
+ TextField("Profile name", text: $name)
+ Button("Rename") { if let p = naming { store.renameProfile(p.id, to: trimmed) } }
+ Button("Cancel", role: .cancel) {}
+ }
+ .alert("Delete “\(deleting?.name ?? "")”?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } })) {
+ Button("Delete", role: .destructive) { if let p = deleting { store.deleteProfile(p.id) } }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("Deleting this Profile will permanently remove any cookies, history, preferences, and logins that belong to it.")
+ }
+ }
+
+ private var trimmed: String { name.trimmingCharacters(in: .whitespaces) }
+
+ private func row<Trailing: View>(name: String, profileID: UUID?, @ViewBuilder trailing: () -> Trailing) -> some View {
+ let spaces = store.spaces(usingProfile: profileID)
+ return SettingsCardRow {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(name).font(.system(size: 13))
+ Text(spaces.isEmpty ? "No Spaces" : spaces.map { "\($0.emoji) \($0.title)" }.joined(separator: ", "))
+ .font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1)
+ }
+ } trailing: {
+ HStack(spacing: 6) { trailing() }
+ }
+ }
+}
diff --git a/Sources/Cra/UI/Settings/SettingsWindowController.swift b/Sources/Cra/UI/Settings/SettingsWindowController.swift
index 1e463b0..de16d80 100644
--- a/Sources/Cra/UI/Settings/SettingsWindowController.swift
+++ b/Sources/Cra/UI/Settings/SettingsWindowController.swift
@@ -8,10 +8,10 @@ struct SettingsActions {
}
/// The panes in Dia's Settings sidebar (Dia 1.54.2: Account, Tabs, Privacy, Profiles, Skills,
-/// Apps, Shortcuts, Advanced). Cra has no account, profiles or AI skills/apps; General
+/// Apps, Shortcuts, Advanced). Cra has no account or AI skills/apps; General
/// (system integration) and Extensions take rows instead.
enum SettingsPane: String, CaseIterable, Identifiable {
- case general, tabs, privacy, extensions, shortcuts, advanced
+ case general, tabs, privacy, profiles, extensions, shortcuts, advanced
var id: String { rawValue }
var title: String {
@@ -19,6 +19,7 @@ enum SettingsPane: String, CaseIterable, Identifiable {
case .general: return "General"
case .tabs: return "Tabs"
case .privacy: return "Privacy"
+ case .profiles: return "Profiles"
case .extensions: return "Extensions"
case .shortcuts: return "Shortcuts"
case .advanced: return "Advanced"
@@ -31,6 +32,7 @@ enum SettingsPane: String, CaseIterable, Identifiable {
case .general: return "gearshape"
case .tabs: return "square.on.square"
case .privacy: return "hand.raised"
+ case .profiles: return "person"
case .extensions: return "puzzlepiece.extension"
case .shortcuts: return "keyboard"
case .advanced: return "gearshape.2"
@@ -220,6 +222,7 @@ struct SettingsContent: View {
case .general: GeneralPane()
case .tabs: TabsPane()
case .privacy: PrivacyPane()
+ case .profiles: ProfilesPane()
case .extensions: ExtensionsPane(actions: actions)
case .shortcuts: ShortcutsPane()
case .advanced: AdvancedPane(actions: actions)
diff --git a/Sources/Cra/UI/Settings/ShortcutsPane.swift b/Sources/Cra/UI/Settings/ShortcutsPane.swift
index 8b1f8e0..105fdd2 100644
--- a/Sources/Cra/UI/Settings/ShortcutsPane.swift
+++ b/Sources/Cra/UI/Settings/ShortcutsPane.swift
@@ -246,6 +246,7 @@ enum ShortcutDescriptions {
private static let table: [String: String] = [
"newTab": "Create a new tab.",
"newWindow": "Open a new window.",
+ "newIncognitoWindow": "Open a window that keeps no history, cookies or tabs once closed.",
"newLittleWindow": "Open a small, disposable window for a quick look.",
"reopenClosedTab": "Bring back the tab you closed last.",
"editURL": "Open the command bar to search or enter a URL.",
@@ -287,7 +288,8 @@ enum ShortcutDescriptions {
"pinTab": "Pin the tab or unpin it.",
"nextTab": "Switch to the next tab.",
"previousTab": "Switch to the previous tab.",
- "recentTab": "Switch between recently used tabs.",
+ "recentTab": "Open the tab switcher and cycle through recent tabs, like ⌘Tab for apps.",
+ "recentTabBackward": "Cycle backwards through recent tabs in the tab switcher.",
"clearToday": "Archive all of today’s tabs.",
"favoriteTab": "Add the tab to the favorites grid.",
"renameTab": "Give the tab a name of your own.",
diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swift
index 0165d97..a59c792 100644
--- a/Sources/Cra/UI/ShellView.swift
+++ b/Sources/Cra/UI/ShellView.swift
@@ -562,8 +562,11 @@ final class ShellView: NSView {
}
statusHost.isHidden = !statusVisible
statusHost.frame = NSRect(x: wb.minX, y: wb.minY, width: min(540, wb.width), height: 34)
- toastHost.isHidden = toastCount == 0
- toastHost.frame = NSRect(x: wb.maxX - 330, y: wb.minY, width: 330, height: CGFloat(toastCount) * 76 + 20)
+ if toastHost.superview === overlayParent {
+ let size = Self.toastStackSize(count: toastCount)
+ toastHost.isHidden = toastCount == 0
+ toastHost.frame = NSRect(x: wb.maxX - size.width, y: wb.minY, width: size.width, height: size.height)
+ }
if findHost.superview === overlayParent {
let size = CraMetrics.findBarSize, inset = CraMetrics.findBarInset
findHost.isHidden = !findVisible
@@ -572,16 +575,25 @@ final class ShellView: NSView {
if !animatingPanes, paneCards.allSatisfy({ $0.frozenWebBounds == nil }) { onPaneFrames?(paneWebFrames(layout)) }
}
- /// Chrome-style hosting: overlays move into a panel above the page windows, and
- /// the find bar into its own panel (FindBarPanel), which the window controller places.
- func moveOverlays(to view: NSView, findBar: NSPanel) {
+ /// The download toast stack, bottom trailing over the focused page.
+ static func toastStackSize(count: Int) -> NSSize {
+ NSSize(width: 330, height: CGFloat(count) * 76 + 20)
+ }
+
+ /// Chrome-style hosting: the status bubble moves into a click-through panel above the
+ /// page windows; the find bar and the toasts, which take clicks, each into their own
+ /// panel just their size, which the window controller places.
+ func moveOverlays(to view: NSView, findBar: NSPanel, toasts: NSPanel) {
overlayParent = view
- for h in [statusHost, toastHost] { h.removeFromSuperview(); view.addSubview(h) }
- findHost.removeFromSuperview()
- findHost.isHidden = false
- findHost.autoresizingMask = [.width, .height]
- findHost.frame = findBar.contentView!.bounds
- findBar.contentView!.addSubview(findHost)
+ statusHost.removeFromSuperview()
+ view.addSubview(statusHost)
+ for (host, panel) in [(findHost, findBar), (toastHost, toasts)] {
+ host.removeFromSuperview()
+ host.isHidden = false
+ host.autoresizingMask = [.width, .height]
+ host.frame = panel.contentView!.bounds
+ panel.contentView!.addSubview(host)
+ }
needsLayout = true
}
diff --git a/Sources/Cra/UI/Sidebar/DownloadsTray.swift b/Sources/Cra/UI/Sidebar/DownloadsTray.swift
new file mode 100644
index 0000000..2b211fd
--- /dev/null
+++ b/Sources/Cra/UI/Sidebar/DownloadsTray.swift
@@ -0,0 +1,126 @@
+import AppKit
+import SwiftUI
+
+/// Arc's downloads list: hovering the Library button lists the recent downloads over the
+/// bottom of the sidebar, newest at the bottom, and the tab list behind them fades out.
+/// Measured on Arc 1.170 (window captures at 60 fps, 27 Oct 2026): rows 56 pt apart, a
+/// 40 pt thumbnail with 6 pt corners 8 pt in, the name at x 61 (14 pt, white 82 %) and
+/// "54 seconds ago" under it (12 pt, white 50 %); the last row ends 2 pt below the list
+/// area. The tab list is hidden from 3 pt above the first row and fades back in over the
+/// 170 pt above that. It opens 0.2 s into the hover, rows rising 5 pt and fading in bottom
+/// first 25 ms apart; it closes 0.07 s after the pointer leaves.
+enum DownloadsTrayMetrics {
+ static let rowPitch: CGFloat = 56
+ static let thumbnail: CGFloat = 40
+ static let fade: CGFloat = 170
+ static func listHeight(rows: Int) -> CGFloat { rows == 0 ? 0 : CGFloat(rows) * rowPitch - (rowPitch - thumbnail) }
+}
+
+extension SidebarUIState {
+ func downloadsHoverChanged() {
+ downloadsListWork?.cancel()
+ let open = (libraryHovered || downloadsListHovered) && !DownloadHistory.shared.recent.isEmpty
+ guard open != downloadsListOpen else { return }
+ let work = DispatchWorkItem { [weak self] in MainActor.assumeIsolated { self?.downloadsListOpen = open } }
+ downloadsListWork = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + (open ? 0.2 : 0.07), execute: work)
+ }
+}
+
+struct DownloadsTray: View {
+ let palette: SpacePalette
+ @Environment(SidebarUIState.self) private var ui
+ private var history: DownloadHistory { .shared }
+
+ var body: some View {
+ let entries = history.recent
+ let open = ui.downloadsListOpen
+ TimelineView(.periodic(from: .now, by: 1)) { context in
+ VStack(alignment: .leading, spacing: DownloadsTrayMetrics.rowPitch - DownloadsTrayMetrics.thumbnail) {
+ ForEach(Array(entries.enumerated()), id: \.element.id) { i, entry in
+ let fromBottom = Double(entries.count - 1 - i)
+ DownloadsTrayRow(entry: entry, palette: palette, now: context.date)
+ .opacity(open ? 1 : 0)
+ .offset(y: open ? 0 : 5)
+ .animation(open ? .easeOut(duration: 0.12).delay(fromBottom * 0.025)
+ : .easeIn(duration: 0.05).delay(fromBottom * 0.015), value: open)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ .allowsHitTesting(open)
+ .onHover { ui.downloadsListHovered = $0; ui.downloadsHoverChanged() }
+ .offset(y: 2)
+ }
+}
+
+private struct DownloadsTrayRow: View {
+ let entry: DownloadHistory.Entry
+ let palette: SpacePalette
+ let now: Date
+ private var ink: Color { palette.isDark ? .white : .black }
+
+ var body: some View {
+ Button { NSWorkspace.shared.open(URL(fileURLWithPath: entry.path)) } label: {
+ HStack(spacing: 13) {
+ Group {
+ if let image = DownloadHistory.shared.thumbnail(for: entry.path) {
+ Image(nsImage: image).resizable().aspectRatio(contentMode: .fill)
+ } else {
+ Color.white.opacity(0.9)
+ }
+ }
+ .frame(width: DownloadsTrayMetrics.thumbnail, height: DownloadsTrayMetrics.thumbnail)
+ .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))
+ VStack(alignment: .leading, spacing: -1) {
+ Text((entry.path as NSString).lastPathComponent)
+ .font(.system(size: 14))
+ .foregroundStyle(ink.opacity(0.82))
+ .lineLimit(1).truncationMode(.middle)
+ Text(Self.age.localizedString(for: min(entry.date, now), relativeTo: now))
+ .font(.system(size: 12))
+ .foregroundStyle(ink.opacity(0.5))
+ }
+ .padding(.top, 1)
+ }
+ .padding(.leading, 8)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .onDrag { NSItemProvider(contentsOf: URL(fileURLWithPath: entry.path)) ?? NSItemProvider() }
+ }
+
+ /// "54 seconds ago", "6 minutes ago".
+ private static let age: RelativeDateTimeFormatter = {
+ let f = RelativeDateTimeFormatter()
+ f.unitsStyle = .full
+ return f
+ }()
+}
+
+/// Hides the tab list under the downloads list and fades it back in above it. One
+/// gradient sized by a GeometryReader: fixed-height layers here raised the sidebar's
+/// minimum height and the window grew to fit them.
+struct DownloadsTrayMask: View {
+ let rows: Int
+ let open: Bool
+
+ var body: some View {
+ ZStack {
+ Color.black.opacity(open ? 0 : 1)
+ GeometryReader { g in
+ let h = max(g.size.height, 1)
+ let clearTop = max(0, h - DownloadsTrayMetrics.listHeight(rows: rows) - 1)
+ let fadeTop = max(0, clearTop - DownloadsTrayMetrics.fade)
+ LinearGradient(stops: [.init(color: .black, location: fadeTop / h),
+ .init(color: .clear, location: clearTop / h),
+ .init(color: .clear, location: 1)],
+ startPoint: .top, endPoint: .bottom)
+ }
+ .opacity(open ? 1 : 0)
+ }
+ .animation(open ? .easeOut(duration: 0.18) : .easeOut(duration: 0.13).delay(0.08), value: open)
+ }
+}
diff --git a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
index 5fb4b04..5f8a10f 100644
--- a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
+++ b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
@@ -64,7 +64,7 @@ struct FavoriteCell: View {
@State private var hover = false
@State private var targeted = false
- private var selected: Bool { store.selectedTabID(in: space.id) == item.id }
+ private var selected: Bool { store.selectedTabID(in: space.id, window: ui.windowID) == item.id }
private var tileColor: String? { item.tab?.tileColor }
private var tileIsDark: Bool { tileColor.flatMap(HexColor.luminance).map { $0 < 0.5 } ?? palette.isDark }
@@ -100,8 +100,8 @@ struct FavoriteCell: View {
.frame(height: 47)
.contentShape(RoundedRectangle(cornerRadius: 13))
.onHover { hover = $0; ui.hoverDraggable(item.id, $0) }
- .onTapGesture { ui.keyboardFocusID = nil; store.selectTab(item.id) }
- .help(item.displayTitle)
+ .onTapGesture { ui.keyboardFocusID = nil; store.selectTab(item.id, window: ui.windowID) }
+ .arcTooltip(item.displayTitle, followsCursor: true)
.draggable(SidebarDragItem.begin(item.id, session))
.dropDestination(for: SidebarDragItem.self) { items, location in
guard let d = items.first, d.id != item.id,
diff --git a/Sources/Cra/UI/Sidebar/SidebarItemView.swift b/Sources/Cra/UI/Sidebar/SidebarItemView.swift
index 979b1e3..6156b7e 100644
--- a/Sources/Cra/UI/Sidebar/SidebarItemView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarItemView.swift
@@ -68,9 +68,10 @@ struct TabRow: View {
@State private var hover = false
@State private var draft = ""
@FocusState private var renameFocused: Bool
+ @AppStorage("didShowRenameHint") private var didShowRenameHint = false
private var tab: TabData { item.tab! }
- private var selected: Bool { store.selectedTabID == item.id }
+ private var selected: Bool { store.selectedTabID(window: ui.windowID) == item.id }
/// While tabs are ⌘/⇧-picked the highlight follows the picks, not the open tab.
private var highlighted: Bool { ui.multiSelection.isEmpty ? selected : ui.multiSelection.contains(item.id) }
/// Close acts on every picked tab when this row is one of them.
@@ -114,8 +115,18 @@ struct TabRow: View {
}
}
Spacer(minLength: 4)
+ if ui.capturingTabIDs.contains(item.id) {
+ // Arc's recording indicator; a red dot by the title, with Arc's tooltip.
+ Circle().fill(Color.red).frame(width: 7, height: 7)
+ .frame(width: 16, height: 16)
+ .contentShape(Rectangle())
+ .arcTooltip("This tab is using your camera or microphone")
+ }
if tab.muted {
- Image(systemName: "speaker.slash.fill").font(.system(size: 10)).foregroundStyle(palette.textTertiary)
+ SidebarIconButton(symbol: "speaker.slash.fill", palette: palette, help: "Unmute Tab", size: 20, iconSize: 10) {
+ store.setMuted(item.id, false)
+ actions.performAction("muteTab:\(item.id)")
+ }
}
if item.isUnread && !selected && !hover {
Circle().fill(palette.textPrimary.opacity(0.55)).frame(width: 6, height: 6)
@@ -126,9 +137,24 @@ struct TabRow: View {
actions.resetPinnedTab(item.id)
}
}
- SidebarIconButton(symbol: "xmark", palette: palette,
- help: closeGroup.count > 1 ? "Close \(closeGroup.count) Tabs (⌘W)" : (pinned ? "Close (keeps the pinned tab)" : "Archive (⌘W)"), size: 22) {
- closeTabs(closeGroup)
+ if closeGroup.count > 1 {
+ SidebarIconButton(symbol: "xmark", palette: palette, help: "Close \(closeGroup.count) Tabs (⌘W)", size: 22) {
+ closeTabs(closeGroup)
+ }
+ } else if pinned && selected {
+ // Arc: the open pinned tab shows a minus; it unloads and stays pinned.
+ SidebarIconButton(symbol: "minus", palette: palette, help: "Close and Keep Pinned (⌘W)", size: 22) {
+ closeTabs([item.id])
+ }
+ } else if pinned {
+ // Arc: any other pinned tab shows ✕, which archives it out of the pinned section.
+ SidebarIconButton(symbol: "xmark", palette: palette, help: "Archive this tab", size: 22) {
+ withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { store.archiveTab(item.id, reason: .manual) }
+ }
+ } else {
+ SidebarIconButton(symbol: "xmark", palette: palette, help: "Archive (⌘W)", size: 22) {
+ closeTabs(closeGroup)
+ }
}
}
}
@@ -155,7 +181,7 @@ struct TabRow: View {
if editing { commitRename() }
ui.clearPicks(anchor: item.id)
ui.keyboardFocusID = nil
- store.selectTab(item.id)
+ store.selectTab(item.id, window: ui.windowID)
}
}
.draggable(SidebarDragItem.begin(item.id, session)) {
@@ -176,7 +202,11 @@ struct TabRow: View {
.background(RoundedRectangle(cornerRadius: 8).fill(.regularMaterial))
}
.contextMenu { contextMenu }
- .help(tab.url)
+ // Arc's row tip is the tab's title by the pointer; the close buttons' own tips win over it.
+ // Like Arc (didShowRenameHint), "Double-click to rename" rides along once.
+ .arcTooltip(editing ? "" : item.displayTitle, followsCursor: true,
+ subtitle: didShowRenameHint || item.title != nil ? nil : "Double-click to rename",
+ onShow: { if !didShowRenameHint && item.title == nil { didShowRenameHint = true } })
.modifier(SidebarDropPreview(id: item.id, palette: palette, depth: depth))
}
@@ -188,7 +218,8 @@ struct TabRow: View {
private func closeTabs(_ ids: [UUID]) {
// The open tab goes last so closing it doesn't hop through tabs about to close.
- let ordered = ids.filter { $0 != store.selectedTabID } + ids.filter { $0 == store.selectedTabID }
+ let open = store.selectedTabID(window: ui.windowID)
+ let ordered = ids.filter { $0 != open } + ids.filter { $0 == open }
withAnimation(.snappy(duration: 0.22, extraBounce: 0)) {
for id in ordered { actions.closeTab(id) }
ui.multiSelection.subtract(ids)
@@ -210,7 +241,7 @@ 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 }
+ let folders = store.children(of: store.focusedSpace(window: ui.windowID).pinnedContainerID).filter { $0.isFolder }
if !folders.isEmpty {
Menu(ids.count > 1 ? "Move \(ids.count) Tabs to Folder" : "Move to Folder") {
ForEach(folders) { f in
@@ -261,8 +292,12 @@ struct TabRow: View {
}
folderMenu([item.id])
Divider()
- Button(pinned ? "Close" : "Archive") { actions.closeTab(item.id) }
- if pinned { Button("Unpin and Archive") { store.archiveTab(item.id, reason: .manual) } }
+ if pinned {
+ if selected || loaded { Button("Close and Keep Pinned") { actions.closeTab(item.id) } }
+ Button("Archive Tab") { store.archiveTab(item.id, reason: .manual) }
+ } else {
+ Button("Archive") { actions.closeTab(item.id) }
+ }
}
}
diff --git a/Sources/Cra/UI/Sidebar/SidebarListDrop.swift b/Sources/Cra/UI/Sidebar/SidebarListDrop.swift
index 0ef0b0e..5e7cd53 100644
--- a/Sources/Cra/UI/Sidebar/SidebarListDrop.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarListDrop.swift
@@ -224,7 +224,7 @@ struct SidebarListDropDelegate: DropDelegate {
if c.isFolder, store.isExpanded(c.id) { walk(store.children(of: c.id), depth + 1) }
}
}
- walk(store.listedPinnedItems(in: space), 0)
+ walk(store.listedPinnedItems(in: space, window: ui.windowID), 0)
walk(store.children(of: space.todayContainerID), 0)
return out
}
diff --git a/Sources/Cra/UI/Sidebar/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
index 82072e3..98b1056 100644
--- a/Sources/Cra/UI/Sidebar/SidebarRootView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
@@ -9,14 +9,14 @@ struct SidebarRootView: View {
@Environment(\.sidebarActions) private var actions
var body: some View {
- let space = store.focusedSpace
+ let space = store.focusedSpace(window: ui.windowID)
let palette = space.theme.palette
VStack(spacing: 0) {
SidebarTopBar(palette: palette)
// Dia's paging container: every space's list sits side by side and the
// strip follows the swipe 1:1, then a spring settles it on a page.
GeometryReader { g in
- let spaces = store.orderedSpaces
+ let spaces = store.pagedSpaces(window: ui.windowID)
let index = CGFloat(spaces.firstIndex { $0.id == space.id } ?? 0)
HStack(alignment: .top, spacing: 0) {
ForEach(spaces) { s in
@@ -36,6 +36,8 @@ struct SidebarRootView: View {
}
.frame(maxHeight: .infinity, alignment: .top)
.clipped()
+ .mask { DownloadsTrayMask(rows: DownloadHistory.shared.recent.count, open: ui.downloadsListOpen) }
+ .overlay(alignment: .bottom) { DownloadsTray(palette: palette) }
UpdateBanner(palette: palette)
.padding(.horizontal, 8)
// Arc's list viewport ends 50pt above the window bottom; the dock sits centred in that band.
@@ -46,8 +48,8 @@ struct SidebarRootView: View {
}
.foregroundStyle(palette.textPrimary)
.ignoresSafeArea()
- .onChange(of: store.focusedSpaceID) { _, _ in ui.clearPicks() }
- .animation(ui.spaceSettleAnimation, value: store.focusedSpaceID)
+ .onChange(of: space.id) { _, _ in ui.clearPicks() }
+ .animation(ui.spaceSettleAnimation, value: space.id)
}
}
@@ -82,7 +84,7 @@ struct SidebarTopBar: View {
Spacer()
if compact {
headerNavButtons
- } else if let t = store.selectedTab?.tab, store.settings.isDeveloperMode(url: t.url) {
+ } else if let t = store.selectedTab(window: ui.windowID)?.tab, store.settings.isDeveloperMode(url: t.url) {
navButtons
}
}
@@ -138,7 +140,7 @@ struct SidebarTopBar: View {
}
private var urlPill: some View {
- let tab = store.selectedTab
+ let tab = store.selectedTab(window: ui.windowID)
let url = tab?.tab?.url ?? ""
let host = URL(string: url)?.host ?? ""
let shape = RoundedRectangle(cornerRadius: 10, style: .continuous)
@@ -180,7 +182,7 @@ struct SidebarTopBar: View {
.contentShape(shape)
.onHover { hoverPill = $0 }
.animation(.easeOut(duration: 0.15), value: hoverHeader)
- .help(url)
+ .arcTooltip(url, followsCursor: true)
}
/// Arc's URL-bar accessories: pinned extensions, Copy Link, then the site controls
@@ -225,7 +227,7 @@ private struct PillImageButton: View {
}
.buttonStyle(.plain)
.onHover { hover = $0 }
- .help(help)
+ .arcTooltip(help)
}
}
@@ -233,6 +235,8 @@ struct SidebarIconButton: View {
let symbol: String
let palette: SpacePalette
var help: String = ""
+ /// Tooltip while ⌥ is held, for buttons that do something else on ⌥-click.
+ var optionHelp: String? = nil
var enabled: Bool = true
var size: CGFloat = 28
var height: CGFloat? = nil
@@ -263,7 +267,7 @@ struct SidebarIconButton: View {
.buttonStyle(.plain)
.disabled(!enabled)
.onHover { hover = $0 }
- .help(help)
+ .arcTooltip(help, optionHelp: optionHelp)
}
}
@@ -391,7 +395,7 @@ struct SpaceSectionView: View {
private var rows: some View {
let todayItems = store.children(of: space.todayContainerID)
- let pinnedItems = store.listedPinnedItems(in: space)
+ let pinnedItems = store.listedPinnedItems(in: space, window: ui.windowID)
return VStack(alignment: .leading, spacing: 0) {
VStack(spacing: CraMetrics.rowSpacing) {
ForEach(pinnedItems) { item in
@@ -415,6 +419,7 @@ struct SpaceSectionView: View {
if hoverDivider && !todayItems.isEmpty {
Button("Clear") { store.clearToday(space.id) }
.buttonStyle(.plain)
+ .arcTooltip("Clear Today tabs")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(palette.textSecondary)
.transition(.opacity)
diff --git a/Sources/Cra/UI/Sidebar/SpaceDock.swift b/Sources/Cra/UI/Sidebar/SpaceDock.swift
index e1274a9..757ac7d 100644
--- a/Sources/Cra/UI/Sidebar/SpaceDock.swift
+++ b/Sources/Cra/UI/Sidebar/SpaceDock.swift
@@ -5,19 +5,23 @@ import SwiftUI
struct SpaceDock: View {
let palette: SpacePalette
@Environment(SidebarStore.self) private var store
+ @Environment(SidebarUIState.self) private var ui
@Environment(\.sidebarActions) private var actions
var body: some View {
HStack(spacing: 0) {
LibraryButton(palette: palette) { actions.showArchive() }
Spacer(minLength: 0)
- HStack(spacing: 6) {
- ForEach(store.orderedSpaces) { space in
- SpaceDockButton(space: space, palette: palette, selected: space.id == store.focusedSpaceID)
+ // An incognito window has one space of its own: nothing to switch to or add.
+ if !store.window(ui.windowID).isIncognito {
+ HStack(spacing: 6) {
+ ForEach(store.orderedSpaces) { space in
+ SpaceDockButton(space: space, palette: palette, selected: space.id == store.focusedSpaceID(window: ui.windowID))
+ }
}
+ Spacer(minLength: 0)
+ SidebarIconButton(symbol: "plus", palette: palette, help: "New Space") { actions.editSpace(nil) }
}
- Spacer(minLength: 0)
- SidebarIconButton(symbol: "plus", palette: palette, help: "New Space") { actions.editSpace(nil) }
}
.frame(height: 36)
}
@@ -28,6 +32,7 @@ struct SpaceDockButton: View {
let palette: SpacePalette
let selected: Bool
@Environment(SidebarStore.self) private var store
+ @Environment(SidebarUIState.self) private var ui
@Environment(\.sidebarActions) private var actions
@State private var hover = false
@State private var targeted = false
@@ -41,8 +46,8 @@ struct SpaceDockButton: View {
.background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(targeted ? palette.hoverFill : .clear))
.contentShape(Rectangle())
.onHover { hover = $0 }
- .onTapGesture { store.focusSpace(space.id) }
- .help(space.title)
+ .onTapGesture { store.focusSpace(space.id, window: ui.windowID) }
+ .arcTooltip(space.title)
.dropDestination(for: SidebarDragItem.self) { items, _ in
guard let d = items.first else { return false }
store.moveTab(d.id, toSpace: space.id)
@@ -53,7 +58,7 @@ struct SpaceDockButton: View {
// item can be carried into that space's list and dropped in place.
guard t, !selected else { return }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- if targeted { store.focusSpace(space.id) }
+ if targeted { store.focusSpace(space.id, window: ui.windowID) }
}
}
.contextMenu {
@@ -62,7 +67,7 @@ struct SpaceDockButton: View {
Button("Move Left") { if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: max(0, i - 1)) } }
Button("Move Right") { if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: i + 1) } }
Divider()
- Button("Delete Space…") { store.focusSpace(space.id); actions.performAction("deleteSpace") }
+ Button("Delete Space…") { store.focusSpace(space.id, window: ui.windowID); actions.performAction("deleteSpace") }
}
}
}
@@ -73,11 +78,27 @@ struct SpaceDockButton: View {
struct LibraryButton: View {
let palette: SpacePalette
let action: () -> Void
+ @Environment(SidebarUIState.self) private var ui
@State private var hover = false
+ /// Where Arc's download bin rests relative to the Library glyph's centre: up and to
+ /// the right, the glyph's box peeking out under its lower-left corner.
+ static let binOffset = CGSize(width: 9, height: -12)
+
var body: some View {
+ libraryGlyph
+ .background(LibraryAnchor(ui: ui))
+ .overlay {
+ if let download = ui.recentDownload {
+ DownloadBin(download: download, dimmed: !ui.appActive)
+ .offset(Self.binOffset)
+ }
+ }
+ }
+
+ private var libraryGlyph: some View {
let ink = palette.isDark ? Color.white.opacity(0.55) : Color.black.opacity(0.26)
- Button(action: action) {
+ return Button(action: action) {
ZStack(alignment: .top) {
// Arc's box has no lid line: a 13×10 rounded box with a light slot near the top.
RoundedRectangle(cornerRadius: 2.5, style: .continuous)
@@ -99,7 +120,68 @@ struct LibraryButton: View {
.background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(hover ? palette.hoverFill : .clear))
}
.buttonStyle(.plain)
- .onHover { hover = $0 }
- .help("Library (⇧⌘L)")
+ .onHover { hover = $0; ui.libraryHovered = $0; ui.downloadsHoverChanged() }
+ .arcTooltip("Library (⇧⌘L)")
+ }
+}
+
+/// Arc's download "bin" (DownloadsUI.DownloadToLibrary): the file's thumbnail, 32 pt with
+/// 8 pt corners, lands over the Library button as the download glyph is launched at it.
+/// It drops in from 6 pt above, overshoots 12 pt below, and settles (measured on Arc 1.170
+/// at 60 fps). Arc draws it faint while its window is in the background.
+private struct DownloadBin: View {
+ let download: RecentDownload
+ let dimmed: Bool
+ @Environment(SidebarUIState.self) private var ui
+ /// Keyframes run when their trigger changes, and the bin is a new view per download.
+ @State private var drops = 0
+
+ var body: some View {
+ Button { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: download.path)]) } label: {
+ Image(nsImage: download.image)
+ .resizable()
+ .aspectRatio(contentMode: .fill)
+ .frame(width: 32, height: 32)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ .opacity(dimmed ? 0.4 : 1)
+ .keyframeAnimator(initialValue: BinMotion(), trigger: drops) { content, m in
+ content.offset(y: m.y).opacity(m.opacity)
+ } keyframes: { _ in
+ KeyframeTrack(\.y) {
+ LinearKeyframe(-6, duration: 0)
+ CubicKeyframe(12, duration: 0.15)
+ LinearKeyframe(12, duration: 0.05)
+ CubicKeyframe(-2, duration: 0.13)
+ CubicKeyframe(0, duration: 0.07)
+ }
+ KeyframeTrack(\.opacity) {
+ LinearKeyframe(0, duration: 0)
+ LinearKeyframe(1, duration: 0.05)
+ }
+ }
+ }
+ .buttonStyle(.plain)
+ .frame(width: 28, height: 28)
+ .onHover { ui.libraryHovered = $0; ui.downloadsHoverChanged() }
+ .arcTooltip((download.path as NSString).lastPathComponent)
+ .onAppear { drops += 1 }
+ .onChange(of: download.id) { drops += 1 }
+ }
+}
+
+private struct BinMotion {
+ var y: CGFloat = 0
+ var opacity: Double = 1
+}
+
+/// Hands the Library button's NSView to the window controller, which aims download
+/// flights at it (the sidebar can live in the window or in the floating sidebar panel).
+private struct LibraryAnchor: NSViewRepresentable {
+ let ui: SidebarUIState
+ func makeNSView(context: Context) -> NSView {
+ let v = NSView()
+ ui.libraryAnchor = v
+ return v
}
+ func updateNSView(_ nsView: NSView, context: Context) { ui.libraryAnchor = nsView }
}
diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swift
index 7fd38ec..c2f285c 100644
--- a/Sources/Cra/UI/SidebarUIState.swift
+++ b/Sources/Cra/UI/SidebarUIState.swift
@@ -7,12 +7,16 @@ import UniformTypeIdentifiers
@MainActor
@Observable
final class SidebarUIState {
+ /// The browser window this sidebar belongs to (its space and open tab, see WindowSession).
+ @ObservationIgnored var windowID = UUID()
var renamingID: UUID?
var draggingID: UUID?
var hoveredTabID: UUID?
/// Loading progress per tab (0...1), fed by the browser manager.
var progress: [UUID: Double] = [:]
var loadedTabIDs: Set<UUID> = []
+ /// Tabs using the camera or microphone (Arc's recording indicator).
+ var capturingTabIDs: Set<UUID> = []
var canGoBack = false
var canGoForward = false
var isLoading = false
@@ -21,6 +25,17 @@ final class SidebarUIState {
var appActive = true
/// Page theme colour of the visible tab ("#RRGGBB" or "").
var pageThemeColor = ""
+ /// The latest download, drawn over the Library button the way Arc does (its
+ /// DownloadToLibrary "bin": the file's thumbnail that the download glyph flies into).
+ var recentDownload: RecentDownload?
+ /// The Library button's view, where download flights land.
+ @ObservationIgnored weak var libraryAnchor: NSView?
+ /// Arc's downloads list over the bottom of the sidebar, open while the Library
+ /// button (or the list) is hovered.
+ var downloadsListOpen = false
+ @ObservationIgnored var libraryHovered = false
+ @ObservationIgnored var downloadsListHovered = false
+ @ObservationIgnored var downloadsListWork: DispatchWorkItem?
/// Tab chosen from the keyboard; Arc draws its yellow/black dashed ring
/// around it until the mouse picks another tab.
var keyboardFocusID: UUID?
@@ -83,9 +98,10 @@ final class SidebarUIState {
/// ⌘-click toggles a tab, ⇧-click adds the run of rows from the anchor.
/// The open tab counts as picked when a selection starts (Finder-style).
func pick(_ id: UUID, range: Bool, in store: SidebarStore) {
- let order = store.listedTabIDs(in: store.focusedSpaceID)
- if multiSelection.isEmpty, let open = store.selectedTabID, order.contains(open) { multiSelection = [open] }
- if range, let a = order.firstIndex(of: selectionAnchor ?? store.selectedTabID ?? id), let b = order.firstIndex(of: id) {
+ let order = store.listedTabIDs(in: store.focusedSpaceID(window: windowID))
+ let open = store.selectedTabID(window: windowID)
+ if multiSelection.isEmpty, let open, order.contains(open) { multiSelection = [open] }
+ if range, let a = order.firstIndex(of: selectionAnchor ?? open ?? id), let b = order.firstIndex(of: id) {
multiSelection.formUnion(order[min(a, b)...max(a, b)])
} else {
if multiSelection.contains(id) { multiSelection.remove(id) } else { multiSelection.insert(id) }
@@ -97,7 +113,7 @@ final class SidebarUIState {
/// 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) }
+ return store.listedTabIDs(in: store.focusedSpaceID(window: windowID)).filter { multiSelection.contains($0) }
}
func clearPicks(anchor: UUID? = nil) {
@@ -112,6 +128,13 @@ struct ToolbarStatus: Equatable, Identifiable {
let text: String
}
+struct RecentDownload: Equatable {
+ let id: UInt32
+ var path: String
+ /// The file type's icon until the download finishes, then its Quick Look thumbnail.
+ var image: NSImage
+}
+
struct TabNavState: Equatable {
var canGoBack = false
var canGoForward = false
diff --git a/Sources/Cra/UI/SiteControlCenter.swift b/Sources/Cra/UI/SiteControlCenter.swift
index 44bf4e6..89d253e 100644
--- a/Sources/Cra/UI/SiteControlCenter.swift
+++ b/Sources/Cra/UI/SiteControlCenter.swift
@@ -115,7 +115,7 @@ struct SiteControlCenterView: View {
.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")
+ .arcTooltip(isSecure ? "Your connection to this site is secure" : "Your connection to this site is not secure")
Spacer(minLength: 0)
SiteControlCenterMoreButton(colors: colors, actions: actions)
}
@@ -196,7 +196,7 @@ private struct SiteControlCenterTile<Label: View>: View {
}
.buttonStyle(.plain)
.onHover { hovered = $0 }
- .help(help)
+ .arcTooltip(help)
}
}
@@ -221,7 +221,7 @@ private struct SiteControlCenterActionButton: View {
}
.buttonStyle(.plain)
.onHover { hovered = $0 }
- .help(help)
+ .arcTooltip(help)
}
}
@@ -250,7 +250,7 @@ private struct SiteControlCenterExtensionButton: View {
.contentShape(Rectangle())
}
.buttonStyle(.plain)
- .help(entry.name)
+ .arcTooltip(entry.name)
.accessibilityLabel(entry.name)
if pinned || hovered {
Button(action: togglePin) {
@@ -264,7 +264,7 @@ private struct SiteControlCenterExtensionButton: View {
.contentShape(Circle())
}
.buttonStyle(.plain)
- .help(pinned ? "Unpin" : "Pin")
+ .arcTooltip(pinned ? "Unpin" : "Pin")
.accessibilityLabel(pinned ? "Unpin" : "Pin")
.offset(x: 37, y: 21)
}
@@ -323,7 +323,7 @@ private struct SiteControlCenterMoreButton: View {
}
.buttonStyle(.plain)
.onHover { hovered = $0 }
- .help("More")
+ .arcTooltip("More")
.accessibilityLabel("More")
}
diff --git a/Sources/Cra/UI/SplitView/PaneCardView.swift b/Sources/Cra/UI/SplitView/PaneCardView.swift
index a8fd24b..9613c8f 100644
--- a/Sources/Cra/UI/SplitView/PaneCardView.swift
+++ b/Sources/Cra/UI/SplitView/PaneCardView.swift
@@ -15,6 +15,10 @@ final class PaneCardView: NSView {
/// The card behind the toolbar, in the toolbar's colour. A card with a page paints nothing else:
/// under the page window's anti-aliased corners any fill of the card's shape shows as a light rim.
private let toolbarBackground = NSView()
+ /// The page's stand-in fill under the page window, inset from the card's rounded edges: the
+ /// page window's corners are anti-aliased, so a fill reaching the card's edge showed through
+ /// them as a light rim in every rounded corner.
+ private let pageBackground = NSView()
var showToolbar = true { didSet { needsLayout = true } }
var toolbarHeight: CGFloat = CraMetrics.toolbarHeight { didSet { needsLayout = true } }
var cornerRadius: CGFloat = CraMetrics.contentCornerRadius { didSet { layer?.cornerRadius = cornerRadius; needsLayout = true } }
@@ -43,11 +47,13 @@ final class PaneCardView: NSView {
layer?.masksToBounds = true
toolbarHost.sizingOptions = []
webArea.wantsLayer = true
- webArea.layer?.cornerCurve = .continuous
webArea.autoresizesSubviews = false
+ pageBackground.wantsLayer = true
+ pageBackground.layer?.cornerCurve = .continuous
toolbarBackground.wantsLayer = true
hairline.wantsLayer = true
hairline.isHidden = true
+ addSubview(pageBackground)
addSubview(webArea)
addSubview(toolbarBackground)
addSubview(hairline)
@@ -64,7 +70,7 @@ final class PaneCardView: NSView {
let bar = toolbarColor.map { NSColor(Color(hex: $0)) } ?? .white
toolbarBackground.layer?.backgroundColor = (hasPage && !transparent ? bar : NSColor.clear).cgColor
let page = pageColor.map { NSColor(Color(hex: $0)) } ?? .white
- webArea.layer?.backgroundColor = (hasPage && !transparent ? page : NSColor.clear).cgColor
+ pageBackground.layer?.backgroundColor = (hasPage && !transparent ? page : NSColor.clear).cgColor
hairline.isHidden = hasPage || transparent || !showToolbar
hairline.layer?.backgroundColor = NSColor(white: isDark ? 1 : 0, alpha: 0.08).cgColor
}
@@ -79,11 +85,18 @@ final class PaneCardView: NSView {
hairline.frame = NSRect(x: 0, y: b.height - th - 1, width: b.width, height: 1)
hairline.isHidden = hasPage || transparent || th == 0
webArea.frame = NSRect(x: 0, y: 0, width: b.width, height: max(0, b.height - th))
- // The page window rounds the card's corners itself; its stand-in fill rounds a little
- // more so it stays inside the page's edge instead of fringing it.
- webArea.layer?.cornerRadius = cornerRadius > 0 ? cornerRadius + 3 : 0
- webArea.layer?.maskedCorners = th == 0 ? [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
- : [.layerMinXMinYCorner, .layerMaxXMinYCorner]
+ // The page window rounds the card's corners itself. Its stand-in fill keeps 1 pt clear of
+ // every rounded edge: the same radius on the inset rect stays at least 1 pt inside the
+ // page's curve, so the page's edge pixels only ever blend with the gradient behind the card.
+ let rounded = cornerRadius > 0
+ let inset: CGFloat = rounded ? 1 : 0
+ var fill = webArea.frame.insetBy(dx: inset, dy: 0)
+ fill.origin.y += inset
+ fill.size.height = max(0, fill.height - (th == 0 ? 2 * inset : inset))
+ pageBackground.frame = fill
+ pageBackground.layer?.cornerRadius = rounded ? cornerRadius : 0
+ pageBackground.layer?.maskedCorners = th == 0 ? [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
+ : [.layerMinXMinYCorner, .layerMaxXMinYCorner]
let wb = frozenWebBounds ?? webArea.bounds
for sub in webArea.subviews where sub.frame != wb { sub.frame = wb }
}
diff --git a/Sources/Cra/UI/SplitView/SplitRow.swift b/Sources/Cra/UI/SplitView/SplitRow.swift
index ec4bead..9d046fd 100644
--- a/Sources/Cra/UI/SplitView/SplitRow.swift
+++ b/Sources/Cra/UI/SplitView/SplitRow.swift
@@ -14,7 +14,7 @@ struct SplitRow: View {
@State private var hover = false
private var children: [SidebarItem] { store.children(of: item.id).filter { $0.isTab } }
- private var selected: Bool { store.selectedTabID.map { id in children.contains { $0.id == id } } ?? false }
+ private var selected: Bool { store.selectedTabID(window: ui.windowID).map { id in children.contains { $0.id == id } } ?? false }
enum Metrics {
static let separatorInset: CGFloat = 9
@@ -26,7 +26,7 @@ struct SplitRow: View {
if i > 0 {
Rectangle().fill(palette.separator).frame(width: 1).padding(.vertical, Metrics.separatorInset)
}
- SplitChildCell(item: child, palette: palette, groupHovered: hover, groupSelected: selected, focused: store.selectedTabID == child.id)
+ SplitChildCell(item: child, palette: palette, groupHovered: hover, groupSelected: selected, focused: store.selectedTabID(window: ui.windowID) == child.id)
}
}
.padding(.leading, CGFloat(depth) * CraMetrics.indent)
@@ -76,7 +76,7 @@ struct SplitChildCell: View {
.truncationMode(.tail)
Spacer(minLength: 2)
if hover {
- SidebarIconButton(symbol: "xmark", palette: palette, help: "Close pane", size: 20, iconSize: 11) {
+ SidebarIconButton(symbol: "xmark", palette: palette, help: "Close pane", optionHelp: "Separate from Split View", size: 20, iconSize: 11) {
// Option-click un-splits instead of closing (Arc flag option-click-split-tab-close-button-to-unsplit).
if NSEvent.modifierFlags.contains(.option) { store.separateFromSplit(item.id) } else { actions.closeTab(item.id) }
}
@@ -88,7 +88,7 @@ struct SplitChildCell: View {
.frame(maxWidth: .infinity, maxHeight: .infinity)
.contentShape(Rectangle())
.onHover { hover = $0; ui.hoverDraggable(item.id, $0) }
- .onTapGesture { store.selectTab(item.id) }
+ .onTapGesture { store.selectTab(item.id, window: ui.windowID) }
.draggable(SidebarDragItem.begin(item.id, session)) {
HStack(spacing: 8) {
FaviconView(key: item.tab?.iconKey, palette: palette)
@@ -106,6 +106,6 @@ struct SplitChildCell: View {
Divider()
Button("Close") { actions.closeTab(item.id) }
}
- .help(item.tab?.url ?? "")
+ .arcTooltip(item.displayTitle, followsCursor: true)
}
}
diff --git a/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift b/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift
new file mode 100644
index 0000000..609714d
--- /dev/null
+++ b/Sources/Cra/UI/TabSwitcher/TabSwitcher.swift
@@ -0,0 +1,159 @@
+import AppKit
+import Observation
+import SwiftUI
+
+/// Arc's tab switcher (ModalItemSwitcher): ⌃Tab shows the space's five most recent tabs
+/// the way ⌘Tab shows apps. While ⌃ is held, Tab / ⇧Tab and ← / → move the selection
+/// (wrapping) and the pointer picks the card it moves over; releasing ⌃, Return or a click
+/// switches, Esc cancels. A quick tap switches to the previous tab without showing the
+/// panel. Arc 1.170 measured 27 Oct 2026: no animation on open, move or close.
+@MainActor
+@Observable
+final class TabSwitcher {
+ struct Item: Identifiable {
+ let id: UUID
+ var title: String
+ var iconKey: String?
+ var snapshot: NSImage?
+ }
+
+ private(set) var items: [Item] = []
+ var selectedIndex = 0
+ private(set) var isOpen = false
+ /// The space's selection colour and appearance, set before opening.
+ var highlight: Color = .clear
+ var isDark = true
+ var palette: SpacePalette?
+
+ @ObservationIgnored var onShow: () -> Void = {}
+ @ObservationIgnored var onHide: () -> Void = {}
+ @ObservationIgnored var onCommit: (UUID) -> Void = { _ in }
+ /// The direction a key press cycles in when it is one of the switcher's own shortcuts.
+ @ObservationIgnored var direction: (NSEvent) -> Int? = { _ in nil }
+
+ @ObservationIgnored private var hold: NSEvent.ModifierFlags = []
+ @ObservationIgnored private var monitor: Any?
+ @ObservationIgnored private var showWork: DispatchWorkItem?
+ @ObservationIgnored private var pointerAtShow: NSPoint?
+
+ init() {
+ NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { [weak self] _ in
+ Task { @MainActor in self?.cancel() }
+ }
+ }
+
+ /// The switcher's shortcut (⌃Tab forward, ⌃⇧Tab back). The first press opens it on the
+ /// next (or last) card; the shortcut's modifiers are what holds it open.
+ func cycle(_ delta: Int, event: NSEvent?, items make: () -> [Item]) {
+ if isOpen { move(delta); return }
+ let list = make()
+ guard list.count > 1 else { return }
+ items = list
+ selectedIndex = delta > 0 ? 1 : list.count - 1
+ isOpen = true
+ // From a menu or the command bar nothing is held: switch straight away.
+ let pressed = event.flatMap { $0.type == .keyDown ? $0.modifierFlags : nil } ?? []
+ hold = pressed.intersection([.control, .option, .command])
+ guard !hold.isEmpty, NSEvent.modifierFlags.isSuperset(of: hold) else { commit(); return }
+ monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .flagsChanged, .leftMouseDown, .rightMouseDown]) { [weak self] event in
+ guard let self else { return event }
+ return self.handle(event)
+ }
+ // Arc waits a moment, so a quick tap never flashes the panel.
+ let work = DispatchWorkItem { [weak self] in
+ guard let self, self.isOpen else { return }
+ self.pointerAtShow = NSEvent.mouseLocation
+ self.onShow()
+ }
+ showWork = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + TabSwitcherMetrics.showDelay, execute: work)
+ }
+
+ func move(_ delta: Int) {
+ guard !items.isEmpty else { return }
+ let n = items.count
+ selectedIndex = ((selectedIndex + delta) % n + n) % n
+ }
+
+ /// The pointer moved over a card. A panel that opens under a resting pointer keeps its
+ /// keyboard selection until the pointer moves.
+ func hover(_ index: Int) {
+ guard isOpen, NSEvent.mouseLocation != pointerAtShow else { return }
+ pointerAtShow = nil
+ selectedIndex = index
+ }
+
+ func click(_ index: Int) {
+ selectedIndex = index
+ commit()
+ }
+
+ func updateSnapshot(_ id: UUID, _ image: NSImage?) {
+ guard let image, let i = items.firstIndex(where: { $0.id == id }) else { return }
+ items[i].snapshot = image
+ }
+
+ func commit() {
+ guard isOpen else { return }
+ let id = items.indices.contains(selectedIndex) ? items[selectedIndex].id : nil
+ close()
+ if let id { onCommit(id) }
+ }
+
+ func cancel() {
+ guard isOpen else { return }
+ close()
+ }
+
+ private func close() {
+ isOpen = false
+ showWork?.cancel()
+ showWork = nil
+ if let monitor { NSEvent.removeMonitor(monitor) }
+ monitor = nil
+ pointerAtShow = nil
+ onHide()
+ }
+
+ /// Every key goes to the switcher while it is open; releasing the held modifier switches.
+ /// A click anywhere else closes it and goes through.
+ private func handle(_ event: NSEvent) -> NSEvent? {
+ if event.type == .leftMouseDown || event.type == .rightMouseDown {
+ if !(event.window is TabSwitcherPanel) { cancel() }
+ return event
+ }
+ if event.type == .flagsChanged {
+ if !event.modifierFlags.isSuperset(of: hold) { commit() }
+ return event
+ }
+ if let d = direction(event) { move(d); return nil }
+ switch event.keyCode {
+ case 48: move(event.modifierFlags.contains(.shift) ? -1 : 1) // Tab
+ case 124: move(1) // →
+ case 123: move(-1) // ←
+ case 53: cancel() // Esc
+ case 36, 76: commit() // Return, Enter
+ default: break
+ }
+ return nil
+ }
+}
+
+/// The switcher's floating window: above the page windows, never key (keys come in
+/// through the switcher's event monitor), clicks and hover still reach the cards.
+final class TabSwitcherPanel: NSPanel {
+ override var canBecomeKey: Bool { false }
+ override var canBecomeMain: Bool { false }
+
+ init() {
+ super.init(contentRect: NSRect(x: 0, y: 0, width: 100, height: 100),
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered, defer: false)
+ backgroundColor = .clear
+ isOpaque = false
+ hasShadow = false
+ hidesOnDeactivate = false
+ animationBehavior = .none
+ collectionBehavior = [.fullScreenAuxiliary, .moveToActiveSpace]
+ }
+}
diff --git a/Sources/Cra/UI/TabSwitcher/TabSwitcherView.swift b/Sources/Cra/UI/TabSwitcher/TabSwitcherView.swift
new file mode 100644
index 0000000..32d63e0
--- /dev/null
+++ b/Sources/Cra/UI/TabSwitcher/TabSwitcherView.swift
@@ -0,0 +1,194 @@
+import AppKit
+import SwiftUI
+
+/// Arc 1.170's tab switcher, measured on a 1× display (27 Oct 2026, see
+/// docs/arc-reverse-engineering.md "Tab switcher").
+enum TabSwitcherMetrics {
+ static let maxItems = 5
+ /// ⌃Tab to panel: Arc showed it 0.18–0.26 s after the key; a 0.13 s tap never showed it.
+ static let showDelay: TimeInterval = 0.15
+ static let card = CGSize(width: 180, height: 158)
+ static let thumbnail = CGSize(width: 158, height: 105)
+ static let thumbnailOrigin = CGPoint(x: 11.5, y: 12)
+ static let cardSpacing: CGFloat = 2
+ static let paddingH: CGFloat = 16.5
+ static let paddingV: CGFloat = 16
+ static let cornerRadius: CGFloat = 26
+ static let cardCornerRadius: CGFloat = 8
+ static let thumbnailCornerRadius: CGFloat = 6.5
+ static let favicon: CGFloat = 16
+ /// Room around the panel for its shadow (the window is this much larger on each side).
+ static let shadowMargin: CGFloat = 40
+
+ static func panelSize(count: Int) -> CGSize {
+ let n = CGFloat(max(count, 1))
+ return CGSize(width: paddingH * 2 + n * card.width + (n - 1) * cardSpacing, height: paddingV * 2 + card.height)
+ }
+
+ static func windowSize(count: Int) -> CGSize {
+ let p = panelSize(count: count)
+ return CGSize(width: p.width + shadowMargin * 2, height: p.height + shadowMargin * 2)
+ }
+}
+
+struct TabSwitcherView: View {
+ let switcher: TabSwitcher
+ private typealias M = TabSwitcherMetrics
+
+ var body: some View {
+ let dark = switcher.isDark
+ let shape = RoundedRectangle(cornerRadius: M.cornerRadius, style: .continuous)
+ HStack(spacing: M.cardSpacing) {
+ ForEach(Array(switcher.items.enumerated()), id: \.element.id) { i, item in
+ card(item, selected: i == switcher.selectedIndex, dark: dark)
+ .contentShape(Rectangle())
+ .onContinuousHover { phase in
+ if case .active = phase { switcher.hover(i) }
+ }
+ .onTapGesture { switcher.click(i) }
+ }
+ }
+ .padding(.horizontal, M.paddingH)
+ .padding(.vertical, M.paddingV)
+ // Arc: #1C1B1A inside a near-black outer line and a 23% white inner line.
+ .background(shape.fill(dark ? Color(red: 28 / 255, green: 27 / 255, blue: 26 / 255) : Color(white: 0.97)))
+ .overlay(shape.inset(by: 1).strokeBorder(dark ? Color.white.opacity(0.23) : Color.white.opacity(0.8), lineWidth: 1))
+ .overlay(shape.strokeBorder(dark ? Color.black.opacity(0.92) : Color.black.opacity(0.12), lineWidth: 1))
+ .shadow(color: .black.opacity(dark ? 0.3 : 0.18), radius: 24, y: 10)
+ .padding(M.shadowMargin)
+ .environment(\.colorScheme, dark ? .dark : .light)
+ }
+
+ private func card(_ item: TabSwitcher.Item, selected: Bool, dark: Bool) -> some View {
+ VStack(alignment: .leading, spacing: 0) {
+ thumbnail(item, dark: dark)
+ .frame(width: M.thumbnail.width, height: M.thumbnail.height)
+ .clipShape(RoundedRectangle(cornerRadius: M.thumbnailCornerRadius, style: .continuous))
+ .shadow(color: .black.opacity(dark ? 0.4 : 0.15), radius: 7, y: 3)
+ .padding(.leading, M.thumbnailOrigin.x)
+ .padding(.top, M.thumbnailOrigin.y)
+ HStack(spacing: 8) {
+ favicon(item, dark: dark)
+ Text(item.title)
+ // Arc's titles measure as SF 14 medium (ink width and cap height match).
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(dark ? Color.white : Color.black.opacity(0.85))
+ .lineLimit(1)
+ .truncationMode(.tail)
+ }
+ .padding(.leading, 13.5)
+ .padding(.trailing, 10.5)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ }
+ .frame(width: M.card.width, height: M.card.height, alignment: .topLeading)
+ .background {
+ if selected { RoundedRectangle(cornerRadius: M.cardCornerRadius, style: .continuous).fill(switcher.highlight) }
+ }
+ }
+
+ @ViewBuilder
+ private func thumbnail(_ item: TabSwitcher.Item, dark: Bool) -> some View {
+ if let image = item.snapshot {
+ Image(nsImage: image).resizable().interpolation(.high).aspectRatio(contentMode: .fill)
+ } else {
+ // A tab never seen since launch: Arc shows an empty #1C1C1C card.
+ Rectangle().fill(dark ? Color(white: 28 / 255) : Color(white: 0.9))
+ }
+ }
+
+ @ViewBuilder
+ private func favicon(_ item: TabSwitcher.Item, dark: Bool) -> some View {
+ if let palette = switcher.palette, item.iconKey != nil {
+ FaviconIconOrPlaceholder(key: item.iconKey, palette: palette, dark: dark)
+ } else {
+ FaviconPlaceholder(dark: dark)
+ }
+ }
+}
+
+/// Arc's switcher draws a missing favicon as a faint rounded square, not a globe.
+private struct FaviconIconOrPlaceholder: View {
+ let key: String?
+ let palette: SpacePalette
+ let dark: Bool
+ @Environment(FaviconCache.self) private var favicons
+
+ var body: some View {
+ if favicons.image(forKey: key) != nil {
+ FaviconView(key: key, palette: palette, size: TabSwitcherMetrics.favicon, onDark: dark)
+ } else {
+ FaviconPlaceholder(dark: dark)
+ }
+ }
+}
+
+private struct FaviconPlaceholder: View {
+ let dark: Bool
+ var body: some View {
+ RoundedRectangle(cornerRadius: 4.5, style: .continuous)
+ .fill(dark ? Color.white.opacity(0.14) : Color.black.opacity(0.1))
+ .frame(width: TabSwitcherMetrics.favicon, height: TabSwitcherMetrics.favicon)
+ }
+}
+
+extension SpaceTheme {
+ /// The selected card: Arc's semantic "hover" colour. In Arc's own data (JYSK and Victor
+ /// spaces) the dark one sits at OKLab lightness ≈ 0.60 in the theme's hue, close to the
+ /// most saturated colour sRGB has there, at 48% opacity; the light one is opaque at ≈ 0.885.
+ func switcherHighlight(dark: Bool) -> Color {
+ let hex = accent ?? colors.first ?? "#808080"
+ let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)
+ let lab = OKLab.from(r: c.r, g: c.g, b: c.b)
+ let chroma = (lab.a * lab.a + lab.b * lab.b).squareRoot()
+ let hue = atan2(lab.b, lab.a)
+ let L = dark ? 0.60 : 0.885
+ // Greys stay grey; anything with a clear hue gets Arc's near-full saturation.
+ let target = OKLab.maxChroma(L: L, hue: hue) * (dark ? 0.87 : 0.5) * min(1, chroma / 0.03)
+ let rgb = OKLab.toRGB(L: L, a: target * cos(hue), b: target * sin(hue))
+ return Color(.sRGB, red: rgb.r, green: rgb.g, blue: rgb.b, opacity: dark ? 0.48 : 1)
+ }
+}
+
+/// Björn Ottosson's OKLab, for colours that keep the same perceived lightness across hues.
+enum OKLab {
+ static func from(r: Double, g: Double, b: Double) -> (L: Double, a: Double, b: Double) {
+ func lin(_ c: Double) -> Double { c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4) }
+ let (lr, lg, lb) = (lin(r), lin(g), lin(b))
+ let l = cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb)
+ let m = cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb)
+ let s = cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb)
+ return (0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
+ 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s)
+ }
+
+ /// Linear-light sRGB before clamping, so callers can tell whether it is in gamut.
+ static func toLinear(L: Double, a: Double, b: Double) -> (r: Double, g: Double, b: Double) {
+ let l = pow(L + 0.3963377774 * a + 0.2158037573 * b, 3)
+ let m = pow(L - 0.1055613458 * a - 0.0638541728 * b, 3)
+ let s = pow(L - 0.0894841775 * a - 1.2914855480 * b, 3)
+ return (4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
+ -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s)
+ }
+
+ static func toRGB(L: Double, a: Double, b: Double) -> (r: Double, g: Double, b: Double) {
+ func enc(_ c: Double) -> Double {
+ let x = max(0, min(1, c))
+ return x <= 0.0031308 ? x * 12.92 : 1.055 * pow(x, 1 / 2.4) - 0.055
+ }
+ let v = toLinear(L: L, a: a, b: b)
+ return (enc(v.r), enc(v.g), enc(v.b))
+ }
+
+ /// The largest chroma at this lightness and hue that sRGB can show.
+ static func maxChroma(L: Double, hue: Double) -> Double {
+ var lo = 0.0, hi = 0.4
+ for _ in 0..<24 {
+ let mid = (lo + hi) / 2
+ let v = toLinear(L: L, a: mid * cos(hue), b: mid * sin(hue))
+ if [v.r, v.g, v.b].allSatisfy({ $0 >= 0 && $0 <= 1 }) { lo = mid } else { hi = mid }
+ }
+ return lo
+ }
+}
diff --git a/Sources/Cra/UI/Theme.swift b/Sources/Cra/UI/Theme.swift
index 3ac84c6..805e468 100644
--- a/Sources/Cra/UI/Theme.swift
+++ b/Sources/Cra/UI/Theme.swift
@@ -215,10 +215,11 @@ struct SpaceBackground: View {
var body: some View {
if let pager {
- let spaces = pager.store.orderedSpaces
- let index = spaces.firstIndex { $0.id == pager.store.focusedSpaceID } ?? 0
+ let spaces = pager.store.pagedSpaces(window: pager.ui.windowID)
+ let focused = pager.store.focusedSpaceID(window: pager.ui.windowID)
+ let index = spaces.firstIndex { $0.id == focused } ?? 0
PagedSpaceBackground(palettes: spaces.map(\.theme.palette), position: Double(index) + Double(pager.ui.spaceSwipe))
- .animation(pager.ui.spaceSettleAnimation, value: pager.store.focusedSpaceID)
+ .animation(pager.ui.spaceSettleAnimation, value: focused)
} else {
gradient
}
diff --git a/Sources/Cra/UI/Updates/UpdateBanner.swift b/Sources/Cra/UI/Updates/UpdateBanner.swift
index 9ccbf5d..9165e42 100644
--- a/Sources/Cra/UI/Updates/UpdateBanner.swift
+++ b/Sources/Cra/UI/Updates/UpdateBanner.swift
@@ -59,7 +59,7 @@ struct UpdateBanner: View {
.onHover { hoverClose = $0 }
.onTapGesture { SoftwareUpdater.shared.dismissBanner() }
.padding(6)
- .help("Dismiss")
+ .arcTooltip("Dismiss")
}
}
.contentShape(RoundedRectangle(cornerRadius: 10, style: .continuous))
diff --git a/Sources/Cra/UI/Windows/ChromeDownloadAnimation.swift b/Sources/Cra/UI/Windows/ChromeDownloadAnimation.swift
new file mode 100644
index 0000000..1cf5f62
--- /dev/null
+++ b/Sources/Cra/UI/Windows/ChromeDownloadAnimation.swift
@@ -0,0 +1,42 @@
+import AppKit
+
+/// Chrome plays a download-started animation when a download begins: a 64 pt round
+/// download glyph that fades in over the page and flies to the toolbar's download button
+/// (DownloadBubbleStartedAnimationViews, 500 ms). Cra keeps Chrome's toolbar hidden, so
+/// the glyph flies to nothing, and Cra shows its own animation like Arc. Chrome has no
+/// switch for it (only reduced motion), so its window is ordered out as soon as it
+/// appears: a views popup parented to the page (a child window), created with
+/// accept_events = false (ignores the mouse), sized 2 × kIconBackgroundRadius 32.
+@MainActor
+enum ChromeDownloadAnimation {
+ private static let size = NSSize(width: 64, height: 64)
+ /// Chrome posts the animation once the toolbar's download button has animated in.
+ private static let watchDuration: TimeInterval = 2
+ private static var watchUntil = Date.distantPast
+ private static var timer: Timer?
+
+ /// Call when a download starts.
+ static func suppress() {
+ watchUntil = Date().addingTimeInterval(watchDuration)
+ guard timer == nil else { return }
+ timer = Timer.scheduledTimer(withTimeInterval: 1.0 / 120, repeats: true) { _ in
+ MainActor.assumeIsolated { tick() }
+ }
+ }
+
+ private static func tick() {
+ for w in NSApp.windows where isAnimationWindow(w) && (w.isVisible || w.alphaValue > 0) {
+ w.alphaValue = 0
+ w.orderOut(nil)
+ }
+ if Date() >= watchUntil {
+ timer?.invalidate()
+ timer = nil
+ }
+ }
+
+ private static func isAnimationWindow(_ w: NSWindow) -> Bool {
+ w.parent != nil && w.ignoresMouseEvents && w.frame.size == size
+ && NSStringFromClass(type(of: w)).contains("NativeWidgetMac")
+ }
+}
diff --git a/Sources/Cra/UI/Windows/ChromiumChildFullscreen.swift b/Sources/Cra/UI/Windows/ChromiumChildFullscreen.swift
new file mode 100644
index 0000000..99a48cc
--- /dev/null
+++ b/Sources/Cra/UI/Windows/ChromiumChildFullscreen.swift
@@ -0,0 +1,55 @@
+import AppKit
+import ObjectiveC
+
+/// Chromium puts a page into fullscreen by making the page's own window FullScreenPrimary
+/// and calling -toggleFullScreen: on it (NativeWidgetNSWindowFullscreenController). Cra
+/// docks that window as a child of the browser window, so macOS gave it a fullscreen
+/// Space of its own next to the browser window's: every video fullscreen left another
+/// empty desktop in Mission Control. For child windows the toggle never reaches AppKit.
+/// Chromium gets the will/did enter and exit callbacks AppKit would send, and the parent
+/// window goes fullscreen instead (didChangeFullscreen in the window controllers).
+@MainActor
+enum ChromiumChildFullscreen {
+ private static let fullscreen = NSHashTable<NSWindow>.weakObjects()
+ private static var patchedClasses = Set<ObjectIdentifier>()
+
+ static func attach(_ window: NSWindow) {
+ let cls: AnyClass = type(of: window)
+ let id = ObjectIdentifier(cls)
+ guard !patchedClasses.contains(id) else { return }
+ patchedClasses.insert(id)
+ let sel = #selector(NSWindow.toggleFullScreen(_:))
+ guard let method = class_getInstanceMethod(cls, sel), let types = method_getTypeEncoding(method) else { return }
+ let original = unsafeBitCast(method_getImplementation(method), to: ToggleIMP.self)
+ let block: @convention(block) (NSWindow, AnyObject?) -> Void = { w, sender in
+ MainActor.assumeIsolated {
+ // ⌃⌘F and the View menu reach the key window, which is the page: that means the browser window.
+ if let parent = w.parent, sender != nil { return parent.toggleFullScreen(sender) }
+ // A page that went fullscreen docked and was undocked since still exits the same way.
+ guard w.parent != nil || fullscreen.contains(w) else { return original(w, sel, sender) }
+ playTransition(w)
+ }
+ }
+ let imp = imp_implementationWithBlock(block)
+ if !class_addMethod(cls, sel, imp, types) { method_setImplementation(method, imp) }
+ }
+
+ private typealias ToggleIMP = @convention(c) (NSWindow, Selector, AnyObject?) -> Void
+
+ /// AppKit calls the will-callback inside -toggleFullScreen: and the did-callback once
+ /// the animation ends; Chromium's state machine expects that order.
+ private static func playTransition(_ w: NSWindow) {
+ let entering = !fullscreen.contains(w)
+ if entering { fullscreen.add(w) } else { fullscreen.remove(w) }
+ send(entering ? "windowWillEnterFullScreen:" : "windowWillExitFullScreen:", entering ? NSWindow.willEnterFullScreenNotification : NSWindow.willExitFullScreenNotification, to: w)
+ DispatchQueue.main.async {
+ send(entering ? "windowDidEnterFullScreen:" : "windowDidExitFullScreen:", entering ? NSWindow.didEnterFullScreenNotification : NSWindow.didExitFullScreenNotification, to: w)
+ }
+ }
+
+ private static func send(_ name: String, _ notification: Notification.Name, to w: NSWindow) {
+ let sel = NSSelectorFromString(name)
+ guard let delegate = w.delegate as? NSObject, delegate.responds(to: sel) else { return }
+ delegate.perform(sel, with: Notification(name: notification, object: w))
+ }
+}
diff --git a/Sources/Cra/UI/Windows/DownloadFlight.swift b/Sources/Cra/UI/Windows/DownloadFlight.swift
new file mode 100644
index 0000000..ed12b55
--- /dev/null
+++ b/Sources/Cra/UI/Windows/DownloadFlight.swift
@@ -0,0 +1,141 @@
+import AppKit
+import QuartzCore
+
+/// Arc's download animation (DownloadsUI.DownloadToLibrary: a window over the browser
+/// window, a "projectile" icon with g, vx0, vy0, apex and apexTime, and a "bin" at the
+/// Library button). Measured on Arc 1.170 at 60 fps, 27 Oct 2026:
+/// - the glyph launches from the pointer as the download starts, rises 90 pt to its apex,
+/// then falls under g ≈ 2630 pt/s² at a constant horizontal speed onto the Library
+/// button (about 1.1 s for a launch from the top of a 1084 pt window);
+/// - it is a navy disc with a light ring and a down arrow, 32 pt at launch, 48 pt at the
+/// apex, shrinking linearly to 10 pt on arrival; it fades in over the climb, and the
+/// arrow turns from ↘ to ↓ during the first half of the flight;
+/// - a faint blue glow surrounds it.
+@MainActor
+enum DownloadFlight {
+ nonisolated static let gravity: CGFloat = 2630
+ nonisolated static let apexHeight: CGFloat = 90
+ private static let maxDiameter: CGFloat = 48
+ private static var flights: [NSPanel] = []
+
+ /// Flies the glyph from `from` to `to` (screen points) over `window`; returns the
+ /// flight time.
+ @discardableResult
+ static func launch(over window: NSWindow, from: NSPoint, to: NSPoint) -> TimeInterval {
+ let frame = window.frame
+ let panel = NSPanel(contentRect: frame, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = false
+ panel.ignoresMouseEvents = true
+ panel.hidesOnDeactivate = false
+ let view = FlippedView(frame: NSRect(origin: .zero, size: frame.size))
+ view.wantsLayer = true
+ panel.contentView = view
+ window.addChildWindow(panel, ordered: .above)
+
+ // Top-left coordinates inside the panel, like Arc's window-sized view.
+ func local(_ p: NSPoint) -> CGPoint { CGPoint(x: p.x - frame.minX, y: frame.maxY - p.y) }
+ let path = Trajectory(start: local(from), end: local(to))
+
+ let icon = CALayer()
+ icon.bounds = CGRect(x: 0, y: 0, width: maxDiameter, height: maxDiameter)
+ icon.contents = glyph
+ icon.contentsScale = window.backingScaleFactor
+ icon.shadowColor = NSColor(red: 0.1, green: 0.42, blue: 0.85, alpha: 1).cgColor
+ icon.shadowOpacity = 0.55
+ icon.shadowRadius = 9
+ icon.shadowOffset = .zero
+ icon.opacity = 0
+ view.layer?.addSublayer(icon)
+
+ let samples = 66
+ var positions: [NSValue] = [], transforms: [NSValue] = [], opacities: [NSNumber] = [], times: [NSNumber] = []
+ for i in 0...samples {
+ let p = CGFloat(i) / CGFloat(samples)
+ positions.append(NSValue(point: path.point(at: p * path.duration)))
+ let apexP = path.apexTime / path.duration
+ // Diameter: 32 → 48 at the apex → 10 on arrival.
+ let d = p < apexP ? 32 + 16 * p / apexP : 48 - 38 * (p - apexP) / (1 - apexP)
+ let turn = min(1, p / 0.5)
+ let angle = -(1 - turn * turn * (3 - 2 * turn)) * (.pi / 4) // ↘ (45°) eased to ↓
+ var t = CATransform3DMakeScale(d / maxDiameter, d / maxDiameter, 1)
+ t = CATransform3DRotate(t, angle, 0, 0, 1)
+ transforms.append(NSValue(caTransform3D: t))
+ opacities.append(NSNumber(value: Double(min(1, p / apexP))))
+ times.append(NSNumber(value: Double(p)))
+ }
+ func track(_ key: String, _ values: [Any]) -> CAKeyframeAnimation {
+ let a = CAKeyframeAnimation(keyPath: key)
+ a.values = values
+ a.keyTimes = times
+ a.calculationMode = .linear
+ return a
+ }
+ let group = CAAnimationGroup()
+ group.animations = [track("position", positions), track("transform", transforms), track("opacity", opacities)]
+ group.duration = path.duration
+ group.fillMode = .forwards
+ group.isRemovedOnCompletion = false
+
+ flights.append(panel)
+ CATransaction.begin()
+ CATransaction.setCompletionBlock {
+ MainActor.assumeIsolated {
+ window.removeChildWindow(panel)
+ panel.orderOut(nil)
+ flights.removeAll { $0 === panel }
+ }
+ }
+ icon.add(group, forKey: "flight")
+ CATransaction.commit()
+ return path.duration
+ }
+
+ /// Projectile from `start` to `end` in top-left coordinates: the apex 90 pt above the
+ /// higher of the two, gravity pulling down, horizontal speed constant.
+ struct Trajectory {
+ let start: CGPoint, end: CGPoint
+ let apexTime: CGFloat, duration: CGFloat, vx: CGFloat, vy: CGFloat
+
+ init(start: CGPoint, end: CGPoint) {
+ self.start = start
+ self.end = end
+ let apexY = min(start.y, end.y) - DownloadFlight.apexHeight
+ let g = DownloadFlight.gravity
+ apexTime = sqrt(2 * (start.y - apexY) / g)
+ duration = apexTime + sqrt(2 * (end.y - apexY) / g)
+ vy = -g * apexTime
+ vx = (end.x - start.x) / duration
+ }
+
+ func point(at t: CGFloat) -> CGPoint {
+ CGPoint(x: start.x + vx * t, y: start.y + vy * t + DownloadFlight.gravity * t * t / 2)
+ }
+ }
+
+ /// The glyph at its largest: navy disc, light ring, down arrow.
+ private static let glyph: NSImage = {
+ let d = maxDiameter
+ return NSImage(size: NSSize(width: d, height: d), flipped: false) { rect in
+ let ring: CGFloat = 2.5
+ let disc = NSBezierPath(ovalIn: rect.insetBy(dx: ring / 2, dy: ring / 2))
+ NSColor(red: 4 / 255, green: 7 / 255, blue: 42 / 255, alpha: 1).setFill()
+ disc.fill()
+ NSColor(red: 239 / 255, green: 239 / 255, blue: 1, alpha: 1).setStroke()
+ disc.lineWidth = ring
+ disc.stroke()
+ let config = NSImage.SymbolConfiguration(pointSize: d * 0.42, weight: .semibold)
+ .applying(.init(paletteColors: [NSColor(red: 239 / 255, green: 239 / 255, blue: 1, alpha: 1)]))
+ if let arrow = NSImage(systemSymbolName: "arrow.down", accessibilityDescription: nil)?.withSymbolConfiguration(config) {
+ let s = arrow.size
+ arrow.draw(in: NSRect(x: (d - s.width) / 2, y: (d - s.height) / 2, width: s.width, height: s.height))
+ }
+ return true
+ }
+ }()
+}
+
+private final class FlippedView: NSView {
+ override var isFlipped: Bool { true }
+}
diff --git a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
index 5ceb21d..fbf957a 100644
--- a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
+++ b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift
@@ -385,10 +385,12 @@ final class ExtensionPageWindow: NSWindow, NSWindowDelegate, @preconcurrency Cra
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.useNormalWindow()
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.useNormalWindow()
app.store.createTab(url: url, select: !background)
app.main.showWindow(nil)
return nil
diff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swift
index 3a6afb9..1375851 100644
--- a/Sources/Cra/UI/Windows/LittleWindowController.swift
+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift
@@ -107,6 +107,8 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
let actions = LittleWindowActions()
let commandBar: CommandBarController
private(set) var browser: CraBrowser?
+ /// The page (a video) is in element fullscreen.
+ private var pageFullscreen = false
private let shell: LittleShellView
private var favicon: NSImage?
private var promoted = false
@@ -126,7 +128,8 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
/// CEF hands it (see `CraBrowserDelegate.browser:popupHostForURL:`).
init(app: AppDelegate, url: String?) {
self.app = app
- state = LittleWindowState(targetSpaceID: app.store.focusedSpaceID)
+ // Little Windows are normal browsing: they target the last normal window's space.
+ state = LittleWindowState(targetSpaceID: app.store.focusedSpaceID(window: app.store.lastNormalWindowID))
commandBar = CommandBarController(engine: app.engine, store: app.store)
let size = app.store.prefs.littleWindowSize.map { NSSizeFromString($0) }
.flatMap { $0 == LittleMetrics.legacyDefaultSize ? nil : $0 }
@@ -201,6 +204,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
w.hasShadow = false
w.isOpaque = false
w.backgroundColor = .clear
+ ChromiumChildFullscreen.attach(w)
if let cv = w.contentView {
cv.isHidden = false // a background tab's page (MainWindowController hides it)
cv.wantsLayer = true
@@ -283,6 +287,8 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
tooltipTimer?.invalidate(); hideTooltip()
closePopup()
let prefill = hasPage ? currentURL : nil
+ // Suggestions come from the normal profile even when an incognito window was in front.
+ app.useNormalWindow()
commandBar.highlight = store.focusedSpace.theme.palette.commandHighlight
commandBar.focusedSpaceID = store.focusedSpaceID
commandBar.open(mode: hasPage ? .editURL : .newTab, prefill: prefill)
@@ -347,9 +353,11 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
switch s.kind {
case .switchToTab(let id):
store.recordQuerySelection(query: query, url: s.url ?? "")
+ app.useNormalWindow()
store.selectTab(id)
app.main.showWindow(nil)
case .archived(let id):
+ app.useNormalWindow()
store.restoreArchived(id)
app.main.showWindow(nil)
case .navigate:
@@ -467,7 +475,9 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
guard let b = browser, hasPage else { return }
closePopup()
commandBar.close()
- let sid = (spaceID ?? state.targetSpaceID).flatMap { store.space($0) != nil ? $0 : nil } ?? store.focusedSpaceID
+ app.useNormalWindow()
+ let sid = (spaceID ?? state.targetSpaceID).flatMap { store.space($0) != nil && !store.isIncognito(space: $0) ? $0 : nil }
+ ?? store.focusedSpaceID
let tab = store.createTab(url: b.currentURL, title: b.currentTitle, in: sid, select: true)
if let favicon, let key = FaviconCache.key(for: b.currentURL) { app.favicons.store(favicon, forKey: key) }
promoted = true
@@ -509,7 +519,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
case "promoteLittleWindow": promote(to: nil)
// No find bar or capture in little windows; keep them off the main window.
case "find", "findNext", "findPrevious", "capturePage", "toggleSidebar", "pinTab", "favoriteTab", "renameTab",
- "duplicateTab", "resetTab", "muteTab", "clearToday", "nextTab", "previousTab", "recentTab":
+ "duplicateTab", "resetTab", "muteTab", "clearToday", "nextTab", "previousTab", "recentTab", "recentTabBackward":
break
default: return false
}
@@ -549,6 +559,13 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
if browser == nil { app.removeLittleWindow(self) }
}
+ /// Left with the green button or ⌃⌘F while a video was fullscreen: the page leaves too.
+ func windowDidExitFullScreen(_ notification: Notification) {
+ guard (notification.object as? NSWindow) === window, pageFullscreen else { return }
+ pageFullscreen = false
+ browser?.exitFullscreen()
+ }
+
func windowDidResize(_ notification: Notification) {
guard let window, (notification.object as? NSWindow) === window, !window.styleMask.contains(.fullScreen) else { return }
if commandBar.isOpen { positionCommandPanel() }
@@ -635,18 +652,20 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
func browser(_ browser: CraBrowser, devToolsDocked docked: Bool) {}
func browser(_ browser: CraBrowser, didChangeFullscreen fullscreen: Bool) {
guard let window else { return }
+ pageFullscreen = fullscreen
if fullscreen != window.styleMask.contains(.fullScreen) { window.toggleFullScreen(nil) }
}
/// Links that want a new tab open another little window (Arc does the same).
func browser(_ browser: CraBrowser, requestsNewTabWithURL url: String, inBackground background: Bool) {
- if url.hasPrefix("cra://") { if let u = URL(string: url) { app.handleInternalURL(u) }; return }
+ // cra:// is Cra's scripting scheme; a page must not drive it.
+ if url.lowercased().hasPrefix("cra:") { return }
app.openLittleWindow(url: url, activate: !background)
if background { window?.makeKeyAndOrderFront(nil) }
}
func browser(_ browser: CraBrowser, popupHostForURL url: String, inBackground background: Bool) -> CraBrowser? {
- if url.hasPrefix("cra://") { if let u = URL(string: url) { app.handleInternalURL(u) }; return nil }
+ if url.lowercased().hasPrefix("cra:") { return nil }
let w = app.makeLittleWindow(url: nil)
w.state.url = url
w.show()
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index be10c6e..5b8bfe6 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -1,6 +1,8 @@
import AppKit
import CraCEF
+import QuickLookThumbnailing
import SwiftUI
+import UniformTypeIdentifiers
@MainActor
final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserManagerDelegate {
@@ -14,6 +16,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
private(set) var shell: ShellView!
private var commandPanel: CommandBarPanel!
private var commandHost: NSHostingView<AnyView>!
+ let tabSwitcher = TabSwitcher()
+ private let tabSwitcherPanel = TabSwitcherPanel()
private var spaceEditor: NSWindow?
private var importWindow: ImportWindowController?
private var scrollMonitor: Any?
@@ -27,17 +31,36 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
private var swipeSamples: [(time: TimeInterval, dx: CGFloat)] = []
private var swipeDetent = 0
private var enteredFullscreenForContent = false
+ /// The tab whose page (a video) is in element fullscreen.
+ private var contentFullscreenTab: UUID?
private var lastSidebarVisible = true
private var lastSidebarWidth: CGFloat = 0
private var commandBarOpenedAt = Date.distantPast
private var commandObserving = false
+ /// Closed for good (another window stayed open): it no longer follows the store.
+ private var isTornDown = false
var currentBrowser: CraBrowser? { browsers.visibleRuntime?.browser }
- init(app: AppDelegate) {
+ /// This window's entry in the store (WindowSession): its space, open tabs, frame.
+ let windowID: UUID
+ /// Pages load in the off-the-record profile; nothing is saved (WindowSession.isIncognito).
+ let isIncognito: Bool
+ var focusedSpaceID: UUID { store.focusedSpaceID(window: windowID) }
+ var focusedSpace: Space { store.focusedSpace(window: windowID) }
+ var selectedTabID: UUID? { store.selectedTabID(window: windowID) }
+ var selectedTab: SidebarItem? { store.selectedTab(window: windowID) }
+ var sidebarVisible: Bool {
+ get { store.window(windowID).sidebarVisible }
+ set { store.updateWindow(windowID) { $0.sidebarVisible = newValue } }
+ }
+
+ init(app: AppDelegate, session: WindowSession) {
self.app = app
+ windowID = session.id
+ isIncognito = session.isIncognito
commandBar = CommandBarController(engine: app.engine, store: app.store)
- let frame = app.store.prefs.windowFrame.map { NSRectFromString($0) } ?? NSRect(x: 0, y: 0, width: 1400, height: 880)
+ let frame = session.frame.map { NSRectFromString($0) } ?? NSRect(x: 0, y: 0, width: 1400, height: 880)
let window = CraWindow(contentRect: frame,
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
@@ -50,10 +73,11 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
window.isReleasedWhenClosed = false
window.tabbingMode = .disallowed
window.title = "Cra"
- if app.store.prefs.windowFrame == nil { window.center() }
+ if session.frame == nil { window.center() }
+ sidebarUI.windowID = session.id
let store = app.store
- let palette = store.focusedSpace.theme.palette
+ let palette = focusedSpace.theme.palette
let env: (AnyView) -> AnyView = { v in
AnyView(v.environment(store).environment(self.sidebarUI).environment(app.favicons).environment(\.sidebarActions, self.sidebarActions))
}
@@ -61,22 +85,30 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
background: SpaceBackground(palette: palette, pager: SpacePager(store: store, ui: sidebarUI)),
sidebar: env(AnyView(SidebarRootView())),
toolbar: env(AnyView(ContentToolbarView(palette: palette))),
- placeholder: AnyView(EmptyContentView(space: store.focusedSpace)),
+ placeholder: AnyView(EmptyContentView(space: focusedSpace)),
status: AnyView(StatusBubble(overlay: overlay)),
toasts: AnyView(ToastStack(overlay: overlay)),
find: AnyView(FindBar(overlay: overlay, onFind: { [weak self] q, fwd in self?.find(q, forward: fwd) },
onClose: { [weak self] in self?.hideFindBar() })))
shell.sidebarWidth = CGFloat(store.prefs.sidebarWidth)
- shell.sidebarVisible = store.prefs.sidebarVisible
+ shell.sidebarVisible = sidebarVisible
shell.showToolbar = store.settings.showToolbar
- lastSidebarVisible = store.prefs.sidebarVisible
- window.trafficLightsHidden = !store.prefs.sidebarVisible
+ lastSidebarVisible = sidebarVisible
+ window.trafficLightsHidden = !sidebarVisible
lastSidebarWidth = CGFloat(store.prefs.sidebarWidth)
window.contentView = shell
window.backgroundColor = NSColor(palette.gradientColors.first ?? .gray)
browsers = BrowserManager(store: store, favicons: app.favicons, container: shell.parkingView)
browsers.delegate = self
+ browsers.windowID = session.id
+ browsers.takeRuntimeFromOtherWindow = { [weak self] id in
+ guard let self else { return nil }
+ for other in self.app.mainWindows where other !== self {
+ if let rt = other.browsers.release(id) { return rt }
+ }
+ return nil
+ }
// AppKit asks the view under a press whether it may move the window. In the
// sidebar's list that is SwiftUI's scroll container, which always says yes,
// so the window's own flag is what keeps a row press for the row's drag.
@@ -84,14 +116,14 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
browsers.paneHost = { [weak self] id in self?.shell.card(for: id)?.webArea }
shell.makeToolbar = { [weak self] id in
guard let self else { return AnyView(EmptyView()) }
- return AnyView(ContentToolbarView(palette: self.store.focusedSpace.theme.palette, paneTabID: id)
+ return AnyView(ContentToolbarView(palette: self.focusedSpace.theme.palette, paneTabID: id)
.environment(self.store).environment(self.sidebarUI).environment(app.favicons).environment(\.sidebarActions, self.sidebarActions))
}
shell.onPaneResizeBegan = { [weak self] in self?.pageWindowsFollowLive = true }
shell.onPaneResizeEnded = { [weak self] factors in
guard let self else { return }
self.pageWindowsFollowLive = false
- if let sel = self.store.selectedTabID, let split = self.store.splitContaining(sel) {
+ if let sel = self.selectedTabID, let split = self.store.splitContaining(sel) {
self.store.setSplitWidthFactors(split.id, factors.mapValues { Double($0) })
}
}
@@ -100,6 +132,21 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
commandHost = NSHostingView(rootView: AnyView(CommandBarView(controller: commandBar).environment(app.favicons)))
commandPanel.contentView = commandHost
commandPanel.delegate = self
+ tabSwitcherPanel.contentView = NSHostingView(rootView: TabSwitcherView(switcher: tabSwitcher).environment(app.favicons))
+ tabSwitcher.onShow = { [weak self] in self?.showTabSwitcherPanel() }
+ tabSwitcher.onHide = { [weak self] in self?.hideTabSwitcherPanel() }
+ tabSwitcher.onCommit = { [weak self] id in
+ guard let self, id != self.selectedTabID else { return }
+ self.store.selectTab(id, window: self.windowID)
+ self.sidebarUI.keyboardFocusID = id
+ }
+ tabSwitcher.direction = { [weak app] event in
+ switch app?.bindings.action(for: event)?.id {
+ case "recentTab": return 1
+ case "recentTabBackward": return -1
+ default: return nil
+ }
+ }
wireActions()
shell.resizeHandle.onDrag = { [weak self] dx in
@@ -149,16 +196,19 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
sidebarActions.toggleSidebar = { [weak self] in self?.toggleSidebar() }
sidebarActions.showArchive = { [weak self] in self?.app.showArchiveWindow() }
sidebarActions.resetPinnedTab = { [weak self] id in self?.resetPinnedTab(id) }
- sidebarActions.openURL = { [weak self] url in self?.store.createTab(url: url) }
+ sidebarActions.openURL = { [weak self] url in
+ guard let self else { return }
+ self.store.createTab(url: url, window: self.windowID)
+ }
sidebarActions.focusPane = { [weak self] id in
- guard let self, self.store.selectedTabID != id else { return }
- self.store.selectTab(id)
+ guard let self, self.selectedTabID != id else { return }
+ self.store.selectTab(id, window: windowID)
}
sidebarActions.closePane = { [weak self] id in self?.closeSplitPane(id) }
sidebarActions.separatePane = { [weak self] id in self?.separatePane(id) }
sidebarActions.paneNavigate = { [weak self] id, what in
guard let self else { return }
- if self.store.selectedTabID != id { self.store.selectTab(id) }
+ if self.selectedTabID != id { self.store.selectTab(id, window: windowID) }
guard let b = self.browsers.runtime(for: id)?.browser else { return }
switch what {
case "goBack": b.goBack()
@@ -169,7 +219,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
sidebarActions.editPaneURL = { [weak self] id in
guard let self else { return }
- if self.store.selectedTabID != id { self.store.selectTab(id) }
+ if self.selectedTabID != id { self.store.selectTab(id, window: windowID) }
self.openCommandBar(.editURL)
}
// Toolbar buttons are ~34 pt wide and the click lands near the middle: the popup's
@@ -177,16 +227,16 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
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 }
+ // menu bar's do: under the toolbar at the card's right end of the window in use.
+ ExtensionActions.shared.watchPopups { [weak app] in
+ guard let main = app?.main, let window = main.window, let key = NSApp.keyWindow, key === window || key.parent === window,
+ let bar = main.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
- self?.browsers.runtime(for: uuid)?.browser.setAudioMuted(muted)
+ self?.app.runtime(for: uuid)?.browser.setAudioMuted(muted)
} else {
self?.app.perform(id)
}
@@ -199,6 +249,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// MARK: Observation
private func observeStore() {
+ guard !isTornDown else { return }
withObservationTracking {
_ = store.revision
_ = store.prefs
@@ -213,7 +264,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
func refresh() {
- let space = store.focusedSpace
+ guard !isTornDown else { return }
+ let space = focusedSpace
let palette = space.theme.palette
shell.backgroundHost.rootView = SpaceBackground(palette: palette, pager: SpacePager(store: store, ui: sidebarUI))
shell.placeholderHost.rootView = AnyView(EmptyContentView(space: space))
@@ -229,9 +281,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
window?.backgroundColor = palette.vibrant ? .clear : NSColor(palette.gradientColors.first ?? .gray)
browsers.pruneMissingTabs()
- let selected = store.selectedTabID
+ let selected = selectedTabID
// Split view: the selected tab's split decides which panes are on screen.
- let panes = store.visiblePaneTabIDs(in: store.focusedSpaceID)
+ let panes = store.visiblePaneTabIDs(in: focusedSpaceID, window: windowID)
let split = selected.flatMap { store.splitContaining($0) }
let factors = SplitPaneLayout.normalizedFactors(ids: panes, stored: split?.split?.widthFactors ?? [:])
let empty = Set(panes.filter { store.item($0)?.isEmptyTab == true })
@@ -247,10 +299,10 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
shell.layoutContentChildren()
syncSidebarUI()
- window?.title = store.selectedTab?.displayTitle ?? space.title
+ window?.title = selectedTab?.displayTitle ?? space.title
- if store.prefs.sidebarVisible != lastSidebarVisible {
- lastSidebarVisible = store.prefs.sidebarVisible
+ if sidebarVisible != lastSidebarVisible {
+ lastSidebarVisible = sidebarVisible
(window as? CraWindow)?.trafficLightsHidden = !lastSidebarVisible
// Anchoring while the sidebar floats: bring it home first so it slides from there.
if lastSidebarVisible { floatingSidebar?.prepareForAnchoring() }
@@ -263,7 +315,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
private func syncSidebarUI() {
- sidebarUI.loadedTabIDs = Set(browsers.runtimes.keys)
+ sidebarUI.loadedTabIDs = Set(app.mainWindows.flatMap { $0.browsers.runtimes.keys })
+ let capturing = Set(app.mainWindows.flatMap { $0.browsers.runtimes.filter { $0.value.browser.isCapturingMedia }.keys })
+ if capturing != sidebarUI.capturingTabIDs { sidebarUI.capturingTabIDs = capturing }
let b = browsers.visibleRuntime?.browser
sidebarUI.canGoBack = b?.canGoBack ?? false
sidebarUI.canGoForward = b?.canGoForward ?? false
@@ -283,7 +337,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// Arc's "Add Split View" (⌃⇧=): a new empty pane opens after the focused
/// one, with the command bar ready to fill it.
func addSplitPane() {
- guard let current = store.selectedTabID else { openCommandBar(.newTab); return }
+ guard let current = selectedTabID else { openCommandBar(.newTab); return }
if store.paneTabIDs(for: current).count >= 4 {
sidebarUI.flashStatus("Cannot Add New Pane", symbol: "rectangle.portrait.split.2x1.slash")
return
@@ -308,11 +362,11 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func separatePane(_ id: UUID) {
guard store.splitContaining(id) != nil else { return }
store.separateFromSplit(id)
- store.selectTab(id)
+ store.selectTab(id, window: windowID)
}
func cycleSplitPane(_ delta: Int) {
- guard let current = store.selectedTabID else { return }
+ guard let current = selectedTabID else { return }
let panes = store.paneTabIDs(for: current)
guard panes.count > 1, let idx = panes.firstIndex(of: current) else { return }
let n = panes.count
@@ -346,10 +400,18 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func browserManager(download: CraDownloadInfo) {
let name = (download.fullPath as NSString).lastPathComponent.isEmpty ? download.suggestedName : (download.fullPath as NSString).lastPathComponent
let toast = DownloadToast(id: download.identifier, name: name, percent: download.percent, state: download.state.rawValue, path: download.fullPath)
- if let i = overlay.toasts.firstIndex(where: { $0.id == toast.id }) { overlay.toasts[i] = toast } else { overlay.toasts.append(toast) }
+ if let i = overlay.toasts.firstIndex(where: { $0.id == toast.id }) { overlay.toasts[i] = toast } else {
+ overlay.toasts.append(toast)
+ ChromeDownloadAnimation.suppress()
+ showDownloadInSidebar(download, name: name)
+ }
+ updateRecentDownload(download)
+ if download.state == .complete, !download.fullPath.isEmpty, finishedDownloads.insert(download.identifier).inserted {
+ DownloadHistory.shared.add(path: download.fullPath)
+ }
shell.toastCount = overlay.toasts.count
- overlayPanel?.ignoresMouseEvents = overlay.toasts.isEmpty
shell.layoutContentChildren()
+ layoutToastPanel()
if download.state != .inProgress {
let id = toast.id
DispatchQueue.main.asyncAfter(deadline: .now() + 8) { [weak self] in
@@ -357,6 +419,55 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
self.overlay.toasts.removeAll { $0.id == id }
self.shell.toastCount = self.overlay.toasts.count
self.shell.layoutContentChildren()
+ self.layoutToastPanel()
+ }
+ }
+ }
+
+ /// Arc's download animation: the file drops onto the Library button and a download
+ /// glyph is thrown at it from the pointer (DownloadFlight). Measured on Arc 1.170: the
+ /// file stays 30 s after the glyph lands, then fades out over 0.15 s.
+ private func showDownloadInSidebar(_ download: CraDownloadInfo, name: String) {
+ let type = UTType(filenameExtension: (name as NSString).pathExtension) ?? .data
+ sidebarUI.recentDownload = RecentDownload(id: download.identifier, path: download.fullPath,
+ image: NSWorkspace.shared.icon(for: type))
+ var flight: TimeInterval = 0
+ if let window, window.isVisible, let anchor = sidebarUI.libraryAnchor, let host = anchor.window,
+ host.isVisible, !anchor.isHiddenOrHasHiddenAncestor {
+ // Aim at the bin's centre (screen coordinates are y-up, the offset is SwiftUI's y-down).
+ let glyph = host.convertToScreen(anchor.convert(anchor.bounds, to: nil))
+ let bin = NSPoint(x: glyph.midX + LibraryButton.binOffset.width, y: glyph.midY - LibraryButton.binOffset.height)
+ flight = DownloadFlight.launch(over: window, from: NSEvent.mouseLocation, to: bin)
+ }
+ let id = download.identifier
+ DispatchQueue.main.asyncAfter(deadline: .now() + flight + 30) { [weak self] in
+ guard let self, self.sidebarUI.recentDownload?.id == id else { return }
+ withAnimation(.easeOut(duration: 0.15)) { self.sidebarUI.recentDownload = nil }
+ }
+ }
+
+ private var finishedDownloads: Set<UInt32> = []
+
+ /// Keeps the Library button's file current: its path once known, its Quick Look
+ /// thumbnail once the download is complete (Arc showed a text file's page).
+ private func updateRecentDownload(_ download: CraDownloadInfo) {
+ // Only the first complete update counts; Chromium sends more after it.
+ guard var recent = sidebarUI.recentDownload, recent.id == download.identifier,
+ !finishedDownloads.contains(download.identifier) else { return }
+ if !download.fullPath.isEmpty, recent.path != download.fullPath {
+ recent.path = download.fullPath
+ sidebarUI.recentDownload = recent
+ }
+ guard download.state == .complete, !download.fullPath.isEmpty else { return }
+ let request = QLThumbnailGenerator.Request(fileAt: URL(fileURLWithPath: download.fullPath), size: CGSize(width: 32, height: 32),
+ scale: window?.backingScaleFactor ?? 2, representationTypes: .thumbnail)
+ let id = download.identifier
+ QLThumbnailGenerator.shared.generateBestRepresentation(for: request) { [weak self] thumbnail, _ in
+ guard let image = thumbnail?.nsImage else { return }
+ DispatchQueue.main.async {
+ guard let self, var recent = self.sidebarUI.recentDownload, recent.id == id else { return }
+ recent.image = image
+ self.sidebarUI.recentDownload = recent
}
}
}
@@ -364,6 +475,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func browserManager(fullscreen: Bool, tabID: UUID) {
guard let window else { return }
shell.contentFullscreen = fullscreen
+ contentFullscreenTab = fullscreen ? tabID : nil
if fullscreen, !window.styleMask.contains(.fullScreen) {
enteredFullscreenForContent = true
window.toggleFullScreen(nil)
@@ -384,8 +496,12 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// MARK: Chrome-style page windows
+ /// Page-sized and always click-through: it covers the whole page, so if it ever took
+ /// mouse events every click on the page would land in it. Anything clickable over the
+ /// page gets its own panel just its size (the find bar, the toasts).
private var overlayPanel: NSPanel?
private var findPanel: FindBarPanel?
+ private var toastPanel: NSPanel?
/// Page area per visible tab, window coordinates (one entry per pane).
private var lastPaneFrames: [UUID: NSRect] = [:]
/// While a divider is dragged the page windows follow every mouse move.
@@ -393,27 +509,54 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
private func ensureOverlayPanel() {
guard overlayPanel == nil, let window else { return }
- let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
- styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
- panel.isOpaque = false
- panel.backgroundColor = .clear
- panel.hasShadow = false
- panel.isMovable = false
+ func clearPanel() -> NSPanel {
+ let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
+ styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = false
+ panel.isMovable = false
+ panel.hidesOnDeactivate = false
+ panel.contentView = NSView(frame: panel.contentRect(forFrameRect: panel.frame))
+ return panel
+ }
+ let panel = clearPanel()
panel.ignoresMouseEvents = true
- panel.hidesOnDeactivate = false
- panel.contentView = NSView(frame: panel.contentRect(forFrameRect: panel.frame))
let find = FindBarPanel()
- shell.moveOverlays(to: panel.contentView!, findBar: find)
+ let toasts = clearPanel()
+ shell.moveOverlays(to: panel.contentView!, findBar: find, toasts: toasts)
window.addChildWindow(panel, ordered: .above)
overlayPanel = panel
findPanel = find
+ toastPanel = toasts
if overlay.findVisible { window.addChildWindow(find, ordered: .above) }
+ layoutToastPanel()
+ }
+
+ /// The toast panel is on screen only while there are toasts, sized to the stack in the
+ /// bottom trailing corner of the focused page (the overlay panel's frame).
+ private func layoutToastPanel() {
+ guard let window, let panel = toastPanel, let page = overlayPanel?.frame else { return }
+ guard !overlay.toasts.isEmpty else {
+ if panel.parent != nil { window.removeChildWindow(panel) }
+ if panel.isVisible { panel.orderOut(nil) }
+ return
+ }
+ let frame = toastPanelFrame(page: page)
+ if panel.frame != frame { panel.setFrame(frame, display: true) }
+ if panel.parent !== window { window.addChildWindow(panel, ordered: .above) }
+ }
+
+ private func toastPanelFrame(page: NSRect) -> NSRect {
+ let size = ShellView.toastStackSize(count: overlay.toasts.count)
+ return NSRect(x: page.maxX - size.width, y: page.minY, width: size.width, height: size.height)
}
/// Overlay panel above the page windows (and the floating sidebar), the find bar above it.
private func raiseOverlayPanels() {
guard let window else { return }
var panels: [NSPanel?] = [overlayPanel]
+ if !overlay.toasts.isEmpty { panels.append(toastPanel) }
if overlay.findVisible { panels.append(findPanel) }
for case let panel? in panels {
window.removeChildWindow(panel)
@@ -449,6 +592,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
w.styleMask.insert(.fullSizeContentView)
ChromiumWindowCorners.setSquare(true, for: w)
ChromiumChildHover.setDocked(true, for: w)
+ ChromiumChildFullscreen.attach(w)
w.titlebarAppearsTransparent = true
w.titleVisibility = .hidden
w.isMovable = false
@@ -511,6 +655,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let focusOnScreen = window.convertToScreen(focusPage)
if let panel = overlayPanel, panel.frame != focusOnScreen { panel.setFrame(focusOnScreen, display: true) }
if let find = findPanel, find.frame != findPanelFrame(page: focusOnScreen) { find.setFrame(findPanelFrame(page: focusOnScreen), display: true) }
+ layoutToastPanel()
}
private func animatePageWindows(to frames: [UUID: NSRect], duration: TimeInterval) {
@@ -533,6 +678,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
overlayPanel?.animator().setFrame(window.convertToScreen(focusPage), display: true)
findPanel?.animator().setFrame(findPanelFrame(page: window.convertToScreen(focusPage)), display: true)
+ if !overlay.toasts.isEmpty { toastPanel?.animator().setFrame(toastPanelFrame(page: window.convertToScreen(focusPage)), display: true) }
}
}
@@ -557,6 +703,18 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
private func updatePageCorners(_ w: NSWindow, page: NSRect, body: NSRect) {
guard let cv = w.contentView, let layer = cv.layer else { return }
fillContentView(w)
+ // Chromium can restore its own style mask (fullscreen, display changes), which brings
+ // back macOS's rounded window corners on all four sides: square the window again.
+ if w.styleMask.contains(.titled) || w.styleMask.contains(.resizable) {
+ w.styleMask.remove([.titled, .resizable])
+ ChromiumWindowCorners.setSquare(true, for: w)
+ }
+ // The whole mask, not only the corner set: a rebuilt layer would otherwise keep
+ // whatever radius and clipping it came with.
+ let radius = shell.contentFullscreen ? 0 : CraMetrics.contentCornerRadius
+ if layer.cornerRadius != radius { layer.cornerRadius = radius }
+ if layer.cornerCurve != .continuous { layer.cornerCurve = .continuous }
+ if !layer.masksToBounds { layer.masksToBounds = true }
// Chromium's content view is flipped, so its layer's MinY edge is the top.
let bottomLeft: CACornerMask = cv.isFlipped ? .layerMinXMaxYCorner : .layerMinXMinYCorner
let bottomRight: CACornerMask = cv.isFlipped ? .layerMaxXMaxYCorner : .layerMaxXMinYCorner
@@ -688,7 +846,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
ChromiumChildHover.setDocked(false, for: w)
w.titlebarAppearsTransparent = false
w.titleVisibility = .visible
- if let url = store.selectedTab?.tab?.url {
+ if let url = selectedTab?.tab?.url {
w.title = "DevTools - " + url.replacingOccurrences(of: "^[a-z]+://", with: "", options: .regularExpression)
}
for type in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] { w.standardWindowButton(type)?.isHidden = false }
@@ -751,17 +909,14 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// Split view: clicking into another pane focuses it (Arc: focusedContentID
// follows the click); its toolbar gets the options button and shortcuts act on it.
if browsers.visibleTabIDs.contains(tabID) {
- store.selectTab(tabID)
+ store.selectTab(tabID, window: windowID)
return
}
guard browsers.runtime(for: tabID)?.browser.isInPictureInPicture == true else { return }
- store.selectTab(tabID)
+ store.selectTab(tabID, window: windowID)
showWindow(nil)
NSApp.activate(ignoringOtherApps: true)
}
- func browserManagerOpenInternalURL(_ url: String) {
- if let u = URL(string: url) { app.handleInternalURL(u) }
- }
func browserManagerPageClosedTab(_ tabID: UUID) { closeTab(tabID) }
@@ -775,11 +930,11 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
if !sidebarUI.multiSelection.isEmpty {
let ids = sidebarUI.multiSelection
sidebarUI.clearPicks()
- for id in ids where id != store.selectedTabID { closeTab(id) }
- if let open = store.selectedTabID, ids.contains(open) { closeTab(open) }
+ for id in ids where id != selectedTabID { closeTab(id) }
+ if let open = selectedTabID, ids.contains(open) { closeTab(open) }
return
}
- guard let id = store.selectedTabID else { return }
+ guard let id = selectedTabID else { return }
closeTab(id)
}
@@ -788,16 +943,12 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func closeTab(_ id: UUID) {
guard let item = store.item(id), item.isTab else { return }
if store.isPinned(id) {
- let wasSelected = store.selectedTabID == id
+ let wasSelected = selectedTabID == id
_ = store.resetPinnedTab(id)
- browsers.unload(id)
+ for w in app.mainWindows { w.browsers.unload(id) }
if wasSelected {
- let back = item.tab?.activeTabBeforeCreationID
- if let back, store.item(back)?.isTab == true, store.spaceID(ofItem: back) == store.focusedSpaceID {
- store.selectTab(back)
- } else {
- store.selectTab(nil)
- }
+ // Arc goes back to the tab used before this one.
+ store.selectTab(store.mostRecentTab(in: focusedSpaceID, excluding: id), window: windowID)
}
} else {
store.archiveTab(id, reason: .manual)
@@ -806,13 +957,13 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func resetPinnedTab(_ id: UUID) {
guard let home = store.resetPinnedTab(id) else { return }
- browsers.runtime(for: id)?.browser.loadURL(home)
+ app.runtime(for: id)?.browser.loadURL(home)
}
func cycleTab(_ delta: Int) {
- let tabs = store.visibleTabs(in: store.focusedSpaceID)
+ let tabs = store.visibleTabs(in: focusedSpaceID)
guard !tabs.isEmpty else { return }
- let idx = store.selectedTabID.flatMap { id in tabs.firstIndex { $0.id == id } } ?? -1
+ let idx = selectedTabID.flatMap { id in tabs.firstIndex { $0.id == id } } ?? -1
let n = tabs.count
store.selectTab(tabs[((idx + delta) % n + n) % n].id)
}
@@ -846,8 +997,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// MARK: Sidebar
func toggleSidebar() {
- store.prefs.sidebarVisible.toggle()
- if !store.prefs.sidebarVisible { setFloatingSidebar(false) }
+ sidebarVisible.toggle()
+ if !sidebarVisible { setFloatingSidebar(false) }
}
/// Arc's floating sidebar lives in its own panel above the page windows (see FloatingSidebarController).
@@ -855,15 +1006,15 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
private func setFloatingSidebar(_ show: Bool) {
guard let floatingSidebar else { return }
- if show { if !store.prefs.sidebarVisible { floatingSidebar.show() } } else { floatingSidebar.hide(animated: true) }
+ if show { if !sidebarVisible { floatingSidebar.show() } } else { floatingSidebar.hide(animated: true) }
}
private func installFloatingSidebar() {
guard let window, floatingSidebar == nil else { return }
let f = FloatingSidebarController(shell: shell, window: window, palette: { [weak self] in
- self?.store.focusedSpace.theme.palette ?? SpaceTheme.presets[0].palette
+ self?.focusedSpace.theme.palette ?? SpaceTheme.presets[0].palette
})
- f.sidebarHidden = { [weak self] in self.map { !$0.store.prefs.sidebarVisible } ?? false }
+ f.sidebarHidden = { [weak self] in self.map { !$0.sidebarVisible } ?? false }
f.didAttachPanel = { [weak self] in
// Keep toasts and the find bar above the floating sidebar.
self?.raiseOverlayPanels()
@@ -914,7 +1065,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
self.swipeX += event.scrollingDeltaX
self.swipeY += event.scrollingDeltaY
guard max(abs(self.swipeX), abs(self.swipeY)) > 6 else { return event }
- guard abs(self.swipeX) > abs(self.swipeY) * 1.2, self.store.spaceOrder.count > 1 else {
+ guard abs(self.swipeX) > abs(self.swipeY) * 1.2, self.store.spaceOrder.count > 1, !self.isIncognito else {
self.swipeAxis = .vertical
return event
}
@@ -948,7 +1099,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
swipeTravel += dx
swipeSamples.append((time, dx))
swipeSamples.removeAll { time - $0.time > 0.08 }
- let index = CGFloat(store.spaceOrder.firstIndex(of: store.focusedSpaceID) ?? 0)
+ let index = CGFloat(store.spaceOrder.firstIndex(of: focusedSpaceID) ?? 0)
let first = -index, last = CGFloat(store.spaceOrder.count - 1) - index
// Content follows the fingers (natural scrolling: fingers left = next space).
var pages = max(-1, min(1, -swipeTravel / width))
@@ -972,7 +1123,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let moved = swipeSamples.reduce(0) { $0 + $1.dx }
// Pages per second; a lone sample carries no timing, so treat it as a slow lift.
let velocity = span > 0.004 ? -moved / CGFloat(span) / width : 0
- let index = store.spaceOrder.firstIndex(of: store.focusedSpaceID) ?? 0
+ let index = store.spaceOrder.firstIndex(of: focusedSpaceID) ?? 0
var step = 0
if abs(velocity) > 0.8 { step = velocity > 0 ? 1 : -1 } else if abs(pages) > 0.5 { step = pages > 0 ? 1 : -1 }
if !(0..<store.spaceOrder.count).contains(index + step) { step = 0 }
@@ -980,7 +1131,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
sidebarUI.spaceSettleVelocity = abs(remaining) > 0.001 ? Double(max(-4, min(12, velocity / remaining))) : 0
withAnimation(sidebarUI.spaceSettleAnimation) {
sidebarUI.spaceSwipe = 0
- if step != 0 { store.focusSpace(store.spaceOrder[index + step]) }
+ if step != 0 { store.focusSpace(store.spaceOrder[index + step], window: windowID) }
}
// Clicks and shortcuts that switch spaces later start from rest.
DispatchQueue.main.async { [weak self] in self?.sidebarUI.spaceSettleVelocity = 0 }
@@ -992,7 +1143,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// Screen y of the focused card's toolbar bottom (its top edge when the toolbar is hidden),
/// and the card's right edge.
- private func toolbarBottomOnScreen() -> (y: CGFloat, cardMaxX: CGFloat)? {
+ fileprivate func toolbarBottomOnScreen() -> (y: CGFloat, cardMaxX: CGFloat)? {
guard let window else { return nil }
let card = shell.focusedCard.map { shell.contentContainer.convert($0.frame, to: nil) }
?? shell.convert(shell.contentContainer.frame, to: nil)
@@ -1034,7 +1185,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
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)
+ store.createTab(url: e.optionsPath.map { base + $0 } ?? "chrome://extensions/?id=\(id)", select: true, window: windowID)
}
}
@@ -1047,7 +1198,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// 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 } ?? ""
+ let url = 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") }
@@ -1062,17 +1213,17 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
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,
+ siteControlCenter.show(relativeTo: rect, of: content, url: url, dark: focusedSpace.theme.palette.isDark,
store: store, actions: actions)
}
private func openTab(_ url: String) {
- store.createTab(url: url, select: true)
+ store.createTab(url: url, select: true, window: windowID)
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 }
+ guard let url = selectedTabID.flatMap({ store.item($0)?.tab?.url }).flatMap(URL.init(string:)) else { return }
NSSharingServicePicker(items: [url]).show(relativeTo: rect, of: view, preferredEdge: .minY)
}
@@ -1119,16 +1270,57 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
}
+ // MARK: Tab switcher
+
+ /// ⌃Tab / ⌃⇧Tab: Arc's switcher over the space's recent tabs.
+ func cycleRecentTabs(_ delta: Int, event: NSEvent?) {
+ let theme = focusedSpace.theme
+ let dark = NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
+ if !tabSwitcher.isOpen {
+ tabSwitcher.isDark = dark
+ tabSwitcher.highlight = theme.switcherHighlight(dark: dark)
+ tabSwitcher.palette = theme.palette
+ }
+ tabSwitcher.cycle(delta, event: event) {
+ store.recentTabs(in: focusedSpaceID, limit: TabSwitcherMetrics.maxItems).compactMap { id in
+ guard let it = store.item(id), let tab = it.tab else { return nil }
+ return TabSwitcher.Item(id: id, title: it.displayTitle, iconKey: tab.iconKey, snapshot: browsers.runtime(for: id)?.snapshot)
+ }
+ }
+ // The page on screen is the freshest thumbnail there is: retake it for its card.
+ guard tabSwitcher.isOpen, let current = browsers.visibleTabID else { return }
+ browsers.captureSnapshot(current) { [weak self] in
+ guard let self else { return }
+ self.tabSwitcher.updateSnapshot(current, self.browsers.runtime(for: current)?.snapshot)
+ }
+ }
+
+ /// Centred on the whole window, like Arc (sidebar included).
+ private func showTabSwitcherPanel() {
+ guard let window else { return }
+ let size = TabSwitcherMetrics.windowSize(count: tabSwitcher.items.count)
+ let wf = window.frame
+ tabSwitcherPanel.setFrame(NSRect(x: (wf.midX - size.width / 2).rounded(.down), y: (wf.midY - size.height / 2).rounded(.down),
+ width: size.width, height: size.height), display: true)
+ if tabSwitcherPanel.parent !== window { window.addChildWindow(tabSwitcherPanel, ordered: .above) }
+ tabSwitcherPanel.orderFront(nil)
+ }
+
+ private func hideTabSwitcherPanel() {
+ if tabSwitcherPanel.parent != nil { window?.removeChildWindow(tabSwitcherPanel) }
+ tabSwitcherPanel.orderOut(nil)
+ }
+
// MARK: Command bar
func openCommandBar(_ mode: CommandBarMode) {
guard let window else { return }
// An empty split pane gets Arc's "Search or Enter URL…" bar; the result fills the pane.
- let fillingEmptyPane = store.selectedTab?.isEmptyTab == true
- let prefill = mode == .editURL && !fillingEmptyPane ? store.selectedTab?.tab?.url : nil
- let effectiveMode: CommandBarMode = (mode == .editURL && (store.selectedTab == nil || fillingEmptyPane)) ? .newTab : mode
- commandBar.highlight = store.focusedSpace.theme.palette.commandHighlight
- commandBar.focusedSpaceID = store.focusedSpaceID
+ let fillingEmptyPane = selectedTab?.isEmptyTab == true
+ let prefill = mode == .editURL && !fillingEmptyPane ? selectedTab?.tab?.url : nil
+ let effectiveMode: CommandBarMode = (mode == .editURL && (selectedTab == nil || fillingEmptyPane)) ? .newTab : mode
+ commandBar.highlight = focusedSpace.theme.palette.commandHighlight
+ commandBar.focusedSpaceID = focusedSpaceID
commandBar.open(mode: effectiveMode, prefill: prefill)
// Always centred in the window, also when opened from the toolbar.
commandBar.attached = false
@@ -1181,11 +1373,11 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let query = commandBar.query
func open(_ url: String) {
store.recordQuerySelection(query: query, url: url)
- let fillsEmptyPane = store.selectedTab?.isEmptyTab == true
- if (mode == .editURL || fillsEmptyPane) && !forceNewTab, store.selectedTabID != nil {
+ let fillsEmptyPane = selectedTab?.isEmptyTab == true
+ if (mode == .editURL || fillsEmptyPane) && !forceNewTab, selectedTabID != nil {
loadInSelectedTab(url)
} else {
- store.createTab(url: url)
+ store.createTab(url: url, window: windowID)
}
}
guard let s else {
@@ -1196,7 +1388,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
switch s.kind {
case .switchToTab(let id):
store.recordQuerySelection(query: query, url: s.url ?? "")
- store.selectTab(id)
+ store.selectTab(id, window: windowID)
case .archived(let id):
store.restoreArchived(id)
case .navigate:
@@ -1209,22 +1401,22 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
case .command(let id):
app.perform(id)
case .switchSpace(let id):
- store.focusSpace(id)
+ store.focusSpace(id, window: windowID)
case .moveToSpace(let id):
- if let t = store.selectedTabID { store.moveTab(t, toSpace: id) }
+ if let t = selectedTabID { store.moveTab(t, toSpace: id) }
case .moveToFolder(let id):
- if let t = store.selectedTabID { store.moveItem(t, to: id, index: nil) }
+ if let t = selectedTabID { store.moveItem(t, to: id, index: nil) }
}
}
/// Navigate the focused tab (an empty split pane gets its first page here).
func loadInSelectedTab(_ url: String) {
- guard let id = store.selectedTabID else { return }
+ guard let id = selectedTabID else { return }
let wasEmpty = store.item(id)?.isEmptyTab == true
store.updateTab(id, url: url)
if let rt = browsers.ensureRuntime(for: id), !wasEmpty { rt.browser.loadURL(url) }
refresh()
- browsers.show(store.visiblePaneTabIDs(in: store.focusedSpaceID), focused: id, focus: true)
+ browsers.show(store.visiblePaneTabIDs(in: focusedSpaceID, window: windowID), focused: id, focus: true)
}
// MARK: Find
@@ -1274,13 +1466,19 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func showSpaceEditor(space: Space?) {
guard let window else { return }
let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 520, height: 520), styleMask: [.titled], backing: .buffered, defer: false)
- let view = SpaceEditorView(existing: space, onSave: { [weak self, weak panel] title, emoji, theme in
+ let view = SpaceEditorView(existing: space, profiles: store.profiles, onSave: { [weak self, weak panel] title, emoji, theme, profile, newName in
guard let self else { return }
+ let id: UUID
if var s = space {
s.title = title; s.emoji = emoji; s.theme = theme
self.store.updateSpace(s)
+ id = s.id
} else {
- self.store.createSpace(title: title, emoji: emoji, theme: theme)
+ id = self.store.createSpace(title: title, emoji: emoji, theme: theme).id
+ }
+ switch profile {
+ case .existing(let p): self.store.setProfile(p, forSpace: id)
+ case .new: self.store.setProfile(self.store.createProfile(name: newName).id, forSpace: id)
}
if let panel { window.endSheet(panel) }
}, onCancel: { [weak panel] in if let panel { window.endSheet(panel) } })
@@ -1359,6 +1557,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func windowDidEnterFullScreen(_ notification: Notification) { shell.needsLayout = true }
func windowDidExitFullScreen(_ notification: Notification) {
+ // Left with the green button or ⌃⌘F while a video was fullscreen: the page leaves too.
+ if let id = contentFullscreenTab { browsers.runtime(for: id)?.browser.exitFullscreen() }
+ contentFullscreenTab = nil
if shell.contentFullscreen { shell.contentFullscreen = false }
enteredFullscreenForContent = false
shell.needsLayout = true
@@ -1366,13 +1567,36 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
private func saveFrame() {
guard let window, !window.styleMask.contains(.fullScreen) else { return }
- store.prefs.windowFrame = NSStringFromRect(window.frame)
+ store.updateWindow(windowID) { $0.frame = NSStringFromRect(window.frame) }
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
if sender === window { commandBar.close() }
return true
}
+
+ func windowWillClose(_ notification: Notification) {
+ guard (notification.object as? NSWindow) === window else { return }
+ tabSwitcher.cancel()
+ app.mainWindowWillClose(self)
+ }
+
+ /// The window closed while others stay open: its pages close (the tabs stay in
+ /// the sidebar) and it lets go of everything that would keep it alive.
+ func tearDown() {
+ isTornDown = true
+ dismissTransientUI()
+ browsers.closeAll()
+ for monitor in [scrollMonitor, childClickMonitor].compactMap({ $0 }) { NSEvent.removeMonitor(monitor) }
+ scrollMonitor = nil
+ childClickMonitor = nil
+ floatingSidebar?.hide(animated: false)
+ floatingSidebar = nil
+ for child in window?.childWindows ?? [] {
+ window?.removeChildWindow(child)
+ child.orderOut(nil)
+ }
+ }
}
diff --git a/Sources/Cra/UI/Windows/SpaceEditorView.swift b/Sources/Cra/UI/Windows/SpaceEditorView.swift
index 8861cf6..dfd51cd 100644
--- a/Sources/Cra/UI/Windows/SpaceEditorView.swift
+++ b/Sources/Cra/UI/Windows/SpaceEditorView.swift
@@ -1,10 +1,18 @@
import SwiftUI
-/// Create or edit a space: name, emoji, colors, intensity, grain, appearance
-/// (Arc: SpaceCreation + SpaceStyleEditor + SpaceIconPicker).
+/// The profile picked for a space: Default (nil), an existing one, or a new one to make.
+enum SpaceProfileChoice: Hashable {
+ case existing(UUID?)
+ case new
+}
+
+/// Create or edit a space: name, emoji, colors, intensity, grain, appearance, profile
+/// (Arc: SpaceCreation + SpaceStyleEditor + SpaceIconPicker + "Edit Space profile").
struct SpaceEditorView: View {
let existing: Space?
- let onSave: (String, String, SpaceTheme) -> Void
+ let profiles: [BrowserProfile]
+ /// Title, emoji, theme, profile; a new profile comes with its name.
+ let onSave: (String, String, SpaceTheme, SpaceProfileChoice, String) -> Void
let onCancel: () -> Void
@State private var title: String
@@ -12,12 +20,17 @@ struct SpaceEditorView: View {
@State private var theme: SpaceTheme
@State private var color1: Color
@State private var color2: Color
+ @State private var profile: SpaceProfileChoice
+ @State private var newProfileName = ""
private static let emojis = ["🌱", "💼", "🏠", "🎨", "🧪", "📚", "🎮", "🎵", "🛒", "✈️", "💡", "🔥", "🌊", "🍕", "🐦", "🧑‍💻",
"📈", "🧠", "❤️", "⭐️", "🌙", "☕️", "🏃", "📷", "🎬", "🧩", "🪴", "🏔️", "🛠️", "💰", "📝", "🎯"]
- init(existing: Space?, onSave: @escaping (String, String, SpaceTheme) -> Void, onCancel: @escaping () -> Void) {
+ init(existing: Space?, profiles: [BrowserProfile], onSave: @escaping (String, String, SpaceTheme, SpaceProfileChoice, String) -> Void,
+ onCancel: @escaping () -> Void) {
self.existing = existing
+ self.profiles = profiles
+ _profile = State(initialValue: .existing(existing?.profileID))
self.onSave = onSave
self.onCancel = onCancel
let t = existing?.theme ?? SpaceTheme.presets[Int.random(in: 0..<5)]
@@ -90,14 +103,16 @@ struct SpaceEditorView: View {
}
.pickerStyle(.segmented)
}
+ Divider()
+ profileSection
HStack {
Button("Cancel") { onCancel() }.keyboardShortcut(.cancelAction)
Spacer()
Button(existing == nil ? "Create Space" : "Save") {
- onSave(title.isEmpty ? "Space" : title, emoji.isEmpty ? "🌱" : emoji, theme)
+ onSave(title.isEmpty ? "Space" : title, emoji.isEmpty ? "🌱" : emoji, theme, profile, trimmedProfileName)
}
.keyboardShortcut(.defaultAction)
- .disabled(title.trimmingCharacters(in: .whitespaces).isEmpty && existing == nil)
+ .disabled((title.trimmingCharacters(in: .whitespaces).isEmpty && existing == nil) || (profile == .new && trimmedProfileName.isEmpty))
}
}
.padding(20)
@@ -105,6 +120,40 @@ struct SpaceEditorView: View {
.onChange(of: color1) { _, c in theme.colors = [c.hexString, color2.hexString] }
.onChange(of: color2) { _, c in theme.colors = [color1.hexString, c.hexString] }
}
+
+ private var trimmedProfileName: String { newProfileName.trimmingCharacters(in: .whitespaces) }
+
+ /// Arc's copy: "Profiles make your Spaces truly separate…" and, when an existing space
+ /// changes profile, "Each Profile has different browser data…".
+ private var profileSection: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack {
+ Picker("Profile", selection: $profile) {
+ Text("Default").tag(SpaceProfileChoice.existing(nil))
+ ForEach(profiles) { p in Text(p.name).tag(SpaceProfileChoice.existing(p.id)) }
+ Divider()
+ Text("New Profile…").tag(SpaceProfileChoice.new)
+ }
+ .frame(width: 260)
+ if profile == .new {
+ TextField("Profile name", text: $newProfileName).textFieldStyle(.roundedBorder)
+ }
+ }
+ Text(profileNote).font(.system(size: 11)).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ private var profileNote: String {
+ if let existing, profile != .existing(existing.profileID) {
+ return "Each Profile has different browser data, so you might get logged out of some websites or need to re-install extensions. Open tabs in this space reload."
+ }
+ if profile == .new {
+ return "This Space will start fresh in your brand new Profile, signed out of every website."
+ }
+ return "Profiles make your Spaces truly separate with their own logins, cookies and site data. Spaces with the same Profile share them."
+ }
}
extension Color {
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index 2e13b77..ece141b 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -38,10 +38,18 @@
// MARK: - Globals
static CefScopedLibraryLoader* g_libraryLoader = nullptr;
+static CefRefPtr<CefRequestContext> g_incognitoContext;
+/// Arc's Profiles: one request context per profile folder (spaces that share a profile share it).
+static std::map<std::string, CefRefPtr<CefRequestContext>> g_profileContexts;
+/// Profiles that finished loading, and browsers waiting for theirs: a Chrome-style
+/// browser view can't be made in a profile still loading from disk (CEF returns null).
+static NSMutableSet<NSString*>* g_readyProfiles = nil;
+static NSMutableDictionary<NSString*, NSMutableArray<CraBrowser*>*>* g_waitingForProfile = nil;
static std::atomic<bool> g_contextInitialized{false};
static std::atomic<int> g_liveBrowsers{0};
static bool g_quitting = false;
static bool g_useChromeStyle = false;
+static bool g_useMockKeychain = false;
static BOOL g_chromeHosting = NO;
static NSMutableArray<CraBrowser*>* g_pendingCreation = nil;
static void (^g_relaunchHandler)(NSArray<NSString*>*) = nil;
@@ -99,6 +107,7 @@ static CraClient* AsCraClient(CefClient* c) {
@property (nonatomic) BOOL closedByPage;
@property (nonatomic) BOOL isInPictureInPicture;
@property (nonatomic) BOOL isPictureInPicturePlaying;
+@property (nonatomic) BOOL isCapturingMedia;
- (void)requestPictureInPictureInFrame:(CefRefPtr<CefFrame>)frame automatic:(BOOL)automatic x:(int)x y:(int)y;
- (void)adoptBrowser:(CefRefPtr<CefBrowser>)browser;
- (void)devToolsBrowserCreated:(CefRefPtr<CefBrowser>)browser;
@@ -107,9 +116,12 @@ static CraClient* AsCraClient(CefClient* c) {
- (CefRefPtr<CefBrowser>)cefBrowser;
- (CefRefPtr<CefClient>)cefClient;
- (void)createNow;
+- (CefRefPtr<CefRequestContext>)requestContext;
- (void)hostWindowCreated:(NSWindow*)window;
- (void)hostPopupBrowserView:(CefRefPtr<CefBrowserView>)view;
@property (nonatomic, strong, nullable) NSWindow* hostWindow;
+/// The page's background as last reported by kBackgroundProbe (ARGB, white until then).
+@property (nonatomic) cef_color_t pageBackgroundColor;
@end
// MARK: - CEF app
@@ -265,6 +277,88 @@ static NSString* ManagedAuthServerAllowlist() {
return nil;
}
+/// 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.
+static void ApplyWebRTCPolicy(CefRefPtr<CefRequestContext> context) {
+ CefRefPtr<CefValue> policy = CefValue::Create();
+ policy->SetString("default_public_interface_only");
+ CefString error;
+ if (!context->SetPreference("webrtc.ip_handling_policy", policy, error)) {
+ NSLog(@"CraCEF: webrtc.ip_handling_policy: %s", error.ToString().c_str());
+ }
+}
+
+/// Cra shows downloads itself, the way Arc does (ADK hands Arc the download and Arc's own UI
+/// shows it; Chrome's toolbar UI never appears). Chrome's download bubble ("Recent download
+/// history") still pops up when a download finishes: with no toolbar to anchor to it is an
+/// invisible window over the page that swallows the next click. This is Chrome's "Show
+/// downloads when they're done" setting.
+static void HideDownloadBubble(CefRefPtr<CefRequestContext> context) {
+ CefRefPtr<CefValue> off = CefValue::Create();
+ off->SetBool(false);
+ CefString error;
+ if (!context->SetPreference("download_bubble.partial_view_enabled", off, error)) {
+ NSLog(@"CraCEF: download_bubble.partial_view_enabled: %s", error.ToString().c_str());
+ }
+}
+
+static void ApplyProfilePreferences(CefRefPtr<CefRequestContext> context) {
+ ApplyWebRTCPolicy(context);
+ HideDownloadBubble(context);
+}
+
+/// Profiles other than the global Default one get the same preferences once they load,
+/// then create the browsers that waited for them.
+class ProfileContextHandler : public CefRequestContextHandler {
+public:
+ explicit ProfileContextHandler(NSString* path = nil) : path_([path copy]) {}
+ void OnRequestContextInitialized(CefRefPtr<CefRequestContext> context) override {
+ ApplyProfilePreferences(context);
+ if (!path_) return;
+ if (!g_readyProfiles) g_readyProfiles = [NSMutableSet set];
+ [g_readyProfiles addObject:path_];
+ NSArray<CraBrowser*>* waiting = [g_waitingForProfile[path_] copy];
+ [g_waitingForProfile removeObjectForKey:path_];
+ for (CraBrowser* b in waiting) [b createNow];
+ }
+private:
+ NSString* path_;
+ IMPLEMENT_REFCOUNTING(ProfileContextHandler);
+};
+
+/// Incognito windows share one off-the-record profile (an empty cache path keeps
+/// cookies, storage and cache in memory) until the last of them closes.
+static CefRefPtr<CefRequestContext> IncognitoContext() {
+ if (!g_incognitoContext) g_incognitoContext = CefRequestContext::CreateContext(CefRequestContextSettings(), new ProfileContextHandler());
+ return g_incognitoContext;
+}
+
+/// A space's own profile: cookies, logins, storage and cache in a folder next to
+/// Default (it must sit under root_cache_path). nil is the global Default profile.
+static CefRefPtr<CefRequestContext> ProfileContext(NSString* path) {
+ if (!path.length) return nullptr;
+ std::string key = path.UTF8String;
+ auto it = g_profileContexts.find(key);
+ if (it != g_profileContexts.end()) return it->second;
+ CefRequestContextSettings settings;
+ CefString(&settings.cache_path) = CefStringFromNS(path);
+ settings.persist_session_cookies = true;
+ CefRefPtr<CefRequestContext> context = CefRequestContext::CreateContext(settings, new ProfileContextHandler(path));
+ g_profileContexts[key] = context;
+ return context;
+}
+
+/// Loads the profile if needed. NO means `browser` waits and is created once it has loaded.
+static BOOL ProfileReady(NSString* path, CraBrowser* browser) {
+ if (!path.length) return YES;
+ ProfileContext(path);
+ if ([g_readyProfiles containsObject:path]) return YES;
+ if (!g_waitingForProfile) g_waitingForProfile = [NSMutableDictionary dictionary];
+ if (!g_waitingForProfile[path]) g_waitingForProfile[path] = [NSMutableArray array];
+ if (![g_waitingForProfile[path] containsObject:browser]) [g_waitingForProfile[path] addObject:browser];
+ return NO;
+}
+
class CraApp : public CefApp, public CefBrowserProcessHandler {
public:
CefRefPtr<CefBrowserProcessHandler> GetBrowserProcessHandler() override { return this; }
@@ -277,10 +371,11 @@ public:
void OnBeforeCommandLineProcessing(const CefString& process_type,
CefRefPtr<CefCommandLine> command_line) override {
if (!process_type.empty()) return;
- // Avoid the "wants to use your confidential information stored in
- // Chromium Safe Storage" keychain prompt. Cookies are still encrypted,
- // just with a key that is not in the user's keychain.
- command_line->AppendSwitch("use-mock-keychain");
+ // Cookies and passwords are encrypted with the secret in the "Cra Safe Storage"
+ // Keychain item (SafeStorage.swift). Only unsigned dev builds on a profile that
+ // never used it keep the mock keychain, whose secret is a public constant: the
+ // Keychain would ask for the login password after every rebuild.
+ if (g_useMockKeychain) command_line->AppendSwitch("use-mock-keychain");
// Chrome-style windows are ours; Chrome must not restore or reopen them.
command_line->AppendSwitch("no-startup-window");
command_line->AppendSwitch("disable-session-crashed-bubble");
@@ -353,14 +448,7 @@ 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());
- }
+ ApplyProfilePreferences(CefRequestContext::GetGlobalContext());
g_contextInitialized = true;
NSArray<CraBrowser*>* pending = [g_pendingCreation copy];
[g_pendingCreation removeAllObjects];
@@ -729,6 +817,14 @@ public:
[o.delegate browser:o didChangeLoading:isLoading canGoBack:canGoBack canGoForward:canGoForward];
}
+ void OnLoadStart(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, TransitionType transition_type) override {
+ // The last page's colour must not show under the next one while it loads.
+ CraBrowser* o = owner_;
+ if (!o || !frame->IsMain()) return;
+ o.pageBackgroundColor = CefColorSetARGB(255, 255, 255, 255);
+ if (CefRefPtr<CefBrowserView> view = CefBrowserView::GetForBrowser(browser)) view->SetBackgroundColor(o.pageBackgroundColor);
+ }
+
void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) override {
// Every frame reports Picture in Picture changes (the events don't bubble, hence capture).
frame->ExecuteJavaScript(
@@ -788,6 +884,12 @@ public:
if (m.compare(0, bgPrefix.size(), bgPrefix) == 0) {
CraBrowser* o = owner_;
NSString* hex = HexFromCSSColor(m.substr(bgPrefix.size()));
+ if (o && hex.length) {
+ // Under the page (CraChromeViewDelegate::OnThemeChanged).
+ o.pageBackgroundColor = 0xFF000000 | (cef_color_t)strtoul(hex.UTF8String + 1, nullptr, 16);
+ if (CefRefPtr<CefBrowserView> view = CefBrowserView::GetForBrowser(browser))
+ view->SetBackgroundColor(o.pageBackgroundColor);
+ }
if (o && hex.length && [o.delegate respondsToSelector:@selector(browser:didReportBackgroundColor:)])
[o.delegate browser:o didReportBackgroundColor:hex];
return true;
@@ -844,6 +946,17 @@ public:
[o.delegate browser:o didChangeTitle:o.currentTitle];
}
+ // Arc's recording indicator ("This tab is using your camera or microphone").
+ void OnMediaAccessChange(CefRefPtr<CefBrowser> browser, bool has_video_access, bool has_audio_access) override {
+ CraBrowser* o = owner_;
+ if (!o) return;
+ BOOL capturing = has_video_access || has_audio_access;
+ if (capturing == o.isCapturingMedia) return;
+ o.isCapturingMedia = capturing;
+ if ([o.delegate respondsToSelector:@selector(browser:didChangeMediaCapture:)])
+ [o.delegate browser:o didChangeMediaCapture:capturing];
+ }
+
void OnFaviconURLChange(CefRefPtr<CefBrowser> browser, const std::vector<CefString>& icon_urls) override {
CraBrowser* o = owner_;
if (!o || icon_urls.empty()) return;
@@ -1119,6 +1232,14 @@ public:
return devtools_ || getenv("CRA_NO_CHROME_TOOLBAR") ? CEF_CTT_NONE : CEF_CTT_NORMAL;
}
cef_runtime_style_t GetBrowserRuntimeStyle() override { return CEF_RUNTIME_STYLE_CHROME; }
+ // CEF hides Chrome's web contents background, which makes the first page of each renderer
+ // transparent (chromiumembedded/cef#3891): a page with no background of its own showed this
+ // view's dark-mode fill (#1F1F1F) until a reload gave it a renderer CEF paints white. The
+ // view takes the page's own colour instead; CEF resets it on every theme change.
+ void OnThemeChanged(CefRefPtr<CefView> view) override {
+ CraBrowser* o = owner_;
+ if (!devtools_) view->SetBackgroundColor(o ? o.pageBackgroundColor : CefColorSetARGB(255, 255, 255, 255));
+ }
CefRefPtr<CefBrowserViewDelegate> GetDelegateForPopupBrowserView(CefRefPtr<CefBrowserView> browser_view,
const CefBrowserSettings& settings,
CefRefPtr<CefClient> client, bool is_devtools) override {
@@ -1204,9 +1325,21 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
}
- (instancetype)initWithFrame:(NSRect)frame url:(NSString*)url delegate:(id<CraBrowserDelegate>)delegate {
+ return [self initWithFrame:frame url:url delegate:delegate incognito:NO];
+}
+
+- (instancetype)initWithFrame:(NSRect)frame url:(NSString*)url delegate:(id<CraBrowserDelegate>)delegate incognito:(BOOL)incognito {
+ return [self initWithFrame:frame url:url delegate:delegate incognito:incognito profilePath:nil];
+}
+
+- (instancetype)initWithFrame:(NSRect)frame url:(NSString*)url delegate:(id<CraBrowserDelegate>)delegate
+ incognito:(BOOL)incognito profilePath:(NSString*)profilePath {
self = [super init];
if (!self) return nil;
_delegate = delegate;
+ _isIncognito = incognito;
+ _profilePath = incognito ? nil : [profilePath copy];
+ _pageBackgroundColor = CefColorSetARGB(255, 255, 255, 255);
_currentURL = url ?: @"";
_currentTitle = @"";
_pendingURL = url;
@@ -1230,10 +1363,12 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
- (void)createNow {
if (_isClosed || _browser) return;
+ if (!_isIncognito && !ProfileReady(_profilePath, self)) return;
if (g_chromeHosting) {
CefBrowserSettings settings;
CefRefPtr<CefBrowserView> view = CefBrowserView::CreateBrowserView(
- _client, CefStringFromNS(_pendingURL ?: @"about:blank"), settings, nullptr, nullptr, new CraChromeViewDelegate(self));
+ _client, CefStringFromNS(_pendingURL ?: @"about:blank"), settings, nullptr,
+ [self requestContext], new CraChromeViewDelegate(self));
CefWindow::CreateTopLevelWindow(new CraChromeWindowDelegate(self, view));
return;
}
@@ -1244,7 +1379,11 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
if (g_useChromeStyle) windowInfo.runtime_style = CEF_RUNTIME_STYLE_CHROME;
CefBrowserSettings settings;
CefBrowserHost::CreateBrowser(windowInfo, _client, CefStringFromNS(_pendingURL ?: @"about:blank"), settings,
- nullptr, nullptr);
+ nullptr, [self requestContext]);
+}
+
+- (CefRefPtr<CefRequestContext>)requestContext {
+ return _isIncognito ? IncognitoContext() : ProfileContext(_profilePath);
}
- (CefRefPtr<CefBrowser>)cefBrowser { return _browser; }
@@ -1292,6 +1431,7 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
- (void)reload { if (_browser) _browser->Reload(); }
- (void)reloadIgnoringCache { if (_browser) _browser->ReloadIgnoreCache(); }
- (void)stopLoading { if (_browser) _browser->StopLoad(); }
+- (void)exitFullscreen { if (_browser) _browser->GetHost()->ExitFullscreen(true); }
- (void)setFocused:(BOOL)focused {
if (_browser) _browser->GetHost()->SetFocus(focused);
@@ -1567,10 +1707,10 @@ private:
// Chrome window (title bar, location bar) the moment the first browser is
// created. Cra restores its own tabs, so the saved session is dropped and the
// profile marked clean before Chromium reads it.
-static void MarkProfileExitedCleanly(NSString* cachePath) {
- NSString* sessions = [cachePath stringByAppendingPathComponent:@"Default/Sessions"];
+static void MarkProfileExitedCleanly(NSString* profileDir) {
+ NSString* sessions = [profileDir stringByAppendingPathComponent:@"Sessions"];
[[NSFileManager defaultManager] removeItemAtPath:sessions error:nil];
- NSString* prefs = [cachePath stringByAppendingPathComponent:@"Default/Preferences"];
+ NSString* prefs = [profileDir stringByAppendingPathComponent:@"Preferences"];
NSData* data = [NSData dataWithContentsOfFile:prefs];
if (!data) return;
NSError* error = nil;
@@ -1629,9 +1769,11 @@ static void MarkProfileExitedCleanly(NSString* cachePath) {
+ (BOOL)initializeWithCachePath:(NSString*)cachePath
userAgentProduct:(NSString*)product
logPath:(NSString*)logPath
- useChromeStyle:(BOOL)useChromeStyle {
+ useChromeStyle:(BOOL)useChromeStyle
+ useMockKeychain:(BOOL)useMockKeychain {
if (g_libraryLoader) return YES;
g_useChromeStyle = useChromeStyle;
+ g_useMockKeychain = useMockKeychain;
g_libraryLoader = new CefScopedLibraryLoader();
if (!g_libraryLoader->LoadInMain()) {
NSLog(@"CraCEF: failed to load Chromium Embedded Framework");
@@ -1651,7 +1793,12 @@ static void MarkProfileExitedCleanly(NSString* cachePath) {
settings.log_severity = LOGSEVERITY_WARNING;
settings.background_color = CefColorSetARGB(255, 255, 255, 255);
- MarkProfileExitedCleanly(cachePath);
+ // Default plus the spaces' own profiles ("Profile <id>").
+ for (NSString* name in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cachePath error:nil]) {
+ if ([name isEqualToString:@"Default"] || [name hasPrefix:@"Profile "]) {
+ MarkProfileExitedCleanly([cachePath stringByAppendingPathComponent:name]);
+ }
+ }
CefRefPtr<CraApp> app(new CraApp());
if (!CefInitialize(mainArgs, settings, app.get(), nullptr)) {
int code = CefGetExitCode();
@@ -1673,7 +1820,12 @@ static void MarkProfileExitedCleanly(NSString* cachePath) {
+ (void)runMessageLoop { CefRunMessageLoop(); }
+ (void)quitMessageLoop { CraQuitMessageLoop(); }
-+ (void)shutdown { CefShutdown(); }
++ (void)shutdown {
+ g_incognitoContext = nullptr;
+ g_profileContexts.clear();
+ g_waitingForProfile = nil;
+ CefShutdown();
+}
+ (void)closeAllBrowsersAndQuit {
g_quitting = true;
@@ -1687,6 +1839,7 @@ static void MarkProfileExitedCleanly(NSString* cachePath) {
}
+ (NSInteger)liveBrowserCount { return g_liveBrowsers; }
++ (void)endIncognitoSession { g_incognitoContext = nullptr; }
+ (NSString*)chromiumVersion {
return [NSString stringWithFormat:@"%d.%d.%d.%d", CHROME_VERSION_MAJOR, CHROME_VERSION_MINOR,
CHROME_VERSION_BUILD, CHROME_VERSION_PATCH];
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index 561a92f..5a9ff7e 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -79,6 +79,8 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
/// Find in page progress: `count` matches, `activeMatch` is the highlighted one
/// (1-based). Either is -1 while Chromium has no new value for it.
- (void)browser:(CraBrowser *)browser didFindMatches:(NSInteger)count activeMatch:(NSInteger)activeMatch;
+/// The page started or stopped using the camera or microphone.
+- (void)browser:(CraBrowser *)browser didChangeMediaCapture:(BOOL)capturing;
@end
@interface CraBrowser : NSObject
@@ -102,10 +104,19 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
@property (nonatomic, readonly) BOOL hasDevTools;
/// Anything you want to hang on the browser (Swift stores the tab id).
@property (nonatomic, strong, nullable) id userInfo;
+/// Runs in the shared off-the-record profile (+[CraCEFRuntime endIncognitoSession]).
+@property (nonatomic, readonly) BOOL isIncognito;
+/// The profile folder this page's cookies, logins and storage live in (a space's own
+/// profile, under the cache root), or nil for the Default profile.
+@property (nonatomic, readonly, copy, nullable) NSString *profilePath;
/// Pass a URL to create a browser now. Pass nil to create a popup host that
/// adopts the next popup CEF gives it (see -browser:popupHostForURL:...).
- (instancetype)initWithFrame:(NSRect)frame url:(nullable NSString *)url delegate:(nullable id<CraBrowserDelegate>)delegate;
+- (instancetype)initWithFrame:(NSRect)frame url:(nullable NSString *)url delegate:(nullable id<CraBrowserDelegate>)delegate
+ incognito:(BOOL)incognito;
+- (instancetype)initWithFrame:(NSRect)frame url:(nullable NSString *)url delegate:(nullable id<CraBrowserDelegate>)delegate
+ incognito:(BOOL)incognito profilePath:(nullable NSString *)profilePath;
- (void)loadURL:(NSString *)url;
- (void)goBack;
@@ -113,6 +124,8 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
- (void)reload;
- (void)reloadIgnoringCache;
- (void)stopLoading;
+/// Leaves element fullscreen (a video), as Esc does.
+- (void)exitFullscreen;
- (void)setFocused:(BOOL)focused;
- (void)showDevToolsInspectingPoint:(NSPoint)point;
- (void)showDevTools;
@@ -132,6 +145,8 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
@property (nonatomic, readonly) BOOL isInPictureInPicture;
/// YES while that video is playing.
@property (nonatomic, readonly) BOOL isPictureInPicturePlaying;
+/// The page is using the camera or microphone (Chromium's media access state).
+@property (nonatomic, readonly) BOOL isCapturingMedia;
/// Play/pause the video in the Picture in Picture window.
- (void)togglePictureInPicturePlayback;
/// Seek the video in the Picture in Picture window by `seconds` (negative = back).
@@ -179,7 +194,8 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
+ (BOOL)initializeWithCachePath:(NSString *)cachePath
userAgentProduct:(NSString *)product
logPath:(NSString *)logPath
- useChromeStyle:(BOOL)useChromeStyle;
+ useChromeStyle:(BOOL)useChromeStyle
+ useMockKeychain:(BOOL)useMockKeychain;
/// Runs the Chromium-integrated AppKit run loop. Returns after -quitMessageLoop.
+ (void)runMessageLoop;
+ (void)quitMessageLoop;
@@ -187,6 +203,9 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
/// Closes every browser, then quits the message loop once they are gone.
+ (void)closeAllBrowsersAndQuit;
+ (NSInteger)liveBrowserCount;
+/// The last incognito window closed: the next incognito page starts a fresh
+/// off-the-record profile (no cookies or storage carried over).
++ (void)endIncognitoSession;
/// YES when initialize failed because another Cra is running and was told
/// about this launch (exit quietly).
+ (BOOL)anotherInstanceWasNotified;
diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.md
index 6f41bbe..38e7bec 100644
--- a/docs/arc-reverse-engineering.md
+++ b/docs/arc-reverse-engineering.md
@@ -745,6 +745,69 @@ of the sidebar strip, pixel runs at x=500 px (2x), y = 160/700/1200/1700/2100.
dark bars, black 5 % on light ones); on example.com Cra reads 34 with 45 at rows 82–83,
Arc 34 with 45 at rows 84–85 (Cra's line sits inside the 32 pt strip, Arc's just under it).
+### Closing vs removing pinned tabs (Arc 1.170, 27 Oct 2026, field metadata + live hover recordings)
+- [O static] `SharedWindowFeature.SidebarCellCloseButtonConfiguration { action, tooltip: String }` with
+ `Action { deselect, close, unsplit }`; the tab cell state carries it as an optional, next to `canResetTab`,
+ `resetTabTitle`, `resetTabIcon`, `closeItemShortcut`, `resetItemShortcut` and
+ `shouldPerformUserAttentionAnimation`.
+- [O live] Pinned tab that is the current tab: no button until hovered, then a **minus** (—) with the
+ tooltip "Close and Keep Pinned ⌘W". Clicking it unloads the tab, keeps it pinned, selects the tab used
+ before it (a Today tab here), scrolls the sidebar to that tab and flashes a dashed yellow ring around it.
+- [O live] Any other pinned tab (here unloaded ones: Canteen plan, Dashboard): hover shows **✕** with the
+ tooltip "Archive this tab". The ✕ removes the tab from the pinned section into the archive (going by the
+ tooltip; not clicked, to keep Victor's pinned tabs).
+- [I] A pinned tab that is loaded but in the background also gets ✕ (`deselect` only makes sense for the
+ current tab; the one capture of a not-yet-current Temp Mail showed ✕). Not confirmed: Arc stopped
+ taking synthetic input before that test finished.
+- [?] Arc's pinned-tab context-menu titles (short Swift literals are inline in code, not in `strings`).
+- Cra (TabRow): current pinned → `minus`, "Close and Keep Pinned (⌘W)", unload + reset + select the
+ most recently active tab (`SidebarStore.mostRecentTab`); other pinned → ✕, "Archive this tab",
+ `archiveTab`. Context menu: "Close and Keep Pinned" (only when open/loaded) and "Archive Tab". The URL
+ tooltip moved from the row to the title so the buttons' tooltips show. No attention ring yet.
+- Tooltips on these buttons (ArcTooltip module, field metadata): `ArcTooltipConfiguration { content,
+ keyboardShortcut, preferredAnchor: .view(edge) | .cursor, presentationBehavior: .onMouseIdle(delay) |
+ .immediate, maxWidth, colorPalette }`, `TooltipController { presentationTimer, lastTooltipDismissedAtTime,
+ … }`. [O live, 1x recordings] Shown 1.60 s after the pointer's last move (two cases, 30 fps); moving
+ straight from one tip to another control swaps at once; pops in with no fade, fades out in ~2 frames.
+ Navy capsule 28 pt, no visible border, 12 pt medium text (fill 96 for "Canteen plan", 110 for
+ "Archive this tab", 198 for "Close and Keep Pinned ⌘W"), 10 pt side padding, 7 pt text→caps, caps
+ ~18 pt with a darker 2 px bottom band (~#777AD3), 3 pt apart. Button tips hang off the bottom-trailing
+ corner of a 16 pt box around the glyph (fill top-left = glyph centre + (8, 7)); row tips ("Canteen plan",
+ the title) follow the cursor at +(13, 14).
+- Cra: `ArcTooltip.swift` (`.arcTooltip(help)`, one shared non-activating child panel, `(⌘W)` suffixes
+ become caps) on SidebarIconButton, ToolbarIcon and ToolbarImageButton. Measured against Arc on the
+ same 1x screen: delay 1.63 s, widths 198/109, height within 1 px; a click dismisses and the next tip waits
+ for idle again. Toolbar/header placement uses the same rule but was not compared with Arc's toolbar. Row
+ tooltips stay native (URL); Arc shows the title in its own pill there.
+- [O static] Arc's tooltip inventory (strings whose translator comment starts "Tooltip"): sidebar "Archive
+ this tab", "Close and Keep Pinned", reset pinned tab, mute/unmute tab, camera/mic indicator ("This tab is
+ using your camera or microphone"), renameable tab subtitle "Double-click to rename", "Separate from Split
+ View", close a tab group, folder create/close ("Close This Folder")/archive, "Clear Today tabs" / "Clear
+ unselected Today tabs", "Organize Today Tabs", space header "Edit Space theme" / "Edit Space profile" /
+ space options, dock "Drag to Reorder Space", Library button, Site Control Center ("Capture a portion of
+ this page", "Capture the full page", copy URL, new Boost, share, ad-blocker states, extension add/pin/unpin),
+ PiP (back to tab, close, minimise), Little Arc copy URL/extensions. Short values (< 16 bytes) are inline in
+ code, so only their comments are listed.
+- Cra (27 Oct): every sidebar/toolbar/Site Control Center/PiP tooltip now uses `.arcTooltip`; tab rows,
+ favorites, split rows and URL fields use the cursor anchor and show the title (Arc) instead of the URL;
+ the innermost hovered control owns the tip; the Today "Clear" button got "Clear Today tabs".
+- Added after that: a muted tab's speaker is a button ("Unmute Tab"); a red dot "This tab is using your
+ camera or microphone" from CEF's OnMediaAccessChange (CraBrowser.isCapturingMedia →
+ SidebarUIState.capturingTabIDs); the split close button reads "Separate from Split View" while ⌥ is held
+ (Arc's allowedModifierKeys / option-click-to-unsplit); "Double-click to rename" as a second line of the
+ row tip, once (Arc: WindowData+RenameHints, `renameHintItemID`, `setRenameHint`, `didShowRenameHint`; Cra
+ shows it on the first row tip of a tab without a custom name, then sets `didShowRenameHint`). Long
+ titles wrap at 280 pt, up to 3 lines (Arc has `maxWidth`, value unknown). Looks of the dot, the mute glyph
+ and the two-line tip are Cra's; Arc's weren't observed. Arc shows the speaker for audible tabs too; CEF
+ has no audible callback short of an audio handler that takes over playback, so Cra shows it when muted.
+ A live Arc sweep (toolbar back/forward/reload, Site Control Center, split menu, favorites, space header,
+ folder) failed: a stuck hover-preview card blocked all of Arc's tooltips, so whether those controls show
+ a tip in Arc is still open.
+- Testing notes: in Arc, still captures taken ~1 s after a pointer move often show the previous hover
+ state; record `screencapture -V` instead. AX `AXScroll*ByPage` on Arc's list scrolled the drawing out of
+ step with the hit-testing, so later clicks landed on other rows. In Cra, `cliclick c:` is too fast for
+ the row's SwiftUI tap; `dd: w:80 du:` selects.
+
### Backdrop-layer blur for light vibrant themes (25 Oct 2026, final)
The system materials could not reproduce Arc's intercept and slope together, so
@@ -934,11 +997,23 @@ browsers on this Mac read read-only. Dia's onboarding itself was not re-run past
PBKDF2-SHA1(secret, "saltysalt", 1003, 16), IV = 16×0x20; the secret is the login-Keychain item
"<Name> Safe Storage" (one OS password prompt per browser). Cookies DB version ≥ 24 prefixes the
plaintext with SHA-256(host_key) — checked to confirm the key, and re-added for Cra's own profile.
- Cra re-encrypts every row with its own key (Cra runs Chromium `--use-mock-keychain`, secret
- "mock_password") and stages them to `pending-credentials.json` (0600); `main.swift` writes them into
+ Cra re-encrypts every row with its own key (the secret in Cra's "Cra Safe Storage" item,
+ `SafeStorage.swift`) and stages them to `pending-credentials.json` (0600); `main.swift` writes them into
the profile's `Cookies` / `Login Data` before CEF starts (both are locked while Chromium runs) and
only when no other instance is up, then deletes the file. Verified end-to-end against this Mac's Dia
profile (1 login + 3052 cookies decrypted, staged, applied on relaunch, idempotent on re-run).
+- [O] Cra's own Safe Storage (reported by Rainatsu, 27 Oct 2026). Until then Cra ran Chromium with
+ `--use-mock-keychain`, so its profile's v10 values used the public secret "mock_password", and imports
+ moved Keychain-protected data under it. Now Chromium reads "Cra Safe Storage" (account "Chromium"):
+ `scripts/cef-patches/keychain-service-name.patch`, and for the cef-156.0.14-codecs2 framework a
+ binary patch in `fetch-cef.sh`. The compiler folded the name's length (21) into both places that copy it
+ into a `std::string` (`mov wN, #0x15` at 0x215fe50 / 0x215ff8c), and builds the 8-byte account
+ "Chromium" from `movk` immediates. Padding a shorter name with NULs is therefore not enough: the
+ lengths must be patched too, and the account cannot be renamed that way. Before Chromium starts, a
+ signed Cra creates the item (16 random bytes, base64, as Chromium does) and, the first time, re-encrypts
+ every mock-keychain BLOB in each profile's Cookies / Login Data / Web Data databases and the staged
+ import. Unsigned dev builds stay on the mock keychain for profiles that never used the Keychain.
+ `Sessions_Encrypted` is not migrated (Cra does not use Chromium's session restore).
- [U] Dia's exact top-sites ranking, its default checkbox states, and the encrypted SNSS v2/v4 session
format. Firefox saved logins are not read from `logins.json`/`key4.db`; Cra takes Firefox passwords
only via its own exported CSV, like Safari.
@@ -1325,3 +1400,89 @@ Arc's popup this time, so geometry is not measured.
- 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).
+
+## Downloads and Chrome's download bubble (Arc 1.170, 27 Oct 2026, static strings + Cra test)
+
+- Arc never shows Chromium's download UI. Downloads go through ADK (`ADK.ContextDownloadDelegate`,
+ `ArcBrowserContextDownloadsDelegate`, `ADKClient/DownloadManager.swift`) into Arc's own views:
+ `DownloadsUI.DownloadToLibraryWindowController`, the Library's downloads page (`HomeButton/DownloadsPageReducer`,
+ `DownloadsContentView`, filter by profile), Little Arc's `LittleBrowserDownloadsTrayViewController`, plus Tidy
+ Downloads renaming (`DownloadRenamedToastContentView`). Arc's Chromium profile sets no `download_bubble.*` pref:
+ Chrome's toolbar UI simply isn't there.
+- Cra (CEF Chrome style) handles every download itself (OnBeforeDownload returns true), but Chrome's bubble still
+ popped up when a download finished: a window titled "Recent Download History" (320×120 for one item), invisible
+ with no toolbar to anchor to, which swallowed the next click on the page. Cra turns it off the way Chrome's
+ "Show downloads when they're done" setting does: `download_bubble.partial_view_enabled` = false on the global and
+ incognito request contexts (CraCEF.mm HideDownloadBubble). Verified in a test instance: no bubble window, the first
+ click after a download reaches the page, Cra's toast still shows.
+- Chrome's download-started animation (DownloadBubbleStartedAnimationViews, Chromium 156.0.8078.48): a views popup
+ parented to the page, `accept_events = false`, 2 × kIconBackgroundRadius 32 = 64×64 pt, 500 ms, flying to the hidden
+ toolbar's download button. Only reduced motion turns it off (CEF_CTBT_DOWNLOAD is deprecated: downloads became a
+ pinned toolbar action). Cra orders that window out as it appears (ChromeDownloadAnimation, a 2 s watch after each
+ new download); verified: every sighting of the 64×64 window was off screen.
+
+### Arc's download animation (DownloadsUI.DownloadToLibrary, live, 60 fps app-only ScreenCaptureKit captures)
+
+ObjC metadata: `DownloadToLibrary.ViewModel` (_downloads, _binPositionX, windowSize, binPositionXAnimator, showsBin,
+animationGroup), `DownloadViewModel` (source, destination, _projectileIconKeyframeAnimation, _iconOffsetX,
+iconOffsetXAnimator, iconBounceAnimator, lazy g / vx0 / vy0 / projectileMotionDuration / apex / apexTime),
+`WindowController` (parentWindow, dismiss, isAnimating): a window over the browser window. Measured (window 1728×1084):
+- Source is the pointer (logged with `cliclick p` every 30 ms): the glyph launched at the pointer; with the pointer off
+ to the right of the window it entered from the window's edge. Destination is the bin.
+- Projectile: constant horizontal speed (−1232 pt/s on a 1361 pt run, every frame within ~10 pt), apex 90 pt above
+ the launch point, g ≈ 2630 pt/s²; 1.10 s from the top of the page to the bin.
+- Glyph: navy disc #04072A, ring #EFEFFF, white down arrow, faint blue glow. Ring diameter 32 pt at launch, 48 pt at the
+ apex, then linear down to ~10 pt at the bin; opacity rises linearly to 1 by the apex; the arrow reads ↘ early and
+ ↓ by mid-flight.
+- Bin: the file's Quick Look thumbnail (a .txt showed its text on a white page), 32 pt, ~8 pt corners, resting 9 pt
+ right of and 12 pt above the Library glyph's centre (the glyph's box peeks out under it). It appears with the launch
+ 6 pt high, drops to 12 pt low at ~0.15 s, back to −2 pt, settled by ~0.4 s. Faint grey while Arc's window is in
+ the background, white when it is key. It leaves 30 s after the glyph lands (appeared 8.47 s, faded 39.37-39.53 s
+ in a 60 fps capture), fading over 0.15 s, the same with Arc in front or behind.
+- With Tidy Downloads on, Arc also shows a "Download renamed to:" card above the bin; Cra has no Tidy Downloads.
+- Cra: DownloadFlight (overlay panel, Core Animation keyframes sampled from the same projectile) and DownloadBin in
+ SpaceDock. Verified side by side with fixed-source test builds.
+- Tidy Downloads card (only with Arc Max's renaming): in over ~0.2 s once the rename is ready, gone after 8.0 s in
+ under 0.1 s. Prompt and inputs (filename, tab title, domain; JSON `newName`) are in the binary next to
+ beginRename(browserContextID:downloadID:defaultFilename:sourceUrl:webContentsTitle:referrerTitle:). Not built in
+ Cra: Victor doesn't want AI features for now (27 Oct 2026).
+
+### Arc's downloads list on hovering the Library button (live, 60 fps, 1728×1084 window)
+
+- Rows for the recent downloads still on disk, oldest at the top, the newest ending 2 pt below the list viewport
+ (just above the dock). Rows 56 pt apart: 40 pt thumbnail (Quick Look, 6 pt corners) at x 8, the file name at
+ x 61 in 14 pt white 82 %, "54 seconds ago" (RelativeDateTimeFormatter, full) in 12 pt white 50 %. Four rows were
+ observed with four downloads available; the maximum is unknown (Cra shows five).
+- The tab list behind is hidden from 3 pt above the first row and fades back in linearly over the 170 pt above it.
+- Opens 0.2 s into the hover: rows fade in and rise 5 pt in ~0.12 s, bottom row first, ~25 ms apart; the fade comes
+ in over ~0.18 s. Closes ~0.07 s after the pointer leaves: rows gone within ~0.05 s (bottom first), the fade
+ out over ~0.13 s. Arc's own "View Library ⇧⌘L" tooltip shows under the button meanwhile.
+- Cra: DownloadsTray / DownloadsTrayMask (sidebar), DownloadHistory (downloads.json). The mask must be a single
+ GeometryReader gradient: fixed-height layers in it raised the sidebar's minimum height and the window grew.
+
+## Tab switcher (Arc 1.170, 27 Oct 2026, live: 100 fps region recordings + 1× stills)
+
+Arc's `ModalItemSwitcher` (`ModalItemSwitcherWindowController`, `ModalItemSwitcherSnapshotUpdateCancellableID`;
+strings "Opens the tab switcher, where you can cycle through recent tabs like Command+Tab on your computer!" and
+"Cycles backwards through your most recent tabs…"). Arc's help centre: the five most recently visited tabs.
+
+- **List:** the focused space's tabs by `timeLastActiveAt`, newest first (checked against StorableSidebar.json: the
+ JYSK space's top four plus one more JYSK tab, skipping a newer one in another space). The current tab is card 0.
+- **Keys:** ⌃Tab opens on card 1 and moves on; ⇧Tab, ← and → move too. All of them wrap at both ends. Releasing ⌃
+ switches, Esc cancels (the tab stays). A tap (⌃ up 0.13 s after Tab) switches with no panel; the panel appeared
+ 0.18–0.26 s after the key, so there is a short show delay.
+- **Pointer:** moving over a card selects it (no separate hover style). It stays selected after the pointer leaves.
+- **No animation:** the panel appears, moves its selection and closes from one frame to the next.
+- **Geometry (pt):** centred on the whole window (sidebar included), integral origin. Panel 941×190 for five cards:
+ 16.5 left/right, 16 top/bottom, cards 180×158 on a 182 pitch. Thumbnail 158×105 at (11.5, 12), corners about 6.5
+ (continuous), soft shadow below. Title row under it: favicon 16×16 at (13.5, 130.5), title 8 pt after it, SF 14
+ medium (ink width of "Example Domain" 108 px, "DL nine" 48 px, cap top to baseline 148–160 from the panel top), tail
+ truncation. Panel corners continuous ≈ 26, card highlight ≈ 8.
+- **Colours (dark):** panel #1C1B1A, 1 px outer line #030303, 1 px inner line #504F4F (white 23%). Empty thumbnail
+ #1C1C1C. Missing favicon: a rounded square, white 14%. Selected card: the space's semantic `hover` colour
+ (JYSK dark: extended sRGB 0.360/0.392/1.019 at α 0.48, measured 58/61/136 over the panel). In Arc's data both
+ spaces' dark `hover` sit at OKLab L ≈ 0.60 in the theme's hue near sRGB's maximum chroma; Cra derives it that way
+ from the theme accent. Light appearance not observed (the Mac runs dark); Cra's light colours are a guess.
+- **Cra test (CraTK, pid-targeted keys):** geometry, borders, text and favicon position match Arc's captures to the
+ pixel. Thumbnails come from `Page.captureScreenshot` of the visible viewport (Chromium draws nothing for hidden
+ pages), taken 1 s after a tab shows or finishes loading and again for the current tab when the switcher opens.
diff --git a/scripts/cef-patches/keychain-service-name.patch b/scripts/cef-patches/keychain-service-name.patch
new file mode 100644
index 0000000..8844039
--- /dev/null
+++ b/scripts/cef-patches/keychain-service-name.patch
@@ -0,0 +1,13 @@
+diff --git a/components/os_crypt/common/keychain_password_mac.mm b/components/os_crypt/common/keychain_password_mac.mm
+--- a/components/os_crypt/common/keychain_password_mac.mm
++++ b/components/os_crypt/common/keychain_password_mac.mm
+@@ -30,5 +30,8 @@
+ const char kDefaultAccountName[] = "Chrome";
+ #else
+-const char kDefaultServiceName[] = "Chromium Safe Storage";
++// Cra: its own item rather than the one every Chromium-based app shares. Cra creates
++// it before Chromium starts (SafeStorage.swift); the account stays "Chromium", as in
++// the items Cra made with the 156 framework scripts/fetch-cef.sh patched.
++const char kDefaultServiceName[] = "Cra Safe Storage";
+ const char kDefaultAccountName[] = "Chromium";
+ #endif
diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.sh
index 27dd310..5188e67 100755
--- a/scripts/fetch-cef.sh
+++ b/scripts/fetch-cef.sh
@@ -42,4 +42,27 @@ if [ ! -f vendor/cef/build/libcef_dll_wrapper/libcef_dll_wrapper.a ]; then
-DCMAKE_OSX_ARCHITECTURES=arm64 > vendor/cef/build-configure.log
cmake --build vendor/cef/build --target libcef_dll_wrapper -j "$(sysctl -n hw.ncpu)" > vendor/cef/build-wrapper.log
fi
+
+# Chromium encrypts cookies, passwords and card numbers with a secret from the login
+# Keychain item "Chromium Safe Storage", which every Chromium-based app without its own
+# name shares. Cra's is "Cra Safe Storage" (SafeStorage.swift creates it before Chromium
+# starts; scripts/cef-patches/keychain-service-name.patch renames it in CEF builds).
+# cef-156.0.14-codecs2 predates that patch, so its framework is patched here: the name
+# in os_crypt's constant pool, and the length (21) the compiler folded into both places
+# that copy it into a std::string. Any other build must come with the source patch.
+# Stop rather than ship a framework that looks for the old item: Cra would encrypt with
+# one secret and Chromium decrypt with another.
+FRAMEWORK_BIN="vendor/cef/Release/Chromium Embedded Framework.framework/Chromium Embedded Framework"
+if LC_ALL=C grep -qa "Chromium Safe Storage" "$FRAMEWORK_BIN"; then
+ if [ "$(shasum -a 256 "$FRAMEWORK_BIN" | cut -d' ' -f1)" != a910874407a9064fb6a944b2ffa0f86d9b5e1ea0a790608e8febea8d4949c7be ]; then
+ echo "This CEF build still uses Chromium Safe Storage; build it with scripts/cef-patches" >&2
+ exit 1
+ fi
+ patch_at() { printf "$2" | dd of="$FRAMEWORK_BIN" bs=1 seek=$(($1)) conv=notrunc status=none; }
+ patch_at 0xc4fcaa1 'Cra Safe Storage\000\000\000\000\000' # was "Chromium Safe Storage"
+ patch_at 0x215fe50 '\011\002\200\122' # mov w9, #16 (was #21)
+ patch_at 0x215ff8c '\010\002\200\122' # mov w8, #16 (was #21)
+ echo "Renamed the Keychain item to Cra Safe Storage"
+fi
+LC_ALL=C grep -qa "Cra Safe Storage" "$FRAMEWORK_BIN" || { echo "CEF names no Cra Safe Storage" >&2; exit 1; }
echo "CEF ready: vendor/cef"