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.
Cra 0.1.23: Arc's now-playing player, split favorites, folder previews, tab sleeping that works (#35)
Victor Kildahl3298608585af
diff --git a/README.md b/README.mdindex cabe36a..6e41594 100644--- a/README.md+++ b/README.md@@ -68,7 +68,7 @@ Embedded Framework, so sites and Chrome extensions work as they do in Chrome.| Import from Arc | ✅ || Easels | Not yet || Boosts | Not yet |-| Peek | Not yet |+| Peek | ✅ || Notes | Not yet || Arc Max | No, Cra has no built-in AI |diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex d1d842a..3e3cc4a 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -46,6 +46,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {installURLEventHandler()CraCEFRuntime.setChromeHosting(store.settings.chromeEngine)CraCEFRuntime.setOwnContextMenus(EmbeddedPages.isEnabled)+ CraCEFRuntime.setDocumentStartScript(PageScript.mainWorld, isolatedScript: PageScript.isolatedWorld, world: PageScript.world)startContentBlocking()SoftwareUpdater.shared.start(app: self)buildMenus()@@ -496,11 +497,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {return}if let st = dict["status"] { main.browserManager(statusMessage: st); return }+ if let t = dict["selectTab"].flatMap(UUID.init(uuidString:)) { store.selectTab(t, window: main.windowID); return }+ // One tab-sleeping pass with a short threshold (seconds), so it can be tried without waiting.+ if let s = dict["sleepTabs"].flatMap(Double.init) {+ for w in mainWindows { w.browsers.sleepIdleTabs(hiddenLongerThan: s) }+ return+ }// Opens what normally needs a pointer or a held key, for screenshots.if let v = dict["downloads"] { main.sidebarUI.downloadsListOpen = v == "1"; return }if let v = dict["banner"] { SoftwareUpdater.shared.debugUpdated(v == "none" ? nil : v); return }if dict["switcher"] != nil { main.debugTabSwitcher(); return }if dict["jumpPill"] != nil { SpaceListView.jumpToSelected(for: main.sidebarUI, space: store.focusedSpaceID); return }+ if let f = dict["folderPreview"] {+ if let id = UUID(uuidString: f) { SpaceListView.debugFolderPreview(id, ui: main.sidebarUI) } else { FolderPreviewController.shared.close() }+ return+ }if dict["littlePopup"] != nil { littleWindows.first?.togglePopup(); return }if let c = dict["combine"], let content = main.window?.contentView {let tabs = store.children(of: store.focusedSpace.todayContainerID).filter { $0.tab != nil }diff --git a/Sources/Cra/Model/SidebarModel.swift b/Sources/Cra/Model/SidebarModel.swiftindex 8fad12f..4f97e1c 100644--- a/Sources/Cra/Model/SidebarModel.swift+++ b/Sources/Cra/Model/SidebarModel.swift@@ -205,14 +205,19 @@ struct SpaceTheme: Codable, Equatable {var vibrant: Bool = false/// The theme's raw first colour (Arc's base colour); drives the toolbar band.var accent: String? = nil+ /// Arc's one-colour theme (blendedSingleColor): a flat fill laid over a dark, slightly+ /// see-through material, at `intensity` (SpacePalette.solidAlpha), not a gradient.+ var solid: Bool = false- init(colors: [String], intensity: Double, noise: Double, appearance: String, vibrant: Bool = false, accent: String? = nil) {+ init(colors: [String], intensity: Double, noise: Double, appearance: String, vibrant: Bool = false, accent: String? = nil,+ solid: Bool = false) {self.colors = colorsself.intensity = intensityself.noise = noiseself.appearance = appearanceself.vibrant = vibrantself.accent = accent+ self.solid = solid}init(from decoder: Decoder) throws {@@ -223,6 +228,7 @@ struct SpaceTheme: Codable, Equatable {appearance = try c.decodeIfPresent(String.self, forKey: .appearance) ?? "auto"vibrant = try c.decodeIfPresent(Bool.self, forKey: .vibrant) ?? falseaccent = try c.decodeIfPresent(String.self, forKey: .accent)+ solid = try c.decodeIfPresent(Bool.self, forKey: .solid) ?? false}/// Dark first: colors borrowed from Victor's other projects (GhostWriter@@ -436,9 +442,15 @@ struct AppSettings: Codable, Equatable {/// Arc's "Open a Peek window when clicking on links to other sites" (modalEnabled): only/// links clicked in favorites and pinned tabs.var peekLinksToOtherSites: Bool = true+ /// Cra's addition (issue #12): links to other sites peek from every tab, not only+ /// favorites and pinned tabs.+ var peekInEveryTab: Bool = false/// Arc's "Open a Peek window when clicking on links with Shift held"/// (shiftClickModalEntryPointEnabled).var peekOnShiftClick: Bool = true+ /// Arc's Previews ▸ Folders (folderPreviewEnabled): resting the pointer on a closed folder+ /// lists its tabs, most recent first, with a search field.+ var folderPreviews: Bool = true/// Arc: "Enable Picture in Picture when you leave a video tab".var autoPictureInPicture: Bool = true/// Dia's onboarding privacy choice "Block third-party ads and trackers": requests@@ -562,7 +574,9 @@ extension AppSettings {// Settings from before Air Traffic Control get Arc's Google Meet route once.linkRoutes = c.contains(.linkRoutes) ? (try? c.decode([LinkRoute].self, forKey: .linkRoutes)) ?? [] : [.googleMeet]peekLinksToOtherSites = try c.decodeIfPresent(Bool.self, forKey: .peekLinksToOtherSites) ?? true+ peekInEveryTab = try c.decodeIfPresent(Bool.self, forKey: .peekInEveryTab) ?? falsepeekOnShiftClick = try c.decodeIfPresent(Bool.self, forKey: .peekOnShiftClick) ?? true+ folderPreviews = try c.decodeIfPresent(Bool.self, forKey: .folderPreviews) ?? truehapticFeedbackOnReorder = try c.decodeIfPresent(Bool.self, forKey: .hapticFeedbackOnReorder) ?? truewarnBeforeQuitting = try c.decodeIfPresent(Bool.self, forKey: .warnBeforeQuitting) ?? falseautoArchiveEnabled = try c.decodeIfPresent(Bool.self, forKey: .autoArchiveEnabled) ?? truediff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swiftindex 9c698f7..5745ab5 100644--- a/Sources/Cra/Services/BrowserManager.swift+++ b/Sources/Cra/Services/BrowserManager.swift@@ -22,6 +22,10 @@ final class TabRuntime {var hiddenAt: Date? = Date()/// Invalidates a pending sleep probe even when navigation returns to the same URL.var navigationRevision: UInt = 0+ /// A page that refused to sleep isn't asked again before this (nil: ask on the next pass).+ var sleepProbeAfter: Date?+ /// Why the page last refused to sleep ("" when it didn't), so the log says it once.+ var sleepRefusal: String?/// Chrome-style hosting: the page's own window (nil until created, or for Alloy).var hostWindow: NSWindow? { browser.hostWindow }init(tabID: UUID, browser: CraBrowser) {@@ -73,6 +77,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {var windowID: UUID?/// A tab's live page held by another window's manager, handed over (see `release`).var takeRuntimeFromOtherWindow: ((UUID) -> TabRuntime?)?+ /// The window's sidebar player (Arc's "now playing"), fed with this manager's pages.+ var nowPlaying: NowPlaying?private var byBrowser: [ObjectIdentifier: UUID] = [:]/// CEF's client holds its owner weakly; keep retired browsers alive until teardown finishes.private var closingBrowsers: [ObjectIdentifier: CraBrowser] = [:]@@ -149,6 +155,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {/// their window belongs to this one.func release(_ tabID: UUID) -> TabRuntime? {guard let rt = runtimes.removeValue(forKey: tabID) else { return nil }+ nowPlaying?.remove(tabID)+ nowPlaying?.pictureInPicture.remove(tabID)byBrowser[ObjectIdentifier(rt.browser)] = nilrt.snapshotWork?.cancel()rt.snapshotWork = nil@@ -189,6 +197,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {guard let rt = ensureRuntime(for: id) else { shown.append(id); continue }if !wasVisible.contains(id) { returnToTab(rt) }rt.hiddenAt = nil+ rt.sleepProbeAfter = nillet v = rt.browser.containerView// Alloy hosting only: the Chromium view moves into its pane. Chrome-style// pages live in their own windows; re-parenting their view makes Chrome@@ -209,6 +218,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {}}visibleTabIDs = shown+ if let np = nowPlaying, np.onScreen != Set(shown) { np.onScreen = Set(shown) }visibleTabID = focused.flatMap { newSet.contains($0) ? $0 : nil } ?? shown.firstif wasVisible != Set(shown) { HitchMonitor.mark("page-shown") }if focus, let f = visibleTabID, let rt = runtimes[f] { rt.browser.setFocused(true) }@@ -286,58 +296,99 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {/// Settings ▸ Tabs ▸ "Sleep tabs I haven't looked at in": a page off screen that long/// closes, like a closed pinned tab, and loads its URL again when shown. Pages that are- /// loading, playing sound, recording, in Picture in Picture or DevTools, holding typed- /// text or asking before they close (beforeunload) stay awake.+ /// loading, playing sound, recording, in Picture in Picture or DevTools, holding text the+ /// user typed or asking before they close (their own onbeforeunload) stay awake, and are+ /// asked again only after `refusalBackoff`. The log says once why a page stays awake.func sleepIdleTabs(hiddenLongerThan seconds: TimeInterval) {- let cutoff = Date().addingTimeInterval(-seconds)+ let now = Date()+ let cutoff = now.addingTimeInterval(-seconds)for (id, rt) in runtimes {let b = rt.browser- guard canSleep(rt, before: cutoff) else { continue }+ guard canSleep(rt, before: cutoff), rt.sleepProbeAfter.map({ $0 <= now }) ?? true else { continue }let url = b.currentURLlet navigationRevision = rt.navigationRevision- b.sendDevToolsMethod("Runtime.evaluate", params: Self.sleepProbe) { [weak self, weak rt] result, _ in+ // Cra's isolated world sees typed text and media; the page's own onbeforeunload is only+ // visible from the page's world, so that's asked second.+ b.evaluate(inIsolatedWorld: PageScript.world, params: Self.sleepProbe) { [weak self, weak rt] result, _ inDispatchQueue.main.async {- guard let self, let rt, let current = self.runtimes[id], current === rt,- current.navigationRevision == navigationRevision, current.browser.currentURL == url,- self.canSleep(current, before: cutoff),- Self.probeSaysIdle(result) else { return }- self.unload(id)+ guard let self, let rt, self.stillSleepable(id, rt, url, navigationRevision, cutoff) else { return }+ let refusal = Self.sleepRefusal(result)+ guard refusal.isEmpty else { return self.keepAwake(rt, url, refusal) }+ rt.browser.sendDevToolsMethod("Runtime.evaluate", params: Self.beforeUnloadProbe) { [weak self, weak rt] result, _ in+ DispatchQueue.main.async {+ guard let self, let rt, self.stillSleepable(id, rt, url, navigationRevision, cutoff) else { return }+ let refusal = Self.sleepRefusal(result)+ guard refusal.isEmpty else { return self.keepAwake(rt, url, refusal) }+ if !rt.browser.isIncognito {+ NSLog("Cra: tab sleep unloads %@ (hidden %d min)", Self.logHost(url),+ Int(Date().timeIntervalSince(rt.hiddenAt ?? Date()) / 60))+ }+ self.unload(id)+ }+ }}}}}+ private func stillSleepable(_ id: UUID, _ rt: TabRuntime, _ url: String, _ revision: UInt, _ cutoff: Date) -> Bool {+ runtimes[id] === rt && rt.navigationRevision == revision && rt.browser.currentURL == url && canSleep(rt, before: cutoff)+ }++ /// Asked again after the back-off; the log names the site once per reason (never an incognito one).+ private func keepAwake(_ rt: TabRuntime, _ url: String, _ refusal: String) {+ rt.sleepProbeAfter = Date().addingTimeInterval(Self.refusalBackoff)+ if rt.sleepRefusal != refusal, !rt.browser.isIncognito { NSLog("Cra: tab sleep keeps %@ awake: %@", Self.logHost(url), refusal) }+ rt.sleepRefusal = refusal+ }++ static let refusalBackoff: TimeInterval = 10 * 60++ /// Only the host: logs get shared in bug reports.+ private static func logHost(_ url: String) -> String {+ URL(string: url).flatMap { $0.host ?? $0.scheme.map { "\($0):" } } ?? "(no page)"+ }+private func canSleep(_ rt: TabRuntime, before cutoff: Date) -> Bool {let b = rt.browserreturn rt.hiddenAt.map { $0 < cutoff } == true && !visibleTabIDs.contains(rt.tabID)&& b.isCreated && !b.isClosed && !b.isLoading && !b.isInPictureInPicture- && !b.isCapturingMedia && !b.hasDevTools+ && !b.isCapturingMedia && !b.isAudible && !b.hasDevTools}- /// true when the page has nothing to lose: no audible media, no edited fields, no- /// beforeunload handler (closing would ask "Leave site?" on a page nobody is looking at).+ /// In Cra's isolated world: "" when the page has nothing to lose, else why it must stay:+ /// media playing, or text the user typed that is still there on the same URL (PageScript+ /// records trusted input; values a framework set, or text submitted by a navigation, don't+ /// count).private static let sleepProbe: String = {let js = """(() => {- const playing = [...document.querySelectorAll('video,audio')].some(m => !m.paused && !m.ended && !m.muted && m.volume > 0);- const typed = [...document.querySelectorAll('input,textarea,select')].some(e =>- e.type === 'checkbox' || e.type === 'radio' ? e.checked !== e.defaultChecked+ if ([...document.querySelectorAll('video,audio')].some(m => !m.paused && !m.ended && !m.muted && m.volume > 0)) return 'playing';+ const edited = e => e.isContentEditable ? e.textContent.trim() !== ''+ : e.type === 'checkbox' || e.type === 'radio' ? e.checked !== e.defaultChecked: e.tagName === 'SELECT' ? [...e.options].some(o => o.selected !== o.defaultSelected)- : !['hidden','submit','button','reset','image','file','search'].includes(e.type) && e.value !== e.defaultValue);- const editing = document.activeElement?.isContentEditable === true;- const guarded = !!window.onbeforeunload || (getEventListeners(window).beforeunload || []).length > 0;- return !(playing || typed || editing || guarded);+ : (e.value ?? '') !== '';+ for (const [e, href] of window.__cra?.typed ?? []) {+ if (!e.isConnected || href !== location.href) { window.__cra.typed.delete(e); continue; }+ if (edited(e)) return 'typed';+ }+ return '';})()"""- let params: [String: Any] = ["expression": js, "returnByValue": true, "includeCommandLineAPI": true]- return String(data: try! JSONSerialization.data(withJSONObject: params), encoding: .utf8)!+ return evaluateParams(js, userGesture: false)}()- private static func probeSaysIdle(_ result: String?) -> Bool {+ /// In the page's world (leaves nothing behind): the page's own onbeforeunload. Listeners a+ /// framework adds with addEventListener don't count: nearly every app registers one, and the+ /// user never sees most of them fire.+ private static let beforeUnloadProbe = evaluateParams("typeof window.onbeforeunload === 'function' ? 'beforeunload' : ''", userGesture: false)++ /// The probe's answer; anything but a clean "" (an exception, no reply) refuses.+ private static func sleepRefusal(_ result: String?) -> String {guard let data = result?.data(using: .utf8),- let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- json["exceptionDetails"] == nil,- let value = (json["result"] as? [String: Any])?["value"] as? Bool else { return false }+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return "no reply" }+ guard json["exceptionDetails"] == nil else { return "probe failed" }+ guard let value = (json["result"] as? [String: Any])?["value"] as? String else { return "no reply" }return value}@@ -404,6 +455,9 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {func browser(_ browser: CraBrowser, didChangePictureInPicture active: Bool) {guard let id = tabID(of: browser), let rt = runtimes[id] else { return }+ if let np = nowPlaying, np.pictureInPicture.contains(id) != active {+ if active { np.pictureInPicture.insert(id) } else { np.pictureInPicture.remove(id) }+ }if active {// The floating window's hover controls act on this tab.PictureInPictureChrome.shared.actions = PictureInPictureActions(@@ -440,9 +494,98 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {delegate?.browserManagerDidUpdate(id)}+ func browser(_ browser: CraBrowser, didChangeAudible audible: Bool) {+ guard let id = tabID(of: browser) else { return }+ if let np = nowPlaying {+ if np.entries.contains(where: { $0.id == id }) {+ np.update(id) { $0.playing = audible }+ } else if audible {+ np.entries.append(.init(id: id, playing: true))+ }+ if audible { refreshMediaControls(id) }+ }+ delegate?.browserManagerDidUpdate(id)+ }++ // MARK: Now playing++ /// Play/pause, previous and next for the sidebar player. The page's own media session+ /// handlers go first (PageScript keeps them; YouTube, Spotify and SoundCloud skip tracks+ /// that way), else the page's media elements. Runs as a user gesture so play() is allowed.+ func performNowPlaying(_ id: UUID, _ action: NowPlaying.Action) {+ let op: String+ switch action {+ case .togglePlayback: op = "toggle"+ case .previous: op = "previoustrack"+ case .next: op = "nexttrack"+ case .dismiss: op = "pause"; nowPlaying?.remove(id)+ case .pictureInPicture:+ runtimes[id]?.browser.requestPictureInPicture(automatic: false)+ return+ case .setVolume(let v):+ nowPlaying?.update(id) { $0.volume = v }+ let js = "(v => { if (window.__cra) window.__cra.volume = v; document.querySelectorAll('video,audio').forEach(m => m.volume = v); })(\(max(0, min(1, v))))"+ runtimes[id]?.browser.evaluate(inIsolatedWorld: PageScript.world, params: Self.evaluateParams(js, userGesture: false)) { _, _ in }+ return+ case .toggleMute, .show: return+ }+ guard let rt = runtimes[id] else { nowPlaying?.remove(id); return }+ let js = """+ ((op) => {+ const cra = window.__cra, has = cra ? cra.query() : [];+ const media = [...document.querySelectorAll('video,audio')];+ const playing = media.some(m => !m.paused && !m.ended);+ if (op === 'toggle') op = playing ? 'pause' : 'play';+ if (has.includes(op)) cra.send(op);+ else if (op === 'pause') media.forEach(m => m.pause());+ else if (op === 'play') (media.find(m => m.currentTime > 0 && !m.ended) ?? media[0])?.play();+ return op === 'pause' ? 'paused' : op === 'play' ? 'playing' : playing ? 'playing' : 'paused';+ })(\(Self.jsonString(op)))+ """+ // No user gesture: the page has been playing, so it already has its activation, and the+ // page's own handlers shouldn't get a fresh one from Cra (PageScript).+ rt.browser.evaluate(inIsolatedWorld: PageScript.world, params: Self.evaluateParams(js, userGesture: false)) { [weak self] result, _ in+ DispatchQueue.main.async {+ guard let state = Self.stringResult(result) else { return }+ self?.nowPlaying?.update(id) { $0.playing = state == "playing" }+ }+ }+ }++ /// Which track buttons the page answers (media session handlers).+ private func refreshMediaControls(_ id: UUID) {+ let js = """+ (() => { const has = window.__cra?.query() ?? [];+ return (has.includes('previoustrack') ? 'p' : '') + (has.includes('nexttrack') ? 'n' : '') + (document.querySelector('video') ? 'v' : ''); })()+ """+ runtimes[id]?.browser.evaluate(inIsolatedWorld: PageScript.world, params: Self.evaluateParams(js, userGesture: false)) { [weak self] result, _ in+ DispatchQueue.main.async {+ guard let has = Self.stringResult(result) else { return }+ self?.nowPlaying?.update(id) { $0.hasPrevious = has.contains("p"); $0.hasNext = has.contains("n"); $0.hasVideo = has.contains("v") }+ }+ }+ }++ private static func evaluateParams(_ js: String, userGesture: Bool) -> String {+ let params: [String: Any] = ["expression": js, "returnByValue": true, "userGesture": userGesture]+ return String(data: try! JSONSerialization.data(withJSONObject: params), encoding: .utf8)!+ }++ private static func jsonString(_ s: String) -> String {+ String(data: try! JSONSerialization.data(withJSONObject: [s]), encoding: .utf8)!.dropFirst().dropLast().description+ }++ private static func stringResult(_ result: String?) -> String? {+ guard let data = result?.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], json["exceptionDetails"] == nil else { return nil }+ return (json["result"] as? [String: Any])?["value"] as? String+ }+func browser(_ browser: CraBrowser, didChangeURL url: String) {guard let id = tabID(of: browser) else { return }runtimes[id]?.navigationRevision &+= 1+ // A quiet page that navigates leaves the player; a playlist moving on keeps its card.+ if !browser.isAudible { nowPlaying?.remove(id) }// Our own error page is a data: URL; keep the real address in the model.if url.hasPrefix("data:text/html;base64,") { return }store.updateTab(id, url: url)diff --git a/Sources/Cra/Services/Import/Importers.swift b/Sources/Cra/Services/Import/Importers.swiftindex 421822e..124d978 100644--- a/Sources/Cra/Services/Import/Importers.swift+++ b/Sources/Cra/Services/Import/Importers.swift@@ -181,7 +181,9 @@ enum ArcImporter {i += 2}}- var sp = ImportedSpace(title: title, emoji: emoji, theme: theme(from: space))+ // A space without a theme is Arc's default dark purple, close to Ink. Not the next+ // preset: that shifted every later space onto another colour (issue #30).+ var sp = ImportedSpace(title: title, emoji: emoji, theme: theme(from: space) ?? SpaceTheme.presets[0])let profile = space["profile"] as? NSDictionarysp.favorites = favoritesByProfile.first { $0.profile.isEqual(profile) }?.items ?? allFavoritesif let p = pinnedID, let c = items[p] { sp.pinned = (c["childrenIds"] as? [String] ?? []).compactMap(convert) }@@ -273,11 +275,25 @@ enum ArcImporter {guard let v = variant else { return nil }if let a = v["contentOverBackgroundAppearance"] as? String { appearance = a }let vibrant = v["isVibrant"] as? Bool ?? false- guard let style = v["style"] as? [String: Any], let color = style["color"] as? [String: Any],- let c0 = color["_0"] as? [String: Any], let bg2 = c0["blendedGradient"] as? [String: Any],- let g = bg2["_0"] as? [String: Any], let base = g["baseColors"] as? [[String: Any]], !base.isEmpty else { return nil }- let overlays = g["overlayColors"] as? [[String: Any]] ?? []func comp(_ c: [String: Any], _ k: String) -> Double { max(0, min(1, c[k] as? Double ?? 0)) }+ func hexOf(_ c: [String: Any]) -> String {+ String(format: "#%02X%02X%02X", Int((comp(c, "red") * 255).rounded()),+ Int((comp(c, "green") * 255).rounded()), Int((comp(c, "blue") * 255).rounded()))+ }+ let c0 = ((v["style"] as? [String: Any])?["color"] as? [String: Any])?["_0"] as? [String: Any]+ // A solid colour (Arc's colour picker with one dot) is `blendedSingleColor`. Themes+ // Cra can't read still carry Arc's derived palette, whose mid tone keeps the hue.+ if let s = (c0?["blendedSingleColor"] as? [String: Any])?["_0"] as? [String: Any], let c = s["color"] as? [String: Any] {+ let mods = s["modifiers"] as? [String: Any]+ return solidTheme(hexOf(c), intensity: mods?["intensityFactor"] as? Double ?? 1,+ noise: mods?["noiseFactor"] as? Double ?? 0, appearance: appearance)+ }+ guard let bg2 = c0?["blendedGradient"] as? [String: Any], let g = bg2["_0"] as? [String: Any],+ let base = g["baseColors"] as? [[String: Any]], !base.isEmpty else {+ guard let mid = (wt["primaryColorPalette"] as? [String: Any])?["midTone"] as? [String: Any] else { return nil }+ return solidTheme(hexOf(mid), intensity: 1, noise: 0, appearance: appearance)+ }+ let overlays = g["overlayColors"] as? [[String: Any]] ?? []// Arc blends an overlay gradient onto the base gradient and the wheel// mixes the two base colours; bake both into our two stops (fitted to// Arc's rendering: top stop leans toward the second base colour).@@ -331,6 +347,12 @@ enum ArcImporter {return SpaceTheme(colors: colors, intensity: intensity,noise: mods?["noiseFactor"] as? Double ?? 0.15, appearance: appearance, vibrant: vibrant, accent: accent)}++ /// One flat colour (SpaceTheme.solid). Arc draws it the same whether or not it is+ /// marked vibrant, so only the colour, intensity and text appearance carry over.+ private static func solidTheme(_ hex: String, intensity: Double, noise: Double, appearance: String) -> SpaceTheme {+ SpaceTheme(colors: [hex, hex], intensity: intensity, noise: noise, appearance: appearance, accent: hex, solid: true)+ }}// MARK: - Diadiff --git a/Sources/Cra/Services/NowPlaying.swift b/Sources/Cra/Services/NowPlaying.swiftnew file mode 100644index 0000000..69a7562--- /dev/null+++ b/Sources/Cra/Services/NowPlaying.swift@@ -0,0 +1,43 @@+import Foundation+import Observation++/// Arc's "now playing" player at the bottom of the sidebar (issue #33): every tab of the+/// window that played sound since it loaded, oldest first. A tab stays listed while paused+/// and leaves when it is dismissed, closes, sleeps, or navigates while quiet. The sidebar+/// shows the ones that aren't on screen. Fed by BrowserManager.+@MainActor @Observable+final class NowPlaying {+ struct Entry: Equatable, Identifiable {+ let id: UUID+ var playing: Bool+ /// The page registered media session handlers for these (else the buttons are dimmed).+ var hasPrevious = false+ var hasNext = false+ /// A video plays: the card offers Picture in Picture.+ var hasVideo = false+ /// The tab's media volume (Arc's volume drawer), 0...1.+ var volume = 1.0+ }++ enum Action { case togglePlayback, previous, next, toggleMute, dismiss, show, pictureInPicture, setVolume(Double) }++ var entries: [Entry] = []+ /// Tabs in the window's panes, and tabs whose video is in Picture in Picture: no card.+ var onScreen: Set<UUID> = []+ var pictureInPicture: Set<UUID> = []+ @ObservationIgnored var perform: (UUID, Action) -> Void = { _, _ in }++ /// Oldest first, as Arc stacks them (the newest is the front card).+ var shown: [Entry] { entries.filter { !onScreen.contains($0.id) && !pictureInPicture.contains($0.id) } }++ func update(_ id: UUID, _ change: (inout Entry) -> Void) {+ guard let i = entries.firstIndex(where: { $0.id == id }) else { return }+ var e = entries[i]+ change(&e)+ if e != entries[i] { entries[i] = e }+ }++ func remove(_ id: UUID) {+ if entries.contains(where: { $0.id == id }) { entries.removeAll { $0.id == id } }+ }+}diff --git a/Sources/Cra/Services/PageScript.swift b/Sources/Cra/Services/PageScript.swiftnew file mode 100644index 0000000..56d0287--- /dev/null+++ b/Sources/Cra/Services/PageScript.swift@@ -0,0 +1,52 @@+import Foundation++/// Scripts that run in every page before its own (CraCEFRuntime.setDocumentStartScript), so Cra+/// can read what the page itself doesn't expose. Almost all of it runs in an isolated world the+/// page can't see (Chrome extensions' content scripts work the same way); `window.__cra` exists+/// only there:+///+/// - `typed`: fields the user typed into (trusted input events only, so values a framework sets+/// don't count), with the URL they were typed on. Tab sleeping keeps such a page awake.+/// - `volume`: the sidebar player's volume drawer; media that starts playing later gets it too.+/// - `send(action)` / `handlers`: the page's media session handlers (YouTube, Spotify…), so the+/// player can skip tracks. `setActionHandler` can't be called from outside and its handlers+/// live in the page's world, so a small wrapper there keeps them in a closure and answers an+/// event whose name is random per launch: nothing in the page's world names Cra.+enum PageScript {+ static let world = "cra"+ private static let channel = "c" + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()++ /// The page's world: only the media session wrapper.+ static let mainWorld = """+ (() => {+ const proto = window.MediaSession?.prototype, set = proto?.setActionHandler;+ if (!set) return;+ const handlers = {};+ Object.defineProperty(proto, 'setActionHandler', { configurable: true, writable: true,+ value: { setActionHandler(action, handler) {+ if (handler) handlers[action] = handler; else delete handlers[action];+ return set.call(this, action, handler);+ } }.setActionHandler });+ addEventListener('\(channel)', e => {+ if (e.detail === '?') return dispatchEvent(new CustomEvent('\(channel)r', { detail: Object.keys(handlers).join(',') }));+ try { handlers[e.detail]?.({ action: e.detail }); } catch {}+ });+ })();+ """++ /// Cra's isolated world.+ static let isolatedWorld = """+ (() => {+ if (window.__cra) return;+ const cra = window.__cra = { typed: new Map(), volume: 1, handlers: [] };+ addEventListener('play', e => { if (cra.volume < 1 && e.target instanceof HTMLMediaElement) e.target.volume = cra.volume; }, true);+ addEventListener('input', e => {+ const t = e.isTrusted && e.composedPath()[0];+ if (t instanceof Element) cra.typed.set(t, location.href);+ }, true);+ addEventListener('\(channel)r', e => { cra.handlers = String(e.detail || '').split(',').filter(Boolean); });+ cra.send = action => dispatchEvent(new CustomEvent('\(channel)', { detail: action }));+ cra.query = () => (cra.send('?'), cra.handlers);+ })();+ """+}diff --git a/Sources/Cra/Services/SidebarExport.swift b/Sources/Cra/Services/SidebarExport.swiftnew file mode 100644index 0000000..693e584--- /dev/null+++ b/Sources/Cra/Services/SidebarExport.swift@@ -0,0 +1,82 @@+import AppKit+import UniformTypeIdentifiers++/// Every space's favorites, pinned tabs and folders as a Netscape bookmark file: the+/// format Chrome, Safari, Firefox and Cra's Safari import all read,+/// and a plain nested list when opened in a browser. A space is a folder, its favorites+/// a "Favorites" folder inside it; split views give their panes to the folder they are in.+/// Today tabs are left out, as Arc archives them.+enum SidebarExport {+ @MainActor+ static func bookmarksHTML(_ store: SidebarStore, date: Date = Date()) -> String {+ var out = """+ <!DOCTYPE NETSCAPE-Bookmark-file-1>+ <!-- Spaces and pinned tabs exported from Cra on \(date.formatted(date: .long, time: .shortened)). -->+ <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">+ <TITLE>Cra Spaces</TITLE>+ <H1>Cra Spaces</H1>+ <DL><p>++ """+ func line(_ depth: Int, _ s: String) { out += String(repeating: " ", count: depth) + s + "\n" }+ func folder(_ name: String, created: Date, depth: Int, _ body: () -> Void) {+ line(depth, "<DT><H3 ADD_DATE=\"\(stamp(created))\">\(escape(name))</H3>")+ line(depth, "<DL><p>")+ body()+ line(depth, "</DL><p>")+ }+ func items(under id: UUID, depth: Int) {+ for item in store.children(of: id) {+ if let tab = item.tab {+ guard !item.isEmptyTab else { continue }+ let url = tab.savedURL.isEmpty ? tab.url : tab.savedURL+ line(depth, "<DT><A HREF=\"\(escape(url))\" ADD_DATE=\"\(stamp(item.createdAt))\">\(escape(item.displayTitle))</A>")+ } else if item.isSplit {+ items(under: item.id, depth: depth)+ } else if item.isFolder {+ folder(item.displayTitle, created: item.createdAt, depth: depth) { items(under: item.id, depth: depth + 1) }+ }+ }+ }+ for space in store.orderedSpaces {+ let name = space.emoji.isEmpty ? space.title : "\(space.emoji) \(space.title)"+ folder(name, created: space.createdAt, depth: 1) {+ if !store.tabs(under: space.favoritesContainerID).isEmpty {+ folder("Favorites", created: space.createdAt, depth: 2) { items(under: space.favoritesContainerID, depth: 3) }+ }+ items(under: space.pinnedContainerID, depth: 2)+ }+ }+ out += "</DL><p>\n"+ return out+ }++ /// Asks where to save, then writes the file. `window` hosts the panel as a sheet.+ @MainActor+ static func run(_ store: SidebarStore, in window: NSWindow?) {+ let panel = NSSavePanel()+ panel.title = "Export Spaces"+ panel.message = "Spaces, favorites and pinned tabs, as a bookmarks file any browser can import."+ panel.nameFieldStringValue = "Cra Spaces \(Date().formatted(.iso8601.year().month().day())).html"+ panel.allowedContentTypes = [.html]+ panel.canCreateDirectories = true+ let html = bookmarksHTML(store)+ let done: (NSApplication.ModalResponse) -> Void = { response in+ guard response == .OK, let url = panel.url else { return }+ do {+ try html.write(to: url, atomically: true, encoding: .utf8)+ NSWorkspace.shared.activateFileViewerSelecting([url])+ } catch {+ NSAlert(error: error).runModal()+ }+ }+ if let window { panel.beginSheetModal(for: window, completionHandler: done) } else { done(panel.runModal()) }+ }++ private static func stamp(_ date: Date) -> Int { Int(date.timeIntervalSince1970) }++ private static func escape(_ s: String) -> String {+ s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<")+ .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)+ }+}diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swiftindex 8fb8508..64356ca 100644--- a/Sources/Cra/Services/SidebarStore.swift+++ b/Sources/Cra/Services/SidebarStore.swift@@ -858,15 +858,19 @@ final class SidebarStore {/// Favorites belong to one space: the tab's own unless another is given.func addToFavorites(_ id: UUID, in spaceID: UUID? = nil) {- // A favorite is one page's tile; a split can be pinned but not a favorite.- guard items[id]?.isSplit != true else { return }+ // A pane brings its whole split: Arc's top apps hold a split as one tile (AppItem.childItems).+ let id = splitContaining(id)?.id ?? id+ guard let it = items[id], it.isTab || it.isSplit else { return }guard let space = spaces[spaceID ?? self.spaceID(ofItem: id) ?? focusedSpaceID] else { return }// A new favorite takes the tile color when every existing one shares it.- let colors = Set(tabs(under: space.favoritesContainerID).map { $0.tab?.tileColor })+ let colors = Set(favoriteTabs(in: space).map { $0.tab?.tileColor })moveItem(id, to: space.favoritesContainerID, index: nil)if colors.count == 1, let color = colors.first!, items[id]?.tab?.tileColor == nil { setTileColor(color, for: [id]) }}+ /// The favorites' own tabs, not the panes of favorite splits.+ func favoriteTabs(in space: Space) -> [SidebarItem] { children(of: space.favoritesContainerID).filter(\.isTab) }+func setTileColor(_ hex: String?, for ids: [UUID]) {for id in ids {guard var it = items[id], var t = it.tab else { continue }@@ -886,6 +890,7 @@ final class SidebarStore {}func removeFromFavorites(_ id: UUID) {+ let id = splitContaining(id)?.id ?? idguard let space = spaceID(ofItem: id).flatMap({ spaces[$0] }) else { return }moveItem(id, to: space.pinnedContainerID, index: nil)}diff --git a/Sources/Cra/UI/ArcTooltip.swift b/Sources/Cra/UI/ArcTooltip.swiftindex b98a08c..3085841 100644--- a/Sources/Cra/UI/ArcTooltip.swift+++ b/Sources/Cra/UI/ArcTooltip.swift@@ -199,8 +199,10 @@ final class ArcTooltipAnchorView: NSView, ArcTooltipTarget {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))+ var options: NSTrackingArea.Options = [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect]+ // Rebuilt under the pointer (its control moved): no mouseEntered comes, so only this gets the mouseExited.+ if let w = window, visibleRect.contains(convert(w.mouseLocationOutsideOfEventStream, from: nil)) { options.insert(.assumeInside) }+ addTrackingArea(NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil))}override func mouseEntered(with event: NSEvent) { MainActor.assumeIsolated { ArcTooltipController.shared.mouseMoved(in: self) } }diff --git a/Sources/Cra/UI/Settings/AdvancedPane.swift b/Sources/Cra/UI/Settings/AdvancedPane.swiftindex dcd487d..4e94b4f 100644--- a/Sources/Cra/UI/Settings/AdvancedPane.swift+++ b/Sources/Cra/UI/Settings/AdvancedPane.swift@@ -44,6 +44,12 @@ struct AdvancedPane: View {.font(.system(size: 11)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)}+ SettingsFormRow(label: "Export:") {+ Button("Export Spaces and Pinned Tabs…") { SidebarExport.run(store, in: NSApp.keyWindow) }+ Text("Save every space's favorites, pinned tabs and folders as a bookmarks file that Chrome, Safari, Firefox and other browsers can import.")+ .font(.system(size: 11)).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }SettingsFormRow(label: "About:") {Text("Cra \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev")").font(.system(size: 13))Text("Chromium \(CraCEFRuntime.chromiumVersion()) · CEF \(CraCEFRuntime.cefVersion())")diff --git a/Sources/Cra/UI/Settings/TabsPane.swift b/Sources/Cra/UI/Settings/TabsPane.swiftindex fb7b5c8..7ca0c5a 100644--- a/Sources/Cra/UI/Settings/TabsPane.swift+++ b/Sources/Cra/UI/Settings/TabsPane.swift@@ -13,6 +13,7 @@ struct TabsPane: View {SettingsCheckbox(title: "Add new tabs to the top", isOn: $store.settings.newTabsAtTop)SettingsCheckbox(title: "Show the New Tab button above tabs", isOn: $store.settings.newTabButtonAtTop)SettingsCheckbox(title: "Haptic feedback when reordering tabs", isOn: $store.settings.hapticFeedbackOnReorder)+ SettingsCheckbox(title: "Preview a folder’s tabs when hovering over it", isOn: $store.settings.folderPreviews)SettingsCheckbox(title: "Show toolbar above the page", isOn: $store.settings.showToolbar)SettingsCheckbox(title: "Pages fill the window edge to edge", isOn: $store.settings.edgeToEdgeContent)SettingsCheckbox(title: "Enable Picture in Picture when you leave a video tab", isOn: $store.settings.autoPictureInPicture)@@ -29,8 +30,9 @@ struct TabsPane: View {SettingsFormRow(label: "Links:") {SettingsCheckbox(title: "Links from other apps open in a Little Window", isOn: $store.settings.openExternalLinksInLittleWindow)SettingsCheckbox(title: "Open a Peek window when clicking on links to other sites", isOn: $store.settings.peekLinksToOtherSites)- Text("Only links in Favorites and Pinned tabs.")- .font(.system(size: 11)).foregroundStyle(.secondary)+ SettingsCheckbox(title: "In every tab, not only Favorites and Pinned tabs", isOn: $store.settings.peekInEveryTab)+ .disabled(!store.settings.peekLinksToOtherSites)+ .padding(.leading, 20)SettingsCheckbox(title: "Open a Peek window when clicking on links with Shift held", isOn: $store.settings.peekOnShiftClick)HStack(spacing: 8) {Button("Air Traffic Control…") { showsAirTrafficControl = true }diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swiftindex 423df6d..fdd89a7 100644--- a/Sources/Cra/UI/ShellView.swift+++ b/Sources/Cra/UI/ShellView.swift@@ -19,7 +19,9 @@ final class ShellView: NSView {private let liftLayer = CAGradientLayer()/// Set by the window controller: light theme that wants the blur path.var vibrantLight = false { didSet { refreshLift() } }- var usesBackdropLayer: Bool { vibrantLight && !vibrantDark && backdropLayer != nil }+ /// Arc's one-colour themes, light or dark: the blur under SpacePalette.solidAlpha's material.+ var solidBackdrop = false { didSet { refreshLift() } }+ var usesBackdropLayer: Bool { (solidBackdrop || vibrantLight && !vibrantDark) && backdropLayer != nil }/// Lifts the dark blur toward Arc's mid-grey base before the gradient goes on.let vibrancyLift = NSView()let backgroundHost: NSView@@ -124,9 +126,10 @@ final class ShellView: NSView {vibrancyLift.isHidden = truebackdropHost.isHidden = falseCATransaction.begin(); CATransaction.setDisableActions(true)- dimLayer.opacity = Float(windowActive ? t.blurDim : t.blurDimInactive)- let top = windowActive ? t.liftActive : t.liftInactive- let bottom = windowActive ? t.liftActiveBottom : t.liftInactive+ // Solid: Arc's material is grey 66 passing 52 % of the backdrop, flat 212 while inactive.+ dimLayer.opacity = Float(solidBackdrop ? (windowActive ? 0.30 : 1) : windowActive ? t.blurDim : t.blurDimInactive)+ let top = solidBackdrop ? (windowActive ? 0.26 : 0.83) : windowActive ? t.liftActive : t.liftInactive+ let bottom = solidBackdrop ? top : windowActive ? t.liftActiveBottom : t.liftInactiveliftLayer.colors = [NSColor(white: 1, alpha: top).cgColor, NSColor(white: 1, alpha: bottom).cgColor]CATransaction.commit()} else {@@ -662,18 +665,40 @@ final class ResizeHandleView: NSView {var onDrag: ((CGFloat) -> Void)?var onEnd: (() -> Void)?private var lastX: CGFloat = 0+ private var dragging = false+ private var tracking: NSTrackingArea?/// The window is movable by its background; this strip must own its drags.override var mouseDownCanMoveWindow: Bool { false }override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }override func resetCursorRects() { addCursorRect(bounds, cursor: .resizeLeftRight) }- override func mouseDown(with event: NSEvent) { lastX = event.locationInWindow.x }++ /// A page window or the floating sidebar's panel is usually not key, so track+ /// always and set the cursor ourselves.+ override func updateTrackingAreas() {+ super.updateTrackingAreas()+ if let tracking { removeTrackingArea(tracking) }+ let t = NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .cursorUpdate, .activeAlways], owner: self, userInfo: nil)+ addTrackingArea(t)+ tracking = t+ }++ override func cursorUpdate(with event: NSEvent) { NSCursor.resizeLeftRight.set() }+ override func mouseEntered(with event: NSEvent) { NSCursor.resizeLeftRight.set() }+ override func mouseExited(with event: NSEvent) { if !dragging { NSCursor.arrow.set() } }++ override func mouseDown(with event: NSEvent) { lastX = event.locationInWindow.x; dragging = true }override func mouseDragged(with event: NSEvent) {let x = event.locationInWindow.xonDrag?(x - lastX)lastX = x+ NSCursor.resizeLeftRight.set()+ }+ override func mouseUp(with event: NSEvent) {+ dragging = false+ onEnd?()+ if !bounds.contains(convert(event.locationInWindow, from: nil)) { NSCursor.arrow.set() }}- override func mouseUp(with event: NSEvent) { onEnd?() }}diff --git a/Sources/Cra/UI/Sidebar/FolderPreview.swift b/Sources/Cra/UI/Sidebar/FolderPreview.swiftnew file mode 100644index 0000000..175e6b1--- /dev/null+++ b/Sources/Cra/UI/Sidebar/FolderPreview.swift@@ -0,0 +1,640 @@+import AppKit++/// Arc's folder preview (Arc 1.171: Previews.FolderPreviewState / FolderPreviewItem /+/// FolderPreviewAction, Arc.FolderPreviewView, setting `folderPreviewEnabled`). Resting the+/// pointer on a closed folder lists every tab in it, nested folders included, most recently used+/// first, each with how long ago it was used, under a "Search <folder>…" field that already has+/// the keys. ↑↓ and ↩ pick a tab, Escape, leaving or a click elsewhere closes it; a row's menu has+/// Copy Link, Open in Split View, Duplicate and Archive (FolderPreviewAction.ContextMenuAction).+/// Timing and geometry: docs/arc-reverse-engineering.md, "Folder previews".+@MainActor+final class FolderPreviewController {+ static let shared = FolderPreviewController()++ private var panel: FolderPreviewPanel?+ private weak var list: SpaceListView?+ private weak var anchor: FolderRowView?+ private(set) var folderID: UUID?+ private var showWork: DispatchWorkItem?+ private var closeWork: DispatchWorkItem?+ private weak var returnKeyWindow: NSWindow?+ private var clickMonitor: Any?+ private var resignObserver: Any?+ /// Typing or arrowing keeps the preview open after the pointer leaves; then only Escape, a+ /// pick or a click elsewhere closes it.+ var extended = false++ var isOpen: Bool { panel?.isVisible == true && folderID != nil }++ /// The list's hovered row changed (nil: the pointer left the rows).+ func hover(_ row: SidebarRowView?, in list: SpaceListView) {+ let folder = (row as? FolderRowView).flatMap { r -> (FolderRowView, UUID)? in+ guard let m = r.model, !m.expanded, !m.editing, m.tabCount > 0 else { return nil }+ return (r, m.id)+ }+ showWork?.cancel()+ showWork = nil+ if let (row, id) = folder, id == folderID, isOpen {+ anchor = row+ closeWork?.cancel()+ return+ }+ if isOpen, !panelHovered { scheduleClose() }+ guard let (row, id) = folder, list.store.settings.folderPreviews, list.ui.draggingID == nil,+ NSEvent.pressedMouseButtons == 0 else { return }+ let work = DispatchWorkItem { [weak self, weak row, weak list] in+ MainActor.assumeIsolated {+ guard let self, let row, let list, row.isHovered, row.model?.id == id else { return }+ self.open(id, row: row, list: list)+ }+ }+ showWork = work+ DispatchQueue.main.asyncAfter(deadline: .now() + FolderPreviewMetrics.openDelay, execute: work)+ }++ private var panelHovered: Bool {+ guard let panel, panel.isVisible else { return false }+ return panel.frame.contains(NSEvent.mouseLocation)+ }++ func pointerEnteredPanel() { closeWork?.cancel() }++ func pointerLeftPanel() {+ if anchor?.isHovered == true { return }+ scheduleClose()+ }++ private func scheduleClose() {+ guard !extended else { return }+ closeWork?.cancel()+ let work = DispatchWorkItem { [weak self] in+ MainActor.assumeIsolated {+ guard let self, !self.panelHovered, self.anchor?.isHovered != true, !self.extended else { return }+ self.close()+ }+ }+ closeWork = work+ DispatchQueue.main.asyncAfter(deadline: .now() + FolderPreviewMetrics.closeGrace, execute: work)+ }++ private func open(_ id: UUID, row: FolderRowView, list: SpaceListView) {+ guard let host = row.window, let folder = list.store.item(id) else { return }+ let items = Self.items(in: id, store: list.store, favicons: list.favicons)+ guard !items.isEmpty else { return }+ let wasOpen = isOpen+ closeWork?.cancel()+ self.list = list+ anchor = row+ folderID = id+ extended = false+ let panel = self.panel ?? FolderPreviewPanel()+ self.panel = panel+ panel.preview.show(title: folder.title ?? "Folder", items: items)+ // Right of the sidebar, centred on the folder, kept 18 pt inside the window.+ let size = NSSize(width: FolderPreviewMetrics.width, height: FolderPreviewMetrics.height(rows: items.count))+ let rowRect = host.convertToScreen(row.convert(row.bounds, to: nil))+ let sidebarRect = host.convertToScreen(list.convert(list.bounds, to: nil))+ let inset = FolderPreviewMetrics.windowInset+ var origin = NSPoint(x: sidebarRect.maxX + FolderPreviewMetrics.gapFromSidebar, y: rowRect.midY - size.height / 2)+ let bounds = host.parent?.frame ?? host.frame+ origin.y = max(min(origin.y, bounds.maxY - inset - size.height), bounds.minY + inset)+ panel.setFrame(NSRect(origin: origin, size: size), display: true)+ if panel.parent !== host {+ panel.parent?.removeChildWindow(panel)+ host.addChildWindow(panel, ordered: .above)+ }+ if !wasOpen { returnKeyWindow = NSApp.keyWindow === panel ? returnKeyWindow : NSApp.keyWindow }+ panel.present()+ // The field takes the keys at once, as in Arc (its caret blinks as the preview opens).+ panel.makeKey()+ panel.preview.focusSearch()+ installMonitors()+ }++ func debugOpen(_ id: UUID, row: FolderRowView, list: SpaceListView) {+ open(id, row: row, list: list)+ extended = true+ }++ func close(restoreFocus: Bool = true) {+ showWork?.cancel()+ closeWork?.cancel()+ guard let panel, isOpen else { folderID = nil; return }+ let wasKey = panel.isKeyWindow+ folderID = nil+ extended = false+ removeMonitors()+ panel.dismiss()+ if restoreFocus, wasKey, let w = returnKeyWindow, w.isVisible { w.makeKey() }+ returnKeyWindow = nil+ }++ private func installMonitors() {+ if clickMonitor == nil {+ clickMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]) { [weak self] e in+ MainActor.assumeIsolated {+ guard let self, let panel = self.panel, e.window !== panel else { return }+ // A click on the folder itself opens it; the preview just goes.+ self.close(restoreFocus: false)+ }+ return e+ }+ }+ if resignObserver == nil {+ resignObserver = NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { [weak self] _ in+ MainActor.assumeIsolated { self?.close(restoreFocus: false) }+ }+ }+ }++ private func removeMonitors() {+ if let m = clickMonitor { NSEvent.removeMonitor(m) }+ clickMonitor = nil+ if let o = resignObserver { NotificationCenter.default.removeObserver(o) }+ resignObserver = nil+ }++ /// Every tab under the folder (nested folders and splits included), most recently used first+ /// (FolderPreviewState.allPossibleChildren, sorted by lastVisitDate).+ static func items(in folderID: UUID, store: SidebarStore, favicons: FaviconCache) -> [FolderPreviewItem] {+ store.tabs(under: folderID).map { t in+ let key = t.tab?.iconKey+ let icon = favicons.image(forKey: key)+ return FolderPreviewItem(id: t.id, title: t.displayTitle, url: t.tab?.url ?? "", icon: icon,+ glyphDark: icon == nil ? nil : favicons.glyphIsDark(forKey: key),+ lastVisit: t.tab?.timeLastActiveAt ?? t.createdAt, badged: t.isUnread)+ }+ .sorted { $0.lastVisit > $1.lastVisit }+ }++ // MARK: Actions++ func pick(_ id: UUID) {+ guard let list else { return }+ close()+ list.ui.keyboardFocusID = nil+ list.store.selectTab(id, window: list.ui.windowID)+ }++ func openInSplitView(_ id: UUID) {+ guard let list else { return }+ let store = list.store+ close()+ guard let current = store.selectedTabID(window: list.ui.windowID), current != id else {+ store.selectTab(id, window: list.ui.windowID)+ return+ }+ let split: SidebarItem?+ if let s = store.splitContaining(current) {+ store.addToSplit(s.id, tabID: id, at: nil)+ split = store.item(s.id)+ } else {+ split = store.createSplit(with: [current, id], at: current)+ }+ let pane = split.flatMap { store.paneID(for: id, in: $0) } ?? id+ store.selectTab(pane, window: list.ui.windowID)+ }++ func duplicate(_ id: UUID) {+ guard let list else { return }+ close()+ if let copy = list.store.duplicateTab(id) { list.store.selectTab(copy.id, window: list.ui.windowID) }+ }++ func archive(_ id: UUID) {+ guard let list else { return }+ list.store.archiveTab(id, reason: .manual)+ guard let folderID, list.store.item(folderID) != nil else { return close() }+ let items = Self.items(in: folderID, store: list.store, favicons: list.favicons)+ if items.isEmpty { close() } else { panel?.preview.replaceItems(items) }+ }+}++struct FolderPreviewItem: Equatable {+ var id: UUID+ var title: String+ var url: String+ var icon: NSImage?+ var glyphDark: Bool?+ var lastVisit: Date+ /// Unread (FolderPreviewItem.isBadged).+ var badged: Bool+}++/// Measured on Arc 1.171 (2x window captures and 120 fps recordings, 31 Oct 2026).+enum FolderPreviewMetrics {+ static let width: CGFloat = 240+ static let maxHeight: CGFloat = 320+ static let corner: CGFloat = 10+ static let searchHeight: CGFloat = 48+ /// From the hairline under the search field to the first row.+ static let listInset: CGFloat = 4+ static let rowPitch: CGFloat = 45+ static let rowFill: CGFloat = 44+ static let rowCorner: CGFloat = 4+ static let sideInset: CGFloat = 4+ /// Favicon and magnifier centre, and where the text starts, from the panel's left edge.+ static let iconCenter: CGFloat = 20+ static let textX: CGFloat = 36+ static let gapFromSidebar: CGFloat = 4+ static let windowInset: CGFloat = 18+ /// The row turns hovered, 0.45 s later the preview fades in (90 ms, scaling up from 0.85 at+ /// the middle of its left edge); it fades out over 80 ms as soon as the pointer is elsewhere.+ static let openDelay: TimeInterval = 0.45+ static let fadeIn: TimeInterval = 0.09+ static let fadeOut: TimeInterval = 0.08+ static let startScale: CGFloat = 0.85+ /// Crossing from the folder to the preview leaves both for a moment.+ static let closeGrace: TimeInterval = 0.06++ /// One row is 98 pt; six and more stop at 320 and scroll. Filtering keeps the size.+ static func height(rows n: Int) -> CGFloat {+ min(searchHeight + 1 + listInset + CGFloat(max(n, 1)) * rowPitch, maxHeight)+ }++ /// "15 hours ago", "1 week ago", as Arc words lastVisitDate.+ static func age(of date: Date, now: Date = Date()) -> String {+ if now.timeIntervalSince(date) < 60 { return "Just now" }+ let f = RelativeDateTimeFormatter()+ f.unitsStyle = .full+ f.dateTimeStyle = .numeric+ return f.localizedString(for: date, relativeTo: now)+ }++ // Arc draws it dark whatever the space's theme: a blur that lets ~12 % of the backdrop+ // through (23 over a dark page, 45/44/36 over a light yellow one), white text at 85 % / 58 %.+ static let title = NSColor(white: 1, alpha: 0.83)+ static let secondary = NSColor(white: 1, alpha: 0.55)+ static let rowFillColor = NSColor(white: 1, alpha: 0.078)+ static let hairline = NSColor(white: 1, alpha: 0.13)+}++/// A borderless panel that can take the search field's keys without activating anything else.+final class FolderPreviewPanel: NSPanel {+ let preview = FolderPreviewView()+ private let container = NSView()++ override var canBecomeKey: Bool { true }+ override var canBecomeMain: Bool { false }++ init() {+ super.init(contentRect: NSRect(x: 0, y: 0, width: FolderPreviewMetrics.width, height: 200),+ styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)+ isFloatingPanel = false+ backgroundColor = .clear+ isOpaque = false+ hasShadow = true+ hidesOnDeactivate = false+ isReleasedWhenClosed = false+ animationBehavior = .none+ collectionBehavior = [.fullScreenAuxiliary, .moveToActiveSpace]+ container.wantsLayer = true+ preview.autoresizingMask = [.width, .height]+ container.addSubview(preview)+ contentView = container+ }++ override func cancelOperation(_ sender: Any?) { FolderPreviewController.shared.close() }++ func present() {+ preview.frame = container.bounds+ let w = frame.width, s = FolderPreviewMetrics.startScale+ // Scale about the middle of the left edge (sublayerTransform works from the layer's centre).+ let start = CATransform3DConcat(CATransform3DMakeScale(s, s, 1), CATransform3DMakeTranslation(-w / 2 * (1 - s), 0, 0))+ alphaValue = 0+ orderFront(nil)+ invalidateShadow()+ if let layer = container.layer {+ let a = CABasicAnimation(keyPath: "sublayerTransform")+ a.fromValue = start+ a.toValue = CATransform3DIdentity+ a.duration = FolderPreviewMetrics.fadeIn+ a.timingFunction = CAMediaTimingFunction(name: .easeOut)+ layer.add(a, forKey: "present")+ }+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = FolderPreviewMetrics.fadeIn+ animator().alphaValue = 1+ }+ }++ func dismiss() {+ NSAnimationContext.runAnimationGroup({ ctx in+ ctx.duration = FolderPreviewMetrics.fadeOut+ animator().alphaValue = 0+ }, completionHandler: { [weak self] in+ MainActor.assumeIsolated {+ // Opened again while it faded: leave it up.+ guard let self, FolderPreviewController.shared.folderID == nil else { return }+ self.parent?.removeChildWindow(self)+ self.orderOut(nil)+ }+ })+ }+}++/// The preview's content: the search field, a hairline, then the rows (scrolling past six).+@MainActor+final class FolderPreviewView: NSView, NSTextFieldDelegate {+ private let blur = NSVisualEffectView()+ private let shade = NSView()+ private let outline = CAShapeLayer()+ private let highlight = CAShapeLayer()+ private let searchIcon = NSImageView()+ private let field = NSTextField()+ private let line = NSView()+ private let scroll = NSScrollView()+ private let rowsView = FlippedRowsView()+ private let empty = NSTextField(wrappingLabelWithString: "")+ private var rows: [FolderPreviewRowView] = []+ private var items: [FolderPreviewItem] = []+ private var shown: [FolderPreviewItem] = []+ private var selected = 0++ init() {+ super.init(frame: NSRect(x: 0, y: 0, width: FolderPreviewMetrics.width, height: 200))+ appearance = NSAppearance(named: .darkAqua)+ wantsLayer = true+ blur.material = .hudWindow+ blur.blendingMode = .behindWindow+ blur.state = .active+ blur.maskImage = Self.mask(radius: FolderPreviewMetrics.corner)+ addSubview(blur)+ // Over hudWindow (27 + 0.52 × backdrop) this leaves ≈ 19 + 0.12 × backdrop, as Arc.+ shade.wantsLayer = true+ shade.layer?.backgroundColor = NSColor(white: 17 / 255, alpha: 0.77).cgColor+ shade.layer?.cornerRadius = FolderPreviewMetrics.corner+ shade.layer?.cornerCurve = .circular+ addSubview(shade)+ searchIcon.image = SidebarSymbols.image("magnifyingglass", size: 12, weight: .semibold)+ searchIcon.contentTintColor = FolderPreviewMetrics.secondary+ addSubview(searchIcon)+ field.isBordered = false+ field.drawsBackground = false+ field.focusRingType = .none+ field.font = .systemFont(ofSize: 13)+ field.textColor = FolderPreviewMetrics.title+ field.delegate = self+ field.cell?.isScrollable = true+ field.cell?.usesSingleLineMode = true+ addSubview(field)+ line.wantsLayer = true+ line.layer?.backgroundColor = FolderPreviewMetrics.hairline.cgColor+ addSubview(line)+ scroll.drawsBackground = false+ scroll.hasVerticalScroller = true+ scroll.autohidesScrollers = true+ scroll.scrollerStyle = .overlay+ scroll.documentView = rowsView+ addSubview(scroll)+ // Arc: "No tabs matching that search 🤔", wrapping the emoji onto a second line.+ empty.stringValue = "No tabs matching that search 🤔"+ empty.font = .systemFont(ofSize: 13)+ empty.textColor = FolderPreviewMetrics.secondary+ empty.alignment = .center+ empty.isHidden = true+ addSubview(empty)+ // Two half-point rims: a grey outline, a faint light line inside it.+ for (l, c) in [(outline, NSColor(white: 0.23, alpha: 1)), (highlight, NSColor(white: 1, alpha: 0.2))] {+ l.fillColor = nil+ l.strokeColor = c.cgColor+ l.lineWidth = 0.5+ l.zPosition = 20+ layer?.addSublayer(l)+ }+ }++ required init?(coder: NSCoder) { fatalError() }++ override var isFlipped: Bool { true }++ private static func mask(radius r: CGFloat) -> NSImage {+ let size = NSSize(width: r * 2 + 1, height: r * 2 + 1)+ let image = NSImage(size: size, flipped: false) { rect in+ NSColor.black.setFill()+ NSBezierPath(roundedRect: rect, xRadius: r, yRadius: r).fill()+ return true+ }+ image.capInsets = NSEdgeInsets(top: r, left: r, bottom: r, right: r)+ image.resizingMode = .stretch+ return image+ }++ func show(title: String, items: [FolderPreviewItem]) {+ field.placeholderAttributedString = NSAttributedString(string: "Search \(title)…", attributes: [+ .foregroundColor: FolderPreviewMetrics.secondary, .font: NSFont.systemFont(ofSize: 13),+ ])+ field.stringValue = ""+ self.items = items+ filter()+ scroll.contentView.scroll(to: .zero)+ }++ func replaceItems(_ items: [FolderPreviewItem]) {+ self.items = items+ filter(keepSelection: true)+ }++ func focusSearch() { window?.makeFirstResponder(field) }++ // MARK: Filtering++ private func filter(keepSelection: Bool = false) {+ let words = field.stringValue.lowercased().split(separator: " ").map(String.init)+ let previous = shown.indices.contains(selected) ? shown[selected].id : nil+ shown = words.isEmpty ? items : items.filter { item in+ let hay = (item.title + " " + item.url).lowercased()+ return words.allSatisfy(hay.contains)+ }+ selected = keepSelection ? (shown.firstIndex { $0.id == previous } ?? min(selected, max(0, shown.count - 1))) : 0+ while rows.count < shown.count {+ let r = FolderPreviewRowView(preview: self)+ rows.append(r)+ rowsView.addSubview(r)+ }+ while rows.count > shown.count { rows.removeLast().removeFromSuperview() }+ let now = Date()+ for (i, (r, item)) in zip(rows, shown).enumerated() { r.show(item, now: now, selected: i == selected) }+ empty.isHidden = !shown.isEmpty+ needsLayout = true+ }++ func controlTextDidChange(_ obj: Notification) {+ FolderPreviewController.shared.extended = true+ filter()+ scroll.contentView.scroll(to: .zero)+ }++ func control(_ control: NSControl, textView: NSTextView, doCommandBy sel: Selector) -> Bool {+ switch sel {+ case #selector(NSResponder.moveDown(_:)): move(by: 1)+ case #selector(NSResponder.moveUp(_:)): move(by: -1)+ case #selector(NSResponder.insertNewline(_:)):+ if shown.indices.contains(selected) { FolderPreviewController.shared.pick(shown[selected].id) }+ case #selector(NSResponder.cancelOperation(_:)): FolderPreviewController.shared.close()+ default: return false+ }+ return true+ }++ private func move(by delta: Int) {+ guard !shown.isEmpty else { return }+ FolderPreviewController.shared.extended = true+ let i = min(max(0, selected + delta), shown.count - 1)+ selected = i+ for (j, r) in rows.enumerated() { r.isSelected = j == i }+ rowsView.scrollToVisible(rows[i].frame.insetBy(dx: 0, dy: -FolderPreviewMetrics.listInset))+ }++ // MARK: Layout++ override func layout() {+ super.layout()+ let w = bounds.width+ let m = FolderPreviewMetrics.self+ blur.frame = bounds+ shade.frame = bounds+ CATransaction.begin()+ CATransaction.setDisableActions(true)+ let r = m.corner+ outline.path = CGPath(roundedRect: bounds.insetBy(dx: 0.25, dy: 0.25), cornerWidth: r - 0.25, cornerHeight: r - 0.25, transform: nil)+ highlight.path = CGPath(roundedRect: bounds.insetBy(dx: 0.75, dy: 0.75), cornerWidth: r - 0.75, cornerHeight: r - 0.75, transform: nil)+ CATransaction.commit()+ let sh = m.searchHeight+ searchIcon.frame = NSRect(x: m.iconCenter - 8, y: (sh - 16) / 2, width: 16, height: 16)+ let fh = field.intrinsicContentSize.height+ // The caret sits at 36 pt; NSTextField draws its text 1 pt inside its frame.+ field.frame = NSRect(x: m.textX - 1, y: (sh - fh) / 2, width: w - m.textX - 12, height: fh)+ line.frame = NSRect(x: 0, y: sh, width: w, height: 1)+ let top = sh + 1+ scroll.frame = NSRect(x: 0, y: top, width: w, height: bounds.height - top)+ rowsView.frame = NSRect(x: 0, y: 0, width: w, height: m.listInset + CGFloat(rows.count) * m.rowPitch)+ for (i, row) in rows.enumerated() {+ row.frame = NSRect(x: 0, y: m.listInset + CGFloat(i) * m.rowPitch, width: w, height: m.rowPitch)+ }+ let ew: CGFloat = 192+ let eh = empty.sizeThatFits(NSSize(width: ew, height: 200)).height+ empty.frame = NSRect(x: (w - ew) / 2, y: top + (bounds.height - top - eh) / 2, width: ew, height: eh)+ }++ // MARK: Pointer++ override func updateTrackingAreas() {+ super.updateTrackingAreas()+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))+ }++ override func mouseEntered(with event: NSEvent) { FolderPreviewController.shared.pointerEnteredPanel() }+ override func mouseExited(with event: NSEvent) { FolderPreviewController.shared.pointerLeftPanel() }++ fileprivate func menu(for row: FolderPreviewRowView) -> NSMenu? {+ guard let i = rows.firstIndex(where: { $0 === row }), shown.indices.contains(i) else { return nil }+ let item = shown[i]+ let c = FolderPreviewController.shared+ let m = NSMenu()+ m.autoenablesItems = false+ c.extended = true+ MenuItems.add(m, "Copy Link") {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(item.url, forType: .string)+ }+ MenuItems.add(m, "Open in Split View") { c.openInSplitView(item.id) }+ MenuItems.add(m, "Duplicate") { c.duplicate(item.id) }+ m.addItem(.separator())+ MenuItems.add(m, "Archive") { c.archive(item.id) }+ return m+ }+}++private final class FlippedRowsView: NSView {+ override var isFlipped: Bool { true }+}++/// One tab in the preview: favicon, title and "15 hours ago". The pointer draws its own highlight+/// beside the keyboard's (Arc shows both at once, in the same fill).+final class FolderPreviewRowView: NSView {+ private weak var preview: FolderPreviewView?+ private let fill = CALayer()+ private let favicon = SidebarFaviconView(size: 16)+ private let title = NSTextField.sidebarLabel(size: 13)+ private let age = NSTextField.sidebarLabel(size: 11)+ private let badge = CALayer()+ private var itemID: UUID?+ var isSelected = false { didSet { if isSelected != oldValue { refresh() } } }+ private var isHovered = false { didSet { if isHovered != oldValue { refresh() } } }++ init(preview: FolderPreviewView) {+ self.preview = preview+ super.init(frame: .zero)+ wantsLayer = true+ fill.cornerRadius = FolderPreviewMetrics.rowCorner+ fill.actions = ["backgroundColor": NSNull()]+ layer?.addSublayer(fill)+ addSubview(favicon)+ title.lineBreakMode = .byTruncatingTail+ title.textColor = FolderPreviewMetrics.title+ addSubview(title)+ age.textColor = FolderPreviewMetrics.secondary+ addSubview(age)+ badge.cornerRadius = 3+ badge.backgroundColor = FolderPreviewMetrics.title.cgColor+ layer?.addSublayer(badge)+ }++ required init?(coder: NSCoder) { fatalError() }++ override var isFlipped: Bool { true }++ func show(_ item: FolderPreviewItem, now: Date, selected: Bool) {+ itemID = item.id+ var colors = SidebarColors()+ colors.isDark = true+ favicon.show(item.icon, flip: item.icon != nil && item.glyphDark == true, colors: colors)+ title.stringValue = item.title+ age.stringValue = FolderPreviewMetrics.age(of: item.lastVisit, now: now)+ badge.isHidden = !item.badged+ isSelected = selected+ refresh()+ needsLayout = true+ }++ private func refresh() {+ fill.backgroundColor = (isSelected || isHovered ? FolderPreviewMetrics.rowFillColor : .clear).cgColor+ }++ override func layout() {+ super.layout()+ let m = FolderPreviewMetrics.self+ CATransaction.begin()+ CATransaction.setDisableActions(true)+ fill.frame = CGRect(x: m.sideInset, y: 0, width: bounds.width - 2 * m.sideInset, height: m.rowFill)+ badge.frame = CGRect(x: bounds.width - m.sideInset - 12 - 6, y: (m.rowFill - 6) / 2, width: 6, height: 6)+ CATransaction.commit()+ favicon.frame = NSRect(x: m.iconCenter - 8, y: (m.rowFill - 16) / 2, width: 16, height: 16)+ let right = bounds.width - m.sideInset - (badge.isHidden ? 10 : 24)+ let th = title.intrinsicContentSize.height, ah = age.intrinsicContentSize.height+ // Arc: the title's caps start 8 pt into the row, the age line ends 35.5 pt in.+ let top = (m.rowFill - th - ah) / 2+ title.frame = NSRect(x: m.textX - SidebarText.inset, y: top, width: right - m.textX + 2 * SidebarText.inset, height: th)+ age.frame = NSRect(x: m.textX - SidebarText.inset, y: top + th, width: right - m.textX + 2 * SidebarText.inset, height: ah)+ }++ override func updateTrackingAreas() {+ super.updateTrackingAreas()+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))+ }++ override func mouseEntered(with event: NSEvent) { isHovered = true }+ override func mouseExited(with event: NSEvent) { isHovered = false }++ override func mouseUp(with event: NSEvent) {+ guard let id = itemID, bounds.contains(convert(event.locationInWindow, from: nil)) else { return }+ FolderPreviewController.shared.pick(id)+ }++ override func mouseDown(with event: NSEvent) {}++ override func menu(for event: NSEvent) -> NSMenu? { preview?.menu(for: self) }+}diff --git a/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift b/Sources/Cra/UI/Sidebar/List/SidebarMenus.swiftindex 45ba27e..7121f80 100644--- a/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift+++ b/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift@@ -227,13 +227,18 @@ enum SidebarMenus {/// Arc 1.171's split menu, item for item where Cra has the feature (no Share or Change Icon)./// It is pinned by dragging it into Pinned or with Pin Tab (⌘D), not from here.static func split(_ m: SplitRowModel, list: SpaceListView) -> NSMenu {- let store = list.store, ui = list.ui, actions = list.actions- let id = m.id+ split(m.id, panes: m.cells.map { ($0.id, $0.title) }, open: m.selected, store: list.store, ui: list.ui, actions: list.actions)+ }++ /// A split's menu, from its sidebar row or its favorite tile.+ static func split(_ id: UUID, panes: [(id: UUID, title: String)], open: Bool, store: SidebarStore, ui: SidebarUIState,+ actions: SidebarActions, leading: (NSMenu) -> Void = { _ in }) -> NSMenu {let menu = menu()- let children = m.cells.map(\.id)+ leading(menu)+ let children = panes.map(\.id)add(menu, "Separate All Tabs") { store.separateAll(id) }// Arc greys it out while the split is closed (no pane to add next to).- add(menu, "Add Tab…", enabled: m.selected && children.count < 4) {+ add(menu, "Add Tab…", enabled: open && children.count < 4) {if let first = children.first {actions.focusPane(first)actions.performAction("addSplitView")@@ -244,8 +249,8 @@ enum SidebarMenus {}menu.addItem(.separator())note(menu, "Tab Options")- for c in m.cells {- paneItems(submenu(menu, c.title), c.id, list: list)+ for c in panes {+ paneItems(submenu(menu, c.title), c.id, store: store, actions: actions)}menu.addItem(.separator())add(menu, "Rename…") { ui.renamingID = id }@@ -261,8 +266,7 @@ enum SidebarMenus {}/// One pane's submenu under "Tab Options" (Arc: childItem(id, …)).- private static func paneItems(_ menu: NSMenu, _ id: UUID, list: SpaceListView) {- let store = list.store, actions = list.actions+ private static func paneItems(_ menu: NSMenu, _ id: UUID, store: SidebarStore, actions: SidebarActions) {guard let tab = store.item(id)?.tab else { return }add(menu, "Separate from Split View") { store.separateFromSplit(id) }menu.addItem(.separator())diff --git a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swiftindex bba122c..d9d7e0d 100644--- a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift+++ b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift@@ -186,6 +186,10 @@ final class SidebarGlyphButton: NSView {/// Header buttons follow the app's active state (nil: the plain sidebar tone).var active: Bool? { didSet { if active != oldValue { refresh() } } }var enabled = true { didSet { if enabled != oldValue { refresh() } } }+ /// Drawn in this colour instead of the sidebar's glyph tone.+ var tint: NSColor? { didSet { if tint != oldValue { refresh() } } }+ /// Keeps the hover fill while what it opened is open (the player's volume drawer).+ var highlighted = false { didSet { if highlighted != oldValue { refresh() } } }init(symbol: String, size: CGFloat, height: CGFloat? = nil, iconSize: CGFloat, weight: NSFont.Weight = .medium, help: String,optionHelp: String? = nil, colors: SidebarColors, action: @escaping () -> Void) {@@ -252,7 +256,7 @@ final class SidebarGlyphButton: NSView {setHelp(help)}- private func setHelp(_ help: String) {+ func setHelp(_ help: String) {if let tip { (tip.text, tip.keys) = ArcTooltipLabel.split(help) } else if !help.isEmpty { tip = ArcTooltipAnchorView.attach(to: self, help: help) }}@@ -268,9 +272,9 @@ final class SidebarGlyphButton: NSView {} else {tint = enabled ? colors.glyph : colors.textTertiary.withAlphaComponent(colors.textTertiary.alphaComponent * 0.55)}- glyph.contentTintColor = tint- mark?.strokeColor = tint.cgColor- layer?.backgroundColor = (hovering && enabled ? colors.hoverFill : .clear).cgColor+ glyph.contentTintColor = self.tint ?? tint+ mark?.strokeColor = (self.tint ?? tint).cgColor+ layer?.backgroundColor = ((hovering || highlighted) && enabled ? colors.hoverFill : .clear).cgColor}override func layout() {@@ -294,7 +298,13 @@ final class SidebarGlyphButton: NSView {override func updateTrackingAreas() {super.updateTrackingAreas()for t in trackingAreas where t.owner === self { removeTrackingArea(t) }- addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))+ // A new area under the pointer gets no mouseEntered, so without assumeInside it never sends+ // the mouseExited either and the hover fill sticks (buttons moved under a resting pointer).+ let inside = window.map { visibleRect.contains(convert($0.mouseLocationOutsideOfEventStream, from: nil)) } ?? false+ var options: NSTrackingArea.Options = [.mouseEnteredAndExited, .activeAlways, .inVisibleRect]+ if inside { options.insert(.assumeInside) }+ addTrackingArea(NSTrackingArea(rect: .zero, options: options, owner: self, userInfo: nil))+ if hovering != inside { hovering = inside }}override func viewDidMoveToWindow() {@@ -667,6 +677,7 @@ struct TabRowModel: Equatable {var selected: Boolvar highlighted: Boolvar capturing: Bool+ var audible: Boolvar muted: Boolvar unread: Boolvar navigatedAway: Bool@@ -749,7 +760,7 @@ final class TabRowView: SidebarRowView, ArcTooltipTarget, NSTextFieldDelegate {rebuildAccessories()}- /// Recording dot, mute, unread dot, and on hover "back to pinned page" and close. Made once+ /// Recording dot, mute or playing sound, unread dot, and on hover "back to pinned page" and close. Made once/// per row and shown or hidden: hover moves from row to row on every frame of a scroll.private lazy var captureDot: NSView = {let dot = NSView(frame: NSRect(x: 0, y: 0, width: 16, height: 16))@@ -762,11 +773,18 @@ final class TabRowView: SidebarRowView, ArcTooltipTarget, NSTextFieldDelegate {_ = ArcTooltipAnchorView.attach(to: dot, help: "This tab is using your camera or microphone")return dot}()- private lazy var muteButton = SidebarGlyphButton(symbol: "speaker.slash.fill", size: 20, iconSize: 10, help: "Unmute Tab", colors: colors) { [weak self] in- guard let self, let id = self.model?.id, let list = self.list else { return }- list.store.setMuted(id, false)- list.actions.performAction("muteTab:\(id)")- }+ /// Arc 1.171: a playing or muted tab shows a speaker between the favicon and the title (17.5 pt+ /// wide, 8 pt before the title, in the glyph tone); clicking it mutes or unmutes the tab+ /// (31 Oct 2026, issue #28).+ private lazy var soundButton = SidebarGlyphButton(symbol: Self.soundSymbol, size: 20, iconSize: 13, weight: .regular,+ help: "Mute Tab", colors: colors) { [weak self] in+ guard let self, let m = self.model, let list = self.list else { return }+ list.store.setMuted(m.id, !m.muted)+ list.actions.performAction("muteTab:\(m.id)")+ }+ private static let soundSymbol = "speaker.wave.3"+ private static let soundGlyphWidth: CGFloat = 17.5+ private var showsSound = falseprivate lazy var unreadDot: NSView = {let dot = NSView(frame: NSRect(x: 0, y: 0, width: 6, height: 6))dot.wantsLayer = true@@ -790,7 +808,15 @@ final class TabRowView: SidebarRowView, ArcTooltipTarget, NSTextFieldDelegate {let id = m.idvar shown: [NSView] = []if m.capturing { shown.append(captureDot) }- if m.muted { muteButton.colors = colors; shown.append(muteButton) }+ let sound = (m.muted || m.audible) && !m.editing+ if sound {+ if soundButton.superview == nil { addSubview(soundButton) }+ soundButton.colors = colors+ soundButton.setSymbol(m.muted ? "speaker.slash" : Self.soundSymbol, iconSize: 13, weight: .regular,+ help: m.muted ? "Unmute Tab" : "Mute Tab")+ }+ soundButton.isHidden = !sound+ if sound != showsSound { showsSound = sound; needsLayout = true }if m.unread && !m.selected && !isHovered {unreadDot.layer?.backgroundColor = colors.textPrimary.withAlphaComponent(0.55).cgColorshown.append(unreadDot)@@ -837,6 +863,11 @@ final class TabRowView: SidebarRowView, ArcTooltipTarget, NSTextFieldDelegate {var x = 8 + CGFloat(m.depth) * CraMetrics.indentfavicon.frame = NSRect(x: x, y: (h - CraMetrics.favicon) / 2, width: CraMetrics.favicon, height: CraMetrics.favicon)x += CraMetrics.favicon + 11+ if showsSound {+ let s = soundButton.size+ soundButton.frame = NSRect(x: x - (s.width - Self.soundGlyphWidth) / 2, y: (h - s.height) / 2, width: s.width, height: s.height)+ x += Self.soundGlyphWidth + 8+ }// HStack(spacing: 11) with a Spacer(minLength: 4) between the text and the trailing items.var right = bounds.width - 6for v in accessories.reversed() {diff --git a/Sources/Cra/UI/Sidebar/List/SidebarView.swift b/Sources/Cra/UI/Sidebar/List/SidebarView.swiftindex 990d1f7..e9fdf83 100644--- a/Sources/Cra/UI/Sidebar/List/SidebarView.swift+++ b/Sources/Cra/UI/Sidebar/List/SidebarView.swift@@ -13,6 +13,7 @@ final class SidebarView: NSView {private let topBar: SidebarTopBarViewprivate let pager: SpacePagerViewprivate let trayHost: DownloadsTrayView+ private let player: NowPlayingTrayViewprivate let trayMask = CAGradientLayer()private let bannerHost = UpdateBannerView()private let dock: SpaceDockView@@ -30,14 +31,16 @@ final class SidebarView: NSView {topBar = SidebarTopBarView(store: store, ui: ui, actions: actions)pager = SpacePagerView(store: store, ui: ui, actions: actions, favicons: favicons)trayHost = DownloadsTrayView(ui: ui)+ player = NowPlayingTrayView(store: store, ui: ui, favicons: favicons)dock = SpaceDockView(store: store, ui: ui, actions: actions)super.init(frame: .zero)wantsLayer = truepager.wantsLayer = truetrayMask.startPoint = CGPoint(x: 0.5, y: 0)trayMask.endPoint = CGPoint(x: 0.5, y: 1)- for v in [topBar, pager, trayHost, bannerHost, dock] as [NSView] { tabs.addSubview(v) }+ for v in [topBar, pager, player, trayHost, bannerHost, dock] as [NSView] { tabs.addSubview(v) }addSubview(tabs)+ player.onCountChange = { [weak self] in self?.needsLayout = true }observe()}@@ -64,6 +67,7 @@ final class SidebarView: NSView {let colors = SidebarColors(palette)trayHost.colors = colorsbannerHost.colors = colors+ player.setTheme(space.theme.accent ?? space.theme.colors.first, dark: palette.isDark)libraryHost?.palette = palette}self.bannerHeight = bannerHeight@@ -153,7 +157,10 @@ final class SidebarView: NSView {dock.frame = NSRect(x: 10, y: b.height - 6 - dockH, width: b.width - 20, height: dockH)let bannerTop = b.height - 6 - dockH - 8 - bannerHeightbannerHost.frame = NSRect(x: 0, y: bannerTop, width: b.width, height: bannerHeight)- pager.frame = NSRect(x: 0, y: th, width: b.width, height: max(0, bannerTop - th))+ // The player rests where the list ends and takes that room from it; opened, it grows over the list.+ player.frame = NSRect(x: 0, y: th, width: b.width, height: max(0, bannerTop - th))+ let listBottom = bannerTop - NowPlayingMetrics.restHeight(cards: player.shownCount)+ pager.frame = NSRect(x: 0, y: th, width: b.width, height: max(0, listBottom - th))let rows = DownloadHistory.shared.recent.countlet trayH = DownloadsTrayMetrics.listHeight(rows: rows) + 4trayHost.frame = NSRect(x: 0, y: pager.frame.maxY - trayH, width: b.width, height: trayH)@@ -580,7 +587,29 @@ final class SpaceDockView: NSView {}}- private var stripX: CGFloat { (bounds.width - CGFloat(order.count) * Self.cell.width) / 2 }+ /// Arc 1.171 with 5 to 22 spaces (31 Oct 2026): every space gets an equal share of the 217 pt+ /// between the Library and + buttons (300 pt sidebar), in half points and at most 34 pt. Below+ /// 22 pt the open space keeps 22 and the others split the rest: 17.5 pt each with 12 spaces, 13+ /// with 16, 9 with 22. The strip stays centred, so it never runs past the buttons.+ private var cellWidths: [CGFloat] {+ let n = order.count+ guard n > 0 else { return [] }+ let room = max(0, bounds.width - 63)+ let even = min(Self.cell.width, floor(room / CGFloat(n) * 2) / 2)+ guard even < 22, n > 1 else { return Array(repeating: even, count: n) }+ let rest = max(4, floor((room - 22) / CGFloat(n - 1) * 2) / 2)+ return order.map { $0 == focused ? 22 : rest }+ }++ /// Left edges of the cells, in order.+ private var cellXs: [CGFloat] {+ let ws = cellWidths+ var x = (bounds.width - ws.reduce(0, +)) / 2+ return ws.map { w in defer { x += w }; return x }+ }++ /// The width a dragged space moves by per cell (the cells other than the open one).+ private var pitch: CGFloat { cellWidths.min() ?? Self.cell.width }override func layout() {super.layout()@@ -593,24 +622,24 @@ final class SpaceDockView: NSView {/// The dragged space follows the pointer; the ones it passes slide a cell the other way, like/// the gap Arc's collection view opens at the proposed drop index.private func placeCells(animated: Bool, dragX: CGFloat = 0) {- let w = Self.cell.width+ let ws = cellWidths, xs = cellXs, step = pitchlet y = (bounds.height - Self.cell.height) / 2for (i, id) in order.enumerated() {guard let c = cells[id] else { continue }- var x = stripX + CGFloat(i) * w+ var x = xs[i]if let r = reorder {- if r.id == id { x += dragX } else if r.from < i && i <= r.to { x -= w } else if r.to <= i && i < r.from { x += w }+ if r.id == id { x += dragX } else if r.from < i && i <= r.to { x -= step } else if r.to <= i && i < r.from { x += step }}- let f = NSRect(x: x, y: y, width: w, height: Self.cell.height)+ let f = NSRect(x: x, y: y, width: ws[i], height: Self.cell.height)if animated && reorder?.id != id { c.animator().frame = f } else { c.frame = f }}if let r = reorder, let c = cells[r.id] { c.removeFromSuperview(); addSubview(c) }}private func index(at p: NSPoint) -> Int? {- let i = Int(floor((p.x - stripX) / Self.cell.width))- guard p.y >= 0, p.y <= bounds.height, i >= 0, i < order.count, p.x >= stripX else { return nil }- return i+ guard p.y >= 0, p.y <= bounds.height else { return nil }+ let ws = cellWidths+ return cellXs.indices.first { p.x >= cellXs[$0] && p.x < cellXs[$0] + ws[$0] }}// Arc's dock items take the mouse themselves (SidebarDockItemView overrides mouseDown:/mouseUp:):@@ -657,7 +686,7 @@ final class SpaceDockView: NSView {let dx = p.x - r.start.xif !r.moved && abs(dx) < 3 && abs(p.y - r.start.y) < 3 { return }r.moved = true- let w = Self.cell.width+ let w = pitchlet clamped = min(max(dx, -CGFloat(r.from) * w), CGFloat(order.count - 1 - r.from) * w)let to = min(max(r.from + Int((clamped / w).rounded()), 0), order.count - 1)let changed = to != r.to@@ -695,8 +724,8 @@ final class SpaceDockView: NSView {NSAnimationContext.runAnimationGroup { ctx inctx.duration = 0.15ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)- placeCells(animated: true, dragX: CGFloat(r.to - r.from) * Self.cell.width)- cells[r.id]?.animator().frame.origin.x = stripX + CGFloat(r.to) * Self.cell.width+ placeCells(animated: true, dragX: CGFloat(r.to - r.from) * pitch)+ cells[r.id]?.animator().frame.origin.x = (cellXs.first ?? 0) + CGFloat(r.to) * pitch} completionHandler: { [weak self] inMainActor.assumeIsolated {guard let self else { return }@@ -788,6 +817,9 @@ final class SpaceCellView: NSView, ArcTooltipTarget {override func layout() {super.layout()emojiHolder.frame = bounds+ // Squeezed cells (many spaces) shrink the emoji with them, like Arc's dots.+ let size = min(13, max(5, (bounds.width * 0.62).rounded()))+ if emoji.font?.pointSize != size { emoji.font = .systemFont(ofSize: size) }let h = emoji.intrinsicContentSize.heightemoji.frame = NSRect(x: 0, y: (bounds.height - h) / 2, width: bounds.width, height: h)}diff --git a/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swift b/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swiftindex 79bb4a7..9789b34 100644--- a/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swift+++ b/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swift@@ -51,14 +51,20 @@ final class SpaceColumnView: NSView {place(animated: false)}+ /// Arc 1.171 (one space, live, 31 Oct) places everything under the favorites from the tiles'+ /// bottom, or with no favorites from the URL field's (the column starts 8 pt under it, where+ /// the first tile's top goes): the header 10 pt below, the divider line 54.5 pt below. With+ /// the header hidden the line is 18.5 pt under the tiles, 15.5 pt under the URL field.private func place(animated: Bool) {let w = bounds.widthlet fh = favorites.height(forWidth: w - 16)let set = { (v: NSView, f: NSRect) in if v.frame != f { animated ? (v.animator().frame = f) : (v.frame = f) } }set(favorites, NSRect(x: 8, y: 0, width: w - 16, height: fh))- let hh: CGFloat = header.isHidden ? 0 : 31- set(header, NSRect(x: 10, y: fh, width: w - 20, height: hh))- let top = fh + hh + 3+ let tiles = favorites.tilesBottom(forWidth: w - 16)+ let base = tiles ?? -8+ set(header, NSRect(x: 10, y: base + 10, width: w - 20, height: header.isHidden ? 0 : 31))+ // The list's line sits 11.5 pt into it (3 pt inset, then halfway down the 18 pt divider).+ let top = base + (!header.isHidden ? 43 : tiles == nil ? 4 : 7)set(list, NSRect(x: 0, y: top, width: w, height: max(0, bounds.height - top)))}}@@ -257,30 +263,28 @@ final class FavoritesGridView: NSView {override var isFlipped: Bool { true }- private struct TileModel: Equatable {- var title: String- var icon: NSImage?- var glyphDark: Bool?- var tileColor: String?- var selected: Bool- var unread: Bool- var focus: Bool- }-private func sync() {syncQueued = false- var models: [(UUID, TileModel)] = []+ var models: [(UUID, FavoriteTileModel)] = []var palette: SpacePalette?withObservationTracking {guard let space = store.space(spaceID) else { return }palette = space.theme.palette- for item in store.tabs(under: space.favoritesContainerID) {- let key = item.tab?.iconKey- let icon = favicons.image(forKey: key)- models.append((item.id, TileModel(title: item.displayTitle, icon: icon, glyphDark: icon == nil ? nil : favicons.glyphIsDark(forKey: key),- tileColor: item.tab?.tileColor,- selected: store.isSelected(item.id, inSpace: spaceID, window: ui.windowID),- unread: item.isUnread, focus: ui.keyboardFocusID == item.id)))+ // A favorite split is one tile with a cell per pane (Arc: AppItem.childItems).+ for item in store.children(of: space.favoritesContainerID) where item.isTab || item.isSplit {+ let panes = item.isSplit ? store.children(of: item.id).filter(\.isTab) : [item]+ guard !panes.isEmpty else { continue }+ let cells = panes.map { p in+ let key = p.tab?.iconKey+ let icon = favicons.image(forKey: key)+ return FavoriteTileModel.Cell(id: p.id, title: p.displayTitle, icon: icon,+ glyphDark: icon == nil ? nil : favicons.glyphIsDark(forKey: key))+ }+ let open = panes.first { store.isSelected($0.id, inSpace: spaceID, window: ui.windowID) }?.id+ let title = item.isSplit && item.title == nil ? panes.map(\.displayTitle).joined(separator: " | ") : item.displayTitle+ models.append((item.id, FavoriteTileModel(title: title, cells: cells, vertical: item.split?.orientation == .vertical,+ tileColor: item.tab?.tileColor, selected: open != nil, openCell: open,+ unread: panes.contains(where: \.isUnread), focus: ui.keyboardFocusID == item.id)))}} onChange: { [weak self] inTask { @MainActor in@@ -303,10 +307,7 @@ final class FavoritesGridView: NSView {addSubview(t)return t}()- if let palette {- t.show(title: m.title, icon: m.icon, glyphDark: m.glyphDark, tileColor: m.tileColor, selected: m.selected,- unread: m.unread, focus: m.focus, palette: palette)- }+ if let palette { t.show(m, palette: palette) }}order = idsif let palette { strip.palette = palette }@@ -315,14 +316,19 @@ final class FavoritesGridView: NSView {if countChanged { onHeightChange(false) }}- /// Arc 1.170 (AX frames at sidebar widths 100–347, 29 Oct): four columns while a tile is at- /// least as wide as it is tall (47 pt), else two, else one; never three.- private static func columns(forWidth w: CGFloat) -> Int {- [4, 2].first { (w - CGFloat($0 - 1) * 8) / CGFloat($0) >= 47 } ?? 1+ /// Arc 1.171 (AX frames, 1–9 favorites at sidebar widths 100–347, 31 Oct): at most as many+ /// columns (up to four) as keep a tile at least as wide as it is tall (47 pt), then the fewest+ /// that need no more rows: one favorite fills the row, five go 3 + 2, nine 3 × 3, four at+ /// 200 pt 2 × 2 (#29). A short last row keeps the tile width, from the left.+ private func columns(forWidth w: CGFloat) -> Int {+ let widest = (1...4).last { (w - CGFloat($0 - 1) * 8) / CGFloat($0) >= 47 } ?? 1+ guard !order.isEmpty else { return widest }+ let rows = (order.count + widest - 1) / widest+ return (order.count + rows - 1) / rows}private func rows(forWidth w: CGFloat) -> Int {- let c = Self.columns(forWidth: w)+ let c = columns(forWidth: w)return (order.count + c - 1) / c}@@ -332,14 +338,31 @@ final class FavoritesGridView: NSView {return grid + (order.isEmpty ? 0 : 4) + strip.height}+ /// Where the header and list are placed from: the tiles' bottom, the open "Add to Favorites"+ /// strip's while a tab is dragged over it, nil with no favorites.+ func tilesBottom(forWidth w: CGFloat) -> CGFloat? {+ if strip.targeted { return height(forWidth: w) }+ let rows = rows(forWidth: w)+ return rows == 0 ? nil : CGFloat(rows) * 47 + CGFloat(rows - 1) * 8+ }++ /// The resting strip only takes drops (AppKit finds drop targets apart from hitTest). With+ /// the header hidden and no favorites the divider sits under it, and its Clear gets the click.+ override func hitTest(_ point: NSPoint) -> NSView? {+ let v = super.hitTest(point)+ return v === self || v === strip ? nil : v+ }+override func layout() {super.layout()let w = bounds.width- let n = Self.columns(forWidth: w)+ let n = columns(forWidth: w)let cw = (w - CGFloat(n - 1) * 8) / CGFloat(n)for (i, id) in order.enumerated() {let r = i / n, c = i % n- tiles[id]?.frame = NSRect(x: CGFloat(c) * (cw + 8), y: CGFloat(r) * (47 + 8), width: cw, height: 47)+ // Arc puts each tile on a half point (84.75 → 85 at 347 pt).+ let x = (CGFloat(c) * (cw + 8) * 2).rounded() / 2+ tiles[id]?.frame = NSRect(x: x, y: CGFloat(r) * (47 + 8), width: cw, height: 47)}let rows = rows(forWidth: w)let grid = rows == 0 ? 0 : CGFloat(rows) * 47 + CGFloat(rows - 1) * 8@@ -347,14 +370,14 @@ final class FavoritesGridView: NSView {}func moveFavorite(_ dragged: UUID, before target: UUID, after: Bool) {- guard dragged != target, store.item(dragged)?.isSplit != true, let space = store.space(spaceID),+ guard dragged != target, let space = store.space(spaceID),let idx = store.item(space.favoritesContainerID)?.children.firstIndex(of: target) else { return }store.moveItem(dragged, to: space.favoritesContainerID, index: idx + (after ? 1 : 0))}func spaceFavoriteIDs() -> [UUID] {guard let space = store.space(spaceID) else { return [] }- return store.tabs(under: space.favoritesContainerID).map(\.id)+ return store.favoriteTabs(in: space).map(\.id)}}@@ -427,6 +450,47 @@ final class FavoritesDropStrip: NSView {}}+/// What a favorite tile shows: one page, or a split's panes. Arc keeps a split in its top apps as+/// one tile cut into a cell per pane (AppItem.childItems, AppTrayItemMaskShape), side by side or,+/// for a vertical split, stacked.+struct FavoriteTileModel: Equatable {+ struct Cell: Equatable {+ var id: UUID+ var title: String+ var icon: NSImage?+ var glyphDark: Bool?+ }+ var title: String+ var cells: [Cell]+ var vertical: Bool+ var tileColor: String?+ var selected: Bool+ /// The pane open in the window while this favorite is the open one.+ var openCell: UUID?+ var unread: Bool+ var focus: Bool+}++enum FavoriteTileMetrics {+ static let corner: CGFloat = 13+ /// The cut between a split's cells (AppTrayItemMaskShape.lineWidth).+ static let cut: CGFloat = 2++ /// Cell frames along the tile, whole points, the last cell taking what rounding leaves.+ static func cellFrames(in bounds: CGRect, count n: Int, vertical: Bool) -> [CGRect] {+ guard n > 1 else { return [bounds] }+ let length = vertical ? bounds.height : bounds.width+ let each = (length - CGFloat(n - 1) * cut) / CGFloat(n)+ var start: CGFloat = 0+ return (0..<n).map { i in+ let end = i == n - 1 ? length : (start + each).rounded()+ defer { start = end + cut }+ return vertical ? CGRect(x: 0, y: start, width: bounds.width, height: end - start)+ : CGRect(x: start, y: 0, width: end - start, height: bounds.height)+ }+ }+}+/// A favorite tile. Arc 1.170: 13 pt circular corners; the active tile is the hover fill with a/// 2 pt darker rim; inactive tiles sit ~4.5% darker than the sidebar. A picked tile colour keeps/// its hue in every state; hover and selection shade it.@@ -437,10 +501,14 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {private let shade = CALayer()/// The selected tile's 2 pt rim, under the focus ring (a layer border would draw over it).private let rim = CALayer()- private let favicon = SidebarFaviconView(size: 20)+ private var favicons: [SidebarFaviconView] = []+ /// Cuts a split's tile into its cells.+ private let cutMask = CAShapeLayer()private let unreadDot = CALayer()private var focusRing: FocusRingLayer?- private var model: (title: String, icon: NSImage?, glyphDark: Bool?, tileColor: String?, selected: Bool, unread: Bool, focus: Bool, palette: SpacePalette)?+ private var model: FavoriteTileModel?+ private var palette: SpacePalette?+ private var hoveredCell: Int? { didSet { if hoveredCell != oldValue { ArcTooltipController.shared.mouseExited(self) } } }private var hovering = false { didSet { if hovering != oldValue { refresh() } } }private var targeted = false { didSet { if targeted != oldValue { refresh() } } }private var press: NSEvent?@@ -451,13 +519,13 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {self.grid = gridsuper.init(frame: .zero)wantsLayer = true- layer?.cornerRadius = 13- shade.cornerRadius = 13+ layer?.cornerRadius = FavoriteTileMetrics.corner+ shade.cornerRadius = FavoriteTileMetrics.cornerlayer?.addSublayer(shade)- rim.cornerRadius = 13+ rim.cornerRadius = FavoriteTileMetrics.cornerrim.zPosition = 5layer?.addSublayer(rim)- addSubview(favicon)+ cutMask.fillRule = .evenOddunreadDot.cornerRadius = 3layer?.addSublayer(unreadDot)registerForDraggedTypes([.craSidebarItem])@@ -470,29 +538,38 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {override var isFlipped: Bool { true }override var mouseDownCanMoveWindow: Bool { false }- func show(title: String, icon: NSImage?, glyphDark: Bool?, tileColor: String?, selected: Bool, unread: Bool, focus: Bool, palette: SpacePalette) {- model = (title, icon, glyphDark, tileColor, selected, unread, focus, palette)- setAccessibilityLabel(title)+ func show(_ m: FavoriteTileModel, palette: SpacePalette) {+ model = m+ self.palette = palette+ setAccessibilityLabel(m.title)+ while favicons.count < m.cells.count {+ let f = SidebarFaviconView(size: 20)+ favicons.append(f)+ addSubview(f)+ }+ while favicons.count > m.cells.count { favicons.removeLast().removeFromSuperview() }+ // Arc 1.171: the open split's tile is one selected tile; the cut shows while it is closed.+ layer?.mask = m.cells.count > 1 && !m.selected ? cutMask : nilrefresh()}private var tileIsDark: Bool {- guard let m = model else { return false }- return m.tileColor.flatMap(HexColor.luminance).map { $0 < 0.5 } ?? m.palette.isDark+ guard let m = model, let palette else { return false }+ return m.tileColor.flatMap(HexColor.luminance).map { $0 < 0.5 } ?? palette.isDark}private func refresh() {- guard let m = model else { return }+ guard let m = model, let palette else { return }let dark = tileIsDark- let colors = SidebarColors(m.palette)+ let colors = SidebarColors(palette)CATransaction.begin()CATransaction.setDisableActions(true)if let hex = m.tileColor {layer?.backgroundColor = NSColor(hex: hex).cgColorshade.backgroundColor = (m.selected || hovering || targeted ? (dark ? NSColor.white.withAlphaComponent(0.12) : NSColor.black.withAlphaComponent(0.07)) : .clear).cgColor} else {- let fill: NSColor = m.selected ? (m.palette.isDark ? NSColor.white.withAlphaComponent(0.13) : NSColor.white.withAlphaComponent(0.38))- : (hovering || targeted ? (m.palette.isDark ? NSColor.white.withAlphaComponent(0.15) : NSColor.black.withAlphaComponent(0.09)) : NSColor(m.palette.pillFill))+ let fill: NSColor = m.selected ? (palette.isDark ? NSColor.white.withAlphaComponent(0.13) : NSColor.white.withAlphaComponent(0.38))+ : (hovering || targeted ? (palette.isDark ? NSColor.white.withAlphaComponent(0.15) : NSColor.black.withAlphaComponent(0.09)) : NSColor(palette.pillFill))layer?.backgroundColor = fill.cgColorshade.backgroundColor = NSColor.clear.cgColor}@@ -500,12 +577,12 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {rim.borderColor = (dark ? NSColor.white.withAlphaComponent(0.14) : NSColor.black.withAlphaComponent(0.17)).cgColorvar faviconColors = colorsfaviconColors.isDark = dark- favicon.show(m.icon, flip: m.icon != nil && m.glyphDark == dark, colors: faviconColors)+ for (f, c) in zip(favicons, m.cells) { f.show(c.icon, flip: c.icon != nil && c.glyphDark == dark, colors: faviconColors) }unreadDot.isHidden = !(m.unread && !m.selected)unreadDot.backgroundColor = (m.tileColor == nil ? colors.textPrimary : (dark ? NSColor.white : NSColor.black)).withAlphaComponent(0.6).cgColorif m.focus != (focusRing != nil) {if m.focus {- let r = FocusRingLayer(radius: 13)+ let r = FocusRingLayer(radius: FavoriteTileMetrics.corner)r.zPosition = 10layer?.addSublayer(r)focusRing = r@@ -524,7 +601,20 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {CATransaction.setDisableActions(true)shade.frame = boundsrim.frame = bounds- favicon.frame = NSRect(x: (bounds.width - 20) / 2, y: (bounds.height - 20) / 2, width: 20, height: 20)+ let cells = cellFrames+ for (f, r) in zip(favicons, cells) { f.frame = NSRect(x: (r.midX - 10).rounded(), y: (r.midY - 10).rounded(), width: 20, height: 20) }+ if cells.count > 1, layer?.mask != nil {+ // The cuts are holes in the tile (even-odd), so fill, rim and focus ring all stop at them.+ let path = CGMutablePath()+ path.addRoundedRect(in: bounds, cornerWidth: FavoriteTileMetrics.corner, cornerHeight: FavoriteTileMetrics.corner)+ let vertical = model?.vertical == true+ for (a, b) in zip(cells, cells.dropFirst()) {+ path.addRect(vertical ? CGRect(x: 0, y: a.maxY, width: bounds.width, height: b.minY - a.maxY)+ : CGRect(x: a.maxX, y: 0, width: b.minX - a.maxX, height: bounds.height))+ }+ cutMask.frame = bounds+ cutMask.path = path+ }unreadDot.frame = CGRect(x: bounds.width - 5 - 6, y: 5, width: 6, height: 6)focusRing?.frame = boundsCATransaction.commit()@@ -538,9 +628,24 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect], owner: self, userInfo: nil))}- override func mouseEntered(with event: NSEvent) { hovering = true; ArcTooltipController.shared.mouseMoved(in: self) }- override func mouseMoved(with event: NSEvent) { ArcTooltipController.shared.mouseMoved(in: self) }- override func mouseExited(with event: NSEvent) { hovering = false; ArcTooltipController.shared.mouseExited(self) }+ private var cellFrames: [CGRect] {+ FavoriteTileMetrics.cellFrames(in: bounds, count: model?.cells.count ?? 1, vertical: model?.vertical == true)+ }++ /// The cell under a point; a cut belongs to the cell before it.+ private func cellIndex(at p: NSPoint) -> Int {+ let vertical = model?.vertical == true+ return cellFrames.lastIndex { vertical ? $0.minY <= p.y : $0.minX <= p.x } ?? 0+ }++ private func trackPointer(_ event: NSEvent) {+ hoveredCell = cellIndex(at: convert(event.locationInWindow, from: nil))+ ArcTooltipController.shared.mouseMoved(in: self)+ }++ override func mouseEntered(with event: NSEvent) { hovering = true; trackPointer(event) }+ override func mouseMoved(with event: NSEvent) { trackPointer(event) }+ override func mouseExited(with event: NSEvent) { hovering = false; hoveredCell = nil; ArcTooltipController.shared.mouseExited(self) }override func mouseDown(with event: NSEvent) { press = event }override func mouseDragged(with event: NSEvent) {@@ -556,7 +661,7 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {let fill = layer?.backgroundColor.flatMap { NSColor(cgColor: $0) } ?? .clearlet image = NSImage(size: bounds.size, flipped: false) { r infill.setFill()- NSBezierPath(roundedRect: r, xRadius: 13, yRadius: 13).fill()+ NSBezierPath(roundedRect: r, xRadius: FavoriteTileMetrics.corner, yRadius: FavoriteTileMetrics.corner).fill()rep?.draw(in: r)return true}@@ -564,10 +669,13 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {beginDraggingSession(with: [item], event: p, source: self)}override func mouseUp(with event: NSEvent) {- guard press != nil, let grid else { return }+ guard let p = press, let grid else { return }press = nilgrid.ui.keyboardFocusID = nil- grid.store.selectTab(itemID, window: grid.ui.windowID)+ // A split opens with the pressed pane focused.+ let cells = model?.cells ?? []+ let i = cellIndex(at: convert(p.locationInWindow, from: nil))+ grid.store.selectTab(cells.indices.contains(i) ? cells[i].id : itemID, window: grid.ui.windowID)}func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {@@ -610,6 +718,12 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {guard let grid, let item = grid.store.item(itemID) else { return nil }let store = grid.store, ui = grid.ui, actions = grid.actions, favicons = grid.faviconslet id = itemID+ if item.isSplit, let m = model {+ return SidebarMenus.split(id, panes: m.cells.map { ($0.id, $0.title) }, open: m.selected, store: store, ui: ui, actions: actions) {+ MenuItems.add($0, "Remove from Favorites") { store.removeFromFavorites(id) }+ $0.addItem(.separator())+ }+ }let tileColor = item.tab?.tileColorlet m = NSMenu()m.autoenablesItems = false@@ -666,7 +780,11 @@ final class FavoriteTileView: NSView, ArcTooltipTarget, NSDraggingSource {}// ArcTooltipTarget: the title by the pointer.- var text: String { model?.title ?? "" }+ var text: String {+ guard let m = model else { return "" }+ if let i = hoveredCell, m.cells.count > 1, m.cells.indices.contains(i) { return m.cells[i].title }+ return m.title+ }var keys: [String] { [] }var followsCursor: Bool { true }var subtitle: String? { nil }diff --git a/Sources/Cra/UI/Sidebar/List/SpaceListView.swift b/Sources/Cra/UI/Sidebar/List/SpaceListView.swiftindex 190f391..69128ce 100644--- a/Sources/Cra/UI/Sidebar/List/SpaceListView.swift+++ b/Sources/Cra/UI/Sidebar/List/SpaceListView.swift@@ -103,7 +103,9 @@ final class SpaceListView: NSView, NSDraggingSource {wantsLayer = truescrollView.drawsBackground = falsescrollView.contentView.drawsBackground = false- scrollView.hasVerticalScroller = false+ scrollView.verticalScroller = SidebarScroller()+ scrollView.hasVerticalScroller = true+ scrollView.autohidesScrollers = truescrollView.hasHorizontalScroller = falsescrollView.horizontalScrollElasticity = .nonescrollView.verticalScrollElasticity = .allowed@@ -190,6 +192,7 @@ final class SpaceListView: NSView, NSDraggingSource {let renaming = ui.renamingIDlet focusID = ui.keyboardFocusIDlet capturing = ui.capturingTabIDs+ let audible = ui.audibleTabIDslet refreshing = LiveFolderManager.shared.refreshingvar out: [Row] = []@@ -249,7 +252,7 @@ final class SpaceListView: NSView, NSDraggingSource {icon: img, flipIcon: flip, githubMark: tab.liveItemURL != nil && tab.customIconKey == nil,editing: renaming == item.id, selected: selected,highlighted: picks.isEmpty ? selected : picks.contains(item.id),- capturing: capturing.contains(item.id), muted: tab.muted, unread: item.isUnread,+ capturing: capturing.contains(item.id), audible: audible.contains(item.id), muted: tab.muted, unread: item.isUnread,navigatedAway: navigatedAway,closeGroup: picks.contains(item.id) && picks.count > 1 ? picks.count : 1,focusRing: focusID == item.id))@@ -275,7 +278,7 @@ final class SpaceListView: NSView, NSDraggingSource {add(item, depth: 0, pinned: true, parent: space.pinnedContainerID, index: pinnedKids.firstIndex(of: item.id) ?? 0)}let section = dropSection(drop)- // With nothing pinned the list is 8 pt tall; a drag opens a real target. Not when+ // With nothing pinned the list takes no room; a drag opens a real target. Not when// collapsed: the placeholder would claim an empty list and open under the pointer,// taking drops meant for the top of Today.if pinnedKids.isEmpty && drop != nil {@@ -339,6 +342,7 @@ final class SpaceListView: NSView, NSDraggingSource {private func apply(_ b: Built) {palette = b.palette+ (scrollView.verticalScroller as? SidebarScroller)?.isDarkTheme = b.palette.isDarklet newColors = SidebarColors(b.palette)let recolor = newColors != colorscolors = newColors@@ -467,8 +471,9 @@ final class SpaceListView: NSView, NSDraggingSource {// MARK: Layout- /// SpaceSectionView's stacks: 3 pt on top, pinned rows (at least 8 pt), the 18 pt divider,- /// then Today; rows 1 pt apart and 10 pt in from the sides.+ /// SpaceSectionView's stacks: 3 pt on top, pinned rows, the 18 pt divider, then Today; rows+ /// 1 pt apart and 10 pt in from the sides. Arc 1.171 (31 Oct): every pinned row takes 41 pt,+ /// the first one too, so the first sits 1 pt lower than Today's; nothing pinned takes none.private func layoutRows() {let width = bounds.widthlet inner = max(0, width - 20)@@ -478,15 +483,13 @@ final class SpaceListView: NSView, NSDraggingSource {let isDivider = rows[i].key == .dividerif i == pinnedCount {pinnedFrame = NSRect(x: 10, y: pinnedTop, width: inner, height: y - pinnedTop)- y = pinnedTop + max(8, y - pinnedTop)}if isDivider {rows[i].frame = NSRect(x: 0, y: y, width: width, height: 18)y += 18continue}- let first = i == 0 || i == pinnedCount + 1- if !first { y += CraMetrics.rowSpacing }+ if i != pinnedCount + 1 { y += CraMetrics.rowSpacing }let h: CGFloatif case .liveStatus(let m) = rows[i].content { h = LiveStatusRowView.height(m, width: inner) } else { h = CraMetrics.rowHeight }rows[i].frame = NSRect(x: 10, y: y, width: inner, height: h)@@ -629,6 +632,14 @@ final class SpaceListView: NSView, NSDraggingSource {for l in all.allObjects where l.ui === ui && l.spaceID == space { l.scrollToSelected() }}+ /// Tests without the pointer (cra://debug?folderPreview=<id>): the folder's preview as if hovered.+ static func debugFolderPreview(_ folderID: UUID, ui: SidebarUIState) {+ for l in all.allObjects where l.ui === ui {+ guard let row = l.views[.item(folderID)] as? FolderRowView else { continue }+ FolderPreviewController.shared.debugOpen(folderID, row: row, list: l)+ }+ }+/// Scrolls the selected tab to the middle of the list (as far as the list allows).private func scrollToSelected() {guard let (row, _) = selectedRow() else { return }@@ -712,6 +723,7 @@ final class SpaceListView: NSView, NSDraggingSource {} else if let h = ui.hoveredTabID, views[.item(h)] != nil {ui.hoveredTabID = nil}+ FolderPreviewController.shared.hover(target, in: self)}target?.hoverMoved(to: local)let tip = scrolling ? nil : target?.tooltipTarget(at: local)@@ -973,12 +985,39 @@ enum SidebarListMetrics {final class SpaceListScrollView: NSScrollView {override class var isCompatibleWithResponsiveScrolling: Bool { false }+ /// Always overlay, also with "Show scroll bars: Always": rows are laid out over the full width.+ override var scrollerStyle: NSScroller.Style {+ get { .overlay }+ set { super.scrollerStyle = .overlay }+ }+override func scrollWheel(with event: NSEvent) {if event.hasPreciseScrollingDeltas, event.momentumPhase.isEmpty, abs(event.scrollingDeltaX) > abs(event.scrollingDeltaY) { return }super.scrollWheel(with: event)}}+/// Arc 1.171's list scroller (31 Oct 2026, issue #31): AppKit's overlay scroller, shown while+/// scrolling and faded out after, with no track and a 4 pt knob 3 pt in from the sidebar's+/// edge, white at 49 % on dark themes. It is only as wide as the 10 pt gutter right of the rows,+/// so it never covers a row's trailing buttons.+final class SidebarScroller: NSScroller {+ var isDarkTheme = true { didSet { if isDarkTheme != oldValue { needsDisplay = true } } }++ override class var isCompatibleWithOverlayScrollers: Bool { true }+ override class func scrollerWidth(for controlSize: NSControl.ControlSize, scrollerStyle: NSScroller.Style) -> CGFloat { 10 }++ override func drawKnobSlot(in slotRect: NSRect, highlight flag: Bool) {}++ override func drawKnob() {+ let knob = rect(for: .knob)+ guard knob.height > 0 else { return }+ let r = NSRect(x: bounds.maxX - 7, y: knob.minY + 2, width: 4, height: max(0, knob.height - 4))+ (isDarkTheme ? NSColor.white.withAlphaComponent(0.49) : NSColor.black.withAlphaComponent(0.3)).setFill()+ NSBezierPath(roundedRect: r, xRadius: 2, yRadius: 2).fill()+ }+}+/// The list's document: rows sit on it, it takes drops, hovers and the list's own menu.final class SpaceListDocument: NSView {weak var list: SpaceListView?diff --git a/Sources/Cra/UI/Sidebar/NowPlayingTray.swift b/Sources/Cra/UI/Sidebar/NowPlayingTray.swiftnew file mode 100644index 0000000..8e2438a--- /dev/null+++ b/Sources/Cra/UI/Sidebar/NowPlayingTray.swift@@ -0,0 +1,545 @@+import AppKit++/// Arc 1.171's "now playing" player over the bottom of the tab list (issue #33): Arc's+/// MediaControlsFeature (MiniPlayerView in a MediaControlsHostingView), measured from window+/// captures at 2x and 120 fps recordings of a running Arc (31 Oct 2026) and read from its+/// binary (Swift metadata, the PlaybackControlForeground colour asset, tooltip strings).+///+/// Cards sit 8 pt in from the sidebar's edges with 6 pt corners, bottom where the tab list ends+/// (50 pt above the window's), filled with the window palette's `backgroundExtra`: 15 % of the+/// theme's deep shade on dark spaces, near-white on light ones. At rest only the newest card+/// shows, 33 pt tall: favicon ("Back to Tab"), previous, play/pause, next and volume, laid out+/// like an HStack (glyphs 16 / 13 / 8.5 / 13 / 19 pt wide, equal gaps, 14 pt in on the left and+/// 12.5 on the right). Up to two more peek out behind it, each 7 pt higher, 5 pt narrower a side+/// and 20 % fainter; the second shows the tops of its controls at 15 %, 7.25 pt higher than the+/// front card's. Hovering opens every card to 65.5 pt with the tab's title (13 pt, 14.5 pt in,+/// centred 16.25 pt from the top), Picture in Picture for a video and ✕, stacked upward 5 pt apart,+/// oldest on top, in 0.2 s (ease-out); leaving folds them back the same way. The volume button+/// opens a drawer, one more 32.75 pt row with a slider, and stays lit while it is open. Glyphs are+/// PlaybackControlForeground (white 66 % / black 50 %), a third of that when unavailable, with a+/// 24 × 23 pt square (white 7 % / black 8 %) on hover. The tab on screen has no card.+enum NowPlayingMetrics {+ static let inset: CGFloat = 8+ static let collapsedHeight: CGFloat = 33+ static let expandedHeight: CGFloat = 65.5+ static let drawerHeight: CGFloat = 33+ static let gap: CGFloat = 5+ static let peek: CGFloat = 7+ static let peekInset: CGFloat = 5+ static let peekFade: CGFloat = 0.2+ static let restingCards = 3+ static let ghostLift: CGFloat = 7.25+ static let ghostAlpha: CGFloat = 0.15+ static let corner: CGFloat = 6+ static let closeCentreFromRight: CGFloat = 21.75+ static let pipCentreFromRight: CGFloat = 45.5+ static let titleCentreFromTop: CGFloat = 16.25+ static let rowCentreFromBottom: CGFloat = 16.5+ static let controlWidths: [CGFloat] = [16, 13, 8.5, 13, 19]+ static let controlsLeading: CGFloat = 14+ static let controlsTrailing: CGFloat = 12.5++ /// Height the tab list gives up while the player rests (with its gap to the list).+ static func restHeight(cards: Int) -> CGFloat {+ cards == 0 ? 0 : collapsedHeight + CGFloat(min(cards, restingCards) - 1) * peek + 8+ }+}++/// The card's colours for a theme colour and scheme. Arc derives them from the window palette+/// (`backgroundExtra`, `PlaybackControlForeground`, `tintedLight`, `shadedDark`); Cra has no Arc+/// palette, so its shades are rebuilt from the theme colour: Arc's shadedDark is the theme's hue,+/// strongly saturated, at ~10 % luminance (#6F5600 for #F8D558, #1F2AFF for a deep blue).+struct NowPlayingColors {+ let isDark: Bool+ let fill: NSColor+ let foreground: NSColor+ let title: NSColor+ let hover: NSColor+ let placeholder: NSColor+ let trackFilled: NSColor+ let trackEmpty: NSColor+ let knob: NSColor++ init(themeColor hex: String?, dark: Bool) {+ let c = HexColor.components(hex ?? "") ?? (0.5, 0.5, 0.5)+ let (h, s, _) = SpaceTheme.hsb(c.r, c.g, c.b)+ let grey = s < 0.05+ func color(_ s: Double, _ v: Double) -> NSColor {+ let o = SpaceTheme.rgb(h: h, s: s, v: v)+ return NSColor(srgbRed: o.0, green: o.1, blue: o.2, alpha: 1)+ }+ // shadedDark: the brightness at which the saturated hue reaches 10 % luminance.+ func lin(_ x: Double) -> Double { x <= 0.04045 ? x / 12.92 : pow((x + 0.055) / 1.055, 2.4) }+ let ds = grey ? 0 : 0.94+ var lo = 0.0, hi = 1.0+ for _ in 0..<20 {+ let v = (lo + hi) / 2, o = SpaceTheme.rgb(h: h, s: ds, v: v)+ if 0.2126 * lin(o.0) + 0.7152 * lin(o.1) + 0.0722 * lin(o.2) < 0.1 { lo = v } else { hi = v }+ }+ isDark = dark+ if dark {+ fill = color(ds, lo * 0.15)+ foreground = NSColor.white.withAlphaComponent(0.66)+ title = NSColor.white.withAlphaComponent(0.81)+ hover = NSColor.white.withAlphaComponent(0.07)+ placeholder = NSColor.white.withAlphaComponent(0.14)+ trackFilled = color(grey ? 0 : 0.25, 0.99)+ trackEmpty = NSColor.white.withAlphaComponent(0.1)+ knob = NSColor(srgbRed: 0.86, green: 0.86, blue: 0.85, alpha: 1)+ } else {+ fill = color(grey ? 0 : 0.012, 0.996)+ foreground = NSColor.black.withAlphaComponent(0.5)+ title = NSColor.black.withAlphaComponent(0.85)+ hover = NSColor.black.withAlphaComponent(0.08)+ placeholder = NSColor.black.withAlphaComponent(0.15)+ trackFilled = color(ds, lo)+ trackEmpty = NSColor.black.withAlphaComponent(0.18)+ knob = .white+ }+ }++ var disabled: NSColor { foreground.withAlphaComponent(foreground.alphaComponent / 3) }++ /// Row-button colours for the card (only the hover fill is used; glyphs take `tint`).+ var buttonColors: SidebarColors {+ var c = SidebarColors(SpaceTheme.presets[isDark ? 0 : SpaceTheme.presets.count - 1].palette)+ c.hoverFill = hover+ return c+ }+}++/// The cards, pinned to the bottom of the tab list's area. The view spans the list so the+/// stack can grow over it; points outside the cards fall through to the list.+@MainActor+final class NowPlayingTrayView: NSView {+ private let store: SidebarStore+ private let ui: SidebarUIState+ private let favicons: FaviconCache+ private var cards: [UUID: NowPlayingCardView] = [:]+ private var order: [UUID] = []+ private var expanded = false+ private var drawerID: UUID?+ private var colors = NowPlayingColors(themeColor: nil, dark: true)+ /// The number of cards changed: the sidebar gives the list more or less room.+ var onCountChange: (() -> Void)?+ var shownCount: Int { order.count }++ init(store: SidebarStore, ui: SidebarUIState, favicons: FaviconCache) {+ self.store = store+ self.ui = ui+ self.favicons = favicons+ super.init(frame: .zero)+ wantsLayer = true+ observe()+ }++ required init?(coder: NSCoder) { fatalError() }++ /// The space's theme colour and scheme, for the cards' palette.+ func setTheme(_ hex: String?, dark: Bool) {+ colors = NowPlayingColors(themeColor: hex, dark: dark)+ for c in cards.values { c.colors = colors }+ }++ private func observe() {+ let shown = withObservationTracking { () -> [(NowPlaying.Entry, NowPlayingCardModel)] in+ ui.nowPlaying.shown.map { e in+ let item = store.item(e.id)+ let icon = favicons.image(forKey: item?.tab?.iconKey)+ return (e, NowPlayingCardModel(title: item?.displayTitle ?? "", icon: icon, playing: e.playing,+ muted: item?.tab?.muted ?? false, hasPrevious: e.hasPrevious, hasNext: e.hasNext,+ hasVideo: e.hasVideo, volume: e.volume))+ }+ } onChange: { [weak self] in+ Task { @MainActor in self?.observe() }+ }+ let ids = shown.map(\.0.id)+ for (e, m) in shown {+ let card = cards[e.id] ?? makeCard(e.id)+ card.apply(m)+ }+ for (id, card) in cards where !ids.contains(id) {+ cards[id] = nil+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = 0.15+ card.animator().alphaValue = 0+ } completionHandler: { card.removeFromSuperview() }+ }+ let countChanged = ids.count != order.count+ order = ids+ if order.isEmpty { expanded = false }+ if let d = drawerID, !ids.contains(d) { drawerID = nil }+ place(animated: true)+ if countChanged { onCountChange?() }+ }++ private func makeCard(_ id: UUID) -> NowPlayingCardView {+ let card = NowPlayingCardView(colors: colors) { [weak self] action in+ guard let self else { return }+ if case .toggleMute = action {+ // Arc's volume button opens the volume drawer; the tab's mute stays on its row.+ self.drawerID = self.drawerID == id ? nil : id+ self.place(animated: true)+ return+ }+ self.ui.nowPlaying.perform(id, action)+ }+ card.frame = restFrame(level: 0)+ card.alphaValue = 0+ addSubview(card, positioned: .below, relativeTo: nil)+ cards[id] = card+ return card+ }++ // MARK: Layout++ /// `level` counts back from the front card.+ private func restFrame(level k: Int) -> NSRect {+ let m = NowPlayingMetrics.self+ let k = CGFloat(min(k, m.restingCards - 1))+ return NSRect(x: m.inset + k * m.peekInset, y: k * m.peek, width: bounds.width - 2 * (m.inset + k * m.peekInset),+ height: m.collapsedHeight)+ }++ private func place(animated: Bool) {+ let m = NowPlayingMetrics.self+ var frames: [(NowPlayingCardView, NSRect, CGFloat)] = []+ var y: CGFloat = 0+ for (k, id) in order.reversed().enumerated() {+ guard let card = cards[id] else { continue }+ card.drawerOpen = expanded && drawerID == id+ if expanded {+ let h = m.expandedHeight + (card.drawerOpen ? m.drawerHeight : 0)+ let f = NSRect(x: m.inset, y: y, width: bounds.width - 2 * m.inset, height: h)+ y += h + m.gap+ frames.append((card, f, f.maxY <= bounds.height ? 1 : 0))+ } else {+ frames.append((card, restFrame(level: k), k < m.restingCards ? 1 - CGFloat(k) * m.peekFade : 0))+ }+ }+ // The front card on top. Cards behind it show only their edge, and their buttons must not+ // take the hover meant for the front card's (tracking areas don't know what covers them).+ for (card, _, _) in frames.reversed() { addSubview(card, positioned: .above, relativeTo: nil) }+ let front = frames.first?.0+ let second = frames.count > 1 ? frames[1].0 : nil+ let hideBehind = { [expanded] in+ for (card, _, _) in frames {+ card.ghostVisible = !expanded && card === second // pictured before its controls hide+ card.contentHidden = !expanded && card !== front+ }+ }+ if expanded { hideBehind() }+ guard animated, window != nil else {+ for (card, f, a) in frames { card.frame = f; card.alphaValue = a }+ hideBehind()+ return+ }+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = 0.2+ ctx.timingFunction = CAMediaTimingFunction(controlPoints: 0.15, 0.85, 0.3, 1)+ ctx.allowsImplicitAnimation = true+ for (card, f, a) in frames {+ card.animator().frame = f+ card.animator().alphaValue = a+ }+ } completionHandler: { [weak self] in+ if self?.expanded == false { hideBehind() }+ }+ }++ override func layout() {+ super.layout()+ place(animated: false)+ }++ // MARK: Hover++ override func updateTrackingAreas() {+ super.updateTrackingAreas()+ for t in trackingAreas where t.owner === self { removeTrackingArea(t) }+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .inVisibleRect],+ owner: self, userInfo: nil))+ }++ override func mouseMoved(with event: NSEvent) { setHovered(overStack(convert(event.locationInWindow, from: nil))) }+ override func mouseEntered(with event: NSEvent) { setHovered(overStack(convert(event.locationInWindow, from: nil))) }+ override func mouseExited(with event: NSEvent) { setHovered(false) }++ /// The whole stack, gaps between cards included, so moving from card to card keeps it open.+ private func overStack(_ p: NSPoint) -> Bool {+ cards.values.filter { $0.alphaValue > 0 }.map(\.frame).reduce(NSRect.null) { $0.union($1) }.contains(p)+ }++ private func setHovered(_ hovered: Bool) {+ let want = hovered && !order.isEmpty+ guard want != expanded else { return }+ expanded = want+ if !want { drawerID = nil }+ place(animated: true)+ }++ override func hitTest(_ point: NSPoint) -> NSView? {+ let p = convert(point, from: superview)+ guard cards.values.contains(where: { $0.alphaValue > 0 && $0.frame.contains(p) }) else { return nil }+ return super.hitTest(point)+ }+}++struct NowPlayingCardModel: Equatable {+ var title: String+ var icon: NSImage?+ var playing: Bool+ var muted: Bool+ var hasPrevious: Bool+ var hasNext: Bool+ var hasVideo: Bool+ var volume: Double+}++/// One card: the title row on top (shown while the stack is open), the controls, and the volume+/// drawer below them. The content stays pinned to the card's bottom, so a resting card shows only+/// the controls and opening it reveals the title from above.+@MainActor+final class NowPlayingCardView: NSView {+ private let content = NSView()+ private let title = NSTextField.sidebarLabel(size: 13)+ private let titleRow = NSView()+ private let icon = NowPlayingIconView()+ private let pip: SidebarGlyphButton+ private let close: SidebarGlyphButton+ private let previous: SidebarGlyphButton+ private let playPause: SidebarGlyphButton+ private let next: SidebarGlyphButton+ private let volume: SidebarGlyphButton+ private let slider = NowPlayingVolumeSlider()+ /// A resting card behind the front one shows a faint, inert copy of its controls (no buttons,+ /// so it can't take the front card's hover or tooltips).+ private let ghost = NowPlayingGhostRow()+ private var model: NowPlayingCardModel?+ private let perform: (NowPlaying.Action) -> Void+ var colors: NowPlayingColors { didSet { applyColors() } }+ var drawerOpen = false {+ didSet {+ guard drawerOpen != oldValue else { return }+ volume.highlighted = drawerOpen+ slider.isHidden = !drawerOpen+ needsLayout = true+ }+ }+ var contentHidden: Bool {+ get { content.isHidden }+ set { if content.isHidden != newValue { content.isHidden = newValue } }+ }+ var ghostVisible = false {+ didSet {+ guard ghostVisible != oldValue else { return }+ if ghostVisible { ghost.show(from: [icon, previous, playPause, next, volume]) }+ ghost.isHidden = !ghostVisible+ needsLayout = true+ }+ }++ init(colors: NowPlayingColors, perform: @escaping (NowPlaying.Action) -> Void) {+ self.colors = colors+ self.perform = perform+ func button(_ symbol: String, _ iconSize: CGFloat, _ help: String, _ action: NowPlaying.Action) -> SidebarGlyphButton {+ SidebarGlyphButton(symbol: symbol, size: 24, height: 23, iconSize: iconSize, help: help, colors: colors.buttonColors) { perform(action) }+ }+ pip = button("rectangle.on.rectangle", 13, "Open Picture in Picture", .pictureInPicture)+ close = button("xmark", 14, "Close Mini Player", .dismiss)+ previous = button("backward.end.fill", 13.5, "Previous Track", .previous)+ playPause = button("pause.fill", 13.5, "Pause", .togglePlayback)+ next = button("forward.end.fill", 13.5, "Next Track", .next)+ volume = button("speaker.wave.3.fill", 14, "Adjust Tab Volume", .toggleMute)+ super.init(frame: .zero)+ wantsLayer = true+ layer?.cornerRadius = NowPlayingMetrics.corner+ layer?.cornerCurve = .continuous+ layer?.masksToBounds = true+ icon.onClick = { perform(.show) }+ _ = ArcTooltipAnchorView.attach(to: icon, help: "Back to Tab")+ // Arc: clicking the title row (titleRowClicked) goes back to the tab.+ titleRow.addGestureRecognizer(NSClickGestureRecognizer(target: self, action: #selector(titleClicked)))+ slider.isHidden = true+ slider.onChange = { v in perform(.setVolume(v)) }+ pip.isHidden = true+ titleRow.addSubview(title)+ for v in [titleRow, pip, close, icon, previous, playPause, next, volume, slider] as [NSView] { content.addSubview(v) }+ addSubview(content)+ ghost.isHidden = true+ ghost.alphaValue = NowPlayingMetrics.ghostAlpha+ addSubview(ghost)+ applyColors()+ }++ required init?(coder: NSCoder) { fatalError() }++ @objc private func titleClicked() { perform(.show) }++ private func applyColors() {+ layer?.backgroundColor = colors.fill.cgColor+ title.textColor = colors.title+ icon.placeholder = colors.placeholder+ slider.colors = colors+ for b in [pip, close, playPause, volume] { b.colors = colors.buttonColors; b.tint = colors.foreground }+ refreshTrackButtons()+ }++ /// Previous/next without a media session handler are dimmed, with no hover and no tooltip.+ private func refreshTrackButtons() {+ for (b, on, help) in [(previous, model?.hasPrevious ?? false, "Previous Track"), (next, model?.hasNext ?? false, "Next Track")] {+ b.colors = colors.buttonColors+ b.enabled = on+ b.tint = on ? colors.foreground : colors.disabled+ b.setHelp(on ? help : "")+ }+ }++ func apply(_ m: NowPlayingCardModel) {+ guard m != model else { return }+ let old = model+ model = m+ title.stringValue = m.title+ icon.image = m.icon+ if old?.playing != m.playing {+ playPause.setSymbol(m.playing ? "pause.fill" : "play.fill", iconSize: 13.5, help: m.playing ? "Pause" : "Play")+ }+ // Arc: three waves, one wave below half volume, none at zero; a muted tab shows the slash.+ if old.map({ $0.muted != m.muted || $0.volume != m.volume }) ?? true {+ let symbol = m.muted ? "speaker.slash.fill" : m.volume <= 0 ? "speaker.fill" : m.volume < 0.5 ? "speaker.wave.1.fill" : "speaker.wave.3.fill"+ volume.setSymbol(symbol, iconSize: 14, help: "Adjust Tab Volume")+ }+ if !slider.isTracking { slider.value = m.volume }+ pip.isHidden = !m.hasVideo+ refreshTrackButtons()+ needsLayout = true+ }++ override func layout() {+ super.layout()+ let m = NowPlayingMetrics.self+ let w = bounds.width+ let drawer = drawerOpen ? m.drawerHeight : 0+ let h = m.expandedHeight + drawer+ content.frame = NSRect(x: 0, y: 0, width: w, height: h)+ if drawerOpen {+ slider.frame = NSRect(x: 8, y: m.rowCentreFromBottom + 0.25 - 10, width: w - 16, height: 20)+ }+ let row = m.rowCentreFromBottom + drawer+ let gap = (w - m.controlsLeading - m.controlsTrailing - m.controlWidths.reduce(0, +)) / 4+ var x = m.controlsLeading+ for (v, glyphWidth) in zip([icon, previous, playPause, next, volume] as [NSView], m.controlWidths) {+ let s = v.frame.size == .zero ? NSSize(width: 24, height: 23) : v.frame.size+ let cx = x + glyphWidth / 2+ v.frame = NSRect(x: cx - s.width / 2, y: (row - s.height / 2).rounded(), width: s.width, height: s.height)+ x += glyphWidth + gap+ }+ let top = h - m.titleCentreFromTop+ close.frame = NSRect(x: w - m.closeCentreFromRight - 12, y: (top - 11.5).rounded(), width: 24, height: 23)+ pip.frame = NSRect(x: w - m.pipCentreFromRight - 12, y: (top - 11.5).rounded(), width: 24, height: 23)+ ghost.frame = NSRect(x: 0, y: (m.rowCentreFromBottom + m.ghostLift - 11.5).rounded(), width: w, height: 23)+ let titleRight = (pip.isHidden ? close.frame.minX : pip.frame.minX) - 4+ titleRow.frame = NSRect(x: 0, y: h - 32.75, width: titleRight, height: 32.75)+ let th = title.intrinsicContentSize.height+ title.frame = NSRect(x: 14.5 - SidebarText.inset, y: (titleRow.bounds.height - m.titleCentreFromTop - th / 2).rounded(),+ width: max(0, titleRight - 4 - 14.5 + SidebarText.inset), height: th)+ }++ override func hitTest(_ point: NSPoint) -> NSView? {+ // The title row is above the visible part of a resting card.+ guard frame.contains(point) else { return nil }+ return super.hitTest(point)+ }+}++/// The tab's favicon on the card ("Back to Tab"); a click goes back to the tab.+final class NowPlayingIconView: NSView {+ private let imageView = NSImageView()+ var onClick: () -> Void = {}+ var placeholder = NSColor.white.withAlphaComponent(0.14) { didSet { refresh() } }+ var image: NSImage? { didSet { imageView.image = image; refresh() } }++ override init(frame: NSRect) {+ super.init(frame: NSRect(x: 0, y: 0, width: 16, height: 16))+ wantsLayer = true+ layer?.cornerRadius = 3+ imageView.imageScaling = .scaleProportionallyUpOrDown+ imageView.frame = bounds+ imageView.autoresizingMask = [.width, .height]+ addSubview(imageView)+ refresh()+ }++ convenience init() { self.init(frame: .zero) }+ required init?(coder: NSCoder) { fatalError() }++ private func refresh() { layer?.backgroundColor = image == nil ? placeholder.cgColor : nil }++ override func mouseDown(with event: NSEvent) {}+ override func mouseUp(with event: NSEvent) {+ if bounds.contains(convert(event.locationInWindow, from: nil)) { onClick() }+ }+}++/// Arc's tab volume slider: a 6 pt rounded track 8 pt in from the card's sides, filled up to a+/// 20 × 16 pt pill knob (the theme's light tint on dark cards, its deep shade on light ones).+final class NowPlayingVolumeSlider: NSView {+ var colors = NowPlayingColors(themeColor: nil, dark: true) { didSet { needsDisplay = true } }+ var value = 1.0 { didSet { if value != oldValue { needsDisplay = true } } }+ var onChange: (Double) -> Void = { _ in }+ private(set) var isTracking = false+ private static let knob = NSSize(width: 20, height: 16)++ override var mouseDownCanMoveWindow: Bool { false }++ override func draw(_ dirtyRect: NSRect) {+ let k = Self.knob+ let track = NSRect(x: 0, y: (bounds.height - 6) / 2, width: bounds.width, height: 6)+ colors.trackEmpty.setFill()+ NSBezierPath(roundedRect: track, xRadius: 3, yRadius: 3).fill()+ let knobX = (bounds.width - k.width) * value+ colors.trackFilled.setFill()+ NSBezierPath(roundedRect: NSRect(x: 0, y: track.minY, width: knobX + k.width / 2, height: 6), xRadius: 3, yRadius: 3).fill()+ let knob = NSBezierPath(roundedRect: NSRect(x: knobX, y: (bounds.height - k.height) / 2, width: k.width, height: k.height),+ xRadius: k.height / 2, yRadius: k.height / 2)+ NSGraphicsContext.saveGraphicsState()+ if !colors.isDark {+ let shadow = NSShadow()+ shadow.shadowColor = NSColor.black.withAlphaComponent(0.18)+ shadow.shadowBlurRadius = 3+ shadow.shadowOffset = NSSize(width: 0, height: -0.5)+ shadow.set()+ }+ colors.knob.setFill()+ knob.fill()+ NSGraphicsContext.restoreGraphicsState()+ }++ private func set(from event: NSEvent) {+ let p = convert(event.locationInWindow, from: nil)+ value = max(0, min(1, (p.x - Self.knob.width / 2) / max(1, bounds.width - Self.knob.width)))+ onChange(value)+ }++ override func mouseDown(with event: NSEvent) { isTracking = true; set(from: event) }+ override func mouseDragged(with event: NSEvent) { set(from: event) }+ override func mouseUp(with event: NSEvent) { set(from: event); isTracking = false }+}++/// Inert pictures of a card's controls, for the faint row a resting back card shows.+final class NowPlayingGhostRow: NSView {+ override func hitTest(_ point: NSPoint) -> NSView? { nil }++ func show(from controls: [NSView]) {+ subviews.forEach { $0.removeFromSuperview() }+ for v in controls {+ guard let rep = v.bitmapImageRepForCachingDisplay(in: v.bounds) else { continue }+ v.cacheDisplay(in: v.bounds, to: rep)+ let image = NSImage(size: v.bounds.size)+ image.addRepresentation(rep)+ let iv = NSImageView(image: image)+ iv.frame = NSRect(x: v.frame.minX, y: 0, width: v.frame.width, height: v.frame.height)+ addSubview(iv)+ }+ }+}diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swiftindex 6538332..e48cae4 100644--- a/Sources/Cra/UI/SidebarUIState.swift+++ b/Sources/Cra/UI/SidebarUIState.swift@@ -17,6 +17,10 @@ final class SidebarUIState {var loadedTabIDs: Set<UUID> = []/// Tabs using the camera or microphone (Arc's recording indicator).var capturingTabIDs: Set<UUID> = []+ /// Tabs playing sound (Arc's speaker button).+ var audibleTabIDs: Set<UUID> = []+ /// The window's sidebar player (NowPlayingTrayView), fed by its BrowserManager.+ @ObservationIgnored let nowPlaying = NowPlaying()var canGoBack = falsevar canGoForward = falsevar isLoading = falsediff --git a/Sources/Cra/UI/Theme.swift b/Sources/Cra/UI/Theme.swiftindex 4d0f98f..91bc6e1 100644--- a/Sources/Cra/UI/Theme.swift+++ b/Sources/Cra/UI/Theme.swift@@ -41,6 +41,14 @@ struct SpacePalette {let gradientAlpha: Doublelet gradientAlphaBottom: Doublelet vibrant: Bool+ /// One flat colour over Arc's solid-theme material (ShellView.solidBackdrop).+ let solid: Bool++ /// Arc 1.171 over solid white and black backdrops (31 Oct 2026, nine colours, sRGB after+ /// undoing the display's P3): out = α·colour + (1 − α)·(66 + 0.52·backdrop) while active,+ /// α·colour + (1 − α)·212 while inactive, with α = 0.19 + 0.55·intensity (fits 0.191,+ /// 0.459, 0.742 at 0, 0.5, 1; within 3/255). isVibrant and the text appearance don't matter.+ static func solidAlpha(intensity: Double) -> Double { 0.19 + 0.55 * max(0, min(1, intensity)) }var gradient: LinearGradient {LinearGradient(colors: gradientColors, startPoint: .top, endPoint: .bottom)@@ -124,7 +132,7 @@ extension SpaceTheme {let base = colors.isEmpty ? ["#DDDDDD"] : colors// Vibrant (Arc): raw colors at `intensity` opacity over the blur.// Opaque: intensity 1 = the raw colors; lower pulls toward white/black.- let pull = vibrant ? 0 : (1 - intensity) * (dark ? 0.35 : 0.6)+ let pull = vibrant || solid ? 0 : (1 - intensity) * (dark ? 0.35 : 0.6)var stops = base.map { SpaceTheme.mix($0, towardWhite: !dark, amount: pull) }if stops.count == 1 { stops.append(SpaceTheme.mix(base[0], towardWhite: !dark, amount: pull + 0.15)) }@@ -157,9 +165,12 @@ extension SpaceTheme {// 27, passes 52 %) could not reach both, so light vibrant themes now blur through// an untinted CABackdropLayer with a 0.19 dim and a 0.16→0.18 lift (ShellView);// opacity 0.43 top / 0.59 bottom then matches Arc within ±5 over white and black.- gradientAlpha: vibrant ? (dark ? max(0.35, min(0.9, intensity * 2.2)) : min(0.95, intensity * 1.70)) : 1,- gradientAlphaBottom: vibrant ? (dark ? max(0.35, min(0.9, intensity * 2.2)) : min(0.95, intensity * 2.35)) : 1,- vibrant: vibrant+ gradientAlpha: solid ? SpacePalette.solidAlpha(intensity: intensity)+ : vibrant ? (dark ? max(0.35, min(0.9, intensity * 2.2)) : min(0.95, intensity * 1.70)) : 1,+ gradientAlphaBottom: solid ? SpacePalette.solidAlpha(intensity: intensity)+ : vibrant ? (dark ? max(0.35, min(0.9, intensity * 2.2)) : min(0.95, intensity * 2.35)) : 1,+ vibrant: vibrant || solid,+ solid: solid)}}diff --git a/Sources/Cra/UI/Windows/FloatingSidebar.swift b/Sources/Cra/UI/Windows/FloatingSidebar.swiftindex dbc2037..160211a 100644--- a/Sources/Cra/UI/Windows/FloatingSidebar.swift+++ b/Sources/Cra/UI/Windows/FloatingSidebar.swift@@ -14,6 +14,8 @@ final class FloatingSidebarController {unowned let window: NSWindow/// Whether the anchored sidebar is hidden right now (floating only makes sense then).var sidebarHidden: () -> Bool = { false }+ /// Something beside the sidebar still belongs to it (a folder preview): the pointer may leave.+ var staysShown: () -> Bool = { false }var palette: () -> SpacePalette/// Called after the panel is attached so the overlay panel can be re-ordered above it.var didAttachPanel: (() -> Void)?@@ -28,10 +30,14 @@ final class FloatingSidebarController {private let lift = NSView()private var gradientHost: PaletteBackgroundView?private var trafficLights: FloatingTrafficLights?+ /// The floating sidebar's right edge drags its width, like the anchored sidebar's handle.+ private let resizeHandle = ResizeHandleView()enum Metrics {static let cornerRadius: CGFloat = 12static let duration: TimeInterval = 0.085+ /// Inside the sidebar's edge: the panel ends there, so the strip cannot straddle it.+ static let resizeHandleWidth: CGFloat = 6}init(shell: ShellView, window: NSWindow, palette: @escaping () -> SpacePalette) {@@ -65,7 +71,7 @@ final class FloatingSidebarController {if !isShown {guard sidebarHidden(), FloatingSidebarGeometry.shouldReveal(at: p, in: shell.bounds, edgeToEdge: shell.edgeToEdge) else { return }show()- } else if FloatingSidebarGeometry.shouldHide(at: p, in: shell.bounds, sidebarWidth: shell.sidebarWidth,+ } else if !staysShown(), FloatingSidebarGeometry.shouldHide(at: p, in: shell.bounds, sidebarWidth: shell.sidebarWidth,pressedMouseButtons: NSEvent.pressedMouseButtons, edgeToEdge: shell.edgeToEdge) {hide(animated: true)}@@ -122,6 +128,14 @@ final class FloatingSidebarController {let lights = FloatingTrafficLights(browserWindow: window)lights.willAct = { [weak self] in self?.hide(animated: false) }trafficLights = lights+ resizeHandle.autoresizingMask = [.minXMargin, .height]+ // The shell's handle owns the width and saves it; the panel follows.+ resizeHandle.onDrag = { [weak self] dx in+ guard let self else { return }+ shell.resizeHandle.onDrag?(dx)+ reposition()+ }+ resizeHandle.onEnd = { [weak self] in self?.shell.resizeHandle.onEnd?() }return p}@@ -164,6 +178,10 @@ final class FloatingSidebarController {lights.setFrameOrigin(NSPoint(x: 13, y: slider.bounds.height - CraMetrics.titleRowCenter - lights.frame.height / 2))slider.addSubview(lights, positioned: .above, relativeTo: host)}+ let w = Metrics.resizeHandleWidth+ resizeHandle.frame = NSRect(x: slider.bounds.width - w, y: 0, width: w, height: slider.bounds.height)+ resizeHandle.isHidden = !shell.sidebarResizable+ slider.addSubview(resizeHandle, positioned: .above, relativeTo: nil)shell.sidebarDetached = trueshell.floatingSidebar = trueif p.parent !== window { window.addChildWindow(p, ordered: .above) }diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swiftindex b855ea2..1ad25f8 100644--- a/Sources/Cra/UI/Windows/MainWindowController.swift+++ b/Sources/Cra/UI/Windows/MainWindowController.swift@@ -249,6 +249,21 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMguard let main = app?.main, let window = main.window, let key = NSApp.keyWindow, key === window || key.parent === window else { return nil }return main.extensionPopupAnchor(id)}+ browsers.nowPlaying = sidebarUI.nowPlaying+ sidebarUI.nowPlaying.perform = { [weak self] id, action in+ guard let self else { return }+ switch action {+ case .show:+ store.selectTab(id, window: windowID)+ window?.makeKeyAndOrderFront(nil)+ case .toggleMute:+ let muted = !(store.item(id)?.tab?.muted ?? false)+ store.setMuted(id, muted)+ app.runtime(for: id)?.browser.setAudioMuted(muted)+ default:+ browsers.performNowPlaying(id, action)+ }+ }sidebarActions.performAction = { [weak self] id inif id.hasPrefix("muteTab:"), let uuid = UUID(uuidString: String(id.dropFirst(8))) {let muted = self?.store.item(uuid)?.tab?.muted ?? false@@ -302,6 +317,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMshell.vibrancyLift.isHidden = !palette.vibrantshell.vibrantDark = palette.isDarkshell.vibrantLight = palette.vibrant && !palette.isDark+ shell.solidBackdrop = palette.solidshell.refreshLift()window?.isOpaque = !palette.vibrantwindow?.backgroundColor = palette.vibrant ? .clear : NSColor(palette.gradientColors.first ?? .gray)@@ -372,6 +388,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMif loaded != sidebarUI.loadedTabIDs { sidebarUI.loadedTabIDs = loaded }let capturing = Set(app.mainWindows.flatMap { $0.browsers.runtimes.filter { $0.value.browser.isCapturingMedia }.keys })if capturing != sidebarUI.capturingTabIDs { sidebarUI.capturingTabIDs = capturing }+ let audible = Set(app.mainWindows.flatMap { $0.browsers.runtimes.filter { $0.value.browser.isAudible }.keys })+ if audible != sidebarUI.audibleTabIDs { sidebarUI.audibleTabIDs = audible }let b = browsers.visibleRuntime?.browserif sidebarUI.canGoBack != (b?.canGoBack ?? false) { sidebarUI.canGoBack = b?.canGoBack ?? false }if sidebarUI.canGoForward != (b?.canGoForward ?? false) { sidebarUI.canGoForward = b?.canGoForward ?? false }@@ -1225,13 +1243,15 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMfunc browserManagerPageClosedTab(_ tabID: UUID) { closeTab(tabID) }/// Arc's Peek (Settings ▸ Tabs ▸ Links): a link to another site clicked in a favorite or- /// pinned tab, or any Shift-clicked link, opens over the window and the tab stays put.+ /// pinned tab (any tab with "In every tab" on), or any Shift-clicked link, opens over the+ /// window and the tab stays put.func browserManagerOpensPeek(url: String, fromTab tabID: UUID, pageURL: String, shiftClick: Bool) -> Bool {guard !isIncognito, let target = SiteKey.site(of: url) else { return false }if shiftClick {guard store.settings.peekOnShiftClick else { return false }} else {- guard store.settings.peekLinksToOtherSites, store.isPinned(tabID),+ guard store.settings.peekLinksToOtherSites,+ store.settings.peekInEveryTab || store.isPinned(tabID),let here = SiteKey.site(of: pageURL), here != target else { return false }}app.openPeek(url: url, over: self)@@ -1405,6 +1425,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMself?.focusedSpace.theme.palette ?? SpaceTheme.presets[0].palette})f.sidebarHidden = { [weak self] in self.map { !$0.sidebarVisible } ?? false }+ f.staysShown = { FolderPreviewController.shared.isOpen }f.didAttachPanel = { [weak self] in// Keep toasts and the find bar above the floating sidebar.self?.raiseOverlayPanels()diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex 8b47745..b58de1d 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -82,6 +82,10 @@ static CefString CefStringFromNS(NSString* s) {/// Page context menus shown by Cra (RunContextMenu) instead of Chrome.static BOOL g_ownContextMenus = NO;+/// Page.addScriptToEvaluateOnNewDocument params every page browser gets once it exists+/// (the page's world, then Cra's isolated world).+static NSArray<NSString*>* g_documentStartParams = nil;+/// The command picked from a context menu Cra shows; -1 while none is.@interface CraMenuPick : NSObject@property (nonatomic) int commandID;@@ -172,6 +176,8 @@ static CraClient* AsCraClient(CefClient* c) {@property (nonatomic) BOOL isInPictureInPicture;@property (nonatomic) BOOL isPictureInPicturePlaying;@property (nonatomic) BOOL isCapturingMedia;+@property (nonatomic) BOOL isAudible;+- (void)audibleChanged:(BOOL)audible;- (void)requestPictureInPictureInFrame:(CefRefPtr<CefFrame>)frame automatic:(BOOL)automatic x:(int)x y:(int)y;- (void)adoptBrowser:(CefRefPtr<CefBrowser>)browser;- (void)devToolsBrowserCreated:(CefRefPtr<CefBrowser>)browser;@@ -1091,6 +1097,15 @@ public:[o.delegate browser:o didChangeMediaCapture:capturing];}+ // Chromium's audible state, which CEF has no callback for: the engine sends it as a+ // "Cra.audible" message (scripts/cef-patches/audible-state.patch).+ bool OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,+ CefProcessId source_process, CefRefPtr<CefProcessMessage> message) override {+ if (source_process != PID_BROWSER || message->GetName() != "Cra.audible") return false;+ if (CraBrowser* o = owner_) [o audibleChanged:message->GetArgumentList()->GetBool(0)];+ return true;+ }+void OnFaviconURLChange(CefRefPtr<CefBrowser> browser, const std::vector<CefString>& icon_urls) override {CraBrowser* o = owner_;if (!o || icon_urls.empty()) return;@@ -1162,6 +1177,32 @@ public:return true;}+ // "Aw, Snap!" and "Page Unresponsive" leave no trace otherwise: Cra ships no crash+ // reporter. One line in chromium.log tells a report of a site that "keeps crashing"+ // apart: crashed, killed, out of memory or hung. Only the host: the log gets shared.+ void OnRenderProcessTerminated(CefRefPtr<CefBrowser> browser, TerminationStatus status, int error_code,+ const CefString& error_string) override {+ static const char* kStatus[] = {"abnormal termination", "killed", "crashed", "out of memory",+ "launch failed", "integrity failure"};+ const char* what = status >= 0 && status < TS_NUM_VALUES ? kStatus[status] : "unknown";+ LOG(ERROR) << "Cra: renderer for " << PageHost(browser) << " ended: " << what << " (code " << error_code+ << ", " << error_string.ToString() << ")";+ }++ bool OnRenderProcessUnresponsive(CefRefPtr<CefBrowser> browser,+ CefRefPtr<CefUnresponsiveProcessCallback> callback) override {+ LOG(ERROR) << "Cra: renderer for " << PageHost(browser) << " is unresponsive";+ return false; // Chrome's "Page Unresponsive" dialog+ }++ static std::string PageHost(CefRefPtr<CefBrowser> browser) {+ CefRefPtr<CefFrame> frame = browser->GetMainFrame();+ CefURLParts parts;+ if (!frame || !CefParseURL(frame->GetURL(), parts)) return "(no page)";+ std::string host = CefString(&parts.host).ToString();+ return host.empty() ? CefString(&parts.scheme).ToString() + ":" : host;+ }+// Context menu --------------------------------------------------------// Embedded pages (EmbeddedPages.swift): Chrome shows the menu through the views widget that@@ -1494,6 +1535,7 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {BOOL _isPopupHost;NSMutableSet<NSNumber*>* _activeDownloads;BOOL _parked;+ NSUInteger _audibleChanges;}- (instancetype)initWithFrame:(NSRect)frame url:(NSString*)url delegate:(id<CraBrowserDelegate>)delegate {@@ -1578,6 +1620,13 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {- (void)adoptBrowser:(CefRefPtr<CefBrowser>)browser {_browser = browser;self.isCreated = YES;+ // The page agent runs new-document scripts only while its domain is enabled.+ if (g_documentStartParams.count) [self sendDevToolsMethod:@"Page.enable" params:@"{}" completion:^(NSString*, NSString*) {}];+ for (NSString* params in g_documentStartParams)+ [self sendDevToolsMethod:@"Page.addScriptToEvaluateOnNewDocument" params:params+ completion:^(NSString*, NSString* error) {+ if (error) NSLog(@"Cra: document start script not installed: %@", error);+ }];if (_pendingFocus) {_pendingFocus = NO;browser->GetHost()->SetFocus(true);@@ -1701,6 +1750,25 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {- (void)stopFinding:(BOOL)clearSelection { if (_browser) _browser->GetHost()->StopFinding(clearSelection); }- (void)setAudioMuted:(BOOL)muted { if (_browser) _browser->GetHost()->SetAudioMuted(muted); }+// Chrome's RecentlyAudibleHelper: quiet only once the page stayed quiet for 2 s, so the+// gap between two tracks doesn't blink the speaker.+- (void)audibleChanged:(BOOL)audible {+ NSUInteger change = ++_audibleChanges;+ if (audible) { [self updateAudible:YES]; return; }+ __weak CraBrowser* weakSelf = self;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ CraBrowser* s = weakSelf;+ if (s && s->_audibleChanges == change) [s updateAudible:NO];+ });+}++- (void)updateAudible:(BOOL)audible {+ if (audible == self.isAudible) return;+ self.isAudible = audible;+ if ([self.delegate respondsToSelector:@selector(browser:didChangeAudible:)])+ [self.delegate browser:self didChangeAudible:audible];+}+// MARK: Picture in Picture//// Chromium only lets a page enter Picture in Picture while it holds a user@@ -1861,6 +1929,36 @@ static NSView* FindRenderWidgetHostView(NSView* root) {completion(nil, @"SendDevToolsMessage failed");}}+// The isolated world the document start script made: the main frame's id, then that world's+// execution context (createIsolatedWorld returns the existing world of that name), then evaluate.+- (void)evaluateInIsolatedWorld:(NSString*)world params:(NSString*)params+ completion:(void (^)(NSString* _Nullable, NSString* _Nullable))completion {+ __weak CraBrowser* weakSelf = self;+ id (^parse)(NSString*) = ^id(NSString* json) {+ return json ? [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil] : nil;+ };+ [self sendDevToolsMethod:@"Page.getFrameTree" params:@"{}" completion:^(NSString* tree, NSString* error) {+ NSString* frameID = [parse(tree) valueForKeyPath:@"frameTree.frame.id"];+ CraBrowser* s = weakSelf;+ if (!s || ![frameID isKindOfClass:NSString.class]) { completion(nil, error ?: @"no frame"); return; }+ NSData* body = [NSJSONSerialization dataWithJSONObject:@{@"frameId": frameID, @"worldName": world} options:0 error:nil];+ [s sendDevToolsMethod:@"Page.createIsolatedWorld" params:[[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding]+ completion:^(NSString* made, NSString* error) {+ NSNumber* context = [parse(made) valueForKey:@"executionContextId"];+ NSMutableDictionary* evaluate = [parse(params) mutableCopy];+ CraBrowser* s = weakSelf;+ if (!s || ![context isKindOfClass:NSNumber.class] || ![evaluate isKindOfClass:NSMutableDictionary.class]) {+ completion(nil, error ?: @"no isolated world");+ return;+ }+ evaluate[@"contextId"] = context;+ NSData* json = [NSJSONSerialization dataWithJSONObject:evaluate options:0 error:nil];+ [s sendDevToolsMethod:@"Runtime.evaluate" params:[[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding]+ completion:completion];+ }];+ }];+}+- (void)notifyMoveOrResizeStarted { if (_browser) _browser->GetHost()->NotifyMoveOrResizeStarted(); }- (void)close {@@ -1938,6 +2036,16 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {+ (void)setChromeHosting:(BOOL)enabled { g_chromeHosting = enabled; }+ (void)setOwnContextMenus:(BOOL)enabled { g_ownContextMenus = enabled; }++ (void)setDocumentStartScript:(NSString*)script isolatedScript:(NSString*)isolatedScript world:(NSString*)world {+ NSMutableArray<NSString*>* all = [NSMutableArray array];+ for (NSDictionary* params in @[@{@"source": script ?: @"", @"runImmediately": @YES},+ @{@"source": isolatedScript ?: @"", @"worldName": world ?: @"", @"runImmediately": @YES}]) {+ if (![params[@"source"] length]) continue;+ NSData* json = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];+ if (json) [all addObject:[[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding]];+ }+ g_documentStartParams = all;+}+ (BOOL)chromeHosting { return g_chromeHosting; }+ (void)setContentBlockingEnabled:(BOOL)enabled { cra_blocker::Enabled().store(enabled); }diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.hindex 08ac136..a21f03b 100644--- a/Sources/CraCEF/include/CraCEF.h+++ b/Sources/CraCEF/include/CraCEF.h@@ -81,6 +81,8 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {- (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;+/// The page started or stopped playing sound (see `isAudible`).+- (void)browser:(CraBrowser *)browser didChangeAudible:(BOOL)audible;/// Arc's Peek: a link the user clicked (`shiftClick` NO: before it navigates the page or/// opens as a target=_blank tab) or Shift-clicked (YES, instead of a new window). Return/// YES to show it in a Peek; the page then stays where it is.@@ -151,6 +153,9 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {@property (nonatomic, readonly) BOOL isPictureInPicturePlaying;/// The page is using the camera or microphone (Chromium's media access state).@property (nonatomic, readonly) BOOL isCapturingMedia;+/// The page is playing sound, in any frame (Chromium's audible state). Like Chrome's tab+/// speaker it stays YES for 2 s after the page goes quiet. Muting the tab doesn't change it.+@property (nonatomic, readonly) BOOL isAudible;/// 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).@@ -163,6 +168,10 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {- (void)probeBackgroundColor;/// Runs script in this browser's DevTools frontend, if open (debug aid behind cra://debug?devtoolsjs=).- (void)executeJavaScript:(NSString *)script inDevTools:(BOOL)inDevTools;+/// Runtime.evaluate (`params` without a context) in the main frame's isolated world `world`,+/// where the isolated document start script runs.+- (void)evaluateInIsolatedWorld:(NSString *)world params:(NSString *)params+ completion:(void (^)(NSString * _Nullable result, NSString * _Nullable error))completion;/// Chrome DevTools Protocol call on this browser's own session (no DevTools window)./// `params` is a JSON object string; the completion gets the result JSON or an error.- (void)sendDevToolsMethod:(NSString *)method params:(NSString *)params@@ -182,6 +191,10 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {+ (BOOL)chromeHosting;/// Page context menus are shown by Cra, not Chrome (pages embedded in their cards).+ (void)setOwnContextMenus:(BOOL)enabled;+/// Run in every frame of every page browser before the page's own scripts (and once in the+/// document already loaded): `script` in the page's world, `isolatedScript` in the isolated+/// world named `world` (invisible to the page). Set before browsers are created.++ (void)setDocumentStartScript:(NSString *)script isolatedScript:(NSString *)isolatedScript world:(NSString *)world;/// Third-party ad and tracker blocking: subresource and subframe requests whose host/// (or a parent domain) is on the blocked list are cancelled when they are third-party/// to the tab's top-level page. Main-frame navigations always load. Takes effect fordiff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swiftindex f1c7b75..f4b573a 100644--- a/Tests/BrowserManagerLifecycleTests.swift+++ b/Tests/BrowserManagerLifecycleTests.swift@@ -3,7 +3,8 @@ import CraCEF@mainenum BrowserManagerLifecycleTests {- private static let idleReply = #"{"result":{"value":true}}"#+ private static let idleReply = #"{"result":{"type":"string","value":""}}"#+ private static let isolatedProbe = "cra:Runtime.evaluate"private static var checks = 0@MainActor@@ -73,7 +74,11 @@ enum BrowserManagerLifecycleTests {manager.unload(rt.tabID)manager.ensureRuntime(for: rt.tabID)?.hiddenAt = Date.distantPast}- await sleepCase("an exception reply cannot authorize sleeping", reply: #"{"exceptionDetails":{},"result":{"value":true}}"#) { _, _ in }+ await sleepCase("an exception reply cannot authorize sleeping", reply: #"{"exceptionDetails":{},"result":{"value":""}}"#) { _, _ in }+ await sleepCase("a page holding typed text stays awake", reply: #"{"result":{"type":"string","value":"typed"}}"#) { _, _ in }+ await refusalBackoffCase()+ await beforeUnloadCase()+ nowPlayingCase()await sleepCase("malformed or missing replies cannot authorize sleeping", reply: nil) { _, _ in }print("Browser manager lifecycle: \(checks) checks passed")}@@ -152,14 +157,87 @@ enum BrowserManagerLifecycleTests {let runtime = manager.ensureRuntime(for: id)!runtime.hiddenAt = Date.distantPastmanager.sleepIdleTabs(hiddenLongerThan: 60)- expect(runtime.browser.replies.contains { $0.method == "Runtime.evaluate" }, "eligible page receives an asynchronous sleep probe")+ expect(runtime.browser.replies.contains { $0.method == isolatedProbe }, "eligible page receives an asynchronous sleep probe")mutate(manager, runtime)- runtime.browser.reply(to: "Runtime.evaluate", with: reply)+ runtime.browser.reply(to: isolatedProbe, with: reply)await drainMainQueue()+ // The page's own onbeforeunload is asked second, in the page's world.+ if runtime.browser.replies.contains(where: { $0.method == "Runtime.evaluate" }) {+ runtime.browser.reply(to: "Runtime.evaluate", with: idleReply)+ await drainMainQueue()+ }expect((manager.runtime(for: id) == nil) == shouldSleep, message)manager.closeAll()}+ /// A page that refused isn't probed again every minute, only after the back-off or once shown again.+ @MainActor+ private static func refusalBackoffCase() async {+ let store = SidebarStore()+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())+ let id = store.createTab(url: "https://example.test/typed").id+ let runtime = manager.ensureRuntime(for: id)!+ runtime.hiddenAt = Date.distantPast+ manager.sleepIdleTabs(hiddenLongerThan: 60)+ runtime.browser.reply(to: isolatedProbe, with: #"{"result":{"type":"string","value":"typed"}}"#)+ await drainMainQueue()+ manager.sleepIdleTabs(hiddenLongerThan: 60)+ expect(!runtime.browser.replies.contains { $0.method == isolatedProbe }, "a refused page is not probed again before the back-off")+ runtime.sleepProbeAfter = Date.distantPast+ manager.sleepIdleTabs(hiddenLongerThan: 60)+ expect(runtime.browser.replies.contains { $0.method == isolatedProbe }, "a refused page is probed again after the back-off")+ manager.closeAll()+ }++ /// The page's own onbeforeunload, asked in its world after the isolated probe, keeps it awake.+ @MainActor+ private static func beforeUnloadCase() async {+ let store = SidebarStore()+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())+ let id = store.createTab(url: "https://example.test/editor").id+ let runtime = manager.ensureRuntime(for: id)!+ runtime.hiddenAt = Date.distantPast+ manager.sleepIdleTabs(hiddenLongerThan: 60)+ runtime.browser.reply(to: isolatedProbe, with: idleReply)+ await drainMainQueue()+ runtime.browser.reply(to: "Runtime.evaluate", with: #"{"result":{"type":"string","value":"beforeunload"}}"#)+ await drainMainQueue()+ expect(manager.runtime(for: id) != nil, "a page with its own onbeforeunload stays awake")+ manager.closeAll()+ }++ /// The sidebar player lists pages that played sound, keeps paused ones, hides the one on+ /// screen, and drops a page that navigates while quiet or closes.+ @MainActor+ private static func nowPlayingCase() {+ let store = SidebarStore()+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())+ let np = NowPlaying()+ manager.nowPlaying = np+ let a = store.createTab(url: "https://example.test/a").id, b = store.createTab(url: "https://example.test/b").id+ let ra = manager.ensureRuntime(for: a)!, rb = manager.ensureRuntime(for: b)!+ ra.browser.isAudible = true+ manager.browser(ra.browser, didChangeAudible: true)+ expect(np.entries.map(\.id) == [a] && np.entries[0].playing, "a page that starts playing gets a card")+ manager.show(a, focus: false)+ expect(np.shown.isEmpty, "the card of the page on screen is hidden")+ manager.show(b, focus: false)+ expect(np.shown.map(\.id) == [a], "leaving the page shows its card")+ ra.browser.isAudible = false+ manager.browser(ra.browser, didChangeAudible: false)+ expect(np.entries.first?.playing == false, "a paused page keeps its card, marked paused")+ rb.browser.isAudible = true+ manager.browser(rb.browser, didChangeAudible: true)+ expect(np.entries.map(\.id) == [a, b], "cards stack oldest first")+ ra.browser.navigate(to: "https://example.test/elsewhere")+ expect(np.entries.map(\.id) == [b], "a quiet page that navigates leaves the player")+ rb.browser.navigate(to: "https://example.test/next-track")+ expect(np.entries.map(\.id) == [b], "a playing page that navigates (a playlist) keeps its card")+ manager.unload(b)+ expect(np.entries.isEmpty, "closing the page removes its card")+ manager.closeAll()+ }+@MainActorprivate static func drainMainQueue() async {await withCheckedContinuation { continuation in DispatchQueue.main.async { continuation.resume() } }diff --git a/Tests/BrowserManagerSupport/CraCEF.swift b/Tests/BrowserManagerSupport/CraCEF.swiftindex 3d71a60..598d72b 100644--- a/Tests/BrowserManagerSupport/CraCEF.swift+++ b/Tests/BrowserManagerSupport/CraCEF.swift@@ -24,6 +24,7 @@ public final class CraBrowser {public var isInPictureInPicture = falsepublic var isPictureInPicturePlaying = falsepublic var isCapturingMedia = false+ public var isAudible = falsepublic var hasDevTools = falsepublic var closedByPage = falsepublic let isIncognito: Bool@@ -53,6 +54,10 @@ public final class CraBrowser {public func sendDevToolsMethod(_ method: String, params: String, completion: @escaping (String?, String?) -> Void) {replies.append((method, completion))}+ /// Recorded as "<world>:Runtime.evaluate".+ public func evaluate(inIsolatedWorld world: String, params: String, completion: @escaping (String?, String?) -> Void) {+ replies.append(("\(world):Runtime.evaluate", completion))+ }public func reply(to method: String, with result: String?) {guard let index = replies.firstIndex(where: { $0.method == method }) else { fatalError("No pending \(method)") }replies.remove(at: index).completion(result, nil)diff --git a/Tests/FloatingSidebarTests.swift b/Tests/FloatingSidebarTests.swiftindex 14b9cc4..9d276c4 100644--- a/Tests/FloatingSidebarTests.swift+++ b/Tests/FloatingSidebarTests.swift@@ -30,6 +30,24 @@ enum FloatingSidebarTests {"an old hide completion must not remove a newly revealed panel")expect(shell.sidebarHost.window === panel, "the revealed sidebar retains its native panel owner")+ // The floating sidebar's edge drags the width through the shell's handle.+ var saved: CGFloat?+ shell.resizeHandle.onDrag = { shell.sidebarWidth += $0 }+ shell.resizeHandle.onEnd = { saved = shell.sidebarWidth }+ let edge = shell.sidebarHost.superview?.subviews.compactMap { $0 as? ResizeHandleView }.first+ expect(edge.map { !$0.isHidden && abs($0.frame.maxX - shell.sidebarHost.frame.maxX) < 0.5 } == true,+ "the floating sidebar has a resize strip on its right edge")+ let panelWidth = panel.frame.width+ edge?.onDrag?(40)+ edge?.onEnd?()+ expect(shell.sidebarWidth == 368 && saved == 368, "dragging the floating edge resizes and saves the width")+ expect(panel.frame.width == panelWidth + 40 && shell.sidebarHost.frame.width == 368+ && abs(edge!.frame.maxX - shell.sidebarHost.frame.maxX) < 0.5,+ "the panel, sidebar and strip follow the new width")+ edge?.onDrag?(-40)+ shell.resizeHandle.onDrag = nil+ shell.resizeHandle.onEnd = nil+// Multiple animation completions can be queued; only the latest show owns it.sidebar.hide(animated: true)sidebar.show()@@ -134,10 +152,16 @@ final class CraTuning {let liftActive: CGFloat = 0.1}+final class ResizeHandleView: NSView {+ var onDrag: ((CGFloat) -> Void)?+ var onEnd: (() -> Void)?+}+final class ShellView: NSView {let sidebarHost = NSView()- let resizeHandle = NSView()+ let resizeHandle = ResizeHandleView()var sidebarWidth: CGFloat = 328+ var sidebarResizable = truevar contentFullscreen = falsevar edgeToEdge = falsevar sidebarDetached = falsediff --git a/Tests/test-browser-manager.sh b/Tests/test-browser-manager.shindex d72ae25..dfa4522 100644--- a/Tests/test-browser-manager.sh+++ b/Tests/test-browser-manager.sh@@ -10,6 +10,6 @@ xcrun swiftc -swift-version 5 -emit-module -emit-library -module-name CraCEF \-emit-module-path "$TEST_DIR/CraCEF.swiftmodule"xcrun swiftc -swift-version 5 -parse-as-library -I "$TEST_DIR" -L "$TEST_DIR" -lCraCEF \-Xlinker -rpath -Xlinker "$TEST_DIR" \- "$MANAGER_SOURCE" Tests/BrowserManagerSupport/AppServices.swift \+ "$MANAGER_SOURCE" Sources/Cra/Services/NowPlaying.swift Sources/Cra/Services/PageScript.swift Tests/BrowserManagerSupport/AppServices.swift \Tests/BrowserManagerLifecycleTests.swift -o "$TEST_DIR/lifecycle-tests""$TEST_DIR/lifecycle-tests"diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.mdindex 4475a66..ea7a819 100644--- a/docs/arc-reverse-engineering.md+++ b/docs/arc-reverse-engineering.md@@ -670,9 +670,26 @@ Observed live on a throwaway Today split (example.com | example.org), archived a### One space (Arc 1.171, static)- [O strings] Defaults key `showSpaceHeaderOnSingleUnnamedSpaces` (+ `…DidChange` action); the space contextmenu has "Show Space Header" / "Hide Space Header" ("Menu item to toggle space header visibility").- Not observed live: it needs a one-space Arc, and rewriting StorableSidebar.json risks syncing deleted spaces.Cra: Hide Space Header on the header's menu with one space, Show Space Header on the list's menu, andSettings ▸ Tabs ▸ "Show the space header with only one space"; hidden also drops the dock's lone icon.+- [O] One-space Arc, run live 31 Oct without risking sync: `CFFIXED_USER_HOME=<fake home>` with a trimmed+ StorableSidebar.json (one untitled space, nothing pinned) plus the Storable{AuthState,FeatureFlags,+ EducationState,MembershipCard,DefaultBrowserPrompts,KeyBindings}.json copies, launched as+ `sandbox-exec` (deny network-outbound ip/tcp/udp) `…/MacOS/Arc --no-sandbox`. Without `--no-sandbox` the+ GPU process dies (nested seatbelt) and Arc never orders its windows in. Traps: cfprefsd ignores the fake+ home, so the copy writes the REAL company.thebrowser.Browser domain (back it up, restore after); `open -a+ Arc` while the copy runs launches the real Arc; File ▸ New Window over AX opens a window.+ "Unnamed" means no title AND no icon: a space with an emoji shows "Space 1" and keeps its header,+ however the defaults key is set. Drop `customInfo.iconType` too and Arc hides the header by itself.+ `topBarURLEnabled` (real domain) puts the URL field in the sidebar; the favorites card closes over AX+ (`sidebarFavoritesEmptyStateDismissButton`, writes `topAppsEmptyStateDismissedForProfiles`).+- [O] Measured (2x px, URL field in the sidebar, 31 Oct). Everything under the favorites is placed from the+ tiles' bottom, or with none from the URL field's; the favorites block (8 pt gap + tiles) takes no room+ when empty. Divider line below that point: header shown 54.5 pt; hidden 15.5 pt (no favorites) or+ 18.5 pt (favorites). Header cap tops 21.5 pt below it either way. Every pinned row takes 41 pt, the+ first one too; nothing pinned takes none. Line → first Today row 11.5 pt. Cra matches all eight+ combinations of header × pinned × favorites to the pixel (SpaceColumnView.place, SpaceListView.layoutRows).+ Left: Arc's header title sits ~1 pt lower and reads slightly larger than Cra's.### DevTools docking, Arc's way (25 Oct)@@ -1628,8 +1645,13 @@ GitHub issue #4: opening in window B a tab that window A shows left A with no ta- [O live] Favorites columns by sidebar width (4 favorites; `sidebarWidth` set in StorableWindows.json with Arcquit, tile frames read from the AX list under `sidebarFavoritesCollectionView`): 347/300/260/230 → 4 columns(tiles 76/…/55/47 × 47), 227/225/220/212/205/200/170/140 → 2 columns (101/100/98/94/90/88/73/58), 100 → 1- (84). Rule: 4 columns while a tile is at least 47 pt wide (as wide as tall), else 2, else 1; 8 pt margins and- gaps. Never 3 (at 200 three 56 pt tiles would fit). Cra: `FavoritesGridView.columns(forWidth:)`.+ (84). That rule ("4, else 2, else 1, never 3") only held for exactly 4 favorites.+- [O live, Arc 1.171, 31 Oct] 1–9 favorites at widths 347/230/200/140/100 (offline copy, AX frames). Widest =+ the most columns up to 4 keeping a tile ≥ 47 pt (3 at 200, 2 at 140, 1 at 100); then the fewest columns+ that need no more rows: 1 → one full-width tile, 2 → halves, 3 → thirds, 5 → 3 + 2, 6 → 3 × 2, 7 → 4 + 3,+ 9 → 3 × 3; 4 at 200 → 2 × 2. A short last row keeps the tile width, left-aligned. Tile x is rounded to the+ half point (84.75 → 85, 254.25 → 254.5); widths are not. Cra (`FavoritesGridView.columns(forWidth:)`)+ matches all 41 measured cases exactly.- [O static] Peek is a Little Arc presented modally (`littleWindowViewController`, `presentModally`,`modalState`, `peekedModalControlsAlternateOrderEnabled`). Links ▸ "Open a Peek window when clicking on links toother sites" (note: "This only affects Favorites and Pinned tabs"; key `modalEnabled`) and "Open a Peek window@@ -1639,3 +1661,116 @@ GitHub issue #4: opening in window B a tab that window A shows left A with no tathat closes it on click, Escape the page didn't use closes it, "Open in <space>" makes it a tab. Same site =registrable domain (`SiteKey`). Verified on a test bundle with a CDP click in a favorite: Peek opened, the tabstayed, promote and ⌘W worked.++### Splits in Favorites (Arc 1.171, 31 Oct 2026, Swift metadata + offline Arc)+Request from a Cra user (DM, 31 Oct): "the split tabs being pinned, I also need them pinned at the top".+- [O static] A top-apps item can be a split: `AppTray…ViewState.AppItem { childItems: OrderedDictionary<id,+ ChildItem { defaultIconType, highFidelityIconMatchingURL }>, layoutOrientation: horizontal|vertical, isSelected,+ isHighlighted, … }`, drawn by `AppTrayItemViewAppKit` with one `AppTrayChildItemView` per pane (own isHovered /+ isSelected / subtitle / badge) and cut by `AppTrayItemMaskShape { numberOfItems, cornerRadius, lineWidth,+ isReversed, layoutOrientation }`; per-cell rects with their own rounded corners (`AppTrayItemLayout.ItemLayout`).+- [O live] Offline Arc (fake home, see "One space") with a horizontal and a vertical split in StorableSidebar's+ topApps container (`splitView` items, children = panes): one tile per split, the same size as a page's tile,+ cut by a 2 pt gap (4 px at 2x) along the split's axis — side by side, or stacked for a vertical split. Outer+ corners stay rounded, the cut's corners are square. Hover darkens the whole tile, not one cell. Clicking a cell+ opens the split; the open split's tile is ONE selected tile with no cut (uniform 240/239/232 on a light theme).+- Cra: favorites hold splits (`SidebarStore.addToFavorites` lifts a pane to its split, `removeFromFavorites` too),+ `FavoriteTileModel.cells` + `FavoriteTileMetrics.cut` (an even-odd mask, dropped while the split is open), a+ click opens the split on the pressed pane, the tooltip names the hovered pane, the menu is the split row's with+ "Remove from Favorites" first. Not seen in Arc: the open split's icons (offline Arc had no favicons).++### Folder previews (Arc 1.171, 31 Oct 2026, Swift metadata + offline Arc, 120 fps recordings)+- [O static] `Previews.FolderPreviewState { itemID, title, allPossibleChildren: [FolderPreviewItem] }`,+ `FolderPreviewItem { sidebarItem, title, url, faviconType, lastVisitDate, isBadged }`,+ `Arc.FolderPreviewView { searchQuery, selectedItemID, contentViewHeight }` in an in-window+ `FolderPreviewHostView` with an event monitor; `FolderPreviewAction = onSelectChildItem(index, resultsCount,+ modifiers, searchQuery) | contextMenu(copyURL, openInSplitView, duplicate, archive) | onAppear | onEscape |+ onLeftMouseDownOutOfFrame`. Shown by `SidebarPreviewHoverTracker` (`showPreviewTask`); settings key+ `folderPreviewEnabled`, one of the "Show Arc Previews:" toggles ("Hover your mouse over an Arc Folder, Pinned,+ or Favorited tab…").+- [O live] Only a CLOSED folder previews (an open one shows nothing). Rows = every tab under it, nested folders+ included, newest `lastVisitDate` first, subtitle "31 minutes ago" / "15 hours ago" / "1 week ago" / "1 month+ ago"; the first row is highlighted and the field already has the caret ("Search Tools…"). Typing filters+ (title/URL), the panel keeps its height; nothing found: "No tabs matching that search 🤔", 13 pt, centred,+ wrapped so the emoji takes a second line. Escape closes. The pointer's row gets the same fill as the+ keyboard's row, both at once (hover doesn't move the selection). Moving onto another folder switches.+- [O live] Timing: the folder row turns hovered, the preview starts 0.45 s later and is in after ~90 ms (opacity+ plus scale from ~0.85 about the middle of its left edge); leaving folder and preview fades it out within+ ~40 ms over ~80 ms.+- [O live] Geometry (2x captures, sidebar 300): 240 pt wide, 4 pt right of the sidebar, centred on the folder+ row and kept 18 pt inside the window (so a folder near the top gets a preview at y 18); height+ 53 + 45 × rows, at most 320 (6+ rows scroll; one row = 98). 10 pt corners, 0.5 pt grey (~58) outline and a 0.5 pt+ white-20 % line inside it. Search area 48 pt (11.5 pt magnifier centred 20 pt in, 13 pt text from x 36,+ placeholder white ~58 %), 1 pt white-13 % hairline, rows from 4 pt below it on a 45 pt pitch, fill 44 pt tall,+ 4 pt in from each side, 4 pt corners, white ~7.5 %; 16 pt favicon centred 20 pt in, title 13 pt regular+ (white ~85 %) and age 11 pt (white ~55 %) from x 36. Always dark, whatever the space theme: a blur that lets+ ~12 % of the backdrop through (23/23/23 over a dark page, 45/44/36 over a light yellow one) — a page icon+ under it did not show through.+- Cra: `UI/Sidebar/FolderPreview.swift` (a child panel, since pages are CEF child windows; hudWindow dark ++ rgb 17 @ 77 % over it), hooked from `SpaceListView.hoverAt`, Settings ▸ Tabs "Preview a folder’s tabs when+ hovering over it" (`AppSettings.folderPreviews`), a floating sidebar stays out while it is up, and+ `cra://debug?folderPreview=<folder id>` opens it for screenshots. Text widths, baselines, hairline and+ magnifier match Arc's to the pixel at 2x. Left as Cra's choice: typing or arrowing keeps it open after the+ pointer leaves (not observed in Arc); picking a tab in a closed folder leaves the folder closed without+ showing the tab under it (Arc keeps a closed folder's open tab visible; Cra's 29 Oct work on that isn't on main).++## Solid themes, list scroller, now playing, many spaces (Arc 1.171, 31 Oct 2026, offline Arc, issues #28 #30–#33)++Offline Arc as in "One space", with these extra traps: Arc wipes a hand-built StorableSidebar.json (first-run+"Space 1") when there is no StorableWindows.json, or when `firebaseSyncState.syncHealthStatus` is `healthy`+(it syncs and empties the spaces); reuse the sync states from a file Arc itself wrote offline (`notWorking`).+Arc's menus are disabled while it is in the background: activate it by pid (`open -a` starts the real Arc).+Theme palettes in a hand-built space can be borrowed; only the `background` style was measured.++**Captures on the built-in display are Display P3.** A solid sRGB colour reads back P3-encoded (cyan #33B2CC →+~#5BB0C9), so convert before comparing with sRGB colours; compare Cra and Arc through the same pipeline.++- [O] Solid colour (`blendedSingleColor`): flat, the same with `isVibrant` true or false and with light or dark+ `contentOverBackgroundAppearance`. Over solid white and black backdrops, nine colours, in sRGB: active =+ α·colour + (1 − α)·(66 + 0.52·backdrop), inactive = α·colour + (1 − α)·212 (flat), α = 0.19 + 0.55·intensity+ (0.191 / 0.459 / 0.742 at 0 / 0.5 / 1), within 3/255. Cra (`SpaceTheme.solid`, `ShellView.solidBackdrop`: dim+ 0.30, lift 0.26; inactive dim 1, lift 0.83) matches all 22 test spaces within 2/255 over both backdrops, except+ intensity 0 over white (19/255 light). A space with no `windowTheme` is Arc's default dark purple; the import+ uses Ink instead of the next preset.+- [O] Tab list scroller: AppKit overlay scroller (AXScrollBar, 17 pt track) shown while scrolling, then faded;+ the knob is 4 pt wide, 3 pt in from the sidebar edge, white 49 % on a dark theme, no track. Cra:+ `SidebarScroller`, 10 pt wide so it stays in the gutter right of the rows (knob on Arc's exact columns).+- [O] Playing tab row: `speaker.wave.3` between favicon and title (17.5 pt wide, 11.5 tall, title 8 pt after+ it), white ~60 % on a dark theme (the glyph tone, not the title's colour).+- [S] Now playing is Arc's `MediaControlsFeature` (ArcCore-free, in the Arc executable): SwiftUI `MiniPlayerView`s in+ a `MediaControlsHostingView`, fed by Chromium's media session (`webContents:didChangeMediaSessionState:`). Swift+ field metadata: `MiniPlayerFeature.State` {title, icon {image, tintColor}, volume: Double, isTabMuted,+ isBackToPIPButtonEnabled, tabURL, isVolumeExpanded, mediaType = audioVideo {mediaSessionStatus, hasNextTrack,+ hasPreviousTrack} | recording {canToggleMicrophone/Camera, isMicrophoneOn/CameraOn}}; view actions setVolume,+ setIsPaused, toggleVolumeDrawer, backToTabClicked, titleRowClicked, controlsRowClicked, playNext/PreviousTrack,+ closeButtonClicked, toggleMuted, toggleCamera/Microphone, backToPipClicked; `MediaControlsData.maxActiveMediaControls`;+ per-card view state {height, opacity, yOffset, widthOffset}; `MiniPlayerView` reads colorPalette + colorScheme;+ marquee titles behind `miniPlayerMarqueeTitleEnabled`. Asset catalog `ARC_MediaControlsFeature.bundle`: one colour,+ `PlaybackControlForeground` = black 50 % (light) / white 66 % (dark). Long strings: "Close Mini Player", "Open+ Picture in Picture", "Adjust Tab Volume", "Toggle Microphone"; symbols backward/forward.end.fill,+ speaker.wave.3.fill / speaker.wave.1.fill, video.slash.fill (short ones are inline, read live instead).+- [O] Now playing, live: a card appears for an audio tab once it is off screen (a video in Picture in Picture has+ none). Cards 8 pt in, bottom where the list ends (50 pt above the window bottom), 6 pt corners, filled with the+ palette's `backgroundExtra` for the space's scheme: dark = 15 % of `shadedDark` (#110D00 for #6F5600), light =+ near-white (#FEFDFC); title white ~81 % / black ~85 %; disabled glyphs a third of the foreground; hover square+ 24 × 23 pt, white 7 % / black 8 %; favicon placeholder foreground ~15 %. Rest: newest card only, 33 pt: favicon,+ previous, play/pause, next, volume, laid out like an HStack (glyphs 16 / 13 / 8.5 / 13 / 19 pt, equal gaps,+ 14 pt in on the left, 12.5 on the right); up to two more peek out, each 7 pt higher, 5 pt narrower a side and+ 0.2 fainter, the second showing the tops of its controls at ~15 % (raised 7.25 pt). Hover: all cards 65.5 pt,+ title row (tab title, 13 pt, 14.5 pt in, centred 16.25 pt from the top; Picture in Picture glyph 15.5 pt wide+ centred 45.5 pt from the right on video tabs; ✕ 11 pt centred 21.75 pt from the right), stacked upward 5 pt+ apart, oldest on top, ~0.2 s ease-out both ways (collapse starts at once). Tooltips: "Back to Tab", "Previous+ Track", "Pause"/"Play", "Next Track", "Adjust Tab Volume", "Open Picture in Picture", "Close Mini Player";+ disabled previous/next (no media session handler) have neither tooltip nor hover; the title row has neither.+ Volume opens a drawer: the card grows 33 pt (bottom fixed) with a slider centred 16.25 pt from the bottom: 6 pt+ rounded track 8 pt in, filled = palette tintedLight (dark) / shadedDark (light), empty = white 10 % / black 18 %,+ knob 20 × 16 pt pill, #DBDBD9 (dark) / white with a soft shadow (light); the volume button stays lit; the glyph+ shows 3 waves, 1 wave (seen at 27 % and 45 %), none at 0. Pause keeps the card (▶); ✕ removes it. Cra:+ `NowPlaying` + `NowPlayingTrayView` (verified side by side in both schemes, glyph boxes within 1 px); controls+ run the page's media session handlers (captured by `PageScript`) or its media elements; volume sets the page's+ media volume. Not built: the recording card (mic/camera) and marquee titles.+- [O] Space dock with many spaces (5, 7, 8, 12, 16, 22 spaces): cells share the 217 pt between Library and ++ (300 pt sidebar) in half points, at most 34; below 22 pt the open space keeps 22 and the others split the+ rest (17.5 / 13 / 9 pt with 12 / 16 / 22 spaces); icon-less spaces are dots, small when squeezed. Cra+ (`SpaceDockView.cellWidths`) follows the widths and shrinks emoji in narrow cells; it has no icon-less spaces+ yet (imported ones get 🗂️).diff --git a/scripts/cef-patches/audible-state.patch b/scripts/cef-patches/audible-state.patchnew file mode 100644index 0000000..6008518--- /dev/null+++ b/scripts/cef-patches/audible-state.patch@@ -0,0 +1,38 @@+diff --git a/cef/libcef/browser/browser_contents_delegate.cc b/cef/libcef/browser/browser_contents_delegate.cc+index 72dd7c5..15d995a 100644+--- a/cef/libcef/browser/browser_contents_delegate.cc++++ b/cef/libcef/browser/browser_contents_delegate.cc+@@ -613,6 +613,21 @@ void CefBrowserContentsDelegate::DidFinishLoad(+ OnLoadEnd(frame, validated_url, http_status_code);+ }+++// Cra: Chromium's audible state (Chrome's tab speaker icon), which CEF has no++// callback for. Delivered as a "Cra.audible" message from PID_BROWSER whose++// only argument is the new state.++void CefBrowserContentsDelegate::OnAudioStateChanged(bool audible) {++ auto c = client();++ auto b = browser();++ if (!c || !b) {++ return;++ }++ CefRefPtr<CefProcessMessage> message =++ CefProcessMessage::Create("Cra.audible");++ message->GetArgumentList()->SetBool(0, audible);++ c->OnProcessMessageReceived(b, b->GetMainFrame(), PID_BROWSER, message);++}+++ void CefBrowserContentsDelegate::TitleWasSet(content::NavigationEntry* entry) {+ // |entry| may be NULL if a popup is created via window.open and never+ // navigated.+diff --git a/cef/libcef/browser/browser_contents_delegate.h b/cef/libcef/browser/browser_contents_delegate.h+index ae50fee..3b7515e 100644+--- a/cef/libcef/browser/browser_contents_delegate.h++++ b/cef/libcef/browser/browser_contents_delegate.h+@@ -134,6 +134,7 @@ class CefBrowserContentsDelegate : public content::WebContentsDelegate,+ void PrimaryMainDocumentElementAvailable() override;+ void LoadProgressChanged(double progress) override;+ void DidStopLoading() override;++ void OnAudioStateChanged(bool audible) override;+ void DidFinishNavigation(+ content::NavigationHandle* navigation_handle) override;+ void DidFailLoad(content::RenderFrameHost* render_frame_host,diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.shindex 65218b2..c96fabc 100755--- a/scripts/fetch-cef.sh+++ b/scripts/fetch-cef.sh@@ -9,11 +9,11 @@set -euo pipefailcd "$(dirname "$0")/.."-CEF_VERSION="${CEF_VERSION:-156.0.14+g4fa4ab5+chromium-156.0.8078.48}"+CEF_VERSION="${CEF_VERSION:-156.0.15+gcf671c0+chromium-156.0.8078.80}"ARCH="${CEF_ARCH:-macosarm64}"NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"# Bump the suffix (codecs2, …) when the build changes but CEF_VERSION does not.-CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs4}"+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs1}"URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"mkdir -p vendor