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.20: Peek, Site Search, favorites grid, instant extension popups
Victordf28d1a0d911
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex 188ff5d..a1ddbb0 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -393,6 +393,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {return w}+ /// Arc's Peek: a Little Window over `parent` that closes when a click lands past it.+ func openPeek(url: String, over parent: MainWindowController) {+ for p in littleWindows where p.peekParent === parent { p.closeWindow() }+ let w = LittleWindowController(app: self, url: url, peekOver: parent)+ littleWindows.append(w)+ w.showAsPeek()+ }+func removeLittleWindow(_ w: LittleWindowController) {littleWindows.removeAll { $0 === w }}@@ -420,9 +428,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {/// cra://commandbar?query=…&mode=edit, cra://action/<id>, cra://open?url=…,/// cra://dismiss.- /// Arc marks a tab chosen from the keyboard with its yellow/black focus ring.- private func markKeyboardFocus() { main.sidebarUI.keyboardFocusID = store.selectedTabID }-func handleInternalURL(_ u: URL) {let comps = URLComponents(url: u, resolvingAgainstBaseURL: false)func q(_ name: String) -> String? { comps?.queryItems?.first { $0.name == name }?.value }@@ -526,7 +531,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {return}if let method = dict["cdp"] {- main.currentBrowser?.sendDevToolsMethod(method, params: dict["params"] ?? "{}") { result, error in+ // target=little: the newest Little Window's (or Peek's) page.+ let b = dict["target"] == "little" ? littleWindows.last?.browser : main.currentBrowser+ b?.sendDevToolsMethod(method, params: dict["params"] ?? "{}") { result, error inNSLog("Cra cdp %@ → %@", method, result ?? "error: \(error ?? "?")")}return@@ -762,8 +769,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {}case "clearToday": store.clearToday()case "pictureInPicture": main.currentBrowser?.requestPictureInPicture(automatic: false)- case "nextTab": main.cycleTab(1); markKeyboardFocus()- case "previousTab": main.cycleTab(-1); markKeyboardFocus()+ case "nextTab": main.cycleTab(1)+ case "previousTab": main.cycleTab(-1)case "recentTab": main.cycleRecentTabs(1, event: NSApp.currentEvent)case "recentTabBackward": main.cycleRecentTabs(-1, event: NSApp.currentEvent)case "nextSpace": store.focusSpace(offset: 1)@@ -780,7 +787,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {default:if id.hasPrefix("item"), let n = Int(id.dropFirst(4)) {let tabs = store.visibleTabs(in: store.focusedSpaceID)- if n - 1 < tabs.count { store.selectTab(tabs[n - 1].id); markKeyboardFocus() }+ if n - 1 < tabs.count { store.selectTab(tabs[n - 1].id) }} else if id.hasPrefix("space"), let n = Int(id.dropFirst(5)) {if n - 1 < store.spaceOrder.count { store.focusSpace(store.spaceOrder[n - 1]) }}diff --git a/Sources/Cra/Model/LinkRouting.swift b/Sources/Cra/Model/LinkRouting.swiftindex 9db112b..f19b4df 100644--- a/Sources/Cra/Model/LinkRouting.swift+++ b/Sources/Cra/Model/LinkRouting.swift@@ -70,3 +70,20 @@ extension AppSettings {linkRoutes.first { $0.matches(url) }?.destination ?? defaultLinkDestination}}++/// Arc's Peek opens links "to other sites": the registrable domain differs, so a link from+/// mail.google.com to accounts.google.com stays in the tab. Cra has no public suffix list;+/// a generic second-level label under a country code (co.uk, com.au) counts as suffix.+enum SiteKey {+ private static let secondLevel: Set<Substring> = ["co", "com", "net", "org", "gov", "edu", "ac", "ne", "or", "go", "gv"]++ static func site(of url: String) -> String? {+ guard let u = URL(string: url), let scheme = u.scheme?.lowercased(), scheme == "http" || scheme == "https",+ let host = u.host?.lowercased(), !host.isEmpty else { return nil }+ let labels = host.split(separator: ".")+ if labels.count <= 2 || host.allSatisfy({ $0.isNumber || $0 == "." }) || host.contains(":") { return host }+ let n = labels.count+ let keep = labels[n - 1].count == 2 && secondLevel.contains(labels[n - 2]) ? 3 : 2+ return labels.suffix(keep).joined(separator: ".")+ }+}diff --git a/Sources/Cra/Model/SidebarModel.swift b/Sources/Cra/Model/SidebarModel.swiftindex 9e731c6..67a5b04 100644--- a/Sources/Cra/Model/SidebarModel.swift+++ b/Sources/Cra/Model/SidebarModel.swift@@ -433,6 +433,12 @@ struct AppSettings: Codable, Equatable {/// Air Traffic Control routes, checked in order (LinkRouting.swift). Starts with Arc's/// Google Meet route.var linkRoutes: [LinkRoute] = [.googleMeet]+ /// 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+ /// Arc's "Open a Peek window when clicking on links with Shift held"+ /// (shiftClickModalEntryPointEnabled).+ var peekOnShiftClick: 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@@ -549,6 +555,8 @@ 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+ peekOnShiftClick = try c.decodeIfPresent(Bool.self, forKey: .peekOnShiftClick) ?? 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 ed606d9..b6a3f86 100644--- a/Sources/Cra/Services/BrowserManager.swift+++ b/Sources/Cra/Services/BrowserManager.swift@@ -50,6 +50,9 @@ protocol BrowserManagerDelegate: AnyObject {func browserManagerFocusedBrowser(_ tabID: UUID)/// The page closed itself (window.close()).func browserManagerPageClosedTab(_ tabID: UUID)+ /// Arc's Peek: a link the user clicked (or Shift-clicked) in `tabID`, whose page is at+ /// `pageURL`. Return true when it opens in a Peek instead.+ func browserManagerOpensPeek(url: String, fromTab tabID: UUID, pageURL: String, shiftClick: Bool) -> Bool}/// Creates, shows, hides and tears down CEF browsers inside a container view.@@ -529,6 +532,11 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {return host}+ func browser(_ browser: CraBrowser, opensPeekForURL url: String, shiftClick: Bool) -> Bool {+ guard let id = tabID(of: browser), !browser.isIncognito else { return false }+ return delegate?.browserManagerOpensPeek(url: url, fromTab: id, pageURL: browser.currentURL, shiftClick: shiftClick) ?? false+ }+func devToolsHostView(for browser: CraBrowser) -> NSView? {guard let id = tabID(of: browser) else { return nil }return delegate?.browserManagerDevToolsHost(for: id)diff --git a/Sources/Cra/Services/ExtensionActions.swift b/Sources/Cra/Services/ExtensionActions.swiftindex 91d9f7d..4eafc9b 100644--- a/Sources/Cra/Services/ExtensionActions.swift+++ b/Sources/Cra/Services/ExtensionActions.swift@@ -50,7 +50,7 @@ final class ExtensionActions {HitchMonitor.mark("extension request \(extensionID)")do {let tab = try await tabTarget(for: browser)- let before = visibleWindows()+ let before = WindowSnapshot()placingOwnPopup = truetriggered = trueHitchMonitor.mark("extension trigger \(extensionID)")@@ -70,40 +70,75 @@ final class ExtensionActions {// MARK: Popup placement- /// Chrome creates the popup's window hidden, sometimes before the popup page exists, so- /// "new" means newly visible.- private func visibleWindows() -> Set<ObjectIdentifier> {- Set(NSApp.windows.filter(\.isVisible).map(ObjectIdentifier.init))+ /// The windows before a popup: Chrome creates the popup's window hidden, sometimes before+ /// the popup page exists, so "new" means newly visible.+ @MainActor private struct WindowSnapshot {+ let visible = Set(NSApp.windows.filter(\.isVisible).map(ObjectIdentifier.init))+ let all = Set(NSApp.windows.map(ObjectIdentifier.init))}+ /// New bubbles kept transparent until they are framed.+ private let hiddenBubbles = NSHashTable<NSWindow>.weakObjects()+/// Chrome shows the popup once its page has loaded; watch for the new window and frame it- /// under the anchor (ExtensionPopupWindow, Arc's BrowserExtensionWindow).- private func placePopup(appearingAfter before: Set<ObjectIdentifier>, anchor: NSPoint, sourceHost: NSWindow? = nil, attempt: Int = 0) {+ /// under the anchor (ExtensionPopupWindow, Arc's BrowserExtensionWindow). Checked every+ /// frame: Chrome first shows it under its hidden toolbar, so a bubble created after+ /// `before` stays transparent until it is in the frame.+ private func placePopup(appearingAfter before: WindowSnapshot, anchor: NSPoint, sourceHost: NSWindow? = nil,+ deadline: Date = Date().addingTimeInterval(3), shownAt: Date? = nil) {+ for w in NSApp.windows where !before.all.contains(ObjectIdentifier(w)) && w.alphaValue == 1+ && ExtensionPopupCandidate.mayBecomePopup(w) {+ w.alphaValue = 0+ hiddenBubbles.add(w)+ }// Sharing badges and tooltips can also become visible during startup. A popup// must belong to a Chromium page in the browser containing the resolved anchor.- if let popup = NSApp.windows.first(where: { candidate in- guard !before.contains(ObjectIdentifier(candidate)),+ let popup = NSApp.windows.first(where: { candidate in+ guard !before.visible.contains(ObjectIdentifier(candidate)),let owner = sourceHost?.parent ?? candidate.parent?.parent,owner.frame.contains(anchor) else { return false }return ExtensionPopupCandidate.matches(candidate, owner: owner, sourceHost: sourceHost,isPageHost: CraCEFRuntime.isPageWindow)- }) {- HitchMonitor.mark("extension present window=\(popup.windowNumber) frame=\(NSStringFromRect(popup.frame)) parent=\(popup.parent?.windowNumber ?? -1)")- placingOwnPopup = false- ExtensionPopupWindow.present(popup, anchor: anchor)- return+ })+ // Hidden windows that showed up as something else (a tooltip) are not kept hidden.+ for w in hiddenBubbles.allObjects where w.isVisible && w !== popup {+ w.alphaValue = 1+ hiddenBubbles.remove(w)+ }+ var shownAt = shownAt+ if let popup {+ let since = shownAt ?? Date()+ shownAt = since+ // At Chrome's minimum (a 25×25 page) the page has not reported its size yet: a hidden+ // bubble waits a moment for it rather than showing a stub that then grows.+ let unsized = popup.frame.width <= 25 + 2 * ExtensionPopupWindow.bubbleInset+ if !unsized || popup.alphaValue > 0 || Date().timeIntervalSince(since) > 0.25 {+ HitchMonitor.mark("extension present window=\(popup.windowNumber) frame=\(NSStringFromRect(popup.frame)) parent=\(popup.parent?.windowNumber ?? -1)")+ placingOwnPopup = false+ ExtensionPopupWindow.present(popup, anchor: anchor)+ revealHiddenBubbles()+ return+ }}// No popup yet (still loading), or an action without one (onClicked): keep looking for 3 s.- guard attempt < 60 else {+ guard Date() < deadline else {HitchMonitor.mark("extension placement-expired source=\(sourceHost?.windowNumber ?? -1)")placingOwnPopup = false+ revealHiddenBubbles()return}- DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in- MainActor.assumeIsolated { self?.placePopup(appearingAfter: before, anchor: anchor, sourceHost: sourceHost, attempt: attempt + 1) }+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.008) { [weak self] in+ MainActor.assumeIsolated {+ self?.placePopup(appearingAfter: before, anchor: anchor, sourceHost: sourceHost, deadline: deadline, shownAt: shownAt)+ }}}+ private func revealHiddenBubbles() {+ for w in hiddenBubbles.allObjects { w.alphaValue = 1 }+ hiddenBubbles.removeAllObjects()+ }+// MARK: Targetsprivate enum Failure: Error { case protocolError(String), noTabTarget }@@ -167,7 +202,7 @@ final class ExtensionActions {url.path == "/" + popup.trimmingCharacters(in: CharacterSet(charactersIn: "/")),seenPopupTargets.insert(target).inserted, !placingOwnPopup,let anchor = defaultAnchor(id) else { return }- placePopup(appearingAfter: visibleWindows(), anchor: anchor)+ placePopup(appearingAfter: WindowSnapshot(), anchor: anchor)}// MARK: Protocol callsdiff --git a/Sources/Cra/Services/SuggestionEngine.swift b/Sources/Cra/Services/SuggestionEngine.swiftindex 27e9736..77f2465 100644--- a/Sources/Cra/Services/SuggestionEngine.swift+++ b/Sources/Cra/Services/SuggestionEngine.swift@@ -44,6 +44,8 @@ struct SuggestionResult {var items: [Suggestion] = []/// Host (or more) to complete the typed text to, e.g. "github.com".var inlineCompletion: String?+ /// The site Tab scopes the bar to ("Search YouTube Tab").+ var siteSearch: SiteSearch?var query: String = ""}@@ -112,6 +114,17 @@ final class SuggestionEngine {}result.items = Array(items.prefix(Self.maxRows))result.inlineCompletion = completion?.text+ result.siteSearch = SiteSearch.match(q, completion: completion?.text)+ return result+ }++ /// The bar scoped to a site (after Tab): one row, the typed text searched there.+ func suggestions(for rawQuery: String, in site: SiteSearch) -> SuggestionResult {+ let query = rawQuery.trimmingCharacters(in: .whitespaces)+ var result = SuggestionResult(query: query)+ guard !query.isEmpty else { return result }+ result.items = [Suggestion(id: "typed", kind: .search, title: query, subtitle: "Search \(site.name)", url: site.searchURL(query),+ faviconKey: nil, symbol: "magnifyingglass", trailing: nil, score: 1000)]return result}@@ -468,6 +481,55 @@ final class SuggestionEngine {}}+/// Arc's Site Search: the sites it seeds into Chromium's keyword table (active, not+/// auto-added), with the pill colour each one gets in the bar.+struct SiteSearch: Equatable {+ let name: String+ /// Chromium's keyword: what the typed text has to start.+ let host: String+ let url: String+ let color: String++ func searchURL(_ query: String) -> String {+ let q = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?+ .replacingOccurrences(of: "&", with: "%26") ?? query+ return url.replacingOccurrences(of: "%s", with: q)+ }++ /// "twit" offers X (twitter.com) though it completes to twitch.tv; the completed host+ /// wins when it is a site search itself.+ static func match(_ q: String, completion: String?) -> SiteSearch? {+ var t = q+ if t.hasPrefix("www.") { t.removeFirst(4) }+ guard !t.isEmpty, !t.contains(" "), !t.contains("/") else { return nil }+ if let completion, let site = all.first(where: { $0.host == completion && $0.host.hasPrefix(t) }) { return site }+ return all.first { $0.host.hasPrefix(t) }+ }++ /// Arc 1.170's list, in its order; colours measured off its pills.+ static let all: [SiteSearch] = [+ SiteSearch(name: "Google Drive", host: "drive.google.com", url: "https://drive.google.com/drive/search?q=%s", color: "#0F9D58"),+ SiteSearch(name: "Gmail", host: "mail.google.com", url: "https://mail.google.com/mail/u/0/#search/%s", color: "#D44638"),+ SiteSearch(name: "Google Maps", host: "maps.google.com", url: "https://www.google.com/maps/search/%s", color: "#FBBC05"),+ SiteSearch(name: "Google Calendar", host: "calendar.google.com", url: "https://calendar.google.com/calendar/u/0/r/search?q=%s", color: "#9C27B0"),+ SiteSearch(name: "Google Docs", host: "docs.google.com", url: "https://docs.google.com/document/u/0/?q=%s", color: "#4285F4"),+ SiteSearch(name: "Dropbox", host: "dropbox.com", url: "https://www.dropbox.com/search/personal?&query=%s", color: "#007EE5"),+ SiteSearch(name: "Amazon", host: "amazon.com", url: "https://www.amazon.com/s?k=%s", color: "#FF9900"),+ SiteSearch(name: "GitHub", host: "github.com", url: "https://github.com/search?q=%s", color: "#743FC7"),+ SiteSearch(name: "Figma", host: "figma.com", url: "https://www.figma.com/files/search?q=%s", color: "#F24E1E"),+ SiteSearch(name: "X", host: "x.com", url: "https://x.com/search?q=%s", color: "#000000"),+ SiteSearch(name: "X", host: "twitter.com", url: "https://x.com/search?q=%s", color: "#000000"),+ SiteSearch(name: "YouTube", host: "youtube.com", url: "https://www.youtube.com/results?search_query=%s", color: "#FF0000"),+ SiteSearch(name: "Wikipedia", host: "wikipedia.org", url: "https://wikipedia.org/w/index.php?search=%s", color: "#FFA500"),+ SiteSearch(name: "Reddit", host: "reddit.com", url: "https://www.reddit.com/search/?q=%s", color: "#FF4500"),+ SiteSearch(name: "SoundCloud", host: "soundcloud.com", url: "https://soundcloud.com/search?q=%s", color: "#F85216"),+ SiteSearch(name: "Asana", host: "asana.com", url: "https://app.asana.com/0/search?q=%s", color: "#F06A6A"),+ SiteSearch(name: "LinkedIn", host: "linkedin.com", url: "https://linkedin.com/search/results/all/?keywords=%s", color: "#0B66C2"),+ SiteSearch(name: "Apple Music", host: "music.apple.com", url: "https://music.apple.com/us/search?term=%s", color: "#FA2A44"),+ SiteSearch(name: "Spotify", host: "spotify.com", url: "https://open.spotify.com/search/%s", color: "#1DB954"),+ ]+}+enum PopularDomains {static let list: [String] = ["google.com", "youtube.com", "github.com", "gmail.com", "mail.google.com", "docs.google.com", "drive.google.com",diff --git a/Sources/Cra/UI/CommandBar/CommandBarController.swift b/Sources/Cra/UI/CommandBar/CommandBarController.swiftindex 7930a48..10e42d5 100644--- a/Sources/Cra/UI/CommandBar/CommandBarController.swift+++ b/Sources/Cra/UI/CommandBar/CommandBarController.swift@@ -15,6 +15,8 @@ final class CommandBarController {/// Text pushed into the field from outside (prefill); bump version to apply.var fieldText = ""var fieldTextVersion = 0+ /// Pushed text arrives selected (a prefill); false puts the caret after it.+ var fieldTextSelected = truevar allowCompletion = true/// Text shown in the field while arrowing through rows (Chrome/Arc fill the/// field with the selected row); nil shows what was typed. Bump version to apply.@@ -26,6 +28,12 @@ final class CommandBarController {var highlight: Color = .accentColor.opacity(0.4)var focusedSpaceID: UUID?var spaceName: (UUID) -> String = { _ in "" }+ /// Arc's Site Search: Tab on "youtube" scopes the bar to YouTube (a pill before the+ /// field) until Backspace on an empty field or Escape.+ private(set) var siteSearch: SiteSearch?+ /// What was typed when Tab entered the site search; Backspace puts it back.+ private var siteSearchTyped = ""+ private var openedPrefill: String?unowned let engine: SuggestionEngineunowned let store: SidebarStore@@ -38,6 +46,7 @@ final class CommandBarController {}var placeholder: String {+ if siteSearch != nil { return "Search…" }switch mode {case .newTab: return "Search or enter URL…"case .editURL: return "Edit URL or search…"@@ -47,8 +56,11 @@ final class CommandBarController {func open(mode: CommandBarMode, prefill: String?) {engine.resetIndex()self.mode = mode+ siteSearch = nil+ openedPrefill = prefillquery = prefill ?? ""fieldText = query+ fieldTextSelected = truefieldTextVersion += 1allowCompletion = falseselectedIndex = 0@@ -60,6 +72,7 @@ final class CommandBarController {/// Replace the typed text (scripting / tests).func setQuery(_ text: String) {fieldText = text+ fieldTextSelected = truefieldTextVersion += 1update(query: text, allowCompletion: true)}@@ -67,6 +80,12 @@ final class CommandBarController {func update(query newQuery: String, allowCompletion: Bool) {query = newQueryself.allowCompletion = allowCompletion+ if let site = siteSearch {+ result = engine.suggestions(for: newQuery, in: site)+ selectedIndex = 0+ previewText = nil+ return+ }result = engine.suggestions(for: newQuery, mode: mode, currentTabID: store.selectedTabID)if !allowCompletion { result.inlineCompletion = nil }selectedIndex = 0@@ -80,6 +99,7 @@ final class CommandBarController {/// The search engine answered: list again, keeping the selected row where it still is.private func relist() {+ guard siteSearch == nil else { return }let selectedID = result.items.indices.contains(selectedIndex) ? result.items[selectedIndex].id : nilresult = engine.suggestions(for: query, mode: mode, currentTabID: store.selectedTabID)if !allowCompletion { result.inlineCompletion = nil }@@ -119,10 +139,40 @@ final class CommandBarController {}}+ /// Tab on text that starts a site search's host: scope the bar to that site.+ func enterSiteSearch() -> Bool {+ guard siteSearch == nil, previewText == nil, let site = result.siteSearch else { return false }+ siteSearchTyped = query+ siteSearch = site+ pushFieldText("")+ return true+ }++ /// Backspace on the empty scoped field: back to what was typed, the hint showing again.+ func leaveSiteSearch() {+ guard siteSearch != nil else { return }+ siteSearch = nil+ pushFieldText(siteSearchTyped)+ }++ /// Escape in a site search goes back to how the bar opened rather than closing it (Arc).+ func cancelSiteSearch() {+ guard siteSearch != nil else { return }+ open(mode: mode, prefill: openedPrefill)+ }++ private func pushFieldText(_ text: String) {+ fieldText = text+ fieldTextSelected = false+ fieldTextVersion += 1+ update(query: text, allowCompletion: false)+ }+/// Accept the inline completion (Tab / →).func acceptCompletion() -> Bool {guard let c = result.inlineCompletion else { return false }fieldText = c+ fieldTextSelected = truefieldTextVersion += 1update(query: c, allowCompletion: false)return true@@ -145,6 +195,7 @@ final class CommandBarController {func close() {guard isOpen else { return }isOpen = false+ siteSearch = nilengine.resetIndex()onClose()}diff --git a/Sources/Cra/UI/CommandBar/CommandBarView.swift b/Sources/Cra/UI/CommandBar/CommandBarView.swiftindex a08e0d1..e24d35d 100644--- a/Sources/Cra/UI/CommandBar/CommandBarView.swift+++ b/Sources/Cra/UI/CommandBar/CommandBarView.swift@@ -20,6 +20,13 @@ final class CommandBarView: NSView {private let leadingIcon = NSImageView()private let text: CommandTextFieldprivate let info = NSImageView()+ /// Site Search: the scoped site's pill before the field, and "Search YouTube Tab" at the+ /// end of the row while the typed text would enter it (Arc 1.170, measured at 2x).+ private let pill = NSView()+ private let pillLabel = NSTextField.sidebarLabel(size: 13, weight: .semibold)+ private let hint = NSTextField.sidebarLabel(size: 13, weight: .semibold)+ private let keycap = NSView()+ private let keycapLabel = NSTextField.sidebarLabel(size: 13, weight: .semibold)private let divider = NSView()private var rows: [CommandBarRowView] = []private var syncQueued = false@@ -44,7 +51,19 @@ final class CommandBarView: NSView {info.imageScaling = .scaleNoneinfo.contentTintColor = .secondaryLabelColordivider.wantsLayer = true- for v in [material, tint, leadingIcon, text.field, info, divider] as [NSView] { addSubview(v) }+ pill.wantsLayer = true+ pill.layer?.cornerCurve = .continuous+ pill.layer?.shadowOpacity = 0.3+ pill.layer?.shadowRadius = 8+ pill.layer?.shadowOffset = .zero+ pillLabel.textColor = .white+ pill.addSubview(pillLabel)+ keycap.wantsLayer = true+ keycap.layer?.cornerRadius = 6+ keycap.layer?.cornerCurve = .continuous+ keycapLabel.stringValue = "Tab"+ keycap.addSubview(keycapLabel)+ for v in [material, tint, leadingIcon, text.field, info, pill, hint, keycap, divider] as [NSView] { addSubview(v) }layer?.addSublayer(border)border.zPosition = 10sync()@@ -86,13 +105,30 @@ final class CommandBarView: NSView {tint.layer?.backgroundColor = (dark ? NSColor.black.withAlphaComponent(0.74) : NSColor.white.withAlphaComponent(0.7)).cgColorborder.strokeColor = NSColor.labelColor.withAlphaComponent(dark ? 0.12 : 0.08).cgColordivider.layer?.backgroundColor = NSColor.labelColor.withAlphaComponent(0.08).cgColor- info.isHidden = !c.query.isEmpty+ let site = c.siteSearch+ info.isHidden = !c.query.isEmpty || site != nildivider.isHidden = items.isEmpty+ pill.isHidden = site == nil+ if let site {+ let color = NSColor(hex: site.color)+ pill.layer?.backgroundColor = color.cgColor+ pill.layer?.shadowColor = color.cgColor+ pillLabel.stringValue = site.name+ }+ let offered = site == nil && c.previewText == nil ? c.result.siteSearch : nil+ hint.isHidden = offered == nil+ keycap.isHidden = offered == nil+ if let offered {+ hint.stringValue = "Search \(offered.name)"+ hint.textColor = NSColor.labelColor.withAlphaComponent(0.33)+ keycapLabel.textColor = NSColor.labelColor.withAlphaComponent(0.67)+ keycap.layer?.backgroundColor = NSColor.labelColor.withAlphaComponent(0.04).cgColor+ }// Follows the row the arrows moved to; otherwise the completing top match.let previewing = c.previewText != nil && items.indices.contains(c.selectedIndex)let row = previewing ? items[c.selectedIndex] : items.first- if let s = row, let key = s.faviconKey, s.id != "typed", let img = favicons.image(forKey: key),+ if site == nil, let s = row, let key = s.faviconKey, s.id != "typed", let img = favicons.image(forKey: key),previewing || c.result.inlineCompletion != nil || c.mode == .editURL {leadingIcon.imageScaling = .scaleProportionallyUpOrDownleadingIcon.image = img@@ -121,7 +157,7 @@ final class CommandBarView: NSView {rows.append(r)addSubview(r)}- let highlight = NSColor(c.highlight)+ let highlight = site.map { NSColor(hex: $0.color) } ?? NSColor(c.highlight)for (i, r) in rows.enumerated() {guard i < items.count else { r.isHidden = true; continue }r.isHidden = false@@ -153,7 +189,25 @@ final class CommandBarView: NSView {info.frame = NSRect(x: right - 18, y: (fh - 18) / 2, width: 18, height: 18)right -= 18 + 14}- let x: CGFloat = 22 + 22 + 14+ if !keycap.isHidden {+ // Key cap 23 tall, 4 pt around "Tab", 10 pt after the hint.+ let kw = ceil(keycapLabel.attributedStringValue.size().width), kh = keycapLabel.intrinsicContentSize.height+ keycap.frame = NSRect(x: right - kw - 8, y: (fh - 23) / 2, width: kw + 8, height: 23)+ keycapLabel.frame = NSRect(x: 4 - SidebarText.inset, y: (23 - kh) / 2, width: kw + 2 * SidebarText.inset, height: kh)+ right = keycap.frame.minX - 10+ let hw = ceil(hint.attributedStringValue.size().width), hh = hint.intrinsicContentSize.height+ hint.frame = NSRect(x: right - hw - SidebarText.inset, y: (fh - hh) / 2, width: hw + 2 * SidebarText.inset, height: hh)+ right -= hw + 14+ }+ var x: CGFloat = 22 + 22 + 14+ if !pill.isHidden {+ // 23 tall, fully round, 10.5 pt around the name; the field starts 11 pt after it.+ let lw = ceil(pillLabel.attributedStringValue.size().width), lh = pillLabel.intrinsicContentSize.height+ pill.frame = NSRect(x: x, y: (fh - 23) / 2, width: lw + 21, height: 23)+ pill.layer?.cornerRadius = 11.5+ pillLabel.frame = NSRect(x: 10.5 - SidebarText.inset, y: (23 - lh) / 2, width: lw + 2 * SidebarText.inset, height: lh)+ x = pill.frame.maxX + 11+ }text.field.frame = NSRect(x: x - 1.5, y: (fh - 30) / 2 + 2, width: max(0, right - x), height: 30)divider.frame = NSRect(x: 16, y: fh, width: max(0, b.width - 32), height: 1)var y: CGFloat = fh + 10diff --git a/Sources/Cra/UI/CommandBar/CommandTextField.swift b/Sources/Cra/UI/CommandBar/CommandTextField.swiftindex 2748381..233791d 100644--- a/Sources/Cra/UI/CommandBar/CommandTextField.swift+++ b/Sources/Cra/UI/CommandBar/CommandTextField.swift@@ -51,9 +51,11 @@ final class CommandTextField {field.stringValue = controller.fieldTextcoord.lastTyped = controller.fieldTextcoord.suppressChange = false+ let selected = controller.fieldTextSelectedDispatchQueue.main.async {field.window?.makeFirstResponder(field)- field.currentEditor()?.selectAll(nil)+ guard let editor = field.currentEditor() else { return }+ if selected { editor.selectAll(nil) } else { editor.selectedRange = NSRange(location: (field.stringValue as NSString).length, length: 0) }}}if coord.appliedPreview != controller.previewVersion {@@ -130,7 +132,10 @@ final class CommandTextField {controller.commit(forceNewTab: cmd)return truecase #selector(NSResponder.cancelOperation(_:)):- controller.close(); return true+ if controller.siteSearch != nil { controller.cancelSiteSearch() } else { controller.close() }+ return true+ case #selector(NSResponder.insertTab(_:)) where controller.enterSiteSearch():+ return truecase #selector(NSResponder.insertTab(_:)), #selector(NSResponder.moveRight(_:)), #selector(NSResponder.moveToEndOfLine(_:)):if pendingCompletion != nil, textView.selectedRange.length > 0 {let text = textView.string@@ -142,6 +147,10 @@ final class CommandTextField {}return selector == #selector(NSResponder.insertTab(_:))case #selector(NSResponder.deleteBackward(_:)):+ if controller.siteSearch != nil, textView.string.isEmpty {+ controller.leaveSiteSearch()+ return true+ }if pendingCompletion != nil, textView.selectedRange.length > 0 {// Remove the suggestion, keep what was typed.let typed = lastTypeddiff --git a/Sources/Cra/UI/Settings/TabsPane.swift b/Sources/Cra/UI/Settings/TabsPane.swiftindex 3db29dc..733c92a 100644--- a/Sources/Cra/UI/Settings/TabsPane.swift+++ b/Sources/Cra/UI/Settings/TabsPane.swift@@ -20,6 +20,10 @@ struct TabsPane: View {// Arc." with an "Air Traffic Control…" button.SettingsFormRow(label: "Links:") {SettingsCheckbox(title: "Links from other apps open in a Little Window", isOn: $store.settings.openExternalLinksInLittleWindow)+ 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: "Open a Peek window when clicking on links with Shift held", isOn: $store.settings.peekOnShiftClick)HStack(spacing: 8) {Button("Air Traffic Control…") { showsAirTrafficControl = true }Text(routesSummary).font(.system(size: 11)).foregroundStyle(.secondary)diff --git a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swiftindex 71a5ea8..5272138 100644--- a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift+++ b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift@@ -41,6 +41,21 @@ enum SidebarSymbols {NSImage(systemSymbolName: name, accessibilityDescription: nil)?.withSymbolConfiguration(.init(pointSize: size, weight: weight))}++ /// The tab row's ✕ (or − for a pinned tab that stays): Arc strokes two 2 pt round-capped lines+ /// 4.25 pt out from a centre on a whole point, crisp at 1x. No SF Symbol size matches it, and an+ /// NSImage drawn for it came out thinner and off-centre at 1x, so the button strokes this itself.+ static func closeMark(minus: Bool = false, centre c: CGPoint) -> CGPath {+ let d: CGFloat = 4.25+ let p = CGMutablePath()+ if minus {+ p.move(to: CGPoint(x: c.x - d, y: c.y)); p.addLine(to: CGPoint(x: c.x + d, y: c.y))+ } else {+ p.move(to: CGPoint(x: c.x - d, y: c.y - d)); p.addLine(to: CGPoint(x: c.x + d, y: c.y + d))+ p.move(to: CGPoint(x: c.x - d, y: c.y + d)); p.addLine(to: CGPoint(x: c.x + d, y: c.y - d))+ }+ return p+ }}enum SidebarText {@@ -66,6 +81,9 @@ final class SidebarGlyphButton: NSView {var action: () -> Voidlet size: NSSizeprivate let glyph = NSImageView()+ /// Stroked instead of the image (SidebarSymbols.closeMark).+ private var mark: CAShapeLayer?+ private var markMinus = falseprivate var tip: ArcTooltipAnchorView?private var hovering = false { didSet { refresh() } }var colors: SidebarColors { didSet { if colors != oldValue { refresh() } } }@@ -98,7 +116,36 @@ final class SidebarGlyphButton: NSView {required init?(coder: NSCoder) { fatalError() }func setSymbol(_ symbol: String, iconSize: CGFloat, weight: NSFont.Weight = .medium, help: String) {- glyph.image = SidebarSymbols.image(symbol, size: iconSize, weight: weight)+ setGlyph(SidebarSymbols.image(symbol, size: iconSize, weight: weight), help: help)+ }++ func setGlyph(_ image: NSImage?, help: String) {+ glyph.image = image+ glyph.isHidden = false+ mark?.isHidden = true+ setHelp(help)+ }++ /// Shows the tab row's ✕ / − (SidebarSymbols.closeMark) in place of the image.+ func setCloseMark(minus: Bool, help: String) {+ if mark == nil {+ let m = CAShapeLayer()+ m.fillColor = nil+ m.lineWidth = 2+ m.lineCap = .round+ m.actions = ["path": NSNull(), "strokeColor": NSNull(), "hidden": NSNull()]+ layer?.addSublayer(m)+ mark = m+ }+ markMinus = minus+ glyph.isHidden = true+ mark?.isHidden = false+ needsLayout = true+ refresh()+ setHelp(help)+ }++ private 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) }}@@ -107,16 +154,34 @@ final class SidebarGlyphButton: NSView {private func refresh() {let tint: NSColorif colors.isDark {- tint = enabled ? NSColor.white.withAlphaComponent(0.55) : colors.textTertiary.withAlphaComponent(colors.textTertiary.alphaComponent * 0.55)+ // Arc's row ✕ is a touch brighter than its other glyphs (white 0.6 over the hover fill, 1x).+ tint = enabled ? NSColor.white.withAlphaComponent(mark != nil ? 0.6 : 0.55) : colors.textTertiary.withAlphaComponent(colors.textTertiary.alphaComponent * 0.55)} else if let active {tint = NSColor.black.withAlphaComponent(enabled && active ? 0.59 : 0.24)} else {tint = enabled ? colors.glyph : colors.textTertiary.withAlphaComponent(colors.textTertiary.alphaComponent * 0.55)}glyph.contentTintColor = tint+ mark?.strokeColor = tint.cgColorlayer?.backgroundColor = (hovering && enabled ? colors.hoverFill : .clear).cgColor}+ override func layout() {+ super.layout()+ guard let mark else { return }+ mark.frame = bounds+ // The centre on a whole point of the window: a dragged sidebar width is fractional.+ let mid = convert(CGPoint(x: bounds.midX, y: bounds.midY), to: nil)+ let centre = convert(CGPoint(x: mid.x.rounded(), y: mid.y.rounded()), from: nil)+ mark.path = SidebarSymbols.closeMark(minus: markMinus, centre: centre)+ mark.contentsScale = window?.backingScaleFactor ?? 2+ }++ override func viewDidChangeBackingProperties() {+ super.viewDidChangeBackingProperties()+ mark?.contentsScale = window?.backingScaleFactor ?? 2+ }+override var mouseDownCanMoveWindow: Bool { false }override func updateTrackingAreas() {@@ -133,7 +198,15 @@ final class SidebarGlyphButton: NSView {// Rows hide their buttons rather than remove them; a button shown again under the pointer is hovered.override func viewDidHide() { hovering = false }- override func viewDidUnhide() { viewDidMoveToWindow() }+ override func viewDidUnhide() {+ viewDidMoveToWindow()+ if mark != nil { needsLayout = true } // the row may have scrolled while hidden+ }++ override func setFrameOrigin(_ newOrigin: NSPoint) {+ super.setFrameOrigin(newOrigin)+ if mark != nil { needsLayout = true }+ }override func mouseEntered(with event: NSEvent) { hovering = true }override func mouseExited(with event: NSEvent) { hovering = false }@@ -591,7 +664,11 @@ final class TabRowView: SidebarRowView, ArcTooltipTarget, NSTextFieldDelegate {guard let self, let id = self.model?.id else { return }self.list?.actions.resetPinnedTab(id)}- private lazy var closeButton = SidebarGlyphButton(symbol: "xmark", size: Self.closeSize, iconSize: 13, help: "", colors: colors) {}+ private lazy var closeButton: SidebarGlyphButton = {+ let b = SidebarGlyphButton(symbol: "xmark", size: Self.closeSize, iconSize: 13, help: "", colors: colors) {}+ b.setCloseMark(minus: false, help: "")+ return b+ }()private static let closeSize: CGFloat = 22private var closeKind = ""@@ -614,13 +691,13 @@ final class TabRowView: SidebarRowView, ArcTooltipTarget, NSTextFieldDelegate {closeKind = kindswitch kind {case "keep":- closeButton.setSymbol("minus", iconSize: 13, help: "Close and Keep Pinned (⌘W)")+ closeButton.setCloseMark(minus: true, help: "Close and Keep Pinned (⌘W)")closeButton.action = { [weak self] in self?.list?.closeTabs([id]) }case "archivePinned":- closeButton.setSymbol("xmark", iconSize: 13, help: "Archive this tab")+ closeButton.setCloseMark(minus: false, help: "Archive this tab")closeButton.action = { [weak self] in self?.list?.store.archiveTab(id, reason: .manual) }default:- closeButton.setSymbol("xmark", iconSize: 13, help: m.closeGroup > 1 ? "Close \(m.closeGroup) Tabs (⌘W)" : "Archive (⌘W)")+ closeButton.setCloseMark(minus: false, help: m.closeGroup > 1 ? "Close \(m.closeGroup) Tabs (⌘W)" : "Archive (⌘W)")closeButton.action = { [weak self] inguard let list = self?.list else { return }list.closeTabs(list.closeGroup(for: id))@@ -1229,7 +1306,8 @@ final class NewTabRowView: SidebarRowView {override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {super.init(key: key, list: list, colors: colors)- plus.image = SidebarSymbols.image("plus", size: 13, weight: .medium)+ // Arc's plus, fitted pixel by pixel at 1x and 2x.+ plus.image = SidebarSymbols.image("plus", size: 14.5, weight: .medium)plus.imageScaling = .scaleNonelabel.stringValue = "New Tab"addSubview(plus)diff --git a/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swift b/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swiftindex 5912214..1518f28 100644--- a/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swift+++ b/Sources/Cra/UI/Sidebar/List/SpaceColumnView.swift@@ -301,9 +301,19 @@ final class FavoritesGridView: NSView {if countChanged { onHeightChange(false) }}- private var rows: Int { (order.count + 3) / 4 }+ /// 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+ }++ private func rows(forWidth w: CGFloat) -> Int {+ let c = Self.columns(forWidth: w)+ return (order.count + c - 1) / c+ }func height(forWidth w: CGFloat) -> CGFloat {+ let rows = rows(forWidth: w)let grid = rows == 0 ? 0 : CGFloat(rows) * 47 + CGFloat(rows - 1) * 8return grid + (order.isEmpty ? 0 : 4) + strip.height}@@ -311,11 +321,13 @@ final class FavoritesGridView: NSView {override func layout() {super.layout()let w = bounds.width- let cw = (w - 3 * 8) / 4+ let n = Self.columns(forWidth: w)+ let cw = (w - CGFloat(n - 1) * 8) / CGFloat(n)for (i, id) in order.enumerated() {- let r = i / 4, c = i % 4+ let r = i / n, c = i % ntiles[id]?.frame = NSRect(x: CGFloat(c) * (cw + 8), 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) * 8strip.frame = NSRect(x: 0, y: grid + (order.isEmpty ? 0 : 4), width: w, height: strip.height)}diff --git a/Sources/Cra/UI/Sidebar/List/SpacePagerView.swift b/Sources/Cra/UI/Sidebar/List/SpacePagerView.swiftindex 906e77b..055eb73 100644--- a/Sources/Cra/UI/Sidebar/List/SpacePagerView.swift+++ b/Sources/Cra/UI/Sidebar/List/SpacePagerView.swift@@ -3,9 +3,10 @@ import SwiftUI/// Dia's paging container in AppKit: every space's column (favorites, header, tab list) sits/// side by side on a strip, the strip follows a swipe 1:1, then a spring settles it on a page.-/// The page index places the strip by frame; the rest of the travel is a translation of the-/// pager's sublayers, which Core Animation moves on its own. A swipe or a settle never lays out,-/// diffs or redraws a row.+/// The strip only ever moves by frame. AppKit draws just the views it knows are inside the pager,+/// so a column brought in or kept on screen by a layer translation alone showed blank: the next+/// space while the fingers moved, the last one while a space change sprang (issue #12). Neither+/// the swipe nor the settle lays out or diffs a row.@MainActorfinal class SpacePagerView: NSView {private let store: SidebarStore@@ -14,16 +15,30 @@ final class SpacePagerView: NSView {private let favicons: FaviconCacheprivate let strip = NSView()private var columns: [UUID: NSView] = [:]- /// The page the strip's frame was placed at, and the width it was placed with.+ /// The page the strip was placed at, and the width it was placed with.private var placedIndex = 0private var placedWidth: CGFloat = 0private var placedSwipe: CGFloat = 0- /// The translation (points) the model layer holds; the presentation may still be springing.- private var offset: CGFloat = 0/// Release speed for the next settle, relative to the distance left (Dia's spring).private var pendingVelocity: Double = 0private var ownSettle: Int?- private static let settleKey = "settle"+ private var spring: Spring?+ private var link: CADisplayLink?++ /// Dia's zero-bounce spring (CASpringAnimation perceptualDuration 0.4, bounce 0): critically+ /// damped, so the offset from the page is (x0 + (v0 + ω·x0)·t)·e^(−ω·t).+ private struct Spring {+ let index: Int+ let start: CFTimeInterval+ let x0: CGFloat+ let v0: CGFloat+ static let omega: CGFloat = 2 * .pi / 0.4++ func offset(at time: CFTimeInterval) -> CGFloat {+ let t = CGFloat(max(0, time - start))+ return (x0 + (v0 + Self.omega * x0) * t) * exp(-Self.omega * t)+ }+ }init(store: SidebarStore, ui: SidebarUIState, actions: SidebarActions, favicons: FaviconCache) {self.store = store@@ -66,12 +81,24 @@ final class SpacePagerView: NSView {return}if placedSwipe == 0 { SpaceListView.endHover(for: ui) }- // Under the fingers the strip follows at once, without a layout pass.- layer?.removeAnimation(forKey: Self.settleKey)- setOffset(-swipe * placedWidth)+ // Under the fingers the strip follows at once, without a layout pass. The swipe counts+ // from the space shown, which a release can change before this view lays out.+ let index = store.pagedSpaces(window: ui.windowID).map(\.id).firstIndex(of: store.focusedSpaceID(window: ui.windowID)) ?? placedIndex+ stopSpring()+ place(index: index, offset: -swipe * placedWidth)placedSwipe = swipe}+ /// The strip at `index`'s page, `offset` points to the right of it.+ private func place(index: Int, offset: CGFloat) {+ let x = -CGFloat(index) * placedWidth + offset+ guard strip.frame.minX != x else { return }+ CATransaction.begin()+ CATransaction.setDisableActions(true)+ strip.setFrameOrigin(NSPoint(x: x, y: 0))+ CATransaction.commit()+ }+private func column(for id: UUID) -> NSView {if let c = columns[id] { return c }let host = SpaceColumnView(spaceID: id, store: store, ui: ui, actions: actions, favicons: favicons)@@ -90,10 +117,11 @@ final class SpacePagerView: NSView {columns[id] = nil}// Where the strip shows now, in pages (mid-spring if one runs).- let shown = presentedPosition()+ let shown = placedWidth > 0 ? -strip.frame.minX / placedWidth : nil+ let swipe = ui.spaceSwipeCATransaction.begin()CATransaction.setDisableActions(true)- strip.frame = NSRect(x: -CGFloat(index) * width, y: 0, width: CGFloat(max(1, ids.count)) * width, height: height)+ strip.setFrameSize(NSSize(width: CGFloat(max(1, ids.count)) * width, height: height))for (i, id) in ids.enumerated() {let f = NSRect(x: CGFloat(i) * width, y: 0, width: width, height: height)let c = column(for: id)@@ -101,56 +129,70 @@ final class SpacePagerView: NSView {}CATransaction.commit()- let swipe = ui.spaceSwipe- defer {- placedIndex = index- placedWidth = width- placedSwipe = swipe- }+ let moved = index != placedIndex || placedSwipe != 0+ placedIndex = index+ placedWidth = width+ placedSwipe = swipeif swipe != 0 {// Fingers on the trackpad: follow them exactly.- layer?.removeAnimation(forKey: Self.settleKey)- setOffset(-swipe * width)- } else if index != placedIndex || placedSwipe != 0, let shown, abs(shown - CGFloat(index)) > 0.002, width > 0 {- settle(from: -(shown - CGFloat(index)) * width)- } else if layer?.animation(forKey: Self.settleKey) == nil {- setOffset(0)+ stopSpring()+ place(index: index, offset: -swipe * width)+ } else if moved, let shown, abs(shown - CGFloat(index)) > 0.002, width > 0 {+ settle(index: index, from: -(shown - CGFloat(index)) * width)+ } else if let spring, spring.index == index {+ place(index: index, offset: spring.offset(at: CACurrentMediaTime()))+ } else {+ stopSpring()+ place(index: index, offset: 0)}}- private func presentedPosition() -> CGFloat? {- guard placedWidth > 0 else { return nil }- let tx = (layer?.presentation()?.value(forKeyPath: "sublayerTransform.translation.x") as? CGFloat) ?? offset- return CGFloat(placedIndex) - tx / placedWidth+ /// Dia settles pages with a zero-bounce spring that picks up the release speed.+ private func settle(index: Int, from x: CGFloat) {+ // CASpringAnimation's initialVelocity: the distance to travel per second.+ spring = Spring(index: index, start: CACurrentMediaTime(), x0: x, v0: -CGFloat(pendingVelocity) * x)+ pendingVelocity = 0+ place(index: index, offset: x)+ ownSettle = ui.beginSpaceSettle()+ guard window != nil else { finishSpring(); return }+ if link == nil {+ let l = displayLink(target: self, selector: #selector(step))+ l.add(to: .main, forMode: .common)+ link = l+ }}- private func setOffset(_ x: CGFloat) {- offset = x- CATransaction.begin()- CATransaction.setDisableActions(true)- layer?.sublayerTransform = CATransform3DMakeTranslation(x, 0, 0)- CATransaction.commit()+ @objc private func step(_ link: CADisplayLink) {+ guard let spring else { stopSpring(); return }+ let time = link.targetTimestamp+ let x = spring.offset(at: time)+ let speed = abs(x - spring.offset(at: time - 0.01)) * 100+ if abs(x) < 0.25 && speed < 5 {+ finishSpring()+ } else {+ place(index: spring.index, offset: x)+ }}- /// Dia settles pages with a zero-bounce spring that picks up the release speed.- private func settle(from x: CGFloat) {- let spring = CASpringAnimation(perceptualDuration: 0.4, bounce: 0)- spring.keyPath = "sublayerTransform.translation.x"- spring.fromValue = x- spring.toValue = 0- spring.initialVelocity = pendingVelocity- spring.duration = spring.settlingDuration- pendingVelocity = 0- let generation = ui.beginSpaceSettle()- ownSettle = generation- CATransaction.begin()- CATransaction.setCompletionBlock { [weak self] in- guard let self else { return }- if self.ownSettle == generation { self.ui.endSpaceSettle(generation) }- SpaceListView.refreshHover(for: self.ui)+ private func finishSpring() {+ let index = spring?.index ?? placedIndex+ stopSpring()+ place(index: index, offset: 0)+ if let generation = ownSettle {+ ownSettle = nil+ ui.endSpaceSettle(generation)}- setOffset(0)- layer?.add(spring, forKey: Self.settleKey)- CATransaction.commit()+ SpaceListView.refreshHover(for: ui)+ }++ private func stopSpring() {+ spring = nil+ link?.invalidate()+ link = nil+ }++ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ if window == nil, spring != nil { finishSpring() }}}diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swiftindex 3fe6f4b..6538332 100644--- a/Sources/Cra/UI/SidebarUIState.swift+++ b/Sources/Cra/UI/SidebarUIState.swift@@ -40,8 +40,8 @@ final class SidebarUIState {/// Library per window and reopens it on the page last shown).var libraryPage: LibraryPage?@ObservationIgnored var lastLibraryPage: LibraryPage = .downloads- /// Tab chosen from the keyboard; Arc draws its yellow/black dashed ring- /// around it until the mouse picks another tab.+ /// Tab chosen from the keyboard in another space (the tab switcher); Arc draws its+ /// yellow/black dashed ring around it until the mouse picks another tab.var keyboardFocusID: UUID?/// The pointer is over a draggable sidebar row or tile. The window is/// movable by its background; the window controller turns that off whilediff --git a/Sources/Cra/UI/Windows/ExtensionPopupCandidate.swift b/Sources/Cra/UI/Windows/ExtensionPopupCandidate.swiftindex d73f5d3..1e7b273 100644--- a/Sources/Cra/UI/Windows/ExtensionPopupCandidate.swift+++ b/Sources/Cra/UI/Windows/ExtensionPopupCandidate.swift@@ -12,4 +12,12 @@ enum ExtensionPopupCandidate {let host = window.parent, isPageHost(host), host.parent === owner else { return false }return sourceHost == nil || host === sourceHost}++ /// A window Chrome has created but not shown yet that can turn out to be the popup's bubble+ /// (kept transparent until it is framed). Its parent is only set once it is shown.+ @MainActor+ static func mayBecomePopup(_ window: NSWindow) -> Bool {+ !window.isVisible && !window.styleMask.contains(.titled) && !(window is NSPanel)+ && NSStringFromClass(type(of: window)) == "NativeWidgetMacNSWindow"+ }}diff --git a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swiftindex 9477831..2f311ce 100644--- a/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift+++ b/Sources/Cra/UI/Windows/ExtensionPopupWindow.swift@@ -181,7 +181,15 @@ final class ExtensionPopupWindow: NSWindow {observers = []if let bubble {removeChildWindow(bubble)- if closingBubble { bubble.close() }+ // Not right away: the key change that got here can come from inside Chrome ordering+ // its bubble out (it hides a popup before closing it), and closing the NSWindow under+ // that trips a CHECK in Chrome (crash 29 Oct, right after wake). A bubble Chrome has+ // hidden or closed meanwhile is Chrome's to finish.+ if closingBubble {+ DispatchQueue.main.async { [weak bubble] in+ if let bubble, bubble.isVisible { bubble.close() }+ }+ }}bubble = nilparent?.removeChildWindow(self)diff --git a/Sources/Cra/UI/Windows/FloatingSidebar.swift b/Sources/Cra/UI/Windows/FloatingSidebar.swiftindex 83e2962..32dadd2 100644--- a/Sources/Cra/UI/Windows/FloatingSidebar.swift+++ b/Sources/Cra/UI/Windows/FloatingSidebar.swift@@ -125,7 +125,8 @@ final class FloatingSidebarController {return p}- private func refreshBackdrop() {+ /// The space's colours behind the sidebar; the window calls it when the theme changes.+ func refreshBackdrop() {guard panel != nil else { return }let pal = palette()let t = CraTuning.shareddiff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swiftindex cdfb3ff..8a01cca 100644--- a/Sources/Cra/UI/Windows/LittleWindowController.swift+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift@@ -116,6 +116,13 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @precoprivate let shell: LittleShellViewprivate var favicon: NSImage?private var promoted = false+ /// Hosts a page's window.open (a sign-in popup); its URL arrives after it shows.+ private let isPopupHost: Bool+ /// Arc's Peek: this Little Window sits over a browser window, which a dimming panel+ /// covers; a click on it, Escape or the close button ends the Peek.+ let isPeek: Bool+ private(set) weak var peekParent: MainWindowController?+ private var dim: PeekDimPanel?private var commandPanel: CommandBarPanel!private var commandHost: CommandBarView!private var commandBarOpenedAt = Date.distantPast@@ -130,17 +137,22 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco/// `url` nil makes a popup host: the browser adopts the next window.open/// CEF hands it (see `CraBrowserDelegate.browser:popupHostForURL:`).- init(app: AppDelegate, url: String?) {+ init(app: AppDelegate, url: String?, peekOver parent: MainWindowController? = nil) {self.app = app- // Little Windows are normal browsing: they target the last normal window's space.- state = LittleWindowState(targetSpaceID: app.store.focusedSpaceID(window: app.store.lastNormalWindowID))+ isPopupHost = url == nil+ isPeek = parent != nil+ peekParent = parent+ // Little Windows are normal browsing: they target the last normal window's space+ // (a Peek: the space of the window it covers).+ state = LittleWindowState(targetSpaceID: parent?.focusedSpaceID ?? app.store.focusedSpaceID(window: app.store.lastNormalWindowID))commandBar = CommandBarController(engine: app.engine, store: app.store)let size = app.store.prefs.littleWindowSize.map { NSSizeFromString($0) }.flatMap { $0 == LittleMetrics.legacyDefaultSize ? nil : $0 }.map { NSSize(width: max(LittleMetrics.minSize.width, $0.width), height: max(LittleMetrics.minSize.height, $0.height)) }?? LittleMetrics.defaultSizelet window = LittleWindow(contentRect: NSRect(origin: .zero, size: size),- styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],+ styleMask: parent != nil ? [.titled, .closable, .fullSizeContentView]+ : [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],backing: .buffered, defer: false)shell = LittleShellView(frame: window.contentView!.bounds)super.init(window: window)@@ -162,7 +174,14 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @precoself.scheduleTooltip(for: h)}shell.openButtonWidth = { [weak self] in self?.state.openButtonWidth ?? 160 }- placeWindow()+ if parent != nil {+ // A Peek is part of its window: no minimizing or zooming it on its own.+ window.isMovableByWindowBackground = false+ window.standardWindowButton(.miniaturizeButton)?.isHidden = true+ window.standardWindowButton(.zoomButton)?.isHidden = true+ } else {+ placeWindow()+ }actions.openCommandBar = { [weak self] in self?.openCommandBar() }actions.copyURL = { [weak self] in self?.copy(self?.currentURL ?? "") }@@ -291,7 +310,42 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @precoshell.needsLayout = trueshell.layoutSubtreeIfNeeded()if let host, host.parent === window { host.alphaValue = 1 }- if hasPage { focusPage() } else { openCommandBar() }+ // A popup host has no URL until Chromium navigates it, but it is a page+ // all the same: the command bar would cover a sign-in popup.+ if hasPage || isPopupHost { focusPage() } else { openCommandBar() }+ }++ // MARK: Peek++ /// The dimming panel and the Peek, in their order above the parent's other children.+ var peekWindows: [NSWindow] { [dim, window].compactMap { $0 } }++ /// Grows out of the pointer like a Little Window, over the page area of its window.+ func showAsPeek() {+ guard let window, let parent = peekParent, let pw = parent.window else { return }+ let dim = PeekDimPanel(covering: pw) { [weak self] in self?.closeWindow() }+ self.dim = dim+ pw.addChildWindow(dim, ordered: .above)+ dim.orderFront(nil)+ dim.fadeIn()+ window.setFrame(parent.peekFrame(), display: false)+ pw.addChildWindow(window, ordered: .above)+ show()+ }++ func repositionPeek() {+ guard let window, let parent = peekParent, let pw = parent.window else { return }+ dim?.setFrame(pw.frame, display: true)+ window.setFrame(parent.peekFrame(), display: true)+ }++ private func endPeek() {+ guard isPeek, let dim else { return }+ self.dim = nil+ dim.parent?.removeChildWindow(dim)+ dim.orderOut(nil)+ if let window, let p = window.parent { p.removeChildWindow(window) }+ if !promoted, let pw = peekParent?.window, NSApp.isActive { pw.makeKeyAndOrderFront(nil) }}// MARK: Command bar (Arc: clicking the pill or ⌘L opens the command bar in the window)@@ -502,7 +556,8 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco/// Archive the page to the Library (Arc keeps closed Little Arcs there too).func archivePage() {- guard hasPage, !promoted else { return }+ // A Peek is a look at a link, not a page to keep.+ guard hasPage, !promoted, !isPeek else { return }store.archiveLittleWindowPage(url: currentURL, title: browser?.currentTitle ?? state.title)if let favicon, let key = FaviconCache.key(for: currentURL) { app.favicons.store(favicon, forKey: key) }promoted = true // archived once; a later close must not archive again@@ -567,6 +622,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @precofunc windowWillClose(_ notification: Notification) {guard (notification.object as? NSWindow) === window else { return }+ endPeek()if browser == nil { app.removeLittleWindow(self) }}@@ -688,7 +744,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @precofunc browser(_ browser: CraBrowser, didCreateDevToolsView view: NSView) {}func browser(_ browser: CraBrowser, didCreateHostWindow window: NSWindow) {attachHostWindow(window)- if hasPage, self.window?.isKeyWindow == true || window.isKeyWindow { focusPage() }+ if hasPage || isPopupHost, self.window?.isKeyWindow == true || window.isKeyWindow { focusPage() }}func browserDidCloseDevTools(_ browser: CraBrowser) {}func browser(_ browser: CraBrowser, handleKeyEvent event: NSEvent) -> Bool {@@ -699,7 +755,14 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco}return app.handleReservedKey(event)}- func browser(_ browser: CraBrowser, handleUnhandledKeyEvent event: NSEvent) -> Bool { app.handleUnhandledKey(event) }+ func browser(_ browser: CraBrowser, handleUnhandledKeyEvent event: NSEvent) -> Bool {+ // Arc's "Exit the current context": Escape the page didn't use closes a Peek.+ if isPeek, event.type == .keyDown, event.keyCode == 53, event.modifierFlags.intersection([.command, .shift, .option, .control]).isEmpty {+ closeWindow()+ return true+ }+ return app.handleUnhandledKey(event)+ }func browser(_ browser: CraBrowser, didUpdateDownload download: CraDownloadInfo) { app.main.browserManager(download: download) }func browser(_ browser: CraBrowser, requestsPermissionForOrigin origin: String, kinds: UInt, completion: @escaping (Bool) -> Void) {@@ -842,10 +905,12 @@ final class LittleWindow: NSWindow {/// macOS's corner radius for this window (16 pt on macOS 26, larger than Arc's/// 10), read from the frame view's private `_cornerRadius`.- var systemCornerRadius: CGFloat {+ var systemCornerRadius: CGFloat { Self.cornerRadius(of: self) }++ static func cornerRadius(of window: NSWindow) -> CGFloat {typealias RadiusIMP = @convention(c) (AnyObject, Selector) -> CGFloatlet sel = NSSelectorFromString("_cornerRadius")- guard let frameView = contentView?.superview, let method = class_getInstanceMethod(type(of: frameView), sel) else { return LittleMetrics.cornerRadius }+ guard let frameView = window.contentView?.superview, let method = class_getInstanceMethod(type(of: frameView), sel) else { return LittleMetrics.cornerRadius }let radius = unsafeBitCast(method_getImplementation(method), to: RadiusIMP.self)(frameView, sel)return radius > 0 ? radius : LittleMetrics.cornerRadius}@@ -870,6 +935,45 @@ final class LittleWindow: NSWindow {}}+/// The shade over a browser window while a Peek shows on it; a click on it ends the Peek.+final class PeekDimPanel: NSPanel {+ private final class Shade: NSView {+ var onClick: () -> Void = {}+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }+ override func mouseDown(with event: NSEvent) { onClick() }+ override func rightMouseDown(with event: NSEvent) { onClick() }+ }++ init(covering parent: NSWindow, onClick: @escaping () -> Void) {+ super.init(contentRect: parent.frame, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)+ isOpaque = false+ backgroundColor = .clear+ hasShadow = false+ isMovable = false+ hidesOnDeactivate = false+ isReleasedWhenClosed = false+ let shade = Shade(frame: NSRect(origin: .zero, size: parent.frame.size))+ shade.onClick = onClick+ shade.wantsLayer = true+ shade.layer?.backgroundColor = NSColor.black.withAlphaComponent(0.25).cgColor+ shade.layer?.cornerRadius = LittleWindow.cornerRadius(of: parent)+ shade.layer?.cornerCurve = .continuous+ shade.autoresizingMask = [.width, .height]+ contentView = shade+ alphaValue = 0+ }++ override var canBecomeKey: Bool { false }+ override var canBecomeMain: Bool { false }++ func fadeIn() {+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = LittleMetrics.openDuration+ animator().alphaValue = 1+ }+ }+}+/// Borderless, non-activating tooltip panel (never takes key status).final class LittleTooltipPanel: NSPanel {override var canBecomeKey: Bool { false }diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swiftindex c31216d..1179ee5 100644--- a/Sources/Cra/UI/Windows/MainWindowController.swift+++ b/Sources/Cra/UI/Windows/MainWindowController.swift@@ -139,8 +139,11 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMtabSwitcher.onHide = { [weak self] in self?.hideTabSwitcherPanel() }tabSwitcher.onCommit = { [weak self] id inguard let self, id != self.selectedTabID else { return }+ let space = self.focusedSpaceIDself.store.selectTab(id, window: self.windowID)- self.sidebarUI.keyboardFocusID = id+ // Arc rings a tab chosen from the keyboard only when it had to change space to show+ // it; within a space the selection alone marks it (issue #12).+ if self.focusedSpaceID != space { self.sidebarUI.keyboardFocusID = id }}tabSwitcher.direction = { [weak app] event inswitch app?.bindings.action(for: event)?.id {@@ -282,6 +285,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM// views show beyond the palette they observe themselves.if shownTheme != space.theme {shownTheme = space.theme+ // A swipe in the floating sidebar changes space under it (issue #12).+ floatingSidebar?.refreshBackdrop()shell.placeholderHost.wantsLayer = trueshell.placeholderHost.layer?.backgroundColor = (palette.isDark ? NSColor.white.withAlphaComponent(0.04) : NSColor.black.withAlphaComponent(0.03)).cgColorshell.isDarkTheme = palette.isDark@@ -643,7 +648,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMvar panels: [NSPanel?] = [overlayPanel]if !overlay.toasts.isEmpty { panels.append(toastPanel) }if overlay.findVisible { panels.append(findPanel) }- let wanted = panels.compactMap { $0 }+ // A Peek (and its dimming) stays above everything else in the window.+ let wanted = panels.compactMap { $0 } + peeks.flatMap(\.peekWindows)// Already the last children, in order, and showing: re-adding each one rebuilt the// window's ordering group, a window server round trip, on every tab switch.let children = window.childWindows ?? []@@ -1162,6 +1168,31 @@ 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.+ 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),+ let here = SiteKey.site(of: pageURL), here != target else { return false }+ }+ app.openPeek(url: url, over: self)+ return true+ }++ /// Arc's Peek covers the page area less a margin, inside this window.+ func peekFrame() -> NSRect {+ guard let window else { return .zero }+ // Asked from windowDidResize, before the shell has laid out at the new size.+ shell.layoutSubtreeIfNeeded()+ let r = window.convertToScreen(shell.convert(shell.contentContainer.frame, to: nil))+ return r.insetBy(dx: max(24, (r.width * 0.06).rounded()), dy: max(20, (r.height * 0.05).rounded()))+ }++ private var peeks: [LittleWindowController] { app.littleWindows.filter { $0.peekParent === self } }+// MARK: Tabs/// cra://debug?devtoolsjs=…: run script in the current tab's DevTools frontend.@@ -1376,12 +1407,16 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMif event.phase == .began || event.phase == .mayBegin { self.swipeAxis = .vertical }// The momentum tail of a space swipe belongs to the swipe, not the tab list.if !event.momentumPhase.isEmpty { return self.swipeAxis == .horizontal ? nil : event }- guard event.window === self.window, event.hasPreciseScrollingDeltas else { return event }+ // The floating sidebar is in its own panel (FloatingSidebarController): its swipes+ // come from that window.+ let host = self.shell.sidebarHost+ guard event.window === self.window || (event.window != nil && event.window === host.window),+ event.hasPreciseScrollingDeltas else { return event }switch event.phase {case .mayBegin, .began:- let p = self.shell.convert(event.locationInWindow, from: nil)// The Library's lists don't page between spaces.- let overSidebar = (self.shell.sidebarVisible || self.shell.floatingSidebar) && self.shell.sidebarHost.frame.contains(p)+ let overSidebar = (self.shell.sidebarVisible || self.shell.floatingSidebar) && event.window === host.window+ && host.bounds.contains(host.convert(event.locationInWindow, from: nil))&& self.sidebarUI.libraryPage == nilself.swipeAxis = overSidebar ? .undecided : .verticalself.swipeX = 0@@ -1479,8 +1514,10 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMvar instant = Transaction()instant.disablesAnimations = truewithTransaction(instant) {- sidebarUI.spaceSwipe = pages - CGFloat(step)+ // The space first: the strip and the tint read what's left of the swipe+ // against the space shown.store.focusSpace(store.spaceOrder[index + step], window: windowID)+ sidebarUI.spaceSwipe = pages - CGFloat(step)}}sidebarUI.spaceSwipe = 0@@ -1913,6 +1950,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMbrowsers.layoutVisible()if commandBar.isOpen { positionCommandPanel() }floatingSidebar?.reposition()+ for p in peeks { p.repositionPeek() }saveFrame()}@@ -2009,6 +2047,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMfunc tearDown() {isTornDown = truedismissTransientUI()+ for p in peeks { p.closeWindow() }// A page another window shows behind its blurred stand-in moves there with its history// and state; closed with this window, that window loaded it again from scratch.for id in Array(browsers.runtimes.keys) {diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex 1b9c9a2..8be7f7b 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -56,6 +56,12 @@ static bool g_useMockKeychain = false;static NSString* g_extensionsDirectory = nil;static BOOL g_chromeHosting = NO;static NSMutableArray<CraBrowser*>* g_pendingCreation = nil;++/// Settings for every page Cra makes. Chrome style draws its own status bubble flush at the+/// page's bottom left, under Cra's own (StatusBubbleView): one link showed in two bubbles.+static void CraPageSettings(CefBrowserSettings& settings) {+ settings.chrome_status_bubble = STATE_DISABLED;+}static void (^g_relaunchHandler)(NSArray<NSString*>*) = nil;static BOOL g_alreadyRunning = NO;static NSHashTable<CraBrowser*>* g_allBrowsers = nil;@@ -906,10 +912,17 @@ public:CEF_REQUIRE_UI_THREAD();CraBrowser* o = owner_;if (!o || !o.delegate) return true;+ // A target=_blank link the user clicked (Shift-clicked: a new window) may open in a+ // Peek; window.open with features (a sign-in popup) is CEF_WOD_NEW_POPUP and stays one.+ if (user_gesture && (target_disposition == CEF_WOD_NEW_FOREGROUND_TAB || target_disposition == CEF_WOD_NEW_WINDOW)+ && [o.delegate respondsToSelector:@selector(browser:opensPeekForURL:shiftClick:)]+ && [o.delegate browser:o opensPeekForURL:NSStringFromCef(target_url)+ shiftClick:target_disposition == CEF_WOD_NEW_WINDOW]) return true;BOOL background = (target_disposition == CEF_WOD_NEW_BACKGROUND_TAB);CraBrowser* host = [o.delegate browser:o popupHostForURL:NSStringFromCef(target_url) inBackground:background];if (!host) return true; // blockedclient = [host cefClient];+ CraPageSettings(settings);if (g_chromeHosting) return false; // Views path: CraChromeViewDelegate hosts the popup viewNSView* view = host.containerView;NSRect b = view.bounds;@@ -1118,10 +1131,24 @@ public:return blocker_;}+ bool OnBeforeBrowse(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request,+ bool user_gesture, bool is_redirect) override {+ CraBrowser* o = owner_;+ if (!o || !user_gesture || is_redirect || !frame->IsMain()) return false;+ cef_transition_type_t tt = request->GetTransitionType();+ if ((tt & TT_SOURCE_MASK) != TT_LINK || (tt & TT_FORWARD_BACK_FLAG)) return false;+ if (![o.delegate respondsToSelector:@selector(browser:opensPeekForURL:shiftClick:)]) return false;+ return [o.delegate browser:o opensPeekForURL:NSStringFromCef(request->GetURL()) shiftClick:NO];+ }+bool OnOpenURLFromTab(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& target_url,WindowOpenDisposition target_disposition, bool user_gesture) override {CraBrowser* o = owner_;if (!o) return false;+ // Shift-click (Chrome: a new window).+ if (user_gesture && target_disposition == CEF_WOD_NEW_WINDOW+ && [o.delegate respondsToSelector:@selector(browser:opensPeekForURL:shiftClick:)]+ && [o.delegate browser:o opensPeekForURL:NSStringFromCef(target_url) shiftClick:YES]) return true;BOOL background = (target_disposition == CEF_WOD_NEW_BACKGROUND_TAB);[o.delegate browser:o requestsNewTabWithURL:NSStringFromCef(target_url) inBackground:background];return true;@@ -1506,6 +1533,7 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {if (!_isIncognito && !ProfileReady(_profilePath, self)) return;if (g_chromeHosting) {CefBrowserSettings settings;+ CraPageSettings(settings);CefRefPtr<CefBrowserView> view = CefBrowserView::CreateBrowserView(_client, CefStringFromNS(_pendingURL ?: @"about:blank"), settings, nullptr,[self requestContext], new CraChromeViewDelegate(self));@@ -1518,6 +1546,7 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {CefRect(0, 0, (int)MAX(b.size.width, 1), (int)MAX(b.size.height, 1)));if (g_useChromeStyle) windowInfo.runtime_style = CEF_RUNTIME_STYLE_CHROME;CefBrowserSettings settings;+ CraPageSettings(settings);CefBrowserHost::CreateBrowser(windowInfo, _client, CefStringFromNS(_pendingURL ?: @"about:blank"), settings,nullptr, [self requestContext]);}diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.hindex 46306a1..08ac136 100644--- a/Sources/CraCEF/include/CraCEF.h+++ b/Sources/CraCEF/include/CraCEF.h@@ -81,6 +81,10 @@ 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;+/// 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.+- (BOOL)browser:(CraBrowser *)browser opensPeekForURL:(NSString *)url shiftClick:(BOOL)shiftClick;@end@interface CraBrowser : NSObjectdiff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swiftindex e10eea7..f1c7b75 100644--- a/Tests/BrowserManagerLifecycleTests.swift+++ b/Tests/BrowserManagerLifecycleTests.swift@@ -191,4 +191,5 @@ private final class Observer: BrowserManagerDelegate {func browserManagerHandleUnhandledKey(_ event: NSEvent) -> Bool { false }func browserManagerFocusedBrowser(_ tabID: UUID) {}func browserManagerPageClosedTab(_ tabID: UUID) { closedTabs.append(tabID) }+ func browserManagerOpensPeek(url: String, fromTab tabID: UUID, pageURL: String, shiftClick: Bool) -> Bool { false }}diff --git a/Tests/ExtensionPopupCandidateTests.swift b/Tests/ExtensionPopupCandidateTests.swiftindex 8fb7567..79f2975 100644--- a/Tests/ExtensionPopupCandidateTests.swift+++ b/Tests/ExtensionPopupCandidateTests.swift@@ -41,8 +41,13 @@ enum ExtensionPopupCandidateTests {"missing browser ownership fails closed")check(!ExtensionPopupCandidate.matches(bubble, owner: owner, sourceHost: host, isPageHost: { _ in false }),"a non-page parent is rejected")+ check(!ExtensionPopupCandidate.mayBecomePopup(bubble), "a shown bubble is not hidden ahead of time")bubble.orderOut(nil)check(!matches(bubble), "a hidden popup is not ready for placement")+ check(ExtensionPopupCandidate.mayBecomePopup(bubble), "a hidden Chromium bubble is kept transparent until framed")+ badge.orderOut(nil)+ check(!ExtensionPopupCandidate.mayBecomePopup(badge), "a hidden non-Chromium window is left alone")+ badge.orderFront(nil)bubble.orderFront(nil)bubble.styleMask.insert(.titled)check(!matches(bubble), "a separate titled extension window is not an action bubble")diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.mdindex 915f54b..dde3d1d 100644--- a/docs/arc-reverse-engineering.md+++ b/docs/arc-reverse-engineering.md@@ -69,6 +69,22 @@ Legend: [O] observed in shipped artifact or data file, [I] inference, [U] unknowveryRecentTabOrDocumentBoost, derankCurrentItemURL, dedupByTitleAndHostList (figma, notion, github, zoom...).- [O] Type-travel triggers e.g. "Go to Sidebar Item 3" / "3. tab" / "3. item".- [U] Weights of the ranking model (a CoreML tensor, CommandBarRankingTensor) are not recoverable statically.+- [O] Site Search (29 Oct, Little Arc driven by keys posted to its pid, 2x captures): Arc seeds 19 sites into+ Chromium's `keywords` table as active (Drive, Gmail, Maps, Calendar, Docs, Dropbox, Amazon, GitHub, Figma, X,+ twitter.com, YouTube, Wikipedia, Reddit, SoundCloud, Asana, LinkedIn, Apple Music, Spotify; URLs in the binary+ next to `rankCommandBar`); Chromium's auto-added engines stay inactive and never offer it. Text that starts an+ active keyword's host shows "Search <name>" (13 pt semibold, white 0.33) and a "Tab" cap (23 pt, white 0.04 fill,+ 22 pt from the edge) on the input row: "twit" offers X even while completing twitch.tv, "gm" offers nothing+ (Gmail's keyword is mail.google.com). Tab (not Space: the space trigger flag is off) puts a 73×23 pt round pill+ in the site's colour (hard-coded, e.g. YouTube #FF0000, GitHub #743FC7; glow in the same colour) before the+ field, placeholder "Search…", rows reduced to the typed search tinted with that colour. Backspace on the empty+ field drops the pill and puts back what was typed; Escape returns to how the bar opened. Cra: SiteSearch.all.+- [O] Sidebar glyphs (29 Oct, 1x and 2x captures, fitted pixel by pixel): the tab row's hover ✕ is two 2 pt+ round-capped strokes 4.25 pt out from a centre on a whole point, white 0.6 over the hover fill; at 1x it is+ perfectly symmetric (176/142/85), which no SF Symbol size reproduces (xmark 13.5 bold is closest at 2x but+ lands between pixels at 1x). Cra strokes it with a CAShapeLayer (SidebarSymbols.closeMark); an NSImage drawn+ the same way rendered thinner and off-centre at 1x. New Tab's plus fits SF plus 14.5 medium at both scales,+ in the label's colour. The New Space plus is a custom square-ended glyph (14 pt, 2 pt stroke).## Key bindings (StorableKeyBindings.json + strings)- [O] Action = {identifier, name}; binding = {keyEquivalent, deviceIndependentModifierFlags}, priority, typeTravelTriggers;@@ -163,8 +179,11 @@ Other measured details: window buttons are muted grey discs (bg −10 %) until treaches the sidebar's title row; favicons 16 pt centred 25.75 pt from the window edge; spaceheader 14 pt medium with no top padding above it; favorites tiles 72 × 47 with 8 pt marginsand gaps; the yellow/black dashed ring (2 pt, systemYellow, 6/6 black dashes) is Arc's-keyboard-focus indicator, shown on a tab chosen without the mouse (it appeared on every-tab selected through AppleScript, never on clicked ones). Host subtitles under pinned+keyboard-focus indicator, shown on a tab chosen without the mouse, never on clicked ones.+Re-measured 29 Oct (issue #12, ScreenCaptureKit frames every ~60 ms): an AppleScript select+of a tab in another space switched the space and drew the ring ~0.4 s later, still there+2.5 s on; a select within the shown space drew none. Cra rings only a tab switcher pick+that changed space; next/previous tab and ⌘1–9 stay in the space and show no ring. Host subtitles under pinnedtabs appear only when the tab left the pinned host (Phantom at /signin shows none); the"Ahrefs / ahrefs.com" row in Arc stays unexplained (same host, same URL, loaded).@@ -1566,3 +1585,19 @@ GitHub issue #4: opening in window B a tab that window A shows left A with no ta(`PaneCardView.elsewhereSnapshot`, the tab switcher's thumbnail) and takes the page back when it becomes key ormain. Windows restored at launch leave the page to the window in use, else the first one. Verified on a renamedtest bundle with two windows on the same tab: page and blur swap each time the other window becomes main.++### Favorites grid columns and Peek (Arc 1.170, 29 Oct 2026, issue #12)+- [O live] Favorites columns by sidebar width (4 favorites; `sidebarWidth` set in StorableWindows.json with Arc+ quit, 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:)`.+- [O static] Peek is a Little Arc presented modally (`littleWindowViewController`, `presentModally`,+ `modalState`, `peekedModalControlsAlternateOrderEnabled`). Links ▸ "Open a Peek window when clicking on links to+ other sites" (note: "This only affects Favorites and Pinned tabs"; key `modalEnabled`) and "Open a Peek window+ when clicking on links with Shift held" (`shiftClickModalEntryPointEnabled`); "Exit the current context. Such+ as closing a Peek window"; "Undo prompt for re-opening a closed Peek". Not seen live (needs a real click).+- Cra: a Little Window docked over the page area (6 %/5 % inset), a 25 % black shade over the browser window+ that 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 tab+ stayed, promote and ⌘W worked.diff --git a/scripts/cef-patches/extension-popup-no-popout-wait.patch b/scripts/cef-patches/extension-popup-no-popout-wait.patchnew file mode 100644index 0000000..109cd68--- /dev/null+++ b/scripts/cef-patches/extension-popup-no-popout-wait.patch@@ -0,0 +1,42 @@+diff --git a/chrome/browser/ui/views/extensions/extensions_toolbar_desktop.cc b/chrome/browser/ui/views/extensions/extensions_toolbar_desktop.cc+index db2447a0db..f714ad282b 100644+--- a/chrome/browser/ui/views/extensions/extensions_toolbar_desktop.cc++++ b/chrome/browser/ui/views/extensions/extensions_toolbar_desktop.cc+@@ -12,6 +12,7 @@+ #include "base/functional/callback_helpers.h"+ #include "base/no_destructor.h"+ #include "base/scoped_observation.h"++#include "base/task/sequenced_task_runner.h"+ #include "base/time/time.h"+ #include "build/build_config.h"+ #include "chrome/app/vector_icons/vector_icons.h"+@@ -68,6 +69,10 @@+ #include "ui/views/widget/widget.h"+ #include "ui/views/widget/widget_observer.h"+++#if BUILDFLAG(ENABLE_CEF)++#include "cef/libcef/browser/chrome/browser_delegate.h"++#endif+++ namespace {++ class IphWidgetActivationObserver : public views::WidgetObserver {+@@ -633,6 +638,18 @@ void ExtensionsToolbarDesktop::PopOutAction(+ DCHECK(!popped_out_action_.has_value());+ popped_out_action_ = action_id;+ UpdateIconVisibility(action_id);++#if BUILDFLAG(ENABLE_CEF)++ // Cra: the toolbar is hidden under Cra's own, so nobody sees the icon pop out++ // and waiting for its 250 ms animation only delays the popup. Snap to the new++ // layout and open the popup right away.++ if (browser_->cef_delegate() && browser_->cef_delegate()->IsViewsHosted()) {++ UpdateContainerVisibility();++ GetAnimatingLayoutManager()->ResetLayout();++ base::SequencedTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE,++ std::move(closure));++ return;++ }++#endif+ GetAnimatingLayoutManager()->PostOrQueueAction(std::move(closure));+ UpdateContainerVisibility();+ }diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.shindex ef54d75..65218b2 100755--- a/scripts/fetch-cef.sh+++ b/scripts/fetch-cef.sh@@ -13,7 +13,7 @@ CEF_VERSION="${CEF_VERSION:-156.0.14+g4fa4ab5+chromium-156.0.8078.48}"ARCH="${CEF_ARCH:-macosarm64}"NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"# Bump the suffix (codecs2, …) when the build changes but CEF_VERSION does not.-CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs3}"+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs4}"URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"mkdir -p vendor