Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Per-space favorites, find bar match count, stay signed in after import

Victora0572f5edb16
diff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swift
index 2da54bd..20a4a15 100644
--- a/Sources/Cra/App/main.swift
+++ b/Sources/Cra/App/main.swift
@@ -11,9 +11,10 @@ MainActor.assumeIsolated {
// Passwords and cookies staged by the import go into the profile while no
// Chromium has it open: before initializing, and only when no other Cra runs.
let me = ProcessInfo.processInfo.processIdentifier
- if CredentialImport.hasPending,
- !NSRunningApplication.runningApplications(withBundleIdentifier: Bundle.main.bundleIdentifier ?? "").contains(where: { $0.processIdentifier != me }) {
- CredentialImport.applyPending(profileDir: AppPaths.chromiumCache.appendingPathComponent("Default", isDirectory: true))
+ if !NSRunningApplication.runningApplications(withBundleIdentifier: Bundle.main.bundleIdentifier ?? "").contains(where: { $0.processIdentifier != me }) {
+ let profile = AppPaths.chromiumCache.appendingPathComponent("Default", isDirectory: true)
+ if CredentialImport.hasPending { CredentialImport.applyPending(profileDir: profile) }
+ CredentialImport.repairImportedCookies(profileDir: profile)
}
NativeMessagingHosts.link(into: AppPaths.chromiumCache)
diff --git a/Sources/Cra/Model/SidebarModel.swift b/Sources/Cra/Model/SidebarModel.swift
index 8099eaf..0b5a90f 100644
--- a/Sources/Cra/Model/SidebarModel.swift
+++ b/Sources/Cra/Model/SidebarModel.swift
@@ -1,23 +1,54 @@
import Foundation
// Cra's sidebar model. Shape follows what Arc persists in StorableSidebar.json
-// (see docs/arc-reverse-engineering.md): spaces own a pinned and a "today"
-// container, favorites live in one shared container, tabs/folders are items in
-// a tree keyed by id with explicit child ordering.
+// (see docs/arc-reverse-engineering.md): spaces own a favorites, a pinned and a
+// "today" container, tabs/folders are items in a tree keyed by id with explicit
+// child ordering. Unlike Arc, favorites are not shared between spaces.
typealias ItemID = UUID
enum ContainerKind: Codable, Equatable, Hashable {
- case favorites
+ case favorites(spaceID: UUID)
case pinned(spaceID: UUID)
case today(spaceID: UUID)
- var spaceID: UUID? {
+ var spaceID: UUID {
switch self {
- case .favorites: return nil
- case .pinned(let id), .today(let id): return id
+ case .favorites(let id), .pinned(let id), .today(let id): return id
}
}
+
+ /// Stands in for the space of the favorites container every space shared
+ /// before favorites became per space; SidebarStore splits it up on load.
+ static let sharedFavoritesSpaceID = UUID(uuid: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
+
+ private enum CodingKeys: String, CodingKey { case favorites, pinned, today }
+ private enum SpaceKeys: String, CodingKey { case spaceID }
+
+ init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ guard let key = c.allKeys.first else {
+ throw DecodingError.dataCorrupted(.init(codingPath: c.codingPath, debugDescription: "No container kind"))
+ }
+ let s = try c.nestedContainer(keyedBy: SpaceKeys.self, forKey: key)
+ switch key {
+ case .favorites: self = .favorites(spaceID: try s.decodeIfPresent(UUID.self, forKey: .spaceID) ?? Self.sharedFavoritesSpaceID)
+ case .pinned: self = .pinned(spaceID: try s.decode(UUID.self, forKey: .spaceID))
+ case .today: self = .today(spaceID: try s.decode(UUID.self, forKey: .spaceID))
+ }
+ }
+
+ func encode(to encoder: Encoder) throws {
+ var c = encoder.container(keyedBy: CodingKeys.self)
+ let key: CodingKeys
+ switch self {
+ case .favorites: key = .favorites
+ case .pinned: key = .pinned
+ case .today: key = .today
+ }
+ var s = c.nestedContainer(keyedBy: SpaceKeys.self, forKey: key)
+ try s.encode(spaceID, forKey: .spaceID)
+ }
}
struct TabData: Codable, Equatable {
@@ -214,6 +245,7 @@ struct Space: Identifiable, Codable, Equatable {
var title: String
var emoji: String
var theme: SpaceTheme
+ var favoritesContainerID: UUID
var pinnedContainerID: UUID
var todayContainerID: UUID
var createdAt: Date
@@ -223,18 +255,19 @@ struct SidebarDocument: Codable {
var version: Int = 1
var spaceOrder: [UUID]
var spaces: [Space]
- var favoritesContainerID: UUID
+ /// The favorites container all spaces shared in older files. Only read, to
+ /// split it up between the spaces; new files leave it out.
+ var favoritesContainerID: UUID?
var items: [SidebarItem]
static func fresh() -> SidebarDocument {
- let fav = SidebarItem.container(.favorites)
let spaceID = UUID()
+ let fav = SidebarItem.container(.favorites(spaceID: spaceID))
let pinned = SidebarItem.container(.pinned(spaceID: spaceID))
let today = SidebarItem.container(.today(spaceID: spaceID))
- let space = Space(id: spaceID, title: "Personal", emoji: "🌱", theme: SpaceTheme.presets[0],
+ let space = Space(id: spaceID, title: "Personal", emoji: "🌱", theme: SpaceTheme.presets[0], favoritesContainerID: fav.id,
pinnedContainerID: pinned.id, todayContainerID: today.id, createdAt: Date())
- return SidebarDocument(spaceOrder: [spaceID], spaces: [space], favoritesContainerID: fav.id,
- items: [fav, pinned, today])
+ return SidebarDocument(spaceOrder: [spaceID], spaces: [space], items: [fav, pinned, today])
}
}
@@ -412,6 +445,21 @@ extension WindowPrefs {
}
}
+extension Space {
+ init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ id = try c.decode(UUID.self, forKey: .id)
+ title = try c.decode(String.self, forKey: .title)
+ emoji = try c.decode(String.self, forKey: .emoji)
+ theme = try c.decode(SpaceTheme.self, forKey: .theme)
+ // Spaces saved while favorites were shared get a container on load (SidebarStore.repair).
+ favoritesContainerID = try c.decodeIfPresent(UUID.self, forKey: .favoritesContainerID) ?? UUID()
+ pinnedContainerID = try c.decode(UUID.self, forKey: .pinnedContainerID)
+ todayContainerID = try c.decode(UUID.self, forKey: .todayContainerID)
+ createdAt = try c.decode(Date.self, forKey: .createdAt)
+ }
+}
+
extension TabData {
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index 45a0873..2cd8f6d 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -27,6 +27,8 @@ final class TabRuntime {
protocol BrowserManagerDelegate: AnyObject {
func browserManagerDidUpdate(_ tabID: UUID)
func browserManager(statusMessage: String)
+ /// Find in page results for the visible tab; -1 = no new value.
+ func browserManager(findMatches count: Int, activeMatch: Int)
func browserManager(download: CraDownloadInfo)
func browserManager(fullscreen: Bool, tabID: UUID)
func browserManagerDevToolsHost(for tabID: UUID) -> NSView?
@@ -292,6 +294,11 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
delegate?.browserManager(statusMessage: message)
}
+ func browser(_ browser: CraBrowser, didFindMatches count: Int, activeMatch: Int) {
+ guard let id = tabID(of: browser), id == visibleTabID else { return }
+ delegate?.browserManager(findMatches: count, activeMatch: activeMatch)
+ }
+
func browser(_ browser: CraBrowser, didChangeFullscreen fullscreen: Bool) {
guard let id = tabID(of: browser) else { return }
delegate?.browserManager(fullscreen: fullscreen, tabID: id)
diff --git a/Sources/Cra/Services/Import/CredentialImport.swift b/Sources/Cra/Services/Import/CredentialImport.swift
index 487783f..c84732f 100644
--- a/Sources/Cra/Services/Import/CredentialImport.swift
+++ b/Sources/Cra/Services/Import/CredentialImport.swift
@@ -326,7 +326,9 @@ enum CredentialImport {
"is_httponly": c.httpOnly, "last_access_utc": c.lastAccess, "has_expires": c.expires > 0,
"is_persistent": c.expires > 0, "priority": Int64(1), "samesite": Int64(c.sameSite),
"source_scheme": Int64(c.secure ? 2 : 1), "source_port": Int64(c.secure ? 443 : 80),
- "last_update_utc": c.lastAccess, "source_type": Int64(0), "has_cross_site_ancestor": false,
+ // Chromium stores every unpartitioned cookie with has_cross_site_ancestor = 1 and
+ // matches on it when it updates or deletes one; see repairImportedCookies.
+ "last_update_utc": c.lastAccess, "source_type": Int64(0), "has_cross_site_ancestor": true,
], orIgnore: true)
if !ok { return false }
}
@@ -334,6 +336,28 @@ enum CredentialImport {
}
}
+ /// Earlier imports wrote unpartitioned cookies with has_cross_site_ancestor = 0.
+ /// Chromium's UPDATE and DELETE never match those rows, so a fresh sign-in sat next
+ /// to the stale imported cookie, and at the next launch Chromium dropped the stale
+ /// duplicate with a DELETE that hit the fresh row instead: signed out after every
+ /// restart. Drops imported rows Chromium has since replaced and fixes the rest.
+ /// Called from main.swift before Chromium starts.
+ static func repairImportedCookies(profileDir: URL) {
+ guard let db = open(profileDir.appendingPathComponent("Cookies")) else { return }
+ defer { sqlite3_close(db) }
+ guard !SQLite.rows(db, "SELECT 1 FROM cookies WHERE top_frame_site_key = '' AND has_cross_site_ancestor = 0 LIMIT 1").isEmpty else { return }
+ let ok = transaction(db) {
+ sqlite3_exec(db, """
+ DELETE FROM cookies WHERE top_frame_site_key = '' AND has_cross_site_ancestor = 0 AND EXISTS (
+ SELECT 1 FROM cookies c WHERE c.top_frame_site_key = '' AND c.has_cross_site_ancestor = 1
+ AND c.host_key = cookies.host_key AND c.name = cookies.name AND c.path = cookies.path
+ AND c.source_scheme = cookies.source_scheme AND c.source_port = cookies.source_port);
+ UPDATE cookies SET has_cross_site_ancestor = 1 WHERE top_frame_site_key = '' AND has_cross_site_ancestor = 0;
+ """, nil, nil, nil) == SQLITE_OK
+ }
+ if !ok { NSLog("Cra: could not repair imported cookies") }
+ }
+
private static func insertLogins(_ logins: [Pending.Login], into url: URL) -> Bool {
guard let db = open(url) else { return false }
defer { sqlite3_close(db) }
diff --git a/Sources/Cra/Services/Import/Importers.swift b/Sources/Cra/Services/Import/Importers.swift
index 28dfba4..2bb7fc4 100644
--- a/Sources/Cra/Services/Import/Importers.swift
+++ b/Sources/Cra/Services/Import/Importers.swift
@@ -20,6 +20,8 @@ struct ImportedSpace {
var title: String
var emoji: String
var theme: SpaceTheme?
+ /// The space's own favorites (Arc: the top apps of the space's profile).
+ var favorites: [ImportedItem] = []
var pinned: [ImportedItem] = []
var today: [ImportedItem] = []
}
@@ -44,17 +46,18 @@ struct ImportedSettings {
struct ImportPlan {
var source: String
var spaces: [ImportedSpace] = []
+ /// Favorites that belong to no imported space; they go to the focused space.
var favorites: [ImportedItem] = []
var archive: [ImportedArchiveEntry] = []
var settings = ImportedSettings()
var tabCount: Int {
func count(_ items: [ImportedItem]) -> Int { items.reduce(0) { $0 + ($1.isFolder ? count($1.children) : 1) } }
- return spaces.reduce(count(favorites)) { $0 + count($1.pinned) + count($1.today) }
+ return spaces.reduce(count(favorites)) { $0 + count($1.favorites) + count($1.pinned) + count($1.today) }
}
var folderCount: Int {
func count(_ items: [ImportedItem]) -> Int { items.reduce(0) { $0 + ($1.isFolder ? 1 + count($1.children) : 0) } }
- return spaces.reduce(count(favorites)) { $0 + count($1.pinned) + count($1.today) }
+ return spaces.reduce(count(favorites)) { $0 + count($1.favorites) + count($1.pinned) + count($1.today) }
}
}
@@ -132,11 +135,15 @@ enum ArcImporter {
return nil
}
- // Favorites (topApps) container(s).
+ // Favorites (topApps): one container per profile, shared by that profile's spaces.
+ var favoritesByProfile: [(profile: NSDictionary, items: [ImportedItem])] = []
+ var allFavorites: [ImportedItem] = []
for (_, it) in items {
guard let d = it["data"] as? [String: Any], let c = d["itemContainer"] as? [String: Any],
- let type = c["containerType"] as? [String: Any], type["topApps"] != nil else { continue }
- for cid in it["childrenIds"] as? [String] ?? [] { if let x = convert(cid) { plan.favorites.append(x) } }
+ let type = c["containerType"] as? [String: Any], let top = type["topApps"] as? [String: Any] else { continue }
+ let favs = (it["childrenIds"] as? [String] ?? []).compactMap(convert)
+ allFavorites += favs
+ if let profile = top["_0"] as? NSDictionary { favoritesByProfile.append((profile, favs)) }
}
for (sid, space) in pairs(main["spaces"]) {
@@ -158,6 +165,8 @@ enum ArcImporter {
}
}
var sp = ImportedSpace(title: title, emoji: emoji, theme: theme(from: space))
+ let profile = space["profile"] as? NSDictionary
+ sp.favorites = favoritesByProfile.first { $0.profile.isEqual(profile) }?.items ?? allFavorites
if let p = pinnedID, let c = items[p] { sp.pinned = (c["childrenIds"] as? [String] ?? []).compactMap(convert) }
if let t = todayID, let c = items[t] { sp.today = (c["childrenIds"] as? [String] ?? []).compactMap(convert) }
plan.spaces.append(sp)
@@ -398,7 +407,7 @@ extension SidebarStore {
}
}
copyFavicons(plan.favorites)
- for sp in plan.spaces { copyFavicons(sp.pinned); copyFavicons(sp.today) }
+ for sp in plan.spaces { copyFavicons(sp.favorites); copyFavicons(sp.pinned); copyFavicons(sp.today) }
func insert(_ items: [ImportedItem], into parent: UUID, skip: Set<String>, pinned: Bool) {
var skip = skip
@@ -427,7 +436,8 @@ extension SidebarStore {
}
}
- insert(plan.favorites, into: favoritesContainerID, skip: existingURLs(under: favoritesContainerID), pinned: true)
+ let current = focusedSpace.favoritesContainerID
+ insert(plan.favorites, into: current, skip: existingURLs(under: current), pinned: true)
for sp in plan.spaces {
let space: Space
@@ -438,6 +448,7 @@ extension SidebarStore {
space = createSpace(title: sp.title, emoji: sp.emoji, theme: sp.theme, focus: false)
result.spaces += 1
}
+ insert(sp.favorites, into: space.favoritesContainerID, skip: existingURLs(under: space.favoritesContainerID), pinned: true)
insert(sp.pinned, into: space.pinnedContainerID, skip: existingURLs(under: space.pinnedContainerID), pinned: true)
insert(sp.today, into: space.todayContainerID, skip: existingURLs(under: space.todayContainerID), pinned: false)
}
diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swift
index 7f3d9ab..6606672 100644
--- a/Sources/Cra/Services/SidebarStore.swift
+++ b/Sources/Cra/Services/SidebarStore.swift
@@ -12,7 +12,6 @@ final class SidebarStore {
private(set) var spaces: [UUID: Space] = [:]
private(set) var spaceOrder: [UUID] = []
private(set) var items: [UUID: SidebarItem] = [:]
- private(set) var favoritesContainerID: UUID = UUID()
private(set) var archive: [ArchivedItem] = []
var prefs = WindowPrefs() { didSet { prefsStore.save(prefs) } }
var settings = AppSettings() { didSet { settingsStore.save(settings) } }
@@ -32,7 +31,6 @@ final class SidebarStore {
init() {
let doc = sidebarFile.load(or: SidebarDocument.fresh)
- favoritesContainerID = doc.favoritesContainerID
for s in doc.spaces { spaces[s.id] = s }
spaceOrder = doc.spaceOrder.filter { spaces[$0] != nil }
for s in doc.spaces where !spaceOrder.contains(s.id) { spaceOrder.append(s.id) }
@@ -46,16 +44,17 @@ final class SidebarStore {
if prefs.focusedSpaceID == nil || spaces[prefs.focusedSpaceID!] == nil {
prefs.focusedSpaceID = spaceOrder.first
}
+ splitSharedFavorites(doc.favoritesContainerID)
}
- /// Make sure every space has its containers, favorites exist, and no item
- /// points at a parent that is gone.
+ /// Make sure every space has its containers and no item points at a
+ /// parent that is gone.
func repair() {
- if items[favoritesContainerID] == nil {
- let fav = SidebarItem.container(.favorites, id: favoritesContainerID)
- items[fav.id] = fav
- }
for (id, var space) in spaces {
+ if items[space.favoritesContainerID] == nil {
+ let c = SidebarItem.container(.favorites(spaceID: id), id: space.favoritesContainerID)
+ items[c.id] = c
+ }
if items[space.pinnedContainerID] == nil {
let c = SidebarItem.container(.pinned(spaceID: id), id: space.pinnedContainerID)
items[c.id] = c
@@ -71,7 +70,7 @@ final class SidebarStore {
let doc = SidebarDocument.fresh()
for s in doc.spaces { spaces[s.id] = s }
spaceOrder = doc.spaceOrder
- for it in doc.items where it.container != .favorites { items[it.id] = it }
+ for it in doc.items { items[it.id] = it }
}
// Drop children references that do not resolve and orphans.
for (id, var it) in items {
@@ -90,16 +89,52 @@ final class SidebarStore {
}
}
+ /// Favorites used to be one set every space shared. Each space gets its own
+ /// copy of that set so nothing disappears anywhere; the focused space keeps
+ /// the original tabs, other spaces get copies.
+ private func splitSharedFavorites(_ sharedID: UUID?) {
+ guard let sharedID, let shared = items[sharedID] else { return }
+ for sid in spaceOrder {
+ guard let space = spaces[sid] else { continue }
+ var copies: [UUID: UUID] = [:]
+ for child in shared.children {
+ if sid == focusedSpaceID {
+ items[child]?.parentID = space.favoritesContainerID
+ items[space.favoritesContainerID]?.children.append(child)
+ } else {
+ copySubtree(child, into: space.favoritesContainerID, copies: &copies)
+ }
+ }
+ // A favorite open in this space stays open: it is now this space's copy.
+ if let sel = prefs.selectedTabPerSpace[sid], let copy = copies[sel] { prefs.selectedTabPerSpace[sid] = copy }
+ for (old, new) in copies where prefs.expandedFolders.contains(old) { prefs.expandedFolders.insert(new) }
+ }
+ items[sharedID] = nil
+ touch()
+ }
+
+ private func copySubtree(_ id: UUID, into parent: UUID, copies: inout [UUID: UUID]) {
+ guard var it = items[id] else { return }
+ let kids = it.children
+ it.id = UUID()
+ it.parentID = parent
+ it.children = []
+ copies[id] = it.id
+ items[it.id] = it
+ items[parent]?.children.append(it.id)
+ for k in kids { copySubtree(k, into: it.id, copies: &copies) }
+ }
+
func save() {
let doc = SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: spaceOrder.compactMap { spaces[$0] },
- favoritesContainerID: favoritesContainerID, items: Array(items.values))
+ items: Array(items.values))
sidebarFile.save(doc)
archiveFile.save(archive)
}
func saveAll() {
let doc = SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: spaceOrder.compactMap { spaces[$0] },
- favoritesContainerID: favoritesContainerID, items: Array(items.values))
+ items: Array(items.values))
sidebarFile.saveNow(doc)
archiveFile.saveNow(archive)
prefsStore.saveNow(prefs)
@@ -167,7 +202,7 @@ final class SidebarStore {
/// ⌘1…⌘9 index into (Arc: "Go to Sidebar Item N").
func visibleTabs(in spaceID: UUID) -> [SidebarItem] {
guard let space = spaces[spaceID] else { return [] }
- return tabs(under: favoritesContainerID) + tabs(under: space.pinnedContainerID) + tabs(under: space.todayContainerID)
+ return tabs(under: space.favoritesContainerID) + tabs(under: space.pinnedContainerID) + tabs(under: space.todayContainerID)
}
/// Which container an item ultimately lives in.
@@ -183,13 +218,7 @@ final class SidebarStore {
return nil
}
- func spaceID(ofItem id: UUID) -> UUID? {
- switch rootContainer(of: id) {
- case .pinned(let s), .today(let s): return s
- case .favorites: return focusedSpaceID
- default: return nil
- }
- }
+ func spaceID(ofItem id: UUID) -> UUID? { rootContainer(of: id)?.spaceID }
func isPinned(_ id: UUID) -> Bool {
switch rootContainer(of: id) {
@@ -198,7 +227,10 @@ final class SidebarStore {
}
}
- func isFavorite(_ id: UUID) -> Bool { rootContainer(of: id) == .favorites }
+ func isFavorite(_ id: UUID) -> Bool {
+ if case .favorites? = rootContainer(of: id) { return true }
+ return false
+ }
func selectedTabID(in spaceID: UUID) -> UUID? {
guard let id = prefs.selectedTabPerSpace[spaceID], items[id]?.isTab == true else { return nil }
@@ -267,7 +299,7 @@ final class SidebarStore {
items[id] = it
revision &+= 1
sidebarFile.save(SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: orderedSpaces,
- favoritesContainerID: favoritesContainerID, items: Array(items.values)), delay: 2)
+ items: Array(items.values)), delay: 2)
}
func markUnread(_ id: UUID, _ unread: Bool = true) {
@@ -348,7 +380,7 @@ final class SidebarStore {
func touchAfterImport() { touch() }
var document: SidebarDocument {
- SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: orderedSpaces, favoritesContainerID: favoritesContainerID, items: Array(items.values))
+ SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: orderedSpaces, items: Array(items.values))
}
/// Most recently used tab other than the current one (⌃Tab).
@@ -391,7 +423,7 @@ final class SidebarStore {
}
let fromParent = it.parentID
let oldIndex = fromParent.flatMap { items[$0]?.children.firstIndex(of: id) }
- if it.isFolder, case .today = rootContainerKind(newParent) ?? .favorites {
+ if it.isFolder, case .today? = rootContainerKind(newParent) {
// Unpack: move the folder's tabs instead.
let kids = it.children
detach(id)
@@ -646,14 +678,20 @@ final class SidebarStore {
if isPinned(id) { unpinTab(id) } else { pinTab(id) }
}
- func addToFavorites(_ id: UUID) { moveItem(id, to: favoritesContainerID, index: nil) }
+ /// Favorites belong to one space: the tab's own unless another is given.
+ func addToFavorites(_ id: UUID, in spaceID: UUID? = nil) {
+ guard let space = spaces[spaceID ?? self.spaceID(ofItem: id) ?? focusedSpaceID] else { return }
+ moveItem(id, to: space.favoritesContainerID, index: nil)
+ }
func removeFromFavorites(_ id: UUID) {
- moveItem(id, to: focusedSpace.pinnedContainerID, index: nil)
+ guard let space = spaceID(ofItem: id).flatMap({ spaces[$0] }) else { return }
+ moveItem(id, to: space.pinnedContainerID, index: nil)
}
func moveTab(_ id: UUID, toSpace sid: UUID) {
guard let space = spaces[sid] else { return }
+ if isFavorite(id) { return moveItem(id, to: space.favoritesContainerID, index: nil) }
let pinned = isPinned(id)
moveItem(id, to: pinned ? space.pinnedContainerID : space.todayContainerID, index: pinned ? nil : 0)
}
@@ -815,13 +853,15 @@ final class SidebarStore {
@discardableResult
func createSpace(title: String, emoji: String, theme: SpaceTheme? = nil, focus: Bool = true) -> Space {
let id = UUID()
+ let favorites = SidebarItem.container(.favorites(spaceID: id))
let pinned = SidebarItem.container(.pinned(spaceID: id))
let today = SidebarItem.container(.today(spaceID: id))
+ items[favorites.id] = favorites
items[pinned.id] = pinned
items[today.id] = today
let t = theme ?? SpaceTheme.presets[spaceOrder.count % SpaceTheme.presets.count]
- let space = Space(id: id, title: title, emoji: emoji, theme: t, pinnedContainerID: pinned.id,
- todayContainerID: today.id, createdAt: Date())
+ let space = Space(id: id, title: title, emoji: emoji, theme: t, favoritesContainerID: favorites.id,
+ pinnedContainerID: pinned.id, todayContainerID: today.id, createdAt: Date())
spaces[id] = space
spaceOrder.append(id)
if focus { prefs.focusedSpaceID = id }
@@ -837,10 +877,11 @@ final class SidebarStore {
func deleteSpace(_ id: UUID) {
guard spaces.count > 1, let space = spaces[id] else { return }
- for t in tabs(under: space.pinnedContainerID) + tabs(under: space.todayContainerID) {
+ for t in tabs(under: space.favoritesContainerID) + tabs(under: space.pinnedContainerID) + tabs(under: space.todayContainerID) {
archiveTab(t.id, reason: .spaceDeleted)
}
- for c in children(of: space.pinnedContainerID) where c.isFolder { deleteFolder(c.id) }
+ for c in children(of: space.favoritesContainerID) + children(of: space.pinnedContainerID) where c.isFolder { deleteFolder(c.id) }
+ items[space.favoritesContainerID] = nil
items[space.pinnedContainerID] = nil
items[space.todayContainerID] = nil
spaces[id] = nil
diff --git a/Sources/Cra/UI/ContentToolbarView.swift b/Sources/Cra/UI/ContentToolbarView.swift
index e807f6a..4eb3aba 100644
--- a/Sources/Cra/UI/ContentToolbarView.swift
+++ b/Sources/Cra/UI/ContentToolbarView.swift
@@ -210,9 +210,8 @@ struct ContentToolbarView: View {
.onTapGesture { editURL() }
.background(onCard ? cardFill : (isEmptyPane ? Color.clear : (palette.isDark ? Color.white.opacity(0.025) : Color.black.opacity(0.03))))
.overlay(alignment: .bottom) {
- // Arc draws a 1 px hairline under the bar on the card too (45/45/45 on a 34 bar, 242 on white).
- if onCard { Rectangle().fill(cardIsLight ? Color.black.opacity(0.05) : Color.white.opacity(0.05)).frame(height: 1) }
- else if !isEmptyPane { Rectangle().fill(palette.isDark ? Color.white.opacity(0.07) : Color.black.opacity(0.07)).frame(height: 1) }
+ // No hairline under the bar on the card: the bar and the page read as one surface (Arc draws one).
+ if !onCard, !isEmptyPane { Rectangle().fill(palette.isDark ? Color.white.opacity(0.07) : Color.black.opacity(0.07)).frame(height: 1) }
}
.ignoresSafeArea()
}
diff --git a/Sources/Cra/UI/Onboarding/ImportFlow.swift b/Sources/Cra/UI/Onboarding/ImportFlow.swift
index 11abfad..706085f 100644
--- a/Sources/Cra/UI/Onboarding/ImportFlow.swift
+++ b/Sources/Cra/UI/Onboarding/ImportFlow.swift
@@ -408,8 +408,9 @@ final class ImportFlowModel {
cats.append(ImportCategory(id: "tabs", title: "Tabs & Folders", symbol: "pin.fill",
detail: count(selection.spaces.reduce(0) { $0 + $1.itemCount }, "tab")))
}
- if includeFavorites && !selection.favorites.isEmpty {
- cats.append(ImportCategory(id: "favorites", title: "Favorites", symbol: "star.fill", detail: count(selection.favorites.count, "favorite")))
+ let favoriteCount = selection.spaces.reduce(selection.favorites.count) { $0 + $1.favorites.count }
+ if favoriteCount > 0 {
+ cats.append(ImportCategory(id: "favorites", title: "Favorites", symbol: "star.fill", detail: count(favoriteCount, "favorite")))
}
if includeArchive && !plan.archive.isEmpty {
cats.append(ImportCategory(id: "archive", title: "Archive", symbol: "archivebox.fill", detail: count(plan.archive.count, "tab")))
@@ -493,7 +494,7 @@ final class ImportFlowModel {
// MARK: Pinned tabs (Dia's PinnedTabsView)
/// Shown unless the favorites grid already has a full row.
- var offersPinnedTabs: Bool { store.tabs(under: store.favoritesContainerID).count < 4 }
+ var offersPinnedTabs: Bool { store.tabs(under: store.focusedSpace.favoritesContainerID).count < 4 }
/// Dia's pre-pinnable apps (PinnedTabs/Icons/* in its Onboarding bundle).
static let presetPins: [PinCandidate] = [
@@ -518,7 +519,7 @@ final class ImportFlowModel {
pinsLoaded = true
let source = self.source?.kind == .safari ? nil : (self.source ?? sources.first { $0.kind != .safari })
let fromExport = exportTopSites
- let existing = Set(store.tabs(under: store.favoritesContainerID).compactMap { $0.tab.flatMap { FaviconCache.key(for: $0.url) } })
+ let existing = Set(store.tabs(under: store.focusedSpace.favoritesContainerID).compactMap { $0.tab.flatMap { FaviconCache.key(for: $0.url) } })
pinCandidates = Self.presetPins
Task { @MainActor in
let (sites, icons) = await Task.detached(priority: .userInitiated) { () -> ([TopSite], [String: NSImage]) in
diff --git a/Sources/Cra/UI/Onboarding/ImportFlowArt.swift b/Sources/Cra/UI/Onboarding/ImportFlowArt.swift
index ecf4fe1..eb936de 100644
--- a/Sources/Cra/UI/Onboarding/ImportFlowArt.swift
+++ b/Sources/Cra/UI/Onboarding/ImportFlowArt.swift
@@ -334,7 +334,7 @@ private struct SidebarPreview: View {
let p = theme.palette
if let plan = model.plan, let i = model.previewSpace, i < plan.spaces.count {
let space = plan.spaces[i]
- let favorites = model.includeFavorites ? Array(plan.favorites.filter { !$0.isFolder }.prefix(8)) : []
+ let favorites = Array((space.favorites + (model.includeFavorites ? plan.favorites : [])).filter { !$0.isFolder }.prefix(8))
VStack(alignment: .leading, spacing: 10) {
if !favorites.isEmpty {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 7), count: 4), spacing: 7) {
diff --git a/Sources/Cra/UI/Onboarding/ImportFlowViews.swift b/Sources/Cra/UI/Onboarding/ImportFlowViews.swift
index 39dcc37..a1db20f 100644
--- a/Sources/Cra/UI/Onboarding/ImportFlowViews.swift
+++ b/Sources/Cra/UI/Onboarding/ImportFlowViews.swift
@@ -246,7 +246,7 @@ private struct SpacesStep: View {
if !plan.favorites.isEmpty {
SelectableRow(c: c, checked: model.includeFavorites, toggle: { model.includeFavorites.toggle() }) {
RowSymbol(name: "star.fill", c: c)
- RowTitle(title: "Favorites", caption: "\(plan.favorites.count) above your spaces", c: c)
+ RowTitle(title: "Favorites", caption: "\(plan.favorites.count) in your current space", c: c)
}
}
if !plan.archive.isEmpty {
diff --git a/Sources/Cra/UI/Overlays.swift b/Sources/Cra/UI/Overlays.swift
index 5f618f3..b36dfdc 100644
--- a/Sources/Cra/UI/Overlays.swift
+++ b/Sources/Cra/UI/Overlays.swift
@@ -19,6 +19,9 @@ final class OverlayState {
var findVisible = false
var findQuery = ""
var findFocusToken = 0
+ /// Find in page results ("2/7" in the bar); nil until the page answers.
+ var findMatchCount: Int?
+ var findActiveMatch = 0
var toasts: [DownloadToast] = []
}
@@ -42,7 +45,7 @@ struct StatusBubble: View {
struct FindBar: View {
let overlay: OverlayState
- let onFind: (String, Bool, Bool) -> Void // query, forward, isNext
+ let onFind: (String, Bool) -> Void // query, forward
let onClose: () -> Void
@FocusState private var focused: Bool
@@ -53,27 +56,48 @@ struct FindBar: View {
Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
TextField("Find in page", text: $overlay.findQuery)
.textFieldStyle(.plain)
- .frame(width: 180)
+ .frame(maxWidth: .infinity)
.focused($focused)
- .onSubmit { onFind(overlay.findQuery, !(NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false), true) }
- .onChange(of: overlay.findQuery) { _, q in onFind(q, true, false) }
+ .onSubmit { onFind(overlay.findQuery, !(NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false)) }
+ .onChange(of: overlay.findQuery) { _, q in onFind(q, true) }
.onExitCommand { onClose() }
- Button { onFind(overlay.findQuery, false, true) } label: { Image(systemName: "chevron.up") }.buttonStyle(.plain)
- Button { onFind(overlay.findQuery, true, true) } label: { Image(systemName: "chevron.down") }.buttonStyle(.plain)
+ if !overlay.findQuery.isEmpty, let count = overlay.findMatchCount {
+ Text("\(count == 0 ? 0 : overlay.findActiveMatch)/\(count)")
+ .font(.system(size: 11).monospacedDigit())
+ .foregroundStyle(.secondary)
+ .fixedSize()
+ }
+ Button { onFind(overlay.findQuery, false) } label: { Image(systemName: "chevron.up") }.buttonStyle(.plain)
+ Button { onFind(overlay.findQuery, true) } label: { Image(systemName: "chevron.down") }.buttonStyle(.plain)
Button { onClose() } label: { Image(systemName: "xmark") }.buttonStyle(.plain)
}
.padding(.horizontal, 10)
- .padding(.vertical, 7)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 10, style: .continuous))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Color.primary.opacity(0.1)))
- .padding(10)
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)
.onAppear { focused = true }
.onChange(of: overlay.findFocusToken) { _, _ in focused = true }
}
}
}
+/// The find bar's own window, just the bar's size, over the page windows. The
+/// page-sized overlay panel can't take key and would swallow every click on the page.
+final class FindBarPanel: NSPanel {
+ override var canBecomeKey: Bool { true }
+ override var canBecomeMain: Bool { false }
+
+ init() {
+ super.init(contentRect: NSRect(origin: .zero, size: CraMetrics.findBarSize),
+ styleMask: [.borderless], backing: .buffered, defer: false)
+ isOpaque = false
+ backgroundColor = .clear
+ hasShadow = false
+ isMovable = false
+ hidesOnDeactivate = false
+ }
+}
+
struct ToastStack: View {
let overlay: OverlayState
var body: some View {
diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swift
index f06c2f7..0165d97 100644
--- a/Sources/Cra/UI/ShellView.swift
+++ b/Sources/Cra/UI/ShellView.swift
@@ -80,6 +80,10 @@ final class ShellView: NSView {
var pageColors: [UUID: String] = [:] {
didSet { for c in paneCards where c.pageColor != pageColors[c.tabID] { c.pageColor = pageColors[c.tabID] } }
}
+ /// Each tab's toolbar colour ("#RRGGBB"), painted behind its toolbar (PaneCardView.toolbarColor).
+ var toolbarColors: [UUID: String] = [:] {
+ didSet { for c in paneCards where c.toolbarColor != toolbarColors[c.tabID] { c.toolbarColor = toolbarColors[c.tabID] } }
+ }
var sidebarWidth: CGFloat = CraMetrics.sidebarDefaultWidth { didSet { needsLayout = true } }
var sidebarVisible = true { didSet { needsLayout = true } }
@@ -258,6 +262,7 @@ final class ShellView: NSView {
let card = PaneCardView(tabID: id, toolbar: makeToolbar?(id == ShellView.noTabID ? nil : id) ?? AnyView(EmptyView()))
card.isDark = isDarkTheme
card.pageColor = pageColors[id]
+ card.toolbarColor = toolbarColors[id]
card.transparent = id == ShellView.noTabID
card.showToolbar = showToolbar && !contentFullscreen
contentContainer.addSubview(card, positioned: .below, relativeTo: placeholderHost)
@@ -559,15 +564,24 @@ final class ShellView: NSView {
statusHost.frame = NSRect(x: wb.minX, y: wb.minY, width: min(540, wb.width), height: 34)
toastHost.isHidden = toastCount == 0
toastHost.frame = NSRect(x: wb.maxX - 330, y: wb.minY, width: 330, height: CGFloat(toastCount) * 76 + 20)
- findHost.isHidden = !findVisible
- findHost.frame = NSRect(x: wb.maxX - 360, y: wb.maxY - 60, width: 360, height: 60)
+ if findHost.superview === overlayParent {
+ let size = CraMetrics.findBarSize, inset = CraMetrics.findBarInset
+ findHost.isHidden = !findVisible
+ findHost.frame = NSRect(x: wb.maxX - size.width - inset, y: wb.maxY - size.height - inset, width: size.width, height: size.height)
+ }
if !animatingPanes, paneCards.allSatisfy({ $0.frozenWebBounds == nil }) { onPaneFrames?(paneWebFrames(layout)) }
}
- /// Chrome-style hosting: overlays move into a panel above the page windows.
- func moveOverlays(to view: NSView) {
+ /// Chrome-style hosting: overlays move into a panel above the page windows, and
+ /// the find bar into its own panel (FindBarPanel), which the window controller places.
+ func moveOverlays(to view: NSView, findBar: NSPanel) {
overlayParent = view
- for h in [statusHost, toastHost, findHost] { h.removeFromSuperview(); view.addSubview(h) }
+ for h in [statusHost, toastHost] { h.removeFromSuperview(); view.addSubview(h) }
+ findHost.removeFromSuperview()
+ findHost.isHidden = false
+ findHost.autoresizingMask = [.width, .height]
+ findHost.frame = findBar.contentView!.bounds
+ findBar.contentView!.addSubview(findHost)
needsLayout = true
}
diff --git a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
index 96d38e8..80a707f 100644
--- a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
+++ b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
@@ -1,7 +1,9 @@
import SwiftUI
-/// Arc's "top apps": a 4-wide grid of favorite tiles shared by every space.
+/// Arc's "top apps": a 4-wide grid of favorite tiles. Arc shares them between
+/// spaces; in Cra every space has its own.
struct FavoritesGrid: View {
+ let space: Space
let palette: SpacePalette
@Environment(SidebarStore.self) private var store
@Environment(SidebarUIState.self) private var ui
@@ -11,11 +13,11 @@ struct FavoritesGrid: View {
private let columns = Array(repeating: GridItem(.flexible(), spacing: 8), count: 4)
var body: some View {
- let favorites = store.tabs(under: store.favoritesContainerID)
+ let favorites = store.tabs(under: space.favoritesContainerID)
VStack(spacing: 0) {
if !favorites.isEmpty {
LazyVGrid(columns: columns, spacing: 8) {
- ForEach(favorites) { item in FavoriteCell(item: item, palette: palette) }
+ ForEach(favorites) { item in FavoriteCell(item: item, space: space, palette: palette) }
}
}
RoundedRectangle(cornerRadius: 10, style: .continuous)
@@ -29,7 +31,7 @@ struct FavoritesGrid: View {
.animation(.easeOut(duration: 0.15), value: targeted)
.dropDestination(for: SidebarDragItem.self) { items, _ in
guard let d = items.first else { return false }
- store.addToFavorites(d.id)
+ store.addToFavorites(d.id, in: space.id)
return true
} isTargeted: { targeted = $0 }
}
@@ -52,6 +54,7 @@ struct FocusRing: View {
struct FavoriteCell: View {
let item: SidebarItem
+ let space: Space
let palette: SpacePalette
@Environment(SidebarStore.self) private var store
@Environment(SidebarUIState.self) private var ui
@@ -59,7 +62,7 @@ struct FavoriteCell: View {
@State private var hover = false
@State private var targeted = false
- private var selected: Bool { store.selectedTabID == item.id }
+ private var selected: Bool { store.selectedTabID(in: space.id) == item.id }
var body: some View {
let session = ui
@@ -90,8 +93,8 @@ struct FavoriteCell: View {
.draggable(SidebarDragItem.begin(item.id, session))
.dropDestination(for: SidebarDragItem.self) { items, location in
guard let d = items.first, d.id != item.id,
- let idx = store.item(store.favoritesContainerID)?.children.firstIndex(of: item.id) else { return false }
- store.moveItem(d.id, to: store.favoritesContainerID, index: idx + (location.x > 30 ? 1 : 0))
+ let idx = store.item(space.favoritesContainerID)?.children.firstIndex(of: item.id) else { return false }
+ store.moveItem(d.id, to: space.favoritesContainerID, index: idx + (location.x > 30 ? 1 : 0))
return true
} isTargeted: { targeted = $0 }
.contextMenu {
diff --git a/Sources/Cra/UI/Sidebar/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
index b9e5a9b..6cc3593 100644
--- a/Sources/Cra/UI/Sidebar/SidebarRootView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
@@ -13,10 +13,6 @@ struct SidebarRootView: View {
let palette = space.theme.palette
VStack(spacing: 0) {
SidebarTopBar(palette: palette)
- // Arc 1.170 keeps favorites and the space header fixed; only the
- // space's tab list scrolls (SpaceSectionView owns that scroll view).
- FavoritesGrid(palette: palette)
- .padding(.horizontal, 8)
// Dia's paging container: every space's list sits side by side and the
// strip follows the swipe 1:1, then a spring settles it on a page.
GeometryReader { g in
@@ -24,9 +20,16 @@ struct SidebarRootView: View {
let index = CGFloat(spaces.firstIndex { $0.id == space.id } ?? 0)
HStack(alignment: .top, spacing: 0) {
ForEach(spaces) { s in
- SpaceSectionView(space: s, palette: s.theme.palette)
- .foregroundStyle(s.theme.palette.textPrimary)
- .frame(width: g.size.width, height: g.size.height, alignment: .top)
+ // Arc 1.170 keeps favorites and the space header fixed; only the
+ // space's tab list scrolls (SpaceSectionView owns that scroll view).
+ // Favorites belong to the space, so they page with it.
+ VStack(spacing: 0) {
+ FavoritesGrid(space: s, palette: s.theme.palette)
+ .padding(.horizontal, 8)
+ SpaceSectionView(space: s, palette: s.theme.palette)
+ }
+ .foregroundStyle(s.theme.palette.textPrimary)
+ .frame(width: g.size.width, height: g.size.height, alignment: .top)
}
}
.offset(x: -(index + ui.spaceSwipe) * g.size.width)
diff --git a/Sources/Cra/UI/SplitView/PaneCardView.swift b/Sources/Cra/UI/SplitView/PaneCardView.swift
index 098f38c..a8fd24b 100644
--- a/Sources/Cra/UI/SplitView/PaneCardView.swift
+++ b/Sources/Cra/UI/SplitView/PaneCardView.swift
@@ -12,8 +12,8 @@ final class PaneCardView: NSView {
let webArea = NSView()
/// Hairline under the toolbar when the pane has no page (Arc draws it on the tinted card).
private let hairline = NSView()
- /// The white card behind the toolbar. A card with a page paints nothing else: under the
- /// page window's anti-aliased corners any fill of the card's shape shows as a light rim.
+ /// The card behind the toolbar, in the toolbar's colour. A card with a page paints nothing else:
+ /// under the page window's anti-aliased corners any fill of the card's shape shows as a light rim.
private let toolbarBackground = NSView()
var showToolbar = true { didSet { needsLayout = true } }
var toolbarHeight: CGFloat = CraMetrics.toolbarHeight { didSet { needsLayout = true } }
@@ -25,6 +25,9 @@ final class PaneCardView: NSView {
/// the card by a frame or more while the window is resized quickly; in that gap the
/// page area must look like the page, not like a white card.
var pageColor: String? { didSet { refreshBackground() } }
+ /// The toolbar's colour (the page's theme-color, white until it reports one). A white backing
+ /// under a dark bar shows through the bar's anti-aliased left edge as a 1px light line.
+ var toolbarColor: String? { didSet { refreshBackground() } }
/// The no-tab stand-in: toolbar on the gradient, no card at all.
var transparent = false { didSet { refreshBackground() } }
/// While a pane is being dragged open/closed its page keeps its last size.
@@ -58,7 +61,8 @@ final class PaneCardView: NSView {
// Measured on Arc 1.170 (Victor theme, 2x): the empty pane is the
// gradient plus about +9/+11/+12 per channel, i.e. a white veil at ~0.2.
layer?.backgroundColor = transparent || hasPage ? NSColor.clear.cgColor : NSColor(white: 1, alpha: isDark ? 0.08 : 0.2).cgColor
- toolbarBackground.layer?.backgroundColor = (hasPage && !transparent ? NSColor.white : NSColor.clear).cgColor
+ let bar = toolbarColor.map { NSColor(Color(hex: $0)) } ?? .white
+ toolbarBackground.layer?.backgroundColor = (hasPage && !transparent ? bar : NSColor.clear).cgColor
let page = pageColor.map { NSColor(Color(hex: $0)) } ?? .white
webArea.layer?.backgroundColor = (hasPage && !transparent ? page : NSColor.clear).cgColor
hairline.isHidden = hasPage || transparent || !showToolbar
diff --git a/Sources/Cra/UI/Theme.swift b/Sources/Cra/UI/Theme.swift
index ecc5983..7d86856 100644
--- a/Sources/Cra/UI/Theme.swift
+++ b/Sources/Cra/UI/Theme.swift
@@ -318,4 +318,7 @@ enum CraMetrics {
static let titleRowCenter: CGFloat = 24
static let titleAreaHeight: CGFloat = 44
static let commandBarWidth: CGFloat = 766
+ static let findBarSize = NSSize(width: 300, height: 38)
+ /// Gap between the find bar and the page's top and trailing edges.
+ static let findBarInset: CGFloat = 10
}
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 9026a56..aa99ca0 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -64,7 +64,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
placeholder: AnyView(EmptyContentView(space: store.focusedSpace)),
status: AnyView(StatusBubble(overlay: overlay)),
toasts: AnyView(ToastStack(overlay: overlay)),
- find: AnyView(FindBar(overlay: overlay, onFind: { [weak self] q, fwd, next in self?.find(q, forward: fwd, next: next) },
+ find: AnyView(FindBar(overlay: overlay, onFind: { [weak self] q, fwd in self?.find(q, forward: fwd) },
onClose: { [weak self] in self?.hideFindBar() })))
shell.sidebarWidth = CGFloat(store.prefs.sidebarWidth)
shell.sidebarVisible = store.prefs.sidebarVisible
@@ -318,6 +318,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
syncSidebarUI()
let colors = browsers.runtimes.compactMapValues { $0.backgroundColor.isEmpty ? nil : $0.backgroundColor }
if colors != shell.pageColors { shell.pageColors = colors }
+ // Same rule as ContentToolbarView.cardHex.
+ let bars = browsers.runtimes.compactMapValues { rt in HexColor.components(rt.themeColor) != nil ? rt.themeColor : nil }
+ if bars != shell.toolbarColors { shell.toolbarColors = bars }
if tabID == browsers.visibleTabID { window?.title = store.item(tabID)?.displayTitle ?? "Cra" }
}
@@ -327,12 +330,18 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
shell.layoutContentChildren()
}
+ func browserManager(findMatches count: Int, activeMatch: Int) {
+ guard overlay.findVisible else { return }
+ if count >= 0 { overlay.findMatchCount = count }
+ if activeMatch >= 0 { overlay.findActiveMatch = activeMatch }
+ }
+
func browserManager(download: CraDownloadInfo) {
let name = (download.fullPath as NSString).lastPathComponent.isEmpty ? download.suggestedName : (download.fullPath as NSString).lastPathComponent
let toast = DownloadToast(id: download.identifier, name: name, percent: download.percent, state: download.state.rawValue, path: download.fullPath)
if let i = overlay.toasts.firstIndex(where: { $0.id == toast.id }) { overlay.toasts[i] = toast } else { overlay.toasts.append(toast) }
shell.toastCount = overlay.toasts.count
- overlayPanel?.ignoresMouseEvents = overlay.toasts.isEmpty && !overlay.findVisible
+ overlayPanel?.ignoresMouseEvents = overlay.toasts.isEmpty
shell.layoutContentChildren()
if download.state != .inProgress {
let id = toast.id
@@ -369,6 +378,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// MARK: Chrome-style page windows
private var overlayPanel: NSPanel?
+ private var findPanel: FindBarPanel?
/// Page area per visible tab, window coordinates (one entry per pane).
private var lastPaneFrames: [UUID: NSRect] = [:]
/// While a divider is dragged the page windows follow every mouse move.
@@ -385,9 +395,30 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
panel.ignoresMouseEvents = true
panel.hidesOnDeactivate = false
panel.contentView = NSView(frame: panel.contentRect(forFrameRect: panel.frame))
- shell.moveOverlays(to: panel.contentView!)
+ let find = FindBarPanel()
+ shell.moveOverlays(to: panel.contentView!, findBar: find)
window.addChildWindow(panel, ordered: .above)
overlayPanel = panel
+ findPanel = find
+ if overlay.findVisible { window.addChildWindow(find, ordered: .above) }
+ }
+
+ /// Overlay panel above the page windows (and the floating sidebar), the find bar above it.
+ private func raiseOverlayPanels() {
+ guard let window else { return }
+ var panels: [NSPanel?] = [overlayPanel]
+ if overlay.findVisible { panels.append(findPanel) }
+ for case let panel? in panels {
+ window.removeChildWindow(panel)
+ window.addChildWindow(panel, ordered: .above)
+ panel.orderFront(nil)
+ }
+ }
+
+ /// The find bar's screen frame: the top trailing corner of the focused page.
+ private func findPanelFrame(page: NSRect) -> NSRect {
+ let size = CraMetrics.findBarSize, inset = CraMetrics.findBarInset
+ return NSRect(x: page.maxX - size.width - inset, y: page.maxY - size.height - inset, width: size.width, height: size.height)
}
/// Attaches the visible tabs' Chrome windows over their pane areas, hides the others.
@@ -430,11 +461,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
if let dev = browsers.visibleDevToolsWindow, dev.parent === window {
raisePageWindows(above: dev)
- } else if let panel = overlayPanel {
- // Keep the overlay panel above the page windows.
- window.removeChildWindow(panel)
- window.addChildWindow(panel, ordered: .above)
- panel.orderFront(nil)
+ } else {
+ raiseOverlayPanels()
}
}
@@ -470,6 +498,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
if shell.frontendPageRect != pr { shell.frontendPageRect = pr }
let focusOnScreen = window.convertToScreen(focusPage)
if let panel = overlayPanel, panel.frame != focusOnScreen { panel.setFrame(focusOnScreen, display: true) }
+ if let find = findPanel, find.frame != findPanelFrame(page: focusOnScreen) { find.setFrame(findPanelFrame(page: focusOnScreen), display: true) }
}
private func animatePageWindows(to frames: [UUID: NSRect], duration: TimeInterval) {
@@ -491,6 +520,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
dev.animator().setFrame(window.convertToScreen(body), display: true)
}
overlayPanel?.animator().setFrame(window.convertToScreen(focusPage), display: true)
+ findPanel?.animator().setFrame(findPanelFrame(page: window.convertToScreen(focusPage)), display: true)
}
}
@@ -688,11 +718,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
window.addChildWindow(w, ordered: .above)
w.orderFront(nil)
}
- if let panel = overlayPanel {
- window.removeChildWindow(panel)
- window.addChildWindow(panel, ordered: .above)
- panel.orderFront(nil)
- }
+ raiseOverlayPanels()
}
private func positionDevToolsWindow(_ rectInWindow: NSRect) {
@@ -826,9 +852,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
f.sidebarHidden = { [weak self] in self.map { !$0.store.prefs.sidebarVisible } ?? false }
f.didAttachPanel = { [weak self] in
// Keep toasts and the find bar above the floating sidebar.
- guard let self, let window = self.window, let panel = self.overlayPanel else { return }
- window.removeChildWindow(panel)
- window.addChildWindow(panel, ordered: .above)
+ self?.raiseOverlayPanels()
}
f.install()
floatingSidebar = f
@@ -1120,30 +1144,40 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
overlay.findVisible = true
overlay.findFocusToken += 1
shell.findVisible = true
- overlayPanel?.ignoresMouseEvents = false
- overlayPanel?.makeKeyAndOrderFront(nil)
shell.layoutContentChildren()
- window?.makeFirstResponder(shell.findHost)
+ if let window, let find = findPanel {
+ if find.parent !== window { window.addChildWindow(find, ordered: .above) }
+ find.makeKeyAndOrderFront(nil)
+ }
}
func hideFindBar() {
overlay.findVisible = false
+ overlay.findMatchCount = nil
shell.findVisible = false
- overlayPanel?.ignoresMouseEvents = overlay.toasts.isEmpty
currentBrowser?.stopFinding(true)
shell.layoutContentChildren()
+ if let find = findPanel, let window {
+ // Typing goes back to the page, unless focus already moved elsewhere.
+ if find.isKeyWindow { browsers.visibleRuntime?.hostWindow?.makeKey() }
+ window.removeChildWindow(find)
+ find.orderOut(nil)
+ }
currentBrowser?.setFocused(true)
}
func findNext(forward: Bool) {
if !overlay.findVisible { showFindBar(); return }
- find(overlay.findQuery, forward: forward, next: true)
+ find(overlay.findQuery, forward: forward)
}
- private func find(_ q: String, forward: Bool, next: Bool) {
+ /// Always a follow-up find: CEF restarts the search when the text changes, and
+ /// unlike a first request that selects a match (Chrome's find bar does this while
+ /// typing), so the bar shows "1/3" rather than "0/3".
+ private func find(_ q: String, forward: Bool) {
guard let b = currentBrowser else { return }
- if q.isEmpty { b.stopFinding(true); return }
- b.findText(q, forward: forward, matchCase: false, findNext: next)
+ if q.isEmpty { overlay.findMatchCount = nil; b.stopFinding(true); return }
+ b.findText(q, forward: forward, matchCase: false, findNext: true)
}
// MARK: Sheets
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index fbade3e..64ae193 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -19,6 +19,7 @@
#include "include/cef_context_menu_handler.h"
#include "include/cef_display_handler.h"
#include "include/cef_download_handler.h"
+#include "include/cef_find_handler.h"
#include "include/cef_focus_handler.h"
#include "include/cef_keyboard_handler.h"
#include "include/cef_life_span_handler.h"
@@ -598,7 +599,8 @@ class CraClient : public CefClient,
public CefKeyboardHandler,
public CefDownloadHandler,
public CefFocusHandler,
- public CefPermissionHandler {
+ public CefPermissionHandler,
+ public CefFindHandler {
public:
CraBrowser* owner() { return owner_; }
explicit CraClient(CraBrowser* owner) : owner_(owner) { CraClientRegistry().insert(static_cast<const void*>(static_cast<CefClient*>(this))); }
@@ -613,6 +615,7 @@ public:
CefRefPtr<CefDownloadHandler> GetDownloadHandler() override { return this; }
CefRefPtr<CefFocusHandler> GetFocusHandler() override { return this; }
CefRefPtr<CefPermissionHandler> GetPermissionHandler() override { return this; }
+ CefRefPtr<CefFindHandler> GetFindHandler() override { return this; }
// Life span -----------------------------------------------------------
@@ -807,6 +810,15 @@ public:
if (CraBrowser* o = owner_) [o.delegate browser:o didChangeStatusMessage:NSStringFromCef(value)];
}
+ // Find ------------------------------------------------------------------
+
+ void OnFindResult(CefRefPtr<CefBrowser> browser, int identifier, int count, const CefRect& selectionRect,
+ int activeMatchOrdinal, bool finalUpdate) override {
+ CraBrowser* o = owner_;
+ if (o && [o.delegate respondsToSelector:@selector(browser:didFindMatches:activeMatch:)])
+ [o.delegate browser:o didFindMatches:count activeMatch:activeMatchOrdinal];
+ }
+
void OnLoadingProgressChange(CefRefPtr<CefBrowser> browser, double progress) override {
if (CraBrowser* o = owner_) [o.delegate browser:o didChangeProgress:progress];
}
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index 2329176..901f39f 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -76,6 +76,9 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
/// canvas colour of its color scheme), as "#RRGGBB". The shell fills the area under
/// the page window with it, so a page lagging behind a resize shows no white edge.
- (void)browser:(CraBrowser *)browser didReportBackgroundColor:(NSString *)hex;
+/// Find in page progress: `count` matches, `activeMatch` is the highlighted one
+/// (1-based). Either is -1 while Chromium has no new value for it.
+- (void)browser:(CraBrowser *)browser didFindMatches:(NSInteger)count activeMatch:(NSInteger)activeMatch;
@end
@interface CraBrowser : NSObject
diff --git a/scripts/cef-patches/cors-origin-header.patch b/scripts/cef-patches/cors-origin-header.patch
new file mode 100644
index 0000000..9b25e65
--- /dev/null
+++ b/scripts/cef-patches/cors-origin-header.patch
@@ -0,0 +1,24 @@
+diff --git a/cef/libcef/browser/net_service/proxy_url_loader_factory.cc b/cef/libcef/browser/net_service/proxy_url_loader_factory.cc
+index b8207e0bc..14af54024 100644
+--- a/cef/libcef/browser/net_service/proxy_url_loader_factory.cc
++++ b/cef/libcef/browser/net_service/proxy_url_loader_factory.cc
+@@ -568,10 +568,15 @@ void InterceptedRequest::Restart() {
+ // Match logic in navigation_request.cc AddAdditionalRequestHeaders.
+ url::Origin origin_header_value =
+ request_.request_initiator.value_or(url::Origin());
+- origin_header_value = content::Referrer::SanitizeOriginForRequest(
+- request_.url, origin_header_value,
+- blink::ReferrerUtils::NetToMojoReferrerPolicy(
+- request_.referrer_policy));
++ // Cra: CORS requests send the initiator as is (CorsURLLoader does the same).
++ // Sanitizing it as a referrer turned chrome-extension:// origins into "null",
++ // and servers that check the extension's origin (1Password) then refuse.
++ if (!should_check_cors) {
++ origin_header_value = content::Referrer::SanitizeOriginForRequest(
++ request_.url, origin_header_value,
++ blink::ReferrerUtils::NetToMojoReferrerPolicy(
++ request_.referrer_policy));
++ }
+
+ request_.headers.SetHeaderIfMissing(net::HttpRequestHeaders::kOrigin,
+ origin_header_value.Serialize());