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.
Command bar: Chromium's search engines, ⌥Return opens a split, Arc's scope bounce and glow; Arc's folder hinge, ⌘ + New Tab pastes, ⇧⌘⌫ clears browsing data (#151)
Victor Kildahlf06802bb80a2
diff --git a/Packages/CraCore/Sources/CraCore/BrowsingDataClear.swift b/Packages/CraCore/Sources/CraCore/BrowsingDataClear.swiftindex 2a3e878..a6926d6 100644--- a/Packages/CraCore/Sources/CraCore/BrowsingDataClear.swift+++ b/Packages/CraCore/Sources/CraCore/BrowsingDataClear.swift@@ -72,4 +72,12 @@ public enum BrowsingDataClear {.filter { !$0.value.isEmpty }return (kept, r)}++ /// The archive without the tabs closed inside `range`. Cra's History (⌘Y) is its archive, and+ /// the command bar lists archived tabs ("Archived 7 days ago"), so they go with the history, as+ /// Chrome's recently closed tabs do. Reported on X, 2 Nov 2026: results from 7 or 8 days ago+ /// stayed after the history was cleared.+ public static func keptArchive(_ archive: [ArchivedItem], clearing range: Range) -> [ArchivedItem] {+ archive.filter { !range.contains($0.archivedAt) }+ }}diff --git a/Packages/CraCore/Sources/CraCore/KeyChord.swift b/Packages/CraCore/Sources/CraCore/KeyChord.swiftindex 3fd8b59..d509e7d 100644--- a/Packages/CraCore/Sources/CraCore/KeyChord.swift+++ b/Packages/CraCore/Sources/CraCore/KeyChord.swift@@ -35,6 +35,9 @@ public struct KeyChord: Codable, Hashable {public static let right = "\u{F703}"public static let up = "\u{F700}"public static let down = "\u{F701}"+ /// The Delete key as a menu's key equivalent wants it (NSBackspaceCharacter), shown ⌫.+ /// Its key events carry U+007F, which the app reads as this.+ public static let delete = "\u{8}"/// How menus and the command bar show it: ⌃⌥⇧⌘ in Apple's order, then the key.public var display: String {@@ -49,6 +52,7 @@ public struct KeyChord: Codable, Hashable {case Self.right: s += "→"case Self.up: s += "↑"case Self.down: s += "↓"+ case Self.delete: s += "⌫"default: s += key.uppercased()}return sdiff --git a/Packages/CraCore/Sources/CraCore/SiteSearch.swift b/Packages/CraCore/Sources/CraCore/SiteSearch.swiftnew file mode 100644index 0000000..7aedd30--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/SiteSearch.swift@@ -0,0 +1,244 @@+import Foundation++/// One of Chromium's search engines, as chrome://settings/searchEngines lists and edits them: a+/// row of the profile's `keywords` table (Web Data), or its default engine, which the profile's+/// `default_search_provider_data.template_url_data` pref holds once one is picked. Arc's command+/// bar is Chromium's omnibox, so the default searches what is typed and an active keyword takes+/// Tab; Cra kept an engine list of its own and ignored both (reported on X, 2 Nov 2026: custom+/// engines did nothing, nor did editing the built-in ones).+public struct ChromiumSearchEngine: Equatable, Sendable {+ public var id: Int64+ public var name: String+ public var keyword: String+ /// Chromium's template: `{searchTerms}` and its other placeholders.+ public var url: String+ public var suggestURL: String+ public var faviconURL: String+ /// Chromium's built-in engines have one (Google 1, Bing 3, DuckDuckGo 92…).+ public var prepopulateID: Int+ /// Chromium may replace it: built-in and auto-added rows, until the user edits them.+ public var safeForAutoreplace: Bool+ /// TemplateURLData::ActiveStatus: 0 unspecified, 1 active, 2 deactivated.+ public var isActive: Int+ /// @bookmarks, @history, @tabs, @gemini…: Chrome's own pages, which Cra has no use for.+ public var starterPackID: Int+ public var syncGUID: String++ public init(id: Int64 = 0, name: String, keyword: String, url: String, suggestURL: String = "", faviconURL: String = "",+ prepopulateID: Int = 0, safeForAutoreplace: Bool = false, isActive: Int = 1, starterPackID: Int = 0, syncGUID: String = "") {+ self.id = id+ self.name = name+ self.keyword = keyword+ self.url = url+ self.suggestURL = suggestURL+ self.faviconURL = faviconURL+ self.prepopulateID = prepopulateID+ self.safeForAutoreplace = safeForAutoreplace+ self.isActive = isActive+ self.starterPackID = starterPackID+ self.syncGUID = syncGUID+ }++ public func searchURL(_ query: String) -> String { Self.expand(url, query: query) }++ /// The engine's suggest endpoint for `query`, nil when it has none.+ public func suggestURL(_ query: String) -> URL? {+ // Google's own template asks for an answer behind an XSSI guard (`xssi=t`) and a session+ // only the omnibox has; its plain endpoint is the one Cra always used.+ let template = suggestURL.hasPrefix("{google:baseSuggestURL}") ? Self.googleSuggest : suggestURL+ return template.isEmpty ? nil : URL(string: Self.expand(template, query: query))+ }++ private static let googleSuggest = "https://www.google.com/complete/search?client=chrome&ie=utf-8&oe=utf-8&q={searchTerms}"++ /// The settings page's "Search engines" list, the ones the picker offers: Chromium's own and+ /// whichever is the default.+ public var isBuiltIn: Bool { prepopulateID > 0 }++ /// Tab on its keyword scopes the bar to it, as Chromium's keyword mode does: an engine the+ /// user added, edited or activated, or a built-in one; not the sites Chromium adds by itself+ /// as you browse (inactive until activated, Arc 1.170) or the starter pack.+ public var takesTab: Bool {+ starterPackID == 0 && isActive != 2 && (isActive == 1 || !safeForAutoreplace || prepopulateID > 0)+ }++ // MARK: Templates++ /// Google's own placeholders resolve to its host; Chrome fills the rest in from the browser's+ /// state (RLZ, field trials, the page's URL), which a search from the bar has none of.+ private static let fixed: [String: String] = [+ "searchTerms": "", "inputEncoding": "UTF-8", "outputEncoding": "UTF-8",+ "google:baseURL": "https://www.google.com/", "google:baseSuggestURL": "https://www.google.com/complete/",+ "google:suggestPath": "search", "google:suggestClient": "chrome",+ ]++ /// Chromium's TemplateURLRef replacement for a typed query: `{searchTerms}` is the query+ /// percent-encoded, `{language}` the first preferred language, the known Google ones their+ /// values, and every other placeholder, optional (`{startPage?}`) or not, nothing. A query+ /// parameter left without a value goes too.+ public static func expand(_ template: String, query: String, language: String = "en") -> String {+ var out = ""+ var rest = Substring(template)+ while let open = rest.firstIndex(of: "{") {+ out += rest[..<open]+ guard let close = rest[open...].firstIndex(of: "}") else { out += rest[open...]; rest = ""; break }+ let name = String(rest[rest.index(after: open)..<close])+ switch name {+ case "searchTerms": out += encode(query)+ case "language": out += language+ default: out += fixed[name] ?? ""+ }+ rest = rest[rest.index(after: close)...]+ }+ out += rest+ return tidyQuery(out)+ }++ /// Unreserved characters stay, everything else is %-encoded (a space as %20).+ private static func encode(_ s: String) -> String {+ var allowed = CharacterSet.alphanumerics+ allowed.insert(charactersIn: "-._~")+ return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s+ }++ /// Drops what emptied placeholders leave in the query: "search?q=a&&gs_ri=&ie=UTF-8&" →+ /// "search?q=a&ie=UTF-8".+ private static func tidyQuery(_ url: String) -> String {+ guard let q = url.firstIndex(of: "?") else { return url }+ let hashAt = url[q...].firstIndex(of: "#") ?? url.endIndex+ let parts = url[url.index(after: q)..<hashAt].split(separator: "&", omittingEmptySubsequences: true).filter { !$0.hasSuffix("=") }+ let query = parts.joined(separator: "&")+ return String(url[..<q]) + (query.isEmpty ? "" : "?" + query) + url[hashAt...]+ }++ // MARK: The default engine pref++ /// `default_search_provider_data.template_url_data` (or its mirror) as Chromium writes it;+ /// nil when it holds no engine.+ public init?(templateURLData d: [String: Any]) {+ guard let name = d["short_name"] as? String, let keyword = d["keyword"] as? String, let url = d["url"] as? String,+ !name.isEmpty, !keyword.isEmpty, !url.isEmpty else { return nil }+ func int(_ key: String) -> Int { (d[key] as? Int) ?? (d[key] as? String).flatMap { Int($0) } ?? 0 }+ self.init(id: Int64(int("id")), name: name, keyword: keyword, url: url, suggestURL: d["suggestions_url"] as? String ?? "",+ faviconURL: d["favicon_url"] as? String ?? "", prepopulateID: int("prepopulate_id"),+ safeForAutoreplace: d["safe_for_autoreplace"] as? Bool ?? false, isActive: int("is_active"),+ starterPackID: int("starter_pack_id"), syncGUID: d["synced_guid"] as? String ?? "")+ }++ /// What Cra writes to that pref to make this the default, in Chromium's own keys+ /// (TemplateURLDataToDictionary). Chromium finds the engine by its GUID and makes it the default.+ public var templateURLData: [String: Any] {+ var d: [String: Any] = [+ "short_name": name, "keyword": keyword, "url": url, "suggestions_url": suggestURL, "favicon_url": faviconURL,+ "prepopulate_id": prepopulateID, "safe_for_autoreplace": safeForAutoreplace, "is_active": isActive,+ "starter_pack_id": starterPackID, "input_encodings": ["UTF-8"], "alternate_urls": [String](),+ "date_created": "0", "last_modified": "0", "usage_count": 0,+ ]+ if id != 0 { d["id"] = String(id) }+ if !syncGUID.isEmpty { d["synced_guid"] = syncGUID }+ return d+ }++ // MARK: Cra's own list (settings.json `searchEngine`)++ /// What Cra's engine setting meant, as Chromium would hold it: the default until Chromium has+ /// one of its own, and the engine an older setting moves to Chromium (Kagi isn't built in).+ public init(_ legacy: SearchEngine) {+ switch legacy {+ case .google:+ self.init(name: "Google", keyword: "google.com", url: "{google:baseURL}search?q={searchTerms}&ie={inputEncoding}",+ suggestURL: Self.googleSuggest,+ faviconURL: "https://www.google.com/favicon.ico", prepopulateID: 1, safeForAutoreplace: true, isActive: 0)+ case .duckduckgo:+ self.init(name: "DuckDuckGo", keyword: "duckduckgo.com", url: "https://duckduckgo.com/?q={searchTerms}",+ suggestURL: "https://duckduckgo.com/ac/?q={searchTerms}&type=list",+ faviconURL: "https://duckduckgo.com/favicon.ico", prepopulateID: 92, safeForAutoreplace: true, isActive: 0)+ case .bing:+ self.init(name: "Microsoft Bing", keyword: "bing.com", url: "https://www.bing.com/search?q={searchTerms}",+ suggestURL: "https://www.bing.com/osjson.aspx?query={searchTerms}",+ faviconURL: "https://www.bing.com/favicon.ico", prepopulateID: 3, safeForAutoreplace: true, isActive: 0)+ case .kagi:+ self.init(name: "Kagi", keyword: "kagi.com", url: "https://kagi.com/search?q={searchTerms}",+ suggestURL: "https://kagi.com/api/autosuggest?q={searchTerms}", faviconURL: "https://kagi.com/favicon.ico")+ }+ }++ /// The built-in row an older Cra setting means (same prepopulate id or keyword), else that+ /// setting as an engine of its own.+ public static func migrating(_ legacy: SearchEngine, among engines: [ChromiumSearchEngine]) -> ChromiumSearchEngine {+ let wanted = ChromiumSearchEngine(legacy)+ return engines.first { $0.prepopulateID > 0 && $0.prepopulateID == wanted.prepopulateID }+ ?? engines.first { $0.keyword.lowercased() == wanted.keyword }+ ?? wanted+ }+}++/// What Tab scopes the command bar to on a site (Arc's Site Search): one of Arc's sites, or one+/// of Chromium's keywords.+public struct SiteSearch: Equatable, Sendable {+ public let name: String+ /// What the typed text has to start (Chromium's keyword).+ public let host: String+ /// `%s` (Arc's list) or Chromium's template.+ public let url: String+ /// The pill's colour, "#RRGGBB"; nil takes the space's, as the tabs scope does.+ public let color: String?++ public init(name: String, host: String, url: String, color: String?) {+ self.name = name+ self.host = host+ self.url = url+ self.color = color+ }++ public init(_ engine: ChromiumSearchEngine) {+ let arc = Self.all.first { $0.host == engine.keyword.lowercased() }+ self.init(name: engine.name, host: engine.keyword, url: engine.url, color: arc?.color)+ }++ public func searchURL(_ query: String) -> String {+ if url.contains("{") { return ChromiumSearchEngine.expand(url, query: query) }+ 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. Chromium's keywords come in around Arc's sites: one+ /// typed out in full wins ("goo" for a Google edited to that), one started only after Arc's+ /// sites have had their turn, and from two letters on.+ public static func match(_ q: String, completion: String?, keywords: [ChromiumSearchEngine] = []) -> SiteSearch? {+ var t = q.lowercased()+ if t.hasPrefix("www.") { t.removeFirst(4) }+ guard !t.isEmpty, !t.contains(" "), !t.contains("/") else { return nil }+ let offered = keywords.filter(\.takesTab)+ if let exact = offered.first(where: { $0.keyword.lowercased() == t }) { return SiteSearch(exact) }+ if let completion, let site = all.first(where: { $0.host == completion && $0.host.hasPrefix(t) }) { return site }+ if let site = all.first(where: { $0.host.hasPrefix(t) }) { return site }+ guard t.count >= 2 else { return nil }+ return offered.first { $0.keyword.lowercased().hasPrefix(t) }.map(SiteSearch.init)+ }++ /// Arc 1.170's list, in its order; colours measured off its pills.+ public 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"),+ ]+}diff --git a/Packages/CraCore/Tests/CraCoreTests/BrowsingDataClearTests.swift b/Packages/CraCore/Tests/CraCoreTests/BrowsingDataClearTests.swiftindex 232f2b7..96906e2 100644--- a/Packages/CraCore/Tests/CraCoreTests/BrowsingDataClearTests.swift+++ b/Packages/CraCore/Tests/CraCoreTests/BrowsingDataClearTests.swift@@ -63,4 +63,16 @@ struct BrowsingDataClearTests {let out = BrowsingDataClear.clearing(.before(now.addingTimeInterval(-30 * 86400)), history: [old.url: old, new.url: new], ranking: RankingData())#expect(Array(out.history.keys) == [new.url])}++ /// Archived tabs show in the command bar ("Archived 7 days ago"): those closed in the range go.+ @Test func archivedTabsInTheRangeGo() {+ func archived(_ daysAgo: Double) -> ArchivedItem {+ ArchivedItem(archivedAt: now.addingTimeInterval(-daysAgo * 86400), reason: .manual, sourceSpaceID: nil, wasPinned: false,+ item: .tab("https://\(Int(daysAgo)).example/", parent: nil))+ }+ let archive = [archived(0.01), archived(3), archived(8), archived(40)]+ #expect(BrowsingDataClear.keptArchive(archive, clearing: .since(now.addingTimeInterval(-7 * 86400))) == Array(archive[2...]))+ #expect(BrowsingDataClear.keptArchive(archive, clearing: .before(now.addingTimeInterval(-30 * 86400))) == Array(archive[..<3]))+ #expect(BrowsingDataClear.keptArchive(archive, clearing: .allTime).isEmpty)+ }}diff --git a/Packages/CraCore/Tests/CraCoreTests/KeyChordTests.swift b/Packages/CraCore/Tests/CraCoreTests/KeyChordTests.swiftindex beed7ad..0915b58 100644--- a/Packages/CraCore/Tests/CraCoreTests/KeyChordTests.swift+++ b/Packages/CraCore/Tests/CraCoreTests/KeyChordTests.swift@@ -22,6 +22,8 @@ struct KeyChordTests {(KeyChord(key: KeyChord.right, modifiers: command), "⌘→"),(KeyChord(key: KeyChord.up, modifiers: KeyChord.Modifiers([.control, .option, .shift, .command]).rawValue), "⌃⌥⇧⌘↑"),(KeyChord(key: KeyChord.down, modifiers: 0), "↓"),+ // Chrome's Clear Browsing Data; menus take the Delete key as NSBackspaceCharacter.+ (KeyChord(key: KeyChord.delete, modifiers: command | KeyChord.Modifiers.shift.rawValue), "⇧⌘⌫"),// Caps Lock and the function-key bit are kept in the file but never shown.(KeyChord(key: "d", modifiers: command | 0x10000 | 0x800000), "⌘D"),])diff --git a/Packages/CraCore/Tests/CraCoreTests/SiteSearchTests.swift b/Packages/CraCore/Tests/CraCoreTests/SiteSearchTests.swiftnew file mode 100644index 0000000..5507539--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/SiteSearchTests.swift@@ -0,0 +1,110 @@+import CraCore+import Foundation+import Testing++/// Chromium's search engines in the command bar: its default searches what is typed, and its+/// keywords take Tab next to Arc's sites (reported on X, 2 Nov 2026).+struct SiteSearchTests {+ /// Rows as Chromium 156 keeps them in Web Data (Cra's own profile, 3 Nov 2026).+ static let google = ChromiumSearchEngine(+ id: 9, name: "Google", keyword: "google.com",+ url: "{google:baseURL}search?q={searchTerms}&{google:RLZ}{google:originalQueryForSuggestion}{google:assistedQueryStats}{google:searchFieldtrialParameter}{google:language}{google:prefetchSource}{google:searchClient}{google:sourceId}{google:searchSource}{google:contextualSearchVersion}ie={inputEncoding}",+ suggestURL: "{google:baseSuggestURL}{google:suggestPath}?{google:searchFieldtrialParameter}client={google:suggestClient}&gs_ri={google:suggestRid}&xssi=t&q={searchTerms}&{google:inputType}sugkey={google:suggestAPIKeyParameter}",+ prepopulateID: 1, safeForAutoreplace: true, isActive: 0, syncGUID: "485bf7d3-0215-45af-87dc-538868000001")+ static let yahoo = ChromiumSearchEngine(+ id: 5, name: "Yahoo Search", keyword: "dk.yahoo.com", url: "https://dk.search.yahoo.com/search{google:pathWildcard}?ei={inputEncoding}&p={searchTerms}",+ prepopulateID: 2, safeForAutoreplace: true, isActive: 0)+ static let duck = ChromiumSearchEngine(+ id: 6, name: "DuckDuckGo", keyword: "duckduckgo.com", url: "https://duckduckgo.com/?q={searchTerms}",+ suggestURL: "https://duckduckgo.com/ac/?q={searchTerms}&type=list", prepopulateID: 92, safeForAutoreplace: true, isActive: 0)+ /// Added by Chromium while browsing YouTube: inactive, so no Tab.+ static let autoYouTube = ChromiumSearchEngine(+ id: 16, name: "YouTube", keyword: "youtube.com", url: "https://www.youtube.com/results?search_query={searchTerms}&page={startPage?}&utm_source=opensearch",+ safeForAutoreplace: true, isActive: 0)+ static let history = ChromiumSearchEngine(id: 11, name: "History", keyword: "@history", url: "chrome://history/?q={searchTerms}",+ safeForAutoreplace: true, isActive: 1, starterPackID: 2)+ /// Added on the settings page.+ static let wiki = ChromiumSearchEngine(id: 30, name: "Wikipedia DA", keyword: "wda", url: "https://da.wikipedia.org/w/index.php?search={searchTerms}")++ @Test func googleExpandsWithoutTheOmniboxState() {+ #expect(Self.google.searchURL("hello world") == "https://www.google.com/search?q=hello%20world&ie=UTF-8")+ // The plain endpoint, not the XSSI-guarded omnibox one.+ #expect(Self.google.suggestURL("a&b")?.absoluteString == "https://www.google.com/complete/search?client=chrome&ie=utf-8&oe=utf-8&q=a%26b")+ }++ @Test func otherTemplates() {+ #expect(Self.yahoo.searchURL("ø") == "https://dk.search.yahoo.com/search?ei=UTF-8&p=%C3%B8")+ #expect(Self.duck.suggestURL("c++")?.absoluteString == "https://duckduckgo.com/ac/?q=c%2B%2B&type=list")+ #expect(Self.autoYouTube.searchURL("lofi") == "https://www.youtube.com/results?search_query=lofi&utm_source=opensearch")+ #expect(ChromiumSearchEngine.expand("https://e.example/?q={searchTerms}&mkt={language}#top", query: "x", language: "da") == "https://e.example/?q=x&mkt=da#top")+ #expect(Self.wiki.suggestURL("x") == nil)+ }++ @Test func whichKeywordsTakeTab() {+ #expect(Self.google.takesTab && Self.duck.takesTab && Self.wiki.takesTab)+ #expect(!Self.autoYouTube.takesTab && !Self.history.takesTab)+ var activated = Self.autoYouTube+ activated.isActive = 1+ #expect(activated.takesTab)+ var deactivated = Self.wiki+ deactivated.isActive = 2+ #expect(!deactivated.takesTab)+ }++ @Test func keywordsAroundArcsSites() {+ let keywords = [Self.google, Self.duck, Self.autoYouTube, Self.history, Self.wiki]+ // Typed out in full: the keyword, before Arc's sites ("goo" for a Google edited to that).+ var edited = Self.google+ edited.keyword = "goo"+ edited.safeForAutoreplace = false+ #expect(SiteSearch.match("goo", completion: nil, keywords: [edited])?.name == "Google")+ #expect(SiteSearch.match("wda", completion: nil, keywords: keywords)?.url == Self.wiki.url)+ // Arc's sites first for what only starts a host; Chromium's next, from two letters on.+ #expect(SiteSearch.match("you", completion: nil, keywords: keywords)?.color == "#FF0000")+ #expect(SiteSearch.match("duck", completion: nil, keywords: keywords)?.name == "DuckDuckGo")+ let kagi = ChromiumSearchEngine(.kagi)+ #expect(SiteSearch.match("k", completion: nil, keywords: [kagi]) == nil)+ #expect(SiteSearch.match("ka", completion: nil, keywords: [kagi])?.name == "Kagi")+ #expect(SiteSearch.match("@hist", completion: nil, keywords: keywords) == nil)+ #expect(SiteSearch.match("duck", completion: nil, keywords: [])?.name == nil)+ // A keyword on one of Arc's hosts keeps Arc's colour; others take the space's.+ var youtube = Self.autoYouTube+ youtube.isActive = 1+ youtube.keyword = "yt"+ #expect(SiteSearch(youtube).color == nil)+ youtube.keyword = "youtube.com"+ #expect(SiteSearch(youtube).color == "#FF0000")+ #expect(SiteSearch(Self.wiki).searchURL("a b") == "https://da.wikipedia.org/w/index.php?search=a%20b")+ }++ /// Arc's own list keeps its `%s` URLs.+ @Test func arcsSitesStillSearch() {+ #expect(SiteSearch.match("twit", completion: "twitch.tv")?.host == "twitter.com")+ #expect(SiteSearch.match("gm", completion: nil) == nil)+ #expect(SiteSearch.all.first { $0.name == "YouTube" }?.searchURL("a&b") == "https://www.youtube.com/results?search_query=a%26b")+ }++ /// The pref Chromium keeps the default in, read and written in its own keys.+ @Test func defaultEnginePref() throws {+ let mirrored: [String: Any] = ["id": "9", "short_name": "Google", "keyword": "google.com", "url": Self.google.url,+ "suggestions_url": Self.google.suggestURL, "prepopulate_id": 1, "safe_for_autoreplace": true,+ "is_active": 0, "starter_pack_id": 0, "synced_guid": Self.google.syncGUID]+ #expect(ChromiumSearchEngine(templateURLData: mirrored) == Self.google)+ #expect(ChromiumSearchEngine(templateURLData: [:]) == nil)+ let data = Self.duck.templateURLData+ #expect(data["synced_guid"] == nil && data["id"] as? String == "6" && data["prepopulate_id"] as? Int == 92)+ let json = try JSONSerialization.data(withJSONObject: data)+ let back = try #require(JSONSerialization.jsonObject(with: json) as? [String: Any])+ #expect(ChromiumSearchEngine(templateURLData: back) == Self.duck)+ }++ /// Cra's older engine setting moves to Chromium as its built-in row, or as an engine of its own.+ @Test func migratingCrasSetting() {+ let rows = [Self.google, Self.duck]+ #expect(ChromiumSearchEngine.migrating(.duckduckgo, among: rows) == Self.duck)+ #expect(ChromiumSearchEngine.migrating(.bing, among: rows).url == "https://www.bing.com/search?q={searchTerms}")+ let kagi = ChromiumSearchEngine.migrating(.kagi, among: rows)+ #expect(kagi.keyword == "kagi.com" && !kagi.isBuiltIn && kagi.searchURL("x") == "https://kagi.com/search?q=x")+ #expect(ChromiumSearchEngine(.google).searchURL("x") == "https://www.google.com/search?q=x&ie=UTF-8")+ }+}diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex 853e7bb..691521b 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -645,6 +645,29 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {}return}+ // What the command bar would list for the text (rows, the Tab scope, the search), without opening it.+ if let text = dict["suggest"] {+ let engine = main.commandBar.engine+ engine.resetIndex()+ let r = engine.suggestions(for: text, mode: .newTab, currentTabID: store.selectedTabID)+ let rows = r.items.map { "\($0.kind) \($0.title) \($0.url ?? "")" }.joined(separator: " | ")+ NSLog("Cra suggest %@ → scope=%@ search=%@ rows=%@", text, r.scope.map { "\($0.name) \($0)" } ?? "none",+ engine.searchURL(text), rows)+ engine.resetIndex()+ return+ }+ // folder=<id>,1 opens a folder, ,0 closes it (its glyph turns as a click's does).+ if let f = dict["folder"]?.split(separator: ","), f.count == 2, let id = UUID(uuidString: String(f[0])) {+ store.setExpanded(id, f[1] == "1")+ return+ }+ // Settings ▸ Advanced's search engine picker, by keyword.+ if let keyword = dict["searchEngine"] {+ if let e = SearchEngines.shared.keywords(profilePath: nil).first(where: { $0.keyword == keyword }) {+ SearchEngines.shared.setDefault(e, store: store)+ }+ return+ }if let spikeURL = dict["chromeSpike"] {CraCEFRuntime.spikeChromeWindow(withURL: spikeURL) { [weak self] w inguard let self, let host = self.main.window else { return }@@ -917,6 +940,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {case "importData": main.showImport()case "rebuildArcProfiles": ArcProfileRebuilder.run(store: store) { [weak self] in self?.relaunch() }case "setDefaultBrowser": Task { await SystemIntegration.shared.makeDefaultBrowser() }+ case "clearBrowsingData":+ // Chrome's dialog, in a normal window: what it deletes from history leaves the command bar too.+ let normal = useNormalWindow()+ _ = store.createTab(url: BrowsingDataClear.pageURL, select: true)+ normal.showWindow(nil)default:if id.hasPrefix("item"), let n = Int(id.dropFirst(4)) {let tabs = store.visibleTabs(in: store.focusedSpaceID)@@ -1003,6 +1031,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {let setDefault = item("setDefaultBrowser")if setDefault.keyEquivalent.isEmpty { setDefault.keyEquivalent = "♡"; setDefault.keyEquivalentModifierMask = .command }appMenu.addItem(setDefault)+ appMenu.addItem(item("clearBrowsingData"))appMenu.addItem(.separator())appMenu.addItem(item("importData"))let update = NSMenuItem(title: "Check for Updates…", action: #selector(SoftwareUpdater.checkForUpdates(_:)), keyEquivalent: "")diff --git a/Sources/Cra/App/KeyBindings.swift b/Sources/Cra/App/KeyBindings.swiftindex 26ad3d6..fec3d9d 100644--- a/Sources/Cra/App/KeyBindings.swift+++ b/Sources/Cra/App/KeyBindings.swift@@ -13,8 +13,8 @@ extension Shortcut {var flags: NSEvent.ModifierFlags { NSEvent.ModifierFlags(rawValue: modifiers) }/// Shift turns "[" into "{" in charactersIgnoringModifiers; undo that.- /// ⇧Tab arrives as backtab (U+0019).- private static let unshift: [String: String] = ["\u{19}": Shortcut.tab, "{": "[", "}": "]", "<": ",", ">": ".", "?": "/", "+": "=", "_": "-", "~": "`", ":": ";", "\"": "'", "|": "\\"]+ /// ⇧Tab arrives as backtab (U+0019), the Delete key as U+007F.+ private static let unshift: [String: String] = ["\u{19}": Shortcut.tab, "\u{7F}": Shortcut.delete, "{": "[", "}": "]", "<": ",", ">": ".", "?": "/", "+": "=", "_": "-", "~": "`", ":": ";", "\"": "'", "|": "\\"]/// Physical-key fallbacks so ⌘[ / ⌘] work on layouts (Danish, German...)/// where those characters live on other keys. Key codes are ANSI positions.@@ -216,6 +216,9 @@ final class KeyBindingRegistry {KeyAction(id: "setDefaultBrowser", name: "Set as Default Browser", section: .app, shortcuts: [], triggers: ["default browser"]),KeyAction(id: "importData", name: "Import from Arc or Dia…", section: .app, shortcuts: [], triggers: ["import", "arc", "dia"]),KeyAction(id: "rebuildArcProfiles", name: "Rebuild Profiles from Arc…", section: .app, shortcuts: [], triggers: ["profiles", "arc profiles"]),+ // Chrome's app menu item and key; Arc has neither, only Settings ▸ Profiles ▸ Clear Browsing Data.+ KeyAction(id: "clearBrowsingData", name: "Clear Browsing Data…", section: .app, shortcuts: [Shortcut(Shortcut.delete, cmdShift)],+ triggers: ["clear history", "delete history", "clear browsing data", "delete browsing data"], symbol: "trash"),]for n in 1...9 {list.append(KeyAction(id: "item\(n)", name: "Go to Tab \(n)", section: .tabs,diff --git a/Sources/Cra/Services/SearchEngines.swift b/Sources/Cra/Services/SearchEngines.swiftnew file mode 100644index 0000000..2826996--- /dev/null+++ b/Sources/Cra/Services/SearchEngines.swift@@ -0,0 +1,102 @@+import CraCEF+import Foundation+import SQLite3++/// Chromium's search engines, which chrome://settings/searchEngines edits (ChromiumSearchEngine):+/// the default from the profile's pref, read live, and the keywords from its Web Data, read again+/// when the file changes. Profiles are named as CraCEFRuntime takes them: nil is Default.+@MainActor+final class SearchEngines {+ static let shared = SearchEngines()++ /// The engine picked on the settings page; empty until one is.+ static let chosenPref = "default_search_provider_data.template_url_data"+ /// Chromium's copy of whichever engine is the default, its built-in one included.+ static let currentPref = "default_search_provider_data.mirrored_template_url_data"+ static let settingsPage = "chrome://settings/searchEngines"++ private var keywordCache: [String: (modified: Date, engines: [ChromiumSearchEngine])] = [:]+ /// Profiles whose older Cra engine setting went to Chromium this run (once, whatever came of it).+ private var migrated: Set<String> = []++ /// The engine typed searches go to. `legacy` is Cra's own setting: Chromium gets it once while+ /// it has no default of its own, and it stands in until the profile has loaded.+ func defaultEngine(profilePath: String?, legacy: SearchEngine) -> ChromiumSearchEngine {+ if let chosen = engine(pref: Self.chosenPref, profilePath: profilePath) { return chosen }+ let key = profilePath ?? ""+ // The pref reads as nil until the profile has loaded, as {} once it has and holds no engine.+ if legacy != .google, !migrated.contains(key), CraCEFRuntime.preference(Self.chosenPref, forProfile: profilePath) != nil {+ migrated.insert(key)+ let engine = ChromiumSearchEngine.migrating(legacy, among: keywords(profilePath: profilePath))+ if setDefault(engine, profilePath: profilePath) { return engine }+ }+ return engine(pref: Self.currentPref, profilePath: profilePath) ?? ChromiumSearchEngine(legacy)+ }++ /// Settings' picker: `engine` becomes the default of every profile that has loaded, as their own+ /// row for it where they have one, and Cra's setting follows so the others take it when they load.+ func setDefault(_ engine: ChromiumSearchEngine, store: SidebarStore) {+ let paths = [nil] + store.profiles.map { AppPaths.chromiumCache.appendingPathComponent($0.directoryName, isDirectory: true).path }+ for path in paths {+ let own = keywords(profilePath: path).first { ($0.isBuiltIn && $0.prepopulateID == engine.prepopulateID) || $0.keyword == engine.keyword }+ setDefault(own ?? engine, profilePath: path)+ }+ if let legacy = SearchEngine.allCases.first(where: { ChromiumSearchEngine($0).keyword == engine.keyword }) {+ store.settings.searchEngine = legacy+ }+ }++ /// Makes `engine` the profile's default, as picking it on the settings page does.+ @discardableResult+ func setDefault(_ engine: ChromiumSearchEngine, profilePath: String?) -> Bool {+ guard let data = try? JSONSerialization.data(withJSONObject: engine.templateURLData),+ let json = String(data: data, encoding: .utf8) else { return false }+ return CraCEFRuntime.setPreference(Self.chosenPref, json: json, forProfile: profilePath)+ }++ private func engine(pref: String, profilePath: String?) -> ChromiumSearchEngine? {+ guard let json = CraCEFRuntime.preference(pref, forProfile: profilePath),+ let d = (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [String: Any] else { return nil }+ return ChromiumSearchEngine(templateURLData: d)+ }++ /// Every row of the profile's keywords table, as the settings page lists them.+ func keywords(profilePath: String?) -> [ChromiumSearchEngine] {+ let dir = profilePath.map { URL(fileURLWithPath: $0, isDirectory: true) } ?? AppPaths.chromiumCache.appendingPathComponent("Default", isDirectory: true)+ let file = dir.appendingPathComponent("Web Data")+ guard let modified = (try? file.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate else { return [] }+ if let hit = keywordCache[file.path], hit.modified == modified { return hit.engines }+ let engines = Self.readKeywords(file)+ keywordCache[file.path] = (modified, engines)+ return engines+ }++ /// Chromium holds the database open with an exclusive lock, so it is read as immutable: no+ /// locks taken, nothing written. A read that lands mid-write gets nothing and the next one,+ /// after the write changes the file's date, tries again.+ nonisolated static func readKeywords(_ file: URL) -> [ChromiumSearchEngine] {+ guard let path = file.path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { return [] }+ var db: OpaquePointer?+ guard sqlite3_open_v2("file:\(path)?immutable=1", &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_URI, nil) == SQLITE_OK else {+ sqlite3_close(db)+ return []+ }+ defer { sqlite3_close(db) }+ let sql = """+ SELECT id, short_name, keyword, url, suggest_url, favicon_url, prepopulate_id, safe_for_autoreplace,+ is_active, starter_pack_id, sync_guid FROM keywords+ """+ var stmt: OpaquePointer?+ guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK else { return [] }+ defer { sqlite3_finalize(stmt) }+ func text(_ i: Int32) -> String { sqlite3_column_text(stmt, i).map { String(cString: $0) } ?? "" }+ var out: [ChromiumSearchEngine] = []+ while sqlite3_step(stmt) == SQLITE_ROW {+ out.append(ChromiumSearchEngine(+ id: sqlite3_column_int64(stmt, 0), name: text(1), keyword: text(2), url: text(3), suggestURL: text(4), faviconURL: text(5),+ prepopulateID: Int(sqlite3_column_int(stmt, 6)), safeForAutoreplace: sqlite3_column_int(stmt, 7) != 0,+ isActive: Int(sqlite3_column_int(stmt, 8)), starterPackID: Int(sqlite3_column_int(stmt, 9)), syncGUID: text(10)))+ }+ return out.filter { !$0.keyword.isEmpty && !$0.url.isEmpty }+ }+}diff --git a/Sources/Cra/Services/SearchSuggestions.swift b/Sources/Cra/Services/SearchSuggestions.swiftindex 6bdf666..8d0be1c 100644--- a/Sources/Cra/Services/SearchSuggestions.swift+++ b/Sources/Cra/Services/SearchSuggestions.swift@@ -32,9 +32,9 @@ final class SearchSuggestions {return langs.enumerated().map { i, l in i == 0 ? l : "\(l);q=\(String(format: "%.1f", 1 - Double(i) * 0.2))" }.joined(separator: ",")}- func items(for query: String, engine: SearchEngine) -> [Item] {+ func items(for query: String, engine: ChromiumSearchEngine) -> [Item] {let q = query.lowercased()- if let hit = cache["\(engine.rawValue)|\(q)"] { return hit }+ if let hit = cache["\(engine.suggestURL)|\(q)"] { return hit }guard let last, pending == q else { return [] }// What still starts the typed text first; the rest only holds the bar's height, since// the engine often corrects the spelling ("ramayyana mov" → "ramayana movie").@@ -43,11 +43,11 @@ final class SearchSuggestions {return narrowed + rest.filter { !narrowed.contains($0) }}- func fetch(_ query: String, engine: SearchEngine, done: @escaping @MainActor () -> Void) {+ func fetch(_ query: String, engine: ChromiumSearchEngine, done: @escaping @MainActor () -> Void) {task?.cancel()pending = nillet q = query.lowercased()- let key = "\(engine.rawValue)|\(q)"+ let key = "\(engine.suggestURL)|\(q)"guard cache[key] == nil, let url = engine.suggestURL(query) else { return }pending = qtask = Task { [session, weak self] indiff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swiftindex 21dcd25..9e80184 100644--- a/Sources/Cra/Services/SidebarStore.swift+++ b/Sources/Cra/Services/SidebarStore.swift@@ -1521,7 +1521,11 @@ final class SidebarStore {/// The Chromium folder a tab's pages load in: its space's profile, or nil for the/// Default profile (and for incognito, which has its own off-the-record one).func profilePath(item id: UUID) -> String? {- guard let sid = spaceID(ofItem: id), !isIncognito(space: sid), let p = profile(spaces[sid]?.profileID) else { return nil }+ spaceID(ofItem: id).flatMap { profilePath(space: $0) }+ }++ func profilePath(space sid: UUID) -> String? {+ guard !isIncognito(space: sid), let p = profile(spaces[sid]?.profileID) else { return nil }return AppPaths.chromiumCache.appendingPathComponent(p.directoryName, isDirectory: true).path}@@ -1613,11 +1617,15 @@ final class SidebarStore {rankingFile.save(ranking)}- /// Chrome's Delete browsing data deleted history: the command bar forgets it too.+ /// Chrome's Delete browsing data deleted history: the command bar forgets it too, and the+ /// archive (Cra's History) drops the tabs closed in that time.func clearHistory(_ range: BrowsingDataClear.Range) {(history, ranking) = BrowsingDataClear.clearing(range, history: history, ranking: ranking)+ archive = BrowsingDataClear.keptArchive(archive, clearing: range)historyFile.saveNow(Array(history.values))rankingFile.saveNow(ranking)+ archiveFile.saveNow(archive)+ touch()CraLog.note("history cleared (\(range == .allTime ? "all time" : "a time range"))")}diff --git a/Sources/Cra/Services/SuggestionEngine.swift b/Sources/Cra/Services/SuggestionEngine.swiftindex 971276e..303148b 100644--- a/Sources/Cra/Services/SuggestionEngine.swift+++ b/Sources/Cra/Services/SuggestionEngine.swift@@ -122,7 +122,8 @@ final class SuggestionEngine {}result.items = Array(items.prefix(Self.maxRows))result.inlineCompletion = completion?.text- result.scope = TabSearchScope.isOffered(by: query) ? .tabs : SiteSearch.match(q, completion: completion?.text).map(CommandBarScope.site)+ result.scope = TabSearchScope.isOffered(by: query) ? .tabs+ : SiteSearch.match(q, completion: completion?.text, keywords: engines.keywords).map(CommandBarScope.site)return result}@@ -200,19 +201,40 @@ final class SuggestionEngine {/// The command bar opened or closed: what it searches may have changed since.func resetIndex() {index = nil+ enginesRead = nilremote.reset()}+ // MARK: Search engines++ private var enginesRead: (default: ChromiumSearchEngine, keywords: [ChromiumSearchEngine])?++ /// Chromium's, in the window's space's profile (an incognito window's are its Default's),+ /// read when the bar opens.+ private var engines: (default: ChromiumSearchEngine, keywords: [ChromiumSearchEngine]) {+ if let enginesRead { return enginesRead }+ let profile = store.profilePath(space: store.focusedSpaceID)+ let read = (SearchEngines.shared.defaultEngine(profilePath: profile, legacy: store.settings.searchEngine),+ SearchEngines.shared.keywords(profilePath: profile))+ enginesRead = read+ return read+ }++ /// Where typed text that isn't an address is searched.+ var searchEngine: ChromiumSearchEngine { engines.default }++ func searchURL(_ text: String) -> String { engines.default.searchURL(text) }+/// Asks the search engine about `rawQuery`; `done` runs when its answer is in, to list again.func fetchSearchSuggestions(for rawQuery: String, done: @escaping @MainActor () -> Void) {let query = rawQuery.trimmingCharacters(in: .whitespaces)guard store.settings.searchSuggestions, !query.isEmpty, !query.contains("://") else { return }- remote.fetch(query, engine: store.settings.searchEngine, done: done)+ remote.fetch(query, engine: searchEngine, done: done)}/// The engine's suggestions not already listed, as search rows (or site rows).private func searchSuggestions(_ query: String, after items: [Suggestion]) -> [Suggestion] {- let engine = store.settings.searchEngine+ let engine = searchEnginelet titles = Set(items.map { $0.title.lowercased() })let urls = Set(items.compactMap(\.url))return remote.items(for: query, engine: engine).compactMap { r in@@ -240,8 +262,8 @@ final class SuggestionEngine {return Suggestion(id: "typed", kind: .navigate, title: query, subtitle: "Open URL", url: url,faviconKey: FaviconKey.key(for: url), symbol: "globe", trailing: nil, score: 1000)}- let engine = store.settings.searchEngine- return Suggestion(id: "typed", kind: .search, title: query, subtitle: "Search \(engine.label)",+ let engine = searchEngine+ return Suggestion(id: "typed", kind: .search, title: query, subtitle: "Search \(engine.name)",url: engine.searchURL(query), faviconKey: nil, symbol: "magnifyingglass", trailing: nil, score: 1000)}@@ -512,55 +534,6 @@ enum CommandBarScope: Equatable {}}-/// 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 1881fd2..440feb0 100644--- a/Sources/Cra/UI/CommandBar/CommandBarController.swift+++ b/Sources/Cra/UI/CommandBar/CommandBarController.swift@@ -41,6 +41,8 @@ final class CommandBarController {var onCommit: (Suggestion?, String, CommandBarMode) -> Void = { _, _, _ in }/// Opens the row in a background tab; false when it has no page to open there.var onOpenInBackground: (Suggestion?, String) -> Bool = { _, _ in false }+ /// Opens the row as a split pane beside the current tab; false when it can't go there.+ var onOpenInSplit: (Suggestion?, String) -> Bool = { _, _ in false }var onClose: () -> Void = {}init(engine: SuggestionEngine, store: SidebarStore) {@@ -203,6 +205,14 @@ final class CommandBarController {onCommit(selected, typed, mode)}+ /// ⌥Return: the row opens in Split View with the current tab. Rows that open no page, and+ /// hosts with no split to make (a Little Window, an empty tab), take it as Return.+ func commitInSplit() {+ guard let (selected, typed) = committed() else { return }+ close()+ if !onOpenInSplit(selected, typed) { onCommit(selected, typed, mode) }+ }+private func committed() -> (Suggestion?, String)? {let selected = result.items.indices.contains(selectedIndex) ? result.items[selectedIndex] : nil// No tab matched: Return has nowhere to go, and the tabs scope never searches the web.diff --git a/Sources/Cra/UI/CommandBar/CommandBarView.swift b/Sources/Cra/UI/CommandBar/CommandBarView.swiftindex 487dde0..fddd88a 100644--- a/Sources/Cra/UI/CommandBar/CommandBarView.swift+++ b/Sources/Cra/UI/CommandBar/CommandBarView.swift@@ -31,6 +31,10 @@ final class CommandBarView: NSView {private var rows: [CommandBarRowView] = []private var syncQueued = falseprivate var attached = false+ /// The scope shown last, to bounce when Tab enters one or Backspace leaves it.+ private var shownScope: CommandBarScope?+ private var splash: NSPanel?+ private var innerSplash: NSView?init(controller: CommandBarController, favicons: FaviconCache) {self.controller = controller@@ -106,9 +110,15 @@ final class CommandBarView: NSView {border.strokeColor = NSColor.labelColor.withAlphaComponent(dark ? 0.12 : 0.08).cgColordivider.layer?.backgroundColor = NSColor.labelColor.withAlphaComponent(0.08).cgColorlet scope = c.scope- // A site's brand colour; the tabs scope takes the space's, the colour of its rows.+ if c.isOpen, (scope == nil) != (shownScope == nil) {+ let site: SiteSearch? = if case .site(let site) = scope { site } else { nil }+ scopeChanged(color: site?.color.map { NSColor(hex: $0) })+ }+ shownScope = c.isOpen ? scope : nil+ // A site's brand colour; the tabs scope and Chromium's other keywords take the space's, the+ // colour of its rows.let highlight: NSColor- if case .site(let site) = scope { highlight = NSColor(hex: site.color) } else { highlight = NSColor(c.highlight) }+ if case .site(let site) = scope, let hex = site.color { highlight = NSColor(hex: hex) } else { highlight = NSColor(c.highlight) }info.isHidden = !c.query.isEmpty || scope != nildivider.isHidden = items.isEmptypill.isHidden = scope == nil@@ -223,6 +233,89 @@ final class CommandBarView: NSView {}}+ // MARK: Entering a scope (Arc's CommandBarContainer, 1.171)++ /// Tab into a scope and Backspace out of it: the bar bounces, and a site's colour washes+ /// through it (Arc's arc_commandBarBounce and SplashView, read from its binary).+ private func scopeChanged(color: NSColor?) {+ bounce()+ splash?.parent?.removeChildWindow(splash!)+ splash?.orderOut(nil)+ splash = nil+ innerSplash?.removeFromSuperview()+ innerSplash = nil+ if let color { showSplash(color) }+ }++ /// A spring toward 0.95 (damping ratio 0.9, response 0.7) cut off after 0.1 s and played+ /// back: the bar dips about 1% and returns within 0.2 s.+ private func bounce() {+ guard let layer else { return }+ let w = layer.bounds.width, h = layer.bounds.height+ // About the bar's centre, whatever anchor AppKit gave the layer.+ let dx = (0.5 - layer.anchorPoint.x) * w, dy = (0.5 - layer.anchorPoint.y) * h+ let scaled = CATransform3DTranslate(CATransform3DScale(CATransform3DMakeTranslation(dx, dy, 0), 0.95, 0.95, 1), -dx, -dy, 0)+ let a = CASpringAnimation(keyPath: "transform")+ a.mass = 1+ a.stiffness = pow(2 * .pi / 0.7, 2)+ a.damping = 4 * .pi * 0.9 / 0.7+ a.fromValue = layer.presentation()?.transform ?? CATransform3DIdentity+ a.toValue = scaled+ a.autoreverses = true+ a.repeatCount = 1+ a.fillMode = .forwards+ a.duration = 0.1+ layer.add(a, forKey: "arc_commandBarBounce")+ }++ /// The site's colour as a 12 pt rounded rectangle under the bar, blurring to 150 and fading+ /// out over 1.2 s (ease-out). It spreads past the bar, so it gets a panel of its own below the+ /// bar's. Arc's sits under the bar's background in the same window and shows through it: the+ /// inside turns dark red at once ((47, 20, 19) over (26, 26, 26) for YouTube), holds for 0.17 s+ /// and is gone after a second (measured at 100 fps, 3 Nov). The bar's material can't see the+ /// panel below, so the inside is the colour under the bar's tint, following that curve.+ private func showSplash(_ color: NSColor) {+ guard let window else { return }+ let inner = NSView(frame: bounds)+ inner.autoresizingMask = [.width, .height]+ inner.wantsLayer = true+ inner.layer?.backgroundColor = color.cgColor+ inner.layer?.opacity = 0+ let fade = CAKeyframeAnimation(keyPath: "opacity")+ fade.keyTimes = Self.innerSplashCurve.map { NSNumber(value: $0.time) }+ fade.values = Self.innerSplashCurve.map { 0.42 * $0.level }+ fade.duration = 1+ inner.layer?.add(fade, forKey: "splash")+ addSubview(inner, positioned: .above, relativeTo: material)+ innerSplash = inner+ let margin: CGFloat = 420+ let panel = NSPanel(contentRect: window.frame.insetBy(dx: -margin, dy: -margin), styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered, defer: false)+ panel.backgroundColor = .clear+ panel.isOpaque = false+ panel.hasShadow = false+ panel.ignoresMouseEvents = true+ panel.collectionBehavior = window.collectionBehavior+ panel.contentView = NSHostingView(rootView: CommandBarSplash(color: Color(nsColor: color), size: window.frame.size))+ window.addChildWindow(panel, ordered: .below)+ splash = panel+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.3) { [weak self, weak panel] in+ guard let self, let panel, self.splash === panel else { return }+ panel.parent?.removeChildWindow(panel)+ panel.orderOut(nil)+ self.splash = nil+ self.innerSplash?.removeFromSuperview()+ self.innerSplash = nil+ }+ }++ /// How much of the site's colour shows inside Arc's bar after Tab, relative to the start (red+ /// over green, sampled off a 100 fps recording of Arc 1.171).+ private static let innerSplashCurve: [(time: Double, level: Double)] = [+ (0, 1), (0.17, 1), (0.21, 0.89), (0.27, 0.67), (0.33, 0.52), (0.39, 0.36), (0.45, 0.30), (0.51, 0.23),+ (0.57, 0.185), (0.69, 0.107), (0.75, 0.078), (0.87, 0.06), (0.93, 0.026), (1, 0),+ ]+/// UnevenRoundedRectangle: smaller top corners while the bar hangs from the toolbar.private static func path(_ r: CGRect, top: CGFloat, bottom: CGFloat) -> CGPath {let p = CGMutablePath()@@ -241,6 +334,29 @@ final class CommandBarView: NSView {}}+/// Arc's SplashView: `Color(nsColor:)` clipped to a 12 pt continuous rounded rectangle, blurred and+/// faded by one ease-out animation of 1.2 s that starts as it appears.+private struct CommandBarSplash: View {+ let color: Color+ let size: CGSize+ @State private var blurRadius: CGFloat = 0+ @State private var opacity: Double = 1++ var body: some View {+ color+ .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))+ .frame(width: size.width, height: size.height)+ .blur(radius: blurRadius, opaque: false)+ .opacity(opacity)+ .animation(.easeOut(duration: 1.2), value: blurRadius)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .onAppear {+ blurRadius = 150+ opacity = 0+ }+ }+}+/// One suggestion: icon, "Title — detail", and "Switch to Tab" + arrow for open tabs.final class CommandBarRowView: NSView {var onHover: () -> Void = {}diff --git a/Sources/Cra/UI/CommandBar/CommandTextField.swift b/Sources/Cra/UI/CommandBar/CommandTextField.swiftindex 466973a..10371b3 100644--- a/Sources/Cra/UI/CommandBar/CommandTextField.swift+++ b/Sources/Cra/UI/CommandBar/CommandTextField.swift@@ -144,6 +144,11 @@ final class CommandTextField {acceptSelectedCompletion(textView)controller.commitInBackground()return true+ // ⌥Return, which a field editor reads as a line break.+ case #selector(NSResponder.insertNewlineIgnoringFieldEditor(_:)):+ acceptSelectedCompletion(textView)+ controller.commitInSplit()+ return truecase #selector(NSResponder.cancelOperation(_:)):if controller.scope != nil { controller.cancelScope() } else { controller.close() }return truediff --git a/Sources/Cra/UI/Settings/AdvancedPane.swift b/Sources/Cra/UI/Settings/AdvancedPane.swiftindex 4e94b4f..a6d4ccb 100644--- a/Sources/Cra/UI/Settings/AdvancedPane.swift+++ b/Sources/Cra/UI/Settings/AdvancedPane.swift@@ -25,11 +25,7 @@ struct AdvancedPane: View {Text("Restart Cra to apply an engine change.").font(.system(size: 11)).foregroundStyle(.secondary)}SettingsFormRow(label: "Address Bar:") {- Picker("", selection: $store.settings.searchEngine) {- ForEach(SearchEngine.allCases) { Text($0.label).tag($0) }- }- .labelsHidden()- .fixedSize()+ SearchEnginePicker(store: store, openURL: actions.openURL)SettingsCheckbox(title: "Show search suggestions", isOn: $store.settings.searchSuggestions)}SettingsFormRow(label: "When quitting Cra:") {@@ -60,3 +56,39 @@ struct AdvancedPane: View {}}}++/// Chromium's default search engine, the one chrome://settings/searchEngines sets (Arc: Settings ▸+/// Profiles ▸ Default Search Engine, beside "Search Settings"): its built-in engines and whichever is+/// the default. The page adds, edits and removes the rest.+private struct SearchEnginePicker: View {+ let store: SidebarStore+ let openURL: (String) -> Void+ @State private var engines: [ChromiumSearchEngine] = []+ @State private var selected = ""++ var body: some View {+ HStack(spacing: 8) {+ Picker("", selection: Binding(get: { selected }, set: pick)) {+ ForEach(engines, id: \.keyword) { Text($0.name).tag($0.keyword) }+ }+ .labelsHidden()+ .fixedSize()+ Button("Manage Search Engines…") { openURL(SearchEngines.settingsPage) }+ }+ .onAppear(perform: reload)+ }++ private func reload() {+ let current = SearchEngines.shared.defaultEngine(profilePath: nil, legacy: store.settings.searchEngine)+ var list = SearchEngines.shared.keywords(profilePath: nil).filter(\.isBuiltIn)+ if !list.contains(where: { $0.keyword == current.keyword }) { list.insert(current, at: 0) }+ engines = list+ selected = current.keyword+ }++ private func pick(_ keyword: String) {+ guard let engine = engines.first(where: { $0.keyword == keyword }) else { return }+ SearchEngines.shared.setDefault(engine, store: store)+ selected = keyword+ }+}diff --git a/Sources/Cra/UI/Settings/ShortcutsPane.swift b/Sources/Cra/UI/Settings/ShortcutsPane.swiftindex 80bc39a..44554cc 100644--- a/Sources/Cra/UI/Settings/ShortcutsPane.swift+++ b/Sources/Cra/UI/Settings/ShortcutsPane.swift@@ -312,5 +312,6 @@ enum ShortcutDescriptions {"setDefaultBrowser": "Make Cra the default browser.","importData": "Bring tabs, spaces and extensions over from Arc or Dia.","rebuildArcProfiles": "Put spaces imported from Arc back on their Arc profiles, with their sign-ins and extensions.",+ "clearBrowsingData": "Delete history, cookies and cached files with Chrome’s dialog.",]}diff --git a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swiftindex f10452c..113591d 100644--- a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift+++ b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift@@ -392,29 +392,52 @@ final class SidebarFaviconView: NSImageView {}}-/// Arc's folder glyph: the outline over a filled folder while closed, GitHub's mark on a live folder.+/// Arc's folder glyph (FolderIconView, read from Arc 1.171's binary): a back panel with the tab+/// and a front panel, both hinged at the bottom-left corner. Opening turns them toward you in+/// perspective, the front tipping forward and the back leaning away, each shaded darker as it+/// turns, with Core Animation's implicit 0.25 s transition. GitHub's mark on a live folder.final class FolderGlyphView: NSView {- private let fill = NSImageView()- private let outline = NSImageView()+ /// Arc fixes the glyph at 16 × 16 pt.+ static let side: CGFloat = 16+ private let icon = CALayer()+ private let back = CAShapeLayer()+ private let backShade = CAGradientLayer()+ private let backShadeMask = CAShapeLayer()+ private let front = CALayer()+ private let frontPanel = CAShapeLayer()+ private let frontShade = CAGradientLayer()+ private let frontShadeMask = CAShapeLayer()private let mark = NSImageView()/// Arc's peeked folder (FolderPeek): three 2 pt dots on a 4 pt pitch in the closed body.private let dots = CAShapeLayer()+ private var expanded = falseoverride init(frame: NSRect) {super.init(frame: frame)- for v in [fill, outline] {- v.imageScaling = .scaleNone- v.autoresizingMask = [.width, .height]- v.frame = bounds- addSubview(v)+ wantsLayer = true+ // Arc: black from clear to 0.36 across the back, to 0.15 across the front.+ backShade.colors = [NSColor.black.withAlphaComponent(0).cgColor, NSColor.black.withAlphaComponent(0.36).cgColor]+ backShade.startPoint = CGPoint(x: 0, y: 0)+ backShade.endPoint = CGPoint(x: 0.6, y: 1)+ backShade.mask = backShadeMask+ frontShade.colors = [NSColor.black.withAlphaComponent(0).cgColor, NSColor.black.withAlphaComponent(0.15).cgColor]+ frontShade.startPoint = CGPoint(x: 0.1, y: 0)+ frontShade.endPoint = CGPoint(x: 0.9, y: 1)+ frontShade.mask = frontShadeMask+ back.addSublayer(backShade)+ front.addSublayer(frontPanel)+ front.addSublayer(frontShade)+ for l in [back, front] as [CALayer] {+ // Hinged on the bottom-left corner.+ l.anchorPoint = CGPoint(x: 0, y: 1)+ icon.addSublayer(l)}- fill.image = SidebarSymbols.image("folder.fill", size: 15)- outline.image = SidebarSymbols.image("folder", size: 15)+ layer?.addSublayer(icon)+ layer?.addSublayer(dots)mark.image = GitHubMark.imagemark.imageScaling = .scaleProportionallyUpOrDownaddSubview(mark)- wantsLayer = true- layer?.addSublayer(dots)+ apply(animated: false)}required init?(coder: NSCoder) { fatalError() }@@ -422,29 +445,97 @@ final class FolderGlyphView: NSView {override var isFlipped: Bool { true }override func hitTest(_ point: NSPoint) -> NSView? { nil }- func show(expanded: Bool, peeked: Bool = false, live: Bool, tint: NSColor, fillColor: NSColor) {- fill.isHidden = expanded- fill.contentTintColor = fillColor- outline.contentTintColor = tint+ func show(expanded: Bool, peeked: Bool = false, live: Bool, tint: NSColor, fillColor: NSColor, animated: Bool = false) {+ CATransaction.begin()+ CATransaction.setDisableActions(true)+ for l in [back, frontPanel] {+ l.fillColor = fillColor.cgColor+ l.strokeColor = tint.cgColor+ }mark.isHidden = !livemark.contentTintColor = tintdots.isHidden = !peeked || expanded || livedots.fillColor = tint.cgColor+ CATransaction.commit()+ guard expanded != self.expanded else { return }+ self.expanded = expanded+ apply(animated: animated)+ }++ /// Arc's per-state transforms: perspective m34 −0.00291, 3 pt to the right, 32° about the+ /// vertical axis, then the back 28° and the front −30° about the horizontal one.+ private func apply(animated: Bool) {+ CATransaction.begin()+ CATransaction.setDisableActions(!animated)+ let open = expanded+ var t = CATransform3DIdentity+ t.m34 = -0.0029129464+ t = CATransform3DTranslate(t, open ? 3 : 0, 0, 0)+ t = CATransform3DRotate(t, open ? 32 * .pi / 180 : 0, 0, 1, 0)+ back.transform = CATransform3DRotate(t, open ? 28 * .pi / 180 : 0, 1, 0, 0)+ front.transform = CATransform3DRotate(t, open ? -30 * .pi / 180 : 0, 1, 0, 0)+ frontShade.opacity = open ? 1 : 0+ backShade.opacity = open ? 1 : 0.2+ CATransaction.commit()+ }++ override func viewDidChangeBackingProperties() {+ super.viewDidChangeBackingProperties()needsLayout = true}override func layout() {super.layout()- mark.frame = NSRect(x: (bounds.width - 7) / 2, y: (bounds.height - 7) / 2 + 1.5, width: 7, height: 7)+ let scale = window?.backingScaleFactor ?? 2+ func px(_ v: CGFloat) -> CGFloat { (v * scale).rounded() / scale }+ let w = Self.side, h = Self.sideCATransaction.begin()CATransaction.setDisableActions(true)- dots.frame = bounds+ icon.frame = CGRect(x: px((bounds.width - w) / 2), y: px((bounds.height - h) / 2), width: w, height: h)+ let r = (w / 7).rounded()+ let tabH = px((h * 0.25).rounded())+ let t = (tabH / 1.5).rounded(.down)+ let line = px(1.25)+ // The back panel with its tab (the view is flipped: y runs down).let path = CGMutablePath()- // On whole points, so each dot is two pixels square at 1x.- let y = (bounds.height / 2 + 1.5).rounded(.down) - 1- for i in -1...1 { path.addEllipse(in: CGRect(x: (bounds.width / 2).rounded(.down) + CGFloat(i) * 4 - 1, y: y, width: 2, height: 2)) }- dots.path = path+ path.move(to: CGPoint(x: r, y: 0))+ path.addLine(to: CGPoint(x: px(0.41 * w), y: 0))+ path.addLine(to: CGPoint(x: px(0.58 * w), y: t))+ path.addLine(to: CGPoint(x: w - r, y: t))+ path.addArc(center: CGPoint(x: w - r, y: t + r), radius: r, startAngle: -.pi / 2, endAngle: 0, clockwise: false)+ path.addLine(to: CGPoint(x: w, y: h - r))+ path.addArc(center: CGPoint(x: w - r, y: h - r), radius: r, startAngle: 0, endAngle: .pi / 2, clockwise: false)+ path.addLine(to: CGPoint(x: r, y: h))+ path.addArc(center: CGPoint(x: r, y: h - r), radius: r, startAngle: .pi / 2, endAngle: .pi, clockwise: false)+ path.addLine(to: CGPoint(x: 0, y: r))+ path.addArc(center: CGPoint(x: r, y: r), radius: r, startAngle: .pi, endAngle: 1.5 * .pi, clockwise: false)+ path.closeSubpath()+ let backFrame = CGRect(x: 0, y: 0, width: w, height: h)+ back.bounds = CGRect(origin: .zero, size: backFrame.size)+ back.position = CGPoint(x: backFrame.minX, y: backFrame.maxY)+ back.path = path+ back.lineWidth = line+ backShade.frame = back.bounds+ backShadeMask.frame = back.bounds+ backShadeMask.path = path+ let frontFrame = CGRect(x: 0, y: tabH, width: w, height: h - tabH)+ front.bounds = CGRect(origin: .zero, size: frontFrame.size)+ front.position = CGPoint(x: frontFrame.minX, y: frontFrame.maxY)+ let panel = CGPath(roundedRect: front.bounds, cornerWidth: r, cornerHeight: r, transform: nil)+ frontPanel.frame = front.bounds+ frontPanel.path = panel+ frontPanel.lineWidth = line+ frontShade.frame = front.bounds+ frontShadeMask.frame = front.bounds+ frontShadeMask.path = panel+ // In the front panel, on whole points so each dot is two pixels square at 1x.+ dots.frame = bounds+ let dotPath = CGMutablePath()+ let y = (icon.frame.minY + frontFrame.midY).rounded(.down) - 1+ for i in -1...1 { dotPath.addEllipse(in: CGRect(x: (bounds.width / 2).rounded(.down) + CGFloat(i) * 4 - 1, y: y, width: 2, height: 2)) }+ dots.path = dotPathCATransaction.commit()+ mark.frame = NSRect(x: icon.frame.minX + (w - 7) / 2, y: icon.frame.minY + frontFrame.midY - 3.5, width: 7, height: 7)}}@@ -1046,8 +1137,10 @@ final class FolderRowView: SidebarRowView, NSTextFieldDelegate {func apply(_ m: FolderRowModel) {guard m != model else { return }+ // The same folder opening or closing turns its glyph; a row taking another folder doesn't.+ let toggled = model.map { $0.id == m.id && $0.expanded != m.expanded } ?? falsemodel = m- glyph.show(expanded: m.expanded, peeked: m.peeked, live: m.live, tint: m.tint, fillColor: m.fill)+ glyph.show(expanded: m.expanded, peeked: m.peeked, live: m.live, tint: m.tint, fillColor: m.fill, animated: toggled && window != nil)titleLabel.stringValue = m.titletitleLabel.textColor = colors.textPrimarysetAccessibilityLabel(m.title)@@ -1477,15 +1570,24 @@ final class LiveStatusRowView: SidebarRowView {final class NewTabRowView: SidebarRowView {private let plus = NSImageView()private let label = NSTextField.sidebarLabel(size: 14)+ /// Zen's ⌘ + New Tab: the clipboard's text under "Paste and Search", in Arc's 11 pt second line.+ private let preview = NSTextField.sidebarLabel(size: 11)+ private var flagsMonitor: Any?+ /// What a click opens while ⌘ is held over the row with text on the clipboard; nil reads New Tab.+ private var paste: ClipboardPaste?+ private var pasteCheck: Task<Void, Never>?override init(key: SpaceListView.RowKey, list: SpaceListView, colors: SidebarColors) {super.init(key: key, list: list, colors: colors)// Arc's plus, fitted pixel by pixel at 1x and 2x.- plus.image = SidebarSymbols.image("plus", size: 14.5, weight: .medium)+ plus.image = Self.plusImageplus.imageScaling = .scaleNonelabel.stringValue = "New Tab"+ preview.lineBreakMode = .byTruncatingTail+ preview.isHidden = trueaddSubview(plus)addSubview(label)+ addSubview(preview)setAccessibilityElement(true)setAccessibilityRole(.button)setAccessibilityLabel("New Tab")@@ -1494,6 +1596,9 @@ final class NewTabRowView: SidebarRowView {required init?(coder: NSCoder) { fatalError() }+ private static let plusImage = SidebarSymbols.image("plus", size: 14.5, weight: .medium)+ private static let clipboardImage = SidebarSymbols.image("doc.on.clipboard", size: 13, weight: .medium)+/// While the ⌘T bar is open Arc draws this row as the open one: the selected tab's fill,/// shadow and text.private var active = false@@ -1509,6 +1614,7 @@ final class NewTabRowView: SidebarRowView {let c = isHovered || active ? colors.textPrimary : colors.textSecondaryplus.contentTintColor = clabel.textColor = c+ preview.textColor = colors.textTertiary}override func setColors(_ c: SidebarColors) {@@ -1526,6 +1632,48 @@ final class NewTabRowView: SidebarRowView {override func hoverChanged() {super.hoverChanged()refreshColors()+ if isHovered, flagsMonitor == nil {+ flagsMonitor = NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { [weak self] e in+ self?.checkClipboard(e.modifierFlags)+ return e+ }+ } else if !isHovered {+ stopWatchingKeys()+ }+ checkClipboard(NSEvent.modifierFlags)+ }++ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ if window == nil { stopWatchingKeys() }+ }++ private func stopWatchingKeys() {+ if let m = flagsMonitor { NSEvent.removeMonitor(m) }+ flagsMonitor = nil+ }++ /// ⌘ alone over the row: what the clipboard holds, asked without reading it where reading+ /// would raise macOS's paste alert.+ private func checkClipboard(_ flags: NSEvent.ModifierFlags) {+ pasteCheck?.cancel()+ guard isHovered, flags.intersection([.command, .shift, .option, .control]) == .command else { return show(nil) }+ pasteCheck = Task { [weak self] in+ let found = await ClipboardPaste.peek()+ guard !Task.isCancelled else { return }+ self?.show(found)+ }+ }++ private func show(_ p: ClipboardPaste?) {+ guard p != paste else { return }+ paste = p+ plus.image = p == nil ? Self.plusImage : Self.clipboardImage+ label.stringValue = p?.title ?? "New Tab"+ preview.stringValue = p?.text?.replacingOccurrences(of: "\n", with: " ") ?? ""+ preview.isHidden = preview.stringValue.isEmpty+ setAccessibilityLabel(label.stringValue)+ needsLayout = true}override func layout() {@@ -1534,10 +1682,54 @@ final class NewTabRowView: SidebarRowView {plus.frame = NSRect(x: 8, y: 0, width: CraMetrics.favicon, height: h)let th = label.intrinsicContentSize.heightlet x = 8 + CraMetrics.favicon + 9- label.frame = NSRect(x: x - SidebarText.inset, y: (h - th) / 2, width: max(0, bounds.width - 10 - x) + 2 * SidebarText.inset, height: th)+ let w = max(0, bounds.width - 10 - x) + 2 * SidebarText.inset+ guard !preview.isHidden else {+ label.frame = NSRect(x: x - SidebarText.inset, y: (h - th) / 2, width: w, height: th)+ return+ }+ let ph = preview.intrinsicContentSize.height+ let top = (h - th - ph) / 2+ label.frame = NSRect(x: x - SidebarText.inset, y: top, width: w, height: th)+ preview.frame = NSRect(x: x - SidebarText.inset, y: top + th, width: w, height: ph)}- override func click(_ event: NSEvent, at point: NSPoint) { list?.actions.openCommandBar(.newTab) }+ override func click(_ event: NSEvent, at point: NSPoint) {+ // Read on the click: the user asked for the paste, so macOS lets it through or asks once.+ if paste != nil, event.modifierFlags.contains(.command), let text = ClipboardPaste.read() {+ show(nil)+ list?.actions.openTyped(text)+ } else {+ list?.actions.openCommandBar(.newTab)+ }+ }+}++/// The clipboard's text as a new tab (Zen's ⌘ + New Tab; Chrome's "Paste and Go" / "Paste and Search").+struct ClipboardPaste: Equatable {+ let isAddress: Bool+ /// The text itself where it can be read without macOS's paste alert, else nil.+ let text: String?++ var title: String { isAddress ? "Paste and Go" : "Paste and Search" }++ /// What the clipboard holds. Since macOS 15.4 reading it unasked raises an alert unless the user+ /// allowed Cra always; asking what kind of text it is never does.+ @MainActor static func peek() async -> ClipboardPaste? {+ let board = NSPasteboard.general+ guard board.types?.contains(.string) == true else { return nil }+ if #available(macOS 15.4, *), board.accessBehavior != .alwaysAllow {+ guard let found = try? await board.detectedPatterns(for: [\.probableWebURL, \.probableWebSearch]), !found.isEmpty else { return nil }+ return ClipboardPaste(isAddress: found.contains(\.probableWebURL), text: nil)+ }+ return read().map { ClipboardPaste(isAddress: TypedURL.looksLikeURL($0), text: $0) }+ }++ /// The clipboard's text on one line, nil when it holds none.+ @MainActor static func read() -> String? {+ guard let s = NSPasteboard.general.string(forType: .string) else { return nil }+ let line = s.split(whereSeparator: \.isWhitespace).joined(separator: " ")+ return line.isEmpty || line.count > 2048 ? nil : line+ }}/// The line between pinned and Today; "Clear" shows on hover.diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swiftindex 2ae1c35..5f2e8c2 100644--- a/Sources/Cra/UI/SidebarUIState.swift+++ b/Sources/Cra/UI/SidebarUIState.swift@@ -219,6 +219,8 @@ final class SidebarActions {var showExtensionsMenu: () -> Void = {}/// The developer bar's address field: a typed URL or search, in the selected tab.var loadTyped: (String) -> Void = { _ in }+ /// A typed URL or search in a new tab (⌘ + New Tab pastes the clipboard's text).+ var openTyped: (String) -> Void = { _ in }}private struct SidebarActionsKey: EnvironmentKey {diff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swiftindex e936cda..4847cc2 100644--- a/Sources/Cra/UI/Windows/LittleWindowController.swift+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift@@ -416,7 +416,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco}guard let s else {if typed.isEmpty { return }- open(SuggestionEngine.looksLikeURL(typed) ? SuggestionEngine.urlFromInput(typed) : store.settings.searchEngine.searchURL(typed))+ open(SuggestionEngine.looksLikeURL(typed) ? SuggestionEngine.urlFromInput(typed) : commandBar.engine.searchURL(typed))return}switch s.kind {@@ -432,7 +432,7 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @precocase .navigate:open(typed == query ? (s.url ?? SuggestionEngine.urlFromInput(typed)) : SuggestionEngine.urlFromInput(typed))case .search:- open(s.url ?? store.settings.searchEngine.searchURL(typed))+ open(s.url ?? commandBar.engine.searchURL(typed))case .history, .topDomain:open(s.url ?? "")case .command(let id):diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swiftindex 8bf1d52..aaacca9 100644--- a/Sources/Cra/UI/Windows/MainWindowController.swift+++ b/Sources/Cra/UI/Windows/MainWindowController.swift@@ -239,7 +239,13 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMguard let self else { return }let t = typed.trimmingCharacters(in: .whitespacesAndNewlines)guard !t.isEmpty else { return }- self.loadInSelectedTab(SuggestionEngine.looksLikeURL(t) ? SuggestionEngine.urlFromInput(t) : self.store.settings.searchEngine.searchURL(t))+ self.loadInSelectedTab(SuggestionEngine.looksLikeURL(t) ? SuggestionEngine.urlFromInput(t) : self.commandBar.engine.searchURL(t))+ }+ sidebarActions.openTyped = { [weak self] typed in+ guard let self else { return }+ let t = typed.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !t.isEmpty else { return }+ self.store.createTab(url: SuggestionEngine.looksLikeURL(t) ? SuggestionEngine.urlFromInput(t) : self.commandBar.engine.searchURL(t), window: self.windowID)}sidebarActions.focusPane = { [weak self] id inguard let self, self.selectedTabID != id else { return }@@ -302,6 +308,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM}commandBar.onCommit = { [weak self] s, typed, mode in self?.handleCommit(s, typed: typed, mode: mode) }commandBar.onOpenInBackground = { [weak self] s, typed in self?.openInBackground(s, typed: typed) ?? false }+ commandBar.onOpenInSplit = { [weak self] s, typed in self?.openInSplit(s, typed: typed) ?? false }commandBar.onClose = { [weak self] in self?.hideCommandPanel() }commandBar.spaceName = { [weak self] id in self?.store.space(id)?.title ?? "" }}@@ -2245,7 +2252,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM}guard let s else {if typed.isEmpty { return }- open(SuggestionEngine.looksLikeURL(typed) ? SuggestionEngine.urlFromInput(typed) : store.settings.searchEngine.searchURL(typed))+ open(SuggestionEngine.looksLikeURL(typed) ? SuggestionEngine.urlFromInput(typed) : commandBar.engine.searchURL(typed))return}switch s.kind {@@ -2258,7 +2265,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMlet url = typed == commandBar.query ? (s.url ?? SuggestionEngine.urlFromInput(typed)) : SuggestionEngine.urlFromInput(typed)open(url)case .search:- open(s.url ?? store.settings.searchEngine.searchURL(typed))+ open(s.url ?? commandBar.engine.searchURL(typed))case .history, .topDomain:open(s.url ?? "")case .command(let id):@@ -2275,30 +2282,65 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM/// ⌘Return in the bar (Arc): the row's page in a new background tab, the current tab staying/// in front; an open tab's row opens its address again rather than switching (GitHub #85).private func openInBackground(_ s: Suggestion?, typed: String) -> Bool {+ guard let url = pageURL(s, typed: typed) else { return false }+ store.recordQuerySelection(query: commandBar.query, url: url)+ let tab = store.createTab(url: url, select: false, window: windowID)+ store.markUnread(tab.id, false) // Arc saves these read, unlike a link opened in the background+ // Creating the page takes key from the bar; it takes key back and stays open, as while+ // opening (windowDidResignKey).+ commandBarOpenedAt = Date()+ browsers.ensureRuntime(for: tab.id) // load it so the title and favicon fill in+ // With the sidebar out the new row shows there; hidden, Arc says so in a toast.+ if !sidebarVisible { showToast("New Tab Created") }+ return true+ }++ /// ⌥Return in the bar: the row opens as a split pane beside the current tab instead of in its+ /// place, an open tab of this space joining the split as it is. False takes it as Return: no+ /// tab to split, an empty one (the row fills it), a tab in another space, a row with no page.+ private func openInSplit(_ s: Suggestion?, typed: String) -> Bool {+ guard let current = selectedTabID, store.item(current)?.isEmptyTab == false else { return false }+ if case .switchToTab(let id)? = s?.kind {+ guard id != current, store.spaceID(ofItem: id) == store.spaceID(ofItem: current) else { return false }+ if store.paneTabIDs(for: current).contains(id) {+ store.selectTab(id, window: windowID)+ return true+ }+ }+ guard store.paneTabIDs(for: current).count < 4 else {+ showToast("Cannot Add New Pane")+ return true+ }+ if case .switchToTab(let id)? = s?.kind {+ store.recordQuerySelection(query: commandBar.query, url: s?.url ?? "")+ let split = store.splitContaining(current).map { sp in store.addToSplit(sp.id, tabID: id, at: nil); return store.item(sp.id) }+ ?? store.createSplit(with: [current, id], at: current)+ store.selectTab(split.flatMap { store.paneID(for: id, in: $0) } ?? id, window: windowID)+ return true+ }+ guard let url = pageURL(s, typed: typed) else { return false }+ store.recordQuerySelection(query: commandBar.query, url: url)+ guard store.addEmptyPane(nextTo: current, url: url) != nil else { return false }+ refresh()+ return true+ }++ /// The page a row opens anew (⌘Return, ⌥Return), nil for rows that open none.+ private func pageURL(_ s: Suggestion?, typed: String) -> String? {let url: String?switch s?.kind {case nil:- url = typed.isEmpty ? nil : SuggestionEngine.looksLikeURL(typed) ? SuggestionEngine.urlFromInput(typed) : store.settings.searchEngine.searchURL(typed)+ url = typed.isEmpty ? nil : SuggestionEngine.looksLikeURL(typed) ? SuggestionEngine.urlFromInput(typed) : commandBar.engine.searchURL(typed)case .navigate?:url = typed == commandBar.query ? (s?.url ?? SuggestionEngine.urlFromInput(typed)) : SuggestionEngine.urlFromInput(typed)case .search?:- url = s?.url ?? store.settings.searchEngine.searchURL(typed)+ url = s?.url ?? commandBar.engine.searchURL(typed)case .switchToTab?, .archived?, .history?, .topDomain?:url = s?.urldefault:url = nil}- guard let url, !url.isEmpty else { return false }- store.recordQuerySelection(query: commandBar.query, url: url)- let tab = store.createTab(url: url, select: false, window: windowID)- store.markUnread(tab.id, false) // Arc saves these read, unlike a link opened in the background- // Creating the page takes key from the bar; it takes key back and stays open, as while- // opening (windowDidResignKey).- commandBarOpenedAt = Date()- browsers.ensureRuntime(for: tab.id) // load it so the title and favicon fill in- // With the sidebar out the new row shows there; hidden, Arc says so in a toast.- if !sidebarVisible { showToast("New Tab Created") }- return true+ return url?.isEmpty == false ? url : nil}/// Arc's toast at the top right of the page (ShinyToast): Cra's confirmations.diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex 98c6a80..56e8e20 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -2625,6 +2625,29 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {if (!value || value->GetType() != VTYPE_DICTIONARY) return nil;return NSStringFromCef(CefWriteJSON(value, JSON_WRITER_DEFAULT));}++ (NSString*)preference:(NSString*)name forProfile:(NSString*)profilePath {+ if (!g_contextInitialized || g_quitting) return nil;+ if (profilePath.length && ![g_readyProfiles containsObject:profilePath]) return nil;+ CefRefPtr<CefRequestContext> context = profilePath.length ? ProfileContext(profilePath) : CefRequestContext::GetGlobalContext();+ CefRefPtr<CefValue> value = context ? context->GetPreference(CefStringFromNS(name)) : nullptr;+ if (!value) return nil;+ return NSStringFromCef(CefWriteJSON(value, JSON_WRITER_DEFAULT));+}++ (BOOL)setPreference:(NSString*)name json:(NSString*)json forProfile:(NSString*)profilePath {+ if (!g_contextInitialized || g_quitting) return NO;+ if (profilePath.length && ![g_readyProfiles containsObject:profilePath]) return NO;+ CefRefPtr<CefRequestContext> context = profilePath.length ? ProfileContext(profilePath) : CefRequestContext::GetGlobalContext();+ CefRefPtr<CefValue> value = CefParseJSON(CefStringFromNS(json), JSON_PARSER_RFC);+ if (!context || !value) return NO;+ CefString cefName = CefStringFromNS(name);+ if (!context->CanSetPreference(cefName)) return NO;+ CefString error;+ if (!context->SetPreference(cefName, value, error)) {+ NSLog(@"CraCEF: %@: %s", name, error.ToString().c_str());+ return NO;+ }+ return YES;+}+ (void)setExtensionSettingsChangeHandler:(void (^)(void))handler {g_extensionSettingsHandler = [handler copy];}diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.hindex 15203d3..522939d 100644--- a/Sources/CraCEF/include/CraCEF.h+++ b/Sources/CraCEF/include/CraCEF.h@@ -331,6 +331,13 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {/// Default), as JSON. Chromium writes it to Preferences ~10 s after a change. nil until/// that profile has loaded.+ (nullable NSString *)extensionSettingsForProfile:(nullable NSString *)profilePath;+/// A profile's pref as Chromium holds it now (nil profilePath is Default), as JSON: how Cra reads+/// `default_search_provider_data.template_url_data`, the engine chrome://settings/searchEngines+/// made the default. nil until that profile has loaded.++ (nullable NSString *)preference:(NSString *)name forProfile:(nullable NSString *)profilePath;+/// Sets a profile's pref to a JSON value, as chrome://settings would. NO when the profile hasn't+/// loaded, a policy holds the pref, or the value isn't one it takes.++ (BOOL)setPreference:(NSString *)name json:(NSString *)json forProfile:(nullable NSString *)profilePath;/// Called on the main queue after a loaded profile's `extensions.settings` changed: an/// extension installed, enabled, disabled or removed.+ (void)setExtensionSettingsChangeHandler:(nullable void (^)(void))handler;diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.mdindex ed39411..6d745a6 100644--- a/docs/arc-reverse-engineering.md+++ b/docs/arc-reverse-engineering.md@@ -87,6 +87,35 @@ Legend: [O] observed in shipped artifact or data file, [I] inference, [U] unknow`siteSearchSpaceTriggerEnabled` show Space was a trigger once and Tab is the only one now. Cra's "%" tab scope(#49, Zen's idea) reuses all of it: "%" offers "Search Tabs Tab", the pill takes the space's colour (Arc has nocolour for a scope that isn't a site), rows are the bar's own tab rows. Cra: TabSearchScope, CommandBarScope.+- [O] Entering and leaving a scope (3 Nov, Arc 1.171, disassembly of `CommandBar.CommandBarContainer` + a 120 fps+ recording of Little Arc, "youtube" Tab): the container's layer gets `arc_commandBarBounce`, a CASpringAnimation on+ `transform` toward scale 0.95 about the centre (damping ratio 0.9, response 0.7: stiffness ≈ 80.57, damping ≈ 16.16,+ mass 1), its duration cut to 0.1 s, autoreverses, fill forwards: the bar dips ~1% and is back within 0.2 s. With a+ site colour, an `NSHostingController<SplashView>` goes under the bar: `Color(nsColor:)` clipped to a 12 pt continuous+ rounded rectangle, `.blur(radius:)` 0 → 150 and `.opacity` 1 → 0 under `.animation(.easeOut(duration: 1.2))`; on+ screen a haze of the site's colour spreads past the bar over the page and fades. Leaving the scope bounces again and+ drops the splash. Measured side by side (100 fps, same crops, 3 Nov): the bar's edge moves in 0.96% (Arc) / 1.0%+ (Cra) peaking at 80/90 ms on Tab, 1.04/1.07% on Backspace; red 60–140 pt above the bar starts at ~150 ms and peaks at+ 10.3 at 450 ms in both, gone by 1 s, within 0.5 at every 50 ms. Arc's splash also shows through the bar: its inside+ goes from (26, 26, 26) to (47, 20, 19) at once, holds for 0.17 s, then fades by 1 s. Cra's material can't see the+ panel under it, so the inside is a layer of the colour under the bar's tint keyed to that curve (within 2 levels).+ Cra: CommandBarView.scopeChanged.+- [O] Search engines (3 Nov): Settings ▸ Profiles has "Default Search Engine" and "Search Settings" (Chromium's page).+ Arc's bar is Chromium's omnibox, so the profile's default (`default_search_provider_data.template_url_data`, kept in+ Secure Preferences with a MAC) and its keywords (Web Data `keywords`) are what it searches with. Chromium adds sites+ it sees as inactive keywords (`safe_for_autoreplace` 1, `is_active` 0); those never take Tab. Cra kept its own engine+ list until 3 Nov (reported on X: custom engines and edited built-in ones did nothing). Cra: ChromiumSearchEngine,+ SearchEngines (reads Web Data as `immutable=1`, Chromium holds it with an exclusive lock), SiteSearch.match.+- [O] Folder glyph (3 Nov, `FolderIcon.FolderIconView` disassembled, checked against AX-toggled folders captured at+ 1x): 16 × 16, r = round(W/7), line px(1.25), tab height px(round(H·0.25)), shoulder floor(tab/1.5); back path (r,0) →+ (0.41W,0) → (0.58W,t) → round corners; the front a rounded rect under the tab. Both hinge on the bottom-left+ (anchor (0,1)); per state m34 −0.0029129464, x +3 / Y 32° when expanded (+1.5 / 16° peeked open), then X +28° on the+ back, −30° on the front (half for peeked open). Shading gradients black 0 → 0.36 (back, 0,0 → 0.6,1, opacity 0.2+ closed / 1 open) and 0 → 0.15 (front, 0.1,0 → 0.9,1, 0 / 1). No animation of its own: the state change runs in a+ CATransaction with actions on, so Core Animation's implicit 0.25 s (recorded: 50% at ~95 ms, 90% at ~165 ms in Arc;+ ~105 / ~175 ms in Cra). Colours come from outside (`ColorSpec`): on one+ gold theme the back was #E9B300, the front #FCEDBC and every edge black at ~26%; how the back colour follows the+ theme was not worked out, so Cra keeps its measured outline over cream. Cra: FolderGlyphView.- [O] Sidebar glyphs (29 Oct, 1x and 2x captures, fitted pixel by pixel): the tab row's hover ✕ is two 2 ptround-capped strokes 4.25 pt out from a centre on a whole point, white 0.6 over the hover fill; at 1x it isperfectly symmetric (176/142/85), which no SF Symbol size reproduces (xmark 13.5 bold is closest at 2x but